partner.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696
  1. # -*- coding: utf-8 -*-
  2. # Part of Odoo. See LICENSE file for full copyright and licensing details.
  3. import time
  4. import logging
  5. from psycopg2 import sql, DatabaseError
  6. from odoo import api, fields, models, _
  7. from odoo.osv import expression
  8. from odoo.tools import DEFAULT_SERVER_DATETIME_FORMAT, mute_logger
  9. from odoo.exceptions import ValidationError, UserError
  10. from odoo.addons.base.models.res_partner import WARNING_MESSAGE, WARNING_HELP
  11. _logger = logging.getLogger(__name__)
  12. class AccountFiscalPosition(models.Model):
  13. _name = 'account.fiscal.position'
  14. _description = 'Fiscal Position'
  15. _order = 'sequence'
  16. sequence = fields.Integer()
  17. name = fields.Char(string='Fiscal Position', required=True)
  18. active = fields.Boolean(default=True,
  19. help="By unchecking the active field, you may hide a fiscal position without deleting it.")
  20. company_id = fields.Many2one(
  21. comodel_name='res.company',
  22. string='Company', required=True, readonly=True,
  23. default=lambda self: self.env.company)
  24. account_ids = fields.One2many('account.fiscal.position.account', 'position_id', string='Account Mapping', copy=True)
  25. tax_ids = fields.One2many('account.fiscal.position.tax', 'position_id', string='Tax Mapping', copy=True)
  26. note = fields.Html('Notes', translate=True, help="Legal mentions that have to be printed on the invoices.")
  27. auto_apply = fields.Boolean(string='Detect Automatically', help="Apply automatically this fiscal position.")
  28. vat_required = fields.Boolean(string='VAT required', help="Apply only if partner has a VAT number.")
  29. company_country_id = fields.Many2one(string="Company Country", related='company_id.account_fiscal_country_id')
  30. country_id = fields.Many2one('res.country', string='Country',
  31. help="Apply only if delivery country matches.")
  32. country_group_id = fields.Many2one('res.country.group', string='Country Group',
  33. help="Apply only if delivery country matches the group.")
  34. state_ids = fields.Many2many('res.country.state', string='Federal States')
  35. zip_from = fields.Char(string='Zip Range From')
  36. zip_to = fields.Char(string='Zip Range To')
  37. # To be used in hiding the 'Federal States' field('attrs' in view side) when selected 'Country' has 0 states.
  38. states_count = fields.Integer(compute='_compute_states_count')
  39. foreign_vat = fields.Char(string="Foreign Tax ID", help="The tax ID of your company in the region mapped by this fiscal position.")
  40. # Technical field used to display a banner on top of foreign vat fiscal positions,
  41. # in order to ease the instantiation of foreign taxes when possible.
  42. foreign_vat_header_mode = fields.Selection(
  43. selection=[('templates_found', "Templates Found"), ('no_template', "No Template")],
  44. compute='_compute_foreign_vat_header_mode')
  45. def _compute_states_count(self):
  46. for position in self:
  47. position.states_count = len(position.country_id.state_ids)
  48. @api.depends('foreign_vat', 'country_id')
  49. def _compute_foreign_vat_header_mode(self):
  50. for record in self:
  51. if not record.foreign_vat or not record.country_id:
  52. record.foreign_vat_header_mode = None
  53. continue
  54. if self.env['account.tax'].search([('country_id', '=', record.country_id.id)], limit=1):
  55. record.foreign_vat_header_mode = None
  56. elif self.env['account.tax.template'].search([('chart_template_id.country_id', '=', record.country_id.id)], limit=1):
  57. record.foreign_vat_header_mode = 'templates_found'
  58. else:
  59. record.foreign_vat_header_mode = 'no_template'
  60. @api.constrains('zip_from', 'zip_to')
  61. def _check_zip(self):
  62. for position in self:
  63. if position.zip_from and position.zip_to and position.zip_from > position.zip_to:
  64. raise ValidationError(_('Invalid "Zip Range", please configure it properly.'))
  65. @api.constrains('country_id', 'state_ids', 'foreign_vat')
  66. def _validate_foreign_vat_country(self):
  67. for record in self:
  68. if record.foreign_vat:
  69. if record.country_id == record.company_id.account_fiscal_country_id:
  70. if record.foreign_vat == record.company_id.vat:
  71. raise ValidationError(_("You cannot create a fiscal position within your fiscal country with the same VAT number as the main one set on your company."))
  72. if not record.state_ids:
  73. if record.company_id.account_fiscal_country_id.state_ids:
  74. raise ValidationError(_("You cannot create a fiscal position with a foreign VAT within your fiscal country without assigning it a state."))
  75. else:
  76. raise ValidationError(_("You cannot create a fiscal position with a foreign VAT within your fiscal country."))
  77. similar_fpos_domain = [
  78. ('foreign_vat', '!=', False),
  79. ('country_id', '=', record.country_id.id),
  80. ('company_id', '=', record.company_id.id),
  81. ('id', '!=', record.id),
  82. ]
  83. if record.state_ids:
  84. similar_fpos_domain.append(('state_ids', 'in', record.state_ids.ids))
  85. similar_fpos_count = self.env['account.fiscal.position'].search_count(similar_fpos_domain)
  86. if similar_fpos_count:
  87. raise ValidationError(_("A fiscal position with a foreign VAT already exists in this region."))
  88. def map_tax(self, taxes):
  89. if not self:
  90. return taxes
  91. result = self.env['account.tax']
  92. for tax in taxes:
  93. taxes_correspondance = self.tax_ids.filtered(lambda t: t.tax_src_id == tax._origin)
  94. result |= taxes_correspondance.tax_dest_id if taxes_correspondance else tax
  95. return result
  96. def map_account(self, account):
  97. for pos in self.account_ids:
  98. if pos.account_src_id == account:
  99. return pos.account_dest_id
  100. return account
  101. def map_accounts(self, accounts):
  102. """ Receive a dictionary having accounts in values and try to replace those accounts accordingly to the fiscal position.
  103. """
  104. ref_dict = {}
  105. for line in self.account_ids:
  106. ref_dict[line.account_src_id] = line.account_dest_id
  107. for key, acc in accounts.items():
  108. if acc in ref_dict:
  109. accounts[key] = ref_dict[acc]
  110. return accounts
  111. @api.onchange('country_id')
  112. def _onchange_country_id(self):
  113. if self.country_id:
  114. self.zip_from = self.zip_to = self.country_group_id = False
  115. self.state_ids = [(5,)]
  116. self.states_count = len(self.country_id.state_ids)
  117. @api.onchange('country_group_id')
  118. def _onchange_country_group_id(self):
  119. if self.country_group_id:
  120. self.zip_from = self.zip_to = self.country_id = False
  121. self.state_ids = [(5,)]
  122. @api.model
  123. def _convert_zip_values(self, zip_from='', zip_to=''):
  124. max_length = max(len(zip_from), len(zip_to))
  125. if zip_from.isdigit():
  126. zip_from = zip_from.rjust(max_length, '0')
  127. if zip_to.isdigit():
  128. zip_to = zip_to.rjust(max_length, '0')
  129. return zip_from, zip_to
  130. @api.model_create_multi
  131. def create(self, vals_list):
  132. for vals in vals_list:
  133. zip_from = vals.get('zip_from')
  134. zip_to = vals.get('zip_to')
  135. if zip_from and zip_to:
  136. vals['zip_from'], vals['zip_to'] = self._convert_zip_values(zip_from, zip_to)
  137. return super().create(vals_list)
  138. def write(self, vals):
  139. zip_from = vals.get('zip_from')
  140. zip_to = vals.get('zip_to')
  141. if zip_from or zip_to:
  142. for rec in self:
  143. vals['zip_from'], vals['zip_to'] = self._convert_zip_values(zip_from or rec.zip_from, zip_to or rec.zip_to)
  144. return super(AccountFiscalPosition, self).write(vals)
  145. @api.model
  146. def _get_fpos_by_region(self, country_id=False, state_id=False, zipcode=False, vat_required=False):
  147. if not country_id:
  148. return False
  149. base_domain = [
  150. ('auto_apply', '=', True),
  151. ('vat_required', '=', vat_required),
  152. ('company_id', 'in', [self.env.company.id, False]),
  153. ]
  154. null_state_dom = state_domain = [('state_ids', '=', False)]
  155. null_zip_dom = zip_domain = [('zip_from', '=', False), ('zip_to', '=', False)]
  156. null_country_dom = [('country_id', '=', False), ('country_group_id', '=', False)]
  157. if zipcode:
  158. zip_domain = [('zip_from', '<=', zipcode), ('zip_to', '>=', zipcode)]
  159. if state_id:
  160. state_domain = [('state_ids', '=', state_id)]
  161. domain_country = base_domain + [('country_id', '=', country_id)]
  162. domain_group = base_domain + [('country_group_id.country_ids', '=', country_id)]
  163. # Build domain to search records with exact matching criteria
  164. fpos = self.search(domain_country + state_domain + zip_domain, limit=1)
  165. # return records that fit the most the criteria, and fallback on less specific fiscal positions if any can be found
  166. if not fpos and state_id:
  167. fpos = self.search(domain_country + null_state_dom + zip_domain, limit=1)
  168. if not fpos and zipcode:
  169. fpos = self.search(domain_country + state_domain + null_zip_dom, limit=1)
  170. if not fpos and state_id and zipcode:
  171. fpos = self.search(domain_country + null_state_dom + null_zip_dom, limit=1)
  172. # fallback: country group with no state/zip range
  173. if not fpos:
  174. fpos = self.search(domain_group + null_state_dom + null_zip_dom, limit=1)
  175. if not fpos:
  176. # Fallback on catchall (no country, no group)
  177. fpos = self.search(base_domain + null_country_dom, limit=1)
  178. return fpos
  179. @api.model
  180. def _get_fiscal_position(self, partner, delivery=None):
  181. """
  182. :return: fiscal position found (recordset)
  183. :rtype: :class:`account.fiscal.position`
  184. """
  185. if not partner:
  186. return self.env['account.fiscal.position']
  187. company = self.env.company
  188. intra_eu = vat_exclusion = False
  189. if company.vat and partner.vat:
  190. eu_country_codes = set(self.env.ref('base.europe').country_ids.mapped('code'))
  191. intra_eu = company.vat[:2] in eu_country_codes and partner.vat[:2] in eu_country_codes
  192. vat_exclusion = company.vat[:2] == partner.vat[:2]
  193. # If company and partner have the same vat prefix (and are both within the EU), use invoicing
  194. if not delivery or (intra_eu and vat_exclusion):
  195. delivery = partner
  196. # partner manually set fiscal position always win
  197. manual_fiscal_position = delivery.property_account_position_id or partner.property_account_position_id
  198. if manual_fiscal_position:
  199. return manual_fiscal_position
  200. # First search only matching VAT positions
  201. vat_required = bool(partner.vat)
  202. fp = self._get_fpos_by_region(delivery.country_id.id, delivery.state_id.id, delivery.zip, vat_required)
  203. # Then if VAT required found no match, try positions that do not require it
  204. if not fp and vat_required:
  205. fp = self._get_fpos_by_region(delivery.country_id.id, delivery.state_id.id, delivery.zip, False)
  206. return fp or self.env['account.fiscal.position']
  207. def action_create_foreign_taxes(self):
  208. self.ensure_one()
  209. self.env['account.tax.template']._try_instantiating_foreign_taxes(self.country_id, self.company_id)
  210. class AccountFiscalPositionTax(models.Model):
  211. _name = 'account.fiscal.position.tax'
  212. _description = 'Tax Mapping of Fiscal Position'
  213. _rec_name = 'position_id'
  214. _check_company_auto = True
  215. position_id = fields.Many2one('account.fiscal.position', string='Fiscal Position',
  216. required=True, ondelete='cascade')
  217. company_id = fields.Many2one('res.company', string='Company', related='position_id.company_id', store=True)
  218. tax_src_id = fields.Many2one('account.tax', string='Tax on Product', required=True, check_company=True)
  219. tax_dest_id = fields.Many2one('account.tax', string='Tax to Apply', check_company=True)
  220. _sql_constraints = [
  221. ('tax_src_dest_uniq',
  222. 'unique (position_id,tax_src_id,tax_dest_id)',
  223. 'A tax fiscal position could be defined only one time on same taxes.')
  224. ]
  225. class AccountFiscalPositionAccount(models.Model):
  226. _name = 'account.fiscal.position.account'
  227. _description = 'Accounts Mapping of Fiscal Position'
  228. _rec_name = 'position_id'
  229. _check_company_auto = True
  230. position_id = fields.Many2one('account.fiscal.position', string='Fiscal Position',
  231. required=True, ondelete='cascade')
  232. company_id = fields.Many2one('res.company', string='Company', related='position_id.company_id', store=True)
  233. account_src_id = fields.Many2one('account.account', string='Account on Product',
  234. check_company=True, required=True,
  235. domain="[('deprecated', '=', False), ('company_id', '=', company_id)]")
  236. account_dest_id = fields.Many2one('account.account', string='Account to Use Instead',
  237. check_company=True, required=True,
  238. domain="[('deprecated', '=', False), ('company_id', '=', company_id)]")
  239. _sql_constraints = [
  240. ('account_src_dest_uniq',
  241. 'unique (position_id,account_src_id,account_dest_id)',
  242. 'An account fiscal position could be defined only one time on same accounts.')
  243. ]
  244. class ResPartner(models.Model):
  245. _name = 'res.partner'
  246. _inherit = 'res.partner'
  247. @property
  248. def _order(self):
  249. res = super()._order
  250. partner_search_mode = self.env.context.get('res_partner_search_mode')
  251. if partner_search_mode not in ('customer', 'supplier'):
  252. return res
  253. order_by_field = f"{partner_search_mode}_rank DESC"
  254. return '%s, %s' % (order_by_field, res) if res else order_by_field
  255. @api.depends_context('company')
  256. def _credit_debit_get(self):
  257. tables, where_clause, where_params = self.env['account.move.line']._where_calc([
  258. ('parent_state', '=', 'posted'),
  259. ('company_id', '=', self.env.company.id)
  260. ]).get_sql()
  261. where_params = [tuple(self.ids)] + where_params
  262. if where_clause:
  263. where_clause = 'AND ' + where_clause
  264. self._cr.execute("""SELECT account_move_line.partner_id, a.account_type, SUM(account_move_line.amount_residual)
  265. FROM """ + tables + """
  266. LEFT JOIN account_account a ON (account_move_line.account_id=a.id)
  267. WHERE a.account_type IN ('asset_receivable','liability_payable')
  268. AND account_move_line.partner_id IN %s
  269. AND account_move_line.reconciled IS NOT TRUE
  270. """ + where_clause + """
  271. GROUP BY account_move_line.partner_id, a.account_type
  272. """, where_params)
  273. treated = self.browse()
  274. for pid, type, val in self._cr.fetchall():
  275. partner = self.browse(pid)
  276. if type == 'asset_receivable':
  277. partner.credit = val
  278. if partner not in treated:
  279. partner.debit = False
  280. treated |= partner
  281. elif type == 'liability_payable':
  282. partner.debit = -val
  283. if partner not in treated:
  284. partner.credit = False
  285. treated |= partner
  286. remaining = (self - treated)
  287. remaining.debit = False
  288. remaining.credit = False
  289. def _asset_difference_search(self, account_type, operator, operand):
  290. if operator not in ('<', '=', '>', '>=', '<='):
  291. return []
  292. if type(operand) not in (float, int):
  293. return []
  294. sign = 1
  295. if account_type == 'liability_payable':
  296. sign = -1
  297. res = self._cr.execute('''
  298. SELECT partner.id
  299. FROM res_partner partner
  300. LEFT JOIN account_move_line aml ON aml.partner_id = partner.id
  301. JOIN account_move move ON move.id = aml.move_id
  302. RIGHT JOIN account_account acc ON aml.account_id = acc.id
  303. WHERE acc.account_type = %s
  304. AND NOT acc.deprecated AND acc.company_id = %s
  305. AND move.state = 'posted'
  306. GROUP BY partner.id
  307. HAVING %s * COALESCE(SUM(aml.amount_residual), 0) ''' + operator + ''' %s''', (account_type, self.env.company.id, sign, operand))
  308. res = self._cr.fetchall()
  309. if not res:
  310. return [('id', '=', '0')]
  311. return [('id', 'in', [r[0] for r in res])]
  312. @api.model
  313. def _credit_search(self, operator, operand):
  314. return self._asset_difference_search('asset_receivable', operator, operand)
  315. @api.model
  316. def _debit_search(self, operator, operand):
  317. return self._asset_difference_search('liability_payable', operator, operand)
  318. def _invoice_total(self):
  319. self.total_invoiced = 0
  320. if not self.ids:
  321. return True
  322. all_partners_and_children = {}
  323. all_partner_ids = []
  324. for partner in self.filtered('id'):
  325. # price_total is in the company currency
  326. all_partners_and_children[partner] = self.with_context(active_test=False).search([('id', 'child_of', partner.id)]).ids
  327. all_partner_ids += all_partners_and_children[partner]
  328. domain = [
  329. ('partner_id', 'in', all_partner_ids),
  330. ('state', 'not in', ['draft', 'cancel']),
  331. ('move_type', 'in', ('out_invoice', 'out_refund')),
  332. ]
  333. price_totals = self.env['account.invoice.report'].read_group(domain, ['price_subtotal'], ['partner_id'])
  334. for partner, child_ids in all_partners_and_children.items():
  335. partner.total_invoiced = sum(price['price_subtotal'] for price in price_totals if price['partner_id'][0] in child_ids)
  336. def _compute_journal_item_count(self):
  337. AccountMoveLine = self.env['account.move.line']
  338. for partner in self:
  339. partner.journal_item_count = AccountMoveLine.search_count([('partner_id', '=', partner.id)])
  340. def _compute_has_unreconciled_entries(self):
  341. for partner in self:
  342. # Avoid useless work if has_unreconciled_entries is not relevant for this partner
  343. if not partner.active or not partner.is_company and partner.parent_id:
  344. partner.has_unreconciled_entries = False
  345. continue
  346. self.env.cr.execute(
  347. """ SELECT 1 FROM(
  348. SELECT
  349. p.last_time_entries_checked AS last_time_entries_checked,
  350. MAX(l.write_date) AS max_date
  351. FROM
  352. account_move_line l
  353. RIGHT JOIN account_account a ON (a.id = l.account_id)
  354. RIGHT JOIN res_partner p ON (l.partner_id = p.id)
  355. WHERE
  356. p.id = %s
  357. AND EXISTS (
  358. SELECT 1
  359. FROM account_move_line l
  360. WHERE l.account_id = a.id
  361. AND l.partner_id = p.id
  362. AND l.amount_residual > 0
  363. )
  364. AND EXISTS (
  365. SELECT 1
  366. FROM account_move_line l
  367. WHERE l.account_id = a.id
  368. AND l.partner_id = p.id
  369. AND l.amount_residual < 0
  370. )
  371. GROUP BY p.last_time_entries_checked
  372. ) as s
  373. WHERE (last_time_entries_checked IS NULL OR max_date > last_time_entries_checked)
  374. """, (partner.id,))
  375. partner.has_unreconciled_entries = self.env.cr.rowcount == 1
  376. def mark_as_reconciled(self):
  377. self.env['account.partial.reconcile'].check_access_rights('write')
  378. return self.sudo().write({'last_time_entries_checked': time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)})
  379. def _get_company_currency(self):
  380. for partner in self:
  381. if partner.company_id:
  382. partner.currency_id = partner.sudo().company_id.currency_id
  383. else:
  384. partner.currency_id = self.env.company.currency_id
  385. credit = fields.Monetary(compute='_credit_debit_get', search=_credit_search,
  386. string='Total Receivable', help="Total amount this customer owes you.",
  387. groups='account.group_account_invoice,account.group_account_readonly')
  388. credit_limit = fields.Float(
  389. string='Credit Limit', help='Credit limit specific to this partner.',
  390. groups='account.group_account_invoice,account.group_account_readonly',
  391. company_dependent=True, copy=False, readonly=False)
  392. use_partner_credit_limit = fields.Boolean(
  393. string='Partner Limit', groups='account.group_account_invoice,account.group_account_readonly',
  394. compute='_compute_use_partner_credit_limit', inverse='_inverse_use_partner_credit_limit')
  395. show_credit_limit = fields.Boolean(
  396. default=lambda self: self.env.company.account_use_credit_limit,
  397. compute='_compute_show_credit_limit', groups='account.group_account_invoice,account.group_account_readonly')
  398. debit = fields.Monetary(
  399. compute='_credit_debit_get', search=_debit_search, string='Total Payable',
  400. help="Total amount you have to pay to this vendor.",
  401. groups='account.group_account_invoice,account.group_account_readonly')
  402. debit_limit = fields.Monetary('Payable Limit')
  403. total_invoiced = fields.Monetary(compute='_invoice_total', string="Total Invoiced",
  404. groups='account.group_account_invoice,account.group_account_readonly')
  405. currency_id = fields.Many2one('res.currency', compute='_get_company_currency', readonly=True,
  406. string="Currency") # currency of amount currency
  407. journal_item_count = fields.Integer(compute='_compute_journal_item_count', string="Journal Items")
  408. property_account_payable_id = fields.Many2one('account.account', company_dependent=True,
  409. string="Account Payable",
  410. domain="[('account_type', '=', 'liability_payable'), ('deprecated', '=', False), ('company_id', '=', current_company_id)]",
  411. help="This account will be used instead of the default one as the payable account for the current partner",
  412. required=True)
  413. property_account_receivable_id = fields.Many2one('account.account', company_dependent=True,
  414. string="Account Receivable",
  415. domain="[('account_type', '=', 'asset_receivable'), ('deprecated', '=', False), ('company_id', '=', current_company_id)]",
  416. help="This account will be used instead of the default one as the receivable account for the current partner",
  417. required=True)
  418. property_account_position_id = fields.Many2one('account.fiscal.position', company_dependent=True,
  419. string="Fiscal Position",
  420. domain="[('company_id', '=', current_company_id)]",
  421. help="The fiscal position determines the taxes/accounts used for this contact.")
  422. property_payment_term_id = fields.Many2one('account.payment.term', company_dependent=True,
  423. string='Customer Payment Terms',
  424. domain="[('company_id', 'in', [current_company_id, False])]",
  425. help="This payment term will be used instead of the default one for sales orders and customer invoices")
  426. property_supplier_payment_term_id = fields.Many2one('account.payment.term', company_dependent=True,
  427. string='Vendor Payment Terms',
  428. domain="[('company_id', 'in', [current_company_id, False])]",
  429. help="This payment term will be used instead of the default one for purchase orders and vendor bills")
  430. ref_company_ids = fields.One2many('res.company', 'partner_id',
  431. string='Companies that refers to partner')
  432. has_unreconciled_entries = fields.Boolean(compute='_compute_has_unreconciled_entries',
  433. help="The partner has at least one unreconciled debit and credit since last time the invoices & payments matching was performed.")
  434. last_time_entries_checked = fields.Datetime(
  435. string='Latest Invoices & Payments Matching Date', readonly=True, copy=False,
  436. help='Last time the invoices & payments matching was performed for this partner. '
  437. 'It is set either if there\'s not at least an unreconciled debit and an unreconciled credit '
  438. 'or if you click the "Done" button.')
  439. invoice_ids = fields.One2many('account.move', 'partner_id', string='Invoices', readonly=True, copy=False)
  440. contract_ids = fields.One2many('account.analytic.account', 'partner_id', string='Partner Contracts', readonly=True)
  441. bank_account_count = fields.Integer(compute='_compute_bank_count', string="Bank")
  442. trust = fields.Selection([('good', 'Good Debtor'), ('normal', 'Normal Debtor'), ('bad', 'Bad Debtor')], string='Degree of trust you have in this debtor', default='normal', company_dependent=True)
  443. invoice_warn = fields.Selection(WARNING_MESSAGE, 'Invoice', help=WARNING_HELP, default="no-message")
  444. invoice_warn_msg = fields.Text('Message for Invoice')
  445. # Computed fields to order the partners as suppliers/customers according to the
  446. # amount of their generated incoming/outgoing account moves
  447. supplier_rank = fields.Integer(default=0, copy=False)
  448. customer_rank = fields.Integer(default=0, copy=False)
  449. # Technical field holding the amount partners that share the same account number as any set on this partner.
  450. duplicated_bank_account_partners_count = fields.Integer(
  451. compute='_compute_duplicated_bank_account_partners_count',
  452. )
  453. def _compute_bank_count(self):
  454. bank_data = self.env['res.partner.bank']._read_group([('partner_id', 'in', self.ids)], ['partner_id'], ['partner_id'])
  455. mapped_data = dict([(bank['partner_id'][0], bank['partner_id_count']) for bank in bank_data])
  456. for partner in self:
  457. partner.bank_account_count = mapped_data.get(partner.id, 0)
  458. def _get_duplicated_bank_accounts(self):
  459. self.ensure_one()
  460. if not self.bank_ids:
  461. return self.env['res.partner.bank']
  462. domains = []
  463. for bank in self.bank_ids:
  464. domains.append([('acc_number', '=', bank.acc_number), ('bank_id', '=', bank.bank_id.id)])
  465. domain = expression.OR(domains)
  466. if self.company_id:
  467. domain = expression.AND([domain, [('company_id', 'in', (False, self.company_id.id))]])
  468. domain = expression.AND([domain, [('partner_id', '!=', self._origin.id)]])
  469. return self.env['res.partner.bank'].search(domain)
  470. @api.depends('bank_ids')
  471. def _compute_duplicated_bank_account_partners_count(self):
  472. for partner in self:
  473. partner.duplicated_bank_account_partners_count = len(partner._get_duplicated_bank_accounts())
  474. @api.depends_context('company')
  475. def _compute_use_partner_credit_limit(self):
  476. for partner in self:
  477. company_limit = self.env['ir.property']._get('credit_limit', 'res.partner')
  478. partner.use_partner_credit_limit = partner.credit_limit != company_limit
  479. def _inverse_use_partner_credit_limit(self):
  480. for partner in self:
  481. if not partner.use_partner_credit_limit:
  482. partner.credit_limit = self.env['ir.property']._get('credit_limit', 'res.partner')
  483. @api.depends_context('company')
  484. def _compute_show_credit_limit(self):
  485. for partner in self:
  486. partner.show_credit_limit = self.env.company.account_use_credit_limit
  487. def _find_accounting_partner(self, partner):
  488. ''' Find the partner for which the accounting entries will be created '''
  489. return partner.commercial_partner_id
  490. @api.model
  491. def _commercial_fields(self):
  492. return super(ResPartner, self)._commercial_fields() + \
  493. ['debit_limit', 'property_account_payable_id', 'property_account_receivable_id', 'property_account_position_id',
  494. 'property_payment_term_id', 'property_supplier_payment_term_id', 'last_time_entries_checked', 'credit_limit']
  495. def action_view_partner_invoices(self):
  496. self.ensure_one()
  497. action = self.env["ir.actions.actions"]._for_xml_id("account.action_move_out_invoice_type")
  498. all_child = self.with_context(active_test=False).search([('id', 'child_of', self.ids)])
  499. action['domain'] = [
  500. ('move_type', 'in', ('out_invoice', 'out_refund')),
  501. ('partner_id', 'in', all_child.ids)
  502. ]
  503. action['context'] = {'default_move_type': 'out_invoice', 'move_type': 'out_invoice', 'journal_type': 'sale', 'search_default_unpaid': 1}
  504. return action
  505. def action_view_partner_with_same_bank(self):
  506. self.ensure_one()
  507. bank_partners = self._get_duplicated_bank_accounts()
  508. # Open a list view or form view of the partner(s) with the same bank accounts
  509. if self.duplicated_bank_account_partners_count == 1:
  510. action_vals = {
  511. 'type': 'ir.actions.act_window',
  512. 'res_model': 'res.partner',
  513. 'view_mode': 'form',
  514. 'res_id': bank_partners.partner_id.id,
  515. 'views': [(False, 'form')],
  516. }
  517. else:
  518. action_vals = {
  519. 'name': _("Partners"),
  520. 'type': 'ir.actions.act_window',
  521. 'res_model': 'res.partner',
  522. 'view_mode': 'tree,form',
  523. 'views': [(False, 'list'), (False, 'form')],
  524. 'domain': [('id', 'in', bank_partners.partner_id.ids)],
  525. }
  526. return action_vals
  527. def can_edit_vat(self):
  528. ''' Can't edit `vat` if there is (non draft) issued invoices. '''
  529. can_edit_vat = super(ResPartner, self).can_edit_vat()
  530. if not can_edit_vat:
  531. return can_edit_vat
  532. has_invoice = self.env['account.move'].search([
  533. ('move_type', 'in', ['out_invoice', 'out_refund']),
  534. ('partner_id', 'child_of', self.commercial_partner_id.id),
  535. ('state', '=', 'posted')
  536. ], limit=1)
  537. return can_edit_vat and not (bool(has_invoice))
  538. @api.model_create_multi
  539. def create(self, vals_list):
  540. search_partner_mode = self.env.context.get('res_partner_search_mode')
  541. is_customer = search_partner_mode == 'customer'
  542. is_supplier = search_partner_mode == 'supplier'
  543. if search_partner_mode:
  544. for vals in vals_list:
  545. if is_customer and 'customer_rank' not in vals:
  546. vals['customer_rank'] = 1
  547. elif is_supplier and 'supplier_rank' not in vals:
  548. vals['supplier_rank'] = 1
  549. return super().create(vals_list)
  550. @api.ondelete(at_uninstall=False)
  551. def _unlink_if_partner_in_account_move(self):
  552. """
  553. Prevent the deletion of a partner "Individual", child of a company if:
  554. - partner in 'account.move'
  555. - state: all states (draft and posted)
  556. """
  557. moves = self.sudo().env['account.move'].search_count([
  558. ('partner_id', 'in', self.ids),
  559. ('state', 'in', ['draft', 'posted']),
  560. ])
  561. if moves:
  562. raise UserError(_("The partner cannot be deleted because it is used in Accounting"))
  563. def _increase_rank(self, field, n=1):
  564. if self.ids and field in ['customer_rank', 'supplier_rank']:
  565. try:
  566. with self.env.cr.savepoint(flush=False), mute_logger('odoo.sql_db'):
  567. query = sql.SQL("""
  568. SELECT {field} FROM res_partner WHERE ID IN %(partner_ids)s FOR NO KEY UPDATE NOWAIT;
  569. UPDATE res_partner SET {field} = {field} + %(n)s
  570. WHERE id IN %(partner_ids)s
  571. """).format(field=sql.Identifier(field))
  572. self.env.cr.execute(query, {'partner_ids': tuple(self.ids), 'n': n})
  573. self.invalidate_recordset([field])
  574. except DatabaseError as e:
  575. # 55P03 LockNotAvailable
  576. # 40001 SerializationFailure
  577. if e.pgcode not in ('55P03', '40001'):
  578. raise e
  579. _logger.debug('Another transaction already locked partner rows. Cannot update partner ranks.')
  580. @api.model
  581. def get_partner_localisation_fields_required_to_invoice(self, country_id):
  582. """ Returns the list of fields that needs to be filled when creating an invoice for the selected country.
  583. This is required for some flows that would allow a user to request an invoice from the portal.
  584. Using these, we can get their information and dynamically create form inputs based for the fields required legally for the company country_id.
  585. The returned fields must be of type ir.model.fields in order to handle translations
  586. :param country_id: The country for which we want the fields.
  587. :return: an array of ir.model.fields for which the user should provide values.
  588. """
  589. return []
  590. def _merge_method(self, destination, source):
  591. """
  592. Prevent merging partners that are linked to already hashed journal items.
  593. """
  594. if self.env['account.move.line'].sudo().search([('move_id.inalterable_hash', '!=', False), ('partner_id', 'in', source.ids)], limit=1):
  595. raise UserError(_('Partners that are used in hashed entries cannot be merged.'))
  596. return super()._merge_method(destination, source)
  597. def _run_vat_test(self, vat_number, default_country, partner_is_company=True):
  598. """ Checks a VAT number syntactically to ensure its validity upon saving.
  599. A first check is made by using the first two characters of the VAT as
  600. the country code. If it fails, a second one is made using default_country instead.
  601. :param vat_number: a string with the VAT number to check.
  602. :param default_country: a res.country object
  603. :param partner_is_company: True if the partner is a company, else False.
  604. .. deprecated:: 16.0
  605. Will be removed in 16.2
  606. :return: The country code (in lower case) of the country the VAT number
  607. was validated for, if it was validated. False if it could not be validated
  608. against the provided or guessed country. None if no country was available
  609. for the check, and no conclusion could be made with certainty.
  610. """
  611. return default_country.code.lower()