-
Notifications
You must be signed in to change notification settings - Fork 223
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
MNTOR-3919: cronjob WIP for churn emails #5495
Draft
mansaj
wants to merge
12
commits into
main
Choose a base branch
from
MNTOR-3919
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+290
−8
Draft
Changes from 8 commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
c91b346
feat: add cronjob for churn discount
mansaj b85fcf0
Merge branch 'main' into MNTOR-3919
mansaj 1533e8f
feat: discount email cron job
mansaj b6d5ec9
Merge branch 'main' into MNTOR-3919
mansaj e6084b3
feat: more logic for churn email
mansaj a1a3719
feat: filter the results to the batch we want to send now
mansaj 78f0831
feat: no need for batch
mansaj 3b792a5
feat: fix logs
mansaj 3e5199c
fix: hide unused imports
mansaj c4025e2
fix: continue when sent date is present
mansaj e565c89
fix: why is there console log
mansaj 8d30d8d
feat: subscriber churns upsert and table
mansaj File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,130 @@ | ||
/* This Source Code Form is subject to the terms of the Mozilla Public | ||
* License, v. 2.0. If a copy of the MPL was not distributed with this | ||
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ | ||
import { | ||
getChurnPreventionEmailSentAt, | ||
markChurnPreventionEmailAsJustSent, | ||
} from "../../db/tables/subscribers"; | ||
// import { getFreeSubscribersWaitingForMonthlyEmail } from "../../db/tables/subscribers"; | ||
// import { getScanResultsWithBroker } from "../../db/tables/onerep_scans"; | ||
// import { updateEmailPreferenceForSubscriber } from "../../db/tables/subscriber_email_preferences"; | ||
// import { renderEmail } from "../../emails/renderEmail"; | ||
// import { MonthlyActivityFreeEmail } from "../../emails/templates/monthlyActivityFree/MonthlyActivityFreeEmail"; | ||
// import { getCronjobL10n } from "../../app/functions/l10n/cronjobs"; | ||
// import { sanitizeSubscriberRow } from "../../app/functions/server/sanitize"; | ||
// import { getDashboardSummary } from "../../app/functions/server/dashboard"; | ||
// import { getSubscriberBreaches } from "../../app/functions/server/getSubscriberBreaches"; | ||
// import { refreshStoredScanResults } from "../../app/functions/server/refreshStoredScanResults"; | ||
// import { getSignupLocaleCountry } from "../../emails/functions/getSignupLocaleCountry"; | ||
// import { getMonthlyActivityFreeUnsubscribeLink } from "../../app/functions/cronjobs/unsubscribeLinks"; | ||
// import { hasPremium } from "../../app/functions/universal/user"; | ||
import { SubscriberRow } from "knex/types/tables"; | ||
import createDbConnection from "../../db/connect"; | ||
import { logger } from "../../app/functions/server/logging"; | ||
import { initEmail, sendEmail, closeEmailPool } from "../../utils/email"; | ||
// Imports the Google Cloud client library | ||
import { Storage } from "@google-cloud/storage"; | ||
import csv from "csv-parser"; | ||
|
||
await run(); | ||
await createDbConnection().destroy(); | ||
|
||
interface FxaChurnSubscriber { | ||
userid: string; | ||
customer: string; | ||
created: string; | ||
nickname: string; | ||
intervl: "monthly" | "yearly"; | ||
intervl_count: number; | ||
plan_id: string; | ||
product_id: string; | ||
current_period_end: string; | ||
} | ||
|
||
async function readCSVFromBucket( | ||
bucketName: string, | ||
fileName: string, | ||
): Promise<FxaChurnSubscriber[]> { | ||
const storage = new Storage(); | ||
const bucket = storage.bucket(bucketName); | ||
const file = bucket.file(fileName); | ||
|
||
const results: FxaChurnSubscriber[] = []; | ||
|
||
return new Promise((resolve, reject) => { | ||
file | ||
.createReadStream() | ||
.pipe(csv()) | ||
.on("data", (row: FxaChurnSubscriber) => { | ||
/** | ||
* Verifies the interval is yearly | ||
* Ensures current_period_end exists | ||
* Checks if the time difference is less than or equal to 7 days (in milliseconds) | ||
* Makes sure the date is in the future | ||
*/ | ||
if ( | ||
row.intervl === "yearly" && | ||
row.current_period_end && | ||
new Date(row.current_period_end).getTime() - new Date().getTime() <= | ||
7 * 24 * 60 * 60 * 1000 && | ||
new Date(row.current_period_end).getTime() > new Date().getTime() | ||
) { | ||
results.push(row); | ||
} | ||
}) | ||
.on("error", reject) | ||
.on("end", () => { | ||
console.log( | ||
`CSV file successfully processed. Num of rows: ${results.length}`, | ||
); | ||
resolve(results); | ||
}); | ||
}); | ||
} | ||
|
||
async function run() { | ||
const bucketName = process.env.GCP_BUCKET; | ||
if (!bucketName) { | ||
throw `Bucket name isn't set ( process.env.GCP_BUCKET = ${process.env.GCP_BUCKET}), please set: 'GCP_BUCKET'`; | ||
} | ||
const fileName = "churningSubscribers.csv"; | ||
const subscribersToEmail = await readCSVFromBucket(bucketName, fileName); | ||
|
||
await initEmail(); | ||
|
||
for (const subscriber of subscribersToEmail) { | ||
try { | ||
// we need to query our db to make sure the email wasn't sent in the past | ||
const sentDate = await getChurnPreventionEmailSentAt( | ||
parseInt(subscriber.userid, 10), | ||
); | ||
if (sentDate) { | ||
logger.warn("send_churn_discount_email_warn", { | ||
subscriberId: subscriber.userid, | ||
message: `email already sent for the user at: ${sentDate}`, | ||
}); | ||
} | ||
// send email | ||
await sendChurnDiscountEmail(subscriber); | ||
logger.info("send_churn_discount_email_success", { | ||
subscriberId: subscriber.userid, | ||
}); | ||
} catch (error) { | ||
logger.error("send_churn_discount_email_error", { | ||
subscriberId: subscriber.userid, | ||
error, | ||
}); | ||
} | ||
} | ||
|
||
closeEmailPool(); | ||
console.log( | ||
`[${new Date(Date.now()).toISOString()}] Sent [${subscribersToEmail.length}] churn email to relevant subscribers.`, | ||
); | ||
} | ||
|
||
async function sendChurnDiscountEmail(subscriber: FxaChurnSubscriber) { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The rendering of the email part will go here @Vinnl |
||
console.log(`sent email to: ${subscriber.userid}`); | ||
// mark as sent | ||
// await markChurnPreventionEmailAsJustSent(parseInt(subscriber.userid, 10)) | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
this part is still TBD, I'm looking into perhaps a different way of getting the data in