views.py 56 KB

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