Merge pull request #288 from odoo-dev/saas-4-mass_mailing_fixes-tde
[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.addons.event.event import event_event as Event
23 from openerp.osv import fields, osv
24 from openerp.tools.translate import _
25
26 class product_template(osv.osv):
27     _inherit = 'product.template'
28     _columns = {
29         '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.'),
30         '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.'),
31     }
32
33     def onchange_event_ok(self, cr, uid, ids, type, event_ok, context=None):
34         if event_ok:
35             return {'value': {'type': 'service'}}
36         return {}
37
38 class product(osv.osv):
39     _inherit = 'product.product'
40
41     def onchange_event_ok(self, cr, uid, ids, type, event_ok, context=None):
42         # cannot directly forward to product.template as the ids are theoretically different
43         if event_ok:
44             return {'value': {'type': 'service'}}
45         return {}
46
47
48 class sale_order_line(osv.osv):
49     _inherit = 'sale.order.line'
50     _columns = {
51         'event_id': fields.many2one('event.event', 'Event',
52             help="Choose an event and it will automatically create a registration for this event."),
53         'event_ticket_id': fields.many2one('event.event.ticket', 'Event Ticket',
54             help="Choose an event ticket and it will automatically create a registration for this event ticket."),
55         #those 2 fields are used for dynamic domains and filled by onchange
56         'event_type_id': fields.related('product_id','event_type_id', type='many2one', relation="event.type", string="Event Type"),
57         'event_ok': fields.related('product_id', 'event_ok', string='event_ok', type='boolean'),
58     }
59
60     def product_id_change(self, cr, uid, ids,
61                           pricelist, 
62                           product,
63                           qty=0,
64                           uom=False,
65                           qty_uos=0,
66                           uos=False,
67                           name='',
68                           partner_id=False,
69                           lang=False,
70                           update_tax=True,
71                           date_order=False,
72                           packaging=False,
73                           fiscal_position=False,
74                           flag=False, context=None):
75         """
76         check product if event type
77         """
78         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)
79         if product:
80             product_res = self.pool.get('product.product').browse(cr, uid, product, context=context)
81             if product_res.event_ok:
82                 res['value'].update({'event_type_id': product_res.event_type_id.id, 'event_ok':product_res.event_ok})
83         return res
84
85     def button_confirm(self, cr, uid, ids, context=None):
86         '''
87         create registration with sales order
88         '''
89         if context is None:
90             context = {}
91         registration_obj = self.pool.get('event.registration')
92         for order_line in self.browse(cr, uid, ids, context=context):
93             if order_line.event_id:
94                 dic = {
95                     'name': order_line.order_id.partner_invoice_id.name,
96                     'partner_id': order_line.order_id.partner_id.id,
97                     'nb_register': int(order_line.product_uom_qty),
98                     'email': order_line.order_id.partner_id.email,
99                     'phone': order_line.order_id.partner_id.phone,
100                     'origin': order_line.order_id.name,
101                     'event_id': order_line.event_id.id,
102                     'event_ticket_id': order_line.event_ticket_id and order_line.event_ticket_id.id or None,
103                 }
104
105                 if order_line.event_ticket_id:
106                     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)
107                 else:
108                     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)
109                 
110                 context.update({'mail_create_nolog': True})
111                 registration_id = registration_obj.create(cr, uid, dic, context=context)
112                 registration_obj.message_post(cr, uid, [registration_id], body=message, context=context)
113         return super(sale_order_line, self).button_confirm(cr, uid, ids, context=context)
114
115     def onchange_event_ticket_id(self, cr, uid, ids, event_ticket_id=False, context=None):
116         price = event_ticket_id and self.pool.get("event.event.ticket").browse(cr, uid, event_ticket_id, context=context).price or False
117         return {'value': {'price_unit': price}}
118
119
120 class event_event(osv.osv):
121     _inherit = 'event.event'
122
123     def _get_seats_max(self, cr, uid, ids, field_name, arg, context=None):
124         result = dict.fromkeys(ids, 0)
125         for rec in self.browse(cr, uid, ids, context=context):
126             result[rec.id] = sum([ticket.seats_max for ticket in rec.event_ticket_ids])
127         return result
128
129     def _get_tickets(self, cr, uid, context={}):
130         try:
131             product = self.pool.get('ir.model.data').get_object(cr, uid, 'event_sale', 'product_product_event')
132             return [{
133                 'name': _('Subscription'),
134                 'product_id': product.id,
135                 'price': 0,
136             }]
137         except ValueError:
138             pass
139         return []
140
141     def _get_ticket_events(self, cr, uid, ids, context=None):
142         # `self` is the event.event.ticket model when called by ORM! 
143         return list(set(ticket.event_id.id
144                             for ticket in self.browse(cr, uid, ids, context)))
145
146     # proxy method, can't import parent method directly as unbound_method: it would receive
147     # an invalid `self` <event_registration> when called by ORM
148     def _events_from_registrations(self, cr, uid, ids, context=None):
149         # `self` is the event.registration model when called by ORM
150         return self.pool['event.event']._get_events_from_registrations(cr, uid, ids, context=context)
151
152     _columns = {
153         'event_ticket_ids': fields.one2many('event.event.ticket', "event_id", "Event Ticket"),
154         'seats_max': fields.function(_get_seats_max,
155             string='Maximum Avalaible Seats',
156             help="The maximum registration level is equal to the sum of the maximum registration of event ticket." +
157             "If you have too much registrations you are not able to confirm your event. (0 to ignore this rule )",
158             type='integer',
159             readonly=True),
160         'seats_available': fields.function(Event._get_seats, oldname='register_avail', string='Available Seats',
161                                            type='integer', multi='seats_reserved',
162                                            store={
163                                               'event.registration': (_events_from_registrations, ['state'], 10),
164                                               'event.event': (lambda self, cr, uid, ids, c = {}: ids,
165                                                               ['seats_max', 'registration_ids'], 20),
166                                               'event.event.ticket': (_get_ticket_events, ['seats_max'], 10),
167                                            }),
168         'badge_back': fields.html('Badge Back', readonly=False, translate=True, states={'done': [('readonly', True)]}),
169         'badge_innerleft': fields.html('Badge Innner Left', readonly=False, translate=True, states={'done': [('readonly', True)]}),
170         'badge_innerright': fields.html('Badge Inner Right', readonly=False, translate=True, states={'done': [('readonly', True)]}),
171     }
172     _defaults = {
173         'event_ticket_ids': _get_tickets
174     }
175
176 class event_ticket(osv.osv):
177     _name = 'event.event.ticket'
178
179     def _get_seats(self, cr, uid, ids, fields, args, context=None):
180         """Get reserved, available, reserved but unconfirmed and used seats for each event tickets.
181         @return: Dictionary of function field values.
182         """
183         res = dict([(id, {}) for id in ids])
184         for ticket in self.browse(cr, uid, ids, context=context):
185             res[ticket.id]['seats_reserved'] = sum(reg.nb_register for reg in ticket.registration_ids if reg.state == "open")
186             res[ticket.id]['seats_used'] = sum(reg.nb_register for reg in ticket.registration_ids if reg.state == "done")
187             res[ticket.id]['seats_unconfirmed'] = sum(reg.nb_register for reg in ticket.registration_ids if reg.state == "draft")
188             res[ticket.id]['seats_available'] = ticket.seats_max - \
189                 (res[ticket.id]['seats_reserved'] + res[ticket.id]['seats_used']) \
190                 if ticket.seats_max > 0 else None
191         return res
192
193     def _is_expired(self, cr, uid, ids, field_name, args, context=None):
194         # FIXME: A ticket is considered expired when the deadline is passed. The deadline should
195         #        be considered in the timezone of the event, not the timezone of the user!
196         #        Until we add a TZ on the event we'll use the context's current date, more accurate
197         #        than using UTC all the time.
198         current_date = fields.date.context_today(self, cr, uid, context=context)
199         return {ticket.id: ticket.deadline and ticket.deadline < current_date
200                       for ticket in self.browse(cr, uid, ids, context=context)}
201         
202
203     _columns = {
204         'name': fields.char('Name', size=64, required=True, translate=True),
205         'event_id': fields.many2one('event.event', "Event", required=True, ondelete='cascade'),
206         'product_id': fields.many2one('product.product', 'Product', required=True, domain=[("event_type_id", "!=", False)]),
207         'registration_ids': fields.one2many('event.registration', 'event_ticket_id', 'Registrations'),
208         'deadline': fields.date("Sales End"),
209         'is_expired': fields.function(_is_expired, type='boolean', string='Is Expired'),
210         'price': fields.float('Price'),
211         'seats_max': fields.integer('Maximum Avalaible Seats', oldname='register_max', 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 )"),
212         'seats_reserved': fields.function(_get_seats, string='Reserved Seats', type='integer', multi='seats_reserved'),
213         'seats_available': fields.function(_get_seats, string='Available Seats', type='integer', multi='seats_reserved'),
214         'seats_unconfirmed': fields.function(_get_seats, string='Unconfirmed Seat Reservations', type='integer', multi='seats_reserved'),
215         'seats_used': fields.function(_get_seats, string='Number of Participations', type='integer', multi='seats_reserved'),
216     }
217
218     def _default_product_id(self, cr, uid, context={}):
219         imd = self.pool.get('ir.model.data')
220         try:
221             product = imd.get_object(cr, uid, 'event_sale', 'product_product_event')
222         except ValueError:
223             return False
224         return product.id
225
226     _defaults = {
227         'product_id': _default_product_id
228     }
229
230     def _check_seats_limit(self, cr, uid, ids, context=None):
231         for ticket in self.browse(cr, uid, ids, context=context):
232             if ticket.seats_max and ticket.seats_available < 0:
233                 return False
234         return True
235
236     _constraints = [
237         (_check_seats_limit, 'No more available tickets.', ['registration_ids','seats_max']),
238     ]
239
240     def onchange_product_id(self, cr, uid, ids, product_id=False, context=None):
241         return {'value': {'price': self.pool.get("product.product").browse(cr, uid, product_id).list_price or 0}}
242
243
244 class event_registration(osv.osv):
245     """Event Registration"""
246     _inherit= 'event.registration'
247     _columns = {
248         'event_ticket_id': fields.many2one('event.event.ticket', 'Event Ticket'),
249     }
250
251     def _check_ticket_seats_limit(self, cr, uid, ids, context=None):
252         for registration in self.browse(cr, uid, ids, context=context):
253             if registration.event_ticket_id.seats_max and registration.event_ticket_id.seats_available < 0:
254                 return False
255         return True
256
257     _constraints = [
258         (_check_ticket_seats_limit, 'No more available tickets.', ['event_ticket_id','nb_register','state']),
259     ]