[FIX] res.partner.address: name_search must treat limit=0|None as unlimited
[odoo/odoo.git] / openerp / addons / base / res / res_partner.py
1 # -*- coding: utf-8 -*-
2 ##############################################################################
3 #
4 #    OpenERP, Open Source Management Solution
5 #    Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>).
6 #
7 #    This program is free software: you can redistribute it and/or modify
8 #    it under the terms of the GNU Affero General Public License as
9 #    published by the Free Software Foundation, either version 3 of the
10 #    License, or (at your option) any later version.
11 #
12 #    This program is distributed in the hope that it will be useful,
13 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
14 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 #    GNU Affero General Public License for more details.
16 #
17 #    You should have received a copy of the GNU Affero General Public License
18 #    along with this program.  If not, see <http://www.gnu.org/licenses/>.
19 #
20 ##############################################################################
21
22 import math
23
24 from osv import fields,osv
25 import tools
26 import pooler
27 from tools.translate import _
28
29 class res_payterm(osv.osv):
30     _description = 'Payment term'
31     _name = 'res.payterm'
32     _order = 'name'
33     _columns = {
34         'name': fields.char('Payment Term (short name)', size=64),
35     }
36 res_payterm()
37
38 class res_partner_category(osv.osv):
39
40     def name_get(self, cr, uid, ids, context=None):
41         """Return the categories' display name, including their direct
42            parent by default.
43
44         :param dict context: the ``partner_category_display`` key can be
45                              used to select the short version of the
46                              category name (without the direct parent),
47                              when set to ``'short'``. The default is
48                              the long version.""" 
49         if context is None:
50             context = {}
51         if context.get('partner_category_display') == 'short':
52             return super(res_partner_category, self).name_get(cr, uid, ids, context=context)
53         reads = self.read(cr, uid, ids, ['name','parent_id'], context=context)
54         res = []
55         for record in reads:
56             name = record['name']
57             if record['parent_id']:
58                 name = record['parent_id'][1]+' / '+name
59             res.append((record['id'], name))
60         return res
61
62     def name_search(self, cr, uid, name, args=None, operator='ilike', context=None, limit=100):
63         if not args:
64             args=[]
65         if not context:
66             context={}
67         if name:
68             # Be sure name_search is symetric to name_get
69             name = name.split(' / ')[-1]
70             ids = self.search(cr, uid, [('name', operator, name)] + args, limit=limit, context=context)
71         else:
72             ids = self.search(cr, uid, args, limit=limit, context=context)
73         return self.name_get(cr, uid, ids, context)
74
75
76     def _name_get_fnc(self, cr, uid, ids, prop, unknow_none, context=None):
77         res = self.name_get(cr, uid, ids, context=context)
78         return dict(res)
79
80     _description='Partner Categories'
81     _name = 'res.partner.category'
82     _columns = {
83         'name': fields.char('Category Name', required=True, size=64, translate=True),
84         'parent_id': fields.many2one('res.partner.category', 'Parent Category', select=True, ondelete='cascade'),
85         'complete_name': fields.function(_name_get_fnc, type="char", string='Full Name'),
86         'child_ids': fields.one2many('res.partner.category', 'parent_id', 'Child Categories'),
87         'active' : fields.boolean('Active', help="The active field allows you to hide the category without removing it."),
88         'parent_left' : fields.integer('Left parent', select=True),
89         'parent_right' : fields.integer('Right parent', select=True),
90         'partner_ids': fields.many2many('res.partner', 'res_partner_category_rel', 'category_id', 'partner_id', 'Partners'),
91     }
92     _constraints = [
93         (osv.osv._check_recursion, 'Error ! You can not create recursive categories.', ['parent_id'])
94     ]
95     _defaults = {
96         'active' : lambda *a: 1,
97     }
98     _parent_store = True
99     _parent_order = 'name'
100     _order = 'parent_left'
101 res_partner_category()
102
103 class res_partner_title(osv.osv):
104     _name = 'res.partner.title'
105     _columns = {
106         'name': fields.char('Title', required=True, size=46, translate=True),
107         'shortcut': fields.char('Shortcut', required=True, size=16, translate=True),
108         'domain': fields.selection([('partner','Partner'),('contact','Contact')], 'Domain', required=True, size=24)
109     }
110     _order = 'name'
111 res_partner_title()
112
113 def _lang_get(self, cr, uid, context=None):
114     obj = self.pool.get('res.lang')
115     ids = obj.search(cr, uid, [], context=context)
116     res = obj.read(cr, uid, ids, ['code', 'name'], context)
117     return [(r['code'], r['name']) for r in res] + [('','')]
118
119
120 class res_partner(osv.osv):
121     _description='Partner'
122     _name = "res.partner"
123     _order = "name"
124     _columns = {
125         'name': fields.char('Name', size=128, required=True, select=True),
126         'date': fields.date('Date', select=1),
127         'title': fields.many2one('res.partner.title','Partner Firm'),
128         'parent_id': fields.many2one('res.partner','Parent Partner'),
129         'child_ids': fields.one2many('res.partner', 'parent_id', 'Partner Ref.'),
130         'ref': fields.char('Reference', size=64, select=1),
131         '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."),
132         'user_id': fields.many2one('res.users', 'Salesman', help='The internal user that is in charge of communicating with this partner if any.'),
133         '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."),
134         'bank_ids': fields.one2many('res.partner.bank', 'partner_id', 'Banks'),
135         'website': fields.char('Website',size=64, help="Website of Partner."),
136         'comment': fields.text('Notes'),
137         'address': fields.one2many('res.partner.address', 'partner_id', 'Contacts'),
138         'category_id': fields.many2many('res.partner.category', 'res_partner_category_rel', 'partner_id', 'category_id', 'Categories'),
139         'events': fields.one2many('res.partner.event', 'partner_id', 'Events'),
140         'credit_limit': fields.float(string='Credit Limit'),
141         'ean13': fields.char('EAN13', size=13),
142         'active': fields.boolean('Active'),
143         'customer': fields.boolean('Customer', help="Check this box if the partner is a customer."),
144         '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."),
145         'city': fields.related('address', 'city', type='char', string='City'),
146         'function': fields.related('address', 'function', type='char', string='function'),
147         'subname': fields.related('address', 'name', type='char', string='Contact Name'),
148         'phone': fields.related('address', 'phone', type='char', string='Phone'),
149         'mobile': fields.related('address', 'mobile', type='char', string='Mobile'),
150         'country': fields.related('address', 'country_id', type='many2one', relation='res.country', string='Country'),
151         'employee': fields.boolean('Employee', help="Check this box if the partner is an Employee."),
152         'email': fields.related('address', 'email', type='char', size=240, string='E-mail'),
153         'company_id': fields.many2one('res.company', 'Company', select=1),
154         'color': fields.integer('Color Index'),
155     }
156     def _default_category(self, cr, uid, context=None):
157         if context is None:
158             context = {}
159         if 'category_id' in context and context['category_id']:
160             return [context['category_id']]
161         return []
162
163     _defaults = {
164         'active': lambda *a: 1,
165         'customer': lambda *a: 1,
166         'category_id': _default_category,
167         'company_id': lambda s,cr,uid,c: s.pool.get('res.company')._company_default_get(cr, uid, 'res.partner', context=c),
168         'color': 0,
169     }
170
171     def copy(self, cr, uid, id, default=None, context=None):
172         if default is None:
173             default = {}
174         name = self.read(cr, uid, [id], ['name'], context)[0]['name']
175         default.update({'name': name+ _(' (copy)'), 'events':[]})
176         return super(res_partner, self).copy(cr, uid, id, default, context)
177
178     def do_share(self, cr, uid, ids, *args):
179         return True
180
181     def _check_ean_key(self, cr, uid, ids, context=None):
182         for partner_o in pooler.get_pool(cr.dbname).get('res.partner').read(cr, uid, ids, ['ean13',]):
183             thisean=partner_o['ean13']
184             if thisean and thisean!='':
185                 if len(thisean)!=13:
186                     return False
187                 sum=0
188                 for i in range(12):
189                     if not (i % 2):
190                         sum+=int(thisean[i])
191                     else:
192                         sum+=3*int(thisean[i])
193                 if math.ceil(sum/10.0)*10-sum!=int(thisean[12]):
194                     return False
195         return True
196
197 #   _constraints = [(_check_ean_key, 'Error: Invalid ean code', ['ean13'])]
198
199     def name_get(self, cr, uid, ids, context=None):
200         if context is None:
201             context = {}
202         if not len(ids):
203             return []
204         if context.get('show_ref'):
205             rec_name = 'ref'
206         else:
207             rec_name = 'name'
208
209         res = [(r['id'], r[rec_name]) for r in self.read(cr, uid, ids, [rec_name], context)]
210         return res
211
212     def name_search(self, cr, uid, name, args=None, operator='ilike', context=None, limit=100):
213         if not args:
214             args = []
215         # short-circuit ref match when possible
216         if name and operator in ('=', 'ilike', '=ilike', 'like'):
217             ids = self.search(cr, uid, [('ref', '=', name)] + args, limit=limit, context=context)
218             if ids:
219                 return self.name_get(cr, uid, ids, context)
220         return super(res_partner,self).name_search(cr, uid, name, args, operator=operator, context=context, limit=limit)
221
222     def _email_send(self, cr, uid, ids, email_from, subject, body, on_error=None):
223         partners = self.browse(cr, uid, ids)
224         for partner in partners:
225             if len(partner.address):
226                 if partner.address[0].email:
227                     tools.email_send(email_from, [partner.address[0].email], subject, body, on_error)
228         return True
229
230     def email_send(self, cr, uid, ids, email_from, subject, body, on_error=''):
231         while len(ids):
232             self.pool.get('ir.cron').create(cr, uid, {
233                 'name': 'Send Partner Emails',
234                 'user_id': uid,
235 #               'nextcall': False,
236                 'model': 'res.partner',
237                 'function': '_email_send',
238                 'args': repr([ids[:16], email_from, subject, body, on_error])
239             })
240             ids = ids[16:]
241         return True
242
243     def address_get(self, cr, uid, ids, adr_pref=None):
244         if adr_pref is None:
245             adr_pref = ['default']
246         address_obj = self.pool.get('res.partner.address')
247         address_ids = address_obj.search(cr, uid, [('partner_id', 'in', ids)])
248         address_rec = address_obj.read(cr, uid, address_ids, ['type'])
249         res = list((addr['type'],addr['id']) for addr in address_rec)
250         adr = dict(res)
251         # get the id of the (first) default address if there is one,
252         # otherwise get the id of the first address in the list
253         if res:
254             default_address = adr.get('default', res[0][1])
255         else:
256             default_address = False
257         result = {}
258         for a in adr_pref:
259             result[a] = adr.get(a, default_address)
260         return result
261
262     def gen_next_ref(self, cr, uid, ids):
263         if len(ids) != 1:
264             return True
265
266         # compute the next number ref
267         cr.execute("select ref from res_partner where ref is not null order by char_length(ref) desc, ref desc limit 1")
268         res = cr.dictfetchall()
269         ref = res and res[0]['ref'] or '0'
270         try:
271             nextref = int(ref)+1
272         except:
273             raise osv.except_osv(_('Warning'), _("Couldn't generate the next id because some partners have an alphabetic id !"))
274
275         # update the current partner
276         cr.execute("update res_partner set ref=%s where id=%s", (nextref, ids[0]))
277         return True
278
279     def view_header_get(self, cr, uid, view_id, view_type, context):
280         res = super(res_partner, self).view_header_get(cr, uid, view_id, view_type, context)
281         if res: return res
282         if (not context.get('category_id', False)):
283             return False
284         return _('Partners: ')+self.pool.get('res.partner.category').browse(cr, uid, context['category_id'], context).name
285     def main_partner(self, cr, uid):
286         ''' Return the id of the main partner
287         '''
288         model_data = self.pool.get('ir.model.data')
289         return model_data.browse(
290             cr, uid,
291             model_data.search(cr, uid, [('module','=','base'),
292                                         ('name','=','main_partner')])[0],
293             ).res_id
294 res_partner()
295
296 class res_partner_address(osv.osv):
297     _description ='Partner Addresses'
298     _name = 'res.partner.address'
299     _order = 'type, name'
300     _columns = {
301         'partner_id': fields.many2one('res.partner', 'Partner Name', ondelete='set null', select=True, help="Keep empty for a private address, not related to partner."),
302         '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."),
303         'function': fields.char('Function', size=128),
304         'title': fields.many2one('res.partner.title','Title'),
305         'name': fields.char('Contact Name', size=64, select=1),
306         'street': fields.char('Street', size=128),
307         'street2': fields.char('Street2', size=128),
308         'zip': fields.char('Zip', change_default=True, size=24),
309         'city': fields.char('City', size=128),
310         'state_id': fields.many2one("res.country.state", 'Fed. State', domain="[('country_id','=',country_id)]"),
311         'country_id': fields.many2one('res.country', 'Country'),
312         'email': fields.char('E-Mail', size=240),
313         'phone': fields.char('Phone', size=64),
314         'fax': fields.char('Fax', size=64),
315         'mobile': fields.char('Mobile', size=64),
316         'birthdate': fields.char('Birthdate', size=64),
317         'is_customer_add': fields.related('partner_id', 'customer', type='boolean', string='Customer'),
318         'is_supplier_add': fields.related('partner_id', 'supplier', type='boolean', string='Supplier'),
319         'active': fields.boolean('Active', help="Uncheck the active field to hide the contact."),
320 #        'company_id': fields.related('partner_id','company_id',type='many2one',relation='res.company',string='Company', store=True),
321         'company_id': fields.many2one('res.company', 'Company',select=1),
322         'color': fields.integer('Color Index'),
323     }
324     _defaults = {
325         'active': lambda *a: 1,
326         'company_id': lambda s,cr,uid,c: s.pool.get('res.company')._company_default_get(cr, uid, 'res.partner.address', context=c),
327     }
328     def name_get(self, cr, user, ids, context=None):
329         if context is None:
330             context = {}
331         if not len(ids):
332             return []
333         res = []
334         for r in self.read(cr, user, ids, ['name','zip','country_id', 'city','partner_id', 'street']):
335             if context.get('contact_display', 'contact')=='partner' and r['partner_id']:
336                 res.append((r['id'], r['partner_id'][1]))
337             else:
338                 # make a comma-separated list with the following non-empty elements
339                 elems = [r['name'], r['country_id'] and r['country_id'][1], r['city'], r['street']]
340                 addr = ', '.join(filter(bool, elems))
341                 if (context.get('contact_display', 'contact')=='partner_address') and r['partner_id']:
342                     res.append((r['id'], "%s: %s" % (r['partner_id'][1], addr or '/')))
343                 else:
344                     res.append((r['id'], addr or '/'))
345         return res
346
347     def name_search(self, cr, user, name, args=None, operator='ilike', context=None, limit=100):
348         if not args:
349             args = []
350         if context is None:
351             context = {}
352
353         if not name:
354             ids = self.search(cr, user, args, limit=limit, context=context)
355         elif context.get('contact_display', 'contact') == 'partner':
356             ids = self.search(cr, user, [('partner_id', operator, name)] + args, limit=limit, context=context)
357         else:
358             # first lookup zip code, as it is a common and efficient way to search on these data
359             ids = self.search(cr, user, [('zip', '=', name)] + args, limit=limit, context=context)
360             # then search on other fields:
361             if context.get('contact_display', 'contact') == 'partner_address':
362                 fields = ['partner_id', 'name', 'country_id', 'city', 'street']
363             else:
364                 fields = ['name', 'country_id', 'city', 'street']
365             # Here we have to search the records that satisfy the domain:
366             #       OR([[(f, operator, name)] for f in fields])) + args
367             # Searching on such a domain can be dramatically inefficient, due to the expansion made
368             # for field translations, and the handling of the disjunction by the DB engine itself.
369             # So instead, we search field by field until the search limit is reached.
370             while (not limit or len(ids) < limit) and fields:
371                 f = fields.pop(0)
372                 new_ids = self.search(cr, user, [(f, operator, name)] + args,
373                                       limit=(limit-len(ids) if limit else limit),
374                                       context=context)
375                 # extend ids with the ones in new_ids that are not in ids yet (and keep order)
376                 old_ids = set(ids)
377                 ids.extend([id for id in new_ids if id not in old_ids])
378
379         ids = ids[:limit]
380         return self.name_get(cr, user, ids, context=context)
381
382     def get_city(self, cr, uid, id):
383         return self.browse(cr, uid, id).city
384
385     def _display_address(self, cr, uid, address, context=None):
386         '''
387         The purpose of this function is to build and return an address formatted accordingly to the
388         standards of the country where it belongs.
389
390         :param address: browse record of the res.partner.address to format
391         :returns: the address formatted in a display that fit its country habits (or the default ones
392             if not country is specified)
393         :rtype: string
394         '''
395         # get the address format
396         address_format = address.country_id and address.country_id.address_format or \
397                                          '%(street)s\n%(street2)s\n%(city)s,%(state_code)s %(zip)s' 
398         # get the information that will be injected into the display format
399         args = {
400             'state_code': address.state_id and address.state_id.code or '',
401             'state_name': address.state_id and address.state_id.name or '',
402             'country_code': address.country_id and address.country_id.code or '',
403             'country_name': address.country_id and address.country_id.name or '',
404         }
405         address_field = ['title', 'street', 'street2', 'zip', 'city']
406         for field in address_field :
407             args[field] = getattr(address, field) or ''
408
409         return address_format % args
410
411 res_partner_address()
412
413
414 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
415