[IMP] res.partner: better context management in name_get/name_search
[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     def name_get(self, cr, uid, ids, context=None):
40         if not len(ids):
41             return []
42         reads = self.read(cr, uid, ids, ['name','parent_id'], context=context)
43         res = []
44         for record in reads:
45             name = record['name']
46             if record['parent_id']:
47                 name = record['parent_id'][1]+' / '+name
48             res.append((record['id'], name))
49         return res
50
51     def name_search(self, cr, uid, name, args=None, operator='ilike', context=None, limit=100):
52         if not args:
53             args=[]
54         if not context:
55             context={}
56         if name:
57             # Be sure name_search is symetric to name_get
58             name = name.split(' / ')[-1]
59             ids = self.search(cr, uid, [('name', operator, name)] + args, limit=limit, context=context)
60         else:
61             ids = self.search(cr, uid, args, limit=limit, context=context)
62         return self.name_get(cr, uid, ids, context)
63
64
65     def _name_get_fnc(self, cr, uid, ids, prop, unknow_none, context=None):
66         res = self.name_get(cr, uid, ids, context=context)
67         return dict(res)
68
69     _description='Partner Categories'
70     _name = 'res.partner.category'
71     _columns = {
72         'name': fields.char('Category Name', required=True, size=64, translate=True),
73         'parent_id': fields.many2one('res.partner.category', 'Parent Category', select=True, ondelete='cascade'),
74         'complete_name': fields.function(_name_get_fnc, method=True, type="char", string='Full Name'),
75         'child_ids': fields.one2many('res.partner.category', 'parent_id', 'Child Categories'),
76         'active' : fields.boolean('Active', help="The active field allows you to hide the category without removing it."),
77         'parent_left' : fields.integer('Left parent', select=True),
78         'parent_right' : fields.integer('Right parent', select=True),
79     }
80     _constraints = [
81         (osv.osv._check_recursion, 'Error ! You can not create recursive categories.', ['parent_id'])
82     ]
83     _defaults = {
84         'active' : lambda *a: 1,
85     }
86     _parent_store = True
87     _parent_order = 'name'
88     _order = 'parent_left'
89 res_partner_category()
90
91 class res_partner_title(osv.osv):
92     _name = 'res.partner.title'
93     _columns = {
94         'name': fields.char('Title', required=True, size=46, translate=True),
95         'shortcut': fields.char('Shortcut', required=True, size=16, translate=True),
96         'domain': fields.selection([('partner','Partner'),('contact','Contact')], 'Domain', required=True, size=24)
97     }
98     _order = 'name'
99 res_partner_title()
100
101 def _lang_get(self, cr, uid, context={}):
102     obj = self.pool.get('res.lang')
103     ids = obj.search(cr, uid, [], context=context)
104     res = obj.read(cr, uid, ids, ['code', 'name'], context)
105     return [(r['code'], r['name']) for r in res] + [('','')]
106
107
108 class res_partner(osv.osv):
109     _description='Partner'
110     _name = "res.partner"
111     _order = "name"
112     _columns = {
113         'name': fields.char('Name', size=128, required=True, select=True),
114         'opt_out':fields.boolean('Opt-out', help="If checked, this partner will not receive any automated email \
115 notifications, such as the availability of invoices."),
116         'date': fields.date('Date', select=1),
117         'title': fields.many2one('res.partner.title','Partner Firm'),
118         'parent_id': fields.many2one('res.partner','Parent Partner'),
119         'child_ids': fields.one2many('res.partner', 'parent_id', 'Partner Ref.'),
120         'ref': fields.char('Reference', size=64, select=1),
121         '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."),
122         'user_id': fields.many2one('res.users', 'Salesman', help='The internal user that is in charge of communicating with this partner if any.'),
123         '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."),
124         'bank_ids': fields.one2many('res.partner.bank', 'partner_id', 'Banks'),
125         'website': fields.char('Website',size=64, help="Website of Partner."),
126         'comment': fields.text('Notes'),
127         'address': fields.one2many('res.partner.address', 'partner_id', 'Contacts'),
128         'category_id': fields.many2many('res.partner.category', 'res_partner_category_rel', 'partner_id', 'category_id', 'Categories'),
129         'events': fields.one2many('res.partner.event', 'partner_id', 'Events'),
130         'credit_limit': fields.float(string='Credit Limit'),
131         'ean13': fields.char('EAN13', size=13),
132         'active': fields.boolean('Active'),
133         'customer': fields.boolean('Customer', help="Check this box if the partner is a customer."),
134         '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."),
135         'city': fields.related('address', 'city', type='char', string='City'),
136         'function': fields.related('address', 'function', type='char', string='function'),
137         'subname': fields.related('address', 'name', type='char', string='Contact Name'),
138         'phone': fields.related('address', 'phone', type='char', string='Phone'),
139         'mobile': fields.related('address', 'mobile', type='char', string='Mobile'),
140         'country': fields.related('address', 'country_id', type='many2one', relation='res.country', string='Country'),
141         'employee': fields.boolean('Employee', help="Check this box if the partner is an Employee."),
142         'email': fields.related('address', 'email', type='char', size=240, string='E-mail'),
143         'company_id': fields.many2one('res.company', 'Company', select=1),
144         'color': fields.integer('Color Index'),
145     }
146
147     def _default_category(self, cr, uid, context={}):
148         if 'category_id' in context and context['category_id']:
149             return [context['category_id']]
150         return []
151
152     _defaults = {
153         'active': lambda *a: 1,
154         'customer': lambda *a: 1,
155         'address': [{'type': 'default'}],
156         'category_id': _default_category,
157         'company_id': lambda s,cr,uid,c: s.pool.get('res.company')._company_default_get(cr, uid, 'res.partner', context=c),
158         'opt_out' : False,
159         'color': 0,
160     }
161
162     def copy(self, cr, uid, id, default={}, context={}):
163         name = self.read(cr, uid, [id], ['name'])[0]['name']
164         default.update({'name': name+ _(' (copy)'), 'events':[]})
165         return super(res_partner, self).copy(cr, uid, id, default, context)
166
167     def do_share(self, cr, uid, ids, *args):
168         return True
169
170     def _check_ean_key(self, cr, uid, ids, context=None):
171         for partner_o in pooler.get_pool(cr.dbname).get('res.partner').read(cr, uid, ids, ['ean13',]):
172             thisean=partner_o['ean13']
173             if thisean and thisean!='':
174                 if len(thisean)!=13:
175                     return False
176                 sum=0
177                 for i in range(12):
178                     if not (i % 2):
179                         sum+=int(thisean[i])
180                     else:
181                         sum+=3*int(thisean[i])
182                 if math.ceil(sum/10.0)*10-sum!=int(thisean[12]):
183                     return False
184         return True
185
186 #   _constraints = [(_check_ean_key, 'Error: Invalid ean code', ['ean13'])]
187
188     def name_get(self, cr, uid, ids, context={}):
189         if not len(ids):
190             return []
191         if context and context.get('show_ref'):
192             rec_name = 'ref'
193         else:
194             rec_name = 'name'
195
196         res = [(r['id'], r[rec_name]) for r in self.read(cr, uid, ids, [rec_name], context)]
197         return res
198
199     def name_search(self, cr, uid, name, args=None, operator='ilike', context=None, limit=100):
200         if not args:
201             args=[]
202         if name:
203             ids = self.search(cr, uid, [('ref', '=', name)] + args, limit=limit, context=context)
204             if not ids:
205                 ids = self.search(cr, uid, [('name', operator, name)] + args, limit=limit, context=context)
206         else:
207             ids = self.search(cr, uid, args, limit=limit, context=context)
208         return self.name_get(cr, uid, ids, context)
209
210     def _email_send(self, cr, uid, ids, email_from, subject, body, on_error=None):
211         partners = self.browse(cr, uid, ids)
212         for partner in partners:
213             if len(partner.address):
214                 if partner.address[0].email:
215                     tools.email_send(email_from, [partner.address[0].email], subject, body, on_error)
216         return True
217
218     def email_send(self, cr, uid, ids, email_from, subject, body, on_error=''):
219         while len(ids):
220             self.pool.get('ir.cron').create(cr, uid, {
221                 'name': 'Send Partner Emails',
222                 'user_id': uid,
223 #               'nextcall': False,
224                 'model': 'res.partner',
225                 'function': '_email_send',
226                 'args': repr([ids[:16], email_from, subject, body, on_error])
227             })
228             ids = ids[16:]
229         return True
230
231     def address_get(self, cr, uid, ids, adr_pref=['default']):
232         address_obj = self.pool.get('res.partner.address')
233         address_ids = address_obj.search(cr, uid, [('partner_id', '=', ids)])
234         address_rec = address_obj.read(cr, uid, address_ids, ['type'])
235         res = list(tuple(addr.values()) for addr in address_rec)
236         adr = dict(res)
237         # get the id of the (first) default address if there is one,
238         # otherwise get the id of the first address in the list
239         if res:
240             default_address = adr.get('default', res[0][1])
241         else:
242             default_address = False
243         result = {}
244         for a in adr_pref:
245             result[a] = adr.get(a, default_address)
246         return result
247
248     def gen_next_ref(self, cr, uid, ids):
249         if len(ids) != 1:
250             return True
251
252         # compute the next number ref
253         cr.execute("select ref from res_partner where ref is not null order by char_length(ref) desc, ref desc limit 1")
254         res = cr.dictfetchall()
255         ref = res and res[0]['ref'] or '0'
256         try:
257             nextref = int(ref)+1
258         except:
259             raise osv.except_osv(_('Warning'), _("Couldn't generate the next id because some partners have an alphabetic id !"))
260
261         # update the current partner
262         cr.execute("update res_partner set ref=%s where id=%s", (nextref, ids[0]))
263         return True
264
265     def view_header_get(self, cr, uid, view_id, view_type, context):
266         res = super(res_partner, self).view_header_get(cr, uid, view_id, view_type, context)
267         if res: return res
268         if (not context.get('category_id', False)):
269             return False
270         return _('Partners: ')+self.pool.get('res.partner.category').browse(cr, uid, context['category_id'], context).name
271     def main_partner(self, cr, uid):
272         ''' Return the id of the main partner
273         '''
274         model_data = self.pool.get('ir.model.data')
275         return model_data.browse(
276             cr, uid,
277             model_data.search(cr, uid, [('module','=','base'),
278                                         ('name','=','main_partner')])[0],
279             ).res_id
280 res_partner()
281
282 class res_partner_address(osv.osv):
283     _description ='Partner Addresses'
284     _name = 'res.partner.address'
285     _order = 'type, name'
286     _columns = {
287         'partner_id': fields.many2one('res.partner', 'Partner Name', ondelete='set null', select=True, help="Keep empty for a private address, not related to partner."),
288         '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."),
289         'function': fields.char('Function', size=64),
290         'title': fields.many2one('res.partner.title','Title'),
291         'name': fields.char('Contact Name', size=64, select=1),
292         'street': fields.char('Street', size=128),
293         'street2': fields.char('Street2', size=128),
294         'zip': fields.char('Zip', change_default=True, size=24),
295         'city': fields.char('City', size=128),
296         'state_id': fields.many2one("res.country.state", 'Fed. State', domain="[('country_id','=',country_id)]"),
297         'country_id': fields.many2one('res.country', 'Country'),
298         'email': fields.char('E-Mail', size=240),
299         'phone': fields.char('Phone', size=64),
300         'fax': fields.char('Fax', size=64),
301         'mobile': fields.char('Mobile', size=64),
302         'birthdate': fields.char('Birthdate', size=64),
303         'is_customer_add': fields.related('partner_id', 'customer', type='boolean', string='Customer'),
304         'is_supplier_add': fields.related('partner_id', 'supplier', type='boolean', string='Supplier'),
305         'active': fields.boolean('Active', help="Uncheck the active field to hide the contact."),
306 #        'company_id': fields.related('partner_id','company_id',type='many2one',relation='res.company',string='Company', store=True),
307         'company_id': fields.many2one('res.company', 'Company',select=1),
308         'color': fields.integer('Color Index'),
309     }
310     _defaults = {
311         'active': lambda *a: 1,
312         'company_id': lambda s,cr,uid,c: s.pool.get('res.company')._company_default_get(cr, uid, 'res.partner.address', context=c),
313     }
314
315     def name_get(self, cr, user, ids, context={}):
316         if context is None:
317             context = {}
318         if not len(ids):
319             return []
320         res = []
321         for r in self.read(cr, user, ids, ['name','zip','country_id', 'city','partner_id', 'street']):
322             if context.get('contact_display', 'contact')=='partner' and r['partner_id']:
323                 res.append((r['id'], r['partner_id'][1]))
324             else:
325                 # make a comma-separated list with the following non-empty elements
326                 elems = [r['name'], r['country_id'] and r['country_id'][1], r['city'], r['street']]
327                 addr = ', '.join(filter(bool, elems))
328                 if (context.get('contact_display', 'contact')=='partner_address') and r['partner_id']:
329                     res.append((r['id'], "%s: %s" % (r['partner_id'][1], addr or '/')))
330                 else:
331                     res.append((r['id'], addr or '/'))
332         return res
333
334     def name_search(self, cr, user, name, args=None, operator='ilike', context=None, limit=100):
335         if not args:
336             args=[]
337         if not context:
338             context={}
339         if context.get('contact_display', 'contact')=='partner ' or context.get('contact_display', 'contact')=='partner_address '  :
340             ids = self.search(cr, user, [('partner_id',operator,name)], limit=limit, context=context)
341         else:
342             if not name:
343                 ids = self.search(cr, user, args, limit=limit, context=context)
344             else:
345                 ids = self.search(cr, user, [('zip','=',name)] + args, limit=limit, context=context)
346             if not ids:
347                 ids = self.search(cr, user, [('city',operator,name)] + args, limit=limit, context=context)
348             if name:
349                 ids += self.search(cr, user, [('name',operator,name)] + args, limit=limit, context=context)
350                 ids += self.search(cr, user, [('partner_id',operator,name)] + args, limit=limit, context=context)
351         return self.name_get(cr, user, ids, context=context)
352
353     def get_city(self, cr, uid, id):
354         return self.browse(cr, uid, id).city
355
356 res_partner_address()
357
358 class res_partner_category(osv.osv):
359     _inherit = 'res.partner.category'
360     _columns = {
361         'partner_ids': fields.many2many('res.partner', 'res_partner_category_rel', 'category_id', 'partner_id', 'Partners'),
362     }
363
364 res_partner_category()
365
366 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
367