stacker.news/api/resolvers/referrals.js

57 lines
2.1 KiB
JavaScript
Raw Normal View History

import { GraphQLError } from 'graphql'
import { withClause, intervalClause } from './growth'
import { timeUnitForRange, whenRange } from '@/lib/time'
2022-12-19 22:27:52 +00:00
export default {
Query: {
referrals: async (parent, { when, from, to }, { models, me }) => {
2022-12-19 22:27:52 +00:00
if (!me) {
throw new GraphQLError('you must be logged in', { extensions: { code: 'UNAUTHENTICATED' } })
2022-12-19 22:27:52 +00:00
}
const range = whenRange(when, from, to)
2023-07-26 16:01:31 +00:00
const [{ totalSats }] = await models.$queryRawUnsafe(`
2022-12-19 22:27:52 +00:00
SELECT COALESCE(FLOOR(sum(msats) / 1000), 0) as "totalSats"
FROM "ReferralAct"
WHERE ${intervalClause(range, 'ReferralAct')}
AND "ReferralAct"."referrerId" = $3
`, ...range, Number(me.id))
2022-12-19 22:27:52 +00:00
2023-07-26 16:01:31 +00:00
const [{ totalReferrals }] = await models.$queryRawUnsafe(`
2023-07-27 00:18:42 +00:00
SELECT count(*)::INTEGER as "totalReferrals"
2022-12-19 22:27:52 +00:00
FROM users
WHERE ${intervalClause(range, 'users')}
AND "referrerId" = $3
2023-11-13 23:15:43 +00:00
`, ...range, Number(me.id))
2022-12-19 22:27:52 +00:00
2023-07-26 16:01:31 +00:00
const stats = await models.$queryRawUnsafe(
`${withClause(range)}
2022-12-19 22:27:52 +00:00
SELECT time, json_build_array(
json_build_object('name', 'referrals', 'value', count(*) FILTER (WHERE act = 'REFERREE')),
json_build_object('name', 'sats', 'value', FLOOR(COALESCE(sum(msats) FILTER (WHERE act IN ('BOOST', 'STREAM', 'FEE')), 0)))
) AS data
FROM times
LEFT JOIN
((SELECT "ReferralAct".created_at, "ReferralAct".msats / 1000.0 as msats, "ItemAct".act::text as act
FROM "ReferralAct"
JOIN "ItemAct" ON "ItemAct".id = "ReferralAct"."itemActId"
WHERE ${intervalClause(range, 'ReferralAct')}
AND "ReferralAct"."referrerId" = $3)
2022-12-19 22:27:52 +00:00
UNION ALL
(SELECT created_at, 0.0 as sats, 'REFERREE' as act
FROM users
WHERE ${intervalClause(range, 'users')}
AND "referrerId" = $3)) u ON time = date_trunc('${timeUnitForRange(range)}', u.created_at)
2022-12-19 22:27:52 +00:00
GROUP BY time
ORDER BY time ASC`, ...range, Number(me.id))
2022-12-19 22:27:52 +00:00
return {
totalSats,
totalReferrals,
stats
}
}
}
}