def check_rmis(self, update=True, client=None): from rmis_integration.client import Client if client is None: client = Client() rmis_id = client.patients.get_rmis_id_for_individual(individual=self) if rmis_id and rmis_id != 'NONERMIS': from directions.models import Napravleniya Napravleniya.objects.filter(client__individual=self, rmis_number='NONERMIS').update(rmis_number=None) return rmis_id
def handle(self, *args, **options): c = RC() request_data = { "refbookCode": "1.2.643.5.1.13.3.1058506043530.1.1.5", "version": "CURRENT", } count_parts = c.get_client("path_directory").service.getRefbookParts(**request_data) for i in range(count_parts): request_data['partNumber'] = i + 1 mkb_part = c.get_client("path_directory").service.getRefbookPartial(**request_data) for m in mkb_part: data = m['column'] code, name, rmis_id = '', '', '' m_type = 1 for j in data: if j['name'] == 'CODE': code = j['data'] if j['name'] == 'NAME': name = j['data'] if j['name'] == 'ID': rmis_id = j['data'] if j['name'] == 'HAS_CHILD': if j['data'] == 'true': m_type = 1 else: m_type = 2 if "-" in code: continue diag = Diagnoses.objects.filter(code=code).first() if diag: if diag.title != name: diag.title = name if rmis_id and diag.rmis_id != rmis_id: diag.rmis_id = rmis_id diag.m_type = m_type diag.save() print(f"обновлено: {code}-{name}-{m_type}") # noqa: T001 if diag is None: Diagnoses(code=code, title=name, m_type=m_type, d_type='mkb10.4', rmis_id=rmis_id).save() print(f"создано: {code}-{name}-{m_type}") # noqa: T001
def handle(self, *args, **options): # sema = threading.BoundedSemaphore(4) c = RC() srv = c.services.client.getServices(clinic=c.search_organization_id()) self.stdout.write("!!!!!!!") self.cnt = len(srv) def ip(self, c, r): # sema.acquire() try: data = helpers.serialize_object( c.services.client.getService(r["id"])) inactive = False if data["toDate"]: inactive = datetime.strptime( data["toDate"].strftime('%Y%m%d'), "%Y%m%d") < datetime.now() RMISServiceInactive.checkInactive(serviceId=r["id"], enabled=inactive) finally: self.n += 1 self.nn += 1 if self.n % 10 == 0 or self.n == self.cnt: self.stdout.write("{}/{}".format(self.n, self.cnt)) if self.n % 100 == 0 or self.n == self.cnt: sec = time.time() - self.start_time self.start_time = time.time() self.stdout.write("--- %s op/s ---" % (int(self.nn / sec))) self.nn = 0 # sema.release() self.start_time = time.time() threads = [] for r in srv: ip(self, c, r) # thread = threading.Thread(target=ip, args= # threads.append(thread) # thread.start() [t.join() for t in threads]
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 handle(self, *args, **options): self.stdout.write("{:%Y-%m-%d %H:%M}".format(datetime.datetime.now()) + " - TRIGGER") ind = Individual.objects.all() all_cnt = ind.count() cnt = 0 c = Client() for i in ind: cnt += 1 i.sync_with_rmis(out=self.stdout, c=c) self.stdout.write("Снхронизировано {}/{}".format(cnt, all_cnt)) ind = Individual.objects.all() after_ind = ind.count() self.stdout.write("Физ.лиц осталось {} из {}".format( after_ind, all_cnt))
def handle(self, *args, **options): maxthreads = 10 sema = threading.BoundedSemaphore(maxthreads) threads = list() def task(dir: Napravleniya, out): sema.acquire() try: out.write( "ADD TO RESEND %s -> %s" % (dir.pk, c.directions.delete_services( dir, user=DoctorProfile.objects.all().order_by("pk")[0]))) finally: sema.release() try: connections.close_all() if out: out.write("Closed db connections") except Exception as e: if out: out.write(f"Error closing connections {e}") def resend(out): out.write("END") r = options['directions_range'].split('-') f = r[0] t = r[1] c = Client() for d in Napravleniya.objects.filter(pk__gte=f, pk__lte=t): thread = threading.Thread(target=task, args=(d, self.stdout)) threads.append(thread) try: thread.start() except RuntimeError: threads.remove(thread) [t.join() for t in threads] resend(self.stdout) self.stdout.write( json.dumps( c.directions.check_and_send_all(self.stdout, maxthreads=6)))
def handle(self, *args, **options): c = Client() sd = c.directions.search_directions(**dict( token.split(':') for token in options['query'].split(','))) self.stdout.write("PKS: %s" % json.dumps(sd)) datas = [ helpers.serialize_object(c.directions.get_direction_data(x)) for x in sd ] datas = [x for x in datas if x.get("refServiceId")] self.stdout.write("datas: %s" % json.dumps(datas, default=json_serial)) datas2 = [c.directions.get_direction_full_data(x["id"]) for x in datas] self.stdout.write("Fdatas: %s" % json.dumps(datas2, default=json_serial)) srv = {} for d in datas: for s in d["refServiceId"]: if s not in srv: srv[s] = helpers.serialize_object( c.services.get_service_data(s)) self.stdout.write("srv: %s" % json.dumps(srv, default=json_serial))
def reset_confirm(request): request_data = json.loads(request.body) pk = request_data["pk"] result = {"ok": False, "message": "Неизвестная ошибка"} if Issledovaniya.objects.filter(pk=pk).exists(): iss: Issledovaniya = Issledovaniya.objects.get(pk=pk) if iss.allow_reset_confirm(request.user): predoc = { "fio": iss.doc_confirmation_fio or 'не подтверждено', "pk": pk, "direction": iss.napravleniye_id } iss.doc_confirmation = iss.executor_confirmation = iss.time_confirmation = None iss.save() iss.napravleniye.sync_confirmed_fields() if iss.napravleniye.result_rmis_send: c = Client() c.directions.delete_services(iss.napravleniye, request.user.doctorprofile) if iss.napravleniye: iss.napravleniye.need_resend_amd = False iss.napravleniye.save() if iss.napravleniye: iss.napravleniye.need_resend_amd = False iss.napravleniye.eds_total_signed = False iss.napravleniye.eds_total_signed_at = None iss.napravleniye.vi_id = None iss.napravleniye.save(update_fields=[ 'eds_total_signed', 'eds_total_signed_at', 'need_resend_amd', 'vi_id' ]) result = {"ok": True} Log.log(str(pk), 24, body=predoc, user=request.user.doctorprofile) else: result[ "message"] = f"Сброс подтверждения разрешен в течении {str(SettingManager.get('lab_reset_confirm_time_min'))} минут" return JsonResponse(result)
def sync_departments(request): c = Client() return HttpResponse("Добавлено: %s. Обновлено: %s." % c.department.sync_departments(), content_type="text/plain")
def rmis_check(request): c = Client() return HttpResponse(c.search_organization_id(check=True) + " " + c.search_dep_id(check=True), content_type="text/plain")
def handle(self, *args, **options): c = Client() self.stdout.write(str(c.get_organization_title(options["id"], full=True))) self.stdout.write(str(c.get_organization_title(options["id"])))
def receive_db(request): # key = request.POST["key"] data = request.POST["data"] code = request.POST["code"] base = Clients.CardBase.objects.filter(short_title=code).first() d = json.loads(data) bulk_cards = [] def fix(s: str): return s.strip().title() from rmis_integration.client import Client from slog.models import Log # Log(key="receive_db", type=0, body=data, user=None).save() c = None try: if SettingManager.get("rmis_enabled", default='false', default_type='b'): c = Client(modules="patients") except (requests.exceptions.ConnectionError, Fault): pass docs_types = Clients.DocumentType.objects.filter( title__startswith="Полис ОМС") snils_types = Clients.DocumentType.objects.filter( title__startswith="СНИЛС") for x in d: polis = Clients.Document.objects.filter( document_type__in=docs_types, serial=x.get("Polisser", ""), number=x.get("Polisnum", "")).exclude(number="") snils = Clients.Document.objects.filter( document_type=snils_types.first(), number=x.get("Snils", "")).exclude(number="") if snils.exists() or polis.exists(): individual = (snils if snils.exists() else polis)[0].individual if not Clients.Card.objects.filter(individual=individual, base__is_rmis=True).exists(): individual.family = fix(x["Family"]) individual.name = fix(x["Name"]) individual.patronymic = fix(x["Twoname"]) individual.birthday = datetime.datetime.strptime( x["Bday"], "%d.%m.%Y").date() individual.sex = x["Sex"].lower().strip() individual.save() else: individual = Clients.Individual.objects.filter( family=fix(x["Family"]), name=fix(x["Name"]), patronymic=fix(x["Twoname"]), birthday=datetime.datetime.strptime( x["Bday"], "%d.%m.%Y").date()).order_by("-pk") if not individual.exists(): individual = Clients.Individual( family=fix(x["Family"]), name=fix(x["Name"]), patronymic=fix(x["Twoname"]), birthday=datetime.datetime.strptime(x["Bday"], "%d.%m.%Y").date(), sex=x["Sex"]) individual.save() else: individual = individual[0] if individual.sex != x["Sex"]: individual.sex = x["Sex"] individual.save() if x.get("Polisnum", "") != "": polis = Clients.Document.objects.filter( document_type__in=Clients.DocumentType.objects.filter( title__startswith="Полис ОМС"), serial=x["Polisser"], number=x["Polisnum"], individual=individual).order_by("-pk") if not polis.exists(): polis = [ Clients.Document( document_type=Clients.DocumentType.objects.filter( title__startswith="Полис ОМС").first(), serial=x["Polisser"], number=x["Polisnum"], individual=individual).save() ] if x.get("Snils", "") != "": snils = Clients.Document.objects.filter( document_type=Clients.DocumentType.objects.filter( title="СНИЛС").first(), number=x["Snils"], individual=individual).order_by("-pk") if not snils.exists(): Clients.Document( document_type=Clients.DocumentType.objects.filter( title="СНИЛС").first(), number=x["Snils"], individual=individual).save() if c is not None: try: individual.sync_with_rmis(c=c) except (requests.exceptions.ConnectionError, Fault): pass cards = Clients.Card.objects.filter( number=x["Number"], base=base, is_archive=False).exclude(individual=individual) todelete = [] for acard in cards: directions = [x.pk for x in acard.napravleniya_set.all()] Log(key=str(acard.pk), type=2004, body=json.dumps({ "individual": str(acard.individual), "directions": directions, "number": acard.number_with_type() }), user=None).save() acard.is_archive = True acard.save() if len(directions) == 0: todelete.append(acard.pk) Log(key=str(acard.pk), type=2005, body="", user=None).save() Clients.Card.objects.filter(pk__in=todelete).delete() if not Clients.Card.objects.filter( number=x["Number"], base=base, is_archive=False).exists(): polis = list(polis) card = Clients.Card(number=x["Number"], base=base, individual=individual, is_archive=False, polis=None if len(polis) == 0 else polis[0], main_diagnosis=x.get("MainDiagnosis", "")) card.save() for t in x.get("Tels", []): card.add_phone(t) card.clear_phones(x.get("Tels", [])) card.main_address = x.get("MainAddress", "") else: for card in Clients.Card.objects.filter(number=x["Number"], base=base, is_archive=False): for t in x.get("Tels", []): card.add_phone(t) card.clear_phones(x.get("Tels", [])) if card.main_diagnosis != x.get( "MainDiagnosis", "") or card.main_address != x.get( "MainAddress", ""): card.main_diagnosis = x.get("MainDiagnosis", "") card.main_address = x.get("MainAddress", "") card.save() if len(bulk_cards) != 0: Clients.Card.objects.bulk_create(bulk_cards) return HttpResponse("OK", content_type="text/plain")
def sync_with_rmis(self, out: OutputWrapper = None, c=None): if out: out.write("Обновление данных для: %s" % self.fio(full=True)) if c is None: from rmis_integration.client import Client c = Client() ok = False has_rmis = False rmis_uid = "" if Card.objects.filter(individual=self, base__is_rmis=True).exists(): rmis_uid = Card.objects.filter(individual=self, base__is_rmis=True)[0].number ok = has_rmis = True if out: out.write("Есть РМИС запись: %s" % rmis_uid) if not ok: docs = Document.objects.filter(individual=self).exclude(document_type__check_priority=0).order_by( "-document_type__check_priority") for document in docs: s = c.patients.search_by_document(document) if len(s) > 0: rmis_uid = s[0] ok = True if out: out.write("Физ.лицо найдено по документу: %s -> %s" % (document, rmis_uid)) break if ok: data = c.patients.get_data(rmis_uid) upd = self.family != data["family"] or self.name != data["name"] or self.patronymic != data[ "patronymic"] or (self.birthday != data["birthday"] and data["birthday"] is not None) if upd: prev = str(self) self.family = data["family"] self.name = data["name"] self.patronymic = data["patronymic"] if data["birthday"] is not None: self.birthday = data["birthday"] self.sex = data["sex"] self.save() if out: out.write("Обновление данных: %s" % self.fio(full=True)) slog.Log(key=str(self.pk), type=2003, body=simplejson.dumps({"Новые данные": str(self), "Не актуальные данные": prev}), user=None).save() if not ok: query = {"surname": self.family, "name": self.name, "patrName": self.patronymic, "birthDate": self.birthday.strftime("%Y-%m-%d")} rows = c.patients.client.searchIndividual(**query) if len(rows) == 1: rmis_uid = rows[0] ok = True if out: out.write("Физ.лицо найдено по ФИО и д.р.: %s" % rmis_uid) if not has_rmis and rmis_uid and rmis_uid != '': ex = Card.objects.filter(number=rmis_uid, is_archive=False, base__is_rmis=True) if ex.exists(): for e in ex: self.join_individual(e.individual, out) s = str(c.patients.create_rmis_card(self, rmis_uid)) if out: out.write("Добавление РМИС карты -> %s" % s) save_docs = [] if ok and rmis_uid != "" and Card.objects.filter(individual=self, base__is_rmis=True, is_archive=False).exists(): pat_data = c.patients.extended_data(rmis_uid) cards = Card.objects.filter(individual=self, base__is_rmis=True, is_archive=False) for card_i in cards: c.patients.sync_card_data(card_i, out) def get_key(d: dict, val): r = [key for key, v in d.items() if v == val] if len(r) > 0: return r[0] return None if out: out.write("Типы документов: %s" % simplejson.dumps(c.patients.local_types)) for document_object in pat_data["identifiers"] or []: k = get_key(c.patients.local_types, document_object["type"]) if k and document_object["active"]: if out: out.write("Тип: %s -> %s (%s)" % (document_object["type"], k, document_object["active"])) data = dict(document_type=DocumentType.objects.get(pk=k), serial=document_object["series"] or "", number=document_object["number"] or "", date_start=document_object["issueDate"], date_end=document_object["expiryDate"], who_give=(document_object["issueOrganization"] or {"name": ""})["name"] or "", individual=self, is_active=True) rowss = Document.objects.filter(document_type=data['document_type'], individual=self, from_rmis=True) if rowss.exclude(serial=data["serial"]).exclude(number=data["number"]).filter( card__isnull=True).exists(): Document.objects.filter(document_type=data['document_type'], individual=self, from_rmis=True).delete() docs = Document.objects.filter(document_type=data['document_type'], serial=data['serial'], number=data['number'], from_rmis=True) if not docs.exists(): doc = Document(**data) doc.save() if out: out.write("Добавление докумена: %s" % doc) kk = "%s_%s_%s" % (doc.document_type.pk, doc.serial, doc.number) save_docs.append(kk) continue else: to_delete = [] has = [] ndocs = {} for d in docs: kk = "%s_%s_%s" % (d.document_type.pk, d.serial, d.number) if out: out.write("Checking: %s" % kk) if kk in has: if out: out.write("to delete: %s" % d.pk) to_delete.append(d.pk) if Card.objects.filter(polis=d).exists(): for c in Card.objects.filter(polis=d): c.polis = ndocs[kk] c.save() else: if out: out.write("To has: %s" % d.pk) has.append(kk) save_docs.append(kk) ndocs[kk] = d Document.objects.filter(pk__in=to_delete).delete() docs = Document.objects.filter(document_type=data['document_type'], serial=data['serial'], number=data['number'], individual=self) for d in docs: if d.date_start != data["date_start"]: d.date_start = data["date_start"] d.save() if out: out.write("Update date_start: %s" % d.date_start) if d.date_end != data["date_end"]: d.date_end = data["date_end"] d.save() if out: out.write("Update date_end: %s" % d.date_end) if d.who_give != data["who_give"]: d.who_give = data["who_give"] d.save() if out: out.write("Update who_give: %s" % d.who_give) if out: out.write("Данные для документов верны: %s" % [str(x) for x in docs]) docs = Document.objects.filter(document_type=data['document_type'], document_type__title__in=['СНИЛС', 'Паспорт гражданина РФ', 'Полис ОМС'], serial=data['serial'], number=data['number']).exclude(individual=self).exclude(number="") if docs.exists(): if out: out.write("Объединение записей физ.лиц") for doc in docs: self.join_individual(doc.individual, out) to_delete_pks = [] for d in Document.objects.filter(individual=self, from_rmis=True): kk = "%s_%s_%s" % (d.document_type.pk, d.serial, d.number) if out: out.write("TD %s %s %s" % (kk, kk not in save_docs, save_docs,)) if kk not in save_docs: to_delete_pks.append(d.pk) Document.objects.filter(pk__in=to_delete_pks).delete() else: if out: out.write("Физ.лицо не найдено в РМИС") return ok