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.

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