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.

187 lines
6.0 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()`.
5 years ago
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()`.
5 years ago
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2018 Tecnativa - Jairo Llopis
  3. # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
  4. import hashlib
  5. import hmac
  6. from odoo import api, fields, models
  7. class PrivacyConsent(models.Model):
  8. _name = 'privacy.consent'
  9. _description = "Consent of data processing"
  10. _inherit = "mail.thread"
  11. _rec_name = "partner_id"
  12. _sql_constraints = [
  13. ("unique_partner_activity", "UNIQUE(partner_id, activity_id)",
  14. "Duplicated partner in this data processing activity"),
  15. ]
  16. active = fields.Boolean(
  17. default=True,
  18. index=True,
  19. )
  20. accepted = fields.Boolean(
  21. track_visibility="onchange",
  22. help="Indicates current acceptance status, which can come from "
  23. "subject's last answer, or from the default specified in the "
  24. "related data processing activity.",
  25. )
  26. last_metadata = fields.Text(
  27. readonly=True,
  28. track_visibility="onchange",
  29. help="Metadata from the last acceptance or rejection by the subject",
  30. )
  31. partner_id = fields.Many2one(
  32. "res.partner",
  33. "Subject",
  34. required=True,
  35. readonly=True,
  36. track_visibility="onchange",
  37. help="Subject asked for consent.",
  38. )
  39. activity_id = fields.Many2one(
  40. "privacy.activity",
  41. "Activity",
  42. readonly=True,
  43. required=True,
  44. track_visibility="onchange",
  45. )
  46. state = fields.Selection(
  47. selection=[
  48. ("draft", "Draft"),
  49. ("sent", "Awaiting response"),
  50. ("answered", "Answered"),
  51. ],
  52. default="draft",
  53. readonly=True,
  54. required=True,
  55. track_visibility="onchange",
  56. )
  57. def _track_subtype(self, init_values):
  58. """Return specific subtypes."""
  59. if self.env.context.get("subject_answering"):
  60. return "privacy_consent.mt_consent_acceptance_changed"
  61. if "activity_id" in init_values or "partner_id" in init_values:
  62. return "privacy_consent.mt_consent_consent_new"
  63. if "state" in init_values:
  64. return "privacy_consent.mt_consent_state_changed"
  65. return super(PrivacyConsent, self)._track_subtype(init_values)
  66. def _token(self):
  67. """Secret token to publicly authenticate this record."""
  68. secret = self.env["ir.config_parameter"].sudo().get_param(
  69. "database.secret")
  70. params = "{}-{}-{}-{}".format(
  71. self.env.cr.dbname,
  72. self.id,
  73. self.partner_id.id,
  74. self.activity_id.id,
  75. )
  76. return hmac.new(
  77. secret.encode('utf-8'),
  78. params.encode('utf-8'),
  79. hashlib.sha512,
  80. ).hexdigest()
  81. def _url(self, accept):
  82. """Tokenized URL to let subject decide consent.
  83. :param bool accept:
  84. Indicates if you want the acceptance URL, or the rejection one.
  85. """
  86. return "/privacy/consent/{}/{}/{}?db={}".format(
  87. "accept" if accept else "reject",
  88. self.id,
  89. self._token(),
  90. self.env.cr.dbname,
  91. )
  92. def _send_consent_notification(self):
  93. """Send email notification to subject."""
  94. for one in self.with_context(tpl_force_default_to=True,
  95. mail_notify_user_signature=False,
  96. mail_auto_subscribe_no_notify=True):
  97. one.activity_id.consent_template_id.send_mail(one.id)
  98. def _run_action(self):
  99. """Execute server action defined in data processing activity."""
  100. for one in self:
  101. # Always skip draft consents
  102. if one.state == "draft":
  103. continue
  104. action = one.activity_id.server_action_id.with_context(
  105. active_id=one.id,
  106. active_ids=one.ids,
  107. active_model=one._name,
  108. )
  109. action.run()
  110. @api.model
  111. def create(self, vals):
  112. """Run server action on create."""
  113. result = super(PrivacyConsent,
  114. self.with_context(mail_create_nolog=True)).create(vals)
  115. # Sync the default acceptance status
  116. result.sudo()._run_action()
  117. return result
  118. def write(self, vals):
  119. """Run server action on update."""
  120. result = super(PrivacyConsent, self).write(vals)
  121. self._run_action()
  122. return result
  123. def message_get_suggested_recipients(self):
  124. result = super(PrivacyConsent, self) \
  125. .message_get_suggested_recipients()
  126. reason = self._fields["partner_id"].string
  127. for one in self:
  128. one._message_add_suggested_recipient(
  129. result,
  130. partner=one.partner_id,
  131. reason=reason,
  132. )
  133. return result
  134. def action_manual_ask(self):
  135. """Let user manually ask for consent."""
  136. return {
  137. "context": {
  138. "default_composition_mode": "mass_mail",
  139. "default_model": self._name,
  140. "default_res_id": self.id,
  141. "default_template_id": self.activity_id.consent_template_id.id,
  142. "default_use_template": True,
  143. "tpl_force_default_to": True,
  144. },
  145. "force_email": True,
  146. "res_model": "mail.compose.message",
  147. "target": "new",
  148. "type": "ir.actions.act_window",
  149. "view_mode": "form",
  150. }
  151. def action_auto_ask(self):
  152. """Automatically ask for consent."""
  153. templated = self.filtered("activity_id.consent_template_id")
  154. automated = templated.filtered(
  155. lambda one: one.activity_id.consent_required == "auto")
  156. automated._send_consent_notification()
  157. def action_answer(self, answer, metadata=False):
  158. """Process answer.
  159. :param bool answer:
  160. Did the subject accept?
  161. :param str metadata:
  162. Metadata from last user acceptance or rejection request.
  163. """
  164. self.write({
  165. "state": "answered",
  166. "accepted": answer,
  167. "last_metadata": metadata,
  168. })