Filter order CSV by date and product code on the server
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -6,9 +6,12 @@ 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
|
||||
from datetime import date
|
||||
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"
|
||||
@@ -24,6 +27,10 @@ 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
|
||||
|
||||
@@ -191,9 +198,148 @@ def orders_after(lines, start: tuple[int, int, int]):
|
||||
return kept
|
||||
|
||||
|
||||
# SgFilter operator and operand codes from SgFilter.js.
|
||||
_OP_GREATER = 3
|
||||
_OP_STARTS = 9
|
||||
_OP_AND = 2
|
||||
_OP_OR = 3
|
||||
_TYPE_STRING = 1
|
||||
_TYPE_DATE = 3
|
||||
_TEHRAN = timezone(timedelta(hours=3, minutes=30))
|
||||
|
||||
|
||||
def _condition(name: str, data_type: int, operator: int, value: str, title: str) -> dict:
|
||||
return {
|
||||
"type": "FilterCondition",
|
||||
"filterItemName": name,
|
||||
"operandDataType": data_type,
|
||||
"operands": [{"value": value, "title": title}],
|
||||
"isParameteric": False,
|
||||
"operator": operator,
|
||||
}
|
||||
|
||||
|
||||
def report_filter_state(day: date, prefixes: list[str]) -> dict:
|
||||
"""Server filter: delivery-note date after day, and any product-code prefix."""
|
||||
moment = datetime(day.year, day.month, day.day, tzinfo=_TEHRAN)
|
||||
parts = [
|
||||
_condition(
|
||||
"ord.Date",
|
||||
_TYPE_DATE,
|
||||
_OP_GREATER,
|
||||
f"/Date({int(moment.timestamp() * 1000)})/",
|
||||
format_jalali(jalali_from_gregorian(day)),
|
||||
)
|
||||
]
|
||||
codes = [prefix for prefix in prefixes if prefix]
|
||||
code_conds = [
|
||||
_condition("pp.code", _TYPE_STRING, _OP_STARTS, code, code)
|
||||
for code in codes
|
||||
]
|
||||
if len(code_conds) == 1:
|
||||
parts.append(code_conds[0])
|
||||
elif code_conds:
|
||||
parts.append({
|
||||
"type": "FilterLogicalExpression",
|
||||
"expressions": code_conds,
|
||||
"operator": _OP_OR,
|
||||
})
|
||||
return {
|
||||
"view": 1,
|
||||
"expression": {
|
||||
"type": "FilterLogicalExpression",
|
||||
"expressions": parts,
|
||||
"operator": _OP_AND,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
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
|
||||
|
||||
|
||||
def _load_order_export(client, day: date, prefixes: list[str]) -> tuple[str, str]:
|
||||
"""Prefer the filtered export. A failed post still returns the full CSV."""
|
||||
if getattr(client, "session", None) is None:
|
||||
return client.fetch_customer_orders()
|
||||
try:
|
||||
return export_filtered_customer_orders(client, day, prefixes)
|
||||
except (_FilterMiss, OSError):
|
||||
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."""
|
||||
_day, start = orders_cutoff()
|
||||
day, start = orders_cutoff()
|
||||
prefixes = code_prefixes()
|
||||
try:
|
||||
from lithium_systemgroup import (
|
||||
@@ -213,7 +359,7 @@ def recent_customer_orders(username: str, password: str, client=None) -> dict:
|
||||
password=password,
|
||||
timeout=30,
|
||||
)
|
||||
body, content_type = client.fetch_customer_orders()
|
||||
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)
|
||||
|
||||
Reference in New Issue
Block a user