Add Products tab with edit, remove, and backup

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
2026-10-07 09:02:04 +03:30
parent 1c63af0a58
commit 2e08cfa0df
10 changed files with 323 additions and 73 deletions

View File

@@ -1,4 +1,5 @@
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
@@ -20,12 +21,56 @@ def list_products(request):
return Product.objects.all()
@api.post('/products', response={201: ProductOut}, tags=['Products'])
@api.post('/products', response={201: ProductOut, 400: dict}, tags=['Products'])
def create_product(request, payload: ProductIn):
product = Product.objects.create(**payload.dict())
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,
},
)
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'])