205 lines
6.2 KiB
Python
205 lines
6.2 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.
|
|
"""
|
|
|
|
import os
|
|
from datetime import date
|
|
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
|
|
|
|
|
|
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
|
|
|
|
|
|
def recent_customer_orders(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(prefer_report_env=True, timeout=30)
|
|
body, content_type = client.fetch_customer_orders()
|
|
lines = parse_customer_orders_document(body, content_type=content_type)
|
|
except (SystemGroupClientError, SystemGroupParseError) as exc:
|
|
text = str(exc)
|
|
if text.startswith("Missing required env vars"):
|
|
text = "Set REPORT_BASE_URL, REPORT_USERNAME, and REPORT_PASSWORD."
|
|
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,
|
|
}
|