Reuse the SystemGroup session instead of signing in on every fetch

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
2026-11-22 08:47:51 +03:30
parent e01e24a167
commit b5b39c591e
3 changed files with 121 additions and 14 deletions

View File

@@ -252,6 +252,31 @@ def export_filtered_customer_orders(client, day: date, prefixes: list[str]) -> t
return client.fetch_customer_orders(filter_state=report_filter_state(day, prefixes))
def _restore_cookies(client, cookies) -> None:
"""Reuse a SystemGroup login. A fresh login() would kick out the other session."""
jar = client.session.cookies
for item in cookies:
if not isinstance(item, dict) or not item.get("name"):
continue
jar.set(
item["name"],
item.get("value") or "",
domain=item.get("domain") or None,
path=item.get("path") or "/",
)
client._logged_in = True
def _cookie_dump(client) -> list[dict]:
jar = getattr(getattr(client, "session", None), "cookies", None)
if jar is None:
return []
return [
{"name": cookie.name, "value": cookie.value, "domain": cookie.domain, "path": cookie.path}
for cookie in jar
]
def _load_order_export(client, day: date, prefixes: list[str]) -> tuple[str, str]:
"""Download the full CSV and let the local date and prefix checks drop rows.
@@ -263,8 +288,12 @@ def _load_order_export(client, day: date, prefixes: list[str]) -> tuple[str, str
return client.fetch_customer_orders()
def recent_customer_orders(username: str, password: str, client=None) -> dict:
"""Fetch the store delivery-note report and keep rows after the cutoff."""
def recent_customer_orders(username: str, password: str, client=None, cookies=None) -> dict:
"""Fetch the store delivery-note report and keep rows after the cutoff.
``cookies`` is a previous SystemGroup login. Reusing it avoids a new login,
which would sign the account out everywhere else.
"""
day, start = orders_cutoff()
prefixes = code_prefixes()
try:
@@ -285,7 +314,16 @@ def recent_customer_orders(username: str, password: str, client=None) -> dict:
password=password,
timeout=30,
)
body, content_type = _load_order_export(client, day, prefixes)
if cookies:
_restore_cookies(client, cookies)
try:
body, content_type = _load_order_export(client, day, prefixes)
except SystemGroupClientError as exc:
if not cookies or "redirected to login" not in str(exc):
raise
client._logged_in = False
client.session.cookies.clear()
body, content_type = _load_order_export(client, day, prefixes)
lines = parse_customer_orders_document(body, content_type=content_type)
except (SystemGroupClientError, SystemGroupParseError) as exc:
text = str(exc)
@@ -307,4 +345,5 @@ def recent_customer_orders(username: str, password: str, client=None) -> dict:
return {
"since": format_jalali(start),
"orders": orders,
"cookies": _cookie_dump(client),
}