views.py 85 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161
  1. from pathlib import Path
  2. from rest_framework.views import APIView
  3. from rest_framework.permissions import AllowAny
  4. from rest_framework import status
  5. from rest_framework import viewsets
  6. from django_filters.rest_framework import DjangoFilterBackend
  7. from rest_framework.filters import OrderingFilter
  8. from django.utils import timezone
  9. from django.db.models import Q, F, Case, When
  10. from django.core.cache import cache
  11. import requests
  12. from collections import defaultdict
  13. from utils.page import MyPageNumberPagination
  14. from .models import *
  15. from .serializers import *
  16. from .filter import *
  17. from .parsers import TextJSONParser
  18. from .parsers import TextJSONRenderer
  19. import logging
  20. import time
  21. from django.db import transaction
  22. from bound.models import BoundListModel, BoundBatchModel, OutBatchModel,BoundDetailModel,OutBoundDetailModel,BatchLogModel
  23. from warehouse.models import ProductListModel
  24. from rest_framework.response import Response
  25. import json
  26. logger = logging.getLogger('wms.boundBill')
  27. class WMSResponse:
  28. """
  29. 入库申请专用响应格式
  30. 使用示例:
  31. return WMSResponse.success(data=serializer.data, total=2, success=2)
  32. return WMSResponse.error(message='验证失败', total=2, fail_count=1,
  33. fail_materials=[{...}])
  34. """
  35. @staticmethod
  36. def success(data, total, success, status=status.HTTP_200_OK):
  37. """成功响应格式"""
  38. logger.info('成功响应 | 数据: %s', data)
  39. return Response({
  40. "status": True,
  41. "errorCode": status,
  42. "message": "success",
  43. "data": {
  44. "failCount": 0,
  45. "totalCount": total,
  46. "successCount": success,
  47. "fail_materials": []
  48. }
  49. }, status=status)
  50. @staticmethod
  51. def error(message, total, fail_count, fail_materials=None,
  52. status=status.HTTP_200_OK, exception=None):
  53. """错误响应格式"""
  54. if fail_materials is None:
  55. fail_materials = []
  56. # 记录详细错误日志
  57. if exception:
  58. logger.error(f"入库申请错误: {message}", exc_info=exception)
  59. return Response({
  60. "status": False,
  61. "errorCode": 400,
  62. "message": message,
  63. "data": {
  64. "failCount": fail_count,
  65. "totalCount": total,
  66. "successCount": total - fail_count,
  67. "fail_materials": fail_materials
  68. }
  69. }, status=status)
  70. """入库申请"""
  71. class InboundApplyCreate(APIView):
  72. """
  73. 生产入库申请
  74. """
  75. authentication_classes = []
  76. permission_classes = [AllowAny]
  77. def post(self, request):
  78. logger.info('生产入库申请请求 | 原始数据: %s', request.data)
  79. try:
  80. total_count = len(request.data.get('materials', []))
  81. if total_count == 0 :
  82. return WMSResponse.error(
  83. message="物料清单不能为空",
  84. total=0,
  85. fail_count=0
  86. )
  87. if total_count != request.data.get('totalCount', 0):
  88. return WMSResponse.error(
  89. message="物料数量不匹配",
  90. total=total_count,
  91. fail_count=total_count
  92. )
  93. serializer = boundPostSerializer(data=request.data)
  94. if not serializer.is_valid():
  95. return self._handle_validation_error(serializer.errors, total_count)
  96. unique_result,error_details = self.find_unique_billid_and_number(serializer)
  97. if not unique_result:
  98. return WMSResponse.error(
  99. message="单据编号或原始单据ID重复",
  100. total=total_count,
  101. fail_count=total_count,
  102. fail_materials=[{
  103. "entryIds": None,
  104. "production_batch": None,
  105. "errors": error_details
  106. }]
  107. )
  108. # 保存或更新入库单
  109. bound_bill = self.save_or_update_inbound_bill(serializer)
  110. # 保存或更新物料明细
  111. self.save_or_update_material_detail(bound_bill, serializer)
  112. return WMSResponse.success(
  113. data=serializer.data,
  114. total=total_count,
  115. success=total_count
  116. )
  117. except Exception as e:
  118. logger.exception("服务器内部错误")
  119. return WMSResponse.error(
  120. message="系统处理异常",
  121. total=total_count,
  122. fail_count=total_count,
  123. status=status.HTTP_500_INTERNAL_SERVER_ERROR,
  124. exception=e
  125. )
  126. def _handle_validation_error(self, errors, total_count):
  127. """增强错误解析"""
  128. fail_materials = []
  129. # 提取嵌套错误信息
  130. material_errors = errors.get('materials', [])
  131. for error in material_errors:
  132. # 解析DRF的错误结构
  133. if isinstance(error, dict) and 'metadata' in error:
  134. fail_materials.append({
  135. "entryIds": error['metadata'].get('entryIds'),
  136. "production_batch": error['metadata'].get('production_batch'),
  137. "errors": {
  138. "missing_fields": error['metadata']['missing_fields'],
  139. "message": error['detail']
  140. }
  141. })
  142. return WMSResponse.error(
  143. message="物料数据不完整",
  144. total=total_count,
  145. fail_count=len(fail_materials),
  146. fail_materials=fail_materials
  147. )
  148. def _format_material_errors(self, error_dict):
  149. """格式化单个物料的错误信息"""
  150. return {
  151. field: details[0] if isinstance(details, list) else details
  152. for field, details in error_dict.items()
  153. }
  154. def find_unique_billid_and_number(self, serializer):
  155. """增强版唯一性验证"""
  156. bill_id = serializer.validated_data['billId']
  157. number = serializer.validated_data['number']
  158. # 使用Q对象进行联合查询
  159. duplicates_id = InboundBill.objects.filter(
  160. Q(billId=bill_id)
  161. ).only('billId')
  162. # 使用Q对象进行联合查询
  163. duplicates_nu = InboundBill.objects.filter(
  164. Q(number=number)
  165. ).only( 'number')
  166. error_details = {}
  167. # 检查单据编号重复
  168. if any(obj.billId != bill_id for obj in duplicates_nu):
  169. error_details['number'] = ["number入库单编码已存在,但是系统中与之前入库单单据ID不一致,请检查"]
  170. # 检查业务编号重复
  171. if any(obj.number != number for obj in duplicates_id):
  172. error_details['billId'] = ["billId入库单单据ID已存在,但是系统中与之前入库申请单编码不一致,请检查"]
  173. if error_details:
  174. return False,error_details
  175. return True,None
  176. def audit_save_status(self, bound_bill_type,base_type):
  177. # 根据不同入库单类型和不同出入库类型,返回审核状态和保存状态
  178. # bound_bill_type:表示不同出入库类型 :1(生产入库申请-生产汇报单)2(采购入库申请-收料通知单) 3(其他入库)4(调拨入库) 1(销售出库申请-发货通知单) 2(生产领料)3(其他出库)
  179. # 1,1 生产入库-> 0,9 (0为未审核,9为无需保存)
  180. # 2,1 采购入库-> 0,0 (0为未审核,0为未保存)
  181. # 3,1 其他入库-> 0,9 (0为未审核,9为无需保存)
  182. # 4,1 调拨入库-> 0,9 (0为未审核,9为无需保存)
  183. # 1,2 销售出库-> 9,0 (9为无需审核,0为未保存)
  184. # 2,2 生产领料-> 0,9 (0为未审核,9为无需保存)
  185. # 3,2 其他出库-> 0,9 (0为未审核,9为无需保存)
  186. # base_type:表示不同入库单类型 1 为入库 2为出库
  187. if base_type == 1: # 入库
  188. if bound_bill_type == 1: # 生产入库
  189. return 0, 9
  190. elif bound_bill_type == 2: # 采购入库
  191. return 0, 0
  192. elif bound_bill_type == 3: # 其他入库
  193. return 0, 9
  194. elif bound_bill_type == 4: # 调拨入库
  195. return 0, 9
  196. else: # 出库
  197. if bound_bill_type == 1: # 销售出库
  198. return 9, 0
  199. elif bound_bill_type == 2: # 生产领料
  200. return 0, 9
  201. elif bound_bill_type == 3: # 其他出库
  202. return 0, 9
  203. return 0, 0
  204. def save_or_update_inbound_bill(self, serializer):
  205. """保存或更新入库单"""
  206. # 保存或更新入库单
  207. try:
  208. bound_bill = InboundBill.objects.get(billId=serializer.validated_data['billId'])
  209. bound_bill.number = serializer.validated_data['number']
  210. bound_bill.type = serializer.validated_data['type']
  211. bound_bill.date = serializer.validated_data['date']
  212. bound_bill.department = (serializer.validated_data['department'] if 'department' in serializer.validated_data else '')
  213. bound_bill.warehouse = serializer.validated_data['warehouse']
  214. bound_bill.creater = serializer.validated_data['creater']
  215. bound_bill.note = (serializer.validated_data['note'] if 'note' in serializer.validated_data else '')
  216. bound_bill.totalCount = serializer.validated_data['totalCount']
  217. if bound_bill.type != 1:
  218. bound_bill.erp_audit_id = bound_bill.number
  219. bound_bill.erp_save_id = bound_bill.billId
  220. bound_bill.audit_status, bound_bill.save_status = self.audit_save_status(bound_bill.type,1)
  221. bound_bill.update_time = timezone.now()
  222. bound_bill.is_delete = False
  223. bound_bill.save()
  224. InboundBillOperateLog.objects.create(
  225. billId=bound_bill,
  226. log_type ='update',
  227. log_content = f"更新入库单{bound_bill.number}信息",
  228. )
  229. except InboundBill.DoesNotExist:
  230. audit_status, save_status = self.audit_save_status(serializer.validated_data['type'], 1)
  231. bound_bill = InboundBill.objects.create(
  232. billId=serializer.validated_data['billId'],
  233. number=serializer.validated_data['number'],
  234. type=serializer.validated_data['type'],
  235. date=serializer.validated_data['date'],
  236. department=(serializer.validated_data['department'] if 'department' in serializer.validated_data else ''),
  237. warehouse=serializer.validated_data['warehouse'],
  238. creater=serializer.validated_data['creater'],
  239. note=(serializer.validated_data['note'] if 'note' in serializer.validated_data else ''),
  240. totalCount=serializer.validated_data['totalCount'],
  241. erp_save_id = serializer.validated_data['billId'],
  242. audit_status = audit_status,
  243. save_status = save_status,
  244. create_time=timezone.now(),
  245. update_time=timezone.now()
  246. )
  247. if bound_bill.type != 1:
  248. bound_bill.erp_audit_id = bound_bill.number
  249. bound_bill.save()
  250. InboundBillOperateLog.objects.create(
  251. billId=bound_bill,
  252. log_type ='create',
  253. log_content = f"创建入库单{bound_bill.number}信息",
  254. )
  255. return bound_bill
  256. def save_or_update_material_detail(self, bound_bill, serializer):
  257. """保存或更新物料明细"""
  258. # 保存或更新物料明细
  259. for item in serializer.validated_data['materials']:
  260. try:
  261. material_detail = MaterialDetail.objects.get(bound_billId=bound_bill, entryIds=item['entryIds'])
  262. material_detail.production_batch = item['production_batch']
  263. material_detail.goods_code = item['goods_code']
  264. material_detail.goods_name = item['goods_name']
  265. material_detail.goods_std = (item['goods_std'] if 'goods_std' in item else '')
  266. material_detail.plan_qty = item['plan_qty']
  267. material_detail.goods_total_weight = item['plan_qty']
  268. material_detail.goods_unit = item['goods_unit']
  269. material_detail.note = (item['note'] if 'note' in item else '')
  270. material_detail.update_time = timezone.now()
  271. material_detail.is_delete = False
  272. material_detail.save()
  273. except MaterialDetail.DoesNotExist:
  274. material_detail = MaterialDetail.objects.create(
  275. bound_billId=bound_bill,
  276. entryIds=item['entryIds'],
  277. production_batch=item['production_batch'],
  278. goods_code=item['goods_code'],
  279. goods_name=item['goods_name'],
  280. goods_std=(item['goods_std'] if 'goods_std' in item else ''),
  281. goods_weight=1,
  282. plan_qty=item['plan_qty'],
  283. goods_total_weight=item['plan_qty'],
  284. goods_unit=item['goods_unit'],
  285. note=(item['note'] if 'note' in item else ''),
  286. create_time=timezone.now(),
  287. update_time=timezone.now()
  288. )
  289. return material_detail
  290. """入库单生成"""
  291. class GenerateInbound(APIView):
  292. """
  293. 生产入库单生成接口
  294. 功能特性:
  295. 1. 防重复创建校验(状态校验+关联单据校验)
  296. 2. 事务级数据一致性保障
  297. 3. 批量操作优化
  298. 4. 完整日志追踪
  299. """
  300. def post(self, request):
  301. try:
  302. bill_id = request.data.get('billId')
  303. if not bill_id:
  304. return Response({"error": "缺少必要参数: billId"},
  305. status=status.HTTP_400_BAD_REQUEST)
  306. # 开启原子事务
  307. with transaction.atomic():
  308. # 锁定原始单据并校验
  309. bill_obj, bound_list = self.validate_and_lock(bill_id)
  310. # 创建出入库主单
  311. bound_list = self.create_bound_list(bill_obj)
  312. logger.info(f"创建出入库主单成功 | bound_code: {bound_list.bound_code}")
  313. # 处理物料明细(批量操作优化)
  314. self.process_materials(bill_obj, bound_list)
  315. # 更新原始单据状态
  316. bill_obj.bound_status = 1
  317. bill_obj.save(update_fields=['bound_status'])
  318. logger.info(f"入库单生成成功 | billId: {bill_id} -> boundCode: {bound_list.bound_code}")
  319. return Response({
  320. "code": 200,
  321. "count": 1,
  322. "next": "null",
  323. "previous": "null",
  324. "results":{
  325. "bound_code": bound_list.bound_code,
  326. "batch_count": bill_obj.totalCount
  327. }
  328. }, status=status.HTTP_200_OK)
  329. except InboundBill.DoesNotExist:
  330. logger.error(f"原始单据不存在 | billId: {bill_id}")
  331. return Response({
  332. "code": 404,
  333. "error": "原始单据不存在"
  334. }, status=status.HTTP_404_NOT_FOUND)
  335. except Exception as e:
  336. logger.exception(f"入库单生成异常 | billId: {bill_id}")
  337. return Response({
  338. "code": 400,
  339. "error": str(e)
  340. }, status=status.HTTP_200_OK)
  341. def validate_and_lock(self, bill_id):
  342. """验证并锁定相关资源"""
  343. # 锁定原始单据
  344. bill_obj = InboundBill.objects.select_for_update().get(
  345. billId=bill_id,
  346. is_delete=False
  347. )
  348. logger.info(f"锁定原始单据成功 | billId: {bill_id}")
  349. logger.info(f"原始单据状态: {bill_obj.bound_status}")
  350. # 状态校验
  351. if bill_obj.bound_status == 1:
  352. logger.warning(f"单据已生成过入库单 | status: {bill_obj.bound_status}")
  353. raise Exception("该单据已生成过入库单")
  354. # 关联单据校验(双重校验机制)
  355. existing_bound = BoundListModel.objects.filter(
  356. Q(bound_desc__contains=f"生产入库单{bill_obj.number}") |
  357. Q(relate_bill=bill_obj),
  358. is_delete=False
  359. ).first()
  360. if existing_bound:
  361. logger.warning(f"发现重复关联单据 | existingCode: {existing_bound.bound_code}")
  362. raise Exception(f"已存在关联入库单[{existing_bound.bound_code}]")
  363. return bill_obj, None
  364. def process_materials(self, bill_obj, bound_list):
  365. """批量处理物料明细"""
  366. materials = MaterialDetail.objects.filter(
  367. bound_billId=bill_obj,
  368. is_delete=False
  369. ).select_related('bound_billId')
  370. if not materials:
  371. raise Exception("入库单没有有效物料明细")
  372. # 批量创建对象列表
  373. batch_list = []
  374. detail_list = []
  375. log_list = []
  376. order_month = str(timezone.now().strftime('%Y%m')) # 修正变量名
  377. for material in materials:
  378. # 规范批次号处理(支持7位和9位格式)
  379. try:
  380. # 拆分生产批次(物料代码-批次号)
  381. parts = material.production_batch.split('-')
  382. if len(parts) < 2:
  383. raise ValueError(f"无效的生产批次格式: {material.production_batch}")
  384. material_goods_code = parts[0]
  385. batch_str = parts[1]
  386. # 标准化批次号处理
  387. if len(batch_str) == 7: # 2508001 格式
  388. # 添加"20"前缀转为9位格式: 202508001
  389. standardized_batch = "20" + batch_str
  390. elif len(batch_str) == 9: # 202508001 格式
  391. standardized_batch = batch_str
  392. else:
  393. raise ValueError(f"无效的批次号长度: {batch_str}")
  394. # 创建规范化的bound_number(物料代码-标准批次号)
  395. bound_number = f"{material_goods_code}-{standardized_batch}"
  396. material.material_goods_code = material_goods_code
  397. material.material_batch_order = standardized_batch
  398. material.save(update_fields=['material_goods_code','material_batch_order'])
  399. except (IndexError, ValueError) as e:
  400. raise Exception(f"物料批次处理错误: {e}")
  401. # 创建批次记录
  402. batch = BoundBatchModel(
  403. bound_number=bound_number, # 使用规范化的批次号
  404. sourced_number=material.production_batch, # 保留原始批次号
  405. bound_month=bound_list.bound_month,
  406. bound_batch_order=standardized_batch, # 存储标准化批次号
  407. warehouse_code='W01',
  408. warehouse_name='立体仓',
  409. goods_code=material.goods_code,
  410. goods_desc=material.goods_name,
  411. goods_std=material.goods_std or '', # 处理空值
  412. goods_unit=material.goods_unit,
  413. goods_qty=material.plan_qty,
  414. goods_weight=float(material.goods_weight),
  415. goods_total_weight=float(material.goods_total_weight),
  416. creater=bound_list.creater,
  417. openid=bound_list.openid,
  418. relate_material=material # 关联原始物料
  419. )
  420. batch_list.append(batch)
  421. # 创建明细记录
  422. detail_list.append(BoundDetailModel(
  423. bound_list=bound_list,
  424. bound_batch=batch,
  425. detail_code=f"{bound_number}-DET", # 使用规范化的批次号
  426. creater=bound_list.creater,
  427. openid=bound_list.openid
  428. ))
  429. # 创建日志记录
  430. log_list.append(BatchLogModel(
  431. batch_id=batch,
  432. log_type=0,
  433. log_date=timezone.now(),
  434. goods_code=batch.goods_code,
  435. goods_desc=batch.goods_desc,
  436. goods_qty=batch.goods_qty,
  437. log_content=f"生产入库批次创建,来源单据:{bill_obj.number}",
  438. creater=batch.creater,
  439. openid=batch.openid
  440. ))
  441. # 批量写入数据库
  442. try:
  443. with transaction.atomic():
  444. BoundBatchModel.objects.bulk_create(batch_list)
  445. BoundDetailModel.objects.bulk_create(detail_list)
  446. BatchLogModel.objects.bulk_create(log_list)
  447. except Exception as e:
  448. raise Exception(f"批次数据保存失败: {str(e)}")
  449. def create_bound_list(self, bill_obj):
  450. """创建出入库主单(带来源标识)"""
  451. if BoundListModel.objects.filter(relate_bill=bill_obj, is_delete=False).exists():
  452. return BoundListModel.objects.get(relate_bill=bill_obj,is_delete=False)
  453. if bill_obj.type == 1:
  454. bound_desc = f"生产入库单{bill_obj.number}"
  455. elif bill_obj.type == 2:
  456. bound_desc = f"采购入库单{bill_obj.number}"
  457. elif bill_obj.type == 4:
  458. bound_desc = f"调拨入库单{bill_obj.number}"
  459. else:
  460. bound_desc = f"其他入库单{bill_obj.number}"
  461. InboundBillOperateLog.objects.create(
  462. billId=bill_obj,
  463. log_type ='wms_audit',
  464. log_content = f"WMS创建入库单{bill_obj.number}信息,开始执行入库任务",
  465. )
  466. # 更新原始单据状态
  467. bill_obj.status = 2
  468. bill_obj.save()
  469. return BoundListModel.objects.create(
  470. bound_month=timezone.now().strftime("%Y%m"),
  471. bound_date=timezone.now().strftime("%Y-%m-%d"),
  472. bound_code=bill_obj.number,
  473. bound_code_type=bill_obj.type,
  474. bound_bs_type='B01',
  475. bound_type='in',
  476. bound_desc=bound_desc,
  477. bound_department=(bill_obj.department if bill_obj.department else 'D99'),
  478. base_type=0,
  479. bound_status='101',
  480. creater=bill_obj.creater,
  481. openid='ERP',
  482. relate_bill=bill_obj
  483. )
  484. def handle_exception(self, exc):
  485. """统一异常处理"""
  486. if isinstance(exc, InboundBill.DoesNotExist):
  487. return Response({"error": "原始单据不存在或已被删除"}, status=status.HTTP_404_NOT_FOUND)
  488. elif "重复" in str(exc):
  489. return Response({"error": str(exc)}, status=status.HTTP_409_CONFLICT)
  490. return super().handle_exception(exc)
  491. class FindExistingBatch(APIView):
  492. """
  493. 预查询是否存在可关联的离线批次
  494. 匹配策略:
  495. 1. 标准化批次号完全匹配
  496. 2. 相同物料代码
  497. 3. 批次未关联其他物料
  498. 4. 批次状态有效
  499. """
  500. def post(self, request):
  501. """
  502. 预查询是否存在可关联的离线批次
  503. 匹配策略:
  504. 1. 标准化批次号完全匹配
  505. 2. 相同物料代码
  506. 3. 批次未关联其他物料
  507. 4. 批次状态有效
  508. """
  509. # 标准化批次号处理
  510. try:
  511. bill_id = request.data.get('billId')
  512. InboundBill_obj = InboundBill.objects.get(billId=bill_id, is_delete=False)
  513. if not InboundBill_obj:
  514. raise InboundBill.DoesNotExist(f"原始单据不存在或已被删除")
  515. MaterialDetail_obj_all = MaterialDetail.objects.filter(bound_billId=InboundBill_obj, is_delete=False).all()
  516. if not MaterialDetail_obj_all:
  517. raise Exception("入库单没有有效物料明细")
  518. # 拆分生产批次(物料代码-批次号)
  519. material_map = {}
  520. for material in MaterialDetail_obj_all:
  521. parts = material.production_batch.split('-')
  522. if len(parts) < 2:
  523. raise ValueError(f"无效的生产批次格式: {material.production_batch}")
  524. material_goods_code = parts[0]
  525. batch_str = parts[1]
  526. # 标准化批次号处理
  527. if len(batch_str) == 7: # 2508001 格式
  528. # 添加"20"前缀转为9位格式: 202508001
  529. standardized_batch = "20" + batch_str
  530. elif len(batch_str) == 9: # 202508001 格式
  531. standardized_batch = batch_str
  532. else:
  533. raise ValueError(f"无效的批次号长度: {batch_str}")
  534. # 创建规范化的bound_number(物料代码-标准批次号)
  535. bound_number = f"{material_goods_code}-{standardized_batch}"
  536. material.material_goods_code = material_goods_code
  537. material.material_batch_order = standardized_batch
  538. material.save(update_fields=['material_goods_code','material_batch_order'])
  539. if BoundBatchModel.objects.filter(bound_number=bound_number, is_delete=False).exists():
  540. material_map[bound_number] = True
  541. else:
  542. material_map[bound_number] = False
  543. return_data= material_map
  544. return Response({
  545. "code": 200,
  546. "data": return_data
  547. }, status=status.HTTP_200_OK)
  548. except (IndexError, ValueError) as e:
  549. raise Exception(f"物料批次处理错误: {e}")
  550. def handle_exception(self, exc):
  551. """统一异常处理"""
  552. if isinstance(exc, InboundBill.DoesNotExist):
  553. return Response({"error": "原始单据不存在或已被删除"}, status=status.HTTP_404_NOT_FOUND)
  554. elif "重复" in str(exc):
  555. return Response({"error": str(exc)}, status=status.HTTP_409_CONFLICT)
  556. return super().handle_exception(exc)
  557. """出库单生成"""
  558. class GenerateOutbound(APIView):
  559. """
  560. 生产出库单生成接口
  561. 功能特性:
  562. 1. 防重复创建校验(状态校验+关联单据校验)
  563. 2. 事务级数据一致性保障
  564. 3. 批量操作优化
  565. 4. 完整日志追踪
  566. """
  567. def post(self, request):
  568. try:
  569. bill_id = request.data.get('billId')
  570. if not bill_id:
  571. return Response({"error": "缺少必要参数: billId"},
  572. status=status.HTTP_400_BAD_REQUEST)
  573. # 开启原子事务
  574. with transaction.atomic():
  575. # 锁定原始单据并校验
  576. bill_obj, bound_list = self.validate_and_lock(bill_id)
  577. # 创建出库主单
  578. bound_list = self.create_bound_list(bill_obj)
  579. logger.info(f"创建出入库主单成功 | bound_code: {bound_list.bound_code}")
  580. # 处理物料明细(批量操作优化)
  581. self.process_materials(bill_obj, bound_list)
  582. # 更新原始单据状态
  583. bill_obj.bound_status = 1
  584. bill_obj.save(update_fields=['bound_status'])
  585. logger.info(f"出库单生成成功 | billId: {bill_id} -> boundCode: {bound_list.bound_code}")
  586. return Response({
  587. "code": 200,
  588. "count": 1,
  589. "next": "null",
  590. "previous": "null",
  591. "results":{
  592. "bound_code": bound_list.bound_code,
  593. "batch_count": bill_obj.totalCount
  594. }
  595. }, status=status.HTTP_200_OK)
  596. except InboundBill.DoesNotExist:
  597. logger.error(f"原始单据不存在 | billId: {bill_id}")
  598. return Response({
  599. "code": 404,
  600. "error": "原始单据不存在"
  601. }, status=status.HTTP_404_NOT_FOUND)
  602. except Exception as e:
  603. logger.exception(f"出库单生成异常 | billId: {bill_id}")
  604. return Response({
  605. "code": 400,
  606. "error": str(e)
  607. }, status=status.HTTP_200_OK)
  608. def validate_and_lock(self, bill_id):
  609. """验证并锁定相关资源"""
  610. # 锁定原始单据
  611. bill_obj = OutboundBill.objects.select_for_update().get(
  612. billId=bill_id,
  613. is_delete=False
  614. )
  615. logger.info(f"锁定原始单据成功 | billId: {bill_id}")
  616. logger.info(f"原始单据状态: {bill_obj.bound_status}")
  617. # 状态校验
  618. if bill_obj.bound_status == 1:
  619. logger.warning(f"单据已生成过出库单 | status: {bill_obj.bound_status}")
  620. raise Exception("该单据已生成过出库单")
  621. # 关联单据校验(双重校验机制)
  622. existing_bound = BoundListModel.objects.filter(
  623. Q(bound_desc__contains=f"生产出库单{bill_obj.number}") |
  624. Q(relate_out_bill=bill_obj),
  625. is_delete=False
  626. ).first()
  627. if existing_bound:
  628. logger.warning(f"发现重复关联单据 | existingCode: {existing_bound.bound_code}")
  629. raise Exception(f"已存在关联出库单[{existing_bound.bound_code}]")
  630. return bill_obj, None
  631. def process_materials(self, bill_obj, bound_list):
  632. """批量处理物料明细 - 出库版本"""
  633. materials = OutMaterialDetail.objects.filter(
  634. bound_billId=bill_obj,
  635. is_delete=False
  636. ).select_related('bound_billId', 'Material_entryIds')
  637. if not materials:
  638. raise Exception("出库单没有有效物料明细")
  639. # 批量创建对象列表
  640. batch_list = []
  641. detail_list = []
  642. log_list = []
  643. for material in materials:
  644. # 直接使用关联的入库明细,避免额外查询
  645. try:
  646. # 拆分生产批次(物料代码-批次号)
  647. parts = material.production_batch.split('-')
  648. if len(parts) < 2:
  649. raise ValueError(f"无效的生产批次格式: {material.production_batch}")
  650. material_goods_code = parts[0]
  651. batch_str = parts[1]
  652. # 标准化批次号处理
  653. if len(batch_str) == 7: # 2508001 格式
  654. # 添加"20"前缀转为9位格式: 202508001
  655. standardized_batch = "20" + batch_str
  656. elif len(batch_str) == 9: # 202508001 格式
  657. standardized_batch = batch_str
  658. else:
  659. raise ValueError(f"无效的批次号长度: {batch_str}")
  660. # 创建规范化的bound_number(物料代码-标准批次号)
  661. bound_number = f"{material_goods_code}-{standardized_batch}"
  662. material.material_goods_code = material_goods_code
  663. material.material_batch_order = standardized_batch
  664. material.save(update_fields=['material_goods_code','material_batch_order'])
  665. except (IndexError, ValueError) as e:
  666. raise Exception(f"物料批次处理错误: {e}")
  667. # 获取关联的入库批次
  668. try:
  669. batch_obj = BoundBatchModel.objects.get(goods_code = material.material_goods_code, bound_batch_order = material.material_batch_order)
  670. except BoundBatchModel.DoesNotExist:
  671. raise Exception(f"入库物料ID:{material.material_goods_code}-{ material.material_batch_order}构成的批次未找到关联批次记录")
  672. except BoundBatchModel.MultipleObjectsReturned:
  673. raise Exception(f"入库物料ID:{material.material_goods_code}-{ material.material_batch_order}构成的批次关联多个批次记录")
  674. # 计算重量 - 使用入库单件的重量进行计算
  675. unit_weight = batch_obj.goods_weight or 1 # 避免除零错误
  676. out_qty = material.goods_out_qty
  677. total_weight = unit_weight * out_qty
  678. # 创建出库批次记录
  679. batch = OutBatchModel(
  680. out_number=batch_obj.bound_number, # 使用标准化的入库批次号
  681. batch_number=batch_obj,
  682. out_date=timezone.now().strftime("%Y-%m-%d %H:%M:%S"),
  683. out_type=bill_obj.type,
  684. out_note=bill_obj.note,
  685. warehouse_code='W01',
  686. warehouse_name='立体仓',
  687. goods_code=batch_obj.goods_code,
  688. goods_desc=batch_obj.goods_desc,
  689. goods_std=batch_obj.goods_std or '', # 处理空值
  690. goods_unit=batch_obj.goods_unit,
  691. goods_qty=batch_obj.goods_qty, # 批次总量
  692. goods_out_qty=out_qty, # 本次出库量
  693. status=0,
  694. container_number=0, # 初始化为空字符串
  695. goods_weight=unit_weight, # 使用实际重量
  696. goods_total_weight=total_weight, # 计算总重量
  697. creater=bill_obj.creater,
  698. openid='ERP', # 使用单据中的openid
  699. relate_material=material,
  700. bound_list = bound_list,
  701. )
  702. batch_list.append(batch)
  703. # 生成出库明细记录
  704. detail_list.append(OutBoundDetailModel(
  705. bound_list=bound_list,
  706. bound_batch=batch,
  707. bound_batch_number=batch_obj,
  708. detail_code=f"{batch_obj.bound_number}-ODET-{material.id}",
  709. creater=bound_list.creater,
  710. openid=bound_list.openid
  711. ))
  712. # 生成批次操作日志
  713. log_list.append(BatchLogModel(
  714. batch_id=batch_obj,
  715. log_type=1,
  716. log_date=timezone.now(),
  717. goods_code=batch_obj.goods_code,
  718. goods_desc=batch_obj.goods_desc,
  719. goods_qty=-out_qty, # 出库为负值,表示减少库存
  720. log_content=f"生产出库批次创建,来源单据:{bill_obj.number},出库数量:{out_qty}",
  721. creater=batch.creater,
  722. openid=batch.openid
  723. ))
  724. # 批量写入数据库(使用事务保证一致性)
  725. try:
  726. with transaction.atomic():
  727. OutBatchModel.objects.bulk_create(batch_list)
  728. OutBoundDetailModel.objects.bulk_create(detail_list)
  729. BatchLogModel.objects.bulk_create(log_list)
  730. except Exception as e:
  731. raise Exception(f"出库批次数据保存失败: {str(e)}")
  732. def create_bound_list(self, bill_obj):
  733. """创建出入库主单(带来源标识)"""
  734. if BoundListModel.objects.filter(relate_out_bill=bill_obj,is_delete=False).exists():
  735. return BoundListModel.objects.get(relate_out_bill=bill_obj)
  736. if bill_obj.type == 1:
  737. bound_desc = f"销售出库单{bill_obj.number}"
  738. elif bill_obj.type == 2:
  739. bound_desc = f"生产领料单{bill_obj.number}"
  740. else:
  741. bound_desc = f"其他出库单{bill_obj.number}"
  742. OutboundBillOperateLog.objects.create(
  743. billId=bill_obj,
  744. log_type ='wms_audit',
  745. log_content = f"WMS创建出库单{bill_obj.number}信息,开始执行出库任务",
  746. )
  747. # 更新原始单据状态
  748. bill_obj.status = 2
  749. bill_obj.save()
  750. return BoundListModel.objects.create(
  751. bound_month=timezone.now().strftime("%Y%m"),
  752. bound_date=timezone.now().strftime("%Y-%m-%d"),
  753. bound_code=bill_obj.number,
  754. bound_code_type=bill_obj.type,
  755. bound_bs_type='B01',
  756. bound_type='out',
  757. bound_desc=bound_desc,
  758. bound_department=(bill_obj.department if bill_obj.department else 'D99'),
  759. base_type=1,
  760. bound_status='201',
  761. creater=bill_obj.creater,
  762. openid='ERP',
  763. relate_out_bill=bill_obj
  764. )
  765. def handle_exception(self, exc):
  766. """统一异常处理"""
  767. if isinstance(exc, OutboundBill.DoesNotExist):
  768. return Response({"error": "原始单据不存在或已被删除"}, status=status.HTTP_404_NOT_FOUND)
  769. elif "重复" in str(exc):
  770. return Response({"error": str(exc)}, status=status.HTTP_409_CONFLICT)
  771. return super().handle_exception(exc)
  772. """出库申请"""
  773. class OutboundApplyCreate(APIView):
  774. """
  775. 生产出库申请
  776. """
  777. authentication_classes = []
  778. permission_classes = [AllowAny]
  779. def post(self, request):
  780. logger.info('出库申请请求 | 原始数据: %s', request.data)
  781. try:
  782. total_count = len(request.data.get('materials', []))
  783. if total_count == 0 :
  784. return WMSResponse.error(
  785. message="物料清单不能为空",
  786. total=0,
  787. fail_count=0
  788. )
  789. if total_count != request.data.get('totalCount', 0):
  790. return WMSResponse.error(
  791. message="物料数量不匹配",
  792. total=total_count,
  793. fail_count=total_count
  794. )
  795. serializer = outboundPostSerializer(data=request.data)
  796. if not serializer.is_valid():
  797. print("出错",serializer.errors)
  798. return self._handle_validation_error(serializer.errors, total_count)
  799. unique_result,error_details = self.find_unique_billid_and_number(serializer)
  800. if not unique_result:
  801. return WMSResponse.error(
  802. message="单据编号或原始单据ID重复",
  803. total=total_count,
  804. fail_count=total_count,
  805. fail_materials=[{
  806. "entryIds": None,
  807. "production_batch": None,
  808. "errors": error_details
  809. }]
  810. )
  811. # 保存或更新出库单
  812. bound_bill = self.save_or_update_outbound_bill(serializer)
  813. # 保存或更新物料明细
  814. self.save_or_update_material_detail(bound_bill, serializer)
  815. return WMSResponse.success(
  816. data=serializer.data,
  817. total=total_count,
  818. success=total_count
  819. )
  820. except Exception as e:
  821. logger.exception("服务器内部错误")
  822. return WMSResponse.error(
  823. message="系统处理异常",
  824. total=total_count,
  825. fail_count=total_count,
  826. status=status.HTTP_500_INTERNAL_SERVER_ERROR,
  827. exception=e
  828. )
  829. def _handle_validation_error(self, errors, total_count):
  830. """增强错误解析"""
  831. fail_materials = []
  832. # 提取嵌套错误信息
  833. material_errors = errors.get('materials', [])
  834. for error in material_errors:
  835. # 解析DRF的错误结构
  836. if isinstance(error, dict) and 'metadata' in error:
  837. fail_materials.append({
  838. "entryIds": error['metadata'].get('entryIds'),
  839. "production_batch": error['metadata'].get('production_batch'),
  840. "errors": {
  841. "missing_fields": error['metadata']['missing_fields'],
  842. "message": error['detail']
  843. }
  844. })
  845. return WMSResponse.error(
  846. message="物料数据不完整",
  847. total=total_count,
  848. fail_count=len(fail_materials),
  849. fail_materials=fail_materials)
  850. def _format_material_errors(self, error_dict):
  851. """格式化单个物料的错误信息"""
  852. return {
  853. field: details[0] if isinstance(details, list) else details
  854. for field, details in error_dict.items()
  855. }
  856. def find_unique_billid_and_number(self, serializer):
  857. """增强版唯一性验证"""
  858. bill_id = serializer.validated_data['billId']
  859. number = serializer.validated_data['number']
  860. # 使用Q对象进行联合查询
  861. duplicates_id = OutboundBill.objects.filter(
  862. Q(billId=bill_id)
  863. ).only('billId')
  864. # 使用Q对象进行联合查询
  865. duplicates_nu = OutboundBill.objects.filter(
  866. Q(number=number)
  867. ).only( 'number')
  868. error_details = {}
  869. # 检查单据编号重复
  870. if any(obj.billId != bill_id for obj in duplicates_nu):
  871. error_details['number'] = ["number出库单编码已存在,但是系统中与之前出库单单据ID不一致,请检查"]
  872. # 检查业务编号重复
  873. if any(obj.number != number for obj in duplicates_id):
  874. error_details['billId'] = ["billId出库库单单据ID已存在,但是系统中与之前出库申请单编码不一致,请检查"]
  875. if error_details:
  876. return False,error_details
  877. return True,None
  878. def audit_save_status(self, bound_bill_type,base_type):
  879. # 根据不同入库单类型和不同出入库类型,返回审核状态和保存状态
  880. # bound_bill_type:表示不同出入库类型 :1(生产入库申请-生产汇报单)2(采购入库申请-收料通知单) 3(其他入库)4(调拨入库) 1(销售出库申请-发货通知单) 2(生产领料)3(其他出库)
  881. # 1,1 生产入库-> 0,9 (0为未审核,9为无需保存)
  882. # 2,1 采购入库-> 0,0 (0为未审核,0为未保存)
  883. # 3,1 其他入库-> 0,9 (0为未审核,9为无需保存)
  884. # 4,1 调拨入库-> 0,9 (0为未审核,9为无需保存)
  885. # 1,2 销售出库-> 9,0 (9为无需审核,0为未保存)
  886. # 2,2 生产领料-> 0,9 (0为未审核,9为无需保存)
  887. # 3,2 其他出库-> 0,9 (0为未审核,9为无需保存)
  888. # base_type:表示不同入库单类型 1 为入库 2为出库
  889. if base_type == 1: # 入库
  890. if bound_bill_type == 1: # 生产入库
  891. return 0, 9
  892. elif bound_bill_type == 2: # 采购入库
  893. return 0, 0
  894. elif bound_bill_type == 3: # 其他入库
  895. return 0, 9
  896. elif bound_bill_type == 4: # 调拨入库
  897. return 0, 9
  898. else: # 出库
  899. if bound_bill_type == 1: # 销售出库
  900. return 9, 0
  901. elif bound_bill_type == 2: # 生产领料
  902. return 0, 9
  903. elif bound_bill_type == 3: # 其他出库
  904. return 0, 9
  905. return 0, 0
  906. def save_or_update_outbound_bill(self, serializer):
  907. """保存或更新出库单"""
  908. try:
  909. bound_bill = OutboundBill.objects.get(billId=serializer.validated_data['billId'])
  910. bound_bill.number = serializer.validated_data['number']
  911. bound_bill.type = serializer.validated_data['type']
  912. bound_bill.date = serializer.validated_data['date']
  913. bound_bill.department = (serializer.validated_data['department'] if 'department' in serializer.validated_data else '')
  914. bound_bill.warehouse = serializer.validated_data['warehouse']
  915. bound_bill.creater = serializer.validated_data['creater']
  916. bound_bill.note = (serializer.validated_data['note'] if 'note' in serializer.validated_data else '')
  917. bound_bill.totalCount = serializer.validated_data['totalCount']
  918. bound_bill.erp_audit_id = bound_bill.number
  919. bound_bill.erp_save_id = bound_bill.billId
  920. bound_bill.audit_status ,bound_bill.save_status = self.audit_save_status(bound_bill.type,2)
  921. bound_bill.update_time = timezone.now()
  922. bound_bill.is_delete = False
  923. bound_bill.save()
  924. OutboundBillOperateLog.objects.create(
  925. billId=bound_bill,
  926. log_type ='update',
  927. log_content = f"ERP更新出库单{bound_bill.number}信息",
  928. )
  929. except OutboundBill.DoesNotExist:
  930. audit_status, save_status = self.audit_save_status(serializer.validated_data['type'], 2)
  931. bound_bill = OutboundBill.objects.create(
  932. billId=serializer.validated_data['billId'],
  933. number=serializer.validated_data['number'],
  934. type=serializer.validated_data['type'],
  935. date=serializer.validated_data['date'],
  936. department=(serializer.validated_data['department'] if 'department' in serializer.validated_data else ''),
  937. warehouse=serializer.validated_data['warehouse'],
  938. creater=serializer.validated_data['creater'],
  939. note=(serializer.validated_data['note'] if 'note' in serializer.validated_data else ''),
  940. totalCount=serializer.validated_data['totalCount'],
  941. erp_audit_id = serializer.validated_data['number'],
  942. erp_save_id = serializer.validated_data['billId'],
  943. audit_status = audit_status,
  944. save_status = save_status,
  945. create_time=timezone.now(),
  946. update_time=timezone.now()
  947. )
  948. OutboundBillOperateLog.objects.create(
  949. billId=bound_bill,
  950. log_type ='create',
  951. log_content = f"ERP创建出库单{bound_bill.number}信息",
  952. )
  953. return bound_bill
  954. def save_or_update_material_detail(self, bound_bill, serializer):
  955. """保存或更新物料明细"""
  956. for item in serializer.validated_data['materials']:
  957. try:
  958. material_detail = OutMaterialDetail.objects.get(bound_billId=bound_bill, entryIds=item['entryIds'])
  959. Material_entryIds = MaterialDetail.objects.filter(
  960. goods_code = item['goods_code'],
  961. production_batch = item['production_batch']
  962. ).first()
  963. if not Material_entryIds:
  964. logger.info("出库单号%s,更新——物料明细不存在",bound_bill.number)
  965. material_detail.Material_entryIds = Material_entryIds
  966. material_detail.production_batch = item['production_batch']
  967. material_detail.goods_code = item['goods_code']
  968. material_detail.goods_name = item['goods_name']
  969. material_detail.goods_out_qty = item['goods_out_qty']
  970. material_detail.goods_total_weight = item['goods_out_qty']
  971. material_detail.goods_unit = item['goods_unit']
  972. material_detail.note = (item['note'] if 'note' in item else '')
  973. material_detail.update_time = timezone.now()
  974. material_detail.is_delete = False
  975. material_detail.save()
  976. except OutMaterialDetail.DoesNotExist:
  977. Material_entryIds = MaterialDetail.objects.filter(
  978. goods_code = item['goods_code'],
  979. production_batch = item['production_batch']
  980. ).first()
  981. if not Material_entryIds:
  982. logger.info("出库单号%s,创建——物料明细不存在",bound_bill.number)
  983. material_detail = OutMaterialDetail.objects.create(
  984. bound_billId=bound_bill,
  985. entryIds=item['entryIds'],
  986. Material_entryIds=Material_entryIds,
  987. production_batch=item['production_batch'],
  988. goods_code=item['goods_code'],
  989. goods_name=item['goods_name'],
  990. goods_weight=1,
  991. goods_out_qty=item['goods_out_qty'],
  992. goods_total_weight=item['goods_out_qty'],
  993. goods_unit=item['goods_unit'],
  994. note=(item['note'] if 'note' in item else ''),
  995. create_time=timezone.now(),
  996. update_time=timezone.now()
  997. )
  998. return material_detail
  999. """产品信息"""
  1000. class ProductInfo(APIView):
  1001. """
  1002. 批次信息更新
  1003. """
  1004. authentication_classes = [] # 禁用所有认证类
  1005. permission_classes = [AllowAny] # 允许任意访问
  1006. # parser_classes = [TextJSONParser] # 强制使用 text/json
  1007. # renderer_classes = [TextJSONRenderer] # 强制使用 text/json
  1008. def post(self, request):
  1009. data = request.data
  1010. logger.info('批次信息更新 | 原始数据: %s', data)
  1011. total_count = data.get('totalCount', 0)
  1012. materials = data.get('materials', [])
  1013. success_count = 0
  1014. fail_count = 0
  1015. fail_materials = []
  1016. try:
  1017. with transaction.atomic(): # 开启事务确保原子性
  1018. # 预查询已存在的产品ID
  1019. existing_ids = set(ProductListModel.objects.filter(
  1020. id__in=[m.get('id') for m in materials if m.get('id')]
  1021. ).values_list('id', flat=True))
  1022. for material in materials:
  1023. material_id = material.get('id')
  1024. try:
  1025. if material_id and material_id in existing_ids:
  1026. instance = ProductListModel.objects.get(id=material_id)
  1027. created = False
  1028. else:
  1029. instance = ProductListModel()
  1030. created = True
  1031. # 字段映射与校验
  1032. instance.id = material_id
  1033. instance.product_code = material.get('product_code', instance.product_code)
  1034. instance.product_name = material.get('product_name', instance.product_name)
  1035. instance.product_std = material.get('product_std', instance.product_std or 'on std')
  1036. instance.product_unit = material.get('product_unit', instance.product_unit or 'KG')
  1037. # 必填字段校验[7](@ref)
  1038. required_fields = ['product_code', 'product_name']
  1039. if any(not getattr(instance, field) for field in required_fields):
  1040. raise ValueError(f"Missing required fields: {required_fields}")
  1041. instance.is_delete = False # 强制重置删除标记[1](@ref)
  1042. instance.full_clean() # 触发模型验证[3](@ref)
  1043. instance.save()
  1044. success_count += 1
  1045. except Exception as e:
  1046. fail_count += 1
  1047. error_msg = f"{type(e).__name__}: {str(e)}"
  1048. logger.warning(f"Material processing failed: {material} | Error: {error_msg}")
  1049. fail_materials.append({
  1050. **material,
  1051. "error": error_msg
  1052. })
  1053. # 检查总数一致性[7](@ref)
  1054. if success_count != total_count:
  1055. return WMSResponse.error(
  1056. message="物料数量不匹配",
  1057. total=total_count,
  1058. fail_count=total_count,
  1059. fail_materials=fail_materials
  1060. )
  1061. except Exception as e:
  1062. logger.error(f"Batch update transaction failed: {str(e)}", exc_info=True)
  1063. return WMSResponse.error(
  1064. message=f"批量处理失败: {str(e)}",
  1065. total=total_count,
  1066. fail_count=fail_count,
  1067. fail_materials=fail_materials,
  1068. exception=e
  1069. )
  1070. return WMSResponse.success(
  1071. data=[], # 根据需求可返回处理后的数据
  1072. total=total_count,
  1073. success=success_count
  1074. )
  1075. """批次更新"""
  1076. class BatchUpdate(APIView):
  1077. """
  1078. 商品信息查询
  1079. """
  1080. authentication_classes = [] # 禁用所有认证类
  1081. permission_classes = [AllowAny] # 允许任意访问
  1082. def post(self, request):
  1083. data = request.data
  1084. total_count = data.get('totalCount', 0)
  1085. material_audit_id = data.get('billnos')
  1086. materials = data.get('materials', [])
  1087. success_count = 0
  1088. fail_count = 0
  1089. fail_materials = []
  1090. try:
  1091. with transaction.atomic(): # 开启事务确保原子性
  1092. if total_count != len(materials):
  1093. return WMSResponse.error(
  1094. message="物料数量不匹配",
  1095. total=total_count,
  1096. fail_count=total_count
  1097. )
  1098. for material in materials:
  1099. material_billId = material.get('billId')
  1100. material_entryId = material.get('entryIds')
  1101. material_status = material.get('status')
  1102. if material_status == 'passing':
  1103. try:
  1104. bill_obj = InboundBill.objects.get(billId=material_billId)
  1105. if not bill_obj:
  1106. logger.info("入库单不存在")
  1107. fail_materials.append({
  1108. **material,
  1109. "error": "入库单不存在"
  1110. })
  1111. fail_count += 1
  1112. continue
  1113. bill_obj.erp_audit_id = material_audit_id
  1114. instance = MaterialDetail.objects.get(bound_billId_id=material_billId,entryIds=material_entryId)
  1115. if not instance:
  1116. logger.info("物料明细不存在")
  1117. fail_materials.append({
  1118. **material,
  1119. "error": "物料明细不存在"
  1120. })
  1121. fail_count += 1
  1122. continue
  1123. if instance.status == 0:
  1124. InboundBillOperateLog.objects.create(
  1125. billId=bill_obj,
  1126. log_type ='update_batch',
  1127. log_content = f"物料明细{instance.goods_name},质检通过",
  1128. )
  1129. instance.status = 1
  1130. logger.info("[1]入库单号%s,物料明细%s,更新状态,审核通过%s",bill_obj.number,material_entryId,material_audit_id)
  1131. logger.info("[2]入库单号%s,物料明细%s,更新状态,审核通过%s",bill_obj.number,material_entryId,bill_obj.erp_audit_id)
  1132. instance.save()
  1133. bill_obj.save()
  1134. success_count += 1
  1135. except Exception as e:
  1136. fail_count += 1
  1137. error_msg = f"{type(e).__name__}: {str(e)}"
  1138. logger.warning(f"Material processing failed: {material} | Error: {error_msg}")
  1139. fail_materials.append({
  1140. **material,
  1141. "error": error_msg
  1142. })
  1143. # 检查总数一致性[7](@ref)
  1144. if success_count != total_count:
  1145. return WMSResponse.error(
  1146. message="单据编码与详细编码不匹配",
  1147. total=total_count,
  1148. fail_count=total_count,
  1149. fail_materials=fail_materials
  1150. )
  1151. except Exception as e:
  1152. logger.error(f"Batch update transaction failed: {str(e)}", exc_info=True)
  1153. return WMSResponse.error(
  1154. message=f"批量处理失败: {str(e)}",
  1155. total=total_count,
  1156. fail_count=fail_count,
  1157. fail_materials=fail_materials,
  1158. exception=e
  1159. )
  1160. return WMSResponse.success(
  1161. data=[],
  1162. total=total_count,
  1163. success=success_count
  1164. )
  1165. """token"""
  1166. class AccessToken(APIView):
  1167. """
  1168. 获取ERP的access_token
  1169. 方法:post到
  1170. https://okyy.test.kdgalaxy.com/kapi/oauth2/getToken
  1171. 参数:
  1172. {
  1173. "client_id" : "WMS",
  1174. "client_secret" : "1Ca~2Tu-3Fx$3Rg@",
  1175. "username" : "xs",
  1176. "accountId" : "2154719510106474496",
  1177. "nonce" : "2025-04-27 11:36:08",
  1178. "timestamp" : "2025-04-27 11:36:08",
  1179. "language" : "zh_CN"
  1180. }
  1181. 返回:
  1182. {
  1183. "data": {
  1184. "access_token": "CanAzMDM=",
  1185. "token_type": "Bearer",
  1186. "refresh_token": "4297d40e-b2ac-48b4-98a2-b50665e6faaf",
  1187. "scope": "API",
  1188. "expires_in": 7199990,
  1189. "id_token": "d09UWXhOakV4TnpjMkE9EVGVV",
  1190. "id_token_expires_in": 7199990,
  1191. "language": "zh_CN"
  1192. },
  1193. "errorCode": "0",
  1194. "message": "",
  1195. "status": true
  1196. }
  1197. """
  1198. authentication_classes = [] # 禁用所有认证类
  1199. permission_classes = [AllowAny] # 允许任意访问
  1200. @classmethod
  1201. def get_token(cls):
  1202. try:
  1203. """获取access_token"""
  1204. # url = "https://okyy.test.kdgalaxy.com/kapi/oauth2/getToken" # 测试环境
  1205. url = "https://okyy.kdgalaxy.com/kapi/oauth2/getToken"
  1206. data = {
  1207. "client_id" : "WMS",
  1208. "client_secret" : "1Ca~2Tu-3Fx$3Rg@",
  1209. "username" : "xs",
  1210. "accountId" : "2154719510106474496",
  1211. "nonce" : timezone.now().strftime("%Y-%m-%d %H:%M:%S"),
  1212. "timestamp" : timezone.now().strftime("%Y-%m-%d %H:%M:%S"),
  1213. "language" : "zh_CN"
  1214. }
  1215. print("请求参数",data)
  1216. response = requests.post(url, json=data,timeout=10)
  1217. if response.status_code == 200:
  1218. result = response.json()
  1219. if result.get('status'):
  1220. logger.info(f"获取access_token成功 | access_token: {result.get('data',{}).get('access_token')}")
  1221. return result.get('data',{}).get('access_token')
  1222. return None
  1223. except Exception as e:
  1224. print("获取access_token异常",e)
  1225. logger.exception("获取access_token异常")
  1226. return None
  1227. @classmethod
  1228. def get_current_token(cls):
  1229. """获取当前有效Token(带缓存机制)"""
  1230. cache_key = 'erp_access_token'
  1231. cached_token = cache.get(cache_key)
  1232. if not cached_token:
  1233. new_token = cls.get_token()
  1234. if new_token:
  1235. # 缓存时间略短于实际有效期
  1236. cache.set(cache_key, new_token, timeout=1000)
  1237. return new_token
  1238. return cached_token
  1239. """基本同步业务类"""
  1240. class ERPSyncBase:
  1241. """ERP同步基类(作为发送方)"""
  1242. max_retries = 30 # 最大重试次数
  1243. retry_delay = 30
  1244. # 重试间隔秒数
  1245. def __init__(self, wms_bill,entryIds):
  1246. self.wms_bill = wms_bill # WMS单据对象
  1247. self.entryIds = entryIds # 物料明细ID数组
  1248. self.erp_id_field = None # 需要更新的ERP ID字段名
  1249. def build_erp_payload(self):
  1250. """构造ERP请求数据(需子类实现)"""
  1251. raise NotImplementedError
  1252. def get_erp_endpoint(self):
  1253. """获取ERP接口地址(需子类实现)"""
  1254. raise NotImplementedError
  1255. def process_erp_response(self, response):
  1256. """处理ERP响应(需子类实现)返回erp_id"""
  1257. raise NotImplementedError
  1258. def execute_sync(self):
  1259. """执行同步操作"""
  1260. # 测试环境 @ todo
  1261. headers = {
  1262. 'accessToken': f'{AccessToken.get_current_token()}',
  1263. 'x-acgw-identity': 'djF8MTk2M2QzMWEzMjUwMTZlMzA3MDF8NDg5ODM4MzM4NjE3OHwYjYJyvo-DbkhOliEpFtiFOsCgKKo6braaiQGE9qdNx3w='
  1264. }
  1265. for attempt in range(self.max_retries):
  1266. try:
  1267. print("请求头:",headers)
  1268. print("请求体:",self.build_erp_payload())
  1269. print("请求地址:",self.get_erp_endpoint())
  1270. response = requests.post(
  1271. self.get_erp_endpoint(),
  1272. json=self.build_erp_payload(),
  1273. headers=headers,
  1274. timeout=60
  1275. )
  1276. response.raise_for_status()
  1277. return self.process_erp_response(response.json())
  1278. except requests.exceptions.HTTPError as http_err:
  1279. if response.status_code == 519:
  1280. print("特定HTTP错误 519:", http_err)
  1281. logger.error(f"ERP接口HTTP错误 519 第{attempt+1}次重试 | 单据:{self.wms_bill.number} | 错误: {http_err}")
  1282. else:
  1283. print("HTTP错误:", http_err)
  1284. logger.error(f"ERP接口HTTP错误 第{attempt+1}次重试 | 单据:{self.wms_bill.number} | 错误: {http_err}")
  1285. time.sleep(self.retry_delay)
  1286. except requests.exceptions.RequestException as e:
  1287. print("ERP接口请求异常:",e)
  1288. print(f"ERP接口请求失败 第{attempt+1}次重试 | 单据:{self.wms_bill.number}")
  1289. logger.error(f"ERP接口请求失败 第{attempt+1}次重试 | 单据:{self.wms_bill.number}")
  1290. time.sleep(self.retry_delay)
  1291. logger.error(f"ERP同步最终失败 | 单据:{self.wms_bill.number}")
  1292. return False
  1293. # ==================== 业务接口 ====================
  1294. """生产入库审核"""
  1295. class ProductionInboundAuditSync(ERPSyncBase):
  1296. erp_id_field = 'erp_audit_id'
  1297. # 请求地址
  1298. def get_erp_endpoint(self):
  1299. # return "https://okyy.test.kdgalaxy.com/kapi/v2/l772/im/im_mdc_mftmanuinbill/audit"
  1300. return "https://okyy.kdgalaxy.com/kapi/v2/l772/im/im_mdc_mftmanuinbill/audit"
  1301. # 请求参数
  1302. # {
  1303. # "data":{
  1304. # "billnos":[
  1305. # "AgTSC",
  1306. # "fgBAH"
  1307. # ]
  1308. # }
  1309. # }
  1310. def build_erp_payload(self):
  1311. return {
  1312. "data": {
  1313. "billnos": [
  1314. self.wms_bill.erp_audit_id,
  1315. ]
  1316. }
  1317. }
  1318. # 处理响应
  1319. def process_erp_response(self, response):
  1320. logger.info("ERP审核响应:",response)
  1321. if response['status']:
  1322. self.wms_bill.audit_status = 1
  1323. self.wms_bill.save()
  1324. return response['status']
  1325. """采购收料入库审核"""
  1326. class PurchaseInboundAuditSync(ERPSyncBase):
  1327. erp_id_field = 'erp_audit_id'
  1328. # 请求地址
  1329. def get_erp_endpoint(self):
  1330. # return "https://okyy.test.kdgalaxy.com/kapi/v2/l772/im/im_purreceivebill/audit"
  1331. return "https://okyy.kdgalaxy.com/kapi/v2/l772/im/im_purreceivebill/audit"
  1332. # 请求参数
  1333. # {
  1334. # "data":{
  1335. # "billnos":[
  1336. # "AgTSC",
  1337. # "fgBAH"
  1338. # ]
  1339. # }
  1340. # }
  1341. def build_erp_payload(self):
  1342. return {
  1343. "data": {
  1344. "billnos": [
  1345. self.wms_bill.erp_audit_id,
  1346. ]
  1347. }
  1348. }
  1349. # 处理响应
  1350. def process_erp_response(self, response):
  1351. logger.info("ERP审核响应:",response)
  1352. if response['status']:
  1353. self.wms_bill.audit_status = 1
  1354. self.wms_bill.save()
  1355. return response['status']
  1356. """其他入库审核"""
  1357. class OtherInboundAuditSync(ERPSyncBase):
  1358. erp_id_field = 'erp_audit_id'
  1359. # 请求地址
  1360. def get_erp_endpoint(self):
  1361. # return "https://okyy.test.kdgalaxy.com/kapi/v2/l772/im/im_otherinbill/audit"
  1362. return "https://okyy.kdgalaxy.com/kapi/v2/l772/im/im_otherinbill/audit"
  1363. # 请求参数
  1364. # {
  1365. # "data":{
  1366. # "billnos":[
  1367. # "AgTSC",
  1368. # "fgBAH"
  1369. # ]
  1370. # }
  1371. # }
  1372. def build_erp_payload(self):
  1373. return {
  1374. "data": {
  1375. "billnos": [
  1376. self.wms_bill.erp_audit_id,
  1377. ]
  1378. }
  1379. }
  1380. # 处理响应
  1381. def process_erp_response(self, response):
  1382. logger.info("ERP审核响应:",response['message'])
  1383. if response['status']:
  1384. self.wms_bill.audit_status = 1
  1385. self.wms_bill.save()
  1386. return response['status']
  1387. """调拨入库审核"""
  1388. class TransferInboundAuditSync(ERPSyncBase):
  1389. erp_id_field = 'erp_audit_id'
  1390. # 请求地址
  1391. def get_erp_endpoint(self):
  1392. # return "https://okyy.test.kdgalaxy.com/kapi/v2/l772/im/im_transdirbill/audit"
  1393. return "https://okyy.kdgalaxy.com/kapi/v2/l772/im/im_transdirbill/audit"
  1394. # 请求参数
  1395. # {
  1396. # "data":{
  1397. # "billnos":[
  1398. # "AgTSC",
  1399. # "fgBAH"
  1400. # ]
  1401. # }
  1402. # }
  1403. def build_erp_payload(self):
  1404. return {
  1405. "data": {
  1406. "billnos": [
  1407. self.wms_bill.erp_audit_id,
  1408. ]
  1409. }
  1410. }
  1411. # 处理响应
  1412. def process_erp_response(self, response):
  1413. logger.info("ERP审核响应:",response)
  1414. if response['status']:
  1415. self.wms_bill.audit_status = 1
  1416. self.wms_bill.save()
  1417. return response['status']
  1418. """其他出库审核"""
  1419. class OtherOutboundAuditSync(ERPSyncBase):
  1420. erp_id_field = 'erp_audit_id'
  1421. # 请求地址
  1422. def get_erp_endpoint(self):
  1423. return "https://okyy.test.kdgalaxy.com/kapi/v2/l772/im/im_otheroutbill/audit"
  1424. # 请求参数
  1425. # {
  1426. # "data":{
  1427. # "billnos":[
  1428. # "AgTSC",
  1429. # "fgBAH"
  1430. # ]
  1431. # }
  1432. # }
  1433. def build_erp_payload(self):
  1434. return {
  1435. "data": {
  1436. "billnos": [
  1437. self.wms_bill.erp_audit_id,
  1438. ]
  1439. }
  1440. }
  1441. # 处理响应
  1442. def process_erp_response(self, response):
  1443. logger.info("ERP审核响应:",response)
  1444. if response['status']:
  1445. self.wms_bill.audit_status = 1
  1446. self.wms_bill.save()
  1447. return response['status']
  1448. """生产领料出库审核"""
  1449. class ProductionOutboundAuditSync(ERPSyncBase):
  1450. erp_id_field = 'erp_audit_id'
  1451. # 请求地址
  1452. def get_erp_endpoint(self):
  1453. # return "https://okyy.test.kdgalaxy.com/kapi/v2/l772/im/im_mdc_mftproorder/audit"
  1454. return "https://okyy.kdgalaxy.com/kapi/v2/l772/im/im_mdc_mftproorder/audit"
  1455. # 请求参数
  1456. # {
  1457. # "data":{
  1458. # "billnos":[
  1459. # "AgTSC",
  1460. # "fgBAH"
  1461. # ]
  1462. # }
  1463. # }
  1464. def build_erp_payload(self):
  1465. return {
  1466. "data": {
  1467. "billnos": [
  1468. self.wms_bill.erp_audit_id,
  1469. ]
  1470. }
  1471. }
  1472. # 处理响应
  1473. def process_erp_response(self, response):
  1474. logger.info("ERP审核响应:",response['message'],response['status'])
  1475. if response['status']:
  1476. self.wms_bill.audit_status = 1
  1477. self.wms_bill.save()
  1478. return response['status']
  1479. """采购入库保存"""
  1480. class PurchaseInboundSaveSync(ERPSyncBase):
  1481. erp_id_field = 'erp_save_id'
  1482. def get_erp_endpoint(self):
  1483. # return "https://okyy.test.kdgalaxy.com/kapi/v2/l772/im/im_purinbill/save"
  1484. return "https://okyy.kdgalaxy.com/kapi/v2/l772/im/im_purinbill/save"
  1485. def build_erp_payload(self):
  1486. # {
  1487. # "purinbill":{
  1488. # "billId":"1745732021174",
  1489. # "entryIds":[
  1490. # "1745732021087"
  1491. # ]
  1492. # }
  1493. # }
  1494. return {
  1495. "purinbill": {
  1496. "billId":self.wms_bill.erp_save_id,
  1497. "entryIds":
  1498. self.entryIds,
  1499. }
  1500. }
  1501. def process_erp_response(self, response):
  1502. logger.info("ERP审核响应:",response['message'])
  1503. if response['status']:
  1504. InboundBillOperateLog.objects.create(
  1505. billId=self.wms_bill,
  1506. log_type ='erp_save',
  1507. log_content = f"保存入库单{self.wms_bill.number}信息",
  1508. )
  1509. self.wms_bill.save_status = 1
  1510. self.wms_bill.save()
  1511. return response['status']
  1512. """销售出库保存"""
  1513. class SaleOutboundSaveSync(ERPSyncBase):
  1514. erp_id_field = 'erp_save_id'
  1515. def get_erp_endpoint(self):
  1516. # return "https://okyy.test.kdgalaxy.com/kapi/v2/l772/im/im_saloutbill/save"
  1517. return "https://okyy.kdgalaxy.com/kapi/v2/l772/im/im_saloutbill/save"
  1518. def build_erp_payload(self):
  1519. # {
  1520. # "saloutbill":{
  1521. # "billId":"1745732823064",
  1522. # "entryIds":[
  1523. # "1745732823073"
  1524. # ]
  1525. # }
  1526. # }
  1527. return {
  1528. "saloutbill": {
  1529. "billId":self.wms_bill.erp_save_id,
  1530. "entryIds":
  1531. self.entryIds,
  1532. }
  1533. }
  1534. def process_erp_response(self, response):
  1535. logger.info("ERP审核响应:",response)
  1536. if response['status']:
  1537. OutboundBillOperateLog.objects.create(
  1538. billId=self.wms_bill,
  1539. log_type ='erp_save',
  1540. log_content = f"保存出库单{self.wms_bill.number}信息",
  1541. )
  1542. self.wms_bill.save_status = 1
  1543. self.wms_bill.save()
  1544. return response['status']
  1545. """审核与保存接口"""
  1546. class bound_apply(APIView):
  1547. """
  1548. 入库单审核与保存
  1549. bill_base :0 入库单 1 出库单
  1550. bill_type :1 生产入库 2 采购入库 3 其他入库 4 调拨入库 2 生产出库 1 销售出库 3 其他出库
  1551. """
  1552. def post(self, request, action_type):
  1553. """统一处理 POST 请求,根据 action_type 分发逻辑"""
  1554. if action_type == 'audit':
  1555. # 调用 audit 逻辑
  1556. return self._audit(request)
  1557. elif action_type == 'save':
  1558. # 调用 save 逻辑
  1559. return self._save(request)
  1560. else:
  1561. return Response({'message': '无效操作'}, status=status.HTTP_400_BAD_REQUEST)
  1562. def _audit(self, request):
  1563. """统一审核逻辑"""
  1564. # 参数校验
  1565. if error_response := self._validate_audit_params(request.data):
  1566. return error_response
  1567. try:
  1568. # 获取审核配置
  1569. config = self._get_audit_config(request.data['billbase'], request.data['billtype'])
  1570. if not config:
  1571. return Response({'message': '无效的业务类型'}, status=status.HTTP_400_BAD_REQUEST)
  1572. # 处理审核业务
  1573. return self._process_audit(
  1574. bill_id=request.data['billid'],
  1575. config=config
  1576. )
  1577. except Exception as e:
  1578. logger.error(f"审核异常: {str(e)}", exc_info=True)
  1579. return Response({'message': '服务器处理失败'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
  1580. def _validate_audit_params(self, data):
  1581. """参数验证"""
  1582. required_params = {'billid', 'billtype', 'billbase'}
  1583. if missing := [p for p in required_params if p not in data]:
  1584. return Response(
  1585. {'message': f'缺少必要参数: {", ".join(missing)}'},
  1586. status=status.HTTP_400_BAD_REQUEST
  1587. )
  1588. return None
  1589. def _get_audit_config(self, bill_base, bill_type):
  1590. """获取审核配置"""
  1591. config_map = {
  1592. # 入库单配置 (bill_base=0)
  1593. (0, 1): {'model': InboundBill, 'sync_class': ProductionInboundAuditSync, 'log_model': InboundBillOperateLog},
  1594. (0, 2): {'model': InboundBill, 'sync_class': PurchaseInboundAuditSync, 'log_model': InboundBillOperateLog},
  1595. (0, 3): {'model': InboundBill, 'sync_class': OtherInboundAuditSync, 'log_model': InboundBillOperateLog},
  1596. (0, 4): {'model': InboundBill, 'sync_class': TransferInboundAuditSync, 'log_model': InboundBillOperateLog},
  1597. # 出库单配置 (bill_base=1)
  1598. (1, 2): {'model': OutboundBill, 'sync_class': ProductionOutboundAuditSync, 'log_model': OutboundBillOperateLog},
  1599. (1, 3): {'model': OutboundBill, 'sync_class': OtherOutboundAuditSync, 'log_model': OutboundBillOperateLog}
  1600. }
  1601. return config_map.get((bill_base, bill_type))
  1602. def _process_audit(self, bill_id, config):
  1603. """执行审核流程"""
  1604. # 获取单据对象
  1605. bill_obj = config['model'].objects.filter(billId=bill_id).first()
  1606. if not bill_obj:
  1607. return Response({'message': '单据不存在'}, status=status.HTTP_404_NOT_FOUND)
  1608. # 执行同步操作
  1609. sync_result = self._execute_sync(
  1610. sync_class=config['sync_class'],
  1611. bill_obj=bill_obj,
  1612. material_ids=[]
  1613. )
  1614. if not sync_result:
  1615. return Response({'message': 'ERP审核失败'}, status=status.HTTP_404_NOT_FOUND)
  1616. # 记录操作日志
  1617. self._create_audit_log(
  1618. log_model=config['log_model'],
  1619. bill_obj=bill_obj
  1620. )
  1621. return Response({'message': '审核成功'}, status=status.HTTP_200_OK)
  1622. def _execute_sync(self, sync_class, bill_obj, material_ids):
  1623. """执行ERP同步"""
  1624. try:
  1625. return sync_class(bill_obj, material_ids).execute_sync()
  1626. except Exception as e:
  1627. logger.error(f"ERP同步失败: {str(e)}")
  1628. return False
  1629. def _create_audit_log(self, log_model, bill_obj):
  1630. """创建审核日志"""
  1631. log_model.objects.create(
  1632. billId=bill_obj,
  1633. log_type='erp_audit',
  1634. log_content='ERP审核成功'
  1635. )
  1636. def _save(self,request):
  1637. """保存"""
  1638. bill_id = request.data.get('billid', None)
  1639. bill_type = request.data.get('billtype', None)
  1640. bill_base = request.data.get('billbase', None)
  1641. if bill_id is None or bill_type is None or bill_base is None:
  1642. return Response({'message': '参数错误'}, status=status.HTTP_400_BAD_REQUEST)
  1643. try:
  1644. if bill_base == 0:
  1645. if bill_type == 2:
  1646. # 采购入库保存
  1647. bill_obj = InboundBill.objects.filter(billId=bill_id).first()
  1648. entryIds = list(MaterialDetail.objects.filter(bound_billId=bill_id).values_list('entryIds', flat=True))
  1649. if bill_obj:
  1650. logger.info(f"[单据ID]:{bill_obj.billId}")
  1651. sync_obj = PurchaseInboundSaveSync(bill_obj,entryIds)
  1652. sync_result = sync_obj.execute_sync()
  1653. return Response({'message': sync_result}, status=status.HTTP_200_OK)
  1654. else:
  1655. return Response({'message': '单据不存在'}, status=status.HTTP_400_BAD_REQUEST)
  1656. elif bill_base == 1:
  1657. if bill_type == 1:
  1658. # 销售出库保存
  1659. bill_obj = OutboundBill.objects.filter(billId=bill_id).first()
  1660. entryIds = list(OutMaterialDetail.objects.filter(bound_billId=bill_id).values_list('entryIds', flat=True))
  1661. if bill_obj:
  1662. sync_obj = SaleOutboundSaveSync(bill_obj,entryIds)
  1663. sync_result = sync_obj.execute_sync()
  1664. return Response({'message': sync_result}, status=status.HTTP_200_OK)
  1665. else:
  1666. return Response({'message': '单据不存在'}, status=status.HTTP_400_BAD_REQUEST)
  1667. else:
  1668. return Response({'message': '无需保存'}, status=status.HTTP_200_OK)
  1669. except Exception as e:
  1670. return Response({'message': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
  1671. """前端视图类·ERP入库"""
  1672. class InboundBills(viewsets.ModelViewSet):
  1673. """
  1674. retrieve:
  1675. Response a data list(get)
  1676. list:
  1677. Response a data list(all)
  1678. """
  1679. # authentication_classes = [] # 禁用所有认证类
  1680. # permission_classes = [AllowAny] # 允许任意访问
  1681. pagination_class = MyPageNumberPagination
  1682. filter_backends = [DjangoFilterBackend, OrderingFilter, ]
  1683. ordering_fields = ["update_time", "create_time"]
  1684. filter_class = InboundBillFilter
  1685. def get_project(self):
  1686. # 获取项目ID,如果不存在则返回None
  1687. try:
  1688. id = self.kwargs.get('pk')
  1689. return id
  1690. except:
  1691. return None
  1692. def get_queryset(self):
  1693. # 根据请求用户过滤查询集
  1694. id = self.get_project()
  1695. if self.request.user:
  1696. if id is None:
  1697. return InboundBill.objects.filter(is_delete=False)
  1698. else:
  1699. return InboundBill.objects.filter(billId=id, is_delete=False)
  1700. else:
  1701. return InboundBill.objects.none()
  1702. def get_serializer_class(self):
  1703. # 根据操作类型选择合适的序列化器
  1704. if self.action in ['list', 'retrieve']:
  1705. return InboundApplySerializer
  1706. else:
  1707. return self.http_method_not_allowed(request=self.request)
  1708. def get_bound_number(self,request):
  1709. billid = request.data.get('billid', None)
  1710. bill_obj = InboundBill.objects.filter(billId=billid).first()
  1711. return_data = {}
  1712. if bill_obj:
  1713. return_data['bill_number'] = bill_obj.number
  1714. return_data['bill_audit'] = bill_obj.erp_audit_id
  1715. return_data['bill_save'] = bill_obj.erp_save_id
  1716. return_data['bill_status'] = bill_obj.bound_status
  1717. return_data['bill_type'] = bill_obj.type
  1718. return Response(return_data,status=status.HTTP_200_OK)
  1719. def destroy(self, request, pk):
  1720. qs = self.get_object()
  1721. qs.is_delete = True
  1722. MaterialDetail.objects.filter(bound_billId=qs).update(is_delete=True)
  1723. qs.save()
  1724. # import datetime
  1725. # qs.save()
  1726. # qs.billId = f"404{qs.billId}{datetime.datetime.now().strftime('%Y%m%d%H%M%S')}"
  1727. # qs.number = f"deleted_{qs.number}_{datetime.datetime.now().strftime('%Y%m%d%H%M%S')}"
  1728. # qs.save()
  1729. return Response({'message': '删除成功'}, status=status.HTTP_200_OK)
  1730. """前端视图类·ERP出库"""
  1731. class OutboundBills(viewsets.ModelViewSet):
  1732. """
  1733. retrieve:
  1734. Response a data list(get)
  1735. list:
  1736. Response a data list(all)
  1737. """
  1738. # authentication_classes = [] # 禁用所有认证类
  1739. # permission_classes = [AllowAny] # 允许任意访问
  1740. pagination_class = MyPageNumberPagination
  1741. filter_backends = [DjangoFilterBackend, OrderingFilter, ]
  1742. ordering_fields = ["update_time", "create_time"]
  1743. filter_class = OutboundBillFilter
  1744. def get_project(self):
  1745. # 获取项目ID,如果不存在则返回None
  1746. try:
  1747. id = self.kwargs.get('pk')
  1748. return id
  1749. except:
  1750. return None
  1751. def get_queryset(self):
  1752. # 根据请求用户过滤查询集
  1753. id = self.get_project()
  1754. if self.request.user:
  1755. if id is None:
  1756. return OutboundBill.objects.filter(is_delete=False)
  1757. else:
  1758. return OutboundBill.objects.filter(billId=id, is_delete=False)
  1759. else:
  1760. return OutboundBill.objects.none()
  1761. def get_serializer_class(self):
  1762. # 根据操作类型选择合适的序列化器
  1763. if self.action in ['list', 'retrieve', ]:
  1764. return OutboundApplySerializer
  1765. else:
  1766. return self.http_method_not_allowed(request=self.request)
  1767. def get_bound_number(self,request):
  1768. billid = request.data.get('billid', None)
  1769. bill_obj = OutboundBill.objects.filter(billId=billid).first()
  1770. return_data = {}
  1771. if bill_obj:
  1772. return_data['bill_number'] = bill_obj.number
  1773. return_data['bill_audit'] = bill_obj.erp_audit_id
  1774. return_data['bill_save'] = bill_obj.erp_save_id
  1775. return_data['bill_status'] = bill_obj.bound_status
  1776. return_data['bill_type'] = bill_obj.type
  1777. return Response(return_data,status=status.HTTP_200_OK)
  1778. def destroy(self, request, pk):
  1779. qs = self.get_object()
  1780. qs.is_delete = True
  1781. OutMaterialDetail.objects.filter(bound_billId=qs).update(is_delete=True)
  1782. qs.save()
  1783. # import datetime
  1784. # qs.save()
  1785. # qs.billId = f"404{qs.billId}{datetime.datetime.now().strftime('%Y%m%d%H%M%S')}"
  1786. # qs.number = f"deleted_{qs.number}_{datetime.datetime.now().strftime('%Y%m%d%H%M%S')}"
  1787. # qs.save()
  1788. return Response({'message': '删除成功'}, status=status.HTTP_200_OK)
  1789. class Materials(viewsets.ModelViewSet):
  1790. """
  1791. retrieve:
  1792. Response a data list(get)
  1793. list:
  1794. Response a data list(all)
  1795. """
  1796. # authentication_classes = [] # 禁用所有认证类
  1797. # permission_classes = [AllowAny] # 允许任意访问
  1798. pagination_class = MyPageNumberPagination
  1799. filter_backends = [DjangoFilterBackend, OrderingFilter, ]
  1800. ordering_fields = ['id', "create_time", "update_time", ]
  1801. filter_class = MaterialDetailFilter
  1802. def get_project(self):
  1803. try:
  1804. id = self.kwargs.get('pk')
  1805. return id
  1806. except:
  1807. return None
  1808. def get_queryset(self):
  1809. id = self.get_project()
  1810. if self.request.user:
  1811. if id is None:
  1812. return MaterialDetail.objects.filter(is_delete=False)
  1813. else:
  1814. return MaterialDetail.objects.filter(id=id)
  1815. else:
  1816. return MaterialDetail.objects.none()
  1817. def get_serializer_class(self):
  1818. if self.action in ['retrieve', 'list']:
  1819. return MaterialDetailSerializer
  1820. else:
  1821. return self.http_method_not_allowed(request=self.request)
  1822. class OutMaterials(viewsets.ModelViewSet):
  1823. """
  1824. retrieve:
  1825. Response a data list(get)
  1826. list:
  1827. Response a data list(all)
  1828. """
  1829. # authentication_classes = [] # 禁用所有认证类
  1830. # permission_classes = [AllowAny] # 允许任意访问
  1831. pagination_class = MyPageNumberPagination
  1832. filter_backends = [DjangoFilterBackend, OrderingFilter, ]
  1833. ordering_fields = ['id', "create_time", "update_time", ]
  1834. filter_class = OutMaterialDetailFilter
  1835. def get_project(self):
  1836. try:
  1837. id = self.kwargs.get('pk')
  1838. return id
  1839. except:
  1840. return None
  1841. def get_queryset(self):
  1842. id = self.get_project()
  1843. if self.request.user:
  1844. if id is None:
  1845. return OutMaterialDetail.objects.filter(is_delete=False)
  1846. else:
  1847. return OutMaterialDetail.objects.filter(id=id)
  1848. else:
  1849. return OutMaterialDetail.objects.none()
  1850. def get_serializer_class(self):
  1851. if self.action in ['retrieve', 'list']:
  1852. return OutMaterialDetailSerializer
  1853. else:
  1854. return self.http_method_not_allowed(request=self.request)
  1855. class InboundBillsLog(viewsets.ModelViewSet):
  1856. """
  1857. retrieve:
  1858. Response a data list(get)
  1859. list:
  1860. Response a data list(all)
  1861. """
  1862. pagination_class = MyPageNumberPagination
  1863. filter_backends = [DjangoFilterBackend, OrderingFilter, ]
  1864. ordering_fields = ["update_time", "create_time"]
  1865. def get_queryset(self):
  1866. billid = self.request.query_params.get('billid', None)
  1867. # body = json.loads(self.request.body)
  1868. # billid = body.get('billid', None)
  1869. if billid is None:
  1870. return InboundBillOperateLog.objects.none()
  1871. else:
  1872. return InboundBillOperateLog.objects.filter(billId_id=billid)
  1873. def get_serializer_class(self):
  1874. return InboundbillOperateLogSerializer
  1875. class OutboundBillsLog(viewsets.ModelViewSet):
  1876. """
  1877. retrieve:
  1878. Response a data list(get)
  1879. list:
  1880. Response a data list(all)
  1881. """
  1882. pagination_class = MyPageNumberPagination
  1883. filter_backends = [DjangoFilterBackend, OrderingFilter, ]
  1884. ordering_fields = ["update_time", "create_time"]
  1885. def get_queryset(self):
  1886. billid = self.request.query_params.get('billid', None)
  1887. # body = json.loads(self.request.body)
  1888. # billid = body.get('billid', None)
  1889. if billid is None:
  1890. return OutboundBillOperateLog.objects.none()
  1891. else:
  1892. return OutboundBillOperateLog.objects.filter(billId_id=billid)
  1893. def get_serializer_class(self):
  1894. return OutboundbillOperateLogSerializer