Exemple #1
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])
Exemple #2
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
Exemple #3
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
Exemple #4
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