hberp/hb_server/apps/wpm/views.py

256 lines
12 KiB
Python

from django.shortcuts import render
from rest_framework.generics import CreateAPIView, GenericAPIView
from rest_framework.mixins import ListModelMixin, RetrieveModelMixin
from rest_framework.utils import serializer_helpers
from rest_framework.utils.field_mapping import get_relation_kwargs
from rest_framework.views import APIView
from rest_framework.viewsets import GenericViewSet, ModelViewSet
from apps.mtm.models import Material, RecordForm, Step, SubprodctionMaterial
from apps.mtm.serializers import RecordFormDetailSerializer
from apps.pm.models import SubProductionPlan, SubProductionProgress
from apps.pm.serializers import SubProductionPlanListSerializer, SubProductionPlanUpdateSerializer
from apps.system.mixins import CreateUpdateModelAMixin, OptimizationMixin
from rest_framework.decorators import action
from apps.wpm.models import WMaterial, WProduct, Operation, OperationMaterial, OperationRecord, OperationRecordItem
from apps.wpm.serializers import OperationDetailSerializer, OperationListSerializer, PickSerializer, OperationInitSerializer, OperationSubmitSerializer, WMaterialListSerializer, WProductListSerializer
from rest_framework.response import Response
# Create your views here.
class WPlanViewSet(ListModelMixin, GenericViewSet):
"""
车间生产计划
"""
perms_map = {'*': '*'}
queryset = SubProductionPlan.objects.select_related('process', 'workshop', 'subproduction', 'main_product').exclude(state=0)
search_fields = []
serializer_class = SubProductionPlanListSerializer
filterset_fields = ['production_plan', 'process', 'state', 'main_product', 'workshop']
ordering_fields = ['process__number']
ordering = ['process__number']
class WMaterialViewSet(CreateUpdateModelAMixin, ListModelMixin, GenericViewSet):
"""
车间物料表
"""
perms_map={'*':'*'}
queryset = WMaterial.objects.select_related('material').all()
serializer_class = WMaterialListSerializer
filterset_fields = ['material', 'subproduction_plan', 'subproduction_plan__process', 'subproduction_plan__workshop']
ordering_fields = ['material__number']
ordering = ['material__number']
@action(methods=['post'], detail=False, perms_map={'post':'*'}, serializer_class=PickSerializer)
def pick(self, request, pk=None):
"""
领料
"""
serializer= PickSerializer(data=request.data, context={'request': request})
serializer.is_valid(raise_exception=True)
serializer.save()
return Response()
class WProductViewSet(ListModelMixin, GenericViewSet):
"""
半成品
"""
perms_map={'*':'*'}
queryset = WProduct.objects.select_related('p_state', 'm_state').filter(is_hidden=True)
serializer_class = WProductListSerializer
filterset_fields = ['p_state', 'subproduction_plan', 'm_state', 'production_plan', 'p_state__process']
search_fields = ['number']
ordering_fields = ['id']
ordering = ['id']
@action(methods=['post'], detail=False, perms_map={'post':'*'}, serializer_class=PickSerializer)
def test():
pass
class OperationViewSet(ListModelMixin, RetrieveModelMixin, GenericViewSet):
"""
生产操作记录
"""
perms_map={'*':'*'}
queryset = Operation.objects.select_related('p_state', 'm_state').all()
serializer_class = OperationListSerializer
filterset_fields = ['p_state', 'm_state']
ordering_fields = ['id']
ordering = ['-id']
def get_serializer_class(self):
if self.action == 'retrieve':
return OperationDetailSerializer
return super().get_serializer_class()
class DoFormInit(CreateAPIView, GenericAPIView):
perms_map={'*':'*'}
serializer_class=OperationInitSerializer
def post(self, request, format=None):
"""
调用操作表单
"""
data = request.data
serializer = OperationInitSerializer(data=data)
serializer.is_valid(raise_exception=True)
vdata = serializer.validated_data
ret = {}
ret_0 = {}
ret_0['step'] = data['step']
ret_0['subproduction_plan'] = data['subproduction_plan']
if 'wproducts' in data and data['wproducts']:
ret_0['wproducts'] = data['wproducts']
else:
ret_0['wproducts'] = []
# 调出该子计划现有物料
ret_0['input'] = list(WMaterial.objects.filter(subproduction_plan=vdata['subproduction_plan'])\
.values('id', 'material', 'material__name', 'count', 'material__number', 'batch'))
for i in ret_0['input']:
i['count_input'] = 0
# 需要输出的物料
if ret_0['wproducts']:
# 排除主要产物, 因为已经放到半成品里了, 由半成品进行处理, 夹层可能需要特殊处理
o_objs = SubProductionProgress.objects.filter(
subproduction_plan=vdata['subproduction_plan'], type=SubprodctionMaterial.SUB_MA_TYPE_OUT).exclude(is_main=True)
else:
o_objs = SubProductionProgress.objects.filter(
subproduction_plan=vdata['subproduction_plan'], type=SubprodctionMaterial.SUB_MA_TYPE_OUT)
ret_0['output'] = list(o_objs.values('material', 'material__name', 'material__number'))
for i in ret_0['output']:
i['count_output']=0
ret['forms'] = []
ret_0['id'] = 0
ret_0['name'] = '基本信息'
ret['forms'].append(ret_0)
forms = RecordForm.objects.filter(step=vdata['step'], type=RecordForm.RF_TYPE_DO)
if forms.exists():
ret['forms'].extend(RecordFormDetailSerializer(instance=forms, many=True).data)
return Response(ret)
class DoFormSubmit(CreateAPIView, GenericAPIView):
perms_map={'*':'*'}
serializer_class = OperationSubmitSerializer
def post(self, request, format=None):
"""
提交操作表单
"""
data = request.data
serializer = OperationSubmitSerializer(data=data, context={'request':self.request})
serializer.is_valid(raise_exception=True)
vdata = serializer.validated_data #校验之后的数据
# 创建一个生产操作记录
action_obj = Operation()
action_obj.p_state = vdata['step']
if 'wproducts' in data and data['wproducts']:
action_obj.wproducts = data['wproducts']
action_obj.m_state = vdata[0].m_state
action_obj.remark = vdata.get('remark', '') # 操作备注
action_obj.create_by = request.user
action_obj.save()
# 保存物料消耗
for i in vdata['input']:
if i['count_input']: #如果有消耗
i_wmat = i['id']
OperationMaterial.objects.create(type=1, operation=action_obj,
wmaterial= i_wmat, count=i['count_input'])
# 更新车间物料
i_wmat.count = i_wmat.count- i['count_input']
i_wmat.save()
# 更新子计划物料消耗情况
sp = SubProductionProgress.objects.get(subproduction_plan=i_wmat.subproduction_plan,
material=i_wmat.material)
sp.count_real = sp.count_real + i['count_input']
sp.save()
# 物料产出
if 'output' in data and data['output']:
for i in vdata['output']: # 已经序列化好的数据
ma = i['material']
if vdata['subproduction_plan'].main_product == ma: # 如果是该计划主产物
# 如果是切割
# 获取下一步子工序
if vdata['step'].type == Step.STEP_TYPE_DIV:
stepIds = [i['id'] for i in vdata['subproduction_plan'].steps]
pindex = stepIds.index(vdata['step'].id)
wpr = dict(m_state=ma, p_state=Step.objects.get(pk=stepIds[pindex+1]),
act_state=WProduct.WPR_ACT_STATE_DOING, is_executed=False, remark='',
subproduction_plan=vdata['subproduction_plan'],
production_plan=vdata['subproduction_plan'].production_plan)
for x in range(i['count_output']):
WProduct.objects.create(**wpr)
else:
# 更新操作产出物料表
OperationMaterial.objects.create(type=2, operation=action_obj,
material= ma, count=i['count_output'])
# 更新车间物料表
ins, _ = WMaterial.objects.get_or_create(subproduction_plan=vdata['subproduction_plan'],
material=ma)
ins.count = ins.count + i['count_output']
ins.save()
# 更新子计划进度表
sp = SubProductionProgress.objects.get(subproduction_plan=vdata['subproduction_plan'],
material=ma)
sp.count_real = sp.count_real + i['count_input']
sp.save()
# 更新动态产品表
if 'wproducts' in data and data['wproducts']:
wproducts = WProduct.objects.filter(pk__in=data['wproducts'])
# 获取下一步子工序
stepIds = [i['id'] for i in vdata['subproduction_plan'].steps]
pindex = stepIds.index(vdata['step'].id)
if pindex + 1 < len(stepIds): # 如果不是最后一步
newstep = Step.objects.get(pk=stepIds[pindex+1])
wproducts.update(p_state=newstep, is_executed=False)
# 特殊情况如果是夹层结合
if vdata['step'].type == Step.STEP_TYPE_COMB:
wproducts.update(is_hidden=True) # 隐藏
WProduct.objects.create(
m_state=vdata['subproduction_plan'].main_product, p_state = newstep,
act_state=WProduct.WPR_ACT_STATE_DOING, is_executed=False, remark='',
subproduction_plan=vdata['subproduction_plan'],
production_plan=vdata['subproduction_plan'].production_plan,
parent = data['wproducts']
)
else: # 如果是最后一步, 此时需要转序并更新状态为待检测
newstep = vdata['step']
wproducts.update(p_state=newstep, is_executed=True, act_state=WProduct.WPR_ACT_STATE_TOTEST)
# 特殊情况如果是夹层结合
if vdata['step'].type == Step.STEP_TYPE_COMB:
wproducts.update(is_hidden=True) # 隐藏
WProduct.objects.create(
m_state=vdata['subproduction_plan'].main_product, p_state = newstep,
act_state=WProduct.WPR_ACT_STATE_TOTEST, is_executed=True, remark='',
subproduction_plan=vdata['subproduction_plan'],
production_plan=vdata['subproduction_plan'].production_plan
)
# 保存自定义表单结果
for i in vdata['forms']:
wr = OperationRecord()
wr.form = i['form']
wr.create_by = request.user
wr.operation = action_obj
wr.save()
wrds = []
for m in i['record_data']: # 保存记录详情
form_field = m['form_field']
m['field_name'] = form_field.field_name
m['field_key'] = form_field.field_key
m['field_type'] = form_field.field_type
m['field_value'] = m['field_value']
m['sort'] = form_field.sort
m['operation_record'] = wr
wrds.append(OperationRecordItem(**m))
OperationRecordItem.objects.bulk_create(wrds)
return Response()