[IMP]event_form
[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     _inherit = ['ir.needaction_mixin','mail.thread']
52
53     def name_get(self, cr, uid, ids, context=None):
54         if not ids:
55               return []
56         res = []
57         for record in self.browse(cr, uid, ids, context=context):
58             date = record.date_begin.split(" ")
59             date = date[0]
60             registers=''
61             if record.register_max !=0:
62                 register_max = str(record.register_max)
63                 register_tot = record.register_current+record.register_prospect
64                 register_tot = str(register_tot)
65                 registers = register_tot+'/'+register_max
66             name = record.name+' ('+date+') '+registers
67             res.append((record['id'], name))
68         return res
69
70     def _name_get_fnc(self, cr, uid, ids,prop,unknow, context=None):
71         res = self.name_get(cr, uid, ids, context=context)
72         return dict(res)
73
74     def create(self, cr, uid, vals, context=None):
75         obj_id = super(event_event, self).create(cr, uid, vals, context)
76         self.create_send_note(cr, uid, [obj_id], context=context)
77         return obj_id
78
79     def copy(self, cr, uid, id, default=None, context=None):
80         """ Reset the state and the registrations while copying an event
81         """
82         if not default:
83             default = {}
84         default.update({
85             'state': 'draft',
86             'registration_ids': False,
87         })
88         return super(event_event, self).copy(cr, uid, id, default=default, context=context)
89
90     def button_draft(self, cr, uid, ids, context=None):
91         self.button_draft_send_note(cr, uid, ids, context=context)
92         return self.write(cr, uid, ids, {'state': 'draft'}, context=context)
93
94     def button_cancel(self, cr, uid, ids, context=None):
95         registration = self.pool.get('event.registration')
96         reg_ids = registration.search(cr, uid, [('event_id','in',ids)], context=context)
97         for event_reg in registration.browse(cr,uid,reg_ids,context=context):
98             if event_reg.state == 'done':
99                 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.") )
100         registration.write(cr, uid, reg_ids, {'state': 'cancel'}, context=context)
101         self.button_cancel_send_note(cr, uid, ids, context=context)
102         return self.write(cr, uid, ids, {'state': 'cancel'}, context=context)
103
104     def button_done(self, cr, uid, ids, context=None):
105         self.button_done_send_note(cr, uid, ids, context=context)
106         return self.write(cr, uid, ids, {'state': 'done'}, context=context)
107
108     def check_registration_limits(self, cr, uid, ids, context=None):
109         register_pool = self.pool.get('event.registration')
110         for self.event in self.browse(cr, uid, ids, context=context):
111             total_confirmed = self.event.register_current
112             if total_confirmed < self.event.register_min or total_confirmed > self.event.register_max and self.event.register_max!=0:
113                 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))
114
115     def check_registration_limits_before(self, cr, uid, ids, no_of_registration, context=None):
116         for event in self.browse(cr, uid, ids, context=context):
117             available_seats = event.register_avail
118             if available_seats and no_of_registration > available_seats:
119                  raise osv.except_osv(_('Warning!'),_("Only %d Seats are Available!") % (available_seats))
120             elif available_seats == 0:
121                 raise osv.except_osv(_('Warning!'),_("No Tickets Available!"))
122
123     def confirm_event(self, cr, uid, ids, context=None):
124         register_pool = self.pool.get('event.registration')
125         if self.event.email_confirmation_id:
126         #send reminder that will confirm the event for all the people that were already confirmed
127             reg_ids = register_pool.search(cr, uid, [
128                                ('event_id', '=', self.event.id),
129                                ('state', 'not in', ['draft', 'cancel'])], context=context)
130             register_pool.mail_user_confirm(cr, uid, reg_ids)
131         return self.write(cr, uid, ids, {'state': 'confirm'}, context=context)
132
133     def button_confirm(self, cr, uid, ids, context=None):
134         """ Confirm Event and send confirmation email to all register peoples
135         """
136         if isinstance(ids, (int, long)):
137             ids = [ids]
138         self.check_registration_limits(cr, uid, ids, context=context)
139         self.button_confirm_send_note(cr, uid, ids, context=context)
140         return self.confirm_event(cr, uid, ids, context=context)
141
142     def _get_register(self, cr, uid, ids, fields, args, context=None):
143         """Get Confirm or uncofirm register value.
144         @param ids: List of Event registration type's id
145         @param fields: List of function fields(register_current and register_prospect).
146         @param context: A standard dictionary for contextual values
147         @return: Dictionary of function fields value.
148         """
149         register_pool = self.pool.get('event.registration')
150         res = {}
151         for event in self.browse(cr, uid, ids, context=context):
152             res[event.id] = {}
153             reg_open = reg_done = reg_draft =0
154             for registration in event.registration_ids:
155                 if registration.state == 'open':
156                     reg_open += registration.nb_register
157                 elif registration.state == 'done':
158                     reg_done += registration.nb_register
159                 elif registration.state == 'draft':
160                     reg_draft += registration.nb_register
161             for field in fields:
162                 number = 0
163                 if field == 'register_current':
164                     number = reg_open
165                 elif field == 'register_attended':
166                     number = reg_done
167                 elif field == 'register_prospect':
168                     number = reg_draft
169                 elif field == 'register_avail':
170                     #the number of ticket is unlimited if the event.register_max field is not set. 
171                     #In that cas we arbitrary set it to 9999, it is used in the kanban view to special case the display of the 'subscribe' button
172                     number = event.register_max - reg_open if event.register_max != 0 else 9999
173                 res[event.id][field] = number
174         return res
175
176     def _subscribe_fnc(self, cr, uid, ids, fields, args, context=None):
177         """This functional fields compute if the current user (uid) is already subscribed or not to the event passed in parameter (ids)
178         """
179         register_pool = self.pool.get('event.registration')
180         res = {}
181         for event in self.browse(cr, uid, ids, context=context):
182             res[event.id] = False
183             curr_reg_id = register_pool.search(cr, uid, [('user_id', '=', uid), ('event_id', '=' ,event.id)])
184             if curr_reg_id:
185                 for reg in register_pool.browse(cr, uid, curr_reg_id, context=context):
186                     if reg.state in ('open','done'):
187                         res[event.id]= True
188                         continue
189         return res 
190
191     _columns = {
192         'name': fields.char('Name', size=64, required=True, translate=True, readonly=False, states={'done': [('readonly', True)]}),
193         'user_id': fields.many2one('res.users', 'Responsible User', readonly=False, states={'done': [('readonly', True)]}),
194         'type': fields.many2one('event.type', 'Type of Event', readonly=False, states={'done': [('readonly', True)]}),
195         'register_max': fields.integer('Maximum Registration', 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)]}),
196         'register_min': fields.integer('Minimum Registration', 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)]}),
197         'register_current': fields.function(_get_register, string='Confirmed Registrations', multi='register_numbers'),
198         'register_avail': fields.function(_get_register, string='Available Registrations', multi='register_numbers',type='integer'),
199         'register_prospect': fields.function(_get_register, string='Unconfirmed Registrations', multi='register_numbers'),
200         'register_attended': fields.function(_get_register, string='# of Participations', multi='register_numbers'), 
201         'registration_ids': fields.one2many('event.registration', 'event_id', 'Registrations', readonly=False, states={'done': [('readonly', True)]}),
202         'date_begin': fields.datetime('Start Date', required=True, readonly=True, states={'draft': [('readonly', False)]}),
203         'date_end': fields.datetime('End Date', required=True, readonly=True, states={'draft': [('readonly', False)]}),
204         'state': fields.selection([
205             ('draft', 'Unconfirmed'),
206             ('cancel', 'Cancelled'),
207             ('confirm', 'Confirmed'),
208             ('done', 'Done')],
209             'Status', readonly=True, required=True,
210             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\'.'),
211         '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.'),
212         '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."),
213         'full_name' : fields.function(_name_get_fnc, type="char", string='Name'),
214         '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."),
215         '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."),
216         'address_id': fields.many2one('res.partner','Location Address', readonly=False, states={'done': [('readonly', True)]}),
217         'street': fields.related('address_id','street',type='char',string='Street'),
218         'zip': fields.related('address_id','zip',type='char',string='zip'),
219         'city': fields.related('address_id','city',type='char',string='city'),
220         'speaker_confirmed': fields.boolean('Speaker Confirmed', readonly=False, states={'done': [('readonly', True)]}),
221         'country_id': fields.related('address_id', 'country_id',
222                     type='many2one', relation='res.country', string='Country', readonly=False, states={'done': [('readonly', True)]}),
223         'note': fields.text('Description', readonly=False, states={'done': [('readonly', True)]}),
224         'company_id': fields.many2one('res.company', 'Company', required=False, change_default=True, readonly=False, states={'done': [('readonly', True)]}),
225         'is_subscribed' : fields.function(_subscribe_fnc, type="boolean", string='Subscribed'),
226     }
227     _defaults = {
228         'state': 'draft',
229         'company_id': lambda self,cr,uid,c: self.pool.get('res.company')._company_default_get(cr, uid, 'event.event', context=c),
230         'user_id': lambda obj, cr, uid, context: uid,
231     }
232     def subscribe_to_event(self, cr, uid, ids, context=None):
233         register_pool = self.pool.get('event.registration')
234         user_pool = self.pool.get('res.users')
235         num_of_seats = int(context.get('ticket', 1))
236         self.check_registration_limits_before(cr, uid, ids, num_of_seats, context=context)
237         user = user_pool.browse(cr, uid, uid, context=context)
238         curr_reg_ids = register_pool.search(cr, uid, [('user_id', '=', user.id), ('event_id', '=' , ids[0])])
239         #the subscription is done with UID = 1 because in case we share the kanban view, we want anyone to be able to subscribe
240         if not curr_reg_ids:
241             curr_reg_ids = [register_pool.create(cr, 1, {'event_id': ids[0] ,'email': user.user_email, 'name':user.name, 'user_id': user.id, 'nb_register': num_of_seats})]
242         else:
243             register_pool.write(cr, uid, curr_reg_ids, {'nb_register': num_of_seats}, context=context)
244         return register_pool.confirm_registration(cr, 1, curr_reg_ids, context=context)
245
246     def unsubscribe_to_event(self, cr, uid, ids, context=None):
247         register_pool = self.pool.get('event.registration')
248         #the unsubscription is done with UID = 1 because in case we share the kanban view, we want anyone to be able to unsubscribe
249         curr_reg_ids = register_pool.search(cr, 1, [('user_id', '=', uid), ('event_id', '=', ids[0])])
250         return register_pool.button_reg_cancel(cr, 1, curr_reg_ids, context=context)
251
252     def _check_closing_date(self, cr, uid, ids, context=None):
253         for event in self.browse(cr, uid, ids, context=context):
254             if event.date_end < event.date_begin:
255                 return False
256         return True
257
258     _constraints = [
259         (_check_closing_date, 'Error ! Closing Date cannot be set before Beginning Date.', ['date_end']),
260     ]
261     def onchange_address_id(self, cr, uid, ids, address, context=None):
262         data ={}
263         if not address:
264             return data
265         addr_obj = self.pool.get('res.partner')
266         addr_id =  addr_obj.browse(cr, uid, address, context=context)
267         data = {
268             'street':addr_id.street,
269             'zip':addr_id.zip,
270             'city':addr_id.city,
271             }
272         return {'value': data}
273     def onchange_event_type(self, cr, uid, ids, type_event, context=None):
274         if type_event:
275             type_info =  self.pool.get('event.type').browse(cr,uid,type_event,context)
276             dic ={
277               'reply_to': type_info.default_reply_to,
278               'email_registration_id': type_info.default_email_registration.id,
279               'email_confirmation_id': type_info.default_email_event.id,
280               'register_min': type_info.default_registration_min,
281               'register_max': type_info.default_registration_max,
282             }
283             return {'value': dic}
284         
285     # ----------------------------------------
286     # OpenChatter methods and notifications
287     # ----------------------------------------
288
289     def get_needaction_user_ids(self, cr, uid, ids, context=None):
290         result = dict.fromkeys(ids, [])
291         for obj in self.browse(cr, uid, ids, context=context):
292             if obj.state == 'draft' and obj.user_id:
293                 result[obj.id] = [obj.user_id.id]
294         return result
295
296     def create_send_note(self, cr, uid, ids, context=None):
297         message = _("Event has been <b>created</b>.")
298         self.message_append_note(cr, uid, ids, body=message, context=context)
299         return True
300
301     def button_cancel_send_note(self, cr, uid, ids, context=None):
302         message = _("Event has been <b>cancelled</b>.")
303         self.message_append_note(cr, uid, ids, body=message, context=context)
304         return True
305
306     def button_draft_send_note(self, cr, uid, ids, context=None):
307         message = _("Event has been set to <b>draft</b>.")
308         self.message_append_note(cr, uid, ids, body=message, context=context)
309         return True
310
311     def button_done_send_note(self, cr, uid, ids, context=None):
312         message = _("Event has been <b>done</b>.")
313         self.message_append_note(cr, uid, ids, body=message, context=context)
314         return True
315
316     def button_confirm_send_note(self, cr, uid, ids, context=None):
317         message = _("Event has been <b>confirmed</b>.")
318         self.message_append_note(cr, uid, ids, body=message, context=context)
319         return True
320
321 event_event()
322
323 class event_registration(osv.osv):
324     """Event Registration"""
325     _name= 'event.registration'
326     _description = __doc__
327     _inherit = ['ir.needaction_mixin','mail.thread','res.partner']
328     _columns = {
329         'id': fields.integer('ID'),
330         'origin': fields.char('Source', size=124,readonly=True,help="Name of the sale order which create the registration"),
331         'nb_register': fields.integer('Number of Participants', required=True, readonly=True, states={'draft': [('readonly', False)]}),
332         'event_id': fields.many2one('event.event', 'Event', required=True, readonly=True, states={'draft': [('readonly', False)]}),
333         'partner_id': fields.many2one('res.partner', 'Partner', states={'done': [('readonly', True)]}),
334         'create_date': fields.datetime('Creation Date' , readonly=True),
335         'date_closed': fields.datetime('Attended Date', readonly=True),
336         'date_open': fields.datetime('Registration Date', readonly=True),
337         'reply_to': fields.related('event_id','reply_to',string='Reply-to Email', type='char', size=128, readonly=True,),
338         'log_ids': fields.one2many('mail.message', 'res_id', 'Logs', domain=[('email_from', '=', False),('model','=',_name)]),
339         'event_end_date': fields.related('event_id','date_end', type='datetime', string="Event End Date", readonly=True),
340         'event_begin_date': fields.related('event_id', 'date_begin', type='datetime', string="Event Start Date", readonly=True),
341         'user_id': fields.many2one('res.users', 'Attendee', states={'done': [('readonly', True)]}),
342         'company_id': fields.related('event_id', 'company_id', type='many2one', relation='res.company', string='Company', store=True, readonly=True, states={'draft':[('readonly',False)]}),
343         'state': fields.selection([('draft', 'Unconfirmed'),
344                                     ('cancel', 'Cancelled'),
345                                     ('open', 'Confirmed'),
346                                     ('done', 'Attended')], 'Status',
347                                     size=16, readonly=True),
348     }
349
350     _defaults = {
351         'nb_register': 1,
352         'state': 'draft',
353     }
354     _order = 'name, create_date desc'
355
356
357     def do_draft(self, cr, uid, ids, context=None):
358         self.do_draft_send_note(cr, uid, ids, context=context)
359         return self.write(cr, uid, ids, {'state': 'draft'}, context=context)
360
361     def confirm_registration(self, cr, uid, ids, context=None):
362         self.message_append(cr, uid, ids,_('State set to open'),body_text= _('Open'))
363         return self.write(cr, uid, ids, {'state': 'open'}, context=context)
364
365     def create(self, cr, uid, vals, context=None):
366         obj_id = super(event_registration, self).create(cr, uid, vals, context)
367         self.create_send_note(cr, uid, [obj_id], context=context)
368         return obj_id
369
370     def registration_open(self, cr, uid, ids, context=None):
371         """ Open Registration
372         """
373         event_obj = self.pool.get('event.event')
374         for register in  self.browse(cr, uid, ids, context=context):
375             event_id = register.event_id.id
376             no_of_registration = register.nb_register
377             event_obj.check_registration_limits_before(cr, uid, [event_id], no_of_registration, context=context)
378         res = self.confirm_registration(cr, uid, ids, context=context)
379         self.mail_user(cr, uid, ids, context=context)
380         return res
381
382     def button_reg_close(self, cr, uid, ids, context=None):
383         """ Close Registration
384         """
385         if context is None:
386             context = {}
387         today = fields.datetime.now()
388         for registration in self.browse(cr, uid, ids, context=context):
389             if today >= registration.event_id.date_begin:
390                 values = {'state': 'done', 'date_closed': today}
391                 self.write(cr, uid, ids, values)
392                 self.message_append(cr, uid, ids, _('State set to Done'), body_text=_('Done'))
393             else:
394                 raise osv.except_osv(_('Error!'),_("You must wait the event starting day to do this action.") )
395         return True
396
397     def button_reg_cancel(self, cr, uid, ids, context=None, *args):
398         self.message_append(cr, uid, ids,_('State set to Cancel'),body_text= _('Cancel'))
399         return self.write(cr, uid, ids, {'state': 'cancel'})
400
401     def mail_user(self, cr, uid, ids, context=None):
402         """
403         Send email to user with email_template when registration is done
404         """
405         for registration in self.browse(cr, uid, ids, context=context):
406             if registration.event_id.state == 'confirm' and registration.event_id.email_confirmation_id.id:
407                 self.mail_user_confirm(cr, uid, ids, context=context)
408             else:
409                 template_id = registration.event_id.email_registration_id.id
410                 if template_id:
411                     mail_message = self.pool.get('email.template').send_mail(cr,uid,template_id,registration.id)
412         return True
413
414     def mail_user_confirm(self, cr, uid, ids, context=None):
415         """
416         Send email to user when the event is confirmed
417         """
418         for registration in self.browse(cr, uid, ids, context=context):
419             template_id = registration.event_id.email_confirmation_id.id
420             if template_id:
421                 mail_message = self.pool.get('email.template').send_mail(cr,uid,template_id,registration.id)
422         return True
423
424     def onchange_contact_id(self, cr, uid, ids, contact, partner, context=None):
425         data ={}
426         if not contact:
427             return data
428         addr_obj = self.pool.get('res.partner')
429         contact_id =  addr_obj.browse(cr, uid, contact, context=context)
430         data = {
431             'email':contact_id.email,
432             'contact_id':contact_id.id,
433             'name':contact_id.name,
434             'phone':contact_id.phone,
435             }
436         return {'value': data}
437
438     def onchange_event(self, cr, uid, ids, event_id, context=None):
439         """This function returns value of Product Name, Unit Price based on Event.
440         """
441         if context is None:
442             context = {}
443         if not event_id:
444             return {}
445         event_obj = self.pool.get('event.event')
446         data_event =  event_obj.browse(cr, uid, event_id, context=context)
447         return {'value': 
448                     {'event_begin_date': data_event.date_begin,
449                      'event_end_date': data_event.date_end,
450                      'company_id': data_event.company_id and data_event.company_id.id or False,
451                     }
452                }
453
454     def onchange_partner_id(self, cr, uid, ids, part, context=None):
455         res_obj = self.pool.get('res.partner')
456         data = {}
457         if not part:
458             return {'value': data}
459         addr = res_obj.address_get(cr, uid, [part]).get('default', False)
460         if addr:
461             d = self.onchange_contact_id(cr, uid, ids, addr, part, context)
462             data.update(d['value'])
463         return {'value': data}
464
465     # ----------------------------------------
466     # OpenChatter methods and notifications
467     # ----------------------------------------
468
469     def get_needaction_user_ids(self, cr, uid, ids, context=None):
470         result = dict.fromkeys(ids, [])
471         for obj in self.browse(cr, uid, ids, context=context):
472             if obj.state == 'draft' and obj.user_id:
473                 result[obj.id] = [obj.user_id.id]
474         return result
475
476     def create_send_note(self, cr, uid, ids, context=None):
477         message = _("Registration has been <b>created</b>.")
478         self.message_append_note(cr, uid, ids, body=message, context=context)
479         return True
480
481     def do_draft_send_note(self, cr, uid, ids, context=None):
482         message = _("Registration has been set as <b>draft</b>.")
483         self.message_append_note(cr, uid, ids, body=message, context=context)
484         return True
485
486 event_registration()
487
488 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: