def pricelist(self, promo, **post): cr, uid, context, model = request.cr, request.uid, request.context, request.registry uid = uid # If the code used is one product.gift, we check : validity and is ok, we create a new line in the cart with the amount. pg = model['product.gift'].search(cr, SUPERUSER_ID, [('code', '=', promo)], context=context) if len(pg): pg = model['product.gift'].browse(cr, SUPERUSER_ID, pg, context=context)[0] if pg.is_used: resp = request.redirect("/shop/cart?gift_msg=%s" % _("This code has been already used !")) elif pg.is_expired(): resp = request.redirect("/shop/cart?gift_msg=%s" % _("The code is expired")) else: order = request.website.sale_get_order(force_create=1) for ol in order.order_line: if ol.product_id.is_gift and ol.price_unit > 0: return request.redirect("/shop/cart?gift_msg=%s" % _("You can not use gift to buy another gift")) if ol.name == pg.code: return request.redirect("/shop/cart?gift_msg=%s" % _("This code already used in this order")) model['sale.order.line'].create(cr, SUPERUSER_ID, { 'order_id': order.id, 'product_id': request.env.ref('website_sale_gift.voucher_gift').product_variant_ids[0].id, 'product_uom_qty': 1, 'price_unit': pg.amount*-1, 'name': pg.code }, context=context) resp = request.redirect("/shop/cart?ok") # else we fallback on default pricelist code else: resp = super(website_sale_voucher, self).pricelist(promo, **post) return resp
def confirm_order(self, **post): cr, uid, context, registry = request.cr, request.uid, request.context, request.registry order = request.website.sale_get_order(context=context) if not order: return request.redirect("/shop") redirection = self.checkout_redirection(order) if redirection: return redirection values = self.checkout_values(post) values["error"], values["error_message"] = self.checkout_form_validate(values["checkout"]) if values["error"]: return request.website.render("website_sale.checkout", values) self.checkout_form_save(values["checkout"]) request.session['sale_last_order_id'] = order.id request.website.sale_get_order(update_pricelist=True, context=context) extra_step = registry['ir.model.data'].xmlid_to_object(cr, uid, 'website_sale.extra_info_option', raise_if_not_found=True) if extra_step.active: return request.redirect("/shop/extra_info") return request.redirect("/shop/payment")
def details(self, redirect=None, **post): partner = request.env['res.users'].browse(request.uid).partner_id values = { 'error': {}, 'error_message': [] } if post: error, error_message = self.details_form_validate(post) values.update({'error': error, 'error_message': error_message}) values.update(post) if not error: post.update({'zip': post.pop('zipcode', '')}) partner.sudo().write(post) if redirect: return request.redirect(redirect) return request.redirect('/my/home') countries = request.env['res.country'].sudo().search([]) states = request.env['res.country.state'].sudo().search([]) values.update({ 'partner': partner, 'countries': countries, 'states': states, 'has_check_vat': hasattr(request.env['res.partner'], 'check_vat'), 'redirect': redirect, }) return request.website.render("website_portal.details", values)
def claim_list(self, **kw): message_error = kw.get('message_error','') message_success = kw.get('message_success','') if request.httprequest.method == 'POST': ############################################################################## # cari dulu data member ############################################################################## Member = http.request.env['netpro.member'] member = Member.search([('card_no','=',kw.get('card_no','') )]) if not member: message = "Member not found! Please try again." return request.redirect('/claim/search?message_error=%s'% (message), code=301) ############################################################################## # cari data claim member tsb yang masih open ############################################################################## Claim = http.request.env['netpro.claim'] claim_ids = Claim.search([('member_id','=',member.id) ]) if not claim_ids: message = "Claim Registration not found!" return request.redirect('/claim/search?message_error=%s'% (message), code=301) # import pdb; pdb.set_trace() # claims = Claim.browse(claim_ids) return http.request.render('vit_claim_web.claim_list', {'message_error' : message_error, 'message_success' : message_success, 'claims' : claim_ids, 'member' : member } )
def cart_update(self, **post): has_paid_tickets = False post['free_tickets'] = 0 for key, value in post.items(): qty = int(value or "0") ticket_words = key.split("-") ticket_id = (ticket_words[0] == 'ticket' and int(ticket_words[1]) or None) if not qty or not ticket_id: continue ticket = request.env['event.event.ticket'].sudo().browse(ticket_id) if not ticket.price: # Accumulate possible multiple free tickets post['free_tickets'] = ( str(int(post['free_tickets']) + qty)) else: has_paid_tickets = True # Add to shopping cart the rest of the items order = request.website.sale_get_order(force_create=1) order.with_context(event_ticket_id=ticket.id)._cart_update( product_id=ticket.product_id.id, add_qty=qty) if not post['free_tickets'] and not has_paid_tickets: return request.redirect("/event/%s" % post['event_id']) request.session.update({ 'free_tickets': post['free_tickets'], 'event_id': post['event_id'], }) return request.redirect("/shop/checkout")
def confirm_order(self, country='', **post): cr, uid, context, registry = request.cr, request.uid, request.context, request.registry order = request.website.sale_get_order(context=context) if not order and country: return request.redirect("/shop/country/%s/country_defined" % slug(country)) if not order and not country: return request.redirect("/shop") redirection = self.checkout_redirection(order) if redirection: return redirection values = self.checkout_values(post) values["error"] = self.checkout_form_validate(values["checkout"]) if values["error"] and country: values.update({'current_country': country}) return request.website.render("website_sale.checkout", values) if values["error"] and not country: return request.website.render("website_sale.checkout", values) self.checkout_form_save(values["checkout"]) request.session['sale_last_order_id'] = order.id request.website.sale_get_order(update_pricelist=True, context=context) if country: return request.redirect("/shop/payment/%s" % slug(country)) if not country: return request.redirect("/shop/payment")
def extra_info(self, **post): cr, uid, context, registry = request.cr, request.uid, request.context, request.registry # Check that this option is activated extra_step = registry['ir.model.data'].xmlid_to_object(cr, uid, 'website_sale.extra_info_option', raise_if_not_found=True) if not extra_step.active: return request.redirect("/shop/payment") # check that cart is valid order = request.website.sale_get_order(context=context) redirection = self.checkout_redirection(order) if redirection: return redirection # if form posted if 'post_values' in post: values = {} for field_name, field_value in post.items(): if field_name in request.registry['sale.order']._fields and field_name.startswith('x_'): values[field_name] = field_value if values: order.write(values) return request.redirect("/shop/payment") values = { 'website_sale_order': order } sale_order_obj = request.registry.get('sale.order') values.update(sale_order_obj._get_website_data(cr, uid, order, context)) return request.website.render("website_sale.extra_info", values)
def confirm_order(self, **post): cr, uid, context, registry = request.cr, request.uid, request.context, request.registry order = request.website.sale_get_order(context=context) sale_order_obj = request.registry.get('sale.order') if not order: return request.redirect("/shop") print order.id redirection = self.checkout_redirection(order) if redirection: return redirection values = self.checkout_values(post) values.update({'errors':''}) values["error"] = self.checkout_form_validate(values["checkout"]) if values["error"]: return request.website.render("website_sale.checkout", values) values['errors'] = sale_order_obj._check_point(cr, SUPERUSER_ID, order.id, context=context) if values['errors']: return request.website.render("website_sale.checkout", values) self.checkout_form_save(values["checkout"]) request.session['sale_last_order_id'] = order.id request.website.sale_get_order(update_pricelist=True, context=context) return request.redirect("/shop/payment")
def partner_list(self, **kw): message_error = kw.get('message_error','') message_success = kw.get('message_success','') if request.httprequest.method == 'POST': ############################################################################## # cari dulu data member ############################################################################## Member = http.request.env['netpro.member'] member = Member.search([('card_no','=',kw.get('card_no','') )]) if not member: message = "Member not found! Please try again." return request.redirect('/Partner/search?message_error=%s'% (message), code=301) ############################################################################## # cari data Partner member tsb yang masih open ############################################################################## Partner = http.request.env['netpro.Partner'] Partner_ids = Partner.search([('member_id','=',member.id) ]) if not Partner_ids: message = "Partner Registration not found!" return request.redirect('/Partner/search?message_error=%s'% (message), code=301) # import pdb; pdb.set_trace() # Partners = Partner.browse(Partner_ids) return http.request.render('vit_universities_web.Partner_list', {'message_error' : message_error, 'message_success' : message_success, 'Partners' : Partner_ids, 'member' : member } )
def payment_validate(self, transaction_id=None, sale_order_id=None, **post): """ Method that should be called by the server when receiving an update for a transaction. State at this point : - UPDATE ME """ cr, uid, context = request.cr, request.uid, request.context email_act = None sale_order_obj = request.registry['sale.order'] if transaction_id is None: tx = request.website.sale_get_transaction() else: tx = request.registry['payment.transaction'].browse(cr, uid, transaction_id, context=context) if sale_order_id is None: order = request.website.sale_get_order(context=context) else: order = request.registry['sale.order'].browse(cr, SUPERUSER_ID, sale_order_id, context=context) assert order.id == request.session.get('sale_last_order_id') if not order or (order.amount_total and not tx): return request.redirect('/shop') if (not order.amount_total and not tx) or tx.state in ['pending', 'done']: if (not order.amount_total and not tx): # Orders are confirmed by payment transactions, but there is none for free orders, # (e.g. free events), so confirm immediately order.action_button_confirm() # send by email email_act = sale_order_obj.action_quotation_send(cr, SUPERUSER_ID, [order.id], context=request.context) elif tx and tx.state == 'cancel': # cancel the quotation sale_order_obj.action_cancel(cr, SUPERUSER_ID, [order.id], context=request.context) # send the email if email_act and email_act.get('context'): composer_obj = request.registry['mail.compose.message'] composer_values = {} email_ctx = email_act['context'] template_values = [ email_ctx.get('default_template_id'), email_ctx.get('default_composition_mode'), email_ctx.get('default_model'), email_ctx.get('default_res_id'), ] composer_values.update(composer_obj.onchange_template_id(cr, SUPERUSER_ID, None, *template_values, context=context).get('value', {})) if not composer_values.get('email_from') and uid == request.website.user_id.id: composer_values['email_from'] = request.website.user_id.company_id.email for key in ['attachment_ids', 'partner_ids']: if composer_values.get(key): composer_values[key] = [(6, 0, composer_values[key])] composer_id = composer_obj.create(cr, SUPERUSER_ID, composer_values, context=email_ctx) composer_obj.send_mail(cr, SUPERUSER_ID, [composer_id], context=email_ctx) # clean context and session, then redirect to the confirmation page request.website.sale_reset(context=context) return request.redirect('/shop/confirmation')
def cart_update(self, product_id, current_country='', country='', add_qty=1, set_qty=0, **kw): cr, uid, context, pool = request.cr, request.uid, request.context, request.registry request.website.sale_get_order(force_create=1)._cart_update(product_id=int(product_id), add_qty=float(add_qty), set_qty=float(set_qty)) country_obj=pool['res.country'] if current_country!='': return request.redirect("/shop/cart/"+current_country) if not current_country: return request.redirect("/shop/cart")
def pricelist(self, promo, **post): cr, uid, pool, context = request.cr, request.uid, request.registry, request.context pl = pool['product.pricelist'].search(cr, SUPERUSER_ID, [('code', '=', promo)], context=context) if pl: if not request.website.is_pricelist_available(pl[0], context=context): return request.redirect("/shop/cart?code_not_available=1") request.website.sale_get_order(code=promo, context=context) return request.redirect("/shop/cart")
def send_invitation(self, member, **kwargs): print "ni" try: request.registry['res.partner'].action_invite(request.cr, SUPERUSER_ID, [member.id], request.context) message = _("Invitation sent to %s") % (member.name) #Votre invitation a été transmise à return request.redirect('/mlm?message_success=%s' % (message), code=301) except Exception, e: message = str(e) return request.redirect('/mlm?message_error=%s' % (message), code=301)
def validate_email(self, token, id, email, forum_id=None, **kwargs): if forum_id: try: forum_id = int(forum_id) except ValueError: forum_id = None done = request.env['res.users'].sudo().browse(int(id)).process_forum_validation_token(token, email, forum_id=forum_id)[0] if done: request.session['validation_email_done'] = True if forum_id: return request.redirect("/forum/%s" % int(forum_id)) return request.redirect('/forum')
def checkout_redirection(self, order): cr, uid, context, registry = request.cr, request.uid, request.context, request.registry # must have a draft sale order with lines at this point, otherwise reset if not order or order.state != 'draft': request.session['sale_order_id'] = None request.session['sale_transaction_id'] = None return request.redirect('/shop') # if transaction pending / done: redirect to confirmation tx = context.get('website_sale_transaction') if tx and tx.state != 'draft': return request.redirect('/shop/payment/confirmation/%s' % order.id)
def payment_validate(self, transaction_id=None, sale_order_id=None, **post): """ Method that should be called by the server when receiving an update for a transaction. State at this point : - UDPATE ME """ cr, uid, context = request.cr, request.uid, request.context email_act = None sale_order_obj = request.registry["sale.order"] if transaction_id is None: tx = request.website.sale_get_transaction() else: tx = request.registry["payment.transaction"].browse(cr, uid, transaction_id, context=context) if sale_order_id is None: order = request.website.sale_get_order(context=context) else: order = request.registry["sale.order"].browse(cr, SUPERUSER_ID, sale_order_id, context=context) assert order.id == request.session.get("sale_last_order_id") if not order or (order.amount_total and not tx): return request.redirect("/shop") if (not order.amount_total and not tx) or tx.state in ["pending", "done"]: if not order.amount_total and not tx: # Orders are confirmed by payment transactions, but there is none for free orders, # (e.g. free events), so confirm immediately order.action_button_confirm() # send by email email_act = sale_order_obj.action_quotation_send(cr, SUPERUSER_ID, [order.id], context=request.context) elif tx and tx.state == "cancel": # cancel the quotation sale_order_obj.action_cancel(cr, SUPERUSER_ID, [order.id], context=request.context) # send the email if email_act and email_act.get("context"): composer_values = {} email_ctx = email_act["context"] public_id = request.website.user_id.id if uid == public_id: composer_values["email_from"] = request.website.user_id.company_id.email composer_id = request.registry["mail.compose.message"].create( cr, SUPERUSER_ID, composer_values, context=email_ctx ) request.registry["mail.compose.message"].send_mail(cr, SUPERUSER_ID, [composer_id], context=email_ctx) # clean context and session, then redirect to the confirmation page request.website.sale_reset(context=context) return request.redirect("/shop/confirmation")
def checkout(self, **post): cr, uid, context = request.cr, request.uid, request.context context.update({'checkout' : True}) _logger.debug("Request for checkout page received") order = request.website.sale_get_order(force_create=1, context=context) #adapt when delivery method is changed carrier_id = post.get('carrier_id') if carrier_id: carrier_id = int(carrier_id) _logger.debug("carrierID : %d", carrier_id) if order: _logger.debug("orderID : %d", order.id) request.registry['sale.order']._check_carrier_quotation(cr, uid, order, force_carrier_id=carrier_id, context=context) if carrier_id: return request.redirect("/shop/checkout") redirection = self.checkout_redirection(order) if redirection: _logger.debug("checkout : redirection") return redirection values = self.checkout_values() #need delivery informations #TODO : overload checkout_values instead of adding get_website_data sale_order_obj = request.registry.get('sale.order') values.update(sale_order_obj._get_website_data(cr, uid, order, context)) #need shipping informations of the shop #order = request.website.sale_get_order(force_create=1, context=context) _logger.debug("order.carrier_id : %d", order.carrier_id) _logger.debug("order.carrier_id.name : %s", order.carrier_id.name) return request.website.render("website_sale.checkout", values)
def jobs_thankyou(self, **post): error = {} for field_name in ["partner_name", "phone", "email_from"]: if not post.get(field_name): error[field_name] = 'missing' if error: request.session['website_hr_recruitment_error'] = error ufile = post.pop('ufile') if ufile: error['ufile'] = 'reset' request.session['website_hr_recruitment_default'] = post return request.redirect('/jobs/apply/%s' % post.get("job_id")) # public user can't create applicants (duh) env = request.env(user=SUPERUSER_ID) value = { 'name': '%s\'s Application' % post.get('partner_name'), } for f in ['email_from', 'partner_name', 'description']: value[f] = post.get(f) for f in ['department_id', 'job_id']: value[f] = int(post.get(f) or 0) # Retro-compatibility for saas-3. "phone" field should be replace by "partner_phone" in the template in trunk. value['partner_phone'] = post.pop('phone', False) applicant = env['hr.applicant'].create(value) if post['ufile']: name = applicant.partner_name if applicant.partner_name else applicant.name applicant.message_post( body = _("%s's Application \n From: %s \n\n %s \n") % (name, applicant.email_from or "", applicant.description or ""), attachments = [(post['ufile'].filename, post['ufile'].read())], content_subtype = 'plaintext', subtype = "hr_recruitment.mt_applicant_hired") return request.render("website_hr_recruitment.thankyou", {})
def cart_update(self, product_id, add_qty=1, set_qty=0, **kw): MIN_QTY = 1 resp = request.website.sale_get_order(force_create=1)._cart_update(product_id=int(product_id), add_qty=float(add_qty), set_qty=float(set_qty), line_id=False) order = request.website.sale_get_order() values = {} for line in order.order_line: if line.id == resp.get('line_id'): if not order.afwerkingpicker: values = {'afwerkingpicker': request.session['aa_houbolak_afwerking']} if line.aantal > 0: resultaatBerekening = int(kw.get('hoogteWebshop')) * int(kw.get('breedteWebshop')) / 1000000 * line.aantal else: resultaatBerekening = int(kw.get('hoogteWebshop')) * int(kw.get('breedteWebshop')) / 1000000 * float(add_qty) _logger.critical("line.aantal: " + str(line.aantal) + "add_qty: " + str(add_qty) + " resultaatBerekening: " + str(resultaatBerekening)) values['order_line'] = [(1, line.id, { 'hoogte': int(kw.get('hoogteWebshop')), 'breedte': int(kw.get('breedteWebshop')), 'aantal': float(add_qty), 'product_uom_qty': max(resultaatBerekening, MIN_QTY), 'links': bool(kw.get('linksWebshop')), 'rechts': bool(kw.get('rechtsWebshop')), 'boven': bool(kw.get('bovenWebshop')), 'onder': bool(kw.get('onderWebshop')), 'boringen': kw.get('boringenWebshop', ''), 'opmerkingen': kw.get('opmerkingenWebshop', ''), })] order.write(values) break return request.redirect("/shop/cart")
def manual_confirmation(self, **post): cr, uid, context = request.cr, request.uid, request.context order = request.website.sale_get_order(force_create=1, context=context) order_obj = request.registry['sale.order'] contact_pool = request.registry['sale.contact.website'] contact_ids = contact_pool.search(cr, uid, []) order.with_context(dict(context, send_email=True)).write({'state': 'sent'}) if order: partners_contact = [] for v in contact_pool.browse(cr, 1, contact_ids): partners_contact.append(v.user_id.partner_id.id) message = "New order: %s" % order.name or '' order.send_notification_to_contact('sale.order', partners_contact, message=message, context={}) if not order: return request.redirect('/shop') #order.with_context(dict(context, send_email=True)).action_confirm() # clean context and session, then redirect to the confirmation page request.website.sale_reset(context=context) request.session.update({ 'website_sale_order': False, }) return request.website.render("website_no_payment.order_confirmed", {'order': order})
def survey_wrapper(self, assignment, token, prev=None, **post): '''wraps a response''' cr, uid, context = request.cr, request.uid, request.context assignment_obj = request.registry['mqo.assignment'] survey_obj = request.registry['survey.survey'] user_input_obj = request.registry['survey.user_input'] # Controls if the survey can be displayed errpage = self._check_bad_cases(cr, uid, request, assignment, assignment_obj, token, context=context) if errpage: return errpage # see if response for this assignment already exists, and create one for this assignment if needed. try: user_input_id = user_input_obj.search(cr, SUPERUSER_ID, [('token', '=', assignment.response_token)], context=context)[0] except IndexError: # No response currently exists for this assignment vals = {'survey_id': assignment.response_survey.id, 'learner': assignment.learner.id, 'token': assignment.response_token, 'state': 'skip'} user_input_id = user_input_obj.create(cr, uid, vals, context=context) user_input = user_input_obj.browse(cr, uid, [user_input_id], context=context)[0] # record response in assignment assignment.write({'responses': user_input_id}) else: user_input = user_input_obj.browse(cr, SUPERUSER_ID, [user_input_id], context=context)[0] return request.redirect('/exercise/fill/%s/%s' % (assignment.response_survey.id, user_input.token))
def start_build(self, build): try: build.sudo().start_server() except Exception as e: _logger.error(e) return request.redirect('/runbot/build/%s' % slug(build))
def jobs_add(self, **kwargs): cr, uid, context = request.cr, request.uid, request.context value = { 'name': _('New Job Offer'), } job_id = request.registry.get('hr.job').create(cr, uid, value, context=context) return request.redirect("/jobs/detail/%s?enable_editor=1" % job_id)
def confirm_order(self, **post): """ Al confirmar el pedido, antes de la pantalla de pago se vuelve a comprobar que el cliente podia usar el cupón, esto se hace porque en los pasos anteriores la venta podía estar asociada a public user. En caso de que no se pudiera usar el cupon se elimina la linea de descuento y se vuelve al paso del carrito mostrando un mensaje de error. """ res = super(WebsiteCoupon, self).confirm_order(**post) if 'error' in res.qcontext: return res order = request.website.sale_get_order() used_coupon = order.coupons if not used_coupon: return res number_of_uses = 0 partner_count = request.env['partner.coupon'].sudo().search( [('coupon', '=', used_coupon.code), ('partner_id', '=', order.partner_id.id)], limit=1) if partner_count: number_of_uses = partner_count.number - 1 correct_coupon = True if number_of_uses >= used_coupon.limit: correct_coupon = False if used_coupon.partner_id and used_coupon.partner_id != order.partner_id: correct_coupon = False if correct_coupon: return res used_coupon.total_avail += 1 order.order_line.filtered(lambda x: x.coupon_discount_line).unlink() order.write({'coupons': [(3, used_coupon.id)]}) return request.redirect("/shop/cart?coupon_not_available=1")
def _handle_exception(self, exception, code=500): code = getattr(exception, 'code', code) if code == 404: page = request.httprequest.path logger.info("Resolving 404 error code... %s" % (page)) url_conf = request.registry['ir.config_parameter'] url = url_conf.get_param(request.cr, request.uid, 'website.notfound_redirect_url') url_request = "%s%s" % (url, page) if url: logger.info("Checking remote url: %s" % (url_request)) try: req = urllib2.Request(url_request) request_old = urllib2.urlopen(req) except (urllib2.HTTPError, urllib2.URLError): request_old = False else: logger.info("No url to redirect defined") return super(ir_http, self)._handle_exception(exception, code) if url and request_old: logger.info("Redirect to %s" % (url_request)) return request.redirect(url_request, code=302) else: logger.info("URL remote not found: %s" % (url_request)) return super(ir_http, self)._handle_exception(exception, code) return super(ir_http, self)._handle_exception(exception, code)
def actions_server(self, path_or_xml_id_or_id, **post): cr, uid, context = request.cr, request.uid, request.context res, action_id, action = None, None, None ServerActions = request.registry['ir.actions.server'] # find the action_id: either an xml_id, the path, or an ID if isinstance(path_or_xml_id_or_id, basestring) and '.' in path_or_xml_id_or_id: action_id = request.registry['ir.model.data'].xmlid_to_res_id(request.cr, request.uid, path_or_xml_id_or_id, raise_if_not_found=False) if not action_id: action_ids = ServerActions.search(cr, uid, [('website_path', '=', path_or_xml_id_or_id), ('website_published', '=', True)], context=context) action_id = action_ids and action_ids[0] or None if not action_id: try: action_id = int(path_or_xml_id_or_id) except ValueError: pass # check it effectively exists if action_id: action_ids = ServerActions.exists(cr, uid, [action_id], context=context) action_id = action_ids and action_ids[0] or None # run it, return only if we got a Response object if action_id: action = ServerActions.browse(cr, uid, action_id, context=context) if action.state == 'code' and action.website_published: action_res = ServerActions.run(cr, uid, [action_id], context=context) if isinstance(action_res, werkzeug.wrappers.Response): res = action_res if res: return res return request.redirect('/')
def confirm_order(self, **post): cr, uid, context, registry = request.cr, request.uid, request.context, request.registry context.update({'checkout' : False}) #more check than for checkout values order = request.website.sale_get_order(context=context) if not order: return request.redirect("/shop") # carrier_id = order.carrier_id.id _logger.debug("order carrier name start of confirm order : %s", order.carrier_id.name) # redirection = self.checkout_redirection(order) if redirection: return redirection values = self.checkout_values(post) if (post.get('shipping_name')) : #needed to check delivery date depending on delivery method values["checkout"]['shipping_name'] = post.get('shipping_name') values["error"] = self.checkout_form_validate(values["checkout"]) if values["error"]: #need delivery informations sale_order_obj = request.registry.get('sale.order') values.update(sale_order_obj._get_website_data(cr, uid, order, context)) return request.website.render("website_sale.checkout", values) self.checkout_form_save(values["checkout"]) request.website.sale_get_order(update_pricelist=True, context=context) #check carrier quotation should be called after sale get order with update pricelist if not request.registry['sale.order']._check_carrier_quotation(cr, uid, order, force_carrier_id=carrier_id, context=context) : _logger.debug("Delivery carrier has changed, send error to qweb") #need delivery informations sale_order_obj = request.registry.get('sale.order') context.update({'checkout' : True}) values.update(sale_order_obj._get_website_data(cr, uid, order, context)) values.update(self.checkout_values()) #update carrier info values["error"].update({'delivery_zip' : 'not_available'}) return request.website.render("website_sale.checkout", values) request.session['sale_last_order_id'] = order.id return request.redirect("/shop/payment")
def cart_update(self, product_id, add_qty=1, set_qty=0, **kw): cr, uid, context = request.cr, request.uid, request.context product = request.registry['product.product'].browse(cr, SUPERUSER_ID, int(product_id), context=context) # Validate (donation) Arbitrary Price warnings = None price = kw.get('price_donate') or product.list_price or product.price # HINT: If price_donate is not a valid number it will be empty and so the product.list_price is used! # Therefore the try statement is not really needed (but kept for safety). try: if product.price_donate_min and float(product.price_donate_min) > float(price): warnings = _('Value must be higher or equal to %s.' % float(product.price_donate_min)) except ValueError: warnings = _('Value must be a valid Number.') pass if warnings: return request.redirect('/shop/product/%s?&warnings=%s' % (product.product_tmpl_id.id, warnings)) # Check Payment Interval # INFO: This is only needed if products are directly added to cart on shop pages (product listings) if 'payment_interval_id' not in kw: if product.payment_interval_ids: kw['payment_interval_id'] = product.payment_interval_ids[0].id # Call Super # INFO: Pass kw to _cart_update to transfer all post variables to _cart_update # This is needed to get the Value of the arbitrary price from the input field request.website.sale_get_order(force_create=1, context=context)._cart_update(product_id=int(product_id), add_qty=float(add_qty), set_qty=float(set_qty), context=context, **kw) # If simple_checkout is set for the product redirect directly to checkout or confirm_order if product.simple_checkout or kw.get('simple_checkout'): kw.pop('simple_checkout', None) if kw.get('email') and kw.get('name') and kw.get('shipping_id'): return request.redirect('/shop/confirm_order' + '?' + request.httprequest.query_string) return request.redirect('/shop/checkout' + '?' + request.httprequest.query_string) # Stay on the current page if "Add to cart and stay on current page" is set if request.session.get('last_page') and request.website['add_to_cart_stay_on_page']: return request.redirect(request.session['last_page']) # Redirect to the shopping cart return request.redirect("/shop/cart")
def payment_transaction(self, acquirer_id): """ Json method that creates a payment.transaction, used to create a transaction when the user clicks on 'pay now' button. After having created the transaction, the event continues and the user is redirected to the acquirer website. :param int acquirer_id: id of a payment.acquirer record. If not set the user is redirected to the checkout page """ cr, uid, context = request.cr, request.uid, request.context payment_obj = request.registry.get('payment.acquirer') transaction_obj = request.registry.get('payment.transaction') order = request.website.sale_get_order(context=context) if not order or not order.order_line or acquirer_id is None: return request.redirect("/shop/checkout") assert order.partner_id.id != request.website.partner_id.id # find an already existing transaction tx = request.website.sale_get_transaction() if tx: tx_id = tx.id if tx.sale_order_id.id != order.id or tx.state in ['error', 'cancel'] or tx.acquirer_id.id != acquirer_id: tx = False tx_id = False elif tx.state == 'draft': # button cliked but no more info -> rewrite on tx or create a new one ? tx.write(dict(transaction_obj.on_change_partner_id(cr, uid, None, order.partner_id.id, context=context).get('values', {}), amount=order.amount_total)) if not tx: tx_id = transaction_obj.create(cr, SUPERUSER_ID, { 'acquirer_id': acquirer_id, 'type': 'form', 'amount': order.amount_total, 'currency_id': order.pricelist_id.currency_id.id, 'partner_id': order.partner_id.id, 'partner_country_id': order.partner_id.country_id.id, 'reference': request.env['payment.transaction'].get_next_reference(order.name), 'sale_order_id': order.id, }, context=context) request.session['sale_transaction_id'] = tx_id tx = transaction_obj.browse(cr, SUPERUSER_ID, tx_id, context=context) # update quotation request.registry['sale.order'].write( cr, SUPERUSER_ID, [order.id], { 'payment_acquirer_id': acquirer_id, 'payment_tx_id': request.session['sale_transaction_id'] }, context=context) return payment_obj.render( cr, SUPERUSER_ID, tx.acquirer_id.id, tx.reference, order.amount_total, order.pricelist_id.currency_id.id, partner_id=order.partner_shipping_id.id or order.partner_invoice_id.id, tx_values={ 'return_url': '/shop/payment/validate', }, context=dict(context, submit_class='btn btn-primary', submit_txt=_('Pay Now')))
def payment(self, **post): """ Payment step. This page proposes several payment means based on available payment.acquirer. State at this point : - a draft sale order with lines; otherwise, clean context / session and back to the shop - no transaction in context / session, or only a draft one, if the customer did go to a payment.acquirer website but closed the tab without paying / canceling """ cr, uid, context = request.cr, request.uid, request.context payment_obj = request.registry.get('payment.acquirer') sale_order_obj = request.registry.get('sale.order') order = request.website.sale_get_order(context=context) redirection = self.checkout_redirection(order) if redirection: return redirection shipping_partner_id = False if order: if order.partner_shipping_id.id: shipping_partner_id = order.partner_shipping_id.id else: shipping_partner_id = order.partner_invoice_id.id values = { 'order': request.registry['sale.order'].browse(cr, SUPERUSER_ID, order.id, context=context) } values['errors'] = sale_order_obj._get_errors(cr, uid, order, context=context) values.update(sale_order_obj._get_website_data(cr, uid, order, context)) # fetch all registered payment means # if tx: # acquirer_ids = [tx.acquirer_id.id] # else: values['errors'] = sale_order_obj._check_point(cr, SUPERUSER_ID, order.id, context=context) if not values['errors']: acquirer_ids = payment_obj.search(cr, SUPERUSER_ID, [('website_published', '=', True), ('company_id', '=', order.company_id.id)], context=context) values['acquirers'] = list(payment_obj.browse(cr, uid, acquirer_ids, context=context)) render_ctx = dict(context, submit_class='btn btn-primary', submit_txt=_('Pay Now')) for acquirer in values['acquirers']: acquirer.button = payment_obj.render( cr, SUPERUSER_ID, acquirer.id, order.name, order.amount_total, order.pricelist_id.currency_id.id, partner_id=shipping_partner_id, tx_values={ 'return_url': '/shop/payment/validate', }, context=render_ctx) else: return request.redirect('/shop/checkout') return request.website.render("website_sale.payment", values)
def checkout(self, contact_name=None, email_from=None, phone=None): cr = request.cr uid = request.uid context = request.context post = { 'contact_name':contact_name or email_from, 'email_from':email_from, 'phone':phone, } error = set(field for field in ['email_from'] if not post.get(field)) values = dict(post, error=error) if error: return request.website.render("website_sale.checkout", values) ## find or create partner partner_obj = request.registry['res.partner'] partner_id = partner_obj.search(request.cr, SUPERUSER_ID, [('email', '=', values['email_from'])]) if partner_id: partner_id = partner_id[0] partner = partner_obj.browse(cr, SUPERUSER_ID, partner_id) values = {} for pk, k in [('name', 'contact_name'), ('phone','phone')]: if post[k]: values[pk] = post[k] if values: partner.write(values) else: partner_id = partner_obj.create(request.cr, SUPERUSER_ID, {'name':values['contact_name'], 'email':values['email_from']}) order = request.website.sale_get_order() #order_obj = request.registry.get('sale.order') order.write({'partner_id':partner_id}) section_ids = {} for line in order.order_line: if not line.product_id.section_id: continue id = line.product_id.section_id.id if id not in section_ids: section_ids[id] = [] section_ids[id].append(line) order_ids = [] for section_id, lines in section_ids.iteritems(): order_id = order.copy({'parent_id': order.id, 'section_id': section_id, 'order_line': [(5, 0, 0)]}) for line in lines: line.copy({'order_id':order_id.id}) request.registry.get('sale.order').signal_workflow(cr, SUPERUSER_ID, order_ids, 'quotation_sent') request.registry.get('sale.order').signal_workflow(cr, SUPERUSER_ID, [order.id], 'cancel') ## send email ir_model_data = request.registry['ir.model.data'] template_id = ir_model_data.get_object_reference(cr, uid, 'website_sales_team', 'email_template_checkout')[1] email_ctx = dict(context) email_ctx.update({ 'default_model': 'sale.order', 'default_res_id': order.id, 'default_use_template': bool(template_id), 'default_template_id': template_id, 'default_composition_mode': 'comment', #'mark_so_as_sent': True }) composer_values = {} public_id = request.website.user_id.id if uid == public_id: composer_values['email_from'] = request.website.user_id.company_id.email composer_id = request.registry['mail.compose.message'].create(cr, SUPERUSER_ID, composer_values, context=email_ctx) request.registry['mail.compose.message'].send_mail(cr, SUPERUSER_ID, [composer_id], context=email_ctx) request.website.sale_reset(context=context) return request.redirect('/shop/ready')
def slide_set_promoted(self, slide): slide.channel_id.promoted_slide_id = slide.id return request.redirect("/slides/%s" % slide.channel_id.id)
def ogonedadi_form_feedback(self, **post): """ Ogone contacts using GET, at least for accept """ _logger.info( 'Ogonedadi: entering form_feedback with post data: \n%s\n', pprint.pformat(post)) # debug cr, uid, context = request.cr, SUPERUSER_ID, request.context # Get the Tx related to the post data of ogone tx_obj = request.registry['payment.transaction'] tx = getattr(tx_obj, '_ogonedadi_form_get_tx_from_data')(cr, SUPERUSER_ID, post, context=context) # Prepare Variables state_old = False do_not_send_status_email = False redirect_url_after_form_feedback = None # Get Redirect URL from website settings if request.website: redirect_url_after_form_feedback = request.website.redirect_url_after_form_feedback or None if tx: # Store Current State of the transaction state_old = tx.state if tx.acquirer_id: do_not_send_status_email = tx.acquirer_id.do_not_send_status_email # Overwrite redirect URL from payment-provider setting redirect_url_after_form_feedback = tx.acquirer_id.redirect_url_after_form_feedback # Overwrite redirect URL from sales-order root_cat setting if tx.sale_order_id \ and tx.sale_order_id.cat_root_id \ and tx.sale_order_id.cat_root_id.redirect_url_after_form_feedback: redirect_url_after_form_feedback = tx.sale_order_id.cat_root_id.redirect_url_after_form_feedback # Error Transaction not found else: _logger.error( _('Could not find correct Transaction for Ogonedadi Transaction-Form-Feedback!' )) if redirect_url_after_form_feedback: return request.redirect(redirect_url_after_form_feedback) else: return request.redirect( request.registry.get('last_shop_page') or request.registry.get('last_page') or '/') # Update the payment.transaction and the Sales Order: # form_feedback will call finally _ogonedadi_form_validate (call besides others) and return True or False # INFO: form_feedback is also inherited by website_sale and website_sale_payment_fix request.registry['payment.transaction'].form_feedback(cr, uid, post, 'ogonedadi', context=context) # If the state changed send an E-Mail (have to do it here since we do not call /payment/validate for ogonedadi) # HINT: we call a special E-Mail template "email_template_webshop" defined in website_sale_payment_fix # for this to work we extended "action_quotation_send" interface with email_template_modell and ..._name if tx.state != state_old and not do_not_send_status_email: _logger.info('Ogonedadi: Send E-Mail for Sales order: \n%s\n', pprint.pformat(tx.sale_order_id.name)) email_act = request.registry['sale.order'].action_quotation_send( cr, SUPERUSER_ID, [tx.sale_order_id.id], context=context, email_template_modell='website_sale_payment_fix', email_template_name='email_template_webshop') if email_act and email_act.get('context'): composer_obj = request.registry['mail.compose.message'] composer_values = {} email_ctx = email_act['context'] template_values = [ email_ctx.get('default_template_id'), email_ctx.get('default_composition_mode'), email_ctx.get('default_model'), email_ctx.get('default_res_id'), ] composer_values.update( composer_obj.onchange_template_id(cr, SUPERUSER_ID, None, *template_values, context=context).get( 'value', {})) if not composer_values.get( 'email_from') and uid == request.website.user_id.id: composer_values[ 'email_from'] = request.website.user_id.company_id.email for key in ['attachment_ids', 'partner_ids']: if composer_values.get(key): composer_values[key] = [(6, 0, composer_values[key])] composer_id = composer_obj.create(cr, SUPERUSER_ID, composer_values, context=email_ctx) composer_obj.send_mail(cr, SUPERUSER_ID, [composer_id], context=email_ctx) # Redirect ot our own Confirmation page (instead of calling /payment/validate) # all the stuff that could be done by /payment/validate for SO was already done by website_sale_payment_fix # "form_feedback" so we are no longer session variable dependent! if tx: if redirect_url_after_form_feedback and '?' not in redirect_url_after_form_feedback: redirect_url_after_form_feedback += '?' # Add the order_id to the GET variables of the redirect URL order_id = '&order_id=' if tx.sale_order_id: order_id += str(tx.sale_order_id.id) if redirect_url_after_form_feedback: return request.redirect(redirect_url_after_form_feedback + order_id) else: return request.redirect('/shop/confirmation_static?' + order_id)
def confirm_agent_order(self, **post): if not post: return request.redirect('/shop') env = request.env website = request.website order_obj = env['sale.order'] order = website.sale_get_order() if not order: order = order_obj.sudo().browse( int(request.session.get('sale_last_order_id'))) if not order: return request.redirect('/shop') return website.render('website_sale_checkout_agent.agent_confirm', {'order': order}) order_info = {} if post.get('partner_id') != 'new-customer': partner = env['res.partner'].sudo().browse( int(post.get('partner_id'))) order_info.update({ 'partner_id': partner.id, 'fiscal_position': partner.property_account_position.id, 'message_follower_ids': [(4, partner.id), (3, request.website.partner_id.id)], 'partner_shipping_id': (int(post.get('partner_shipping_id'))), 'partner_invoice_id': (int(post.get('partner_invoice_id'))) }) order_info.update(order.sudo().onchange_partner_id( partner.id)['value']) else: partner = order.partner_id.root_partner_id order_info.update({'partner_id': partner.id}) order_info.update(order.sudo().onchange_partner_id( partner.id)['value']) fiscal_update = order.sudo().onchange_fiscal_position( partner.property_account_position.id, [(4, l.id) for l in order.order_line])['value'] order_info.update(fiscal_update) transaction_obj = env['payment.transaction'] note = post.get('note') order_info.update({'note': note}) order.sudo().write(order_info) season = None order.recalculate_prices() for line in order.order_line: season = line.product_id.season_id request.session['sale_last_order_id'] = order.id acquired = env.ref( 'payment_direct_order.payment_acquirer_direct_order') tx = transaction_obj.sudo().create({ 'acquirer_id': acquired.id, 'type': 'form', 'amount': order.amount_total, 'currency_id': order.pricelist_id.currency_id.id, 'partner_id': order.partner_id.id, 'partner_country_id': order.partner_id.country_id.id, 'reference': transaction_obj.get_next_reference(order.name), 'sale_order_id': order.id, 'state': 'pending' }) request.session['sale_transaction_id'] = tx request.session['sale_last_order_id'] = order.id order.sudo().write({ 'payment_acquirer_id': acquired.id, 'payment_tx_id': tx.id, 'season_id': season and season.id or None }) order.sudo().force_quotation_send() website.sale_reset() return website.render('website_sale_checkout_agent.agent_confirm', {'order': order})
def cart_add_update(self, **post): try: select = post['selection'] order = request.website.sale_get_order(force_create=1) contract_day = http.request.env['bespoke.contracts'].search([ ('id', '=', select['contract']) ]).days add_qty = select['meals_day'] price_contrato = 0 if contract_day: if 'price_day' in select: order._pay_contract_bespoke( qty=(float(select['price_day']) * int(contract_day))) add_qty *= contract_day automatic_extras = self.automatic_extras( meal_type=select['meal_type'], goal_cal=select['goal_calories']) value = {} if 'contract' in select: order.type_contract(int(select['contract'])) bki_obj = http.request.env['bespoke.kitchen_information'] bki = bki_obj.search([('active', '=', False), ('sale_order_id', '=', order.id)]) set_element_order = set( self.getListidObj(http.request.env['sale.order.line'].search([ ('order_id', '=', order.id), ('is_product_diet', '=', True) ]), is_product=False, change=False)) set_automatic_extras_protein = set([]) set_automatic_extras_fat = set([]) flag_fat = False flag_protein = False if automatic_extras: if 'prod_protein_ext' in automatic_extras: set_automatic_extras_protein = set( self.getListidObj( automatic_extras['prod_protein_ext'])) flag_protein = True if 'prod_fat_ext' in automatic_extras: set_automatic_extras_fat = set( self.getListidObj(automatic_extras['prod_fat_ext'])) flag_fat = True set_extras = set(self.getListidLD(select['extras'])) set_exclusions = set(self.getListidLD(select['exclusions'])) all_prod_selct = set_extras | set_exclusions | set_automatic_extras_protein | set_automatic_extras_fat # Delete act = [] for x in list(set_element_order.difference(all_prod_selct)): obj_line = http.request.env['sale.order.line'].search([ ('order_id', '=', order.id), ('product_id', '=', x), ('is_product_diet', '=', True) ]) if len(obj_line) > 0: act.append((2, obj_line.id, False)) if len(act) > 0: order.write({'order_line': act}) # Extras extras = [] if len(select['extras']) > 0: # Update for x in list(set_element_order.intersection(set_extras)): self.cart(order, product_id=x, set_qty=add_qty) # Add for x in list(set_extras.difference(set_element_order)): linea = self.cart(order, product_id=x, add_qty=add_qty) self.change_msg(linea['line_id'], 'Extra / ' + select['meal_type']) extras.append((0, 0, { 'product_id': x, 'product_uom_qty': add_qty })) # Exclusions exclusions = [] if len(select['exclusions']) > 0: # Update for x in list(set_element_order.intersection(set_exclusions)): linea = self.cart(order, product_id=x, set_qty=add_qty) # self.change_price(linea['line_id'], 0.0) # Add for x in list(set_exclusions.difference(set_element_order)): linea = self.cart(order, product_id=x, add_qty=add_qty) self.change_msg(linea['line_id'], 'Exclusion / ' + select['meal_type']) exclusions.append((0, 0, { 'product_id': x, 'product_uom_qty': add_qty })) # Automatic Protein protein = [] if flag_protein: if len(automatic_extras['prod_protein_ext']) > 0: # Update for x in list( set_element_order.intersection( set_automatic_extras_protein)): self.cart(order, product_id=x, set_qty=add_qty * automatic_extras['protein']) # Add for x in list( set_automatic_extras_protein.difference( set_element_order)): linea = self.cart(order, product_id=x, add_qty=add_qty * automatic_extras['protein']) self.change_msg( linea['line_id'], 'Automatic Extra / ' + select['meal_type']) extras.append((0, 0, { 'product_id': x, 'product_uom_qty': add_qty * automatic_extras['protein'] })) # Automatic FAT fat = [] if flag_fat: if len(automatic_extras['prod_fat_ext']) > 0: # Update for x in list( set_element_order.intersection( set_automatic_extras_fat)): self.cart(order, product_id=x, set_qty=add_qty * automatic_extras['fat']) # Add for x in list( set_automatic_extras_fat.difference( set_element_order)): linea = self.cart(order, product_id=x, add_qty=add_qty * automatic_extras['fat']) self.change_msg( linea['line_id'], 'Automatic Extra / ' + select['meal_type']) extras.append((0, 0, { 'product_id': x, 'product_uom_qty': add_qty * automatic_extras['fat'] })) if select['qty_extra_pay'] != 0: order.pay_exclusion(select['qty_extra_pay']) pos = http.request.env['pos.category'].search([ ('name', '=', select['meal_type']) ]) body_fat_percentage = "" if 'body_fat_percentage' in select: body_fat_percentage = select['body_fat_percentage'] k = { 'type_plan_id': select['goal_plan'], 'protein': select['macros_protein'], 'carb': select['macros_carbs'], # 'tdee': select['tdee'], # 'bmr': select['bmr'], 'fat': select['macros_fat'], 'juice_cleanse': select['juice_cleanse'], 'activity_level': select['activity_level'], 'meal_type_id': pos.id, 'exclusions_ids': exclusions, 'extras_ids': extras + fat + protein, # 'goal_calories': select['goal_calories'], 'meal_number_id': select['feed_day_id'], 'dpw': select['meals_week'], 'body_fat_percentage': body_fat_percentage, 'delivery_day': select['meals_week'], 'age': select['date_birth'], 'gender': select['sex'], 'weight': select['weight'], 'height': select['height'], } if len(bki) == 1: bki.write(k) else: k['sale_order_id'] = order.id bki_obj.create(k) return value except: if request.httprequest.headers and request.httprequest.headers.get( 'Referer'): return request.redirect( str(request.httprequest.headers.get('Referer'))) return request.redirect('/shop')
def payment_validate(self, transaction_id=None, sale_order_id=None, **post): """ Method that should be called by the server when receiving an update for a transaction. State at this point : - UDPATE ME """ cr, uid, context = request.cr, request.uid, request.context email_act = None sale_order_obj = request.registry['sale.order'] if transaction_id is None: tx = request.website.sale_get_transaction() else: tx = request.registry['payment.transaction'].browse( cr, uid, transaction_id, context=context) if sale_order_id is None: order = request.website.sale_get_order(context=context) else: order = request.registry['sale.order'].browse(cr, SUPERUSER_ID, sale_order_id, context=context) assert order.id == request.session.get('sale_last_order_id') if not order or (order.amount_total and not tx): return request.redirect('/shop') if (not order.amount_total and not tx) or tx.state in ['pending', 'done']: if (not order.amount_total and not tx): # Orders are confirmed by payment transactions, but there is none for free orders, # (e.g. free events), so confirm immediately order.action_button_confirm() # send by email email_act = sale_order_obj.action_quotation_send( cr, SUPERUSER_ID, [order.id], context=request.context) elif tx and tx.state == 'cancel': # cancel the quotation sale_order_obj.action_cancel(cr, SUPERUSER_ID, [order.id], context=request.context) # send the email if email_act and email_act.get('context'): composer_values = {} email_ctx = email_act['context'] public_id = request.website.user_id.id if uid == public_id: composer_values[ 'email_from'] = request.website.user_id.company_id.email composer_id = request.registry['mail.compose.message'].create( cr, SUPERUSER_ID, composer_values, context=email_ctx) request.registry['mail.compose.message'].send_mail( cr, SUPERUSER_ID, [composer_id], context=email_ctx) # clean context and session, then redirect to the confirmation page request.website.sale_reset(context=context) return request.redirect('/shop/confirmation')
def cart_update(self, product_id, add_qty=1, set_qty=0, **kw): cr, uid, context = request.cr, request.uid, request.context product = request.registry['product.product'].browse(cr, SUPERUSER_ID, int(product_id), context=context) # Redirect to the calling page (referrer) if the browser has added it # HINT: Not every browser adds the referrer to the header referrer = request.httprequest.referrer if not referrer: if request.session.get('last_page'): referrer = request.session.get('last_page') else: referrer = '/shop/product/%s' % product.product_tmpl_id.id if '?' not in referrer: referrer = referrer + '?' # Validate (donation) Arbitrary Price warnings = None price = kw.get('price_donate') or product.list_price or product.price # HINT: If price_donate is not a valid number it will be empty and so the product.list_price is used! # Therefore the try statement is not really needed (but kept for safety). try: if product.price_donate_min and float( product.price_donate_min) > float(price): warnings = _('Value must be higher or equal to %s.' % float(product.price_donate_min)) except ValueError: warnings = _('Value must be a valid Number.') pass if warnings: referrer = referrer + '&warnings=' + warnings return request.redirect(referrer) # PAYMENT INTERVAL # INFO: This is only needed if products are directly added to cart on shop pages (product listings) if 'payment_interval_id' not in kw: if product.payment_interval_ids: kw['payment_interval_id'] = product.payment_interval_ids[0].id # ARBITRARY PRICE (price_donate) # HINT: price_donate= can already be set! See _cart_update in website_sale_donate.py # Call Super # INFO: Pass kw to _cart_update to transfer all post variables to _cart_update # This is needed to get the Value of the arbitrary price from the input field order_line = request.website.sale_get_order( force_create=1, context=context)._cart_update(product_id=int(product_id), add_qty=float(add_qty), set_qty=float(set_qty), context=context, **kw) order = request.website.sale_get_order(context=context) print "cart_update order name: %s" % order # FS_PTOKEN: set sales order partner by fs_ptoken # If fs_ptoken in kwargs add them to the kw and check if this selects the right user in _cart_update if 'fs_ptoken' in kw and order: # Only change partner if NOT logged in if request.website.user_id.id == uid: # Find related res.partner for the token fstoken_obj = request.registry['res.partner.fstoken'] fstoken_id = fstoken_obj.search( cr, SUPERUSER_ID, [('name', '=', request.httprequest.args['fs_ptoken'])], limit=1) fstoken = fstoken_obj.browse(cr, SUPERUSER_ID, fstoken_id) # Update the sale.order with the res.partner from fs_ptoken # https://www.odoo.com/documentation/8.0/reference/orm.html#fields (openerp.fields.Datetime) if fstoken: # Check if the token is still valid expiration_date = fields.datetime.now() if fstoken.expiration_date: expiration_date = fields.Datetime.from_string( fstoken.expiration_date) else: expiration_date = fields.Datetime.from_string( fstoken.create_date) + timedelta(days=14) if fields.datetime.now() <= expiration_date: values = { 'partner_id': fstoken.partner_id.id, 'partner_invoice_id': fstoken.partner_id.id, 'partner_shipping_id': fstoken.partner_id.id, } order_obj = request.registry['sale.order'] order_obj.write(cr, SUPERUSER_ID, [order.id], values, context=context) # EXIT A) Simple Checkout if product.simple_checkout or kw.get('simple_checkout'): kw.pop('simple_checkout', None) # Redirect to the product page if product-page-layout is one-page-checkout if product.product_page_template == u'website_sale_donate.ppt_opc': request.redirect('/shop/product/' + product.product_tmpl_id.id + '?' + request.httprequest.query_string) # Redirect to the checkout page return request.redirect('/shop/checkout' + '?' + request.httprequest.query_string) # EXIT B) Stay on the current page if "Add to cart and stay on current page" is set if request.website['add_to_cart_stay_on_page']: return request.redirect(referrer) # EXIT C) Redirect to the shopping cart return request.redirect("/shop/cart")
def confirm_order(self, **post): """Overload because no payment should be proposed for group order, invoice should be periodically send to the administrator Rewrite all the function because there is no hookpoint""" cr, uid, context, registry = request.cr, request.uid, request.context, request.registry context.update({'checkout': False}) order = request.website.sale_get_order(context=context) if not order: return request.redirect("/shop") carrier_id = order.carrier_id.id redirection = self.checkout_redirection(order) if redirection: return redirection if order.portal_group_id: values = self.checkout_values(post) values["error"] = self.checkout_form_validate(values["checkout"]) if values["error"]: #need delivery informations sale_order_obj = request.registry.get('sale.order') values.update( sale_order_obj._get_website_data(cr, uid, order, context)) return request.website.render("website_sale.checkout", values) self.checkout_form_save(values["checkout"]) order = request.website.sale_get_order(update_pricelist=True, context=context) sale_order_obj = request.registry.get('sale.order') if not request.registry['sale.order']._check_carrier_quotation( cr, uid, order, force_carrier_id=carrier_id, context=context): _logger.debug( "Delivery carrier has changed, send error to qweb") #need delivery informations context.update({'checkout': True}) values.update( sale_order_obj._get_website_data(cr, uid, order, context)) values.update(self.checkout_values()) #update carrier info values["error"].update({'delivery_zip': 'not_available'}) return request.website.render("website_sale.checkout", values) _logger.debug("Before confirmation") request.session['sale_last_order_id'] = order.id #context=dict(context or {},send_email = True) registry.get('sale.order').action_button_confirm(cr, uid, order.id, context=context) #old odoo version doesn't send mail with action_button_confirm order_id = order.id email_act = sale_order_obj.action_quotation_send(cr, SUPERUSER_ID, [order_id], context=context) if email_act and email_act.get('context'): composer_obj = registry['mail.compose.message'] composer_values = {} email_ctx = email_act['context'] template_values = [ email_ctx.get('default_template_id'), email_ctx.get('default_composition_mode'), email_ctx.get('default_model'), email_ctx.get('default_res_id'), ] composer_values.update( composer_obj.onchange_template_id(cr, SUPERUSER_ID, None, *template_values, context=context).get( 'value', {})) if not composer_values.get('email_from'): composer_values['email_from'] = sale_order_obj.browse( cr, uid, order_id, context=context).company_id.email for key in ['attachment_ids', 'partner_ids']: if composer_values.get(key): _logger.debug("Composer values : %s : %s", key, composer_values[key]) composer_values[key] = [(6, 0, composer_values[key])] composer_id = composer_obj.create(cr, SUPERUSER_ID, composer_values, context=email_ctx) _logger.debug("After create") composer_obj.send_mail(cr, SUPERUSER_ID, [composer_id], context=email_ctx) _logger.debug("After send_mail") #order.with_context(dict(context, send_email=True)).action_button_confirm(cr, uid, order.id) #new api way #uid should be portal user #no need to go further # clean context and session, then redirect to the confirmation page request.website.sale_reset(context=context) return request.redirect('/shop/confirmation') return super(WebsiteSale, self).confirm_order(**post)
def _dispatch(self): first_pass = not hasattr(request, 'website') request.website = None func = None try: func, arguments = self._find_handler() request.website_enabled = func.routing.get('website', False) except werkzeug.exceptions.NotFound: # either we have a language prefixed route, either a real 404 # in all cases, website processes them request.website_enabled = True request.website_multilang = request.website_enabled and func and func.routing.get( 'multilang', True) if 'geoip' not in request.session: record = {} if self.geo_ip_resolver is None: try: import GeoIP # updated database can be downloaded on MaxMind website # http://dev.maxmind.com/geoip/legacy/install/city/ geofile = config.get('geoip_database', '/usr/share/GeoIP/GeoLiteCity.dat') if os.path.exists(geofile): self.geo_ip_resolver = GeoIP.open( geofile, GeoIP.GEOIP_STANDARD) else: self.geo_ip_resolver = False logger.warning( 'GeoIP database file %r does not exists', geofile) except ImportError: self.geo_ip_resolver = False if self.geo_ip_resolver and request.httprequest.remote_addr: record = self.geo_ip_resolver.record_by_addr( request.httprequest.remote_addr) or {} request.session['geoip'] = record if request.website_enabled: if func: self._authenticate(func.routing['auth']) else: self._auth_method_public() request.redirect = lambda url: werkzeug.utils.redirect(url_for(url) ) request.website = request.registry['website'].get_current_website( request.cr, request.uid, context=request.context) if first_pass: request.lang = request.website.default_lang_code request.context['lang'] = request.lang if not func: path = request.httprequest.path.split('/') langs = [lg[0] for lg in request.website.get_languages()] if path[1] in langs: request.lang = request.context['lang'] = path.pop(1) path = '/'.join(path) or '/' if request.lang == request.website.default_lang_code: # If language is in the url and it is the default language, redirect # to url without language so google doesn't see duplicate content return request.redirect( path + '?' + request.httprequest.query_string) return self.reroute(path) return super(ir_http, self)._dispatch()
def paper_submit(self, **post): """ Submitted papers are send to this route. The data is then validated and if valid stored in the model. Afterwards the '/paper_submission/' route is called :param post: submitted request data :return: the '/paper_submission/' route """ cr = request.cr registry = request.registry context = request.context uid = request.uid error = [] for value in self.mandatory_values: if value in post: pass # parse request values and store in variables if "title" in post: title = post["title"] if "abstract" in post: abstract = post["abstract"] submitter_id = uid if "minitrack" in post: minitrack_id = post["minitrack"] if "tag_ids" in post: tag_names = post["tag_ids"] tag_names = tag_names.split(",") orm_tag = registry.get("event.track.tag") # get tags from the system curr_tag_ids = orm_tag.search(cr, SUPERUSER_ID, [], context=context) curr_tag_objects = orm_tag.browse(cr, SUPERUSER_ID, curr_tag_ids, context=context) tag_ids = [] for tag_name in tag_names: tag_id = self.get_tag_id(tag_name, curr_tag_objects) if tag_id == -1: tag_id = orm_tag.create(cr, SUPERUSER_ID, {"name": tag_name}, context=context) tag_ids.append(tag_id) if "document" in post: document = post["document"] else: error.append("document") if "add_files_file" in post: if "add_files_desc" in post: additional_file_desc = post["add_files_desc"] additional_file_file = post["add_files_file"] file_ids = [] if additional_file_desc != "" and additional_file_file: orm_file = registry.get('paper_submission.file') file_info = { "description": additional_file_desc, "binary": additional_file_file } file_id = orm_file.create(cr, SUPERUSER_ID, file_info, context=context) file_ids.append(file_id) else: error.append("add_files_desc") else: file_ids = [] if "author_count": author_count = int(post["author_count"]) else: error.append("author") # if there are no errors append insert paper and other model stuff if len(error) == 0: # document_file_name = "/opt/odoo/my-modules/paper_submission/papers/" + document.filename # destination = open(document_file_name, "wb") # document.save(destination) # add authors author_ids = [] orm_partner = registry.get('res.partner') for x in range(1, author_count): author_data = post["author" + str(x)] author_info = json.loads(author_data) author_info["name"] = author_info[ "first_name"] + " " + author_info["last_name"] curr_author_ids = orm_partner.search(cr, SUPERUSER_ID, [], context=context) curr_author_objects = orm_partner.browse(cr, SUPERUSER_ID, curr_author_ids, context=context) author_id = self.get_author_id(author_info["email"], curr_author_objects) if author_id == -1: author_id = orm_partner.create(cr, SUPERUSER_ID, author_info, context=context) # create user: #orm_user = registry.get('res.users') #user_id = orm_user.create(cr, SUPERUSER_ID, {'partner_id': author_id, 'login': author_info["email"]}, context=context) author_ids.append(author_id) # add paper orm_paper = registry.get('paper_submission.paper') paper_info = { "title": title, "abstract": abstract, "submitter_id": submitter_id, "minitrack_id": minitrack_id, "tag_ids": [(6, 0, tag_ids)], "author_ids": [(6, 0, author_ids)], "file_ids": [(6, 0, file_ids)], "document": document } paper_id = orm_paper.create(cr, SUPERUSER_ID, paper_info, context=context) # add paper link to files if file_ids: file_records = orm_file.browse(cr, SUPERUSER_ID, file_ids, context=context) file_records.write({"paper_id": paper_id}) # add paper link to authors authors = orm_partner.browse(cr, SUPERUSER_ID, author_ids, context=context) for author in authors: author.write({"paper_ids": [(4, paper_id, 0)]}) return request.redirect("/paper_submission/")
def login_subscriber(self, **kwargs): return request.redirect("/page/become_subscriber")
def delete(self, delete_pm_id=None): if delete_pm_id: pay_meth = request.env['payment.method'].browse(int(delete_pm_id)) pay_meth.unlink() return request.redirect('/my/payment_method')
def reseller_register_new(self, issue_id=None, action=None, **post): _logger.warn('\n\naction: %s\n' % action) validation = {} children = {} issue = self.get_issue(issue_id, post.get('token')) if issue_id and not issue: # Token didn't match return request.website.render('website.403', {}) values = { 'help': self.get_help(), } if not issue: partner = request.env['res.partner'].sudo().create({ 'name': _('My Company'), 'is_company': True, 'active': False, 'property_invoice_type': None, 'website_short_description': None, }) issue = request.env['project.issue'].sudo().create({ 'name': 'New Reseller Application', 'partner_id': partner.id, 'project_id': request.env.ref( 'website_reseller_register.project_reseller_register').id }) self.set_issue_id(issue.id) return partner.redirect_token('/reseller_register/%s' % issue.id) elif request.httprequest.method == 'POST': company_registry = issue.partner_id.company_registry vat = issue.partner_id.vat try: self.update_partner_info(issue, post) if action == 'new_contact': return request.redirect( '/reseller_register/%s/contact/new' % issue.id) return request.redirect('/reseller_register/%s/thanks' % issue.id) except ValidationError as e: if 'company registry' in e[1] or '`vat`' in e[1]: validation['company_company_registry'] = 'has-error' values['help']['help_company_company_registry'] = _( 'Check your organization number.') values['company_company_registry'] = post[ 'company_company_registry'] post['company_company_registry'] = company_registry try: self.update_partner_info(issue, post) issue.partner_id.vat = vat except Exception as e: _logger.warn(e) else: children = self.get_children(issue) values.update({ 'issue': issue, 'validation': validation, 'country_selection': [(country['id'], country['name']) for country in request.env['res.country'].search_read([], ['name'])], 'invoice_type_selection': [(invoice_type['id'], invoice_type['name']) for invoice_type in request.env['sale_journal.invoice.type'].sudo( ).search_read([], ['name'])], }) if any(children): for k, v in children.items(): values[k] = v return request.website.render( 'website_reseller_register.register_form', values)
def pricelist(self, promo, **post): cr, uid, context = request.cr, request.uid, request.context request.website.sale_get_order(code=promo, context=context) return request.redirect("/shop/cart")
def reseller_contact_new(self, issue_id=None, contact=0, **post): help_dic = self.get_help() issue = self.get_issue(issue_id, post.get('token')) if issue_id and not issue: # Token didn't match return request.website.render('website.403', {}) if contact: contact = request.env['res.partner'].sudo().browse(contact) if not (contact in issue.partner_id.child_ids): contact = request.env['res.partner'].sudo().browse([]) else: contact = request.env['res.partner'].sudo().browse([]) validation = {} instruction_contact = '' if request.httprequest.method == 'POST': instruction_contact = _( 'Any images or attachments you uploaded have not been saved. Please reupload them.' ) # Values values = { f: post['contact_%s' % f] for f in self.contact_fields() if post.get('contact_%s' % f) and f not in ['attachment', 'image'] } if post.get('image'): image = post['image'].read() values['image'] = base64.encodestring(image) elif post.get('image_b64'): values['image'] = post.get('image_b64') values['parent_id'] = issue.partner_id.id # multi select # ~ category_id = [] # ~ for c in request.httprequest.form.getlist('category_id'): # ~ category_id.append(int(c)) # ~ values['category_id'] = [(6, 0, category_id)] # multi checkbox categ_list = [] for k in post.keys(): if k.split('_')[0] == 'category': categ_list.append(int(post.get(k))) values['category_id'] = [(6, 0, categ_list)] # Validation and store for field in self.contact_fields(): if field not in ['attachment', 'image']: validation['contact_%s' % field] = 'has-success' # Check required fields for field in ['name', 'email']: if not values.get(field): validation['contact_%s' % field] = 'has-error' if not 'has-error' in validation.values(): if contact: contact.sudo().write(values) else: if request.env['res.users'].sudo().with_context( active_test=False).search([('login', '=', values.get('email'))]): validation['contact_email'] = 'has-error' contact = request.env['res.partner'].sudo().browse([]) help_dic['help_contact_email'] = _( 'This email aldready exists. Choose another one!') return request.website.render( 'website_reseller_register.contact_form', { 'issue': issue, 'contact': contact, 'help': help_dic, 'validation': validation, 'instruction_contact': instruction_contact, 'res_partner_category_selection': [(category['id'], category['name']) for category in request.env['res.partner.category'].sudo( ).search_read([( 'id', 'in', [7, 16, 20, 29, 34, 35])], ['name'], order='name')], 'values': post, }) try: template = request.env.ref( 'website_reseller_register.reseller_template' ).sudo() user = template.with_context( no_reset_password=True).copy({ 'name': values.get('name'), 'login': values.get('email'), 'image': values.get('image'), 'active': False, }) contact = user.partner_id.sudo() contact.write(values) except Exception as e: err = sys.exc_info() error = ''.join( traceback.format_exception(err[0], err[1], err[2])) _logger.info('Cannot create user %s: %s' % (values.get('name'), error)) contact = None request.env.cr.rollback() instruction_contact = _( 'Something went wrong when creating the contact. Please try again and contact support of error persists. ' ) + instruction_contact if contact: if post.get('attachment'): attachment = request.env['ir.attachment'].sudo( ).create({ 'name': post['attachment'].filename, 'res_model': 'res.partner', 'res_id': contact.id, 'datas': base64.encodestring(post['attachment'].read()), 'datas_fname': post['attachment'].filename, }) return request.redirect('/reseller_register/%s?token=%s' % (issue.id, post.get('token'))) else: issue = request.env['project.issue'].sudo().browse(int(issue)) return request.website.render( 'website_reseller_register.contact_form', { 'issue': issue, 'contact': contact, 'help': help_dic, 'validation': validation, 'instruction_contact': instruction_contact, 'res_partner_category_selection': [(category['id'], category['name']) for category in request.env['res.partner.category'].sudo(). search_read([('id', 'in', [7, 16, 20, 29, 34, 35])], ['name'], order='name')], 'values': post, })
def jobs_add(self, **kwargs): job = request.env['hr.job'].create({ 'name': _('New Job Offer'), }) return request.redirect("/jobs/detail/%s?enable_editor=1" % slug(job))
def website_lang_redirect(self, **post): return request.redirect('/website/lang/%s' % request.env.user.lang)
def _dispatch(self): first_pass = not hasattr(request, 'website') request.website = None func = None try: func, arguments = self._find_handler() request.website_enabled = func.routing.get('website', False) except werkzeug.exceptions.NotFound: # either we have a language prefixed route, either a real 404 # in all cases, website processes them request.website_enabled = True request.website_multilang = request.website_enabled and func and func.routing.get('multilang', True) if 'geoip' not in request.session: record = {} if self.geo_ip_resolver is None: try: import GeoIP # updated database can be downloaded on MaxMind website # http://dev.maxmind.com/geoip/legacy/install/city/ geofile = config.get('geoip_database') if os.path.exists(geofile): self.geo_ip_resolver = GeoIP.open(geofile, GeoIP.GEOIP_STANDARD) else: self.geo_ip_resolver = False logger.warning('GeoIP database file %r does not exists', geofile) except ImportError: self.geo_ip_resolver = False if self.geo_ip_resolver and request.httprequest.remote_addr: record = self.geo_ip_resolver.record_by_addr(request.httprequest.remote_addr) or {} request.session['geoip'] = record if request.website_enabled: try: if func: self._authenticate(func.routing['auth']) else: self._auth_method_public() except Exception as e: return self._handle_exception(e) request.redirect = lambda url, code=302: werkzeug.utils.redirect(url_for(url), code) request.website = request.registry['website'].get_current_website(request.cr, request.uid, context=request.context) langs = [lg[0] for lg in request.website.get_languages()] path = request.httprequest.path.split('/') if first_pass: if request.website_multilang: # If the url doesn't contains the lang and that it's the first connection, we to retreive the user preference if it exists. if not path[1] in langs and not request.httprequest.cookies.get('session_id'): if request.lang not in langs: # Try to find a similar lang. Eg: fr_BE and fr_FR short = request.lang.split('_')[0] langs_withshort = [lg[0] for lg in request.website.get_languages() if lg[0].startswith(short)] if len(langs_withshort): request.lang = langs_withshort[0] else: request.lang = request.website.default_lang_code # We redirect with the right language in url if request.lang != request.website.default_lang_code: path.insert(1, request.lang) path = '/'.join(path) or '/' return request.redirect(path + '?' + request.httprequest.query_string) else: request.lang = request.website.default_lang_code request.context['lang'] = request.lang if not func: if path[1] in langs: request.lang = request.context['lang'] = path.pop(1) path = '/'.join(path) or '/' if request.lang == request.website.default_lang_code: # If language is in the url and it is the default language, redirect # to url without language so google doesn't see duplicate content return request.redirect(path + '?' + request.httprequest.query_string, code=301) return self.reroute(path) # bind modified context request.website = request.website.with_context(request.context) return super(ir_http, self)._dispatch()
def order(self, **kw): post_email = request.session.get('post_email') if post_email: return request.redirect('/order_tool') else: return http.request.render('bespoke_order.order')
def _dispatch(self): first_pass = not hasattr(request, 'website') request.website = None func = None try: if request.httprequest.method == 'GET' and '//' in request.httprequest.path: new_url = request.httprequest.path.replace( '//', '/') + '?' + request.httprequest.query_string return werkzeug.utils.redirect(new_url, 301) func, arguments = self._find_handler() request.website_enabled = func.routing.get('website', False) except werkzeug.exceptions.NotFound: # either we have a language prefixed route, either a real 404 # in all cases, website processes them request.website_enabled = True request.website_multilang = ( request.website_enabled and func and func.routing.get('multilang', func.routing['type'] == 'http')) self._geoip_setup_resolver() self._geoip_resolve() cook_lang = request.httprequest.cookies.get('website_lang') if request.website_enabled: try: if func: self._authenticate(func.routing['auth']) elif request.uid is None: self._auth_method_public() except Exception as e: return self._handle_exception(e) request.redirect = lambda url, code=302: werkzeug.utils.redirect( url_for(url), code) request.website = request.registry['website'].get_current_website( request.cr, request.uid, context=request.context) request.context['website_id'] = request.website.id langs = [lg[0] for lg in request.website.get_languages()] path = request.httprequest.path.split('/') if first_pass: nearest_lang = not func and self.get_nearest_lang(path[1]) url_lang = nearest_lang and path[1] preferred_lang = ((cook_lang if cook_lang in langs else False) or self.get_nearest_lang(request.lang) or request.website.default_lang_code) is_a_bot = self.is_a_bot() request.lang = request.context[ 'lang'] = nearest_lang or preferred_lang # if lang in url but not the displayed or default language --> change or remove # or no lang in url, and lang to dispay not the default language --> add lang # and not a POST request # and not a bot or bot but default lang in url if ((url_lang and (url_lang != request.lang or url_lang == request.website.default_lang_code)) or (not url_lang and request.website_multilang and request.lang != request.website.default_lang_code) and request.httprequest.method != 'POST') \ and (not is_a_bot or (url_lang and url_lang == request.website.default_lang_code)): if url_lang: path.pop(1) if request.lang != request.website.default_lang_code: path.insert(1, request.lang) path = '/'.join(path) or '/' redirect = request.redirect( path + '?' + request.httprequest.query_string) redirect.set_cookie('website_lang', request.lang) return redirect elif url_lang: path.pop(1) return self.reroute('/'.join(path) or '/') if path[1] == request.website.default_lang_code: request.context['edit_translations'] = False if not request.context.get('tz'): request.context['tz'] = request.session.get( 'geoip', {}).get('time_zone') # bind modified context request.website = request.website.with_context(request.context) # cache for auth public cache_time = getattr(func, 'routing', {}).get('cache') cache_enable = cache_time and request.httprequest.method == "GET" and request.website.user_id.id == request.uid cache_response = None if cache_enable: key = self.get_page_key() try: r = self.pool.cache[key] if r['time'] + cache_time > time.time(): cache_response = openerp.http.Response( r['content'], mimetype=r['mimetype']) else: del self.pool.cache[key] except KeyError: pass if cache_response: request.cache_save = False resp = cache_response else: request.cache_save = key if cache_enable else False resp = super(ir_http, self)._dispatch() if request.website_enabled and cook_lang != request.lang and hasattr( resp, 'set_cookie'): resp.set_cookie('website_lang', request.lang) return resp
def payment_transaction(self, acquirer_id): """ Json method that creates a payment.transaction, used to create a transaction when the user clicks on 'pay now' button. After having created the transaction, the event continues and the user is redirected to the acquirer website. :param int acquirer_id: id of a payment.acquirer record. If not set the user is redirected to the checkout page """ cr, uid, context = request.cr, request.uid, request.context transaction_obj = request.registry.get('payment.transaction') order = request.website.sale_get_order(context=context) if not order or not order.order_line or acquirer_id is None: return request.redirect("/shop/checkout") assert order.partner_id.id != request.website.partner_id.id # find an already existing transaction tx = request.website.sale_get_transaction() if tx: if tx.state == 'draft': # button cliked but no more info -> rewrite on tx or create a new one ? tx.write({ 'acquirer_id': acquirer_id, }) tx_id = tx.id else: tx_id = transaction_obj.create( cr, SUPERUSER_ID, { 'acquirer_id': acquirer_id, 'type': 'form', 'amount': order.amount_total, 'currency_id': order.pricelist_id.currency_id.id, 'partner_id': order.partner_id.id, 'partner_country_id': order.partner_id.country_id.id, 'reference': order.name, 'sale_order_id': order.id, }, context=context) request.session['sale_transaction_id'] = tx_id tx = transaction_obj.browse(cr, SUPERUSER_ID, tx_id, context=context) # update quotation request.registry['sale.order'].write( cr, SUPERUSER_ID, [order.id], { 'payment_acquirer_id': acquirer_id, 'payment_tx_id': request.session['sale_transaction_id'] }, context=context) # confirm the quotation if tx.acquirer_id.auto_confirm == 'at_pay_now': request.registry['sale.order'].action_button_confirm( cr, SUPERUSER_ID, [order.id], context=request.context) return tx_id
def blog_post(self, blog, blog_post, tag_id=None, page=1, enable_editor=None, **post): """ Prepare all values to display the blog. :return dict values: values for the templates, containing - 'blog_post': browse of the current post - 'blog': browse of the current blog - 'blogs': list of browse records of blogs - 'tag': current tag, if tag_id in parameters - 'tags': all tags, for tag-based navigation - 'pager': a pager on the comments - 'nav_list': a dict [year][month] for archives navigation - 'next_post': next blog post, to direct the user towards the next interesting post """ cr, uid, context = request.cr, request.uid, request.context tag_obj = request.registry['blog.tag'] blog_post_obj = request.registry['blog.post'] date_begin, date_end = post.get('date_begin'), post.get('date_end') pager_url = "/blogpost/%s" % blog_post.id pager = request.website.pager(url=pager_url, total=len(blog_post.website_message_ids), page=page, step=self._post_comment_per_page, scope=7) pager_begin = (page - 1) * self._post_comment_per_page pager_end = page * self._post_comment_per_page comments = blog_post.website_message_ids[pager_begin:pager_end] tag = None if tag_id: tag = request.registry['blog.tag'].browse(request.cr, request.uid, int(tag_id), context=request.context) blog_url = QueryURL('', ['blog', 'tag'], blog=blog_post.blog_id, tag=tag, date_begin=date_begin, date_end=date_end) if not blog_post.blog_id.id == blog.id: return request.redirect("/blog/%s/post/%s" % (slug(blog_post.blog_id), slug(blog_post))) tags = tag_obj.browse(cr, uid, tag_obj.search(cr, uid, [], context=context), context=context) # Find next Post all_post_ids = blog_post_obj.search(cr, uid, [('blog_id', '=', blog.id)], context=context) # should always return at least the current post current_blog_post_index = all_post_ids.index(blog_post.id) next_post_id = all_post_ids[0 if current_blog_post_index == len(all_post_ids) - 1 \ else current_blog_post_index + 1] next_post = next_post_id and blog_post_obj.browse( cr, uid, next_post_id, context=context) or False values = { 'tags': tags, 'tag': tag, 'blog': blog, 'blog_post': blog_post, 'blog_post_cover_properties': json.loads(blog_post.cover_properties), 'main_object': blog_post, 'nav_list': self.nav_list(blog), 'enable_editor': enable_editor, 'next_post': next_post, 'next_post_cover_properties': json.loads(next_post.cover_properties) if next_post else {}, 'date': date_begin, 'blog_url': blog_url, 'pager': pager, 'comments': comments, } response = request.website.render("website_blog.blog_post_complete", values) request.session[request.session_id] = request.session.get( request.session_id, []) if not (blog_post.id in request.session[request.session_id]): request.session[request.session_id].append(blog_post.id) # Increase counter blog_post_obj.write(cr, SUPERUSER_ID, [blog_post.id], { 'visits': blog_post.visits + 1, }, context=context) return response
def registration_process(self, **kw): # import pdb;pdb.set_trace() message = kw.get('message', '') member_id = kw.get('member_id', '') member_data = http.request.env['netpro.member'].browse(int(member_id)) policy_id = http.request.env['netpro.policy'].browse( int(member_data.policy_id.id)) member_plan_id = kw.get('member_plan_id', False) MemberPlan = http.request.env['netpro.member_plan'] member_plan = MemberPlan.browse(int(member_plan_id)) email_template_obj = http.request.env['netpro.email_template'] email_template = email_template_obj.search([('name', '=', 'claim_email')]) if not member_plan: message = "Member Plan not found! Please try again." return request.redirect('/claim/registration?message_error=%s' % (message), code=301) Claim = http.request.env['netpro.claim'] claim_data = {} if kw.get('confirm') == '': ############################################################################## # insert into netpro_claim ############################################################################## claim_details = [(0, 0, { 'benefit_id': x.benefit_id.id }) for x in member_plan.member_plan_detail_ids] data = { 'claim_date': time.strftime("%Y-%m-%d"), 'member_id': int(member_id), 'policy_id': int(policy_id.id), 'member_plan_id': member_plan.id, 'claim_detail_ids': claim_details, 'state': "open", } claim_data = Claim.create(data) message = "Claim Registration Success!" if kw.get('email') == '': if member_data.email: claim_data = Claim.browse(int(kw.get('claim_id'))) subject_email = '' body_email = '' if email_template: subject_email = self.replaceString(email_template.subject, claim_data, member_plan) body_email = self.replaceString(email_template.body, claim_data, member_plan) values = { 'subject': subject_email, 'email_to': member_data.email, 'body_html': body_email, 'res_id': False, } mail_mail_obj = http.request.env['mail.mail'] msg_id = mail_mail_obj.create(values) #mail_mail_obj.send(msg_id.id) message = "Message Sent" else: message = "Member's email cannot be found, please filling email on member form to sending email." #return request.redirect('/claim/registration?message_success=%s'% (message), code=301) return http.request.render( 'vit_claim_web.loa', { 'member': member_data, 'member_plan': member_plan, 'claim': claim_data, 'message': message })
def theme_customize_reload(self, href, enable, disable): self.theme_customize(enable and enable.split(",") or [], disable and disable.split(",") or []) return request.redirect( href + ("&theme=true" if "#" in href else "#theme=true"))
def pricelist_change(self, pl_id, **post): if request.website.is_pricelist_available(pl_id.id, context=request.context): request.session['website_sale_current_pl'] = pl_id.id request.website.sale_get_order(force_pricelist=pl_id.id, context=request.context) return request.redirect(request.httprequest.referrer or '/shop')
def page(self, page, **opt): values = { 'path': page, 'deletable': True, # used to add 'delete this page' in content menu } cr, uid, context, pool = request.cr, request.uid, request.context, request.registry if not context.get('pricelist'): pricelist = self.get_pricelist() context['pricelist'] = int(pricelist) else: pricelist = pool.get('product.pricelist').browse( cr, uid, context['pricelist'], context) order = request.website.sale_get_order() if order: from_currency = order.company_id.currency_id to_currency = order.pricelist_id.currency_id compute_currency = lambda price: pool['res.currency']._compute( cr, uid, from_currency, to_currency, price, context=context) else: compute_currency = lambda price: price values.update({ 'website_sale_order': order, 'compute_currency': compute_currency, 'pricelist': pricelist, }) if not hasattr(request.website, 'keep'): keep = QueryURL('/shop', category=0, search='', attrib=[]) values.update({ 'keep': keep, }) if not hasattr(request.website, 'new_products'): domain = [('sale_ok', '=', True)] product_obj = pool.get('product.template') product_ids = product_obj.search( cr, uid, domain, limit=10, offset=None, order='website_published desc, website_sequence desc', context=context) new_products = product_obj.browse(cr, uid, product_ids, context=context) values.update({ 'new_products': new_products, }) #THANH: Categ Laptop if not hasattr(request.website, 'new_categ_laptops'): domain = [('sale_ok', '=', True), ('public_categ_ids.name', '=', 'Laptops')] product_obj = pool.get('product.template') product_ids = product_obj.search( cr, uid, domain, limit=10, offset=None, order='website_published desc, website_sequence desc', context=context) new_categ_laptops = product_obj.browse(cr, uid, product_ids, context=context) values.update({ 'new_categ_laptops': new_categ_laptops, }) #THANH: Categ Network if not hasattr(request.website, 'new_categ_networks'): domain = [('sale_ok', '=', True), ('public_categ_ids.name', '=', 'Network')] product_obj = pool.get('product.template') product_ids = product_obj.search( cr, uid, domain, limit=10, offset=None, order='website_published desc, website_sequence desc', context=context) new_categ_networks = product_obj.browse(cr, uid, product_ids, context=context) values.update({ 'new_categ_networks': new_categ_networks, }) # /page/website.XXX --> /page/XXX if page.startswith('website.'): return request.redirect('/page/' + page[8:], code=301) elif '.' not in page: page = 'website.%s' % page try: request.website.get_template(page) except ValueError, e: # page not found if request.website.is_publisher(): values.pop('deletable') page = 'website.page_404' else: return request.registry['ir.http']._handle_exception(e, 404)
def cart_update(self, product_id, add_qty=1, set_qty=0, **kw): request.website.sale_get_order(force_create=1)._cart_update(product_id=int(product_id), add_qty=float(add_qty), set_qty=float(set_qty)) return request.redirect("/shop/cart")
def add_product_to_wishlist_from_shop(self, product_id=False): cr, uid, context = request.cr, request.uid, request.context cr.execute( 'insert into wishlist_partner_product_rel (product_id,user_id) values (%s,%s)', (product_id, uid)) return request.redirect("#")
def _dispatch(self): first_pass = not hasattr(request, 'website') request.website = None func = None try: func, arguments = self._find_handler() request.website_enabled = func.routing.get('website', False) except werkzeug.exceptions.NotFound: # either we have a language prefixed route, either a real 404 # in all cases, website processes them request.website_enabled = True request.website_multilang = ( request.website_enabled and func and func.routing.get('multilang', func.routing['type'] == 'http') ) if 'geoip' not in request.session: record = {} if self.geo_ip_resolver is None: try: import GeoIP # updated database can be downloaded on MaxMind website # http://dev.maxmind.com/geoip/legacy/install/city/ geofile = config.get('geoip_database') if os.path.exists(geofile): self.geo_ip_resolver = GeoIP.open(geofile, GeoIP.GEOIP_STANDARD) else: self.geo_ip_resolver = False logger.warning('GeoIP database file %r does not exists', geofile) except ImportError: self.geo_ip_resolver = False if self.geo_ip_resolver and request.httprequest.remote_addr: record = self.geo_ip_resolver.record_by_addr(request.httprequest.remote_addr) or {} request.session['geoip'] = record cook_lang = request.httprequest.cookies.get('website_lang') if request.website_enabled: try: if func: self._authenticate(func.routing['auth']) else: self._auth_method_public() except Exception as e: return self._handle_exception(e) request.redirect = lambda url, code=302: werkzeug.utils.redirect(url_for(url), code) request.website = request.registry['website'].get_current_website(request.cr, request.uid, context=request.context) langs = [lg[0] for lg in request.website.get_languages()] path = request.httprequest.path.split('/') if first_pass: nearest_lang = not func and self.get_nearest_lang(path[1]) url_lang = nearest_lang and path[1] preferred_lang = ((cook_lang if cook_lang in langs else False) or self.get_nearest_lang(request.lang) or request.website.default_lang_code) is_a_bot = self.is_a_bot() request.lang = request.context['lang'] = nearest_lang or preferred_lang # if lang in url but not the displayed or default language --> change or remove # or no lang in url, and lang to dispay not the default language --> add lang # and not a POST request # and not a bot or bot but default lang in url if ((url_lang and (url_lang != request.lang or url_lang == request.website.default_lang_code)) or (not url_lang and request.website_multilang and request.lang != request.website.default_lang_code) and request.httprequest.method != 'POST') \ and (not is_a_bot or (url_lang and url_lang == request.website.default_lang_code)): if url_lang: path.pop(1) if request.lang != request.website.default_lang_code: path.insert(1, request.lang) path = '/'.join(path) or '/' redirect = request.redirect(path + '?' + request.httprequest.query_string) redirect.set_cookie('website_lang', request.lang) return redirect elif url_lang: path.pop(1) return self.reroute('/'.join(path) or '/') # bind modified context request.website = request.website.with_context(request.context) resp = super(ir_http, self)._dispatch() if request.website_enabled and cook_lang != request.lang and hasattr(resp, 'set_cookie'): resp.set_cookie('website_lang', request.lang) return resp
def payment_transaction_logic(self, acquirer_id, checkout_page=None, **post): cr, uid, context = request.cr, request.uid, request.context transaction_obj = request.registry.get('payment.transaction') order = request.website.sale_get_order(context=context) if not order or not order.order_line or acquirer_id is None: _logger.error( _('Sale Order is missing or it contains no products!')) if checkout_page: if 'opc_warnings' not in checkout_page.qcontext: checkout_page.qcontext['opc_warnings'] = list() checkout_page.qcontext['opc_warnings'].append( _('Please add products or donations.')) return checkout_page else: return request.redirect("/shop/checkout") assert order.partner_id.id != request.website.partner_id.id # Find an already existing transaction or create a new one # TODO: Transaction is not updated after first creation! We should do a force update here. tx = request.website.sale_get_transaction() if tx: tx_id = tx.id if tx.reference != order.name: tx = False tx_id = False elif tx.state == 'draft': # button clicked but no more info -> rewrite on tx or create a new one ? tx.write({ 'acquirer_id': acquirer_id, 'amount': order.amount_total, }) if not tx: tx_id = transaction_obj.create( cr, SUPERUSER_ID, { 'acquirer_id': acquirer_id, 'type': 'form', 'amount': order.amount_total, 'currency_id': order.pricelist_id.currency_id.id, 'partner_id': order.partner_id.id, 'partner_country_id': order.partner_id.country_id.id, 'reference': order.name, 'sale_order_id': order.id, }, context=context) request.session['sale_transaction_id'] = tx_id # Update sale order so_tx = request.registry['sale.order'].write( cr, SUPERUSER_ID, [order.id], { 'payment_acquirer_id': acquirer_id, 'payment_tx_id': request.session['sale_transaction_id'] }, context=context) if not so_tx: _logger.error( _('Could not update sale order after creation or update of the payment transaction!' )) # Reset sales order of current session for Dadi Payment Providers # HINT: THis is the integration of the former addon website_sale_payment_fix # HINT: Since we have a transaction right now we reset the sale-order of the current session # for our own payment providers. Therefore it does not matter what happens by the PP if tx_id: # get the payment.transaction tx = request.registry['payment.transaction'].browse( cr, SUPERUSER_ID, [tx_id], context=context) # Only reset the current shop session for our own payment providers if tx.acquirer_id.provider in ('ogonedadi', 'frst', 'postfinance'): # Confirm the sales order so no changes are allowed any more in the odoo backend request.registry['sale.order'].action_button_confirm( cr, SUPERUSER_ID, [tx.sale_order_id.id], context=context) # Clear the session to restart SO in case we get no answer from the PP or browser back button is used request.website.sale_reset(context=context) # HINT: Maybe it is also needed to reset the sale_last_order_id? Disabled for now # request.session.update({'sale_last_order_id': False}) return tx_id