import datetime from django.core.cache import cache from django.db.models import Sum from django.utils.timezone import localtime from django.core.exceptions import ObjectDoesNotExist from rest_framework.exceptions import ParseError from apps.inm.models import MIO, MIOItem from apps.mtm.models import Mgroup, Shift from .models import SfLog, SfLogExp, WMaterial def make_sflogs(mgroup: Mgroup, start_date: datetime.date, end_date: datetime.date): for shift in Shift.objects.all(): start_time_o = shift.start_time_o end_time_o = shift.end_time_o current_date = start_date while current_date <= end_date: start_time = datetime.datetime.combine(current_date, start_time_o) end_time = datetime.datetime.combine(current_date, end_time_o) if start_time > end_time: start_time -= datetime.timedelta(days=1) SfLog.objects.get_or_create(mgroup=mgroup, shift=shift, start_time=start_time, defaults={ "mgroup": mgroup, "shift": shift, "start_time": start_time, "end_time": end_time, "total_hour_now": 12 }) current_date = current_date + datetime.timedelta(days=1) def get_pcoal_heat(year_s: int, month_s: int, day_s: int): """ 获取煤粉热值 只有回转窑需要录入煤粉热值 """ key = f'pgoal_val_{year_s}_{month_s}_{day_s}' pcoal_heat = cache.get(key, None) if pcoal_heat is not None: return pcoal_heat else: try: qs = SfLog.objects.get(end_time__year=year_s, end_time__month=month_s, end_time__day=day_s, mgroup__name='回转窑', shift__name='白班') if qs.pcoal_heat is None: qs.pcoal_heat = 0 qs.save() cache.set(f'pgoal_val_{year_s}_{month_s}_{day_s}', qs.pcoal_heat) return qs.pcoal_heat except Exception: return 0 def do_out(mio: MIO): """ 生产领料到车间 """ belong_dept = mio.belong_dept do_user = mio.do_user mioitems = MIOItem.objects.filter(mio=mio) for item in mioitems: wm, new_create = WMaterial.objects.get_or_create(batch=item.batch, material=item.material, belong_dept=belong_dept, defaults={ "batch": item.batch, "material": item.material, "count": item.count, "create_by": do_user, "belong_dept": belong_dept }) if not new_create: wm.count = wm.count + item.count wm.update_by = do_user wm.save() def do_in(mio: MIO): """ 生产入库 """ belong_dept = mio.belong_dept do_user = mio.do_user mioitems = MIOItem.objects.filter(mio=mio) for item in mioitems: try: wm = WMaterial.objects.get( batch=item.batch, material=item.material, belong_dept=belong_dept) except ObjectDoesNotExist: raise ParseError('车间物料不存在') new_count = wm.count - item.count if new_count > 0: wm.count = new_count wm.update_by = do_user wm.save() elif new_count == 0: wm.delete() else: raise ParseError('车间物料不足')