Debian Codegraph @

odoorpc/report.py

raw
1 # -*- coding: utf-8 -*-
2 # Copyright 2014 Sébastien Alix
3 # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl)
4 """This module provide the :class:`Report` class to list available reports and
5 to generate/download them.
6 """
7 import base64
8 import io
9
10 from odoorpc.tools import get_encodings, v
11
12
13 def encode2bytes(data):
14 for encoding in get_encodings():
15 try:
16 return data.decode(encoding)
17 except Exception:
18 pass
19 return data
20
21
22 class Report(object):
23 """The `Report` class represents the report management service.
24
25 It provides methods to list and download available reports from the server.
26
27 .. note::
28 This service have to be used through the :attr:`odoorpc.ODOO.report`
29 property.
30
31 .. doctest::
32 :options: +SKIP
33
34 >>> import odoorpc
35 >>> odoo = odoorpc.ODOO('localhost', port=8069)
36 >>> odoo.login('odoorpc_test', 'admin', 'password')
37 >>> odoo.report
38 <odoorpc.report.Report object at 0x7f82fe7a1d50>
39
40 .. doctest::
41 :hide:
42
43 >>> import odoorpc
44 >>> odoo = odoorpc.ODOO(HOST, protocol=PROTOCOL, port=PORT)
45 >>> odoo.login(DB, USER, PWD)
46 >>> odoo.report
47 <odoorpc.report.Report object at ...>
48 """
49
50 def __init__(self, odoo):
51 self._odoo = odoo
52
53 def download(self, name, ids, datas=None, context=None):
54 """Download a report from the server and return it as a remote file.
55
56 Warning: this feature is not supported for Odoo >= 14 (CSRF token required).
57
58 For instance, to download the "Quotation / Order" report of sale orders
59 identified by the IDs ``[2, 3]``:
60
61 .. doctest::
62 :options: +SKIP
63
64 >>> report = odoo.report.download('sale.report_saleorder', [2, 3])
65
66 .. doctest::
67 :hide:
68
69 >>> from odoorpc.tools import v
70 >>> if v(VERSION) < v('14.0'):
71 ... report = odoo.report.download('sale.report_saleorder', [2])
72
73 Write it on the file system:
74
75 .. doctest::
76 :options: +SKIP
77
78 >>> with open('sale_orders.pdf', 'wb') as report_file:
79 ... report_file.write(report.read())
80 ...
81
82 .. doctest::
83 :hide:
84
85 >>> from odoorpc.tools import v
86 >>> if v(VERSION) < v('14.0'):
87 ... with open('sale_orders.pdf', 'wb') as report_file:
88 ... fileno = report_file.write(report.read()) # Python 3
89 ...
90
91 *Python 2:*
92
93 :return: `io.BytesIO`
94 :raise: :class:`odoorpc.error.RPCError` (wrong parameters)
95 :raise: `ValueError` (received invalid data)
96 :raise: `urllib2.URLError` (connection error)
97
98 *Python 3:*
99
100 :return: `io.BytesIO`
101 :raise: :class:`odoorpc.error.RPCError` (wrong parameters)
102 :raise: `ValueError` (received invalid data)
103 :raise: `urllib.error.URLError` (connection error)
104 """
105 if context is None:
106 context = self._odoo.env.context
107
108 def check_report(name):
109 report_model = 'ir.actions.report'
110 if v(self._odoo.version)[0] < 11:
111 report_model = 'ir.actions.report.xml'
112 IrReport = self._odoo.env[report_model]
113 report_ids = IrReport.search([('report_name', '=', name)])
114 report_id = report_ids and report_ids[0] or False
115 if not report_id:
116 raise ValueError("The report '%s' does not exist." % name)
117 return report_id
118
119 report_id = check_report(name)
120
121 # Odoo >= 11.0
122 if v(self._odoo.version)[0] >= 11:
123 IrReport = self._odoo.env['ir.actions.report']
124 report = IrReport.browse(report_id)
125 if v(self._odoo.version)[0] >= 14:
126 # Need a CSRF token to print reports on Odoo >= 14
127 raise NotImplementedError
128 # response = report.with_context(context)._render(
129 # ids, data=datas
130 # )
131 else:
132 response = report.with_context(context).render(ids, data=datas)
133 content = response[0]
134 # On the server the result is a bytes string,
135 # but the RPC layer of Odoo returns it as a unicode string,
136 # so we encode it again as bytes
137 result = content.encode('latin1')
138 return io.BytesIO(result)
139 # Odoo < 11.0
140 else:
141 args_to_send = [
142 self._odoo.env.db,
143 self._odoo.env.uid,
144 self._odoo._password,
145 name,
146 ids,
147 datas,
148 context,
149 ]
150 data = self._odoo.json(
151 '/jsonrpc',
152 {
153 'service': 'report',
154 'method': 'render_report',
155 'args': args_to_send,
156 },
157 )
158 if 'result' not in data and not data['result'].get('result'):
159 raise ValueError("Received invalid data.")
160 # Encode to bytes forced to be compatible with Python 3.2
161 # (its 'base64.standard_b64decode()' function only accepts bytes)
162 result = encode2bytes(data['result']['result'])
163 content = base64.standard_b64decode(result)
164 return io.BytesIO(content)
165
166 def list(self):
167 """List available reports from the server.
168
169 It returns a dictionary with reports classified by data model:
170
171 .. doctest::
172 :options: +SKIP
173
174 >>> from odoorpc.tools import v
175 >>> inv_model = 'account.move'
176 >>> if v(VERSION) < v('13.0'):
177 ... inv_model = 'account.invoice'
178 >>> odoo.report.list()[inv_model]
179 [{'name': u'Duplicates',
180 'report_name': u'account.account_invoice_report_duplicate_main',
181 'report_type': u'qweb-pdf'},
182 {'name': 'Invoices',
183 'report_type': 'qweb-pdf',
184 'report_name': 'account.report_invoice'}]
185
186 .. doctest::
187 :hide:
188
189 >>> from odoorpc.tools import v
190 >>> inv_model = 'account.move'
191 >>> if v(VERSION) < v('13.0'):
192 ... inv_model = 'account.invoice'
193 >>> from pprint import pprint as pp
194 >>> any(data['report_name'] == 'account.report_invoice'
195 ... for data in odoo.report.list()[inv_model])
196 True
197
198 *Python 2:*
199
200 :return: `list` of dictionaries
201 :raise: `urllib2.URLError` (connection error)
202
203 *Python 3:*
204
205 :return: `list` of dictionaries
206 :raise: `urllib.error.URLError` (connection error)
207 """
208 report_model = 'ir.actions.report'
209 if v(self._odoo.version)[0] < 11:
210 report_model = 'ir.actions.report.xml'
211 IrReport = self._odoo.env[report_model]
212 report_ids = IrReport.search([])
213 reports = IrReport.read(
214 report_ids, ['name', 'model', 'report_name', 'report_type']
215 )
216 result = {}
217 for report in reports:
218 model = report.pop('model')
219 report.pop('id')
220 if model not in result:
221 result[model] = []
222 result[model].append(report)
223 return result