views.py 50 KB

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