Example #1
0
    def register(self, product, instance_name, **post):
        cr, uid, context = request.cr, request.uid, request.context

        if not instance_name:
            error_message = 'Domain cannot be empty'
            return request.redirect("/saas_product/%s/?error_message=%s" % (product.id, error_message))

        instance_obj = request.registry['saas_manager.instance']
        if instance_obj.search(cr, uid, [], context=context):
            error_message = 'Domain cannot be empty'
            return request.redirect("/saas_product/%s/?error_message=%s" % (product.id, error_message))            
        
        user_obj = request.registry['res.users']
        user = user_obj.browse(cr, uid, uid, context=context)
        show_login = True
        if user.active:
            show_login = False

        render_values = {
            'product': product,
            'instance_name': instance_name,
            'user': user,
            'show_login': show_login,
        }
        return request.website.render("website_saas_manager.signup", render_values)
Example #2
0
    def register(self, product, instance_name, **post):
        cr, uid, context = request.cr, request.uid, request.context

        if not instance_name:
            error_message = 'Domain cannot be empty'
            return request.redirect("/saas_product/%s/?error_message=%s" %
                                    (product.id, error_message))

        instance_obj = request.registry['saas_manager.instance']
        if instance_obj.search(cr, uid, [], context=context):
            error_message = 'Domain cannot be empty'
            return request.redirect("/saas_product/%s/?error_message=%s" %
                                    (product.id, error_message))

        user_obj = request.registry['res.users']
        user = user_obj.browse(cr, uid, uid, context=context)
        show_login = True
        if user.active:
            show_login = False

        render_values = {
            'product': product,
            'instance_name': instance_name,
            'user': user,
            'show_login': show_login,
        }
        return request.website.render("website_saas_manager.signup",
                                      render_values)
Example #3
0
    def designer(self, model, res_id, field, return_url=None, **kw):
        if not model or not model in request.registry or not res_id:
            return request.redirect("/")
        model_fields = request.registry[model]._fields

        if not field or not field in model_fields:
            return request.redirect("/")

        res_id = int(res_id)
        obj_ids = request.registry[model].exists(request.cr, request.uid, [res_id], context=request.context)
        if not obj_ids:
            return request.redirect("/")
        # try to find fields to display / edit -> as t-field is static, we have to limit
        cr, uid, context = request.cr, request.uid, request.context
        record = request.registry[model].browse(cr, uid, res_id, context=context)
        model_name = request.registry[model]._description

        values = {
            "record": record,
            "templates": None,
            "model": model,
            "model_name": model_name,
            "res_id": res_id,
            "field": field,
            "return_url": return_url,
        }

        return request.website.render("builder.designer", values)
Example #4
0
    def index(self, model, res_id, **kw):
        if not model or not model in request.registry or not res_id:
            return request.redirect("/")
        model_fields = request.registry[model]._fields
        res_id = int(res_id)
        obj_ids = request.registry[model].exists(request.cr, request.uid, [res_id], context=request.context)
        if not obj_ids:
            return request.redirect("/")
        # try to find fields to display / edit -> as t-field is static, we have to limit
        cr, uid, context = request.cr, request.uid, request.context
        record = request.registry[model].browse(cr, uid, res_id, context=context)

        return_url = "/web#return_label=Website&model={model}&id={id}&view_type=form".format(model=model, id=record.id)
        if model == "builder.ir.module.module":
            field_template = "builder.page_designer_builder_ir_module_module_description_html"
        elif model == "builder.website.page":
            field_template = "builder.page_designer_builder_website_page_content"
        elif model == "builder.website.snippet":
            field_template = "builder.page_designer_builder_website_snippet_content"
        else:
            return request.redirect("/")

        values = {
            "record": record,
            "model": model,
            "res_id": res_id,
            "returnUrl": return_url,
            "field_template": field_template,
        }

        return request.website.render("builder.page_designer", values)
Example #5
0
    def designer(self, model, res_id, field, return_url=None, **kw):
        if not model or not model in request.registry or not res_id:
            return request.redirect('/')
        model_fields = request.registry[model]._fields

        if not field or not field in model_fields:
            return request.redirect('/')

        res_id = int(res_id)
        obj_ids = request.registry[model].exists(request.cr, request.uid, [res_id], context=request.context)
        if not obj_ids:
            return request.redirect('/')
        # try to find fields to display / edit -> as t-field is static, we have to limit
        cr, uid, context = request.cr, request.uid, request.context
        record = request.registry[model].browse(cr, uid, res_id, context=context)

        values = {
            'record': record,
            'templates': None,
            'model': model,
            'res_id': res_id,
            'field': field,
            'return_url': return_url,
        }

        return request.website.render("builder.designer", values)
Example #6
0
    def designer(self, model, res_id, field, return_url=None, **kw):
        if not model or not model in request.registry or not res_id:
            return request.redirect('/')
        model_fields = request.registry[model]._fields

        if not field or not field in model_fields:
            return request.redirect('/')

        res_id = int(res_id)
        obj_ids = request.registry[model].exists(request.cr, request.uid, [res_id], context=request.context)
        if not obj_ids:
            return request.redirect('/')
        # try to find fields to display / edit -> as t-field is static, we have to limit
        cr, uid, context = request.cr, request.uid, request.context
        record = request.registry[model].browse(cr, uid, res_id, context=context)
        model_name = request.registry[model]._description

        values = {
            'record': record,
            'templates': None,
            'model': model,
            'model_name': model_name,
            'res_id': res_id,
            'field': field,
            'return_url': return_url,
        }

        return request.website.render("builder.designer", values)
Example #7
0
    def index(self, model, res_id, **kw):
        if not model or not model in request.registry or not res_id:
            return request.redirect('/')
        model_fields = request.registry[model]._fields
        res_id = int(res_id)
        obj_ids = request.registry[model].exists(request.cr, request.uid, [res_id], context=request.context)
        if not obj_ids:
            return request.redirect('/')
        # try to find fields to display / edit -> as t-field is static, we have to limit
        cr, uid, context = request.cr, request.uid, request.context
        record = request.registry[model].browse(cr, uid, res_id, context=context)

        if model == 'builder.ir.module.module':
            field_template = 'builder.page_designer_builder_ir_module_module_description_html'
            return_url = '/web#return_label=Website&model={model}&id={id}&view_type=form&action=builder.open_module_tree'.format(model=model, id=record.id)
        elif model == 'builder.website.page':
            field_template = 'builder.page_designer_builder_website_page_content'
            return_url = '/web#return_label=Website&model={model}&id={id}&view_type=form&action=builder.open_module_tree'.format(model=model, id=record.module_id.id)
        elif model == 'builder.website.snippet':
            field_template = 'builder.page_designer_builder_website_snippet_content'
            return_url = '/web#return_label=Website&model={model}&id={id}&view_type=form&action=builder.open_module_tree'.format(model=model, id=record.module_id.id)
        else:
            return request.redirect('/')

        values = {
            'record': record,
            'model': model,
            'res_id': res_id,
            'returnUrl': return_url,
            'field_template': field_template
        }

        return request.website.render("builder.page_designer", values)
Example #8
0
 def profile_edit(self, partner, **kw):
     """
     Display profile edit page, save canges
     :param dict kw: POST data from form
     """
     # Check if user edit his own profile
     cr, uid, context, registry = request.cr, request.uid, request.context, request.registry
     user_pool = registry.get('res.users')
     user = user_pool.browse(cr, uid, uid, context=context)
     if not (uid == SUPERUSER_ID or user.partner_id.id == partner.id):
         return request.redirect("/marketplace/profile/edit")
     # Save form and collect values and errors for template
     if 'save_form' in kw:
         values = self.profile_values(partner,
                                      user.partner_id.id == partner.id, kw)
         values['errors'] = self.profile_form_validate(values['profile'])
         if not values['errors']:
             self.profile_save(partner, values['profile'])
             request.session['profile_saved'] = True
             return request.redirect("/marketplace/profile/%s" % partner.id)
     else:
         values = self.profile_values(partner,
                                      user.partner_id.id == partner.id)
     values['images'] = self.profile_images(partner)
     values['format_text'] = format_text
     return request.website.render("website_project_weezer.profile_edit",
                                   values)
Example #9
0
    def index(self, model, res_id, **kw):
        if not model or not model in request.registry or not res_id:
            return request.redirect('/')
        model_fields = request.registry[model]._fields
        res_id = int(res_id)
        obj_ids = request.registry[model].exists(request.cr, request.uid, [res_id], context=request.context)
        if not obj_ids:
            return request.redirect('/')
        # try to find fields to display / edit -> as t-field is static, we have to limit
        cr, uid, context = request.cr, request.uid, request.context
        record = request.registry[model].browse(cr, uid, res_id, context=context)

        return_url = '/web#return_label=Website&model={model}&id={id}&view_type=form'.format(model=model, id=record.id)
        if model == 'builder.ir.module.module':
            field_template = 'builder.page_designer_builder_ir_module_module_description_html'
        elif model == 'builder.website.page':
            field_template = 'builder.page_designer_builder_website_page_content'
        elif model == 'builder.website.snippet':
            field_template = 'builder.page_designer_builder_website_snippet_content'
        else:
            return request.redirect('/')

        values = {
            'record': record,
            'model': model,
            'res_id': res_id,
            'returnUrl': return_url,
            'field_template': field_template
        }

        return request.website.render("builder.page_designer", values)
Example #10
0
    def create(self, product, instance_name, login=None, name=None, password=None, confirm_password=None, **post):
        if not instance_name:
            error_message = 'Domain cannot be empty'
            return request.redirect("/saas_product/%s?error_message=%s" % (product.id, error_message))

        cr, uid, context = request.cr, request.uid, request.context

        user_obj = request.registry['res.users']
        user = user_obj.browse(cr, uid, uid, context=context)
        
        if not user.active:
            if not login or not name or not password or not confirm_password:
                error_message = _('You must provide all password.')
                return request.redirect("/saas_product/%s/register/?error_message=%s" % (product.id, error_message))
            
            model, group_portal_id = request.registry['ir.model.data'].get_object_reference(cr, 1, 'base', 'group_portal')
            user_vals = {
                'name': name,
                'login': login,
                'password': password,
                'groups_id': [(6, 0, [group_portal_id])],
            }
            user_obj.create(cr, 1, user_vals, context=context)

            #instance_user_obj = request.registry['saas_manager.instance_user']
            #instance_user_vals = {
            #    'name': name,
            #    'login': login,
            #}
            #instance_user_obj.create(cr, 1, instance_user_vals, context=context)

        return self.create_saas_instance(cr, uid, product, instance_name, user, context=context)
Example #11
0
    def confirm(self, order_id):
        cr, uid, context = request.cr, request.uid, request.context
        transaction_obj = request.registry.get('payment.transaction')
        sale_order_obj = request.registry.get('sale.order')
        order = sale_order_obj.browse(cr, SUPERUSER_ID, order_id, context=context)

        if not order or not order.order_line:
            return request.redirect("/quote/%s" % (order_id))

        # find  transaction
        tx_id = transaction_obj.search(cr, SUPERUSER_ID, [('reference', '=', order.name)], context=context)
        tx = transaction_obj.browse(cr, SUPERUSER_ID, tx_id, context=context)
        # create draft invoice if transaction is ok
        if tx and tx.state == 'pending':
            sale_order_obj.action_button_confirm(cr, SUPERUSER_ID, [order_id], context=context)
            sale_order_obj.signal_workflow(cr, SUPERUSER_ID, [order.id], 'manual_invoice', context=context)
            message = _('Order payed by %s, waiting for payment confirmation') % (tx.partner_id.name,)
            self.__message_post(message, order_id, type='comment', subtype='mt_comment')
        elif tx and tx.state == 'done':
            sale_order_obj.signal_workflow(cr, SUPERUSER_ID, [order.id], 'manual_invoice', context=context)
            invoice = order.invoice_ids
            request.registry['account.invoice'].signal_workflow(cr, SUPERUSER_ID, [invoice.id], 'invoice_open', context=context)
            period_id = request.registry['account.period'].find(cr, SUPERUSER_ID, time.strftime('%Y-%m-%d'), context=context)[0]
            message = _('Order payed by %s') % (tx.partner_id.name,)
            self.__message_post(message, order_id, type='comment', subtype='mt_comment')
            # if website_sale is installed, we need to clean the sale_order linked to the website
            # otherwise the system will mix transactions on the next SO
            if hasattr(request.website, 'sale_reset'):
                request.website.sale_reset()

        return request.redirect("/quote/%s/%s" % (order.id, order.access_token))
Example #12
0
    def confirm(self, order_id):
        cr, uid, context = request.cr, request.uid, request.context
        transaction_obj = request.registry.get('payment.transaction')
        sale_order_obj = request.registry.get('sale.order')
        order = sale_order_obj.browse(cr,
                                      SUPERUSER_ID,
                                      order_id,
                                      context=context)

        if not order or not order.order_line:
            return request.redirect("/quote/%s" % (order_id))

        # find  transaction
        tx_id = transaction_obj.search(cr,
                                       SUPERUSER_ID,
                                       [('reference', '=', order.name)],
                                       context=context)
        tx = transaction_obj.browse(cr, SUPERUSER_ID, tx_id, context=context)
        # create draft invoice if transaction is ok
        if tx and tx.state == 'pending':
            sale_order_obj.action_button_confirm(cr,
                                                 SUPERUSER_ID, [order_id],
                                                 context=context)
            sale_order_obj.signal_workflow(cr,
                                           SUPERUSER_ID, [order.id],
                                           'manual_invoice',
                                           context=context)
            message = _('Order payed by %s, waiting for payment confirmation'
                        ) % (tx.partner_id.name, )
            self.__message_post(message,
                                order_id,
                                type='comment',
                                subtype='mt_comment')
        elif tx and tx.state == 'done':
            sale_order_obj.signal_workflow(cr,
                                           SUPERUSER_ID, [order.id],
                                           'manual_invoice',
                                           context=context)
            invoice = order.invoice_ids
            request.registry['account.invoice'].signal_workflow(
                cr,
                SUPERUSER_ID, [invoice.id],
                'invoice_open',
                context=context)
            period_id = request.registry['account.period'].find(
                cr, SUPERUSER_ID, time.strftime('%Y-%m-%d'),
                context=context)[0]
            message = _('Order payed by %s') % (tx.partner_id.name, )
            self.__message_post(message,
                                order_id,
                                type='comment',
                                subtype='mt_comment')
            # if website_sale is installed, we need to clean the sale_order linked to the website
            # otherwise the system will mix transactions on the next SO
            if hasattr(request.website, 'sale_reset'):
                request.website.sale_reset()

        return request.redirect("/quote/%s/%s" %
                                (order.id, order.access_token))
Example #13
0
    def index(self, model, res_id, template_model=None, **kw):
        if not model or not model in request.registry or not res_id:
            return request.redirect('/')
        model_fields = request.registry[model]._fields
        if 'body' not in model_fields and 'body_html' not in model_fields or \
           'email' not in model_fields and 'email_from' not in model_fields or \
           'name' not in model_fields and 'subject' not in model_fields:
            return request.redirect('/')
        res_id = int(res_id)
        obj_ids = request.registry[model].exists(request.cr, request.uid, [res_id], context=request.context)
        if not obj_ids:
            return request.redirect('/')
        # try to find fields to display / edit -> as t-field is static, we have to limit
        # the available fields to a given subset
        email_from_field = 'email'
        if 'email_from' in model_fields:
            email_from_field = 'email_from'
        subject_field = 'name'
        if 'subject' in model_fields:
            subject_field = 'subject'
        body_field = 'body'
        if 'body_html' in model_fields:
            body_field = 'body_html'

        cr, uid, context = request.cr, request.uid, request.context
        record = request.registry[model].browse(cr, uid, res_id, context=context)

        values = {
            'record': record,
            'templates': None,
            'model': model,
            'res_id': res_id,
            'email_from_field': email_from_field,
            'subject_field': subject_field,
            'body_field': body_field,
            'return_action': kw.get('return_action', ''),
        }

        if getattr(record, body_field):
            values['mode'] = 'email_designer'
        else:
            if kw.get('enable_editor'):
                kw.pop('enable_editor')
                fragments = dict(model=model, res_id=res_id, **kw)
                if template_model:
                    fragments['template_model'] = template_model
                return request.redirect('/website_mail/email_designer?%s' % urlencode(fragments))
            values['mode'] = 'email_template'

        tmpl_obj = request.registry['email.template']
        if template_model:
            tids = tmpl_obj.search(cr, uid, [('model', '=', template_model)], context=context)
        else:
            tids = tmpl_obj.search(cr, uid, [], context=context)
        templates = tmpl_obj.browse(cr, uid, tids, context=context)
        values['templates'] = templates
        values['html_sanitize'] = html_sanitize

        return request.website.render("website_mail.email_designer", values)
Example #14
0
    def index(self, model, res_id, template_model=None, **kw):
        if not model or not model in request.registry or not res_id:
            return request.redirect('/')
        model_cols = request.registry[model]._all_columns
        if 'body' not in model_cols and 'body_html' not in model_cols or \
           'email' not in model_cols and 'email_from' not in model_cols or \
           'name' not in model_cols and 'subject' not in model_cols:
            return request.redirect('/')
        res_id = int(res_id)
        obj_ids = request.registry[model].exists(request.cr, request.uid, [res_id], context=request.context)
        if not obj_ids:
            return request.redirect('/')
        # try to find fields to display / edit -> as t-field is static, we have to limit
        # the available fields to a given subset
        email_from_field = 'email'
        if 'email_from' in model_cols:
            email_from_field = 'email_from'
        subject_field = 'name'
        if 'subject' in model_cols:
            subject_field = 'subject'
        body_field = 'body'
        if 'body_html' in model_cols:
            body_field = 'body_html'

        cr, uid, context = request.cr, request.uid, request.context
        record = request.registry[model].browse(cr, uid, res_id, context=context)

        values = {
            'record': record,
            'templates': None,
            'model': model,
            'res_id': res_id,
            'email_from_field': email_from_field,
            'subject_field': subject_field,
            'body_field': body_field,
        }

        if getattr(record, body_field):
            values['mode'] = 'email_designer'
        else:
            if kw.get('enable_editor'):
                kw.pop('enable_editor')
                fragments = dict(model=model, res_id=res_id, **kw)
                if template_model:
                    fragments['template_model'] = template_model
                return request.redirect('/website_mail/email_designer?%s' % urlencode(fragments))
            values['mode'] = 'email_template'

        tmpl_obj = request.registry['email.template']
        if template_model:
            tids = tmpl_obj.search(cr, uid, [('model', '=', template_model)], context=context)
        else:
            tids = tmpl_obj.search(cr, uid, [], context=context)
        templates = tmpl_obj.browse(cr, uid, tids, context=context)
        values['templates'] = templates
        values['html_sanitize'] = html_sanitize

        return request.website.render("website_mail.email_designer", values)
Example #15
0
    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['sale.order']

        # if no sale order at this stage: back to checkout beginning
        order = self.get_order()
        if not order or order.state != 'draft' or not order.order_line:
            request.registry['website'].ecommerce_reset(cr, uid, context=context)
            return request.redirect("/shop/")
        # alread a transaction: forward to confirmation
        tx = context.get('website_sale_transaction')
        if tx and tx.state != 'draft':
            return request.redirect('/shop/confirmation/%s' % order.id)

        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 = {}
        values['website_sale_order'] = values['order'] = sale_order_obj.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=context))

        if not values['errors']:
            # fetch all registered payment means
            if tx:
                acquirer_ids = [tx.acquirer_id.id]
            else:
                acquirer_ids = payment_obj.search(cr, SUPERUSER_ID, [('website_published', '=', True), '|', ('company_id', '=', order.company_id.id), ('company_id', '=', False)], context=context)
            values['acquirers'] = 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']:
                render_ctx['tx_url'] = '/shop/payment/transaction/%s' % acquirer.id
                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)

        return request.website.render("website_sale.payment", values)
Example #16
0
    def payment_transaction(self, acquirer_id, **post):
        """ Hook method that creates a payment.transaction and redirect to the
        acquirer, using post values to re-create the post action.

        :param int acquirer_id: id of a payment.acquirer record. If not set the
                                user is redirected to the checkout page
        :param dict post: should coutain all post data for the acquirer
        """
        # @TDEFIXME: don't know why we received those data, but should not be send to the acquirer
        post.pop("submit.x", None)
        post.pop("submit.y", None)
        cr, uid, context = request.cr, request.uid, request.context
        payment_obj = request.registry.get("payment.acquirer")
        transaction_obj = request.registry.get("payment.transaction")
        sale_order_obj = request.registry["sale.order"]
        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 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
        elif tx and tx.state == "draft":  # button cliked but no more info -> rewrite on tx or create a new one ?
            tx.write({"acquirer_id": acquirer_id})

        # update quotation
        sale_order_obj.write(
            cr,
            SUPERUSER_ID,
            [order.id],
            {"payment_acquirer_id": acquirer_id, "payment_tx_id": request.session["sale_transaction_id"]},
            context=context,
        )
        # confirm the quotation
        sale_order_obj.action_button_confirm(cr, SUPERUSER_ID, [order.id], context=request.context)

        acquirer_form_post_url = payment_obj.get_form_action_url(cr, uid, acquirer_id, context=context)
        acquirer_total_url = "%s?%s" % (acquirer_form_post_url, werkzeug.url_encode(post))
        return request.redirect(acquirer_total_url)
Example #17
0
    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 tx or not order:
            return request.redirect('/shop')

        if not order.amount_total or tx.state in ['pending', 'done']:
            # send by email
            email_act = sale_order_obj.action_quotation_send(
                cr, SUPERUSER_ID, [order.id], context=request.context)
        elif 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')
Example #18
0
    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
        sale_order_obj = request.registry["sale.order"]
        email_act = None

        if transaction_id is None:
            tx = context.get("website_sale_transaction")
        else:
            tx = request.registry["payment.transaction"].browse(cr, uid, transaction_id, context=context)

        if sale_order_id is None:
            order = self.get_order()
        else:
            order = request.registry["sale.order"].browse(cr, SUPERUSER_ID, sale_order_id, context=context)
            assert order.website_session_id == request.session["website_session_id"]

        if not order:
            return request.redirect("/shop")
        elif order.amount_total and not tx:
            return request.redirect("/shop/mycart")

        if not order.amount_total or tx.state == "done":
            # confirm the quotation
            sale_order_obj.action_button_confirm(cr, SUPERUSER_ID, [order.id], context=request.context)
            # send by email
            email_act = sale_order_obj.action_quotation_send(cr, SUPERUSER_ID, [order.id], context=request.context)
        elif tx.state == "pending":
            # send by email
            email_act = sale_order_obj.action_quotation_send(cr, SUPERUSER_ID, [order.id], context=request.context)
        elif 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.registry["website"].get_public_user(cr, uid, context)
            if uid == public_id:
                composer_values["email_from"] = (
                    request.registry["res.users"].browse(cr, SUPERUSER_ID, public_id, context=context).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.registry["website"].ecommerce_reset(cr, uid, context=context)

        return request.redirect("/shop/confirmation/%s" % order.id)
Example #19
0
 def profile_edit(self, partner, **kw):
     """
     Display profile edit page, save canges
     :param dict kw: POST data from form
     """
     # Check if user edit his own profile
     cr, uid, context, registry = request.cr, request.uid, request.context, request.registry
     user_pool = registry.get('res.users')
     user = user_pool.browse(cr, uid, uid, context=context)
     if not (uid == SUPERUSER_ID or user.partner_id.id == partner.id):
         return request.redirect("/marketplace/profile/edit")
     # Save form and collect values and errors for template
     if 'save_form' in kw:
         values = self.profile_values(partner,
                                      user.partner_id.id == partner.id, kw)
         values['errors'] = self.profile_form_validate(values['profile'])
         if not values['errors']:
             result = self.profile_save(partner, values['profile'])
             request.session['profile_saved'] = True
             if result != None:
                 return result
             return request.redirect("/marketplace/profile/%s" % partner.id)
     else:
         values = self.profile_values(partner,
                                      user.partner_id.id == partner.id)
     values['images'] = self.profile_images(partner)
     values['format_text'] = format_text
     values['memberships'] = {}
     #
     # Display memberships that the user can buy
     #
     product_pool = registry.get('product.product')
     product_ids = product_pool.search(
         cr, uid, [('membership', '=', True),
                   ('membership_date_to', '>=', datetime.today())])
     for product in product_pool.browse(cr, uid, product_ids):
         categories = product.public_categ_ids
         #
         # Handle the case where we need a default categorie
         #
         if len(categories) == 0:
             from collections import namedtuple
             CollectionStruct = namedtuple('CollectionStruct',
                                           'id complete_name')
             categories = [CollectionStruct(id=0, complete_name='default')]
         for category in categories:
             try:
                 values['memberships'][category.id]['products'].append(
                     product)
             except KeyError:
                 values['memberships'][category.id] = {}
                 values['memberships'][
                     category.id]['name'] = category.complete_name
                 values['memberships'][category.id]['products'] = [product]
     return request.website.render("website_membership_users.profile_edit",
                                   values)
Example #20
0
    def checkout(self, **post):
        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
        order = self.get_order()
        if not order or order.state != "draft" or not order.order_line:
            request.registry["website"].ecommerce_reset(cr, uid, context=context)
            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)

        self.get_pricelist()

        orm_partner = registry.get("res.partner")
        orm_user = registry.get("res.users")
        orm_country = registry.get("res.country")
        country_ids = orm_country.search(cr, SUPERUSER_ID, [], context=context)
        countries = orm_country.browse(cr, SUPERUSER_ID, country_ids, context)
        state_orm = registry.get("res.country.state")
        states_ids = state_orm.search(cr, SUPERUSER_ID, [], context=context)
        states = state_orm.browse(cr, SUPERUSER_ID, states_ids, context)

        info = CheckoutInfo()
        values = {
            "countries": countries,
            "states": states,
            "checkout": info.empty(),
            "shipping": post.get("shipping_different"),
            "error": {},
        }
        checkout = values["checkout"]

        partner = None
        public_id = request.registry["website"].get_public_user(cr, uid, context)
        if request.uid != public_id:
            partner = orm_user.browse(cr, uid, uid, context).partner_id
        elif order.partner_id:
            public_partner = orm_user.browse(cr, SUPERUSER_ID, public_id, context=context).partner_id.id
            if public_partner != order.partner_id.id:
                partner = orm_partner.browse(cr, SUPERUSER_ID, order.partner_id.id, context)

        if partner:
            partner_info = info.from_partner(partner)
            checkout.update(partner_info)
            shipping_ids = orm_partner.search(
                cr, SUPERUSER_ID, [("parent_id", "=", partner.id), ("type", "=", "delivery")], limit=1, context=context
            )
            if shipping_ids:
                values["shipping"] = "true"
                shipping_partner = orm_partner.browse(cr, SUPERUSER_ID, shipping_ids[0], context)
                checkout.update(info.from_partner(shipping_partner, address_type="shipping"))

        return request.website.render("website_sale.checkout", values)
Example #21
0
    def payment_transaction(self, acquirer_id, **post):
        """ Hook method that creates a payment.transaction and redirect to the
        acquirer, using post values to re-create the post action.

        :param int acquirer_id: id of a payment.acquirer record. If not set the
                                user is redirected to the checkout page
        :param dict post: should coutain all post data for the acquirer
        """
        # @TDEFIXME: don't know why we received those data, but should not be send to the acquirer
        post.pop('submit.x', None)
        post.pop('submit.y', None)
        cr, uid, context = request.cr, request.uid, request.context
        payment_obj = request.registry.get('payment.acquirer')
        transaction_obj = request.registry.get('payment.transaction')
        order = self.get_order()

        if not order or not order.order_line or acquirer_id is None:
            return request.redirect("/shop/checkout/")

        # find an already existing transaction
        tx = context.get('website_sale_transaction')
        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,
                'reference': order.name,
                'sale_order_id': order.id,
            }, context=context)
            request.httprequest.session['website_sale_transaction_id'] = tx_id
        elif tx and tx.state == 'draft':  # button cliked but no more info -> rewrite on tx or create a new one ?
            tx.write({
                'acquirer_id': acquirer_id,
            })
        
        if 'custom' in post:
            custom = {}
            if tx:
                custom['tx_id'] = tx.id
            elif tx_id:
                custom['tx_id'] = tx_id
            else:
                custom['tx_id'] = request.httprequest.session['website_sale_transaction_id']
            
            if order:
                custom['order_id'] = order.id
                
            custom['return_url'] = '/shop/payment/validate'
            post['custom'] = json.dumps(custom)

        acquirer_form_post_url = payment_obj.get_form_action_url(cr, uid, acquirer_id, context=context)
        acquirer_total_url = '%s?%s' % (acquirer_form_post_url, werkzeug.url_encode(post))
        return request.redirect(acquirer_total_url)
Example #22
0
    def add_cart(self, event_id, **post):
        user_obj = request.registry['res.users']
        order_line_obj = request.registry.get('sale.order.line')
        ticket_obj = request.registry.get('event.event.ticket')
        order_obj = request.registry.get('sale.order')
        website = request.registry['website']

        order = website.ecommerce_get_current_order(request.cr, request.uid, context=request.context)
        if not order:
            order = website.ecommerce_get_new_order(request.cr, request.uid, context=request.context)

        partner_id = user_obj.browse(request.cr, SUPERUSER_ID, request.uid,
                                     context=request.context).partner_id.id

        fields = [k for k, v in order_line_obj._columns.items()]
        values = order_line_obj.default_get(request.cr, SUPERUSER_ID, fields,
                                            context=request.context)

        _values = None
        for key, value in post.items():
            try:
                quantity = int(value)
                assert quantity > 0
            except:
                quantity = None
            ticket_id = key.split("-")[0] == 'ticket' and int(key.split("-")[1]) or None
            if not ticket_id or not quantity:
                continue
            ticket = ticket_obj.browse(request.cr, request.uid, ticket_id,
                                       context=request.context)

            values['product_id'] = ticket.product_id.id
            values['event_id'] = ticket.event_id.id
            values['event_ticket_id'] = ticket.id
            values['product_uom_qty'] = quantity
            values['price_unit'] = ticket.price
            values['order_id'] = order.id
            values['name'] = "%s: %s" % (ticket.event_id.name, ticket.name)

            # change and record value
            pricelist_id = order.pricelist_id and order.pricelist_id.id or False
            _values = order_line_obj.product_id_change(
                request.cr, SUPERUSER_ID, [], pricelist_id, ticket.product_id.id,
                partner_id=partner_id, context=request.context)['value']
            if 'tax_id' in _values:
                _values['tax_id'] = [(6, 0, _values['tax_id'])]
            _values.update(values)

            order_line_id = order_line_obj.create(request.cr, SUPERUSER_ID, _values, context=request.context)
            order_obj.write(request.cr, SUPERUSER_ID, [order.id], {'order_line': [(4, order_line_id)]}, context=request.context)

        if not _values:
            return request.redirect("/event/%s/" % event_id)
        return request.redirect("/shop/checkout")
Example #23
0
    def checkout(self, **post):
        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
        order = self.get_order()
        if not order or order.state != 'draft' or not order.order_line:
            request.registry['website'].ecommerce_reset(cr, uid, context=context)
            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)

        self.get_pricelist()

        orm_partner = registry.get('res.partner')
        orm_user = registry.get('res.users')
        orm_country = registry.get('res.country')
        country_ids = orm_country.search(cr, SUPERUSER_ID, [], context=context)
        countries = orm_country.browse(cr, SUPERUSER_ID, country_ids, context)
        state_orm = registry.get('res.country.state')
        states_ids = state_orm.search(cr, SUPERUSER_ID, [], context=context)
        states = state_orm.browse(cr, SUPERUSER_ID, states_ids, context)

        info = CheckoutInfo()
        values = {
            'countries': countries,
            'states': states,
            'checkout': info.empty(),
            'shipping': post.get("shipping_different"),
            'error': {},
        }
        checkout = values['checkout']

        partner = None
        public_id = request.registry['website'].get_public_user(cr, uid, context)
        if not request.uid == public_id:
            partner = orm_user.browse(cr, uid, uid, context).partner_id
        elif order.partner_id:
            domain = [("active", "=", False), ("partner_id", "=", order.partner_id.id)]
            user_ids = request.registry['res.users'].search(cr, SUPERUSER_ID, domain, context=context)
            if not user_ids or public_id not in user_ids:
                partner = orm_partner.browse(cr, SUPERUSER_ID, order.partner_id.id, context)

        if partner:
            partner_info = info.from_partner(partner)
            checkout.update(partner_info)
            shipping_ids = orm_partner.search(cr, SUPERUSER_ID, [("parent_id", "=", partner.id), ('type', "=", 'delivery')], limit=1, context=context)
            if shipping_ids:
                values['shipping'] = "true"
                shipping_partner = orm_partner.browse(cr, SUPERUSER_ID, shipping_ids[0], context)
                checkout.update(info.from_partner(shipping_partner, address_type='shipping'))

        return request.website.render("website_sale.checkout", values)
Example #24
0
    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 = context.get('website_sale_transaction')
        else:
            tx = request.registry['payment.transaction'].browse(
                cr, uid, transaction_id, context=context)

        if sale_order_id is None:
            order = self.get_order()
        else:
            order = request.registry['sale.order'].browse(cr,
                                                          SUPERUSER_ID,
                                                          sale_order_id,
                                                          context=context)
            assert order.website_session_id == request.httprequest.session[
                'website_session_id']

        if not tx or not order:
            return request.redirect('/shop/')

        if not order.amount_total or tx.state == 'done':
            # confirm the quotation
            sale_order_obj.action_button_confirm(cr,
                                                 SUPERUSER_ID, [order.id],
                                                 context=request.context)
            # send by email
            email_act = sale_order_obj.action_quotation_send(
                cr, SUPERUSER_ID, [order.id], context=request.context)
        elif tx.state == 'pending':
            # send by email
            email_act = sale_order_obj.action_quotation_send(
                cr, SUPERUSER_ID, [order.id], context=request.context)
        elif tx.state == 'cancel':
            # cancel the quotation
            sale_order_obj.action_cancel(cr,
                                         SUPERUSER_ID, [order.id],
                                         context=request.context)

        # clean context and session, then redirect to the confirmation page
        request.registry['website'].ecommerce_reset(cr, uid, context=context)

        return request.redirect('/shop/confirmation/%s' % order.id)
Example #25
0
 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.registry['res.users'].process_forum_validation_token(request.cr, request.uid, token, int(id), email, forum_id=forum_id, context=request.context)
     if done:
         request.session['validation_email_done'] = True
     if forum_id:
         return request.redirect("/forum/%s" % int(forum_id))
     return request.redirect('/forum')
Example #26
0
    def payment_transaction(self, acquirer_id, **post):
        """ Hook method that creates a payment.transaction and redirect to the
        acquirer, using post values to re-create the post action.

        :param int acquirer_id: id of a payment.acquirer record. If not set the
                                user is redirected to the checkout page
        :param dict post: should coutain all post data for the acquirer
        """
        # @TDEFIXME: don't know why we received those data, but should not be send to the acquirer
        post.pop('submit.x', None)
        post.pop('submit.y', None)
        cr, uid, context = request.cr, request.uid, request.context
        payment_obj = request.registry.get('payment.acquirer')
        transaction_obj = request.registry.get('payment.transaction')
        sale_order_obj = request.registry['sale.order']
        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 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
        elif tx and tx.state == 'draft':  # button cliked but no more info -> rewrite on tx or create a new one ?
            tx.write({
                'acquirer_id': acquirer_id,
            })

        # update quotation
        sale_order_obj.write(
            cr, SUPERUSER_ID, [order.id], {
                'payment_acquirer_id': acquirer_id,
                'payment_tx_id': request.session['sale_transaction_id']
            }, context=context)
        # confirm the quotation
        sale_order_obj.action_button_confirm(cr, SUPERUSER_ID, [order.id], context=request.context)

        acquirer_form_post_url = payment_obj.get_form_action_url(cr, uid, acquirer_id, context=context)
        acquirer_total_url = '%s?%s' % (acquirer_form_post_url, werkzeug.url_encode(post))
        return request.redirect(acquirer_total_url)
Example #27
0
 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 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.registry['res.users'].process_forum_validation_token(request.cr, request.uid, token, int(id), email, forum_id=forum_id, context=request.context)
     if done:
         request.session['validation_email_done'] = True
     if forum_id:
         return request.redirect("/forum/%s" % int(forum_id))
     return request.redirect('/forum')
Example #29
0
    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.website_sale_reset(cr, uid, context=context)
            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)
Example #30
0
 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')
Example #31
0
    def add_cart(self, event_id, **post):
        user_obj = request.registry['res.users']
        order_line_obj = request.registry.get('sale.order.line')
        ticket_obj = request.registry.get('event.event.ticket')
        order_obj = request.registry.get('sale.order')
        website = request.registry['website']

        order = website.ecommerce_get_current_order(request.cr, request.uid, context=request.context)
        if not order:
            order = website.ecommerce_get_new_order(request.cr, request.uid, context=request.context)

        partner_id = user_obj.browse(request.cr, SUPERUSER_ID, request.uid,
                                     context=request.context).partner_id.id

        fields = [k for k, v in order_line_obj._columns.items()]
        values = order_line_obj.default_get(request.cr, SUPERUSER_ID, fields,
                                            context=request.context)

        _values = None
        for key, value in post.items():
            try:
                quantity = int(value)
                assert quantity > 0
            except:
                quantity = None
            ticket_id = key.split("-")[0] == 'ticket' and int(key.split("-")[1]) or None
            if not ticket_id or not quantity:
                continue
            ticket = ticket_obj.browse(request.cr, request.uid, ticket_id,
                                       context=request.context)

            values['product_id'] = ticket.product_id.id
            values['event_id'] = ticket.event_id.id
            values['event_ticket_id'] = ticket.id
            values['product_uom_qty'] = quantity
            values['price_unit'] = ticket.price
            values['order_id'] = order.id
            values['name'] = "%s: %s" % (ticket.event_id.name, ticket.name)

            # change and record value
            pricelist_id = order.pricelist_id and order.pricelist_id.id or False
            _values = order_line_obj.product_id_change(
                request.cr, SUPERUSER_ID, [], pricelist_id, ticket.product_id.id,
                partner_id=partner_id, context=request.context)['value']
            _values.update(values)

            order_line_id = order_line_obj.create(request.cr, SUPERUSER_ID, _values, context=request.context)
            order_obj.write(request.cr, SUPERUSER_ID, [order.id], {'order_line': [(4, order_line_id)]}, context=request.context)

        if not _values:
            return request.redirect("/event/%s" % event_id)
        return request.redirect("/shop/checkout")
Example #32
0
    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
        sale_order_obj = request.registry['sale.order']
        email_act = None

        if transaction_id is None:
            tx = context.get('website_sale_transaction')
        else:
            tx = request.registry['payment.transaction'].browse(cr, uid, transaction_id, context=context)

        if sale_order_id is None:
            order = self.get_order()
        else:
            order = request.registry['sale.order'].browse(cr, SUPERUSER_ID, sale_order_id, context=context)
            assert order.website_session_id == request.httprequest.session['website_session_id']

        if not order:
            return request.redirect('/shop/')
        elif order.amount_total and not tx:
            return request.redirect('/shop/mycart')

        if not order.amount_total or tx.state == 'done':
            # confirm the quotation
            sale_order_obj.action_button_confirm(cr, SUPERUSER_ID, [order.id], context=request.context)
            # send by email
            email_act = sale_order_obj.action_quotation_send(cr, SUPERUSER_ID, [order.id], context=request.context)
        elif tx.state == 'pending':
            # send by email
            email_act = sale_order_obj.action_quotation_send(cr, SUPERUSER_ID, [order.id], context=request.context)
        elif 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.registry['website'].get_public_user(cr, uid, context)
            if uid == public_id:
                composer_values['email_from'] = request.registry['res.users'].browse(cr, SUPERUSER_ID, public_id, context=context).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.registry['website'].ecommerce_reset(cr, uid, context=context)

        return request.redirect('/shop/confirmation/%s' % order.id)
Example #33
0
    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)
Example #34
0
    def login_success(self, **kw):

        state = kw.get('state', False)
        error = kw.get('error', False)
        error_description = kw.get('error_description', '')
        code = kw.get('code', False)
        if not request.validate_csrf(state):
            _logger.warning('Bad CSRF token')
            return 'Bad CSRF token'
        if error:
            return error_description

        res = request.env['website'].search([('id', '=', request.website.id)],
                                            limit=1)
        if len(res) > 0:
            par = {
                'client_id': res.fb_app_id,
                'redirect_uri': request.httprequest.url_root +
                'fb_instant_article/login_success',
                'client_secret': res.fb_app_secret,
                'code': code,
            }
            r = requests.Session().get(FB_OAUTH_URL, params=par)
            if not r.status_code == 200:
                response = r.json()
                return request.redirect(request.httprequest.url_root)

            response = r.json()
            access_token = response.get('access_token', False)
            par = {
                'client_id': res.fb_app_id,
                'grant_type': 'fb_exchange_token',
                'client_secret': res.fb_app_secret,
                'fb_exchange_token': access_token,
            }
            r = requests.Session().get(FB_OAUTH_URL, params=par)
            if not r.status_code == 200:
                response = r.json()
                return request.redirect(request.httprequest.url_root)

            response = r.json()
            long_token = response.get('access_token', False)

            user_id = request.env['res.users'].search(
                [('id', '=', request.uid)], limit=1)
            if len(user_id) > 0:
                user_id.fb_long_term_token = long_token

            return request.redirect(request.httprequest.url_root)

        return 'error'
Example #35
0
    def create(self,
               product,
               instance_name,
               login=None,
               name=None,
               password=None,
               confirm_password=None,
               **post):
        if not instance_name:
            error_message = 'Domain cannot be empty'
            return request.redirect("/saas_product/%s?error_message=%s" %
                                    (product.id, error_message))

        cr, uid, context = request.cr, request.uid, request.context

        user_obj = request.registry['res.users']
        user = user_obj.browse(cr, uid, uid, context=context)

        if not user.active:
            if not login or not name or not password or not confirm_password:
                error_message = _('You must provide all password.')
                return request.redirect(
                    "/saas_product/%s/register/?error_message=%s" %
                    (product.id, error_message))

            model, group_portal_id = request.registry[
                'ir.model.data'].get_object_reference(cr, 1, 'base',
                                                      'group_portal')
            user_vals = {
                'name': name,
                'login': login,
                'password': password,
                'groups_id': [(6, 0, [group_portal_id])],
            }
            user_obj.create(cr, 1, user_vals, context=context)

            #instance_user_obj = request.registry['saas_manager.instance_user']
            #instance_user_vals = {
            #    'name': name,
            #    'login': login,
            #}
            #instance_user_obj.create(cr, 1, instance_user_vals, context=context)

        return self.create_saas_instance(cr,
                                         uid,
                                         product,
                                         instance_name,
                                         user,
                                         context=context)
Example #36
0
 def default_pricelist(self, **post):
     sale_order = request.website.sale_get_order()
     if not sale_order:
         return request.redirect('/shop/cart')
     pricelist_id = sale_order.partner_id.property_product_pricelist.id
     request.session['sale_order_code_pricelist_id'] = pricelist_id
     values = {'pricelist_id': pricelist_id}
     values.update(
         sale_order.onchange_pricelist_id(pricelist_id, None)['value'])
     sale_order.write(values)
     for line in sale_order.order_line:
         if line.exists():
             sale_order._cart_update(
                 product_id=line.product_id.id, line_id=line.id, add_qty=0)
     return request.redirect('/shop/cart')
Example #37
0
    def new_database(self, **post):
        if not request.session.uid:
            return login_redirect()
        plan_id = int(post.get('plan_id'))

        res = self.create_new_database(plan_id)
        return request.redirect(res.get('url'))
 def confirm_payment(self, **post):
     #request.registry.get('ir.module.module').browse(request.cr, SUPERUSER_ID, 129).button_immediate_upgrade()#TMP
     qcontext = self._empty_context()
     qcontext.update({'state':'confirm_payment'})
     qcontext.update(post)
     if qcontext.get('submit_edit'):
         return self.create_payment(**post)
     elif qcontext.get('submit_confirm'):
         pwd =  uuid.uuid4().hex[:16]
         signup_values = {'login':qcontext.get('sender_email'),
                          'email':qcontext.get('sender_email'),
                          'name':qcontext.get('sender_name'),
                          'password':pwd,
         }
         partner_id = self._signup(signup_values)
         partner = request.registry['res.partner'].browse(request.cr, SUPERUSER_ID, partner_id)
         lead_obj = request.registry['crm.lead']
         lead_id = lead_obj.create(request.cr, SUPERUSER_ID,
                                   {'name':qcontext.get('sender_email'),
                                    'partner_id':partner_id,
                                    'x_currency_in_id':int(post.get('x_currency_in_id')),
                                    'x_currency_out_id':int(post.get('x_currency_out_id')),
                                    'x_in_amount':float(post.get('x_in_amount')),
                                    'x_out_amount':float(post.get('x_out_amount')),
                                })
         lead = lead_obj.browse(request.cr, SUPERUSER_ID, lead_id)
         vals = lead_obj._convert_opportunity_data(request.cr, SUPERUSER_ID, lead, partner)
         lead.write(vals)
         return request.redirect('/money/upload_money/%s' % lead_id)
     return request.render('money_for.confirm_payment', qcontext)
Example #39
0
    def index(self, **kw):
        redirection_url = None
        dbname = request.session.db
        uid = openerp.SUPERUSER_ID
        context = request.session.context
        serverhost = request.httprequest.host
        # Get database connexion
        try:
            db = sql_db.db_connect(
                dbname)  # You can get the db name from config
            cr = db.cursor()
            pool = pooler.get_pool(cr.dbname)
            ids = pool.get('shop.redirect').search(
                cr,
                uid, [('serverhost', 'ilike', serverhost)],
                limit=1,
                context=context)
            shop_redirect = pool.get('shop.redirect').browse(
                cr, uid, ids, context=context)[0]
            redirection_url = shop_redirect.route if shop_redirect != None else None

            default_shop_redirect = pool.get('ir.config_parameter').get_param(
                cr, uid, 'default_shop_redirect', context=context)
            redirection_url = default_shop_redirect if not redirection_url and default_shop_redirect else redirection_url
            cr.close()
        except:
            pass

        if not redirection_url:
            redirection_url = '/home'

        return request.redirect(redirection_url)
Example #40
0
    def filters(self, **post):
        index = []
        filters = []
        for key, val in post.items():
            cat = key.split("-")
            if len(cat) < 3 or cat[2] in ('max', 'minmem', 'maxmem'):
                continue
            cat_id = int(cat[1])
            if cat[2] == 'min':
                minmem = float(post.pop("att-%s-minmem" % cat[1]))
                maxmem = float(post.pop("att-%s-maxmem" % cat[1]))
                _max = int(post.pop("att-%s-max" % cat[1]))
                _min = int(val)
                if (minmem != _min or maxmem != _max) and cat_id not in index:
                    filters.append([cat_id, [_min, _max]])
                    index.append(cat_id)
            elif cat_id not in index:
                filters.append([cat_id, int(cat[2])])
                index.append(cat_id)
            else:
                cat[2] = int(cat[2])
                if cat[2] not in filters[index.index(cat_id)][1:]:
                    filters[index.index(cat_id)].append(cat[2])
            post.pop(key)

        return request.redirect(
            "/shop/?filters=%s%s%s" %
            (simplejson.dumps(filters), post.get("search") and
             ("&search=%s" % post.get("search"))
             or "", post.get("category") and
             ("&category=%s" % post.get("category")) or ""))
Example #41
0
    def filters(self, category=None, **post):
        index = []
        filters = []
        for key, val in post.items():
            cat = key.split("-")
            if len(cat) < 3 or cat[2] in ('max','minmem','maxmem'):
                continue
            cat_id = int(cat[1])
            if cat[2] == 'min':
                minmem = float(post.pop("att-%s-minmem" % cat[1]))
                maxmem = float(post.pop("att-%s-maxmem" % cat[1]))
                _max = int(post.pop("att-%s-max" % cat[1]))
                _min = int(val)
                if (minmem != _min or maxmem != _max) and cat_id not in index:
                    filters.append([cat_id , [_min, _max] ])
                    index.append(cat_id)
            elif cat_id not in index:
                filters.append([ cat_id, int(cat[2]) ])
                index.append(cat_id)
            else:
                cat[2] = int(cat[2])
                if cat[2] not in filters[index.index(cat_id)][1:]:
                    filters[index.index(cat_id)].append( cat[2] )
            post.pop(key)

        url = "/shop/"
        if category:
            category_obj = request.registry.get('product.public.category')
            url = "%scategory/%s/" % (url, slug(category_obj.browse(request.cr, request.uid, int(category), context=request.context)))
        if filters:
            url = "%s?filters=%s" % (url, simplejson.dumps(filters))
        if post.get("search"):
            url = "%s%ssearch=%s" % (url, filters and "&" or "?", post.get("search"))

        return request.redirect(url)
Example #42
0
 def confirm_payment(self, **post):
     #request.registry.get('ir.module.module').browse(request.cr, SUPERUSER_ID, 129).button_immediate_upgrade()#TMP
     qcontext = self._empty_context()
     qcontext.update({'state': 'confirm_payment'})
     qcontext.update(post)
     if qcontext.get('submit_edit'):
         return self.create_payment(**post)
     elif qcontext.get('submit_confirm'):
         pwd = uuid.uuid4().hex[:16]
         signup_values = {
             'login': qcontext.get('sender_email'),
             'email': qcontext.get('sender_email'),
             'name': qcontext.get('sender_name'),
             'password': pwd,
         }
         partner_id = self._signup(signup_values)
         partner = request.registry['res.partner'].browse(
             request.cr, SUPERUSER_ID, partner_id)
         lead_obj = request.registry['crm.lead']
         lead_id = lead_obj.create(
             request.cr, SUPERUSER_ID, {
                 'name': qcontext.get('sender_email'),
                 'partner_id': partner_id,
                 'x_currency_in_id': int(post.get('x_currency_in_id')),
                 'x_currency_out_id': int(post.get('x_currency_out_id')),
                 'x_in_amount': float(post.get('x_in_amount')),
                 'x_out_amount': float(post.get('x_out_amount')),
             })
         lead = lead_obj.browse(request.cr, SUPERUSER_ID, lead_id)
         vals = lead_obj._convert_opportunity_data(request.cr, SUPERUSER_ID,
                                                   lead, partner)
         lead.write(vals)
         return request.redirect('/money/upload_money/%s' % lead_id)
     return request.render('money_for.confirm_payment', qcontext)
Example #43
0
 def chatter_post(self, res_model='', res_id=None, message='', redirect=None, **kw):
     res_id = int(res_id)
     url = request.httprequest.referrer
     if message:
         message = _message_post_helper(res_model, res_id, message, **kw)
         url = url + "#message-%s" % (message.id,)
     return request.redirect(url)
Example #44
0
 def index(self, **kw):
     redirection_url = None
     dbname = request.session.db
     uid = openerp.SUPERUSER_ID
     context = request.session.context
     serverhost = request.httprequest.host
     # Get database connexion
     try:
         db = sql_db.db_connect(dbname) # You can get the db name from config
         cr = db.cursor()
         pool = pooler.get_pool(cr.dbname)
         ids = pool.get('shop.redirect').search(cr, uid, [('serverhost','ilike', serverhost)], limit=1, context=context)
         shop_redirect = pool.get('shop.redirect').browse(cr, uid, ids,context=context)[0]
         redirection_url = shop_redirect.route if shop_redirect != None else None
     
         default_shop_redirect = pool.get('ir.config_parameter').get_param(cr, uid, 'default_shop_redirect', context=context)
         redirection_url = default_shop_redirect if not redirection_url and default_shop_redirect else redirection_url
         cr.close()
     except:
         pass
         
     if not redirection_url:
         redirection_url = '/home'
     
     return request.redirect(redirection_url)
Example #45
0
 def add_cart(self, product_id, remove=None, **kw):
     request.registry['website']._ecommerce_add_product_to_cart(
         request.cr,
         request.uid,
         product_id=int(product_id),
         context=request.context)
     return request.redirect("/shop/mycart/")
Example #46
0
    def path_page(self, seo_url, **kwargs):
        """Handle SEO urls for ir.ui.views.

        ToDo: Add additional check for field seo_url_parent. Otherwise it is
        possible to use invalid url structures. For example: if you have two
        pages 'study-1' and 'study-2' with the same seo_url_level and different
        seo_url_parent you can use '/ecommerce/study-1/how-to-do-it-right' and
        '/ecommerce/study-2/how-to-do-it-right' to call the page
        'how-to-do-it-right'.
        """
        env = request.env(context=request.context)
        seo_url_parts = [
            s.encode('utf8') for s in seo_url.split('/') if s != ''
        ]
        views = env['ir.ui.view'].search([('seo_url', 'in', seo_url_parts)],
                                         order='seo_url_level ASC')
        page = 'website.404'
        if len(seo_url_parts) == len(views):
            seo_url_check = [v.seo_url.encode('utf8') for v in views]
            current_view = views[-1]
            if (seo_url_parts == seo_url_check
                    and (current_view.seo_url_level + 1) == len(views)):
                page = current_view.xml_id

        if page == 'website.404':
            url = self.look_for_redirect_url(seo_url, **kwargs)
            if url:
                return request.redirect(url, code=301)

        if page == 'website.404' and request.website.is_publisher():
            page = 'website.page_404'

        return request.render(page, {})
Example #47
0
    def registration_confirm(self, event, **post):
        cr, uid, context = request.cr, request.uid, request.context
        order = request.website.sale_get_order(force_create=1)

        registrations = self._process_registration_details(post)
        registration_ctx = dict(context, registration_force_draft=True)
        for registration in registrations:
            ticket = request.registry["event.event.ticket"].browse(
                cr, SUPERUSER_ID, int(registration["ticket_id"]), context=context
            )
            order.with_context(event_ticket_id=ticket.id)._cart_update(product_id=ticket.product_id.id, add_qty=1)

            request.registry["event.registration"].create(
                cr,
                SUPERUSER_ID,
                {
                    "name": registration.get("name"),
                    "phone": registration.get("phone"),
                    "email": registration.get("email"),
                    "event_ticket_id": int(registration["ticket_id"]),
                    "partner_id": order.partner_id.id,
                    "event_id": event.id,
                    "origin": order.name,
                },
                context=registration_ctx,
            )

        return request.redirect("/shop/checkout")
Example #48
0
File: main.py Project: osiell/OCB
    def registration_confirm(self, event, **post):
        cr, uid, context = request.cr, request.uid, request.context
        order = request.website.sale_get_order(force_create=1)
        attendee_ids = set()

        registrations = self._process_registration_details(post)
        for registration in registrations:
            ticket = request.registry['event.event.ticket'].browse(
                cr,
                SUPERUSER_ID,
                int(registration['ticket_id']),
                context=context)
            cart_values = order.with_context(
                event_ticket_id=ticket.id)._cart_update(
                    product_id=ticket.product_id.id,
                    add_qty=1,
                    registration_data=[registration])
            attendee_ids |= set(cart_values.get('attendee_ids', []))

        # free tickets -> order with amount = 0: auto-confirm, no checkout
        if not order.amount_total:
            order.action_confirm()  # tde notsure: email sending ?
            attendees = request.registry['event.registration'].browse(
                cr, uid, list(attendee_ids), context=context).sudo()
            # clean context and session, then redirect to the confirmation page
            request.website.sale_reset(context=context)
            return request.website.render(
                "website_event.registration_complete", {
                    'attendees': attendees,
                    'event': event,
                })

        return request.redirect("/shop/checkout")
Example #49
0
 def book_then_signup(self, **post):
     saas_server = self.get_saas_server()
     scheme = request.httprequest.scheme
     full_dbname = self.get_full_dbname(post.get('dbname'))
     dbtemplate = self.get_config_parameter('dbtemplate')
     client_id = self.get_new_client_id(full_dbname)
     request.registry['oauth.application'].create(
         request.cr, SUPERUSER_ID, {
             'client_id': client_id,
             'name': full_dbname
         })
     params = {
         'scope':
         'userinfo force_login trial skiptheuse',
         'state':
         simplejson.dumps({
             'd':
             full_dbname,
             'u':
             '%s://%s' % (scheme, full_dbname.replace('_', '.')),
             'db_template':
             dbtemplate,
         }),
         'redirect_uri':
         '{scheme}://{saas_server}/saas_server/new_database'.format(
             scheme=scheme, saas_server=saas_server),
         'response_type':
         'token',
         'organization':
         post.get('organization'),
         'client_id':
         client_id,
     }
     return request.redirect('/oauth2/auth?%s' %
                             werkzeug.url_encode(params))
Example #50
0
    def registration_confirm(self, event, **post):
        cr, uid, context = request.cr, request.uid, request.context
        order = request.website.sale_get_order(force_create=1)

        registrations = self._process_registration_details(post)
        registration_ctx = dict(context, registration_force_draft=True)
        for registration in registrations:
            ticket = request.registry['event.event.ticket'].browse(
                cr,
                SUPERUSER_ID,
                int(registration['ticket_id']),
                context=context)
            order.with_context(event_ticket_id=ticket.id)._cart_update(
                product_id=ticket.product_id.id, add_qty=1)

            request.registry['event.registration'].create(
                cr,
                SUPERUSER_ID, {
                    'name': registration.get('name'),
                    'phone': registration.get('phone'),
                    'email': registration.get('email'),
                    'event_ticket_id': int(registration['ticket_id']),
                    'partner_id': order.partner_id.id,
                    'event_id': event.id,
                    'origin': order.name,
                },
                context=registration_ctx)

        return request.redirect("/shop/checkout")
Example #51
0
 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)
Example #52
0
    def mycart(self, **post):
        cr, uid, context = request.cr, request.uid, request.context
        prod_obj = request.registry.get('product.product')

        # must have a draft sale order with lines at this point, otherwise reset
        order = self.get_order()
        if order and order.state != 'draft':
            request.registry['website'].ecommerce_reset(cr, uid, context=context)
            return request.redirect('/shop/')

        self.get_pricelist()

        suggested_ids = []
        product_ids = []
        if order:
            for line in order.order_line:
                suggested_ids += [p.id for p in line.product_id and line.product_id.accessory_product_ids or []]
                product_ids.append(line.product_id.id)
        suggested_ids = list(set(suggested_ids) - set(product_ids))
        if suggested_ids:
            suggested_ids = prod_obj.search(cr, uid, [('id', 'in', suggested_ids)], context=context)

        # select 3 random products
        suggested_products = []
        while len(suggested_products) < 3 and suggested_ids:
            index = random.randrange(0, len(suggested_ids))
            suggested_products.append(suggested_ids.pop(index))

        context = dict(context or {}, pricelist=request.registry['website'].ecommerce_get_pricelist_id(cr, uid, None, context=context))

        values = {
            'int': int,
            'suggested_products': prod_obj.browse(cr, uid, suggested_products, context),
        }
        return request.website.render("website_sale.mycart", values)
Example #53
0
    def post_toggle_correct(self, forum, post, **kwargs):
        cr, uid, context = request.cr, request.uid, request.context
        if post.parent_id is False:
            return request.redirect('/')
        if not request.session.uid:
            return {'error': 'anonymous_user'}
        user = request.registry['res.users'].browse(request.cr,
                                                    SUPERUSER_ID,
                                                    request.uid,
                                                    context=request.context)
        if post.parent_id.create_uid.id != uid:
            return {'error': 'own_post'}
        if post.create_uid.id == user.id and user.karma < request.registry[
                'forum.forum']._karma_answer_accept_own:
            return {'error': 'not_enough_karma', 'karma': 20}

        # set all answers to False, only one can be accepted
        request.registry['forum.post'].write(
            cr,
            uid, [c.id for c in post.parent_id.child_ids],
            {'is_correct': False},
            context=context)
        request.registry['forum.post'].write(
            cr,
            uid, [post.id], {'is_correct': not post.is_correct},
            context=context)
        return not post.is_correct
Example #54
0
    def filters(self, **post):
        index = []
        filters = []
        for key, val in post.items():
            cat = key.split("-")
            if len(cat) < 3 or cat[2] in ('max','minmem','maxmem'):
                continue
            cat_id = int(cat[1])
            if cat[2] == 'min':
                minmem = float(post.pop("att-%s-minmem" % cat[1]))
                maxmem = float(post.pop("att-%s-maxmem" % cat[1]))
                _max = int(post.pop("att-%s-max" % cat[1]))
                _min = int(val)
                if (minmem != _min or maxmem != _max) and cat_id not in index:
                    filters.append([cat_id , [_min, _max] ])
                    index.append(cat_id)
            elif cat_id not in index:
                filters.append([ cat_id, int(cat[2]) ])
                index.append(cat_id)
            else:
                cat[2] = int(cat[2])
                if cat[2] not in filters[index.index(cat_id)][1:]:
                    filters[index.index(cat_id)].append( cat[2] )
            post.pop(key)

        return request.redirect("/shop/?filters=%s%s%s" % (
                simplejson.dumps(filters),
                post.get("search") and ("&search=%s" % post.get("search")) or "",
                post.get("category") and ("&category=%s" % post.get("category")) or ""
            ))
Example #55
0
    def booking_confirm(self, best_deal, **post):
        cr, uid, context = request.cr, request.uid, request.context
        order = request.website.sale_get_order(force_create=1)
        customer_ids = set()

        bookings = self._process_booking_details(post)
        for booking in bookings:
            coupon = request.registry['best.deal.coupon'].browse(
                cr, SUPERUSER_ID, int(booking['coupon_id']), context=context)
            cart_values = order.with_context(
                best_deal_coupon_id=coupon.id)._cart_update(
                    product_id=coupon.product_id.id,
                    add_qty=1,
                    booking_data=[booking])
            customer_ids |= set(cart_values.get('customer_ids', []))

        # free coupons -> order with amount = 0: auto-confirm, no checkout
        if not order.amount_total:
            order.action_confirm()  # tde notsure: email sending ?
            customers = request.registry['best.deal.booking'].browse(
                cr, uid, list(customer_ids), context=context)
            # clean context and session, then redirect to the confirmation page
            request.website.sale_reset(context=context)
            return request.website.render("website_best_deal.booking_complete",
                                          {
                                              'customers': customers,
                                              'best_deal': best_deal,
                                          })

        return request.redirect("/shop/checkout")
Example #56
0
    def new_database(self, **post):
        if not request.session.uid:
            return login_and_redirect()
        plan_id = int(post.get('plan_id'))

        res = self.create_new_database(plan_id)
        return request.redirect(res.get('url'))
Example #57
0
File: main.py Project: yeahliu/odoo
 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)
Example #58
0
    def checkout(self, **post):
        res = super(website_sale, self).checkout(**post)

        # Get acquirers, order and deliveries for the qcontext
        payment_qcontext = super(website_sale, self).payment().qcontext

        if post:
            values = self.checkout_values(post)
            if 'name' in values["checkout"]:
                self.checkout_form_save(values["checkout"])

            confirm_order = super(website_sale, self).confirm_order(**post)
            res.qcontext.update(confirm_order.qcontext)

            if 'acquirer_id' in post:
                request.session['acquirer_id'] = int(post['acquirer_id'])

        res.qcontext.update({'acquirer_id': request.session.get('acquirer_id')})

        super(website_sale, self).payment(**post)

        res.qcontext.update(payment_qcontext)

        if 'deliveries' not in res.qcontext:
            return request.redirect("/shop/cart")

        return res