def tubes_control(request): """ Создание новых и настройка существующих пробирок """ if request.method == "PUT": if hasattr(request, '_post'): del request._post del request._files try: request.method = "POST" request._load_post_and_files() request.method = "PUT" except AttributeError: request.META['REQUEST_METHOD'] = 'POST' request._load_post_and_files() request.META['REQUEST_METHOD'] = 'PUT' request.PUT = request.POST title = request.PUT["title"] color = "#" + request.PUT["color"] new_tube = Tubes(title=title, color=color, short_title=request.PUT.get("short_title", "")) new_tube.save() slog.Log(key=str(new_tube.pk), user=request.user.doctorprofile, type=1, body=json.dumps({ "data": { "title": request.POST["title"], "color": request.POST["color"], "code": request.POST.get("code", "") } })).save() if request.method == "POST": id = int(request.POST["id"]) title = request.POST["title"] color = "#" + request.POST["color"] tube = Tubes.objects.get(id=id) tube.color = color tube.title = title tube.short_title = request.POST.get("code", "") tube.save() slog.Log(key=str(tube.pk), user=request.user.doctorprofile, type=2, body=json.dumps({ "data": { "title": request.POST["title"], "color": request.POST["color"], "code": request.POST.get("code", "") } })).save() return JsonResponse({})
def list_wait_save(data, doc_who_create): patient_card = Card.objects.get(pk=data['card_pk']) if 'card' not in data else data['card'] research_obj = Researches.objects.get(pk=data['research']) list_wait = ListWait( client=patient_card, research=research_obj, exec_at=datetime.datetime.strptime(data['date'], '%Y-%m-%d'), comment=data['comment'], phone=data['phone'], doc_who_create=doc_who_create, work_status=0, ) list_wait.save() slog.Log( key=list_wait.pk, type=80005, body=json.dumps( { "card_pk": patient_card.pk, "research": research_obj.title, "date": data['date'], "comment": data['comment'], } ), user=doc_who_create, ).save() return list_wait.pk
def plan_hospitalization_save(data, doc_who_create): patient_card = Card.objects.get( pk=data['card_pk']) if 'card' not in data else data['card'] research_obj = Researches.objects.get(pk=data['research']) plan_hospitalization = PlanHospitalization( client=patient_card, research=research_obj, exec_at=datetime.strptime(data['date'], '%Y-%m-%d'), comment=data['comment'], phone=data['phone'], doc_who_create=doc_who_create, work_status=0, hospital_department_id=data['hospital_department_id'], action=data['action'], diagnos=data.get('diagnos') or '', ) plan_hospitalization.save() slog.Log( key=plan_hospitalization.pk, type=80007, body=json.dumps({ "card_pk": patient_card.pk, "research": research_obj.title, "date": data['date'], "comment": data['comment'], "hospital_department_id": data['hospital_department_id'], }), user=doc_who_create, ).save() return plan_hospitalization.pk
def create_pod(request): """ Создание подразделения """ p = False e = True mess = '' podr = Podrazdeleniya.objects.all() # Выбор подразделения if request.method == 'POST': # Проверка типа запроса title = request.POST['title'] # Получение названия if title: # Если название есть if not Podrazdeleniya.objects.filter( title=title).exists(): # Если название не существует pd = Podrazdeleniya.objects.create() # Создание подразделения pd.title = title pd.save() # Сохранение подразделения p = True e = False slog.Log(key=str(pd.pk), user=request.user.doctorprofile, type=17, body=json.dumps({"title": title})).save() else: mess = "Такое подразделение уже есть" else: mess = "Название заполнено некорректно" else: e = False return render(request, 'dashboard/create_podr.html', { 'error': e, 'mess': mess, 'title': '', 'status': p, 'podr': podr })
def tubes_relation(request): """ Создание связи пробирка-фракция """ return_result = {} if request.method == "PUT": if hasattr(request, '_post'): del request._post del request._files try: request.method = "POST" request._load_post_and_files() request.method = "PUT" except AttributeError: request.META['REQUEST_METHOD'] = 'POST' request._load_post_and_files() request.META['REQUEST_METHOD'] = 'PUT' request.PUT = request.POST tube_id = request.PUT["id"] tube = Tubes.objects.get(id=tube_id) from directory.models import ReleationsFT relation = ReleationsFT(tube=tube) relation.save() return_result["id"] = relation.pk return_result["title"] = tube.title return_result["color"] = tube.color slog.Log(key=str(relation.pk), user=request.user.doctorprofile, type=20, body=json.dumps({"data": { "id": tube_id }})).save() return JsonResponse(return_result)
def change_password(request): doc: DoctorProfile = request.user.doctorprofile doc.reset_password() slog.Log(key='', type=120000, body="IP: {0}".format(slog.Log.get_client_ip(request)), user=request.user.doctorprofile).save() return status_response(True)
def add(user: users.DoctorProfile, research: directory.Researches, direction: int): isdoc = True # isdoc = user.labtype == 1 pts = sum([x.uet_doc if isdoc else x.uet_lab for x in directory.Fractions.objects.filter(research__pk=research.pk)]) if pts > 0: row = Uet(user=user, points=pts) row.save() slog.Log(key=str(direction), type=26, body=str(pts), user=user).save()
def join_individual(self, b: 'Individual', out: OutputWrapper = None): if out: out.write("Карт для переноса: %s" % Card.objects.filter(individual=b).count()) slog.Log(key=str(self.pk), type=2002, body=simplejson.dumps({"Сохраняемая запись": str(self), "Объединяемая запись": str(b)}), user=None).save() for c in Card.objects.filter(individual=b): c.individual = self c.save() b.delete()
def clear_notice(self, doc_r): old_notice = self.notice if old_notice == "": return self.notice = "" self.save() slog.Log(key=str(self.pk), user=doc_r, type=4000, body=json.dumps({"Удалённое замечание": old_notice})).save()
def set_notice(self, doc_r, notice): """ Установка замечания для пробирки :param doc_r: врач/лаборант, указавший замечание :param notice: текст замечания :return: """ self.notice = notice self.save() slog.Log(key=str(self.pk), user=doc_r, type=12, body=json.dumps({"status": self.getstatus(), "notice": self.notice})).save()
def loose_password(request): if request.user.is_authenticated: return status_response(False) data = json.loads(request.body) step = data.get('step') email = data.get('email') code = data.get('code') if email: email = email.strip() if code: code = code.strip() if step == 'request-code': if email and DoctorProfile.objects.filter( email__iexact=email).exists(): doc: DoctorProfile = DoctorProfile.objects.filter( email__iexact=email)[0] request.session['email'] = email request.session['code'] = str(randint(10000, 999999)) send_password_reset_code.delay(email, request.session['code'], doc.hospital_safe_title) slog.Log(key=email, type=121000, body="IP: {0}".format(slog.Log.get_client_ip(request)), user=doc).save() return status_response(True) elif step == 'check-code': if email and DoctorProfile.objects.filter( email__iexact=email).exists() and request.session.get( 'email') == email and code and request.session.get( 'code') == code: doc: DoctorProfile = DoctorProfile.objects.filter( email__iexact=email)[0] doc.reset_password() slog.Log(key=email, type=121001, body="IP: {0}".format(slog.Log.get_client_ip(request)), user=doc).save() request.session['email'] = None request.session['code'] = None return status_response(True) return status_response(False)
def set_r(self, doc_r): """ Установка статуса принятия материала лабораторией :param doc_r: врач/лаборант, принявший материал :return: """ from django.utils import timezone self.time_recive = timezone.now() self.doc_recive = doc_r self.save() slog.Log(key=str(self.pk), user=doc_r, type=11, body=json.dumps({"status": self.getstatus(), "notice": self.notice})).save()
def set_get(self, doc_get): """ Установка статуса взятия :param doc_get: врач/мед сестра, взявшая материал :return: None """ from django.utils import timezone self.time_get = timezone.now() self.doc_get = doc_get self.barcode = self.pk self.save() slog.Log(key=str(self.pk), type=9, body="", user=doc_get).save()
def auth(request): data = json.loads(request.body) username = data.get('username', '') password = data.get('password', '') user = authenticate(username=username, password=password) f1 = re.findall(r"^([ X0-9]{5})([0-9a-fA-F]{5})$", username) if user: if user.is_active: login(request, user) log = slog.Log(key="", type=18, body="IP: {0}".format( slog.Log.get_client_ip(request)), user=request.user.doctorprofile) log.save() request.user.doctorprofile.register_login( slog.Log.get_client_ip(request)) return status_response( True, data={'fio': user.doctorprofile.get_full_fio()}) return status_response(False, message="Ваш аккаунт отключен") elif len(password) == 0 and len(f1) == 1 and len(f1[0]) == 2: did = int(f1[0][0].replace("X", "")) u = DoctorProfile.objects.filter(pk=did).first() if u and u.get_login_id() == username and u.user.is_active: user = u.user login(request, user, backend="django.contrib.auth.backends.ModelBackend") slog.Log(key='По штрих-коду', type=18, body="IP: {0}".format(slog.Log.get_client_ip(request)), user=request.user.doctorprofile).save() request.user.doctorprofile.register_login( slog.Log.get_client_ip(request)) return status_response( True, data={'fio': user.doctorprofile.get_full_fio()}) return status_response(False, message="Неверное имя пользователя или пароль")
def list_wait_change_status(data, doc_who_create): list_wait = ListWait.objects.filter(pk=data['pk_list_wait'])[0] list_wait.doc_who_create = doc_who_create list_wait.status = data['status'] list_wait.save() slog.Log( key=list_wait.pk, type=80006, body=json.dumps({"card_pk": list_wait.client.pk, "status": list_wait.status}), user=doc_who_create, ).save() return list_wait.pk
def doctor_call_cancel(data, doc_who_create): doc_call = DoctorCall.objects.filter(pk=data['pk_doc_call'])[0] doc_call.doc_who_create = doc_who_create doc_call.cancel = not doc_call.canceled doc_call.save() slog.Log( key=doc_call.pk, type=80004, body=json.dumps({"card_pk": doc_call.client.pk, "status": doc_call.cancel}), user=doc_who_create, ).save() return doc_call.pk
def directory_researches_group(request): """GET: получение списка исследований для группы. POST: добавление новой или выбор существующей группы и привязка исследований к ней""" return_result = {} if request.method == "GET": return_result = {"researches": []} subgroup_id = request.GET["lab_group"] gid = int(request.GET["gid"]) researches = Researches.objects.filter(subgroup__pk=subgroup_id) for research in researches: resdict = {"pk": research.pk, "title": research.title} if gid < 0: if not research.direction: return_result["researches"].append(resdict) else: if research.direction and research.direction.pk == gid: return_result["researches"].append(resdict) elif request.method == "POST": gid = int(request.POST["group"]) if gid < 0: direction = DirectionsGroup() direction.save() type = 5 else: direction = DirectionsGroup.objects.get(pk=gid) type = 6 slog.Log(key=direction.pk, type=type, body="{'data': " + request.POST["researches"] + "}", user=request.user.doctorprofile).save() tmp_researches = Researches.objects.filter(direction=direction) for v in tmp_researches: v.direction = None v.save() researches = json.loads(request.POST["researches"]) for k in researches.keys(): if researches[k]: if k == "" or not k.isdigit() or not Researches.objects.filter( pk=k).exists(): continue research = Researches.objects.get(pk=k) research.direction = direction research.save() return_result["gid"] = direction.pk return HttpResponse(json.dumps(return_result), content_type="application/json") # Создание JSON
def confirm_reset(request): result = {"ok": False, "msg": "Ошибка"} if "pk" in request.POST.keys() or "pk" in request.GET.keys(): if request.method == "POST": pk = int(request.POST["pk"]) else: pk = int(request.GET["pk"]) if Issledovaniya.objects.filter(pk=pk).exists(): iss = Issledovaniya.objects.get(pk=pk) import time ctp = int(0 if not iss.time_confirmation else int( time. mktime(timezone.localtime(iss.time_confirmation).timetuple()))) ctime = int(time.time()) cdid = -1 if not iss.doc_confirmation else iss.doc_confirmation.pk if ( ctime - ctp < SettingManager.get("lab_reset_confirm_time_min") * 60 and cdid == request.user.doctorprofile.pk ) or request.user.is_superuser or "Сброс подтверждений результатов" in [ str(x) for x in request.user.groups.all() ]: predoc = { "fio": 'не подтверждено' if cdid == -1 else iss.doc_confirmation.get_fio(), "pk": cdid, "direction": iss.napravleniye.pk } iss.doc_confirmation = iss.time_confirmation = None iss.save() if iss.napravleniye.result_rmis_send: c = Client() c.directions.delete_services(iss.napravleniye, request.user.doctorprofile) result = {"ok": True} slog.Log(key=pk, type=24, body=json.dumps(predoc), user=request.user.doctorprofile).save() else: result[ "msg"] = "Сброс подтверждения разрешен в течении %s минут" % ( str(SettingManager.get("lab_reset_confirm_time_min"))) return JsonResponse(result)
def directory_toggle_hide_research(request): """ Переключение скрытия исследования для выписки :param request: :return: """ if request.method == "POST": pk = request.POST["pk"] else: pk = request.GET["pk"] research = Researches.objects.get(pk=int(pk)) research.hide = not research.hide research.save() slog.Log(key=pk, type=19, body=json.dumps({"hide": research.hide}), user=request.user.doctorprofile).save() return JsonResponse({"status_hide": research.hide})
def set_notice(self, doc_r, notice): """ Установка замечания для пробирки :param doc_r: врач/лаборант, указавший замечание :param notice: текст замечания :return: """ if notice != "": self.doc_recive = None self.time_recive = None self.notice = notice self.save() slog.Log(key=str(self.pk), user=doc_r, type=12, body=json.dumps({"Замечание не приёма": self.notice})).save()
def discharge_add(request): r = {"ok": True} if request.method == "POST": import podrazdeleniya.models as pod import discharge.models as discharge client_surname = request.POST.get("client_surname", "").strip() client_name = request.POST.get("client_name", "").strip() client_patronymic = request.POST.get("client_patronymic", "").strip() client_birthday = request.POST.get("client_birthday", "").strip() client_sex = request.POST.get("client_sex", "").strip() client_cardnum = request.POST.get("client_cardnum", "").strip() client_historynum = request.POST.get("client_historynum", "").strip() otd = pod.Podrazdeleniya.objects.get( pk=int(request.POST.get("otd", "-1"))) doc_fio = request.POST.get("doc_fio", "").strip() if "" not in [client_surname, client_name, client_patronymic ] and request.FILES.get('file', "") != "": obj = discharge.Discharge(client_surname=client_surname, client_name=client_name, client_patronymic=client_patronymic, client_birthday=client_birthday, client_sex=client_sex, client_cardnum=client_cardnum, client_historynum=client_historynum, otd=otd, doc_fio=doc_fio, creator=request.user.doctorprofile, file=request.FILES["file"]) obj.save() slog.Log(key=obj.pk, type=1000, body=json.dumps({ "client_surname": client_surname, "client_name": client_name, "client_patronymic": client_patronymic, "client_birthday": client_birthday, "client_sex": client_sex, "client_cardnum": client_cardnum, "client_historynum": client_historynum, "otd": otd.title + ", " + str(otd.pk), "doc_fio": doc_fio, "file": obj.file.name }), user=request.user.doctorprofile).save() return HttpResponse(json.dumps(r), content_type="application/json")
def directory_researches_group(request): """GET: получение списка исследований для группы. POST: добавление новой или выбор существующей группы и привязка исследований к ней""" return_result = {} if request.method == "GET": return_result = {"researches": []} gid = int(request.GET["gid"]) researches = Researches.objects.filter(podrazdeleniye__isnull=False) if request.GET["lab"] != "-1": researches = researches.filter(podrazdeleniye__pk=request.GET["lab"]).order_by("title", "podrazdeleniye", "hide") for research in researches: resdict = {"pk": research.pk, "title": "{}{} | {}".format({True: "Скрыто | "}.get(research.hide, ""), research.get_title(), research.podrazdeleniye.get_title())} if gid < 0: if not research.direction: return_result["researches"].append(resdict) else: if research.direction and research.direction.pk == gid: return_result["researches"].append(resdict) elif request.method == "POST": gid = int(request.POST["group"]) if gid < 0: direction = DirectionsGroup() direction.save() type = 5 else: direction = DirectionsGroup.objects.get(pk=gid) type = 6 slog.Log(key=direction.pk, type=type, body="{'data': " + request.POST["researches"] + "}", user=request.user.doctorprofile).save() tmp_researches = Researches.objects.filter(direction=direction) for v in tmp_researches: v.direction = None v.save() researches = json.loads(request.POST["researches"]) for k in researches.keys(): if researches[k]: if k == "" or not k.isdigit() or not Researches.objects.filter(pk=k).exists(): continue research = Researches.objects.get(pk=k) research.direction = direction research.save() return_result["gid"] = direction.pk return JsonResponse(return_result)
def create_pod(request): """ Создание подразделения """ p = False e = True mess = '' podr = Podrazdeleniya.objects.all().order_by("pk") # Выбор подразделения if request.method == 'POST': # Проверка типа запроса if request.POST.get("update_podr", "0") == "1": pd = Podrazdeleniya.objects.get(pk=request.POST.get("pk")) if "title" in request.POST: pd.title = request.POST["title"] if "hide" in request.POST: pd.hide = request.POST["hide"] == "true" if "is_lab" in request.POST: pd.isLab = request.POST["is_lab"] == "true" pd.save() return JsonResponse({}) title = request.POST['title'] # Получение названия if title: # Если название есть if not Podrazdeleniya.objects.filter( title=title).exists(): # Если название не существует pd = Podrazdeleniya.objects.create() # Создание подразделения pd.title = title pd.save() # Сохранение подразделения p = True e = False slog.Log(key=str(pd.pk), user=request.user.doctorprofile, type=17, body=json.dumps({"title": title})).save() else: mess = "Такое подразделение уже есть" else: mess = "Название заполнено некорректно" else: e = False return render( request, 'dashboard/create_podr.html', { 'error': e, 'mess': mess, 'title': '', 'status': p, 'podr': podr, 'types': Podrazdeleniya.TYPES })
def set_r(self, doc_r): """ Установка статуса принятия материала лабораторией :param doc_r: врач/лаборант, принявший материал :return: """ from django.utils import timezone if not self.getstatus(): self.set_get(doc_r) self.time_recive = timezone.now() self.doc_recive = doc_r self.save() slog.Log(key=str(self.pk), user=doc_r, type=11, body=json.dumps({"Замечание не приёма": self.notice}) if self.notice != "" else "").save()
def plan_hospitalization_change_status(data, doc_who_create): plan_hosp = PlanHospitalization.objects.get(pk=data['pk_plan']) plan_hosp.doc_who_create = doc_who_create if data["status"] == 2: plan_hosp.why_cancel = data.get('cancelReason') or '' if plan_hosp.work_status == 2: plan_hosp.work_status = 0 else: plan_hosp.work_status = 2 plan_hosp.save() slog.Log( key=plan_hosp.pk, type=80008, body=json.dumps({ "card_pk": plan_hosp.client.pk, "status": plan_hosp.work_status, "action": data["action"] }), user=doc_who_create, ).save() return plan_hosp.pk
def confirm_reset(request): result = {"ok": False, "msg": "Ошибка"} if "pk" in request.POST.keys() or "pk" in request.GET.keys(): if request.method == "POST": pk = int(request.POST["pk"]) else: pk = int(request.GET["pk"]) if Issledovaniya.objects.filter(pk=pk).exists(): iss = Issledovaniya.objects.get(pk=pk) import time ctp = int(0 if not iss.time_confirmation else int( time.mktime(iss.time_confirmation.timetuple()))) + 8 * 60 * 60 ctime = int(time.time()) cdid = -1 if not iss.doc_confirmation else iss.doc_confirmation.pk if (ctime - ctp < SettingManager.get("lab_reset_confirm_time_min") * 60 and cdid == request.user.doctorprofile.pk ) or request.user.is_superuser: predoc = { "fio": iss.doc_confirmation.get_fio(), "pk": iss.doc_confirmation.pk } iss.doc_confirmation = iss.time_confirmation = None iss.save() result = {"ok": True} slog.Log(key=pk, type=24, body=json.dumps(predoc), user=request.user.doctorprofile).save() else: result[ "msg"] = "Сброс подтверждения разрешен в течении %s минут" % ( str(SettingManager.get("lab_reset_confirm_time_min"))) return HttpResponse(json.dumps(result), content_type="application/json")
def limit_date_hospitalization_save(data, doc_who_create): research_obj = Researches.objects.get(pk=data['research']) limit_plan_hospitalization = LimitDatePlanHospitalization( research=research_obj, date=datetime.strptime(data['date'], '%Y-%m-%d'), doc_who_create=doc_who_create, hospital_department_id=data['hospital_department_id'], count=data['count'], ) limit_plan_hospitalization.save() slog.Log( key=limit_plan_hospitalization.pk, type=80009, body=json.dumps({ "research": research_obj.title, "date": data['date'], "hospital_department_id": data['hospital_department_id'], }), user=doc_who_create, ).save() return limit_plan_hospitalization.pk
def send(request): """ Sysmex save results :param request: :return: """ result = {"ok": False} try: if request.method == "POST": resdict = yaml.load(request.POST["result"]) appkey = request.POST["key"] else: resdict = yaml.load(request.GET["result"]) appkey = request.GET["key"] astm_user = users.DoctorProfile.objects.filter(user__pk=866).first() if "LYMPH%" in resdict["result"]: resdict["orders"] = {} dpk = -1 if "bydirection" in request.POST or "bydirection" in request.GET: dpk = resdict["pk"] if dpk >= 4600000000000: dpk -= 4600000000000 dpk //= 10 if directions.TubesRegistration.objects.filter( issledovaniya__napravleniye__pk=dpk).exists(): resdict["pk"] = directions.TubesRegistration.objects.filter( issledovaniya__napravleniye__pk=dpk).first().pk else: resdict["pk"] = -1 resdict["bysapphire"] = True if resdict["pk"] and models.Application.objects.filter( key=appkey).exists( ) and directions.TubesRegistration.objects.filter( pk=resdict["pk"]).exists(): tubei = directions.TubesRegistration.objects.get(pk=resdict["pk"]) direction = tubei.issledovaniya_set.first().napravleniye for key in resdict["result"].keys(): if models.RelationFractionASTM.objects.filter( astm_field=key).exists(): fractionRels = models.RelationFractionASTM.objects.filter( astm_field=key) for fractionRel in fractionRels: fraction = fractionRel.fraction if directions.Issledovaniya.objects.filter( napravleniye=direction, research=fraction.research, doc_confirmation__isnull=True).exists(): issled = directions.Issledovaniya.objects.get( napravleniye=direction, research=fraction.research) fraction_result = None if directions.Result.objects.filter( issledovaniye=issled, fraction=fraction).exists( ): # Если результат для фракции существует fraction_result = directions.Result.objects.get( issledovaniye=issled, fraction__pk=fraction.pk ) # Выборка результата из базы else: fraction_result = directions.Result( issledovaniye=issled, fraction=fraction ) # Создание нового результата fraction_result.value = resdict["result"][ key].strip() # Установка значения if fractionRel.get_multiplier_display() > 1: if fraction_result.value.isdigit(): fraction_result.value = "%s.0" % fraction_result.value import re find = re.findall("\d+.\d+", fraction_result.value) if len(find) > 0: val = int( float(find[0]) * fractionRel.get_multiplier_display()) fraction_result.value = fraction_result.value.replace( find[0], str(val)) fraction_result.iteration = 1 # Установка итерации fraction_result.save() # Сохранение fraction_result.issledovaniye.doc_save = astm_user # Кто сохранил from datetime import datetime fraction_result.issledovaniye.time_save = timezone.now( ) # Время сохранения fraction_result.issledovaniye.save() slog.Log(key=appkey, type=22, body=json.dumps(resdict), user=astm_user).save() result["ok"] = True elif not directions.TubesRegistration.objects.filter( pk=resdict["pk"]).exists(): if dpk > -1: resdict["pk"] = dpk slog.Log(key=resdict["pk"], type=23, body=json.dumps(resdict), user=astm_user).save() except Exception: result = {"ok": False, "Exception": True} return HttpResponse(json.dumps(result), content_type="application/json") # Создание JSON
def save_data(data, doc_who_create): patient_card = Card.objects.filter(pk=data['card_pk'])[0] direction_obj = data['direction'] type_operation = data.get('type_operation', '') doc_operate_obj = DoctorProfile.objects.filter(pk=data['hirurg'])[0] doc_anesthetist = data.get('doc_anesthetist', None) doc_anesthetist_obj = None if doc_anesthetist: doc_anesthetist_obj = DoctorProfile.objects.filter( pk=doc_anesthetist)[0] if data['pk_plan'] == -1: plan_obj = PlanOperations( patient_card=patient_card, direction=direction_obj, date=datetime.strptime(data['date'], '%Y-%m-%d'), doc_operate=doc_operate_obj, type_operation=type_operation, doc_anesthetist=doc_anesthetist_obj, doc_who_create=doc_who_create, canceled=False, ) plan_obj.save() slog.Log( key=plan_obj.pk, type=80001, body=json.dumps({ "card_pk": data['card_pk'], "direction": direction_obj, "date_operation": data['date'], "doc_operate": data['hirurg'], "type_operation": type_operation, }), user=doc_who_create, ).save() else: plan_obj = PlanOperations.objects.filter(pk=data['pk_plan'])[0] plan_obj.doc_operate = doc_operate_obj plan_obj.type_operation = type_operation if 'doc_anesthetist' in data: plan_obj.doc_anesthetist = doc_anesthetist_obj plan_obj.doc_who_create = doc_who_create plan_obj.date = datetime.strptime( data['date'], '%Y-%m-%d') if '-' in data['date'] else datetime.strptime( data['date'], '%d.%m.%Y') plan_obj.direction = direction_obj plan_obj.patient_card = patient_card plan_obj.canceled = False plan_obj.save() slog.Log( key=data['pk_plan'], type=80002, body=json.dumps({ "card_pk": data['card_pk'], "direction": direction_obj, "date_operation": data['date'], "doc_operate": data['hirurg'], "type_operation": type_operation, }), user=doc_who_create, ).save() return plan_obj.pk
def doctor_call_save(data, doc_who_create=None): patient_card = Card.objects.get(pk=data['card_pk']) if 'card' not in data else data['card'] research_obj = Researches.objects.get(pk=data['research']) if int(data['district']) < 0: district_obj = None else: district_obj = District.objects.get(pk=data['district']) if int(data['doc']) < 0: doc_obj = None else: doc_obj = DoctorProfile.objects.get(pk=data['doc']) if int(data['purpose']) < 0: purpose = 5 else: purpose = int(data['purpose']) hospital_obj: Optional[Hospitals] if int(data['hospital']) < 0: hospital_obj = None else: hospital_obj = Hospitals.objects.get(pk=data['hospital']) email = data.get('email') has_external_org = bool(hospital_obj and hospital_obj.remote_url) is_main_external = has_external_org and data.get('is_main_external', SettingManager.l2('send_doc_calls')) doc_call = DoctorCall( client=patient_card, research=research_obj, exec_at=datetime.datetime.strptime(data['date'], '%Y-%m-%d') if isinstance(data['date'], str) else data['date'], comment=data['comment'], doc_who_create=doc_who_create, cancel=False, district=district_obj, address=data['address'], phone=data['phone'], purpose=purpose, doc_assigned=doc_obj, hospital=hospital_obj, is_external=data['external'], is_main_external=bool(is_main_external), external_num=data.get('external_num') or '', email=None if not email else email[:64], need_send_to_external=has_external_org and SettingManager.l2('send_doc_calls') and not is_main_external, direction_id=data.get('direction'), ) if data.get('as_executed'): doc_call.status = 3 doc_call.executor = doc_who_create doc_call.save() slog.Log( key=doc_call.pk, type=80003, body=json.dumps( { "card_pk": patient_card.pk, "card": str(patient_card), "research": research_obj.title, "district": district_obj.title if district_obj else None, "purpose": doc_call.get_purpose_display(), "doc_assigned": str(doc_obj), "hospital": str(hospital_obj), "date": str(data['date']), "comment": data['comment'], "is_external": data['external'], "external_num": data.get('external_num'), "is_main_external": data.get('is_main_external'), "email": email, "as_executed": data.get('as_executed'), } ), user=doc_who_create, ).save() return doc_call