views.py 44 KB

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