Use SystemGroup filtered order export
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -6,12 +6,9 @@ are Jalali, so the cutoff is converted before the comparison.
|
||||
The host stays in .env. Username and password are supplied per request.
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
from datetime import date, datetime, timedelta, timezone
|
||||
from pathlib import Path
|
||||
from urllib.parse import urljoin
|
||||
|
||||
_DIGIT_MAP = str.maketrans("۰۱۲۳۴۵۶۷۸۹٠١٢٣٤٥٦٧٨٩", "01234567890123456789")
|
||||
_ENV_FILE = Path(__file__).resolve().parents[1] / ".env"
|
||||
@@ -27,10 +24,6 @@ class CrmAuthError(CrmOrdersError):
|
||||
"""SystemGroup rejected the username or password."""
|
||||
|
||||
|
||||
class _FilterMiss(Exception):
|
||||
"""Filtered report post did not yield a CSV. Caller downloads the full report."""
|
||||
|
||||
|
||||
# Thirty days. The API refreshes this on each successful fetch.
|
||||
SESSION_TTL_SECONDS = 30 * 24 * 60 * 60
|
||||
|
||||
@@ -255,76 +248,8 @@ def report_filter_state(day: date, prefixes: list[str]) -> dict:
|
||||
|
||||
|
||||
def export_filtered_customer_orders(client, day: date, prefixes: list[str]) -> tuple[str, str]:
|
||||
"""Run the report with the SgFilter applied, then download the CSV.
|
||||
|
||||
PageID and TimeStamp key the server viewstate, same as the BoM list frame.
|
||||
"""
|
||||
from lithium_systemgroup import (
|
||||
SystemGroupClientError,
|
||||
extract_aspnet_post_fields,
|
||||
extract_export_url_base,
|
||||
strip_clientstate_updated,
|
||||
)
|
||||
from lithium_systemgroup.client import customer_orders_report_path_from_env
|
||||
|
||||
path = customer_orders_report_path_from_env()
|
||||
stamp = int(time.time() * 1000)
|
||||
sep = "&" if "?" in path else "?"
|
||||
page = (
|
||||
f"{path}{sep}PageID={stamp}&TimeStamp={stamp}"
|
||||
"&PageWidth=1050&PageHeight=670"
|
||||
)
|
||||
url = urljoin(client.base_url, page)
|
||||
timeout = getattr(client, "timeout", 30)
|
||||
resp = client.session.get(url, timeout=timeout, allow_redirects=True)
|
||||
resp.raise_for_status()
|
||||
if "login.aspx" in (resp.url or "").lower():
|
||||
raise SystemGroupClientError(
|
||||
"Customer orders report redirected to login; check credentials."
|
||||
)
|
||||
action, fields = extract_aspnet_post_fields(resp.text)
|
||||
post_url = urljoin(resp.url, action) if action and "PageID=" in action else resp.url
|
||||
fields = strip_clientstate_updated(fields)
|
||||
fields["__EVENTTARGET"] = "reportViewer"
|
||||
fields["__EVENTARGUMENT"] = json.dumps(
|
||||
{"commandName": "Execute"}, separators=(",", ":")
|
||||
)
|
||||
fields["__ASYNCPOST"] = "true"
|
||||
fields["SgScriptManager1"] = "UpdatePanel1|reportViewer"
|
||||
fields["reportViewer_GenericFilterTemplate_Filter_ord_ClientState"] = json.dumps(
|
||||
report_filter_state(day, prefixes), ensure_ascii=False, separators=(",", ":")
|
||||
)
|
||||
posted = client.session.post(
|
||||
post_url,
|
||||
data=fields,
|
||||
headers={
|
||||
"Referer": post_url,
|
||||
"X-MicrosoftAjax": "Delta=true",
|
||||
"X-Requested-With": "XMLHttpRequest",
|
||||
},
|
||||
timeout=timeout,
|
||||
allow_redirects=True,
|
||||
)
|
||||
posted.raise_for_status()
|
||||
if "login.aspx" in (posted.url or "").lower():
|
||||
raise SystemGroupClientError(
|
||||
"Customer orders report redirected to login; check credentials."
|
||||
)
|
||||
export = extract_export_url_base(posted.text)
|
||||
if not export:
|
||||
raise _FilterMiss()
|
||||
csv_resp = client.session.get(
|
||||
urljoin(client.base_url, export.lstrip("/") + "CSV"),
|
||||
timeout=timeout,
|
||||
allow_redirects=True,
|
||||
)
|
||||
csv_resp.raise_for_status()
|
||||
if "login.aspx" in (csv_resp.url or "").lower():
|
||||
raise SystemGroupClientError(
|
||||
"Customer orders export redirected to login; check credentials."
|
||||
)
|
||||
ctype = csv_resp.headers.get("Content-Type", "text/csv")
|
||||
return csv_resp.content.decode("utf-8-sig"), ctype
|
||||
"""Run the report with the SgFilter applied, then download the CSV."""
|
||||
return client.fetch_customer_orders(filter_state=report_filter_state(day, prefixes))
|
||||
|
||||
|
||||
def _load_order_export(client, day: date, prefixes: list[str]) -> tuple[str, str]:
|
||||
@@ -336,7 +261,10 @@ def _load_order_export(client, day: date, prefixes: list[str]) -> tuple[str, str
|
||||
client.login()
|
||||
try:
|
||||
return export_filtered_customer_orders(client, day, prefixes)
|
||||
except (_FilterMiss, OSError):
|
||||
except Exception as exc:
|
||||
if login_rejected(str(exc)):
|
||||
raise
|
||||
# A broken filter post must not blank the page. The full CSV still filters locally.
|
||||
return client.fetch_customer_orders()
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user