[MERGE] Forward-port of latest 7.0 bugfixes, up to rev. 9846 revid:dle@openerp.com...
[odoo/odoo.git] / addons / event / event.py
index 02d2b58..72894ea 100644 (file)
 #
 ##############################################################################
 
-import time
-from osv import fields, osv
-from tools.translate import _
-import decimal_precision as dp
+from datetime import datetime, timedelta
+from openerp.osv import fields, osv
+from openerp.tools.translate import _
+from openerp import SUPERUSER_ID
 
 class event_type(osv.osv):
     """ Event Type """
@@ -38,44 +38,34 @@ class event_type(osv.osv):
     }
     _defaults = {
         'default_registration_min': 0,
-        'default_registration_max':0,
-        }
+        'default_registration_max': 0,
+    }
 
-event_type()
 
 class event_event(osv.osv):
     """Event"""
     _name = 'event.event'
     _description = __doc__
     _order = 'date_begin'
-    _inherit = ['ir.needaction_mixin','mail.thread']
+    _inherit = ['mail.thread', 'ir.needaction_mixin']
 
     def name_get(self, cr, uid, ids, context=None):
         if not ids:
-              return []
+            return []
+
+        if isinstance(ids, (long, int)):
+            ids = [ids]
+
         res = []
         for record in self.browse(cr, uid, ids, context=context):
-            date = record.date_begin.split(" ")
-            date = date[0]
-            registers=''
-            if record.register_max !=0:
-                register_max = str(record.register_max)
-                register_tot = record.register_current+record.register_prospect
-                register_tot = str(register_tot)
-                registers = register_tot+'/'+register_max
-            name = record.name+' ('+date+') '+registers
-            res.append((record['id'], name))
+            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 _name_get_fnc(self, cr, uid, ids,prop,unknow, context=None):
-        res = self.name_get(cr, uid, ids, context=context)
-        return dict(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
         """
@@ -88,7 +78,6 @@ class event_event(osv.osv):
         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):
@@ -98,19 +87,24 @@ class event_event(osv.osv):
             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):
-        register_pool = self.pool.get('event.registration')
         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. You should maybe reconsider those limits before going further") % (self.event.name))
+                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')
@@ -128,7 +122,6 @@ class event_event(osv.osv):
         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):
@@ -138,7 +131,6 @@ class event_event(osv.osv):
         @param context: A standard dictionary for contextual values
         @return: Dictionary of function fields value.
         """
-        register_pool = self.pool.get('event.registration')
         res = {}
         for event in self.browse(cr, uid, ids, context=context):
             res[event.id] = {}
@@ -159,7 +151,7 @@ class event_event(osv.osv):
                 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. 
+                    #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
@@ -178,7 +170,13 @@ class event_event(osv.osv):
                     if reg.state in ('open','done'):
                         res[event.id]= True
                         continue
-        return res 
+        return res
+
+    def _get_visibility_selection(self, cr, uid, context=None):
+        return [('public', 'All Users'),
+                ('employees', 'Employees Only')]
+    # Lambda indirection method to avoid passing a copy of the overridable method when declaring the field
+    _visibility_selection = lambda self, *args, **kwargs: self._get_visibility_selection(*args, **kwargs)
 
     _columns = {
         'name': fields.char('Name', size=64, required=True, translate=True, readonly=False, states={'done': [('readonly', True)]}),
@@ -189,7 +187,7 @@ class event_event(osv.osv):
         '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='Attended 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)]}),
@@ -198,44 +196,54 @@ class event_event(osv.osv):
             ('cancel', 'Cancelled'),
             ('confirm', 'Confirmed'),
             ('done', 'Done')],
-            'State', 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\'.'),
+            'Status', readonly=True, required=True,
+            track_visibility='onchange',
+            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','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."),
-        'full_name' : fields.function(_name_get_fnc, type="char", string='Name'),
         '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."),
-        'speaker_ids': fields.many2many('res.partner', 'event_speaker_rel', 'speaker_id', 'partner_id', 'Other Speakers', readonly=False, states={'done': [('readonly', True)]}),
         'address_id': fields.many2one('res.partner','Location Address', readonly=False, states={'done': [('readonly', True)]}),
+        'street': fields.related('address_id','street',type='char',string='Street'),
+        'street2': fields.related('address_id','street2',type='char',string='Street2'),
+        'state_id': fields.related('address_id','state_id',type='many2one', relation="res.country.state", string='State'),
+        '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'),
+        'visibility': fields.selection(_visibility_selection, 'Privacy / Visibility',
+            select=True, required=True),
     }
-
     _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,
+        'visibility': 'employees',
     }
 
     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 UID = 1 because in case we share the kanban view, we want anyone to be able to subscribe
+        #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, 1, {'event_id': ids[0] ,'email': user.user_email, 'name':user.name, 'user_id': user.id,})]
-        return register_pool.confirm_registration(cr, 1, curr_reg_ids, context=context)
+            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})]
+        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 UID = 1 because in case we share the kanban view, we want anyone to be able to unsubscribe
-        curr_reg_ids = register_pool.search(cr, 1, [('user_id', '=', uid), ('event_id', '=', ids[0])])
-        return register_pool.button_reg_cancel(cr, 1, curr_reg_ids, context=context)
+        #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):
@@ -248,6 +256,7 @@ class event_event(osv.osv):
     ]
 
     def onchange_event_type(self, cr, uid, ids, type_event, context=None):
+        values = {}
         if type_event:
             type_info =  self.pool.get('event.type').browse(cr,uid,type_event,context)
             dic ={
@@ -257,54 +266,43 @@ class event_event(osv.osv):
               'register_min': type_info.default_registration_min,
               'register_max': type_info.default_registration_max,
             }
-            return {'value': dic}
-        
-    # ----------------------------------------
-    # OpenChatter methods and notifications
-    # ----------------------------------------
-
-    def get_needaction_user_ids(self, cr, uid, ids, context=None):
-        result = dict.fromkeys(ids, [])
-        for obj in self.browse(cr, uid, ids, context=context):
-            if obj.state == 'draft' and obj.user_id:
-                result[obj.id] = [obj.user_id.id]
-        return result
-
-    def create_send_note(self, cr, uid, ids, context=None):
-        message = _("Event has been <b>created</b>.")
-        self.message_append_note(cr, uid, ids, body=message, context=context)
-        return True
-
-    def button_cancel_send_note(self, cr, uid, ids, context=None):
-        message = _("Event has been <b>cancelled</b>.")
-        self.message_append_note(cr, uid, ids, body=message, 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_append_note(cr, uid, ids, body=message, context=context)
-        return True
-
-    def button_done_send_note(self, cr, uid, ids, context=None):
-        message = _("Event has been <b>done</b>.")
-        self.message_append_note(cr, uid, ids, body=message, context=context)
-        return True
-
-    def button_confirm_send_note(self, cr, uid, ids, context=None):
-        message = _("Event has been <b>confirmed</b>.")
-        self.message_append_note(cr, uid, ids, body=message, context=context)
-        return True
+            values.update(dic)
+        return values
+
+    def on_change_address_id(self, cr, uid, ids, address_id, context=None):
+        values = {}
+        if not address_id:
+            return values
+        address = self.pool.get('res.partner').browse(cr, uid, address_id, context=context)
+        values.update({
+            'street' : address.street,
+            'street2' : address.street2,
+            'city' : address.city,
+            'country_id' : address.country_id and address.country_id.id or False,
+            'state_id' : address.state_id and address.state_id.id or False,
+            'zip' : address.zip,
+        })
+        return {'value' : values}
+
+    def onchange_start_date(self, cr, uid, ids, date_begin=False, date_end=False, context=None):
+        res = {'value':{}}
+        if date_end:
+            return res
+        if date_begin and isinstance(date_begin, str):
+            date_begin = datetime.strptime(date_begin, "%Y-%m-%d %H:%M:%S")
+            date_end = date_begin + timedelta(hours=1)
+            res['value'] = {'date_end': date_end.strftime("%Y-%m-%d %H:%M:%S")}
+        return res
 
-event_event()
 
 class event_registration(osv.osv):
     """Event Registration"""
     _name= 'event.registration'
     _description = __doc__
-    _inherit = ['ir.needaction_mixin','mail.thread','res.partner']
+    _inherit = ['mail.thread', 'ir.needaction_mixin']
     _columns = {
         'id': fields.integer('ID'),
-        'origin': fields.char('Origin', size=124,readonly=True,help="Name of the sale order which create the registration"),
+        'origin': fields.char('Source Document', size=124,readonly=True,help="Reference of the sales order which created 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)]}),
@@ -312,41 +310,43 @@ class event_registration(osv.osv):
         '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)]),
+        'log_ids': fields.one2many('mail.message', 'res_id', 'Logs', domain=[('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', 'Attendee', states={'done': [('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')], 'State',
+                                    ('done', 'Attended')], 'Status',
+                                    track_visibility='onchange',
                                     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',
     }
     _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_append(cr, uid, ids,_('State set to open'),body_text= _('Open'))
+        for reg in self.browse(cr, uid, ids, context=context or {}):
+            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)
         return self.write(cr, uid, ids, {'state': '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
@@ -361,13 +361,11 @@ class event_registration(osv.osv):
             if today >= registration.event_id.date_begin:
                 values = {'state': 'done', 'date_closed': today}
                 self.write(cr, uid, ids, values)
-                self.message_append(cr, uid, ids, _('State set to Done'), body_text=_('Done'))
             else:
-                raise osv.except_osv(_('Error!'),_("You must wait the event starting day to do this action.") )
+                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_append(cr, uid, ids,_('State set to Cancel'),body_text= _('Cancel'))
         return self.write(cr, uid, ids, {'state': 'cancel'})
 
     def mail_user(self, cr, uid, ids, context=None):
@@ -394,34 +392,15 @@ class event_registration(osv.osv):
         return True
 
     def onchange_contact_id(self, cr, uid, ids, contact, partner, context=None):
-        data ={}
         if not contact:
-            return data
+            return {}
         addr_obj = self.pool.get('res.partner')
         contact_id =  addr_obj.browse(cr, uid, contact, context=context)
-        data = {
+        return {'value': {
             'email':contact_id.email,
-            'contact_id':contact_id.id,
             'name':contact_id.name,
             'phone':contact_id.phone,
-            }
-        return {'value': data}
-
-    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')
@@ -434,28 +413,4 @@ class event_registration(osv.osv):
             data.update(d['value'])
         return {'value': data}
 
-    # ----------------------------------------
-    # OpenChatter methods and notifications
-    # ----------------------------------------
-
-    def get_needaction_user_ids(self, cr, uid, ids, context=None):
-        result = dict.fromkeys(ids, [])
-        for obj in self.browse(cr, uid, ids, context=context):
-            if obj.state == 'draft' and obj.user_id:
-                result[obj.id] = [obj.user_id.id]
-        return result
-
-    def create_send_note(self, cr, uid, ids, context=None):
-        message = _("Registration has been <b>created</b>.")
-        self.message_append_note(cr, uid, ids, body=message, 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_append_note(cr, uid, ids, body=message, context=context)
-        return True
-
-event_registration()
-
-
 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: