Exemple #1
0
    def createParagraphs(self, contato, stylesheet):

        cleaned_data = self.filterset.form.cleaned_data

        imprimir_cargo = (cleaned_data['imprimir_cargo'] == 'True')\
            if 'imprimir_cargo' in cleaned_data and\
            cleaned_data['imprimir_cargo'] else False

        local_cargo = cleaned_data['local_cargo']\
            if 'local_cargo' in cleaned_data and\
            cleaned_data['local_cargo'] else ''

        story = []

        linha_pronome = ''
        prefixo_nome = ''

        if contato.pronome_tratamento:
            if 'imprimir_pronome' in cleaned_data and\
                    cleaned_data['imprimir_pronome'] == 'True':
                linha_pronome = getattr(
                    contato.pronome_tratamento,
                    'enderecamento_singular_%s' % lower(contato.sexo))
            prefixo_nome = getattr(
                contato.pronome_tratamento,
                'prefixo_nome_singular_%s' % lower(contato.sexo))

        if local_cargo == ImpressoEnderecamentoContatoFilterSet.DEPOIS_PRONOME\
                and imprimir_cargo and (linha_pronome or contato.cargo):
            linha_pronome = '%s - %s' % (linha_pronome, contato.cargo)

        if linha_pronome:
            story.append(Paragraph(linha_pronome, stylesheet['pronome_style']))

        linha_nome = '%s %s' % (prefixo_nome, contato.nome)\
            if prefixo_nome else contato.nome

        if local_cargo == ImpressoEnderecamentoContatoFilterSet.LINHA_NOME\
                and imprimir_cargo:

            linha_nome = '%s %s' % (contato.cargo, linha_nome)
            linha_nome = linha_nome.strip()

        linha_nome = linha_nome.upper()\
            if 'nome_maiusculo' in cleaned_data and\
            cleaned_data['nome_maiusculo'] == 'True' else linha_nome

        story.append(Paragraph(linha_nome, stylesheet['nome_style']))

        if local_cargo == ImpressoEnderecamentoContatoFilterSet.DEPOIS_NOME\
                and imprimir_cargo and contato.cargo:
            story.append(Paragraph(contato.cargo,
                                   stylesheet['endereco_style']))

        endpref = contato.endereco_set.filter(preferencial=True).first()
        if endpref:
            endereco = endpref.endereco +\
                (' - ' + endpref.numero if endpref.numero else '') +\
                (' - ' + endpref.complemento if endpref.complemento else '')

            story.append(Paragraph(endereco, stylesheet['endereco_style']))

            b_m_uf = '%s - %s - %s' % (endpref.bairro if endpref.bairro else
                                       '', endpref.municipio.nome if
                                       endpref.municipio else '', endpref.uf)

            story.append(Paragraph(b_m_uf, stylesheet['endereco_style']))
            story.append(Paragraph(endpref.cep, stylesheet['endereco_style']))

        return story
Exemple #2
0
    def get_data(self):
        """data ini 2016-08-29 09:45:43.018039
        data fim 2016-08-29 09:47:16.667659
        enumerate ini 2016-08-29 09:47:16.667745
        enumerate fim 2016-08-29 09:47:16.671923
        table ini 2016-08-29 09:47:16.671954
        table fim 2016-08-29 09:47:17.233298
        doc ini 2016-08-29 09:47:17.233338
        doc fim 2016-08-29 10:13:36.675347"""
        # 211 páginas
        # 6723

        MAX_TITULO = 80

        s = getSampleStyleSheet()
        h3 = s["Heading3"]
        h3.fontName = _baseFontNameB
        h3.alignment = TA_CENTER

        h4 = s["Heading4"]
        h4.fontName = _baseFontNameB

        h5 = s["Heading5"]
        h5.fontName = _baseFontNameB
        h5.alignment = TA_CENTER

        s = s["BodyText"]
        s.wordWrap = None  # 'LTR'
        s.spaceBefore = 0
        s.fontSize = 8
        s.leading = 8

        s_min = getSampleStyleSheet()
        s_min = s_min["BodyText"]
        s_min.wordWrap = None  # 'LTR'
        s_min.spaceBefore = 0
        s_min.fontSize = 6
        s_min.leading = 8

        s_center = getSampleStyleSheet()
        s_center = s_center["BodyText"]
        s_center.wordWrap = None  # 'LTR'
        s_center.spaceBefore = 0
        s_center.alignment = TA_CENTER
        s_center.fontSize = 8
        s_center.leading = 8

        s_right = getSampleStyleSheet()
        s_right = s_right["BodyText"]
        s_right.wordWrap = None  # 'LTR'
        s_right.spaceBefore = 0
        s_right.alignment = TA_RIGHT
        s_right.fontSize = 8
        s_right.leading = 8

        cleaned_data = self.filterset.form.cleaned_data

        agrupamento = cleaned_data['agrupamento']

        agrupamento = '' if agrupamento == 'sem_agrupamento' else agrupamento

        if not agrupamento:
            self.object_list = self.object_list.order_by(
                'data', 'titulo', 'contatos__nome')
        else:
            self.object_list = self.object_list.order_by(
                agrupamento).distinct(agrupamento).values_list(
                agrupamento, flat=True)

        data = []
        cabec = []
        cabec.append(Paragraph(_('Data'), h5))
        if agrupamento != 'titulo':
            cabec.append(Paragraph(_('Título'), h5))
        cabec.append(Paragraph(_('Nome'), h5))
        cabec.append(Paragraph(_('Endereço'), h5))
        cabec.append(Paragraph(_('Telefone'), h5))

        where = self.object_list.query.where

        for p in self.object_list.all():

            contatos_query = []
            item = []

            label_agrupamento = ''
            if not p or isinstance(p, str):
                label_agrupamento = dict(
                    ContatoAgrupadoPorProcessoFilterSet.AGRUPAMENTO_CHOICE)
                label_agrupamento = force_text(
                    label_agrupamento[agrupamento])

            if not data:
                tit_relatorio = _('Relatório de Contatos e Processos')
                tit_relatorio = force_text(tit_relatorio) + ' ' + ((
                    force_text(_('Agrupados')) + ' ' +
                    label_agrupamento) if label_agrupamento else (
                    force_text(_('Sem Agrupamento')) +
                    ' ' + label_agrupamento))

                data.append([Paragraph(tit_relatorio, h3)])

                if not label_agrupamento:
                    data.append(cabec)

            if not p or isinstance(p, str):
                data.append([])

                data.append([Paragraph((
                    label_agrupamento + ' - ' + str(p)) if p
                    else (force_text(_('Sem Agrupamento')) +
                          ' ' + label_agrupamento), h4)])

                data.append(cabec)

                p_filter = (('processo_set__' + agrupamento, p),)
                if not p:
                    p_filter = (
                        (p_filter[0][0] + '__isnull', True),
                        (p_filter[0][0] + '__exact', '')
                    )

                q = Q()
                for filtro in p_filter:
                    filtro_dict = {filtro[0]: filtro[1]}
                    q = q | Q(**filtro_dict)

                contatos_query = Contato.objects.all()
                contatos_query.query.where = where.clone()
                contatos_query = contatos_query.filter(q)

                params = {self.container_field: self.request.user.pk}
                contatos_query = contatos_query.filter(**params)

                contatos_query = contatos_query.order_by(
                    'processo_set__' + agrupamento,
                    'processo_set__data',
                    'nome',
                    'endereco_set__bairro__nome',
                    'endereco_set__endereco').distinct(
                    'processo_set__' + agrupamento,
                    'processo_set__data',
                    'nome')

            else:
                item = [
                    Paragraph(p.data.strftime('%d/%m/%Y'), s_center),
                    Paragraph(
                        str(p.titulo) if len(p.titulo) < MAX_TITULO
                        else p.titulo[:MAX_TITULO] +
                        force_text(_(' (Continua...)')), s if len(p.titulo) < MAX_TITULO else s_min)]

                contatos_query = p.contatos.all()

            contatos = []
            enderecos = []
            telefones = []
            for contato in contatos_query:

                if agrupamento:
                    contatos = []
                    enderecos = []
                    telefones = []
                    item = []

                if contatos:
                    contatos.append(Paragraph('--------------', s_center))
                    enderecos.append(Paragraph('--------------', s_center))
                    telefones.append(Paragraph('--------------', s_center))

                contatos.append(Paragraph(str(contato.nome), s))

                endpref = contato.endereco_set.filter(
                    preferencial=True).first()
                endereco = ''
                if endpref:
                    endereco = endpref.endereco +\
                        (' - ' + endpref.numero
                         if endpref.numero else '') +\
                        (' - ' + endpref.complemento
                         if endpref.complemento else '')

                    endereco = '%s - %s - %s - %s' % (
                        endereco,
                        endpref.bairro if endpref.bairro else '',
                        endpref.municipio.nome
                        if endpref.municipio else '',
                        endpref.uf)

                enderecos.append(Paragraph(endereco, s))

                tels = '\n'.join(map(
                    lambda x: str(x), list(contato.telefone_set.all())
                )) if contato.telefone_set.exists() else ''

                telefones.append((Paragraph(tels, s_center)))

                if agrupamento:
                    params = {'contatos': contato,
                              self.container_field: self.request.user.pk}
                    processos = Processo.objects.all()
                    processos.query.where = where.clone()
                    processos = processos.filter(**params)

                    ps = None
                    data_abertura = []
                    titulo = []
                    for ps in processos:

                        if data_abertura:
                            data_abertura.append(
                                Paragraph('--------------', s_center))
                            if agrupamento != 'titulo':
                                titulo.append(
                                    Paragraph('--------------', s_center))

                        data_abertura.append(
                            Paragraph(
                                ps.data.strftime('%d/%m/%Y'), s_center))

                        if agrupamento != 'titulo':
                            titulo.append(
                                Paragraph(
                                    str(ps.titulo)
                                    if len(ps.titulo) < MAX_TITULO
                                    else ps.titulo[:MAX_TITULO] +
                                    force_text(_(' (Continua...)')),
                                    s if len(ps.titulo) < MAX_TITULO
                                    else s_min))
                    if not ps:
                        data_abertura.append(Paragraph('-----', s_center))
                        if agrupamento != 'titulo':
                            titulo.append(Paragraph('-----', s_center))

                    if len(data_abertura) == 1:
                        item += data_abertura
                        if agrupamento != 'titulo':
                            item += titulo
                    else:
                        item.append(data_abertura)
                        if agrupamento != 'titulo':
                            item.append(titulo)

                    item.append(contatos[0])
                    item.append(enderecos[0])
                    item.append(telefones[0])

                    data.append(item)

                    """if len(data) > 2000:
                        return data"""

            if not agrupamento:
                if len(contatos) == 0:
                    item.append('-----')
                else:
                    item.append(contatos)
                    item.append(enderecos)
                    item.append(telefones)

                data.append(item)

                """if len(data) > 2000:
                    return data"""

        return data
def _build_invoices(prestations, invoice_number, invoice_date,
                    prescription_date, accident_id, accident_date,
                    patient_invoice_date, patient):
    # Draw things on the PDF. Here's where the PDF generation happens.
    # See the ReportLab documentation for the full list of functionality.
    elements = []
    i = 0
    data = []
    patientSocNumber = ''
    patientNameAndFirstName = ''
    patientName = ''
    patient_first_name = ''
    patient_address = ''

    data.append(('Num. titre', 'Prestation', 'Date', 'Nombre', 'Brut', 'CNS',
                 'Part. Client'))
    for presta in prestations:
        i += 1
        patientSocNumber = patient.code_sn
        patientNameAndFirstName = patient
        patientName = patient.name
        patient_first_name = patient.first_name
        patient_address = patient.address
        patientZipCode = patient.zipcode
        patientCity = patient.city
        data.append((
            i, presta.carecode.code, (presta.date).strftime('%d/%m/%Y'), '1',
            presta.carecode.gross_amount(presta.date),
            presta.carecode.net_amount(
                presta.date, patient.is_private,
                patient.participation_statutaire
                and patient.age > 18), "%10.2f" %
            (decimal.Decimal(presta.carecode.gross_amount(presta.date)) -
             decimal.Decimal(
                 presta.carecode.net_amount(presta.date, patient.is_private,
                                            patient.participation_statutaire)))
        ))

    for x in range(len(data), 22):
        data.append((x, '', '', '', '', '', ''))

    newData = []
    for y in range(0, len(data) - 1):
        newData.append(data[y])
        if (y % 10 == 0 and y != 0):
            _gross_sum = _compute_sum(data[y - 9:y + 1], 4)
            _net_sum = _compute_sum(data[y - 9:y + 1], 5)
            _part_sum = _compute_sum(data[y - 9:y + 1], 6)
            newData.append(('', '', '', 'Sous-Total', "%10.2f" % _gross_sum,
                            "%10.2f" % _net_sum, "%10.2f" % _part_sum))
    _total_facture = _compute_sum(data[1:], 5)
    _participation_personnelle = decimal.Decimal(_compute_sum(
        data[1:], 4)) - decimal.Decimal(_total_facture)
    newData.append(('', '', '', 'Total', "%10.2f" % _compute_sum(data[1:], 4),
                    "%10.2f" % _compute_sum(data[1:], 5),
                    "%10.2f" % _compute_sum(data[1:], 6)))

    headerData = [
        [
            'IDENTIFICATION DU FOURNISSEUR DE SOINS DE SANTE\n' +
            'Regine SIMBA\n' + '1A, rue fort wallis\n' +
            'L-2714 Luxembourg\n' + u"Tél: 691.30.85.84",
            'CODE DU FOURNISSEUR DE SOINS DE SANTE\n' + '300744-44'
        ],
        [
            u'Matricule patient: %s' % smart_text(patientSocNumber.strip()) +
            "\n" + u'Nom et Pr' + smart_text("e") +
            u'nom du patient: %s' % smart_text(patientNameAndFirstName),
            u'Nom: %s' % smart_text(patientName.strip()) + '\n' + u'Pr' +
            smart_text(u"é") +
            u'nom: %s' % smart_text(patient_first_name.strip()) + '\n' +
            u'Rue: %s' % patient_address.strip() + '\n' +
            u'Code postal: %s' % smart_text(patientZipCode.strip()) + '\n' +
            u'Ville: %s' % smart_text(patientCity.strip())
        ],
        [
            u'Date accident: %s\n' % (accident_date if accident_date else "") +
            u'Num. accident: %s' % (accident_id if accident_id else "")
        ]
    ]

    headerTable = Table(headerData, 2 * [10 * cm],
                        [2.5 * cm, 1 * cm, 1.5 * cm])
    headerTable.setStyle(
        TableStyle([
            ('ALIGN', (1, 1), (-2, -2), 'LEFT'),
            ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
            ('FONTSIZE', (0, 0), (-1, -1), 9),
            ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
            ('SPAN', (1, 1), (1, 2)),
        ]))

    table = Table(newData, 9 * [2.5 * cm], 24 * [0.5 * cm])
    table.setStyle(
        TableStyle([
            ('ALIGN', (1, 1), (-2, -2), 'LEFT'),
            ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
            ('ALIGN', (0, -1), (-6, -1), 'RIGHT'),
            ('INNERGRID', (0, -1), (-6, -1), 0, colors.white),
            ('ALIGN', (0, -2), (-6, -2), 'RIGHT'),
            ('INNERGRID', (0, -2), (-6, -2), 0, colors.white),
            ('FONTSIZE', (0, 0), (-1, -1), 8),
            ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
        ]))

    elements.append(headerTable)
    styles = getSampleStyleSheet()
    styles.add(ParagraphStyle(name='Center', alignment=TA_CENTER))
    elements.append(Spacer(1, 18))
    if (prescription_date is not None):
        elements.append(
            Paragraph(
                u"Mémoire d'Honoraires Num. %s en date du : %s Ordonnance du %s "
                % (invoice_number, invoice_date, prescription_date),
                styles['Heading4']))
    else:
        elements.append(
            Paragraph(
                u"Mémoire d'Honoraires Num. %s en date du : %s " %
                (invoice_number, invoice_date), styles['Heading4']))

    elements.append(Spacer(1, 18))

    elements.append(table)

    elements.append(Spacer(1, 18))

    _total_a_payer = Table([[
        "Total participation personnelle:",
        "%10.2f Euros" % _participation_personnelle
    ]], [10 * cm, 5 * cm],
                           1 * [0.5 * cm],
                           hAlign='LEFT')
    elements.append(Spacer(1, 18))
    elements.append(_total_a_payer)
    elements.append(Spacer(1, 18))

    elements.append(Spacer(1, 10))

    if patient_invoice_date is not None:
        from utils import setlocale
        with setlocale('en_GB.utf8'):
            if isinstance(patient_invoice_date, unicode):
                elements.append(
                    Table([[
                        u"Date envoi de la présente facture: %s " %
                        patient_invoice_date.strftime('%d %B %Y').encode(
                            'utf-8')
                    ]], [10 * cm],
                          1 * [0.5 * cm],
                          hAlign='LEFT'))
            else:
                elements.append(
                    Table([[
                        u"Date envoi de la présente facture: %s " %
                        patient_invoice_date.strftime('%d %B %Y').decode(
                            'utf-8')
                    ]], [10 * cm],
                          1 * [0.5 * cm],
                          hAlign='LEFT'))
        elements.append(Spacer(1, 10))

    return {
        "elements": elements,
        "invoice_number": invoice_number,
        "patient_name": patientName + " " + patient_first_name,
        "invoice_amount": newData[23][5],
        "invoice_pp": newData[23][6]
    }
Exemple #4
0
    def set_body_data(self, where, contatos_query, data, item):
        contatos = []
        enderecos = []
        telefones = []
        for contato in contatos_query:

            if self.agrupamento:
                contatos = []
                enderecos = []
                telefones = []
                item = []

            if contatos:
                contatos.append(Paragraph('--------------', self.s_center))
                enderecos.append(Paragraph('--------------', self.s_center))
                telefones.append(Paragraph('--------------', self.s_center))

            contatos.append(Paragraph(str(contato.nome), self.h_style))

            endpref = contato.endereco_set.filter(preferencial=True).first()
            endereco = ''
            if endpref:
                endereco = endpref.endereco + \
                           (' - ' + endpref.numero
                            if endpref.numero else '') + \
                           (' - ' + endpref.complemento
                            if endpref.complemento else '')

                endereco = '%s - %s - %s - %s' % (
                    endereco, endpref.bairro if endpref.bairro else '',
                    endpref.municipio.nome if endpref.municipio else '',
                    endpref.uf)

            enderecos.append(Paragraph(endereco, self.h_style))

            tels = '\n'.join(
                map(lambda x: str(x), list(contato.telefone_set.all()))
            ) if contato.telefone_set.exists() else ''

            telefones.append((Paragraph(tels, self.s_center)))

            if self.agrupamento:
                params = {
                    'contatos': contato,
                    self.container_field: self.request.user.pk
                }
                processos = Processo.objects.all()
                processos.query.where = where.clone()
                processos = processos.filter(**params)

                ps = None
                data_abertura = []
                titulo = []
                for ps in processos:

                    if data_abertura:
                        data_abertura.append(
                            Paragraph('--------------', self.s_center))
                        if self.agrupamento != 'titulo':
                            titulo.append(
                                Paragraph('--------------', self.s_center))

                    data_abertura.append(
                        Paragraph(ps.data.strftime('%d/%m/%Y'), self.s_center))

                    if self.agrupamento != 'titulo':
                        if len(ps.titulo) < self.MAX_TITULO:
                            paragrafo = str(ps.titulo)
                            estilo = self.h_style
                        else:
                            paragrafo = (ps.titulo[:self.MAX_TITULO] +
                                         force_text(_(' (Continua...)')))
                            estilo = self.s_min
                        titulo.append(Paragraph(paragrafo, estilo))

                if not ps:
                    data_abertura.append(Paragraph('-----', self.s_center))
                    if self.agrupamento != 'titulo':
                        titulo.append(Paragraph('-----', self.s_center))

                if len(data_abertura) == 1:
                    item += data_abertura
                    if self.agrupamento != 'titulo':
                        item += titulo
                else:
                    item.append(data_abertura)
                    if self.agrupamento != 'titulo':
                        item.append(titulo)

                item.append(contatos[0])
                item.append(enderecos[0])
                item.append(telefones[0])

                data.append(item)

        if not self.agrupamento:
            if len(contatos) == 0:
                item.append('-----')
            else:
                item.append(contatos)
                item.append(enderecos)
                item.append(telefones)

            data.append(item)
Exemple #5
0
    def build_pdf(self, response):
        CONTATO = 0
        TELEFONES_PREFERENCIAL = 1

        CIDADE = 0
        ENDERECO = 1
        BAIRRO = 2
        NUMERO = 3
        GRUPO = 4
        ID = 5
        NOME = 6

        self.set_headings()
        self.set_styles()
        self.set_cabec(self.h5)
        estilo = self.h_style

        corpo_relatorio = []
        self.add_relat_title(corpo_relatorio)

        registros = self.get_data()
        for dados in registros:
            endereco = ','.join(dados[CONTATO][ENDERECO:NUMERO])

            item = [
                Paragraph(dados[CONTATO][CIDADE], estilo),
                Paragraph(dados[CONTATO][GRUPO], estilo),
                Paragraph(dados[CONTATO][NOME], estilo),
                Paragraph(endereco, estilo),
                Paragraph(dados[TELEFONES_PREFERENCIAL], estilo),
            ]
            corpo_relatorio.append(item)

        style = TableStyle([
            ('FONTSIZE', (0, 0), (-1, -1), 8),
            ('LEADING', (0, 0), (-1, -1), 7),
            ('GRID', (0, 0), (-1, -1), 0.1, colors.black),
            ('INNERGRID', (0, 0), (-1, -1), 0.1, colors.black),
            ('TOPPADDING', (0, 0), (-1, -1), 0),
            ('BOTTOMPADDING', (0, 0), (-1, -1), 0),
            ('LEFTPADDING', (0, 0), (-1, -1), 3),
            ('RIGHTPADDING', (0, 0), (-1, -1), 3),
        ])
        style.add('VALIGN', (0, 0), (-1, -1), 'MIDDLE')

        for i, value in enumerate(corpo_relatorio):
            if len(value) <= 1:
                style.add('SPAN', (0, i), (-1, i))

            if len(value) == 0:
                style.add('INNERGRID', (0, i), (-1, i), 0, colors.black),
                style.add('GRID', (0, i), (-1, i), -1, colors.white)
                style.add('LINEABOVE', (0, i), (-1, i), 0.1, colors.black)

            if len(value) == 1:
                style.add('LINEABOVE', (0, i), (-1, i), 0.1, colors.black)

        rowHeights = 20
        t = LongTable(corpo_relatorio, rowHeights=rowHeights, splitByRow=True)
        t.setStyle(style)
        if len(t._argW) == 5:
            t._argW[0] = 1.8 * cm
            t._argW[1] = 6 * cm
            t._argW[2] = 6.5 * cm
            t._argW[3] = 9.5 * cm
            t._argW[4] = 2.4 * cm
        elif len(t._argW) == 4:
            t._argW[0] = 2 * cm
            t._argW[1] = 10 * cm
            t._argW[2] = 11.5 * cm
            t._argW[3] = 3 * cm

        for i, value in enumerate(corpo_relatorio):
            if len(value) == 0:
                t._argH[i] = 7
                continue
            for cell in value:
                if isinstance(cell, list):
                    t._argH[i] = (rowHeights) * (len(cell) -
                                                 (0 if len(cell) > 1 else 0))
                    break

        elements = [t]

        doc = SimpleDocTemplate(response,
                                pagesize=landscape(A4),
                                rightMargin=1.25 * cm,
                                leftMargin=1.25 * cm,
                                topMargin=1.1 * cm,
                                bottomMargin=0.8 * cm)
        doc.build(elements)
Exemple #6
0
def report_reserva(request, fecha1, fecha2, estado):
    #Create the HttpResponse headers with PDF
    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'inline; filename="reporte-reserva.pdf"'
    #Create the pdf object, using the BytesIO object as its "file."
    buffer = BytesIO()
    c = canvas.Canvas(buffer, pagesize=A4)

    # Header
    c.setLineWidth(.3)
    c.setFont('Helvetica', 22)
    c.drawString(30, 750, 'Hotel Amanecer')

    c.setFont('Helvetica', 12)
    c.drawString(30, 735, 'Reporte de Reservas')

    c.setFont('Helvetica-Bold', 12)
    c.drawString(480, 750, str(datetime.date.today()))
    # start X, height end y, heigth
    c.line(460, 747, 560, 747)

    # Tabla Reservas
    reservas = Reserva.objects.none()
    if estado == 'Todos':
        reservas = list(
            Reserva.objects.exclude(estado="Anulado").filter(
                fecha_entrada__gte=fecha1,
                fecha_entrada__lt=fecha2,
            ))
    else:
        reservas = list(
            Reserva.objects.filter(fecha_entrada__gte=fecha1,
                                   fecha_entrada__lt=fecha2,
                                   estado=estado))

    # Table header
    styles = getSampleStyleSheet()
    styleBH = styles["Normal"]
    styleBH.alignment = TA_CENTER
    styleBH.fontSize = 18

    cliente = Paragraph('''Cliente''', styleBH)
    habitacion = Paragraph('''Habitacion''', styleBH)
    fecha_entrada = Paragraph('''Entrada''', styleBH)
    fecha_salida = Paragraph('''Salida''', styleBH)
    costo_alojamiento = Paragraph('''Importe''', styleBH)

    data = []
    data.append(
        [cliente, habitacion, fecha_entrada, fecha_salida, costo_alojamiento])

    # Table body
    styleN = styles["Normal"]
    styleN.alignment = TA_CENTER
    styleN.fontSize = 7

    high = 650
    for reserva in reservas:
        this_reserva = [
            reserva.id_cliente_fk,
            reserva.id_habitacion_fk,
            reserva.fecha_entrada,
            reserva.fecha_salida,
            reserva.costo_alojamiento,
        ]
        data.append(this_reserva)
        high = high - 18

    # Table size
    width, height = A4
    table = Table(data,
                  colWidths=[
                      4.125 * cm,
                      2.5 * cm,
                      4.125 * cm,
                      4.125 * cm,
                      4.125 * cm,
                  ])
    table.setStyle(
        TableStyle([
            ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
            ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
        ]))
    # Pdf size
    table.wrapOn(c, width, height)
    table.drawOn(c, 30, high)

    # End writing

    c.showPage()
    c.save()
    # get the value of BytesIO buffer and write response
    pdf = buffer.getvalue()
    buffer.close()
    response.write(pdf)

    return response
Exemple #7
0
def _build_recap(recaps, payment_ref):
    elements = []
    data = []
    i = 0
    styles = getSampleStyleSheet()
    styles.add(ParagraphStyle(name='Center', alignment=TA_CENTER))
    elements.append(Spacer(3, 18))
    elements.append(Paragraph(u"Récapitulatif des notes", styles['Center']))
    elements.append(Spacer(3, 18))

    data.append(("No d'ordre", u"Note no°", u"Nom et prénom", "Montant"))
    total = 0.0
    for recap in recaps:
        i += 1
        data.append((i, recap[0], recap[1], recap[2]))
        total = decimal.Decimal(total) + decimal.Decimal(recap[2])
    data.append(("", "", u"Total", round(total, 2)))

    table = Table(data, [2 * cm, 3 * cm, 7 * cm, 3 * cm, 3 * cm])
    table.setStyle(
        TableStyle([
            ('ALIGN', (1, 1), (-2, -2), 'LEFT'),
            ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
            ('FONTSIZE', (0, 0), (-1, -1), 9),
            ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
        ]))
    elements.append(table)

    elements.append(Spacer(3, 18))

    _intro = Table([[
        u"Veuillez trouver ci-joint le récapitulatif des notes ainsi que le montant total payer"
    ]], [10 * cm, 5 * cm],
                   1 * [0.5 * cm],
                   hAlign='LEFT')
    elements.append(_intro)

    _total_a_payer = Table(
        [["Total " + u"à" + " payer:",
          "%10.2f Euros" % total]], [10 * cm, 5 * cm],
        1 * [0.5 * cm],
        hAlign='LEFT')
    elements.append(_total_a_payer)
    elements.append(Spacer(1, 18))

    _infos_iban = Table(
        [[u"Numéro compte IBAN: LU55 0019 4555 2516 1000 BCEELULL"]],
        [10 * cm],
        1 * [0.5 * cm],
        hAlign='LEFT')
    elements.append(_infos_iban)

    elements.append(Spacer(1, 18))
    _infos_iban = Table([[
        u"Lors du virement, veuillez indiquer la référence: %s " %
        payment_ref.upper()
    ]], [10 * cm],
                        1 * [0.5 * cm],
                        hAlign='LEFT')
    elements.append(_infos_iban)

    return elements
Exemple #8
0
def _build_invoices(prestations, invoice_number, invoice_date, accident_id,
                    accident_date):
    # Draw things on the PDF. Here's where the PDF generation happens.
    # See the ReportLab documentation for the full list of functionality.
    # import pydevd; pydevd.settrace()
    elements = []
    i = 0
    data = []
    patientSocNumber = ''
    patientNameAndFirstName = ''
    patientName = ''
    patientFirstName = ''
    patientAddress = ''

    data.append(('Num. titre', 'Prestation', 'Date', 'Nombre', 'Brut', 'Net',
                 'Heure', 'P. Pers', 'Executant'))
    pytz_luxembourg = pytz.timezone("Europe/Luxembourg")
    for presta in prestations:
        patient = presta.invoice_item.patient
        patientSocNumber = patient.code_sn
        patientNameAndFirstName = patient
        patientName = patient.name
        patientFirstName = patient.first_name
        patientAddress = patient.address
        patientZipCode = patient.zipcode
        patientCity = patient.city
        if presta.carecode.reimbursed:
            i += 1
            data.append((
                i,
                presta.carecode.code,
                (pytz_luxembourg.normalize(presta.date)).strftime('%d/%m/%Y'),
                '1',
                presta.carecode.gross_amount(presta.date),
                presta.carecode.gross_amount(presta.date),
                (pytz_luxembourg.normalize(presta.date)).strftime('%H:%M'),
                "",
                #TODO : replace with Global setting
                "300744-44"))

    for x in range(len(data), 22):
        data.append((x, '', '', '', '', '', '', '', ''))

    newData = []
    for y in range(0, len(data) - 1):
        newData.append(data[y])
        if y % 10 == 0 and y != 0:
            _gross_sum = _compute_sum(data[y - 9:y + 1], 4)
            _net_sum = _compute_sum(data[y - 9:y + 1], 5)
            newData.append(
                ('', '', '', 'Sous-Total', _gross_sum, _net_sum, '', '', ''))
    newData.append(('', '', '', 'Total', _compute_sum(data[1:], 4),
                    _compute_sum(data[1:], 5), '', '', ''))
    _total_facture = _compute_sum(data[1:], 5)

    headerData = [
        [
            'IDENTIFICATION DU FOURNISSEUR DE SOINS DE SANTE\n'
            # TODO : replace with Global setting
            + 'Regine SIMBA\n' + '1A, rue fort wallis\n' +
            'L-2714 Luxembourg\n' + u'Tél: 691.30.85.84',
            'CODE DU FOURNISSEUR DE SOINS DE SANTE\n' + '300744-44'
        ],
        [
            u'Matricule patient: %s' % smart_text(patientSocNumber.strip()) +
            "\n" + u'Nom et Pr' + smart_text("e") +
            u'nom du patient: %s' % smart_text(patientNameAndFirstName),
            u'Nom: %s' % smart_text(patientName.strip()) + '\n' + u'Pr' +
            smart_text(u"é") +
            u'nom: %s' % smart_text(patientFirstName.strip()) + '\n' +
            u'Rue: %s' % patientAddress.strip() + '\n' +
            u'Code postal: %s' % smart_text(patientZipCode.strip()) + '\n' +
            u'Ville: %s' % smart_text(patientCity.strip())
        ],
        [
            u'Date accident: %s\n' % (accident_date if accident_date else "") +
            u'Num. accident: %s' % (accident_id if accident_id else "")
        ]
    ]

    headerTable = Table(headerData, 2 * [10 * cm],
                        [2.5 * cm, 1 * cm, 1.5 * cm])
    headerTable.setStyle(
        TableStyle([
            ('ALIGN', (1, 1), (-2, -2), 'LEFT'),
            ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
            ('FONTSIZE', (0, 0), (-1, -1), 9),
            ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
            ('SPAN', (1, 1), (1, 2)),
        ]))

    table = Table(newData, 9 * [2 * cm], 24 * [0.5 * cm])
    table.setStyle(
        TableStyle([
            ('ALIGN', (1, 1), (-2, -2), 'LEFT'),
            ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
            ('ALIGN', (0, -1), (-6, -1), 'RIGHT'),
            ('INNERGRID', (0, -1), (-6, -1), 0, colors.white),
            ('ALIGN', (0, -2), (-6, -2), 'RIGHT'),
            ('INNERGRID', (0, -2), (-6, -2), 0, colors.white),
            ('FONTSIZE', (0, 0), (-1, -1), 8),
            ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
        ]))

    elements.append(headerTable)
    styles = getSampleStyleSheet()
    styles.add(ParagraphStyle(name='Center', alignment=TA_CENTER))
    elements.append(Spacer(1, 18))
    elements.append(
        Paragraph(
            u"Mémoire d'Honoraires Num. %s en date du : %s" %
            (invoice_number, invoice_date), styles['Center']))
    elements.append(Spacer(1, 18))
    elements.append(table)
    elements.append(Spacer(1, 18))
    _total_a_payer = Table(
        [["Total facture:", "%10.2f Euros" % _total_facture]],
        [10 * cm, 5 * cm],
        1 * [0.5 * cm],
        hAlign='LEFT')
    elements.append(Spacer(1, 18))
    elements.append(_total_a_payer)
    elements.append(Spacer(1, 18))

    return {
        "elements": elements,
        "invoice_number": invoice_number,
        "patient_name": patientName + " " + patientFirstName,
        "invoice_amount": newData[23][5]
    }
Exemple #9
0
def factura(request, pk, pago, vuelto):
    #Create the HttpResponse headers with PDF
    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'inline; filename="reporte-reserva.pdf"'
    #Create the pdf object, using the BytesIO object as its "file."
    buffer = BytesIO()
    c = canvas.Canvas(buffer, pagesize=A4)
    
    # Tabla Reservas
    reserva = Reserva.objects.get(id_reserva=pk)
    detalle_venta_prod = reserva.detalle_venta_prod.all()

    # Header
    c.setLineWidth(.3)
    c.setFont('Helvetica', 22)
    c.drawString(30,750,'Hotel Amanecer')
    
    c.setFont('Helvetica', 12)
    c.drawString(30,730, f'{"Factura - "} {reserva.id_reserva}')
    c.drawString(30,710, f'{"Costo de Alojamiento: "} {reserva.tag_costo_alojamiento()}')
    c.drawString(300,710, f'{"Consumo: "} {reserva.tag_total_consumo()}')
    c.drawString(30,690, f'{"Total: "} {reserva.tag_total()}')
    c.drawString(30,670, f'{"Total Abonado: "} {reserva.tag_total_pagos()}')
    c.drawString(300,670, f'{"Saldo Pendiente: "} {reserva.tag_saldo_pendiente()}')
    #c.drawString(30,675, f'{"Monto Pagado: "} {"..."}')
    #c.drawString(300,675, f'{"Vuelto: "} {"..."}')
    
    
    c.setFont('Helvetica-Bold', 12)
    c.drawString(480,750, str(datetime.date.today()))
    # start X, height end y, heigth
    c.line(460, 747, 560, 747)
    
    # Table header
    styles = getSampleStyleSheet()
    styleBH = styles["Normal"]
    styleBH.alignment = TA_CENTER
    styleBH.fontSize = 18
    
    producto = Paragraph('''Producto''', styleBH)
    cantidad = Paragraph('''Cantidad''', styleBH)
    precio = Paragraph('''Precio''', styleBH)
    subtotal = Paragraph('''Subtotal''', styleBH)
    
    data = []
    data.append([producto, cantidad, precio, subtotal])
    
    # Table body
    styleN = styles["Normal"]
    styleN.alignment = TA_CENTER
    styleN.fontSize = 7
    
    high = 630
    for consumo in detalle_venta_prod:
        this_consumo = [consumo.id_producto_fk,
                        consumo.tag_cantidad(),
                        consumo.tag_precio(),
                        consumo.tag_sub_total()
                        ]
        data.append(this_consumo)
        high = high - 18
        
    # Table size
    width, height = A4
    table = Table(data, colWidths=[4.75 * cm, 4.75 * cm, 4.75 * cm, 4.75 * cm, 4.75 * cm])
    table.setStyle(TableStyle([
        ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
        ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
        ]))
    # Pdf size
    table.wrapOn(c, width, height)
    table.drawOn(c, 30, high)
    
    high = high - 35
    
    c.drawString(30,high, f'{"Monto Pagado: "} {pago}')
    if int(vuelto) > 0:
        c.drawString(300,high, f'{"Vuelto: "} {vuelto}')  
    
    
    
    # End writing

    c.showPage()
    c.save()
    # get the value of BytesIO buffer and write response
    pdf = buffer.getvalue()
    buffer.close()
    response.write(pdf)

    return response
Exemple #10
0
 def append_para(self, text, in_style='Normal', bulletText=None):
     if type(text) in (ListType, TupleType):
         text = ''.join([self.encode(t) for t in text])
     style = self.styleSheet[in_style]
     self.story.append(Paragraph(self.encode(text), style, \
                                 bulletText=bulletText, context=self.styleSheet))