10cc24182b9badee744a30901fd0c7ac68a4a073
[odoo/odoo.git] / addons / website_event / controllers / main.py
1 # -*- coding: utf-8 -*-
2 ##############################################################################
3 #
4 #    OpenERP, Open Source Management Solution
5 #    Copyright (C) 2013-Today OpenERP SA (<http://www.openerp.com>).
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 from datetime import datetime, timedelta
24 from dateutil.relativedelta import relativedelta
25
26 import werkzeug.urls
27 from werkzeug.exceptions import NotFound
28
29 from openerp import http
30 from openerp import tools
31 from openerp.http import request
32 from openerp.tools.translate import _
33 from openerp.addons.website.models.website import slug
34
35 class website_event(http.Controller):
36     @http.route(['/event', '/event/page/<int:page>'], type='http', auth="public", website=True)
37     def events(self, page=1, **searches):
38         cr, uid, context = request.cr, request.uid, request.context
39         event_obj = request.registry['event.event']
40         type_obj = request.registry['event.type']
41         country_obj = request.registry['res.country']
42
43         searches.setdefault('date', 'all')
44         searches.setdefault('type', 'all')
45         searches.setdefault('country', 'all')
46
47         domain_search = {}
48
49         def sdn(date):
50             return date.strftime('%Y-%m-%d 23:59:59')
51         def sd(date):
52             return date.strftime(tools.DEFAULT_SERVER_DATETIME_FORMAT)
53         today = datetime.today()
54         dates = [
55             ['all', _('Next Events'), [("date_end", ">", sd(today))], 0],
56             ['today', _('Today'), [
57                 ("date_end", ">", sd(today)),
58                 ("date_begin", "<", sdn(today))],
59                 0],
60             ['week', _('This Week'), [
61                 ("date_end", ">=", sd(today + relativedelta(days=-today.weekday()))),
62                 ("date_begin", "<", sdn(today  + relativedelta(days=6-today.weekday())))],
63                 0],
64             ['nextweek', _('Next Week'), [
65                 ("date_end", ">=", sd(today + relativedelta(days=7-today.weekday()))),
66                 ("date_begin", "<", sdn(today  + relativedelta(days=13-today.weekday())))],
67                 0],
68             ['month', _('This month'), [
69                 ("date_end", ">=", sd(today.replace(day=1))),
70                 ("date_begin", "<", (today.replace(day=1) + relativedelta(months=1)).strftime('%Y-%m-%d 00:00:00'))],
71                 0],
72             ['nextmonth', _('Next month'), [
73                 ("date_end", ">=", sd(today.replace(day=1) + relativedelta(months=1))),
74                 ("date_begin", "<", (today.replace(day=1)  + relativedelta(months=2)).strftime('%Y-%m-%d 00:00:00'))],
75                 0],
76             ['old', _('Old Events'), [
77                 ("date_end", "<", today.strftime('%Y-%m-%d 00:00:00'))],
78                 0],
79         ]
80
81         # search domains
82         current_date = None
83         current_type = None
84         current_country = None
85         for date in dates:
86             if searches["date"] == date[0]:
87                 domain_search["date"] = date[2]
88                 if date[0] != 'all':
89                     current_date = date[1]
90         if searches["type"] != 'all':
91             current_type = type_obj.browse(cr, uid, int(searches['type']), context=context)
92             domain_search["type"] = [("type", "=", int(searches["type"]))]
93
94         if searches["country"] != 'all' and searches["country"] != 'online':
95             current_country = country_obj.browse(cr, uid, int(searches['country']), context=context)
96             domain_search["country"] = ['|', ("country_id", "=", int(searches["country"])), ("country_id", "=", False)]
97         elif searches["country"] == 'online':
98             domain_search["country"] = [("country_id", "=", False)]
99
100         def dom_without(without):
101             domain = [('state', "in", ['draft','confirm','done'])]
102             for key, search in domain_search.items():
103                 if key != without:
104                     domain += search
105             return domain
106
107         # count by domains without self search
108         for date in dates:
109             if date[0] <> 'old':
110                 date[3] = event_obj.search(
111                     request.cr, request.uid, dom_without('date') + date[2],
112                     count=True, context=request.context)
113
114         domain = dom_without('type')
115         types = event_obj.read_group(
116             request.cr, request.uid, domain, ["id", "type"], groupby="type",
117             orderby="type", context=request.context)
118         type_count = event_obj.search(request.cr, request.uid, domain,
119                                       count=True, context=request.context)
120         types.insert(0, {
121             'type_count': type_count,
122             'type': ("all", _("All Categories"))
123         })
124
125         domain = dom_without('country')
126         countries = event_obj.read_group(
127             request.cr, request.uid, domain, ["id", "country_id"],
128             groupby="country_id", orderby="country_id", context=request.context)
129         country_id_count = event_obj.search(request.cr, request.uid, domain,
130                                             count=True, context=request.context)
131         countries.insert(0, {
132             'country_id_count': country_id_count,
133             'country_id': ("all", _("All Countries"))
134         })
135
136         step = 10  # Number of events per page
137         event_count = event_obj.search(
138             request.cr, request.uid, dom_without("none"), count=True,
139             context=request.context)
140         pager = request.website.pager(url="/event", total=event_count, page=page, step=step, scope=5)
141
142         order = 'website_published desc, date_begin'
143         if searches.get('date','all') == 'old':
144             order = 'website_published desc, date_begin desc'
145         obj_ids = event_obj.search(
146             request.cr, request.uid, dom_without("none"), limit=step,
147             offset=pager['offset'], order=order, context=request.context)
148         events_ids = event_obj.browse(request.cr, request.uid, obj_ids,
149                                       context=request.context)
150
151         values = {
152             'current_date': current_date,
153             'current_country': current_country,
154             'current_type': current_type,
155             'event_ids': events_ids,
156             'dates': dates,
157             'types': types,
158             'countries': countries,
159             'pager': pager,
160             'searches': searches,
161             'search_path': "?%s" % werkzeug.url_encode(searches),
162         }
163
164         return request.website.render("website_event.index", values)
165
166     @http.route(['/event/<model("event.event"):event>/page/<path:page>'], type='http', auth="public", website=True)
167     def event_page(self, event, page, **post):
168         values = {
169             'event': event,
170             'main_object': event
171         }
172
173         if '.' not in page:
174             page = 'website_event.%s' % page
175
176         try:
177             request.website.get_template(page)
178         except ValueError, e:
179             # page not found
180             raise NotFound
181
182         return request.website.render(page, values)
183
184     @http.route(['/event/<model("event.event"):event>'], type='http', auth="public", website=True)
185     def event(self, event, **post):
186         if event.menu_id and event.menu_id.child_id:
187             target_url = event.menu_id.child_id[0].url
188         else:
189             target_url = '/event/%s/register' % str(event.id)
190         if post.get('enable_editor') == '1':
191             target_url += '?enable_editor=1'
192         return request.redirect(target_url);
193
194     @http.route(['/event/<model("event.event"):event>/register'], type='http', auth="public", website=True)
195     def event_register(self, event, **post):
196         values = {
197             'event': event,
198             'main_object': event,
199             'range': range,
200         }
201         return request.website.render("website_event.event_description_full", values)
202
203     @http.route('/event/add_event', type='http', auth="user", methods=['POST'], website=True)
204     def add_event(self, event_name="New Event", **kwargs):
205         return self._add_event(event_name, request.context, **kwargs)
206
207     def _add_event(self, event_name=None, context={}, **kwargs):
208         if not event_name:
209             event_name = _("New Event")
210         Event = request.registry.get('event.event')
211         date_begin = datetime.today() + timedelta(days=(14))
212         vals = {
213             'name': event_name,
214             'date_begin': date_begin.strftime('%Y-%m-%d'),
215             'date_end': (date_begin + timedelta(days=(1))).strftime('%Y-%m-%d'),
216         }
217         event_id = Event.create(request.cr, request.uid, vals, context=context)
218         event = Event.browse(request.cr, request.uid, event_id, context=context)
219         return request.redirect("/event/%s/register?enable_editor=1" % slug(event))
220
221     def get_formated_date(self, event):
222         start_date = datetime.strptime(event.date_begin, tools.DEFAULT_SERVER_DATETIME_FORMAT).date()
223         end_date = datetime.strptime(event.date_end, tools.DEFAULT_SERVER_DATETIME_FORMAT).date()
224         return ('%s %s%s') % (start_date.strftime("%b"), start_date.strftime("%e"), (end_date != start_date and ("-"+end_date.strftime("%e")) or ""))
225     
226     @http.route('/event/get_country_event_list', type='http', auth='public', website=True)
227     def get_country_events(self ,**post):
228         cr, uid, context, event_ids = request.cr, request.uid, request.context,[]
229         country_obj = request.registry['res.country']
230         event_obj = request.registry['event.event']
231         country_code = request.session['geoip'].get('country_code')
232         result = {'events':[],'country':False}
233         if country_code:
234             country_ids = country_obj.search(cr, uid, [('code', '=', country_code)], context=context)
235             event_ids = event_obj.search(cr, uid, ['|', ('address_id', '=', None),('country_id.code', '=', country_code),('date_begin','>=', time.strftime('%Y-%m-%d 00:00:00')),('state', '=', 'confirm')], order="date_begin", context=context)
236         if not event_ids:
237             event_ids = event_obj.search(cr, uid, [('date_begin','>=', time.strftime('%Y-%m-%d 00:00:00')),('state', '=', 'confirm')], order="date_begin", context=context)
238         for event in event_obj.browse(cr, uid, event_ids, context=context)[:6]:
239             if country_code and event.country_id.code == country_code:
240                 result['country'] = country_obj.browse(cr, uid, country_ids[0], context=context)
241             result['events'].append({
242                  "date": self.get_formated_date(event),
243                  "event": event,
244                  "url": event.website_url})
245         return request.website.render("website_event.country_events_list",result)