##############################################################################
import math
-import os
+import openerp
from osv import osv, fields
+from openerp import SUPERUSER_ID
import re
import tools
from tools.translate import _
import logging
import pooler
+import pytz
+from lxml import etree
+
+class format_address(object):
+ def fields_view_get_address(self, cr, uid, arch, context={}):
+ user_obj = self.pool.get('res.users')
+ fmt = user_obj.browse(cr, SUPERUSER_ID, uid, context).company_id.country_id
+ fmt = fmt and fmt.address_format
+ layouts = {
+ '%(city)s %(state_code)s\n%(zip)s': """
+ <div class="address_format">
+ <field name="city" placeholder="City" style="width: 50%%"/>
+ <field name="state_id" class="oe_no_button" placeholder="State" style="width: 47%%" options='{"no_open": true}'/>
+ <br/>
+ <field name="zip" placeholder="ZIP"/>
+ </div>
+ """,
+ '%(zip)s %(city)s': """
+ <div class="address_format">
+ <field name="zip" placeholder="ZIP" style="width: 40%%"/>
+ <field name="city" placeholder="City" style="width: 57%%"/>
+ <br/>
+ <field name="state_id" class="oe_no_button" placeholder="State" options='{"no_open": true}'/>
+ </div>
+ """,
+ '%(city)s\n%(state_name)s\n%(zip)s': """
+ <div class="address_format">
+ <field name="city" placeholder="City"/>
+ <field name="state_id" class="oe_no_button" placeholder="State" options='{"no_open": true}'/>
+ <field name="zip" placeholder="ZIP"/>
+ </div>
+ """
+ }
+ for k,v in layouts.items():
+ if fmt and (k in fmt):
+ doc = etree.fromstring(arch)
+ for node in doc.xpath("//div[@class='address_format']"):
+ tree = etree.fromstring(v)
+ node.getparent().replace(node, tree)
+ arch = etree.tostring(doc)
+ break
+ return arch
-class res_payterm(osv.osv):
- _description = 'Payment term'
- _name = 'res.payterm'
- _order = 'name'
- _columns = {
- 'name': fields.char('Payment Term (short name)', size=64),
- }
+
+def _tz_get(self,cr,uid, context=None):
+ return [(x, x) for x in pytz.all_timezones]
class res_partner_category(osv.osv):
return super(res_partner_category, self).name_get(cr, uid, ids, context=context)
if isinstance(ids, (int, long)):
ids = [ids]
- reads = self.read(cr, uid, ids, ['name','parent_id'], context=context)
+ reads = self.read(cr, uid, ids, ['name', 'parent_id'], context=context)
res = []
for record in reads:
name = record['name']
if record['parent_id']:
- name = record['parent_id'][1]+' / '+name
+ name = record['parent_id'][1] + ' / ' + name
res.append((record['id'], name))
return res
def name_search(self, cr, uid, name, args=None, operator='ilike', context=None, limit=100):
if not args:
- args=[]
+ args = []
if not context:
- context={}
+ context = {}
if name:
# Be sure name_search is symetric to name_get
name = name.split(' / ')[-1]
res = self.name_get(cr, uid, ids, context=context)
return dict(res)
- _description='Partner Categories'
+ _description = 'Partner Categories'
_name = 'res.partner.category'
_columns = {
'name': fields.char('Category Name', required=True, size=64, translate=True),
'parent_id': fields.many2one('res.partner.category', 'Parent Category', select=True, ondelete='cascade'),
'complete_name': fields.function(_name_get_fnc, type="char", string='Full Name'),
'child_ids': fields.one2many('res.partner.category', 'parent_id', 'Child Categories'),
- 'active' : fields.boolean('Active', help="The active field allows you to hide the category without removing it."),
- 'parent_left' : fields.integer('Left parent', select=True),
- 'parent_right' : fields.integer('Right parent', select=True),
+ 'active': fields.boolean('Active', help="The active field allows you to hide the category without removing it."),
+ 'parent_left': fields.integer('Left parent', select=True),
+ 'parent_right': fields.integer('Right parent', select=True),
'partner_ids': fields.many2many('res.partner', id1='category_id', id2='partner_id', string='Partners'),
}
_constraints = [
(osv.osv._check_recursion, 'Error ! You can not create recursive categories.', ['parent_id'])
]
_defaults = {
- 'active' : lambda *a: 1,
+ 'active': 1,
}
_parent_store = True
_parent_order = 'name'
_columns = {
'name': fields.char('Title', required=True, size=46, translate=True),
'shortcut': fields.char('Abbreviation', size=16, translate=True),
- 'domain': fields.selection([('partner','Partner'),('contact','Contact')], 'Domain', required=True, size=24)
+ 'domain': fields.selection([('partner', 'Partner'), ('contact', 'Contact')], 'Domain', required=True, size=24)
}
_defaults = {
'domain': 'contact',
lang_pool = self.pool.get('res.lang')
ids = lang_pool.search(cr, uid, [], context=context)
res = lang_pool.read(cr, uid, ids, ['code', 'name'], context)
- return [(r['code'], r['name']) for r in res] + [('','')]
+ return [(r['code'], r['name']) for r in res]
POSTAL_ADDRESS_FIELDS = ('street', 'street2', 'zip', 'city', 'state_id', 'country_id')
ADDRESS_FIELDS = POSTAL_ADDRESS_FIELDS + ('email', 'phone', 'fax', 'mobile', 'website', 'ref', 'lang')
-class res_partner(osv.osv):
- _description='Partner'
+class res_partner(osv.osv, format_address):
+ _description = 'Partner'
_name = "res.partner"
def _address_display(self, cr, uid, ids, name, args, context=None):
- res={}
+ res = {}
for partner in self.browse(cr, uid, ids, context=context):
- res[partner.id] =self._display_address(cr, uid, partner, context=context)
+ res[partner.id] = self._display_address(cr, uid, partner, context=context)
return res
def _get_image(self, cr, uid, ids, name, args, context=None):
result = dict.fromkeys(ids, False)
for obj in self.browse(cr, uid, ids, context=context):
- resized_image_dict = tools.get_resized_images(obj.image)
- result[obj.id] = {
- 'image_medium': resized_image_dict['image_medium'],
- 'image_small': resized_image_dict['image_small'],
- }
+ result[obj.id] = tools.image_get_resized_images(obj.image)
return result
-
+
def _set_image(self, cr, uid, id, name, value, args, context=None):
- return self.write(cr, uid, [id], {'image': tools.resize_image_big(value)}, context=context)
-
- def onchange_image(self, cr, uid, ids, value, context=None):
- return {'value': tools.get_resized_images(value)}
+ return self.write(cr, uid, [id], {'image': tools.image_resize_image_big(value)}, context=context)
_order = "name"
_columns = {
'name': fields.char('Name', size=128, required=True, select=True),
'date': fields.date('Date', select=1),
- 'title': fields.many2one('res.partner.title','Title'),
- 'parent_id': fields.many2one('res.partner','Company'),
+ 'title': fields.many2one('res.partner.title', 'Title'),
+ 'parent_id': fields.many2one('res.partner', 'Related Company'),
'child_ids': fields.one2many('res.partner', 'parent_id', 'Contacts'),
'ref': fields.char('Reference', size=64, select=1),
- 'lang': fields.selection(_lang_get, 'Language', help="If the selected language is loaded in the system, all documents related to this partner will be printed in this language. If not, it will be english."),
- 'user_id': fields.many2one('res.users', 'Salesperson', help='The internal user that is in charge of communicating with this partner if any.'),
- 'vat': fields.char('VAT',size=32 ,help="Value Added Tax number. Check the box if the partner is subjected to the VAT. Used by the VAT legal statement."),
+ 'lang': fields.selection(_lang_get, 'Language',
+ help="If the selected language is loaded in the system, all documents related to this contact will be printed in this language. If not, it will be English."),
+ 'tz': fields.selection(_tz_get, 'Timezone', size=64,
+ help="The partner's timezone, used to output proper date and time values inside printed reports. "
+ "It is important to set a value for this field. You should use the same timezone "
+ "that is otherwise used to pick and render date and time values: your computer's timezone."),
+ 'user_id': fields.many2one('res.users', 'Salesperson', help='The internal user that is in charge of communicating with this contact if any.'),
+ 'vat': fields.char('TIN', size=32, help="Tax Identification Number. Check the box if this contact is subjected to taxes. Used by the some of the legal statements."),
'bank_ids': fields.one2many('res.partner.bank', 'partner_id', 'Banks'),
- 'website': fields.char('Website',size=64, help="Website of Partner or Company"),
+ 'website': fields.char('Website', size=64, help="Website of Partner or Company"),
'comment': fields.text('Notes'),
- 'address': fields.one2many('res.partner.address', 'partner_id', 'Contacts'), # should be removed in version 7, but kept until then for backward compatibility
+ 'address': fields.one2many('res.partner.address', 'partner_id', 'Addresses',
+ deprecated="The address information is now directly stored on each Partner record. "\
+ "Multiple contacts with their own address can be added via the child_ids relationship. "\
+ "This field will be removed as of OpenERP 7.1."),
'category_id': fields.many2many('res.partner.category', id1='partner_id', id2='category_id', string='Tags'),
'credit_limit': fields.float(string='Credit Limit'),
'ean13': fields.char('EAN13', size=13),
'active': fields.boolean('Active'),
- 'customer': fields.boolean('Customer', help="Check this box if the partner is a customer."),
- 'supplier': fields.boolean('Supplier', help="Check this box if the partner is a supplier. If it's not checked, purchase people will not see it when encoding a purchase order."),
- 'employee': fields.boolean('Employee', help="Check this box if the partner is an Employee."),
+ 'customer': fields.boolean('Customer', help="Check this box if this contact is a customer."),
+ 'supplier': fields.boolean('Supplier', help="Check this box if this contact is a supplier. If it's not checked, purchase people will not see it when encoding a purchase order."),
+ 'employee': fields.boolean('Employee', help="Check this box if this contact is an Employee."),
'function': fields.char('Job Position', size=128),
- 'type': fields.selection( [('default','Default'),('invoice','Invoice'),
- ('delivery','Delivery'), ('contact','Contact'),
- ('other','Other')],
- 'Address Type', help="Used to select automatically the right address according to the context in sales and purchases documents."),
+ 'type': fields.selection([('default', 'Default'), ('invoice', 'Invoice'),
+ ('delivery', 'Delivery'), ('contact', 'Contact'),
+ ('other', 'Other')], 'Address Type',
+ help="Used to select automatically the right address according to the context in sales and purchases documents."),
'street': fields.char('Street', size=128),
'street2': fields.char('Street2', size=128),
'zip': fields.char('Zip', change_default=True, size=24),
'city': fields.char('City', size=128),
- 'state_id': fields.many2one("res.country.state", 'State', domain="[('country_id','=',country_id)]"),
+ 'state_id': fields.many2one("res.country.state", 'State'),
'country_id': fields.many2one('res.country', 'Country'),
- 'country': fields.related('country_id', type='many2one', relation='res.country', string='Country'), # for backward compatibility
+ 'country': fields.related('country_id', type='many2one', relation='res.country', string='Country',
+ deprecated="This field will be removed as of OpenERP 7.1, use country_id instead"),
'email': fields.char('Email', size=240),
'phone': fields.char('Phone', size=64),
'fax': fields.char('Fax', size=64),
'mobile': fields.char('Mobile', size=64),
'birthdate': fields.char('Birthdate', size=64),
- 'is_company': fields.boolean('Company', help="Check if the contact is a company, otherwise it is a person"),
+ 'is_company': fields.boolean('Is a Company', help="Check if the contact is a company, otherwise it is a person"),
'use_parent_address': fields.boolean('Use Company Address', help="Select this if you want to set company's address information for this contact"),
+ # image: all image fields are base64 encoded and PIL-supported
'image': fields.binary("Image",
- help="This field holds the image used as avatar for the "\
- "partner. The image is base64 encoded, and PIL-supported. "\
- "It is limited to a 1024x1024 px image."),
+ help="This field holds the image used as avatar for this contact, limited to 1024x1024px"),
'image_medium': fields.function(_get_image, fnct_inv=_set_image,
string="Medium-sized image", type="binary", multi="_get_image",
- store = {
+ store={
'res.partner': (lambda self, cr, uid, ids, c={}: ids, ['image'], 10),
},
- help="Medium-sized image of the partner. It is automatically "\
- "resized as a 180x180 px image, with aspect ratio preserved. "\
+ help="Medium-sized image of this contact. It is automatically "\
+ "resized as a 128x128px image, with aspect ratio preserved. "\
"Use this field in form views or some kanban views."),
'image_small': fields.function(_get_image, fnct_inv=_set_image,
string="Small-sized image", type="binary", multi="_get_image",
- store = {
+ store={
'res.partner': (lambda self, cr, uid, ids, c={}: ids, ['image'], 10),
},
- help="Small-sized image of the partner. It is automatically "\
- "resized as a 50x50 px image, with aspect ratio preserved. "\
+ help="Small-sized image of this contact. It is automatically "\
+ "resized as a 64x64px image, with aspect ratio preserved. "\
"Use this field anywhere a small image is required."),
'company_id': fields.many2one('res.company', 'Company', select=1),
'color': fields.integer('Color Index'),
+ 'user_ids': fields.one2many('res.users', 'partner_id', 'Users'),
'contact_address': fields.function(_address_display, type='char', string='Complete Address'),
}
return [context['category_id']]
return False
- def _get_default_image(self, cr, uid, is_company, context=None):
+ def _get_default_image(self, cr, uid, is_company, context=None, colorize=False):
if is_company:
- image_path = os.path.join( tools.config['root_path'], 'addons', 'base', 'res', 'company_icon.png')
+ image = open(openerp.modules.get_module_resource('base', 'static/src/img', 'company_image.png')).read()
else:
- image_path = os.path.join( tools.config['root_path'], 'addons', 'base', 'res', 'photo.png')
- return tools.resize_image_big(open(image_path, 'rb').read().encode('base64'))
+ image = tools.image_colorize(open(openerp.modules.get_module_resource('base', 'static/src/img', 'avatar.png')).read())
+ return tools.image_resize_image_big(image.encode('base64'))
+
+ def fields_view_get(self, cr, user, view_id=None, view_type='form', context=None, toolbar=False, submenu=False):
+ if (not view_id) and (view_type=='form') and context and context.get('force_email', False):
+ view_id = self.pool.get('ir.model.data').get_object_reference(cr, user, 'base', 'view_partner_simple_form')[1]
+ res = super(res_partner,self).fields_view_get(cr, user, view_id, view_type, context, toolbar=toolbar, submenu=submenu)
+ if view_type == 'form':
+ res['arch'] = self.fields_view_get_address(cr, user, res['arch'], context=context)
+ return res
_defaults = {
'active': True,
+ 'lang': lambda self, cr, uid, ctx: ctx.get('lang', 'en_US'),
+ 'tz': lambda self, cr, uid, ctx: ctx.get('tz', False),
'customer': True,
'category_id': _default_category,
- 'company_id': lambda s,cr,uid,c: s.pool.get('res.company')._company_default_get(cr, uid, 'res.partner', context=c),
+ 'company_id': lambda self, cr, uid, ctx: self.pool.get('res.company')._company_default_get(cr, uid, 'res.partner', context=ctx),
'color': 0,
'is_company': False,
'type': 'default',
'use_parent_address': True,
- 'image': lambda self, cr, uid, context: self._get_default_image(cr, uid, False, context),
+ 'image': lambda self, cr, uid, ctx: self._get_default_image(cr, uid, ctx.get('default_is_company', False), ctx),
}
def copy(self, cr, uid, id, default=None, context=None):
if default is None:
default = {}
name = self.read(cr, uid, [id], ['name'], context)[0]['name']
- default.update({'name': _('%s (copy)')%(name)})
+ default.update({'name': _('%s (copy)') % (name)})
return super(res_partner, self).copy(cr, uid, id, default, context)
def onchange_type(self, cr, uid, ids, is_company, context=None):
# get value as for an onchange on the image
- value = self.onchange_image(cr, uid, ids, self._get_default_image(cr, uid, is_company, context), context=context)['value']
+ value = tools.image_get_resized_images(self._get_default_image(cr, uid, is_company, context), return_big=True, return_medium=False, return_small=False)
value['title'] = False
if is_company:
value['parent_id'] = False
return {'value': dict((key, value_or_id(parent[key])) for key in ADDRESS_FIELDS)}
return {}
+ def onchange_state(self, cr, uid, ids, state_id, context=None):
+ if state_id:
+ country_id = self.pool.get('res.country.state').browse(cr, uid, state_id, context).country_id.id
+ return {'value':{'country_id':country_id}}
+ return {}
+
def _check_ean_key(self, cr, uid, ids, context=None):
for partner_o in pooler.get_pool(cr.dbname).get('res.partner').read(cr, uid, ids, ['ean13',]):
thisean=partner_o['ean13']
domain_siblings = [('parent_id', '=', vals['parent_id']), ('use_parent_address', '=', True)]
update_ids = [vals['parent_id']] + self.search(cr, uid, domain_siblings, context=context)
self.update_address(cr, uid, update_ids, vals, context)
- if 'image' not in vals :
- image_value = self._get_default_image(cr, uid, vals.get('is_company', False) or context.get('default_is_company'), context)
- vals.update(self.onchange_image(cr, uid, [], image_value, context=context)['value'])
return super(res_partner,self).create(cr, uid, vals, context=context)
def update_address(self, cr, uid, ids, vals, context=None):
addr_vals = dict((key, vals[key]) for key in POSTAL_ADDRESS_FIELDS if vals.get(key))
- return super(res_partner, self).write(cr, uid, ids, addr_vals, context)
+ if addr_vals:
+ return super(res_partner, self).write(cr, uid, ids, addr_vals, context)
def name_get(self, cr, uid, ids, context=None):
if context is None:
res.append((record.id, name))
return res
+ def _parse_partner_name(self, text, context=None):
+ """ Supported syntax:
+ - 'Raoul <raoul@grosbedon.fr>': will find name and email address
+ - otherwise: default, everything is set as the name """
+ match = re.search(r'([^\s,<@]+@[^>\s,]+)', text)
+ if match:
+ email = match.group(1)
+ name = text[:text.index(email)].replace('"','').replace('<','').strip()
+ else:
+ name, email = text, ''
+ return name, email
+
def name_create(self, cr, uid, name, context=None):
""" Override of orm's name_create method for partners. The purpose is
to handle some basic formats to create partners using the
name_create.
- Supported syntax:
- - 'raoul@grosbedon.fr': create a partner with name raoul@grosbedon.fr
- and sets its email to raoul@grosbedon.fr
- - 'Raoul Grosbedon <raoul@grosbedon.fr>': create a partner with name
- Raoul Grosbedon, and set its email to raoul@grosbedon.fr
- - anything else: fall back on the default name_create
- Regex :
- - ([a-zA-Z0-9._%-]+@[a-zA-Z0-9_-]+\.[a-zA-Z0-9._]{1,8}): raoul@grosbedon.fr
- - ([\w\s.\\-]+)[\<]([a-zA-Z0-9._%-]+@[a-zA-Z0-9_-]+\.[a-zA-Z0-9._]{1,8})[\>]:
- Raoul Grosbedon, raoul@grosbedon.fr
- """
- contact_regex = re.compile('([\w\s.\\-]+)[\<]([a-zA-Z0-9._%-]+@[a-zA-Z0-9_-]+\.[a-zA-Z0-9._]{1,8})[\>]')
- email_regex = re.compile('([a-zA-Z0-9._%-]+@[a-zA-Z0-9_-]+\.[a-zA-Z0-9._]{1,8})')
- contact_regex_res = contact_regex.findall(name)
- email_regex_res = email_regex.findall(name)
- if contact_regex_res:
- name = contact_regex_res[0][0].rstrip(' ') # remove extra spaces on the right
- email = contact_regex_res[0][1]
- rec_id = self.create(cr, uid, {self._rec_name: name, 'email': email}, context);
- return self.name_get(cr, uid, [rec_id], context)[0]
- elif email_regex:
- email = '%s' % (email_regex_res[0])
- rec_id = self.create(cr, uid, {self._rec_name: email, 'email': email}, context);
- return self.name_get(cr, uid, [rec_id], context)[0]
- else:
- return super(res_partner, self).create(cr, uid, name, context)
+ If only an email address is received and that the regex cannot find
+ a name, the name will have the email value.
+ If 'force_email' key in context: must find the email address. """
+ if context is None:
+ context = {}
+ name, email = self._parse_partner_name(name, context=context)
+ if context.get('force_email') and not email:
+ raise osv.except_osv(_('Warning'), _("Couldn't create contact without email address !"))
+ if not name and email:
+ name = email
+ rec_id = self.create(cr, uid, {self._rec_name: name or email, 'email': email or False}, context=context)
+ return self.name_get(cr, uid, [rec_id], context)[0]
def name_search(self, cr, uid, name, args=None, operator='ilike', context=None, limit=100):
if not args:
return self.name_get(cr, uid, ids, context)
return super(res_partner,self).name_search(cr, uid, name, args, operator=operator, context=context, limit=limit)
+ def find_or_create(self, cr, uid, email, context=None):
+ """ Find a partner with the given ``email`` or use :py:method:`~.name_create`
+ to create one
+
+ :param str email: email-like string, which should contain at least one email,
+ e.g. ``"Raoul Grosbedon <r.g@grosbedon.fr>"``"""
+ assert email, 'an email is required for find_or_create to work'
+ emails = tools.email_split(email)
+ if emails:
+ email = emails[0]
+ ids = self.search(cr, uid, [('email','ilike',email)], context=context)
+ if not ids:
+ return self.name_create(cr, uid, email, context=context)[0]
+ return ids[0]
+
def _email_send(self, cr, uid, ids, email_from, subject, body, on_error=None):
partners = self.browse(cr, uid, ids)
for partner in partners:
# get the information that will be injected into the display format
# get the address format
address_format = address.country_id and address.country_id.address_format or \
- '%(company_name)s\n%(street)s\n%(street2)s\n%(city)s,%(state_code)s %(zip)s'
+ "%(street)s\n%(street2)s\n%(city)s %(state_code)s %(zip)s\n%(country_name)s"
args = {
'state_code': address.state_id and address.state_id.code or '',
'state_name': address.state_id and address.state_id.name or '',
args[field] = getattr(address, field) or ''
if without_company:
args['company_name'] = ''
+ elif address.parent_id:
+ address_format = '%(company_name)s\n' + address_format
return address_format % args
-
-
# res.partner.address is deprecated; it is still there for backward compability only and will be removed in next version
class res_partner_address(osv.osv):
_table = "res_partner"