Skip to content

Commit

Permalink
Selectively refresh stats for opened campaigns
Browse files Browse the repository at this point in the history
  • Loading branch information
pushchris committed Dec 27, 2024
1 parent 69a5e9b commit 54981a4
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 2 deletions.
4 changes: 3 additions & 1 deletion apps/platform/src/campaigns/CampaignInteractJob.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import App from '../app'
import { Job } from '../queue'
import { unsubscribe } from '../subscriptions/SubscriptionService'
import { CampaignSend } from './Campaign'
import { getCampaignSend, updateCampaignSend } from './CampaignService'
import { CacheKeys, getCampaignSend, updateCampaignSend } from './CampaignService'

interface CampaignIteraction {
user_id: number
Expand All @@ -25,6 +26,7 @@ export default class CampaignInteractJob extends Job {

if (type === 'opened' && !send.opened_at) {
await updateCampaignSend(send.id, { opened_at: new Date() })
await App.main.redis.sadd(CacheKeys.pendingStats, campaign_id)
}

if (type === 'clicked') {
Expand Down
4 changes: 4 additions & 0 deletions apps/platform/src/campaigns/CampaignService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,10 @@ import Template from '../render/Template'
import { differenceInDays, subDays } from 'date-fns'
import { raw } from '../core/Model'

export const CacheKeys = {
pendingStats: 'campaigns:pending_stats',
}

export const pagedCampaigns = async (params: PageParams, projectId: number) => {
const result = await Campaign.search(
{ ...params, fields: ['name'] },
Expand Down
7 changes: 6 additions & 1 deletion apps/platform/src/campaigns/CampaignStateJob.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { subDays } from 'date-fns'
import { Job } from '../queue'
import Campaign from './Campaign'
import { updateCampaignProgress } from './CampaignService'
import { CacheKeys, updateCampaignProgress } from './CampaignService'
import App from '../app'

export default class CampaignStateJob extends Job {
static $name = 'campaign_state_job'
Expand All @@ -10,15 +11,19 @@ export default class CampaignStateJob extends Job {

// Fetch anything that is currently running or has finished
// within the last two days
const openedCampaignIds = await App.main.redis.smembers(CacheKeys.pendingStats)
const campaigns = await Campaign.query()
.whereIn('state', ['scheduled', 'running'])
.orWhere(function(qb) {
qb.where('state', 'finished')
.where('send_at', '>', subDays(Date.now(), 2))
})
.orWhereIn('id', openedCampaignIds.map(id => parseInt(id, 10))) as Campaign[]

for (const campaign of campaigns) {
await updateCampaignProgress(campaign)
}

await App.main.redis.srem(CacheKeys.pendingStats, ...campaigns.map(c => c.id))
}
}

0 comments on commit 54981a4

Please sign in to comment.