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