def addEventAction(self, eventId, actionTypeId, jobTicketId, date, idx, amount): def checkActionTypeIdByTissueType(actionTypeId): tissueTypeId = forceRef(self.takenTissueRecord.value('tissueType_id')) table = QtGui.qApp.db.table('ActionType_TissueType') cond = [table['master_id'].eq(actionTypeId), table['tissueType_id'].eq(tissueTypeId)] return bool(QtGui.qApp.db.getRecordEx(table, 'id', cond)) def setTicketIdToAction(action, jobTicketId): propertyTypeList = action.getType().getPropertiesById().values() if action else [] for propertyType in propertyTypeList: if type(propertyType.valueType) == CJobTicketActionPropertyValueType: property = action.getPropertyById(propertyType.id) property.setValue(jobTicketId) return True return False db = QtGui.qApp.db record = db.table('Action').newRecord() fillActionRecord(self, record, actionTypeId) action = CAction(record=record) if setTicketIdToAction(action, jobTicketId): # record.setValue('directionDate', QVariant(date)) record.setValue('setPerson_id', QtCore.QVariant(QtGui.qApp.userId)) if not amount is None: record.setValue('amount', QtCore.QVariant(amount)) if self.takenTissueRecord and checkActionTypeIdByTissueType(actionTypeId): record.setValue('takenTissueJournal_id', self.takenTissueRecord.value('id')) actionId = action.save(eventId, idx) self.actionIdListCanDeleted.append(actionId) self.mapActionIdToAction[actionId] = action return action return None
def loadData(self, eventId): record = None db = QtGui.qApp.db tableAction = db.table('Action') propertyDefList = [] for row in xrange(self.rowCount()): for column in xrange(self.columnCount()): propertyName = self.getPropertyName(row, column) if propertyName is not None: propertyDefList.append({'name' : propertyName, 'descr' : None, 'unit' : None, 'typeName' : 'String', 'valueDomain' : None, 'isVector' : False, 'norm' : None, 'sex' : None, 'age' : None }) actionTypeFlatCode = u'calfTeeth' if self._isCalf else u'permanentTeeth' ensureActionTypePresence(actionTypeFlatCode, propTypeList = propertyDefList, isUseFlatCode=True) actionType = CActionTypeCache.getByFlatCode(actionTypeFlatCode) if eventId: cond = [tableAction['deleted'].eq(0), tableAction['event_id'].eq(eventId), tableAction['actionType_id'].eq(actionType.id)] record = db.getRecordEx(tableAction, '*', cond, order = 'idx') self._dentalNotationAction = CAction(record = record if record else None, actionType = actionType)
def getPlannedEndDateByJobTicketProperty(record): # план заполняется по номерку, a номерок может подбираться автоматом if record: action = CAction(record=record) actionType = action.getType() propertyTypeList = actionType.getPropertiesById().values() for propertyType in propertyTypeList: if type(propertyType.valueType ) == CJobTicketActionPropertyValueType: property = action.getPropertyById(propertyType.id) jobTicketId = property.getValue() if jobTicketId: db = QtGui.qApp.db date = forceDate( db.translate('Job_Ticket', 'id', jobTicketId, 'datetime')) jobId = forceRef( db.translate('Job_Ticket', 'id', jobTicketId, 'master_id')) jobTypeId = forceRef( db.translate('Job', 'id', jobId, 'jobType_id')) ticketDuration = forceInt( db.translate('rbJobType', 'id', jobTypeId, 'ticketDuration')) return date.addDays(ticketDuration) return None
def loadEvent(self, event_id): db = QtGui.qApp.db for rec in db.getRecordList('Action', where='event_id=%d AND deleted=0' % event_id): action = CAction(record=rec) action_type = action.getType() # type: CActionType self._items[action_type.class_].append(action)
def __init__(self, context, actionId, action=None): db = QtGui.qApp.db if not action: record = db.getRecord('Action', '*', actionId) action = CAction(record=record) else: record = action.getRecord() CCookedActionInfo.__init__(self, context, record, action)
def saveData(self): if self.action and self.eventId: times = self.action['times'] lenItems = len(self.items) diff = lenItems - len(times) if diff < 0: self.items.extend([None] * (-diff)) elif diff > 0: times.extend([None] * diff) for row in xrange(lenItems): itemTime = self.items[row][0] times[row] = forceTime(itemTime) self.action['times'] = times db = QtGui.qApp.db db.transaction() try: self.saveDataNumbers(self.date.day() - 1) db.commit() if self.actionTypeCode == constants.atcAmbulance: self.tableItems[CTimeTableModel.ciAmbChange] = False elif self.actionTypeCode == constants.atcHome: self.tableItems[CTimeTableModel.ciHomeChange] = False self.action = CAction.getAction(self.eventId, self.actionTypeCode) except: db.rollback() QtGui.qApp.logCurrentException() raise
def setActionTypeId(self, actionTypeId): self.cmbActionType.setValue(actionTypeId) self.tabWidget.setTabEnabled(1, bool(actionTypeId)) old_props = dict() if self.action: old_props = self.action._propertiesByName if actionTypeId: if (not self.action or self.action.getType().id != actionTypeId): self.action = CAction.createByTypeId(actionTypeId) self.tblProps.model().setAction(self.action, None, 0, None) self.tblProps.resizeRowsToContents() else: self.action = None self.tblProps.model().setAction(self.action, None, 0, None) self.tblProps.resizeRowsToContents() if self.action: new_props = self.action._propertiesByName for prop in old_props: if prop in self.action._propertiesByName and \ new_props[prop]._type.getValueType() == old_props[prop]._type.getValueType(): new_props[prop]._changed = True new_props[prop]._evaluation = old_props[prop]._evaluation new_props[prop]._isAssigned = old_props[prop]._isAssigned new_props[prop]._norm = old_props[prop]._norm new_props[prop]._unitId = old_props[prop]._unitId new_props[prop]._value = old_props[prop]._value
def getTimeRangeOffice(self, date, personId): atcAmbulance = 'amb' etcTimeTable = '0' timeRange = ('--:--', '--:--') office = u'' times = [] queue = [] db = QtGui.qApp.db eventTypeId = getEventType(etcTimeTable).eventTypeId eventTable = db.table('Event') cond = [ eventTable['deleted'].eq(0), eventTable['eventType_id'].eq(eventTypeId), eventTable['execDate'].eq(date), eventTable['execPerson_id'].eq(personId) ] event = db.getRecordEx(eventTable, '*', cond) if event: eventId = forceRef(event.value('id')) action = CAction.getAction(eventId, atcAmbulance) begTime = action['begTime'] endTime = action['endTime'] office = action['office'] times = action['times'] queue = action['queue'] if begTime and endTime: timeRange = begTime.toString( 'H:mm') + ' - ' + endTime.toString('H:mm') return timeRange, office, times, queue
def __getitem__(self, key): v = self._items[key] if v is None: record = QtGui.qApp.db.getRecord('Action', '*', self.idList[key]) action = CAction(record=record) v = self.getInstance(CCookedActionInfo, record, action) self._items[key] = v return v
def getHospitalDirectionNumberStr(self, eventId): numberStr = '' if self.hospitalDirectionActionTypeId: db=QtGui.qApp.db table = db.table('Action') record = db.getRecordEx(table, '*', u'event_id=\'%d\' AND actionType_id=\'%d\'' % (eventId, self.hospitalDirectionActionTypeId)) if record: action = CAction() action.setRecord(record) property = action.getProperty(u'Номер направления') if property: numberStr = property.getTextScalar() return numberStr
def loadItems(self, eventId): self._analysesGroups.clear() self._items = [] db = QtGui.qApp.db tableAction = db.table('Action') tableAT = db.table('ActionType') table = tableAction.innerJoin(tableAT, [ tableAT['id'].eq(tableAction['actionType_id']), tableAT['class'].eq(ActionClass.Analyses), tableAT['deleted'].eq(0) ]) cols = [tableAction['id'], tableAction['parent_id']] cond = [ tableAction['event_id'].eq(eventId), tableAction['deleted'].eq(0) ] idList = [] childMap = DefaultOrderedDict(list) for record in db.iterRecordList( table, cols, cond, order=tableAction['idx'] if not self.orderByDirectionDate else tableAction['directionDate'].desc()): id = forceRef(record.value('id')) parentId = forceRef(record.value('parent_id')) idList.append(id) if parentId: childMap[parentId].append(id) recordMap = dict( (forceRef(rec.value('id')), rec) for rec in db.iterRecordList( tableAction, '*', tableAction['id'].inlist(idList))) for mainActionId, childrenIdList in childMap.iteritems(): mainAction = CAction(record=recordMap[mainActionId]) for actionId in childrenIdList: action = CAction(record=recordMap[actionId]) self._analysesGroups[mainAction].append(action) self._recalcItems() self.reset()
def checkEventData(self, eventData): """Проверяет наличие требуемых полей в импортируемых данных, а также соответствий в БД, куда производится импорт. Для устранения дублирующихся вызовов идентификаторы записей в справочниках БД также заносятся в поля экземпляра обращения. @param eventData: экземпляр обращения """ eventId = eventData.ExternalId eventTypeCode = eventData.EventTypeCode if not eventTypeCode: self.err2log(CErrorLevel.error, 'Event type code not specified', 'Event', eventId) return -1 eventTypeId = self.getEventTypeIdByCode(eventTypeCode) if not eventTypeId: self.err2log( CErrorLevel.error, 'Event type with code %s was not found in target database' % eventTypeCode, 'Event', eventId) return -2 eventData.eventTypeId = eventTypeId for actionData in eventData.Action: actionTypeCode = actionData.ActionTypeCode if not actionTypeCode: self.err2log(CErrorLevel.error, 'Action type code not specified', 'Event', eventId) return -3 try: action = CAction.createByTypeCode(actionTypeCode) except AssertionError: self.err2log( CErrorLevel.error, 'Action type with code %s was not found in target database' % actionData.actionTypeCode, 'Event', eventId) return -4 actionData.instance = action for ap in actionData.ActionProperty: apType = ap.ActionPropertyType if not apType: self.err2log( CErrorLevel.error, u'Action property type not specified in action with action type code "%s"' % actionTypeCode, 'Event', eventId) return -5 try: action[apType] = ap.ActionPropertyValue except KeyError: self.err2log( CErrorLevel.error, u'Action property with type "%s" not found in description of ActionType with code "%s"' % (ap.ActionPropertyType, actionTypeCode), 'Event', eventId) return -6 return 0
def getChildren(self): db = QtGui.qApp.db tableAction = db.table('Action') actionId = forceRef(self._record.value('id')) return [ self.getInstance(CCookedActionInfo, record, CAction(record=record)) for record in db.iterRecordList(tableAction, '*', [ tableAction['parent_id'].eq(actionId), tableAction['deleted'].eq(0) ]) ]
def setActionId(self): if self.actionId: db = QtGui.qApp.db record = db.getRecord('Action', '*', self.actionId) else: record = None if record: self.setAction(CAction(record=record)) else: self.setAction(None)
def setProbeResultToActionProperties(tissueJournalId, testId, result): db = QtGui.qApp.db tableAction = db.table('Action') tableActionPropertyType = db.table('ActionPropertyType') queryTable = tableAction.innerJoin( tableActionPropertyType, tableActionPropertyType['actionType_id'].eq( tableAction['actionType_id'])) cond = [ tableAction['takenTissueJournal_id'].eq(tissueJournalId), tableActionPropertyType['test_id'].eq(testId) ] actionRecordList = db.getRecordList(queryTable, 'Action.*', cond) for actionRecord in actionRecordList: needSave = False action = CAction(record=actionRecord) actionType = action.getType() propertyTypeItemsList = actionType.getPropertiesById().items() for propertyTypeId, propertyType in propertyTypeItemsList: if propertyType.testId == testId: property = action.getPropertyById(propertyTypeId) if not propertyType.isVector: property.setValue( propertyType.convertQVariantToPyValue(result)) needSave = True if needSave: action.save(idx=forceInt(actionRecord.value('idx')))
def loadItems(self, eventId): self._items = [] db = QtGui.qApp.db tableAction = db.table('Action') tableEvent = db.table('Event') tableEventTypeAction = db.table('EventType_Action') tableActionType = db.table('ActionType') cond = [ tableAction['deleted'].eq(0), tableAction['event_id'].eq(eventId) ] if self.actionTypeClass is not None: cond.append(tableAction['actionType_id'].inlist( self.actionTypeIdList)) if self.ignoredActionTypesIdList: cond.append(tableAction['actionType_id'].notInlist( self.ignoredActionTypesIdList)) actionTypeProtocolIdList = getActionTypeIdListByFlatCode(u'protocol%') if actionTypeProtocolIdList: cond.append(tableAction['actionType_id'].notInlist( actionTypeProtocolIdList)) actionTypeIdList = [] for record in db.iterRecordList(tableAction, '*', cond, order=['idx', 'id']): self.addItem((record, CAction(record=record))) actionTypeIdList.append(forceRef(record.value('actionType_id'))) queryTable = tableEvent.innerJoin( tableEventTypeAction, tableEventTypeAction['eventType_id'].eq( tableEvent['eventType_id'])) queryTable = queryTable.innerJoin( tableActionType, tableActionType['id'].eq(tableEventTypeAction['actionType_id'])) notDeletedActionTypeRecordList = db.getRecordList( queryTable, cols=[ tableActionType['id'], tableActionType['code'], tableActionType['name'] ], where=[ tableEvent['id'].eq(eventId), tableEventTypeAction['isCompulsory'].eq(1), tableActionType['id'].inlist(actionTypeIdList) ]) for record in notDeletedActionTypeRecordList: self.notDeletedActionTypes[forceRef( record.value('id'))] = forceString( record.value('code')) + '|' + forceString( record.value('name')) self.reset()
def on_openInRedactor(self): index = self.currentIndex() if index.isValid(): row = index.row() items = self.model().items() if 0 <= row < len(items): oldRecord, oldAction = items[row] oldRecord.setValue('event_id', toVariant(self._parent.eventEditor.itemId()) ) # Необходимо для шаблонов печати. dialog = CActionEditDialog(self) dialog.save = lambda: True dialog.setForceClientId(self._parent.clientId()) dialog.setRecord(QtSql.QSqlRecord(oldRecord)) dialog.setReduced(True) CAction.copyAction(oldAction, dialog.action) if dialog.exec_(): record = dialog.getRecord() items[row] = (record, dialog.action) self._parent.onActionCurrentChanged()
def addRow(self, actionTypeId=None, amount=None, financeId=None, contractId=None, presetAction=None): if not presetAction: record = self.fillNewRecord(actionTypeId, amount, financeId, contractId) item = (record, CAction(record=record) if actionTypeId else None) else: record = presetAction.getRecord() item = (record, presetAction) if item[1]: item[1].initPropertyPresetValues() return self.insertItem(item)
def _load(self): db = QtGui.qApp.db tableAction = db.table('Action') tableAT = db.table('ActionType') tableATG = db.table('ActionType').alias('ActionTypeGroup') queryTable = tableAction.join( tableAT, tableAction['actionType_id'].eq(tableAT['id'])) queryTable = queryTable.join(tableATG, tableAT['group_id'].eq(tableATG['id'])) fields = (tableAction['id'], tableAT['flatCode'], tableATG['flatCode']) cond = (tableAction['event_id'].eq(self.__event_id), ) height = None weight = None regimen = None feed = None for actionRecord in db.getRecordIter(queryTable, fields, cond, 'Action.createDatetime DESC'): actionId = forceRef(actionRecord.value(0)) flatCode = forceString(actionRecord.value(1)) groupCode = forceString(actionRecord.value(2)) if flatCode in ('regimen', 'feed') or groupCode in ('primaryInspection', ): action = CAction.getById(actionId) if 'height' in action._propertiesByCode: if not height and action['height', ]: height = action['height', ] if 'weight' in action._propertiesByCode: if not weight and action['weight', ]: weight = action['weight', ] if 'regimen' in action._propertiesByCode: if not regimen and action['regimen', ]: regimen = action['regimen', ] if 'feed' in action._propertiesByCode: if not feed and action['feed', ]: feed = action['feed', ] if height and weight and regimen and weight: break self.__height = height or u'Неизвестно' self.__weight = weight or u'Неизвестно' self.__regimen = regimen or u'Неизвестно' self.__feed = feed or u'Неизвестно' self.__square = height * weight / 3600.0 if height and weight else u'Неизвестно'
def setData(self, index, value, role=QtCore.Qt.EditRole, presetAction=None): if role == QtCore.Qt.EditRole: row = index.row() actionTypeId = forceRef(value) if actionTypeId and not ( self.checkMaxOccursLimit(actionTypeId) and self.checkMovingNoLeaved(actionTypeId) and self.checkMovingAfterReceived(actionTypeId) and self.checkLeavedAfterMoving(actionTypeId) and self.checkLeavedAfterMovingDate(actionTypeId) and self.checkCompatibility(actionTypeId) and self.checkPeriodicActionPosibility(actionTypeId)): return False if row == len(self._items): if actionTypeId is None: return False self.addRow(presetAction=presetAction) if not presetAction: record = self._items[row][0] self.fillRecord(record, actionTypeId) action = None if actionTypeId is None else CAction( record=record) else: record = presetAction.getRecord() action = presetAction setPerson = forceRef(record.value('setPerson_id')) execPerson = forceRef(record.value('person_id')) if not QtGui.qApp.userSpecialityId: if setPerson == QtGui.qApp.userId: record.setValue('setPerson_id', toVariant(None)) if execPerson == QtGui.qApp.userId: record.setValue('person_id', toVariant(None)) self._items[row] = (record, action) self.emitDataChanged(index) self.emitItemsCountChanged() return True
def _load(self): # TODO: отвязаться от необходимости знать внутреннюю структуру actInfo if isinstance(self.__model, CPrescriptionSqlModel): cAction = self.__model.actInfo._cAction else: cAction = CAction.getById(self.__model.id) self._action = cAction.toInfo(self.context) self._eventInfo = self.context.getInstance(CEventInfo, cAction.event_id) self._clientInfo = self.context.getInstance(CClientInfo, cAction.Event.client_id) self._prescIntervals = self.context.getInstance( CPrescDrugCellInfoList, self.__model, self.__interval, self.__step) self._execIntervals = self.context.getInstance(CExecDrugCellInfoList, self.__model, self.__interval, self.__step) self._drugs = CDrugInfoList(self.context, self.__model.drugComponents) self._interval = CDateTimeIntervalInfo(self.context, self.__interval, self.__step) return True
def getTimeRange(actionTypeCode, date, personId): timeRange = ('--:--', '--:--') db = QtGui.qApp.db eventTypeId = getEventType(etcTimeTable).eventTypeId eventTable = db.table('Event') cond = [ eventTable['deleted'].eq(0), eventTable['eventType_id'].eq(eventTypeId), eventTable['execDate'].eq(date), eventTable['execPerson_id'].eq(personId) ] event = db.getRecordEx(eventTable, '*', cond) if event: eventId = forceRef(event.value('id')) action = CAction.getAction(eventId, actionTypeCode) begTime = action['begTime'] endTime = action['endTime'] if begTime and endTime: timeRange = begTime.toString( 'H:mm') + ' - ' + endTime.toString('H:mm') return timeRange
def loadClientDentitionHistory(self, clientId, setDate): self._dentitionHistoryItems = [] self._resultDentitionHistoryItems.clear() self._clientId = clientId db = QtGui.qApp.db tableEvent = db.table('Event') tableAction = db.table('Action') tableActionType = db.table('ActionType') cond = [ tableEvent['client_id'].eq(clientId), tableEvent['deleted'].eq(0), tableAction['deleted'].eq(0), tableActionType['flatCode'].inlist( [u'dentitionInspection', u'parodentInsp']) ] if setDate: cond.append(tableAction['begDate'].yearEq(setDate)) queryTable = tableEvent.innerJoin( tableAction, tableAction['event_id'].eq(tableEvent['id'])) queryTable = queryTable.innerJoin( tableActionType, tableActionType['id'].eq(tableAction['actionType_id'])) # order = tableAction['begDate'].name() + ' DESC' + ', ' + tableAction['event_id'].name() + ' DESC' order = [tableAction['id']] fields = 'Event.id AS eventId, ActionType.flatCode AS flatCode, Action.*' recordList = db.getRecordList(queryTable, fields, cond, order) for record in recordList: id = forceRef(record.value('id')) eventId = forceRef(record.value('eventId')) action = CAction(record=record) isChecked = 0 self._resultDentitionHistoryItems[eventId] = (record, action, id, eventId, isChecked) self._dentitionHistoryItems.append( (record, action, id, eventId, isChecked)) if len(self._dentitionHistoryItems) > 0: self._dentitionHistoryItems.sort( key=lambda x: forceDate(x[0].value('begDate'))) self._dentitionHistoryItems.reverse() self.reset()
def getAssistants(self): if self._assistans is None: self._assistans = CAction.loadAssistants(self.id) return self._assistans
def __init__(self, context, actionId): db = QtGui.qApp.db record = db.getRecord('Action', '*', actionId) action = CAction(record=record) CCookedActionInfo.__init__(self, context, record, action)
def processResults(self, results): defaultEventTypeId = forceRef( self.db.translate('EventType', 'code', '001', 'id')) tableJobTicket = self.db.table('Job_Ticket').alias('jt') tableAction = self.db.table('Action').alias('a') currentDate = QDate.currentDate() for i in range(results.length()): result = results.at(i) localId = result.firstChildElement('ido').text() externalId = result.firstChildElement('idi').text() tests = result.firstChildElement('tests') if not tests: continue test = tests.firstChildElement('test') if not test: continue dateString = test.firstChildElement('date').text() date = QDate.fromString(dateString, Qt.ISODate) value = test.firstChildElement('value').text() status = test.firstChildElement('status').text() comment = test.firstChildElement('comment').text() if localId: stmt = u'''SELECT a.id as actionId, Event.id as eventId FROM Job_Ticket jt INNER JOIN Job j ON j.id = jt.master_id AND jt.status = 0 INNER JOIN rbJobType jt1 ON jt1.code = '4-4' AND jt1.id= j.jobType_id INNER JOIN ActionProperty_Job_Ticket apjt ON apjt.value = jt.id INNER JOIN ActionProperty ap ON ap.id = apjt.id INNER JOIN Action a ON a.id = ap.action_id AND a.deleted = 0 INNER JOIN Event ON Event.id = a.event_id AND Event.deleted = 0 INNER JOIN Client c ON c.id = Event.client_id AND c.deleted = 0 WHERE %s''' cond = [ self.tableEvent['client_id'].eq(forceRef(localId)), tableJobTicket['datetime'].dateEq(date), tableAction['actionType_id'].eq(self.actionType) ] query = self.db.query(stmt % self.db.joinAnd(cond)) if not query.first(): continue record = query.record() eventId = forceRef(record.value('eventId')) action = CAction.getAction(eventId, u'А06.09.007.002*') actionRecord = action.getRecord() endDate = forceDate(actionRecord.value('endDate')) if not endDate: actionRecord.setValue('endDate', toVariant(currentDate)) actionRecord.setValue( 'status', toVariant(2 if status == 1 else 3 if status == 2 else 0)) action[u'Результат'] = externalId + u' ' + value action[u'Описание'] = comment action.setRecord(actionRecord) action.save() elif defaultEventTypeId: localId = self._mapIDOtoIDI.get(externalId, None) if localId is None: print 'Error: found test result without information about client. Skipping.' continue self.db.transaction() try: eventRecord = self.tableEvent.newRecord() eventRecord.setValue('eventType_id', toVariant(defaultEventTypeId)) eventRecord.setValue('client_id', toVariant(localId)) eventRecord.setValue('setDate', toVariant(date)) eventRecord.setValue('isPrimary', toVariant(1)) eventRecord.setValue('order', toVariant(1)) eventId = self.db.insertRecord('Event', eventRecord) action = CAction.createByTypeId(self.actionType) actionRecord = action.getRecord() if not actionRecord: actionRecord = self.tableAction.newRecord() actionRecord.setValue('actionType_id', toVariant(self.actionType)) actionRecord.setValue( 'status', toVariant(2 if status == 1 else 3 if status == 2 else 0)) actionRecord.setValue('begDate', toVariant(date)) actionRecord.setValue('endDate', toVariant(currentDate)) action[u'Результат'] = externalId + ' ' + value action[u'Описание'] = comment action.setRecord(actionRecord) action.save(eventId) self.db.commit() except: self.db.rollback() raise
def setRecordByNext(self, record): oldAction = self.action newAction = CAction(record=record) CAction.copyAction(oldAction, newAction, isCopyRecordData=False) self.setAction(newAction)
def setRecord(self, record): action = CAction(record=record) self._initByAction(action)
class CF025DentalModel(QtCore.QAbstractTableModel): def __init__(self, isCalf, parent = None): super(CF025DentalModel, self).__init__(parent) self._isCalf = isCalf self._dentalNotationAction = None #--- re-implement def rowCount(self, parentIndex = QtCore.QModelIndex()): return 4 def columnCount(self, parentIndex = QtCore.QModelIndex()): return 10 if self._isCalf else 16 def flags(self, index): flags = QtCore.Qt.NoItemFlags if self._dentalNotationAction and index.isValid(): row = index.row() column = index.column() if column in xrange(self.columnCount()): if row in [0, 3]: flags = QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEditable propertyName = self.getPropertyName(row, column) prop = self._dentalNotationAction.getProperty(propertyName) if prop.type().isAssignable: flags += QtCore.Qt.ItemIsUserCheckable elif row in [1, 2]: flags = QtCore.Qt.ItemIsEnabled return flags def data(self, index, role = QtCore.Qt.DisplayRole): if self._dentalNotationAction and index.isValid(): row = index.row() column = index.column() if column in xrange(self.columnCount()): if row in [0, 3]: propertyName = self.getPropertyName(row, column) prop = self._dentalNotationAction.getProperty(propertyName) if role == QtCore.Qt.DisplayRole: return QtCore.QVariant(prop.getText()) elif role == QtCore.Qt.CheckStateRole: if prop.type().isAssignable: QtCore.QVariant(QtCore.Qt.Checked if prop.isAssigned() else QtCore.Qt.Unchecked) elif role == QtCore.Qt.EditRole: return QtCore.QVariant(prop.getValue()) elif role == QtCore.Qt.DecorationRole: return QtCore.QVariant(prop.getImage()) elif role == QtCore.Qt.ForegroundRole: if prop.getEvaluation(): return QtCore.QVariant(QtGui.QBrush(QtGui.QColor(255, 0, 0))) elif role == QtCore.Qt.FontRole: evaluation = prop.getEvaluation() if evaluation and abs(evaluation) == 2: font = QtGui.QFont() font.setBold(True) return QtCore.QVariant(font) elif row in [1, 2]: if role == QtCore.Qt.DisplayRole: return QtCore.QVariant(self.getPropertyName(0 if row == 1 else 3, column)) elif role == QtCore.Qt.FontRole: font = QtGui.QFont() font.setBold(True) return QtCore.QVariant(font) elif role == QtCore.Qt.TextAlignmentRole: return QtCore.QVariant(QtCore.Qt.AlignCenter) return QtCore.QVariant() def setData(self, index, value, role = QtCore.Qt.EditRole): if self._dentalNotationAction and index.isValid(): row = index.row() column = index.column() if column in xrange(self.columnCount()): if row in [0, 3]: propertyName = self.getPropertyName(row, column) prop = self._dentalNotationAction.getProperty(propertyName) if role == QtCore.Qt.EditRole: prop.setValue(prop.type().convertQVariantToPyValue(value)) self.dataChanged.emit(index, index) return True elif role == QtCore.Qt.CheckStateRole: prop.setAssigned(value == QtCore.Qt.Checked) self.dataChanged.emit(index, index) return True return False #--- working def getPropertyName(self, row, column): if row not in (0, self.rowCount() - 1): return None if (column * 2) < self.columnCount(): quadrant = 1 if row == 0 else 4 number = (self.columnCount() / 2) - column else: quadrant = 2 if row == 0 else 3 number = column - (self.columnCount() / 2) + 1 if self._isCalf: quadrant += 4 return u'%s%s' % (quadrant, number) def loadData(self, eventId): record = None db = QtGui.qApp.db tableAction = db.table('Action') propertyDefList = [] for row in xrange(self.rowCount()): for column in xrange(self.columnCount()): propertyName = self.getPropertyName(row, column) if propertyName is not None: propertyDefList.append({'name' : propertyName, 'descr' : None, 'unit' : None, 'typeName' : 'String', 'valueDomain' : None, 'isVector' : False, 'norm' : None, 'sex' : None, 'age' : None }) actionTypeFlatCode = u'calfTeeth' if self._isCalf else u'permanentTeeth' ensureActionTypePresence(actionTypeFlatCode, propTypeList = propertyDefList, isUseFlatCode=True) actionType = CActionTypeCache.getByFlatCode(actionTypeFlatCode) if eventId: cond = [tableAction['deleted'].eq(0), tableAction['event_id'].eq(eventId), tableAction['actionType_id'].eq(actionType.id)] record = db.getRecordEx(tableAction, '*', cond, order = 'idx') self._dentalNotationAction = CAction(record = record if record else None, actionType = actionType) def saveData(self, eventId): if self._dentalNotationAction: self._dentalNotationAction.save(eventId = eventId)
def on_btnNextAction_clicked(self): if self.cmbStatus.currentIndex() == 3: currentDateTime = QtCore.QDateTime.currentDateTime() db = QtGui.qApp.db table = db.table('vrbPersonWithSpeciality') personId = QtGui.qApp.userId if ( QtGui.qApp.userId and QtGui.qApp.userSpecialityId) else self.cmbSetPerson.value() record = db.getRecordEx(table, [table['name']], [table['id'].eq(personId)]) if personId else None personName = forceString(record.value('name')) if record else '' self.edtNote.setText('Отменить: %s %s' % (currentDateTime.toString('dd-MM-yyyy hh:mm'), personName)) else: self.newActionId = None prevRecord = self.getRecord() if prevRecord: actionTypeId = forceRef(prevRecord.value('actionType_id')) if prevRecord else None duration = self.edtDuration.value() aliquoticity = self.edtAliquoticity.value() if duration >= 1 or aliquoticity > 1: recordList = {} periodicity = self.edtPeriodicity.value() if aliquoticity and actionTypeId: db = QtGui.qApp.db tableAction = db.table('Action') eventId = forceRef(prevRecord.value('event_id')) actionId = forceRef(prevRecord.value('id')) directionDate = forceDateTime(prevRecord.value('directionDate')) setPersonId = forceRef(prevRecord.value('setPerson_id')) if eventId: cond = [ tableAction['deleted'].eq(0), tableAction['actionType_id'].eq(actionTypeId), tableAction['event_id'].eq(eventId), tableAction['directionDate'].eq(directionDate), tableAction['setPerson_id'].eq(setPersonId) ] for recordOld in db.iterRecordList( tableAction, tableAction['*'], cond, tableAction['begDate'] ): id = forceRef(recordOld.value('id')) begDateOld = forceDateTime(recordOld.value('begDate')) recordList[(id, begDateOld)] = recordOld keysList = recordList.keys() keysList.sort() keyList = keysList[-1] quoticity = 0 if aliquoticity > 1: for key in recordList.keys(): if key[1].date() == keyList[1].date(): quoticity += 1 if duration >= 1 or (aliquoticity > 1 and aliquoticity > quoticity): lastRecord = recordList.get(keyList, None) newRecordAction = False if lastRecord: prevActionId = forceRef(lastRecord.value('id')) if actionId == prevActionId: begDate = forceDateTime(prevRecord.value('begDate')) if QtGui.qApp.userId and QtGui.qApp.userSpecialityId: execPersonId = QtGui.qApp.userId else: execPersonId = self.cmbSetPerson.value() dialog = CExecTimeNextActionDialog(self, begDate, execPersonId) if dialog.exec_(): execTime = dialog.getExecTime() execPersonId = dialog.getExecPersonId() specifiedName = forceString(prevRecord.value('specifiedName')) prevRecord.setValue('person_id', toVariant(execPersonId)) executionPlan = self.action.getExecutionPlan() executionPlanKeys = executionPlan.keys() executionPlanKeys.sort() executionPlanBegDate = executionPlan.get(pyDate(begDate.date()), {}) if not executionPlanBegDate: for keyDate in executionPlanKeys: executionPlanTimes = executionPlan.get(keyDate, {}) aliquoticityNew = len(executionPlanTimes) if aliquoticityNew: executionPlanTimeKeys = executionPlanTimes.keys() executionPlanTimeKeys.sort() aliquoticity = aliquoticityNew begDateDate = begDate.date() durationNew = duration - begDateDate.daysTo( QtCore.QDate(keyDate)) duration = durationNew begDate = QtCore.QDateTime(QtCore.QDate(keyDate), executionPlanTimeKeys[0]) break else: executionPlanBegDateKeys = executionPlanBegDate.keys() executionPlanBegDateKeys.sort() begTime = executionPlanBegDateKeys[0] executionPlanKeys = executionPlan.keys() executionPlanKeys.sort() if QtCore.QDate(executionPlanKeys[0]) == begDate.date(): aliquoticity = len(executionPlanBegDateKeys) newBegDate = begDate.date().addDays(1) maxBegDate = executionPlanKeys[len(executionPlanKeys) - 1] while newBegDate <= maxBegDate: periodicityPlanTimes = executionPlan.get(pyDate(newBegDate), {}) if len(periodicityPlanTimes): periodicity = begDate.date().daysTo(newBegDate) - 1 break else: newBegDate = newBegDate.addDays(1) if periodicity < 0: periodicity = 0 begDate = QtCore.QDateTime(begDate.date(), begTime) prevRecord.setValue('aliquoticity', toVariant(aliquoticity)) prevRecord.setValue('begDate', toVariant(begDate)) prevRecord.setValue('endDate', toVariant(QtCore.QDateTime(begDate.date(), execTime))) prevRecord.setValue('status', toVariant(2)) prevRecord.setValue('plannedEndDate', toVariant(begDate.addDays(duration - 1))) prevRecord.setValue('duration', toVariant(duration)) endDate = forceDateTime(prevRecord.value('endDate')) newExecutionPlan = {} tableActionExecutionPlan = db.table('Action_ExecutionPlan') for execDate, timeList in executionPlan.items(): timeListDict = {} for execTime, record in timeList.items(): if QtCore.QDateTime(QtCore.QDate(execDate), execTime) > begDate: newExecPlanRecord = tableActionExecutionPlan.newRecord() newExecPlanRecord.setValue('execDate', toVariant(record.value('execDate'))) newExecPlanRecord.setValue('master_id', toVariant(None)) newExecPlanRecord.setValue('id', toVariant(None)) timeListDict[execTime] = newExecPlanRecord if timeListDict or QtCore.QDate(execDate) > begDate.date(): newExecutionPlan[execDate] = timeListDict begDateNew = None periodicityNew = -1 if newExecutionPlan: newExecutionPlanKeys = newExecutionPlan.keys() newExecutionPlanKeys.sort() newExecTimeList = {} newExecDate = None for planKey in newExecutionPlanKeys: newExecTimeList = newExecutionPlan.get(planKey, {}) if newExecTimeList: newExecDate = planKey break if newExecTimeList and newExecDate: newExecTimeListKeys = newExecTimeList.keys() if len(newExecTimeListKeys) > 0: newExecTimeListKeys.sort() newExecTime = newExecTimeListKeys[0] begDateNew = QtCore.QDateTime(QtCore.QDate(newExecDate), newExecTime) aliquoticity = len(newExecTimeListKeys) begDateDate = begDate.date() periodicity = begDateDate.daysTo(begDateNew.date()) - 1 if periodicity < 0: periodicity = 0 if begDateDate == begDateNew.date(): durationNew = duration else: durationNew = duration - 1 - periodicity periodicityNew = 0 begDateNewDate = begDateNew.date() for newExecutionKey in newExecutionPlanKeys: newExecutionDate = QtCore.QDate(newExecutionKey) if newExecutionDate > begDateNewDate: periodicityNew = begDateNewDate.daysTo( newExecutionDate) - 1 if periodicityNew < 0: periodicityNew = 0 break elif aliquoticity > 1 and aliquoticity > quoticity: begDateNew = QtCore.QDateTime(endDate.date(), execTime if execTime else self.getCurrentTimeAction( endDate)) durationNew = duration else: endDateNew = endDate.addDays(periodicity + 1) begDateNew = QtCore.QDateTime(endDateNew.date(), execTime if execTime else self.getCurrentTimeAction( endDate)) durationNew = duration - 1 - periodicity prevRecord.setValue('periodicity', toVariant(periodicity)) if begDateNew and durationNew: if periodicityNew > -1: periodicity = periodicityNew newRecord = tableAction.newRecord() newRecord.setValue('event_id', toVariant(prevRecord.value('event_id'))) newRecord.setValue('begDate', toVariant(begDateNew)) newRecord.setValue('status', toVariant(0)) newRecord.setValue('idx', toVariant(9999)) newRecord.setValue('specifiedName', toVariant(specifiedName)) newRecord.setValue('duration', toVariant(durationNew)) newRecord.setValue('periodicity', toVariant(periodicity)) newRecord.setValue('aliquoticity', toVariant(aliquoticity)) newRecord.setValue('plannedEndDate', toVariant(begDateNew.addDays(durationNew - 1))) newRecord.setValue('actionType_id', toVariant(actionTypeId)) newRecord.setValue('directionDate', toVariant(prevRecord.value('directionDate'))) newRecord.setValue('setPerson_id', toVariant(prevRecord.value('setPerson_id'))) newRecord.setValue('person_id', toVariant(QtGui.qApp.userId if ( QtGui.qApp.userId and QtGui.qApp.userSpecialityId) else self.cmbSetPerson.value())) newRecord.setValue('org_id', toVariant(prevRecord.value('org_id'))) newRecord.setValue('amount', toVariant(prevRecord.value('amount'))) newAction = CAction(record=newRecord) if newExecutionPlan: newAction.setExecutionPlan(newExecutionPlan) if newAction: for properties in self.action._properties: type = properties._type name = type.name if (type.canChangeOnlyOwner > 0 or type.inActionsSelectionTable == 1 or type.isActionNameSpecifier ) and name: newAction[name] = self.action[name] self.newActionId = newAction.save(idx=9999) newRecordAction = True self.setRecordByNext(prevRecord) self.saveData() self.close() if duration == 1 and not newRecordAction: begDate = forceDateTime(prevRecord.value('begDate')) prevRecord.setValue('status', toVariant(2)) endDate = forceDateTime(prevRecord.value('endDate')) if not endDate: prevRecord.setValue('endDate', toVariant(begDate)) prevRecord.setValue('person_id', toVariant(QtGui.qApp.userId if ( QtGui.qApp.userId and QtGui.qApp.userSpecialityId) else self.cmbSetPerson.value())) prevRecord.setValue('plannedEndDate', toVariant(begDate.addDays(duration - 1))) self.setRecordByNext(prevRecord) self.saveData() self.close()