コード例 #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()
コード例 #2
0
ファイル: PatientEntranceReport.py プロジェクト: dio4/vista_1
    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
コード例 #3
0
    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
コード例 #4
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
コード例 #5
0
ファイル: InfoSourceReport.py プロジェクト: dio4/vista_1
    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)