def setRecord(self, record): self._itemId = forceRef(record.value(u'id')) serviceId = forceRef(record.value(u'service_id')) self.cmbService.setValue(serviceId) self.edtPrice.setValue(forceDecimal(record.value(u'price'))) self.edtAmount.setValue(forceDecimal(record.value(u'amount'))) self.edtSum.setValue(forceDecimal(record.value(u'sum'))) self.cmbUnit.setValue(u'unit_id') self.edtUET.setValue(forceDecimal(record.value(u'uet'))) if serviceId is None: otherName, otherSource = forceString(self.getServiceName(record)) otherSourceName = { self.EventSource: u'Событие', self.ActionSource: u'Действие', self.VisitSource: u'Посещение', self.ServiceSource: u'Услуга' }.get(otherSource, u'') if otherSourceName and otherName != CCol.invalid: self.lblServiceNameSource.setText(otherSourceName) self.lblServiceName.setText(otherName) masterId = forceRef( QtGui.qApp.db.translate(u'Account_Item', u'id', self._itemId, u'master_id')) self.cmbAccount.setCurrentIndex(self.accountIdList.index(masterId))
def __init__(self, name=u'', quantity=forceDecimal(1.0), price=forceDecimal(0.0), payStatus=None, department=0, discountInfo=(1, 0), userInfo=None, vat=VAT_0, clientId=None): self._name = name self._quantity = quantity self._price = price self._department = department self._discountType = discountInfo[0] self._discountValue = forceDecimal(discountInfo[1]) self._payStatus = payStatus self._isSelected = bool(payStatus == CPayStatus.exposed) self._payStatusChanged = False self._vat = vat self._clientId = clientId self.errorList = [] self.lastCheckInfo = {} self.userInfo = userInfo
def summ(self, withDiscount=False): discountSumm = self.quantity * self.price if withDiscount: if self._discountType == CCashRegisterDriverInfo.DiscountType.percent: discountSumm -= forceDecimal(discountSumm) * forceDecimal( self.discountValue) / forceDecimal(100) else: discountSumm -= forceDecimal(self.discountValue) return discountSumm
def discountValue(self, value): if value < CCheckItem.precision: value = forceDecimal(0) if self.discountType == CCashRegisterDriverInfo.DiscountType.percent: if value > forceDecimal(100): value = forceDecimal(100) elif self.discountType == CCashRegisterDriverInfo.DiscountType.currency: value = min(self.summ(False), value) self._discountValue = value
def build(self, params): begDate = params.get('begDate') endDate = params.get('endDate') statusOrg = params.get('statusOrg') partner = params.get('partner') isValid = params.get('isValid') query = selectData(begDate, endDate, statusOrg, isValid, partner) doc = QtGui.QTextDocument() cursor = QtGui.QTextCursor(doc) cursor.setCharFormat(CReportBase.ReportTitle) cursor.insertText(self.title()) cursor.insertBlock() self.dumpParams(cursor, params) cursor.insertBlock() tableColumns = [('10%', [u'Контрагент'], CReportBase.AlignLeft), ('10%', [u'Номер договора'], CReportBase.AlignLeft), ('10%', [u'Дата заключения'], CReportBase.AlignLeft), ('10%', [u'Дата окончания'], CReportBase.AlignLeft), ('20%', [u'Предмет договора'], CReportBase.AlignLeft), ('10%', [u'Сумма остатка'], CReportBase.AlignLeft)] table = createTable(cursor, tableColumns) table.mergeCells(0, 0, 1, 1) #Контрагент table.mergeCells(0, 0, 1, 1) #Номер договора table.mergeCells(0, 0, 1, 1) #Дата заключения table.mergeCells(0, 0, 1, 1) #Дата окончания table.mergeCells(0, 0, 1, 1) #Предмет договора table.mergeCells(0, 0, 1, 1) #Сумма остатка for record in query: i = table.addRow() table.setText( i, 0, forceString( self.db.translate(self.tblOrganisation, self.tblOrganisation['id'], forceInt(record.value('org_id')), self.tblOrganisation['shortName']))) table.setText(i, 1, forceString(record.value('number'))) table.setText(i, 2, forceString(record.value('begDate'))) table.setText(i, 3, forceString(record.value('endDate'))) table.setText(i, 4, forceString(record.value('subjectContract'))) table.setText( i, 5, forceDecimal( forceDecimal(record.value('total')) - forceDecimal(record.value('spent')))) return doc
def getClientList(self, record, params): begDate = params.get('begDate') endDate = params.get('endDate') isValid = params.get('isValid') protocolNum = params.get('protocolNum') resultString = u'' totalCount = forceDecimal(0) if not forceInt(record.value('clientId')) in self.clintIdList: query = selectEventsList(begDate, endDate, protocolNum, isValid, forceInt(record.value('clientId'))) while query.next(): rec = query.record() totalCount += (forceDecimal(rec.value('price')) * forceDecimal(rec.value('amount'))) resultString += forceString(rec.value('serviceName')) + u': ' + forceString(rec.value('price')) + u' * ' + forceString(rec.value('amount')) + u'\n' if resultString: resultString += u'Итого: ' + forceString(totalCount) self.clintIdList.append(forceInt(record.value('clientId'))) return resultString
def build(self, params): begDate = params.get('begDate') endDate = params.get('endDate') statusOrg = params.get('statusOrg') partner = params.get('partner') isValid = params.get('isValid') query = selectFinanceData(begDate, endDate, statusOrg, isValid, partner) doc = QtGui.QTextDocument() cursor = QtGui.QTextCursor(doc) cursor.setCharFormat(CReportBase.ReportTitle) cursor.insertText(self.title()) cursor.insertBlock() self.dumpParams(cursor, params) cursor.insertBlock() tableColumns = [ ('10%', [u'Контрагент'], CReportBase.AlignLeft), ('10%', [u'Номер договора'], CReportBase.AlignLeft), ('10%', [u'Дата заключения'], CReportBase.AlignLeft), ('10%', [u'Дата окончания'], CReportBase.AlignLeft), ('10%', [u'Сумма остатка'], CReportBase.AlignLeft), ('10%', [u'Сумма выписанных услуг'], CReportBase.AlignLeft), ('10%', [u'Сумма выставленных счетов'], CReportBase.AlignLeft), ('10%', [u'Сумма не выставленных счетов'], CReportBase.AlignLeft), ('10%', [u'Сумма не оплаченных счетов'], CReportBase.AlignLeft) ] table = createTable(cursor, tableColumns) table.mergeCells(0, 0, 1, 1) # Контрагент table.mergeCells(0, 0, 1, 1) # Номер договора table.mergeCells(0, 0, 1, 1) # Дата заключения table.mergeCells(0, 0, 1, 1) # Дата окончания table.mergeCells(0, 0, 1, 1) # Сумма остатка table.mergeCells(0, 0, 1, 1) # Сумма выписанных услуг table.mergeCells(0, 0, 1, 1) # Сумма выставленных счетов table.mergeCells(0, 0, 1, 1) # Сумма не выставленных счетов table.mergeCells(0, 0, 1, 1) # Сумма не оплаченных счетов while query.next(): record = query.record() i = table.addRow() table.setText( i, 0, forceString( self.db.translate(self.tblOrganisation, self.tblOrganisation['id'], forceInt(record.value('org_id')), self.tblOrganisation['shortName']))) table.setText(i, 1, forceString(record.value('number'))) table.setText(i, 2, forceString(record.value('begDate'))) table.setText(i, 3, forceString(record.value('endDate'))) table.setText( i, 4, forceDecimal( forceDecimal(record.value('total')) - forceDecimal(record.value('spent')))) table.setText(i, 5, forceDecimal(record.value('sumUsl'))) table.setText(i, 6, forceDecimal(record.value('sumAcc'))) table.setText(i, 7, forceDecimal(record.value('sumNotAcc'))) table.setText(i, 8, forceDecimal(record.value('sumNotPayed'))) return doc
def isCorrect(self): self.errorList = [] if self.quantity < 0: self.errorList.append(u'отрицательное количество') elif self.quantity < CCheckItem.precision: self.errorList.append(u'нулевое количество') if self.price < 0: self.errorList.append(u'отрицательная цена') elif self.price < CCheckItem.precision: self.errorList.append(u'нулевая цена') if self.department not in xrange(17): self.errorList.append(u'неверная секция: %d' % self.department) # Проверка корректности процентной скидки (тип = 1) if self.discountType == 1 and not ( forceDecimal(0) <= self.discountValue <= forceDecimal(100)): self.errorList.append(u'ошибочная скидка: %d%%' % self.discountValue) if self.payStatus not in [ None, CPayStatus.exposed, CPayStatus.payed, CPayStatus.refused ]: self.errorList.append(u'ошибочный статус оплаты: %d' % self.payStatus) return len(self.errorList) == 0
def createInstantAccount(eventId): """Создание счёта по всем действиям события. @param eventId: идентификатор события, которое будет выставлено в счета. """ db = QtGui.qApp.db tableAction = db.table('Action') tableActionType = db.table('ActionType') tableEvent = db.table('Event') tableContract = db.table('Contract') tableFinance = db.table('rbFinance') tableResult = db.table('rbResult') tablePaymentScheme = db.table('PaymentScheme') tablePaymentSchemeItem = db.table('PaymentSchemeItem') remainSum = None depositTable = tableContract.innerJoin(tableEvent, db.joinAnd([tableEvent['contract_id'].eq(tableContract['id']), tableEvent['id'].eq(eventId)])) depositRecord = db.getRecordEx(depositTable, 'Contract.deposit, Contract.id as contract_id, Contract.number as contract_number, Event.externalId, Event.eventType_id') deposit = forceDecimal(depositRecord.value('deposit')) eventContractId = forceRef(depositRecord.value('contract_id')) eventContractNumber = forceRef(depositRecord.value('contract_number')) eventExternalId = forceString(depositRecord.value('externalId')) eventTypeId = forceRef(depositRecord.value('eventType_id')) if deposit > 0: sumUsedRecord = db.getRecordEx('Account', 'SUM(Account.sum) as totalSum', 'Account.deleted = 0 AND Account.contract_id = %s' % eventContractId) sumUsed = forceDecimal(sumUsedRecord.value('totalSum')) remainSum = deposit - sumUsed if remainSum <= 0: QtGui.QMessageBox.critical(None, u'Внимание!', u'Выставление счета невозможно, так как сумма депозита по договору %s исчерпана.' % eventContractNumber, QtGui.QMessageBox.Ok, QtGui.QMessageBox.Ok ) return table = tableAction table = table.leftJoin(tableActionType, tableActionType['id'].eq(tableAction['actionType_id'])) table = table.leftJoin(tableEvent, tableEvent['id'].eq(tableAction['event_id'])) table = table.leftJoin(tableContract, 'Contract.id = IF(Action.contract_id IS NULL, Event.contract_id, Action.contract_id)') table = table.leftJoin(tableFinance, tableFinance['id'].eq(tableContract['finance_id'])) table = table.leftJoin(tableResult, tableResult['id'].eq(tableEvent['result_id'])) cond = [ tableAction['deleted'].eq(0), tableAction['event_id'].eq(eventId), '(Action.payStatus & (3 << 2 * CAST(%s AS UNSIGNED ))) = 0' % tableFinance['code'].name(), #getPayStatusMaskByCode(CFinanceType.cash) db.joinOr([tableResult['notAccount'].eq(0), tableResult['notAccount'].isNull()]), db.joinOr([tableActionType['class'].ne(ActionClass.Analyses), tableAction['parent_id'].isNotNull()]) # только дочерние дествия со вкладки "Анализы" ] mapContractIdToActionIdList = defaultdict(list) for record in db.iterRecordList(table, [tableContract['id'].alias('contract_id'), tableAction['id'].alias('action_id')], cond): contractId = forceRef(record.value('contract_id')) actionId = forceRef(record.value('action_id')) mapContractIdToActionIdList[contractId].append(actionId) accountIdList = [] try: today = QtCore.QDate.currentDate() franchisPercent = getFranchisePercentByEvent(eventId) db.transaction() for contractId in sorted(mapContractIdToActionIdList.keys()): builder = CAccountBuilder() contractInfo = getContractInfo(contractId) accountPool = CAccountPool(contractInfo, QtGui.qApp.currentOrgId(), QtGui.qApp.currentOrgStructureId(), today, False) actionIdList = sorted(mapContractIdToActionIdList[contractId]) builder.exposeByActions(None, contractInfo, accountPool.getAccount, actionIdList, today, franchisePercent=franchisPercent) accountPool.updateDetails() if getExternalIdAsAccountNumber(eventTypeId): for details in accountPool.getDetailsList(): details.changeNumber(eventExternalId, step=True, fromZero=True) if contractId == eventContractId and remainSum != None: exposedSum = 0 for details in accountPool.getDetailsList(): exposedSum += (details.totalSum * (franchisPercent/100.0)) if franchisPercent else details.totalSum paySchemeId = forceInt( db.translate(tablePaymentSchemeItem, tablePaymentSchemeItem['contract_id'], contractId, tablePaymentSchemeItem['paymentScheme_id'])) if paySchemeId: recPayScheme = db.getRecordEx(tablePaymentScheme, '*', tablePaymentScheme['id'].eq(paySchemeId)) remainSumPayScheme = forceDecimal(recPayScheme.value('total')) - forceDecimal(recPayScheme.value('spent')) if exposedSum > remainSumPayScheme: QtGui.QMessageBox.critical(None, u'Внимание!', u'Выставление счета невозможно, так как выставляемая сумма превышает сумму схемы оплаты %s.' % forceString(recPayScheme.value('numberProtocol')), QtGui.QMessageBox.Ok, QtGui.QMessageBox.Ok) db.rollback() return else: recPayScheme.setValue('spent', toVariant(forceDecimal(recPayScheme.value('spent')) + forceDecimal(exposedSum))) db.updateRecord(tablePaymentScheme, recPayScheme) if exposedSum > remainSum: QtGui.QMessageBox.critical(None, u'Внимание!', u'Выставление счета невозможно, так как выставляемая сумма превышает сумму депозита по договору %s.' % eventContractNumber, QtGui.QMessageBox.Ok, QtGui.QMessageBox.Ok) db.rollback() return if contractInfo.endDate: if forceDate(contractInfo.endDate) > QtCore.QDate.currentDate(): QtGui.QMessageBox.critical(None, u'Внимание!', u'Выставление счета невозможно, так как срок действия договора %s истек.' % eventContractNumber, QtGui.QMessageBox.Ok, QtGui.QMessageBox.Ok) db.rollback() return accountIdList += accountPool.getAccountIdList() db.commit() except: db.rollback() raise if accountIdList: dialog = CInstantAccountDialog(QtGui.qApp.mainWindow, eventId) dialog.setAccountIdList(accountIdList) dialog.exec_() else: QtGui.QMessageBox.information( QtGui.qApp.mainWindow, u'Создание счёта по событию', u'Счёт не создан, так как нечего выставлять.', QtGui.QMessageBox.Ok, QtGui.QMessageBox.Ok)
def fillAmbEventSteps(self, event, eventId): def addMedRecord(currentStep, medRecord): if hasattr(currentStep, 'MedRecords'): currentStep.MedRecords.MedRecord.append(medRecord) else: currentStep.MedRecords = self.emk.factory.create( 'ns6:ArrayOfMedRecord') currentStep.MedRecords.MedRecord = [medRecord] ambStepRecordsList = self.db.getRecordList(stmt=VISIT_AMB_STEPS_STMT % eventId) if not ambStepRecordsList: return False event.Steps = self.emk.factory.create('ns9:ArrayOfStepAmb') event.Steps.StepAmb = [] for r in ambStepRecordsList: step = self.emk.factory.create('ns9:StepAmb') step.DateStart = forceDateTuple(r.value('DateStart')) step.DateEnd = forceDateTuple(r.value('DateEnd')) step.IdPaymentType = forceRef(r.value('IdPaymentType')) step.Doctor = self.getMedicalStaff(record=r) step.IdStepMis = forceStringEx(r.value('IdStepMis')) step.IdVisitPlace = forceRef(r.value('IdVisitPlace')) step.IdVisitPurpose = forceRef(r.value('IdVisitPurpose')) serviceRec = getVisitServiceRecord(self.db, forceRef(r.value('visitId'))) if serviceRec: service = self.emk.factory.create('ns6:Service') service.DateStart = forceDateTuple( serviceRec.value('DateStart')) service.DateEnd = forceDateTuple(serviceRec.value('DateEnd')) service.IdServiceType = forceString( serviceRec.value('IdServiceType')) service.ServiceName = forceString( serviceRec.value('ServiceName')) service.PaymentInfo = self.emk.factory.create( 'ns6:PaymentInfo') service.PaymentInfo.HealthCareUnit = forceString( serviceRec.value('HealthCareUnit')) service.PaymentInfo.IdPaymentType = forceString( serviceRec.value('IdPaymentType')) service.PaymentInfo.PaymentState = forceInt( serviceRec.value('PaymentState')) service.PaymentInfo.Quantity = forceInt( serviceRec.value('Quantity')) service.PaymentInfo.Tariff = forceDecimal( serviceRec.value('Tariff')) service.Performer = self.emk.factory.create('ns6:Performer') service.Performer.Doctor = self.getMedicalStaff(record=r) service.Performer.IdRole = 3 # addMedRecord(step, service) drugRecipeRecList = getDrugRecipeRecordList(self.db, eventId) for recipeRec in drugRecipeRecList: recipe = self.emk.factory.create('ns835:AppointedMedication') recipe.AnatomicTherapeuticChemicalClassification = forceString( recipeRec.value('ATCC')) recipe.CourseDose = self.emk.factory.create('ns835:CourseDose') recipe.CourseDose.IdUnit = forceInt( recipeRec.value('CourseDoseIdUnit')) recipe.CourseDose.Value = forceDecimal( recipeRec.value('CourseDoseValue')) recipe.DayDose = self.emk.factory.create('ns835:DayDose') recipe.DayDose.IdUnit = forceInt( recipeRec.value('DayDoseIdUnit')) recipe.DayDose.Value = forceDecimal( recipeRec.value('DayDoseValue')) recipe.DaysCount = forceInt(recipeRec.value('DaysCount')) recipe.Doctor = self.getMedicalStaff( personId=forceInt(recipeRec.value('IdPersonMis'))) recipe.IssuedDate = forceDateTuple( recipeRec.value('IssuedDate')) recipe.MedicineIssueType = forceString( recipeRec.value('MedicineIssueType')) recipe.MedicineName = forceString( recipeRec.value('MedicineName')) recipe.MedicineType = forceInt(recipeRec.value('MedicineType')) recipe.MedicineUseWay = forceInt( recipeRec.value('MedicineUseWay')) recipe.Number = forceString(recipeRec.value('Number')) recipe.OneTimeDose = self.emk.factory.create( 'ns835:OneTimeDose') recipe.OneTimeDose.IdUnit = forceInt( recipeRec.value('DayDoseIdUnit')) recipe.OneTimeDose.Value = forceDecimal( recipeRec.value('DayDoseValue')) recipe.Seria = forceString(recipeRec.value('Seria')) addMedRecord(step, recipe) event.Steps.StepAmb.append(step) return True
def build(self,params): begDate = params.get('begDate') endDate = params.get('endDate') isValid = params.get('isValid') group = params.get('group') protocolNum = params.get('protocolNum') if forceInt(group): query = selectEventsList(begDate, endDate, protocolNum, isValid) doc = QtGui.QTextDocument() cursor = QtGui.QTextCursor(doc) cursor.setCharFormat(CReportBase.ReportTitle) cursor.insertText(self.title()) cursor.insertBlock() self.dumpParams(cursor, params) cursor.insertBlock() names = self.getVisitsList(forceInt(self.db.translate('PaymentScheme', 'numberProtocol', protocolNum, 'id'))) tableColumns = [('20%', [u'Пациент'], CReportBase.AlignLeft)] for v in names: tableColumns.append(('10%', forceString(v), CReportBase.AlignLeft)) table = createTable(cursor, tableColumns) while query.next(): columnsCount = len(names) record = query.record() i = table.addRow() table.setText(i, 0, forceString(record.value('lastName')) + u' ' + forceString(record.value('firstName')) + u' ' + forceString(record.value('patrName'))) for count in xrange(columnsCount): table.setText(i, count + 1, self.getVisitDone(record, params, names[count])) return doc else: query = selectEventsList(begDate, endDate, protocolNum, isValid) doc = QtGui.QTextDocument() cursor = QtGui.QTextCursor(doc) cursor.setCharFormat(CReportBase.ReportTitle) cursor.insertText(self.title()) cursor.insertBlock() self.dumpParams(cursor, params) cursor.insertBlock() tableColumns = [('20%', [u'Пациент'], CReportBase.AlignLeft), ('10%', [u'Номер визита'], CReportBase.AlignLeft), ('60%', [u'Сумма оказанных услуг'], CReportBase.AlignLeft), ('10%', [u'Статус визита'], CReportBase.AlignLeft)] table = createTable(cursor, tableColumns) while query.next(): record = query.record() i = table.addRow() table.setText(i, 0, forceString(record.value('lastName')) + u' ' + forceString(record.value('firstName')) + u' ' + forceString(record.value('patrName'))) table.setText(i, 1, forceString(record.value('protocolName'))) table.setText(i, 2, forceString(self.getClientList(record, params))) table.setText(i, 3, forceString(self.checkOnClose(record)) + u'оплачен' if forceDecimal(record.value('sumUsl')) == forceDecimal(record.value('sumPayed')) else self.checkOnClose(record) + u'не оплачен') return doc
def fillTable(self, table, eventId): db = QtGui.qApp.db results = [] event = db.getRecord( table='Event ' ' LEFT JOIN Person ON Person.id = Event.execPerson_id' ' LEFT JOIN mes.MES ON MES.id = Event.MES_id' ' LEFT JOIN rbService ON rbService.code = MES.code', cols=[ 'Event.client_id', 'Event.setDate', 'Event.execDate', 'Event.eventType_id', 'Event.MES_id', 'rbService.id as serviceId', 'Person.tariffCategory_id', 'Event.contract_id' ], itemId=eventId) eventContractId = forceRef(event.value('contract_id')) contractInfo = getContractInfo(eventContractId) eventEndDate = forceDate(event.value('execDate')) eventTypeId = forceRef(event.value('eventType_id')) tariffCategoryId = forceRef(event.value('tariffCategory_id')) eventBegDate = forceDateTime(event.value('setDate')) mesId = forceRef(event.value('MES_id')) clientId = forceRef(event.value('client_id')) # Случай лечения tariffList = contractInfo.tariffByEventType.get(eventTypeId, []) for tariff in tariffList: if isTariffApplicable(tariff, eventId, tariffCategoryId, eventEndDate, mapEventIdToMKB=self.mapEventIdToMKB): serviceId = getEventServiceId(eventTypeId) price = tariff.price federalPrice = 0 if contractInfo.isConsiderFederalPrice: federalPrice = tariff.federalPrice discount = getClientDiscountInfo(clientId)[0] price *= 1.0 - discount sum = round((price + federalPrice), 2) results.append((forceString( db.translate('rbService', 'id', serviceId, 'name')), sum)) break # Визит по МЭС serviceId = forceRef(event.value('serviceId')) tariffList = contractInfo.tariffVisitsByMES.get( (eventTypeId, serviceId), []) for tariff in tariffList: if isTariffApplicable(tariff, eventId, tariffCategoryId, eventEndDate, mapEventIdToMKB=self.mapEventIdToMKB): amount = float(getMesAmount(eventId, mesId)) federalPrice = 0 if contractInfo.isConsiderFederalPrice: federalPrice = tariff.federalPrice amount, price, sum = tariff.evalAmountPriceSum( amount, clientId) sum = round((price + federalPrice) * amount, 2) results.append((forceString( db.translate('rbService', 'id', serviceId, 'name')), sum)) break # Обращение по МЭС tariffDate = eventEndDate # Дата для выбора подходящего тарифа tariffList = contractInfo.tariffEventByMES.get( (eventTypeId, serviceId), []) eventLengthDays = getEventLengthDays(eventBegDate, eventEndDate, True, eventTypeId) # Если включена опция "Учитывать максимальную длительность по стандарту" if contractInfo.exposeByMESMaxDuration: # Получаем максимальную длительность текущего МЭС mesMaxDuration = CMesInfo(self.infoContext, mesId).maxDuration else: # В качестве максимальной используем реальную длительность события mesMaxDuration = eventLengthDays # Если максимальная длительность события по МЭС меньше реальной if mesMaxDuration < eventLengthDays: purposeCode = getEventPurposeCode(eventTypeId) # Для обращений с типом назначения "заболевание", "профилактика" или "патронаж" if purposeCode in ['1', '2', '3']: # Дата, по которой ищется нужный тариф, получается путем добавления к дате начала обращения максимальной длительности с учетом выходных tariffDate = addPeriod(eventBegDate, mesMaxDuration, True) # Для обращений с типом назначения "Реабилитация" или "Стационар" elif purposeCode in ['7', '10']: # Дата, по которой ищется нужный тариф, получается путем добавления к дате начала обращения максимальной длительности без учета выходных tariffDate = addPeriod(eventBegDate, mesMaxDuration, False) for tariff in tariffList: if isTariffApplicable(tariff, eventId, tariffCategoryId, tariffDate, mapEventIdToMKB=self.mapEventIdToMKB): if tariff.tariffType == CTariff.ttEventByMESLen: amount = eventLengthDays else: amount = 1 federalPrice = 0 if contractInfo.isConsiderFederalPrice: federalPrice = tariff.federalPrice amount, price, sum = tariff.evalAmountPriceSum( amount, clientId) sum = round((price + federalPrice) * amount, 2) results.append((forceString( db.translate('rbService', 'id', serviceId, 'name')), sum)) break # Визиты visitStmt = db.selectStmt( table='Visit' ' LEFT JOIN Person ON Person.id = Visit.person_id', fields=[ 'Visit.id', 'Visit.event_id', 'Visit.date', 'Visit.service_id', 'Person.tariffCategory_id', 'Person.speciality_id', ], where='Visit.event_id = %s AND Visit.deleted = 0' % eventId) visitQuery = db.query(visitStmt) while visitQuery.next(): visit = visitQuery.record() serviceId = forceRef(visit.value('service_id')) tariffList = contractInfo.tariffByVisitService.get(serviceId, None) if tariffList: visitDate = forceDate(visit.value('date')) specialityId = forceRef(visit.value('speciality_id')) tariffCategoryId = forceRef(visit.value('tariffCategory_id')) for tariff in tariffList: if isTariffApplicable( tariff, eventId, tariffCategoryId, visitDate, mapEventIdToMKB=self.mapEventIdToMKB): if not tariff.specialityId or specialityId == tariff.specialityId: price = tariff.price federalPrice = 0 if contractInfo.isConsiderFederalPrice: federalPrice = tariff.federalPrice discount = getClientDiscountInfo(clientId)[0] price *= 1.0 - discount amount = 1.0 sum = round((price + federalPrice) * amount, 2) results.append((forceString( db.translate('rbService', 'id', serviceId, 'name')), sum)) actionStmt = db.selectStmt( table='Action' ' LEFT JOIN Person ON Person.id = Action.person_id' ' LEFT JOIN mes.MES ON MES.id = Action.MES_id' ' LEFT JOIN rbService ON rbService.code = MES.code', fields=[ 'Action.id', 'Action.actionType_id', 'Action.event_id, Action.begDate', 'Action.endDate', 'Action.amount', 'Action.MKB', 'Person.tariffCategory_id', 'Action.MES_id', 'Action.contract_id', 'rbService.id as serviceId' ], where='Action.event_id = %s AND Action.deleted = 0' % eventId) actionQuery = db.query(actionStmt) while actionQuery.next(): success = False action = actionQuery.record() actionContractId = forceRef(action.value('contract_id')) if actionContractId and actionContractId != eventContractId: actionContractInfo = getContractInfo(actionContractId) else: actionContractInfo = contractInfo serviceId = forceRef(action.value('serviceId')) tariffList = actionContractInfo.tariffActionsByMES.get( (eventTypeId, serviceId), None) amount = getActionLengthDays(forceDate(action.value('begDate')), forceDate(action.value('endDate')), True, eventTypeId) if tariffList: endDate = forceDate(action.value('endDate')) MKB = forceString(action.value('MKB')) tariffCategoryId = forceRef(action.value('tariffCategory_id')) for tariff in tariffList: if isTariffApplicable( tariff, eventId, tariffCategoryId, endDate, MKB, mapEventIdToMKB=self.mapEventIdToMKB): amount, price, sum = tariff.evalAmountPriceSum( amount, clientId) results.append((forceString( db.translate('rbService', 'id', serviceId, 'name')), sum)) success = True break if success: continue serviceIdList = CMapActionTypeIdToServiceIdList.getActionTypeServiceIdList( forceRef(action.value('actionType_id')), actionContractInfo.finance_id) origAmount = forceDecimal(action.value('amount')) for serviceId in serviceIdList: tariffList = actionContractInfo.tariffByActionService.get( serviceId, None) if tariffList: endDate = forceDate(action.value('endDate')) MKB = forceString(action.value('MKB')) tariffCategoryId = forceRef( action.value('tariffCategory_id')) for tariff in tariffList: if isTariffApplicable( tariff, eventId, tariffCategoryId, endDate, MKB, mapEventIdToMKB=self.mapEventIdToMKB): federalPrice = 0 if actionContractInfo.isConsiderFederalPrice: federalPrice = tariff.federalPrice amount, price, sum = tariff.evalAmountPriceSum( origAmount, clientId) sum += federalPrice * amount results.append((forceString( db.translate('rbService', 'id', serviceId, 'name')), sum)) break for result in results: i = table.addRow() table.setText(i, 0, result[0]) table.setText(i, 1, result[1])
def setValue(self, item, value): decValue = forceDecimal(value) super(CDecimalAttribCol, self).setValue(item, decValue)
def totalSumm(self, onlySelected=True, withDiscount=False): totalSumm = forceDecimal(0.0) for item in self.items(): if item.isSelected or not onlySelected: totalSumm += item.summ(withDiscount) return totalSumm
def setData(self, index, value, role=QtCore.Qt.EditRole): if not index.isValid(): return False row = index.row() column = index.column() rowCount = self.rowCount() if row not in xrange(rowCount): return False if self._editable and row == (rowCount - 1): self.beginInsertRows(index.parent(), row, row) self._items.append(CCheckItem(payStatus=None)) self.endInsertRows() if role == QtCore.Qt.CheckStateRole and column == self.columnInfo[ 'name']['index']: item = self.items()[row] item.isSelected = (value != QtCore.Qt.Unchecked) checkResult, checkMessage, canIgnore = self.checkItemSelect(item) if not checkResult: buttons = QtGui.QMessageBox.Ok if canIgnore: buttons |= QtGui.QMessageBox.Ignore userChoise = QtGui.QMessageBox.warning( QtGui.qApp.activeWindow(), u'Внимание!', checkMessage, buttons=buttons, defaultButton=QtGui.QMessageBox.Ok) if userChoise == QtGui.QMessageBox.Ok: item.isSelected = not item.isSelected return False self.dataChanged.emit(index, index) return True if role == QtCore.Qt.EditRole and self._editable: item = self.items()[row] sumIndex = self.index(index.row(), self.columnInfo['sum']['index']) if column == self.columnInfo['name']['index']: item.name = forceString(value) self.dataChanged.emit(index, index) return True elif column == self.columnInfo['quantity']['index']: newValue = forceDecimal(value) if newValue < forceDecimal(0): return False item.quantity = newValue self.dataChanged.emit(index, sumIndex) return True elif column == self.columnInfo['price']['index']: newValue = forceDecimal(value) if newValue < forceDecimal(0): return False item.price = newValue self.dataChanged.emit(index, sumIndex) return True elif column == self.columnInfo['discount']['index']: newValue = forceDecimal(value) if newValue <= CCheckItem.precision: newValue = forceDecimal(0) item.discountType = CCashRegisterDriverInfo.DiscountType.percent item.discountValue = forceDecimal(value) return True elif column == self.columnInfo['vat']['index']: item.vat = forceInt(value) return True return False
def processCheck(self, checkType, password, operationInfo=None, enableCheckSum=False, doublePrintCheck=False): self.serviceLog( msg=u""" [0] Значение аргументов функции `processCheck`: * checkType = {checkType} * password = {password} * operationInfo.operationTypeId = {operationTypeId} * enableCheckSum = {enableCheckSum} * doublePrintCheck = {doublePrintCheck} """.format( checkType=checkType, password=password, operationTypeId=operationInfo.operationTypeId if operationInfo else operationInfo, enableCheckSum=enableCheckSum, doublePrintCheck=doublePrintCheck ) ) result = False if not self.isCorrect(True): self.serviceLog(msg=u'[0.1] Выход из функции: Состояние ККМ не корректно') return result if not self.isSessionOpened(): self.onError(u'Не открыта смена', False) return result items = self.model().selectedItems() if not items: self.onError(u'Не выбрано элементов для внесения в чек', False) return result log(logDir=QtGui.qApp.logDir, title=u'Касса. Пытаемся провести операцию', message=u'\n'.join([unicode(item) for item in items])) self._isCanceled = False isOpenned = False totalSumm = forceDecimal(0.0) newPayStatusInfoList = [] try: self.serviceLog(msg=u'[1] Вход в блок операций') if not self.setMode(1, password): # 1 - Режим регистрации return result if self.openCheck(checkType): self.serviceLog(msg=u'[1.1] Открываем чек: чек открыт') isOpenned = True else: self.serviceLog(msg=u'[1.2] Открываем чек: чек открыть не удалось') return result self.serviceLog(msg=u'[2] Вход в цикл обработки позиций в чеке') for item in items: if self._isCanceled or not self.isCorrect(): self.serviceLog(msg=u'[2.1.1] Отмена операции /%s/' % item.name) self.cancelCheck() self.nextProgressStep.emit(u'Отменено') break else: self.serviceLog(msg=u'[2.1.2] Регистрация позиции чека /%s/' % item.name) self.nextProgressStep.emit(u'Регистрация') # Заполняем так, поскольку мало ли при заполнении `self._ecrDriver` летит exception self.serviceLog(msg=u""" [2.2] Заполнение структуры позиции чека * checkType = {checkType} /* CCashRegisterDriverInfo.CheckType */ * TestMode = {testMode} * TextWrap = 1 # 0 - нет переноса, 1 - перенос по словам, 2 - перенос по строке * Name = {itemName} * Quantity = {quantity} * Price = {price} * Department = {department} * DiscountType = {discountType} * DiscountValue = {discountValue} * TaxTypeNumber = {vat} """.format( checkType=checkType, testMode=self._testMode, itemName=item.name, quantity=forceDouble(item.quantity), price=forceDouble(item.price), department=item.department, discountType=item.discountType, discountValue=forceDouble(item.discountValue) if item.discountValue > item.precision else 0.0, vat=item.vat )) self._ecrDriver.TestMode = self._testMode self._ecrDriver.TextWrap = 1 # 0 - нет переноса, 1 - перенос по словам, 2 - перенос по строке self._ecrDriver.Name = item.name self._ecrDriver.Quantity = forceDouble(item.quantity) self._ecrDriver.Price = forceDouble(item.price) self._ecrDriver.Department = item.department self._ecrDriver.DiscountType = item.discountType self._ecrDriver.DiscountValue = forceDouble(item.discountValue) if item.discountValue > item.precision else 0.0 self._ecrDriver.TaxTypeNumber = item.vat self.serviceLog(msg=u'[2.3] Выбор типа операции') if checkType == CCashRegisterDriverInfo.CheckType.returnSale: self.serviceLog(msg=u'[2.3.1] Тип операции: ВОЗВРАТ') self.returnSale(item, enableCheckSum) newPayStatus = CPayStatus.exposed elif checkType == CCashRegisterDriverInfo.CheckType.annulateSale: self.serviceLog(msg=u'[2.3.2] Тип операции: АННУЛИРОВАНИЕ') self.annulateSale(item, enableCheckSum) newPayStatus = CPayStatus.exposed else: self.serviceLog(msg=u'[2.3.1] Тип операции: ПРОДАЖА (РЕГИСТРАЦИЯ)') self.registration(item) newPayStatus = CPayStatus.payed self.serviceLog(msg=u'[2.4] Внесение результатов в ВМ /%s/' % item.name) newPayStatusInfoList.append((item, newPayStatus)) item.isSelected = False totalSumm += item.quantity * item.price QtGui.qApp.processEvents() # end for except Exception, e: self.onException(e) if isOpenned: self.cancelCheck()
def build(self, params): begDate = params.get('begDate') endDate = params.get('endDate') partner = params.get('partner') isValid = params.get('isValid') orgStruct = params.get('orgStruct') researcher = params.get('researcher') isEnrollment = params.get('enrollment') query = selectFinanceData(begDate, endDate, partner, isValid, orgStruct, researcher, isEnrollment) doc = QtGui.QTextDocument() cursor = QtGui.QTextCursor(doc) cursor.setCharFormat(CReportBase.ReportTitle) cursor.insertText(self.title()) cursor.insertBlock() self.dumpParams(cursor, params) cursor.insertBlock() tableColumns = [ ('10%', [u'Подразделение'], CReportBase.AlignLeft), ('10%', [u'Главный исследователь'], CReportBase.AlignLeft), ('20%', [u'Контрагент'], CReportBase.AlignLeft), ('10%', [u'Номер договора'], CReportBase.AlignLeft), ('10%', [u'Номер протокола'], CReportBase.AlignLeft), ('10%', [u'Действующий'], CReportBase.AlignLeft), ('10%', [u'Сумма выписанных услуг'], CReportBase.AlignLeft), ('10%', [u'Сумма выставленных счетов'], CReportBase.AlignLeft), ('10%', [u'Сумма не выставленных счетов'], CReportBase.AlignLeft), ('10%', [u'Сумма не оплаченных счетов'], CReportBase.AlignLeft) ] table = createTable(cursor, tableColumns) table.mergeCells(0, 0, 1, 1) # Подразделение table.mergeCells(0, 0, 1, 1) # Главный исследователь table.mergeCells(0, 0, 1, 1) # Контрагент table.mergeCells(0, 0, 1, 1) # Номер договора table.mergeCells(0, 0, 1, 1) # Номер протокола table.mergeCells(0, 0, 1, 1) # Действующий table.mergeCells(0, 0, 1, 1) # Сумма выписанных услуг table.mergeCells(0, 0, 1, 1) # Сумма выставленных счетов table.mergeCells(0, 0, 1, 1) # Сумма не выставленных счетов table.mergeCells(0, 0, 1, 1) # Сумма не оплаченных счетов while query.next(): record = query.record() i = table.addRow() recPerson = self.db.getRecordEx( self.tblPrson, '*', self.tblPrson['id'].eq(forceInt(record.value('person_id')))) table.setText( i, 0, forceString( self.db.translate( self.tblOrgStruct, self.tblOrgStruct['id'], forceInt(record.value('orgStructure_id')), self.tblOrgStruct['name']))) table.setText( i, 1, forceString( forceString(recPerson.value('lastName')) + u' ' + forceString(recPerson.value('firstName')) + u' ' + forceString(recPerson.value('patrName')))) table.setText( i, 2, forceString( self.db.translate(self.tblOrganisation, self.tblOrganisation['id'], forceInt(record.value('org_id')), self.tblOrganisation['shortName']))) table.setText(i, 3, forceString(record.value('number'))) table.setText(i, 4, forceString(record.value('numberProtocol'))) table.setText( i, 5, u'Действующий' if forceDate(record.value('endDate')) > QtCore.QDate.currentDate() else u'Недействующий') table.setText(i, 6, forceDecimal(record.value('sumUsl'))) table.setText(i, 7, forceDecimal(record.value('sumAcc'))) table.setText(i, 8, forceDecimal(record.value('sumNotAcc'))) table.setText(i, 9, forceDecimal(record.value('sumNotPayed'))) return doc