[REM] Unnecessary `size` parameters on char fields
[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 import pytz
22 from openerp.tools import DEFAULT_SERVER_DATETIME_FORMAT
23 from datetime import datetime, timedelta
24 from openerp.osv import fields, osv
25 from openerp.tools.translate import _
26 from openerp import SUPERUSER_ID
27
28 class event_type(osv.osv):
29     """ Event Type """
30     _name = 'event.type'
31     _description = __doc__
32     _columns = {
33         'name': fields.char('Event Type', required=True),
34         '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." ),
35         '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"),
36         '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"),
37         'default_registration_min': fields.integer('Default Minimum Registration', help="It will select this default minimum value when you choose this event"),
38         'default_registration_max': fields.integer('Default Maximum Registration', help="It will select this default maximum value when you choose this event"),
39     }
40     _defaults = {
41         'default_registration_min': 0,
42         'default_registration_max': 0,
43     }
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 copy(self, cr, uid, id, default=None, context=None):
70         """ Reset the state and the registrations while copying an event
71         """
72         if not default:
73             default = {}
74         default.update({
75             'state': 'draft',
76             'registration_ids': False,
77         })
78         return super(event_event, self).copy(cr, uid, id, default=default, context=context)
79
80     def button_draft(self, cr, uid, ids, context=None):
81         return self.write(cr, uid, ids, {'state': 'draft'}, context=context)
82
83     def button_cancel(self, cr, uid, ids, context=None):
84         registration = self.pool.get('event.registration')
85         reg_ids = registration.search(cr, uid, [('event_id','in',ids)], context=context)
86         for event_reg in registration.browse(cr,uid,reg_ids,context=context):
87             if event_reg.state == 'done':
88                 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.") )
89         registration.write(cr, uid, reg_ids, {'state': 'cancel'}, context=context)
90         return self.write(cr, uid, ids, {'state': 'cancel'}, context=context)
91
92     def button_done(self, cr, uid, ids, context=None):
93         return self.write(cr, uid, ids, {'state': 'done'}, context=context)
94
95     def confirm_event(self, cr, uid, ids, context=None):
96         register_pool = self.pool.get('event.registration')
97         for event in self.browse(cr, uid, ids, context=context):
98             if event.email_confirmation_id:
99             #send reminder that will confirm the event for all the people that were already confirmed
100                 reg_ids = register_pool.search(cr, uid, [
101                                    ('event_id', '=', event.id),
102                                    ('state', 'not in', ['draft', 'cancel'])], context=context)
103                 register_pool.mail_user_confirm(cr, uid, reg_ids)
104         return self.write(cr, uid, ids, {'state': 'confirm'}, context=context)
105
106     def button_confirm(self, cr, uid, ids, context=None):
107         """ Confirm Event and send confirmation email to all register peoples
108         """
109         return self.confirm_event(cr, uid, isinstance(ids, (int, long)) and [ids] or ids, context=context)
110
111     def _get_seats(self, cr, uid, ids, fields, args, context=None):
112         """Get reserved, available, reserved but unconfirmed and used seats.
113         @return: Dictionary of function field values.
114         """
115         keys = {'draft': 'seats_unconfirmed', 'open':'seats_reserved', 'done': 'seats_used'}
116         res = {}
117         for event_id in ids:
118             res[event_id] = {key:0 for key in keys.values()}
119         query = "SELECT state, sum(nb_register) FROM event_registration WHERE event_id = %s AND state IN ('draft','open','done') GROUP BY state"
120         for event in self.pool.get('event.event').browse(cr, uid, ids, context=context):
121             cr.execute(query, (event.id,))
122             reg_states = cr.fetchall()
123             for reg_state in reg_states:
124                 res[event.id][keys[reg_state[0]]] = reg_state[1]
125             res[event.id]['seats_available'] = event.seats_max - \
126                 (res[event.id]['seats_reserved'] + res[event.id]['seats_used']) \
127                 if event.seats_max > 0 else None
128         return res
129
130     def _get_events_from_registrations(self, cr, uid, ids, context=None):
131         """Get reserved, available, reserved but unconfirmed and used seats, of the event related to a registration.
132         @return: Dictionary of function field values.
133         """
134         event_ids=set()
135         for registration in self.pool['event.registration'].browse(cr, uid, ids, context=context):
136             event_ids.add(registration.event_id.id)
137         return list(event_ids)
138
139     def _subscribe_fnc(self, cr, uid, ids, fields, args, context=None):
140         """This functional fields compute if the current user (uid) is already subscribed or not to the event passed in parameter (ids)
141         """
142         register_pool = self.pool.get('event.registration')
143         res = {}
144         for event in self.browse(cr, uid, ids, context=context):
145             res[event.id] = False
146             curr_reg_id = register_pool.search(cr, uid, [('user_id', '=', uid), ('event_id', '=' ,event.id)])
147             if curr_reg_id:
148                 for reg in register_pool.browse(cr, uid, curr_reg_id, context=context):
149                     if reg.state in ('open','done'):
150                         res[event.id]= True
151                         continue
152         return res
153     
154     def _count_registrations(self, cr, uid, ids, field_name, arg, context=None):
155         return {
156             event.id: len(event.registration_ids)
157             for event in self.browse(cr, uid, ids, context=context)
158         }
159
160     def _compute_date_tz(self, cr, uid, ids, fld, arg, context=None):
161         if context is None:
162             context = {}
163         res = {}
164         for event in self.browse(cr, uid, ids, context=context):
165             ctx = dict(context, tz=(event.date_tz or 'UTC'))
166             if fld == 'date_begin_located':
167                 date_to_convert = event.date_begin
168             elif fld == 'date_end_located':
169                 date_to_convert = event.date_end
170             res[event.id] = fields.datetime.context_timestamp(cr, uid, datetime.strptime(date_to_convert, DEFAULT_SERVER_DATETIME_FORMAT), context=ctx)
171         return res
172
173     def _tz_get(self, cr, uid, context=None):
174         return [(x, x) for x in pytz.all_timezones]
175
176     _columns = {
177         'name': fields.char('Event 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         'seats_max': fields.integer('Maximum Avalaible Seats', oldname='register_max', 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         'seats_min': fields.integer('Minimum Reserved Seats', oldname='register_min', 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         'seats_reserved': fields.function(_get_seats, oldname='register_current', string='Reserved Seats', type='integer', multi='seats_reserved',
183             store={'event.registration': (_get_events_from_registrations, ['state'], 10),
184                    'event.event': (lambda  self, cr, uid, ids, c = {}: ids, ['seats_max', 'registration_ids'], 20)}),
185         'seats_available': fields.function(_get_seats, oldname='register_avail', string='Available Seats', type='integer', multi='seats_reserved',
186             store={'event.registration': (_get_events_from_registrations, ['state'], 10),
187                    'event.event': (lambda  self, cr, uid, ids, c = {}: ids, ['seats_max', 'registration_ids'], 20)}),
188         'seats_unconfirmed': fields.function(_get_seats, oldname='register_prospect', string='Unconfirmed Seat Reservations', type='integer', multi='seats_reserved',
189             store={'event.registration': (_get_events_from_registrations, ['state'], 10),
190                    'event.event': (lambda  self, cr, uid, ids, c = {}: ids, ['seats_max', 'registration_ids'], 20)}),
191         'seats_used': fields.function(_get_seats, oldname='register_attended', string='Number of Participations', type='integer', multi='seats_reserved',
192             store={'event.registration': (_get_events_from_registrations, ['state'], 10),
193                    'event.event': (lambda  self, cr, uid, ids, c = {}: ids, ['seats_max', 'registration_ids'], 20)}),
194         'registration_ids': fields.one2many('event.registration', 'event_id', 'Registrations', readonly=False, states={'done': [('readonly', True)]}),
195         'date_tz': fields.selection(_tz_get, string='Timezone'),
196         'date_begin': fields.datetime('Start Date', required=True, readonly=True, states={'draft': [('readonly', False)]}),
197         'date_end': fields.datetime('End Date', required=True, readonly=True, states={'draft': [('readonly', False)]}),
198         'date_begin_located': fields.function(_compute_date_tz, string='Start Date Located', type="datetime"),
199         'date_end_located': fields.function(_compute_date_tz, string='End Date Located', type="datetime"),
200         'state': fields.selection([
201             ('draft', 'Unconfirmed'),
202             ('cancel', 'Cancelled'),
203             ('confirm', 'Confirmed'),
204             ('done', 'Done')],
205             'Status', readonly=True, required=True,
206             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\'.'),
207         '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.'),
208         '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."),
209         '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."),
210         'address_id': fields.many2one('res.partner','Location', readonly=False, states={'done': [('readonly', True)]}),
211         'country_id': fields.related('address_id', 'country_id',
212                     type='many2one', relation='res.country', string='Country', readonly=False, states={'done': [('readonly', True)]}, store=True),
213         'description': fields.html(
214             'Description', readonly=False, translate=True,
215             states={'done': [('readonly', True)]},
216             oldname='note'),
217         'company_id': fields.many2one('res.company', 'Company', required=False, change_default=True, readonly=False, states={'done': [('readonly', True)]}),
218         'is_subscribed' : fields.function(_subscribe_fnc, type="boolean", string='Subscribed'),
219         'organizer_id': fields.many2one('res.partner', "Organizer"),
220         'count_registrations': fields.function(_count_registrations, type="integer", string="Registrations"),
221     }
222     _defaults = {
223         'state': 'draft',
224         'company_id': lambda self,cr,uid,c: self.pool.get('res.company')._company_default_get(cr, uid, 'event.event', context=c),
225         'user_id': lambda obj, cr, uid, context: uid,
226         'organizer_id': lambda self, cr, uid, c: self.pool.get('res.users').browse(cr, uid, uid, context=c).company_id.partner_id.id,
227         'address_id': lambda self, cr, uid, c: self.pool.get('res.users').browse(cr, uid, uid, context=c).company_id.partner_id.id,
228         'date_tz': lambda self, cr, uid, ctx: ctx.get('tz', "UTC"),
229     }
230
231     def _check_seats_limit(self, cr, uid, ids, context=None):
232         for event in self.browse(cr, uid, ids, context=context):
233             if event.seats_max and event.seats_available < 0:
234                 return False
235         return True
236
237     _constraints = [
238         (_check_seats_limit, 'No more available seats.', ['registration_ids','seats_max']),
239     ]
240
241     def subscribe_to_event(self, cr, uid, ids, context=None):
242         register_pool = self.pool.get('event.registration')
243         user_pool = self.pool.get('res.users')
244         num_of_seats = int(context.get('ticket', 1))
245         user = user_pool.browse(cr, uid, uid, context=context)
246         curr_reg_ids = register_pool.search(cr, uid, [('user_id', '=', user.id), ('event_id', '=' , ids[0])])
247         #the subscription is done with SUPERUSER_ID because in case we share the kanban view, we want anyone to be able to subscribe
248         if not curr_reg_ids:
249             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})]
250         else:
251             register_pool.write(cr, uid, curr_reg_ids, {'nb_register': num_of_seats}, context=context)
252         return register_pool.confirm_registration(cr, SUPERUSER_ID, curr_reg_ids, context=context)
253
254     def unsubscribe_to_event(self, cr, uid, ids, context=None):
255         register_pool = self.pool.get('event.registration')
256         #the unsubscription is done with SUPERUSER_ID because in case we share the kanban view, we want anyone to be able to unsubscribe
257         curr_reg_ids = register_pool.search(cr, SUPERUSER_ID, [('user_id', '=', uid), ('event_id', '=', ids[0])])
258         return register_pool.button_reg_cancel(cr, SUPERUSER_ID, curr_reg_ids, context=context)
259
260     def _check_closing_date(self, cr, uid, ids, context=None):
261         for event in self.browse(cr, uid, ids, context=context):
262             if event.date_end < event.date_begin:
263                 return False
264         return True
265
266     _constraints = [
267         (_check_closing_date, 'Error ! Closing Date cannot be set before Beginning Date.', ['date_end']),
268     ]
269
270     def onchange_event_type(self, cr, uid, ids, type_event, context=None):
271         values = {}
272         if type_event:
273             type_info =  self.pool.get('event.type').browse(cr,uid,type_event,context)
274             dic ={
275               'reply_to': type_info.default_reply_to,
276               'email_registration_id': type_info.default_email_registration.id,
277               'email_confirmation_id': type_info.default_email_event.id,
278               'seats_min': type_info.default_registration_min,
279               'seats_max': type_info.default_registration_max,
280             }
281             values.update(dic)
282         return values
283
284     def onchange_start_date(self, cr, uid, ids, date_begin=False, date_end=False, context=None):
285         res = {'value':{}}
286         if date_end:
287             return res
288         if date_begin and isinstance(date_begin, str):
289             date_begin = datetime.strptime(date_begin, "%Y-%m-%d %H:%M:%S")
290             date_end = date_begin + timedelta(hours=1)
291             res['value'] = {'date_end': date_end.strftime("%Y-%m-%d %H:%M:%S")}
292         return res
293
294
295 class event_registration(osv.osv):
296     """Event Registration"""
297     _name= 'event.registration'
298     _description = __doc__
299     _inherit = ['mail.thread', 'ir.needaction_mixin']
300     _columns = {
301         'id': fields.integer('ID'),
302         'origin': fields.char('Source Document', readonly=True,help="Reference of the sales order which created the registration"),
303         'nb_register': fields.integer('Number of Participants', required=True, readonly=True, states={'draft': [('readonly', False)]}),
304         'event_id': fields.many2one('event.event', 'Event', required=True, readonly=True, states={'draft': [('readonly', False)]}),
305         'partner_id': fields.many2one('res.partner', 'Partner', states={'done': [('readonly', True)]}),
306         'create_date': fields.datetime('Creation Date' , readonly=True),
307         'date_closed': fields.datetime('Attended Date', readonly=True),
308         'date_open': fields.datetime('Registration Date', readonly=True),
309         'reply_to': fields.related('event_id','reply_to',string='Reply-to Email', type='char', readonly=True,),
310         'log_ids': fields.one2many('mail.message', 'res_id', 'Logs', domain=[('model','=',_name)]),
311         'event_end_date': fields.related('event_id','date_end', type='datetime', string="Event End Date", readonly=True),
312         'event_begin_date': fields.related('event_id', 'date_begin', type='datetime', string="Event Start Date", readonly=True),
313         'user_id': fields.many2one('res.users', 'User', states={'done': [('readonly', True)]}),
314         'company_id': fields.related('event_id', 'company_id', type='many2one', relation='res.company', string='Company', store=True, readonly=True, states={'draft':[('readonly',False)]}),
315         'state': fields.selection([('draft', 'Unconfirmed'),
316                                     ('cancel', 'Cancelled'),
317                                     ('open', 'Confirmed'),
318                                     ('done', 'Attended')], 'Status',
319                                     readonly=True),
320         'email': fields.char('Email', size=64),
321         'phone': fields.char('Phone', size=64),
322         'name': fields.char('Name', select=True),
323     }
324     _defaults = {
325         'nb_register': 1,
326         'state': 'draft',
327     }
328     _order = 'name, create_date desc'
329
330
331     def _check_seats_limit(self, cr, uid, ids, context=None):
332         for registration in self.browse(cr, uid, ids, context=context):
333             if registration.event_id.seats_max and \
334                 registration.event_id.seats_available < (registration.state == 'draft' and registration.nb_register or 0):
335                 return False
336         return True
337
338     _constraints = [
339         (_check_seats_limit, 'No more available seats.', ['event_id','nb_register','state']),
340     ]
341
342     def do_draft(self, cr, uid, ids, context=None):
343         return self.write(cr, uid, ids, {'state': 'draft'}, context=context)
344
345     def confirm_registration(self, cr, uid, ids, context=None):
346         for reg in self.browse(cr, uid, ids, context=context or {}):
347             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)
348             self.message_post(cr, uid, reg.id, body=_('Event Registration confirmed.'), context=context)
349         return self.write(cr, uid, ids, {'state': 'open'}, context=context)
350
351     def registration_open(self, cr, uid, ids, context=None):
352         """ Open Registration
353         """
354         res = self.confirm_registration(cr, uid, ids, context=context)
355         self.mail_user(cr, uid, ids, context=context)
356         return res
357
358     def button_reg_close(self, cr, uid, ids, context=None):
359         """ Close Registration
360         """
361         if context is None:
362             context = {}
363         today = fields.datetime.now()
364         for registration in self.browse(cr, uid, ids, context=context):
365             if today >= registration.event_id.date_begin:
366                 values = {'state': 'done', 'date_closed': today}
367                 self.write(cr, uid, ids, values)
368             else:
369                 raise osv.except_osv(_('Error!'), _("You must wait for the starting day of the event to do this action."))
370         return True
371
372     def button_reg_cancel(self, cr, uid, ids, context=None, *args):
373         return self.write(cr, uid, ids, {'state': 'cancel'})
374
375     def mail_user(self, cr, uid, ids, context=None):
376         """
377         Send email to user with email_template when registration is done
378         """
379         for registration in self.browse(cr, uid, ids, context=context):
380             if registration.event_id.state == 'confirm' and registration.event_id.email_confirmation_id.id:
381                 self.mail_user_confirm(cr, uid, ids, context=context)
382             else:
383                 template_id = registration.event_id.email_registration_id.id
384                 if template_id:
385                     mail_message = self.pool.get('email.template').send_mail(cr,uid,template_id,registration.id)
386         return True
387
388     def mail_user_confirm(self, cr, uid, ids, context=None):
389         """
390         Send email to user when the event is confirmed
391         """
392         for registration in self.browse(cr, uid, ids, context=context):
393             template_id = registration.event_id.email_confirmation_id.id
394             if template_id:
395                 mail_message = self.pool.get('email.template').send_mail(cr,uid,template_id,registration.id)
396         return True
397
398     def onchange_contact_id(self, cr, uid, ids, contact, partner, context=None):
399         if not contact:
400             return {}
401         addr_obj = self.pool.get('res.partner')
402         contact_id =  addr_obj.browse(cr, uid, contact, context=context)
403         return {'value': {
404             'email':contact_id.email,
405             'name':contact_id.name,
406             'phone':contact_id.phone,
407             }}
408
409     def onchange_partner_id(self, cr, uid, ids, part, context=None):
410         res_obj = self.pool.get('res.partner')
411         data = {}
412         if not part:
413             return {'value': data}
414         addr = res_obj.address_get(cr, uid, [part]).get('default', False)
415         if addr:
416             d = self.onchange_contact_id(cr, uid, ids, addr, part, context)
417             data.update(d['value'])
418         return {'value': data}
419
420 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: