views.py 76 KB

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