Skip to content
Merged
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
4 changes: 3 additions & 1 deletion src/app/(platform)/(ops)/admin/reports/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,7 @@ function filterFor(status: string | undefined): Filter {
/** The chosen report in full: what it is about, who sent it, when, and the decisions open to staff. */
function ReportDetail({ report }: { report: ContentReportRow }) {
const subject = subjectOf(report)
const reporterName = displayName(report.reporter, report.reporter?.email ?? "")
return (
<div className="hl-stack hl-stack--tight">
<div>
Expand All @@ -185,7 +186,8 @@ function ReportDetail({ report }: { report: ContentReportRow }) {
</blockquote>
) : null}
<p className="hl-hint" style={{ margin: 0 }}>
Reported by {displayName(report.reporter, report.reporter?.email ?? "")} on{" "}
Reported by{" "}
{report.reporter ? <Link href={`/admin/users/${report.reporter.id}`}>{reporterName}</Link> : reporterName} on{" "}
{formatUtcDateTime(parseDbTimestamp(report.createdAt))}
</p>
<ReportActions report={report} subject={subject} />
Expand Down
27 changes: 15 additions & 12 deletions src/lib/grant-return-coins.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,28 +2,31 @@ import { describe, expect, test } from "bun:test"
import { grantReturnCoins } from "@/lib/grant-return-coins"

describe("grantReturnCoins", () => {
test("the unissued part of the cap and the returned balance both pay", () => {
// A $30 cap, a $10 card with $1 spent: $20 never issued plus $9 returned.
expect(grantReturnCoins(30, 1000, 100)).toBe(29)
// A $30 cap, a $20 card with $1 spent: $10 never issued plus $19 returned.
expect(grantReturnCoins(30, 2000, 100)).toBe(29)
test("the cap less everything the grant spent is paid", () => {
// A $30 cap with $1 spent: $29 left.
expect(grantReturnCoins(30, 100)).toBe(29)
})

test("top-ups add nothing: the cap less the spend, whatever was topped up", () => {
// A $30 cap, a $30 card topped up to $33, $27 spent: $3 left, measured against the cap.
expect(grantReturnCoins(30, 3000, 2700)).toBe(3)
test("a $12 grant topped up by $10, with $17 spent and $5 back, pays 13 coins", () => {
// The $10 top-up is spent along with the rest, so spend is $22 - $5 = $17; the cap is still $30.
expect(grantReturnCoins(30, 1700)).toBe(13)
})

test("a grant given $2 over the tier pays the cap less spend, not the $2 back", () => {
// $32 given, $22 back: $10 spent, so $30 - $10 = 20 coins.
expect(grantReturnCoins(30, 1000)).toBe(20)
})

test("an unspent card pays the whole cap", () => {
expect(grantReturnCoins(30, 3000, 0)).toBe(30)
expect(grantReturnCoins(30, 0)).toBe(30)
})

test("spend past what was issued, from a top-up, pays nothing beyond the unissued part", () => {
expect(grantReturnCoins(30, 3000, 3300)).toBe(0)
test("spend past the cap pays nothing", () => {
expect(grantReturnCoins(30, 3300)).toBe(0)
})

test("only whole coins are paid", () => {
// $30 cap, $0.50 spent: $29.50 left, which pays 29 coins.
expect(grantReturnCoins(30, 3000, 50)).toBe(29)
expect(grantReturnCoins(30, 50)).toBe(29)
})
})
23 changes: 11 additions & 12 deletions src/lib/grant-return-coins.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,13 @@ import db from "@/lib/prisma8"
/**
* Coins for a design whose grant card was handed back, or converted to a reimbursement.
*
* The maker could have claimed up to the project's cap, so the part of the cap they did not spend is theirs in coins: the cap less what the cards spent. Whatever was never issued counts the same as whatever came back, and top-ups add nothing, since they are not part of the cap.
* The maker is paid the part of the cap they did not spend: the cap less everything the grant spent. Spend counts every top-up and any amount above the tier, since the maker spent that money too, but neither raises the cap, so a top-up or an over-tier amount that comes back is not paid as coins.
*
* One coin is one dollar, and whole coins only, so a half-dollar left over is not paid.
*/
export function grantReturnCoins(capUsd: number, issuedCents: number, spentCents: number): number {
export function grantReturnCoins(capUsd: number, spentCents: number): number {
const capCents = Math.round(capUsd * 100)
const spent = Math.min(spentCents, issuedCents)
return Math.max(0, Math.floor((capCents - spent) / 100))
return Math.max(0, Math.floor((capCents - spentCents) / 100))
}

export interface GrantReturnCoinsResult {
Expand All @@ -44,7 +43,6 @@ const isPayableReturn = (hcbStatus: string | null): boolean =>
hcbStatus === PRE_ACTIVATION_STATUS || (hcbStatus !== null && PLAIN_RETURN_STATUSES.includes(hcbStatus))

interface ReturnedDesignCard {
amountCents: number
hcbCardGrantId: string | null
hcbStatus: string | null
id: string
Expand All @@ -63,17 +61,19 @@ export async function syncGrantReturnCoins(input: {
/** A dry run's preview: the cards the buffer sync would mark RETURNED, with the HCB status it would store. Empty on a live run. */
pending?: readonly PendingReturn[]
}): Promise<GrantReturnCoinsResult> {
const pendingById = new Map<string, string | null>()
for (const pending of input.pending ?? []) pendingById.set(pending.id, pending.hcbStatus)
const pendingById = new Map<string, PendingReturn>()
for (const pending of input.pending ?? []) pendingById.set(pending.id, pending)
const rows = await db.orm.public.HcbGrantCard.where({ phase: Phase.DESIGN })
.where(row => row.status.in([HcbGrantCardStatus.RETURNED, HcbGrantCardStatus.ISSUED, HcbGrantCardStatus.AMBIGUOUS]))
.select("amountCents", "hcbCardGrantId", "hcbStatus", "id", "spentCents", "status", "themeProjectId", "userId")
.select("hcbCardGrantId", "hcbStatus", "id", "spentCents", "status", "themeProjectId", "userId")
.all()
const cards: ReturnedDesignCard[] = []
// A live run has already marked its returns, so an unmarked card is not a return yet. A dry run previews the ones it would mark.
for (const row of rows)
if (pendingById.has(row.id)) cards.push({ ...row, hcbStatus: pendingById.get(row.id) ?? null })
for (const row of rows) {
const pending = pendingById.get(row.id)
if (pending) cards.push({ ...row, hcbStatus: pending.hcbStatus, spentCents: pending.spentCents ?? row.spentCents })
else if (row.status === HcbGrantCardStatus.RETURNED) cards.push(row)
}

const byProject = new Map<string, ReturnedDesignCard[]>()
for (const card of cards) {
Expand Down Expand Up @@ -148,9 +148,8 @@ export async function syncGrantReturnCoins(input: {
continue
}

const issuedCents = group.reduce((sum, card) => sum + card.amountCents, 0)
const spentCents = spent.reduce((sum, value) => sum + value, 0)
const target = grantReturnCoins(capUsd, issuedCents, spentCents)
const target = grantReturnCoins(capUsd, spentCents)
const userId = group[0]?.userId
if (userId === undefined) continue
if (!input.dryRun)
Expand Down
15 changes: 15 additions & 0 deletions src/lib/hcb-buffer-topups.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import {
returnedByMaker,
returnHcbStatus,
selectBufferTopUps,
spentFromReturn,
} from "@/lib/hcb-buffer-topups"

const disbursement = (overrides: Partial<GrantDisbursement> = {}): GrantDisbursement => ({
Expand Down Expand Up @@ -196,3 +197,17 @@ describe("returnHcbStatus", () => {
)
})
})

describe("spentFromReturn", () => {
test("a $12 grant topped up by $10 and returned at $5 spent $17", () => {
expect(spentFromReturn(2200, 500)).toBe(1700)
})

test("a $32 grant returned at $22 spent $10", () => {
expect(spentFromReturn(3200, 2200)).toBe(1000)
})

test("a return larger than what was granted is not a spend figure", () => {
expect(spentFromReturn(1000, 1200)).toBeNull()
})
})
71 changes: 61 additions & 10 deletions src/lib/hcb-buffer-topups.ts
Original file line number Diff line number Diff line change
Expand Up @@ -212,10 +212,24 @@ const LIVE_CARD_STATUSES = [
type CardTable = "project" | "shop"

interface LiveCardRef {
/** The row's original amount. Null for a shop card, which the coin pass never pays. */
amountCents: number | null
id: string
/** What the row already records as spent. Null until a return fixes it. */
spentCents: number | null
table: CardTable
}

/**
* What a card spent, from HCB's own totals: everything the grant was given (its original amount, every top-up, and any
* amount above the tier) less the balance HCB sent back. Spend cannot be read from the card once it is returned, so this
* is the figure the coin pass uses. Null when the totals do not add up, so the design is skipped rather than guessed at.
*/
export function spentFromReturn(grantedCents: number, returnedCents: number): number | null {
const spent = grantedCents - returnedCents
return spent < 0 ? null : spent
}

/**
* Record that the maker handed a card back. The money has left the card, so the row is finished either way: it is no
* longer live, and a returned card is never reissued by the system (both issue paths refuse a settled card).
Expand All @@ -225,6 +239,7 @@ export async function markCardReturned(
id: string,
returnedAt: string,
hcbStatus: string | null,
spentCents: number | null,
): Promise<void> {
const error = "The maker returned this grant on HCB; its balance went back to the organisation"
const update = {
Expand All @@ -239,6 +254,7 @@ export async function markCardReturned(
await db.orm.public.HcbGrantCard.where({ id }).update({
...update,
returnedAt: formatDbTimestamp(new Date(returnedAt)),
...(spentCents === null ? {} : { spentCents }),
})
}

Expand Down Expand Up @@ -272,7 +288,7 @@ export async function refuseCancelOrRecordReturn(
throw error
}
if (returnedAt === null) throw error
await markCardReturned(table, id, returnedAt, null)
await markCardReturned(table, id, returnedAt, null, null)
throw new HttpError(
"CONFLICT",
"The maker already returned this grant on HCB, so it cannot be cancelled. It is now marked returned",
Expand All @@ -283,6 +299,7 @@ export async function refuseCancelOrRecordReturn(
export interface PendingReturn {
hcbStatus: string | null
id: string
spentCents: number | null
}

export interface BufferTopUpSyncResult {
Expand Down Expand Up @@ -332,18 +349,36 @@ export async function syncBufferTopUps(input: { dryRun: boolean }): Promise<Buff
const liveCards = new Map<string, LiveCardRef>()
for (const card of await db.orm.public.HcbGrantCard.where({})
.where(row => row.status.in(LIVE_CARD_STATUSES))
.select("hcbCardGrantId", "id")
.select("amountCents", "hcbCardGrantId", "id", "spentCents")
.all())
if (card.hcbCardGrantId) liveCards.set(bareGrantId(card.hcbCardGrantId), { id: card.id, table: "project" })
if (card.hcbCardGrantId)
liveCards.set(bareGrantId(card.hcbCardGrantId), {
amountCents: card.amountCents,
id: card.id,
spentCents: card.spentCents,
table: "project",
})
for (const card of await db.orm.public.HcbShopGrantCard.where({})
.where(row => row.status.in(LIVE_CARD_STATUSES))
.select("hcbCardGrantId", "id")
.all())
if (card.hcbCardGrantId) liveCards.set(bareGrantId(card.hcbCardGrantId), { id: card.id, table: "shop" })
if (card.hcbCardGrantId)
liveCards.set(bareGrantId(card.hcbCardGrantId), {
amountCents: null,
id: card.id,
spentCents: null,
table: "shop",
})

let topUpsFound = 0
let alreadyRecorded = 0
const returned: { hcbStatus: string | null; id: string; returnedAt: string; table: CardTable }[] = []
const returned: {
hcbStatus: string | null
id: string
returnedAt: string
spentCents: number | null
table: CardTable
}[] = []
const grantStatuses: { [_: string]: number } = {}
const returnsSeen: ReturnSeen[] = []
const canceledWithoutReturn: CanceledWithoutReturn[] = []
Expand Down Expand Up @@ -384,9 +419,22 @@ export async function syncBufferTopUps(input: { dryRun: boolean }): Promise<Buff
})
const returnedAt = found !== null && !found.expired ? found.disbursement.createdAt : null
const liveCardId = liveCards.get(bareGrantId(grant.id))
if (returnedAt !== null && liveCardId)
returned.push({ hcbStatus, id: liveCardId.id, returnedAt, table: liveCardId.table })
for (const [index, disbursement] of selectBufferTopUps(read.rows, sitePayments, grant.id).entries()) {
const buffered = selectBufferTopUps(read.rows, sitePayments, grant.id)
if (returnedAt !== null && liveCardId && found !== null) {
// Granted is the card's original amount plus every top-up, whether it came from the buffer or from Half Life.
// Spent is what that left once HCB sent the balance back. A row that already has a figure keeps it.
const siteTopUps = sitePayments.filter(p => bareGrantId(p.grantHashid) === bareGrantId(grant.id))
const grantedCents =
(liveCardId.amountCents ?? 0)
+ buffered.reduce((sum, d) => sum + d.amountCents, 0)
+ siteTopUps.reduce((sum, p) => sum + p.amountCents, 0)
const spentCents =
liveCardId.table === "project" && liveCardId.amountCents !== null
? (liveCardId.spentCents ?? spentFromReturn(grantedCents, found.disbursement.amountCents))
: null
returned.push({ hcbStatus, id: liveCardId.id, returnedAt, spentCents, table: liveCardId.table })
}
for (const [index, disbursement] of buffered.entries()) {
topUpsFound++
const key = bufferTopUpKey(grant.id, disbursement, index)
if (known.has(key)) {
Expand All @@ -405,7 +453,8 @@ export async function syncBufferTopUps(input: { dryRun: boolean }): Promise<Buff
}

if (!input.dryRun && returned.length > 0)
for (const card of returned) await markCardReturned(card.table, card.id, card.returnedAt, card.hcbStatus)
for (const card of returned)
await markCardReturned(card.table, card.id, card.returnedAt, card.hcbStatus, card.spentCents)

if (!input.dryRun && fresh.length > 0)
await db.orm.public.HcbBufferTopUp.createAll(
Expand All @@ -425,7 +474,9 @@ export async function syncBufferTopUps(input: { dryRun: boolean }): Promise<Buff
grantStatuses,
grantsScanned: list.rows.length,
pendingReturns: input.dryRun
? returned.filter(r => r.table === "project").map(r => ({ hcbStatus: r.hcbStatus, id: r.id }))
? returned
.filter(r => r.table === "project")
.map(r => ({ hcbStatus: r.hcbStatus, id: r.id, spentCents: r.spentCents }))
: [],
recorded: input.dryRun ? 0 : fresh.length,
returnedMarked: input.dryRun ? 0 : returned.length,
Expand Down
Loading