Example #1
0
    def build_local_entities(self, header_meta, pack_entity):
        clinic_data = pack_entity['data']
        clinic_addition = safe_traverse(pack_entity, 'addition') or {}
        AddressAllInfos = clinic_addition.get(TambovEntityCode.ADDRESS_ALL_INFO)
        entities = RequestEntities(self.reformer.stream_id)

        src_entity_code = header_meta['remote_entity_code']
        src_operation_code = header_meta['remote_operation_code']

        # сопоставление параметров родительских сущностей
        # params_map = {
        #     TambovEntityCode.SMART_PATIENT: {
        #         'entity': RisarEntityCode.CARD, 'param': 'card_id'
        #     }
        # }
        # self.reform_remote_parents_params(header_meta, src_entity_code, params_map)

        org_item = entities.set_main_entity(
            dst_entity_code=RisarEntityCode.ORGANIZATION,
            dst_parents_params=header_meta['local_parents_params'],
            dst_main_id_name='regionalCode',
            src_operation_code=src_operation_code,
            src_entity_code=src_entity_code,
            src_main_id_name=header_meta['remote_main_param_name'],
            src_id=header_meta['remote_main_id'],
            level_count=1,
        )
        if src_operation_code != OperationCode.DELETE:
            self.build_local_org_body(org_item, clinic_data, AddressAllInfos, header_meta)

        return entities
Example #2
0
    def build_local_entities(self, header_meta, pack_entity):
        src_entity_code = header_meta['remote_entity_code']
        src_operation_code = header_meta['remote_operation_code']

        # сопоставление параметров родительских сущностей
        params_map = {
            TambovEntityCode.CLINIC: {
                'entity': RisarEntityCode.ORGANIZATION,
                'param': 'regionalCode'
            }
        }
        self.reform_remote_parents_params(header_meta, src_entity_code,
                                          params_map)

        entities = RequestEntities(self.reformer.stream_id)
        doctor_item = entities.set_main_entity(
            dst_entity_code=RisarEntityCode.DOCTOR,
            dst_parents_params=header_meta['local_parents_params'],
            dst_main_id_name='regional_code',
            src_operation_code=src_operation_code,
            src_entity_code=src_entity_code,
            src_main_id_name=header_meta['remote_main_param_name'],
            src_id=pack_entity['main_id'],
            level_count=1,
        )
        if src_operation_code != OperationCode.DELETE:
            empl_pos_addition = pack_entity[
                'addition']  # в эмплой позишн клали индивид, т.к. первый не нужен в диффах
            self.build_local_doctor_body(doctor_item, pack_entity,
                                         empl_pos_addition, header_meta,
                                         pack_entity['main_id'])

        return entities
Example #3
0
    def build_local_entities(self, header_meta, data):
        src_operation_code = self.get_operation_code_by_method(
            header_meta['remote_method'])
        entities = RequestEntities(self.reformer.stream_id)
        main_item = entities.set_main_entity(
            dst_entity_code=RisarEntityCode.ORG_DEPARTMENT,
            dst_parents_params=header_meta['local_parents_params'],
            dst_main_id_name='regionalCode',
            src_operation_code=src_operation_code,
            src_entity_code=header_meta['remote_entity_code'],
            src_main_id_name=header_meta['remote_main_param_name'],
            src_id=header_meta['remote_main_id'],
            level_count=1,
        )
        if src_operation_code != OperationCode.DELETE:
            main_item['body'] = data
            # внешний код хранится в рисар в исходном виде
            # if 'organisation_id' in data:
            #     org_id = self.reformer.get_local_id_by_remote(
            #         RisarEntityCode.ORGANIZATION,
            #         TulaEntityCode.ORGANIZATION,
            #         data['organisation_id'],
            #     )
            #     main_item['body']['organisation_id'] = org_id

        return entities
Example #4
0
    def build_local_entities(self, header_meta, data):
        src_entity_code = header_meta['remote_entity_code']
        src_operation_code = self.get_operation_code_by_method(
            header_meta['remote_method'])

        # сопоставление параметров родительских сущностей
        params_map = {
            TulaEntityCode.ORGANIZATION: {
                'entity': RisarEntityCode.ORGANIZATION,
                'param': 'organization'
            },
        }
        self.reform_remote_parents_params(header_meta, src_entity_code,
                                          params_map)

        entities = RequestEntities(self.reformer.stream_id)
        main_item = entities.set_main_entity(
            dst_entity_code=RisarEntityCode.DOCTOR,
            dst_parents_params=header_meta['local_parents_params'],
            dst_main_id_name='regional_code',
            src_operation_code=src_operation_code,
            src_entity_code=src_entity_code,
            src_main_id_name=header_meta['remote_main_param_name'],
            src_id=header_meta['remote_main_id'],
            level_count=1,
        )
        if src_operation_code != OperationCode.DELETE:
            main_item['body'] = data.copy()
            if 'department' in data:
                # при ПОСТ сопоставления еще нет и писать филиал некуда
                # сейчас филиал дозапрашивается при записи на прием
                # self.save_doct_filial(data['regional_code'], data['department'])
                del main_item['body']['department']

        return entities
Example #5
0
    def build_local_entities(self, header_meta, data):
        src_entity_code = header_meta['remote_entity_code']
        src_operation_code = self.get_operation_code_by_method(
            header_meta['remote_method'])

        # сопоставление параметров родительских сущностей
        params_map = {
            TulaEntityCode.CARD: {
                'entity': RisarEntityCode.CARD,
                'param': 'card_id'
            },
        }
        self.reform_remote_parents_params(header_meta, src_entity_code,
                                          params_map)

        entities = RequestEntities(self.reformer.stream_id)
        main_item = entities.set_main_entity(
            dst_entity_code=RisarEntityCode.CHECKUP_OBS_SECOND_TICKET,
            dst_parents_params=header_meta['local_parents_params'],
            dst_main_id_name='exam_obs_id',
            src_operation_code=src_operation_code,
            src_entity_code=src_entity_code,
            src_main_id_name=header_meta['remote_main_param_name'],
            src_id=header_meta['remote_main_id'],
            level_count=1,
        )
        if src_operation_code != OperationCode.DELETE:
            main_item['body'] = data

        return entities
Example #6
0
    def build_local_entities(self, header_meta, data):
        src_entity_code = header_meta['remote_entity_code']
        src_operation_code = self.get_operation_code_by_method(header_meta['remote_method'])

        # сопоставление параметров родительских сущностей
        params_map = {
            TulaEntityCode.CARD: {
                'entity': RisarEntityCode.CARD, 'param': 'card_id'
            },
        }
        self.reform_remote_parents_params(header_meta, src_entity_code, params_map)

        entities = RequestEntities(self.reformer.stream_id)
        main_item = entities.set_main_entity(
            dst_entity_code=RisarEntityCode.MEASURE_HOSPITALIZATION,
            dst_parents_params=header_meta['local_parents_params'],
            dst_main_id_name='result_action_id',
            src_operation_code=src_operation_code,
            src_entity_code=src_entity_code,
            src_main_id_name=header_meta['remote_main_param_name'],
            src_id=header_meta['remote_main_id'],
            level_count=1,
        )
        if src_operation_code != OperationCode.DELETE:
            main_item['body'] = data
            main_item['body']['result_action_id'] = ''  # заполняется в set_current_id_common_func
            if data['measure_id']:
                local_measure_id = self.reformer.get_local_id_by_remote(
                    RisarEntityCode.MEASURE,
                    TulaEntityCode.MEASURE,
                    data['measure_id'],
                )
                main_item['body']['measure_id'] = local_measure_id

        return entities
Example #7
0
    def build_local_entities(self, header_meta, pack_entity):
        sm_patient_data = pack_entity['data']
        patient_node = pack_entity['addition'][TambovEntityCode.PATIENT][0]
        patient_data = patient_node['data']
        src_entity_code = header_meta['remote_entity_code']
        src_operation_code = header_meta['remote_operation_code']

        # сопоставление параметров родительских сущностей
        # params_map = {
        #     TambovEntityCode.SMART_PATIENT: {
        #         'entity': RisarEntityCode.CARD, 'param': 'card_id'
        #     }
        # }
        # self.reform_remote_parents_params(header_meta, src_entity_code, params_map)

        entities = RequestEntities(self.reformer.stream_id)
        main_item = entities.set_main_entity(
            dst_entity_code=RisarEntityCode.CLIENT,
            dst_parents_params=header_meta['local_parents_params'],
            dst_main_id_name='client_id',
            src_operation_code=src_operation_code,
            src_entity_code=src_entity_code,
            src_main_id_name=header_meta['remote_main_param_name'],
            src_id=header_meta['remote_main_id'],
            level_count=1,
        )
        if src_operation_code != OperationCode.DELETE:
            self.build_local_client_body(main_item, sm_patient_data,
                                         patient_data)

        return entities
Example #8
0
    def build_local_entities(self, header_meta, pack_entity):
        src_entity_code = header_meta['remote_entity_code']
        src_operation_code = header_meta['remote_operation_code']
        hospital_rec_data = pack_entity['data']
        case_entity = pack_entity['addition'][TambovEntityCode.CASE][0]
        case_data = case_entity['data']

        # сопоставление параметров родительских сущностей
        params_map = {
            TambovEntityCode.SMART_PATIENT: {
                'entity': RisarEntityCode.CARD,
                'param': 'card_id'
            },
        }
        self.reform_remote_parents_params(header_meta, src_entity_code,
                                          params_map)
        dm = DiagsMatch()

        entities = RequestEntities(self.reformer.stream_id)
        hosp_entity = entities.set_main_entity(
            dst_entity_code=RisarEntityCode.MEASURE_HOSPITALIZATION,
            dst_parents_params=header_meta['local_parents_params'],
            dst_main_id_name='result_action_id',
            src_operation_code=src_operation_code,
            src_entity_code=src_entity_code,
            src_main_id_name=header_meta['remote_main_param_name'],
            src_id=header_meta['remote_main_id'],
            level_count=1,
        )
        if src_operation_code != OperationCode.DELETE:
            employee_position_id = self.get_employee_position(
                hospital_rec_data['resourceGroupId'])
            diag_1_code = diag_4_code = None
            for diag_data in case_data['diagnoses']:
                if diag_data['stageId'] == '1':
                    diag_1_code = dm.diag_code(diag_data['diagnosId'])
                elif diag_data['stageId'] == '4':
                    diag_4_code = dm.diag_code(diag_data['diagnosId'])
            hosp_entity['body'] = {
                # 'result_action_id': None,  # заполняется в set_current_id_func
                # 'measure_id': None,  # мис сама не отдаёт направление госп.
                'hospital': case_data['medicalOrganizationId'],
                'doctor': employee_position_id,
                'diagnosis_in': diag_1_code
                or 'A01.1',  # нет поля в сервисе, они будут доделывать
                'diagnosis_out': diag_4_code
                or 'A01.1',  # нет поля в сервисе, они будут доделывать
                # --
                'external_id': header_meta['remote_main_id'],
                'date_in': encode(hospital_rec_data['admissionDate'])
                or Undefined,
                'date_out': encode(hospital_rec_data['outcomeDate'])
                or Undefined,
                'status': 'performed',
            }
        return entities
Example #9
0
    def build_remote_entities(self, header_meta, pack_entity):
        """
        Вход в header_meta
        local_operation_code
        local_entity_code
        local_main_param_name
        local_main_id
        local_parents_params

        Выход в entity
        dst_entity_code
        dst_main_param_name
        """
        card_data = pack_entity['data']
        src_operation_code = header_meta['local_operation_code']
        src_entity_code = header_meta['local_entity_code']

        # сопоставление параметров родительских сущностей
        params_map = {
            RisarEntityCode.CLIENT: {
                'entity': TulaEntityCode.CLIENT,
                'param': 'client_id'
            }
        }
        self.reform_local_parents_params(header_meta, src_entity_code,
                                         params_map)

        entities = RequestEntities(self.reformer.stream_id)
        main_item = entities.set_main_entity(
            dst_entity_code=TulaEntityCode.CARD,
            dst_parents_params=header_meta['remote_parents_params'],
            dst_main_id_name='card_id',
            src_operation_code=src_operation_code,
            src_entity_code=src_entity_code,
            src_main_id_name=header_meta['local_main_param_name'],
            src_id=header_meta['local_main_id'],
            level_count=1,
        )
        if src_operation_code != OperationCode.DELETE:
            main_item['body'] = card_data
            main_item['body'][
                'client_id'] = self.reformer.get_remote_id_by_local(
                    TulaEntityCode.CLIENT,
                    RisarEntityCode.CLIENT,
                    main_item['body']['client_id'],
                )

        return entities
Example #10
0
    def build_local_entities(self, header_meta, data):
        src_operation_code = self.get_operation_code_by_method(header_meta['remote_method'])
        entities = RequestEntities(self.reformer.stream_id)
        main_item = entities.set_main_entity(
            dst_entity_code=RisarEntityCode.ORGANIZATION,
            dst_parents_params=header_meta['local_parents_params'],
            dst_main_id_name='regionalCode',
            src_operation_code=src_operation_code,
            src_entity_code=header_meta['remote_entity_code'],
            src_main_id_name=header_meta['remote_main_param_name'],
            src_id=header_meta['remote_main_id'],
            level_count=1,
        )
        if src_operation_code != OperationCode.DELETE:
            main_item['body'] = data

        return entities
Example #11
0
    def build_local_entities(self, header_meta, data):
        src_operation_code = self.get_operation_code_by_method(
            header_meta['remote_method'])
        entities = RequestEntities(self.reformer.stream_id)
        main_item = entities.set_main_entity(
            dst_entity_code=RisarEntityCode.CLIENT,
            dst_parents_params=header_meta['local_parents_params'],
            dst_main_id_name='client_id',
            src_operation_code=src_operation_code,
            src_entity_code=header_meta['remote_entity_code'],
            src_main_id_name=header_meta['remote_main_param_name'],
            src_id=header_meta['remote_main_id'],
            level_count=1,
        )
        if src_operation_code != OperationCode.DELETE:
            main_item['body'] = deepcopy(data)
            main_item['body'][
                'client_id'] = ''  # заполняется в set_current_id_common_func
            if 'document' in data:
                main_item['body']['documents'] = [
                    main_item['body'].pop('document')
                ]

        return entities
Example #12
0
    def build_remote_entities(self, header_meta, pack_entity):
        """
        Вход в header_meta
        local_operation_code
        local_entity_code
        local_main_param_name
        local_main_id
        local_parents_params

        Выход в entity
        dst_entity_code
        dst_main_param_name
        """
        schedule_ticket_data = pack_entity['data']
        src_operation_code = header_meta['local_operation_code']
        src_entity_code = header_meta['local_entity_code']

        # сопоставление параметров родительских сущностей
        params_map = {
            RisarEntityCode.DOCTOR: {
                'entity': TulaEntityCode.DOCTOR,
                'param': 'doctor'
            },
            RisarEntityCode.CLIENT: {
                'entity': TulaEntityCode.CLIENT,
                'param': 'patient'
            },
        }
        self.reform_local_parents_params(header_meta, src_entity_code,
                                         params_map)

        entities = RequestEntities(self.reformer.stream_id)

        remote_id_prefix = None
        if src_operation_code != OperationCode.DELETE:
            if schedule_ticket_data['schedule_ticket_type'] == '1':
                remote_id_prefix = 'outplan'
            else:
                remote_id_prefix = 'plan'

        def after_send_func(entity_meta, entity_body, answer_body):
            if src_operation_code != OperationCode.DELETE:
                res = self.reformer.update_local_match_parent(
                    RisarEntityCode.SCHEDULE_TICKET,
                    TulaEntityCode.SCHEDULE_TICKET,
                    schedule_ticket_data['schedule_ticket_id'],
                    matching_parent_id,
                )
                if not res:
                    raise InternalError(
                        u'Не удалось привязать тикет (%s) к родителю (%s)' %
                        (schedule_ticket_data['schedule_ticket_id'],
                         matching_parent_id))

        main_item = entities.set_main_entity(
            dst_entity_code=TulaEntityCode.SCHEDULE_TICKET,
            dst_parents_params=header_meta['remote_parents_params'],
            dst_main_id_name='schedule_ticket_id',
            dst_id_prefix=remote_id_prefix,
            src_operation_code=src_operation_code,
            src_entity_code=src_entity_code,
            src_main_id_name=header_meta['local_main_param_name'],
            after_send_func=after_send_func,
            src_id=header_meta['local_main_id'],
            level_count=1,
            dst_request_mode=RequestModeCode.XML_DATA,
        )
        remote_pp = header_meta['remote_parents_params']
        filial_code = self.get_filial_code(
            remote_pp['doctor']['id'],
            schedule_ticket_data['date'],
        )
        remote_sch_ticket_id = None
        if src_operation_code != OperationCode.ADD:
            remote_sch_ticket_id = self.reformer.get_remote_id_by_local(
                TulaEntityCode.SCHEDULE_TICKET,
                RisarEntityCode.SCHEDULE_TICKET,
                schedule_ticket_data['schedule_ticket_id'],
            )
        if src_operation_code != OperationCode.DELETE:
            matching_parent = self.reformer.get_by_local_id(
                TulaEntityCode.SCHEDULE,
                RisarEntityCode.SCHEDULE,
                schedule_ticket_data['schedule_id'],
            )
            matching_parent_id = matching_parent.id
            if schedule_ticket_data['schedule_ticket_type'] == '1':
                time_begin = schedule_ticket_data[
                    'time_begin'] or datetime.today().time().isoformat()[:5]
                sch_treat_add_req_data = self.get_sch_treat_add_req_data(
                    filial_code,
                    remote_pp['patient']['id'],
                    remote_pp['doctor']['id'],
                    schedule_ticket_data['date'],
                    remote_sch_ticket_id,
                    schedule_ticket_data['schedule_ticket_id'],
                    time_begin,
                )
                main_item['body'] = sch_treat_add_req_data
            else:
                remote_schedule_id = matching_parent.remote_id
                sched_reserve_req_data = self.get_sch_reserve_req_data(
                    filial_code,
                    remote_pp['patient']['id'],
                    remote_pp['doctor']['id'],
                    schedule_ticket_data['date'],
                    remote_schedule_id,
                    schedule_ticket_data['schedule_ticket_id'],
                    schedule_ticket_data['time_begin'],
                    schedule_ticket_data['time_end'],
                )
                main_item['body'] = sched_reserve_req_data
        else:
            if schedule_ticket_data['schedule_ticket_type'] == '1':
                today = datetime.today()
                today_date = today.date()
                today_time = today.time()
                sched_remove_req_data = self.get_sch_treat_remove_req_data(
                    filial_code,
                    remote_pp['patient']['id'],
                    remote_pp['doctor']['id'],
                    schedule_ticket_data['date'],
                    remote_sch_ticket_id,
                    schedule_ticket_data['schedule_ticket_id'],
                    today_time.isoformat()[:5],
                    today_date.isoformat(),
                    schedule_ticket_data['current_person'],
                )
                main_item['body'] = sched_remove_req_data
            else:
                sched_remove_req_data = self.get_sch_remove_req_data(
                    filial_code,
                    remote_pp['patient']['id'],
                    remote_sch_ticket_id,
                )
                main_item['body'] = sched_remove_req_data

        return entities
Example #13
0
    def build_remote_entities_checkup(self, header_meta, pack_entity,
                                      checkup_code, gen_info):
        """
        Требует в header_meta
        local_operation_code
        local_entity_code
        local_main_param_name
        local_main_id
        local_parents_params

        Устанавливает в entity
        dst_entity_code
        """
        ticket_data = pack_entity['data']
        src_operation_code = header_meta['local_operation_code']
        src_entity_code = header_meta['local_entity_code']
        resource_group_id = None

        # сопоставление параметров родительских сущностей
        params_map = {
            RisarEntityCode.CARD: {
                'entity': TambovEntityCode.SMART_PATIENT,
                'param': 'patientUid'
            }
        }
        self.reform_local_parents_params(header_meta, src_entity_code,
                                         params_map)
        dm = DiagsMatch()

        entities = RequestEntities(self.reformer.stream_id)
        main_item = entities.set_main_entity(
            dst_entity_code=TambovEntityCode.CASE,
            dst_parents_params=header_meta['remote_parents_params'],
            dst_main_id_name='id',
            src_operation_code=src_operation_code,
            src_entity_code=src_entity_code,
            src_main_id_name=header_meta['local_main_param_name'],
            src_id=header_meta['local_main_id'],
            level_count=2,
        )
        if src_operation_code != OperationCode.DELETE:
            main_item['body'] = {
                # 'id': None,  # проставляется в set_current_id_func
                'uid':
                str(header_meta['local_main_id']),
                'patientUid':
                header_meta['remote_parents_params']['patientUid']['id'],
                'medicalOrganizationId':
                safe_traverse(ticket_data, 'hospital') or '',
                'caseTypeId':
                '1',
                'fundingSourceTypeId':
                '1',
                'careRegimenId':
                '1',
                'paymentMethodId':
                '22',
                'careLevelId':
                safe_traverse(ticket_data, 'medical_care'),
                # неотложная или плановая
                'careProvidingFormId':
                2
                if safe_traverse(ticket_data, 'medical_care_emergency') else 3,
                'initGoalId':
                safe_traverse(ticket_data, 'visit_type') or '7',
                'stateId':
                '1',
            }
            diagnosis = safe_traverse(ticket_data, 'diagnosis')
            if diagnosis:
                main_item['body']['diagnoses'] = [{
                    'stageId':
                    3,
                    'main':
                    True,
                    'diagnosId':
                    dm.safe_diag_id(diagnosis),
                    'establishmentDate':
                    to_date(safe_traverse(ticket_data, 'date_open')),
                    'diseaseTypeId':
                    safe_traverse(ticket_data, 'disease_character'),
                }]

        checkup_node = pack_entity['addition'][checkup_code][0]
        checkup_data = checkup_node['data']
        visit_item = entities.set_child_entity(
            parent_item=main_item,
            dst_entity_code=TambovEntityCode.VISIT,
            dst_parents_params=header_meta['remote_parents_params'],
            dst_main_id_name='id',
            dst_parent_id_name='caseId',
            src_operation_code=src_operation_code,
            src_entity_code=src_entity_code,
            src_main_id_name=header_meta['local_main_param_name'],
            src_id=header_meta['local_main_id'],
        )
        if src_operation_code != OperationCode.DELETE:
            visit_item['body'] = {
                # 'id': None,  # проставляется в set_current_id_func
                'visitResultId':
                safe_traverse(ticket_data, 'treatment_result'),
                'deseaseResultId':
                safe_traverse(ticket_data, 'disease_outcome'),
                'admissionDate':
                to_date(safe_traverse(checkup_data[gen_info], 'date')),
                'goalId':
                safe_traverse(ticket_data, 'visit_type') or '7',
                'placeId':
                '1',
                'profileId':
                safe_traverse(ticket_data, 'medical_care_profile'),
            }
            if not self.reformer.find_remote_id_by_local(
                    TambovEntityCode.VISIT,
                    src_entity_code,
                    header_meta['local_main_id'],
            ):
                resource_group_id = self.get_resource_group_id(
                    ticket_data['hospital'], ticket_data['doctor'])
                visit_item['body']['resourceGroupId'] = resource_group_id
            diagnosis_osn = safe_traverse(checkup_data, 'medical_report',
                                          'diagnosis_osn', 'MKB')
            if diagnosis_osn:
                diags_osl = safe_traverse(checkup_data, 'medical_report',
                                          'diagnosis_osl')
                diags_sop = safe_traverse(checkup_data, 'medical_report',
                                          'diagnosis_sop')
                visit_diagnoses = visit_item['body'].setdefault(
                    'diagnoses', [])
                gen_info_date = to_date(
                    safe_traverse(checkup_data[gen_info], 'date'))
                disease_character = safe_traverse(ticket_data,
                                                  'disease_character')
                self.add_visit_diagnosis(visit_diagnoses, diagnosis_osn, '1',
                                         gen_info_date, disease_character, dm)
                for diagnosis_osl in diags_osl or ():
                    self.add_visit_diagnosis(
                        visit_diagnoses, safe_traverse(diagnosis_osl, 'MKB'),
                        '3', gen_info_date, disease_character, dm)
                for diagnosis_sop in diags_sop or ():
                    self.add_visit_diagnosis(
                        visit_diagnoses, safe_traverse(diagnosis_sop, 'MKB'),
                        '2', gen_info_date, disease_character, dm)

        srv_api_method = self.reformer.get_api_method(
            self.remote_sys_code,
            TambovEntityCode.SERVICE,
            OperationCode.READ_MANY,
        )
        for medical_serv_item in (safe_traverse(ticket_data,
                                                'medical_services') or ()):
            if not self.validate_service(medical_serv_item):
                continue
            prototype_code = safe_traverse(medical_serv_item,
                                           'medical_service') or ''
            prototype_id = SrvPrototypeMatch.get_prototype_id_by_prototype_code(
                prototype_code)

            def set_parent_id_func(parent_meta, entity_meta, entity_body):
                case_meta = parent_meta['parent_entity']['meta']
                entity_body['medicalCaseId'] = case_meta['dst_id']

            serv_item = entities.set_child_entity(
                parent_item=visit_item,
                dst_entity_code=TambovEntityCode.REND_SERVICE,
                dst_parents_params=header_meta['remote_parents_params'],
                dst_main_id_name='id',
                dst_parent_id_name='stepId',
                src_operation_code=src_operation_code,
                src_entity_code=src_entity_code,
                src_main_id_name=header_meta['local_main_param_name'],
                src_id='_'.join(
                    (str(header_meta['local_main_id']), prototype_id)),
                set_parent_id_func=set_parent_id_func,
            )
            org_code = safe_traverse(ticket_data, 'hospital') or ''
            req = DataRequest(self.reformer.stream_id)
            req.set_req_params(
                url=srv_api_method['template_url'],
                method=srv_api_method['method'],
                protocol=ProtocolCode.SOAP,
                data={
                    'clinic': org_code,
                    'prototype': prototype_id,
                },
            )
            srvs_data = self.transfer__send_request(req)
            if not srvs_data:
                raise ExternalError(
                    '%s not found for clinic="%s" prototype="%s"' %
                    (TambovEntityCode.SERVICE, org_code, prototype_id))
            srv_data = srvs_data[0]  # считаем, что будет одна
            if src_operation_code != OperationCode.DELETE:
                serv_item['body'] = {
                    # 'id': None,  # проставляется в set_current_id_func
                    'patientUid':
                    header_meta['remote_parents_params']['patientUid']['id'],
                    'serviceId':
                    srv_data['id'],
                    'dateFrom':
                    to_date(safe_traverse(ticket_data, 'date_open')),
                    'dateTo':
                    to_date(safe_traverse(ticket_data, 'date_open')),
                    'isRendered':
                    True,
                    'orgId':
                    safe_traverse(ticket_data, 'hospital') or '',
                    'quantity':
                    safe_traverse(medical_serv_item,
                                  'medical_service_quantity'),
                    'fundingSourceTypeId':
                    1,
                }
                diagnosis = safe_traverse(ticket_data, 'diagnosis')
                if diagnosis:
                    serv_item['body']['diagnosisId'] = dm.diag_id(diagnosis)
                if not self.reformer.find_remote_id_by_local(
                        TambovEntityCode.REND_SERVICE,
                        src_entity_code,
                        '_'.join(
                            (str(header_meta['local_main_id']), prototype_id)),
                ):
                    resource_group_id = self.get_resource_group_id(
                        ticket_data['hospital'],
                        safe_traverse(medical_serv_item,
                                      'medical_service_doctor'))
                    serv_item['body']['resourceGroupId'] = resource_group_id

        return entities
Example #14
0
    def build_local_entities(self, header_meta, pack_entity):
        src_entity_code = header_meta['remote_entity_code']
        src_operation_code = header_meta['remote_operation_code']
        referral_data = pack_entity['data']

        # сопоставление параметров родительских сущностей
        params_map = {
            TambovEntityCode.SMART_PATIENT: {
                'entity': RisarEntityCode.CARD,
                'param': 'card_id'
            },
        }
        self.reform_remote_parents_params(header_meta, src_entity_code,
                                          params_map)

        entities = RequestEntities(self.reformer.stream_id)
        childs = pack_entity['childs']
        rend_serv_item = childs[TambovEntityCode.REND_SERVICE][0]
        rend_serv_data = rend_serv_item['data']
        # Евгений Коняев, [12.01.17 20:02]
        # всё на что у нас нашлось сопоставление в файле уже есть. С остальными будем разбираться отдельно
        # 0001 из сопоставления убираем и ошибки в этйо части решены
        measure_code = SrvPrototypeMatch.get_measure_code(
            rend_serv_data['prototypeId'], error_ignore=True)
        if not measure_code:
            return entities

        if referral_data:
            measure_item = entities.set_main_entity(
                dst_entity_code=RisarEntityCode.MEASURE,
                dst_parents_params=header_meta['local_parents_params'],
                dst_main_id_name='measure_id',
                src_operation_code=src_operation_code,
                src_entity_code=src_entity_code,
                src_main_id_name=header_meta['remote_main_param_name'],
                src_id=header_meta['remote_main_id'],
                level_count=2,
            )
            if src_operation_code != OperationCode.DELETE:
                measure_item['body'] = {
                    # 'measure_id': None,  # заполняется в set_current_id_func
                    'measure_type_code': measure_code,
                    'begin_datetime': encode(referral_data['referralDate']),
                    'end_datetime': encode(referral_data['referralDate']),
                    'status': 'created',  # referral_data['refStatusId'],
                }
        else:
            measure_item = None

        measure_type = SrvPrototypeMatch.get_measure_type(
            rend_serv_data['prototypeId'])
        research_meas_types = ('lab_test', 'func_test')
        checkup_meas_types = ('checkup', 'healthcare', 'social_preventiv')
        if measure_type in checkup_meas_types:
            self.build_local_measure_specialists_checkup(
                header_meta, entities, rend_serv_data, measure_item,
                measure_code)
        else:
            assert measure_type in research_meas_types
            self.build_local_measure_research(header_meta, entities,
                                              rend_serv_item, rend_serv_data,
                                              measure_item, measure_code)
        return entities
Example #15
0
    def build_remote_entities(self, header_meta, pack_entity):
        """
        Вход в header_meta
        local_operation_code
        local_entity_code
        local_main_param_name
        local_main_id
        local_parents_params

        Выход в entity
        dst_entity_code
        dst_main_param_name
        """
        measure_data = pack_entity['data']
        appointment_node = pack_entity['addition'][
            RisarEntityCode.APPOINTMENT][0]
        appoint_data = appointment_node['data']
        src_operation_code = header_meta['local_operation_code']
        src_entity_code = header_meta['local_entity_code']

        entities = RequestEntities(self.reformer.stream_id)
        # todo: стоит напрямую найти measure_type, а в неГоспитализациях дозапрашивать
        # prototype_id, так как в госпитализации нет прототипа (в файле
        # фейковый проставлен)
        prototype_id = SrvPrototypeMatch.get_prototype_id_by_mes_code(
            measure_data.get('measure_type_code'), error_ignore=True)
        if not prototype_id:
            return entities
        measure_type = SrvPrototypeMatch.get_measure_type(prototype_id)
        if measure_type in ('healthcare', 'social_preventiv'):
            return entities

        # сопоставление параметров родительских сущностей
        params_map = {
            RisarEntityCode.CARD: {
                'entity': TambovEntityCode.SMART_PATIENT,
                'param': 'patientUid'
            }
        }
        self.reform_local_parents_params(header_meta, src_entity_code,
                                         params_map)

        main_item = entities.set_main_entity(
            dst_entity_code=TambovEntityCode.REFERRAL,
            dst_parents_params=header_meta['remote_parents_params'],
            dst_main_id_name='id',
            src_operation_code=src_operation_code,
            src_entity_code=src_entity_code,
            src_main_id_name=header_meta['local_main_param_name'],
            src_id=header_meta['local_main_id'],
            level_count=1,
        )

        org_code = appoint_data.get('referral_lpu') or appoint_data.get(
            'appointed_lpu')
        date = appoint_data.get('date') or appoint_data.get(
            'referral_date') or measure_data.get('begin_datetime')
        srv_api_method = self.reformer.get_api_method(
            self.remote_sys_code,
            TambovEntityCode.SERVICE,
            OperationCode.READ_MANY,
        )

        srv_data = None
        typeId = self.measure_type__type_id__map[measure_type]
        if measure_type != 'hospitalization':
            req = DataRequest(self.reformer.stream_id)
            req.set_req_params(
                url=srv_api_method['template_url'],
                method=srv_api_method['method'],
                protocol=ProtocolCode.SOAP,
                data={
                    'clinic': org_code,
                    'prototype': prototype_id,
                },
            )
            srvs_data = self.transfer__send_request(req)
            if not srvs_data:
                raise ExternalError(
                    '%s not found for clinic="%s" prototype="%s"' %
                    (TambovEntityCode.SERVICE, org_code, prototype_id))
            srv_data = srvs_data[0]  # считаем, что будет одна
        if src_operation_code != OperationCode.DELETE:
            main_item['body'] = {
                # 'id': None,  # проставляется в set_current_id_func
                'patientUid':
                header_meta['remote_parents_params']['patientUid']['id'],
                'referralDate':
                to_date(date),
                'referralOrganizationId':
                appoint_data.get('appointed_lpu'),
                'refServiceId':
                srv_data and [srv_data['id']],  # баг какой-то. ждет список
                'typeId':
                typeId,
                'receivingOrganizationId':
                org_code,
                'referralSpecialistId':
                appoint_data.get('appointed_doctor'),
            }
            dm = DiagsMatch()
            diagnosis_code = appoint_data.get('diagnosis')
            if diagnosis_code:
                main_item['body']['diagnosisId'] = dm.diag_id(diagnosis_code)

        return entities
Example #16
0
    def build_local_entities(self, header_meta, pack_entity):
        sched_data = pack_entity['data']
        src_entity_code = header_meta['remote_entity_code']
        src_operation_code = self.get_operation_code_by_method(header_meta['remote_method'])

        # сопоставление параметров родительских сущностей
        params_map = {
            TulaEntityCode.ORGANIZATION: {
                'entity': RisarEntityCode.ORGANIZATION, 'param': 'organisation'
            },
            TulaEntityCode.DOCTOR: {
                'entity': RisarEntityCode.DOCTOR, 'param': 'doctor'
            },
        }
        self.reform_remote_parents_params(header_meta, src_entity_code, params_map)
        find_prefix = './/{http://sdsys.ru/}'

        entities = RequestEntities(self.reformer.stream_id)
        main_item = entities.set_main_entity(
            dst_entity_code=RisarEntityCode.SCHEDULE,
            dst_parents_params=header_meta['local_parents_params'],
            dst_main_id_name='schedule_id',
            src_operation_code=src_operation_code,
            src_entity_code=src_entity_code,
            src_main_id_name=header_meta['remote_main_param_name'],
            src_id=header_meta['remote_main_id'],
            level_count=1,
        )
        if src_operation_code != OperationCode.DELETE:
            doct_sch_data = sched_data.find(find_prefix + 'DOCTSCHED')
            SCHEDINT = sched_data.find(find_prefix + 'SCHEDINT')
            main_item['body'] = {
                'date': self.date_misf_mrf(doct_sch_data, find_prefix + 'WDATE'),
                'time_begin': self.time_misf_mrf(doct_sch_data, find_prefix + 'BEGHOUR', find_prefix + 'BEGMIN'),
                'time_end': self.time_misf_mrf(doct_sch_data, find_prefix + 'ENDHOUR', find_prefix + 'ENDMIN'),
                'doctor': header_meta['local_parents_params']['doctor']['id'],
                'hospital': header_meta['local_parents_params']['organisation']['id'],
            }
            build_schedule_tickets = []
            for INTERVAL in SCHEDINT.findall(find_prefix + 'INTERVAL'):
                client_id = None
                pcode = INTERVAL.findtext(find_prefix + 'PCODE')
                if pcode:
                    client_id = self.reformer.find_local_id_by_remote(
                        RisarEntityCode.CLIENT,
                        TulaEntityCode.CLIENT,
                        pcode,
                    )
                    # если пациент еще не передавался в МР, но занял слот
                    if not client_id:
                        logger.debug('stream_id: %s INTERVAL PCODE: (%s)' %
                                     (self.reformer.stream_id, pcode))

                build_schedule_tickets.append({
                    'time_begin': self.time_misf_mrf(INTERVAL, find_prefix + 'BHOUR', find_prefix + 'BMIN'),
                    'time_end': self.time_misf_mrf(INTERVAL, find_prefix + 'FHOUR', find_prefix + 'FMIN'),
                    'patient': client_id or Undefined,
                })
            main_item['body']['schedule_tickets'] = build_schedule_tickets

        return entities
Example #17
0
    def build_remote_entities(self, header_meta, pack_entity):
        """
        Вход в header_meta
        local_operation_code
        local_entity_code
        local_main_param_name
        local_main_id
        local_parents_params

        Выход в entity
        dst_entity_code
        dst_main_param_name
        """
        measure_data = pack_entity['data']
        appointment_node = pack_entity['addition'][
            RisarEntityCode.APPOINTMENT][0]
        appoint_data = appointment_node['data']
        src_operation_code = header_meta['local_operation_code']
        src_entity_code = header_meta['local_entity_code']

        # сопоставление параметров родительских сущностей
        params_map = {
            RisarEntityCode.CARD: {
                'entity': TulaEntityCode.CARD,
                'param': 'card_id'
            }
        }
        self.reform_local_parents_params(header_meta, src_entity_code,
                                         params_map)

        entities = RequestEntities(self.reformer.stream_id)
        main_item = entities.set_main_entity(
            dst_entity_code=TulaEntityCode.MEASURE,
            dst_parents_params=header_meta['remote_parents_params'],
            dst_main_id_name='measure_id',
            src_operation_code=src_operation_code,
            src_entity_code=src_entity_code,
            src_main_id_name=header_meta['local_main_param_name'],
            src_id=header_meta['local_main_id'],
            level_count=1,
        )
        if src_operation_code != OperationCode.DELETE:
            main_item['body'] = {
                "measure_id": measure_data.get('measure_id'),
                "measure_type_code": measure_data.get('measure_type_code'),
                "begin_date": measure_data.get('begin_datetime'),
                "end_date": measure_data.get('end_datetime'),
                "status": measure_data.get('status'),
                # ---
                "appointment": {
                    "appointment_id":
                    measure_data.get('appointment_id'),
                    "appointment_code":
                    appoint_data.get('appointment_code'),
                    "appointed_date":
                    appoint_data.get('date'),
                    "appointed_lpu":
                    appoint_data.get('appointed_lpu'),
                    "appointed_doctor":
                    appoint_data.get('appointed_doctor'),
                    "referral_lpu":
                    appoint_data.get('referral_lpu'),
                    "referral_date":
                    appoint_data.get('referral_date'),
                    "execution_time":
                    appoint_data.get('execution_time'),
                    "diagnosis":
                    appoint_data.get('diagnosis'),
                    "indications":
                    measure_data.get('indications'),
                    "parameters":
                    appoint_data.get('parameters'),
                    "comment":
                    appoint_data.get('comment'),
                    "hospitalization_form":
                    appoint_data.get('hospitalization_form'),
                    "operation":
                    appoint_data.get('operation'),
                    "profile":
                    appoint_data.get('profile'),
                    # "bed_profile": appoint_data.get(''),
                },
                "result_action_id": measure_data.get('result_action_id'),
            }

        return entities
Example #18
0
    def build_local_entities(self, header_meta, data):
        src_operation_code = self.get_operation_code_by_method(
            header_meta['remote_method'])
        entities = RequestEntities(self.reformer.stream_id)

        if src_operation_code != OperationCode.DELETE:

            def after_send_func(entity_meta, entity_body, answer_body):
                # пишем сопоставления по всем тикетам с записью,
                # чтобы по ним можно было работать в потоке schedule_ticket
                matching_parent = self.reformer.get_by_local_id(
                    remote_entity_code=TulaEntityCode.SCHEDULE,
                    local_entity_code=RisarEntityCode.SCHEDULE,
                    local_id=entity_meta['dst_id'],
                )
                answ_tickets = {}
                extra_answ_tickets = {}
                for answ_st in answer_body.get('schedule_tickets') or ():
                    if answ_st.get('schedule_ticket_id') and answ_st.get(
                            'patient'):
                        if answ_st.get('schedule_ticket_type') == '1':
                            extra_answ_tickets.setdefault(
                                answ_st['patient'],
                                []).append(answ_st['schedule_ticket_id'])
                        else:
                            answ_tickets[(answ_st['time_begin'],
                                          answ_st['time_end']
                                          )] = answ_st['schedule_ticket_id']
                for req_st in data.get('schedule_tickets') or ():
                    if req_st.get('schedule_ticket_id') and req_st.get(
                            'patient'):
                        if req_st.get('schedule_ticket_type') == '1':
                            local_patient_id = self.reformer.find_local_id_by_remote(
                                RisarEntityCode.CLIENT,
                                TulaEntityCode.CLIENT,
                                req_st['patient'],
                            )
                            answ_st_id = extra_answ_tickets[
                                local_patient_id].pop()
                        else:
                            answ_st_id = answ_tickets[(req_st['time_begin'],
                                                       req_st['time_end'])]
                        upd_res = self.reformer.update_local_match_parent(
                            TulaEntityCode.SCHEDULE_TICKET,
                            RisarEntityCode.SCHEDULE_TICKET,
                            answ_st_id,
                            matching_parent.id,
                        )
                        if not upd_res:
                            if req_st.get('schedule_ticket_type') == '1':
                                remote_id_prefix = 'outplan'
                                # req_st_id = req_st['schedule_ticket_id'][8:]  # если железно будет префикс
                                req_st_id = req_st[
                                    'schedule_ticket_id'].lstrip('outplan_')
                            else:
                                remote_id_prefix = 'plan'
                                req_st_id = req_st['schedule_ticket_id']
                            self.reformer.register_entity_match(
                                RisarEntityCode.SCHEDULE_TICKET,
                                answ_st_id,
                                TulaEntityCode.SCHEDULE_TICKET,
                                req_st_id,
                                local_param_name='schedule_ticket_id',
                                remote_param_name='schedule_ticket_id',
                                remote_id_prefix=remote_id_prefix,
                                matching_parent_id=matching_parent.id,
                            )

            main_item = entities.set_main_entity(
                dst_entity_code=RisarEntityCode.SCHEDULE,
                dst_parents_params=header_meta['local_parents_params'],
                dst_main_id_name='schedule_id',
                src_operation_code=src_operation_code,
                src_entity_code=header_meta['remote_entity_code'],
                src_main_id_name=header_meta['remote_main_param_name'],
                after_send_func=after_send_func,
                src_id_prefix=data['time_begin'],
                src_id=header_meta['remote_main_id'],
                level_count=1,
            )
            main_item['body'] = deepcopy(data)
            main_item['body'][
                'schedule_id'] = ''  # заполняется в set_current_id_common_func
            # внешний код хранится в рисар в исходном виде
            # if 'hospital' in data:
            #     hospital_code = self.reformer.get_local_id_by_remote(
            #         RisarEntityCode.ORGANIZATION,
            #         TulaEntityCode.ORGANIZATION,
            #         data['hospital'],
            #     )
            #     main_item['body']['hospital'] = hospital_code
            # if 'doctor' in data:
            #     doctor_code = self.reformer.get_local_id_by_remote(
            #         RisarEntityCode.DOCTOR,
            #         TulaEntityCode.DOCTOR,
            #         data['doctor'],
            #     )
            #     main_item['body']['doctor'] = doctor_code
            for schedule_ticket in main_item['body'].get(
                    'schedule_tickets') or ():
                # if 'schedule_ticket_id' in schedule_ticket:
                #     local_schedule_ticket_id = self.reformer.find_local_id_by_remote(
                #         RisarEntityCode.SCHEDULE_TICKET,
                #         TulaEntityCode.SCHEDULE_TICKET,
                #         schedule_ticket['schedule_ticket_id'],
                #     )
                # PUT отключен, поэтому всегда ''
                schedule_ticket['schedule_ticket_id'] = ''
                if 'patient' in schedule_ticket:
                    patient_code = self.reformer.find_local_id_by_remote(
                        RisarEntityCode.CLIENT,
                        TulaEntityCode.CLIENT,
                        schedule_ticket['patient'],
                    )
                    # 1 - ИД псевдо пациента "Занято". Бывает нужен,
                    # если занято мужчиной, либо пациент еще не приходил
                    schedule_ticket['patient'] = patient_code or '1'
        else:  # delete
            all_matches = self.reformer.find_all_matches_by_remote(
                RisarEntityCode.SCHEDULE,
                TulaEntityCode.SCHEDULE,
                header_meta['remote_main_id'],
            )
            for match in all_matches:
                entities.set_main_entity(
                    dst_entity_code=RisarEntityCode.SCHEDULE,
                    dst_parents_params=header_meta['local_parents_params'],
                    dst_main_id_name='schedule_id',
                    src_operation_code=src_operation_code,
                    src_entity_code=header_meta['remote_entity_code'],
                    src_main_id_name=header_meta['remote_main_param_name'],
                    src_id_prefix=match.remote_id_prefix,
                    src_id=match.remote_id,
                    level_count=1,
                )

        return entities
Example #19
0
    def build_local_entities(self, header_meta, data):
        src_operation_code = self.get_operation_code_by_method(
            header_meta['remote_method'])
        entities = RequestEntities(self.reformer.stream_id)

        if src_operation_code == OperationCode.DELETE:
            # тела нет, поэтому определяем по ID
            if 'outplan_' in header_meta['remote_main_id']:
                remote_main_id = header_meta['remote_main_id'][8:]
                remote_id_prefix = 'outplan'
            else:
                remote_id_prefix = 'plan'
                remote_main_id = header_meta['remote_main_id']
        else:
            if data['schedule_ticket_type'] == '1':
                remote_id_prefix = 'outplan'
                # remote_main_id = header_meta['remote_main_id'][8:]  # если железно будет префикс
                remote_main_id = header_meta['remote_main_id'].lstrip(
                    'outplan_')
            else:
                remote_id_prefix = 'plan'
                remote_main_id = header_meta['remote_main_id']

        def after_send_func(entity_meta, entity_body, answer_body):
            if src_operation_code != OperationCode.DELETE:
                self.reformer.update_local_match_parent(
                    RisarEntityCode.SCHEDULE_TICKET,
                    TulaEntityCode.SCHEDULE_TICKET,
                    answer_body['schedule_ticket_id'],
                    matching_parent_id,
                )

        main_item = entities.set_main_entity(
            dst_entity_code=RisarEntityCode.SCHEDULE_TICKET,
            dst_parents_params=header_meta['local_parents_params'],
            dst_main_id_name='schedule_ticket_id',
            src_operation_code=src_operation_code,
            src_entity_code=header_meta['remote_entity_code'],
            src_main_id_name=header_meta['remote_main_param_name'],
            after_send_func=after_send_func,
            src_id_prefix=remote_id_prefix,
            src_id=remote_main_id,
            level_count=1,
        )
        if src_operation_code != OperationCode.DELETE:
            # если при инициализации тикет придет раньше своего графика, то упадем здесь
            matching_parent = self.reformer.get_by_remote_id(
                RisarEntityCode.SCHEDULE,
                TulaEntityCode.SCHEDULE,
                data['schedule_id'],
                data['schedule_time_begin'],
            )
            matching_parent_id = matching_parent.id

            main_item['body'] = deepcopy(data)
            main_item['body']['schedule_id'] = matching_parent.local_id
            main_item['body']['schedule_time_begin'] = Undefined
            main_item['body'][
                'schedule_ticket_id'] = ''  # заполняется в set_current_id_common_func
            # внешний код хранится в рисар в исходном виде
            # if 'hospital' in data:
            #     hospital_code = self.reformer.get_local_id_by_remote(
            #         RisarEntityCode.ORGANIZATION,
            #         TulaEntityCode.ORGANIZATION,
            #         data['hospital'],
            #     )
            #     main_item['body']['hospital'] = hospital_code
            # if 'doctor' in data:
            #     doctor_code = self.reformer.get_local_id_by_remote(
            #         RisarEntityCode.DOCTOR,
            #         TulaEntityCode.DOCTOR,
            #         data['doctor'],
            #     )
            #     main_item['body']['doctor'] = doctor_code
            if 'patient' in data:
                patient_code = self.reformer.find_local_id_by_remote(
                    RisarEntityCode.CLIENT,
                    TulaEntityCode.CLIENT,
                    data['patient'],
                )
                # 1 - ИД псевдо пациента "Занято". Бывает нужен,
                # если занято мужчиной, либо пациент еще не приходил
                main_item['body']['patient'] = patient_code or '1'

        return entities
Example #20
0
    def build_local_entities(self, header_meta, pack_entity):
        time_data = pack_entity['data']
        src_entity_code = header_meta['remote_entity_code']
        src_operation_code = header_meta['remote_operation_code']

        # сопоставление параметров родительских сущностей
        params_map = {
            TambovEntityCode.CLINIC: {
                'entity': RisarEntityCode.ORGANIZATION,
                'param': 'lpu_code'
            },
        }
        self.reform_remote_parents_params(header_meta, src_entity_code,
                                          params_map)

        entities = RequestEntities(self.reformer.stream_id)
        doctor_code = self.reformer.find_local_id_by_remote(
            RisarEntityCode.DOCTOR,
            TambovEntityCode.EMPLOYEE_POSITION,
            time_data['employee_pos'],
        )
        if not doctor_code:
            return entities

        time_item = entities.set_main_entity(
            dst_entity_code=RisarEntityCode.SCHEDULE,
            dst_parents_params=header_meta['local_parents_params'],
            dst_main_id_name='schedule_id',
            src_operation_code=src_operation_code,
            src_entity_code=src_entity_code,
            src_main_id_name=header_meta['remote_main_param_name'],
            src_id=header_meta['remote_main_id'],
            level_count=1,
        )
        if src_operation_code != OperationCode.DELETE:
            time_item['body'] = {
                # 'schedule_id': None,  # заполняется в set_current_id_func
                'hospital':
                header_meta['local_parents_params']['lpu_code']['id'],
                'doctor':
                doctor_code,
                'date':
                time_data['date'],
                'time_begin':
                time_data['work_interval']['work_beg'].isoformat()[:5],
                'time_end':
                time_data['work_interval']['work_end'].isoformat()[:5],
            }
            for slot_data in time_data['slots']:
                patient = None
                if slot_data['patient']:
                    patient_code = self.reformer.find_local_id_by_remote(
                        RisarEntityCode.CLIENT,
                        TambovEntityCode.SMART_PATIENT,
                        slot_data['patient'],
                    )
                    if not patient_code:
                        if self.request_patient(slot_data['patient']):
                            patient_code = self.reformer.find_local_id_by_remote(
                                RisarEntityCode.CLIENT,
                                TambovEntityCode.SMART_PATIENT,
                                slot_data['patient'],
                            )
                    # 2 - ИД псевдо пациента "Занято". Бывает нужен,
                    # если занято мужчиной, либо пациент еще не приходил
                    patient = patient_code or '2'

                time_item['body'].setdefault('schedule_tickets', []).append({
                    'time_begin':
                    slot_data['slot_beg'].isoformat()[:5],
                    'time_end':
                    slot_data['slot_end'].isoformat()[:5],
                    'patient':
                    patient or Undefined,
                    'schedule_ticket_type':
                    '0',
                })

        return entities
Example #21
0
    def build_local_entities(self, header_meta, pack_entity):
        birth_data = pack_entity['data']
        src_entity_code = header_meta['remote_entity_code']
        src_operation_code = header_meta['remote_operation_code']

        # сопоставление параметров родительских сущностей
        params_map = {
            TambovEntityCode.SMART_PATIENT: {
                'entity': RisarEntityCode.CARD,
                'param': 'card_id'
            },
        }
        self.reform_remote_parents_params(header_meta, src_entity_code,
                                          params_map)

        entities = RequestEntities(self.reformer.stream_id)
        if not safe_traverse_attrs(birth_data, 'Part1', 'InDate'):
            # пустой ответ
            return entities
        main_item = entities.set_main_entity(
            dst_entity_code=RisarEntityCode.CHILDBIRTH,
            dst_parents_params=header_meta['local_parents_params'],
            dst_main_id_name='card_id',
            src_operation_code=src_operation_code,
            src_entity_code=src_entity_code,
            src_main_id_name=header_meta['remote_main_param_name'],
            src_id=header_meta['remote_main_id'],
            level_count=1,
        )
        if src_operation_code != OperationCode.DELETE:
            dm = DiagsMatch()
            part1 = birth_data['Part1']
            part2 = birth_data['Part2']
            part3 = birth_data['Part3']
            part4 = birth_data['Part4']
            part5 = birth_data['Part5']
            part6 = birth_data['Part6']
            # days = safe_int(stk(part1, 'PregnantTimeSpan', 'Days'))
            main_item['body'] = {
                # "required": ["admission_date", "pregnancy_duration",
                #              "delivery_date", "delivery_time",
                #              "maternity_hospital", "diagnosis_osn",
                #              "pregnancy_final"]
                'general_info': {
                    'admission_date':
                    encode(part1['InDate']),
                    'maternity_hospital':
                    str(stk(part1, 'ClinicId')),
                    'delivery_date':
                    encode(stk(part1, 'ChildBirth', 'Date')),
                    'delivery_time':
                    encode(stk(part1, 'ChildBirth', 'Time'))[:5] or '00:00',

                    # todo: test
                    # 'pregnancy_final': stk(part1, 'ChildBirth', 'ChildBirthOutcome'),  # rbRisarPregnancy_Final
                    'pregnancy_final':
                    'rodami',  # rbRisarPregnancy_Final
                    'pregnancy_duration':
                    stk(part1, 'ChildBirth', 'PregnantWeeks'),
                    # 'pregnancy_duration': days and int(days / 7) or 0,
                    # --
                    'diagnosis_osn':
                    dm.diag_code(
                        stk(part1, 'ChildBirth', 'Diagnoses', 'MainDiagnoses'))
                    or Undefined,
                    # --
                    # 'diagnosis_sop': part1['Extra'] or Undefined,
                    # 'diagnosis_osl': part1['Complication'] or Undefined,
                    'maternity_hospital_doctor':
                    (lambda x: x and str(x) or Undefined)(
                        self.get_employee_positions(
                            stk(part1, 'ChildBirth', 'EmployeeId'))),
                    'curation_hospital':
                    stk(part1, 'CuratioLpu') or Undefined,
                    'pregnancy_speciality':
                    stk(part1, 'BirthSpeciality') or Undefined,
                    'postnatal_speciality':
                    stk(part1, 'AfterBirthSpeciality') or Undefined,
                    'help':
                    stk(part1, 'HelpProvided') or Undefined,
                    # 'abortion': stk(part1, 'Abort') or Undefined,  # rbRisarAbort
                    # 'death': ???,
                },
                'complications': {
                    # 'delivery_waters': part3['BirthWaterBreak'] or Undefined,  # rbRisarDelivery_Waters
                    'pre_birth_delivery_waters':
                    safe_bool_none(part3['PrenatalWaterBreak']) or Undefined,
                    'weakness':
                    stk(part3, 'BirthPowerWeakness')
                    or Undefined,  # rbRisarWeakness
                    'meconium_color':
                    safe_bool_none(stk(part3, 'AmiaticWater')) or Undefined,
                    'pathological_preliminary_period':
                    safe_bool_none(stk(part3, 'PatologicPreliminaryPeriod'))
                    or Undefined,
                    'abnormalities_of_labor':
                    safe_bool_none(stk(part3, 'BirthActivityAnomaly'))
                    or Undefined,
                    'chorioamnionitis':
                    safe_bool_none(stk(part3, 'Horiamnionit')) or Undefined,
                    # 'perineal_tear': part3['PerinealRupture'] or Undefined,  # rbPerinealTear
                    # 'eclampsia': part3['Nefropaty'] or Undefined,  # rbRisarEclampsia
                    'anemia':
                    safe_bool_none(stk(part3, 'Anemia')) or Undefined,
                    'infections_during_delivery':
                    stk(part3, 'InfectionDuringBirth') or Undefined,
                    'infections_after_delivery':
                    stk(part3, 'InfectionAfterBirth') or Undefined,
                    # 'funiculus': stk(part3, 'CordPatology', 'Term') or Undefined,  # rbRisarFuniculus
                    # 'afterbirth': stk(part3, 'PlacentaPatology', 'Term') or Undefined,  # rbRisarAfterbirth
                },
                'manipulations': {
                    'caul':
                    safe_bool_none(stk(part4, 'Amniotomy')) or Undefined,
                    'calfbed':
                    safe_bool_none(stk(part4, 'ManualWombSurvey'))
                    or Undefined,
                    'perineotomy':
                    stk(part4, 'Perineotomy') or Undefined,
                    'secundines':
                    safe_bool_none(stk(part4, 'ManualRemovalAfterBirth'))
                    or Undefined,
                    'other_manipulations':
                    stk(part4, 'AnotherManipulations') or Undefined,
                },
                'operations': {
                    # 'caesarean_section': part5['CesarianDelivery'] or Undefined,  #rbRisarCaesarean_Section
                    # 'obstetrical_forceps': part5['Forceps'] or Undefined,  # rbRisarObstetrical_Forceps
                    # 'vacuum_extraction': safe_bool_none(part5['Vacuum']),  # boolean
                    # 'indication': part5['Indicator'] or Undefined,  # rbRisarIndication
                    'specialities':
                    stk(part5, 'Speciality') or Undefined,
                    # 'anesthetization': part5['Anestesia'] or Undefined,  # rbRisarAnesthetization
                    # 'hysterectomy': part5['Hysterectomy'] or Undefined,  # rbRisarHysterectomy
                    # 'complications': part5['Complication'] or Undefined,  # MKB
                    'embryotomy':
                    safe_bool_none(stk(part5, 'Embryotomy')) or Undefined,
                },
                'kids': []
            }

            mother_death_required = [
                "reason_of_death", "death_date", "death_time"
            ]
            mother_death = {
                'death_date':
                encode(stk(part2, 'MotherDeathData', 'DeathDate')),
                'death_time':
                (encode(stk(part2, 'MotherDeathData', 'DeathTime')) or '')[:5],
                'reason_of_death':
                stk(part2, 'MotherDeathData', 'MotherDeathReason'),
                # --
                # 'pat_diagnosis_osn': stk(part2, 'MotherDeathData', 'PatologicalDiagnos'),
                # 'pat_diagnosis_sop': stk(part2, 'MotherDeathData', 'AcompanyDiagnos'),
                # 'pat_diagnosis_osl': stk(part2, 'MotherDeathData', 'ComplicationDiagnos'),
                'control_expert_conclusion':
                stk(part2, 'LkkResult') or Undefined,
            }
            if all(mother_death[x] for x in mother_death_required):
                main_item['body']['mother_death'] = mother_death

            kids = []
            childs = part6['Child']
            for child in childs:
                # "required": ["alive", "sex", "weight", "length", "date"]
                kids.append({
                    'alive':
                    safe_bool(stk(child, 'Alive')),
                    'sex':
                    safe_int(stk(child, 'Gender')) - 1,
                    'weight':
                    safe_double(stk(child, 'Weight')),
                    'length':
                    safe_double(stk(child, 'Height')),
                    'date':
                    encode(stk(child, 'BirthDate')),
                    # --
                    'time':
                    '00:00' if safe_bool(stk(child, 'Alive')) else Undefined,
                    # 'maturity_rate': stk(child, 'FullTerm') or Undefined,  # rbRisarMaturity_Rate
                    'apgar_score_1':
                    safe_int(stk(child, 'Apgar_1min')) or Undefined,
                    'apgar_score_5':
                    safe_int(stk(child, 'Apgar_5min')) or Undefined,
                    'apgar_score_10':
                    safe_int(stk(child, 'Apgar_10min')) or Undefined,
                    'death_date':
                    encode(stk(child, 'DeathDate')) or Undefined,
                    'death_time': (encode(stk(child, 'DeathTime')) or '')[:5]
                    or Undefined,
                    'death_reason':
                    stk(child, 'DeathReason') or Undefined,
                    # 'diseases': child['NewbornSeakness'] or Undefined,
                })
            main_item['body']['kids'] = kids

        return entities
Example #22
0
    def build_remote_entities_exch_card(self, header_meta, pack_entity):
        exch_card_data = pack_entity['data']
        src_operation_code = header_meta['local_operation_code']
        src_entity_code = header_meta['local_entity_code']

        # сопоставление параметров родительских сущностей
        params_map = {
            RisarEntityCode.CARD: {
                'entity': TambovEntityCode.SMART_PATIENT,
                'param': 'patientUid',
            },
            RisarEntityCode.ORGANIZATION: {
                'entity': TambovEntityCode.CLINIC,
                'param': 'orgId',
            },
        }
        self.reform_local_parents_params(header_meta, src_entity_code,
                                         params_map)

        entities = RequestEntities(self.reformer.stream_id)
        main_item = entities.set_main_entity(
            dst_entity_code=TambovEntityCode.REND_SERVICE,
            dst_parents_params=header_meta['remote_parents_params'],
            dst_main_id_name='id',
            src_operation_code=src_operation_code,
            src_entity_code=src_entity_code,
            src_main_id_name=header_meta['local_main_param_name'],
            src_id=header_meta['local_main_id'],
            level_count=2,
        )
        if src_operation_code != OperationCode.DELETE:
            clinic_id = header_meta['remote_parents_params']['orgId']['id']
            srv_api_method = self.reformer.get_api_method(
                self.remote_sys_code,
                TambovEntityCode.SERVICE,
                OperationCode.READ_MANY,
            )
            req = DataRequest(self.reformer.stream_id)
            req.set_req_params(
                url=srv_api_method['template_url'],
                method=srv_api_method['method'],
                protocol=ProtocolCode.SOAP,
                data={
                    'clinic': clinic_id,
                    'prototype': '11245',
                    'code': '99999',
                },
            )
            srvs_data = self.transfer__send_request(req)
            if not srvs_data:
                raise ExternalError(
                    '%s not found for clinic="%s" prototype="%s" code="%s"' %
                    (TambovEntityCode.SERVICE, clinic_id, '11245', '99999'))
            srv_data = srvs_data[0]  # считаем, что будет одна
            today = datetime.today()

            main_item['body'] = {
                # 'id': None,  # проставляется в set_current_id_func
                'patientUid':
                header_meta['remote_parents_params']['patientUid']['id'],
                'serviceId':
                srv_data['id'],
                'isRendered':
                True,
                'orgId':
                clinic_id,
                'dateFrom':
                today,
                'dateTo':
                today,
            }

        child_item = entities.set_child_entity(
            parent_item=main_item,
            dst_entity_code=TambovEntityCode.SRV_PROTOCOL,
            dst_parents_params=header_meta['remote_parents_params'],
            dst_main_id_name='id',
            dst_parent_id_name='id',
            dst_request_mode=RequestModeCode.MULTIPART_FILE,
            src_operation_code=src_operation_code,
            src_entity_code=src_entity_code,
            src_main_id_name=header_meta['local_main_param_name'],
            src_id=header_meta['local_main_id'],
        )
        if src_operation_code != OperationCode.DELETE:
            child_item['body'] = {
                'exch_card_1.xml':
                exch_card_data['exch_card'].replace('\n', '')
            }

        return entities