views.py 40 KB

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