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