[MERGE] forward port of branch 8.0 up to e883193
[odoo/odoo.git] / addons / event / event.py
index c328469..8ef3a70 100644 (file)
 #
 ##############################################################################
 
-from osv import fields, osv
-from tools.translate import _
-from openerp import SUPERUSER_ID
+import datetime
+import pytz
 
-class event_type(osv.osv):
-    """ Event Type """
-    _name = 'event.type'
-    _description = __doc__
-    _columns = {
-        'name': fields.char('Event Type', size=64, required=True),
-        '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." ),
-        '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"),
-        '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"),
-        'default_registration_min': fields.integer('Default Minimum Registration', help="It will select this default minimum value when you choose this event"),
-        'default_registration_max': fields.integer('Default Maximum Registration', help="It will select this default maximum value when you choose this event"),
-    }
-    _defaults = {
-        'default_registration_min': 0,
-        'default_registration_max':0,
-        }
+from openerp import models, fields, api, _
+from openerp.exceptions import Warning
 
-event_type()
 
-class event_event(osv.osv):
+class event_type(models.Model):
+    """ Event Type """
+    _name = 'event.type'
+    _description = 'Event Type'
+
+    name = fields.Char(string='Event Type', required=True)
+    default_reply_to = fields.Char(string='Default Reply-To',
+        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.")
+    default_email_event = fields.Many2one('email.template', string='Event Confirmation Email',
+        help="It will select this default confirmation event mail value when you choose this event")
+    default_email_registration = fields.Many2one('email.template', string='Registration Confirmation Email',
+        help="It will select this default confirmation registration mail value when you choose this event")
+    default_registration_min = fields.Integer(string='Default Minimum Registration', default=0,
+        help="It will select this default minimum value when you choose this event")
+    default_registration_max = fields.Integer(string='Default Maximum Registration', default=0,
+        help="It will select this default maximum value when you choose this event")
+
+
+class event_event(models.Model):
     """Event"""
     _name = 'event.event'
-    _description = __doc__
+    _description = 'Event'
+    _inherit = ['mail.thread', 'ir.needaction_mixin']
     _order = 'date_begin'
-    _inherit = ['mail.thread','ir.needaction_mixin']
-
-    def name_get(self, cr, uid, ids, context=None):
-        if not ids:
-            return []
-        res = []
-        for record in self.browse(cr, uid, ids, context=context):
-            date = record.date_begin.split(" ")[0]
-            date_end = record.date_end.split(" ")[0]
-            if date != date_end:
-                date += ' - ' + date_end
-            display_name = record.name + ' (' + date + ')'
-            res.append((record['id'], display_name))
-        return res
 
-    def create(self, cr, uid, vals, context=None):
-        obj_id = super(event_event, self).create(cr, uid, vals, context)
-        self.create_send_note(cr, uid, [obj_id], context=context)
-        return obj_id
-
-    def copy(self, cr, uid, id, default=None, context=None):
-        """ Reset the state and the registrations while copying an event
-        """
-        if not default:
-            default = {}
-        default.update({
-            'state': 'draft',
-            'registration_ids': False,
-        })
-        return super(event_event, self).copy(cr, uid, id, default=default, context=context)
-
-    def button_draft(self, cr, uid, ids, context=None):
-        self.button_draft_send_note(cr, uid, ids, context=context)
-        return self.write(cr, uid, ids, {'state': 'draft'}, context=context)
-
-    def button_cancel(self, cr, uid, ids, context=None):
-        registration = self.pool.get('event.registration')
-        reg_ids = registration.search(cr, uid, [('event_id','in',ids)], context=context)
-        for event_reg in registration.browse(cr,uid,reg_ids,context=context):
-            if event_reg.state == 'done':
-                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.") )
-        registration.write(cr, uid, reg_ids, {'state': 'cancel'}, context=context)
-        self.button_cancel_send_note(cr, uid, ids, context=context)
-        return self.write(cr, uid, ids, {'state': 'cancel'}, context=context)
-
-    def button_done(self, cr, uid, ids, context=None):
-        self.button_done_send_note(cr, uid, ids, context=context)
-        return self.write(cr, uid, ids, {'state': 'done'}, context=context)
-
-    def check_registration_limits(self, cr, uid, ids, context=None):
-        for self.event in self.browse(cr, uid, ids, context=context):
-            total_confirmed = self.event.register_current
-            if total_confirmed < self.event.register_min or total_confirmed > self.event.register_max and self.event.register_max!=0:
-                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))
-
-    def check_registration_limits_before(self, cr, uid, ids, no_of_registration, context=None):
-        for event in self.browse(cr, uid, ids, context=context):
-            available_seats = event.register_avail
-            if available_seats and no_of_registration > available_seats:
-                raise osv.except_osv(_('Warning!'),_("Only %d Seats are Available!") % (available_seats))
-            elif available_seats == 0:
-                raise osv.except_osv(_('Warning!'),_("No Tickets Available!"))
-
-    def confirm_event(self, cr, uid, ids, context=None):
-        register_pool = self.pool.get('event.registration')
-        if self.event.email_confirmation_id:
-        #send reminder that will confirm the event for all the people that were already confirmed
-            reg_ids = register_pool.search(cr, uid, [
-                               ('event_id', '=', self.event.id),
-                               ('state', 'not in', ['draft', 'cancel'])], context=context)
-            register_pool.mail_user_confirm(cr, uid, reg_ids)
-        return self.write(cr, uid, ids, {'state': 'confirm'}, context=context)
-
-    def button_confirm(self, cr, uid, ids, context=None):
-        """ Confirm Event and send confirmation email to all register peoples
-        """
-        if isinstance(ids, (int, long)):
-            ids = [ids]
-        self.check_registration_limits(cr, uid, ids, context=context)
-        self.button_confirm_send_note(cr, uid, ids, context=context)
-        return self.confirm_event(cr, uid, ids, context=context)
-
-    def _get_register(self, cr, uid, ids, fields, args, context=None):
-        """Get Confirm or uncofirm register value.
-        @param ids: List of Event registration type's id
-        @param fields: List of function fields(register_current and register_prospect).
-        @param context: A standard dictionary for contextual values
-        @return: Dictionary of function fields value.
-        """
-        res = {}
-        for event in self.browse(cr, uid, ids, context=context):
-            res[event.id] = {}
-            reg_open = reg_done = reg_draft =0
-            for registration in event.registration_ids:
-                if registration.state == 'open':
-                    reg_open += registration.nb_register
-                elif registration.state == 'done':
-                    reg_done += registration.nb_register
-                elif registration.state == 'draft':
-                    reg_draft += registration.nb_register
-            for field in fields:
-                number = 0
-                if field == 'register_current':
-                    number = reg_open
-                elif field == 'register_attended':
-                    number = reg_done
-                elif field == 'register_prospect':
-                    number = reg_draft
-                elif field == 'register_avail':
-                    #the number of ticket is unlimited if the event.register_max field is not set.
-                    #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
-                    number = event.register_max - reg_open if event.register_max != 0 else 9999
-                res[event.id][field] = number
-        return res
+    name = fields.Char(string='Event Name', translate=True, required=True,
+        readonly=False, states={'done': [('readonly', True)]})
+    user_id = fields.Many2one('res.users', string='Responsible User',
+        default=lambda self: self.env.user,
+        readonly=False, states={'done': [('readonly', True)]})
+    type = fields.Many2one('event.type', string='Type of Event',
+        readonly=False, states={'done': [('readonly', True)]})
+    color = fields.Integer('Kanban Color Index')
+    seats_max = fields.Integer(string='Maximum Available Seats', oldname='register_max',
+        readonly=True, states={'draft': [('readonly', False)]},
+        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 )")
+    seats_min = fields.Integer(string='Minimum Reserved Seats', oldname='register_min',
+        readonly=True, states={'draft': [('readonly', False)]},
+        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 )")
+
+    seats_reserved = fields.Integer(oldname='register_current', string='Reserved Seats',
+        store=True, readonly=True, compute='_compute_seats')
+    seats_available = fields.Integer(oldname='register_avail', string='Available Seats',
+        store=True, readonly=True, compute='_compute_seats')
+    seats_unconfirmed = fields.Integer(oldname='register_prospect', string='Unconfirmed Seat Reservations',
+        store=True, readonly=True, compute='_compute_seats')
+    seats_used = fields.Integer(oldname='register_attended', string='Number of Participations',
+        store=True, readonly=True, compute='_compute_seats')
+
+    @api.multi
+    @api.depends('seats_max', 'registration_ids.state', 'registration_ids.nb_register')
+    def _compute_seats(self):
+        """ Determine reserved, available, reserved but unconfirmed and used seats. """
+        # initialize fields to 0
+        for event in self:
+            event.seats_unconfirmed = event.seats_reserved = event.seats_used = 0
+        # aggregate registrations by event and by state
+        if self.ids:
+            state_field = {
+                'draft': 'seats_unconfirmed',
+                'open':'seats_reserved',
+                'done': 'seats_used',
+            }
+            query = """ SELECT event_id, state, sum(nb_register)
+                        FROM event_registration
+                        WHERE event_id IN %s AND state IN ('draft', 'open', 'done')
+                        GROUP BY event_id, state
+                    """
+            self._cr.execute(query, (tuple(self.ids),))
+            for event_id, state, num in self._cr.fetchall():
+                event = self.browse(event_id)
+                event[state_field[state]] += num
+        # compute seats_available
+        for event in self:
+            event.seats_available = \
+                event.seats_max - (event.seats_reserved + event.seats_used) \
+                if event.seats_max > 0 else 0
+
+    registration_ids = fields.One2many('event.registration', 'event_id', string='Registrations',
+        readonly=False, states={'done': [('readonly', True)]})
+    count_registrations = fields.Integer(string='Registrations',
+        compute='_count_registrations')
+
+    date_begin = fields.Datetime(string='Start Date', required=True,
+        readonly=True, states={'draft': [('readonly', False)]})
+    date_end = fields.Datetime(string='End Date', required=True,
+        readonly=True, states={'draft': [('readonly', False)]})
+
+    @api.model
+    def _tz_get(self):
+        return [(x, x) for x in pytz.all_timezones]
+
+    date_tz = fields.Selection('_tz_get', string='Timezone',
+                        default=lambda self: self._context.get('tz', 'UTC'))
+
+    @api.one
+    @api.depends('date_tz', 'date_begin')
+    def _compute_date_begin_tz(self):
+        if self.date_begin:
+            self_in_tz = self.with_context(tz=(self.date_tz or 'UTC'))
+            date_begin = fields.Datetime.from_string(self.date_begin)
+            self.date_begin_located = fields.Datetime.to_string(fields.Datetime.context_timestamp(self_in_tz, date_begin))
+        else:
+            self.date_begin_located = False
+
+    @api.one
+    @api.depends('date_tz', 'date_end')
+    def _compute_date_end_tz(self):
+        if self.date_end:
+            self_in_tz = self.with_context(tz=(self.date_tz or 'UTC'))
+            date_end = fields.Datetime.from_string(self.date_end)
+            self.date_end_located = fields.Datetime.to_string(fields.Datetime.context_timestamp(self_in_tz, date_end))
+        else:
+            self.date_end_located = False
 
-    def _subscribe_fnc(self, cr, uid, ids, fields, args, context=None):
-        """This functional fields compute if the current user (uid) is already subscribed or not to the event passed in parameter (ids)
-        """
-        register_pool = self.pool.get('event.registration')
-        res = {}
-        for event in self.browse(cr, uid, ids, context=context):
-            res[event.id] = False
-            curr_reg_id = register_pool.search(cr, uid, [('user_id', '=', uid), ('event_id', '=' ,event.id)])
-            if curr_reg_id:
-                for reg in register_pool.browse(cr, uid, curr_reg_id, context=context):
-                    if reg.state in ('open','done'):
-                        res[event.id]= True
-                        continue
-        return res
+    date_begin_located = fields.Datetime(string='Start Date Located', compute='_compute_date_begin_tz')
+    date_end_located = fields.Datetime(string='End Date Located', compute='_compute_date_end_tz')
 
-    _columns = {
-        'name': fields.char('Name', size=64, required=True, translate=True, readonly=False, states={'done': [('readonly', True)]}),
-        'user_id': fields.many2one('res.users', 'Responsible User', readonly=False, states={'done': [('readonly', True)]}),
-        'type': fields.many2one('event.type', 'Type of Event', readonly=False, states={'done': [('readonly', True)]}),
-        '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)]}),
-        '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)]}),
-        'register_current': fields.function(_get_register, string='Confirmed Registrations', multi='register_numbers'),
-        'register_avail': fields.function(_get_register, string='Available Registrations', multi='register_numbers',type='integer'),
-        'register_prospect': fields.function(_get_register, string='Unconfirmed Registrations', multi='register_numbers'),
-        'register_attended': fields.function(_get_register, string='# of Participations', multi='register_numbers'),
-        'registration_ids': fields.one2many('event.registration', 'event_id', 'Registrations', readonly=False, states={'done': [('readonly', True)]}),
-        'date_begin': fields.datetime('Start Date', required=True, readonly=True, states={'draft': [('readonly', False)]}),
-        'date_end': fields.datetime('End Date', required=True, readonly=True, states={'draft': [('readonly', False)]}),
-        'state': fields.selection([
+    state = fields.Selection([
             ('draft', 'Unconfirmed'),
             ('cancel', 'Cancelled'),
             ('confirm', 'Confirmed'),
-            ('done', 'Done')],
-            'Status', readonly=True, required=True,
-            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\'.'),
-        '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.'),
-        '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."),
-        '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."),
-        '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."),
-        'address_id': fields.many2one('res.partner','Location Address', readonly=False, states={'done': [('readonly', True)]}),
-        'street': fields.related('address_id','street',type='char',string='Street'),
-        'zip': fields.related('address_id','zip',type='char',string='zip'),
-        'city': fields.related('address_id','city',type='char',string='city'),
-        'speaker_confirmed': fields.boolean('Speaker Confirmed', readonly=False, states={'done': [('readonly', True)]}),
-        'country_id': fields.related('address_id', 'country_id',
-                    type='many2one', relation='res.country', string='Country', readonly=False, states={'done': [('readonly', True)]}),
-        'note': fields.text('Description', readonly=False, states={'done': [('readonly', True)]}),
-        'company_id': fields.many2one('res.company', 'Company', required=False, change_default=True, readonly=False, states={'done': [('readonly', True)]}),
-        'is_subscribed' : fields.function(_subscribe_fnc, type="boolean", string='Subscribed'),
-    }
-    _defaults = {
-        'state': 'draft',
-        'company_id': lambda self,cr,uid,c: self.pool.get('res.company')._company_default_get(cr, uid, 'event.event', context=c),
-        'user_id': lambda obj, cr, uid, context: uid,
-    }
-    def subscribe_to_event(self, cr, uid, ids, context=None):
-        register_pool = self.pool.get('event.registration')
-        user_pool = self.pool.get('res.users')
-        num_of_seats = int(context.get('ticket', 1))
-        self.check_registration_limits_before(cr, uid, ids, num_of_seats, context=context)
-        user = user_pool.browse(cr, uid, uid, context=context)
-        curr_reg_ids = register_pool.search(cr, uid, [('user_id', '=', user.id), ('event_id', '=' , ids[0])])
-        #the subscription is done with SUPERUSER_ID because in case we share the kanban view, we want anyone to be able to subscribe
-        if not curr_reg_ids:
-            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})]
+            ('done', 'Done')
+        ], string='Status', default='draft', readonly=True, required=True, copy=False,
+        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'.")
+    email_registration_id = fields.Many2one(
+        'email.template', string='Registration Confirmation Email',
+        domain=[('model', '=', 'event.registration')],
+        help='This field contains the template of the mail that will be automatically sent each time a registration for this event is confirmed.')
+    email_confirmation_id = fields.Many2one(
+        'email.template', string='Event Confirmation Email',
+        domain=[('model', '=', 'event.registration')],
+        help="If you set an email template, each participant will receive this email announcing the confirmation of the event.")
+    reply_to = fields.Char(string='Reply-To Email',
+        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.")
+    address_id = fields.Many2one('res.partner', string='Location',
+        default=lambda self: self.env.user.company_id.partner_id,
+        readonly=False, states={'done': [('readonly', True)]})
+    country_id = fields.Many2one('res.country', string='Country', related='address_id.country_id',
+        store=True, readonly=False, states={'done': [('readonly', True)]})
+    description = fields.Html(string='Description', oldname='note', translate=True,
+        readonly=False, states={'done': [('readonly', True)]})
+    company_id = fields.Many2one('res.company', string='Company', change_default=True,
+        default=lambda self: self.env['res.company']._company_default_get('event.event'),
+        required=False, readonly=False, states={'done': [('readonly', True)]})
+    organizer_id = fields.Many2one('res.partner', string='Organizer',
+        default=lambda self: self.env.user.company_id.partner_id)
+
+    is_subscribed = fields.Boolean(string='Subscribed',
+        compute='_compute_subscribe')
+
+    @api.one
+    @api.depends('registration_ids')
+    def _count_registrations(self):
+        self.count_registrations = len(self.registration_ids)
+
+    @api.one
+    @api.depends('registration_ids.user_id', 'registration_ids.state')
+    def _compute_subscribe(self):
+        """ Determine whether the current user is already subscribed to any event in `self` """
+        user = self.env.user
+        self.is_subscribed = any(
+            reg.user_id == user and reg.state in ('open', 'done')
+            for reg in self.registration_ids
+        )
+
+    @api.multi
+    @api.depends('name', 'date_begin', 'date_end')
+    def name_get(self):
+        result = []
+        for event in self:
+            dates = [dt.split(' ')[0] for dt in [event.date_begin, event.date_end] if dt]
+            dates = sorted(set(dates))
+            result.append((event.id, '%s (%s)' % (event.name, ' - '.join(dates))))
+        return result
+
+    @api.one
+    @api.constrains('seats_max', 'seats_available')
+    def _check_seats_limit(self):
+        if self.seats_max and self.seats_available < 0:
+            raise Warning(_('No more available seats.'))
+
+    @api.one
+    @api.constrains('date_begin', 'date_end')
+    def _check_closing_date(self):
+        if self.date_end < self.date_begin:
+            raise Warning(_('Closing Date cannot be set before Beginning Date.'))
+
+    @api.one
+    def button_draft(self):
+        self.state = 'draft'
+
+    @api.one
+    def button_cancel(self):
+        for event_reg in self.registration_ids:
+            if event_reg.state == 'done':
+                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."))
+        self.registration_ids.write({'state': 'cancel'})
+        self.state = 'cancel'                
+
+    @api.one
+    def button_done(self):
+        self.state = 'done'
+
+    @api.one
+    def confirm_event(self):
+        if self.email_confirmation_id:
+            # send reminder that will confirm the event for all the people that were already confirmed
+            regs = self.registration_ids.filtered(lambda reg: reg.state not in ('draft', 'cancel'))
+            regs.mail_user_confirm()
+        self.state = 'confirm'
+
+    @api.one
+    def button_confirm(self):
+        """ Confirm Event and send confirmation email to all register peoples """
+        self.confirm_event()
+
+    @api.one
+    def subscribe_to_event(self):
+        """ Subscribe the current user to a given event """
+        user = self.env.user
+        num_of_seats = int(self._context.get('ticket', 1))
+        regs = self.registration_ids.filtered(lambda reg: reg.user_id == user)
+        # the subscription is done as SUPERUSER_ID because in case we share the
+        # kanban view, we want anyone to be able to subscribe
+        if not regs:
+            regs = regs.sudo().create({
+                'event_id': self.id,
+                'email': user.email,
+                'name': user.name,
+                'user_id': user.id,
+                'nb_register': num_of_seats,
+            })
         else:
-            register_pool.write(cr, uid, curr_reg_ids, {'nb_register': num_of_seats}, context=context)
-        return register_pool.confirm_registration(cr, SUPERUSER_ID, curr_reg_ids, context=context)
-
-    def unsubscribe_to_event(self, cr, uid, ids, context=None):
-        register_pool = self.pool.get('event.registration')
-        #the unsubscription is done with SUPERUSER_ID because in case we share the kanban view, we want anyone to be able to unsubscribe
-        curr_reg_ids = register_pool.search(cr, SUPERUSER_ID, [('user_id', '=', uid), ('event_id', '=', ids[0])])
-        return register_pool.button_reg_cancel(cr, SUPERUSER_ID, curr_reg_ids, context=context)
-
-    def _check_closing_date(self, cr, uid, ids, context=None):
-        for event in self.browse(cr, uid, ids, context=context):
-            if event.date_end < event.date_begin:
-                return False
-        return True
-
-    _constraints = [
-        (_check_closing_date, 'Error ! Closing Date cannot be set before Beginning Date.', ['date_end']),
-    ]
-    def onchange_event_type(self, cr, uid, ids, type_event, context=None):
-        if type_event:
-            type_info =  self.pool.get('event.type').browse(cr,uid,type_event,context)
-            dic ={
-              'reply_to': type_info.default_reply_to,
-              'email_registration_id': type_info.default_email_registration.id,
-              'email_confirmation_id': type_info.default_email_event.id,
-              'register_min': type_info.default_registration_min,
-              'register_max': type_info.default_registration_max,
-            }
-            return {'value': dic}
-
-    # ----------------------------------------
-    # OpenChatter methods and notifications
-    # ----------------------------------------
-
-    def create_send_note(self, cr, uid, ids, context=None):
-        message = _("Event has been <b>created</b>.")
-        self.message_post(cr, uid, ids, body=message, subtype="new", context=context)
-        return True
-
-    def button_cancel_send_note(self, cr, uid, ids, context=None):
-        message = _("Event has been <b>cancelled</b>.")
-        self.message_post(cr, uid, ids, body=message, subtype="cancel", context=context)
-        return True
-
-    def button_draft_send_note(self, cr, uid, ids, context=None):
-        message = _("Event has been set to <b>draft</b>.")
-        self.message_post(cr, uid, ids, body=message, subtype="new", context=context)
-        return True
-
-    def button_done_send_note(self, cr, uid, ids, context=None):
-        message = _("Event has been <b>done</b>.")
-        self.message_post(cr, uid, ids, body=message, subtype="close", context=context)
-        return True
-
-    def button_confirm_send_note(self, cr, uid, ids, context=None):
-        message = _("Event has been <b>confirmed</b>.")
-        self.message_post(cr, uid, ids, body=message, subtype="confirm", context=context)
-        return True
-
-event_event()
-
-class event_registration(osv.osv):
-    """Event Registration"""
-    _name= 'event.registration'
-    _description = __doc__
-    _inherit = ['ir.needaction_mixin','mail.thread']
-    _columns = {
-        'id': fields.integer('ID'),
-        'origin': fields.char('Source', size=124,readonly=True,help="Name of the sale order which create the registration"),
-        'nb_register': fields.integer('Number of Participants', required=True, readonly=True, states={'draft': [('readonly', False)]}),
-        'event_id': fields.many2one('event.event', 'Event', required=True, readonly=True, states={'draft': [('readonly', False)]}),
-        'partner_id': fields.many2one('res.partner', 'Partner', states={'done': [('readonly', True)]}),
-        'create_date': fields.datetime('Creation Date' , readonly=True),
-        'date_closed': fields.datetime('Attended Date', readonly=True),
-        'date_open': fields.datetime('Registration Date', readonly=True),
-        'reply_to': fields.related('event_id','reply_to',string='Reply-to Email', type='char', size=128, readonly=True,),
-        'log_ids': fields.one2many('mail.message', 'res_id', 'Logs', domain=[('email_from', '=', False),('model','=',_name)]),
-        'event_end_date': fields.related('event_id','date_end', type='datetime', string="Event End Date", readonly=True),
-        'event_begin_date': fields.related('event_id', 'date_begin', type='datetime', string="Event Start Date", readonly=True),
-        'user_id': fields.many2one('res.users', 'User', states={'done': [('readonly', True)]}),
-        'company_id': fields.related('event_id', 'company_id', type='many2one', relation='res.company', string='Company', store=True, readonly=True, states={'draft':[('readonly',False)]}),
-        'state': fields.selection([('draft', 'Unconfirmed'),
-                                    ('cancel', 'Cancelled'),
-                                    ('open', 'Confirmed'),
-                                    ('done', 'Attended')], 'Status',
-                                    size=16, readonly=True),
-        'email': fields.char('Email', size=64),
-        'phone': fields.char('Phone', size=64),
-        'name': fields.char('Name', size=128, select=True),
-    }
-
-    _defaults = {
-        'nb_register': 1,
-        'state': 'draft',
-    }
+            regs.write({'nb_register': num_of_seats})
+        regs.sudo().confirm_registration()
+
+    @api.one
+    def unsubscribe_to_event(self):
+        """ Unsubscribe the current user from a given event """
+        # the unsubscription is done as SUPERUSER_ID because in case we share
+        # the kanban view, we want anyone to be able to unsubscribe
+        user = self.env.user
+        regs = self.sudo().registration_ids.filtered(lambda reg: reg.user_id == user)
+        regs.button_reg_cancel()
+
+    @api.onchange('type')
+    def _onchange_type(self):
+        if self.type:
+            self.reply_to = self.type.default_reply_to
+            self.email_registration_id = self.type.default_email_registration
+            self.email_confirmation_id = self.type.default_email_event
+            self.seats_min = self.type.default_registration_min
+            self.seats_max = self.type.default_registration_max
+
+    @api.multi
+    def action_event_registration_report(self):
+        res = self.env['ir.actions.act_window'].for_xml_id('event', 'action_report_event_registration')
+        res['context'] = {
+            "search_default_event_id": self.id,
+            "group_by": ['event_date:day'],
+        }
+        return res
+
+
+class event_registration(models.Model):
+    _name = 'event.registration'
+    _description = 'Event Registration'
+    _inherit = ['mail.thread', 'ir.needaction_mixin']
     _order = 'name, create_date desc'
 
-    def do_draft(self, cr, uid, ids, context=None):
-        self.do_draft_send_note(cr, uid, ids, context=context)
-        return self.write(cr, uid, ids, {'state': 'draft'}, context=context)
-
-    def confirm_registration(self, cr, uid, ids, context=None):
-        self.message_post(cr, uid, ids, body=_('State set to open'), context=context)
-        return self.write(cr, uid, ids, {'state': 'open'}, subtype="open", context=context)
-
-    def create(self, cr, uid, vals, context=None):
-        obj_id = super(event_registration, self).create(cr, uid, vals, context)
-        self.create_send_note(cr, uid, [obj_id], context=context)
-        return obj_id
-
-    def registration_open(self, cr, uid, ids, context=None):
-        """ Open Registration
-        """
-        event_obj = self.pool.get('event.event')
-        for register in  self.browse(cr, uid, ids, context=context):
-            event_id = register.event_id.id
-            no_of_registration = register.nb_register
-            event_obj.check_registration_limits_before(cr, uid, [event_id], no_of_registration, context=context)
-        res = self.confirm_registration(cr, uid, ids, context=context)
-        self.mail_user(cr, uid, ids, context=context)
-        return res
+    origin = fields.Char(string='Source Document', readonly=True,
+        help="Reference of the sales order which created the registration")
+    nb_register = fields.Integer(string='Number of Participants', required=True, default=1,
+        readonly=True, states={'draft': [('readonly', False)]})
+    event_id = fields.Many2one('event.event', string='Event', required=True,
+        readonly=True, states={'draft': [('readonly', False)]})
+    partner_id = fields.Many2one('res.partner', string='Partner',
+        states={'done': [('readonly', True)]})
+    date_open = fields.Datetime(string='Registration Date', readonly=True)
+    date_closed = fields.Datetime(string='Attended Date', readonly=True)
+    reply_to = fields.Char(string='Reply-to Email', related='event_id.reply_to',
+        readonly=True)
+    log_ids = fields.One2many('mail.message', 'res_id', string='Logs',
+        domain=[('model', '=', _name)])
+    event_begin_date = fields.Datetime(string="Event Start Date", related='event_id.date_begin',
+        readonly=True)
+    event_end_date = fields.Datetime(string="Event End Date", related='event_id.date_end',
+        readonly=True)
+    user_id = fields.Many2one('res.users', string='User', states={'done': [('readonly', True)]})
+    company_id = fields.Many2one('res.company', string='Company', related='event_id.company_id',
+        store=True, readonly=True, states={'draft':[('readonly', False)]})
+    state = fields.Selection([
+            ('draft', 'Unconfirmed'),
+            ('cancel', 'Cancelled'),
+            ('open', 'Confirmed'),
+            ('done', 'Attended'),
+        ], string='Status', default='draft', readonly=True, copy=False)
+    email = fields.Char(string='Email')
+    phone = fields.Char(string='Phone')
+    name = fields.Char(string='Name', select=True)
+
+    @api.one
+    @api.constrains('event_id', 'state', 'nb_register')
+    def _check_seats_limit(self):
+        if self.event_id.seats_max and \
+            self.event_id.seats_available < (self.nb_register if self.state == 'draft' else 0):
+                raise Warning(_('No more available seats.'))
+
+    @api.one
+    def do_draft(self):
+        self.state = 'draft'
+
+    @api.one
+    def confirm_registration(self):
+        self.event_id.message_post(
+            body=_('New registration confirmed: %s.') % (self.name or ''),
+            subtype="event.mt_event_registration")
+        self.message_post(body=_('Event Registration confirmed.'))
+        self.state = 'open'
+
+    @api.one
+    def registration_open(self):
+        """ Open Registration """
+        self.confirm_registration()
+        self.mail_user()
+
+    @api.one
+    def button_reg_close(self):
+        """ Close Registration """
+        today = fields.Datetime.now()
+        if self.event_id.date_begin <= today:
+            self.write({'state': 'done', 'date_closed': today})
+        else:
+            raise Warning(_("You must wait for the starting day of the event to do this action."))
+
+    @api.one
+    def button_reg_cancel(self):
+        self.state = 'cancel'
 
-    def button_reg_close(self, cr, uid, ids, context=None):
-        """ Close Registration
-        """
-        if context is None:
-            context = {}
-        today = fields.datetime.now()
-        for registration in self.browse(cr, uid, ids, context=context):
-            if today >= registration.event_id.date_begin:
-                values = {'state': 'done', 'date_closed': today}
-                self.write(cr, uid, ids, values)
-                self.message_post(cr, uid, ids, body=_('State set to Done'), subtype="close", context=context)
-            else:
-                raise osv.except_osv(_('Error!'),_("You must wait for the starting day of the event to do this action.") )
-        return True
-
-    def button_reg_cancel(self, cr, uid, ids, context=None, *args):
-        self.message_post(cr, uid, ids, body=_('State set to Cancel'), subtype="cancel", context=context)
-        return self.write(cr, uid, ids, {'state': 'cancel'})
-
-    def mail_user(self, cr, uid, ids, context=None):
-        """
-        Send email to user with email_template when registration is done
-        """
-        for registration in self.browse(cr, uid, ids, context=context):
-            if registration.event_id.state == 'confirm' and registration.event_id.email_confirmation_id.id:
-                self.mail_user_confirm(cr, uid, ids, context=context)
-            else:
-                template_id = registration.event_id.email_registration_id.id
-                if template_id:
-                    mail_message = self.pool.get('email.template').send_mail(cr,uid,template_id,registration.id)
-        return True
-
-    def mail_user_confirm(self, cr, uid, ids, context=None):
-        """
-        Send email to user when the event is confirmed
-        """
-        for registration in self.browse(cr, uid, ids, context=context):
-            template_id = registration.event_id.email_confirmation_id.id
-            if template_id:
-                mail_message = self.pool.get('email.template').send_mail(cr,uid,template_id,registration.id)
-        return True
-
-    def onchange_contact_id(self, cr, uid, ids, contact, partner, context=None):
-        if not contact:
-            return {}
-        addr_obj = self.pool.get('res.partner')
-        contact_id =  addr_obj.browse(cr, uid, contact, context=context)
-        return {'value': {
-            'email':contact_id.email,
-            'name':contact_id.name,
-            'phone':contact_id.phone,
-            }}
-
-    def onchange_event(self, cr, uid, ids, event_id, context=None):
-        """This function returns value of Product Name, Unit Price based on Event.
-        """
-        if context is None:
-            context = {}
-        if not event_id:
-            return {}
-        event_obj = self.pool.get('event.event')
-        data_event =  event_obj.browse(cr, uid, event_id, context=context)
-        return {'value':
-                    {'event_begin_date': data_event.date_begin,
-                     'event_end_date': data_event.date_end,
-                     'company_id': data_event.company_id and data_event.company_id.id or False,
-                    }
-               }
-
-    def onchange_partner_id(self, cr, uid, ids, part, context=None):
-        res_obj = self.pool.get('res.partner')
-        data = {}
-        if not part:
-            return {'value': data}
-        addr = res_obj.address_get(cr, uid, [part]).get('default', False)
-        if addr:
-            d = self.onchange_contact_id(cr, uid, ids, addr, part, context)
-            data.update(d['value'])
-        return {'value': data}
-
-    # ----------------------------------------
-    # OpenChatter methods and notifications
-    # ----------------------------------------
-
-    def create_send_note(self, cr, uid, ids, context=None):
-        message = _("Registration has been <b>created</b>.")
-        self.message_post(cr, uid, ids, body=message, subtype="new", context=context)
-        return True
-
-    def do_draft_send_note(self, cr, uid, ids, context=None):
-        message = _("Registration has been set as <b>draft</b>.")
-        self.message_post(cr, uid, ids, body=message, subtype="new", context=context)
-        return True
-
-event_registration()
+    @api.one
+    def mail_user(self):
+        """Send email to user with email_template when registration is done """
+        if self.event_id.state == 'confirm' and self.event_id.email_confirmation_id:
+            self.mail_user_confirm()
+        else:
+            template = self.event_id.email_registration_id
+            if template:
+                mail_message = template.send_mail(self.id)
+
+    @api.one
+    def mail_user_confirm(self):
+        """Send email to user when the event is confirmed """
+        template = self.event_id.email_confirmation_id
+        if template:
+            mail_message = template.send_mail(self.id)
+
+    @api.onchange('partner_id')
+    def _onchange_partner(self):
+        if self.partner_id:
+            contact_id = self.partner_id.address_get().get('default', False)
+            if contact_id:
+                contact = self.env['res.partner'].browse(contact_id)
+                self.name = contact.name
+                self.email = contact.email
+                self.phone = contact.phone
 
 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: