You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

352 lines
13 KiB

  1. # Copyright 2013 Camptocamp SA
  2. # Copyright 2017 ACSONE SA/NV
  3. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
  4. import itertools
  5. import tempfile
  6. from io import StringIO, BytesIO
  7. import base64
  8. import csv
  9. import codecs
  10. from odoo import api, fields, models, _
  11. class AccountingWriter(object):
  12. """
  13. A CSV writer which will write rows to CSV file "f",
  14. which is encoded in the given encoding.
  15. """
  16. def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
  17. # Redirect output to a queue
  18. self.queue = StringIO()
  19. # created a writer with Excel formating settings
  20. self.writer = csv.writer(self.queue, dialect=dialect, **kwds)
  21. self.stream = f
  22. self.encoder = codecs.getincrementalencoder(encoding)()
  23. def writerow(self, row):
  24. # we ensure that we do not try to encode none or bool
  25. row = (x or '' for x in row)
  26. self.writer.writerow(row)
  27. # Fetch UTF-8 output from the queue ...
  28. data = self.queue.getvalue()
  29. # ... and reencode it into the target encoding as BytesIO
  30. data = self.encoder.encode(data)
  31. # write to the target stream
  32. self.stream.write(data)
  33. # seek() or truncate() have side effect then we reinitialize StringIO
  34. # https://stackoverflow.com/questions/4330812/how-do-i-clear-a-stringio-object
  35. self.queue = StringIO()
  36. def writerows(self, rows):
  37. for row in rows:
  38. self.writerow(row)
  39. # https://docs.python.org/3/library/io.html#io.IOBase.close
  40. self.queue.close()
  41. class AccountCSVExport(models.TransientModel):
  42. _name = 'account.csv.export'
  43. _description = 'Export Accounting'
  44. data = fields.Binary('CSV', readonly=True)
  45. company_id = fields.Many2one(
  46. comodel_name='res.company', string='Company', invisible=True,
  47. default=lambda self: self._get_company_default())
  48. date_start = fields.Date(required=True)
  49. date_end = fields.Date(required=True)
  50. date_range_id = fields.Many2one(
  51. comodel_name='date.range', string='Date range')
  52. journal_ids = fields.Many2many(
  53. comodel_name='account.journal', string='Journals',
  54. default=lambda s: s._get_journal_default(),
  55. help='If empty, use all journals, only used for journal entries')
  56. export_filename = fields.Char(
  57. string='Export CSV Filename', size=128, default='account_export.csv')
  58. @api.model
  59. def _get_journal_default(self):
  60. """ Implements your own default """
  61. return False
  62. @api.model
  63. def _get_company_default(self):
  64. return self.env.user.company_id
  65. @api.onchange('date_range_id')
  66. def _onchange_date_range(self):
  67. if self.date_range_id:
  68. self.date_start = self.date_range_id.date_start
  69. self.date_end = self.date_range_id.date_end
  70. @api.onchange('date_start', 'date_end')
  71. def _onchange_dates(self):
  72. if self.date_range_id:
  73. if self.date_start != self.date_range_id.date_start or \
  74. self.date_end != self.date_range_id.date_end:
  75. self.date_range_id = False
  76. def action_manual_export_account(self):
  77. self.ensure_one()
  78. rows = self._get_data("account")
  79. file_data = BytesIO()
  80. try:
  81. writer = AccountingWriter(file_data)
  82. writer.writerows(rows)
  83. file_value = file_data.getvalue()
  84. self.write({'data': base64.encodestring(file_value)})
  85. finally:
  86. file_data.close()
  87. return {
  88. 'type': 'ir.actions.act_window',
  89. 'res_model': 'account.csv.export',
  90. 'view_mode': 'form',
  91. 'res_id': self.id,
  92. 'views': [(False, 'form')],
  93. 'target': 'new',
  94. }
  95. def _get_header_account(self):
  96. return [
  97. _('CODE'),
  98. _('NAME'),
  99. _('DEBIT'),
  100. _('CREDIT'),
  101. _('BALANCE'),
  102. ]
  103. def _get_rows_account(self, journal_ids):
  104. """
  105. Return list to generate rows of the CSV file
  106. """
  107. self.ensure_one()
  108. self.env.cr.execute("""
  109. select ac.code,ac.name,
  110. sum(debit) as sum_debit,
  111. sum(credit) as sum_credit,
  112. sum(debit) - sum(credit) as balance
  113. from account_move_line as aml,account_account as ac
  114. where aml.account_id = ac.id
  115. AND aml.date >= %(date_start)s
  116. AND aml.date <= %(date_end)s
  117. group by ac.id,ac.code,ac.name
  118. order by ac.code
  119. """, {'date_start': self.date_start,
  120. 'date_end': self.date_end})
  121. res = self.env.cr.fetchall()
  122. rows = []
  123. for line in res:
  124. rows.append(list(line))
  125. return rows
  126. def action_manual_export_analytic(self):
  127. self.ensure_one()
  128. rows = self._get_data("analytic")
  129. file_data = BytesIO()
  130. try:
  131. writer = AccountingWriter(file_data)
  132. writer.writerows(rows)
  133. file_value = file_data.getvalue()
  134. self.write({'data': base64.encodestring(file_value)})
  135. finally:
  136. file_data.close()
  137. return {
  138. 'type': 'ir.actions.act_window',
  139. 'res_model': 'account.csv.export',
  140. 'view_mode': 'form',
  141. 'view_type': 'form',
  142. 'res_id': self.id,
  143. 'views': [(False, 'form')],
  144. 'target': 'new',
  145. }
  146. def _get_header_analytic(self):
  147. return [
  148. _('ANALYTIC CODE'),
  149. _('ANALYTIC NAME'),
  150. _('CODE'),
  151. _('ACCOUNT NAME'),
  152. _('DEBIT'),
  153. _('CREDIT'),
  154. _('BALANCE'),
  155. ]
  156. def _get_rows_analytic(self, journal_ids):
  157. """
  158. Return list to generate rows of the CSV file
  159. """
  160. self.ensure_one()
  161. self.env.cr.execute(""" select aac.code as analytic_code,
  162. aac.name as analytic_name,
  163. ac.code,ac.name,
  164. sum(debit) as sum_debit,
  165. sum(credit) as sum_credit,
  166. sum(debit) - sum(credit) as balance
  167. from account_move_line
  168. left outer join account_analytic_account as aac
  169. on (account_move_line.analytic_account_id = aac.id)
  170. inner join account_account as ac
  171. on account_move_line.account_id = ac.id
  172. AND account_move_line.date >= %(date_start)s
  173. AND account_move_line.date <= %(date_end)s
  174. group by aac.id,aac.code,aac.name,ac.id,ac.code,ac.name
  175. order by aac.code
  176. """, {'date_start': self.date_start,
  177. 'date_end': self.date_end})
  178. res = self.env.cr.fetchall()
  179. rows = []
  180. for line in res:
  181. rows.append(list(line))
  182. return rows
  183. def action_manual_export_journal_entries(self):
  184. """
  185. Here we use TemporaryFile to avoid full filling the Odoo worker
  186. Memory
  187. We also write the data to the wizard with SQL query as write seems
  188. to use too much memory as well.
  189. Those improvements permitted to improve the export from a 100k line to
  190. 200k lines
  191. with default `limit_memory_hard = 805306368` (768MB) with more lines,
  192. you might encounter a MemoryError when trying to download the file even
  193. if it has been generated.
  194. To be able to export bigger volume of data, it is advised to set
  195. limit_memory_hard to 2097152000 (2 GB) to generate the file and let
  196. Odoo load it in the wizard when trying to download it.
  197. Tested with up to a generation of 700k entry lines
  198. """
  199. self.ensure_one()
  200. rows = self._get_data("journal_entries")
  201. with tempfile.TemporaryFile() as file_data:
  202. writer = AccountingWriter(file_data)
  203. writer.writerows(rows)
  204. with tempfile.TemporaryFile() as base64_data:
  205. file_data.seek(0)
  206. base64.encode(file_data, base64_data)
  207. base64_data.seek(0)
  208. self.env.cr.execute("""
  209. UPDATE account_csv_export
  210. SET data = %s
  211. WHERE id = %s""", (base64_data.read(), self.id))
  212. return {
  213. 'type': 'ir.actions.act_window',
  214. 'res_model': 'account.csv.export',
  215. 'view_mode': 'form',
  216. 'res_id': self.id,
  217. 'views': [(False, 'form')],
  218. 'target': 'new',
  219. }
  220. def _get_header_journal_entries(self):
  221. return [
  222. # Standard Sage export fields
  223. _('DATE'),
  224. _('JOURNAL CODE'),
  225. _('ACCOUNT CODE'),
  226. _('PARTNER NAME'),
  227. _('REF'),
  228. _('DESCRIPTION'),
  229. _('DEBIT'),
  230. _('CREDIT'),
  231. _('FULL RECONCILE'),
  232. _('ANALYTIC ACCOUNT CODE'),
  233. # Other fields
  234. _('ENTRY NUMBER'),
  235. _('ACCOUNT NAME'),
  236. _('BALANCE'),
  237. _('AMOUNT CURRENCY'),
  238. _('CURRENCY'),
  239. _('ANALYTIC ACCOUNT NAME'),
  240. _('JOURNAL'),
  241. _('TAX CODE'),
  242. _('TAX NAME'),
  243. _('BANK STATEMENT'),
  244. ]
  245. def _get_rows_journal_entries(self, journal_ids):
  246. """
  247. Create a generator of rows of the CSV file
  248. """
  249. self.ensure_one()
  250. self.env.cr.execute("""
  251. SELECT
  252. account_move_line.date AS date,
  253. account_journal.name as journal,
  254. account_account.code AS account_code,
  255. res_partner.name AS partner_name,
  256. account_move_line.ref AS ref,
  257. account_move_line.name AS description,
  258. account_move_line.debit AS debit,
  259. account_move_line.credit AS credit,
  260. account_full_reconcile.name as full_reconcile,
  261. account_analytic_account.code AS analytic_account_code,
  262. account_move.name AS entry_number,
  263. account_account.name AS account_name,
  264. account_move_line.debit - account_move_line.credit AS balance,
  265. account_move_line.amount_currency AS amount_currency,
  266. res_currency.name AS currency,
  267. account_analytic_account.name AS analytic_account_name,
  268. account_journal.name as journal,
  269. acct.description as tax_code,
  270. acct.name as tax_name,
  271. account_bank_statement.name AS bank_statement
  272. FROM
  273. public.account_move_line
  274. JOIN account_account on
  275. (account_account.id=account_move_line.account_id)
  276. JOIN account_journal on
  277. (account_journal.id = account_move_line.journal_id)
  278. LEFT JOIN res_currency on
  279. (res_currency.id=account_move_line.currency_id)
  280. LEFT JOIN account_full_reconcile on
  281. (account_full_reconcile.id = account_move_line.full_reconcile_id)
  282. LEFT JOIN res_partner on
  283. (res_partner.id=account_move_line.partner_id)
  284. LEFT JOIN account_move on
  285. (account_move.id=account_move_line.move_id)
  286. LEFT JOIN account_analytic_account on
  287. (account_analytic_account.id=account_move_line.analytic_account_id)
  288. LEFT JOIN account_bank_statement on
  289. (account_bank_statement.id=account_move_line.statement_id)
  290. LEFT JOIN account_tax acct on
  291. (acct.id=account_move_line.tax_line_id)
  292. WHERE account_move_line.date >= %(date_start)s
  293. AND account_move_line.date <= %(date_end)s
  294. AND account_journal.id IN %(journal_ids)s
  295. ORDER BY account_move_line.date
  296. """, {'journal_ids': tuple(journal_ids),
  297. 'date_start': self.date_start,
  298. 'date_end': self.date_end})
  299. while 1:
  300. # http://initd.org/psycopg/docs/cursor.html#cursor.fetchmany
  301. # Set cursor.arraysize to minimize network round trips
  302. self.env.cr.arraysize = 100
  303. rows = self.env.cr.fetchmany()
  304. if not rows:
  305. break
  306. for row in rows:
  307. yield row
  308. def _get_data(self, result_type):
  309. self.ensure_one()
  310. get_header_func = getattr(
  311. self, ("_get_header_%s" % (result_type)), None)
  312. get_rows_func = getattr(self, ("_get_rows_%s" % (result_type)), None)
  313. if self.journal_ids:
  314. journal_ids = [x.id for x in self.journal_ids]
  315. else:
  316. j_obj = self.env["account.journal"]
  317. journal_ids = j_obj.search([]).ids
  318. rows = itertools.chain((get_header_func(),),
  319. get_rows_func(journal_ids))
  320. return rows