[PYTHON] ~sage export: export account lines even if balance is equal to 0
[burette/etudesetchantiersidf.git] / wizard / account_export_csv.py
1 # -*- coding: utf-8 -*-
2 ##############################################################################
3 #
4 # etudesetchantiersidf module for OpenERP, Custom module for Étude et
5 # Chantiers île-de-France
6 # Copyright (C) 2014-2022 etudesetchantiersidf
7 # (<http://etudesetchantiersiledefrance.unarec.org/>)
8 #
9 # This file is a part of etudesetchantiersidf
10 #
11 # etudesetchantiersidf is free software: you can redistribute it and/or
12 # modify it under the terms of the GNU General Public License as published
13 # by the Free Software Foundation, either version 3 of the License, or (at
14 # your option) any later version.
15 #
16 # etudesetchantiersidf is distributed in the hope that it will be useful,
17 # but WITHOUT ANY WARRANTY; without even the implied warranty of
18 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 # GNU General Public License for more details.
20 #
21 # You should have received a copy of the GNU General Public License
22 # along with this program. If not, see <http://www.gnu.org/licenses/>.
23 #
24 ##############################################################################
25
26 import StringIO
27 import cStringIO
28 import base64
29 import csv
30 import codecs
31 import calendar
32 import datetime
33 import string
34
35 import openerp.exceptions
36 from openerp.osv import osv
37 from openerp.tools.translate import _
38 from openerp.addons.account_export_csv.wizard.account_export_csv import AccountUnicodeWriter
39
40
41 class AccountUnicodeWriter(AccountUnicodeWriter):
42
43 def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
44 # Redirect output to a queue
45 self.queue = cStringIO.StringIO()
46 # created a writer with Excel formating settings
47
48 self.writer = csv.writer(self.queue, dialect=dialect,
49 quoting=csv.QUOTE_NONE, **kwds)
50 self.stream = f
51 self.encoder = codecs.getincrementalencoder(encoding)()
52
53
54 class AccountCSVExport(osv.osv_memory):
55 _inherit = "account.csv.export"
56
57 def action_manual_export_sage(self, cr, uid, ids, context=None):
58 this = self.browse(cr, uid, ids)[0]
59 rows = self.get_data(cr, uid, ids, "sage", context)
60 file_data = StringIO.StringIO()
61 try:
62 writer = AccountUnicodeWriter(file_data)
63 writer.writerows(rows)
64 file_value = file_data.getvalue()
65 self.write(cr, uid, ids,
66 {'data': base64.encodestring(file_value)},
67 context=context)
68 finally:
69 file_data.close()
70 return {
71 'type': 'ir.actions.act_window',
72 'res_model': 'account.csv.export',
73 'view_mode': 'form',
74 'view_type': 'form',
75 'res_id': this.id,
76 'views': [(False, 'form')],
77 'target': 'new',
78 }
79
80 def _get_header_sage(self, cr, uid, ids, context=None):
81 """Return header for SAGE export"""
82 return [_(u'Code du journal'),
83 _(u'N° de pièce'),
84 _(u'Date'),
85 _(u'Compte Général'),
86 _(u'Compte Tiers'),
87 _(u'Général/analytique'),
88 _(u'Compte Analytique'),
89 _(u'Nom du client'),
90 _(u'Débit'),
91 _(u'Crédit'),
92 ]
93
94 def format_row_sage(self, dico, numero_piece, side):
95 """Return a formatted row for SAGE export"""
96 if side == "D":
97 debit = dico['debit']
98 credit = 0
99 if side == "C":
100 debit = 0
101 credit = dico['credit']
102 return [
103 dico['journal_code'],
104 numero_piece,
105 dico['date'],
106 dico['account_code'],
107 dico['compte_tiers'],
108 dico['general_analytic'],
109 dico['analytic_account'],
110 dico['client_name'],
111 debit,
112 credit,
113 ]
114
115 def _get_rows_sage(self, cr, uid, ids,
116 fiscalyear_id,
117 period_range_ids,
118 journal_ids,
119 account_ids=None,
120 context=None):
121 fiscalyear_obj = self.pool.get('account.fiscalyear')
122 fiscalyear_code = fiscalyear_obj.browse(cr, uid, fiscalyear_id, context=context)
123 fiscalyear_code = fiscalyear_obj.browse(cr, uid, fiscalyear_id, context=context).code
124
125 period_obj = self.pool.get('account.period')
126 journal_obj = self.pool.get('account.journal')
127 account_obj = self.pool.get('account.account')
128 account_type_obj = self.pool.get('account.account.type')
129 numero_piece = 0
130 prev_period = 0
131 prev_journal = 0
132 cr.execute("""
133 select
134 aml.period_id,
135 aml.journal_id as journal_id,
136 aml.account_id as account_id,
137 sum(aml.debit) as sum_debit,
138 sum(aml.credit) as sum_credit
139 from
140 account_move_line as aml
141 where
142 aml.period_id in %(period_ids)s and
143 aml.journal_id in %(journal_ids)s and
144 aml.account_id in %(account_ids)s
145 group by
146 period_id,
147 journal_id,
148 account_id
149 order by
150 period_id,
151 journal_id,
152 account_id
153 """,
154 {
155 'period_ids': tuple(period_range_ids),
156 'journal_ids': tuple(journal_ids),
157 'account_ids': tuple(account_ids),
158 }
159 )
160 res = cr.fetchall()
161 rows = []
162 for line in res:
163 dico = {}
164 journal = journal_obj.browse(cr, uid, line[1], context=context)
165 dico['journal_code'] = journal.code[0:2]
166 period = period_obj.browse(cr, uid, line[0], context=context)
167 if prev_journal != journal or prev_period != period:
168 numero_piece += 1
169 year = int(period.code[3:7])
170 month = int(period.code[0:2])
171 day = calendar.monthrange(year, month)[1]
172 dico['date'] = datetime.datetime(year, month, day).strftime("%d/%m/%Y")
173 account = account_obj.browse(cr, uid, line[2], context=context)
174 dico['account_code'] = account.code
175 preformatted_client_name = journal.name.split(" - ", 1)[1].upper().replace(' ','')
176 for char in string.punctuation:
177 preformatted_client_name = preformatted_client_name.replace(char,'')
178 dico['client_name'] = preformatted_client_name
179 if account.type in ("receivable", "payable"):
180 dico['compte_tiers'] = dico['client_name']
181 else:
182 dico['compte_tiers'] = ""
183 dico['general_analytic'] = "G"
184 dico['analytic_account'] = ""
185 dico['debit'] = line[3]
186 dico['credit'] = line[4]
187 if dico['debit']:
188 row = self.format_row_sage(dico, numero_piece, "D")
189 rows.append(row)
190 if dico['credit']:
191 row = self.format_row_sage(dico, numero_piece, "C")
192 rows.append(row)
193 account_type = account_type_obj.browse(
194 cr, uid, account.user_type.id, context=context
195 )
196 if account_type.code in ("expense","income"):
197 dico['general_analytic'] = "A"
198 dico['analytic_account'] = journal.code[3:]
199 if dico['debit']:
200 row = self.format_row_sage(dico, numero_piece, "D")
201 rows.append(row)
202 if dico['credit']:
203 row = self.format_row_sage(dico, numero_piece, "C")
204 rows.append(row)
205
206 prev_journal = journal
207 prev_period = period
208 return rows
209
210 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: