allow viewing reward ranges
This commit is contained in:
parent
a40eb642a0
commit
b6c822f40e
|
@ -3,20 +3,33 @@ import { amountSchema, ssValidate } from '../../lib/validate'
|
||||||
import serialize from './serial'
|
import serialize from './serial'
|
||||||
import { ANON_USER_ID } from '../../lib/constants'
|
import { ANON_USER_ID } from '../../lib/constants'
|
||||||
import { getItem } from './item'
|
import { getItem } from './item'
|
||||||
|
import { datePivot, dayMonthYear } from '../../lib/time'
|
||||||
|
|
||||||
export default {
|
export default {
|
||||||
Query: {
|
Query: {
|
||||||
rewards: async (parent, { when }, { models }) => {
|
rewards: async (parent, { when }, { models }) => {
|
||||||
if (when && isNaN(new Date(when))) {
|
if (when) {
|
||||||
|
if (when.length > 2) {
|
||||||
|
throw new GraphQLError('too many dates', { extensions: { code: 'BAD_USER_INPUT' } })
|
||||||
|
}
|
||||||
|
when = when.map(w => {
|
||||||
|
if (isNaN(new Date(w))) {
|
||||||
throw new GraphQLError('invalid date', { extensions: { code: 'BAD_USER_INPUT' } })
|
throw new GraphQLError('invalid date', { extensions: { code: 'BAD_USER_INPUT' } })
|
||||||
}
|
}
|
||||||
|
return dayMonthYear(datePivot(new Date(w), { days: -1 }))
|
||||||
|
})
|
||||||
|
} else {
|
||||||
|
// default to tomorrow's rewards
|
||||||
|
when = [dayMonthYear(new Date())]
|
||||||
|
}
|
||||||
|
|
||||||
const [result] = await models.$queryRaw`
|
const results = await models.$queryRaw`
|
||||||
WITH day_cte (day) AS (
|
WITH days_cte (day) AS (
|
||||||
SELECT COALESCE(${when}::text::timestamp - interval '1 day', date_trunc('day', now() AT TIME ZONE 'America/Chicago'))
|
SELECT t::date
|
||||||
|
FROM generate_series(${when[0]}::text::timestamp, ${when[when.length - 1]}::text::timestamp, interval '1 day') AS t
|
||||||
)
|
)
|
||||||
SELECT coalesce(FLOOR(sum(sats)), 0) as total,
|
SELECT coalesce(FLOOR(sum(sats)), 0) as total,
|
||||||
COALESCE(${when}::text::timestamp, date_trunc('day', (now() + interval '1 day') AT TIME ZONE 'America/Chicago')) as time,
|
days_cte.day + interval '1 day' as time,
|
||||||
json_build_array(
|
json_build_array(
|
||||||
json_build_object('name', 'donations', 'value', coalesce(FLOOR(sum(sats) FILTER(WHERE type = 'DONATION')), 0)),
|
json_build_object('name', 'donations', 'value', coalesce(FLOOR(sum(sats) FILTER(WHERE type = 'DONATION')), 0)),
|
||||||
json_build_object('name', 'fees', 'value', coalesce(FLOOR(sum(sats) FILTER(WHERE type NOT IN ('BOOST', 'STREAM', 'DONATION', 'ANON'))), 0)),
|
json_build_object('name', 'fees', 'value', coalesce(FLOOR(sum(sats) FILTER(WHERE type NOT IN ('BOOST', 'STREAM', 'DONATION', 'ANON'))), 0)),
|
||||||
|
@ -24,16 +37,16 @@ export default {
|
||||||
json_build_object('name', 'jobs', 'value', coalesce(FLOOR(sum(sats) FILTER(WHERE type = 'STREAM')), 0)),
|
json_build_object('name', 'jobs', 'value', coalesce(FLOOR(sum(sats) FILTER(WHERE type = 'STREAM')), 0)),
|
||||||
json_build_object('name', 'anon''s stack', 'value', coalesce(FLOOR(sum(sats) FILTER(WHERE type = 'ANON')), 0))
|
json_build_object('name', 'anon''s stack', 'value', coalesce(FLOOR(sum(sats) FILTER(WHERE type = 'ANON')), 0))
|
||||||
) AS sources
|
) AS sources
|
||||||
FROM day_cte
|
FROM days_cte
|
||||||
CROSS JOIN LATERAL (
|
CROSS JOIN LATERAL (
|
||||||
(SELECT ("ItemAct".msats - COALESCE("ReferralAct".msats, 0)) / 1000.0 as sats, act::text as type
|
(SELECT ("ItemAct".msats - COALESCE("ReferralAct".msats, 0)) / 1000.0 as sats, act::text as type
|
||||||
FROM "ItemAct"
|
FROM "ItemAct"
|
||||||
LEFT JOIN "ReferralAct" ON "ReferralAct"."itemActId" = "ItemAct".id
|
LEFT JOIN "ReferralAct" ON "ReferralAct"."itemActId" = "ItemAct".id
|
||||||
WHERE date_trunc('day', "ItemAct".created_at AT TIME ZONE 'UTC' AT TIME ZONE 'America/Chicago') = day_cte.day AND "ItemAct".act <> 'TIP')
|
WHERE date_trunc('day', "ItemAct".created_at AT TIME ZONE 'UTC' AT TIME ZONE 'America/Chicago') = days_cte.day AND "ItemAct".act <> 'TIP')
|
||||||
UNION ALL
|
UNION ALL
|
||||||
(SELECT sats::FLOAT, 'DONATION' as type
|
(SELECT sats::FLOAT, 'DONATION' as type
|
||||||
FROM "Donation"
|
FROM "Donation"
|
||||||
WHERE date_trunc('day', created_at AT TIME ZONE 'UTC' AT TIME ZONE 'America/Chicago') = day_cte.day)
|
WHERE date_trunc('day', created_at AT TIME ZONE 'UTC' AT TIME ZONE 'America/Chicago') = days_cte.day)
|
||||||
UNION ALL
|
UNION ALL
|
||||||
-- any earnings from anon's stack that are not forwarded to other users
|
-- any earnings from anon's stack that are not forwarded to other users
|
||||||
(SELECT "ItemAct".msats / 1000.0 as sats, 'ANON' as type
|
(SELECT "ItemAct".msats / 1000.0 as sats, 'ANON' as type
|
||||||
|
@ -41,33 +54,47 @@ export default {
|
||||||
JOIN "ItemAct" ON "ItemAct"."itemId" = "Item".id
|
JOIN "ItemAct" ON "ItemAct"."itemId" = "Item".id
|
||||||
LEFT JOIN "ItemForward" ON "ItemForward"."itemId" = "Item".id
|
LEFT JOIN "ItemForward" ON "ItemForward"."itemId" = "Item".id
|
||||||
WHERE "Item"."userId" = ${ANON_USER_ID} AND "ItemAct".act = 'TIP'
|
WHERE "Item"."userId" = ${ANON_USER_ID} AND "ItemAct".act = 'TIP'
|
||||||
AND date_trunc('day', "ItemAct".created_at AT TIME ZONE 'UTC' AT TIME ZONE 'America/Chicago') = day_cte.day
|
AND date_trunc('day', "ItemAct".created_at AT TIME ZONE 'UTC' AT TIME ZONE 'America/Chicago') = days_cte.day
|
||||||
GROUP BY "ItemAct".id, "ItemAct".msats
|
GROUP BY "ItemAct".id, "ItemAct".msats
|
||||||
HAVING COUNT("ItemForward".id) = 0)
|
HAVING COUNT("ItemForward".id) = 0)
|
||||||
) subquery`
|
) subquery
|
||||||
|
GROUP BY days_cte.day
|
||||||
|
ORDER BY days_cte.day ASC`
|
||||||
|
|
||||||
return result || { total: 0, time: 0, sources: [] }
|
return results || [{ total: 0, time: 0, sources: [] }]
|
||||||
},
|
},
|
||||||
meRewards: async (parent, { when }, { me, models }) => {
|
meRewards: async (parent, { when }, { me, models }) => {
|
||||||
if (!me) {
|
if (!me) {
|
||||||
return null
|
return null
|
||||||
}
|
}
|
||||||
|
|
||||||
const [result] = await models.$queryRaw`
|
if (!when || !Array.isArray(when) || when.length > 2) {
|
||||||
WITH day_cte (day) AS (
|
throw new GraphQLError('invalid date range', { extensions: { code: 'BAD_USER_INPUT' } })
|
||||||
SELECT date_trunc('day', ${when}::text::timestamp AT TIME ZONE 'America/Chicago')
|
}
|
||||||
|
for (const w of when) {
|
||||||
|
if (isNaN(new Date(w))) {
|
||||||
|
throw new GraphQLError('invalid date', { extensions: { code: 'BAD_USER_INPUT' } })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const results = await models.$queryRaw`
|
||||||
|
WITH days_cte (day) AS (
|
||||||
|
SELECT t::date
|
||||||
|
FROM generate_series(${when[0]}::text::timestamp, ${when[when.length - 1]}::text::timestamp, interval '1 day') AS t
|
||||||
)
|
)
|
||||||
SELECT coalesce(sum(sats), 0) as total, json_agg("Earn".*) as rewards
|
SELECT coalesce(sum(sats), 0) as total, json_agg("Earn".*) as rewards
|
||||||
FROM day_cte
|
FROM days_cte
|
||||||
CROSS JOIN LATERAL (
|
CROSS JOIN LATERAL (
|
||||||
(SELECT FLOOR("Earn".msats / 1000.0) as sats, type, rank, "typeId"
|
(SELECT FLOOR("Earn".msats / 1000.0) as sats, type, rank, "typeId"
|
||||||
FROM "Earn"
|
FROM "Earn"
|
||||||
WHERE "Earn"."userId" = ${me.id}
|
WHERE "Earn"."userId" = ${me.id}
|
||||||
AND date_trunc('day', "Earn".created_at AT TIME ZONE 'UTC' AT TIME ZONE 'America/Chicago') = day_cte.day
|
AND date_trunc('day', "Earn".created_at AT TIME ZONE 'UTC' AT TIME ZONE 'America/Chicago') = days_cte.day
|
||||||
ORDER BY "Earn".msats DESC)
|
ORDER BY "Earn".msats DESC)
|
||||||
) "Earn"`
|
) "Earn"
|
||||||
|
GROUP BY days_cte.day
|
||||||
|
ORDER BY days_cte.day ASC`
|
||||||
|
|
||||||
return result
|
return results
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
Mutation: {
|
Mutation: {
|
||||||
|
|
|
@ -65,6 +65,7 @@ export default gql`
|
||||||
type Earn {
|
type Earn {
|
||||||
id: ID!
|
id: ID!
|
||||||
earnedSats: Int!
|
earnedSats: Int!
|
||||||
|
minSortTime: Date!
|
||||||
sortTime: Date!
|
sortTime: Date!
|
||||||
sources: EarnSources
|
sources: EarnSources
|
||||||
}
|
}
|
||||||
|
|
|
@ -2,8 +2,8 @@ import { gql } from 'graphql-tag'
|
||||||
|
|
||||||
export default gql`
|
export default gql`
|
||||||
extend type Query {
|
extend type Query {
|
||||||
rewards(when: String): Rewards!
|
rewards(when: [String!]): [Rewards!]
|
||||||
meRewards(when: String!): MeRewards
|
meRewards(when: [String!]!): [MeRewards]
|
||||||
}
|
}
|
||||||
|
|
||||||
extend type Mutation {
|
extend type Mutation {
|
||||||
|
|
|
@ -12,8 +12,7 @@ const REWARDS = gql`
|
||||||
|
|
||||||
export default function Rewards () {
|
export default function Rewards () {
|
||||||
const { data } = useQuery(REWARDS, SSR ? { ssr: false } : { pollInterval: 60000, nextFetchPolicy: 'cache-and-network' })
|
const { data } = useQuery(REWARDS, SSR ? { ssr: false } : { pollInterval: 60000, nextFetchPolicy: 'cache-and-network' })
|
||||||
const total = data?.rewards?.total
|
const total = data?.rewards?.[0]?.total
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Link href='/rewards' className='nav-link p-0 p-0 d-inline-flex'>
|
<Link href='/rewards' className='nav-link p-0 p-0 d-inline-flex'>
|
||||||
{total ? <span><RewardLine total={total} /></span> : 'rewards'}
|
{total ? <span><RewardLine total={total} /></span> : 'rewards'}
|
||||||
|
|
|
@ -7,7 +7,7 @@ import { NOTIFICATIONS } from '../fragments/notifications'
|
||||||
import MoreFooter from './more-footer'
|
import MoreFooter from './more-footer'
|
||||||
import Invite from './invite'
|
import Invite from './invite'
|
||||||
import { ignoreClick } from '../lib/clicks'
|
import { ignoreClick } from '../lib/clicks'
|
||||||
import { timeSince } from '../lib/time'
|
import { dayMonthYear, timeSince } from '../lib/time'
|
||||||
import Link from 'next/link'
|
import Link from 'next/link'
|
||||||
import Check from '../svgs/check-double-line.svg'
|
import Check from '../svgs/check-double-line.svg'
|
||||||
import HandCoin from '../svgs/hand-coin-fill.svg'
|
import HandCoin from '../svgs/hand-coin-fill.svg'
|
||||||
|
@ -156,12 +156,14 @@ function Streak ({ n }) {
|
||||||
}
|
}
|
||||||
|
|
||||||
function EarnNotification ({ n }) {
|
function EarnNotification ({ n }) {
|
||||||
|
const time = n.minSortTime === n.sortTime ? dayMonthYear(new Date(n.minSortTime)) : `${dayMonthYear(new Date(n.minSortTime))} to ${dayMonthYear(new Date(n.sortTime))}`
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className='d-flex ms-2 py-1'>
|
<div className='d-flex ms-2 py-1'>
|
||||||
<HandCoin className='align-self-center fill-boost mx-1' width={24} height={24} style={{ flex: '0 0 24px', transform: 'rotateY(180deg)' }} />
|
<HandCoin className='align-self-center fill-boost mx-1' width={24} height={24} style={{ flex: '0 0 24px', transform: 'rotateY(180deg)' }} />
|
||||||
<div className='ms-2'>
|
<div className='ms-2'>
|
||||||
<div className='fw-bold text-boost'>
|
<div className='fw-bold text-boost'>
|
||||||
you stacked {numWithUnits(n.earnedSats, { abbreviate: false })} in rewards<small className='text-muted ms-1 fw-normal' suppressHydrationWarning>{timeSince(new Date(n.sortTime))}</small>
|
you stacked {numWithUnits(n.earnedSats, { abbreviate: false })} in rewards<small className='text-muted ms-1 fw-normal' suppressHydrationWarning>{time}</small>
|
||||||
</div>
|
</div>
|
||||||
{n.sources &&
|
{n.sources &&
|
||||||
<div style={{ fontSize: '80%', color: 'var(--theme-grey)' }}>
|
<div style={{ fontSize: '80%', color: 'var(--theme-grey)' }}>
|
||||||
|
|
|
@ -40,6 +40,7 @@ export const NOTIFICATIONS = gql`
|
||||||
... on Earn {
|
... on Earn {
|
||||||
id
|
id
|
||||||
sortTime
|
sortTime
|
||||||
|
minSortTime
|
||||||
earnedSats
|
earnedSats
|
||||||
sources {
|
sources {
|
||||||
posts
|
posts
|
||||||
|
|
|
@ -15,7 +15,7 @@ export const REWARDS = gql`
|
||||||
|
|
||||||
export const ME_REWARDS = gql`
|
export const ME_REWARDS = gql`
|
||||||
${ITEM_FULL_FIELDS}
|
${ITEM_FULL_FIELDS}
|
||||||
query meRewards($when: String) {
|
query meRewards($when: [String!]) {
|
||||||
rewards(when: $when) {
|
rewards(when: $when) {
|
||||||
total
|
total
|
||||||
time
|
time
|
||||||
|
|
|
@ -33,6 +33,8 @@ function datePivot (date,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const dayMonthYear = when => new Date(when).toISOString().slice(0, 10)
|
||||||
|
|
||||||
function timeLeft (timeStamp) {
|
function timeLeft (timeStamp) {
|
||||||
const now = new Date()
|
const now = new Date()
|
||||||
const secondsPast = (timeStamp - now.getTime()) / 1000
|
const secondsPast = (timeStamp - now.getTime()) / 1000
|
||||||
|
@ -57,4 +59,4 @@ function timeLeft (timeStamp) {
|
||||||
|
|
||||||
const sleep = (ms) => new Promise((resolve, reject) => setTimeout(resolve, ms))
|
const sleep = (ms) => new Promise((resolve, reject) => setTimeout(resolve, ms))
|
||||||
|
|
||||||
module.exports = { timeSince, datePivot, timeLeft, sleep }
|
module.exports = { timeSince, dayMonthYear, datePivot, timeLeft, sleep }
|
||||||
|
|
|
@ -8,6 +8,7 @@ import { getGetServerSideProps } from '../../api/ssrApollo'
|
||||||
import { fixedDecimal } from '../../lib/format'
|
import { fixedDecimal } from '../../lib/format'
|
||||||
import Trophy from '../../svgs/trophy-fill.svg'
|
import Trophy from '../../svgs/trophy-fill.svg'
|
||||||
import { ListItem } from '../../components/items'
|
import { ListItem } from '../../components/items'
|
||||||
|
import { dayMonthYear } from '../../lib/time'
|
||||||
|
|
||||||
const GrowthPieChart = dynamic(() => import('../../components/charts').then(mod => mod.GrowthPieChart), {
|
const GrowthPieChart = dynamic(() => import('../../components/charts').then(mod => mod.GrowthPieChart), {
|
||||||
loading: () => <div>Loading...</div>
|
loading: () => <div>Loading...</div>
|
||||||
|
@ -15,38 +16,39 @@ const GrowthPieChart = dynamic(() => import('../../components/charts').then(mod
|
||||||
|
|
||||||
export const getServerSideProps = getGetServerSideProps({
|
export const getServerSideProps = getGetServerSideProps({
|
||||||
query: ME_REWARDS,
|
query: ME_REWARDS,
|
||||||
notFound: (data, params) => data.rewards.total === 0 || new Date(data.rewards.time) > new Date()
|
notFound: (data, params) => data.rewards.reduce((a, r) => a || new Date(r.time) > new Date(), false)
|
||||||
})
|
})
|
||||||
|
|
||||||
const timeString = when => new Date(when).toISOString().slice(0, 10)
|
|
||||||
|
|
||||||
export default function Rewards ({ ssrData }) {
|
export default function Rewards ({ ssrData }) {
|
||||||
const router = useRouter()
|
const router = useRouter()
|
||||||
const { data } = useQuery(ME_REWARDS, { variables: { ...router.query } })
|
const { data } = useQuery(ME_REWARDS, { variables: { ...router.query } })
|
||||||
if (!data && !ssrData) return <PageLoading />
|
if (!data && !ssrData) return <PageLoading />
|
||||||
|
|
||||||
const { rewards: { total, sources, time }, meRewards } = data || ssrData
|
const { rewards, meRewards } = data || ssrData
|
||||||
const when = router.query.when
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<CenterLayout footerLinks>
|
<CenterLayout footerLinks>
|
||||||
<div className='py-3'>
|
<div className='mw-100'>
|
||||||
|
{rewards.map(({ total, sources, time }, i) => (
|
||||||
|
<div className='py-3 w-100 d-grid' key={time} style={{ gridTemplateColumns: 'minmax(0, 1fr)' }}>
|
||||||
<h4 className='fw-bold text-muted ps-0'>
|
<h4 className='fw-bold text-muted ps-0'>
|
||||||
{when && <div className='text-muted fst-italic fs-6 fw-normal pb-1'>On {timeString(time)} at 12a CT</div>}
|
{time && <div className='text-muted fst-italic fs-6 fw-normal pb-1'>On {dayMonthYear(time)} at 12a CT</div>}
|
||||||
{total} sats were rewarded
|
{total} sats were rewarded
|
||||||
</h4>
|
</h4>
|
||||||
<div className='my-3 w-100'>
|
<div className='my-3 w-100 justify-self-center'>
|
||||||
<GrowthPieChart data={sources} />
|
<GrowthPieChart data={sources} />
|
||||||
</div>
|
</div>
|
||||||
{meRewards &&
|
{meRewards[i] &&
|
||||||
<>
|
<div className='justify-self-center mw-100'>
|
||||||
<h4 className='fw-bold text-muted text-center'>
|
<h4 className='fw-bold text-muted'>
|
||||||
you earned {meRewards.total} sats ({fixedDecimal(meRewards.total * 100 / total, 2)}%)
|
you earned {meRewards[i].total} sats ({fixedDecimal(meRewards[i].total * 100 / total, 2)}%)
|
||||||
</h4>
|
</h4>
|
||||||
<div>
|
<div>
|
||||||
{meRewards.rewards?.map((r, i) => <Reward key={[r.rank, r.type].join('-')} {...r} />)}
|
{meRewards[i].rewards?.map((r, i) => <Reward key={[r.rank, r.type].join('-')} {...r} />)}
|
||||||
</div>
|
</div>
|
||||||
</>}
|
</div>}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
</div>
|
</div>
|
||||||
</CenterLayout>
|
</CenterLayout>
|
||||||
)
|
)
|
|
@ -66,7 +66,7 @@ export default function Rewards ({ ssrData }) {
|
||||||
const { data } = useQuery(REWARDS, SSR ? {} : { pollInterval: 1000, nextFetchPolicy: 'cache-and-network' })
|
const { data } = useQuery(REWARDS, SSR ? {} : { pollInterval: 1000, nextFetchPolicy: 'cache-and-network' })
|
||||||
if (!data && !ssrData) return <PageLoading />
|
if (!data && !ssrData) return <PageLoading />
|
||||||
|
|
||||||
const { rewards: { total, sources } } = data || ssrData
|
const { rewards: [{ total, sources }] } = data || ssrData
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<CenterLayout footerLinks>
|
<CenterLayout footerLinks>
|
||||||
|
|
|
@ -173,6 +173,10 @@ $btn-close-bg: none;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.justify-self-center {
|
||||||
|
justify-self: center;
|
||||||
|
}
|
||||||
|
|
||||||
.text-primary svg {
|
.text-primary svg {
|
||||||
fill: var(--bs-primary);
|
fill: var(--bs-primary);
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in New Issue