Files
product-slip/slips/api.py
2026-10-14 12:06:12 +03:30

160 lines
5.9 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 .models import Product, Order
from .schemas import (
ProductOut, ProductIn, OrderOut, OrderIn, OrderUpdateIn,
CalibrationIn, CalibrationOut,
)
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
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,
)
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)
if payload.canister_count is not None or payload.box_count is not None:
if order.status != 'pending':
return 400, {'detail': 'Only pending orders can change label counts'}
if payload.canister_count is not None and payload.canister_count < 1:
return 400, {'detail': 'canister_count must be >= 1'}
if payload.box_count is not None and payload.box_count < 1:
return 400, {'detail': 'box_count must be >= 1'}
order.set_counts(payload.canister_count, payload.box_count)
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
# ─── 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))