Exemple #1
0
 def __init__(self, parent, clientId, actionIdList, visibleOkButton=False):
     CDialogBase.__init__(self, parent)
     cols = [
         CDateTimeFixedCol(u'Дата и время приема', ['directionDate'], 20),
         CRefBookCol(u'Тип', ['actionType_id'], 'ActionType', 15),
         CEnumCol(u'Состояние', ['status'],
                  CActionType.retranslateClass(False).statusNames, 4),
         CRefBookCol(u'Назначил', ['setPerson_id'],
                     'vrbPersonWithSpeciality', 20),
         CRefBookCol(u'Специалист', ['person_id'],
                     'vrbPersonWithSpeciality', 20),
         CTextCol(u'Каб', ['office'], 6),
         CTextCol(u'Примечания', ['note'], 6),
     ]
     self.addModels('Actions', CTableModel(self, cols, 'Action'))
     self.btnPrint = QtGui.QPushButton(u'Печать', self)
     self.btnPrint.setObjectName('btnPrint')
     self.setupUi(self)
     self.setWindowFlags(QtCore.Qt.Dialog
                         | QtCore.Qt.WindowMaximizeButtonHint
                         | QtCore.Qt.WindowCloseButtonHint)
     if visibleOkButton:
         self.buttonBox.setStandardButtons(QtGui.QDialogButtonBox.Ok
                                           | QtGui.QDialogButtonBox.Cancel)
     else:
         self.buttonBox.setStandardButtons(QtGui.QDialogButtonBox.Close)
     self.buttonBox.addButton(self.btnPrint,
                              QtGui.QDialogButtonBox.ActionRole)
     self.tblActions.setModel(self.modelActions)
     self.tblActions.addPopupPrintRow(self)
     self.clientId = clientId
     self.txtClientInfoBrowser.setHtml(
         getClientBanner(self.clientId) if self.clientId else '')
     self.modelActions.setIdList(actionIdList)
     self.buttonBox.setEnabled(bool(actionIdList))
Exemple #2
0
    def getDescription(self, params):
        begDate = params.get('begDate', None)
        endDate = params.get('endDate', None)
        chkStatus = params.get('chkStatus', False)
        status = params.get('status', None)
        chkGroupByPatient = params.get('chkGroupByPatient', None)
        contractText = params.get('contractText', None)
        financeText = params.get('financeText', None)

        rows = []

        if begDate:
            rows.append(u'Начальная дата периода: %s' % forceString(begDate))
        if endDate:
            rows.append(u'Конечная дата периода: %s' % forceString(endDate))
        if chkStatus and not status is None:
            rows.append(
                u'Статус: %s' %
                CActionType.retranslateClass(False).statusNames[status])
        if chkGroupByPatient:
            rows.append(u'Группировка по пациентам')
        if financeText:
            rows.append(u'Тип финансирования: %s' % financeText)
        if contractText:
            rows.append(u'Контракт: %s' % contractText)

        return rows
    def __init__(self, clientId, actionPropertyList, parent):
        CInDocTableModel.__init__(self, 'ActionProperty', 'id', '', parent)
        self.clientId = clientId
        self.actionPropertyList = actionPropertyList
        self.addCol(
            CDateInDocTableCol(u'Начато', 'begDate', 10, canBeEmpty=True))
        self.addCol(
            CDateInDocTableCol(u'Окончено', 'endDate', 10, canBeEmpty=True))
        self.addCol(
            CEnumInDocTableCol(
                u'Состояние', 'status', 10,
                CActionType.retranslateClass(False).statusNames))

        for i, (actionProperty, showUnit,
                showNorm) in enumerate(self.actionPropertyList):
            seq = '_' + str(i + 1)
            self.addCol(
                CActionPropertyValueTableCol(actionProperty.type().name,
                                             'value' + seq, 30,
                                             actionProperty))
            if showUnit:
                self.addCol(
                    CRBInDocTableCol(u'Ед.изм.',
                                     'unit_id' + seq,
                                     10,
                                     'rbUnit',
                                     isRTF=True))
            if showNorm:
                self.addCol(CInDocTableCol(u'Норма', 'norm' + seq, 30))
        self.setEnableAppendLine(False)
Exemple #4
0
    def __init__(self, parent):
        CItemEditorBaseDialog.__init__(self, parent, 'Action')
        CJobTicketReserveMixin.__init__(self)
        self.eventId = None
        self.eventTypeId = None
        self.clientId = None
        self.forceClientId = None
        self.clientSex = None
        self.clientAge = None
        self.personId = None
        self.personSpecialityId = None
        self.newActionId = None
        self.clientInfo = None
        self._mainWindowState = QtGui.qApp.mainWindow.windowState()

        self.addModels('ActionProperties', CExActionPropertiesTableModel(self))

        self.actEditClient = QtGui.QAction(u'Изменить описание клиента', self)

        self.actEditClient.setObjectName('actEditClient')
        self.btnPrint = getPrintButton(self, '')
        self.btnPrint.setObjectName('btnPrint')
        self.btnLoadTemplate = CActionTemplateChooseButton(self)
        self.btnLoadTemplate.setObjectName('btnLoadTemplate')
        self.btnLoadTemplate.setText(u'Загрузить шаблон')
        self.btnSaveAsTemplate = QtGui.QPushButton(u'Сохранить шаблон', self)
        self.btnSaveAsTemplate.setObjectName('btnSaveAsTemplate')
        self.setupUi(self)
        # Заполнение элементов комбобокса переведенными значениями из первоисточника
        self.cmbStatus.clear()
        self.cmbStatus.addItems(CActionType.retranslateClass(False).statusNames)
        self.setWindowFlags(QtCore.Qt.Dialog | QtCore.Qt.WindowMaximizeButtonHint | QtCore.Qt.WindowCloseButtonHint)
        self.setWindowTitleEx(u'Мероприятие')
        self.edtDirectionDate.canBeEmpty(True)
        self.edtEndDate.canBeEmpty(True)
        self.edtBegDate.canBeEmpty(True)
        self.buttonBox.addButton(self.btnPrint, QtGui.QDialogButtonBox.ActionRole)
        self.buttonBox.addButton(self.btnLoadTemplate, QtGui.QDialogButtonBox.ActionRole)
        self.buttonBox.addButton(self.btnSaveAsTemplate, QtGui.QDialogButtonBox.ActionRole)
        self.setModelsEx(self.tblProps, self.modelActionProperties, self.selectionModelActionProperties)
        self.txtClientInfoBrowser.actions.append(self.actEditClient)
        self.actEditClient.setEnabled(QtGui.qApp.userHasAnyRight([urAdmin, urRegTabWriteRegistry]))

        self.setupDirtyCather()
        self.setIsDirty(False)

        self.actionTemplateCache = CActionTemplateCache(self)

        action = QtGui.QAction(self)
        self.actSetLaboratoryCalculatorInfo = action
        self.actSetLaboratoryCalculatorInfo.setObjectName('actSetLaboratoryCalculatorInfo')
        action.setShortcut(QtGui.QKeySequence(QtCore.Qt.Key_F3))
        self.addAction(action)
        self.connect(self.actSetLaboratoryCalculatorInfo, QtCore.SIGNAL('triggered()'),
                     self.on_actSetLaboratoryCalculatorInfo)
        self.connect(self.btnCloseWidgets, QtCore.SIGNAL('arrowTypeChanged(bool)'), self.on_arrowTypeChanged)
        self.setVisibleBtnCloseWidgets(False)
        self._canUseLaboratoryCalculatorPropertyTypeList = None
Exemple #5
0
    def actionSelected(self, action):
        # toggle widgets enabled state
        self.attrsAP.setEnabled(True)
        self.tblAPProps.setEnabled(True)

        # set action to props model
        self.modelAPProps.setAction(action, self.eventEditor.clientId,
                                    self.eventEditor.clientSex,
                                    self.eventEditor.clientAge)
        self.tblAPProps.init()
        self.tblAPProps.resizeRowsToContents()
        setActionPropertiesColumnVisible(action.getType(), self.tblAPProps)

        # set values to top widgets
        setDatetimeEditValue(self.edtAPBegDate, self.edtAPBegTime,
                             action.getRecord(), 'begDate')
        setDatetimeEditValue(self.edtAPEndDate, self.edtAPEndTime,
                             action.getRecord(), 'endDate')
        if not forceDate(action.getRecord().value('endDate')).isNull() and \
                not (forceInt(action.getRecord().value('status')) in CActionType.retranslateClass(False).ignoreStatus) and \
                forceRef(action.getRecord().value('status')) is not None:
            self.cmbAPStatus.setCurrentIndex(2)
        else:
            self.cmbAPStatus.setCurrentIndex(
                forceInt(action.getRecord().value('status')))
        setPerson = forceRef(action.getRecord().value('setPerson_id'))
        if not setPerson:
            if u'moving' in action.getType().flatCode.lower(
            ) and self.eventEditor.prevEventId:
                setPerson = self.presetPerson
            else:
                setPerson = None
        self.cmbAPSetPerson.setValue(setPerson)
        personId = forceRef(action.getRecord().value('person_id'))
        if not personId:
            if u'moving' in action.getType().flatCode.lower(
            ) and self.eventEditor.prevEventId:
                personId = self.presetPerson
            else:
                personId = None
        self.cmbAPPerson.setValue(personId)
        self.cmbMKB.setText(forceString(action.getRecord().value('MKB')))
        self.recalculateUET()

        # setup template buttons
        if QtGui.qApp.userHasRight(urLoadActionTemplate) and action:
            self.btnAPLoadTemplate.setEnabled(True)
        else:
            self.btnAPLoadTemplate.setEnabled(False)
        self.btnAPSaveAsTemplate.setEnabled(
            QtGui.qApp.userHasRight(urSaveActionTemplate))
        self.btnAPLoadPrevAction.setEnabled(
            QtGui.qApp.userHasRight(urCopyPrevAction) and bool(action))
        self.updatePrintButton(action.getType())
Exemple #6
0
    def __init__(self, parent=None):
        QtGui.QDialog.__init__(self, parent)
        self.patientRequired = False
        self.setupUi(self)
        # Заполнение элементов комбобокса переведенными значениями из первоисточника
        self.cmbStatus.clear()
        self.cmbStatus.addItems(CActionType.retranslateClass(False).statusNames)
        self.cmbFinance.setTable('rbFinance', addNone=True)
        self.cmbTissueType.setTable('rbTissueType', addNone=True, specialValues=[(-1, u'-', u'Любой')])

        self.edtDate.setDisplayFormat('MM.yyyy')
        self.cmbActionTypeGroup.setClass(None)
        self.cmbActionTypeGroup.model().setLeavesVisible(False)
Exemple #7
0
    def __init__(self, parent, actionsMap=None):
        """

        :param parent: владелец создаваемого объекта
        :param actionsMap: словарь {actionId : CAction} для актуализации вывода ассистентов
        """
        if not actionsMap:
            actionsMap = {}
        self._parent = parent
        self._actionsMap = actionsMap

        fields = [
            CDesignationCol(u'Мероприятие', ['actionType_id'], ('ActionType', 'name'), 20),
            CPayStatusColumn(u'Оплата', ['payStatus', 'contract_id'], 20, 'l'),
            CEnumCol(u'Статус', ['status'], CActionType.retranslateClass(False).statusNames, 6),
            CDateTimeCol(u'Назначено', ['directionDate'], 20),
            CDesignationCol(u'Назначил', ['setPerson_id'], ('vrbPersonWithSpeciality', 'name'), 20),
            CDesignationCol(u'Ответственный', ['person_id'], ('vrbPersonWithSpeciality', 'name'), 20)
        ]

        # Добавление столбцов с ассистентами
        # FIXME: atronah: не обновляется значение после изменения его через F2 (диалоговый редактор),
        # так как здесь чтение из базы, в которую изменения еще не попали
        for assistantSuffix in [u'', u'2', u'3']:
            if self._actionsMap:
                valuesGetter = self.CAssistantIdGetter(self._actionsMap, u'assistant' + assistantSuffix)
            else:
                valuesGetter = None
            assistantTypeId = forceRef(QtGui.qApp.db.translate('rbActionAssistantType',
                                                               'code',
                                                               u'assistant' + assistantSuffix,
                                                               'id'))
            fields.append(CBackRelationCol(interfaceCol=CDesignationCol(title=u'Ассистент' + assistantSuffix,
                                                                        fields=['person_id'],
                                                                        designationChain=(
                                                                            'vrbPersonWithSpeciality', 'name'),
                                                                        defaultWidth=20),
                                           primaryKey='id',
                                           subTableName='Action_Assistant',
                                           subTableForeignKey='action_id',
                                           subTableCond='assistantType_id = %s' % assistantTypeId,
                                           alternativeValuesGetter=valuesGetter))

        if QtGui.qApp.defaultMorphologyMKBIsVisible():
            fields.insert(2, CTextCol(u'МКБ', ['MKB'], 8))
            fields.insert(3, CTextCol(u'Морфология МКБ', ['morphologyMKB'], 14))
        CTableModel.__init__(self, parent, fields)
        self.loadField('*')
        self.setTable('Action', recordCacheCapacity=None)
Exemple #8
0
    def __init__(self, parent=None):
        CDialogBase.__init__(self, parent)
        self.setupUi(self)
        # Заполнение элементов комбобокса переведенными значениями из первоисточника
        self.cmbStatus.clear()
        self.cmbStatus.addItems(
            CActionType.retranslateClass(False).statusNames)
        self.cmbFinance.setTable('rbFinance', addNone=True)
        self.cmbAssistantPost.setTable('rbPost')

        self.patientRequired = False
        self.groupByPatientVisible = False
        self.setupByOrgStructureVisible = False
        self.setupByOrgStructureOnlyVisible = False
        self.setupByEventTypeVisible = False
        self.setupByPersonVisible = False
        self.strongOrgStructureVisible = False
        self.clientAgeCategoryVisible = False
        self.onlyClientAsPersonInLPUVisible = False
        self.outputByOrgStructureVisible = False
        self.onlyDiscountPaymentVisible = False
        self.onlyStaffRelativeVisible = False
        self.chkPersonVisible = False
        self.chkRefusedVisible = False
        self.serviceTypesVisible = False
        self.chkShowClientVisible = False

        self.setStrongOrgStructureVisible(self.strongOrgStructureVisible)
        self.setGroupByPatientVisible(self.groupByPatientVisible)
        self.setSetupByOrgStructureVisible(self.setupByOrgStructureVisible)
        self.setSetupByEventTypeVisible(self.setupByEventTypeVisible)
        self.setSetupByPersonVisible(self.setupByPersonVisible)
        self.setClientAgeCategoryVisible(self.clientAgeCategoryVisible)
        self.setOnlyClientAsPersonInLPUVisible(
            self.onlyClientAsPersonInLPUVisible)
        self.setOutputByOrgStructureVisible(self.outputByOrgStructureVisible)
        self.setOnlyDiscountPaymentVisible(self.onlyDiscountPaymentVisible)
        self.setOnlyStaffRelativeVisible(self.onlyStaffRelativeVisible)
        self.setRefusedVisible(self.chkRefusedVisible)
        self.setChkPersonVisible(self.chkPersonVisible)
        self.setVisibleAssistant(False)
        self.setServiceTypesVisible(self.serviceTypesVisible)
        self.setChkShowClientVisible(self.chkShowClientVisible)

        self.addModels('ServiceType', CServiceTypeModel(1, 10))
        self.lstServiceTypes.setModel(self.modelServiceType)
        self.lstServiceTypes.selectAll()
Exemple #9
0
 def postSetupUi(self):
     self.cmbAPStatus.clear()
     self.cmbAPStatus.addItems(
         CActionType.retranslateClass(False).statusNames)
     self.cmbDocType.setTable(
         rbDocumentType, True,
         'group_id IN (SELECT id FROM rbDocumentTypeGroup WHERE code=\'1\')'
     )
     self.setupModels()
     self.tabCoordination.setFocusProxy(self.grpLocalContract)
     self.tabActionsAndCash.setFocusProxy(self.tblAccActions)
     self.windowTitle = u''
     self._updateEditable()
     self.connect(self.modelAccActions, QtCore.SIGNAL('sumChanged()'),
                  self.setUpdatePaymentsSum)
     self.connect(self.modelPayments, QtCore.SIGNAL('sumChanged()'),
                  self.setUpdatePaymentsSum)
Exemple #10
0
    def __init__(self, parent):
        CItemEditorBaseDialog.__init__(self, parent, 'ActionTemplate')
        self.addModels('ActionProperties', CActionPropertiesTableModel(self))
        self.setupUi(self)
        # Заполнение элементов комбобокса переведенными значениями из первоисточника
        self.cmbStatus.clear()
        self.cmbStatus.addItems(
            CActionType.retranslateClass(False).statusNames)
        self.setWindowTitleEx(u'Шаблон действия')
        self.cmbActionType.setClasses([0, 1, 2, 3])

        self.cmbSpeciality.setTable('rbSpeciality')
        self.setModels(self.tblProps, self.modelActionProperties,
                       self.selectionModelActionProperties)
        self.groupId = None
        self.action = None
        self.actionId = None
        self.setupDirtyCather()
Exemple #11
0
    def __init__(self, parent=None):
        super(CActionsWidget, self).__init__(parent)
        self.eventEditor = parent
        self.actionTemplateCache = CActionTemplateCache(parent)

        self.setupUi(self)

        self.shcCreateAction = QtGui.QShortcut(QtCore.Qt.Key_F9, self)
        self.shcCreateAction.activated.connect(self.createActions)

        self.modelAPActions = CActionsTreeModel(self.tblAPActions)
        self.modelAPProps = CExActionPropertiesTableModel(self.tblAPProps)
        self.tblAPActions.setModel(self.modelAPActions)
        self.tblAPProps.setModel(self.modelAPProps)

        self.tblAPActions.initHeader()
        self.cmbAPStatus.addItems(
            CActionType.retranslateClass(False).statusNames)
        self.btnAPLoadTemplate.setModelCallback(self.getTemplatesModel)
        # self.btnAPLoadPrevAction.setMenu(self.mnuAPLoadPrevAction)

        # setup signals
        self.tblAPActions.actionSelected.connect(self.actionSelected)
        self.tblAPActions.actionDeselected.connect(self.actionDeselected)
        self.connect(self.edtAPBegDate,
                     QtCore.SIGNAL('dateChanged(const QDate &)'),
                     self.begDateChanged)
        self.edtAPBegTime.timeChanged.connect(self.begTimeChanged)
        self.connect(self.edtAPEndDate,
                     QtCore.SIGNAL('dateChanged(const QDate &)'),
                     self.endDateChanged)
        self.edtAPEndTime.timeChanged.connect(self.endTimeChanged)
        self.cmbAPPerson.currentIndexChanged.connect(self.personChanged)
        self.cmbAPSetPerson.currentIndexChanged.connect(self.setPersonChanged)
        self.cmbAPStatus.currentIndexChanged.connect(self.statusChanged)
        self.cmbMKB.editTextChanged.connect(self.mkbChanged)
        self.connect(self.btnAPLoadTemplate,
                     QtCore.SIGNAL('templateSelected(int)'), self.loadTemplate)
        self.btnAPSaveAsTemplate.clicked.connect(self.saveTemplate)
        self.connect(self.btnAPPrint, QtCore.SIGNAL('printByTemplate(int)'),
                     self.printByTemplate)
        self.modelAPActions.dataChanged.connect(self.actionsChanged)
Exemple #12
0
    def getDescription(self, params):
        date = params.get('date', QtCore.QDate.currentDate())
        financeId = params.get('financeId', None)
        class_ = params.get('class', None)
        actionTypeGroupId = params.get('actionTypeGroupId', None)
        status = params.get('status', None)
        orgStructureId = params.get('orgStructureId', None)
        personId = params.get('personId', None)
        assistantId = params.get('assistantId', None)
        tissueTypeId = params.get('tissueTypeId', None)

        rows = [u'Год: %d'%date.year(),
                u'Месяц: %s'%[u'январь',
                              u'февраль',
                              u'март',
                              u'апрель',
                              u'май',
                              u'июнь',
                              u'июль',
                              u'август',
                              u'сентябрь',
                              u'октябрь',
                              u'ноябрь',
                              u'декабрь'][date.month()-1]]
        db = QtGui.qApp.db
        if financeId:
            rows.append(u'Тип финансирования: %s'%forceString(db.translate('rbFinance', 'id', financeId, 'name')))
        if not class_ is None:
            rows.append(u'Класс типов действия: %s'%[u'статус', u'диагностика', u'лечение', u'прочие мероприятия'][class_])
        if actionTypeGroupId:
            rows.append(u'Группа типов действий: %s'%forceString(db.translate('ActionType', 'id', actionTypeGroupId, 'CONCAT(code, \' | \', name)')))
        if not status is None:
            rows.append(u'Статус: %s' % CActionType.retranslateClass(False).statusNames[status])
        if orgStructureId:
            rows.append(u'Подразделение: %s'%forceString(db.translate('OrgStructure', 'id', orgStructureId, 'name')))
        if personId:
            rows.append(u'Назначивший: %s'%forceString(db.translate('vrbPersonWithSpeciality', 'id', personId, 'name')))
        if assistantId:
            rows.append(u'Ассистент: %s'%forceString(db.translate('vrbPersonWithSpeciality', 'id', assistantId, 'name')))
        if tissueTypeId:
            rows.append(u'Тип биоматериала: %s'%forceString(db.translate('rbTissueType', 'id', tissueTypeId, 'CONCAT(code, \' | \', name)')))
        return rows
Exemple #13
0
    def getDescription(self, params):
        begDate = params.get('begDate', None)
        endDate = params.get('endDate', None)
        chkStatus = params.get('chkStatus', False)
        status = params.get('status', None)
        reportType = params.get('reportType', None)
        chkAllOrgStructure = params.get('chkAllOrgStructure', False)
        contractText = params.get('contractText', None)
        financeText = params.get('financeText', None)
        detailServiceTypes = params.get('detailServiceTypes', None)
        serviceTypes = params.get('serviceTypes', None)

        rows = []

        if begDate:
            rows.append(u'Начальная дата периода: %s' % forceString(begDate))
        if endDate:
            rows.append(u'Конечная дата периода: %s' % forceString(endDate))
        if chkStatus and status is not None:
            rows.append(
                u'Статус: %s' %
                CActionType.retranslateClass(False).statusNames[status])
        if reportType is not None:
            rows.append(u'Отчет по: %s' % [
                u'отделениям выполнившего действие врача',
                u'отделениям за которым закрепленно действие'
            ][reportType])
        if chkAllOrgStructure:
            rows.append(
                u'Действия связаны со всеми возможными подразделениями')
        if financeText:
            rows.append(u'Тип финансирования: %s' % financeText)
        if contractText:
            rows.append(u'Контракт: %s' % contractText)
        if detailServiceTypes and serviceTypes:
            rows.append(
                u'Типы услуг: ' +
                u', '.join(map(lambda x: docServiceTypeName[x], serviceTypes)))
        return rows
Exemple #14
0
    def __init__(self,
                 parent,
                 actionTypeIdList=None,
                 patternActionTypeId=None):
        if not actionTypeIdList:
            actionTypeIdList = []
        self._actionTypeIdList = actionTypeIdList
        self._table = QtGui.qApp.db.table('ActionType')

        CDialogBase.__init__(self, parent)

        self.setupUi(self)
        # Заполнение элементов комбобокса переведенными значениями из первоисточника
        self.cmbDefaultStatus.clear()
        self.cmbDefaultStatus.addItems(
            CActionType.retranslateClass(False).statusNames)

        self._load(patternActionTypeId)

        self.setWindowTitle(u'Групповой редактор')

        self.addModels('ServiceType', CServiceTypeModel(1))
        self.cmbServiceType.setModel(self.modelServiceType)
Exemple #15
0
    def build(self, params):
        doc = QtGui.QTextDocument()
        cursor = QtGui.QTextCursor(doc)

        cursor.setCharFormat(CReportBase.ReportTitle)
        cursor.insertText(self.title())
        cursor.insertBlock()

        self.chkDiagnosis = params.get('chkDiagnosis')

        if self.chkDiagnosis:
            tableColumns = [
                ('5%', [u'№'], CReportBase.AlignRight),
                ('20%', [u'Пациент'], CReportBase.AlignLeft),
                ('5%', [u'Заболевания', u'Код по МКБ'], CReportBase.AlignLeft),
                ('5%', [u'', u'С'], CReportBase.AlignLeft),
                ('5%', [u'', u'По'], CReportBase.AlignLeft),
                ('5%', [u'', u'Характер'], CReportBase.AlignLeft),
                ('5%', [u'Посещения', u'Дата'], CReportBase.AlignLeft),
                ('20%', [u'', u'Врач'], CReportBase.AlignLeft),
                ('5%', [u'', u'Услуга'], CReportBase.AlignLeft),
                ('5%', [u'Мероприятия', u'Тип'], CReportBase.AlignLeft),
                ('5%', [u'', u'Начато'], CReportBase.AlignLeft),
                ('5%', [u'', u'Окончено'], CReportBase.AlignLeft),
                ('5%', [u'', u'Состояние'], CReportBase.AlignLeft),
                ('5%', [u'', u'Количество'], CReportBase.AlignLeft)
            ]
        else:
            tableColumns = [
                ('5%', [u'№'], CReportBase.AlignRight),
                ('15%', [u'Пациент'], CReportBase.AlignLeft),
                ('5%', [u'Заболевания', u'Код по МКБ'], CReportBase.AlignLeft),
                ('5%', [u'', u'С'], CReportBase.AlignLeft),
                ('5%', [u'', u'По'], CReportBase.AlignLeft),
                ('5%', [u'', u'Характер'], CReportBase.AlignLeft),
                ('5%', [u'Посещения', u'Дата'], CReportBase.AlignLeft),
                ('15%', [u'', u'Врач'], CReportBase.AlignLeft),
                ('5%', [u'', u'Услуга'], CReportBase.AlignLeft),
                ('5%', [u'Мероприятия', u'Тип'], CReportBase.AlignLeft),
                ('5%', [u'', u'Начато'], CReportBase.AlignLeft),
                ('5%', [u'', u'Окончено'], CReportBase.AlignLeft),
                ('5%', [u'', u'Состояние'], CReportBase.AlignLeft),
                ('5%', [u'', u'Количество'], CReportBase.AlignLeft),
                ('10%', [u'', u'Код по MKБ'], CReportBase.AlignLeft)
            ]

        table = createTable(cursor, tableColumns)
        table.mergeCells(0, 0, 2, 1)
        table.mergeCells(0, 1, 2, 1)
        table.mergeCells(0, 2, 1, 4)
        table.mergeCells(0, 6, 1, 3)
        if self.chkDiagnosis:
            table.mergeCells(0, 9, 1, 5)
        else:
            table.mergeCells(0, 9, 1, 6)

        self.diagnostic = [[], [], [], [], [], []]
        self.visit = [[], [], [], [], []]
        if self.chkDiagnosis:
            self.action = [[], [], [], [], [], [], []]
        else:
            self.action = [[], [], [], [], [], [], [], []]

        def clearList(self):
            self.diagnostic[0] = []  # id диагноза
            self.diagnostic[1] = []  # код по МКБ
            self.diagnostic[2] = []  # дата С
            self.diagnostic[3] = []  # дата ПО
            self.diagnostic[4] = []  # характер заболевания
            self.diagnostic[5] = []  # посещение, за которым закреплено

            self.visit[0] = []  # id визита
            self.visit[1] = []  # дата визита
            self.visit[2] = []  # врач
            self.visit[3] = []  # услуга
            self.visit[4] = [
            ]  # хранит номер строки, разделяющей разные посещения

            self.action[0] = []  # id мероприятия
            self.action[1] = []  # тип мероприятия
            self.action[2] = []  # дата начала
            self.action[3] = []  # дата окончания
            self.action[4] = []  # состояние
            self.action[5] = []  # количество
            self.action[6] = []  # посещение, за которым закреплено
            if not self.chkDiagnosis:
                self.action[7] = []  # код по МКБ

        def addRow(table, currentRow, index, i, indexDeposite):
            oppositeIndex = 0 if index == 1 else 1
            if not currentRow[oppositeIndex] and currentRow[index]:
                indexDeposite[oppositeIndex].append(i)
            if len(indexDeposite[index]) == 0:
                if currentRow[index]:
                    i = table.addRow()
                    currentRow[oppositeIndex] = False
                    return i, currentRow, indexDeposite, i
                else:
                    currentRow[index] = True
                    return i, currentRow, indexDeposite, i
            else:
                currentI = i
                i = indexDeposite[index][0]
                del indexDeposite[index][0]
                return i, currentRow, indexDeposite, currentI

        def tableAddRows(self, table):
            if len(self.diagnostic) > 0 and len(self.visit) > 0 and len(
                    self.action) > 0 and self.clientId != None:
                if self.clientId == 206570:
                    pass
                i = table.addRow()
                currentRow = [False, False]
                startRowClient = i
                table.setText(i, 0, self.number)
                table.setHtml(i, 1, getClientBanner(self.clientId))
                j = 0
                visitIndexLow = 0
                for visitMerge in self.visit[4]:
                    sumDiagnostic = 0
                    sumAction = 0
                    indexDeposite = [[], []]
                    if visitMerge != self.visit[4][0]:
                        i = table.addRow()
                        currentRow = [False, False]
                    table.setText(i, 6, self.visit[1][j])
                    table.setText(i, 7, self.visit[2][j])
                    table.setText(i, 8, self.visit[3][j])
                    for rowNumber in range(
                            len(self.diagnostic[0]) if len(self.diagnostic[0])
                            >= len(self.action[0]) else len(self.action[0])):
                        if rowNumber < len(
                                self.diagnostic[0]
                        ) and self.diagnostic[5][rowNumber] == visitIndexLow:
                            i, currentRow, indexDeposite, currentI = addRow(
                                table, currentRow, 0, i, indexDeposite)
                            table.setText(i, 2, self.diagnostic[1][rowNumber])
                            table.setText(i, 3, self.diagnostic[2][rowNumber])
                            table.setText(i, 4, self.diagnostic[3][rowNumber])
                            table.setText(i, 5, self.diagnostic[4][rowNumber])
                            sumDiagnostic += 1
                            i = currentI
                        if rowNumber < len(self.action[0]) and self.action[6][
                                rowNumber] == visitIndexLow:
                            i, currentRow, indexDeposite, currentI = addRow(
                                table, currentRow, 1, i, indexDeposite)
                            table.setText(i, 9, self.action[1][rowNumber])
                            table.setText(i, 10, self.action[2][rowNumber])
                            table.setText(i, 11, self.action[3][rowNumber])
                            table.setText(i, 12, self.action[4][rowNumber])
                            table.setText(i, 13, self.action[5][rowNumber])
                            if not self.chkDiagnosis:
                                table.setText(i, 14, self.action[7][rowNumber])
                            sumAction += 1
                            i = currentI
                    j += 1
                    if sumDiagnostic == 0:
                        sumDiagnostic = 1
                    if sumAction == 0:
                        sumAction = 1
                    table.mergeCells(
                        startRowClient + visitMerge + sumDiagnostic - 1, 2,
                        sumAction - sumDiagnostic + 1, 1)
                    table.mergeCells(
                        startRowClient + visitMerge + sumDiagnostic - 1, 3,
                        sumAction - sumDiagnostic + 1, 1)
                    table.mergeCells(
                        startRowClient + visitMerge + sumDiagnostic - 1, 4,
                        sumAction - sumDiagnostic + 1, 1)
                    table.mergeCells(
                        startRowClient + visitMerge + sumDiagnostic - 1, 5,
                        sumAction - sumDiagnostic + 1, 1)
                    table.mergeCells(startRowClient + visitMerge, 6,
                                     i + visitMerge - startRowClient + 1, 1)
                    table.mergeCells(startRowClient + visitMerge, 7,
                                     i + visitMerge - startRowClient + 1, 1)
                    table.mergeCells(startRowClient + visitMerge, 8,
                                     i + visitMerge - startRowClient + 1, 1)
                    table.mergeCells(
                        startRowClient + visitMerge + sumAction - 1, 9,
                        sumDiagnostic - sumAction + 1, 1)
                    table.mergeCells(
                        startRowClient + visitMerge + sumAction - 1, 10,
                        sumDiagnostic - sumAction + 1, 1)
                    table.mergeCells(
                        startRowClient + visitMerge + sumAction - 1, 11,
                        sumDiagnostic - sumAction + 1, 1)
                    table.mergeCells(
                        startRowClient + visitMerge + sumAction - 1, 12,
                        sumDiagnostic - sumAction + 1, 1)
                    table.mergeCells(
                        startRowClient + visitMerge + sumAction - 1, 13,
                        sumDiagnostic - sumAction + 1, 1)
                    if not self.chkDiagnosis:
                        table.mergeCells(
                            startRowClient + visitMerge + sumAction - 1, 14,
                            sumDiagnostic - sumAction + 1, 1)
                    visitIndexLow += 1
                table.mergeCells(startRowClient, 0, i - startRowClient + 1, 1)
                table.mergeCells(startRowClient, 1, i - startRowClient + 1, 1)
            clearList(self)

        self.clientId = None
        self.number = 0
        query = selectDataNew(params)
        self.setQueryText(forceString(query.lastQuery()))
        while query.next():
            record = query.record()
            if self.clientId != forceInt(
                    record.value('client_id')) or self.clientId == None:
                tableAddRows(self, table)
                self.clientId = forceInt(record.value('client_id'))
                self.number += 1
                visitIndex = -1
            if len(self.visit[0]) == 0 or (
                    self.visit[0][-1] != forceInt(record.value('visitId'))
                    and forceInt(record.value('visitId')) != 0):
                self.visit[0].append(forceInt(record.value('visitId')))
                self.visit[1].append(
                    forceDateTime(record.value('visitDate')).toString(
                        'hh:mm dd.MM.yyyy'))
                if forceString(record.value('lastName')) and forceString(
                        record.value('firstName')) and forceString(
                            record.value('patrName')) and forceString(
                                record.value('postName')):
                    diagnosticPerson = forceString(
                        record.value('lastName')) + ' ' + forceString(
                            record.value('firstName')) + ' ' + forceString(
                                record.value('patrName')
                            ) + u', должность: ' + forceString(
                                record.value('postName'))
                elif forceString(record.value('lastName')) and forceString(
                        record.value('firstName')) and forceString(
                            record.value('patrName')):
                    diagnosticPerson = forceString(
                        record.value('lastName')) + ' ' + forceString(
                            record.value('firstName')) + ' ' + forceString(
                                record.value('patrName'))
                else:
                    diagnosticPerson = ''
                self.visit[2].append(diagnosticPerson)
                self.visit[3].append(forceString(record.value('serviceName')))
                self.visit[4].append(
                    len(self.diagnostic[0]) if len(self.diagnostic[0]) >= len(
                        self.action[0]) else len(self.action[0]))
                visitIndex += 1
            if len(self.diagnostic[0]) == 0 or (
                    self.diagnostic[0][-1] != forceInt(
                        record.value('diagnosticId'))
                    and forceInt(record.value('diagnosticId')) != 0):
                self.diagnostic[0].append(
                    forceInt(record.value('diagnosticId')))
                self.diagnostic[1].append(forceString(record.value('MKB')))
                self.diagnostic[2].append(
                    forceDate(record.value('setDate')).toString('dd.MM.yyyy'))
                self.diagnostic[3].append(
                    forceDate(record.value('endDate')).toString('dd.MM.yyyy'))
                diseaseCharacter = forceString(
                    record.value('diseaseCharacter'))
                if diseaseCharacter == '1':
                    self.diagnostic[4].append(u'острый')
                elif diseaseCharacter == '3':
                    self.diagnostic[4].append(u'хронический')
                else:
                    self.diagnostic[4].append(u'')
                self.diagnostic[5].append(visitIndex)
            if len(self.action[0]) == 0 or (
                    self.action[0][-1] != forceInt(record.value('actionId'))
                    and forceInt(record.value('actionId')) != 0):
                self.action[0].append(forceInt(record.value('actionId')))
                self.action[1].append(
                    forceString(record.value('actionTypeName')))
                self.action[2].append(
                    forceDate(
                        record.value('actionBegDate')).toString('dd.MM.yyyy'))
                self.action[3].append(
                    forceDate(
                        record.value('actionEndDate')).toString('dd.MM.yyyy'))
                status = forceInt(record.value('status'))
                self.action[4].append(
                    CActionType.retranslateClass(False).
                    statusNames[status] if status in xrange(5) else u'')
                self.action[5].append(forceString(record.value('amount')))
                if not self.chkDiagnosis:
                    self.action[7].append(
                        forceString(record.value('actionMKB')))
                self.action[6].append(visitIndex)
        tableAddRows(self, table)
        return doc
Exemple #16
0
    def on_btnSend_clicked(self):
        if self.writtenFileName:
            db = QtGui.qApp.db
            record = None

            for x in self.parent.selectedContractIdList:
                record = db.getRecord('Contract', 'format_id', forceInt(x))
                if record:
                    formatId = forceInt(record.value('format_id'))
                    if formatId:
                        record = db.getRecordEx('rbAccountExportFormat', '*', \
                            'id=%d' % formatId)
                        if record:
                            break

                    record = None

            if not record:
                record = db.getRecordEx('rbAccountExportFormat', '*',
                                        'prog=\'XML\'')

            if record:
                emailTo = forceString(record.value('emailTo'))
                subject = forceString(record.value('subject'))
                message = forceString(record.value('message'))
            else:
                emailTo = u'<введите адрес эл.почты>'
                subject = u'Результаты действий'
                message = u'Уважаемые господа,\n'                       \
                        u'Высылаем Вам результаты действий в формате XML\n' \
                        u'в {shortName}, ОГРН: {OGRN}\n'              \
                        u'за период с {actBegDate} по {actEndDate}\n'       \
                        u'в приложении {NR} записей\n'                \
                        u'для {NC} пациентов\n' \
                        u'фильтр статуса действий {actStatus}\n' \
                        u'номера договора(ов): {contractNumber}\n' \
                        u'\n'                                         \
                        u'--\n'                                       \
                        u'WBR\n'                                      \
                        u'{shortName}\n'

            orgRec = QtGui.qApp.db.getRecord('Organisation',
                                             'INN, OGRN, shortName',
                                             QtGui.qApp.currentOrgId())
            data = {}
            data['INN'] = forceString(orgRec.value('INN'))
            data['OGRN'] = forceString(orgRec.value('OGRN'))
            data['shortName'] = forceString(orgRec.value('shortName'))

            filtersPage = self.parent.page(
                0)  # qwizardpage с фильтрами по экспорту

            data['actBegDate'] = forceString(
                filtersPage.edtActionBegDate.date().toString(Qt.ISODate))
            data['actEndDate'] = forceString(
                filtersPage.edtActionEndDate.date().toString(Qt.ISODate))

            if filtersPage.chkActionStatus.isChecked():
                data['actStatus'] = CActionType.retranslateClass(
                    False).statusNames[
                        filtersPage.cmbActionStatus.currentIndex()]
            else:
                data['actStatus'] = u'любой'

            data['NR'] = self.recordsNumber
            data['NC'] = self.clientsNumber

            contractNumberList = []
            for x in self.parent.selectedContractIdList:
                contractInfo = getContractInfo(x)
                contractNumberList.append(forceString(contractInfo.number))

            data['contractNumber'] = u', '.join(
                [str(et) for et in contractNumberList])
            subject = substFields(subject, data)
            message = substFields(message, data)

            sendMail(self, emailTo, subject, message, [self.writtenFileName])