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.

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