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