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.

238 lines
8.9 KiB

  1. # -*- coding: utf-8 -*-
  2. # Copyright 2018 Eficent Business and IT Consulting Services S.L.
  3. # License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
  4. from openerp import api, fields, models, _
  5. from openerp.osv import fields as old_fields
  6. from openerp.exceptions import UserError
  7. class PrivacyPartnerReport(models.TransientModel):
  8. _name = "privacy.partner.report"
  9. _description = "Privacy Partner Report"
  10. company_id = fields.Many2one(
  11. comodel_name='res.company',
  12. string='Company',
  13. required=True,
  14. default=lambda self: self.env.user.company_id,
  15. )
  16. partner_id = fields.Many2one(
  17. comodel_name='res.partner',
  18. string='Partner',
  19. required=True,
  20. )
  21. table_ids = fields.Many2many(
  22. comodel_name='privacy.partner.data',
  23. string='Models with related partner data',
  24. )
  25. @api.onchange('partner_id')
  26. def _onchange_partner_id(self):
  27. if self.partner_id:
  28. data = self._get_tables_from_partner(self.partner_id)
  29. names = self._get_table_names(data)
  30. tables = self.env['privacy.partner.data']
  31. for name in sorted(names):
  32. vals = self._get_default_table(
  33. name=name,
  34. data=[t for t in data if t[0] == name and not t[5]],
  35. )
  36. if vals:
  37. tables |= self.env['privacy.partner.data'].create(vals)
  38. self.table_ids = tables
  39. else:
  40. self.table_ids = self.env['privacy.partner.data']
  41. return {
  42. 'domain': {
  43. 'table_ids': [
  44. ('id', 'in', self.table_ids.ids)],
  45. },
  46. }
  47. @api.onchange('company_id')
  48. def _onchange_company_id(self):
  49. if not self.company_id:
  50. self.company_id = self.env.user.company_id
  51. return {
  52. 'domain': {
  53. 'partner_id': [
  54. ('company_id', 'in', [self.company_id.id, False])],
  55. },
  56. }
  57. @api.multi
  58. def button_export_xlsx(self):
  59. self.ensure_one()
  60. return self.check_report(xlsx_report=True)
  61. def _build_contexts(self, data):
  62. result = {}
  63. result['partner_id'] = data['form']['partner_id'][0] or False
  64. result['company_id'] = data['form']['company_id'][0] or False
  65. result['table_ids'] = 'table_ids' in data['form'] and \
  66. data['form']['table_ids'] or False
  67. return result
  68. def _clean_data(self, model, rows):
  69. cleaned_rows = []
  70. for i, row in enumerate(rows):
  71. cleaned_rows.append({})
  72. for key, value in row.items():
  73. label = self.env[model]._fields[key].string or key
  74. if self.env[model]._fields[key].store:
  75. if 'many2one' == self.env[model]._fields[key].type:
  76. comodel = self.env[model]._fields[key].comodel_name
  77. if value:
  78. record = self.env[comodel].sudo().browse(value)
  79. cleaned_rows[i][label] = \
  80. record.display_name.encode('utf8')
  81. else:
  82. cleaned_rows[i][label] = rows[i][key]
  83. elif '2many' not in self.env[model]._fields[key].type:
  84. cleaned_rows[i][label] = rows[i][key]
  85. return cleaned_rows
  86. @api.multi
  87. def check_report(self, xlsx_report=False):
  88. self.ensure_one()
  89. data = {}
  90. data['ids'] = self.env.context.get('active_ids', [])
  91. data['model'] = self.env.context.get('active_model', 'ir.ui.menu')
  92. data['form'] = self.read(['partner_id', 'company_id', 'table_ids'])[0]
  93. used_context = self._build_contexts(data)
  94. data['form']['used_context'] = dict(
  95. used_context, lang=self.env.context.get('lang', 'en_US'))
  96. return self._print_report(data=data, xlsx_report=xlsx_report)
  97. @api.multi
  98. def compute_data_for_report(self, data):
  99. if not data.get('form'):
  100. raise UserError(
  101. _("Form content is missing, this report cannot be printed."))
  102. partner = data['form'].get('partner_id', False)
  103. if not partner:
  104. raise UserError(
  105. _("No provided partner."))
  106. partner = self.env['res.partner'].sudo().browse(partner[0])
  107. tables = data['form'].get('table_ids', False)
  108. if tables:
  109. tables = self.env['privacy.partner.data'].browse(tables)
  110. tables = self._get_rows_from_tables(tables, partner)
  111. data.update({'tables': tables, })
  112. return data
  113. def _exclude_column(self, model, column):
  114. # To remove in v10:
  115. # (non-stored function fields should have _fnct_search)
  116. column_info = self.env[model]._columns.get(column)
  117. next_model = self.env[model]
  118. while not column_info and column in next_model._inherit_fields:
  119. next_model = self.env[next_model._inherit_fields[column][0]]
  120. column_info = next_model._columns.get(column)
  121. if isinstance(column_info, old_fields.function) \
  122. and not column_info.store and not column_info._fnct_search:
  123. return True
  124. # https://github.com/odoo/odoo/issues/24927
  125. if model in ('mail.compose.message', 'survey.mail.compose.message'):
  126. if column in ('needaction_partner_ids', 'starred_partner_ids'):
  127. return True
  128. # feel free to add more specific cases meanwhile the issue is not fixed
  129. return False
  130. def _get_default_table(self, name, data):
  131. if data:
  132. data_type = data[0][4]
  133. res = self.env[data[0][1]]
  134. for t in data:
  135. res |= self.env[t[1]].sudo().browse(t[3])
  136. if res:
  137. values = {
  138. 'name': name,
  139. 'model_id': self.env['ir.model'].sudo().search(
  140. [('model', '=', res._name)]).id,
  141. 'count_rows': len(res.ids),
  142. 'type': data_type,
  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.encode('utf8')] = 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. processed_data = self.compute_data_for_report(data)
  193. if xlsx_report:
  194. return self.env['report'].with_context(landscape=True).get_action(
  195. records=records, report_name='privacy.report_partner_xlsx',
  196. data=processed_data)
  197. class PrivacyPartnerData(models.TransientModel):
  198. _name = "privacy.partner.data"
  199. _description = "Privacy Partner Data"
  200. name = fields.Char(
  201. string='Database Table',
  202. )
  203. model_id = fields.Many2one(
  204. comodel_name='ir.model',
  205. ondelete='cascade',
  206. string='Models',
  207. )
  208. type = fields.Char(
  209. string="Type",
  210. )
  211. count_rows = fields.Integer(
  212. default=0,
  213. string='Number of lines',
  214. )