262 lines
9.2 KiB
Python
262 lines
9.2 KiB
Python
from typing import List, Optional
|
|
from django.db import IntegrityError
|
|
from django.shortcuts import get_object_or_404
|
|
from django.utils import timezone
|
|
from ninja import NinjaAPI, Query
|
|
|
|
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, 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')
|
|
|
|
|
|
# ─── Products ────────────────────────────────────────────
|
|
|
|
@api.get('/products', response=List[ProductOut], tags=['Products'])
|
|
def list_products(request):
|
|
return Product.objects.all()
|
|
|
|
|
|
@api.post('/products', response={201: ProductOut, 400: dict}, tags=['Products'])
|
|
def create_product(request, payload: ProductIn):
|
|
try:
|
|
product = Product.objects.create(**payload.dict())
|
|
except IntegrityError:
|
|
return 400, {'detail': 'Product code already exists'}
|
|
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 ──────────────────────────────────────────────
|
|
|
|
@api.get('/orders', response=List[OrderOut], tags=['Orders'])
|
|
def list_orders(request, status: Optional[str] = Query(None)):
|
|
qs = Order.objects.select_related('product').all()
|
|
if status:
|
|
qs = qs.filter(status=status)
|
|
return qs
|
|
|
|
|
|
@api.post('/orders', response={201: OrderOut, 400: dict}, tags=['Orders'])
|
|
def create_order(request, payload: OrderIn):
|
|
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(
|
|
product=product,
|
|
batch_number=payload.batch_number,
|
|
production_date=production_date,
|
|
next_control_date=next_control_date,
|
|
total_weight=payload.total_weight,
|
|
canister_weight=payload.canister_weight,
|
|
canisters_per_box=payload.canisters_per_box,
|
|
custom_labels=custom_labels,
|
|
)
|
|
order.apply_weight()
|
|
order.save()
|
|
return 201, order
|
|
|
|
|
|
@api.patch('/orders/{order_id}', response={200: OrderOut, 400: dict}, tags=['Orders'])
|
|
def update_order(request, order_id: int, payload: OrderUpdateIn):
|
|
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
|
|
if payload.status == 'done':
|
|
order.printed_at = timezone.now()
|
|
elif payload.status == 'pending':
|
|
order.printed_at = None
|
|
|
|
order.save()
|
|
return order
|
|
|
|
|
|
@api.delete('/orders/{order_id}', response={204: None}, tags=['Orders'])
|
|
def delete_order(request, order_id: int):
|
|
order = get_object_or_404(Order, id=order_id)
|
|
order.delete()
|
|
return 204, None
|
|
|
|
|
|
_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 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 = _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 ─────────────────────────────────────────
|
|
|
|
@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))
|