unitbytes 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- unitbytes/__init__.py +43 -0
- unitbytes/_exceptions.py +94 -0
- unitbytes/_serialization.py +272 -0
- unitbytes/_transports.py +1529 -0
- unitbytes/ai.py +938 -0
- unitbytes/ali1688.py +538 -0
- unitbytes/alibaba.py +211 -0
- unitbytes/cli.py +454 -0
- unitbytes/client.py +124 -0
- unitbytes/gmaps.py +339 -0
- unitbytes/goofish.py +566 -0
- unitbytes/jobs.py +869 -0
- unitbytes/news.py +491 -0
- unitbytes/py.typed +1 -0
- unitbytes/reddit.py +342 -0
- unitbytes/rednote.py +286 -0
- unitbytes/request.py +7 -0
- unitbytes/shopping.py +644 -0
- unitbytes/travel.py +878 -0
- unitbytes/trends.py +1275 -0
- unitbytes-1.0.0.dist-info/METADATA +238 -0
- unitbytes-1.0.0.dist-info/RECORD +26 -0
- unitbytes-1.0.0.dist-info/WHEEL +5 -0
- unitbytes-1.0.0.dist-info/entry_points.txt +2 -0
- unitbytes-1.0.0.dist-info/licenses/LICENSE +21 -0
- unitbytes-1.0.0.dist-info/top_level.txt +1 -0
unitbytes/shopping.py
ADDED
|
@@ -0,0 +1,644 @@
|
|
|
1
|
+
"""Google Shopping domain namespace (`ub.shopping`) with Minimum Advertised Price (MAP) violation auditing."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import asdict, dataclass
|
|
6
|
+
from decimal import Decimal
|
|
7
|
+
import os
|
|
8
|
+
import re
|
|
9
|
+
from typing import TYPE_CHECKING, Any, Literal, Mapping, Sequence
|
|
10
|
+
from urllib.parse import urlparse
|
|
11
|
+
|
|
12
|
+
from ._serialization import filter_unseen_by_key
|
|
13
|
+
from ._transports import unwrap_items_payload
|
|
14
|
+
|
|
15
|
+
if TYPE_CHECKING:
|
|
16
|
+
from .client import UnitBytes
|
|
17
|
+
|
|
18
|
+
ACTOR_GOOGLE_SHOPPING = "unitbytes/google-shopping-scraper"
|
|
19
|
+
DEFAULT_SHOPPING_STATE_FILE = ".google_shopping_seen_state.json"
|
|
20
|
+
|
|
21
|
+
ShoppingSortOption = Literal["relevance", "price_asc", "price_desc", "rating_desc"]
|
|
22
|
+
ProductCondition = Literal["any", "new", "used"]
|
|
23
|
+
|
|
24
|
+
SHOPPING_SORT_OPTIONS: frozenset[str] = frozenset({"relevance", "price_asc", "price_desc", "rating_desc"})
|
|
25
|
+
SHOPPING_CONDITIONS: frozenset[str] = frozenset({"any", "new", "used"})
|
|
26
|
+
|
|
27
|
+
_VALID_GOOGLE_TLD_SUFFIXES: frozenset[str] = frozenset(
|
|
28
|
+
{
|
|
29
|
+
"com", "ad", "ae", "al", "am", "as", "at", "az", "ba", "be", "bf", "bg", "bi", "bj",
|
|
30
|
+
"bs", "bt", "by", "ca", "cat", "cd", "cf", "cg", "ch", "ci", "cl", "cm", "cn", "cv",
|
|
31
|
+
"cz", "de", "dj", "dk", "dm", "dz", "ee", "es", "fi", "fm", "fr", "ga", "ge", "gg",
|
|
32
|
+
"gl", "gm", "gr", "gy", "hn", "hr", "ht", "hu", "ie", "im", "iq", "is", "it", "je",
|
|
33
|
+
"jo", "kg", "ki", "kz", "la", "li", "lk", "lt", "lu", "lv", "md", "me", "mg", "mk",
|
|
34
|
+
"ml", "mn", "mu", "mv", "mw", "ne", "nl", "no", "nr", "nu", "pl", "pn", "ps", "pt",
|
|
35
|
+
"ro", "rs", "ru", "rw", "sc", "se", "sh", "si", "sk", "sm", "sn", "so", "sr", "st",
|
|
36
|
+
"td", "tg", "tl", "tm", "tn", "to", "tt", "vg", "vu",
|
|
37
|
+
"co.ao", "co.bw", "co.ck", "co.cr", "co.id", "co.il", "co.in", "co.jp", "co.ke",
|
|
38
|
+
"co.kr", "co.ls", "co.ma", "co.mz", "co.nz", "co.th", "co.tz", "co.ug", "co.uk",
|
|
39
|
+
"co.uz", "co.ve", "co.vi", "co.za", "co.zm", "co.zw",
|
|
40
|
+
"com.af", "com.ag", "com.ai", "com.ar", "com.au", "com.bd", "com.bh", "com.bn",
|
|
41
|
+
"com.bo", "com.br", "com.bz", "com.co", "com.cu", "com.cy", "com.do", "com.ec",
|
|
42
|
+
"com.eg", "com.et", "com.fj", "com.gh", "com.gi", "com.gt", "com.hk", "com.jm",
|
|
43
|
+
"com.kh", "com.kw", "com.lb", "com.ly", "com.mm", "com.mt", "com.mx", "com.my",
|
|
44
|
+
"com.na", "com.ng", "com.ni", "com.np", "com.om", "com.pa", "com.pe", "com.pg",
|
|
45
|
+
"com.ph", "com.pk", "com.pr", "com.py", "com.qa", "com.sa", "com.sb", "com.sg",
|
|
46
|
+
"com.sl", "com.sv", "com.tj", "com.tr", "com.tw", "com.ua", "com.uy", "com.vc",
|
|
47
|
+
"com.vn",
|
|
48
|
+
}
|
|
49
|
+
)
|
|
50
|
+
_DOMAIN_CLEAN_RE = re.compile(r"^[a-z0-9.-]+$")
|
|
51
|
+
_SPLIT_LIST_RE = re.compile(r"[\n;]+")
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _to_float(value: Any) -> float | None:
|
|
55
|
+
if value is None or isinstance(value, bool):
|
|
56
|
+
return None
|
|
57
|
+
if isinstance(value, (int, float)):
|
|
58
|
+
return float(value)
|
|
59
|
+
text = str(value).strip().replace(",", "")
|
|
60
|
+
if not text:
|
|
61
|
+
return None
|
|
62
|
+
match = re.search(r"-?\d+(?:\.\d+)?", text)
|
|
63
|
+
if not match:
|
|
64
|
+
return None
|
|
65
|
+
try:
|
|
66
|
+
return float(match.group(0))
|
|
67
|
+
except ValueError:
|
|
68
|
+
return None
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _classify_google_commerce_host(host: str) -> str | None:
|
|
72
|
+
for prefix, kind in (
|
|
73
|
+
("shopping.google.", "shopping"),
|
|
74
|
+
("news.google.", "news"),
|
|
75
|
+
("www.google.", "main"),
|
|
76
|
+
("google.", "main"),
|
|
77
|
+
):
|
|
78
|
+
if host.startswith(prefix) and host[len(prefix) :] in _VALID_GOOGLE_TLD_SUFFIXES:
|
|
79
|
+
return kind
|
|
80
|
+
return None
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def validate_google_commerce_url(raw_url: str, *, label: str = "startUrls") -> str:
|
|
84
|
+
"""Validate an HTTPS Google Shopping/News/Search URL."""
|
|
85
|
+
cleaned = str(raw_url or "").strip()
|
|
86
|
+
if not cleaned:
|
|
87
|
+
raise ValueError(f"{label} entry cannot be empty.")
|
|
88
|
+
if any(ch.isspace() or ord(ch) < 32 for ch in cleaned):
|
|
89
|
+
raise ValueError(f"{label} must not contain whitespace or control characters.")
|
|
90
|
+
parsed = urlparse(cleaned)
|
|
91
|
+
if parsed.scheme.lower() != "https":
|
|
92
|
+
raise ValueError(f"{label} must use https:// scheme: {cleaned!r}")
|
|
93
|
+
if parsed.username or parsed.password or "@" in (parsed.netloc or ""):
|
|
94
|
+
raise ValueError(f"{label} must not contain embedded credentials.")
|
|
95
|
+
if parsed.port not in (None, 443):
|
|
96
|
+
raise ValueError(f"{label} port must be 443 (or omitted).")
|
|
97
|
+
host = (parsed.hostname or "").strip().lower().rstrip(".")
|
|
98
|
+
host_kind = _classify_google_commerce_host(host)
|
|
99
|
+
if host_kind is None:
|
|
100
|
+
raise ValueError(
|
|
101
|
+
f"Unsupported host {host!r} in {label}. Provide an https:// Google Search, Shopping, or News URL."
|
|
102
|
+
)
|
|
103
|
+
if host_kind == "main":
|
|
104
|
+
path_low = (parsed.path or "").lower()
|
|
105
|
+
if not any(path_low == p or path_low.startswith(f"{p}/") for p in ("/search", "/shopping", "/news")):
|
|
106
|
+
raise ValueError(
|
|
107
|
+
f"Unsupported path {parsed.path!r} in {label}. Expected '/search', '/shopping', or '/news'."
|
|
108
|
+
)
|
|
109
|
+
return cleaned
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def normalize_domain(raw: str) -> str:
|
|
113
|
+
"""Normalize a publisher or merchant domain (e.g. `'https://www.BestBuy.com/shop'` -> `'bestbuy.com'`)."""
|
|
114
|
+
text = str(raw or "").strip().lower()
|
|
115
|
+
if not text:
|
|
116
|
+
raise ValueError("Domain cannot be empty.")
|
|
117
|
+
if text.startswith("site:"):
|
|
118
|
+
text = text[5:].strip()
|
|
119
|
+
if "://" in text:
|
|
120
|
+
parsed = urlparse(text)
|
|
121
|
+
if parsed.username or parsed.password:
|
|
122
|
+
raise ValueError("Domain URL must not include embedded credentials.")
|
|
123
|
+
text = (parsed.hostname or "").lower()
|
|
124
|
+
else:
|
|
125
|
+
text = text.split("/", 1)[0].split("?", 1)[0].split("#", 1)[0].strip()
|
|
126
|
+
if text.startswith("www.") and text.count(".") >= 2:
|
|
127
|
+
text = text[4:]
|
|
128
|
+
text = text.rstrip(".")
|
|
129
|
+
if not text or "." not in text or ".." in text or not _DOMAIN_CLEAN_RE.fullmatch(text):
|
|
130
|
+
raise ValueError(f"Invalid domain {raw!r}. Expected a domain such as 'bestbuy.com'.")
|
|
131
|
+
return text
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def _extract_domain_from_url_or_text(raw: str | None) -> str | None:
|
|
135
|
+
if not raw or not str(raw).strip():
|
|
136
|
+
return None
|
|
137
|
+
try:
|
|
138
|
+
return normalize_domain(str(raw).strip())
|
|
139
|
+
except ValueError:
|
|
140
|
+
return None
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def _normalize_seller_identifier(raw: str) -> str:
|
|
144
|
+
text = str(raw or "").strip()
|
|
145
|
+
if not text:
|
|
146
|
+
return ""
|
|
147
|
+
domain = _extract_domain_from_url_or_text(text)
|
|
148
|
+
if domain:
|
|
149
|
+
return domain
|
|
150
|
+
return re.sub(r"\s+", " ", text).lower()
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def is_seller_authorized(
|
|
154
|
+
merchant_name: str | None,
|
|
155
|
+
merchant_domain: str | None,
|
|
156
|
+
merchant_url: str | None,
|
|
157
|
+
authorized_sellers: Sequence[str] | None,
|
|
158
|
+
) -> bool | None:
|
|
159
|
+
"""Check whether a seller offer matches an authorized seller name or domain list."""
|
|
160
|
+
if authorized_sellers is None:
|
|
161
|
+
return None
|
|
162
|
+
normalized_allowlist = [
|
|
163
|
+
_normalize_seller_identifier(entry)
|
|
164
|
+
for entry in authorized_sellers
|
|
165
|
+
if str(entry or "").strip()
|
|
166
|
+
]
|
|
167
|
+
if not normalized_allowlist:
|
|
168
|
+
return False
|
|
169
|
+
|
|
170
|
+
cand_domain = (
|
|
171
|
+
_extract_domain_from_url_or_text(merchant_domain)
|
|
172
|
+
or _extract_domain_from_url_or_text(merchant_url)
|
|
173
|
+
or _extract_domain_from_url_or_text(merchant_name)
|
|
174
|
+
)
|
|
175
|
+
cand_name = re.sub(r"\s+", " ", str(merchant_name or "").strip()).lower()
|
|
176
|
+
cand_name_no_tld = re.sub(r"\.(?:com|net|org|co\.[a-z]{2}|[a-z]{2})$", "", cand_name)
|
|
177
|
+
|
|
178
|
+
for allowed in normalized_allowlist:
|
|
179
|
+
if "." in allowed:
|
|
180
|
+
if cand_domain and (cand_domain == allowed or cand_domain.endswith(f".{allowed}")):
|
|
181
|
+
return True
|
|
182
|
+
if cand_name == allowed:
|
|
183
|
+
return True
|
|
184
|
+
else:
|
|
185
|
+
if cand_name and (cand_name == allowed or cand_name_no_tld == allowed):
|
|
186
|
+
return True
|
|
187
|
+
if cand_domain and cand_domain.split(".", 1)[0] == allowed.replace(" ", ""):
|
|
188
|
+
return True
|
|
189
|
+
return False
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
@dataclass(frozen=True)
|
|
193
|
+
class MapViolation:
|
|
194
|
+
"""Single merchant offer violating a Minimum Advertised Price (MAP) threshold."""
|
|
195
|
+
|
|
196
|
+
product_id: str
|
|
197
|
+
catalog_id: str | None
|
|
198
|
+
title: str
|
|
199
|
+
brand: str | None
|
|
200
|
+
merchant_name: str
|
|
201
|
+
merchant_domain: str | None
|
|
202
|
+
merchant_url: str | None
|
|
203
|
+
observed_price: float
|
|
204
|
+
currency: str | None
|
|
205
|
+
map_price: float
|
|
206
|
+
undercut_amount: float
|
|
207
|
+
undercut_pct: float
|
|
208
|
+
is_authorized: bool | None
|
|
209
|
+
is_cheapest_offer: bool
|
|
210
|
+
delivery: str | None
|
|
211
|
+
google_shopping_url: str | None
|
|
212
|
+
scraped_at: str | None
|
|
213
|
+
|
|
214
|
+
def to_dict(self) -> dict[str, Any]:
|
|
215
|
+
return asdict(self)
|
|
216
|
+
|
|
217
|
+
def __getitem__(self, key: str) -> Any:
|
|
218
|
+
return self.to_dict()[key]
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
@dataclass(frozen=True)
|
|
222
|
+
class MapAuditReport:
|
|
223
|
+
"""Structured MAP compliance and multi-seller price undercut report across Google Shopping products."""
|
|
224
|
+
|
|
225
|
+
map_price: float
|
|
226
|
+
tolerance: float
|
|
227
|
+
total_products_scanned: int
|
|
228
|
+
total_offers_scanned: int
|
|
229
|
+
violating_products_count: int
|
|
230
|
+
total_violations_count: int
|
|
231
|
+
unauthorized_violations_count: int
|
|
232
|
+
lowest_observed_price: float | None
|
|
233
|
+
max_undercut_amount: float
|
|
234
|
+
max_undercut_pct: float
|
|
235
|
+
cheapest_offer: dict[str, Any] | None
|
|
236
|
+
violations: list[MapViolation]
|
|
237
|
+
unauthorized_offers: list[dict[str, Any]]
|
|
238
|
+
product_summaries: list[dict[str, Any]]
|
|
239
|
+
|
|
240
|
+
def to_dict(self) -> dict[str, Any]:
|
|
241
|
+
return {
|
|
242
|
+
"map_price": self.map_price,
|
|
243
|
+
"tolerance": self.tolerance,
|
|
244
|
+
"total_products_scanned": self.total_products_scanned,
|
|
245
|
+
"total_offers_scanned": self.total_offers_scanned,
|
|
246
|
+
"violating_products_count": self.violating_products_count,
|
|
247
|
+
"total_violations_count": self.total_violations_count,
|
|
248
|
+
"unauthorized_violations_count": self.unauthorized_violations_count,
|
|
249
|
+
"lowest_observed_price": self.lowest_observed_price,
|
|
250
|
+
"max_undercut_amount": self.max_undercut_amount,
|
|
251
|
+
"max_undercut_pct": self.max_undercut_pct,
|
|
252
|
+
"cheapest_offer": self.cheapest_offer,
|
|
253
|
+
"violations": [v.to_dict() for v in self.violations],
|
|
254
|
+
"unauthorized_offers": self.unauthorized_offers,
|
|
255
|
+
"product_summaries": self.product_summaries,
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
def __getitem__(self, key: str) -> Any:
|
|
259
|
+
return self.to_dict()[key]
|
|
260
|
+
|
|
261
|
+
def __len__(self) -> int:
|
|
262
|
+
return len(self.violations)
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
def _collect_normalized_product_offers(product: Mapping[str, Any]) -> list[dict[str, Any]]:
|
|
266
|
+
collected: list[dict[str, Any]] = []
|
|
267
|
+
seen_keys: set[tuple[str, str, float]] = set()
|
|
268
|
+
|
|
269
|
+
raw_offers = product.get("offers")
|
|
270
|
+
candidates: list[Mapping[str, Any]] = []
|
|
271
|
+
if isinstance(raw_offers, Sequence) and not isinstance(raw_offers, (str, bytes)):
|
|
272
|
+
for entry in raw_offers:
|
|
273
|
+
if isinstance(entry, Mapping):
|
|
274
|
+
candidates.append(entry)
|
|
275
|
+
|
|
276
|
+
headline_price = _to_float(product.get("price"))
|
|
277
|
+
if headline_price is not None:
|
|
278
|
+
candidates.append(
|
|
279
|
+
{
|
|
280
|
+
"merchantName": product.get("merchantName"),
|
|
281
|
+
"merchantDomain": product.get("merchantDomain"),
|
|
282
|
+
"merchantUrl": product.get("merchantUrl"),
|
|
283
|
+
"price": headline_price,
|
|
284
|
+
"currency": product.get("currency"),
|
|
285
|
+
"delivery": product.get("delivery"),
|
|
286
|
+
}
|
|
287
|
+
)
|
|
288
|
+
|
|
289
|
+
for cand in candidates:
|
|
290
|
+
price = _to_float(cand.get("price"))
|
|
291
|
+
if price is None or price <= 0:
|
|
292
|
+
continue
|
|
293
|
+
m_url = str(cand.get("merchantUrl") or "").strip() or None
|
|
294
|
+
m_dom = (
|
|
295
|
+
_extract_domain_from_url_or_text(cand.get("merchantDomain"))
|
|
296
|
+
or _extract_domain_from_url_or_text(m_url)
|
|
297
|
+
or _extract_domain_from_url_or_text(cand.get("merchantName"))
|
|
298
|
+
)
|
|
299
|
+
m_name = str(cand.get("merchantName") or m_dom or "Unknown Seller").strip()
|
|
300
|
+
currency = str(cand.get("currency") or product.get("currency") or "").strip() or None
|
|
301
|
+
delivery = str(cand.get("delivery") or "").strip() or None
|
|
302
|
+
|
|
303
|
+
dedup_seller = (m_dom or m_name).lower()
|
|
304
|
+
dedup_url = (m_url or "").lower()
|
|
305
|
+
rounded_price = round(price, 2)
|
|
306
|
+
key = (dedup_seller, dedup_url, rounded_price)
|
|
307
|
+
if any(
|
|
308
|
+
existing["seller_key"] == dedup_seller and existing["price"] == rounded_price
|
|
309
|
+
for existing in collected
|
|
310
|
+
):
|
|
311
|
+
continue
|
|
312
|
+
if key in seen_keys:
|
|
313
|
+
continue
|
|
314
|
+
seen_keys.add(key)
|
|
315
|
+
collected.append(
|
|
316
|
+
{
|
|
317
|
+
"seller_key": dedup_seller,
|
|
318
|
+
"merchantName": m_name,
|
|
319
|
+
"merchantDomain": m_dom,
|
|
320
|
+
"merchantUrl": m_url,
|
|
321
|
+
"price": rounded_price,
|
|
322
|
+
"currency": currency,
|
|
323
|
+
"delivery": delivery,
|
|
324
|
+
}
|
|
325
|
+
)
|
|
326
|
+
|
|
327
|
+
collected.sort(key=lambda r: r["price"])
|
|
328
|
+
return collected
|
|
329
|
+
|
|
330
|
+
|
|
331
|
+
def detect_map_violations(
|
|
332
|
+
products: Sequence[Mapping[str, Any]],
|
|
333
|
+
map_price: float,
|
|
334
|
+
authorized_sellers: Sequence[str] | None = None,
|
|
335
|
+
*,
|
|
336
|
+
tolerance: float = 0.0,
|
|
337
|
+
) -> MapAuditReport:
|
|
338
|
+
"""Scan Google Shopping `offers[]` across merchants to flag MAP violators and unauthorized undercuts."""
|
|
339
|
+
parsed_map = _to_float(map_price)
|
|
340
|
+
if parsed_map is None or parsed_map <= 0:
|
|
341
|
+
raise ValueError(f"map_price must be > 0, got {map_price!r}.")
|
|
342
|
+
if tolerance < 0:
|
|
343
|
+
raise ValueError(f"tolerance must be >= 0, got {tolerance!r}.")
|
|
344
|
+
|
|
345
|
+
target_map = round(parsed_map, 2)
|
|
346
|
+
effective_floor = round(target_map - float(tolerance), 4)
|
|
347
|
+
|
|
348
|
+
violations: list[MapViolation] = []
|
|
349
|
+
unauthorized_offers: list[dict[str, Any]] = []
|
|
350
|
+
product_summaries: list[dict[str, Any]] = []
|
|
351
|
+
|
|
352
|
+
total_products = 0
|
|
353
|
+
total_offers = 0
|
|
354
|
+
violating_products = 0
|
|
355
|
+
global_cheapest: dict[str, Any] | None = None
|
|
356
|
+
|
|
357
|
+
for raw_prod in products:
|
|
358
|
+
if not isinstance(raw_prod, Mapping):
|
|
359
|
+
continue
|
|
360
|
+
total_products += 1
|
|
361
|
+
prod_id = str(raw_prod.get("productId") or raw_prod.get("catalogId") or f"idx_{total_products}").strip()
|
|
362
|
+
cat_id = str(raw_prod.get("catalogId") or "").strip() or None
|
|
363
|
+
title = str(raw_prod.get("title") or "Untitled Product").strip()
|
|
364
|
+
brand = str(raw_prod.get("brand") or "").strip() or None
|
|
365
|
+
gshop_url = str(raw_prod.get("googleShoppingUrl") or "").strip() or None
|
|
366
|
+
scraped_at = str(raw_prod.get("scrapedAt") or "").strip() or None
|
|
367
|
+
|
|
368
|
+
offers = _collect_normalized_product_offers(raw_prod)
|
|
369
|
+
total_offers += len(offers)
|
|
370
|
+
prod_cheapest = offers[0] if offers else None
|
|
371
|
+
prod_violation_count = 0
|
|
372
|
+
|
|
373
|
+
if prod_cheapest is not None:
|
|
374
|
+
if global_cheapest is None or prod_cheapest["price"] < global_cheapest["price"]:
|
|
375
|
+
global_cheapest = {
|
|
376
|
+
"productId": prod_id,
|
|
377
|
+
"catalogId": cat_id,
|
|
378
|
+
"title": title,
|
|
379
|
+
"brand": brand,
|
|
380
|
+
"merchantName": prod_cheapest["merchantName"],
|
|
381
|
+
"merchantDomain": prod_cheapest["merchantDomain"],
|
|
382
|
+
"merchantUrl": prod_cheapest["merchantUrl"],
|
|
383
|
+
"price": prod_cheapest["price"],
|
|
384
|
+
"currency": prod_cheapest["currency"],
|
|
385
|
+
"undercutAmount": round(max(0.0, target_map - prod_cheapest["price"]), 2),
|
|
386
|
+
"undercutPct": round(
|
|
387
|
+
max(0.0, ((target_map - prod_cheapest["price"]) / target_map) * 100.0),
|
|
388
|
+
2,
|
|
389
|
+
),
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
for idx, offer in enumerate(offers):
|
|
393
|
+
obs_price = offer["price"]
|
|
394
|
+
authorized = is_seller_authorized(
|
|
395
|
+
offer["merchantName"],
|
|
396
|
+
offer["merchantDomain"],
|
|
397
|
+
offer["merchantUrl"],
|
|
398
|
+
authorized_sellers,
|
|
399
|
+
)
|
|
400
|
+
violates = obs_price < effective_floor
|
|
401
|
+
|
|
402
|
+
if authorized is False:
|
|
403
|
+
unauthorized_offers.append(
|
|
404
|
+
{
|
|
405
|
+
"productId": prod_id,
|
|
406
|
+
"title": title,
|
|
407
|
+
"merchantName": offer["merchantName"],
|
|
408
|
+
"merchantDomain": offer["merchantDomain"],
|
|
409
|
+
"merchantUrl": offer["merchantUrl"],
|
|
410
|
+
"price": obs_price,
|
|
411
|
+
"currency": offer["currency"],
|
|
412
|
+
"violatesMap": violates,
|
|
413
|
+
}
|
|
414
|
+
)
|
|
415
|
+
|
|
416
|
+
if violates:
|
|
417
|
+
prod_violation_count += 1
|
|
418
|
+
undercut_amt = round(target_map - obs_price, 2)
|
|
419
|
+
undercut_pct = round(((target_map - obs_price) / target_map) * 100.0, 2)
|
|
420
|
+
violations.append(
|
|
421
|
+
MapViolation(
|
|
422
|
+
product_id=prod_id,
|
|
423
|
+
catalog_id=cat_id,
|
|
424
|
+
title=title,
|
|
425
|
+
brand=brand,
|
|
426
|
+
merchant_name=offer["merchantName"],
|
|
427
|
+
merchant_domain=offer["merchantDomain"],
|
|
428
|
+
merchant_url=offer["merchantUrl"],
|
|
429
|
+
observed_price=obs_price,
|
|
430
|
+
currency=offer["currency"],
|
|
431
|
+
map_price=target_map,
|
|
432
|
+
undercut_amount=undercut_amt,
|
|
433
|
+
undercut_pct=undercut_pct,
|
|
434
|
+
is_authorized=authorized,
|
|
435
|
+
is_cheapest_offer=(idx == 0),
|
|
436
|
+
delivery=offer["delivery"],
|
|
437
|
+
google_shopping_url=gshop_url,
|
|
438
|
+
scraped_at=scraped_at,
|
|
439
|
+
)
|
|
440
|
+
)
|
|
441
|
+
|
|
442
|
+
if prod_violation_count > 0:
|
|
443
|
+
violating_products += 1
|
|
444
|
+
|
|
445
|
+
product_summaries.append(
|
|
446
|
+
{
|
|
447
|
+
"productId": prod_id,
|
|
448
|
+
"catalogId": cat_id,
|
|
449
|
+
"title": title,
|
|
450
|
+
"offersScanned": len(offers),
|
|
451
|
+
"violationsCount": prod_violation_count,
|
|
452
|
+
"cheapestPrice": prod_cheapest["price"] if prod_cheapest else None,
|
|
453
|
+
"cheapestMerchant": prod_cheapest["merchantName"] if prod_cheapest else None,
|
|
454
|
+
"cheapestMerchantUrl": prod_cheapest["merchantUrl"] if prod_cheapest else None,
|
|
455
|
+
}
|
|
456
|
+
)
|
|
457
|
+
|
|
458
|
+
violations.sort(key=lambda v: (v.observed_price, v.is_authorized is True))
|
|
459
|
+
unauth_violations = sum(1 for v in violations if v.is_authorized is False)
|
|
460
|
+
max_undercut_amt = max((v.undercut_amount for v in violations), default=0.0)
|
|
461
|
+
max_undercut_pct = max((v.undercut_pct for v in violations), default=0.0)
|
|
462
|
+
lowest_price = global_cheapest["price"] if global_cheapest is not None else None
|
|
463
|
+
|
|
464
|
+
return MapAuditReport(
|
|
465
|
+
map_price=target_map,
|
|
466
|
+
tolerance=round(float(tolerance), 4),
|
|
467
|
+
total_products_scanned=total_products,
|
|
468
|
+
total_offers_scanned=total_offers,
|
|
469
|
+
violating_products_count=violating_products,
|
|
470
|
+
total_violations_count=len(violations),
|
|
471
|
+
unauthorized_violations_count=unauth_violations,
|
|
472
|
+
lowest_observed_price=lowest_price,
|
|
473
|
+
max_undercut_amount=max_undercut_amt,
|
|
474
|
+
max_undercut_pct=max_undercut_pct,
|
|
475
|
+
cheapest_offer=global_cheapest,
|
|
476
|
+
violations=violations,
|
|
477
|
+
unauthorized_offers=unauthorized_offers,
|
|
478
|
+
product_summaries=product_summaries,
|
|
479
|
+
)
|
|
480
|
+
|
|
481
|
+
|
|
482
|
+
def _normalize_string_list(raw: Sequence[str] | str | None, *, split_commas: bool = False) -> list[str]:
|
|
483
|
+
if raw is None:
|
|
484
|
+
return []
|
|
485
|
+
splitter = re.compile(r"[\n,;]+") if split_commas else _SPLIT_LIST_RE
|
|
486
|
+
if isinstance(raw, str):
|
|
487
|
+
s = raw.strip()
|
|
488
|
+
if not s:
|
|
489
|
+
return []
|
|
490
|
+
if "://" in s[:12]:
|
|
491
|
+
return [ln.strip() for ln in s.splitlines() if ln.strip()]
|
|
492
|
+
return [part.strip() for part in splitter.split(s) if part.strip()]
|
|
493
|
+
out: list[str] = []
|
|
494
|
+
for elem in raw:
|
|
495
|
+
if elem is not None and str(elem).strip():
|
|
496
|
+
out.append(str(elem).strip())
|
|
497
|
+
return out
|
|
498
|
+
|
|
499
|
+
|
|
500
|
+
def _extract_shopping_record_key(record: Mapping[str, Any]) -> str | None:
|
|
501
|
+
for key in ("catalogId", "productId", "offerId", "googleShoppingUrl", "url"):
|
|
502
|
+
val = record.get(key)
|
|
503
|
+
if val is not None and str(val).strip():
|
|
504
|
+
return str(val).strip()
|
|
505
|
+
return None
|
|
506
|
+
|
|
507
|
+
|
|
508
|
+
class ShoppingNamespace:
|
|
509
|
+
"""Google Shopping search & MAP compliance auditing (`ub.shopping`)."""
|
|
510
|
+
|
|
511
|
+
def __init__(self, client: UnitBytes) -> None:
|
|
512
|
+
self._client = client
|
|
513
|
+
|
|
514
|
+
def search(
|
|
515
|
+
self,
|
|
516
|
+
queries: Sequence[str] | str | None = None,
|
|
517
|
+
*,
|
|
518
|
+
start_urls: Sequence[str | Mapping[str, Any]] | str | None = None,
|
|
519
|
+
country: str = "us",
|
|
520
|
+
language: str = "",
|
|
521
|
+
sort_by: ShoppingSortOption = "relevance",
|
|
522
|
+
min_price: float | None = None,
|
|
523
|
+
max_price: float | None = None,
|
|
524
|
+
on_sale_only: bool = False,
|
|
525
|
+
free_shipping_only: bool = False,
|
|
526
|
+
condition: ProductCondition = "any",
|
|
527
|
+
min_rating: float | None = None,
|
|
528
|
+
max_products: int = 50,
|
|
529
|
+
resolve_merchant_links: bool = True,
|
|
530
|
+
proxy_configuration: Mapping[str, Any] | None = None,
|
|
531
|
+
only_new: bool = False,
|
|
532
|
+
state_file: str | os.PathLike[str] | None = None,
|
|
533
|
+
max_total_charge_usd: float | Decimal | None = None,
|
|
534
|
+
) -> list[dict[str, Any]]:
|
|
535
|
+
"""Search Google Shopping product listings, multi-seller offers, and merchant checkout links."""
|
|
536
|
+
parsed_queries = _normalize_string_list(queries)
|
|
537
|
+
for q_item in parsed_queries:
|
|
538
|
+
if "://" in q_item[:12]:
|
|
539
|
+
validate_google_commerce_url(q_item, label="queries")
|
|
540
|
+
|
|
541
|
+
normalized_urls: list[dict[str, str]] = []
|
|
542
|
+
if isinstance(start_urls, str) and start_urls.strip():
|
|
543
|
+
normalized_urls.append({"url": validate_google_commerce_url(start_urls, label="startUrls")})
|
|
544
|
+
elif isinstance(start_urls, Sequence) and not isinstance(start_urls, (str, bytes)):
|
|
545
|
+
for entry in start_urls:
|
|
546
|
+
raw_u = entry.get("url") if isinstance(entry, Mapping) else entry
|
|
547
|
+
if raw_u is not None and str(raw_u).strip():
|
|
548
|
+
normalized_urls.append({"url": validate_google_commerce_url(str(raw_u), label="startUrls")})
|
|
549
|
+
|
|
550
|
+
if not parsed_queries and not normalized_urls:
|
|
551
|
+
raise ValueError("Provide at least one search query in 'queries' or a Google Shopping URL in 'start_urls'.")
|
|
552
|
+
|
|
553
|
+
norm_sort = str(sort_by or "relevance").strip().lower()
|
|
554
|
+
if norm_sort not in SHOPPING_SORT_OPTIONS:
|
|
555
|
+
raise ValueError(f"Invalid sort_by {sort_by!r}. Supported values: {sorted(SHOPPING_SORT_OPTIONS)}.")
|
|
556
|
+
|
|
557
|
+
norm_cond = str(condition or "any").strip().lower()
|
|
558
|
+
if norm_cond not in SHOPPING_CONDITIONS:
|
|
559
|
+
raise ValueError(f"Invalid condition {condition!r}. Supported values: {sorted(SHOPPING_CONDITIONS)}.")
|
|
560
|
+
|
|
561
|
+
if min_price is not None and float(min_price) < 0:
|
|
562
|
+
raise ValueError("min_price must be >= 0.")
|
|
563
|
+
if max_price is not None and float(max_price) < 0:
|
|
564
|
+
raise ValueError("max_price must be >= 0.")
|
|
565
|
+
if min_price is not None and max_price is not None and float(min_price) > float(max_price):
|
|
566
|
+
raise ValueError(f"min_price ({min_price}) cannot exceed max_price ({max_price}).")
|
|
567
|
+
if min_rating is not None and not (1.0 <= float(min_rating) <= 5.0):
|
|
568
|
+
raise ValueError("min_rating must be between 1.0 and 5.0.")
|
|
569
|
+
if int(max_products) < 1 or int(max_products) > 5000:
|
|
570
|
+
raise ValueError("max_products must be between 1 and 5000.")
|
|
571
|
+
|
|
572
|
+
norm_country = str(country or "us").strip().lower()
|
|
573
|
+
if not norm_country:
|
|
574
|
+
raise ValueError("country cannot be empty.")
|
|
575
|
+
|
|
576
|
+
run_input: dict[str, Any] = {
|
|
577
|
+
"country": norm_country,
|
|
578
|
+
"sortBy": norm_sort,
|
|
579
|
+
"onSaleOnly": bool(on_sale_only),
|
|
580
|
+
"freeShippingOnly": bool(free_shipping_only),
|
|
581
|
+
"condition": norm_cond,
|
|
582
|
+
"maxProducts": int(max_products),
|
|
583
|
+
"resolveMerchantLinks": bool(resolve_merchant_links),
|
|
584
|
+
}
|
|
585
|
+
if parsed_queries:
|
|
586
|
+
run_input["queries"] = parsed_queries
|
|
587
|
+
if normalized_urls:
|
|
588
|
+
run_input["startUrls"] = normalized_urls
|
|
589
|
+
if language and str(language).strip():
|
|
590
|
+
run_input["language"] = str(language).strip()
|
|
591
|
+
if min_price is not None:
|
|
592
|
+
run_input["minPrice"] = round(float(min_price), 2)
|
|
593
|
+
if max_price is not None:
|
|
594
|
+
run_input["maxPrice"] = round(float(max_price), 2)
|
|
595
|
+
if min_rating is not None:
|
|
596
|
+
run_input["minRating"] = round(float(min_rating), 1)
|
|
597
|
+
if proxy_configuration is not None:
|
|
598
|
+
run_input["proxyConfiguration"] = dict(proxy_configuration)
|
|
599
|
+
|
|
600
|
+
raw = self._client._transport.execute_operation(
|
|
601
|
+
service="shopping",
|
|
602
|
+
operation="search",
|
|
603
|
+
actor_slug=ACTOR_GOOGLE_SHOPPING,
|
|
604
|
+
actor_input=run_input,
|
|
605
|
+
http_method="POST",
|
|
606
|
+
json_body=run_input,
|
|
607
|
+
max_total_charge_usd=max_total_charge_usd,
|
|
608
|
+
)
|
|
609
|
+
products = [p for p in unwrap_items_payload(raw) if not p.get("error")][: int(max_products)]
|
|
610
|
+
if only_new:
|
|
611
|
+
products = filter_unseen_by_key(
|
|
612
|
+
products,
|
|
613
|
+
key_fn=_extract_shopping_record_key,
|
|
614
|
+
state_file=state_file or DEFAULT_SHOPPING_STATE_FILE,
|
|
615
|
+
max_return=int(max_products),
|
|
616
|
+
)
|
|
617
|
+
return products
|
|
618
|
+
|
|
619
|
+
@staticmethod
|
|
620
|
+
def detect_map_violations(
|
|
621
|
+
products: Sequence[Mapping[str, Any]],
|
|
622
|
+
map_price: float,
|
|
623
|
+
authorized_sellers: Sequence[str] | None = None,
|
|
624
|
+
*,
|
|
625
|
+
tolerance: float = 0.0,
|
|
626
|
+
) -> MapAuditReport:
|
|
627
|
+
"""Scan `offers[]` across merchants to flag MAP violators, unauthorized sellers, and cheapest undercuts."""
|
|
628
|
+
return detect_map_violations(
|
|
629
|
+
products,
|
|
630
|
+
map_price=map_price,
|
|
631
|
+
authorized_sellers=authorized_sellers,
|
|
632
|
+
tolerance=tolerance,
|
|
633
|
+
)
|
|
634
|
+
|
|
635
|
+
|
|
636
|
+
__all__ = [
|
|
637
|
+
"ShoppingNamespace",
|
|
638
|
+
"MapViolation",
|
|
639
|
+
"MapAuditReport",
|
|
640
|
+
"detect_map_violations",
|
|
641
|
+
"is_seller_authorized",
|
|
642
|
+
"normalize_domain",
|
|
643
|
+
"validate_google_commerce_url",
|
|
644
|
+
]
|