diff --git a/prisma/migrations/20260528143000_add_bounty_issue_metadata/migration.sql b/prisma/migrations/20260528143000_add_bounty_issue_metadata/migration.sql new file mode 100644 index 0000000..38201fc --- /dev/null +++ b/prisma/migrations/20260528143000_add_bounty_issue_metadata/migration.sql @@ -0,0 +1,9 @@ +ALTER TABLE "Bounty" ADD COLUMN "issueTitle" TEXT; +ALTER TABLE "Bounty" ADD COLUMN "issueUrl" TEXT; +ALTER TABLE "Bounty" ADD COLUMN "issueState" TEXT; +ALTER TABLE "Bounty" ADD COLUMN "issueExcerpt" TEXT; +ALTER TABLE "Bounty" ADD COLUMN "issueCreatedAt" TIMESTAMP(3); +ALTER TABLE "Bounty" ADD COLUMN "issueUpdatedAt" TIMESTAMP(3); + +CREATE INDEX "Bounty_issueUpdatedAt_idx" ON "Bounty"("issueUpdatedAt"); +CREATE INDEX "Bounty_amount_idx" ON "Bounty"("amount"); diff --git a/prisma/schema.prisma b/prisma/schema.prisma index df1171d..d157f2d 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -54,22 +54,30 @@ model GithubUserLink { } model Bounty { - id String @id @default(cuid()) - repositoryId String - issueNumber Int - issueNodeId String? - labelName String - amount Decimal @db.Decimal(18, 6) - currency String - status BountyStatus @default(OPEN) - createdAt DateTime @default(now()) - updatedAt DateTime @updatedAt + id String @id @default(cuid()) + repositoryId String + issueNumber Int + issueNodeId String? + issueTitle String? + issueUrl String? + issueState String? + issueExcerpt String? @db.Text + issueCreatedAt DateTime? + issueUpdatedAt DateTime? + labelName String + amount Decimal @db.Decimal(18, 6) + currency String + status BountyStatus @default(OPEN) + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt repository RepositoryInstallation @relation(fields: [repositoryId], references: [id], onDelete: Cascade) rewards RewardAttempt[] @@unique([repositoryId, issueNumber, labelName]) @@index([repositoryId, issueNumber]) + @@index([issueUpdatedAt]) + @@index([amount]) } model RewardAttempt { diff --git a/src/app/deploy/page.tsx b/src/app/deploy/page.tsx new file mode 100644 index 0000000..5c63fe6 --- /dev/null +++ b/src/app/deploy/page.tsx @@ -0,0 +1,469 @@ +import type { CSSProperties, ReactNode } from "react"; + +const flowSteps = [ + "A repository owner installs the GitHub App.", + "A maintainer labels an issue with a Pvium bounty label, for example pvium:20USDC or pvium:10.", + "When a pull request is merged into a configured reward target branch and closes that issue, the app checks the PR author.", + "If the PR author is already linked to a Pvium account, the app creates a Pvium payment link and comments a Pay reward link on the PR.", + "If the PR author is not linked, the app generates a signed Pvium OAuth invite for type: github and comments the invite link on the PR.", + "Once the user accepts the invite and connects the matching GitHub account in Pvium, the Pvium webhook creates the payment link and comments the Pay reward link on the PR.", + "When Pvium sends a paid or funded webhook, the app marks the reward and bounty as PAID.", +]; + +const localSetupCommands = [ + "cd /Users/Projects/Javascript/paytrack/sdks/node", + "npm install", + "npm run build", + "", + "cd /Users/Projects/Javascript/paytrack/github-app", + "npm install", + "cp .env.example .env", + "npm run prisma:generate", + "npm run prisma:migrate", + "npm run dev", +]; + +const envExample = `DATABASE_URL="postgresql://postgres:postgres@localhost:5432/pvium_github_app" + +GITHUB_APP_ID="" +GITHUB_APP_PRIVATE_KEY="" +GITHUB_WEBHOOK_SECRET="" +GITHUB_REWARD_TARGET_BRANCHES="main,master" +PVIUM_BOUNTY_LABEL_PREFIX="pvium:" + +PVIUM_ENVIRONMENT="sandbox" +PVIUM_API_BASE_URL="" +PVIUM_CONSENT_HOST="" +PVIUM_SDK_LOG_REQUESTS="false" +PVIUM_API_KEY="" +PVIUM_CLIENT_ID="" +PVIUM_WEBHOOK_SECRET="" +PVIUM_INVITE_SIGNER_PRIVATE_KEY="" +PVIUM_OAUTH_REDIRECT_URI="http://localhost:3000/api/pvium/oauth/callback" +PVIUM_REWARD_PAYMENT_MODEL="instant-batch" +PVIUM_REWARD_PAYMENT_SIGNER_PRIVATE_KEY="" +PVIUM_REWARD_PAYMENT_CHAIN="base" +PVIUM_REWARD_PAYMENT_CHAIN_ID="8453" +PVIUM_REWARD_PAYMENT_CURRENCY="USDC" +PVIUM_REWARD_PAYMENT_TOKEN_ADDRESS="" +PVIUM_REWARD_PAYMENT_TOKEN_DECIMALS="6" +PVIUM_REWARD_PLATFORM_FEE_WALLET="" +PVIUM_REWARD_PLATFORM_FEE_BASIS_POINTS="0" +PVIUM_REWARD_MAX_FEE_AMOUNT="0" +PVIUM_INVOICE_REDIRECT_URI="http://localhost:3000/api/pvium/oauth/callback" + +APP_BASE_URL="http://localhost:3000"`; + +const githubPermissions = [ + "Issues: read and write", + "Pull requests: read and write", + "Metadata: read-only", +]; + +const githubEvents = ["issues", "pull_request"]; + +const configItems = [ + "GITHUB_REWARD_TARGET_BRANCHES is a comma-separated list of base branches that can trigger reward processing when a PR is merged.", + "PVIUM_BOUNTY_LABEL_PREFIX controls the GitHub issue label prefix used to detect bounties. It defaults to pvium: when unset or empty.", + "PVIUM_ENVIRONMENT resolves Pvium hosts: test uses localhost, sandbox uses api-sandbox.pvium.com, and production uses api.pvium.com.", + "PVIUM_API_BASE_URL and PVIUM_CONSENT_HOST override the resolved Pvium hosts when needed.", + "PVIUM_SDK_LOG_REQUESTS=true logs SDK request method, host, path, status, duration, and network errors without logging full URLs or secrets.", + "PVIUM_REWARD_PAYMENT_MODEL controls the payment artifact. Use instant-batch for finalized instant batch payment links or invoice for the legacy invoice flow.", + "PVIUM_REWARD_PAYMENT_CHAIN is the chain used by both invoice payment channels and instant batch links.", + "PVIUM_REWARD_PAYMENT_CURRENCY is the invoice payment currency.", + "PVIUM_REWARD_PAYMENT_SIGNER_PRIVATE_KEY signs instant batches. If omitted, the invite signer is used.", + "PVIUM_REWARD_PAYMENT_CHAIN_ID is the chain id used to finalize instant batches.", + "PVIUM_REWARD_PAYMENT_TOKEN_ADDRESS and PVIUM_REWARD_PAYMENT_TOKEN_DECIMALS define the instant batch payout token.", + "PVIUM_REWARD_PLATFORM_FEE_WALLET receives the platform fee. If omitted, no platform fee payee is added.", + "PVIUM_REWARD_PLATFORM_FEE_BASIS_POINTS sets the fee. For example, 100 is 1% and 250 is 2.5%.", + "PVIUM_REWARD_MAX_FEE_AMOUNT caps the computed platform fee. Use 0 for no cap.", +]; + +const pviumEvents = [ + "oauth.invite.accepted", + "invoice.paid", + "invoice.payment_completed", + "invoice.payment.succeeded", + "payment.attached", + "batch.funded", + "batch.payment_completed", + "batch.payment.succeeded", +]; + +const usageSteps = [ + "Install the GitHub App on a repository.", + "Add a bounty label to an issue, such as pvium:20USDC or pvium:20. If PVIUM_BOUNTY_LABEL_PREFIX is changed, use that prefix instead.", + "Merge a PR into a configured reward target branch with a closing reference like Closes #123.", + "The app comments on the merged PR.", + "If the contributor needs to link Pvium, they use the invite link in the comment.", + "Pvium redirects back to /api/pvium/oauth/callback with an OAuth code.", + "The app exchanges the code through the local Pvium SDK, verifies the accepted GitHub handle, saves the OAuth token set, creates the payment link, and comments a Pay reward link.", + "The maintainer clicks Pay reward and completes payment in Pvium.", +]; + +export default function Home() { + return ( +
+
+
+
+ + Powered by Pvium + + + Install GitHub App + + + Issue Discovery + +
+ + Pvium logo + +
+

Pvium GitHub App

+

+ Reward GitHub contributors with Pvium payment links. +

+

+ Turn merged pull requests into payable rewards. Maintainers label + bounty issues, contributors close them with PRs, and Pvium handles the + invite, payment link, funded webhook, and paid status updates. +

+
+ + + +
+
+ +
+ +
+ +
+

+ The reward automation uses the local Pvium SDK at{" "} + + /Users/Projects/Javascript/paytrack/sdks/node + + . The package points @pvium/sdk{" "} + at file:../sdks/node, so + rebuild the SDK after changing it. +

+ +
+ +
+

+ Required values are documented in .env.example: +

+ +
+ +
+

+ Generate GITHUB_APP_PRIVATE_KEY{" "} + from the GitHub App settings page under Private keys, then copy the + full PEM contents into the environment with line breaks replaced by{" "} + \n. +

+

+ Configure the webhook URL as{" "} + + https://<your-host>/api/github/webhook + + . +

+
+ + +
+
+ +
+

+ Configure the Pvium webhook URL as{" "} + + https://<your-host>/api/pvium/webhook + + . Set PVIUM_WEBHOOK_SECRET to + the same secret configured on the Pvium client app. +

+ +

+ When{" "} + + PVIUM_REWARD_PLATFORM_FEE_WALLET + {" "} + is set and the fee basis points are greater than zero, instant batches + include the platform fee as the first payee with memo{" "} + platform fee. The contributor + reward amount is not reduced by the fee. +

+
+ +
+
+ + +
+
+ +
+ +

+ The app stores Pvium OAuth access and refresh tokens on the GitHub + user link so future merged PRs for the same contributor can create + rewards without asking the contributor to authorize again. Treat these + OAuth tokens as secrets; production deployments should encrypt them at + rest and restrict database access. +

+
+
+ ); +} + +function Section({ title, children }: { title: string; children: ReactNode }) { + return ( +
+

{title}

+ {children} +
+ ); +} + +function Endpoint({ label, value }: { label: string; value: string }) { + return ( +
+ {label} + {value} +
+ ); +} + +function ListBlock({ title, items }: { title: string; items: string[] }) { + return ( +
+

{title}

+ +
+ ); +} + +function BulletList({ items }: { items: string[] }) { + return ( + + ); +} + +function NumberedList({ items }: { items: string[] }) { + return ( +
    + {items.map((item) => ( +
  1. + {item} +
  2. + ))} +
+ ); +} + +function CodeBlock({ value }: { value: string }) { + return
{value}
; +} + +const styles: Record = { + page: { + minHeight: "100vh", + margin: 0, + padding: "48px 20px", + background: "#f7f8fb", + color: "#172033", + fontFamily: + 'Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif', + }, + hero: { + maxWidth: 980, + margin: "0 auto 24px", + padding: "32px 0 8px", + }, + brandRow: { + display: "flex", + alignItems: "center", + justifyContent: "space-between", + gap: 12, + marginBottom: 18, + }, + topLinks: { + display: "flex", + alignItems: "center", + flexWrap: "wrap", + gap: 10, + }, + logo: { + width: 96, + height: 96, + borderRadius: 8, + objectFit: "contain", + }, + logoLink: { + display: "inline-flex", + lineHeight: 0, + }, + poweredBy: { + display: "inline-flex", + alignItems: "center", + padding: "9px 13px", + border: "1px solid #c8d0df", + borderRadius: 999, + background: "#ffffff", + color: "#172033", + fontSize: 14, + fontWeight: 600, + textDecoration: "none", + }, + installLink: { + display: "inline-flex", + alignItems: "center", + padding: "10px 14px", + borderRadius: 8, + background: "#172033", + color: "#ffffff", + fontSize: 14, + fontWeight: 700, + textDecoration: "none", + }, + eyebrow: { + margin: "0 0 12px", + color: "#52627a", + fontSize: 14, + fontWeight: 700, + textTransform: "uppercase", + }, + title: { + maxWidth: 820, + margin: "0 0 18px", + fontSize: 48, + lineHeight: 1.08, + letterSpacing: 0, + }, + lede: { + maxWidth: 760, + margin: "0 0 24px", + color: "#46556e", + fontSize: 18, + lineHeight: 1.65, + }, + endpointGrid: { + display: "grid", + gridTemplateColumns: "repeat(auto-fit, minmax(230px, 1fr))", + gap: 12, + maxWidth: 920, + }, + endpoint: { + border: "1px solid #d9deea", + borderRadius: 8, + background: "#ffffff", + padding: 16, + }, + endpointLabel: { + display: "block", + marginBottom: 8, + color: "#66748a", + fontSize: 13, + fontWeight: 700, + }, + endpointCode: { + color: "#172033", + fontSize: 14, + wordBreak: "break-word", + }, + section: { + maxWidth: 980, + margin: "18px auto", + padding: 24, + border: "1px solid #d9deea", + borderRadius: 8, + background: "#ffffff", + }, + sectionTitle: { + margin: "0 0 16px", + fontSize: 24, + letterSpacing: 0, + }, + paragraph: { + margin: "0 0 14px", + color: "#46556e", + fontSize: 15, + lineHeight: 1.7, + }, + columns: { + display: "grid", + gridTemplateColumns: "repeat(auto-fit, minmax(250px, 1fr))", + gap: 18, + }, + listBlock: { + minWidth: 0, + }, + listTitle: { + margin: "0 0 10px", + color: "#263247", + fontSize: 16, + }, + list: { + margin: 0, + paddingLeft: 22, + color: "#46556e", + fontSize: 15, + lineHeight: 1.7, + }, + listItem: { + marginBottom: 8, + }, + codeBlock: { + margin: "14px 0 0", + padding: 16, + overflowX: "auto", + borderRadius: 8, + background: "#141925", + color: "#eef3ff", + fontSize: 13, + lineHeight: 1.6, + }, + inlineCode: { + padding: "2px 5px", + borderRadius: 5, + background: "#eef1f6", + color: "#263247", + fontSize: "0.92em", + }, +}; diff --git a/src/app/page.tsx b/src/app/page.tsx index 659e33f..d06d9ac 100644 --- a/src/app/page.tsx +++ b/src/app/page.tsx @@ -1,466 +1,380 @@ -import type { CSSProperties, ReactNode } from "react"; +import type { CSSProperties } from "react"; +import { prisma } from "@/lib/db/prisma"; +import { + DiscoveryIssue, + filterAndSortIssues, + formatRewardAmount, + normalizeDiscoveryParams, +} from "@/lib/issues/discovery"; -const flowSteps = [ - "A repository owner installs the GitHub App.", - "A maintainer labels an issue with a Pvium bounty label, for example pvium:20USDC or pvium:10.", - "When a pull request is merged into a configured reward target branch and closes that issue, the app checks the PR author.", - "If the PR author is already linked to a Pvium account, the app creates a Pvium payment link and comments a Pay reward link on the PR.", - "If the PR author is not linked, the app generates a signed Pvium OAuth invite for type: github and comments the invite link on the PR.", - "Once the user accepts the invite and connects the matching GitHub account in Pvium, the Pvium webhook creates the payment link and comments the Pay reward link on the PR.", - "When Pvium sends a paid or funded webhook, the app marks the reward and bounty as PAID.", -]; +export const dynamic = "force-dynamic"; -const localSetupCommands = [ - "cd /Users/Projects/Javascript/paytrack/sdks/node", - "npm install", - "npm run build", - "", - "cd /Users/Projects/Javascript/paytrack/github-app", - "npm install", - "cp .env.example .env", - "npm run prisma:generate", - "npm run prisma:migrate", - "npm run dev", -]; - -const envExample = `DATABASE_URL="postgresql://postgres:postgres@localhost:5432/pvium_github_app" - -GITHUB_APP_ID="" -GITHUB_APP_PRIVATE_KEY="" -GITHUB_WEBHOOK_SECRET="" -GITHUB_REWARD_TARGET_BRANCHES="main,master" -PVIUM_BOUNTY_LABEL_PREFIX="pvium:" - -PVIUM_ENVIRONMENT="sandbox" -PVIUM_API_BASE_URL="" -PVIUM_CONSENT_HOST="" -PVIUM_SDK_LOG_REQUESTS="false" -PVIUM_API_KEY="" -PVIUM_CLIENT_ID="" -PVIUM_WEBHOOK_SECRET="" -PVIUM_INVITE_SIGNER_PRIVATE_KEY="" -PVIUM_OAUTH_REDIRECT_URI="http://localhost:3000/api/pvium/oauth/callback" -PVIUM_REWARD_PAYMENT_MODEL="instant-batch" -PVIUM_REWARD_PAYMENT_SIGNER_PRIVATE_KEY="" -PVIUM_REWARD_PAYMENT_CHAIN="base" -PVIUM_REWARD_PAYMENT_CHAIN_ID="8453" -PVIUM_REWARD_PAYMENT_CURRENCY="USDC" -PVIUM_REWARD_PAYMENT_TOKEN_ADDRESS="" -PVIUM_REWARD_PAYMENT_TOKEN_DECIMALS="6" -PVIUM_REWARD_PLATFORM_FEE_WALLET="" -PVIUM_REWARD_PLATFORM_FEE_BASIS_POINTS="0" -PVIUM_REWARD_MAX_FEE_AMOUNT="0" -PVIUM_INVOICE_REDIRECT_URI="http://localhost:3000/api/pvium/oauth/callback" - -APP_BASE_URL="http://localhost:3000"`; - -const githubPermissions = [ - "Issues: read and write", - "Pull requests: read and write", - "Metadata: read-only", -]; - -const githubEvents = ["issues", "pull_request"]; - -const configItems = [ - "GITHUB_REWARD_TARGET_BRANCHES is a comma-separated list of base branches that can trigger reward processing when a PR is merged.", - "PVIUM_BOUNTY_LABEL_PREFIX controls the GitHub issue label prefix used to detect bounties. It defaults to pvium: when unset or empty.", - "PVIUM_ENVIRONMENT resolves Pvium hosts: test uses localhost, sandbox uses api-sandbox.pvium.com, and production uses api.pvium.com.", - "PVIUM_API_BASE_URL and PVIUM_CONSENT_HOST override the resolved Pvium hosts when needed.", - "PVIUM_SDK_LOG_REQUESTS=true logs SDK request method, host, path, status, duration, and network errors without logging full URLs or secrets.", - "PVIUM_REWARD_PAYMENT_MODEL controls the payment artifact. Use instant-batch for finalized instant batch payment links or invoice for the legacy invoice flow.", - "PVIUM_REWARD_PAYMENT_CHAIN is the chain used by both invoice payment channels and instant batch links.", - "PVIUM_REWARD_PAYMENT_CURRENCY is the invoice payment currency.", - "PVIUM_REWARD_PAYMENT_SIGNER_PRIVATE_KEY signs instant batches. If omitted, the invite signer is used.", - "PVIUM_REWARD_PAYMENT_CHAIN_ID is the chain id used to finalize instant batches.", - "PVIUM_REWARD_PAYMENT_TOKEN_ADDRESS and PVIUM_REWARD_PAYMENT_TOKEN_DECIMALS define the instant batch payout token.", - "PVIUM_REWARD_PLATFORM_FEE_WALLET receives the platform fee. If omitted, no platform fee payee is added.", - "PVIUM_REWARD_PLATFORM_FEE_BASIS_POINTS sets the fee. For example, 100 is 1% and 250 is 2.5%.", - "PVIUM_REWARD_MAX_FEE_AMOUNT caps the computed platform fee. Use 0 for no cap.", -]; - -const pviumEvents = [ - "oauth.invite.accepted", - "invoice.paid", - "invoice.payment_completed", - "invoice.payment.succeeded", - "payment.attached", - "batch.funded", - "batch.payment_completed", - "batch.payment.succeeded", -]; +type PageProps = { + searchParams?: Promise>; +}; -const usageSteps = [ - "Install the GitHub App on a repository.", - "Add a bounty label to an issue, such as pvium:20USDC or pvium:20. If PVIUM_BOUNTY_LABEL_PREFIX is changed, use that prefix instead.", - "Merge a PR into a configured reward target branch with a closing reference like Closes #123.", - "The app comments on the merged PR.", - "If the contributor needs to link Pvium, they use the invite link in the comment.", - "Pvium redirects back to /api/pvium/oauth/callback with an OAuth code.", - "The app exchanges the code through the local Pvium SDK, verifies the accepted GitHub handle, saves the OAuth token set, creates the payment link, and comments a Pay reward link.", - "The maintainer clicks Pay reward and completes payment in Pvium.", -]; +export default async function Home({ searchParams }: PageProps) { + const params = normalizeDiscoveryParams((await searchParams) ?? {}); + const issues = filterAndSortIssues(await loadIssues(), params); + const rewardTotals = getRewardTotals(issues); -export default function Home() { return (
-
-
- +
+
+

Pvium GitHub App

+

Issue Discovery

+
+
-

Pvium GitHub App

-

- Reward GitHub contributors with Pvium payment links. -

-

- Turn merged pull requests into payable rewards. Maintainers label - bounty issues, contributors close them with PRs, and Pvium handles the - invite, payment link, funded webhook, and paid status updates. -

-
- - - -
-
- -
- -
+ + -
-

- The reward automation uses the local Pvium SDK at{" "} - - /Users/Projects/Javascript/paytrack/sdks/node - - . The package points @pvium/sdk{" "} - at file:../sdks/node, so - rebuild the SDK after changing it. -

- -
- -
-

- Required values are documented in .env.example: -

- -
- -
-

- Generate GITHUB_APP_PRIVATE_KEY{" "} - from the GitHub App settings page under Private keys, then copy the - full PEM contents into the environment with line breaks replaced by{" "} - \n. -

-

- Configure the webhook URL as{" "} - - https://<your-host>/api/github/webhook - - . -

-
- - -
-
- -
-

- Configure the Pvium webhook URL as{" "} - - https://<your-host>/api/pvium/webhook - - . Set PVIUM_WEBHOOK_SECRET to - the same secret configured on the Pvium client app. -

- -

- When{" "} - - PVIUM_REWARD_PLATFORM_FEE_WALLET - {" "} - is set and the fee basis points are greater than zero, instant batches - include the platform fee as the first payee with memo{" "} - platform fee. The contributor - reward amount is not reduced by the fee. -

-
- -
-
- - +
+
+ + + + +
+
+ {issues.length} + open records + {rewardTotals.map(([currency, amount]) => ( + {formatRewardAmount(amount, currency)} + ))}
-
+
-
- -

- The app stores Pvium OAuth access and refresh tokens on the GitHub - user link so future merged PRs for the same contributor can create - rewards without asking the contributor to authorize again. Treat these - OAuth tokens as secrets; production deployments should encrypt them at - rest and restrict database access. -

-
+ {issues.length > 0 ? ( +
+ {issues.map((issue) => ( +
+
+
+ {issue.repository} + {issue.status} + {issue.bountyStatus} +
+

+ + {issue.title} + +

+

{issue.excerpt}

+
+
+ + {formatRewardAmount(issue.amount, issue.currency)} + + +
+
+ ))} +
+ ) : ( +
+

No matching issues

+

+ Pvium bounty labels will appear here after connected repositories + send issue events. +

+
+ )}
); } -function Section({ title, children }: { title: string; children: ReactNode }) { - return ( -
-

{title}

- {children} -
- ); -} - -function Endpoint({ label, value }: { label: string; value: string }) { - return ( -
- {label} - {value} -
- ); -} +function getRewardTotals(issues: DiscoveryIssue[]) { + const totals = new Map(); + for (const issue of issues) { + totals.set(issue.currency, (totals.get(issue.currency) ?? 0) + issue.amount); + } -function ListBlock({ title, items }: { title: string; items: string[] }) { - return ( -
-

{title}

- -
- ); + return [...totals.entries()].sort(([a], [b]) => a.localeCompare(b)); } -function BulletList({ items }: { items: string[] }) { - return ( -
    - {items.map((item) => ( -
  • - {item} -
  • - ))} -
- ); -} +async function loadIssues(): Promise { + try { + const bounties = await prisma.bounty.findMany({ + include: { + repository: true, + }, + orderBy: [{ updatedAt: "desc" }], + take: 200, + }); -function NumberedList({ items }: { items: string[] }) { - return ( -
    - {items.map((item) => ( -
  1. - {item} -
  2. - ))} -
- ); -} + return bounties.map((bounty) => { + const repository = `${bounty.repository.owner}/${bounty.repository.repo}`; + const issueUrl = + bounty.issueUrl ?? + `https://github.com/${repository}/issues/${bounty.issueNumber}`; -function CodeBlock({ value }: { value: string }) { - return
{value}
; + return { + id: bounty.id, + title: bounty.issueTitle ?? `${repository}#${bounty.issueNumber}`, + repository, + amount: Number(bounty.amount), + currency: bounty.currency, + status: bounty.issueState ?? "open", + bountyStatus: bounty.status, + createdAt: bounty.issueCreatedAt ?? bounty.createdAt, + updatedAt: bounty.issueUpdatedAt ?? bounty.updatedAt, + excerpt: + bounty.issueExcerpt ?? + `Bounty label ${bounty.labelName} on issue #${bounty.issueNumber}.`, + url: issueUrl, + }; + }); + } catch (error) { + console.error("[issue-discovery] failed to load bounty issues", error); + return []; + } } const styles: Record = { page: { minHeight: "100vh", margin: 0, - padding: "48px 20px", - background: "#f7f8fb", + padding: "32px 20px 48px", + background: "#f6f8fb", color: "#172033", fontFamily: 'Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif', }, - hero: { - maxWidth: 980, - margin: "0 auto 24px", - padding: "32px 0 8px", - }, - brandRow: { + header: { + maxWidth: 1120, + margin: "0 auto 18px", display: "flex", alignItems: "center", justifyContent: "space-between", - gap: 12, - marginBottom: 18, + gap: 16, + }, + eyebrow: { + margin: "0 0 6px", + color: "#52627a", + fontSize: 13, + fontWeight: 700, + textTransform: "uppercase", + }, + title: { + margin: 0, + fontSize: 36, + lineHeight: 1.15, + letterSpacing: 0, }, - topLinks: { + nav: { display: "flex", alignItems: "center", - flexWrap: "wrap", gap: 10, }, - logo: { - width: 96, - height: 96, + primaryLink: { + padding: "10px 14px", borderRadius: 8, - objectFit: "contain", - }, - logoLink: { - display: "inline-flex", - lineHeight: 0, + background: "#172033", + color: "#ffffff", + fontSize: 14, + fontWeight: 700, + textDecoration: "none", }, - poweredBy: { - display: "inline-flex", - alignItems: "center", + secondaryLink: { padding: "9px 13px", border: "1px solid #c8d0df", - borderRadius: 999, + borderRadius: 8, background: "#ffffff", color: "#172033", fontSize: 14, - fontWeight: 600, + fontWeight: 700, textDecoration: "none", }, - installLink: { - display: "inline-flex", - alignItems: "center", - padding: "10px 14px", + toolbar: { + maxWidth: 1120, + margin: "0 auto 16px", + padding: 16, + border: "1px solid #d9deea", borderRadius: 8, - background: "#172033", - color: "#ffffff", - fontSize: 14, - fontWeight: 700, - textDecoration: "none", + background: "#ffffff", + display: "flex", + alignItems: "end", + justifyContent: "space-between", + gap: 16, + flexWrap: "wrap", }, - eyebrow: { - margin: "0 0 12px", - color: "#52627a", - fontSize: 14, + form: { + display: "flex", + alignItems: "end", + gap: 12, + flexWrap: "wrap", + }, + field: { + display: "grid", + gap: 6, + }, + label: { + color: "#5d6a80", + fontSize: 12, fontWeight: 700, textTransform: "uppercase", }, - title: { - maxWidth: 820, - margin: "0 0 18px", - fontSize: 48, - lineHeight: 1.08, - letterSpacing: 0, + input: { + minWidth: 150, + height: 40, + padding: "0 10px", + border: "1px solid #c8d0df", + borderRadius: 8, + background: "#ffffff", + color: "#172033", + fontSize: 14, }, - lede: { - maxWidth: 760, - margin: "0 0 24px", - color: "#46556e", - fontSize: 18, - lineHeight: 1.65, + button: { + height: 40, + padding: "0 16px", + border: 0, + borderRadius: 8, + background: "#0f766e", + color: "#ffffff", + fontSize: 14, + fontWeight: 800, + cursor: "pointer", }, - endpointGrid: { + summary: { + display: "flex", + alignItems: "center", + gap: 10, + color: "#52627a", + fontSize: 14, + }, + issueList: { + maxWidth: 1120, + margin: "0 auto", display: "grid", - gridTemplateColumns: "repeat(auto-fit, minmax(230px, 1fr))", gap: 12, - maxWidth: 920, }, - endpoint: { + issueCard: { + display: "grid", + gridTemplateColumns: "minmax(0, 1fr) auto", + gap: 18, + padding: 18, border: "1px solid #d9deea", borderRadius: 8, background: "#ffffff", - padding: 16, }, - endpointLabel: { - display: "block", + issueMain: { + minWidth: 0, + }, + issueMeta: { + display: "flex", + alignItems: "center", + gap: 8, + flexWrap: "wrap", marginBottom: 8, - color: "#66748a", - fontSize: 13, - fontWeight: 700, }, - endpointCode: { - color: "#172033", - fontSize: 14, - wordBreak: "break-word", + repo: { + color: "#334155", + fontSize: 13, + fontWeight: 800, }, - section: { - maxWidth: 980, - margin: "18px auto", - padding: 24, - border: "1px solid #d9deea", - borderRadius: 8, - background: "#ffffff", + status: { + padding: "3px 7px", + borderRadius: 6, + background: "#e8f4f2", + color: "#0f766e", + fontSize: 12, + fontWeight: 800, + textTransform: "uppercase", }, - sectionTitle: { - margin: "0 0 16px", - fontSize: 24, + issueTitle: { + margin: "0 0 8px", + fontSize: 20, + lineHeight: 1.25, letterSpacing: 0, }, - paragraph: { - margin: "0 0 14px", - color: "#46556e", - fontSize: 15, - lineHeight: 1.7, - }, - columns: { - display: "grid", - gridTemplateColumns: "repeat(auto-fit, minmax(250px, 1fr))", - gap: 18, + issueLink: { + color: "#172033", + textDecoration: "none", }, - listBlock: { - minWidth: 0, + excerpt: { + margin: 0, + color: "#52627a", + fontSize: 14, + lineHeight: 1.55, }, - listTitle: { - margin: "0 0 10px", - color: "#263247", - fontSize: 16, + issueAside: { + display: "grid", + justifyItems: "end", + alignContent: "center", + gap: 6, + minWidth: 120, }, - list: { - margin: 0, - paddingLeft: 22, - color: "#46556e", - fontSize: 15, - lineHeight: 1.7, + amount: { + color: "#92400e", + fontSize: 18, }, - listItem: { - marginBottom: 8, + date: { + color: "#64748b", + fontSize: 13, }, - codeBlock: { - margin: "14px 0 0", - padding: 16, - overflowX: "auto", + empty: { + maxWidth: 1120, + margin: "0 auto", + padding: 28, + border: "1px solid #d9deea", borderRadius: 8, - background: "#141925", - color: "#eef3ff", - fontSize: 13, - lineHeight: 1.6, + background: "#ffffff", }, - inlineCode: { - padding: "2px 5px", - borderRadius: 5, - background: "#eef1f6", - color: "#263247", - fontSize: "0.92em", + emptyTitle: { + margin: "0 0 8px", + fontSize: 22, + letterSpacing: 0, }, }; diff --git a/src/lib/github/webhook-handler.ts b/src/lib/github/webhook-handler.ts index 46a7c5e..99870e1 100644 --- a/src/lib/github/webhook-handler.ts +++ b/src/lib/github/webhook-handler.ts @@ -3,6 +3,7 @@ import { getEnv } from "@/lib/config/env"; import { serializeError } from "@/lib/errors"; import { parseBountyLabel } from "@/lib/github/bounty-label"; import { createIssueComment } from "@/lib/github/client"; +import { summarizeIssueBody } from "@/lib/issues/discovery"; import { bountyRegisteredMessage, inviteRequiredMessage, @@ -110,6 +111,7 @@ async function handleIssueLabeled(payload: GithubWebhookPayload) { } const repository = await upsertRepository(payload); + const issueMetadata = getIssueMetadata(payload.issue); const bounty = await prisma.bounty.upsert({ where: { repositoryId_issueNumber_labelName: { @@ -122,11 +124,13 @@ async function handleIssueLabeled(payload: GithubWebhookPayload) { amount: parsed.amount, currency: parsed.currency, status: "OPEN", + ...issueMetadata, }, create: { repositoryId: repository.id, issueNumber: payload.issue.number, issueNodeId: payload.issue.node_id, + ...issueMetadata, labelName: parsed.raw, amount: parsed.amount, currency: parsed.currency, @@ -156,6 +160,23 @@ async function handleIssueLabeled(payload: GithubWebhookPayload) { return { bountyId: bounty.id }; } +function getIssueMetadata(issue: GithubWebhookPayload["issue"]) { + return { + issueTitle: typeof issue?.title === "string" ? issue.title : null, + issueUrl: typeof issue?.html_url === "string" ? issue.html_url : null, + issueState: typeof issue?.state === "string" ? issue.state : null, + issueExcerpt: summarizeIssueBody(issue?.body), + issueCreatedAt: dateFromGithub(issue?.created_at), + issueUpdatedAt: dateFromGithub(issue?.updated_at), + }; +} + +function dateFromGithub(value: unknown) { + if (typeof value !== "string") return null; + const date = new Date(value); + return Number.isNaN(date.getTime()) ? null : date; +} + async function handlePullRequestClosed(payload: GithubWebhookPayload) { const env = getEnv(); const pullRequest = payload.pull_request; diff --git a/src/lib/issues/discovery.ts b/src/lib/issues/discovery.ts new file mode 100644 index 0000000..0b6dc9e --- /dev/null +++ b/src/lib/issues/discovery.ts @@ -0,0 +1,94 @@ +export type IssueSort = "recent" | "top"; +export type SortOrder = "asc" | "desc"; + +export interface DiscoveryIssue { + id: string; + title: string; + repository: string; + amount: number; + currency: string; + status: string; + bountyStatus: string; + createdAt: Date; + updatedAt: Date; + excerpt: string; + url: string; +} + +export interface DiscoveryParams { + sort: IssueSort; + order: SortOrder; + minBounty: number; +} + +const DEFAULT_PARAMS: DiscoveryParams = { + sort: "recent", + order: "desc", + minBounty: 0, +}; + +export function normalizeDiscoveryParams( + searchParams: Record, +): DiscoveryParams { + const sort = firstValue(searchParams.sort); + const order = firstValue(searchParams.order); + const minBounty = Number(firstValue(searchParams.minBounty) ?? 0); + + return { + sort: sort === "top" ? "top" : DEFAULT_PARAMS.sort, + order: order === "asc" ? "asc" : DEFAULT_PARAMS.order, + minBounty: + Number.isFinite(minBounty) && minBounty > 0 ? minBounty : DEFAULT_PARAMS.minBounty, + }; +} + +export function filterAndSortIssues( + issues: DiscoveryIssue[], + params: DiscoveryParams, +) { + const direction = params.order === "asc" ? 1 : -1; + + return issues + .filter((issue) => issue.amount >= params.minBounty) + .sort((a, b) => { + if (params.sort === "top") { + const amountDiff = (a.amount - b.amount) * direction; + if (amountDiff !== 0) return amountDiff; + } + + const dateDiff = + (a.updatedAt.getTime() - b.updatedAt.getTime()) * direction; + if (dateDiff !== 0) return dateDiff; + + return a.repository.localeCompare(b.repository); + }); +} + +export function formatRewardAmount(amount: number, currency: string) { + const formatter = new Intl.NumberFormat("en-US", { + maximumFractionDigits: amount % 1 === 0 ? 0 : 6, + }); + + return `${formatter.format(amount)} ${currency}`; +} + +export function summarizeIssueBody(body: unknown, maxLength = 180) { + if (typeof body !== "string") return ""; + + const normalized = body + .replace(//g, " ") + .replace(/```[\s\S]*?```/g, " ") + .replace(/`([^`]+)`/g, "$1") + .replace(/!\[[^\]]*\]\([^)]+\)/g, " ") + .replace(/\[([^\]]+)\]\([^)]+\)/g, "$1") + .replace(/[#>*_\-|]/g, " ") + .replace(/\s+/g, " ") + .trim(); + + if (normalized.length <= maxLength) return normalized; + return `${normalized.slice(0, maxLength - 1).trim()}...`; +} + +function firstValue(value: string | string[] | undefined) { + return Array.isArray(value) ? value[0] : value; +} diff --git a/tests/discovery.test.ts b/tests/discovery.test.ts new file mode 100644 index 0000000..b621c11 --- /dev/null +++ b/tests/discovery.test.ts @@ -0,0 +1,110 @@ +import assert from "node:assert/strict"; +import { describe, it } from "node:test"; +import { + filterAndSortIssues, + normalizeDiscoveryParams, + summarizeIssueBody, +} from "../src/lib/issues/discovery.ts"; + +const baseIssue = { + id: "issue-1", + title: "Add dashboard", + repository: "pvium/github-app", + currency: "USDC", + status: "open", + bountyStatus: "OPEN", + excerpt: "Build a dashboard.", + url: "https://github.com/pvium/github-app/issues/1", +}; + +describe("normalizeDiscoveryParams", () => { + it("keeps invalid controls on safe defaults", () => { + assert.deepEqual( + normalizeDiscoveryParams({ + sort: "unknown", + order: "sideways", + minBounty: "-20", + }), + { + sort: "recent", + order: "desc", + minBounty: 0, + }, + ); + }); + + it("accepts top sorting, ascending order, and a positive minimum bounty", () => { + assert.deepEqual( + normalizeDiscoveryParams({ + sort: "top", + order: "asc", + minBounty: "25", + }), + { + sort: "top", + order: "asc", + minBounty: 25, + }, + ); + }); +}); + +describe("filterAndSortIssues", () => { + const issues = [ + { + ...baseIssue, + id: "low-new", + amount: 10, + createdAt: new Date("2026-05-20T00:00:00Z"), + updatedAt: new Date("2026-05-27T00:00:00Z"), + }, + { + ...baseIssue, + id: "high-old", + amount: 100, + createdAt: new Date("2026-05-18T00:00:00Z"), + updatedAt: new Date("2026-05-22T00:00:00Z"), + }, + { + ...baseIssue, + id: "mid", + amount: 50, + createdAt: new Date("2026-05-19T00:00:00Z"), + updatedAt: new Date("2026-05-25T00:00:00Z"), + }, + ]; + + it("filters by minimum bounty and sorts recent issues first", () => { + assert.deepEqual( + filterAndSortIssues(issues, { + sort: "recent", + order: "desc", + minBounty: 25, + }).map((issue) => issue.id), + ["mid", "high-old"], + ); + }); + + it("sorts top issues by highest payout first", () => { + assert.deepEqual( + filterAndSortIssues(issues, { + sort: "top", + order: "desc", + minBounty: 0, + }).map((issue) => issue.id), + ["high-old", "mid", "low-new"], + ); + }); +}); + +describe("summarizeIssueBody", () => { + it("removes markdown noise and truncates long issue bodies", () => { + assert.equal( + summarizeIssueBody( + "# Title\n\nAdd **recent** [issues](https://example.com) to the page with enough details for discovery.", + 48, + ), + "Title Add recent issues to the page with enough...", + ); + }); +});