wulf-pulse/app/api/pax8/sync/route.ts
lorentz fdc9919381 feat(13-02): gate POST /api/pax8/sync on the disabled toggle
- Return 403 when integration_settings.key='pax8' has disabled=true
- Check runs as the first statement, before isSyncInProgress()
- GET handler unchanged; no new imports (postgresClient already imported)
2026-07-11 09:46:20 -04:00

64 lines
2.1 KiB
TypeScript

import { NextRequest, NextResponse } from 'next/server';
import { getPax8SyncService } from '@/lib/services/pax8-sync-service';
import postgresClient from '@/lib/services/postgres-client';
export async function POST(req: NextRequest) {
const disabledRes = await postgresClient.query<{ disabled: boolean }>(
`SELECT disabled FROM integration_settings WHERE key = 'pax8'`
);
if (disabledRes.rows[0]?.disabled === true) {
return NextResponse.json(
{ error: 'PAX8 is disabled', message: 'PAX8 sync is disabled via /admin/integrations' },
{ status: 403 }
);
}
const body = await req.json().catch(() => ({}));
const triggeredBy = body.triggeredBy || 'manual';
const svc = getPax8SyncService();
if (svc.isSyncInProgress()) {
return NextResponse.json({ error: 'Sync already in progress' }, { status: 409 });
}
// Fire and forget — return immediately, sync runs in background
svc.fullSync(triggeredBy).catch(err =>
console.error('[Pax8Sync] Background sync error:', err.message)
);
return NextResponse.json({ ok: true, message: 'PAX8 sync started' });
}
export async function GET() {
try {
const svc = getPax8SyncService();
const inProgress = svc.isSyncInProgress();
const counts = await postgresClient.query(`
SELECT
(SELECT COUNT(*) FROM pax8_companies WHERE is_deleted = false) AS companies,
(SELECT COUNT(*) FROM pax8_subscriptions WHERE is_deleted = false) AS subscriptions,
(SELECT COUNT(*) FROM pax8_products WHERE is_deleted = false) AS products
`);
const history = await postgresClient.query(
`SELECT id, sync_type, status, started_at, completed_at,
records_added, records_updated, records_deleted, error_message, triggered_by
FROM sync_history
WHERE entity_type = 'pax8'
ORDER BY started_at DESC
LIMIT 10`
);
return NextResponse.json({
inProgress,
counts: counts.rows[0],
history: history.rows,
});
} catch (err) {
return NextResponse.json(
{ error: err instanceof Error ? err.message : 'Failed to get PAX8 sync status' },
{ status: 500 }
);
}
}