1
0
forked from erp-dev/erp

feat: app verion && some field modify (printing & shipment)

This commit is contained in:
2026-07-08 20:36:51 +08:00
parent ddbf798665
commit 36e4bb6de6
32 changed files with 3465 additions and 26 deletions

View File

@@ -1,4 +1,6 @@
from django.core.management.base import BaseCommand
from datetime import date
from django.core.management.base import BaseCommand, CommandError
from flower.app_version import set_cached_app_version_payload
@@ -11,12 +13,26 @@ class Command(BaseCommand):
parser.add_argument("--minor", type=int, required=True)
parser.add_argument("--build", type=int, required=True)
parser.add_argument("--download-url", required=True)
parser.add_argument("--force", action="store_true", default=False)
parser.add_argument(
"--publish-date",
help="发布日期,格式 YYYY-MM-DD;不传则使用当前日期",
)
def handle(self, *args, **options):
publish_date = options.get("publish_date")
if publish_date:
try:
date.fromisoformat(publish_date)
except ValueError as exc:
raise CommandError("publish-date 必须是 YYYY-MM-DD 格式") from exc
payload = set_cached_app_version_payload(
major=options["major"],
minor=options["minor"],
build=options["build"],
download_url=options["download_url"],
force=options["force"],
publish_date=publish_date,
)
self.stdout.write(self.style.SUCCESS(str(payload)))

View File

@@ -897,6 +897,7 @@ def _build_external_order_data(
'rolling_warn': str(first.get('BeiZhu') or '').strip() or None,
'curve': str(first.get('MeoA') or '').strip() or None,
'position': str(first.get('FidJ') or '').strip() or None,
'kd_riqi': _parse_external_datetime(first.get('KdRiQi')),
'outgoing_date': _parse_external_datetime(first.get('KdRiQi')),
'created_by': created_by_user,
'external_order_id': external_order_id,

View File

@@ -0,0 +1,242 @@
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Permission
from django.test import TestCase
from rest_framework import status
from rest_framework.test import APIClient
from basic_info import models as basic_models
User = get_user_model()
class CustomerAddressAPITestCase(TestCase):
def setUp(self):
self.client = APIClient()
self.merchant = basic_models.Merchant.objects.create(
name="客户地址商户", type=basic_models.MerchantTypeEnum.FACTORY
)
self.other_merchant = basic_models.Merchant.objects.create(
name="其它客户地址商户", type=basic_models.MerchantTypeEnum.FACTORY
)
self.user = User.objects.create_user(username="addr-user", password="testpass123")
self.employee = basic_models.Employee.objects.create(
sys_user=self.user,
merchant=self.merchant,
name="地址员工",
status=basic_models.EmployeeStatusEnum.ACTIVE,
)
self.other_user = User.objects.create_user(
username="addr-other-user", password="testpass123"
)
self.other_employee = basic_models.Employee.objects.create(
sys_user=self.other_user,
merchant=self.merchant,
name="其它地址员工",
status=basic_models.EmployeeStatusEnum.ACTIVE,
)
self.foreign_user = User.objects.create_user(
username="addr-foreign-user", password="testpass123"
)
self.foreign_employee = basic_models.Employee.objects.create(
sys_user=self.foreign_user,
merchant=self.other_merchant,
name="外部地址员工",
status=basic_models.EmployeeStatusEnum.ACTIVE,
)
self.visible_customer = basic_models.Customer.objects.create(
merchant=self.merchant,
name="可见客户",
mobile="13800138000",
area="杭州",
created_by=self.employee,
)
self.invisible_customer = basic_models.Customer.objects.create(
merchant=self.merchant,
name="不可见客户",
mobile="13800138001",
area="绍兴",
created_by=self.other_employee,
)
self.foreign_customer = basic_models.Customer.objects.create(
merchant=self.other_merchant,
name="外部客户",
mobile="13800138002",
area="苏州",
created_by=self.foreign_employee,
)
self.visible_address = basic_models.CustomerAddress.objects.create(
merchant=self.merchant,
customer=self.visible_customer,
address="杭州市测试路1号",
contact_name="张三",
contact_phone="13800138000",
area="杭州",
coordinates="120.1,30.2",
is_default=True,
remark="一号仓",
extra={"source": "test"},
created_by=self.employee,
)
self.invisible_address = basic_models.CustomerAddress.objects.create(
merchant=self.merchant,
customer=self.invisible_customer,
address="绍兴市测试路2号",
contact_name="李四",
contact_phone="13900139000",
area="绍兴",
created_by=self.other_employee,
)
self.foreign_address = basic_models.CustomerAddress.objects.create(
merchant=self.other_merchant,
customer=self.foreign_customer,
address="苏州市测试路3号",
contact_name="王五",
contact_phone="13700137000",
area="苏州",
created_by=self.foreign_employee,
)
self.client.force_authenticate(user=self.user)
def test_list_only_visible_customer_addresses(self):
resp = self.client.get("/api/v1/customer-addresses/")
self.assertEqual(resp.status_code, status.HTTP_200_OK)
ids = {item["id"] for item in resp.json()["results"]}
self.assertIn(self.visible_address.id, ids)
self.assertNotIn(self.invisible_address.id, ids)
self.assertNotIn(self.foreign_address.id, ids)
def test_visible_employees_can_see_customer_address(self):
self.invisible_customer.visible_employees.add(self.employee)
resp = self.client.get("/api/v1/customer-addresses/")
self.assertEqual(resp.status_code, status.HTTP_200_OK)
ids = {item["id"] for item in resp.json()["results"]}
self.assertIn(self.invisible_address.id, ids)
def test_view_all_customers_permission_sees_same_merchant_addresses(self):
permission = Permission.objects.get(codename="view_all_customers")
self.user.user_permissions.add(permission)
resp = self.client.get("/api/v1/customer-addresses/")
self.assertEqual(resp.status_code, status.HTTP_200_OK)
ids = {item["id"] for item in resp.json()["results"]}
self.assertIn(self.visible_address.id, ids)
self.assertIn(self.invisible_address.id, ids)
self.assertNotIn(self.foreign_address.id, ids)
def test_create_address_for_visible_customer_sets_merchant_and_creator(self):
payload = {
"customer": self.visible_customer.id,
"address": "杭州市新增地址",
"contact_name": "赵六",
"contact_phone": "13600136000",
"area": "杭州",
"coordinates": "120.2,30.3",
"is_default": False,
"remark": "新增备注",
"extra": {"tag": "new"},
}
resp = self.client.post("/api/v1/customer-addresses/", payload, format="json")
self.assertEqual(resp.status_code, status.HTTP_201_CREATED)
data = resp.json()
self.assertEqual(data["merchant"], self.merchant.id)
self.assertEqual(data["created_by"], self.employee.id)
self.assertEqual(data["coordinates"], "120.2,30.3")
self.assertEqual(data["extra"], {"tag": "new"})
def test_create_address_for_invisible_customer_is_rejected(self):
payload = {
"customer": self.invisible_customer.id,
"address": "不可见客户地址",
}
resp = self.client.post("/api/v1/customer-addresses/", payload, format="json")
self.assertEqual(resp.status_code, status.HTTP_400_BAD_REQUEST)
def test_default_address_is_unique_per_customer(self):
old_default = self.visible_address
resp = self.client.post(
"/api/v1/customer-addresses/",
{
"customer": self.visible_customer.id,
"address": "新的默认地址",
"is_default": True,
},
format="json",
)
self.assertEqual(resp.status_code, status.HTTP_201_CREATED)
old_default.refresh_from_db()
self.assertFalse(old_default.is_default)
self.assertTrue(
basic_models.CustomerAddress.objects.get(id=resp.json()["id"]).is_default
)
def test_set_default_address_endpoint_unsets_other_default_addresses(self):
new_address = basic_models.CustomerAddress.objects.create(
merchant=self.merchant,
customer=self.visible_customer,
address="待设默认地址",
created_by=self.employee,
)
resp = self.client.post(
f"/api/v1/customer-address/{new_address.id}/set-default/"
)
self.assertEqual(resp.status_code, status.HTTP_200_OK)
self.visible_address.refresh_from_db()
new_address.refresh_from_db()
self.assertFalse(self.visible_address.is_default)
self.assertTrue(new_address.is_default)
self.assertTrue(resp.json()["is_default"])
def test_delete_soft_deletes_address_and_query_deleted_records(self):
resp = self.client.delete(f"/api/v1/customer-addresses/{self.visible_address.id}/")
self.assertEqual(resp.status_code, status.HTTP_204_NO_CONTENT)
self.visible_address.refresh_from_db()
self.assertIsNotNone(self.visible_address.deleted_at)
self.assertEqual(self.visible_address.deleted_by, self.employee)
self.assertFalse(self.visible_address.is_default)
default_resp = self.client.get("/api/v1/customer-addresses/")
default_ids = {item["id"] for item in default_resp.json()["results"]}
self.assertNotIn(self.visible_address.id, default_ids)
include_resp = self.client.get("/api/v1/customer-addresses/?include_deleted=true")
include_ids = {item["id"] for item in include_resp.json()["results"]}
self.assertIn(self.visible_address.id, include_ids)
only_resp = self.client.get("/api/v1/customer-addresses/?only_deleted=true")
only_ids = {item["id"] for item in only_resp.json()["results"]}
self.assertEqual(only_ids, {self.visible_address.id})
def test_filters(self):
query = (
f"/api/v1/customer-addresses/?customer={self.visible_customer.id}"
"&customer_name=可见&address=测试路&contact_name=张"
"&contact_phone=138&area=杭州&is_default=true&search=一号仓"
)
resp = self.client.get(query)
self.assertEqual(resp.status_code, status.HTTP_200_OK)
data = resp.json()
self.assertEqual(data["count"], 1)
self.assertEqual(data["results"][0]["id"], self.visible_address.id)
def test_retrieve_invisible_address_returns_404(self):
resp = self.client.get(f"/api/v1/customer-addresses/{self.invisible_address.id}/")
self.assertEqual(resp.status_code, status.HTTP_404_NOT_FOUND)

View File

@@ -164,6 +164,7 @@ class ExternalPrintingRecordsSyncTaskTest(TestCase):
self.assertEqual(job.printing_order.position, r'\\fw\\2026年-LWQ15\\2026\\H鸿烨\\Tj1712#')
self.assertEqual(job.printing_order.fabric, '120克本白四面弹单定')
self.assertEqual(job.printing_order.area, '周边')
self.assertEqual(job.printing_order.kd_riqi.isoformat(), '2026-01-26T20:00:52+00:00')
@patch('api_v1.tasks._advance_external_printing_cursor')
@patch('api_v1.tasks._fetch_external_product_image')

View File

@@ -32,14 +32,18 @@ from .views.products import ProductQuickViewSet
from .views.parameters import StateParameterViewSet
from .views.users import CreateUserWithProfileView
from .views.mingdaoyun import MDYPlateOrderStagingViewSet
from .views.basic_info import CustomerAddressViewSet
from .views.shipment import (
SalesItemDetailView,
SalesItemRebuildView,
SalesItemByCustomerGroupView,
SalesItemByCustomerView,
SalesItemByPrintingOrderGroupView,
SalesItemByPrintingOrderView,
SalesItemCreateView,
ShipmentStatusUpdateView,
ShipmentDeliveryBindShipmentsView,
ShipmentDeliveryByPrintingOrderView,
ShipmentDeliveryCancelView,
ShipmentDeliveryDetailView,
ShipmentDeliveryListCreateView,
@@ -69,6 +73,9 @@ main_router.register(r"plate-orders", PlateOrderViewSet, basename="plate-order")
main_router.register(r"upload", UploadFileViewSet, basename="upload")
main_router.register(r"products/quick", ProductQuickViewSet, basename="product-quick")
main_router.register(r"parameters", StateParameterViewSet, basename="parameter")
main_router.register(
r"customer-addresses", CustomerAddressViewSet, basename="customer-address"
)
main_router.register(
r"mdy-plate-order-staging",
MDYPlateOrderStagingViewSet,
@@ -76,6 +83,11 @@ main_router.register(
)
urlpatterns = [
path(
"customer-address/<int:pk>/set-default/",
CustomerAddressViewSet.as_view({"post": "set_default"}),
name="customer_address_set_default",
),
# 库存变动相关API
path(
"stock-snapshots/", StockSnapshotListView.as_view(), name="list_stock_snapshots"
@@ -355,6 +367,11 @@ urlpatterns = [
ShipmentDeliveryListCreateView.as_view(),
name="shipment_delivery_list_create",
),
path(
"shipment/deliveries/by-printing-order/<str:printing_order_id>/",
ShipmentDeliveryByPrintingOrderView.as_view(),
name="shipment_deliveries_by_printing_order",
),
path(
"shipment/deliveries/<int:pk>/",
ShipmentDeliveryDetailView.as_view(),
@@ -380,11 +397,21 @@ urlpatterns = [
ShipmentSalesItemCustomerListView.as_view(),
name="sales_item_customers",
),
path(
"shipment/sales-items/by-customer/<int:customer_id>/group/",
SalesItemByCustomerGroupView.as_view(),
name="sales_items_by_customer_group",
),
path(
"shipment/sales-items/by-customer/<int:customer_id>/",
SalesItemByCustomerView.as_view(),
name="sales_items_by_customer",
),
path(
"shipment/sales-items/by-printing-order/<str:printing_order_id>/group/",
SalesItemByPrintingOrderGroupView.as_view(),
name="sales_items_by_printing_order_group",
),
path(
"shipment/sales-items/by-printing-order/<str:printing_order_id>/",
SalesItemByPrintingOrderView.as_view(),

247
api_v1/views/basic_info.py Normal file
View File

@@ -0,0 +1,247 @@
from django.db import transaction
from django.db.models import Q
from django.utils import timezone
from rest_framework import serializers
from rest_framework.exceptions import PermissionDenied, ValidationError
from rest_framework import filters
from rest_framework.response import Response
from flower.viewsets import LimitedModelViewSet
from basic_info import models as basic_models
from basic_info.services import CustomerVisibilityService
def _parse_bool(value: str | None) -> bool | None:
if value is None:
return None
normalized = value.strip().lower()
if normalized in {"1", "true", "yes", "y"}:
return True
if normalized in {"0", "false", "no", "n"}:
return False
return None
class CustomerAddressSerializer(serializers.ModelSerializer):
merchant_name = serializers.CharField(source="merchant.name", read_only=True)
customer_name = serializers.CharField(source="customer.name", read_only=True)
created_by_name = serializers.CharField(source="created_by.name", read_only=True, allow_null=True)
deleted_by_name = serializers.CharField(source="deleted_by.name", read_only=True, allow_null=True)
class Meta:
model = basic_models.CustomerAddress
fields = [
"id",
"merchant",
"merchant_name",
"customer",
"customer_name",
"address",
"contact_name",
"contact_phone",
"area",
"coordinates",
"is_default",
"remark",
"extra",
"created_by",
"created_by_name",
"deleted_at",
"deleted_by",
"deleted_by_name",
"created_at",
"updated_at",
]
read_only_fields = [
"id",
"merchant",
"merchant_name",
"customer_name",
"created_by",
"created_by_name",
"deleted_at",
"deleted_by",
"deleted_by_name",
"created_at",
"updated_at",
]
def validate_customer(self, customer):
request = self.context["request"]
view = self.context["view"]
if self.instance is not None and customer.id != self.instance.customer_id:
raise serializers.ValidationError("不允许修改客户")
if not view.can_access_customer(customer, request.user):
raise serializers.ValidationError("客户不存在或不可见")
return customer
class CustomerAddressViewSet(LimitedModelViewSet):
"""
客户地址 CRUD。
查询参数:
- customer: 客户ID
- customer_name: 客户名称模糊查询
- address: 地址模糊查询
- contact_name: 联系人模糊查询
- contact_phone: 联系电话模糊查询
- area: 地区模糊查询
- is_default: 是否默认地址 true/false
- include_deleted: 是否包含软删除记录 true/false
- only_deleted: 是否仅查询软删除记录 true/false
- search: 客户名/地址/联系人/电话/地区/备注模糊搜索
- ordering: id/-id/created_at/-created_at/updated_at/-updated_at/is_default/-is_default
"""
queryset = basic_models.CustomerAddress.objects.all()
serializer_class = CustomerAddressSerializer
filter_backends = [filters.OrderingFilter]
ordering_fields = ["id", "created_at", "updated_at", "is_default"]
ordering = ["-is_default", "-created_at", "-id"]
def get_employee(self):
return getattr(self.request.user, "employee", None)
def can_view_all_customers(self, user) -> bool:
return user.is_superuser or user.has_perm("basic_info.view_all_customers")
def can_access_customer(self, customer, user) -> bool:
if user.is_superuser:
return True
emp = getattr(user, "employee", None)
if emp is None or emp.merchant_id != customer.merchant_id:
return False
if user.has_perm("basic_info.view_all_customers"):
return True
return CustomerVisibilityService.is_customer_visible_to_employee(customer, user)
def get_queryset(self):
queryset = (
super()
.get_queryset()
.select_related("merchant", "customer", "created_by", "deleted_by")
)
user = self.request.user
if not user.is_superuser:
emp = self.get_employee()
if emp is None or emp.merchant_id is None:
return queryset.none()
queryset = queryset.filter(merchant=emp.merchant)
if not user.has_perm("basic_info.view_all_customers"):
customer_queryset = CustomerVisibilityService.filter_customers_for_employee(
basic_models.Customer.objects.filter(merchant=emp.merchant),
user,
)
queryset = queryset.filter(customer__in=customer_queryset)
only_deleted = _parse_bool(self.request.query_params.get("only_deleted"))
include_deleted = _parse_bool(self.request.query_params.get("include_deleted"))
if only_deleted:
queryset = queryset.filter(deleted_at__isnull=False)
elif not include_deleted:
queryset = queryset.filter(deleted_at__isnull=True)
customer = self.request.query_params.get("customer")
if customer:
if not customer.strip().isdigit():
return queryset.none()
queryset = queryset.filter(customer_id=customer)
customer_name = (self.request.query_params.get("customer_name") or "").strip()
if customer_name:
queryset = queryset.filter(customer__name__icontains=customer_name)
address = (self.request.query_params.get("address") or "").strip()
if address:
queryset = queryset.filter(address__icontains=address)
contact_name = (self.request.query_params.get("contact_name") or "").strip()
if contact_name:
queryset = queryset.filter(contact_name__icontains=contact_name)
contact_phone = (self.request.query_params.get("contact_phone") or "").strip()
if contact_phone:
queryset = queryset.filter(contact_phone__icontains=contact_phone)
area = (self.request.query_params.get("area") or "").strip()
if area:
queryset = queryset.filter(area__icontains=area)
is_default = _parse_bool(self.request.query_params.get("is_default"))
if is_default is not None:
queryset = queryset.filter(is_default=is_default)
search = (self.request.query_params.get("search") or "").strip()
if search:
queryset = queryset.filter(
Q(customer__name__icontains=search)
| Q(address__icontains=search)
| Q(contact_name__icontains=search)
| Q(contact_phone__icontains=search)
| Q(area__icontains=search)
| Q(remark__icontains=search)
)
return queryset.distinct()
def _unset_other_default_addresses(self, address: basic_models.CustomerAddress):
if not address.is_default or address.deleted_at is not None:
return
basic_models.CustomerAddress.objects.filter(
merchant=address.merchant,
customer=address.customer,
deleted_at__isnull=True,
is_default=True,
).exclude(id=address.id).update(is_default=False)
@transaction.atomic
def perform_create(self, serializer):
customer = serializer.validated_data["customer"]
emp = self.get_employee()
if not self.request.user.is_superuser and emp is None:
raise PermissionDenied("当前用户未绑定员工")
address = serializer.save(
merchant=customer.merchant,
created_by=emp,
)
self._unset_other_default_addresses(address)
@transaction.atomic
def perform_update(self, serializer):
address = serializer.save()
self._unset_other_default_addresses(address)
@transaction.atomic
def perform_destroy(self, instance):
if instance.deleted_at is not None:
return
emp = self.get_employee()
if not self.request.user.is_superuser and emp is None:
raise PermissionDenied("当前用户未绑定员工")
instance.deleted_at = timezone.now()
instance.deleted_by = emp
instance.is_default = False
instance.save(update_fields=["deleted_at", "deleted_by", "is_default", "updated_at"])
@transaction.atomic
def set_default(self, request, pk: int):
address = self.get_object()
if address.deleted_at is not None:
raise ValidationError("已删除的客户地址不能设为默认地址")
address.is_default = True
address.save(update_fields=["is_default", "updated_at"])
self._unset_other_default_addresses(address)
serializer = self.get_serializer(address)
return Response(serializer.data)

View File

@@ -33,6 +33,30 @@ def _build_absolute_media_url(url: str | None, request):
return build_public_media_url(url, request=request)
def _resolve_printing_order_external_first_record_field(obj, field_name):
if not getattr(obj, 'external_order_id', None):
return None
try:
raw = obj.external_raw or {}
first_record = raw.get('first_record') or {}
value = first_record.get(field_name)
except AttributeError:
return None
value = str(value or '').strip()
return value or None
def resolve_printing_order_bianhao_kd(obj):
return _resolve_printing_order_external_first_record_field(obj, 'BianHaoKD')
def resolve_printing_order_kd_riqi(obj):
value = getattr(obj, 'kd_riqi', None)
if value is not None:
return serializers.DateTimeField().to_representation(value)
return _resolve_printing_order_external_first_record_field(obj, 'KdRiQi')
def _serialize_plate_images(raw_value, request):
if not raw_value:
return []
@@ -163,6 +187,8 @@ class PrintingOrderListSerializer(serializers.ModelSerializer):
external_customer_id = serializers.CharField(read_only=True)
external_customer_name = serializers.CharField(read_only=True)
external_employee_name = serializers.CharField(read_only=True)
bianhao_kd = serializers.SerializerMethodField()
kd_riqi = serializers.SerializerMethodField()
class Meta:
model = models.PrintingOrder
@@ -172,7 +198,7 @@ class PrintingOrderListSerializer(serializers.ModelSerializer):
'is_fabric_received', 'outgoing_date', 'is_invalid', 'new_curve',
'process', 'process_name', 'progress', 'position', 'print_count',
'jobs_status_summary', 'jobs_last_status_summary',
'external_order_id', 'external_customer_id', 'external_customer_name', 'external_employee_name',
'external_order_id', 'bianhao_kd', 'kd_riqi', 'external_customer_id', 'external_customer_name', 'external_employee_name',
'created_by', 'created_by_name',
'created_at', 'updated_at',
]
@@ -260,6 +286,12 @@ class PrintingOrderListSerializer(serializers.ModelSerializer):
emp = getattr(user, 'employee', None)
return getattr(emp, 'name', None)
def get_bianhao_kd(self, obj):
return resolve_printing_order_bianhao_kd(obj)
def get_kd_riqi(self, obj):
return resolve_printing_order_kd_riqi(obj)
class PrintingOrderDetailSerializer(serializers.ModelSerializer):
"""印染订单详情序列化器"""
@@ -274,6 +306,8 @@ class PrintingOrderDetailSerializer(serializers.ModelSerializer):
external_customer_id = serializers.CharField(read_only=True)
external_customer_name = serializers.CharField(read_only=True)
external_employee_name = serializers.CharField(read_only=True)
bianhao_kd = serializers.SerializerMethodField()
kd_riqi = serializers.SerializerMethodField()
class Meta:
model = models.PrintingOrder
@@ -283,7 +317,7 @@ class PrintingOrderDetailSerializer(serializers.ModelSerializer):
'is_fabric_received', 'craft', 'description', 'outgoing_date',
'curve', 'new_curve', 'position', 'created_by_name',
'printing_warn', 'rolling_warn', 'production_warn',
'external_order_id', 'external_customer_id', 'external_customer_name', 'external_employee_name',
'external_order_id', 'bianhao_kd', 'kd_riqi', 'external_customer_id', 'external_customer_name', 'external_employee_name',
'is_invalid', 'process', 'process_name', 'progress', 'print_count',
'created_at', 'updated_at'
]
@@ -297,6 +331,12 @@ class PrintingOrderDetailSerializer(serializers.ModelSerializer):
emp = getattr(user, 'employee', None)
return getattr(emp, 'name', None)
def get_bianhao_kd(self, obj):
return resolve_printing_order_bianhao_kd(obj)
def get_kd_riqi(self, obj):
return resolve_printing_order_kd_riqi(obj)
class PrintingOrderCreateUpdateSerializer(serializers.ModelSerializer):
"""印染订单创建/更新序列化器"""

View File

@@ -1,7 +1,7 @@
"""
PrintingOrder API 测试
"""
from datetime import datetime
from datetime import datetime, timezone as dt_timezone
from django.test import TestCase
from django.db import connection
from django.conf import settings
@@ -260,6 +260,12 @@ class PrintingOrderAPITestCase(TestCase):
external_customer_id='KH00991',
external_customer_name='李泽柔',
external_employee_name='丽容',
external_raw={
'first_record': {
'BianHaoKD': '7.07',
'KdRiQi': '2026-07-06T21:48:58Z',
}
},
)
printing_models.PrintingOrder.objects.create(
merchant=self.merchant,
@@ -277,11 +283,65 @@ class PrintingOrderAPITestCase(TestCase):
self.assertEqual(item['external_customer_id'], 'KH00991')
self.assertEqual(item['external_customer_name'], '李泽柔')
self.assertEqual(item['external_employee_name'], '丽容')
self.assertEqual(item['bianhao_kd'], '7.07')
self.assertEqual(item['kd_riqi'], '2026-07-06T21:48:58Z')
detail = self.client.get(f'/api/v1/printing-orders/{order1.id}/')
self.assertEqual(detail.status_code, status.HTTP_200_OK)
self.assertEqual(detail.data['external_order_id'], 'KD20410611')
self.assertEqual(detail.data['external_customer_id'], 'KH00991')
self.assertEqual(detail.data['bianhao_kd'], '7.07')
self.assertEqual(detail.data['kd_riqi'], '2026-07-06T21:48:58Z')
def test_bianhao_kd_returns_null_without_external_order_id(self):
order = printing_models.PrintingOrder.objects.create(
merchant=self.merchant,
customer=self.customer,
fabric='普通订单',
width='150cm',
external_raw={'first_record': {'BianHaoKD': '7.07'}},
)
response = self.client.get(f'/api/v1/printing-orders/{order.id}/')
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertIsNone(response.data['bianhao_kd'])
self.assertIsNone(response.data['kd_riqi'])
def test_filter_and_order_by_kd_riqi(self):
older = printing_models.PrintingOrder.objects.create(
merchant=self.merchant,
customer=self.customer,
fabric='旧开单时间',
width='150cm',
external_order_id='KD-OLDER',
kd_riqi=datetime(2026, 7, 1, 10, 0, tzinfo=dt_timezone.utc),
)
newer = printing_models.PrintingOrder.objects.create(
merchant=self.merchant,
customer=self.customer,
fabric='新开单时间',
width='150cm',
external_order_id='KD-NEWER',
kd_riqi=datetime(2026, 7, 2, 10, 0, tzinfo=dt_timezone.utc),
)
printing_models.PrintingOrder.objects.create(
merchant=self.merchant,
customer=self.customer,
fabric='范围外开单时间',
width='150cm',
external_order_id='KD-OUTSIDE',
kd_riqi=datetime(2026, 7, 3, 10, 0, tzinfo=dt_timezone.utc),
)
response = self.client.get(
'/api/v1/printing-orders/?kd_riqi_from=2026-07-01&kd_riqi_to=2026-07-02&ordering=kd_riqi'
)
self.assertEqual(response.status_code, status.HTTP_200_OK)
result_ids = [item['id'] for item in response.data['results']]
self.assertEqual(result_ids, [older.id, newer.id])
self.assertEqual(response.data['results'][0]['kd_riqi'], '2026-07-01T18:00:00+08:00')
def test_retrieve_printing_order(self):
"""测试获取订单详情"""

View File

@@ -90,6 +90,8 @@ class PrintingOrderFilterSet(django_filters.FilterSet):
area = django_filters.CharFilter(lookup_expr="icontains")
outgoing_date_from = django_filters.CharFilter(method="filter_outgoing_date_from")
outgoing_date_to = django_filters.CharFilter(method="filter_outgoing_date_to")
kd_riqi_from = django_filters.CharFilter(method="filter_kd_riqi_from")
kd_riqi_to = django_filters.CharFilter(method="filter_kd_riqi_to")
created_date_from = django_filters.DateFilter(
field_name="created_at", lookup_expr="gte"
)
@@ -196,6 +198,21 @@ class PrintingOrderFilterSet(django_filters.FilterSet):
# 日期时间:按“<=”包含到秒
return queryset.filter(outgoing_date__lte=dt)
def filter_kd_riqi_from(self, queryset, name, value):
dt, _has_time = self._parse_date_or_datetime(value)
if dt is None:
raise ValidationError("kd_riqi_from 必须是日期或日期时间")
return queryset.filter(kd_riqi__gte=dt)
def filter_kd_riqi_to(self, queryset, name, value):
dt, has_time = self._parse_date_or_datetime(value)
if dt is None:
raise ValidationError("kd_riqi_to 必须是日期或日期时间")
if not has_time:
return queryset.filter(kd_riqi__lt=dt + timedelta(days=1))
return queryset.filter(kd_riqi__lte=dt)
def filter_created_date_to(self, queryset, name, value):
"""
过滤 created_at <= 指定日期的 23:59:59.999999
@@ -234,6 +251,8 @@ class PrintingOrderViewSet(CustomerVisibilityFilterMixin, LimitedModelViewSet):
- area: 地区(模糊查询)
- outgoing_date_from: 出货日期起始
- outgoing_date_to: 出货日期结束
- kd_riqi_from: 外部开单日期时间起始
- kd_riqi_to: 外部开单日期时间结束
- created_date_from: 创建日期起始
- created_date_to: 创建日期结束
- search: 全文搜索(客户名称、面料、地区、工艺)
@@ -266,6 +285,7 @@ class PrintingOrderViewSet(CustomerVisibilityFilterMixin, LimitedModelViewSet):
"created_at",
"updated_at",
"outgoing_date",
"kd_riqi",
"is_urgent",
"is_fabric_received",
"is_invalid",

View File

@@ -6,11 +6,14 @@ Shipment API 模块
from .views import (
SalesItemDetailView,
SalesItemRebuildView,
SalesItemByCustomerGroupView,
SalesItemByCustomerView,
SalesItemByPrintingOrderGroupView,
SalesItemByPrintingOrderView,
SalesItemCreateView,
ShipmentStatusUpdateView,
ShipmentDeliveryBindShipmentsView,
ShipmentDeliveryByPrintingOrderView,
ShipmentDeliveryDetailView,
ShipmentDeliveryListCreateView,
ShipmentDeliveryCancelView,
@@ -24,11 +27,14 @@ from .views import (
__all__ = [
'SalesItemDetailView',
'SalesItemRebuildView',
'SalesItemByCustomerGroupView',
'SalesItemByCustomerView',
'SalesItemByPrintingOrderGroupView',
'SalesItemByPrintingOrderView',
'SalesItemCreateView',
'ShipmentStatusUpdateView',
'ShipmentDeliveryBindShipmentsView',
'ShipmentDeliveryByPrintingOrderView',
'ShipmentDeliveryDetailView',
'ShipmentDeliveryListCreateView',
'ShipmentDeliveryCancelView',

View File

@@ -111,6 +111,9 @@ class ShipmentSerializer(serializers.ModelSerializer):
"""
customer_name = serializers.CharField(source="customer.name", read_only=True)
address_id = serializers.IntegerField(
source="customer_address.id", read_only=True, allow_null=True
)
created_by_id = serializers.IntegerField(
source="created_by.id", read_only=True, allow_null=True
)
@@ -142,6 +145,7 @@ class ShipmentSerializer(serializers.ModelSerializer):
"merchant_name",
"customer",
"customer_name",
"address_id",
"fabric",
"order_description",
"shipment_date",
@@ -149,11 +153,13 @@ class ShipmentSerializer(serializers.ModelSerializer):
"contact_name",
"contact_phone",
"area",
"coordinates",
"remark",
"status",
"status_display",
"external_id",
"geo_coordinates",
"extra",
"delivery_id",
"status_modified_at",
"cancelled_by_id",
@@ -277,6 +283,12 @@ class ShipmentCreateNormalSerializer(serializers.Serializer):
allow_blank=True,
help_text="地址(可选)",
)
address_id = serializers.IntegerField(
required=False,
allow_null=True,
min_value=1,
help_text="客户地址ID(可选)",
)
contact_name = serializers.CharField(
max_length=100,
required=False,
@@ -292,15 +304,35 @@ class ShipmentCreateNormalSerializer(serializers.Serializer):
help_text="联系电话(可选)",
)
area = serializers.CharField(
max_length=30,
max_length=100,
required=False,
default="",
allow_blank=True,
help_text="出货地区(可选)",
)
coordinates = serializers.CharField(
max_length=100,
required=False,
allow_blank=True,
allow_null=True,
default=None,
help_text="经纬度字符串(可选)",
)
extra = serializers.JSONField(
required=False,
allow_null=True,
default=None,
help_text="扩展信息(可选)",
)
remark = serializers.CharField(
required=False, default="", allow_blank=True, help_text="备注"
)
status = serializers.ChoiceField(
choices=ShipmentStatus.choices,
required=False,
default=ShipmentStatus.DRAFT,
help_text="出货单状态(可选,默认 1=草稿)",
)
sales_items = serializers.ListField(
child=serializers.IntegerField(),
required=False,
@@ -357,12 +389,26 @@ class ShipmentCreateExternalSerializer(serializers.Serializer):
help_text="联系电话(可选)",
)
area = serializers.CharField(
max_length=30,
max_length=100,
required=False,
default="",
allow_blank=True,
help_text="出货地区(可选)",
)
coordinates = serializers.CharField(
max_length=100,
required=False,
allow_blank=True,
allow_null=True,
default=None,
help_text="经纬度字符串(可选)",
)
extra = serializers.JSONField(
required=False,
allow_null=True,
default=None,
help_text="扩展信息(可选)",
)
remark = serializers.CharField(
required=False, default="", allow_blank=True, help_text="备注"
)
@@ -404,7 +450,19 @@ class ShipmentUpdateSerializer(serializers.Serializer):
max_length=50, required=False, allow_blank=True, help_text="联系电话(可选)"
)
area = serializers.CharField(
max_length=30, required=False, allow_blank=True, help_text="出货地区(可选)"
max_length=100, required=False, allow_blank=True, help_text="出货地区(可选)"
)
coordinates = serializers.CharField(
max_length=100,
required=False,
allow_blank=True,
allow_null=True,
help_text="经纬度字符串(可选)",
)
extra = serializers.JSONField(
required=False,
allow_null=True,
help_text="扩展信息(可选)",
)
remark = serializers.CharField(
required=False, allow_blank=True, help_text="备注(可选)"
@@ -650,6 +708,74 @@ class ShipmentDeliverySerializer(serializers.ModelSerializer):
).data
class ShipmentDeliveryByPrintingOrderSerializer(serializers.ModelSerializer):
"""
按生产订单查询送货单的专用 DTO。
当前字段基本对齐送货单列表,后续可按该查询场景独立调整。
"""
status_display = serializers.CharField(source="get_status_display", read_only=True)
merchant_id = serializers.IntegerField(source="merchant.id", read_only=True)
merchant_name = serializers.CharField(source="merchant.name", read_only=True)
created_by_id = serializers.IntegerField(
source="created_by.id", read_only=True, allow_null=True
)
created_by_name = serializers.SerializerMethodField()
operator_id = serializers.IntegerField(
source="operator.id", read_only=True, allow_null=True
)
operator_name = serializers.CharField(source="operator.name", read_only=True, allow_null=True)
shipments_count = serializers.SerializerMethodField()
shipments = serializers.SerializerMethodField()
class Meta:
model = ShipmentDelivery
fields = [
"id",
"merchant_id",
"merchant_name",
"driver_name",
"vehicle_trip",
"contact_phone",
"vehicle_capacity",
"remark",
"internal_remark",
"shipment_order_ids",
"status",
"status_display",
"started_at",
"delivered_at",
"cancelled_at",
"shipments_count",
"shipments",
"created_by_id",
"created_by_name",
"operator_id",
"operator_name",
"created_at",
"updated_at",
]
read_only_fields = fields
def get_created_by_name(self, obj):
if obj.created_by:
employee = getattr(obj.created_by, "employee", None)
if employee:
return employee.name
return obj.created_by.username
return None
def get_shipments_count(self, obj):
return obj.shipments.count()
def get_shipments(self, obj):
return ShipmentDeliveryShipmentSummarySerializer(
obj.shipments.order_by("id"),
many=True,
).data
class ShipmentDeliveryCreateSerializer(serializers.Serializer):
driver_name = serializers.CharField(max_length=100, help_text="司机名")
vehicle_trip = serializers.CharField(max_length=100, help_text="车次")

View File

@@ -295,6 +295,81 @@ class SalesItemByPrintingOrderAPITestCase(TestCase):
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertIn("匹配到多个生产订单", response.json()["detail"])
def test_get_sales_items_by_printing_order_group_groups_by_printing_job(self):
url = (
f"/api/v1/shipment/sales-items/by-printing-order/{self.printing_order.id}/"
"group/"
)
response = self.client.get(url)
self.assertEqual(response.status_code, status.HTTP_200_OK)
data = response.json()
self.assertEqual(data["count"], 1)
self.assertEqual(len(data["results"]), 1)
group = data["results"][0]
self.assertEqual(group["printing_job_id"], self.printing_job1.id)
self.assertEqual(group["count"], 2)
self.assertEqual(
{item["id"] for item in group["items"]},
{self.sales_item1.id, self.sales_item2.id},
)
def test_get_sales_items_by_printing_order_group_supports_external_order_id(self):
response = self.client.get(
"/api/v1/shipment/sales-items/by-printing-order/EXT-PO-001/group/"
)
self.assertEqual(response.status_code, status.HTTP_200_OK)
data = response.json()
self.assertEqual(data["count"], 1)
self.assertEqual(data["results"][0]["printing_job_id"], self.printing_job1.id)
def test_get_sales_items_by_printing_order_group_paginates_printing_job_groups(self):
url = (
f"/api/v1/shipment/sales-items/by-printing-order/{self.printing_order.id}/"
"group/?include_already_has_shipment=true&limit=1&offset=1"
)
response = self.client.get(url)
self.assertEqual(response.status_code, status.HTTP_200_OK)
data = response.json()
self.assertEqual(data["count"], 2)
self.assertEqual(len(data["results"]), 1)
self.assertEqual(data["results"][0]["printing_job_id"], self.printing_job2.id)
self.assertEqual(data["results"][0]["count"], 1)
self.assertEqual(data["results"][0]["items"][0]["id"], self.sales_item3.id)
def test_get_sales_items_by_printing_order_group_multiple_external_matches(self):
printing_models.PrintingOrder.objects.create(
merchant=self.merchant,
customer=self.customer,
fabric="测试面料3",
width="160cm",
process=self.process,
created_by=self.user,
external_order_id="EXT-DUPLICATED-GROUP",
)
printing_models.PrintingOrder.objects.create(
merchant=self.merchant,
customer=self.customer,
fabric="测试面料4",
width="170cm",
process=self.process,
created_by=self.user,
external_order_id="EXT-DUPLICATED-GROUP",
)
response = self.client.get(
"/api/v1/shipment/sales-items/by-printing-order/EXT-DUPLICATED-GROUP/group/"
)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertIn("匹配到多个生产订单", response.json()["detail"])
def test_get_sales_items_printing_order_not_found(self):
"""测试生产订单不存在"""
url = "/api/v1/shipment/sales-items/by-printing-order/99999/"
@@ -351,6 +426,252 @@ class SalesItemByPrintingOrderAPITestCase(TestCase):
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
class ShipmentDeliveryByPrintingOrderAPITestCase(TestCase):
"""测试按生产订单查询送货单 API"""
def setUp(self):
self.client = APIClient()
self.merchant = basic_models.Merchant.objects.create(
name="送货查询商户", type=basic_models.MerchantTypeEnum.FACTORY
)
self.other_merchant = basic_models.Merchant.objects.create(
name="其它送货查询商户", type=basic_models.MerchantTypeEnum.FACTORY
)
self.user = User.objects.create_user(
username="delivery_by_order_user", password="testpass123"
)
self.employee = basic_models.Employee.objects.create(
sys_user=self.user,
merchant=self.merchant,
name="送货查询员工",
status=basic_models.EmployeeStatusEnum.ACTIVE,
)
self.customer = basic_models.Customer.objects.create(
merchant=self.merchant,
name="送货查询客户",
created_by=self.employee,
)
self.state = stateflow_models.State.objects.create(name="待送货查询")
self.process = stateflow_models.Process.objects.create(name="送货查询流程")
self.process.replace_nodes([self.state])
self.product = basic_models.Product.objects.create(
merchant=self.merchant,
category=basic_models.ProductCategory.objects.create(
merchant=self.merchant,
name="送货查询分类",
),
name="送货查询产品",
)
self.printing_order = printing_models.PrintingOrder.objects.create(
merchant=self.merchant,
customer=self.customer,
fabric="送货查询面料",
width="150cm",
process=self.process,
created_by=self.user,
external_order_id="EXT-DELIVERY-001",
)
self.printing_job1 = printing_models.PrintingJob.objects.create(
merchant=self.merchant,
printing_order=self.printing_order,
product=self.product,
quantity=100,
unit="米",
created_by=self.user,
)
self.printing_job2 = printing_models.PrintingJob.objects.create(
merchant=self.merchant,
printing_order=self.printing_order,
product=self.product,
quantity=80,
unit="米",
created_by=self.user,
)
self.delivery1 = shipment_models.ShipmentDelivery.objects.create(
merchant=self.merchant,
driver_name="张司机",
vehicle_trip="KD-001",
contact_phone="13800138000",
vehicle_capacity="9.6米厢车",
remark="外部备注A",
internal_remark="内部备注A",
status=shipment_models.ShipmentDeliveryStatus.IN_TRANSIT,
started_at=timezone.datetime(2026, 7, 1, 9, 0, tzinfo=timezone.get_current_timezone()),
created_by=self.user,
)
self.delivery2 = shipment_models.ShipmentDelivery.objects.create(
merchant=self.merchant,
driver_name="李司机",
vehicle_trip="KD-002",
contact_phone="13900139000",
vehicle_capacity="13米高栏",
remark="外部备注B",
internal_remark="内部备注B",
status=shipment_models.ShipmentDeliveryStatus.DELIVERED,
delivered_at=timezone.datetime(2026, 7, 3, 18, 0, tzinfo=timezone.get_current_timezone()),
created_by=self.user,
)
self.shipment1 = shipment_models.Shipment.objects.create(
merchant=self.merchant,
customer=self.customer,
shipment_date="2026-07-01",
delivery=self.delivery1,
created_by=self.user,
)
self.shipment2 = shipment_models.Shipment.objects.create(
merchant=self.merchant,
customer=self.customer,
shipment_date="2026-07-03",
delivery=self.delivery2,
created_by=self.user,
)
self.sales_item1 = shipment_models.SalesItem.objects.create(
merchant=self.merchant,
name="送货销售品1",
quantity=Decimal("10.00"),
unit=shipment_models.UnitChoices.METER,
printing_job_id=self.printing_job1.id,
shipment=self.shipment1,
customer_id=self.customer.id,
created_by=self.user,
)
self.sales_item2 = shipment_models.SalesItem.objects.create(
merchant=self.merchant,
name="送货销售品2",
quantity=Decimal("20.00"),
unit=shipment_models.UnitChoices.METER,
printing_job_id=self.printing_job1.id,
shipment=self.shipment1,
customer_id=self.customer.id,
created_by=self.user,
)
self.sales_item3 = shipment_models.SalesItem.objects.create(
merchant=self.merchant,
name="送货销售品3",
quantity=Decimal("30.00"),
unit=shipment_models.UnitChoices.METER,
printing_job_id=self.printing_job2.id,
shipment=self.shipment2,
customer_id=self.customer.id,
created_by=self.user,
)
other_order = printing_models.PrintingOrder.objects.create(
merchant=self.merchant,
customer=self.customer,
fabric="其它面料",
width="160cm",
process=self.process,
created_by=self.user,
external_order_id="EXT-OTHER-DELIVERY",
)
other_job = printing_models.PrintingJob.objects.create(
merchant=self.merchant,
printing_order=other_order,
product=self.product,
quantity=50,
unit="米",
created_by=self.user,
)
other_delivery = shipment_models.ShipmentDelivery.objects.create(
merchant=self.merchant,
driver_name="王司机",
vehicle_trip="KD-999",
created_by=self.user,
)
other_shipment = shipment_models.Shipment.objects.create(
merchant=self.merchant,
customer=self.customer,
shipment_date="2026-07-04",
delivery=other_delivery,
created_by=self.user,
)
shipment_models.SalesItem.objects.create(
merchant=self.merchant,
name="其它订单销售品",
quantity=Decimal("40.00"),
unit=shipment_models.UnitChoices.METER,
printing_job_id=other_job.id,
shipment=other_shipment,
customer_id=self.customer.id,
created_by=self.user,
)
self.client.force_authenticate(user=self.user)
def test_list_deliveries_by_internal_printing_order_id(self):
resp = self.client.get(
f"/api/v1/shipment/deliveries/by-printing-order/{self.printing_order.id}/"
)
self.assertEqual(resp.status_code, status.HTTP_200_OK)
data = resp.json()
self.assertEqual(data["count"], 2)
ids = {item["id"] for item in data["results"]}
self.assertEqual(ids, {self.delivery1.id, self.delivery2.id})
def test_list_deliveries_by_external_order_id(self):
resp = self.client.get(
"/api/v1/shipment/deliveries/by-printing-order/EXT-DELIVERY-001/"
)
self.assertEqual(resp.status_code, status.HTTP_200_OK)
data = resp.json()
self.assertEqual(data["count"], 2)
self.assertEqual(data["results"][0]["driver_name"], "李司机")
def test_list_deliveries_filters_driver_status_and_time_ranges(self):
resp = self.client.get(
f"/api/v1/shipment/deliveries/by-printing-order/{self.printing_order.id}/"
"?status=2&driver_name=张&vehicle_trip=KD-001&contact_phone=138"
"&vehicle_capacity=9.6&remark=外部备注A&internal_remark=内部备注A"
"&started_at_from=2026-07-01&started_at_to=2026-07-01"
"&shipment_date_from=2026-07-01&shipment_date_to=2026-07-01"
)
self.assertEqual(resp.status_code, status.HTTP_200_OK)
data = resp.json()
self.assertEqual(data["count"], 1)
self.assertEqual(data["results"][0]["id"], self.delivery1.id)
def test_list_deliveries_supports_pagination_and_ordering(self):
resp = self.client.get(
f"/api/v1/shipment/deliveries/by-printing-order/{self.printing_order.id}/"
"?ordering=id&limit=1&offset=1"
)
self.assertEqual(resp.status_code, status.HTTP_200_OK)
data = resp.json()
self.assertEqual(data["count"], 2)
self.assertEqual(len(data["results"]), 1)
self.assertEqual(data["results"][0]["id"], self.delivery2.id)
def test_list_deliveries_duplicate_external_order_id_returns_500(self):
printing_models.PrintingOrder.objects.create(
merchant=self.merchant,
customer=self.customer,
fabric="重复面料1",
width="150cm",
process=self.process,
created_by=self.user,
external_order_id="EXT-DELIVERY-DUP",
)
printing_models.PrintingOrder.objects.create(
merchant=self.merchant,
customer=self.customer,
fabric="重复面料2",
width="150cm",
process=self.process,
created_by=self.user,
external_order_id="EXT-DELIVERY-DUP",
)
resp = self.client.get(
"/api/v1/shipment/deliveries/by-printing-order/EXT-DELIVERY-DUP/"
)
self.assertEqual(resp.status_code, status.HTTP_500_INTERNAL_SERVER_ERROR)
self.assertIn("匹配到多个生产订单", resp.json()["message"])
class ShipmentSalesItemCustomersAPITestCase(TestCase):
"""测试由未出货销售品汇总客户 API"""
@@ -483,6 +804,39 @@ class ShipmentSalesItemCustomersAPITestCase(TestCase):
self.assertEqual(len(data["results"]), 1)
self.assertEqual(data["results"][0]["customer_id"], self.customer2.id)
def test_list_customers_with_unshipped_sales_items_filters_by_customer_name(self):
resp = self.client.get(
"/api/v1/shipment/sales-items/customers/?customer_name=客户A"
)
self.assertEqual(resp.status_code, status.HTTP_200_OK)
data = resp.json()
self.assertEqual(data["count"], 1)
self.assertEqual(data["results"][0]["customer_id"], self.customer1.id)
self.assertEqual(data["results"][0]["unshipped_sales_items_count"], 2)
def test_list_customers_with_unshipped_sales_items_filters_by_missing_customer_name(self):
resp = self.client.get(
"/api/v1/shipment/sales-items/customers/?customer_name=不存在"
)
self.assertEqual(resp.status_code, status.HTTP_200_OK)
data = resp.json()
self.assertEqual(data["count"], 0)
self.assertEqual(data["results"], [])
def test_list_customers_with_unshipped_sales_items_ignores_blank_customer_name(self):
resp = self.client.get(
"/api/v1/shipment/sales-items/customers/?customer_name=++"
)
self.assertEqual(resp.status_code, status.HTTP_200_OK)
data = resp.json()
self.assertEqual(data["count"], 2)
def test_list_customers_with_unshipped_sales_items_unauthenticated(self):
self.client.logout()
@@ -684,6 +1038,141 @@ class SalesItemByCustomerAPITestCase(TestCase):
self.assertEqual(set(result_ids), {self.sales_item1.id, self.sales_item2.id})
self.assertNotIn(other_sales_item.id, result_ids)
def test_get_sales_items_by_customer_group_groups_by_external_order_id_and_name(self):
duplicate_sales_item = shipment_models.SalesItem.objects.create(
merchant=self.merchant,
name="销售品1",
quantity=Decimal("11.00"),
unit=shipment_models.UnitChoices.METER,
printing_job_id=self.printing_job.id,
customer_id=self.customer.id,
created_by=self.user,
)
resp = self.client.get(
f"/api/v1/shipment/sales-items/by-customer/{self.customer.id}/group/"
)
self.assertEqual(resp.status_code, status.HTTP_200_OK)
data = resp.json()
self.assertEqual(data["count"], 1)
self.assertEqual(len(data["results"]), 1)
external_group = data["results"][0]
self.assertEqual(external_group["external_order_id"], "EXT-CUST-001")
self.assertEqual(external_group["count"], 3)
by_name = {group["name"]: group for group in external_group["name_groups"]}
self.assertEqual(by_name["销售品1"]["count"], 2)
self.assertEqual(by_name["销售品2"]["count"], 1)
self.assertEqual(
{item["id"] for item in by_name["销售品1"]["items"]},
{self.sales_item1.id, duplicate_sales_item.id},
)
def test_get_sales_items_by_customer_group_paginates_external_order_id_groups_with_null_last(self):
other_printing_order = printing_models.PrintingOrder.objects.create(
merchant=self.merchant,
customer=self.customer,
fabric="其它面料",
width="160cm",
process=self.process,
created_by=self.user,
external_order_id="EXT-CUST-OTHER",
)
other_printing_job = printing_models.PrintingJob.objects.create(
merchant=self.merchant,
printing_order=other_printing_order,
product=self.product,
quantity=50,
unit="米",
created_by=self.user,
)
shipment_models.SalesItem.objects.create(
merchant=self.merchant,
name="其它外部订单销售品",
quantity=Decimal("66.00"),
unit=shipment_models.UnitChoices.METER,
printing_job_id=other_printing_job.id,
customer_id=self.customer.id,
created_by=self.user,
)
shipment_models.SalesItem.objects.create(
merchant=self.merchant,
name="无外部订单销售品",
quantity=Decimal("77.00"),
unit=shipment_models.UnitChoices.METER,
customer_id=self.customer.id,
created_by=self.user,
)
first_page = self.client.get(
f"/api/v1/shipment/sales-items/by-customer/{self.customer.id}/group/"
"?limit=1&offset=0"
)
second_page = self.client.get(
f"/api/v1/shipment/sales-items/by-customer/{self.customer.id}/group/"
"?limit=1&offset=1"
)
third_page = self.client.get(
f"/api/v1/shipment/sales-items/by-customer/{self.customer.id}/group/"
"?limit=1&offset=2"
)
self.assertEqual(first_page.status_code, status.HTTP_200_OK)
self.assertEqual(second_page.status_code, status.HTTP_200_OK)
self.assertEqual(third_page.status_code, status.HTTP_200_OK)
self.assertEqual(first_page.json()["count"], 3)
self.assertEqual(
first_page.json()["results"][0]["external_order_id"], "EXT-CUST-001"
)
self.assertEqual(
second_page.json()["results"][0]["external_order_id"], "EXT-CUST-OTHER"
)
self.assertIsNone(third_page.json()["results"][0]["external_order_id"])
def test_get_sales_items_by_customer_group_supports_external_order_id_filter(self):
other_printing_order = printing_models.PrintingOrder.objects.create(
merchant=self.merchant,
customer=self.customer,
fabric="其它面料",
width="160cm",
process=self.process,
created_by=self.user,
external_order_id="EXT-CUST-OTHER",
)
other_printing_job = printing_models.PrintingJob.objects.create(
merchant=self.merchant,
printing_order=other_printing_order,
product=self.product,
quantity=50,
unit="米",
created_by=self.user,
)
other_sales_item = shipment_models.SalesItem.objects.create(
merchant=self.merchant,
name="其它外部订单销售品",
quantity=Decimal("66.00"),
unit=shipment_models.UnitChoices.METER,
printing_job_id=other_printing_job.id,
customer_id=self.customer.id,
created_by=self.user,
)
resp = self.client.get(
f"/api/v1/shipment/sales-items/by-customer/{self.customer.id}/group/"
"?external_order_id=EXT-CUST-OTHER"
)
self.assertEqual(resp.status_code, status.HTTP_200_OK)
data = resp.json()
self.assertEqual(data["count"], 1)
self.assertEqual(data["results"][0]["external_order_id"], "EXT-CUST-OTHER")
self.assertEqual(
data["results"][0]["name_groups"][0]["items"][0]["id"],
other_sales_item.id,
)
def test_get_sales_items_by_customer_not_found(self):
resp = self.client.get("/api/v1/shipment/sales-items/by-customer/99999/")
@@ -1283,7 +1772,9 @@ class ShipmentCreateAPITestCase(TestCase):
"address": "杭州市测试路 1 号",
"contact_name": "张三",
"contact_phone": "13800138000",
"area": "华东",
"area": "华东" * 25,
"coordinates": "120.1551,30.2741",
"extra": {"source": "customer_address", "tags": ["snapshot"]},
"remark": "测试备注",
"sales_items": [self.sales_item1.id, self.sales_item2.id],
}
@@ -1301,7 +1792,9 @@ class ShipmentCreateAPITestCase(TestCase):
self.assertEqual(result["address"], "杭州市测试路 1 号")
self.assertEqual(result["contact_name"], "张三")
self.assertEqual(result["contact_phone"], "13800138000")
self.assertEqual(result.get("area", ""), "华东")
self.assertEqual(result.get("area", ""), "华东" * 25)
self.assertEqual(result["coordinates"], "120.1551,30.2741")
self.assertEqual(result["extra"], {"source": "customer_address", "tags": ["snapshot"]})
self.assertEqual(result["remark"], "测试备注")
self.assertEqual(result["status"], shipment_models.ShipmentStatus.DRAFT)
self.assertEqual(result["status_display"], "草稿(未发布)")
@@ -1314,6 +1807,105 @@ class ShipmentCreateAPITestCase(TestCase):
self.assertEqual(self.sales_item1.shipment_id, result["id"])
self.assertEqual(self.sales_item2.shipment_id, result["id"])
def test_create_shipment_with_address_id_keeps_address_snapshot(self):
customer_address = basic_models.CustomerAddress.objects.create(
merchant=self.merchant,
customer=self.customer,
address="客户地址表地址",
contact_name="地址联系人",
contact_phone="13900139000",
area="地址地区",
created_by=self.employee,
)
data = {
"customer": self.customer.id,
"address_id": customer_address.id,
"shipment_date": "2026-01-14",
"address": "出货单快照地址",
"contact_name": "快照联系人",
"contact_phone": "13800138000",
"area": "快照地区",
"coordinates": "121.0000,31.0000",
"extra": {"floor": "3F"},
"sales_items": [self.sales_item1.id, self.sales_item2.id],
}
response = self.client.post("/api/v1/shipment/shipments/", data, format="json")
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
result = response.json()
self.assertEqual(result["address_id"], customer_address.id)
self.assertEqual(result["address"], "出货单快照地址")
self.assertEqual(result["contact_name"], "快照联系人")
self.assertEqual(result["contact_phone"], "13800138000")
self.assertEqual(result["area"], "快照地区")
self.assertEqual(result["coordinates"], "121.0000,31.0000")
self.assertEqual(result["extra"], {"floor": "3F"})
shipment = shipment_models.Shipment.objects.get(id=result["id"])
self.assertEqual(shipment.customer_address_id, customer_address.id)
self.assertEqual(shipment.coordinates, "121.0000,31.0000")
self.assertEqual(shipment.extra, {"floor": "3F"})
def test_create_shipment_accepts_status(self):
data = {
"customer": self.customer.id,
"shipment_date": "2026-01-14",
"status": shipment_models.ShipmentStatus.APPROVED,
}
response = self.client.post("/api/v1/shipment/shipments/", data, format="json")
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
result = response.json()
self.assertEqual(result["status"], shipment_models.ShipmentStatus.APPROVED)
self.assertEqual(result["status_display"], "已审核")
shipment = shipment_models.Shipment.objects.get(id=result["id"])
self.assertEqual(shipment.status, shipment_models.ShipmentStatus.APPROVED)
def test_create_shipment_rejects_mismatched_address_id(self):
other_customer = basic_models.Customer.objects.create(
merchant=self.merchant,
name="其它客户",
)
customer_address = basic_models.CustomerAddress.objects.create(
merchant=self.merchant,
customer=other_customer,
address="其它客户地址",
created_by=self.employee,
)
data = {
"customer": self.customer.id,
"address_id": customer_address.id,
"shipment_date": "2026-01-14",
}
response = self.client.post("/api/v1/shipment/shipments/", data, format="json")
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertIn("客户地址与客户不匹配", response.json()["detail"])
def test_create_shipment_rejects_deleted_address_id(self):
customer_address = basic_models.CustomerAddress.objects.create(
merchant=self.merchant,
customer=self.customer,
address="已删除客户地址",
deleted_at=timezone.now(),
deleted_by=self.employee,
created_by=self.employee,
)
data = {
"customer": self.customer.id,
"address_id": customer_address.id,
"shipment_date": "2026-01-14",
}
response = self.client.post("/api/v1/shipment/shipments/", data, format="json")
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertIn("已删除", response.json()["detail"])
@override_settings(TESTING=False, SHIPMENT_CREATED_WECOM_NOTIFY_ENABLED=True)
def test_create_shipment_enqueues_wecom_notification_task(self):
"""测试创建出货单后投递企业微信通知任务"""
@@ -1387,8 +1979,8 @@ class ShipmentCreateAPITestCase(TestCase):
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertIn("已关联", response.json()["detail"])
def test_create_shipment_rejects_sales_items_from_different_printing_orders(self):
"""测试销售品来自不同生产订单时拒绝创建"""
def test_create_shipment_allows_sales_items_from_different_printing_orders(self):
"""测试销售品可以来自不同生产订单"""
data = {
"customer": self.customer.id,
"shipment_date": "2026-01-14",
@@ -1397,8 +1989,14 @@ class ShipmentCreateAPITestCase(TestCase):
response = self.client.post("/api/v1/shipment/shipments/", data, format="json")
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertIn("同一个生产订单", response.json()["detail"])
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
result = response.json()
self.assertEqual(result["items_count"], 2)
self.sales_item1.refresh_from_db()
self.sales_item_other_order.refresh_from_db()
self.assertEqual(self.sales_item1.shipment_id, result["id"])
self.assertEqual(self.sales_item_other_order.shipment_id, result["id"])
def test_create_shipment_rejects_sales_item_without_printing_job(self):
"""测试销售品缺少生产任务时拒绝创建"""
@@ -1846,6 +2444,8 @@ class ShipmentQueryAPITestCase(TestCase):
self.assertEqual(result["id"], self.shipment1.id)
self.assertIn("area", result)
self.assertEqual(result["area"], "A1")
self.assertIn("coordinates", result)
self.assertIn("extra", result)
self.assertEqual(result["status"], shipment_models.ShipmentStatus.DRAFT)
self.assertEqual(result["status_display"], "草稿(未发布)")
self.assertIn("sales_items", result)
@@ -1865,6 +2465,8 @@ class ShipmentQueryAPITestCase(TestCase):
"address": "宁波市滨海路 9 号",
"contact_name": "王五",
"contact_phone": "13700137000",
"coordinates": "120.2000,30.3000",
"extra": {"dock": "A"},
},
format="json",
)
@@ -1875,12 +2477,16 @@ class ShipmentQueryAPITestCase(TestCase):
self.assertEqual(result["address"], "宁波市滨海路 9 号")
self.assertEqual(result["contact_name"], "王五")
self.assertEqual(result["contact_phone"], "13700137000")
self.assertEqual(result["coordinates"], "120.2000,30.3000")
self.assertEqual(result["extra"], {"dock": "A"})
self.shipment1.refresh_from_db()
self.assertEqual(getattr(self.shipment1, "area", ""), "更新地区")
self.assertEqual(self.shipment1.address, "宁波市滨海路 9 号")
self.assertEqual(self.shipment1.contact_name, "王五")
self.assertEqual(self.shipment1.contact_phone, "13700137000")
self.assertEqual(self.shipment1.coordinates, "120.2000,30.3000")
self.assertEqual(self.shipment1.extra, {"dock": "A"})
def test_patch_shipment_allows_approved_shipment_without_delivery(self):
"""
@@ -1911,6 +2517,24 @@ class ShipmentQueryAPITestCase(TestCase):
self.shipment1.refresh_from_db()
self.assertEqual(self.shipment1.area, "审核后可修改")
def test_patch_shipment_allows_cancelled_shipment_without_delivery(self):
self.shipment1.status = shipment_models.ShipmentStatus.CANCELLED
self.shipment1.save(update_fields=["status", "updated_at"])
resp = self.client.patch(
f"/api/v1/shipment/shipments/{self.shipment1.id}/",
data={"area": "取消后可修改"},
format="json",
)
self.assertEqual(resp.status_code, status.HTTP_200_OK)
self.assertEqual(resp.json()["area"], "取消后可修改")
self.assertEqual(resp.json()["status"], shipment_models.ShipmentStatus.CANCELLED)
self.shipment1.refresh_from_db()
self.assertEqual(self.shipment1.area, "取消后可修改")
self.assertEqual(self.shipment1.status, shipment_models.ShipmentStatus.CANCELLED)
def test_patch_shipment_rejects_when_bound_to_delivery(self):
delivery = shipment_models.ShipmentDelivery.objects.create(
merchant=self.merchant1,

View File

@@ -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):
"""
手动创建销售品

View File

@@ -402,6 +402,25 @@ class PrintingOrderWithoutSalesOrderAPITest(TestCase):
self.assertNotIn(self.active_bound_order.id, result_ids)
self.assertNotIn(self.other_customer_order.id, result_ids)
def test_list_orders_returns_bianhao_kd(self):
self.unbound_order.external_order_id = 'KD20410611'
self.unbound_order.external_raw = {
'first_record': {
'BianHaoKD': '7.07',
'KdRiQi': '2026-07-06T21:48:58Z',
}
}
self.unbound_order.save(update_fields=['external_order_id', 'external_raw', 'updated_at'])
response = self.client.get(self.url, {'customer_id': self.customer.id})
self.assertEqual(response.status_code, 200)
by_id = {item['id']: item for item in response.data}
self.assertEqual(by_id[self.unbound_order.id]['bianhao_kd'], '7.07')
self.assertEqual(by_id[self.unbound_order.id]['kd_riqi'], '2026-07-06T21:48:58Z')
self.assertIsNone(by_id[self.legacy_unbound_order.id]['bianhao_kd'])
self.assertIsNone(by_id[self.legacy_unbound_order.id]['kd_riqi'])
def test_customer_id_is_required(self):
response = self.client.get(self.url)
self.assertEqual(response.status_code, 400)

View File

@@ -21,6 +21,8 @@ from api_v1.tasks import (
from api_man.serializers import ProductSerializer
from api_v1.views.printing.serializers import (
PlateOrderListSerializer as PlateOrderListV1Serializer,
resolve_printing_order_bianhao_kd,
resolve_printing_order_kd_riqi,
_serialize_plate_images,
)
from stateflow import models as stateflow_models
@@ -190,6 +192,8 @@ class PrintingOrderWithoutSalesOrderSerializer(serializers.ModelSerializer):
"""未关联非作废销售单的印染订单列表序列化器。"""
customer_name = serializers.CharField(source='customer.name', read_only=True)
bianhao_kd = serializers.SerializerMethodField()
kd_riqi = serializers.SerializerMethodField()
class Meta:
model = printing_models.PrintingOrder
@@ -197,6 +201,8 @@ class PrintingOrderWithoutSalesOrderSerializer(serializers.ModelSerializer):
'id',
'human_id',
'external_order_id',
'bianhao_kd',
'kd_riqi',
'customer',
'customer_name',
'fabric',
@@ -209,6 +215,12 @@ class PrintingOrderWithoutSalesOrderSerializer(serializers.ModelSerializer):
]
read_only_fields = fields
def get_bianhao_kd(self, obj):
return resolve_printing_order_bianhao_kd(obj)
def get_kd_riqi(self, obj):
return resolve_printing_order_kd_riqi(obj)
class PrintingOrderWithoutSalesOrderView(APIView):
"""

View File

@@ -122,6 +122,35 @@ class CustomerAdmin(AdminBase):
return '0 (动态逻辑字段待实现)'
@admin.register(models.CustomerAddress)
class CustomerAddressAdmin(AdminBase):
list_display = (
'customer',
'address',
'contact_name',
'contact_phone',
'area',
'is_default',
'deleted_at',
)
list_filter = ('is_default', 'deleted_at', 'area')
search_fields = (
'customer__name',
'address',
'contact_name',
'contact_phone',
'area',
)
def get_queryset(self, request):
qs = super().get_queryset(request).select_related('customer')
customer_qs = CustomerVisibilityService.filter_customers_for_employee(
models.Customer.objects.all(),
request.user,
)
return qs.filter(customer__in=customer_qs)
@admin.register(models.Employee)
class EmployeeAdmin(AdminBase):
list_display = ('name', 'mobile', 'status', 'position_display', 'sys_user')

View File

@@ -0,0 +1,41 @@
# Generated by Django 5.2.8 on 2026-07-07 12:30
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('basic_info', '0027_employee_wecom_user_id'),
]
operations = [
migrations.CreateModel(
name='CustomerAddress',
fields=[
('created_at', models.DateTimeField(auto_now_add=True, verbose_name='创建时间')),
('updated_at', models.DateTimeField(auto_now=True, verbose_name='更新时间')),
('id', models.BigAutoField(primary_key=True, serialize=False)),
('address', models.CharField(max_length=255, verbose_name='地址')),
('contact_name', models.CharField(blank=True, default='', max_length=100, verbose_name='联系人')),
('contact_phone', models.CharField(blank=True, default='', max_length=50, verbose_name='联系电话')),
('area', models.CharField(blank=True, default='', max_length=100, verbose_name='地区')),
('coordinates', models.CharField(blank=True, help_text='经纬度字符串,格式由调用方决定', max_length=100, null=True, verbose_name='经纬度')),
('is_default', models.BooleanField(default=False, verbose_name='是否默认地址')),
('remark', models.CharField(blank=True, default='', max_length=200, verbose_name='备注')),
('extra', models.JSONField(blank=True, null=True, verbose_name='扩展信息')),
('deleted_at', models.DateTimeField(blank=True, null=True, verbose_name='删除时间')),
('created_by', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, related_name='created_customer_addresses', to='basic_info.employee', verbose_name='创建者')),
('customer', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='addresses', to='basic_info.customer', verbose_name='客户')),
('deleted_by', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='deleted_customer_addresses', to='basic_info.employee', verbose_name='删除者')),
('merchant', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='customer_addresses', to='basic_info.merchant', verbose_name='所属商户')),
],
options={
'verbose_name': '客户地址',
'verbose_name_plural': '客户地址',
'ordering': ['-is_default', '-created_at', '-id'],
'indexes': [models.Index(fields=['merchant', 'customer'], name='basic_info__merchan_d9f31e_idx'), models.Index(fields=['deleted_at'], name='basic_info__deleted_a6a24f_idx'), models.Index(fields=['is_default'], name='basic_info__is_defa_487d27_idx')],
},
),
]

View File

@@ -0,0 +1,12 @@
# Generated by OpenCode on 2026-07-07
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('basic_info', '0028_customeraddress'),
]
operations = []

View File

@@ -450,6 +450,66 @@ class Customer(ModelBase):
]
class CustomerAddress(ModelBase):
id = models.BigAutoField(primary_key=True)
merchant = models.ForeignKey(
'Merchant',
on_delete=models.PROTECT,
related_name='customer_addresses',
verbose_name='所属商户',
)
customer = models.ForeignKey(
'Customer',
on_delete=models.PROTECT,
related_name='addresses',
verbose_name='客户',
)
address = models.CharField(max_length=255, verbose_name='地址')
contact_name = models.CharField(max_length=100, blank=True, default='', verbose_name='联系人')
contact_phone = models.CharField(max_length=50, blank=True, default='', verbose_name='联系电话')
area = models.CharField(max_length=100, blank=True, default='', verbose_name='地区')
coordinates = models.CharField(
max_length=100,
null=True,
blank=True,
verbose_name='经纬度',
help_text='经纬度字符串,格式由调用方决定',
)
is_default = models.BooleanField(default=False, verbose_name='是否默认地址')
remark = models.CharField(max_length=200, blank=True, default='', verbose_name='备注')
extra = models.JSONField(null=True, blank=True, verbose_name='扩展信息')
created_by = models.ForeignKey(
'Employee',
on_delete=models.PROTECT,
related_name='created_customer_addresses',
null=True,
blank=True,
verbose_name='创建者',
)
deleted_at = models.DateTimeField(null=True, blank=True, verbose_name='删除时间')
deleted_by = models.ForeignKey(
'Employee',
on_delete=models.SET_NULL,
related_name='deleted_customer_addresses',
null=True,
blank=True,
verbose_name='删除者',
)
def __str__(self):
return f'{self.customer.name} - {self.address}'
class Meta:
verbose_name = '客户地址'
verbose_name_plural = '客户地址'
ordering = ['-is_default', '-created_at', '-id']
indexes = [
models.Index(fields=['merchant', 'customer']),
models.Index(fields=['deleted_at']),
models.Index(fields=['is_default']),
]
class Employee(ModelBase):
id = models.BigAutoField(primary_key=True)
merchant = models.ForeignKey('Merchant', on_delete=models.PROTECT, related_name='employees', verbose_name='所属商户')

View File

@@ -0,0 +1,224 @@
# API v1 Customer Address API
## Scope
客户地址 API 用于维护客户的一对多地址资料。地址归属 `basic_info.Customer`,并通过 `merchant` 做商户隔离。
所有接口需要登录。普通员工只能访问自己可见客户的地址;拥有 `basic_info.view_all_customers` 权限的员工可以访问本商户全部客户地址;superuser 可以访问全部数据。
## Data Model
| Field | Type | Description |
| --- | --- | --- |
| `id` | integer | 客户地址 ID |
| `merchant` | integer | 所属商户 ID,创建时由后端根据客户自动写入 |
| `merchant_name` | string | 所属商户名称,只读 |
| `customer` | integer | 客户 ID |
| `customer_name` | string | 客户名称,只读 |
| `address` | string | 地址 |
| `contact_name` | string | 联系人,可为空字符串 |
| `contact_phone` | string | 联系电话,可为空字符串 |
| `area` | string | 地区,可为空字符串 |
| `coordinates` | string/null | 经纬度字符串,格式由调用方决定 |
| `is_default` | boolean | 是否默认地址 |
| `remark` | string | 备注,可为空字符串 |
| `extra` | object/null | 扩展 JSON |
| `created_by` | integer/null | 创建员工 ID,只读 |
| `created_by_name` | string/null | 创建员工姓名,只读 |
| `deleted_at` | datetime/null | 软删除时间,只读 |
| `deleted_by` | integer/null | 删除员工 ID,只读 |
| `deleted_by_name` | string/null | 删除员工姓名,只读 |
| `created_at` | datetime | 创建时间,只读 |
| `updated_at` | datetime | 更新时间,只读 |
## Endpoints
| Method | Path | Description |
| --- | --- | --- |
| GET | `/api/v1/customer-addresses/` | 查询客户地址列表 |
| POST | `/api/v1/customer-addresses/` | 创建客户地址 |
| GET | `/api/v1/customer-addresses/{id}/` | 查询客户地址详情 |
| PUT | `/api/v1/customer-addresses/{id}/` | 完整更新客户地址 |
| PATCH | `/api/v1/customer-addresses/{id}/` | 部分更新客户地址 |
| DELETE | `/api/v1/customer-addresses/{id}/` | 软删除客户地址 |
| POST | `/api/v1/customer-address/{id}/set-default/` | 将客户地址设为默认地址 |
## Visibility Rules
普通员工可访问的客户地址必须同时满足:
- 地址所属商户等于当前员工商户。
- 地址所属客户对当前员工可见。
客户可见性规则:
- `customer.created_by == 当前员工`
- 或当前员工在 `customer.visible_employees` 中。
权限例外:
- `basic_info.view_all_customers`:可访问本商户全部客户地址。
- superuser:可访问全部客户地址。
创建地址时,`customer` 也必须在当前用户可访问范围内。`merchant` 不由前端传入,后端使用客户所属商户自动写入。
## Query Parameters
`GET /api/v1/customer-addresses/` 支持以下查询参数:
| Parameter | Description |
| --- | --- |
| `customer` | 按客户 ID 精确过滤 |
| `customer_name` | 按客户名称模糊过滤 |
| `address` | 按地址模糊过滤 |
| `contact_name` | 按联系人模糊过滤 |
| `contact_phone` | 按联系电话模糊过滤 |
| `area` | 按地区模糊过滤 |
| `is_default` | 按默认地址过滤,支持 `true/false/1/0/yes/no` |
| `include_deleted` | 是否包含软删除记录,支持 `true/false/1/0/yes/no` |
| `only_deleted` | 是否只查询软删除记录,支持 `true/false/1/0/yes/no` |
| `search` | 对客户名称、地址、联系人、电话、地区、备注做模糊搜索 |
| `ordering` | 排序字段,支持 `id`、`created_at`、`updated_at`、`is_default` 及其 `-` 倒序形式 |
| `limit` | 分页数量 |
| `offset` | 分页偏移 |
默认行为:
- 不传 `include_deleted` 和 `only_deleted` 时,只返回未删除地址。
- `only_deleted=true` 优先于 `include_deleted=true`。
## Create
`POST /api/v1/customer-addresses/`
Request body:
```json
{
"customer": 3,
"address": "杭州市测试路 1 号",
"contact_name": "张三",
"contact_phone": "13800138000",
"area": "杭州",
"coordinates": "120.1,30.2",
"is_default": true,
"remark": "默认收货地址",
"extra": {
"source": "manual"
}
}
```
Success response: HTTP 201
```json
{
"id": 10,
"merchant": 1,
"merchant_name": "测试印花厂",
"customer": 3,
"customer_name": "客户A",
"address": "杭州市测试路 1 号",
"contact_name": "张三",
"contact_phone": "13800138000",
"area": "杭州",
"coordinates": "120.1,30.2",
"is_default": true,
"remark": "默认收货地址",
"extra": {
"source": "manual"
},
"created_by": 5,
"created_by_name": "业务员A",
"deleted_at": null,
"deleted_by": null,
"deleted_by_name": null,
"created_at": "2026-07-07T12:00:00Z",
"updated_at": "2026-07-07T12:00:00Z"
}
```
## Update
`PATCH /api/v1/customer-addresses/{id}/`
Example:
```json
{
"address": "杭州市更新路 2 号",
"contact_phone": "13900139000",
"coordinates": null
}
```
Notes:
- 不允许修改 `customer`。
- 不允许修改 `merchant`。
- `created_by`、`deleted_at`、`deleted_by` 为只读字段。
## Default Address
同一客户最多一个未删除默认地址。
以下操作会自动取消同一客户其他未删除地址的默认状态:
- 创建地址时传 `is_default=true`。
- 更新地址时传 `is_default=true`。
- 调用 `set-default` 接口。
`POST /api/v1/customer-address/{id}/set-default/`
Success response: HTTP 200,返回更新后的地址对象。
如果地址已经软删除,返回 HTTP 400。
## Soft Delete
`DELETE /api/v1/customer-addresses/{id}/`
删除是软删除,不会物理删除记录。后端会写入:
- `deleted_at`
- `deleted_by`
- `is_default=false`
Success response: HTTP 204。
查询软删除记录:
```http
GET /api/v1/customer-addresses/?include_deleted=true
GET /api/v1/customer-addresses/?only_deleted=true
```
## Error Cases
| Condition | Status | Notes |
| --- | --- | --- |
| 未登录 | 401 | 全部接口需要登录 |
| 查询不可见地址详情 | 404 | 不暴露不可见数据存在性 |
| 给不可见客户创建地址 | 400 | `customer` 字段校验失败 |
| 修改 `customer` | 400 | 不允许地址跨客户移动 |
| 已删除地址设为默认 | 400 | 通过 `set-default` 接口返回校验错误 |
## Test Coverage
Dedicated tests:
```bash
docker compose exec -T -e DB_HOST=postgres -e DB_PORT=5432 web uv run python manage.py test api_v1.test_customer_address_api --keepdb --noinput
```
Covered behavior:
- 商户隔离和客户可见性。
- `visible_employees` 授权后可见。
- `basic_info.view_all_customers` 可访问本商户全部客户地址。
- 创建地址时自动写入 `merchant` 和 `created_by`。
- 不可见客户创建地址失败。
- 默认地址互斥。
- `set-default` 接口互斥设置默认地址。
- 软删除和 `include_deleted` / `only_deleted` 查询。
- 常用过滤参数。

View File

@@ -0,0 +1,826 @@
# Shipment 模块 API v1 文档
面向前端对接,基于当前代码生成。接口统一前缀为 `/api/v1/`。
## 通用说明
- 认证:所有接口均要求登录认证。
- 商户隔离:普通用户只能访问自己员工所属商户的数据;超级管理员部分接口可跨商户,具体见接口说明。
- 分页:列表接口使用 `limit`、`offset`,分页响应一般为 `{ "count": 0, "next": null, "previous": null, "results": [] }`。
- 错误:业务校验失败通常返回 `400 { "detail": "错误原因" }`;不存在通常返回 `404`。
## 枚举
### 出货单状态 `ShipmentStatus`
| 值 | 含义 |
| --- | --- |
| `1` | 草稿(未发布) |
| `2` | 已发布 |
| `3` | 已取消 |
| `4` | 已驳回 |
| `5` | 已审核 |
### 送货单状态 `ShipmentDeliveryStatus`
| 值 | 含义 |
| --- | --- |
| `1` | 待送货 |
| `2` | 送货中 |
| `3` | 已送达 |
### 销售品单位 `UnitChoices`
| 值 | 含义 |
| --- | --- |
| `1` | 米 |
| `2` | 件 |
| `3` | 码 |
| `4` | 个 |
## 公共响应结构
### Shipment
```json
{
"id": 1,
"merchant_id": 1,
"merchant_name": "测试印花厂",
"customer": 10,
"customer_name": "客户A",
"address_id": 5,
"fabric": "面料信息",
"order_description": "订单描述",
"shipment_date": "2026-01-14",
"address": "杭州市测试路 1 号",
"contact_name": "张三",
"contact_phone": "13800138000",
"area": "华东",
"coordinates": "120.1551,30.2741",
"remark": "备注",
"status": 1,
"status_display": "草稿(未发布)",
"external_id": null,
"geo_coordinates": null,
"extra": {"source": "customer_address"},
"delivery_id": null,
"status_modified_at": null,
"cancelled_by_id": null,
"cancelled_by_name": null,
"approved_by_id": null,
"approved_by_name": null,
"items_count": 2,
"created_by_id": 1,
"created_by_name": "张三",
"external_finished_products_count": 0,
"sales_items": [],
"external_finished_products": [],
"created_at": "2026-01-14T10:00:00Z",
"updated_at": "2026-01-14T10:00:00Z"
}
```
字段说明:
| 字段 | 类型 | 说明 |
| --- | --- | --- |
| `address_id` | integer/null | 关联客户地址 ID,只表示关联关系 |
| `address` | string | 出货单地址快照,由请求体写入 |
| `contact_name` | string | 联系人快照,由请求体写入 |
| `contact_phone` | string | 联系电话快照,由请求体写入 |
| `area` | string | 地区快照,最大 100 字符 |
| `coordinates` | string/null | 经纬度字符串,最大 100 字符 |
| `geo_coordinates` | object/array/null | 历史 Geo 字段,保留兼容老数据 |
| `extra` | object/array/null | 扩展 JSON |
重要行为:传 `address_id` 时,后端只校验并保存关联,不会用 `CustomerAddress` 自动覆盖 `address/contact_name/contact_phone/area/coordinates/extra`。这些快照字段仍以请求体为准。
### SalesItem
```json
{
"id": 1,
"name": "销售品A",
"quantity": "100.00",
"unit": 1,
"unit_display": "米",
"position": "A1-01",
"remark": "备注",
"printing_job_id": 123,
"printing_order_id": 456,
"external_order_id": "KD20441758",
"customer_id": 10,
"customer_name": "客户A",
"shipment_id": null,
"shipment_date": null,
"merge_remark": null,
"created_at": "2026-01-14T10:00:00Z",
"created_by_id": 1,
"created_by_name": "张三"
}
```
详情接口额外包含:
| 字段 | 类型 | 说明 |
| --- | --- | --- |
| `product_image_url` | string/null | 关联生产任务产品主图 URL |
### ShipmentDelivery
```json
{
"id": 1,
"merchant_id": 1,
"merchant_name": "测试印花厂",
"driver_name": "司机A",
"vehicle_trip": "浙A12345",
"contact_phone": "13800138000",
"vehicle_capacity": "4.2米",
"remark": "备注",
"internal_remark": "内部备注",
"shipment_order_ids": [1, 2, 3],
"status": 1,
"status_display": "待送货",
"started_at": null,
"delivered_at": null,
"cancelled_at": null,
"shipments_count": 2,
"shipments": [],
"created_by_id": 1,
"created_by_name": "张三",
"operator_id": null,
"operator_name": null,
"cancelled_by_id": null,
"cancelled_by_name": null,
"created_at": "2026-01-14T10:00:00Z",
"updated_at": "2026-01-14T10:00:00Z"
}
```
`shipments` 内元素为送货单内出货单摘要:
```json
{
"id": 1,
"customer": 10,
"customer_name": "客户A",
"fabric": "面料信息",
"order_description": "订单描述",
"shipment_date": "2026-01-14",
"status": 5,
"status_display": "已审核",
"external_id": null,
"delivery_id": 1
}
```
## 出货单接口
### 查询出货单列表
`GET /api/v1/shipment/shipments/`
查询参数:
| 参数 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| `customer` | integer | 否 | 客户 ID |
| `status` | integer | 否 | 出货单状态 |
| `delivery_id` | integer | 否 | 送货单 ID;空字符串、`null`、`none` 不触发过滤 |
| `delivery_isnull` | boolean | 否 | `true/1/yes` 查未绑定送货单,`false/0/no` 查已绑定送货单 |
| `external_id` | string | 否 | 外部订单号精确匹配 |
| `shipment_date_from` | date | 否 | 出货日期起始,`YYYY-MM-DD` |
| `shipment_date_to` | date | 否 | 出货日期结束,`YYYY-MM-DD` |
| `only_address_null` | boolean | 否 | `true` 查地址为空字符串,`false` 查地址非空 |
| `limit` | integer | 否 | 分页大小 |
| `offset` | integer | 否 | 分页偏移 |
响应:分页 `Shipment[]`。
### 创建出货单
`POST /api/v1/shipment/shipments/`
请求体:
```json
{
"customer": 10,
"address_id": 5,
"shipment_date": "2026-01-14",
"address": "杭州市测试路 1 号",
"contact_name": "张三",
"contact_phone": "13800138000",
"area": "华东",
"coordinates": "120.1551,30.2741",
"extra": {"source": "customer_address"},
"remark": "备注",
"sales_items": [1, 2, 3]
}
```
请求字段:
| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| `customer` | integer | 是 | 客户 ID |
| `address_id` | integer/null | 否 | 客户地址 ID;仅校验和关联 |
| `shipment_date` | date | 是 | 出货日期 |
| `address` | string | 否 | 地址快照,默认 `""`,最大 255 |
| `contact_name` | string | 否 | 联系人快照,默认 `""`,最大 100 |
| `contact_phone` | string | 否 | 联系电话快照,默认 `""`,最大 50 |
| `area` | string | 否 | 地区快照,默认 `""`,最大 100 |
| `coordinates` | string/null | 否 | 经纬度字符串,最大 100 |
| `extra` | JSON/null | 否 | 扩展信息 |
| `remark` | string | 否 | 出货单备注,默认 `""` |
| `sales_items` | integer[] | 否 | 要关联的销售品 ID 列表,默认 `[]`,后端会去重 |
业务规则:
- 用户必须关联商户。
- 客户必须属于当前商户。
- `address_id` 存在时,客户地址必须存在、未软删除、属于当前商户、属于请求中的 `customer`。
- `sales_items` 非空时,销售品必须存在、未删除、未绑定其他出货单、属于当前商户,并且都来自同一个生产订单。
响应:`201 Shipment`。
### 创建外部出货单
`POST /api/v1/shipment/shipments/external/`
用于没有内部销售品、但需要记录外部成品表的出货单。
请求体:
```json
{
"customer": 10,
"shipment_date": "2026-01-14",
"address": "杭州市测试路 1 号",
"contact_name": "张三",
"contact_phone": "13800138000",
"area": "华东",
"coordinates": "120.1551,30.2741",
"extra": {"source": "external"},
"remark": "备注",
"external_id": "EXT-001",
"external_finished_products": [
{
"style_name": "款式A",
"num_of_rolls": 10,
"remark": "成品备注"
}
]
}
```
请求字段:
| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| `customer` | integer | 是 | 客户 ID |
| `shipment_date` | date | 是 | 出货日期 |
| `address` | string | 否 | 地址,最大 255 |
| `contact_name` | string | 否 | 联系人,最大 100 |
| `contact_phone` | string | 否 | 联系电话,最大 50 |
| `area` | string | 否 | 地区,最大 100 |
| `coordinates` | string/null | 否 | 经纬度字符串,最大 100 |
| `extra` | JSON/null | 否 | 扩展信息 |
| `remark` | string | 否 | 备注 |
| `external_id` | string | 是 | 外部订单号,不能为空,最大 120 |
| `external_finished_products` | array | 是 | 外部成品表,不能为空 |
`external_finished_products` 元素:
| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| `style_name` | string | 是 | 款式名,最大 200 |
| `num_of_rolls` | integer | 是 | 卷数,最小 0 |
| `remark` | string/null | 否 | 备注,最大 200 |
响应:`201 Shipment`。
### 获取出货单详情
`GET /api/v1/shipment/shipments/{id}/`
查询参数:
| 参数 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| `status` | integer | 否 | 可选状态过滤;不匹配则返回 404 |
响应:`200 Shipment`。
### 更新出货单
`PATCH /api/v1/shipment/shipments/{id}/`
`PUT /api/v1/shipment/shipments/{id}/`
当前 `PUT` 行为等同 `PATCH`,允许只传部分字段。
请求体:
```json
{
"customer": 10,
"shipment_date": "2026-01-15",
"address": "新地址",
"contact_name": "李四",
"contact_phone": "13900139000",
"area": "华南",
"coordinates": null,
"extra": null,
"remark": "新备注",
"external_id": "EXT-002",
"geo_coordinates": {"lng": 120.1, "lat": 30.2}
}
```
可更新字段:
| 字段 | 类型 | 说明 |
| --- | --- | --- |
| `customer` | integer | 客户 ID |
| `shipment_date` | date | 出货日期 |
| `address` | string | 地址,最大 255 |
| `contact_name` | string | 联系人,最大 100 |
| `contact_phone` | string | 联系电话,最大 50 |
| `area` | string | 地区,最大 100 |
| `coordinates` | string/null | 经纬度字符串;传 `null` 可清空 |
| `extra` | JSON/null | 扩展信息;传 `null` 可清空 |
| `remark` | string | 备注 |
| `external_id` | string/null | 外部订单号;空字符串或 `null` 会清空 |
| `geo_coordinates` | JSON/null | 当前 serializer 接收该字段,但业务更新服务未保存它,前端不建议使用 |
业务规则:
- 已关联送货单的出货单不允许修改业务数据。
- 修改客户时,新客户必须存在且属于同一商户。
响应:`200 Shipment`。
### 修改出货单状态
`PATCH /api/v1/shipment/shipments/{id}/status/`
`PUT /api/v1/shipment/shipments/{id}/status/`
请求体:
```json
{
"status": 5
}
```
响应:`200 Shipment`。
## 送货单接口
### 查询送货单列表
`GET /api/v1/shipment/deliveries/`
查询参数:
| 参数 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| `status` | integer | 否 | 送货单状态 |
| `driver_name` | string | 否 | 司机名模糊匹配 |
| `vehicle_trip` | string | 否 | 车次模糊匹配 |
| `limit` | integer | 否 | 分页大小 |
| `offset` | integer | 否 | 分页偏移 |
响应:分页 `ShipmentDelivery[]`。
### 创建送货单
`POST /api/v1/shipment/deliveries/`
请求体:
```json
{
"driver_name": "司机A",
"vehicle_trip": "浙A12345",
"contact_phone": "13800138000",
"vehicle_capacity": "4.2米",
"remark": "备注",
"internal_remark": "内部备注",
"shipment_order_ids": [3, 2, 1],
"shipments": [1, 2, 3]
}
```
请求字段:
| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| `driver_name` | string | 是 | 司机名,最大 100 |
| `vehicle_trip` | string | 是 | 车次,最大 100 |
| `contact_phone` | string | 否 | 联系电话,默认 `""`,最大 50 |
| `vehicle_capacity` | string | 否 | 车辆容量,默认 `""`,最大 100 |
| `remark` | string | 否 | 备注,默认 `""`,最大 200 |
| `internal_remark` | string | 否 | 内部备注,默认 `""`,最大 200 |
| `shipment_order_ids` | array/null | 否 | 前端自管出货单排序 ID 数组,可为 `null` |
| `shipments` | integer[] | 否 | 要关联的出货单 ID 列表,默认 `[]`,后端会去重 |
响应:`201 ShipmentDelivery`。
### 按生产订单查询送货单
`GET /api/v1/shipment/deliveries/by-printing-order/{printing_order_id}/`
路径参数:
- `printing_order_id` 支持内部 `PrintingOrder.id` 或 `external_order_id`。
- 如果 `external_order_id` 匹配多个生产订单,返回 `500 { "message": "...请改用内部ID查询" }`。
查询参数:
| 参数 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| `status` | integer | 否 | 送货单状态 |
| `driver_name` | string | 否 | 模糊匹配 |
| `vehicle_trip` | string | 否 | 模糊匹配 |
| `contact_phone` | string | 否 | 模糊匹配 |
| `vehicle_capacity` | string | 否 | 模糊匹配 |
| `remark` | string | 否 | 模糊匹配 |
| `internal_remark` | string | 否 | 模糊匹配 |
| `started_at_from` | date/datetime | 否 | 开始送货时间起 |
| `started_at_to` | date/datetime | 否 | 开始送货时间止 |
| `delivered_at_from` | date/datetime | 否 | 送达时间起 |
| `delivered_at_to` | date/datetime | 否 | 送达时间止 |
| `cancelled_at_from` | date/datetime | 否 | 取消时间起 |
| `cancelled_at_to` | date/datetime | 否 | 取消时间止 |
| `created_at_from` | date/datetime | 否 | 创建时间起 |
| `created_at_to` | date/datetime | 否 | 创建时间止 |
| `shipment_date_from` | date | 否 | 关联出货日期起 |
| `shipment_date_to` | date | 否 | 关联出货日期止 |
| `ordering` | string | 否 | 可选 `id/created_at/updated_at/started_at/delivered_at/cancelled_at/status`,支持前缀 `-` |
| `limit` | integer | 否 | 分页大小 |
| `offset` | integer | 否 | 分页偏移 |
响应:分页 `ShipmentDelivery[]`,字段使用专用 DTO,不包含 `cancelled_by_id/cancelled_by_name`。
### 获取送货单详情
`GET /api/v1/shipment/deliveries/{id}/`
响应:`200 ShipmentDelivery`。
### 更新送货单
`PATCH /api/v1/shipment/deliveries/{id}/`
`PUT /api/v1/shipment/deliveries/{id}/`
当前 `PUT` 行为等同 `PATCH`。
请求体:
```json
{
"driver_name": "司机B",
"vehicle_trip": "浙B12345",
"contact_phone": "13900139000",
"vehicle_capacity": "9.6米",
"remark": "新备注",
"internal_remark": "新内部备注",
"shipment_order_ids": [2, 1],
"shipments": [1, 2]
}
```
可更新字段:
| 字段 | 类型 | 说明 |
| --- | --- | --- |
| `driver_name` | string | 司机名,最大 100,不允许空字符串 |
| `vehicle_trip` | string | 车次,最大 100,不允许空字符串 |
| `contact_phone` | string | 联系电话,最大 50 |
| `vehicle_capacity` | string | 车辆容量,最大 100 |
| `remark` | string | 备注,最大 200 |
| `internal_remark` | string | 内部备注,最大 200 |
| `shipment_order_ids` | array/null | 前端自管排序 ID 数组,传入即更新 |
| `shipments` | integer[] | 传入即替换当前绑定出货单 |
响应:`200 ShipmentDelivery`。
### 删除送货单
`DELETE /api/v1/shipment/deliveries/{id}/`
响应:`204 No Content`。
### 修改送货单状态
`POST /api/v1/shipment/deliveries/{id}/status/`
请求体:
```json
{
"status": 2
}
```
允许状态:`1`、`2`、`3`。
响应:`200 ShipmentDelivery`。
### 取消送货单
`POST /api/v1/shipment/deliveries/{id}/cancel/`
权限:需要 `shipment.cancel_shipmentdelivery`。
响应:`200 ShipmentDelivery`。
### 追加绑定出货单到送货单
`POST /api/v1/shipment/deliveries/{id}/bind-shipments/`
请求体:
```json
{
"shipments": [4, 5]
}
```
请求字段:
| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| `shipments` | integer[] | 是 | 要追加绑定的出货单 ID,不能为空,后端会去重 |
响应:`200 ShipmentDelivery`。
## 销售品接口
### 查询当前可出货客户
`GET /api/v1/shipment/sales-items/customers/`
从未出货销售品反推出客户列表。
查询参数:
| 参数 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| `merchant` | integer | 超级管理员必填 | 超级管理员必须传商户 ID;普通用户忽略 |
| `customer_name` | string | 否 | 客户名称模糊匹配 |
| `limit` | integer | 否 | 分页大小 |
| `offset` | integer | 否 | 分页偏移 |
响应:
```json
{
"count": 1,
"next": null,
"previous": null,
"results": [
{
"customer_id": 10,
"customer_name": "客户A",
"mobile": "13900139000",
"area": "杭州",
"unshipped_sales_items_count": 3
}
]
}
```
### 按客户查询销售品
`GET /api/v1/shipment/sales-items/by-customer/{customer_id}/`
查询参数:
| 参数 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| `include_already_has_shipment` | boolean | 否 | 是否包含已关联出货单销售品,默认 `false`;只有字符串 `true` 会视为真 |
| `external_order_id` | string | 否 | 按生产订单外部订单号过滤 |
| `limit` | integer | 否 | 分页大小 |
| `offset` | integer | 否 | 分页偏移 |
响应:分页 `SalesItem[]`。
### 按客户查询销售品分组
`GET /api/v1/shipment/sales-items/by-customer/{customer_id}/group/`
第一层按 `external_order_id` 分组并分页,第二层按 `name` 分组。
查询参数同“按客户查询销售品”。
响应:
```json
{
"count": 1,
"next": null,
"previous": null,
"results": [
{
"external_order_id": "KD20441758",
"count": 2,
"name_groups": [
{
"name": "销售品A",
"count": 2,
"items": []
}
]
}
]
}
```
排序:`external_order_id = null` 排最后。
### 按生产订单查询销售品
`GET /api/v1/shipment/sales-items/by-printing-order/{printing_order_id}/`
路径参数:
- `printing_order_id` 支持内部 `PrintingOrder.id` 或 `external_order_id`。
- 如果 `external_order_id` 匹配多个生产订单,此接口返回 `400 { "detail": "...请改用内部ID查询" }`。
查询参数:
| 参数 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| `include_already_has_shipment` | boolean | 否 | 是否包含已关联出货单销售品,默认 `false`;只有字符串 `true` 会视为真 |
响应:
```json
{
"count": 2,
"results": []
}
```
`results` 为 `SalesItem[]`,该接口不使用标准分页。
### 按生产订单查询销售品分组
`GET /api/v1/shipment/sales-items/by-printing-order/{printing_order_id}/group/`
按 `printing_job_id` 分组并分页。
查询参数:
| 参数 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| `include_already_has_shipment` | boolean | 否 | 是否包含已关联出货单销售品,默认 `false` |
| `limit` | integer | 否 | 分页大小,作用于分组数量 |
| `offset` | integer | 否 | 分页偏移,作用于分组数量 |
响应:
```json
{
"count": 1,
"next": null,
"previous": null,
"results": [
{
"printing_job_id": 123,
"count": 2,
"items": []
}
]
}
```
### 手动创建销售品
`POST /api/v1/shipment/sales-items/`
请求体:
```json
{
"printing_job_id": 123,
"name": "销售品A",
"quantity": "100.50",
"unit": 1,
"customer_id": 10,
"remark": "备注",
"position": "A1-01",
"merge_remark": {
"merge_type": "merge",
"jobs": [1, 2],
"main_job": 1,
"quantity": "100.50",
"unit": "米",
"job_count": 2
}
}
```
请求字段:
| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| `printing_job_id` | integer | 是 | 生产任务 ID,最小 1 |
| `name` | string | 是 | 销售品名称,最大 200 |
| `quantity` | string | 是 | 数量,最大 20,支持小数 |
| `unit` | integer | 是 | 单位:`1/2/3/4` |
| `customer_id` | integer/null | 否 | 客户 ID;不传时默认从生产订单获取 |
| `remark` | string | 否 | 备注,最大 200 |
| `position` | string | 否 | 货位,最大 200 |
| `merge_remark` | object/null | 否 | 合卷备注 JSON,结构严格校验 |
`merge_remark` 必须只包含这些字段:`merge_type`、`jobs`、`main_job`、`quantity`、`unit`、`job_count`。
响应:`201 SalesItem`。
### 获取销售品详情
`GET /api/v1/shipment/sales-items/{id}/`
响应:`200 SalesItem`,包含 `product_image_url`。
### 更新销售品
`PATCH /api/v1/shipment/sales-items/{id}/`
请求体只能包含以下字段:
```json
{
"quantity": "80.00",
"remark": "新备注",
"position": "B2-01"
}
```
可更新字段:
| 字段 | 类型 | 说明 |
| --- | --- | --- |
| `quantity` | string | 数量,支持小数 |
| `remark` | string | 备注,最大 200 |
| `position` | string | 货位,最大 200 |
如果请求包含其他字段,返回 `400`。
响应:`200 SalesItem`,包含 `product_image_url`。
### 删除销售品
`DELETE /api/v1/shipment/sales-items/{id}/`
权限:需要 `shipment.soft_delete_salesitem`。
响应:
```json
{
"detail": "销售品已标记为删除"
}
```
### 重建销售品
`POST /api/v1/shipment/sales-items/{id}/rebuild/`
仅销售品创建者可执行。
请求体:
```json
{
"new_printing_job_id": 456,
"quantity": "50.00"
}
```
请求字段:
| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| `new_printing_job_id` | integer | 是 | 新生产任务 ID,最小 1 |
| `quantity` | string | 否 | 新数量;不传则沿用原销售品数量 |
响应:`200 SalesItem`。
## 前端重点注意
- 创建出货单时,`address_id` 不会自动填充地址快照。前端若选择客户地址,需要同时把地址表中的 `address/contact_name/contact_phone/area/coordinates/extra` 放入创建请求。
- `coordinates` 是新的字符串字段,前端不要再把新数据写到 `geo_coordinates`。
- `geo_coordinates` 是历史兼容字段,读取时可能存在旧值,但更新接口目前不保存它。
- `area` 现在最大 100 字符,可以直接承载客户地址的 `area`。
- `extra` 可用于承载客户地址扩展信息,允许对象、数组或 `null`。
- 更新出货单时,传 `coordinates: null` 或 `extra: null` 可以清空对应字段;不传则不修改。
- 按生产订单查送货单的 `external_order_id` 多匹配错误返回 `500 + message`;按生产订单查销售品的同类错误返回 `400 + detail`。

View File

@@ -0,0 +1,198 @@
# API v1 Shipment Deliveries By Printing Order
## Scope
该接口用于按生产订单查询相关送货单,也就是司机/车次相关的送货数据。
查询链路:
```text
PrintingOrder -> PrintingJob -> SalesItem -> Shipment -> ShipmentDelivery
```
只返回已经关联到送货单的出货数据。没有绑定送货单的 `Shipment` 不会出现在结果中。
## Endpoint
```http
GET /api/v1/shipment/deliveries/by-printing-order/{printing_order_id}/
```
需要登录。
## Path Parameters
| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| `printing_order_id` | string | yes | 支持生产订单内部 ID,也支持 `PrintingOrder.external_order_id` |
解析规则:
- 如果 `printing_order_id` 是纯数字,优先按内部 `PrintingOrder.id` 查询。
- 如果内部 ID 未命中,再按 `external_order_id` 查询。
- 如果不是纯数字,按 `external_order_id` 查询。
- 如果 `external_order_id` 匹配多个生产订单,返回 HTTP 500 和明确 `message`。
## Query Parameters
| Parameter | Description |
| --- | --- |
| `status` | 送货单状态精确过滤 |
| `driver_name` | 司机名模糊过滤 |
| `vehicle_trip` | 车次模糊过滤 |
| `contact_phone` | 联系电话模糊过滤 |
| `vehicle_capacity` | 车辆容量模糊过滤 |
| `remark` | 备注模糊过滤 |
| `internal_remark` | 内部备注模糊过滤 |
| `started_at_from` | 开始送货时间起始 |
| `started_at_to` | 开始送货时间截止 |
| `delivered_at_from` | 送达时间起始 |
| `delivered_at_to` | 送达时间截止 |
| `cancelled_at_from` | 取消时间起始 |
| `cancelled_at_to` | 取消时间截止 |
| `created_at_from` | 送货单创建时间起始 |
| `created_at_to` | 送货单创建时间截止 |
| `shipment_date_from` | 关联出货单出货日期起始,格式 `YYYY-MM-DD` |
| `shipment_date_to` | 关联出货单出货日期截止,格式 `YYYY-MM-DD` |
| `ordering` | 排序字段 |
| `limit` | 分页数量 |
| `offset` | 分页偏移 |
时间参数说明:
- `*_at_from` / `*_at_to` 支持日期或 datetime 字符串。
- 如果传日期,例如 `2026-07-01`,会按对应字段的日期部分过滤。
- 如果传 datetime,例如 `2026-07-01T09:00:00+08:00`,会按完整时间过滤。
`ordering` 支持:
```text
id
-id
created_at
-created_at
updated_at
-updated_at
started_at
-started_at
delivered_at
-delivered_at
cancelled_at
-cancelled_at
status
-status
```
默认排序:`-created_at, -id`。
## Response
分页响应。
```json
{
"count": 2,
"next": null,
"previous": null,
"results": [
{
"id": 12,
"merchant_id": 1,
"merchant_name": "测试印花厂",
"driver_name": "张司机",
"vehicle_trip": "KD-001",
"contact_phone": "13800138000",
"vehicle_capacity": "9.6米厢车",
"remark": "外部备注",
"internal_remark": "内部备注",
"shipment_order_ids": [101, 102],
"status": 2,
"status_display": "送货中",
"started_at": "2026-07-01T09:00:00+08:00",
"delivered_at": null,
"cancelled_at": null,
"shipments_count": 2,
"shipments": [
{
"id": 101,
"customer": 3,
"customer_name": "客户A",
"fabric": "全棉",
"order_description": "订单描述",
"shipment_date": "2026-07-01",
"status": 5,
"status_display": "已审核",
"external_id": null,
"delivery_id": 12
}
],
"created_by_id": 5,
"created_by_name": "业务员A",
"operator_id": null,
"operator_name": null,
"created_at": "2026-07-01T08:00:00+08:00",
"updated_at": "2026-07-01T09:00:00+08:00"
}
]
}
```
## Examples
按内部生产订单 ID 查询:
```http
GET /api/v1/shipment/deliveries/by-printing-order/9986/
```
按外部生产订单号查询:
```http
GET /api/v1/shipment/deliveries/by-printing-order/KD20441758/
```
按司机、状态和出货日期过滤:
```http
GET /api/v1/shipment/deliveries/by-printing-order/KD20441758/?status=2&driver_name=张&shipment_date_from=2026-07-01&shipment_date_to=2026-07-31
```
分页和排序:
```http
GET /api/v1/shipment/deliveries/by-printing-order/KD20441758/?ordering=id&limit=20&offset=0
```
## Error Responses
| Condition | Status | Response |
| --- | --- | --- |
| 未登录 | 401 | 全局认证错误结构 |
| 当前商户下找不到生产订单 | 404 | `{ "detail": "生产订单 {printing_order_id} 不存在" }` |
| `external_order_id` 匹配多个生产订单 | 500 | `{ "message": "external_order_id ... 匹配到多个生产订单,请改用内部ID查询" }` |
## Notes
- 普通用户只能查询自己员工所属商户下的生产订单和送货单。
- superuser 不受商户限制。
- 一个送货单可能通过多个销售品命中同一个生产订单,接口会对送货单去重。
- 查询只统计未软删除的 `SalesItem`。
- 响应使用专用 DTO:`ShipmentDeliveryByPrintingOrderSerializer`,后续可以独立调整字段,不影响普通送货单列表接口。
## Test Coverage
Dedicated tests:
```bash
docker compose exec -T -e DB_HOST=postgres -e DB_PORT=5432 web uv run python manage.py test api_v1.views.shipment.test_api.ShipmentDeliveryByPrintingOrderAPITestCase --keepdb --noinput
```
Covered behavior:
- 按内部 `PrintingOrder.id` 查询。
- 按 `external_order_id` 查询。
- 司机、状态、车次、电话、车辆容量、备注、内部备注过滤。
- 开始送货时间和出货日期范围过滤。
- 分页和排序。
- 送货单去重。
- `external_order_id` 多匹配返回 HTTP 500 和明确 `message`。

BIN
flower-app_latest.tar.gz Normal file

Binary file not shown.

View File

@@ -1,5 +1,6 @@
from django.conf import settings
from django.core.cache import cache
from django.utils import timezone
from rest_framework.permissions import AllowAny
from rest_framework.response import Response
from rest_framework.views import APIView
@@ -12,7 +13,19 @@ def _coerce_version_part(value) -> int:
return max(0, int(value or 0))
def build_app_version_payload(*, major, minor, build, download_url: str) -> dict:
def _coerce_publish_date(value) -> str:
return str(value or timezone.localdate().isoformat()).strip()
def build_app_version_payload(
*,
major,
minor,
build,
download_url: str,
force=False,
publish_date=None,
) -> dict:
return {
"latest_version": {
"major": _coerce_version_part(major),
@@ -20,6 +33,8 @@ def build_app_version_payload(*, major, minor, build, download_url: str) -> dict
"build": _coerce_version_part(build),
},
"download_url": str(download_url or "").strip(),
"force": bool(force),
"publish_date": _coerce_publish_date(publish_date),
}
@@ -33,6 +48,8 @@ def get_app_version_payload() -> dict:
minor=version["minor"],
build=version["build"],
download_url=cached_payload.get("download_url", ""),
force=cached_payload["force"],
publish_date=cached_payload["publish_date"],
)
except (KeyError, TypeError, ValueError):
pass
@@ -42,15 +59,27 @@ def get_app_version_payload() -> dict:
minor=getattr(settings, "APP_LATEST_VERSION_MINOR", 0),
build=getattr(settings, "APP_LATEST_VERSION_BUILD", 0),
download_url=getattr(settings, "APP_DOWNLOAD_URL", ""),
force=getattr(settings, "APP_FORCE_UPDATE", False),
publish_date=getattr(settings, "APP_PUBLISH_DATE", None),
)
def set_cached_app_version_payload(*, major, minor, build, download_url: str) -> dict:
def set_cached_app_version_payload(
*,
major,
minor,
build,
download_url: str,
force=False,
publish_date=None,
) -> dict:
payload = build_app_version_payload(
major=major,
minor=minor,
build=build,
download_url=download_url,
force=force,
publish_date=publish_date,
)
cache.set(APP_VERSION_CACHE_KEY, payload, timeout=None)
return payload

View File

@@ -117,6 +117,8 @@ APP_LATEST_VERSION_MAJOR = env.int('APP_LATEST_VERSION_MAJOR', default=0)
APP_LATEST_VERSION_MINOR = env.int('APP_LATEST_VERSION_MINOR', default=0)
APP_LATEST_VERSION_BUILD = env.int('APP_LATEST_VERSION_BUILD', default=0)
APP_DOWNLOAD_URL = env('APP_DOWNLOAD_URL', default='')
APP_FORCE_UPDATE = env.bool('APP_FORCE_UPDATE', default=False)
APP_PUBLISH_DATE = env('APP_PUBLISH_DATE', default='')
# 定时财务同步客户列表(临时需求,直接写死不走 env)
FINANCE_SYNC_CUSTOMER_NAMES: list[str] = [

View File

@@ -3,6 +3,7 @@ from io import StringIO
from django.core.cache import cache
from django.core.management import call_command
from django.test import TestCase, override_settings
from django.utils import timezone
from rest_framework.test import APIClient
from flower.app_version import APP_VERSION_CACHE_KEY
@@ -21,6 +22,8 @@ class AppVersionAPITest(TestCase):
APP_LATEST_VERSION_MINOR=2,
APP_LATEST_VERSION_BUILD=345,
APP_DOWNLOAD_URL="https://example.com/app.apk",
APP_FORCE_UPDATE=True,
APP_PUBLISH_DATE="2026-07-08",
)
def test_app_version_api_returns_settings_payload_without_auth(self):
response = self.client.get("/api/app-version/")
@@ -35,10 +38,12 @@ class AppVersionAPITest(TestCase):
"build": 345,
},
"download_url": "https://example.com/app.apk",
"force": True,
"publish_date": "2026-07-08",
},
)
def test_set_app_version_command_updates_cached_api_payload(self):
def test_set_app_version_command_updates_cached_api_payload_with_defaults(self):
output = StringIO()
call_command(
"set_app_version",
@@ -58,4 +63,32 @@ class AppVersionAPITest(TestCase):
self.assertEqual(response.status_code, 200)
self.assertEqual(response.data["latest_version"], {"major": 2, "minor": 5, "build": 1001})
self.assertEqual(response.data["download_url"], "https://example.com/latest.apk")
self.assertEqual(response.data["force"], False)
self.assertEqual(response.data["publish_date"], timezone.localdate().isoformat())
self.assertIn("'build': 1001", output.getvalue())
def test_set_app_version_command_accepts_force_and_publish_date(self):
output = StringIO()
call_command(
"set_app_version",
"--major",
"2",
"--minor",
"6",
"--build",
"1002",
"--download-url",
"https://example.com/force.apk",
"--force",
"--publish-date",
"2026-07-01",
stdout=output,
)
response = self.client.get("/api/app-version/")
self.assertEqual(response.status_code, 200)
self.assertEqual(response.data["latest_version"], {"major": 2, "minor": 6, "build": 1002})
self.assertEqual(response.data["download_url"], "https://example.com/force.apk")
self.assertEqual(response.data["force"], True)
self.assertEqual(response.data["publish_date"], "2026-07-01")

View File

@@ -0,0 +1,18 @@
# Generated by Django 5.2.8 on 2026-07-08 11:57
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('printing', '0039_printingjob_sub_id'),
]
operations = [
migrations.AddField(
model_name='printingorder',
name='kd_riqi',
field=models.DateTimeField(blank=True, db_index=True, null=True, verbose_name='外部开单日期时间'),
),
]

View File

@@ -388,6 +388,12 @@ class PrintingOrder(ModelBase):
null=True,
verbose_name='外部员工名',
)
kd_riqi = models.DateTimeField(
null=True,
blank=True,
db_index=True,
verbose_name='外部开单日期时间',
)
external_raw = models.JSONField(
default=dict,
blank=True,

View File

@@ -0,0 +1,20 @@
# Generated by Django 5.2.8 on 2026-07-08 05:38
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('basic_info', '0029_customeraddress_coordinates'),
('shipment', '0025_alter_shipmentdelivery_options_and_more'),
]
operations = [
migrations.AddField(
model_name='shipment',
name='customer_address',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='shipments', to='basic_info.customeraddress', verbose_name='客户地址'),
),
]

View File

@@ -0,0 +1,28 @@
# Generated by Django 5.2.8 on 2026-07-08 05:50
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('shipment', '0026_shipment_customer_address'),
]
operations = [
migrations.AddField(
model_name='shipment',
name='coordinates',
field=models.CharField(blank=True, help_text='经纬度字符串,格式由调用方决定', max_length=100, null=True, verbose_name='经纬度'),
),
migrations.AddField(
model_name='shipment',
name='extra',
field=models.JSONField(blank=True, null=True, verbose_name='扩展信息'),
),
migrations.AlterField(
model_name='shipment',
name='area',
field=models.CharField(blank=True, default='', help_text='出货地区(可空字符串)', max_length=100, verbose_name='地区'),
),
]

View File

@@ -149,6 +149,15 @@ class Shipment(ModelBase):
related_name='shipments',
verbose_name='客户'
)
customer_address = models.ForeignKey(
basic_models.CustomerAddress,
on_delete=models.SET_NULL,
null=True,
blank=True,
related_name='shipments',
verbose_name='客户地址',
)
shipment_date = models.DateField(
verbose_name='出货日期',
@@ -177,12 +186,20 @@ class Shipment(ModelBase):
)
area = models.CharField(
max_length=30,
max_length=100,
blank=True,
default='',
verbose_name='地区',
help_text='出货地区(可空字符串)',
)
coordinates = models.CharField(
max_length=100,
null=True,
blank=True,
verbose_name='经纬度',
help_text='经纬度字符串,格式由调用方决定',
)
remark = models.TextField(
blank=True,
@@ -205,6 +222,12 @@ class Shipment(ModelBase):
help_text='由 Geo 系统返回的坐标信息,结构由调用方决定,后端不作校验',
)
extra = models.JSONField(
null=True,
blank=True,
verbose_name='扩展信息',
)
rejected_sales_item_ids = models.JSONField(
default=list,
blank=True,

View File

@@ -710,8 +710,10 @@ def update_shipment(
contact_name: str | None = None,
contact_phone: str | None = None,
area: str | None = None,
coordinates=UNSET,
remark: str | None = None,
external_id: str | None = None,
extra=UNSET,
) -> Shipment:
"""
更新出货单业务数据。
@@ -743,10 +745,14 @@ def update_shipment(
shipment.contact_phone = contact_phone or ""
if area is not None:
shipment.area = (area or "").strip()
if coordinates is not UNSET:
shipment.coordinates = coordinates or None
if remark is not None:
shipment.remark = remark or ""
if external_id is not None:
shipment.external_id = (external_id or "").strip() or None
if extra is not UNSET:
shipment.extra = extra
shipment.save()
return shipment
@@ -759,11 +765,15 @@ def create_shipment(
shipment_date,
sales_item_ids: List[int],
created_by,
address_id: int | None = None,
address: str = "",
contact_name: str = "",
contact_phone: str = "",
remark: str = "",
area: str = "",
coordinates: str | None = None,
extra: dict | list | None = None,
status: int = ShipmentStatus.DRAFT,
) -> Shipment:
"""
创建出货单并关联销售品
@@ -781,7 +791,7 @@ def create_shipment(
Raises:
ValueError: 如果销售品不存在或已被关联到其他出货单
"""
from basic_info.models import Customer
from basic_info.models import Customer, CustomerAddress
# 验证客户存在
try:
@@ -798,6 +808,20 @@ def create_shipment(
if customer.merchant_id != merchant.id:
raise ValueError("无权限为该客户创建出货单")
customer_address = None
if address_id is not None:
try:
customer_address = CustomerAddress.objects.get(id=address_id)
except CustomerAddress.DoesNotExist:
raise ValueError(f"客户地址 {address_id} 不存在")
if customer_address.deleted_at is not None:
raise ValueError(f"客户地址 {address_id} 已删除")
if customer_address.merchant_id != merchant.id:
raise ValueError("无权限使用该客户地址")
if customer_address.customer_id != customer.id:
raise ValueError("客户地址与客户不匹配")
# 验证销售品
if sales_item_ids:
from printing.models import PrintingJob
@@ -844,22 +868,20 @@ def create_shipment(
f"以下销售品关联的生产任务不存在,无法创建出货单: {affected_item_ids}"
)
printing_order_ids = {
printing_job_map[item.printing_job_id] for item in sales_items_list
}
if len(printing_order_ids) > 1:
raise ValueError("出货单中的销售品必须来自同一个生产订单")
# 创建出货单
shipment = Shipment.objects.create(
merchant=merchant,
customer=customer,
customer_address=customer_address,
shipment_date=shipment_date,
address=address or "",
contact_name=contact_name or "",
contact_phone=contact_phone or "",
area=(area or "").strip(),
coordinates=coordinates or None,
remark=remark,
extra=extra,
status=status,
created_by=created_by,
)
@@ -996,6 +1018,8 @@ def create_external_shipment(
contact_phone: str = "",
remark: str = "",
area: str = "",
coordinates: str | None = None,
extra: dict | list | None = None,
) -> Shipment:
"""
创建出货单(external 版),并批量写入外部成品表并关联到出货单。
@@ -1035,7 +1059,9 @@ def create_external_shipment(
contact_name=contact_name or "",
contact_phone=contact_phone or "",
area=(area or "").strip(),
coordinates=coordinates or None,
remark=remark,
extra=extra,
created_by=created_by,
external_id=external_id,
)