views.py 44 KB

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