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.

186 lines
5.9 KiB

privacy_consent: Separate automated emails send process Before https://github.com/OCA/data-protection/pull/29 there was a race condition where an email could be sent while the same transaction that created the `privacy.consent` record still wasn't committed, producing a 404 error if the user clicked on "Accept" or "Reject" before all mails were sent. To avoid that, a raw `cr.commit()` was issued, but this produced another situation where the user had to wait until the full email queue is cleared to get his page loaded. It wasn't an error, but a long queue meant several minutes waiting, and it's ulikely that an average human is so patient. So, here's the final fix (I hope!). The main problem was that I was looking in the wrong place to send the email. It turns out that the `self.post_message_with_template()` method is absolutely helpless in the case at hand, where these criteria must be met: * E-mail must be enqueued, no matter if there are less or more than 50 consents to send. * The template must be processed per record. * In an ideal world, a `cr.commit()` must be issued after each sent mail. The metod that was being used: * Didn't allow to use `auto_commit` mode. * Only allowed to render the template per record if called with `composition_mode="mass_mail"`. * Only allowed to enqueue emails if called with `composition_mode="mass_post"`. Obviously, I cannot set 2 different values for `composition_mode`, so a different strategy had to be used. I discovered that the `mail.template` model has a helpful method called `send_mail()` that, by default: * Renders the template per record * Enqueues the email * The email queue is cleared in `auto_commit=True` mode. So, from now on, problems are gone: * The user click, or the cron run, will just generate the missing `privacy.consent` records and enqueue mails for them. * The mail queue manager will send them later, in `auto_commit` mode. * After sending the e-mail, this module will set the `privacy.consent` record as `sent`. * Thanks to *not* sending the email, the process the user faces when he hits the "generate" button is faster. * Instructions in the README and text in the "generate" button are updated to reflect this new behavior. * Thanks to the `auto_commit` feature, if Odoo is rebooted in the middle of a mail queue clearance, the records that were sent remain properly marked as sent, and the missing mails will be sent after the next boot. * No hardcoded commits. * No locked transactions. * BTW I discovered that 2 different emails were created when creating a new consent. I started using `mail_create_nolog=True` to avoid that problem and only log a single creation message. Note to self: never use again `post_message_with_template()`.
6 years ago
  1. # Copyright 2018 Tecnativa - Jairo Llopis
  2. # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
  3. import hashlib
  4. import hmac
  5. from odoo import api, fields, models
  6. class PrivacyConsent(models.Model):
  7. _name = "privacy.consent"
  8. _description = "Consent of data processing"
  9. _inherit = "mail.thread"
  10. _rec_name = "partner_id"
  11. _sql_constraints = [
  12. (
  13. "unique_partner_activity",
  14. "UNIQUE(partner_id, activity_id)",
  15. "Duplicated partner in this data processing activity",
  16. ),
  17. ]
  18. active = fields.Boolean(
  19. default=True,
  20. index=True,
  21. )
  22. accepted = fields.Boolean(
  23. track_visibility="onchange",
  24. help="Indicates current acceptance status, which can come from "
  25. "subject's last answer, or from the default specified in the "
  26. "related data processing activity.",
  27. )
  28. last_metadata = fields.Text(
  29. readonly=True,
  30. track_visibility="onchange",
  31. help="Metadata from the last acceptance or rejection by the subject",
  32. )
  33. partner_id = fields.Many2one(
  34. "res.partner",
  35. "Subject",
  36. required=True,
  37. readonly=True,
  38. track_visibility="onchange",
  39. help="Subject asked for consent.",
  40. )
  41. activity_id = fields.Many2one(
  42. "privacy.activity",
  43. "Activity",
  44. readonly=True,
  45. required=True,
  46. track_visibility="onchange",
  47. )
  48. state = fields.Selection(
  49. selection=[
  50. ("draft", "Draft"),
  51. ("sent", "Awaiting response"),
  52. ("answered", "Answered"),
  53. ],
  54. default="draft",
  55. readonly=True,
  56. required=True,
  57. track_visibility="onchange",
  58. )
  59. def _creation_subtype(self):
  60. return self.env.ref("privacy_consent.mt_consent_consent_new")
  61. def _track_subtype(self, init_values):
  62. """Return specific subtypes."""
  63. if self.env.context.get("subject_answering"):
  64. return self.env.ref("privacy_consent.mt_consent_acceptance_changed")
  65. if "state" in init_values:
  66. return self.env.ref("privacy_consent.mt_consent_state_changed")
  67. return super(PrivacyConsent, self)._track_subtype(init_values)
  68. def _token(self):
  69. """Secret token to publicly authenticate this record."""
  70. secret = self.env["ir.config_parameter"].sudo().get_param("database.secret")
  71. params = "{}-{}-{}-{}".format(
  72. self.env.cr.dbname,
  73. self.id,
  74. self.partner_id.id,
  75. self.activity_id.id,
  76. )
  77. return hmac.new(
  78. secret.encode("utf-8"),
  79. params.encode("utf-8"),
  80. hashlib.sha512,
  81. ).hexdigest()
  82. def _url(self, accept):
  83. """Tokenized URL to let subject decide consent.
  84. :param bool accept:
  85. Indicates if you want the acceptance URL, or the rejection one.
  86. """
  87. return "/privacy/consent/{}/{}/{}?db={}".format(
  88. "accept" if accept else "reject",
  89. self.id,
  90. self._token(),
  91. self.env.cr.dbname,
  92. )
  93. def _send_consent_notification(self):
  94. """Send email notification to subject."""
  95. for one in self.with_context(
  96. tpl_force_default_to=True,
  97. mail_notify_user_signature=False,
  98. mail_auto_subscribe_no_notify=True,
  99. ):
  100. one.activity_id.consent_template_id.send_mail(one.id)
  101. def _run_action(self):
  102. """Execute server action defined in data processing activity."""
  103. for one in self:
  104. # Always skip draft consents
  105. if one.state == "draft":
  106. continue
  107. action = one.activity_id.server_action_id.with_context(
  108. active_id=one.id,
  109. active_ids=one.ids,
  110. active_model=one._name,
  111. )
  112. action.run()
  113. @api.model_create_multi
  114. def create(self, vals_list):
  115. """Run server action on create."""
  116. results = super().create(vals_list)
  117. # Sync the default acceptance status
  118. results._run_action()
  119. return results
  120. def write(self, vals):
  121. """Run server action on update."""
  122. result = super().write(vals)
  123. self._run_action()
  124. return result
  125. def message_get_suggested_recipients(self):
  126. result = super().message_get_suggested_recipients()
  127. reason = self._fields["partner_id"].string
  128. for one in self:
  129. one._message_add_suggested_recipient(
  130. result,
  131. partner=one.partner_id,
  132. reason=reason,
  133. )
  134. return result
  135. def action_manual_ask(self):
  136. """Let user manually ask for consent."""
  137. return {
  138. "context": {
  139. "default_composition_mode": "comment",
  140. "default_model": self._name,
  141. "default_res_id": self.id,
  142. "default_template_id": self.activity_id.consent_template_id.id,
  143. "default_use_template": True,
  144. "tpl_force_default_to": True,
  145. },
  146. "force_email": True,
  147. "res_model": "mail.compose.message",
  148. "target": "new",
  149. "type": "ir.actions.act_window",
  150. "view_mode": "form",
  151. }
  152. def action_auto_ask(self):
  153. """Automatically ask for consent."""
  154. templated = self.filtered("activity_id.consent_template_id")
  155. automated = templated.filtered(
  156. lambda one: one.activity_id.consent_required == "auto"
  157. )
  158. automated._send_consent_notification()
  159. def action_answer(self, answer, metadata=False):
  160. """Process answer.
  161. :param bool answer:
  162. Did the subject accept?
  163. :param str metadata:
  164. Metadata from last user acceptance or rejection request.
  165. """
  166. self.write({"state": "answered", "accepted": answer, "last_metadata": metadata})