388 lines
12 KiB
Python
388 lines
12 KiB
Python
"""Customer orders from SystemGroup, dated after REPORT_ORDERS_SINCE.
|
|
|
|
The cutoff in .env is a Gregorian date. Delivery-note dates on the report
|
|
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"
|
|
_SINCE_KEY = "REPORT_ORDERS_SINCE"
|
|
_PREFIX_KEY = "REPORT_ORDERS_PREFIXES"
|
|
|
|
|
|
class CrmOrdersError(RuntimeError):
|
|
pass
|
|
|
|
|
|
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
|
|
|
|
_AUTH_MARKERS = ("Login appears to have failed", "redirected to login")
|
|
|
|
|
|
def login_rejected(message: str) -> bool:
|
|
text = message or ""
|
|
return any(marker in text for marker in _AUTH_MARKERS)
|
|
|
|
|
|
def report_base_url() -> str:
|
|
"""Shared SystemGroup host. Credentials are not read from the environment."""
|
|
base = (_setting("REPORT_BASE_URL") or _setting("CRM_BASE_URL") or "").strip()
|
|
if not base:
|
|
raise CrmOrdersError("Set REPORT_BASE_URL.")
|
|
if not base.endswith("/"):
|
|
base += "/"
|
|
return base
|
|
|
|
|
|
def parse_jalali(raw: str) -> tuple[int, int, int] | None:
|
|
text = (raw or "").translate(_DIGIT_MAP).strip().replace("-", "/")
|
|
bits = text.split("/")
|
|
if len(bits) != 3 or not all(bit.isdigit() for bit in bits):
|
|
return None
|
|
year, month, day = (int(bit) for bit in bits)
|
|
if year < 1200 or not 1 <= month <= 12 or not 1 <= day <= 31:
|
|
return None
|
|
return year, month, day
|
|
|
|
|
|
def jalali_from_gregorian(day: date) -> tuple[int, int, int]:
|
|
gy, gm, gd = day.year, day.month, day.day
|
|
g_days = (0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334)
|
|
gy2 = gy + 1 if gm > 2 else gy
|
|
days = (
|
|
355666
|
|
+ 365 * gy
|
|
+ (gy2 + 3) // 4
|
|
- (gy2 + 99) // 100
|
|
+ (gy2 + 399) // 400
|
|
+ gd
|
|
+ g_days[gm - 1]
|
|
)
|
|
jy = -1595 + 33 * (days // 12053)
|
|
days %= 12053
|
|
jy += 4 * (days // 1461)
|
|
days %= 1461
|
|
if days > 365:
|
|
jy += (days - 1) // 365
|
|
days = (days - 1) % 365
|
|
if days < 186:
|
|
jm = 1 + days // 31
|
|
jd = 1 + (days % 31)
|
|
else:
|
|
jm = 7 + (days - 186) // 30
|
|
jd = 1 + ((days - 186) % 30)
|
|
return jy, jm, jd
|
|
|
|
|
|
def format_jalali(parts: tuple[int, int, int]) -> str:
|
|
year, month, day = parts
|
|
return f"{year:04d}/{month:02d}/{day:02d}"
|
|
|
|
|
|
def note_date_as_jalali(raw: str) -> str:
|
|
parsed = parse_jalali(raw)
|
|
if parsed is None:
|
|
return (raw or "").strip()
|
|
return format_jalali(parsed)
|
|
|
|
|
|
def parse_gregorian(raw: str) -> date | None:
|
|
"""Parse YYYY-MM-DD or DD/MM/YYYY. Years before 1700 are rejected."""
|
|
text = (raw or "").translate(_DIGIT_MAP).strip().replace("-", "/").replace(".", "/")
|
|
bits = text.split("/")
|
|
if len(bits) != 3 or not all(bit.isdigit() for bit in bits):
|
|
return None
|
|
a, b, c = (int(bit) for bit in bits)
|
|
if a > 31:
|
|
year, month, day = a, b, c
|
|
elif c > 31:
|
|
day, month, year = a, b, c
|
|
else:
|
|
return None
|
|
if not 1700 <= year <= 2500:
|
|
return None
|
|
try:
|
|
return date(year, month, day)
|
|
except ValueError:
|
|
return None
|
|
|
|
|
|
def _env_file_value(key: str) -> str | None:
|
|
"""Return the value from .env, or None when the key is absent.
|
|
|
|
An empty value is returned as '' so a blank line is not ignored.
|
|
"""
|
|
if not _ENV_FILE.is_file():
|
|
return None
|
|
prefix = key + "="
|
|
for raw in _ENV_FILE.read_text(encoding="utf-8").splitlines():
|
|
line = raw.strip()
|
|
if not line or line.startswith("#") or not line.startswith(prefix):
|
|
continue
|
|
value = line[len(prefix):].strip()
|
|
if len(value) >= 2 and value[0] == value[-1] and value[0] in "\"'":
|
|
value = value[1:-1]
|
|
return value
|
|
return None
|
|
|
|
|
|
def _setting(key: str) -> str | None:
|
|
"""Project .env wins so a refresh sees edits; otherwise the process env."""
|
|
raw = _env_file_value(key)
|
|
if raw is None:
|
|
raw = os.environ.get(key)
|
|
return raw
|
|
|
|
|
|
def orders_cutoff() -> tuple[date, tuple[int, int, int]]:
|
|
"""Gregorian cutoff from .env, plus the same day as a Jalali tuple."""
|
|
day = parse_gregorian(_setting(_SINCE_KEY) or "")
|
|
if day is None:
|
|
raise CrmOrdersError(
|
|
"Set REPORT_ORDERS_SINCE in .env to a Gregorian date, e.g. 2026-09-23."
|
|
)
|
|
return day, jalali_from_gregorian(day)
|
|
|
|
|
|
def parse_prefixes(raw: str | None) -> list[str]:
|
|
if not raw:
|
|
return []
|
|
return [part.strip() for part in raw.split(",") if part.strip()]
|
|
|
|
|
|
def code_prefixes() -> list[str]:
|
|
"""Comma-separated product-code prefixes. An empty list keeps every code."""
|
|
return parse_prefixes(_setting(_PREFIX_KEY))
|
|
|
|
|
|
def code_matches(code: str, prefixes: list[str]) -> bool:
|
|
if not prefixes:
|
|
return True
|
|
text = (code or "").strip()
|
|
return any(text.startswith(prefix) for prefix in prefixes)
|
|
|
|
|
|
def orders_after(lines, start: tuple[int, int, int]):
|
|
"""Keep lines whose delivery-note date is strictly after start."""
|
|
kept = []
|
|
for line in lines:
|
|
parsed = parse_jalali(getattr(line, "delivery_note_date", ""))
|
|
if parsed is not None and parsed > start:
|
|
kept.append(line)
|
|
kept.sort(
|
|
key=lambda line: (
|
|
parse_jalali(line.delivery_note_date),
|
|
line.delivery_note_number,
|
|
line.product_code,
|
|
),
|
|
reverse=True,
|
|
)
|
|
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()
|
|
# The report GET redirects to login until the client has signed in.
|
|
if hasattr(client, "login") and not getattr(client, "_logged_in", False):
|
|
client.login()
|
|
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()
|
|
prefixes = code_prefixes()
|
|
try:
|
|
from lithium_systemgroup import (
|
|
SystemGroupClient,
|
|
SystemGroupClientError,
|
|
SystemGroupParseError,
|
|
parse_customer_orders_document,
|
|
)
|
|
except ImportError as exc:
|
|
raise CrmOrdersError("lithium-systemgroup is not installed") from exc
|
|
|
|
try:
|
|
if client is None:
|
|
client = SystemGroupClient(
|
|
base_url=report_base_url(),
|
|
username=username,
|
|
password=password,
|
|
timeout=30,
|
|
)
|
|
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)
|
|
if login_rejected(text):
|
|
raise CrmAuthError("SystemGroup rejected this username or password.") from exc
|
|
if text.startswith("Missing required env vars"):
|
|
text = "Set REPORT_BASE_URL."
|
|
raise CrmOrdersError(text) from exc
|
|
|
|
kept = [
|
|
line for line in orders_after(lines, start)
|
|
if code_matches(line.product_code, prefixes)
|
|
]
|
|
orders = []
|
|
for line in kept:
|
|
row = line.as_dict()
|
|
row["delivery_note_date"] = note_date_as_jalali(row["delivery_note_date"])
|
|
orders.append(row)
|
|
return {
|
|
"since": format_jalali(start),
|
|
"orders": orders,
|
|
}
|