Răsfoiți Sursa

Merge pull request #18593 from overleaf/jdt-mailchimp-tagging

allow adding and removing tags from users in mailchimp

GitOrigin-RevId: 15e491d3346877e86d55fb6eccb45813daa41e88
Jimmy Domagala-Tang 2 ani în urmă
părinte
comite
d3c270369d

+ 8 - 0
services/web/app/src/Features/Newsletter/MailChimpClient.js

@@ -41,6 +41,14 @@ class MailChimpClient {
     return await this.request(path, options)
   }
 
+  async post(path, body) {
+    const options = Object.assign({}, this.fetchOptions)
+    options.method = 'POST'
+    options.json = body
+
+    return await this.request(path, options)
+  }
+
   async delete(path) {
     const options = Object.assign({}, this.fetchOptions)
     options.method = 'DELETE'

+ 39 - 0
services/web/app/src/Features/Newsletter/MailChimpProvider.js

@@ -46,6 +46,8 @@ function makeMailchimpProvider(listName, listId) {
     subscribe,
     unsubscribe,
     changeEmail,
+    tag,
+    removeTag,
   }
 
   async function subscribed(user) {
@@ -85,6 +87,38 @@ function makeMailchimpProvider(listName, listId) {
     }
   }
 
+  async function tag(user, tag) {
+    try {
+      const path = getMemberTagsPath(user.email)
+      await mailchimp.post(path, {
+        tags: [{ name: tag, status: 'active' }],
+      })
+      logger.debug({ user, listName }, `finished adding ${tag} to user`)
+    } catch (err) {
+      throw OError.tag(err, `error adding ${tag} to user`, {
+        userId: user._id,
+        listName,
+        tag,
+      })
+    }
+  }
+
+  async function removeTag(user, tag) {
+    try {
+      const path = getMemberTagsPath(user.email)
+      await mailchimp.post(path, {
+        tags: [{ name: tag, status: 'inactive' }],
+      })
+      logger.debug({ user, listName }, `finished removing ${tag} from user`)
+    } catch (err) {
+      throw OError.tag(err, `error removing ${tag} from user`, {
+        userId: user._id,
+        listName,
+        tag,
+      })
+    }
+  }
+
   async function unsubscribe(user, options = {}) {
     try {
       const path = getSubscriberPath(user.email)
@@ -208,6 +242,11 @@ function makeMailchimpProvider(listName, listId) {
     return `/lists/${MAILCHIMP_LIST_ID}/members/${emailHash}`
   }
 
+  function getMemberTagsPath(email) {
+    const emailHash = hashEmail(email)
+    return `/lists/${MAILCHIMP_LIST_ID}/members/${emailHash}/tags`
+  }
+
   function hashEmail(email) {
     return crypto.createHash('md5').update(email.toLowerCase()).digest('hex')
   }