1 # -*- encoding: utf-8 -*-
2 ##############################################################################
4 # Author: Nicolas Bessi. Copyright Camptocamp SA
5 # Donors: Hasa Sàrl, Open Net Sàrl and Prisme Solutions Informatique SA
7 # This program is free software: you can redistribute it and/or modify
8 # it under the terms of the GNU Affero General Public License as
9 # published by the Free Software Foundation, either version 3 of the
10 # License, or (at your option) any later version.
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU Affero General Public License for more details.
17 # You should have received a copy of the GNU Affero General Public License
18 # along with this program. If not, see <http://www.gnu.org/licenses/>.
20 ##############################################################################
27 from mako.template import Template
28 from mako.lookup import TemplateLookup
29 from mako import exceptions
32 from report import report_sxw
33 from report_webkit import webkit_report
34 from report_webkit import report_helper
37 from osv.osv import except_osv
39 from tools import mod10r
40 from tools.translate import _
41 from tools.config import config
50 class l10n_ch_report_webkit_html(report_sxw.rml_parse):
51 def __init__(self, cr, uid, name, context):
52 super(l10n_ch_report_webkit_html, self).__init__(cr, uid, name, context=context)
53 self.localcontext.update({
57 'user':self.pool.get("res.users").browse(cr, uid, uid),
59 '_space': self._space,
60 '_get_ref': self._get_ref,
61 'comma_me': self.comma_me,
62 'police_absolute_path': self.police_absolute_path,
63 'bvr_absolute_path': self.bvr_absolute_path,
64 'headheight': self.headheight
67 _compile_get_ref = re.compile('[^0-9]')
68 _compile_comma_me = re.compile("^(-?\d+)(\d{3})")
69 _compile_check_bvr = re.compile('[0-9][0-9]-[0-9]{3,6}-[0-9]')
70 _compile_check_bvr_add_num = re.compile('[0-9]*$')
72 def set_context(self, objects, data, ids, report_type=None):
73 user = self.pool.get('res.users').browse(self.cr, self.uid, self.uid)
74 company = user.company_id
75 if not company.invoice_only:
77 return super(l10n_ch_report_webkit_html, self).set_context(objects, data, ids, report_type=report_type)
79 def police_absolute_path(self, inner_path) :
80 """Will get the ocrb police absolute path"""
81 path = addons.get_module_resource(os.path.join('l10n_ch', 'report', inner_path))
84 def bvr_absolute_path(self) :
85 """Will get the ocrb police absolute path"""
86 path = addons.get_module_resource(os.path.join('l10n_ch', 'report', 'bvr1.jpg'))
90 report_id = self.pool.get('ir.actions.report.xml').search(self.cr, self.uid, [('name','=', 'BVR invoice')])[0]
91 report = self.pool.get('ir.actions.report.xml').browse(self.cr, self.uid, report_id)
92 return report.webkit_header.margin_top
94 def comma_me(self, amount):
95 """Fast swiss number formatting"""
96 if isinstance(amount, float):
97 amount = str('%.2f'%amount)
101 new = self._compile_comma_me.sub("\g<1>'\g<2>", amount)
105 return self.comma_me(new)
107 def _space(self, nbr, nbrspc=5):
111 >>> self._space('123456789012345')
114 return ''.join([' '[(i - 2) % nbrspc:] + c for i, c in enumerate(nbr)])
117 def _get_ref(self, inv):
118 """Retrieve ESR/BVR reference form invoice in order to print it"""
120 if inv.partner_bank_id.bvr_adherent_num:
121 res = inv.partner_bank_id.bvr_adherent_num
124 invoice_number = self._compile_get_ref.sub('', inv.number)
125 return mod10r(res + invoice_number.rjust(26-len(res), '0'))
127 def _check(self, invoice_ids):
128 """Check if the invoice is ready to be printed"""
133 invoice_obj = pool.get('account.invoice')
135 for invoice in invoice_obj.browse(cursor, self.uid, ids):
136 invoice_name = "%s %s" %(invoice.name, invoice.number)
137 if not invoice.partner_bank_id:
138 raise except_osv(_('UserError'),
139 _('No bank specified on invoice:\n%s' %(invoice_name)))
140 if not self._compile_check_bvr.match(
141 invoice.partner_bank_id.post_number or ''):
142 raise except_osv(_('UserError'),
143 _(('Your bank BVR number should be of the form 0X-XXX-X! '
144 'Please check your company '
145 'information for the invoice:\n%s')
147 if invoice.partner_bank_id.bvr_adherent_num \
148 and not self._compile_check_bvr_add_num.match(
149 invoice.partner_bank_id.bvr_adherent_num):
150 raise except_osv(_('UserError'),
151 _(('Your bank BVR adherent number must contain only '
152 'digits!\nPlease check your company '
153 'information for the invoice:\n%s') %(invoice_name)))
156 def mako_template(text):
157 """Build a Mako template.
159 This template uses UTF-8 encoding
161 tmp_lookup = TemplateLookup() #we need it in order to allow inclusion and inheritance
162 return Template(text, input_encoding='utf-8', output_encoding='utf-8', lookup=tmp_lookup)
164 class BVRWebKitParser(webkit_report.WebKitParser):
166 bvr_file_path = os.path.join('l10n_ch','report','bvr.mako')
168 def create_single_pdf(self, cursor, uid, ids, data, report_xml, context=None):
169 """generate the PDF"""
170 context = context or {}
171 if report_xml.report_type != 'webkit':
172 return super(WebKitParser,self).create_single_pdf(cursor, uid, ids, data, report_xml, context=context)
173 self.parser_instance = self.parser(cursor,
177 self.pool = pooler.get_pool(cursor.dbname)
178 objs = self.getObjects(cursor, uid, ids, context)
179 self.parser_instance.set_context(objs, data, ids, report_xml.report_type)
181 if report_xml.report_file :
182 path = addons.get_module_resource(report_xml.report_file)
183 if os.path.exists(path) :
184 template = file(path).read()
185 if not template and report_xml.report_webkit_data :
186 template = report_xml.report_webkit_data
188 raise except_osv(_('Error'),_('Webkit Report template not found !'))
189 header = report_xml.webkit_header.html
190 footer = report_xml.webkit_header.footer_html
191 if not header and report_xml.header:
193 _('No header defined for this Webkit report!'),
194 _('Please set a header in company settings')
196 if not report_xml.header :
198 default_head = addons.get_module_resource('report_webkit', 'default_header.html')
199 with open(default_head,'r') as f:
201 css = report_xml.webkit_header.css
204 user = self.pool.get('res.users').browse(cursor, uid, uid)
205 company = user.company_id
206 body_mako_tpl = mako_template(template)
208 bvr_path = addons.get_module_resource(self.bvr_file_path)
209 body_bvr_tpl = mako_template(file(bvr_path).read())
210 helper = report_helper.WebKitHelper(cursor, uid, report_xml.id, context)
214 self.parser_instance.localcontext['objects'] = [obj]
215 if not company.bvr_only:
217 html = body_mako_tpl.render(helper=helper,
219 _=self.translate_call,
220 **self.parser_instance.localcontext)
222 raise Exception(exceptions.text_error_template().render())
224 if not company.invoice_only:
226 bvr = body_bvr_tpl.render(helper=helper,
228 _=self.translate_call,
229 **self.parser_instance.localcontext)
231 raise Exception(exceptions.text_error_template().render())
233 head_mako_tpl = Template(header, input_encoding='utf-8', output_encoding='utf-8')
235 head = head_mako_tpl.render(helper=helper,
238 _=self.translate_call,
239 **self.parser_instance.localcontext)
241 raise Exception(exceptions.text_error_template().render())
243 if footer and company.invoice_only :
244 foot_mako_tpl = Template(footer, input_encoding='utf-8', output_encoding='utf-8')
246 foot = foot_mako_tpl.render(helper=helper,
248 _=self.translate_call,
249 **self.parser_instance.localcontext)
251 raise Exception(exceptions.text_error_template().render())
252 if report_xml.webkit_debug :
254 deb = head_mako_tpl.render(helper=helper,
257 _=self.translate_call,
258 **self.parser_instance.localcontext)
260 raise Exception(exceptions.text_error_template().render())
262 bin = self.get_lib(cursor, uid)
263 pdf = self.generate_pdf(bin, report_xml, head, foot, htmls)
267 BVRWebKitParser('report.invoice_web_bvr',
269 'addons/l10n_ch/report/report_webkit_html.mako',
270 parser=l10n_ch_report_webkit_html)
272 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: