1
0
forked from erp-dev/erp

feat: batch add parameters

This commit is contained in:
2026-01-07 16:33:33 +08:00
parent 5b07332015
commit beaa93c3cb
9 changed files with 722 additions and 15 deletions

View File

@@ -1654,3 +1654,226 @@ class PrintingOrderBatchAdvanceRecordsAPITest(TestCase):
self.client.logout()
response = self.client.get(f'/api/v2/printing-orders/{self.printing_order.id}/batch-advance-records/')
self.assertEqual(response.status_code, 401)
class PrintingJobBatchAddParametersAPITest(TestCase):
"""测试批量补充工艺参数 API"""
def setUp(self):
self.client = APIClient()
self.merchant = basic_models.Merchant.objects.create(
name='测试工厂',
type=basic_models.MerchantTypeEnum.FACTORY,
)
self.user = get_user_model().objects.create_user(username='factory_user', password='pass12345')
self.employee = basic_models.Employee.objects.create(
merchant=self.merchant,
name='工厂员工',
sys_user=self.user
)
self.client.force_authenticate(user=self.user)
# 创建客户
self.customer = basic_models.Customer.objects.create(
merchant=self.merchant,
name='测试客户'
)
# 创建产品类别和产品
self.category = basic_models.ProductCategory.objects.create(
merchant=self.merchant,
name='测试类别'
)
self.product = basic_models.Product.objects.create(
merchant=self.merchant,
name='测试产品',
category=self.category,
unit=basic_models.ProductUnitEnum.METER
)
# 创建流程状态
self.state1 = stateflow_models.State.objects.create(name='染色', description='染色工序')
self.state2 = stateflow_models.State.objects.create(name='整理', description='整理工序')
# 创建流程
self.process = stateflow_models.Process.objects.create(name='印染流程')
stateflow_models.ProcessNode.objects.create(process=self.process, state=self.state1, order=1)
stateflow_models.ProcessNode.objects.create(process=self.process, state=self.state2, order=2)
# 创建印染订单
self.printing_order = printing_models.PrintingOrder.objects.create(
customer=self.customer,
fabric='测试面料',
width='150cm',
process=self.process
)
# 创建印染明细并绑定流程实例
self.job1 = printing_models.PrintingJob.objects.create(
printing_order=self.printing_order,
product=self.product,
quantity=100,
unit=''
)
self.job2 = printing_models.PrintingJob.objects.create(
printing_order=self.printing_order,
product=self.product,
quantity=200,
unit=''
)
# 创建业务对象并推进到 state1
from stateflow import services as stateflow_services
from django.contrib.contenttypes.models import ContentType
ct = ContentType.objects.get_for_model(printing_models.PrintingJob)
self.bo1 = stateflow_models.BusinessObject.objects.create(
name=f'PrintingJob-{self.job1.id}',
process=self.process,
content_type=ct,
object_id=self.job1.id
)
self.job1.business_object = self.bo1
self.job1.save()
self.bo2 = stateflow_models.BusinessObject.objects.create(
name=f'PrintingJob-{self.job2.id}',
process=self.process,
content_type=ct,
object_id=self.job2.id
)
self.job2.business_object = self.bo2
self.job2.save()
# 推进到 state1创建 state_log
stateflow_services.advance_to_next_state(self.bo1, self.user, temperature='25.0')
stateflow_services.advance_to_next_state(self.bo2, self.user, temperature='25.0')
def test_batch_add_parameters_success(self):
"""测试成功批量补充参数"""
response = self.client.post(
'/api/v2/printing-jobs/batch-add-parameters/',
{
'printing_job_ids': [self.job1.id, self.job2.id],
'state_id': self.state1.id,
'parameters': {'temperature': '26.0', 'operator': '李四'},
'remark': '补测数据'
},
format='json'
)
self.assertEqual(response.status_code, 200)
data = response.data
self.assertEqual(data['detail'], '批量补充参数成功')
self.assertEqual(data['printing_order_id'], self.printing_order.id)
self.assertEqual(set(data['printing_job_ids']), {self.job1.id, self.job2.id})
self.assertEqual(data['state_id'], self.state1.id)
self.assertEqual(data['state_name'], '染色')
self.assertEqual(data['affected_count'], 2)
# 验证创建了批量操作记录
record = printing_models.PrintingJobBatchAdvanceRecord.objects.get(id=data['batch_record_id'])
self.assertTrue(record.only_parameters)
self.assertEqual(record.parameters, {'temperature': '26.0', 'operator': '李四'})
self.assertEqual(record.printing_jobs.count(), 2)
def test_batch_add_parameters_empty_parameters(self):
"""测试参数为空时返回错误"""
response = self.client.post(
'/api/v2/printing-jobs/batch-add-parameters/',
{
'printing_job_ids': [self.job1.id],
'state_id': self.state1.id,
'parameters': {},
},
format='json'
)
self.assertEqual(response.status_code, 400)
def test_batch_add_parameters_job_not_found(self):
"""测试 job 不存在时返回错误"""
response = self.client.post(
'/api/v2/printing-jobs/batch-add-parameters/',
{
'printing_job_ids': [99999],
'state_id': self.state1.id,
'parameters': {'temperature': '26.0'},
},
format='json'
)
self.assertEqual(response.status_code, 400)
self.assertIn('missing_jobs', response.data)
def test_batch_add_parameters_state_not_found(self):
"""测试 state 不存在时返回错误"""
response = self.client.post(
'/api/v2/printing-jobs/batch-add-parameters/',
{
'printing_job_ids': [self.job1.id],
'state_id': 99999,
'parameters': {'temperature': '26.0'},
},
format='json'
)
self.assertEqual(response.status_code, 400)
def test_batch_add_parameters_missing_state_log(self):
"""测试 job 没有对应 state_log 时返回错误"""
# state2 的 state_log 尚未创建(还没推进到那一步)
response = self.client.post(
'/api/v2/printing-jobs/batch-add-parameters/',
{
'printing_job_ids': [self.job1.id],
'state_id': self.state2.id, # 还没推进到这个状态
'parameters': {'temperature': '26.0'},
},
format='json'
)
self.assertEqual(response.status_code, 400)
self.assertIn('missing_state_log', response.data)
def test_batch_add_parameters_different_orders(self):
"""测试 jobs 属于不同订单时返回错误"""
# 创建另一个订单和 job
another_order = printing_models.PrintingOrder.objects.create(
customer=self.customer,
fabric='另一面料',
width='160cm'
)
another_job = printing_models.PrintingJob.objects.create(
printing_order=another_order,
product=self.product,
quantity=300,
unit=''
)
response = self.client.post(
'/api/v2/printing-jobs/batch-add-parameters/',
{
'printing_job_ids': [self.job1.id, another_job.id],
'state_id': self.state1.id,
'parameters': {'temperature': '26.0'},
},
format='json'
)
self.assertEqual(response.status_code, 400)
def test_batch_add_parameters_unauthenticated(self):
"""测试未登录时返回 401"""
self.client.logout()
response = self.client.post(
'/api/v2/printing-jobs/batch-add-parameters/',
{
'printing_job_ids': [self.job1.id],
'state_id': self.state1.id,
'parameters': {'temperature': '26.0'},
},
format='json'
)
self.assertEqual(response.status_code, 401)

View File

@@ -7,6 +7,7 @@ from api_v2.views import (
PrintingJobByCustomerView,
PrintingJobBatchAdvancePreviewView,
PrintingJobBatchAdvanceSubmitView,
PrintingJobBatchAddParametersView,
PlateOrderByProcessNodeView,
PlateOrderByProcessView,
PlateOrderByStateStatusView,
@@ -25,6 +26,7 @@ urlpatterns = [
path('printing-jobs/by-customer/', PrintingJobByCustomerView.as_view(), name='api_v2_printing_job_by_customer'),
path('printing-jobs/batch-advance/preview/', PrintingJobBatchAdvancePreviewView.as_view(), name='api_v2_printing_job_batch_advance_preview'),
path('printing-jobs/batch-advance/', PrintingJobBatchAdvanceSubmitView.as_view(), name='api_v2_printing_job_batch_advance_submit'),
path('printing-jobs/batch-add-parameters/', PrintingJobBatchAddParametersView.as_view(), name='api_v2_printing_job_batch_add_parameters'),
path('printing-orders/<int:printing_order_id>/batch-advance-records/', PrintingOrderBatchAdvanceRecordsView.as_view(), name='api_v2_printing_order_batch_advance_records'),
path('plate-orders/by-process-node/', PlateOrderByProcessNodeView.as_view(), name='api_v2_plate_order_by_process_node'),
path('plate-orders/by-process/', PlateOrderByProcessView.as_view(), name='api_v2_plate_order_by_process'),

View File

@@ -9,6 +9,7 @@ from .printing import (
PrintingJobV2Serializer,
PrintingJobBatchAdvancePreviewView,
PrintingJobBatchAdvanceSubmitView,
PrintingJobBatchAddParametersView,
PlateOrderByProcessNodeView,
PlateOrderByProcessView,
PlateOrderByStateStatusView,
@@ -25,6 +26,7 @@ __all__ = [
'PrintingJobV2Serializer',
'PrintingJobBatchAdvancePreviewView',
'PrintingJobBatchAdvanceSubmitView',
'PrintingJobBatchAddParametersView',
'PlateOrderByProcessNodeView',
'PlateOrderByProcessView',
'PlateOrderByStateStatusView',

View File

@@ -1348,7 +1348,7 @@ class PlateOrderBatchUpdateView(APIView):
class BatchAdvanceRecordSerializer(serializers.ModelSerializer):
"""批量推进记录序列化器"""
"""批量操作记录序列化器"""
state_id = serializers.IntegerField(source='state.id', read_only=True)
state_name = serializers.CharField(source='state.name', read_only=True)
@@ -1369,6 +1369,7 @@ class BatchAdvanceRecordSerializer(serializers.ModelSerializer):
'created_by_username',
'created_by_name',
'parameters',
'only_parameters',
'printing_job_ids',
'printing_job_count',
'created_at',
@@ -1458,3 +1459,200 @@ class PrintingOrderBatchAdvanceRecordsView(APIView):
'records': serializer.data,
'total_count': records.count(),
})
class PrintingJobBatchAddParametersRequestSerializer(serializers.Serializer):
"""批量补充参数请求序列化器"""
printing_job_ids = serializers.ListField(
child=serializers.IntegerField(),
min_length=1,
help_text='印染明细ID列表'
)
state_id = serializers.IntegerField(help_text='目标流程节点ID')
parameters = serializers.DictField(
child=serializers.CharField(allow_blank=True),
help_text='要补充的工艺参数'
)
remark = serializers.CharField(required=False, default='', allow_blank=True, help_text='备注说明')
def _validate_jobs_for_batch_add_parameters(printing_job_ids: list[int], state_id: int) -> dict:
"""
验证批量补充参数的 jobs 并返回相关数据
验证规则:
1. 所有 job 必须存在
2. 所有 job 必须属于同一个 printing_order
3. 所有 job 必须有 business_object
4. 所有 job 的 business_object 必须有对应 state_id 的 state_log未撤销
返回:
{
'jobs': QuerySet[PrintingJob],
'printing_order': PrintingOrder,
'printing_order_id': int,
'state': State,
'state_logs': dict[int, StateFlowRecord], # job_id -> state_log
}
"""
from stateflow import models as stateflow_models
jobs = (
printing_models.PrintingJob.objects
.select_related('printing_order', 'business_object')
.filter(id__in=printing_job_ids)
)
found_ids = set(jobs.values_list('id', flat=True))
missing_ids = [i for i in printing_job_ids if i not in found_ids]
if missing_ids:
raise serializers.ValidationError({
'detail': f'以下 PrintingJob 不存在: {missing_ids}',
'missing_jobs': missing_ids,
})
# 验证同一订单
order_ids = set(jobs.values_list('printing_order_id', flat=True))
if len(order_ids) != 1:
raise serializers.ValidationError({
'detail': '所有 PrintingJob 必须属于同一个 PrintingOrder',
})
printing_order_id = order_ids.pop()
printing_order = printing_models.PrintingOrder.objects.get(id=printing_order_id)
# 验证 state 存在
try:
state = stateflow_models.State.objects.get(id=state_id)
except stateflow_models.State.DoesNotExist:
raise serializers.ValidationError({
'detail': f'State ID {state_id} 不存在',
})
# 验证所有 job 有 business_object 和对应的 state_log
jobs_without_bo = []
jobs_without_state_log = []
state_logs = {} # job_id -> state_log
for job in jobs:
if not job.business_object:
jobs_without_bo.append(job.id)
continue
# 查找对应 state_id 的 state_log未撤销
state_log = job.business_object.state_logs.filter(
state_id=state_id,
is_cancelled=False
).first()
if not state_log:
jobs_without_state_log.append(job.id)
else:
state_logs[job.id] = state_log
if jobs_without_bo:
raise serializers.ValidationError({
'detail': f'以下 PrintingJob 没有流程实例 (business_object): {jobs_without_bo}',
'missing_business_object': jobs_without_bo,
})
if jobs_without_state_log:
raise serializers.ValidationError({
'detail': f'以下 PrintingJob 没有对应 state_id={state_id} 的状态流转记录(或已撤销): {jobs_without_state_log}',
'missing_state_log': jobs_without_state_log,
})
return {
'jobs': jobs,
'printing_order': printing_order,
'printing_order_id': printing_order_id,
'state': state,
'state_logs': state_logs,
}
class PrintingJobBatchAddParametersView(APIView):
"""
批量补充工艺参数
为多个 PrintingJob 的已完成状态流转记录批量补充工艺参数。
POST /api/v2/printing-jobs/batch-add-parameters/
请求体:
{
"printing_job_ids": [101, 102, 103],
"state_id": 7,
"parameters": {
"temperature": "26.0",
"operator": "李四"
},
"remark": "批量补充参数备注"
}
响应:
{
"detail": "批量补充参数成功",
"batch_record_id": 15,
"printing_order_id": 55,
"printing_job_ids": [101, 102, 103],
"state_id": 7,
"state_name": "染色",
"parameters": {...},
"affected_count": 3
}
"""
permission_classes = [permissions.IsAuthenticated, IsPrintingFactory]
def post(self, request):
srz = PrintingJobBatchAddParametersRequestSerializer(data=request.data)
srz.is_valid(raise_exception=True)
payload = srz.validated_data
printing_job_ids = payload['printing_job_ids']
state_id = payload['state_id']
parameters = payload['parameters']
remark = payload.get('remark', '')
if not parameters:
raise serializers.ValidationError({
'detail': '参数不能为空',
})
# 验证数据
data = _validate_jobs_for_batch_add_parameters(printing_job_ids, state_id)
from stateflow import services as stateflow_services
# 全成功/全失败
with transaction.atomic():
# 创建批量操作记录
record = printing_models.PrintingJobBatchAdvanceRecord.objects.create(
printing_order=data['printing_order'],
state=data['state'],
created_by=request.user,
parameters=parameters,
only_parameters=True, # 标记为仅补充参数
)
record.printing_jobs.set(data['jobs'])
# 逐个补充参数
for job in data['jobs']:
state_log = data['state_logs'][job.id]
stateflow_services.add_parameters_to_state_log(
state_log,
remark=remark,
**parameters
)
return Response({
'detail': '批量补充参数成功',
'batch_record_id': record.id,
'printing_order_id': data['printing_order_id'],
'printing_job_ids': [j.id for j in data['jobs']],
'state_id': state_id,
'state_name': data['state'].name,
'parameters': parameters,
'affected_count': len(data['jobs']),
})