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.

253 lines
9.3 KiB

  1. # Copyright 2018 Eficent Business and IT Consulting Services S.L.
  2. # License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
  3. from odoo import api, fields, models, _
  4. from odoo.exceptions import UserError
  5. import ast
  6. class PrivacyPartnerReport(models.TransientModel):
  7. _name = "privacy.partner.report"
  8. _description = "Privacy Partner Report"
  9. company_id = fields.Many2one(
  10. comodel_name='res.company',
  11. string='Company',
  12. required=True,
  13. default=lambda self: self.env.user.company_id,
  14. )
  15. partner_id = fields.Many2one(
  16. comodel_name='res.partner',
  17. string='Partner',
  18. required=True,
  19. )
  20. table_ids = fields.Many2many(
  21. comodel_name='privacy.partner.data',
  22. string='Models with related partner data',
  23. )
  24. @api.onchange('partner_id')
  25. def _onchange_partner_id(self):
  26. if self.partner_id:
  27. data = self._get_tables_from_partner(self.partner_id)
  28. names = self._get_table_names(data)
  29. tables = self.env['privacy.partner.data']
  30. for name in sorted(names):
  31. vals = self._get_default_table(
  32. name=name,
  33. data=[t for t in data if t[0] == name and not t[5]],
  34. )
  35. if vals:
  36. tables |= self.env['privacy.partner.data'].create(vals)
  37. self.table_ids = tables
  38. else:
  39. self.table_ids = self.env['privacy.partner.data']
  40. return {
  41. 'domain': {
  42. 'table_ids': [
  43. ('id', 'in', self.table_ids.ids)],
  44. },
  45. }
  46. @api.onchange('company_id')
  47. def _onchange_company_id(self):
  48. if not self.company_id:
  49. self.company_id = self.env.user.company_id
  50. return {
  51. 'domain': {
  52. 'partner_id': [
  53. ('company_id', 'in', [self.company_id.id, False])],
  54. },
  55. }
  56. @api.multi
  57. def button_export_xlsx(self):
  58. self.ensure_one()
  59. if not self.table_ids:
  60. raise UserError(_('No data for this partner.'))
  61. return self.check_report(xlsx_report=True)
  62. def _build_contexts(self, data):
  63. result = {}
  64. result['partner_id'] = data['form']['partner_id'][0] or False
  65. result['company_id'] = data['form']['company_id'][0] or False
  66. result['table_ids'] = 'table_ids' in data['form'] and \
  67. data['form']['table_ids'] or False
  68. return result
  69. @staticmethod
  70. def _transform_binary(binary):
  71. # TODO: Implement if needed
  72. return False
  73. def _clean_data(self, model, rows):
  74. cleaned_rows = []
  75. for i, row in enumerate(rows):
  76. cleaned_rows.append({})
  77. for key, value in row.items():
  78. label = self.env[model]._fields[key].string or key
  79. if self.env[model]._fields[key].store:
  80. if 'many2one' == self.env[model]._fields[key].type:
  81. comodel = self.env[model]._fields[key].comodel_name
  82. if value:
  83. record = self.env[comodel].sudo().browse(value)
  84. cleaned_rows[i][label] = record.display_name
  85. else:
  86. cleaned_rows[i][label] = rows[i][key]
  87. elif 'binary' == self.env[model]._fields[key].type:
  88. binary = self._transform_binary(rows[i][key])
  89. if binary:
  90. cleaned_rows[i][label] = binary
  91. elif '2many' not in self.env[model]._fields[key].type:
  92. cleaned_rows[i][label] = rows[i][key]
  93. return cleaned_rows
  94. @api.multi
  95. def check_report(self, xlsx_report=False):
  96. self.ensure_one()
  97. data = {}
  98. data['ids'] = self.env.context.get('active_ids', [])
  99. data['model'] = self.env.context.get('active_model', 'ir.ui.menu')
  100. data['form'] = self.read(['partner_id', 'company_id', 'table_ids'])[0]
  101. used_context = self._build_contexts(data)
  102. data['form']['id'] = str(data['form']['id'])
  103. data['form']['used_context'] = dict(
  104. used_context, lang=self.env.context.get('lang', 'en_US'))
  105. return self._print_report(data=data, xlsx_report=xlsx_report)
  106. @api.multi
  107. def compute_data_for_report(self, data):
  108. if not data.get('form'):
  109. raise UserError(
  110. _("Form content is missing, this report cannot be printed."))
  111. partner = data['form'].get('partner_id', False)
  112. if not partner:
  113. raise UserError(
  114. _("No provided partner."))
  115. partner = self.env['res.partner'].sudo().browse(partner[0])
  116. tables = data['form'].get('table_ids', False)
  117. if tables:
  118. tables = self.env['privacy.partner.data'].browse(tables)
  119. tables = self._get_rows_from_tables(tables, partner)
  120. data.update({'tables': tables, })
  121. return data
  122. def _exclude_column(self, model, column):
  123. # https://github.com/odoo/odoo/issues/24927
  124. if model in ('mail.compose.message', 'survey.mail.compose.message'):
  125. if column in ('needaction_partner_ids', 'starred_partner_ids'):
  126. return True
  127. # feel free to add more specific cases meanwhile the issue is not fixed
  128. return False
  129. def _get_default_table(self, name, data):
  130. if data:
  131. field_type = data[0][4]
  132. res = self.env[data[0][1]]
  133. for t in data:
  134. res |= self.env[t[1]].sudo().browse(t[3])
  135. if res:
  136. values = {
  137. 'name': name,
  138. 'model_id': self.env['ir.model'].sudo().search(
  139. [('model', '=', res._name)]).id,
  140. 'count_rows': len(res.ids),
  141. 'field_type': field_type,
  142. 'res_ids': res.ids,
  143. }
  144. return values
  145. return {}
  146. def _get_model_from_table(self, table, partner):
  147. new_tables = {}
  148. for model in table.model_id:
  149. rows = self._get_rows_from_model(model, partner)
  150. new_tables[model.display_name] = rows
  151. return new_tables
  152. def _get_rows_from_model(self, model, partner):
  153. lines = self.env[model.model]
  154. columns = [k for k, v in self.env[model.model]._fields.items()
  155. if v.comodel_name == 'res.partner' and
  156. v.store and not self._exclude_column(model.model, k)]
  157. for column in columns:
  158. lines |= self.env[model.model].sudo().search(
  159. [(column, '=', partner.id)])
  160. rows = lines.sudo().read(load=False)
  161. rows = self._clean_data(model.model, rows)
  162. return rows
  163. def _get_rows_from_tables(self, tables, partner):
  164. new_tables = {}
  165. for table in tables:
  166. data_table = self._get_model_from_table(table, partner)
  167. new_tables[str(table.name)] = data_table
  168. return new_tables
  169. def _get_table_names(self, data):
  170. names = []
  171. for t in data:
  172. if t[3] and not t[5] and t[0] not in names:
  173. names.append(t[0])
  174. return names
  175. def _get_tables_from_partner(self, partner):
  176. tables = [t[0] for t in [
  177. [[self.env[m]._table, m, k, self.env[m].sudo().search(
  178. [(k, '=', partner.id)]).ids, v.type, self.env[m]._transient]
  179. for k, v in self.env[m]._fields.items()
  180. if v.comodel_name == 'res.partner' and self.env[m]._auto and
  181. v.store and not self._exclude_column(m, k)]
  182. for m in [x for x in self.env.registry.keys()]] if t]
  183. for i, t in enumerate(tables):
  184. if t[4] == 'many2many':
  185. if t[3]:
  186. relation = self.env[t[1]]._fields[t[2]].relation
  187. if relation:
  188. tables[i][0] = relation
  189. return tables
  190. def _print_report(self, data, xlsx_report=False):
  191. records = self.env[data['model']].sudo().browse(data.get('ids', []))
  192. if xlsx_report:
  193. return self.env.ref('privacy_partner_report.report_partner_xlsx').\
  194. with_context(landscape=True).report_action(
  195. records, data=data)
  196. class PrivacyPartnerData(models.TransientModel):
  197. _name = "privacy.partner.data"
  198. _description = "Privacy Partner Data"
  199. name = fields.Char(
  200. string='Database Table',
  201. )
  202. model_id = fields.Many2one(
  203. comodel_name='ir.model',
  204. ondelete='cascade',
  205. string='Models',
  206. )
  207. field_type = fields.Char(
  208. string="Type", oldname='type',
  209. )
  210. count_rows = fields.Integer(
  211. default=0,
  212. string='Number of lines',
  213. )
  214. res_ids = fields.Char('Related Document IDs', index=True,
  215. help='List of Related Document IDs')
  216. @api.multi
  217. def action_view_records(self):
  218. self.ensure_one()
  219. response = {
  220. 'name': self.model_id.display_name,
  221. 'type': 'ir.actions.act_window',
  222. 'res_model': self.model_id.model,
  223. 'view_mode': 'tree,form',
  224. 'domain': [('id', 'in', ast.literal_eval(self.res_ids))],
  225. 'target': 'current',
  226. 'context': {'delete': True},
  227. }
  228. return response