forked from erp-dev/erp
feat: app verion && some field modify (printing & shipment)
This commit is contained in:
@@ -8,6 +8,7 @@ from rest_framework.mixins import ListModelMixin, RetrieveModelMixin
|
||||
from rest_framework.permissions import IsAuthenticated
|
||||
from rest_framework.response import Response
|
||||
from rest_framework.views import APIView
|
||||
from django.utils.dateparse import parse_date, parse_datetime
|
||||
|
||||
from flower.viewsets import LimitedLimitOffsetPagination
|
||||
from shipment.models import Shipment, ShipmentDelivery
|
||||
@@ -19,6 +20,7 @@ from .serializers import (
|
||||
SalesItemUpdateSerializer,
|
||||
ShipmentStatusUpdateSerializer,
|
||||
ShipmentDeliveryBindShipmentsSerializer,
|
||||
ShipmentDeliveryByPrintingOrderSerializer,
|
||||
ShipmentDeliveryCreateSerializer,
|
||||
ShipmentDeliverySerializer,
|
||||
ShipmentDeliveryStatusUpdateSerializer,
|
||||
@@ -210,11 +212,15 @@ class ShipmentListCreateView(ListModelMixin, GenericAPIView):
|
||||
shipment_date=data["shipment_date"],
|
||||
sales_item_ids=data["sales_items"],
|
||||
created_by=request.user,
|
||||
address_id=data.get("address_id"),
|
||||
address=data.get("address", ""),
|
||||
contact_name=data.get("contact_name", ""),
|
||||
contact_phone=data.get("contact_phone", ""),
|
||||
remark=data.get("remark", ""),
|
||||
area=data.get("area", ""),
|
||||
coordinates=data.get("coordinates"),
|
||||
extra=data.get("extra"),
|
||||
status=data.get("status"),
|
||||
)
|
||||
except ValueError as e:
|
||||
return Response({"detail": str(e)}, status=status.HTTP_400_BAD_REQUEST)
|
||||
@@ -274,7 +280,7 @@ class ShipmentDetailView(RetrieveModelMixin, GenericAPIView):
|
||||
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
|
||||
data = serializer.validated_data
|
||||
|
||||
from shipment.services import update_shipment
|
||||
from shipment.services import UNSET, update_shipment
|
||||
|
||||
try:
|
||||
shipment = update_shipment(
|
||||
@@ -285,8 +291,10 @@ class ShipmentDetailView(RetrieveModelMixin, GenericAPIView):
|
||||
contact_name=data.get("contact_name"),
|
||||
contact_phone=data.get("contact_phone"),
|
||||
area=data.get("area"),
|
||||
coordinates=data["coordinates"] if "coordinates" in data else UNSET,
|
||||
remark=data.get("remark"),
|
||||
external_id=data.get("external_id"),
|
||||
extra=data["extra"] if "extra" in data else UNSET,
|
||||
)
|
||||
except ValueError as e:
|
||||
return Response({"detail": str(e)}, status=status.HTTP_400_BAD_REQUEST)
|
||||
@@ -444,6 +452,172 @@ class ShipmentDeliveryListCreateView(ListModelMixin, GenericAPIView):
|
||||
)
|
||||
|
||||
|
||||
class ShipmentDeliveryByPrintingOrderView(GenericAPIView):
|
||||
"""
|
||||
按生产订单查询相关送货单。
|
||||
|
||||
GET /api/v1/shipment/deliveries/by-printing-order/<printing_order_id>/
|
||||
"""
|
||||
|
||||
permission_classes = [IsAuthenticated]
|
||||
serializer_class = ShipmentDeliveryByPrintingOrderSerializer
|
||||
pagination_class = LimitedLimitOffsetPagination
|
||||
|
||||
ordering_fields = {
|
||||
"id",
|
||||
"created_at",
|
||||
"updated_at",
|
||||
"started_at",
|
||||
"delivered_at",
|
||||
"cancelled_at",
|
||||
"status",
|
||||
}
|
||||
|
||||
def _get_merchant_limited_printing_orders(self):
|
||||
from printing.models import PrintingOrder
|
||||
|
||||
queryset = PrintingOrder.objects.all()
|
||||
user = self.request.user
|
||||
if getattr(user, "is_superuser", False):
|
||||
return queryset
|
||||
|
||||
emp = getattr(user, "employee", None)
|
||||
merchant = getattr(emp, "merchant", None) if emp else None
|
||||
if not merchant:
|
||||
return queryset.none()
|
||||
return queryset.filter(merchant=merchant)
|
||||
|
||||
def _resolve_printing_order(self, printing_order_id: str):
|
||||
raw_value = str(printing_order_id).strip()
|
||||
base_queryset = self._get_merchant_limited_printing_orders()
|
||||
|
||||
if raw_value.isdigit():
|
||||
printing_order = base_queryset.filter(id=int(raw_value)).first()
|
||||
if printing_order is not None:
|
||||
return printing_order, None
|
||||
|
||||
matched_orders = list(
|
||||
base_queryset.filter(external_order_id=raw_value).only("id", "merchant_id")[:2]
|
||||
)
|
||||
if len(matched_orders) > 1:
|
||||
return None, Response(
|
||||
{
|
||||
"message": (
|
||||
f"external_order_id {raw_value} 匹配到多个生产订单,"
|
||||
"请改用内部ID查询"
|
||||
)
|
||||
},
|
||||
status=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
)
|
||||
if len(matched_orders) == 1:
|
||||
return matched_orders[0], None
|
||||
return None, Response(
|
||||
{"detail": f"生产订单 {printing_order_id} 不存在"},
|
||||
status=status.HTTP_404_NOT_FOUND,
|
||||
)
|
||||
|
||||
def _apply_datetime_range(self, queryset, field_name: str, from_param: str, to_param: str):
|
||||
start_value = (self.request.query_params.get(from_param) or "").strip()
|
||||
if start_value:
|
||||
if "T" in start_value or ":" in start_value:
|
||||
parsed = parse_datetime(start_value)
|
||||
if parsed is not None:
|
||||
queryset = queryset.filter(**{f"{field_name}__gte": parsed})
|
||||
else:
|
||||
parsed = parse_date(start_value)
|
||||
if parsed is not None:
|
||||
queryset = queryset.filter(**{f"{field_name}__date__gte": parsed})
|
||||
|
||||
end_value = (self.request.query_params.get(to_param) or "").strip()
|
||||
if end_value:
|
||||
if "T" in end_value or ":" in end_value:
|
||||
parsed = parse_datetime(end_value)
|
||||
if parsed is not None:
|
||||
queryset = queryset.filter(**{f"{field_name}__lte": parsed})
|
||||
else:
|
||||
parsed = parse_date(end_value)
|
||||
if parsed is not None:
|
||||
queryset = queryset.filter(**{f"{field_name}__date__lte": parsed})
|
||||
return queryset
|
||||
|
||||
def _apply_filters(self, queryset):
|
||||
status_val = self.request.query_params.get("status")
|
||||
if status_val:
|
||||
queryset = queryset.filter(status=status_val)
|
||||
|
||||
for field_name in [
|
||||
"driver_name",
|
||||
"vehicle_trip",
|
||||
"contact_phone",
|
||||
"vehicle_capacity",
|
||||
"remark",
|
||||
"internal_remark",
|
||||
]:
|
||||
value = (self.request.query_params.get(field_name) or "").strip()
|
||||
if value:
|
||||
queryset = queryset.filter(**{f"{field_name}__icontains": value})
|
||||
|
||||
queryset = self._apply_datetime_range(
|
||||
queryset, "started_at", "started_at_from", "started_at_to"
|
||||
)
|
||||
queryset = self._apply_datetime_range(
|
||||
queryset, "delivered_at", "delivered_at_from", "delivered_at_to"
|
||||
)
|
||||
queryset = self._apply_datetime_range(
|
||||
queryset, "cancelled_at", "cancelled_at_from", "cancelled_at_to"
|
||||
)
|
||||
queryset = self._apply_datetime_range(
|
||||
queryset, "created_at", "created_at_from", "created_at_to"
|
||||
)
|
||||
|
||||
shipment_date_from = (self.request.query_params.get("shipment_date_from") or "").strip()
|
||||
if shipment_date_from:
|
||||
queryset = queryset.filter(shipments__shipment_date__gte=shipment_date_from)
|
||||
shipment_date_to = (self.request.query_params.get("shipment_date_to") or "").strip()
|
||||
if shipment_date_to:
|
||||
queryset = queryset.filter(shipments__shipment_date__lte=shipment_date_to)
|
||||
|
||||
ordering = (self.request.query_params.get("ordering") or "").strip()
|
||||
if ordering:
|
||||
normalized = ordering[1:] if ordering.startswith("-") else ordering
|
||||
if normalized in self.ordering_fields:
|
||||
return queryset.order_by(ordering, "-id").distinct()
|
||||
|
||||
return queryset.order_by("-created_at", "-id").distinct()
|
||||
|
||||
def get(self, request, printing_order_id: str):
|
||||
printing_order, error_response = self._resolve_printing_order(printing_order_id)
|
||||
if error_response is not None:
|
||||
return error_response
|
||||
|
||||
from printing.models import PrintingJob
|
||||
|
||||
printing_job_ids = list(
|
||||
PrintingJob.objects.filter(printing_order=printing_order).values_list(
|
||||
"id", flat=True
|
||||
)
|
||||
)
|
||||
if not printing_job_ids:
|
||||
queryset = ShipmentDelivery.objects.none()
|
||||
else:
|
||||
queryset = (
|
||||
ShipmentDelivery.objects.filter(
|
||||
merchant=printing_order.merchant,
|
||||
shipments__items__printing_job_id__in=printing_job_ids,
|
||||
shipments__items__delete_at__isnull=True,
|
||||
)
|
||||
.select_related("merchant", "created_by", "operator", "cancelled_by")
|
||||
.prefetch_related("shipments", "shipments__customer")
|
||||
)
|
||||
queryset = self._apply_filters(queryset)
|
||||
|
||||
page = self.paginate_queryset(queryset)
|
||||
serializer = self.get_serializer(page if page is not None else queryset, many=True)
|
||||
if page is not None:
|
||||
return self.get_paginated_response(serializer.data)
|
||||
return Response(serializer.data)
|
||||
|
||||
|
||||
class ShipmentDeliveryDetailView(RetrieveModelMixin, GenericAPIView):
|
||||
"""
|
||||
送货单详情 / 修改 / 删除
|
||||
@@ -712,6 +886,8 @@ class ShipmentExternalCreateView(APIView):
|
||||
contact_phone=data.get("contact_phone", ""),
|
||||
remark=data.get("remark", ""),
|
||||
area=data.get("area", ""),
|
||||
coordinates=data.get("coordinates"),
|
||||
extra=data.get("extra"),
|
||||
)
|
||||
except ValueError as e:
|
||||
return Response({"detail": str(e)}, status=status.HTTP_400_BAD_REQUEST)
|
||||
@@ -753,7 +929,15 @@ class ShipmentSalesItemCustomerListView(GenericAPIView):
|
||||
|
||||
from shipment.services import get_customers_with_unshipped_sales_items
|
||||
|
||||
return get_customers_with_unshipped_sales_items(merchant=merchant)
|
||||
qs = get_customers_with_unshipped_sales_items(merchant=merchant)
|
||||
|
||||
customer_name = self.request.query_params.get("customer_name")
|
||||
if customer_name:
|
||||
customer_name = customer_name.strip()
|
||||
if customer_name:
|
||||
qs = qs.filter(name__icontains=customer_name)
|
||||
|
||||
return qs
|
||||
|
||||
def get(self, request):
|
||||
queryset = self.get_queryset()
|
||||
@@ -872,6 +1056,134 @@ class SalesItemByPrintingOrderView(APIView):
|
||||
return Response({"count": len(serializer.data), "results": serializer.data})
|
||||
|
||||
|
||||
class SalesItemByPrintingOrderGroupView(SalesItemByPrintingOrderView):
|
||||
"""
|
||||
通过生产订单查询销售品,并按 printing_job_id 分组分页。
|
||||
|
||||
GET /api/v1/shipment/sales-items/by-printing-order/<printing_order_id>/group/
|
||||
"""
|
||||
|
||||
pagination_class = LimitedLimitOffsetPagination
|
||||
|
||||
@property
|
||||
def paginator(self):
|
||||
if not hasattr(self, "_paginator"):
|
||||
self._paginator = self.pagination_class()
|
||||
return self._paginator
|
||||
|
||||
def paginate_queryset(self, queryset):
|
||||
return self.paginator.paginate_queryset(queryset, self.request, view=self)
|
||||
|
||||
def get_paginated_response(self, data):
|
||||
return self.paginator.get_paginated_response(data)
|
||||
|
||||
def get(self, request, printing_order_id):
|
||||
from printing.models import PrintingOrder
|
||||
|
||||
user = request.user
|
||||
if getattr(user, "is_superuser", False):
|
||||
base_queryset = PrintingOrder.objects.all()
|
||||
else:
|
||||
emp = getattr(user, "employee", None)
|
||||
merchant = getattr(emp, "merchant", None) if emp else None
|
||||
if not merchant:
|
||||
return Response(
|
||||
{"detail": f"生产订单 {printing_order_id} 不存在"},
|
||||
status=status.HTTP_404_NOT_FOUND,
|
||||
)
|
||||
base_queryset = PrintingOrder.objects.filter(merchant=merchant)
|
||||
|
||||
printing_order = None
|
||||
if printing_order_id.isdigit():
|
||||
printing_order = base_queryset.filter(id=int(printing_order_id)).first()
|
||||
|
||||
if printing_order is None:
|
||||
matched_orders = list(
|
||||
base_queryset.filter(external_order_id=printing_order_id).only("id")[:2]
|
||||
)
|
||||
if len(matched_orders) > 1:
|
||||
return Response(
|
||||
{
|
||||
"detail": (
|
||||
f"external_order_id {printing_order_id} 匹配到多个生产订单,"
|
||||
"请改用内部ID查询"
|
||||
)
|
||||
},
|
||||
status=status.HTTP_400_BAD_REQUEST,
|
||||
)
|
||||
if len(matched_orders) == 1:
|
||||
printing_order = matched_orders[0]
|
||||
|
||||
if printing_order is None:
|
||||
return Response(
|
||||
{"detail": f"生产订单 {printing_order_id} 不存在"},
|
||||
status=status.HTTP_404_NOT_FOUND,
|
||||
)
|
||||
|
||||
include_already_has_shipment = (
|
||||
request.query_params.get("include_already_has_shipment", "false").lower()
|
||||
== "true"
|
||||
)
|
||||
|
||||
from shipment.services import get_sales_items_by_printing_order
|
||||
|
||||
queryset = get_sales_items_by_printing_order(
|
||||
printing_order_id=printing_order_id,
|
||||
include_already_has_shipment=include_already_has_shipment,
|
||||
merchant=printing_order.merchant,
|
||||
)
|
||||
all_items = list(queryset)
|
||||
printing_job_ids = []
|
||||
seen_printing_job_ids = set()
|
||||
for item in all_items:
|
||||
group_key = item.printing_job_id
|
||||
if group_key not in seen_printing_job_ids:
|
||||
seen_printing_job_ids.add(group_key)
|
||||
printing_job_ids.append(group_key)
|
||||
printing_job_ids.sort(key=lambda value: (value is None, value or 0))
|
||||
|
||||
page_printing_job_ids = self.paginate_queryset(printing_job_ids)
|
||||
selected_printing_job_ids = (
|
||||
page_printing_job_ids
|
||||
if page_printing_job_ids is not None
|
||||
else printing_job_ids
|
||||
)
|
||||
selected_printing_job_id_set = set(selected_printing_job_ids)
|
||||
|
||||
selected_items = [
|
||||
item
|
||||
for item in all_items
|
||||
if item.printing_job_id in selected_printing_job_id_set
|
||||
]
|
||||
serializer = SalesItemSerializer(
|
||||
selected_items,
|
||||
many=True,
|
||||
context=_build_sales_item_serializer_context(selected_items),
|
||||
)
|
||||
|
||||
grouped_by_printing_job_id = {
|
||||
printing_job_id: {
|
||||
"printing_job_id": printing_job_id,
|
||||
"count": 0,
|
||||
"items": [],
|
||||
}
|
||||
for printing_job_id in selected_printing_job_ids
|
||||
}
|
||||
for item in serializer.data:
|
||||
printing_job_id = item["printing_job_id"]
|
||||
group = grouped_by_printing_job_id[printing_job_id]
|
||||
group["count"] += 1
|
||||
group["items"].append(item)
|
||||
|
||||
groups = [
|
||||
grouped_by_printing_job_id[printing_job_id]
|
||||
for printing_job_id in selected_printing_job_ids
|
||||
]
|
||||
if page_printing_job_ids is not None:
|
||||
return self.get_paginated_response(groups)
|
||||
return Response(groups)
|
||||
|
||||
|
||||
class SalesItemByCustomerView(GenericAPIView):
|
||||
"""
|
||||
通过客户查询销售品。
|
||||
@@ -931,6 +1243,117 @@ class SalesItemByCustomerView(GenericAPIView):
|
||||
return Response(serializer.data)
|
||||
|
||||
|
||||
class SalesItemByCustomerGroupView(SalesItemByCustomerView):
|
||||
"""
|
||||
通过客户查询销售品,并按 external_order_id、name 分组。
|
||||
|
||||
GET /api/v1/shipment/sales-items/by-customer/<customer_id>/group/
|
||||
"""
|
||||
|
||||
def get(self, request, customer_id: int):
|
||||
from basic_info.models import Customer
|
||||
|
||||
user = request.user
|
||||
if getattr(user, "is_superuser", False):
|
||||
customer = Customer.objects.filter(id=customer_id).first()
|
||||
else:
|
||||
emp = getattr(user, "employee", None)
|
||||
merchant = getattr(emp, "merchant", None) if emp else None
|
||||
if not merchant:
|
||||
return Response(
|
||||
{"detail": f"客户 {customer_id} 不存在"},
|
||||
status=status.HTTP_404_NOT_FOUND,
|
||||
)
|
||||
customer = Customer.objects.filter(id=customer_id, merchant=merchant).first()
|
||||
|
||||
if customer is None:
|
||||
return Response(
|
||||
{"detail": f"客户 {customer_id} 不存在"},
|
||||
status=status.HTTP_404_NOT_FOUND,
|
||||
)
|
||||
|
||||
include_already_has_shipment = (
|
||||
request.query_params.get("include_already_has_shipment", "false").lower()
|
||||
== "true"
|
||||
)
|
||||
external_order_id = (request.query_params.get("external_order_id") or "").strip()
|
||||
|
||||
from shipment.services import get_sales_items_by_customer
|
||||
|
||||
queryset = get_sales_items_by_customer(
|
||||
merchant=customer.merchant,
|
||||
customer_id=customer.id,
|
||||
include_already_has_shipment=include_already_has_shipment,
|
||||
external_order_id=external_order_id or None,
|
||||
)
|
||||
all_items = list(queryset)
|
||||
serializer_context = _build_sales_item_serializer_context(all_items)
|
||||
serialized_items = self.get_serializer(
|
||||
all_items,
|
||||
many=True,
|
||||
context=serializer_context,
|
||||
).data
|
||||
|
||||
external_order_ids = []
|
||||
seen_external_order_ids = set()
|
||||
for item in serialized_items:
|
||||
group_key = item["external_order_id"]
|
||||
if group_key not in seen_external_order_ids:
|
||||
seen_external_order_ids.add(group_key)
|
||||
external_order_ids.append(group_key)
|
||||
external_order_ids.sort(key=lambda value: (value is None, value or ""))
|
||||
|
||||
page_external_order_ids = self.paginate_queryset(external_order_ids)
|
||||
selected_external_order_ids = (
|
||||
page_external_order_ids
|
||||
if page_external_order_ids is not None
|
||||
else external_order_ids
|
||||
)
|
||||
selected_external_order_id_set = set(selected_external_order_ids)
|
||||
|
||||
grouped_by_external_order_id = {
|
||||
external_order_id: {
|
||||
"external_order_id": external_order_id,
|
||||
"count": 0,
|
||||
"name_groups": [],
|
||||
}
|
||||
for external_order_id in selected_external_order_ids
|
||||
}
|
||||
name_group_maps = {
|
||||
external_order_id: {} for external_order_id in selected_external_order_ids
|
||||
}
|
||||
|
||||
for item in serialized_items:
|
||||
external_order_id = item["external_order_id"]
|
||||
if external_order_id not in selected_external_order_id_set:
|
||||
continue
|
||||
|
||||
external_group = grouped_by_external_order_id[external_order_id]
|
||||
external_group["count"] += 1
|
||||
|
||||
name = item["name"]
|
||||
name_group_map = name_group_maps[external_order_id]
|
||||
if name not in name_group_map:
|
||||
name_group_map[name] = {
|
||||
"name": name,
|
||||
"count": 0,
|
||||
"items": [],
|
||||
}
|
||||
external_group["name_groups"].append(name_group_map[name])
|
||||
|
||||
name_group = name_group_map[name]
|
||||
name_group["count"] += 1
|
||||
name_group["items"].append(item)
|
||||
|
||||
groups = [
|
||||
grouped_by_external_order_id[external_order_id]
|
||||
for external_order_id in selected_external_order_ids
|
||||
]
|
||||
if page_external_order_ids is not None:
|
||||
return self.get_paginated_response(groups)
|
||||
return Response(groups)
|
||||
|
||||
|
||||
class SalesItemCreateView(APIView):
|
||||
"""
|
||||
手动创建销售品
|
||||
|
||||
Reference in New Issue
Block a user