views.py 60 KB

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