Exemplo n.º 1
0
    def on_printSelected(self):
        items = self.model().items()
        rows = self.getSelectedRows()
        items = [(row, items[row]) for row in rows]
        temp = OrderedDict()
        for row, item in items:
            actionType = item[1]._actionType
            if not temp.has_key(actionType):
                temp[actionType] = []
            temp[actionType].append(
                (row, forceDateTime(item[0].value('directionDate'))))

        data = OrderedDict()
        for actionType, actionData in temp.items():
            data[actionType.id] = {
                'name': actionType.name,
                'actionData': actionData,
                'templates': getPrintTemplates(actionType.context)
            }
        dlg = CActionTemplatePrintWidget()
        self.connect(dlg, QtCore.SIGNAL('printActionTemplateList'),
                     self.on_printActionTemplateList)
        dlg.setItems(
            data, self._isDirty,
            forceBool(
                QtGui.qApp.preferences.appPrefs.get('groupPrintWithoutDialog',
                                                    QtCore.QVariant())))
        if dlg.model._items:
            dlg.exec_()
        else:
            dlg.printOnly()
Exemplo n.º 2
0
    def createRowsCols(self, table, chkDenouement, dict_denouement_mkb):
        '''

        :param table:
        :param chkDenouement: bool
        :param dict_denouement_mkb: MKBs
        :return:
        '''
        lst_frth_row = [u'1', u'2', u'3', u'4', u'5', u'6', u'7', u'8', u'9', u'10', u'11', u'12']

        lst_count = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21]

        dict_mkb = OrderedDict()
        dict_mkb['некоторые инфекционные и паразитарные болезни'] = 'A00 - B99'
        dict_mkb['новообразования'] = 'C00 - D48'
        dict_mkb['болезни крови, кроветворных органов и отдельные нарушения, вовлекающие иммунный механизм'] = 'D50 - D89'
        dict_mkb['болезни эндокринной системы, расстройства питания и нарушения обмена веществ'] = 'E00 - E90'
        dict_mkb['психические расстройства и расстройства поведения'] = 'F00 - F99'
        dict_mkb['болезни нервной системы'] = 'G00 - G99'
        dict_mkb['болезни глаза и его придаточного аппарата'] = 'H00 - H59'
        dict_mkb['болезни уха и сосцевидного отростка'] = 'H60 - H95'
        dict_mkb['болезни системы кровообращения'] = 'I00 - I99'
        dict_mkb['болезни органов дыхания'] = 'J00 - J99'
        dict_mkb['болезни органов пищеварения'] = 'K00 - K93'
        dict_mkb['болезни кожи и подкожной клетчатки'] = 'L00 - L98'
        dict_mkb['болезни костно-мышечной системы и соединительной ткани'] = 'M00 - M99'
        dict_mkb['болезни мочеполовой системы'] = 'N00 - N99'
        dict_mkb['беременность, роды и послеродовой период'] = 'O00 - O99'
        dict_mkb['отдельные состояния, возникающие в перинатальном периоде'] = 'P00 - P96'
        dict_mkb['врожденные аномалии, пороки развития, деформации и хромосомные нарушения'] = 'Q00 - Q99'
        dict_mkb['симптомы, признаки и отклонения от нормы, выявленные при клинических и лабораторных исследованиях, ' \
                 'не классифицированные в других  рубриках'] = 'R00 - R99'
        dict_mkb['травмы, отравления и некоторые другие последствия воздействия внешних причин'] = 'S00 - T98'
        dict_mkb['Кроме того: факторы, влияющие на состояние здоровья и обращения в учреждения здравоохранения'] = 'Z00 - Z99'
        #OrderedDict((word, True) for word in dict_mkb)
        i = table.addRow()
        for j in range(0, 12):
            table.setText(i, lst_count[j], lst_frth_row[j])

        i = table.addRow()
        table.setText(i, 0, "Всего, в том числе:")
        table.setText(i, 1, "1")

        if chkDenouement is False:
            table.setText(i, 2, "A00-T98")
            for j in range(0, len(dict_mkb)):
                i = table.addRow()
                table.setText(i, 0, dict_mkb.keys()[j])
                table.setText(i, 1, lst_count[j+2])
                table.setText(i, 2, dict_mkb.values()[j])
        elif chkDenouement is True:
            table.setText(i, 2, "")
            for j in range(0, len(dict_denouement_mkb)):
                i = table.addRow()
                table.setText(i, 0, dict_denouement_mkb.keys()[j])
                table.setText(i, 1, j+2)
                table.setText(i, 2, dict_denouement_mkb.values()[j])
Exemplo n.º 3
0
    def __init__(self, parent):
        QtGui.QDialog.__init__(self, parent)
        self.setupUi(self)

        self.edtConnectionName.completer().setCompletionMode(
            QtGui.QCompleter.UnfilteredPopupCompletion)
        self.connect(self, QtCore.SIGNAL('accepted()'),
                     self.saveConnectionInfo)
        self.connectionInfo = OrderedDict()
        self.loadConnectionInfo()
Exemplo n.º 4
0
 def params(self):
     params = {}
     params['begDate'] = self.edtBegDate.date()
     params['endDate'] = self.edtEndDate.date()
     params['eventTypeId'] = self.cmbEventType.value()
     params['orgStructureId'] = self.cmbOrgStructure.value()
     params['financeId'] = self.cmbFinance.value()
     params['diagnosisType'] = self.cmbDiagnosisType.value()
     params['MKBFilter'] = self.cmbMKBFilter.currentIndex()
     params['MKBFrom'] = forceString(self.edtMKBFrom.text())
     params['MKBTo'] = forceString(self.edtMKBTo.text())
     params['area'] = self.chkArea.isChecked()
     params['result'] = self.cmbResult.currentIndex()
     params['outputColumns'] = OrderedDict()
     for key in columns.keys():
         params['outputColumns'][key] = self.callObjectAtributeMethod(
             'chk%s' % key, 'isChecked')
     params['eventTypeIdMulti'] = self.lstEventType.nameValues()
     params['chkEventType'] = self.chkEventTypeMulti.isChecked()
     params['orgStructureIdMulti'] = self.lstOrgStructure.nameValues()
     params['chkOrgStructure'] = self.chkOrgStructureMulti.isChecked()
     params['financeIdMulti'] = self.lstOrgStructure.nameValues()
     params['chkFinance'] = self.chkOrgStructureMulti.isChecked()
     params['chkBirthDate'] = self.chkBirthDate.isChecked()
     params['MESFilter'] = self.cmbMES.currentIndex()
     params['MESFrom'] = forceString(self.edtMESFrom.text())
     params['MESTo'] = forceString(self.edtMESTo.text())
     return params
Exemplo n.º 5
0
    def __init__(self, parent):
        QtGui.QWizardPage.__init__(self, parent)
        self.setupUi(self)
        CExportHelperMixin.__init__(self)
        self.progressBar.setMinimum(0)
        self.progressBar.setMaximum(1)
        self.progressBar.setText('')

        self.setTitle(u'Экспорт справочников')
        self.setSubTitle(u'для выполнения шага нажмите на кнопку "Экспорт"')

        self.addModels('RefBooks', CRefBooksModel(self))
        self.setModels(self.tblRefBooks, self.modelRefBooks, self.selectionModelRefBooks)

        self.setExportMode(False)
        self.aborted = False
        self.done = False
        self._refBooks = OrderedDict()
        self.parent = parent
        self.loadPreferences(getPref(QtGui.qApp.preferences.windowPrefs, self.objectName(), {}))
        self.connect(parent, QtCore.SIGNAL('rejected()'), self.abort)
Exemplo n.º 6
0
    def build(self, params):
        query = selectData(params)
        self.setQueryText(forceString(query.lastQuery()))
        doc = QtGui.QTextDocument()
        cursor = QtGui.QTextCursor(doc)
        cursor.setCharFormat(CReportBase.ReportTitle)

        org_id = QtGui.qApp.currentOrgId()
        org_info = getOrganisationInfo(org_id)

        cursor.insertBlock(CReportBase.AlignCenter)
        cursor.insertText(org_info.get('fullName'))
        cursor.insertBlock(CReportBase.AlignCenter)
        cursor.insertText(self.title())

        cursor.insertBlock()
        self.dumpParams(cursor, params)
        cursor.insertBlock()

        tableColumns = [('20%', [u'Отделение'], CReportBase.AlignCenter)]

        valueDomain = QtGui.qApp.db.translate('ActionPropertyType', 'name',
                                              u'Cостояние пациента',
                                              'valueDomain')
        state_list = CStrComboBox.parse(forceString(valueDomain))[0]
        state_list.insert(0, u'')
        for header in state_list:
            tableColumns.append(('12%', [header], CReportBase.AlignCenter))

        tableColumns.append(('8%', [u'Всего'], CReportBase.AlignCenter))
        table = createTable(cursor, tableColumns)
        struct = OrderedDict()
        while query.next():
            record = query.record()
            org_struct = forceString(record.value('org_struct'))
            org_struct = org_struct if org_struct else u'без уточнения'
            patient_state = forceString(record.value('patient_state'))
            d = struct.setdefault(org_struct,
                                  OrderedDict.fromkeys(state_list, 0))
            d[patient_state] += 1

        total_col = OrderedDict.fromkeys(state_list, 0)
        total_col['total'] = 0
        for org_struct, d in struct.items():
            i = table.addRow()
            table.setText(i, 0, org_struct)
            total_row = 0
            for col, (state, num) in enumerate(d.items()):
                table.setText(i, col + 1, num)
                total_row += num
                total_col[state] += num
            table.setText(i, len(d) + 1, total_row)
            total_col['total'] += total_row
        i = table.addRow()
        table.setText(i, 0, u'Всего', CReportBase.TableTotal)
        for col, N in enumerate(total_col.values()):
            table.setText(i, col + 1, N, CReportBase.TableTotal)

        return doc
Exemplo n.º 7
0
 def params(self):
     params = {}
     params['begDate'] = self.edtBegDate.date()
     params['endDate'] = self.edtEndDate.date()
     params['orgStructureId'] = self.cmbOrgStructure.value()
     params['result'] = self.cmbResult.value()
     params['outputColumns'] = OrderedDict()
     for key in columns.keys():
         params['outputColumns'][key] = self.callObjectAtributeMethod(
             'chk%s' % key, 'isChecked')
     params['lstOrgStructure'] = self.lstOrgStructure.nameValues()
     params['chkOrgStructure'] = self.chkOrgStructureMulti.isChecked()
     params['cmbOrgStructure'] = params['chkOrgStructure']
     params['chkGroupOrgStructure'] = self.chkGroupOrgStructure.isChecked()
     params['clientDetail'] = self.chkClientDetail.isChecked()
     return params
Exemplo n.º 8
0
 def params(self):
     params = {}
     params['begDate'] = self.edtBegDate.date()
     params['endDate'] = self.edtEndDate.date()
     params['chkEventType'] = self.chkEventType.isChecked()
     params['eventTypeId'] = self.cmbEventType.value()
     params['lstEventType'] = self.lstEventType.nameValues()
     params['cmbOrgStructure'] = self.chkOrgStructure.isChecked()
     params['orgStructureId'] = self.cmbOrgStructure.value()
     params['lstOrgStructure'] = self.lstOrgStructure.nameValues()
     params['typeRegistry'] = self.cmbTypeRegistry.currentIndex()
     params['typeHospitalization'] = self.cmbHospitalization.currentIndex()
     params['columnsFilter'] = OrderedDict()
     for key in columns.keys():
         try:
             params['columnsFilter'][key] = self.callObjectAtributeMethod(
                 'chk%s' % key, 'isChecked')
         except AttributeError:
             params['columnsFilter'][key] = True
     return params
Exemplo n.º 9
0
class CExportPage1(QtGui.QWizardPage, Ui_ExportPage1, CExportHelperMixin, CConstructHelperMixin, CContainerPreferencesMixin):
    def __init__(self, parent):
        QtGui.QWizardPage.__init__(self, parent)
        self.setupUi(self)
        CExportHelperMixin.__init__(self)
        self.progressBar.setMinimum(0)
        self.progressBar.setMaximum(1)
        self.progressBar.setText('')

        self.setTitle(u'Экспорт справочников')
        self.setSubTitle(u'для выполнения шага нажмите на кнопку "Экспорт"')

        self.addModels('RefBooks', CRefBooksModel(self))
        self.setModels(self.tblRefBooks, self.modelRefBooks, self.selectionModelRefBooks)

        self.setExportMode(False)
        self.aborted = False
        self.done = False
        self._refBooks = OrderedDict()
        self.parent = parent
        self.loadPreferences(getPref(QtGui.qApp.preferences.windowPrefs, self.objectName(), {}))
        self.connect(parent, QtCore.SIGNAL('rejected()'), self.abort)

    def setExportMode(self, flag):
        """
            Настройка активных кнопок в зависимости от текущего состояния.
        """
        self.btnCancel.setEnabled(flag)
        self.btnExport.setEnabled(not flag)
        self.btnExport.setEnabled(not flag)

    def log(self, str, forceLog = True):
        """
            Вывод сообщения в окно отчета.
        """
        self.logBrowser.append(str)
        self.logBrowser.update()

    def export(self):
        (result, rc) = QtGui.qApp.call(self, self.exportInt)
        self.setExportMode(False)
        if self.aborted or not result:
            self.progressBar.setText(u'прервано')
        else:
            self.progressBar.setText(u'готово')
            self.done = True
            self.emit(QtCore.SIGNAL('completeChanged()'))

    def prepareToExport(self):
        self.done = False
        self.aborted = False
        self.emit(QtCore.SIGNAL('completeChanged()'))
        self.setExportMode(True)
        output = self.createXML()
        self.progressBar.reset()
        items = self.modelRefBooks.items()
        self._refBooks = self.modelRefBooks.getRBStructure()
        self.progressBar.setMaximum(len(items))
        self.progressBar.setValue(0)
        return output, items

    def exportInt(self):
        out, items = self.prepareToExport()
        refBooksOut = CRefBooksStreamWriter(self)
        refBooksOut.setCodec(QtCore.QTextCodec.codecForName('cp1251'))
        refBooksOut.writeFileHeader(out, self.parent.getFullXmlFileName(), QtCore.QDate.currentDate())
        for item in items:
            QtGui.qApp.processEvents()
            if self.aborted:
                break
            self.progressBar.step()
            rbData = self.getRBData(item)
            if rbData:
                refBooksOut.writeRecord(item, rbData)

        refBooksOut.writeFileFooter()
        out.close()

    def getRBData(self, item):
        """
            item: (rbTableName, keyColumnName)
            depends: self._refBooks
            Загрузка справочника из БД
        """
        columns = self._refBooks.get(item[0], {}).get('cols', None)
        if columns is None:
            return None
        fields = columns.keys()
        db = QtGui.qApp.db
        stmt = db.selectStmt(item[0], map(lambda x: '`'+x+'`', fields))
        query = db.query(stmt)
        result = []
        while query.next():
            record = query.record()
            recordValues = {}
            for field in fields:
                recordValues[field] = forceString(record.value(field))
            result.append(recordValues)
        return result

# *****************************************************************************************

    def getTxtFileName(self):
        lpuCode = forceString(QtGui.qApp.db.translate(
            'Organisation', 'id', QtGui.qApp.currentOrgId() , 'infisCode'))
        return forceString(lpuCode + u'.TXT')

    def createTxt(self):
        txt = QFile(os.path.join(self.parent.getTmpDir(), self.getTxtFileName()))
        txt.open(QIODevice.WriteOnly | QIODevice.Text)
        txtStream =  QTextStream(txt)
        txtStream.setCodec('CP866')
        return txt,  txtStream


    def validatePage(self):
        return True

# *****************************************************************************************

    def createXML(self):
        outFile = QtCore.QFile(self.parent.getFullXmlFileName())
        outFile.open(QtCore.QFile.WriteOnly | QtCore.QFile.Text)
        return outFile

# *****************************************************************************************

    def isComplete(self):
        return self.done


    def abort(self):
        self.aborted = True
        self.savePreferences()


    @QtCore.pyqtSignature('')
    def on_btnExport_clicked(self):
        self.export()


    @QtCore.pyqtSignature('')
    def on_btnCancel_clicked(self):
        self.abort()
Exemplo n.º 10
0
    def build(self, params):
        doc = QtGui.QTextDocument()

        cursor = QtGui.QTextCursor(doc)
        cursor.setCharFormat(CReportBase.ReportTitle)
        cursor.insertText(self.title())
        cursor.insertBlock()
        self.dumpParams(cursor, params)
        cursor.insertBlock()
        cursor.insertText("(2000)")
        cursor.insertBlock()

        tableColumns = [
            ('24%', [u'Профиль коек', u'', u'', u''], CReportBase.AlignLeft),
            ('3%', [u'№ строки', u'', u'', u''], CReportBase.AlignLeft),
            ('7%', [u'Дневные стационары медицинских организаций, оказывающих медицинскую помощь '
                    u'в стационарных условиях', u'Число коек', u'для взрослых', u'на конец года'], CReportBase.AlignLeft),
            ('6%', [u'', u'', u'', u'среднегодовых'], CReportBase.AlignLeft),
            ('6%', [u'', u'', u'для детей', u'на конец года'], CReportBase.AlignLeft),
            ('6%', [u'', u'', u'', u'среднегодовых'], CReportBase.AlignLeft),
            ('9%', [u'', u'Выписано пациентов', u'', u'взрослых'], CReportBase.AlignLeft),
            ('8%', [u'', u'', u'из них:', u'лиц старше трудоспособного возраста'], CReportBase.AlignLeft),
            ('8%', [u'', u'', u'', u'детей 0-17 лет включительно'], CReportBase.AlignLeft),
            ('9%', [u'', u'Проведено пациенто-дней', u'', u'взрослыми:'], CReportBase.AlignLeft),
            ('8%', [u'', u'', u'из них:', u'лицами старше трудоспособного возраста'], CReportBase.AlignLeft),
            ('6%', [u'', u'', u'', u'детьми 0-17 лет включительно'], CReportBase.AlignLeft)
        ]

        table = createTable(cursor, tableColumns)

        db = QtGui.qApp.db
        tblrbHospitalBedProfile = db.table('rbHospitalBedProfile')
        rbHospitalBedProfile = db.getRecordList(tblrbHospitalBedProfile, cols='*')
        profileBedId = getVal(params, 'profileBedId', None)

        #
        #  bedProfile_dict collects the bed types we have. If none bed_type is chosen, then we have to take all the
        #  bed_types in the db, else only the chosen beds
        #
        # else: we have the whole table 'rbhospitalbedprofile', and from the table we have to find the item with that
        # particular id and to put it in the list bedProfile_dict
        #
        #
        from decimal import Decimal
        bedProfile_dict = {}
        if profileBedId is None or not profileBedId:
            for i in range(0, len(rbHospitalBedProfile)):
                name = forceStringEx((rbHospitalBedProfile[i]).value('name'))
                row_code = forceStringEx((rbHospitalBedProfile[i]).value('row_code'))
                if row_code:
                    bedProfile_dict.update({name : Decimal(row_code)})
        else:
            for i in range(0, len(profileBedId)):
                rbProfileBed = db.getRecordEx(tblrbHospitalBedProfile, cols='name, row_code',
                                              where=tblrbHospitalBedProfile['id'].eq(profileBedId[i]))
                name = forceStringEx(rbProfileBed.value('name').toString())
                row_code = forceStringEx(rbProfileBed.value('row_code').toString())
                # print type(name), type(row_code)
                # Vidi dali da go pravish so Decimal(row_code), bidejki kako i da e unicode
                # ne mi teknuva dali nekade ke mi treba kako cifra, ili ke projde so Unicode,
                # ako sto brisi
                bedProfile_dict.update({name : Decimal(row_code)})

        #
        # creates as much rows as there are bed_profiles
        #
        from library.vm_collections import OrderedDict
        from operator import itemgetter
        bedProfile_dict = OrderedDict(sorted(bedProfile_dict.items(), key=itemgetter(1)))
        self.createRowsCols(table, bedProfile_dict)

        orgStructureId = getVal(params, 'orgStructureId', None)
        tblOrgstructure = db.table('OrgStructure')
        Orgstructure = db.getRecordList(tblOrgstructure, cols='id, name, parent_id')
        lst_id = []

        if orgStructureId is None:
            #
            # load everything from orgstructure, if no organisation is chosen
            #
            for rec in Orgstructure:
                lst_id.append(int(forceString(rec.value("id"))))
        else:
            #
            # list from the organisation_tree that should be included
            #
            lst_id.append(int(orgStructureId))
            for id in lst_id:
                for rec in Orgstructure:
                    if int(id) == int(forceString(rec.value("parent_id"))) and int(
                            forceString(rec.value("id"))) not in lst_id:
                        lst_id.append(int(forceString(rec.value("id"))))

        ageId = getVal(params, 'ageId', None)
        RegularBedId = getVal(params, 'RegularBedId', None)


        ii = 0

        lst_age = [
            "((YEAR(event.setDate) - YEAR(DATE(c.birthDate)) - (RIGHT(DATE(event.setDate), 5) < RIGHT(DATE(c.birthDate), 5))) >= 18)",
            "(((YEAR(event.setDate) - YEAR(DATE(c.birthDate)) - (RIGHT(DATE(event.setDate), 5) < RIGHT(DATE(c.birthDate), 5))) >= 60) AND c.sex = 1) "
            "OR (((YEAR(event.setDate) - YEAR(DATE(c.birthDate)) - (RIGHT(DATE(event.setDate), 5) < RIGHT(DATE(c.birthDate), 5))) >= 55) AND c.sex = 2)",
            "((YEAR(event.setDate) - YEAR(DATE(c.birthDate)) - (RIGHT(DATE(event.setDate), 5) < RIGHT(DATE(c.birthDate), 5))) < 18)"
            "AND ((YEAR(event.setDate) - YEAR(DATE(c.birthDate)) - (RIGHT(DATE(event.setDate), 5) < RIGHT(DATE(c.birthDate), 5))) >=0)"]

        lst_bedProfile = [
            "(oh.isPermanent = 1 OR oh.isPermanent = 0)", "oh.isPermanent = 1", "oh.isPermanent = 0"
        ]

        bedProfile = lst_bedProfile[0]
        if RegularBedId == 0:
            bedProfile = lst_bedProfile[0]
        elif RegularBedId == 1:
            bedProfile = lst_bedProfile[1]
        else:
            bedProfile = lst_bedProfile[2]

        sumBeds_col3 = 0
        sumBeds_col5 = 0
        sumPac_col7 = 0
        sumPac_col8 = 0
        sumPac_col9 = 0
        sumDays_col10 = 0
        sumDays_col11 = 0
        sumDays_col12 = 0

        #
        # We are looping through beds with row_code given, checking in each orgstructure if they have that bed
        # summing the values for each bed
        #
        for bed_id in range(0, len(bedProfile_dict)):
            sum_koek_vzrolsye = 0
            sum_koek_detey = 0
            sum_col7 = 0
            sum_col8 = 0
            sum_col9 = 0
            sum_col10 = 0
            sum_col11 = 0
            sum_col12 = 0

            for org_id in range(0, len(lst_id)):
                #
                # summing the columns for each organisation
                #
                query = selectData(params, lst_id[org_id], bedProfile, (bedProfile_dict.values()[bed_id]))
                self.setQueryText(forceString(query.lastQuery()))  # this does nothing?
                #
                # list of age range that is appending each time to the query
                # This is done in order to make the query smaller and simpler (changing the age range by looping in for cycle)
                #
                for j in range (0, len(lst_age)):
                    queryPacDays = selectData_PacientDays(params, lst_age[j], bedProfile, lst_id[org_id],
                                                          (bedProfile_dict.values()[bed_id]))
                    self.setQueryText(forceString(queryPacDays.lastQuery()))  # this does nothing?
                    #
                    # input: query that outputs the events (setDate, execDate and eventId). We calculate the days spend
                    # in SDP for a pacient belonging in particular age range (lst_age)
                    #
                    while queryPacDays.next():
                        recordPacDays = queryPacDays.record()
                        days = getEventLengthDays(
                            forceDate(recordPacDays.value('e_set')),
                            forceDate(recordPacDays.value('e_exec')),
                            countRedDays=False,
                            eventTypeId=forceString(recordPacDays.value('et_id')),
                            isDayStationary= True)

                        #
                        # Depending on the index in lst_age we sum the days for a pacient in a particular age range
                        #
                        if j == 0:
                            sum_col10 = sum_col10 + int(days)
                            sumDays_col10 = sumDays_col10 + int(days)
                        elif j == 1:
                            sum_col11 = sum_col11 + int(days)
                            sumDays_col11 = sumDays_col11 + int(days)
                        else:
                            sum_col12 = sum_col12 + int(days)
                            sumDays_col12 = sumDays_col12 + int(days)

                while query.next():
                    record = query.record()
                    try:
                        sum_koek_vzrolsye = sum_koek_vzrolsye + int(forceString(record.value('koek_vzroslye')))
                    except ValueError:
                        pass
                    try:
                        sum_koek_detey = sum_koek_detey + int(forceString(record.value('koek_detey')))
                    except ValueError:
                        pass
                    try:
                        sum_col7 = sum_col7 + int(forceString(record.value('col_7')))
                    except ValueError:
                        pass
                    try:
                        sum_col8 = sum_col8 + int(forceString(record.value('col_8')))
                    except ValueError:
                        pass
                    try:
                        sum_col9 = sum_col9 + int(forceString(record.value('col_9')))
                    except ValueError:
                        pass


            #
            # Depending on the choice in the combobox we have to choose the which columns are going to be filled
            #
            if ageId == 0:
                table.setText(ii + 6, 2, sum_koek_vzrolsye)
                table.setText(ii + 6, 4, sum_koek_detey)
                sumBeds_col3 = sumBeds_col3 + sum_koek_vzrolsye
                sumBeds_col5 = sumBeds_col5 + sum_koek_detey

                table.setText(ii + 6, 6, sum_col7)
                table.setText(ii + 6, 7, sum_col8)
                table.setText(ii + 6, 8, sum_col9)
                sumPac_col7 = sumPac_col7 + sum_col7
                sumPac_col8 = sumPac_col8 + sum_col8
                sumPac_col9 = sumPac_col9 + sum_col9

                table.setText(ii + 6, 9, sum_col10)
                table.setText(ii + 6, 10, sum_col11)
                table.setText(ii + 6, 11, sum_col12)
            elif ageId == 1:  # detey
                table.setText(ii + 6, 4, sum_koek_detey)
                sumBeds_col5 = sumBeds_col5 + sum_koek_detey

                table.setText(ii + 6, 8, sum_col9)
                sumPac_col9 = sumPac_col9 + sum_col9

                table.setText(ii + 6, 11, sum_col12)
            elif ageId == 2:  # vzroslye
                table.setText(ii + 6, 2, sum_koek_vzrolsye)
                sumBeds_col3 = sumBeds_col3 + sum_koek_vzrolsye

                table.setText(ii + 6, 6, sum_col7)
                table.setText(ii + 6, 7, sum_col8)
                sumPac_col7 = sumPac_col7 + sum_col7
                sumPac_col8 = sumPac_col8 + sum_col8

                table.setText(ii + 6, 9, sum_col10)
                table.setText(ii + 6, 10, sum_col11)

            ii = ii + 1
        if ageId == 0:
            table.setText(5, 2, sumBeds_col3)
            table.setText(5, 4, sumBeds_col5)
            table.setText(5, 6, sumPac_col7)
            table.setText(5, 7, sumPac_col8)
            table.setText(5, 8, sumPac_col9)
            table.setText(5, 9, sumDays_col10)
            table.setText(5, 10, sumDays_col11)
            table.setText(5, 11, sumDays_col12)
        elif ageId == 1:
            table.setText(5, 4, sumBeds_col5)
            table.setText(5, 8, sumPac_col9)
            table.setText(5, 11, sumDays_col12)
        else:
            table.setText(5, 2, sumBeds_col3)
            table.setText(5, 6, sumPac_col7)
            table.setText(5, 7, sumPac_col8)
            table.setText(5, 9, sumDays_col10)
            table.setText(5, 10, sumDays_col11)

        self.merge_cells(table)
        return doc
Exemplo n.º 11
0
class CConnectionDialog(QtGui.QDialog, Ui_connectionDialog):

    iniFileName = 'connections.ini'

    def __init__(self, parent):
        QtGui.QDialog.__init__(self, parent)
        self.setupUi(self)

        self.edtConnectionName.completer().setCompletionMode(
            QtGui.QCompleter.UnfilteredPopupCompletion)
        self.connect(self, QtCore.SIGNAL('accepted()'),
                     self.saveConnectionInfo)
        self.connectionInfo = OrderedDict()
        self.loadConnectionInfo()

    def setDriverName(self, val):
        pass

    def driverName(self):
        return 'mysql'

    def setServerName(self, val):
        self.edtServerName.setText(val)

    def setConnectionName(self, name):
        defaultName = u'Основной'
        connectionIndex = self.edtConnectionName.findText(name)
        if connectionIndex < 0:
            connectionIndex = self.edtConnectionName.findText(defaultName)
        if connectionIndex < 0:
            connectionIndex = self.edtConnectionName.findText(
                self.serverName())

        if connectionIndex < 0:
            self.edtConnectionName.setEditText(defaultName)
        else:
            self.edtConnectionName.setCurrentIndex(connectionIndex)

    def connectionName(self):
        return self.edtConnectionName.currentText()

    def serverName(self):
        return str(self.edtServerName.text())

    def setServerPort(self, val):
        self.edtServerPort.setValue(val)

    def serverPort(self):
        return self.edtServerPort.value()

    def setDatabsaseName(self, val):
        self.edtDatabaseName.setText(val)

    def setLoggerDbName(self, val):
        self.edtLoggerDbName.setText(val)

    def databaseName(self):
        return self.edtDatabaseName.text()

    def loggerDbName(self):
        if self.edtLoggerDbName.text():
            return self.edtLoggerDbName.text()
        else:
            self.edtLoggerDbName.setText(u"logger")
            return self.edtLoggerDbName.text()

    def setCompressData(self, val):
        self.chkCompressData.setChecked(bool(val))

    def compressData(self):
        return self.chkCompressData.isChecked()

    def setUserName(self, val):
        self.edtUserName.setText(val)

    def userName(self):
        return self.edtUserName.text()

    def setPassword(self, val):
        self.edtPassword.setText(val)

    def password(self):
        return str(self.edtPassword.text())

    def setNewAuthorizationScheme(self, val):
        checkedValue = bool(val)
        self.chkAutScheme.setChecked(checkedValue)
        self.on_chkAutScheme_clicked(checkedValue)

    def newAuthorizationScheme(self):
        return self.chkAutScheme.isChecked()

    def connectionOrgId(self):
        connectionInfo = self.connectionInfo.get(
            self.edtConnectionName.currentText(), None)
        return connectionInfo[3] if connectionInfo else 0

    def connectionLogin(self):
        connectionInfo = self.connectionInfo.get(
            self.edtConnectionName.currentText(), None)
        return connectionInfo[4] if connectionInfo else u''

    def connectionOrgStructureId(self):
        connectionInfo = self.connectionInfo.get(
            self.edtConnectionName.currentText(), None)
        return connectionInfo[5] if connectionInfo else 0

    @QtCore.pyqtSlot(bool)
    def saveConnectionInfo(self):
        settings = CPreferences.getSettings(self.iniFileName)
        settings.beginGroup(self.edtConnectionName.currentText())
        settings.setValue('host', toVariant(self.serverName()))
        settings.setValue('port', toVariant(self.serverPort()))
        settings.setValue('database', toVariant(self.databaseName()))
        settings.setValue('loggerdb', toVariant(self.loggerDbName()))
        #        settings.setValue('orgId', toVariant(QtGui.qApp.currentOrgId()))
        settings.endGroup()
        settings.sync()

    def loadConnectionInfo(self):
        self.connectionInfo.clear()
        settings = CPreferences.getSettings(self.iniFileName)
        for connectionName in settings.childGroups():
            settings.beginGroup(connectionName)
            self.connectionInfo[connectionName] = (
                forceString(settings.value('host', connectionName)),
                forceInt(settings.value('port', 0)),
                forceString(settings.value('database', u's11')),
                forceRef(settings.value('orgId', None)),
                forceString(settings.value('login', u'')),
                forceRef(settings.value('orgStructureId', None)),
                forceString(settings.value('loggerdb', u'logger')))
            settings.endGroup()
        self.edtConnectionName.addItems(self.connectionInfo.keys())

    @QtCore.pyqtSlot(bool)
    def on_chkAutScheme_clicked(self, checked):
        self.groupBox.setEnabled(not checked)

    @QtCore.pyqtSlot(int)
    def on_edtConnectionName_currentIndexChanged(self, index):
        currentText = self.edtConnectionName.currentText()
        if currentText in self.connectionInfo.keys():
            host, port, database = self.connectionInfo[currentText][:3]
            loggerdb = self.connectionInfo[currentText][6]
            self.setServerName(host)
            self.setServerPort(port)
            self.setDatabsaseName(database)
            self.setLoggerDbName(loggerdb)

    @QtCore.pyqtSlot()
    def on_btnDelConnectionInfo_clicked(self):
        settings = CPreferences.getSettings(self.iniFileName)
        currentText = self.edtConnectionName.currentText()
        if currentText in settings.childGroups():
            settings.remove(currentText)
            settings.sync()
        self.connectionInfo.pop(currentText, None)
        self.edtConnectionName.clear()
        self.edtConnectionName.addItems(self.connectionInfo.keys())
        self.edtConnectionName.setCurrentIndex(0)
Exemplo n.º 12
0
#############################################################################
##
## Copyright (C) 2006-2014 Chuk&Gek and Vista Software. All rights reserved.
##
#############################################################################

from PyQt4 import QtCore, QtGui

from Reports.Report import CReport
from Reports.ReportBase import createTable, CReportBase
from Ui_ReportAccount import Ui_ReportAccount
from library.AmountToWords import amountToWords
from library.Utils import forceDate, forceDouble, forceInt, forceRef, forceString
from library.vm_collections import OrderedDict

nameUnit = OrderedDict()
nameUnit[u'Стационар']                                 = (5,  u'койко-день')
nameUnit[u'Поликлиника']                               = (6,  u'посещение')
nameUnit[u'Стоматология']                              = (7,  u'УЕТ')
nameUnit[u'Дневной стационар']                         = (9,  u'пациенто-день')
nameUnit[u'Стационар дневного пребывания']             = (10, u'пациенто-день')
nameUnit[u'Женская консультация']                      = (11, u'посещение')
nameUnit[u'Стационар на дому']                         = (12, u'пациенто-день')
nameUnit[u'Дневной стационар женской консультации']    = (13, u'пациенто-день')
nameUnit[u'Центр здоровья']                            = (14, u'посещение')
nameUnit[u'Приемное отделение']                        = (15, u'посещение')
nameUnit[u'Фельдшерско-акушерский пункт']              = (16, u'посещение')
nameUnit[u'Скорая медицинская помощь']                 = (17, u'вызов')
nameUnit[u'Неотложная помощь']                         = (18, u'посещение')
nameUnit[u'Стационар санаторно-курортного учреждения'] = (19, u'койко-день')
nameUnit[u'Высокотехнологичная МП']                    = (20, u'койко-день')
Exemplo n.º 13
0
    def build_R2(self, cursor, query):
        tableColumns = [('35%', [u'Источник информации'],
                         CReportBase.AlignLeft),
                        ('10%', [u'Код пациента'], CReportBase.AlignRight),
                        ('35%', [u'ФИО'], CReportBase.AlignLeft),
                        ('20%', [u'Примечание'], CReportBase.AlignLeft)]
        table = createTable(cursor, tableColumns)
        from library.vm_collections import OrderedDict
        virtTable = OrderedDict()
        #virtTable structure:
        #{ sourceID : {
        #    'sourceName' : sourceName,
        #    'cnt' : cnt,
        #    'clients' : [
        #        {'Id': id, 'FIO': lastName + firstName + patrName},
        #        {}, ...
        #     ]
        # }, sourceID : {}, ... }
        total_cnt = 0
        while query.next():
            record = query.record()
            sourceID = forceRef(record.value('sourceID'))
            sourceName = forceString(record.value('sourceName'))
            Id = forceString(record.value('id'))
            lastName = forceString(record.value('lastName'))
            firstName = forceString(record.value('firstName'))
            patrName = forceString(record.value('patrName'))
            total_cnt += 1
            sourceName = sourceName if sourceID else u'<не указан источник информации>'
            sourceDict = virtTable.setdefault(sourceID, {
                'sourceName': sourceName,
                'cnt': 0,
                'clients': []
            })
            sourceDict.get('clients').append({
                'Id':
                Id,
                'FIO':
                formatName(lastName, firstName, patrName)
            })
            cnt = sourceDict.get('cnt')
            cnt += 1
            sourceDict['cnt'] = cnt

        charFormat = QtGui.QTextCharFormat()
        charFormat.setFontItalic(True)
        for sourceID, sourceDict in virtTable.items():
            i = table.addRow()
            sourceName = sourceDict.get('sourceName')
            clients = sourceDict.get('clients')
            cl = clients.pop(0)
            table.setText(i, 0, sourceName)
            table.setText(i, 1, cl.get('Id'))
            table.setText(i, 2, cl.get('FIO'))
            for cl in clients:
                j = table.addRow()
                table.setText(j, 1, cl.get('Id'))
                table.setText(j, 2, cl.get('FIO'))
            cnt = sourceDict.get('cnt')
            rate = float(cnt) / float(total_cnt) * 100.0
            table.mergeCells(i, 0, cnt, 1)
            i = table.addRow()
            table.setText(i, 0, u'Итого: ' + '%i (%.2f %%)' % (cnt, rate),
                          charFormat)
            table.mergeCells(i, 0, 1, 4)
        i = table.addRow()
        charFormat.setFontWeight(QtGui.QFont.Bold)
        table.setText(i, 0, u'Итоговое итого: ' + str(total_cnt), charFormat)
        table.mergeCells(i, 0, 1, 4)
Exemplo n.º 14
0
    def build(self, params):
        begDate = params.get('begDate', None)
        endDate = params.get('endDate', None)
        workOrgId = params.get('workOrgId', None)
        sex = params.get('sex', 0)
        ageFrom = params.get('ageFrom', 0)
        ageTo = params.get('ageTo', 150)
        areaIdEnabled = params.get('areaIdEnabled', False)
        areaId = params.get('areaId', None)
        MKBFilter = params.get('MKBFilter', 0)
        MKBFrom = params.get('MKBFrom', 'A00')
        MKBTo = params.get('MKBTo', 'Z99.9')
        MKBExFilter = params.get('MKBExFilter', 0)
        MKBExFrom = params.get('MKBExFrom', 'A00')
        MKBExTo = params.get('MKBExTo', 'Z99.9')
        socStatusType = params.get('socStatusType', None)
        socStatusClass = params.get('socStatusClass', None)
        personId = params.get('personId', None)

        query = QtGui.qApp.db.query(
            selectData(begDate, endDate, workOrgId, sex, ageFrom, ageTo,
                       areaIdEnabled, areaId, MKBFilter, MKBFrom, MKBTo,
                       MKBExFilter, MKBExFrom, MKBExTo, socStatusType,
                       socStatusClass, personId))
        self.setQueryText(forceString(query.lastQuery()))

        rows = OrderedDict()

        while query.next():
            rec = query.record()
            cid = forceRef(rec.value('cid'))
            dispanser = forceInt(rec.value('dispanser'))
            clientName = forceString(rec.value('clientName'))
            birthDate = forceDate(rec.value('birthDate'))
            clientPolicy = forceString(rec.value('clientPolicy'))
            SNILS = forceString(rec.value('SNILS'))
            socStatus = forceString(rec.value('socStatus'))
            diagName = forceString(rec.value('DiagName'))
            diagId = forceString(rec.value('DiagId'))
            setDate = forceDate(rec.value('setDate'))
            execDate = forceDate(rec.value('execDate'))
            visits = forceInt(rec.value('visits'))
            f20 = forceString(rec.value('f20'))

            d = rows.setdefault((cid, diagId), INITIAL_ROW_DICT.copy())
            if clientName:
                d['clientName'] = clientName
            if birthDate:
                d['birthDate'] = birthDate
            if clientPolicy:
                d['clientPolicy'] = clientPolicy
            if SNILS:
                d['SNILS'] = SNILS
            if socStatus:
                d['socStatus'] = socStatus
            if diagName:
                d['diagName'] = diagName
            if diagId:
                d['diagId'] = diagId
            if setDate and (not d['setDate']
                            or d['setDate'] > setDate) and dispanser in (1, 2):
                d['setDate'] = setDate
            if execDate and (not d['execDate'] or
                             d['execDate'] < execDate) and dispanser in (3, 4,
                                                                         5):
                d['execDate'] = execDate
            if visits:
                d['visits'] += visits
            if f20:
                d['f20'] = f20

        doc = QtGui.QTextDocument()
        cursor = QtGui.QTextCursor(doc)

        cursor.setCharFormat(CReportBase.ReportTitle)
        cursor.insertText(self.title())
        cursor.insertBlock()
        self.dumpParams(cursor, params)
        cursor.insertBlock()

        tableColumns = [
            ('5%', [u'№ п/п', u'', u'', u'', u'1'], CReportBase.AlignLeft),
            ('5%', [
                u'Сведения врача-терапевта участкового, врача-педиатра участкового, врача общей практики '
                u'(семейного врача)', u'Ф.И.О. пациента', u'', u'', u'2'
            ], CReportBase.AlignLeft),
            ('5%', [u'', u'Дата рождения', u'', u'',
                    u'3'], CReportBase.AlignLeft),
            ('5%', [u'', u'Номер полиса ОМС', u'', u'',
                    u'4'], CReportBase.AlignLeft),
            ('5%', [u'', u'СНИЛС', u'', u'', u'5'], CReportBase.AlignLeft),
            ('5%', [u'', u'Код категории льготы', u'', u'',
                    u'6'], CReportBase.AlignLeft),
            ('5%', [u'', u'Наименование заболевания', u'', u'',
                    u'7'], CReportBase.AlignLeft),
            ('5%', [u'', u'Код по МКБ-10', u'', u'',
                    u'8'], CReportBase.AlignLeft),
            ('5%',
             [u'', u'Дата начала диспансерного наблюдения', u'', u'',
              u'9'], CReportBase.AlignLeft),
            ('5%', [
                u'', u'Дата прекращения диспансерного наблюдения', u'', u'',
                u'10'
            ], CReportBase.AlignLeft),
            ('5%', [u'', u'Число посещений', u'', u'',
                    u'11'], CReportBase.AlignLeft),
            ('5%', [
                u'Сведения организационно-методического кабинета',
                u'Лекарственное обеспечение', u'выписано',
                u'наименование лекарственного препарата, дозировка', u'12'
            ], CReportBase.AlignLeft),
            ('5%', [u'', u'', u'', u'№ и серия рецепта',
                    u'13'], CReportBase.AlignLeft),
            ('5%', [
                u'', u'',
                u'фактически получено (наименование лекарственного препарата, дозировка)',
                u'', u'14'
            ], CReportBase.AlignLeft),
            ('5%',
             [u'', u'Стоимость лекарственного обеспечения', u'', u'',
              u'15'], CReportBase.AlignLeft),
            ('5%', [
                u'', u'Санитарно-курортное лечение', u'Выдано:',
                u'справок для получения путевки на санаторно-курортное лечение',
                u'16'
            ], CReportBase.AlignLeft),
            ('5%', [
                u'', u'', u'', u'из них на амбулаторное курортное лечение',
                u'17'
            ], CReportBase.AlignLeft),
            ('5%', [u'', u'', u'', u'санаторно-курортных карт',
                    u'18'], CReportBase.AlignLeft),
            ('5%', [
                u'', u'',
                u'Возвращено обратных талонов санаторно-курортных карт', u'',
                u'19'
            ], CReportBase.AlignLeft),
            ('5%', [
                u'',
                u'Направлено на госпитализацию, медицинскую реабилитацию, обследование, консультацию',
                u'', u'', u'20'
            ], CReportBase.AlignLeft),
        ]

        table = createTable(cursor, tableColumns)
        table.mergeCells(0, 0, 4, 1)
        table.mergeCells(0, 1, 1, 10)
        table.mergeCells(1, 1, 3, 1)
        table.mergeCells(1, 2, 3, 1)
        table.mergeCells(1, 3, 3, 1)
        table.mergeCells(1, 4, 3, 1)
        table.mergeCells(1, 5, 3, 1)
        table.mergeCells(1, 6, 3, 1)
        table.mergeCells(1, 7, 3, 1)
        table.mergeCells(1, 8, 3, 1)
        table.mergeCells(1, 9, 3, 1)
        table.mergeCells(1, 10, 3, 1)
        table.mergeCells(0, 11, 1, 9)
        table.mergeCells(1, 11, 1, 3)
        table.mergeCells(2, 11, 1, 2)
        table.mergeCells(2, 13, 2, 1)
        table.mergeCells(1, 14, 3, 1)
        table.mergeCells(1, 15, 1, 4)
        table.mergeCells(2, 15, 1, 3)
        table.mergeCells(2, 18, 2, 1)
        table.mergeCells(1, 19, 3, 1)

        for i, row in enumerate(rows.values()):
            birthDate = row['birthDate'].toString(
                'dd.MM.yyyy') if row['birthDate'] else '-'
            setDate = row['setDate'].toString(
                'dd.MM.yyyy') if row['setDate'] else '-'
            execDate = row['execDate'].toString(
                'dd.MM.yyyy') if row['execDate'] else '-'
            table.addRowWithContent(str(i + 1), row['clientName'], birthDate,
                                    row['clientPolicy'], row['SNILS'],
                                    row['socStatus'], row['diagName'],
                                    row['diagId'], setDate, execDate,
                                    str(row['visits']), '', '', '', '', '', '',
                                    '', '', row['f20'])

        cursor.movePosition(QtGui.QTextCursor.End)
        return doc
Exemplo n.º 15
0
#############################################################################
##
## Copyright (C) 2006-2014 Chuk&Gek and Vista Software. All rights reserved.
##
#############################################################################

from PyQt4 import QtGui

from library.Utils import forceString, forceInt, forcePrettyDouble
from library.vm_collections import OrderedDict
from Orgs.Utils import getOrgStructureDescendants
from Reports.Report import CReport
from Reports.ReportBase import createTable, CReportBase
from Reports.ReportOperationsActivity import CReportOperationsActivityDialog

columns = OrderedDict()
columns['ExternalId'] = u'№ истории \n болезни'
columns['ClientId'] = u'№ Амб. карты'
columns['FullName'] = u'ФИО'
columns['DaysBefore'] = u'Кол-во дней до'
columns['DaysAfter'] = u'Кол-во дней после'
columns['ExecPerson'] = u'Лечащий врач'
columns['ExecDate'] = u'Дата выписки'
columns['Result'] = u'Результат'


def selectData(params, group=True):
    begDate = params.get('begDate')
    endDate = params.get('endDate')
    orgStructureIds = (params.get('chkOrgStructure'),
                       params.get('orgStructureId'),
Exemplo n.º 16
0
    def build(self, params):
        doc = QtGui.QTextDocument()

        cursor = QtGui.QTextCursor(doc)
        cursor.setCharFormat(CReportBase.ReportTitle)
        cursor.insertText(self.title())
        cursor.insertBlock()
        self._title = u"3.1. Дневные стационары для взрослых"
        cursor.insertText(self.title())
        cursor.insertBlock()
        self.dumpParams(cursor, params)
        cursor.insertBlock()
        cursor.insertText("(3000)")
        cursor.insertBlock()

        tableColumns = [
            ('24%', [u'Наименование классов МКБ-10', u'', u''], CReportBase.AlignLeft),
            ('3%', [u'№ строки', u'', u''], CReportBase.AlignLeft),
            ('10%', [u'Код по МКБ-10', u'', u''], CReportBase.AlignLeft),
            ('7%', [u'Дневные стационары медицинских организаций, оказывающих медицинскую помощь', u'в стационарных условиях', u'Выписано пациентов'], CReportBase.AlignLeft),
            ('7%', [u'', u'', u'Проведено пациенто - дней'], CReportBase.AlignLeft),
            ('7%', [u'', u'', u'Умерло'], CReportBase.AlignLeft),
            ('7%', [u'', u'в амбулаторных условиях', u'Выписано пациентов'], CReportBase.AlignLeft),
            ('7%', [u'', u'', u'Проведено пациенто - дней'], CReportBase.AlignLeft),
            ('7%', [u'', u'', u'Умерло'], CReportBase.AlignLeft),
            ('7%', [u'', u'на дому', u'Выписано пациентов'], CReportBase.AlignLeft),
            ('7%', [u'', u'', u'Проведено пациенто - дней'], CReportBase.AlignLeft),
            ('7%', [u'', u'', u'Умерло'], CReportBase.AlignLeft)
        ]

        table = createTable(cursor, tableColumns)
        RegularBedId = getVal(params, 'RegularBedId', None)
        chkDenouement = getVal(params, 'chkDenouement', False)

        db = QtGui.qApp.db
        orgStructureId = getVal(params, 'orgStructureId', None)
        tblOrgstructure = db.table('OrgStructure')
        Orgstructure = db.getRecordList(tblOrgstructure, cols='id, name, parent_id')
        lst_id = []

        if orgStructureId is None:
            '''
            load everything from orgstructure, if no organisation is chosen
            '''
            for rec in Orgstructure:
                lst_id.append(int(forceString(rec.value("id"))))
        else:
            '''
            list from the organisation_tree that should be included
            '''
            lst_id.append(int(orgStructureId))
            for id in lst_id:
                for rec in Orgstructure:
                    if int(id) == int(forceString(rec.value("parent_id"))) and int(
                            forceString(rec.value("id"))) not in lst_id:
                        lst_id.append(int(forceString(rec.value("id"))))

        ii = 0
        lst_bedProfile = [
            "(oh.isPermanent = 1 OR oh.isPermanent = 0)", "oh.isPermanent = 1", "oh.isPermanent = 0"
        ]

        lst_MKB = ["'A00%%' AND 'B99%%' OR d.MKB LIKE 'B99%%'", "'C00%%' AND 'D48%%' OR d.MKB LIKE 'D48%%'",
                   "'D50%%' AND 'D89%%' OR d.MKB LIKE 'D89%%'", "'E00%%' AND 'E90%%' OR d.MKB LIKE 'E90%%'",
                   "'F00%%' AND 'F99%%' OR d.MKB LIKE 'F99%%'", "'G00%%' AND 'G99%%' OR d.MKB LIKE 'G99%%'",
                   "'H00%%' AND 'H59%%' OR d.MKB LIKE 'H59%%'", "'H60%%' AND 'H95%%' OR d.MKB LIKE 'H95%%'",
                   "'I00%%' AND 'I99%%' OR d.MKB LIKE 'I99%%'", "'J00%%' AND 'J99%%' OR d.MKB LIKE 'J99%%'",
                   "'K00%%' AND 'K93%%' OR d.MKB LIKE 'K93%%'", "'L00%%' AND 'L98%%' OR d.MKB LIKE 'L98%%'",
                   "'M00%%' AND 'M99%%' OR d.MKB LIKE 'M99%%'", "'N00%%' AND 'N99%%' OR d.MKB LIKE 'N99%%'",
                   "'O00%%' AND 'O99%%' OR d.MKB LIKE 'O99%%'", "'P00%%' AND 'P96%%' OR d.MKB LIKE 'P96%%'",
                   "'Q00%%' AND 'Q99%%' OR d.MKB LIKE 'Q99%%'", "'R00%%' AND 'R99%%' OR d.MKB LIKE 'R99%%'",
                   "'S00%%' AND 'T98%%' OR d.MKB LIKE 'T98%%'", "'Z00%%' AND 'Z99%%' OR d.MKB LIKE 'Z99%%'"]

        bedProfile = lst_bedProfile[0]
        if RegularBedId == 0:
            bedProfile = lst_bedProfile[0]
        elif RegularBedId == 1:
            bedProfile = lst_bedProfile[1]
        else:
            bedProfile = lst_bedProfile[2]

        dict_denouement_mkb = OrderedDict()
        tblMKB = db.table('MKB')

        if chkDenouement is True:
            for row in range(0, len(lst_MKB)):
                for org_id in range(0, len(lst_id)):
                    MKB_query = u"d.MKB BETWEEN %s" % lst_MKB[row]
                    query_SDP = selectDataMKB(params, lst_id[org_id], bedProfile,8, MKB_query)
                    query_DS = selectDataMKB(params, lst_id[org_id], bedProfile, 7, MKB_query)
                    self.setQueryText(forceString(query_SDP.lastQuery()))
                    self.setQueryText(forceString(query_DS.lastQuery()))
                    while query_SDP.next():
                        record = query_SDP.record()
                        mkb = forceString(record.value('MKB'))
                        mkb_name = db.getRecordEx(table=tblMKB, cols='DiagName', where=tblMKB['DiagID'].eq(mkb))
                        field = mkb_name.field(0)
                        dict_denouement_mkb[field.value().toString()] = forceString(record.value('MKB'))

                    while query_DS.next():
                        record = query_DS.record()
                        mkb = forceString(record.value('MKB'))
                        mkb_name = db.getRecordEx(table=tblMKB, cols='DiagName', where=tblMKB['DiagID'].eq(mkb))
                        field = mkb_name.field(0)
                        dict_denouement_mkb[field.value().toString()] = forceString(record.value('MKB'))

        elif chkDenouement is False:
            for row in range(0, len(lst_MKB)):
                dict_denouement_mkb[lst_MKB[row]] = ""

        self.createRowsCols(table, chkDenouement, dict_denouement_mkb)

        sumPac_col4 = 0
        sumDays_col5 = 0
        sumOth_col6 = 0
        sumPac_col7 = 0
        sumDays_col8 = 0
        sumOth_col9 = 0
        '''
        We are looping through list of MKB ranges, checking in each orgstructure if they have that bed
        summing the values for each bed
        '''
        for row in range(0, len(dict_denouement_mkb)):
            sum_col5 = 0
            sum_col8 = 0
            days_col5 = 0
            days_col8 = 0
            sumcol4 = 0
            sumcol6 = 0
            sumcol7 = 0
            sumcol9 = 0

            for org_id in range(0, len(lst_id)):
                if chkDenouement is False:
                    str_mkb = str(dict_denouement_mkb.keys()[row])[-6:-1]  # F99%%
                    MKB_query = u"(d.MKB BETWEEN %s OR d.MKB LIKE '%s')" % (dict_denouement_mkb.keys()[row], str_mkb)
                    '''
                    MKB_query (d.MKB BETWEEN 'E00%' AND 'E90%' OR d.MKB='E00')
                    '''
                    #MKB_query = u"d.MKB BETWEEN %s" % (dict_denouement_mkb.keys()[row])

                elif chkDenouement is True:
                    MKB_query = u"d.MKB = '%s'" % dict_denouement_mkb.values()[row]

                query_col5 = selectData_PacientDays(params, lst_id[org_id],bedProfile, 8, MKB_query)
                query_col8 = selectData_PacientDays(params, lst_id[org_id], bedProfile, 7, MKB_query)

                query = selectData(params, lst_id[org_id], bedProfile, MKB_query)

                self.setQueryText(forceString(query.lastQuery()))
                self.setQueryText(forceString(query_col5.lastQuery()))
                self.setQueryText(forceString(query_col8.lastQuery()))
                '''
                sum of pacients for every organisation (that's why in this for)
                '''
                while query_col5.next():
                    record_col5 = query_col5.record()
                    '''
                    get the number of days having in mind the length of the working week
                    '''
                    days_col5 = getEventLengthDays(
                        forceDate(record_col5.value('e_set')),
                        forceDate(record_col5.value('e_exec')),
                        countRedDays=False,
                        eventTypeId=forceString(record_col5.value('et_id')),
                        isDayStationary=True)

                    sum_col5 += int(days_col5)
                '''
                Всего, в том числе
                '''

                while query_col8.next():
                    record_col8 = query_col8.record()
                    days_col8 = getEventLengthDays(
                        forceDate(record_col8.value('e_set')),
                        forceDate(record_col8.value('e_exec')),
                        countRedDays=False,
                        eventTypeId=forceString(record_col8.value('et_id')),
                        isDayStationary=True)
                    sum_col8 += int(days_col8)

                while query.next():
                    record = query.record()
                    sumcol4 += int(forceString(record.value('discharge_Patients_SDP')))
                    sumcol7 += int(forceString(record.value('discharge_Patients_DS')))
                    sumcol6 += int(forceString(record.value('dead_SDP')))
                    sumcol9 += int(forceString(record.value('dead_DS')))

            sumDays_col5 += sum_col5
            sumDays_col8 += sum_col8

            table.setText(ii + 5, 4, sum_col5)
            table.setText(ii + 5, 7, sum_col8)

            sumPac_col4 += sumcol4
            sumPac_col7 += sumcol7
            sumOth_col6 += sumcol6
            sumOth_col9 += sumcol9
            table.setText(ii + 5, 3, sumcol4)
            table.setText(ii + 5, 5, sumcol6)
            table.setText(ii + 5, 6, sumcol7)
            table.setText(ii + 5, 8, sumcol9)

            ii = ii + 1

        '''
        sum of all the columns minus the last one (Z)
        '''
        if chkDenouement is False:
            sumPac_col4 -= int(sumcol4)
            sumDays_col5 -= int(days_col5)
            sumOth_col6 -= int(sumcol6)
            sumPac_col7 -= int(sumcol7)
            sumDays_col8 -= int(days_col8)
            sumOth_col9 -= int(sumcol9)

        table.setText(4, 3, sumPac_col4)
        table.setText(4, 4, sumDays_col5)
        table.setText(4, 5, sumOth_col6)
        table.setText(4, 6, sumPac_col7)
        table.setText(4, 7, sumDays_col8)
        table.setText(4, 8, sumOth_col9)

        self.merge_cells(table)
        return doc
    def build(self, params):
        query = selectData(params)
        self.setQueryText(forceString(query.lastQuery()))

        doc = QtGui.QTextDocument()
        cursor = QtGui.QTextCursor(doc)
        cursor.setCharFormat(CReportBase.ReportTitle)
        cursor.insertText(self.title())
        cursor.insertBlock()
        self.dumpParams(cursor, params)
        cursor.insertBlock()

        tableColumns = [('28%', [u'Отделение', u''], CReportBase.AlignLeft),
                        ('5%', [u'Госпитализировано',
                                u'Всего'], CReportBase.AlignRight),
                        ('8%', [u'', u'Плановых'], CReportBase.AlignRight),
                        ('8%', [u'', u'Экстренных'], CReportBase.AlignRight),
                        ('10%', [u'', u'в т.ч. ОМС'], CReportBase.AlignRight),
                        ('5%', [u'Не госпитализировано',
                                u'Всего'], CReportBase.AlignRight),
                        ('10%', [u'', u'Амбулатор.'], CReportBase.AlignRight),
                        ('10%', [u'', u'Отказн.'], CReportBase.AlignRight),
                        ('8%', [u'в т.ч. умерло',
                                u''], CReportBase.AlignRight),
                        ('8%', [u'Всего', u''], CReportBase.AlignRight)]

        table = createTable(cursor, tableColumns)
        table.mergeCells(0, 0, 2, 1)
        table.mergeCells(0, 1, 1, 4)
        table.mergeCells(0, 5, 1, 3)
        table.mergeCells(0, 8, 2, 1)
        table.mergeCells(0, 9, 2, 1)

        report = OrderedDict()

        while query.next():
            record = query.record()
            departmnt = forceString(record.value('departmnt'))
            depType = forceInt(record.value('depType'))
            evOrder = forceInt(record.value('evOrder'))
            rbFinance = forceString(record.value('rbFinance'))
            reasonDeny = forceString(record.value('reasonDeny'))
            actionResult = forceString(record.value('actionResult'))
            eventResult = forceString(record.value('eventResult'))
            """
            алгоритм:

            если есть св-во "Причина отказа от госпитализации":
                # это ветка Не госпитализировано
                если OrgStructure.type == 4:
                    -- это ветка Отказн --
                иначе:
                    -- это ветка Амбулатор --
            иначе:
                # это ветка Госпитализировано
                если Event.order == 1:
                    -- это ветка Плановых --
                если Event.order == 2:
                    -- это ветка Экстрен --
                если Event.order in (1,2) AND rbFinance == 'ОМС':
                    -- это ветка в т.ч. ОМС --

            если actionResult == 'умер' or eventResult.find('умер') > -1 or eventResult.find('смерть') > -1:
                -- это ветка в т.ч. умерло --
            """

            repRow = report.setdefault(departmnt, {
                'plan': 0,
                'extren': 0,
                'OMS': 0,
                'amb': 0,
                'deny': 0,
                'died': 0
            })

            if reasonDeny:
                if depType == 4:
                    repRow['deny'] += 1
                else:
                    repRow['amb'] += 1
            else:
                if evOrder == 1:
                    repRow['plan'] += 1
                if evOrder == 2:
                    repRow['extren'] += 1
                if evOrder in (1, 2) and rbFinance.upper() == u'ОМС':
                    repRow['OMS'] += 1
            eventResult = eventResult.lower()
            if actionResult.lower() == u'умер' or eventResult.find(
                    u'умер') > -1 or eventResult.find(u'смерть') > -1:
                repRow['died'] += 1

        total = {
            'plan': 0,
            'extren': 0,
            'OMS': 0,
            'amb': 0,
            'deny': 0,
            'died': 0
        }
        for department, depStat in report.items():
            i = table.addRow()

            plan = depStat.get('plan')
            extren = depStat.get('extren')
            OMS = depStat.get('OMS')
            deny = depStat.get('deny')
            amb = depStat.get('amb')
            died = depStat.get('died')

            table.setText(i, 0,
                          department if department else u'<без уточнения>')
            table.setText(i, 1, plan + extren)
            table.setText(i, 2, plan)
            table.setText(i, 3, extren)
            table.setText(i, 4, OMS)
            table.setText(i, 5, amb + deny)
            table.setText(i, 6, amb)
            table.setText(i, 7, deny)
            table.setText(i, 8, died)
            table.setText(i, 9, plan + extren + amb + deny)

            total['plan'] += plan
            total['extren'] += extren
            total['OMS'] += OMS
            total['deny'] += deny
            total['amb'] += amb
            total['died'] += died

        i = table.addRow()
        table.setText(i, 0, u'Итого:', CReportBase.TableTotal)
        table.setText(i, 1, total['plan'] + total['extren'],
                      CReportBase.TableTotal)
        table.setText(i, 2, total['plan'], CReportBase.TableTotal)
        table.setText(i, 3, total['extren'], CReportBase.TableTotal)
        table.setText(i, 4, total['OMS'], CReportBase.TableTotal)
        table.setText(i, 5, total['amb'] + total['deny'],
                      CReportBase.TableTotal)
        table.setText(i, 6, total['amb'], CReportBase.TableTotal)
        table.setText(i, 7, total['deny'], CReportBase.TableTotal)
        table.setText(i, 8, total['died'], CReportBase.TableTotal)
        table.setText(
            i, 9,
            total['plan'] + total['extren'] + total['amb'] + total['deny'],
            CReportBase.TableTotal)

        return doc
Exemplo n.º 18
0
    def build(self, params):
        noFinanceDetail = params.get('noFinanceDetail', False)

        db = QtGui.qApp.db
        doc = QtGui.QTextDocument()
        cursor = QtGui.QTextCursor(doc)
        cursor.setCharFormat(CReportBase.ReportTitle)
        cursor.insertText(self.title())
        cursor.insertBlock()
        self.dumpParams(cursor, params)
        cursor.insertBlock()
        tableColumns = [
            ('5%', [u'', u'', u'', u'', u''], CReportBase.AlignLeft),
            ('10%', [u'', u'', u'', u'', u''], CReportBase.AlignLeft),
            ('10%', [
                u'Движение больных за истекшие сутки',
                u'Состояло больных на начало текущих суток', u'', u'', u'1'
            ], CReportBase.AlignLeft),
            ('10%', [u'', u'Поступило больных', u'Всего', u'',
                     u'2'], CReportBase.AlignLeft),
            ('10%', [u'', u'', u'из них', u'пенсионеров',
                     u'3'], CReportBase.AlignLeft),
            ('10%', [u'', u'', u'из иногородних', u'всего',
                     u'4'], CReportBase.AlignLeft),
            ('10%', [u'', u'', u'', u'жителей села',
                     u'5'], CReportBase.AlignLeft),
            ('10%', [
                u'', u'Переведено больных внутри больницы',
                u'из других отделений', u'', u'6'
            ], CReportBase.AlignLeft),
            ('10%', [u'', u'', u'в другие отделения', u'',
                     u'7'], CReportBase.AlignLeft),
            ('5%', [u'', u'Выписано больных', u'', u'',
                    u'8'], CReportBase.AlignLeft),
            ('5%', [u'', u'Умерло', u'', u'', u'9'], CReportBase.AlignLeft),
            ('10%',
             [u'Состоит больных на начало текущего дня', u'', u'', u'',
              u'10'], CReportBase.AlignLeft)
        ]
        table = createTable(cursor, tableColumns)
        table.mergeCells(0, 0, 5, 1)
        table.mergeCells(0, 1, 5, 1)
        table.mergeCells(0, 2, 1, 9)
        table.mergeCells(1, 2, 3, 1)
        table.mergeCells(1, 3, 1, 4)
        table.mergeCells(2, 3, 2, 1)
        table.mergeCells(2, 5, 1, 2)
        table.mergeCells(1, 7, 1, 2)
        table.mergeCells(2, 7, 2, 1)
        table.mergeCells(2, 8, 2, 1)
        table.mergeCells(1, 9, 3, 1)
        table.mergeCells(1, 10, 3, 1)
        table.mergeCells(0, 11, 4, 1)

        (hospET, dayHospET, movingAT, receivedAT, leavedAT, movingCurOSAPT,
         movingFromOSAPT, movingToOSAPT, receivedCurOSAPT, leavedCurOSAPT,
         leavedOutcomeAPT, quoteAP, omsFinance, pmuFinance, dmsFinance,
         omsVmpFinance, omsLtFinance, akiFinance, budgetFinance,
         reanimationDepId, allReanimationsId) = loadIds()

        def getFinanceRow(rec):
            quotaClass = forceInt(rec.value('quotaClass')) if not rec.value(
                'quotaClass').isNull() else None
            financeID = forceInt(rec.value(
                'financeID')) if not rec.value('financeId').isNull() else None
            if quotaClass == 0:
                return 'vmp'
            if quotaClass == 1:
                return 'smp'
            if quotaClass == 7 or financeID == akiFinance:
                return 'aki'
            if financeID == omsFinance:
                return 'oms'
            if financeID == pmuFinance:
                return 'pmu'
            if financeID == dmsFinance:
                return 'dms'
            if financeID == omsVmpFinance and quotaClass == 5:
                return 'oms_vmp'
            if financeID == omsLtFinance:
                return 'oms_lt'
            if financeID == budgetFinance:
                return 'budget'
            QtGui.qApp.restoreOverrideCursor()
            res = QtGui.QMessageBox().warning(
                None, u'Не удалось определить тип финансирования',
                u'Код клиента: %s\nВнешний код: %s\nfinanceId: %s\nquotaClass: %s\n\n'
                u'Открыть обращение?' %
                (forceString(rec.value('cid')),
                 forceString(rec.value('externalId')), financeID, quotaClass),
                QtGui.QMessageBox.Yes | QtGui.QMessageBox.Retry
                | QtGui.QMessageBox.Cancel)
            if res == QtGui.QMessageBox.Yes:
                editEvent(None, forceRef(rec.value('eventId')))
            elif res == QtGui.QMessageBox.Retry:
                CArrivedDepartedPatients(None).exec_()
            raise ValueError

        def getEventType(rec):
            return 'ks' if forceRef(rec.value('eventType')) == hospET else 'ds'

        def getClientItem(rec):
            return '%s %s.%s. (%s)' % (forceString(rec.value('lastName')),
                                       forceString(rec.value('firstName'))[:1],
                                       forceString(rec.value('patrName'))[:1],
                                       forceString(rec.value('externalId')))

        # strType = '(type = 1 or type = 5)' if params['reanimation'] else 'type = 1'
        os_ids = params['LPU'] if not params['allLPU'] else \
            QtGui.qApp.db.getIdList('OrgStructure',
                                    where='(type = 1 or type = 5) AND hasHospitalBeds = 1 AND deleted = 0 AND '
                                          'EXISTS(SELECT oshb.id '
                                          '         FROM OrgStructure_HospitalBed oshb '
                                          '         WHERE oshb.master_id = OrgStructure.id)', order='code')

        finances = lambda: {
            'vmp': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
            'smp': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
            'oms': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
            'pmu': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
            'dms': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
            'oms_vmp': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
            'oms_lt': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
            'aki': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
            'budget': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
            'total': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
        }

        types = lambda: {
            'ks': finances(),
            'ds': finances(),
            'total': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
        }

        names = lambda: {'ks': set(), 'ds': set()}

        OSdata = OrderedDict((os_id, types()) for os_id in os_ids)
        OSdata['total'] = types()

        received = names()
        leaved_alive = names()
        leaved_dead = names()
        moved_to_current = names()  # Переведено из других
        moved_from_current = names()  # Переведено в другие

        startDate = params['begDate'].toTime_t(
        )  # int(time.mktime(datetime.strptime('2017-04-04 00:00:00', '%Y-%m-%d %H:%M:%S').timetuple()))
        endDate = params['endDate'].toTime_t(
        )  # int(time.mktime(datetime.strptime('2017-04-04 23:59:59', '%Y-%m-%d %H:%M:%S').timetuple()))

        moving_sql = MOVING_QUERY.format(hospET=hospET,
                                         dayHospET=dayHospET,
                                         movingAT=movingAT,
                                         movingCurOSAPT=movingCurOSAPT,
                                         quoteAP=quoteAP,
                                         movingFromOSAPT=movingFromOSAPT,
                                         movingToOSAPT=movingToOSAPT,
                                         startDate=startDate,
                                         endDate=endDate)

        queryReanimation_sql = QUERY_REANIMATIONDEPARTMENT.format(
            hospET=hospET,
            dayHospET=dayHospET,
            movingAT=movingAT,
            quoteAP=quoteAP,
            startDate=startDate,
            endDate=endDate,
            reanimationDepId=reanimationDepId,
            allReanimationsId=allReanimationsId)

        transfer_sql = TRANSFER_QUERY.format(hospET=hospET,
                                             dayHospET=dayHospET,
                                             movingAT=movingAT,
                                             movingCurOSAPT=movingCurOSAPT,
                                             quoteAP=quoteAP,
                                             movingFromOSAPT=movingFromOSAPT,
                                             movingToOSAPT=movingToOSAPT,
                                             startDate=startDate,
                                             endDate=endDate)

        received_sql = RECEIVED_QUERY.format(hospET=hospET,
                                             dayHospET=dayHospET,
                                             receivedAT=receivedAT,
                                             receivedCurOSAPT=receivedCurOSAPT,
                                             movingAT=movingAT,
                                             quoteAP=quoteAP,
                                             startDate=startDate,
                                             endDate=endDate)

        leaved_sql = LEAVED_QUERY.format(hospET=hospET,
                                         dayHospET=dayHospET,
                                         leavedAT=leavedAT,
                                         leavedCurOSAPT=leavedCurOSAPT,
                                         leavedOutcomeAPT=leavedOutcomeAPT,
                                         movingAT=movingAT,
                                         quoteAP=quoteAP,
                                         startDate=startDate,
                                         endDate=endDate)

        self.setQueryText(';\n'.join((moving_sql, received_sql, leaved_sql,
                                      transfer_sql, queryReanimation_sql)) +
                          ';')

        def inc(os, rec, column):
            financeRow = getFinanceRow(rec)
            eventType = getEventType(rec)
            OSdata[os]['total'][column] += 1
            OSdata[os][eventType]['total'][column] += 1
            OSdata[os][eventType][financeRow][column] += 1
            OSdata['total']['total'][column] += 1
            OSdata['total'][eventType]['total'][column] += 1
            OSdata['total'][eventType][financeRow][column] += 1

        try:
            if params['reanimation']:
                for rec in db.iterRecordList(stmt=transfer_sql):
                    recBegDate = forceLong(rec.value('begUNIX'))
                    recEndDate = forceLong(rec.value('endUNIX'))
                    recCurrentOS = forceRef(rec.value('currentOS'))
                    if startDate <= recBegDate <= endDate and recCurrentOS in OSdata.keys(
                    ):
                        moved_to_current[getEventType(rec)].add(
                            getClientItem(rec))
                        inc(recCurrentOS, rec, MOVED_TO_CURRENT)
                    if startDate <= recEndDate <= endDate and recCurrentOS in OSdata.keys(
                    ):
                        moved_from_current[getEventType(rec)].add(
                            getClientItem(rec))
                        inc(recCurrentOS, rec, MOVED_FROM_CURRENT)

            for rec in db.iterRecordList(stmt=queryReanimation_sql):
                recBegDate = forceLong(rec.value('begDate'))
                recEndDate = forceLong(rec.value('endDate'))
                recCurrentOS = forceRef(rec.value('currentOS'))
                endDateIndicator = forceInt(rec.value('endDateIndicator'))
                # moreThan2H = forceInt(rec.value('moreThan2H'))
                # if endDateIndicator == moreThan2H:
                if (
                        rec.value('endDate').isNull()
                        or recEndDate > recBegDate
                ) and recBegDate < startDate and recCurrentOS in OSdata.keys():
                    #startDate <= recBegDate <= endDate
                    inc(recCurrentOS, rec, START_COUNT)
                if startDate <= recBegDate <= endDate and recCurrentOS in OSdata.keys(
                ):
                    moved_to_current[getEventType(rec)].add(getClientItem(rec))
                    inc(recCurrentOS, rec, MOVED_TO_CURRENT)
                if (startDate <= recEndDate <=
                        endDate) and recCurrentOS in OSdata.keys():
                    moved_from_current[getEventType(rec)].add(
                        getClientItem(rec))
                    inc(recCurrentOS, rec, MOVED_FROM_CURRENT)
                if (
                        rec.value('endDate').isNull() or recEndDate > endDate
                ) and recBegDate <= endDate and recCurrentOS in OSdata.keys():
                    inc(recCurrentOS, rec, END_COUNT)

            for rec in db.iterRecordList(stmt=moving_sql):
                recBegDate = forceLong(rec.value('begDate'))
                recEndDate = forceLong(rec.value('endDate'))
                recCurrentOS = forceRef(rec.value('currentOS'))
                recFromOS = forceRef(rec.value('fromOS'))
                recToOS = forceRef(rec.value('toOS'))
                if (recBegDate <= startDate and
                    (recEndDate >= startDate or rec.value('endDate').isNull())
                        and recCurrentOS in OSdata.keys()):
                    inc(recCurrentOS, rec, START_COUNT)
                if (recBegDate <= endDate and
                    (recEndDate >= endDate or rec.value('endDate').isNull())
                        and recCurrentOS in OSdata.keys()):
                    inc(recCurrentOS, rec, END_COUNT)
                # переведены в указанные отделения
                if (startDate <= recEndDate <= endDate
                        and recCurrentOS is not None
                        and recToOS in OSdata.keys()):
                    moved_to_current[getEventType(rec)].add(getClientItem(rec))
                    inc(recToOS, rec, MOVED_TO_CURRENT)
                # переведены из указанных отделений
                if (startDate <= recBegDate <= endDate
                        and recCurrentOS is not None
                        and recFromOS in OSdata.keys()):
                    moved_from_current[getEventType(rec)].add(
                        getClientItem(rec))
                    inc(recFromOS, rec, MOVED_FROM_CURRENT)

            for rec in db.iterRecordList(stmt=received_sql):
                recIsVillager = forceBool(rec.value('isVillager'))
                recIsForeigner = forceBool(rec.value('isForeigner'))
                recIsPensioner = forceBool(rec.value('isPensioner'))
                recCurrentOS = forceRef(rec.value('currentOS'))
                recEndDate = forceLong(rec.value('endDate'))
                if (startDate <= recEndDate <= endDate
                        and recCurrentOS in OSdata.keys()):
                    inc(recCurrentOS, rec, RECEIVED_TOTAL)
                    received[getEventType(rec)].add(getClientItem(rec))
                    if recIsPensioner:
                        inc(recCurrentOS, rec, RECEIVED_PENSIONER)
                    if recIsForeigner:
                        inc(recCurrentOS, rec, RECEIVED_FOREIGN)
                    if recIsVillager:
                        inc(recCurrentOS, rec, RECEIVED_VILLAGER)

            for rec in db.iterRecordList(stmt=leaved_sql):
                recBegDate = forceLong(rec.value('begDate'))
                recCurrentOS = forceRef(rec.value('currentOS'))
                recIsDeath = forceString(rec.value('outcome')) == u'умер'
                if startDate <= recBegDate <= endDate and recCurrentOS in OSdata.keys(
                ):
                    if recIsDeath:
                        leaved_dead[getEventType(rec)].add(getClientItem(rec))
                        inc(recCurrentOS, rec, LEAVED_DEAD)
                    else:
                        leaved_alive[getEventType(rec)].add(getClientItem(rec))
                        inc(recCurrentOS, rec, LEAVED_ALIVE)
        except ValueError:
            return None

        def write_event_type(os_id, is_ks=True):
            et = 'ks' if is_ks else 'ds'
            if not noFinanceDetail:
                row = table.addRowWithContent(u'', u'ВМП',
                                              *OSdata[os_id][et]['vmp'])
                table.addRowWithContent(u'', u'СМП', *OSdata[os_id][et]['smp'])
                table.addRowWithContent(u'', u'ОМС', *OSdata[os_id][et]['oms'])
                table.addRowWithContent(u'', u'ПМУ', *OSdata[os_id][et]['pmu'])
                table.addRowWithContent(u'', u'ДМС', *OSdata[os_id][et]['dms'])
                table.addRowWithContent(u'', u'ВМП из ОМС',
                                        *OSdata[os_id][et]['oms_vmp'])
                table.addRowWithContent(u'', u'ОМС ЛТ',
                                        *OSdata[os_id][et]['oms_lt'])
                table.addRowWithContent(u'', u'АКИ', *OSdata[os_id][et]['aki'])
                table.addRowWithContent(u'', u'Донор/Прочее',
                                        *OSdata[os_id][et]['budget'])
            table.addRowWithContent(u'КС' if is_ks else u'ДС',
                                    u'Итого',
                                    *OSdata[os_id][et]['total'],
                                    charFormat=self.boldFormat)
            if not noFinanceDetail:
                table.mergeCells(row, 0, 10, 1)

        for os_id in OSdata.keys():
            if os_id == 'total':
                if len(os_ids) == 1:
                    continue
                os_code = u'все подразделения'
            else:
                os_code = forceString(
                    db.translate('OrgStructure', 'id', os_id, 'code'))
            row = table.addRowWithContent(os_code)
            table.mergeCells(row, 0, 1, 12)
            write_event_type(os_id)
            write_event_type(os_id, False)
            row = table.addRowWithContent(u'Итого ' + os_code,
                                          u'',
                                          *OSdata[os_id]['total'],
                                          charFormat=self.boldFormat)
            table.mergeCells(row, 0, 1, 2)

        if noFinanceDetail:
            table.table.removeColumns(1, 1)

        cursor.movePosition(QtGui.QTextCursor.End)
        cursor.insertBlock()
        cursor.insertText(
            u'\nДежурная медсестра: _____________________________________')
        cursor.insertBlock()

        if not params['allLPU']:

            def insertClientList(lst, row, col):
                table.setHtml(
                    row, col,
                    u'<ol><li>' + u'</li><li>'.join(lst) + u'</li></ol>')

            def insertClientsRow(et):
                table.addRow()
                insertClientList(received[et], 1, 0)
                insertClientList(leaved_alive[et], 1, 1)
                insertClientList(leaved_dead[et], 1, 2)
                insertClientList(moved_to_current[et], 1, 3)
                insertClientList(moved_from_current[et], 1, 4)

            tableColumns = [
                ('20%', [u'Поступило:'], CReport.AlignLeft),
                ('20%', [u'Выписано:'], CReport.AlignLeft),
                ('20%', [u'Умерло:'], CReport.AlignLeft),
                ('20%', [u'Переведено из:'], CReport.AlignLeft),
                ('20%', [u'Переведено в:'], CReport.AlignLeft),
            ]

            cursor.insertText(u'\n\nГоспитализация', CReport.ReportSubTitle)
            textFormat = QtGui.QTextBlockFormat()
            textFormat.setPageBreakPolicy(
                QtGui.QTextBlockFormat.PageBreak_AlwaysBefore)
            cursor.setBlockFormat(textFormat)
            cursor.insertBlock()
            textFormat.setPageBreakPolicy(
                QtGui.QTextBlockFormat.PageBreak_Auto)
            cursor.setBlockFormat(textFormat)

            table = createTable(cursor, tableColumns, border=0, cellPadding=0)
            insertClientsRow('ks')
            cursor.movePosition(QtGui.QTextCursor.End)

            cursor.insertBlock()
            cursor.insertText(u'\n\nДС Госпитализация', CReport.ReportSubTitle)
            cursor.insertBlock()
            table = createTable(cursor, tableColumns, border=0, cellPadding=0)
            table.table.format().setAlignment(QtCore.Qt.AlignTop)
            insertClientsRow('ds')

        return doc