[IMP] button_cancel if we done an even every registration will be done except if...
[odoo/odoo.git] / addons / event / event.py
1 # -*- coding: utf-8 -*-
2 ##############################################################################
3 #
4 #    OpenERP, Open Source Management Solution
5 #    Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
6 #
7 #    This program is free software: you can redistribute it and/or modify
8 #    it under the terms of the GNU Affero General Public License as
9 #    published by the Free Software Foundation, either version 3 of the
10 #    License, or (at your option) any later version.
11 #
12 #    This program is distributed in the hope that it will be useful,
13 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
14 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 #    GNU Affero General Public License for more details.
16 #
17 #    You should have received a copy of the GNU Affero General Public License
18 #    along with this program.  If not, see <http://www.gnu.org/licenses/>.
19 #
20 ##############################################################################
21
22 import time
23
24 from crm import crm
25 from osv import fields, osv
26 from tools.translate import _
27 import decimal_precision as dp
28 from crm import wizard
29 import time
30
31
32 wizard.mail_compose_message.SUPPORTED_MODELS.append('event.registration')
33
34 class event_type(osv.osv):
35     """ Event Type """
36     _name = 'event.type'
37     _description = __doc__
38     _columns = {
39         'name': fields.char('Event type', size=64, required=True),
40         '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." ),
41         '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"),
42         '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"),
43         'default_registration_min': fields.integer('Default Minimum Registration', help="It will select this default minimum value when you choose this event"),
44         'default_registration_max': fields.integer('Default Maximum Registration', help="It will select this default maximum value when you choose this event"),
45     }
46     _defaults = {
47         'default_registration_min': 0,
48         'default_registration_max':0,
49         }
50
51 event_type()
52
53 class event_event(osv.osv):
54     """Event"""
55     _name = 'event.event'
56     _description = __doc__
57     _order = 'date_begin'
58
59     def name_get(self, cr, uid, ids, context=None):
60         if not ids:
61               return []
62         res = []
63         for record in self.browse(cr, uid, ids, context=context):
64             date = record.date_begin.split(" ")
65             date = date[0]
66             registers=''
67             if record.register_max !=0:
68                 register_max = str(record.register_max)
69                 register_tot = record.register_current+record.register_prospect
70                 register_tot = str(register_tot)
71                 registers = register_tot+'/'+register_max
72             name = record.name+' ('+date+') '+registers
73             res.append((record['id'], name))
74         return res
75
76     def _name_get_fnc(self, cr, uid, ids,prop,unknow, context=None):
77         res = self.name_get(cr, uid, ids, context=context)
78         return dict(res)
79
80     def copy(self, cr, uid, id, default=None, context=None):
81         """ Reset the state and the registrations while copying an event
82         """
83         if not default:
84             default = {}
85         default.update({
86             'state': 'draft',
87             'registration_ids': False,
88         })
89         return super(event_event, self).copy(cr, uid, id, default=default, context=context)
90
91     def button_draft(self, cr, uid, ids, context=None):
92         return self.write(cr, uid, ids, {'state': 'draft'}, context=context)
93
94     def button_cancel(self, cr, uid, ids, context=None):
95         registration = self.pool.get('event.registration')
96         reg_ids = registration.search(cr, uid, [('event_id','in',ids)], context=context)
97         for event_reg in registration.browse(cr,uid,reg_ids,context=context):
98             if event_reg.state == 'done':
99                 raise osv.except_osv(_('Error!'),_("You have already done a registration please reset to draft if you want to cancel this event") )
100                 return
101         registration.write(cr, uid, reg_ids, {'state': 'cancel'}, context=context)
102         return self.write(cr, uid, ids, {'state': 'cancel'}, context=context)
103
104     def button_done(self, cr, uid, ids, context=None):
105         return self.write(cr, uid, ids, {'state': 'done'}, context=context)
106
107     def button_confirm(self, cr, uid, ids, context=None):
108         """ Confirm Event and send confirmation email to all register peoples
109         """
110         if isinstance(ids, (int, long)):
111             ids = [ids]
112         #renforcing method : create a list of ids
113         register_pool = self.pool.get('event.registration')
114         for event in self.browse(cr, uid, ids, context=context):
115             total_confirmed = event.register_current
116             if total_confirmed < event.register_min or total_confirmed > event.register_max and event.register_max!=0:
117                 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") % (event.name))
118             if event.email_confirmation_id:
119                 #send reminder that will confirm the event for all the people that were already confirmed
120                 reg_ids = register_pool.search(cr, uid, [
121                                ('event_id', '=', event.id),
122                                ('state', 'not in', ['draft', 'cancel'])], context=context)
123                 register_pool.mail_user_confirm(cr, uid, reg_ids)
124         return self.write(cr, uid, ids, {'state': 'confirm'}, context=context)
125
126     def _get_register(self, cr, uid, ids, fields, args, context=None):
127         """Get Confirm or uncofirm register value.
128         @param ids: List of Event registration type's id
129         @param fields: List of function fields(register_current and register_prospect).
130         @param context: A standard dictionary for contextual values
131         @return: Dictionary of function fields value.
132         """
133         register_pool = self.pool.get('event.registration')
134         res = {}
135         for event in self.browse(cr, uid, ids, context=context):
136             res[event.id] = {}
137             for field in fields:
138                 res[event.id][field] = False
139             state = []
140             state_done = []
141             if 'register_current' in fields:
142                 state += ['open']
143             if 'register_prospect' in fields:
144                 state.append('draft')
145             reg_open_ids = register_pool.search(cr, uid, [('event_id', '=', event.id),('state', '=', 'open')], context=context)
146             reg_done_ids=  register_pool.search(cr, uid, [('event_id', '=', event.id),('state', '=', 'done')], context=context)
147             reg_draft_ids=  register_pool.search(cr, uid, [('event_id', '=', event.id),('state', '=', 'draft')], context=context)
148             res[event.id]['register_current'] = len(reg_open_ids)
149             res[event.id]['register_prospect'] = len(reg_done_ids)
150             res[event.id]['register_attended'] = len(reg_draft_ids)
151
152         return res
153
154     _columns = {
155         'name': fields.char('Event Name', size=64, required=True, translate=True, readonly=False, states={'done': [('readonly', True)]}),
156         'user_id': fields.many2one('res.users', 'Responsible User', readonly=False, states={'done': [('readonly', True)]}),
157         'type': fields.many2one('event.type', 'Type of Event', readonly=False, states={'done': [('readonly', True)]}),
158         '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)]}),
159         '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)]}),
160         'register_current': fields.function(_get_register, string='Confirmed Registrations', multi='register_current'),
161         'register_prospect': fields.function(_get_register, string='Unconfirmed Registrations', multi='register_prospect'),
162         'register_attended': fields.function(_get_register, string='Attended Registrations', multi='register_prospect'), 
163         'registration_ids': fields.one2many('event.registration', 'event_id', 'Registrations', readonly=False, states={'done': [('readonly', True)]}),
164         'date_begin': fields.datetime('Starting Date', required=True, readonly=True, states={'draft': [('readonly', False)]}),
165         'date_end': fields.datetime('Closing Date', required=True, readonly=True, states={'draft': [('readonly', False)]}),
166         'state': fields.selection([
167             ('draft', 'Draft'),
168             ('confirm', 'Confirmed'),
169             ('done', 'Done'),
170             ('cancel', 'Cancelled')],
171             'State', readonly=True, required=True,
172             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\'.'),
173         'email_registration_id' : fields.many2one('email.template','Registration Confirmation Email'),
174         '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."),
175         'full_name' : fields.function(_name_get_fnc, type="char", string='Name'),
176         '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."),
177         '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."),
178         'speaker_ids': fields.many2many('res.partner', 'event_speaker_rel', 'speaker_id', 'partner_id', 'Other Speakers', readonly=False, states={'done': [('readonly', True)]}),
179         'address_id': fields.many2one('res.partner.address','Location Address', readonly=False, states={'done': [('readonly', True)]}),
180         'speaker_confirmed': fields.boolean('Speaker Confirmed',help='You can choose this checkbox for your information => ca veut rien dire ca', readonly=False, states={'done': [('readonly', True)]}),
181         'country_id': fields.related('address_id', 'country_id',
182                     type='many2one', relation='res.country', string='Country', readonly=False, states={'done': [('readonly', True)]}),
183         'note': fields.text('Description', readonly=False, states={'done': [('readonly', True)]}),
184         'company_id': fields.many2one('res.company', 'Company', required=False, change_default=True, readonly=False, states={'done': [('readonly', True)]}),
185     }
186
187     _defaults = {
188         'state': 'draft',
189         'company_id': lambda self,cr,uid,c: self.pool.get('res.company')._company_default_get(cr, uid, 'event.event', context=c),
190         'user_id': lambda obj, cr, uid, context: uid,
191     }
192
193     def _check_closing_date(self, cr, uid, ids, context=None):
194         for event in self.browse(cr, uid, ids, context=context):
195             if event.date_end < event.date_begin:
196                 return False
197         return True
198
199     _constraints = [
200         (_check_closing_date, 'Error ! Closing Date cannot be set before Beginning Date.', ['date_end']),
201     ]
202
203     def onchange_evnet_type(self, cr, uid, ids, type_event, context=None):
204         if type_event:
205             type_info =  self.pool.get('event.type').browse(cr,uid,type_event,context)
206             dic ={
207               'reply_to':type_info.default_reply_to,
208               'email_registration_id':type_info.default_email_registration.id,
209               'email_confirmation_id':type_info.default_email_event.id,
210               'register_min':type_info.default_registration_min,
211               'register_max':type_info.default_registration_max,
212             }
213             res = {'value':dic}
214             return res
215 event_event()
216
217 class event_registration(osv.osv):
218     """Event Registration"""
219     _name= 'event.registration'
220     _description = __doc__
221     _inherit = ['mail.thread','res.partner.address']
222     _columns = {
223         'id': fields.integer('ID'),
224         'origin': fields.char('Origin', size=124,readonly=True,help="Name of the sale order which create the registration"),
225         'nb_register': fields.integer('Number of Participants', required=True, readonly=True, states={'draft': [('readonly', False)]}),
226         'event_id': fields.many2one('event.event', 'Event', required=True, readonly=True, states={'draft': [('readonly', False)]}),
227         'partner_id': fields.many2one('res.partner', 'Partner', states={'done': [('readonly', True)]}),
228         'partner_address_id': fields.many2one('res.partner.address', 'Partner', states={'done': [('readonly', True)]}),
229         "contact_id": fields.many2one('res.partner.address', 'Partner Contact', readonly=False, states={'done': [('readonly', True)]}),
230         'create_date': fields.datetime('Creation Date' , readonly=True),
231         'date_closed': fields.datetime('Attended Date', readonly=True),
232         'date_open': fields.datetime('Registration Date', readonly=True),
233         'reply_to': fields.related('event_id','reply_to',string='Reply-to Email', type='char', size=128, readonly=True,),
234         'log_ids': fields.one2many('mail.message', 'res_id', 'Logs', domain=[('email_from', '=', False),('model','=',_name)]),
235         'event_end_date': fields.related('event_id','date_end', type='datetime', string="Event End Date", readonly=True),
236         'event_begin_date': fields.related('event_id', 'date_begin', type='datetime', string="Event Start Date", readonly=True),
237         'user_id': fields.many2one('res.users', 'Responsible', states={'done': [('readonly', True)]}),
238         'company_id': fields.related('event_id', 'company_id', type='many2one', relation='res.company', string='Company', store=True, readonly=True, states={'draft':[('readonly',False)]}),
239         'state': fields.selection([('draft', 'Unconfirmed'),
240                                     ('open', 'Confirmed'),
241                                     ('cancel', 'Cancelled'),
242                                     ('done', 'Attended')], 'State',
243                                     size=16, readonly=True)
244     }
245
246     _defaults = {
247         'nb_register': 1,
248         'state': 'draft',
249         'user_id': lambda self, cr, uid, ctx: uid,
250     }
251     _order = 'create_date desc'
252
253
254     def do_draft(self, cr, uid, ids, context=None):
255         return self.write(cr, uid, ids, {'state': 'draft'}, context=context)
256
257     def registration_open(self, cr, uid, ids, context=None):
258         """ Open Registration
259         """
260         res = self.write(cr, uid, ids, {'state': 'open'}, context=context)
261         self.mail_user(cr, uid, ids)
262         self.message_append(cr, uid, ids,_('Statut'),body_text= _('Open'))
263         return res
264
265     def case_close(self, cr, uid, ids, context=None):
266         """ Close Registration
267         """
268         if context is None:
269             context = {}
270         values = {'state': 'done', 'date_closed': time.strftime('%Y-%m-%d %H:%M:%S')}
271         res = self.write(cr, uid, ids, values)
272         self.message_append(cr, uid, ids,_('Statut'),body_text= _('Done'))
273         return res
274
275     # event uses add_note wizard from crm, which expects case_* methods
276     def case_open(self, cr, uid, ids, context):
277         return self.registration_open(cr, uid, ids, context)
278
279     # event uses add_note wizard from crm, which expects case_* methods
280     def case_cancel(self, cr, uid, ids, context=None):
281         """ Cancel Registration
282         """
283         self.message_append(cr, uid, ids,_('Statut'),body_text= _('Cancel'))
284         return self.write(cr, uid, ids, {'state': 'cancel'})
285
286     def button_reg_close(self, cr, uid, ids, context=None):
287         """This Function Close Event Registration.
288         """
289         return self.case_close(cr, uid, ids)
290
291     def button_reg_cancel(self, cr, uid, ids, context=None, *args):
292         return self.case_cancel(cr, uid, ids)
293
294     def mail_user(self, cr, uid, ids, confirm=False, context=None):
295         """
296         Send email to user with email_template when registration is done
297         """
298         for registration in self.browse(cr, uid, ids, context=context):
299             template_id = registration.event_id.email_registration_id.id
300             if template_id:
301                 mail_message = self.pool.get('email.template').send_mail(cr,uid,template_id,registration.id)
302         return True
303
304     def mail_user_confirm(self, cr, uid, ids, context=None):
305         """
306         Send email to user when the event is done
307         """
308         for registration in self.browse(cr, uid, ids, context=context):
309             template_id = registration.event_id.email_confirmation_id.id
310             if template_id:
311                 mail_message = self.pool.get('email.template').send_mail(cr,uid,template_id,registration.id)
312         return True
313
314     def onchange_contact_id(self, cr, uid, ids, contact, partner, context=None):
315         data ={}
316         if not contact:
317             return data
318         addr_obj = self.pool.get('res.partner.address')
319         contact_id =  addr_obj.browse(cr, uid, contact, context=context)
320         data = {
321             'email':contact_id.email,
322             'contact_id':contact_id.id,
323             'name':contact_id.name,
324             'phone':contact_id.phone,
325             }
326         return {'value': data}
327
328     def onchange_event(self, cr, uid, ids, event_id, context=None):
329         """This function returns value of Product Name, Unit Price based on Event.
330         """
331         if context is None:
332             context = {}
333         if not event_id:
334             return {}
335         event_obj = self.pool.get('event.event')
336         data_event =  event_obj.browse(cr, uid, event_id, context=context)
337         return {'value': 
338                     {'event_begin_date': data_event.date_begin,
339                      'event_end_date': data_event.date_end,
340                      'company_id': data_event.company_id and data_event.company_id.id or False,
341                     }
342                }
343
344     def onchange_partner_id(self, cr, uid, ids, part, context=None):
345         res_obj = self.pool.get('res.partner')
346         data = {}
347         if not part:
348             return {'value': data}
349         addr = res_obj.address_get(cr, uid, [part]).get('default', False)
350         if addr:
351             d = self.onchange_contact_id(cr, uid, ids, addr, part, context)
352             data.update(d['value'])
353         return {'value': data}
354
355 event_registration()
356 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: