views.py 37 KB

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