Debian Codegraph @

addons/l10n_fr_account/wizard/account_fr_fec_export_wizard.py

raw
1 # -*- coding: utf-8 -*-
2 # Copyright (C) 2013-2015 Akretion (http://www.akretion.com)
3 import csv
4 import io
5 from odoo.tools import float_is_zero, SQL
6 from odoo import fields, models, api
7 from odoo.tools.misc import get_lang
8 from stdnum.fr import siren
9
10
11 class L10n_FrFecExportWizard(models.TransientModel):
12 _name = 'l10n_fr.fec.export.wizard'
13 _description = 'Fichier Echange Informatise'
14
15 date_from = fields.Date(string='Start Date', required=True, default=lambda self: self.env.context.get('report_dates', {}).get('date_from'))
16 date_to = fields.Date(string='End Date', required=True, default=lambda self: self.env.context.get('report_dates', {}).get('date_to'))
17 filename = fields.Char(string='Filename', size=256, readonly=True)
18 test_file = fields.Boolean()
19 export_type = fields.Selection([
20 ('official', 'Official FEC report (posted entries only)'),
21 ('nonofficial', 'Non-official FEC report (posted and unposted entries)'),
22 ], string='Export Type', required=True, default='official')
23 excluded_journal_ids = fields.Many2many('account.journal', string="Excluded Journals",
24 domain="[('company_id', 'parent_of', current_company_id)]")
25
26 @api.onchange('test_file')
27 def _onchange_export_file(self):
28 if not self.test_file:
29 self.export_type = 'official'
30
31 def _get_base_domain(self):
32 domain = [('company_id', 'in', tuple(self.env.company._accessible_branches().ids)), ('balance', '!=', 0.0)]
33 # For official report: only use posted entries
34 if self.export_type == "official":
35 domain.append(('parent_state', '=', 'posted'))
36 if self.excluded_journal_ids:
37 domain.append(('journal_id', 'not in', self.excluded_journal_ids.ids))
38 return domain
39
40 def _do_query_unaffected_earnings(self):
41 """ Compute the sum of ending balances for all accounts that are of a type that does not bring forward the balance in new fiscal years.
42 This is needed because we have to display only one line for the initial balance of all expense/revenue accounts in the FEC.
43 """
44 query = self.env['account.move.line']._search(self._get_base_domain() + [
45 ('date', '<', self.date_from),
46 ('account_id.include_initial_balance', '=', False),
47 ])
48 sql_query = query.select(SQL(
49 """
50 'OUV' AS JournalCode,
51 'Balance initiale' AS JournalLib,
52 'OUVERTURE/' || %(formatted_date_year)s AS EcritureNum,
53 %(formatted_date_from)s AS EcritureDate,
54 '120/129' AS CompteNum,
55 'Benefice (perte) reporte(e)' AS CompteLib,
56 '' AS CompAuxNum,
57 '' AS CompAuxLib,
58 '-' AS PieceRef,
59 %(formatted_date_from)s AS PieceDate,
60 '/' AS EcritureLib,
61 replace(CASE WHEN COALESCE(sum(account_move_line.balance), 0) <= 0 THEN '0,00' ELSE to_char(SUM(account_move_line.balance), '000000000000000D99') END, '.', ',') AS Debit,
62 replace(CASE WHEN COALESCE(sum(account_move_line.balance), 0) >= 0 THEN '0,00' ELSE to_char(-SUM(account_move_line.balance), '000000000000000D99') END, '.', ',') AS Credit,
63 '' AS EcritureLet,
64 '' AS DateLet,
65 %(formatted_date_from)s AS ValidDate,
66 '' AS Montantdevise,
67 '' AS Idevise
68 """,
69 formatted_date_year=self.date_from.year,
70 formatted_date_from=fields.Date.to_string(self.date_from).replace('-', ''),
71 ))
72 self.env.flush_all()
73 self.env.cr.execute(sql_query)
74 return list(self.env.cr.fetchone())
75
76 def _get_company_legal_data(self, company):
77 """
78 Dom-Tom are excluded from the EU's fiscal territory
79 Those regions do not have SIREN
80 sources:
81 https://www.service-public.fr/professionnels-entreprises/vosdroits/F23570
82 http://www.douane.gouv.fr/articles/a11024-tva-dans-les-dom
83
84 * Returns the siren if the company is french or an empty siren for dom-tom
85 * For non-french companies -> returns the complete vat number
86 """
87 is_dom_tom = company.account_fiscal_country_id and 'DOM-TOM' in company.account_fiscal_country_id.country_group_codes
88 if not company.vat or is_dom_tom:
89 return ''
90 elif company.country_id.code == 'FR' and len(company.vat) >= 13 and siren.is_valid(company.vat[4:13]):
91 return company.vat[4:13]
92 else:
93 return company.vat
94
95 def generate_fec(self):
96 # We choose to implement the flat file instead of the XML file for 2 reasons :
97 # 1) the XSD file impose to have the label on the account.move, but Odoo has the label on the account.move.line,
98 # so that's a problem !
99 # 2) CSV files are easier to read/use for a regular accountant. So it will be easier for the accountant to check
100 # the file before sending it to the fiscal administration
101 company = self.env.company
102 company_legal_data = self._get_company_legal_data(company)
103
104 header = [
105 u'JournalCode', # 0
106 u'JournalLib', # 1
107 u'EcritureNum', # 2
108 u'EcritureDate', # 3
109 u'CompteNum', # 4
110 u'CompteLib', # 5
111 u'CompAuxNum', # 6 We use partner.id
112 u'CompAuxLib', # 7
113 u'PieceRef', # 8
114 u'PieceDate', # 9
115 u'EcritureLib', # 10
116 u'Debit', # 11
117 u'Credit', # 12
118 u'EcritureLet', # 13
119 u'DateLet', # 14
120 u'ValidDate', # 15
121 u'Montantdevise', # 16
122 u'Idevise', # 17
123 ]
124
125 rows_to_write = [header]
126 # INITIAL BALANCE
127 unaffected_earnings_account = self.env['account.account'].search([
128 *self.env['account.account']._check_company_domain(company),
129 ('account_type', '=', 'equity_unaffected'),
130 ], limit=1)
131 unaffected_earnings_line = True # used to make sure that we add the unaffected earning initial balance only once
132 if unaffected_earnings_account:
133 #compute the benefit/loss of last year to add in the initial balance of the current year earnings account
134 unaffected_earnings_results = self._do_query_unaffected_earnings()
135 unaffected_earnings_line = False
136
137 aa_name = self.env['account.account']._field_to_sql('account_move_line__account_id', 'name')
138
139 query = self.env['account.move.line']._search(self._get_base_domain() + [
140 ('date', '<', self.date_from),
141 ('account_id.include_initial_balance', '=', True),
142 ('account_id.account_type', 'not in', ['asset_receivable', 'liability_payable']),
143 ])
144 aa_code = self.env['account.account']._field_to_sql('account_move_line__account_id', 'code', query)
145 sql_query = query.select(SQL(
146 """
147 'OUV' AS JournalCode,
148 'Balance initiale' AS JournalLib,
149 'OUVERTURE/' || %(formatted_date_year)s AS EcritureNum,
150 %(formatted_date_from)s AS EcritureDate,
151 MIN(%(aa_code)s) AS CompteNum,
152 replace(replace(MIN(%(aa_name)s), '|', '/'), '\t', '') AS CompteLib,
153 '' AS CompAuxNum,
154 '' AS CompAuxLib,
155 '-' AS PieceRef,
156 %(formatted_date_from)s AS PieceDate,
157 '/' AS EcritureLib,
158 replace(CASE WHEN sum(account_move_line.balance) <= 0 THEN '0,00' ELSE to_char(SUM(account_move_line.balance), '000000000000000D99') END, '.', ',') AS Debit,
159 replace(CASE WHEN sum(account_move_line.balance) >= 0 THEN '0,00' ELSE to_char(-SUM(account_move_line.balance), '000000000000000D99') END, '.', ',') AS Credit,
160 '' AS EcritureLet,
161 '' AS DateLet,
162 %(formatted_date_from)s AS ValidDate,
163 '' AS Montantdevise,
164 '' AS Idevise,
165 MIN(account_move_line__account_id.id) AS CompteID
166 """,
167 formatted_date_year=self.date_from.year,
168 formatted_date_from=fields.Date.to_string(self.date_from).replace('-', ''),
169 aa_code=aa_code,
170 aa_name=aa_name,
171 ))
172 self.env.cr.execute(SQL('%s GROUP BY account_move_line__account_id.id', sql_query))
173
174 currency_digits = 2
175 for row in self.env.cr.fetchall():
176 listrow = list(row)
177 account_id = listrow.pop()
178 if not unaffected_earnings_line:
179 account = self.env['account.account'].browse(account_id)
180 if account.account_type == 'equity_unaffected':
181 #add the benefit/loss of previous fiscal year to the first unaffected earnings account found.
182 unaffected_earnings_line = True
183 current_amount = float(listrow[11].replace(',', '.')) - float(listrow[12].replace(',', '.'))
184 unaffected_earnings_amount = float(unaffected_earnings_results[11].replace(',', '.')) - float(unaffected_earnings_results[12].replace(',', '.'))
185 listrow_amount = current_amount + unaffected_earnings_amount
186 if float_is_zero(listrow_amount, precision_digits=currency_digits):
187 continue
188 if listrow_amount > 0:
189 listrow[11] = str(listrow_amount).replace('.', ',')
190 listrow[12] = '0,00'
191 else:
192 listrow[11] = '0,00'
193 listrow[12] = str(-listrow_amount).replace('.', ',')
194 rows_to_write.append(listrow)
195
196 #if the unaffected earnings account wasn't in the selection yet: add it manually
197 if (not unaffected_earnings_line
198 and unaffected_earnings_results
199 and (unaffected_earnings_results[11] != '0,00'
200 or unaffected_earnings_results[12] != '0,00')):
201 #search an unaffected earnings account
202 unaffected_earnings_account = self.env['account.account'].search([
203 ('account_type', '=', 'equity_unaffected')
204 ], limit=1)
205 if unaffected_earnings_account:
206 unaffected_earnings_results[4] = unaffected_earnings_account.code
207 unaffected_earnings_results[5] = unaffected_earnings_account.name
208 rows_to_write.append(unaffected_earnings_results)
209
210 # INITIAL BALANCE - receivable/payable
211 query = self.env['account.move.line']._search(self._get_base_domain() + [
212 ('date', '<', self.date_from),
213 ('account_id.include_initial_balance', '=', True),
214 ('account_id.account_type', 'in', ['asset_receivable', 'liability_payable']),
215 ])
216 query.left_join('account_move_line', 'partner_id', 'res_partner', 'id', 'partner_id')
217 aa_code = self.env['account.account']._field_to_sql('account_move_line__account_id', 'code', query)
218 sql_query = query.select(SQL(
219 """
220 'OUV' AS JournalCode,
221 'Balance initiale' AS JournalLib,
222 'OUVERTURE/' || %(formatted_date_year)s AS EcritureNum,
223 %(formatted_date_from)s AS EcritureDate,
224 MIN(%(aa_code)s) AS CompteNum,
225 replace(MIN(%(aa_name)s), '|', '/') AS CompteLib,
226 COALESCE(NULLIF(replace(account_move_line__partner_id.ref, '|', '/'), ''), account_move_line__partner_id.id::text) AS CompAuxNum,
227 COALESCE(replace(account_move_line__partner_id.name, '|', '/'), '') AS CompAuxLib,
228 '-' AS PieceRef,
229 %(formatted_date_from)s AS PieceDate,
230 '/' AS EcritureLib,
231 replace(CASE WHEN sum(account_move_line.balance) <= 0 THEN '0,00' ELSE to_char(SUM(account_move_line.balance), '000000000000000D99') END, '.', ',') AS Debit,
232 replace(CASE WHEN sum(account_move_line.balance) >= 0 THEN '0,00' ELSE to_char(-SUM(account_move_line.balance), '000000000000000D99') END, '.', ',') AS Credit,
233 '' AS EcritureLet,
234 '' AS DateLet,
235 %(formatted_date_from)s AS ValidDate,
236 '' AS Montantdevise,
237 '' AS Idevise,
238 MIN(account_move_line__account_id.id) AS CompteID
239 """,
240 formatted_date_year=self.date_from.year,
241 formatted_date_from=fields.Date.to_string(self.date_from).replace('-', ''),
242 aa_code=aa_code,
243 aa_name=aa_name,
244 ))
245 self.env.cr.execute(SQL('%s GROUP BY account_move_line__partner_id.id, account_move_line__account_id.id', sql_query))
246
247 for row in self.env.cr.fetchall():
248 listrow = list(row)
249 listrow.pop()
250 rows_to_write.append(listrow)
251
252 # LINES
253 query_limit = int(self.env['ir.config_parameter'].sudo().get_param('l10n_fr_fec.batch_size', 500000)) # To prevent memory errors when fetching the results
254 query = self.env['account.move.line']._search(
255 domain=self._get_base_domain() + [
256 ('date', '>=', self.date_from),
257 ('date', '<=', self.date_to),
258 ],
259 limit=query_limit + 1,
260 order='date, move_name, id',
261 )
262 account_alias = query.join('account_move_line', 'account_id', 'account_account', 'id', 'account_id')
263 aa_code = self.env['account.account']._field_to_sql(account_alias, 'code', query)
264
265 aj_name = self.env['account.journal']._field_to_sql('account_move_line__journal_id', 'name')
266 columns = SQL(
267 """
268 REGEXP_REPLACE(replace(%(journal_alias)s.code, '|', '/'), '[\\t\\r\\n]', ' ', 'g') AS JournalCode,
269 REGEXP_REPLACE(replace(%(aj_name)s, '|', '/'), '[\\t\\r\\n]', ' ', 'g') AS JournalLib,
270 REGEXP_REPLACE(replace(%(move_alias)s.name, '|', '/'), '[\\t\\r\\n]', ' ', 'g') AS EcritureNum,
271 TO_CHAR(%(move_alias)s.date, 'YYYYMMDD') AS EcritureDate,
272 %(aa_code)s AS CompteNum,
273 REGEXP_REPLACE(replace(%(aa_name)s, '|', '/'), '[\\t\\r\\n]', ' ', 'g') AS CompteLib,
274 CASE WHEN %(account_alias)s.account_type IN ('asset_receivable', 'liability_payable')
275 THEN
276 CASE WHEN %(partner_alias)s.ref IS null OR %(partner_alias)s.ref = ''
277 THEN %(partner_alias)s.id::text
278 ELSE replace(%(partner_alias)s.ref, '|', '/')
279 END
280 ELSE ''
281 END
282 AS CompAuxNum,
283 CASE WHEN %(account_alias)s.account_type IN ('asset_receivable', 'liability_payable')
284 THEN COALESCE(REGEXP_REPLACE(replace(%(partner_alias)s.name, '|', '/'), '[\\t\\r\\n]', ' ', 'g'), '')
285 ELSE ''
286 END AS CompAuxLib,
287 CASE WHEN %(move_alias)s.ref IS null OR %(move_alias)s.ref = ''
288 THEN '-'
289 ELSE REGEXP_REPLACE(replace(%(move_alias)s.ref, '|', '/'), '[\\t\\r\\n]', ' ', 'g')
290 END AS PieceRef,
291 TO_CHAR(COALESCE(%(move_alias)s.invoice_date, %(move_alias)s.date), 'YYYYMMDD') AS PieceDate,
292 CASE WHEN account_move_line.name IS NULL OR account_move_line.name = '' THEN '/'
293 WHEN account_move_line.name SIMILAR TO '[\\t|\\s|\\n]*' THEN '/'
294 ELSE REGEXP_REPLACE(replace(account_move_line.name, '|', '/'), '[\\t\\n\\r]', ' ', 'g') END AS EcritureLib,
295 replace(CASE WHEN account_move_line.debit = 0 THEN '0,00' ELSE to_char(account_move_line.debit, '000000000000000D99') END, '.', ',') AS Debit,
296 replace(CASE WHEN account_move_line.credit = 0 THEN '0,00' ELSE to_char(account_move_line.credit, '000000000000000D99') END, '.', ',') AS Credit,
297 CASE WHEN %(full_alias)s.id IS NULL THEN ''::text ELSE %(full_alias)s.id::text END AS EcritureLet,
298 CASE WHEN account_move_line.full_reconcile_id IS NULL THEN '' ELSE TO_CHAR(%(full_alias)s.create_date, 'YYYYMMDD') END AS DateLet,
299 TO_CHAR(%(move_alias)s.date, 'YYYYMMDD') AS ValidDate,
300 CASE
301 WHEN account_move_line.amount_currency IS NULL OR account_move_line.amount_currency = 0 THEN ''
302 ELSE replace(to_char(account_move_line.amount_currency, '000000000000000D99'), '.', ',')
303 END AS Montantdevise,
304 CASE WHEN account_move_line.currency_id IS NULL THEN '' ELSE %(currency_alias)s.name END AS Idevise
305 """,
306 currency_alias=SQL.identifier(query.left_join('account_move_line', 'currency_id', 'res_currency', 'id', 'currency_id')),
307 full_alias=SQL.identifier(query.left_join('account_move_line', 'full_reconcile_id', 'account_full_reconcile', 'id', 'full_reconcile_id')),
308 journal_alias=SQL.identifier(query.left_join('account_move_line', 'journal_id', 'account_journal', 'id', 'journal_id')),
309 move_alias=SQL.identifier(query.left_join('account_move_line', 'move_id', 'account_move', 'id', 'move_id')),
310 partner_alias=SQL.identifier(query.left_join('account_move_line', 'partner_id', 'res_partner', 'id', 'partner_id')),
311 account_alias=SQL.identifier(account_alias),
312 aj_name=aj_name,
313 aa_code=aa_code,
314 aa_name=aa_name,
315 )
316 with io.StringIO() as fecfile:
317 csv_writer = csv.writer(fecfile, delimiter='|', lineterminator='\r\n')
318
319 # Write header and initial balances
320 csv_writer.writerows(rows_to_write)
321
322 # Write current period's data
323 has_more_results = True
324 while has_more_results:
325 self.env.cr.execute(query.select(columns))
326 query.offset += query_limit
327 has_more_results = self.env.cr.rowcount > query_limit # we load one more result than the limit to check if there is more
328 query_results = self.env.cr.fetchall()
329 csv_writer.writerows(query_results[:query_limit])
330 content = fecfile.getvalue()[:-2].encode()
331
332 end_date = fields.Date.to_string(self.date_to).replace('-', '')
333 suffix = ''
334 if self.export_type == "nonofficial":
335 suffix = '-NONOFFICIAL'
336
337 # Set fiscal year lock date to the end date (not in test)
338 fiscalyear_lock_date = self.env.company.fiscalyear_lock_date
339 if not self.test_file and (not fiscalyear_lock_date or fiscalyear_lock_date < self.date_to):
340 self.env.company.write({'fiscalyear_lock_date': self.date_to})
341
342 return {
343 'file_name': f"{company_legal_data}FEC{end_date}{suffix}.txt",
344 'file_content': content,
345 'file_type': 'txt'
346 }
347
348 def create_fec_report_action(self):
349 # HOOK
350 return