account_journal.py 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948
  1. # -*- coding: utf-8 -*-
  2. from odoo import api, Command, fields, models, _
  3. from odoo.exceptions import UserError, ValidationError
  4. from odoo.addons.base.models.res_bank import sanitize_account_number
  5. from odoo.tools import remove_accents
  6. import logging
  7. import re
  8. _logger = logging.getLogger(__name__)
  9. def is_encodable_as_ascii(string):
  10. try:
  11. remove_accents(string).encode('ascii')
  12. except UnicodeEncodeError:
  13. return False
  14. return True
  15. class AccountJournalGroup(models.Model):
  16. _name = 'account.journal.group'
  17. _description = "Account Journal Group"
  18. _check_company_auto = True
  19. name = fields.Char("Journal Group", required=True, translate=True)
  20. company_id = fields.Many2one('res.company', required=True, default=lambda self: self.env.company)
  21. excluded_journal_ids = fields.Many2many('account.journal', string="Excluded Journals", domain="[('company_id', '=', company_id)]",
  22. check_company=True)
  23. sequence = fields.Integer(default=10)
  24. _sql_constraints = [
  25. ('uniq_name', 'unique(company_id, name)', 'A journal group name must be unique per company.'),
  26. ]
  27. class AccountJournal(models.Model):
  28. _name = "account.journal"
  29. _description = "Journal"
  30. _order = 'sequence, type, code'
  31. _inherit = ['mail.thread', 'mail.activity.mixin']
  32. _check_company_auto = True
  33. _rec_names_search = ['name', 'code']
  34. def _default_inbound_payment_methods(self):
  35. return self.env.ref('account.account_payment_method_manual_in')
  36. def _default_outbound_payment_methods(self):
  37. return self.env.ref('account.account_payment_method_manual_out')
  38. def __get_bank_statements_available_sources(self):
  39. return [('undefined', _('Undefined Yet'))]
  40. def _get_bank_statements_available_sources(self):
  41. return self.__get_bank_statements_available_sources()
  42. def _default_invoice_reference_model(self):
  43. """Get the invoice reference model according to the company's country."""
  44. country_code = self.env.company.country_id.code
  45. country_code = country_code and country_code.lower()
  46. if country_code:
  47. for model in self._fields['invoice_reference_model'].get_values(self.env):
  48. if model.startswith(country_code):
  49. return model
  50. return 'odoo'
  51. name = fields.Char(string='Journal Name', required=True)
  52. code = fields.Char(string='Short Code', size=5, required=True, help="Shorter name used for display. The journal entries of this journal will also be named using this prefix by default.")
  53. active = fields.Boolean(default=True, help="Set active to false to hide the Journal without removing it.")
  54. type = fields.Selection([
  55. ('sale', 'Sales'),
  56. ('purchase', 'Purchase'),
  57. ('cash', 'Cash'),
  58. ('bank', 'Bank'),
  59. ('general', 'Miscellaneous'),
  60. ], required=True,
  61. inverse='_inverse_type',
  62. help="Select 'Sale' for customer invoices journals.\n"\
  63. "Select 'Purchase' for vendor bills journals.\n"\
  64. "Select 'Cash' or 'Bank' for journals that are used in customer or vendor payments.\n"\
  65. "Select 'General' for miscellaneous operations journals.")
  66. account_control_ids = fields.Many2many('account.account', 'journal_account_control_rel', 'journal_id', 'account_id', string='Allowed accounts',
  67. check_company=True,
  68. domain="[('deprecated', '=', False), ('company_id', '=', company_id), ('is_off_balance', '=', False)]")
  69. default_account_type = fields.Char(string='Default Account Type', compute="_compute_default_account_type")
  70. default_account_id = fields.Many2one(
  71. comodel_name='account.account', check_company=True, copy=False, ondelete='restrict',
  72. string='Default Account',
  73. domain="[('deprecated', '=', False), ('company_id', '=', company_id),"
  74. "('account_type', '=', default_account_type), ('account_type', 'not in', ('asset_receivable', 'liability_payable'))]")
  75. suspense_account_id = fields.Many2one(
  76. comodel_name='account.account', check_company=True, ondelete='restrict', readonly=False, store=True,
  77. compute='_compute_suspense_account_id',
  78. help="Bank statements transactions will be posted on the suspense account until the final reconciliation "
  79. "allowing finding the right account.", string='Suspense Account',
  80. domain="[('deprecated', '=', False), ('company_id', '=', company_id), \
  81. ('account_type', '=', 'asset_current')]")
  82. restrict_mode_hash_table = fields.Boolean(string="Lock Posted Entries with Hash",
  83. help="If ticked, the accounting entry or invoice receives a hash as soon as it is posted and cannot be modified anymore.")
  84. sequence = fields.Integer(help='Used to order Journals in the dashboard view', default=10)
  85. invoice_reference_type = fields.Selection(string='Communication Type', required=True, selection=[('none', 'Open'), ('partner', 'Based on Customer'), ('invoice', 'Based on Invoice')], default='invoice', help='You can set here the default communication that will appear on customer invoices, once validated, to help the customer to refer to that particular invoice when making the payment.')
  86. invoice_reference_model = fields.Selection(string='Communication Standard', required=True, selection=[('odoo', 'Odoo'), ('euro', 'European')], default=_default_invoice_reference_model, help="You can choose different models for each type of reference. The default one is the Odoo reference.")
  87. #groups_id = fields.Many2many('res.groups', 'account_journal_group_rel', 'journal_id', 'group_id', string='Groups')
  88. currency_id = fields.Many2one('res.currency', help='The currency used to enter statement', string="Currency")
  89. company_id = fields.Many2one('res.company', string='Company', required=True, readonly=True, index=True, default=lambda self: self.env.company,
  90. help="Company related to this journal")
  91. country_code = fields.Char(related='company_id.account_fiscal_country_id.code', readonly=True)
  92. refund_sequence = fields.Boolean(string='Dedicated Credit Note Sequence', help="Check this box if you don't want to share the same sequence for invoices and credit notes made from this journal", default=False)
  93. payment_sequence = fields.Boolean(
  94. string='Dedicated Payment Sequence',
  95. compute='_compute_payment_sequence', readonly=False, store=True, precompute=True,
  96. help="Check this box if you don't want to share the same sequence on payments and bank transactions posted on this journal",
  97. )
  98. sequence_override_regex = fields.Text(help="Technical field used to enforce complex sequence composition that the system would normally misunderstand.\n"\
  99. "This is a regex that can include all the following capture groups: prefix1, year, prefix2, month, prefix3, seq, suffix.\n"\
  100. "The prefix* groups are the separators between the year, month and the actual increasing sequence number (seq).\n"\
  101. "e.g: ^(?P<prefix1>.*?)(?P<year>\d{4})(?P<prefix2>\D*?)(?P<month>\d{2})(?P<prefix3>\D+?)(?P<seq>\d+)(?P<suffix>\D*?)$")
  102. inbound_payment_method_line_ids = fields.One2many(
  103. comodel_name='account.payment.method.line',
  104. domain=[('payment_type', '=', 'inbound')],
  105. compute='_compute_inbound_payment_method_line_ids',
  106. store=True,
  107. readonly=False,
  108. string='Inbound Payment Methods',
  109. inverse_name='journal_id',
  110. copy=False,
  111. check_company=True,
  112. help="Manual: Get paid by any method outside of Odoo.\n"
  113. "Payment Providers: Each payment provider has its own Payment Method. Request a transaction on/to a card thanks to a payment token saved by the partner when buying or subscribing online.\n"
  114. "Batch Deposit: Collect several customer checks at once generating and submitting a batch deposit to your bank. Module account_batch_payment is necessary.\n"
  115. "SEPA Direct Debit: Get paid in the SEPA zone thanks to a mandate your partner will have granted to you. Module account_sepa is necessary.\n"
  116. )
  117. outbound_payment_method_line_ids = fields.One2many(
  118. comodel_name='account.payment.method.line',
  119. domain=[('payment_type', '=', 'outbound')],
  120. compute='_compute_outbound_payment_method_line_ids',
  121. store=True,
  122. readonly=False,
  123. string='Outbound Payment Methods',
  124. inverse_name='journal_id',
  125. copy=False,
  126. check_company=True,
  127. help="Manual: Pay by any method outside of Odoo.\n"
  128. "Check: Pay bills by check and print it from Odoo.\n"
  129. "SEPA Credit Transfer: Pay in the SEPA zone by submitting a SEPA Credit Transfer file to your bank. Module account_sepa is necessary.\n"
  130. )
  131. profit_account_id = fields.Many2one(
  132. comodel_name='account.account', check_company=True,
  133. help="Used to register a profit when the ending balance of a cash register differs from what the system computes",
  134. string='Profit Account',
  135. domain="[('deprecated', '=', False), ('company_id', '=', company_id), \
  136. ('account_type', 'in', ('income', 'income_other'))]")
  137. loss_account_id = fields.Many2one(
  138. comodel_name='account.account', check_company=True,
  139. help="Used to register a loss when the ending balance of a cash register differs from what the system computes",
  140. string='Loss Account',
  141. domain="[('deprecated', '=', False), ('company_id', '=', company_id), \
  142. ('account_type', '=', 'expense')]")
  143. # Bank journals fields
  144. company_partner_id = fields.Many2one('res.partner', related='company_id.partner_id', string='Account Holder', readonly=True, store=False)
  145. bank_account_id = fields.Many2one('res.partner.bank',
  146. string="Bank Account",
  147. ondelete='restrict', copy=False,
  148. check_company=True,
  149. domain="[('partner_id','=', company_partner_id), '|', ('company_id', '=', False), ('company_id', '=', company_id)]")
  150. bank_statements_source = fields.Selection(selection=_get_bank_statements_available_sources, string='Bank Feeds', default='undefined', help="Defines how the bank statements will be registered")
  151. bank_acc_number = fields.Char(related='bank_account_id.acc_number', readonly=False)
  152. bank_id = fields.Many2one('res.bank', related='bank_account_id.bank_id', readonly=False)
  153. # Sale journals fields
  154. sale_activity_type_id = fields.Many2one('mail.activity.type', string='Schedule Activity', default=False, help="Activity will be automatically scheduled on payment due date, improving collection process.")
  155. sale_activity_user_id = fields.Many2one('res.users', string="Activity User", help="Leave empty to assign the Salesperson of the invoice.")
  156. sale_activity_note = fields.Text('Activity Summary')
  157. # alias configuration for journals
  158. alias_id = fields.Many2one('mail.alias', string='Email Alias', help="Send one separate email for each invoice.\n\n"
  159. "Any file extension will be accepted.\n\n"
  160. "Only PDF and XML files will be interpreted by Odoo", copy=False)
  161. alias_domain = fields.Char('Alias domain', compute='_compute_alias_domain')
  162. alias_name = fields.Char('Alias Name', copy=False, compute='_compute_alias_name', inverse='_inverse_type', help="It creates draft invoices and bills by sending an email.")
  163. journal_group_ids = fields.Many2many('account.journal.group',
  164. domain="[('company_id', '=', company_id)]",
  165. check_company=True,
  166. string="Journal Groups")
  167. secure_sequence_id = fields.Many2one('ir.sequence',
  168. help='Sequence to use to ensure the securisation of data',
  169. check_company=True,
  170. readonly=True, copy=False)
  171. available_payment_method_ids = fields.Many2many(
  172. comodel_name='account.payment.method',
  173. compute='_compute_available_payment_method_ids'
  174. )
  175. # used to hide or show payment method options if needed
  176. selected_payment_method_codes = fields.Char(
  177. compute='_compute_selected_payment_method_codes',
  178. )
  179. _sql_constraints = [
  180. ('code_company_uniq', 'unique (company_id, code)', 'Journal codes must be unique per company.'),
  181. ]
  182. @api.depends('outbound_payment_method_line_ids', 'inbound_payment_method_line_ids')
  183. def _compute_available_payment_method_ids(self):
  184. """
  185. Compute the available payment methods id by respecting the following rules:
  186. Methods of mode 'unique' cannot be used twice on the same company
  187. Methods of mode 'multi' cannot be used twice on the same journal
  188. """
  189. method_information = self.env['account.payment.method']._get_payment_method_information()
  190. pay_methods = self.env['account.payment.method'].search([('code', 'in', list(method_information.keys()))])
  191. pay_method_by_code = {x.code + x.payment_type: x for x in pay_methods}
  192. unique_pay_methods = [k for k, v in method_information.items() if v['mode'] == 'unique']
  193. pay_methods_by_company = {}
  194. pay_methods_by_journal = {}
  195. if unique_pay_methods:
  196. self._cr.execute('''
  197. SELECT
  198. journal.id,
  199. journal.company_id,
  200. ARRAY_AGG(DISTINCT apm.id)
  201. FROM account_payment_method_line apml
  202. JOIN account_journal journal ON journal.id = apml.journal_id
  203. JOIN account_payment_method apm ON apm.id = apml.payment_method_id
  204. WHERE apm.code IN %s
  205. GROUP BY
  206. journal.id,
  207. journal.company_id
  208. ''', [tuple(unique_pay_methods)])
  209. for journal_id, company_id, payment_method_ids in self._cr.fetchall():
  210. pay_methods_by_company[company_id] = set(payment_method_ids)
  211. pay_methods_by_journal[journal_id] = set(payment_method_ids)
  212. pay_method_ids_commands_x_journal = {j: [Command.clear()] for j in self}
  213. for payment_type in ('inbound', 'outbound'):
  214. for code, vals in method_information.items():
  215. payment_method = pay_method_by_code.get(code + payment_type)
  216. if not payment_method:
  217. continue
  218. # Get the domain of the journals on which the current method is usable.
  219. method_domain = payment_method._get_payment_method_domain(payment_method.code)
  220. for journal in self.filtered_domain(method_domain):
  221. protected_pay_method_ids = pay_methods_by_company.get(journal.company_id._origin.id, set()) \
  222. - pay_methods_by_journal.get(journal._origin.id, set())
  223. if payment_type == 'inbound':
  224. lines = journal.inbound_payment_method_line_ids
  225. else:
  226. lines = journal.outbound_payment_method_line_ids
  227. already_used = payment_method in lines.payment_method_id
  228. is_protected = payment_method.id in protected_pay_method_ids
  229. if vals['mode'] == 'unique' and (already_used or is_protected):
  230. continue
  231. # Only the manual payment method can be used multiple time on a single journal.
  232. if payment_method.code != "manual" and already_used:
  233. continue
  234. pay_method_ids_commands_x_journal[journal].append(Command.link(payment_method.id))
  235. for journal, pay_method_ids_commands in pay_method_ids_commands_x_journal.items():
  236. journal.available_payment_method_ids = pay_method_ids_commands
  237. @api.depends('type')
  238. def _compute_default_account_type(self):
  239. default_account_id_types = {
  240. 'bank': 'asset_cash',
  241. 'cash': 'asset_cash',
  242. 'sale': 'income',
  243. 'purchase': 'expense'
  244. }
  245. for journal in self:
  246. if journal.type in default_account_id_types:
  247. journal.default_account_type = default_account_id_types[journal.type]
  248. else:
  249. journal.default_account_type = False
  250. @api.depends('type', 'currency_id')
  251. def _compute_inbound_payment_method_line_ids(self):
  252. for journal in self:
  253. pay_method_line_ids_commands = [Command.clear()]
  254. if journal.type in ('bank', 'cash'):
  255. default_methods = journal._default_inbound_payment_methods()
  256. pay_method_line_ids_commands += [Command.create({
  257. 'name': pay_method.name,
  258. 'payment_method_id': pay_method.id,
  259. }) for pay_method in default_methods]
  260. journal.inbound_payment_method_line_ids = pay_method_line_ids_commands
  261. @api.depends('type', 'currency_id')
  262. def _compute_outbound_payment_method_line_ids(self):
  263. for journal in self:
  264. pay_method_line_ids_commands = [Command.clear()]
  265. if journal.type in ('bank', 'cash'):
  266. default_methods = journal._default_outbound_payment_methods()
  267. pay_method_line_ids_commands += [Command.create({
  268. 'name': pay_method.name,
  269. 'payment_method_id': pay_method.id,
  270. }) for pay_method in default_methods]
  271. journal.outbound_payment_method_line_ids = pay_method_line_ids_commands
  272. @api.depends('outbound_payment_method_line_ids', 'inbound_payment_method_line_ids')
  273. def _compute_selected_payment_method_codes(self):
  274. """
  275. Set the selected payment method as a list of comma separated codes like: ,manual,check_printing,...
  276. These will be then used to display or not payment method specific fields in the view.
  277. """
  278. for journal in self:
  279. codes = [line.code for line in journal.inbound_payment_method_line_ids + journal.outbound_payment_method_line_ids if line.code]
  280. journal.selected_payment_method_codes = ',' + ','.join(codes) + ','
  281. @api.depends('company_id', 'type')
  282. def _compute_suspense_account_id(self):
  283. for journal in self:
  284. if journal.type not in ('bank', 'cash'):
  285. journal.suspense_account_id = False
  286. elif journal.suspense_account_id:
  287. journal.suspense_account_id = journal.suspense_account_id
  288. elif journal.company_id.account_journal_suspense_account_id:
  289. journal.suspense_account_id = journal.company_id.account_journal_suspense_account_id
  290. else:
  291. journal.suspense_account_id = False
  292. def _inverse_type(self):
  293. # Create an alias for purchase/sales journals
  294. for journal in self:
  295. if journal.type not in ('purchase', 'sale'):
  296. if journal.alias_id:
  297. journal.alias_id.sudo().unlink()
  298. continue
  299. alias_name = next(string for string in (
  300. journal.alias_name,
  301. journal.name,
  302. journal.code,
  303. journal.type,
  304. ) if string and is_encodable_as_ascii(string))
  305. if journal.company_id != self.env.ref('base.main_company'):
  306. if is_encodable_as_ascii(journal.company_id.name):
  307. alias_name = f"{alias_name}-{journal.company_id.name}"
  308. else:
  309. alias_name = f"{alias_name}-{journal.company_id.id}"
  310. alias_values = {
  311. 'alias_defaults': {
  312. 'move_type': 'in_invoice' if journal.type == 'purchase' else 'out_invoice',
  313. 'company_id': journal.company_id.id,
  314. 'journal_id': journal.id,
  315. },
  316. 'alias_parent_thread_id': journal.id,
  317. 'alias_name': alias_name,
  318. }
  319. if journal.alias_id:
  320. journal.alias_id.sudo().write(alias_values)
  321. else:
  322. alias_values['alias_model_id'] = self.env['ir.model']._get('account.move').id
  323. alias_values['alias_parent_model_id'] = self.env['ir.model']._get('account.journal').id
  324. journal.alias_id = self.env['mail.alias'].sudo().create(alias_values)
  325. self.invalidate_recordset(['alias_name'])
  326. @api.depends('name')
  327. def _compute_alias_domain(self):
  328. self.alias_domain = self.env["ir.config_parameter"].sudo().get_param("mail.catchall.domain")
  329. @api.depends('alias_id', 'alias_id.alias_name')
  330. def _compute_alias_name(self):
  331. for journal in self:
  332. journal.alias_name = journal.alias_id.alias_name
  333. @api.constrains('account_control_ids')
  334. def _constrains_account_control_ids(self):
  335. self.env['account.move.line'].flush_model(['account_id', 'journal_id', 'display_type'])
  336. self.flush_recordset(['account_control_ids'])
  337. self._cr.execute("""
  338. SELECT aml.id
  339. FROM account_move_line aml
  340. WHERE aml.journal_id in (%s)
  341. AND EXISTS (SELECT 1 FROM journal_account_control_rel rel WHERE rel.journal_id = aml.journal_id)
  342. AND NOT EXISTS (SELECT 1 FROM journal_account_control_rel rel WHERE rel.account_id = aml.account_id AND rel.journal_id = aml.journal_id)
  343. AND aml.display_type NOT IN ('line_section', 'line_note')
  344. """, tuple(self.ids))
  345. if self._cr.fetchone():
  346. raise ValidationError(_('Some journal items already exist in this journal but with other accounts than the allowed ones.'))
  347. @api.constrains('type', 'bank_account_id')
  348. def _check_bank_account(self):
  349. for journal in self:
  350. if journal.type == 'bank' and journal.bank_account_id:
  351. if journal.bank_account_id.company_id and journal.bank_account_id.company_id != journal.company_id:
  352. raise ValidationError(_('The bank account of a bank journal must belong to the same company (%s).', journal.company_id.name))
  353. # A bank account can belong to a customer/supplier, in which case their partner_id is the customer/supplier.
  354. # Or they are part of a bank journal and their partner_id must be the company's partner_id.
  355. if journal.bank_account_id.partner_id != journal.company_id.partner_id:
  356. raise ValidationError(_('The holder of a journal\'s bank account must be the company (%s).', journal.company_id.name))
  357. @api.constrains('company_id')
  358. def _check_company_consistency(self):
  359. if not self:
  360. return
  361. self.env['account.move'].flush_model(['company_id', 'journal_id'])
  362. self.flush_recordset(['company_id'])
  363. self._cr.execute('''
  364. SELECT move.id
  365. FROM account_move move
  366. JOIN account_journal journal ON journal.id = move.journal_id
  367. WHERE move.journal_id IN %s
  368. AND move.company_id != journal.company_id
  369. ''', [tuple(self.ids)])
  370. if self._cr.fetchone():
  371. raise UserError(_("You can't change the company of your journal since there are some journal entries linked to it."))
  372. @api.constrains('type', 'default_account_id')
  373. def _check_type_default_account_id_type(self):
  374. for journal in self:
  375. if journal.type in ('sale', 'purchase') and journal.default_account_id.account_type in ('asset_receivable', 'liability_payable'):
  376. raise ValidationError(_("The type of the journal's default credit/debit account shouldn't be 'receivable' or 'payable'."))
  377. @api.constrains('inbound_payment_method_line_ids', 'outbound_payment_method_line_ids')
  378. def _check_payment_method_line_ids_multiplicity(self):
  379. """
  380. Check and ensure that the payment method lines multiplicity is respected.
  381. """
  382. method_info = self.env['account.payment.method']._get_payment_method_information()
  383. unique_codes = tuple(code for code, info in method_info.items() if info.get('mode') == 'unique')
  384. if not unique_codes:
  385. return
  386. self.flush_model(['inbound_payment_method_line_ids', 'outbound_payment_method_line_ids', 'company_id'])
  387. self.env['account.payment.method.line'].flush_model(['payment_method_id', 'journal_id'])
  388. self.env['account.payment.method'].flush_model(['code'])
  389. if unique_codes:
  390. self._cr.execute('''
  391. SELECT apm.id
  392. FROM account_payment_method apm
  393. JOIN account_payment_method_line apml on apm.id = apml.payment_method_id
  394. JOIN account_journal journal on journal.id = apml.journal_id
  395. JOIN res_company company on journal.company_id = company.id
  396. WHERE apm.code in %s
  397. GROUP BY
  398. company.id,
  399. apm.id
  400. HAVING array_length(array_agg(journal.id), 1) > 1;
  401. ''', [unique_codes])
  402. method_ids = [res[0] for res in self._cr.fetchall()]
  403. if method_ids:
  404. methods = self.env['account.payment.method'].browse(method_ids)
  405. raise ValidationError(_("Some payment methods supposed to be unique already exists somewhere else.\n"
  406. "(%s)", ', '.join([method.display_name for method in methods])))
  407. @api.constrains('active')
  408. def _check_auto_post_draft_entries(self):
  409. # constraint should be tested just after archiving a journal, but shouldn't be raised when unarchiving a journal containing draft entries
  410. for journal in self.filtered(lambda j: not j.active):
  411. pending_moves = self.env['account.move'].search([
  412. ('journal_id', '=', journal.id),
  413. ('state', '=', 'draft')
  414. ], limit=1)
  415. if pending_moves:
  416. raise ValidationError(_("You can not archive a journal containing draft journal entries.\n\n"
  417. "To proceed:\n"
  418. "1/ click on the top-right button 'Journal Entries' from this journal form\n"
  419. "2/ then filter on 'Draft' entries\n"
  420. "3/ select them all and post or delete them through the action menu"))
  421. @api.onchange('type')
  422. def _onchange_type(self):
  423. self.refund_sequence = self.type in ('sale', 'purchase')
  424. @api.depends('type')
  425. def _compute_payment_sequence(self):
  426. for journal in self:
  427. journal.payment_sequence = journal.type in ('bank', 'cash')
  428. def unlink(self):
  429. bank_accounts = self.env['res.partner.bank'].browse()
  430. for bank_account in self.mapped('bank_account_id'):
  431. accounts = self.search([('bank_account_id', '=', bank_account.id)])
  432. if accounts <= self:
  433. bank_accounts += bank_account
  434. self.mapped('alias_id').sudo().unlink()
  435. ret = super(AccountJournal, self).unlink()
  436. bank_accounts.unlink()
  437. return ret
  438. @api.returns('self', lambda value: value.id)
  439. def copy(self, default=None):
  440. default = dict(default or {})
  441. # Find a unique code for the copied journal
  442. read_codes = self.env['account.journal'].with_context(active_test=False).search_read([('company_id', '=', self.company_id.id)], ['code'])
  443. all_journal_codes = {code_data['code'] for code_data in read_codes}
  444. copy_code = self.code
  445. code_prefix = re.sub(r'\d+', '', self.code).strip()
  446. counter = 1
  447. while counter <= len(all_journal_codes) and copy_code in all_journal_codes:
  448. counter_str = str(counter)
  449. copy_prefix = code_prefix[:self._fields['code'].size - len(counter_str)]
  450. copy_code = ("%s%s" % (copy_prefix, counter_str))
  451. counter += 1
  452. if counter > len(all_journal_codes):
  453. # Should never happen, but put there just in case.
  454. raise UserError(_("Could not compute any code for the copy automatically. Please create it manually."))
  455. default.update(
  456. code=copy_code,
  457. name=_("%s (copy)") % (self.name or ''))
  458. return super(AccountJournal, self).copy(default)
  459. def write(self, vals):
  460. for journal in self:
  461. company = journal.company_id
  462. if ('company_id' in vals and journal.company_id.id != vals['company_id']):
  463. if self.env['account.move'].search([('journal_id', '=', journal.id)], limit=1):
  464. raise UserError(_('This journal already contains items, therefore you cannot modify its company.'))
  465. company = self.env['res.company'].browse(vals['company_id'])
  466. if journal.bank_account_id.company_id and journal.bank_account_id.company_id != company:
  467. journal.bank_account_id.write({
  468. 'company_id': company.id,
  469. 'partner_id': company.partner_id.id,
  470. })
  471. if 'currency_id' in vals:
  472. if journal.bank_account_id:
  473. journal.bank_account_id.currency_id = vals['currency_id']
  474. if 'bank_account_id' in vals:
  475. if vals.get('bank_account_id'):
  476. bank_account = self.env['res.partner.bank'].browse(vals['bank_account_id'])
  477. if bank_account.partner_id != company.partner_id:
  478. raise UserError(_("The partners of the journal's company and the related bank account mismatch."))
  479. if 'restrict_mode_hash_table' in vals and not vals.get('restrict_mode_hash_table'):
  480. journal_entry = self.env['account.move'].sudo().search([('journal_id', '=', self.id), ('state', '=', 'posted'), ('secure_sequence_number', '!=', 0)], limit=1)
  481. if journal_entry:
  482. field_string = self._fields['restrict_mode_hash_table'].get_description(self.env)['string']
  483. raise UserError(_("You cannot modify the field %s of a journal that already has accounting entries.", field_string))
  484. result = super(AccountJournal, self).write(vals)
  485. # Ensure the liquidity accounts are sharing the same foreign currency.
  486. if 'currency_id' in vals:
  487. for journal in self.filtered(lambda journal: journal.type in ('bank', 'cash')):
  488. journal.default_account_id.currency_id = journal.currency_id
  489. # Create the bank_account_id if necessary
  490. if 'bank_acc_number' in vals:
  491. for journal in self.filtered(lambda r: r.type == 'bank' and not r.bank_account_id):
  492. journal.set_bank_account(vals.get('bank_acc_number'), vals.get('bank_id'))
  493. for record in self:
  494. if record.restrict_mode_hash_table and not record.secure_sequence_id:
  495. record._create_secure_sequence(['secure_sequence_id'])
  496. return result
  497. @api.model
  498. def get_next_bank_cash_default_code(self, journal_type, company, protected_codes=False):
  499. prefix_map = {'cash': 'CSH', 'general': 'GEN', 'bank': 'BNK'}
  500. journal_code_base = prefix_map.get(journal_type)
  501. journals = self.env['account.journal'].with_context(active_test=False).search([('code', 'like', journal_code_base + '%'), ('company_id', '=', company.id)])
  502. for num in range(1, 100):
  503. # journal_code has a maximal size of 5, hence we can enforce the boundary num < 100
  504. journal_code = journal_code_base + str(num)
  505. if journal_code not in journals.mapped('code') and (protected_codes and journal_code not in protected_codes or not protected_codes):
  506. return journal_code
  507. @api.model
  508. def _prepare_liquidity_account_vals(self, company, code, vals):
  509. return {
  510. 'name': vals.get('name'),
  511. 'code': code,
  512. 'account_type': 'asset_cash',
  513. 'currency_id': vals.get('currency_id'),
  514. 'company_id': company.id,
  515. }
  516. @api.model
  517. def _fill_missing_values(self, vals, protected_codes=False):
  518. journal_type = vals.get('type')
  519. is_import = 'import_file' in self.env.context
  520. if is_import and not journal_type:
  521. vals['type'] = journal_type = 'general'
  522. # 'type' field is required.
  523. if not journal_type:
  524. return
  525. # === Fill missing company ===
  526. company = self.env['res.company'].browse(vals['company_id']) if vals.get('company_id') else self.env.company
  527. vals['company_id'] = company.id
  528. # Don't get the digits on 'chart_template_id' since the chart template could be a custom one.
  529. random_account = self.env['account.account'].search([('company_id', '=', company.id)], limit=1)
  530. digits = len(random_account.code) if random_account else 6
  531. if journal_type in ('bank', 'cash'):
  532. has_liquidity_accounts = vals.get('default_account_id')
  533. has_profit_account = vals.get('profit_account_id')
  534. has_loss_account = vals.get('loss_account_id')
  535. if journal_type == 'bank':
  536. liquidity_account_prefix = company.bank_account_code_prefix or ''
  537. else:
  538. liquidity_account_prefix = company.cash_account_code_prefix or company.bank_account_code_prefix or ''
  539. # === Fill missing name ===
  540. vals['name'] = vals.get('name') or vals.get('bank_acc_number')
  541. # === Fill missing code ===
  542. if 'code' not in vals:
  543. vals['code'] = self.get_next_bank_cash_default_code(journal_type, company)
  544. if not vals['code']:
  545. raise UserError(_("Cannot generate an unused journal code. Please fill the 'Shortcode' field."))
  546. # === Fill missing accounts ===
  547. if not has_liquidity_accounts:
  548. default_account_code = self.env['account.account']._search_new_account_code(company, digits, liquidity_account_prefix)
  549. default_account_vals = self._prepare_liquidity_account_vals(company, default_account_code, vals)
  550. vals['default_account_id'] = self.env['account.account'].create(default_account_vals).id
  551. if journal_type in ('cash', 'bank') and not has_profit_account:
  552. vals['profit_account_id'] = company.default_cash_difference_income_account_id.id
  553. if journal_type in ('cash', 'bank') and not has_loss_account:
  554. vals['loss_account_id'] = company.default_cash_difference_expense_account_id.id
  555. if is_import and not vals.get('code'):
  556. code = vals['name'][:5]
  557. vals['code'] = code if not protected_codes or code not in protected_codes else self.get_next_bank_cash_default_code(journal_type, company, protected_codes)
  558. if not vals['code']:
  559. raise UserError(_("Cannot generate an unused journal code. Please change the name for journal %s.", vals['name']))
  560. # === Fill missing refund_sequence ===
  561. if 'refund_sequence' not in vals:
  562. vals['refund_sequence'] = vals['type'] in ('sale', 'purchase')
  563. @api.model_create_multi
  564. def create(self, vals_list):
  565. for vals in vals_list:
  566. # have to keep track of new journal codes when importing
  567. codes = [vals['code'] for vals in vals_list if 'code' in vals] if 'import_file' in self.env.context else False
  568. self._fill_missing_values(vals, protected_codes=codes)
  569. journals = super(AccountJournal, self.with_context(mail_create_nolog=True)).create(vals_list)
  570. for journal, vals in zip(journals, vals_list):
  571. # Create the bank_account_id if necessary
  572. if journal.type == 'bank' and not journal.bank_account_id and vals.get('bank_acc_number'):
  573. journal.set_bank_account(vals.get('bank_acc_number'), vals.get('bank_id'))
  574. return journals
  575. def set_bank_account(self, acc_number, bank_id=None):
  576. """ Create a res.partner.bank (if not exists) and set it as value of the field bank_account_id """
  577. self.ensure_one()
  578. res_partner_bank = self.env['res.partner.bank'].search([
  579. ('sanitized_acc_number', '=', sanitize_account_number(acc_number)),
  580. ('partner_id', '=', self.company_id.partner_id.id),
  581. ], limit=1)
  582. if res_partner_bank:
  583. self.bank_account_id = res_partner_bank.id
  584. else:
  585. self.bank_account_id = self.env['res.partner.bank'].create({
  586. 'acc_number': acc_number,
  587. 'bank_id': bank_id,
  588. 'currency_id': self.currency_id.id,
  589. 'partner_id': self.company_id.partner_id.id,
  590. 'journal_id': self,
  591. }).id
  592. def name_get(self):
  593. res = []
  594. for journal in self:
  595. name = journal.name
  596. if journal.currency_id and journal.currency_id != journal.company_id.currency_id:
  597. name = "%s (%s)" % (name, journal.currency_id.name)
  598. res += [(journal.id, name)]
  599. return res
  600. def action_configure_bank_journal(self):
  601. """ This function is called by the "configure" button of bank journals,
  602. visible on dashboard if no bank statement source has been defined yet
  603. """
  604. # We simply call the setup bar function.
  605. return self.env['res.company'].setting_init_bank_account_action()
  606. def _create_document_from_attachment(self, attachment_ids=None):
  607. """
  608. Create invoices from the attachments (for instance a Factur-X XML file)
  609. """
  610. attachments = self.env['ir.attachment'].browse(attachment_ids)
  611. if not attachments:
  612. raise UserError(_("No attachment was provided"))
  613. invoices = self.env['account.move']
  614. with invoices._disable_discount_precision():
  615. for attachment in attachments:
  616. decoders = self.env['account.move']._get_create_document_from_attachment_decoders()
  617. invoice = False
  618. for decoder in sorted(decoders, key=lambda d: d[0]):
  619. invoice = decoder[1](attachment)
  620. if invoice:
  621. break
  622. if not invoice:
  623. invoice = self.env['account.move'].create({})
  624. invoice.with_context(no_new_invoice=True).message_post(attachment_ids=[attachment.id])
  625. attachment.write({'res_model': 'account.move', 'res_id': invoice.id})
  626. invoices += invoice
  627. return invoices
  628. def create_document_from_attachment(self, attachment_ids=None):
  629. """
  630. Create invoices from the attachments (for instance a Factur-X XML file)
  631. and redirect the user to the newly created invoice(s).
  632. :param attachment_ids: list of attachment ids
  633. :return: action to open the created invoices
  634. """
  635. invoices = self._create_document_from_attachment(attachment_ids)
  636. action_vals = {
  637. 'name': _('Generated Documents'),
  638. 'domain': [('id', 'in', invoices.ids)],
  639. 'res_model': 'account.move',
  640. 'type': 'ir.actions.act_window',
  641. 'context': self._context
  642. }
  643. if len(invoices) == 1:
  644. action_vals.update({
  645. 'views': [[False, "form"]],
  646. 'view_mode': 'form',
  647. 'res_id': invoices[0].id,
  648. })
  649. else:
  650. action_vals.update({
  651. 'views': [[False, "list"], [False, "kanban"], [False, "form"]],
  652. 'view_mode': 'list, kanban, form',
  653. })
  654. return action_vals
  655. def _create_secure_sequence(self, sequence_fields):
  656. """This function creates a no_gap sequence on each journal in self that will ensure
  657. a unique number is given to all posted account.move in such a way that we can always
  658. find the previous move of a journal entry on a specific journal.
  659. """
  660. for journal in self:
  661. vals_write = {}
  662. for seq_field in sequence_fields:
  663. if not journal[seq_field]:
  664. vals = {
  665. 'name': _('Securisation of %s - %s') % (seq_field, journal.name),
  666. 'code': 'SECUR%s-%s' % (journal.id, seq_field),
  667. 'implementation': 'no_gap',
  668. 'prefix': '',
  669. 'suffix': '',
  670. 'padding': 0,
  671. 'company_id': journal.company_id.id}
  672. seq = self.env['ir.sequence'].create(vals)
  673. vals_write[seq_field] = seq.id
  674. if vals_write:
  675. journal.write(vals_write)
  676. # -------------------------------------------------------------------------
  677. # REPORTING METHODS
  678. # -------------------------------------------------------------------------
  679. # TODO move to `account_reports` in master (simple read_group)
  680. def _get_journal_bank_account_balance(self, domain=None):
  681. ''' Get the bank balance of the current journal by filtering the journal items using the journal's accounts.
  682. /!\ The current journal is not part of the applied domain. This is the expected behavior since we only want
  683. a logic based on accounts.
  684. :param domain: An additional domain to be applied on the account.move.line model.
  685. :return: Tuple having balance expressed in journal's currency
  686. along with the total number of move lines having the same account as of the journal's default account.
  687. '''
  688. self.ensure_one()
  689. self.env['account.move.line'].check_access_rights('read')
  690. if not self.default_account_id:
  691. return 0.0, 0
  692. domain = (domain or []) + [
  693. ('account_id', 'in', tuple(self.default_account_id.ids)),
  694. ('display_type', 'not in', ('line_section', 'line_note')),
  695. ('parent_state', '!=', 'cancel'),
  696. ]
  697. query = self.env['account.move.line']._where_calc(domain)
  698. tables, where_clause, where_params = query.get_sql()
  699. query = '''
  700. SELECT
  701. COUNT(account_move_line.id) AS nb_lines,
  702. COALESCE(SUM(account_move_line.balance), 0.0),
  703. COALESCE(SUM(account_move_line.amount_currency), 0.0)
  704. FROM ''' + tables + '''
  705. WHERE ''' + where_clause + '''
  706. '''
  707. company_currency = self.company_id.currency_id
  708. journal_currency = self.currency_id if self.currency_id and self.currency_id != company_currency else False
  709. self._cr.execute(query, where_params)
  710. nb_lines, balance, amount_currency = self._cr.fetchone()
  711. return amount_currency if journal_currency else balance, nb_lines
  712. def _get_journal_inbound_outstanding_payment_accounts(self):
  713. """
  714. :return: A recordset with all the account.account used by this journal for inbound transactions.
  715. """
  716. self.ensure_one()
  717. account_ids = set()
  718. for line in self.inbound_payment_method_line_ids:
  719. account_ids.add(line.payment_account_id.id or self.company_id.account_journal_payment_debit_account_id.id)
  720. return self.env['account.account'].browse(account_ids)
  721. def _get_journal_outbound_outstanding_payment_accounts(self):
  722. """
  723. :return: A recordset with all the account.account used by this journal for outbound transactions.
  724. """
  725. self.ensure_one()
  726. account_ids = set()
  727. for line in self.outbound_payment_method_line_ids:
  728. account_ids.add(line.payment_account_id.id or self.company_id.account_journal_payment_credit_account_id.id)
  729. return self.env['account.account'].browse(account_ids)
  730. # TODO remove in master
  731. def _get_journal_outstanding_payments_account_balance(self, domain=None, date=None):
  732. ''' Get the outstanding payments balance of the current journal by filtering the journal items using the
  733. journal's accounts.
  734. :param domain: An additional domain to be applied on the account.move.line model.
  735. :param date: The date to be used when performing the currency conversions.
  736. :return: The balance expressed in the journal's currency.
  737. '''
  738. self.ensure_one()
  739. self.env['account.move.line'].check_access_rights('read')
  740. conversion_date = date or fields.Date.context_today(self)
  741. accounts = self._get_journal_inbound_outstanding_payment_accounts().union(self._get_journal_outbound_outstanding_payment_accounts())
  742. if not accounts:
  743. return 0.0, 0
  744. # Allow user managing payments without any statement lines.
  745. # In that case, the user manages transactions only using the register payment wizard.
  746. if self.default_account_id in accounts:
  747. return 0.0, 0
  748. domain = (domain or []) + [
  749. ('account_id', 'in', tuple(accounts.ids)),
  750. ('display_type', 'not in', ('line_section', 'line_note')),
  751. ('parent_state', '!=', 'cancel'),
  752. ('reconciled', '=', False),
  753. ('journal_id', '=', self.id),
  754. ]
  755. query = self.env['account.move.line']._where_calc(domain)
  756. tables, where_clause, where_params = query.get_sql()
  757. self._cr.execute('''
  758. SELECT
  759. COUNT(account_move_line.id) AS nb_lines,
  760. account_move_line.currency_id,
  761. account.reconcile AS is_account_reconcile,
  762. SUM(account_move_line.amount_residual) AS amount_residual,
  763. SUM(account_move_line.balance) AS balance,
  764. SUM(account_move_line.amount_residual_currency) AS amount_residual_currency,
  765. SUM(account_move_line.amount_currency) AS amount_currency
  766. FROM ''' + tables + '''
  767. JOIN account_account account ON account.id = account_move_line.account_id
  768. WHERE ''' + where_clause + '''
  769. GROUP BY account_move_line.currency_id, account.reconcile
  770. ''', where_params)
  771. company_currency = self.company_id.currency_id
  772. journal_currency = self.currency_id if self.currency_id and self.currency_id != company_currency else False
  773. balance_currency = journal_currency or company_currency
  774. total_balance = 0.0
  775. nb_lines = 0
  776. for res in self._cr.dictfetchall():
  777. nb_lines += res['nb_lines']
  778. amount_currency = res['amount_residual_currency'] if res['is_account_reconcile'] else res['amount_currency']
  779. balance = res['amount_residual'] if res['is_account_reconcile'] else res['balance']
  780. if res['currency_id'] and journal_currency and res['currency_id'] == journal_currency.id:
  781. total_balance += amount_currency
  782. elif journal_currency:
  783. total_balance += company_currency._convert(balance, balance_currency, self.company_id, conversion_date)
  784. else:
  785. total_balance += balance
  786. return total_balance, nb_lines
  787. # TODO move to `account_reports` in master
  788. def _get_last_bank_statement(self, domain=None):
  789. ''' Retrieve the last bank statement created using this journal.
  790. :param domain: An additional domain to be applied on the account.bank.statement model.
  791. :return: An account.bank.statement record or an empty recordset.
  792. '''
  793. self.ensure_one()
  794. last_statement_domain = (domain or []) + [('journal_id', '=', self.id), ('statement_id', '!=', False)]
  795. last_st_line = self.env['account.bank.statement.line'].search(last_statement_domain, order='date desc, id desc', limit=1)
  796. return last_st_line.statement_id
  797. def _get_available_payment_method_lines(self, payment_type):
  798. """
  799. This getter is here to allow filtering the payment method lines if needed in other modules.
  800. It does NOT serve as a general getter to get the lines.
  801. For example, it'll be extended to filter out lines from inactive payment providers in the payment module.
  802. :param payment_type: either inbound or outbound, used to know which lines to return
  803. :return: Either the inbound or outbound payment method lines
  804. """
  805. if not self:
  806. return self.env['account.payment.method.line']
  807. self.ensure_one()
  808. if payment_type == 'inbound':
  809. return self.inbound_payment_method_line_ids
  810. else:
  811. return self.outbound_payment_method_line_ids
  812. def _is_payment_method_available(self, payment_method_code):
  813. """ Check if the payment method is available on this journal. """
  814. self.ensure_one()
  815. return self.filtered_domain(self.env['account.payment.method']._get_payment_method_domain(payment_method_code))
  816. def _process_reference_for_sale_order(self, order_reference):
  817. '''
  818. returns the order reference to be used for the payment.
  819. Hook to be overriden: see l10n_ch for an example.
  820. '''
  821. self.ensure_one()
  822. return order_reference