Use SystemGroup filtered order export

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
2026-11-21 14:41:39 +03:30
parent 09f0a2a24a
commit f11f40f5f0
3 changed files with 16 additions and 125 deletions

View File

@@ -2,4 +2,4 @@ django>=5.1,<5.3
django-ninja>=1.7,<2.0 django-ninja>=1.7,<2.0
gunicorn>=22.0,<24.0 gunicorn>=22.0,<24.0
whitenoise>=6.7,<7.0 whitenoise>=6.7,<7.0
lithium-systemgroup @ git+https://github.com/s-diaco/lithium-systemgroup.git@1c237c3d2917c11a5d9ae49e868be73bef1720b5 lithium-systemgroup @ git+https://github.com/s-diaco/lithium-systemgroup.git@a42f1d3147807efd9e15881d39cfcc0da8d8d4ab

View File

@@ -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. The host stays in .env. Username and password are supplied per request.
""" """
import json
import os import os
import time
from datetime import date, datetime, timedelta, timezone from datetime import date, datetime, timedelta, timezone
from pathlib import Path from pathlib import Path
from urllib.parse import urljoin
_DIGIT_MAP = str.maketrans("۰۱۲۳۴۵۶۷۸۹٠١٢٣٤٥٦٧٨٩", "01234567890123456789") _DIGIT_MAP = str.maketrans("۰۱۲۳۴۵۶۷۸۹٠١٢٣٤٥٦٧٨٩", "01234567890123456789")
_ENV_FILE = Path(__file__).resolve().parents[1] / ".env" _ENV_FILE = Path(__file__).resolve().parents[1] / ".env"
@@ -27,10 +24,6 @@ class CrmAuthError(CrmOrdersError):
"""SystemGroup rejected the username or password.""" """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. # Thirty days. The API refreshes this on each successful fetch.
SESSION_TTL_SECONDS = 30 * 24 * 60 * 60 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]: 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. """Run the report with the SgFilter applied, then download the CSV."""
return client.fetch_customer_orders(filter_state=report_filter_state(day, prefixes))
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
def _load_order_export(client, day: date, prefixes: list[str]) -> tuple[str, str]: 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() client.login()
try: try:
return export_filtered_customer_orders(client, day, prefixes) 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() return client.fetch_customer_orders()

View File

@@ -128,8 +128,6 @@ class SystemGroupLoginTests(unittest.TestCase):
recent_customer_orders("ada", "wrong") recent_customer_orders("ada", "wrong")
def test_report_filter_uses_date_and_code_prefixes(self): def test_report_filter_uses_date_and_code_prefixes(self):
import json
state = report_filter_state(date(2026, 3, 21), ["ICJ/", "RMJ/"]) state = report_filter_state(date(2026, 3, 21), ["ICJ/", "RMJ/"])
expr = state["expression"] expr = state["expression"]
self.assertEqual(expr["operator"], 2) self.assertEqual(expr["operator"], 2)
@@ -144,54 +142,19 @@ class SystemGroupLoginTests(unittest.TestCase):
) )
self.assertEqual(report_filter_state(date(2026, 3, 21), [])["expression"]["expressions"][0]["filterItemName"], "ord.Date") self.assertEqual(report_filter_state(date(2026, 3, 21), [])["expression"]["expressions"][0]["filterItemName"], "ord.Date")
class Resp: seen = {}
def __init__(self, text, url, content=None):
self.text = text
self.url = url
self.content = text.encode() if content is None else content
self.headers = {"Content-Type": "text/csv"}
self.status_code = 200
def raise_for_status(self): class Client:
return None def fetch_customer_orders(self, filter_state=None):
seen["filter_state"] = filter_state
return "note,code\n", "text/csv"
class Sess: body, ctype = export_filtered_customer_orders(Client(), date(2026, 3, 21), ["KR"])
def __init__(self):
self.posts = []
self.gets = []
def get(self, url, timeout, allow_redirects=True):
self.gets.append(url)
if url.endswith("CSV"):
return Resp("note,code\n", url, b"note,code\n")
return Resp(
'<form action="./ReportViewer.aspx?PageID=9" method="post">'
'<input type="hidden" name="__VIEWSTATE" value="" />'
'</form>',
"http://crm.example/ReportViewer.aspx?PageID=9",
)
def post(self, url, data, headers, timeout, allow_redirects=True):
self.posts.append(data)
return Resp(
'{"ExportUrlBase":"/Reserved.ReportViewerWebControl.axd?Format="}',
url,
)
sess = Sess()
client = SimpleNamespace(base_url="http://crm.example/", timeout=5, session=sess)
with patch(
"lithium_systemgroup.client.customer_orders_report_path_from_env",
return_value="ReportViewer.aspx?x=1",
):
body, ctype = export_filtered_customer_orders(client, date(2026, 3, 21), ["KR"])
self.assertEqual(body, "note,code\n") self.assertEqual(body, "note,code\n")
self.assertEqual(ctype, "text/csv") self.assertEqual(ctype, "text/csv")
posted = json.loads(sess.posts[0]["reportViewer_GenericFilterTemplate_Filter_ord_ClientState"]) posted = seen["filter_state"]["expression"]["expressions"][1]
self.assertEqual(posted["expression"]["expressions"][1]["filterItemName"], "pp.code") self.assertEqual(posted["filterItemName"], "pp.code")
self.assertEqual(posted["expression"]["expressions"][1]["operands"][0]["value"], "KR") self.assertEqual(posted["operands"][0]["value"], "KR")
self.assertIn("PageID=", sess.gets[0])
self.assertIn("TimeStamp=", sess.gets[0])
def test_filtered_export_logs_in_first(self): def test_filtered_export_logs_in_first(self):
calls = [] calls = []