Skip to content

Commit 6c4fbb3

Browse files
committed
territoryRevenue; territoryStatus; wip referralReward
1 parent 89187db commit 6c4fbb3

File tree

2 files changed

+57
-4
lines changed

2 files changed

+57
-4
lines changed

lib/webPush.js

Lines changed: 36 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import webPush from 'web-push'
22
import removeMd from 'remove-markdown'
33
import { COMMENT_DEPTH_LIMIT, FOUND_BLURBS, LOST_BLURBS } from './constants'
44
import { msatsToSats, numWithUnits } from './format'
5+
import { nextBillingWithGrace } from '@/lib/territory'
56
import models from '@/api/models'
67
import { isMuted } from '@/lib/user'
78
import { Prisma } from '@prisma/client'
@@ -103,6 +104,7 @@ async function sendUserNotification (userId, notification) {
103104
const subscriptions = await models.pushSubscription.findMany({
104105
where: { userId, ...userFilter }
105106
})
107+
console.log('notification', payload)
106108
await Promise.allSettled(
107109
subscriptions.map(subscription => sendNotification(subscription, payload))
108110
)
@@ -373,16 +375,49 @@ export const notifyTerritoryTransfer = async ({ models, sub, to }) => {
373375
}
374376
}
375377

378+
export const notifyTerritoryStatusChange = async ({ sub }) => {
379+
const dueDate = nextBillingWithGrace(sub)
380+
const days = Math.ceil((new Date(dueDate) - new Date()) / (1000 * 60 * 60 * 24))
381+
const timeLeft = days === 1 ? 'tomorrow' : `in ${days} days`
382+
const title = sub.status === 'ACTIVE'
383+
? 'your territory is active again'
384+
: sub.status === 'GRACE'
385+
? `your territory payment for ~${sub.name} is due or your territory will be archived ${timeLeft}`
386+
: `~${sub.name} has been archived!`
387+
388+
try {
389+
await sendUserNotification(sub.userId, { title, tag: `TERRITORY_STATUS_CHANGE-${sub.name}` })
390+
} catch (err) {
391+
console.error(err)
392+
}
393+
}
394+
395+
export const notifyTerritoryRevenue = async (subAct) => {
396+
const fmt = msats => numWithUnits(msatsToSats(msats, { abbreviate: false }))
397+
const title = `you earned ${fmt(subAct.msats)} in revenue from ~${subAct.subName}`
398+
try {
399+
await sendUserNotification(subAct.userId, { title, tag: `TERRITORY_REVENUE-${subAct.subName}` })
400+
} catch (err) {
401+
console.error(err)
402+
}
403+
}
404+
405+
// TODO: needs testing, fix rewards not working first
376406
export async function notifyEarner (userId, earnings) {
377407
const fmt = msats => numWithUnits(msatsToSats(msats, { abbreviate: false }))
378408

409+
// TODO: remove
410+
console.log('notifying earners', JSON.stringify(earnings, null, 2))
411+
379412
const title = `you stacked ${fmt(earnings.msats)} in rewards`
380413
const tag = 'EARN'
381414
let body = ''
382415
if (earnings.POST) body += `#${earnings.POST.bestRank} among posts with ${fmt(earnings.POST.msats)} in total\n`
383416
if (earnings.COMMENT) body += `#${earnings.COMMENT.bestRank} among comments with ${fmt(earnings.COMMENT.msats)} in total\n`
384417
if (earnings.TIP_POST) body += `#${earnings.TIP_POST.bestRank} in post zapping with ${fmt(earnings.TIP_POST.msats)} in total\n`
385-
if (earnings.TIP_COMMENT) body += `#${earnings.TIP_COMMENT.bestRank} in comment zapping with ${fmt(earnings.TIP_COMMENT.msats)} in total`
418+
if (earnings.TIP_COMMENT) body += `#${earnings.TIP_COMMENT.bestRank} in comment zapping with ${fmt(earnings.TIP_COMMENT.msats)} in total\n`
419+
if (earnings.FOREVER_REFERRAL) body += `#${earnings.FOREVER_REFERRAL.bestRank} in referral rewards with ${fmt(earnings.FOREVER_REFERRAL.msats)} in total\n`
420+
if (earnings.ONE_DAY_REFERRAL) body += `#${earnings.ONE_DAY_REFERRAL.bestRank} in referral rewards with ${fmt(earnings.ONE_DAY_REFERRAL.msats)} in total`
386421

387422
try {
388423
await sendUserNotification(userId, { title, tag, body })

worker/territory.js

Lines changed: 21 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,17 +3,18 @@ import performPaidAction from '@/api/paidAction'
33
import { PAID_ACTION_PAYMENT_METHODS } from '@/lib/constants'
44
import { nextBillingWithGrace } from '@/lib/territory'
55
import { datePivot } from '@/lib/time'
6+
import { notifyTerritoryStatusChange, notifyTerritoryRevenue } from '@/lib/webPush'
67

78
export async function territoryBilling ({ data: { subName }, boss, models }) {
8-
const sub = await models.sub.findUnique({
9+
let sub = await models.sub.findUnique({
910
where: {
1011
name: subName
1112
}
1213
})
1314

1415
async function territoryStatusUpdate () {
1516
if (sub.status !== 'STOPPED') {
16-
await models.sub.update({
17+
sub = await models.sub.update({
1718
include: { user: true },
1819
where: {
1920
name: subName
@@ -24,7 +25,8 @@ export async function territoryBilling ({ data: { subName }, boss, models }) {
2425
}
2526
})
2627
}
27-
28+
// send push notification with the new status
29+
await notifyTerritoryStatusChange({ sub })
2830
// retry billing in one day
2931
await boss.send('territoryBilling', { subName }, { startAfter: datePivot(new Date(), { days: 1 }) })
3032
}
@@ -44,6 +46,9 @@ export async function territoryBilling ({ data: { subName }, boss, models }) {
4446
})
4547
if (!result) {
4648
throw new Error('not enough fee credits to auto-renew territory')
49+
} else if (sub.status === 'GRACE' && result.status === 'ACTIVE') {
50+
// if the sub was in grace and we successfully auto-renewed it, send a push notification
51+
await notifyTerritoryStatusChange({ sub })
4752
}
4853
} catch (e) {
4954
console.error(e)
@@ -90,4 +95,17 @@ export async function territoryRevenue ({ models }) {
9095
"stackedMsats" = users."stackedMsats" + "SubActResultTotal".total_msats
9196
FROM "SubActResultTotal"
9297
WHERE users.id = "SubActResultTotal"."userId"`
98+
99+
const territoryRevenue = await models.subAct.findMany({
100+
where: {
101+
createdAt: { // retrieve revenue calculated in the last hour
102+
gte: datePivot(new Date(), { hours: -1 })
103+
},
104+
type: 'REVENUE'
105+
}
106+
})
107+
108+
await Promise.allSettled(
109+
territoryRevenue.map(subAct => notifyTerritoryRevenue(subAct))
110+
)
93111
}

0 commit comments

Comments
 (0)