"""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 os from datetime import date, datetime, timedelta, timezone from pathlib import Path _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.""" # 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.""" return client.fetch_customer_orders(filter_state=report_filter_state(day, prefixes)) def _restore_cookies(client, cookies) -> None: """Reuse a SystemGroup login. A fresh login() would kick out the other session.""" jar = client.session.cookies for item in cookies: if not isinstance(item, dict) or not item.get("name"): continue jar.set( item["name"], item.get("value") or "", domain=item.get("domain") or None, path=item.get("path") or "/", ) client._logged_in = True def _cookie_dump(client) -> list[dict]: jar = getattr(getattr(client, "session", None), "cookies", None) if jar is None: return [] return [ {"name": cookie.name, "value": cookie.value, "domain": cookie.domain, "path": cookie.path} for cookie in jar ] def _load_order_export(client, day: date, prefixes: list[str]) -> tuple[str, str]: """Download the full CSV and let the local date and prefix checks drop rows. A server-side filter re-runs the report after the page has already loaded (~1.8s) to avoid downloading about 20KB. Direct export is faster. ponytail: pass filter_state=report_filter_state(day, prefixes) if this export starts taking more than a couple of seconds. """ return client.fetch_customer_orders() def recent_customer_orders(username: str, password: str, client=None, cookies=None) -> dict: """Fetch the store delivery-note report and keep rows after the cutoff. ``cookies`` is a previous SystemGroup login. Reusing it avoids a new login, which would sign the account out everywhere else. """ 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, ) if cookies: _restore_cookies(client, cookies) try: body, content_type = _load_order_export(client, day, prefixes) except SystemGroupClientError as exc: if not cookies or "redirected to login" not in str(exc): raise client._logged_in = False client.session.cookies.clear() 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, "cookies": _cookie_dump(client), }