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