1 # -*- coding: utf-8 -*-
3 from datetime import datetime
7 from werkzeug.exceptions import Forbidden
10 from openerp import api, fields, models
11 from openerp import modules
12 from openerp import tools
13 from openerp import SUPERUSER_ID
14 from openerp.addons.website.models.website import slug
15 from openerp.exceptions import Warning
17 _logger = logging.getLogger(__name__)
20 class KarmaError(Forbidden):
21 """ Karma-related error, used for forum and posts. """
25 class Forum(models.Model):
27 _description = 'Forum'
28 _inherit = ['mail.thread', 'website.seo.metadata']
31 """ Add forum uuid for user email validation.
33 TDE TODO: move me somewhere else, auto_init ? """
34 forum_uuids = self.pool['ir.config_parameter'].search(cr, SUPERUSER_ID, [('key', '=', 'website_forum.uuid')])
36 self.pool['ir.config_parameter'].set_param(cr, SUPERUSER_ID, 'website_forum.uuid', str(uuid.uuid4()), ['base.group_system'])
39 def _get_default_faq(self):
40 fname = modules.get_module_resource('website_forum', 'data', 'forum_default_faq.html')
41 with open(fname, 'r') as f:
46 name = fields.Char('Forum Name', required=True, translate=True)
47 faq = fields.Html('Guidelines', default=_get_default_faq, translate=True)
48 description = fields.Html(
50 default='<p> This community is for professionals and enthusiasts of our products and services.'
51 'Share and discuss the best content and new marketing ideas,'
52 'build your professional profile and become a better marketer together.</p>')
53 default_order = fields.Selection([
54 ('create_date desc', 'Newest'),
55 ('write_date desc', 'Last Updated'),
56 ('vote_count desc', 'Most Voted'),
57 ('relevancy desc', 'Relevancy'),
58 ('child_count desc', 'Answered')],
59 string='Default Order', required=True, default='write_date desc')
60 relevancy_post_vote = fields.Float('First Relevancy Parameter', default=0.8)
61 relevancy_time_decay = fields.Float('Second Relevancy Parameter', default=1.8)
62 default_post_type = fields.Selection([
63 ('question', 'Question'),
64 ('discussion', 'Discussion'),
66 string='Default Post', required=True, default='question')
67 allow_question = fields.Boolean('Questions', help="Users can answer only once per question. Contributors can edit answers and mark the right ones.", default=True)
68 allow_discussion = fields.Boolean('Discussions', default=False)
69 allow_link = fields.Boolean('Links', help="When clicking on the post, it redirects to an external link", default=False)
71 karma_gen_question_new = fields.Integer(string='Asking a question', default=2)
72 karma_gen_question_upvote = fields.Integer(string='Question upvoted', default=5)
73 karma_gen_question_downvote = fields.Integer(string='Question downvoted', default=-2)
74 karma_gen_answer_upvote = fields.Integer(string='Answer upvoted', default=10)
75 karma_gen_answer_downvote = fields.Integer(string='Answer downvoted', default=-2)
76 karma_gen_answer_accept = fields.Integer(string='Accepting an answer', default=2)
77 karma_gen_answer_accepted = fields.Integer(string='Answer accepted', default=15)
78 karma_gen_answer_flagged = fields.Integer(string='Answer flagged', default=-100)
80 karma_ask = fields.Integer(string='Ask a new question', default=3)
81 karma_answer = fields.Integer(string='Answer a question', default=3)
82 karma_edit_own = fields.Integer(string='Edit its own posts', default=1)
83 karma_edit_all = fields.Integer(string='Edit all posts', default=300)
84 karma_close_own = fields.Integer(string='Close its own posts', default=100)
85 karma_close_all = fields.Integer(string='Close all posts', default=500)
86 karma_unlink_own = fields.Integer(string='Delete its own posts', default=500)
87 karma_unlink_all = fields.Integer(string='Delete all posts', default=1000)
88 karma_upvote = fields.Integer(string='Upvote', default=5)
89 karma_downvote = fields.Integer(string='Downvote', default=50)
90 karma_answer_accept_own = fields.Integer(string='Accept an answer on its own questions', default=20)
91 karma_answer_accept_all = fields.Integer(string='Accept an answers to all questions', default=500)
92 karma_editor_link_files = fields.Integer(string='Linking files (Editor)', default=20)
93 karma_editor_clickable_link = fields.Integer(string='Add clickable links (Editor)', default=20)
94 karma_comment_own = fields.Integer(string='Comment its own posts', default=1)
95 karma_comment_all = fields.Integer(string='Comment all posts', default=1)
96 karma_comment_convert_own = fields.Integer(string='Convert its own answers to comments and vice versa', default=50)
97 karma_comment_convert_all = fields.Integer(string='Convert all answers to answers and vice versa', default=500)
98 karma_comment_unlink_own = fields.Integer(string='Unlink its own comments', default=50)
99 karma_comment_unlink_all = fields.Integer(string='Unlinnk all comments', default=500)
100 karma_retag = fields.Integer(string='Change question tags', default=75)
101 karma_flag = fields.Integer(string='Flag a post as offensive', default=500)
102 karma_dofollow = fields.Integer(string='Disabled links', help='If the author has not enough karma, a nofollow attribute is added to links', default=500)
105 def create(self, values):
106 return super(Forum, self.with_context(mail_create_nolog=True)).create(values)
109 def _tag_to_write_vals(self, tags=''):
110 User = self.env['res.users']
111 Tag = self.env['forum.tag']
113 for tag in filter(None, tags.split(',')):
114 if tag.startswith('_'): # it's a new tag
115 # check that not arleady created meanwhile or maybe excluded by the limit on the search
116 tag_ids = Tag.search([('name', '=', tag[1:])])
118 post_tags.append((4, int(tag_ids[0])))
120 # check if user have Karma needed to create need tag
121 user = User.sudo().browse(self._uid)
122 if user.exists() and user.karma >= self.karma_retag:
123 post_tags.append((0, 0, {'name': tag[1:], 'forum_id': self.id}))
125 post_tags.append((4, int(tag)))
129 class Post(models.Model):
131 _description = 'Forum Post'
132 _inherit = ['mail.thread', 'website.seo.metadata']
133 _order = "is_correct DESC, vote_count DESC, write_date DESC"
135 name = fields.Char('Title')
136 forum_id = fields.Many2one('forum.forum', string='Forum', required=True)
137 content = fields.Html('Content')
138 content_link = fields.Char('URL', help="URL of Link Articles")
139 tag_ids = fields.Many2many('forum.tag', 'forum_tag_rel', 'forum_id', 'forum_tag_id', string='Tags')
140 state = fields.Selection([('active', 'Active'), ('close', 'Close'), ('offensive', 'Offensive')], string='Status', default='active')
141 views = fields.Integer('Number of Views', default=0)
142 active = fields.Boolean('Active', default=True)
143 post_type = fields.Selection([
144 ('question', 'Question'),
146 ('discussion', 'Discussion')],
147 string='Type', default='question')
148 website_message_ids = fields.One2many(
149 'mail.message', 'res_id',
150 domain=lambda self: ['&', ('model', '=', self._name), ('type', 'in', ['email', 'comment'])],
151 string='Post Messages', help="Comments on forum post",
154 create_date = fields.Datetime('Asked on', select=True, readonly=True)
155 create_uid = fields.Many2one('res.users', string='Created by', select=True, readonly=True)
156 write_date = fields.Datetime('Update on', select=True, readonly=True)
157 write_uid = fields.Many2one('res.users', string='Updated by', select=True, readonly=True)
158 relevancy = fields.Float('Relevancy', compute="_compute_relevancy", store=True)
161 @api.depends('vote_count', 'forum_id.relevancy_post_vote', 'forum_id.relevancy_time_decay')
162 def _compute_relevancy(self):
163 days = (datetime.today() - datetime.strptime(self.create_date, tools.DEFAULT_SERVER_DATETIME_FORMAT)).days
164 self.relevancy = math.copysign(1, self.vote_count) * (abs(self.vote_count - 1) ** self.forum_id.relevancy_post_vote / (days + 2) ** self.forum_id.relevancy_time_decay)
167 vote_ids = fields.One2many('forum.post.vote', 'post_id', string='Votes')
168 user_vote = fields.Integer('My Vote', compute='_get_user_vote')
169 vote_count = fields.Integer('Votes', compute='_get_vote_count', store=True)
172 def _get_user_vote(self):
173 votes = self.env['forum.post.vote'].search_read([('post_id', 'in', self._ids), ('user_id', '=', self._uid)], ['vote', 'post_id'])
174 mapped_vote = dict([(v['post_id'][0], v['vote']) for v in votes])
176 vote.user_vote = mapped_vote.get(vote.id, 0)
179 @api.depends('vote_ids')
180 def _get_vote_count(self):
181 read_group_res = self.env['forum.post.vote'].read_group([('post_id', 'in', self._ids)], ['post_id', 'vote'], ['post_id', 'vote'], lazy=False)
182 result = dict.fromkeys(self._ids, 0)
183 for data in read_group_res:
184 result[data['post_id'][0]] += data['__count'] * int(data['vote'])
186 post.vote_count = result[post.id]
189 favourite_ids = fields.Many2many('res.users', string='Favourite')
190 user_favourite = fields.Boolean('Is Favourite', compute='_get_user_favourite')
191 favourite_count = fields.Integer('Favorite Count', compute='_get_favorite_count', store=True)
194 def _get_user_favourite(self):
195 self.user_favourite = self._uid in self.favourite_ids.ids
198 @api.depends('favourite_ids')
199 def _get_favorite_count(self):
200 self.favourite_count = len(self.favourite_ids)
203 is_correct = fields.Boolean('Correct', help='Correct answer or answer accepted')
204 parent_id = fields.Many2one('forum.post', string='Question', ondelete='cascade')
205 self_reply = fields.Boolean('Reply to own question', compute='_is_self_reply', store=True)
206 child_ids = fields.One2many('forum.post', 'parent_id', string='Answers')
207 child_count = fields.Integer('Number of answers', compute='_get_child_count', store=True)
208 uid_has_answered = fields.Boolean('Has Answered', compute='_get_uid_has_answered')
209 has_validated_answer = fields.Boolean('Is answered', compute='_get_has_validated_answer', store=True)
212 @api.depends('create_uid', 'parent_id')
213 def _is_self_reply(self):
214 self_replies = self.search([('parent_id.create_uid', '=', self._uid)])
216 post.is_self_reply = post in self_replies
219 @api.depends('child_ids', 'website_message_ids')
220 def _get_child_count(self):
222 total = len(node.website_message_ids) + len(node.child_ids)
223 for child in node.child_ids:
224 total += process(child)
226 self.child_count = process(self)
229 def _get_uid_has_answered(self):
230 self.uid_has_answered = any(answer.create_uid.id == self._uid for answer in self.child_ids)
233 @api.depends('child_ids', 'is_correct')
234 def _get_has_validated_answer(self):
235 correct_posts = [ans.parent_id for ans in self.search([('parent_id', 'in', self._ids), ('is_correct', '=', True)])]
237 post.is_correct = post in correct_posts
240 closed_reason_id = fields.Many2one('forum.post.reason', string='Reason')
241 closed_uid = fields.Many2one('res.users', string='Closed by', select=1)
242 closed_date = fields.Datetime('Closed on', readonly=True)
243 # karma calculation and access
244 karma_accept = fields.Integer('Convert comment to answer', compute='_get_post_karma_rights')
245 karma_edit = fields.Integer('Karma to edit', compute='_get_post_karma_rights')
246 karma_close = fields.Integer('Karma to close', compute='_get_post_karma_rights')
247 karma_unlink = fields.Integer('Karma to unlink', compute='_get_post_karma_rights')
248 karma_comment = fields.Integer('Karma to comment', compute='_get_post_karma_rights')
249 karma_comment_convert = fields.Integer('Karma to convert comment to answer', compute='_get_post_karma_rights')
250 can_ask = fields.Boolean('Can Ask', compute='_get_post_karma_rights')
251 can_answer = fields.Boolean('Can Answer', compute='_get_post_karma_rights')
252 can_accept = fields.Boolean('Can Accept', compute='_get_post_karma_rights')
253 can_edit = fields.Boolean('Can Edit', compute='_get_post_karma_rights')
254 can_close = fields.Boolean('Can Close', compute='_get_post_karma_rights')
255 can_unlink = fields.Boolean('Can Unlink', compute='_get_post_karma_rights')
256 can_upvote = fields.Boolean('Can Upvote', compute='_get_post_karma_rights')
257 can_downvote = fields.Boolean('Can Downvote', compute='_get_post_karma_rights')
258 can_comment = fields.Boolean('Can Comment', compute='_get_post_karma_rights')
259 can_comment_convert = fields.Boolean('Can Convert to Comment', compute='_get_post_karma_rights')
262 def _get_post_karma_rights(self):
265 self.karma_accept = self.parent_id and self.parent_id.create_uid.id == self._uid and self.forum_id.karma_answer_accept_own or self.forum_id.karma_answer_accept_all
266 self.karma_edit = self.create_uid.id == self._uid and self.forum_id.karma_edit_own or self.forum_id.karma_edit_all
267 self.karma_close = self.create_uid.id == self._uid and self.forum_id.karma_close_own or self.forum_id.karma_close_all
268 self.karma_unlink = self.create_uid.id == self._uid and self.forum_id.karma_unlink_own or self.forum_id.karma_unlink_all
269 self.karma_comment = self.create_uid.id == self._uid and self.forum_id.karma_comment_own or self.forum_id.karma_comment_all
270 self.karma_comment_convert = self.create_uid.id == self._uid and self.forum_id.karma_comment_convert_own or self.forum_id.karma_comment_convert_all
272 self.can_ask = user.karma >= self.forum_id.karma_ask
273 self.can_answer = user.karma >= self.forum_id.karma_answer
274 self.can_accept = user.karma >= self.karma_accept
275 self.can_edit = user.karma >= self.karma_edit
276 self.can_close = user.karma >= self.karma_close
277 self.can_unlink = user.karma >= self.karma_unlink
278 self.can_upvote = user.karma >= self.forum_id.karma_upvote
279 self.can_downvote = user.karma >= self.forum_id.karma_downvote
280 self.can_comment = user.karma >= self.karma_comment
281 self.can_comment_convert = user.karma >= self.karma_comment_convert
284 def create(self, vals):
285 post = super(Post, self.with_context(mail_create_nolog=True)).create(vals)
286 # deleted or closed questions
287 if post.parent_id and (post.parent_id.state == 'close' or post.parent_id.active is False):
288 raise Warning(_('Posting answer on a [Deleted] or [Closed] question is not possible'))
290 if not post.parent_id and not post.can_ask:
291 raise KarmaError('Not enough karma to create a new question')
292 elif post.parent_id and not post.can_answer:
293 raise KarmaError('Not enough karma to answer to a question')
294 # messaging and chatter
295 base_url = self.env['ir.config_parameter'].get_param('web.base.url')
298 '<p>A new answer for <i>%s</i> has been posted. <a href="%s/forum/%s/question/%s">Click here to access the post.</a></p>' %
299 (post.parent_id.name, base_url, slug(post.parent_id.forum_id), slug(post.parent_id))
301 post.parent_id.message_post(subject=_('Re: %s') % post.parent_id.name, body=body, subtype='website_forum.mt_answer_new')
304 '<p>A new question <i>%s</i> has been asked on %s. <a href="%s/forum/%s/question/%s">Click here to access the question.</a></p>' %
305 (post.name, post.forum_id.name, base_url, slug(post.forum_id), slug(post))
307 post.message_post(subject=post.name, body=body, subtype='website_forum.mt_question_new')
308 self.env.user.sudo().add_karma(post.forum_id.karma_gen_question_new)
312 def write(self, vals):
314 if vals['state'] in ['active', 'close'] and any(not post.can_close for post in self):
315 raise KarmaError('Not enough karma to close or reopen a post.')
317 if any(not post.can_unlink for post in self):
318 raise KarmaError('Not enough karma to delete or reactivate a post')
319 if 'is_correct' in vals:
320 if any(not post.can_accept for post in self):
321 raise KarmaError('Not enough karma to accept or refuse an answer')
322 # update karma except for self-acceptance
323 mult = 1 if vals['is_correct'] else -1
325 if vals['is_correct'] != post.is_correct and post.create_uid.id != self._uid:
326 post.create_uid.sudo().add_karma(post.forum_id.karma_gen_answer_accepted * mult)
327 self.env.user.sudo().add_karma(post.forum_id.karma_gen_answer_accept * mult)
328 if any(key not in ['state', 'active', 'is_correct', 'closed_uid', 'closed_date', 'closed_reason_id'] for key in vals.keys()) and any(not post.can_edit for post in self):
329 raise KarmaError('Not enough karma to edit a post.')
331 res = super(Post, self).write(vals)
332 # if post content modify, notify followers
333 if 'content' in vals or 'name' in vals:
336 body, subtype = _('Answer Edited'), 'website_forum.mt_answer_edit'
337 obj_id = post.parent_id
339 body, subtype = _('Question Edited'), 'website_forum.mt_question_edit'
341 obj_id.message_post(body=body, subtype=subtype)
346 if any(post.parent_id or post.state != 'close' for post in self):
349 reason_offensive = self.env.ref('website_forum.reason_7')
350 reason_spam = self.env.ref('website_forum.reason_8')
352 if post.closed_reason_id in (reason_offensive, reason_spam):
353 _logger.info('Upvoting user <%s>, reopening spam/offensive question',
355 # TODO: in master, consider making this a tunable karma parameter
356 post.create_uid.sudo().add_karma(post.forum_id.karma_gen_question_downvote * -5)
358 self.sudo().write({'state': 'active'})
361 def close(self, reason_id):
362 if any(post.parent_id for post in self):
365 reason_offensive = self.env.ref('website_forum.reason_7').id
366 reason_spam = self.env.ref('website_forum.reason_8').id
367 if reason_id in (reason_offensive, reason_spam):
369 _logger.info('Downvoting user <%s> for posting spam/offensive contents',
371 # TODO: in master, consider making this a tunable karma parameter
372 post.create_uid.sudo().add_karma(post.forum_id.karma_gen_question_downvote * 5)
376 'closed_uid': self._uid,
377 'closed_date': datetime.today().strftime(tools.DEFAULT_SERVER_DATETIME_FORMAT),
378 'closed_reason_id': reason_id,
384 if any(not post.can_unlink for post in self):
385 raise KarmaError('Not enough karma to unlink a post')
386 # if unlinking an answer with accepted answer: remove provided karma
389 post.create_uid.sudo().add_karma(post.forum_id.karma_gen_answer_accepted * -1)
390 self.env.user.sudo().add_karma(post.forum_id.karma_gen_answer_accepted * -1)
391 return super(Post, self).unlink()
394 def vote(self, upvote=True):
395 Vote = self.env['forum.post.vote']
396 vote_ids = Vote.search([('post_id', 'in', self._ids), ('user_id', '=', self._uid)])
397 new_vote = '1' if upvote else '-1'
398 voted_forum_ids = set()
400 for vote in vote_ids:
402 new_vote = '0' if vote.vote == '-1' else '1'
404 new_vote = '0' if vote.vote == '1' else '-1'
406 voted_forum_ids.add(vote.post_id.id)
407 for post_id in set(self._ids) - voted_forum_ids:
408 for post_id in self._ids:
409 Vote.create({'post_id': post_id, 'vote': new_vote})
410 return {'vote_count': self.vote_count, 'user_vote': new_vote}
413 def convert_answer_to_comment(self):
414 """ Tools to convert an answer (forum.post) to a comment (mail.message).
415 The original post is unlinked and a new comment is posted on the question
416 using the post create_uid as the comment's author. """
417 if not self.parent_id:
420 # karma-based action check: use the post field that computed own/all value
421 if not self.can_comment_convert:
422 raise KarmaError('Not enough karma to convert an answer to a comment')
425 question = self.parent_id
427 'author_id': self.create_uid.partner_id.id,
428 'body': tools.html2plaintext(self.content),
430 'subtype': 'mail.mt_comment',
431 'date': self.create_date,
433 new_message = self.browse(question.id).with_context(mail_create_nosubcribe=True).message_post(**values)
435 # unlink the original answer, using SUPERUSER_ID to avoid karma issues
441 def convert_comment_to_answer(self, message_id, default=None):
442 """ Tool to convert a comment (mail.message) into an answer (forum.post).
443 The original comment is unlinked and a new answer from the comment's author
444 is created. Nothing is done if the comment's author already answered the
446 comment = self.env['mail.message'].sudo().browse(message_id)
447 post = self.browse(comment.res_id)
448 if not comment.author_id or not comment.author_id.user_ids: # only comment posted by users can be converted
451 # karma-based action check: must check the message's author to know if own / all
452 karma_convert = comment.author_id.id == self.env.user.partner_id.id and post.forum_id.karma_comment_convert_own or post.forum_id.karma_comment_convert_all
453 can_convert = self.env.user.karma >= karma_convert
455 raise KarmaError('Not enough karma to convert a comment to an answer')
457 # check the message's author has not already an answer
458 question = post.parent_id if post.parent_id else post
459 post_create_uid = comment.author_id.user_ids[0]
460 if any(answer.create_uid.id == post_create_uid.id for answer in question.child_ids):
463 # create the new post
465 'forum_id': question.forum_id.id,
466 'content': comment.body,
467 'parent_id': question.id,
469 # done with the author user to have create_uid correctly set
470 new_post = self.sudo(post_create_uid.id).create(post_values)
478 def unlink_comment(self, message_id):
480 comment = self.env['mail.message'].sudo().browse(message_id)
481 if not comment.model == 'forum.post' or not comment.res_id == self.id:
483 # karma-based action check: must check the message's author to know if own or all
484 karma_unlink = comment.author_id.id == user.partner_id.id and self.forum_id.karma_comment_unlink_own or self.forum_id.karma_comment_unlink_all
485 can_unlink = user.karma >= karma_unlink
487 raise KarmaError('Not enough karma to unlink a comment')
488 return comment.unlink()
491 def set_viewed(self):
492 self._cr.execute("""UPDATE forum_post SET views = views+1 WHERE id IN %s""", (self._ids,))
496 def _get_access_link(self, mail, partner):
497 post = self.browse(mail.res_id)
498 res_id = post.parent_id and "%s#answer-%s" % (post.parent_id.id, post.id) or post.id
499 return "/forum/%s/question/%s" % (post.forum_id.id, res_id)
501 @api.cr_uid_ids_context
502 def message_post(self, cr, uid, thread_id, type='notification', subtype=None, context=None, **kwargs):
503 if thread_id and type == 'comment': # user comments have a restriction on karma
504 if isinstance(thread_id, (list, tuple)):
505 post_id = thread_id[0]
508 post = self.browse(cr, uid, post_id, context=context)
509 # TDE FIXME: trigger browse because otherwise the function field is not compted - check with RCO
510 tmp1, tmp2 = post.karma_comment, post.can_comment
511 user = self.pool['res.users'].browse(cr, uid, uid)
514 if not post.can_comment:
515 raise KarmaError('Not enough karma to comment')
516 return super(Post, self).message_post(cr, uid, thread_id, type=type, subtype=subtype, context=context, **kwargs)
519 class PostReason(models.Model):
520 _name = "forum.post.reason"
521 _description = "Post Closing Reason"
524 name = fields.Char(string='Closing Reason', required=True, translate=True)
527 class Vote(models.Model):
528 _name = 'forum.post.vote'
529 _description = 'Vote'
531 post_id = fields.Many2one('forum.post', string='Post', ondelete='cascade', required=True)
532 user_id = fields.Many2one('res.users', string='User', required=True, default=lambda self: self._uid)
533 vote = fields.Selection([('1', '1'), ('-1', '-1'), ('0', '0')], string='Vote', required=True, default='1')
534 create_date = fields.Datetime('Create Date', select=True, readonly=True)
535 forum_id = fields.Many2one('forum.forum', string='Forum', related="post_id.forum_id", store=True)
536 recipient_id = fields.Many2one('res.users', string='To', related="post_id.create_uid", store=True)
538 def _get_karma_value(self, old_vote, new_vote, up_karma, down_karma):
540 '-1': {'-1': 0, '0': -1 * down_karma, '1': -1 * down_karma + up_karma},
541 '0': {'-1': 1 * down_karma, '0': 0, '1': up_karma},
542 '1': {'-1': -1 * up_karma + down_karma, '0': -1 * up_karma, '1': 0}
544 return _karma_upd[old_vote][new_vote]
547 def create(self, vals):
548 vote = super(Vote, self).create(vals)
551 if vote.user_id.id == vote.post_id.create_uid.id:
552 raise Warning('Not allowed to vote for its own post')
554 if vote.vote == '1' and not vote.post_id.can_upvote:
555 raise KarmaError('Not enough karma to upvote.')
556 elif vote.vote == '-1' and not vote.post_id.can_downvote:
557 raise KarmaError('Not enough karma to downvote.')
559 if vote.post_id.parent_id:
560 karma_value = self._get_karma_value('0', vote.vote, vote.forum_id.karma_gen_answer_upvote, vote.forum_id.karma_gen_answer_downvote)
562 karma_value = self._get_karma_value('0', vote.vote, vote.forum_id.karma_gen_question_upvote, vote.forum_id.karma_gen_question_downvote)
563 vote.recipient_id.sudo().add_karma(karma_value)
567 def write(self, values):
571 if vote.user_id.id == vote.post_id.create_uid.id:
572 raise Warning('Not allowed to vote for its own post')
574 if (values['vote'] == '1' or vote.vote == '-1' and values['vote'] == '0') and not vote.post_id.can_upvote:
575 raise KarmaError('Not enough karma to upvote.')
576 elif (values['vote'] == '-1' or vote.vote == '1' and values['vote'] == '0') and not vote.post_id.can_downvote:
577 raise KarmaError('Not enough karma to downvote.')
580 if vote.post_id.parent_id:
581 karma_value = self._get_karma_value(vote.vote, values['vote'], vote.forum_id.karma_gen_answer_upvote, vote.forum_id.karma_gen_answer_downvote)
583 karma_value = self._get_karma_value(vote.vote, values['vote'], vote.forum_id.karma_gen_question_upvote, vote.forum_id.karma_gen_question_downvote)
584 vote.recipient_id.sudo().add_karma(karma_value)
585 res = super(Vote, self).write(values)
589 class Tags(models.Model):
591 _description = "Forum Tag"
592 _inherit = ['website.seo.metadata']
594 name = fields.Char('Name', required=True)
595 create_uid = fields.Many2one('res.users', string='Created by', readonly=True)
596 forum_id = fields.Many2one('forum.forum', string='Forum', required=True)
597 post_ids = fields.Many2many('forum.post', 'forum_tag_rel', 'forum_tag_id', 'forum_id', string='Posts')
598 posts_count = fields.Integer('Number of Posts', compute='_get_posts_count', store=True)
601 @api.depends("post_ids.tag_ids")
602 def _get_posts_count(self):
604 tag.posts_count = len(tag.post_ids)