""" Printing 模块信号处理函数 监听 stateflow 信号,在流程完成时执行业务逻辑。 """ import logging from django.db import transaction logger = logging.getLogger(__name__) def on_printing_job_process_completed(sender, **kwargs): """ PrintingJob 流程完成时的处理 当 PrintingJob 的工艺流程全部完成时,自动创建 SalesItem(销售品)。 Args: sender: PrintingJob 类 content_object: PrintingJob 实例 last_completed_by: 最后步骤操作人 其他参数见 stateflow.signals.process_completed """ from shipment.models import SalesItem, UnitChoices content_object = kwargs.get('content_object') last_completed_by = kwargs.get('last_completed_by') if content_object is None: logger.warning('process_completed 信号缺少 content_object') return printing_job = content_object # 单位映射:PrintingJob.unit(字符串)→ SalesItem.unit(IntegerChoices) unit_mapping = { '米': UnitChoices.METER, 'm': UnitChoices.METER, 'M': UnitChoices.METER, '件': UnitChoices.PIECE, '码': UnitChoices.YARD, 'yd': UnitChoices.YARD, 'YD': UnitChoices.YARD, '个': UnitChoices.UNIT, 'pcs': UnitChoices.UNIT, 'PCS': UnitChoices.UNIT, } # 默认单位为"件" sales_unit = unit_mapping.get(printing_job.unit, UnitChoices.PIECE) # 获取产品名称 product_name = printing_job.product.name if printing_job.product else '未知产品' # 获取客户ID(从主订单获取) customer_id = None if printing_job.printing_order and printing_job.printing_order.customer: customer_id = printing_job.printing_order.customer_id try: with transaction.atomic(): sales_item = SalesItem.objects.create( shipment=None, # 暂不关联出货单,待后续分配 name=product_name, quantity=printing_job.quantity, unit=sales_unit, created_by=last_completed_by, printing_job_id=printing_job.id, customer_id=customer_id, ) logger.info( f'PrintingJob #{printing_job.id} 流程完成,' f'已创建销售品 SalesItem #{sales_item.id}: ' f'{product_name} x {printing_job.quantity}' ) except Exception as e: logger.error( f'PrintingJob #{printing_job.id} 流程完成后创建销售品失败: {e}', exc_info=True )