Add orders tab for recent SystemGroup delivery notes
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
17
.env.example
17
.env.example
@@ -7,3 +7,20 @@ HTTP_PORT=80
|
|||||||
# Optional PyPI index URL for uv during image build
|
# Optional PyPI index URL for uv during image build
|
||||||
# PIP_INDEX_URL=https://pypi.tuna.tsinghua.edu.cn/simple
|
# PIP_INDEX_URL=https://pypi.tuna.tsinghua.edu.cn/simple
|
||||||
# PIP_TRUSTED_HOST=pypi.tuna.tsinghua.edu.cn
|
# PIP_TRUSTED_HOST=pypi.tuna.tsinghua.edu.cn
|
||||||
|
|
||||||
|
# SystemGroup store delivery-note report (Orders tab). Never commit real values.
|
||||||
|
# REPORT_BASE_URL=http://crm.example/
|
||||||
|
# REPORT_USERNAME=
|
||||||
|
# REPORT_PASSWORD=
|
||||||
|
# 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 the matching REPORT_* value is unset.
|
||||||
|
# CRM_BASE_URL=
|
||||||
|
# CRM_USERNAME=
|
||||||
|
# CRM_PASSWORD=
|
||||||
|
|||||||
@@ -3,6 +3,27 @@ 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'
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ urlpatterns = [
|
|||||||
path('entry/', views.entry, name='entry'),
|
path('entry/', views.entry, name='entry'),
|
||||||
path('products/', views.products, name='products'),
|
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'),
|
||||||
]
|
]
|
||||||
|
|||||||
@@ -13,6 +13,15 @@ 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_USERNAME=${REPORT_USERNAME:-}
|
||||||
|
- REPORT_PASSWORD=${REPORT_PASSWORD:-}
|
||||||
|
- REPORT_ORDERS_PATH=${REPORT_ORDERS_PATH:-}
|
||||||
|
- REPORT_ORDERS_SINCE=${REPORT_ORDERS_SINCE:-}
|
||||||
|
- REPORT_ORDERS_PREFIXES=${REPORT_ORDERS_PREFIXES:-}
|
||||||
|
- CRM_BASE_URL=${CRM_BASE_URL:-}
|
||||||
|
- CRM_USERNAME=${CRM_USERNAME:-}
|
||||||
|
- CRM_PASSWORD=${CRM_PASSWORD:-}
|
||||||
networks:
|
networks:
|
||||||
- web
|
- web
|
||||||
|
|
||||||
@@ -33,3 +42,7 @@ 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
|
||||||
|
|||||||
@@ -9,5 +9,6 @@ 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;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,3 +2,4 @@ django>=5.1,<5.3
|
|||||||
django-ninja>=1.7,<2.0
|
django-ninja>=1.7,<2.0
|
||||||
gunicorn>=22.0,<24.0
|
gunicorn>=22.0,<24.0
|
||||||
whitenoise>=6.7,<7.0
|
whitenoise>=6.7,<7.0
|
||||||
|
lithium-systemgroup @ git+https://github.com/s-diaco/lithium-systemgroup.git@1c237c3d2917c11a5d9ae49e868be73bef1720b5
|
||||||
|
|||||||
12
slips/api.py
12
slips/api.py
@@ -4,10 +4,11 @@ from django.shortcuts import get_object_or_404
|
|||||||
from django.utils import timezone
|
from django.utils import timezone
|
||||||
from ninja import NinjaAPI, Query
|
from ninja import NinjaAPI, Query
|
||||||
|
|
||||||
|
from .crm_orders import CrmOrdersError, recent_customer_orders
|
||||||
from .models import Product, Order, clean_custom_labels
|
from .models import Product, Order, clean_custom_labels
|
||||||
from .schemas import (
|
from .schemas import (
|
||||||
ProductOut, ProductIn, OrderOut, OrderIn, OrderUpdateIn,
|
ProductOut, ProductIn, OrderOut, OrderIn, OrderUpdateIn,
|
||||||
CalibrationIn, CalibrationOut,
|
CalibrationIn, CalibrationOut, CrmOrdersOut,
|
||||||
)
|
)
|
||||||
from .calibration import load_calibration, save_calibration, DEFAULTS, for_api
|
from .calibration import load_calibration, save_calibration, DEFAULTS, for_api
|
||||||
|
|
||||||
@@ -154,6 +155,15 @@ def delete_order(request, order_id: int):
|
|||||||
return 204, None
|
return 204, None
|
||||||
|
|
||||||
|
|
||||||
|
@api.get('/crm-orders', response={200: CrmOrdersOut, 502: dict}, tags=['Orders'])
|
||||||
|
def list_crm_orders(request):
|
||||||
|
"""Store delivery notes dated after REPORT_ORDERS_SINCE."""
|
||||||
|
try:
|
||||||
|
return recent_customer_orders()
|
||||||
|
except CrmOrdersError as exc:
|
||||||
|
return 502, {'detail': str(exc)}
|
||||||
|
|
||||||
|
|
||||||
# ─── Calibration ─────────────────────────────────────────
|
# ─── Calibration ─────────────────────────────────────────
|
||||||
|
|
||||||
@api.get('/calibration', response=CalibrationOut, tags=['Calibration'])
|
@api.get('/calibration', response=CalibrationOut, tags=['Calibration'])
|
||||||
|
|||||||
204
slips/crm_orders.py
Normal file
204
slips/crm_orders.py
Normal file
@@ -0,0 +1,204 @@
|
|||||||
|
"""Customer orders from SystemGroup, dated after REPORT_ORDERS_SINCE.
|
||||||
|
|
||||||
|
The cutoff in .env is a Gregorian date. Delivery-note dates on the report
|
||||||
|
are Jalali, so the cutoff is converted before the comparison.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import os
|
||||||
|
from datetime import date
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
_DIGIT_MAP = str.maketrans("۰۱۲۳۴۵۶۷۸۹٠١٢٣٤٥٦٧٨٩", "01234567890123456789")
|
||||||
|
_ENV_FILE = Path(__file__).resolve().parents[1] / ".env"
|
||||||
|
_SINCE_KEY = "REPORT_ORDERS_SINCE"
|
||||||
|
_PREFIX_KEY = "REPORT_ORDERS_PREFIXES"
|
||||||
|
|
||||||
|
|
||||||
|
class CrmOrdersError(RuntimeError):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def parse_jalali(raw: str) -> tuple[int, int, int] | None:
|
||||||
|
text = (raw or "").translate(_DIGIT_MAP).strip().replace("-", "/")
|
||||||
|
bits = text.split("/")
|
||||||
|
if len(bits) != 3 or not all(bit.isdigit() for bit in bits):
|
||||||
|
return None
|
||||||
|
year, month, day = (int(bit) for bit in bits)
|
||||||
|
if year < 1200 or not 1 <= month <= 12 or not 1 <= day <= 31:
|
||||||
|
return None
|
||||||
|
return year, month, day
|
||||||
|
|
||||||
|
|
||||||
|
def jalali_from_gregorian(day: date) -> tuple[int, int, int]:
|
||||||
|
gy, gm, gd = day.year, day.month, day.day
|
||||||
|
g_days = (0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334)
|
||||||
|
gy2 = gy + 1 if gm > 2 else gy
|
||||||
|
days = (
|
||||||
|
355666
|
||||||
|
+ 365 * gy
|
||||||
|
+ (gy2 + 3) // 4
|
||||||
|
- (gy2 + 99) // 100
|
||||||
|
+ (gy2 + 399) // 400
|
||||||
|
+ gd
|
||||||
|
+ g_days[gm - 1]
|
||||||
|
)
|
||||||
|
jy = -1595 + 33 * (days // 12053)
|
||||||
|
days %= 12053
|
||||||
|
jy += 4 * (days // 1461)
|
||||||
|
days %= 1461
|
||||||
|
if days > 365:
|
||||||
|
jy += (days - 1) // 365
|
||||||
|
days = (days - 1) % 365
|
||||||
|
if days < 186:
|
||||||
|
jm = 1 + days // 31
|
||||||
|
jd = 1 + (days % 31)
|
||||||
|
else:
|
||||||
|
jm = 7 + (days - 186) // 30
|
||||||
|
jd = 1 + ((days - 186) % 30)
|
||||||
|
return jy, jm, jd
|
||||||
|
|
||||||
|
|
||||||
|
def format_jalali(parts: tuple[int, int, int]) -> str:
|
||||||
|
year, month, day = parts
|
||||||
|
return f"{year:04d}/{month:02d}/{day:02d}"
|
||||||
|
|
||||||
|
|
||||||
|
def note_date_as_jalali(raw: str) -> str:
|
||||||
|
parsed = parse_jalali(raw)
|
||||||
|
if parsed is None:
|
||||||
|
return (raw or "").strip()
|
||||||
|
return format_jalali(parsed)
|
||||||
|
|
||||||
|
|
||||||
|
def parse_gregorian(raw: str) -> date | None:
|
||||||
|
"""Parse YYYY-MM-DD or DD/MM/YYYY. Years before 1700 are rejected."""
|
||||||
|
text = (raw or "").translate(_DIGIT_MAP).strip().replace("-", "/").replace(".", "/")
|
||||||
|
bits = text.split("/")
|
||||||
|
if len(bits) != 3 or not all(bit.isdigit() for bit in bits):
|
||||||
|
return None
|
||||||
|
a, b, c = (int(bit) for bit in bits)
|
||||||
|
if a > 31:
|
||||||
|
year, month, day = a, b, c
|
||||||
|
elif c > 31:
|
||||||
|
day, month, year = a, b, c
|
||||||
|
else:
|
||||||
|
return None
|
||||||
|
if not 1700 <= year <= 2500:
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
return date(year, month, day)
|
||||||
|
except ValueError:
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _env_file_value(key: str) -> str | None:
|
||||||
|
"""Return the value from .env, or None when the key is absent.
|
||||||
|
|
||||||
|
An empty value is returned as '' so a blank line is not ignored.
|
||||||
|
"""
|
||||||
|
if not _ENV_FILE.is_file():
|
||||||
|
return None
|
||||||
|
prefix = key + "="
|
||||||
|
for raw in _ENV_FILE.read_text(encoding="utf-8").splitlines():
|
||||||
|
line = raw.strip()
|
||||||
|
if not line or line.startswith("#") or not line.startswith(prefix):
|
||||||
|
continue
|
||||||
|
value = line[len(prefix):].strip()
|
||||||
|
if len(value) >= 2 and value[0] == value[-1] and value[0] in "\"'":
|
||||||
|
value = value[1:-1]
|
||||||
|
return value
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _setting(key: str) -> str | None:
|
||||||
|
"""Project .env wins so a refresh sees edits; otherwise the process env."""
|
||||||
|
raw = _env_file_value(key)
|
||||||
|
if raw is None:
|
||||||
|
raw = os.environ.get(key)
|
||||||
|
return raw
|
||||||
|
|
||||||
|
|
||||||
|
def orders_cutoff() -> tuple[date, tuple[int, int, int]]:
|
||||||
|
"""Gregorian cutoff from .env, plus the same day as a Jalali tuple."""
|
||||||
|
day = parse_gregorian(_setting(_SINCE_KEY) or "")
|
||||||
|
if day is None:
|
||||||
|
raise CrmOrdersError(
|
||||||
|
"Set REPORT_ORDERS_SINCE in .env to a Gregorian date, e.g. 2026-09-23."
|
||||||
|
)
|
||||||
|
return day, jalali_from_gregorian(day)
|
||||||
|
|
||||||
|
|
||||||
|
def parse_prefixes(raw: str | None) -> list[str]:
|
||||||
|
if not raw:
|
||||||
|
return []
|
||||||
|
return [part.strip() for part in raw.split(",") if part.strip()]
|
||||||
|
|
||||||
|
|
||||||
|
def code_prefixes() -> list[str]:
|
||||||
|
"""Comma-separated product-code prefixes. An empty list keeps every code."""
|
||||||
|
return parse_prefixes(_setting(_PREFIX_KEY))
|
||||||
|
|
||||||
|
|
||||||
|
def code_matches(code: str, prefixes: list[str]) -> bool:
|
||||||
|
if not prefixes:
|
||||||
|
return True
|
||||||
|
text = (code or "").strip()
|
||||||
|
return any(text.startswith(prefix) for prefix in prefixes)
|
||||||
|
|
||||||
|
|
||||||
|
def orders_after(lines, start: tuple[int, int, int]):
|
||||||
|
"""Keep lines whose delivery-note date is strictly after start."""
|
||||||
|
kept = []
|
||||||
|
for line in lines:
|
||||||
|
parsed = parse_jalali(getattr(line, "delivery_note_date", ""))
|
||||||
|
if parsed is not None and parsed > start:
|
||||||
|
kept.append(line)
|
||||||
|
kept.sort(
|
||||||
|
key=lambda line: (
|
||||||
|
parse_jalali(line.delivery_note_date),
|
||||||
|
line.delivery_note_number,
|
||||||
|
line.product_code,
|
||||||
|
),
|
||||||
|
reverse=True,
|
||||||
|
)
|
||||||
|
return kept
|
||||||
|
|
||||||
|
|
||||||
|
def recent_customer_orders(client=None) -> dict:
|
||||||
|
"""Fetch the store delivery-note report and keep rows after the cutoff."""
|
||||||
|
_day, start = orders_cutoff()
|
||||||
|
prefixes = code_prefixes()
|
||||||
|
try:
|
||||||
|
from lithium_systemgroup import (
|
||||||
|
SystemGroupClient,
|
||||||
|
SystemGroupClientError,
|
||||||
|
SystemGroupParseError,
|
||||||
|
parse_customer_orders_document,
|
||||||
|
)
|
||||||
|
except ImportError as exc:
|
||||||
|
raise CrmOrdersError("lithium-systemgroup is not installed") from exc
|
||||||
|
|
||||||
|
try:
|
||||||
|
if client is None:
|
||||||
|
client = SystemGroupClient(prefer_report_env=True, timeout=30)
|
||||||
|
body, content_type = client.fetch_customer_orders()
|
||||||
|
lines = parse_customer_orders_document(body, content_type=content_type)
|
||||||
|
except (SystemGroupClientError, SystemGroupParseError) as exc:
|
||||||
|
text = str(exc)
|
||||||
|
if text.startswith("Missing required env vars"):
|
||||||
|
text = "Set REPORT_BASE_URL, REPORT_USERNAME, and REPORT_PASSWORD."
|
||||||
|
raise CrmOrdersError(text) from exc
|
||||||
|
|
||||||
|
kept = [
|
||||||
|
line for line in orders_after(lines, start)
|
||||||
|
if code_matches(line.product_code, prefixes)
|
||||||
|
]
|
||||||
|
orders = []
|
||||||
|
for line in kept:
|
||||||
|
row = line.as_dict()
|
||||||
|
row["delivery_note_date"] = note_date_as_jalali(row["delivery_note_date"])
|
||||||
|
orders.append(row)
|
||||||
|
return {
|
||||||
|
"since": format_jalali(start),
|
||||||
|
"orders": orders,
|
||||||
|
}
|
||||||
@@ -98,3 +98,22 @@ class CalibrationIn(Schema):
|
|||||||
|
|
||||||
class CalibrationOut(CalibrationIn):
|
class CalibrationOut(CalibrationIn):
|
||||||
pass
|
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 CrmOrdersOut(Schema):
|
||||||
|
since: str
|
||||||
|
orders: List[CrmOrderOut]
|
||||||
|
|||||||
@@ -133,6 +133,21 @@ 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;
|
||||||
@@ -327,6 +342,25 @@ html[lang="fa"] body {
|
|||||||
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;
|
||||||
@@ -465,6 +499,11 @@ 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;
|
||||||
@@ -631,6 +670,26 @@ button.badge:hover {
|
|||||||
background: var(--bg-hover);
|
background: var(--bg-hover);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.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);
|
||||||
|
}
|
||||||
|
|
||||||
|
a.code-link {
|
||||||
|
color: var(--accent);
|
||||||
|
font-weight: 600;
|
||||||
|
text-decoration: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
a.code-link:hover {
|
||||||
|
text-decoration: underline;
|
||||||
|
}
|
||||||
|
|
||||||
.empty-state {
|
.empty-state {
|
||||||
text-align: center;
|
text-align: center;
|
||||||
color: var(--text-secondary);
|
color: var(--text-secondary);
|
||||||
|
|||||||
180
slips/static/slips/js/crm_orders.js
Normal file
180
slips/static/slips/js/crm_orders.js
Normal file
@@ -0,0 +1,180 @@
|
|||||||
|
const seenOrderKeys = new Set();
|
||||||
|
let ordersLoaded = false;
|
||||||
|
let lastSince = '';
|
||||||
|
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 groupedRows(rows) {
|
||||||
|
const groups = new Map();
|
||||||
|
rows.forEach((row) => {
|
||||||
|
const name = (row.customer_name || '').trim() || '—';
|
||||||
|
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 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 renderSince() {
|
||||||
|
const wrap = document.getElementById('crm-since');
|
||||||
|
const el = document.getElementById('crm-since-date');
|
||||||
|
if (!wrap || !el) return;
|
||||||
|
if (!lastSince) {
|
||||||
|
wrap.hidden = true;
|
||||||
|
el.textContent = '';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
wrap.hidden = false;
|
||||||
|
el.textContent = lastSince;
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderChrome() {
|
||||||
|
renderSince();
|
||||||
|
if (lastRows) renderOrders(lastRows, 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);
|
||||||
|
if (!rows.length) {
|
||||||
|
status.hidden = false;
|
||||||
|
status.textContent = 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);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
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 loadCrmOrders() {
|
||||||
|
const button = document.getElementById('crm-refresh');
|
||||||
|
button.disabled = true;
|
||||||
|
if (!ordersLoaded) setStatus(t('crm_loading'));
|
||||||
|
try {
|
||||||
|
const [ordersRes, productsRes] = await Promise.all([
|
||||||
|
fetch('/api/crm-orders', { cache: 'no-store' }),
|
||||||
|
fetch('/api/products'),
|
||||||
|
]);
|
||||||
|
if (productsRes.ok) {
|
||||||
|
const products = await productsRes.json().catch(() => []);
|
||||||
|
productCodes = new Set((products || []).map((p) => (p.code || '').trim()));
|
||||||
|
}
|
||||||
|
const data = await ordersRes.json().catch(() => ({}));
|
||||||
|
if (!ordersRes.ok) {
|
||||||
|
const message = data.detail || t('no_crm_orders');
|
||||||
|
if (!ordersLoaded) setStatus(message);
|
||||||
|
showToast(message, true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
lastSince = data.since || '';
|
||||||
|
lastRows = data.orders || [];
|
||||||
|
renderSince();
|
||||||
|
const added = renderOrders(lastRows, ordersLoaded);
|
||||||
|
ordersLoaded = true;
|
||||||
|
if (added > 0) showToast(t('crm_new'));
|
||||||
|
} catch (err) {
|
||||||
|
setStatus(t('no_crm_orders'));
|
||||||
|
showToast('Network error', true);
|
||||||
|
} finally {
|
||||||
|
button.disabled = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
document.addEventListener('DOMContentLoaded', () => {
|
||||||
|
document.getElementById('crm-refresh').addEventListener('click', loadCrmOrders);
|
||||||
|
loadCrmOrders();
|
||||||
|
});
|
||||||
|
|
||||||
|
document.addEventListener('slip-language', renderChrome);
|
||||||
@@ -146,6 +146,24 @@ document.addEventListener('DOMContentLoaded', () => {
|
|||||||
});
|
});
|
||||||
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();
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ const translations = {
|
|||||||
'en': {
|
'en': {
|
||||||
'app_title': 'Label Printer',
|
'app_title': 'Label Printer',
|
||||||
'data_entry': 'Data Entry',
|
'data_entry': 'Data Entry',
|
||||||
|
'crm_orders': 'Orders',
|
||||||
'products': 'Products',
|
'products': 'Products',
|
||||||
'print_queue': 'Print Queue',
|
'print_queue': 'Print Queue',
|
||||||
'calibrate': 'Calibrate',
|
'calibrate': 'Calibrate',
|
||||||
@@ -47,6 +48,18 @@ const translations = {
|
|||||||
'status_cancelled': 'Cancelled',
|
'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',
|
||||||
|
'delivery_note': 'Note #',
|
||||||
|
'note_qty': 'Ordered',
|
||||||
|
'delivered_qty': 'Delivered',
|
||||||
|
'remaining_qty': 'Remaining',
|
||||||
|
'product_title': 'Title',
|
||||||
|
'crm_loading': 'Loading orders…',
|
||||||
|
'no_crm_orders': 'No orders after this date',
|
||||||
|
'orders_after': 'Orders after',
|
||||||
|
'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.',
|
||||||
@@ -61,6 +74,7 @@ const translations = {
|
|||||||
'fa': {
|
'fa': {
|
||||||
'app_title': 'پرینتر لیبل',
|
'app_title': 'پرینتر لیبل',
|
||||||
'data_entry': 'ثبت اطلاعات',
|
'data_entry': 'ثبت اطلاعات',
|
||||||
|
'crm_orders': 'حوالهها',
|
||||||
'products': 'محصولات',
|
'products': 'محصولات',
|
||||||
'print_queue': 'صف چاپ',
|
'print_queue': 'صف چاپ',
|
||||||
'calibrate': 'کالیبراسیون',
|
'calibrate': 'کالیبراسیون',
|
||||||
@@ -106,6 +120,18 @@ const translations = {
|
|||||||
'status_cancelled': 'لغو شده',
|
'status_cancelled': 'لغو شده',
|
||||||
'add_to_queue': 'افزودن به صف چاپ',
|
'add_to_queue': 'افزودن به صف چاپ',
|
||||||
'recent_orders': 'سفارشات اخیر',
|
'recent_orders': 'سفارشات اخیر',
|
||||||
|
'crm_orders_title': 'حوالهها',
|
||||||
|
'refresh': 'بهروزرسانی',
|
||||||
|
'customer': 'مشتری',
|
||||||
|
'delivery_note': 'شماره حواله',
|
||||||
|
'note_qty': 'مقدار حواله',
|
||||||
|
'delivered_qty': 'تحویلشده',
|
||||||
|
'remaining_qty': 'مانده',
|
||||||
|
'product_title': 'عنوان',
|
||||||
|
'crm_loading': 'در حال دریافت سفارشها…',
|
||||||
|
'no_crm_orders': 'سفارشی بعد از این تاریخ نیست',
|
||||||
|
'orders_after': 'حوالههای بعد از',
|
||||||
|
'crm_new': 'سفارش جدید اضافه شد',
|
||||||
'status': 'وضعیت',
|
'status': 'وضعیت',
|
||||||
'no_orders': 'سفارشی ثبت نشده',
|
'no_orders': 'سفارشی ثبت نشده',
|
||||||
'no_pending_orders': 'سفارشی در انتظار چاپ نیست.',
|
'no_pending_orders': 'سفارشی در انتظار چاپ نیست.',
|
||||||
@@ -173,6 +199,7 @@ function applyLanguage(lang) {
|
|||||||
if (typeof window.updateLabelsPreview === 'function') {
|
if (typeof window.updateLabelsPreview === 'function') {
|
||||||
window.updateLabelsPreview();
|
window.updateLabelsPreview();
|
||||||
}
|
}
|
||||||
|
document.dispatchEvent(new Event('slip-language'));
|
||||||
}
|
}
|
||||||
|
|
||||||
function toggleLanguage() {
|
function toggleLanguage() {
|
||||||
|
|||||||
@@ -31,6 +31,7 @@
|
|||||||
</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">ثبت اطلاعات</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">صف چاپ</a>
|
<a href="{% url 'print_queue' %}" class="nav-link {% block nav_print_active %}{% endblock %}" data-i18n="print_queue">صف چاپ</a>
|
||||||
</div>
|
</div>
|
||||||
<div class="nav-actions">
|
<div class="nav-actions">
|
||||||
@@ -55,7 +56,7 @@
|
|||||||
{% block content %}{% endblock %}
|
{% block content %}{% endblock %}
|
||||||
</main>
|
</main>
|
||||||
|
|
||||||
<script src="{% static 'slips/js/i18n.js' %}"></script>
|
<script src="{% static 'slips/js/i18n.js' %}?v=3"></script>
|
||||||
{% block extra_scripts %}{% endblock %}
|
{% block extra_scripts %}{% endblock %}
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
46
slips/templates/slips/crm_orders.html
Normal file
46
slips/templates/slips/crm_orders.html
Normal file
@@ -0,0 +1,46 @@
|
|||||||
|
{% 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>
|
||||||
|
<p class="card-subtitle" id="crm-since" hidden>
|
||||||
|
<span data-i18n="orders_after">حوالههای بعد از</span>
|
||||||
|
<span id="crm-since-date" class="mono" dir="ltr"></span>
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<div class="card-actions">
|
||||||
|
<button type="button" class="btn btn-ghost btn-sm" id="crm-refresh" data-i18n="refresh">بهروزرسانی</button>
|
||||||
|
<span class="card-badge badge-muted" id="crm-count">0</span>
|
||||||
|
</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_scripts %}
|
||||||
|
<script src="{% static 'slips/js/crm_orders.js' %}?v=6"></script>
|
||||||
|
{% endblock %}
|
||||||
@@ -18,7 +18,7 @@
|
|||||||
<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-weight="{{ p.default_net_weight }}" data-requires-dates="{{ p.requires_dates|yesno:'true,false' }}">
|
<option value="{{ p.id }}" data-code="{{ p.code }}" data-weight="{{ p.default_net_weight }}" data-requires-dates="{{ p.requires_dates|yesno:'true,false' }}">
|
||||||
{{ p.code }} — {{ p.description }}
|
{{ p.code }} — {{ p.description }}
|
||||||
</option>
|
</option>
|
||||||
{% endfor %}
|
{% endfor %}
|
||||||
@@ -169,5 +169,5 @@
|
|||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|
||||||
{% block extra_scripts %}
|
{% block extra_scripts %}
|
||||||
<script src="{% static 'slips/js/entry.js' %}"></script>
|
<script src="{% static 'slips/js/entry.js' %}?v=4"></script>
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|||||||
58
slips/tests.py
Normal file
58
slips/tests.py
Normal file
@@ -0,0 +1,58 @@
|
|||||||
|
import unittest
|
||||||
|
from datetime import date
|
||||||
|
from types import SimpleNamespace
|
||||||
|
|
||||||
|
from slips.crm_orders import (
|
||||||
|
code_matches,
|
||||||
|
format_jalali,
|
||||||
|
jalali_from_gregorian,
|
||||||
|
note_date_as_jalali,
|
||||||
|
orders_after,
|
||||||
|
parse_gregorian,
|
||||||
|
parse_jalali,
|
||||||
|
parse_prefixes,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
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(""), [])
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -24,6 +24,10 @@ def products(request):
|
|||||||
})
|
})
|
||||||
|
|
||||||
|
|
||||||
|
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]
|
||||||
|
|||||||
Reference in New Issue
Block a user