views.py 70 KB

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