AutoRpa/rpa_cart/cart_search.py

93 lines
2.9 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 再搜条形码,保留原始商品字段给加车用。
#
# 导入路径由 selection_path 放进 rpa_selection,这里不再改 sys.path。
from __future__ import annotations
from typing import Any
import requests
import selection_path # noqa: F401 先把 rpa_selection 放进导入路径
from cart_match import CartOffer
from search_yaoex import map_yaoex_products, query_yaoex_products
from search_ybm import map_ybm_products, query_ybm_products
# 按条形码搜 1 号药城,结果转成 CartOffer 并带上原始商品字段。
def search_yaoex_offers(
auth,
query_key: str,
session: requests.Session | None = None,
cache: dict[str, list[CartOffer]] | None = None,
) -> list[CartOffer]:
store = cache if cache is not None else {}
if query_key in store:
return store[query_key]
own = session is None
client = session or requests.Session()
try:
products, user_id = query_yaoex_products(client, auth, query_key)
candidates = map_yaoex_products(products, user_id)
offers = [
_from_candidate(candidate, raw)
for candidate, raw in zip(candidates, products)
]
finally:
if own:
client.close()
store[query_key] = offers
return offers
# 按条形码搜药帮忙,结果转成 CartOffer 并带上原始商品字段。
def search_ybm_offers(
cookies: dict[str, str],
query_key: str,
session: requests.Session | None = None,
cache: dict[str, list[CartOffer]] | None = None,
) -> list[CartOffer]:
store = cache if cache is not None else {}
if query_key in store:
return store[query_key]
own = session is None
client = session or requests.Session()
try:
if own:
for name, value in cookies.items():
client.cookies.set(name, value)
rows = query_ybm_products(client, query_key)
candidates = map_ybm_products(rows)
offers = [
_from_candidate(candidate, _ybm_raw(row))
for candidate, row in zip(candidates, rows)
]
finally:
if own:
client.close()
store[query_key] = offers
return offers
# 从药帮忙搜索行抽出商品原始字段,补上 skuId。
def _ybm_raw(row: dict[str, Any]) -> dict[str, Any]:
product = row.get("productInfo")
raw = dict(product) if isinstance(product, dict) else dict(row)
if not raw.get("skuId"):
raw["skuId"] = row.get("skuId")
return raw
# 把选品候选加上原始字段收成加购用的 CartOffer。
def _from_candidate(candidate, raw: dict[str, Any]) -> CartOffer:
extra = dict(candidate.extra)
extra["raw"] = raw
return CartOffer(
sku_id=candidate.sku_id,
vendor_raw=candidate.vendor_raw,
vendor_norm=candidate.vendor_norm,
stock=candidate.stock,
price=candidate.price,
extra=extra,
)