feat(talent): wire recruiter candidate-unlock UI to Creem revenue path
The recruiter placement/unlock backend was end-to-end (routes, talentBillingService, Creem checkout + signed webhook settlement) but had no frontend, so recruiters literally could not pay. This closes the only fully dead-ended money surface. Web (gitgram/web): - talentGraphService: add listUnlocks, requestUnlock (idempotent, optional placement success-fee), and getCandidateContact mapping the existing owner-gated backend routes, with typed placement/contact envelopes. - utils/talentUnlock: pure gating helpers (deriveUnlockState, findPlacement, interpretUnlockResult, formatFee) so the owner-only logic is unit tested without rendering. - talent-network page: owner-only "Unlock candidate" action on each match card — opens the Creem checkout, reveals contact + full evidence once the entitlement is paid (poll via "check payment" and on-return via query params), with not-owner / pending / unlocked / already-unlocked states. Backend (gitgram/backend): - talentBillingController: point the checkout successUrl at the real /talent-network page (with opportunity + unlocked params) instead of a non-existent /talent/opportunities route, so payment return is not a 404. Tests: unit-test the three service methods (idempotency header, success-fee body, already-unlocked, 402-when-unpaid, id encoding) and the gating helper (not-owner/unlockable/pending/unlocked, checkout-vs-reveal). 21 new tests. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
parent
72c0f8c12c
commit
757cd50d12
@ -54,9 +54,11 @@ export const talentBillingController = {
|
||||
});
|
||||
if (!recruiter?.email) throw Errors.userNotFound(req.userId);
|
||||
|
||||
const successUrl = `${process.env.FRONTEND_URL ?? ''}/talent/opportunities/${encodeURIComponent(
|
||||
// Land back on the talent-network page, which reads these params to select
|
||||
// the opportunity and reveal the unlocked candidate once payment settles.
|
||||
const successUrl = `${process.env.FRONTEND_URL ?? ''}/talent-network?opportunity=${encodeURIComponent(
|
||||
opportunityId,
|
||||
)}?unlocked=${encodeURIComponent(candidateId)}`;
|
||||
)}&unlocked=${encodeURIComponent(candidateId)}`;
|
||||
|
||||
const result = await requestCandidateUnlock({
|
||||
recruiterId: req.userId!,
|
||||
|
||||
@ -6,12 +6,15 @@ import {
|
||||
CoverageStrength,
|
||||
CreateTalentOpportunityInput,
|
||||
NeedCoverageAnalysis,
|
||||
TalentCandidateContact,
|
||||
TalentMatch,
|
||||
TalentOpportunity,
|
||||
TalentPilot,
|
||||
TalentPlacement,
|
||||
TalentReferral,
|
||||
talentGraphService,
|
||||
} from '@/services/talentGraphService'
|
||||
import { deriveUnlockState, findPlacement, formatFee, interpretUnlockResult } from '@/utils/talentUnlock'
|
||||
import styles from './talent-network.module.css'
|
||||
|
||||
type Notice = {
|
||||
@ -164,6 +167,10 @@ export default function TalentNetworkPage() {
|
||||
const [referralsError, setReferralsError] = useState<string | null>(null)
|
||||
const [referralsRequest, setReferralsRequest] = useState(0)
|
||||
const [referringId, setReferringId] = useState<string | null>(null)
|
||||
const [unlocks, setUnlocks] = useState<TalentPlacement[]>([])
|
||||
const [unlocksRequest, setUnlocksRequest] = useState(0)
|
||||
const [unlockedContacts, setUnlockedContacts] = useState<Record<string, TalentCandidateContact>>({})
|
||||
const [unlockBusyId, setUnlockBusyId] = useState<string | null>(null)
|
||||
const [notice, setNotice] = useState<Notice | null>(null)
|
||||
const mutationKeys = useRef(new Map<string, { body: string; key: string }>())
|
||||
|
||||
@ -294,6 +301,93 @@ export default function TalentNetworkPage() {
|
||||
return () => { active = false }
|
||||
}, [matchesRequest, selectedId])
|
||||
|
||||
const isOpportunityOwner = selected?.viewerRole === 'institution'
|
||||
|
||||
// Owner-only: load the recruiter's placement entitlements (receipts) so match
|
||||
// cards know which candidates are already unlocked or have a checkout pending.
|
||||
useEffect(() => {
|
||||
if (!selectedId || !isOpportunityOwner) {
|
||||
setUnlocks([])
|
||||
return
|
||||
}
|
||||
let active = true
|
||||
talentGraphService.listUnlocks(selectedId)
|
||||
.then((items) => active && setUnlocks(items))
|
||||
.catch(() => active && setUnlocks([]))
|
||||
return () => { active = false }
|
||||
}, [selectedId, isOpportunityOwner, unlocksRequest])
|
||||
|
||||
// On-return from the Creem checkout the backend redirects to
|
||||
// /talent-network?opportunity=<id>&unlocked=<candidateId>. Select that
|
||||
// opportunity and reveal the candidate once the entitlement has settled.
|
||||
useEffect(() => {
|
||||
if (typeof window === 'undefined') return
|
||||
const params = new URLSearchParams(window.location.search)
|
||||
const opportunityId = params.get('opportunity')
|
||||
const candidateId = params.get('unlocked')
|
||||
if (!opportunityId) return
|
||||
setSelectedId(opportunityId)
|
||||
if (!candidateId) return
|
||||
talentGraphService.getCandidateContact(opportunityId, candidateId)
|
||||
.then((contact) => {
|
||||
setUnlockedContacts((current) => ({ ...current, [candidateId]: contact }))
|
||||
setUnlocksRequest((request) => request + 1)
|
||||
})
|
||||
.catch(() => { /* still pending — the owner can retry from the match card */ })
|
||||
}, [])
|
||||
|
||||
async function revealContact(opportunityId: string, candidateId: string) {
|
||||
const contact = await talentGraphService.getCandidateContact(opportunityId, candidateId)
|
||||
setUnlockedContacts((current) => ({ ...current, [candidateId]: contact }))
|
||||
setUnlocksRequest((request) => request + 1)
|
||||
}
|
||||
|
||||
async function unlockCandidate(match: TalentMatch) {
|
||||
if (!selected || !isOpportunityOwner) return
|
||||
setUnlockBusyId(match.profile.id)
|
||||
setNotice(null)
|
||||
const action = `unlock:${selected.id}:${match.profile.id}`
|
||||
const payload = { candidateId: match.profile.id }
|
||||
try {
|
||||
const result = await talentGraphService.requestUnlock(selected.id, match.profile.id, mutationKey(action, payload))
|
||||
settleMutation(action)
|
||||
setUnlocks((current) => [result.placement, ...current.filter((placement) => placement.id !== result.placement.id)])
|
||||
const interpreted = interpretUnlockResult(result)
|
||||
if (interpreted.action === 'reveal') {
|
||||
await revealContact(selected.id, match.profile.id)
|
||||
setNotice({ tone: 'status', text: `${match.profile.displayName || match.profile.username} için kişi bilgisi ve tam kanıt açıldı.` })
|
||||
} else if (interpreted.checkoutUrl) {
|
||||
window.open(interpreted.checkoutUrl, '_blank', 'noopener,noreferrer')
|
||||
setNotice({ tone: 'status', text: 'Creem ödeme sekmesi açıldı. Ödeme tamamlanınca "Ödemeyi kontrol et" ile adayı açın.' })
|
||||
}
|
||||
} catch (error) {
|
||||
settleMutation(action, error)
|
||||
setNotice({
|
||||
tone: 'error',
|
||||
text: getErrorMessage(error, 'Aday açılamadı. Fırsat sahibi oturumunu kontrol edip tekrar deneyin.'),
|
||||
})
|
||||
} finally {
|
||||
setUnlockBusyId(null)
|
||||
}
|
||||
}
|
||||
|
||||
async function checkUnlockPayment(match: TalentMatch) {
|
||||
if (!selected) return
|
||||
setUnlockBusyId(match.profile.id)
|
||||
setNotice(null)
|
||||
try {
|
||||
await revealContact(selected.id, match.profile.id)
|
||||
setNotice({ tone: 'status', text: `${match.profile.displayName || match.profile.username} için kişi bilgisi ve tam kanıt açıldı.` })
|
||||
} catch (error) {
|
||||
setNotice({
|
||||
tone: 'error',
|
||||
text: getErrorMessage(error, 'Ödeme henüz doğrulanmadı. Ödemeyi tamamladıysanız birkaç saniye sonra tekrar deneyin.'),
|
||||
})
|
||||
} finally {
|
||||
setUnlockBusyId(null)
|
||||
}
|
||||
}
|
||||
|
||||
async function createOpportunity(event: FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault()
|
||||
const requiredSkills = skillsText.split(',').map((skill) => skill.trim().toLowerCase()).filter(Boolean)
|
||||
@ -616,9 +710,12 @@ export default function TalentNetworkPage() {
|
||||
const referral = myReferrals.find((item) => item.opportunityId === selected?.id && item.participantId === match.profile.id)
|
||||
const existingPilot = myPilots.find((item) => item.opportunityId === selected?.id && item.participantId === match.profile.id)
|
||||
const isZenPath = selected?.sourceChannel === 'zen-talent'
|
||||
const isOpportunityOwner = selected?.viewerRole === 'institution'
|
||||
const actionRecordsLoading = isOpportunityOwner && (pilotsLoading || (isZenPath && referralsLoading))
|
||||
const actionRecordsUnavailable = isOpportunityOwner && Boolean(pilotsError || (isZenPath && referralsError))
|
||||
const placement = findPlacement(unlocks, match.profile.id)
|
||||
const unlockState = deriveUnlockState({ isOwner: isOpportunityOwner, placement })
|
||||
const revealedContact = unlockedContacts[match.profile.id]
|
||||
const unlockBusy = unlockBusyId === match.profile.id
|
||||
return (
|
||||
<article className={styles.match} key={match.profile.id}>
|
||||
<div className={styles.rank}>{String(index + 1).padStart(2, '0')}</div>
|
||||
@ -668,6 +765,52 @@ export default function TalentNetworkPage() {
|
||||
{referringId === match.profile.id ? 'Yönlendiriliyor' : 'Zen’e yönlendir'}
|
||||
</button>
|
||||
)}
|
||||
{unlockState !== 'not-owner' && (
|
||||
<div className={styles.unlock}>
|
||||
{unlockState === 'unlockable' && (
|
||||
<>
|
||||
<span className={styles.unlockHint}>Kişi bilgisi ve tam kanıt için ödemeli erişim</span>
|
||||
<button type="button" disabled={unlockBusy} onClick={() => unlockCandidate(match)}>
|
||||
{unlockBusy ? 'Ödeme açılıyor' : 'Adayı aç'}
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
{unlockState === 'pending' && (
|
||||
<>
|
||||
<span className={styles.unlockHint}>
|
||||
Ödeme bekleniyor{placement ? ` · ${formatFee(placement.feeCents, placement.currency)}` : ''}
|
||||
</span>
|
||||
<button type="button" disabled={unlockBusy} onClick={() => checkUnlockPayment(match)}>
|
||||
{unlockBusy ? 'Kontrol ediliyor' : 'Ödemeyi kontrol et'}
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
{unlockState === 'unlocked' && !revealedContact && (
|
||||
<button type="button" disabled={unlockBusy} onClick={() => checkUnlockPayment(match)}>
|
||||
{unlockBusy ? 'Yükleniyor' : 'Kişi bilgisini göster'}
|
||||
</button>
|
||||
)}
|
||||
{revealedContact && (
|
||||
<div className={styles.contactCard}>
|
||||
<h4>Aday iletişim bilgisi</h4>
|
||||
<dl>
|
||||
{revealedContact.contact.displayName && (
|
||||
<><dt>Ad</dt><dd>{revealedContact.contact.displayName}</dd></>
|
||||
)}
|
||||
{revealedContact.contact.username && (
|
||||
<><dt>Kullanıcı</dt><dd>@{revealedContact.contact.username}</dd></>
|
||||
)}
|
||||
{revealedContact.contact.email && (
|
||||
<><dt>E-posta</dt><dd><a href={`mailto:${revealedContact.contact.email}`}>{revealedContact.contact.email}</a></dd></>
|
||||
)}
|
||||
{revealedContact.contact.githubUsername && (
|
||||
<><dt>GitHub</dt><dd><a href={`https://github.com/${revealedContact.contact.githubUsername}`} target="_blank" rel="noreferrer">{revealedContact.contact.githubUsername}</a></dd></>
|
||||
)}
|
||||
</dl>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</article>
|
||||
)
|
||||
|
||||
@ -251,3 +251,15 @@
|
||||
.coverageCount { font-size: 10px; color: var(--ink); opacity: 0.7; font-variant-numeric: tabular-nums; }
|
||||
.coverageGap { margin: 16px 0 0; font-size: 12px; font-weight: 700; color: var(--red); }
|
||||
.coverageNote { margin: 8px 0 0; font-size: 10px; text-transform: uppercase; letter-spacing: 0.04em; }
|
||||
|
||||
/* Recruiter candidate-unlock revenue (owner-only) */
|
||||
.unlock { margin-top: 20px; display: flex; flex-direction: column; align-items: flex-end; gap: 8px; text-align: right; }
|
||||
.unlock button { margin-top: 0; }
|
||||
.unlockHint { display: block; font-size: 10px; text-transform: uppercase; letter-spacing: 0.04em; opacity: 0.75; }
|
||||
.unlockFee { font-variant-numeric: tabular-nums; font-weight: 700; }
|
||||
.contactCard { margin-top: 16px; padding: 14px 16px; border: 1px solid var(--ink); border-left: 4px solid var(--red); background: var(--paper); text-align: left; }
|
||||
.contactCard h4 { margin: 0 0 8px; font-size: 11px; text-transform: uppercase; letter-spacing: 0.04em; }
|
||||
.contactCard dl { margin: 0; display: grid; grid-template-columns: auto 1fr; gap: 4px 12px; }
|
||||
.contactCard dt { font-size: 10px; text-transform: uppercase; letter-spacing: 0.04em; opacity: 0.7; }
|
||||
.contactCard dd { margin: 0; font-size: 12px; word-break: break-word; }
|
||||
.contactCard a { color: var(--ink); font-size: 12px; text-underline-offset: 3px; }
|
||||
|
||||
@ -200,6 +200,51 @@ export interface CreateTalentOpportunityInput {
|
||||
communityReferralConsent: boolean
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Recruiter placement / candidate-unlock revenue (Creem)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export type TalentPlacementStatus = 'pending' | 'paid' | 'failed' | 'refunded'
|
||||
export type TalentFeeModel = 'unlock' | 'placement'
|
||||
|
||||
/** A recruiter's placement entitlement (receipt) for a matched candidate. */
|
||||
export interface TalentPlacement {
|
||||
id: string
|
||||
opportunityId: string
|
||||
candidateId: string
|
||||
recruiterId: string
|
||||
feeCents: number
|
||||
currency: string
|
||||
feeModel: TalentFeeModel
|
||||
status: TalentPlacementStatus
|
||||
provider: string
|
||||
checkoutId: string | null
|
||||
providerOrderId: string | null
|
||||
paidAt: string | null
|
||||
createdAt: string
|
||||
updatedAt: string
|
||||
}
|
||||
|
||||
/** Result of opening (or replaying) a candidate-unlock charge. */
|
||||
export interface RequestUnlockResult {
|
||||
placement: TalentPlacement
|
||||
/** Hosted Creem checkout URL, or null when the entitlement is already paid. */
|
||||
checkoutUrl: string | null
|
||||
alreadyUnlocked: boolean
|
||||
}
|
||||
|
||||
/** The gated resource revealed only once a paid unlock entitlement exists. */
|
||||
export interface TalentCandidateContact {
|
||||
contact: {
|
||||
id: string
|
||||
username: string | null
|
||||
displayName: string | null
|
||||
email: string | null
|
||||
githubUsername: string | null
|
||||
}
|
||||
evidence: TalentGraph
|
||||
}
|
||||
|
||||
export const talentGraphService = {
|
||||
getMine: async (): Promise<TalentGraph> => {
|
||||
const { data } = await api.get<{ data: TalentGraph }>('/talent-graph/me')
|
||||
@ -260,6 +305,50 @@ export const talentGraphService = {
|
||||
const { data } = await api.patch<{ data: TalentPilot }>(`/talent-graph/pilots/${encodeURIComponent(pilotId)}`, input, mutationConfig(idempotencyKey))
|
||||
return data.data
|
||||
},
|
||||
|
||||
// ── Recruiter placement / candidate-unlock revenue ──────────────────────
|
||||
// The opportunity owner pays a Creem placement fee to reveal a matched
|
||||
// candidate's contact details + full evidence. All three endpoints are
|
||||
// owner-gated on the backend (talentBillingController).
|
||||
|
||||
/** Lists the recruiter's placement entitlements (receipts) for an opportunity. */
|
||||
listUnlocks: async (opportunityId: string): Promise<TalentPlacement[]> => {
|
||||
const { data } = await api.get<{ data: TalentPlacement[] }>(`/talent-graph/opportunities/${encodeURIComponent(opportunityId)}/unlocks`)
|
||||
return data.data
|
||||
},
|
||||
|
||||
/**
|
||||
* Opens (or replays) a paid unlock for a matched candidate. Returns a Creem
|
||||
* checkout URL to complete payment, or `alreadyUnlocked` when the entitlement
|
||||
* is already settled. `placementAmountCents` switches the flat access fee to a
|
||||
* success-fee model when an agreed placement amount is known.
|
||||
*/
|
||||
requestUnlock: async (
|
||||
opportunityId: string,
|
||||
candidateId: string,
|
||||
idempotencyKey: string,
|
||||
placementAmountCents?: number,
|
||||
): Promise<RequestUnlockResult> => {
|
||||
const body: { candidateId: string; placementAmountCents?: number } = { candidateId }
|
||||
if (placementAmountCents !== undefined) body.placementAmountCents = placementAmountCents
|
||||
const { data } = await api.post<{ data: RequestUnlockResult }>(
|
||||
`/talent-graph/opportunities/${encodeURIComponent(opportunityId)}/unlocks`,
|
||||
body,
|
||||
mutationConfig(idempotencyKey),
|
||||
)
|
||||
return data.data
|
||||
},
|
||||
|
||||
/**
|
||||
* Reads the gated contact details + full evidence for an unlocked candidate.
|
||||
* The backend returns 402 Payment Required until the entitlement is paid.
|
||||
*/
|
||||
getCandidateContact: async (opportunityId: string, candidateId: string): Promise<TalentCandidateContact> => {
|
||||
const { data } = await api.get<{ data: TalentCandidateContact }>(
|
||||
`/talent-graph/opportunities/${encodeURIComponent(opportunityId)}/candidates/${encodeURIComponent(candidateId)}/contact`,
|
||||
)
|
||||
return data.data
|
||||
},
|
||||
}
|
||||
|
||||
function mutationConfig(idempotencyKey: string) {
|
||||
|
||||
@ -48,3 +48,102 @@ describe('talentGraphService.getOpportunityCoverage', () => {
|
||||
expect(requestedUrl).toContain('/talent-graph/opportunities/a%2Fb/coverage')
|
||||
})
|
||||
})
|
||||
|
||||
describe('talentGraphService recruiter unlock revenue', () => {
|
||||
beforeEach(() => {
|
||||
mock.reset()
|
||||
})
|
||||
|
||||
it('lists placement entitlements for an opportunity', async () => {
|
||||
mock.onGet('/v1/talent-graph/opportunities/opp-1/unlocks').reply(200, {
|
||||
data: [{ id: 'plc-1', opportunityId: 'opp-1', candidateId: 'cand-1', status: 'paid', feeCents: 4900 }],
|
||||
})
|
||||
|
||||
const placements = await talentGraphService.listUnlocks('opp-1')
|
||||
|
||||
expect(placements).toHaveLength(1)
|
||||
expect(placements[0].status).toBe('paid')
|
||||
})
|
||||
|
||||
it('posts an unlock request with the idempotency header and returns a checkout URL', async () => {
|
||||
let sentHeaders: Record<string, unknown> = {}
|
||||
let sentBody: unknown = null
|
||||
mock.onPost('/v1/talent-graph/opportunities/opp-1/unlocks').reply((config) => {
|
||||
sentHeaders = (config.headers ?? {}) as Record<string, unknown>
|
||||
sentBody = JSON.parse(config.data)
|
||||
return [201, {
|
||||
data: {
|
||||
placement: { id: 'plc-1', status: 'pending', feeCents: 4900 },
|
||||
checkoutUrl: 'https://test-api.creem.io/checkout/abc',
|
||||
alreadyUnlocked: false,
|
||||
},
|
||||
}]
|
||||
})
|
||||
|
||||
const result = await talentGraphService.requestUnlock('opp-1', 'cand-1', 'idem-key-1')
|
||||
|
||||
expect(sentHeaders['Idempotency-Key']).toBe('idem-key-1')
|
||||
expect(sentBody).toEqual({ candidateId: 'cand-1' })
|
||||
expect(result.checkoutUrl).toBe('https://test-api.creem.io/checkout/abc')
|
||||
expect(result.alreadyUnlocked).toBe(false)
|
||||
})
|
||||
|
||||
it('includes the placement amount when a success fee is requested', async () => {
|
||||
let sentBody: unknown = null
|
||||
mock.onPost('/v1/talent-graph/opportunities/opp-1/unlocks').reply((config) => {
|
||||
sentBody = JSON.parse(config.data)
|
||||
return [201, { data: { placement: { id: 'plc-1', status: 'pending' }, checkoutUrl: 'https://x', alreadyUnlocked: false } }]
|
||||
})
|
||||
|
||||
await talentGraphService.requestUnlock('opp-1', 'cand-1', 'idem-key-2', 1_500_000)
|
||||
|
||||
expect(sentBody).toEqual({ candidateId: 'cand-1', placementAmountCents: 1_500_000 })
|
||||
})
|
||||
|
||||
it('reports an already-unlocked entitlement with no checkout URL', async () => {
|
||||
mock.onPost('/v1/talent-graph/opportunities/opp-1/unlocks').reply(200, {
|
||||
data: { placement: { id: 'plc-1', status: 'paid' }, checkoutUrl: null, alreadyUnlocked: true },
|
||||
})
|
||||
|
||||
const result = await talentGraphService.requestUnlock('opp-1', 'cand-1', 'idem-key-3')
|
||||
|
||||
expect(result.alreadyUnlocked).toBe(true)
|
||||
expect(result.checkoutUrl).toBeNull()
|
||||
})
|
||||
|
||||
it('reads gated candidate contact + evidence once unlocked', async () => {
|
||||
mock.onGet('/v1/talent-graph/opportunities/opp-1/candidates/cand-1/contact').reply(200, {
|
||||
data: {
|
||||
contact: { id: 'cand-1', username: 'octocat', displayName: 'Octo Cat', email: 'octo@example.com', githubUsername: 'octocat' },
|
||||
evidence: { profile: { id: 'cand-1' }, projects: [] },
|
||||
},
|
||||
})
|
||||
|
||||
const contact = await talentGraphService.getCandidateContact('opp-1', 'cand-1')
|
||||
|
||||
expect(contact.contact.email).toBe('octo@example.com')
|
||||
expect(contact.contact.githubUsername).toBe('octocat')
|
||||
})
|
||||
|
||||
it('propagates a 402 Payment Required when the candidate is not yet unlocked', async () => {
|
||||
mock.onGet('/v1/talent-graph/opportunities/opp-1/candidates/cand-1/contact').reply(402, {
|
||||
error: { message: 'Unlock this candidate to view their contact details and full evidence' },
|
||||
})
|
||||
|
||||
await expect(talentGraphService.getCandidateContact('opp-1', 'cand-1')).rejects.toMatchObject({
|
||||
response: { status: 402 },
|
||||
})
|
||||
})
|
||||
|
||||
it('encodes ids in the contact request path', async () => {
|
||||
let requestedUrl = ''
|
||||
mock.onGet(/\/talent-graph\/opportunities\/.*\/candidates\/.*\/contact/).reply((config) => {
|
||||
requestedUrl = config.url || ''
|
||||
return [200, { data: { contact: { id: 'a/b' }, evidence: { profile: { id: 'a/b' }, projects: [] } } }]
|
||||
})
|
||||
|
||||
await talentGraphService.getCandidateContact('opp/1', 'cand/2')
|
||||
|
||||
expect(requestedUrl).toContain('/talent-graph/opportunities/opp%2F1/candidates/cand%2F2/contact')
|
||||
})
|
||||
})
|
||||
|
||||
99
gitgram/web/tests/talentUnlock.test.ts
Normal file
99
gitgram/web/tests/talentUnlock.test.ts
Normal file
@ -0,0 +1,99 @@
|
||||
/// <reference types="vitest/globals" />
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import {
|
||||
deriveUnlockState,
|
||||
findPlacement,
|
||||
formatFee,
|
||||
interpretUnlockResult,
|
||||
} from '@/utils/talentUnlock'
|
||||
import type { RequestUnlockResult, TalentPlacement } from '@/services/talentGraphService'
|
||||
|
||||
function placement(overrides: Partial<TalentPlacement> = {}): TalentPlacement {
|
||||
return {
|
||||
id: 'plc-1',
|
||||
opportunityId: 'opp-1',
|
||||
candidateId: 'cand-1',
|
||||
recruiterId: 'rec-1',
|
||||
feeCents: 4900,
|
||||
currency: 'usd',
|
||||
feeModel: 'unlock',
|
||||
status: 'pending',
|
||||
provider: 'creem',
|
||||
checkoutId: 'chk-1',
|
||||
providerOrderId: null,
|
||||
paidAt: null,
|
||||
createdAt: '2026-09-06T00:00:00.000Z',
|
||||
updatedAt: '2026-09-06T00:00:00.000Z',
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
describe('deriveUnlockState', () => {
|
||||
it('returns not-owner when the viewer does not own the opportunity', () => {
|
||||
expect(deriveUnlockState({ isOwner: false, placement: null })).toBe('not-owner')
|
||||
// Ownership gates even when a paid entitlement somehow exists.
|
||||
expect(deriveUnlockState({ isOwner: false, placement: placement({ status: 'paid' }) })).toBe('not-owner')
|
||||
})
|
||||
|
||||
it('returns unlockable for an owner with no entitlement yet', () => {
|
||||
expect(deriveUnlockState({ isOwner: true, placement: null })).toBe('unlockable')
|
||||
expect(deriveUnlockState({ isOwner: true })).toBe('unlockable')
|
||||
})
|
||||
|
||||
it('returns pending for an owner with an open (unpaid) checkout', () => {
|
||||
expect(deriveUnlockState({ isOwner: true, placement: placement({ status: 'pending' }) })).toBe('pending')
|
||||
})
|
||||
|
||||
it('returns unlocked for an owner with a paid entitlement', () => {
|
||||
expect(deriveUnlockState({ isOwner: true, placement: placement({ status: 'paid' }) })).toBe('unlocked')
|
||||
})
|
||||
|
||||
it('treats failed/refunded entitlements as unlockable (a fresh charge can be opened)', () => {
|
||||
expect(deriveUnlockState({ isOwner: true, placement: placement({ status: 'failed' }) })).toBe('unlockable')
|
||||
expect(deriveUnlockState({ isOwner: true, placement: placement({ status: 'refunded' }) })).toBe('unlockable')
|
||||
})
|
||||
})
|
||||
|
||||
describe('findPlacement', () => {
|
||||
it('finds the entitlement matching the candidate id', () => {
|
||||
const list = [placement({ id: 'a', candidateId: 'cand-1' }), placement({ id: 'b', candidateId: 'cand-2' })]
|
||||
expect(findPlacement(list, 'cand-2')?.id).toBe('b')
|
||||
})
|
||||
|
||||
it('returns null when no entitlement matches', () => {
|
||||
expect(findPlacement([placement({ candidateId: 'cand-1' })], 'cand-9')).toBeNull()
|
||||
expect(findPlacement([], 'cand-1')).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('interpretUnlockResult', () => {
|
||||
it('reveals immediately when already unlocked', () => {
|
||||
const result: RequestUnlockResult = { placement: placement({ status: 'paid' }), checkoutUrl: null, alreadyUnlocked: true }
|
||||
expect(interpretUnlockResult(result)).toEqual({ action: 'reveal', checkoutUrl: null })
|
||||
})
|
||||
|
||||
it('opens a checkout when an unpaid entitlement returns a checkout URL', () => {
|
||||
const result: RequestUnlockResult = {
|
||||
placement: placement({ status: 'pending' }),
|
||||
checkoutUrl: 'https://test-api.creem.io/checkout/abc',
|
||||
alreadyUnlocked: false,
|
||||
}
|
||||
expect(interpretUnlockResult(result)).toEqual({ action: 'checkout', checkoutUrl: 'https://test-api.creem.io/checkout/abc' })
|
||||
})
|
||||
|
||||
it('falls back to reveal when no checkout URL is present', () => {
|
||||
const result: RequestUnlockResult = { placement: placement(), checkoutUrl: null, alreadyUnlocked: false }
|
||||
expect(interpretUnlockResult(result)).toEqual({ action: 'reveal', checkoutUrl: null })
|
||||
})
|
||||
})
|
||||
|
||||
describe('formatFee', () => {
|
||||
it('formats usd cents as a dollar amount', () => {
|
||||
expect(formatFee(4900)).toBe('$49.00')
|
||||
expect(formatFee(199900, 'usd')).toBe('$1999.00')
|
||||
})
|
||||
|
||||
it('formats non-usd currencies with an ISO suffix', () => {
|
||||
expect(formatFee(4900, 'eur')).toBe('49.00 EUR')
|
||||
})
|
||||
})
|
||||
67
gitgram/web/utils/talentUnlock.ts
Normal file
67
gitgram/web/utils/talentUnlock.ts
Normal file
@ -0,0 +1,67 @@
|
||||
/**
|
||||
* Pure helpers for the recruiter candidate-unlock revenue flow.
|
||||
*
|
||||
* These keep the gating/error logic out of the talent-network page component so
|
||||
* it can be unit tested without rendering. The backend
|
||||
* (talentBillingController) is the source of truth for authorization; these
|
||||
* helpers only decide what the owner-facing UI should show.
|
||||
*/
|
||||
import type { RequestUnlockResult, TalentPlacement } from '@/services/talentGraphService'
|
||||
|
||||
/**
|
||||
* UI state for a single candidate's unlock action:
|
||||
* - `not-owner` — the viewer does not own the opportunity; no unlock action.
|
||||
* - `unlockable` — owner, no entitlement yet; the paid unlock can be started.
|
||||
* - `pending` — owner, a checkout is open but not yet settled.
|
||||
* - `unlocked` — owner, the entitlement is paid; contact can be revealed.
|
||||
*/
|
||||
export type UnlockState = 'not-owner' | 'unlockable' | 'pending' | 'unlocked'
|
||||
|
||||
/** Finds the recruiter's placement entitlement for a candidate, if any. */
|
||||
export function findPlacement(
|
||||
placements: ReadonlyArray<TalentPlacement>,
|
||||
candidateId: string,
|
||||
): TalentPlacement | null {
|
||||
return placements.find((placement) => placement.candidateId === candidateId) ?? null
|
||||
}
|
||||
|
||||
/**
|
||||
* Derives the unlock UI state for a candidate. Only the opportunity owner may
|
||||
* unlock; a `paid` entitlement means unlocked, a `pending` one means a checkout
|
||||
* is in flight, and anything else (including no entitlement) is unlockable.
|
||||
*/
|
||||
export function deriveUnlockState(params: {
|
||||
isOwner: boolean
|
||||
placement?: Pick<TalentPlacement, 'status'> | null
|
||||
}): UnlockState {
|
||||
if (!params.isOwner) return 'not-owner'
|
||||
switch (params.placement?.status) {
|
||||
case 'paid':
|
||||
return 'unlocked'
|
||||
case 'pending':
|
||||
return 'pending'
|
||||
default:
|
||||
return 'unlockable'
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Interprets a `requestUnlock` response: either the entitlement is already paid
|
||||
* (reveal now) or a checkout URL must be opened to collect payment.
|
||||
*/
|
||||
export function interpretUnlockResult(result: RequestUnlockResult): {
|
||||
action: 'reveal' | 'checkout'
|
||||
checkoutUrl: string | null
|
||||
} {
|
||||
if (result.alreadyUnlocked || !result.checkoutUrl) {
|
||||
return { action: 'reveal', checkoutUrl: null }
|
||||
}
|
||||
return { action: 'checkout', checkoutUrl: result.checkoutUrl }
|
||||
}
|
||||
|
||||
/** Formats a fee in cents as a plain currency string (e.g. 4900 → "$49.00"). */
|
||||
export function formatFee(feeCents: number, currency = 'usd'): string {
|
||||
const amount = (feeCents / 100).toFixed(2)
|
||||
const symbol = currency.toLowerCase() === 'usd' ? '$' : ''
|
||||
return symbol ? `${symbol}${amount}` : `${amount} ${currency.toUpperCase()}`
|
||||
}
|
||||
Reference in New Issue
Block a user