Exemplo n.º 1
0
    def remove_tag(cls, task_id, tag_id):
        """
        Assigns the provided to this task

        :param task_id: ID of task
        :param tag_id: ID of tag
        """
        Activity = Pool().get('nereid.activity')
        task = cls.get_task(task_id)

        cls.write([task], {'tags': [('remove', [tag_id])]})
        Activity.create([{
            'actor': request.nereid_user.id,
            'object_': 'project.work, %d' % task.id,
            'verb': 'removed_tag_from_task',
            'target': 'project.work, %d' % task.parent.id,
            'project': task.parent.id,
        }])

        if request.method == 'POST':
            flash('Tag removed from task %s' % task.rec_name)
            return redirect(request.referrer)

        flash("Tag cannot be removed")
        return redirect(request.referrer)
Exemplo n.º 2
0
    def github_authorized_login(cls):
        """
        Authorized handler to which github will redirect the user to
        after the login attempt is made.
        """
        github = request.nereid_website.get_github_oauth_client()
        if github is None:
            return redirect(request.referrer
                            or url_for('nereid.website.login'))

        try:
            # The response is an oauth2 response with code. But Github API
            # requires the
            if 'oauth_verifier' in request.args:
                data = github.handle_oauth1_response()
            elif 'code' in request.args:
                data = github.handle_oauth2_response()
            else:
                data = github.handle_unknown_response()
            github.free_request_token()
        except Exception, exc:
            current_app.logger.error("Github login failed %s" % exc)
            flash(_("We cannot talk to github at this time. Please try again"))
            return redirect(request.referrer
                            or url_for('nereid.website.login'))
Exemplo n.º 3
0
    def delete_task(cls, task_id):
        """
        Delete the task from project

        Tasks can be deleted only if
            1. The user is project admin
            2. The user is an admin member in the project

        :param task_id: Id of the task to be deleted
        """
        task = cls.get_task(task_id)

        # Check if user is among the project admins
        if not request.nereid_user.is_admin_of_project(task.parent):
            flash("Sorry! You are not allowed to delete tasks. \
                Contact your project admin for the same.")
            return redirect(request.referrer)

        cls.write([task], {'active': False})

        if request.is_xhr:
            return jsonify({
                'success': True,
            })

        flash("The task has been deleted")
        return redirect(
            url_for('project.work.render_project', project_id=task.parent.id))
Exemplo n.º 4
0
    def checkout(self):
        '''Submit of default checkout

        A GET to the method will result in passing of control to begin as
        that is basically the entry point to the checkout

        A POST to the method will result in the confirmation of the order and
        subsequent handling of data.
        '''
        cart_obj = Pool().get('nereid.cart')
        sale_obj = Pool().get('sale.sale')

        cart = cart_obj.open_cart()
        if not cart.sale:
            # This case is possible if the user changes his currency at
            # the point of checkout and the cart gets cleared.
            return redirect(url_for('nereid.cart.view_cart'))

        sale = cart.sale
        if not sale.lines:
            flash(_("Add some items to your cart before you checkout!"))
            return redirect(url_for('nereid.website.home'))
        if request.method == 'GET':
            return (self._begin_guest() if request.is_guest_user \
                else self._begin_registered())

        elif request.method == 'POST':
            form, do_process = self._submit_guest() if request.is_guest_user \
                else self._submit_registered()
            if do_process:
                # Process Shipping
                self._process_shipment(sale, form)

                # Process Payment, if the returned value from the payment
                # is a response object (isinstance) then return that instead
                # of the success page. This will allow reidrects to a third 
                # party gateway or service to collect payment.
                response = self._process_payment(sale, form)
                if isinstance(response, BaseResponse):
                    return response

                if sale.state == 'draft':
                    # Ensure that the order date is that of today
                    cart_obj.check_update_date(cart)
                    # Confirm the order
                    sale_obj.quote([sale.id])
                    sale_obj.confirm([sale.id])

                flash(_("Your order #%(sale)s has been processed", sale=sale.reference))
                if request.is_guest_user:
                    return redirect(url_for('nereid.website.home'))
                else:
                    return redirect(
                        url_for(
                            'sale.sale.render', sale=sale.id, 
                            confirmation=True
                        )
                    )

            return render_template('checkout.jinja', form=form, cart=cart)
Exemplo n.º 5
0
    def assign_task(self, task_id):
        """Assign task to a user

        :param task_id: Id of Task
        """
        nereid_user_obj = Pool().get('nereid.user')

        task = self.get_task(task_id)

        new_assignee = nereid_user_obj.browse(int(request.form['user']))

        if self.can_write(task.parent, new_assignee):
            self.write(task.id, {
                'assigned_to': new_assignee.id
            })

            if request.is_xhr:
                return jsonify({
                    'success': True,
                })

            flash("Task assigned to %s" % new_assignee.name)
            return redirect(request.referrer)

        flash("Only employees can be assigned to tasks.")
        return redirect(request.referrer)
Exemplo n.º 6
0
    def facebook_authorized_login(self):
        """Authorized handler to which facebook will redirect the user to
        after the login attempt is made.
        """
        website_obj = Pool().get('nereid.website')

        facebook = website_obj.get_facebook_oauth_client()
        if facebook is None:
            return redirect(
                request.referrer or url_for('nereid.website.login')
            )

        try:
            if 'oauth_verifier' in request.args:
                data = facebook.handle_oauth1_response()
            elif 'code' in request.args:
                data = facebook.handle_oauth2_response()
            else:
                data = facebook.handle_unknown_response()
            facebook.free_request_token()
        except Exception, exc:
            current_app.logger.error("Facebook login failed", exc)
            flash(_("We cannot talk to facebook at this time. Please try again"))
            return redirect(
                request.referrer or url_for('nereid.website.login')
            )
Exemplo n.º 7
0
    def render_comments(self):
        """
        Render comments

        GET: Return json of all the comments of this post.
        POST: Create new comment for this post.
        """
        if self.state != 'Published':
            abort(404)

        # Add re_captcha if the configuration has such an option and user
        # is guest
        if 're_captcha_public' in CONFIG.options and request.is_guest_user:
            comment_form = GuestCommentForm(
                request.form, captcha={'ip_address': request.remote_addr}
            )
        else:
            comment_form = PostCommentForm(request.form)

        if request.method == 'GET':
            if self.nereid_user == request.nereid_user:
                return jsonify(comments=[
                    comment.serialize() for comment in self.comments
                ])
            return jsonify(comments=[
                comment.serialize() for comment in self.comments
                if not comment.is_spam
            ])

        # If post does not allow guest comments,
        # then dont allow guest user to comment
        if not self.allow_guest_comments and request.is_guest_user:
            flash('Guests are not allowed to write comments')
            if request.is_xhr:
                return jsonify(
                    success=False,
                    errors=['Guests are not allowed to write comments']
                )
            return redirect(url_for(
                'blog.post.render', user_id=self.nereid_user.id, uri=self.uri
            ))

        if request.method == 'POST' and comment_form.validate():
            self.write([self], {
                'comments': [('create', [{
                    'nereid_user': current_user.id
                        if not current_user.is_anonymous() else None,
                    'name': current_user.display_name
                        if not current_user.is_anonymous()
                            else comment_form.name.data,
                    'content': comment_form.content.data,
                }])]
            })

        if request.is_xhr:
            return jsonify(success=True) if comment_form.validate() \
                else jsonify(success=False, errors=comment_form.errors)
        return redirect(url_for(
            'blog.post.render', user_id=self.nereid_user.id, uri=self.uri
        ))
Exemplo n.º 8
0
    def delete_task(cls, task_id):
        """
        Delete the task from project

        Tasks can be deleted only if
            1. The user is project admin
            2. The user is an admin member in the project

        :param task_id: Id of the task to be deleted
        """
        task = cls.get_task(task_id)

        # Check if user is among the project admins
        if not request.nereid_user.is_admin_of_project(task.parent):
            flash(
                "Sorry! You are not allowed to delete tasks. \
                Contact your project admin for the same."
            )
            return redirect(request.referrer)

        cls.write([task], {"active": False})

        if request.is_xhr:
            return jsonify({"success": True})

        flash("The task has been deleted")
        return redirect(url_for("project.work.render_project", project_id=task.parent.id))
Exemplo n.º 9
0
    def remove_tag(cls, task_id, tag_id):
        """
        Assigns the provided to this task

        :param task_id: ID of task
        :param tag_id: ID of tag
        """
        Activity = Pool().get('nereid.activity')
        task = cls.get_task(task_id)

        cls.write(
            [task], {'tags': [('remove', [tag_id])]}
        )
        Activity.create([{
            'actor': request.nereid_user.id,
            'object_': 'project.work, %d' % task.id,
            'verb': 'removed_tag_from_task',
            'target': 'project.work, %d' % task.parent.id,
            'project': task.parent.id,
        }])

        if request.method == 'POST':
            flash('Tag removed from task %s' % task.rec_name)
            return redirect(request.referrer)

        flash("Tag cannot be removed")
        return redirect(request.referrer)
Exemplo n.º 10
0
    def create_task(self, project_id):
        """Create a new task for the specified project

        POST will create a new task
        """
        project = self.get_project(project_id)
        # Check if user is among the participants
        self.can_write(project, request.nereid_user)

        if request.method == 'POST':
            task_id = self.create({
                'parent': project_id,
                'name': request.form['name'],
                'type': 'task',
                'comment': request.form.get('description', False),
            })
            flash("Task successfully added to project %s" % project.name)
            return redirect(
                url_for('project.work.render_task',
                    project_id=project_id, task_id=task_id
                )
            )

        flash("Could not create task. Try again.")
        return redirect(request.referrer)
Exemplo n.º 11
0
    def linkedin_authorized_login(cls):
        """Authorized handler to which linkedin will redirect the user to
        after the login attempt is made.
        """
        Party = Pool().get('party.party')

        linkedin = request.nereid_website.get_linkedin_oauth_client()
        if linkedin is None:
            return redirect(
                request.referrer or url_for('nereid.website.login')
            )

        try:
            if 'oauth_verifier' in request.args:
                data = linkedin.handle_oauth1_response()
            elif 'code' in request.args:
                data = linkedin.handle_oauth2_response()
            else:
                data = linkedin.handle_unknown_response()
            linkedin.free_request_token()
        except Exception, exc:
            current_app.logger.error("LinkedIn login failed %s" % exc)
            flash(_(
                "We cannot talk to linkedin at this time. Please try again"
            ))
            return redirect(
                request.referrer or url_for('nereid.website.login')
            )
Exemplo n.º 12
0
    def remove_tag(cls, task_id, tag_id):
        """
        Assigns the provided to this task

        :param task_id: ID of task
        :param tag_id: ID of tag
        """
        Activity = Pool().get("nereid.activity")
        task = cls.get_task(task_id)

        cls.write([task], {"tags": [("unlink", [tag_id])]})
        Activity.create(
            [
                {
                    "actor": request.nereid_user.id,
                    "object_": "project.work, %d" % task.id,
                    "verb": "removed_tag_from_task",
                    "target": "project.work, %d" % task.parent.id,
                    "project": task.parent.id,
                }
            ]
        )

        if request.method == "POST":
            flash("Tag removed from task %s" % task.rec_name)
            return redirect(request.referrer)

        flash("Tag cannot be removed")
        return redirect(request.referrer)
Exemplo n.º 13
0
    def linkedin_authorized_login(cls):
        """Authorized handler to which linkedin will redirect the user to
        after the login attempt is made.
        """
        Party = Pool().get('party.party')

        linkedin = request.nereid_website.get_linkedin_oauth_client()
        if linkedin is None:
            return redirect(request.referrer
                            or url_for('nereid.website.login'))

        try:
            if 'oauth_verifier' in request.args:
                data = linkedin.handle_oauth1_response()
            elif 'code' in request.args:
                data = linkedin.handle_oauth2_response()
            else:
                data = linkedin.handle_unknown_response()
            linkedin.free_request_token()
        except Exception, exc:
            current_app.logger.error("LinkedIn login failed %s" % exc)
            flash(
                _("We cannot talk to linkedin at this time. Please try again"))
            return redirect(request.referrer
                            or url_for('nereid.website.login'))
Exemplo n.º 14
0
    def github_authorized_login(cls):
        """
        Authorized handler to which github will redirect the user to
        after the login attempt is made.
        """
        github = request.nereid_website.get_github_oauth_client()
        if github is None:
            return redirect(
                request.referrer or url_for('nereid.website.login')
            )

        try:
            # The response is an oauth2 response with code. But Github API
            # requires the
            if 'oauth_verifier' in request.args:
                data = github.handle_oauth1_response()
            elif 'code' in request.args:
                data = github.handle_oauth2_response()
            else:
                data = github.handle_unknown_response()
            github.free_request_token()
        except Exception, exc:
            current_app.logger.error("Github login failed %s" % exc)
            flash(_("We cannot talk to github at this time. Please try again"))
            return redirect(
                request.referrer or url_for('nereid.website.login')
            )
Exemplo n.º 15
0
    def facebook_authorized_login(self):
        """Authorized handler to which facebook will redirect the user to
        after the login attempt is made.
        """
        website_obj = Pool().get('nereid.website')

        facebook = website_obj.get_facebook_oauth_client()
        if facebook is None:
            return redirect(request.referrer
                            or url_for('nereid.website.login'))

        try:
            if 'oauth_verifier' in request.args:
                data = facebook.handle_oauth1_response()
            elif 'code' in request.args:
                data = facebook.handle_oauth2_response()
            else:
                data = facebook.handle_unknown_response()
            facebook.free_request_token()
        except Exception, exc:
            current_app.logger.error("Facebook login failed", exc)
            flash(
                _("We cannot talk to facebook at this time. Please try again"))
            return redirect(request.referrer
                            or url_for('nereid.website.login'))
Exemplo n.º 16
0
    def assign_lead(self):
        "Change the employee on lead"
        NereidUser = Pool().get('nereid.user')

        new_assignee = NereidUser(int(request.form['user']))
        if self.employee.id == new_assignee.employee.id:
            flash("Lead already assigned to %s" % new_assignee.party.name)
            return redirect(request.referrer)

        self.write([self], {'employee': new_assignee.employee.id})

        flash("Lead assigned to %s" % new_assignee.party.name)
        return redirect(request.referrer)
Exemplo n.º 17
0
    def change_estimated_hours(self):
        """Change estimated hours.

        :param task_id: ID of the task.
        """
        if not request.nereid_user.employee:
            flash("Sorry! You are not allowed to change estimate hours.")
            return redirect(request.referrer)

        estimated_hours = request.form.get("new_estimated_hours", None, type=float)
        if estimated_hours:
            self.write([self], {"effort": estimated_hours})
        flash("The estimated hours have been changed for this task.")
        return redirect(request.referrer)
Exemplo n.º 18
0
    def assign_lead(self):
        "Change the employee on lead"
        NereidUser = Pool().get('nereid.user')

        new_assignee = NereidUser(int(request.form['user']))
        if self.employee.id == new_assignee.employee.id:
            flash("Lead already assigned to %s" % new_assignee.party.name)
            return redirect(request.referrer)

        self.write([self], {
            'employee': new_assignee.employee.id
        })

        flash("Lead assigned to %s" % new_assignee.party.name)
        return redirect(request.referrer)
Exemplo n.º 19
0
    def render_wishlist(self):
        """
        Render specific wishlist of current user.
        rename wishlist on post  and delete on delete request
        """
        Wishlist = Pool().get('wishlist.wishlist')

        if self.nereid_user != current_user and \
                (request.method != "GET" or not self.is_public):

            abort(404)

        if request.method == "POST" and request.form.get('name'):

            name = request.form.get('name')
            wishlist = Wishlist.search([
                ('nereid_user', '=', current_user.id),
                ('id', '!=', self.id),
                ('name', '=', name),
            ], limit=1)
            if wishlist:
                flash(
                    _(
                        'Wishlist with name: %(name)s already exists.',
                        name=name
                    )
                )
                return redirect(request.referrer)
            else:
                self.name = name
                self.is_public = True if request.form.get('is_public') \
                    else False
                self.save()
                flash(_('Wishlist Updated'))
            if request.is_xhr:
                return 'success', 200

            return redirect(request.referrer)

        elif request.method == "DELETE":
            Wishlist.delete([self])
            if request.is_xhr:
                # TODO: send serialized data of current wishlist
                return 'success', 200

            return url_for('wishlist.wishlist.render_wishlists')

        return render_template('wishlist.jinja', wishlist=self)
Exemplo n.º 20
0
    def change_constraint_dates(cls, task_id):
        """
        Change the constraint dates
        """
        Activity = Pool().get("nereid.activity")

        task = cls.get_task(task_id)

        data = {"constraint_start_time": False, "constraint_finish_time": False}

        constraint_start = request.form.get("constraint_start_time", None)
        constraint_finish = request.form.get("constraint_finish_time", None)

        if constraint_start:
            data["constraint_start_time"] = datetime.strptime(constraint_start, "%m/%d/%Y")
        if constraint_finish:
            data["constraint_finish_time"] = datetime.strptime(constraint_finish, "%m/%d/%Y")

        cls.write([task], data)
        Activity.create(
            [
                {
                    "actor": request.nereid_user.id,
                    "object_": "project.work, %d" % task.id,
                    "verb": "changed_date",
                    "project": task.parent.id,
                }
            ]
        )

        if request.is_xhr:
            return jsonify({"success": True})

        flash("The constraint dates have been changed for this task.")
        return redirect(request.referrer)
Exemplo n.º 21
0
    def edit_task(self):
        """
        Edit the task
        """
        Activity = Pool().get('nereid.activity')
        Work = Pool().get('timesheet.work')

        task = self.get_task(self.id)

        Work.write([task.work], {
            'name': request.form.get('name'),
        })
        self.write([task], {
            'comment': request.form.get('comment')
        })
        Activity.create([{
            'actor': request.nereid_user.id,
            'object_': 'project.work, %d' % task.id,
            'verb': 'edited_task',
            'target': 'project.work, %d' % task.parent.id,
            'project': task.parent.id,
        }])
        if request.is_xhr:
            return jsonify({
                'success': True,
                'name': self.rec_name,
                'comment': self.comment,
            })
        return redirect(request.referrer)
Exemplo n.º 22
0
    def edit_task(self):
        """
        Edit the task
        """
        Activity = Pool().get("nereid.activity")
        Work = Pool().get("timesheet.work")

        task = self.get_task(self.id)

        Work.write([task.work], {"name": request.form.get("name")})
        self.write([task], {"comment": request.form.get("comment")})
        Activity.create(
            [
                {
                    "actor": request.nereid_user.id,
                    "object_": "project.work, %d" % task.id,
                    "verb": "edited_task",
                    "target": "project.work, %d" % task.parent.id,
                    "project": task.parent.id,
                }
            ]
        )
        if request.is_xhr:
            return jsonify({"success": True, "name": self.rec_name, "comment": self.comment})
        return redirect(request.referrer)
Exemplo n.º 23
0
    def cms_static_upload(cls, upload_type):
        """
        Upload the file for cms
        """
        StaticFile = Pool().get("nereid.static.file")

        file = request.files['file']
        if file:
            static_file, = StaticFile.create([{
                'folder':
                current_website.cms_static_folder,
                'name':
                '_'.join([
                    str(int(time.time())),
                    secure_filename(file.filename),
                ]),
                'type':
                upload_type,
                'file_binary':
                file.read(),
            }])
            if request.is_xhr:
                return jsonify(success=True, item=static_file.serialize())

            flash("File uploaded")
        if request.is_xhr:
            return jsonify(success=False)
        return redirect(request.referrer)
Exemplo n.º 24
0
    def update_comment(self, task_id, comment_id):
        """
        Update a specific comment.
        """
        project_obj = Pool().get('project.work')
        nereid_user_obj = Pool().get('nereid.user')

        # allow modification only if the user is an admin or the author of
        # this ticket
        task = project_obj.browse(task_id)
        comment = self.browse(comment_id)
        assert task.type == "task"
        assert comment.project.id == task.id

        # Allow only admins and author of this comment to edit it
        if nereid_user_obj.is_project_admin(request.nereid_user) or \
                comment.updated_by == request.nereid_user:
            self.write(comment_id, {'comment': request.form['comment']})
        else:
            abort(403)

        if request.is_xhr:
            comment_record = self.browse(comment_id)
            html = render_template('comment.jinja', comment=comment_record)
            return jsonify({
                'success': True,
                'html': html,
                'state': project_obj.browse(task.id).state,
            })
        return redirect(request.referrer)
Exemplo n.º 25
0
    def edit_post(self):
        """
            Edit an existing post
        """
        if self.nereid_user != request.nereid_user:
            abort(404)

        # Search for a post with same uri
        post_form = BlogPostForm(request.form, obj=self)

        with Transaction().set_context(blog_id=self.id):
            if request.method == 'POST' and post_form.validate():
                self.title = post_form.title.data
                self.content = post_form.content.data
                self.allow_guest_comments = post_form.allow_guest_comments.data
                self.save()
                flash('Your post has been updated.')
                if request.is_xhr:
                    return jsonify(success=True, item=self.serialize())
                return redirect(
                    url_for('blog.post.render',
                            user_id=self.nereid_user.id,
                            uri=self.uri))
        if request.is_xhr:
            return jsonify(
                success=request.method != 'POST',  # False for POST, else True
                errors=post_form.errors or None,
            )
        return render_template('blog_post_edit.jinja',
                               form=post_form,
                               post=self)
Exemplo n.º 26
0
    def change_estimated_hours(self):
        """Change estimated hours.

        :param task_id: ID of the task.
        """
        if not request.nereid_user.employee:
            flash("Sorry! You are not allowed to change estimate hours.")
            return redirect(request.referrer)

        estimated_hours = request.form.get('new_estimated_hours',
                                           None,
                                           type=float)
        if estimated_hours:
            self.write([self], {'effort': estimated_hours})
        flash("The estimated hours have been changed for this task.")
        return redirect(request.referrer)
Exemplo n.º 27
0
    def revenue_opportunity(self):
        """
        Set the Conversion Probability and estimated revenue amount
        """
        NereidUser = Pool().get('nereid.user')

        nereid_user = NereidUser.search(
            [('employee', '=', self.employee.id)], limit=1
        )
        if nereid_user:
            employee = nereid_user[0]
        else:
            employee = None

        if request.method == 'POST':
            self.write([self], {
                'probability': request.form['probability'],
                'amount': Decimal(request.form.get('amount'))
            })
            flash('Lead has been updated.')
            return redirect(
                url_for('sale.opportunity.admin_lead', active_id=self.id)
                + "#tab-revenue"
            )
        return render_template(
            'crm/admin-lead.jinja', lead=self, employee=employee,
        )
Exemplo n.º 28
0
    def new_post(cls):
        """Create a new post
        """
        post_form = BlogPostForm(request.form)

        if request.method == 'POST' and post_form.validate():
            post, = cls.create([{
                'title': post_form.title.data,
                'uri': post_form.uri.data,
                'content': post_form.content.data,
                'nereid_user': request.nereid_user.id,
                'allow_guest_comments': post_form.allow_guest_comments.data,
            }])
            if post_form.publish.data:
                cls.publish([post])
                flash('Your post has been published.')
            else:
                flash('Your post has been saved.')

            if request.is_xhr:
                return jsonify(success=True, item=post.serialize())
            return redirect(url_for(
                'blog.post.render', user_id=post.nereid_user.id,
                uri=post.uri
            ))
        if request.is_xhr:
            return jsonify(
                success=request.method != 'POST',  # False for POST, else True
                errors=post_form.errors or None,
            )
        return render_template('blog_post_form.jinja', form=post_form)
Exemplo n.º 29
0
    def edit_task(self):
        """
        Edit the task
        """
        Activity = Pool().get('nereid.activity')
        Work = Pool().get('timesheet.work')

        task = self.get_task(self.id)

        Work.write([task.work], {
            'name': request.form.get('name'),
        })
        self.write([task], {'comment': request.form.get('comment')})
        Activity.create([{
            'actor': request.nereid_user.id,
            'object_': 'project.work, %d' % task.id,
            'verb': 'edited_task',
            'target': 'project.work, %d' % task.parent.id,
            'project': task.parent.id,
        }])
        if request.is_xhr:
            return jsonify({
                'success': True,
                'name': self.rec_name,
                'comment': self.comment,
            })
        return redirect(request.referrer)
Exemplo n.º 30
0
    def edit_post(self):
        """
            Edit an existing post
        """
        if self.nereid_user != request.nereid_user:
            abort(404)

        # Search for a post with same uri
        post_form = BlogPostForm(request.form, obj=self)

        with Transaction().set_context(blog_id=self.id):
            if request.method == 'POST' and post_form.validate():
                self.title = post_form.title.data
                self.content = post_form.content.data
                self.allow_guest_comments = post_form.allow_guest_comments.data
                self.save()
                flash('Your post has been updated.')
                if request.is_xhr:
                    return jsonify(success=True, item=self.serialize())
                return redirect(url_for(
                    'blog.post.render', user_id=self.nereid_user.id,
                    uri=self.uri
                ))
        if request.is_xhr:
            return jsonify(
                success=request.method != 'POST',  # False for POST, else True
                errors=post_form.errors or None,
            )
        return render_template(
            'blog_post_edit.jinja', form=post_form, post=self
        )
Exemplo n.º 31
0
    def revenue_opportunity(self):
        """
        Set the Conversion Probability and estimated revenue amount
        """
        NereidUser = Pool().get('nereid.user')

        nereid_user = NereidUser.search([('employee', '=', self.employee.id)],
                                        limit=1)
        if nereid_user:
            employee = nereid_user[0]
        else:
            employee = None

        if request.method == 'POST':
            self.write(
                [self], {
                    'probability': request.form['probability'],
                    'amount': Decimal(request.form.get('amount'))
                })
            flash('Lead has been updated.')
            return redirect(
                url_for('sale.opportunity.admin_lead', active_id=self.id) +
                "#tab-revenue")
        return render_template(
            'crm/admin-lead.jinja',
            lead=self,
            employee=employee,
        )
Exemplo n.º 32
0
    def payment_method(cls):
        '''
        Select/Create a payment method

        Allows adding new payment profiles for registered users. Guest users
        are allowed to fill in credit card information or chose from one of
        the existing payment gateways.
        '''
        NereidCart = Pool().get('nereid.cart')
        PaymentMethod = Pool().get('nereid.website.payment_method')
        Date = Pool().get('ir.date')

        cart = NereidCart.open_cart()
        if not cart.sale.shipment_address:
            return redirect(url_for('nereid.checkout.shipping_address'))

        payment_form = cls.get_payment_form()
        credit_card_form = cls.get_credit_card_form()

        if request.method == 'POST' and payment_form.validate():

            # Setting sale date as current date
            cart.sale.sale_date = Date.today()
            cart.sale.save()

            # call the billing address method which will handle any
            # address submission that may be there in this request
            cls.billing_address()

            if not cart.sale.invoice_address:
                # If still there is no billing address. Do not proceed
                # with this
                return redirect(url_for('nereid.checkout.billing_address'))

            rv = cls._process_payment(cart)
            if isinstance(rv, BaseResponse):
                # Return if BaseResponse
                return rv

            flash(_("Error is processing payment."), "warning")

        return render_template(
            'checkout/payment_method.jinja',
            payment_form=payment_form,
            credit_card_form=credit_card_form,
            PaymentMethod=PaymentMethod,
        )
Exemplo n.º 33
0
    def payment_method(cls):
        '''
        Select/Create a payment method

        Allows adding new payment profiles for registered users. Guest users
        are allowed to fill in credit card information or chose from one of
        the existing payment gateways.
        '''
        NereidCart = Pool().get('nereid.cart')
        PaymentMethod = Pool().get('nereid.website.payment_method')
        Date = Pool().get('ir.date')

        cart = NereidCart.open_cart()
        if not cart.sale.shipment_address:
            return redirect(url_for('nereid.checkout.shipping_address'))

        payment_form = cls.get_payment_form()
        credit_card_form = cls.get_credit_card_form()

        if request.method == 'POST' and payment_form.validate():

            # Setting sale date as current date
            cart.sale.sale_date = Date.today()
            cart.sale.save()

            # call the billing address method which will handle any
            # address submission that may be there in this request
            cls.billing_address()

            if not cart.sale.invoice_address:
                # If still there is no billing address. Do not proceed
                # with this
                return redirect(url_for('nereid.checkout.billing_address'))

            rv = cls._process_payment(cart)
            if isinstance(rv, BaseResponse):
                # Return if BaseResponse
                return rv

            flash(_("Error is processing payment."), "warning")

        return render_template(
            'checkout/payment_method.jinja',
            payment_form=payment_form,
            credit_card_form=credit_card_form,
            PaymentMethod=PaymentMethod,
        )
Exemplo n.º 34
0
    def validate_address(cls):
        '''
        Validation of shipping address (optional)

        Shipping address can be validated and address suggestions could be shown
        to the user. Here user can chooose address from suggestion and update
        the saved address on `POST`
        '''
        NereidCart = Pool().get('nereid.cart')

        cart = NereidCart.open_cart()

        if not cart.sale.shipment_address:
            return redirect(url_for('nereid.checkout.shipping_address'))

        # TODO: Not implemented yet
        return redirect(url_for('nereid.checkout.delivery_method'))
Exemplo n.º 35
0
 def wrapper(*args, **kwargs):
     NereidCart = Pool().get('nereid.cart')
     cart = NereidCart.open_cart()
     if not (cart.sale and cart.sale.lines):
         current_app.logger.debug(
             'No sale or lines. Redirect to shopping-cart')
         return redirect(url_for('nereid.cart.view_cart'))
     return function(*args, **kwargs)
Exemplo n.º 36
0
 def validate_for_product_inventory(self):
     """
     This method validates the sale line against the product's inventory
     attributes. This method requires request context.
     """
     if has_request_context() and not self.product.can_buy_from_eshop():
         flash(_('This product is no longer available'))
         abort(redirect(request.referrer))
Exemplo n.º 37
0
    def validate_address(cls):
        '''
        Validation of shipping address (optional)

        Shipping address can be validated and address suggestions could be shown
        to the user. Here user can chooose address from suggestion and update
        the saved address on `POST`
        '''
        NereidCart = Pool().get('nereid.cart')

        cart = NereidCart.open_cart()

        if not cart.sale.shipment_address:
            return redirect(url_for('nereid.checkout.shipping_address'))

        # TODO: Not implemented yet
        return redirect(url_for('nereid.checkout.delivery_method'))
Exemplo n.º 38
0
 def validate_for_product_inventory(self):
     """
     This method validates the sale line against the product's inventory
     attributes. This method requires request context.
     """
     if has_request_context() and not self.product.can_buy_from_eshop():
         flash(_("This product is no longer available"))
         abort(redirect(request.referrer))
Exemplo n.º 39
0
    def render_wishlist(self):
        """
        Render specific wishlist of current user.
        rename wishlist on post  and delete on delete request
        """
        Wishlist = Pool().get('wishlist.wishlist')

        if self.nereid_user != current_user and \
                (request.method != "GET" or not self.is_public):

            abort(404)

        if request.method == "POST" and request.form.get('name'):

            name = request.form.get('name')
            wishlist = Wishlist.search([
                ('nereid_user', '=', current_user.id),
                ('id', '!=', self.id),
                ('name', '=', name),
            ],
                                       limit=1)
            if wishlist:
                flash(
                    _('Wishlist with name: %(name)s already exists.',
                      name=name))
                return redirect(request.referrer)
            else:
                self.name = name
                self.is_public = True if request.form.get('is_public') \
                    else False
                self.save()
                flash(_('Wishlist Updated'))
            if request.is_xhr:
                return 'success', 200

            return redirect(request.referrer)

        elif request.method == "DELETE":
            Wishlist.delete([self])
            if request.is_xhr:
                # TODO: send serialized data of current wishlist
                return 'success', 200

            return url_for('wishlist.wishlist.render_wishlists')

        return render_template('wishlist.jinja', wishlist=self)
Exemplo n.º 40
0
    def move_task_to_project(self, project_id):
        """
        Move task from one project to another.
        """
        ProjectWork = Pool().get('project.work')

        assert self.type == 'task'

        try:
            target_project, = ProjectWork.search([
                ('id', '=', project_id),
                ('type', '=', 'project')
            ], limit=1)
        except ValueError:
            flash("No project found with given details")
            return redirect(request.referrer)

        if not (
            current_user.is_admin_of_project(self.parent) and
            current_user.is_admin_of_project(target_project)
        ):
            abort(403)

        if self.parent.id == target_project.id:
            flash("Task already in this project")
            return redirect(request.referrer)

        if self.assigned_to not in [
            member.user for member in target_project.members
        ]:
            self.assigned_to = None

        # Move task to target project
        self.parent = target_project.id
        self.save()

        flash("Task #%d successfully moved to project %s" % (
            self.id, target_project.work.name
        ))
        return redirect(
            url_for(
                'project.work.render_task',
                project_id=target_project.id, task_id=self.id
            )
        )
Exemplo n.º 41
0
    def delivery_method(cls):
        '''
        Selection of delivery method (options)

        Based on the shipping address selected, the delivery options
        could be shown to the user. This may include choosing shipping speed
        and if there are multiple items, the option to choose items as they are
        available or all at once.
        '''
        NereidCart = Pool().get('nereid.cart')

        cart = NereidCart.open_cart()

        if not cart.sale.shipment_address:
            return redirect(url_for('nereid.checkout.shipping_address'))

        # TODO: Not implemented yet
        return redirect(url_for('nereid.checkout.payment_method'))
Exemplo n.º 42
0
    def delete_tag(self, tag_id):
        """Delete the tag from project
        """
        # Check if user is among the project admins
        if not request.nereid_user.is_project_admin(request.nereid_user):
            flash("Sorry! You are not allowed to delete tags. \
                Contact your project admin for the same.")
            return redirect(request.referrer)

        if request.method == 'POST' and request.is_xhr:
            tag_id = self.delete(tag_id)

            return jsonify({
                'success': True,
            })

        flash("Could not delete tag! Try again.")
        return redirect(request.referrer)
Exemplo n.º 43
0
    def remove_tag(self, task_id, tag_id):
        """Assigns the provided to this task

        :param task_id: ID of task
        :param tag_id: ID of tag
        """
        task = self.get_task(task_id)

        self.write(
            task.id, {'tags': [('unlink', [tag_id])]}
        )

        if request.method == 'POST':
            flash('Tag removed from task %s' % task.name)
            return redirect(request.referrer)

        flash("Tag cannot be removed")
        return redirect(request.referrer)
Exemplo n.º 44
0
    def delivery_method(cls):
        '''
        Selection of delivery method (options)

        Based on the shipping address selected, the delivery options
        could be shown to the user. This may include choosing shipping speed
        and if there are multiple items, the option to choose items as they are
        available or all at once.
        '''
        NereidCart = Pool().get('nereid.cart')

        cart = NereidCart.open_cart()

        if not cart.sale.shipment_address:
            return redirect(url_for('nereid.checkout.shipping_address'))

        # TODO: Not implemented yet
        return redirect(url_for('nereid.checkout.payment_method'))
Exemplo n.º 45
0
 def wrapper(*args, **kwargs):
     NereidCart = Pool().get('nereid.cart')
     cart = NereidCart.open_cart()
     if not (cart.sale and cart.sale.lines):
         current_app.logger.debug(
             'No sale or lines. Redirect to shopping-cart'
         )
         return redirect(url_for('nereid.cart.view_cart'))
     return function(*args, **kwargs)
Exemplo n.º 46
0
    def delivery_method(cls):
        '''
        Selection of delivery method (options)
        Based on the shipping address selected, the delivery options
        could be shown to the user. This may include choosing shipping speed
        and if there are multiple items, the option to choose items as they are
        available or all at once.
        '''
        NereidCart = Pool().get('nereid.cart')
        Carrier = Pool().get('carrier')
        Sale = Pool().get('sale.sale')

        signer = URLSafeSerializer(current_app.config['SECRET_KEY'])

        cart_sale = NereidCart.open_cart().sale

        if not cart_sale.shipment_address:
            return redirect(url_for('nereid.checkout.shipping_address'))

        if not cart_sale.package_weight:
            # No weight, no shipping. Have fun !
            return redirect(url_for('nereid.checkout.payment_method'))

        if request.method == 'POST' and \
                request.form.get('shipping_service_data'):
            try:
                shipping_service_data = signer.loads(
                    request.form.get('shipping_service_data'))
            except BadSignature:
                abort(400)
            Sale.write([cart_sale], shipping_service_data)
            cart_sale.apply_shipping()
            return redirect(url_for('nereid.checkout.payment_method'))

        shipping_overweight = False
        delivery_rates = []
        with Transaction().set_context(sale=cart_sale.id):
            try:
                delivery_rates = Carrier.get_rate_list()
            except UserError, e:
                # Possible Errors: Overweighted shipment, Invalid address
                # TODO: Handle gracefully
                flash(e.message)
                return redirect(url_for('nereid.checkout.shipping_address'))
Exemplo n.º 47
0
    def update_task(self, task_id, project_id=None):
        """
        Accepts a POST request against a task_id and updates the ticket

        :param task_id: The ID of the task which needs to be updated
        """
        history_obj = Pool().get('project.work.history')

        task = self.get_task(task_id)

        history_data = {
            'project': task.id,
            'updated_by': request.nereid_user.id,
            'comment': request.form['comment']
        }

        updatable_attrs = ['state']
        post_attrs = [request.form.get(attr, None) for attr in updatable_attrs]

        if any(post_attrs):
            # Combined update of task and history since there is some value
            # posted in addition to the comment
            task_changes = {}
            for attr in updatable_attrs:
                if getattr(task, attr) != request.form[attr]:
                    task_changes[attr] = request.form[attr]

            if task_changes:
                # Only write change if anything has really changed
                self.write(task.id, task_changes)
                comment_id = self.browse(task.id).history[-1].id
                history_obj.write(comment_id, history_data)
            else:
                # just create comment since nothing really changed since this
                # update. This is to cover to cover cases where two users who
                # havent refreshed the web page close the ticket
                comment_id = history_obj.create(history_data)
        else:
            # Just comment, no update to task
            comment_id = history_obj.create(history_data)

        if request.nereid_user.id not in (p.id for p in task.participants):
            # Add the user to the participants if not already in the list
            self.write(
                task.id, {'participants': [('add', [request.nereid_user.id])]}
            )

        if request.is_xhr:
            comment_record = history_obj.browse(comment_id)
            html = render_template('comment.jinja', comment=comment_record)
            return jsonify({
                'success': True,
                'html': html,
                'state': self.browse(task.id).state,
            })
        return redirect(request.referrer)
Exemplo n.º 48
0
 def wrapper(*args, **kwargs):
     NereidCart = Pool().get('nereid.cart')
     cart = NereidCart.open_cart()
     if cart.sale and \
             cart.sale.party == current_website.guest_user.party:
         # The cart is owned by the guest user party
         current_app.logger.debug(
             'Cart is owned by guest. Redirect to sign-in')
         return redirect(url_for('nereid.checkout.sign_in'))
     return function(*args, **kwargs)
Exemplo n.º 49
0
    def delivery_method(cls):
        '''
        Selection of delivery method (options)

        Based on the shipping address selected, the delivery options
        could be shown to the user. This may include choosing shipping speed
        and if there are multiple items, the option to choose items as they are
        available or all at once.
        '''
        NereidCart = Pool().get('nereid.cart')
        Carrier = Pool().get('carrier')
        CarrierService = Pool().get('carrier.service')
        Currency = Pool().get('currency.currency')
        cart_sale = NereidCart.open_cart().sale
        if not cart_sale.shipment_address:
            return redirect(url_for('nereid.checkout.shipping_address'))

        if not cart_sale.weight:
            # No weight, no shipping. Have fun !
            return redirect(url_for('nereid.checkout.payment_method'))

        if request.method == 'POST' and request.form.get('carrier_json'):
            rate = json.loads(request.form.get('carrier_json'))
            rate.update({
                'carrier': Carrier(rate['carrier']),
                'carrier_service': CarrierService(rate['carrier_service']),
                'cost_currency': Currency(rate['cost_currency']),
                'cost': Decimal("%s" % (rate['cost'], ))
            })
            cart_sale.apply_shipping_rate(rate)
            return redirect(url_for('nereid.checkout.payment_method'))

        delivery_rates = []
        try:
            delivery_rates = cart_sale.get_shipping_rates(
                current_website.carriers,
                silent=True
            )
        except UserError, e:
            # Possible Errors: Overweighted shipment, Invalid address
            # TODO: Handle gracefully
            flash(e.message)
            return redirect(url_for('nereid.checkout.shipping_address'))
Exemplo n.º 50
0
 def validate_payment_profile(self, payment_profile):
     """
     Checks if payment profile belongs to right party
     """
     if not current_user.is_anonymous and \
             payment_profile.party != current_user.party:
         # verify that the payment profile belongs to the registered
         # user.
         flash(_('The payment profile chosen is invalid'))
         return redirect(url_for('nereid.checkout.payment_method'))
Exemplo n.º 51
0
 def mark_cancelled(self):
     """
     Convert the lead as cancelled
     """
     self.cancel([self])
     if request.is_xhr or request.is_json:
         return jsonify({
             'success': True,
             'message': 'The lead is cancelled.'
         })
     return redirect(request.referrer)
Exemplo n.º 52
0
    def delete_tag(self):
        """
        Delete the tag from project
        """
        # Check if user is among the project admins
        if request.method == 'POST' and not \
                request.nereid_user.is_admin_of_project(self.project):
            flash("Sorry! You are not allowed to delete tags." +
                  " Contact your project admin for the same.")
            return redirect(request.referrer)

        if request.method == 'POST' and request.is_xhr:
            self.delete([self])

            return jsonify({
                'success': True,
            })

        flash("Could not delete tag! Try again.")
        return redirect(request.referrer)
Exemplo n.º 53
0
 def mark_converted(self):
     """
     Convert the opportunity
     """
     self.convert([self])
     if request.is_xhr or request.is_json:
         return jsonify({
             'success': True,
             'message': 'Awesome! The Opportunity is converted.'
         })
     return redirect(request.referrer)
Exemplo n.º 54
0
 def mark_lead(self):
     """
     Convert the opportunity to lead
     """
     self.lead([self])
     if request.is_xhr or request.is_json:
         return jsonify({
             'success': True,
             'message': 'The lead is marked back to open.'
         })
     return redirect(request.referrer)
Exemplo n.º 55
0
 def mark_lost(self):
     """
     Convert the lead to lost
     """
     self.lost([self])
     if request.is_xhr or request.is_json:
         return jsonify({
             'success': True,
             'message': 'The lead is marked as lost.'
         })
     return redirect(request.referrer)
Exemplo n.º 56
0
    def render(cls, uri, path=None):
        """
        Render gift card template if product is of type gift card
        """
        render_obj = super(Product, cls).render(uri, path)

        if not isinstance(render_obj, NotFound) \
                and render_obj.context['product'].is_gift_card:
            # Render gift card
            return redirect(
                url_for('product.product.render_gift_card', uri=uri))
        return render_obj
Exemplo n.º 57
0
 def facebook_login(cls):
     """The URL to which a new request to authenticate to facebook begins
     Usually issues a redirect.
     """
     facebook = request.nereid_website.get_facebook_oauth_client()
     if facebook is None:
         return redirect(request.referrer
                         or url_for('nereid.website.login'))
     return facebook.authorize(callback=url_for(
         'nereid.user.facebook_authorized_login',
         next=request.args.get('next') or request.referrer or None,
         _external=True))
Exemplo n.º 58
0
 def linkedin_login(cls):
     """The URL to which a new request to authenticate to linedin begins
     Usually issues a redirect.
     """
     linkedin = request.nereid_website.get_linkedin_oauth_client()
     if linkedin is None:
         return redirect(request.referrer
                         or url_for('nereid.website.login'))
     return linkedin.authorize(callback=url_for(
         'nereid.user.linkedin_authorized_login',
         next=request.args.get('next') or request.referrer or None,
         _external=True))
Exemplo n.º 59
0
 def github_login(cls):
     """
     The URL to which a new request to authenticate to github begins
     Usually issues a redirect.
     """
     github = request.nereid_website.get_github_oauth_client()
     if github is None:
         return redirect(request.referrer
                         or url_for('nereid.website.login'))
     return github.authorize(callback=url_for(
         'nereid.user.github_authorized_login',
         next=request.args.get('next') or request.referrer or None,
         _external=True))
Exemplo n.º 60
0
 def mark_opportunity(self):
     """
     Convert the lead to opportunity
     """
     self.opportunity([self])
     if request.is_xhr or request.is_json:
         return jsonify({
             'success':
             True,
             'message':
             'Good Work! This lead is an opportunity now.'
         })
     return redirect(request.referrer)