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
11 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
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
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
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
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. # -*- coding: utf-8 -*-
  2. # Copyright 2018 Tecnativa - Jairo Llopis
  3. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
  4. from contextlib import contextmanager
  5. from odoo.exceptions import ValidationError
  6. from odoo.tests.common import HttpCase
  7. class ActivityCase(HttpCase):
  8. def setUp(self):
  9. super(ActivityCase, self).setUp()
  10. # HACK https://github.com/odoo/odoo/issues/12237
  11. # TODO Remove hack in v12
  12. self._oldenv = self.env
  13. self.env = self._oldenv(self.cursor())
  14. # HACK end
  15. self.cron = self.env.ref("privacy_consent.cron_auto_consent")
  16. self.cron_mail_queue = self.env.ref(
  17. "mail.ir_cron_mail_scheduler_action")
  18. self.update_opt_out = self.env.ref("privacy_consent.update_opt_out")
  19. self.mt_consent_consent_new = self.env.ref(
  20. "privacy_consent.mt_consent_consent_new")
  21. self.mt_consent_acceptance_changed = self.env.ref(
  22. "privacy_consent.mt_consent_acceptance_changed")
  23. self.mt_consent_state_changed = self.env.ref(
  24. "privacy_consent.mt_consent_state_changed")
  25. # Some partners to ask for consent
  26. self.partners = self.env["res.partner"]
  27. self.partners += self.partners.create({
  28. "name": "consent-partner-0",
  29. "email": "partner0@example.com",
  30. "notify_email": "none",
  31. "opt_out": False,
  32. })
  33. self.partners += self.partners.create({
  34. "name": "consent-partner-1",
  35. "email": "partner1@example.com",
  36. "notify_email": "always",
  37. "opt_out": True,
  38. })
  39. self.partners += self.partners.create({
  40. "name": "consent-partner-2",
  41. "email": "partner2@example.com",
  42. "opt_out": False,
  43. })
  44. # Partner without email, on purpose
  45. self.partners += self.partners.create({
  46. "name": "consent-partner-3",
  47. "opt_out": True,
  48. })
  49. # Activity without consent
  50. self.activity_noconsent = self.env["privacy.activity"].create({
  51. "name": "activity_noconsent",
  52. "description": "I'm activity 1",
  53. })
  54. # Activity with auto consent, for all partners
  55. self.activity_auto = self.env["privacy.activity"].create({
  56. "name": "activity_auto",
  57. "description": "I'm activity auto",
  58. "subject_find": True,
  59. "subject_domain": repr([("id", "in", self.partners.ids)]),
  60. "consent_required": "auto",
  61. "default_consent": True,
  62. "server_action_id": self.update_opt_out.id,
  63. })
  64. # Activity with manual consent, skipping partner 0
  65. self.activity_manual = self.env["privacy.activity"].create({
  66. "name": "activity_manual",
  67. "description": "I'm activity 3",
  68. "subject_find": True,
  69. "subject_domain": repr([("id", "in", self.partners[1:].ids)]),
  70. "consent_required": "manual",
  71. "default_consent": False,
  72. "server_action_id": self.update_opt_out.id,
  73. })
  74. # HACK https://github.com/odoo/odoo/issues/12237
  75. # TODO Remove hack in v12
  76. def tearDown(self):
  77. self.env = self._oldenv
  78. super(ActivityCase, self).tearDown()
  79. # HACK https://github.com/odoo/odoo/issues/12237
  80. # TODO Remove hack in v12
  81. @contextmanager
  82. def release_cr(self):
  83. self.env.cr.release()
  84. yield
  85. self.env.cr.acquire()
  86. def check_activity_auto_properly_sent(self):
  87. """Check emails sent by ``self.activity_auto``."""
  88. consents = self.env["privacy.consent"].search([
  89. ("activity_id", "=", self.activity_auto.id),
  90. ])
  91. # Check pending mails
  92. for consent in consents:
  93. self.assertEqual(consent.state, "draft")
  94. messages = consent.message_ids
  95. self.assertEqual(len(messages), 2)
  96. # Check sent mails
  97. self.cron_mail_queue.method_direct_trigger()
  98. for consent in consents:
  99. self.assertEqual(consent.state, "sent")
  100. messages = consent.message_ids
  101. self.assertEqual(len(messages), 3)
  102. # 2nd message notifies creation
  103. self.assertEqual(
  104. messages[2].subtype_id,
  105. self.mt_consent_consent_new,
  106. )
  107. # 3rd message notifies subject
  108. # Placeholder links should be logged
  109. self.assertTrue("/privacy/consent/accept/" in messages[1].body)
  110. self.assertTrue("/privacy/consent/reject/" in messages[1].body)
  111. # Tokenized links shouldn't be logged
  112. self.assertFalse(consent._url(True) in messages[1].body)
  113. self.assertFalse(consent._url(False) in messages[1].body)
  114. # 4th message contains the state change
  115. self.assertEqual(
  116. messages[0].subtype_id,
  117. self.mt_consent_state_changed,
  118. )
  119. # Partner's opt_out should be synced with default consent
  120. self.assertFalse(consent.partner_id.opt_out)
  121. def test_default_template(self):
  122. """We have a good mail template by default."""
  123. good = self.env.ref("privacy_consent.template_consent")
  124. self.assertEqual(
  125. self.activity_noconsent.consent_template_id,
  126. good,
  127. )
  128. self.assertEqual(
  129. self.activity_noconsent.consent_template_default_body_html,
  130. good.body_html,
  131. )
  132. self.assertEqual(
  133. self.activity_noconsent.consent_template_default_subject,
  134. good.subject,
  135. )
  136. def test_find_subject_if_consent_required(self):
  137. """If user wants to require consent, it needs subjects."""
  138. # Test the onchange helper
  139. onchange_activity1 = self.env["privacy.activity"].new(
  140. self.activity_noconsent.copy_data()[0])
  141. self.assertFalse(onchange_activity1.subject_find)
  142. onchange_activity1.consent_required = "auto"
  143. onchange_activity1._onchange_consent_required_subject_find()
  144. self.assertTrue(onchange_activity1.subject_find)
  145. # Test very dumb user that forces an error
  146. with self.assertRaises(ValidationError):
  147. self.activity_noconsent.consent_required = "manual"
  148. def test_template_required_auto(self):
  149. """Automatic consent activities need a template."""
  150. self.activity_noconsent.subject_find = True
  151. self.activity_noconsent.consent_template_id = False
  152. self.activity_noconsent.consent_required = "manual"
  153. with self.assertRaises(ValidationError):
  154. self.activity_noconsent.consent_required = "auto"
  155. def test_generate_manually(self):
  156. """Manually-generated consents work as expected."""
  157. self.partners.write({"opt_out": False})
  158. result = self.activity_manual.action_new_consents()
  159. self.assertEqual(result["res_model"], "privacy.consent")
  160. consents = self.env[result["res_model"]].search(result["domain"])
  161. self.assertEqual(consents.mapped("state"), ["draft"] * 2)
  162. self.assertEqual(consents.mapped("partner_id.opt_out"), [False] * 2)
  163. self.assertEqual(consents.mapped("accepted"), [False] * 2)
  164. self.assertEqual(consents.mapped("last_metadata"), [False] * 2)
  165. # Check sent mails
  166. messages = consents.mapped("message_ids")
  167. self.assertEqual(len(messages), 2)
  168. subtypes = messages.mapped("subtype_id")
  169. self.assertTrue(subtypes & self.mt_consent_consent_new)
  170. self.assertFalse(subtypes & self.mt_consent_acceptance_changed)
  171. self.assertFalse(subtypes & self.mt_consent_state_changed)
  172. # Send one manual request
  173. action = consents[0].action_manual_ask()
  174. self.assertEqual(action["res_model"], "mail.compose.message")
  175. composer = self.env[action["res_model"]] \
  176. .with_context(active_ids=consents[0].ids,
  177. active_model=consents._name,
  178. **action["context"]).create({})
  179. composer.onchange_template_id_wrapper()
  180. composer.send_mail()
  181. messages = consents.mapped("message_ids") - messages
  182. self.assertEqual(len(messages), 2)
  183. self.assertEqual(messages[0].subtype_id, self.mt_consent_state_changed)
  184. self.assertEqual(consents.mapped("state"), ["sent", "draft"])
  185. self.assertEqual(consents.mapped("partner_id.opt_out"), [True, False])
  186. # Placeholder links should be logged
  187. self.assertTrue("/privacy/consent/accept/" in messages[1].body)
  188. self.assertTrue("/privacy/consent/reject/" in messages[1].body)
  189. # Tokenized links shouldn't be logged
  190. accept_url = consents[0]._url(True)
  191. reject_url = consents[0]._url(False)
  192. self.assertNotIn(accept_url, messages[1].body)
  193. self.assertNotIn(reject_url, messages[1].body)
  194. # Visit tokenized accept URL
  195. with self.release_cr():
  196. result = self.url_open(accept_url).read()
  197. self.assertIn("accepted", result)
  198. self.assertIn(reject_url, result)
  199. self.assertIn(self.activity_manual.name, result)
  200. self.assertIn(self.activity_manual.description, result)
  201. consents.invalidate_cache()
  202. self.assertEqual(consents.mapped("accepted"), [True, False])
  203. self.assertTrue(consents[0].last_metadata)
  204. self.assertFalse(consents[0].partner_id.opt_out)
  205. self.assertEqual(consents.mapped("state"), ["answered", "draft"])
  206. self.assertEqual(
  207. consents[0].message_ids[0].subtype_id,
  208. self.mt_consent_acceptance_changed,
  209. )
  210. # Visit tokenized reject URL
  211. with self.release_cr():
  212. result = self.url_open(reject_url).read()
  213. self.assertIn("rejected", result)
  214. self.assertIn(accept_url, result)
  215. self.assertIn(self.activity_manual.name, result)
  216. self.assertIn(self.activity_manual.description, result)
  217. consents.invalidate_cache()
  218. self.assertEqual(consents.mapped("accepted"), [False, False])
  219. self.assertTrue(consents[0].last_metadata)
  220. self.assertTrue(consents[0].partner_id.opt_out)
  221. self.assertEqual(consents.mapped("state"), ["answered", "draft"])
  222. self.assertEqual(
  223. consents[0].message_ids[0].subtype_id,
  224. self.mt_consent_acceptance_changed,
  225. )
  226. self.assertFalse(consents[1].last_metadata)
  227. def test_generate_automatically(self):
  228. """Automatically-generated consents work as expected."""
  229. result = self.activity_auto.action_new_consents()
  230. self.assertEqual(result["res_model"], "privacy.consent")
  231. self.check_activity_auto_properly_sent()
  232. def test_generate_cron(self):
  233. """Cron-generated consents work as expected."""
  234. self.cron.method_direct_trigger()
  235. self.check_activity_auto_properly_sent()
  236. def test_mail_template_without_links(self):
  237. """Cannot create mail template without needed links."""
  238. with self.assertRaises(ValidationError):
  239. self.activity_manual.consent_template_id.body_html = "No links :("