Example #1
0
 def getPayStatusMask(self, accountId):
     result = self._mapAccountIdToPayStatusMask.get(accountId, None)
     if result is None:
         tblAccount = self._db.table('Account')
         tblContract = self._db.table('Contract')
         tbl = tblAccount.join(tblContract, tblContract['id'].eq(tblAccount['contract_id']))
         record = self._db.getRecordEx(tbl, tblContract['finance_id'], tblAccount['id'].eq(accountId))
         if record:
             result = getPayStatusMask(forceRef(record.value('finance_id')))
         self._mapAccountIdToPayStatusMask[accountId] = result
     return result
Example #2
0
    def processAccountItemIdList(self, recordList, refuseDate, refuseTypeId):
        payStatusMask = 0

        for record in recordList:
            QtGui.qApp.processEvents()
            self.accountIdSet.add(forceRef(record.value('Account_id')))
            contractId = forceRef(record.value('contract_id'))

            if self.prevContractId != contractId:
                self.prevContractId = contractId
                financeId = forceRef(
                    self.db.translate('Contract', 'id', contractId,
                                      'finance_id'))
                payStatusMask = getPayStatusMask(financeId)

            accDate = forceDate(record.value('Account_date'))
            accItemDate = forceDate(record.value('Account_Item_date'))
            accountItemId = forceRef(record.value('id'))

            if accItemDate or (refuseDate and (accDate > refuseDate)):
                self.err2log(u'счёт уже отказан')
                return

            self.nProcessed += 1

            accItem = self.db.getRecord(self.tableAccountItem, '*',
                                        accountItemId)
            accItem.setValue(
                'date',
                toVariant(refuseDate if refuseDate else QDate.currentDate()))

            if refuseDate:
                self.nRefused += 1
                accItem.setValue('refuseType_id', toVariant(refuseTypeId))
                updateDocsPayStatus(accItem, payStatusMask,
                                    CPayStatus.refusedBits)
                self.err2log(u'отказан, id=`%d`' % refuseTypeId)
            else:
                self.err2log(u'подтверждён')
                self.nPayed += 1

            accItem.setValue('number', toVariant(self.confirmation))
            self.db.updateRecord(self.tableAccountItem, accItem)

        if recordList == []:
            self.nNotFound += 1
            self.err2log(u'счёт не найден')
Example #3
0
    def processRow(self, row, currentAccountOnly, importPayed, importRefused,
                   confirmation, accountIdSet):
        lastName = nameCase(row.get(u'ФАМ', ''))
        firstName = nameCase(row.get(u'ИМЯ', ''))
        patrName = nameCase(row.get(u'ОТЧ', ''))
        refuseReasonCodeList = forceString(row.get(u'ОШЛ', '')).split(',')
        refuseDate = QDate().currentDate(
        ) if refuseReasonCodeList != [u''] else None
        refuseComment = row.get(u'ЗАМ', '')
        accountItemId = forceInt(row.get(u'УКЛ')) / 100
        recNum = accountItemId if accountItemId else 0
        payStatusMask = 0

        self.errorPrefix = u'Элемент №%d (%s %s %s): ' % (recNum, lastName,
                                                          firstName, patrName)

        if not accountItemId:
            self.err2log(u'не найден в реестре.')
            self.nNotFound += 1
            return

        cond = []
        cond.append(self.tableAccountItem['id'].eq(accountItemId))

        if currentAccountOnly:
            cond.append(self.tableAccount['id'].eq(toVariant(self.accountId)))

        fields = 'Account_Item.id, Account.date as Account_date, Account_Item.date as Account_Item_date, Account_Item.master_id as Account_id, Account.contract_id as contract_id'
        recordList = self.db.getRecordList(self.tableAcc, fields, where=cond)

        for record in recordList:
            accountIdSet.add(forceRef(record.value('Account_id')))
            contractId = forceRef(record.value('contract_id'))

            if self.prevContractId != contractId:
                self.prevContractId = contractId
                financeId = forceRef(
                    self.db.translate('Contract', 'id', contractId,
                                      'finance_id'))
                payStatusMask = getPayStatusMask(financeId)

            accDate = forceDate(record.value('Account_date'))
            accItemDate = forceDate(record.value('Account_Item_date'))

            if accItemDate or (refuseDate and (accDate > refuseDate)):
                self.err2log(u'счёт уже отказан')
                return

            self.nProcessed += 1

            accItem = self.db.getRecord(self.tableAccountItem, '*',
                                        accountItemId)
            accItem.setValue(
                'date',
                toVariant(refuseDate if refuseDate else QDate.currentDate()))
            refuseTypeId = None

            if refuseDate:
                self.nRefused += 1
                refuseTypeId = self.getRefuseTypeId(refuseReasonCodeList[0])

                if not refuseTypeId:
                    refuseTypeId = self.addRefuseTypeId(
                        refuseReasonCodeList[0], refuseComment)
                    self.refuseTypeIdCache[
                        refuseReasonCodeList[0]] = refuseTypeId

                accItem.setValue('refuseType_id', toVariant(refuseTypeId))
                updateDocsPayStatus(accItem, payStatusMask,
                                    CPayStatus.refusedBits)
                self.err2log(u'отказан, код `%s`:`%s`' %
                             (refuseReasonCodeList[0], refuseComment))
            else:
                self.err2log(u'подтверждён')
                self.nPayed += 1

            accItem.setValue('number', toVariant(confirmation))
            self.db.updateRecord(self.tableAccountItem, accItem)

        if recordList == []:
            self.nNotFound += 1
            self.err2log(u'счёт не найден')
Example #4
0
    def processRow(self,  row):
        lastName = forceString(row['FIO'])
        firstName = forceString(row['IMA'])
        patrName = forceString(row['OTCH'])
        sex = self.sexMap.get(forceString(row['POL']))
        birthDate = QDate(row['DATR']) if row['DATR'] else QDate()
        refuseDate = QDate(row['DVOZVRAT']) if row['DVOZVRAT'] else QDate()
        refuseReasonCodeList =  forceString(row['PV']).split(' ')
        eventId = forceRef(row['SN'])
        payStatusMask = 0
        accDate = QDate(row['DATS'])#QDate(row['DATPS']) if row['DATPS'] else QDate()
        accNumber = forceString(row['NS'])

        self.errorPrefix = u'Строка %d (%s %s %s): ' % (self.progressBar.value(), lastName,  firstName,  patrName)

        accountType = forceString(row['VS'])
        if accountType not in ('3', '7', 'b', 'f', 'j', 'n'):
            self.err2log(u'тип счёта не возвратный, код "%s"' % accountType)
            return

        if refuseDate.isValid() and refuseReasonCodeList == []:
            self.err2log(u'нет кода отказа')
            return

        if not refuseDate.isValid() and refuseReasonCodeList != []:
            self.err2log(u'нет даты отказа')
            return

        if not eventId:
            self.err2log(u'отсутствует идентификатор случая')

        cond=[]
        if self.isStationary:
            cond.append(self.db.joinOr([self.tableEvent['externalId'].eq(eventId), self.tableEvent['id'].eq(eventId)]))
        else:
            # Пытаемся восстановить старую логику ДККБ
            cond.append(self.tableEvent['client_id' if self.isDKKB else 'id'].eq(toVariant(eventId)))

        if accDate.isValid():
            cond.append(self.tableAccount['settleDate'].eq(toVariant(accDate)))

        # if accNumber:
        #     cond.append(self.tableAccount['number'].eq(toVariant(accNumber)))

        # if self.currentAccountOnly:
        cond.append(self.tableAccount['id'].eq(toVariant(self.accountId)))

        fields = 'Account_Item.id, Account.date as Account_date, Account_Item.date as Account_Item_date, Account_Item.master_id as Account_id, Account.contract_id as contract_id'
        recordList = self.db.getRecordList(self.tableAcc, fields, where=cond)

        if recordList != []:
            for record in recordList:
                self.accountIdSet.add(forceRef(record.value('Account_id')))
                contractId = forceRef(record.value('contract_id'))

                if self.prevContractId != contractId:
                    self.prevContractId = contractId
                    financeId = forceRef(self.db.translate('Contract', 'id', contractId, 'finance_id'))
                    payStatusMask = getPayStatusMask(financeId)

                accDate = forceDate(record.value('Account_date'))
                accItemDate = forceDate(record.value('Account_Item_date'))

                if accItemDate:
                    self.err2log(u'счёт уже отказан')
                    return

                if accDate > refuseDate:
                    self.err2log(u'счёт уже отказан')
                    return

                self.nProcessed += 1
                accountItemId = forceRef(record.value('id'))

                accItem = self.db.getRecord(self.tableAccountItem, '*', accountItemId)
                accItem.setValue('date', toVariant(refuseDate))
                refuseTypeId = None

                if refuseDate:
                    self.nRefused += 1
                    refuseTypeId=forceRef(self.db.translate(
                    'rbPayRefuseType', 'code', refuseReasonCodeList[0], 'id'))

                if not refuseTypeId:
                    refuseTypeId = self.addRefuseTypeId(refuseReasonCodeList[0])

                accItem.setValue('refuseType_id', toVariant(refuseTypeId))
                updateDocsPayStatus(accItem, payStatusMask, CPayStatus.refusedBits)

                accItem.setValue('number', toVariant(self.confirmation))
                self.db.updateRecord(self.tableAccountItem, accItem)
        else:
            self.nNotFound += 1
            self.err2log(u'счёт не найден')
Example #5
0
    def selectData(self, params):
        # для понимания происходящего в подзапросах рекомендуется прочесть
        # http://www.xaprb.com/blog/2006/12/07/how-to-select-the-firstleastmax-row-per-group-in-sql/
        stmt = u'''
        SELECT
            OrgStructureInfo.name AS orgStructureName,
            HospitalBedsInfo.profileName AS profileName,
            Event.id AS eventId,
            Event.MES_id AS mesId,
            Account_Item.amount,
            Account_Item.sum,
            Account_Item.price,
            Contract.regionalTariffRegulationFactor AS regulator,
            AdditionalExpenseM.percent AS additionalExpenseMPercent,
            PaymentExpense.percent AS paymentExpensePercent,
            IF (
                Account_Item.service_id IS NOT NULL,
                rbItemService.infis,
                IF(Account_Item.visit_id IS NOT NULL, rbVisitService.infis, rbEventService.infis)
            ) AS service
        FROM
            Account_Item
            INNER JOIN Account ON Account_Item.master_id = Account.id
            INNER JOIN Event ON Account_Item.event_id = Event.id
            INNER JOIN EventType ON Event.eventType_id = EventType.id
            INNER JOIN rbEventTypePurpose ON EventType.purpose_id = rbEventTypePurpose.id AND rbEventTypePurpose.code IN (101, 102)
            INNER JOIN Contract_Tariff ON Contract_Tariff.id = Account_Item.tariff_id
            INNER JOIN Contract ON Contract.id = Contract_Tariff.master_id
            INNER JOIN Person ON Event.execPerson_id = Person.id

            LEFT JOIN %s

            LEFT JOIN (
                SELECT
                    A.event_id,
                    OS.name AS orgStructureName,
                    rbHBP.name AS profileName
                FROM
                    Action AS A
                    INNER JOIN ActionType AS AT ON A.actionType_id = AT.id
                    INNER JOIN ActionPropertyType AS APT ON APT.actionType_id = AT.id AND APT.name RLIKE 'койк'
                    INNER JOIN ActionProperty AS AP ON AP.action_id = A.id AND AP.type_id = APT.id
                    INNER JOIN ActionProperty_HospitalBed AS APHB ON APHB.id = AP.id
                    INNER JOIN OrgStructure_HospitalBed AS OSHB ON OSHB.id = APHB.value
                    INNER JOIN rbHospitalBedProfile AS rbHBP ON OSHB.profile_id = rbHBP.id
                    INNER JOIN OrgStructure AS OS ON OS.id = OSHB.master_id

                    INNER JOIN (
                        SELECT
                            A.event_id,
                            MIN(A.id) as id
                        FROM
                            Action AS A
                            INNER JOIN ActionType AS AT ON A.actionType_id = AT.id
                            INNER JOIN ActionPropertyType AS APT ON APT.actionType_id = AT.id AND APT.name RLIKE 'койк'
                            INNER JOIN ActionProperty AS AP ON AP.action_id = A.id AND AP.type_id = APT.id
                            INNER JOIN ActionProperty_HospitalBed AS APHB ON APHB.id = AP.id
                            INNER JOIN OrgStructure_HospitalBed AS OSHB ON OSHB.id = APHB.value
                            INNER JOIN rbHospitalBedProfile AS rbHBP ON OSHB.profile_id = rbHBP.id
                            INNER JOIN OrgStructure AS OS ON OS.id = OSHB.master_id
                        WHERE
                            A.deleted = 0
                            AND AT.deleted = 0
                            AND APT.deleted = 0
                            AND AP.deleted = 0
                        GROUP BY
                            A.event_id
                    ) AS MA ON A.event_id = MA.event_id AND A.id = MA.id

                WHERE
                    A.deleted = 0
                    AND AT.deleted = 0
                    AND APT.deleted = 0
                    AND AP.deleted = 0
            ) AS HospitalBedsInfo ON HospitalBedsInfo.event_id = Event.id

            LEFT JOIN rbMedicalAidType ON rbMedicalAidType.id = EventType.medicalAidType_id
            LEFT JOIN rbService AS rbEventService ON rbEventService.id = EventType.service_id
            LEFT JOIN Visit ON Visit.id = Account_Item.visit_id
            LEFT JOIN rbService AS rbVisitService ON rbVisitService.id = Visit.service_id
            LEFT JOIN rbService AS rbItemService ON rbItemService.id = Account_Item.service_id

            LEFT JOIN Contract_CompositionExpense AS AdditionalExpenseM ON  AdditionalExpenseM.id = (
                SELECT MAX(CCE3.id)
                FROM Contract_CompositionExpense AS CCE3
                LEFT JOIN rbExpenseServiceItem ON CCE3.rbTable_id =rbExpenseServiceItem.id
                WHERE rbExpenseServiceItem.code IN ('3', '230004')  AND CCE3.master_id = Contract_Tariff.id
            )

            LEFT JOIN Contract_CompositionExpense AS PaymentExpense ON  PaymentExpense.id = (
                SELECT MAX(CCE4.id)
                FROM Contract_CompositionExpense AS CCE4
                LEFT JOIN rbExpenseServiceItem ON CCE4.rbTable_id =rbExpenseServiceItem.id
                WHERE rbExpenseServiceItem.code IN ('4', '230005')  AND CCE4.master_id = Contract_Tariff.id
            )

        WHERE
            %s
        '''
        db = QtGui.qApp.db

        orgStructureByAction = params.get('orgStructureByAction', True)
        if orgStructureByAction:
            orgStructureInfo = u'''
            (
                SELECT
                    Event.id as event_id,
                    OS.name
                FROM
                    Event
                    INNER JOIN Action AS A ON Event.id = A.event_id
                    INNER JOIN ActionPropertyType AS APT
                    INNER JOIN ActionProperty AS AP ON AP.type_id=APT.id
                    INNER JOIN ActionProperty_OrgStructure AS APOS ON APOS.id=AP.id
                    INNER JOIN OrgStructure AS OS ON OS.id = APOS.value

                    INNER JOIN (
                        SELECT
                            Event.id AS event_id,
                            MAX(A.begDate) AS begDate
                        FROM
                            Event
                            INNER JOIN Action AS A ON Event.id = A.event_id
                            INNER JOIN ActionPropertyType AS APT
                            INNER JOIN ActionProperty AS AP ON AP.type_id=APT.id
                            INNER JOIN ActionProperty_OrgStructure AS APOS ON APOS.id=AP.id
                            INNER JOIN OrgStructure AS OS ON OS.id = APOS.value
                        WHERE
                            A.actionType_id IN (SELECT id FROM ActionType where name = 'Движение')
                            AND APT.actionType_id = A.actionType_id
                            AND AP.action_id = A.id
                            AND APT.deleted = 0
                            AND (APT.name RLIKE 'Отделение')
                            AND OS.deleted = 0
                        GROUP BY
                            event_id
                    ) AS MA ON A.event_id = MA.event_id AND A.begDate = MA.begDate
                WHERE
                    A.actionType_id IN (SELECT id FROM ActionType where name = 'Движение')
                    AND APT.actionType_id = A.actionType_id
                    AND AP.action_id = A.id
                    AND APT.deleted = 0
                    AND (APT.name RLIKE 'Отделение')
                    AND OS.deleted = 0
            ) AS OrgStructureInfo ON OrgStructureInfo.event_id = Event.id
            '''
        else:
            orgStructureInfo = u'''OrgStructure AS OrgStructureInfo ON Person.orgStructure_id = OrgStructureInfo.id'''

        tableEvent = db.table('Event')
        tableEventType = db.table('EventType')
        tableContractTariff = db.table('Contract_Tariff')
        tableContract = db.table('Contract')
        tableAccount = db.table('Account')
        tableAccountItem = db.table('Account_Item')
        tablePerson = db.table('Person')
        tableOrgStructure = db.table('OrgStructure')

        cond = [
            tableEvent['execDate'].isNotNull(),
            tableEvent['deleted'].eq(0),
            tableEventType['deleted'].eq(0),
            tableContractTariff['deleted'].eq(0),
            tableContract['deleted'].eq(0),
            tableAccount['deleted'].eq(0),
            tableAccountItem['deleted'].eq(0),
            tablePerson['deleted'].eq(0),
        ]

        if not orgStructureByAction:
            cond.append(
                tableOrgStructure.alias('OrgStructureInfo')['deleted'].eq(0))

        financeId = forceInt(params.get('financeId', None))
        if financeId:
            cond.append(tableContract['finance_id'].eq(financeId))
        accountNumber = params.get('accountNumber')
        cond.append(tableAccount['number'].inlist(accountNumber))

        payStatusCheckState = params.get('payStatusCheckState',
                                         QtCore.Qt.Unchecked)
        payStatus = params.get('payStatus', '')

        # тип реестра
        if payStatusCheckState == QtCore.Qt.Checked:
            payStatusIndex = self.dialog.payStatusList.index(payStatus)
            payStatusList = []
            baseTable = 'Event'
            if payStatusIndex == 0:  # Нет выставления, оплаты и отказа
                cond.append('%s.payStatus = 0' % baseTable)
            elif payStatusIndex == 1:  # Выставлено, нет оплаты и отказа
                for f_id in self._financeIds:
                    payStatusList.append(
                        str(getExposed(getPayStatusMask(f_id))))
                cond.append('%s.payStatus IN (%s)' %
                            (baseTable, ','.join(payStatusList)))
            elif payStatusIndex == 2:  # Отказано, нет оплаты
                for f_id in self._financeIds:
                    payStatusList.append(
                        str(getRefused(getPayStatusMask(f_id))))
                cond.append('%s.payStatus IN (%s)' %
                            (baseTable, ','.join(payStatusList)))
            elif payStatusIndex == 3:  # Оплачено
                for f_id in self._financeIds:
                    payStatusList.append(str(getPayed(getPayStatusMask(f_id))))
                cond.append('%s.payStatus IN (%s)' %
                            (baseTable, ','.join(payStatusList)))
            else:  # Выставлено, оплачено, отказано
                cond.append('%s.payStatus <> 0' % baseTable)

        return db.query(stmt % (orgStructureInfo, db.joinAnd(cond)))
Example #6
0
    def selectData(self, params):
        stmt = u'''
            SELECT
                Account_Item.amount,
                Account_Item.sum,
                Account.number,

                IF (
                    Account_Item.service_id IS NOT NULL,
                    rbItemService.infis,
                    rbEventService.infis
                ) AS serviceCode,

                IF (
                    Account_Item.service_id IS NOT NULL,
                    rbItemService.name,
                    rbEventService.name
                ) AS serviceName,

                Person.orgStructure_id AS orgStructureId
            FROM
                Account_Item
                INNER JOIN Account ON Account_Item.master_id = Account.id AND Account.deleted = 0 
                INNER JOIN Event ON Account_Item.event_id = Event.id
                INNER JOIN Contract ON Event.contract_id = Contract.id
                LEFT JOIN EventType ON Event.eventType_id = EventType.id
                LEFT JOIN rbService AS rbItemService ON Account_Item.service_id = rbItemService.id
                LEFT JOIN rbService AS rbEventService ON EventType.service_id = rbEventService.id
                LEFT JOIN Person ON Person.id = Event.execPerson_id
                LEFT JOIN Action ON Action.id = Account_Item.action_id
                LEFT JOIN Visit ON Visit.id = Account_Item.visit_id
            %s
            HAVING
                serviceCode LIKE 'A%%' OR serviceCode LIKE 'B%%'
            ORDER BY
                orgStructureId
        '''

        orgStructureId = params.get('orgStructureId', None)
        financeId = params.get('typeFinanceId', None)
        begDate = params.get('begDate', QtCore.QDate())
        endDate = params.get('endDate', QtCore.QDate())
        accountNumberList = params.get('accountNumber', None)
        filterByDate = len(accountNumberList) == 0

        payStatusCheckState = params.get('payStatusCheckState',
                                         QtCore.Qt.Unchecked)
        payStatus = params.get('payStatus', '')

        db = QtGui.qApp.db
        tablePerson = db.table('Person')
        tableContract = db.table('Contract')
        tableAccount = db.table('Account')
        tableEvent = db.table('Event')

        cond = [
            tableEvent['execDate'].isNotNull(), u'Account_Item.deleted = 0'
        ]
        if financeId is not None:
            cond.append(tableContract['finance_id'].eq(financeId))

        if orgStructureId:
            cond.append(
                db.joinAnd([
                    db.joinOr([
                        tablePerson['orgStructure_id'].eq(orgStructureId),
                        tablePerson['orgStructure_id'].inInnerStmt(
                            "(SELECT id FROM OrgStructure_Ancestors WHERE fullPath LIKE '%"
                            + str(orgStructureId) + "%')")
                    ]),
                ]))

        if filterByDate:
            if begDate:
                cond.append(
                    u"DATE(COALESCE(Action.endDate, Visit.date, Event.execDate)) >= DATE('%s')"
                    % begDate.toString('yyyy-MM-dd'))
            if endDate:
                cond.append(
                    u"DATE(COALESCE(Action.endDate, Visit.date, Event.execDate)) <= DATE('%s')"
                    % endDate.toString('yyyy-MM-dd'))
        else:
            cond.append(tableAccount['number'].inlist(accountNumberList))

        # тип реестра
        if payStatusCheckState == QtCore.Qt.Checked:
            payStatusIndex = self.dialog.payStatusList.index(payStatus)
            payStatusList = []
            baseTable = 'Event'
            if payStatusIndex == 0:  # Нет выставления, оплаты и отказа
                cond.append('%s.payStatus = 0' % baseTable)
            elif payStatusIndex == 1:  # Выставлено, нет оплаты и отказа
                for f_id in self._financeIds:
                    payStatusList.append(
                        str(getExposed(getPayStatusMask(f_id))))
                cond.append('%s.payStatus IN (%s)' %
                            (baseTable, ','.join(payStatusList)))
            elif payStatusIndex == 2:  # Отказано, нет оплаты
                for f_id in self._financeIds:
                    payStatusList.append(
                        str(getRefused(getPayStatusMask(f_id))))
                cond.append('%s.payStatus IN (%s)' %
                            (baseTable, ','.join(payStatusList)))
            elif payStatusIndex == 3:  # Оплачено
                for f_id in self._financeIds:
                    payStatusList.append(str(getPayed(getPayStatusMask(f_id))))
                cond.append('%s.payStatus IN (%s)' %
                            (baseTable, ','.join(payStatusList)))
            else:  # Выставлено, оплачено, отказано
                cond.append('%s.payStatus <> 0' % baseTable)

        return db.query(stmt %
                        (u'WHERE\n' + db.joinAnd(cond) if cond else u''))
Example #7
0
    def startImport(self):
        curr_acc = self.AccCheck.isChecked()
        imp_oplat = self.OplataCheck.isChecked()
        imp_otkaz = self.OtkazCheck.isChecked()
        imp_only_attach = self.chkOnlyAttach.isChecked()
        podtv = self.edtPodtv.text()
        if not podtv:
            self.log.append(u'нет подтверждения')
            return

        dbfFileName = unicode(self.edtFileName.text())
        dbfRD1 = dbf.Dbf(dbfFileName, readOnly=True, encoding='cp866')
        imp_attach = self.chkAttach.isChecked() and forceString(
            self.edtAttach.text()) in dbfRD1.header.fields

        if imp_only_attach and not imp_attach:
            self.log.append(u'загрузка всех данных выключена')
            dbfRD1.close()
            return

        db = QtGui.qApp.db
        prevContractId = None
        payStatusMask = 0
        accountIdSet = set()

        n = 0
        n_ld = 0
        n_oplata = 0
        n_otkaz = 0
        n_notfound = 0

        tableAccount_Item = tbl('Account_Item')
        tableAccount = tbl('Account')
        tableAcc = db.join(tableAccount_Item, tableAccount,
                           'Account_Item.master_id=Account.id')
        self.labelNum.setText(u'всего записей в источнике: ' +
                              str(len(dbfRD1)))
        #        RD1fields=get_RD1_fields()
        #        RD1fields=[f[0] for f in RD1fields]
        requiredFields = [
            'COMMENT', 'DATE_OPLAT', 'DATE_OTKAZ', 'DR', 'ERR_S', 'FAM', 'ID',
            'IM', 'KOD_OTKAZ', 'KOD_PROG', 'N_ACT', 'OT', 'POL'
        ]

        #FIXME: Нужно проверить что выбрасывается разумное исключение, которое приводит к понятному messageBox-у
        #        assert dbfCheckNames(dbfRD1, RD1fields)
        assert dbfCheckNames(dbfRD1, requiredFields)
        self.progressBar.setMaximum(len(dbfRD1) - 1)
        for row in dbfRD1:
            QtGui.qApp.processEvents()
            if self.abort: break
            self.progressBar.setValue(n)
            self.stat.setText(
                u'обработано: %d; оплаченых: %d; отказаных: %d; не найдено: %d' % \
                (n_ld, n_oplata, n_otkaz, n_notfound))
            n += 1
            self.n = n
            self.row = row
            #            NUMTR=row['NUMTR']
            #            DATETR=row['DATETR']
            ID = int(row['ID'])
            #            KOD_ORG_OK=row['KOD_ORG_OK']
            #            KOD_ORG_OG=row['KOD_ORG_OG']
            #            PERIOD=row['PERIOD']
            #            DATE_DOG=row['DATE_DOG']
            #            NOMER_DOG=row['NOMER_DOG']
            FAM = row['FAM']
            IM = row['IM']
            OT = row['OT']
            POL = int(row['POL']) if row['POL'] else 0
            DR = row['DR']
            #            SMO=row['SMO']
            ERR_S = row['ERR_S']
            if 'ID_PAT' in dbfRD1.header.fields:
                ID_PAT = row['ID_PAT']
                ID_PAT = int(ID_PAT) if ID_PAT else None
            else:
                ID_PAT = None
            if 'ERR_REM' in dbfRD1.header.fields:
                ERR_REM = row['ERR_REM']
            else:
                ERR_REM = ''

            DATE_OPLAT = row['DATE_OPLAT']
            DATE_OTKAZ = row['DATE_OTKAZ']
            N_ACT = row['N_ACT']
            KOD_OTKAZ = row['KOD_OTKAZ']
            #            COMMENT=row['COMMENT']
            self.err_txt = u'ID=%s; ID_PAT=%s (%s %s %s): ' % (
                row['ID'], str(ID_PAT), FAM, IM, OT)

            KOD_PROG = row['KOD_PROG']
            if KOD_PROG != 4:
                continue
#            if not ID or not ID_PAT:
#                self.err2log(u'отсутствует ID или ID_PAT')
#                continue
            if not ID:
                self.err2log(u'отсутствует ID')
                continue

            if not imp_only_attach:
                if not DATE_OPLAT and not DATE_OTKAZ:
                    self.err2log(u'отсутствуют даты оплаты и отказа')
                    continue
                if DATE_OPLAT and DATE_OTKAZ:
                    self.err2log(u'есть и дата оплаты, и дата отказа')
                    continue
                if DATE_OTKAZ and not ERR_S:
                    self.err2log(u'нет кода отказа')
                    continue
                if not DATE_OTKAZ and ERR_S:
                    self.err2log(u'нет даты отказа')
                    continue
                if DATE_OPLAT and not imp_oplat:
                    continue
                if DATE_OTKAZ and not imp_otkaz:
                    continue

            Event = db.getRecord('Event', '*', ID)
            if not Event:
                self.err2log(u'Event не найден')
                continue
            if ID_PAT:
                if Event.value('client_id').toInt()[0] != ID_PAT:
                    self.err2log(u'Event.client_id не совпадает с ID_PAT')
                    continue
            else:
                ID_PAT = Event.value('client_id').toInt()[0]

            Client = db.getRecord('Client', '*', ID_PAT)
            if not Client:
                self.err2log(u'пациент не найден')
                continue
            if ((FAM or IM or OT or DR or POL) and
                (forceString(Client.value('lastName')).upper() != FAM.upper()
                 or forceString(
                     Client.value('firstName')).upper() != IM.upper() or
                 forceString(Client.value('patrName')).upper() != OT.upper()
                 or get_date(Client.value('birthDate')) != DR
                 or Client.value('sex').toInt()[0] != POL)):
                self.err2log(u'информация о пациенте не совпадает')
#                continue

            if imp_attach:
                attachField = forceString(self.edtAttach.text())
                attach = row[attachField]
                if attach:
                    lpuId = self.infis2orgId(attach)
                    if lpuId:
                        ClientAttachFields = [('client_id', ID_PAT),
                                              ('attachType_id', 2),
                                              ('LPU_id', lpuId)]
                        getId(self.tableClientAttach, ClientAttachFields)

            if not imp_only_attach:
                cond = []
                cond.append(tableAccount_Item['event_id'].eq(toVariant(ID)))
                if curr_acc:
                    cond.append(tableAccount['id'].eq(toVariant(
                        self.accountId)))

    #                cond.append(tableAccount_Item['date'].isNull())
                DATE = DATE_OPLAT if DATE_OPLAT else DATE_OTKAZ
                #                cond.append(tableAccount['date'].le(toVariant(DATE)))
                fields = 'Account_Item.id, Account.date as Account_date, Account_Item.date as Account_Item_date, Account_Item.master_id as Account_id, Account.contract_id as contract_id'
                AccRecord = db.getRecordEx(tableAcc, fields, where=cond)
                if AccRecord:
                    accountIdSet.add(forceRef(AccRecord.value('Account_id')))
                    contractId = forceRef(AccRecord.value('contract_id'))
                    if prevContractId != contractId:
                        prevContractId = contractId
                        financeId = forceRef(
                            db.translate('Contract', 'id', contractId,
                                         'finance_id'))
                        payStatusMask = getPayStatusMask(financeId)

                    Account_date = get_date(AccRecord.value('Account_date'))
                    Account_Item_date = get_date(
                        AccRecord.value('Account_Item_date'))
                    if Account_Item_date:
                        self.err2log(u'счёт уже оплачен или отказан')
                        continue
                    if Account_date > DATE:
                        self.err2log(u'счёт уже оплачен или отказан')
                        continue

                    n_ld += 1

                    Account_ItemId = AccRecord.value('id').toInt()[0]
                    Account_Item = db.getRecord('Account_Item', '*',
                                                Account_ItemId)
                    Account_Item.setValue('date', toVariant(DATE))
                    refuseType_id = None
                    #                    if DATE_OTKAZ and KOD_OTKAZ:
                    #                        refuseType_id={}.get(KOD_OTKAZ, 61)
                    if DATE_OTKAZ:
                        n_otkaz += 1
                        ERR_S = ERR_S.replace(';', ',').split(',')[0]
                        refuseType_id = forceInt(
                            db.translate('rbPayRefuseType', 'code', ERR_S,
                                         'id'))
                        if not refuseType_id:
                            #                        refuseType_id=61
                            table = tbl('rbPayRefuseType')
                            record = table.newRecord()
                            record.setValue('code', toVariant(ERR_S))
                            record.setValue(
                                'name ',
                                toVariant(u'неизвестная причина с кодом "%s"' %
                                          ERR_S))
                            record.setValue('finance_id', toVariant(5))
                            record.setValue('rerun', toVariant(1))
                            refuseType_id = db.insertRecord(table, record)
                        Account_Item.setValue('refuseType_id',
                                              toVariant(refuseType_id))
                        updateDocsPayStatus(Account_Item, payStatusMask,
                                            CPayStatus.refusedBits)
                    else:
                        n_oplata += 1
                        updateDocsPayStatus(Account_Item, payStatusMask,
                                            CPayStatus.payedBits)
                    Account_Item.setValue(
                        'number', toVariant(str(N_ACT) if N_ACT else podtv))
                    Account_Item.setValue(
                        'note',
                        toVariant(row['ERR_S'] + ';' + ERR_REM + ' ' +
                                  row['COMMENT']))
                    db.updateRecord(tableAccount_Item, Account_Item)
                else:
                    n_notfound += 1
                    self.err2log(u'счёт не найден')

        self.progressBar.setValue(n)
        self.stat.setText(
            u'обработано: %d; оплаченых: %d; отказаных: %d; не найдено: %d' % \
            (n_ld, n_oplata, n_otkaz, n_notfound))
        self.progressBar.setValue(n - 1)
        updateAccounts(list(accountIdSet))
Example #8
0
    def __init__(self, parent, accountId, accountItemIdList):
        QtGui.QDialog.__init__(self)
        self.setupUi(self)
        self.parent = parent
        CDBFimport.__init__(self, self.log)
        #self.accountId=accountId
        #self.accountItemIdList=accountItemIdList

        self.accountId = accountId
        self.process = None
        self.processedEvents = []
        self.checkName()
        self.errorPrefix = ''
        self.nProcessed = 0
        self.nPayed = 0
        self.nRefused = 0
        self.nNotFound = 0

        self.tabImportType.setVisible(False)
        self.label_3.setVisible(False)

        self.processedEvents = []

        self.tblPayRefuseType = tbl('rbPayRefuseType')
        self.tableAccountItem = tbl('Account_Item')
        self.tableEvent = tbl('Event')
        self.tableAccount = tbl('Account')
        self.tableClientPolicy = tbl('ClientPolicy')
        self.tableVisit = tbl('Visit')
        self.tableAction = tbl('Action')
        self.tableAcc = self.db.join(self.tableAccountItem, self.tableAccount,
                                     'Account_Item.master_id=Account.id').join(
                                         self.tableEvent,
                                         'Account_Item.event_id=Event.id')
        self.prevContractId = None
        self.financeTypeOMS = forceRef(
            self.db.translate('rbFinance', 'code', '2', 'id'))
        self.orgCache = {}
        self.deleteAccount = False
        self.setWindowTitle(u'Загрузка отказов оплаты для Ростовской области')
        self.labelNum.setText(u'')

        # Получаем тип финансирования и маску
        if accountId:
            tempQ = QtGui.qApp.db.query(
                'SELECT Contract.finance_id FROM Account LEFT JOIN Contract ON Contract.id = Account.contract_id WHERE Account.id = %s'
                % accountId)
            if tempQ.next():
                rec = tempQ.record()
                self.financeId = forceRef(rec.value('finance_id'))
                self.payStatusMask = getPayStatusMask(self.financeId)
            else:
                self.financeId = 0
                self.payStatusMask = 0
        else:
            self.financeId = 0
            self.payStatusMask = 0
        self.requiredFields = {  #self.processKontrol: ['NSCHT', 'KODP', 'ER_COD', 'COMENT'],         # Должно быть по стандарту, но в Ростове - мудаки.
            self.processKontrol: ['NSCHT', 'KODP', 'ER_COD', 'ER_MESSAGE'],
            self.processPolicy:
            ['KODST', 'SERIA', 'NPOLI', 'VPOLIS', 'NSTRA', 'KTERR'],
            self.processExpertise: ['NSCHT', 'KOTK', 'PRIM']
        }