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 CrmOrdersError, recent_customer_orders from .models import Product, Order, clean_custom_labels from .schemas import ( ProductOut, ProductIn, OrderOut, OrderIn, OrderUpdateIn, CalibrationIn, CalibrationOut, 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 @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 ───────────────────────────────────────── @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))