1
1
# Copyright 2019 Creu Blanca
2
2
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
3
3
4
+ import logging
5
+
4
6
from odoo import api , fields , models
7
+ from odoo .exceptions import AccessError
8
+ from odoo .tools .safe_eval import safe_eval , time
9
+
10
+ _logger = logging .getLogger (__name__ )
5
11
6
12
7
13
class ReportAction (models .Model ):
@@ -19,18 +25,58 @@ class ReportAction(models.Model):
19
25
"there is a character that fail to be encoded." ,
20
26
)
21
27
28
+ def _create_csv_attachment (self , record , data ):
29
+ attachment_name = safe_eval (self .attachment , {"object" : record , "time" : time })
30
+ # Unable to compute a name for the attachment.
31
+ if not attachment_name :
32
+ return
33
+ if record and data :
34
+ attachment = {
35
+ "name" : attachment_name ,
36
+ "raw" : data ,
37
+ "res_model" : self .model ,
38
+ "res_id" : record .id ,
39
+ "type" : "binary" ,
40
+ }
41
+ try :
42
+ self .env ["ir.attachment" ].create (attachment )
43
+ except AccessError :
44
+ _logger .info (
45
+ "Cannot save csv report %r as attachment" , attachment ["name" ]
46
+ )
47
+ else :
48
+ _logger .info (
49
+ "The csv document %s is now saved in the database" ,
50
+ attachment ["name" ],
51
+ )
52
+
22
53
@api .model
23
54
def _render_csv (self , report_ref , docids , data ):
24
55
report_sudo = self ._get_report (report_ref )
25
56
report_model_name = "report.%s" % report_sudo .report_name
26
57
report_model = self .env [report_model_name ]
27
- return report_model .with_context (
58
+ res_id = len (docids ) == 1 and docids [0 ]
59
+ if not res_id or not report_sudo .attachment or not report_sudo .attachment_use :
60
+ return report_model .with_context (
61
+ ** {
62
+ "active_model" : report_sudo .model ,
63
+ "encoding" : self .encoding ,
64
+ "encode_error_handling" : self .encode_error_handling ,
65
+ }
66
+ ).create_csv_report (docids , data )
67
+ record = self .env [report_sudo .model ].browse (res_id )
68
+ attachment = report_sudo .retrieve_attachment (record )
69
+ if attachment :
70
+ return attachment .raw .decode (), "csv"
71
+ data , ext = report_model .with_context (
28
72
** {
29
73
"active_model" : report_sudo .model ,
30
74
"encoding" : self .encoding ,
31
75
"encode_error_handling" : self .encode_error_handling ,
32
76
}
33
77
).create_csv_report (docids , data )
78
+ report_sudo ._create_csv_attachment (record , data )
79
+ return data , ext
34
80
35
81
@api .model
36
82
def _get_report_from_name (self , report_name ):
0 commit comments