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.

346 lines
14 KiB

9 years ago
9 years ago
  1. from lxml import etree
  2. from openerp import api, models, fields, SUPERUSER_ID
  3. from openerp.tools import email_split
  4. from openerp.tools.translate import _
  5. class wizard(models.TransientModel):
  6. _name = 'mail_move_message.wizard'
  7. def _model_selection(self):
  8. selection = []
  9. config_parameters = self.env['ir.config_parameter']
  10. model_names = config_parameters.get_param('mail_relocation_models')
  11. model_names = model_names.split(',') if model_names else []
  12. if 'default_message_id' in self.env.context:
  13. message = self.env['mail.message'].browse(self.env.context['default_message_id'])
  14. if message.model and message.model not in model_names:
  15. model_names.append(message.model)
  16. if message.moved_from_model and message.moved_from_model not in model_names:
  17. model_names.append(message.moved_from_model)
  18. if model_names:
  19. selection = [(m.model, m.display_name) for m in self.env['ir.model'].search([('model', 'in', model_names)])]
  20. return selection
  21. @api.model
  22. def default_get(self, fields_list):
  23. res = super(wizard, self).default_get(fields_list)
  24. model_fields = self.fields_get()
  25. if model_fields['model']['selection']:
  26. res['model'] = model_fields['model']['selection'] and model_fields['model']['selection'][0][0]
  27. if 'message_id' in res:
  28. message = self.env['mail.message'].browse(res['message_id'])
  29. email_from = message.email_from
  30. parts = email_split(email_from.replace(' ',','))
  31. if parts:
  32. email = parts[0]
  33. name = email_from[:email_from.index(email)].replace('"', '').replace('<', '').strip() or email_from
  34. else:
  35. name, email = email_from
  36. res['message_name_from'] = name
  37. res['message_email_from'] = email
  38. if message.author_id and self.env.uid not in [u.id for u in message.author_id.user_ids]:
  39. res['filter_by_partner'] = True
  40. if message.author_id and res.get('model'):
  41. res_id = self.env[res['model']].search([], order='id desc', limit=1)
  42. res['res_id'] = res_id and res_id[0].id
  43. res['uid'] = self.env.uid
  44. return res
  45. message_id = fields.Many2one('mail.message', string='Message')
  46. message_body = fields.Html(related='message_id.body', string='Message to move', readonly=True)
  47. message_moved_by_message_id = fields.Many2one('mail.message', related='message_id.moved_by_message_id', string='Moved with', readonly=True)
  48. message_moved_by_user_id = fields.Many2one('res.users', related='message_id.moved_by_user_id', string='Moved by', readonly=True)
  49. message_is_moved = fields.Boolean(string='Is Moved', related='message_id.is_moved', readonly=True)
  50. parent_id = fields.Many2one('mail.message', string='Search by name', )
  51. model = fields.Selection(_model_selection, string='Model')
  52. res_id = fields.Integer(string='Record')
  53. can_move = fields.Boolean('Can move', compute='get_can_move')
  54. move_back = fields.Boolean('MOVE TO ORIGIN', help='Move message and submessages to original place')
  55. partner_id = fields.Many2one('res.partner', string='Author', related='message_id.author_id')
  56. filter_by_partner = fields.Boolean('Filter Records by partner')
  57. message_email_from = fields.Char()
  58. message_name_from = fields.Char()
  59. # FIXME message_to_read should be True even if current message or any his childs are unread
  60. message_to_read = fields.Boolean(related='message_id.to_read')
  61. uid = fields.Integer()
  62. @api.depends('message_id')
  63. @api.one
  64. def get_can_move(self):
  65. # message was not moved before OR message is a top message of previous move
  66. self.can_move = not self.message_id.moved_by_message_id or self.message_id.moved_by_message_id.id == self.message_id.id
  67. @api.onchange('move_back')
  68. def on_change_move_back(self):
  69. if not self.move_back:
  70. return
  71. self.parent_id = self.message_id.moved_from_parent_id
  72. model = self.message_id.moved_from_model
  73. if self.message_id.is_moved:
  74. self.model = model
  75. self.res_id = self.message_id.moved_from_res_id
  76. @api.onchange('parent_id', 'res_id', 'model')
  77. def update_move_back(self):
  78. model = self.message_id.moved_from_model
  79. self.move_back = self.parent_id == self.message_id.moved_from_parent_id \
  80. and self.res_id == self.message_id.moved_from_res_id \
  81. and (self.model == model or (not self.model and not model))
  82. @api.onchange('parent_id')
  83. def on_change_parent_id(self):
  84. if self.parent_id and self.parent_id.model:
  85. self.model = self.parent_id.model
  86. self.res_id = self.parent_id.res_id
  87. else:
  88. self.model = None
  89. self.res_id = None
  90. @api.onchange('model', 'filter_by_partner', 'partner_id')
  91. def on_change_partner(self):
  92. domain = {'res_id': []}
  93. if self.model and self.filter_by_partner and self.partner_id:
  94. fields = self.env[self.model].fields_get(False)
  95. contact_field = False
  96. for n, f in fields.iteritems():
  97. if f['type'] == 'many2one' and f['relation'] == 'res.partner':
  98. contact_field = n
  99. break
  100. if contact_field:
  101. domain['res_id'] = [(contact_field, '=', self.partner_id.id)]
  102. if self.model and self.partner_id:
  103. res_id = self.env[self.model].search(domain['res_id'], order='id desc', limit=1)
  104. self.res_id = res_id and res_id[0].id
  105. else:
  106. self.res_id = None
  107. return {'domain': domain}
  108. @api.one
  109. def check_access(self):
  110. cr = self._cr
  111. uid = self.env.user.id
  112. operation = 'write'
  113. context = self._context
  114. if not ( self.model and self.res_id ):
  115. return True
  116. model_obj = self.pool[self.model]
  117. mids = model_obj.exists(cr, uid, [self.res_id])
  118. if hasattr(model_obj, 'check_mail_message_access'):
  119. model_obj.check_mail_message_access(cr, uid, mids, operation, context=context)
  120. else:
  121. self.pool['mail.thread'].check_mail_message_access(cr, uid, mids, operation, model_obj=model_obj, context=context)
  122. @api.multi
  123. def open_moved_by_message_id(self):
  124. message_id = None
  125. for r in self:
  126. message_id = r.message_moved_by_message_id.id
  127. return {
  128. 'type': 'ir.actions.act_window',
  129. 'res_model': 'mail_move_message.wizard',
  130. 'view_mode': 'form',
  131. 'view_type': 'form',
  132. 'views': [[False, 'form']],
  133. 'target': 'new',
  134. 'context': {'default_message_id': message_id},
  135. }
  136. @api.multi
  137. def move(self):
  138. for r in self:
  139. r.check_access()
  140. if r.parent_id:
  141. if not (r.parent_id.model == r.model and
  142. r.parent_id.res_id == r.res_id):
  143. r.parent_id = None
  144. r.message_id.move(r.parent_id.id, r.res_id, r.model, r.move_back)
  145. if not ( r.model and r.res_id ):
  146. obj = self.pool.get('ir.model.data').get_object_reference(self._cr, SUPERUSER_ID, 'mail', 'mail_archivesfeeds')[1]
  147. return {
  148. 'type' : 'ir.actions.client',
  149. 'name' : 'Archive',
  150. 'tag' : 'reload',
  151. 'params' : {'menu_id': obj},
  152. }
  153. return {
  154. 'name': _('Record'),
  155. 'view_type': 'form',
  156. 'view_mode': 'form',
  157. 'res_model': r.model,
  158. 'res_id': r.res_id,
  159. 'views': [(False, 'form')],
  160. 'type': 'ir.actions.act_window',
  161. }
  162. @api.one
  163. def delete(self):
  164. self.message_id.unlink()
  165. return {}
  166. @api.model
  167. def create_partner(self, message_id, relation, partner_id, message_name_from, message_email_from):
  168. model = self.env[relation]
  169. message = self.env['mail.message'].browse(message_id)
  170. if not partner_id and message_name_from:
  171. partner_id = self.env['res.partner'].with_context({'update_message_author': True}).create({
  172. 'name': message_name_from,
  173. 'email': message_email_from
  174. }).id
  175. context = {'partner_id': partner_id}
  176. if model._rec_name:
  177. context.update({'default_%s' % model._rec_name: message.subject})
  178. fields = model.fields_get()
  179. contact_field = False
  180. for n, f in fields.iteritems():
  181. if f['type'] == 'many2one' and f['relation'] == 'res.partner':
  182. contact_field = n
  183. break
  184. if contact_field:
  185. context.update({'default_%s' % contact_field: partner_id})
  186. return context
  187. @api.one
  188. def read_close(self):
  189. self.message_id.set_message_read(True)
  190. self.message_id.child_ids.set_message_read(True)
  191. return {'type': 'ir.actions.act_window_close'}
  192. class mail_message(models.Model):
  193. _inherit = 'mail.message'
  194. is_moved = fields.Boolean('Is moved')
  195. moved_from_res_id = fields.Integer('Related Document ID (Original)')
  196. moved_from_model = fields.Char('Related Document Model (Original)')
  197. moved_from_parent_id = fields.Many2one('mail.message', 'Parent Message (Original)', ondelete='set null')
  198. moved_by_message_id = fields.Many2one('mail.message', 'Moved by message', ondelete='set null', help='Top message, that initate moving this message')
  199. moved_by_user_id = fields.Many2one('res.users', 'Moved by user', ondelete='set null')
  200. all_child_ids = fields.One2many('mail.message', string='All childs', compute='_get_all_childs', help='all childs, including subchilds')
  201. @api.one
  202. def _get_all_childs(self, include_myself=True):
  203. ids = []
  204. if include_myself:
  205. ids.append(self.id)
  206. while True:
  207. new_ids = self.search([('parent_id', 'in', ids), ('id', 'not in', ids)]).ids
  208. if new_ids:
  209. ids = ids + new_ids
  210. continue
  211. break
  212. moved_childs = self.search([('moved_by_message_id', '=', self.id)]).ids
  213. self.all_child_ids = ids + moved_childs
  214. @api.one
  215. def move(self, parent_id, res_id, model, move_back):
  216. vals = {}
  217. if move_back:
  218. # clear variables if we move everything back
  219. vals['is_moved'] = False
  220. vals['moved_by_user_id'] = None
  221. vals['moved_by_message_id'] = None
  222. vals['moved_from_res_id'] = None
  223. vals['moved_from_model'] = None
  224. vals['moved_from_parent_id'] = None
  225. else:
  226. vals['parent_id'] = parent_id
  227. vals['res_id'] = res_id
  228. vals['model'] = model
  229. vals['is_moved'] = True
  230. vals['moved_by_user_id'] = self.env.user.id
  231. vals['moved_by_message_id'] = self.id
  232. for r in self.all_child_ids:
  233. r_vals = vals.copy()
  234. if not r.is_moved:
  235. # moved_from_* variables contain not last, but original
  236. # reference
  237. r_vals['moved_from_parent_id'] = r.parent_id.id
  238. r_vals['moved_from_res_id'] = r.res_id
  239. r_vals['moved_from_model'] = r.model
  240. elif move_back:
  241. r_vals['parent_id'] = r.moved_from_parent_id.id
  242. r_vals['res_id'] = r.moved_from_res_id
  243. r_vals['model'] = r.moved_from_model
  244. print 'update message', r, r_vals
  245. r.sudo().write(r_vals)
  246. def name_get(self, cr, uid, ids, context=None):
  247. if not (context or {}).get('extended_name'):
  248. return super(mail_message, self).name_get(cr, uid, ids, context=context)
  249. if isinstance(ids, (list, tuple)) and not len(ids):
  250. return []
  251. if isinstance(ids, (long, int)):
  252. ids = [ids]
  253. reads = self.read(cr, uid, ids, ['record_name','model', 'res_id'], context=context)
  254. res = []
  255. for record in reads:
  256. name = record['record_name'] or ''
  257. extended_name = ' [%s] ID %s' % (record.get('model', 'UNDEF'), record.get('res_id', 'UNDEF'))
  258. res.append((record['id'], name + extended_name))
  259. return res
  260. def _message_read_dict(self, cr, uid, message, parent_id=False, context=None):
  261. res = super(mail_message, self)._message_read_dict(cr, uid, message, parent_id, context)
  262. res['is_moved'] = message.is_moved
  263. return res
  264. class mail_move_message_configuration(models.TransientModel):
  265. _name = 'mail_move_message.config.settings'
  266. _inherit = 'res.config.settings'
  267. model_ids = fields.Many2many(comodel_name='ir.model', string='Models')
  268. @api.model
  269. def get_default_model_ids(self, fields):
  270. config_parameters = self.env['ir.config_parameter']
  271. model_obj = self.env['ir.model']
  272. model_names = config_parameters.get_param('mail_relocation_models')
  273. if not model_names:
  274. return {}
  275. model_names = model_names.split(',')
  276. model_ids = model_obj.search([('model', 'in', model_names)])
  277. return {'model_ids': [m.id for m in model_ids]}
  278. @api.multi
  279. def set_model_ids(self):
  280. config_parameters = self.env['ir.config_parameter']
  281. model_names = ''
  282. for record in self:
  283. model_names = ','.join([m.model for m in record.model_ids])
  284. config_parameters.set_param('mail_relocation_models', model_names)
  285. class res_partner(models.Model):
  286. _inherit = 'res.partner'
  287. @api.model
  288. def create(self, vals):
  289. res = super(res_partner, self).create(vals)
  290. if 'update_message_author' in self.env.context and 'email' in vals:
  291. mail_message_obj = self.env['mail.message']
  292. # Escape special SQL characters in email_address to avoid invalid matches
  293. email_address = (vals['email'].replace('\\', '\\\\').replace('%', '\\%').replace('_', '\\_'))
  294. email_brackets = "<%s>" % email_address
  295. messages = mail_message_obj.search([
  296. '|',
  297. ('email_from', '=ilike', email_address),
  298. ('email_from', 'ilike', email_brackets),
  299. ('author_id', '=', False)
  300. ])
  301. if messages:
  302. messages.sudo().write({'author_id': res.id})
  303. return res