Beispiel #1
0
 def validate_service(service_data):
     values = (
         safe_traverse(service_data, 'medical_service'),
         safe_traverse(service_data, 'medical_service_quantity'),
         safe_traverse(service_data, 'medical_service_doctor'),
     )
     return all(values)
Beispiel #2
0
 def validate_checkup(checkup_data, checkup_code):
     if checkup_code == RisarEntityCode.CHECKUP_OBS_FIRST:
         gen_info = 'general_info'
     else:
         gen_info = 'dynamic_monitoring'
     values = (
         safe_traverse(checkup_data, 'medical_report', 'diagnosis_osn',
                       'MKB'),
         to_date(safe_traverse(checkup_data[gen_info], 'date')),
     )
     return all(values)
Beispiel #3
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
Beispiel #4
0
 def validate_ticket(self, ticket_data):
     values = (
         safe_traverse(ticket_data, 'diagnosis'),
         to_date(safe_traverse(ticket_data, 'date_open')),
         safe_traverse(ticket_data, 'visit_type'),
         safe_traverse(ticket_data, 'disease_character'),
         safe_traverse(ticket_data, 'disease_outcome'),
         safe_traverse(ticket_data, 'treatment_result'),
         safe_traverse(ticket_data, 'medical_care'),
         # safe_traverse(ticket_data, 'medical_care_emergency'),
         safe_traverse(ticket_data, 'medical_care_profile'),
         any(
             map(self.validate_service,
                 (safe_traverse(ticket_data, 'medical_services') or ()))),
     )
     return all(values)
Beispiel #5
0
def update_nsi_dicts():
    parser = argparse.ArgumentParser()
    parser.add_argument('--all',
                        action='store_const',
                        const=True,
                        default=False)
    parser.add_argument('--list',
                        action='store_const',
                        const=True,
                        default=False)
    parser.add_argument('--host', default=None)
    parser.add_argument('--port', default=None)
    parser.add_argument('--url', default=url)
    parser.add_argument('--key', default=key)
    parser.add_argument('--db', default=nvesta_db)

    args = parser.parse_args(sys.argv[1:])

    mongo = pymongo.MongoClient(
        host=args.host,
        port=args.port,
    )

    RefBookRegistry.bootstrap(mongo[args.db])
    client = NsiClient(url=args.url, user_key=args.key)

    print('Retrieving data from NSI')
    listed = list_nsi_dictionaries(client)

    cooked = [(their['code'], their['name'],
               safe_traverse(our, 'version',
                             default='?'), their.get('version', 0), their)
              for our, their in ((safe_dict(desc['our']),
                                  safe_dict(desc['their']))
                                 for desc in listed)]

    if args.list:
        for code, name, our, their, nsi_dict in cooked:
            print('%s %s %s->%s' % (code, name, our, their))
    elif args.all:
        to_update = [(code, name, our, their, nsi_dict)
                     for code, name, our, their, nsi_dict in cooked
                     if their != our]
        for code, name, our, their, nsi_dict in to_update:
            print('%s %s %s->%s' % (code, name, our, their))
            print 'Updating (%s) %s...' % (code, name)
            nsi_dict['version'] = their
            import_nsi_dict(nsi_dict, client)
        if not to_update:
            print('Nothing to update')
Beispiel #6
0
def migrate_from_v1():
    def blocks(iterable, max_size=2000):
        result = []
        i = 0
        for item in iterable:
            result.append(item)
            i += 1
            if i >= max_size:
                yield result
                result = []
                i = 0
        if result:
            yield result

    def get_field_codes(collection):
        codes = set()
        for row in collection.find():
            codes |= set(row.keys())
        codes.discard('_id')
        return codes

    parser = argparse.ArgumentParser()
    parser.add_argument('--all',
                        action='store_const',
                        const=True,
                        default=False)
    parser.add_argument('--host', default=None)
    parser.add_argument('--port', default=None)
    parser.add_argument('--from-db', default='vesta')
    parser.add_argument('--db', default=nvesta_db)

    args = parser.parse_args(sys.argv[1:])

    mongo = pymongo.MongoClient(
        host=args.host,
        port=args.port,
    )

    RefBookRegistry.bootstrap(mongo[args.db])

    db_vesta = mongo[args.from_db]
    RefBookRegistry.bootstrap(mongo[args.db])

    processed_dicts = {'dict_names'}
    processed_dicts.update(set(RefBookRegistry.names()))

    for v_description in db_vesta['dict_names'].find():
        code = v_description.get('code')
        if code in processed_dicts:
            continue
        v_collection = db_vesta[code]
        count = v_collection.count()

        print 'Transferring', str(count).rjust(6), code

        primary_link = None
        linked = v_description.get('linked')
        if linked:
            primary_link = {
                'left_field': linked['origin_field'],
                'right_field': linked['linked_field'],
                'right_rb': linked['collection']['code'],
            }

        rb = RefBookRegistry.create({
            'code':
            code,
            'name':
            v_description.get('name') or code,
            'description':
            v_description.get('description'),
            'oid':
            v_description.get('oid'),
            'fields': [{
                'key': fc,
                'mandatory': fc == 'code',
            } for fc in sorted(get_field_codes(v_collection))],
            'primary_link':
            primary_link,
            'version':
            safe_traverse(v_description, 'version', 'version', default=None)
        })

        for block in blocks(v_collection.find()):
            rb.save_bulk(rb.record_factory(raw) for raw in block)

        processed_dicts.add(code)

    for code in db_vesta.collection_names(False):
        if code in processed_dicts:
            continue

        v_collection = db_vesta[code]
        count = v_collection.count()

        print 'Transferring', str(count).rjust(6), code

        rb = RefBookRegistry.create({
            'code':
            code,
            'name':
            code,
            'description':
            '',
            'oid':
            '',
            'fields': [{
                'key': fc,
                'mandatory': fc == 'code',
            } for fc in sorted(get_field_codes(v_collection))],
            'primary_link':
            None,
        })

        for block in blocks(v_collection.find()):
            rb.save_bulk(rb.record_factory(raw) for raw in block)

    RefBookRegistry.bootstrap(mongo[args.db])
Beispiel #7
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
Beispiel #8
0
def init_app_config():
    cnf = load_config_int()
    app.config.update(safe_traverse(cnf, 'subsystems', 'tsukino_usagi', 'app'))
Beispiel #9
0
 def init_app(self, app):
     self._dont_check_tgt = safe_traverse(
         app.config, 'external_cas', 'enabled', default=False
     )
     super(CasExtension, self).init_app(app)
Beispiel #10
0
from sirius.app import app

from contextlib import contextmanager

from sirius.blueprints.monitor.exception import ExternalError, ConnectError

config = app.config
hippo_url = config.get('HIPPOCRATE_URL', 'http://127.0.0.1:6600/').rstrip('/')
coldstar_url = config.get('COLDSTAR_URL', 'http://127.0.0.1:6605/').rstrip('/')
login = config.get('HIPPOCRATE_API_LOGIN', u'ВнешСис')
password = config.get('HIPPOCRATE_API_PASSWORD', '')
authent_token_name = config.get('CASTIEL_AUTH_TOKEN', 'CastielAuthToken')
authoriz_token_name = config.get('HIPPOCRATE_SESSION_KEY', 'hippocrates.session.id')
session = None
dont_check_tgt = safe_traverse(
    config, 'external_cas', 'enabled', default=False
)


def get_token(login, password):
    url = u'%s/cas/api/acquire' % coldstar_url
    result = requests.post(
        url,
        {
            'login': login,
            'password': password
        }
    )
    j = result.json()
    if not j['success']:
        print j