chore: merge executor worktree (worktree-agent-a11c767c2a8721d5b)

This commit is contained in:
lorentz 2026-07-11 14:31:20 -04:00
commit 580e7ac508
5 changed files with 528 additions and 0 deletions

View file

@ -0,0 +1,79 @@
/**
* POST /api/pax8/company-matches/[id]/resolve
* Body: { companyId: number, note?: string }
*
* Resolves a flagged PAX8 -> Autotask company match by linking the PAX8
* company to the given Autotask company id. Unlike the read-side GET
* /api/pax8/company-matches (D-07, requireAuth only), this mutation is
* admin-gated (D-08) mutating a match crosses a privilege boundary.
*
* companyId is NOT required to be one of the review's candidate_company_ids
* (D-05 manual-search fallback / D-09 zero-candidate case) the resolver
* validates existence + active state instead of candidate membership.
*/
import { NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';
import { requirePermission } from '@/lib/auth-utils';
import postgresClient from '@/lib/services/postgres-client';
import { resolvePax8CompanyMatch } from '@/lib/services/pax8-company-match-resolver';
const ResolveBody = z.object({
companyId: z.number().int().positive(),
note: z.string().max(500).optional(),
});
export async function POST(
request: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
const { session, error } = await requirePermission('admin', 'access');
if (error) return error;
const { id } = await params;
if (!/^[0-9a-f-]{36}$/i.test(id)) {
return NextResponse.json({ error: 'Invalid review id' }, { status: 400 });
}
let body: unknown;
try {
body = await request.json();
} catch {
return NextResponse.json({ error: 'Invalid JSON body' }, { status: 400 });
}
const parsed = ResolveBody.safeParse(body);
if (!parsed.success) {
return NextResponse.json(
{ error: 'Invalid payload', details: parsed.error.flatten() },
{ status: 400 }
);
}
try {
const result = await postgresClient.transaction((tx) =>
resolvePax8CompanyMatch(tx, {
reviewId: id,
companyId: parsed.data.companyId,
note: parsed.data.note ?? null,
userId: session?.user?.id ?? null,
})
);
if (result.ok) {
return NextResponse.json({ ok: true, resolvedToCompanyId: result.resolvedToCompanyId });
}
const statusByCode: Record<typeof result.code, number> = {
not_found: 404,
already_resolved: 409,
company_not_found: 400,
};
return NextResponse.json({ error: result.message }, { status: statusByCode[result.code] });
} catch (err) {
console.error('Failed to resolve PAX8 company match:', err);
return NextResponse.json(
{ error: 'Failed to resolve PAX8 company match', message: err instanceof Error ? err.message : 'Unknown error' },
{ status: 500 }
);
}
}

View file

@ -0,0 +1,94 @@
/**
* GET /api/pax8/company-matches
* Returns unresolved PAX8 company match reviews with bulk-fetched candidate
* Autotask company names, paged.
* Query params:
* limit (default 50, max 200)
* offset (default 0)
*
* D-07: gated by requireAuth() only viewing the flagged-match queue is
* manager-visible; only the resolve mutation (POST .../[id]/resolve) is
* admin-gated.
*/
import { NextRequest, NextResponse } from 'next/server';
import { requireAuth } from '@/lib/auth-utils';
import postgresClient from '@/lib/services/postgres-client';
interface ReviewRow {
id: string;
detected_at: string;
candidate_company_ids: number[];
match_confidences: string[];
pax8_company_id: string;
pax8_company_name: string;
}
interface CompanyRow {
id: string;
company_name: string;
}
export async function GET(request: NextRequest) {
const { error } = await requireAuth();
if (error) return error;
const url = request.nextUrl;
const limit = Math.min(parseInt(url.searchParams.get('limit') ?? '50', 10) || 50, 200);
const offset = Math.max(parseInt(url.searchParams.get('offset') ?? '0', 10) || 0, 0);
try {
const reviews = await postgresClient.query<ReviewRow>(
`SELECT r.id::text, r.detected_at::text, r.candidate_company_ids, r.match_confidences,
pc.id AS pax8_company_id, pc.name AS pax8_company_name
FROM pax8_company_match_review r
JOIN pax8_companies pc ON pc.id = r.pax8_company_id
WHERE r.resolved_at IS NULL
ORDER BY r.detected_at DESC
LIMIT $1 OFFSET $2`,
[limit, offset]
);
// Bulk-fetch all candidate company names in one query.
const allCandidateIds = new Set<number>();
for (const r of reviews.rows) {
for (const id of r.candidate_company_ids ?? []) allCandidateIds.add(Number(id));
}
const nameMap = new Map<number, string>();
if (allCandidateIds.size > 0) {
const companyRes = await postgresClient.query<CompanyRow>(
`SELECT id, company_name FROM companies WHERE id = ANY($1::bigint[])`,
[Array.from(allCandidateIds)]
);
for (const c of companyRes.rows) nameMap.set(Number(c.id), c.company_name);
}
const totalRes = await postgresClient.query<{ count: string }>(
`SELECT COUNT(*)::text AS count FROM pax8_company_match_review WHERE resolved_at IS NULL`
);
const total = parseInt(totalRes.rows[0]?.count ?? '0', 10);
const items = reviews.rows.map((r) => ({
id: r.id,
detectedAt: r.detected_at,
pax8CompanyId: r.pax8_company_id,
pax8CompanyName: r.pax8_company_name,
candidates: (r.candidate_company_ids ?? []).map((companyId, i) => {
const numId = Number(companyId);
return {
companyId: numId,
companyName: nameMap.get(numId) ?? null,
confidence: r.match_confidences?.[i] ?? null,
};
}),
}));
return NextResponse.json({ items, total, limit, offset });
} catch (error) {
console.error('Failed to fetch PAX8 company match review queue:', error);
return NextResponse.json(
{ error: 'Failed to fetch PAX8 company match review queue', message: error instanceof Error ? error.message : 'Unknown error' },
{ status: 500 }
);
}
}