def setRecord(self, record): CItemEditorBaseDialog.setRecord(self, record) setLineEditValue(self.edtCode, record, 'code') setLineEditValue(self.edtName, record, 'name') setLineEditValue(self.edtShortName, record, 'shortName') setLineEditValue(self.edtOKSOName, record, 'OKSOName') setLineEditValue(self.edtOKSOCode, record, 'OKSOCode') setLineEditValue(self.edtFederalCode, record, 'federalCode') setLineEditValue(self.edtRegionalCode, record, 'regionalCode') setLineEditValue(self.edtSyncGUID, record, 'syncGUID') setRBComboBoxValue(self.cmbLocalService, record, 'service_id') setRBComboBoxValue(self.cmbProvinceService, record, 'provinceService_id') setRBComboBoxValue(self.cmbOtherService, record, 'otherService_id') setRBComboBoxValue(self.cmbFundingService, record, 'fundingService_id') setComboBoxValue(self.cmbSex, record, 'sex') (begUnit, begCount, endUnit, endCount) = parseAgeSelector(forceString(record.value('age'))) versSpec = forceStringEx(record.value('versSpec')) self.cmbVersSpec.setCurrentIndex({ 'v004': 1, 'v015': 2 }.get(versSpec.lower(), 0)) self.cmbBegAgeUnit.setCurrentIndex(begUnit) self.edtBegAgeCount.setText(str(begCount)) self.cmbEndAgeUnit.setCurrentIndex(endUnit) self.edtEndAgeCount.setText(str(endCount)) setLineEditValue(self.edtMKBFilter, record, 'mkbFilter') self.modelQueueShare.load(self.itemId())
def checkContingentDDGlobalPreference(self): self._contingentDDAgeSelectors = [] self._contingentDDEventTypeCodes = [] filterDD = self._globalPreferences.get('52', u'').replace(' ', '') delimInd = filterDD.find(';') if delimInd == -1: return False ageSelectors = filterDD[:delimInd] for selectorTuple in parseAgeSelector(ageSelectors, True): if not selectorTuple: return False begUnit, begCount, endUnit, endCount, step, useCalendarYear, useExlusion = selectorTuple begAge, endAge = convertAgeSelectorToAgeRange((begUnit, begCount, endUnit, endCount)) if begAge > endAge: return False self._contingentDDAgeSelectors.append((begAge, endAge, step, useCalendarYear, useExlusion)) eventTypeCodes = filterDD[delimInd + 1:] if not eventTypeCodes: return False self._contingentDDEventTypeCodes = eventTypeCodes.split(',') return True
def _load(self, actionTypeId): record = QtGui.qApp.db.getRecord(self._table, '*', actionTypeId) setComboBoxValue(self.cmbSex, record, 'sex') (begUnit, begCount, endUnit, endCount) = parseAgeSelector(forceString(record.value('age'))) self.cmbBegAgeUnit.setCurrentIndex(begUnit) self.edtBegAgeCount.setText(str(begCount)) self.cmbEndAgeUnit.setCurrentIndex(endUnit) self.edtEndAgeCount.setText(str(endCount)) setComboBoxValue(self.cmbDefaultStatus, record, 'defaultStatus') setComboBoxValue(self.cmbDefaultDirectionDate, record, 'defaultDirectionDate') setComboBoxValue(self.cmbDefaultPlannedEndDate, record, 'defaultPlannedEndDate') setComboBoxValue(self.cmbDefaultBeginDate, record, 'defaultBeginDate') setComboBoxValue(self.cmbDefaultEndDate, record, 'defaultEndDate') setRBComboBoxValue(self.cmbDefaultExecPerson, record, 'defaultExecPerson_id') setComboBoxValue(self.cmbDefaultPersonInEvent, record, 'defaultPersonInEvent') setComboBoxValue(self.cmbDefaultPersonInEditor, record, 'defaultPersonInEditor') self.cmbDefaultOrg.setValue(forceRef(record.value('defaultOrg_id'))) setComboBoxValue(self.cmbDefaultMKB, record, 'defaultMKB') setComboBoxValue(self.cmbDefaultMorphology, record, 'defaultMorphology') setComboBoxValue(self.cmbIsMorphologyRequired, record, 'isMorphologyRequired') setLineEditValue(self.edtOffice, record, 'office') setCheckBoxValue(self.chkShowInForm, record, 'showInForm') setCheckBoxValue(self.chkShowTime, record, 'showTime') setCheckBoxValue(self.chkShowAPOrg, record, 'showAPOrg') setCheckBoxValue(self.chkShowAPNotes, record, 'showAPNotes') setCheckBoxValue(self.chkRequiredCoordination, record, 'isRequiredCoordination') setComboBoxValue(self.cmbAssistantRequired, record, 'hasAssistant') setLineEditValue(self.edtContext, record, 'context') setCheckBoxValue(self.chkIsPreferable, record, 'isPreferable') setSpinBoxValue(self.edtAmount, record, 'amount') setSpinBoxValue(self.edtMaxOccursInEvent, record, 'maxOccursInEvent') setComboBoxValue(self.cmbServiceType, record, 'serviceType') setCheckBoxValue(self.chkPropertyAssignedVisible, record, 'propertyAssignedVisible') setCheckBoxValue(self.chkPropertyUnitVisible, record, 'propertyUnitVisible') setCheckBoxValue(self.chkPropertyNormVisible, record, 'propertyNormVisible') setCheckBoxValue(self.chkPropertyEvaluationVisible, record, 'propertyEvaluationVisible') setSpinBoxValue(self.edtRecommendationExpirePeriod, record, 'recommendationExpirePeriod') setCheckBoxValue(self.chkRecommendationControl, record, 'recommendationControl') setCheckBoxValue(self.chkExecRequiredForEventExec, record, 'isExecRequiredForEventExec') setCheckBoxValue(self.chkIgnoreEventEndDate, record, 'isIgnoreEventExecDate')
def getRBNetValues(self): db = QtGui.qApp.db recordList = db.getRecordList('rbNet') self.nets = {} for record in recordList: netId = forceRef(record.value('id')) netSex = forceInt(record.value('sex')) netAge = forceString(record.value('age')) self.nets[netId] = { 'sex': netSex, 'ageSelector': parseAgeSelector(netAge) }
def recordAcceptable(specialityId, sex, age): if specialityId: if specialityId != self.personSpecialityId: return False if sex: if sex != self.clientSex: return False if age: if self.clientAge == None: return False ageSelector = parseAgeSelector(age) return checkAgeSelector(ageSelector, self.clientAge) return True
def loadChildren(self): result = [] db = QtGui.qApp.db table = db.table('ActionTemplate') tableAction = db.table('Action') cond = [table['group_id'].eq(self._id), table['deleted'].eq(0)] if self._filter.actionTypeId: cond.append( db.joinOr([ tableAction['actionType_id'].eq(self._filter.actionTypeId), table['action_id'].isNull() ])) if self._filter.personId: cond.append( db.joinOr([ table['owner_id'].eq(self._filter.personId), table['owner_id'].isNull() ])) if self._filter.specialityId: cond.append( db.joinOr([ table['speciality_id'].eq(self._filter.specialityId), table['speciality_id'].isNull() ])) if self._filter.clientSex: cond.append(table['sex'].inlist([self._filter.clientSex, 0])) query = db.query( db.selectStmt(table.leftJoin( tableAction, tableAction['id'].eq(table['action_id'])), [ table['id'].name(), table['name'].name(), table['action_id'].name(), table['age'].name() ], where=cond, order=table['name'].name())) while query.next(): record = query.record() age = forceString(record.value('age')) if age and self._filter.clientAge: if not checkAgeSelector(parseAgeSelector(age), self._filter.clientAge): continue id = forceInt(record.value('id')) name = forceString(record.value('name')) actionId = forceRef(record.value('action_id')) child = CActionTemplateTreeItem(self, name, id, self.model, actionId, self._filter) if not self._filter.removeEmptyNodes or not child.isEmpty(): result.append(child) return result
def setRecord(self, record): CItemEditorBaseDialog.setRecord(self, record) setLineEditValue(self.edtCode, record, 'code') setLineEditValue(self.edtName, record, 'name') setComboBoxValue(self.cmbSex, record, 'sex') (begUnit, begCount, endUnit, endCount) = parseAgeSelector(forceString(record.value('age'))) self.cmbBegAgeUnit.setCurrentIndex(begUnit) self.edtBegAgeCount.setText(str(begCount)) self.cmbEndAgeUnit.setCurrentIndex(endUnit) self.edtEndAgeCount.setText(str(endCount)) # Полю flags можно сделать битовым и хранить в нем несколько разных состояний. Пока там одно, поэтому работаем # как с обычным полем со значениями 0-1 setCheckBoxValue(self.chkUseInCreateClients, record, 'flags')
def getCsgListByDiagnosis(): if not mkb: return [] cond = [u''' '%s' LIKE `mes`.`SPR69`.MKBX''' % mkb] if date: cond.append( u''' '%s' BETWEEN `mes`.`SPR69`.begDate AND `mes`.`SPR69`.endDate''' % date.toString('yyyy-MM-dd')) if sex: cond.append(db.joinOr([tblSPR69['sex'].eq(0), tblSPR69['sex'].eq(sex)])) if code: cond.append(tblSPR69['KSG'].like(code)) if duration and duration < 3: cond.append(db.joinOr([tblSPR69['duration'].eq(1), tblSPR69['duration'].eq(0)])) if mkb2List != ['']: mkb2Cond = [tblSPR69['MKBX2'].eq('')] for mkb2 in mkb2List: mkb2Cond.append(u''' '%s' LIKE `mes`.`SPR69`.MKBX2''' % mkb2) cond.extend([db.joinOr(mkb2Cond)]) if len(actionTypeCodesList) != 0: uslCond = [tblSPR69['KUSL'].eq('')] for usl in actionTypeCodesList: uslCond.append(u''' '%s' LIKE `mes`.`SPR69`.KUSL''' % usl) cond.extend([db.joinOr(uslCond)]) csgList = db.getRecordList(table=tblSPR69, cols='*', isDistinct=True, where=db.joinAnd(cond)) result = [] for csg in csgList: ageString = forceString(csg.value('age')) skipCsg = False for x in result: if csg.value('KSG') == x.value('KSG'): skipCsg = True break # Проверяем на наличие в списке таким образом, потому что исходный # вариант сравнивал адреса csg и элемента списка result. Адреса будут # в большинстве случаев разные, а вот содержимое может совпадать if not skipCsg: # csg not in result: if age is None: result.append(csg) continue if ageString: ageSelectors = parseAgeSelector(ageString, isExtend=True) if checkExtendedAgeSelector(ageSelectors, age): result.append(csg) # break result = filterSPr69RecordsByAge(filterSPR69Records(result)) return result
def _isEnabled(self, item): actionTypeId = self.actionCol.getActionTypeId( forceRef(item.value('action_id'))) sex = forceInt(item.value('sex')) age = forceString(item.value('age')) personId = forceRef(item.value('owner_id')) specialityId = forceRef(item.value('speciality_id')) if self.filter.actionTypeId and ( actionTypeId is None or (actionTypeId and self.filter.actionTypeId != actionTypeId)): return False if self.filter.personId and personId and self.filter.personId != personId: return False if self.filter.specialityId and specialityId and self.filter.specialityId != specialityId: return False if self.filter.clientSex and sex and self.filter.clientSex != sex: return False if self.filter.clientAge and age and not checkAgeSelector( parseAgeSelector(age), self.filter.clientAge): return False return True
def setRecord(self, record): CItemEditorBaseDialog.setRecord(self, record) setLineEditValue(self.edtCode, record, 'DiagID') self.chkPrim.setChecked(bool(forceString(record.value('Prim')))) setTextEditValue(self.edtName, record, 'DiagName') setRBComboBoxValue(self.cmbMKBSubclass, record, 'MKBSubclass_id') setComboBoxValue(self.cmbCharacters, record, 'characters') setComboBoxValue(self.cmbSex, record, 'sex') (begUnit, begCount, endUnit, endCount) = parseAgeSelector(forceString(record.value('age'))) self.cmbBegAgeUnit.setCurrentIndex(begUnit) self.edtBegAgeCount.setText(str(begCount)) self.cmbEndAgeUnit.setCurrentIndex(endUnit) self.edtEndAgeCount.setText(str(endCount)) setSpinBoxValue(self.edtDuration, record, 'duration') self.modelServiceSpecialty.loadItems(self.itemId()) self.edtBegDate.setDate(forceDate(record.value('begDate'))) self.edtEndDate.setDate(forceDate(record.value('endDate'))) self.chkOMS.setChecked(forceBool(record.value('OMS'))) self.chkMTR.setChecked(forceBool(record.value('MTR'))) self.prevCode = forceStringEx(self.edtCode.text()) self.parentCode = forceString(record.value('parent_code'))
def setRecord(self, record): CItemEditorBaseDialog.setRecord(self, record) self.setGroupId(forceRef(record.value('group_id'))) setLineEditValue(self.edtName, record, 'name') setComboBoxValue(self.cmbSex, record, 'sex') (begUnit, begCount, endUnit, endCount) = parseAgeSelector(forceString(record.value('age'))) self.cmbBegAgeUnit.setCurrentIndex(begUnit) self.edtBegAgeCount.setText(str(begCount)) self.cmbEndAgeUnit.setCurrentIndex(endUnit) self.edtEndAgeCount.setText(str(endCount)) ownerId = forceRef(record.value('owner_id')) specialityId = forceRef(record.value('speciality_id')) if ownerId: self.rbVisibleToOwner.setChecked(True) self.cmbOwner.setValue(ownerId) elif specialityId: self.rbVisibleToSpeciality.setChecked(True) self.cmbSpeciality.setValue(specialityId) else: self.rbVisibleToAll.setChecked(True) self.setActionId(forceRef(record.value('action_id'))) self.setIsDirty(False)
def checkDiags(self, eventId, sex, setDate, execDate, eventTypeId, clientAge): db=QtGui.qApp.db selectionGroups=self.get_Diag_selectionGroups(eventTypeId) if not selectionGroups: self.err2log(u'проверка диагнозов пропущена, так как не реализована') return # skip check mnogo=False malo=False zak_diags=0 zak_gz=0 gz_max=0 no_person=False person_0=False person_null=False for selectionGroup in selectionGroups: stmt=u''' select Diagnostic.endDate, Diagnostic.diagnosisType_id, Diagnostic.stage_id, Diagnostic.person_id, Diagnosis.MKB, Diagnostic.healthGroup_id, rbSpeciality.code as speciality, rbSpeciality.name as sname, EventType_Diagnostic.sex as EventType_Diagnostic_sex, EventType_Diagnostic.age, EventType_Diagnostic.actuality, Person.code as person_code, Person.federalCode from Diagnostic left join Person on Diagnostic.person_id=Person.id left join Diagnosis on Diagnosis.id=Diagnostic.diagnosis_id left join rbSpeciality on rbSpeciality.id=Diagnostic.speciality_id left join Event on Event.id=Diagnostic.event_id left join EventType_Diagnostic on (EventType_Diagnostic.eventType_id=Event.eventType_id and EventType_Diagnostic.speciality_id=Diagnostic.speciality_id) where Diagnostic.event_id=%d and Diagnostic.deleted = 0 and EventType_Diagnostic.eventType_id=%d and EventType_Diagnostic.selectionGroup=%d order by Diagnostic.diagnosisType_id ''' % (eventId, eventTypeId, selectionGroup) query=QtGui.qApp.db.query(stmt) diag_num=0 diag_osn={} # количество осн./закл. диагнозов while query.next(): diag_num+=1 record=query.record() speciality=forceString(record.value('speciality')) osn_num=diag_osn.get(speciality, 0) sname=forceString(record.value('sname')) MKB=forceStringEx(record.value('MKB')) if not MKB: self.err2log(u'отсутствует МКБ') continue if MKB != MKB.upper(): self.err2log(u'неправильный МКБ') continue if not db.getRecordEx('MKB', '*', 'DiagID="%s"' % MKBwithoutSubclassification(MKB)): self.err2log(u'неправильный МКБ') continue person_code=forceString(record.value('person_code')) federalCode=forceString(record.value('federalCode')) if person_code=='' and federalCode=='': no_person=True elif person_code in ['', '0'] and federalCode in ['', '0']: person_0=True endDate=forceDate(record.value('endDate')) diagnosisTypeId=forceInt(record.value('diagnosisType_id')) healthGroupId=forceInt(record.value('healthGroup_id')) personId=forceInt(record.value('person_id')) if not personId: person_null=True if MKB[:1] in ['Z', 'z']: # if diagnosisTypeId not in [1, 2]: # #z0-z13.9 # mkb_num=MKB[1:].split('.') # if len(mkb_num): # num1=int(mkb_num[0]) # if num1<13 or (num1==13 and (len(mkb_num)>1 and int(mkb_num[1])<=9)): # self.err2log(u'диагноз Z назначен сопутствующим') if healthGroupId>1 and diagnosisTypeId>1: #z0-z13.9 mkb_num=MKB[1:].split('.') if len(mkb_num): num1=int(mkb_num[0]) if num1<14: self.err2log(u'группа>1 диагноз Z') else: if healthGroupId==1: self.err2log(u'группа=1 диагноз не Z') if diagnosisTypeId==1: zak_diags+=1 zak_gz=healthGroupId if healthGroupId<1 or healthGroupId>6: self.err2log(u'неправильная группа заключительного диагноза') if diagnosisTypeId in [1, 2]: gz_max=max(gz_max, healthGroupId) diag_osn[speciality]=osn_num+1 else: diag_osn[speciality]=osn_num EventType_Diagnostic_sex=forceInt(record.value('EventType_Diagnostic_sex')) age=forceString(record.value('age')) actuality=forceInt(record.value('actuality')) if age and clientAge: ageSelector = parseAgeSelector(age) if not checkAgeSelector(ageSelector, clientAge): self.err2log(u'осмотр спец. '+sname+u' не подходит по возрасту') beg=setDate.addMonths(-actuality) if not endDate: self.err2log(u'осмотр спец. '+sname+u' без даты') if endDate and endDate<beg: self.err2log(u'осмотр спец. '+sname+u' раньше начала ДД') if endDate and endDate>execDate: self.err2log(u'осмотр спец. '+sname+u' позже окончания ДД') if EventType_Diagnostic_sex and EventType_Diagnostic_sex!=sex: self.err2log(u'осмотр спец. '+sname+u' не подходит по полу') cond='eventType_id=%d and selectionGroup=%d' % (eventTypeId, selectionGroup) EventType_Diagnostic=QtGui.qApp.db.getRecordEx( 'EventType_Diagnostic', cols='sex, age', where=cond) if EventType_Diagnostic: EventType_Diagnostic_sex=forceString(EventType_Diagnostic.value('sex')) if EventType_Diagnostic_sex and EventType_Diagnostic_sex!=sex: continue age=forceString(EventType_Diagnostic.value('age')) if age and clientAge: ageSelector = parseAgeSelector(age) if not checkAgeSelector(ageSelector, clientAge): continue for (spec, num) in diag_osn.iteritems(): sname=forceString(db.translate('rbSpeciality', 'code', spec, 'name')) if num==0: self.err2log(u'нет основного диагноза у спец. '+sname) if num>1: self.err2log(u'несколько основных диагнозов у спец. '+sname) if selectionGroup>1: if diag_num>1: mnogo=True elif not diag_num: malo=True elif selectionGroup==1: if not diag_num: malo=True elif selectionGroup==0: if diag_num: mnogo=True else: if diag_num>1: mnogo=True if mnogo: self.err2log(u'лишние диагнозы') if malo: self.err2log(u'не хватает диагнозов') if zak_diags==0: self.err2log(u'нет заключительного диагноза') elif zak_diags>1: self.err2log(u'несколько заключительных диагнозов') if zak_gz<gz_max: self.err2log(u'у заключительного диагноза не самая высокая группа здоровья') if person_null: self.err2log(u'нет врача') elif no_person: self.err2log(u'нет кода врача') elif person_0: self.err2log(u'код врача 0')
def initBySimpleType(self, sex, age): self.sex = sex self.age = parseAgeSelector(age) if age else None
def checkDatesRegardToClientLife(widget, clientId, eventSetDate, eventDate, eventTypeId): result = True if clientId: db = QtGui.qApp.db birthDate = forceDate( db.translate('Client', 'id', clientId, 'birthDate')) deathDate = getDeathDate(clientId) possibleDeathDate = birthDate.addYears(QtGui.qApp.maxLifeDuration) if birthDate: postmortem = isEventDeath(eventTypeId) if eventSetDate: result = result and (eventSetDate >= birthDate or confirmTrouble( widget, u'Дата назначения %s не должна быть раньше даты рождения пациента %s' % (forceString(eventSetDate), forceString(birthDate)))) if deathDate: result = result and ( eventSetDate <= deathDate or postmortem or confirmTrouble( widget, u'Дата назначения %s не должна быть позже имеющейся даты смерти пациента %s' % (forceString(eventSetDate), forceString(deathDate)))) else: result = result and ( eventSetDate <= possibleDeathDate or postmortem or confirmTrouble( widget, u'Дата назначения %s не должна быть позже возможной даты смерти пациента %s' % (forceString(eventSetDate), forceString(possibleDeathDate)))) ageConstraint = forceString( db.translate('EventType', 'id', eventTypeId, 'age')) ageConstraint = parseAgeSelector(ageConstraint, isExtend=True) clientAge = calcAgeTuple(birthDate, eventSetDate) ageResult = False if QtGui.qApp.region() == u'91': eventTypeCode = getEventCode(eventTypeId) ageResult = (QtGui.qApp.region() == u'91' and eventTypeCode.lower() in [u'дв1', u'дв2'] and hasSocStatus( clientId, {'specialCase': ['10', '11', '12']})) if not ageResult: for ageSelector in ageConstraint: begUnit, begCount, endUnit, endCount, step, useCalendarYear, useExclusion = ageSelector checkClientAge = clientAge if useCalendarYear and isinstance( checkClientAge, CAgeTuple): checkClientAge = CAgeTuple( (checkClientAge[0], checkClientAge[1], checkClientAge[2], eventSetDate.year() - birthDate.year()), birthDate, eventSetDate) ageResult = checkAgeSelector( (begUnit, begCount, endUnit, endCount), checkClientAge) if ageResult: if step: unit = begUnit if begUnit else endUnit if (checkClientAge[unit - 1] - begCount) % step != 0: ageResult = False if ageResult: ageResult = not useExclusion break if clientAge and ageConstraint and not ageResult: result = result and confirmTrouble( widget, u'Возраст пациента не подходит для создания обращения данного типа' ) if eventDate: result = result and (eventDate >= birthDate or confirmTrouble( widget, u'Дата выполнения (окончания) %s не должна быть раньше даты рождения пациента %s' % (forceString(eventDate), forceString(birthDate)))) if deathDate: result = result and ( eventDate <= deathDate or postmortem or confirmTrouble( widget, u'Дата выполнения (окончания) %s не должна быть позже имеющейся даты смерти пациента %s' % (forceString(eventDate), forceString(deathDate)))) else: result = result and ( eventDate <= possibleDeathDate or postmortem or confirmTrouble( widget, u'Дата выполнения (окончания) %s не должна быть позже возможной даты смерти пациента %s' % (forceString(eventDate), forceString(possibleDeathDate)))) return result
def checkActions(self, eventId, sex, setDate, execDate, eventTypeId, clientAge): selectionGroups=self.get_Action_selectionGroups(eventTypeId) mnogo=False malo=False for selectionGroup in selectionGroups: stmt=''' select ActionType.name, Action.actionType_id, Action.begDate, Action.endDate, EventType_Action.sex as EventType_Action_sex, EventType_Action.age, EventType_Action.actuality from Action join ActionType on ActionType.id=Action.actionType_id join EventType_Action on EventType_Action.actionType_id=Action.actionType_id where Action.event_id=%d and EventType_Action.eventType_id=%d and EventType_Action.selectionGroup=%d ''' % (eventId, eventTypeId, selectionGroup) query=QtGui.qApp.db.query(stmt) act_num=0 while query.next(): act_num+=1 record=query.record() begDate=forceDate(record.value('begDate')) endDate=forceDate(record.value('endDate')) name=forceString(record.value('name')) EventType_Action_sex=forceInt(record.value('EventType_Action_sex')) age=forceString(record.value('age')) actuality=forceInt(record.value('actuality')) if age and clientAge: ageSelector = parseAgeSelector(age) if not checkAgeSelector(ageSelector, clientAge): self.err2log(u'исслед. '+name+u' не подходит по возрасту') beg=setDate.addMonths(-actuality) if not endDate: self.err2log(u'исслед. '+name+u' без даты') # if begDate and begDate<beg: # self.err2log(u'исслед. '+name+u' раньше начала ДД') if endDate and endDate>execDate: self.err2log(u'исслед. '+name+u' позже окончания ДД') if EventType_Action_sex and EventType_Action_sex!=sex: self.err2log(u'исслед. '+name+u' не подходит по полу') cond='eventType_id=%d and selectionGroup=%d' % (eventTypeId, selectionGroup) EventType_Action=QtGui.qApp.db.getRecordEx('EventType_Action', cols='sex, age', where=cond) if EventType_Action: EventType_Action_sex=forceString(EventType_Action.value('sex')) if EventType_Action_sex and EventType_Action_sex!=sex: continue age=forceString(EventType_Action.value('age')) if age and clientAge: ageSelector = parseAgeSelector(age) if not checkAgeSelector(ageSelector, clientAge): continue if selectionGroup>1: if act_num>1: mnogo=True elif not act_num: malo=True elif selectionGroup==1: if not act_num: malo=True elif selectionGroup==0: if act_num: mnogo=True else: if act_num>1: mnogo=True if mnogo: self.err2log(u'лишние исслед.') if malo: self.err2log(u'не хватает исслед.')
def checkAge(ageTag, age): if age is None: return True ageSelectors = parseAgeSelector(ageTag, isExtend=True) return checkExtendedAgeSelector(ageSelectors, age)
def getMesIdList(self, useSex, useAge, useProfile, useMesCode, useMesName, useSpeciality, useContract, mkbCond, operativeMes): db = QtGui.qApp.db tableMES = db.table('mes.MES') queryTable = tableMES cond = [] if (useSex and self._clientSex) or (useAge and self._clientAge): tableService = db.table('rbService') tableServiceProfile = db.table('rbService_Profile') queryTable = queryTable.leftJoin(tableService, tableService['code'].eq(tableMES['code'])) queryTable = queryTable.leftJoin(tableServiceProfile, [tableServiceProfile['master_id'].eq(tableService['id']), tableServiceProfile['speciality_id'].eq(self._specialityId)]) sexCond = db.joinOr([tableServiceProfile['id'].isNull(), tableServiceProfile['sex'].inlist([self._clientSex, 0]) ]) if useSex and self._clientSex: cond.append(sexCond) if self._actionTypeIdList and operativeMes: tableMesService = db.table('mes.MES_service') tableMrbService = db.table('mes.mrbService') tableService = db.table('rbService') tableActionType = db.table('ActionType') condTable = tableMesService condTable = condTable.innerJoin(tableMrbService, tableMesService['service_id'].eq(tableMrbService['id'])) condTable = condTable.innerJoin(tableService, tableMrbService['code'].eq(tableService['code'])) condTable = condTable.innerJoin(tableActionType, tableService['id'].eq(tableActionType['nomenclativeService_id'])) subCond = [ tableMesService['master_id'].eq(tableMES['id']), tableActionType['id'].inlist(self._actionTypeIdList)] if self._checkDate: dateStr = self._checkDate.toString(QtCore.Qt.ISODate) subCond.append( 'IF(mes.MES_service.begDate IS NULL, 1, mes.MES_service.begDate <= DATE(\'%s\'))' % dateStr) subCond.append( 'IF(mes.MES_service.endDate IS NULL, 1, mes.MES_service.endDate >= DATE(\'%s\'))' % dateStr) cond.append(db.existsStmt(condTable, subCond)) if self._eventProfileId and useProfile: tableMESGroup = db.table('mes.mrbMESGroup') tableEventProfile = db.table('rbEventProfile') queryTable = queryTable.leftJoin(tableMESGroup, tableMESGroup['id'].eq(tableMES['group_id'])) queryTable = queryTable.leftJoin(tableEventProfile, tableEventProfile['regionalCode'].eq(tableMESGroup['code'])) cond.append(tableEventProfile['id'].eq(self._eventProfileId)) if self._mesCodeTemplate and useMesCode: cond.append(tableMES['code'].regexp(self._mesCodeTemplate)) if self._mesNameTemplate and useMesName: cond.append(tableMES['name'].regexp(self._mesNameTemplate)) if self._specialityId and useSpeciality: regionalCode = db.translate('rbSpeciality', 'id', self._specialityId, 'regionalCode') tableMESVisit = db.table('mes.MES_visit') tableMESSpeciality = db.table('mes.mrbSpeciality') tableMESVisitType = db.table('mes.mrbVisitType') subTable = tableMESVisit.leftJoin(tableMESVisitType, tableMESVisitType['id'].eq(tableMESVisit['visitType_id'])) subTable = subTable.leftJoin(tableMESSpeciality, tableMESSpeciality['id'].eq(tableMESVisit['speciality_id'])) subCond = [tableMESVisit['master_id'].eq(tableMES['id']), tableMESSpeciality['regionalCode'].eq(regionalCode)] cond.append(db.joinOr([ db.existsStmt(subTable, subCond), 'NOT ' + db.existsStmt(tableMESVisit, tableMESVisit['master_id'].eq(tableMES['id'])) ])) if self._contractId and useContract: tableContractTariff = db.table('Contract_Tariff') tableContractService = db.table('rbService').alias('contractService') queryTable = queryTable.leftJoin(tableContractService, tableMES['code'].eq(tableContractService['code'])) queryTable = queryTable.leftJoin( tableContractTariff, db.joinAnd([ tableContractService['id'].eq(tableContractTariff['service_id']), tableContractTariff['deleted'].eq(0), tableContractTariff['tariffType'].inlist([CTariff.ttVisitsByMES, CTariff.ttEventByMES, CTariff.ttEventByMESLen, CTariff.ttActionsByMES]) ]) ) cond.append(tableContractTariff['master_id'].eq(self._contractId)) if self._endDateForTariff: cond.append(db.joinOr([tableContractTariff['begDate'].dateLe(self._endDateForTariff), tableContractTariff['begDate'].isNull()])) cond.append(db.joinOr([tableContractTariff['endDate'].dateGe(self._endDateForTariff), tableContractTariff['endDate'].isNull()])) if self._MKB and mkbCond and not operativeMes: tableMESMkb = db.table('mes.MES_mkb') if mkbCond == 2: # строгое соответствие subCond = tableMESMkb['mkb'].inlist([self._MKB, MKBwithoutSubclassification(self._MKB)]) else: # по рубрике subCond = tableMESMkb['mkb'].like(self._MKB[:3] + '%') subCond = [tableMESMkb['master_id'].eq(tableMES['id']), subCond] cond.append(db.existsStmt(tableMESMkb, subCond)) # atronah: None - не фильтровать по списку id. [] - фильтровать по пустому списку (т.е. запрет выбора МЭС) if isinstance(self._availableIdList, list): cond.append(tableMES['id'].inlist(self._availableIdList)) cond.append(tableMES['deleted'].eq(0)) idList = [] order = 'mes.MES.code, mes.MES.id' if (useAge and self._clientAge): recordList = db.getRecordList(queryTable, cols=[tableMES['id'], tableServiceProfile['age']], where=cond, order=order) for record in recordList: mesId = forceRef(record.value('id')) ageString = forceString(record.value('age')) if mesId in idList: continue if ageString: ageSelectors = parseAgeSelector(ageString, isExtend=True) if checkExtendedAgeSelector(ageSelectors, self._clientAge): idList.append(mesId) else: idList.append(mesId) if not idList: regionalCheck = (QtGui.qApp.region() == u'91' and hasattr(self, '_eventTypeId') and hasattr(self, '_clientId') and getEventCode(self._eventTypeId).lower() in [u'дв1', u'дв2'] and hasSocStatus(self._clientId, {'specialCase': ['10', '11', '12']})) if regionalCheck: distFunction = lambda record: findExtendedAgeSelectorDist( parseAgeSelector(forceString(record.value('age')), isExtend=True), self._clientAge) nearestRecord = argMin(recordList, key=distFunction) idList = [forceInt(nearestRecord.value('id'))] if nearestRecord else [] else: idList = db.getDistinctIdList(queryTable, tableMES['id'].name(), where=cond, order=order) return idList
def build(self, params): accumSize = 2 # [totalAmount, totalSum] def printTotal(): totalByReport = printOrgStructures(resultDict) totalMessage = u'Итог по всем отделениям' if outputByOrgStructure else u'Итог по всем специалистам' row = table.addRow() table.setText(row, len(tableColumns) - 3, totalMessage, CReport.TableTotal) table.setText(row, len(tableColumns) - 2, totalByReport[0], CReport.TableTotal) table.setText(row, len(tableColumns) - 1, totalByReport[1], CReport.TableTotal) table.mergeCells(row, 0, 1, len(tableColumns) - 2) def printOrgStructures(reportData): total = [0] * accumSize printLeaf = onlyOrgStructures printHeadAndTotal = not onlyOrgStructures and outputByOrgStructure totalMessage = u'Итог по отделению' orgStructures = reportData.keys() orgStructures.sort() for orgStructure, orgStructureId in orgStructures: if printHeadAndTotal: row = table.addRow() table.setText(row, 0, orgStructure, blockFormat=CReportBase.AlignCenter, fontBold=True) table.mergeCells(row, 0, 1, len(tableColumns)) totalByOrgStructure = printSpecialities( reportData[(orgStructure, orgStructureId)]) total = map(add, total, totalByOrgStructure) if printLeaf: row = table.addRow() table.setText(row, len(tableColumns) - 3, orgStructure) table.setText(row, len(tableColumns) - 2, totalByOrgStructure[0]) table.setText(row, len(tableColumns) - 1, totalByOrgStructure[1]) table.mergeCells(row, 0, 1, len(tableColumns) - 2) if printHeadAndTotal: row = table.addRow() table.setText(row, len(tableColumns) - 3, totalMessage, fontBold=True) table.setText(row, len(tableColumns) - 2, totalByOrgStructure[0], fontBold=True) table.setText(row, len(tableColumns) - 1, totalByOrgStructure[1], fontBold=True) table.mergeCells(row, 0, 1, len(tableColumns) - 2) return total def printSpecialities(reportData): total = [0] * accumSize printTotal = not onlyOrgStructures and not outputByOrgStructure totalMessage = u'Итог по специальности' specialities = reportData.keys() specialities.sort() for speciality in specialities: totalBySpeciality = printPersons(reportData[speciality]) total = map(add, total, totalBySpeciality) if printTotal: row = table.addRow() table.setText(row, len(tableColumns) - 3, totalMessage, fontBold=True) table.setText(row, len(tableColumns) - 2, totalBySpeciality[0], fontBold=True) table.setText(row, len(tableColumns) - 1, totalBySpeciality[1], fontBold=True) table.mergeCells(row, 0, 1, len(tableColumns) - 2) return total def printPersons(reportData): total = [0] * accumSize printLeaf = not onlyOrgStructures printTotal = not onlyOrgStructures and not outputByOrgStructure totalMessage = u'Итог по специалисту' persons = reportData.keys() persons.sort() for person, personId in persons: firstRow = table.rows() totalByPerson = printDates(reportData[(person, personId)]) total = map(add, total, totalByPerson) if printLeaf: table.setText(firstRow, 0, person) table.mergeCells(firstRow, 0, table.rows() - firstRow, 1) if printTotal: row = table.addRow() table.setText(row, len(tableColumns) - 3, totalMessage, fontBold=True) table.setText(row, len(tableColumns) - 2, totalByPerson[0], fontBold=True) table.setText(row, len(tableColumns) - 1, totalByPerson[1], fontBold=True) table.mergeCells(row, 0, 1, len(tableColumns) - 2) return total def printDates(reportData): total = [0] * accumSize printLeaf = not onlyOrgStructures and showDates dates = reportData.keys() dates.sort() for date in dates: firstRow = table.rows() totalByDate = printServices(reportData[date]) total = map(add, total, totalByDate) if printLeaf: table.setText(firstRow, 1, date) table.mergeCells(firstRow, 1, table.rows() - firstRow, 1) return total def printServices(reportData): total = [0] * accumSize printLeaf = not onlyOrgStructures column = 2 if showDates else 1 services = reportData.keys() services.sort() for serviceCode, serviceName in services: firstRow = table.rows() totalByService = printClients(reportData[(serviceCode, serviceName)]) total = map(add, total, totalByService) if printLeaf: table.setText(firstRow, column, serviceCode) table.mergeCells(firstRow, column, table.rows() - firstRow, 1) table.setText(firstRow, column + 1, serviceName) table.mergeCells(firstRow, column + 1, table.rows() - firstRow, 1) return total def printClients(reportData): total = [0] * accumSize printLeaf = not onlyOrgStructures column = 3 + (1 if showDates else 0) + (1 if showClient else 0) clients = reportData.keys() clients.sort() for client in clients: serviceInfo = reportData[client] total[0] += serviceInfo['amount'] total[1] += serviceInfo['sum'] if printLeaf: row = table.addRow() if showClient: table.setText(row, column - 1, client) table.setText(row, column, serviceInfo['price']) table.setText(row, column + 1, serviceInfo['amount']) table.setText(row, column + 2, serviceInfo['sum']) return total queryActions = selectDataByActions(params) queryVisits = selectDataByVisits(params) outputByOrgStructure = params.get('chkOutputByOrgStructure', False) onlyOrgStructures = outputByOrgStructure and params.get( 'onlyOrgStructures', False) showClient = params.get('showClient', False) showDates = params.get('showDates', False) resultDict = {} self.setQueryText('\n\n'.join([ u'-------------Actions--------------', forceString(queryActions.lastQuery()), u'-------------Visits--------------', forceString(queryVisits.lastQuery()) ])) for query in [queryActions, queryVisits]: while query.next(): record = query.record() endDate = forceString(record.value('endDate')).split(' ')[0] serviceCode = forceString(record.value('serviceCode')) serviceName = forceString(record.value('serviceName')) personId = forceRef(record.value('personId')) personName = forceString(record.value('personName')) clientFIO = ' '.join([ forceString(record.value('lastName')), forceString(record.value('firstName')), forceString(record.value('patrName')) ]) amount = forceInt(record.value('amount')) price = forceDouble(record.value('price')) specialityId = forceRef(record.value('speciality_id')) orgStructureId = forceRef(record.value('orgStructureId')) orgStructureName = forceString( record.value('orgStructureName')) if query == queryVisits: tariffAge = forceString(record.value('tariffAge')) clientAge = forceInt(record.value('clientAge')) if tariffAge: begUnit, begCount, endUnit, endCount = parseAgeSelector( tariffAge) if (begUnit == 4 and begCount >= clientAge) or ( endUnit == 4 and clientAge >= endCount): continue orgStructureDict = resultDict.setdefault( (orgStructureName, orgStructureId), {}) specialityDict = orgStructureDict.setdefault(specialityId, {}) personDict = specialityDict.setdefault((personName, personId), {}) dateDict = personDict.setdefault(endDate if showDates else '', {}) serviceDict = dateDict.setdefault((serviceCode, serviceName), {}) serviceInfo = serviceDict.setdefault( clientFIO if showClient else '', {}) serviceInfo.setdefault('price', 0.0) serviceInfo.setdefault('amount', 0) serviceInfo.setdefault('sum', 0.0) serviceInfo['price'] = price serviceInfo['amount'] += amount serviceInfo['sum'] += price * amount doc = QtGui.QTextDocument() cursor = QtGui.QTextCursor(doc) cursor.setCharFormat(CReportBase.ReportTitle) cursor.insertText(self.title()) cursor.insertBlock() self.dumpParams(cursor, params) cursor.insertBlock() tableColumns = [ ('25%', [u'Специалист'], CReportBase.AlignLeft), ('20%', [u'Код услуги'], CReportBase.AlignLeft), ('20%', [u'Наименование услуги'], CReportBase.AlignLeft), ('10%', [u'Цена услуги'], CReportBase.AlignRight), ('10%', [u'Количество'], CReportBase.AlignRight), ('10%', [u'Стоимость'], CReportBase.AlignRight), ] if showClient: tableColumns.insert(3, ('15%', [u'Пациент'], CReportBase.AlignLeft)) if showDates: tableColumns.insert(1, ('10%', [u'Дата'], CReportBase.AlignRight)) table = createTable(cursor, tableColumns) boldChars = QtGui.QTextCharFormat() boldChars.setFontWeight(QtGui.QFont.Bold) printTotal() return doc