From b8c4e703fbddc46ab1c347f40e1856835894e7b9 Mon Sep 17 00:00:00 2001 From: diaco Date: Wed, 11 Nov 2026 14:53:44 +0330 Subject: [PATCH] Sign in to SystemGroup per user on the orders page Co-authored-by: Cursor --- .env.example | 8 +- docker-compose.yml | 4 - slips/api.py | 86 +++++++++++++++- slips/crm_orders.py | 40 +++++++- slips/schemas.py | 6 ++ slips/static/slips/css/style.css | 9 ++ slips/static/slips/js/crm_orders.js | 136 ++++++++++++++++++++++---- slips/static/slips/js/i18n.js | 14 +++ slips/templates/slips/base.html | 4 +- slips/templates/slips/crm_orders.html | 19 +++- slips/tests.py | 124 ++++++++++++++++++++++- 11 files changed, 408 insertions(+), 42 deletions(-) diff --git a/.env.example b/.env.example index aaddb0c..0d2ae26 100644 --- a/.env.example +++ b/.env.example @@ -9,9 +9,9 @@ HTTP_PORT=80 # 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/ -# 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. @@ -20,7 +20,5 @@ HTTP_PORT=80 # Comma-separated product-code prefixes. A note is listed only when its code starts with one of these. # 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. +# Optional CRM host. Used only when REPORT_BASE_URL is unset. # CRM_BASE_URL= -# CRM_USERNAME= -# CRM_PASSWORD= diff --git a/docker-compose.yml b/docker-compose.yml index 9713d33..9aa7375 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -14,14 +14,10 @@ services: - DJANGO_DEBUG=0 - 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: - web diff --git a/slips/api.py b/slips/api.py index ac89963..c9db44e 100644 --- a/slips/api.py +++ b/slips/api.py @@ -4,11 +4,16 @@ from django.shortcuts import get_object_or_404 from django.utils import timezone from ninja import NinjaAPI, Query -from .crm_orders import CrmOrdersError, recent_customer_orders +from .crm_orders import ( + SESSION_TTL_SECONDS, + CrmAuthError, + CrmOrdersError, + recent_customer_orders, +) from .models import Product, Order, clean_custom_labels from .schemas import ( ProductOut, ProductIn, OrderOut, OrderIn, OrderUpdateIn, - CalibrationIn, CalibrationOut, CrmOrdersOut, + CalibrationIn, CalibrationOut, CrmLoginIn, CrmOrdersOut, ) from .calibration import load_calibration, save_calibration, DEFAULTS, for_api @@ -155,13 +160,84 @@ def delete_order(request, order_id: int): return 204, None -@api.get('/crm-orders', response={200: CrmOrdersOut, 502: dict}, tags=['Orders']) +_SG_USER = 'sg_username' +_SG_PASS = 'sg_password' + + +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 _remember_credentials(request, username, password): + request.session[_SG_USER] = username + request.session[_SG_PASS] = password + request.session.set_expiry(SESSION_TTL_SECONDS) + + +def _forget_credentials(request): + request.session.pop(_SG_USER, None) + request.session.pop(_SG_PASS, None) + + +def _customer_orders(username, password): + data = recent_customer_orders(username, password) + data['username'] = username + return data + + +@api.get('/crm-orders', response={200: CrmOrdersOut, 401: dict, 502: dict}, tags=['Orders']) def list_crm_orders(request): - """Store delivery notes dated after REPORT_ORDERS_SINCE.""" + """Store delivery notes for the SystemGroup account saved in this session.""" + creds = _session_credentials(request) + if creds is None: + return 401, {'detail': 'Sign in to SystemGroup.', 'code': 'login_required'} + username, password = creds try: - return recent_customer_orders() + data = _customer_orders(username, password) + 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) + 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 = _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) + return data + + +@api.delete('/crm-orders/session', response={204: None}, tags=['Orders']) +def end_crm_session(request): + _forget_credentials(request) + return 204, None # ─── Calibration ───────────────────────────────────────── diff --git a/slips/crm_orders.py b/slips/crm_orders.py index fc7760d..e8b90ea 100644 --- a/slips/crm_orders.py +++ b/slips/crm_orders.py @@ -2,6 +2,8 @@ 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 @@ -18,6 +20,31 @@ 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("/") @@ -164,7 +191,7 @@ def orders_after(lines, start: tuple[int, int, int]): return kept -def recent_customer_orders(client=None) -> dict: +def recent_customer_orders(username: str, password: str, client=None) -> dict: """Fetch the store delivery-note report and keep rows after the cutoff.""" _day, start = orders_cutoff() prefixes = code_prefixes() @@ -180,13 +207,20 @@ def recent_customer_orders(client=None) -> dict: try: if client is None: - client = SystemGroupClient(prefer_report_env=True, timeout=30) + client = SystemGroupClient( + base_url=report_base_url(), + username=username, + password=password, + 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 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, REPORT_USERNAME, and REPORT_PASSWORD." + text = "Set REPORT_BASE_URL." raise CrmOrdersError(text) from exc kept = [ diff --git a/slips/schemas.py b/slips/schemas.py index c8257aa..b626fd1 100644 --- a/slips/schemas.py +++ b/slips/schemas.py @@ -114,6 +114,12 @@ class CrmOrderOut(Schema): notes: str +class CrmLoginIn(Schema): + username: str + password: str + + class CrmOrdersOut(Schema): since: str + username: str orders: List[CrmOrderOut] diff --git a/slips/static/slips/css/style.css b/slips/static/slips/css/style.css index 4e7415a..8701ec5 100644 --- a/slips/static/slips/css/style.css +++ b/slips/static/slips/css/style.css @@ -401,6 +401,15 @@ form { padding-right: 0; } +#crm-login { + max-width: 22rem; +} + +/* .form-stack { display: flex } would otherwise override the hidden attribute. */ +#crm-login[hidden] { + display: none !important; +} + #add-custom-line { align-self: flex-start; } diff --git a/slips/static/slips/js/crm_orders.js b/slips/static/slips/js/crm_orders.js index 4e15a7b..8e68231 100644 --- a/slips/static/slips/js/crm_orders.js +++ b/slips/static/slips/js/crm_orders.js @@ -1,6 +1,7 @@ const seenOrderKeys = new Set(); let ordersLoaded = false; let lastSince = ''; +let lastUsername = ''; let lastRows = null; let productCodes = new Set(); @@ -72,7 +73,35 @@ function renderSince() { el.textContent = 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; +} + +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(); renderSince(); if (lastRows) renderOrders(lastRows, false); } @@ -138,32 +167,51 @@ function setStatus(message) { 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 = ''; + renderSince(); + 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(); + renderSince(); + const added = renderOrders(lastRows, 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, productsRes] = await Promise.all([ + const [ordersRes] = await Promise.all([ fetch('/api/crm-orders', { cache: 'no-store' }), - fetch('/api/products'), + fetchProducts(), ]); - 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')); + await applyOrdersResponse(ordersRes); } catch (err) { setStatus(t('no_crm_orders')); showToast('Network error', true); @@ -172,8 +220,58 @@ async function loadCrmOrders() { } } +async function signIn(event) { + event.preventDefault(); + const button = document.getElementById('crm-sign-in'); + button.disabled = true; + setStatus(t('crm_loading')); + try { + const [ordersRes] = await Promise.all([ + fetch('/api/crm-orders/session', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + cache: 'no-store', + body: JSON.stringify({ + username: document.getElementById('crm-username').value.trim(), + password: document.getElementById('crm-password').value, + }), + }), + fetchProducts(), + ]); + await applyOrdersResponse(ordersRes); + } catch (err) { + setStatus(t('sg_need_login')); + showToast('Network error', true); + } finally { + button.disabled = false; + } +} + +async function signOut() { + const button = document.getElementById('crm-forget'); + button.disabled = true; + try { + const res = await fetch('/api/crm-orders/session', { method: 'DELETE' }); + if (!res.ok) { + showToast('Network error', true); + return; + } + seenOrderKeys.clear(); + lastSince = ''; + renderSince(); + showLogin(); + setStatus(t('sg_need_login')); + } catch (err) { + showToast('Network error', true); + } finally { + button.disabled = false; + } +} + document.addEventListener('DOMContentLoaded', () => { document.getElementById('crm-refresh').addEventListener('click', loadCrmOrders); + document.getElementById('crm-forget').addEventListener('click', signOut); + loginForm().addEventListener('submit', signIn); loadCrmOrders(); }); diff --git a/slips/static/slips/js/i18n.js b/slips/static/slips/js/i18n.js index ce24b91..ae4b397 100644 --- a/slips/static/slips/js/i18n.js +++ b/slips/static/slips/js/i18n.js @@ -57,6 +57,13 @@ const translations = { 'remaining_qty': 'Remaining', 'product_title': 'Title', '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', 'orders_after': 'Orders after', 'crm_new': 'New orders added', @@ -129,6 +136,13 @@ const translations = { 'remaining_qty': 'مانده', 'product_title': 'عنوان', 'crm_loading': 'در حال دریافت سفارش‌ها…', + 'sg_username': 'نام کاربری', + 'sg_password': 'رمز عبور', + 'sg_sign_in': 'ورود', + 'sg_sign_out': 'خروج', + 'sg_signed_in': 'کاربر', + 'sg_need_login': 'برای دیدن حواله‌ها وارد شوید.', + 'sg_rejected': 'نام کاربری یا رمز سامانه گروه نادرست است.', 'no_crm_orders': 'سفارشی بعد از این تاریخ نیست', 'orders_after': 'حواله‌های بعد از', 'crm_new': 'سفارش جدید اضافه شد', diff --git a/slips/templates/slips/base.html b/slips/templates/slips/base.html index de1b608..3180779 100644 --- a/slips/templates/slips/base.html +++ b/slips/templates/slips/base.html @@ -10,7 +10,7 @@ - + + {% block extra_scripts %}{% endblock %} diff --git a/slips/templates/slips/crm_orders.html b/slips/templates/slips/crm_orders.html index bd57a05..8de8c42 100644 --- a/slips/templates/slips/crm_orders.html +++ b/slips/templates/slips/crm_orders.html @@ -16,10 +16,23 @@

- - 0 + + + +
+
@@ -42,5 +55,5 @@ {% endblock %} {% block extra_scripts %} - + {% endblock %} diff --git a/slips/tests.py b/slips/tests.py index 59bd58c..d867d85 100644 --- a/slips/tests.py +++ b/slips/tests.py @@ -1,16 +1,26 @@ import unittest -from datetime import date +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, code_matches, 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, ) @@ -54,5 +64,117 @@ class OrdersAfterTests(unittest.TestCase): 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") + + +class CrmSessionTests(TestCase): + def test_session_lasts_thirty_days_and_slides(self): + from slips import api + + def fake(username, password, client=None): + return {"since": "1405/01/01", "orders": []} + + 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.assertEqual(self.client.session["sg_username"], "ada") + self.assertEqual(self.client.session["sg_password"], "secret") + 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.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) + 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): + 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()