Compare commits

..

2 Commits

Author SHA1 Message Date
df04d5243b Fix entry form date defaults and input overflow.
Wire date fields so Date defaults to today and Next Control tracks +6 months; constrain inputs to the form column width.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-01 17:30:03 +03:30
c8e93566a1 Bump Docker base image to Python 3.14 slim.
Keep a pinned latest-stable tag for reproducible builds.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-01 16:59:45 +03:30
44 changed files with 685 additions and 4581 deletions

View File

@@ -1,143 +0,0 @@
---
name: gitea-prs
description: >-
Create, merge, and clean up pull requests on this repo's Gitea host using tea
and SSH. Use when the user asks to open a PR, create a pull request, merge a
PR, push a feature branch, or delete a feature branch after merge. Draft PRs
use a WIP: title and must be undrafted before merge (tea merge fails otherwise).
Do not use gh (GitHub CLI) for this repository.
---
# Gitea pull requests (product-slip)
Host: `https://git.faryad.top/rhino/product-slip`
CLI: `tea` (login name `faryad`, user `rhino`)
Git remote: SSH on port **2222** (HTTPS push prompts for credentials and fails non-interactively).
```
origin ssh://git@git.faryad.top:2222/rhino/product-slip.git
```
If `origin` is still HTTPS, set SSH before push:
```bash
git remote set-url origin ssh://git@git.faryad.top:2222/rhino/product-slip.git
```
## Push feature branch
```bash
git push -u origin HEAD
```
## Create PR
```bash
tea pulls create \
--head <feature-branch> \
--base main \
--title "<short imperative title>" \
--description "$(cat <<'EOF'
## Summary
- <1-3 bullets>
## Test plan
- [ ] <checks>
EOF
)"
```
- Title: short, imperative (same style as commit messages; prefer under 20 words).
- Return the PR URL from tea output (e.g. `https://git.faryad.top/rhino/product-slip/pulls/N`).
### Draft PRs
`tea pulls create` has no `--draft` flag. This Gitea marks a PR as draft when the title starts with `WIP:` (API `draft: true` alone is ignored / cleared if the prefix is removed).
For a draft PR, either:
- Create with `--title "WIP: <title>"`, or
- `POST /api/v1/repos/rhino/product-slip/pulls` with `"draft": true` **and** a `WIP:` title (token from `tea` login in `~/.config/tea/config.yml`).
Before merge, strip `WIP:` (see **Merge PR**) — drafts are not mergeable.
## Merge PR
**Draft / `WIP:` PRs cannot be merged.** `tea pulls merge` fails with `Failed to merge PR. Is it still open?` while the title still starts with `WIP:` (even though the PR is open). Always undraft first.
1. If the title starts with `WIP:`, remove that prefix via API (token from `tea` login in `~/.config/tea/config.yml`):
```bash
export PR_INDEX=23 # the PR number
python3 <<'PY'
import json, os, urllib.request, yaml
from pathlib import Path
pr = os.environ["PR_INDEX"]
cfg = yaml.safe_load(Path.home().joinpath(".config/tea/config.yml").read_text())
login = next(l for l in cfg["logins"] if l.get("default"))
token, base = login["token"], login["url"].rstrip("/")
req = urllib.request.Request(
f"{base}/api/v1/repos/rhino/product-slip/pulls/{pr}",
headers={"Authorization": f"token {token}", "Accept": "application/json"},
)
with urllib.request.urlopen(req) as resp:
data = json.load(resp)
title = data["title"]
if title.startswith("WIP:"):
title = title[4:].lstrip()
payload = json.dumps({"title": title, "draft": False}).encode()
req = urllib.request.Request(
f"{base}/api/v1/repos/rhino/product-slip/pulls/{pr}",
data=payload,
headers={
"Authorization": f"token {token}",
"Content-Type": "application/json",
"Accept": "application/json",
},
method="PATCH",
)
with urllib.request.urlopen(req) as resp:
data = json.load(resp)
print(f"draft={data.get('draft')} mergeable={data.get('mergeable')} title={data['title']!r}")
PY
```
2. Merge:
```bash
tea pulls merge <pr-index> --style merge
```
3. Update local main:
```bash
git fetch --prune origin
git checkout main
git pull --ff-only origin main
```
Then delete the feature branch (next section).
## Delete feature branch after merge
Do this automatically after every merge unless the user says to keep the branch.
Prefer in order:
1. `tea pulls clean <pr-index> --ignore-sha`
(May fail if tea expects an HTTPS remote — fall through.)
2. Remote: `git push origin --delete <feature-branch>`
3. Local: `git branch -d <feature-branch>` (if still checked out elsewhere / still exists)
4. `git fetch --prune origin`
Confirm gone:
```bash
git ls-remote --heads origin '<feature-branch>'
```
## Do not
- Use `gh` / GitHub APIs for this repo.
- Force-push `main`.
- Leave the feature branch on the remote after merge.

View File

@@ -1,24 +0,0 @@
# Host port published by nginx (maps to container port 80)
HTTP_PORT=80
# Optional Debian apt mirror host (replaces deb.debian.org / security.debian.org)
# APT_MIRROR=mirrors.tuna.tsinghua.edu.cn
# Optional PyPI index URL for uv during image build
# PIP_INDEX_URL=https://pypi.tuna.tsinghua.edu.cn/simple
# PIP_TRUSTED_HOST=pypi.tuna.tsinghua.edu.cn
# 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/
# Optional report page path (no host). Leave unset to use the package default.
# REPORT_ORDERS_PATH=
# Gregorian cutoff. The Orders tab lists delivery notes dated after this day.
# Accepted forms: YYYY-MM-DD or DD/MM/YYYY (also DD-MM-YYYY). Shown on the Orders tab as Jalali.
# REPORT_ORDERS_SINCE=21-03-2026
# Comma-separated product-code prefixes. A note is listed only when its code starts with one of these.
# Leave empty to keep every code.
# REPORT_ORDERS_PREFIXES=ICJ/,RMJ/,IJP/,KR
# Optional CRM host. Used only when REPORT_BASE_URL is unset.
# CRM_BASE_URL=

View File

@@ -1,44 +1,13 @@
FROM python:3.14-slim FROM python:3.14-slim
COPY --from=ghcr.io/astral-sh/uv:latest /uv /uvx /bin/
ENV PYTHONDONTWRITEBYTECODE=1 ENV PYTHONDONTWRITEBYTECODE=1
ENV PYTHONUNBUFFERED=1 ENV PYTHONUNBUFFERED=1
ENV UV_LINK_MODE=copy
ARG APT_MIRROR=
ARG PIP_INDEX_URL=
ARG PIP_TRUSTED_HOST=
# Optional Debian apt mirror (host only, e.g. mirror.example.com)
RUN if [ -n "$APT_MIRROR" ]; then \
if [ -f /etc/apt/sources.list.d/debian.sources ]; then \
sed -i "s|deb.debian.org|${APT_MIRROR}|g; s|security.debian.org|${APT_MIRROR}|g" \
/etc/apt/sources.list.d/debian.sources; \
fi; \
if [ -f /etc/apt/sources.list ]; then \
sed -i "s|deb.debian.org|${APT_MIRROR}|g; s|security.debian.org|${APT_MIRROR}|g" \
/etc/apt/sources.list; \
fi; \
fi
# Git is required to fetch the VCS requirement in requirements.txt.
RUN apt-get update \
&& apt-get install -y --no-install-recommends git \
&& rm -rf /var/lib/apt/lists/*
# Optional PyPI mirror (PIP_* kept for .env compat; mapped to uv only when set)
ENV PIP_INDEX_URL=${PIP_INDEX_URL}
ENV PIP_TRUSTED_HOST=${PIP_TRUSTED_HOST}
WORKDIR /app WORKDIR /app
# Install dependencies (BuildKit uv cache survives rebuilds) # Install dependencies
COPY requirements.txt . COPY requirements.txt .
RUN --mount=type=cache,target=/root/.cache/uv \ RUN pip install --no-cache-dir -r requirements.txt
if [ -n "$PIP_INDEX_URL" ]; then export UV_DEFAULT_INDEX="$PIP_INDEX_URL"; fi; \
if [ -n "$PIP_TRUSTED_HOST" ]; then export UV_INSECURE_HOST="$PIP_TRUSTED_HOST"; fi; \
uv pip install --system -r requirements.txt
# Copy project # Copy project
COPY . . COPY . .

Binary file not shown.

View File

@@ -1,115 +0,0 @@
# 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.

252
PLAN.md Normal file
View File

@@ -0,0 +1,252 @@
# Product Slip Printing App — Implementation Plan
## 1. Overview
Web app for printing variable data onto pre-printed ink canister labels.
Two users on the same LAN: one enters orders, another prints slips.
**Stack**: Django Ninja + SQLite + Docker (Gunicorn + Nginx)
---
## 2. Excel Analysis
File: `ETICHETTE PER INKS(دون خط 4 تایی).xlsx` — 5 sheets, one per product.
### Products Found
| Sheet | Code | Description | Default Net Weight |
|-------|------|-------------|--------------------|
| ICJ408 | ICJ/408 | DIGITAL INK RED BROWN | 5 kg |
| ICJ407 | ICJ/407 | DIGITAL INK RED BROWN | 5 kg |
| ICJ309 | ICJ/309 | DIGITAL INK CYAN | 10 kg |
| ICJ630 | ICJ/EH630 | DIGITAL INK BLACK | 5 kg |
| ICJ308 | ICJ/308 | DIGITAL INK BLUE | 20 kg |
### A4 Page Layout — 4 Slips per Page (2×2 Grid)
```
┌──────────────────────┬──────────────────────┐
│ SLIP 1 (Cols A-I) │ SLIP 2 (Cols K-S) │
│ Rows 9-39 │ Rows 9-39 │
├──────────────────────┼──────────────────────┤
│ SLIP 3 (Cols A-I) │ SLIP 4 (Cols K-S) │
│ Rows 53-83 │ Rows 53-83 │
└──────────────────────┴──────────────────────┘
```
### What We Print (4 variable fields only)
The physical labels come pre-printed with company info, product code,
description, and all fixed text. We only overprint these values:
| Field | Cell Position (Slip 1) | Example |
|-------|----------------------|---------|
| Batch# | C18 | 1028/26 |
| Date | G18 | 05/05/2026 |
| Net Weight | C20 | 20 |
| Next Control Date | F19 | 05/11/2026 |
Page: A4 portrait, ~1cm margins all sides, paperSize=9.
---
## 3. Architecture
```
LAN
├── Machine A (Data Entry) ──→ http://server/entry
├── Machine B (Printer) ──→ http://server/print
│
└── Server (Docker)
├── nginx:alpine (port 80) ──→ reverse proxy
└── python:3.12-slim (port 8000)
├── Django Ninja (API + Views)
├── Gunicorn (WSGI)
├── WhiteNoise (static files)
└── SQLite (/app/data/db.sqlite3)
```
**Framework Choice: Django Ninja** (over Flask and plain Django)
- Django ORM + built-in migrations + free admin panel
- FastAPI-style Pydantic schemas for clean API validation
- Auto-generated Swagger docs at `/api/docs`
- Less boilerplate than Flask+SQLAlchemy+Marshmallow
---
## 4. Database Schema
```sql
CREATE TABLE products (
id INTEGER PRIMARY KEY AUTOINCREMENT,
code TEXT NOT NULL UNIQUE,
description TEXT NOT NULL,
default_net_weight REAL DEFAULT 5.0,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE orders (
id INTEGER PRIMARY KEY AUTOINCREMENT,
product_id INTEGER NOT NULL REFERENCES products(id),
batch_number TEXT NOT NULL,
production_date DATE NOT NULL,
next_control_date DATE NOT NULL,
net_weight REAL NOT NULL,
canister_count INTEGER NOT NULL,
pages_needed INTEGER NOT NULL,
status TEXT DEFAULT 'pending',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
printed_at TIMESTAMP NULL
);
```
---
## 5. API Endpoints (Django Ninja)
| Method | Endpoint | Purpose |
|--------|----------|---------|
| GET | `/` | Redirect to `/entry` |
| GET | `/entry` | Data entry panel |
| GET | `/print` | Print queue panel |
| GET | `/calibrate` | Calibration page |
| GET | `/api/products` | List products |
| POST | `/api/products` | Add new product |
| GET | `/api/orders` | List orders (?status=pending) |
| POST | `/api/orders` | Create order |
| PATCH | `/api/orders/{id}` | Update status |
| DELETE | `/api/orders/{id}` | Delete order |
| GET | `/print-page/{id}` | Printable slip page |
| GET | `/api/docs` | Auto Swagger UI |
| GET | `/admin/` | Django admin panel |
---
## 6. Frontend Panels
### Data Entry (`/entry`)
- Product dropdown (from catalog) + "Add New Product"
- Batch # input
- Date picker (default: today)
- Next control date (auto: date + 6 months, editable)
- Net weight (auto from product default, editable)
- Canister count → auto-calculates pages = ceil(count/4)
- Submit → adds to print queue
- Recent orders table with status
### Print Queue (`/print`)
- Pending orders list (auto-refreshes every 10s)
- Print button → opens printable page → browser print dialog
- Mark Done button
- Print history table
### Print Page (`/print-page/{id}`)
- CSS @media print with absolute positioning
- Only prints 4 variable values at exact positions
- Multiple pages if order needs > 1 page (4 slips/page)
### Calibration (`/calibrate`)
- Cross-hair markers at field positions
- Print on blank paper, overlay on pre-printed label to check alignment
---
## 7. i18n (English / Persian LTR)
| Key | English | Persian |
|-----|---------|---------|
| app_title | Product Slip Manager | مدیریت برچسب محصول |
| new_order | New Order | سفارش جدید |
| product | Product | محصول |
| batch_number | Batch # | شماره بچ |
| date | Date | تاریخ |
| next_control | Next Control Date | تاریخ کنترل بعدی |
| net_weight | Net Weight (kg) | وزن خالص (کیلوگرم) |
| canisters | Canisters | تعداد قوطی |
| pages_needed | Pages Needed | تعداد صفحات |
| add_to_queue | Add to Print Queue | افزودن به صف چاپ |
| print_queue | Print Queue | صف چاپ |
| pending | Pending | در انتظار |
| done | Done | انجام شده |
| print | Print | چاپ |
| mark_done | Mark as Done | تایید چاپ |
| cancel | Cancel | لغو |
Persian text direction: LTR (as requested).
---
## 8. UI Design
- **Theme**: Dark navy (#0f172a) with glassmorphism panels
- **Accent**: Blue gradient (#3b82f6 → #60a5fa)
- **Font**: Inter (Google Fonts), JetBrains Mono for data values
- **Effects**: backdrop-filter blur, smooth transitions, pulse on pending badges
- **Status colors**: amber=pending, green=done, red=cancelled
---
## 9. File Structure
```
product-slip/
├── docker-compose.yml ✅ created
├── Dockerfile ✅ created
├── nginx.conf ✅ created
├── requirements.txt ✅ created
├── manage.py ✅ created
├── .gitignore ✅ created
├── config/ ✅ created
│ ├── __init__.py
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
├── slips/ ⬜ TODO
│ ├── __init__.py
│ ├── models.py
│ ├── admin.py
│ ├── schemas.py
│ ├── api.py
│ ├── views.py
│ ├── management/
│ │ └── commands/
│ │ └── seed_products.py
│ ├── templates/slips/
│ │ ├── base.html
│ │ ├── entry.html
│ │ ├── print.html
│ │ ├── print_page.html
│ │ └── calibrate.html
│ └── static/slips/
│ ├── css/style.css
│ └── js/
│ ├── i18n.js
│ ├── entry.js
│ └── print.js
└── data/ (Docker volume, gitignored)
```
---
## 10. Docker Stack
```yaml
services:
app: # Django + Gunicorn on port 8000
nginx: # Reverse proxy on port 80
volumes:
db_data: # SQLite persistence
```
Startup: migrate → seed products → gunicorn
---
## 11. Defaults & Assumptions
- Date format: DD/MM/YYYY (European, matching Excel)
- Products: pre-defined dropdown + "Add New" option
- Quantity: user enters canister count, app calculates pages = ceil(n/4)
- Net weight: auto-fills from product, editable per order
- Next control: auto-calculated as date + 6 months, editable

View File

@@ -1,4 +1,4 @@
# Lithium Labels # Product Slip Manager
A self-hosted web application for tracking production orders and generating pixel-perfect labels for canisters and boxes. A self-hosted web application for tracking production orders and generating pixel-perfect labels for canisters and boxes.
@@ -23,20 +23,13 @@ The application is fully containerized using Docker, meaning it can be deployed
```bash ```bash
cd path/to/product-slip cd path/to/product-slip
``` ```
2. (Optional) Copy `.env.example` to `.env` and adjust settings: 2. Start the application stack using Docker Compose:
```bash
cp .env.example .env
```
- `HTTP_PORT` — host port for the app (default `80`)
- `APT_MIRROR` — Debian apt mirror host used during image build
- `PIP_INDEX_URL` / `PIP_TRUSTED_HOST` — PyPI mirror used by uv during image build (`PIP_TRUSTED_HOST` allows insecure/HTTP hosts)
3. Start the application stack using Docker Compose:
```bash ```bash
docker compose up -d --build docker compose up -d --build
``` ```
4. The server is now running! You can access the application from any device on the same local network: 3. The server is now running! You can access the application from any device on the same local network:
- If you are on the same machine: Open your browser and go to `http://localhost` (or `http://localhost:$HTTP_PORT` if you changed the port) - If you are on the same machine: Open your browser and go to `http://localhost`
- If you are on a different machine on the same network: Find the host computer's local IP address (e.g., `192.168.1.15`) and go to `http://192.168.1.15` (add `:$HTTP_PORT` if not using port 80) - If you are on a different machine on the same network: Find the host computer's local IP address (e.g., `192.168.1.15`) and go to `http://192.168.1.15`
### Stopping the Server ### Stopping the Server
To safely stop the application without losing data: To safely stop the application without losing data:
@@ -53,26 +46,32 @@ Because the application prints dynamic text directly over your physical, pre-pri
Follow these steps to calibrate the alignment for your specific printer: Follow these steps to calibrate the alignment for your specific printer:
### 1. Open the Calibrate tab ### 1. Print the Calibration Sheet
1. Open the application and navigate to **Calibrate** in the top menu. 1. Open the application and navigate to the **Calibrate** tab in the top menu.
2. You will see a live A4 preview (2×2 slips) and a control panel with millimeter positions. 2. Load a **blank** piece of A4 paper into your printer.
3. Click the "Print Calibration Sheet" button to print it out.
### 2. Print and check the alignment ### 2. Check the Alignment
1. Load a **blank** piece of A4 paper into your printer. 1. Take your printed blank calibration sheet.
2. Click **Print** on the calibrate page. 2. Place it perfectly behind one of your **actual pre-printed label sheets**.
3. Place the printed sheet perfectly behind one of your **actual pre-printed label sheets**. 3. Hold them both up to a light source (like a window or lamp).
4. Hold them both up to a light source (window or lamp). 4. Look for the crosshairs (`┼`). They should align perfectly inside the target boxes (Batch, Date, Next Control, and Weight).
5. The crosshairs (`┼`) should sit inside the target boxes (Batch, Date, Next Control, and Weight).
### 3. Adjust positions in the UI ### 3. Adjusting the Millimeters (If Necessary)
If text is too high, low, or off to the side, nudge it in the panel — no code edits or Docker restart needed. If the text is printing slightly too high, too low, or too far to a side, you can adjust the CSS margins in the codebase to shift the text.
1. Use **+/−** (or type a value) for each field’s `top` / `left` (and font if needed). 1. Open the file: `slips/templates/slips/print_page.html`
- Move **DOWN**: increase `top`. 2. Scroll to the `<style>` block at the top, and find the `.var-field` CSS section.
- Move **RIGHT**: increase `left`. 3. You will see absolute positioning values in millimeters (`mm`), for example:
2. Click a crosshair on the preview to jump to that field’s controls; arrow keys also nudge the selection. ```css
3. Click **Save** when it looks right. Values are stored in `data/calibration.json` (same persistent data volume as the database). .val-batch { top: 15mm; left: 40mm; }
4. Print a new calibration sheet and overlay again until perfect. ```
5. **Reset defaults** restores the built-in starting positions. 4. **Adjust the numbers**:
- To move text **DOWN**: Increase the `top` value (e.g., `15mm` -> `17mm`).
Order print pages load the latest saved calibration automatically when you open Print (no hard refresh required). - To move text **RIGHT**: Increase the `left` value (e.g., `40mm` -> `42mm`).
5. Save the file.
6. Restart the Docker container so the changes take effect:
```bash
docker compose restart app
```
7. Print a new calibration sheet and test again until perfect!

View File

@@ -3,27 +3,6 @@ from pathlib import Path
BASE_DIR = Path(__file__).resolve().parent.parent BASE_DIR = Path(__file__).resolve().parent.parent
def _load_env_file(path: Path) -> None:
"""Fill unset variables from a local env file. The process environment wins."""
if not path.is_file():
return
for raw in path.read_text(encoding='utf-8').splitlines():
line = raw.strip()
if not line or line.startswith('#') or '=' not in line:
continue
key, value = line.split('=', 1)
key = key.strip()
if not key or key in os.environ:
continue
value = value.strip()
if len(value) >= 2 and value[0] == value[-1] and value[0] in '"\'':
value = value[1:-1]
os.environ[key] = value
_load_env_file(BASE_DIR / '.env')
SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY', 'dev-secret-key-change-in-production') SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY', 'dev-secret-key-change-in-production')
DEBUG = os.environ.get('DJANGO_DEBUG', '1') == '1' DEBUG = os.environ.get('DJANGO_DEBUG', '1') == '1'

View File

@@ -8,9 +8,7 @@ urlpatterns = [
path('api/', api.urls), path('api/', api.urls),
path('', views.index, name='index'), path('', views.index, name='index'),
path('entry/', views.entry, name='entry'), path('entry/', views.entry, name='entry'),
path('products/', views.products, name='products'),
path('print/', views.print_queue, name='print_queue'), path('print/', views.print_queue, name='print_queue'),
path('crm-orders/', views.crm_orders, name='crm_orders'),
path('print-page/<int:order_id>/', views.print_page, name='print_page'), path('print-page/<int:order_id>/', views.print_page, name='print_page'),
path('calibrate/', views.calibrate, name='calibrate'), path('calibrate/', views.calibrate, name='calibrate'),
] ]

View File

@@ -1,11 +1,6 @@
services: services:
app: app:
build: build: .
context: .
args:
APT_MIRROR: ${APT_MIRROR:-}
PIP_INDEX_URL: ${PIP_INDEX_URL:-}
PIP_TRUSTED_HOST: ${PIP_TRUSTED_HOST:-}
restart: unless-stopped restart: unless-stopped
volumes: volumes:
- db_data:/app/data - db_data:/app/data
@@ -13,11 +8,6 @@ services:
- DJANGO_SECRET_KEY=change-me-in-production-use-a-real-secret - DJANGO_SECRET_KEY=change-me-in-production-use-a-real-secret
- DJANGO_DEBUG=0 - DJANGO_DEBUG=0
- DJANGO_ALLOWED_HOSTS=* - DJANGO_ALLOWED_HOSTS=*
- REPORT_BASE_URL=${REPORT_BASE_URL:-}
- REPORT_ORDERS_PATH=${REPORT_ORDERS_PATH:-}
- REPORT_ORDERS_SINCE=${REPORT_ORDERS_SINCE:-}
- REPORT_ORDERS_PREFIXES=${REPORT_ORDERS_PREFIXES:-}
- CRM_BASE_URL=${CRM_BASE_URL:-}
networks: networks:
- web - web
@@ -25,7 +15,7 @@ services:
image: nginx:alpine image: nginx:alpine
restart: unless-stopped restart: unless-stopped
ports: ports:
- "${HTTP_PORT:-80}:80" - "80:80"
volumes: volumes:
- ./nginx.conf:/etc/nginx/conf.d/default.conf:ro - ./nginx.conf:/etc/nginx/conf.d/default.conf:ro
depends_on: depends_on:
@@ -38,7 +28,3 @@ volumes:
networks: networks:
web: web:
# Happ/xray claims 172.19.0.0/30, which overlaps Docker's default pool on this host.
ipam:
config:
- subnet: 172.28.10.0/24

View File

@@ -9,6 +9,5 @@ server {
proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header X-Forwarded-Proto $scheme;
proxy_read_timeout 120s;
} }
} }

View File

@@ -2,4 +2,3 @@ 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@cbcadf37c2166ca4978f56f66c91007eb510ffcc

View File

@@ -4,8 +4,7 @@ from .models import Product, Order
@admin.register(Product) @admin.register(Product)
class ProductAdmin(admin.ModelAdmin): class ProductAdmin(admin.ModelAdmin):
list_display = ['code', 'description', 'default_net_weight', 'requires_dates', 'created_at'] list_display = ['code', 'description', 'default_net_weight', 'created_at']
list_editable = ['requires_dates']
search_fields = ['code', 'description'] search_fields = ['code', 'description']
@@ -15,4 +14,4 @@ class OrderAdmin(admin.ModelAdmin):
'box_count', 'status', 'created_at'] 'box_count', 'status', 'created_at']
list_filter = ['status', 'product'] list_filter = ['status', 'product']
search_fields = ['batch_number', 'product__code'] search_fields = ['batch_number', 'product__code']
readonly_fields = ['canister_pages', 'box_pages'] readonly_fields = ['canister_count', 'box_count', 'canister_pages', 'box_pages']

View File

@@ -1,23 +1,12 @@
from typing import List, Optional from typing import List, Optional
from django.db import IntegrityError
from django.shortcuts import get_object_or_404 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 ( from .models import Product, Order
SESSION_TTL_SECONDS, from .schemas import ProductOut, ProductIn, OrderOut, OrderIn, OrderStatusIn
CrmAuthError,
CrmOrdersError,
recent_customer_orders,
)
from .models import Product, Order, clean_custom_labels
from .schemas import (
ProductOut, ProductIn, OrderOut, OrderIn, OrderUpdateIn,
CalibrationIn, CalibrationOut, CrmLoginIn, CrmOrdersOut,
)
from .calibration import load_calibration, save_calibration, DEFAULTS, for_api
api = NinjaAPI(title='Lithium Labels', version='1.0.0', urls_namespace='slips_api') api = NinjaAPI(title='Product Slip API', version='1.0.0', urls_namespace='slips_api')
# ─── Products ──────────────────────────────────────────── # ─── Products ────────────────────────────────────────────
@@ -27,57 +16,12 @@ def list_products(request):
return Product.objects.all() return Product.objects.all()
@api.post('/products', response={201: ProductOut, 400: dict}, tags=['Products']) @api.post('/products', response={201: ProductOut}, tags=['Products'])
def create_product(request, payload: ProductIn): def create_product(request, payload: ProductIn):
try:
product = Product.objects.create(**payload.dict()) product = Product.objects.create(**payload.dict())
except IntegrityError:
return 400, {'detail': 'Product code already exists'}
return 201, product return 201, product
@api.post('/products/restore', response={200: dict, 400: dict}, tags=['Products'])
def restore_products(request, payload: List[ProductIn]):
if not payload:
return 400, {'detail': 'Empty backup'}
created = updated = 0
for item in payload:
_, was_created = Product.objects.update_or_create(
code=item.code,
defaults={
'description': item.description,
'default_net_weight': item.default_net_weight,
'requires_dates': item.requires_dates,
},
)
if was_created:
created += 1
else:
updated += 1
return {'created': created, 'updated': updated, 'total': created + updated}
@api.put('/products/{product_id}', response={200: ProductOut, 400: dict}, tags=['Products'])
def update_product(request, product_id: int, payload: ProductIn):
product = get_object_or_404(Product, id=product_id)
try:
for key, value in payload.dict().items():
setattr(product, key, value)
product.save()
except IntegrityError:
return 400, {'detail': 'Product code already exists'}
return product
@api.delete('/products/{product_id}', response={204: None, 400: dict}, tags=['Products'])
def delete_product(request, product_id: int):
product = get_object_or_404(Product, id=product_id)
if product.orders.exists():
return 400, {'detail': 'Product has orders and cannot be removed'}
product.delete()
return 204, None
# ─── Orders ────────────────────────────────────────────── # ─── Orders ──────────────────────────────────────────────
@api.get('/orders', response=List[OrderOut], tags=['Orders']) @api.get('/orders', response=List[OrderOut], tags=['Orders'])
@@ -88,67 +32,28 @@ def list_orders(request, status: Optional[str] = Query(None)):
return qs return qs
@api.post('/orders', response={201: OrderOut, 400: dict}, tags=['Orders']) @api.post('/orders', response={201: OrderOut}, tags=['Orders'])
def create_order(request, payload: OrderIn): def create_order(request, payload: OrderIn):
product = get_object_or_404(Product, id=payload.product_id) product = get_object_or_404(Product, id=payload.product_id)
if product.requires_dates:
if not payload.production_date or not payload.next_control_date:
return 400, {'detail': 'production_date and next_control_date are required'}
production_date = payload.production_date
next_control_date = payload.next_control_date
else:
production_date = None
next_control_date = None
try:
custom_labels = clean_custom_labels(payload.custom_labels)
except ValueError as exc:
return 400, {'detail': str(exc)}
order = Order( order = Order(
product=product, product=product,
batch_number=payload.batch_number, batch_number=payload.batch_number,
production_date=production_date, production_date=payload.production_date,
next_control_date=next_control_date, next_control_date=payload.next_control_date,
total_weight=payload.total_weight, total_weight=payload.total_weight,
canister_weight=payload.canister_weight, canister_weight=payload.canister_weight,
canisters_per_box=payload.canisters_per_box, canisters_per_box=payload.canisters_per_box,
custom_labels=custom_labels,
) )
order.apply_weight()
order.save() order.save()
return 201, order return 201, order
@api.patch('/orders/{order_id}', response={200: OrderOut, 400: dict}, tags=['Orders']) @api.patch('/orders/{order_id}', response=OrderOut, tags=['Orders'])
def update_order(request, order_id: int, payload: OrderUpdateIn): def update_order_status(request, order_id: int, payload: OrderStatusIn):
order = get_object_or_404(Order, id=order_id) order = get_object_or_404(Order, id=order_id)
counts_changed = payload.canister_count is not None or payload.box_count is not None
custom_changed = payload.custom_labels is not None
if counts_changed or custom_changed:
if order.status != 'pending':
return 400, {'detail': 'Only pending orders can change label counts'}
cc = payload.canister_count if payload.canister_count is not None else order.canister_count
bc = payload.box_count if payload.box_count is not None else order.box_count
if cc < 0 or bc < 0:
return 400, {'detail': 'counts must be >= 0'}
try:
custom = clean_custom_labels(payload.custom_labels) if custom_changed else (order.custom_labels or [])
except ValueError as exc:
return 400, {'detail': str(exc)}
if cc == 0 and bc == 0 and not custom:
return 400, {'detail': 'at least one label is required'}
if counts_changed:
order.set_counts(payload.canister_count, payload.box_count)
if custom_changed:
order.custom_labels = custom
if payload.status is not None:
order.status = payload.status order.status = payload.status
if payload.status == 'done': if payload.status == 'done':
order.printed_at = timezone.now() order.printed_at = timezone.now()
elif payload.status == 'pending':
order.printed_at = None
order.save() order.save()
return order return order
@@ -158,119 +63,3 @@ def delete_order(request, order_id: int):
order = get_object_or_404(Order, id=order_id) order = get_object_or_404(Order, id=order_id)
order.delete() order.delete()
return 204, None return 204, None
_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):
"""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:
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:
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 ─────────────────────────────────────────
@api.get('/calibration', response=CalibrationOut, tags=['Calibration'])
def get_calibration(request):
return for_api(load_calibration())
@api.put('/calibration', response=CalibrationOut, tags=['Calibration'])
def put_calibration(request, payload: CalibrationIn):
data = payload.dict()
# Drop None optional keys so merge keeps defaults only when omitted
for field, vals in data.items():
data[field] = {k: v for k, v in vals.items() if v is not None}
return for_api(save_calibration(data))
@api.post('/calibration/reset', response=CalibrationOut, tags=['Calibration'])
def reset_calibration(request):
return for_api(save_calibration(DEFAULTS))

View File

@@ -4,4 +4,4 @@ from django.apps import AppConfig
class SlipsConfig(AppConfig): class SlipsConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField' default_auto_field = 'django.db.models.BigAutoField'
name = 'slips' name = 'slips'
verbose_name = 'Lithium Labels' verbose_name = 'Product Slips'

View File

@@ -1,138 +0,0 @@
"""Label field positions (mm / pt). Stored in data/calibration.json."""
from __future__ import annotations
import json
import os
from copy import deepcopy
from pathlib import Path
# Matches prior label_print.css defaults (screen + print).
DEFAULTS = {
'batch': {
'top': 63.0,
'left': 30.2,
'font': 7.0,
'bottom_top': 43.3,
'right_left': 22.2,
},
'date': {
'top': 63.0,
'left': 67.4,
'font': 6.0,
'bottom_top': 43.3,
'bottom_left': 70.4,
},
'next': {
'top': 68.5,
'left': 84.2,
'font': 7.0,
'bottom_top': 48.8,
'bottom_left': 87.2,
},
'weight': {
'top': 68.5,
'left': 37.3,
'font': 7.0,
'bottom_top': 48.8,
'right_left': 29.3,
},
}
FIELDS = ('batch', 'date', 'next', 'weight')
def _data_dir() -> Path:
db_env = os.environ.get('DB_PATH')
if db_env:
return Path(db_env).parent
try:
from django.conf import settings
return Path(settings.BASE_DIR) / 'data'
except Exception:
return Path(__file__).resolve().parents[1] / 'data'
def calibration_path() -> Path:
return _data_dir() / 'calibration.json'
def _merge(base: dict, overlay: dict) -> dict:
out = deepcopy(base)
for field, vals in (overlay or {}).items():
if field not in out or not isinstance(vals, dict):
continue
for key, val in vals.items():
if key in out[field] and isinstance(val, (int, float)):
out[field][key] = float(val)
return out
def load_calibration() -> dict:
path = calibration_path()
if not path.is_file():
return deepcopy(DEFAULTS)
try:
with path.open(encoding='utf-8') as f:
data = json.load(f)
except (OSError, json.JSONDecodeError):
return deepcopy(DEFAULTS)
return _merge(DEFAULTS, data)
def for_api(cal: dict) -> dict:
"""Ensure optional keys are present (null) for API schema."""
out = {}
for field in FIELDS:
v = cal[field]
out[field] = {
'top': v['top'],
'left': v['left'],
'font': v['font'],
'bottom_top': v['bottom_top'],
'bottom_left': v.get('bottom_left'),
'right_left': v.get('right_left'),
}
return out
def save_calibration(data: dict) -> dict:
merged = _merge(DEFAULTS, data)
path = calibration_path()
path.parent.mkdir(parents=True, exist_ok=True)
tmp = path.with_suffix('.tmp')
with tmp.open('w', encoding='utf-8') as f:
json.dump(merged, f, indent=2)
f.write('\n')
tmp.replace(path)
return merged
def css_vars(cal: dict | None = None) -> str:
"""Inline :root block for print + calibrate pages."""
cal = cal or load_calibration()
lines = [':root {']
for field in FIELDS:
v = cal[field]
lines.append(f' --{field}-top: {v["top"]}mm;')
lines.append(f' --{field}-left: {v["left"]}mm;')
lines.append(f' --{field}-font: {v["font"]}pt;')
lines.append(f' --{field}-bottom-top: {v["bottom_top"]}mm;')
if 'bottom_left' in v:
lines.append(f' --{field}-bottom-left: {v["bottom_left"]}mm;')
if 'right_left' in v:
lines.append(f' --{field}-right-left: {v["right_left"]}mm;')
lines.append('}')
return '\n'.join(lines)
# ponytail: assert-based check; upgrade to pytest if suite grows
if __name__ == '__main__':
css = css_vars(DEFAULTS)
assert '--batch-top: 63.0mm;' in css
assert '--date-bottom-left: 70.4mm;' in css
assert '--weight-right-left: 29.3mm;' in css
merged = _merge(DEFAULTS, {'batch': {'top': 64, 'bogus': 1}})
assert merged['batch']['top'] == 64.0
assert 'bogus' not in merged['batch']
assert merged['date']['left'] == DEFAULTS['date']['left']
print('ok')

View File

@@ -1,349 +0,0 @@
"""Customer orders from SystemGroup, dated after REPORT_ORDERS_SINCE.
The cutoff in .env is a Gregorian date. Delivery-note dates on the report
are Jalali, so the cutoff is converted before the comparison.
The host stays in .env. Username and password are supplied per request.
"""
import os
from datetime import date, datetime, timedelta, timezone
from pathlib import Path
_DIGIT_MAP = str.maketrans("۰۱۲۳۴۵۶۷۸۹٠١٢٣٤٥٦٧٨٩", "01234567890123456789")
_ENV_FILE = Path(__file__).resolve().parents[1] / ".env"
_SINCE_KEY = "REPORT_ORDERS_SINCE"
_PREFIX_KEY = "REPORT_ORDERS_PREFIXES"
class CrmOrdersError(RuntimeError):
pass
class CrmAuthError(CrmOrdersError):
"""SystemGroup rejected the username or password."""
# Thirty days. The API refreshes this on each successful fetch.
SESSION_TTL_SECONDS = 30 * 24 * 60 * 60
_AUTH_MARKERS = ("Login appears to have failed", "redirected to login")
def login_rejected(message: str) -> bool:
text = message or ""
return any(marker in text for marker in _AUTH_MARKERS)
def report_base_url() -> str:
"""Shared SystemGroup host. Credentials are not read from the environment."""
base = (_setting("REPORT_BASE_URL") or _setting("CRM_BASE_URL") or "").strip()
if not base:
raise CrmOrdersError("Set REPORT_BASE_URL.")
if not base.endswith("/"):
base += "/"
return base
def parse_jalali(raw: str) -> tuple[int, int, int] | None:
text = (raw or "").translate(_DIGIT_MAP).strip().replace("-", "/")
bits = text.split("/")
if len(bits) != 3 or not all(bit.isdigit() for bit in bits):
return None
year, month, day = (int(bit) for bit in bits)
if year < 1200 or not 1 <= month <= 12 or not 1 <= day <= 31:
return None
return year, month, day
def jalali_from_gregorian(day: date) -> tuple[int, int, int]:
gy, gm, gd = day.year, day.month, day.day
g_days = (0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334)
gy2 = gy + 1 if gm > 2 else gy
days = (
355666
+ 365 * gy
+ (gy2 + 3) // 4
- (gy2 + 99) // 100
+ (gy2 + 399) // 400
+ gd
+ g_days[gm - 1]
)
jy = -1595 + 33 * (days // 12053)
days %= 12053
jy += 4 * (days // 1461)
days %= 1461
if days > 365:
jy += (days - 1) // 365
days = (days - 1) % 365
if days < 186:
jm = 1 + days // 31
jd = 1 + (days % 31)
else:
jm = 7 + (days - 186) // 30
jd = 1 + ((days - 186) % 30)
return jy, jm, jd
def format_jalali(parts: tuple[int, int, int]) -> str:
year, month, day = parts
return f"{year:04d}/{month:02d}/{day:02d}"
def note_date_as_jalali(raw: str) -> str:
parsed = parse_jalali(raw)
if parsed is None:
return (raw or "").strip()
return format_jalali(parsed)
def parse_gregorian(raw: str) -> date | None:
"""Parse YYYY-MM-DD or DD/MM/YYYY. Years before 1700 are rejected."""
text = (raw or "").translate(_DIGIT_MAP).strip().replace("-", "/").replace(".", "/")
bits = text.split("/")
if len(bits) != 3 or not all(bit.isdigit() for bit in bits):
return None
a, b, c = (int(bit) for bit in bits)
if a > 31:
year, month, day = a, b, c
elif c > 31:
day, month, year = a, b, c
else:
return None
if not 1700 <= year <= 2500:
return None
try:
return date(year, month, day)
except ValueError:
return None
def _env_file_value(key: str) -> str | None:
"""Return the value from .env, or None when the key is absent.
An empty value is returned as '' so a blank line is not ignored.
"""
if not _ENV_FILE.is_file():
return None
prefix = key + "="
for raw in _ENV_FILE.read_text(encoding="utf-8").splitlines():
line = raw.strip()
if not line or line.startswith("#") or not line.startswith(prefix):
continue
value = line[len(prefix):].strip()
if len(value) >= 2 and value[0] == value[-1] and value[0] in "\"'":
value = value[1:-1]
return value
return None
def _setting(key: str) -> str | None:
"""Project .env wins so a refresh sees edits; otherwise the process env."""
raw = _env_file_value(key)
if raw is None:
raw = os.environ.get(key)
return raw
def orders_cutoff() -> tuple[date, tuple[int, int, int]]:
"""Gregorian cutoff from .env, plus the same day as a Jalali tuple."""
day = parse_gregorian(_setting(_SINCE_KEY) or "")
if day is None:
raise CrmOrdersError(
"Set REPORT_ORDERS_SINCE in .env to a Gregorian date, e.g. 2026-09-23."
)
return day, jalali_from_gregorian(day)
def parse_prefixes(raw: str | None) -> list[str]:
if not raw:
return []
return [part.strip() for part in raw.split(",") if part.strip()]
def code_prefixes() -> list[str]:
"""Comma-separated product-code prefixes. An empty list keeps every code."""
return parse_prefixes(_setting(_PREFIX_KEY))
def code_matches(code: str, prefixes: list[str]) -> bool:
if not prefixes:
return True
text = (code or "").strip()
return any(text.startswith(prefix) for prefix in prefixes)
def orders_after(lines, start: tuple[int, int, int]):
"""Keep lines whose delivery-note date is strictly after start."""
kept = []
for line in lines:
parsed = parse_jalali(getattr(line, "delivery_note_date", ""))
if parsed is not None and parsed > start:
kept.append(line)
kept.sort(
key=lambda line: (
parse_jalali(line.delivery_note_date),
line.delivery_note_number,
line.product_code,
),
reverse=True,
)
return kept
# SgFilter operator and operand codes from SgFilter.js.
_OP_GREATER = 3
_OP_STARTS = 9
_OP_AND = 2
_OP_OR = 3
_TYPE_STRING = 1
_TYPE_DATE = 3
_TEHRAN = timezone(timedelta(hours=3, minutes=30))
def _condition(name: str, data_type: int, operator: int, value: str, title: str) -> dict:
return {
"type": "FilterCondition",
"filterItemName": name,
"operandDataType": data_type,
"operands": [{"value": value, "title": title}],
"isParameteric": False,
"operator": operator,
}
def report_filter_state(day: date, prefixes: list[str]) -> dict:
"""Server filter: delivery-note date after day, and any product-code prefix."""
moment = datetime(day.year, day.month, day.day, tzinfo=_TEHRAN)
parts = [
_condition(
"ord.Date",
_TYPE_DATE,
_OP_GREATER,
f"/Date({int(moment.timestamp() * 1000)})/",
format_jalali(jalali_from_gregorian(day)),
)
]
codes = [prefix for prefix in prefixes if prefix]
code_conds = [
_condition("pp.code", _TYPE_STRING, _OP_STARTS, code, code)
for code in codes
]
if len(code_conds) == 1:
parts.append(code_conds[0])
elif code_conds:
parts.append({
"type": "FilterLogicalExpression",
"expressions": code_conds,
"operator": _OP_OR,
})
return {
"view": 1,
"expression": {
"type": "FilterLogicalExpression",
"expressions": parts,
"operator": _OP_AND,
},
}
def export_filtered_customer_orders(client, day: date, prefixes: list[str]) -> tuple[str, str]:
"""Run the report with the SgFilter applied, then download the CSV."""
return client.fetch_customer_orders(filter_state=report_filter_state(day, prefixes))
def _restore_cookies(client, cookies) -> None:
"""Reuse a SystemGroup login. A fresh login() would kick out the other session."""
jar = client.session.cookies
for item in cookies:
if not isinstance(item, dict) or not item.get("name"):
continue
jar.set(
item["name"],
item.get("value") or "",
domain=item.get("domain") or None,
path=item.get("path") or "/",
)
client._logged_in = True
def _cookie_dump(client) -> list[dict]:
jar = getattr(getattr(client, "session", None), "cookies", None)
if jar is None:
return []
return [
{"name": cookie.name, "value": cookie.value, "domain": cookie.domain, "path": cookie.path}
for cookie in jar
]
def _load_order_export(client, day: date, prefixes: list[str]) -> tuple[str, str]:
"""Download the full CSV and let the local date and prefix checks drop rows.
A server-side filter re-runs the report after the page has already loaded
(~1.8s) to avoid downloading about 20KB. Direct export is faster.
ponytail: pass filter_state=report_filter_state(day, prefixes) if this
export starts taking more than a couple of seconds.
"""
return client.fetch_customer_orders()
def recent_customer_orders(username: str, password: str, client=None, cookies=None) -> dict:
"""Fetch the store delivery-note report and keep rows after the cutoff.
``cookies`` is a previous SystemGroup login. Reusing it avoids a new login,
which would sign the account out everywhere else.
"""
day, start = orders_cutoff()
prefixes = code_prefixes()
try:
from lithium_systemgroup import (
SystemGroupClient,
SystemGroupClientError,
SystemGroupParseError,
parse_customer_orders_document,
)
except ImportError as exc:
raise CrmOrdersError("lithium-systemgroup is not installed") from exc
try:
if client is None:
client = SystemGroupClient(
base_url=report_base_url(),
username=username,
password=password,
timeout=30,
)
if cookies:
_restore_cookies(client, cookies)
try:
body, content_type = _load_order_export(client, day, prefixes)
except SystemGroupClientError as exc:
if not cookies or "redirected to login" not in str(exc):
raise
client._logged_in = False
client.session.cookies.clear()
body, content_type = _load_order_export(client, day, prefixes)
lines = parse_customer_orders_document(body, content_type=content_type)
except (SystemGroupClientError, SystemGroupParseError) as exc:
text = str(exc)
if login_rejected(text):
raise CrmAuthError("SystemGroup rejected this username or password.") from exc
if text.startswith("Missing required env vars"):
text = "Set REPORT_BASE_URL."
raise CrmOrdersError(text) from exc
kept = [
line for line in orders_after(lines, start)
if code_matches(line.product_code, prefixes)
]
orders = []
for line in kept:
row = line.as_dict()
row["delivery_note_date"] = note_date_as_jalali(row["delivery_note_date"])
orders.append(row)
return {
"since": format_jalali(start),
"orders": orders,
"cookies": _cookie_dump(client),
}

View File

@@ -5,9 +5,9 @@ from slips.models import Product
SEED_PRODUCTS = [ SEED_PRODUCTS = [
{'code': 'ICJ/408', 'description': 'DIGITAL INK RED BROWN', 'default_net_weight': 5}, {'code': 'ICJ/408', 'description': 'DIGITAL INK RED BROWN', 'default_net_weight': 5},
{'code': 'ICJ/407', 'description': 'DIGITAL INK RED BROWN', 'default_net_weight': 5}, {'code': 'ICJ/407', 'description': 'DIGITAL INK RED BROWN', 'default_net_weight': 5},
{'code': 'ICJ/309', 'description': 'DIGITAL INK CYAN', 'default_net_weight': 5}, {'code': 'ICJ/309', 'description': 'DIGITAL INK CYAN', 'default_net_weight': 10},
{'code': 'ICJ/EH630', 'description': 'DIGITAL INK BLACK', 'default_net_weight': 5}, {'code': 'ICJ/EH630', 'description': 'DIGITAL INK BLACK', 'default_net_weight': 5},
{'code': 'ICJ/308', 'description': 'DIGITAL INK BLUE', 'default_net_weight': 5}, {'code': 'ICJ/308', 'description': 'DIGITAL INK BLUE', 'default_net_weight': 20},
] ]
@@ -25,16 +25,10 @@ class Command(BaseCommand):
created_count = 0 created_count = 0
for product_data in SEED_PRODUCTS: for product_data in SEED_PRODUCTS:
if options['skip_existing']: if options['skip_existing']:
product, created = Product.objects.get_or_create( _, created = Product.objects.get_or_create(
code=product_data['code'], code=product_data['code'],
defaults=product_data, defaults=product_data,
) )
if not created:
# Sync seed canister weight without wiping other edits
w = product_data['default_net_weight']
if product.default_net_weight != w:
product.default_net_weight = w
product.save(update_fields=['default_net_weight'])
else: else:
Product.objects.update_or_create( Product.objects.update_or_create(
code=product_data['code'], code=product_data['code'],

View File

@@ -1,39 +0,0 @@
# Generated by Django 5.2.17 on 2026-10-14 08:25
import django.utils.timezone
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('slips', '0002_remove_order_net_weight_remove_order_pages_needed_and_more'),
]
operations = [
migrations.AddField(
model_name='product',
name='requires_dates',
field=models.BooleanField(default=True),
),
migrations.AlterField(
model_name='order',
name='box_count',
field=models.PositiveIntegerField(default=0),
),
migrations.AlterField(
model_name='order',
name='canister_count',
field=models.PositiveIntegerField(default=0),
),
migrations.AlterField(
model_name='order',
name='next_control_date',
field=models.DateField(blank=True, null=True),
),
migrations.AlterField(
model_name='order',
name='production_date',
field=models.DateField(blank=True, default=django.utils.timezone.now, null=True),
),
]

View File

@@ -1,16 +0,0 @@
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('slips', '0003_product_requires_dates_order_dates_nullable'),
]
operations = [
migrations.AddField(
model_name='order',
name='custom_labels',
field=models.JSONField(blank=True, default=list),
),
]

View File

@@ -7,7 +7,6 @@ class Product(models.Model):
code = models.CharField(max_length=50, unique=True) code = models.CharField(max_length=50, unique=True)
description = models.CharField(max_length=200) description = models.CharField(max_length=200)
default_net_weight = models.FloatField(default=5.0) default_net_weight = models.FloatField(default=5.0)
requires_dates = models.BooleanField(default=True)
created_at = models.DateTimeField(auto_now_add=True) created_at = models.DateTimeField(auto_now_add=True)
class Meta: class Meta:
@@ -27,17 +26,15 @@ class Order(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='orders') product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='orders')
batch_number = models.CharField(max_length=50) batch_number = models.CharField(max_length=50)
production_date = models.DateField(default=timezone.now, null=True, blank=True) production_date = models.DateField(default=timezone.now)
next_control_date = models.DateField(null=True, blank=True) next_control_date = models.DateField()
total_weight = models.FloatField(default=0) total_weight = models.FloatField(default=0)
canister_weight = models.FloatField(default=5) canister_weight = models.FloatField(default=5)
canisters_per_box = models.PositiveIntegerField(default=4) canisters_per_box = models.PositiveIntegerField(default=4)
# Label counts (set from weight on create; editable afterwards) # Calculated fields
canister_count = models.PositiveIntegerField(default=0) canister_count = models.PositiveIntegerField(editable=False, default=0)
box_count = models.PositiveIntegerField(default=0) box_count = models.PositiveIntegerField(editable=False, default=0)
# User-defined slips printed before box and canister labels: [{"weight", "count"}]
custom_labels = models.JSONField(default=list, blank=True)
canister_pages = models.PositiveIntegerField(editable=False, default=0) canister_pages = models.PositiveIntegerField(editable=False, default=0)
box_pages = models.PositiveIntegerField(editable=False, default=0) box_pages = models.PositiveIntegerField(editable=False, default=0)
@@ -51,57 +48,9 @@ class Order(models.Model):
def __str__(self): def __str__(self):
return f"Order #{self.id} — {self.product.code} — {self.batch_number}" return f"Order #{self.id} — {self.product.code} — {self.batch_number}"
@property def save(self, *args, **kwargs):
def custom_count(self):
return sum(int(line['count']) for line in (self.custom_labels or []))
@property
def box_weight(self):
return self.canister_weight * self.canisters_per_box
def apply_weight(self):
"""Derive canister/box counts from total_weight (create path)."""
self.canister_count = math.ceil(self.total_weight / self.canister_weight) self.canister_count = math.ceil(self.total_weight / self.canister_weight)
self.box_count = math.ceil(self.canister_count / self.canisters_per_box) self.box_count = math.ceil(self.canister_count / self.canisters_per_box)
self.canister_pages = math.ceil(self.canister_count / 4)
def set_counts(self, canister_count=None, box_count=None): self.box_pages = math.ceil(self.box_count / 4)
"""Edit print quantities only; total_weight stays the packaging truth."""
if canister_count is not None:
self.canister_count = canister_count
if box_count is not None:
self.box_count = box_count
def save(self, *args, **kwargs):
# Mixed sheets: custom + box + canister labels share pages; total in canister_pages
n = self.canister_count + self.box_count + self.custom_count
self.canister_pages = math.ceil(n / 4) if n else 0
self.box_pages = 0
super().save(*args, **kwargs) super().save(*args, **kwargs)
def clean_custom_labels(lines):
"""Normalize [{weight, count}] lines. Empty is valid. Raises ValueError."""
if not lines:
return []
cleaned = []
for line in lines:
if isinstance(line, dict):
weight, count = line.get('weight'), line.get('count')
else:
weight, count = line.weight, line.count
try:
weight = float(weight)
except (TypeError, ValueError):
raise ValueError('custom label weight and count must be numbers')
if isinstance(count, float) and not count.is_integer():
raise ValueError('custom label count must be a whole number')
try:
count = int(count)
except (TypeError, ValueError):
raise ValueError('custom label weight and count must be numbers')
if not math.isfinite(weight) or weight <= 0 or count < 1:
raise ValueError('custom label weight must be > 0 and count >= 1')
if weight.is_integer():
weight = int(weight)
cleaned.append({'weight': weight, 'count': count})
return cleaned

View File

@@ -1,120 +0,0 @@
"""Build print pages: per-slip weights, always 4 slips per page."""
import math
def _display_weight(w):
"""Whole numbers as int (5 not 5.0) for print labels."""
f = float(w)
return int(f) if f.is_integer() else f
def _pad_to_four(weights):
"""Pad short page by repeating the first slip on that page."""
if not weights:
return weights
first = weights[0]
while len(weights) < 4:
weights.append(first)
return weights
def _box_weight_template(order):
"""Box weights from order packaging (total_weight), not print counts."""
if not order.canister_weight or not order.canisters_per_box:
return []
logical_cans = math.ceil(order.total_weight / order.canister_weight)
if not logical_cans:
return []
cans_left = logical_cans
logical_boxes = math.ceil(logical_cans / order.canisters_per_box)
template = []
for _ in range(logical_boxes):
cans_in_box = min(order.canisters_per_box, cans_left)
template.append(_display_weight(order.canister_weight * cans_in_box))
cans_left -= cans_in_box
return template
def _custom_weights(order):
"""User-defined slips. Counts repeat the stored weight; they are not derived."""
weights = []
for line in getattr(order, 'custom_labels', None) or []:
weights.extend([_display_weight(line['weight'])] * int(line['count']))
return weights
def build_print_pages(order):
"""Custom labels, then boxes, then canisters, on shared sheets (pad only last page).
Counts are print quantities. Box and canister weights come from total_weight
packaging, so those steppers do not change label content. Custom weights are
the ones stored on the order.
"""
cw = _display_weight(order.canister_weight)
canister_weights = [cw] * order.canister_count
template = _box_weight_template(order)
if not template:
box_weights = []
else:
box_weights = [template[i % len(template)] for i in range(order.box_count)]
weights = _custom_weights(order) + box_weights + canister_weights
pages = []
for i in range(0, len(weights), 4):
pages.append({
'slips': _pad_to_four(weights[i:i + 4]),
})
return pages
# ponytail: assert-based check; upgrade to pytest if suite grows
if __name__ == '__main__':
class O:
total_weight = 50.0
canister_count = 10
canister_weight = 5.0
canisters_per_box = 4
box_count = 3
custom_labels = []
pages = build_print_pages(O())
assert len(pages) == 4 # 13 labels → 4 mixed pages
assert all(len(p['slips']) == 4 for p in pages)
assert pages[0]['slips'] == [20, 20, 10, 5] # boxes first, then cans
assert all(isinstance(w, int) for w in pages[0]['slips'])
assert pages[1]['slips'] == [5, 5, 5, 5]
assert pages[2]['slips'] == [5, 5, 5, 5]
assert pages[3]['slips'] == [5, 5, 5, 5] # last page full
# Fewer canister labels to print — box weights unchanged
class FewerCans(O):
canister_count = 7
fewer = build_print_pages(FewerCans())
assert fewer[0]['slips'][:3] == [20, 20, 10]
assert len(fewer) == 3 # 3 boxes + 7 cans = 10 → 3 pages
# 3 cans + 1 box → one mixed page
class Small:
total_weight = 15.0
canister_count = 3
canister_weight = 5.0
canisters_per_box = 4
box_count = 1
one = build_print_pages(Small())
assert len(one) == 1
assert one[0]['slips'] == [15, 5, 5, 5]
# Custom slips print first; box and canister weights stay on the packaging recipe
class WithCustom(O):
custom_labels = [{'weight': 8.0, 'count': 1}, {'weight': 1.5, 'count': 1}]
mixed = build_print_pages(WithCustom())
assert mixed[0]['slips'] == [8, 1.5, 20, 20]
assert isinstance(mixed[0]['slips'][0], int)
assert mixed[1]['slips'] == [10, 5, 5, 5]
assert len(mixed) == 4 # 2 custom + 3 boxes + 10 cans = 15 → 4 pages
print('ok')

View File

@@ -1,5 +1,5 @@
from datetime import date from datetime import date
from typing import List, Optional from typing import Optional
from ninja import Schema from ninja import Schema
@@ -8,30 +8,22 @@ class ProductOut(Schema):
code: str code: str
description: str description: str
default_net_weight: float default_net_weight: float
requires_dates: bool
class ProductIn(Schema): class ProductIn(Schema):
code: str code: str
description: str description: str
default_net_weight: float = 5.0 default_net_weight: float = 5.0
requires_dates: bool = True
class CustomLabel(Schema):
weight: float
count: int
class OrderIn(Schema): class OrderIn(Schema):
product_id: int product_id: int
batch_number: str batch_number: str
production_date: Optional[date] = None production_date: date
next_control_date: Optional[date] = None next_control_date: date
total_weight: float total_weight: float
canister_weight: float canister_weight: float
canisters_per_box: int canisters_per_box: int
custom_labels: Optional[List[CustomLabel]] = None
class OrderOut(Schema): class OrderOut(Schema):
@@ -40,14 +32,13 @@ class OrderOut(Schema):
product_code: str product_code: str
product_description: str product_description: str
batch_number: str batch_number: str
production_date: Optional[date] = None production_date: date
next_control_date: Optional[date] = None next_control_date: date
total_weight: float total_weight: float
canister_weight: float canister_weight: float
canisters_per_box: int canisters_per_box: int
canister_count: int canister_count: int
box_count: int box_count: int
custom_labels: List[CustomLabel]
canister_pages: int canister_pages: int
box_pages: int box_pages: int
status: str status: str
@@ -73,53 +64,5 @@ class OrderOut(Schema):
return None return None
class OrderUpdateIn(Schema): class OrderStatusIn(Schema):
status: Optional[str] = None status: str
canister_count: Optional[int] = None
box_count: Optional[int] = None
custom_labels: Optional[List[CustomLabel]] = None
class FieldCalibration(Schema):
top: float
left: float
font: float
bottom_top: float
bottom_left: Optional[float] = None
right_left: Optional[float] = None
class CalibrationIn(Schema):
batch: FieldCalibration
date: FieldCalibration
next: FieldCalibration
weight: FieldCalibration
class CalibrationOut(CalibrationIn):
pass
class CrmOrderOut(Schema):
sales_office: str
customer_name: str
delivery_note_date: str
product_code: str
product_title: str
note_quantity: str
delivered_quantity: str
remaining_quantity: str
warehouse_delivery_date: str
delivery_note_number: str
notes: str
class CrmLoginIn(Schema):
username: str
password: str
class CrmOrdersOut(Schema):
since: str
username: str
orders: List[CrmOrderOut]

Binary file not shown.

Before

Width:  |  Height:  |  Size: 81 KiB

View File

@@ -1,65 +0,0 @@
/* Shared label field layout — positions from CSS vars
* (defaults here; calibrate UI / data/calibration.json override via :root).
*/
.var-field {
position: absolute;
font-family: Arial, sans-serif;
font-weight: bold;
white-space: nowrap;
}
.val-batch {
font-size: var(--batch-font, 7pt);
top: var(--batch-top, 63mm);
left: var(--batch-left, 30.2mm);
}
.val-date {
font-size: var(--date-font, 6pt);
top: var(--date-top, 63mm);
left: var(--date-left, 67.4mm);
}
.val-next {
font-size: var(--next-font, 7pt);
top: var(--next-top, 68.5mm);
left: var(--next-left, 84.2mm);
}
.val-weight {
font-size: var(--weight-font, 7pt);
top: var(--weight-top, 68.5mm);
left: var(--weight-left, 37.3mm);
}
/*
* Bottom row is not at true half-page: PDF vertical pitch between
* matching fields is ~118.8mm (not 148.5mm). Shift bottom slips up.
* Quadrant order in the 2×2 grid: 1=TL, 2=TR, 3=BL, 4=BR.
*/
.slip-quadrant:nth-child(n + 3) .val-batch {
top: var(--batch-bottom-top, 43.3mm);
}
.slip-quadrant:nth-child(n + 3) .val-date {
top: var(--date-bottom-top, 43.3mm);
left: var(--date-bottom-left, 70.4mm);
}
.slip-quadrant:nth-child(n + 3) .val-next {
top: var(--next-bottom-top, 48.8mm);
left: var(--next-bottom-left, 87.2mm);
}
.slip-quadrant:nth-child(n + 3) .val-weight {
top: var(--weight-bottom-top, 48.8mm);
}
/* Right column (TR, BR): Batch# and Net weight */
.slip-quadrant:nth-child(2n) .val-batch {
left: var(--batch-right-left, 22.2mm);
}
.slip-quadrant:nth-child(2n) .val-weight {
left: var(--weight-right-left, 29.3mm);
}

View File

@@ -1,75 +1,19 @@
/* Base Variables — light default: vivid coral + cool slate */ /* Base Variables */
:root { :root {
--brand: #f43f5e;
--brand-hover: #e11d48;
--brand-soft: rgba(244, 63, 94, 0.12);
--bg-primary: #f4f6f8;
--bg-secondary: #ffffff;
--bg-glass: rgba(255, 255, 255, 0.92);
--bg-input: #f8fafc;
--bg-muted: rgba(15, 23, 42, 0.04);
--bg-hover: rgba(15, 23, 42, 0.06);
--bg-inset: #e2e8f0;
--bg-glow-a: rgba(244, 63, 94, 0.07);
--bg-glow-b: rgba(100, 116, 139, 0.1);
--bg-dot: rgba(15, 23, 42, 0.055);
--accent: var(--brand);
--accent-glow: #fb7185;
--accent-soft: var(--brand-soft);
--success: #059669;
--warning: #d97706;
--danger: #e11d48;
--text-primary: #0f172a;
--text-secondary: #64748b;
--border: rgba(15, 23, 42, 0.1);
--shadow: rgba(15, 23, 42, 0.1);
--navbar-bg: var(--brand);
--navbar-fg: #ffffff;
--navbar-muted: rgba(255, 255, 255, 0.8);
--navbar-accent: #ffffff;
--navbar-border: transparent;
--navbar-hover: rgba(255, 255, 255, 0.16);
--font-sans: 'Inter', sans-serif;
--font-fa: 'Vazirmatn', sans-serif;
--font-mono: 'JetBrains Mono', monospace;
--content-max: 1200px;
}
[data-theme="dark"] {
--brand: #3b82f6;
--brand-hover: #2563eb;
--brand-soft: rgba(59, 130, 246, 0.12);
--bg-primary: #0f172a; --bg-primary: #0f172a;
--bg-secondary: #1e293b; --bg-secondary: #1e293b;
--bg-glass: rgba(30, 41, 59, 0.7); --bg-glass: rgba(30, 41, 59, 0.7);
--bg-input: rgba(15, 23, 42, 0.5); --accent: #3b82f6;
--bg-muted: rgba(0, 0, 0, 0.2);
--bg-hover: rgba(255, 255, 255, 0.05);
--bg-inset: rgba(15, 23, 42, 0.4);
--bg-glow-a: rgba(59, 130, 246, 0.12);
--bg-glow-b: rgba(15, 23, 42, 0.5);
--bg-dot: rgba(148, 163, 184, 0.08);
--accent: var(--brand);
--accent-glow: #60a5fa; --accent-glow: #60a5fa;
--accent-soft: var(--brand-soft);
--success: #10b981; --success: #10b981;
--warning: #f59e0b; --warning: #f59e0b;
--danger: #ef4444; --danger: #ef4444;
--text-primary: #f1f5f9; --text-primary: #f1f5f9;
--text-secondary: #94a3b8; --text-secondary: #94a3b8;
--border: rgba(148, 163, 184, 0.1); --border: rgba(148, 163, 184, 0.1);
--shadow: rgba(0, 0, 0, 0.3);
--navbar-bg: var(--bg-glass); --font-sans: 'Inter', sans-serif;
--navbar-fg: var(--text-primary); --font-mono: 'JetBrains Mono', monospace;
--navbar-muted: var(--text-secondary);
--navbar-accent: var(--accent);
--navbar-border: var(--border);
--navbar-hover: rgba(255, 255, 255, 0.05);
} }
/* Reset & Base */ /* Reset & Base */
@@ -79,53 +23,31 @@
box-sizing: border-box; box-sizing: border-box;
} }
html {
color-scheme: light;
}
html[data-theme="dark"] {
color-scheme: dark;
}
body { body {
font-family: var(--font-sans); font-family: var(--font-sans);
background-color: var(--bg-primary); background-color: var(--bg-primary);
background-image:
radial-gradient(circle at 1px 1px, var(--bg-dot) 1px, transparent 0),
radial-gradient(900px 520px at 8% -12%, var(--bg-glow-a), transparent 55%),
radial-gradient(800px 480px at 100% 0%, var(--bg-glow-b), transparent 50%);
background-size: 22px 22px, auto, auto;
background-attachment: fixed;
color: var(--text-primary); color: var(--text-primary);
line-height: 1.5; line-height: 1.5;
min-height: 100vh; min-height: 100vh;
} }
html[lang="fa"] body {
font-family: var(--font-fa);
}
.mono { .mono {
font-family: var(--font-mono); font-family: var(--font-mono);
} }
/* Navigation */ /* Navigation */
.navbar { .navbar {
background: var(--navbar-bg); background: var(--bg-glass);
backdrop-filter: blur(12px); backdrop-filter: blur(12px);
-webkit-backdrop-filter: blur(12px); -webkit-backdrop-filter: blur(12px);
border-bottom: 1px solid var(--navbar-border); border-bottom: 1px solid var(--border);
position: sticky; position: sticky;
top: 0; top: 0;
z-index: 50; z-index: 50;
overflow: hidden;
view-transition-name: navbar;
} }
.nav-container { .nav-container {
position: relative; max-width: 1200px;
z-index: 1;
max-width: var(--content-max);
margin: 0 auto; margin: 0 auto;
padding: 1rem 2rem; padding: 1rem 2rem;
display: flex; display: flex;
@@ -133,47 +55,23 @@ html[lang="fa"] body {
align-items: center; align-items: center;
} }
@media (max-width: 800px) {
.navbar {
overflow: visible;
}
.nav-container {
flex-wrap: wrap;
padding: 0.75rem 1rem;
gap: 0.5rem 1rem;
}
.nav-links,
.nav-setup {
gap: 1rem;
}
}
.nav-logo { .nav-logo {
display: flex; display: flex;
align-items: center; align-items: center;
gap: 0.75rem; gap: 0.75rem;
text-decoration: none; text-decoration: none;
color: var(--navbar-fg); color: var(--text-primary);
font-weight: 700; font-weight: 700;
font-size: 1.25rem; font-size: 1.25rem;
} }
.logo-icon {
width: 32px;
height: 32px;
object-fit: contain;
border-radius: 6px;
flex-shrink: 0;
}
.nav-links { .nav-links {
display: flex; display: flex;
gap: 2rem; gap: 2rem;
} }
.nav-link { .nav-link {
position: relative; color: var(--text-secondary);
color: var(--navbar-muted);
text-decoration: none; text-decoration: none;
font-weight: 500; font-weight: 500;
transition: color 0.2s; transition: color 0.2s;
@@ -181,118 +79,23 @@ html[lang="fa"] body {
} }
.nav-link:hover, .nav-link.active { .nav-link:hover, .nav-link.active {
color: var(--navbar-fg); color: var(--text-primary);
} }
.nav-link.active::after { .nav-link.active {
content: ""; border-bottom: 2px solid var(--accent);
position: absolute;
left: 0;
right: 0;
bottom: 0;
height: 2px;
background: var(--navbar-accent);
border-radius: 2px;
view-transition-name: nav-indicator;
}
.nav-setup {
display: flex;
align-items: center;
gap: 2rem;
margin-inline-end: 1rem;
}
.nav-actions {
display: flex;
align-items: center;
gap: 0.5rem;
}
.nav-actions .btn-ghost {
color: var(--navbar-muted);
border-color: color-mix(in srgb, var(--navbar-fg) 22%, transparent);
}
.nav-actions .btn-ghost:hover {
background: var(--navbar-hover);
color: var(--navbar-fg);
}
.lang-label {
display: inline-flex;
align-items: center;
gap: 0.35rem;
}
.lang-flag {
width: 1.15em;
height: 0.85em;
border-radius: 2px;
box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.15);
flex-shrink: 0;
} }
/* Layout */ /* Layout */
@media (min-width: 1400px) {
:root {
--content-max: 1600px;
}
}
@media (min-width: 1800px) {
:root {
--content-max: 1800px;
}
}
.main-content { .main-content {
max-width: var(--content-max); max-width: 1200px;
margin: 2rem auto; margin: 2rem auto;
padding: 0 2rem; padding: 0 2rem;
view-transition-name: main;
}
@view-transition {
navigation: auto;
}
::view-transition-group(navbar),
::view-transition-old(navbar),
::view-transition-new(navbar) {
animation: none;
}
::view-transition-old(main) {
animation: 180ms ease both main-leave;
}
::view-transition-new(main) {
animation: 180ms ease both main-enter;
}
@keyframes main-leave {
to {
opacity: 0;
}
}
@keyframes main-enter {
from {
opacity: 0;
transform: translateY(6px);
}
}
@media (prefers-reduced-motion: reduce) {
@view-transition {
navigation: none;
}
} }
.page-grid { .page-grid {
display: grid; display: grid;
grid-template-columns: minmax(280px, 1fr) minmax(0, 2fr); grid-template-columns: 1fr 1.5fr;
gap: 2rem; gap: 2rem;
align-items: start; align-items: start;
} }
@@ -314,7 +117,7 @@ html[lang="fa"] body {
background: var(--bg-glass); background: var(--bg-glass);
backdrop-filter: blur(16px); backdrop-filter: blur(16px);
-webkit-backdrop-filter: blur(16px); -webkit-backdrop-filter: blur(16px);
box-shadow: 0 4px 16px -4px var(--shadow), 0 2px 4px -2px var(--shadow); box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
} }
.card-header { .card-header {
@@ -325,42 +128,11 @@ html[lang="fa"] body {
align-items: center; align-items: center;
} }
.card-actions {
display: flex;
align-items: center;
gap: 0.75rem;
}
.form-actions-inline {
display: flex;
gap: 0.75rem;
flex-wrap: wrap;
}
.card-title { .card-title {
font-size: 1.25rem; font-size: 1.25rem;
font-weight: 600; font-weight: 600;
} }
.card-header-wrap {
flex-wrap: wrap;
gap: 0.75rem;
}
.card-header-wrap > div:first-child {
flex: 1 1 16rem;
}
.card-subtitle {
margin-top: 0.25rem;
color: var(--text-secondary);
font-size: 0.875rem;
}
.card-subtitle .mono {
margin-inline-start: 0.35rem;
}
/* Forms */ /* Forms */
form { form {
padding: 1.5rem; padding: 1.5rem;
@@ -378,120 +150,6 @@ form {
gap: 1rem; gap: 1rem;
} }
.custom-lines {
display: flex;
flex-direction: column;
gap: 0.5rem;
}
.custom-line {
display: flex;
gap: 0.5rem;
align-items: center;
}
.custom-line input {
flex: 1;
}
.custom-line .btn {
flex: none;
width: 2.5rem;
padding-left: 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 {
align-self: flex-start;
}
.custom-label-list {
display: flex;
flex-direction: column;
gap: 0.35rem;
align-items: flex-start;
}
.form-group { .form-group {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
@@ -499,19 +157,6 @@ jdp-container {
min-width: 0; min-width: 0;
} }
.checkbox-label {
display: flex;
align-items: center;
gap: 0.5rem;
cursor: pointer;
}
.checkbox-label input[type="checkbox"] {
width: auto;
min-width: 0;
padding: 0;
}
label { label {
font-size: 0.875rem; font-size: 0.875rem;
font-weight: 500; font-weight: 500;
@@ -522,7 +167,7 @@ input, select {
width: 100%; width: 100%;
min-width: 0; min-width: 0;
box-sizing: border-box; box-sizing: border-box;
background: var(--bg-input); background: rgba(15, 23, 42, 0.5);
border: 1px solid var(--border); border: 1px solid var(--border);
color: var(--text-primary); color: var(--text-primary);
padding: 0.75rem 1rem; padding: 0.75rem 1rem;
@@ -535,24 +180,20 @@ input, select {
input:focus, select:focus { input:focus, select:focus {
outline: none; outline: none;
border-color: var(--accent); border-color: var(--accent);
box-shadow: 0 0 0 2px var(--accent-soft); box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.2);
} }
.computed-value { .computed-value {
padding: 0.75rem 1rem; padding: 0.75rem 1rem;
background: var(--accent-soft); background: rgba(59, 130, 246, 0.1);
border-radius: 6px; border-radius: 6px;
color: var(--brand-hover); color: var(--accent-glow);
font-weight: 600; font-weight: 600;
font-family: var(--font-mono); font-family: var(--font-mono);
} }
[data-theme="dark"] .computed-value {
color: var(--accent-glow);
}
.sub-panel { .sub-panel {
background: var(--bg-muted); background: rgba(0, 0, 0, 0.2);
padding: 1rem; padding: 1rem;
border-radius: 8px; border-radius: 8px;
margin-top: 0.5rem; margin-top: 0.5rem;
@@ -579,11 +220,6 @@ input:focus, select:focus {
font-size: 0.875rem; font-size: 0.875rem;
} }
.btn:disabled {
opacity: 0.6;
cursor: wait;
}
.btn-lg { .btn-lg {
padding: 1rem 2rem; padding: 1rem 2rem;
font-size: 1.125rem; font-size: 1.125rem;
@@ -595,15 +231,15 @@ input:focus, select:focus {
} }
.btn-accent:hover { .btn-accent:hover {
background: var(--brand-hover); background: #2563eb;
} }
.btn-glow { .btn-glow {
box-shadow: 0 0 15px color-mix(in srgb, var(--accent) 40%, transparent); box-shadow: 0 0 15px rgba(59, 130, 246, 0.4);
} }
.btn-glow:hover { .btn-glow:hover {
box-shadow: 0 0 25px color-mix(in srgb, var(--accent) 60%, transparent); box-shadow: 0 0 25px rgba(59, 130, 246, 0.6);
transform: translateY(-1px); transform: translateY(-1px);
} }
@@ -614,7 +250,7 @@ input:focus, select:focus {
} }
.btn-ghost:hover { .btn-ghost:hover {
background: var(--bg-hover); background: rgba(255, 255, 255, 0.05);
color: var(--text-primary); color: var(--text-primary);
} }
@@ -632,114 +268,22 @@ input:focus, select:focus {
overflow-x: auto; overflow-x: auto;
} }
.table-wrap-capped {
max-height: calc(100dvh - 10rem);
overflow: auto;
}
/* width:1% shrinks the column to its content; nowrap keeps "20 kg × 15" on one line. */
.labels-cell {
width: 1%;
white-space: nowrap;
}
.label-counts {
display: inline-flex;
flex-direction: column;
align-items: stretch;
gap: 0.35rem;
vertical-align: middle;
}
.label-counts > .count-stepper,
.label-counts > .mono,
.label-counts > [id^="custom-"],
.label-counts .custom-label-list,
.label-counts .custom-label-list .count-stepper,
.label-counts .custom-label-list .mono {
width: 100%;
box-sizing: border-box;
}
.label-counts > [id^="custom-"]:empty {
display: none;
}
.label-counts > [id^="custom-"],
.label-counts .custom-label-list {
display: flex;
flex-direction: column;
align-items: stretch;
gap: 0.35rem;
}
.label-counts .count-stepper {
display: grid;
grid-template-columns: minmax(max-content, 1fr) 1.5rem 2.25rem 1.5rem;
align-items: center;
justify-items: center;
gap: 0.35rem;
}
.label-counts .count-stepper,
.label-counts .mono {
direction: ltr;
unicode-bidi: isolate;
white-space: nowrap;
}
.label-counts .count-stepper .stepper-label {
justify-self: start;
margin-inline-start: 0;
white-space: nowrap;
}
.status-cell {
white-space: nowrap;
}
.status-cell .badge + .badge,
.status-cell .badge + button.badge {
margin-inline-start: 0.35rem;
}
button.badge {
cursor: pointer;
font: inherit;
font-size: 0.75rem;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.05em;
}
button.badge:hover {
filter: brightness(0.92);
}
.data-table { .data-table {
width: 100%; width: 100%;
border-collapse: collapse; border-collapse: collapse;
text-align: start; text-align: left;
} }
.data-table th, .data-table td { .data-table th, .data-table td {
padding: 0.85rem 1rem; padding: 1rem 1.5rem;
border-bottom: 1px solid var(--border); border-bottom: 1px solid var(--border);
text-align: start;
vertical-align: middle;
}
@media (min-width: 1400px) {
.data-table th, .data-table td {
padding: 1rem 1.25rem;
}
} }
.data-table th { .data-table th {
font-weight: 500; font-weight: 500;
color: var(--text-secondary); color: var(--text-secondary);
font-size: 0.875rem; font-size: 0.875rem;
background: var(--bg-muted); background: rgba(0, 0, 0, 0.2);
} }
.data-table tbody tr { .data-table tbody tr {
@@ -747,34 +291,7 @@ button.badge:hover {
} }
.data-table tbody tr:hover { .data-table tbody tr:hover {
background: var(--bg-hover); background: rgba(255, 255, 255, 0.02);
}
.data-table tbody tr.row-new {
background: color-mix(in srgb, var(--success) 16%, transparent);
}
.data-table tr.group-row td {
background: var(--bg-muted);
font-weight: 600;
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 {
color: var(--accent);
font-weight: 600;
text-decoration: none;
}
a.code-link:hover {
text-decoration: underline;
} }
.empty-state { .empty-state {
@@ -788,7 +305,6 @@ a.code-link:hover {
.badge { .badge {
display: inline-flex; display: inline-flex;
align-items: center; align-items: center;
gap: 0.25em;
padding: 0.25rem 0.75rem; padding: 0.25rem 0.75rem;
border-radius: 999px; border-radius: 999px;
font-size: 0.75rem; font-size: 0.75rem;
@@ -797,16 +313,14 @@ a.code-link:hover {
letter-spacing: 0.05em; letter-spacing: 0.05em;
} }
.badge-pending { background: rgba(239, 68, 68, 0.1); color: var(--danger); border: 1px solid rgba(239, 68, 68, 0.2); } .badge-pending { background: rgba(245, 158, 11, 0.1); color: var(--warning); border: 1px solid rgba(245, 158, 11, 0.2); }
.badge-done { background: rgba(16, 185, 129, 0.1); color: var(--success); border: 1px solid rgba(16, 185, 129, 0.2); } .badge-done { background: rgba(16, 185, 129, 0.1); color: var(--success); border: 1px solid rgba(16, 185, 129, 0.2); }
.badge-cancelled { background: rgba(239, 68, 68, 0.1); color: var(--danger); border: 1px solid rgba(239, 68, 68, 0.2); } .badge-cancelled { background: rgba(239, 68, 68, 0.1); color: var(--danger); border: 1px solid rgba(239, 68, 68, 0.2); }
.badge-accent { background: var(--accent-soft); color: var(--brand-hover); border: 1px solid color-mix(in srgb, var(--accent) 30%, transparent); } .badge-accent { background: rgba(59, 130, 246, 0.1); color: var(--accent-glow); border: 1px solid rgba(59, 130, 246, 0.2); }
.badge-neutral { background: rgba(255, 255, 255, 0.05); color: var(--text-secondary); border: 1px solid var(--border); }
[data-theme="dark"] .badge-accent { color: var(--accent-glow); }
.badge-neutral { background: var(--bg-hover); color: var(--text-secondary); border: 1px solid var(--border); }
.card-badge { .card-badge {
background: var(--bg-muted); background: rgba(0,0,0,0.3);
padding: 0.25rem 0.75rem; padding: 0.25rem 0.75rem;
border-radius: 999px; border-radius: 999px;
font-size: 0.875rem; font-size: 0.875rem;
@@ -822,98 +336,14 @@ a.code-link:hover {
} }
.queue-item { .queue-item {
background: var(--bg-inset); background: rgba(15, 23, 42, 0.4);
transition: transform 0.2s, box-shadow 0.2s; transition: transform 0.2s, box-shadow 0.2s;
} }
.queue-item:hover { .queue-item:hover {
transform: translateY(-2px); transform: translateY(-2px);
box-shadow: 0 10px 15px -3px var(--shadow); box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.3);
border-color: color-mix(in srgb, var(--accent) 40%, transparent); border-color: rgba(59, 130, 246, 0.3);
}
/* Light: coral chrome + side graphic */
[data-theme="light"] .navbar,
[data-theme="light"] .card-header {
background: var(--brand);
}
[data-theme="light"] .card-header {
position: relative;
overflow: hidden;
color: var(--navbar-fg);
border-bottom-color: transparent;
}
[data-theme="light"] .card-header .card-title,
[data-theme="light"] .card-header .card-badge {
position: relative;
z-index: 1;
}
[data-theme="light"] .card-header .card-title {
color: var(--navbar-fg);
}
[data-theme="light"] .card-badge {
background: rgba(255, 255, 255, 0.22);
color: #fff;
}
[data-theme="light"] .badge-accent {
color: var(--brand-hover);
}
/* Modern side graphic: angled glaze + pixel grid */
[data-theme="light"] .navbar::before,
[data-theme="light"] .card-header::before {
content: "";
position: absolute;
inset-inline-end: 0;
top: 0;
bottom: 0;
width: 10rem;
background: linear-gradient(
112deg,
transparent 0 42%,
rgba(255, 255, 255, 0.1) 42% 68%,
transparent 68%
);
pointer-events: none;
}
[data-theme="light"] .navbar::after,
[data-theme="light"] .card-header::after {
content: "";
position: absolute;
inset-inline-end: 0.85rem;
top: 50%;
width: 3.75rem;
height: 3.75rem;
translate: 0 -50%;
background-image:
linear-gradient(rgba(255, 255, 255, 0.28) 1px, transparent 1px),
linear-gradient(90deg, rgba(255, 255, 255, 0.28) 1px, transparent 1px);
background-size: 9px 9px;
background-position: center;
mask-image: linear-gradient(to left, #000 10%, transparent);
opacity: 0.85;
pointer-events: none;
}
html[dir="rtl"][data-theme="light"] .navbar::before,
html[dir="rtl"][data-theme="light"] .card-header::before {
background: linear-gradient(
-112deg,
transparent 0 42%,
rgba(255, 255, 255, 0.1) 42% 68%,
transparent 68%
);
}
html[dir="rtl"][data-theme="light"] .navbar::after,
html[dir="rtl"][data-theme="light"] .card-header::after {
mask-image: linear-gradient(to right, #000 10%, transparent);
} }
.queue-item-header { .queue-item-header {
@@ -922,7 +352,7 @@ html[dir="rtl"][data-theme="light"] .card-header::after {
align-items: center; align-items: center;
padding: 1rem 1.5rem; padding: 1rem 1.5rem;
border-bottom: 1px solid var(--border); border-bottom: 1px solid var(--border);
background: var(--bg-muted); background: rgba(0, 0, 0, 0.2);
} }
.queue-item-body { .queue-item-body {
@@ -963,51 +393,11 @@ html[dir="rtl"][data-theme="light"] .card-header::after {
margin-top: 1rem; margin-top: 1rem;
padding-top: 1rem; padding-top: 1rem;
border-top: 1px solid var(--border); border-top: 1px solid var(--border);
flex-wrap: wrap;
align-items: center;
}
.count-stepper {
display: inline-flex;
align-items: center;
gap: 0.35rem;
padding: 0.2rem 0.5rem;
border: 1px solid var(--border);
border-radius: 6px;
background: var(--bg-muted);
font-variant-numeric: tabular-nums;
}
.count-stepper .stepper-label {
font-size: 0.75rem;
color: var(--text-secondary);
margin-inline-start: 0.15rem;
}
.stepper-btn {
width: 1.5rem;
height: 1.5rem;
padding: 0;
border: 1px solid var(--border);
border-radius: 4px;
background: var(--bg-secondary);
color: var(--text-primary);
cursor: pointer;
font-size: 1rem;
line-height: 1;
display: inline-flex;
align-items: center;
justify-content: center;
}
.stepper-btn:hover {
background: var(--bg-hover);
border-color: var(--accent);
} }
.queue-item-actions { .queue-item-actions {
padding: 1rem 1.5rem; padding: 1rem 1.5rem;
background: var(--bg-muted); background: rgba(0, 0, 0, 0.2);
border-top: 1px solid var(--border); border-top: 1px solid var(--border);
display: flex; display: flex;
gap: 1rem; gap: 1rem;
@@ -1023,24 +413,18 @@ html[dir="rtl"][data-theme="light"] .card-header::after {
bottom: 2rem; bottom: 2rem;
right: 2rem; right: 2rem;
background: var(--bg-secondary); background: var(--bg-secondary);
color: var(--text-primary); color: white;
padding: 1rem 1.5rem; padding: 1rem 1.5rem;
border-radius: 8px; border-radius: 8px;
box-shadow: 0 10px 15px -3px var(--shadow); box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.3);
border-left: 4px solid var(--accent); border-left: 4px solid var(--accent);
transform: translateY(calc(100% + 2rem)); transform: translateY(150%);
opacity: 0; transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1);
visibility: hidden;
pointer-events: none;
transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1), opacity 0.3s, visibility 0.3s;
z-index: 100; z-index: 100;
} }
.toast.show { .toast.show {
transform: translateY(0); transform: translateY(0);
opacity: 1;
visibility: visible;
pointer-events: auto;
} }
.toast.error { .toast.error {
@@ -1048,13 +432,6 @@ html[dir="rtl"][data-theme="light"] .card-header::after {
} }
/* RTL Support for Persian */ /* RTL Support for Persian */
html[dir="rtl"] .toast { html[dir="rtl"] {
right: auto; /* Kept LTR as requested by user, but framework is ready if they change their mind */
left: 2rem;
border-left: none;
border-right: 4px solid var(--accent);
}
html[dir="rtl"] .toast.error {
border-right-color: var(--danger);
} }

View File

@@ -1,349 +0,0 @@
(() => {
const FIELDS = ['batch', 'date', 'next', 'weight'];
const LABELS = { batch: 'Batch', date: 'Date', next: 'Next control', weight: 'Weight' };
const TOP_KEYS = [
{ key: 'top', label: 'top' },
{ key: 'left', label: 'left' },
{ key: 'font', label: 'font pt' },
];
const BOTTOM_KEYS = {
batch: [{ key: 'bottom_top', label: 'top' }],
date: [
{ key: 'bottom_top', label: 'top' },
{ key: 'bottom_left', label: 'left' },
],
next: [
{ key: 'bottom_top', label: 'top' },
{ key: 'bottom_left', label: 'left' },
],
weight: [{ key: 'bottom_top', label: 'top' }],
};
const RIGHT_KEYS = {
batch: [{ key: 'right_left', label: 'left' }],
weight: [{ key: 'right_left', label: 'left' }],
};
const dataEl = document.getElementById('calibration-data');
let state = JSON.parse(dataEl.textContent);
let saved = structuredClone(state);
let selected = { field: 'batch', section: 'top' };
const statusEl = document.getElementById('status');
const stepEl = document.getElementById('step');
const varsEl = document.getElementById('calibration-vars');
function round1(n) {
return Math.round(Number(n) * 10) / 10;
}
function isDirty() {
return JSON.stringify(state) !== JSON.stringify(saved);
}
function setStatus(msg, kind) {
statusEl.textContent = msg;
statusEl.className = 'status' + (kind ? ' ' + kind : '');
}
function cssFromState(cal) {
const lines = [':root {'];
for (const field of FIELDS) {
const v = cal[field];
lines.push(` --${field}-top: ${v.top}mm;`);
lines.push(` --${field}-left: ${v.left}mm;`);
lines.push(` --${field}-font: ${v.font}pt;`);
lines.push(` --${field}-bottom-top: ${v.bottom_top}mm;`);
if (v.bottom_left != null) lines.push(` --${field}-bottom-left: ${v.bottom_left}mm;`);
if (v.right_left != null) lines.push(` --${field}-right-left: ${v.right_left}mm;`);
}
lines.push('}');
return lines.join('\n');
}
function applyLive() {
varsEl.textContent = cssFromState(state);
if (isDirty()) setStatus('Unsaved changes', 'dirty');
else setStatus('Saved', 'ok');
syncInputs();
highlightSelected();
}
function step() {
const s = parseFloat(stepEl.value);
return Number.isFinite(s) && s > 0 ? s : 0.5;
}
function setValue(field, key, value) {
if (!(key in state[field])) return;
let v = round1(value);
if (key === 'font') v = Math.max(4, Math.min(20, v));
else v = Math.max(0, Math.min(150, v));
state[field][key] = v;
applyLive();
}
function nudge(field, key, dir) {
setValue(field, key, state[field][key] + dir * step());
}
function makeNudgeRow(field, key, label) {
const row = document.createElement('div');
row.className = 'nudge';
row.dataset.field = field;
row.dataset.key = key;
const lab = document.createElement('label');
lab.textContent = label;
const input = document.createElement('input');
input.type = 'number';
input.step = '0.1';
input.value = state[field][key];
input.addEventListener('change', () => setValue(field, key, input.value));
const minus = document.createElement('button');
minus.type = 'button';
minus.textContent = '−';
minus.addEventListener('click', () => nudge(field, key, -1));
const plus = document.createElement('button');
plus.type = 'button';
plus.textContent = '+';
plus.addEventListener('click', () => nudge(field, key, 1));
row.append(lab, input, minus, plus);
return row;
}
function makeFieldBlock(field, keys, section) {
const block = document.createElement('div');
block.className = 'field-block';
block.dataset.field = field;
block.dataset.section = section;
const h = document.createElement('h3');
h.textContent = LABELS[field];
block.appendChild(h);
for (const { key, label } of keys) {
if (state[field][key] == null) continue;
block.appendChild(makeNudgeRow(field, key, label));
}
block.addEventListener('click', () => {
selected = { field, section };
highlightSelected();
});
return block;
}
function buildPanel() {
const top = document.getElementById('sec-top');
const bottom = document.getElementById('sec-bottom');
const right = document.getElementById('sec-right');
for (const field of FIELDS) {
top.appendChild(makeFieldBlock(field, TOP_KEYS, 'top'));
if (BOTTOM_KEYS[field]) {
bottom.appendChild(makeFieldBlock(field, BOTTOM_KEYS[field], 'bottom'));
}
if (RIGHT_KEYS[field]) {
right.appendChild(makeFieldBlock(field, RIGHT_KEYS[field], 'right'));
}
}
}
function syncInputs() {
document.querySelectorAll('.nudge').forEach((row) => {
const field = row.dataset.field;
const key = row.dataset.key;
const input = row.querySelector('input');
if (input && document.activeElement !== input) {
input.value = state[field][key];
}
});
}
function highlightSelected() {
document.querySelectorAll('.field-block').forEach((el) => {
el.classList.toggle(
'active',
el.dataset.field === selected.field && el.dataset.section === selected.section
);
});
document.querySelectorAll('.var-field').forEach((el) => {
const q = el.dataset.scope;
const field = el.dataset.field;
let match = field === selected.field;
if (selected.section === 'top') {
match = match && (q === 'TL' || q === 'TR');
} else if (selected.section === 'bottom') {
match = match && (q === 'BL' || q === 'BR');
} else if (selected.section === 'right') {
match = match && (q === 'TR' || q === 'BR');
}
el.classList.toggle('selected', match);
});
}
function payloadFromState() {
// API schema expects all keys; optional ones may be null
const out = {};
for (const field of FIELDS) {
out[field] = {
top: state[field].top,
left: state[field].left,
font: state[field].font,
bottom_top: state[field].bottom_top,
bottom_left: state[field].bottom_left ?? null,
right_left: state[field].right_left ?? null,
};
}
return out;
}
async function save() {
const btn = document.getElementById('btn-save');
btn.disabled = true;
try {
const res = await fetch('/api/calibration', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payloadFromState()),
});
if (!res.ok) throw new Error('HTTP ' + res.status);
state = await res.json();
saved = structuredClone(state);
applyLive();
setStatus('Saved to server', 'ok');
return true;
} catch (e) {
setStatus('Save failed: ' + e.message, 'err');
return false;
} finally {
btn.disabled = false;
}
}
async function reset() {
if (!confirm('Reset all positions to built-in defaults?')) return;
try {
const res = await fetch('/api/calibration/reset', { method: 'POST' });
if (!res.ok) throw new Error('HTTP ' + res.status);
state = await res.json();
saved = structuredClone(state);
applyLive();
setStatus('Defaults restored', 'ok');
} catch (e) {
setStatus('Reset failed: ' + e.message, 'err');
}
}
function backup() {
const blob = new Blob([JSON.stringify(payloadFromState(), null, 2) + '\n'], {
type: 'application/json',
});
const a = document.createElement('a');
const d = new Date();
const stamp = [
d.getFullYear(),
String(d.getMonth() + 1).padStart(2, '0'),
String(d.getDate()).padStart(2, '0'),
].join('');
a.href = URL.createObjectURL(blob);
a.download = `label-print-calibration-${stamp}.json`;
a.click();
URL.revokeObjectURL(a.href);
setStatus('Backup downloaded', 'ok');
}
function parseCalibrationFile(raw) {
const data = typeof raw === 'string' ? JSON.parse(raw) : raw;
if (!data || typeof data !== 'object') throw new Error('invalid file');
const required = ['top', 'left', 'font', 'bottom_top'];
for (const field of FIELDS) {
const v = data[field];
if (!v || typeof v !== 'object') throw new Error('missing ' + field);
for (const key of required) {
if (!Number.isFinite(Number(v[key]))) throw new Error(field + '.' + key);
}
}
return data;
}
async function restoreFromFile(file) {
try {
const data = parseCalibrationFile(await file.text());
if (!confirm('Replace current calibration with this file and save to server?')) return;
state = data;
applyLive();
if (await save()) setStatus('Restored from file', 'ok');
} catch (e) {
setStatus('Restore failed: ' + e.message, 'err');
}
}
document.querySelectorAll('.var-field').forEach((el) => {
el.addEventListener('click', () => {
const q = el.dataset.scope;
const field = el.dataset.field;
let section = 'top';
if ((q === 'TR' || q === 'BR') && (field === 'batch' || field === 'weight')) {
section = 'right';
} else if (q === 'BL' || q === 'BR') {
section = 'bottom';
}
selected = { field, section };
const block = document.querySelector(
`.field-block[data-field="${field}"][data-section="${section}"]`
);
if (block) block.scrollIntoView({ block: 'nearest', behavior: 'smooth' });
highlightSelected();
});
});
document.addEventListener('keydown', (e) => {
if (e.target.matches('input, textarea')) return;
const map = {
ArrowLeft: ['leftish', -1],
ArrowRight: ['leftish', 1],
ArrowUp: ['topish', -1],
ArrowDown: ['topish', 1],
};
const hit = map[e.key];
if (!hit) return;
e.preventDefault();
const [axis, dir] = hit;
const { field, section } = selected;
let key;
if (section === 'top') {
key = axis === 'topish' ? 'top' : 'left';
} else if (section === 'bottom') {
key = axis === 'topish' ? 'bottom_top' : 'bottom_left';
} else {
key = axis === 'topish' ? null : 'right_left';
}
if (!key || state[field][key] == null) return;
nudge(field, key, dir);
});
const restoreFileEl = document.getElementById('restore-file');
document.getElementById('btn-save').addEventListener('click', save);
document.getElementById('btn-reset').addEventListener('click', reset);
document.getElementById('btn-print').addEventListener('click', () => window.print());
document.getElementById('btn-backup').addEventListener('click', backup);
document.getElementById('btn-restore').addEventListener('click', () => {
restoreFileEl.value = '';
restoreFileEl.click();
});
restoreFileEl.addEventListener('change', () => {
const file = restoreFileEl.files && restoreFileEl.files[0];
if (file) restoreFromFile(file);
});
buildPanel();
applyLive();
})();

View File

@@ -1,460 +0,0 @@
const seenOrderKeys = new Set();
let ordersLoaded = false;
let lastSince = '';
let lastUsername = '';
let lastRows = null;
let productCodes = new Set();
function t(key) {
const pack = translations[currentLang] || translations.en;
return pack[key] || translations.en[key] || key;
}
function orderKey(row) {
return `${row.delivery_note_number}|${row.product_code}`;
}
function dateKey(raw) {
const match = /^(\d{4})\/(\d{1,2})\/(\d{1,2})$/.exec((raw || '').trim());
if (!match) return 0;
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) {
const groups = new Map();
rows.forEach((row) => {
const name = companyName(row);
if (!groups.has(name)) groups.set(name, []);
groups.get(name).push(row);
});
const list = [...groups.entries()];
list.forEach(([, items]) => {
items.sort((a, b) => dateKey(b.delivery_note_date) - dateKey(a.delivery_note_date));
});
list.sort((a, b) => dateKey(b[1][0].delivery_note_date) - dateKey(a[1][0].delivery_note_date));
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) {
const td = document.createElement('td');
if (className) td.className = className;
if (ltr) td.dir = 'ltr';
td.textContent = text || '';
return td;
}
function codeCell(row) {
const td = document.createElement('td');
td.className = 'mono';
const code = (row.product_code || '').trim();
if (!productCodes.has(code)) {
td.textContent = code;
return td;
}
const link = document.createElement('a');
const weight = (row.remaining_quantity || '').trim();
link.className = 'code-link';
link.href = `/entry/?code=${encodeURIComponent(code)}&weight=${encodeURIComponent(weight)}`;
link.textContent = code;
td.appendChild(link);
return td;
}
function syncDateDefaults() {
const start = document.getElementById('crm-start');
if (!start) return;
if (!start.value.trim() && lastSince) start.value = lastSince;
}
function loginForm() {
return document.getElementById('crm-login');
}
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() {
if (!loginForm().hidden) setStatus(t('sg_need_login'));
if (lastUsername) showSession();
syncDateDefaults();
if (lastRows) renderOrders(filteredRows(), false);
}
function renderOrders(rows, markNew) {
const body = document.getElementById('crm-orders-body');
const count = document.getElementById('crm-count');
const status = document.getElementById('crm-orders-status');
body.replaceChildren();
count.textContent = String(rows.length);
document.getElementById('crm-filters').hidden = !(lastRows && lastRows.length);
if (!rows.length) {
status.hidden = false;
status.textContent = lastRows && lastRows.length ? t('no_crm_matches') : t('no_crm_orders');
document.getElementById('crm-orders-table').hidden = true;
return 0;
}
status.hidden = true;
status.textContent = '';
document.getElementById('crm-orders-table').hidden = false;
let added = 0;
groupedRows(rows).forEach(([company, items]) => {
const head = document.createElement('tr');
head.className = 'group-row';
const label = document.createElement('td');
label.colSpan = 6;
label.textContent = company;
head.appendChild(label);
body.appendChild(head);
items.forEach((row) => {
const key = orderKey(row);
const isNew = markNew && !seenOrderKeys.has(key);
if (isNew) added += 1;
const tr = document.createElement('tr');
if (isNew) tr.className = 'row-new';
if (row.notes) tr.title = row.notes;
tr.append(
cell(row.delivery_note_date, 'mono', true),
codeCell(row),
cell(row.product_title),
cell(row.note_quantity, 'mono'),
cell(row.delivered_quantity, 'mono'),
cell(row.remaining_quantity, 'mono'),
);
body.appendChild(tr);
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;
}
function setStatus(message) {
const status = document.getElementById('crm-orders-status');
const body = document.getElementById('crm-orders-body');
body.replaceChildren();
document.getElementById('crm-count').textContent = '0';
document.getElementById('crm-orders-table').hidden = true;
if (!message) {
status.hidden = true;
status.textContent = '';
return;
}
status.hidden = false;
status.textContent = message;
}
async function fetchProducts() {
const res = await fetch('/api/products');
if (!res.ok) return;
const products = await res.json().catch(() => []);
productCodes = new Set((products || []).map((p) => (p.code || '').trim()));
}
async function applyOrdersResponse(ordersRes) {
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) {
const message = data.detail || t('no_crm_orders');
if (!ordersLoaded) setStatus(message);
showToast(message, true);
return;
}
lastSince = data.since || '';
lastUsername = data.username || '';
lastRows = data.orders || [];
showSession();
syncDateDefaults();
const added = renderOrders(filteredRows(), ordersLoaded);
ordersLoaded = true;
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) {
setStatus(t('no_crm_orders'));
showToast('Network error', true);
} finally {
button.disabled = false;
}
}
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.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();
});
checkRowMatches();
document.addEventListener('slip-language', renderChrome);

View File

@@ -1,102 +1,32 @@
document.addEventListener('DOMContentLoaded', () => { document.addEventListener('DOMContentLoaded', () => {
const productSelect = document.getElementById('product'); const productSelect = document.getElementById('product');
const dateFields = document.getElementById('date-fields');
const dateInput = document.getElementById('prod-date'); const dateInput = document.getElementById('prod-date');
const nextControlInput = document.getElementById('next-control'); const nextControlInput = document.getElementById('next-control');
const totalWeightInput = document.getElementById('total-weight'); const totalWeightInput = document.getElementById('total-weight');
const canisterWeightInput = document.getElementById('canister-weight'); const canisterWeightInput = document.getElementById('canister-weight');
const canistersPerBoxInput = document.getElementById('canisters-per-box'); const canistersPerBoxInput = document.getElementById('canisters-per-box');
const customLines = document.getElementById('custom-lines');
const previewDisplay = document.getElementById('preview-display'); const previewDisplay = document.getElementById('preview-display');
const form = document.getElementById('order-form'); const form = document.getElementById('order-form');
// European display dd/mm/yyyy; API still gets ISO yyyy-mm-dd // Default dates (local calendar — valueAsDate is UTC and shifts in +0330)
function localDmy(d) { function localYmd(d) {
const day = String(d.getDate()).padStart(2, '0'); const y = d.getFullYear();
const m = String(d.getMonth() + 1).padStart(2, '0');
return `${day}/${m}/${d.getFullYear()}`;
}
function parseDmy(s) {
const m = /^(\d{2})\/(\d{2})\/(\d{4})$/.exec((s || '').trim());
if (!m) return null;
const d = new Date(+m[3], +m[2] - 1, +m[1]);
if (d.getFullYear() !== +m[3] || d.getMonth() !== +m[2] - 1 || d.getDate() !== +m[1]) return null;
return d;
}
function toYmd(d) {
const m = String(d.getMonth() + 1).padStart(2, '0'); const m = String(d.getMonth() + 1).padStart(2, '0');
const day = String(d.getDate()).padStart(2, '0'); const day = String(d.getDate()).padStart(2, '0');
return `${d.getFullYear()}-${m}-${day}`; return `${y}-${m}-${day}`;
} }
dateInput.value = localYmd(new Date());
function productRequiresDates() {
const opt = productSelect.options[productSelect.selectedIndex];
if (!opt || !opt.value) return true;
return opt.dataset.requiresDates !== 'false';
}
function syncDateFields() {
const needed = productRequiresDates();
dateFields.style.display = needed ? '' : 'none';
dateInput.required = needed;
nextControlInput.required = needed;
if (needed && !dateInput.value) {
dateInput.value = localDmy(new Date());
updateNextControl();
}
}
dateInput.value = localDmy(new Date());
// Auto calculate +6 months // Auto calculate +6 months
function updateNextControl() { function updateNextControl() {
const d = parseDmy(dateInput.value); const [y, m, day] = (dateInput.value || '').split('-').map(Number);
if (!d) return; if (!y) return;
const d = new Date(y, m - 1, day);
d.setMonth(d.getMonth() + 6); d.setMonth(d.getMonth() + 6);
nextControlInput.value = localDmy(d); nextControlInput.value = localYmd(d);
} }
updateNextControl(); updateNextControl();
dateInput.addEventListener('change', updateNextControl); dateInput.addEventListener('change', updateNextControl);
dateInput.addEventListener('input', updateNextControl);
function collectCustomLabels() {
const lines = [];
customLines.querySelectorAll('.custom-line').forEach((row) => {
const weight = parseFloat(row.querySelector('.custom-weight').value);
const count = parseInt(row.querySelector('.custom-count').value, 10);
if (weight > 0 && count >= 1) lines.push({ weight, count });
});
return lines;
}
function addCustomLine() {
const row = document.createElement('div');
row.className = 'custom-line';
const weight = document.createElement('input');
weight.type = 'number';
weight.className = 'custom-weight';
weight.required = true;
weight.step = '0.1';
weight.min = '0.1';
weight.placeholder = 'kg';
weight.setAttribute('aria-label', 'Weight (kg)');
const count = document.createElement('input');
count.type = 'number';
count.className = 'custom-count';
count.required = true;
count.step = '1';
count.min = '1';
count.value = '1';
count.setAttribute('aria-label', 'Count');
const remove = document.createElement('button');
remove.type = 'button';
remove.className = 'btn btn-ghost btn-sm custom-remove';
remove.textContent = '×';
remove.setAttribute('aria-label', 'Remove');
row.append(weight, count, remove);
customLines.appendChild(row);
weight.focus();
}
// Auto calculate previews // Auto calculate previews
function updatePreview() { function updatePreview() {
@@ -105,92 +35,41 @@ document.addEventListener('DOMContentLoaded', () => {
const cpb = parseInt(canistersPerBoxInput.value) || 1; const cpb = parseInt(canistersPerBoxInput.value) || 1;
const cc = Math.ceil(tw / cw); const cc = Math.ceil(tw / cw);
const bc = Math.ceil(cc / cpb); const cp = Math.ceil(cc / 4);
let cu = 0;
customLines.querySelectorAll('.custom-count').forEach((input) => {
cu += parseInt(input.value, 10) || 0;
});
const pages = Math.ceil((cc + bc + cu) / 4) || 0;
const t = translations[currentLang] || translations.en; const bc = Math.ceil(cc / cpb);
previewDisplay.textContent = const bp = Math.ceil(bc / 4);
`${t.canisters_unit}: ${cc} | ${t.boxes_unit}: ${bc} | ${t.custom_unit}: ${cu} | ${pages} ${t.preview_pages}`;
previewDisplay.textContent = `Canisters: ${cc} (${cp} pages) | Boxes: ${bc} (${bp} pages)`;
} }
window.updateLabelsPreview = updatePreview;
// Listeners for updates // Listeners for updates
totalWeightInput.addEventListener('input', updatePreview); totalWeightInput.addEventListener('input', updatePreview);
canisterWeightInput.addEventListener('input', updatePreview); canisterWeightInput.addEventListener('input', updatePreview);
canistersPerBoxInput.addEventListener('input', updatePreview); canistersPerBoxInput.addEventListener('input', updatePreview);
customLines.addEventListener('input', updatePreview);
customLines.addEventListener('click', (e) => {
const btn = e.target.closest('.custom-remove');
if (!btn) return;
btn.closest('.custom-line').remove();
updatePreview();
});
document.getElementById('add-custom-line').addEventListener('click', () => {
addCustomLine();
updatePreview();
});
updatePreview(); updatePreview();
// Auto weight + date visibility from product selection // Auto weight from product selection
productSelect.addEventListener('change', (e) => { productSelect.addEventListener('change', (e) => {
const opt = e.target.options[e.target.selectedIndex]; const opt = e.target.options[e.target.selectedIndex];
if (opt && opt.dataset.weight) { if (opt && opt.dataset.weight) {
canisterWeightInput.value = opt.dataset.weight; canisterWeightInput.value = opt.dataset.weight;
updatePreview(); updatePreview();
} }
syncDateFields();
}); });
syncDateFields();
const params = new URLSearchParams(location.search);
const presetCode = params.get('code');
if (presetCode) {
const opt = [...productSelect.options].find((o) => o.dataset.code === presetCode);
if (opt) {
productSelect.value = opt.value;
productSelect.dispatchEvent(new Event('change'));
}
}
const presetWeight = params.get('weight');
if (presetWeight) {
const n = Number(String(presetWeight).replace(/[,،]/g, ''));
if (Number.isFinite(n) && n > 0) {
totalWeightInput.value = String(n);
updatePreview();
}
}
// Submit new order // Submit new order
form.addEventListener('submit', async (e) => { form.addEventListener('submit', async (e) => {
e.preventDefault(); e.preventDefault();
const needsDates = productRequiresDates();
let production_date = null;
let next_control_date = null;
if (needsDates) {
const prodDate = parseDmy(dateInput.value);
const nextDate = parseDmy(nextControlInput.value);
if (!prodDate || !nextDate) {
showToast(currentLang === 'fa' ? 'تاریخ را به صورت روز/ماه/سال وارد کنید' : 'Use date format dd/mm/yyyy', true);
return;
}
production_date = toYmd(prodDate);
next_control_date = toYmd(nextDate);
}
const payload = { const payload = {
product_id: parseInt(productSelect.value), product_id: parseInt(productSelect.value),
batch_number: document.getElementById('batch').value, batch_number: document.getElementById('batch').value,
production_date, production_date: dateInput.value,
next_control_date, next_control_date: nextControlInput.value,
total_weight: parseFloat(totalWeightInput.value), total_weight: parseFloat(totalWeightInput.value),
canister_weight: parseFloat(canisterWeightInput.value), canister_weight: parseFloat(canisterWeightInput.value),
canisters_per_box: parseInt(canistersPerBoxInput.value), canisters_per_box: parseInt(canistersPerBoxInput.value)
custom_labels: collectCustomLabels()
}; };
try { try {
@@ -203,10 +82,8 @@ document.addEventListener('DOMContentLoaded', () => {
if (res.ok) { if (res.ok) {
showToast(currentLang === 'fa' ? 'سفارش به صف چاپ اضافه شد' : 'Order added to print queue!'); showToast(currentLang === 'fa' ? 'سفارش به صف چاپ اضافه شد' : 'Order added to print queue!');
form.reset(); form.reset();
customLines.replaceChildren(); dateInput.value = localYmd(new Date());
dateInput.value = localDmy(new Date());
updateNextControl(); updateNextControl();
syncDateFields();
updatePreview(); updatePreview();
setTimeout(() => window.location.reload(), 1000); setTimeout(() => window.location.reload(), 1000);
} else { } else {
@@ -219,3 +96,64 @@ document.addEventListener('DOMContentLoaded', () => {
} }
}); });
}); });
// Inline Product addition
function showAddProduct() {
document.getElementById('add-product-panel').style.display = 'block';
}
function hideAddProduct() {
document.getElementById('add-product-panel').style.display = 'none';
}
async function addProduct() {
const code = document.getElementById('new-code').value;
const desc = document.getElementById('new-desc').value;
const weight = parseFloat(document.getElementById('new-weight').value);
if (!code || !desc) {
showToast('Code and Description are required', true);
return;
}
try {
const res = await fetch('/api/products', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ code, description: desc, default_net_weight: weight })
});
if (res.ok) {
const p = await res.json();
const select = document.getElementById('product');
const opt = document.createElement('option');
opt.value = p.id;
opt.dataset.weight = p.default_net_weight;
opt.textContent = `${p.code} — ${p.description}`;
select.appendChild(opt);
select.value = p.id;
document.getElementById('canister-weight').value = p.default_net_weight;
updatePreview();
hideAddProduct();
showToast('Product added');
} else {
showToast('Error adding product', true);
}
} catch (err) {
showToast('Network error', true);
}
}
async function deleteOrder(id) {
if (!confirm('Cancel this order?')) return;
try {
const res = await fetch(`/api/orders/${id}`, { method: 'DELETE' });
if (res.ok) {
window.location.reload();
}
} catch (err) {
showToast('Error', true);
}
}

View File

@@ -1,24 +1,15 @@
const translations = { const translations = {
'en': { 'en': {
'app_title': 'Label Printer', 'app_title': 'Product Slip Manager',
'data_entry': 'Data Entry', 'data_entry': 'Data Entry',
'crm_orders': 'Orders',
'products': 'Products',
'print_queue': 'Print Queue', 'print_queue': 'Print Queue',
'calibrate': 'Calibrate', 'calibrate': 'Calibrate',
'new_order': 'New Order', 'new_order': 'New Order',
'product': 'Product', 'product': 'Product',
'add_product': '+ Add New Product', 'add_product': '+ Add New Product',
'edit_product': 'Edit Product',
'edit': 'Edit',
'backup': 'Backup',
'restore': 'Restore',
'no_products': 'No products yet',
'product_code': 'Product Code', 'product_code': 'Product Code',
'description': 'Description', 'description': 'Description',
'default_weight': 'Default Weight', 'default_weight': 'Default Weight',
'requires_dates': 'Requires Date / Next Control',
'requires_dates_short': 'Dates',
'save': 'Save', 'save': 'Save',
'cancel': 'Cancel', 'cancel': 'Cancel',
'batch_number': 'Batch #', 'batch_number': 'Batch #',
@@ -31,78 +22,30 @@ const translations = {
'labels_preview': 'Labels Generated', 'labels_preview': 'Labels Generated',
'canisters': 'Canisters', 'canisters': 'Canisters',
'boxes': 'Boxes', 'boxes': 'Boxes',
'canisters_unit': 'Canisters',
'boxes_unit': 'Boxes',
'labels': 'Labels',
'custom': 'Custom',
'custom_unit': 'Custom',
'custom_labels': 'Custom Labels',
'add_custom_label': '+ Add custom label',
'pages_unit': 'Page(s)',
'preview_pages': 'pages',
'pages_needed': 'Pages Needed', 'pages_needed': 'Pages Needed',
'total_pages': 'Pages', 'total_pages': 'Pages',
'status_pending': 'Pending',
'status_done': 'Done',
'status_printing': 'Printing',
'status_cancelled': 'Cancelled',
'add_to_queue': 'Add to Print Queue', 'add_to_queue': 'Add to Print Queue',
'recent_orders': 'Recent Orders', 'recent_orders': 'Recent Orders',
'crm_orders_title': 'Orders',
'refresh': 'Refresh',
'customer': 'Customer',
'company_name': 'Company name',
'delivery_note': 'Note #',
'note_qty': 'Ordered',
'delivered_qty': 'Delivered',
'remaining_qty': 'Remaining',
'product_title': 'Title',
'subtotal': 'Subtotal',
'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_matches': 'No orders match this search',
'orders_after': 'Orders after',
'start_date': 'From date',
'end_date': 'To date',
'crm_new': 'New orders added',
'status': 'Status', 'status': 'Status',
'no_orders': 'No orders yet', 'no_orders': 'No orders yet',
'no_pending_orders': 'No pending orders to print.', 'no_pending_orders': 'No pending orders to print.',
'print': 'Print', 'print': 'Print',
'mark_done': 'Mark Done', 'mark_done': 'Mark Done',
'undo_done': 'Undo',
'remove': 'Remove',
'print_history': 'Print History', 'print_history': 'Print History',
'printed_at': 'Printed At', 'printed_at': 'Printed At',
'no_history': 'No print history' 'no_history': 'No print history'
}, },
'fa': { 'fa': {
'app_title': 'پرینتر لیبل', 'app_title': 'مدیریت برچسب محصول',
'data_entry': 'ثبت اطلاعات', 'data_entry': 'ثبت اطلاعات',
'crm_orders': 'حواله‌ها',
'products': 'محصولات',
'print_queue': 'صف چاپ', 'print_queue': 'صف چاپ',
'calibrate': 'کالیبراسیون', 'calibrate': 'کالیبراسیون',
'new_order': 'سفارش جدید', 'new_order': 'سفارش جدید',
'product': 'محصول', 'product': 'محصول',
'add_product': '+ افزودن محصول جدید', 'add_product': '+ افزودن محصول جدید',
'edit_product': 'ویرایش محصول',
'edit': 'ویرایش',
'backup': 'پشتیبان',
'restore': 'بازیابی',
'no_products': 'محصولی ثبت نشده',
'product_code': 'کد محصول', 'product_code': 'کد محصول',
'description': 'شرح', 'description': 'شرح',
'default_weight': 'وزن پیش‌فرض', 'default_weight': 'وزن پیش‌فرض',
'requires_dates': 'نیاز به تاریخ / کنترل بعدی',
'requires_dates_short': 'تاریخ',
'save': 'ذخیره', 'save': 'ذخیره',
'cancel': 'لغو', 'cancel': 'لغو',
'batch_number': 'شماره بچ', 'batch_number': 'شماره بچ',
@@ -110,93 +53,29 @@ const translations = {
'next_control': 'تاریخ کنترل بعدی', 'next_control': 'تاریخ کنترل بعدی',
'net_weight': 'وزن خالص (کیلوگرم)', 'net_weight': 'وزن خالص (کیلوگرم)',
'total_weight': 'وزن کل (کیلوگرم)', 'total_weight': 'وزن کل (کیلوگرم)',
'canister_weight': 'وزن گالن (کیلوگرم)', 'canister_weight': 'وزن قوطی (کیلوگرم)',
'canisters_per_box': 'تعداد گالن در هر کارتن', 'canisters_per_box': 'تعداد قوطی در هر کارتن',
'labels_preview': 'برچسب‌های تولیدی', 'labels_preview': 'برچسب‌های تولیدی',
'canisters': 'تعداد گالن', 'canisters': 'تعداد قوطی',
'boxes': 'تعداد کارتن', 'boxes': 'تعداد کارتن',
'canisters_unit': 'گالن',
'boxes_unit': 'کارتن',
'labels': 'برچسب‌ها',
'custom': 'سفارشی',
'custom_unit': 'سفارشی',
'custom_labels': 'برچسب سفارشی',
'add_custom_label': '+ افزودن برچسب سفارشی',
'pages_unit': 'صفحه',
'preview_pages': 'صفحه',
'pages_needed': 'تعداد صفحات', 'pages_needed': 'تعداد صفحات',
'total_pages': 'صفحات', 'total_pages': 'صفحات',
'status_pending': 'در انتظار',
'status_done': 'انجام شد',
'status_printing': 'در حال چاپ',
'status_cancelled': 'لغو شده',
'add_to_queue': 'افزودن به صف چاپ', 'add_to_queue': 'افزودن به صف چاپ',
'recent_orders': 'سفارشات اخیر', 'recent_orders': 'سفارشات اخیر',
'crm_orders_title': 'حواله‌ها',
'refresh': 'به‌روزرسانی',
'customer': 'مشتری',
'company_name': 'نام شرکت',
'delivery_note': 'شماره حواله',
'note_qty': 'مقدار حواله',
'delivered_qty': 'تحویل‌شده',
'remaining_qty': 'مانده',
'product_title': 'عنوان',
'subtotal': 'جمع',
'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_matches': 'حواله‌ای با این جستجو پیدا نشد',
'orders_after': 'حواله‌های بعد از',
'start_date': 'از تاریخ',
'end_date': 'تا تاریخ',
'crm_new': 'سفارش جدید اضافه شد',
'status': 'وضعیت', 'status': 'وضعیت',
'no_orders': 'سفارشی ثبت نشده', 'no_orders': 'سفارشی ثبت نشده',
'no_pending_orders': 'سفارشی در انتظار چاپ نیست.', 'no_pending_orders': 'سفارشی در انتظار چاپ نیست.',
'print': 'چاپ', 'print': 'چاپ',
'mark_done': 'چاپ شد', 'mark_done': 'تایید چاپ',
'undo_done': 'بازگردانی',
'remove': 'حذف',
'print_history': 'سابقه چاپ', 'print_history': 'سابقه چاپ',
'printed_at': 'زمان چاپ', 'printed_at': 'زمان چاپ',
'no_history': 'سابقه‌ای وجود ندارد' 'no_history': 'سابقه‌ای وجود ندارد'
} }
}; };
let currentLang = localStorage.getItem('slip_lang') || 'fa'; let currentLang = localStorage.getItem('slip_lang') || 'en';
let currentTheme = localStorage.getItem('slip_theme') || 'light';
// SVG flags: Windows often cannot render flag emojis (shows "IR"/"GB" instead)
const FLAG_SVG = {
fa: '<svg class="lang-flag" viewBox="0 0 9 6" aria-hidden="true"><rect width="9" height="2" fill="#239f40"/><rect y="2" width="9" height="2" fill="#fff"/><rect y="4" width="9" height="2" fill="#da0000"/></svg>',
en: '<svg class="lang-flag" viewBox="0 0 60 30" aria-hidden="true"><rect width="60" height="30" fill="#012169"/><path d="M0,0 60,30M60,0 0,30" stroke="#fff" stroke-width="6"/><path d="M0,0 60,30M60,0 0,30" stroke="#C8102E" stroke-width="2"/><path d="M30,0v30M0,15h60" stroke="#fff" stroke-width="10"/><path d="M30,0v30M0,15h60" stroke="#C8102E" stroke-width="6"/></svg>',
};
function applyTheme(theme) {
document.documentElement.setAttribute('data-theme', theme);
const label = document.getElementById('theme-label');
if (label) {
// show the theme you'll switch to
label.textContent = theme === 'light' ? '🌙' : '☀️';
}
}
function toggleTheme() {
currentTheme = currentTheme === 'light' ? 'dark' : 'light';
localStorage.setItem('slip_theme', currentTheme);
applyTheme(currentTheme);
}
function applyLanguage(lang) { function applyLanguage(lang) {
document.documentElement.lang = lang;
document.documentElement.dir = lang === 'fa' ? 'rtl' : 'ltr';
document.querySelectorAll('[data-i18n]').forEach(el => { document.querySelectorAll('[data-i18n]').forEach(el => {
const key = el.getAttribute('data-i18n'); const key = el.getAttribute('data-i18n');
if (translations[lang][key]) { if (translations[lang][key]) {
@@ -204,26 +83,13 @@ function applyLanguage(lang) {
} }
}); });
document.querySelectorAll('[data-i18n-title]').forEach(el => {
const key = el.getAttribute('data-i18n-title');
if (translations[lang][key]) el.title = translations[lang][key];
});
document.querySelectorAll('[data-i18n-aria]').forEach(el => {
const key = el.getAttribute('data-i18n-aria');
if (translations[lang][key]) el.setAttribute('aria-label', translations[lang][key]);
});
// Button shows the language you can switch to
const toggleBtn = document.getElementById('lang-label'); const toggleBtn = document.getElementById('lang-label');
if (toggleBtn) { if (toggleBtn) {
const next = lang === 'en' ? 'fa' : 'en'; toggleBtn.textContent = lang === 'en' ? '🇮🇷 FA' : '🇬🇧 EN';
toggleBtn.innerHTML = FLAG_SVG[next] + ' ' + next.toUpperCase();
} }
if (typeof window.updateLabelsPreview === 'function') { // User requested Persian to be LTR, so we don't change the dir attribute
window.updateLabelsPreview(); // document.documentElement.dir = lang === 'fa' ? 'rtl' : 'ltr';
}
document.dispatchEvent(new Event('slip-language'));
} }
function toggleLanguage() { function toggleLanguage() {
@@ -248,149 +114,7 @@ function showToast(message, isError = false) {
setTimeout(() => toast.classList.remove('show'), 3000); setTimeout(() => toast.classList.remove('show'), 3000);
} }
async function adjustCount(id, field, delta) {
const spanId = field === 'canister_count' ? `cc-${id}` : `bc-${id}`;
const otherId = field === 'canister_count' ? `bc-${id}` : `cc-${id}`;
const span = document.getElementById(spanId);
if (!span) return;
const next = parseInt(span.textContent, 10) + delta;
if (next < 0) return;
const other = document.getElementById(otherId);
const otherVal = other ? parseInt(other.textContent, 10) : 0;
if (next === 0 && otherVal === 0) {
const custom = document.getElementById(`custom-${id}`);
if (!custom || !custom.querySelector('.cl-count')) return;
}
try {
const res = await fetch(`/api/orders/${id}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ [field]: next })
});
if (!res.ok) {
showToast(currentLang === 'fa' ? 'خطا در ویرایش' : 'Error updating order', true);
return;
}
const order = await res.json();
const cc = document.getElementById(`cc-${id}`);
const bc = document.getElementById(`bc-${id}`);
if (cc) cc.textContent = order.canister_count;
if (bc) bc.textContent = order.box_count;
const tw = document.getElementById(`tw-${id}`);
if (tw) tw.textContent = `${order.total_weight} kg`;
const pages = document.getElementById(`pages-${id}`);
if (pages) pages.textContent = order.canister_pages + order.box_pages;
} catch (err) {
showToast('Network error', true);
}
}
function formatWeight(w) {
const n = Number(w);
if (!Number.isFinite(n)) return String(w);
return Number.isInteger(n) ? String(n) : String(parseFloat(n.toFixed(6)));
}
function renderCustomLabels(id, labels, pending) {
const cell = document.getElementById(`custom-${id}`);
if (!cell) return;
const lines = (labels || []).filter((line) => line && Number(line.count) > 0);
if (!lines.length) {
cell.replaceChildren();
return;
}
const list = document.createElement('div');
list.className = 'custom-label-list';
lines.forEach((line, i) => {
const weight = Number(line.weight);
const count = Number(line.count);
const weightLabel = formatWeight(weight);
const row = document.createElement('div');
if (!pending) {
row.className = 'mono';
row.textContent = `${weightLabel} kg × ${count}`;
} else {
row.className = 'count-stepper';
row.dataset.weight = String(weight);
const label = document.createElement('span');
label.className = 'stepper-label';
label.textContent = `${weightLabel} kg`;
const down = document.createElement('button');
down.type = 'button';
down.className = 'stepper-btn';
down.textContent = '−';
down.setAttribute('aria-label', '-');
down.addEventListener('click', () => adjustCustomCount(id, i, -1));
const countEl = document.createElement('span');
countEl.className = 'cl-count';
countEl.textContent = String(count);
const up = document.createElement('button');
up.type = 'button';
up.className = 'stepper-btn';
up.textContent = '+';
up.setAttribute('aria-label', '+');
up.addEventListener('click', () => adjustCustomCount(id, i, 1));
row.append(label, down, countEl, up);
}
list.appendChild(row);
});
cell.replaceChildren(list);
}
async function adjustCustomCount(id, index, delta) {
const cell = document.getElementById(`custom-${id}`);
if (!cell) return;
const rows = [...cell.querySelectorAll('.count-stepper')];
const row = rows[index];
if (!row) return;
const next = parseInt(row.querySelector('.cl-count').textContent, 10) + delta;
if (next < 0) return;
const labels = rows.map((r, i) => ({
weight: parseFloat(r.dataset.weight),
count: i === index ? next : parseInt(r.querySelector('.cl-count').textContent, 10),
})).filter((line) => line.count > 0);
const cc = parseInt(document.getElementById(`cc-${id}`)?.textContent, 10) || 0;
const bc = parseInt(document.getElementById(`bc-${id}`)?.textContent, 10) || 0;
if (cc === 0 && bc === 0 && labels.length === 0) return;
try {
const res = await fetch(`/api/orders/${id}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ custom_labels: labels }),
});
if (!res.ok) {
showToast(currentLang === 'fa' ? 'خطا در ویرایش' : 'Error updating order', true);
return;
}
const order = await res.json();
renderCustomLabels(id, order.custom_labels, true);
const pages = document.getElementById(`pages-${id}`);
if (pages) pages.textContent = order.canister_pages + order.box_pages;
} catch (err) {
showToast('Network error', true);
}
}
async function deleteOrder(id) {
const msg = currentLang === 'fa' ? 'این سفارش حذف شود؟' : 'Remove this order?';
if (!confirm(msg)) return;
try {
const res = await fetch(`/api/orders/${id}`, { method: 'DELETE' });
if (res.ok) {
window.location.reload();
} else {
showToast(currentLang === 'fa' ? 'خطا در حذف' : 'Error removing order', true);
}
} catch (err) {
showToast('Network error', true);
}
}
// Initialize on load // Initialize on load
document.addEventListener('DOMContentLoaded', () => { document.addEventListener('DOMContentLoaded', () => {
applyTheme(currentTheme);
applyLanguage(currentLang); applyLanguage(currentLang);
}); });

View File

@@ -1,6 +1,6 @@
function printOrder(id) { function printOrder(id) {
// Cache-bust so a second print of the same order is not a stale HTML document // Open the print page in a new window/tab
const win = window.open(`/print-page/${id}/?t=${Date.now()}`, '_blank'); const win = window.open(`/print-page/${id}/`, '_blank');
if (win) { if (win) {
win.focus(); win.focus();
} else { } else {
@@ -17,30 +17,12 @@ async function markDone(id) {
}); });
if (res.ok) { if (res.ok) {
showToast(currentLang === 'fa' ? 'سفارش به عنوان چاپ‌شده علامت خورد' : 'Order marked as done'); showToast('Order marked as done');
document.getElementById(`order-${id}`).style.display = 'none'; document.getElementById(`order-${id}`).style.display = 'none';
// Reload after brief delay to update history table
setTimeout(() => window.location.reload(), 1500); setTimeout(() => window.location.reload(), 1500);
} else { } else {
showToast(currentLang === 'fa' ? 'خطا در به‌روزرسانی وضعیت' : 'Error updating status', true); showToast('Error updating status', true);
}
} catch (err) {
showToast('Network error', true);
}
}
async function undoDone(id) {
try {
const res = await fetch(`/api/orders/${id}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ status: 'pending' })
});
if (res.ok) {
showToast(currentLang === 'fa' ? 'سفارش به صف چاپ بازگشت' : 'Order returned to print queue');
setTimeout(() => window.location.reload(), 1000);
} else {
showToast(currentLang === 'fa' ? 'خطا در بازگردانی' : 'Error undoing status', true);
} }
} catch (err) { } catch (err) {
showToast('Network error', true); showToast('Network error', true);

View File

@@ -1,159 +0,0 @@
document.addEventListener('DOMContentLoaded', () => {
const form = document.getElementById('product-form');
form.addEventListener('submit', async (e) => {
e.preventDefault();
const id = document.getElementById('edit-id').value;
const payload = {
code: document.getElementById('prod-code').value.trim(),
description: document.getElementById('prod-desc').value.trim(),
default_net_weight: parseFloat(document.getElementById('prod-weight').value),
requires_dates: document.getElementById('prod-requires-dates').checked,
};
if (!payload.code || !payload.description) {
showToast(currentLang === 'fa' ? 'کد و شرح لازم است' : 'Code and Description are required', true);
return;
}
const url = id ? `/api/products/${id}` : '/api/products';
const method = id ? 'PUT' : 'POST';
try {
const res = await fetch(url, {
method,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload),
});
if (res.ok) {
showToast(id
? (currentLang === 'fa' ? 'محصول به‌روز شد' : 'Product updated')
: (currentLang === 'fa' ? 'محصول افزوده شد' : 'Product added'));
setTimeout(() => window.location.reload(), 600);
} else {
const err = await res.json().catch(() => ({}));
showToast(err.detail || (currentLang === 'fa' ? 'خطا در ذخیره' : 'Error saving product'), true);
}
} catch (err) {
showToast('Network error', true);
}
});
});
function setFormMode(editing) {
const title = document.getElementById('product-form-title');
const cancel = document.getElementById('product-cancel-btn');
const t = translations[currentLang] || translations.en;
title.textContent = editing ? t.edit_product : t.add_product;
title.removeAttribute('data-i18n');
title.setAttribute('data-i18n', editing ? 'edit_product' : 'add_product');
cancel.style.display = editing ? '' : 'none';
}
function editProduct(btn) {
document.getElementById('edit-id').value = btn.dataset.id;
document.getElementById('prod-code').value = btn.dataset.code;
document.getElementById('prod-desc').value = btn.dataset.desc;
document.getElementById('prod-weight').value = btn.dataset.weight;
document.getElementById('prod-requires-dates').checked = btn.dataset.requiresDates !== 'false';
setFormMode(true);
document.getElementById('prod-code').focus();
}
function cancelEdit() {
document.getElementById('edit-id').value = '';
document.getElementById('product-form').reset();
document.getElementById('prod-weight').value = 5;
document.getElementById('prod-requires-dates').checked = true;
setFormMode(false);
}
async function deleteProduct(id) {
const msg = currentLang === 'fa' ? 'این محصول حذف شود؟' : 'Remove this product?';
if (!confirm(msg)) return;
try {
const res = await fetch(`/api/products/${id}`, { method: 'DELETE' });
if (res.ok) {
window.location.reload();
} else {
const err = await res.json().catch(() => ({}));
showToast(
err.detail || (currentLang === 'fa' ? 'خطا در حذف' : 'Error removing product'),
true
);
}
} catch (err) {
showToast('Network error', true);
}
}
async function backupProducts() {
try {
const res = await fetch('/api/products');
if (!res.ok) {
showToast(currentLang === 'fa' ? 'خطا در پشتیبان‌گیری' : 'Backup failed', true);
return;
}
const products = await res.json();
const payload = products.map((p) => ({
code: p.code,
description: p.description,
default_net_weight: p.default_net_weight,
requires_dates: p.requires_dates !== false,
}));
const blob = new Blob([JSON.stringify(payload, null, 2) + '\n'], { type: 'application/json' });
const a = document.createElement('a');
const d = new Date();
const stamp = [
d.getFullYear(),
String(d.getMonth() + 1).padStart(2, '0'),
String(d.getDate()).padStart(2, '0'),
].join('');
a.href = URL.createObjectURL(blob);
a.download = `products-backup-${stamp}.json`;
a.click();
URL.revokeObjectURL(a.href);
showToast(currentLang === 'fa' ? 'فایل پشتیبان دانلود شد' : 'Backup downloaded');
} catch (err) {
showToast('Network error', true);
}
}
function parseProductsBackup(raw) {
const data = typeof raw === 'string' ? JSON.parse(raw) : raw;
if (!Array.isArray(data) || !data.length) throw new Error('empty or invalid file');
return data.map((item) => {
if (!item || typeof item !== 'object') throw new Error('invalid item');
const code = String(item.code || '').trim();
const description = String(item.description || '').trim();
const weight = Number(item.default_net_weight);
if (!code || !description || !Number.isFinite(weight)) throw new Error('invalid product: ' + code);
const requires_dates = item.requires_dates !== false;
return { code, description, default_net_weight: weight, requires_dates };
});
}
async function restoreProducts(input) {
const file = input.files && input.files[0];
input.value = '';
if (!file) return;
try {
const payload = parseProductsBackup(await file.text());
const msg = currentLang === 'fa'
? 'محصولات از این فایل بازیابی شوند؟ (بر اساس کد ادغام می‌شود)'
: 'Restore products from this file? (merged by code)';
if (!confirm(msg)) return;
const res = await fetch('/api/products/restore', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload),
});
if (!res.ok) {
const err = await res.json().catch(() => ({}));
showToast(err.detail || (currentLang === 'fa' ? 'خطا در بازیابی' : 'Restore failed'), true);
return;
}
showToast(currentLang === 'fa' ? 'بازیابی شد' : 'Restored from file');
setTimeout(() => window.location.reload(), 600);
} catch (err) {
showToast((currentLang === 'fa' ? 'خطا در بازیابی: ' : 'Restore failed: ') + err.message, true);
}
}

View File

@@ -1 +0,0 @@
/* vendored @majidh1/jalalidatepicker@1.0.0 — https://github.com/majidh1/JalaliDatePicker */

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@@ -1,52 +1,31 @@
{% load static %} {% load static %}
<!DOCTYPE html> <!DOCTYPE html>
<html lang="fa" dir="rtl"> <html lang="en" dir="ltr">
<head> <head>
<meta charset="UTF-8"> <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{% block title %}پرینتر لیبل{% endblock %}</title> <title>{% block title %}Product Slip Manager{% endblock %}</title>
<link rel="icon" href="{% static 'lithium.png' %}" type="image/png">
<link rel="apple-touch-icon" href="{% static 'lithium.png' %}">
<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&display=swap" rel="stylesheet">
<link rel="stylesheet" href="{% static 'slips/css/style.css' %}?v=6"> <link rel="stylesheet" href="{% static 'slips/css/style.css' %}">
<script>
(function () {
var t = localStorage.getItem('slip_theme') || 'light';
document.documentElement.setAttribute('data-theme', t);
var lang = localStorage.getItem('slip_lang') || 'fa';
document.documentElement.lang = lang;
document.documentElement.dir = lang === 'fa' ? 'rtl' : 'ltr';
})();
</script>
{% block extra_head %}{% endblock %} {% block extra_head %}{% endblock %}
</head> </head>
<body> <body>
<nav class="navbar"> <nav class="navbar">
<div class="nav-container"> <div class="nav-container">
<a href="{% url 'entry' %}" class="nav-logo"> <a href="{% url 'entry' %}" class="nav-logo">
<img class="logo-icon" src="{% static 'lithium.png' %}" alt="" width="32" height="32"> <span class="logo-icon">🏭</span>
<span class="logo-text" data-i18n="app_title">پرینتر لیبل</span> <span class="logo-text" data-i18n="app_title">Product Slip Manager</span>
</a> </a>
<div class="nav-links"> <div class="nav-links">
<a href="{% url 'entry' %}" class="nav-link {% block nav_entry_active %}{% endblock %}" data-i18n="data_entry">ثبت اطلاعات</a> <a href="{% url 'entry' %}" class="nav-link {% block nav_entry_active %}{% endblock %}" data-i18n="data_entry">Data Entry</a>
<a href="{% url 'crm_orders' %}" class="nav-link {% block nav_crm_active %}{% endblock %}" data-i18n="crm_orders">حواله‌ها</a> <a href="{% url 'print_queue' %}" class="nav-link {% block nav_print_active %}{% endblock %}" data-i18n="print_queue">Print Queue</a>
<a href="{% url 'print_queue' %}" class="nav-link {% block nav_print_active %}{% endblock %}" data-i18n="print_queue">صف چاپ</a> <a href="{% url 'calibrate' %}" class="nav-link" data-i18n="calibrate">Calibrate</a>
</div> </div>
<div class="nav-actions"> <div class="nav-actions">
<div class="nav-setup"> <button id="lang-toggle" class="btn btn-ghost" onclick="toggleLanguage()">
<a href="{% url 'products' %}" class="nav-link {% block nav_products_active %}{% endblock %}" data-i18n="products">محصولات</a> <span id="lang-label">🇬🇧 EN</span>
<a href="{% url 'calibrate' %}" class="nav-link" data-i18n="calibrate">کالیبراسیون</a>
</div>
<button id="theme-toggle" class="btn btn-ghost" type="button" onclick="toggleTheme()" aria-label="Toggle theme">
<span id="theme-label">🌙</span>
</button>
<button id="lang-toggle" class="btn btn-ghost" type="button" onclick="toggleLanguage()" aria-label="Toggle language">
<span id="lang-label" class="lang-label">
<svg class="lang-flag" viewBox="0 0 60 30" aria-hidden="true"><rect width="60" height="30" fill="#012169"/><path d="M0,0 60,30M60,0 0,30" stroke="#fff" stroke-width="6"/><path d="M0,0 60,30M60,0 0,30" stroke="#C8102E" stroke-width="2"/><path d="M30,0v30M0,15h60" stroke="#fff" stroke-width="10"/><path d="M30,0v30M0,15h60" stroke="#C8102E" stroke-width="6"/></svg>
EN
</span>
</button> </button>
</div> </div>
</div> </div>
@@ -56,7 +35,7 @@
{% block content %}{% endblock %} {% block content %}{% endblock %}
</main> </main>
<script src="{% static 'slips/js/i18n.js' %}?v=6"></script> <script src="{% static 'slips/js/i18n.js' %}"></script>
{% block extra_scripts %}{% endblock %} {% block extra_scripts %}{% endblock %}
</body> </body>
</html> </html>

View File

@@ -4,283 +4,81 @@
<head> <head>
<meta charset="UTF-8"> <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Calibration — Label Printer</title> <title>Calibration Page</title>
<link rel="stylesheet" href="{% static 'slips/css/label_print.css' %}">
<style id="calibration-vars">
{{ calibration_css|safe }}
</style>
<style> <style>
* { box-sizing: border-box; margin: 0; padding: 0; } * { box-sizing: border-box; margin: 0; padding: 0; }
body { body { font-family: Arial, sans-serif; background-color: #f0f0f0; }
font-family: system-ui, sans-serif;
background: #0f172a; .preview-controls {
color: #e2e8f0; background: #1e293b; color: #fff; padding: 1rem; text-align: center;
min-height: 100vh; position: fixed; top: 0; left: 0; right: 0; z-index: 100;
}
.preview-controls button {
background: #3b82f6; color: white; border: none; padding: 10px 20px;
font-size: 16px; border-radius: 6px; cursor: pointer; font-weight: bold;
} }
.layout { .page-wrapper { margin-top: 80px; display: flex; justify-content: center; padding-bottom: 40px; }
display: grid;
grid-template-columns: minmax(300px, 360px) 1fr;
min-height: 100vh;
}
.panel {
background: #1e293b;
border-right: 1px solid #334155;
padding: 1rem;
display: flex;
flex-direction: column;
gap: 0.75rem;
max-height: 100vh;
overflow: auto;
}
.panel h1 { font-size: 1.1rem; font-weight: 700; }
.panel .hint { font-size: 0.8rem; color: #94a3b8; line-height: 1.4; }
.toolbar {
display: flex;
flex-wrap: wrap;
gap: 0.4rem;
}
.toolbar button, .nudge button {
background: #334155;
color: #f1f5f9;
border: 1px solid #475569;
border-radius: 6px;
padding: 0.45rem 0.7rem;
font-size: 0.85rem;
font-weight: 600;
cursor: pointer;
}
.toolbar button.primary { background: #2563eb; border-color: #2563eb; }
.toolbar button.danger { background: #7f1d1d; border-color: #991b1b; }
.toolbar button:hover, .nudge button:hover { filter: brightness(1.1); }
.toolbar button:disabled { opacity: 0.5; cursor: default; }
.status {
font-size: 0.8rem;
min-height: 1.2em;
color: #94a3b8;
}
.status.dirty { color: #fbbf24; }
.status.ok { color: #34d399; }
.status.err { color: #f87171; }
.step-row {
display: flex;
align-items: center;
gap: 0.5rem;
font-size: 0.85rem;
}
.step-row input[type="number"] {
width: 4.5rem;
background: #0f172a;
border: 1px solid #475569;
color: #f1f5f9;
border-radius: 4px;
padding: 0.3rem 0.4rem;
}
.section {
border: 1px solid #334155;
border-radius: 8px;
padding: 0.65rem;
background: #0f172a66;
}
.section h2 {
font-size: 0.75rem;
text-transform: uppercase;
letter-spacing: 0.04em;
color: #94a3b8;
margin-bottom: 0.5rem;
}
.field-block {
border-radius: 6px;
padding: 0.4rem;
margin-bottom: 0.35rem;
border: 1px solid transparent;
}
.field-block.active {
border-color: #3b82f6;
background: rgba(59, 130, 246, 0.12);
}
.field-block h3 {
font-size: 0.85rem;
margin-bottom: 0.35rem;
color: #f8fafc;
}
.nudge {
display: grid;
grid-template-columns: 4.5rem 1fr auto auto auto;
gap: 0.3rem;
align-items: center;
margin-bottom: 0.25rem;
font-size: 0.8rem;
}
.nudge label { color: #94a3b8; }
.nudge input[type="number"] {
width: 100%;
background: #0f172a;
border: 1px solid #475569;
color: #f1f5f9;
border-radius: 4px;
padding: 0.25rem 0.35rem;
font-variant-numeric: tabular-nums;
}
.nudge button { padding: 0.2rem 0.55rem; min-width: 2rem; }
.preview-wrap {
padding: 1.25rem;
overflow: auto;
display: flex;
justify-content: center;
align-items: flex-start;
}
.a4-page { .a4-page {
width: 210mm; width: 210mm; height: 297mm; background: white; position: relative;
height: 297mm; box-shadow: 0 10px 25px rgba(0,0,0,0.15); overflow: hidden;
background: white;
position: relative;
box-shadow: 0 10px 25px rgba(0,0,0,0.35);
overflow: hidden;
background-image: background-image:
linear-gradient(to right, #e2e8f0 1px, transparent 1px), linear-gradient(to right, #e2e8f0 1px, transparent 1px),
linear-gradient(to bottom, #e2e8f0 1px, transparent 1px); linear-gradient(to bottom, #e2e8f0 1px, transparent 1px);
background-size: 10mm 10mm; background-size: 10mm 10mm;
flex-shrink: 0;
transform-origin: top center;
} }
.slip-grid { .slip-grid {
display: grid; display: grid; grid-template-columns: 1fr 1fr; grid-template-rows: 1fr 1fr;
grid-template-columns: 1fr 1fr; width: 100%; height: 100%;
grid-template-rows: 1fr 1fr;
width: 100%;
height: 100%;
} }
.slip-quadrant { .slip-quadrant { position: relative; width: 105mm; height: 148.5mm; border: 1px dashed #cbd5e1; }
position: relative;
width: 105mm;
height: 148.5mm;
border: 1px dashed #cbd5e1;
}
.var-field { .var-field {
color: #dc2626; position: absolute; font-family: Arial, sans-serif; font-weight: bold;
cursor: pointer; color: red; /* Red for visibility during calibration */
outline: 1px solid transparent;
padding: 0 1px;
}
.var-field:hover { outline-color: #3b82f6; }
.var-field.selected {
outline: 2px solid #2563eb;
background: rgba(37, 99, 235, 0.12);
}
.var-field::before {
content: "┼";
position: absolute;
left: -10px;
top: -5px;
color: #2563eb;
font-size: 20px;
pointer-events: none;
} }
.q-tag { .crosshair::before {
position: absolute; content: "┼"; position: absolute; left: -10px; top: -5px; color: blue; font-size: 20px;
top: 4px;
left: 6px;
font-size: 10px;
color: #64748b;
font-family: sans-serif;
pointer-events: none;
} }
.val-batch { font-size: 15pt; top: 65mm; left: 20mm; }
.val-date { font-size: 13pt; top: 65mm; left: 60mm; }
.val-next { font-size: 15pt; top: 72mm; left: 50mm; }
.val-weight { font-size: 15pt; top: 80mm; left: 20mm; }
@media print { @media print {
@page { size: A4 portrait; margin: 0; } @page { size: A4 portrait; margin: 0; }
body { background: none; margin: 0; color: #000; } body { background: none; margin: 0; }
.panel { display: none !important; } .preview-controls { display: none; }
.layout { display: block; } .page-wrapper { margin: 0; padding: 0; display: block; }
.preview-wrap { margin: 0; padding: 0; display: block; overflow: visible; } .a4-page { box-shadow: none; width: 100%; height: 100vh; background-image: none; }
.a4-page {
box-shadow: none;
width: 100%;
height: 100vh;
background-image: none;
transform: none !important;
}
.slip-quadrant { border: none; }
.q-tag { display: none; }
.var-field { color: #000; outline: none !important; background: none !important; }
.var-field::before { display: none; }
}
@media (max-width: 900px) {
.layout { grid-template-columns: 1fr; }
.panel { max-height: none; border-right: none; border-bottom: 1px solid #334155; }
} }
</style> </style>
</head> </head>
<body> <body>
<div class="layout"> <div class="preview-controls">
<aside class="panel"> <p style="margin-bottom: 10px;">Calibration Sheet. Print this on blank paper and overlay on a pre-printed label against light.</p>
<h1>Label calibration</h1> <button onclick="window.print()">🖨️ Print Calibration</button>
<p class="hint"> <button onclick="window.close()" style="background:#64748b; margin-left: 10px;">Close</button>
Nudge fields in mm, print on blank A4, overlay on a pre-printed sheet against light.
Save writes <code>data/calibration.json</code> (used by real prints too).
</p>
<div class="toolbar">
<button type="button" class="primary" id="btn-save">Save</button>
<button type="button" id="btn-print">Print</button>
<button type="button" id="btn-backup">Backup</button>
<button type="button" id="btn-restore">Restore</button>
<input type="file" id="restore-file" accept="application/json,.json" hidden>
<button type="button" class="danger" id="btn-reset">Reset defaults</button>
<a href="{% url 'entry' %}" style="align-self:center;color:#93c5fd;font-size:0.85rem;margin-left:0.25rem;">← Back</a>
</div>
<div class="status" id="status">Loaded from server</div>
<div class="step-row">
<label for="step">Step</label>
<input type="number" id="step" value="0.5" min="0.1" max="5" step="0.1">
<span>mm</span>
</div> </div>
<div class="section" id="sec-top"> <div class="page-wrapper">
<h2>Top row (TL / TR base)</h2> <div class="a4-page">
</div>
<div class="section" id="sec-bottom">
<h2>Bottom row overrides</h2>
</div>
<div class="section" id="sec-right">
<h2>Right column overrides</h2>
</div>
</aside>
<div class="preview-wrap">
<div class="a4-page" id="a4-page">
<div class="slip-grid"> <div class="slip-grid">
{% for label in quadrants %} {% for i in "1234" %}
<div class="slip-quadrant" data-q="{{ label }}"> <div class="slip-quadrant">
<span class="q-tag">{{ label }}</span> <div class="var-field crosshair val-batch">[Batch#]</div>
<div class="var-field val-batch" data-field="batch" data-scope="{{ label }}">[Batch#]</div> <div class="var-field crosshair val-date">[Date]</div>
<div class="var-field val-date" data-field="date" data-scope="{{ label }}">[Date]</div> <div class="var-field crosshair val-next">[Next Control]</div>
<div class="var-field val-next" data-field="next" data-scope="{{ label }}">[Next]</div> <div class="var-field crosshair val-weight">[Weight]</div>
<div class="var-field val-weight" data-field="weight" data-scope="{{ label }}">[Weight]</div>
</div> </div>
{% endfor %} {% endfor %}
</div> </div>
</div> </div>
</div> </div>
</div>
{{ calibration_json|json_script:"calibration-data" }}
<script src="{% static 'slips/js/calibrate.js' %}"></script>
</body> </body>
</html> </html>

View File

@@ -1,84 +0,0 @@
{% extends 'slips/base.html' %}
{% load static %}
{% block title %}Orders — Label Printer{% endblock %}
{% block nav_crm_active %}active{% endblock %}
{% block content %}
<div class="page-grid print-queue-layout">
<section class="card glass-card">
<div class="card-header card-header-wrap">
<div>
<h2 class="card-title" data-i18n="crm_orders_title">حواله‌ها</h2>
</div>
<div class="card-actions">
<span id="crm-account" class="card-subtitle" hidden></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>
<p class="empty-state" id="crm-orders-status" hidden></p>
<div class="table-wrap">
<table class="data-table" id="crm-orders-table">
<thead>
<tr>
<th data-i18n="date">تاریخ</th>
<th data-i18n="product_code">کد محصول</th>
<th data-i18n="product_title">عنوان</th>
<th data-i18n="note_qty">مقدار حواله</th>
<th data-i18n="delivered_qty">تحویل‌شده</th>
<th data-i18n="remaining_qty">مانده</th>
</tr>
</thead>
<tbody id="crm-orders-body"></tbody>
</table>
</div>
</section>
</div>
<div id="toast" class="toast"></div>
{% endblock %}
{% block extra_head %}
<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 %}

View File

@@ -1,7 +1,7 @@
{% extends 'slips/base.html' %} {% extends 'slips/base.html' %}
{% load static %} {% load static %}
{% block title %}Data Entry — Label Printer{% endblock %} {% block title %}Data Entry — Product Slip Manager{% endblock %}
{% block nav_entry_active %}active{% endblock %} {% block nav_entry_active %}active{% endblock %}
{% block content %} {% block content %}
@@ -18,11 +18,34 @@
<select id="product" required> <select id="product" required>
<option value="">— Select —</option> <option value="">— Select —</option>
{% for p in products %} {% for p in products %}
<option value="{{ p.id }}" data-code="{{ p.code }}" data-weight="{{ p.default_net_weight }}" data-requires-dates="{{ p.requires_dates|yesno:'true,false' }}"> <option value="{{ p.id }}" data-weight="{{ p.default_net_weight }}">
{{ p.code }} — {{ p.description }} {{ p.code }} — {{ p.description }}
</option> </option>
{% endfor %} {% endfor %}
</select> </select>
<button type="button" class="btn btn-sm btn-ghost" onclick="showAddProduct()" data-i18n="add_product">+ Add New Product</button>
</div>
<!-- Add Product Inline (hidden) -->
<div id="add-product-panel" class="sub-panel" style="display:none;">
<div class="form-row">
<div class="form-group">
<label for="new-code" data-i18n="product_code">Product Code</label>
<input type="text" id="new-code" placeholder="ICJ/000">
</div>
<div class="form-group">
<label for="new-desc" data-i18n="description">Description</label>
<input type="text" id="new-desc" placeholder="DIGITAL INK ...">
</div>
<div class="form-group">
<label for="new-weight" data-i18n="default_weight">Default Weight</label>
<input type="number" id="new-weight" value="5" step="0.1" min="0.1">
</div>
</div>
<div class="form-actions-inline">
<button type="button" class="btn btn-accent btn-sm" onclick="addProduct()" data-i18n="save">Save</button>
<button type="button" class="btn btn-ghost btn-sm" onclick="hideAddProduct()" data-i18n="cancel">Cancel</button>
</div>
</div> </div>
<div class="form-group"> <div class="form-group">
@@ -30,42 +53,36 @@
<input type="text" id="batch" required placeholder="1028/26"> <input type="text" id="batch" required placeholder="1028/26">
</div> </div>
<div class="form-row" id="date-fields"> <div class="form-row">
<div class="form-group"> <div class="form-group">
<label for="prod-date" data-i18n="date">Date</label> <label for="prod-date" data-i18n="date">Date</label>
<input type="text" id="prod-date" placeholder="dd/mm/yyyy" pattern="\d{2}/\d{2}/\d{4}" inputmode="numeric" autocomplete="off"> <input type="date" id="prod-date" required>
</div> </div>
<div class="form-group"> <div class="form-group">
<label for="next-control" data-i18n="next_control">Next Control Date</label> <label for="next-control" data-i18n="next_control">Next Control Date</label>
<input type="text" id="next-control" placeholder="dd/mm/yyyy" pattern="\d{2}/\d{2}/\d{4}" inputmode="numeric" autocomplete="off"> <input type="date" id="next-control" required>
</div> </div>
</div> </div>
<div class="form-row"> <div class="form-row">
<div class="form-group"> <div class="form-group">
<label for="total-weight" data-i18n="total_weight">Total Weight (kg)</label> <label for="total-weight" data-i18n="total_weight">Total Weight (kg)</label>
<input type="number" id="total-weight" required step="1" min="1" value="100"> <input type="number" id="total-weight" required step="0.1" min="0.1" value="100">
</div> </div>
<div class="form-group"> <div class="form-group">
<label for="canister-weight" data-i18n="canister_weight">Canister Weight (kg)</label> <label for="canister-weight" data-i18n="canister_weight">Canister Weight (kg)</label>
<input type="number" id="canister-weight" required step="1" min="1" value="5"> <input type="number" id="canister-weight" required step="0.1" min="0.1" value="5">
</div> </div>
<div class="form-group"> <div class="form-group">
<label for="canisters-per-box" data-i18n="canisters_per_box">Canisters per Box</label> <label for="canisters-per-box" data-i18n="canisters_per_box">Canisters per Box</label>
<input type="number" id="canisters-per-box" required step="1" min="1" value="4"> <input type="number" id="canisters-per-box" required min="1" value="4">
</div> </div>
</div> </div>
<div class="form-group">
<label data-i18n="custom_labels">Custom Labels</label>
<div id="custom-lines" class="custom-lines"></div>
<button type="button" class="btn btn-ghost btn-sm" id="add-custom-line" data-i18n="add_custom_label">+ Add custom label</button>
</div>
<div class="form-group"> <div class="form-group">
<label data-i18n="labels_preview">Labels Generated</label> <label data-i18n="labels_preview">Labels Generated</label>
<div class="computed-value" style="font-size: 0.9em" id="preview-display"> <div class="computed-value" style="font-size: 0.9em" id="preview-display">
Canisters: - | Boxes: - | - pages Canisters: - ( - pages ) | Boxes: - ( - pages )
</div> </div>
</div> </div>
@@ -82,81 +99,36 @@
<h2 class="card-title" data-i18n="recent_orders">Recent Orders</h2> <h2 class="card-title" data-i18n="recent_orders">Recent Orders</h2>
<span class="card-badge badge-muted" id="order-count">{{ orders|length }}</span> <span class="card-badge badge-muted" id="order-count">{{ orders|length }}</span>
</div> </div>
<div class="table-wrap table-wrap-capped"> <div class="table-wrap">
<table class="data-table" id="orders-table"> <table class="data-table" id="orders-table">
<thead> <thead>
<tr> <tr>
<th>#</th> <th>#</th>
<th data-i18n="product">Product</th> <th data-i18n="product">Product</th>
<th data-i18n="batch_number">Batch</th> <th data-i18n="batch_number">Batch</th>
<th data-i18n="labels">Labels</th> <th data-i18n="canisters">Canisters</th>
<th data-i18n="total_pages">Pages</th> <th data-i18n="boxes">Boxes</th>
<th data-i18n="status">Status</th> <th data-i18n="status">Status</th>
<th></th>
</tr> </tr>
</thead> </thead>
<tbody id="orders-body"> <tbody id="orders-body">
{% for o in orders %} {% for o in orders %}
<tr id="order-row-{{ o.id }}"> <tr>
<td class="mono">{{ o.id }}</td> <td class="mono">{{ o.id }}</td>
<td>{{ o.product.code }}</td> <td>{{ o.product.code }}</td>
<td class="mono">{{ o.batch_number }}</td> <td class="mono">{{ o.batch_number }}</td>
<td class="labels-cell"> <td>{{ o.canister_count }}</td>
<div class="label-counts"> <td>{{ o.box_count }}</td>
<td><span class="badge badge-{{ o.status }}">{{ o.get_status_display }}</span></td>
<td>
{% if o.status == 'pending' %} {% if o.status == 'pending' %}
<div class="count-stepper"> <button class="btn btn-ghost btn-sm btn-danger" onclick="deleteOrder({{ o.id }})" data-i18n="cancel">Cancel</button>
<span class="stepper-label">{{ o.canister_weight|floatformat:-2 }} kg</span>
<button type="button" class="stepper-btn" onclick="adjustCount({{ o.id }}, 'canister_count', -1)" aria-label="-">−</button>
<span id="cc-{{ o.id }}">{{ o.canister_count }}</span>
<button type="button" class="stepper-btn" onclick="adjustCount({{ o.id }}, 'canister_count', 1)" aria-label="+">+</button>
</div>
<div class="count-stepper">
<span class="stepper-label">{{ o.box_weight|floatformat:-2 }} kg</span>
<button type="button" class="stepper-btn" onclick="adjustCount({{ o.id }}, 'box_count', -1)" aria-label="-">−</button>
<span id="bc-{{ o.id }}">{{ o.box_count }}</span>
<button type="button" class="stepper-btn" onclick="adjustCount({{ o.id }}, 'box_count', 1)" aria-label="+">+</button>
</div>
{% else %}
<div class="mono">{{ o.canister_weight|floatformat:-2 }} kg × <span id="cc-{{ o.id }}">{{ o.canister_count }}</span></div>
<div class="mono">{{ o.box_weight|floatformat:-2 }} kg × <span id="bc-{{ o.id }}">{{ o.box_count }}</span></div>
{% endif %}
<div id="custom-{{ o.id }}">
{% if o.custom_labels %}
<div class="custom-label-list">
{% if o.status == 'pending' %}
{% for line in o.custom_labels %}
<div class="count-stepper" data-weight="{{ line.weight }}">
<span class="stepper-label">{{ line.weight|floatformat:-2 }} kg</span>
<button type="button" class="stepper-btn" onclick="adjustCustomCount({{ o.id }}, {{ forloop.counter0 }}, -1)" aria-label="-">−</button>
<span class="cl-count">{{ line.count }}</span>
<button type="button" class="stepper-btn" onclick="adjustCustomCount({{ o.id }}, {{ forloop.counter0 }}, 1)" aria-label="+">+</button>
</div>
{% endfor %}
{% else %}
{% for line in o.custom_labels %}
<div class="mono">{{ line.weight|floatformat:-2 }} kg × {{ line.count }}</div>
{% endfor %}
{% endif %}
</div>
{% endif %}
</div>
</div>
</td>
<td class="mono" id="pages-{{ o.id }}">{{ o.canister_pages|add:o.box_pages }}</td>
<td class="status-cell">
{% if o.status == 'pending' %}
<span class="badge badge-pending">⏳ <span data-i18n="status_pending">Pending</span></span>
<button type="button" class="badge badge-pending" onclick="deleteOrder({{ o.id }})" title="حذف" aria-label="حذف" data-i18n-title="remove" data-i18n-aria="remove">×</button>
{% elif o.status == 'done' %}
<span class="badge badge-done">✓ <span data-i18n="status_done">Done</span></span>
{% elif o.status == 'printing' %}
<span class="badge badge-accent">🖨 <span data-i18n="status_printing">Printing</span></span>
{% else %}
<span class="badge badge-cancelled">✕ <span data-i18n="status_cancelled">Cancelled</span></span>
{% endif %} {% endif %}
</td> </td>
</tr> </tr>
{% empty %} {% empty %}
<tr><td colspan="6" class="empty-state" data-i18n="no_orders">No orders yet</td></tr> <tr><td colspan="7" class="empty-state" data-i18n="no_orders">No orders yet</td></tr>
{% endfor %} {% endfor %}
</tbody> </tbody>
</table> </table>
@@ -169,5 +141,5 @@
{% endblock %} {% endblock %}
{% block extra_scripts %} {% block extra_scripts %}
<script src="{% static 'slips/js/entry.js' %}?v=4"></script> <script src="{% static 'slips/js/entry.js' %}"></script>
{% endblock %} {% endblock %}

View File

@@ -1,7 +1,7 @@
{% extends 'slips/base.html' %} {% extends 'slips/base.html' %}
{% load static %} {% load static %}
{% block title %}Print Queue — Label Printer{% endblock %} {% block title %}Print Queue — Product Slip Manager{% endblock %}
{% block nav_print_active %}active{% endblock %} {% block nav_print_active %}active{% endblock %}
{% block content %} {% block content %}
@@ -21,7 +21,7 @@
<div class="queue-item card" id="order-{{ o.id }}"> <div class="queue-item card" id="order-{{ o.id }}">
<div class="queue-item-header"> <div class="queue-item-header">
<span class="order-id mono">#{{ o.id }}</span> <span class="order-id mono">#{{ o.id }}</span>
<span class="badge badge-pending">⏳ <span data-i18n="status_pending">Pending</span></span> <span class="badge badge-pending">⏳ Pending</span>
</div> </div>
<div class="queue-item-body"> <div class="queue-item-body">
<h3 class="product-title">{{ o.product.code }} — {{ o.product.description }}</h3> <h3 class="product-title">{{ o.product.code }} — {{ o.product.description }}</h3>
@@ -30,19 +30,22 @@
<span class="label" data-i18n="batch_number">Batch:</span> <span class="label" data-i18n="batch_number">Batch:</span>
<span class="value mono">{{ o.batch_number }}</span> <span class="value mono">{{ o.batch_number }}</span>
</div> </div>
{% if o.product.requires_dates %}
<div class="detail-col"> <div class="detail-col">
<span class="label" data-i18n="date">Date:</span> <span class="label" data-i18n="date">Date:</span>
<span class="value">{{ o.production_date|date:"d/m/Y" }}</span> <span class="value">{{ o.production_date|date:"d/m/Y" }}</span>
</div> </div>
<div class="detail-col">
<span class="label" data-i18n="total_weight">Total:</span>
<span class="value">{{ o.total_weight }} kg</span>
</div>
<div class="detail-col"> <div class="detail-col">
<span class="label" data-i18n="next_control">Next:</span> <span class="label" data-i18n="next_control">Next:</span>
<span class="value">{{ o.next_control_date|date:"d/m/Y" }}</span> <span class="value">{{ o.next_control_date|date:"d/m/Y" }}</span>
</div> </div>
{% endif %}
</div> </div>
<div class="print-meta"> <div class="print-meta">
<span class="badge badge-accent">{{ o.canister_pages|add:o.box_pages }} <span data-i18n="pages_unit">Page(s)</span></span> <span class="badge badge-neutral">{{ o.canister_count }} Canisters | {{ o.box_count }} Boxes</span>
<span class="badge badge-accent">{{ o.canister_pages|add:o.box_pages }} Page(s)</span>
</div> </div>
</div> </div>
<div class="queue-item-actions"> <div class="queue-item-actions">
@@ -78,7 +81,6 @@
<th data-i18n="batch_number">Batch</th> <th data-i18n="batch_number">Batch</th>
<th data-i18n="total_pages">Pages</th> <th data-i18n="total_pages">Pages</th>
<th data-i18n="printed_at">Printed At</th> <th data-i18n="printed_at">Printed At</th>
<th></th>
</tr> </tr>
</thead> </thead>
<tbody id="history-body"> <tbody id="history-body">
@@ -89,12 +91,9 @@
<td class="mono">{{ o.batch_number }}</td> <td class="mono">{{ o.batch_number }}</td>
<td>{{ o.canister_pages|add:o.box_pages }}</td> <td>{{ o.canister_pages|add:o.box_pages }}</td>
<td>{{ o.printed_at|date:"d/m/Y H:i" }}</td> <td>{{ o.printed_at|date:"d/m/Y H:i" }}</td>
<td>
<button class="btn btn-ghost btn-sm" onclick="undoDone({{ o.id }})" data-i18n="undo_done">Undo</button>
</td>
</tr> </tr>
{% empty %} {% empty %}
<tr><td colspan="6" class="empty-state" data-i18n="no_history">No print history</td></tr> <tr><td colspan="5" class="empty-state" data-i18n="no_history">No print history</td></tr>
{% endfor %} {% endfor %}
</tbody> </tbody>
</table> </table>

View File

@@ -5,10 +5,6 @@
<meta charset="UTF-8"> <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Print Order #{{ order.id }}</title> <title>Print Order #{{ order.id }}</title>
<link rel="stylesheet" href="{% static 'slips/css/label_print.css' %}">
<style id="calibration-vars">
{{ calibration_css|safe }}
</style>
<style> <style>
/* Base reset and print-specific settings */ /* Base reset and print-specific settings */
* { * {
@@ -48,37 +44,12 @@
font-weight: bold; font-weight: bold;
} }
.preview-controls button:hover:not(:disabled) { .preview-controls button:hover {
background: #2563eb; background: #2563eb;
} }
.preview-controls button:disabled {
opacity: 0.55;
cursor: wait;
}
.preview-controls .page-range {
display: inline-flex;
align-items: center;
gap: 8px;
margin-right: 12px;
font-family: sans-serif;
font-size: 14px;
vertical-align: middle;
}
.preview-controls .page-range input {
width: 4.5em;
padding: 8px 6px;
font-size: 16px;
border: 1px solid #475569;
border-radius: 6px;
background: #0f172a;
color: #fff;
}
.page-wrapper { .page-wrapper {
margin-top: 110px; /* Space for controls */ margin-top: 80px; /* Space for controls */
display: flex; display: flex;
flex-direction: column; flex-direction: column;
align-items: center; align-items: center;
@@ -98,25 +69,6 @@
page-break-after: always; page-break-after: always;
} }
.a4-page.skip-print {
opacity: 0.4;
}
.page-badge {
position: absolute;
top: 8px;
right: 8px;
z-index: 2;
background: #1e293b;
color: #fff;
font-family: sans-serif;
font-size: 12px;
font-weight: bold;
padding: 4px 8px;
border-radius: 4px;
pointer-events: none;
}
/* CSS Grid for the 4 slips */ /* CSS Grid for the 4 slips */
.slip-grid { .slip-grid {
display: grid; display: grid;
@@ -132,6 +84,46 @@
height: 148.5mm; /* Half height */ height: 148.5mm; /* Half height */
} }
/*
* EXACT POSITIONING CALIBRATION
* These values map to the Excel cells:
* Batch: C18
* Date: G18
* Weight: C20
* Next Control: F19
*/
.var-field {
position: absolute;
font-family: Arial, sans-serif;
font-weight: bold;
white-space: nowrap;
}
.val-batch {
font-size: 15pt;
top: 65mm;
left: 20mm;
}
.val-date {
font-size: 13pt;
top: 65mm;
left: 60mm;
}
.val-next {
font-size: 15pt;
top: 72mm;
left: 50mm;
}
.val-weight {
font-size: 15pt;
top: 80mm;
left: 20mm;
}
/* Print Media Query */ /* Print Media Query */
@media print { @media print {
@page { @page {
@@ -159,15 +151,6 @@
box-shadow: none; box-shadow: none;
width: 100%; width: 100%;
height: 100vh; /* Fill printed page */ height: 100vh; /* Fill printed page */
opacity: 1;
}
.a4-page.skip-print {
display: none !important;
}
.page-badge {
display: none;
} }
} }
</style> </style>
@@ -176,127 +159,64 @@
<div class="preview-controls"> <div class="preview-controls">
<p style="margin-bottom: 10px; font-family: sans-serif;"> <p style="margin-bottom: 10px; font-family: sans-serif;">
Order #{{ order.id }} — {{ order.product.code }} <br> Order #{{ order.id }} — {{ order.product.code }} <br>
{% if order.custom_count %}{{ order.custom_count }} Custom |{% endif %} {{ order.canister_count }} Canisters ({{ order.canister_pages }} Pages) |
{{ order.canister_count }} Canisters | {{ order.box_count }} Boxes ({{ order.box_pages }} Pages)
{{ order.box_count }} Boxes |
{{ order.canister_pages|add:order.box_pages }} Pages
</p> </p>
<label class="page-range"> <button onclick="window.print()">🖨️ Print Now</button>
Pages <button onclick="window.close()" style="background:#64748b; margin-left: 10px;">Close</button>
<input id="start-from" type="number" min="1" max="{{ pages|length }}" value="1" {% if not pages %}disabled{% endif %}>
–
<input id="end-at" type="number" min="1" max="{{ pages|length }}" value="{{ pages|length }}" {% if not pages %}disabled{% endif %}>
/ {{ pages|length }}
</label>
<button id="btn-print" type="button" disabled>🖨️ Print Now</button>
<button type="button" onclick="window.close()" style="background:#64748b; margin-left: 10px;">Close</button>
</div> </div>
<div class="page-wrapper"> <div class="page-wrapper">
{% for page in pages %} {% for page in pages %}
<div class="a4-page" data-page="{{ forloop.counter }}"> <div class="a4-page">
<div class="page-badge">Page {{ forloop.counter }} / {{ pages|length }}</div>
<div class="slip-grid"> <div class="slip-grid">
{% for weight in page.slips %} <!-- Top Left -->
<div class="slip-quadrant"> <div class="slip-quadrant">
{% if 0 in page.slips %}
<div class="var-field val-batch">{{ order.batch_number }}</div> <div class="var-field val-batch">{{ order.batch_number }}</div>
{% if show_dates %}
<div class="var-field val-date">{{ date_formatted }}</div> <div class="var-field val-date">{{ date_formatted }}</div>
<div class="var-field val-next">{{ next_control_formatted }}</div> <div class="var-field val-next">{{ next_control_formatted }}</div>
<div class="var-field val-weight">{{ page.weight }}</div>
{% endif %}
</div>
<!-- Top Right -->
<div class="slip-quadrant">
{% if 1 in page.slips %}
<div class="var-field val-batch">{{ order.batch_number }}</div>
<div class="var-field val-date">{{ date_formatted }}</div>
<div class="var-field val-next">{{ next_control_formatted }}</div>
<div class="var-field val-weight">{{ page.weight }}</div>
{% endif %}
</div>
<!-- Bottom Left -->
<div class="slip-quadrant">
{% if 2 in page.slips %}
<div class="var-field val-batch">{{ order.batch_number }}</div>
<div class="var-field val-date">{{ date_formatted }}</div>
<div class="var-field val-next">{{ next_control_formatted }}</div>
<div class="var-field val-weight">{{ page.weight }}</div>
{% endif %}
</div>
<!-- Bottom Right -->
<div class="slip-quadrant">
{% if 3 in page.slips %}
<div class="var-field val-batch">{{ order.batch_number }}</div>
<div class="var-field val-date">{{ date_formatted }}</div>
<div class="var-field val-next">{{ next_control_formatted }}</div>
<div class="var-field val-weight">{{ page.weight }}</div>
{% endif %} {% endif %}
<div class="var-field val-weight">{{ weight }}</div>
</div> </div>
{% endfor %}
</div> </div>
</div> </div>
{% endfor %} {% endfor %}
</div> </div>
<script> <script>
(function () { // Optional: auto-trigger print dialog when opened
const FIELDS = ['batch', 'date', 'next', 'weight']; // window.onload = function() { window.print(); }
const varsEl = document.getElementById('calibration-vars');
const btn = document.getElementById('btn-print');
const startInput = document.getElementById('start-from');
const endInput = document.getElementById('end-at');
const pages = document.querySelectorAll('.a4-page');
const total = pages.length;
function cssFromCal(cal) {
const lines = [':root {'];
for (const field of FIELDS) {
const v = cal[field];
lines.push(' --' + field + '-top: ' + v.top + 'mm;');
lines.push(' --' + field + '-left: ' + v.left + 'mm;');
lines.push(' --' + field + '-font: ' + v.font + 'pt;');
lines.push(' --' + field + '-bottom-top: ' + v.bottom_top + 'mm;');
if (v.bottom_left != null) {
lines.push(' --' + field + '-bottom-left: ' + v.bottom_left + 'mm;');
}
if (v.right_left != null) {
lines.push(' --' + field + '-right-left: ' + v.right_left + 'mm;');
}
}
lines.push('}');
return lines.join('\n');
}
function clampPage(n) {
if (!total) return 1;
n = parseInt(n, 10);
if (isNaN(n) || n < 1) return 1;
if (n > total) return total;
return n;
}
function applySkip() {
let start = clampPage(startInput.value);
let end = clampPage(endInput.value);
if (start > end) end = start;
startInput.value = start;
endInput.value = end;
pages.forEach(function (el) {
const pageNum = parseInt(el.getAttribute('data-page'), 10);
el.classList.toggle('skip-print', pageNum < start || pageNum > end);
});
}
function seedFromQuery() {
const params = new URLSearchParams(window.location.search);
const from = params.get('from');
const to = params.get('to');
if (from != null) startInput.value = clampPage(from);
if (to != null) endInput.value = clampPage(to);
applySkip();
}
function enablePrint() {
btn.disabled = false;
btn.onclick = function () {
applySkip();
window.print();
};
}
startInput.addEventListener('change', applySkip);
startInput.addEventListener('input', applySkip);
endInput.addEventListener('change', applySkip);
endInput.addEventListener('input', applySkip);
seedFromQuery();
fetch('/api/calibration', { cache: 'no-store' })
.then(function (res) {
if (!res.ok) throw new Error('HTTP ' + res.status);
return res.json();
})
.then(function (cal) {
varsEl.textContent = cssFromCal(cal);
})
.catch(function () {
// Keep server-rendered vars; still allow print
})
.finally(enablePrint);
})();
</script> </script>
</body> </body>
</html> </html>

View File

@@ -1,99 +0,0 @@
{% extends 'slips/base.html' %}
{% load static %}
{% block title %}Products — Label Printer{% endblock %}
{% block nav_products_active %}active{% endblock %}
{% block content %}
<div class="page-grid">
<!-- Add / Edit Product -->
<section class="card glass-card">
<div class="card-header">
<h2 class="card-title" id="product-form-title" data-i18n="add_product">+ Add New Product</h2>
<span class="card-badge badge-accent">📦</span>
</div>
<form id="product-form" class="form-stack">
<input type="hidden" id="edit-id" value="">
<div class="form-group">
<label for="prod-code" data-i18n="product_code">Product Code</label>
<input type="text" id="prod-code" required placeholder="ICJ/000">
</div>
<div class="form-group">
<label for="prod-desc" data-i18n="description">Description</label>
<input type="text" id="prod-desc" required placeholder="DIGITAL INK ...">
</div>
<div class="form-group">
<label for="prod-weight" data-i18n="default_weight">Default Weight</label>
<input type="number" id="prod-weight" value="5" step="1" min="1" required>
</div>
<div class="form-group">
<label class="checkbox-label">
<input type="checkbox" id="prod-requires-dates" checked>
<span data-i18n="requires_dates">Requires Date / Next Control</span>
</label>
</div>
<div class="form-actions-inline">
<button type="submit" class="btn btn-accent" id="product-save-btn" data-i18n="save">Save</button>
<button type="button" class="btn btn-ghost" id="product-cancel-btn" style="display:none;" onclick="cancelEdit()" data-i18n="cancel">Cancel</button>
</div>
</form>
</section>
<!-- Product List -->
<section class="card glass-card">
<div class="card-header">
<h2 class="card-title" data-i18n="products">Products</h2>
<div class="card-actions">
<button type="button" class="btn btn-ghost btn-sm" onclick="backupProducts()" data-i18n="backup">Backup</button>
<button type="button" class="btn btn-ghost btn-sm" onclick="document.getElementById('restore-file').click()" data-i18n="restore">Restore</button>
<input type="file" id="restore-file" accept="application/json,.json" hidden onchange="restoreProducts(this)">
<span class="card-badge badge-muted" id="product-count">{{ products|length }}</span>
</div>
</div>
<div class="table-wrap">
<table class="data-table" id="products-table">
<thead>
<tr>
<th data-i18n="product_code">Code</th>
<th data-i18n="description">Description</th>
<th data-i18n="default_weight">Weight</th>
<th data-i18n="requires_dates_short">Dates</th>
<th></th>
</tr>
</thead>
<tbody id="products-body">
{% for p in products %}
<tr id="product-row-{{ p.id }}">
<td class="mono">{{ p.code }}</td>
<td>{{ p.description }}</td>
<td class="mono">{{ p.default_net_weight }}</td>
<td>{{ p.requires_dates|yesno:"✓,—" }}</td>
<td>
<button type="button" class="btn btn-ghost btn-sm"
data-id="{{ p.id }}"
data-code="{{ p.code }}"
data-desc="{{ p.description }}"
data-weight="{{ p.default_net_weight }}"
data-requires-dates="{{ p.requires_dates|yesno:'true,false' }}"
onclick="editProduct(this)"
data-i18n="edit">Edit</button>
<button type="button" class="btn btn-ghost btn-sm btn-danger"
onclick="deleteProduct({{ p.id }})"
data-i18n="remove">Remove</button>
</td>
</tr>
{% empty %}
<tr><td colspan="5" class="empty-state" data-i18n="no_products">No products yet</td></tr>
{% endfor %}
</tbody>
</table>
</div>
</section>
</div>
<div id="toast" class="toast"></div>
{% endblock %}
{% block extra_scripts %}
<script src="{% static 'slips/js/products.js' %}"></script>
{% endblock %}

View File

@@ -1,277 +0,0 @@
import unittest
from datetime import date, timedelta
from types import SimpleNamespace
from unittest.mock import patch
from django.test import TestCase
from django.utils import timezone
from slips.crm_orders import (
SESSION_TTL_SECONDS,
CrmAuthError,
CrmOrdersError,
_load_order_export,
code_matches,
export_filtered_customer_orders,
format_jalali,
jalali_from_gregorian,
login_rejected,
note_date_as_jalali,
orders_after,
parse_gregorian,
parse_jalali,
parse_prefixes,
recent_customer_orders,
report_base_url,
report_filter_state,
)
def _line(note_date, number, code="P"):
return SimpleNamespace(
delivery_note_date=note_date,
delivery_note_number=number,
product_code=code,
)
class OrdersAfterTests(unittest.TestCase):
def test_gregorian_cutoff_converts_before_compare(self):
self.assertEqual(jalali_from_gregorian(date(2026, 3, 21)), (1405, 1, 1))
self.assertEqual(jalali_from_gregorian(date(2026, 11, 11)), (1405, 8, 20))
self.assertEqual(jalali_from_gregorian(date(2026, 9, 23)), (1405, 7, 1))
self.assertEqual(format_jalali(jalali_from_gregorian(date(2026, 3, 21))), "1405/01/01")
self.assertEqual(note_date_as_jalali("۱۴۰۵/۰۸/۱۶"), "1405/08/16")
self.assertEqual(parse_gregorian("2026-09-23"), date(2026, 9, 23))
self.assertEqual(parse_gregorian("23/09/2026"), date(2026, 9, 23))
self.assertIsNone(parse_gregorian("1405/07/01"))
lines = [
_line("1405/07/01", "0"),
_line("1405/07/19", "1"),
_line("۱۴۰۵/۰۷/۲۰", "2", "B"),
_line("1405/08/11", "3", "A"),
_line("not-a-date", "5"),
]
start = jalali_from_gregorian(parse_gregorian("2026-09-23"))
kept = orders_after(lines, start)
self.assertEqual([line.delivery_note_number for line in kept], ["3", "2", "1"])
self.assertIsNone(parse_jalali("1405/13/01"))
def test_code_prefix_list(self):
self.assertEqual(code_matches("ICJ/308", ["ICJ/"]), True)
self.assertEqual(code_matches("RMJ/001", ["ICJ/"]), False)
self.assertEqual(code_matches("RMJ/001", ["ICJ/", "RMJ"]), True)
self.assertEqual(code_matches("CGM5721", []), True)
self.assertEqual(parse_prefixes("ICJ/, RMJ/"), ["ICJ/", "RMJ/"])
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__":
unittest.main()

View File

@@ -1,8 +1,6 @@
import math
from django.shortcuts import render, redirect, get_object_or_404 from django.shortcuts import render, redirect, get_object_or_404
from django.views.decorators.cache import never_cache
from .calibration import css_vars, load_calibration
from .models import Product, Order from .models import Product, Order
from .print_layout import build_print_pages
def index(request): def index(request):
@@ -18,16 +16,6 @@ def entry(request):
}) })
def products(request):
return render(request, 'slips/products.html', {
'products': Product.objects.all(),
})
def crm_orders(request):
return render(request, 'slips/crm_orders.html')
def print_queue(request): def print_queue(request):
pending = Order.objects.select_related('product').filter(status='pending') pending = Order.objects.select_related('product').filter(status='pending')
history = Order.objects.select_related('product').filter(status='done').order_by('-printed_at')[:20] history = Order.objects.select_related('product').filter(status='done').order_by('-printed_at')[:20]
@@ -37,29 +25,41 @@ def print_queue(request):
}) })
@never_cache
def print_page(request, order_id): def print_page(request, order_id):
order = get_object_or_404(Order.objects.select_related('product'), id=order_id) order = get_object_or_404(Order.objects.select_related('product'), id=order_id)
pages = build_print_pages(order)
cal = load_calibration() pages = []
show_dates = order.product.requires_dates
# 1. Canister Labels
remaining_canisters = order.canister_count
for _ in range(order.canister_pages):
slips_on_page = min(4, remaining_canisters)
pages.append({
'type': 'Canister',
'weight': order.canister_weight,
'slips': range(slips_on_page),
})
remaining_canisters -= slips_on_page
# 2. Box Labels
remaining_boxes = order.box_count
box_weight = order.canister_weight * order.canisters_per_box
for _ in range(order.box_pages):
slips_on_page = min(4, remaining_boxes)
pages.append({
'type': 'Box',
'weight': box_weight,
'slips': range(slips_on_page),
})
remaining_boxes -= slips_on_page
return render(request, 'slips/print_page.html', { return render(request, 'slips/print_page.html', {
'order': order, 'order': order,
'pages': pages, 'pages': pages,
'show_dates': show_dates, 'date_formatted': order.production_date.strftime('%d/%m/%Y'),
'date_formatted': order.production_date.strftime('%d/%m/%Y') if order.production_date else '', 'next_control_formatted': order.next_control_date.strftime('%d/%m/%Y'),
'next_control_formatted': order.next_control_date.strftime('%d/%m/%Y') if order.next_control_date else '',
'calibration_css': css_vars(cal),
}) })
@never_cache
def calibrate(request): def calibrate(request):
cal = load_calibration() return render(request, 'slips/calibrate.html')
return render(request, 'slips/calibrate.html', {
'calibration': cal,
'calibration_css': css_vars(cal),
'calibration_json': cal,
'quadrants': ['TL', 'TR', 'BL', 'BR'],
})