[ADD] add functionality to select hiostory when editing question or answer.
authorTurkesh Patel (Open ERP) <tpa@tinyerp.com>
Mon, 31 Mar 2014 12:32:43 +0000 (18:02 +0530)
committerTurkesh Patel (Open ERP) <tpa@tinyerp.com>
Mon, 31 Mar 2014 12:32:43 +0000 (18:02 +0530)
bzr revid: tpa@tinyerp.com-20140331123243-ig3h0bpmyufsk874

1  2 
addons/website_forum/controllers/main.py
addons/website_forum/models/forum.py
addons/website_forum/static/src/js/website_forum.js
addons/website_forum/views/website_forum.xml

@@@ -341,18 -341,18 +341,26 @@@ class website_forum(http.Controller)
              }, context=create_context)
          return werkzeug.utils.redirect("/forum/%s/question/%s" % (slug(forum),post_id))
  
--    @http.route(['/forum/<model("website.forum"):forum>/question/<model("website.forum.post"):post>/editanswer'], type='http', auth="user", website=True, multilang=True)
--    def edit_answer(self, forum, post, **kwargs):
++    @http.route(['/forum/<model("website.forum"):forum>/question/<model("website.forum.post"):post>/editanswer',
++                 '/forum/<model("website.forum"):forum>/answer/<model("website.forum.post"):post>/edit/<model("website.forum.post"):answer>']
++                , type='http', auth="user", website=True, multilang=True)
++    def edit_answer(self, forum, post, answer='', **kwargs):
          cr, uid, context = request.cr, request.uid, request.context
          request.registry['res.users'].write(cr, SUPERUSER_ID, uid, {'forum': True}, context=context)
--        for answer in post.child_ids:
--            if answer.user_id.id == request.uid:
--                post_answer = answer
++        for record in post.child_ids:
++            if record.user_id.id == request.uid and not answer:
++                answer = record
++
++        history_obj = request.registry['website.forum.post.history']
++        history_ids = history_obj.search(cr, uid, [('post_id','=', answer.id)], order = "id desc", context=context)
++        post_history = history_obj.browse(cr, uid, history_ids, context=context)
++
          values = {
              'post': post,
--            'post_answer': post_answer,
++            'post_answer': answer,
              'notifications': self._get_notifications(),
              'forum': forum,
++            'post_history': post_history,
              'searches': kwargs
          }
          return request.website.render("website_forum.edit_answer", values)
          request.registry['res.users'].write(cr, SUPERUSER_ID, uid, {'forum': True}, context=context)
          answer_id = int(post.get('answer_id'))
          new_question_id = request.registry['website.forum.post'].write( cr, uid, [answer_id], {
--                'content': post.get('answer_content'),
++                'content': post.get('content'),
              }, context=context)
          return werkzeug.utils.redirect("/forum/%s/question/%s" % (slug(forum),post.get('post_id')))
  
  
      @http.route('/forum/<model("website.forum"):forum>/edit/question/<model("website.forum.post"):post>', type='http', auth="user", multilang=True, website=True)
      def edit_question(self, forum, post, **kwarg):
 -        post_history_obj = request.registry['website.forum.post.history'];
++        cr, uid, context = request.cr, request.uid, request.context
++        history_obj = request.registry['website.forum.post.history']
++        history_ids = history_obj.search(cr, uid, [('post_id','=', post.id)], order = "id desc", context=context)
++        post_history = history_obj.browse(cr, uid, history_ids, context=context)
++
          tags = ""
          for tag_name in post.tags:
              tags += tag_name.name + ","
              'forum': forum,
              'searches': kwarg,
              'notifications': self._get_notifications(),
 -            'history': post_history,
++            'post_history': post_history,
          }
          return request.website.render("website_forum.edit_question", values)
  
++    @http.route('/forum/selecthistory', type='json', auth="user", multilang=True, methods=['POST'], website=True)
++    def post_history(self, **kwarg):
++        cr, uid, context = request.cr, request.uid, request.context
++        post_history = request.registry['website.forum.post.history'].browse(cr, uid, int(kwarg.get('history_id')), context=context)
++        tags = ""
++        for tag_name in post_history.tags:
++            tags += tag_name.name + ","
++        data = {
++            'name': post_history.post_name,
++            'content': post_history.content,
++            'tags': tags,
++        }
++        return data
++
      @http.route('/forum/<model("website.forum"):forum>/question/savequestion/', type='http', auth="user", multilang=True, methods=['POST'], website=True)
      def save_edited_question(self, forum, **post):
          cr, uid, context = request.cr, request.uid, request.context
                  question_tags.append((0,0,{'name' : tag,'forum_id' : forum.id}))
  
          request.registry['website.forum.post'].write(cr, uid, [int(post.get('post_id'))], {
--            'content': post.get('answer_content'),
++            'content': post.get('content'),
              'name': post.get('question_name'),
              'tags' : question_tags,
          }, context=context)
          return werkzeug.utils.redirect("/forum/%s/question/%s" % (slug(forum),post.get('post_id')))
  
--    @http.route('/forum/<model("website.forum"):forum>/answer/<model("website.forum.post"):post>/edit/<model("website.forum.post"):answer>', type='http', auth="user", multilang=True, website=True)
--    def edit_ans(self, forum, post, answer, **kwarg):
--        values = {
--            'post': post,
--            'post_answer': answer,
--            'forum': forum,
--            'searches': kwarg,
--            'notifications': self._get_notifications(),
--        }
--        return request.website.render("website_forum.edit_answer", values)
--
      @http.route('/forum/correct_answer/', type='json', auth="user", multilang=True, methods=['POST'], website=True)
      def correct_answer(self, **kwarg):
          cr, uid, context = request.cr, request.uid, request.context
          post_ids.append(post.id)
          request.registry['website.forum.post'].message_unsubscribe( cr, uid, post_ids, [partner_id], context=context)
          return werkzeug.utils.redirect("/forum/%s/question/%s" % (slug(forum),post.id))
 -    @http.route('/forum/change_question/', type='json', auth="user", multilang=True, methods=['POST'], website=True)
 -    def correct_answer(self, **kwarg):
 -        cr, uid, context = request.cr, request.uid, request.context
 -        return True
 -
  import re
  
  import openerp
++from openerp import tools
  from openerp import SUPERUSER_ID
  from openerp.osv import osv, fields
  from openerp.tools.translate import _
++from datetime import date, datetime
  
  from openerp.addons.website.models.website import slug
  
@@@ -198,16 -198,16 +200,19 @@@ class Post(osv.Model)
          'active': True,
      }
  
--    def create_history(self, cr, uid, ids, vals, context=None):
++    def create_history(self, cr, uid, ids, context=None):
          hist_obj = self.pool['website.forum.post.history']
          for post in self.browse(cr, uid, ids, context=context):
++            history_count = hist_obj.search(cr, uid, [('post_id','=', post.id)], count=True, context=context)
++            date = datetime.today().strftime(tools.DEFAULT_SERVER_DATETIME_FORMAT)
++            name = "No.%s Revision" %(history_count+1) if history_count else "initial version"
              hist_obj.create(cr, uid, {
                  'post_id': post.id,
                  'content': post.content,
--                'name': post.name,
++                'name': '%s - (%s) %s' % (history_count+1, date, name),
++                'post_name': post.name,
                  'tags': [(6,0, [x.id for x in post.tags])],
--                'date': post.write_date or post.create_date,
--                'user_id': post.write_uid and post.write_uid.id or post.user_id.id
++                'user_id': post.write_uid and post.write_uid.id or post.user_id.id,
              }, context=context)
  
      def create(self, cr, uid, vals, context=None):
              #add 2 karma to user when asks question.
              self.pool['res.users'].write(cr, SUPERUSER_ID, [vals.get('user_id')], {'karma': 2}, context=context)
          post_id = super(Post, self).create(cr, uid, vals, context=create_context)
++        self.create_history(cr, uid, [post_id], context=context)
          self.message_post(cr, uid, [post_id], body=_(body), subtype=subtype, context=context)
          return post_id
  
      def write(self, cr, uid, ids, vals, context=None):
-         self.create_history(cr, uid, ids, vals, context=context)
++        super(Post, self).write(cr, uid, ids, vals, context=context)
          #NOTE: to avoid message post on write of last comment time
          if not vals.get('message_last_post'):
 -            self.create_history(cr, uid, ids, vals, context=context)
++            self.create_history(cr, uid, ids, context=context)
              for post in self.browse(cr, uid, ids, context=context):
                  body, subtype = "Edited question", "website_forum.mt_question_edit"
                  if post.parent_id:
              elif vals.get('correct') == False:
                  value = -15 
              self.pool['res.users'].write(cr, SUPERUSER_ID, [post.user_id.id], {'karma': value}, context=context)
--        return super(Post, self).write(cr, uid, ids, vals, context=context)
++        return True
  
  class PostStatistics(osv.Model):
      _name = "website.forum.post.statistics"
@@@ -310,11 -310,11 +317,11 @@@ class PostHistory(osv.Model)
      _description = 'Post History'
      _inherit = ['website.seo.metadata']
      _columns = {
--        'name': fields.char('Post Title'),
++        'name': fields.char('History Title'),
          'post_id': fields.many2one('website.forum.post', 'Post', ondelete='cascade'),
--        'date': fields.datetime('Created on', select=True, readonly=True),
++        'post_name': fields.char('Post Name'),
++        'content': fields.text('Content'),
          'user_id': fields.many2one('res.users', 'Created by', select=True, readonly=True),
--        'content': fields.html('Contents', help='Automatically sanitized HTML contents'),
          'tags': fields.many2many('website.forum.tag', 'post_tag_rel', 'post_id', 'post_tag_id', 'Tag'),
      }
  
@@@ -95,25 -95,34 +95,43 @@@ $(document).ready(function () 
      });
  
      if($('input.load_tags').length){
--          var previous_tags = $("input.load_tags").val();
--            $("input.load_tags").val("");
--            $("input.load_tags").textext({
--                plugins: 'tags focus autocomplete ajax',
--                tagsItems: previous_tags.split(","),
--                //Note: The following list of keyboard keys is added. All entries are default except {32 : 'whitespace!'}.
--                keys: {8: 'backspace', 9: 'tab', 13: 'enter!', 27: 'escape!', 37: 'left', 38: 'up!', 39: 'right',
--                        40: 'down!', 46: 'delete', 108: 'numpadEnter', 32: 'whitespace!'},
--                ajax: {
--                    url: '/forum/get_tags',
--                    dataType: 'json',
--                    cacheResults: true
--                }
--            });
--            // Note: Adding event handler of whitespaceKeyDown event.
--            $("input.load_tags").bind("whitespaceKeyDown",function () {
--                $(this).textext()[0].tags().addTags([ $(this).val() ]);
--                $(this).val("");
--        });
++        var tags = $("input.load_tags").val();
++        $("input.load_tags").val("");
++        set_tags(tags);
      };
  
 -    $('.change_question').change(function (ev) {
++    function set_tags(tags) {
++        $("input.load_tags").textext({
++            plugins: 'tags focus autocomplete ajax',
++            tagsItems: tags.split(","),
++            //Note: The following list of keyboard keys is added. All entries are default except {32 : 'whitespace!'}.
++            keys: {8: 'backspace', 9: 'tab', 13: 'enter!', 27: 'escape!', 37: 'left', 38: 'up!', 39: 'right',
++                40: 'down!', 46: 'delete', 108: 'numpadEnter', 32: 'whitespace!'},
++            ajax: {
++                url: '/forum/get_tags',
++                dataType: 'json',
++                cacheResults: true
++            }
++        });
++        // Note: Adding event handler of whitespaceKeyDown event.
++        $("input.load_tags").bind("whitespaceKeyDown",function () {
++            $(this).textext()[0].tags().addTags([ $(this).val() ]);
++            $(this).val("");
++        });
++    }
++
++    $('.post_history').change(function (ev) {
+         var $option = $(ev.currentTarget);
 -        openerp.jsonRpc("/forum/change_question/", 'call', {
 -            'option': $option.attr("id")})
++        openerp.jsonRpc("/forum/selecthistory", 'call', {
++            'history_id': $option.attr("value")})
+             .then(function (data) {
++                var $input = $('<input type="text" name="question_tag" class="form-control col-md-9 load_tags" placeholder="Tags"/>')
++                $option.parent().find(".text-core").replaceWith($input);
++                set_tags(data['tags']);
++                $option.parent().find("#question_name").attr('value', data['name']);
++                CKEDITOR.instances['content'].setData(data['content'])
+             })
+         return true;
+     });
  });
              <t t-call="website_forum.header">
                  <h3>Edit question</h3>
                  <form t-attf-action="/forum/#{ slug(forum) }/question/savequestion/" method="post" role="form" class="tag_text">
-                     <input type="text" name="question_name" required="True" t-attf-value="#{post.name or ''}"
 -                    <select class="form-control change_question" id="change_que">
 -                        <t t-foreach="history" t-as="history_post">
 -                            <option t-att-value="history_post.id"><t t-esc="history_post.name"/></option>
++                    <select class="form-control post_history">
++                        <t t-foreach="post_history" t-as="history">
++                            <option t-att-value="history.id"><t t-esc="history.name"/></option>
+                         </t>
+                      </select>
 -                    <input type="text" name="question_name" required="True" t-attf-value="#{post.name or ''}"
++                    <input type="text" name="question_name" id="question_name" required="True" t-attf-value="#{post.name or ''}"
                          class="form-control" placeholder="Edit your Question"/>
                      <h5 class="mt20">Please enter a descriptive question (should finish by a '?')</h5>
--                    <textarea name="answer_content" required="True" value="content" class="form-control">
++                    <textarea name="content" required="True"  class="form-control">
                          <t t-esc="post.content"/>
                      </textarea>
                      <br/>
                      <button class="btn btn-primary btn-lg">Save</button>
                  </form>
                  <script type="text/javascript">
--                    CKEDITOR.replace("answer_content");
++                    CKEDITOR.replace("content");
                  </script>
              </t>
          </template>
              <t t-call="website_forum.header">
                  <h3>Edit answer</h3>
                  <form t-attf-action="/forum/#{ slug(forum) }/question/saveanswer/" method="post" role="form">
--                    <textarea name="answer_content" required="True" value="content" class="form-control">
++                    <select class="form-control post_history">
++                        <t t-foreach="post_history" t-as="history">
++                            <option t-att-value="history.id"><t t-esc="history.name"/></option>
++                        </t>
++                    </select>
++                    <textarea name="content" required="True" value="content" class="form-control">
                          <t t-esc="post_answer.content"/>
                      </textarea>
                      <input name="post_id" t-att-value="post.id" type="hidden"/>
                      <button class="btn btn-primary btn-lg">Save</button>
                  </form>
                  <script type="text/javascript">
--                    CKEDITOR.replace("answer_content");
++                    CKEDITOR.replace("content");
                  </script>
              </t>
          </template>