Compare commits
No commits in common. "main" and "feat/talent-coverage-web-slice" have entirely different histories.
main
...
feat/talen
@ -18,27 +18,13 @@ GITHUB_CLIENT_SECRET=
|
||||
GOOGLE_CLIENT_ID=
|
||||
GOOGLE_CLIENT_SECRET=
|
||||
|
||||
# Payments — subscriptions (Polar)
|
||||
# Payments
|
||||
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=
|
||||
|
||||
2
.gitignore
vendored
2
.gitignore
vendored
@ -79,5 +79,3 @@ Thumbs.db
|
||||
*.key
|
||||
*.p8
|
||||
*.p12
|
||||
*.env.production
|
||||
.env.gitgram.production
|
||||
|
||||
25
LICENSE
25
LICENSE
@ -1,25 +0,0 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 caelum0x (GitGram and AITimeMachine contributors)
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
|
||||
This MIT license covers the original GitGram and AITimeMachine code in this
|
||||
repository. Vendored third-party directories keep their own licenses; see
|
||||
THIRD_PARTY_NOTICES.md.
|
||||
@ -261,7 +261,3 @@ Deploy pipeline and secrets contracts: [docs/deploy-pipeline.md](docs/deploy-pip
|
||||
- Manual launch runbook — [docs/runbook.md](docs/runbook.md)
|
||||
- Environment matrix — [docs/environment-matrix.md](docs/environment-matrix.md)
|
||||
- Agents guide — [docs/AGENTS.md](docs/AGENTS.md)
|
||||
|
||||
## License
|
||||
|
||||
MIT for original GitGram and AITimeMachine code. Vendored third-party directories keep their own licenses, see [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md).
|
||||
|
||||
@ -1,16 +0,0 @@
|
||||
# Third-party notices
|
||||
|
||||
The root LICENSE (MIT) covers original GitGram and AITimeMachine code. The
|
||||
directories below are vendored from other projects and stay under their own
|
||||
licenses. Each directory contains its upstream license file.
|
||||
|
||||
| Directory | Upstream | License |
|
||||
| --- | --- | --- |
|
||||
| aitimemachine/a2a | github.com/a2aproject/a2a-js | Apache-2.0 |
|
||||
| aitimemachine/beads | Beads contributors | MIT |
|
||||
| aitimemachine/context7 | github.com/upstash/context7 | MIT |
|
||||
| aitimemachine/gemini-cli | github.com/google-gemini/gemini-cli | Apache-2.0 |
|
||||
| aitimemachine/git | git (git-scm.com) | GPL-2.0 |
|
||||
| aitimemachine/gitnexus, gitnexus-web, gitnexus-shared | github.com/abhigyanpatwari/GitNexus | PolyForm Noncommercial 1.0.0 (no commercial use) |
|
||||
| aitimemachine/pal-mcp-server | PAL MCP server | Apache-2.0 |
|
||||
| gitgram/mobile/proximity | Proximity (Instagram-style RN app) | GPL-3.0 |
|
||||
@ -159,13 +159,3 @@ APP_URL=http://localhost:3000
|
||||
# BACKUP_DIR=
|
||||
# Comma-separated local feature flags
|
||||
# FEATURE_FLAGS=
|
||||
|
||||
# ── Talent GraphRAG (explainMine / explainPublic) ───────────────────────────
|
||||
# Railyard Relay (OpenAI-compatible LLM gateway), tried first when both are set.
|
||||
# RELAY_URL=
|
||||
# RELAY_API_KEY=
|
||||
# Direct fallback when Relay isn't configured or a Relay call fails.
|
||||
# OPENROUTER_API_KEY=
|
||||
# Model overrides (optional; sane defaults are used otherwise).
|
||||
# GITGRAM_RAG_RELAY_MODEL=claude-haiku-4-5-20251001
|
||||
# GITGRAM_RAG_DIRECT_MODEL=anthropic/claude-haiku-4.5
|
||||
|
||||
@ -3,12 +3,6 @@ module.exports = {
|
||||
testEnvironment: 'node',
|
||||
roots: ['<rootDir>/src', '<rootDir>/tests'],
|
||||
testMatch: ['**/__tests__/**/*.ts', '**/?(*.)+(spec|test).ts'],
|
||||
// The end-to-end suite (tests/e2e/*.e2e.test.ts) runs the REAL Express app
|
||||
// against a REAL Postgres + Redis and has its own config (jest.e2e.config.js,
|
||||
// run via `npm run test:e2e`). Excluding it here keeps the default unit /
|
||||
// integration run deterministic — it must not require Docker datastores and
|
||||
// must not collide on ports when run in parallel.
|
||||
testPathIgnorePatterns: ['/node_modules/', '<rootDir>/tests/e2e/'],
|
||||
transform: {
|
||||
'^.+\\.ts$': ['ts-jest', { diagnostics: false }],
|
||||
},
|
||||
|
||||
@ -1,33 +0,0 @@
|
||||
-- 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;
|
||||
@ -1,2 +0,0 @@
|
||||
-- AlterTable
|
||||
ALTER TABLE "Message" ALTER COLUMN "receiverId" DROP NOT NULL;
|
||||
@ -571,9 +571,7 @@ model Follow {
|
||||
model Message {
|
||||
id String @id @default(cuid())
|
||||
senderId String
|
||||
// Nullable: group-chat messages (chatId set) have no single receiver. Only
|
||||
// 1:1 direct messages populate this.
|
||||
receiverId String?
|
||||
receiverId String
|
||||
chatId String?
|
||||
content String @db.Text
|
||||
mediaUrl String?
|
||||
@ -584,9 +582,9 @@ model Message {
|
||||
deletedForSender Boolean @default(false)
|
||||
createdAt DateTime @default(now())
|
||||
|
||||
sender Account @relation("MessageSender", fields: [senderId], references: [id], onDelete: Cascade)
|
||||
receiver Account? @relation("MessageReceiver", fields: [receiverId], references: [id], onDelete: Cascade)
|
||||
chat Chat? @relation(fields: [chatId], references: [id], onDelete: Cascade)
|
||||
sender Account @relation("MessageSender", fields: [senderId], references: [id], onDelete: Cascade)
|
||||
receiver Account @relation("MessageReceiver", fields: [receiverId], references: [id], onDelete: Cascade)
|
||||
chat Chat? @relation(fields: [chatId], references: [id], onDelete: Cascade)
|
||||
|
||||
reactions MessageReaction[]
|
||||
|
||||
@ -1076,7 +1074,6 @@ model TalentOpportunity {
|
||||
revision Int @default(1)
|
||||
pilots TalentPilot[]
|
||||
referrals TalentReferral[]
|
||||
placements TalentPlacement[]
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
@ -1084,38 +1081,6 @@ 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 {
|
||||
|
||||
@ -11,28 +11,17 @@ SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
BACKEND_DIR="$(cd "${SCRIPT_DIR}/.." && pwd)"
|
||||
COMPOSE_FILE="${BACKEND_DIR}/docker-compose.test.yml"
|
||||
|
||||
# Support both the Compose v2 plugin (`docker compose`) and the standalone
|
||||
# binary (`docker-compose`) — not every machine/CI image ships the plugin.
|
||||
if docker compose version >/dev/null 2>&1; then
|
||||
COMPOSE=(docker compose)
|
||||
elif command -v docker-compose >/dev/null 2>&1; then
|
||||
COMPOSE=(docker-compose)
|
||||
else
|
||||
echo "error: neither 'docker compose' nor 'docker-compose' is available" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
export DATABASE_URL="postgresql://gitgram_test:gitgram_test@localhost:5433/gitgram_test"
|
||||
export REDIS_URL="redis://localhost:6380"
|
||||
export NODE_ENV="test"
|
||||
|
||||
cleanup() {
|
||||
"${COMPOSE[@]}" -f "${COMPOSE_FILE}" down -v >/dev/null 2>&1 || true
|
||||
docker compose -f "${COMPOSE_FILE}" down -v >/dev/null 2>&1 || true
|
||||
}
|
||||
trap cleanup EXIT
|
||||
|
||||
echo "==> Starting ephemeral Postgres + Redis"
|
||||
"${COMPOSE[@]}" -f "${COMPOSE_FILE}" up -d --wait
|
||||
docker compose -f "${COMPOSE_FILE}" up -d --wait
|
||||
|
||||
echo "==> Running E2E suite"
|
||||
cd "${BACKEND_DIR}"
|
||||
|
||||
@ -599,21 +599,14 @@ export const authController = {
|
||||
const { password } = req.body;
|
||||
|
||||
const user = await prisma.user.findUnique({ where: { id: userId } });
|
||||
if (!user) {
|
||||
if (!user || !user.password) {
|
||||
throw Errors.notFound('User');
|
||||
}
|
||||
|
||||
// Password accounts must re-enter their password; OAuth-only accounts have
|
||||
// no password to check, so the authenticated session is the proof.
|
||||
if (user.password) {
|
||||
if (!password) {
|
||||
throw Errors.badRequest('Password is required to delete account');
|
||||
}
|
||||
|
||||
const validPassword = await bcrypt.compare(password, user.password);
|
||||
if (!validPassword) {
|
||||
throw Errors.unauthorized('Invalid password');
|
||||
}
|
||||
// Verify password
|
||||
const validPassword = await bcrypt.compare(password, user.password);
|
||||
if (!validPassword) {
|
||||
throw Errors.unauthorized('Invalid password');
|
||||
}
|
||||
|
||||
// Delete user and all associated data (cascades handle most relations)
|
||||
|
||||
@ -11,7 +11,6 @@ import { getCachedProfile, setCachedProfile, setCachedRepo } from '../utils/gith
|
||||
import { fetchGitHubTrending } from '../services/ghSocialBridge'
|
||||
import { GitHubService } from '../services/githubService'
|
||||
import { createNotification } from '../services/notificationService'
|
||||
import { harvestContributionEvidence } from '../services/githubContributionsService'
|
||||
|
||||
/**
|
||||
* Resolve the authenticated user's stored GitHub OAuth token, or throw a
|
||||
@ -96,17 +95,7 @@ export const githubController = {
|
||||
})
|
||||
}
|
||||
|
||||
// Backfill real talent-graph contribution evidence for the user's claimed
|
||||
// repositories from the GitHub GraphQL contributionsCollection. Non-fatal:
|
||||
// a failure here must never break the primary project sync.
|
||||
let contributionEvidence = { scannedRepositories: 0, mapped: 0, created: 0 }
|
||||
try {
|
||||
contributionEvidence = await harvestContributionEvidence(userId)
|
||||
} catch (error) {
|
||||
logger.warn('syncProjects: contribution evidence backfill failed', error)
|
||||
}
|
||||
|
||||
res.json({ message: 'Projects synced', count: repos.length, contributionEvidence })
|
||||
res.json({ message: 'Projects synced', count: repos.length })
|
||||
}),
|
||||
|
||||
getProjects: asyncHandler(async (req: AuthRequest, res: Response) => {
|
||||
|
||||
@ -6,34 +6,6 @@ import { blockService } from '../services/blockService';
|
||||
import logger from '../utils/logger';
|
||||
import { asyncHandler, Errors, ApiError } from '../middleware/errorHandler';
|
||||
|
||||
/**
|
||||
* Message.senderId / Message.receiverId / MessageReaction.userId are foreign
|
||||
* keys into Account, not User, even though every other identifier in this
|
||||
* file (req.userId, ChatMember.userId, UserBlock, socket room names,
|
||||
* isUserOnline) is a User id. Passing a raw User id into those columns
|
||||
* violates the FK constraint -- sending a message or reacting to one failed
|
||||
* outright for every caller until these helpers were introduced. Resolve the
|
||||
* caller's (or another participant's) Account id once per request instead.
|
||||
*/
|
||||
async function getOwnAccountId(userId: string): Promise<string> {
|
||||
const account = await prisma.account.findFirst({ where: { userId }, select: { id: true } });
|
||||
if (!account) {
|
||||
throw Errors.notFound('Account');
|
||||
}
|
||||
return account.id;
|
||||
}
|
||||
|
||||
async function getAccountIdForUser(userId: string): Promise<string | null> {
|
||||
const account = await prisma.account.findFirst({ where: { userId }, select: { id: true } });
|
||||
return account?.id ?? null;
|
||||
}
|
||||
|
||||
async function getUserIdForAccount(accountId: string | null | undefined): Promise<string | null> {
|
||||
if (!accountId) return null;
|
||||
const account = await prisma.account.findUnique({ where: { id: accountId }, select: { userId: true } });
|
||||
return account?.userId ?? null;
|
||||
}
|
||||
|
||||
export const sendMessage = asyncHandler(async (req: AuthRequest, res: Response) => {
|
||||
const userId = req.userId!;
|
||||
const { receiverId, content, mediaUrl, chatId } = req.body;
|
||||
@ -46,38 +18,14 @@ export const sendMessage = asyncHandler(async (req: AuthRequest, res: Response)
|
||||
}
|
||||
}
|
||||
|
||||
// Cross-tenant guard: a group-chat message must come from an actual member
|
||||
// of that chat, otherwise any authenticated user could inject messages into
|
||||
// any chat by guessing/supplying its chatId.
|
||||
if (chatId) {
|
||||
const membership = await prisma.chatMember.findFirst({
|
||||
where: { chatId, userId },
|
||||
select: { id: true },
|
||||
});
|
||||
if (!membership) {
|
||||
throw Errors.forbidden('Not authorized to send messages in this chat');
|
||||
}
|
||||
}
|
||||
|
||||
const senderAccountId = await getOwnAccountId(userId);
|
||||
let receiverAccountId: string | null = null;
|
||||
if (receiverId) {
|
||||
receiverAccountId = await getAccountIdForUser(receiverId);
|
||||
if (!receiverAccountId) {
|
||||
throw Errors.notFound('Recipient');
|
||||
}
|
||||
} else if (!chatId) {
|
||||
throw Errors.badRequest('Either receiverId or chatId is required');
|
||||
}
|
||||
|
||||
// Check if recipient is online to set deliveredAt
|
||||
const recipientOnline = isUserOnline(receiverId);
|
||||
const now = new Date();
|
||||
|
||||
const message = await prisma.message.create({
|
||||
data: {
|
||||
senderId: senderAccountId,
|
||||
receiverId: receiverAccountId,
|
||||
senderId: userId,
|
||||
receiverId,
|
||||
chatId,
|
||||
content,
|
||||
mediaUrl,
|
||||
@ -122,17 +70,11 @@ export const getMessages = asyncHandler(async (req: AuthRequest, res: Response)
|
||||
throw Errors.forbidden('Cannot access messages with this user');
|
||||
}
|
||||
|
||||
const ownAccountId = await getOwnAccountId(userId);
|
||||
const otherAccountId = await getAccountIdForUser(otherUserId);
|
||||
if (!otherAccountId) {
|
||||
throw Errors.notFound('User');
|
||||
}
|
||||
|
||||
const messages = await prisma.message.findMany({
|
||||
where: {
|
||||
OR: [
|
||||
{ senderId: ownAccountId, receiverId: otherAccountId },
|
||||
{ senderId: otherAccountId, receiverId: ownAccountId }
|
||||
{ senderId: userId, receiverId: otherUserId },
|
||||
{ senderId: otherUserId, receiverId: userId }
|
||||
]
|
||||
},
|
||||
include: {
|
||||
@ -151,7 +93,7 @@ export const getMessages = asyncHandler(async (req: AuthRequest, res: Response)
|
||||
// Format messages with read receipt status and aggregated reactions
|
||||
const formattedMessages = messages.map(msg => ({
|
||||
...msg,
|
||||
reactions: aggregateReactions(msg.reactions, ownAccountId),
|
||||
reactions: aggregateReactions(msg.reactions, userId),
|
||||
readAt: msg.readAt?.toISOString() || null,
|
||||
deliveredAt: msg.deliveredAt?.toISOString() || null,
|
||||
status: msg.read ? 'read' : (msg.deliveredAt ? 'delivered' : 'sent')
|
||||
@ -162,21 +104,15 @@ export const getMessages = asyncHandler(async (req: AuthRequest, res: Response)
|
||||
|
||||
export const getConversations = asyncHandler(async (req: AuthRequest, res: Response) => {
|
||||
const userId = req.userId!;
|
||||
const ownAccountId = await getOwnAccountId(userId);
|
||||
|
||||
// Get blocked user IDs to filter out from conversations, translated to the
|
||||
// Account ids that Message.senderId/receiverId actually store.
|
||||
const blockedUserIds = await blockService.getAllBlockedIds(userId);
|
||||
const blockedAccounts = blockedUserIds.length
|
||||
? await prisma.account.findMany({ where: { userId: { in: blockedUserIds } }, select: { id: true } })
|
||||
: [];
|
||||
const blockedAccountIds = new Set(blockedAccounts.map(a => a.id));
|
||||
// Get blocked user IDs to filter out from conversations
|
||||
const blockedIds = await blockService.getAllBlockedIds(userId);
|
||||
|
||||
const messages = await prisma.message.findMany({
|
||||
where: {
|
||||
OR: [
|
||||
{ senderId: ownAccountId },
|
||||
{ receiverId: ownAccountId }
|
||||
{ senderId: userId },
|
||||
{ receiverId: userId }
|
||||
]
|
||||
},
|
||||
distinct: ['senderId', 'receiverId'],
|
||||
@ -196,16 +132,15 @@ export const getConversations = asyncHandler(async (req: AuthRequest, res: Respo
|
||||
const conversationPartnerIds: string[] = [];
|
||||
|
||||
messages.forEach(msg => {
|
||||
const otherId = msg.senderId === ownAccountId ? msg.receiverId : msg.senderId;
|
||||
if (!otherId) return; // group-chat message with no single receiver
|
||||
const otherId = msg.senderId === userId ? msg.receiverId : msg.senderId;
|
||||
// Skip blocked users
|
||||
if (blockedAccountIds.has(otherId)) {
|
||||
if (blockedIds.includes(otherId)) {
|
||||
return;
|
||||
}
|
||||
if (!conversations.has(otherId)) {
|
||||
conversationPartnerIds.push(otherId);
|
||||
conversations.set(otherId, {
|
||||
user: msg.senderId === ownAccountId ? msg.receiver : msg.sender,
|
||||
user: msg.senderId === userId ? msg.receiver : msg.sender,
|
||||
lastMessage: {
|
||||
...msg,
|
||||
readAt: msg.readAt?.toISOString() || null,
|
||||
@ -222,7 +157,7 @@ export const getConversations = asyncHandler(async (req: AuthRequest, res: Respo
|
||||
by: ['senderId'],
|
||||
where: {
|
||||
senderId: { in: conversationPartnerIds },
|
||||
receiverId: ownAccountId,
|
||||
receiverId: userId,
|
||||
read: false,
|
||||
deletedForSender: false
|
||||
},
|
||||
@ -245,16 +180,10 @@ export const markAsRead = asyncHandler(async (req: AuthRequest, res: Response) =
|
||||
const { otherUserId } = req.params;
|
||||
const now = new Date();
|
||||
|
||||
const ownAccountId = await getOwnAccountId(userId);
|
||||
const otherAccountId = await getAccountIdForUser(otherUserId);
|
||||
if (!otherAccountId) {
|
||||
throw Errors.notFound('User');
|
||||
}
|
||||
|
||||
const result = await prisma.message.updateMany({
|
||||
where: {
|
||||
senderId: otherAccountId,
|
||||
receiverId: ownAccountId,
|
||||
senderId: otherUserId,
|
||||
receiverId: userId,
|
||||
read: false
|
||||
},
|
||||
data: {
|
||||
@ -268,8 +197,8 @@ export const markAsRead = asyncHandler(async (req: AuthRequest, res: Response) =
|
||||
// Get the message IDs that were marked as read
|
||||
const readMessages = await prisma.message.findMany({
|
||||
where: {
|
||||
senderId: otherAccountId,
|
||||
receiverId: ownAccountId,
|
||||
senderId: otherUserId,
|
||||
receiverId: userId,
|
||||
readAt: now
|
||||
},
|
||||
select: { id: true }
|
||||
@ -295,19 +224,6 @@ export const createGroupChat = asyncHandler(async (req: AuthRequest, res: Respon
|
||||
const userId = req.userId!;
|
||||
const { name, memberIds } = req.body;
|
||||
|
||||
// Block enforcement gap: sendMessage only checks hasBlockRelationship on the
|
||||
// receiverId (DM) branch, never on the chatId (group chat) branch. Without a
|
||||
// check here, a blocked user could route around a block entirely by creating
|
||||
// a "group chat" whose only other member is the user who blocked them, then
|
||||
// messaging through that chatId instead of receiverId. Reject chat creation
|
||||
// up front so that vector doesn't exist.
|
||||
const blockChecks = await Promise.all(
|
||||
memberIds.map((memberId: string) => blockService.hasBlockRelationship(userId, memberId))
|
||||
);
|
||||
if (blockChecks.some(Boolean)) {
|
||||
throw Errors.forbidden('Cannot create a chat with a blocked user');
|
||||
}
|
||||
|
||||
const chat = await prisma.chat.create({
|
||||
data: {
|
||||
name,
|
||||
@ -328,23 +244,10 @@ export const createGroupChat = asyncHandler(async (req: AuthRequest, res: Respon
|
||||
});
|
||||
|
||||
export const getChatMessages = asyncHandler(async (req: AuthRequest, res: Response) => {
|
||||
const userId = req.userId!;
|
||||
const { chatId } = req.params;
|
||||
const { page = 1, limit = 50 } = req.query;
|
||||
const skip = (Number(page) - 1) * Number(limit);
|
||||
|
||||
// Cross-tenant guard: only members of this chat may read its messages.
|
||||
// Without this check any authenticated user could read any group chat's
|
||||
// messages by chatId alone.
|
||||
const membership = await prisma.chatMember.findFirst({
|
||||
where: { chatId, userId },
|
||||
select: { id: true },
|
||||
});
|
||||
|
||||
if (!membership) {
|
||||
throw Errors.forbidden('Not authorized to view this chat');
|
||||
}
|
||||
|
||||
const messages = await prisma.message.findMany({
|
||||
where: { chatId },
|
||||
include: {
|
||||
@ -406,8 +309,7 @@ export const editMessage = asyncHandler(async (req: AuthRequest, res: Response)
|
||||
throw Errors.notFound('Message');
|
||||
}
|
||||
|
||||
const ownAccountId = await getOwnAccountId(userId);
|
||||
if (message.senderId !== ownAccountId) {
|
||||
if (message.senderId !== userId) {
|
||||
throw Errors.forbidden('Not authorized to edit this message');
|
||||
}
|
||||
|
||||
@ -433,13 +335,9 @@ export const editMessage = asyncHandler(async (req: AuthRequest, res: Response)
|
||||
}
|
||||
});
|
||||
|
||||
// Emit socket event for real-time update. Socket rooms are keyed by User
|
||||
// id, so the Account id on the message has to be translated back.
|
||||
// Emit socket event for real-time update
|
||||
if (global.io && message.receiverId) {
|
||||
const receiverUserId = await getUserIdForAccount(message.receiverId);
|
||||
if (receiverUserId) {
|
||||
global.io.to(`user:${receiverUserId}`).emit('message:edited', updatedMessage);
|
||||
}
|
||||
global.io.to(`user:${message.receiverId}`).emit('message:edited', updatedMessage);
|
||||
}
|
||||
if (global.io && message.chatId) {
|
||||
global.io.to(`chat:${message.chatId}`).emit('message:edited', updatedMessage);
|
||||
@ -465,8 +363,7 @@ export const deleteMessage = asyncHandler(async (req: AuthRequest, res: Response
|
||||
throw Errors.notFound('Message');
|
||||
}
|
||||
|
||||
const ownAccountId = await getOwnAccountId(userId);
|
||||
if (message.senderId !== ownAccountId) {
|
||||
if (message.senderId !== userId) {
|
||||
throw Errors.forbidden('Not authorized to delete this message');
|
||||
}
|
||||
|
||||
@ -481,10 +378,7 @@ export const deleteMessage = asyncHandler(async (req: AuthRequest, res: Response
|
||||
|
||||
// Emit socket event for real-time update
|
||||
if (global.io && message.receiverId) {
|
||||
const receiverUserId = await getUserIdForAccount(message.receiverId);
|
||||
if (receiverUserId) {
|
||||
global.io.to(`user:${receiverUserId}`).emit('message:deleted', { messageId, forEveryone: true });
|
||||
}
|
||||
global.io.to(`user:${message.receiverId}`).emit('message:deleted', { messageId, forEveryone: true });
|
||||
}
|
||||
if (global.io && message.chatId) {
|
||||
global.io.to(`chat:${message.chatId}`).emit('message:deleted', { messageId, forEveryone: true });
|
||||
@ -527,8 +421,7 @@ export const getMessage = asyncHandler(async (req: AuthRequest, res: Response) =
|
||||
}
|
||||
|
||||
// Ensure user is participant
|
||||
const ownAccountId = await getOwnAccountId(userId);
|
||||
if (message.senderId !== ownAccountId && message.receiverId !== ownAccountId) {
|
||||
if (message.senderId !== userId && message.receiverId !== userId) {
|
||||
// Check if user is in the chat
|
||||
if (message.chatId) {
|
||||
const membership = await prisma.chatMember.findFirst({
|
||||
@ -572,8 +465,7 @@ export const reportMessage = asyncHandler(async (req: AuthRequest, res: Response
|
||||
}
|
||||
|
||||
// Verify user has access to this message
|
||||
const ownAccountId = await getOwnAccountId(userId);
|
||||
if (message.senderId !== ownAccountId && message.receiverId !== ownAccountId) {
|
||||
if (message.senderId !== userId && message.receiverId !== userId) {
|
||||
if (message.chatId) {
|
||||
const membership = await prisma.chatMember.findFirst({
|
||||
where: { chatId: message.chatId, userId }
|
||||
@ -610,17 +502,11 @@ export const markConversationAsRead = asyncHandler(async (req: AuthRequest, res:
|
||||
|
||||
const now = new Date();
|
||||
|
||||
const ownAccountId = await getOwnAccountId(userId);
|
||||
const partnerAccountId = await getAccountIdForUser(conversationPartnerId);
|
||||
if (!partnerAccountId) {
|
||||
throw Errors.notFound('User');
|
||||
}
|
||||
|
||||
// Mark all unread messages from the other user as read
|
||||
const result = await prisma.message.updateMany({
|
||||
where: {
|
||||
senderId: partnerAccountId,
|
||||
receiverId: ownAccountId,
|
||||
senderId: conversationPartnerId,
|
||||
receiverId: userId,
|
||||
read: false
|
||||
},
|
||||
data: {
|
||||
@ -632,8 +518,8 @@ export const markConversationAsRead = asyncHandler(async (req: AuthRequest, res:
|
||||
// Get the IDs of messages that were marked as read for WebSocket notification
|
||||
const readMessages = await prisma.message.findMany({
|
||||
where: {
|
||||
senderId: partnerAccountId,
|
||||
receiverId: ownAccountId,
|
||||
senderId: conversationPartnerId,
|
||||
receiverId: userId,
|
||||
readAt: now
|
||||
},
|
||||
select: { id: true }
|
||||
@ -675,8 +561,7 @@ export const markMessageAsRead = asyncHandler(async (req: AuthRequest, res: Resp
|
||||
}
|
||||
|
||||
// Only the receiver can mark a message as read
|
||||
const ownAccountId = await getOwnAccountId(userId);
|
||||
if (message.receiverId !== ownAccountId) {
|
||||
if (message.receiverId !== userId) {
|
||||
throw Errors.forbidden('Not authorized to mark this message as read');
|
||||
}
|
||||
|
||||
@ -708,14 +593,11 @@ export const markMessageAsRead = asyncHandler(async (req: AuthRequest, res: Resp
|
||||
|
||||
// Emit WebSocket event to notify sender that their message was read
|
||||
if (global.io) {
|
||||
const senderUserId = await getUserIdForAccount(message.senderId);
|
||||
if (senderUserId) {
|
||||
global.io.to(`user:${senderUserId}`).emit('message:read', {
|
||||
readBy: userId,
|
||||
messageIds: [messageId],
|
||||
readAt: now.toISOString()
|
||||
});
|
||||
}
|
||||
global.io.to(`user:${message.senderId}`).emit('message:read', {
|
||||
readBy: userId,
|
||||
messageIds: [messageId],
|
||||
readAt: now.toISOString()
|
||||
});
|
||||
|
||||
// Also emit to chat room if it's a group chat
|
||||
if (message.chatId) {
|
||||
@ -740,11 +622,10 @@ export const markMessageAsRead = asyncHandler(async (req: AuthRequest, res: Resp
|
||||
*/
|
||||
export const getUnreadCount = asyncHandler(async (req: AuthRequest, res: Response) => {
|
||||
const userId = req.userId!;
|
||||
const ownAccountId = await getOwnAccountId(userId);
|
||||
|
||||
const count = await prisma.message.count({
|
||||
where: {
|
||||
receiverId: ownAccountId,
|
||||
receiverId: userId,
|
||||
read: false,
|
||||
deletedForSender: false
|
||||
}
|
||||
@ -765,11 +646,10 @@ const MAX_REACTIONS_PER_USER = 5;
|
||||
* to (DM sender/receiver or a member of the group chat). Throws otherwise.
|
||||
*/
|
||||
async function assertMessageAccess(
|
||||
message: { senderId: string; receiverId: string | null; chatId: string | null },
|
||||
message: { senderId: string; receiverId: string; chatId: string | null },
|
||||
userId: string,
|
||||
ownAccountId: string,
|
||||
): Promise<void> {
|
||||
if (message.senderId === ownAccountId || message.receiverId === ownAccountId) {
|
||||
if (message.senderId === userId || message.receiverId === userId) {
|
||||
return;
|
||||
}
|
||||
if (message.chatId) {
|
||||
@ -826,19 +706,17 @@ export const addReaction = asyncHandler(async (req: AuthRequest, res: Response)
|
||||
throw Errors.notFound('Message');
|
||||
}
|
||||
|
||||
const ownAccountId = await getOwnAccountId(userId);
|
||||
await assertMessageAccess(message, userId, ownAccountId);
|
||||
await assertMessageAccess(message, userId);
|
||||
|
||||
// Enforce the per-user reaction cap, but allow re-adding an emoji the user
|
||||
// already has (idempotent) so the cap can't lock a user out of a no-op.
|
||||
// MessageReaction.userId is an Account id FK, like Message.senderId/receiverId.
|
||||
const existing = await prisma.messageReaction.findUnique({
|
||||
where: { messageId_userId_emoji: { messageId, userId: ownAccountId, emoji } },
|
||||
where: { messageId_userId_emoji: { messageId, userId, emoji } },
|
||||
});
|
||||
|
||||
if (!existing) {
|
||||
const distinctCount = await prisma.messageReaction.count({
|
||||
where: { messageId, userId: ownAccountId },
|
||||
where: { messageId, userId },
|
||||
});
|
||||
if (distinctCount >= MAX_REACTIONS_PER_USER) {
|
||||
throw Errors.badRequest(
|
||||
@ -846,7 +724,7 @@ export const addReaction = asyncHandler(async (req: AuthRequest, res: Response)
|
||||
);
|
||||
}
|
||||
await prisma.messageReaction.create({
|
||||
data: { messageId, userId: ownAccountId, emoji },
|
||||
data: { messageId, userId, emoji },
|
||||
});
|
||||
}
|
||||
|
||||
@ -854,22 +732,15 @@ export const addReaction = asyncHandler(async (req: AuthRequest, res: Response)
|
||||
where: { messageId },
|
||||
select: { emoji: true, userId: true },
|
||||
});
|
||||
const aggregated = aggregateReactions(reactions, ownAccountId);
|
||||
const aggregated = aggregateReactions(reactions, userId);
|
||||
|
||||
// Notify the other participant(s) so reactions appear in real time. Socket
|
||||
// rooms are keyed by User id, so translate the Account ids back.
|
||||
// Notify the other participant(s) so reactions appear in real time.
|
||||
if (global.io) {
|
||||
const payload = { messageId, userId, emoji, reactions: aggregated };
|
||||
const [receiverUserId, senderUserId] = await Promise.all([
|
||||
getUserIdForAccount(message.receiverId),
|
||||
getUserIdForAccount(message.senderId),
|
||||
]);
|
||||
if (receiverUserId) {
|
||||
global.io.to(`user:${receiverUserId}`).emit('message:reaction', payload);
|
||||
}
|
||||
if (senderUserId) {
|
||||
global.io.to(`user:${senderUserId}`).emit('message:reaction', payload);
|
||||
if (message.receiverId) {
|
||||
global.io.to(`user:${message.receiverId}`).emit('message:reaction', payload);
|
||||
}
|
||||
global.io.to(`user:${message.senderId}`).emit('message:reaction', payload);
|
||||
if (message.chatId) {
|
||||
global.io.to(`chat:${message.chatId}`).emit('message:reaction', payload);
|
||||
}
|
||||
@ -897,31 +768,24 @@ export const removeReaction = asyncHandler(async (req: AuthRequest, res: Respons
|
||||
throw Errors.notFound('Message');
|
||||
}
|
||||
|
||||
const ownAccountId = await getOwnAccountId(userId);
|
||||
await assertMessageAccess(message, userId, ownAccountId);
|
||||
await assertMessageAccess(message, userId);
|
||||
|
||||
await prisma.messageReaction.deleteMany({
|
||||
where: { messageId, userId: ownAccountId, emoji },
|
||||
where: { messageId, userId, emoji },
|
||||
});
|
||||
|
||||
const reactions = await prisma.messageReaction.findMany({
|
||||
where: { messageId },
|
||||
select: { emoji: true, userId: true },
|
||||
});
|
||||
const aggregated = aggregateReactions(reactions, ownAccountId);
|
||||
const aggregated = aggregateReactions(reactions, userId);
|
||||
|
||||
if (global.io) {
|
||||
const payload = { messageId, userId, emoji, removed: true, reactions: aggregated };
|
||||
const [receiverUserId, senderUserId] = await Promise.all([
|
||||
getUserIdForAccount(message.receiverId),
|
||||
getUserIdForAccount(message.senderId),
|
||||
]);
|
||||
if (receiverUserId) {
|
||||
global.io.to(`user:${receiverUserId}`).emit('message:reaction', payload);
|
||||
}
|
||||
if (senderUserId) {
|
||||
global.io.to(`user:${senderUserId}`).emit('message:reaction', payload);
|
||||
if (message.receiverId) {
|
||||
global.io.to(`user:${message.receiverId}`).emit('message:reaction', payload);
|
||||
}
|
||||
global.io.to(`user:${message.senderId}`).emit('message:reaction', payload);
|
||||
if (message.chatId) {
|
||||
global.io.to(`chat:${message.chatId}`).emit('message:reaction', payload);
|
||||
}
|
||||
@ -948,15 +812,14 @@ export const searchMessages = asyncHandler(async (req: AuthRequest, res: Respons
|
||||
}
|
||||
|
||||
const searchTerm = query.trim();
|
||||
const ownAccountId = await getOwnAccountId(userId);
|
||||
|
||||
// Fetch matching messages where the current user is a participant
|
||||
const messages = await prisma.message.findMany({
|
||||
where: {
|
||||
content: { contains: searchTerm, mode: 'insensitive' },
|
||||
OR: [
|
||||
{ senderId: ownAccountId },
|
||||
{ receiverId: ownAccountId },
|
||||
{ senderId: userId },
|
||||
{ receiverId: userId },
|
||||
{
|
||||
chatId: {
|
||||
in: (
|
||||
|
||||
@ -1,130 +0,0 @@
|
||||
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
|
||||
* Creem 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);
|
||||
|
||||
// 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)}`;
|
||||
|
||||
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,
|
||||
},
|
||||
});
|
||||
}),
|
||||
};
|
||||
@ -6,33 +6,6 @@ import { analyzeNeedCoverage } from '../services/talentGapAnalysisService';
|
||||
import prisma from '../utils/prisma';
|
||||
import { normalizePublicHttpUrl } from '../utils/publicHttpUrl';
|
||||
import { runTalentMutation, type TalentMutationResult } from '../services/talentMutationService';
|
||||
import { explainTalentMatch } from '../services/talentGraphRag';
|
||||
import { liveRagAsk } from '../services/talentGraphLlmClient';
|
||||
import type { TalentGraphView } from '../services/talentGraphEdges';
|
||||
|
||||
/**
|
||||
* Run a grounded GraphRAG explanation and translate the module's plain errors
|
||||
* into the API's typed errors. The LLM seam (`ask`) is injected here so the
|
||||
* controller stays a thin adapter over the testable service. `liveRagAsk`
|
||||
* tries Railyard Relay first, falls back to a direct OpenRouter call, and
|
||||
* throws the same "No LLM client" message (surfaced as a 503) when neither
|
||||
* is configured.
|
||||
*/
|
||||
async function runGroundedExplain(
|
||||
developerId: string,
|
||||
query: unknown,
|
||||
loadView?: (id: string) => Promise<TalentGraphView | null>,
|
||||
) {
|
||||
const cleanedQuery = boundedText(query, 'query', 2000);
|
||||
try {
|
||||
return await explainTalentMatch(developerId, cleanedQuery, { ask: liveRagAsk, loadView });
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
if (message.includes('No LLM client')) throw Errors.serviceUnavailable('Talent GraphRAG');
|
||||
if (message.includes('No talent graph view')) throw Errors.userNotFound(developerId);
|
||||
throw Errors.badRequest(message);
|
||||
}
|
||||
}
|
||||
|
||||
const PILOT_STATUSES = ['PLANNED', 'ACTIVE', 'REVIEW', 'COMPLETED', 'CANCELLED'] as const;
|
||||
type PilotStatus = (typeof PILOT_STATUSES)[number];
|
||||
@ -120,33 +93,6 @@ export const talentGraphController = {
|
||||
res.json({ data: graph, meta: { proofSchemaVersion: 1 } });
|
||||
}),
|
||||
|
||||
// GraphRAG serving: grounded "why/how does this developer match?" over the
|
||||
// authenticated user's own assembled talent graph. Non-breaking — a new route
|
||||
// that reuses getTalentGraph via the RAG service's default view loader.
|
||||
explainMine: asyncHandler(async (req: AuthRequest, res: Response) => {
|
||||
const result = await runGroundedExplain(req.userId!, req.body?.query);
|
||||
res.setHeader('Cache-Control', 'no-store, private');
|
||||
res.json({ data: result });
|
||||
}),
|
||||
|
||||
// Grounded explanation over a public developer's privacy-safe dossier. Reuses
|
||||
// getTalentGraph in publicView mode as the injected view loader.
|
||||
explainPublic: asyncHandler(async (req: AuthRequest, res: Response) => {
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { username: req.params.username },
|
||||
select: { id: true, isPrivate: true },
|
||||
});
|
||||
if (!user || user.isPrivate) throw Errors.userNotFound(req.params.username);
|
||||
|
||||
const result = await runGroundedExplain(
|
||||
user.id,
|
||||
req.body?.query,
|
||||
async (id) => (await getTalentGraph(id, { publicView: true })) as TalentGraphView | null,
|
||||
);
|
||||
res.setHeader('Cache-Control', 'no-store');
|
||||
res.json({ data: result });
|
||||
}),
|
||||
|
||||
listOpportunities: asyncHandler(async (req: AuthRequest, res: Response) => {
|
||||
const opportunities = await prisma.talentOpportunity.findMany({
|
||||
where: { status: { in: ['OPEN', 'MATCHING', 'PILOT'] } },
|
||||
|
||||
@ -85,7 +85,6 @@ 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';
|
||||
@ -167,11 +166,9 @@ app.use(requestId);
|
||||
// Compression middleware
|
||||
app.use(compression());
|
||||
|
||||
// Payment webhooks must receive the raw body for HMAC signature verification —
|
||||
// Polar webhook 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' }));
|
||||
@ -286,12 +283,6 @@ app.use('/api/v1/notifications', notificationRoutes);
|
||||
// Notification preferences routes
|
||||
app.use('/api/v1/notifications/preferences', notificationPreferencesRoutes);
|
||||
|
||||
// Alias: the mobile app's settingsService calls GET/PUT /settings/notifications,
|
||||
// which never had a matching route — every load/save silently 404'd and no
|
||||
// preference was ever persisted or read back. Mount the same, already-working
|
||||
// preferences router here too so that client actually reaches real logic.
|
||||
app.use('/api/v1/settings/notifications', notificationPreferencesRoutes);
|
||||
|
||||
// Muted words / tags routes (per-user keyword muting)
|
||||
app.use('/api/v1/muted-words', mutedWordsRoutes);
|
||||
|
||||
|
||||
@ -12,7 +12,6 @@ export type ApiErrorType =
|
||||
| 'rate_limit_exceeded'
|
||||
| 'server_error'
|
||||
| 'conflict'
|
||||
| 'payment_required'
|
||||
| 'validation_error';
|
||||
|
||||
export interface ApiErrorResponse {
|
||||
@ -183,15 +182,6 @@ 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),
|
||||
|
||||
@ -313,15 +313,14 @@ router.post('/recover-account',
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* required:
|
||||
* - password
|
||||
* properties:
|
||||
* password:
|
||||
* type: string
|
||||
* description: Required for password accounts; omitted by OAuth-only accounts
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Account deletion initiated
|
||||
* 400:
|
||||
* description: Password missing on a password account
|
||||
* 401:
|
||||
* description: Invalid password
|
||||
*/
|
||||
@ -329,18 +328,7 @@ router.delete('/delete-account',
|
||||
authenticate,
|
||||
accountDeletionLimiter,
|
||||
validate([
|
||||
body('password').optional({ nullable: true }).isString().withMessage('Password must be a string'),
|
||||
]),
|
||||
authController.deleteAccount
|
||||
);
|
||||
|
||||
// Alias clients used to call (web `userService`, mobile `complianceService`).
|
||||
// Kept so old app builds that shipped the `/auth/account` path keep working.
|
||||
router.delete('/account',
|
||||
authenticate,
|
||||
accountDeletionLimiter,
|
||||
validate([
|
||||
body('password').optional({ nullable: true }).isString().withMessage('Password must be a string'),
|
||||
body('password').notEmpty().withMessage('Password is required to delete account'),
|
||||
]),
|
||||
authController.deleteAccount
|
||||
);
|
||||
|
||||
@ -1,196 +0,0 @@
|
||||
/**
|
||||
* 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<string, unknown>;
|
||||
|
||||
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<void> {
|
||||
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<void> => {
|
||||
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<typeof creemEnv>;
|
||||
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;
|
||||
@ -1,7 +1,6 @@
|
||||
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';
|
||||
|
||||
@ -28,17 +27,11 @@ function requireMutationOrigin(req: Request, _res: Response, next: NextFunction)
|
||||
}
|
||||
|
||||
router.get('/me', authenticate, talentGraphController.getMine);
|
||||
router.post('/me/explain', authenticate, requireMutationOrigin, interactionLimiter, talentGraphController.explainMine);
|
||||
router.get('/public/:username', talentGraphController.getPublic);
|
||||
router.post('/public/:username/explain', optionalAuth, requireMutationOrigin, interactionLimiter, talentGraphController.explainPublic);
|
||||
router.get('/opportunities', optionalAuth, talentGraphController.listOpportunities);
|
||||
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);
|
||||
|
||||
@ -1,120 +0,0 @@
|
||||
/**
|
||||
* 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<string, string | number>;
|
||||
}
|
||||
|
||||
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<CreateCreemCheckoutInput>,
|
||||
): Promise<CreemCheckout> {
|
||||
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,
|
||||
};
|
||||
}
|
||||
@ -1,333 +0,0 @@
|
||||
/**
|
||||
* GitHub contributions harvester (talent-graph evidence backfill).
|
||||
*
|
||||
* The talent graph derives `github_activity` evidence from `RepositoryActivity`
|
||||
* rows. Until now those rows were written ONLY by the GitHub App webhook
|
||||
* (githubActivityService.processGitHubEvent), so a brand-new user's
|
||||
* contribution-trajectory evidence was empty until an owner configured a
|
||||
* webhook and it fired — an operational dependency, not real data at first run.
|
||||
*
|
||||
* This service backfills genuine contribution evidence at sync time using the
|
||||
* GitHub GraphQL `contributionsCollection` (real commits / PRs / reviews /
|
||||
* issues the user actually made). It is:
|
||||
* - Real, never fabricated — every row maps to an actual GitHub contribution.
|
||||
* - Scoped to the user's *managed* repositories (RepositoryManager), so it
|
||||
* only produces evidence the talent graph will surface, and never invents
|
||||
* Repository rows.
|
||||
* - Attributed to the user's GitHub identity (actorLogin = githubUsername),
|
||||
* which is exactly what the evidence query filters on.
|
||||
* - Deduped by a deterministic `eventId`, mirroring the delivery-id
|
||||
* idempotency discipline the webhook path uses, so re-syncing is a no-op.
|
||||
*
|
||||
* The mapping (`mapContributionsToActivities`) is pure and dependency-injected
|
||||
* so it can be unit tested without a live Postgres or GitHub.
|
||||
*/
|
||||
import { Octokit } from '@octokit/rest';
|
||||
import { GitHubEventType, Prisma } from '@prisma/client';
|
||||
import prisma from '../utils/prisma';
|
||||
import logger from '../utils/logger';
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// GraphQL response shapes (only the fields we consume; external data)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
interface ContribRepoRef {
|
||||
nameWithOwner: string;
|
||||
url?: string | null;
|
||||
}
|
||||
|
||||
interface CommitContributionsByRepository {
|
||||
repository: ContribRepoRef;
|
||||
contributions: { nodes: Array<{ occurredAt: string; commitCount: number } | null> };
|
||||
}
|
||||
|
||||
interface PullRequestContributionsByRepository {
|
||||
repository: ContribRepoRef;
|
||||
contributions: {
|
||||
nodes: Array<{
|
||||
pullRequest: { id: string; number: number; title: string; url: string; createdAt: string; merged: boolean } | null;
|
||||
} | null>;
|
||||
};
|
||||
}
|
||||
|
||||
interface PullRequestReviewContributionsByRepository {
|
||||
repository: ContribRepoRef;
|
||||
contributions: {
|
||||
nodes: Array<{
|
||||
occurredAt?: string | null;
|
||||
pullRequestReview: { id: string; url?: string | null; submittedAt?: string | null } | null;
|
||||
pullRequest: { number: number; title: string; url?: string | null } | null;
|
||||
} | null>;
|
||||
};
|
||||
}
|
||||
|
||||
interface IssueContributionsByRepository {
|
||||
repository: ContribRepoRef;
|
||||
contributions: {
|
||||
nodes: Array<{
|
||||
issue: { id: string; number: number; title: string; url: string; createdAt: string } | null;
|
||||
} | null>;
|
||||
};
|
||||
}
|
||||
|
||||
export interface ContributionsCollection {
|
||||
commitContributionsByRepository?: CommitContributionsByRepository[] | null;
|
||||
pullRequestContributionsByRepository?: PullRequestContributionsByRepository[] | null;
|
||||
pullRequestReviewContributionsByRepository?: PullRequestReviewContributionsByRepository[] | null;
|
||||
issueContributionsByRepository?: IssueContributionsByRepository[] | null;
|
||||
}
|
||||
|
||||
export interface ContributionsResponse {
|
||||
user: { contributionsCollection: ContributionsCollection | null } | null;
|
||||
}
|
||||
|
||||
export interface MapContributionsContext {
|
||||
/** The GitHub login these contributions belong to (evidence attribution). */
|
||||
githubUsername: string;
|
||||
/** Managed repository ids keyed by lowercased `owner/name`. */
|
||||
repoIdByFullName: ReadonlyMap<string, string>;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// GraphQL query
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export const CONTRIBUTIONS_QUERY = `
|
||||
query ContributionEvidence($login: String!) {
|
||||
user(login: $login) {
|
||||
contributionsCollection {
|
||||
commitContributionsByRepository(maxRepositories: 100) {
|
||||
repository { nameWithOwner url }
|
||||
contributions(first: 100) { nodes { occurredAt commitCount } }
|
||||
}
|
||||
pullRequestContributionsByRepository(maxRepositories: 100) {
|
||||
repository { nameWithOwner url }
|
||||
contributions(first: 50) { nodes { pullRequest { id number title url createdAt merged } } }
|
||||
}
|
||||
pullRequestReviewContributionsByRepository(maxRepositories: 100) {
|
||||
repository { nameWithOwner url }
|
||||
contributions(first: 50) { nodes { occurredAt pullRequestReview { id url submittedAt } pullRequest { number title url } } }
|
||||
}
|
||||
issueContributionsByRepository(maxRepositories: 100) {
|
||||
repository { nameWithOwner url }
|
||||
contributions(first: 50) { nodes { issue { id number title url createdAt } } }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Pure mapping: contributionsCollection -> RepositoryActivity create inputs
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function resolveRepoId(
|
||||
repository: ContribRepoRef | undefined,
|
||||
repoIdByFullName: ReadonlyMap<string, string>,
|
||||
): string | null {
|
||||
const fullName = repository?.nameWithOwner;
|
||||
if (!fullName) return null;
|
||||
return repoIdByFullName.get(fullName.toLowerCase()) ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Maps a GraphQL `contributionsCollection` into RepositoryActivity create
|
||||
* inputs, restricted to the user's managed repositories. Pure and deterministic:
|
||||
* - only contributions to a managed repository are emitted;
|
||||
* - `actorLogin` is always the user (attribution the evidence query needs);
|
||||
* - `eventId` is a stable, content-derived key so re-runs dedupe cleanly.
|
||||
*/
|
||||
export function mapContributionsToActivities(
|
||||
collection: ContributionsCollection | null | undefined,
|
||||
ctx: MapContributionsContext,
|
||||
): Prisma.RepositoryActivityCreateManyInput[] {
|
||||
if (!collection) return [];
|
||||
const actorLogin = ctx.githubUsername;
|
||||
const rows: Prisma.RepositoryActivityCreateManyInput[] = [];
|
||||
const seenEventIds = new Set<string>();
|
||||
|
||||
const push = (row: Prisma.RepositoryActivityCreateManyInput): void => {
|
||||
if (seenEventIds.has(row.eventId)) return;
|
||||
seenEventIds.add(row.eventId);
|
||||
rows.push(row);
|
||||
};
|
||||
|
||||
// Commits — aggregated per repository into day buckets by the API.
|
||||
for (const entry of collection.commitContributionsByRepository ?? []) {
|
||||
const repositoryId = resolveRepoId(entry?.repository, ctx.repoIdByFullName);
|
||||
if (!repositoryId) continue;
|
||||
const url = entry.repository.url ?? null;
|
||||
for (const node of entry.contributions?.nodes ?? []) {
|
||||
if (!node || !node.occurredAt || !node.commitCount) continue;
|
||||
const commitCount = node.commitCount;
|
||||
push({
|
||||
repositoryId,
|
||||
eventType: GitHubEventType.PUSH,
|
||||
eventId: `contrib:commit:${repositoryId}:${node.occurredAt}`,
|
||||
action: 'contributed',
|
||||
actorLogin,
|
||||
title: `Contributed ${commitCount} commit${commitCount === 1 ? '' : 's'}`,
|
||||
url,
|
||||
occurredAt: new Date(node.occurredAt),
|
||||
metadata: { source: 'contributionsCollection', kind: 'commit', commitCount },
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Pull requests authored.
|
||||
for (const entry of collection.pullRequestContributionsByRepository ?? []) {
|
||||
const repositoryId = resolveRepoId(entry?.repository, ctx.repoIdByFullName);
|
||||
if (!repositoryId) continue;
|
||||
for (const node of entry.contributions?.nodes ?? []) {
|
||||
const pr = node?.pullRequest;
|
||||
if (!pr || !pr.id || !pr.createdAt) continue;
|
||||
push({
|
||||
repositoryId,
|
||||
eventType: GitHubEventType.PULL_REQUEST,
|
||||
eventId: `contrib:pr:${pr.id}`,
|
||||
action: pr.merged ? 'merged' : 'opened',
|
||||
actorLogin,
|
||||
title: `Opened PR #${pr.number}: ${pr.title}`,
|
||||
url: pr.url ?? null,
|
||||
occurredAt: new Date(pr.createdAt),
|
||||
metadata: { source: 'contributionsCollection', kind: 'pull_request', number: pr.number, merged: pr.merged },
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Pull request reviews.
|
||||
for (const entry of collection.pullRequestReviewContributionsByRepository ?? []) {
|
||||
const repositoryId = resolveRepoId(entry?.repository, ctx.repoIdByFullName);
|
||||
if (!repositoryId) continue;
|
||||
for (const node of entry.contributions?.nodes ?? []) {
|
||||
const review = node?.pullRequestReview;
|
||||
const occurredAt = node?.occurredAt ?? review?.submittedAt;
|
||||
if (!review || !review.id || !occurredAt) continue;
|
||||
const number = node?.pullRequest?.number;
|
||||
push({
|
||||
repositoryId,
|
||||
eventType: GitHubEventType.PULL_REQUEST,
|
||||
eventId: `contrib:review:${review.id}`,
|
||||
action: 'reviewed',
|
||||
actorLogin,
|
||||
title: number != null ? `Reviewed PR #${number}` : 'Reviewed a pull request',
|
||||
url: review.url ?? node?.pullRequest?.url ?? null,
|
||||
occurredAt: new Date(occurredAt),
|
||||
metadata: { source: 'contributionsCollection', kind: 'pull_request_review', number: number ?? null },
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Issues opened.
|
||||
for (const entry of collection.issueContributionsByRepository ?? []) {
|
||||
const repositoryId = resolveRepoId(entry?.repository, ctx.repoIdByFullName);
|
||||
if (!repositoryId) continue;
|
||||
for (const node of entry.contributions?.nodes ?? []) {
|
||||
const issue = node?.issue;
|
||||
if (!issue || !issue.id || !issue.createdAt) continue;
|
||||
push({
|
||||
repositoryId,
|
||||
eventType: GitHubEventType.ISSUES,
|
||||
eventId: `contrib:issue:${issue.id}`,
|
||||
action: 'opened',
|
||||
actorLogin,
|
||||
title: `Opened issue #${issue.number}: ${issue.title}`,
|
||||
url: issue.url ?? null,
|
||||
occurredAt: new Date(issue.createdAt),
|
||||
metadata: { source: 'contributionsCollection', kind: 'issue', number: issue.number },
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return rows;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Harvester (GraphQL fetch + deduped insert)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export type GraphqlClient = (query: string, variables: Record<string, unknown>) => Promise<ContributionsResponse>;
|
||||
|
||||
export interface HarvestDb {
|
||||
user: { findUnique: (args: unknown) => Promise<{ githubAccessToken: string | null; githubUsername: string | null } | null> };
|
||||
repositoryManager: { findMany: (args: unknown) => Promise<Array<{ repository: { id: string; fullName: string } }>> };
|
||||
repositoryActivity: { createMany: (args: { data: Prisma.RepositoryActivityCreateManyInput[]; skipDuplicates?: boolean }) => Promise<{ count: number }> };
|
||||
}
|
||||
|
||||
export interface HarvestDeps {
|
||||
db?: HarvestDb;
|
||||
graphqlClient?: GraphqlClient;
|
||||
}
|
||||
|
||||
export interface HarvestResult {
|
||||
scannedRepositories: number;
|
||||
mapped: number;
|
||||
created: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Backfills contribution evidence for a user's managed repositories. Safe to
|
||||
* call on every sync: it is a no-op when the user has no linked GitHub token,
|
||||
* no GitHub username, or no managed repositories, and inserts are deduped by
|
||||
* the deterministic contribution eventId.
|
||||
*/
|
||||
export async function harvestContributionEvidence(
|
||||
userId: string,
|
||||
deps: HarvestDeps = {},
|
||||
): Promise<HarvestResult> {
|
||||
const db = deps.db ?? (prisma as unknown as HarvestDb);
|
||||
const empty: HarvestResult = { scannedRepositories: 0, mapped: 0, created: 0 };
|
||||
|
||||
const user = await db.user.findUnique({
|
||||
where: { id: userId },
|
||||
select: { githubAccessToken: true, githubUsername: true },
|
||||
});
|
||||
if (!user?.githubAccessToken || !user.githubUsername) return empty;
|
||||
|
||||
const managed = await db.repositoryManager.findMany({
|
||||
where: { userId },
|
||||
select: { repository: { select: { id: true, fullName: true } } },
|
||||
});
|
||||
if (managed.length === 0) return empty;
|
||||
|
||||
const repoIdByFullName = new Map<string, string>();
|
||||
for (const manager of managed) {
|
||||
if (manager.repository?.fullName && manager.repository.id) {
|
||||
repoIdByFullName.set(manager.repository.fullName.toLowerCase(), manager.repository.id);
|
||||
}
|
||||
}
|
||||
if (repoIdByFullName.size === 0) return empty;
|
||||
|
||||
const graphqlClient: GraphqlClient =
|
||||
deps.graphqlClient ??
|
||||
((query, variables) =>
|
||||
new Octokit({ auth: user.githubAccessToken! }).graphql<ContributionsResponse>(query, variables));
|
||||
|
||||
let response: ContributionsResponse;
|
||||
try {
|
||||
response = await graphqlClient(CONTRIBUTIONS_QUERY, { login: user.githubUsername });
|
||||
} catch (error) {
|
||||
logger.warn('[contributions] GraphQL harvest failed', { userId, error });
|
||||
return { ...empty, scannedRepositories: repoIdByFullName.size };
|
||||
}
|
||||
|
||||
const activities = mapContributionsToActivities(response?.user?.contributionsCollection, {
|
||||
githubUsername: user.githubUsername,
|
||||
repoIdByFullName,
|
||||
});
|
||||
|
||||
if (activities.length === 0) {
|
||||
return { scannedRepositories: repoIdByFullName.size, mapped: 0, created: 0 };
|
||||
}
|
||||
|
||||
const result = await db.repositoryActivity.createMany({ data: activities, skipDuplicates: true });
|
||||
|
||||
logger.info('[contributions] Backfilled contribution evidence', {
|
||||
userId,
|
||||
scannedRepositories: repoIdByFullName.size,
|
||||
mapped: activities.length,
|
||||
created: result.count,
|
||||
});
|
||||
|
||||
return { scannedRepositories: repoIdByFullName.size, mapped: activities.length, created: result.count };
|
||||
}
|
||||
@ -1,323 +0,0 @@
|
||||
/**
|
||||
* 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 Creem adapter (a merchant-of-record supporting Turkey-based
|
||||
* sellers) and settled by the signed Creem `checkout.completed` 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, Creem, 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<any> };
|
||||
talentPlacement: {
|
||||
findUnique: (args: any) => Promise<any>;
|
||||
create: (args: any) => Promise<any>;
|
||||
update: (args: any) => Promise<any>;
|
||||
};
|
||||
};
|
||||
|
||||
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<RequestCandidateUnlockResult> {
|
||||
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 (Creem checkout.completed 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<SettlePlacementResult> {
|
||||
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<boolean> {
|
||||
const placement = await db.talentPlacement.findUnique({
|
||||
where: placementWhere(opportunityId, candidateId, recruiterId),
|
||||
});
|
||||
return placement?.status === 'paid';
|
||||
}
|
||||
@ -1,133 +0,0 @@
|
||||
/**
|
||||
* Edge extraction from the assembled talent graph.
|
||||
*
|
||||
* `getTalentGraph` (talentGraphService.ts) already assembles a developer's
|
||||
* projects, collaborators and evidence on read, but returns them as nested view
|
||||
* objects — not as typed, provenanced edges. This module is the extraction step
|
||||
* of the graph pipeline: it turns that view into flat candidate edges
|
||||
* (`TalentEdgeInput`) which the ontology's `validateEdges` then vets against
|
||||
* domain/range before anything is persisted. Extract → validate → serve.
|
||||
*
|
||||
* It REUSES rather than rebuilds:
|
||||
* - the shapes produced by `getTalentGraph` (structural subset below),
|
||||
* - `canonicalizeSkill` from skillTaxonomyService for skill-node identity,
|
||||
* - the ontology's `EvidenceSource` union, aligned with `TalentEvidence.kind`.
|
||||
*
|
||||
* Pure and dependency-light: takes an already-fetched graph view, does no I/O.
|
||||
*/
|
||||
import { canonicalizeSkill } from './skillTaxonomyService';
|
||||
import { EVIDENCE_SOURCES, type EvidenceSource, type TalentEdgeInput } from './talentGraphOntology';
|
||||
|
||||
type EvidenceLevel = 'verified' | 'linked' | 'recorded';
|
||||
|
||||
/** Confidence for an edge derived from a project at a given verification tier. */
|
||||
const CONFIDENCE_BY_LEVEL: Readonly<Record<EvidenceLevel, number>> = {
|
||||
verified: 1,
|
||||
linked: 0.75,
|
||||
recorded: 0.5,
|
||||
};
|
||||
|
||||
const SOURCE_SET: ReadonlySet<string> = new Set(EVIDENCE_SOURCES);
|
||||
|
||||
/** Structural subset of one project as returned by `getTalentGraph`. */
|
||||
export interface GraphProjectView {
|
||||
readonly id: string;
|
||||
readonly url: string | null;
|
||||
readonly topics: readonly string[];
|
||||
readonly verificationLevel: EvidenceLevel;
|
||||
readonly lastVerifiedAt: Date;
|
||||
readonly evidence: readonly { readonly kind: string; readonly sourceUrl: string | null }[];
|
||||
}
|
||||
|
||||
/** Structural subset of one collaborator as returned by `getTalentGraph`. */
|
||||
export interface GraphCollaboratorView {
|
||||
readonly id: string;
|
||||
readonly sharedProjects: readonly { readonly id: string; readonly url: string }[];
|
||||
}
|
||||
|
||||
/** Structural subset of the whole graph view `deriveTalentEdges` consumes. */
|
||||
export interface TalentGraphView {
|
||||
readonly profile: { readonly id: string };
|
||||
readonly projects: readonly GraphProjectView[];
|
||||
readonly collaborators: readonly GraphCollaboratorView[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Pick the provenance source for a project-derived edge from its strongest
|
||||
* evidence record, falling back to `project_record` when the evidence carries no
|
||||
* recognized kind. Keeps edge provenance traceable to the same evidence the
|
||||
* dossier shows the user.
|
||||
*/
|
||||
function projectSource(project: GraphProjectView): EvidenceSource {
|
||||
const known = project.evidence.find((item) => SOURCE_SET.has(item.kind));
|
||||
return (known?.kind as EvidenceSource) ?? 'project_record';
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract candidate edges from a talent graph view. The output is intentionally
|
||||
* untrusted `TalentEdgeInput[]`: run it through `validateEdges` to get the vetted,
|
||||
* de-duplicated edge set. Emits three relation families:
|
||||
* - developer —contributed_to→ repo (one per project)
|
||||
* - developer —has_skill→ skill (one per canonicalized project topic)
|
||||
* - developer —collaborated_with→ developer (one per collaborator, symmetric)
|
||||
*/
|
||||
export function deriveTalentEdges(graph: TalentGraphView): TalentEdgeInput[] {
|
||||
const developerId = graph.profile.id;
|
||||
const edges: TalentEdgeInput[] = [];
|
||||
if (!developerId) return edges;
|
||||
|
||||
for (const project of graph.projects) {
|
||||
const source = projectSource(project);
|
||||
const confidence = CONFIDENCE_BY_LEVEL[project.verificationLevel];
|
||||
|
||||
edges.push({
|
||||
type: 'contributed_to',
|
||||
from: { id: developerId, type: 'developer' },
|
||||
to: { id: project.id, type: 'repo' },
|
||||
provenance: {
|
||||
source,
|
||||
observedAt: project.lastVerifiedAt,
|
||||
confidence,
|
||||
sourceUrl: project.url,
|
||||
},
|
||||
});
|
||||
|
||||
const seenSkills = new Set<string>();
|
||||
for (const topic of project.topics) {
|
||||
const skill = canonicalizeSkill(topic);
|
||||
if (!skill || seenSkills.has(skill)) continue;
|
||||
seenSkills.add(skill);
|
||||
edges.push({
|
||||
type: 'has_skill',
|
||||
from: { id: developerId, type: 'developer' },
|
||||
to: { id: skill, type: 'skill' },
|
||||
provenance: {
|
||||
source,
|
||||
observedAt: project.lastVerifiedAt,
|
||||
// A skill inferred from a repo topic is weaker than the contribution
|
||||
// itself; cap it at the "recorded" tier.
|
||||
confidence: Math.min(confidence, CONFIDENCE_BY_LEVEL.recorded),
|
||||
sourceUrl: project.url,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
for (const collaborator of graph.collaborators) {
|
||||
if (!collaborator.id || collaborator.id === developerId) continue;
|
||||
const shared = collaborator.sharedProjects[0];
|
||||
edges.push({
|
||||
type: 'collaborated_with',
|
||||
from: { id: developerId, type: 'developer' },
|
||||
to: { id: collaborator.id, type: 'developer' },
|
||||
provenance: {
|
||||
source: 'github_sync',
|
||||
observedAt: new Date(),
|
||||
confidence: CONFIDENCE_BY_LEVEL.recorded,
|
||||
sourceUrl: shared?.url ?? null,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return edges;
|
||||
}
|
||||
@ -1,115 +0,0 @@
|
||||
/**
|
||||
* Real LLM seam for talent GraphRAG's `explainTalentMatch`.
|
||||
*
|
||||
* Relay-first: Railyard Relay (our TensorZero fork) serves Anthropic models
|
||||
* through an OpenAI-compatible endpoint, billed to our own Anthropic credits
|
||||
* with a per-key spend cap. Falls back to a direct OpenRouter call on any
|
||||
* Relay failure (network, non-2xx, bad JSON) or when Relay isn't configured.
|
||||
* Both paths speak the same OpenAI-compatible chat/completions shape, so one
|
||||
* request builder and one response parser cover both.
|
||||
*
|
||||
* Env-gated, not hardcoded: `RELAY_URL`+`RELAY_API_KEY` enable the Relay path,
|
||||
* `OPENROUTER_API_KEY` enables the direct fallback. Neither configured ->
|
||||
* throws the same "No LLM client is configured" message `defaultRagAsk` does,
|
||||
* so callers can't silently get a different error shape.
|
||||
*/
|
||||
import logger from '../utils/logger';
|
||||
import type { RagAsk, RagAskRequest } from './talentGraphRagPrompt';
|
||||
|
||||
const RELAY_CHAT_PATH = '/openai/v1/chat/completions';
|
||||
const OPENROUTER_URL = 'https://openrouter.ai/api/v1/chat/completions';
|
||||
const RELAY_MODEL_PREFIX = 'tensorzero::model_name::anthropic::';
|
||||
const DEFAULT_RELAY_MODEL = 'claude-haiku-4-5-20251001';
|
||||
const DEFAULT_DIRECT_MODEL = 'anthropic/claude-haiku-4.5';
|
||||
const DEFAULT_TIMEOUT_MS = 60_000;
|
||||
const MAX_TOKENS = 1024;
|
||||
|
||||
interface ChatCompletionConfig {
|
||||
readonly endpoint: string;
|
||||
readonly apiKey: string;
|
||||
readonly model: string;
|
||||
}
|
||||
|
||||
function toChatBody(request: RagAskRequest, model: string): Record<string, unknown> {
|
||||
return {
|
||||
model,
|
||||
max_tokens: MAX_TOKENS,
|
||||
temperature: 0,
|
||||
messages: [
|
||||
{ role: 'system', content: request.system },
|
||||
{ role: 'user', content: `${request.context}\n\nQUESTION: ${request.query}` },
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
async function callChatCompletions(config: ChatCompletionConfig, body: Record<string, unknown>): Promise<string> {
|
||||
const response = await fetch(config.endpoint, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
authorization: `Bearer ${config.apiKey}`,
|
||||
'content-type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify(body),
|
||||
signal: AbortSignal.timeout(DEFAULT_TIMEOUT_MS),
|
||||
});
|
||||
if (!response.ok) {
|
||||
const detail = (await response.text().catch(() => '')).slice(0, 200);
|
||||
throw new Error(`LLM endpoint ${config.endpoint} answered ${response.status}: ${detail}`);
|
||||
}
|
||||
const json = (await response.json()) as {
|
||||
choices?: { message?: { content?: unknown } }[];
|
||||
};
|
||||
const text = json.choices?.[0]?.message?.content;
|
||||
if (typeof text !== 'string' || !text.trim()) {
|
||||
throw new Error('LLM endpoint returned no message content');
|
||||
}
|
||||
return text;
|
||||
}
|
||||
|
||||
function relayConfig(): ChatCompletionConfig | null {
|
||||
const url = process.env.RELAY_URL?.trim();
|
||||
const apiKey = process.env.RELAY_API_KEY?.trim();
|
||||
if (!url || !apiKey) return null;
|
||||
const model = process.env.GITGRAM_RAG_RELAY_MODEL?.trim() || DEFAULT_RELAY_MODEL;
|
||||
return {
|
||||
endpoint: new URL(RELAY_CHAT_PATH, url).toString(),
|
||||
apiKey,
|
||||
model: `${RELAY_MODEL_PREFIX}${model}`,
|
||||
};
|
||||
}
|
||||
|
||||
function directConfig(): ChatCompletionConfig | null {
|
||||
const apiKey = process.env.OPENROUTER_API_KEY?.trim();
|
||||
if (!apiKey) return null;
|
||||
const model = process.env.GITGRAM_RAG_DIRECT_MODEL?.trim() || DEFAULT_DIRECT_MODEL;
|
||||
return { endpoint: OPENROUTER_URL, apiKey, model };
|
||||
}
|
||||
|
||||
/**
|
||||
* Real LLM client: Relay first, falls back to a direct OpenRouter call on any
|
||||
* Relay failure or when Relay isn't configured. Exactly the `RagAsk` seam
|
||||
* `explainTalentMatch` expects — raw prompt in, raw model text out; grounding
|
||||
* enforcement happens in the caller, not here.
|
||||
*/
|
||||
export const liveRagAsk: RagAsk = async (request) => {
|
||||
const relay = relayConfig();
|
||||
const direct = directConfig();
|
||||
if (!relay && !direct) {
|
||||
throw new Error(
|
||||
'No LLM client is configured for talent GraphRAG. Set RELAY_URL/RELAY_API_KEY or OPENROUTER_API_KEY.',
|
||||
);
|
||||
}
|
||||
if (relay) {
|
||||
try {
|
||||
return await callChatCompletions(relay, toChatBody(request, relay.model));
|
||||
} catch (error) {
|
||||
const reason = error instanceof Error ? error.message.slice(0, 160) : String(error);
|
||||
if (!direct) throw error;
|
||||
logger.warn('talent-graphrag relay call failed, falling back to direct provider', {
|
||||
event: 'talent_graph.rag.relay_fallback',
|
||||
reason,
|
||||
});
|
||||
}
|
||||
}
|
||||
return callChatCompletions(direct as ChatCompletionConfig, toChatBody(request, (direct as ChatCompletionConfig).model));
|
||||
};
|
||||
@ -1,291 +0,0 @@
|
||||
/**
|
||||
* Talent-graph ontology + edge validation.
|
||||
*
|
||||
* A graph is a PRODUCT WITH A SCHEMA, not a pile of triples. Before this rung the
|
||||
* talent graph was assembled implicitly inside `getTalentGraph` — projects,
|
||||
* collaborators and skills were derived on read, but no typed contract said which
|
||||
* relationships are *legal*. This module promotes that implicit structure to an
|
||||
* explicit ontology and adds the single guardrail that removes hallucinated
|
||||
* structure: every candidate edge is validated against its edge type's
|
||||
* domain/range, and type-incompatible edges are rejected with a reason.
|
||||
*
|
||||
* Entities (node types): developer, repo, org, skill, contribution.
|
||||
* Relations (edge types): contributed_to, member_of, has_skill, collaborated_with.
|
||||
*
|
||||
* Discipline applied here (not recited):
|
||||
* - Model types BEFORE writing edges (TALENT_ONTOLOGY below).
|
||||
* - Provenance on EVERY fact: source, observedAt, confidence, sourceUrl.
|
||||
* - Validate edges against domain/range; reject type-incompatible ones.
|
||||
* - Incremental & pure: no Prisma, no I/O — unit-testable in isolation, mirroring
|
||||
* skillTaxonomyService / talentGapAnalysisService.
|
||||
*
|
||||
* The evidence `source` union is deliberately aligned with the `kind` field of
|
||||
* `TalentEvidence` in talentGraphService.ts (plus `profile_interest`) so edges
|
||||
* derived from that service carry provenance the rest of the graph already speaks.
|
||||
*/
|
||||
|
||||
export const TALENT_NODE_TYPES = ['developer', 'repo', 'org', 'skill', 'contribution'] as const;
|
||||
export type TalentNodeType = (typeof TALENT_NODE_TYPES)[number];
|
||||
|
||||
export const TALENT_EDGE_TYPES = ['contributed_to', 'member_of', 'has_skill', 'collaborated_with'] as const;
|
||||
export type TalentEdgeType = (typeof TALENT_EDGE_TYPES)[number];
|
||||
|
||||
/**
|
||||
* Provenance sources. Kept in lock-step with `TalentEvidence['kind']` in
|
||||
* talentGraphService.ts, extended with `profile_interest` for the weakest signal
|
||||
* (a self-declared interest with no repository/pilot evidence behind it).
|
||||
*/
|
||||
export const EVIDENCE_SOURCES = [
|
||||
'repository_claim',
|
||||
'github_sync',
|
||||
'github_activity',
|
||||
'project_record',
|
||||
'institutional_pilot',
|
||||
'profile_interest',
|
||||
] as const;
|
||||
export type EvidenceSource = (typeof EVIDENCE_SOURCES)[number];
|
||||
|
||||
/**
|
||||
* Domain/range contract for one edge type. `domain` is the set of legal source
|
||||
* node types, `range` the set of legal target node types. `symmetric` marks
|
||||
* undirected relations (collaborated_with) so A→B and B→A collapse to one edge.
|
||||
* `reflexiveAllowed` guards self-loops (a developer cannot collaborate with self).
|
||||
*/
|
||||
export interface EdgeTypeDefinition {
|
||||
readonly type: TalentEdgeType;
|
||||
readonly domain: readonly TalentNodeType[];
|
||||
readonly range: readonly TalentNodeType[];
|
||||
readonly symmetric: boolean;
|
||||
readonly reflexiveAllowed: boolean;
|
||||
}
|
||||
|
||||
export const TALENT_ONTOLOGY: Readonly<Record<TalentEdgeType, EdgeTypeDefinition>> = {
|
||||
contributed_to: {
|
||||
type: 'contributed_to',
|
||||
domain: ['developer'],
|
||||
range: ['repo'],
|
||||
symmetric: false,
|
||||
reflexiveAllowed: false,
|
||||
},
|
||||
member_of: {
|
||||
type: 'member_of',
|
||||
domain: ['developer'],
|
||||
range: ['org'],
|
||||
symmetric: false,
|
||||
reflexiveAllowed: false,
|
||||
},
|
||||
has_skill: {
|
||||
type: 'has_skill',
|
||||
domain: ['developer'],
|
||||
range: ['skill'],
|
||||
symmetric: false,
|
||||
reflexiveAllowed: false,
|
||||
},
|
||||
collaborated_with: {
|
||||
type: 'collaborated_with',
|
||||
domain: ['developer'],
|
||||
range: ['developer'],
|
||||
symmetric: true,
|
||||
reflexiveAllowed: false,
|
||||
},
|
||||
};
|
||||
|
||||
export interface NodeRef {
|
||||
readonly id: string;
|
||||
readonly type: TalentNodeType;
|
||||
}
|
||||
|
||||
export interface EdgeProvenance {
|
||||
readonly source: EvidenceSource;
|
||||
readonly observedAt: Date;
|
||||
/** Confidence in (0, 1]. Verified evidence is 1; weaker signals score lower. */
|
||||
readonly confidence: number;
|
||||
readonly sourceUrl: string | null;
|
||||
}
|
||||
|
||||
/** An accepted, well-typed edge. `key` is its canonical dedup identity. */
|
||||
export interface TalentEdge {
|
||||
readonly type: TalentEdgeType;
|
||||
readonly from: NodeRef;
|
||||
readonly to: NodeRef;
|
||||
readonly provenance: EdgeProvenance;
|
||||
readonly key: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Untrusted edge input, exactly as it might arrive from an extractor, a GitHub
|
||||
* sync, or an LLM. Every field is loosely typed on purpose — validation is what
|
||||
* narrows it. Never trust external data.
|
||||
*/
|
||||
export interface TalentEdgeInput {
|
||||
readonly type: string;
|
||||
readonly from: { readonly id: string; readonly type: string };
|
||||
readonly to: { readonly id: string; readonly type: string };
|
||||
readonly provenance: {
|
||||
readonly source: string;
|
||||
readonly observedAt: Date | string | number;
|
||||
readonly confidence: number;
|
||||
readonly sourceUrl?: string | null;
|
||||
};
|
||||
}
|
||||
|
||||
export type EdgeRejectionCode =
|
||||
| 'unknown_edge_type'
|
||||
| 'missing_from_id'
|
||||
| 'missing_to_id'
|
||||
| 'unknown_from_type'
|
||||
| 'unknown_to_type'
|
||||
| 'domain_violation'
|
||||
| 'range_violation'
|
||||
| 'self_reference'
|
||||
| 'unknown_source'
|
||||
| 'invalid_confidence'
|
||||
| 'invalid_observed_at';
|
||||
|
||||
export interface EdgeRejection {
|
||||
readonly code: EdgeRejectionCode;
|
||||
readonly message: string;
|
||||
}
|
||||
|
||||
export type EdgeValidation =
|
||||
| { readonly valid: true; readonly edge: TalentEdge }
|
||||
| { readonly valid: false; readonly rejections: readonly EdgeRejection[] };
|
||||
|
||||
export interface EdgeBatchResult {
|
||||
readonly accepted: readonly TalentEdge[];
|
||||
readonly rejected: readonly { readonly input: TalentEdgeInput; readonly rejections: readonly EdgeRejection[] }[];
|
||||
}
|
||||
|
||||
const NODE_TYPE_SET: ReadonlySet<string> = new Set(TALENT_NODE_TYPES);
|
||||
const SOURCE_SET: ReadonlySet<string> = new Set(EVIDENCE_SOURCES);
|
||||
|
||||
function isTalentEdgeType(value: string): value is TalentEdgeType {
|
||||
return Object.prototype.hasOwnProperty.call(TALENT_ONTOLOGY, value);
|
||||
}
|
||||
|
||||
function coerceDate(value: Date | string | number): Date | null {
|
||||
const date = value instanceof Date ? value : new Date(value);
|
||||
return Number.isNaN(date.getTime()) ? null : date;
|
||||
}
|
||||
|
||||
/**
|
||||
* Canonical identity of an edge. For symmetric edge types the two endpoints are
|
||||
* sorted so that A—B and B—A share one key; for directed edges the order is kept.
|
||||
*/
|
||||
export function edgeKey(type: TalentEdgeType, from: NodeRef, to: NodeRef): string {
|
||||
const left = `${from.type}:${from.id}`;
|
||||
const right = `${to.type}:${to.id}`;
|
||||
const [a, b] = TALENT_ONTOLOGY[type].symmetric && right < left ? [right, left] : [left, right];
|
||||
return `${type}|${a}|${b}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate a single untrusted edge against the ontology. Returns the normalized,
|
||||
* accepted edge, or ALL the reasons it was rejected (validation is comprehensive
|
||||
* rather than fail-fast so callers can surface every problem at once).
|
||||
*/
|
||||
export function validateEdge(input: TalentEdgeInput): EdgeValidation {
|
||||
const rejections: EdgeRejection[] = [];
|
||||
|
||||
const type = typeof input.type === 'string' ? input.type.trim() : '';
|
||||
const fromId = typeof input.from?.id === 'string' ? input.from.id.trim() : '';
|
||||
const toId = typeof input.to?.id === 'string' ? input.to.id.trim() : '';
|
||||
const fromType = typeof input.from?.type === 'string' ? input.from.type.trim() : '';
|
||||
const toType = typeof input.to?.type === 'string' ? input.to.type.trim() : '';
|
||||
|
||||
if (!isTalentEdgeType(type)) {
|
||||
rejections.push({ code: 'unknown_edge_type', message: `Unknown edge type "${input.type}"` });
|
||||
}
|
||||
if (!fromId) rejections.push({ code: 'missing_from_id', message: 'Edge is missing a source node id' });
|
||||
if (!toId) rejections.push({ code: 'missing_to_id', message: 'Edge is missing a target node id' });
|
||||
if (!NODE_TYPE_SET.has(fromType)) {
|
||||
rejections.push({ code: 'unknown_from_type', message: `Unknown source node type "${fromType}"` });
|
||||
}
|
||||
if (!NODE_TYPE_SET.has(toType)) {
|
||||
rejections.push({ code: 'unknown_to_type', message: `Unknown target node type "${toType}"` });
|
||||
}
|
||||
|
||||
// Domain/range only make sense once the edge type is known.
|
||||
if (isTalentEdgeType(type)) {
|
||||
const def = TALENT_ONTOLOGY[type];
|
||||
if (NODE_TYPE_SET.has(fromType) && !def.domain.includes(fromType as TalentNodeType)) {
|
||||
rejections.push({
|
||||
code: 'domain_violation',
|
||||
message: `${type} requires a source of type [${def.domain.join(', ')}], got "${fromType}"`,
|
||||
});
|
||||
}
|
||||
if (NODE_TYPE_SET.has(toType) && !def.range.includes(toType as TalentNodeType)) {
|
||||
rejections.push({
|
||||
code: 'range_violation',
|
||||
message: `${type} requires a target of type [${def.range.join(', ')}], got "${toType}"`,
|
||||
});
|
||||
}
|
||||
if (!def.reflexiveAllowed && fromId && toId && fromType === toType && fromId === toId) {
|
||||
rejections.push({
|
||||
code: 'self_reference',
|
||||
message: `${type} cannot connect a node to itself (${fromType}:${fromId})`,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const source = typeof input.provenance?.source === 'string' ? input.provenance.source.trim() : '';
|
||||
if (!SOURCE_SET.has(source)) {
|
||||
rejections.push({ code: 'unknown_source', message: `Unknown provenance source "${source}"` });
|
||||
}
|
||||
const confidence = input.provenance?.confidence;
|
||||
if (typeof confidence !== 'number' || !Number.isFinite(confidence) || confidence <= 0 || confidence > 1) {
|
||||
rejections.push({ code: 'invalid_confidence', message: 'Provenance confidence must be a number in (0, 1]' });
|
||||
}
|
||||
const observedAt = input.provenance?.observedAt === undefined ? null : coerceDate(input.provenance.observedAt);
|
||||
if (!observedAt) {
|
||||
rejections.push({ code: 'invalid_observed_at', message: 'Provenance observedAt must be a valid date' });
|
||||
}
|
||||
|
||||
if (rejections.length > 0) return { valid: false, rejections };
|
||||
|
||||
const edgeType = type as TalentEdgeType;
|
||||
const from: NodeRef = { id: fromId, type: fromType as TalentNodeType };
|
||||
const to: NodeRef = { id: toId, type: toType as TalentNodeType };
|
||||
const provenance: EdgeProvenance = {
|
||||
source: source as EvidenceSource,
|
||||
observedAt: observedAt as Date,
|
||||
confidence: confidence as number,
|
||||
sourceUrl: input.provenance.sourceUrl ?? null,
|
||||
};
|
||||
|
||||
return {
|
||||
valid: true,
|
||||
edge: { type: edgeType, from, to, provenance, key: edgeKey(edgeType, from, to) },
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate a batch of untrusted edges, partitioning into accepted and rejected.
|
||||
* Accepted edges are de-duplicated by canonical `key` (first writer wins); when a
|
||||
* duplicate carries higher confidence the stronger provenance is kept.
|
||||
*
|
||||
* This is the "single validation step that removes hallucinated structure": feed
|
||||
* it raw extraction output, persist only `accepted`, and inspect `rejected` to
|
||||
* see exactly which type-incompatible triples were dropped and why.
|
||||
*/
|
||||
export function validateEdges(inputs: readonly TalentEdgeInput[]): EdgeBatchResult {
|
||||
const acceptedByKey = new Map<string, TalentEdge>();
|
||||
const rejected: EdgeBatchResult['rejected'] = [];
|
||||
|
||||
for (const input of inputs) {
|
||||
const result = validateEdge(input);
|
||||
if (!result.valid) {
|
||||
(rejected as { input: TalentEdgeInput; rejections: readonly EdgeRejection[] }[]).push({
|
||||
input,
|
||||
rejections: result.rejections,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
const existing = acceptedByKey.get(result.edge.key);
|
||||
if (!existing || result.edge.provenance.confidence > existing.provenance.confidence) {
|
||||
acceptedByKey.set(result.edge.key, result.edge);
|
||||
}
|
||||
}
|
||||
|
||||
return { accepted: Array.from(acceptedByKey.values()), rejected };
|
||||
}
|
||||
@ -1,212 +0,0 @@
|
||||
/**
|
||||
* Talent GraphRAG serving layer — grounded "why does this developer match?" query.
|
||||
*
|
||||
* This is the top of the GraphRAG vertical slice. It composes the pieces that
|
||||
* were each built to be pure and testable:
|
||||
* load view → buildTalentSubgraph (retrieve) → serializeTalentSubgraphForLLM
|
||||
* → ask the LLM under a grounding contract → enforce grounding on the reply.
|
||||
*
|
||||
* Grounding is enforced on OUR side, not trusted from the model: the LLM is asked
|
||||
* to cite edges by their canonical key, and we intersect its citations with the
|
||||
* keys that actually exist in the retrieved subgraph. Any cited key that is not
|
||||
* in the subgraph is a hallucinated reference and is dropped; the returned
|
||||
* `evidence` therefore only ever references facts that were truly retrieved.
|
||||
*
|
||||
* The LLM call is injected via `deps.ask` so the retrieval + serialization +
|
||||
* grounding logic is fully unit-testable without a live API. `deps.loadView` is
|
||||
* likewise injectable; a default wires it to the existing `getTalentGraph`
|
||||
* dossier assembler, keeping the seam while reusing the read path.
|
||||
*/
|
||||
import logger from '../utils/logger';
|
||||
import { getTalentGraph } from './talentGraphService';
|
||||
import type { TalentGraphView } from './talentGraphEdges';
|
||||
import type {
|
||||
EvidenceSource,
|
||||
NodeRef,
|
||||
TalentEdge,
|
||||
TalentEdgeType,
|
||||
} from './talentGraphOntology';
|
||||
import {
|
||||
buildTalentSubgraph,
|
||||
type TalentSubgraph,
|
||||
} from './talentSubgraphRetrieval';
|
||||
import { serializeTalentSubgraphForLLM } from './talentSubgraphSerializer';
|
||||
import {
|
||||
buildRagPrompt,
|
||||
parseRagResponse,
|
||||
type RagAsk,
|
||||
} from './talentGraphRagPrompt';
|
||||
|
||||
const DEFAULT_DEPTH = 2;
|
||||
const MAX_QUERY_LENGTH = 2000;
|
||||
|
||||
/** A single cited fact returned to the caller — a projection of a subgraph edge. */
|
||||
export interface EdgeReference {
|
||||
readonly key: string;
|
||||
readonly type: TalentEdgeType;
|
||||
readonly from: NodeRef;
|
||||
readonly to: NodeRef;
|
||||
readonly source: EvidenceSource;
|
||||
readonly confidence: number;
|
||||
readonly observedAt: string;
|
||||
readonly sourceUrl: string | null;
|
||||
}
|
||||
|
||||
/** The grounded answer plus the evidence it is allowed to stand on. */
|
||||
export interface ExplainTalentMatchResult {
|
||||
readonly developerId: string;
|
||||
readonly query: string;
|
||||
readonly answer: string;
|
||||
readonly evidence: readonly EdgeReference[];
|
||||
readonly retrieval: {
|
||||
readonly depth: number;
|
||||
readonly nodeCount: number;
|
||||
readonly edgeCount: number;
|
||||
};
|
||||
/**
|
||||
* Keys the model cited that were NOT in the subgraph. Always empty in a
|
||||
* well-behaved run; surfaced (not hidden) so grounding violations are
|
||||
* observable rather than silently absorbed.
|
||||
*/
|
||||
readonly droppedCitations: readonly string[];
|
||||
}
|
||||
|
||||
/** Injectable dependencies for {@link explainTalentMatch}. */
|
||||
export interface ExplainTalentMatchDeps {
|
||||
/** The LLM seam. Required — there is no implicit network call. */
|
||||
readonly ask: RagAsk;
|
||||
/** How to obtain the assembled view. Defaults to {@link getTalentGraph}. */
|
||||
readonly loadView?: (developerId: string) => Promise<TalentGraphView | null>;
|
||||
/** k-hop retrieval depth. Defaults to {@link DEFAULT_DEPTH}. */
|
||||
readonly depth?: number;
|
||||
}
|
||||
|
||||
/** Default view loader: reuse the existing dossier assembler on the read path. */
|
||||
async function defaultLoadView(developerId: string): Promise<TalentGraphView | null> {
|
||||
return (await getTalentGraph(developerId)) as TalentGraphView | null;
|
||||
}
|
||||
|
||||
function toEdgeReference(edge: TalentEdge): EdgeReference {
|
||||
return {
|
||||
key: edge.key,
|
||||
type: edge.type,
|
||||
from: edge.from,
|
||||
to: edge.to,
|
||||
source: edge.provenance.source,
|
||||
confidence: edge.provenance.confidence,
|
||||
observedAt: edge.provenance.observedAt.toISOString(),
|
||||
sourceUrl: edge.provenance.sourceUrl,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Enforce grounding: partition the model's cited keys into those present in the
|
||||
* subgraph (kept as evidence, de-duplicated, in subgraph order) and those that
|
||||
* are not (dropped as hallucinations). This is the guardrail that guarantees the
|
||||
* returned evidence only references retrieved facts.
|
||||
*/
|
||||
function groundCitations(
|
||||
subgraph: TalentSubgraph,
|
||||
citedKeys: readonly string[],
|
||||
): { evidence: EdgeReference[]; dropped: string[] } {
|
||||
const edgesByKey = new Map(subgraph.edges.map((edge) => [edge.key, edge]));
|
||||
const seen = new Set<string>();
|
||||
const dropped: string[] = [];
|
||||
|
||||
for (const key of citedKeys) {
|
||||
if (!edgesByKey.has(key)) {
|
||||
if (!dropped.includes(key)) dropped.push(key);
|
||||
}
|
||||
}
|
||||
|
||||
// Preserve deterministic subgraph edge order for cited, in-subgraph keys.
|
||||
const citedSet = new Set(citedKeys);
|
||||
const evidence: EdgeReference[] = [];
|
||||
for (const edge of subgraph.edges) {
|
||||
if (citedSet.has(edge.key) && !seen.has(edge.key)) {
|
||||
seen.add(edge.key);
|
||||
evidence.push(toEdgeReference(edge));
|
||||
}
|
||||
}
|
||||
|
||||
return { evidence, dropped };
|
||||
}
|
||||
|
||||
function normalizeQuery(query: string): string {
|
||||
const cleaned = typeof query === 'string' ? query.trim() : '';
|
||||
if (!cleaned) throw new Error('A non-empty query is required to explain a talent match');
|
||||
if (cleaned.length > MAX_QUERY_LENGTH) {
|
||||
throw new Error(`Query must be at most ${MAX_QUERY_LENGTH} characters`);
|
||||
}
|
||||
return cleaned;
|
||||
}
|
||||
|
||||
/**
|
||||
* Explain, grounded in the retrieved subgraph, why/how a developer matches a
|
||||
* query. Retrieves the k-hop neighborhood, serializes it, asks the injected LLM
|
||||
* under the grounding contract, then enforces that the returned evidence only
|
||||
* references retrieved edges.
|
||||
*
|
||||
* @throws if inputs are invalid, the developer has no assembled view, or the LLM
|
||||
* reply cannot be parsed. Errors are explicit — never silently swallowed.
|
||||
*/
|
||||
export async function explainTalentMatch(
|
||||
rootDeveloperId: string,
|
||||
query: string,
|
||||
deps: ExplainTalentMatchDeps,
|
||||
): Promise<ExplainTalentMatchResult> {
|
||||
const developerId = typeof rootDeveloperId === 'string' ? rootDeveloperId.trim() : '';
|
||||
if (!developerId) throw new Error('explainTalentMatch requires a non-empty rootDeveloperId');
|
||||
if (!deps || typeof deps.ask !== 'function') {
|
||||
throw new Error('explainTalentMatch requires deps.ask (the injectable LLM call)');
|
||||
}
|
||||
const cleanedQuery = normalizeQuery(query);
|
||||
const depth = deps.depth ?? DEFAULT_DEPTH;
|
||||
const loadView = deps.loadView ?? defaultLoadView;
|
||||
|
||||
const view = await loadView(developerId);
|
||||
if (!view) throw new Error(`No talent graph view found for developer "${developerId}"`);
|
||||
|
||||
const subgraph = buildTalentSubgraph(view, developerId, depth);
|
||||
const context = serializeTalentSubgraphForLLM(subgraph);
|
||||
const prompt = buildRagPrompt(cleanedQuery, context);
|
||||
|
||||
const raw = await deps.ask(prompt);
|
||||
const parsed = parseRagResponse(raw);
|
||||
const { evidence, dropped } = groundCitations(subgraph, parsed.citedEdgeKeys);
|
||||
|
||||
if (dropped.length > 0) {
|
||||
logger.warn('talent-graphrag dropped hallucinated citations not present in the subgraph', {
|
||||
event: 'talent_graph.rag.hallucinated_citation',
|
||||
developerId,
|
||||
droppedCount: dropped.length,
|
||||
dropped,
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
developerId,
|
||||
query: cleanedQuery,
|
||||
answer: parsed.answer,
|
||||
evidence,
|
||||
retrieval: {
|
||||
depth: subgraph.depth,
|
||||
nodeCount: subgraph.nodes.length,
|
||||
edgeCount: subgraph.edges.length,
|
||||
},
|
||||
droppedCitations: dropped,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Default LLM seam. There is no LLM client wired into gitgram-ai yet, so this
|
||||
* default fails loudly rather than pretending to answer — production wiring
|
||||
* should replace it with a real client (e.g. via `deps.ask`) while keeping this
|
||||
* exact signature. Kept as a named export so the controller can depend on the
|
||||
* seam and tests can substitute their own `ask`.
|
||||
*/
|
||||
export const defaultRagAsk: RagAsk = async () => {
|
||||
throw new Error(
|
||||
'No LLM client is configured for talent GraphRAG. Provide deps.ask to explainTalentMatch.',
|
||||
);
|
||||
};
|
||||
@ -1,97 +0,0 @@
|
||||
/**
|
||||
* Grounded prompt construction + response parsing for talent GraphRAG.
|
||||
*
|
||||
* This file owns the *grounding contract* between our retrieval layer and the
|
||||
* LLM: the system instruction that forbids outside knowledge, the user prompt
|
||||
* that carries the serialized subgraph and the query, and the strict parser that
|
||||
* turns the model's reply back into a typed answer + cited edge keys. Keeping the
|
||||
* contract in one small module makes the grounding rules auditable and lets the
|
||||
* parser be unit-tested without any live API.
|
||||
*/
|
||||
|
||||
/** The instruction that pins the model to the retrieved subgraph only. */
|
||||
export const GROUNDING_SYSTEM_PROMPT = [
|
||||
'You are a talent-graph analyst. You answer ONLY using the facts in the',
|
||||
'provided subgraph context. Never use outside knowledge, and never invent',
|
||||
'developers, repositories, skills, organizations, or relationships that are',
|
||||
'not present in the EDGES list.',
|
||||
'',
|
||||
'Every claim in your answer must be supported by one or more edges, cited by',
|
||||
'their [key]. If the subgraph does not contain enough information to answer,',
|
||||
'say so plainly and cite no edges.',
|
||||
'',
|
||||
'Respond with a single JSON object and nothing else, of the exact shape:',
|
||||
'{"answer": string, "citedEdgeKeys": string[]}',
|
||||
'where each citedEdgeKeys entry is an edge [key] copied verbatim from EDGES.',
|
||||
].join('\n');
|
||||
|
||||
/** A request handed to an injected LLM. `context` is the serialized subgraph. */
|
||||
export interface RagAskRequest {
|
||||
readonly system: string;
|
||||
readonly query: string;
|
||||
readonly context: string;
|
||||
}
|
||||
|
||||
/** The injectable LLM seam: raw prompt in, raw model text out. */
|
||||
export type RagAsk = (request: RagAskRequest) => Promise<string>;
|
||||
|
||||
/** Parsed, still-untrusted model reply before grounding is enforced. */
|
||||
export interface ParsedRagResponse {
|
||||
readonly answer: string;
|
||||
readonly citedEdgeKeys: readonly string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the user-facing prompt body. The query is included verbatim but clearly
|
||||
* fenced from the context so a hostile query cannot masquerade as graph facts.
|
||||
*/
|
||||
export function buildRagPrompt(query: string, context: string): RagAskRequest {
|
||||
const cleanedQuery = typeof query === 'string' ? query.trim() : '';
|
||||
if (!cleanedQuery) throw new Error('A non-empty query is required to explain a talent match');
|
||||
return {
|
||||
system: GROUNDING_SYSTEM_PROMPT,
|
||||
query: cleanedQuery,
|
||||
context,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse a raw LLM reply into a typed response. Tolerant of a leading/trailing
|
||||
* code fence but otherwise strict: the payload must be a JSON object with a
|
||||
* string `answer` and an array of string `citedEdgeKeys`. Anything else is a
|
||||
* hard error — we never guess at a malformed model reply. Grounding (checking the
|
||||
* cited keys actually exist in the subgraph) happens in the caller.
|
||||
*/
|
||||
export function parseRagResponse(raw: string): ParsedRagResponse {
|
||||
if (typeof raw !== 'string' || raw.trim() === '') {
|
||||
throw new Error('LLM returned an empty response');
|
||||
}
|
||||
const stripped = raw
|
||||
.trim()
|
||||
.replace(/^```(?:json)?\s*/i, '')
|
||||
.replace(/\s*```$/i, '')
|
||||
.trim();
|
||||
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = JSON.parse(stripped);
|
||||
} catch {
|
||||
throw new Error('LLM response was not valid JSON');
|
||||
}
|
||||
|
||||
if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
|
||||
throw new Error('LLM response must be a JSON object');
|
||||
}
|
||||
const record = parsed as Record<string, unknown>;
|
||||
if (typeof record.answer !== 'string') {
|
||||
throw new Error('LLM response is missing a string "answer"');
|
||||
}
|
||||
if (!Array.isArray(record.citedEdgeKeys) || record.citedEdgeKeys.some((key) => typeof key !== 'string')) {
|
||||
throw new Error('LLM response "citedEdgeKeys" must be an array of strings');
|
||||
}
|
||||
|
||||
return {
|
||||
answer: record.answer.trim(),
|
||||
citedEdgeKeys: record.citedEdgeKeys as string[],
|
||||
};
|
||||
}
|
||||
@ -1,9 +1,6 @@
|
||||
import prisma from '../utils/prisma';
|
||||
import logger from '../utils/logger';
|
||||
import { normalizePublicHttpUrl } from '../utils/publicHttpUrl';
|
||||
import { canonicalizeSkill, canonicalizeSkills, expandSkillQueryTokens } from './skillTaxonomyService';
|
||||
import { deriveTalentEdges, type TalentGraphView } from './talentGraphEdges';
|
||||
import { validateEdges, type EdgeBatchResult } from './talentGraphOntology';
|
||||
import type { PrismaClient } from '@prisma/client';
|
||||
|
||||
type EvidenceLevel = 'verified' | 'linked' | 'recorded';
|
||||
@ -59,38 +56,6 @@ function projectKey(owner: string | null, name: string, fullName: string | null)
|
||||
return (fullName || (owner ? `${owner}/${name}` : name)).toLowerCase();
|
||||
}
|
||||
|
||||
/**
|
||||
* Non-breaking validation gate for the assembled talent graph.
|
||||
*
|
||||
* `getTalentGraph` assembles a read-only dossier; it does not persist edges. This
|
||||
* gate realizes the ontology guardrail on that read path: it derives typed,
|
||||
* provenanced candidate edges from the assembled view and vets them with
|
||||
* `validateEdges` (domain/range, provenance, symmetric dedup). It is WARN-ONLY —
|
||||
* it never mutates, drops, or reshapes the response. Ontology-invalid
|
||||
* ("hallucinated") structure is surfaced as a single structured warning (reason
|
||||
* codes + endpoint types) so violations are observable via logs/metrics without
|
||||
* changing any success-path output existing consumers depend on. Returns the
|
||||
* batch result so callers and tests can inspect what the gate saw.
|
||||
*/
|
||||
export function auditTalentGraphEdges(view: TalentGraphView): EdgeBatchResult {
|
||||
const result = validateEdges(deriveTalentEdges(view));
|
||||
if (result.rejected.length > 0) {
|
||||
logger.warn('talent-graph edge validation rejected ontology-invalid edges', {
|
||||
event: 'talent_graph.edge_validation.rejected',
|
||||
developerId: view.profile.id,
|
||||
acceptedCount: result.accepted.length,
|
||||
rejectedCount: result.rejected.length,
|
||||
rejections: result.rejected.map((entry) => ({
|
||||
edgeType: entry.input.type,
|
||||
fromType: entry.input.from?.type,
|
||||
toType: entry.input.to?.type,
|
||||
codes: entry.rejections.map((rejection) => rejection.code),
|
||||
})),
|
||||
});
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
export async function getTalentGraph(userId: string, options: { publicView?: boolean } = {}) {
|
||||
const [user, syncedProjects, managedRepositories] = await Promise.all([
|
||||
prisma.user.findUnique({
|
||||
@ -391,7 +356,7 @@ export async function getTalentGraph(userId: string, options: { publicView?: boo
|
||||
(a, b) => b.sharedProjects.length - a.sharedProjects.length,
|
||||
);
|
||||
|
||||
const graph = {
|
||||
return {
|
||||
profile: {
|
||||
id: user.id,
|
||||
username: user.username,
|
||||
@ -412,21 +377,6 @@ export async function getTalentGraph(userId: string, options: { publicView?: boo
|
||||
collaborators: talentCollaborators,
|
||||
generatedAt: new Date(),
|
||||
};
|
||||
|
||||
// Realize the ontology guardrail on the read path. Warn-only and defensive:
|
||||
// the gate observes ontology-invalid structure but never changes `graph`, and a
|
||||
// failure here must never break a dossier read.
|
||||
try {
|
||||
auditTalentGraphEdges(graph);
|
||||
} catch (error) {
|
||||
logger.error('talent-graph edge validation gate failed', {
|
||||
event: 'talent_graph.edge_validation.error',
|
||||
developerId: user.id,
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
});
|
||||
}
|
||||
|
||||
return graph;
|
||||
}
|
||||
|
||||
export async function findTalentMatches(requiredSkills: string[], limit = 12, db: TalentMatchDb = prisma) {
|
||||
|
||||
@ -1,177 +0,0 @@
|
||||
/**
|
||||
* k-hop subgraph retrieval for the talent GraphRAG serving layer.
|
||||
*
|
||||
* GraphRAG serves *structure*, not prose: before an LLM can ground an answer we
|
||||
* must first retrieve the bounded neighborhood of facts that are relevant to a
|
||||
* developer. This module is the retrieval half. It REUSES the existing graph
|
||||
* pipeline rather than rebuilding it:
|
||||
* assembled view → deriveTalentEdges → validateEdges → k-hop subgraph
|
||||
* so every fact that reaches the LLM has already been vetted against the
|
||||
* ontology's domain/range and carries provenance (source, confidence, observedAt).
|
||||
*
|
||||
* Two entry points:
|
||||
* - `buildSubgraphFromEdges` — the pure BFS core over an already-validated edge
|
||||
* set. Traversal is undirected (a neighborhood, not a reachability query) so a
|
||||
* developer's repos, skills, orgs and collaborators are all gathered, but never
|
||||
* beyond `depth` hops. This is the unit-testable heart of retrieval.
|
||||
* - `buildTalentSubgraph` — the view-based wrapper that runs the extract→validate
|
||||
* pipeline before delegating to the BFS core.
|
||||
*
|
||||
* Pure and dependency-light: no Prisma, no I/O, immutable output.
|
||||
*/
|
||||
import {
|
||||
deriveTalentEdges,
|
||||
type TalentGraphView,
|
||||
} from './talentGraphEdges';
|
||||
import {
|
||||
validateEdges,
|
||||
type NodeRef,
|
||||
type TalentEdge,
|
||||
type TalentNodeType,
|
||||
} from './talentGraphOntology';
|
||||
|
||||
/** A node that appears in a retrieved subgraph, tagged with its BFS distance. */
|
||||
export interface SubgraphNode {
|
||||
readonly id: string;
|
||||
readonly type: TalentNodeType;
|
||||
/** Hops from the root developer. The root itself is 0. */
|
||||
readonly distance: number;
|
||||
}
|
||||
|
||||
/** A bounded, validated neighborhood of the talent graph around one developer. */
|
||||
export interface TalentSubgraph {
|
||||
readonly root: NodeRef;
|
||||
readonly depth: number;
|
||||
readonly nodes: readonly SubgraphNode[];
|
||||
readonly edges: readonly TalentEdge[];
|
||||
}
|
||||
|
||||
const MAX_DEPTH = 6;
|
||||
|
||||
function nodeKey(type: TalentNodeType, id: string): string {
|
||||
return `${type}:${id}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate the requested traversal depth at the boundary. Retrieval must always
|
||||
* terminate, so depth is a non-negative integer capped at MAX_DEPTH. Never trust
|
||||
* a caller-supplied bound.
|
||||
*/
|
||||
function normalizeDepth(depth: number): number {
|
||||
if (typeof depth !== 'number' || !Number.isInteger(depth) || depth < 0) {
|
||||
throw new RangeError('Subgraph depth must be a non-negative integer');
|
||||
}
|
||||
return Math.min(depth, MAX_DEPTH);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve the k-hop neighborhood around `root` from a set of already-validated
|
||||
* edges. Undirected BFS assigns each reachable node its shortest hop distance;
|
||||
* nodes farther than `depth` are excluded, and an edge is kept only when BOTH of
|
||||
* its endpoints made it into the node set. This is what stops "wrong hops":
|
||||
* facts hanging off a node one step beyond the frontier never enter the context.
|
||||
*
|
||||
* The root is always present (distance 0) even when it has no edges, so callers
|
||||
* always get a well-formed subgraph. Termination is guaranteed: each node is
|
||||
* enqueued at most once.
|
||||
*/
|
||||
export function buildSubgraphFromEdges(
|
||||
edges: readonly TalentEdge[],
|
||||
root: NodeRef,
|
||||
depth: number,
|
||||
): TalentSubgraph {
|
||||
if (!root || typeof root.id !== 'string' || root.id.trim() === '') {
|
||||
throw new Error('Subgraph retrieval requires a root node with a non-empty id');
|
||||
}
|
||||
const maxDepth = normalizeDepth(depth);
|
||||
const rootRef: NodeRef = { id: root.id, type: root.type };
|
||||
|
||||
// Adjacency list over an undirected view of the (directed) edge set.
|
||||
const adjacency = new Map<string, { neighbor: NodeRef }[]>();
|
||||
const addAdjacency = (from: NodeRef, to: NodeRef) => {
|
||||
const key = nodeKey(from.type, from.id);
|
||||
const list = adjacency.get(key) ?? [];
|
||||
list.push({ neighbor: to });
|
||||
adjacency.set(key, list);
|
||||
};
|
||||
for (const edge of edges) {
|
||||
addAdjacency(edge.from, edge.to);
|
||||
addAdjacency(edge.to, edge.from);
|
||||
}
|
||||
|
||||
// BFS from the root, recording the shortest distance to every node.
|
||||
const distances = new Map<string, SubgraphNode>();
|
||||
const rootKey = nodeKey(rootRef.type, rootRef.id);
|
||||
distances.set(rootKey, { id: rootRef.id, type: rootRef.type, distance: 0 });
|
||||
let frontier: NodeRef[] = [rootRef];
|
||||
|
||||
for (let hop = 1; hop <= maxDepth && frontier.length > 0; hop += 1) {
|
||||
const next: NodeRef[] = [];
|
||||
for (const node of frontier) {
|
||||
for (const { neighbor } of adjacency.get(nodeKey(node.type, node.id)) ?? []) {
|
||||
const key = nodeKey(neighbor.type, neighbor.id);
|
||||
if (distances.has(key)) continue;
|
||||
distances.set(key, { id: neighbor.id, type: neighbor.type, distance: hop });
|
||||
next.push(neighbor);
|
||||
}
|
||||
}
|
||||
frontier = next;
|
||||
}
|
||||
|
||||
// Keep only edges whose BOTH endpoints are inside the retrieved node set.
|
||||
const included = (node: NodeRef) => distances.has(nodeKey(node.type, node.id));
|
||||
const keptEdges = edges.filter((edge) => included(edge.from) && included(edge.to));
|
||||
|
||||
const nodes = Array.from(distances.values());
|
||||
return {
|
||||
root: rootRef,
|
||||
depth: maxDepth,
|
||||
nodes: sortNodes(nodes),
|
||||
edges: sortEdges(keptEdges),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* View-based retrieval entry point. Runs the existing extract→validate pipeline
|
||||
* (`deriveTalentEdges` + `validateEdges`) so only ontology-valid, provenance-
|
||||
* carrying edges are traversed, then returns the k-hop subgraph around the given
|
||||
* developer. `rootDeveloperId` is validated against the view's own profile to keep
|
||||
* the seam honest — you can only build a subgraph for the developer the view
|
||||
* describes.
|
||||
*/
|
||||
export function buildTalentSubgraph(
|
||||
view: TalentGraphView,
|
||||
rootDeveloperId: string,
|
||||
depth: number,
|
||||
): TalentSubgraph {
|
||||
if (!view || typeof view !== 'object') {
|
||||
throw new Error('buildTalentSubgraph requires an assembled talent graph view');
|
||||
}
|
||||
const developerId = typeof rootDeveloperId === 'string' ? rootDeveloperId.trim() : '';
|
||||
if (!developerId) {
|
||||
throw new Error('buildTalentSubgraph requires a non-empty rootDeveloperId');
|
||||
}
|
||||
if (view.profile?.id !== developerId) {
|
||||
throw new Error(
|
||||
`rootDeveloperId "${developerId}" does not match the view profile "${view.profile?.id ?? ''}"`,
|
||||
);
|
||||
}
|
||||
|
||||
const { accepted } = validateEdges(deriveTalentEdges(view));
|
||||
return buildSubgraphFromEdges(accepted, { id: developerId, type: 'developer' }, depth);
|
||||
}
|
||||
|
||||
/** Deterministic node ordering: by distance, then type, then id. */
|
||||
function sortNodes(nodes: readonly SubgraphNode[]): SubgraphNode[] {
|
||||
return [...nodes].sort(
|
||||
(a, b) =>
|
||||
a.distance - b.distance ||
|
||||
a.type.localeCompare(b.type) ||
|
||||
a.id.localeCompare(b.id),
|
||||
);
|
||||
}
|
||||
|
||||
/** Deterministic edge ordering by canonical key. */
|
||||
function sortEdges(edges: readonly TalentEdge[]): TalentEdge[] {
|
||||
return [...edges].sort((a, b) => a.key.localeCompare(b.key));
|
||||
}
|
||||
@ -1,101 +0,0 @@
|
||||
/**
|
||||
* Deterministic serialization of a retrieved talent subgraph into LLM-ready
|
||||
* context.
|
||||
*
|
||||
* The grounding contract of GraphRAG is only as strong as the context window is
|
||||
* faithful: the LLM may answer ONLY from what we hand it, so the serialized block
|
||||
* must (a) be deterministic — identical subgraph in, byte-identical text out, so
|
||||
* prompts are cacheable and tests are stable — and (b) expose the citation handle
|
||||
* (each edge's canonical `key`) the model is required to cite, alongside the
|
||||
* provenance (source, confidence, observedAt) that makes each fact auditable.
|
||||
*
|
||||
* Nodes are grouped by ontology type in a fixed order; edges are rendered as
|
||||
* subject–predicate–object triples with their provenance and citation key. No
|
||||
* prose, no I/O — pure formatting.
|
||||
*/
|
||||
import {
|
||||
TALENT_NODE_TYPES,
|
||||
type TalentEdge,
|
||||
type TalentNodeType,
|
||||
} from './talentGraphOntology';
|
||||
import type { SubgraphNode, TalentSubgraph } from './talentSubgraphRetrieval';
|
||||
|
||||
/** Human-facing labels for each node type, kept stable for prompt determinism. */
|
||||
const NODE_TYPE_LABELS: Readonly<Record<TalentNodeType, string>> = {
|
||||
developer: 'Developers',
|
||||
repo: 'Repositories',
|
||||
org: 'Organizations',
|
||||
skill: 'Skills',
|
||||
contribution: 'Contributions',
|
||||
};
|
||||
|
||||
/** Verb phrasing for each edge type so triples read naturally but stay stable. */
|
||||
const EDGE_TYPE_PHRASES: Readonly<Record<string, string>> = {
|
||||
contributed_to: 'contributed to',
|
||||
member_of: 'is a member of',
|
||||
has_skill: 'has skill',
|
||||
collaborated_with: 'collaborated with',
|
||||
};
|
||||
|
||||
function formatConfidence(value: number): string {
|
||||
return value.toFixed(2);
|
||||
}
|
||||
|
||||
function formatNodeLine(node: SubgraphNode): string {
|
||||
return ` - ${node.type}:${node.id} (depth ${node.distance})`;
|
||||
}
|
||||
|
||||
function formatEdgeLine(edge: TalentEdge): string {
|
||||
const phrase = EDGE_TYPE_PHRASES[edge.type] ?? edge.type;
|
||||
const provenance =
|
||||
`source=${edge.provenance.source}` +
|
||||
`, confidence=${formatConfidence(edge.provenance.confidence)}` +
|
||||
`, observedAt=${edge.provenance.observedAt.toISOString()}` +
|
||||
`, sourceUrl=${edge.provenance.sourceUrl ?? 'none'}`;
|
||||
return (
|
||||
` - [${edge.key}] ${edge.from.type}:${edge.from.id} ` +
|
||||
`${phrase} ${edge.to.type}:${edge.to.id} {${provenance}}`
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Render the subgraph as a deterministic text block for the LLM context window.
|
||||
* Structure:
|
||||
* ROOT: <type>:<id> (depth <k>)
|
||||
* NODES
|
||||
* <grouped by type, sorted>
|
||||
* EDGES (facts — cite by [key])
|
||||
* <sorted by key, one triple per line with provenance>
|
||||
*
|
||||
* The input is assumed already ordered by the retrieval layer; grouping here is a
|
||||
* stable re-projection, so the output is a pure function of the subgraph.
|
||||
*/
|
||||
export function serializeTalentSubgraphForLLM(subgraph: TalentSubgraph): string {
|
||||
if (!subgraph || typeof subgraph !== 'object') {
|
||||
throw new Error('serializeTalentSubgraphForLLM requires a subgraph');
|
||||
}
|
||||
|
||||
const lines: string[] = [];
|
||||
lines.push(`ROOT: ${subgraph.root.type}:${subgraph.root.id} (depth ${subgraph.depth})`);
|
||||
|
||||
lines.push('NODES');
|
||||
if (subgraph.nodes.length === 0) {
|
||||
lines.push(' (none)');
|
||||
} else {
|
||||
for (const type of TALENT_NODE_TYPES) {
|
||||
const ofType = subgraph.nodes.filter((node) => node.type === type);
|
||||
if (ofType.length === 0) continue;
|
||||
lines.push(` ${NODE_TYPE_LABELS[type]}:`);
|
||||
for (const node of ofType) lines.push(` ${formatNodeLine(node)}`);
|
||||
}
|
||||
}
|
||||
|
||||
lines.push('EDGES (facts — cite by [key]):');
|
||||
if (subgraph.edges.length === 0) {
|
||||
lines.push(' (none)');
|
||||
} else {
|
||||
for (const edge of subgraph.edges) lines.push(formatEdgeLine(edge));
|
||||
}
|
||||
|
||||
return lines.join('\n');
|
||||
}
|
||||
@ -871,10 +871,8 @@ describe('DELETE /api/v1/auth/delete-account', () => {
|
||||
expect(res.status).toBe(401);
|
||||
});
|
||||
|
||||
it('should reject when password body field is missing for a password account', async () => {
|
||||
it('should reject when password body field is missing', async () => {
|
||||
const token = generateTestAccessToken(TEST_USER_ID);
|
||||
const user = prismaUserWithPassword(PASSWORD, { id: TEST_USER_ID });
|
||||
mockPrisma.user.findUnique.mockResolvedValue(user);
|
||||
|
||||
const res = await request(app)
|
||||
.delete('/api/v1/auth/delete-account')
|
||||
@ -882,40 +880,6 @@ describe('DELETE /api/v1/auth/delete-account', () => {
|
||||
.send({});
|
||||
|
||||
expect(res.status).toBe(400);
|
||||
expect(mockPrisma.$transaction).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should delete an OAuth (passwordless) account without a password', async () => {
|
||||
const token = generateTestAccessToken(TEST_USER_ID);
|
||||
mockPrisma.user.findUnique.mockResolvedValue(
|
||||
testFixtures.createPrismaUser({ id: TEST_USER_ID, password: null }),
|
||||
);
|
||||
mockPrisma.$transaction.mockResolvedValue([{}, {}, {}]);
|
||||
|
||||
const res = await request(app)
|
||||
.delete('/api/v1/auth/delete-account')
|
||||
.set('Authorization', authHeader(token))
|
||||
.send({});
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.message).toMatch(/deleted/i);
|
||||
expect(mockPrisma.$transaction).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should cascade-delete sessions, linked accounts and the user', async () => {
|
||||
const token = generateTestAccessToken(TEST_USER_ID);
|
||||
const user = prismaUserWithPassword(PASSWORD, { id: TEST_USER_ID });
|
||||
mockPrisma.user.findUnique.mockResolvedValue(user);
|
||||
mockPrisma.$transaction.mockResolvedValue([{}, {}, {}]);
|
||||
|
||||
await request(app)
|
||||
.delete('/api/v1/auth/delete-account')
|
||||
.set('Authorization', authHeader(token))
|
||||
.send({ password: PASSWORD });
|
||||
|
||||
expect(mockPrisma.session.deleteMany).toHaveBeenCalledWith({ where: { userId: TEST_USER_ID } });
|
||||
expect(mockPrisma.account.deleteMany).toHaveBeenCalledWith({ where: { userId: TEST_USER_ID } });
|
||||
expect(mockPrisma.user.delete).toHaveBeenCalledWith({ where: { id: TEST_USER_ID } });
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@ -1,210 +0,0 @@
|
||||
import { GitHubEventType } from '@prisma/client';
|
||||
import {
|
||||
mapContributionsToActivities,
|
||||
harvestContributionEvidence,
|
||||
type ContributionsCollection,
|
||||
type ContributionsResponse,
|
||||
type HarvestDb,
|
||||
} from '../src/services/githubContributionsService';
|
||||
|
||||
/**
|
||||
* Unit tests for the talent-graph contribution-evidence backfill. These lock in
|
||||
* the properties the evidence layer depends on:
|
||||
* - only contributions to *managed* repositories become evidence;
|
||||
* - every row is attributed to the user's GitHub identity (actorLogin);
|
||||
* - re-runs dedupe via a deterministic eventId;
|
||||
* - the harvest is a safe no-op without a token / username / managed repos.
|
||||
*/
|
||||
|
||||
const repoIdByFullName = new Map<string, string>([
|
||||
['octocat/hello-world', 'repo-1'],
|
||||
['octocat/spoon-knife', 'repo-2'],
|
||||
]);
|
||||
|
||||
const ctx = { githubUsername: 'octocat', repoIdByFullName } as const;
|
||||
|
||||
function sampleCollection(): ContributionsCollection {
|
||||
return {
|
||||
commitContributionsByRepository: [
|
||||
{
|
||||
repository: { nameWithOwner: 'octocat/Hello-World', url: 'https://github.com/octocat/Hello-World' },
|
||||
contributions: { nodes: [{ occurredAt: '2026-09-01T00:00:00Z', commitCount: 3 }] },
|
||||
},
|
||||
// Not a managed repository — must be skipped.
|
||||
{
|
||||
repository: { nameWithOwner: 'stranger/repo', url: 'https://github.com/stranger/repo' },
|
||||
contributions: { nodes: [{ occurredAt: '2026-09-02T00:00:00Z', commitCount: 9 }] },
|
||||
},
|
||||
],
|
||||
pullRequestContributionsByRepository: [
|
||||
{
|
||||
repository: { nameWithOwner: 'octocat/spoon-knife', url: 'https://github.com/octocat/spoon-knife' },
|
||||
contributions: {
|
||||
nodes: [
|
||||
{ pullRequest: { id: 'PR_1', number: 42, title: 'Add feature', url: 'https://github.com/octocat/spoon-knife/pull/42', createdAt: '2026-08-20T00:00:00Z', merged: true } },
|
||||
{ pullRequest: null },
|
||||
],
|
||||
},
|
||||
},
|
||||
],
|
||||
pullRequestReviewContributionsByRepository: [
|
||||
{
|
||||
repository: { nameWithOwner: 'octocat/hello-world', url: 'https://github.com/octocat/hello-world' },
|
||||
contributions: {
|
||||
nodes: [
|
||||
{ occurredAt: '2026-08-21T00:00:00Z', pullRequestReview: { id: 'PRR_1', url: 'https://github.com/octocat/hello-world/pull/7#review', submittedAt: '2026-08-21T00:00:00Z' }, pullRequest: { number: 7, title: 'Fix bug', url: 'https://github.com/octocat/hello-world/pull/7' } },
|
||||
],
|
||||
},
|
||||
},
|
||||
],
|
||||
issueContributionsByRepository: [
|
||||
{
|
||||
repository: { nameWithOwner: 'octocat/hello-world', url: 'https://github.com/octocat/hello-world' },
|
||||
contributions: {
|
||||
nodes: [
|
||||
{ issue: { id: 'I_1', number: 5, title: 'Crash on load', url: 'https://github.com/octocat/hello-world/issues/5', createdAt: '2026-08-15T00:00:00Z' } },
|
||||
],
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
describe('mapContributionsToActivities', () => {
|
||||
it('maps commit, PR, review, and issue contributions for managed repositories', () => {
|
||||
const rows = mapContributionsToActivities(sampleCollection(), ctx);
|
||||
|
||||
const byType = rows.reduce<Record<string, number>>((acc, row) => {
|
||||
acc[row.eventType] = (acc[row.eventType] ?? 0) + 1;
|
||||
return acc;
|
||||
}, {});
|
||||
// 1 commit-day (managed) + 1 PR + 1 review (both PULL_REQUEST) + 1 issue.
|
||||
expect(byType[GitHubEventType.PUSH]).toBe(1);
|
||||
expect(byType[GitHubEventType.PULL_REQUEST]).toBe(2);
|
||||
expect(byType[GitHubEventType.ISSUES]).toBe(1);
|
||||
});
|
||||
|
||||
it('skips contributions to repositories the user does not manage', () => {
|
||||
const rows = mapContributionsToActivities(sampleCollection(), ctx);
|
||||
// The "stranger/repo" commit contribution (9 commits) must not appear.
|
||||
expect(rows.some((row) => row.repositoryId !== 'repo-1' && row.repositoryId !== 'repo-2')).toBe(false);
|
||||
expect(rows.find((row) => row.eventType === GitHubEventType.PUSH)?.repositoryId).toBe('repo-1');
|
||||
});
|
||||
|
||||
it('attributes every row to the user GitHub identity (evidence query filter)', () => {
|
||||
const rows = mapContributionsToActivities(sampleCollection(), ctx);
|
||||
expect(rows.length).toBeGreaterThan(0);
|
||||
expect(rows.every((row) => row.actorLogin === 'octocat')).toBe(true);
|
||||
});
|
||||
|
||||
it('produces deterministic eventIds and dedupes repeated contribution nodes', () => {
|
||||
const collection = sampleCollection();
|
||||
// Duplicate the same PR node — the API can surface the same contribution twice.
|
||||
collection.pullRequestContributionsByRepository![0].contributions.nodes.push({
|
||||
pullRequest: { id: 'PR_1', number: 42, title: 'Add feature', url: 'https://x', createdAt: '2026-08-20T00:00:00Z', merged: true },
|
||||
});
|
||||
|
||||
const rows = mapContributionsToActivities(collection, ctx);
|
||||
const prRows = rows.filter((row) => row.eventId === 'contrib:pr:PR_1');
|
||||
expect(prRows).toHaveLength(1);
|
||||
expect(prRows[0].action).toBe('merged');
|
||||
|
||||
const ids = rows.map((row) => row.eventId);
|
||||
expect(new Set(ids).size).toBe(ids.length);
|
||||
});
|
||||
|
||||
it('returns an empty list for a null / empty collection', () => {
|
||||
expect(mapContributionsToActivities(null, ctx)).toEqual([]);
|
||||
expect(mapContributionsToActivities(undefined, ctx)).toEqual([]);
|
||||
expect(mapContributionsToActivities({}, ctx)).toEqual([]);
|
||||
});
|
||||
|
||||
it('skips malformed nodes (missing ids or timestamps)', () => {
|
||||
const collection: ContributionsCollection = {
|
||||
commitContributionsByRepository: [
|
||||
{
|
||||
repository: { nameWithOwner: 'octocat/hello-world', url: null },
|
||||
contributions: { nodes: [null, { occurredAt: '', commitCount: 0 }] },
|
||||
},
|
||||
],
|
||||
issueContributionsByRepository: [
|
||||
{
|
||||
repository: { nameWithOwner: 'octocat/hello-world', url: null },
|
||||
contributions: { nodes: [{ issue: null }] },
|
||||
},
|
||||
],
|
||||
};
|
||||
expect(mapContributionsToActivities(collection, ctx)).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('harvestContributionEvidence', () => {
|
||||
function makeDb(overrides: Partial<HarvestDb> = {}): { db: HarvestDb; createMany: jest.Mock } {
|
||||
const createMany = jest.fn().mockResolvedValue({ count: 4 });
|
||||
const db: HarvestDb = {
|
||||
user: { findUnique: jest.fn().mockResolvedValue({ githubAccessToken: 'gho_x', githubUsername: 'octocat' }) },
|
||||
repositoryManager: {
|
||||
findMany: jest.fn().mockResolvedValue([
|
||||
{ repository: { id: 'repo-1', fullName: 'octocat/Hello-World' } },
|
||||
{ repository: { id: 'repo-2', fullName: 'octocat/spoon-knife' } },
|
||||
]),
|
||||
},
|
||||
repositoryActivity: { createMany },
|
||||
...overrides,
|
||||
};
|
||||
return { db, createMany };
|
||||
}
|
||||
|
||||
it('is a no-op when the user has no GitHub token', async () => {
|
||||
const { db, createMany } = makeDb({
|
||||
user: { findUnique: jest.fn().mockResolvedValue({ githubAccessToken: null, githubUsername: 'octocat' }) },
|
||||
});
|
||||
const graphqlClient = jest.fn();
|
||||
|
||||
const result = await harvestContributionEvidence('user-1', { db, graphqlClient });
|
||||
|
||||
expect(result).toEqual({ scannedRepositories: 0, mapped: 0, created: 0 });
|
||||
expect(graphqlClient).not.toHaveBeenCalled();
|
||||
expect(createMany).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('is a no-op when the user manages no repositories', async () => {
|
||||
const { db, createMany } = makeDb({
|
||||
repositoryManager: { findMany: jest.fn().mockResolvedValue([]) },
|
||||
});
|
||||
const graphqlClient = jest.fn();
|
||||
|
||||
const result = await harvestContributionEvidence('user-1', { db, graphqlClient });
|
||||
|
||||
expect(result).toEqual({ scannedRepositories: 0, mapped: 0, created: 0 });
|
||||
expect(graphqlClient).not.toHaveBeenCalled();
|
||||
expect(createMany).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('harvests, maps to managed repos, and deduped-inserts real contribution evidence', async () => {
|
||||
const { db, createMany } = makeDb();
|
||||
const response: ContributionsResponse = { user: { contributionsCollection: sampleCollection() } };
|
||||
const graphqlClient = jest.fn().mockResolvedValue(response);
|
||||
|
||||
const result = await harvestContributionEvidence('user-1', { db, graphqlClient });
|
||||
|
||||
expect(graphqlClient).toHaveBeenCalledWith(expect.stringContaining('contributionsCollection'), { login: 'octocat' });
|
||||
expect(createMany).toHaveBeenCalledTimes(1);
|
||||
const insertArg = createMany.mock.calls[0][0];
|
||||
expect(insertArg.skipDuplicates).toBe(true);
|
||||
// Only managed-repo rows are inserted (the stranger/repo commit is dropped).
|
||||
expect(insertArg.data.every((row: { repositoryId: string }) => ['repo-1', 'repo-2'].includes(row.repositoryId))).toBe(true);
|
||||
expect(result.scannedRepositories).toBe(2);
|
||||
expect(result.created).toBe(4);
|
||||
});
|
||||
|
||||
it('never throws when the GraphQL call fails', async () => {
|
||||
const { db, createMany } = makeDb();
|
||||
const graphqlClient = jest.fn().mockRejectedValue(new Error('rate limited'));
|
||||
|
||||
const result = await harvestContributionEvidence('user-1', { db, graphqlClient });
|
||||
|
||||
expect(result).toEqual({ scannedRepositories: 2, mapped: 0, created: 0 });
|
||||
expect(createMany).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@ -437,8 +437,6 @@ 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) => {
|
||||
|
||||
@ -1,157 +0,0 @@
|
||||
/**
|
||||
* 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<string, unknown> = {}) {
|
||||
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');
|
||||
});
|
||||
});
|
||||
@ -1,418 +0,0 @@
|
||||
/**
|
||||
* 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<string, string | undefined> = {};
|
||||
|
||||
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);
|
||||
});
|
||||
});
|
||||
@ -1,171 +0,0 @@
|
||||
/**
|
||||
* Tests for the talent-graph validation GATE (not just the ontology library).
|
||||
*
|
||||
* The ontology unit tests (talentGraphOntology.test.ts) prove validateEdge /
|
||||
* validateEdges are correct in isolation. These tests prove that the gate is
|
||||
* actually WIRED into the service read path — `getTalentGraph` runs the assembled
|
||||
* graph through `auditTalentGraphEdges` — and that it is non-breaking:
|
||||
* - valid edges pass through with no warning and the response shape is unchanged,
|
||||
* - an ontology-invalid edge (here: unparseable provenance timestamp from a
|
||||
* corrupt DB row) triggers exactly one structured warning while the dossier is
|
||||
* still returned intact (warn-only, nothing dropped, nothing reshaped).
|
||||
*
|
||||
* Prisma and the logger are mocked globally by tests/setup.ts.
|
||||
*/
|
||||
import { auditTalentGraphEdges, getTalentGraph } from '../../src/services/talentGraphService';
|
||||
import type { TalentGraphView } from '../../src/services/talentGraphEdges';
|
||||
import { mockPrisma } from '../setup';
|
||||
import logger from '../../src/utils/logger';
|
||||
|
||||
const warn = logger.warn as jest.Mock;
|
||||
|
||||
function makeView(overrides: Partial<TalentGraphView> = {}): TalentGraphView {
|
||||
return {
|
||||
profile: { id: 'dev-1' },
|
||||
projects: [
|
||||
{
|
||||
id: 'repo-1',
|
||||
url: 'https://github.com/acme/repo-1',
|
||||
topics: ['typescript'],
|
||||
verificationLevel: 'verified',
|
||||
lastVerifiedAt: new Date('2026-01-01T00:00:00Z'),
|
||||
evidence: [{ kind: 'repository_claim', sourceUrl: 'https://github.com/acme/repo-1' }],
|
||||
},
|
||||
],
|
||||
collaborators: [],
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe('auditTalentGraphEdges (the gate)', () => {
|
||||
it('accepts well-typed edges from a clean view and emits no warning', () => {
|
||||
const result = auditTalentGraphEdges(makeView());
|
||||
|
||||
expect(result.rejected).toHaveLength(0);
|
||||
// developer→repo contribution + developer→skill has_skill.
|
||||
expect(result.accepted.length).toBeGreaterThanOrEqual(2);
|
||||
expect(warn).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects an ontology-invalid edge and emits one structured warning (warn-only)', () => {
|
||||
// A corrupt DB timestamp flows into edge provenance as an unparseable date.
|
||||
const corrupt = makeView({
|
||||
projects: [
|
||||
{
|
||||
id: 'repo-1',
|
||||
url: 'https://github.com/acme/repo-1',
|
||||
topics: [],
|
||||
verificationLevel: 'verified',
|
||||
lastVerifiedAt: new Date('not-a-real-date'),
|
||||
evidence: [{ kind: 'repository_claim', sourceUrl: null }],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const result = auditTalentGraphEdges(corrupt);
|
||||
|
||||
expect(result.rejected.length).toBeGreaterThan(0);
|
||||
expect(result.rejected[0].rejections.map((r) => r.code)).toContain('invalid_observed_at');
|
||||
|
||||
expect(warn).toHaveBeenCalledTimes(1);
|
||||
const [message, meta] = warn.mock.calls[0];
|
||||
expect(message).toMatch(/edge validation rejected/i);
|
||||
expect(meta).toMatchObject({
|
||||
event: 'talent_graph.edge_validation.rejected',
|
||||
developerId: 'dev-1',
|
||||
rejectedCount: result.rejected.length,
|
||||
});
|
||||
expect(meta.rejections[0].codes).toContain('invalid_observed_at');
|
||||
});
|
||||
});
|
||||
|
||||
describe('getTalentGraph invokes the gate on the real read path', () => {
|
||||
const userId = 'dev-real-1';
|
||||
|
||||
function seedUser() {
|
||||
mockPrisma.user.__rows = [
|
||||
{
|
||||
id: userId,
|
||||
username: 'dev-real',
|
||||
displayName: 'Dev Real',
|
||||
avatar: null,
|
||||
avatarUrl: null,
|
||||
bio: null,
|
||||
githubId: null,
|
||||
githubUsername: null,
|
||||
createdAt: new Date('2025-01-01T00:00:00Z'),
|
||||
isPrivate: false,
|
||||
},
|
||||
];
|
||||
// Unused-but-queried tables must resolve to empty sets.
|
||||
mockPrisma.repositoryManager.__rows = [];
|
||||
mockPrisma.repositoryActivity.__rows = [];
|
||||
// The talent* models are not part of the shared prisma mock; stub the reads
|
||||
// getTalentGraph performs so the assembly runs without touching a real DB.
|
||||
mockPrisma.talentPilot = { findMany: jest.fn().mockResolvedValue([]) };
|
||||
mockPrisma.talentPublicProof = { findMany: jest.fn().mockResolvedValue([]) };
|
||||
}
|
||||
|
||||
function seedProject(updatedAt: Date) {
|
||||
mockPrisma.project.__rows = [
|
||||
{
|
||||
id: 'proj-1',
|
||||
userId,
|
||||
owner: 'acme',
|
||||
name: 'repo-1',
|
||||
fullName: 'acme/repo-1',
|
||||
description: 'a project',
|
||||
url: 'https://github.com/acme/repo-1',
|
||||
repoUrl: 'https://github.com/acme/repo-1',
|
||||
language: 'TypeScript',
|
||||
tags: ['typescript'],
|
||||
stars: 3,
|
||||
forks: 1,
|
||||
githubId: null,
|
||||
updatedAt,
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
it('runs the gate and returns the unchanged dossier shape for clean data (no warning)', async () => {
|
||||
seedUser();
|
||||
seedProject(new Date('2026-02-01T00:00:00Z'));
|
||||
|
||||
const graph = await getTalentGraph(userId);
|
||||
|
||||
// Success-path response shape is exactly what consumers depend on.
|
||||
expect(graph).not.toBeNull();
|
||||
expect(graph).toEqual(
|
||||
expect.objectContaining({
|
||||
profile: expect.objectContaining({ id: userId }),
|
||||
summary: expect.objectContaining({ projectCount: 1 }),
|
||||
projects: expect.any(Array),
|
||||
collaborators: expect.any(Array),
|
||||
generatedAt: expect.any(Date),
|
||||
}),
|
||||
);
|
||||
expect(graph!.projects).toHaveLength(1);
|
||||
// Clean data => the gate found nothing to warn about.
|
||||
expect(warn).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('emits a gate warning when the assembled graph carries an ontology-invalid edge, still returning the dossier', async () => {
|
||||
seedUser();
|
||||
// Corrupt persisted timestamp -> invalid edge provenance on the read path.
|
||||
seedProject(new Date('totally-invalid'));
|
||||
|
||||
const graph = await getTalentGraph(userId);
|
||||
|
||||
// Warn-only: the dossier is still returned intact, nothing dropped.
|
||||
expect(graph).not.toBeNull();
|
||||
expect(graph!.projects).toHaveLength(1);
|
||||
|
||||
// The gate actually ran inside getTalentGraph and flagged the violation.
|
||||
expect(warn).toHaveBeenCalledTimes(1);
|
||||
const [, meta] = warn.mock.calls[0];
|
||||
expect(meta).toMatchObject({
|
||||
event: 'talent_graph.edge_validation.rejected',
|
||||
developerId: userId,
|
||||
});
|
||||
});
|
||||
});
|
||||
@ -1,227 +0,0 @@
|
||||
/**
|
||||
* Unit tests for the talent-graph ontology + edge validation and extraction.
|
||||
*
|
||||
* These are pure (no Prisma, no I/O), mirroring skillTaxonomyService /
|
||||
* talentGapAnalysisService tests. They pin the load-bearing behavior of this
|
||||
* rung: edges are validated against the ontology's domain/range so
|
||||
* type-incompatible ("hallucinated") structure is rejected, provenance is
|
||||
* required on every fact, symmetric edges de-duplicate, and edges extracted from
|
||||
* a graph view all pass validation.
|
||||
*/
|
||||
import {
|
||||
validateEdge,
|
||||
validateEdges,
|
||||
edgeKey,
|
||||
TALENT_ONTOLOGY,
|
||||
type TalentEdgeInput,
|
||||
} from '../../src/services/talentGraphOntology';
|
||||
import { deriveTalentEdges, type TalentGraphView } from '../../src/services/talentGraphEdges';
|
||||
|
||||
function makeInput(overrides: Partial<TalentEdgeInput> = {}): TalentEdgeInput {
|
||||
return {
|
||||
type: 'contributed_to',
|
||||
from: { id: 'dev-1', type: 'developer' },
|
||||
to: { id: 'repo-1', type: 'repo' },
|
||||
provenance: {
|
||||
source: 'repository_claim',
|
||||
observedAt: new Date('2026-01-01T00:00:00Z'),
|
||||
confidence: 1,
|
||||
sourceUrl: 'https://github.com/acme/repo-1',
|
||||
},
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe('validateEdge', () => {
|
||||
it('accepts a well-typed developer→repo contribution and normalizes it', () => {
|
||||
const result = validateEdge(makeInput());
|
||||
expect(result.valid).toBe(true);
|
||||
if (!result.valid) return;
|
||||
expect(result.edge.type).toBe('contributed_to');
|
||||
expect(result.edge.from).toEqual({ id: 'dev-1', type: 'developer' });
|
||||
expect(result.edge.to).toEqual({ id: 'repo-1', type: 'repo' });
|
||||
expect(result.edge.provenance.confidence).toBe(1);
|
||||
expect(result.edge.provenance.observedAt).toBeInstanceOf(Date);
|
||||
expect(result.edge.key).toBe('contributed_to|developer:dev-1|repo:repo-1');
|
||||
});
|
||||
|
||||
it('rejects an unknown edge type', () => {
|
||||
const result = validateEdge(makeInput({ type: 'founded' }));
|
||||
expect(result.valid).toBe(false);
|
||||
if (result.valid) return;
|
||||
expect(result.rejections.map((r) => r.code)).toContain('unknown_edge_type');
|
||||
});
|
||||
|
||||
it('rejects a domain violation (repo cannot be the source of contributed_to)', () => {
|
||||
const result = validateEdge(
|
||||
makeInput({ from: { id: 'repo-1', type: 'repo' }, to: { id: 'repo-2', type: 'repo' } }),
|
||||
);
|
||||
expect(result.valid).toBe(false);
|
||||
if (result.valid) return;
|
||||
expect(result.rejections.map((r) => r.code)).toContain('domain_violation');
|
||||
});
|
||||
|
||||
it('rejects a range violation (has_skill must target a skill, not a repo)', () => {
|
||||
const result = validateEdge(
|
||||
makeInput({ type: 'has_skill', to: { id: 'repo-1', type: 'repo' } }),
|
||||
);
|
||||
expect(result.valid).toBe(false);
|
||||
if (result.valid) return;
|
||||
expect(result.rejections.map((r) => r.code)).toContain('range_violation');
|
||||
});
|
||||
|
||||
it('rejects an unknown node type', () => {
|
||||
const result = validateEdge(
|
||||
makeInput({ type: 'member_of', to: { id: 'x', type: 'company' } }),
|
||||
);
|
||||
expect(result.valid).toBe(false);
|
||||
if (result.valid) return;
|
||||
expect(result.rejections.map((r) => r.code)).toContain('unknown_to_type');
|
||||
});
|
||||
|
||||
it('rejects a self-referential collaborated_with edge', () => {
|
||||
const result = validateEdge(
|
||||
makeInput({
|
||||
type: 'collaborated_with',
|
||||
from: { id: 'dev-1', type: 'developer' },
|
||||
to: { id: 'dev-1', type: 'developer' },
|
||||
}),
|
||||
);
|
||||
expect(result.valid).toBe(false);
|
||||
if (result.valid) return;
|
||||
expect(result.rejections.map((r) => r.code)).toContain('self_reference');
|
||||
});
|
||||
|
||||
it('rejects missing endpoint ids', () => {
|
||||
const result = validateEdge(makeInput({ from: { id: ' ', type: 'developer' } }));
|
||||
expect(result.valid).toBe(false);
|
||||
if (result.valid) return;
|
||||
expect(result.rejections.map((r) => r.code)).toContain('missing_from_id');
|
||||
});
|
||||
|
||||
it('rejects out-of-range and non-finite confidence', () => {
|
||||
for (const confidence of [0, 1.5, -0.2, Number.NaN]) {
|
||||
const result = validateEdge(
|
||||
makeInput({ provenance: { source: 'github_sync', observedAt: new Date(), confidence, sourceUrl: null } }),
|
||||
);
|
||||
expect(result.valid).toBe(false);
|
||||
if (result.valid) continue;
|
||||
expect(result.rejections.map((r) => r.code)).toContain('invalid_confidence');
|
||||
}
|
||||
});
|
||||
|
||||
it('rejects an unknown provenance source and an invalid date together', () => {
|
||||
const result = validateEdge(
|
||||
makeInput({ provenance: { source: 'psychic_intuition', observedAt: 'not-a-date', confidence: 0.5 } }),
|
||||
);
|
||||
expect(result.valid).toBe(false);
|
||||
if (result.valid) return;
|
||||
const codes = result.rejections.map((r) => r.code);
|
||||
expect(codes).toContain('unknown_source');
|
||||
expect(codes).toContain('invalid_observed_at');
|
||||
});
|
||||
|
||||
it('coerces an ISO-string observedAt into a Date', () => {
|
||||
const result = validateEdge(
|
||||
makeInput({ provenance: { source: 'github_activity', observedAt: '2026-02-01T12:00:00Z', confidence: 0.75, sourceUrl: null } }),
|
||||
);
|
||||
expect(result.valid).toBe(true);
|
||||
if (!result.valid) return;
|
||||
expect(result.edge.provenance.observedAt.toISOString()).toBe('2026-02-01T12:00:00.000Z');
|
||||
});
|
||||
});
|
||||
|
||||
describe('edgeKey', () => {
|
||||
it('is order-independent for symmetric edges and directed for others', () => {
|
||||
const a = { id: 'dev-a', type: 'developer' as const };
|
||||
const b = { id: 'dev-b', type: 'developer' as const };
|
||||
expect(edgeKey('collaborated_with', a, b)).toBe(edgeKey('collaborated_with', b, a));
|
||||
|
||||
const dev = { id: 'dev-a', type: 'developer' as const };
|
||||
const repo = { id: 'repo-1', type: 'repo' as const };
|
||||
expect(edgeKey('contributed_to', dev, repo)).not.toBe(edgeKey('contributed_to', repo as never, dev as never));
|
||||
});
|
||||
|
||||
it('every ontology edge type has a coherent domain/range', () => {
|
||||
for (const def of Object.values(TALENT_ONTOLOGY)) {
|
||||
expect(def.domain.length).toBeGreaterThan(0);
|
||||
expect(def.range.length).toBeGreaterThan(0);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('validateEdges (batch)', () => {
|
||||
it('partitions accepted from rejected and dedups symmetric edges keeping strongest confidence', () => {
|
||||
const inputs: TalentEdgeInput[] = [
|
||||
makeInput(),
|
||||
// duplicate symmetric collaboration in both directions, second stronger
|
||||
makeInput({
|
||||
type: 'collaborated_with',
|
||||
from: { id: 'dev-1', type: 'developer' },
|
||||
to: { id: 'dev-2', type: 'developer' },
|
||||
provenance: { source: 'github_sync', observedAt: new Date(), confidence: 0.5, sourceUrl: null },
|
||||
}),
|
||||
makeInput({
|
||||
type: 'collaborated_with',
|
||||
from: { id: 'dev-2', type: 'developer' },
|
||||
to: { id: 'dev-1', type: 'developer' },
|
||||
provenance: { source: 'github_sync', observedAt: new Date(), confidence: 0.9, sourceUrl: null },
|
||||
}),
|
||||
// hallucinated / type-incompatible: a skill cannot contribute to a repo
|
||||
makeInput({ from: { id: 'skill-x', type: 'skill' } }),
|
||||
];
|
||||
|
||||
const { accepted, rejected } = validateEdges(inputs);
|
||||
|
||||
// one contribution + one deduped collaboration
|
||||
expect(accepted).toHaveLength(2);
|
||||
const collab = accepted.find((e) => e.type === 'collaborated_with');
|
||||
expect(collab?.provenance.confidence).toBe(0.9);
|
||||
|
||||
expect(rejected).toHaveLength(1);
|
||||
expect(rejected[0].rejections.map((r) => r.code)).toContain('domain_violation');
|
||||
});
|
||||
});
|
||||
|
||||
describe('deriveTalentEdges', () => {
|
||||
const view: TalentGraphView = {
|
||||
profile: { id: 'dev-1' },
|
||||
projects: [
|
||||
{
|
||||
id: 'repo-1',
|
||||
url: 'https://github.com/acme/repo-1',
|
||||
topics: ['reactjs', 'k8s', 'reactjs'], // alias + duplicate → one skill
|
||||
verificationLevel: 'verified',
|
||||
lastVerifiedAt: new Date('2026-01-01T00:00:00Z'),
|
||||
evidence: [{ kind: 'repository_claim', sourceUrl: 'https://github.com/acme/repo-1' }],
|
||||
},
|
||||
],
|
||||
collaborators: [
|
||||
{ id: 'dev-2', sharedProjects: [{ id: 'repo-1', url: 'https://github.com/acme/repo-1' }] },
|
||||
{ id: 'dev-1', sharedProjects: [] }, // self — must be skipped
|
||||
],
|
||||
};
|
||||
|
||||
it('emits contributed_to, canonicalized+deduped has_skill, and collaborated_with edges', () => {
|
||||
const edges = deriveTalentEdges(view);
|
||||
const byType = edges.reduce<Record<string, TalentEdgeInput[]>>((acc, e) => {
|
||||
(acc[e.type] ??= []).push(e);
|
||||
return acc;
|
||||
}, {});
|
||||
|
||||
expect(byType.contributed_to).toHaveLength(1);
|
||||
expect(byType.has_skill.map((e) => e.to.id).sort()).toEqual(['kubernetes', 'react']);
|
||||
// self-collaborator dev-1 skipped, only dev-2 remains
|
||||
expect(byType.collaborated_with).toHaveLength(1);
|
||||
expect(byType.collaborated_with[0].to.id).toBe('dev-2');
|
||||
});
|
||||
|
||||
it('produces edges that all pass ontology validation', () => {
|
||||
const { accepted, rejected } = validateEdges(deriveTalentEdges(view));
|
||||
expect(rejected).toHaveLength(0);
|
||||
expect(accepted.length).toBeGreaterThan(0);
|
||||
// skill edges are capped at the recorded tier even for a verified project
|
||||
const skillEdge = accepted.find((e) => e.type === 'has_skill');
|
||||
expect(skillEdge?.provenance.confidence).toBe(0.5);
|
||||
});
|
||||
});
|
||||
@ -1,303 +0,0 @@
|
||||
/**
|
||||
* Unit tests for the talent GraphRAG serving layer.
|
||||
*
|
||||
* Pure (no Prisma, no network): the LLM call and the view loader are both
|
||||
* injected. These tests pin the three load-bearing guarantees of the layer:
|
||||
* 1. Retrieval correctness — the k-hop subgraph contains the right nodes at the
|
||||
* right depth, takes no wrong hops, and always terminates.
|
||||
* 2. Deterministic serialization — identical subgraph in, byte-identical text.
|
||||
* 3. Grounding — the answer's evidence only ever references edges that were
|
||||
* actually retrieved; hallucinated citations are dropped.
|
||||
*/
|
||||
import { validateEdge, type TalentEdge } from '../../src/services/talentGraphOntology';
|
||||
import {
|
||||
buildSubgraphFromEdges,
|
||||
buildTalentSubgraph,
|
||||
} from '../../src/services/talentSubgraphRetrieval';
|
||||
import { serializeTalentSubgraphForLLM } from '../../src/services/talentSubgraphSerializer';
|
||||
import { parseRagResponse } from '../../src/services/talentGraphRagPrompt';
|
||||
import {
|
||||
explainTalentMatch,
|
||||
type ExplainTalentMatchDeps,
|
||||
} from '../../src/services/talentGraphRag';
|
||||
import type { TalentGraphView } from '../../src/services/talentGraphEdges';
|
||||
|
||||
// --- helpers ---------------------------------------------------------------
|
||||
|
||||
function edge(
|
||||
type: string,
|
||||
from: { id: string; type: string },
|
||||
to: { id: string; type: string },
|
||||
confidence = 1,
|
||||
source = 'repository_claim',
|
||||
): TalentEdge {
|
||||
const result = validateEdge({
|
||||
type,
|
||||
from,
|
||||
to,
|
||||
provenance: { source, observedAt: new Date('2026-01-01T00:00:00Z'), confidence, sourceUrl: null },
|
||||
});
|
||||
if (!result.valid) throw new Error(`test edge invalid: ${result.rejections.map((r) => r.code).join(',')}`);
|
||||
return result.edge;
|
||||
}
|
||||
|
||||
const DEV = (id: string) => ({ id, type: 'developer' as const });
|
||||
const REPO = (id: string) => ({ id, type: 'repo' as const });
|
||||
|
||||
/** A multi-hop edge set: dev-1 is the root; repo-2 sits two hops away. */
|
||||
function multiHopEdges(): TalentEdge[] {
|
||||
return [
|
||||
edge('contributed_to', DEV('dev-1'), REPO('repo-1')),
|
||||
edge('has_skill', DEV('dev-1'), { id: 'react', type: 'skill' }),
|
||||
edge('member_of', DEV('dev-1'), { id: 'org-1', type: 'org' }),
|
||||
edge('collaborated_with', DEV('dev-1'), DEV('dev-2'), 0.5, 'github_sync'),
|
||||
// dev-2's own contribution — reachable only at depth 2 from dev-1
|
||||
edge('contributed_to', DEV('dev-2'), REPO('repo-2')),
|
||||
];
|
||||
}
|
||||
|
||||
// --- retrieval correctness -------------------------------------------------
|
||||
|
||||
describe('buildSubgraphFromEdges (k-hop retrieval)', () => {
|
||||
it('depth 0 returns only the root, no edges', () => {
|
||||
const sub = buildSubgraphFromEdges(multiHopEdges(), DEV('dev-1'), 0);
|
||||
expect(sub.nodes).toHaveLength(1);
|
||||
expect(sub.nodes[0]).toMatchObject({ id: 'dev-1', type: 'developer', distance: 0 });
|
||||
expect(sub.edges).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('depth 1 includes direct neighbors but takes no wrong hops', () => {
|
||||
const sub = buildSubgraphFromEdges(multiHopEdges(), DEV('dev-1'), 1);
|
||||
const nodeIds = sub.nodes.map((n) => `${n.type}:${n.id}`).sort();
|
||||
expect(nodeIds).toEqual([
|
||||
'developer:dev-1',
|
||||
'developer:dev-2',
|
||||
'org:org-1',
|
||||
'repo:repo-1',
|
||||
'skill:react',
|
||||
]);
|
||||
// repo-2 is two hops away — it must NOT appear, and neither must its edge.
|
||||
expect(nodeIds).not.toContain('repo:repo-2');
|
||||
expect(sub.edges.some((e) => e.to.id === 'repo-2' || e.from.id === 'repo-2')).toBe(false);
|
||||
// every edge kept has both endpoints inside the node set
|
||||
const present = new Set(nodeIds);
|
||||
for (const e of sub.edges) {
|
||||
expect(present.has(`${e.from.type}:${e.from.id}`)).toBe(true);
|
||||
expect(present.has(`${e.to.type}:${e.to.id}`)).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it('depth 2 expands to the second hop and includes the bridging edge', () => {
|
||||
const sub = buildSubgraphFromEdges(multiHopEdges(), DEV('dev-1'), 2);
|
||||
const repo2 = sub.nodes.find((n) => n.id === 'repo-2');
|
||||
expect(repo2).toBeDefined();
|
||||
expect(repo2?.distance).toBe(2);
|
||||
expect(sub.edges.some((e) => e.from.id === 'dev-2' && e.to.id === 'repo-2')).toBe(true);
|
||||
});
|
||||
|
||||
it('terminates on cycles and caps runaway depth', () => {
|
||||
const cyclic = [
|
||||
edge('collaborated_with', DEV('dev-1'), DEV('dev-2'), 0.5, 'github_sync'),
|
||||
edge('collaborated_with', DEV('dev-2'), DEV('dev-3'), 0.5, 'github_sync'),
|
||||
edge('collaborated_with', DEV('dev-3'), DEV('dev-1'), 0.5, 'github_sync'),
|
||||
];
|
||||
const sub = buildSubgraphFromEdges(cyclic, DEV('dev-1'), 1000);
|
||||
// three developers, each visited once; depth is capped, not 1000
|
||||
expect(sub.nodes).toHaveLength(3);
|
||||
expect(sub.depth).toBeLessThanOrEqual(6);
|
||||
});
|
||||
|
||||
it('rejects a negative or non-integer depth at the boundary', () => {
|
||||
expect(() => buildSubgraphFromEdges(multiHopEdges(), DEV('dev-1'), -1)).toThrow();
|
||||
expect(() => buildSubgraphFromEdges(multiHopEdges(), DEV('dev-1'), 1.5)).toThrow();
|
||||
});
|
||||
|
||||
it('rejects an empty root id', () => {
|
||||
expect(() => buildSubgraphFromEdges(multiHopEdges(), DEV(' '), 1)).toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
// --- view-based retrieval --------------------------------------------------
|
||||
|
||||
const VIEW: TalentGraphView = {
|
||||
profile: { id: 'dev-1' },
|
||||
projects: [
|
||||
{
|
||||
id: 'repo-1',
|
||||
url: 'https://github.com/acme/repo-1',
|
||||
topics: ['reactjs', 'k8s'],
|
||||
verificationLevel: 'verified',
|
||||
lastVerifiedAt: new Date('2026-01-01T00:00:00Z'),
|
||||
evidence: [{ kind: 'repository_claim', sourceUrl: 'https://github.com/acme/repo-1' }],
|
||||
},
|
||||
],
|
||||
collaborators: [
|
||||
{ id: 'dev-2', sharedProjects: [{ id: 'repo-1', url: 'https://github.com/acme/repo-1' }] },
|
||||
],
|
||||
};
|
||||
|
||||
describe('buildTalentSubgraph (view-based)', () => {
|
||||
it('retrieves the developer neighborhood from an assembled view', () => {
|
||||
const sub = buildTalentSubgraph(VIEW, 'dev-1', 1);
|
||||
const types = sub.nodes.map((n) => n.type);
|
||||
expect(types).toContain('developer'); // root + collaborator
|
||||
expect(types).toContain('repo');
|
||||
expect(types).toContain('skill');
|
||||
// canonicalized skills present
|
||||
expect(sub.nodes.some((n) => n.type === 'skill' && n.id === 'react')).toBe(true);
|
||||
expect(sub.nodes.some((n) => n.type === 'skill' && n.id === 'kubernetes')).toBe(true);
|
||||
// every edge carries provenance
|
||||
for (const e of sub.edges) {
|
||||
expect(e.provenance.confidence).toBeGreaterThan(0);
|
||||
expect(e.provenance.observedAt).toBeInstanceOf(Date);
|
||||
expect(typeof e.provenance.source).toBe('string');
|
||||
}
|
||||
});
|
||||
|
||||
it('rejects a rootDeveloperId that does not match the view profile', () => {
|
||||
expect(() => buildTalentSubgraph(VIEW, 'someone-else', 1)).toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
// --- deterministic serialization ------------------------------------------
|
||||
|
||||
describe('serializeTalentSubgraphForLLM', () => {
|
||||
it('is deterministic: the same subgraph produces byte-identical text', () => {
|
||||
// Serialization is a pure function of the subgraph, so a single retrieved
|
||||
// subgraph must serialize identically every time (cacheable prompts). We
|
||||
// build once and serialize twice; edge order is fixed by the retrieval layer.
|
||||
const sub = buildSubgraphFromEdges(multiHopEdges(), DEV('dev-1'), 2);
|
||||
expect(serializeTalentSubgraphForLLM(sub)).toBe(serializeTalentSubgraphForLLM(sub));
|
||||
});
|
||||
|
||||
it('orders edges canonically regardless of input edge order', () => {
|
||||
const forward = buildSubgraphFromEdges(multiHopEdges(), DEV('dev-1'), 2);
|
||||
const shuffled = buildSubgraphFromEdges([...multiHopEdges()].reverse(), DEV('dev-1'), 2);
|
||||
expect(serializeTalentSubgraphForLLM(forward)).toBe(serializeTalentSubgraphForLLM(shuffled));
|
||||
});
|
||||
|
||||
it('exposes edge citation keys and provenance in the context', () => {
|
||||
const sub = buildTalentSubgraph(VIEW, 'dev-1', 2);
|
||||
const text = serializeTalentSubgraphForLLM(sub);
|
||||
expect(text).toContain('ROOT: developer:dev-1');
|
||||
expect(text).toContain('EDGES (facts — cite by [key]):');
|
||||
for (const e of sub.edges) {
|
||||
expect(text).toContain(`[${e.key}]`);
|
||||
}
|
||||
expect(text).toMatch(/source=/);
|
||||
expect(text).toMatch(/confidence=/);
|
||||
});
|
||||
|
||||
it('renders an empty subgraph without crashing', () => {
|
||||
const empty = buildSubgraphFromEdges([], DEV('dev-1'), 1);
|
||||
const text = serializeTalentSubgraphForLLM(empty);
|
||||
expect(text).toContain('ROOT: developer:dev-1');
|
||||
expect(text).toContain('(none)');
|
||||
});
|
||||
});
|
||||
|
||||
// --- response parsing ------------------------------------------------------
|
||||
|
||||
describe('parseRagResponse', () => {
|
||||
it('parses a clean JSON object', () => {
|
||||
const parsed = parseRagResponse('{"answer":"ok","citedEdgeKeys":["k1","k2"]}');
|
||||
expect(parsed.answer).toBe('ok');
|
||||
expect(parsed.citedEdgeKeys).toEqual(['k1', 'k2']);
|
||||
});
|
||||
|
||||
it('tolerates a ```json code fence', () => {
|
||||
const parsed = parseRagResponse('```json\n{"answer":"x","citedEdgeKeys":[]}\n```');
|
||||
expect(parsed.answer).toBe('x');
|
||||
});
|
||||
|
||||
it('throws on non-JSON, wrong shape, or non-string citations', () => {
|
||||
expect(() => parseRagResponse('not json')).toThrow();
|
||||
expect(() => parseRagResponse('[]')).toThrow();
|
||||
expect(() => parseRagResponse('{"answer":1,"citedEdgeKeys":[]}')).toThrow();
|
||||
expect(() => parseRagResponse('{"answer":"x","citedEdgeKeys":[1]}')).toThrow();
|
||||
expect(() => parseRagResponse('')).toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
// --- grounding (the core guarantee) ---------------------------------------
|
||||
|
||||
describe('explainTalentMatch (grounding)', () => {
|
||||
const loadView: ExplainTalentMatchDeps['loadView'] = async () => VIEW;
|
||||
|
||||
it('returns an answer whose evidence only references retrieved edges', async () => {
|
||||
// Discover the real edge keys the subgraph will contain.
|
||||
const sub = buildTalentSubgraph(VIEW, 'dev-1', 2);
|
||||
const realKey = sub.edges[0].key;
|
||||
const hallucinatedKey = 'collaborated_with|developer:ghost|developer:phantom';
|
||||
|
||||
const ask: ExplainTalentMatchDeps['ask'] = async (req) => {
|
||||
// sanity: the grounding contract and the serialized context were passed
|
||||
expect(req.system).toMatch(/ONLY using the facts/i);
|
||||
expect(req.context).toContain('ROOT: developer:dev-1');
|
||||
return JSON.stringify({
|
||||
answer: 'dev-1 matches because of contributed repositories and skills.',
|
||||
citedEdgeKeys: [realKey, hallucinatedKey],
|
||||
});
|
||||
};
|
||||
|
||||
const result = await explainTalentMatch('dev-1', 'Why does this developer match React work?', {
|
||||
ask,
|
||||
loadView,
|
||||
depth: 2,
|
||||
});
|
||||
|
||||
const subgraphKeys = new Set(sub.edges.map((e) => e.key));
|
||||
// INVARIANT: every cited piece of evidence exists in the retrieved subgraph
|
||||
for (const ev of result.evidence) {
|
||||
expect(subgraphKeys.has(ev.key)).toBe(true);
|
||||
}
|
||||
expect(result.evidence.map((e) => e.key)).toContain(realKey);
|
||||
// the hallucinated citation was dropped, not returned as evidence
|
||||
expect(result.evidence.map((e) => e.key)).not.toContain(hallucinatedKey);
|
||||
expect(result.droppedCitations).toContain(hallucinatedKey);
|
||||
// evidence carries provenance for auditability
|
||||
expect(result.evidence[0].source).toBeDefined();
|
||||
expect(result.evidence[0].confidence).toBeGreaterThan(0);
|
||||
expect(result.retrieval.edgeCount).toBe(sub.edges.length);
|
||||
});
|
||||
|
||||
it('de-duplicates repeated citations and preserves the answer text', async () => {
|
||||
const sub = buildTalentSubgraph(VIEW, 'dev-1', 2);
|
||||
const key = sub.edges[0].key;
|
||||
const ask: ExplainTalentMatchDeps['ask'] = async () =>
|
||||
JSON.stringify({ answer: 'grounded answer', citedEdgeKeys: [key, key, key] });
|
||||
|
||||
const result = await explainTalentMatch('dev-1', 'why match', { ask, loadView, depth: 2 });
|
||||
expect(result.answer).toBe('grounded answer');
|
||||
expect(result.evidence.filter((e) => e.key === key)).toHaveLength(1);
|
||||
expect(result.droppedCitations).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('returns no evidence when the model cites nothing', async () => {
|
||||
const ask: ExplainTalentMatchDeps['ask'] = async () =>
|
||||
JSON.stringify({ answer: 'insufficient information in the subgraph', citedEdgeKeys: [] });
|
||||
const result = await explainTalentMatch('dev-1', 'why match', { ask, loadView });
|
||||
expect(result.evidence).toHaveLength(0);
|
||||
expect(result.answer).toMatch(/insufficient/);
|
||||
});
|
||||
|
||||
it('validates inputs and surfaces a missing view', async () => {
|
||||
const ask: ExplainTalentMatchDeps['ask'] = async () => '{"answer":"x","citedEdgeKeys":[]}';
|
||||
await expect(explainTalentMatch('', 'q', { ask, loadView })).rejects.toThrow(/rootDeveloperId/);
|
||||
await expect(explainTalentMatch('dev-1', ' ', { ask, loadView })).rejects.toThrow(/query/);
|
||||
await expect(
|
||||
explainTalentMatch('dev-1', 'q', { ask, loadView: async () => null }),
|
||||
).rejects.toThrow(/No talent graph view/);
|
||||
});
|
||||
|
||||
it('requires an injected ask function', async () => {
|
||||
await expect(
|
||||
explainTalentMatch('dev-1', 'q', { loadView } as unknown as ExplainTalentMatchDeps),
|
||||
).rejects.toThrow(/deps.ask/);
|
||||
});
|
||||
|
||||
it('propagates a malformed LLM reply as an explicit error', async () => {
|
||||
const ask: ExplainTalentMatchDeps['ask'] = async () => 'garbage not json';
|
||||
await expect(explainTalentMatch('dev-1', 'q', { ask, loadView })).rejects.toThrow(/JSON/);
|
||||
});
|
||||
});
|
||||
@ -12,38 +12,12 @@
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"resolveJsonModule": true,
|
||||
"moduleResolution": "node",
|
||||
// TS7.0 turns the legacy "node" (node10) resolver into a hard error. We keep
|
||||
// node10 semantics intentionally (CommonJS output) and silence the pre-7.0
|
||||
// deprecation so `tsc --noEmit` stays green until a deliberate resolver bump.
|
||||
// "6.0" is not a value the pinned typescript@^5.9.3 (see package.json)
|
||||
// recognizes -- it hard-errors with TS5103 and the project fails to build
|
||||
// or even boot via ts-node at all. "5.0" is the value this TS major
|
||||
// actually accepts for this flag.
|
||||
"ignoreDeprecations": "5.0",
|
||||
"typeRoots": ["./node_modules/@types"],
|
||||
"declaration": true,
|
||||
"declarationMap": true,
|
||||
"sourceMap": true
|
||||
},
|
||||
"include": ["src/**/*"],
|
||||
"exclude": ["node_modules", "dist", "tests"],
|
||||
// `npm run dev` (nodemon --exec ts-node) refused to boot at all: this is an
|
||||
// npm workspaces monorepo, and express-rate-limit is only hoisted to the
|
||||
// *root* node_modules, not nested under backend/node_modules. Its own type
|
||||
// declarations resolve `express` by walking up from where the package
|
||||
// actually lives, so they land on the root's hoisted express@4 (and its
|
||||
// @types/express-serve-static-core@4.19.8) instead of this package's own
|
||||
// pinned express@5.1.0 / @types/express@5.0.5 -- producing a real-looking
|
||||
// but spurious "RateLimitRequestHandler not assignable to Application"
|
||||
// type error on every `app.use(limiter)` call. `npx tsc`/`tsc --noEmit`
|
||||
// (the actual build + CI gate) do NOT hit this: they resolve cleanly and
|
||||
// stay the source of truth for real type errors. `transpileOnly` makes the
|
||||
// dev-loop ts-node process behave the same way most Node teams run
|
||||
// ts-node in watch mode -- strip types fast, don't re-typecheck on every
|
||||
// save -- so `npm run dev` boots instead of crashing on a cross-package
|
||||
// typings collision that isn't a real bug in this project's own code.
|
||||
"ts-node": {
|
||||
"transpileOnly": true
|
||||
}
|
||||
"exclude": ["node_modules", "dist", "tests"]
|
||||
}
|
||||
|
||||
|
||||
@ -1,99 +0,0 @@
|
||||
import React from 'react';
|
||||
import { Alert } from 'react-native';
|
||||
import { render, fireEvent, waitFor, act } from '@testing-library/react-native';
|
||||
import ExportDataScreen from '../../../app/backup/export';
|
||||
import {
|
||||
requestAndDownloadDataExport,
|
||||
shareExportFile,
|
||||
DataExportTimeoutError,
|
||||
} from '../../../utils/dataExportFlow';
|
||||
|
||||
jest.mock('../../../utils/dataExportFlow');
|
||||
|
||||
describe('ExportDataScreen', () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
jest.spyOn(Alert, 'alert').mockImplementation(() => undefined);
|
||||
});
|
||||
|
||||
it('wires the export button to the real data-export flow and shares the result', async () => {
|
||||
(requestAndDownloadDataExport as jest.Mock).mockImplementation(async (onPhaseChange) => {
|
||||
onPhaseChange?.('requesting');
|
||||
onPhaseChange?.('processing');
|
||||
onPhaseChange?.('downloading');
|
||||
onPhaseChange?.('done');
|
||||
return { exportId: 'export-123', fileUri: 'file:///mock-cache/export.json' };
|
||||
});
|
||||
(shareExportFile as jest.Mock).mockResolvedValue(undefined);
|
||||
|
||||
const { getByText } = render(<ExportDataScreen />);
|
||||
|
||||
await act(async () => {
|
||||
fireEvent.press(getByText('JSON'));
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(requestAndDownloadDataExport).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
expect(shareExportFile).toHaveBeenCalledWith('file:///mock-cache/export.json');
|
||||
expect(getByText('Your data export is ready.')).toBeTruthy();
|
||||
expect(Alert.alert).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('shows a user-visible error instead of failing silently when the export request fails', async () => {
|
||||
(requestAndDownloadDataExport as jest.Mock).mockRejectedValue(
|
||||
new Error('Network request failed')
|
||||
);
|
||||
|
||||
const { getByText } = render(<ExportDataScreen />);
|
||||
|
||||
await act(async () => {
|
||||
fireEvent.press(getByText('JSON'));
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(Alert.alert).toHaveBeenCalledWith('Export Failed', 'Network request failed');
|
||||
});
|
||||
expect(shareExportFile).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('shows a friendly timeout message when the export never becomes ready', async () => {
|
||||
(requestAndDownloadDataExport as jest.Mock).mockRejectedValue(
|
||||
new DataExportTimeoutError('export-slow')
|
||||
);
|
||||
|
||||
const { getByText } = render(<ExportDataScreen />);
|
||||
|
||||
await act(async () => {
|
||||
fireEvent.press(getByText('JSON'));
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(Alert.alert).toHaveBeenCalledWith(
|
||||
'Export Failed',
|
||||
'Still preparing your export. Please check back in a few minutes.'
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
it('tells the user the export downloaded even if sharing it fails', async () => {
|
||||
(requestAndDownloadDataExport as jest.Mock).mockResolvedValue({
|
||||
exportId: 'export-123',
|
||||
fileUri: 'file:///mock-cache/export.json',
|
||||
});
|
||||
(shareExportFile as jest.Mock).mockRejectedValue(new Error('Share sheet unavailable'));
|
||||
|
||||
const { getByText } = render(<ExportDataScreen />);
|
||||
|
||||
await act(async () => {
|
||||
fireEvent.press(getByText('JSON'));
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(Alert.alert).toHaveBeenCalledWith(
|
||||
'Export Downloaded',
|
||||
'Your data export was downloaded but could not be opened for sharing. It is saved in app storage.'
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
@ -1,61 +0,0 @@
|
||||
import { backupService } from '../../services/backupService';
|
||||
import api from '../../services/api';
|
||||
|
||||
jest.mock('../../services/api');
|
||||
|
||||
describe('backupService', () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
describe('requestDataExport', () => {
|
||||
it('calls the real GDPR export request endpoint', async () => {
|
||||
const mockResponse = {
|
||||
data: {
|
||||
success: true,
|
||||
data: {
|
||||
exportId: 'export-123',
|
||||
estimatedTime: '2-5 minutes',
|
||||
createdAt: '2026-10-21T00:00:00.000Z',
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
(api.post as jest.Mock).mockResolvedValue(mockResponse);
|
||||
|
||||
const result = await backupService.requestDataExport();
|
||||
|
||||
expect(api.post).toHaveBeenCalledWith('/data-export/request');
|
||||
expect(result).toEqual(mockResponse.data);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getDataExportStatus', () => {
|
||||
it('calls the status endpoint with the exportId path param', async () => {
|
||||
const mockResponse = {
|
||||
data: {
|
||||
success: true,
|
||||
data: { exportId: 'export-123', status: 'processing', progress: 40 },
|
||||
},
|
||||
};
|
||||
|
||||
(api.get as jest.Mock).mockResolvedValue(mockResponse);
|
||||
|
||||
const result = await backupService.getDataExportStatus('export-123');
|
||||
|
||||
expect(api.get).toHaveBeenCalledWith('/data-export/export-123/status');
|
||||
expect(result).toEqual(mockResponse.data);
|
||||
});
|
||||
});
|
||||
|
||||
describe('exportData (legacy, deprecated)', () => {
|
||||
it('still calls the old non-existent compliance endpoint', async () => {
|
||||
const mockResponse = { data: { message: 'queued' } };
|
||||
(api.post as jest.Mock).mockResolvedValue(mockResponse);
|
||||
|
||||
await backupService.exportData('json');
|
||||
|
||||
expect(api.post).toHaveBeenCalledWith('/compliance/export-data', { format: 'json' });
|
||||
});
|
||||
});
|
||||
});
|
||||
@ -1,212 +0,0 @@
|
||||
import * as FileSystem from 'expo-file-system/legacy';
|
||||
import * as Sharing from 'expo-sharing';
|
||||
import {
|
||||
requestAndDownloadDataExport,
|
||||
shareExportFile,
|
||||
DataExportTimeoutError,
|
||||
} from '../../utils/dataExportFlow';
|
||||
import { backupService } from '../../services/backupService';
|
||||
import { useAuthStore } from '../../store/authStore';
|
||||
|
||||
jest.mock('../../services/backupService');
|
||||
jest.mock('../../store/authStore');
|
||||
|
||||
describe('dataExportFlow', () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
jest.useRealTimers();
|
||||
|
||||
(useAuthStore.getState as jest.Mock) = jest.fn(() => ({
|
||||
accessToken: 'test-access-token',
|
||||
refreshAccessToken: jest.fn(),
|
||||
}));
|
||||
});
|
||||
|
||||
describe('requestAndDownloadDataExport', () => {
|
||||
it('requests the export, polls until ready, then downloads the file', async () => {
|
||||
(backupService.requestDataExport as jest.Mock).mockResolvedValue({
|
||||
success: true,
|
||||
data: { exportId: 'export-abc', estimatedTime: '2-5 minutes', createdAt: 'now' },
|
||||
});
|
||||
|
||||
(backupService.getDataExportStatus as jest.Mock)
|
||||
.mockResolvedValueOnce({
|
||||
success: true,
|
||||
data: { exportId: 'export-abc', status: 'processing', progress: 20 },
|
||||
})
|
||||
.mockResolvedValueOnce({
|
||||
success: true,
|
||||
data: { exportId: 'export-abc', status: 'ready', progress: 100 },
|
||||
});
|
||||
|
||||
jest.useFakeTimers();
|
||||
const phases: string[] = [];
|
||||
const resultPromise = requestAndDownloadDataExport((phase) => phases.push(phase));
|
||||
await jest.advanceTimersByTimeAsync(3000);
|
||||
const result = await resultPromise;
|
||||
jest.useRealTimers();
|
||||
|
||||
expect(backupService.requestDataExport).toHaveBeenCalledTimes(1);
|
||||
expect(backupService.getDataExportStatus).toHaveBeenCalledTimes(2);
|
||||
expect(FileSystem.downloadAsync).toHaveBeenCalledWith(
|
||||
expect.stringContaining('/data-export/export-abc/download'),
|
||||
expect.stringContaining('export-abc'),
|
||||
{ headers: { Authorization: 'Bearer test-access-token' } }
|
||||
);
|
||||
expect(result).toEqual({
|
||||
exportId: 'export-abc',
|
||||
fileUri: 'file:///mock-cache/mock-export.json',
|
||||
});
|
||||
expect(phases).toEqual(['requesting', 'processing', 'downloading', 'done']);
|
||||
});
|
||||
|
||||
it('falls back to a refreshed token when there is no access token yet', async () => {
|
||||
const refreshAccessToken = jest.fn().mockResolvedValue('refreshed-token');
|
||||
(useAuthStore.getState as jest.Mock).mockReturnValue({
|
||||
accessToken: null,
|
||||
refreshAccessToken,
|
||||
});
|
||||
|
||||
(backupService.requestDataExport as jest.Mock).mockResolvedValue({
|
||||
success: true,
|
||||
data: { exportId: 'export-xyz', estimatedTime: '2-5 minutes', createdAt: 'now' },
|
||||
});
|
||||
(backupService.getDataExportStatus as jest.Mock).mockResolvedValue({
|
||||
success: true,
|
||||
data: { exportId: 'export-xyz', status: 'ready', progress: 100 },
|
||||
});
|
||||
|
||||
await requestAndDownloadDataExport();
|
||||
|
||||
expect(refreshAccessToken).toHaveBeenCalledTimes(1);
|
||||
expect(FileSystem.downloadAsync).toHaveBeenCalledWith(
|
||||
expect.any(String),
|
||||
expect.any(String),
|
||||
{ headers: { Authorization: 'Bearer refreshed-token' } }
|
||||
);
|
||||
});
|
||||
|
||||
it('throws when the user is not signed in and cannot refresh a token', async () => {
|
||||
(useAuthStore.getState as jest.Mock).mockReturnValue({
|
||||
accessToken: null,
|
||||
refreshAccessToken: jest.fn().mockResolvedValue(null),
|
||||
});
|
||||
|
||||
(backupService.requestDataExport as jest.Mock).mockResolvedValue({
|
||||
success: true,
|
||||
data: { exportId: 'export-xyz', estimatedTime: '2-5 minutes', createdAt: 'now' },
|
||||
});
|
||||
(backupService.getDataExportStatus as jest.Mock).mockResolvedValue({
|
||||
success: true,
|
||||
data: { exportId: 'export-xyz', status: 'ready', progress: 100 },
|
||||
});
|
||||
|
||||
await expect(requestAndDownloadDataExport()).rejects.toThrow(
|
||||
'You must be signed in to export your data.'
|
||||
);
|
||||
});
|
||||
|
||||
it('throws a user-visible error when the export fails server-side', async () => {
|
||||
(backupService.requestDataExport as jest.Mock).mockResolvedValue({
|
||||
success: true,
|
||||
data: { exportId: 'export-fail', estimatedTime: '2-5 minutes', createdAt: 'now' },
|
||||
});
|
||||
(backupService.getDataExportStatus as jest.Mock).mockResolvedValue({
|
||||
success: true,
|
||||
data: { exportId: 'export-fail', status: 'failed', progress: 0 },
|
||||
});
|
||||
|
||||
await expect(requestAndDownloadDataExport()).rejects.toThrow(
|
||||
'Data export failed. Please try again.'
|
||||
);
|
||||
});
|
||||
|
||||
it('throws a user-visible error when the export expires before download', async () => {
|
||||
(backupService.requestDataExport as jest.Mock).mockResolvedValue({
|
||||
success: true,
|
||||
data: { exportId: 'export-expired', estimatedTime: '2-5 minutes', createdAt: 'now' },
|
||||
});
|
||||
(backupService.getDataExportStatus as jest.Mock).mockResolvedValue({
|
||||
success: true,
|
||||
data: { exportId: 'export-expired', status: 'expired', progress: 100 },
|
||||
});
|
||||
|
||||
await expect(requestAndDownloadDataExport()).rejects.toThrow(
|
||||
'Data export expired before it could be downloaded. Please request a new one.'
|
||||
);
|
||||
});
|
||||
|
||||
it('propagates the request error without silently swallowing it', async () => {
|
||||
(backupService.requestDataExport as jest.Mock).mockRejectedValue(
|
||||
new Error('Network request failed')
|
||||
);
|
||||
|
||||
await expect(requestAndDownloadDataExport()).rejects.toThrow('Network request failed');
|
||||
expect(backupService.getDataExportStatus).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('throws DataExportTimeoutError when the export never becomes ready', async () => {
|
||||
(backupService.requestDataExport as jest.Mock).mockResolvedValue({
|
||||
success: true,
|
||||
data: { exportId: 'export-slow', estimatedTime: '2-5 minutes', createdAt: 'now' },
|
||||
});
|
||||
(backupService.getDataExportStatus as jest.Mock).mockResolvedValue({
|
||||
success: true,
|
||||
data: { exportId: 'export-slow', status: 'processing', progress: 10 },
|
||||
});
|
||||
|
||||
jest.useFakeTimers();
|
||||
// Attach the rejection assertion synchronously, right when the promise
|
||||
// is created, so Node never sees it as unhandled while the fake timers
|
||||
// are advanced below.
|
||||
const assertion = expect(requestAndDownloadDataExport()).rejects.toBeInstanceOf(
|
||||
DataExportTimeoutError
|
||||
);
|
||||
// Let every poll's sleep() resolve without waiting real wall-clock time.
|
||||
await jest.advanceTimersByTimeAsync(3000 * 61);
|
||||
|
||||
await assertion;
|
||||
jest.useRealTimers();
|
||||
}, 15000);
|
||||
|
||||
it('surfaces a non-2xx download status as a thrown error', async () => {
|
||||
(backupService.requestDataExport as jest.Mock).mockResolvedValue({
|
||||
success: true,
|
||||
data: { exportId: 'export-bad', estimatedTime: '2-5 minutes', createdAt: 'now' },
|
||||
});
|
||||
(backupService.getDataExportStatus as jest.Mock).mockResolvedValue({
|
||||
success: true,
|
||||
data: { exportId: 'export-bad', status: 'ready', progress: 100 },
|
||||
});
|
||||
(FileSystem.downloadAsync as jest.Mock).mockResolvedValueOnce({
|
||||
uri: 'file:///mock-cache/export-bad.json',
|
||||
status: 410,
|
||||
});
|
||||
|
||||
await expect(requestAndDownloadDataExport()).rejects.toThrow(
|
||||
'Failed to download export (status 410).'
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('shareExportFile', () => {
|
||||
it('shares the downloaded file via the OS share sheet', async () => {
|
||||
await shareExportFile('file:///mock-cache/mock-export.json');
|
||||
|
||||
expect(Sharing.isAvailableAsync).toHaveBeenCalledTimes(1);
|
||||
expect(Sharing.shareAsync).toHaveBeenCalledWith('file:///mock-cache/mock-export.json', {
|
||||
mimeType: 'application/json',
|
||||
dialogTitle: 'Save or share your data export',
|
||||
});
|
||||
});
|
||||
|
||||
it('throws a user-visible error when sharing is unavailable on this device', async () => {
|
||||
(Sharing.isAvailableAsync as jest.Mock).mockResolvedValueOnce(false);
|
||||
|
||||
await expect(shareExportFile('file:///mock-cache/mock-export.json')).rejects.toThrow(
|
||||
'Sharing is not available on this device. The file was saved to app storage.'
|
||||
);
|
||||
expect(Sharing.shareAsync).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
});
|
||||
@ -14,47 +14,20 @@ import Header from '../../components/navigation/Header';
|
||||
import LoadingSpinner from '../../components/common/LoadingSpinner';
|
||||
import { useAuthStore } from '../../store/authStore';
|
||||
import { logger } from '../../utils/logger';
|
||||
import { authService } from '../../services/authService';
|
||||
import { complianceService } from '../../services/complianceService';
|
||||
|
||||
export default function DeleteAccountScreen() {
|
||||
const router = useRouter();
|
||||
const { logout } = useAuthStore();
|
||||
const { user, logout } = useAuthStore();
|
||||
const [confirmText, setConfirmText] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
// null until we know — OAuth-only accounts have no password to re-enter.
|
||||
const [hasPassword, setHasPassword] = useState<boolean | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
React.useEffect(() => {
|
||||
let active = true;
|
||||
authService
|
||||
.getMe()
|
||||
.then((data) => {
|
||||
if (active) setHasPassword(Boolean(data?.user?.password));
|
||||
})
|
||||
.catch((error) => {
|
||||
logger.error('Load account type error:', error);
|
||||
// Fall back to showing the password field; the backend tells us if it
|
||||
// actually is required.
|
||||
if (active) setHasPassword(true);
|
||||
});
|
||||
return () => {
|
||||
active = false;
|
||||
};
|
||||
}, []);
|
||||
|
||||
const handleDelete = () => {
|
||||
if (confirmText !== 'DELETE') {
|
||||
Alert.alert('Error', 'Please type DELETE to confirm');
|
||||
return;
|
||||
}
|
||||
|
||||
if (hasPassword && !password) {
|
||||
Alert.alert('Error', 'Please enter your password to confirm');
|
||||
return;
|
||||
}
|
||||
|
||||
Alert.alert(
|
||||
'Delete Account',
|
||||
'This action cannot be undone. All your data will be permanently deleted. Are you absolutely sure?',
|
||||
@ -66,17 +39,13 @@ export default function DeleteAccountScreen() {
|
||||
onPress: async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
await complianceService.deleteAccount(hasPassword ? password : undefined);
|
||||
await complianceService.deleteAccount();
|
||||
await logout();
|
||||
Alert.alert('Account Deleted', 'Your account has been permanently deleted.');
|
||||
router.replace('/(auth)/login');
|
||||
} catch (error) {
|
||||
logger.error('Delete account error:', error);
|
||||
const message =
|
||||
(error as { response?: { data?: { error?: string; message?: string } } })
|
||||
?.response?.data?.message ||
|
||||
(error as { response?: { data?: { error?: string } } })?.response?.data?.error;
|
||||
Alert.alert('Error', message || 'Failed to delete account. Please try again.');
|
||||
Alert.alert('Error', 'Failed to delete account. Please try again.');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
@ -104,22 +73,6 @@ export default function DeleteAccountScreen() {
|
||||
<Text style={styles.listItem}>• All your saved content</Text>
|
||||
</View>
|
||||
|
||||
{hasPassword && (
|
||||
<>
|
||||
<Text style={styles.confirmLabel}>Confirm with your password:</Text>
|
||||
<TextInput
|
||||
style={styles.input}
|
||||
value={password}
|
||||
onChangeText={setPassword}
|
||||
placeholder="Password"
|
||||
placeholderTextColor={Colors.textSecondary}
|
||||
secureTextEntry
|
||||
autoCapitalize="none"
|
||||
autoCorrect={false}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
|
||||
<Text style={styles.confirmLabel}>
|
||||
Type <Text style={styles.confirmWord}>DELETE</Text> to confirm:
|
||||
</Text>
|
||||
@ -216,3 +169,4 @@ const styles = StyleSheet.create({
|
||||
fontWeight: '600',
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
@ -11,58 +11,23 @@ import { Colors } from '../../constants/Colors';
|
||||
import Header from '../../components/navigation/Header';
|
||||
import LoadingSpinner from '../../components/common/LoadingSpinner';
|
||||
import { logger } from '../../utils/logger';
|
||||
import {
|
||||
requestAndDownloadDataExport,
|
||||
shareExportFile,
|
||||
DataExportTimeoutError,
|
||||
DataExportPhase,
|
||||
} from '../../utils/dataExportFlow';
|
||||
import { backupService } from '../../services/backupService';
|
||||
import Icon from 'react-native-vector-icons/MaterialIcons';
|
||||
|
||||
const PHASE_MESSAGES: Record<DataExportPhase, string> = {
|
||||
requesting: 'Requesting your export…',
|
||||
processing: 'Preparing your export… this can take a couple of minutes.',
|
||||
downloading: 'Export ready — downloading…',
|
||||
done: 'Export downloaded. Opening share sheet…',
|
||||
};
|
||||
|
||||
export default function ExportDataScreen() {
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [statusMessage, setStatusMessage] = useState<string | null>(null);
|
||||
|
||||
const handleExport = async () => {
|
||||
const handleExport = async (format: 'json' | 'csv') => {
|
||||
setLoading(true);
|
||||
setStatusMessage(null);
|
||||
try {
|
||||
const { fileUri } = await requestAndDownloadDataExport((phase) => {
|
||||
setStatusMessage(PHASE_MESSAGES[phase]);
|
||||
});
|
||||
|
||||
try {
|
||||
await shareExportFile(fileUri);
|
||||
} catch (shareError) {
|
||||
// The export downloaded fine; sharing it is best-effort, so surface
|
||||
// this but don't treat it as a failed export.
|
||||
logger.error('Share export file error:', shareError);
|
||||
Alert.alert(
|
||||
'Export Downloaded',
|
||||
'Your data export was downloaded but could not be opened for sharing. It is saved in app storage.'
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
setStatusMessage('Your data export is ready.');
|
||||
await backupService.exportData(format);
|
||||
Alert.alert(
|
||||
'Export Started',
|
||||
`Your data export in ${format.toUpperCase()} format will be ready shortly. You'll receive a notification when it's complete.`
|
||||
);
|
||||
} catch (error) {
|
||||
logger.error('Export data error:', error);
|
||||
Alert.alert(
|
||||
'Export Failed',
|
||||
error instanceof DataExportTimeoutError
|
||||
? 'Still preparing your export. Please check back in a few minutes.'
|
||||
: error instanceof Error
|
||||
? error.message
|
||||
: 'Failed to export data. Please try again.'
|
||||
);
|
||||
setStatusMessage(null);
|
||||
Alert.alert('Error', 'Failed to export data. Please try again.');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
@ -73,14 +38,14 @@ export default function ExportDataScreen() {
|
||||
<Header title="Export Data" />
|
||||
<ScrollView style={styles.content}>
|
||||
<Text style={styles.description}>
|
||||
Export a copy of your data including posts, snippets, collections, messages, and account information.
|
||||
Export a copy of your data including posts, comments, messages, and account information.
|
||||
</Text>
|
||||
|
||||
<View style={styles.section}>
|
||||
<Text style={styles.sectionTitle}>Export Format</Text>
|
||||
<TouchableOpacity
|
||||
style={[styles.formatOption, loading && styles.formatOptionDisabled]}
|
||||
onPress={handleExport}
|
||||
style={styles.formatOption}
|
||||
onPress={() => handleExport('json')}
|
||||
disabled={loading}
|
||||
>
|
||||
<Icon name="code" size={24} color={Colors.text} />
|
||||
@ -92,17 +57,26 @@ export default function ExportDataScreen() {
|
||||
</View>
|
||||
<Icon name="chevron-right" size={24} color={Colors.textSecondary} />
|
||||
</TouchableOpacity>
|
||||
</View>
|
||||
|
||||
{statusMessage && (
|
||||
<View style={styles.statusBanner}>
|
||||
<Text style={styles.statusText}>{statusMessage}</Text>
|
||||
</View>
|
||||
)}
|
||||
<TouchableOpacity
|
||||
style={styles.formatOption}
|
||||
onPress={() => handleExport('csv')}
|
||||
disabled={loading}
|
||||
>
|
||||
<Icon name="table-chart" size={24} color={Colors.text} />
|
||||
<View style={styles.formatInfo}>
|
||||
<Text style={styles.formatLabel}>CSV</Text>
|
||||
<Text style={styles.formatDescription}>
|
||||
Spreadsheet format, easy to view
|
||||
</Text>
|
||||
</View>
|
||||
<Icon name="chevron-right" size={24} color={Colors.textSecondary} />
|
||||
</TouchableOpacity>
|
||||
</View>
|
||||
|
||||
<View style={styles.note}>
|
||||
<Text style={styles.noteText}>
|
||||
Note: Large exports may take a couple of minutes to process. Keep this screen open while your export is prepared, then use the share sheet to save or send the file.
|
||||
Note: Large exports may take several minutes to process. You'll receive a notification when your export is ready.
|
||||
</Text>
|
||||
</View>
|
||||
</ScrollView>
|
||||
@ -157,19 +131,6 @@ const styles = StyleSheet.create({
|
||||
fontSize: 14,
|
||||
color: Colors.textSecondary,
|
||||
},
|
||||
formatOptionDisabled: {
|
||||
opacity: 0.6,
|
||||
},
|
||||
statusBanner: {
|
||||
backgroundColor: Colors.surface,
|
||||
borderRadius: 8,
|
||||
padding: 12,
|
||||
marginBottom: 20,
|
||||
},
|
||||
statusText: {
|
||||
fontSize: 14,
|
||||
color: Colors.text,
|
||||
},
|
||||
note: {
|
||||
backgroundColor: Colors.surface,
|
||||
borderRadius: 8,
|
||||
|
||||
@ -38,24 +38,6 @@ jest.mock('expo-constants', () => ({
|
||||
},
|
||||
}));
|
||||
|
||||
// Mock expo-sharing (used to let the user save/share a downloaded file)
|
||||
jest.mock('expo-sharing', () => ({
|
||||
isAvailableAsync: jest.fn(() => Promise.resolve(true)),
|
||||
shareAsync: jest.fn(() => Promise.resolve()),
|
||||
}));
|
||||
|
||||
// Mock expo-file-system legacy API (used for downloading the GDPR export to
|
||||
// local app storage before handing it to expo-sharing)
|
||||
jest.mock('expo-file-system/legacy', () => ({
|
||||
cacheDirectory: 'file:///mock-cache/',
|
||||
downloadAsync: jest.fn(() =>
|
||||
Promise.resolve({ uri: 'file:///mock-cache/mock-export.json', status: 200 })
|
||||
),
|
||||
getInfoAsync: jest.fn(() => Promise.resolve({ exists: false, isDirectory: false })),
|
||||
readDirectoryAsync: jest.fn(() => Promise.resolve([])),
|
||||
deleteAsync: jest.fn(() => Promise.resolve()),
|
||||
}));
|
||||
|
||||
// Mock expo-notifications
|
||||
jest.mock('expo-notifications', () => ({
|
||||
setNotificationHandler: jest.fn(),
|
||||
|
||||
@ -44,7 +44,6 @@
|
||||
"expo-media-library": "^18.2.0",
|
||||
"expo-notifications": "^0.32.13",
|
||||
"expo-router": "^6.0.15",
|
||||
"expo-sharing": "~14.0.8",
|
||||
"expo-status-bar": "~3.0.8",
|
||||
"expo-video": "^3.0.14",
|
||||
"expo-web-browser": "^15.0.9",
|
||||
|
||||
@ -1,50 +1,11 @@
|
||||
import api from './api';
|
||||
|
||||
export type DataExportStatus = 'processing' | 'ready' | 'expired' | 'failed';
|
||||
|
||||
export interface DataExportRequestResponse {
|
||||
success: boolean;
|
||||
data: {
|
||||
exportId: string;
|
||||
estimatedTime: string;
|
||||
createdAt: string;
|
||||
};
|
||||
}
|
||||
|
||||
export interface DataExportStatusResponse {
|
||||
success: boolean;
|
||||
data: {
|
||||
exportId: string;
|
||||
status: DataExportStatus;
|
||||
progress: number;
|
||||
};
|
||||
}
|
||||
|
||||
export const backupService = {
|
||||
/**
|
||||
* @deprecated Hits `/compliance/export-data`, which does not exist on the
|
||||
* backend (always 404s). Use `requestDataExport` + `getDataExportStatus` +
|
||||
* `utils/dataExportFlow.ts`'s `requestAndDownloadDataExport`, which drive the
|
||||
* real GDPR export pipeline at `/api/v1/data-export` (see
|
||||
* backend/src/routes/dataExport.ts). Matches the web fix in commit 842be56e.
|
||||
*/
|
||||
exportData: async (format: 'json' | 'csv') => {
|
||||
const response = await api.post('/compliance/export-data', { format });
|
||||
return response.data;
|
||||
},
|
||||
|
||||
// Data export (GDPR). Backend flow is async: request -> poll status -> download
|
||||
// once ready. See backend/src/routes/dataExport.ts + services/dataExportService.ts.
|
||||
requestDataExport: async (): Promise<DataExportRequestResponse> => {
|
||||
const { data } = await api.post('/data-export/request');
|
||||
return data;
|
||||
},
|
||||
|
||||
getDataExportStatus: async (exportId: string): Promise<DataExportStatusResponse> => {
|
||||
const { data } = await api.get(`/data-export/${exportId}/status`);
|
||||
return data;
|
||||
},
|
||||
|
||||
importData: async (fileUri: string) => {
|
||||
const formData = new FormData();
|
||||
formData.append('file', {
|
||||
|
||||
@ -6,15 +6,8 @@ export const complianceService = {
|
||||
return response.data;
|
||||
},
|
||||
|
||||
/**
|
||||
* Deletes the account. The backend lives at `DELETE /auth/delete-account`
|
||||
* (not `/compliance/account`, which never existed and always 404'd).
|
||||
* Password accounts must pass `password`; OAuth-only accounts omit it.
|
||||
*/
|
||||
deleteAccount: async (password?: string) => {
|
||||
const response = await api.delete('/auth/delete-account', {
|
||||
data: password ? { password } : {},
|
||||
});
|
||||
deleteAccount: async () => {
|
||||
const response = await api.delete('/compliance/account');
|
||||
return response.data;
|
||||
},
|
||||
|
||||
|
||||
@ -1,119 +0,0 @@
|
||||
import * as FileSystem from 'expo-file-system/legacy';
|
||||
import * as Sharing from 'expo-sharing';
|
||||
import { API_BASE_URL } from '../constants/Config';
|
||||
import { useAuthStore } from '../store/authStore';
|
||||
import { backupService } from '../services/backupService';
|
||||
|
||||
/**
|
||||
* Drives the full GDPR data-export flow against the real backend
|
||||
* (backend/src/routes/dataExport.ts): request -> poll status -> download ->
|
||||
* share/save. Mirrors web/utils/dataExportFlow.ts (fixed in commit 842be56e).
|
||||
*
|
||||
* The backend generates the export asynchronously (2-5 min estimate), so this
|
||||
* polls until the job is 'ready' (or fails/expires), downloads the resulting
|
||||
* file into app storage via expo-file-system, then hands it to expo-sharing
|
||||
* so the user can save or share it. Used by app/backup/export.tsx, which
|
||||
* previously called `backupService.exportData` -> `/compliance/export-data`,
|
||||
* an endpoint that never existed on the backend and always 404'd.
|
||||
*/
|
||||
|
||||
const POLL_INTERVAL_MS = 3000;
|
||||
const MAX_POLL_ATTEMPTS = 60; // ~3 minutes
|
||||
|
||||
export type DataExportPhase = 'requesting' | 'processing' | 'downloading' | 'done';
|
||||
|
||||
export interface DataExportFlowResult {
|
||||
exportId: string;
|
||||
fileUri: string;
|
||||
}
|
||||
|
||||
export class DataExportTimeoutError extends Error {
|
||||
constructor(public exportId: string) {
|
||||
super('Export is taking longer than expected. Check back in a few minutes.');
|
||||
this.name = 'DataExportTimeoutError';
|
||||
}
|
||||
}
|
||||
|
||||
function sleep(ms: number): Promise<void> {
|
||||
return new Promise((resolve) => setTimeout(resolve, ms));
|
||||
}
|
||||
|
||||
async function getAuthHeader(): Promise<Record<string, string>> {
|
||||
const { accessToken, refreshAccessToken } = useAuthStore.getState();
|
||||
const token = accessToken ?? (await refreshAccessToken());
|
||||
|
||||
if (!token) {
|
||||
throw new Error('You must be signed in to export your data.');
|
||||
}
|
||||
|
||||
return { Authorization: `Bearer ${token}` };
|
||||
}
|
||||
|
||||
async function downloadExportFile(exportId: string): Promise<string> {
|
||||
const headers = await getAuthHeader();
|
||||
const url = `${API_BASE_URL}/data-export/${exportId}/download`;
|
||||
const destUri = `${FileSystem.cacheDirectory}gitgram-data-export-${exportId}.json`;
|
||||
|
||||
const result = await FileSystem.downloadAsync(url, destUri, { headers });
|
||||
|
||||
if (result.status < 200 || result.status >= 300) {
|
||||
throw new Error(`Failed to download export (status ${result.status}).`);
|
||||
}
|
||||
|
||||
return result.uri;
|
||||
}
|
||||
|
||||
/**
|
||||
* Requests a new export, polls until it is ready, and downloads the file to
|
||||
* local app storage. Does not share/save the file — call `shareExportFile`
|
||||
* with the returned `fileUri` to let the user save or share it.
|
||||
*/
|
||||
export async function requestAndDownloadDataExport(
|
||||
onPhaseChange?: (phase: DataExportPhase) => void
|
||||
): Promise<DataExportFlowResult> {
|
||||
onPhaseChange?.('requesting');
|
||||
const requested = await backupService.requestDataExport();
|
||||
const { exportId } = requested.data;
|
||||
|
||||
onPhaseChange?.('processing');
|
||||
for (let attempt = 0; attempt < MAX_POLL_ATTEMPTS; attempt += 1) {
|
||||
const statusResult = await backupService.getDataExportStatus(exportId);
|
||||
const { status } = statusResult.data;
|
||||
|
||||
if (status === 'ready') {
|
||||
onPhaseChange?.('downloading');
|
||||
const fileUri = await downloadExportFile(exportId);
|
||||
onPhaseChange?.('done');
|
||||
return { exportId, fileUri };
|
||||
}
|
||||
|
||||
if (status === 'failed') {
|
||||
throw new Error('Data export failed. Please try again.');
|
||||
}
|
||||
|
||||
if (status === 'expired') {
|
||||
throw new Error('Data export expired before it could be downloaded. Please request a new one.');
|
||||
}
|
||||
|
||||
await sleep(POLL_INTERVAL_MS);
|
||||
}
|
||||
|
||||
throw new DataExportTimeoutError(exportId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Hands the downloaded export file to the OS share sheet so the user can
|
||||
* save it (Files app, Drive, etc.) or share it elsewhere.
|
||||
*/
|
||||
export async function shareExportFile(fileUri: string): Promise<void> {
|
||||
const canShare = await Sharing.isAvailableAsync();
|
||||
|
||||
if (!canShare) {
|
||||
throw new Error('Sharing is not available on this device. The file was saved to app storage.');
|
||||
}
|
||||
|
||||
await Sharing.shareAsync(fileUri, {
|
||||
mimeType: 'application/json',
|
||||
dialogTitle: 'Save or share your data export',
|
||||
});
|
||||
}
|
||||
@ -1,9 +1,8 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect, useState } from 'react'
|
||||
import { useState } from 'react'
|
||||
import { useRouter } from 'next/navigation'
|
||||
import { useAuthStore } from '@/store/authStore'
|
||||
import userService from '@/services/userService'
|
||||
import api from '@/services/api'
|
||||
import { useToast } from '@/components/ui/toast'
|
||||
|
||||
@ -12,48 +11,22 @@ export default function DeleteAccountPage() {
|
||||
const { showToast } = useToast()
|
||||
const { logout } = useAuthStore()
|
||||
const [confirmText, setConfirmText] = useState('')
|
||||
const [password, setPassword] = useState('')
|
||||
// null until known — OAuth-only accounts have no password to re-enter.
|
||||
const [hasPassword, setHasPassword] = useState<boolean | null>(null)
|
||||
const [deleting, setDeleting] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
let active = true
|
||||
api
|
||||
.get('/v1/auth/me')
|
||||
.then(({ data }) => {
|
||||
if (active) setHasPassword(Boolean(data?.user?.password))
|
||||
})
|
||||
.catch(() => {
|
||||
// Fall back to showing the field; the backend says if it is required.
|
||||
if (active) setHasPassword(true)
|
||||
})
|
||||
return () => {
|
||||
active = false
|
||||
}
|
||||
}, [])
|
||||
|
||||
const handleDelete = async () => {
|
||||
if (confirmText !== 'DELETE') {
|
||||
showToast('Please type DELETE to confirm', 'warning')
|
||||
return
|
||||
}
|
||||
|
||||
if (hasPassword && !password) {
|
||||
showToast('Please enter your password to confirm', 'warning')
|
||||
return
|
||||
}
|
||||
|
||||
setDeleting(true)
|
||||
try {
|
||||
await userService.deleteAccount(hasPassword ? password : undefined)
|
||||
await api.delete('/v1/compliance/account')
|
||||
await logout()
|
||||
router.push('/login')
|
||||
} catch (error) {
|
||||
console.error('Delete account error:', error)
|
||||
const message = (error as { response?: { data?: { message?: string; error?: string } } })
|
||||
?.response?.data?.message
|
||||
showToast(message || 'Failed to delete account', 'error')
|
||||
showToast('Failed to delete account', 'error')
|
||||
} finally {
|
||||
setDeleting(false)
|
||||
}
|
||||
@ -73,22 +46,6 @@ export default function DeleteAccountPage() {
|
||||
</div>
|
||||
|
||||
<div className="space-y-4">
|
||||
{hasPassword && (
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-foreground mb-2">
|
||||
Confirm with your password
|
||||
</label>
|
||||
<input
|
||||
type="password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
autoComplete="current-password"
|
||||
className="w-full px-4 py-2 bg-surface border border-border rounded-lg text-foreground focus:outline-none focus:ring-2 focus:ring-red-500"
|
||||
placeholder="Password"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-foreground mb-2">
|
||||
Type <strong>DELETE</strong> to confirm
|
||||
@ -122,3 +79,4 @@ export default function DeleteAccountPage() {
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@ -3,7 +3,6 @@
|
||||
import { Suspense, useState } from 'react';
|
||||
import { useRouter, useSearchParams } from 'next/navigation';
|
||||
import { useToast } from '@/components/ui/toast';
|
||||
import { githubService } from '@/services/githubService';
|
||||
|
||||
function AuthForm() {
|
||||
const searchParams = useSearchParams();
|
||||
@ -16,15 +15,6 @@ function AuthForm() {
|
||||
const router = useRouter();
|
||||
const { showToast } = useToast();
|
||||
|
||||
const handleGitHubSignIn = () => {
|
||||
if (!process.env.NEXT_PUBLIC_GITHUB_CLIENT_ID) {
|
||||
showToast('GitHub OAuth not configured', 'error');
|
||||
return;
|
||||
}
|
||||
// Redirects to GitHub's authorize page; /auth/github/callback completes it.
|
||||
githubService.connectGitHub();
|
||||
};
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setLoading(true);
|
||||
@ -71,27 +61,6 @@ function AuthForm() {
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleGitHubSignIn}
|
||||
aria-label="Sign in with GitHub"
|
||||
className="w-full flex items-center justify-center gap-3 py-3 mb-6 rounded-lg bg-gray-900 text-white font-medium hover:bg-black transition"
|
||||
>
|
||||
<svg className="w-5 h-5" fill="currentColor" viewBox="0 0 24 24" aria-hidden="true">
|
||||
<path d="M12 .5C5.37.5 0 5.87 0 12.5c0 5.3 3.44 9.8 8.21 11.39.6.11.82-.26.82-.58 0-.29-.01-1.04-.02-2.05-3.34.72-4.04-1.61-4.04-1.61-.55-1.39-1.34-1.76-1.34-1.76-1.09-.75.08-.73.08-.73 1.2.09 1.84 1.24 1.84 1.24 1.07 1.83 2.81 1.3 3.5.99.11-.78.42-1.3.76-1.6-2.67-.3-5.47-1.33-5.47-5.93 0-1.31.47-2.38 1.24-3.22-.13-.3-.54-1.52.11-3.18 0 0 1.01-.32 3.3 1.23a11.5 11.5 0 016 0c2.29-1.55 3.3-1.23 3.3-1.23.65 1.66.24 2.88.12 3.18.77.84 1.23 1.91 1.23 3.22 0 4.61-2.8 5.63-5.48 5.92.43.37.81 1.1.81 2.22 0 1.6-.01 2.9-.01 3.29 0 .32.22.7.83.58A12.01 12.01 0 0024 12.5C24 5.87 18.63.5 12 .5z" />
|
||||
</svg>
|
||||
Sign in with GitHub
|
||||
</button>
|
||||
|
||||
<div className="relative mb-6">
|
||||
<div className="absolute inset-0 flex items-center">
|
||||
<div className="w-full border-t border-gray-200 dark:border-gray-700" />
|
||||
</div>
|
||||
<div className="relative flex justify-center text-sm">
|
||||
<span className="px-3 bg-white dark:bg-gray-800 text-gray-500">or</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-2 mb-6">
|
||||
<button
|
||||
onClick={() => setIsLogin(true)}
|
||||
@ -164,7 +133,7 @@ function AuthForm() {
|
||||
</form>
|
||||
|
||||
<div className="mt-6 text-center text-sm text-gray-600 dark:text-gray-400">
|
||||
<p>New: Repositories are social accounts!</p>
|
||||
<p>🎉 New: Repositories are social accounts!</p>
|
||||
<p className="mt-2">Claim your repos and post as them</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@ -1,8 +1,8 @@
|
||||
'use client'
|
||||
|
||||
import { useState } from 'react'
|
||||
import api from '@/services/api'
|
||||
import { useToast } from '@/components/ui/toast'
|
||||
import { requestAndDownloadDataExport, DataExportTimeoutError } from '@/utils/dataExportFlow'
|
||||
|
||||
export default function ExportDataPage() {
|
||||
const { showToast } = useToast()
|
||||
@ -11,18 +11,17 @@ export default function ExportDataPage() {
|
||||
const handleExport = async () => {
|
||||
setExporting(true)
|
||||
try {
|
||||
await requestAndDownloadDataExport((phase) => {
|
||||
if (phase === 'processing') showToast('Preparing your export… this can take a couple of minutes.', 'info')
|
||||
})
|
||||
showToast('Your data export downloaded successfully.', 'success')
|
||||
const response = await api.get('/v1/compliance/export-data')
|
||||
const blob = new Blob([JSON.stringify(response.data, null, 2)], { type: 'application/json' })
|
||||
const url = URL.createObjectURL(blob)
|
||||
const a = document.createElement('a')
|
||||
a.href = url
|
||||
a.download = `gitgram-data-export-${new Date().toISOString()}.json`
|
||||
a.click()
|
||||
URL.revokeObjectURL(url)
|
||||
} catch (error) {
|
||||
console.error('Export data error:', error)
|
||||
showToast(
|
||||
error instanceof DataExportTimeoutError
|
||||
? 'Still preparing your export. Please check back in a few minutes.'
|
||||
: 'Failed to export data',
|
||||
'error',
|
||||
)
|
||||
showToast('Failed to export data', 'error')
|
||||
} finally {
|
||||
setExporting(false)
|
||||
}
|
||||
|
||||
@ -178,7 +178,7 @@ export default function CollaboratePage() {
|
||||
}
|
||||
|
||||
const handleCopyShareLink = async () => {
|
||||
if (!graph?.profile.username) return
|
||||
if (!graph.profile.username) return
|
||||
|
||||
try {
|
||||
const url = new URL('/collaborate', window.location.origin)
|
||||
|
||||
@ -1,38 +0,0 @@
|
||||
import type { MetadataRoute } from 'next'
|
||||
|
||||
const SITE_URL = process.env.NEXT_PUBLIC_SITE_URL || 'https://gitgram.app'
|
||||
|
||||
// There was no robots.txt (static or dynamic) anywhere in the app, so search
|
||||
// engines had no explicit crawl directives and no sitemap reference for this
|
||||
// site. Authenticated/private surfaces (messages, settings, admin, etc.) are
|
||||
// disallowed; public profile/repo/discovery pages remain crawlable.
|
||||
export default function robots(): MetadataRoute.Robots {
|
||||
return {
|
||||
rules: {
|
||||
userAgent: '*',
|
||||
allow: '/',
|
||||
disallow: [
|
||||
'/api/',
|
||||
'/admin',
|
||||
'/settings',
|
||||
'/messages',
|
||||
'/notifications',
|
||||
'/account',
|
||||
'/create',
|
||||
'/create-change-story',
|
||||
'/create-story',
|
||||
'/drafts',
|
||||
'/edit',
|
||||
'/backup',
|
||||
'/compose',
|
||||
'/camera',
|
||||
'/chat',
|
||||
'/follow-requests',
|
||||
'/creator-studio',
|
||||
'/api-test',
|
||||
],
|
||||
},
|
||||
sitemap: `${SITE_URL}/sitemap.xml`,
|
||||
host: SITE_URL,
|
||||
}
|
||||
}
|
||||
@ -4,7 +4,6 @@ import { useState, useEffect } from 'react'
|
||||
import { useRouter } from 'next/navigation'
|
||||
import Link from 'next/link'
|
||||
import api from '@/services/api'
|
||||
import { requestAndDownloadDataExport, DataExportTimeoutError } from '@/utils/dataExportFlow'
|
||||
|
||||
export default function DataSettingsPage() {
|
||||
const router = useRouter()
|
||||
@ -15,7 +14,6 @@ export default function DataSettingsPage() {
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [saving, setSaving] = useState(false)
|
||||
const [exporting, setExporting] = useState(false)
|
||||
const [exportMessage, setExportMessage] = useState<string | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
loadSettings()
|
||||
@ -48,22 +46,17 @@ export default function DataSettingsPage() {
|
||||
|
||||
const handleExport = async () => {
|
||||
setExporting(true)
|
||||
setExportMessage(null)
|
||||
try {
|
||||
await requestAndDownloadDataExport((phase) => {
|
||||
if (phase === 'processing') setExportMessage('Preparing your export… this can take a couple of minutes.')
|
||||
if (phase === 'downloading') setExportMessage('Export ready — starting download…')
|
||||
})
|
||||
setExportMessage('Your data export downloaded successfully.')
|
||||
const response = await api.get('/v1/compliance/export-data')
|
||||
const blob = new Blob([JSON.stringify(response.data, null, 2)], { type: 'application/json' })
|
||||
const url = URL.createObjectURL(blob)
|
||||
const a = document.createElement('a')
|
||||
a.href = url
|
||||
a.download = `gitgram-data-export-${new Date().toISOString()}.json`
|
||||
a.click()
|
||||
URL.revokeObjectURL(url)
|
||||
} catch (error) {
|
||||
console.error('Export data error:', error)
|
||||
setExportMessage(
|
||||
error instanceof DataExportTimeoutError
|
||||
? 'Still preparing your export. Please check back in a few minutes.'
|
||||
: error instanceof Error
|
||||
? error.message
|
||||
: 'Failed to export data. Please try again.',
|
||||
)
|
||||
} finally {
|
||||
setExporting(false)
|
||||
}
|
||||
@ -95,9 +88,6 @@ export default function DataSettingsPage() {
|
||||
>
|
||||
{exporting ? 'Exporting...' : 'Export Data'}
|
||||
</button>
|
||||
{exportMessage && (
|
||||
<p className="mt-3 text-sm text-foreground/70">{exportMessage}</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="bg-surface rounded-lg p-6">
|
||||
|
||||
@ -4,7 +4,6 @@ import { useState, useEffect, useCallback } from 'react'
|
||||
import { useAuthStore } from '@/store/authStore'
|
||||
import { useRouter } from 'next/navigation'
|
||||
import { settingsService } from '@/services/settingsService'
|
||||
import { requestAndDownloadDataExport, DataExportTimeoutError } from '@/utils/dataExportFlow'
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
|
||||
@ -326,19 +325,13 @@ export default function PrivacySettingsPage() {
|
||||
setExportLoading(true)
|
||||
setExportMessage(null)
|
||||
try {
|
||||
await requestAndDownloadDataExport((phase) => {
|
||||
if (phase === 'processing') setExportMessage('Preparing your export… this can take a couple of minutes.')
|
||||
if (phase === 'downloading') setExportMessage('Export ready — starting download…')
|
||||
})
|
||||
setExportMessage('Your data export downloaded successfully.')
|
||||
} catch (err: unknown) {
|
||||
const response = await settingsService.getDataSettings()
|
||||
setExportMessage(
|
||||
err instanceof DataExportTimeoutError
|
||||
? 'Still preparing your export. Please check back in a few minutes.'
|
||||
: err instanceof Error
|
||||
? `Failed: ${err.message}`
|
||||
: 'Failed to request data export. Please try again.',
|
||||
(response as Record<string, unknown>).message as string
|
||||
?? 'Your data export has been queued. You will receive an email with the download link within 24 hours.',
|
||||
)
|
||||
} catch (err: unknown) {
|
||||
setExportMessage('Failed to request data export. Please try again.')
|
||||
} finally {
|
||||
setExportLoading(false)
|
||||
}
|
||||
@ -720,7 +713,7 @@ export default function PrivacySettingsPage() {
|
||||
<div style={{ flex: 1, minWidth: '200px' }}>
|
||||
<p style={{ margin: 0, fontSize: '13px', color: '#6b7280', lineHeight: 1.6 }}>
|
||||
Includes your posts, followers, messages, repositories, and account metadata.
|
||||
Preparation takes a couple of minutes; the file downloads automatically when ready.
|
||||
You will receive a download link via email within 24 hours.
|
||||
</p>
|
||||
{exportMessage && (
|
||||
<p
|
||||
|
||||
@ -1,30 +0,0 @@
|
||||
import type { MetadataRoute } from 'next'
|
||||
|
||||
const SITE_URL = process.env.NEXT_PUBLIC_SITE_URL || 'https://gitgram.app'
|
||||
|
||||
// Static, always-public marketing/discovery routes. User/repo profile pages
|
||||
// are dynamic ([username], [owner]/[repo]) and intentionally left out here
|
||||
// rather than querying the database at build time from this file; add a
|
||||
// dedicated sitemap route (e.g. app/sitemap/[id]/route.ts with
|
||||
// generateSitemaps) if those need to be indexed individually.
|
||||
const STATIC_ROUTES = [
|
||||
'',
|
||||
'/explore',
|
||||
'/discover',
|
||||
'/trending',
|
||||
'/search',
|
||||
'/pricing',
|
||||
'/about',
|
||||
'/terms',
|
||||
'/privacy-policy',
|
||||
]
|
||||
|
||||
export default function sitemap(): MetadataRoute.Sitemap {
|
||||
const now = new Date()
|
||||
return STATIC_ROUTES.map((path) => ({
|
||||
url: `${SITE_URL}${path}`,
|
||||
lastModified: now,
|
||||
changeFrequency: path === '' ? 'daily' : 'weekly',
|
||||
priority: path === '' ? 1 : 0.7,
|
||||
}))
|
||||
}
|
||||
@ -6,15 +6,12 @@ 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 = {
|
||||
@ -167,10 +164,6 @@ 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 }>())
|
||||
|
||||
@ -301,93 +294,6 @@ 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)
|
||||
@ -710,12 +616,9 @@ 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>
|
||||
@ -765,52 +668,6 @@ 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,15 +251,3 @@
|
||||
.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; }
|
||||
|
||||
9
gitgram/web/css-modules.d.ts
vendored
9
gitgram/web/css-modules.d.ts
vendored
@ -1,9 +0,0 @@
|
||||
// Ambient declarations for side-effect stylesheet imports.
|
||||
//
|
||||
// Next.js compiles CSS imports at build time, but a raw `tsc --noEmit` (the
|
||||
// configured typecheck gate) has no knowledge of `.css` files and errors on
|
||||
// `import './globals.css'` style side-effect imports (TS2882). Declaring the
|
||||
// modules here keeps the typecheck gate green without affecting the build.
|
||||
declare module '*.css';
|
||||
declare module '*.scss';
|
||||
declare module '*.sass';
|
||||
@ -200,51 +200,6 @@ 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')
|
||||
@ -305,50 +260,6 @@ 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) {
|
||||
|
||||
@ -78,12 +78,8 @@ export const userService = {
|
||||
},
|
||||
|
||||
// Account management
|
||||
// Real route is DELETE /v1/auth/delete-account (there is no /v1/auth/account).
|
||||
// Password accounts must pass a password; OAuth-only accounts omit it.
|
||||
deleteAccount: async (password?: string) => {
|
||||
const { data } = await api.delete('/v1/auth/delete-account', {
|
||||
data: password ? { password } : {},
|
||||
})
|
||||
deleteAccount: async (password: string) => {
|
||||
const { data } = await api.delete('/v1/auth/account', { data: { password } })
|
||||
return data
|
||||
},
|
||||
|
||||
@ -162,22 +158,14 @@ export const userService = {
|
||||
return data
|
||||
},
|
||||
|
||||
// Data export (GDPR). Backend flow is async: request -> poll status -> download
|
||||
// once ready. See backend/src/routes/dataExport.ts.
|
||||
requestDataExport: async (): Promise<{ success: boolean; data: { exportId: string; estimatedTime: string; createdAt: string } }> => {
|
||||
// Data export
|
||||
requestDataExport: async () => {
|
||||
const { data } = await api.post('/v1/data-export/request')
|
||||
return data
|
||||
},
|
||||
|
||||
getExportStatus: async (
|
||||
exportId: string
|
||||
): Promise<{ success: boolean; data: { exportId: string; status: 'processing' | 'ready' | 'expired' | 'failed'; progress: number } }> => {
|
||||
const { data } = await api.get(`/v1/data-export/${exportId}/status`)
|
||||
return data
|
||||
},
|
||||
|
||||
downloadDataExport: async (exportId: string): Promise<Blob> => {
|
||||
const { data } = await api.get(`/v1/data-export/${exportId}/download`, { responseType: 'blob' })
|
||||
getExportStatus: async () => {
|
||||
const { data } = await api.get('/v1/data-export/status')
|
||||
return data
|
||||
},
|
||||
|
||||
|
||||
@ -1,40 +0,0 @@
|
||||
/// <reference types="vitest/globals" />
|
||||
import { describe, it, expect, beforeEach, afterEach } from 'vitest'
|
||||
import { githubService } from '@/services/githubService'
|
||||
|
||||
/**
|
||||
* connectGitHub is the "Sign in with GitHub" entry point surfaced on the login
|
||||
* screens. It must redirect to GitHub's OAuth authorize endpoint with the
|
||||
* client id, the callback redirect URI, and the scopes the backend needs to
|
||||
* write back stars/follows and read the user's email.
|
||||
*/
|
||||
describe('githubService.connectGitHub', () => {
|
||||
const originalLocation = window.location
|
||||
const originalClientId = process.env.NEXT_PUBLIC_GITHUB_CLIENT_ID
|
||||
|
||||
beforeEach(() => {
|
||||
Object.defineProperty(window, 'location', {
|
||||
configurable: true,
|
||||
value: { origin: 'https://app.gitgram.com', href: '' },
|
||||
})
|
||||
process.env.NEXT_PUBLIC_GITHUB_CLIENT_ID = 'test-client-123'
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
Object.defineProperty(window, 'location', { configurable: true, value: originalLocation })
|
||||
process.env.NEXT_PUBLIC_GITHUB_CLIENT_ID = originalClientId
|
||||
})
|
||||
|
||||
it('redirects to the GitHub authorize endpoint', () => {
|
||||
githubService.connectGitHub()
|
||||
expect(window.location.href).toContain('https://github.com/login/oauth/authorize')
|
||||
})
|
||||
|
||||
it('includes the configured client id, callback redirect, and scopes', () => {
|
||||
githubService.connectGitHub()
|
||||
const url = new URL(window.location.href)
|
||||
expect(url.searchParams.get('client_id')).toBe('test-client-123')
|
||||
expect(url.searchParams.get('redirect_uri')).toBe('https://app.gitgram.com/auth/github/callback')
|
||||
expect(url.searchParams.get('scope')).toBe('user:email,repo,read:user')
|
||||
})
|
||||
})
|
||||
@ -48,102 +48,3 @@ 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')
|
||||
})
|
||||
})
|
||||
|
||||
@ -1,99 +0,0 @@
|
||||
/// <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')
|
||||
})
|
||||
})
|
||||
@ -1,77 +0,0 @@
|
||||
import { userService } from '@/services/userService'
|
||||
|
||||
/**
|
||||
* Drives the full GDPR data-export flow against the real backend
|
||||
* (backend/src/routes/dataExport.ts): request -> poll status -> download.
|
||||
*
|
||||
* The backend generates the export asynchronously (2-5 min estimate), so this
|
||||
* polls until the job is 'ready' (or fails/expires), then streams the file
|
||||
* and triggers a browser download. Used by both settings/privacy and
|
||||
* settings/data, which previously called endpoints that never existed on the
|
||||
* backend (`/v1/settings/data`, `/v1/compliance/export-data`) and always 404'd.
|
||||
*/
|
||||
|
||||
const POLL_INTERVAL_MS = 3000
|
||||
const MAX_POLL_ATTEMPTS = 60 // ~3 minutes
|
||||
|
||||
export type DataExportPhase = 'requesting' | 'processing' | 'downloading' | 'done'
|
||||
|
||||
export interface DataExportFlowResult {
|
||||
exportId: string
|
||||
}
|
||||
|
||||
export class DataExportTimeoutError extends Error {
|
||||
constructor(public exportId: string) {
|
||||
super('Export is taking longer than expected. Check back in a few minutes.')
|
||||
this.name = 'DataExportTimeoutError'
|
||||
}
|
||||
}
|
||||
|
||||
function sleep(ms: number): Promise<void> {
|
||||
return new Promise((resolve) => setTimeout(resolve, ms))
|
||||
}
|
||||
|
||||
function triggerBlobDownload(blob: Blob, filename: string): void {
|
||||
const url = URL.createObjectURL(blob)
|
||||
const anchor = document.createElement('a')
|
||||
anchor.href = url
|
||||
anchor.download = filename
|
||||
document.body.appendChild(anchor)
|
||||
anchor.click()
|
||||
anchor.remove()
|
||||
URL.revokeObjectURL(url)
|
||||
}
|
||||
|
||||
export async function requestAndDownloadDataExport(
|
||||
onPhaseChange?: (phase: DataExportPhase) => void
|
||||
): Promise<DataExportFlowResult> {
|
||||
onPhaseChange?.('requesting')
|
||||
const requested = await userService.requestDataExport()
|
||||
const exportId = requested.data.exportId
|
||||
|
||||
onPhaseChange?.('processing')
|
||||
for (let attempt = 0; attempt < MAX_POLL_ATTEMPTS; attempt += 1) {
|
||||
const statusResult = await userService.getExportStatus(exportId)
|
||||
const { status } = statusResult.data
|
||||
|
||||
if (status === 'ready') {
|
||||
onPhaseChange?.('downloading')
|
||||
const blob = await userService.downloadDataExport(exportId)
|
||||
triggerBlobDownload(blob, `gitgram-data-export-${new Date().toISOString()}.json`)
|
||||
onPhaseChange?.('done')
|
||||
return { exportId }
|
||||
}
|
||||
|
||||
if (status === 'failed') {
|
||||
throw new Error('Data export failed. Please try again.')
|
||||
}
|
||||
|
||||
if (status === 'expired') {
|
||||
throw new Error('Data export expired before it could be downloaded. Please request a new one.')
|
||||
}
|
||||
|
||||
await sleep(POLL_INTERVAL_MS)
|
||||
}
|
||||
|
||||
throw new DataExportTimeoutError(exportId)
|
||||
}
|
||||
@ -1,67 +0,0 @@
|
||||
/**
|
||||
* 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()}`
|
||||
}
|
||||
@ -2,7 +2,7 @@
|
||||
"name": "gitgram-ai",
|
||||
"version": "1.0.0",
|
||||
"private": true,
|
||||
"description": "Gitgram AI monorepo \u2014 social platform for developers + AITimeMachine",
|
||||
"description": "Gitgram AI monorepo — social platform for developers + AITimeMachine",
|
||||
"workspaces": [
|
||||
"gitgram/web",
|
||||
"gitgram/backend",
|
||||
@ -37,7 +37,7 @@
|
||||
"dev:aitm-mcp": "cd aitimemachine/mcp && npm run dev",
|
||||
"dev:gitnexus": "cd aitimemachine/gitnexus && npm run dev",
|
||||
"dev:gitnexus-web": "cd aitimemachine/gitnexus-web && npm run dev",
|
||||
"dev:a2a": "cd aitimemachine/a2a && npm run dev 2>/dev/null || echo 'a2a has no dev script \u2014 build with: cd aitimemachine/a2a && npm run build'",
|
||||
"dev:a2a": "cd aitimemachine/a2a && npm run dev 2>/dev/null || echo 'a2a has no dev script — build with: cd aitimemachine/a2a && npm run build'",
|
||||
"dev:context7": "cd aitimemachine/context7/packages/mcp && npm run dev 2>/dev/null || node aitimemachine/context7/packages/mcp/dist/index.js",
|
||||
"dev:pal-mcp": "cd aitimemachine/pal-mcp-server && ./run-server.sh",
|
||||
"dev:repo2txt": "cd aitimemachine/tools/repo2txt && npm run dev",
|
||||
@ -76,6 +76,5 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@types/uuid": "^9.0.8"
|
||||
},
|
||||
"license": "MIT"
|
||||
}
|
||||
}
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user