Compare commits
21 Commits
1910e7560f
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| bcc9409bc1 | |||
| bce0e2f2e4 | |||
| 7760fbbd0c | |||
| b5b39c591e | |||
| e01e24a167 | |||
| 0fa05ab48d | |||
| 2bf8c046c6 | |||
| 051b87f0e2 | |||
| f11f40f5f0 | |||
| 09f0a2a24a | |||
| 8f6e617972 | |||
| 389b39105e | |||
| 171a5847ae | |||
| 3f35cec709 | |||
| 8280eeed7c | |||
| ee218bccae | |||
| f5632ed464 | |||
| d7a68c2e51 | |||
| c883063c08 | |||
| c221b8fe58 | |||
| b8c4e703fb |
@@ -9,9 +9,9 @@ HTTP_PORT=80
|
|||||||
# PIP_TRUSTED_HOST=pypi.tuna.tsinghua.edu.cn
|
# PIP_TRUSTED_HOST=pypi.tuna.tsinghua.edu.cn
|
||||||
|
|
||||||
# SystemGroup store delivery-note report (Orders tab). Never commit real values.
|
# SystemGroup store delivery-note report (Orders tab). Never commit real values.
|
||||||
|
# The host is shared. Each person signs in on the Orders page; the password
|
||||||
|
# stays in the server session for 30 days and is not read from this file.
|
||||||
# REPORT_BASE_URL=http://crm.example/
|
# REPORT_BASE_URL=http://crm.example/
|
||||||
# REPORT_USERNAME=
|
|
||||||
# REPORT_PASSWORD=
|
|
||||||
# Optional report page path (no host). Leave unset to use the package default.
|
# Optional report page path (no host). Leave unset to use the package default.
|
||||||
# REPORT_ORDERS_PATH=
|
# REPORT_ORDERS_PATH=
|
||||||
# Gregorian cutoff. The Orders tab lists delivery notes dated after this day.
|
# Gregorian cutoff. The Orders tab lists delivery notes dated after this day.
|
||||||
@@ -20,7 +20,5 @@ HTTP_PORT=80
|
|||||||
# Comma-separated product-code prefixes. A note is listed only when its code starts with one of these.
|
# Comma-separated product-code prefixes. A note is listed only when its code starts with one of these.
|
||||||
# Leave empty to keep every code.
|
# Leave empty to keep every code.
|
||||||
# REPORT_ORDERS_PREFIXES=ICJ/,RMJ/,IJP/,KR
|
# REPORT_ORDERS_PREFIXES=ICJ/,RMJ/,IJP/,KR
|
||||||
# Optional CRM host. Used only when the matching REPORT_* value is unset.
|
# Optional CRM host. Used only when REPORT_BASE_URL is unset.
|
||||||
# CRM_BASE_URL=
|
# CRM_BASE_URL=
|
||||||
# CRM_USERNAME=
|
|
||||||
# CRM_PASSWORD=
|
|
||||||
|
|||||||
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.
|
||||||
@@ -14,14 +14,10 @@ services:
|
|||||||
- DJANGO_DEBUG=0
|
- DJANGO_DEBUG=0
|
||||||
- DJANGO_ALLOWED_HOSTS=*
|
- DJANGO_ALLOWED_HOSTS=*
|
||||||
- REPORT_BASE_URL=${REPORT_BASE_URL:-}
|
- REPORT_BASE_URL=${REPORT_BASE_URL:-}
|
||||||
- REPORT_USERNAME=${REPORT_USERNAME:-}
|
|
||||||
- REPORT_PASSWORD=${REPORT_PASSWORD:-}
|
|
||||||
- REPORT_ORDERS_PATH=${REPORT_ORDERS_PATH:-}
|
- REPORT_ORDERS_PATH=${REPORT_ORDERS_PATH:-}
|
||||||
- REPORT_ORDERS_SINCE=${REPORT_ORDERS_SINCE:-}
|
- REPORT_ORDERS_SINCE=${REPORT_ORDERS_SINCE:-}
|
||||||
- REPORT_ORDERS_PREFIXES=${REPORT_ORDERS_PREFIXES:-}
|
- REPORT_ORDERS_PREFIXES=${REPORT_ORDERS_PREFIXES:-}
|
||||||
- CRM_BASE_URL=${CRM_BASE_URL:-}
|
- CRM_BASE_URL=${CRM_BASE_URL:-}
|
||||||
- CRM_USERNAME=${CRM_USERNAME:-}
|
|
||||||
- CRM_PASSWORD=${CRM_PASSWORD:-}
|
|
||||||
networks:
|
networks:
|
||||||
- web
|
- web
|
||||||
|
|
||||||
|
|||||||
@@ -2,4 +2,4 @@ django>=5.1,<5.3
|
|||||||
django-ninja>=1.7,<2.0
|
django-ninja>=1.7,<2.0
|
||||||
gunicorn>=22.0,<24.0
|
gunicorn>=22.0,<24.0
|
||||||
whitenoise>=6.7,<7.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
|
||||||
|
|||||||
101
slips/api.py
101
slips/api.py
@@ -4,11 +4,16 @@ from django.shortcuts import get_object_or_404
|
|||||||
from django.utils import timezone
|
from django.utils import timezone
|
||||||
from ninja import NinjaAPI, Query
|
from ninja import NinjaAPI, Query
|
||||||
|
|
||||||
from .crm_orders import CrmOrdersError, recent_customer_orders
|
from .crm_orders import (
|
||||||
|
SESSION_TTL_SECONDS,
|
||||||
|
CrmAuthError,
|
||||||
|
CrmOrdersError,
|
||||||
|
recent_customer_orders,
|
||||||
|
)
|
||||||
from .models import Product, Order, clean_custom_labels
|
from .models import Product, Order, clean_custom_labels
|
||||||
from .schemas import (
|
from .schemas import (
|
||||||
ProductOut, ProductIn, OrderOut, OrderIn, OrderUpdateIn,
|
ProductOut, ProductIn, OrderOut, OrderIn, OrderUpdateIn,
|
||||||
CalibrationIn, CalibrationOut, CrmOrdersOut,
|
CalibrationIn, CalibrationOut, CrmLoginIn, CrmOrdersOut,
|
||||||
)
|
)
|
||||||
from .calibration import load_calibration, save_calibration, DEFAULTS, for_api
|
from .calibration import load_calibration, save_calibration, DEFAULTS, for_api
|
||||||
|
|
||||||
@@ -155,13 +160,99 @@ def delete_order(request, order_id: int):
|
|||||||
return 204, None
|
return 204, None
|
||||||
|
|
||||||
|
|
||||||
@api.get('/crm-orders', response={200: CrmOrdersOut, 502: dict}, tags=['Orders'])
|
_SG_USER = 'sg_username'
|
||||||
|
_SG_PASS = 'sg_password'
|
||||||
|
_SG_COOKIES = 'sg_cookies'
|
||||||
|
|
||||||
|
|
||||||
|
def _session_credentials(request):
|
||||||
|
username = (request.session.get(_SG_USER) or '').strip()
|
||||||
|
password = request.session.get(_SG_PASS) or ''
|
||||||
|
if not username or not password:
|
||||||
|
return None
|
||||||
|
return 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, cookies=None):
|
||||||
|
data = recent_customer_orders(username, password, cookies=cookies)
|
||||||
|
saved = data.pop('cookies', None)
|
||||||
|
data['username'] = username
|
||||||
|
return data, saved
|
||||||
|
|
||||||
|
|
||||||
|
@api.get('/crm-orders', response={200: CrmOrdersOut, 401: dict, 502: dict}, tags=['Orders'])
|
||||||
def list_crm_orders(request):
|
def list_crm_orders(request):
|
||||||
"""Store delivery notes dated after REPORT_ORDERS_SINCE."""
|
"""Store delivery notes for the SystemGroup account saved in this session."""
|
||||||
|
creds = _session_credentials(request)
|
||||||
|
if creds is None:
|
||||||
|
return 401, {'detail': 'Sign in to SystemGroup.', 'code': 'login_required'}
|
||||||
|
username, password = creds
|
||||||
try:
|
try:
|
||||||
return recent_customer_orders()
|
data, cookies = _customer_orders(
|
||||||
|
username, password, _stored_cookies(request, username)
|
||||||
|
)
|
||||||
|
except CrmAuthError:
|
||||||
|
_forget_credentials(request)
|
||||||
|
return 401, {
|
||||||
|
'detail': 'SystemGroup rejected this username or password.',
|
||||||
|
'code': 'login_rejected',
|
||||||
|
}
|
||||||
except CrmOrdersError as exc:
|
except CrmOrdersError as exc:
|
||||||
return 502, {'detail': str(exc)}
|
return 502, {'detail': str(exc)}
|
||||||
|
_remember_credentials(request, username, password, cookies)
|
||||||
|
return data
|
||||||
|
|
||||||
|
|
||||||
|
@api.post(
|
||||||
|
'/crm-orders/session',
|
||||||
|
response={200: CrmOrdersOut, 400: dict, 401: dict, 502: dict},
|
||||||
|
tags=['Orders'],
|
||||||
|
)
|
||||||
|
def start_crm_session(request, payload: CrmLoginIn):
|
||||||
|
"""Check SystemGroup credentials, then keep them for 30 days."""
|
||||||
|
username = payload.username.strip()
|
||||||
|
password = payload.password
|
||||||
|
if not username or not password:
|
||||||
|
return 400, {'detail': 'Username and password are required.'}
|
||||||
|
try:
|
||||||
|
data, cookies = _customer_orders(username, password)
|
||||||
|
except CrmAuthError:
|
||||||
|
return 401, {
|
||||||
|
'detail': 'SystemGroup rejected this username or password.',
|
||||||
|
'code': 'login_rejected',
|
||||||
|
}
|
||||||
|
except CrmOrdersError as exc:
|
||||||
|
return 502, {'detail': str(exc)}
|
||||||
|
_remember_credentials(request, username, password, cookies)
|
||||||
|
return data
|
||||||
|
|
||||||
|
|
||||||
|
@api.delete('/crm-orders/session', response={204: None}, tags=['Orders'])
|
||||||
|
def end_crm_session(request):
|
||||||
|
_forget_credentials(request)
|
||||||
|
return 204, None
|
||||||
|
|
||||||
|
|
||||||
# ─── Calibration ─────────────────────────────────────────
|
# ─── Calibration ─────────────────────────────────────────
|
||||||
|
|||||||
@@ -2,10 +2,12 @@
|
|||||||
|
|
||||||
The cutoff in .env is a Gregorian date. Delivery-note dates on the report
|
The cutoff in .env is a Gregorian date. Delivery-note dates on the report
|
||||||
are Jalali, so the cutoff is converted before the comparison.
|
are Jalali, so the cutoff is converted before the comparison.
|
||||||
|
|
||||||
|
The host stays in .env. Username and password are supplied per request.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import os
|
import os
|
||||||
from datetime import date
|
from datetime import date, datetime, timedelta, timezone
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
_DIGIT_MAP = str.maketrans("۰۱۲۳۴۵۶۷۸۹٠١٢٣٤٥٦٧٨٩", "01234567890123456789")
|
_DIGIT_MAP = str.maketrans("۰۱۲۳۴۵۶۷۸۹٠١٢٣٤٥٦٧٨٩", "01234567890123456789")
|
||||||
@@ -18,6 +20,31 @@ class CrmOrdersError(RuntimeError):
|
|||||||
pass
|
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:
|
def parse_jalali(raw: str) -> tuple[int, int, int] | None:
|
||||||
text = (raw or "").translate(_DIGIT_MAP).strip().replace("-", "/")
|
text = (raw or "").translate(_DIGIT_MAP).strip().replace("-", "/")
|
||||||
bits = text.split("/")
|
bits = text.split("/")
|
||||||
@@ -164,9 +191,110 @@ def orders_after(lines, start: tuple[int, int, int]):
|
|||||||
return kept
|
return kept
|
||||||
|
|
||||||
|
|
||||||
def recent_customer_orders(client=None) -> dict:
|
# SgFilter operator and operand codes from SgFilter.js.
|
||||||
"""Fetch the store delivery-note report and keep rows after the cutoff."""
|
_OP_GREATER = 3
|
||||||
_day, start = orders_cutoff()
|
_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()
|
prefixes = code_prefixes()
|
||||||
try:
|
try:
|
||||||
from lithium_systemgroup import (
|
from lithium_systemgroup import (
|
||||||
@@ -180,13 +308,29 @@ def recent_customer_orders(client=None) -> dict:
|
|||||||
|
|
||||||
try:
|
try:
|
||||||
if client is None:
|
if client is None:
|
||||||
client = SystemGroupClient(prefer_report_env=True, timeout=30)
|
client = SystemGroupClient(
|
||||||
body, content_type = client.fetch_customer_orders()
|
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)
|
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)
|
||||||
|
if login_rejected(text):
|
||||||
|
raise CrmAuthError("SystemGroup rejected this username or password.") from exc
|
||||||
if text.startswith("Missing required env vars"):
|
if text.startswith("Missing required env vars"):
|
||||||
text = "Set REPORT_BASE_URL, REPORT_USERNAME, and REPORT_PASSWORD."
|
text = "Set REPORT_BASE_URL."
|
||||||
raise CrmOrdersError(text) from exc
|
raise CrmOrdersError(text) from exc
|
||||||
|
|
||||||
kept = [
|
kept = [
|
||||||
@@ -201,4 +345,5 @@ def recent_customer_orders(client=None) -> dict:
|
|||||||
return {
|
return {
|
||||||
"since": format_jalali(start),
|
"since": format_jalali(start),
|
||||||
"orders": orders,
|
"orders": orders,
|
||||||
|
"cookies": _cookie_dump(client),
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -114,6 +114,12 @@ class CrmOrderOut(Schema):
|
|||||||
notes: str
|
notes: str
|
||||||
|
|
||||||
|
|
||||||
|
class CrmLoginIn(Schema):
|
||||||
|
username: str
|
||||||
|
password: str
|
||||||
|
|
||||||
|
|
||||||
class CrmOrdersOut(Schema):
|
class CrmOrdersOut(Schema):
|
||||||
since: str
|
since: str
|
||||||
|
username: str
|
||||||
orders: List[CrmOrderOut]
|
orders: List[CrmOrderOut]
|
||||||
|
|||||||
@@ -401,6 +401,86 @@ form {
|
|||||||
padding-right: 0;
|
padding-right: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#crm-login {
|
||||||
|
max-width: 22rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* .form-stack { display: flex } would otherwise override the hidden attribute. */
|
||||||
|
#crm-login[hidden] {
|
||||||
|
display: none !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
#crm-filters {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(4, minmax(0, 1fr));
|
||||||
|
gap: 1rem;
|
||||||
|
padding: 1rem 1.5rem;
|
||||||
|
border-bottom: 1px solid var(--border);
|
||||||
|
}
|
||||||
|
|
||||||
|
#crm-filters[hidden] {
|
||||||
|
display: none !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 1100px) {
|
||||||
|
#crm-filters {
|
||||||
|
grid-template-columns: 1fr 1fr;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 700px) {
|
||||||
|
#crm-filters {
|
||||||
|
grid-template-columns: 1fr;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
jdp-container {
|
||||||
|
--jdp-primary: var(--accent);
|
||||||
|
font-family: inherit;
|
||||||
|
}
|
||||||
|
|
||||||
|
.suggest {
|
||||||
|
position: relative;
|
||||||
|
z-index: 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
.suggest-list {
|
||||||
|
position: absolute;
|
||||||
|
z-index: 3;
|
||||||
|
inset-inline: 0;
|
||||||
|
top: calc(100% + 0.25rem);
|
||||||
|
margin: 0;
|
||||||
|
padding: 0.25rem 0;
|
||||||
|
list-style: none;
|
||||||
|
background: var(--bg-secondary);
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: 6px;
|
||||||
|
max-height: 12rem;
|
||||||
|
overflow: auto;
|
||||||
|
box-shadow: 0 8px 24px var(--shadow);
|
||||||
|
}
|
||||||
|
|
||||||
|
.suggest-list[hidden] {
|
||||||
|
display: none !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
.suggest-list button {
|
||||||
|
display: block;
|
||||||
|
width: 100%;
|
||||||
|
text-align: start;
|
||||||
|
background: none;
|
||||||
|
border: 0;
|
||||||
|
color: inherit;
|
||||||
|
font: inherit;
|
||||||
|
padding: 0.5rem 0.75rem;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
|
||||||
|
.suggest-list button:hover,
|
||||||
|
.suggest-list button[aria-selected="true"] {
|
||||||
|
background: var(--bg-hover);
|
||||||
|
}
|
||||||
|
|
||||||
#add-custom-line {
|
#add-custom-line {
|
||||||
align-self: flex-start;
|
align-self: flex-start;
|
||||||
}
|
}
|
||||||
@@ -680,6 +760,13 @@ button.badge:hover {
|
|||||||
color: var(--text-primary);
|
color: var(--text-primary);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.data-table tr.subtotal-row td {
|
||||||
|
background: color-mix(in srgb, var(--bg-muted) 55%, transparent);
|
||||||
|
font-weight: 600;
|
||||||
|
color: var(--text-secondary);
|
||||||
|
border-top: 1px solid var(--border);
|
||||||
|
}
|
||||||
|
|
||||||
a.code-link {
|
a.code-link {
|
||||||
color: var(--accent);
|
color: var(--accent);
|
||||||
font-weight: 600;
|
font-weight: 600;
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
const seenOrderKeys = new Set();
|
const seenOrderKeys = new Set();
|
||||||
let ordersLoaded = false;
|
let ordersLoaded = false;
|
||||||
let lastSince = '';
|
let lastSince = '';
|
||||||
|
let lastUsername = '';
|
||||||
let lastRows = null;
|
let lastRows = null;
|
||||||
let productCodes = new Set();
|
let productCodes = new Set();
|
||||||
|
|
||||||
@@ -19,10 +20,68 @@ function dateKey(raw) {
|
|||||||
return (+match[1]) * 10000 + (+match[2]) * 100 + (+match[3]);
|
return (+match[1]) * 10000 + (+match[2]) * 100 + (+match[3]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function companyName(row) {
|
||||||
|
return (row.customer_name || '').trim() || '—';
|
||||||
|
}
|
||||||
|
|
||||||
|
function rowMatches(row, companyQuery, codeQuery, start, end) {
|
||||||
|
const company = companyQuery.trim().toLocaleLowerCase();
|
||||||
|
const code = codeQuery.trim().toLocaleLowerCase();
|
||||||
|
const name = companyName(row).toLocaleLowerCase();
|
||||||
|
const product = (row.product_code || '').trim().toLocaleLowerCase();
|
||||||
|
if (company && !name.includes(company)) return false;
|
||||||
|
if (code && !product.includes(code)) return false;
|
||||||
|
const startKey = dateKey(start);
|
||||||
|
const endKey = dateKey(end);
|
||||||
|
if (!startKey && !endKey) return true;
|
||||||
|
const rowDate = dateKey(row.delivery_note_date);
|
||||||
|
if (!rowDate) return false;
|
||||||
|
if (startKey && rowDate < startKey) return false;
|
||||||
|
if (endKey && rowDate > endKey) return false;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
function filteredRows() {
|
||||||
|
const company = document.getElementById('crm-company').value;
|
||||||
|
const code = document.getElementById('crm-code').value;
|
||||||
|
const start = document.getElementById('crm-start').value;
|
||||||
|
const end = document.getElementById('crm-end').value;
|
||||||
|
return (lastRows || []).filter((row) => rowMatches(row, company, code, start, end));
|
||||||
|
}
|
||||||
|
|
||||||
|
function suggestionValues(values, query) {
|
||||||
|
const q = query.trim().toLocaleLowerCase();
|
||||||
|
const unique = [...new Set(values.map((value) => (value || '').trim()).filter(Boolean))];
|
||||||
|
unique.sort((a, b) => a.localeCompare(b, 'fa'));
|
||||||
|
const matched = q ? unique.filter((value) => value.toLocaleLowerCase().includes(q)) : unique;
|
||||||
|
// ponytail: first 8 matches; raise the cap if a list is routinely longer
|
||||||
|
return matched.slice(0, 8);
|
||||||
|
}
|
||||||
|
|
||||||
|
function checkRowMatches() {
|
||||||
|
const row = { customer_name: 'شرکت آلفا', product_code: 'PR-10', delivery_note_date: '1403/08/15' };
|
||||||
|
console.assert(rowMatches(row, 'آلفا', '', '', ''), 'company');
|
||||||
|
console.assert(rowMatches(row, '', 'pr-10', '', ''), 'code');
|
||||||
|
console.assert(!rowMatches(row, 'بتا', '', '', ''), 'other company');
|
||||||
|
console.assert(!rowMatches(row, 'آلفا', 'zz', '', ''), 'both');
|
||||||
|
console.assert(rowMatches({ customer_name: ' ', product_code: 'A', delivery_note_date: '1403/01/01' }, '—', '', '', ''), 'blank company');
|
||||||
|
console.assert(suggestionValues(['شرکت بتا', 'شرکت آلفا', 'شرکت آلفا'], 'آلفا').join() === 'شرکت آلفا', 'suggest');
|
||||||
|
console.assert(rowMatches(row, '', '', '1403/08/15', ''), 'on start');
|
||||||
|
console.assert(rowMatches(row, '', '', '1403/08/01', '1403/08/20'), 'in range');
|
||||||
|
console.assert(!rowMatches(row, '', '', '1403/08/16', ''), 'before start');
|
||||||
|
console.assert(!rowMatches(row, '', '', '', '1403/08/14'), 'after end');
|
||||||
|
const totals = qtyTotals([
|
||||||
|
{ note_quantity: '10', delivered_quantity: '4', remaining_quantity: '6' },
|
||||||
|
{ note_quantity: '2.5', delivered_quantity: '0', remaining_quantity: '2.5' },
|
||||||
|
]);
|
||||||
|
console.assert(totals.note === 12.5 && totals.delivered === 4 && totals.remaining === 8.5, 'qty totals');
|
||||||
|
console.assert(formatQty(12.5) === '12.5' && formatQty(4) === '4', 'format qty');
|
||||||
|
}
|
||||||
|
|
||||||
function groupedRows(rows) {
|
function groupedRows(rows) {
|
||||||
const groups = new Map();
|
const groups = new Map();
|
||||||
rows.forEach((row) => {
|
rows.forEach((row) => {
|
||||||
const name = (row.customer_name || '').trim() || '—';
|
const name = companyName(row);
|
||||||
if (!groups.has(name)) groups.set(name, []);
|
if (!groups.has(name)) groups.set(name, []);
|
||||||
groups.get(name).push(row);
|
groups.get(name).push(row);
|
||||||
});
|
});
|
||||||
@@ -34,6 +93,27 @@ function groupedRows(rows) {
|
|||||||
return list;
|
return list;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function parseQty(raw) {
|
||||||
|
const n = Number(String(raw || '').trim().replace(/,/g, ''));
|
||||||
|
return Number.isFinite(n) ? n : 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatQty(n) {
|
||||||
|
if (!Number.isFinite(n)) return '';
|
||||||
|
return Number.isInteger(n) ? String(n) : String(parseFloat(n.toFixed(6)));
|
||||||
|
}
|
||||||
|
|
||||||
|
function qtyTotals(items) {
|
||||||
|
return items.reduce(
|
||||||
|
(sum, row) => ({
|
||||||
|
note: sum.note + parseQty(row.note_quantity),
|
||||||
|
delivered: sum.delivered + parseQty(row.delivered_quantity),
|
||||||
|
remaining: sum.remaining + parseQty(row.remaining_quantity),
|
||||||
|
}),
|
||||||
|
{ note: 0, delivered: 0, remaining: 0 },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
function cell(text, className, ltr) {
|
function cell(text, className, ltr) {
|
||||||
const td = document.createElement('td');
|
const td = document.createElement('td');
|
||||||
if (className) td.className = className;
|
if (className) td.className = className;
|
||||||
@@ -59,22 +139,53 @@ function codeCell(row) {
|
|||||||
return td;
|
return td;
|
||||||
}
|
}
|
||||||
|
|
||||||
function renderSince() {
|
function syncDateDefaults() {
|
||||||
const wrap = document.getElementById('crm-since');
|
const start = document.getElementById('crm-start');
|
||||||
const el = document.getElementById('crm-since-date');
|
if (!start) return;
|
||||||
if (!wrap || !el) return;
|
if (!start.value.trim() && lastSince) start.value = lastSince;
|
||||||
if (!lastSince) {
|
}
|
||||||
wrap.hidden = true;
|
|
||||||
el.textContent = '';
|
function loginForm() {
|
||||||
return;
|
return document.getElementById('crm-login');
|
||||||
}
|
}
|
||||||
wrap.hidden = false;
|
|
||||||
el.textContent = lastSince;
|
function showLogin() {
|
||||||
|
loginForm().hidden = false;
|
||||||
|
document.getElementById('crm-refresh').hidden = true;
|
||||||
|
document.getElementById('crm-forget').hidden = true;
|
||||||
|
document.getElementById('crm-account').hidden = true;
|
||||||
|
document.getElementById('crm-count').hidden = true;
|
||||||
|
lastRows = null;
|
||||||
|
lastUsername = '';
|
||||||
|
ordersLoaded = false;
|
||||||
|
const filters = document.getElementById('crm-filters');
|
||||||
|
if (filters) filters.hidden = true;
|
||||||
|
const company = document.getElementById('crm-company');
|
||||||
|
const code = document.getElementById('crm-code');
|
||||||
|
const start = document.getElementById('crm-start');
|
||||||
|
const end = document.getElementById('crm-end');
|
||||||
|
if (company) company.value = '';
|
||||||
|
if (code) code.value = '';
|
||||||
|
if (start) start.value = '';
|
||||||
|
if (end) end.value = '';
|
||||||
|
}
|
||||||
|
|
||||||
|
function showSession() {
|
||||||
|
loginForm().hidden = true;
|
||||||
|
document.getElementById('crm-password').value = '';
|
||||||
|
document.getElementById('crm-refresh').hidden = false;
|
||||||
|
document.getElementById('crm-forget').hidden = false;
|
||||||
|
document.getElementById('crm-count').hidden = false;
|
||||||
|
const account = document.getElementById('crm-account');
|
||||||
|
account.hidden = !lastUsername;
|
||||||
|
account.textContent = lastUsername ? `${t('sg_signed_in')} ${lastUsername}` : '';
|
||||||
}
|
}
|
||||||
|
|
||||||
function renderChrome() {
|
function renderChrome() {
|
||||||
renderSince();
|
if (!loginForm().hidden) setStatus(t('sg_need_login'));
|
||||||
if (lastRows) renderOrders(lastRows, false);
|
if (lastUsername) showSession();
|
||||||
|
syncDateDefaults();
|
||||||
|
if (lastRows) renderOrders(filteredRows(), false);
|
||||||
}
|
}
|
||||||
|
|
||||||
function renderOrders(rows, markNew) {
|
function renderOrders(rows, markNew) {
|
||||||
@@ -83,9 +194,10 @@ function renderOrders(rows, markNew) {
|
|||||||
const status = document.getElementById('crm-orders-status');
|
const status = document.getElementById('crm-orders-status');
|
||||||
body.replaceChildren();
|
body.replaceChildren();
|
||||||
count.textContent = String(rows.length);
|
count.textContent = String(rows.length);
|
||||||
|
document.getElementById('crm-filters').hidden = !(lastRows && lastRows.length);
|
||||||
if (!rows.length) {
|
if (!rows.length) {
|
||||||
status.hidden = false;
|
status.hidden = false;
|
||||||
status.textContent = t('no_crm_orders');
|
status.textContent = lastRows && lastRows.length ? t('no_crm_matches') : t('no_crm_orders');
|
||||||
document.getElementById('crm-orders-table').hidden = true;
|
document.getElementById('crm-orders-table').hidden = true;
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
@@ -119,6 +231,19 @@ function renderOrders(rows, markNew) {
|
|||||||
body.appendChild(tr);
|
body.appendChild(tr);
|
||||||
seenOrderKeys.add(key);
|
seenOrderKeys.add(key);
|
||||||
});
|
});
|
||||||
|
const totals = qtyTotals(items);
|
||||||
|
const foot = document.createElement('tr');
|
||||||
|
foot.className = 'subtotal-row';
|
||||||
|
const totalLabel = document.createElement('td');
|
||||||
|
totalLabel.colSpan = 3;
|
||||||
|
totalLabel.textContent = t('subtotal');
|
||||||
|
foot.append(
|
||||||
|
totalLabel,
|
||||||
|
cell(formatQty(totals.note), 'mono'),
|
||||||
|
cell(formatQty(totals.delivered), 'mono'),
|
||||||
|
cell(formatQty(totals.remaining), 'mono'),
|
||||||
|
);
|
||||||
|
body.appendChild(foot);
|
||||||
});
|
});
|
||||||
return added;
|
return added;
|
||||||
}
|
}
|
||||||
@@ -138,20 +263,24 @@ function setStatus(message) {
|
|||||||
status.textContent = message;
|
status.textContent = message;
|
||||||
}
|
}
|
||||||
|
|
||||||
async function loadCrmOrders() {
|
async function fetchProducts() {
|
||||||
const button = document.getElementById('crm-refresh');
|
const res = await fetch('/api/products');
|
||||||
button.disabled = true;
|
if (!res.ok) return;
|
||||||
if (!ordersLoaded) setStatus(t('crm_loading'));
|
const products = await res.json().catch(() => []);
|
||||||
try {
|
|
||||||
const [ordersRes, productsRes] = await Promise.all([
|
|
||||||
fetch('/api/crm-orders', { cache: 'no-store' }),
|
|
||||||
fetch('/api/products'),
|
|
||||||
]);
|
|
||||||
if (productsRes.ok) {
|
|
||||||
const products = await productsRes.json().catch(() => []);
|
|
||||||
productCodes = new Set((products || []).map((p) => (p.code || '').trim()));
|
productCodes = new Set((products || []).map((p) => (p.code || '').trim()));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function applyOrdersResponse(ordersRes) {
|
||||||
const data = await ordersRes.json().catch(() => ({}));
|
const data = await ordersRes.json().catch(() => ({}));
|
||||||
|
if (ordersRes.status === 401) {
|
||||||
|
const rejected = data.code === 'login_rejected';
|
||||||
|
seenOrderKeys.clear();
|
||||||
|
lastSince = '';
|
||||||
|
showLogin();
|
||||||
|
setStatus(t('sg_need_login'));
|
||||||
|
if (rejected) showToast(t('sg_rejected'), true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
if (!ordersRes.ok) {
|
if (!ordersRes.ok) {
|
||||||
const message = data.detail || t('no_crm_orders');
|
const message = data.detail || t('no_crm_orders');
|
||||||
if (!ordersLoaded) setStatus(message);
|
if (!ordersLoaded) setStatus(message);
|
||||||
@@ -159,11 +288,25 @@ async function loadCrmOrders() {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
lastSince = data.since || '';
|
lastSince = data.since || '';
|
||||||
|
lastUsername = data.username || '';
|
||||||
lastRows = data.orders || [];
|
lastRows = data.orders || [];
|
||||||
renderSince();
|
showSession();
|
||||||
const added = renderOrders(lastRows, ordersLoaded);
|
syncDateDefaults();
|
||||||
|
const added = renderOrders(filteredRows(), ordersLoaded);
|
||||||
ordersLoaded = true;
|
ordersLoaded = true;
|
||||||
if (added > 0) showToast(t('crm_new'));
|
if (added > 0) showToast(t('crm_new'));
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadCrmOrders() {
|
||||||
|
const button = document.getElementById('crm-refresh');
|
||||||
|
button.disabled = true;
|
||||||
|
if (!ordersLoaded) setStatus(t('crm_loading'));
|
||||||
|
try {
|
||||||
|
const [ordersRes] = await Promise.all([
|
||||||
|
fetch('/api/crm-orders', { cache: 'no-store' }),
|
||||||
|
fetchProducts(),
|
||||||
|
]);
|
||||||
|
await applyOrdersResponse(ordersRes);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
setStatus(t('no_crm_orders'));
|
setStatus(t('no_crm_orders'));
|
||||||
showToast('Network error', true);
|
showToast('Network error', true);
|
||||||
@@ -172,9 +315,146 @@ async function loadCrmOrders() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function signIn(event) {
|
||||||
|
event.preventDefault();
|
||||||
|
const button = document.getElementById('crm-sign-in');
|
||||||
|
button.disabled = true;
|
||||||
|
setStatus(t('crm_loading'));
|
||||||
|
try {
|
||||||
|
const [ordersRes] = await Promise.all([
|
||||||
|
fetch('/api/crm-orders/session', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
cache: 'no-store',
|
||||||
|
body: JSON.stringify({
|
||||||
|
username: document.getElementById('crm-username').value.trim(),
|
||||||
|
password: document.getElementById('crm-password').value,
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
fetchProducts(),
|
||||||
|
]);
|
||||||
|
await applyOrdersResponse(ordersRes);
|
||||||
|
} catch (err) {
|
||||||
|
setStatus(t('sg_need_login'));
|
||||||
|
showToast('Network error', true);
|
||||||
|
} finally {
|
||||||
|
button.disabled = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function signOut() {
|
||||||
|
const button = document.getElementById('crm-forget');
|
||||||
|
button.disabled = true;
|
||||||
|
try {
|
||||||
|
const res = await fetch('/api/crm-orders/session', { method: 'DELETE' });
|
||||||
|
if (!res.ok) {
|
||||||
|
showToast('Network error', true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
seenOrderKeys.clear();
|
||||||
|
lastSince = '';
|
||||||
|
showLogin();
|
||||||
|
setStatus(t('sg_need_login'));
|
||||||
|
} catch (err) {
|
||||||
|
showToast('Network error', true);
|
||||||
|
} finally {
|
||||||
|
button.disabled = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function applyFilter() {
|
||||||
|
if (lastRows) renderOrders(filteredRows(), false);
|
||||||
|
}
|
||||||
|
|
||||||
|
function bindSuggest(inputId, listId, valuesFn) {
|
||||||
|
const input = document.getElementById(inputId);
|
||||||
|
const list = document.getElementById(listId);
|
||||||
|
|
||||||
|
function close() {
|
||||||
|
list.hidden = true;
|
||||||
|
list.replaceChildren();
|
||||||
|
input.setAttribute('aria-expanded', 'false');
|
||||||
|
}
|
||||||
|
|
||||||
|
function choose(value) {
|
||||||
|
input.value = value;
|
||||||
|
close();
|
||||||
|
applyFilter();
|
||||||
|
}
|
||||||
|
|
||||||
|
function open() {
|
||||||
|
const items = suggestionValues(valuesFn(), input.value);
|
||||||
|
list.replaceChildren(...items.map((value) => {
|
||||||
|
const li = document.createElement('li');
|
||||||
|
const button = document.createElement('button');
|
||||||
|
button.type = 'button';
|
||||||
|
button.textContent = value;
|
||||||
|
button.setAttribute('role', 'option');
|
||||||
|
button.addEventListener('mousedown', (event) => {
|
||||||
|
event.preventDefault();
|
||||||
|
choose(value);
|
||||||
|
});
|
||||||
|
li.appendChild(button);
|
||||||
|
return li;
|
||||||
|
}));
|
||||||
|
const show = items.length > 0 && document.activeElement === input;
|
||||||
|
list.hidden = !show;
|
||||||
|
input.setAttribute('aria-expanded', show ? 'true' : 'false');
|
||||||
|
}
|
||||||
|
|
||||||
|
input.addEventListener('input', () => {
|
||||||
|
applyFilter();
|
||||||
|
open();
|
||||||
|
});
|
||||||
|
input.addEventListener('focus', open);
|
||||||
|
input.addEventListener('blur', close);
|
||||||
|
input.addEventListener('keydown', (event) => {
|
||||||
|
if (event.key === 'Escape') {
|
||||||
|
close();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (event.key !== 'ArrowDown' && event.key !== 'ArrowUp' && event.key !== 'Enter') return;
|
||||||
|
if (list.hidden) open();
|
||||||
|
const buttons = [...list.querySelectorAll('button')];
|
||||||
|
if (!buttons.length) return;
|
||||||
|
event.preventDefault();
|
||||||
|
const current = buttons.findIndex((button) => button.getAttribute('aria-selected') === 'true');
|
||||||
|
if (event.key === 'Enter') {
|
||||||
|
if (current >= 0) choose(buttons[current].textContent);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const step = event.key === 'ArrowDown' ? 1 : -1;
|
||||||
|
const nextIndex = current < 0 ? (step > 0 ? 0 : buttons.length - 1) : (current + step + buttons.length) % buttons.length;
|
||||||
|
const next = buttons[nextIndex];
|
||||||
|
buttons.forEach((button) => button.removeAttribute('aria-selected'));
|
||||||
|
next.setAttribute('aria-selected', 'true');
|
||||||
|
next.scrollIntoView({ block: 'nearest' });
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
document.addEventListener('DOMContentLoaded', () => {
|
document.addEventListener('DOMContentLoaded', () => {
|
||||||
document.getElementById('crm-refresh').addEventListener('click', loadCrmOrders);
|
document.getElementById('crm-refresh').addEventListener('click', loadCrmOrders);
|
||||||
|
document.getElementById('crm-forget').addEventListener('click', signOut);
|
||||||
|
['crm-start', 'crm-end'].forEach((id) => {
|
||||||
|
const input = document.getElementById(id);
|
||||||
|
input.addEventListener('input', applyFilter);
|
||||||
|
input.addEventListener('jdp:change', applyFilter);
|
||||||
|
});
|
||||||
|
if (window.jalaliDatepicker) {
|
||||||
|
jalaliDatepicker.startWatch({
|
||||||
|
selector: '#crm-filters input[data-jdp]',
|
||||||
|
autoReadOnlyInput: false,
|
||||||
|
showCloseBtn: true,
|
||||||
|
time: false,
|
||||||
|
zIndex: 200,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
bindSuggest('crm-company', 'crm-company-list', () => (lastRows || []).map(companyName));
|
||||||
|
bindSuggest('crm-code', 'crm-code-list', () => (lastRows || []).map((row) => row.product_code));
|
||||||
|
loginForm().addEventListener('submit', signIn);
|
||||||
loadCrmOrders();
|
loadCrmOrders();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
checkRowMatches();
|
||||||
|
|
||||||
document.addEventListener('slip-language', renderChrome);
|
document.addEventListener('slip-language', renderChrome);
|
||||||
|
|||||||
@@ -51,14 +51,26 @@ const translations = {
|
|||||||
'crm_orders_title': 'Orders',
|
'crm_orders_title': 'Orders',
|
||||||
'refresh': 'Refresh',
|
'refresh': 'Refresh',
|
||||||
'customer': 'Customer',
|
'customer': 'Customer',
|
||||||
|
'company_name': 'Company name',
|
||||||
'delivery_note': 'Note #',
|
'delivery_note': 'Note #',
|
||||||
'note_qty': 'Ordered',
|
'note_qty': 'Ordered',
|
||||||
'delivered_qty': 'Delivered',
|
'delivered_qty': 'Delivered',
|
||||||
'remaining_qty': 'Remaining',
|
'remaining_qty': 'Remaining',
|
||||||
'product_title': 'Title',
|
'product_title': 'Title',
|
||||||
|
'subtotal': 'Subtotal',
|
||||||
'crm_loading': 'Loading orders…',
|
'crm_loading': 'Loading orders…',
|
||||||
|
'sg_username': 'Username',
|
||||||
|
'sg_password': 'Password',
|
||||||
|
'sg_sign_in': 'Sign in',
|
||||||
|
'sg_sign_out': 'Sign out',
|
||||||
|
'sg_signed_in': 'Signed in as',
|
||||||
|
'sg_need_login': 'Sign in to load orders.',
|
||||||
|
'sg_rejected': 'SystemGroup rejected this username or password.',
|
||||||
'no_crm_orders': 'No orders after this date',
|
'no_crm_orders': 'No orders after this date',
|
||||||
|
'no_crm_matches': 'No orders match this search',
|
||||||
'orders_after': 'Orders after',
|
'orders_after': 'Orders after',
|
||||||
|
'start_date': 'From date',
|
||||||
|
'end_date': 'To date',
|
||||||
'crm_new': 'New orders added',
|
'crm_new': 'New orders added',
|
||||||
'status': 'Status',
|
'status': 'Status',
|
||||||
'no_orders': 'No orders yet',
|
'no_orders': 'No orders yet',
|
||||||
@@ -123,14 +135,26 @@ const translations = {
|
|||||||
'crm_orders_title': 'حوالهها',
|
'crm_orders_title': 'حوالهها',
|
||||||
'refresh': 'بهروزرسانی',
|
'refresh': 'بهروزرسانی',
|
||||||
'customer': 'مشتری',
|
'customer': 'مشتری',
|
||||||
|
'company_name': 'نام شرکت',
|
||||||
'delivery_note': 'شماره حواله',
|
'delivery_note': 'شماره حواله',
|
||||||
'note_qty': 'مقدار حواله',
|
'note_qty': 'مقدار حواله',
|
||||||
'delivered_qty': 'تحویلشده',
|
'delivered_qty': 'تحویلشده',
|
||||||
'remaining_qty': 'مانده',
|
'remaining_qty': 'مانده',
|
||||||
'product_title': 'عنوان',
|
'product_title': 'عنوان',
|
||||||
|
'subtotal': 'جمع',
|
||||||
'crm_loading': 'در حال دریافت سفارشها…',
|
'crm_loading': 'در حال دریافت سفارشها…',
|
||||||
|
'sg_username': 'نام کاربری',
|
||||||
|
'sg_password': 'رمز عبور',
|
||||||
|
'sg_sign_in': 'ورود',
|
||||||
|
'sg_sign_out': 'خروج',
|
||||||
|
'sg_signed_in': 'کاربر',
|
||||||
|
'sg_need_login': 'برای دیدن حوالهها وارد شوید.',
|
||||||
|
'sg_rejected': 'نام کاربری یا رمز سامانه گروه نادرست است.',
|
||||||
'no_crm_orders': 'سفارشی بعد از این تاریخ نیست',
|
'no_crm_orders': 'سفارشی بعد از این تاریخ نیست',
|
||||||
|
'no_crm_matches': 'حوالهای با این جستجو پیدا نشد',
|
||||||
'orders_after': 'حوالههای بعد از',
|
'orders_after': 'حوالههای بعد از',
|
||||||
|
'start_date': 'از تاریخ',
|
||||||
|
'end_date': 'تا تاریخ',
|
||||||
'crm_new': 'سفارش جدید اضافه شد',
|
'crm_new': 'سفارش جدید اضافه شد',
|
||||||
'status': 'وضعیت',
|
'status': 'وضعیت',
|
||||||
'no_orders': 'سفارشی ثبت نشده',
|
'no_orders': 'سفارشی ثبت نشده',
|
||||||
|
|||||||
1
slips/static/slips/vendor/jalalidatepicker/VERSION.txt
vendored
Normal file
1
slips/static/slips/vendor/jalalidatepicker/VERSION.txt
vendored
Normal file
@@ -0,0 +1 @@
|
|||||||
|
/* vendored @majidh1/jalalidatepicker@1.0.0 — https://github.com/majidh1/JalaliDatePicker */
|
||||||
1
slips/static/slips/vendor/jalalidatepicker/jalalidatepicker.min.css
vendored
Normal file
1
slips/static/slips/vendor/jalalidatepicker/jalalidatepicker.min.css
vendored
Normal file
File diff suppressed because one or more lines are too long
1
slips/static/slips/vendor/jalalidatepicker/jalalidatepicker.min.js
vendored
Normal file
1
slips/static/slips/vendor/jalalidatepicker/jalalidatepicker.min.js
vendored
Normal file
File diff suppressed because one or more lines are too long
@@ -10,7 +10,7 @@
|
|||||||
<link rel="preconnect" href="https://fonts.googleapis.com">
|
<link rel="preconnect" href="https://fonts.googleapis.com">
|
||||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||||
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=JetBrains+Mono:wght@400;600&family=Vazirmatn:wght@300;400;500;600;700&display=swap" rel="stylesheet">
|
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=JetBrains+Mono:wght@400;600&family=Vazirmatn:wght@300;400;500;600;700&display=swap" rel="stylesheet">
|
||||||
<link rel="stylesheet" href="{% static 'slips/css/style.css' %}">
|
<link rel="stylesheet" href="{% static 'slips/css/style.css' %}?v=6">
|
||||||
<script>
|
<script>
|
||||||
(function () {
|
(function () {
|
||||||
var t = localStorage.getItem('slip_theme') || 'light';
|
var t = localStorage.getItem('slip_theme') || 'light';
|
||||||
@@ -56,7 +56,7 @@
|
|||||||
{% block content %}{% endblock %}
|
{% block content %}{% endblock %}
|
||||||
</main>
|
</main>
|
||||||
|
|
||||||
<script src="{% static 'slips/js/i18n.js' %}?v=3"></script>
|
<script src="{% static 'slips/js/i18n.js' %}?v=6"></script>
|
||||||
{% block extra_scripts %}{% endblock %}
|
{% block extra_scripts %}{% endblock %}
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -10,14 +10,47 @@
|
|||||||
<div class="card-header card-header-wrap">
|
<div class="card-header card-header-wrap">
|
||||||
<div>
|
<div>
|
||||||
<h2 class="card-title" data-i18n="crm_orders_title">حوالهها</h2>
|
<h2 class="card-title" data-i18n="crm_orders_title">حوالهها</h2>
|
||||||
<p class="card-subtitle" id="crm-since" hidden>
|
|
||||||
<span data-i18n="orders_after">حوالههای بعد از</span>
|
|
||||||
<span id="crm-since-date" class="mono" dir="ltr"></span>
|
|
||||||
</p>
|
|
||||||
</div>
|
</div>
|
||||||
<div class="card-actions">
|
<div class="card-actions">
|
||||||
<button type="button" class="btn btn-ghost btn-sm" id="crm-refresh" data-i18n="refresh">بهروزرسانی</button>
|
<span id="crm-account" class="card-subtitle" hidden></span>
|
||||||
<span class="card-badge badge-muted" id="crm-count">0</span>
|
<button type="button" class="btn btn-ghost btn-sm" id="crm-forget" data-i18n="sg_sign_out" hidden>خروج</button>
|
||||||
|
<button type="button" class="btn btn-ghost btn-sm" id="crm-refresh" data-i18n="refresh" hidden>بهروزرسانی</button>
|
||||||
|
<span class="card-badge badge-muted" id="crm-count" hidden>0</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<form id="crm-login" class="form-stack" hidden>
|
||||||
|
<div class="form-group">
|
||||||
|
<label for="crm-username" data-i18n="sg_username">نام کاربری</label>
|
||||||
|
<input id="crm-username" name="username" autocomplete="username" required>
|
||||||
|
</div>
|
||||||
|
<div class="form-group">
|
||||||
|
<label for="crm-password" data-i18n="sg_password">رمز عبور</label>
|
||||||
|
<input id="crm-password" name="password" type="password" autocomplete="current-password" required>
|
||||||
|
</div>
|
||||||
|
<button type="submit" class="btn btn-accent" id="crm-sign-in" data-i18n="sg_sign_in">ورود</button>
|
||||||
|
</form>
|
||||||
|
<div id="crm-filters" hidden>
|
||||||
|
<div class="form-group">
|
||||||
|
<label for="crm-start" data-i18n="start_date">از تاریخ</label>
|
||||||
|
<input id="crm-start" class="mono" type="text" data-jdp dir="ltr" inputmode="numeric" placeholder="YYYY/MM/DD" autocomplete="off">
|
||||||
|
</div>
|
||||||
|
<div class="form-group">
|
||||||
|
<label for="crm-end" data-i18n="end_date">تا تاریخ</label>
|
||||||
|
<input id="crm-end" class="mono" type="text" data-jdp dir="ltr" inputmode="numeric" placeholder="YYYY/MM/DD" autocomplete="off">
|
||||||
|
</div>
|
||||||
|
<div class="form-group">
|
||||||
|
<label for="crm-company" data-i18n="company_name">نام شرکت</label>
|
||||||
|
<div class="suggest">
|
||||||
|
<input id="crm-company" type="search" autocomplete="off" role="combobox" aria-autocomplete="list" aria-expanded="false" aria-controls="crm-company-list">
|
||||||
|
<ul id="crm-company-list" class="suggest-list" role="listbox" hidden></ul>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="form-group">
|
||||||
|
<label for="crm-code" data-i18n="product_code">کد محصول</label>
|
||||||
|
<div class="suggest">
|
||||||
|
<input id="crm-code" type="search" dir="ltr" autocomplete="off" role="combobox" aria-autocomplete="list" aria-expanded="false" aria-controls="crm-code-list">
|
||||||
|
<ul id="crm-code-list" class="suggest-list" role="listbox" dir="ltr" hidden></ul>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<p class="empty-state" id="crm-orders-status" hidden></p>
|
<p class="empty-state" id="crm-orders-status" hidden></p>
|
||||||
@@ -41,6 +74,11 @@
|
|||||||
<div id="toast" class="toast"></div>
|
<div id="toast" class="toast"></div>
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|
||||||
{% block extra_scripts %}
|
{% block extra_head %}
|
||||||
<script src="{% static 'slips/js/crm_orders.js' %}?v=6"></script>
|
<link rel="stylesheet" href="{% static 'slips/vendor/jalalidatepicker/jalalidatepicker.min.css' %}?v=1">
|
||||||
|
{% endblock %}
|
||||||
|
|
||||||
|
{% block extra_scripts %}
|
||||||
|
<script src="{% static 'slips/vendor/jalalidatepicker/jalalidatepicker.min.js' %}?v=1"></script>
|
||||||
|
<script src="{% static 'slips/js/crm_orders.js' %}?v=13"></script>
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|||||||
221
slips/tests.py
221
slips/tests.py
@@ -1,16 +1,29 @@
|
|||||||
import unittest
|
import unittest
|
||||||
from datetime import date
|
from datetime import date, timedelta
|
||||||
from types import SimpleNamespace
|
from types import SimpleNamespace
|
||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
from django.test import TestCase
|
||||||
|
from django.utils import timezone
|
||||||
|
|
||||||
from slips.crm_orders import (
|
from slips.crm_orders import (
|
||||||
|
SESSION_TTL_SECONDS,
|
||||||
|
CrmAuthError,
|
||||||
|
CrmOrdersError,
|
||||||
|
_load_order_export,
|
||||||
code_matches,
|
code_matches,
|
||||||
|
export_filtered_customer_orders,
|
||||||
format_jalali,
|
format_jalali,
|
||||||
jalali_from_gregorian,
|
jalali_from_gregorian,
|
||||||
|
login_rejected,
|
||||||
note_date_as_jalali,
|
note_date_as_jalali,
|
||||||
orders_after,
|
orders_after,
|
||||||
parse_gregorian,
|
parse_gregorian,
|
||||||
parse_jalali,
|
parse_jalali,
|
||||||
parse_prefixes,
|
parse_prefixes,
|
||||||
|
recent_customer_orders,
|
||||||
|
report_base_url,
|
||||||
|
report_filter_state,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@@ -54,5 +67,211 @@ class OrdersAfterTests(unittest.TestCase):
|
|||||||
self.assertEqual(parse_prefixes(""), [])
|
self.assertEqual(parse_prefixes(""), [])
|
||||||
|
|
||||||
|
|
||||||
|
class SystemGroupLoginTests(unittest.TestCase):
|
||||||
|
def test_login_rejected_markers(self):
|
||||||
|
self.assertEqual(SESSION_TTL_SECONDS, 30 * 24 * 60 * 60)
|
||||||
|
self.assertTrue(login_rejected("Login appears to have failed (still on Login.aspx)."))
|
||||||
|
self.assertTrue(login_rejected("Customer orders report redirected to login; check credentials."))
|
||||||
|
self.assertFalse(login_rejected("Set REPORT_BASE_URL."))
|
||||||
|
|
||||||
|
def test_base_url_ignores_shared_password(self):
|
||||||
|
import slips.crm_orders as mod
|
||||||
|
|
||||||
|
def setting(key):
|
||||||
|
if key == "REPORT_BASE_URL":
|
||||||
|
return "http://crm.example"
|
||||||
|
return None
|
||||||
|
|
||||||
|
with patch.object(mod, "_setting", setting):
|
||||||
|
self.assertEqual(report_base_url(), "http://crm.example/")
|
||||||
|
with self.assertRaises(CrmOrdersError):
|
||||||
|
mod._setting = lambda key: None
|
||||||
|
report_base_url()
|
||||||
|
|
||||||
|
def test_fetch_uses_supplied_credentials(self):
|
||||||
|
import slips.crm_orders as mod
|
||||||
|
|
||||||
|
seen = {}
|
||||||
|
|
||||||
|
class FakeClient:
|
||||||
|
def __init__(self, **kwargs):
|
||||||
|
seen.update(kwargs)
|
||||||
|
|
||||||
|
def fetch_customer_orders(self):
|
||||||
|
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
|
||||||
|
|
||||||
|
with patch.object(mod, "_setting", setting), \
|
||||||
|
patch("lithium_systemgroup.SystemGroupClient", FakeClient), \
|
||||||
|
patch("lithium_systemgroup.parse_customer_orders_document", lambda body, content_type="": []):
|
||||||
|
result = recent_customer_orders("ada", "secret")
|
||||||
|
self.assertEqual(seen["username"], "ada")
|
||||||
|
self.assertEqual(seen["password"], "secret")
|
||||||
|
self.assertEqual(seen["base_url"], "http://crm.example/")
|
||||||
|
self.assertNotIn("prefer_report_env", seen)
|
||||||
|
self.assertEqual(result["orders"], [])
|
||||||
|
|
||||||
|
class RejectClient(FakeClient):
|
||||||
|
def fetch_customer_orders(self):
|
||||||
|
from lithium_systemgroup import SystemGroupClientError
|
||||||
|
raise SystemGroupClientError("Login appears to have failed")
|
||||||
|
|
||||||
|
with patch.object(mod, "_setting", setting), \
|
||||||
|
patch("lithium_systemgroup.SystemGroupClient", RejectClient):
|
||||||
|
with self.assertRaises(CrmAuthError):
|
||||||
|
recent_customer_orders("ada", "wrong")
|
||||||
|
|
||||||
|
def test_report_filter_uses_date_and_code_prefixes(self):
|
||||||
|
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")
|
||||||
|
|
||||||
|
seen = {}
|
||||||
|
|
||||||
|
class Client:
|
||||||
|
def fetch_customer_orders(self, filter_state=None):
|
||||||
|
seen["filter_state"] = filter_state
|
||||||
|
return "note,code\n", "text/csv"
|
||||||
|
|
||||||
|
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 test_load_uses_direct_export(self):
|
||||||
|
seen = {}
|
||||||
|
|
||||||
|
class Client:
|
||||||
|
def fetch_customer_orders(self, **kwargs):
|
||||||
|
seen.update(kwargs)
|
||||||
|
return "full", "text/csv"
|
||||||
|
|
||||||
|
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
|
||||||
|
|
||||||
|
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(
|
||||||
|
"/api/crm-orders/session",
|
||||||
|
data={"username": "ada", "password": "secret"},
|
||||||
|
content_type="application/json",
|
||||||
|
)
|
||||||
|
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),
|
||||||
|
)
|
||||||
|
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")
|
||||||
|
|
||||||
|
def test_rejected_password_is_not_stored(self):
|
||||||
|
from slips import api
|
||||||
|
|
||||||
|
def fake(username, password, client=None, cookies=None):
|
||||||
|
raise CrmAuthError("nope")
|
||||||
|
|
||||||
|
with patch.object(api, "recent_customer_orders", fake):
|
||||||
|
res = self.client.post(
|
||||||
|
"/api/crm-orders/session",
|
||||||
|
data={"username": "ada", "password": "wrong"},
|
||||||
|
content_type="application/json",
|
||||||
|
)
|
||||||
|
self.assertEqual(res.status_code, 401)
|
||||||
|
self.assertEqual(res.json()["code"], "login_rejected")
|
||||||
|
self.assertNotIn("sg_password", self.client.session)
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
unittest.main()
|
unittest.main()
|
||||||
|
|||||||
Reference in New Issue
Block a user