1 # -*- coding: utf-8 -*-
2 ##############################################################################
4 # OpenERP, Open Source Management Solution
5 # Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>).
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 ##############################################################################
25 from lxml import etree
36 # encode a value to a string in utf8 and converts XML entities
39 if isinstance(val, str):
41 elif isinstance(val, unicode):
42 str_utf8 = val.encode('utf-8')
45 return str_utf8.replace('&', '&').replace('<','<').replace('>','>')
47 class report_int(netsvc.Service):
48 def __init__(self, name, audience='*'):
49 assert not self.exists(name), 'The report "%s" already exists!' % name
50 super(report_int, self).__init__(name, audience)
51 if name[0:7]<>'report.':
52 raise Exception, 'ConceptionError, bad report name, should start with "report."'
55 self.name2 = '.'.join(name.split('.')[1:])
57 #self.joinGroup('report')
58 self.exportMethod(self.create)
60 def create(self, cr, uid, ids, datas, context=None):
64 Class to automatically build a document using the transformation process:
65 XML -> DATAS -> RML -> PDF
67 using a XSL:RML transformation
69 class report_rml(report_int):
70 def __init__(self, name, table, tmpl, xsl):
71 super(report_rml, self).__init__(name)
77 'pdf': self.create_pdf,
78 'html': self.create_html,
79 'raw': self.create_raw,
80 'sxw': self.create_sxw,
81 'txt': self.create_txt,
82 'odt': self.create_odt,
83 'html2html' : self.create_html2html,
84 'makohtml2html' :self.create_makohtml2html,
87 def create(self, cr, uid, ids, datas, context):
88 xml = self.create_xml(cr, uid, ids, datas, context)
89 xml = tools.ustr(xml).encode('utf8')
90 report_type = datas.get('report_type', 'pdf')
91 if report_type == 'raw':
92 return (xml,report_type)
93 rml = self.create_rml(cr, xml, uid, context)
94 pool = pooler.get_pool(cr.dbname)
95 ir_actions_report_xml_obj = pool.get('ir.actions.report.xml')
96 report_xml_ids = ir_actions_report_xml_obj.search(cr, uid, [('report_name', '=', self.name[7:])], context=context)
97 self.title = report_xml_ids and ir_actions_report_xml_obj.browse(cr,uid,report_xml_ids)[0].name or 'OpenERP Report'
98 create_doc = self.generators[report_type]
99 pdf = create_doc(rml, title=self.title)
100 return (pdf, report_type)
102 def create_xml(self, cr, uid, ids, datas, context=None):
105 doc = print_xml.document(cr, uid, datas, {})
106 self.bin_datas.update( doc.bin_datas or {})
107 doc.parse(self.tmpl, ids, self.table, context)
110 return self.post_process_xml_data(cr, uid, xml, context)
112 def post_process_xml_data(self, cr, uid, xml, context=None):
115 # find the position of the 3rd tag
116 # (skip the <?xml ...?> and the "root" tag)
117 iter = re.finditer('<[^>]*>', xml)
122 doc = print_xml.document(cr, uid, {}, {})
123 tmpl_path = addons.get_module_resource('base', 'report', 'corporate_defaults.xml')
124 doc.parse(tmpl_path, [uid], 'res.users', context)
125 corporate_header = doc.xml_get()
128 # find the position of the tag after the <?xml ...?> tag
129 iter = re.finditer('<[^>]*>', corporate_header)
133 return xml[:pos_xml] + corporate_header[pos_header:] + xml[pos_xml:]
136 # TODO: The translation doesn't work for "<tag t="1">textext<tag> tex</tag>text</tag>"
138 def create_rml(self, cr, xml, uid, context=None):
141 service = netsvc.LocalService("object_proxy")
143 # In some case we might not use xsl ...
147 stylesheet = etree.parse(tools.file_open(self.xsl))
148 xsl_path, _ = os.path.split(self.xsl)
149 for import_child in stylesheet.findall('./import'):
150 if 'href' in import_child.attrib:
151 imp_file = import_child.get('href')
152 _, imp_file = tools.file_open(imp_file, subdir=xsl_path, pathinfo=True)
153 import_child.set('href', urllib.quote(str(imp_file)))
155 #TODO: get all the translation in one query. That means we have to:
156 # * build a list of items to translate,
157 # * issue the query to translate them,
158 # * (re)build/update the stylesheet with the translated items
160 def translate(doc, lang):
161 for node in doc.xpath('//*[@t]'):
162 translation = service.execute(
163 cr.dbname, uid, 'ir.translation', '_get_source',
164 self.name2, 'xsl', lang, node.text)
166 node.text = translation
168 if context.get('lang', False):
169 translate(stylesheet, context['lang'])
171 transform = etree.XSLT(stylesheet)
172 xml = etree.tostring(
173 transform(etree.fromstring(xml)))
177 def create_pdf(self, rml, localcontext = None, logo=None, title=None):
179 self.bin_datas['logo'] = logo
181 if 'logo' in self.bin_datas:
182 del self.bin_datas['logo']
183 obj = render.rml(rml, localcontext, self.bin_datas, tools.config['root_path'],title)
187 def create_html(self, rml, localcontext = None, logo=None, title=None):
188 obj = render.rml2html(rml, localcontext, self.bin_datas)
192 def create_txt(self, rml,localcontext, logo=None, title=None):
193 obj = render.rml2txt(rml, localcontext, self.bin_datas)
195 return obj.get().encode('utf-8')
197 def create_html2html(self, rml, localcontext = None, logo=None, title=None):
198 obj = render.html2html(rml, localcontext, self.bin_datas)
203 def create_raw(self,rml, localcontext = None, logo=None, title=None):
204 obj = render.odt2odt(etree.XML(rml),localcontext)
206 return etree.tostring(obj.get())
208 def create_sxw(self,rml,localcontext = None):
209 obj = render.odt2odt(rml,localcontext)
213 def create_odt(self,rml,localcontext = None):
214 obj = render.odt2odt(rml,localcontext)
218 def create_makohtml2html(self,html,localcontext = None):
219 obj = render.makohtml2html(html,localcontext)
223 from report_sxw import report_sxw
225 def register_all(db):
228 cr.execute("SELECT * FROM ir_act_report_xml WHERE auto=%s ORDER BY id", (True,))
229 result = cr.dictfetchall()
231 svcs = netsvc.Service._services
233 if svcs.has_key('report.'+r['report_name']):
235 if r['report_rml'] or r['report_rml_content_data']:
236 report_sxw('report.'+r['report_name'], r['model'],
237 opj('addons',r['report_rml'] or '/'), header=r['header'])
239 report_rml('report.'+r['report_name'], r['model'],
240 opj('addons',r['report_xml']),
241 r['report_xsl'] and opj('addons',r['report_xsl']))
244 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: