Sign in to SystemGroup per user on the orders page #43
@@ -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=
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
86
slips/api.py
86
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 ─────────────────────────────────────────
|
||||
|
||||
@@ -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 = [
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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();
|
||||
});
|
||||
|
||||
|
||||
@@ -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': 'سفارش جدید اضافه شد',
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com">
|
||||
<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 rel="stylesheet" href="{% static 'slips/css/style.css' %}">
|
||||
<link rel="stylesheet" href="{% static 'slips/css/style.css' %}?v=2">
|
||||
<script>
|
||||
(function () {
|
||||
var t = localStorage.getItem('slip_theme') || 'light';
|
||||
@@ -56,7 +56,7 @@
|
||||
{% block content %}{% endblock %}
|
||||
</main>
|
||||
|
||||
<script src="{% static 'slips/js/i18n.js' %}?v=3"></script>
|
||||
<script src="{% static 'slips/js/i18n.js' %}?v=4"></script>
|
||||
{% block extra_scripts %}{% endblock %}
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -16,10 +16,23 @@
|
||||
</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>
|
||||
<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>
|
||||
<p class="empty-state" id="crm-orders-status" hidden></p>
|
||||
<div class="table-wrap">
|
||||
<table class="data-table" id="crm-orders-table">
|
||||
@@ -42,5 +55,5 @@
|
||||
{% endblock %}
|
||||
|
||||
{% block extra_scripts %}
|
||||
<script src="{% static 'slips/js/crm_orders.js' %}?v=6"></script>
|
||||
<script src="{% static 'slips/js/crm_orders.js' %}?v=7"></script>
|
||||
{% endblock %}
|
||||
|
||||
124
slips/tests.py
124
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()
|
||||
|
||||
Reference in New Issue
Block a user