views.py 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061
  1. from rest_framework import viewsets
  2. from utils.page import MyPageNumberPagination
  3. from utils.datasolve import sumOfList, transportation_calculate
  4. from utils.md5 import Md5
  5. from rest_framework.filters import OrderingFilter
  6. from django_filters.rest_framework import DjangoFilterBackend
  7. from rest_framework.response import Response
  8. from rest_framework.exceptions import APIException
  9. from django.utils import timezone
  10. from django.db import transaction
  11. import logging
  12. from rest_framework import status
  13. from .models import DeviceModel,LocationModel,LocationGroupModel,LocationContainerLink,LocationChangeLog,alloction_pre,base_location
  14. from bound.models import BoundBatchModel,BoundDetailModel,BoundListModel
  15. from .filter import DeviceFilter,LocationFilter,LocationContainerLinkFilter,LocationChangeLogFilter,LocationGroupFilter
  16. from .serializers import LocationListSerializer,LocationPostSerializer
  17. from .serializers import LocationGroupListSerializer,LocationGroupPostSerializer
  18. # 以后添加模块时,只需要在这里添加即可
  19. from rest_framework.permissions import AllowAny
  20. from container.models import ContainerListModel,ContainerDetailModel,ContainerOperationModel,TaskModel
  21. from django.db.models import Prefetch
  22. import copy
  23. import json
  24. from collections import defaultdict
  25. logger = logging.getLogger(__name__)
  26. # 库位分配
  27. # 入库规则函数
  28. # 逻辑根据批次下的托盘数目来找满足区间范围的库位,按照优先级排序,
  29. class locationViewSet(viewsets.ModelViewSet):
  30. """
  31. retrieve:
  32. Response a data list(get)
  33. list:
  34. Response a data list(all)
  35. create:
  36. Create a data line(post)
  37. delete:
  38. Delete a data line(delete)
  39. """
  40. # authentication_classes = [] # 禁用所有认证类
  41. # permission_classes = [AllowAny] # 允许任意访问
  42. pagination_class = MyPageNumberPagination
  43. filter_backends = [DjangoFilterBackend, OrderingFilter, ]
  44. ordering_fields = ['id', "create_time", "update_time", ]
  45. filter_class = LocationFilter
  46. def get_project(self):
  47. try:
  48. id = self.kwargs.get('pk')
  49. return id
  50. except:
  51. return None
  52. def get_queryset(self):
  53. id = self.get_project()
  54. prefetch_containers = Prefetch(
  55. 'container_links',
  56. queryset=LocationContainerLink.objects.filter(
  57. is_active=True
  58. ).select_related('container'), # 加载关联的托盘对象
  59. to_attr='active_links' # 新的属性名称
  60. )
  61. if self.request.user:
  62. if id is None:
  63. return LocationModel.objects.prefetch_related(prefetch_containers).all()
  64. else:
  65. return LocationModel.objects.prefetch_related(prefetch_containers).filter(id=id)
  66. else:
  67. return LocationModel.objects.none()
  68. def get_serializer_class(self):
  69. if self.action == 'list':
  70. return LocationListSerializer
  71. elif self.action == 'update':
  72. return LocationPostSerializer
  73. elif self.action =='retrieve':
  74. return LocationListSerializer
  75. def update(self, request, *args, **kwargs):
  76. qs = self.get_object()
  77. data = self.request.data
  78. location_code = data.get('location_code')
  79. # 处理库位对象
  80. location_obj = LocationModel.objects.filter(location_code=location_code).first()
  81. if not location_obj:
  82. logger.info(f"库位 {location_code} 不存在")
  83. return Response(
  84. {'code': '400', 'message': '库位不存在', 'data': None},
  85. status=status.HTTP_400_BAD_REQUEST
  86. )
  87. else:
  88. data['id'] = location_obj.id
  89. logger.info(f"库位 {location_code} 已存在")
  90. serializer = self.get_serializer(qs, data=data)
  91. serializer.is_valid(raise_exception=True)
  92. serializer.save()
  93. headers = self.get_success_headers(serializer.data)
  94. self.handle_group_location_status(location_code,location_obj.location_group)
  95. return Response(serializer.data, status=200, headers=headers)
  96. def handle_group_location_status(self,location_code,location_group):
  97. """
  98. 处理库位组和库位的关联关系
  99. :param location_code: 库位编码
  100. :param location_group: 库位组编码
  101. :return:
  102. """
  103. # 1. 获取库位空闲状态的库位数目
  104. location_obj_number = LocationModel.objects.filter(
  105. location_group=location_group,
  106. status='available'
  107. ).all().count()
  108. # 2. 获取库位组对象
  109. logger.info(f"库位组 {location_group} 下的库位数目:{location_obj_number}")
  110. # 1. 获取库位和库位组的关联关系
  111. location_group_obj = LocationGroupModel.objects.filter(
  112. group_code=location_group
  113. ).first()
  114. if not location_group_obj:
  115. logger.info(f"库位组 {location_group} 不存在")
  116. return None
  117. else:
  118. if location_obj_number == 0:
  119. # 库位组库位已满,更新库位组状态为full
  120. location_group_obj.status = 'full'
  121. location_group_obj.save()
  122. elif location_obj_number < location_group_obj.max_capacity:
  123. location_group_obj.status = 'occupied'
  124. location_group_obj.save()
  125. else:
  126. location_group_obj.status = 'available'
  127. location_group_obj.save()
  128. def batch_status_location(self, request):
  129. """
  130. 优化版:批量获取库位批次状态
  131. 基于模型结构优化查询
  132. """
  133. layer = request.data.get('layer')
  134. # 使用反向关系名 'container_links' 进行预取
  135. locations = LocationModel.objects.filter(
  136. layer=layer
  137. ).prefetch_related(
  138. Prefetch(
  139. 'container_links', # 使用模型定义的 related_name
  140. queryset=LocationContainerLink.objects.filter(is_active=True)
  141. .select_related('container'),
  142. to_attr='active_links'
  143. )
  144. )
  145. # 收集所有激活链接的容器ID
  146. container_ids = set()
  147. for loc in locations:
  148. if loc.active_links: # 每个库位最多只有一个激活链接
  149. container_ids.add(loc.active_links[0].container_id)
  150. # 批量查询容器详情及其批次状态
  151. container_batch_status = defaultdict(set)
  152. if container_ids:
  153. container_details = ContainerDetailModel.objects.filter(
  154. container_id__in=container_ids,
  155. is_delete=False
  156. ).select_related('batch')
  157. for detail in container_details:
  158. if detail.batch_id:
  159. # 使用集合自动去重
  160. container_batch_status[detail.container_id].add(
  161. [detail.batch.check_status if detail.batch else "404",
  162. detail.batch.check_time if detail.batch else "no_check_time",
  163. detail.batch if detail.batch else "no_batch"]
  164. )
  165. # 构造返回数据
  166. return_data = []
  167. for loc in locations:
  168. batch_statuses = []
  169. if loc.active_links:
  170. container_id = loc.active_links[0].container_id
  171. # 将集合转换为列表
  172. batch_statuses = list(container_batch_status.get(container_id, set()))
  173. else:
  174. batch_statuses = ["404"] # 无关联容器标识
  175. # 使用Django模型自带的model_to_dict转换基础字段
  176. from django.forms.models import model_to_dict
  177. location_data = model_to_dict(loc, fields=[
  178. "id", "shelf_type", "row", "col", "layer", "update_time",
  179. "empty_label", "location_code", "location_group", "location_type",
  180. "status", "max_capacity", "current_quantity", "c_number",
  181. "coordinate", "access_priority", "is_active"
  182. ])
  183. # 添加批次状态字段
  184. location_data["batch_statuses"] = batch_statuses
  185. return_data.append(location_data)
  186. return Response(return_data, status=200)
  187. class locationGroupViewSet(viewsets.ModelViewSet):
  188. """
  189. retrieve:
  190. Response a data list(get)
  191. list:
  192. Response a data list(all)
  193. create:
  194. Create a data line(post)
  195. delete:
  196. Delete a data line(delete)
  197. """
  198. # authentication_classes = [] # 禁用所有认证类
  199. # permission_classes = [AllowAny] # 允许任意访问
  200. pagination_class = MyPageNumberPagination
  201. filter_backends = [DjangoFilterBackend, OrderingFilter, ]
  202. ordering_fields = ['id', "create_time", "update_time", ]
  203. filter_class = LocationGroupFilter
  204. def get_project(self):
  205. try:
  206. id = self.kwargs.get('pk')
  207. return id
  208. except:
  209. return None
  210. def get_queryset(self):
  211. id = self.get_project()
  212. if self.request.user:
  213. if id is None:
  214. return LocationGroupModel.objects.filter()
  215. else:
  216. return LocationGroupModel.objects.filter(id=id)
  217. else:
  218. return LocationGroupModel.objects.none()
  219. def get_serializer_class(self):
  220. if self.action == 'list':
  221. return LocationGroupListSerializer
  222. elif self.action == 'update':
  223. return LocationGroupPostSerializer
  224. elif self.action =='retrieve':
  225. return LocationGroupListSerializer
  226. def update(self, request, *args, **kwargs):
  227. data = self.request.data
  228. order_month = str(timezone.now().strftime('%Y%m'))
  229. data['month'] = order_month
  230. group_code = data.get('group_code')
  231. # 处理库位组对象
  232. group_obj = LocationGroupModel.objects.filter(group_code=group_code).first()
  233. if group_obj:
  234. data['id'] = group_obj.id
  235. logger.info(f"库位组 {group_code} 已存在")
  236. else:
  237. logger.info(f"库位组 {group_code} 不存在,创建库位组对象")
  238. serializer_list = LocationGroupPostSerializer(data=data)
  239. serializer_list.is_valid(raise_exception=True)
  240. serializer_list.save()
  241. data['id'] = serializer_list.data.get('id')
  242. return Response(data, status=status.HTTP_201_CREATED)
  243. class LocationAllocation:
  244. # 入库规则函数
  245. # fun:get_pallet_count_by_batch: 根据托盘码查询批次下托盘总数
  246. # fun:get_left_locationGroup_number_by_type: 获取每层库位组剩余数量
  247. # fun:get_location_type: 根据托盘数目获取库位类型
  248. # fun:update_location_container_link: 更新库位和托盘的关联关系
  249. # fun:update_location_group_batch: 更新库位组的批次
  250. # fun:update_batch_status: 更新批次状态yes/no
  251. # fun:update_location_status: 更新库位状态和
  252. # fun:up
  253. # fun:get_batch_status: 获取批次状态
  254. # fun:get_batch: 获取批次
  255. # fun:get_location_list_remainder: 获取可用库位的c_number列表
  256. # fun
  257. # fun:get_location_by_type_remainder: 根据库位类型获取库位
  258. # fun:get_location_by_type: 第一次入库,根据库位类型获取库位
  259. # fun:get_location_by_status: 根据库位状态获取库位
  260. @transaction.atomic
  261. def get_pallet_count_by_batch(self, container_code):
  262. """
  263. 根据托盘码查询批次下托盘总数
  264. :param container_code: 要查询的托盘码
  265. :return: 所属批次下的托盘总数
  266. """
  267. # 1. 通过托盘码获取托盘详情
  268. container = ContainerListModel.objects.filter(
  269. container_code=container_code
  270. ).first()
  271. if not container:
  272. logger.error(f"托盘 {container_code} 不存在")
  273. return None
  274. # 2. 获取关联的批次明细
  275. container_detail = ContainerDetailModel.objects.filter(
  276. container=container.id,is_delete=False
  277. ).exclude(status = 3).first()
  278. if not container_detail:
  279. logger.error(f"托盘 {container_code} 未组盘")
  280. return None
  281. batch_container = ContainerDetailModel.objects.filter(
  282. batch = container_detail.batch.id,
  283. is_delete = False,
  284. status = 1
  285. ).all()
  286. # 统计批次下的不同托盘 item.contianer_id
  287. batch_container_count = 0
  288. container_ids = []
  289. for item in batch_container:
  290. if item.container_id not in container_ids:
  291. batch_container_count = batch_container_count + 1
  292. container_ids.append(item.container_id)
  293. batch_item = BoundBatchModel.objects.filter( bound_number = container_detail.batch.bound_number).first()
  294. if not batch_item:
  295. print(f"批次号获取失败!")
  296. return None
  297. batch_item.container_number = batch_container_count
  298. batch_item.save()
  299. return batch_container_count
  300. def get_left_locationGroup_number_by_type(self):
  301. """
  302. 获取每层库位组剩余数量
  303. :return:
  304. """
  305. try:
  306. # 定义库位组和层号
  307. group = ['T1', 'T2', 'S4', 'T4', 'T5']
  308. layer = [1, 2, 3]
  309. # 初始化结果列表,包含三个空字典对应三个层
  310. left_number = [{} for _ in layer]
  311. for item in group:
  312. for idx, layer_num in enumerate(layer):
  313. # 检查库位组是否存在(不考虑状态)
  314. exists = LocationGroupModel.objects.filter(
  315. group_type=item,
  316. layer=layer_num
  317. ).exists()
  318. if not exists:
  319. print(f"库位组 {item}_{layer_num} 不存在")
  320. left_number[idx][item] = 0
  321. else:
  322. # 统计可用状态的库位组数量
  323. count = LocationGroupModel.objects.filter(
  324. group_type=item,
  325. layer=layer_num,
  326. status='available'
  327. ).count()
  328. left_number[idx][item] = count
  329. return left_number
  330. except Exception as e:
  331. logger.error(f"获取库位组剩余数量失败:{str(e)}")
  332. print(f"获取库位组剩余数量失败:{str(e)}")
  333. return None
  334. @transaction.atomic
  335. def update_location_container_link(self,location_code,container_code):
  336. """
  337. 更新库位和托盘的关联关系
  338. :param location_code: 库位编码
  339. :param container_code: 托盘编码
  340. :return:
  341. """
  342. try:
  343. # 1. 获取库位和托盘的关联关系
  344. location = LocationModel.objects.filter(
  345. location_code=location_code
  346. ).first()
  347. container = ContainerListModel.objects.filter(
  348. container_code=container_code
  349. ).first()
  350. # 2. 如果库位和托盘的关联关系不存在,创建新的关联关系
  351. if not LocationContainerLink.objects.filter(location=location).exists():
  352. location_container_link = LocationContainerLink(
  353. location=location,
  354. container=container
  355. )
  356. location_container_link.save()
  357. print(f"更新库位和托盘的关联关系成功!")
  358. return True
  359. # 3. 更新库位和托盘的关联关系
  360. else:
  361. LocationContainerLink.objects.filter(location=location).update(location=location, container=container)
  362. print(f"更新库位和托盘的关联关系成功!")
  363. return True
  364. except Exception as e:
  365. logger.error(f"更新库位和托盘的关联关系失败:{str(e)}")
  366. print(f"更新库位和托盘的关联关系失败:{str(e)}")
  367. return False
  368. def update_container_detail_status(self,container_code,status):
  369. try:
  370. # 1. 获取托盘
  371. container = ContainerListModel.objects.filter(
  372. container_code=container_code
  373. ).first()
  374. if not container:
  375. print(f"托盘 {container_code} 不存在")
  376. return False
  377. # 2. 更新托盘状态
  378. container_detail = ContainerDetailModel.objects.filter(
  379. container=container.id,is_delete=False
  380. ).exclude(status=3).first()
  381. if not container_detail:
  382. print(f"托盘 {container_code} 未组盘_from update_container_detail_status")
  383. return False
  384. container_detail.status = status
  385. container_detail.save()
  386. print(f"更新托盘状态成功!")
  387. return True
  388. except Exception as e:
  389. logger.error(f"更新托盘状态失败:{str(e)}")
  390. print(f"更新托盘状态失败:{str(e)}")
  391. return False
  392. def update_location_group_batch(self,location,container_code):
  393. """
  394. :param location: 库位对象
  395. :param container_code: 托盘码
  396. :return:
  397. """
  398. try:
  399. # 1. 获取库位组
  400. location_group = LocationGroupModel.objects.filter(
  401. group_code=location.location_group
  402. ).first()
  403. if not location_group:
  404. print(f"库位组获取失败!")
  405. return False
  406. # 2. 更新库位组的批次
  407. bound_number=self.get_batch(container_code)
  408. if not bound_number:
  409. print(f"批次号获取失败!")
  410. return False
  411. location_group.current_batch = bound_number
  412. location_group.save()
  413. print(f"更新库位组的批次成功!")
  414. return True
  415. except Exception as e:
  416. logger.error(f"更新库位组的批次失败:{str(e)}")
  417. print(f"更新库位组的批次失败:{str(e)}")
  418. return False
  419. def update_location_status(self,location_code,status):
  420. """
  421. 更新库位状态
  422. :param location_code: 库位编码
  423. :param status: 库位状态
  424. :return:
  425. """
  426. try:
  427. # 1. 获取库位
  428. location = LocationModel.objects.filter(
  429. location_code=location_code
  430. ).first()
  431. if not location:
  432. print(f"库位获取失败!")
  433. return False
  434. # 2. 更新库位状态
  435. location.status = status
  436. location.save()
  437. print(f"更新库位状态成功!")
  438. return True
  439. except Exception as e:
  440. logger.error(f"更新库位状态失败:{str(e)}")
  441. print(f"更新库位状态失败:{str(e)}")
  442. return False
  443. def update_group_status_reserved(self,location_group_list):
  444. """
  445. 更新库位组状态
  446. :param location_group_list: 库位组对象列表
  447. :return:
  448. """
  449. try:
  450. for location_group in location_group_list:
  451. # 1. 获取库位组
  452. if not location_group:
  453. print(f"库位组获取失败!")
  454. return False
  455. # 2. 更新库位组状态
  456. location_group_id = location_group.split('_')[1]
  457. location_group_item = LocationGroupModel.objects.filter(
  458. id=location_group_id
  459. ).first()
  460. if not location_group_item:
  461. print(f"库位组 {location_group} 不存在")
  462. return False
  463. # 3. 更新库位组状态
  464. location_group_item.status = 'reserved'
  465. location_group_item.save()
  466. return True
  467. except Exception as e:
  468. logger.error(f"更新库位组状态失败:{str(e)}")
  469. print(f"更新库位组状态失败:{str(e)}")
  470. return False
  471. @transaction.atomic
  472. def update_location_group_status(self, location_code):
  473. """
  474. 更新库位组状态
  475. :param location_code: 库位编码
  476. :return:
  477. """
  478. try:
  479. # 1. 获取库位
  480. location = LocationModel.objects.filter(
  481. location_code=location_code
  482. ).first()
  483. if not location:
  484. print(f"库位获取失败!")
  485. return False
  486. # 2. 获取库位组
  487. location_group = LocationGroupModel.objects.filter(
  488. group_code=location.location_group
  489. ).first()
  490. if not location_group:
  491. print(f"库位组获取失败!")
  492. return False
  493. current=0
  494. for location_item in location_group.location_items.all():
  495. if location_item.status != 'available':
  496. current=current + 1
  497. # 3. 更新库位组状态
  498. if current == 0:
  499. location_group.status = 'available'
  500. elif current == location_group.max_capacity:
  501. location_group.status = 'full'
  502. else:
  503. location_group.status = 'occupied'
  504. location_group.current_goods_quantity = sum(
  505. [loc.current_quantity for loc in location_group.location_items.all()]
  506. )
  507. location_group.current_quantity = current
  508. location_group.save()
  509. print(f"更新库位组状态成功!")
  510. return True
  511. except Exception as e:
  512. logger.error(f"更新库位组状态失败:{str(e)}")
  513. print(f"更新库位组状态失败:{str(e)}")
  514. def update_batch_status(self,container_code,status):
  515. """
  516. 更新批次状态
  517. :param batch_id: 批次id
  518. :param status: 批次状态
  519. :return:
  520. """
  521. try:
  522. # 1. 通过托盘码获取托盘详情
  523. container = ContainerListModel.objects.filter(
  524. container_code=container_code
  525. ).first()
  526. if not container:
  527. logger.error(f"托盘 {container_code} 不存在")
  528. print(f"托盘 {container_code} 不存在")
  529. return None
  530. # 2. 获取关联的批次明细
  531. container_detail = ContainerDetailModel.objects.filter(
  532. container=container.id,is_delete=False
  533. ).exclude(status=3).first()
  534. if not container_detail:
  535. print (f"托盘 {container_code} 未组盘")
  536. logger.error(f"托盘 {container_code} 未组盘_from update_batch_status")
  537. return None
  538. # 3. 更新批次状态
  539. batch = container_detail.batch
  540. batch.status = status
  541. batch.save()
  542. print(f"更新批次状态成功!")
  543. return True
  544. except Exception as e:
  545. logger.error(f"更新批次状态失败:{str(e)}")
  546. print(f"更新批次状态失败:{str(e)}")
  547. return False
  548. # def update_batch_goods_in_location_qty(self,container_code,taskworking):
  549. # """
  550. # 更新批次库位入库数量
  551. # :param container_code: 托盘码
  552. # :param goods_in_location_qty: 库位入库数量
  553. # :return:
  554. # """
  555. # try:
  556. # # 1. 通过托盘码获取托盘详情
  557. # container = ContainerListModel.objects.filter(
  558. # container_code=container_code
  559. # ).first()
  560. # if not container:
  561. # logger.error(f"托盘 {container_code} 不存在")
  562. # print(f"托盘 {container_code} 不存在")
  563. # return None
  564. # # 2. 获取关联的批次明细
  565. # container_detail = ContainerDetailModel.objects.filter(
  566. # container=container.id,is_delete=False
  567. # ).exclude(status=3).all()
  568. # if not container_detail:
  569. # print (f"托盘 {container_code} 未组盘")
  570. # logger.error(f"托盘 {container_code} 未组盘_from update_batch_goods_in_location_qty")
  571. # return None
  572. # for item in container_detail:
  573. # if item.goods_class == 2:
  574. # continue
  575. # item.batch.goods_in_location_qty += item.goods_qty * taskworking
  576. # item.batch.save()
  577. # print(f"更新批次库位入库数量成功!")
  578. # return True
  579. # except Exception as e:
  580. # logger.error(f"更新批次库位入库数量失败:{str(e)}")
  581. # print(f"更新批次库位入库数量失败:{str(e)}")
  582. # return False
  583. def get_batch_status(self,container_code):
  584. """
  585. 获取批次状态
  586. :param container_code: 托盘码
  587. :return: 批次状态
  588. """
  589. # 1. 通过托盘码获取托盘详情
  590. container = ContainerListModel.objects.filter(
  591. container_code=container_code
  592. ).first()
  593. if not container:
  594. logger.error(f"托盘 {container_code} 不存在")
  595. print(f"托盘 {container_code} 不存在")
  596. return None
  597. # 2. 获取关联的批次明细
  598. container_detail = ContainerDetailModel.objects.filter(
  599. container=container.id,is_delete=False
  600. ).exclude(status=3).first()
  601. if not container_detail:
  602. print (f"托盘 {container_code} 未组盘")
  603. logger.error(f"托盘 {container_code} 未组盘_from get_batch_status")
  604. return None
  605. batch_status = container_detail.batch.status
  606. return batch_status
  607. def get_batch(self,container_code):
  608. """
  609. 获取批次
  610. :param container_code: 托盘码
  611. :return: 批次
  612. """
  613. # 1. 通过托盘码获取托盘详情
  614. container = ContainerListModel.objects.filter(
  615. container_code=container_code
  616. ).first()
  617. if not container:
  618. logger.error(f"托盘 {container_code} 不存在")
  619. print(f"托盘 {container_code} 不存在")
  620. return None
  621. # 2. 获取关联的批次明细
  622. container_detail = ContainerDetailModel.objects.filter(
  623. container=container.id,is_delete=False
  624. ).exclude(status=3).first()
  625. if not container_detail:
  626. print (f"托盘 {container_code} 未组盘")
  627. logger.error(f"托盘 {container_code} 未组盘_from get_batch")
  628. return None
  629. batch = container_detail.batch.bound_number
  630. return batch
  631. @transaction.atomic
  632. def get_location_list_remainder(self, location_group_list,container_code):
  633. """
  634. 获取可用库位的c_number列表
  635. :param location_list: 库位对象列表
  636. :return: 可用库位编号列表
  637. """
  638. if not location_group_list:
  639. return None
  640. min_c_number=1000
  641. min_c_number_index=1000
  642. current_task = self.get_current_finish_task(container_code)
  643. print(f"[1]当前已完成任务: {current_task}")
  644. # 按压力排序
  645. sorted_pressure = sorted(
  646. [(0, current_task[0]), (1, current_task[1]), (2, current_task[2])],
  647. key=lambda x: (-x[1], x[0])
  648. )
  649. # 交换第一和第二个元素的位置
  650. sorted_pressure[0], sorted_pressure[1] = sorted_pressure[1], sorted_pressure[0]
  651. print(f"[2]任务排序: {sorted_pressure}")
  652. print(f"[3]当前选择:{sorted_pressure[0][0]+1}")
  653. location_type_dict = json.loads(self.divide_solution_by_layer(location_group_list))
  654. # print(f"库位类型分配方案: {location_type_dict}")
  655. for layer, _ in sorted_pressure:
  656. if not location_type_dict.get(str(layer+1)):
  657. continue
  658. # print(f"当前层: {layer+1}")
  659. # print(f"当前层库位组: {location_type_dict[str(layer+1)].keys()}")
  660. for group_id in location_type_dict[str(layer+1)].keys():
  661. location_group = LocationGroupModel.objects.filter(
  662. id=group_id,
  663. ).first()
  664. if not location_group:
  665. continue
  666. location_list = location_group.location_items.filter(
  667. status='available'
  668. ).all().order_by('c_number')
  669. if not location_list:
  670. print(f"当前层库位组 {location_group.group_code} 可用库位: None")
  671. continue
  672. # 提取所有库位的 c_number
  673. c_numbers = [loc.c_number for loc in location_list]
  674. print(f"当前层库位组 {location_group.group_code} 可用库位: {c_numbers}")
  675. # 更新任务完成数目
  676. current_task[layer] = current_task[layer] + 1
  677. self.update_current_finish_task(container_code,current_task)
  678. return location_list[0]
  679. @transaction.atomic
  680. def get_location_type(self, container_code):
  681. """
  682. 智能库位分配核心算法
  683. :param container_code: 托盘码
  684. :return: 库位类型分配方案
  685. """
  686. try:
  687. batch = self.get_batch(container_code)
  688. if not batch:
  689. logger.error("批次信息获取失败")
  690. return None
  691. # 检查已有分配方案
  692. existing_solution = alloction_pre.objects.filter(batch_number=batch).first()
  693. if existing_solution:
  694. return existing_solution.layer_pre_type
  695. # 获取关键参数
  696. total_pallets = self.get_pallet_count_by_batch(container_code)
  697. layer_capacity = self.get_left_locationGroup_number_by_type()
  698. current_pressure = self.get_current_pressure()
  699. # 测试参数
  700. # total_pallets = 30
  701. # layer_capacity = [{'T1': 29, 'T2': 14, 'S4': 10, 'T4': 27, 'T5': 27}, {'T1': 0, 'T2': 0, 'S4': 0, 'T4': 0, 'T5': 21}, {'T1': 29, 'T2': 14, 'S4': 10, 'T4': 27, 'T5': 27}]
  702. # current_pressure = [1,0,0]
  703. print(f"[1]托盘数目: {total_pallets}")
  704. print(f"[2]层容量: {layer_capacity}")
  705. # print(f"[3]当前压力: {current_pressure}")
  706. # 定义库位容量表
  707. LOCATION_CAPACITY = {'T1':1, 'T2':2, 'T4':4, 'S4':4, 'T5':5}
  708. def allocate(remain, path, pressure,real_pressure,layer_capacity_state, depth=0):
  709. # 终止条件
  710. if remain <= 0:
  711. return [path,real_pressure]
  712. # 深拷贝当前层容量状态
  713. new_layer_capacity = copy.deepcopy(layer_capacity_state)
  714. # print(f"[2]当前剩余: {new_layer_capacity}")
  715. # 压力平衡系数
  716. balance_factor = 1.0 - (0.1 * min(depth, 5))
  717. # 层选择策略
  718. print (f"[3]当前压力: {pressure}")
  719. layer_priority = sorted(
  720. [(0, pressure[0]), (1, pressure[1]), (2, pressure[2])],
  721. key=lambda x: (x[1] * balance_factor, x[0])
  722. )
  723. for layer, _ in layer_priority:
  724. # 生成候选库位类型(按效率和容量排序)
  725. # 排序键函数 :
  726. # min(x[1], remain) 计算当前库位类型的容量 c 和剩余数量 remain 中的较小值。
  727. # -min(x[1], remain) 和 -x[1] 都使用了负号,这意味着排序是按降序进行的。
  728. # 首先按 -min(x[1], remain) 排序,即优先选择容量与剩余数量更接近的库位类型。
  729. # 如果有多个库位类型的容量与剩余数量相同,则按 -x[1] 排序,即优先选择容量更大的库位类型。
  730. print(f"[4]当前层: {layer+1}, 剩余: {remain}, 容量状态: {new_layer_capacity[layer]}")
  731. candidates = sorted(
  732. [(t, c) for t, c in LOCATION_CAPACITY.items()
  733. if new_layer_capacity[layer].get(t,0) > 0],
  734. key=lambda x: (abs(x[1]-remain), -x[1])
  735. )
  736. print(f"[4]候选库位类型: {candidates}")
  737. for loc_type, cap in candidates:
  738. # 更新容量状态
  739. updated_capacity = copy.deepcopy(new_layer_capacity)
  740. updated_capacity[layer][loc_type] -= 1 # 占用一个库位组
  741. # 允许适度空间浪费(当剩余<2时)
  742. # effective_cap = min(cap, remain) if (cap - remain) < 2 else cap
  743. effective_cap = min(cap, remain)
  744. if effective_cap <= remain:
  745. new_remain = remain - effective_cap
  746. new_pressure = pressure.copy()
  747. for i in range(0, 3):
  748. new_pressure[i] -=1 if new_pressure[i] > 0 else 0
  749. new_pressure[layer] += effective_cap # 按实际存放数计算压力,此时别的楼层压力可能降下来了
  750. real_pressure[layer] += effective_cap # 实际压力
  751. result = allocate(
  752. new_remain,
  753. path + [f"{layer+1}_{loc_type}"],
  754. new_pressure,
  755. real_pressure,
  756. updated_capacity,
  757. depth + 1
  758. )
  759. if result:
  760. print (f"[5]分配方案: {result}")
  761. return result
  762. return None
  763. # 执行分配
  764. allocation = allocate(total_pallets, [], [current_pressure[0], current_pressure[1],current_pressure[2]],[current_pressure[0], current_pressure[1],current_pressure[2]], layer_capacity)
  765. if not allocation:
  766. logger.error("无法生成有效分配方案")
  767. return None
  768. # 保存分配方案
  769. allocation_json = self.divide_solution_by_layer(allocation[0])
  770. print(f"[6]分配方案: {allocation_json}")
  771. solution = alloction_pre(
  772. batch_number=batch,
  773. layer_pre_type =allocation_json
  774. )
  775. solution_pressure, created = base_location.objects.get_or_create(
  776. id=1,
  777. defaults={
  778. 'layer1_pressure': 0,
  779. 'layer2_pressure': 0,
  780. 'layer3_pressure': 0
  781. }
  782. )
  783. solution_pressure.layer1_pressure = allocation[1][0]
  784. solution_pressure.layer2_pressure = allocation[1][1]
  785. solution_pressure.layer3_pressure = allocation[1][2]
  786. solution.save()
  787. solution_pressure.save()
  788. return [loc.split('_')[1] for loc in allocation[0]]
  789. except Exception as e:
  790. logger.error(f"分配算法异常:{str(e)}")
  791. return None
  792. def divide_solution_by_layer(self, data):
  793. # 统计所有存在的层级
  794. layer_counts = defaultdict(lambda: defaultdict(int))
  795. existing_layers = set()
  796. for item in data:
  797. # 分割层级和类型
  798. try:
  799. layer, loc_type = item.split('_')
  800. layer_num = int(layer)
  801. existing_layers.add(layer_num)
  802. layer_counts[layer_num][loc_type] += 1
  803. except (ValueError, IndexError):
  804. continue # 跳过无效格式的数据
  805. # 确定最大层级(至少包含1层)
  806. max_layer = max(existing_layers) if existing_layers else 1
  807. # 构建包含所有层级的最终结果
  808. final_result = {}
  809. for layer in range(1, max_layer + 1):
  810. final_result[str(layer)] = dict(layer_counts.get(layer, {}))
  811. return json.dumps(final_result, indent=2)
  812. def get_current_pressure(self):
  813. """获取实时工作压力"""
  814. last_solution = base_location.objects.order_by('-id').first()
  815. if not last_solution:
  816. base_location.objects.create(
  817. layer1_pressure=0,
  818. layer2_pressure=0,
  819. layer3_pressure=0,
  820. ).save()
  821. return [
  822. last_solution.layer1_pressure if last_solution else 0,
  823. last_solution.layer2_pressure if last_solution else 0,
  824. last_solution.layer3_pressure if last_solution else 0,
  825. ]
  826. def get_current_finish_task(self,container):
  827. batch = self.get_batch(container)
  828. if not batch:
  829. return None
  830. solution = alloction_pre.objects.filter(batch_number=batch).first()
  831. if not solution:
  832. return None
  833. return [solution.layer1_task_finish_number,solution.layer2_task_finish_number,solution.layer3_task_finish_number]
  834. def update_current_finish_task(self,container,task_finish_number):
  835. batch = self.get_batch(container)
  836. if not batch:
  837. return None
  838. solution = alloction_pre.objects.filter(batch_number=batch).first()
  839. if not solution:
  840. return None
  841. solution.layer1_task_finish_number = task_finish_number[0]
  842. solution.layer2_task_finish_number = task_finish_number[1]
  843. solution.layer3_task_finish_number = task_finish_number[2]
  844. solution.save()
  845. return True
  846. @transaction.atomic
  847. def get_location_by_type(self, location_type_list, start_location, container_code):
  848. """
  849. 根据库位类型获取库位,先根据工作压力找出最空闲的层,看下这层有没有工作,如果有,就从里面找,如果没有,则跳过该层,继续找下一层
  850. :param location_type_list: 库位分配方案
  851. {
  852. "1": {
  853. "S4": 1
  854. },
  855. "2": {},
  856. "3": {
  857. "T5": 1
  858. }
  859. }
  860. :param start_location: 起始位置(决定优先级排序方式)
  861. :return: 符合条件的库位列表
  862. """
  863. locations = []
  864. # 检查已有分配方案
  865. existing_solution = alloction_pre.objects.filter(batch_number=self.get_batch(container_code)).first()
  866. if existing_solution.layer_solution_type:
  867. print(f"[0]已有库位分配方案:{existing_solution.layer_solution_type}")
  868. return existing_solution.layer_solution_type
  869. for layer, location_type_dict in location_type_list.items():
  870. if not location_type_dict:
  871. continue
  872. # 获取库位类型列表
  873. location_type = list(location_type_dict.keys())
  874. demand_number = sum(location_type_dict.values())
  875. print (f"[1]层{layer} 需求数量: {demand_number}, 库位: {location_type}")
  876. location_groups = LocationGroupModel.objects.filter(
  877. group_type__in=location_type,
  878. layer=layer,
  879. status='available'
  880. )
  881. if not location_groups:
  882. print(f"层{layer} 无库位")
  883. # 根据起始位置选择排序字段
  884. if start_location == '203':
  885. ordered_groups = location_groups.order_by('left_priority')
  886. elif start_location == '103':
  887. ordered_groups = location_groups.order_by('right_priority')
  888. else:
  889. ordered_groups = location_groups.none()
  890. number = 0
  891. for location_group in ordered_groups:
  892. if number >= demand_number:
  893. break
  894. locations.append(f"{layer}_{location_group.id}")
  895. number += 1
  896. existing_solution.layer_solution_type = locations
  897. existing_solution.save()
  898. print(f"[2]分配方案: {locations}")
  899. return locations if locations else None
  900. @transaction.atomic
  901. def get_location_by_status(self,container_code,start_location):
  902. """
  903. 根据库位状态获取库位
  904. :param location_type: 库位类型
  905. :param start_location: 起始库位 if in1 优先考虑left_priority, if in2 优先考虑right_priority 就是获取库位组列表之后进行排序
  906. :return: 库位列表
  907. """
  908. # 1. 获取批次状态 1 为已组盘 2 为部分入库 3 为全部入库
  909. status = self.get_batch_status(container_code)
  910. #
  911. if status == 1:
  912. # 2. 获取库位组
  913. print(f"[1]第一次入库")
  914. # 重新获取最新数据
  915. self.get_location_type(container_code)
  916. location_type_list = json.loads(alloction_pre.objects.filter(batch_number=self.get_batch(container_code)).first().layer_pre_type)
  917. location_list = self.get_location_by_type(location_type_list,start_location,container_code)
  918. # 预定这些库组
  919. self.update_group_status_reserved(location_list)
  920. location_min_value = self.get_location_list_remainder(location_list,container_code)
  921. print(f"库位安排到第{location_min_value.c_number}个库位:{location_min_value}")
  922. # if not location_list[location_min_index]:
  923. # # 库位已满,返回None
  924. # return None
  925. # else:
  926. # return location_list[location_min_index]
  927. return location_min_value
  928. elif status == 2:
  929. # 3. 获取部分入库库位
  930. print (f"部分入库")
  931. location_list = alloction_pre.objects.filter(batch_number=self.get_batch(container_code)).first().layer_solution_type
  932. location_min_value = self.get_location_list_remainder(location_list,container_code)
  933. print(f"库位安排到第{location_min_value.c_number}个库位:{location_min_value}")
  934. return location_min_value
  935. def release_location(self, location_code):
  936. """释放库位并更新关联数据"""
  937. try:
  938. location = LocationModel.objects.get(location_code=location_code)
  939. links = LocationContainerLink.objects.get(location=location, is_active=True)
  940. print(f"释放库位: {location_code}, 关联托盘: {links.container_id}")
  941. # 解除关联并标记为非活跃
  942. links.is_active = False
  943. links.save()
  944. return True
  945. except Exception as e:
  946. logger.error(f"释放库位失败: {str(e)}")
  947. return False