[IMP] website_*: remove useless % chars surrounding ilike operand, this is the default
[odoo/odoo.git] / addons / website_sale / controllers / main.py
1 # -*- coding: utf-8 -*-
2 import random
3 import simplejson
4 import werkzeug
5
6 from openerp import SUPERUSER_ID
7 from openerp.addons.web import http
8 from openerp.addons.web.http import request
9
10 PPG = 20                        # Products Per Page
11 PPR = 4                         # Products Per Row
12
13
14 class CheckoutInfo(object):
15     mandatory_billing_fields = ["name", "phone", "email", "street", "city", "country_id", "zip"]
16     optional_billing_fields = ["company", "state_id"]
17     string_billing_fields = ["name", "phone", "email", "street", "city", "zip"]
18
19     mandatory_shipping_fields = ["shipping_name", "shipping_phone", "shipping_street", "shipping_city", "shipping_country_id", "shipping_zip"]
20     optional_shipping_field = ["shipping_state_id"]
21     string_shipping_fields = ["shipping_name", "shipping_phone", "shipping_street", "shipping_city", "shipping_zip"]
22
23     def mandatory_fields(self):
24         return self.mandatory_billing_fields + self.mandatory_shipping_fields
25
26     def optional_fields(self):
27         return self.optional_billing_fields + self.optional_shipping_field
28
29     def all_fields(self):
30         return self.mandatory_fields() + self.optional_fields()
31
32     def empty(self):
33         return dict.fromkeys(self.all_fields(), '')
34
35     def from_partner(self, partner, address_type='billing'):
36         assert address_type in ('billing', 'shipping')
37         if address_type == 'billing':
38             prefix = ''
39         else:
40             prefix = 'shipping_'
41         result = dict((prefix + field_name, getattr(partner, field_name)) for field_name in self.string_billing_fields if getattr(partner, field_name))
42         result[prefix + 'state_id'] = partner.state_id and partner.state_id.id or ''
43         result[prefix + 'country_id'] = partner.country_id and partner.country_id.id or ''
44         result[prefix + 'company'] = partner.parent_id and partner.parent_id.name or ''
45         return result
46
47     def from_post(self, post):
48         return dict((field_name, post[field_name]) for field_name in self.all_fields() if post[field_name])
49
50
51 #
52 # Compute grid of products according to their sizes
53 #
54 class table_compute(object):
55     def __init__(self):
56         self.table = {}
57
58     def _check_place(self, posx, posy, sizex, sizey):
59         for y in range(sizey):
60             for x in range(sizex):
61                 if posx+x>=PPR:
62                     return False
63                 row = self.table.setdefault(posy+y, {})
64                 if row.setdefault(posx+x) is not None:
65                     return False
66         return True
67
68     def process(self, products):
69         # Compute products positions on the grid
70         minpos = 0
71         index = 0
72         maxy = 0
73         for p in products:
74             x = p.website_size_x
75             y = p.website_size_y
76             if index>PPG:
77                 x = y = 1
78
79             pos = minpos
80             while not self._check_place(pos%PPR, pos/PPR, x, y):
81                 pos += 1
82
83             if index>PPG and (pos/PPR)>maxy:
84                 break
85
86             if x==1 and y==1:   # simple heuristic for CPU optimization
87                 minpos = pos/PPR
88
89             for y2 in range(y):
90                 for x2 in range(x):
91                     self.table[(pos/PPR)+y2][(pos%PPR)+x2] = False
92             self.table[pos/PPR][pos%PPR] = {
93                 'product': p, 'x':x, 'y': y,
94                 'class': " ".join(map(lambda x: x.html_class, p.website_style_ids))
95             }
96             if index<=PPG:
97                 maxy=max(maxy,y+(pos/PPR))
98             index += 1
99
100         # Format table according to HTML needs
101         rows = self.table.items()
102         rows.sort()
103         rows = map(lambda x: x[1], rows)
104         for col in range(len(rows)):
105             cols = rows[col].items()
106             cols.sort()
107             rows[col] = map(lambda x: x[1], cols)
108         return filter(bool, rows)
109
110
111 class Ecommerce(http.Controller):
112
113     _order = 'website_published desc, website_sequence desc'
114
115     def get_characteristic_ids(self):
116         characteristics_obj = request.registry['product.characteristic']
117         characteristics_ids = characteristics_obj.search(request.cr, request.uid, [], context=request.context)
118         return characteristics_obj.browse(request.cr, request.uid, characteristics_ids, context=request.context)
119
120     def get_pricelist(self):
121         """ Shortcut to get the pricelist from the website model """
122         return request.registry['website'].ecommerce_get_pricelist_id(request.cr, request.uid, None, context=request.context)
123
124     def get_order(self):
125         """ Shortcut to get the current ecommerce quotation from the website model """
126         return request.registry['website'].ecommerce_get_current_order(request.cr, request.uid, context=request.context)
127
128     def get_products(self, product_ids):
129         product_obj = request.registry.get('product.template')
130         request.context['pricelist'] = self.get_pricelist()
131         # search for checking of access rules and keep order
132         product_ids = [id for id in product_ids if id in product_obj.search(request.cr, request.uid, [("id", 'in', product_ids)], context=request.context)]
133         return product_obj.browse(request.cr, request.uid, product_ids, context=request.context)
134
135     def has_search_filter(self, characteristic_id, value_id=None):
136         if request.httprequest.args.get('filters'):
137             filters = simplejson.loads(request.httprequest.args['filters'])
138         else:
139             filters = []
140         for key_val in filters:
141             if key_val[0] == characteristic_id and (not value_id or value_id in key_val[1:]):
142                 return key_val
143         return False
144
145     @http.route(['/shop/filters/'], type='http', auth="public", website=True, multilang=True)
146     def filters(self, **post):
147         index = []
148         filters = []
149         for key, val in post.items():
150             cat = key.split("-")
151             if len(cat) < 3 or cat[2] in ('max','minmem','maxmem'):
152                 continue
153             cat_id = int(cat[1])
154             if cat[2] == 'min':
155                 minmem = float(post.pop("att-%s-minmem" % cat[1]))
156                 maxmem = float(post.pop("att-%s-maxmem" % cat[1]))
157                 _max = int(post.pop("att-%s-max" % cat[1]))
158                 _min = int(val)
159                 if (minmem != _min or maxmem != _max) and cat_id not in index:
160                     filters.append([cat_id , [_min, _max] ])
161                     index.append(cat_id)
162             elif cat_id not in index:
163                 filters.append([ cat_id, int(cat[2]) ])
164                 index.append(cat_id)
165             else:
166                 cat[2] = int(cat[2])
167                 if cat[2] not in filters[index.index(cat_id)][1:]:
168                     filters[index.index(cat_id)].append( cat[2] )
169             post.pop(key)
170
171         return request.redirect("/shop/?filters=%s%s%s" % (
172                 simplejson.dumps(filters),
173                 post.get("search") and ("&search=%s" % post.get("search")) or "",
174                 post.get("category") and ("&category=%s" % post.get("category")) or ""
175             ))
176
177     def characteristics_to_ids(self, characteristics):
178         obj = request.registry.get('product.characteristic.product')
179         domain = []
180         for key_val in characteristics:
181             domain.append(("characteristic_id", "=", key_val[0]))
182             if isinstance(key_val[1], list):
183                 domain.append(("value", ">=", key_val[1][0]))
184                 domain.append(("value", "<=", key_val[1][1]))
185             else:
186                 domain.append(("value_id", "in", key_val[1:]))
187         att_ids = obj.search(request.cr, request.uid, domain, context=request.context)
188         att = obj.read(request.cr, request.uid, att_ids, ["product_tmpl_id"], context=request.context)
189         return [r["product_tmpl_id"][0] for r in att]
190
191     @http.route(['/shop/pricelist'], type='http', auth="public", website=True, multilang=True)
192     def shop_promo(self, promo=None, **post):
193         request.registry['website']._ecommerce_change_pricelist(request.cr, request.uid, code=promo, context=request.context)
194         return request.redirect("/shop/mycart/")
195
196     @http.route([
197         '/shop/',
198         '/shop/page/<int:page>/',
199         '/shop/category/<model("product.public.category"):category>/',
200         '/shop/category/<model("product.public.category"):category>/page/<int:page>/'
201     ], type='http', auth="public", website=True, multilang=True)
202     def shop(self, category=None, page=0, filters='', search='', **post):
203         cr, uid, context = request.cr, request.uid, request.context
204         product_obj = request.registry.get('product.template')
205         domain = request.registry.get('website').ecommerce_get_product_domain()
206         if search:
207             domain += ['|',
208                 ('name', 'ilike', search),
209                 ('description', 'ilike', search)]
210         if category:
211             domain.append(('product_variant_ids.public_categ_id', 'child_of', category.id))
212         if filters:
213             filters = simplejson.loads(filters)
214             if filters:
215                 ids = self.characteristics_to_ids(filters)
216                 domain.append(('id', 'in', ids or [0]))
217
218         product_count = product_obj.search_count(cr, uid, domain, context=context)
219         pager = request.website.pager(url="/shop/", total=product_count, page=page, step=PPG, scope=7, url_args=post)
220
221         request.context['pricelist'] = self.get_pricelist()
222
223         pids = product_obj.search(cr, uid, domain, limit=PPG+10, offset=pager['offset'], order=self._order, context=context)
224         products = product_obj.browse(cr, uid, pids, context=context)
225
226         styles = []
227         try:
228             style_obj = request.registry.get('website.product.style')
229             style_ids = style_obj.search(request.cr, request.uid, [], context=request.context)
230             styles = style_obj.browse(request.cr, request.uid, style_ids, context=request.context)
231         except:
232             pass
233
234         category_obj = request.registry.get('product.public.category')
235         category_ids = category_obj.search(cr, uid, [], context=context)
236         categories = category_obj.browse(cr, uid, category_ids, context=context)
237         categs = filter(lambda x: not x.parent_id, categories)
238
239         values = {
240             'products': products,
241             'bins': table_compute().process(products),
242             'rows': PPR,
243             'range': range,
244             'search': {
245                 'search': search,
246                 'category': category and category.id,
247                 'filters': filters,
248             },
249             'pager': pager,
250             'styles': styles,
251             'categories': categs,
252             'Ecommerce': self,   # TODO fp: Should be removed
253             'style_in_product': lambda style, product: style.id in [s.id for s in product.website_style_ids],
254         }
255         return request.website.render("website_sale.products", values)
256
257     @http.route(['/shop/product/<model("product.template"):product>/'], type='http', auth="public", website=True, multilang=True)
258     def product(self, product, search='', category='', filters='', **kwargs):
259         category_obj = request.registry.get('product.public.category')
260
261         category_ids = category_obj.search(request.cr, request.uid, [], context=request.context)
262         category_list = category_obj.name_get(request.cr, request.uid, category_ids, context=request.context)
263         category_list = sorted(category_list, key=lambda category: category[1])
264
265         if category:
266             category = category_obj.browse(request.cr, request.uid, int(category), context=request.context)
267
268         request.context['pricelist'] = self.get_pricelist()
269
270         values = {
271             'Ecommerce': self,
272             'category': category,
273             'category_list': category_list,
274             'main_object': product,
275             'product': product,
276             'search': {
277                 'search': search,
278                 'category': category and str(category.id),
279                 'filters': filters,
280             }
281         }
282         return request.website.render("website_sale.product", values)
283
284     @http.route(['/shop/product/comment'], type='http', auth="public", methods=['POST'], website=True)
285     def product_comment(self, product_template_id, **post):
286         cr, uid, context = request.cr, request.uid, request.context
287         if post.get('comment'):
288             request.registry['product.template'].message_post(
289                 cr, uid, product_template_id,
290                 body=post.get('comment'),
291                 type='comment',
292                 subtype='mt_comment',
293                 context=dict(context, mail_create_nosubcribe=True))
294         return werkzeug.utils.redirect(request.httprequest.referrer + "#comments")
295
296     @http.route(['/shop/add_product/'], type='http', auth="user", methods=['POST'], website=True, multilang=True)
297     def add_product(self, name="New Product", category=0, **post):
298         Product = request.registry.get('product.product')
299         product_id = Product.create(request.cr, request.uid, {
300             'name': name, 'public_categ_id': category
301         }, context=request.context)
302         product = Product.browse(request.cr, request.uid, product_id, context=request.context)
303
304         return request.redirect("/shop/product/%s/?enable_editor=1" % product.product_tmpl_id.id)
305
306     @http.route(['/shop/mycart/'], type='http', auth="public", website=True, multilang=True)
307     def mycart(self, **post):
308         cr, uid, context = request.cr, request.uid, request.context
309         prod_obj = request.registry.get('product.product')
310
311         # must have a draft sale order with lines at this point, otherwise reset
312         order = self.get_order()
313         if order and order.state != 'draft':
314             request.registry['website'].sale_reset_order(cr, uid, context=context)
315             return request.redirect('/shop/')
316
317         self.get_pricelist()
318
319         suggested_ids = []
320         product_ids = []
321         if order:
322             for line in order.order_line:
323                 suggested_ids += [p.id for p in line.product_id and line.product_id.suggested_product_ids or []]
324                 product_ids.append(line.product_id.id)
325         suggested_ids = list(set(suggested_ids) - set(product_ids))
326         if suggested_ids:
327             suggested_ids = prod_obj.search(cr, uid, [('id', 'in', suggested_ids)], context=context)
328
329         # select 3 random products
330         suggested_products = []
331         while len(suggested_products) < 3 and suggested_ids:
332             index = random.randrange(0, len(suggested_ids))
333             suggested_products.append(suggested_ids.pop(index))
334
335         context = dict(context or {}, pricelist=request.registry['website'].ecommerce_get_pricelist_id(cr, uid, None, context=context))
336
337         values = {
338             'int': int,
339             'suggested_products': prod_obj.browse(cr, uid, suggested_products, context),
340         }
341         return request.website.render("website_sale.mycart", values)
342
343     @http.route(['/shop/add_cart/'], type='http', auth="public", methods=['POST'], website=True, multilang=True)
344     def add_cart(self, product_id, remove=None, **kw):
345         request.registry['website']._ecommerce_add_product_to_cart(request.cr, request.uid,
346             product_id=int(product_id),
347             context=request.context)
348         return request.redirect("/shop/mycart/")
349
350     @http.route(['/shop/change_cart/<int:order_line_id>/'], type='http', auth="public", website=True, multilang=True)
351     def add_cart_order_line(self, order_line_id=None, remove=None, **kw):
352         request.registry['website']._ecommerce_add_product_to_cart(request.cr, request.uid,
353             order_line_id=order_line_id, number=(remove and -1 or 1),
354             context=request.context)
355         return request.redirect("/shop/mycart/")
356
357     @http.route(['/shop/add_cart_json/'], type='json', auth="public", website=True, multilang=True)
358     def add_cart_json(self, product_id=None, order_line_id=None, remove=None):
359         quantity = request.registry['website']._ecommerce_add_product_to_cart(request.cr, request.uid,
360             product_id=product_id, order_line_id=order_line_id, number=(remove and -1 or 1),
361             context=request.context)
362         order = self.get_order()
363         return [quantity,
364                 order.get_number_of_products(),
365                 order.amount_total,
366                 request.website._render("website_sale.total", {'website_sale_order': order})]
367
368     @http.route(['/shop/set_cart_json/'], type='json', auth="public")
369     def set_cart_json(self, path=None, product_id=None, order_line_id=None, set_number=0, json=None):
370         quantity = request.registry['website']._ecommerce_add_product_to_cart(request.cr, request.uid,
371             product_id=product_id, order_line_id=order_line_id, set_number=set_number,
372             context=request.context)
373         return quantity
374
375     @http.route(['/shop/checkout/'], type='http', auth="public", website=True, multilang=True)
376     def checkout(self, **post):
377         cr, uid, context, registry = request.cr, request.uid, request.context, request.registry
378
379         # must have a draft sale order with lines at this point, otherwise reset
380         order = self.get_order()
381         if not order or order.state != 'draft' or not order.order_line:
382             request.registry['website'].ecommerce_reset(cr, uid, context=context)
383             return request.redirect('/shop/')
384         # if transaction pending / done: redirect to confirmation
385         tx = context.get('website_sale_transaction')
386         if tx and tx.state != 'draft':
387             return request.redirect('/shop/payment/confirmation/%s' % order.id)
388
389         self.get_pricelist()
390
391         orm_partner = registry.get('res.partner')
392         orm_user = registry.get('res.users')
393         orm_country = registry.get('res.country')
394         country_ids = orm_country.search(cr, SUPERUSER_ID, [], context=context)
395         countries = orm_country.browse(cr, SUPERUSER_ID, country_ids, context)
396         state_orm = registry.get('res.country.state')
397         states_ids = state_orm.search(cr, SUPERUSER_ID, [], context=context)
398         states = state_orm.browse(cr, SUPERUSER_ID, states_ids, context)
399
400         info = CheckoutInfo()
401         values = {
402             'countries': countries,
403             'states': states,
404             'checkout': info.empty(),
405             'shipping': post.get("shipping_different"),
406             'error': {},
407         }
408         checkout = values['checkout']
409
410         partner = None
411         public_id = request.registry['website'].get_public_user(cr, uid, context)
412         if not request.uid == public_id:
413             partner = orm_user.browse(cr, uid, uid, context).partner_id
414         elif order.partner_id:
415             domain = [("active", "=", False), ("partner_id", "=", order.partner_id.id)]
416             user_ids = request.registry['res.users'].search(cr, SUPERUSER_ID, domain, context=context)
417             if not user_ids or public_id not in user_ids:
418                 partner = orm_partner.browse(cr, SUPERUSER_ID, order.partner_id.id, context)
419
420         if partner:
421             partner_info = info.from_partner(partner)
422             checkout.update(partner_info)
423             shipping_ids = orm_partner.search(cr, SUPERUSER_ID, [("parent_id", "=", partner.id), ('type', "=", 'delivery')], limit=1, context=context)
424             if shipping_ids:
425                 values['shipping'] = "true"
426                 shipping_partner = orm_partner.browse(cr, SUPERUSER_ID, shipping_ids[0], context)
427                 checkout.update(info.from_partner(shipping_partner, address_type='shipping'))
428
429         return request.website.render("website_sale.checkout", values)
430
431     @http.route(['/shop/confirm_order/'], type='http', auth="public", website=True, multilang=True)
432     def confirm_order(self, **post):
433         cr, uid, context, registry = request.cr, request.uid, request.context, request.registry
434         order_line_obj = request.registry.get('sale.order')
435
436         # must have a draft sale order with lines at this point, otherwise redirect to shop
437         order = self.get_order()
438         if not order or order.state != 'draft' or not order.order_line:
439             request.registry['website'].ecommerce_reset(cr, uid, context=context)
440             return request.redirect('/shop/')
441         # if transaction pending / done: redirect to confirmation
442         tx = context.get('website_sale_transaction')
443         if tx and tx.state != 'draft':
444             return request.redirect('/shop/payment/confirmation/%s' % order.id)
445
446         orm_partner = registry.get('res.partner')
447         orm_user = registry.get('res.users')
448         orm_country = registry.get('res.country')
449         country_ids = orm_country.search(cr, SUPERUSER_ID, [], context=context)
450         countries = orm_country.browse(cr, SUPERUSER_ID, country_ids, context)
451         orm_state = registry.get('res.country.state')
452         states_ids = orm_state.search(cr, SUPERUSER_ID, [], context=context)
453         states = orm_state.browse(cr, SUPERUSER_ID, states_ids, context)
454
455         info = CheckoutInfo()
456         values = {
457             'countries': countries,
458             'states': states,
459             'checkout': info.empty(),
460             'shipping': post.get("shipping_different"),
461             'error': {},
462         }
463         checkout = values['checkout']
464         checkout.update(post)
465         error = values['error']
466
467         for field_name in info.mandatory_billing_fields:
468             if not checkout[field_name]:
469                 error[field_name] = 'missing'
470         if post.get("shipping_different"):
471             for field_name in info.mandatory_shipping_fields:
472                 if not checkout[field_name]:
473                     error[field_name] = 'missing'
474         if error:
475             return request.website.render("website_sale.checkout", values)
476
477         company_name = checkout['company']
478         company_id = None
479         if post['company']:
480             company_ids = orm_partner.search(cr, SUPERUSER_ID, [("name", "ilike", company_name), ('is_company', '=', True)], context=context)
481             company_id = (company_ids and company_ids[0]) or orm_partner.create(cr, SUPERUSER_ID, {'name': company_name, 'is_company': True}, context)
482
483         billing_info = dict((k, v) for k,v in checkout.items() if "shipping_" not in k and k != "company")
484         billing_info['parent_id'] = company_id
485
486         partner_id = None
487         public_id = request.registry['website'].get_public_user(cr, uid, context)
488         if request.uid != public_id:
489             partner_id = orm_user.browse(cr, SUPERUSER_ID, uid, context=context).partner_id.id
490         elif order.partner_id:
491             domain = [("active", "=", False), ("partner_id", "=", order.partner_id.id)]
492             user_ids = request.registry['res.users'].search(cr, SUPERUSER_ID, domain, context=context)
493             if not user_ids or public_id not in user_ids:
494                 partner_id = order.partner_id.id
495
496         if partner_id:
497             orm_partner.write(cr, SUPERUSER_ID, [partner_id], billing_info, context=context)
498         else:
499             partner_id = orm_partner.create(cr, SUPERUSER_ID, billing_info, context=context)
500
501         shipping_id = None
502         if post.get('shipping_different'):
503             shipping_info = {
504                 'phone': post['shipping_phone'],
505                 'zip': post['shipping_zip'],
506                 'street': post['shipping_street'],
507                 'city': post['shipping_city'],
508                 'name': post['shipping_name'],
509                 'email': post['email'],
510                 'type': 'delivery',
511                 'parent_id': partner_id,
512                 'country_id': post['shipping_country_id'],
513                 'state_id': post['shipping_state_id'],
514             }
515             domain = [(key, '_id' in key and '=' or 'ilike', '_id' in key and value and int(value) or value)
516                       for key, value in shipping_info.items() if key in info.mandatory_billing_fields + ["type", "parent_id"]]
517
518             shipping_ids = orm_partner.search(cr, SUPERUSER_ID, domain, context=context)
519             if shipping_ids:
520                 shipping_id = shipping_ids[0]
521                 orm_partner.write(cr, SUPERUSER_ID, [shipping_id], shipping_info, context)
522             else:
523                 shipping_id = orm_partner.create(cr, SUPERUSER_ID, shipping_info, context)
524
525         order_info = {
526             'partner_id': partner_id,
527             'message_follower_ids': [(4, partner_id)],
528             'partner_invoice_id': partner_id,
529             'partner_shipping_id': shipping_id or partner_id
530         }
531         order_info.update(registry.get('sale.order').onchange_partner_id(cr, SUPERUSER_ID, [], partner_id, context=context)['value'])
532         order_info.pop('user_id')
533
534         order_line_obj.write(cr, SUPERUSER_ID, [order.id], order_info, context=context)
535
536         return request.redirect("/shop/payment/")
537
538     @http.route(['/shop/payment/'], type='http', auth="public", website=True, multilang=True)
539     def payment(self, **post):
540         """ Payment step. This page proposes several payment means based on available
541         payment.acquirer. State at this point :
542
543          - a draft sale order with lines; otherwise, clean context / session and
544            back to the shop
545          - no transaction in context / session, or only a draft one, if the customer
546            did go to a payment.acquirer website but closed the tab without
547            paying / canceling
548         """
549         cr, uid, context = request.cr, request.uid, request.context
550         payment_obj = request.registry.get('payment.acquirer')
551
552         # if no sale order at this stage: back to checkout beginning
553         order = self.get_order()
554         if not order or order.state != 'draft' or not order.order_line:
555             request.registry['website'].ecommerce_reset(cr, uid, context=context)
556             return request.redirect("/shop/")
557         # alread a transaction: forward to confirmation
558         tx = context.get('website_sale_transaction')
559         if tx and tx.state != 'draft':
560             return request.redirect('/shop/confirmation/%s' % order.id)
561
562         shipping_partner_id = False
563         if order:
564             if order.partner_shipping_id.id:
565                 shipping_partner_id = order.partner_shipping_id.id
566             else:
567                 shipping_partner_id = order.partner_invoice_id.id
568
569         values = {
570             'order': request.registry['sale.order'].browse(cr, SUPERUSER_ID, order.id, context=context)
571         }
572         values.update(request.registry.get('sale.order')._get_website_data(cr, uid, order, context))
573
574         # fetch all registered payment means
575         if tx:
576             acquirer_ids = [tx.acquirer_id.id]
577         else:
578             acquirer_ids = payment_obj.search(cr, SUPERUSER_ID, [('website_published', '=', True)], context=context)
579         values['acquirers'] = payment_obj.browse(cr, uid, acquirer_ids, context=context)
580         render_ctx = dict(context, submit_class='btn btn-primary', submit_txt='Pay Now')
581         for acquirer in values['acquirers']:
582             render_ctx['tx_url'] = '/shop/payment/transaction/%s' % acquirer.id
583             acquirer.button = payment_obj.render(
584                 cr, SUPERUSER_ID, acquirer.id,
585                 order.name,
586                 order.amount_total,
587                 order.pricelist_id.currency_id.id,
588                 partner_id=shipping_partner_id,
589                 tx_values={
590                     'return_url': '/shop/payment/validate',
591                 },
592                 context=render_ctx)
593
594         return request.website.render("website_sale.payment", values)
595
596     @http.route(['/shop/payment/transaction/<int:acquirer_id>'],
597                    type='http', methods=['POST'], auth="public", website=True)
598     def payment_transaction(self, acquirer_id, **post):
599         """ Hook method that creates a payment.transaction and redirect to the
600         acquirer, using post values to re-create the post action.
601
602         :param int acquirer_id: id of a payment.acquirer record. If not set the
603                                 user is redirected to the checkout page
604         :param dict post: should coutain all post data for the acquirer
605         """
606         # @TDEFIXME: don't know why we received those data, but should not be send to the acquirer
607         post.pop('submit.x', None)
608         post.pop('submit.y', None)
609         cr, uid, context = request.cr, request.uid, request.context
610         payment_obj = request.registry.get('payment.acquirer')
611         transaction_obj = request.registry.get('payment.transaction')
612         order = self.get_order()
613
614         if not order or not order.order_line or acquirer_id is None:
615             return request.redirect("/shop/checkout/")
616
617         # find an already existing transaction
618         tx = context.get('website_sale_transaction')
619         if not tx:
620             tx_id = transaction_obj.create(cr, SUPERUSER_ID, {
621                 'acquirer_id': acquirer_id,
622                 'type': 'form',
623                 'amount': order.amount_total,
624                 'currency_id': order.pricelist_id.currency_id.id,
625                 'partner_id': order.partner_id.id,
626                 'reference': order.name,
627                 'sale_order_id': order.id,
628             }, context=context)
629             request.httprequest.session['website_sale_transaction_id'] = tx_id
630         elif tx and tx.state == 'draft':  # button cliked but no more info -> rewrite on tx or create a new one ?
631             tx.write({
632                 'acquirer_id': acquirer_id,
633             })
634
635         acquirer_form_post_url = payment_obj.get_form_action_url(cr, uid, acquirer_id, context=context)
636         acquirer_total_url = '%s?%s' % (acquirer_form_post_url, werkzeug.url_encode(post))
637         return request.redirect(acquirer_total_url)
638
639     @http.route('/shop/payment/get_status/<int:sale_order_id>', type='json', auth="public", website=True, multilang=True)
640     def payment_get_status(self, sale_order_id, **post):
641         cr, uid, context = request.cr, request.uid, request.context
642
643         order = request.registry['sale.order'].browse(cr, SUPERUSER_ID, sale_order_id, context=context)
644         assert order.website_session_id == request.httprequest.session['website_session_id']
645
646         if not order:
647             return {
648                 'state': 'error',
649                 'message': '<p>There seems to be an error with your request.</p>',
650             }
651
652         tx_ids = request.registry['payment.transaction'].search(
653             cr, uid, [
654                 '|', ('sale_order_id', '=', order.id), ('reference', '=', order.name)
655             ], context=context)
656
657         if not tx_ids:
658             if order.amount_total:
659                 return {
660                     'state': 'error',
661                     'message': '<p>There seems to be an error with your request.</p>',
662                 }
663             else:
664                 state = 'done'
665                 message = ""
666                 validation = None
667         else:
668             tx = request.registry['payment.transaction'].browse(cr, uid, tx_ids[0], context=context)
669             state = tx.state
670             if state == 'done':
671                 message = '<p>Your payment has been received.</p>'
672             elif state == 'cancel':
673                 message = '<p>The payment seems to have been canceled.</p>'
674             elif state == 'pending' and tx.acquirer_id.validation == 'manual':
675                 message = '<p>Your transaction is waiting confirmation.</p>'
676                 message += tx.acquirer_id.post_msg
677             else:
678                 message = '<p>Your transaction is waiting confirmation.</p>'
679             validation = tx.acquirer_id.validation
680
681         return {
682             'state': state,
683             'message': message,
684             'validation': validation
685         }
686
687     @http.route('/shop/payment/validate/', type='http', auth="public", website=True, multilang=True)
688     def payment_validate(self, transaction_id=None, sale_order_id=None, **post):
689         """ Method that should be called by the server when receiving an update
690         for a transaction. State at this point :
691
692          - UDPATE ME
693         """
694         cr, uid, context = request.cr, request.uid, request.context
695         email_act = None
696         sale_order_obj = request.registry['sale.order']
697
698         if transaction_id is None:
699             tx = context.get('website_sale_transaction')
700         else:
701             tx = request.registry['payment.transaction'].browse(cr, uid, transaction_id, context=context)
702
703         if sale_order_id is None:
704             order = self.get_order()
705         else:
706             order = request.registry['sale.order'].browse(cr, SUPERUSER_ID, sale_order_id, context=context)
707             assert order.website_session_id == request.httprequest.session['website_session_id']
708
709         if not tx or not order:
710             return request.redirect('/shop/')
711
712         if not order.amount_total or tx.state == 'done':
713             # confirm the quotation
714             sale_order_obj.action_button_confirm(cr, SUPERUSER_ID, [order.id], context=request.context)
715             # send by email
716             email_act = sale_order_obj.action_quotation_send(cr, SUPERUSER_ID, [order.id], context=request.context)
717         elif tx.state == 'pending':
718             # send by email
719             email_act = sale_order_obj.action_quotation_send(cr, SUPERUSER_ID, [order.id], context=request.context)
720         elif tx.state == 'cancel':
721             # cancel the quotation
722             sale_order_obj.action_cancel(cr, SUPERUSER_ID, [order.id], context=request.context)
723
724         # clean context and session, then redirect to the confirmation page
725         request.registry['website'].ecommerce_reset(cr, uid, context=context)
726
727         return request.redirect('/shop/confirmation/%s' % order.id)
728
729     @http.route(['/shop/confirmation/<int:sale_order_id>'], type='http', auth="public", website=True, multilang=True)
730     def payment_confirmation(self, sale_order_id, **post):
731         """ End of checkout process controller. Confirmation is basically seing
732         the status of a sale.order. State at this point :
733
734          - should not have any context / session info: clean them
735          - take a sale.order id, because we request a sale.order and are not
736            session dependant anymore
737         """
738         cr, uid, context = request.cr, request.uid, request.context
739
740         order = request.registry['sale.order'].browse(cr, SUPERUSER_ID, sale_order_id, context=context)
741         assert order.website_session_id == request.httprequest.session['website_session_id']
742
743         request.registry['website']._ecommerce_change_pricelist(cr, uid, None, context=context or {})
744
745         return request.website.render("website_sale.confirmation", {'order': order})
746
747     @http.route(['/shop/change_sequence/'], type='json', auth="public")
748     def change_sequence(self, id, sequence):
749         product_obj = request.registry.get('product.template')
750         if sequence == "top":
751             product_obj.set_sequence_top(request.cr, request.uid, [id], context=request.context)
752         elif sequence == "bottom":
753             product_obj.set_sequence_bottom(request.cr, request.uid, [id], context=request.context)
754         elif sequence == "up":
755             product_obj.set_sequence_up(request.cr, request.uid, [id], context=request.context)
756         elif sequence == "down":
757             product_obj.set_sequence_down(request.cr, request.uid, [id], context=request.context)
758
759     @http.route(['/shop/change_styles/'], type='json', auth="public")
760     def change_styles(self, id, style_id):
761         product_obj = request.registry.get('product.template')
762         product = product_obj.browse(request.cr, request.uid, id, context=request.context)
763
764         remove = []
765         active = False
766         for style in product.website_style_ids:
767             if style.id == style_id:
768                 remove.append(style.id)
769                 active = True
770                 break
771
772         style = request.registry.get('website.product.style').browse(request.cr, request.uid, style_id, context=request.context)
773
774         if remove:
775             product.write({'website_style_ids': [(3, rid) for rid in remove]})
776         if not active:
777             product.write({'website_style_ids': [(4, style.id)]})
778
779         return not active
780
781     @http.route(['/shop/change_size/'], type='json', auth="public")
782     def change_size(self, id, x, y):
783         product_obj = request.registry.get('product.template')
784         product = product_obj.browse(request.cr, request.uid, id, context=request.context)
785         return product.write({'website_size_x': x, 'website_size_y': y})
786
787 # vim:expandtab:tabstop=4:softtabstop=4:shiftwidth=4: