83 lines
3.3 KiB
Python
83 lines
3.3 KiB
Python
from __future__ import annotations
|
|
|
|
import json
|
|
|
|
from django.http import JsonResponse
|
|
from django.views.decorators.http import require_GET, require_POST
|
|
|
|
from shop.services import OrderService, ProductService
|
|
|
|
|
|
@require_GET
|
|
async def product_search_view(request):
|
|
keyword = request.GET.get("q", "").strip()
|
|
page = int(request.GET.get("page", 1))
|
|
page_size = int(request.GET.get("page_size", 50))
|
|
if not keyword:
|
|
return JsonResponse({"error": "搜索关键字不能为空"}, status=400)
|
|
if page <= 0 or page_size <= 0:
|
|
return JsonResponse({"error": "页码和每页大小必须大于0"}, status=400)
|
|
try:
|
|
products = await ProductService.search_products(keyword, page=page, page_size=page_size)
|
|
products_data = [
|
|
{
|
|
"id": p.id,
|
|
"name": p.name,
|
|
"description": p.description,
|
|
"price": str(p.price),
|
|
"stock": p.stock,
|
|
"keywords": p.keywords,
|
|
}
|
|
for p in products
|
|
]
|
|
return JsonResponse({"products": products_data})
|
|
except Exception as e:
|
|
return JsonResponse({"error": "系统异常", "detail": str(e)}, status=500)
|
|
|
|
|
|
@require_POST
|
|
async def batch_order_view(request):
|
|
try:
|
|
data = json.loads(request.body)
|
|
order_items = data.get("items", [])
|
|
if not order_items:
|
|
return JsonResponse({"error": "订单明细不能为空"}, status=400)
|
|
order_id, results = await OrderService.batch_create_order(order_items)
|
|
return JsonResponse({"order_id": order_id, "results": results})
|
|
except Exception as e:
|
|
return JsonResponse({"error": "系统异常", "detail": str(e)}, status=500)
|
|
|
|
|
|
@require_POST
|
|
async def create_product_view(request):
|
|
try:
|
|
data = json.loads(request.body)
|
|
product_data = data.get("data", {})
|
|
required_fields = ["name", "price", "stock"]
|
|
for field in required_fields:
|
|
if not product_data.get(field):
|
|
return JsonResponse({"error": f"字段 {field} 不能为空"}, status=400)
|
|
# 字段类型校验
|
|
if not isinstance(product_data["name"], str) or not product_data["name"].strip():
|
|
return JsonResponse({"error": "商品名称必须为非空字符串"}, status=400)
|
|
try:
|
|
from decimal import Decimal
|
|
|
|
price = Decimal(str(product_data["price"]))
|
|
if price <= 0:
|
|
return JsonResponse({"error": "商品价格必须为正数"}, status=400)
|
|
except Exception:
|
|
return JsonResponse({"error": "商品价格格式不正确"}, status=400)
|
|
try:
|
|
stock = int(product_data["stock"])
|
|
if stock < 0:
|
|
return JsonResponse({"error": "库存不能为负数"}, status=400)
|
|
except Exception:
|
|
return JsonResponse({"error": "库存格式不正确"}, status=400)
|
|
if "keywords" in product_data and not isinstance(product_data["keywords"], str):
|
|
return JsonResponse({"error": "关键词必须为字符串"}, status=400)
|
|
result = await ProductService.create_product(**product_data)
|
|
return JsonResponse({"result": result})
|
|
except Exception as e:
|
|
return JsonResponse({"error": "系统异常", "detail": str(e)}, status=500)
|