[IMP]
[odoo/odoo.git] / addons / event / event.py
1 # -*- coding: utf-8 -*-
2 ##############################################################################
3 #
4 #    OpenERP, Open Source Management Solution
5 #    Copyright (C) 2004-2010 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 time
23 from osv import fields, osv
24 from tools.translate import _
25 import decimal_precision as dp
26
27 class event_type(osv.osv):
28     """ Event Type """
29     _name = 'event.type'
30     _description = __doc__
31     _columns = {
32         'name': fields.char('Event type', size=64, required=True),
33         'default_reply_to': fields.char('Default Reply-To', size=64,help="The email address of the organizer which is put in the 'Reply-To' of all emails sent automatically at event or registrations confirmation. You can also put your email address of your mail gateway if you use one." ),
34         'default_email_event': fields.many2one('email.template','Event Confirmation Email', help="It will select this default confirmation event mail value when you choose this event"),
35         'default_email_registration': fields.many2one('email.template','Registration Confirmation Email', help="It will select this default confirmation registration mail value when you choose this event"),
36         'default_registration_min': fields.integer('Default Minimum Registration', help="It will select this default minimum value when you choose this event"),
37         'default_registration_max': fields.integer('Default Maximum Registration', help="It will select this default maximum value when you choose this event"),
38     }
39     _defaults = {
40         'default_registration_min': 0,
41         'default_registration_max':0,
42         }
43
44 event_type()
45
46 class event_event(osv.osv):
47     """Event"""
48     _name = 'event.event'
49     _description = __doc__
50     _order = 'date_begin'
51
52     def name_get(self, cr, uid, ids, context=None):
53         if not ids:
54               return []
55         res = []
56         for record in self.browse(cr, uid, ids, context=context):
57             date = record.date_begin.split(" ")
58             date = date[0]
59             registers=''
60             if record.register_max !=0:
61                 register_max = str(record.register_max)
62                 register_tot = record.register_current+record.register_prospect
63                 register_tot = str(register_tot)
64                 registers = register_tot+'/'+register_max
65             name = record.name+' ('+date+') '+registers
66             res.append((record['id'], name))
67         return res
68
69     def _name_get_fnc(self, cr, uid, ids,prop,unknow, context=None):
70         res = self.name_get(cr, uid, ids, context=context)
71         return dict(res)
72
73     def copy(self, cr, uid, id, default=None, context=None):
74         """ Reset the state and the registrations while copying an event
75         """
76         if not default:
77             default = {}
78         default.update({
79             'state': 'draft',
80             'registration_ids': False,
81         })
82         return super(event_event, self).copy(cr, uid, id, default=default, context=context)
83
84     def button_draft(self, cr, uid, ids, context=None):
85         return self.write(cr, uid, ids, {'state': 'draft'}, context=context)
86
87     def button_cancel(self, cr, uid, ids, context=None):
88         registration = self.pool.get('event.registration')
89         reg_ids = registration.search(cr, uid, [('event_id','in',ids)], context=context)
90         for event_reg in registration.browse(cr,uid,reg_ids,context=context):
91             if event_reg.state == 'done':
92                 raise osv.except_osv(_('Error!'),_("You have already set a registration for this event as 'Attended'. Please reset it to draft if you want to cancel this event.") )
93         registration.write(cr, uid, reg_ids, {'state': 'cancel'}, context=context)
94         return self.write(cr, uid, ids, {'state': 'cancel'}, context=context)
95
96     def button_done(self, cr, uid, ids, context=None):
97         return self.write(cr, uid, ids, {'state': 'done'}, context=context)
98
99     def check_registration_limits(self, cr, uid, ids, context=None):
100         register_pool = self.pool.get('event.registration')
101         for self.event in self.browse(cr, uid, ids, context=context):
102             total_confirmed = self.event.register_current
103             if total_confirmed < self.event.register_min or total_confirmed > self.event.register_max and self.event.register_max!=0:
104                 raise osv.except_osv(_('Error!'),_("The total of confirmed registration for the event '%s' does not meet the expected minimum/maximum. You should maybe reconsider those limits before going further") % (self.event.name))
105
106     def confirm_event(self, cr, uid, ids, context=None):
107         register_pool = self.pool.get('event.registration')
108         if self.event.email_confirmation_id:
109         #send reminder that will confirm the event for all the people that were already confirmed
110             reg_ids = register_pool.search(cr, uid, [
111                                ('event_id', '=', self.event.id),
112                                ('state', 'not in', ['draft', 'cancel'])], context=context)
113             register_pool.mail_user_confirm(cr, uid, reg_ids)
114         return self.write(cr, uid, ids, {'state': 'confirm'}, context=context)
115
116     def button_confirm(self, cr, uid, ids, context=None):
117         """ Confirm Event and send confirmation email to all register peoples
118         """
119         if isinstance(ids, (int, long)):
120             ids = [ids]
121         self.check_registration_limits(cr, uid, ids, context=context)
122         return self.confirm_event(cr, uid, ids, context=context)
123
124     def _get_register(self, cr, uid, ids, fields, args, context=None):
125         """Get Confirm or uncofirm register value.
126         @param ids: List of Event registration type's id
127         @param fields: List of function fields(register_current and register_prospect).
128         @param context: A standard dictionary for contextual values
129         @return: Dictionary of function fields value.
130         """
131         register_pool = self.pool.get('event.registration')
132         res = {}
133         for event in self.browse(cr, uid, ids, context=context):
134             res[event.id] = {}
135             reg_open = reg_done = reg_draft =0
136             for registration in event.registration_ids:
137                 if registration.state == 'open':
138                     reg_open += registration.nb_register
139                 elif registration.state == 'done':
140                     reg_done += registration.nb_register
141                 elif registration.state == 'draft':
142                     reg_draft += registration.nb_register
143             for field in fields:
144                 number = 0
145                 if field == 'register_current':
146                     number = reg_open
147                 elif field == 'register_attended':
148                     number = reg_done
149                 elif field == 'register_prospect':
150                     number = reg_draft
151                 elif field == 'register_avail':
152                     number = event.register_max-reg_open
153                 res[event.id][field] = number
154         return res
155     
156     def _subscribe_fnc(self, cr, uid, ids, fields, args, context=None):
157         """Get Confirm or uncofirm register value.
158         @param ids: List of Event registration type's id
159         @param fields: List of function fields(register_current and register_prospect).
160         @param context: A standard dictionary for contextual values
161         @return: Dictionary of function fields value.
162         """
163         register_pool = self.pool.get('event.registration')
164         res = {}
165         for event in self.browse(cr, uid, ids, context=context):
166             curr_reg_id = register_pool.search(cr,uid,[('user_id','=',uid),('event_id','=',event.id)])
167             if not curr_reg_id:res[event.id] = False
168             if curr_reg_id:
169                 for reg in register_pool.browse(cr,uid,curr_reg_id,context=context):
170                     if not reg.subscribe:
171                         res[event.id]=False
172                     else:
173                         res[event.id]=True
174         return res 
175
176     _columns = {
177         'name': fields.char('Name', size=64, required=True, translate=True, readonly=False, states={'done': [('readonly', True)]}),
178         'user_id': fields.many2one('res.users', 'Responsible User', readonly=False, states={'done': [('readonly', True)]}),
179         'type': fields.many2one('event.type', 'Type of Event', readonly=False, states={'done': [('readonly', True)]}),
180         'register_max': fields.integer('Maximum Registrations', help="You can for each event define a maximum registration level. If you have too much registrations you are not able to confirm your event. (put 0 to ignore this rule )", readonly=True, states={'draft': [('readonly', False)]}),
181         'register_min': fields.integer('Minimum Registrations', help="You can for each event define a minimum registration level. If you do not enough registrations you are not able to confirm your event. (put 0 to ignore this rule )", readonly=True, states={'draft': [('readonly', False)]}),
182         'register_current': fields.function(_get_register, string='Confirmed Registrations', multi='register_numbers'),
183         'register_avail': fields.function(_get_register, string='Available Registrations', multi='register_numbers',type='integer'),
184         'register_prospect': fields.function(_get_register, string='Unconfirmed Registrations', multi='register_numbers'),
185         'register_attended': fields.function(_get_register, string='Attended Registrations', multi='register_numbers'), 
186         'registration_ids': fields.one2many('event.registration', 'event_id', 'Registrations', readonly=False, states={'done': [('readonly', True)]}),
187         'date_begin': fields.datetime('Start Date', required=True, readonly=True, states={'draft': [('readonly', False)]}),
188         'date_end': fields.datetime('End Date', required=True, readonly=True, states={'draft': [('readonly', False)]}),
189         'state': fields.selection([
190             ('draft', 'Draft'),
191             ('confirm', 'Confirmed'),
192             ('done', 'Done'),
193             ('cancel', 'Cancelled')],
194             'State', readonly=True, required=True,
195             help='If event is created, the state is \'Draft\'.If event is confirmed for the particular dates the state is set to \'Confirmed\'. If the event is over, the state is set to \'Done\'.If event is cancelled the state is set to \'Cancelled\'.'),
196         'email_registration_id' : fields.many2one('email.template','Registration Confirmation Email', help='This field contains the template of the mail that will be automatically sent each time a registration for this event is confirmed.'),
197         'email_confirmation_id' : fields.many2one('email.template','Event Confirmation Email', help="If you set an email template, each participant will receive this email announcing the confirmation of the event."),
198         'full_name' : fields.function(_name_get_fnc, type="char", string='Name'),
199         'reply_to': fields.char('Reply-To Email', size=64, readonly=False, states={'done': [('readonly', True)]}, help="The email address of the organizer is likely to be put here, with the effect to be in the 'Reply-To' of the mails sent automatically at event or registrations confirmation. You can also put the email address of your mail gateway if you use one."),
200         'main_speaker_id': fields.many2one('res.partner','Main Speaker', readonly=False, states={'done': [('readonly', True)]}, help="Speaker who will be giving speech at the event."),
201         'speaker_ids': fields.many2many('res.partner', 'event_speaker_rel', 'speaker_id', 'partner_id', 'Other Speakers', readonly=False, states={'done': [('readonly', True)]}),
202         'address_id': fields.many2one('res.partner.address','Location Address', readonly=False, states={'done': [('readonly', True)]}),
203         'speaker_confirmed': fields.boolean('Speaker Confirmed', readonly=False, states={'done': [('readonly', True)]}),
204         'country_id': fields.related('address_id', 'country_id',
205                     type='many2one', relation='res.country', string='Country', readonly=False, states={'done': [('readonly', True)]}),
206         'note': fields.text('Description', readonly=False, states={'done': [('readonly', True)]}),
207         'company_id': fields.many2one('res.company', 'Company', required=False, change_default=True, readonly=False, states={'done': [('readonly', True)]}),
208         'subscribe' : fields.function(_subscribe_fnc, type="boolean", string='Subscribe'),
209     }
210
211     _defaults = {
212         'state': 'draft',
213         'company_id': lambda self,cr,uid,c: self.pool.get('res.company')._company_default_get(cr, uid, 'event.event', context=c),
214         'user_id': lambda obj, cr, uid, context: uid,
215     }
216     
217     def subscribe_to_event(self,cr,uid,ids,context=None):
218         register_pool = self.pool.get('event.registration')
219         user_pool = self.pool.get('res.users')
220         curr_reg_id = register_pool.search(cr,uid,[('user_id','=',uid),('event_id','=',ids[0])])
221         user = user_pool.browse(cr,uid,uid,context)
222         if not curr_reg_id:
223             curr_reg_id = register_pool.create(cr, uid, {'event_id':ids[0],
224                                                          'email':user.user_email,
225                                                          'name':user.name,
226                                                          'user_id':uid,
227                                                          'subscribe':True,
228                                                     })
229             
230             
231         else:
232             register_pool.write(cr, uid, curr_reg_id,{'state':'open','subscribe':True,
233                             'event_id':ids[0],
234                             })
235         if isinstance(curr_reg_id, (int, long)):
236             curr_reg_id = [curr_reg_id]
237         register_pool.confirm_registration(cr,uid,curr_reg_id,context)
238         self.write(cr,uid,ids,{'subscribe':True})
239         return True
240     
241     def unsubscribe_to_event(self,cr,uid,ids,context=None):
242         register_pool = self.pool.get('event.registration')
243         curr_reg_id = register_pool.search(cr,uid,[('user_id','=',uid),('event_id','=',ids[0])])
244         if curr_reg_id:
245             if isinstance(curr_reg_id, (int, long)):
246                 curr_reg_id = [curr_reg_id]
247             register_pool.write(cr, uid, curr_reg_id,{'event_id':ids[0],
248                                                       'subscribe':False
249                                                      })
250             register_pool.button_reg_cancel(cr,uid,curr_reg_id,context)
251             self.write(cr,uid,ids,{'subscribe':False})
252         return True
253
254     def _check_closing_date(self, cr, uid, ids, context=None):
255         for event in self.browse(cr, uid, ids, context=context):
256             if event.date_end < event.date_begin:
257                 return False
258         return True
259
260     _constraints = [
261         (_check_closing_date, 'Error ! Closing Date cannot be set before Beginning Date.', ['date_end']),
262     ]
263
264     def onchange_event_type(self, cr, uid, ids, type_event, context=None):
265         if type_event:
266             type_info =  self.pool.get('event.type').browse(cr,uid,type_event,context)
267             dic ={
268               'reply_to': type_info.default_reply_to,
269               'email_registration_id': type_info.default_email_registration.id,
270               'email_confirmation_id': type_info.default_email_event.id,
271               'register_min': type_info.default_registration_min,
272               'register_max': type_info.default_registration_max,
273             }
274             return {'value': dic}
275 event_event()
276
277 class event_registration(osv.osv):
278     """Event Registration"""
279     _name= 'event.registration'
280     _description = __doc__
281     _inherit = ['mail.thread','res.partner.address']
282     _columns = {
283         'id': fields.integer('ID'),
284         'origin': fields.char('Origin', size=124,readonly=True,help="Name of the sale order which create the registration"),
285         'nb_register': fields.integer('Number of Participants', required=True, readonly=True, states={'draft': [('readonly', False)]}),
286         'event_id': fields.many2one('event.event', 'Event', required=True, readonly=True, states={'draft': [('readonly', False)]}),
287         'partner_id': fields.many2one('res.partner', 'Partner', states={'done': [('readonly', True)]}),
288         'partner_address_id': fields.many2one('res.partner.address', 'Partner', states={'done': [('readonly', True)]}),
289         "contact_id": fields.many2one('res.partner.address', 'Partner Contact', readonly=False, states={'done': [('readonly', True)]}),
290         'create_date': fields.datetime('Creation Date' , readonly=True),
291         'date_closed': fields.datetime('Attended Date', readonly=True),
292         'date_open': fields.datetime('Registration Date', readonly=True),
293         'reply_to': fields.related('event_id','reply_to',string='Reply-to Email', type='char', size=128, readonly=True,),
294         'log_ids': fields.one2many('mail.message', 'res_id', 'Logs', domain=[('email_from', '=', False),('model','=',_name)]),
295         'event_end_date': fields.related('event_id','date_end', type='datetime', string="Event End Date", readonly=True),
296         'event_begin_date': fields.related('event_id', 'date_begin', type='datetime', string="Event Start Date", readonly=True),
297         'user_id': fields.many2one('res.users', 'Attendee', states={'done': [('readonly', True)]}),
298         'company_id': fields.related('event_id', 'company_id', type='many2one', relation='res.company', string='Company', store=True, readonly=True, states={'draft':[('readonly',False)]}),
299         'state': fields.selection([('draft', 'Unconfirmed'),
300                                     ('open', 'Confirmed'),
301                                     ('cancel', 'Cancelled'),
302                                     ('done', 'Attended')], 'State',
303                                     size=16, readonly=True),
304         'subscribe': fields.boolean('Subscribe'),
305     }
306
307     _defaults = {
308         'nb_register': 1,
309         'state': 'draft',
310         #'user_id': lambda self, cr, uid, ctx: uid,
311     }
312     _order = 'name, create_date desc'
313
314
315     def do_draft(self, cr, uid, ids, context=None):
316         return self.write(cr, uid, ids, {'state': 'draft'}, context=context)
317
318     def confirm_registration(self, cr, uid, ids, context=None):
319         self.message_append(cr, uid, ids,_('State set to open'),body_text= _('Open'))
320         return self.write(cr, uid, ids, {'state': 'open'}, context=context)
321
322
323     def registration_open(self, cr, uid, ids, context=None):
324         """ Open Registration
325         """
326         res = self.confirm_registration(cr, uid, ids, context=context)
327         self.mail_user(cr, uid, ids, context=context)
328         return res
329
330     def button_reg_close(self, cr, uid, ids, context=None):
331         """ Close Registration
332         """
333         if context is None:
334             context = {}
335         today = fields.datetime.now()
336         for registration in self.browse(cr, uid, ids, context=context):
337             if today >= registration.event_id.date_begin:
338                 values = {'state': 'done', 'date_closed': today}
339                 self.write(cr, uid, ids, values)
340                 self.message_append(cr, uid, ids, _('State set to Done'), body_text=_('Done'))
341             else:
342                 raise osv.except_osv(_('Error!'),_("You must wait the event starting day to do this action.") )
343         return True
344
345     def button_reg_cancel(self, cr, uid, ids, context=None, *args):
346         self.message_append(cr, uid, ids,_('State set to Cancel'),body_text= _('Cancel'))
347         return self.write(cr, uid, ids, {'state': 'cancel'})
348
349     def mail_user(self, cr, uid, ids, context=None):
350         """
351         Send email to user with email_template when registration is done
352         """
353         for registration in self.browse(cr, uid, ids, context=context):
354             if registration.event_id.state == 'confirm' and registration.event_id.email_confirmation_id.id:
355                 self.mail_user_confirm(cr, uid, ids, context=context)
356             else:
357                 template_id = registration.event_id.email_registration_id.id
358                 if template_id:
359                     mail_message = self.pool.get('email.template').send_mail(cr,uid,template_id,registration.id)
360         return True
361
362     def mail_user_confirm(self, cr, uid, ids, context=None):
363         """
364         Send email to user when the event is confirmed
365         """
366         for registration in self.browse(cr, uid, ids, context=context):
367             template_id = registration.event_id.email_confirmation_id.id
368             if template_id:
369                 mail_message = self.pool.get('email.template').send_mail(cr,uid,template_id,registration.id)
370         return True
371
372     def onchange_contact_id(self, cr, uid, ids, contact, partner, context=None):
373         data ={}
374         if not contact:
375             return data
376         addr_obj = self.pool.get('res.partner.address')
377         contact_id =  addr_obj.browse(cr, uid, contact, context=context)
378         data = {
379             'email':contact_id.email,
380             'contact_id':contact_id.id,
381             'name':contact_id.name,
382             'phone':contact_id.phone,
383             }
384         return {'value': data}
385
386     def onchange_event(self, cr, uid, ids, event_id, context=None):
387         """This function returns value of Product Name, Unit Price based on Event.
388         """
389         if context is None:
390             context = {}
391         if not event_id:
392             return {}
393         event_obj = self.pool.get('event.event')
394         data_event =  event_obj.browse(cr, uid, event_id, context=context)
395         return {'value': 
396                     {'event_begin_date': data_event.date_begin,
397                      'event_end_date': data_event.date_end,
398                      'company_id': data_event.company_id and data_event.company_id.id or False,
399                     }
400                }
401
402     def onchange_partner_id(self, cr, uid, ids, part, context=None):
403         res_obj = self.pool.get('res.partner')
404         data = {}
405         if not part:
406             return {'value': data}
407         addr = res_obj.address_get(cr, uid, [part]).get('default', False)
408         if addr:
409             d = self.onchange_contact_id(cr, uid, ids, addr, part, context)
410             data.update(d['value'])
411         return {'value': data}
412
413 event_registration()
414
415 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: