Files
odoo_source/addons/website_quote/controllers/main.py
T
Mitali Patel 84f528bcff [IMP] Portal - Share link : Easily share the url of a document
Purpose
=======
- Quickly share the url to someone else (a client, a colleague,...)
- Ensure that the recipient can access at least
  the portal view of the shared record.
- Typically used when a client cannot retrieve the mail to access his order.
  The share link can be used in this case.

Specifications
==============
For any object inheriting form portal.mixin:
    - Add a button SHARE (not visible in edit mode)
    - When clicking on this button, a popup opens with :
        - A warning message for tasks and projects only (see below)
        - the link (like in gmail) that can be copied
        - Recipients
        - mail composer (with preselected template) ==> see below
        - button [Send Link] [Copy Link] Discard
        - After sharing document, put internal note like
          "Document shared to xyz,...." with template message
    - Anyone with the link, even anonymous user (not logged in) can have access
      to the document with the access token provided in the url.

Impacted models:
    - account.invoice (Community)
    - project.project (Community)
    - project.task (Community)
    - purchase.order (Community)
    - sale.order (Community)
    - helpdesk.ticket (Enterprise)

Warning messages and access rules:
    Allowed :
        - SO canceled or draft will be accessible with the link
          with access_token
        - If the customer account is B2B (signup not enabled), the recipient
          will anyway see the document as the user specifically wants the
          recipient to see the document.
    Restrictions :
        - For Project and Task, if the privacy is not public, then, there is a
          contradiction between the access_token mechanism
          and the privacy of the document.
        - A warning message will be displayed in the share wizard to inform the
          user if the document cannot be visible by the recipients and to
          ask him to set the privacy to 'Visible by following customer'.
          The send button will, in that case, be hidden.
        - To avoid to block the share for a new project, default privacy value
          is now set to 'Visible by followong customer'

Technical implementation
========================
- Move the access_token mechanism (field + methods + mail controller)
  to the portal.mixin to be able to use it in a generic way for each object
  inheriting the portal.mixin
- Generalise a part of the _*model*_get_page_view_values method
  into a single one in portal
- Generalize the _*model*_check_access into the portal controller of the
  portal module
- Remove the init_column + default value for the access_token
  > old records have an access_token,
  > new one won't but it will be generated on demand via the get_access_token
  Done for performance reasons
- Add share button into action menu separately. + kanban view context menu
  (except for task and project where button not in action menu but 'simple'
  button for task and project because other modules already provide action
  to send documents by email, which is not the case for project and task.)
- Add a sign_token used to authentify the recipient in the portal view chatter,
  if any. The message will be posted as if the user was logged in.
- Set the _get_share_url as private for security reason
- Add a redirect parameter to _get_share_url to get
    If false : The direct portal view url
    If True : The redirect url (mail/view/?)
- Cleaning up unnecessary code

- Bug fix :
    - Before, if user was not logged and record had partner_id,
      if partner id was null, post message was done as admin.
      Now, the post message is done as public user.
    - If the user had an uid but had no access_token, he could be able
      to gain the access token of the record.
      check_access_rights was missing in the get_access_action.

Task ID : 30985
Closes #25629
2018-08-03 15:20:42 +02:00

226 lines
11 KiB
Python

# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import werkzeug
from odoo import exceptions, fields, http, _
from odoo.http import request
from odoo.addons.portal.controllers.portal import get_records_pager
from odoo.addons.sale.controllers.portal import CustomerPortal
from odoo.addons.portal.controllers.mail import _message_post_helper
from odoo.osv import expression
class CustomerPortal(CustomerPortal):
@http.route()
def portal_order_page(self, order_id=None, access_token=None, **kw):
try:
order_sudo = self._document_check_access('sale.order', order_id, access_token=access_token)
except exceptions.AccessError:
pass
else:
if order_sudo.template_id and order_sudo.template_id.active:
return request.redirect('/quote/%s/%s' % (order_id, access_token or ''))
return super(CustomerPortal, self).portal_order_page(order_id=order_id, access_token=access_token, **kw)
def _portal_quote_user_can_accept(self, order):
result = super(CustomerPortal, self)._portal_quote_user_can_accept(order)
# either use quote template settings or fallback on default behavior
return order.require_signature if order.template_id else result
class sale_quote(http.Controller):
@http.route("/quote/<int:order_id>", type='http', auth="user", website=True)
def view_user(self, *args, **kwargs):
return self.view(*args, **kwargs)
@http.route("/quote/<int:order_id>/<token>", type='http', auth="public", website=True)
def view(self, order_id, pdf=None, token=None, message=False, **post):
# use sudo to allow accessing/viewing orders for public user
# only if he knows the private token
now = fields.Date.today()
if token:
Order = request.env['sale.order'].sudo().search([('id', '=', order_id), ('access_token', '=', token)])
else:
Order = request.env['sale.order'].search([('id', '=', order_id)])
# Log only once a day
if Order and request.session.get('view_quote_%s' % Order.id) != now and request.env.user.share and token:
request.session['view_quote_%s' % Order.id] = now
body = _('Quotation viewed by customer')
_message_post_helper(res_model='sale.order', res_id=Order.id, message=body, token=Order.access_token, message_type='notification', subtype="mail.mt_note", partner_ids=Order.user_id.sudo().partner_id.ids)
if not Order:
return request.render('website.404')
# Token or not, sudo the order, since portal user has not access on
# taxes, required to compute the total_amout of SO.
order_sudo = Order.sudo()
days = 0
if order_sudo.validity_date:
days = (fields.Date.from_string(order_sudo.validity_date) - fields.Date.from_string(fields.Date.today())).days + 1
if pdf:
pdf = request.env.ref('website_quote.report_web_quote').sudo().with_context(set_viewport_size=True).render_qweb_pdf([order_sudo.id])[0]
pdfhttpheaders = [('Content-Type', 'application/pdf'), ('Content-Length', len(pdf))]
return request.make_response(pdf, headers=pdfhttpheaders)
transaction = order_sudo.get_portal_last_transaction()
values = {
'quotation': order_sudo,
'message': message and int(message) or False,
'option': any(not x.line_id for x in order_sudo.options),
'order_valid': (not order_sudo.validity_date) or (now <= order_sudo.validity_date),
'days_valid': days,
'action': request.env.ref('sale.action_quotations').id,
'no_breadcrumbs': request.env.user.partner_id.commercial_partner_id not in order_sudo.message_partner_ids,
'tx_id': transaction.id if transaction else False,
'tx_state': transaction.state if transaction else False,
'payment_tx': transaction,
'tx_post_msg': transaction.acquirer_id.post_msg if transaction else False,
'need_payment': order_sudo.invoice_status == 'to invoice' and transaction.state in ['draft', 'cancel'],
'token': token,
'return_url': '/shop/payment/validate',
'bootstrap_formatting': True,
'partner_id': order_sudo.partner_id.id,
}
if order_sudo.has_to_be_paid() or values['need_payment']:
domain = expression.AND([
['&', ('website_published', '=', True), ('company_id', '=', order_sudo.company_id.id)],
['|', ('specific_countries', '=', False), ('country_ids', 'in', [order_sudo.partner_id.country_id.id])]
])
acquirers = request.env['payment.acquirer'].sudo().search(domain)
values['form_acquirers'] = [acq for acq in acquirers if acq.payment_flow == 'form' and acq.view_template_id]
values['s2s_acquirers'] = [acq for acq in acquirers if acq.payment_flow == 's2s' and acq.registration_view_template_id]
values['pms'] = request.env['payment.token'].search(
[('partner_id', '=', order_sudo.partner_id.id),
('acquirer_id', 'in', [acq.id for acq in values['s2s_acquirers']])])
history = request.session.get('my_quotes_history', [])
values.update(get_records_pager(history, order_sudo))
return request.render('website_quote.so_quotation', values)
@http.route(['/quote/<int:order_id>/<token>/decline'], type='http', auth="public", methods=['POST'], website=True)
def decline(self, order_id, token, **post):
Order = request.env['sale.order'].sudo().browse(order_id)
if token != Order.access_token:
return request.render('website.404')
if Order.state != 'sent':
return werkzeug.utils.redirect("/quote/%s/%s?message=4" % (order_id, token))
Order.action_cancel()
message = post.get('decline_message')
if message:
_message_post_helper(message=message, res_id=order_id, res_model='sale.order', **{'token': token} if token else {})
return werkzeug.utils.redirect("/quote/%s/%s?message=2" % (order_id, token))
@http.route(['/quote/update_line'], type='json', auth="public", website=True)
def update(self, line_id, remove=False, unlink=False, order_id=None, token=None, **post):
Order = request.env['sale.order'].sudo().browse(int(order_id))
if token != Order.access_token:
return request.render('website.404')
if Order.state not in ('draft', 'sent'):
return False
OrderLine = request.env['sale.order.line'].sudo().browse(int(line_id))
if unlink:
OrderLine.unlink()
return False
number = -1 if remove else 1
quantity = OrderLine.product_uom_qty + number
OrderLine.write({'product_uom_qty': quantity})
return [str(quantity), str(Order.amount_total)]
@http.route(["/quote/template/<model('sale.quote.template'):quote>"], type='http', auth="user", website=True)
def template_view(self, quote, **post):
values = {'template': quote}
return request.render('website_quote.so_template', values)
@http.route(["/quote/add_line/<int:option_id>/<int:order_id>/<token>"], type='http', auth="public", website=True)
def add(self, option_id, order_id, token, **post):
Order = request.env['sale.order'].sudo().browse(order_id)
if token != Order.access_token:
return request.render('website.404')
if Order.state not in ['draft', 'sent']:
return request.render('website.http_error', {'status_code': 'Forbidden', 'status_message': _('You cannot add options to a confirmed order.')})
Option = request.env['sale.order.option'].sudo().browse(option_id)
vals = {
'price_unit': Option.price_unit,
'website_description': Option.website_description,
'name': Option.name,
'order_id': Order.id,
'product_id': Option.product_id.id,
'product_uom_qty': Option.quantity,
'product_uom': Option.uom_id.id,
'discount': Option.discount,
}
OrderLine = request.env['sale.order.line'].sudo().create(vals)
OrderLine._compute_tax_id()
Option.write({'line_id': OrderLine.id})
return werkzeug.utils.redirect("/quote/%s/%s#pricing" % (Order.id, token))
# note dbo: website_sale code
@http.route(['/quote/<int:order_id>/transaction/'], type='json', auth="public", website=True)
def payment_transaction_token(self, acquirer_id, order_id, save_token=False,access_token=None, **kwargs):
""" 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
"""
# Ensure a payment acquirer is selected
if not acquirer_id:
return False
try:
acquirer_id = int(acquirer_id)
except:
return False
order = request.env['sale.order'].sudo().browse(order_id)
if not order or not order.order_line:
return False
# Create transaction
vals = {
'acquirer_id': acquirer_id,
'type': order._get_payment_type(),
}
transaction = order._create_payment_transaction(vals)
return transaction.render_sale_button(
order,
'/quote/%s/%s' % (order_id, access_token) if access_token else '/quote/%s' % order_id,
submit_txt=_('Pay & Confirm'),
render_values={
'type': order._get_payment_type(),
'alias_usage': _('If we store your payment information on our server, subscription payments will be made automatically.'),
}
)
@http.route('/quote/<int:order_id>/transaction/token', type='http', auth='public', website=True)
def payment_token(self, order_id, pm_id=None, **kwargs):
order = request.env['sale.order'].sudo().browse(order_id)
if not order or not order.order_line or pm_id is None:
return request.redirect("/quote/%s" % order_id)
# try to convert pm_id into an integer, if it doesn't work redirect the user to the quote
try:
pm_id = int(pm_id)
except ValueError:
return request.redirect('/quote/%s' % order_id)
# Create transaction
vals = {
'payment_token_id': pm_id,
'type': 'server2server',
}
order._create_payment_transaction(vals)
return request.redirect('/quote/%s/%s' % (order_id, order.access_token))