Exemplo n.º 1
0
    def build(self, params):
        begDate = params.get('begDate', QtCore.QDate())
        endDate = params.get('endDate', QtCore.QDate())
        workOrgId = params.get('workOrgId', None)
        sex = params.get('sex', 0)
        ageFrom = params.get('ageFrom', 0)
        ageTo = params.get('ageTo', 150)
        areaIdEnabled = params.get('areaIdEnabled', False)
        areaId = params.get('areaId', None)
        MKBFilter = params.get('MKBFilter', 0)
        MKBFrom = params.get('MKBFrom', 'A00')
        MKBTo = params.get('MKBTo', 'Z99.9')
        MKBExFilter = params.get('MKBExFilter', 0)
        MKBExFrom = params.get('MKBExFrom', 'A00')
        MKBExTo = params.get('MKBExTo', 'Z99.9')
        personId = params.get('personId', None)
        specialityId = params.get('specialityId', None)
        rowGrouping = params.get('rowGrouping', 0)
        orgStructureAttachTypeId = params.get('orgStructureAttachTypeId', None)

        doc = QtGui.QTextDocument()
        cursor = QtGui.QTextCursor(doc)

        cursor.setCharFormat(CReportBase.ReportTitle)
        cursor.insertText(self.title())
        cursor.insertBlock()
        self.dumpParams(cursor, params)
        cursor.insertBlock()

        tableColumns = [
            ('2%', [u'№'], CReportBase.AlignLeft),
            ('11%', [u'ФИО'], CReportBase.AlignLeft),
            ('2%', [u'пол'], CReportBase.AlignCenter),
            ('6%', [u'д.р.'], CReportBase.AlignLeft),
            ('5%', [u'СНИЛС'], CReportBase.AlignLeft),
            ('8%', [u'Полис'], CReportBase.AlignLeft),
            ('8%', [u'Документ'], CReportBase.AlignLeft),
            ('17%', [u'Адрес'], CReportBase.AlignLeft),
            ('7%', [u'Контакты'], CReportBase.AlignLeft),
            ('9%', [u'Занятость'], CReportBase.AlignLeft),
            ('8%', [u'Льгота'], CReportBase.AlignLeft),
            ('5%', [u'Дата взятия на учет'], CReportBase.AlignLeft),
            ('5%', [u'Дата последнего Д - осмотра'], CReportBase.AlignLeft),
            ('8%', [u'Врач'], CReportBase.AlignLeft),
            ('7%', [u'МКБ'], CReportBase.AlignRight),
            ('10%', [u'Примечание'], CReportBase.AlignLeft)
        ]

        table = createTable(cursor, tableColumns)

        query = selectData(begDate, endDate, workOrgId, sex, ageFrom, ageTo,
                           areaIdEnabled, areaId, MKBFilter, MKBFrom, MKBTo,
                           MKBExFilter, MKBExFrom, MKBExTo, personId,
                           specialityId, rowGrouping, self.forChildren,
                           orgStructureAttachTypeId)

        if rowGrouping == 3:  # by personId
            forceKeyVal = forceRef
            keyValToString = lambda personId: forceString(
                QtGui.qApp.db.translate('vrbPersonWithSpeciality', 'id',
                                        personId, 'name'))
        elif rowGrouping == 2:  # by speciality_id
            forceKeyVal = forceRef
            keyValToString = lambda specialityId: forceString(
                QtGui.qApp.db.translate('rbSpeciality', 'id', specialityId,
                                        'name'))
        elif rowGrouping == 1:  # by orgStructureId
            forceKeyVal = forceRef
            keyValToString = lambda orgStructureId: forceString(
                QtGui.qApp.db.translate('OrgStructure', 'id', orgStructureId,
                                        'name'))
        prevRowKey = ''
        count = 0
        n = 0
        countViewClient = 1

        self.setQueryText(forceString(query.lastQuery()))
        currentClient = None
        while query.next():
            record = query.record()
            clientId = forceInt(record.value('id'))
            name = formatName(record.value('lastName'),
                              record.value('firstName'),
                              record.value('patrName'))
            birthDate = forceString(record.value('birthDate'))
            sex = formatSex(forceInt(record.value('sex')))
            SNILS = formatSNILS(record.value('SNILS'))
            policy = ' '.join([
                forceString(record.value('policySerial')),
                forceString(record.value('policyNumber')),
                forceString(record.value('insurer'))
            ])
            document = ' '.join([
                forceString(record.value('documentSerial')),
                forceString(record.value('documentNumber'))
            ])
            regAddress = forceString(record.value('regAddress'))
            locAddress = forceString(record.value('locAddress'))
            MKB = forceString(record.value('MKB'))
            #            endDate = forceDate(record.value('endDate'))
            contacts = forceString(record.value('contact'))
            socStatus = forceString(record.value('socStatus'))
            dateAccount = forceDate(
                record.value('dateAccount')).toString('dd.MM.yyyy')
            dateView = forceDate(
                record.value('dateView')).toString('dd.MM.yyyy')
            person = forceString(record.value('person'))
            work = ' '.join([
                forceString(record.value('workName')),
                forceString(record.value('workPost'))
            ])
            firstInPeriod = forceString(record.value('firstInPeriod'))
            if rowGrouping:
                rowKey = forceKeyVal(record.value('rowKey'))
                if prevRowKey and rowKey != prevRowKey:
                    i = table.addRow()
                    if not rowKey:
                        table.setText(i, 1, u'всего по ' + '-',
                                      CReportBase.TableTotal)
                    else:
                        table.setText(
                            i, 1, u'всего по ' + keyValToString(prevRowKey),
                            CReportBase.TableTotal)
                    table.setText(i, 2, n, CReportBase.TableTotal)
                    table.mergeCells(i, 2, 1, 15)
                    n = 0
                if rowKey != prevRowKey:
                    i = table.addRow()
                    table.mergeCells(i, 0, 1, 15)
                    i = table.addRow()
                    if not rowKey:
                        table.setText(i, 0, '-', CReportBase.TableTotal)
                    else:
                        table.setText(i, 0, keyValToString(rowKey),
                                      CReportBase.TableTotal)
                    table.mergeCells(i, 0, 1, 15)
                    prevRowKey = rowKey
            i = table.addRow()
            if not self.forChildren:
                currentClient = None
            if currentClient != clientId:
                currentDateAccount = None
                if self.forChildren:
                    for column in xrange(15):
                        if column not in (14, 13, 12, 11):
                            table.mergeCells(i - countViewClient, column,
                                             countViewClient, 1)
                n += 1
                table.setText(i, 0, n)
                table.setText(i, 1, name)
                table.setText(i, 2, sex)
                table.setText(i, 3, birthDate)
                table.setText(i, 4, SNILS)
                table.setText(i, 5, policy)
                table.setText(i, 6, document)
                table.setText(i, 7, regAddress + '\n' + locAddress)
                table.setText(i, 8, contacts)
                table.setText(i, 9, work)
                table.setText(i, 10, socStatus)
                table.setText(i, 11, dateAccount)
                table.setText(i, 12, dateView)
                table.setText(i, 13, person)
                table.setText(i, 14, MKB)
                if self.forChildren:
                    table.setText(i, 15, firstInPeriod)
                count += 1
                countViewClient = 1
                currentClient = clientId
                countDateAccount = 1
            else:
                countViewClient += 1
                if dateAccount != currentDateAccount:
                    table.mergeCells(i - countDateAccount, 11,
                                     countDateAccount, 1)
                    table.setText(i, 11, dateAccount)
                    currentDateAccount = dateAccount
                    countDateAccount = 0
                table.setText(i, 12, dateView)
                table.setText(i, 13, person)
                table.setText(i, 14, MKB)
                if self.forChildren:
                    table.setText(i, 15, firstInPeriod)
                countDateAccount += 1

        if rowGrouping:
            i = table.addRow()
            table.setText(i, 1, u'всего по ' + keyValToString(rowKey),
                          CReportBase.TableTotal)
            table.setText(i, 2, n)
            table.mergeCells(i, 2, 1, 15)
            i = table.addRow()
            table.setText(i, 1, u'ВСЕГО', CReportBase.TableTotal)
            table.setText(i, 2, count, CReportBase.TableTotal)
            table.mergeCells(i, 2, 1, 15)
        if self.forChildren:
            sex = params.get('sex', 0)
            query = selectResultData(begDate, endDate, workOrgId, sex, ageFrom,
                                     ageTo, areaIdEnabled, areaId, MKBFilter,
                                     MKBFrom, MKBTo, MKBExFilter, MKBExFrom,
                                     MKBExTo, personId, self.forChildren,
                                     orgStructureAttachTypeId)
            self.setQueryText(forceString(query.lastQuery()))
            if query.first():
                record = query.record()
                count = forceInt(record.value('count'))
                countInFirst = forceInt(record.value('countInFirst'))
                i = table.addRow()
                table.mergeCells(i, 0, 1, 2)
                table.mergeCells(i, 2, 1, 14)
                table.setText(i, 0, u'Всего состоит: ')
                table.setText(i, 2, count)
                i = table.addRow()
                table.mergeCells(i, 0, 1, 2)
                table.mergeCells(i, 2, 1, 14)
                table.setText(i, 0, u'Всего взято впервые: ')
                table.setText(i, 2, countInFirst)
        return doc
Exemplo n.º 2
0
    def getItemFromRecord(self, record):
        begDate = forceDateTime(record.value('begDate'))
        endDate = forceDateTime(record.value('endDate'))
        bedCodeName = forceString(record.value('bedCodeName')).split("  ")
        directionDate = forceDateTime(record.value('directionDate'))

        statusObservation = forceString(record.value('statusObservation')).split("  ")
        statusObservationCode = forceString(statusObservation[0]) if len(statusObservation)>=1 else ''
        statusObservationName = forceString(statusObservation[1]) if len(statusObservation)>=2 else ''
        statusObservationColor = forceString(statusObservation[2]) if len(statusObservation)>=3 else ''

        comfortable = forceString(record.value('comfortable'))
        comfortableList = []
        if comfortable:
            comfortableList = comfortable.split("  ")
        comfortableDate = forceDateTime(QtCore.QVariant(comfortableList[0])) if len(comfortableList)>=1 else ''
        comfortableStatus = forceInt(QtCore.QVariant(comfortableList[1])) if len(comfortableList)>=2 else 0
        if comfortableStatus:
            comfortablePayStatus = getRealPayed(comfortableStatus)
        else:
            comfortablePayStatus = False
        birthDate = forceDate(record.value('birthDate'))
        ageString = forceString(calcAge(birthDate, forceDate(endDate)))
        ageInYears = forceInt(calcAgeInYears(birthDate, forceDate(QtCore.QDate().currentDate())))
        sex = forceInt(record.value('sex'))
        item = {'statusObservationCode' : statusObservationCode,
                'nameFinance' : forceString(record.value('nameFinance')),
                'codeFinance' : forceString(record.value('codeFinance')),
                'feed' : forceBool(record.value('countEventFeedId')),
                'physicalActivityName' : forceString(record.value('physicalActivityName')),
                'clientId' : forceRef(record.value('client_id')),
                'contractInfo': '%s %s %s' % tuple(map(lambda f: forceStringEx(record.value(f)), ['contract_number', 'contract_date', 'contract_resolution'])),
                'externalId' : forceString(record.value('externalId')),
                'clientName' : forceString(record.value('lastName')) + u' ' + forceString(record.value('firstName')) + u' ' + forceString(record.value('patrName')),
                'sex' : self.sex[sex],
                'birthDateRaw' : birthDate,
                'birthDate' : forceString(birthDate),
                'age' : ageString,
                'employable': self.employableCheck(sex, ageInYears),
                'plannedEndDate' : forceDate(record.value('plannedEndDate')),
                'MKB' : forceString(record.value('MKB')),
                'quota':  forceString(record.value('quotaCode')),#quotaTypeClassItems[forceInt(record.value('class'))][0] if forceRef(record.value('class')) >= 0 else u'',
                'codeBed' : forceString(bedCodeName[0]) if len(bedCodeName)>=1 else '' + forceString(bedCodeName[2]) if len(bedCodeName)>=3 else '',
                'nameBed' : forceString(bedCodeName[1]) if len(bedCodeName)>=2 else '',
                'profileBed': forceString(record.value('bedProfile')),
                'nameOS' : forceString(record.value('nameOS')),
                'codeOS' : forceString(record.value('codeOS')),
                'idOS' : forceRef(record.value('idOS')),
                'namePerson' : forceString(record.value('namePerson')),
                'eventId' : forceRef(record.value('eventId')),
                'statusObservationName' : statusObservationName,
                'actionId' : forceRef(record.value('actionId')),
                'actionTypeId' : forceRef(record.value('actionType_id')),
                'statusObservationColor' : statusObservationColor,
                'begDate' : begDate,
                'endDate' : endDate,
                'begDateString' : begDate.toString('dd.MM.yyyy hh:mm'),
                'endDateString' : endDate.toString('dd.MM.yyyy hh:mm'),
                'begDateReceived' : forceDateTime(record.value('setDate')).toString('dd.MM.yyyy hh:mm'),
                'waitingDays': directionDate.daysTo(QtCore.QDateTime.currentDateTime()) if not directionDate.date().isNull() else u'',
                'isHasNotPayedActions' : forceBool(record.value('isExistsNotPayedActions')),     #Определение наличия в событии клиента действий, имеющих тип финансирования ПМУ и без состояния "Оплачено" (задача 482, atronah)
                'comfortableDate' : comfortableDate,
                'comfortablePayStatus' : comfortablePayStatus,
                'patronage': u'да' if forceBool(record.value('patronage')) else u'',
                'currentCommonOSName' : forceStringEx(record.value('currentCommonOSName')),
                'isUnconscious': forceInt(record.value('isUnconscious')),
                'isVIP': forceInt(record.value('isVIP')),
                'vipColor': forceInt(record.value('vipColor')),
                'snils': formatSNILS(forceString(record.value('SNILS'))),
                'directionDate': forceDate(record.value('directionDate'))
                }
        return item
Exemplo n.º 3
0
    def process(self, dbfP, record, codeLPU):
        db = QtGui.qApp.db
        birthDate = forceDate(record.value('clientBirthDate'))
        # Номер стат.талона
        clientId = forceRef(record.value('clientId'))
        eventId = forceRef(record.value('eventId'))

        insurerArea = forceString(record.value('insurerArea'))
        isAlien = insurerArea[:2] != QtGui.qApp.defaultKLADR()[:2]

        if not ((clientId, eventId) in self.exportedClients):
            dbfRecord = dbfP.newRecord()
            # номер реестра счетов (п. 1 примечаний) обязательное
            # dbfRecord['NS'] = 123 #self.edtRegistryNumber.value()
            # тип реестра счетов (п. 2;4 примечаний) обязательное SPR21
            # dbfRecord['VS'] = accType
            # дата формирования реестра счетов (п. 3 примечаний) обязательное
            dbfRecord['DATS'] = pyDate(QtCore.QDate())
            # номер персонального счета	обязательное
            dbfRecord[
                'SN'] = eventId  # В импорте ФЛК в этом поле ожидается Event.id
            # дата формирования персонального счета обязательное
            dbfRecord['DATPS'] = pyDate(QtCore.QDate())
            # код медицинской организации в системе ОМС,
            # предоставившей медицинскую помощь обязательное SPR01
            dbfRecord['CODE_MO'] = codeLPU
            # ОГРН плательщика
            dbfRecord['PL_OGRN'] = forceString(
                record.value('insurerOGRN')) or (self.TF_OGRN
                                                 if isAlien else '')
            #  фамилия (п. 5 примечаний) обязательное
            dbfRecord['FIO'] = nameCase(
                forceString(record.value('clientLastName')))
            # имя (п. 5 примечаний) обязательное
            dbfRecord['IMA'] = nameCase(
                forceString(record.value('clientFirstName')))
            # отчество (п. 5 примечаний)
            patrName = forceString(record.value('clientPatrName'))
            dbfRecord['OTCH'] = nameCase(patrName)
            # пол (М/Ж) (п. 6 примечаний) обязательное
            dbfRecord['POL'] = formatSex(record.value('clientSex')).upper()
            # дата рождения (п. 7 примечаний) обязательное
            dbfRecord['DATR'] = pyDate(birthDate)
            # СНИЛС
            dbfRecord['SNILS'] = formatSNILS(
                forceString(record.value('clientSNILS')))
            # статус пациента обязательное SPR40
            age = calcAgeInYears(birthDate, QtCore.QDate.currentDate())

            # код ОКАТО территории страхования по ОМС обязательное для инокраевых SPR39
            dbfRecord['OKATO_OMS'] = forceStringEx(
                record.value('insurerOKATO'))

            if not dbfRecord['OKATO_OMS']:
                insurerName = forceString(record.value('insurerName'))
                self.log(u'<b><font color=orange>Внимание</font></b>:' \
                         u' ОКАТО для ОМС "%s" не задан, пытаюсь определить по области страхования!' % insurerName)

                dbfRecord['OKATO_OMS'] = forceString(
                    db.translate('kladr.KLADR',
                                 'CODE',
                                 insurerArea,
                                 'OCATD',
                                 idFieldName='CODE'))
                if not dbfRecord['OKATO_OMS']:
                    self.log(u'<b><font color=red>Внимание</font></b>:' \
                             u' ОКАТО для ОМС "%s" не задан!' % forceString(record.value('insurerName')))

                    policyInsuranceArea = forceString(
                        record.value('policyInsuranceArea'))
                    if policyInsuranceArea:
                        dbfRecord['OKATO_OMS'] = forceString(
                            db.translate('kladr.KLADR',
                                         'CODE',
                                         policyInsuranceArea,
                                         'OCATD',
                                         idFieldName='CODE'))

            # серия полиса ОМС обязательное
            dbfRecord['SPS'] = forceString(record.value('policySerial'))
            # номер полиса ОМС обязательное
            dbfRecord['SPN'] = forceString(record.value('policyNumber'))
            # дата начала действия полиса ОМС (п. 8 примечаний) обязательное для инокраевых

            # серия документа, удостоверяющего личность пациента (представителя) (п. 10 примечаний)
            documentSerial = forceString(record.value('documentSerial'))
            if documentSerial:
                dbfRecord['S_DOC'] = documentSerial
            # номер документа, удостоверяющего личность пациента (представителя) (п. 10 примечаний)
            documentNumber = forceString(record.value('documentNumber'))
            if documentNumber:
                dbfRecord['N_DOC'] = documentNumber

            # Признак новорожденого
            isLittleStrangerAge = calcAgeInDays(
                birthDate, forceDate(record.value('eventSetDate'))) < 90
            exportAsLittleStranger = isLittleStrangerAge and (
                dbfRecord['S_DOC'] == '' and dbfRecord['N_DOC'] == '')
            # (dbfRecord['SPS'] == '' and dbfRecord['SPN'] == '') and \

            # признак "Особый случай" при регистрации обращения
            # за медицинской помощью (п. 9 примечаний) SPR42
            flags = ''
            if dbfRecord['SPS'] == '' and dbfRecord['SPN'] == '' and forceDate(
                    record.value('eventExecDate')) <= QtCore.QDate(
                        2016, 9, 30):  # нет данных по полису:
                flags += ' 1'
            if exportAsLittleStranger:  # новорождённый:
                flags += ' 2'
            if patrName == '':
                flags += ' 4'
            flags += ' ' + self.getSocStatusFederalCode(clientId)

            dbfRecord['Q_G'] = trim(flags)

            representativeInfo = self.getClientRepresentativeInfo(clientId)
            if exportAsLittleStranger and representativeInfo:
                # статус представителя пациента  обязательное для инокраевых SPR41
                # dbfRecord['STAT_P'] = representativeInfo.get('relationTypeCode', '0')[:1] # 'C', 1),
                # фамилия родителя (представителя) пациента (п. 5 примечаний) обязательное для инокраевых
                dbfRecord['FAMP'] = representativeInfo.get('lastName', '')
                # имя родителя (представителя) пациента (п. 5 примечаний) обязательное для инокраевых
                dbfRecord['IMP'] = representativeInfo.get('firstName', '')
                # отчество родителя (представителя) пациента (п. 5 примечаний)
                dbfRecord['OTP'] = representativeInfo.get('patrName', '')
                s = representativeInfo.get('serial', '')
                n = representativeInfo.get('number', '')

                # код типа документа, удостоверяющего личность пациента (представителя) (п. 10 примечаний) SPR43
                dbfRecord['C_DOC'] = representativeInfo.get(
                    'documentTypeRegionalCode', 18 if s or n else 0) % 100
                # серия документа, удостоверяющего личность пациента (представителя) (п. 10 примечаний)
                dbfRecord['S_DOC'] = s
                # номер документа, удостоверяющего личность пациента (представителя) (п. 10 примечаний)
                dbfRecord['N_DOC'] = n

                sexp = representativeInfo.get('sex', 0)
                dbfRecord[
                    'POLP'] = u'М' if sexp == 1 else u'Ж' if sexp == 2 else u'0'

                dbfRecord['DATRP'] = pyDate(
                    representativeInfo.get('birthDate', None))

                dbfRecord['FIO'] = dbfRecord['FAMP']
                dbfRecord['IMA'] = dbfRecord['IMP']
                dbfRecord['OTCH'] = dbfRecord['OTP']
                dbfRecord['POL'] = dbfRecord['POLP']
                dbfRecord['DATR'] = dbfRecord['DATRP']
                dbfRecord['SNILS'] = formatSNILS(
                    representativeInfo.get('SNILS', ''))
                dbfRecord['SPS'] = representativeInfo.get('policySerial', '')
                dbfRecord['SPN'] = representativeInfo.get('policyNumber', '')

            # код типа документа, удостоверяющего личность пациента (представителя)
            # (п. 10 примечаний) SPR43
            documentRegionalCode = forceInt(
                record.value('documentTypeRegionalCode')) % 100
            if documentRegionalCode and (documentSerial or documentNumber):
                dbfRecord['C_DOC'] = documentRegionalCode

            dbfRecord['SPV'] = forceInt(record.value('policyKindCode')) % 10
            setDate = forceDate(record.value('eventSetDate')).toPyDate()
            execDate = forceDate(record.value('eventExecDate')).toPyDate()
            dbfRecord['DATN'] = setDate
            dbfRecord['DATO'] = execDate

            dbfRecord.store()
            self.exportedClients.add((clientId, eventId))
Exemplo n.º 4
0
    def build(self, description, params):
        def getAddressRecord(record, type=0):
            if type == 0:
                prefix = 'reg'
            else:
                prefix = 'loc'
            address = smartDict()
            address.KLADRCode = forceString(record.value(prefix + 'KLADRCode'))
            address.KLADRStreetCode = forceString(
                record.value(prefix + 'KLADRStreetCode'))
            address.number = forceString(record.value(prefix + 'Number'))
            address.corpus = forceString(record.value(prefix + 'Corpus'))
            address.flat = forceString(record.value(prefix + 'Flat'))
            address.freeInput = forceString(record.value(prefix + 'FreeInput'))
            return address

        accountItemIdList = params.get('accountItemIdList', None)
        currentFinanceId = params.get('currentFinanceId', None)
        showLocAddr = params.get('showLocAddr', False)
        query = selectData(accountItemIdList, currentFinanceId, showLocAddr)

        # now text
        doc = QtGui.QTextDocument()
        cursor = QtGui.QTextCursor(doc)

        cursor.setCharFormat(CReportBase.ReportTitle)
        cursor.insertText(self.title())
        cursor.insertBlock()
        cursor.setCharFormat(CReportBase.ReportBody)
        cursor.insertText(description)
        cursor.insertBlock()

        if showLocAddr:
            tableColumns = [
                ('3%', [u'№'], CReportBase.AlignRight),
                ('5%', [u'Номер карты'], CReportBase.AlignCenter),
                ('10%', [u'СНИЛС'], CReportBase.AlignLeft),
                ('20%', [u'ФИО'], CReportBase.AlignLeft),
                ('8%', [u'Дата рождения'], CReportBase.AlignLeft),
                ('3%', [u'Пол'], CReportBase.AlignCenter),
                ('12%', [u'Полис'], CReportBase.AlignCenter),
                ('10%', [u'Документ'], CReportBase.AlignCenter),
                ('15%', [u'Адрес регистрации'], CReportBase.AlignLeft),
                ('15%', [u'Адрес проживания'], CReportBase.AlignLeft),
            ]
        else:
            tableColumns = [('3%', [u'№'], CReportBase.AlignRight),
                            ('10%', [u'СНИЛС'], CReportBase.AlignLeft),
                            ('20%', [u'ФИО'], CReportBase.AlignLeft),
                            ('10%', [u'Дата рождения'], CReportBase.AlignLeft),
                            ('3%', [u'Пол'], CReportBase.AlignCenter),
                            ('15%', [u'Полис'], CReportBase.AlignCenter),
                            ('15%', [u'Документ'], CReportBase.AlignCenter),
                            ('20%', [u'Адрес'], CReportBase.AlignLeft)]

        table = createTable(cursor, tableColumns)
        n = 0
        offset = 1 if showLocAddr else 0
        self.setQueryText(forceString(query.lastQuery()))
        while query.next():
            n += 1
            record = query.record()
            externalId = forceString(record.value('numberCardCall'))
            if not externalId:
                externalId = forceString(record.value('externalId'))
            name = formatName(record.value('lastName'),
                              record.value('firstName'),
                              record.value('patrName'))
            birthDate = forceString(record.value('birthDate'))
            sex = formatSex(forceInt(record.value('sex')))
            SNILS = formatSNILS(record.value('SNILS'))
            policyInfoList = [
                forceString(record.value('policySerial')),
                forceString(record.value('policyNumber')),
                forceString(record.value('policyInsurer'))
            ]
            if showLocAddr:
                policyInfoList.append(
                    forceString(record.value('policyInsurerName')))

            policy = ' '.join(policyInfoList)
            policyName = forceString(record.value('policyName'))
            if policyName:
                policy += '\n' + policyName
            document = ' '.join([
                forceString(record.value('documentSerial')),
                forceString(record.value('documentNumber'))
            ])
            i = table.addRow()
            table.setText(i, 0, n)
            if showLocAddr:
                table.setText(i, 1, externalId)
            table.setText(i, 1 + offset, SNILS)
            table.setText(i, 2 + offset, name)
            table.setText(i, 3 + offset, birthDate)
            table.setText(i, 4 + offset, sex)
            table.setText(i, 5 + offset, policy)
            table.setText(i, 6 + offset, document)

            if showLocAddr:
                from Registry.Utils import formatAddressInt
                regAddress = formatAddressInt(getAddressRecord(record))
                locAddress = formatAddressInt(getAddressRecord(record, 1))
                table.setText(i, 7 + offset, regAddress)
                table.setText(i, 8 + offset, locAddress)
            else:
                table.setText(i, 7 + offset,
                              forceString(record.value('address')))
        return doc
Exemplo n.º 5
0
    def sendClient(self, clientId):
        loc = UploadServiceLocator()
        tracefile = open(self.tracefilename,
                         'a') if self.tracefilename is not None else None
        port = loc.getUploadServiceSoap(url=(self.url +
                                             '/drugstore/UploadService.asmx'),
                                        tracefile=tracefile,
                                        transdict={'timeout': 5})
        failures = []
        db = self.db
        tableClient = db.table('Client')
        tableClientRecipeExport = db.table('ClientRecipeExport')
        clientRecord = db.getRecord(tableClient, '*', clientId)
        query = self.getPrivilege(clientId)
        errorList = []
        msg = None
        try:
            msg = PersonClientSaveSoapIn()
            msg._clientId = self.clientId
            msg._persons = ns0.ArrayOfPersonClient_Def('_persons')
            person = ns0.PersonClient_Def('_PersonClient')
            msg._persons._PersonClient = [person]

            person._Firstname = forceString(clientRecord.value('firstName'))
            person._Lastname = forceString(clientRecord.value('lastName'))
            person._Patronymic = forceString(clientRecord.value('patrName'))
            SNILS = clientRecord.value('SNILS')
            if not forceString(clientRecord.value('SNILS')):
                tableFakeSNILS = db.table('ClientFakeSNILS')
                fakeSnilsRecord = db.getRecordEx(tableFakeSNILS,
                                                 '*',
                                                 where='client_id = %d' %
                                                 clientId)
                if fakeSnilsRecord:
                    SNILS = fakeSnilsRecord.value('fakeSNILS')
            person._Snils = formatSNILS(forceString(SNILS))
            person._Sex = [u'', u'М',
                           u'Ж'][forceInt(clientRecord.value('sex'))]
            person._Birthday = self.toDateTuple(
                forceDateTime(clientRecord.value('birthDate')))
            person._CredentialTypeName = u'ПАСПОРТ'  # ?
            person._PersonFound = False
            person._Uploaded = False
            person._PrivilegeDocuments = ns0.ArrayOfPrivilegeDocumentClient_Def(
                '_PrivilegeDocuments')
            person._PrivilegeDocuments._PrivilegeDocumentClient = []
            while query.next():
                documentRecord = query.record()
                privilegeDocumentClient = ns0.PrivilegeDocumentClient_Def(
                    '_PrivilegeDocumentClient')
                privilegeDocumentClient._PrivilegeDocumentSeria = forceString(
                    documentRecord.value('serial'))
                privilegeDocumentClient._PrivilegeDocumentNumber = forceString(
                    documentRecord.value('number'))
                privilegeDocumentClient._PrivilegeDocumentName = forceString(
                    documentRecord.value('name'))
                privilegeDocumentClient._PrivilegeCategoryCode = forceString(
                    documentRecord.value('code'))
                privilegeDocumentClient._PrivilegeDocumentStart = self.toCorrectBegDate(
                    forceDateTime(documentRecord.value('begDate')))
                privilegeDocumentClient._PrivilegeDocumentEnd = self.toCorrectEndDate(
                    forceDateTime(documentRecord.value('endDate')))
                if forceBool(documentRecord.value('deleted')):
                    privilegeDocumentClient._PrivilegeDocumentDeleted = self.toDateTuple(
                        forceDateTime(documentRecord.value('modifyDatetime')))
                privilegeDocumentClient._Uploaded = False
                person._PrivilegeDocuments._PrivilegeDocumentClient.append(
                    privilegeDocumentClient)

            resp = port.PersonClientSave(msg)

            if not forceString(clientRecord.value('SNILS')):
                tableFakeSNILS = db.table('ClientFakeSNILS')
                fakeSnilsRecord = db.getRecordEx(tableFakeSNILS,
                                                 '*',
                                                 where='client_id = %d' %
                                                 clientId)
                if not fakeSnilsRecord:
                    fakeSnilsRecord = tableFakeSNILS.newRecord()
                    fakeSnilsRecord.setValue('client_id', toVariant(clientId))
                    fakeSnilsRecord.setValue(
                        'fakeSNILS',
                        toVariant(
                            unformatSNILS(resp._PersonClientSaveResult.
                                          _PersonClient[0]._Snils)))
                    db.insertRecord(tableFakeSNILS, fakeSnilsRecord)

            if forceString(resp._PersonClientSaveResult._PersonClient[0].
                           _Uploaded) == u'true':
                clientExportRecord = db.getRecordEx(tableClientRecipeExport,
                                                    '*',
                                                    where='client_id = %d' %
                                                    clientId)
                if clientExportRecord is None:
                    clientExportRecord = tableClientRecipeExport.newRecord()
                clientExportRecord.setValue('client_id', toVariant(clientId))
                clientExportRecord.setValue('sentToMiac', toVariant(1))
                clientExportRecord.setValue('errorList', toVariant(''))
                db.insertOrUpdate(tableClientRecipeExport, clientExportRecord)
            else:
                errorList.append(u'<Check>' + resp._PersonClientSaveResult.
                                 _PersonClient[0]._Check.decode('utf8') +
                                 u'</Check>; ')

        except SocketError:
            errorList.append(u'не удалось установить соединение')
        except Exception, e:
            errorList.append(u'неизвестная ошибка: {0}'.format(forceString(e)))
Exemplo n.º 6
0
    def sendRecipes(self, recipesIdList):
        loc = UploadServiceLocator()
        tracefile = open(self.tracefilename,
                         'a') if self.tracefilename is not None else None
        port = loc.getUploadServiceSoap(url=(self.url +
                                             '/drugstore/UploadService.asmx'),
                                        tracefile=tracefile,
                                        transdict={'timeout': 5})
        failures = False  # Возможно лучше словарь и возвращать сразу список ошибок

        db = self.db
        tableDrugRecipe = db.table('DrugRecipe')
        stmt = u'''
        SELECT
            DrugRecipe.*,
            Client.SNILS,
            Client.id AS clientId,
            Organisation.OGRN,
            OrgStructure.bookkeeperCode AS FOMS,
            rbFinance.code AS typeFinanceCode,
            Person.federalCode AS personCode,
            dlo_rbMNN.code AS mnnCode,
            dlo_rbTradeName.code AS trnCode,
            dlo_rbMNN.name AS mnnName,
            dlo_rbTradeName.name AS trnName,
            dlo_rbIssueForm.code AS cureFormCode,
            DloDrugFormulary_Item.dosageLs AS dosageLs,
            DloDrugFormulary_Item.qnt AS packQnt
        FROM
            DrugRecipe
            INNER JOIN Event ON DrugRecipe.event_id = Event.id
            INNER JOIN Client ON Event.client_id = Client.id
            INNER JOIN Person ON Event.execPerson_id = Person.id
            INNER JOIN Organisation ON Event.org_id = Organisation.id
            INNER JOIN OrgStructure ON Person.orgStructure_id = OrgStructure.id
            INNER JOIN DloDrugFormulary_Item ON DrugRecipe.formularyItem_id = DloDrugFormulary_Item.id
            INNER JOIN dlo_rbMNN ON DloDrugFormulary_Item.mnn_id = dlo_rbMNN.id
            INNER JOIN dlo_rbTradeName ON DloDrugFormulary_Item.tradename_id=dlo_rbTradeName.id
            INNER JOIN dlo_rbIssueForm ON DloDrugFormulary_Item.issueForm_id = dlo_rbIssueForm.id
            INNER JOIN rbFinance ON DrugRecipe.finance_id = rbFinance.id
        WHERE
            %s
        '''
        query = db.query(stmt % tableDrugRecipe['id'].inlist(recipesIdList))
        drugRecords = []
        try:
            # msg = None
            msg = RecipesClientSaveSoapIn()
            msg._clientId = self.clientId
            msg._recipes = ns0.ArrayOfRecipeClient_Def('_recipes')
            msg._recipes._RecipeClient = []
            while query.next():
                record = query.record()
                drugRecord = db.getRecord(tableDrugRecipe, '*',
                                          forceInt(record.value('id')))
                drugRecords.append(drugRecord)
                recipe = ns0.RecipeClient_Def('_RecipeClient')
                msg._recipes._RecipeClient.append(recipe)

                recipe._Seria, recipe._Number = forceString(
                    record.value('number')).split('#')
                SNILS = record.value('SNILS')
                if not forceString(record.value('SNILS')):
                    tableFakeSNILS = db.table('ClientFakeSNILS')
                    fakeSnilsRecord = db.getRecordEx(
                        tableFakeSNILS,
                        '*',
                        where='client_id = %s' %
                        forceString(record.value('clientId')))
                    if fakeSnilsRecord:
                        SNILS = fakeSnilsRecord.value('fakeSNILS')
                recipe._Snils = formatSNILS(forceString(SNILS))
                recipe._LpuOgrn = forceString(record.value('OGRN'))
                recipe._LpuFoms = forceString(record.value('FOMS'))
                recipe._DoctorCode = forceString(record.value('personCode'))
                recipe._MkbCode = forceString(record.value('mkb'))
                recipe._FundingSourceCode = {
                    '70': 1,
                    '71': 2,
                    '72': 3,
                    '73': 0
                }[forceString(record.value('typeFinanceCode'))]
                recipe._PrivilegeCode = forceString(record.value('socCode'))
                periods = [u'5d', u'10d', u'1m', u'3m'] if self.getYear(
                    forceDateTime(record.value('dateTime'))) < 2016 else [
                        u'5d', u'15d', u'30d', u'90d'
                    ]
                recipe._ValidPeriodCode = periods[forceInt(
                    record.value('term'))]
                recipe._PayPercent = {
                    100: 0,
                    50: 1
                }[forceInt(record.value('percentage'))]
                recipe._IsVk = forceBool(record.value('isVk'))
                recipe._Dosage = forceString(
                    record.value('dosageLs'))  # dlo_rbDosage.miacCode
                recipe._Quantity = 1000 * forceDouble(
                    record.value('qnt')) / forceDouble(record.value('packQnt'))
                if not record.value('cureFormCode').isNull():
                    recipe._CureformCode = forceString(
                        record.value('cureFormCode'))
                # recipe._UnitCode = forceString(record.value('unitCode'))

                if forceBool(record.value('printMnn')) and forceString(
                        record.value('mnnName')) != '~' or record.value(
                            'trnName').isNull():
                    recipe._IsTrn = False
                    recipe._MnnCode = forceString(
                        record.value('mnnCode')
                    ) if not record.value('mnnCode').isNull() else forceString(
                        record.value('mnnName'))
                else:
                    recipe._IsTrn = True
                    recipe._TrnCode = forceString(
                        record.value('trnCode')
                    ) if not record.value('trnCode').isNull() else forceString(
                        record.value('trnName'))

                recipe._IssueDate = self.toDateTuple(
                    forceDateTime(record.value('dateTime')))

                recipeStatus = forceInt(record.value('status'))
                recipe._IsAnnulled = False if not recipeStatus else True
                if recipeStatus:
                    recipe._CauseOfAnnulment = recipeStatusNames[recipeStatus]

                recipe._PatientFound = False
                recipe._LpuFound = False
                recipe._DoctorFound = False
                recipe._MkbFound = False
                recipe._FundingSourceFound = False
                recipe._PrivilegeCodeFound = False
                recipe._NosologyFound = False
                recipe._ProgramFound = False
                recipe._ValidPeriodFound = False
                recipe._PayPercentFound = False
                recipe._TrnFound = False
                recipe._MnnFound = False
                recipe._CureformFound = False
                recipe._UnitFound = False
                recipe._CauseOfAnnulmentFound = False
                recipe._Uploaded = False

                # recipe._IsDeleted = False

            if not drugRecords:
                return failures

            resp = port.RecipesClientSave(msg)

            for index, recipeResponse in enumerate(
                    resp._RecipesClientSaveResult._RecipeClient):
                errorList = []
                drugRecord = drugRecords[index]

                if recipeResponse._Uploaded:
                    drugRecord.setValue('sentToMiac', toVariant(1))
                    drugRecord.setValue('errorList', toVariant(''))
                    db.updateRecord(tableDrugRecipe, drugRecord)
                else:
                    if hasattr(recipeResponse, '_RecipeCheck'):
                        if forceString(recipeResponse._RecipeCheck).startswith(
                                u'Статус рецепта'):
                            drugRecord.setValue('sentToMiac', toVariant(1))
                            drugRecord.setValue('errorList', toVariant(''))
                            db.updateRecord(tableDrugRecipe, drugRecord)
                            return
                        errorList.append(
                            forceString(recipeResponse._RecipeCheck))
                    if not recipeResponse._PatientFound:
                        errorList.append(u'пациент не найден')
                    if not recipeResponse._LpuFound:
                        errorList.append(u'ЛПУ не найдено')
                    if not recipeResponse._DoctorFound:
                        errorList.append(u'врач не найден')
                    if not recipeResponse._MkbFound:
                        errorList.append(u'код МКБ не найден')
                    if not recipeResponse._FundingSourceFound:
                        errorList.append(u'источник финансирования не найден')
                    if not recipeResponse._ValidPeriodFound:
                        errorList.append(u'срок действия рецепта не найден')
                    if not recipeResponse._PayPercentFound:
                        errorList.append(u'процент оплаты не найден')
                    if not recipeResponse._CureformFound:
                        errorList.append(
                            u'код формы выпуска препарата не найден')
                    if recipeResponse._IsTrn:
                        if not recipeResponse._TrnFound:
                            errorList.append(u'торговое название не найдено')
                    else:
                        if not recipeResponse._MnnFound:
                            errorList.append(u'МНН не найдено')

                if errorList:
                    drugRecord.setValue('sentToMiac', toVariant(0))
                    drugRecord.setValue('errorCode',
                                        toVariant(', '.join(errorList)))
                    db.updateRecord(tableDrugRecipe, drugRecord)
                    failures = True

        except SocketError:
            for drugRecord in drugRecords:
                drugRecord.setValue('sentToMiac', toVariant(0))
                drugRecord.setValue(
                    'errorCode',
                    toVariant(u'не удалось установить соединение'))
                db.updateRecord(tableDrugRecipe, drugRecord)
            failures = True
        except Exception, e:
            for drugRecord in drugRecords:
                drugRecord.setValue('sentToMiac', toVariant(0))
                drugRecord.setValue(
                    'errorCode',
                    toVariant(u'неизвестная ошибка: {0}'.format(
                        forceString(e))))
                db.updateRecord(tableDrugRecipe, drugRecord)
            failures = True
Exemplo n.º 7
0
    def build(self, params):
        begDate = params.get('begDate', QtCore.QDate())
        endDate = params.get('endDate', QtCore.QDate())
        statusInPeriod = params.get('statusInPeriod', 0)
        statusStart = params.get('statusStart', 0)
        statusFinish = params.get('statusFinish', 0)
        sex = params.get('sex', 0)
        ageFrom = params.get('ageFrom', 0)
        ageTo = params.get('ageTo', 150)
        groupId = params.get('groupId', 0)
        onlyPermanentAttach = params.get('onlyPermanentAttach', False)
        addMKB = params.get('addMKB', False)
        addDeathDate = params.get('addDeathDate', False)
        groupBySocStatus = params.get('groupBySocStatus', True)
        orgStructureId = getVal(params, 'orgStructureId', None)
        areaAddressType = getVal(params, 'areaAddressType', 0)
        grbOrgStructure = params.get('grbOrgStructure', False)
        socStatusTypesDict = params.get('socStatusTypes', None)
        socStatusTypes = socStatusTypesDict.keys()
        outcome = params.get('outcom', False)

        orgStructureIdList = []
        if grbOrgStructure:
            orgStructureIndex = self.socStatusSetupDialog.cmbOrgStructure._model.index(
                self.socStatusSetupDialog.cmbOrgStructure.currentIndex(), 0,
                self.socStatusSetupDialog.cmbOrgStructure.rootModelIndex())
            orgStructureIdList = self.getOrgStructureIdList(orgStructureIndex)

        db = QtGui.qApp.db

        doc = QtGui.QTextDocument()
        cursor = QtGui.QTextCursor(doc)

        cursor.setCharFormat(CReportBase.ReportTitle)
        cursor.insertText(u'Социальный статус')
        cursor.insertBlock()
        if groupId:
            statusType = forceString(
                db.translate('rbSocStatusClass', 'id', groupId, 'name '))
            cursor.insertText(u'тип социального статуса: %s\n' % statusType)
        self.dumpParams(cursor, params)
        if statusInPeriod:
            cursor.insertText(u'статус присутствует в периоде\n')
        if statusStart:
            cursor.insertText(u'статус начал действовать в периоде\n')
        if statusFinish:
            cursor.insertText(u'статус прекратил действовать в периоде\n')
        cursor.insertBlock()

        if groupBySocStatus:
            tableColumns = [
                ('2%', [u'№'], CReportBase.AlignRight),
                ('10%', [u'ФИО'], CReportBase.AlignLeft),
                ('2%', [u'пол'], CReportBase.AlignLeft),
                ('8%', [u'д/р'], CReportBase.AlignLeft),
                ('8%', [u'СНИЛС'], CReportBase.AlignLeft),
                ('20%', [u'полис'], CReportBase.AlignLeft),
                ('10%', [u'документ'], CReportBase.AlignLeft),
                ('20%', [u'Адрес'], CReportBase.AlignLeft),
                ('10%', [u'телефон'], CReportBase.AlignLeft),
            ]
        else:
            tableColumns = [
                ('2%', [u'№'], CReportBase.AlignRight),
                ('8%', [u'ФИО'], CReportBase.AlignLeft),
                ('1%', [u'пол'], CReportBase.AlignLeft),
                ('6%', [u'д/р'], CReportBase.AlignLeft),
                ('7%', [u'СНИЛС'], CReportBase.AlignLeft),
                ('20%', [u'полис'], CReportBase.AlignLeft),
                ('9%', [u'документ'], CReportBase.AlignLeft),
                ('20%', [u'Адрес'], CReportBase.AlignLeft),
                ('10%', [u'телефон'], CReportBase.AlignLeft),
                ('20%', [u'класс\nсоц.статуса'], CReportBase.AlignLeft),
                ('20%', [u'тип\nсоц.статуса'], CReportBase.AlignLeft),
            ]
        if addMKB:
            tableColumns.append(
                ('10%', [u'Заболевания'], CReportBase.AlignLeft))
        if addDeathDate:
            tableColumns.append(
                ('10%', [u'Дата смерти'], CReportBase.AlignLeft))

        table = createTable(cursor, tableColumns)
        n = 0
        query = selectData(begDate, endDate, statusInPeriod, statusStart,
                           statusFinish, sex, ageFrom, ageTo, groupId,
                           onlyPermanentAttach, groupBySocStatus,
                           grbOrgStructure, orgStructureIdList,
                           areaAddressType, socStatusTypes, outcome)
        prevSocStatusTypeId = False
        self.setQueryText(forceString(query.lastQuery()))
        while query.next():
            n += 1
            record = query.record()
            clientId = forceRef(record.value('client_id'))
            name = forceString(record.value('lastName')) + ' ' + forceString(
                record.value('firstName')) + ' ' + forceString(
                    record.value('patrName'))
            sex = forceString(record.value('sex'))
            birthDate = forceString(record.value('birthDate'))
            regAddress = forceString(record.value('address'))
            phones = forceString(record.value('contact'))
            SNILS = formatSNILS(forceString(record.value('SNILS')))
            policy = forceString(record.value('policy'))
            serial = forceString(record.value('serial'))
            number = forceString(record.value('number'))
            document = forceString(record.value('document'))
            begDate = forceDate(record.value('begDate'))
            endDate = forceDate(record.value('endDate'))
            #info = getClientInfo(clientId)
            # name = '\n'.join([info['lastName'], info['firstName'], info['patrName']])
            # sex = formatSex(info['sexCode'])
            # birthDate = formatDate(info['birthDate'])
            # regAddress = getVal(info, 'regAddress', u'не указан')
            # phones = getClientPhonesEx(clientId)
            # SNILS=formatSNILS(info['SNILS'])
            #policy=getVal(info, 'policy', u'нет')
            serialAndNumber = '\n'.join([serial, number])
            socStatusTypeId = forceRef(record.value('socStatusType_id'))
            socStatusClassName = forceString(
                record.value('socStatusClassName'))
            socStatusTypeName = forceString(record.value('socStatusTypeName'))
            deathDate = forceString(record.value('deathDate'))
            #document=getVal(info, 'document', u'нет')

            if groupBySocStatus:
                if socStatusTypeId != prevSocStatusTypeId:
                    i = table.addRow()
                    table.mergeCells(i, 0, 1, 9)
                    table.setText(
                        i, 0, socStatusClassName + ': ' + socStatusTypeName,
                        CReportBase.ReportSubTitle, CReportBase.AlignLeft)
                    prevSocStatusTypeId = socStatusTypeId
                    n = 1

            i = table.addRow()
            table.setText(i, 0, n)
            table.setText(i, 1, name)
            table.setText(i, 2, sex)
            table.setText(i, 3, birthDate)
            table.setText(i, 4, SNILS)
            table.setText(i, 5, policy)
            table.setText(i, 6, document)
            table.setText(i, 7, regAddress)
            table.setText(i, 8, phones)
            if not groupBySocStatus:
                table.setText(i, 9, socStatusClassName)
                table.setText(i, 10, socStatusTypeName)
            if addMKB:
                if addDeathDate:
                    decrease = 2
                else:
                    decrease = 1
                strMKB = getMKB(clientId)
                table.setText(i, len(tableColumns) - decrease, strMKB)
            if addDeathDate:
                table.setText(i, len(tableColumns) - 1, deathDate)

        return doc
Exemplo n.º 8
0
    def checkClient(self, clientId):
        loc = UploadServiceLocator()
        tracefile = open(self.tracefilename,
                         'a') if self.tracefilename is not None else None
        port = loc.getUploadServiceSoap(url=(self.url +
                                             '/drugstore/UploadService.asmx'),
                                        tracefile=tracefile,
                                        transdict={'timeout': 5})
        failures = []

        db = self.db
        tableClient = db.table('Client')
        clientRecord = db.getRecord(tableClient, '*', clientId)

        msg = None
        try:
            msg = PersonClientCheckSoapIn()
            msg._clientId = self.clientId
            msg._persons = ns0.ArrayOfPersonClient_Def('_persons')
            person = ns0.PersonClient_Def('_PersonClient')
            msg._persons._PersonClient = [person]

            person._Uploaded = False
            person._PersonFound = False
            if forceString(clientRecord.value('SNILS')):
                person._Snils = formatSNILS(
                    forceString(clientRecord.value('SNILS')))
            else:
                tableFakeSNILS = db.table('ClientFakeSNILS')
                fakeSnilsRecord = db.getRecordEx(tableFakeSNILS,
                                                 '*',
                                                 where='client_id = %d' %
                                                 clientId)
                if fakeSnilsRecord:
                    person._Snils = formatSNILS(
                        forceString(fakeSnilsRecord.value('fakeSNILS')))
                else:
                    person._Firstname = forceString(
                        clientRecord.value('firstName'))
                    person._Lastname = forceString(
                        clientRecord.value('lastName'))
                    person._Patronymic = forceString(
                        clientRecord.value('patrName'))
                    person._Sex = [u'', u'М',
                                   u'Ж'][forceInt(clientRecord.value('sex'))]
                    person._Birthday = self.toDateTuple(
                        forceDateTime(clientRecord.value('birthDate')))

            resp = port.PersonClientCheck(msg)
            if (hasattr(resp._PersonClientCheckResult._PersonClient[0], '_PersonFound') and
                    not resp._PersonClientCheckResult._PersonClient[0]._PersonFound) or \
                    hasattr(resp._PersonClientCheckResult._PersonClient[0], '_Check'):
                return False

            if (hasattr(resp._PersonClientCheckResult._PersonClient[0]),
                    '_PrivilegeDocuments'):
                documents = resp._PersonClientCheckResult._PersonClient[
                    0]._PrivilegeDocuments
                for doc in documents:
                    if (hasattr(doc, '_PrivilegeDocumentDeleted')):
                        tDocuments = self.db.table('ClientDocument')
                        docNumber = forceString(doc._PrivilegeDocumentNumber)
                        docSerial = forceString(doc._PrivilegeDocumentSeria)
                        docEndDate = forceDateTime(
                            doc._PrivilegeDocumentDeleted)
                        recDoc = self.db.getRecordEx(tDocuments, '*', [
                            tDocuments['client_id'].eq(clientId),
                            tDocuments['number'].eq(docNumber),
                            tDocuments['serial'].eq(docSerial)
                        ])
                        if recDoc:
                            if not forceString(docEndDate) == forceString(
                                    recDoc.value('endDate')):
                                recDoc.setValue('endDate', docEndDate)
                                self.db.updateRecord(tDocuments, recDoc)

            return self.checkPrivilege(resp, self.getPrivilege(clientId))

        except Exception as e:
            print e
            return False
Exemplo n.º 9
0
def sendTestHl7OverXml(widget, clientInfo, jobTicketId, laboratory, testCodes,
                       properties):
    import hl7.ORM_O01
    from ZSI import TC
    from aksiSoap import svcHl7Message_client

    now = QtCore.QDateTime.currentDateTime()
    timestamp = now.toTime_t()
    message = hl7.ORM_O01.ORM_O01()
    message.MSH.MSH_1 = '|'
    message.MSH.MSH_2 = '^~\\&'
    message.MSH.MSH_3.HD_1 = u'vista-med'
    message.MSH.MSH_4.HD_1 = laboratory.ownName
    message.MSH.MSH_6.HD_1 = laboratory.labName
    message.MSH.MSH_7.TS_1 = hl7.datetimeToHl7(now)
    message.MSH.MSH_9.MSG_1 = 'ORM'
    message.MSH.MSH_9.MSG_2 = 'O01'
    message.MSH.MSH_9.MSG_3 = 'ORM_O01'
    message.MSH.MSH_10 = idToUuid(timestamp, jobTicketId).hex

    message.MSH.MSH_11.PT_1 = 'D'
    message.MSH.MSH_12.VID_1 = '2.5'
    #message.MSH.MSH_18.append('UNICODE UTF-8')

    message.ORM_O01_PATIENT.PID.PID_3.append()
    message.ORM_O01_PATIENT.PID.PID_3[0].CX_1 = formatSNILS(
        clientInfo['SNILS'])
    message.ORM_O01_PATIENT.PID.PID_3[0].CX_5 = 'XX'
    message.ORM_O01_PATIENT.PID.PID_5.append()
    message.ORM_O01_PATIENT.PID.PID_5[0].XPN_1.FN_1 = clientInfo['lastName']
    message.ORM_O01_PATIENT.PID.PID_5[0].XPN_2 = clientInfo['firstName']
    message.ORM_O01_PATIENT.PID.PID_5[0].XPN_3 = clientInfo['patrName']
    message.ORM_O01_PATIENT.PID.PID_7.TS_1 = hl7.datetimeToHl7(
        clientInfo['birthDate'])
    message.ORM_O01_PATIENT.PID.PID_8 = ['U', 'M', 'F'][clientInfo['sexCode']]

    i = 0
    for property in properties:
        testId = property.type().testId
        if testId in testCodes:
            i += 1
            book, code, name = testCodes[testId]
            propertyRecordId = forceRef(property.getRecord().value('id'))
            id = idToUuid(timestamp, propertyRecordId).hex
            message.ORM_O01_ORDER.append()
            order = message.ORM_O01_ORDER[-1]
            order.ORC.ORC_1 = 'NW'
            order.ORC.ORC_2.EI_3 = id
            order.ORC.ORC_2.EI_4 = 'L'
            order.ORM_O01_ORDER_DETAIL.ORM_O01_OBRRQDRQ1RXOODSODT_SUPPGRP.OBR.OBR_1 = str(
                i)
            order.ORM_O01_ORDER_DETAIL.ORM_O01_OBRRQDRQ1RXOODSODT_SUPPGRP.OBR.OBR_2.EI_3 = id
            order.ORM_O01_ORDER_DETAIL.ORM_O01_OBRRQDRQ1RXOODSODT_SUPPGRP.OBR.OBR_2.EI_4 = 'L'
            order.ORM_O01_ORDER_DETAIL.ORM_O01_OBRRQDRQ1RXOODSODT_SUPPGRP.OBR.OBR_4.CE_1 = code
            order.ORM_O01_ORDER_DETAIL.ORM_O01_OBRRQDRQ1RXOODSODT_SUPPGRP.OBR.OBR_4.CE_2 = name
            order.ORM_O01_ORDER_DETAIL.ORM_O01_OBRRQDRQ1RXOODSODT_SUPPGRP.OBR.OBR_4.CE_3 = book
            order.ORM_O01_ORDER_DETAIL.ORM_O01_OBRRQDRQ1RXOODSODT_SUPPGRP.OBR.OBR_11 = 'L'
            order.ORM_O01_ORDER_DETAIL.ORM_O01_OBRRQDRQ1RXOODSODT_SUPPGRP.OBR.OBR_13 = ''
        else:
            pass  # 'testId' not found

    loc = svcHl7Message_client.svcHl7MessageLocator()
    port = loc.getHl7Message(laboratory.address)
    data = message.toDom()
    data.typecode = TC.XML('NoName', comments=0, inline=1, wrapped=False)
    req = svcHl7Message_client.msgHl7MessageIn()
    req._any = data
    res = QtGui.qApp.callWithWaitCursor(widget, port.opHl7Message, req)
    QtGui.QMessageBox.information(widget, u'Результат', u'Передача успешна',
                                  QtGui.QMessageBox.Close)
Exemplo n.º 10
0
    def build(self, params):
        begDate = params.get('begDate', QtCore.QDate())
        endDate = params.get('endDate', QtCore.QDate())
        eventTypeId = params.get('eventTypeId', None)
        sex = params.get('sex', 0)
        ageFrom = params.get('ageFrom', 0)
        ageTo = params.get('ageTo', 150)
        actionTypeClass = params.get('actionTypeClass', None)
        actionTypeId = params.get('actionTypeId', None)
        onlyPermanentAttach = params.get('onlyPermanentAttach', None)
        MKBFilter = params.get('MKBFilter', 0)
        MKBFrom = params.get('MKBFrom', '')
        MKBTo = params.get('MKBTo', '')
        onlyPayedEvents = params.get('onlyPayedEvents', False)
        begPayDate = params.get('begPayDate', QtCore.QDate())
        endPayDate = params.get('endPayDate', QtCore.QDate())

        db = QtGui.qApp.db

        doc = QtGui.QTextDocument()
        cursor = QtGui.QTextCursor(doc)

        cursor.setCharFormat(CReportBase.ReportTitle)
        cursor.insertText(self.title())
        cursor.insertBlock()
        self.dumpParams(cursor, params)
        cursor.insertBlock()

        tableColumns = [
            ('5%', [u'№ п/п'], CReportBase.AlignRight),
            ('15%', [u'ФИО'], CReportBase.AlignLeft),
            ('5%', [u'д/р'], CReportBase.AlignLeft),
            ('5%', [u'возраст'], CReportBase.AlignLeft),
            ('25%', [u'Адрес'], CReportBase.AlignLeft),
            ('7%', [u'Полис'], CReportBase.AlignCenter),
            ('9%', [u'паспорт'], CReportBase.AlignCenter),
            ('10%', [u'СНИЛС'], CReportBase.AlignLeft),
            ('5%', [u'кабинет'], CReportBase.AlignLeft),
            ('15%', [u'примечение'], CReportBase.AlignLeft),
        ]

        table = createTable(cursor, tableColumns)

        query = selectData(begDate, endDate, eventTypeId, sex, ageFrom, ageTo,
                           actionTypeClass, actionTypeId, onlyPermanentAttach,
                           MKBFilter, MKBFrom, MKBTo, onlyPayedEvents,
                           begPayDate, endPayDate)

        num = 0
        prevActionTypeId = None
        self.setQueryText(forceString(query.lastQuery()))
        while query.next():
            record = query.record()
            fio = formatName(record.value('lastName'),
                             record.value('firstName'),
                             record.value('patrName'))
            birthDate = forceDate(record.value('birthDate'))
            date = forceDate(record.value('date'))
            age = calcAge(birthDate, date)
            address = forceString(record.value('address'))
            policy = ' '.join([
                forceString(record.value('policySerial')),
                forceString(record.value('policyNumber'))
            ])
            document = ' '.join([
                forceString(record.value('documentSerial')),
                forceString(record.value('documentNumber'))
            ])
            SNILS = formatSNILS(record.value('SNILS'))
            office = forceString(record.value('office'))
            note = forceString(record.value('note'))
            row = [
                fio,
                birthDate.toString('dd.MM.yyyy'), age, address, policy,
                document, SNILS, office, note
            ]
            actionTypeId = forceInt(record.value('actionType_id'))
            actionTypeName = forceString(record.value('actionTypeName'))
            if actionTypeId != prevActionTypeId:
                num = 0
                i = table.addRow()
                prevActionTypeId = actionTypeId
                table.mergeCells(i, 0, 1, 10)
                table.setText(i, 0, actionTypeName, CReportBase.ReportSubTitle,
                              CReportBase.AlignLeft)
            i = table.addRow()
            num += 1
            table.setText(i, 0, num)
            for j, val in enumerate(row):
                table.setText(i, j + 1, val)
        return doc
Exemplo n.º 11
0
    def build(self, params):
        begDate = params.get('begDate', QtCore.QDate())
        endDate = params.get('endDate', QtCore.QDate())
        byPeriod = params.get('byPeriod', False)
        doctype = params.get('doctype', 0)
        tempInvalidReason = params.get('tempInvalidReason', None)
        onlyClosed = params.get('onlyClosed', True)
        orgStructureId = params.get('orgStructureId', None)
        personId = params.get('personId', None)
        durationFrom = params.get('durationFrom', 0)
        durationTo = params.get('durationTo', 0)
        sex = params.get('sex', 0)
        ageFrom = params.get('ageFrom', 0)
        ageTo = params.get('ageTo', 150)
        socStatusClassId = params.get('socStatusClassId', None)
        socStatusTypeId = params.get('socStatusTypeId', None)
        MKBFilter = params.get('MKBFilter', 0)
        MKBFrom = params.get('MKBFrom', '')
        MKBTo = params.get('MKBTo', '')
        insuranceOfficeMark = params.get('insuranceOfficeMark', 0)

        db = QtGui.qApp.db
        tbl = db.table('TempInvalid')
        tblDiag = db.table('Diagnosis')
        tblReas = db.table('rbTempInvalidReason')

        doc = QtGui.QTextDocument()
        cursor = QtGui.QTextCursor(doc)

        cursor.setCharFormat(CReportBase.ReportTitle)
        cursor.insertText(self.name)
        cursor.insertBlock()
        self.dumpParams(cursor, params)
        cursor.insertBlock()

        tableColumns = [
            ('5%', [u'№'], CReportBase.AlignRight),
            ('5%', [u'код'], CReportBase.AlignLeft),
            ('20%', [u'ФИО,\nдата рождения (возраст),\nпол'], CReportBase.AlignLeft),
            ('25%', [u'Адрес,\nтелефон'], CReportBase.AlignLeft),
            ('10%', [u'Паспортные данные,\nсерия - номер'], CReportBase.AlignLeft),
            ('10%', [u'СНИЛС,\nполис'], CReportBase.AlignLeft),
            ('5%', [u'Шифр МКБ\nТип'], CReportBase.AlignLeft),
            ('5%', [u'Период'], CReportBase.AlignLeft),
            ('5%', [u'Дней'], CReportBase.AlignRight),
            ('5%', [u'Серия\nНомер'], CReportBase.AlignLeft),
            ('5%', [u'Место работы'], CReportBase.AlignLeft),
        ]

        table = createTable(cursor, tableColumns)
        n = 0
        query = selectData(
            begDate, endDate, byPeriod, doctype, tempInvalidReason, onlyClosed, orgStructureId, personId,
            durationFrom, durationTo, sex, ageFrom, ageTo, socStatusClassId, socStatusTypeId, MKBFilter, MKBFrom,
            MKBTo, insuranceOfficeMark
        )
        self.setQueryText(forceString(query.lastQuery()))
        while query.next():
            n += 1
            sumDuration = 0
            record = query.record()
            clientId = forceRef(record.value('client_id'))
            serial = forceString(record.value('serial'))
            number = forceString(record.value('number'))
            caseBegDate = forceDate(record.value('caseBegDate'))
            #            begDate = forceDate(record.value('begDate'))
            endDate = forceDate(record.value('endDate'))
            duration = forceInt(record.value('duration'))
            MKB = forceString(record.value('MKB'))
            work = forceString(record.value('work'))
            document = forceString(record.value('doc'))
            reasonCode = forceString(record.value('code'))
            prev_id = forceInt(record.value('prev_id'))

            info = getClientInfo(clientId)
            name = formatName(info['lastName'], info['firstName'], info['patrName'])
            nameBDateAndSex = '\n'.join([
                name, '%s (%s)' % (formatDate(info['birthDate']), calcAge(info['birthDate'], begDate)),
                formatSex(info['sexCode'])
            ])
            regAddress = getVal(info, 'regAddress', u'не указан')
            locAddress = getVal(info, 'locAddress', u'не указан')
            phones = getClientPhonesEx(clientId)
            addressAndPhone = regAddress if regAddress else ''
            addressAndPhone += '\n' + locAddress if locAddress else ''
            addressAndPhone += '\n' + phones if phones else ''
            SNILSAndPolicy = '\n'.join([formatSNILS(info['SNILS']), getVal(info, 'policy', u'нет')])
            MKBandType = '\n'.join([MKB, reasonCode])
            period = '\n'.join([forceString(caseBegDate), forceString(endDate)])
            serialAndNumber = '\n'.join([serial, number])

            i = table.addRow()
            table.setText(i, 0, n)
            table.setText(i, 1, clientId)
            table.setText(i, 2, nameBDateAndSex)
            table.setText(i, 3, addressAndPhone)
            table.setText(i, 4, document)
            table.setText(i, 5, SNILSAndPolicy)
            table.setText(i, 6, MKBandType)
            table.setText(i, 7, period)
            table.setText(i, 8, duration)
            table.setText(i, 9, serialAndNumber)
            table.setText(i, 10, work)

            if prev_id and onlyClosed:
                sumDuration += duration
                extraRows = 0
                while prev_id:
                    prev_record = db.getRecordEx(
                        tbl,
                        [
                            tbl['begDate'], tbl['endDate'], tbl['duration'], tbl['serial'], tbl['number'],
                            tbl['prev_id'], tbl['diagnosis_id'], tbl['tempInvalidReason_id']
                        ],
                        [tbl['id'].eq(prev_id), tbl['deleted'].eq(0)]
                    )
                    if prev_record:
                        i = table.addRow()
                        extraRows += 1
                        begDate = forceDate(prev_record.value('begDate'))
                        endDate = forceDate(prev_record.value('endDate'))
                        duration = forceInt(prev_record.value('duration'))
                        serial = forceString(prev_record.value('serial'))
                        number = forceString(prev_record.value('number'))
                        prev_id = forceInt(prev_record.value('prev_id'))
                        diagnosis_id = forceInt(prev_record.value('diagnosis_id'))
                        reason_id = forceInt(prev_record.value('tempInvalidReason_id'))
                        MKB = forceString(db.translate(tblDiag, tblDiag['id'], diagnosis_id, tblDiag['MKB']))
                        reason = forceString(db.translate(tblReas, tblReas['id'], reason_id, tblReas['code']))
                        period = '\n'.join([forceString(begDate), forceString(endDate)])
                        serialAndNumber = '\n'.join([serial, number])
                        table.setText(i, 6, MKB + '\n' + reason)
                        table.setText(i, 7, period)
                        table.setText(i, 8, duration)
                        table.setText(i, 9, serialAndNumber)
                        sumDuration += duration
                i = table.addRow()
                extraRows += 1
                table.setText(i, 7, u'')
                table.setText(i, 8, u'Всего дней: ' + unicode(sumDuration))
                table.mergeCells(i - extraRows, 0, extraRows + 1, 1)
                table.mergeCells(i - extraRows, 1, extraRows + 1, 1)
                table.mergeCells(i - extraRows, 2, extraRows + 1, 1)
                table.mergeCells(i - extraRows, 3, extraRows + 1, 1)
                table.mergeCells(i - extraRows, 4, extraRows + 1, 1)
                table.mergeCells(i - extraRows, 5, extraRows + 1, 1)
                table.mergeCells(i, 6, 1, 2)

        return doc
Exemplo n.º 12
0
Arquivo: Data.py Projeto: dio4/vista_1
    def getPersonItem(self, clientId):
        u"""
        :param clientId: Client.id
        :rtype: PersonItem
        """
        db = self.db
        tableClient = db.table('Client')
        tableDocument = db.table('ClientDocument')
        tableDocumentType = db.table('rbDocumentType')
        tablePolicy = db.table('ClientPolicy')
        tablePolicyKind = db.table('rbPolicyKind')
        tableInsurer = db.table('Organisation').alias('Ins')
        tableInsurerHead = db.table('Organisation').alias('InsHead')

        table = tableClient
        table = table.leftJoin(
            tableDocument, tableDocument['id'].eq(
                db.func.getClientDocumentId(tableClient['id'])))
        table = table.leftJoin(
            tableDocumentType,
            tableDocumentType['id'].eq(tableDocument['documentType_id']))
        table = table.leftJoin(
            tablePolicy, tablePolicy['id'].eq(
                db.func.getClientPolicyId(tableClient['id'], 1)))
        table = table.leftJoin(
            tablePolicyKind,
            tablePolicyKind['id'].eq(tablePolicy['policyKind_id']))
        table = table.leftJoin(
            tableInsurer, tableInsurer['id'].eq(tablePolicy['insurer_id']))
        table = table.leftJoin(
            tableInsurerHead,
            tableInsurerHead['id'].eq(tableInsurer['head_id']))

        cols = [
            tableClient['lastName'], tableClient['firstName'],
            tableClient['patrName'], tableClient['sex'],
            tableClient['birthDate'], tableClient['SNILS'],
            tableDocument['serial'].alias('docSerial'),
            tableDocument['number'].alias('docNumber'),
            tableDocumentType['code'].alias('docType'),
            tablePolicy['serial'].alias('policySerial'),
            tablePolicy['number'].alias('policyNumber'),
            tablePolicyKind['regionalCode'].alias('policyType'),
            db.ifnull(tableInsurerHead['miacCode'],
                      tableInsurer['miacCode']).alias('insurerCode'),
            db.ifnull(tableInsurerHead['OKATO'],
                      tableInsurer['OKATO']).alias('insurerOKATO')
        ]

        rec = self.db.getRecordEx(table, cols, tableClient['id'].eq(clientId))
        if rec:
            policyNumber = forceString(rec.value('policyNumber'))
            policyType = forceInt(rec.value('policyType'))
            return PersonItem(
                lastName=nameCase(forceString(rec.value('lastName'))),
                firstName=nameCase(forceString(rec.value('firstName'))),
                patrName=nameCase(forceString(rec.value('patrName'))),
                sex=forceInt(rec.value('sex')),
                birthDate=forceDate(rec.value('birthDate')),
                SNILS=formatSNILS(forceString(rec.value('SNILS'))),
                docSerial=forceString(rec.value('docSerial')),
                docNumber=forceString(rec.value('docNumber')),
                docType=forceInt(rec.value('docType')),
                policySerial=forceString(rec.value('policySerial')),
                policyNumber=policyNumber,
                policyType=policyType,
                insurerCode=forceString(rec.value('insurerCode')),
                insuranceArea=forceString(rec.value('insurerOKATO')),
            )

        return PersonItem()
Exemplo n.º 13
0
    def toPlanItemList(self, idList):
        u"""
        Персонализированный список лиц, подлежажих проф. мероприятиям
        :param idList: [list of ClientExaminationPlan.id]
        :rtype: list of PlanItem
        """
        db = self.db
        tableAttach = db.table('ClientAttach')
        tableLastAttach = tableAttach.alias('LastAttach')
        tableClientExamPlan = db.table('ClientExaminationPlan')
        tableClient = db.table('Client')
        tableDocument = db.table('ClientDocument')
        tableDocumentType = db.table('rbDocumentType')
        tableEvent = db.table('Event')
        tableEventType = db.table('EventType')
        tableEventProfile = db.table('rbEventProfile')
        tableEventResult = db.table('rbResult')
        tablePolicy = db.table('ClientPolicy')
        tablePolicyKind = db.table('rbPolicyKind')
        tableInsurer = db.table('Organisation').alias('Ins')
        tableInsurerHead = db.table('Organisation').alias('InsHead')

        table = tableClientExamPlan

        table = table.innerJoin(
            tableClient,
            tableClient['id'].eq(tableClientExamPlan['client_id']))
        table = table.leftJoin(
            tableDocument, tableDocument['id'].eq(
                db.func.getClientDocumentId(tableClient['id'])))
        table = table.leftJoin(
            tableDocumentType,
            tableDocumentType['id'].eq(tableDocument['documentType_id']))
        table = table.leftJoin(
            tablePolicy, tablePolicy['id'].eq(
                db.func.getClientPolicyId(tableClient['id'], 1)))
        table = table.leftJoin(
            tablePolicyKind,
            tablePolicyKind['id'].eq(tablePolicy['policyKind_id']))
        table = table.leftJoin(
            tableInsurer, tableInsurer['id'].eq(tablePolicy['insurer_id']))
        table = table.leftJoin(
            tableInsurerHead,
            tableInsurerHead['id'].eq(tableInsurer['head_id']))

        table = table.leftJoin(
            tableLastAttach, tableLastAttach['id'].eqStmt(
                db.selectMax(tableAttach, tableAttach['id'], [
                    tableAttach['client_id'].eq(tableClient['id']),
                    tableAttach['attachType_id'].inlist(
                        self.attachedAttachTypes),
                    tableAttach['endDate'].isNull(),
                    tableAttach['deleted'].eq(0)
                ])))

        table = table.leftJoin(
            tableEvent, tableEvent['id'].eq(tableClientExamPlan['event_id']))
        table = table.leftJoin(
            tableEventType,
            tableEventType['id'].eq(tableEvent['eventType_id']))
        table = table.leftJoin(
            tableEventProfile,
            tableEventProfile['id'].eq(tableEventType['eventProfile_id']))
        table = table.leftJoin(
            tableEventResult,
            tableEventResult['id'].eq(tableEvent['result_id']))

        cols = [
            tableClient['lastName'], tableClient['firstName'],
            tableClient['patrName'], tableClient['sex'],
            tableClient['birthDate'], tableClient['SNILS'],
            tableDocument['serial'].alias('docSerial'),
            tableDocument['number'].alias('docNumber'),
            tableDocumentType['code'].alias('docType'),
            tablePolicy['serial'].alias('policySerial'),
            tablePolicy['number'].alias('policyNumber'),
            tablePolicyKind['regionalCode'].alias('policyType'),
            db.ifnull(tableInsurerHead['miacCode'],
                      tableInsurer['miacCode']).alias('insurerCode'),
            db.ifnull(tableInsurerHead['OKATO'],
                      tableInsurer['OKATO']).alias('insurerOKATO'),
            tableClientExamPlan['id'], tableClientExamPlan['year'],
            tableClientExamPlan['month'], tableClientExamPlan['kind'],
            tableClientExamPlan['category'],
            tableLastAttach['orgStructure_id'].alias('attachOrgStructureId'),
            tableEvent['execDate'],
            tableEventProfile['regionalCode'].alias('eventProfileCode')
        ]
        cond = [tableClientExamPlan['id'].inlist(idList)]

        planItems = []
        for rec in db.iterRecordList(table, cols, cond):
            attachOrgCode, attachSectionCode = CBookkeeperCode.getOrgCode(
                forceRef(rec.value('attachOrgStructureId')))
            person = PersonItem(
                lastName=nameCase(forceString(rec.value('lastName'))),
                firstName=nameCase(forceString(rec.value('firstName'))),
                patrName=nameCase(forceString(rec.value('patrName'))),
                sex=forceInt(rec.value('sex')),
                birthDate=forceDate(rec.value('birthDate')),
                SNILS=formatSNILS(forceString(rec.value('SNILS'))),
                docSerial=forceString(rec.value('docSerial')),
                docNumber=forceString(rec.value('docNumber')),
                docType=forceInt(rec.value('docType')),
                policySerial=forceString(rec.value('policySerial')),
                policyNumber=forceString(rec.value('policyNumber')),
                policyType=forceInt(rec.value('policyType')),
                insurerCode=forceString(rec.value('insurerCode')),
                insuranceArea=forceString(rec.value('insurerOKATO')),
            )
            planItem = PlanItem(rid=forceRef(rec.value('id')),
                                kind=forceInt(rec.value('kind')),
                                year=forceInt(rec.value('year')),
                                month=forceInt(rec.value('month')),
                                category=forceInt(rec.value('category')),
                                orgCode=attachOrgCode,
                                sectionCode=attachSectionCode,
                                person=person)
            planItems.append(planItem)

        return planItems
Exemplo n.º 14
0
    def toFactExecList(self, idList):
        u"""
        Список проведенных проф. мероприятий
        :param idList: [list of ClientExaminationPlan.id]
        :rtype: list of FactExec
        """
        db = self.db
        tableClient = db.table('Client')
        tableClientExamPlan = db.table('ClientExaminationPlan')
        tableDocument = db.table('ClientDocument')
        tableDocumentType = db.table('rbDocumentType')
        tableEvent = db.table('Event')
        tableOrganisation = db.table('Organisation')
        tableInsurer = db.table('Organisation').alias('Ins')
        tableInsurerHead = db.table('Organisation').alias('InsHead')
        tablePolicy = db.table('ClientPolicy')
        tablePolicyKind = db.table('rbPolicyKind')

        table = tableClientExamPlan
        table = table.innerJoin(
            tableClient,
            tableClient['id'].eq(tableClientExamPlan['client_id']))
        table = table.leftJoin(
            tableDocument, tableDocument['id'].eq(
                db.func.getClientDocumentId(tableClient['id'])))
        table = table.leftJoin(
            tableDocumentType,
            tableDocumentType['id'].eq(tableDocument['documentType_id']))
        table = table.leftJoin(
            tablePolicy, tablePolicy['id'].eq(
                db.func.getClientPolicyId(tableClient['id'], 1)))
        table = table.leftJoin(
            tablePolicyKind,
            tablePolicyKind['id'].eq(tablePolicy['policyKind_id']))
        table = table.leftJoin(
            tableInsurer, tableInsurer['id'].eq(tablePolicy['insurer_id']))
        table = table.leftJoin(
            tableInsurerHead,
            tableInsurerHead['id'].eq(tableInsurer['head_id']))
        table = table.leftJoin(
            tableEvent, tableEvent['id'].eq(tableClientExamPlan['event_id']))
        table = table.leftJoin(
            tableOrganisation,
            tableOrganisation['id'].eq(tableEvent['org_id']))

        cols = [
            tableClientExamPlan['id'], tableClientExamPlan['year'],
            tableClientExamPlan['month'], tableClientExamPlan['kind'],
            tableClientExamPlan['category'], tableClientExamPlan['step'],
            tableClientExamPlan['date'], tableClient['lastName'],
            tableClient['firstName'], tableClient['patrName'],
            tableClient['sex'], tableClient['birthDate'], tableClient['SNILS'],
            tableDocument['serial'].alias('docSerial'),
            tableDocument['number'].alias('docNumber'),
            tableDocumentType['code'].alias('docType'),
            tablePolicy['serial'].alias('policySerial'),
            tablePolicy['number'].alias('policyNumber'),
            tablePolicyKind['regionalCode'].alias('policyType'),
            db.ifnull(tableInsurerHead['miacCode'],
                      tableInsurer['miacCode']).alias('insurerCode'),
            db.ifnull(tableInsurerHead['OKATO'],
                      tableInsurer['OKATO']).alias('insurerOKATO'),
            tableOrganisation['infisCode'].alias('orgCode')
        ]
        cond = [tableClientExamPlan['id'].inlist(idList)]

        factExecs = []
        for rec in db.iterRecordList(table, cols, cond):
            person = PersonItem(
                lastName=nameCase(forceString(rec.value('lastName'))),
                firstName=nameCase(forceString(rec.value('firstName'))),
                patrName=nameCase(forceString(rec.value('patrName'))),
                sex=forceInt(rec.value('sex')),
                birthDate=forceDate(rec.value('birthDate')),
                SNILS=formatSNILS(forceString(rec.value('SNILS'))),
                docSerial=forceString(rec.value('docSerial')),
                docNumber=forceString(rec.value('docNumber')),
                docType=forceInt(rec.value('docType')),
                policySerial=forceString(rec.value('policySerial')),
                policyNumber=forceString(rec.value('policyNumber')),
                policyType=forceInt(rec.value('policyType')),
                insurerCode=forceString(rec.value('insurerCode')),
                insuranceArea=forceString(rec.value('insurerOKATO')),
            )
            factExec = FactExec(rid=forceRef(rec.value('id')),
                                orgCode=forceString(rec.value('orgCode'))
                                or self.orgCode,
                                date=forceDate(rec.value('date')),
                                step=forceInt(rec.value('step')),
                                person=person)
            factExecs.append(factExec)

        return factExecs
Exemplo n.º 15
0
    def _load(self):
        db = QtGui.qApp.db
        tablePerson = db.table('Person')
        record = db.getRecord(tablePerson, '*', self.personId)
        if record:
            self._code = forceString(record.value('code'))
            self._federalCode = forceString(record.value('federalCode'))
            self._regionalCode = forceString(record.value('regionalCode'))
            self._lastName = forceString(record.value('lastName'))
            self._firstName = forceString(record.value('firstName'))
            self._patrName = forceString(record.value('patrName'))
            self._sexCode = forceInt(record.value('sex'))
            self._sex = formatSex(self._sexCode)
            self._birthDate = CDateInfo(record.value('birthDate'))
            self._birthPlace = forceString(record.value('birthPlace'))
            self._ageTuple = calcAgeTuple(self._birthDate.date,
                                          QtCore.QDate.currentDate())
            self._age = formatAgeTuple(self._ageTuple, self._birthDate.date,
                                       QtCore.QDate.currentDate())
            self._SNILS = formatSNILS(forceString(record.value('SNILS')))
            self._office = forceString(record.value('office'))
            self._office2 = forceString(record.value('office2'))

            self._post = self.getInstance(CPostInfo,
                                          forceRef(record.value('post_id')))
            self._speciality = self.getInstance(
                CSpecialityInfo, forceRef(record.value('speciality_id')))
            self._organisation = self.getInstance(
                COrgInfo, forceRef(record.value('org_id')))
            self._orgStructure = self.getInstance(
                COrgStructureInfo, forceRef(record.value('orgStructure_id')))
            self._academicDegree = forceInt(record.value('academicDegree'))
            self._tariffCategory = self.getInstance(
                CTariffCategoryInfo,
                forceRef(record.value('tariffCategory_id')))
            self._login = forceString(record.value('login'))

            self._maritalStatus = forceInt(record.value('maritalStatus'))
            self._contactNumber = forceString(record.value('contactNumber'))
            self._regType = forceInt(record.value('regType'))
            self._regBegDate = forceDate(record.value('regBegDate'))
            self._regEndDate = forceDate(record.value('regEndDate'))
            self._isReservist = forceInt(record.value('isReservist'))
            self._employmentType = forceInt(record.value('employmentType'))
            self._occupationType = forceInt(record.value('occupationType'))
            self._citizenship_id = forceInt(record.value('citizenship_id'))
            self._education = self.getInstance(CPersonEducationItemInfoList,
                                               self.personId)

            self._INN = forceString(record.value('INN'))
            self._document = self.getInstance(CPersonDocumentInfo,
                                              self.personId)
            self._addressRegistry = self.getInstance(
                CPersonAddressRegistryInfoList, self.personId)
            self._addressResidentional = self.getInstance(
                CPersonAddressResidentionalInfoList, self.personId)
            self._finance_id = forceInt(record.value('finance_id'))
            self._awards = self.getInstance(CPersonAwardsInfoList,
                                            self.personId)

            return True
        else:
            return False