def processEvent(self, eventElement, clientId, date, insurerInfis): eventId = self.getElementValue(eventElement, 'NHISTORY', isRequired=True) # Применимо только в МО tblEvent = self._db.table('Event') eventRecord = self._db.getRecordEx(table=tblEvent, cols=[tblEvent['id'].eq(eventId), tblEvent['client_id'].eq(clientId), tblEvent['deleted'].eq(0)]) if not eventRecord: self.logger().warning(u'Не найден случай лечения NHISTORY=%s для пациента ID_PAC=%s' % (eventId, clientId)) return False tblAccountItem = self._db.table('Account_Item') fields = [tblAccountItem['id'], tblAccountItem['date'], tblAccountItem['action_id'], tblAccountItem['visit_id'], tblAccountItem['event_id'], tblAccountItem['master_id'], tblAccountItem['refuseType_id'], tblAccountItem['number'], tblAccountItem['note']] accountItemList = self._db.getRecordList(tblAccountItem, cols=fields, where=[tblAccountItem['event_id'].eq(eventId)]) self._db.transaction() try: for accountItem in accountItemList: oplata = self.getElementValue(eventElement, 'OPLATA', typeName='n') accountItem.setValue('date', toVariant(date)) accountNote = forceStringEx(accountItem.value('note')) if insurerInfis: accountNote += '$$insurer:%s$$' % insurerInfis sankElement = self.getElement(eventElement, 'SANK') if not sankElement.isNull(): refReason = self.getElementValue(sankElement, 'S_OSN') accountNote += '\nS_COM: %s' % self.getElementValue(sankElement, 'S_COM') else: refReason = '' if oplata != 0 else '53' # mdldml: 53 -- flatCode "Некорректного заполнения полей реестра" accountItem.setValue('note', toVariant(accountNote)) accountId = forceRef(accountItem.value('master_id')) payStatusMask = self.getPayStatusMask(accountId) if oplata != 1 and refReason: refuseTypeId = self.getRefuseTypeId(refReason) accountItem.setValue('refuseType_id', toVariant(refuseTypeId)) accountItem.setValue('number', toVariant(u'Отказ по МЭК')) updateDocsPayStatus(accountItem, payStatusMask, CPayStatus.refusedBits) else: accountItem.setValue('number', toVariant(u'Оплачено')) accountItem.setValue('refuseType_id', toVariant(None)) updateDocsPayStatus(accountItem, payStatusMask, CPayStatus.payedBits) self._db.updateRecord(tblAccountItem, accountItem) self._processedAccountIdSet.add(accountId) self._db.commit() except: self._db.rollback()
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'счёт не найден')
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'счёт не найден')
def processEvent(self, eventElement, clientId, date, insurerInfis): eventId = self.getElementValue(eventElement, 'NHISTORY', isRequired=True) # Применимо только в МО tblEvent = self._db.table('Event') eventRecord = self._db.getRecordEx(table=tblEvent, cols=[tblEvent['id'].eq(eventId), tblEvent['client_id'].eq(clientId), tblEvent['deleted'].eq(0)]) if not eventRecord: self.logger().warning(u'Не найден случай лечения NHISTORY=%s для пациента ID_PAC=%s' % (eventId, clientId)) return False eventSetDate = self.getElementValue(eventElement, 'DATE_1', typeName='d') eventExecDate = self.getElementValue(eventElement, 'DATE_2', typeName='d') tblAccountItem = self._db.table('Account_Item') tblVisit = self._db.table('Visit') tblAction = self._db.table('Action') tblService = self._db.table('rbService') queryTable = tblAccountItem.innerJoin(tblEvent, tblEvent['id'].eq(tblAccountItem['event_id'])) queryTable = queryTable.leftJoin(tblVisit, tblVisit['id'].eq(tblAccountItem['visit_id'])) queryTable = queryTable.leftJoin(tblAction, tblAction['id'].eq(tblAccountItem['action_id'])) queryTable = queryTable.leftJoin(tblService, tblService['id'].eq(tblAccountItem['service_id'])) fields = [tblAccountItem['id'], tblAccountItem['date'], tblAccountItem['action_id'], tblAccountItem['visit_id'], tblAccountItem['event_id'], tblAccountItem['master_id'], tblAccountItem['refuseType_id'], tblAccountItem['number'], tblAccountItem['note'], tblAccountItem['service_id'], # tblAccountItem['insurer_sum'], tblAccountItem['sum'], tblAccountItem['price'], tblAccountItem['amount'], tblAction['begDate'].alias('actionBegDate'), tblAction['endDate'].alias('actionEndDate'), tblVisit['date'].alias('visitDate'), tblEvent['setDate'].alias('eventSetDate'), tblEvent['execDate'].alias('eventExecDate'), tblService['code'].alias('serviceCode'), ] accountItemList = self._db.getRecordList(queryTable, cols=fields, where=[tblEvent['id'].eq(eventId) ]) if not accountItemList: self._skipped += 1 self.logger().warning(u'Не найден случай лечения NHISTORY=%s для пациента ID_PAC=%s' % (eventId, clientId)) return False self._db.transaction() try: self._db.query('UPDATE Event SET FLCStatus = 2 WHERE id = %s' % eventId) oplata = self.getElementValue(eventElement, 'OPLATA', typeName='n') for accountItem in accountItemList: accountItem.setValue('date', toVariant(date)) accountNote = forceStringEx(accountItem.value('note')) if insurerInfis: accountNote += '\n$$insurer:%s$$' % insurerInfis sankElement = self.getElement(eventElement, 'SANK') if not sankElement.isNull(): refReason = self.getElementValue(sankElement, 'S_OSN') accountNote += '\nS_COM: %s' % self.getElementValue(sankElement, 'S_COM') else: refReason = '' if oplata != 0 else '53' # mdldml: 53 -- flatCode "Некорректного заполнения полей реестра" accountId = forceRef(accountItem.value('master_id')) payStatusMask = self.getPayStatusMask(accountId) accountItem.setValue('note', toVariant(accountNote)) if oplata != 1 and refReason: refuseTypeId = self.getRefuseTypeId(refReason) accountItem.setValue('refuseType_id', toVariant(refuseTypeId)) accountItem.setValue('number', toVariant(u'Отказ по МЭК')) updateDocsPayStatus(accountItem, payStatusMask, CPayStatus.refusedBits) else: accountItem.setValue('number', toVariant(u'Оплачено')) accountItem.setValue('refuseType_id', toVariant(None)) updateDocsPayStatus(accountItem, payStatusMask, CPayStatus.payedBits) eventLevelAccountItems = [ai for ai in accountItemList if ai.value('action_id').isNull() and ai.value('visit_id').isNull()] if not eventLevelAccountItems: serviceList = [] serviceElement = eventElement.firstChildElement('USL') while not serviceElement.isNull(): serviceList.append(self._get_service_info(serviceElement)) serviceElement = serviceElement.nextSiblingElement('USL') for accountItem in accountItemList: if forceRef(accountItem.value('action_id')): begDate = forceDate(accountItem.value('actionBegDate')) endDate = forceDate(accountItem.value('actionEndDate')) elif forceRef(accountItem.value('visit_id')): begDate = endDate = forceDate(accountItem.value('visitDate')) else: begDate = forceDate(accountItem.value('eventSetDate')) endDate = forceDate(accountItem.value('eventExecDate')) filtered_list = sorted(filter(lambda x: x['code'] == forceStringEx(accountItem.value('serviceCode')) and \ x['begDate'] == begDate and x['endDate'] == endDate and \ x['amount'] == forceDouble(accountItem.value('amount')) , serviceList), key=lambda x: abs(x['sum'] - forceDouble(accountItem.value('sum')))) if filtered_list: service_info = filtered_list[0] accountItem.setValue('sum', toVariant(service_info['sum'])) accountItem.setValue('price', toVariant(service_info['price'])) serviceList.remove(service_info) else: eventServiceInfo = self._get_event_service_info(eventElement) # проверить, что это действительно та услуга: как минимум, # code_mes должен совпадать с Account.event_id -> Event.mes_id -> mes.MES.code, # даты должны совпадать с датами обращения otherAccountItems = [item for item in accountItemList if item not in eventLevelAccountItems] tableEvent = self._db.table('Event') tableMes = self._db.table('mes.MES') eventData = self._db.getRecordList( tableEvent.leftJoin(tableMes, tableEvent['MES_id'].eq(tableMes['id'])), [tableEvent['id'], tableEvent['setDate'], tableEvent['execDate'], tableMes['code']], tableEvent['id'].inlist([forceRef(item.value('event_id')) for item in eventLevelAccountItems]) ) eventMap = {} for eventRecord in eventData: eventMap[forceRef(eventRecord.value('id'))] = { 'setDate': forceDate(eventRecord.value('setDate')), 'execDate': forceDate(eventRecord.value('execDate')), 'code': forceStringEx(eventRecord.value('code')) } accountsChanged = set() for accountItem in eventLevelAccountItems: # accountId = forceRef(accountItem.value('master_id')) eventInfo = eventMap[forceRef(accountItem.value('event_id'))] if forceRef(accountItem.value('master_id')) not in accountsChanged and \ eventServiceInfo['code'] == eventInfo['code'] and \ eventServiceInfo['begDate'] == eventInfo['setDate'] and \ eventServiceInfo['endDate'] == eventInfo['execDate']: accountItem.setValue('sum', toVariant(eventServiceInfo['sum'])) accountItem.setValue('price', toVariant(eventServiceInfo['price'])) accountsChanged.add(forceRef(accountItem.value('master_id'))) for accountItem in otherAccountItems: if forceRef(accountItem.value('master_id')) in accountsChanged: accountItem.setValue('sum', toVariant(0)) accountItem.setValue('price', toVariant(0)) for accountItem in accountItemList: accountId = forceRef(accountItem.value('master_id')) for field in ('actionBegDate', 'actionEndDate', 'visitDate', 'eventSetDate', 'eventExecDate', 'serviceCode'): accountItem.remove(accountItem.indexOf(field)) self._db.updateRecord(tblAccountItem, accountItem) self._processedAccountIdSet.add(accountId) self._processedAccountItems.add(forceRef(accountItem.value('id'))) self._db.commit() except: self._db.rollback()
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'счёт не найден')
def processSluch(self, sluch, clientId): idcase = forceString(sluch.firstChildElement('IDCASE').text()) eventTypeIdList = self.getEventTypeIdList(sluch, idcase) if not eventTypeIdList: self.err2log(u'Не найден тип события для IDCASE = %s' % idcase) self.nNotFound += 1 self.nProcessed += 1 return False dateInStr = forceString(sluch.firstChildElement('DATE_1').text()) dateOutStr = forceString(sluch.firstChildElement('DATE_2').text()) dateIn = QtCore.QDate.fromString(dateInStr, QtCore.Qt.ISODate) dateOut = QtCore.QDate.fromString(dateOutStr, QtCore.Qt.ISODate) if not dateIn.isValid(): self.err2log( u'Не удалось определить дату начала лечения для IDCASE = %s' % idcase) self.nNotFound += 1 self.nProcessed += 1 return False # if not dateOut.isValid(): # self.err2log(u'Не удалось определить дату окончания лечения для IDCASE = %s' % idcase) # self.nNotFound += 1 # self.nProcessed += 1 # return False eventRecord = self.db.getRecordEx(self.tblEvent, 'id', [ self.tblEvent['client_id'].eq(clientId), self.tblEvent['eventType_id'].inlist(eventTypeIdList), self.tblEvent['setDate'].dateEq(dateIn), self.tblEvent['execDate'].dateEq(dateOut) if dateOut.isValid() else 'NOT Event.execDate', self.tblEvent['deleted'].eq(0) ]) if not eventRecord: self.err2log(u'Не найден случай лечения для IDCASE = %s' % idcase) self.nNotFound += 1 self.nProcessed += 1 return False eventId = forceRef(eventRecord.value('id')) oplata = forceInt(sluch.firstChildElement('OPLATA').text()) usl = sluch.firstChildElement('USL') if not usl: self.err2log( u'В ID_CASE = %s не указано ни одной услуги для оплаты' % idcase) fields = 'Account_Item.id, Account_Item.date, Account_Item.action_id, Account_Item.visit_id, Account_Item.event_id, Account_Item.master_id, Account_Item.refuseType_id, Account_Item.number, Account_Item.note' accountItemList = self.db.getRecordList('Account_Item', fields, 'event_id = %s' % eventId) tableAccountItem = self.db.table('Account_Item') self.db.transaction() try: for accountItem in accountItemList: accountItem.setValue('date', toVariant(self.date)) if self.insurerInfis: accountItem.setValue( 'note', '%s\n$$insurer:%s$$' % (forceStringEx( accountItem.value('note')), self.insurerInfis)) sank = sluch.firstChildElement('SANK') refReason = None if sank: refReason = forceStringEx( sank.firstChildElement('S_OSN').text()) # refReason = forceString(sluch.firstChildElement('REFREASON').text()) accountId = forceRef(accountItem.value('master_id')) payStatusMask = self.getPayStatusMask(accountId) if oplata > 1 and refReason: refuseTypeId = self.getRefuseTypeId(refReason) accountItem.setValue('refuseType_id', toVariant(refuseTypeId)) accountItem.setValue('number', toVariant(u'Отказ по МЭК')) updateDocsPayStatus(accountItem, payStatusMask, CPayStatus.refusedBits) self.nRefused += 1 self.nProcessed += 1 else: accountItem.setValue('number', toVariant(u'Оплачено')) updateDocsPayStatus(accountItem, payStatusMask, CPayStatus.payedBits) self.nPayed += 1 self.nProcessed += 1 self.db.updateRecord(tableAccountItem, accountItem) self.accountIdSet.add(accountId) self.db.commit() except: self.db.rollback() QtGui.qApp.logCurrentException() raise
def processAccountItem(self, eventKey, eventElement, accInfo, MEKErrorList): eventId = self.getElementValue(eventElement, 'NHISTORY', isRequired=True, mekErrorList=MEKErrorList) oplata = forceInt( self.getElementValue(eventElement, 'OPLATA', isRequired=True, mekErrorList=MEKErrorList)) tableAccount = self._db.table('Account') tableAccountItem = self._db.table('Account_Item') tableEvent = self._db.table('Event') queryTable = tableAccount.innerJoin( tableAccountItem, tableAccountItem['master_id'].eq(tableAccount['id'])) queryTable = queryTable.innerJoin( tableEvent, tableEvent['id'].eq(tableAccountItem['event_id'])) recordList = self._db.getRecordList(queryTable, 'Account_Item.*', [ tableAccount['number'].eq(accInfo['number']), tableAccount['exposeDate'].eq(accInfo['exposeDate']), 'YEAR(%s) = %s' % (tableAccount['settleDate'], accInfo['year']), tableEvent['id'].eq(eventId) ]) recordEvent = self._db.getRecordEx(tableEvent, 'Event.*', tableEvent['id'].eq(eventId)) externalId = forceStringEx(recordEvent.value('externalId')) partsExternalId = externalId.strip().split('#') if len(partsExternalId) == 0: partsExternalId = [""] * 3 if len(partsExternalId) == 1: partsExternalId.extend([""] * 2) partsExternalId[2] = eventKey recordEvent.setValue( 'externalId', toVariant("#".join( [forceStringEx(part) for part in partsExternalId]))) # self._db.updateRecord(tableEvent.name(), recordEvent) sankElement = self.getElement(eventElement, 'SANK', isRequired=False) for record in recordList: # noinspection PyArgumentList record.setValue('date', toVariant(QtCore.QDate.currentDate())) accountId = forceRef(record.value('master_id')) payStatusMask = self.getPayStatusMask(accountId) if oplata > 1: refuseTypeId = self.getPayRefuseId( self.getElementValue(sankElement, 'S_OSN', isRequired=True, mekErrorList=MEKErrorList)) record.setValue('refuseType_id', toVariant(refuseTypeId)) record.setValue('number', toVariant(u'Отказ по МЭК')) updateDocsPayStatus(record, payStatusMask, CPayStatus.refusedBits) elif sankElement.isNull(): record.setValue('refuseType_id', toVariant(None)) record.setValue('number', toVariant(u'Оплачено')) updateDocsPayStatus(record, payStatusMask, CPayStatus.payedBits) self._db.updateRecord(tableAccountItem.name(), record) accInfo['countUpdate'] += 1
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))