示例#1
0
    def setClientId(self, clientId):
        self.clientId = clientId
        if clientId:
            if u'онко' in forceString(QtGui.qApp.db.translate('Organisation', 'id', QtGui.qApp.currentOrgId(), 'infisCode')):
                vipRecord = QtGui.qApp.db.getRecordEx(
                    QtGui.qApp.db.table('ClientVIP'),
                    [
                        QtGui.qApp.db.table('ClientVIP')['client_id'],
                        QtGui.qApp.db.table('ClientVIP')['color']
                    ],
                    [
                        QtGui.qApp.db.table('ClientVIP')['deleted'].eq(0),
                        QtGui.qApp.db.table('ClientVIP')['client_id'].eq(self.clientId)
                    ]
                )

                self.isVipClient = forceBool(vipRecord);
                if self.isVipClient:
                    self.vipColor = forceString(vipRecord.value('color'))

            self.txtClientInfoBrowser.setHtml(getClientBanner(clientId))
            self.checkVipPerson(self.txtClientInfoBrowser)
            db = QtGui.qApp.db
            table = db.table('Client')
            record = db.getRecord(table, 'sex, birthDate', clientId)
            if record:
                self.clientSex = forceInt(record.value('sex'))
                self.clientBirthDate = forceDate(record.value('birthDate'))
                self.clientAge = calcAgeTuple(self.clientBirthDate, self.date)
        else:
            self.txtClientInfoBrowser.setText('')
示例#2
0
 def setClientInfo(self, clientId, eventDate):
     self.clientId = clientId
     self.eventDate = eventDate
     db = QtGui.qApp.db
     table = db.table('Client')
     record = db.getRecord(table, 'sex, birthDate', clientId)
     if record:
         self.clientSex = forceInt(record.value('sex'))
         self.clientBirthDate = forceDate(record.value('birthDate'))
         self.clientAge = calcAgeTuple(self.clientBirthDate, eventDate)
         if not self.clientAge:
             self.clientAge = (0, 0, 0, 0)
示例#3
0
    def __init__(self, parent, eventId):
        QtCore.QObject.__init__(self, parent)
        db = QtGui.qApp.db
        self._parent = parent
        self._id = eventId
        self._record = db.getRecord('Event', '*', eventId)

        self.eventTypeId = forceRef(self._record.value('eventType_id'))
        self.eventSetDateTime = forceDateTime(self._record.value('setDate'))
        self.eventDate = forceDate(self._record.value('execDate'))
        self.personId = forceRef(self._record.value('setPerson_id'))
        orgId = forceRef(self._record.value('org_id'))
        self.orgId = orgId if orgId else QtGui.qApp.currentOrgId()
        self.personSpecialityId = forceRef(db.translate('Person', 'id', self.personId, 'speciality_id'))

        self.contractId = forceRef(self._record.value('contract_id'))
        if self.contractId:
            self.eventFinanceId = forceRef(db.translate('Contract', 'id', self.contractId, 'finance_id'))
        else:
            self.eventFinanceId = getEventFinanceId(self.eventTypeId)

        self.clientId = forceRef(self._record.value('client_id'))
        self.clientInfo = getClientInfo(self.clientId)
        try:
            clientKLADRCode = self.clientInfo.regAddressInfo.KLADRCode
        except:
            clientKLADRCode = ''
        if KLADRMatch(clientKLADRCode, QtGui.qApp.defaultKLADR()):
            self.clientType = CFakeEventEditor.ctLocal
        elif KLADRMatch(clientKLADRCode, QtGui.qApp.provinceKLADR()):
            self.clientType = CFakeEventEditor.ctProvince
        else:
            self.clientType = CFakeEventEditor.ctOther
        self.clientSex = self.clientInfo.sexCode
        self.clientBirthDate = self.clientInfo.birthDate
        self.clientAge = calcAgeTuple(self.clientBirthDate, self.eventDate)

        workRecord = getClientWork(self.clientId)
        self.clientWorkOrgId = forceRef(workRecord.value('org_id')) if workRecord else None

        self.clientPolicyInfoList = []
        policyRecord = self.clientInfo.compulsoryPolicyRecord
        if policyRecord:
            self.clientPolicyInfoList.append(self.getPolicyInfo(policyRecord))
        policyRecord = self.clientInfo.voluntaryPolicyRecord
        if policyRecord:
            self.clientPolicyInfoList.append(self.getPolicyInfo(policyRecord))

        self.personCache = {}
        self.contractTariffCache = CContractTariffCache()
示例#4
0
 def setClientInfo(self, clientId, eventDate):
     db = QtGui.qApp.db
     table  = db.table('Client')
     record = db.getRecord(table, 'lastName, firstName, patrName, sex, birthDate', clientId)
     if record:
         lastName  = record.value('lastName')
         firstName = record.value('firstName')
         partName  = record.value('patrName')
         self.__clientName      = formatName(lastName, firstName, partName)
         self.__clientSex       = forceInt(record.value('sex'))
         self.__clientBirthDate = forceDate(record.value('birthDate'))
         self.__clientAge       = calcAgeTuple(self.__clientBirthDate, eventDate)
         if not self.__clientAge:
             self.__clientAge = (0, 0, 0, 0)
         
         self.setClientWorkHurtCodeList(clientId)
         self.setClientWorkHurtFactorCodeList(clientId)
示例#5
0
 def update(cls, action):
     actionRecord = action.getRecord()
     eventId = forceRef(actionRecord.value('event_id'))
     actionId = forceRef(actionRecord.value('id'))
     if eventId not in cls.existsEventIdList:
         cls.existsEventIdList.append(eventId)
         db = QtGui.qApp.db
         clientId = forceRef(db.translate('Event', 'id', eventId, 'client_id'))
         clientRecord = db.getRecord('Client', '*', clientId)
         if clientRecord:
             directionDate = forceDate(actionRecord.value('directionDate'))
             clientSex = forceInt(clientRecord.value('sex'))
             clientBirthDate = forceDate(clientRecord.value('birthDate'))
             clientAge = calcAgeTuple(clientBirthDate, directionDate)
         else:
             clientSex = clientAge = None
         cls.cache[actionId] = (clientSex, clientAge)
         cls.cacheByEventId[eventId] = (clientSex, clientAge)
     else:
         cls.cache[actionId] = cls.cacheByEventId[eventId]
示例#6
0
    def getContract(self, eventRec, clientRec=None):
        eventTypeId = forceRef(eventRec.value('eventType_id'))
        financeId = getEventFinanceId(eventTypeId)
        setDate = forceDate(eventRec.value('setDate'))
        execDate = forceDate(eventRec.value('execDate'))
        clientId = forceRef(eventRec.value('client_id'))
        clientPolicyId = forceRef(eventRec.value('clientPolicy_id'))
        orgId = forceRef(eventRec.value('org_id'))

        self.contractModel.setOrgId(orgId)
        self.contractModel.setCheckMaxClients(True)
        self.contractModel.setBegDate(setDate)
        self.contractModel.setEndDate(execDate)
        self.contractModel.setEventTypeId(eventTypeId)
        self.contractModel.setFinanceId(financeId)

        if clientId:
            clientSex = forceInt(clientRec.value('sex'))
            clientAge = calcAgeTuple(forceDate(clientRec.value('birthDate')),
                                     setDate)
            clientWorkRecord = getClientWork(clientId)
            clientWorkOrgId = forceRef(
                clientWorkRecord.value('org_id')) if clientWorkRecord else None

            policyRec = self.db.getRecord('ClientPolicy',
                                          'insurer_id, policyType_id',
                                          clientPolicyId)
            insurerId, policyTypeId = (
                forceRef(policyRec.value('insurer_id')),
                forceRef(
                    policyRec.value('policyType_id'))) if policyRec else (None,
                                                                          None)
            clientPolicyInfoList = [(insurerId, policyTypeId)]

            self.contractModel.setClientInfo(clientId, clientSex, clientAge,
                                             clientWorkOrgId,
                                             clientPolicyInfoList)

        self.contractData.select(self.contractModel)

        return self.contractData.idList[0] if self.contractData.idList else None
    def createAttaches(self):
        self.logBrowser.append(u'Начинаем процесс прикрепления\n')
        self.logBrowser.append(u'Определение параметров\n')
        self.getRBNetValues()
        orgStructureIdList = self.getOrgStructureIdList(
            self.cmbOrgStructure._model.index(
                self.cmbOrgStructure.currentIndex(), 0,
                self.cmbOrgStructure.rootModelIndex()))
        areaAddressType = self.cmbAreaAddressType.currentIndex()
        self.attachByNet = self.cmbAttachBy.currentIndex() in [0, 1]
        self.attachByAreaType = self.cmbAttachBy.currentIndex() in [0, 2]
        db = QtGui.qApp.db
        tableOrgStructureAddress = db.table('OrgStructure_Address')
        tableOrgStructure = db.table('OrgStructure')
        tableClient = db.table('Client')
        tableClientAttach = db.table('ClientAttach')
        tableAttachType = db.table('rbAttachType')
        tableClientAddress = db.table('ClientAddress')
        tableAddress = db.table('Address')

        houseIdList = db.getDistinctIdList(
            tableOrgStructureAddress, tableOrgStructureAddress['house_id'],
            [tableOrgStructureAddress['master_id'].inlist(orgStructureIdList)])

        cols = [
            tableOrgStructureAddress['master_id'],
            tableOrgStructureAddress['house_id'],
            tableOrgStructure['organisation_id'], tableOrgStructure['net_id'],
            tableOrgStructure['isArea'], tableOrgStructure['parent_id']
        ]
        records = db.getRecordList(
            tableOrgStructureAddress.innerJoin(
                tableOrgStructure, tableOrgStructureAddress['master_id'].eq(
                    tableOrgStructure['id'])), cols,
            [tableOrgStructureAddress['house_id'].inlist(houseIdList)])
        houseIdList = {}
        for record in records:
            houseMasterInfoList = {}
            masterId = forceRef(record.value('master_id'))
            houseMasterInfoList['masterId'] = masterId
            houseId = forceRef(record.value('house_id'))
            houseMasterInfoList['houseId'] = houseId
            parentId = forceRef(record.value('parent_id'))
            houseMasterInfoList['parentId'] = parentId
            houseMasterInfoList['organisationId'] = forceRef(
                record.value('organisation_id'))
            houseMasterInfoList['isArea'] = forceInt(record.value('isArea'))
            netId = forceRef(record.value('net_id'))
            while parentId and not netId:
                recordParent = db.getRecordEx(tableOrgStructure, [
                    tableOrgStructure['parent_id'], tableOrgStructure['net_id']
                ], [
                    tableOrgStructure['id'].eq(parentId),
                    tableOrgStructure['deleted'].eq(0)
                ])
                if recordParent:
                    netId = forceRef(recordParent.value('net_id'))
                    parentId = forceRef(recordParent.value('parent_id'))
            houseMasterInfoList['netId'] = netId
            masterInfoList = houseIdList.get(houseId, {})
            if masterId not in masterInfoList.keys():
                masterInfoList[masterId] = houseMasterInfoList
                houseIdList[houseId] = masterInfoList

        self.logBrowser.append(u'Получение людей, которые будут прикреплены\n')
        clientsStmt = u'''
            SELECT DISTINCT
                Client.id
            FROM
                Address
                INNER JOIN ClientAddress ON ClientAddress.address_id = Address.id
                INNER JOIN Client ON Client.id = ClientAddress.client_id
            WHERE
                %s
        '''
        clientsCond = [
            tableAddress['house_id'].inlist(houseIdList.keys()),
            tableAddress['deleted'].eq(0), tableClientAddress['deleted'].eq(0),
            tableClientAddress['type'].eq(areaAddressType),
            'NOT EXISTS (SELECT ClientAttach.id FROM ClientAttach INNER JOIN rbAttachType ON rbAttachType.id = ClientAttach.attachType_id WHERE ClientAttach.id = (SELECT MAX(ClientAttachTemp.id) FROM ClientAttach AS ClientAttachTemp WHERE ClientAttachTemp.client_id = ClientAddress.client_id) AND rbAttachType.outcome = 1)'
        ]
        if self.cmbSex.currentIndex() != 0:
            clientsCond.append(tableClient['sex'].eq(
                self.cmbSex.currentIndex()))
        if self.cmbAge.currentIndex() != 0:
            clientsCond.append(u'age(Client.birthDate, DATE(NOW()))' + (
                u' < ' if self.cmbAge.currentIndex() == 1 else u' >= ') +
                               u'18')
        query = db.query(clientsStmt % db.joinAnd(clientsCond))
        clientIdList = []
        while query.next():
            clientIdList.append(forceRef(query.record().value('id')))

        currentDate = QtCore.QDate.currentDate()
        cols = [
            tableClient['birthDate'], tableClient['sex'],
            tableClientAttach['id'].alias('clientAttachId'),
            tableClientAttach['client_id'],
            tableClientAttach['orgStructure_id'], tableAddress['house_id']
        ]
        #cols.append(u'age(Client.birthDate, %s) AS clientAge'%(db.formatDate(currentDate)))
        if self.chkAttach.isChecked():
            # Учитывать тип прикрепления "прикрепление":
            # (территориал или прикрепление) и (подразделение не указано или указано одно из тех, на которые надо прикрепить) -> 1 (заполнить найденное прикрепление)
            # иначе, если тип прикрепления не территориал и не прикрепление -> 2 (добавить новое прикрепление)
            # иначе 0 (ничего не делать)
            cols.append(
                u'IF((rbAttachType.code = 1 OR rbAttachType.code = 2) AND (ClientAttach.orgStructure_id IS NULL OR ClientAttach.orgStructure_id NOT IN (%s)), 1, IF(rbAttachType.code NOT IN (\'1\', \'2\'),2,0)) AS attachCode'
                % (u','.join(
                    str(orgStructureId)
                    for orgStructureId in orgStructureIdList
                    if orgStructureId)))
        else:
            # Не учитывать ип прикрепления "прикрепление":
            # территориал и (подразделение не указано или указано одно из тех, на которые надо прикрепить) или (прикрепление и подразделение не указано) -> 1 (заполнить найденное прикрепление)
            cols.append(
                u'IF((rbAttachType.code = 1 AND (ClientAttach.orgStructure_id IS NULL OR ClientAttach.orgStructure_id NOT IN (%s))) OR (rbAttachType.code = 2 AND ClientAttach.orgStructure_id IS NULL), 1, IF(rbAttachType.code NOT IN (\'1\', \'2\'),2,0)) AS attachCode'
                % (u','.join(
                    str(orgStructureId)
                    for orgStructureId in orgStructureIdList
                    if orgStructureId)))

        self.logBrowser.append(u'Будет прикреплено %i человек\n' %
                               len(clientIdList))
        self.progressBar.setMaximum(len(clientIdList))
        i = 0
        for clientId in clientIdList:
            i += 1
            self.progressBar.setValue(i)
            QtGui.qApp.processEvents()
            if self.stopped: break

            cond = [
                tableClientAttach['client_id'].eq(clientId),
                tableClientAttach['deleted'].eq(0),
                tableClient['deleted'].eq(0), tableAddress['deleted'].eq(0),
                tableClientAddress['type'].eq(areaAddressType)
            ]
            table = tableClientAttach.leftJoin(
                tableAttachType,
                tableClientAttach['attachType_id'].eq(tableAttachType['id']))
            table = table.leftJoin(
                tableClient,
                tableClientAttach['client_id'].eq(tableClient['id']))
            table = table.innerJoin(
                tableClientAddress,
                tableClientAddress['client_id'].eq(tableClient['id']))
            table = table.innerJoin(
                tableAddress,
                tableClientAddress['address_id'].eq(tableAddress['id']))
            record = db.getRecordEx(
                table, cols, cond,
                u'ClientAttach.begDate DESC, ClientAddress.id DESC')
            if record:
                attachCode = forceInt(record.value('attachCode'))
                clientAttachId = forceRef(record.value('clientAttachId'))
                houseId = forceRef(record.value('house_id'))
                ageTuple = calcAgeTuple(forceDate(record.value('birthDate')),
                                        currentDate)
                sex = forceInt(record.value('sex'))
                #clientAge = forceInt(record.value('clientAge'))
                if attachCode:
                    masterId, organisationId = self.getMasterIdOrganisationId(
                        houseIdList, houseId, ageTuple, sex)
                    if masterId:
                        if attachCode == 1:
                            newRecord = db.getRecordEx(
                                tableClientAttach, '*',
                                [tableClientAttach['id'].eq(clientAttachId)])
                            newRecord.setValue('orgStructure_id',
                                               QtCore.QVariant(masterId))
                            newRecord.setValue('LPU_id',
                                               QtCore.QVariant(organisationId))
                            newRecord.setValue('begDate',
                                               toVariant(currentDate))
                            db.updateRecords(
                                tableClientAttach, newRecord,
                                [tableClientAttach['id'].eq(clientAttachId)])
                        elif attachCode == 2:
                            newRecord = tableClientAttach.newRecord()
                            newRecord.setValue('client_id',
                                               QtCore.QVariant(clientId))
                            newRecord.setValue('attachType_id',
                                               QtCore.QVariant(1))
                            newRecord.setValue('LPU_id',
                                               QtCore.QVariant(organisationId))
                            newRecord.setValue('orgStructure_id',
                                               QtCore.QVariant(masterId))
                            newRecord.setValue('begDate',
                                               toVariant(currentDate))
                            db.insertRecord(tableClientAttach, newRecord)
            else:
                cols = [
                    tableClient['birthDate'],
                    tableAddress['house_id'],
                    tableClient['sex'],
                ]
                #cols.append(u'age(Client.birthDate, %s) AS clientAge'%(db.formatDate(currentDate)))
                cond = [
                    tableClient['id'].eq(clientId),
                    tableClient['deleted'].eq(0),
                    tableAddress['house_id'].inlist(houseIdList.keys()),
                    tableAddress['deleted'].eq(0),
                    tableClientAddress['type'].eq(areaAddressType)
                ]
                table = tableClient.innerJoin(
                    tableClientAddress,
                    tableClientAddress['client_id'].eq(tableClient['id']))
                table = table.innerJoin(
                    tableAddress,
                    tableClientAddress['address_id'].eq(tableAddress['id']))
                recordClient = db.getRecordEx(table, cols, cond,
                                              u'ClientAddress.id DESC')
                if recordClient:
                    ageTuple = calcAgeTuple(
                        forceDate(recordClient.value('birthDate')),
                        currentDate)
                    sex = forceInt(recordClient.value('sex'))
                    #clientAge = forceInt(recordClient.value('clientAge'))
                    houseId = forceRef(recordClient.value('house_id'))
                    masterId, organisationId = self.getMasterIdOrganisationId(
                        houseIdList, houseId, ageTuple, sex)
                    newRecord = tableClientAttach.newRecord()
                    newRecord.setValue('client_id', QtCore.QVariant(clientId))
                    newRecord.setValue('attachType_id', QtCore.QVariant(1))
                    newRecord.setValue('LPU_id',
                                       QtCore.QVariant(organisationId))
                    newRecord.setValue('orgStructure_id',
                                       QtCore.QVariant(masterId))
                    newRecord.setValue('begDate', toVariant(currentDate))
                    db.insertRecord(tableClientAttach, newRecord)

        self.logBrowser.append(u'Прикрепление прошло успешно\n\n')
        self.modelTable.clearCache()
        self.updateOrgStructureTable()
示例#8
0
 def updateClientInfo(self):
     self.clientInfo = getClientInfo(self.clientId)
     self.txtClientInfoBrowser.setHtml(formatClientBanner(self.clientInfo))
     self.clientSex = self.clientInfo.sexCode
     self.clientBirthDate = self.clientInfo.birthDate
     self.clientAge = calcAgeTuple(self.clientBirthDate, self.edtDirectionDate.date())
示例#9
0
def checkDatesRegardToClientLife(widget, clientId, eventSetDate, eventDate,
                                 eventTypeId):
    result = True
    if clientId:
        db = QtGui.qApp.db
        birthDate = forceDate(
            db.translate('Client', 'id', clientId, 'birthDate'))
        deathDate = getDeathDate(clientId)
        possibleDeathDate = birthDate.addYears(QtGui.qApp.maxLifeDuration)
        if birthDate:
            postmortem = isEventDeath(eventTypeId)
            if eventSetDate:
                result = result and (eventSetDate >= birthDate or confirmTrouble(
                    widget,
                    u'Дата назначения %s не должна быть раньше даты рождения пациента %s'
                    % (forceString(eventSetDate), forceString(birthDate))))
                if deathDate:
                    result = result and (
                        eventSetDate <= deathDate or postmortem
                        or confirmTrouble(
                            widget,
                            u'Дата назначения %s не должна быть позже имеющейся даты смерти пациента %s'
                            % (forceString(eventSetDate),
                               forceString(deathDate))))
                else:
                    result = result and (
                        eventSetDate <= possibleDeathDate or postmortem
                        or confirmTrouble(
                            widget,
                            u'Дата назначения %s не должна быть позже возможной даты смерти пациента %s'
                            % (forceString(eventSetDate),
                               forceString(possibleDeathDate))))

                ageConstraint = forceString(
                    db.translate('EventType', 'id', eventTypeId, 'age'))
                ageConstraint = parseAgeSelector(ageConstraint, isExtend=True)
                clientAge = calcAgeTuple(birthDate, eventSetDate)
                ageResult = False
                if QtGui.qApp.region() == u'91':
                    eventTypeCode = getEventCode(eventTypeId)
                    ageResult = (QtGui.qApp.region() == u'91'
                                 and eventTypeCode.lower() in [u'дв1', u'дв2']
                                 and hasSocStatus(
                                     clientId,
                                     {'specialCase': ['10', '11', '12']}))
                if not ageResult:
                    for ageSelector in ageConstraint:
                        begUnit, begCount, endUnit, endCount, step, useCalendarYear, useExclusion = ageSelector
                        checkClientAge = clientAge
                        if useCalendarYear and isinstance(
                                checkClientAge, CAgeTuple):
                            checkClientAge = CAgeTuple(
                                (checkClientAge[0],
                                 checkClientAge[1], checkClientAge[2],
                                 eventSetDate.year() - birthDate.year()),
                                birthDate, eventSetDate)
                        ageResult = checkAgeSelector(
                            (begUnit, begCount, endUnit, endCount),
                            checkClientAge)
                        if ageResult:
                            if step:
                                unit = begUnit if begUnit else endUnit
                                if (checkClientAge[unit - 1] -
                                        begCount) % step != 0:
                                    ageResult = False
                            if ageResult:
                                ageResult = not useExclusion
                                break

                if clientAge and ageConstraint and not ageResult:
                    result = result and confirmTrouble(
                        widget,
                        u'Возраст пациента не подходит для создания обращения данного типа'
                    )

            if eventDate:
                result = result and (eventDate >= birthDate or confirmTrouble(
                    widget,
                    u'Дата выполнения (окончания) %s не должна быть раньше даты рождения пациента %s'
                    % (forceString(eventDate), forceString(birthDate))))
                if deathDate:
                    result = result and (
                        eventDate <= deathDate or postmortem or confirmTrouble(
                            widget,
                            u'Дата выполнения (окончания) %s не должна быть позже имеющейся даты смерти пациента %s'
                            %
                            (forceString(eventDate), forceString(deathDate))))
                else:
                    result = result and (
                        eventDate <= possibleDeathDate or postmortem
                        or confirmTrouble(
                            widget,
                            u'Дата выполнения (окончания) %s не должна быть позже возможной даты смерти пациента %s'
                            % (forceString(eventDate),
                               forceString(possibleDeathDate))))
    return result
示例#10
0
 def check(self):
     global EventTypes
     db=QtGui.qApp.db
     my_orgId=QtGui.qApp.currentOrgId()
     checkExt=self.checkExt.isChecked()
     checkSetPerson=self.checkSetPerson.isChecked()
     checkPolis=self.checkPolis.isChecked()
     n=0
     q='''
         select
             Event.id as event_id, Event.externalId,
             Event.org_id as event_org_id, Event.contract_id,
             Event.setDate, Event.setPerson_id, Event.execDate, Event.execPerson_id,
             Event.result_id, Event.eventType_id,
             Client.id as client_id, Client.birthDate, Client.sex,
             Client.lastName, Client.firstName, Client.patrName
         from
             Event
             join Client on Client.id=Event.client_id
         where
             1
         '''
     date1=forceString(self.dateEdit_1.date().toString('yyyy-MM-dd'))
     date2=forceString(self.dateEdit_2.date().toString('yyyy-MM-dd'))
     q+=' and (Event.execDate between "'+date1+'" and "'+date2+'")'
     EventTypes=self.tblEventType.values()
     if EventTypes:
         q+=' and Event.eventType_id in ('+', '.join([str(et) for et in EventTypes])+')'
     if self.checkPayed.isChecked():
         q+=' and isEventPayed(Event.id)'
     query=db.query(q)
     query.setForwardOnly(True)
     n=0
     n_bad=0
     s=query.size()
     if s>0:
         self.progressBar.setMaximum(s-1)
     while query.next():
         QtGui.qApp.processEvents()
         if self.abort: break
         self.progressBar.setValue(n)
         n+=1
         self.item_bad=False
         record=query.record()
         def val(name): return record.value(name)
         eventId=forceInt(val('event_id'))
         self.eventId=eventId
         self.itemId=eventId
         clientId=forceInt(val('client_id'))
         lastName=forceString(val('lastName'))
         firstName=forceString(val('firstName'))
         patrName=forceString(val('patrName'))
         fio=lastName+' '+firstName+' '+patrName
         birthDate=forceDate(val('birthDate'))
         sex=forceInt(val('sex'))
         setDate=forceDate(val('setDate'))
         execDate=forceDate(val('execDate'))
         self.err_str='client '+forceString(clientId)+' ('+fio+', '+forceString(birthDate.toString('dd.MM.yyyy'))+') event '+forceString(execDate.toString('dd.MM.yyyy'))+' '
         if checkPolis:
             self.checkPolicy(clientId, setDate, execDate)
         externalId=forceString(val('externalId'))
         event_orgId=forceInt(val('event_org_id'))
         if checkExt and not externalId and event_orgId!=str(my_orgId):
             self.err2log(u'без внешнего идентификатора')
         contractId=forceInt(val('contract_id'))
         if not contractId and event_orgId==my_orgId:
             self.err2log(u'без договора')
         if checkSetPerson:
             setPersonId=forceInt(val('setPerson_id'))
             if not setPersonId:
                 self.err2log(u'без ответственного врача')
         execPersonId=forceInt(val('execPerson_id'))
         if not execPersonId:
             self.err2log(u'без выполнившего врача')
         resultId=forceInt(val('result_id'))
         if not resultId:
             self.err2log(u'отсутствует код результата')
         elif not db.getRecord('rbResult', 'id', resultId):
             self.err2log(u'неправильный код результата')
         eventTypeId=forceInt(val('eventType_id'))
         clientAge = calcAgeTuple(birthDate, execDate)
         self.checkDiags(eventId, sex, setDate, execDate, eventTypeId, clientAge)
         self.checkActions(eventId, sex, setDate, execDate, eventTypeId, clientAge)
         if self.item_bad:
             n_bad+=1
         self.labelInfo.setText(u'%d карточек всего; %d с ошибками' % (s, n_bad))
         EventTypes=self.tblEventType.values()
示例#11
0
    def processEvents(self, startDate, endDate):
        db = QtGui.qApp.db
        self.btnStart.setEnabled(False)
        self.logBrowser.append(u'Перевыставление начато')

        getEventsStmt = u'''
          SELECT
              Event.id                                              as eventId,
              EP.regionalCode                                       as eventCode,
              Client.sex                                            as sex,
              Client.birthDate                                      as bDay,
              Event.setDate                                         as setDate,
              Event.execDate                                        as execDate
          FROM
              Event
              INNER JOIN EventType ON Event.eventType_id = EventType.id
              INNER JOIN rbEventProfile AS EP ON EventType.eventProfile_id = EP.id
              INNER JOIN Client ON Event.client_id = Client.id
          WHERE(
              EP.regionalCode = '11' OR EP.regionalCode = '12' OR EP.regionalCode = '51' OR EP.regionalCode = '52' OR
              EP.regionalCode = '71' OR EP.regionalCode = '72' OR EP.regionalCode = '41' OR EP.regionalCode = '42' OR
              EP.regionalCode = '90' OR EP.regionalCode = '43') AND
              Event.execDate BETWEEN '%s' AND '%s'
              AND Event.deleted = 0 AND Client.deleted = 0
        ''' % (startDate.toString('yyyy.MM.dd'),
               endDate.toString('yyyy.MM.dd'))
        eventsQ = db.query(getEventsStmt)
        events = []
        while eventsQ.next():
            QtGui.qApp.processEvents()
            record = eventsQ.record()

            event = {}
            event['id'] = forceRef(record.value('eventId'))
            event['sex'] = forceInt(record.value('sex'))
            event['age'] = calcAgeTuple(forceDate(record.value('bDay')),
                                        forceDate(record.value('setDate')))

            event['code'] = getCSGDepartmentMaskByRegionalCode(
                forceString(record.value('eventCode')))
            event['setDate'] = forceDate(record.value('setDate'))
            event['execDate'] = forceDate(record.value('execDate'))

            getMKBstmt = u'''
                SELECT Diagnosis.MKB
                FROM Event INNER JOIN Diagnostic ON Event.id = Diagnostic.event_id INNER JOIN rbDiagnosisType ON Diagnostic.diagnosisType_id = rbDiagnosisType.id INNER JOIN Diagnosis ON Diagnostic.diagnosis_id = Diagnosis.id
                WHERE Event.id = '%i' AND (rbDiagnosisType.name = 'заключительный' OR rbDiagnosisType.name = 'основной')
                LIMIT 1
            ''' % (event['id'])
            mkbQ = db.query(getMKBstmt)
            mkbQ.next()
            mkbQ = mkbQ.record()
            if not mkbQ:
                self.badEvents.append(event['id'])
                continue
            mkb = forceString(mkbQ.value('MKB'))
            event['mkb'] = mkb

            getMKB2stmt = u'''
                SELECT Diagnosis.MKB
                FROM Event INNER JOIN Diagnostic ON Event.id = Diagnostic.event_id INNER JOIN rbDiagnosisType ON Diagnostic.diagnosisType_id = rbDiagnosisType.id INNER JOIN Diagnosis ON Diagnostic.diagnosis_id = Diagnosis.id
                WHERE Event.id = '%i' AND rbDiagnosisType.name = 'сопутствующий'
            ''' % (event['id'])
            mkbQ = db.query(getMKB2stmt)
            mkb2 = []
            while mkbQ.next():
                mkb2.append(forceString(mkbQ.record().value('MKB')))
            event['mkb2'] = mkb2

            getActionCodesstmt = u'''
                SELECT ActionType.code
                FROM Event INNER JOIN Action ON Event.id = Action.event_id INNER JOIN ActionType ON Action.actionType_id = ActionType.id
                WHERE Event.id = '%i' AND Action.status = 2 AND Action.deleted = 0
            ''' % (event['id'])
            actQ = db.query(getActionCodesstmt)
            actCodes = []
            while actQ.next():
                actCodes.append(forceString(actQ.record().value('code')))
            event['ATCodes'] = actCodes

            events.append(event)

        self.logBrowser.append(u'Список случаев получен: %i' % len(events))
        self.reselectKSG(events)
示例#12
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