[IMP] Renaming fields
[odoo/odoo.git] / addons / event_sale / event_sale.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 from openerp.osv import fields, osv
23 from openerp.tools.translate import _
24
25 class product(osv.osv):
26     _inherit = 'product.template'
27     _columns = {
28         'event_ok': fields.boolean('Event Subscription', help='Determine if a product needs to create automatically an event registration at the confirmation of a sales order line.'),
29         'event_type_id': fields.many2one('event.type', 'Type of Event', help='Select event types so when we use this product in sales order lines, it will filter events of this type only.'),
30     }
31
32     def onchange_event_ok(self, cr, uid, ids, type, event_ok, context=None):
33         return {'value': {'type': event_ok and 'service' or type != 'service' and type or False}}
34
35
36 class sale_order_line(osv.osv):
37     _inherit = 'sale.order.line'
38     _columns = {
39         'event_id': fields.many2one('event.event', 'Event',
40             help="Choose an event and it will automatically create a registration for this event."),
41         'event_ticket_id': fields.many2one('event.event.ticket', 'Event Ticket',
42             help="Choose an event ticket and it will automatically create a registration for this event ticket."),
43         #those 2 fields are used for dynamic domains and filled by onchange
44         'event_type_id': fields.related('product_id','event_type_id', type='many2one', relation="event.type", string="Event Type"),
45         'event_ok': fields.related('product_id', 'event_ok', string='event_ok', type='boolean'),
46     }
47
48     def product_id_change(self, cr, uid, ids,
49                           pricelist, 
50                           product,
51                           qty=0,
52                           uom=False,
53                           qty_uos=0,
54                           uos=False,
55                           name='',
56                           partner_id=False,
57                           lang=False,
58                           update_tax=True,
59                           date_order=False,
60                           packaging=False,
61                           fiscal_position=False,
62                           flag=False, context=None):
63         """
64         check product if event type
65         """
66         res = super(sale_order_line,self).product_id_change(cr, uid, ids, pricelist, product, qty=qty, uom=uom, qty_uos=qty_uos, uos=uos, name=name, partner_id=partner_id, lang=lang, update_tax=update_tax, date_order=date_order, packaging=packaging, fiscal_position=fiscal_position, flag=flag, context=context)
67         if product:
68             product_res = self.pool.get('product.product').browse(cr, uid, product, context=context)
69             if product_res.event_ok:
70                 res['value'].update({'event_type_id': product_res.event_type_id.id, 'event_ok':product_res.event_ok})
71         return res
72
73     def button_confirm(self, cr, uid, ids, context=None):
74         '''
75         create registration with sales order
76         '''
77         if context is None:
78             context = {}
79         registration_obj = self.pool.get('event.registration')
80         for order_line in self.browse(cr, uid, ids, context=context):
81             if order_line.event_id:
82                 dic = {
83                     'name': order_line.order_id.partner_invoice_id.name,
84                     'partner_id': order_line.order_id.partner_id.id,
85                     'nb_register': int(order_line.product_uom_qty),
86                     'email': order_line.order_id.partner_id.email,
87                     'phone': order_line.order_id.partner_id.phone,
88                     'origin': order_line.order_id.name,
89                     'event_id': order_line.event_id.id,
90                     'event_ticket_id': order_line.event_ticket_id and order_line.event_ticket_id.id or None,
91                 }
92
93                 if order_line.event_ticket_id:
94                     if order_line.event_ticket_id.register_avail != 9999 and dic['nb_register'] > order_line.event_ticket_id.register_avail:
95                         raise osv.except_osv(_('Error!'), _('There are not enough tickets available (%s) for %s' % (order_line.event_ticket_id.register_avail, order_line.event_ticket_id.name)))
96                     message = _("The registration has been created for event <i>%s</i> with the ticket <i>%s</i> from the Sale Order %s. ") % (order_line.event_id.name, order_line.event_ticket_id.name, order_line.order_id.name)
97                 else:
98                     message = _("The registration has been created for event <i>%s</i> from the Sale Order %s. ") % (order_line.event_id.name, order_line.order_id.name)
99                 
100                 context.update({'mail_create_nolog': True})
101                 registration_id = registration_obj.create(cr, uid, dic, context=context)
102                 registration_obj.message_post(cr, uid, [registration_id], body=message, context=context)
103         return super(sale_order_line, self).button_confirm(cr, uid, ids, context=context)
104
105     def onchange_event_ticket_id(self, cr, uid, ids, event_ticket_id=False, context=None):
106         price = event_ticket_id and self.pool.get("event.event.ticket").browse(cr, uid, event_ticket_id, context=context).price or False
107         return {'value': {'price_unit': price}}
108
109
110 class event_event(osv.osv):
111     _inherit = 'event.event'
112
113     def _get_register_max(self, cr, uid, ids, field_name, arg, context=None):
114         result = dict.fromkeys(ids, 0)
115         for rec in self.browse(cr, uid, ids, context=context):
116             result[rec.id] = sum([ep.register_max for ep in rec.event_ticket_ids])
117         return result
118
119     def _get_tickets(self, cr, uid, context={}):
120         imd = self.pool.get('ir.model.data')
121         try:
122             product = imd.get_object(cr, uid, 'event_sale', 'product_product_event')
123         except ValueError:
124             return []
125         return [{
126             'name': _('Subscription'),
127             'product_id': product.id,
128             'price': 0,
129         }]
130
131     _columns = {
132         'event_ticket_ids': fields.one2many('event.event.ticket', "event_id", "Event Ticket"),
133         'register_max': fields.function(_get_register_max,
134             string='Maximum Registrations',
135             help="The maximum registration level is equal to the sum of the maximum registration of event ticket." +
136             "If you have too much registrations you are not able to confirm your event. (0 to ignore this rule )",
137             type='integer')
138     }
139     _defaults = {
140         'event_ticket_ids': _get_tickets
141     }
142
143     def check_registration_limits(self, cr, uid, ids, context=None):
144         for event in self.browse(cr, uid, ids, context=context):
145             if event.event_ticket_ids:
146                 for ticket in event.event_ticket_ids:
147                     ticket.check_registration_limits_before(0)
148         return super(event_event, self).check_registration_limits(cr, uid, ids, context=context)
149
150
151 class event_ticket(osv.osv):
152     _name = 'event.event.ticket'
153
154     def _get_register(self, cr, uid, ids, fields, args, context=None):
155         """Get Confirm or uncofirm register value.
156         @param ids: List of Event Ticket registration type's id
157         @param fields: List of function fields(register_current and register_prospect).
158         @param context: A standard dictionary for contextual values
159         @return: Dictionary of function fields value.
160         """
161         res = {}
162         for event in self.browse(cr, uid, ids, context=context):
163             res[event.id] = {}
164             reg_open = reg_done = reg_draft =0
165             for registration in event.registration_ids:
166                 if registration.state == 'open':
167                     reg_open += registration.nb_register
168                 elif registration.state == 'done':
169                     reg_done += registration.nb_register
170                 elif registration.state == 'draft':
171                     reg_draft += registration.nb_register
172             for field in fields:
173                 number = 0
174                 if field == 'register_current':
175                     number = reg_open
176                 elif field == 'register_attended':
177                     number = reg_done
178                 elif field == 'register_prospect':
179                     number = reg_draft
180                 elif field == 'register_avail':
181                     #the number of ticket is unlimited if the event.register_max field is not set.
182                     #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
183                     number = event.register_max - reg_open if event.register_max != 0 else 9999
184                 res[event.id][field] = number
185         return res
186
187     _columns = {
188         'name': fields.char('Name', size=64, required=True),
189         'event_id': fields.many2one('event.event', "Event", required=True, ondelete='cascade'),
190         'product_id': fields.many2one('product.product', 'Product', required=True, domain=[("event_type_id", "!=", False)]),
191         'registration_ids': fields.one2many('event.registration', 'event_ticket_id', 'Registrations'),
192         'deadline': fields.date("Sales End"),
193         'price': fields.float('Price'),
194         'register_max': fields.integer('Maximum Registrations'),
195         'register_current': fields.function(_get_register, string='Current Registrations', type='integer', multi='register_numbers'),
196         'register_avail': fields.function(_get_register, string='Available Registrations', type='integer', multi='register_numbers'),
197         'register_prospect': fields.function(_get_register, string='Unconfirmed Registrations', type='integer', multi='register_numbers'),
198         'register_attended': fields.function(_get_register, string='# of Participations', type='integer', multi='register_numbers'),
199     }
200
201     def _default_product_id(self, cr, uid, context={}):
202         imd = self.pool.get('ir.model.data')
203         try:
204             product = imd.get_object(cr, uid, 'event_sale', 'product_product_event')
205         except ValueError:
206             return False
207         return product.id
208
209     _defaults = {
210         'product_id': _default_product_id
211     }
212
213
214     def check_registration_limits_before(self, cr, uid, ids, number, context=None):
215         for ticket in self.browse(cr, uid, ids, context=context):
216             if ticket.register_max:
217                 if not ticket.register_avail:
218                     raise osv.except_osv(_('Warning!'),_('No Tickets Available for "%s"' % ticket.name))
219                 elif number + ticket.register_current > ticket.register_max:
220                     raise osv.except_osv(_('Warning!'), _('There only %d tickets available for "%s"' % (ticket.register_avail, ticket.name)))
221         return True
222
223     def onchange_product_id(self, cr, uid, ids, product_id=False, context=None):
224         return {'value': {'price': self.pool.get("product.product").browse(cr, uid, product_id).list_price or 0}}
225
226
227 class event_registration(osv.osv):
228     """Event Registration"""
229     _inherit= 'event.registration'
230     _columns = {
231         'event_ticket_id': fields.many2one('event.event.ticket', 'Event Ticket'),
232     }
233
234     def registration_open(self, cr, uid, ids, context=None):
235         """ Open Registration
236         """
237         for registration in self.browse(cr, uid, ids, context=context):
238             if registration.event_ticket_id:
239                 registration.event_ticket_id.check_registration_limits_before(1)
240         return super(event_registration, self).registration_open(cr, uid, ids, context=context)