Skip to content
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

fix: missing push notifications #1856

Draft
wants to merge 3 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 36 additions & 1 deletion lib/webPush.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import webPush from 'web-push'
import removeMd from 'remove-markdown'
import { COMMENT_DEPTH_LIMIT, FOUND_BLURBS, LOST_BLURBS } from './constants'
import { msatsToSats, numWithUnits } from './format'
import { nextBillingWithGrace } from '@/lib/territory'
import models from '@/api/models'
import { isMuted } from '@/lib/user'
import { Prisma } from '@prisma/client'
Expand Down Expand Up @@ -103,6 +104,7 @@ async function sendUserNotification (userId, notification) {
const subscriptions = await models.pushSubscription.findMany({
where: { userId, ...userFilter }
})
console.log('notification', payload)
await Promise.allSettled(
subscriptions.map(subscription => sendNotification(subscription, payload))
)
Expand Down Expand Up @@ -373,16 +375,49 @@ export const notifyTerritoryTransfer = async ({ models, sub, to }) => {
}
}

export const notifyTerritoryStatusChange = async ({ sub }) => {
const dueDate = nextBillingWithGrace(sub)
const days = Math.ceil((new Date(dueDate) - new Date()) / (1000 * 60 * 60 * 24))
const timeLeft = days === 1 ? 'tomorrow' : `in ${days} days`
const title = sub.status === 'ACTIVE'
? 'your territory is active again'
: sub.status === 'GRACE'
? `your territory payment for ~${sub.name} is due or your territory will be archived ${timeLeft}`
: `~${sub.name} has been archived!`

try {
await sendUserNotification(sub.userId, { title, tag: `TERRITORY_STATUS_CHANGE-${sub.name}` })
} catch (err) {
console.error(err)
}
}

export const notifyTerritoryRevenue = async (subAct) => {
const fmt = msats => numWithUnits(msatsToSats(msats, { abbreviate: false }))
const title = `you earned ${fmt(subAct.msats)} in revenue from ~${subAct.subName}`
try {
await sendUserNotification(subAct.userId, { title, tag: `TERRITORY_REVENUE-${subAct.subName}` })
} catch (err) {
console.error(err)
}
}

// TODO: needs testing, fix rewards not working first
export async function notifyEarner (userId, earnings) {
const fmt = msats => numWithUnits(msatsToSats(msats, { abbreviate: false }))

// TODO: remove
console.log('notifying earners', JSON.stringify(earnings, null, 2))

const title = `you stacked ${fmt(earnings.msats)} in rewards`
const tag = 'EARN'
let body = ''
if (earnings.POST) body += `#${earnings.POST.bestRank} among posts with ${fmt(earnings.POST.msats)} in total\n`
if (earnings.COMMENT) body += `#${earnings.COMMENT.bestRank} among comments with ${fmt(earnings.COMMENT.msats)} in total\n`
if (earnings.TIP_POST) body += `#${earnings.TIP_POST.bestRank} in post zapping with ${fmt(earnings.TIP_POST.msats)} in total\n`
if (earnings.TIP_COMMENT) body += `#${earnings.TIP_COMMENT.bestRank} in comment zapping with ${fmt(earnings.TIP_COMMENT.msats)} in total`
if (earnings.TIP_COMMENT) body += `#${earnings.TIP_COMMENT.bestRank} in comment zapping with ${fmt(earnings.TIP_COMMENT.msats)} in total\n`
if (earnings.ONE_DAY_REFERRAL) body += `in referral rewards with ${fmt(earnings.ONE_DAY_REFERRAL)} in total\n`
if (earnings.FOREVER_REFERRAL) body += `in lifetime referral rewards with ${fmt(earnings.FOREVER_REFERRAL)} in total`

try {
await sendUserNotification(userId, { title, tag, body })
Expand Down
16 changes: 16 additions & 0 deletions worker/earn.js
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,14 @@ export async function earn ({ name }) {
type: 'FOREVER_REFERRAL',
rank: earner.rank
}, { models }))

const userN = notifications[earner.foreverReferrerId] || {}
const prevMsats = userN.msats || 0
const msats = foreverReferrerEarnings + prevMsats
notifications[earner.foreverReferrerId] = {
...userN,
FOREVER_REFERRAL: msats
}
} else if (earner.oneDayReferrerId) {
// if the person doesn't have a forever referrer yet, they give double to their one day referrer
oneDayReferrerEarnings += foreverReferrerEarnings
Expand All @@ -162,6 +170,14 @@ export async function earn ({ name }) {
type: 'ONE_DAY_REFERRAL',
rank: earner.rank
}, { models }))

const userN = notifications[earner.oneDayReferrerId] || {}
const prevMsats = userN.msats || 0
const msats = oneDayReferrerEarnings + prevMsats
notifications[earner.oneDayReferrerId] = {
...userN,
ONE_DAY_REFERRAL: msats
}
}
}

Expand Down
24 changes: 21 additions & 3 deletions worker/territory.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,18 @@ import performPaidAction from '@/api/paidAction'
import { PAID_ACTION_PAYMENT_METHODS } from '@/lib/constants'
import { nextBillingWithGrace } from '@/lib/territory'
import { datePivot } from '@/lib/time'
import { notifyTerritoryStatusChange, notifyTerritoryRevenue } from '@/lib/webPush'

export async function territoryBilling ({ data: { subName }, boss, models }) {
const sub = await models.sub.findUnique({
let sub = await models.sub.findUnique({
where: {
name: subName
}
})

async function territoryStatusUpdate () {
if (sub.status !== 'STOPPED') {
await models.sub.update({
sub = await models.sub.update({
include: { user: true },
where: {
name: subName
Expand All @@ -24,7 +25,8 @@ export async function territoryBilling ({ data: { subName }, boss, models }) {
}
})
}

// send push notification with the new status
await notifyTerritoryStatusChange({ sub })
// retry billing in one day
await boss.send('territoryBilling', { subName }, { startAfter: datePivot(new Date(), { days: 1 }) })
}
Expand All @@ -44,6 +46,9 @@ export async function territoryBilling ({ data: { subName }, boss, models }) {
})
if (!result) {
throw new Error('not enough fee credits to auto-renew territory')
} else if (sub.status === 'GRACE' && result.status === 'ACTIVE') {
// if the sub was in grace and we successfully auto-renewed it, send a push notification
await notifyTerritoryStatusChange({ sub })
}
} catch (e) {
console.error(e)
Expand Down Expand Up @@ -90,4 +95,17 @@ export async function territoryRevenue ({ models }) {
"stackedMsats" = users."stackedMsats" + "SubActResultTotal".total_msats
FROM "SubActResultTotal"
WHERE users.id = "SubActResultTotal"."userId"`

const territoryRevenue = await models.subAct.findMany({
where: {
createdAt: { // retrieve revenue calculated in the last hour
gte: datePivot(new Date(), { hours: -1 })
},
type: 'REVENUE'
}
})

await Promise.allSettled(
territoryRevenue.map(subAct => notifyTerritoryRevenue(subAct))
)
}