From 72c0f8c12ca06668f9b735ccb79045fb8fb114af Mon Sep 17 00:00:00 2001 From: caelum0x Date: Wed, 26 Aug 2026 21:31:07 +0300 Subject: [PATCH] feat(talent): wire recruiter placement/unlock revenue via Creem MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The talent graph's recruiter monetization was designed (Opportunity → Pilot → Proof funnel) but never wired to charge. This adds the placement/candidate-unlock revenue engine on top of the existing talent graph, charged through Creem (a merchant-of-record with Turkey-based-seller payout support — the portfolio standard used by bidstage/CalDesk), not Polar/Stripe. Revenue gate: a recruiter (opportunity owner) unlocks a matched candidate's contact + full evidence. Gating mirrors the referral gate (owner-only, no self-unlock, candidate must have real matching evidence). The fee is charged via a Creem checkout whose custom_price is the exact computed fee, and settled by the signed checkout.completed webhook, which records the entitlement + receipt. - Fee math (pure, configurable): flat unlock access fee (TALENT_UNLOCK_FEE_CENTS, default $49) or a percentage placement success fee (rate + min/max clamps) when a placement amount is supplied. - New TalentPlacement model + migration: entitlement/receipt with a compound unique key (opportunity, candidate, recruiter) for charge idempotency and a unique providerOrderId; provider defaults to creem. - Creem adapter (createCreemCheckout) mirroring the reviewed bidstage lib/creem.ts, and a signed Creem webhook route (HMAC-SHA256, timing-safe) that settles placements. Amount is revalidated against the quoted fee before unlocking. - Routes: POST/GET /talent-graph/opportunities/:id/unlocks and gated GET .../candidates/:candidateId/contact (402 until paid). - Errors.paymentRequired (402) helper. - Tests: fee math, gating, charge idempotency, and the signed webhook settlement path (75 tests). Secrets are env-only (CREEM_API_KEY, CREEM_WEBHOOK_SECRET, CREEM_PRODUCT_ID) — none committed. Co-Authored-By: Claude Opus 4.8 (1M context) --- .env.gitgram.example | 16 +- .../migration.sql | 33 ++ gitgram/backend/prisma/schema.prisma | 33 ++ .../controllers/talentBillingController.ts | 128 ++++++ gitgram/backend/src/index.ts | 5 +- .../backend/src/middleware/errorHandler.ts | 10 + gitgram/backend/src/routes/creemWebhooks.ts | 196 ++++++++ gitgram/backend/src/routes/talentGraph.ts | 5 + gitgram/backend/src/services/creemService.ts | 120 +++++ .../src/services/talentBillingService.ts | 323 ++++++++++++++ gitgram/backend/tests/setup.ts | 2 + .../backend/tests/unit/creemWebhook.test.ts | 157 +++++++ .../backend/tests/unit/talentBilling.test.ts | 418 ++++++++++++++++++ 13 files changed, 1444 insertions(+), 2 deletions(-) create mode 100644 gitgram/backend/prisma/migrations/20260826000000_add_talent_placements/migration.sql create mode 100644 gitgram/backend/src/controllers/talentBillingController.ts create mode 100644 gitgram/backend/src/routes/creemWebhooks.ts create mode 100644 gitgram/backend/src/services/creemService.ts create mode 100644 gitgram/backend/src/services/talentBillingService.ts create mode 100644 gitgram/backend/tests/unit/creemWebhook.test.ts create mode 100644 gitgram/backend/tests/unit/talentBilling.test.ts diff --git a/.env.gitgram.example b/.env.gitgram.example index 9cf2dc97..3f67364c 100644 --- a/.env.gitgram.example +++ b/.env.gitgram.example @@ -18,13 +18,27 @@ GITHUB_CLIENT_SECRET= GOOGLE_CLIENT_ID= GOOGLE_CLIENT_SECRET= -# Payments +# Payments — subscriptions (Polar) POLAR_ACCESS_TOKEN= POLAR_WEBHOOK_SECRET= POLAR_PREMIUM_PRODUCT_ID= POLAR_CREATOR_PRODUCT_ID= POLAR_MODE=production +# Payments — talent-graph recruiter placement / candidate-unlock fees (Creem). +# Creem is a merchant-of-record with Turkey-based-seller payout support. +CREEM_API_KEY= +CREEM_WEBHOOK_SECRET= +CREEM_PRODUCT_ID= +# Set to "false" for live charges; defaults to test mode otherwise. +CREEM_TEST_MODE=false +# Flat candidate-unlock access fee in cents (default 4900 = $49.00). +TALENT_UNLOCK_FEE_CENTS=4900 +# Placement success-fee model (used when a placement amount is supplied). +TALENT_PLACEMENT_FEE_RATE=0.10 +TALENT_PLACEMENT_FEE_MIN_CENTS=4900 +TALENT_PLACEMENT_FEE_MAX_CENTS=2000000 + # Email / monitoring RESEND_API_KEY= SENTRY_DSN= diff --git a/gitgram/backend/prisma/migrations/20260826000000_add_talent_placements/migration.sql b/gitgram/backend/prisma/migrations/20260826000000_add_talent_placements/migration.sql new file mode 100644 index 00000000..069b01be --- /dev/null +++ b/gitgram/backend/prisma/migrations/20260826000000_add_talent_placements/migration.sql @@ -0,0 +1,33 @@ +-- Recruiter placement / candidate-unlock revenue entitlement + receipt. +-- Charged through the Creem adapter (merchant-of-record with Turkey payout +-- support), settled by the signed Creem checkout.completed webhook. + +CREATE TABLE "TalentPlacement" ( + "id" TEXT NOT NULL, + "opportunityId" TEXT NOT NULL, + "candidateId" TEXT NOT NULL, + "recruiterId" TEXT NOT NULL, + "feeCents" INTEGER NOT NULL, + "currency" TEXT NOT NULL DEFAULT 'usd', + "feeModel" TEXT NOT NULL DEFAULT 'unlock', + "status" TEXT NOT NULL DEFAULT 'pending', + "provider" TEXT NOT NULL DEFAULT 'creem', + "checkoutId" TEXT, + "providerOrderId" TEXT, + "paidAt" TIMESTAMP(3), + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updatedAt" TIMESTAMP(3) NOT NULL, + CONSTRAINT "TalentPlacement_pkey" PRIMARY KEY ("id"), + CONSTRAINT "TalentPlacement_feeCents_check" CHECK ("feeCents" >= 0) +); + +CREATE UNIQUE INDEX "TalentPlacement_providerOrderId_key" ON "TalentPlacement"("providerOrderId"); +CREATE UNIQUE INDEX "TalentPlacement_opportunityId_candidateId_recruiterId_key" ON "TalentPlacement"("opportunityId", "candidateId", "recruiterId"); +CREATE INDEX "TalentPlacement_recruiterId_status_idx" ON "TalentPlacement"("recruiterId", "status"); +CREATE INDEX "TalentPlacement_candidateId_idx" ON "TalentPlacement"("candidateId"); +CREATE INDEX "TalentPlacement_status_idx" ON "TalentPlacement"("status"); + +ALTER TABLE "TalentPlacement" + ADD CONSTRAINT "TalentPlacement_opportunityId_fkey" + FOREIGN KEY ("opportunityId") REFERENCES "TalentOpportunity"("id") + ON DELETE CASCADE ON UPDATE CASCADE; diff --git a/gitgram/backend/prisma/schema.prisma b/gitgram/backend/prisma/schema.prisma index 0aba4e11..0f4a2b3c 100644 --- a/gitgram/backend/prisma/schema.prisma +++ b/gitgram/backend/prisma/schema.prisma @@ -1074,6 +1074,7 @@ model TalentOpportunity { revision Int @default(1) pilots TalentPilot[] referrals TalentReferral[] + placements TalentPlacement[] createdAt DateTime @default(now()) updatedAt DateTime @updatedAt @@ -1081,6 +1082,38 @@ model TalentOpportunity { @@index([status, createdAt]) } +/// Recruiter placement/unlock entitlement + receipt. The recruiter (opportunity +/// owner) pays a placement/access fee to unlock a matched candidate's contact +/// and full evidence. The fee is charged through the Creem adapter (Creem is a +/// merchant-of-record that supports Turkey-based sellers) and settled by the +/// signed `checkout.completed` webhook, which flips status to `paid` and stamps +/// the receipt (paidAt + providerOrderId). The compound unique key makes the +/// unlock idempotent: one entitlement per (opportunity, candidate, recruiter), +/// so a repeated unlock request never opens a second charge. +model TalentPlacement { + id String @id @default(cuid()) + opportunityId String + candidateId String + recruiterId String + feeCents Int + currency String @default("usd") + feeModel String @default("unlock") // unlock | placement + status String @default("pending") // pending | paid | failed | refunded + provider String @default("creem") + checkoutId String? + providerOrderId String? @unique + paidAt DateTime? + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + + opportunity TalentOpportunity @relation(fields: [opportunityId], references: [id], onDelete: Cascade) + + @@unique([opportunityId, candidateId, recruiterId]) + @@index([recruiterId, status]) + @@index([candidateId]) + @@index([status]) +} + /// Consent-gated community introduction. The participant controls the outcome; /// public opportunity responses expose aggregate counts rather than identities. model TalentReferral { diff --git a/gitgram/backend/src/controllers/talentBillingController.ts b/gitgram/backend/src/controllers/talentBillingController.ts new file mode 100644 index 00000000..ad6920a8 --- /dev/null +++ b/gitgram/backend/src/controllers/talentBillingController.ts @@ -0,0 +1,128 @@ +import type { Response } from 'express'; +import type { AuthRequest } from '../middleware/auth'; +import { asyncHandler, Errors } from '../middleware/errorHandler'; +import prisma from '../utils/prisma'; +import { getTalentGraph } from '../services/talentGraphService'; +import { + requestCandidateUnlock, + isCandidateUnlocked, +} from '../services/talentBillingService'; + +function boundedId(value: unknown, field: string): string { + const text = typeof value === 'string' ? value.trim() : ''; + if (!text || text.length > 160) { + throw Errors.invalidField(field, `${field} must contain 1 to 160 characters`); + } + return text; +} + +function parsePlacementAmount(value: unknown): number | undefined { + if (value === undefined || value === null || value === '') return undefined; + const amount = Number(value); + if (!Number.isInteger(amount) || amount <= 0) { + throw Errors.invalidField('placementAmountCents', 'placementAmountCents must be a positive integer number of cents'); + } + return amount; +} + +async function requireOwnedOpportunity(opportunityId: string, userId: string) { + const opportunity = await prisma.talentOpportunity.findUnique({ + where: { id: opportunityId }, + select: { id: true, createdById: true }, + }); + if (!opportunity) throw Errors.notFound('Talent opportunity', opportunityId); + if (opportunity.createdById !== userId) { + throw Errors.forbidden('Only the opportunity owner can manage candidate unlocks'); + } + return opportunity; +} + +export const talentBillingController = { + /** + * POST /opportunities/:id/unlocks + * Recruiter opens (or replays) a paid unlock for a matched candidate. Returns a + * Polar checkout URL, or `alreadyUnlocked` when the entitlement is already paid. + */ + requestUnlock: asyncHandler(async (req: AuthRequest, res: Response) => { + const opportunityId = req.params.id; + const candidateId = boundedId(req.body.candidateId, 'candidateId'); + const placementAmountCents = parsePlacementAmount(req.body.placementAmountCents); + + const recruiter = await prisma.user.findUnique({ + where: { id: req.userId! }, + select: { email: true }, + }); + if (!recruiter?.email) throw Errors.userNotFound(req.userId); + + const successUrl = `${process.env.FRONTEND_URL ?? ''}/talent/opportunities/${encodeURIComponent( + opportunityId, + )}?unlocked=${encodeURIComponent(candidateId)}`; + + const result = await requestCandidateUnlock({ + recruiterId: req.userId!, + opportunityId, + candidateId, + recruiterEmail: recruiter.email, + successUrl, + placementAmountCents, + }); + + res.setHeader('Cache-Control', 'no-store'); + res.status(result.alreadyUnlocked ? 200 : 201).json({ data: result }); + }), + + /** + * GET /opportunities/:id/unlocks + * Lists the recruiter's placement entitlements (receipts) for an opportunity. + */ + listUnlocks: asyncHandler(async (req: AuthRequest, res: Response) => { + await requireOwnedOpportunity(req.params.id, req.userId!); + const placements = await prisma.talentPlacement.findMany({ + where: { opportunityId: req.params.id, recruiterId: req.userId! }, + orderBy: { createdAt: 'desc' }, + take: 200, + }); + res.setHeader('Cache-Control', 'no-store, private'); + res.json({ data: placements }); + }), + + /** + * GET /opportunities/:id/candidates/:candidateId/contact + * The gated resource. Contact details + full evidence are returned only when the + * recruiter holds a paid unlock entitlement; otherwise 402 Payment Required. + */ + getCandidateContact: asyncHandler(async (req: AuthRequest, res: Response) => { + const opportunityId = req.params.id; + const candidateId = req.params.candidateId; + await requireOwnedOpportunity(opportunityId, req.userId!); + + const unlocked = await isCandidateUnlocked(opportunityId, candidateId, req.userId!); + if (!unlocked) { + throw Errors.paymentRequired( + 'Unlock this candidate to view their contact details and full evidence', + ); + } + + const candidate = await prisma.user.findUnique({ + where: { id: candidateId }, + select: { id: true, username: true, displayName: true, email: true, githubUsername: true }, + }); + if (!candidate) throw Errors.userNotFound(candidateId); + + const evidence = await getTalentGraph(candidateId, { publicView: true }); + + res.setHeader('Cache-Control', 'no-store, private'); + res.json({ + data: { + contact: { + id: candidate.id, + username: candidate.username, + displayName: candidate.displayName, + email: candidate.email, + githubUsername: candidate.githubUsername, + }, + evidence, + }, + }); + }), +}; diff --git a/gitgram/backend/src/index.ts b/gitgram/backend/src/index.ts index 54b256e2..ba430b18 100644 --- a/gitgram/backend/src/index.ts +++ b/gitgram/backend/src/index.ts @@ -85,6 +85,7 @@ import contributionRoutes from './routes/contributions'; import auditLogRoutes from './routes/auditLog'; import postAnalyticsRoutes from './routes/postAnalytics'; import polarWebhookRoutes from './routes/polarWebhooks'; +import creemWebhookRoutes from './routes/creemWebhooks'; import repositoryInsightsRoutes from './routes/repositoryInsights'; import recommendationRoutes from './routes/recommendations'; import activityRoutes from './routes/activity'; @@ -166,9 +167,11 @@ app.use(requestId); // Compression middleware app.use(compression()); -// Polar webhook must receive the raw body for HMAC signature verification — +// Payment webhooks must receive the raw body for HMAC signature verification — // mount BEFORE the global JSON parser so express.raw captures the unparsed buffer. app.use('/api/v1/webhooks/polar', express.raw({ type: 'application/json' }), polarWebhookRoutes); +// Creem settles the talent-graph recruiter placement / candidate-unlock fees. +app.use('/api/v1/webhooks/creem', express.raw({ type: 'application/json' }), creemWebhookRoutes); // Body parsing middleware app.use(express.json({ limit: '10mb' })); diff --git a/gitgram/backend/src/middleware/errorHandler.ts b/gitgram/backend/src/middleware/errorHandler.ts index ba1a89f3..4891e23d 100644 --- a/gitgram/backend/src/middleware/errorHandler.ts +++ b/gitgram/backend/src/middleware/errorHandler.ts @@ -12,6 +12,7 @@ export type ApiErrorType = | 'rate_limit_exceeded' | 'server_error' | 'conflict' + | 'payment_required' | 'validation_error'; export interface ApiErrorResponse { @@ -182,6 +183,15 @@ export const Errors = { invalidField: (field: string, message: string) => new ApiError('validation_error', 'invalid_field', message, 400, field), + // Payment required errors (402) + paymentRequired: (message?: string) => + new ApiError( + 'payment_required', + 'payment_required', + message || 'Payment is required to access this resource', + 402 + ), + // Conflict errors (409) conflict: (message: string) => new ApiError('conflict', 'conflict', message, 409), diff --git a/gitgram/backend/src/routes/creemWebhooks.ts b/gitgram/backend/src/routes/creemWebhooks.ts new file mode 100644 index 00000000..6b472b8f --- /dev/null +++ b/gitgram/backend/src/routes/creemWebhooks.ts @@ -0,0 +1,196 @@ +/** + * Creem Webhook Route + * + * Settles talent-graph recruiter placement / candidate-unlock fees. Creem sends + * signed events; the signature is HMAC-SHA256 over the raw body using + * CREEM_WEBHOOK_SECRET (see bidstage `app/api/webhooks/creem/route.ts` — the + * reviewed reference this mirrors). + * + * Registered at: POST /api/v1/webhooks/creem + * + * Mounted with express.raw BEFORE the global JSON parser so signature + * verification receives the unparsed buffer: + * app.use('/api/v1/webhooks/creem', express.raw({ type: 'application/json' }), creemWebhookRoutes); + * + * Handled events: + * checkout.completed – a placement fee was paid; settle the entitlement + receipt. + */ + +import { Router, Request, Response } from 'express'; +import { createHmac, timingSafeEqual } from 'crypto'; +import logger from '../utils/logger'; +import { creemEnv } from '../services/creemService'; +import { settlePlacementOrder } from '../services/talentBillingService'; + +// --------------------------------------------------------------------------- +// Types + parsing helpers +// --------------------------------------------------------------------------- + +type JsonObject = Record; + +interface CreemEvent { + id: string; + eventType: string; + object: JsonObject & { id: string }; +} + +function asObject(value: unknown, label: string): JsonObject { + if (!value || typeof value !== 'object' || Array.isArray(value)) { + throw new Error(`${label} must be an object`); + } + return value as JsonObject; +} + +function asText(value: unknown, label: string): string { + if (typeof value !== 'string' || value.length === 0) { + throw new Error(`${label} must be a non-empty string`); + } + return value; +} + +function entityId(value: unknown): string | null { + if (typeof value === 'string') return value; + if (value && typeof value === 'object' && !Array.isArray(value)) { + const id = (value as JsonObject).id; + return typeof id === 'string' ? id : null; + } + return null; +} + +function parseEvent(value: unknown): CreemEvent { + const envelope = asObject(value, 'Creem event'); + const payload = asObject(envelope.object, 'Creem event object'); + return { + id: asText(envelope.id, 'Creem event id'), + eventType: asText(envelope.eventType, 'Creem event type'), + object: { ...payload, id: asText(payload.id, 'Creem object id') }, + }; +} + +// --------------------------------------------------------------------------- +// Signature verification (HMAC-SHA256, hex, timing-safe) +// --------------------------------------------------------------------------- + +function verifiedSignature(rawBody: Buffer, signature: string, secret: string): boolean { + if (!/^[a-f0-9]{64}$/i.test(signature)) return false; + const expected = createHmac('sha256', secret).update(rawBody).digest(); + const supplied = Buffer.from(signature, 'hex'); + return supplied.length === expected.length && timingSafeEqual(supplied, expected); +} + +function validMode(mode: unknown, testMode: boolean): boolean { + if (typeof mode !== 'string') return false; + return testMode ? ['test', 'sandbox', 'local'].includes(mode) : mode === 'prod'; +} + +// --------------------------------------------------------------------------- +// checkout.completed → settle placement +// --------------------------------------------------------------------------- + +async function settleCheckoutCompleted( + event: CreemEvent, + expectedProductId: string, + testMode: boolean, +): Promise { + const payload = event.object; + const order = asObject(payload.order, 'Creem order'); + const metadata = payload.metadata && typeof payload.metadata === 'object' && !Array.isArray(payload.metadata) + ? (payload.metadata as JsonObject) + : {}; + + if ( + payload.status !== 'completed' || + order.status !== 'paid' || + entityId(order.product) !== expectedProductId || + !validMode(payload.mode, testMode) + ) { + logger.warn('[creemWebhook] checkout.completed is not a paid order for the configured product', { + eventId: event.id, + status: payload.status, + orderStatus: order.status, + }); + return; + } + + // We anchored request_id to the placement id when opening the checkout. + const placementId = + (typeof metadata.placementId === 'string' && metadata.placementId) || + (typeof payload.request_id === 'string' ? payload.request_id : ''); + if (!placementId) { + logger.warn('[creemWebhook] checkout.completed missing placement reference', { eventId: event.id }); + return; + } + + const amountCents = Number.isSafeInteger(order.amount) ? (order.amount as number) : undefined; + const result = await settlePlacementOrder({ + placementId, + providerOrderId: asText(order.id, 'Creem order id'), + amountCents, + }); + + logger.info('[creemWebhook] checkout.completed processed', { + eventId: event.id, + placementId, + settled: result.settled, + alreadyPaid: result.alreadyPaid, + amountMismatch: result.amountMismatch ?? false, + }); +} + +// --------------------------------------------------------------------------- +// Route +// --------------------------------------------------------------------------- + +const router = Router(); + +router.post('/', async (req: Request, res: Response): Promise => { + const signature = req.headers['creem-signature']; + if (typeof signature !== 'string' || signature.length === 0) { + res.status(400).json({ success: false, error: 'missing_signature' }); + return; + } + + let env: ReturnType; + try { + env = creemEnv(); + } catch (err: unknown) { + logger.error('[creemWebhook] Creem is not configured — rejecting', { + error: err instanceof Error ? err.message : String(err), + }); + res.status(503).json({ success: false, error: 'creem_not_configured' }); + return; + } + + const rawBody = Buffer.isBuffer(req.body) ? req.body : Buffer.from(JSON.stringify(req.body ?? {})); + if (!verifiedSignature(rawBody, signature, env.webhookSecret)) { + logger.warn('[creemWebhook] Signature verification failed'); + res.status(400).json({ success: false, error: 'invalid_signature' }); + return; + } + + let event: CreemEvent; + try { + event = parseEvent(JSON.parse(rawBody.toString('utf-8'))); + } catch { + res.status(400).json({ success: false, error: 'invalid_event' }); + return; + } + + try { + if (event.eventType === 'checkout.completed') { + await settleCheckoutCompleted(event, env.productId, env.testMode); + } else { + logger.info('[creemWebhook] Unhandled event type — ignored', { eventType: event.eventType }); + } + res.status(200).json({ success: true, received: true }); + } catch (err: unknown) { + logger.error('[creemWebhook] Event processing failed', { + eventId: event.id, + eventType: event.eventType, + error: err instanceof Error ? err.message : String(err), + }); + res.status(500).json({ success: false, error: 'event_processing_failed' }); + } +}); + +export default router; diff --git a/gitgram/backend/src/routes/talentGraph.ts b/gitgram/backend/src/routes/talentGraph.ts index 3dabaaed..36243058 100644 --- a/gitgram/backend/src/routes/talentGraph.ts +++ b/gitgram/backend/src/routes/talentGraph.ts @@ -1,6 +1,7 @@ import { Router, type NextFunction, type Request, type Response } from 'express'; import { authenticate, optionalAuth } from '../middleware/auth'; import { talentGraphController } from '../controllers/talentGraphController'; +import { talentBillingController } from '../controllers/talentBillingController'; import { interactionLimiter } from '../middleware/rateLimiter'; import { Errors } from '../middleware/errorHandler'; @@ -32,6 +33,10 @@ router.get('/opportunities', optionalAuth, talentGraphController.listOpportuniti router.post('/opportunities', authenticate, requireMutationOrigin, interactionLimiter, talentGraphController.createOpportunity); router.get('/opportunities/:id/matches', optionalAuth, talentGraphController.getOpportunityMatches); router.get('/opportunities/:id/coverage', optionalAuth, talentGraphController.getOpportunityCoverage); +// Recruiter placement / candidate-unlock revenue gate. +router.get('/opportunities/:id/unlocks', authenticate, talentBillingController.listUnlocks); +router.post('/opportunities/:id/unlocks', authenticate, requireMutationOrigin, interactionLimiter, talentBillingController.requestUnlock); +router.get('/opportunities/:id/candidates/:candidateId/contact', authenticate, talentBillingController.getCandidateContact); router.post('/opportunities/:id/pilots', authenticate, requireMutationOrigin, interactionLimiter, talentGraphController.startPilot); router.post('/opportunities/:id/referrals', authenticate, requireMutationOrigin, interactionLimiter, talentGraphController.createReferral); router.get('/referrals/mine', authenticate, talentGraphController.listMyReferrals); diff --git a/gitgram/backend/src/services/creemService.ts b/gitgram/backend/src/services/creemService.ts new file mode 100644 index 00000000..8cf0fb92 --- /dev/null +++ b/gitgram/backend/src/services/creemService.ts @@ -0,0 +1,120 @@ +/** + * Creem payment adapter. + * + * Creem is a merchant-of-record that supports Turkey-based sellers, so it is the + * portfolio-standard provider (bidstage + CalDesk) for GitGram's recruiter + * placement fees. This mirrors the reviewed bidstage `lib/creem.ts` checkout + * adapter: a configured one-time product anchors the checkout and `custom_price` + * carries the exact fee computed by the talent billing engine. Price and + * settlement are revalidated in the signed webhook before an entitlement is + * granted. + * + * Secrets are read from the environment only — never hardcoded: + * CREEM_API_KEY, CREEM_PRODUCT_ID, CREEM_WEBHOOK_SECRET, CREEM_TEST_MODE. + */ + +export interface CreemEnv { + apiKey: string; + productId: string; + webhookSecret: string; + testMode: boolean; +} + +function requiredEnv(name: string): string { + const value = process.env[name]; + if (!value || value.trim() === '') { + throw new Error(`${name} is not configured`); + } + return value.trim(); +} + +/** + * Resolves and validates the Creem configuration. Reads fresh each call (no + * module-level caching) so tests and hot config changes stay honest. + */ +export function creemEnv(): CreemEnv { + return { + apiKey: requiredEnv('CREEM_API_KEY'), + productId: requiredEnv('CREEM_PRODUCT_ID'), + webhookSecret: requiredEnv('CREEM_WEBHOOK_SECRET'), + // Default to test mode unless explicitly disabled, matching bidstage. + testMode: process.env.CREEM_TEST_MODE !== 'false', + }; +} + +export function creemBaseUrl(testMode: boolean): string { + return testMode ? 'https://test-api.creem.io' : 'https://api.creem.io'; +} + +export type CreemCheckoutStatus = 'pending' | 'processing' | 'completed' | 'expired'; + +export interface CreemCheckout { + id: string; + checkoutUrl: string; + status: CreemCheckoutStatus; +} + +export interface CreateCreemCheckoutInput { + /** Our stable reference for this charge (the placement id). */ + requestId: string; + /** Exact amount to charge, in cents (drives Creem custom_price). */ + amountCents: number; + successUrl: string; + metadata: Record; +} + +interface CreemCheckoutResponse { + id?: unknown; + checkout_url?: unknown; + status?: unknown; +} + +const CHECKOUT_STATUSES: CreemCheckoutStatus[] = ['pending', 'processing', 'completed', 'expired']; + +/** + * Opens a Creem checkout for a one-time placement/unlock fee. Returns the + * provider checkout id + hosted checkout URL the recruiter is redirected to. + */ +export async function createCreemCheckout( + input: Readonly, +): Promise { + if (!Number.isInteger(input.amountCents) || input.amountCents <= 0) { + throw new Error('Creem checkout amount must be a positive integer number of cents'); + } + const env = creemEnv(); + const response = await fetch(`${creemBaseUrl(env.testMode)}/v1/checkouts`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'x-api-key': env.apiKey, + }, + body: JSON.stringify({ + product_id: env.productId, + request_id: input.requestId, + units: 1, + custom_price: input.amountCents, + success_url: input.successUrl, + metadata: input.metadata, + }), + cache: 'no-store', + signal: AbortSignal.timeout(10_000), + }); + + const body = (await response.json().catch(() => ({}))) as CreemCheckoutResponse; + if (!response.ok) { + throw new Error(`Creem checkout failed with status ${response.status}`); + } + if ( + typeof body.id !== 'string' || + typeof body.checkout_url !== 'string' || + !/^https:\/\//i.test(body.checkout_url) || + !CHECKOUT_STATUSES.includes(String(body.status) as CreemCheckoutStatus) + ) { + throw new Error('Creem returned an invalid checkout response'); + } + return { + id: body.id, + checkoutUrl: body.checkout_url, + status: body.status as CreemCheckoutStatus, + }; +} diff --git a/gitgram/backend/src/services/talentBillingService.ts b/gitgram/backend/src/services/talentBillingService.ts new file mode 100644 index 00000000..5aad679f --- /dev/null +++ b/gitgram/backend/src/services/talentBillingService.ts @@ -0,0 +1,323 @@ +/** + * Talent Graph placement / candidate-unlock revenue engine. + * + * This is the recruiter monetization the talent graph was designed for but never + * wired: a recruiter (the opportunity owner) pays a placement/access fee to + * unlock a matched candidate's contact details and full evidence. The fee is + * charged through the shared Polar adapter (the same provider used for + * subscriptions and the store) and settled by the Polar `order.created` webhook. + * + * Design notes: + * - Fee math is pure and configuration-driven (see the `*FeeCents` helpers). + * - Gating mirrors the referral gate: only the opportunity owner may unlock, and + * only a candidate with real matching evidence can be unlocked. + * - The charge is idempotent. The DB enforces one entitlement per + * (opportunity, candidate, recruiter); a repeated unlock never opens a second + * charge, and settlement is a no-op once the entitlement is already paid. + * - Every function accepts injectable dependencies so the flow can be unit + * tested without a live Postgres, Polar, or the matcher (same pattern as + * `findTalentMatches`). + */ +import prisma from '../utils/prisma'; +import { findTalentMatches } from './talentGraphService'; +import { createCreemCheckout } from './creemService'; +import { Errors } from '../middleware/errorHandler'; +import logger from '../utils/logger'; + +// --------------------------------------------------------------------------- +// Configuration + fee math (pure) +// --------------------------------------------------------------------------- + +/** Flat access fee to unlock a single candidate's contact + evidence. */ +export const DEFAULT_UNLOCK_FEE_CENTS = 4900; // $49.00 +/** Success-fee rate applied to an agreed placement amount (Wellfound-style). */ +export const DEFAULT_PLACEMENT_FEE_RATE = 0.1; // 10% +/** Floor for a computed placement success fee. */ +export const DEFAULT_PLACEMENT_FEE_MIN_CENTS = 4900; // $49.00 +/** Ceiling for a computed placement success fee. */ +export const DEFAULT_PLACEMENT_FEE_MAX_CENTS = 2_000_000; // $20,000.00 +/** Absolute guard rail — reject absurd inputs before they reach a charge. */ +const MAX_REASONABLE_AMOUNT_CENTS = 1_000_000_000; // $10,000,000.00 + +export type FeeModel = 'unlock' | 'placement'; + +function readPositiveIntEnv(name: string, fallback: number): number { + const raw = process.env[name]; + if (raw === undefined || raw === '') return fallback; + const value = Number(raw); + if (!Number.isInteger(value) || value <= 0) { + logger.warn(`[talentBilling] ${name} is not a positive integer — using default`, { raw, fallback }); + return fallback; + } + return value; +} + +function readRateEnv(name: string, fallback: number): number { + const raw = process.env[name]; + if (raw === undefined || raw === '') return fallback; + const value = Number(raw); + if (!Number.isFinite(value) || value <= 0 || value >= 1) { + logger.warn(`[talentBilling] ${name} must be a rate in (0, 1) — using default`, { raw, fallback }); + return fallback; + } + return value; +} + +/** The flat candidate-unlock access fee, in cents. */ +export function getUnlockFeeCents(): number { + return readPositiveIntEnv('TALENT_UNLOCK_FEE_CENTS', DEFAULT_UNLOCK_FEE_CENTS); +} + +export interface PlacementFeeOptions { + rate?: number; + minCents?: number; + maxCents?: number; +} + +/** + * Computes a placement success fee from an agreed placement amount: + * fee = clamp(round(amount * rate), min, max) + * Rounding is half-up to the nearest cent. Throws on non-positive / non-integer + * amounts so a bad input can never silently produce a charge. + */ +export function computePlacementFeeCents( + placementAmountCents: number, + options: PlacementFeeOptions = {}, +): number { + if (!Number.isInteger(placementAmountCents) || placementAmountCents <= 0) { + throw Errors.invalidField( + 'placementAmountCents', + 'placementAmountCents must be a positive integer number of cents', + ); + } + if (placementAmountCents > MAX_REASONABLE_AMOUNT_CENTS) { + throw Errors.invalidField('placementAmountCents', 'placementAmountCents is unreasonably large'); + } + + const rate = options.rate ?? readRateEnv('TALENT_PLACEMENT_FEE_RATE', DEFAULT_PLACEMENT_FEE_RATE); + const minCents = options.minCents ?? readPositiveIntEnv('TALENT_PLACEMENT_FEE_MIN_CENTS', DEFAULT_PLACEMENT_FEE_MIN_CENTS); + const maxCents = options.maxCents ?? readPositiveIntEnv('TALENT_PLACEMENT_FEE_MAX_CENTS', DEFAULT_PLACEMENT_FEE_MAX_CENTS); + // Guard against a misconfigured floor above the ceiling. + const effectiveMin = Math.min(minCents, maxCents); + + const raw = Math.round(placementAmountCents * rate); + return Math.min(maxCents, Math.max(effectiveMin, raw)); +} + +/** + * Resolves the fee for an unlock request. When the recruiter supplies an agreed + * placement amount the success-fee model applies; otherwise the flat access fee. + */ +export function resolvePlacementFee(input: { placementAmountCents?: number }): { + feeCents: number; + feeModel: FeeModel; +} { + if (input.placementAmountCents !== undefined) { + return { feeCents: computePlacementFeeCents(input.placementAmountCents), feeModel: 'placement' }; + } + return { feeCents: getUnlockFeeCents(), feeModel: 'unlock' }; +} + +// --------------------------------------------------------------------------- +// Injectable dependency shapes +// --------------------------------------------------------------------------- + +/** Minimal Prisma surface the billing flow touches. */ +export type BillingDb = { + talentOpportunity: { findUnique: (args: any) => Promise }; + talentPlacement: { + findUnique: (args: any) => Promise; + create: (args: any) => Promise; + update: (args: any) => Promise; + }; +}; + +export interface UnlockDeps { + db?: BillingDb; + matcher?: typeof findTalentMatches; + createCheckout?: typeof createCreemCheckout; +} + +export interface RequestCandidateUnlockParams { + recruiterId: string; + opportunityId: string; + candidateId: string; + recruiterEmail: string; + successUrl: string; + placementAmountCents?: number; +} + +export interface RequestCandidateUnlockResult { + placement: any; + checkoutUrl: string | null; + alreadyUnlocked: boolean; +} + +function placementWhere(opportunityId: string, candidateId: string, recruiterId: string) { + return { opportunityId_candidateId_recruiterId: { opportunityId, candidateId, recruiterId } }; +} + +// --------------------------------------------------------------------------- +// Unlock request (the charged gate) +// --------------------------------------------------------------------------- + +/** + * Opens (or replays) a candidate-unlock charge for a recruiter. Gating: + * - the opportunity must exist and be owned by the recruiter; + * - a recruiter cannot unlock themselves; + * - the candidate must be a real match with evidence for the opportunity. + * + * Idempotency: a paid entitlement short-circuits with no new charge; a pending + * entitlement is reused so at most one charge is ever open per candidate. + */ +export async function requestCandidateUnlock( + params: RequestCandidateUnlockParams, + deps: UnlockDeps = {}, +): Promise { + const db = deps.db ?? (prisma as unknown as BillingDb); + const matcher = deps.matcher ?? findTalentMatches; + const createCheckout = deps.createCheckout ?? createCreemCheckout; + + const { recruiterId, opportunityId, candidateId } = params; + if (candidateId === recruiterId) { + throw Errors.badRequest('A recruiter cannot unlock their own profile'); + } + + const opportunity = await db.talentOpportunity.findUnique({ where: { id: opportunityId } }); + if (!opportunity) throw Errors.notFound('Talent opportunity', opportunityId); + if (opportunity.createdById !== recruiterId) { + throw Errors.forbidden('Only the opportunity owner can unlock candidates'); + } + + // Reuse an existing entitlement before charging again (DB-backed idempotency). + const existing = await db.talentPlacement.findUnique({ + where: placementWhere(opportunityId, candidateId, recruiterId), + }); + if (existing?.status === 'paid') { + return { placement: existing, checkoutUrl: null, alreadyUnlocked: true }; + } + + // Gate: the candidate must have real, matching evidence for this opportunity. + const matches = await matcher(opportunity.requiredSkills, 25, db as any); + const candidateMatch = matches.find((match) => match.profile.id === candidateId); + if (!candidateMatch || candidateMatch.projects.length === 0) { + throw Errors.badRequest( + 'Candidate must have public repository or completed-pilot evidence matching this opportunity', + ); + } + + const { feeCents, feeModel } = resolvePlacementFee(params); + + const placement = existing + ? existing + : await db.talentPlacement.create({ + data: { opportunityId, candidateId, recruiterId, feeCents, feeModel, status: 'pending' }, + }); + + // Creem custom_price charges the exact fee our engine computed; the amount is + // revalidated against feeCents in the signed webhook before we grant access. + const checkout = await createCheckout({ + requestId: placement.id, + amountCents: feeCents, + successUrl: params.successUrl, + metadata: { + kind: 'talent_placement', + placementId: placement.id, + opportunityId, + candidateId, + recruiterId, + feeModel, + recruiterEmail: params.recruiterEmail, + }, + }); + + const withCheckout = await db.talentPlacement.update({ + where: { id: placement.id }, + data: { checkoutId: checkout.id }, + }); + + logger.info('[talentBilling] Candidate unlock checkout opened', { + placementId: placement.id, + opportunityId, + recruiterId, + feeCents, + feeModel, + provider: 'creem', + }); + + return { placement: withCheckout, checkoutUrl: checkout.checkoutUrl, alreadyUnlocked: false }; +} + +// --------------------------------------------------------------------------- +// Settlement (Polar order webhook) + entitlement check +// --------------------------------------------------------------------------- + +export interface SettlePlacementParams { + placementId: string; + providerOrderId: string; + /** Amount the provider reports as paid; revalidated against the quoted fee. */ + amountCents?: number; +} + +export interface SettlePlacementResult { + settled: boolean; + alreadyPaid: boolean; + amountMismatch?: boolean; +} + +/** + * Settles a placement entitlement from a paid Creem order. Idempotent: replaying + * the same order (or any order for an already-paid placement) is a no-op. When + * the provider reports an amount it must equal the quoted fee, so a tampered or + * under-paid checkout can never unlock a candidate. + */ +export async function settlePlacementOrder( + params: SettlePlacementParams, + deps: { db?: BillingDb } = {}, +): Promise { + const db = deps.db ?? (prisma as unknown as BillingDb); + const placement = await db.talentPlacement.findUnique({ where: { id: params.placementId } }); + + if (!placement) { + logger.warn('[talentBilling] settle: placement not found', { placementId: params.placementId }); + return { settled: false, alreadyPaid: false }; + } + if (placement.status === 'paid') { + logger.info('[talentBilling] settle: placement already paid — no-op', { placementId: placement.id }); + return { settled: false, alreadyPaid: true }; + } + if (params.amountCents !== undefined && params.amountCents !== placement.feeCents) { + logger.error('[talentBilling] settle: paid amount does not match quoted fee — refusing', { + placementId: placement.id, + quotedFeeCents: placement.feeCents, + paidAmountCents: params.amountCents, + }); + return { settled: false, alreadyPaid: false, amountMismatch: true }; + } + + await db.talentPlacement.update({ + where: { id: placement.id }, + data: { status: 'paid', paidAt: new Date(), providerOrderId: params.providerOrderId }, + }); + + logger.info('[talentBilling] Placement settled — candidate unlocked', { + placementId: placement.id, + providerOrderId: params.providerOrderId, + feeCents: placement.feeCents, + }); + + return { settled: true, alreadyPaid: false }; +} + +/** True only when the recruiter holds a paid unlock entitlement for the candidate. */ +export async function isCandidateUnlocked( + opportunityId: string, + candidateId: string, + recruiterId: string, + db: BillingDb = prisma as unknown as BillingDb, +): Promise { + const placement = await db.talentPlacement.findUnique({ + where: placementWhere(opportunityId, candidateId, recruiterId), + }); + return placement?.status === 'paid'; +} diff --git a/gitgram/backend/tests/setup.ts b/gitgram/backend/tests/setup.ts index d38cfd83..493688b3 100644 --- a/gitgram/backend/tests/setup.ts +++ b/gitgram/backend/tests/setup.ts @@ -437,6 +437,8 @@ const mockPrisma: any = { repositoryReferrer: createMockPrismaModel(), storeItem: createMockPrismaModel(), storePurchase: createMockPrismaModel(), + talentOpportunity: createMockPrismaModel(), + talentPlacement: createMockPrismaModel(), $connect: jest.fn().mockResolvedValue(undefined), $disconnect: jest.fn().mockResolvedValue(undefined), $transaction: jest.fn().mockImplementation(async (fn: any) => { diff --git a/gitgram/backend/tests/unit/creemWebhook.test.ts b/gitgram/backend/tests/unit/creemWebhook.test.ts new file mode 100644 index 00000000..9f826ab1 --- /dev/null +++ b/gitgram/backend/tests/unit/creemWebhook.test.ts @@ -0,0 +1,157 @@ +/** + * Integration test for the Creem placement webhook. + * + * Mounts only the Creem webhook router (with express.raw, exactly as index.ts + * does) so the signed-settlement path is exercised end-to-end without the full + * app. Prisma is the shared in-memory mock from tests/setup.ts. + * + * Covers: valid signed checkout.completed settles + unlocks the placement; + * a bad signature is rejected; and redelivery is idempotent. + */ +import crypto from 'crypto'; +import express from 'express'; +import request from 'supertest'; +import { mockPrisma } from '../setup'; + +const WEBHOOK_SECRET = 'creem-webhook-secret-value'; +const PRODUCT_ID = 'prod_talent_placement'; + +process.env.CREEM_API_KEY = 'creem-test-key'; +process.env.CREEM_PRODUCT_ID = PRODUCT_ID; +process.env.CREEM_WEBHOOK_SECRET = WEBHOOK_SECRET; +process.env.CREEM_TEST_MODE = 'true'; + +import creemWebhookRouter from '../../src/routes/creemWebhooks'; + +function buildApp() { + const app = express(); + app.use('/api/v1/webhooks/creem', express.raw({ type: 'application/json' }), creemWebhookRouter); + return app; +} + +function sign(rawBody: string): string { + return crypto.createHmac('sha256', WEBHOOK_SECRET).update(rawBody).digest('hex'); +} + +function seedPendingPlacement(feeCents = 4900): void { + mockPrisma.talentPlacement.__rows.push({ + id: 'placement-1', + opportunityId: 'opp-1', + candidateId: 'candidate-1', + recruiterId: 'recruiter-1', + feeCents, + feeModel: 'unlock', + status: 'pending', + provider: 'creem', + checkoutId: 'checkout-1', + providerOrderId: null, + paidAt: null, + }); +} + +function checkoutCompletedEvent(overrides: Record = {}) { + return { + id: 'evt_1', + eventType: 'checkout.completed', + object: { + id: 'ch_1', + status: 'completed', + mode: 'test', + request_id: 'placement-1', + metadata: { placementId: 'placement-1', kind: 'talent_placement' }, + order: { + id: 'ord_1', + status: 'paid', + product: PRODUCT_ID, + amount: 4900, + currency: 'usd', + }, + ...overrides, + }, + }; +} + +beforeEach(() => { + (mockPrisma.talentPlacement as any).__rows.length = 0; +}); + +describe('POST /api/v1/webhooks/creem', () => { + it('rejects a missing signature', async () => { + const res = await request(buildApp()) + .post('/api/v1/webhooks/creem') + .set('Content-Type', 'application/json') + .send(JSON.stringify(checkoutCompletedEvent())); + expect(res.status).toBe(400); + expect(res.body.error).toBe('missing_signature'); + }); + + it('rejects an invalid signature', async () => { + const raw = JSON.stringify(checkoutCompletedEvent()); + const res = await request(buildApp()) + .post('/api/v1/webhooks/creem') + .set('Content-Type', 'application/json') + .set('creem-signature', 'a'.repeat(64)) + .send(raw); + expect(res.status).toBe(400); + expect(res.body.error).toBe('invalid_signature'); + }); + + it('settles + unlocks the placement on a valid signed checkout.completed', async () => { + seedPendingPlacement(); + const raw = JSON.stringify(checkoutCompletedEvent()); + const res = await request(buildApp()) + .post('/api/v1/webhooks/creem') + .set('Content-Type', 'application/json') + .set('creem-signature', sign(raw)) + .send(raw); + + expect(res.status).toBe(200); + expect(res.body).toEqual({ success: true, received: true }); + + const row = (mockPrisma.talentPlacement as any).__rows.find((r: any) => r.id === 'placement-1'); + expect(row.status).toBe('paid'); + expect(row.providerOrderId).toBe('ord_1'); + expect(row.paidAt).toBeInstanceOf(Date); + }); + + it('is idempotent across redelivery of the same event', async () => { + seedPendingPlacement(); + const raw = JSON.stringify(checkoutCompletedEvent()); + const app = buildApp(); + + await request(app) + .post('/api/v1/webhooks/creem') + .set('Content-Type', 'application/json') + .set('creem-signature', sign(raw)) + .send(raw); + const firstPaidAt = (mockPrisma.talentPlacement as any).__rows.find((r: any) => r.id === 'placement-1').paidAt; + + const res = await request(app) + .post('/api/v1/webhooks/creem') + .set('Content-Type', 'application/json') + .set('creem-signature', sign(raw)) + .send(raw); + + expect(res.status).toBe(200); + const row = (mockPrisma.talentPlacement as any).__rows.find((r: any) => r.id === 'placement-1'); + expect(row.status).toBe('paid'); + expect(row.paidAt).toBe(firstPaidAt); // unchanged — no re-settlement + }); + + it('does not settle when the order product does not match the configured product', async () => { + seedPendingPlacement(); + const event = checkoutCompletedEvent({ + order: { id: 'ord_1', status: 'paid', product: 'prod_wrong', amount: 4900, currency: 'usd' }, + }); + const raw = JSON.stringify(event); + const res = await request(buildApp()) + .post('/api/v1/webhooks/creem') + .set('Content-Type', 'application/json') + .set('creem-signature', sign(raw)) + .send(raw); + + expect(res.status).toBe(200); // acknowledged, but ignored + const row = (mockPrisma.talentPlacement as any).__rows.find((r: any) => r.id === 'placement-1'); + expect(row.status).toBe('pending'); + }); +}); diff --git a/gitgram/backend/tests/unit/talentBilling.test.ts b/gitgram/backend/tests/unit/talentBilling.test.ts new file mode 100644 index 00000000..57ff950e --- /dev/null +++ b/gitgram/backend/tests/unit/talentBilling.test.ts @@ -0,0 +1,418 @@ +/** + * Unit tests for the talent-graph placement / candidate-unlock revenue engine + * (talentBillingService). Covers the three load-bearing concerns of a charge: + * 1. Fee math — flat unlock fee + percentage placement success fee (rounding, + * floor/ceiling clamps, invalid inputs). + * 2. Gating — only the opportunity owner can unlock, no self-unlock, and the + * candidate must have real matching evidence. + * 3. Idempotency — a paid entitlement never re-charges, a pending entitlement + * is reused, and settlement is a no-op once paid. + * + * Everything runs in-memory against injected fakes (db / matcher / checkout), so + * no live Postgres or Polar is required — the same pattern as the matcher tests. + */ +import { + getUnlockFeeCents, + computePlacementFeeCents, + resolvePlacementFee, + requestCandidateUnlock, + settlePlacementOrder, + isCandidateUnlocked, + DEFAULT_UNLOCK_FEE_CENTS, + type BillingDb, +} from '../../src/services/talentBillingService'; + +// --------------------------------------------------------------------------- +// In-memory fakes +// --------------------------------------------------------------------------- + +type PlacementRow = { + id: string; + opportunityId: string; + candidateId: string; + recruiterId: string; + feeCents: number; + feeModel: string; + status: string; + checkoutId?: string | null; + polarOrderId?: string | null; + paidAt?: Date | null; +}; + +function makeFakeDb(opportunity: any, seedPlacements: PlacementRow[] = []) { + const placements = [...seedPlacements]; + let counter = 0; + const db: BillingDb = { + talentOpportunity: { + findUnique: async ({ where }: any) => + opportunity && opportunity.id === where.id ? { ...opportunity } : null, + }, + talentPlacement: { + findUnique: async ({ where }: any) => { + if (where.id) return placements.find((p) => p.id === where.id) ?? null; + const key = where.opportunityId_candidateId_recruiterId; + if (key) { + return ( + placements.find( + (p) => + p.opportunityId === key.opportunityId && + p.candidateId === key.candidateId && + p.recruiterId === key.recruiterId, + ) ?? null + ); + } + return null; + }, + create: async ({ data }: any) => { + const row: PlacementRow = { id: `placement-${++counter}`, ...data }; + placements.push(row); + return { ...row }; + }, + update: async ({ where, data }: any) => { + const row = placements.find((p) => p.id === where.id); + if (!row) throw new Error('placement not found'); + Object.assign(row, data); + return { ...row }; + }, + }, + }; + return { db, placements }; +} + +const OPPORTUNITY = { + id: 'opp-1', + createdById: 'recruiter-1', + requiredSkills: ['typescript'], +}; + +function matcherWithEvidence(candidateId: string) { + return (async () => [ + { profile: { id: candidateId }, projects: [{ id: 'r1' }] }, + ]) as any; +} + +const matcherNoEvidence = (async () => []) as any; + +function fakeCheckout() { + const calls: any[] = []; + const fn = (async (input: any) => { + calls.push(input); + return { + id: `checkout-${calls.length}`, + checkoutUrl: `https://checkout.creem.io/session-${calls.length}`, + status: 'pending' as const, + }; + }) as any; + return { fn, calls }; +} + +const baseParams = { + recruiterId: 'recruiter-1', + opportunityId: 'opp-1', + candidateId: 'candidate-1', + recruiterEmail: 'recruiter@example.com', + successUrl: 'https://app.example.com/return', +}; + +// --------------------------------------------------------------------------- +// Fee math +// --------------------------------------------------------------------------- + +describe('fee math', () => { + const ENV_KEYS = [ + 'TALENT_UNLOCK_FEE_CENTS', + 'TALENT_PLACEMENT_FEE_RATE', + 'TALENT_PLACEMENT_FEE_MIN_CENTS', + 'TALENT_PLACEMENT_FEE_MAX_CENTS', + ]; + const saved: Record = {}; + + beforeEach(() => { + for (const key of ENV_KEYS) { + saved[key] = process.env[key]; + delete process.env[key]; + } + }); + afterEach(() => { + for (const key of ENV_KEYS) { + if (saved[key] === undefined) delete process.env[key]; + else process.env[key] = saved[key]; + } + }); + + it('returns the default flat unlock fee', () => { + expect(getUnlockFeeCents()).toBe(DEFAULT_UNLOCK_FEE_CENTS); + expect(getUnlockFeeCents()).toBe(4900); + }); + + it('honours a valid TALENT_UNLOCK_FEE_CENTS override', () => { + process.env.TALENT_UNLOCK_FEE_CENTS = '9900'; + expect(getUnlockFeeCents()).toBe(9900); + }); + + it('falls back to the default when the env override is invalid', () => { + process.env.TALENT_UNLOCK_FEE_CENTS = 'not-a-number'; + expect(getUnlockFeeCents()).toBe(DEFAULT_UNLOCK_FEE_CENTS); + process.env.TALENT_UNLOCK_FEE_CENTS = '-5'; + expect(getUnlockFeeCents()).toBe(DEFAULT_UNLOCK_FEE_CENTS); + }); + + it('computes a percentage placement fee (10% of $10,000 = $1,000)', () => { + // 10% default rate, amount 1,000,000 cents ($10k) -> 100,000 cents ($1k) + expect(computePlacementFeeCents(1_000_000)).toBe(100_000); + }); + + it('rounds the computed fee half-up to the nearest cent', () => { + // 3333 * 0.10 = 333.3 -> 333 ; 3335 * 0.10 = 333.5 -> 334 + expect(computePlacementFeeCents(3333, { rate: 0.1, minCents: 1, maxCents: 10_000_000 })).toBe(333); + expect(computePlacementFeeCents(3335, { rate: 0.1, minCents: 1, maxCents: 10_000_000 })).toBe(334); + }); + + it('applies the floor when the raw fee is below the minimum', () => { + // 1,000 * 0.10 = 100, floored to 4,900 + expect(computePlacementFeeCents(1_000)).toBe(4_900); + }); + + it('applies the ceiling when the raw fee is above the maximum', () => { + // 100,000,000 * 0.10 = 10,000,000, capped to 2,000,000 + expect(computePlacementFeeCents(100_000_000)).toBe(2_000_000); + }); + + it('rejects non-positive or non-integer placement amounts', () => { + expect(() => computePlacementFeeCents(0)).toThrow(); + expect(() => computePlacementFeeCents(-100)).toThrow(); + expect(() => computePlacementFeeCents(12.5)).toThrow(); + }); + + it('resolvePlacementFee selects the unlock model without an amount', () => { + expect(resolvePlacementFee({})).toEqual({ feeCents: DEFAULT_UNLOCK_FEE_CENTS, feeModel: 'unlock' }); + }); + + it('resolvePlacementFee selects the placement model with an amount', () => { + expect(resolvePlacementFee({ placementAmountCents: 1_000_000 })).toEqual({ + feeCents: 100_000, + feeModel: 'placement', + }); + }); +}); + +// --------------------------------------------------------------------------- +// Gating +// --------------------------------------------------------------------------- + +describe('requestCandidateUnlock gating', () => { + it('rejects a recruiter unlocking their own profile', async () => { + const { db } = makeFakeDb(OPPORTUNITY); + const checkout = fakeCheckout(); + await expect( + requestCandidateUnlock( + { ...baseParams, candidateId: 'recruiter-1' }, + { db, matcher: matcherWithEvidence('recruiter-1'), createCheckout: checkout.fn }, + ), + ).rejects.toThrow(/cannot unlock their own/i); + expect(checkout.calls).toHaveLength(0); + }); + + it('rejects when the opportunity does not exist', async () => { + const { db } = makeFakeDb(null); + const checkout = fakeCheckout(); + await expect( + requestCandidateUnlock(baseParams, { + db, + matcher: matcherWithEvidence('candidate-1'), + createCheckout: checkout.fn, + }), + ).rejects.toThrow(/not found/i); + expect(checkout.calls).toHaveLength(0); + }); + + it('rejects a recruiter who does not own the opportunity', async () => { + const { db } = makeFakeDb({ ...OPPORTUNITY, createdById: 'someone-else' }); + const checkout = fakeCheckout(); + await expect( + requestCandidateUnlock(baseParams, { + db, + matcher: matcherWithEvidence('candidate-1'), + createCheckout: checkout.fn, + }), + ).rejects.toThrow(/only the opportunity owner/i); + expect(checkout.calls).toHaveLength(0); + }); + + it('rejects a candidate without matching evidence', async () => { + const { db, placements } = makeFakeDb(OPPORTUNITY); + const checkout = fakeCheckout(); + await expect( + requestCandidateUnlock(baseParams, { db, matcher: matcherNoEvidence, createCheckout: checkout.fn }), + ).rejects.toThrow(/evidence/i); + expect(checkout.calls).toHaveLength(0); + expect(placements).toHaveLength(0); + }); +}); + +// --------------------------------------------------------------------------- +// Happy path + idempotency of the charge +// --------------------------------------------------------------------------- + +describe('requestCandidateUnlock charge + idempotency', () => { + it('opens a checkout for a valid unlock and records a pending entitlement', async () => { + const { db, placements } = makeFakeDb(OPPORTUNITY); + const checkout = fakeCheckout(); + + const result = await requestCandidateUnlock(baseParams, { + db, + matcher: matcherWithEvidence('candidate-1'), + createCheckout: checkout.fn, + }); + + expect(result.alreadyUnlocked).toBe(false); + expect(result.checkoutUrl).toBe('https://checkout.creem.io/session-1'); + expect(checkout.calls).toHaveLength(1); + expect(placements).toHaveLength(1); + expect(placements[0].status).toBe('pending'); + expect(placements[0].feeCents).toBe(DEFAULT_UNLOCK_FEE_CENTS); + expect(placements[0].feeModel).toBe('unlock'); + expect(placements[0].checkoutId).toBe('checkout-1'); + // Creem custom_price is charged the exact computed fee. + expect(checkout.calls[0].amountCents).toBe(DEFAULT_UNLOCK_FEE_CENTS); + expect(checkout.calls[0].requestId).toBe(placements[0].id); + // metadata carries the placement id for webhook settlement + expect(checkout.calls[0].metadata.placementId).toBe(placements[0].id); + expect(checkout.calls[0].metadata.kind).toBe('talent_placement'); + }); + + it('uses the placement success-fee model when an amount is supplied', async () => { + const { db, placements } = makeFakeDb(OPPORTUNITY); + const checkout = fakeCheckout(); + + await requestCandidateUnlock( + { ...baseParams, placementAmountCents: 1_000_000 }, + { db, matcher: matcherWithEvidence('candidate-1'), createCheckout: checkout.fn }, + ); + + expect(placements[0].feeModel).toBe('placement'); + expect(placements[0].feeCents).toBe(100_000); + }); + + it('does not re-charge when the candidate is already unlocked (paid)', async () => { + const paid: PlacementRow = { + id: 'placement-existing', + opportunityId: 'opp-1', + candidateId: 'candidate-1', + recruiterId: 'recruiter-1', + feeCents: 4900, + feeModel: 'unlock', + status: 'paid', + paidAt: new Date(), + }; + const { db, placements } = makeFakeDb(OPPORTUNITY, [paid]); + const checkout = fakeCheckout(); + + const result = await requestCandidateUnlock(baseParams, { + db, + matcher: matcherWithEvidence('candidate-1'), + createCheckout: checkout.fn, + }); + + expect(result.alreadyUnlocked).toBe(true); + expect(result.checkoutUrl).toBeNull(); + expect(checkout.calls).toHaveLength(0); + expect(placements).toHaveLength(1); + }); + + it('reuses a pending entitlement instead of creating a second one', async () => { + const pending: PlacementRow = { + id: 'placement-pending', + opportunityId: 'opp-1', + candidateId: 'candidate-1', + recruiterId: 'recruiter-1', + feeCents: 4900, + feeModel: 'unlock', + status: 'pending', + }; + const { db, placements } = makeFakeDb(OPPORTUNITY, [pending]); + const checkout = fakeCheckout(); + + const result = await requestCandidateUnlock(baseParams, { + db, + matcher: matcherWithEvidence('candidate-1'), + createCheckout: checkout.fn, + }); + + expect(result.alreadyUnlocked).toBe(false); + expect(placements).toHaveLength(1); // reused, not duplicated + expect(result.placement.id).toBe('placement-pending'); + expect(checkout.calls).toHaveLength(1); + }); +}); + +// --------------------------------------------------------------------------- +// Settlement + entitlement +// --------------------------------------------------------------------------- + +describe('settlePlacementOrder + isCandidateUnlocked', () => { + function seedPending(): { db: BillingDb; placements: PlacementRow[] } { + return makeFakeDb(OPPORTUNITY, [ + { + id: 'placement-1', + opportunityId: 'opp-1', + candidateId: 'candidate-1', + recruiterId: 'recruiter-1', + feeCents: 4900, + feeModel: 'unlock', + status: 'pending', + }, + ]); + } + + it('marks a pending placement paid and stamps the receipt', async () => { + const { db, placements } = seedPending(); + const result = await settlePlacementOrder( + { placementId: 'placement-1', providerOrderId: 'order-abc', amountCents: 4900 }, + { db }, + ); + expect(result).toEqual({ settled: true, alreadyPaid: false }); + expect(placements[0].status).toBe('paid'); + expect(placements[0].providerOrderId).toBe('order-abc'); + expect(placements[0].paidAt).toBeInstanceOf(Date); + }); + + it('is idempotent — replaying the order for a paid placement is a no-op', async () => { + const { db, placements } = seedPending(); + await settlePlacementOrder({ placementId: 'placement-1', providerOrderId: 'order-abc' }, { db }); + const firstPaidAt = placements[0].paidAt; + + const replay = await settlePlacementOrder( + { placementId: 'placement-1', providerOrderId: 'order-duplicate' }, + { db }, + ); + expect(replay).toEqual({ settled: false, alreadyPaid: true }); + expect(placements[0].providerOrderId).toBe('order-abc'); // unchanged + expect(placements[0].paidAt).toBe(firstPaidAt); + }); + + it('refuses to settle when the paid amount does not match the quoted fee', async () => { + const { db, placements } = seedPending(); + const result = await settlePlacementOrder( + { placementId: 'placement-1', providerOrderId: 'order-abc', amountCents: 100 }, + { db }, + ); + expect(result).toEqual({ settled: false, alreadyPaid: false, amountMismatch: true }); + expect(placements[0].status).toBe('pending'); + expect(placements[0].providerOrderId).toBeUndefined(); + }); + + it('reports a missing placement without throwing', async () => { + const { db } = seedPending(); + const result = await settlePlacementOrder({ placementId: 'nope', providerOrderId: 'order-x' }, { db }); + expect(result).toEqual({ settled: false, alreadyPaid: false }); + }); + + it('isCandidateUnlocked is true only after settlement', async () => { + const { db } = seedPending(); + expect(await isCandidateUnlocked('opp-1', 'candidate-1', 'recruiter-1', db)).toBe(false); + await settlePlacementOrder({ placementId: 'placement-1', providerOrderId: 'order-abc' }, { db }); + expect(await isCandidateUnlocked('opp-1', 'candidate-1', 'recruiter-1', db)).toBe(true); + expect(await isCandidateUnlocked('opp-1', 'other', 'recruiter-1', db)).toBe(false); + }); +});