[CLEAN] event: lint / remove dead code
[odoo/odoo.git] / addons / event / event.py
1 # -*- coding: utf-8 -*-
2
3 import pytz
4
5 from openerp import models, fields, api, _
6 from openerp.exceptions import Warning
7
8
9 class event_type(models.Model):
10     """ Event Type """
11     _name = 'event.type'
12     _description = 'Event Type'
13
14     name = fields.Char(string='Event Type', required=True)
15     default_reply_to = fields.Char(
16         string='Default Reply-To',
17         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.")
18     default_email_event = fields.Many2one(
19         'email.template', string='Event Confirmation Email',
20         help="It will select this default confirmation event mail value when you choose this event")
21     default_email_registration = fields.Many2one(
22         'email.template', string='Registration Confirmation Email',
23         help="It will select this default confirmation registration mail value when you choose this event")
24     default_registration_min = fields.Integer(
25         string='Default Minimum Registration', default=0,
26         help="It will select this default minimum value when you choose this event")
27     default_registration_max = fields.Integer(
28         string='Default Maximum Registration', default=0,
29         help="It will select this default maximum value when you choose this event")
30
31
32 class event_event(models.Model):
33     """Event"""
34     _name = 'event.event'
35     _description = 'Event'
36     _inherit = ['mail.thread', 'ir.needaction_mixin']
37     _order = 'date_begin'
38
39     name = fields.Char(
40         string='Name', translate=True, required=True,
41         readonly=False, states={'done': [('readonly', True)]})
42     user_id = fields.Many2one(
43         'res.users', string='Responsible',
44         default=lambda self: self.env.user,
45         readonly=False, states={'done': [('readonly', True)]})
46     company_id = fields.Many2one(
47         'res.company', string='Company', change_default=True,
48         default=lambda self: self.env['res.company']._company_default_get('event.event'),
49         required=False, readonly=False, states={'done': [('readonly', True)]})
50     organizer_id = fields.Many2one(
51         'res.partner', string='Organizer',
52         default=lambda self: self.env.user.company_id.partner_id)
53     type = fields.Many2one(
54         'event.type', string='Category',
55         readonly=False, states={'done': [('readonly', True)]})
56     color = fields.Integer('Kanban Color Index')
57
58     # Seats and computation
59     seats_max = fields.Integer(
60         string='Maximum Available Seats', oldname='register_max',
61         readonly=True, states={'draft': [('readonly', False)]},
62         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 )")
63     seats_availability = fields.Selection(
64         [('limited', 'Limited'), ('unlimited', 'Unlimited')],
65         'Available Seat', required=True, default='unlimited')
66     seats_min = fields.Integer(
67         string='Minimum Reserved Seats', oldname='register_min',
68         readonly=True, states={'draft': [('readonly', False)]},
69         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 )")
70     seats_reserved = fields.Integer(
71         oldname='register_current', string='Reserved Seats',
72         store=True, readonly=True, compute='_compute_seats')
73     seats_available = fields.Integer(
74         oldname='register_avail', string='Available Seats',
75         store=True, readonly=True, compute='_compute_seats')
76     seats_unconfirmed = fields.Integer(
77         oldname='register_prospect', string='Unconfirmed Seat Reservations',
78         store=True, readonly=True, compute='_compute_seats')
79     seats_used = fields.Integer(
80         oldname='register_attended', string='Number of Participations',
81         store=True, readonly=True, compute='_compute_seats')
82
83     @api.multi
84     @api.depends('seats_max', 'registration_ids.state', 'registration_ids.nb_register')
85     def _compute_seats(self):
86         """ Determine reserved, available, reserved but unconfirmed and used seats. """
87         # initialize fields to 0
88         for event in self:
89             event.seats_unconfirmed = event.seats_reserved = event.seats_used = event.seats_available = 0
90         # aggregate registrations by event and by state
91         if self.ids:
92             state_field = {
93                 'draft': 'seats_unconfirmed',
94                 'open': 'seats_reserved',
95                 'done': 'seats_used',
96             }
97             query = """ SELECT event_id, state, sum(nb_register)
98                         FROM event_registration
99                         WHERE event_id IN %s AND state IN ('draft', 'open', 'done')
100                         GROUP BY event_id, state
101                     """
102             self._cr.execute(query, (tuple(self.ids),))
103             for event_id, state, num in self._cr.fetchall():
104                 event = self.browse(event_id)
105                 event[state_field[state]] += num
106         # compute seats_available
107         for event in self:
108             if event.seats_max > 0:
109                 event.seats_available = event.seats_max - (event.seats_reserved + event.seats_used)
110
111     # Registration fields
112     registration_ids = fields.One2many(
113         'event.registration', 'event_id', string='Registrations',
114         readonly=False, states={'done': [('readonly', True)]})
115     count_registrations = fields.Integer(string='Registrations', compute='_count_registrations')
116
117     @api.one
118     @api.depends('registration_ids')
119     def _count_registrations(self):
120         self.count_registrations = len(self.registration_ids)
121
122     # Date fields
123     date_tz = fields.Selection('_tz_get', string='Timezone', default=lambda self: self.env.user.tz)
124     date_begin = fields.Datetime(
125         string='Start Date', required=True,
126         readonly=True, states={'draft': [('readonly', False)]})
127     date_end = fields.Datetime(
128         string='End Date', required=True,
129         readonly=True, states={'draft': [('readonly', False)]})
130     date_begin_located = fields.Datetime(string='Start Date Located', compute='_compute_date_begin_tz')
131     date_end_located = fields.Datetime(string='End Date Located', compute='_compute_date_end_tz')
132
133     @api.model
134     def _tz_get(self):
135         return [(x, x) for x in pytz.all_timezones]
136
137     @api.one
138     @api.depends('date_tz', 'date_begin')
139     def _compute_date_begin_tz(self):
140         if self.date_begin:
141             self_in_tz = self.with_context(tz=(self.date_tz or 'UTC'))
142             date_begin = fields.Datetime.from_string(self.date_begin)
143             self.date_begin_located = fields.Datetime.to_string(fields.Datetime.context_timestamp(self_in_tz, date_begin))
144         else:
145             self.date_begin_located = False
146
147     @api.one
148     @api.depends('date_tz', 'date_end')
149     def _compute_date_end_tz(self):
150         if self.date_end:
151             self_in_tz = self.with_context(tz=(self.date_tz or 'UTC'))
152             date_end = fields.Datetime.from_string(self.date_end)
153             self.date_end_located = fields.Datetime.to_string(fields.Datetime.context_timestamp(self_in_tz, date_end))
154         else:
155             self.date_end_located = False
156
157     state = fields.Selection([
158         ('draft', 'Unconfirmed'), ('cancel', 'Cancelled'),
159         ('confirm', 'Confirmed'), ('done', 'Done')],
160         string='Status', default='draft', readonly=True, required=True, copy=False,
161         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'.")
162     auto_confirm = fields.Boolean(string='Auto Confirmation Activated', compute='_compute_auto_confirm')
163
164     @api.one
165     def _compute_auto_confirm(self):
166         self.auto_confirm = self.env['ir.values'].get_default('marketing.config.settings', 'auto_confirmation')
167
168     # Mailing
169     email_registration_id = fields.Many2one(
170         'email.template', string='Registration Confirmation Email',
171         domain=[('model', '=', 'event.registration')],
172         help='This field contains the template of the mail that will be automatically sent each time a registration for this event is confirmed.')
173     email_confirmation_id = fields.Many2one(
174         'email.template', string='Event Confirmation Email',
175         domain=[('model', '=', 'event.registration')],
176         help="If you set an email template, each participant will receive this email announcing the confirmation of the event.")
177     reply_to = fields.Char(
178         string='Reply-To Email', readonly=False, states={'done': [('readonly', True)]},
179         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.")
180     address_id = fields.Many2one(
181         'res.partner', string='Location', default=lambda self: self.env.user.company_id.partner_id,
182         readonly=False, states={'done': [('readonly', True)]})
183     country_id = fields.Many2one(
184         'res.country', string='Country', related='address_id.country_id',
185         store=True, readonly=False, states={'done': [('readonly', True)]})
186     description = fields.Html(
187         string='Description', oldname='note', translate=True,
188         readonly=False, states={'done': [('readonly', True)]})
189
190     @api.multi
191     @api.depends('name', 'date_begin', 'date_end')
192     def name_get(self):
193         result = []
194         for event in self:
195             dates = [dt.split(' ')[0] for dt in [event.date_begin, event.date_end] if dt]
196             dates = sorted(set(dates))
197             result.append((event.id, '%s (%s)' % (event.name, ' - '.join(dates))))
198         return result
199
200     @api.one
201     @api.constrains('seats_max', 'seats_available')
202     def _check_seats_limit(self):
203         if self.seats_max and self.seats_available < 0:
204             raise Warning(_('No more available seats.'))
205
206     @api.one
207     @api.constrains('date_begin', 'date_end')
208     def _check_closing_date(self):
209         if self.date_end < self.date_begin:
210             raise Warning(_('Closing Date cannot be set before Beginning Date.'))
211
212     @api.model
213     def create(self, vals):
214         res = super(event_event, self).create(vals)
215         if res.auto_confirm:
216             res.confirm_event()
217         return res
218
219     @api.one
220     def button_draft(self):
221         self.state = 'draft'
222
223     @api.one
224     def button_cancel(self):
225         for event_reg in self.registration_ids:
226             if event_reg.state == 'done':
227                 raise Warning(_("You have already set a registration for this event as 'Attended'. Please reset it to draft if you want to cancel this event."))
228         self.registration_ids.write({'state': 'cancel'})
229         self.state = 'cancel'
230
231     @api.one
232     def button_done(self):
233         self.state = 'done'
234
235     @api.one
236     def confirm_event(self):
237         if self.email_confirmation_id:
238             # send reminder that will confirm the event for all the people that were already confirmed
239             regs = self.registration_ids.filtered(lambda reg: reg.state not in ('draft', 'cancel'))
240             regs.mail_user_confirm()
241         self.state = 'confirm'
242
243     @api.one
244     def button_confirm(self):
245         """ Confirm Event and send confirmation email to all register peoples """
246         self.confirm_event()
247
248     @api.one
249     def subscribe_to_event(self):
250         """ Subscribe the current user to a given event """
251         user = self.env.user
252         num_of_seats = int(self._context.get('ticket', 1))
253         regs = self.registration_ids.filtered(lambda reg: reg.user_id == user)
254         # the subscription is done as SUPERUSER_ID because in case we share the
255         # kanban view, we want anyone to be able to subscribe
256         if not regs:
257             regs = regs.sudo().create({
258                 'event_id': self.id,
259                 'email': user.email,
260                 'name': user.name,
261                 'user_id': user.id,
262                 'nb_register': num_of_seats,
263             })
264         else:
265             regs.write({'nb_register': num_of_seats})
266         if regs._check_auto_confirmation():
267             regs.sudo().confirm_registration()
268
269     @api.one
270     def unsubscribe_to_event(self):
271         """ Unsubscribe the current user from a given event """
272         # the unsubscription is done as SUPERUSER_ID because in case we share
273         # the kanban view, we want anyone to be able to unsubscribe
274         user = self.env.user
275         regs = self.sudo().registration_ids.filtered(lambda reg: reg.user_id == user)
276         regs.button_reg_cancel()
277
278     @api.onchange('type')
279     def _onchange_type(self):
280         if self.type:
281             self.reply_to = self.type.default_reply_to
282             self.email_registration_id = self.type.default_email_registration
283             self.email_confirmation_id = self.type.default_email_event
284             self.seats_min = self.type.default_registration_min
285             self.seats_max = self.type.default_registration_max
286
287     @api.multi
288     def action_event_registration_report(self):
289         res = self.env['ir.actions.act_window'].for_xml_id('event', 'action_report_event_registration')
290         res['context'] = {
291             "search_default_event_id": self.id,
292             "group_by": ['event_date:day'],
293         }
294         return res
295
296
297 class event_registration(models.Model):
298     _name = 'event.registration'
299     _description = 'Event Registration'
300     _inherit = ['mail.thread', 'ir.needaction_mixin']
301     _order = 'name, create_date desc'
302
303     origin = fields.Char(
304         string='Source Document', readonly=True,
305         help="Reference of the sales order which created the registration")  # funny we refer sale orders... event is not sale related
306     nb_register = fields.Integer(
307         string='Number of Participants', required=True, default=1,
308         readonly=True, states={'draft': [('readonly', False)]})
309     event_id = fields.Many2one(
310         'event.event', string='Event', required=True,
311         readonly=True, states={'draft': [('readonly', False)]})
312     partner_id = fields.Many2one(
313         'res.partner', string='Partner',
314         states={'done': [('readonly', True)]})
315     date_open = fields.Datetime(string='Registration Date', readonly=True)
316     date_closed = fields.Datetime(string='Attended Date', readonly=True)
317     reply_to = fields.Char(string='Reply-to Email', related='event_id.reply_to', readonly=True)
318     event_begin_date = fields.Datetime(string="Event Start Date", related='event_id.date_begin', readonly=True)
319     event_end_date = fields.Datetime(string="Event End Date", related='event_id.date_end', readonly=True)
320     user_id = fields.Many2one('res.users', string='User', states={'done': [('readonly', True)]})
321     company_id = fields.Many2one(
322         'res.company', string='Company', related='event_id.company_id',
323         store=True, readonly=True, states={'draft': [('readonly', False)]})
324     state = fields.Selection([
325         ('draft', 'Unconfirmed'), ('cancel', 'Cancelled'),
326         ('open', 'Confirmed'), ('done', 'Attended')],
327         string='Status', default='draft', readonly=True, copy=False, track_visibility='onchange')
328     email = fields.Char(string='Email')
329     phone = fields.Char(string='Phone')
330     name = fields.Char(string='Name', select=True)
331
332     @api.one
333     @api.constrains('event_id', 'state', 'nb_register')
334     def _check_seats_limit(self):
335         if self.event_id.seats_max and \
336                 self.event_id.seats_available < (self.nb_register if self.state == 'draft' else 0):
337             raise Warning(_('Only %s seats available for this event') % self.event_id.seats_available if self.event_id.seats_available > 0 else _('No more seats available for this event.'))
338
339     @api.one
340     def _check_auto_confirmation(self):
341         if self.event_id and self.event_id.state == 'confirm' and self.event_id.auto_confirm and self.event_id.seats_available:
342             return True
343         return False
344
345     @api.model
346     def create(self, vals):
347         res = super(event_registration, self).create(vals)
348         if res._check_auto_confirmation():
349             res.sudo().confirm_registration()
350         return res
351
352     @api.one
353     def do_draft(self):
354         self.state = 'draft'
355
356     @api.one
357     def confirm_registration(self):
358         self.event_id.message_post(
359             body=_('New registration confirmed: %s.') % (self.name or ''),
360             subtype="event.mt_event_registration")
361         self.state = 'open'
362
363     @api.one
364     def registration_open(self):
365         """ Open Registration """
366         self.confirm_registration()
367         self.mail_user()
368
369     @api.one
370     def button_reg_close(self):
371         """ Close Registration """
372         today = fields.Datetime.now()
373         if self.event_id.date_begin <= today:
374             self.write({'state': 'done', 'date_closed': today})
375         else:
376             raise Warning(_("You must wait for the starting day of the event to do this action."))
377
378     @api.one
379     def button_reg_cancel(self):
380         self.state = 'cancel'
381
382     @api.one
383     def mail_user(self):
384         """Send email to user with email_template when registration is done """
385         if self.event_id.state == 'confirm' and self.event_id.email_confirmation_id:
386             self.mail_user_confirm()
387         else:
388             template = self.event_id.email_registration_id
389             if template:
390                 template.send_mail(self.id)
391
392     @api.one
393     def mail_user_confirm(self):
394         """Send email to user when the event is confirmed """
395         template = self.event_id.email_confirmation_id
396         if template:
397             template.send_mail(self.id)
398
399     @api.onchange('partner_id')
400     def _onchange_partner(self):
401         if self.partner_id:
402             contact_id = self.partner_id.address_get().get('default', False)
403             if contact_id:
404                 contact = self.env['res.partner'].browse(contact_id)
405                 self.name = contact.name
406                 self.email = contact.email
407                 self.phone = contact.phone