1 # -*- coding: utf-8 -*-
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 _
9 PPG = 20 # Products Per Page
10 PPR = 4 # Products Per Row
12 class table_compute(object):
16 def _check_place(self, posx, posy, sizex, sizey):
18 for y in range(sizey):
19 for x in range(sizex):
23 row = self.table.setdefault(posy+y, {})
24 if row.setdefault(posx+x) is not None:
28 self.table[posy+y].setdefault(x, None)
31 def process(self, products):
32 # Compute products positions on the grid
43 while not self._check_place(pos%PPR, pos/PPR, x, y):
46 if index>PPG and (pos/PPR)>maxy:
49 if x==1 and y==1: # simple heuristic for CPU optimization
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))
60 maxy=max(maxy,y+(pos/PPR))
63 # Format table according to HTML needs
64 rows = self.table.items()
66 rows = map(lambda x: x[1], rows)
67 for col in range(len(rows)):
68 cols = rows[col].items()
71 rows[col] = [c for c in map(lambda x: x[1], cols) if c != False]
75 # TODO keep with input type hidden
78 class QueryURL(object):
79 def __init__(self, path='', **args):
83 def __call__(self, path=None, **kw):
86 for k,v in self.args.items():
89 for k,v in kw.items():
91 if isinstance(v, list) or isinstance(v, set):
92 l.append(werkzeug.url_encode([(k,i) for i in v]))
94 l.append(werkzeug.url_encode([(k,v)]))
96 path += '?' + '&'.join(l)
100 class website_sale(http.Controller):
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')
106 pricelist = sale_order.pricelist_id
108 partner = pool['res.users'].browse(cr, SUPERUSER_ID, uid, context=context).partner_id
109 pricelist = partner.property_product_pricelist
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
120 domain = request.website.sale_product_domain()
122 domain += ['|', ('name', 'ilike', search), ('description', 'ilike', search)]
124 domain += [('product_variant_ids.public_categ_id', 'child_of', int(category))]
126 attrib_values = map(int,request.httprequest.args.getlist('attrib'))
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)
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)
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)
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)
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)
155 'category': category and int(category),
156 'attrib_set': attrib_set,
158 'pricelist': self.get_pricelist(),
159 'products': products,
160 'bins': table_compute().process(products),
163 'categories': categs,
164 'attributes': attributes,
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]),
170 return request.website.render("website_sale.products", values)
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']
178 category = category_obj.browse(request.cr, request.uid, int(category), context=request.context)
180 attrib_values = map(int,request.httprequest.args.getlist('attrib'))
181 attrib_set = set(attrib_values)
183 keep = QueryURL('/shop', category=category and category.id, search=search, attrib=attrib_set)
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])
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)
195 'category': category,
196 'pricelist': self.get_pricelist(),
197 'attrib_set': attrib_set,
199 'category_list': category_list,
200 'main_object': product,
203 return request.website.render("website_sale.product", values)
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'),
213 subtype='mt_comment',
214 context=dict(context, mail_create_nosubcribe=True))
215 return werkzeug.utils.redirect(request.httprequest.referrer + "#comments")
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()
222 'suggested_products': [],
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)
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")
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)
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()
248 #------------------------------------------------------
250 #------------------------------------------------------
252 def checkout_redirection(self, order):
253 cr, uid, context, registry = request.cr, request.uid, request.context, request.registry
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')
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)
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')
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)
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) )
283 shipping_ids = orm_partner.search(cr, SUPERUSER_ID, [("parent_id", "=", partner.id), ('type', "=", 'delivery')], limit=1, context=context)
285 shipping = orm_user.browse(cr, SUPERUSER_ID, request.uid, context)
286 checkout.update( self.checkout_parse("shipping", shipping) )
287 checkout['shipping_different'] = True
289 order = request.website.sale_get_order(force_create=1, context=context)
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) )
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
302 'countries': countries,
304 'checkout': checkout,
305 'shipping_different': checkout.get('shipping_different'),
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"]
315 def checkout_parse(self, address_type, data):
316 """ data is a dict OR a partner browse record
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
324 all_fields = self.mandatory_shipping_fields + self.optional_shipping_fields
328 if isinstance(data, dict):
329 query = dict((field_name, data[field_name]) for field_name in all_fields if data.get(field_name))
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))
334 query[prefix + 'company'] = data.parent_id.name
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'])
343 def checkout_form_validate(self, data):
344 cr, uid, context, registry = request.cr, request.uid, request.context, request.registry
348 for field_name in self.mandatory_billing_fields:
349 if not data.get(field_name):
350 error[field_name] = 'missing'
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'
359 def checkout_form_save(self, post):
360 cr, uid, context, registry = request.cr, request.uid, request.context, request.registry
362 order = request.website.sale_get_order(force_create=1, context=context)
364 orm_partner = registry.get('res.partner')
365 orm_user = registry.get('res.users')
366 order_line_obj = request.registry.get('sale.order')
368 billing_info = self.checkout_parse('billing', post)
370 # save partner for order
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)
377 billing_info['parent_id'] = company_id
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
389 # save partner informations
391 orm_partner.write(cr, SUPERUSER_ID, [partner_id], billing_info, context=context)
393 partner_id = orm_partner.create(cr, SUPERUSER_ID, billing_info, context=context)
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
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)
407 # save shipping informations
409 shipping_id = shipping_ids[0]
410 orm_partner.write(cr, SUPERUSER_ID, [shipping_id], shipping_info, context)
412 shipping_id = orm_partner.create(cr, SUPERUSER_ID, shipping_info, context)
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
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')
423 order_line_obj.write(cr, SUPERUSER_ID, [order.id], order_info, context=context)
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
429 order = request.website.sale_get_order(force_create=1, context=context)
431 redirection = self.checkout_redirection(order)
435 values = self.checkout_values()
437 return request.website.render("website_sale.checkout", values)
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
443 order = request.website.sale_get_order(context=context)
445 redirection = self.checkout_redirection(order)
449 values = self.checkout_values(post)
450 values["error"] = self.checkout_form_validate(values["checkout"])
452 return request.website.render("website_sale.checkout", values)
454 self.checkout_form_save(values["checkout"])
455 request.session['sale_last_order_id'] = order.id
457 return request.redirect("/shop/payment")
459 #------------------------------------------------------
461 #------------------------------------------------------
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 :
468 - a draft sale order with lines; otherwise, clean context / session and
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
474 cr, uid, context = request.cr, request.uid, request.context
475 payment_obj = request.registry.get('payment.acquirer')
477 order = request.website.sale_get_order(context=context)
479 redirection = self.checkout_redirection(order)
483 shipping_partner_id = False
485 if order.partner_shipping_id.id:
486 shipping_partner_id = order.partner_shipping_id.id
488 shipping_partner_id = order.partner_invoice_id.id
491 'order': request.registry['sale.order'].browse(cr, SUPERUSER_ID, order.id, context=context)
493 values.update(request.registry.get('sale.order')._get_website_data(cr, uid, order, context))
495 # fetch all registered payment means
497 # acquirer_ids = [tx.acquirer_id.id]
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,
508 order.pricelist_id.currency_id.id,
509 partner_id=shipping_partner_id,
511 'return_url': '/shop/payment/validate',
515 return request.website.render("website_sale.payment", values)
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.
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
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)
534 if not order or not order.order_line or acquirer_id is None:
535 return request.redirect("/shop/checkout/")
537 # find an already existing transaction
538 tx = request.website.sale_get_transaction()
540 tx_id = transaction_obj.create(cr, SUPERUSER_ID, {
541 'acquirer_id': acquirer_id,
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,
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 ?
552 'acquirer_id': acquirer_id,
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)
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
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')
569 'message': '<p>There seems to be an error with your request.</p>',
572 tx_ids = request.registry['payment.transaction'].search(
574 '|', ('sale_order_id', '=', order.id), ('reference', '=', order.name)
578 if order.amount_total:
581 'message': '<p>There seems to be an error with your request.</p>',
588 tx = request.registry['payment.transaction'].browse(cr, uid, tx_ids[0], context=context)
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
598 message = '<p>Your transaction is waiting confirmation.</p>'
599 validation = tx.acquirer_id.validation
604 'validation': validation
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 :
614 cr, uid, context = request.cr, request.uid, request.context
616 sale_order_obj = request.registry['sale.order']
618 if transaction_id is None:
619 tx = request.website.sale_get_transaction()
621 tx = request.registry['payment.transaction'].browse(cr, uid, transaction_id, context=context)
623 if sale_order_id is None:
624 order = request.website.sale_get_order(context=context)
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')
629 if not tx or not order:
630 return request.redirect('/shop/')
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)
636 email_act = sale_order_obj.action_quotation_send(cr, SUPERUSER_ID, [order.id], context=request.context)
637 elif tx.state == 'pending':
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)
644 # clean context and session, then redirect to the confirmation page
645 request.website.sale_reset(context=context)
647 return request.redirect('/shop/confirmation/')
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 :
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
658 cr, uid, context = request.cr, request.uid, request.context
660 sale_order_id = request.session.get('sale_last_order_id')
662 order = request.registry['sale.order'].browse(cr, SUPERUSER_ID, sale_order_id, context=context)
664 return request.redirect('/shop/')
666 return request.website.render("website_sale.confirmation", {'order': order})
668 #------------------------------------------------------
670 #------------------------------------------------------
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
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)
681 return request.redirect("/shop/product/%s/?enable_editor=1" % product.product_tmpl_id.id)
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)
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)
694 for style in product.website_style_ids:
695 if style.id == style_id:
696 remove.append(style.id)
700 style = request.registry.get('product.style').browse(request.cr, request.uid, style_id, context=request.context)
703 product.write({'website_style_ids': [(3, rid) for rid in remove]})
705 product.write({'website_style_ids': [(4, style.id)]})
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})
716 # vim:expandtab:tabstop=4:softtabstop=4:shiftwidth=4: