res_partner.py 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120
  1. # -*- coding: utf-8 -*-
  2. # Part of Odoo. See LICENSE file for full copyright and licensing details.
  3. import base64
  4. import collections
  5. import datetime
  6. import hashlib
  7. import pytz
  8. import threading
  9. import re
  10. import requests
  11. from collections import defaultdict
  12. from lxml import etree
  13. from random import randint
  14. from werkzeug import urls
  15. from odoo import api, fields, models, tools, SUPERUSER_ID, _, Command
  16. from odoo.osv.expression import get_unaccent_wrapper
  17. from odoo.exceptions import RedirectWarning, UserError, ValidationError
  18. # Global variables used for the warning fields declared on the res.partner
  19. # in the following modules : sale, purchase, account, stock
  20. WARNING_MESSAGE = [
  21. ('no-message','No Message'),
  22. ('warning','Warning'),
  23. ('block','Blocking Message')
  24. ]
  25. WARNING_HELP = 'Selecting the "Warning" option will notify user with the message, Selecting "Blocking Message" will throw an exception with the message and block the flow. The Message has to be written in the next field.'
  26. ADDRESS_FIELDS = ('street', 'street2', 'zip', 'city', 'state_id', 'country_id')
  27. @api.model
  28. def _lang_get(self):
  29. return self.env['res.lang'].get_installed()
  30. # put POSIX 'Etc/*' entries at the end to avoid confusing users - see bug 1086728
  31. _tzs = [(tz, tz) for tz in sorted(pytz.all_timezones, key=lambda tz: tz if not tz.startswith('Etc/') else '_')]
  32. def _tz_get(self):
  33. return _tzs
  34. class FormatAddressMixin(models.AbstractModel):
  35. _name = "format.address.mixin"
  36. _description = 'Address Format'
  37. def _view_get_address(self, arch):
  38. # consider the country of the user, not the country of the partner we want to display
  39. address_view_id = self.env.company.country_id.address_view_id.sudo()
  40. address_format = self.env.company.country_id.address_format
  41. if address_view_id and not self._context.get('no_address_format') and (not address_view_id.model or address_view_id.model == self._name):
  42. #render the partner address accordingly to address_view_id
  43. for address_node in arch.xpath("//div[hasclass('o_address_format')]"):
  44. Partner = self.env['res.partner'].with_context(no_address_format=True)
  45. sub_arch, _sub_view = Partner._get_view(address_view_id.id, 'form')
  46. #if the model is different than res.partner, there are chances that the view won't work
  47. #(e.g fields not present on the model). In that case we just return arch
  48. if self._name != 'res.partner':
  49. try:
  50. self.env['ir.ui.view'].postprocess_and_fields(sub_arch, model=self._name)
  51. except ValueError:
  52. return arch
  53. address_node.getparent().replace(address_node, sub_arch)
  54. elif address_format and not self._context.get('no_address_format'):
  55. # For the zip, city and state fields we need to move them around in order to follow the country address format.
  56. # The purpose of this is to help the user by following a format he is used to.
  57. city_line = [line.split(' ') for line in address_format.split('\n') if 'city' in line]
  58. if city_line:
  59. field_order = [field.replace('%(', '').replace(')s', '') for field in city_line[0]]
  60. for address_node in arch.xpath("//div[hasclass('o_address_format')]"):
  61. concerned_fields = {'zip', 'city', 'state_id'} - {field_order[0]}
  62. current_field = address_node.find(f".//field[@name='{field_order[0]}']")
  63. # First loop into the fields displayed in the address_format, and order them.
  64. for field in field_order[1:]:
  65. if field in ('state_code', 'state_name'):
  66. field = 'state_id'
  67. previous_field = current_field
  68. current_field = address_node.find(f".//field[@name='{field}']")
  69. if previous_field is not None and current_field is not None:
  70. previous_field.addnext(current_field)
  71. concerned_fields -= {field}
  72. # Add the remaining fields in 'concerned_fields' at the end, after the others
  73. for field in concerned_fields:
  74. previous_field = current_field
  75. current_field = address_node.find(f".//field[@name='{field}']")
  76. if previous_field is not None and current_field is not None:
  77. previous_field.addnext(current_field)
  78. return arch
  79. @api.model
  80. def _get_view_cache_key(self, view_id=None, view_type='form', **options):
  81. """The override of _get_view, using _view_get_address,
  82. changing the architecture according to the address view of the company,
  83. makes the view cache dependent on the company.
  84. Different companies could use each a different address view"""
  85. key = super()._get_view_cache_key(view_id, view_type, **options)
  86. return key + (self.env.company, self._context.get('no_address_format'),)
  87. @api.model
  88. def _get_view(self, view_id=None, view_type='form', **options):
  89. arch, view = super()._get_view(view_id, view_type, **options)
  90. if view.type == 'form':
  91. arch = self._view_get_address(arch)
  92. return arch, view
  93. class PartnerCategory(models.Model):
  94. _description = 'Partner Tags'
  95. _name = 'res.partner.category'
  96. _order = 'name'
  97. _parent_store = True
  98. def _get_default_color(self):
  99. return randint(1, 11)
  100. name = fields.Char(string='Tag Name', required=True, translate=True)
  101. color = fields.Integer(string='Color', default=_get_default_color)
  102. parent_id = fields.Many2one('res.partner.category', string='Parent Category', index=True, ondelete='cascade')
  103. child_ids = fields.One2many('res.partner.category', 'parent_id', string='Child Tags')
  104. active = fields.Boolean(default=True, help="The active field allows you to hide the category without removing it.")
  105. parent_path = fields.Char(index=True, unaccent=False)
  106. partner_ids = fields.Many2many('res.partner', column1='category_id', column2='partner_id', string='Partners', copy=False)
  107. @api.constrains('parent_id')
  108. def _check_parent_id(self):
  109. if not self._check_recursion():
  110. raise ValidationError(_('You can not create recursive tags.'))
  111. def name_get(self):
  112. """ Return the categories' display name, including their direct
  113. parent by default.
  114. If ``context['partner_category_display']`` is ``'short'``, the short
  115. version of the category name (without the direct parent) is used.
  116. The default is the long version.
  117. """
  118. if self._context.get('partner_category_display') == 'short':
  119. return super(PartnerCategory, self).name_get()
  120. res = []
  121. for category in self:
  122. names = []
  123. current = category
  124. while current:
  125. names.append(current.name)
  126. current = current.parent_id
  127. res.append((category.id, ' / '.join(reversed(names))))
  128. return res
  129. @api.model
  130. def _name_search(self, name, args=None, operator='ilike', limit=100, name_get_uid=None):
  131. args = args or []
  132. if name:
  133. # Be sure name_search is symetric to name_get
  134. name = name.split(' / ')[-1]
  135. args = [('name', operator, name)] + args
  136. return self._search(args, limit=limit, access_rights_uid=name_get_uid)
  137. class PartnerTitle(models.Model):
  138. _name = 'res.partner.title'
  139. _order = 'name'
  140. _description = 'Partner Title'
  141. name = fields.Char(string='Title', required=True, translate=True)
  142. shortcut = fields.Char(string='Abbreviation', translate=True)
  143. class Partner(models.Model):
  144. _description = 'Contact'
  145. _inherit = ['format.address.mixin', 'avatar.mixin']
  146. _name = "res.partner"
  147. _order = "display_name ASC, id DESC"
  148. _rec_names_search = ['display_name', 'email', 'ref', 'vat', 'company_registry'] # TODO vat must be sanitized the same way for storing/searching
  149. def _default_category(self):
  150. return self.env['res.partner.category'].browse(self._context.get('category_id'))
  151. @api.model
  152. def default_get(self, default_fields):
  153. """Add the company of the parent as default if we are creating a child partner.
  154. Also take the parent lang by default if any, otherwise, fallback to default DB lang."""
  155. values = super().default_get(default_fields)
  156. parent = self.env["res.partner"]
  157. if 'parent_id' in default_fields and values.get('parent_id'):
  158. parent = self.browse(values.get('parent_id'))
  159. values['company_id'] = parent.company_id.id
  160. if 'lang' in default_fields:
  161. values['lang'] = values.get('lang') or parent.lang or self.env.lang
  162. # protection for `default_type` values leaking from menu action context (e.g. for crm's email)
  163. if 'type' in default_fields and values.get('type'):
  164. if values['type'] not in self._fields['type'].get_values(self.env):
  165. values['type'] = None
  166. return values
  167. name = fields.Char(index=True, default_export_compatible=True)
  168. display_name = fields.Char(compute='_compute_display_name', recursive=True, store=True, index=True)
  169. date = fields.Date(index=True)
  170. title = fields.Many2one('res.partner.title')
  171. parent_id = fields.Many2one('res.partner', string='Related Company', index=True)
  172. parent_name = fields.Char(related='parent_id.name', readonly=True, string='Parent name')
  173. child_ids = fields.One2many('res.partner', 'parent_id', string='Contact', domain=[('active', '=', True)]) # force "active_test" domain to bypass _search() override
  174. ref = fields.Char(string='Reference', index=True)
  175. lang = fields.Selection(_lang_get, string='Language',
  176. help="All the emails and documents sent to this contact will be translated in this language.")
  177. active_lang_count = fields.Integer(compute='_compute_active_lang_count')
  178. tz = fields.Selection(_tz_get, string='Timezone', default=lambda self: self._context.get('tz'),
  179. help="When printing documents and exporting/importing data, time values are computed according to this timezone.\n"
  180. "If the timezone is not set, UTC (Coordinated Universal Time) is used.\n"
  181. "Anywhere else, time values are computed according to the time offset of your web client.")
  182. tz_offset = fields.Char(compute='_compute_tz_offset', string='Timezone offset', invisible=True)
  183. user_id = fields.Many2one(
  184. 'res.users', string='Salesperson',
  185. compute='_compute_user_id',
  186. precompute=True, # avoid queries post-create
  187. readonly=False, store=True,
  188. help='The internal user in charge of this contact.')
  189. vat = fields.Char(string='Tax ID', index=True, help="The Tax Identification Number. Values here will be validated based on the country format. You can use '/' to indicate that the partner is not subject to tax.")
  190. same_vat_partner_id = fields.Many2one('res.partner', string='Partner with same Tax ID', compute='_compute_same_vat_partner_id', store=False)
  191. same_company_registry_partner_id = fields.Many2one('res.partner', string='Partner with same Company Registry', compute='_compute_same_vat_partner_id', store=False)
  192. company_registry = fields.Char(string="Company ID", compute='_compute_company_registry', store=True, readonly=False,
  193. help="The registry number of the company. Use it if it is different from the Tax ID. It must be unique across all partners of a same country")
  194. bank_ids = fields.One2many('res.partner.bank', 'partner_id', string='Banks')
  195. website = fields.Char('Website Link')
  196. comment = fields.Html(string='Notes')
  197. category_id = fields.Many2many('res.partner.category', column1='partner_id',
  198. column2='category_id', string='Tags', default=_default_category)
  199. active = fields.Boolean(default=True)
  200. employee = fields.Boolean(help="Check this box if this contact is an Employee.")
  201. function = fields.Char(string='Job Position')
  202. type = fields.Selection(
  203. [('contact', 'Contact'),
  204. ('invoice', 'Invoice Address'),
  205. ('delivery', 'Delivery Address'),
  206. ('private', 'Private Address'),
  207. ('other', 'Other Address'),
  208. ], string='Address Type',
  209. default='contact',
  210. help="- Contact: Use this to organize the contact details of employees of a given company (e.g. CEO, CFO, ...).\n"
  211. "- Invoice Address : Preferred address for all invoices. Selected by default when you invoice an order that belongs to this company.\n"
  212. "- Delivery Address : Preferred address for all deliveries. Selected by default when you deliver an order that belongs to this company.\n"
  213. "- Private: Private addresses are only visible by authorized users and contain sensitive data (employee home addresses, ...).\n"
  214. "- Other: Other address for the company (e.g. subsidiary, ...)")
  215. # address fields
  216. street = fields.Char()
  217. street2 = fields.Char()
  218. zip = fields.Char(change_default=True)
  219. city = fields.Char()
  220. state_id = fields.Many2one("res.country.state", string='State', ondelete='restrict', domain="[('country_id', '=?', country_id)]")
  221. country_id = fields.Many2one('res.country', string='Country', ondelete='restrict')
  222. country_code = fields.Char(related='country_id.code', string="Country Code")
  223. partner_latitude = fields.Float(string='Geo Latitude', digits=(10, 7))
  224. partner_longitude = fields.Float(string='Geo Longitude', digits=(10, 7))
  225. email = fields.Char()
  226. email_formatted = fields.Char(
  227. 'Formatted Email', compute='_compute_email_formatted',
  228. help='Format email address "Name <email@domain>"')
  229. phone = fields.Char(unaccent=False)
  230. mobile = fields.Char(unaccent=False)
  231. is_company = fields.Boolean(string='Is a Company', default=False,
  232. help="Check if the contact is a company, otherwise it is a person")
  233. is_public = fields.Boolean(compute='_compute_is_public')
  234. industry_id = fields.Many2one('res.partner.industry', 'Industry')
  235. # company_type is only an interface field, do not use it in business logic
  236. company_type = fields.Selection(string='Company Type',
  237. selection=[('person', 'Individual'), ('company', 'Company')],
  238. compute='_compute_company_type', inverse='_write_company_type')
  239. company_id = fields.Many2one('res.company', 'Company', index=True)
  240. color = fields.Integer(string='Color Index', default=0)
  241. user_ids = fields.One2many('res.users', 'partner_id', string='Users', auto_join=True)
  242. partner_share = fields.Boolean(
  243. 'Share Partner', compute='_compute_partner_share', store=True,
  244. help="Either customer (not a user), either shared user. Indicated the current partner is a customer without "
  245. "access or with a limited access created for sharing data.")
  246. contact_address = fields.Char(compute='_compute_contact_address', string='Complete Address')
  247. # technical field used for managing commercial fields
  248. commercial_partner_id = fields.Many2one(
  249. 'res.partner', string='Commercial Entity',
  250. compute='_compute_commercial_partner', store=True,
  251. recursive=True, index=True)
  252. commercial_company_name = fields.Char('Company Name Entity', compute='_compute_commercial_company_name',
  253. store=True)
  254. company_name = fields.Char('Company Name')
  255. barcode = fields.Char(help="Use a barcode to identify this contact.", copy=False, company_dependent=True)
  256. # hack to allow using plain browse record in qweb views, and used in ir.qweb.field.contact
  257. self = fields.Many2one(comodel_name=_name, compute='_compute_get_ids')
  258. _sql_constraints = [
  259. ('check_name', "CHECK( (type='contact' AND name IS NOT NULL) or (type!='contact') )", 'Contacts require a name'),
  260. ]
  261. def _get_street_split(self):
  262. self.ensure_one()
  263. return tools.street_split(self.street or '')
  264. @api.depends('name', 'user_ids.share', 'image_1920', 'is_company', 'type')
  265. def _compute_avatar_1920(self):
  266. super()._compute_avatar_1920()
  267. @api.depends('name', 'user_ids.share', 'image_1024', 'is_company', 'type')
  268. def _compute_avatar_1024(self):
  269. super()._compute_avatar_1024()
  270. @api.depends('name', 'user_ids.share', 'image_512', 'is_company', 'type')
  271. def _compute_avatar_512(self):
  272. super()._compute_avatar_512()
  273. @api.depends('name', 'user_ids.share', 'image_256', 'is_company', 'type')
  274. def _compute_avatar_256(self):
  275. super()._compute_avatar_256()
  276. @api.depends('name', 'user_ids.share', 'image_128', 'is_company', 'type')
  277. def _compute_avatar_128(self):
  278. super()._compute_avatar_128()
  279. def _compute_avatar(self, avatar_field, image_field):
  280. partners_with_internal_user = self.filtered(lambda partner: partner.user_ids - partner.user_ids.filtered('share'))
  281. super(Partner, partners_with_internal_user)._compute_avatar(avatar_field, image_field)
  282. partners_without_image = (self - partners_with_internal_user).filtered(lambda p: not p[image_field])
  283. for _, group in tools.groupby(partners_without_image, key=lambda p: p._avatar_get_placeholder_path()):
  284. group_partners = self.env['res.partner'].concat(*group)
  285. group_partners[avatar_field] = base64.b64encode(group_partners[0]._avatar_get_placeholder())
  286. for partner in self - partners_with_internal_user - partners_without_image:
  287. partner[avatar_field] = partner[image_field]
  288. def _avatar_get_placeholder_path(self):
  289. if self.is_company:
  290. return "base/static/img/company_image.png"
  291. if self.type == 'delivery':
  292. return "base/static/img/truck.png"
  293. if self.type == 'invoice':
  294. return "base/static/img/money.png"
  295. return super()._avatar_get_placeholder_path()
  296. @api.depends('is_company', 'name', 'parent_id.display_name', 'type', 'company_name', 'commercial_company_name')
  297. def _compute_display_name(self):
  298. # retrieve name_get() without any fancy feature
  299. names = dict(self.with_context({}).name_get())
  300. for partner in self:
  301. partner.display_name = names.get(partner.id)
  302. @api.depends('lang')
  303. def _compute_active_lang_count(self):
  304. lang_count = len(self.env['res.lang'].get_installed())
  305. for partner in self:
  306. partner.active_lang_count = lang_count
  307. @api.depends('tz')
  308. def _compute_tz_offset(self):
  309. for partner in self:
  310. partner.tz_offset = datetime.datetime.now(pytz.timezone(partner.tz or 'GMT')).strftime('%z')
  311. @api.depends('parent_id')
  312. def _compute_user_id(self):
  313. """ Synchronize sales rep with parent if partner is a person """
  314. for partner in self.filtered(lambda partner: not partner.user_id and partner.company_type == 'person' and partner.parent_id.user_id):
  315. partner.user_id = partner.parent_id.user_id
  316. @api.depends('user_ids.share', 'user_ids.active')
  317. def _compute_partner_share(self):
  318. super_partner = self.env['res.users'].browse(SUPERUSER_ID).partner_id
  319. if super_partner in self:
  320. super_partner.partner_share = False
  321. for partner in self - super_partner:
  322. partner.partner_share = not partner.user_ids or not any(not user.share for user in partner.user_ids)
  323. @api.depends('vat', 'company_id', 'company_registry')
  324. def _compute_same_vat_partner_id(self):
  325. for partner in self:
  326. # use _origin to deal with onchange()
  327. partner_id = partner._origin.id
  328. #active_test = False because if a partner has been deactivated you still want to raise the error,
  329. #so that you can reactivate it instead of creating a new one, which would loose its history.
  330. Partner = self.with_context(active_test=False).sudo()
  331. domain = [
  332. ('vat', '=', partner.vat),
  333. ]
  334. if partner.company_id:
  335. domain += [('company_id', 'in', [False, partner.company_id.id])]
  336. if partner_id:
  337. domain += [('id', '!=', partner_id), '!', ('id', 'child_of', partner_id)]
  338. # For VAT number being only one character, we will skip the check just like the regular check_vat
  339. should_check_vat = partner.vat and len(partner.vat) != 1
  340. partner.same_vat_partner_id = should_check_vat and not partner.parent_id and Partner.search(domain, limit=1)
  341. # check company_registry
  342. domain = [
  343. ('company_registry', '=', partner.company_registry),
  344. ('company_id', 'in', [False, partner.company_id.id]),
  345. ]
  346. if partner_id:
  347. domain += [('id', '!=', partner_id), '!', ('id', 'child_of', partner_id)]
  348. partner.same_company_registry_partner_id = bool(partner.company_registry) and not partner.parent_id and Partner.search(domain, limit=1)
  349. @api.depends(lambda self: self._display_address_depends())
  350. def _compute_contact_address(self):
  351. for partner in self:
  352. partner.contact_address = partner._display_address()
  353. def _compute_get_ids(self):
  354. for partner in self:
  355. partner.self = partner.id
  356. @api.depends('is_company', 'parent_id.commercial_partner_id')
  357. def _compute_commercial_partner(self):
  358. for partner in self:
  359. if partner.is_company or not partner.parent_id:
  360. partner.commercial_partner_id = partner
  361. else:
  362. partner.commercial_partner_id = partner.parent_id.commercial_partner_id
  363. @api.depends('company_name', 'parent_id.is_company', 'commercial_partner_id.name')
  364. def _compute_commercial_company_name(self):
  365. for partner in self:
  366. p = partner.commercial_partner_id
  367. partner.commercial_company_name = p.is_company and p.name or partner.company_name
  368. def _compute_company_registry(self):
  369. # exists to allow overrides
  370. for company in self:
  371. company.company_registry = company.company_registry
  372. @api.model
  373. def _get_view(self, view_id=None, view_type='form', **options):
  374. if (not view_id) and (view_type == 'form') and self._context.get('force_email'):
  375. view_id = self.env.ref('base.view_partner_simple_form').id
  376. arch, view = super()._get_view(view_id, view_type, **options)
  377. company = self.env.company
  378. if company.country_id.vat_label:
  379. for node in arch.xpath("//field[@name='vat']"):
  380. node.attrib["string"] = company.country_id.vat_label
  381. return arch, view
  382. @api.constrains('parent_id')
  383. def _check_parent_id(self):
  384. if not self._check_recursion():
  385. raise ValidationError(_('You cannot create recursive Partner hierarchies.'))
  386. def copy(self, default=None):
  387. self.ensure_one()
  388. chosen_name = default.get('name') if default else ''
  389. new_name = chosen_name or _('%s (copy)', self.name)
  390. default = dict(default or {}, name=new_name)
  391. return super(Partner, self).copy(default)
  392. @api.onchange('parent_id')
  393. def onchange_parent_id(self):
  394. # return values in result, as this method is used by _fields_sync()
  395. if not self.parent_id:
  396. return
  397. result = {}
  398. partner = self._origin
  399. if partner.parent_id and partner.parent_id != self.parent_id:
  400. result['warning'] = {
  401. 'title': _('Warning'),
  402. 'message': _('Changing the company of a contact should only be done if it '
  403. 'was never correctly set. If an existing contact starts working for a new '
  404. 'company then a new contact should be created under that new '
  405. 'company. You can use the "Discard" button to abandon this change.')}
  406. if partner.type == 'contact' or self.type == 'contact':
  407. # for contacts: copy the parent address, if set (aka, at least one
  408. # value is set in the address: otherwise, keep the one from the
  409. # contact)
  410. address_fields = self._address_fields()
  411. if any(self.parent_id[key] for key in address_fields):
  412. def convert(value):
  413. return value.id if isinstance(value, models.BaseModel) else value
  414. result['value'] = {key: convert(self.parent_id[key]) for key in address_fields}
  415. return result
  416. @api.onchange('parent_id')
  417. def _onchange_parent_id_for_lang(self):
  418. # While creating / updating child contact, take the parent lang by default if any
  419. # otherwise, fallback to default context / DB lang
  420. if self.parent_id:
  421. self.lang = self.parent_id.lang or self.env.context.get('default_lang') or self.env.lang
  422. @api.onchange('country_id')
  423. def _onchange_country_id(self):
  424. if self.country_id and self.country_id != self.state_id.country_id:
  425. self.state_id = False
  426. @api.onchange('state_id')
  427. def _onchange_state(self):
  428. if self.state_id.country_id:
  429. self.country_id = self.state_id.country_id
  430. @api.onchange('email')
  431. def onchange_email(self):
  432. if not self.image_1920 and self._context.get('gravatar_image') and self.email:
  433. self.image_1920 = self._get_gravatar_image(self.email)
  434. @api.onchange('parent_id', 'company_id')
  435. def _onchange_company_id(self):
  436. if self.parent_id:
  437. self.company_id = self.parent_id.company_id.id
  438. @api.depends('name', 'email')
  439. def _compute_email_formatted(self):
  440. """ Compute formatted email for partner, using formataddr. Be defensive
  441. in computation, notably
  442. * double format: if email already holds a formatted email like
  443. 'Name' <email@domain.com> we should not use it as it to compute
  444. email formatted like "Name <'Name' <email@domain.com>>";
  445. * multi emails: sometimes this field is used to hold several addresses
  446. like email1@domain.com, email2@domain.com. We currently let this value
  447. untouched, but remove any formatting from multi emails;
  448. * invalid email: if something is wrong, keep it in email_formatted as
  449. this eases management and understanding of failures at mail.mail,
  450. mail.notification and mailing.trace level;
  451. * void email: email_formatted is False, as we cannot do anything with
  452. it;
  453. """
  454. self.email_formatted = False
  455. for partner in self:
  456. emails_normalized = tools.email_normalize_all(partner.email)
  457. if emails_normalized:
  458. # note: multi-email input leads to invalid email like "Name" <email1, email2>
  459. # but this is current behavior in Odoo 14+ and some servers allow it
  460. partner.email_formatted = tools.formataddr((
  461. partner.name or u"False",
  462. ','.join(emails_normalized)
  463. ))
  464. elif partner.email:
  465. partner.email_formatted = tools.formataddr((
  466. partner.name or u"False",
  467. partner.email
  468. ))
  469. @api.depends('is_company')
  470. def _compute_company_type(self):
  471. for partner in self:
  472. partner.company_type = 'company' if partner.is_company else 'person'
  473. def _write_company_type(self):
  474. for partner in self:
  475. partner.is_company = partner.company_type == 'company'
  476. @api.onchange('company_type')
  477. def onchange_company_type(self):
  478. self.is_company = (self.company_type == 'company')
  479. @api.constrains('barcode')
  480. def _check_barcode_unicity(self):
  481. for partner in self:
  482. if partner.barcode and self.env['res.partner'].search_count([('barcode', '=', partner.barcode)]) > 1:
  483. raise ValidationError(_('Another partner already has this barcode'))
  484. def _update_fields_values(self, fields):
  485. """ Returns dict of write() values for synchronizing ``fields`` """
  486. values = {}
  487. for fname in fields:
  488. field = self._fields[fname]
  489. if field.type == 'many2one':
  490. values[fname] = self[fname].id
  491. elif field.type == 'one2many':
  492. raise AssertionError(_('One2Many fields cannot be synchronized as part of `commercial_fields` or `address fields`'))
  493. elif field.type == 'many2many':
  494. values[fname] = [Command.set(self[fname].ids)]
  495. else:
  496. values[fname] = self[fname]
  497. return values
  498. @api.model
  499. def _address_fields(self):
  500. """Returns the list of address fields that are synced from the parent."""
  501. return list(ADDRESS_FIELDS)
  502. @api.model
  503. def _formatting_address_fields(self):
  504. """Returns the list of address fields usable to format addresses."""
  505. return self._address_fields()
  506. def update_address(self, vals):
  507. addr_vals = {key: vals[key] for key in self._address_fields() if key in vals}
  508. if addr_vals:
  509. return super(Partner, self).write(addr_vals)
  510. @api.model
  511. def _commercial_fields(self):
  512. """ Returns the list of fields that are managed by the commercial entity
  513. to which a partner belongs. These fields are meant to be hidden on
  514. partners that aren't `commercial entities` themselves, and will be
  515. delegated to the parent `commercial entity`. The list is meant to be
  516. extended by inheriting classes. """
  517. return ['vat', 'company_registry', 'industry_id']
  518. def _commercial_sync_from_company(self):
  519. """ Handle sync of commercial fields when a new parent commercial entity is set,
  520. as if they were related fields """
  521. commercial_partner = self.commercial_partner_id
  522. if commercial_partner != self:
  523. sync_vals = commercial_partner._update_fields_values(self._commercial_fields())
  524. self.write(sync_vals)
  525. self._commercial_sync_to_children()
  526. def _commercial_sync_to_children(self):
  527. """ Handle sync of commercial fields to descendants """
  528. commercial_partner = self.commercial_partner_id
  529. sync_vals = commercial_partner._update_fields_values(self._commercial_fields())
  530. sync_children = self.child_ids.filtered(lambda c: not c.is_company)
  531. for child in sync_children:
  532. child._commercial_sync_to_children()
  533. res = sync_children.write(sync_vals)
  534. sync_children._compute_commercial_partner()
  535. return res
  536. def _fields_sync(self, values):
  537. """ Sync commercial fields and address fields from company and to children after create/update,
  538. just as if those were all modeled as fields.related to the parent """
  539. # 1. From UPSTREAM: sync from parent
  540. if values.get('parent_id') or values.get('type') == 'contact':
  541. # 1a. Commercial fields: sync if parent changed
  542. if values.get('parent_id'):
  543. self.sudo()._commercial_sync_from_company()
  544. # 1b. Address fields: sync if parent or use_parent changed *and* both are now set
  545. if self.parent_id and self.type == 'contact':
  546. onchange_vals = self.onchange_parent_id().get('value', {})
  547. self.update_address(onchange_vals)
  548. # 2. To DOWNSTREAM: sync children
  549. self._children_sync(values)
  550. def _children_sync(self, values):
  551. if not self.child_ids:
  552. return
  553. # 2a. Commercial Fields: sync if commercial entity
  554. if self.commercial_partner_id == self:
  555. commercial_fields = self._commercial_fields()
  556. if any(field in values for field in commercial_fields):
  557. self.sudo()._commercial_sync_to_children()
  558. for child in self.child_ids.filtered(lambda c: not c.is_company):
  559. if child.commercial_partner_id != self.commercial_partner_id:
  560. self.sudo()._commercial_sync_to_children()
  561. break
  562. # 2b. Address fields: sync if address changed
  563. address_fields = self._address_fields()
  564. if any(field in values for field in address_fields):
  565. contacts = self.child_ids.filtered(lambda c: c.type == 'contact')
  566. contacts.update_address(values)
  567. def _handle_first_contact_creation(self):
  568. """ On creation of first contact for a company (or root) that has no address, assume contact address
  569. was meant to be company address """
  570. parent = self.parent_id
  571. address_fields = self._address_fields()
  572. if (parent.is_company or not parent.parent_id) and len(parent.child_ids) == 1 and \
  573. any(self[f] for f in address_fields) and not any(parent[f] for f in address_fields):
  574. addr_vals = self._update_fields_values(address_fields)
  575. parent.update_address(addr_vals)
  576. def _clean_website(self, website):
  577. url = urls.url_parse(website)
  578. if not url.scheme:
  579. if not url.netloc:
  580. url = url.replace(netloc=url.path, path='')
  581. website = url.replace(scheme='http').to_url()
  582. return website
  583. def _compute_is_public(self):
  584. for partner in self.with_context(active_test=False):
  585. users = partner.user_ids
  586. partner.is_public = users and any(user._is_public() for user in users)
  587. def write(self, vals):
  588. if vals.get('active') is False:
  589. # DLE: It should not be necessary to modify this to make work the ORM. The problem was just the recompute
  590. # of partner.user_ids when you create a new user for this partner, see test test_70_archive_internal_partners
  591. # You modified it in a previous commit, see original commit of this:
  592. # https://github.com/odoo/odoo/commit/9d7226371730e73c296bcc68eb1f856f82b0b4ed
  593. #
  594. # RCO: when creating a user for partner, the user is automatically added in partner.user_ids.
  595. # This is wrong if the user is not active, as partner.user_ids only returns active users.
  596. # Hence this temporary hack until the ORM updates inverse fields correctly.
  597. self.invalidate_recordset(['user_ids'])
  598. users = self.env['res.users'].sudo().search([('partner_id', 'in', self.ids)])
  599. if users:
  600. if self.env['res.users'].sudo(False).check_access_rights('write', raise_exception=False):
  601. error_msg = _('You cannot archive contacts linked to an active user.\n'
  602. 'You first need to archive their associated user.\n\n'
  603. 'Linked active users : %(names)s', names=", ".join([u.display_name for u in users]))
  604. action_error = users._action_show()
  605. raise RedirectWarning(error_msg, action_error, _('Go to users'))
  606. else:
  607. raise ValidationError(_('You cannot archive contacts linked to an active user.\n'
  608. 'Ask an administrator to archive their associated user first.\n\n'
  609. 'Linked active users :\n%(names)s', names=", ".join([u.display_name for u in users])))
  610. # res.partner must only allow to set the company_id of a partner if it
  611. # is the same as the company of all users that inherit from this partner
  612. # (this is to allow the code from res_users to write to the partner!) or
  613. # if setting the company_id to False (this is compatible with any user
  614. # company)
  615. if vals.get('website'):
  616. vals['website'] = self._clean_website(vals['website'])
  617. if vals.get('parent_id'):
  618. vals['company_name'] = False
  619. if 'company_id' in vals:
  620. company_id = vals['company_id']
  621. for partner in self:
  622. if company_id and partner.user_ids:
  623. company = self.env['res.company'].browse(company_id)
  624. companies = set(user.company_id for user in partner.user_ids)
  625. if len(companies) > 1 or company not in companies:
  626. raise UserError(
  627. ("The selected company is not compatible with the companies of the related user(s)"))
  628. if partner.child_ids:
  629. partner.child_ids.write({'company_id': company_id})
  630. result = True
  631. # To write in SUPERUSER on field is_company and avoid access rights problems.
  632. if 'is_company' in vals and self.user_has_groups('base.group_partner_manager') and not self.env.su:
  633. result = super(Partner, self.sudo()).write({'is_company': vals.get('is_company')})
  634. del vals['is_company']
  635. result = result and super(Partner, self).write(vals)
  636. for partner in self:
  637. if any(u._is_internal() for u in partner.user_ids if u != self.env.user):
  638. self.env['res.users'].check_access_rights('write')
  639. partner._fields_sync(vals)
  640. return result
  641. @api.model_create_multi
  642. def create(self, vals_list):
  643. if self.env.context.get('import_file'):
  644. self._check_import_consistency(vals_list)
  645. for vals in vals_list:
  646. if vals.get('website'):
  647. vals['website'] = self._clean_website(vals['website'])
  648. if vals.get('parent_id'):
  649. vals['company_name'] = False
  650. partners = super(Partner, self).create(vals_list)
  651. if self.env.context.get('_partners_skip_fields_sync'):
  652. return partners
  653. for partner, vals in zip(partners, vals_list):
  654. partner._fields_sync(vals)
  655. # Lang: propagate from parent if no value was given
  656. if 'lang' not in vals and partner.parent_id:
  657. partner._onchange_parent_id_for_lang()
  658. partner._handle_first_contact_creation()
  659. return partners
  660. @api.ondelete(at_uninstall=False)
  661. def _unlink_except_user(self):
  662. users = self.env['res.users'].sudo().search([('partner_id', 'in', self.ids)])
  663. if not users:
  664. return # no linked user, operation is allowed
  665. if self.env['res.users'].sudo(False).check_access_rights('write', raise_exception=False):
  666. error_msg = _('You cannot delete contacts linked to an active user.\n'
  667. 'You should rather archive them after archiving their associated user.\n\n'
  668. 'Linked active users : %(names)s', names=", ".join([u.display_name for u in users]))
  669. action_error = users._action_show()
  670. raise RedirectWarning(error_msg, action_error, _('Go to users'))
  671. else:
  672. raise ValidationError(_('You cannot delete contacts linked to an active user.\n'
  673. 'Ask an administrator to archive their associated user first.\n\n'
  674. 'Linked active users :\n%(names)s', names=", ".join([u.display_name for u in users])))
  675. def _load_records_create(self, vals_list):
  676. partners = super(Partner, self.with_context(_partners_skip_fields_sync=True))._load_records_create(vals_list)
  677. # batch up first part of _fields_sync
  678. # group partners by commercial_partner_id (if not self) and parent_id (if type == contact)
  679. groups = collections.defaultdict(list)
  680. for partner, vals in zip(partners, vals_list):
  681. cp_id = None
  682. if vals.get('parent_id') and partner.commercial_partner_id != partner:
  683. cp_id = partner.commercial_partner_id.id
  684. add_id = None
  685. if partner.parent_id and partner.type == 'contact':
  686. add_id = partner.parent_id.id
  687. groups[(cp_id, add_id)].append(partner.id)
  688. for (cp_id, add_id), children in groups.items():
  689. # values from parents (commercial, regular) written to their common children
  690. to_write = {}
  691. # commercial fields from commercial partner
  692. if cp_id:
  693. to_write = self.browse(cp_id)._update_fields_values(self._commercial_fields())
  694. # address fields from parent
  695. if add_id:
  696. parent = self.browse(add_id)
  697. for f in self._address_fields():
  698. v = parent[f]
  699. if v:
  700. to_write[f] = v.id if isinstance(v, models.BaseModel) else v
  701. if to_write:
  702. self.sudo().browse(children).write(to_write)
  703. # do the second half of _fields_sync the "normal" way
  704. for partner, vals in zip(partners, vals_list):
  705. partner._children_sync(vals)
  706. partner._handle_first_contact_creation()
  707. return partners
  708. def create_company(self):
  709. self.ensure_one()
  710. if self.company_name:
  711. # Create parent company
  712. values = dict(name=self.company_name, is_company=True, vat=self.vat)
  713. values.update(self._update_fields_values(self._address_fields()))
  714. new_company = self.create(values)
  715. # Set new company as my parent
  716. self.write({
  717. 'parent_id': new_company.id,
  718. 'child_ids': [Command.update(partner_id, dict(parent_id=new_company.id)) for partner_id in self.child_ids.ids]
  719. })
  720. return True
  721. def open_commercial_entity(self):
  722. """ Utility method used to add an "Open Company" button in partner views """
  723. self.ensure_one()
  724. return {'type': 'ir.actions.act_window',
  725. 'res_model': 'res.partner',
  726. 'view_mode': 'form',
  727. 'res_id': self.commercial_partner_id.id,
  728. 'target': 'current',
  729. }
  730. def open_parent(self):
  731. """ Utility method used to add an "Open Parent" button in partner views """
  732. self.ensure_one()
  733. address_form_id = self.env.ref('base.view_partner_address_form').id
  734. return {'type': 'ir.actions.act_window',
  735. 'res_model': 'res.partner',
  736. 'view_mode': 'form',
  737. 'views': [(address_form_id, 'form')],
  738. 'res_id': self.parent_id.id,
  739. 'target': 'new',
  740. }
  741. def _get_contact_name(self, partner, name):
  742. return "%s, %s" % (partner.commercial_company_name or partner.sudo().parent_id.name, name)
  743. def _get_name(self):
  744. """ Utility method to allow name_get to be overrided without re-browse the partner """
  745. partner = self
  746. name = partner.name or ''
  747. if partner.company_name or partner.parent_id:
  748. if not name and partner.type in ['invoice', 'delivery', 'other']:
  749. name = dict(self.fields_get(['type'])['type']['selection'])[partner.type]
  750. if not partner.is_company:
  751. name = self._get_contact_name(partner, name)
  752. if self._context.get('show_address_only'):
  753. name = partner._display_address(without_company=True)
  754. if self._context.get('show_address'):
  755. name = name + "\n" + partner._display_address(without_company=True)
  756. name = re.sub(r'\s+\n', '\n', name)
  757. if self._context.get('partner_show_db_id'):
  758. name = "%s (%s)" % (name, partner.id)
  759. if self._context.get('address_inline'):
  760. splitted_names = name.split("\n")
  761. name = ", ".join([n for n in splitted_names if n.strip()])
  762. if self._context.get('show_email') and partner.email:
  763. name = "%s <%s>" % (name, partner.email)
  764. if self._context.get('html_format'):
  765. name = name.replace('\n', '<br/>')
  766. if self._context.get('show_vat') and partner.vat:
  767. name = "%s ‒ %s" % (name, partner.vat)
  768. return name.strip()
  769. def name_get(self):
  770. res = []
  771. for partner in self:
  772. name = partner._get_name()
  773. res.append((partner.id, name))
  774. return res
  775. def _parse_partner_name(self, text):
  776. """ Parse partner name (given by text) in order to find a name and an
  777. email. Supported syntax:
  778. * Raoul <raoul@grosbedon.fr>
  779. * "Raoul le Grand" <raoul@grosbedon.fr>
  780. * Raoul raoul@grosbedon.fr (strange fault tolerant support from
  781. df40926d2a57c101a3e2d221ecfd08fbb4fea30e now supported directly
  782. in 'email_split_tuples';
  783. Otherwise: default, everything is set as the name. Starting from 13.3
  784. returned email will be normalized to have a coherent encoding.
  785. """
  786. name, email = '', ''
  787. split_results = tools.email_split_tuples(text)
  788. if split_results:
  789. name, email = split_results[0]
  790. if email:
  791. email = tools.email_normalize(email)
  792. else:
  793. name, email = text, ''
  794. return name, email
  795. @api.model
  796. def name_create(self, name):
  797. """ Override of orm's name_create method for partners. The purpose is
  798. to handle some basic formats to create partners using the
  799. name_create.
  800. If only an email address is received and that the regex cannot find
  801. a name, the name will have the email value.
  802. If 'force_email' key in context: must find the email address. """
  803. default_type = self._context.get('default_type')
  804. if default_type and default_type not in self._fields['type'].get_values(self.env):
  805. context = dict(self._context)
  806. context.pop('default_type')
  807. self = self.with_context(context)
  808. name, email = self._parse_partner_name(name)
  809. if self._context.get('force_email') and not email:
  810. raise ValidationError(_("Couldn't create contact without email address!"))
  811. create_values = {self._rec_name: name or email}
  812. if email: # keep default_email in context
  813. create_values['email'] = email
  814. partner = self.create(create_values)
  815. return partner.name_get()[0]
  816. @api.model
  817. def _search(self, args, offset=0, limit=None, order=None, count=False, access_rights_uid=None):
  818. """ Override search() to always show inactive children when searching via ``child_of`` operator. The ORM will
  819. always call search() with a simple domain of the form [('parent_id', 'in', [ids])]. """
  820. # a special ``domain`` is set on the ``child_ids`` o2m to bypass this logic, as it uses similar domain expressions
  821. if len(args) == 1 and len(args[0]) == 3 and args[0][:2] == ('parent_id','in') \
  822. and args[0][2] != [False]:
  823. self = self.with_context(active_test=False)
  824. return super(Partner, self)._search(args, offset=offset, limit=limit, order=order,
  825. count=count, access_rights_uid=access_rights_uid)
  826. @api.model
  827. @api.returns('self', lambda value: value.id)
  828. def find_or_create(self, email, assert_valid_email=False):
  829. """ Find a partner with the given ``email`` or use :py:method:`~.name_create`
  830. to create a new one.
  831. :param str email: email-like string, which should contain at least one email,
  832. e.g. ``"Raoul Grosbedon <r.g@grosbedon.fr>"``
  833. :param boolean assert_valid_email: raise if no valid email is found
  834. :return: newly created record
  835. """
  836. if not email:
  837. raise ValueError(_('An email is required for find_or_create to work'))
  838. parsed_name, parsed_email = self._parse_partner_name(email)
  839. if not parsed_email and assert_valid_email:
  840. raise ValueError(_('A valid email is required for find_or_create to work properly.'))
  841. partners = self.search([('email', '=ilike', parsed_email)], limit=1)
  842. if partners:
  843. return partners
  844. create_values = {self._rec_name: parsed_name or parsed_email}
  845. if parsed_email: # keep default_email in context
  846. create_values['email'] = parsed_email
  847. return self.create(create_values)
  848. def _get_gravatar_image(self, email):
  849. email_hash = hashlib.md5(email.lower().encode('utf-8')).hexdigest()
  850. url = "https://www.gravatar.com/avatar/" + email_hash
  851. try:
  852. res = requests.get(url, params={'d': '404', 's': '128'}, timeout=5)
  853. if res.status_code != requests.codes.ok:
  854. return False
  855. except requests.exceptions.ConnectionError as e:
  856. return False
  857. except requests.exceptions.Timeout as e:
  858. return False
  859. return base64.b64encode(res.content)
  860. def _email_send(self, email_from, subject, body, on_error=None):
  861. for partner in self.filtered('email'):
  862. tools.email_send(email_from, [partner.email], subject, body, on_error)
  863. return True
  864. def address_get(self, adr_pref=None):
  865. """ Find contacts/addresses of the right type(s) by doing a depth-first-search
  866. through descendants within company boundaries (stop at entities flagged ``is_company``)
  867. then continuing the search at the ancestors that are within the same company boundaries.
  868. Defaults to partners of type ``'default'`` when the exact type is not found, or to the
  869. provided partner itself if no type ``'default'`` is found either. """
  870. adr_pref = set(adr_pref or [])
  871. if 'contact' not in adr_pref:
  872. adr_pref.add('contact')
  873. result = {}
  874. visited = set()
  875. for partner in self:
  876. current_partner = partner
  877. while current_partner:
  878. to_scan = [current_partner]
  879. # Scan descendants, DFS
  880. while to_scan:
  881. record = to_scan.pop(0)
  882. visited.add(record)
  883. if record.type in adr_pref and not result.get(record.type):
  884. result[record.type] = record.id
  885. if len(result) == len(adr_pref):
  886. return result
  887. to_scan = [c for c in record.child_ids
  888. if c not in visited
  889. if not c.is_company] + to_scan
  890. # Continue scanning at ancestor if current_partner is not a commercial entity
  891. if current_partner.is_company or not current_partner.parent_id:
  892. break
  893. current_partner = current_partner.parent_id
  894. # default to type 'contact' or the partner itself
  895. default = result.get('contact', self.id or False)
  896. for adr_type in adr_pref:
  897. result[adr_type] = result.get(adr_type) or default
  898. return result
  899. @api.model
  900. def view_header_get(self, view_id, view_type):
  901. if self.env.context.get('category_id'):
  902. return _(
  903. 'Partners: %(category)s',
  904. category=self.env['res.partner.category'].browse(self.env.context['category_id']).name,
  905. )
  906. return super().view_header_get(view_id, view_type)
  907. @api.model
  908. @api.returns('self')
  909. def main_partner(self):
  910. ''' Return the main partner '''
  911. return self.env.ref('base.main_partner')
  912. @api.model
  913. def _get_default_address_format(self):
  914. return "%(street)s\n%(street2)s\n%(city)s %(state_code)s %(zip)s\n%(country_name)s"
  915. @api.model
  916. def _get_address_format(self):
  917. return self.country_id.address_format or self._get_default_address_format()
  918. def _prepare_display_address(self, without_company=False):
  919. # get the information that will be injected into the display format
  920. # get the address format
  921. address_format = self._get_address_format()
  922. args = defaultdict(str, {
  923. 'state_code': self.state_id.code or '',
  924. 'state_name': self.state_id.name or '',
  925. 'country_code': self.country_id.code or '',
  926. 'country_name': self._get_country_name(),
  927. 'company_name': self.commercial_company_name or '',
  928. })
  929. for field in self._formatting_address_fields():
  930. args[field] = getattr(self, field) or ''
  931. if without_company:
  932. args['company_name'] = ''
  933. elif self.commercial_company_name:
  934. address_format = '%(company_name)s\n' + address_format
  935. return address_format, args
  936. def _display_address(self, without_company=False):
  937. '''
  938. The purpose of this function is to build and return an address formatted accordingly to the
  939. standards of the country where it belongs.
  940. :param without_company: if address contains company
  941. :returns: the address formatted in a display that fit its country habits (or the default ones
  942. if not country is specified)
  943. :rtype: string
  944. '''
  945. address_format, args = self._prepare_display_address(without_company)
  946. return address_format % args
  947. def _display_address_depends(self):
  948. # field dependencies of method _display_address()
  949. return self._formatting_address_fields() + [
  950. 'country_id', 'company_name', 'state_id',
  951. ]
  952. @api.model
  953. def get_import_templates(self):
  954. return [{
  955. 'label': _('Import Template for Customers'),
  956. 'template': '/base/static/xls/res_partner.xlsx'
  957. }]
  958. @api.model
  959. def _check_import_consistency(self, vals_list):
  960. """
  961. The values created by an import are generated by a name search, field by field.
  962. As a result there is no check that the field values are consistent with each others.
  963. We check that if the state is given a value, it does belong to the given country, or we remove it.
  964. """
  965. States = self.env['res.country.state']
  966. states_ids = {vals['state_id'] for vals in vals_list if vals.get('state_id')}
  967. state_to_country = States.search([('id', 'in', list(states_ids))]).read(['country_id'])
  968. for vals in vals_list:
  969. if vals.get('state_id'):
  970. country_id = next(c['country_id'][0] for c in state_to_country if c['id'] == vals.get('state_id'))
  971. state = States.browse(vals['state_id'])
  972. if state.country_id.id != country_id:
  973. state_domain = [('code', '=', state.code),
  974. ('country_id', '=', country_id)]
  975. state = States.search(state_domain, limit=1)
  976. vals['state_id'] = state.id # replace state or remove it if not found
  977. def _get_country_name(self):
  978. return self.country_id.name or ''
  979. class ResPartnerIndustry(models.Model):
  980. _description = 'Industry'
  981. _name = "res.partner.industry"
  982. _order = "name"
  983. name = fields.Char('Name', translate=True)
  984. full_name = fields.Char('Full Name', translate=True)
  985. active = fields.Boolean('Active', default=True)