Compare commits
9 Commits
09f0a2a24a
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| bcc9409bc1 | |||
| bce0e2f2e4 | |||
| 7760fbbd0c | |||
| b5b39c591e | |||
| e01e24a167 | |||
| 0fa05ab48d | |||
| 2bf8c046c6 | |||
| 051b87f0e2 | |||
| f11f40f5f0 |
115
INVENTORY_DASHBOARD_HANDOFF.md
Normal file
115
INVENTORY_DASHBOARD_HANDOFF.md
Normal file
@@ -0,0 +1,115 @@
|
||||
# Inventory dashboard — implementation handoff
|
||||
|
||||
## Goal and scope
|
||||
Add an **Inventory / موجودی** tab to Lithium Labels: a modern, responsive dashboard showing current SystemGroup stock, pigment-based producible yield, and available position. Reuse the supplied report’s information hierarchy, not its static date or quantities. Deliver within the existing Django application; do not implement a separate frontend service.
|
||||
|
||||
**Required:** fetch CRM → normalize → persist unmodified quantities in SQLite → apply persistent signed offsets → calculate metrics → serve JSON/UI. **No Excel files, Excel intermediate steps, workbook libraries, PDF pipeline, or runtime dependency on the report folder.** This document is a plan only; no application changes have been made.
|
||||
|
||||
## Verified starting points
|
||||
- Django 5.x + Django Ninja, SQLite in persistent `data/`, templates and vanilla JavaScript; no JS build tool. Docker runs two Gunicorn workers with a 120-second request timeout.
|
||||
- Navigation: `slips/templates/slips/base.html`; routes: `config/urls.py`; views: `slips/views.py`; API/schemas: `slips/api.py`, `slips/schemas.py`.
|
||||
- Theme tokens: `slips/static/slips/css/style.css`. Translation/runtime language switching: `slips/static/slips/js/i18n.js` (`slip-language` event), Persian RTL and English LTR. Preserve all existing tabs and label/print behavior.
|
||||
- `slips/crm_orders.py` supplies host resolution, cookie restore/dump, authentication-error handling, and expired-cookie retry. `slips/api.py` stores per-browser SystemGroup credentials/cookies in the server-side Django session for 30 days. Do not introduce shared environment credentials or a second independent login.
|
||||
- `requirements.txt` pins lithium-systemgroup to commit `cbcadf37c2166ca4978f56f66c91007eb510ffcc`. The installed venv has editable distribution metadata reporting 0.2.0; this does **not** establish the pinned package’s inventory capabilities. Verify the actual pinned API before coding against it.
|
||||
|
||||
### Source material to port, not execute/import at runtime
|
||||
Under `/home/diaco/OpenCloud/Inco/Reports/2026/11/1122 Inventory/`:
|
||||
- `Stock_Report_22-11-2026.html`: content/layout reference, **not a live-data fixture** (root workbook quantities may have been manually adjusted).
|
||||
- `.cursor/skills/inco-crm-stock-report/SKILL.md` and `scripts/generate_crm_stock_report.py`: warehouse selection, filtering, raw-material aggregation.
|
||||
- `.cursor/skills/inco-stock-report/formulation.json` and `scripts/generate_stock_report.py`: mappings, `extract_code()`, `compute()`, primary/alternate rules.
|
||||
|
||||
Copy only the formulation JSON and necessary pure parsing/calculation logic into this repository, with provenance comments. Do not copy scripts wholesale: they write workbooks, manipulate `sys.path`, and depend on external folders.
|
||||
|
||||
## Architectural decisions
|
||||
|
||||
### 1. Modules and persistence
|
||||
Keep the `slips` app. Add:
|
||||
- `slips/systemgroup_session.py`: shared credential/cookie/session utilities extracted from the current API; preserve existing Orders endpoints and behavior.
|
||||
- `slips/crm_inventory.py`: SystemGroup adapter, warehouse fetches, normalization, validation; injectable client for tests.
|
||||
- `slips/inventory.py`: pure Decimal calculations, offset application, formulation validation and response assembly.
|
||||
- `slips/inventory_api.py`: Ninja router mounted under `/api/inventory`; explicit request/response schemas in `slips/schemas.py`.
|
||||
- `slips/data/inventory_formulation.json`: version-controlled mapping copied from the reference, loaded with `Decimal` percentages and validated on use. Include its content hash in responses.
|
||||
|
||||
Add models in `slips/models.py` and a migration:
|
||||
|
||||
| Model | Fields / invariants |
|
||||
|---|---|
|
||||
| `InventorySnapshot` | UUID, scope hash, product/raw warehouse codes, fetch-start/completed timestamps, source row counts, normalized validated rows in JSON (decimal strings), formulation-independent raw quantities. Immutable once published. |
|
||||
| `InventorySyncState` | Unique scope hash, latest snapshot FK, refresh lease token/expiry, last attempt/error metadata. Scope = canonical server-configured CRM host + CRM username + both warehouses. Never include passwords/cookies in snapshots or scope data. |
|
||||
| `InventoryOffset` | Warehouse code + kind (`product`, `pigment`, `solvent`) + canonical code + source-host scope; unique together. `DecimalField(max_digits=18, decimal_places=6)` signed delta in kg, reason, revision, updated timestamp, Django user FK. Shared across authorized users for the same inventory scope, not per browser. |
|
||||
| `InventoryOffsetChange` | Append-only audit: offset key, previous/new delta, reason, actor, timestamp, revision. Reset writes zero and an audit row; do not erase history. |
|
||||
|
||||
Do not reuse the existing label `Product` table as the inventory catalog: inventory contains codes without label defaults. Do not mutate Orders or subtract label quantities from CRM stock. Retain only the latest successful snapshot per scope plus one previous snapshot; prune older snapshots after successful publication. Keep offset audit history.
|
||||
|
||||
### 2. Warehouse fetch and normalization
|
||||
- Use `SystemGroupClient.fetch_quantitative_review_lines(warehouse_code=...)` and `filter_inventory_lines`; the source skill requires warehouse support available in lithium-systemgroup ≥0.2.10. Check signatures, pagination completion and unit fields against the pinned package; if necessary pin a reviewed immutable compatible commit. Never depend on floating `main` or a developer-local checkout.
|
||||
- Fetch sequentially with one authenticated client: products from warehouse **2002**, raw materials from **2001**. Add `INCO_PRODUCT_WAREHOUSE` / `INCO_RAW_WAREHOUSE` settings with these defaults and pass through Compose.
|
||||
- Products: retain `ICJ/` and `RMJ/`. Raw: the reference `ICQ|RMS/` text filter plus code extraction from title, falling back to part code. Preserve recognition of forms such as `ICQ 13Q468`, `IC 13/436`, `RMS/403`; normalize whitespace, case and Persian/Arabic digits first.
|
||||
- Aggregate distinct source rows by canonical code **within each warehouse only**. Detect repeated pages/rows before summing; do not combine warehouses. Preserve source identifiers/titles for diagnostics.
|
||||
- Quantities must be finite Decimal kg. Use original numeric text if the client exposes it; otherwise `Decimal(str(quantity))`, never `Decimal(float)`. Validate units; do not silently treat pieces or litres as kg. If the client lacks unit/completion metadata, resolve that adapter limitation before declaring production readiness.
|
||||
- Fail publication for unparseable retained rows, unsupported units, truncated paging, login HTML, unexpectedly empty product/raw datasets, or failure of either warehouse. Report a sanitized error; never turn failed/missing fetches into zero inventory. Genuine zero-valued rows are valid.
|
||||
- Only a validated complete snapshot may replace the current one, in one short transaction. Fetching two warehouses is not an atomic CRM read: expose fetch start/end and label the values as a snapshot.
|
||||
|
||||
### 3. Offset semantics — explicit and non-compounding
|
||||
For each normalized inventory key:
|
||||
|
||||
`adjusted_kg = crm_kg + offset_kg` (default offset = 0)
|
||||
|
||||
Example: CRM 100, offset −15 → display 85. Next refresh CRM 120 → display 105, **not** 85. Refresh never changes the offset; editing an offset never changes the stored CRM quantity.
|
||||
|
||||
- Apply offsets **after aggregation and before yield calculations**, to finished products, pigments and solvents independently. No editable offsets on derived producible/available totals.
|
||||
- Editor shows CRM quantity, current delta, adjusted result, reason, last editor/time and explicit reset-to-zero. Save sets an absolute delta, not an increment. Optionally entering a physical count computes `physical − displayed CRM`, requiring the displayed snapshot ID still be current; reject stale forms with 409.
|
||||
- Require reason and expected revision on mutation; compare-and-swap inside a transaction, return 409 on concurrent updates. All API numeric values are decimal strings; reject nonfinite, out-of-range and overprecision inputs.
|
||||
- Keep signed adjusted inventory visible and flag negatives; for physical production potential use `max(adjusted_pigment_kg, 0) / share`, never generate negative yield. Product stock totals retain signed balances. Explain this deliberate edge-case refinement of the reference.
|
||||
- A missing code in a complete snapshot has no fabricated CRM quantity. Retain its offset and show it as **orphaned/unapplied** in the editor; do not add it to totals. Mapped pigments absent from a complete raw snapshot may render as zero with an explicit “absent from source” marker, but offsets stay unapplied until that key reappears. A mapped product with positive yield but absent finished-stock row must appear with stock 0 and an absence marker, so its yield is not silently lost.
|
||||
- Compute responses from one captured snapshot plus one consistent read of offsets; expose an offset revision/hash. Saving offsets recomputes immediately from that snapshot, without contacting CRM.
|
||||
|
||||
### 4. Preserve the report’s business rules
|
||||
- `yield = adjusted pigment stock / formulation share`; sum **primary** yields per product; `available = adjusted finished stock + primary yield`.
|
||||
- Q462 and Q468 map primarily to **ICJ/407 at 40%**; **ICJ/408 at 45%** is an alternative use of the same stock, shown in notes only, never added to product/KPI totals.
|
||||
- **ICQ12/Q300 remains excluded** from pigment report/KPI and yield until explicitly mapped; keep its raw snapshot row and disclose excluded material separately. Never infer Q300 → ICJ/308.
|
||||
- Include other unmapped pigments with stock and unknown yield; do not invent percentages. Solvents are inventory only. Preserve configured solvent order, then append new codes deterministically.
|
||||
- Retain full precision in calculations; format to Western digits, thousands separators and whole kg at presentation. Totals use unrounded values, not rounded row sums; disclose possible rounding differences. Offset editor shows full stored precision.
|
||||
- Label producible as **pigment-based potential**, not confirmed executable production: this calculation does not constrain yield by solvents, other ingredients, capacity or scheduling.
|
||||
|
||||
### 5. Freshness, concurrency and errors
|
||||
MVP uses on-open stale refresh and a manual Refresh button; no Celery, Redis, unattended credential use or background threads.
|
||||
- `GET /api/inventory` reads the current account’s cached snapshot only; requires the saved SystemGroup session. Return snapshot/formulation/offset metadata, rows, KPIs, warnings, last error and stale state. No snapshot returns an explicit empty state, not a zero report.
|
||||
- Client calls `POST /api/inventory/refresh` on first open or when snapshot age exceeds **5 minutes**, and on manual refresh. Do not poll hidden tabs. Show “as of” time, warehouse codes and refresh progress; cached data remains visible with a stale/error banner if refresh fails.
|
||||
- Use a DB-backed compare-and-swap refresh lease per scope, not a Python lock (two workers). Return 409 `refresh_in_progress` for a held lease; expiry permits recovery and publication requires the matching token. Never hold a SQLite transaction during CRM I/O.
|
||||
- Bound the whole synchronous fetch to **90 seconds**, including cookie-expiry retry and both warehouses, with per-request timeouts and pagination limits; lease outlives this budget. Check nginx/proxy timeouts too. If the package cannot enforce a total deadline, fix that capability before shipping; do not silently publish partial data or merely increase worker timeouts indefinitely.
|
||||
- Reuse saved cookies to avoid logging the account out elsewhere. On recognized expired login, clear stale cookies and retry authentication once; invalid credentials → 401 and shared session cleared. Other upstream failures → 502/504 with stable sanitized codes and old snapshot retained. No browser access to CRM secrets.
|
||||
|
||||
### 6. Security / access boundaries
|
||||
- Scope cached reads by current CRM identity and host/warehouse combination; do not return another account’s snapshot. A saved CRM session is not a Django staff identity.
|
||||
- Require an authenticated **Django staff user plus valid CRM session** for offset writes/audit access. Use Django admin login and a staff-only dashboard editor; show read-only adjustment badges to other CRM users. This intentionally adds no custom role system and prevents anonymous LAN clients from changing shared physical corrections.
|
||||
- Protect **all new cookie/session-backed mutations** (refresh, inventory login/logout, offsets) with actual enforced Django CSRF validation; Ninja’s default behavior is not sufficient evidence. Send CSRF headers from JS and test with `enforce_csrf_checks=True`. Preserve legacy Orders API compatibility while extracting shared helpers.
|
||||
- Add inventory-specific session POST/DELETE endpoints using the shared utilities, validating credentials by fetching inventory rather than unnecessarily downloading Orders or requiring `REPORT_ORDERS_SINCE`. Reuse an existing session automatically. Inventory and Orders sign-out clear the same credentials.
|
||||
- Escape source text (`textContent`, not HTML injection); do not return raw CRM HTML, tracebacks, cookies or credentials. No secrets in logs, model audit records, localStorage or source control. Responses use `Cache-Control: no-store`.
|
||||
|
||||
## UI contract
|
||||
Add `/inventory/`, a nav link/active block and `slips/templates/slips/inventory.html`, with scoped `slips/static/slips/css/inventory.css` and `js/inventory.js`. Extend existing tokens and translation dictionaries; do not globally redesign the app or add React/CDN chart dependencies.
|
||||
|
||||
Layout: title + account/warehouse/as-of toolbar → five KPI cards (adjusted product stock, primary producible potential, available position, included pigments, solvents) → sorted horizontal paired stock/producible bars → Products / Pigments / Solvents tables → exclusions/shared-stock warnings. Use accessible local SVG or CSS bars, text values, legend and a visible zero baseline supporting negative stock. Tables expose CRM, offset and adjusted values via expandable detail; adjusted values drive the main dashboard.
|
||||
|
||||
Use restrained cards, clear typography, tabular numerals, responsive KPI columns, scrollable tables, loading skeletons, empty/error/stale states and adjustment/negative/mapping badges. Keyboard-accessible editor, named controls, status announcements, adequate light/dark contrast; do not convey status through color alone. Codes/numbers remain LTR within Persian RTL. Re-render dynamic labels on `slip-language`; theme via CSS variables. Search/filter tables without changing overall KPI totals; label chart sorting by adjusted available position. Mobile layout must not overflow the page.
|
||||
|
||||
## Exact implementation sequence
|
||||
1. **Baseline:** run existing Django checks/tests; inspect the installed and pinned lithium APIs with mocks, especially inventory warehouse selection, units, pagination, cookies and timeouts. Record pre-existing failures. Confirm required package capability or update to an immutable pin; do not perform live CRM login without available credentials/authorization.
|
||||
2. **Pure domain layer:** copy formulation JSON; implement parser, strict validation, Decimal normalization, aggregation, exclusions, primary/alternate calculations, negative handling and deterministic ordering. Add synthetic fixtures and unit tests before UI work.
|
||||
3. **Database:** add snapshot/sync/offset/audit models and migration, constraints/indexes, refresh lease CAS, atomic publication/pruning and optimistic offset updates. Validate from an empty DB and against existing migrations. Keep label models unchanged.
|
||||
4. **Shared authentication + adapter:** extract session helpers with regression tests for Orders; implement inventory client reuse, bounded expired-cookie retry, complete two-warehouse fetch and sanitized failures. Never port workbook generation or local-path imports.
|
||||
5. **API:** register router; implement GET dashboard, POST refresh, POST/DELETE inventory session, GET staff offsets/audit and PUT offset (zero means reset). Encode composite code keys in request bodies/query fields, not slash-containing path segments. Implement explicit schemas/status codes, CSRF, authorization, scope separation and revision checks.
|
||||
6. **UI:** add route/view/tab/template, responsive styles, chart, tables, staff offset editor, shared sign-in/out, refresh/staleness flow and both translations. Use the project frontend/dataviz guidance when implementing visuals.
|
||||
7. **Deployment/docs:** document warehouses, stale threshold, deadline/lease, staff provisioning, offset semantics and database backup; add warehouse env passthrough. Verify packaged formulation/static assets in Docker and collectstatic. Keep application data in the existing volume; no spreadsheet/PDF dependencies or artifacts.
|
||||
8. **Acceptance:** run `python manage.py check`, `python manage.py makemigrations --check --dry-run`, `python manage.py test`, and `python manage.py collectstatic --noinput` using the project environment. Verify browser behavior in both languages/themes and mobile/desktop; inspect browser console/network. With authorized LAN access, smoke-test both warehouses and compare normalized CRM quantities with the source, documenting any unavailable live verification.
|
||||
|
||||
## Required acceptance tests
|
||||
- Warehouse isolation, full pagination, distinct-row summing vs repeated-page detection, Unicode/code parsing, zero rows, unsupported units, unparseable rows, new codes and orphaned offsets.
|
||||
- Positive/negative/zero offsets persist across refresh and restart, never compound, and apply before yield; −15 at CRM 100/120 gives 85/105. Same code in different warehouses/hosts stays isolated.
|
||||
- Q300 never contributes; Q462/Q468 alternates never double-count. Test exact reference mapping with synthetic data: Q100 1000 → 2222.222…; Q345 500 → 1428.571…; Q322 300 → 1071.428…; Q630 1825 → 3650; Q660 2700 → 5400; Q710 250 → 555.555…. Combined potential formats as 14,328 kg, independent of finished-stock fixture values.
|
||||
- Failure of the second warehouse, page truncation or timeout leaves the prior snapshot intact; first-run failure never renders fabricated zeros. Cross-worker refresh collisions and expired lease tokens cannot overwrite newer data.
|
||||
- 401 login/expiry, 403 unauthorized offset mutation, 403 missing CSRF, 409 stale editor/revision and refresh collision; identity isolation; stored source HTML cannot execute. Existing Orders session reuse and print/label tests remain green.
|
||||
- No `.xlsx`/`.xls`, workbook snapshots or spreadsheet-generation dependencies introduced. Unit/API tests run offline with a fake client and no live credentials. Report fixture math tests are not a claim that the November 22 HTML matches today’s CRM.
|
||||
|
||||
**Definition of done:** a user can open Inventory, reuse/sign into SystemGroup, refresh both warehouses, see timestamped adjusted stock and correctly qualified yield, and (as staff) persist/audit/reset corrections without changing raw CRM values or affecting any existing tab.
|
||||
@@ -2,4 +2,4 @@ django>=5.1,<5.3
|
||||
django-ninja>=1.7,<2.0
|
||||
gunicorn>=22.0,<24.0
|
||||
whitenoise>=6.7,<7.0
|
||||
lithium-systemgroup @ git+https://github.com/s-diaco/lithium-systemgroup.git@1c237c3d2917c11a5d9ae49e868be73bef1720b5
|
||||
lithium-systemgroup @ git+https://github.com/s-diaco/lithium-systemgroup.git@cbcadf37c2166ca4978f56f66c91007eb510ffcc
|
||||
|
||||
31
slips/api.py
31
slips/api.py
@@ -162,6 +162,7 @@ def delete_order(request, order_id: int):
|
||||
|
||||
_SG_USER = 'sg_username'
|
||||
_SG_PASS = 'sg_password'
|
||||
_SG_COOKIES = 'sg_cookies'
|
||||
|
||||
|
||||
def _session_credentials(request):
|
||||
@@ -172,21 +173,33 @@ def _session_credentials(request):
|
||||
return username, password
|
||||
|
||||
|
||||
def _remember_credentials(request, username, password):
|
||||
def _stored_cookies(request, username):
|
||||
raw = request.session.get(_SG_COOKIES)
|
||||
if not isinstance(raw, dict) or raw.get('username') != username:
|
||||
return None
|
||||
cookies = raw.get('cookies')
|
||||
return cookies if isinstance(cookies, list) and cookies else None
|
||||
|
||||
|
||||
def _remember_credentials(request, username, password, cookies=None):
|
||||
request.session[_SG_USER] = username
|
||||
request.session[_SG_PASS] = password
|
||||
if cookies:
|
||||
request.session[_SG_COOKIES] = {'username': username, 'cookies': cookies}
|
||||
request.session.set_expiry(SESSION_TTL_SECONDS)
|
||||
|
||||
|
||||
def _forget_credentials(request):
|
||||
request.session.pop(_SG_USER, None)
|
||||
request.session.pop(_SG_PASS, None)
|
||||
request.session.pop(_SG_COOKIES, None)
|
||||
|
||||
|
||||
def _customer_orders(username, password):
|
||||
data = recent_customer_orders(username, password)
|
||||
def _customer_orders(username, password, cookies=None):
|
||||
data = recent_customer_orders(username, password, cookies=cookies)
|
||||
saved = data.pop('cookies', None)
|
||||
data['username'] = username
|
||||
return data
|
||||
return data, saved
|
||||
|
||||
|
||||
@api.get('/crm-orders', response={200: CrmOrdersOut, 401: dict, 502: dict}, tags=['Orders'])
|
||||
@@ -197,7 +210,9 @@ def list_crm_orders(request):
|
||||
return 401, {'detail': 'Sign in to SystemGroup.', 'code': 'login_required'}
|
||||
username, password = creds
|
||||
try:
|
||||
data = _customer_orders(username, password)
|
||||
data, cookies = _customer_orders(
|
||||
username, password, _stored_cookies(request, username)
|
||||
)
|
||||
except CrmAuthError:
|
||||
_forget_credentials(request)
|
||||
return 401, {
|
||||
@@ -206,7 +221,7 @@ def list_crm_orders(request):
|
||||
}
|
||||
except CrmOrdersError as exc:
|
||||
return 502, {'detail': str(exc)}
|
||||
_remember_credentials(request, username, password)
|
||||
_remember_credentials(request, username, password, cookies)
|
||||
return data
|
||||
|
||||
|
||||
@@ -222,7 +237,7 @@ def start_crm_session(request, payload: CrmLoginIn):
|
||||
if not username or not password:
|
||||
return 400, {'detail': 'Username and password are required.'}
|
||||
try:
|
||||
data = _customer_orders(username, password)
|
||||
data, cookies = _customer_orders(username, password)
|
||||
except CrmAuthError:
|
||||
return 401, {
|
||||
'detail': 'SystemGroup rejected this username or password.',
|
||||
@@ -230,7 +245,7 @@ def start_crm_session(request, payload: CrmLoginIn):
|
||||
}
|
||||
except CrmOrdersError as exc:
|
||||
return 502, {'detail': str(exc)}
|
||||
_remember_credentials(request, username, password)
|
||||
_remember_credentials(request, username, password, cookies)
|
||||
return data
|
||||
|
||||
|
||||
|
||||
@@ -6,12 +6,9 @@ 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"
|
||||
@@ -27,10 +24,6 @@ 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
|
||||
|
||||
@@ -255,93 +248,52 @@ def report_filter_state(day: date, prefixes: list[str]) -> dict:
|
||||
|
||||
|
||||
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.
|
||||
"""Run the report with the SgFilter applied, then download the CSV."""
|
||||
return client.fetch_customer_orders(filter_state=report_filter_state(day, prefixes))
|
||||
|
||||
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."
|
||||
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 "/",
|
||||
)
|
||||
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
|
||||
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]:
|
||||
"""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()
|
||||
"""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) -> dict:
|
||||
"""Fetch the store delivery-note report and keep rows after the cutoff."""
|
||||
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:
|
||||
@@ -362,7 +314,16 @@ def recent_customer_orders(username: str, password: str, client=None) -> dict:
|
||||
password=password,
|
||||
timeout=30,
|
||||
)
|
||||
body, content_type = _load_order_export(client, day, prefixes)
|
||||
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)
|
||||
@@ -384,4 +345,5 @@ def recent_customer_orders(username: str, password: str, client=None) -> dict:
|
||||
return {
|
||||
"since": format_jalali(start),
|
||||
"orders": orders,
|
||||
"cookies": _cookie_dump(client),
|
||||
}
|
||||
|
||||
148
slips/tests.py
148
slips/tests.py
@@ -128,8 +128,6 @@ class SystemGroupLoginTests(unittest.TestCase):
|
||||
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)
|
||||
@@ -144,88 +142,88 @@ class SystemGroupLoginTests(unittest.TestCase):
|
||||
)
|
||||
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])
|
||||
|
||||
def test_filtered_export_logs_in_first(self):
|
||||
calls = []
|
||||
seen = {}
|
||||
|
||||
class Client:
|
||||
def __init__(self):
|
||||
self.session = object()
|
||||
self._logged_in = False
|
||||
def fetch_customer_orders(self, filter_state=None):
|
||||
seen["filter_state"] = filter_state
|
||||
return "note,code\n", "text/csv"
|
||||
|
||||
def login(self):
|
||||
calls.append("login")
|
||||
self._logged_in = True
|
||||
body, ctype = export_filtered_customer_orders(Client(), date(2026, 3, 21), ["KR"])
|
||||
self.assertEqual(body, "note,code\n")
|
||||
self.assertEqual(ctype, "text/csv")
|
||||
posted = seen["filter_state"]["expression"]["expressions"][1]
|
||||
self.assertEqual(posted["filterItemName"], "pp.code")
|
||||
self.assertEqual(posted["operands"][0]["value"], "KR")
|
||||
|
||||
def fetch_customer_orders(self):
|
||||
calls.append("full")
|
||||
def test_load_uses_direct_export(self):
|
||||
seen = {}
|
||||
|
||||
class Client:
|
||||
def fetch_customer_orders(self, **kwargs):
|
||||
seen.update(kwargs)
|
||||
return "full", "text/csv"
|
||||
|
||||
client = Client()
|
||||
with patch(
|
||||
"slips.crm_orders.export_filtered_customer_orders",
|
||||
return_value=("filtered", "text/csv"),
|
||||
) as filtered:
|
||||
body, ctype = _load_order_export(client, date(2026, 3, 21), ["KR"])
|
||||
self.assertEqual(calls, ["login"])
|
||||
self.assertEqual((body, ctype), ("filtered", "text/csv"))
|
||||
filtered.assert_called_once()
|
||||
body, ctype = _load_order_export(Client(), date(2026, 3, 21), ["KR"])
|
||||
self.assertEqual((body, ctype), ("full", "text/csv"))
|
||||
self.assertNotIn("filter_state", seen)
|
||||
|
||||
def test_saved_cookies_are_reused_until_the_session_is_replaced(self):
|
||||
import requests
|
||||
from lithium_systemgroup import SystemGroupClientError
|
||||
|
||||
class Client:
|
||||
def __init__(self, replaced=False):
|
||||
self.session = requests.Session()
|
||||
self._logged_in = False
|
||||
self.replaced = replaced
|
||||
self.fetches = []
|
||||
|
||||
def fetch_customer_orders(self):
|
||||
self.fetches.append(self._logged_in)
|
||||
if self._logged_in and self.replaced:
|
||||
self.replaced = False
|
||||
raise SystemGroupClientError(
|
||||
"Customer orders report redirected to login"
|
||||
)
|
||||
self._logged_in = True
|
||||
self.session.cookies.set("auth", "ok", domain="crm.example", path="/")
|
||||
return "", "text/csv"
|
||||
|
||||
def setting(key):
|
||||
if key == "REPORT_BASE_URL":
|
||||
return "http://crm.example"
|
||||
if key == "REPORT_ORDERS_SINCE":
|
||||
return "2026-03-21"
|
||||
return None
|
||||
|
||||
fresh = Client()
|
||||
with patch("slips.crm_orders._setting", setting), \
|
||||
patch("lithium_systemgroup.parse_customer_orders_document", lambda body, content_type="": []):
|
||||
saved = recent_customer_orders("ada", "secret", client=fresh)["cookies"]
|
||||
self.assertEqual(fresh.fetches, [False])
|
||||
self.assertEqual(saved[0]["name"], "auth")
|
||||
reused = Client()
|
||||
recent_customer_orders("ada", "secret", client=reused, cookies=saved)
|
||||
self.assertEqual(reused.fetches, [True])
|
||||
replaced = Client(replaced=True)
|
||||
recent_customer_orders("ada", "secret", client=replaced, cookies=saved)
|
||||
self.assertEqual(replaced.fetches, [True, False])
|
||||
|
||||
|
||||
class CrmSessionTests(TestCase):
|
||||
def test_session_lasts_thirty_days_and_slides(self):
|
||||
from slips import api
|
||||
|
||||
def fake(username, password, client=None):
|
||||
return {"since": "1405/01/01", "orders": []}
|
||||
seen = {}
|
||||
|
||||
def fake(username, password, client=None, cookies=None):
|
||||
seen["cookies"] = cookies
|
||||
return {
|
||||
"since": "1405/01/01",
|
||||
"orders": [],
|
||||
"cookies": [{"name": "auth", "value": "1", "domain": "crm", "path": "/"}],
|
||||
}
|
||||
|
||||
with patch.object(api, "recent_customer_orders", fake):
|
||||
res = self.client.post(
|
||||
@@ -235,14 +233,17 @@ class CrmSessionTests(TestCase):
|
||||
)
|
||||
self.assertEqual(res.status_code, 200)
|
||||
self.assertEqual(res.json()["username"], "ada")
|
||||
self.assertNotIn("cookies", res.json())
|
||||
self.assertEqual(self.client.session["sg_username"], "ada")
|
||||
self.assertEqual(self.client.session["sg_password"], "secret")
|
||||
self.assertEqual(self.client.session["sg_cookies"]["username"], "ada")
|
||||
self.assertGreater(
|
||||
self.client.session.get_expiry_date() - timezone.now(),
|
||||
timedelta(days=29),
|
||||
)
|
||||
res = self.client.get("/api/crm-orders")
|
||||
self.assertEqual(res.status_code, 200)
|
||||
self.assertEqual(seen["cookies"][0]["name"], "auth")
|
||||
self.assertGreater(
|
||||
self.client.session.get_expiry_date() - timezone.now(),
|
||||
timedelta(days=29),
|
||||
@@ -250,6 +251,7 @@ class CrmSessionTests(TestCase):
|
||||
self.client.delete("/api/crm-orders/session")
|
||||
self.assertNotIn("sg_username", self.client.session)
|
||||
self.assertNotIn("sg_password", self.client.session)
|
||||
self.assertNotIn("sg_cookies", self.client.session)
|
||||
res = self.client.get("/api/crm-orders")
|
||||
self.assertEqual(res.status_code, 401)
|
||||
self.assertEqual(res.json()["code"], "login_required")
|
||||
@@ -257,7 +259,7 @@ class CrmSessionTests(TestCase):
|
||||
def test_rejected_password_is_not_stored(self):
|
||||
from slips import api
|
||||
|
||||
def fake(username, password, client=None):
|
||||
def fake(username, password, client=None, cookies=None):
|
||||
raise CrmAuthError("nope")
|
||||
|
||||
with patch.object(api, "recent_customer_orders", fake):
|
||||
|
||||
Reference in New Issue
Block a user