Skip to content

Commit

Permalink
[MIG] l10n_ch_payment_slip: Migration to 11.0
Browse files Browse the repository at this point in the history
Update headers
Port code to python3
Update README
Fix tests with correct report render calls
Adapt code to report module split
  • Loading branch information
yvaucher committed Dec 1, 2017
1 parent b8ebe8c commit 84e3ed4
Show file tree
Hide file tree
Showing 13 changed files with 138 additions and 208 deletions.
2 changes: 1 addition & 1 deletion l10n_ch_payment_slip/README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ To import v11, use the wizard provided in bank statement.

.. image:: https://odoo-community.org/website/image/ir.attachment/5784_f2813bd/datas
:alt: Try me on Runbot
:target: https://runbot.odoo-community.org/runbot/125/10.0
:target: https://runbot.odoo-community.org/runbot/125/11.0

Bug Tracker
===========
Expand Down
11 changes: 4 additions & 7 deletions l10n_ch_payment_slip/__manifest__.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,14 @@
# -*- coding: utf-8 -*-
# © 2012-2016 Camptocamp SA
# Copyright 2012-2016 Camptocamp SA
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{'name': 'Switzerland - Payment Slip (BVR/ESR)',
'summary': 'Print ESR/BVR payment slip with your invoices',
'version': '10.0.1.1.0',
'version': '11.0.1.0.0',
'author': "Camptocamp,Odoo Community Association (OCA)",
'category': 'Localization',
'website': 'http://www.camptocamp.com',
'license': 'AGPL-3',
'depends': [
'base',
'account',
'report',
'account_invoicing',
'l10n_ch_base_bank',
'base_transaction_id', # OCA/bank-statement-reconcile
],
Expand All @@ -27,6 +24,6 @@
'demo': [],
'test': [],
'auto_install': False,
'installable': False,
'installable': True,
'images': []
}
3 changes: 1 addition & 2 deletions l10n_ch_payment_slip/models/bank.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
# © 2012-2016 Camptocamp SA
# Copyright 2012-2016 Camptocamp SA
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import models, fields

Expand Down
3 changes: 1 addition & 2 deletions l10n_ch_payment_slip/models/company.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
# © 2012-2015 Camptocamp SA
# Copyright 2012-2015 Camptocamp SA
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import models, fields

Expand Down
13 changes: 8 additions & 5 deletions l10n_ch_payment_slip/models/invoice.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
# © 2012-2016 Camptocamp SA
# Copyright 2012-2017 Camptocamp SA
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import _, api, exceptions, fields, models

Expand Down Expand Up @@ -99,7 +98,7 @@ def _action_bvr_number_move_line(self, move_line, ref):
self.env.cr.execute('UPDATE account_move_line SET transaction_ref=%s'
' WHERE id=%s', (ref, move_line.id))
self._update_ref_on_account_analytic_line(ref, move_line.move_id.id)
self.env.invalidate_all()
self.env.cache.invalidate()

@api.multi
def invoice_validate(self):
Expand Down Expand Up @@ -136,8 +135,12 @@ def print_bvr(self):
self.write({
'sent': True
})
return self.env['report'].get_action(
self, 'l10n_ch_payment_slip.one_slip_per_page_from_invoice')
report_name = 'l10n_ch_payment_slip.one_slip_per_page_from_invoice'
docids = self
act_report = self.env['ir.actions.report'].search(
[('report_name', '=', report_name)], limit=1)

return act_report.report_action(docids)

@api.multi
def _check_bvr_generatable(self):
Expand Down
20 changes: 7 additions & 13 deletions l10n_ch_payment_slip/models/payment_slip.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
# -*- coding: utf-8 -*-
# © 2014-2016 Camptocamp SA
# Copyright 2014-2017 Camptocamp SA
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from __future__ import division

import base64
import StringIO
import io
import contextlib
import re
import textwrap
Expand All @@ -13,9 +12,8 @@
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.lib.units import inch
from odoo import models, fields, api, _, exceptions
from odoo.report import report_sxw
from odoo.modules import get_module_resource
from odoo.tools.misc import mod10r
from odoo.tools.misc import mod10r, format_date

FontMeta = namedtuple('FontMeta', ('name', 'size'))

Expand All @@ -27,7 +25,7 @@ class PaymentSlipSettings(object):
"""Slip report setting container"""

def __init__(self, report_name, **kwargs):
for param, value in kwargs.iteritems():
for param, value in kwargs.items():
setattr(self, param, value)
self.report_name = report_name
self.validate()
Expand Down Expand Up @@ -556,11 +554,7 @@ def _draw_description_line(self, canvas, print_settings, initial_position,
date_maturity = self.move_line_id.date_maturity
message = _('Payment slip related to invoice %s '
'due on the %s')
rml_parser = report_sxw.rml_parse(self.env.cr,
self.env.uid,
'payment_slip',
context=self.env.context)
fmt_date = rml_parser.formatLang(date_maturity, date=True)
fmt_date = format_date(self.env, date_maturity)
canvas.setFont(font.name, font.size)
canvas.drawString(x, y,
message % (invoice.number, fmt_date))
Expand Down Expand Up @@ -818,7 +812,7 @@ def _draw_payment_slip(self, a4=False, out_format='PDF', scale=None,
canvas_size = (595.27, 841.89)
else:
canvas_size = (595.27, 286.81)
with contextlib.closing(StringIO.StringIO()) as buff:
with contextlib.closing(io.BytesIO()) as buff:
canvas = Canvas(buff,
pagesize=canvas_size,
pageCompression=None)
Expand Down
129 changes: 95 additions & 34 deletions l10n_ch_payment_slip/report/ir_action.py
Original file line number Diff line number Diff line change
@@ -1,46 +1,107 @@
# -*- coding: utf-8 -*-
# © 2012-2016 Camptocamp SA
# Copyright 2012-2017 Camptocamp SA
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
import os
import tempfile
import io
import PyPDF2

from odoo import models, fields, api


class IrActionsReportXMLReportlab(models.Model):
class IrActionsReportReportlab(models.Model):

_inherit = 'ir.actions.report.xml'
_inherit = 'ir.actions.report'

report_type = fields.Selection(selection_add=[('reportlab-pdf',
report_type = fields.Selection(selection_add=[('reportlab_pdf',
'Report renderer')])

@api.model
def _lookup_report(self, name):
self.env.cr.execute(
"SELECT * FROM ir_act_report_xml WHERE report_name=%s", (name,))
report = self.env.cr.dictfetchone()
if report and report['report_type'] == 'reportlab-pdf':
return report['report_name']
@api.multi
def _generate_one_slip_per_page_from_invoice_pdf(self, report_name=None):
"""Generate payment slip PDF(s) from report model.
If there is many pdf they are merged in memory or on
file system based on company settings
:return: the generated PDF content
"""
user_model = self.env['res.users']
slip_model = self.env['l10n_ch.payment_slip']
invoice_model = self.env['account.invoice']
company = user_model.browse(self.env.uid).company_id
invoices = invoice_model.browse(self.ids)

docs = slip_model._compute_pay_slips_from_invoices(invoices)
if len(docs) == 1:
return docs[0]._draw_payment_slip(a4=True,
b64=False,
report_name=report_name,
out_format='PDF')
else:
return super(IrActionsReportXMLReportlab, self)._lookup_report(
name)
pdfs = (x._draw_payment_slip(a4=True, b64=False, out_format='PDF',
report_name=report_name)
for x in docs)
if company.merge_mode == 'in_memory':
return self.merge_pdf_in_memory(pdfs)
return self.merge_pdf_on_disk(pdfs)

@api.multi
def render_report(self, res_ids, name, data):
"""
Override to work with real pdf in testing and not html
as we use reportlab as renderer
"""
context = self._context
if context is None:
context = {}
if context.get('force_pdf'):
new_report = self._lookup_report(name)
if isinstance(new_report, (str, unicode)):
return self.env['report'].get_pdf(
res_ids,
new_report,
data=data,
), 'pdf'
return super(IrActionsReportXMLReportlab, self).render_report(
res_ids,
name,
data,
def render_reportlab_pdf(self, docids, data=None):
if (self.report_name == 'l10n_ch_payment_slip.'
'one_slip_per_page_from_invoice'):
reports = self.browse(docids)
pdf_content = reports._generate_one_slip_per_page_from_invoice_pdf(
report_name=self.report_name,
)
return pdf_content, 'pdf'

def merge_pdf_in_memory(self, docs):
streams = []
merger = PyPDF2.PdfFileMerger()
for doc in docs:
current_buff = io.BytesIO()
streams.append(current_buff)
current_buff.write(doc)
current_buff.seek(0)
merger.append(PyPDF2.PdfFileReader(current_buff))
buff = io.BytesIO()
try:
# The writer close the reader file here
merger.write(buff)
return buff.getvalue()
except IOError:
raise
finally:
buff.close()
for stream in streams:
stream.close()

def merge_pdf_on_disk(self, docs):
streams = []
writer = PyPDF2.PdfFileWriter()
for doc in docs:
current_buff = tempfile.mkstemp(
suffix='.pdf',
prefix='credit_control_slip')[0]
current_buff = os.fdopen(current_buff, 'w+b')
current_buff.seek(0)
streams.append(current_buff)
current_buff.write(doc)
current_buff.seek(0)
reader = PyPDF2.PdfFileReader(current_buff)
for page in range(reader.getNumPages()):
writer.addPage(reader.getPage(page))
buff = tempfile.mkstemp(
suffix='.pdf',
prefix='credit_control_slip_merged')[0]
try:
buff = os.fdopen(buff, 'w+b')
# The writer close the reader file here
buff.seek(0)
writer.write(buff)
buff.seek(0)
return buff.read()
except IOError:
raise
finally:
buff.close()
for stream in streams:
stream.close()
107 changes: 1 addition & 106 deletions l10n_ch_payment_slip/report/report.py
Original file line number Diff line number Diff line change
@@ -1,112 +1,7 @@
# -*- coding: utf-8 -*-
# © 2014-2016 Camptocamp SA
# Copyright 2014-2017 Camptocamp SA
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import models, api
import os
import tempfile
import StringIO
import pyPdf


class BVRFromInvoice(models.AbstractModel):
_name = 'report.one_slip_per_page_from_invoice'


class Report(models.Model):

_inherit = 'report'

@api.multi
def _generate_one_slip_per_page_from_invoice_pdf(self, report_name=None):
"""Generate payment slip PDF(s) from report model.
If there is many pdf they are merged in memory or on
file system based on company settings
:return: the generated PDF content
"""
user_model = self.env['res.users']
slip_model = self.env['l10n_ch.payment_slip']
invoice_model = self.env['account.invoice']
company = user_model.browse(self.env.uid).company_id
invoices = invoice_model.browse(self.ids)

docs = slip_model._compute_pay_slips_from_invoices(invoices)
if len(docs) == 1:
return docs[0]._draw_payment_slip(a4=True,
b64=False,
report_name=report_name,
out_format='PDF')
else:
pdfs = (x._draw_payment_slip(a4=True, b64=False, out_format='PDF',
report_name=report_name)
for x in docs)
if company.merge_mode == 'in_memory':
return self.merge_pdf_in_memory(pdfs)
return self.merge_pdf_on_disk(pdfs)

@api.multi
def get_pdf(self, docids, report_name, html=None, data=None):
if (report_name == 'l10n_ch_payment_slip.'
'one_slip_per_page_from_invoice'):
reports = self.browse(docids)
return reports._generate_one_slip_per_page_from_invoice_pdf(
report_name=report_name,
)
else:
return super(Report, self).get_pdf(docids, report_name, html=html,
data=data)

def merge_pdf_in_memory(self, docs):
streams = []
writer = pyPdf.PdfFileWriter()
for doc in docs:
current_buff = StringIO.StringIO()
streams.append(current_buff)
current_buff.write(doc)
current_buff.seek(0)
reader = pyPdf.PdfFileReader(current_buff)
for page in xrange(reader.getNumPages()):
writer.addPage(reader.getPage(page))
buff = StringIO.StringIO()
try:
# The writer close the reader file here
writer.write(buff)
return buff.getvalue()
except IOError:
raise
finally:
buff.close()
for stream in streams:
stream.close()

def merge_pdf_on_disk(self, docs):
streams = []
writer = pyPdf.PdfFileWriter()
for doc in docs:
current_buff = tempfile.mkstemp(
suffix='.pdf',
prefix='credit_control_slip')[0]
current_buff = os.fdopen(current_buff, 'w+b')
current_buff.seek(0)
streams.append(current_buff)
current_buff.write(doc)
current_buff.seek(0)
reader = pyPdf.PdfFileReader(current_buff)
for page in xrange(reader.getNumPages()):
writer.addPage(reader.getPage(page))
buff = tempfile.mkstemp(
suffix='.pdf',
prefix='credit_control_slip_merged')[0]
try:
buff = os.fdopen(buff, 'w+b')
# The writer close the reader file here
buff.seek(0)
writer.write(buff)
buff.seek(0)
return buff.read()
except IOError:
raise
finally:
buff.close()
for stream in streams:
stream.close()
Loading

0 comments on commit 84e3ed4

Please sign in to comment.