You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

468 lines
20 KiB

9 years ago
  1. # Copyright 2016 Ildar Nasyrov <https://it-projects.info/team/iledarn>
  2. # Copyright 2016-2018 Ivan Yelizariev <https://it-projects.info/team/yelizariev>
  3. # Copyright 2016 intero-chz <https://github.com/intero-chz>
  4. # Copyright 2016 manawi <https://github.com/manawi>
  5. # Copyright 2018 Kolushov Alexandr <https://it-projects.info/team/KolushovAlexandr>
  6. # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html).
  7. from odoo import api
  8. from odoo import fields
  9. from odoo import models
  10. from odoo.tools import email_split
  11. from odoo.tools.translate import _
  12. from odoo import exceptions
  13. class Wizard(models.TransientModel):
  14. _name = 'mail_move_message.wizard'
  15. @api.model
  16. def _model_selection(self):
  17. selection = []
  18. config_parameters = self.env['ir.config_parameter']
  19. model_names = config_parameters.sudo().get_param('mail_relocation_models')
  20. model_names = model_names.split(',') if model_names else []
  21. if 'default_message_id' in self.env.context:
  22. message = self.env['mail.message'].browse(self.env.context['default_message_id'])
  23. if message.model and message.model not in model_names:
  24. model_names.append(message.model)
  25. if message.moved_from_model and message.moved_from_model not in model_names:
  26. model_names.append(message.moved_from_model)
  27. if model_names:
  28. selection = [(m.model, m.display_name) for m in self.env['ir.model'].search([('model', 'in', model_names)])]
  29. return selection
  30. @api.model
  31. def default_get(self, fields_list):
  32. res = super(Wizard, self).default_get(fields_list)
  33. available_models = self._model_selection()
  34. if len(available_models):
  35. record = self.env[available_models[0][0]].search([], limit=1)
  36. res['model_record'] = len(record) and (available_models[0][0] + ',' + str(record.id)) or False
  37. if 'message_id' in res:
  38. message = self.env['mail.message'].browse(res['message_id'])
  39. email_from = message.email_from
  40. parts = email_split(email_from.replace(' ', ','))
  41. if parts:
  42. email = parts[0]
  43. name = email_from.find(email) != -1 and email_from[:email_from.index(email)].replace('"', '').replace('<', '').strip() or email_from
  44. else:
  45. name, email = email_from
  46. res['message_name_from'] = name
  47. res['message_email_from'] = email
  48. res['partner_id'] = message.author_id.id
  49. if message.author_id and self.env.uid not in [u.id for u in message.author_id.user_ids]:
  50. res['filter_by_partner'] = True
  51. if message.author_id and res.get('model'):
  52. res_id = self.env[res['model']].search([], order='id desc', limit=1)
  53. if res_id:
  54. res['res_id'] = res_id[0].id
  55. config_parameters = self.env['ir.config_parameter']
  56. res['move_followers'] = config_parameters.sudo().get_param('mail_relocation_move_followers')
  57. res['uid'] = self.env.uid
  58. return res
  59. message_id = fields.Many2one('mail.message', string='Message')
  60. message_body = fields.Html(related='message_id.body', string='Message to move', readonly=True)
  61. message_from = fields.Char(related='message_id.email_from', string='From', readonly=True)
  62. message_subject = fields.Char(related='message_id.subject', string='Subject', readonly=True)
  63. message_moved_by_message_id = fields.Many2one('mail.message', related='message_id.moved_by_message_id', string='Moved with', readonly=True)
  64. message_moved_by_user_id = fields.Many2one('res.users', related='message_id.moved_by_user_id', string='Moved by', readonly=True)
  65. message_is_moved = fields.Boolean(string='Is Moved', related='message_id.is_moved', readonly=True)
  66. parent_id = fields.Many2one('mail.message', string='Search by name', )
  67. model_record = fields.Reference(selection="_model_selection", string='Record')
  68. model = fields.Char(compute="_compute_model_res_id", string='Model')
  69. res_id = fields.Integer(compute="_compute_model_res_id", string='Record')
  70. can_move = fields.Boolean('Can move', compute='_compute_get_can_move')
  71. move_back = fields.Boolean('MOVE TO ORIGIN', help='Move message and submessages to original place')
  72. partner_id = fields.Many2one('res.partner', string='Author')
  73. filter_by_partner = fields.Boolean('Filter Records by partner')
  74. message_email_from = fields.Char()
  75. message_name_from = fields.Char()
  76. # FIXME message_to_read should be True even if current message or any his childs are unread
  77. message_to_read = fields.Boolean(compute='_compute_is_read', string="Unread message",
  78. help="Service field shows that this message were unread when moved")
  79. uid = fields.Integer()
  80. move_followers = fields.Boolean(
  81. 'Move Followers',
  82. help="Add followers of current record to a new record.\n"
  83. "You must use this option, if new record has restricted access.\n"
  84. "You can change default value for this option at Settings/System Parameters")
  85. @api.multi
  86. @api.depends('model_record')
  87. def _compute_model_res_id(self):
  88. for rec in self:
  89. rec.model = rec.model_record and rec.model_record._name or False
  90. rec.res_id = rec.model_record and rec.model_record.id or False
  91. @api.depends('message_id')
  92. @api.multi
  93. def _compute_get_can_move(self):
  94. for r in self:
  95. r.get_can_move_one()
  96. @api.multi
  97. def _compute_is_read(self):
  98. messages = self.env['mail.message'].sudo().browse(self.message_id.all_child_ids.ids + [self.message_id.id])
  99. self.message_to_read = True in [m.needaction for m in messages]
  100. @api.multi
  101. def get_can_move_one(self):
  102. self.ensure_one()
  103. # message was not moved before OR message is a top message of previous move
  104. self.can_move = not self.message_id.moved_by_message_id or self.message_id.moved_by_message_id.id == self.message_id.id
  105. @api.onchange('move_back')
  106. def on_change_move_back(self):
  107. if not self.move_back:
  108. return
  109. self.parent_id = self.message_id.moved_from_parent_id
  110. message = self.message_id
  111. if message.is_moved:
  112. self.model_record = self.env[message.moved_from_model].browse(message.moved_from_res_id)
  113. @api.onchange('parent_id', 'model_record')
  114. def update_move_back(self):
  115. model = self.message_id.moved_from_model
  116. self.move_back = self.parent_id == self.message_id.moved_from_parent_id \
  117. and self.res_id == self.message_id.moved_from_res_id \
  118. and (self.model == model or (not self.model and not model))
  119. @api.onchange('parent_id')
  120. def on_change_parent_id(self):
  121. if self.parent_id and self.parent_id.model:
  122. self.model = self.parent_id.model
  123. self.res_id = self.parent_id.res_id
  124. else:
  125. self.model = None
  126. self.res_id = None
  127. @api.onchange('model', 'filter_by_partner', 'partner_id')
  128. def on_change_partner(self):
  129. domain = {'res_id': [('id', '!=', self.message_id.res_id)]}
  130. if self.model and self.filter_by_partner and self.partner_id:
  131. fields = self.env[self.model].fields_get(False)
  132. contact_field = False
  133. for n, f in fields.items():
  134. if f['type'] == 'many2one' and f['relation'] == 'res.partner':
  135. contact_field = n
  136. break
  137. if contact_field:
  138. domain['res_id'].append((contact_field, '=', self.partner_id.id))
  139. if self.model:
  140. res_id = self.env[self.model].search(domain['res_id'], order='id desc', limit=1)
  141. self.res_id = res_id and res_id[0].id
  142. else:
  143. self.res_id = None
  144. return {'domain': domain}
  145. @api.multi
  146. def check_access(self):
  147. for r in self:
  148. r.check_access_one()
  149. @api.multi
  150. def check_access_one(self):
  151. self.ensure_one()
  152. operation = 'write'
  153. if not (self.model and self.res_id):
  154. return True
  155. model_obj = self.env[self.model]
  156. mids = model_obj.browse(self.res_id).exists()
  157. if hasattr(model_obj, 'check_mail_message_access'):
  158. model_obj.check_mail_message_access(mids.ids, operation)
  159. else:
  160. self.env['mail.thread'].check_mail_message_access(mids.ids, operation, model_name=self.model)
  161. @api.multi
  162. def open_moved_by_message_id(self):
  163. message_id = None
  164. for r in self:
  165. message_id = r.message_moved_by_message_id.id
  166. return {
  167. 'type': 'ir.actions.act_window',
  168. 'res_model': 'mail_move_message.wizard',
  169. 'view_mode': 'form',
  170. 'view_type': 'form',
  171. 'views': [[False, 'form']],
  172. 'target': 'new',
  173. 'context': {'default_message_id': message_id},
  174. }
  175. @api.multi
  176. def move(self):
  177. for r in self:
  178. if not r.model:
  179. raise exceptions.except_orm(_('Record field is empty!'), _('Select a record for relocation first'))
  180. for r in self:
  181. r.check_access()
  182. if not r.parent_id or not (r.parent_id.model == r.model and
  183. r.parent_id.res_id == r.res_id):
  184. # link with the first message of record
  185. parent = self.env['mail.message'].search([('model', '=', r.model), ('res_id', '=', r.res_id)], order='id', limit=1)
  186. r.parent_id = parent.id or None
  187. r.message_id.move(r.parent_id.id, r.res_id, r.model, r.move_back, r.move_followers, r.message_to_read, r.partner_id)
  188. if r.model in ['mail.message', 'mail.channel', False]:
  189. return {
  190. 'name': 'Chess game page',
  191. 'type': 'ir.actions.act_url',
  192. 'url': '/web',
  193. 'target': 'self',
  194. }
  195. return {
  196. 'name': _('Record'),
  197. 'view_type': 'form',
  198. 'view_mode': 'form',
  199. 'res_model': r.model,
  200. 'res_id': r.res_id,
  201. 'views': [(False, 'form')],
  202. 'type': 'ir.actions.act_window',
  203. }
  204. @api.multi
  205. def delete(self):
  206. for r in self:
  207. r.delete_one()
  208. @api.multi
  209. def delete_one(self):
  210. self.ensure_one()
  211. msg_id = self.message_id.id
  212. # Send notification
  213. notification = {'id': msg_id}
  214. self.env['bus.bus'].sendone((self._cr.dbname, 'mail_move_message.delete_message'), notification)
  215. self.message_id.unlink()
  216. return {}
  217. @api.multi
  218. def read_close(self):
  219. for r in self:
  220. r.read_close_one()
  221. @api.multi
  222. def read_close_one(self):
  223. self.ensure_one()
  224. self.message_id.set_message_done()
  225. self.message_id.child_ids.set_message_done()
  226. return {'type': 'ir.actions.act_window_close'}
  227. class MailMessage(models.Model):
  228. _inherit = 'mail.message'
  229. is_moved = fields.Boolean('Is moved')
  230. moved_from_res_id = fields.Integer('Related Document ID (Original)')
  231. moved_from_model = fields.Char('Related Document Model (Original)')
  232. moved_from_parent_id = fields.Many2one('mail.message', 'Parent Message (Original)', ondelete='set null')
  233. moved_by_message_id = fields.Many2one('mail.message', 'Moved by message', ondelete='set null', help='Top message, that initate moving this message')
  234. moved_by_user_id = fields.Many2one('res.users', 'Moved by user', ondelete='set null')
  235. all_child_ids = fields.One2many('mail.message', string='All childs', compute='_compute_get_all_childs', help='all childs, including subchilds')
  236. moved_as_unread = fields.Boolean('Was Unread', default=False)
  237. @api.multi
  238. def _compute_get_all_childs(self, include_myself=True):
  239. for r in self:
  240. r._get_all_childs_one(include_myself=include_myself)
  241. @api.multi
  242. def _get_all_childs_one(self, include_myself=True):
  243. self.ensure_one()
  244. ids = []
  245. if include_myself:
  246. ids.append(self.id)
  247. while True:
  248. new_ids = self.search([('parent_id', 'in', ids), ('id', 'not in', ids)]).ids
  249. if new_ids:
  250. ids = ids + new_ids
  251. continue
  252. break
  253. moved_childs = self.search([('moved_by_message_id', '=', self.id)]).ids
  254. self.all_child_ids = ids + moved_childs
  255. @api.multi
  256. def move_followers(self, model, ids):
  257. fol_obj = self.env['mail.followers']
  258. for message in self:
  259. followers = fol_obj.sudo().search([('res_model', '=', message.model),
  260. ('res_id', '=', message.res_id)])
  261. for f in followers:
  262. self.env[model].browse(ids).message_subscribe([f.partner_id.id], [s.id for s in f.subtype_ids])
  263. @api.multi
  264. def move(self, parent_id, res_id, model, move_back, move_followers=False, message_to_read=False, author=False):
  265. for r in self:
  266. r.move_one(parent_id, res_id, model, move_back, move_followers=move_followers, message_to_read=message_to_read, author=author)
  267. @api.multi
  268. def move_one(self, parent_id, res_id, model, move_back, move_followers=False, message_to_read=False, author=False):
  269. self.ensure_one()
  270. if parent_id == self.id:
  271. # if for any reason method is called to move message with parent
  272. # equal to oneself, we need stop to prevent infinitive loop in
  273. # building message tree
  274. return
  275. if not self.author_id:
  276. self.write({
  277. 'author_id': author.id,
  278. })
  279. vals = {}
  280. if move_back:
  281. # clear variables if we move everything back
  282. vals['is_moved'] = False
  283. vals['moved_by_user_id'] = None
  284. vals['moved_by_message_id'] = None
  285. vals['moved_from_res_id'] = None
  286. vals['moved_from_model'] = None
  287. vals['moved_from_parent_id'] = None
  288. vals['moved_as_unread'] = None
  289. else:
  290. vals['parent_id'] = parent_id
  291. vals['res_id'] = res_id
  292. vals['model'] = model
  293. vals['is_moved'] = True
  294. vals['moved_by_user_id'] = self.env.user.id
  295. vals['moved_by_message_id'] = self.id
  296. vals['moved_as_unread'] = message_to_read
  297. # Update record_name in message
  298. vals['record_name'] = self._get_record_name(vals)
  299. # unread message remains unread after moving back to origin
  300. if self.moved_as_unread and move_back:
  301. notification = {
  302. 'mail_message_id': self.id,
  303. 'res_partner_id': self.env.user.partner_id.id,
  304. 'is_read': False,
  305. }
  306. self.write({
  307. 'notification_ids': [(0, 0, notification)],
  308. })
  309. for r in self.all_child_ids:
  310. r_vals = vals.copy()
  311. if not r.is_moved:
  312. # moved_from_* variables contain not last, but original
  313. # reference
  314. r_vals['moved_from_parent_id'] = r.parent_id.id or r.env.context.get('uid')
  315. r_vals['moved_from_res_id'] = r.res_id or r.id
  316. r_vals['moved_from_model'] = r.model or r._name
  317. elif move_back:
  318. r_vals['parent_id'] = r.moved_from_parent_id.id
  319. r_vals['res_id'] = r.moved_from_res_id
  320. r_vals['model'] = (r.moved_from_model and r.moved_from_model not in ['mail.message', 'mail.channel', False]) and r.moved_from_model
  321. r_vals['record_name'] = r_vals['model'] and self.env[r.moved_from_model].browse(r.moved_from_res_id).name
  322. if move_followers:
  323. r.sudo().move_followers(r_vals.get('model'), r_vals.get('res_id'))
  324. r.sudo().write(r_vals)
  325. r.attachment_ids.sudo().write({
  326. 'res_id': r_vals.get('res_id'),
  327. 'res_model': r_vals.get('model')
  328. })
  329. # Send notification
  330. notification = {
  331. 'id': self.id,
  332. 'res_id': vals.get('res_id'),
  333. 'model': vals.get('model'),
  334. 'is_moved': vals['is_moved'],
  335. 'record_name': 'record_name' in vals and vals['record_name'],
  336. }
  337. self.env['bus.bus'].sendone((self._cr.dbname, 'mail_move_message'), notification)
  338. @api.multi
  339. def name_get(self):
  340. context = self.env.context
  341. if not (context or {}).get('extended_name'):
  342. return super(MailMessage, self).name_get()
  343. reads = self.read(['record_name', 'model', 'res_id'])
  344. res = []
  345. for record in reads:
  346. name = record['record_name'] or ''
  347. extended_name = ' [%s] ID %s' % (record.get('model', 'UNDEF'), record.get('res_id', 'UNDEF'))
  348. res.append((record['id'], name + extended_name))
  349. return res
  350. @api.multi
  351. def message_format(self):
  352. message_values = super(MailMessage, self).message_format()
  353. message_index = {message['id']: message for message in message_values}
  354. for item in self:
  355. msg = message_index.get(item.id)
  356. if msg:
  357. msg['is_moved'] = item.is_moved
  358. return message_values
  359. class MailMoveMessageConfiguration(models.TransientModel):
  360. _inherit = 'res.config.settings'
  361. model_ids = fields.Many2many(comodel_name='ir.model', string='Models')
  362. move_followers = fields.Boolean('Move Followers')
  363. @api.model
  364. def get_values(self):
  365. res = super(MailMoveMessageConfiguration, self).get_values()
  366. config_parameters = self.env["ir.config_parameter"].sudo()
  367. model_names = config_parameters.sudo().get_param('mail_relocation_models')
  368. model_names = model_names.split(',')
  369. model_ids = self.env['ir.model'].sudo().search([('model', 'in', model_names)])
  370. res.update(
  371. model_ids=[m.id for m in model_ids],
  372. move_followers=config_parameters.sudo().get_param('mail_relocation_move_followers'),
  373. )
  374. return res
  375. @api.multi
  376. def set_values(self):
  377. super(MailMoveMessageConfiguration, self).set_values()
  378. config_parameters = self.env["ir.config_parameter"].sudo()
  379. for record in self:
  380. model_names = ','.join([x.model for x in record.model_ids])
  381. config_parameters.set_param("mail_relocation_models", model_names or '')
  382. config_parameters.set_param("mail_relocation_move_followers", record.move_followers or '')
  383. class ResPartner(models.Model):
  384. _inherit = 'res.partner'
  385. @api.model
  386. def create(self, vals):
  387. res = super(ResPartner, self).create(vals)
  388. if 'update_message_author' in self.env.context and 'email' in vals:
  389. mail_message_obj = self.env['mail.message']
  390. # Escape special SQL characters in email_address to avoid invalid matches
  391. email_address = (vals['email'].replace('\\', '\\\\').replace('%', '\\%').replace('_', '\\_'))
  392. email_brackets = "<%s>" % email_address
  393. messages = mail_message_obj.search([
  394. '|',
  395. ('email_from', '=ilike', email_address),
  396. ('email_from', 'ilike', email_brackets),
  397. ('author_id', '=', False)
  398. ])
  399. if messages:
  400. messages.sudo().write({'author_id': res.id})
  401. return res
  402. @api.model
  403. def default_get(self, default_fields):
  404. contextual_self = self
  405. if 'mail_move_message' in self.env.context and self.env.context['mail_move_message']:
  406. contextual_self = self.with_context(
  407. default_name=self.env.context['message_name_from'] or '',
  408. default_email=self.env.context['message_email_from'] or '',
  409. )
  410. return super(ResPartner, contextual_self).default_get(default_fields)