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.
|
The host stays in .env. Username and password are supplied per request.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
import json
|
||||||
import os
|
import os
|
||||||
from datetime import date
|
import time
|
||||||
|
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"
|
||||||
@@ -24,6 +27,10 @@ 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
|
||||||
|
|
||||||
@@ -191,9 +198,148 @@ def orders_after(lines, start: tuple[int, int, int]):
|
|||||||
return kept
|
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:
|
def recent_customer_orders(username: str, password: str, client=None) -> dict:
|
||||||
"""Fetch the store delivery-note report and keep rows after the cutoff."""
|
"""Fetch the store delivery-note report and keep rows after the cutoff."""
|
||||||
_day, start = orders_cutoff()
|
day, start = orders_cutoff()
|
||||||
prefixes = code_prefixes()
|
prefixes = code_prefixes()
|
||||||
try:
|
try:
|
||||||
from lithium_systemgroup import (
|
from lithium_systemgroup import (
|
||||||
@@ -213,7 +359,7 @@ def recent_customer_orders(username: str, password: str, client=None) -> dict:
|
|||||||
password=password,
|
password=password,
|
||||||
timeout=30,
|
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)
|
lines = parse_customer_orders_document(body, content_type=content_type)
|
||||||
except (SystemGroupClientError, SystemGroupParseError) as exc:
|
except (SystemGroupClientError, SystemGroupParseError) as exc:
|
||||||
text = str(exc)
|
text = str(exc)
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ from slips.crm_orders import (
|
|||||||
CrmAuthError,
|
CrmAuthError,
|
||||||
CrmOrdersError,
|
CrmOrdersError,
|
||||||
code_matches,
|
code_matches,
|
||||||
|
export_filtered_customer_orders,
|
||||||
format_jalali,
|
format_jalali,
|
||||||
jalali_from_gregorian,
|
jalali_from_gregorian,
|
||||||
login_rejected,
|
login_rejected,
|
||||||
@@ -21,6 +22,7 @@ from slips.crm_orders import (
|
|||||||
parse_prefixes,
|
parse_prefixes,
|
||||||
recent_customer_orders,
|
recent_customer_orders,
|
||||||
report_base_url,
|
report_base_url,
|
||||||
|
report_filter_state,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@@ -124,6 +126,72 @@ class SystemGroupLoginTests(unittest.TestCase):
|
|||||||
with self.assertRaises(CrmAuthError):
|
with self.assertRaises(CrmAuthError):
|
||||||
recent_customer_orders("ada", "wrong")
|
recent_customer_orders("ada", "wrong")
|
||||||
|
|
||||||
|
def test_report_filter_uses_date_and_code_prefixes(self):
|
||||||
|
import json
|
||||||
|
|
||||||
|
state = report_filter_state(date(2026, 3, 21), ["ICJ/", "RMJ/"])
|
||||||
|
expr = state["expression"]
|
||||||
|
self.assertEqual(expr["operator"], 2)
|
||||||
|
self.assertEqual(expr["expressions"][0]["filterItemName"], "ord.Date")
|
||||||
|
self.assertEqual(expr["expressions"][0]["operator"], 3)
|
||||||
|
self.assertTrue(expr["expressions"][0]["operands"][0]["value"].startswith("/Date("))
|
||||||
|
codes = expr["expressions"][1]
|
||||||
|
self.assertEqual(codes["operator"], 3)
|
||||||
|
self.assertEqual(
|
||||||
|
[item["operands"][0]["value"] for item in codes["expressions"]],
|
||||||
|
["ICJ/", "RMJ/"],
|
||||||
|
)
|
||||||
|
self.assertEqual(report_filter_state(date(2026, 3, 21), [])["expression"]["expressions"][0]["filterItemName"], "ord.Date")
|
||||||
|
|
||||||
|
class Resp:
|
||||||
|
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):
|
||||||
|
return None
|
||||||
|
|
||||||
|
class Sess:
|
||||||
|
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(ctype, "text/csv")
|
||||||
|
posted = json.loads(sess.posts[0]["reportViewer_GenericFilterTemplate_Filter_ord_ClientState"])
|
||||||
|
self.assertEqual(posted["expression"]["expressions"][1]["filterItemName"], "pp.code")
|
||||||
|
self.assertEqual(posted["expression"]["expressions"][1]["operands"][0]["value"], "KR")
|
||||||
|
self.assertIn("PageID=", sess.gets[0])
|
||||||
|
self.assertIn("TimeStamp=", sess.gets[0])
|
||||||
|
|
||||||
|
|
||||||
class CrmSessionTests(TestCase):
|
class CrmSessionTests(TestCase):
|
||||||
def test_session_lasts_thirty_days_and_slides(self):
|
def test_session_lasts_thirty_days_and_slides(self):
|
||||||
|
|||||||
Reference in New Issue
Block a user