Initial commit: Port Nimara CRM (Layers 0-4)
Some checks failed
Build & Push Docker Images / build-and-push (push) Has been cancelled
Build & Push Docker Images / deploy (push) Has been cancelled
Build & Push Docker Images / lint (push) Has been cancelled

Full CRM rebuild with Next.js 15, TypeScript, Tailwind, Drizzle ORM,
PostgreSQL, Redis, BullMQ, MinIO, and Socket.io. Includes 461 source
files covering clients, berths, interests/pipeline, documents/EOI,
expenses/invoices, email, notifications, dashboard, admin, and
client portal. CI/CD via Gitea Actions with Docker builds.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-03-26 11:52:51 +01:00
commit 67d7e6e3d5
572 changed files with 86496 additions and 0 deletions

View File

@@ -0,0 +1,4 @@
import { auth } from '@/lib/auth';
import { toNextJsHandler } from 'better-auth/next-js';
export const { GET, POST } = toNextJsHandler(auth);

View File

@@ -0,0 +1,68 @@
import { NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { redis } from '@/lib/redis';
import { minioClient } from '@/lib/minio';
import { env } from '@/lib/env';
import { sql } from 'drizzle-orm';
type CheckStatus = 'ok' | 'error';
interface HealthChecks {
postgres: CheckStatus;
redis: CheckStatus;
minio: CheckStatus;
}
interface HealthResponse {
status: 'healthy' | 'degraded';
checks: HealthChecks;
timestamp: string;
}
export async function GET(): Promise<NextResponse<HealthResponse>> {
const checks: HealthChecks = {
postgres: 'error',
redis: 'error',
minio: 'error',
};
await Promise.allSettled([
db
.execute(sql`SELECT 1`)
.then(() => {
checks.postgres = 'ok';
})
.catch(() => {
checks.postgres = 'error';
}),
redis
.ping()
.then(() => {
checks.redis = 'ok';
})
.catch(() => {
checks.redis = 'error';
}),
minioClient
.bucketExists(env.MINIO_BUCKET)
.then(() => {
checks.minio = 'ok';
})
.catch(() => {
checks.minio = 'error';
}),
]);
const allHealthy = Object.values(checks).every((s) => s === 'ok');
const status: HealthResponse['status'] = allHealthy ? 'healthy' : 'degraded';
const body: HealthResponse = {
status,
checks,
timestamp: new Date().toISOString(),
};
return NextResponse.json(body, { status: allHealthy ? 200 : 503 });
}

View File

@@ -0,0 +1,12 @@
import { NextResponse } from 'next/server';
import { PORTAL_COOKIE } from '@/lib/portal/auth';
import { env } from '@/lib/env';
export async function POST(): Promise<NextResponse> {
const response = NextResponse.redirect(new URL('/portal/login', env.APP_URL));
response.cookies.delete(PORTAL_COOKIE);
return response;
}

View File

@@ -0,0 +1,28 @@
import { NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';
import { requestMagicLink } from '@/lib/services/portal.service';
import { logger } from '@/lib/logger';
const bodySchema = z.object({
email: z.string().email(),
});
export async function POST(req: NextRequest): Promise<NextResponse> {
try {
const body = await req.json();
const parsed = bodySchema.safeParse(body);
if (!parsed.success) {
return NextResponse.json({ error: 'Invalid email address' }, { status: 400 });
}
await requestMagicLink(parsed.data.email);
// Always return success to prevent email enumeration
return NextResponse.json({ success: true });
} catch (error) {
logger.error({ error }, 'Portal magic link request failed');
return NextResponse.json({ error: 'Failed to process request' }, { status: 500 });
}
}

View File

@@ -0,0 +1,38 @@
import { NextRequest, NextResponse } from 'next/server';
import { verifyPortalToken, PORTAL_COOKIE } from '@/lib/portal/auth';
import { env } from '@/lib/env';
import { logger } from '@/lib/logger';
export async function GET(req: NextRequest): Promise<NextResponse> {
try {
const token = req.nextUrl.searchParams.get('token');
if (!token) {
return NextResponse.redirect(new URL('/portal/login?error=missing_token', env.APP_URL));
}
const session = await verifyPortalToken(token);
if (!session) {
return NextResponse.redirect(new URL('/portal/login?error=invalid_token', env.APP_URL));
}
const response = NextResponse.redirect(new URL('/portal/dashboard', env.APP_URL));
response.cookies.set(PORTAL_COOKIE, token, {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'lax',
path: '/',
maxAge: 60 * 60 * 24, // 24 hours
});
logger.info({ clientId: session.clientId }, 'Portal session created');
return response;
} catch (error) {
logger.error({ error }, 'Portal token verification failed');
return NextResponse.redirect(new URL('/portal/login?error=server_error', env.APP_URL));
}
}

View File

@@ -0,0 +1,20 @@
import { NextResponse } from 'next/server';
import { withPortalAuth } from '@/lib/portal/helpers';
import { getPortalDashboard } from '@/lib/services/portal.service';
import { logger } from '@/lib/logger';
export const GET = withPortalAuth(async (_req, session) => {
try {
const dashboard = await getPortalDashboard(session.clientId, session.portId);
if (!dashboard) {
return NextResponse.json({ error: 'Client not found' }, { status: 404 });
}
return NextResponse.json({ data: dashboard });
} catch (error) {
logger.error({ error }, 'Portal dashboard fetch failed');
return NextResponse.json({ error: 'Failed to load dashboard' }, { status: 500 });
}
});

View File

@@ -0,0 +1,26 @@
import { NextResponse } from 'next/server';
import { withPortalAuth } from '@/lib/portal/helpers';
import { getDocumentDownloadUrl } from '@/lib/services/portal.service';
import { logger } from '@/lib/logger';
export const GET = withPortalAuth(async (_req, session, params) => {
try {
const documentId = params.documentId;
if (!documentId) {
return NextResponse.json({ error: 'Document ID required' }, { status: 400 });
}
const url = await getDocumentDownloadUrl(session.clientId, documentId, session.portId);
if (!url) {
return NextResponse.json({ error: 'Document not found' }, { status: 404 });
}
return NextResponse.json({ url });
} catch (error) {
logger.error({ error }, 'Portal document download URL fetch failed');
return NextResponse.json({ error: 'Failed to generate download URL' }, { status: 500 });
}
});

View File

@@ -0,0 +1,15 @@
import { NextResponse } from 'next/server';
import { withPortalAuth } from '@/lib/portal/helpers';
import { getClientDocuments } from '@/lib/services/portal.service';
import { logger } from '@/lib/logger';
export const GET = withPortalAuth(async (_req, session) => {
try {
const data = await getClientDocuments(session.clientId, session.portId);
return NextResponse.json({ data });
} catch (error) {
logger.error({ error }, 'Portal documents fetch failed');
return NextResponse.json({ error: 'Failed to load documents' }, { status: 500 });
}
});

View File

@@ -0,0 +1,15 @@
import { NextResponse } from 'next/server';
import { withPortalAuth } from '@/lib/portal/helpers';
import { getClientInterests } from '@/lib/services/portal.service';
import { logger } from '@/lib/logger';
export const GET = withPortalAuth(async (_req, session) => {
try {
const data = await getClientInterests(session.clientId, session.portId);
return NextResponse.json({ data });
} catch (error) {
logger.error({ error }, 'Portal interests fetch failed');
return NextResponse.json({ error: 'Failed to load interests' }, { status: 500 });
}
});

View File

@@ -0,0 +1,15 @@
import { NextResponse } from 'next/server';
import { withPortalAuth } from '@/lib/portal/helpers';
import { getClientInvoices } from '@/lib/services/portal.service';
import { logger } from '@/lib/logger';
export const GET = withPortalAuth(async (_req, session) => {
try {
const data = await getClientInvoices(session.clientId, session.portId);
return NextResponse.json({ data });
} catch (error) {
logger.error({ error }, 'Portal invoices fetch failed');
return NextResponse.json({ error: 'Failed to load invoices' }, { status: 500 });
}
});

View File

@@ -0,0 +1,167 @@
import { NextRequest, NextResponse } from 'next/server';
import { and, eq } from 'drizzle-orm';
import { db } from '@/lib/db';
import { interests } from '@/lib/db/schema/interests';
import { clients, clientContacts } from '@/lib/db/schema/clients';
import { createAuditLog } from '@/lib/audit';
import { errorResponse, RateLimitError } from '@/lib/errors';
import { publicInterestSchema } from '@/lib/validators/interests';
// ─── Simple in-memory rate limiter ───────────────────────────────────────────
// Max 5 requests per hour per IP
const ipHits = new Map<string, { count: number; resetAt: number }>();
const WINDOW_MS = 60 * 60 * 1000; // 1 hour
const MAX_HITS = 5;
function checkRateLimit(ip: string): void {
const now = Date.now();
const entry = ipHits.get(ip);
if (!entry || now > entry.resetAt) {
ipHits.set(ip, { count: 1, resetAt: now + WINDOW_MS });
return;
}
if (entry.count >= MAX_HITS) {
const retryAfter = Math.ceil((entry.resetAt - now) / 1000);
throw new RateLimitError(retryAfter);
}
entry.count += 1;
}
// POST /api/public/interests — unauthenticated public interest registration
export async function POST(req: NextRequest) {
try {
const ip = req.headers.get('x-forwarded-for')?.split(',')[0]?.trim() ?? 'unknown';
checkRateLimit(ip);
const body = await req.json();
const data = publicInterestSchema.parse(body);
// Resolve portId from query param or header (public endpoints need explicit port)
const portId = req.nextUrl.searchParams.get('portId') ?? req.headers.get('X-Port-Id');
if (!portId) {
return NextResponse.json({ error: 'Port context required' }, { status: 400 });
}
// Find or create client by email
let clientId: string;
const existingContact = await db.query.clientContacts.findFirst({
where: and(
eq(clientContacts.channel, 'email'),
eq(clientContacts.value, data.email),
),
});
if (existingContact) {
// Find the client associated with this contact
const existingClient = await db.query.clients.findFirst({
where: eq(clients.id, existingContact.clientId),
});
if (existingClient && existingClient.portId === portId) {
clientId = existingClient.id;
} else {
// Create new client for this port
const [newClient] = await db
.insert(clients)
.values({
portId,
fullName: data.fullName,
companyName: data.companyName,
yachtName: data.yachtName,
yachtLengthFt: data.yachtLengthFt != null ? String(data.yachtLengthFt) : undefined,
yachtWidthFt: data.yachtWidthFt != null ? String(data.yachtWidthFt) : undefined,
yachtDraftFt: data.yachtDraftFt != null ? String(data.yachtDraftFt) : undefined,
berthSizeDesired: data.preferredBerthSize,
source: 'website',
})
.returning();
clientId = newClient!.id;
await db.insert(clientContacts).values({
clientId,
channel: 'email',
value: data.email,
isPrimary: true,
});
if (data.phone) {
await db.insert(clientContacts).values({
clientId,
channel: 'phone',
value: data.phone,
isPrimary: false,
});
}
}
} else {
// Create brand-new client
const [newClient] = await db
.insert(clients)
.values({
portId,
fullName: data.fullName,
companyName: data.companyName,
yachtName: data.yachtName,
yachtLengthFt: data.yachtLengthFt != null ? String(data.yachtLengthFt) : undefined,
yachtWidthFt: data.yachtWidthFt != null ? String(data.yachtWidthFt) : undefined,
yachtDraftFt: data.yachtDraftFt != null ? String(data.yachtDraftFt) : undefined,
berthSizeDesired: data.preferredBerthSize,
source: 'website',
})
.returning();
clientId = newClient!.id;
await db.insert(clientContacts).values({
clientId,
channel: 'email',
value: data.email,
isPrimary: true,
});
if (data.phone) {
await db.insert(clientContacts).values({
clientId,
channel: 'phone',
value: data.phone,
isPrimary: false,
});
}
}
// Create the interest
const [interest] = await db
.insert(interests)
.values({
portId,
clientId,
source: 'website',
pipelineStage: 'open',
notes: data.notes,
})
.returning();
void createAuditLog({
userId: null as unknown as string,
portId,
action: 'create',
entityType: 'interest',
entityId: interest!.id,
newValue: { clientId, source: 'website', pipelineStage: 'open' },
metadata: { type: 'public_registration', ip },
ipAddress: ip,
userAgent: req.headers.get('user-agent') ?? 'unknown',
});
return NextResponse.json(
{ data: { id: interest!.id, message: 'Interest registered successfully' } },
{ status: 201 },
);
} catch (error) {
return errorResponse(error);
}
}

View File

@@ -0,0 +1,18 @@
import { NextResponse } from 'next/server';
import { withAuth } from '@/lib/api/helpers';
import { errorResponse } from '@/lib/errors';
import { getActiveConnections } from '@/lib/services/system-monitoring.service';
export const GET = withAuth(async (_req, ctx) => {
try {
if (!ctx.isSuperAdmin) {
return NextResponse.json({ error: 'Insufficient permissions' }, { status: 403 });
}
const connections = await getActiveConnections();
return NextResponse.json({ data: connections });
} catch (error) {
return errorResponse(error);
}
});

View File

@@ -0,0 +1,69 @@
import { NextRequest, NextResponse } from 'next/server';
import { withAuth, withPermission } from '@/lib/api/helpers';
import { errorResponse, NotFoundError } from '@/lib/errors';
import { updateFieldSchema } from '@/lib/validators/custom-fields';
import {
updateDefinition,
deleteDefinition,
} from '@/lib/services/custom-fields.service';
export const PATCH = withAuth(
withPermission(
'admin',
'manage_custom_fields',
async (req: NextRequest, ctx, params) => {
try {
const { fieldId } = params;
if (!fieldId) throw new NotFoundError('Custom field');
const body = await req.json();
// Parse only allowed fields; if fieldType sneaks in, the service will catch it
const data = updateFieldSchema.parse(body);
// Pass raw body too so service can detect fieldType mutation attempts
const updated = await updateDefinition(
ctx.portId,
fieldId,
ctx.userId,
{ ...data, ...(body.fieldType !== undefined && { fieldType: body.fieldType }) },
{
userId: ctx.userId,
portId: ctx.portId,
ipAddress: ctx.ipAddress,
userAgent: ctx.userAgent,
},
);
return NextResponse.json({ data: updated });
} catch (error) {
return errorResponse(error);
}
},
),
);
export const DELETE = withAuth(
withPermission(
'admin',
'manage_custom_fields',
async (_req: NextRequest, ctx, params) => {
try {
const { fieldId } = params;
if (!fieldId) throw new NotFoundError('Custom field');
const result = await deleteDefinition(ctx.portId, fieldId, ctx.userId, {
userId: ctx.userId,
portId: ctx.portId,
ipAddress: ctx.ipAddress,
userAgent: ctx.userAgent,
});
return NextResponse.json({ data: result });
} catch (error) {
return errorResponse(error);
}
},
),
);

View File

@@ -0,0 +1,43 @@
import { NextRequest, NextResponse } from 'next/server';
import { withAuth, withPermission } from '@/lib/api/helpers';
import { errorResponse } from '@/lib/errors';
import { createFieldSchema } from '@/lib/validators/custom-fields';
import {
listDefinitions,
createDefinition,
} from '@/lib/services/custom-fields.service';
export const GET = withAuth(
withPermission('admin', 'manage_custom_fields', async (req: NextRequest, ctx) => {
try {
const { searchParams } = new URL(req.url);
const entityType = searchParams.get('entityType') ?? undefined;
const data = await listDefinitions(ctx.portId, entityType);
return NextResponse.json({ data });
} catch (error) {
return errorResponse(error);
}
}),
);
export const POST = withAuth(
withPermission('admin', 'manage_custom_fields', async (req: NextRequest, ctx) => {
try {
const body = await req.json();
const data = createFieldSchema.parse(body);
const definition = await createDefinition(ctx.portId, ctx.userId, data, {
userId: ctx.userId,
portId: ctx.portId,
ipAddress: ctx.ipAddress,
userAgent: ctx.userAgent,
});
return NextResponse.json({ data: definition }, { status: 201 });
} catch (error) {
return errorResponse(error);
}
}),
);

View File

@@ -0,0 +1,21 @@
import { NextRequest, NextResponse } from 'next/server';
import { withAuth } from '@/lib/api/helpers';
import { errorResponse } from '@/lib/errors';
import { getRecentErrors } from '@/lib/services/system-monitoring.service';
export const GET = withAuth(async (req: NextRequest, ctx) => {
try {
if (!ctx.isSuperAdmin) {
return NextResponse.json({ error: 'Insufficient permissions' }, { status: 403 });
}
const url = new URL(req.url);
const limit = Math.min(100, Math.max(1, parseInt(url.searchParams.get('limit') ?? '20', 10)));
const errors = await getRecentErrors(limit);
return NextResponse.json({ data: errors });
} catch (error) {
return errorResponse(error);
}
});

View File

@@ -0,0 +1,18 @@
import { NextResponse } from 'next/server';
import { withAuth } from '@/lib/api/helpers';
import { errorResponse } from '@/lib/errors';
import { healthCheck } from '@/lib/services/system-monitoring.service';
export const GET = withAuth(async (_req, ctx) => {
try {
if (!ctx.isSuperAdmin) {
return NextResponse.json({ error: 'Insufficient permissions' }, { status: 403 });
}
const status = await healthCheck();
return NextResponse.json({ data: status });
} catch (error) {
return errorResponse(error);
}
});

View File

@@ -0,0 +1,29 @@
import { NextResponse } from 'next/server';
import { withAuth } from '@/lib/api/helpers';
import { errorResponse } from '@/lib/errors';
import { retryJob } from '@/lib/services/system-monitoring.service';
import { QUEUE_CONFIGS, type QueueName } from '@/lib/queue';
export const POST = withAuth(async (_req, ctx, params) => {
try {
if (!ctx.isSuperAdmin) {
return NextResponse.json({ error: 'Insufficient permissions' }, { status: 403 });
}
const queueName = params['queueName'];
const jobId = params['jobId'];
if (!queueName || !jobId) {
return NextResponse.json({ error: 'Missing parameters' }, { status: 400 });
}
const validQueues = Object.keys(QUEUE_CONFIGS) as QueueName[];
if (!validQueues.includes(queueName as QueueName)) {
return NextResponse.json({ error: 'Invalid queue name' }, { status: 400 });
}
await retryJob(queueName as QueueName, jobId, ctx.userId);
return NextResponse.json({ data: { success: true } });
} catch (error) {
return errorResponse(error);
}
});

View File

@@ -0,0 +1,29 @@
import { NextResponse } from 'next/server';
import { withAuth } from '@/lib/api/helpers';
import { errorResponse } from '@/lib/errors';
import { deleteJob } from '@/lib/services/system-monitoring.service';
import { QUEUE_CONFIGS, type QueueName } from '@/lib/queue';
export const DELETE = withAuth(async (_req, ctx, params) => {
try {
if (!ctx.isSuperAdmin) {
return NextResponse.json({ error: 'Insufficient permissions' }, { status: 403 });
}
const queueName = params['queueName'];
const jobId = params['jobId'];
if (!queueName || !jobId) {
return NextResponse.json({ error: 'Missing parameters' }, { status: 400 });
}
const validQueues = Object.keys(QUEUE_CONFIGS) as QueueName[];
if (!validQueues.includes(queueName as QueueName)) {
return NextResponse.json({ error: 'Invalid queue name' }, { status: 400 });
}
await deleteJob(queueName as QueueName, jobId, ctx.userId);
return new NextResponse(null, { status: 204 });
} catch (error) {
return errorResponse(error);
}
});

View File

@@ -0,0 +1,35 @@
import { NextRequest, NextResponse } from 'next/server';
import { withAuth } from '@/lib/api/helpers';
import { errorResponse } from '@/lib/errors';
import { getQueueJobs } from '@/lib/services/system-monitoring.service';
import { QUEUE_CONFIGS, type QueueName } from '@/lib/queue';
export const GET = withAuth(async (req: NextRequest, ctx, params) => {
try {
if (!ctx.isSuperAdmin) {
return NextResponse.json({ error: 'Insufficient permissions' }, { status: 403 });
}
const { queueName } = params;
const validQueues = Object.keys(QUEUE_CONFIGS) as QueueName[];
if (!validQueues.includes(queueName as QueueName)) {
return NextResponse.json({ error: 'Invalid queue name' }, { status: 400 });
}
const url = new URL(req.url);
const status = (url.searchParams.get('status') ?? 'failed') as
| 'waiting'
| 'active'
| 'completed'
| 'failed'
| 'delayed';
const page = Math.max(1, parseInt(url.searchParams.get('page') ?? '1', 10));
const limit = Math.min(100, Math.max(1, parseInt(url.searchParams.get('limit') ?? '20', 10)));
const result = await getQueueJobs(queueName as QueueName, status, page, limit);
return NextResponse.json({ data: result });
} catch (error) {
return errorResponse(error);
}
});

View File

@@ -0,0 +1,18 @@
import { NextResponse } from 'next/server';
import { withAuth } from '@/lib/api/helpers';
import { errorResponse } from '@/lib/errors';
import { getQueueDashboard } from '@/lib/services/system-monitoring.service';
export const GET = withAuth(async (_req, ctx) => {
try {
if (!ctx.isSuperAdmin) {
return NextResponse.json({ error: 'Insufficient permissions' }, { status: 403 });
}
const queues = await getQueueDashboard();
return NextResponse.json({ data: queues });
} catch (error) {
return errorResponse(error);
}
});

View File

@@ -0,0 +1,30 @@
import { NextResponse } from 'next/server';
import { eq } from 'drizzle-orm';
import { withAuth, withPermission } from '@/lib/api/helpers';
import { db } from '@/lib/db';
import { roles } from '@/lib/db/schema';
import { errorResponse, NotFoundError } from '@/lib/errors';
export const GET = withAuth(
withPermission('admin', 'manage_users', async (_req, _ctx, params) => {
try {
const { id } = params;
if (!id) {
throw new NotFoundError('Role');
}
const role = await db.query.roles.findFirst({
where: eq(roles.id, id),
});
if (!role) {
throw new NotFoundError('Role');
}
return NextResponse.json({ data: role });
} catch (error) {
return errorResponse(error);
}
}),
);

View File

@@ -0,0 +1,19 @@
import { NextResponse } from 'next/server';
import { withAuth, withPermission } from '@/lib/api/helpers';
import { db } from '@/lib/db';
import { errorResponse } from '@/lib/errors';
export const GET = withAuth(
withPermission('admin', 'manage_users', async (_req, _ctx) => {
try {
const data = await db.query.roles.findMany({
orderBy: (roles, { asc }) => [asc(roles.name)],
});
return NextResponse.json({ data });
} catch (error) {
return errorResponse(error);
}
}),
);

View File

@@ -0,0 +1,37 @@
import { NextResponse } from 'next/server';
import { withAuth, withPermission } from '@/lib/api/helpers';
import { parseBody } from '@/lib/api/route-helpers';
import { errorResponse } from '@/lib/errors';
import { rollbackAdminTemplate } from '@/lib/services/document-templates.service';
import { rollbackAdminTemplateSchema } from '@/lib/validators/document-templates';
/**
* POST /api/v1/admin/templates/[templateId]/rollback
* Rolls the template back to a previously saved version.
* Creates a new version number (current + 1) with the restored content.
*
* Body: { version: number }
*/
export const POST = withAuth(
withPermission('documents', 'manage', async (req, ctx, params) => {
try {
const body = await parseBody(req, rollbackAdminTemplateSchema);
const result = await rollbackAdminTemplate(
ctx.portId,
params.templateId!,
body.version,
ctx.userId,
{
userId: ctx.userId,
portId: ctx.portId,
ipAddress: ctx.ipAddress,
userAgent: ctx.userAgent,
},
);
return NextResponse.json({ data: result });
} catch (error) {
return errorResponse(error);
}
}),
);

View File

@@ -0,0 +1,78 @@
import { NextResponse } from 'next/server';
import { withAuth, withPermission } from '@/lib/api/helpers';
import { parseBody } from '@/lib/api/route-helpers';
import { errorResponse } from '@/lib/errors';
import {
getAdminTemplate,
updateAdminTemplate,
deleteAdminTemplate,
} from '@/lib/services/document-templates.service';
import { updateAdminTemplateSchema } from '@/lib/validators/document-templates';
/**
* GET /api/v1/admin/templates/[templateId]
* Retrieve a single TipTap-based document template.
*/
export const GET = withAuth(
withPermission('documents', 'manage', async (req, ctx, params) => {
try {
const template = await getAdminTemplate(ctx.portId, params.templateId!);
return NextResponse.json({ data: template });
} catch (error) {
return errorResponse(error);
}
}),
);
/**
* PATCH /api/v1/admin/templates/[templateId]
* Update a TipTap-based document template. Increments version if content changes.
*/
export const PATCH = withAuth(
withPermission('documents', 'manage', async (req, ctx, params) => {
try {
const body = await parseBody(req, updateAdminTemplateSchema);
const updated = await updateAdminTemplate(
ctx.portId,
params.templateId!,
ctx.userId,
body,
{
userId: ctx.userId,
portId: ctx.portId,
ipAddress: ctx.ipAddress,
userAgent: ctx.userAgent,
},
);
return NextResponse.json({ data: updated });
} catch (error) {
return errorResponse(error);
}
}),
);
/**
* DELETE /api/v1/admin/templates/[templateId]
* Delete a TipTap-based document template.
*/
export const DELETE = withAuth(
withPermission('documents', 'manage', async (req, ctx, params) => {
try {
await deleteAdminTemplate(
ctx.portId,
params.templateId!,
ctx.userId,
{
userId: ctx.userId,
portId: ctx.portId,
ipAddress: ctx.ipAddress,
userAgent: ctx.userAgent,
},
);
return new NextResponse(null, { status: 204 });
} catch (error) {
return errorResponse(error);
}
}),
);

View File

@@ -0,0 +1,23 @@
import { NextResponse } from 'next/server';
import { withAuth, withPermission } from '@/lib/api/helpers';
import { errorResponse } from '@/lib/errors';
import { getAdminTemplateVersions } from '@/lib/services/document-templates.service';
/**
* GET /api/v1/admin/templates/[templateId]/versions
* Returns version history for a template, sourced from audit_logs.
*/
export const GET = withAuth(
withPermission('documents', 'manage', async (req, ctx, params) => {
try {
const versions = await getAdminTemplateVersions(
ctx.portId,
params.templateId!,
);
return NextResponse.json({ data: versions });
} catch (error) {
return errorResponse(error);
}
}),
);

View File

@@ -0,0 +1,77 @@
import { NextResponse } from 'next/server';
import { withAuth, withPermission } from '@/lib/api/helpers';
import { parseBody } from '@/lib/api/route-helpers';
import { errorResponse, ValidationError } from '@/lib/errors';
import { generatePdf } from '@/lib/pdf/generate';
import {
validateTipTapDocument,
tipTapToPdfmeTemplate,
buildContentInputsFromDoc,
substituteVariables,
type TipTapNode,
} from '@/lib/pdf/tiptap-to-pdfme';
import { previewAdminTemplateSchema } from '@/lib/validators/document-templates';
/**
* POST /api/v1/admin/templates/preview
*
* Generates a preview PDF from a TipTap JSON content block.
* Returns { data: { pdfBase64: string } } — the client can render this
* in an <iframe src="data:application/pdf;base64,..."> or open in a new tab.
*
* Body:
* content: TipTap JSON document
* sampleData?: Record<string, string> — variable substitutions
*/
export const POST = withAuth(
withPermission('documents', 'manage', async (req, _ctx) => {
try {
const body = await parseBody(req, previewAdminTemplateSchema);
const doc = body.content as unknown as TipTapNode;
const sampleData = body.sampleData ?? {};
// Validate content nodes
const unsupported = validateTipTapDocument(doc);
if (unsupported.length > 0) {
throw new ValidationError(
`Content contains unsupported node types: ${unsupported.join(', ')}`,
);
}
// Substitute variables in text nodes
const substitutedDoc = substituteInDoc(doc, sampleData);
// Convert to pdfme template + inputs
const template = tipTapToPdfmeTemplate(substitutedDoc);
const inputs = buildContentInputsFromDoc(substitutedDoc, template);
const pdfBytes = await generatePdf(template, inputs);
const pdfBase64 = Buffer.from(pdfBytes).toString('base64');
return NextResponse.json({ data: { pdfBase64 } });
} catch (error) {
return errorResponse(error);
}
}),
);
/**
* Deeply substitutes {{variable}} tokens in all text nodes of a TipTap doc.
*/
function substituteInDoc(
node: TipTapNode,
data: Record<string, string>,
): TipTapNode {
if (node.type === 'text' && node.text) {
return { ...node, text: substituteVariables(node.text, data) };
}
if (node.content) {
return {
...node,
content: node.content.map((child) => substituteInDoc(child, data)),
};
}
return node;
}

View File

@@ -0,0 +1,50 @@
import { NextResponse } from 'next/server';
import { withAuth, withPermission } from '@/lib/api/helpers';
import { parseQuery, parseBody } from '@/lib/api/route-helpers';
import { errorResponse } from '@/lib/errors';
import {
listAdminTemplates,
createAdminTemplate,
} from '@/lib/services/document-templates.service';
import {
listAdminTemplatesSchema,
createAdminTemplateSchema,
} from '@/lib/validators/document-templates';
/**
* GET /api/v1/admin/templates
* List TipTap-based document templates for the port.
*/
export const GET = withAuth(
withPermission('documents', 'manage', async (req, ctx) => {
try {
const query = parseQuery(req, listAdminTemplatesSchema);
const data = await listAdminTemplates(ctx.portId, query);
return NextResponse.json({ data });
} catch (error) {
return errorResponse(error);
}
}),
);
/**
* POST /api/v1/admin/templates
* Create a new TipTap-based document template.
*/
export const POST = withAuth(
withPermission('documents', 'manage', async (req, ctx) => {
try {
const body = await parseBody(req, createAdminTemplateSchema);
const template = await createAdminTemplate(ctx.portId, ctx.userId, body, {
userId: ctx.userId,
portId: ctx.portId,
ipAddress: ctx.ipAddress,
userAgent: ctx.userAgent,
});
return NextResponse.json({ data: template }, { status: 201 });
} catch (error) {
return errorResponse(error);
}
}),
);

View File

@@ -0,0 +1,25 @@
import { NextResponse } from 'next/server';
import { eq } from 'drizzle-orm';
import { withAuth } from '@/lib/api/helpers';
import { db } from '@/lib/db';
import { userPortRoles, userProfiles } from '@/lib/db/schema';
import { errorResponse } from '@/lib/errors';
export const GET = withAuth(async (_req, ctx) => {
try {
const rows = await db
.select({
id: userPortRoles.userId,
displayName: userProfiles.displayName,
})
.from(userPortRoles)
.innerJoin(userProfiles, eq(userPortRoles.userId, userProfiles.userId))
.where(eq(userPortRoles.portId, ctx.portId))
.orderBy(userProfiles.displayName);
return NextResponse.json({ data: rows });
} catch (error) {
return errorResponse(error);
}
});

View File

@@ -0,0 +1,40 @@
import { NextResponse } from 'next/server';
import { eq } from 'drizzle-orm';
import { withAuth, withPermission } from '@/lib/api/helpers';
import { db } from '@/lib/db';
import { userPortRoles, userProfiles, roles } from '@/lib/db/schema';
import { errorResponse } from '@/lib/errors';
export const GET = withAuth(
withPermission('admin', 'manage_users', async (_req, ctx) => {
try {
const rows = await db
.select({
userId: userPortRoles.userId,
displayName: userProfiles.displayName,
isActive: userProfiles.isActive,
lastLoginAt: userProfiles.lastLoginAt,
roleId: roles.id,
roleName: roles.name,
})
.from(userPortRoles)
.innerJoin(userProfiles, eq(userPortRoles.userId, userProfiles.userId))
.innerJoin(roles, eq(userPortRoles.roleId, roles.id))
.where(eq(userPortRoles.portId, ctx.portId))
.orderBy(userProfiles.displayName);
const data = rows.map((row) => ({
userId: row.userId,
displayName: row.displayName,
isActive: row.isActive,
lastLoginAt: row.lastLoginAt,
role: { id: row.roleId, name: row.roleName },
}));
return NextResponse.json({ data });
} catch (error) {
return errorResponse(error);
}
}),
);

View File

@@ -0,0 +1,22 @@
import { NextRequest, NextResponse } from 'next/server';
import { withAuth, withPermission } from '@/lib/api/helpers';
import { parseQuery } from '@/lib/api/route-helpers';
import { errorResponse } from '@/lib/errors';
import { listDeliveriesSchema } from '@/lib/validators/webhooks';
import { listDeliveries } from '@/lib/services/webhooks.service';
// ─── GET /api/v1/admin/webhooks/[webhookId]/deliveries ────────────────────────
export const GET = withAuth(
withPermission('admin', 'manage_webhooks', async (req: NextRequest, ctx, params) => {
try {
const { webhookId } = params;
const query = parseQuery(req, listDeliveriesSchema);
const result = await listDeliveries(ctx.portId, webhookId!, query);
return NextResponse.json(result);
} catch (error) {
return errorResponse(error);
}
}),
);

View File

@@ -0,0 +1,24 @@
import { NextRequest, NextResponse } from 'next/server';
import { withAuth, withPermission } from '@/lib/api/helpers';
import { errorResponse } from '@/lib/errors';
import { regenerateSecret } from '@/lib/services/webhooks.service';
// ─── POST /api/v1/admin/webhooks/[webhookId]/regenerate-secret ────────────────
export const POST = withAuth(
withPermission('admin', 'manage_webhooks', async (_req: NextRequest, ctx, params) => {
try {
const { webhookId } = params;
const data = await regenerateSecret(ctx.portId, webhookId!, {
userId: ctx.userId,
portId: ctx.portId,
ipAddress: ctx.ipAddress,
userAgent: ctx.userAgent,
});
return NextResponse.json({ data });
} catch (error) {
return errorResponse(error);
}
}),
);

View File

@@ -0,0 +1,64 @@
import { NextRequest, NextResponse } from 'next/server';
import { withAuth, withPermission } from '@/lib/api/helpers';
import { parseBody } from '@/lib/api/route-helpers';
import { errorResponse } from '@/lib/errors';
import { updateWebhookSchema } from '@/lib/validators/webhooks';
import {
getWebhook,
updateWebhook,
deleteWebhook,
} from '@/lib/services/webhooks.service';
// ─── GET /api/v1/admin/webhooks/[webhookId] ───────────────────────────────────
export const GET = withAuth(
withPermission('admin', 'manage_webhooks', async (_req: NextRequest, ctx, params) => {
try {
const { webhookId } = params;
const data = await getWebhook(ctx.portId, webhookId!);
return NextResponse.json({ data });
} catch (error) {
return errorResponse(error);
}
}),
);
// ─── PATCH /api/v1/admin/webhooks/[webhookId] ─────────────────────────────────
export const PATCH = withAuth(
withPermission('admin', 'manage_webhooks', async (req: NextRequest, ctx, params) => {
try {
const { webhookId } = params;
const body = await parseBody(req, updateWebhookSchema);
const data = await updateWebhook(ctx.portId, webhookId!, body, {
userId: ctx.userId,
portId: ctx.portId,
ipAddress: ctx.ipAddress,
userAgent: ctx.userAgent,
});
return NextResponse.json({ data });
} catch (error) {
return errorResponse(error);
}
}),
);
// ─── DELETE /api/v1/admin/webhooks/[webhookId] ────────────────────────────────
export const DELETE = withAuth(
withPermission('admin', 'manage_webhooks', async (_req: NextRequest, ctx, params) => {
try {
const { webhookId } = params;
await deleteWebhook(ctx.portId, webhookId!, {
userId: ctx.userId,
portId: ctx.portId,
ipAddress: ctx.ipAddress,
userAgent: ctx.userAgent,
});
return NextResponse.json({ success: true });
} catch (error) {
return errorResponse(error);
}
}),
);

View File

@@ -0,0 +1,27 @@
import { NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';
import { withAuth, withPermission } from '@/lib/api/helpers';
import { parseBody } from '@/lib/api/route-helpers';
import { errorResponse } from '@/lib/errors';
import { WEBHOOK_EVENTS } from '@/lib/services/webhook-event-map';
import { sendTestWebhook } from '@/lib/services/webhooks.service';
const testWebhookSchema = z.object({
eventType: z.enum(WEBHOOK_EVENTS).default('client.created'),
});
// ─── POST /api/v1/admin/webhooks/[webhookId]/test ─────────────────────────────
export const POST = withAuth(
withPermission('admin', 'manage_webhooks', async (req: NextRequest, ctx, params) => {
try {
const { webhookId } = params;
const body = await parseBody(req, testWebhookSchema);
const result = await sendTestWebhook(ctx.portId, webhookId!, body.eventType);
return NextResponse.json({ data: result });
} catch (error) {
return errorResponse(error);
}
}),
);

View File

@@ -0,0 +1,39 @@
import { NextRequest, NextResponse } from 'next/server';
import { withAuth, withPermission } from '@/lib/api/helpers';
import { parseBody } from '@/lib/api/route-helpers';
import { errorResponse } from '@/lib/errors';
import { createWebhookSchema } from '@/lib/validators/webhooks';
import { listWebhooks, createWebhook } from '@/lib/services/webhooks.service';
// ─── GET /api/v1/admin/webhooks ───────────────────────────────────────────────
export const GET = withAuth(
withPermission('admin', 'manage_webhooks', async (_req: NextRequest, ctx) => {
try {
const data = await listWebhooks(ctx.portId);
return NextResponse.json({ data });
} catch (error) {
return errorResponse(error);
}
}),
);
// ─── POST /api/v1/admin/webhooks ──────────────────────────────────────────────
export const POST = withAuth(
withPermission('admin', 'manage_webhooks', async (req: NextRequest, ctx) => {
try {
const body = await parseBody(req, createWebhookSchema);
const webhook = await createWebhook(ctx.portId, ctx.userId, body, {
userId: ctx.userId,
portId: ctx.portId,
ipAddress: ctx.ipAddress,
userAgent: ctx.userAgent,
});
return NextResponse.json({ data: webhook }, { status: 201 });
} catch (error) {
return errorResponse(error);
}
}),
);

View File

@@ -0,0 +1,24 @@
import { NextResponse } from 'next/server';
import { withAuth } from '@/lib/api/helpers';
import { getEmailDraftResult } from '@/lib/services/email-draft.service';
import { errorResponse } from '@/lib/errors';
export const GET = withAuth(async (_req, _ctx, params) => {
try {
const { jobId } = params;
if (!jobId) {
return NextResponse.json({ error: 'jobId is required' }, { status: 400 });
}
const result = await getEmailDraftResult(jobId);
if (result === null) {
return NextResponse.json({ status: 'processing' });
}
return NextResponse.json({ status: 'complete', data: result });
} catch (error) {
return errorResponse(error);
}
});

View File

@@ -0,0 +1,38 @@
import { NextResponse } from 'next/server';
import { and, eq } from 'drizzle-orm';
import { withAuth } from '@/lib/api/helpers';
import { db } from '@/lib/db';
import { systemSettings } from '@/lib/db/schema/system';
import { requestEmailDraft } from '@/lib/services/email-draft.service';
import { parseBody } from '@/lib/api/route-helpers';
import { requestDraftSchema } from '@/lib/validators/ai';
import { errorResponse } from '@/lib/errors';
export const POST = withAuth(async (req, ctx) => {
try {
// Feature flag check
const flag = await db.query.systemSettings.findFirst({
where: and(
eq(systemSettings.key, 'ai_email_drafts'),
eq(systemSettings.portId, ctx.portId),
),
});
if (flag?.value !== true) {
return NextResponse.json({ error: 'Feature not available' }, { status: 404 });
}
const body = await parseBody(req, requestDraftSchema);
const { jobId } = await requestEmailDraft(ctx.userId, {
interestId: body.interestId,
clientId: body.clientId,
portId: ctx.portId,
context: body.context,
additionalInstructions: body.additionalInstructions,
});
return NextResponse.json({ jobId }, { status: 202 });
} catch (error) {
return errorResponse(error);
}
});

View File

@@ -0,0 +1,28 @@
import { NextResponse } from 'next/server';
import { and, eq } from 'drizzle-orm';
import { withAuth } from '@/lib/api/helpers';
import { db } from '@/lib/db';
import { systemSettings } from '@/lib/db/schema/system';
import { calculateBulkScores } from '@/lib/services/interest-scoring.service';
import { errorResponse } from '@/lib/errors';
export const GET = withAuth(async (_req, ctx) => {
try {
// Feature flag check
const flag = await db.query.systemSettings.findFirst({
where: and(
eq(systemSettings.key, 'ai_interest_scoring'),
eq(systemSettings.portId, ctx.portId),
),
});
if (flag?.value !== true) {
return NextResponse.json({ error: 'Feature not available' }, { status: 404 });
}
const scores = await calculateBulkScores(ctx.portId);
return NextResponse.json({ data: scores });
} catch (error) {
return errorResponse(error);
}
});

View File

@@ -0,0 +1,32 @@
import { NextResponse } from 'next/server';
import { and, eq } from 'drizzle-orm';
import { withAuth } from '@/lib/api/helpers';
import { db } from '@/lib/db';
import { systemSettings } from '@/lib/db/schema/system';
import { calculateInterestScore } from '@/lib/services/interest-scoring.service';
import { parseQuery } from '@/lib/api/route-helpers';
import { requestScoreSchema } from '@/lib/validators/ai';
import { errorResponse } from '@/lib/errors';
export const GET = withAuth(async (req, ctx) => {
try {
// Feature flag check
const flag = await db.query.systemSettings.findFirst({
where: and(
eq(systemSettings.key, 'ai_interest_scoring'),
eq(systemSettings.portId, ctx.portId),
),
});
if (flag?.value !== true) {
return NextResponse.json({ error: 'Feature not available' }, { status: 404 });
}
const { interestId } = parseQuery(req, requestScoreSchema);
const score = await calculateInterestScore(interestId, ctx.portId);
return NextResponse.json({ data: score });
} catch (error) {
return errorResponse(error);
}
});

View File

@@ -0,0 +1,22 @@
import { NextResponse } from 'next/server';
import { withAuth, withPermission } from '@/lib/api/helpers';
import { errorResponse } from '@/lib/errors';
import { exportBerthPdf } from '@/lib/services/record-export';
export const POST = withAuth(
withPermission('berths', 'view', async (req, ctx, params) => {
try {
const pdfBytes = await exportBerthPdf(params.id!, ctx.portId);
return new NextResponse(Buffer.from(pdfBytes), {
status: 200,
headers: {
'Content-Type': 'application/pdf',
'Content-Disposition': 'attachment; filename="berth-spec.pdf"',
},
});
} catch (error) {
return errorResponse(error);
}
}),
);

View File

@@ -0,0 +1,37 @@
import { NextResponse } from 'next/server';
import { withAuth, withPermission } from '@/lib/api/helpers';
import { parseBody } from '@/lib/api/route-helpers';
import { addMaintenanceLogSchema } from '@/lib/validators/berths';
import { getMaintenanceLogs, addMaintenanceLog } from '@/lib/services/berths.service';
import { errorResponse } from '@/lib/errors';
// GET /api/v1/berths/[id]/maintenance
export const GET = withAuth(
withPermission('berths', 'view', async (req, ctx, params) => {
try {
const logs = await getMaintenanceLogs(params.id!, ctx.portId);
return NextResponse.json({ data: logs });
} catch (error) {
return errorResponse(error);
}
}),
);
// POST /api/v1/berths/[id]/maintenance
export const POST = withAuth(
withPermission('berths', 'edit', async (req, ctx, params) => {
try {
const body = await parseBody(req, addMaintenanceLogSchema);
const log = await addMaintenanceLog(params.id!, ctx.portId, body, {
userId: ctx.userId,
portId: ctx.portId,
ipAddress: ctx.ipAddress,
userAgent: ctx.userAgent,
});
return NextResponse.json({ data: log }, { status: 201 });
} catch (error) {
return errorResponse(error);
}
}),
);

View File

@@ -0,0 +1,37 @@
import { NextResponse } from 'next/server';
import { withAuth, withPermission } from '@/lib/api/helpers';
import { parseBody } from '@/lib/api/route-helpers';
import { updateBerthSchema } from '@/lib/validators/berths';
import { getBerthById, updateBerth } from '@/lib/services/berths.service';
import { errorResponse } from '@/lib/errors';
// GET /api/v1/berths/[id]
export const GET = withAuth(
withPermission('berths', 'view', async (req, ctx, params) => {
try {
const berth = await getBerthById(params.id!, ctx.portId);
return NextResponse.json({ data: berth });
} catch (error) {
return errorResponse(error);
}
}),
);
// PATCH /api/v1/berths/[id] — update berth fields (no DELETE — import-only)
export const PATCH = withAuth(
withPermission('berths', 'edit', async (req, ctx, params) => {
try {
const body = await parseBody(req, updateBerthSchema);
const updated = await updateBerth(params.id!, ctx.portId, body, {
userId: ctx.userId,
portId: ctx.portId,
ipAddress: ctx.ipAddress,
userAgent: ctx.userAgent,
});
return NextResponse.json({ data: updated });
} catch (error) {
return errorResponse(error);
}
}),
);

View File

@@ -0,0 +1,25 @@
import { NextResponse } from 'next/server';
import { withAuth, withPermission } from '@/lib/api/helpers';
import { parseBody } from '@/lib/api/route-helpers';
import { updateBerthStatusSchema } from '@/lib/validators/berths';
import { updateBerthStatus } from '@/lib/services/berths.service';
import { errorResponse } from '@/lib/errors';
// PATCH /api/v1/berths/[id]/status
export const PATCH = withAuth(
withPermission('berths', 'edit', async (req, ctx, params) => {
try {
const body = await parseBody(req, updateBerthStatusSchema);
const updated = await updateBerthStatus(params.id!, ctx.portId, body, {
userId: ctx.userId,
portId: ctx.portId,
ipAddress: ctx.ipAddress,
userAgent: ctx.userAgent,
});
return NextResponse.json({ data: updated });
} catch (error) {
return errorResponse(error);
}
}),
);

View File

@@ -0,0 +1,29 @@
import { NextResponse } from 'next/server';
import { z } from 'zod';
import { withAuth, withPermission } from '@/lib/api/helpers';
import { parseBody } from '@/lib/api/route-helpers';
import { setBerthTags } from '@/lib/services/berths.service';
import { errorResponse } from '@/lib/errors';
const setTagsSchema = z.object({
tagIds: z.array(z.string()),
});
// PUT /api/v1/berths/[id]/tags
export const PUT = withAuth(
withPermission('berths', 'edit', async (req, ctx, params) => {
try {
const body = await parseBody(req, setTagsSchema);
const result = await setBerthTags(params.id!, ctx.portId, body.tagIds, {
userId: ctx.userId,
portId: ctx.portId,
ipAddress: ctx.ipAddress,
userAgent: ctx.userAgent,
});
return NextResponse.json({ data: result });
} catch (error) {
return errorResponse(error);
}
}),
);

View File

@@ -0,0 +1,90 @@
import { NextResponse } from 'next/server';
import { and, eq } from 'drizzle-orm';
import { withAuth, withPermission } from '@/lib/api/helpers';
import { parseBody } from '@/lib/api/route-helpers';
import { updateWaitingListSchema } from '@/lib/validators/berths';
import { reorderWaitingListSchema } from '@/lib/validators/interests';
import { getWaitingList, updateWaitingList } from '@/lib/services/berths.service';
import { errorResponse, NotFoundError } from '@/lib/errors';
import { db } from '@/lib/db';
import { berthWaitingList } from '@/lib/db/schema/berths';
// GET /api/v1/berths/[id]/waiting-list
export const GET = withAuth(
withPermission('berths', 'view', async (req, ctx, params) => {
try {
const entries = await getWaitingList(params.id!, ctx.portId);
return NextResponse.json({ data: entries });
} catch (error) {
return errorResponse(error);
}
}),
);
// PUT /api/v1/berths/[id]/waiting-list
export const PUT = withAuth(
withPermission('berths', 'manage_waiting_list', async (req, ctx, params) => {
try {
const body = await parseBody(req, updateWaitingListSchema);
const entries = await updateWaitingList(params.id!, ctx.portId, body, {
userId: ctx.userId,
portId: ctx.portId,
ipAddress: ctx.ipAddress,
userAgent: ctx.userAgent,
});
return NextResponse.json({ data: entries });
} catch (error) {
return errorResponse(error);
}
}),
);
// PATCH /api/v1/berths/[id]/waiting-list — reorder a single entry
export const PATCH = withAuth(
withPermission('berths', 'manage_waiting_list', async (req, ctx, params) => {
try {
const body = await parseBody(req, reorderWaitingListSchema);
const berthId = params.id!;
const entry = await db.query.berthWaitingList.findFirst({
where: and(
eq(berthWaitingList.id, body.entryId),
eq(berthWaitingList.berthId, berthId),
),
});
if (!entry) throw new NotFoundError('Waiting list entry');
if (entry.position !== body.newPosition) {
// Fetch all entries sorted by position
const allEntries = await db
.select()
.from(berthWaitingList)
.where(eq(berthWaitingList.berthId, berthId))
.orderBy(berthWaitingList.position);
// Remove the moved entry then insert at newPosition (1-indexed)
const others = allEntries.filter((e) => e.id !== body.entryId);
others.splice(body.newPosition - 1, 0, entry);
// Update all positions in sequence
for (let i = 0; i < others.length; i++) {
await db
.update(berthWaitingList)
.set({ position: i + 1 })
.where(eq(berthWaitingList.id, others[i]!.id));
}
}
const entries = await db
.select()
.from(berthWaitingList)
.where(eq(berthWaitingList.berthId, berthId))
.orderBy(berthWaitingList.position);
return NextResponse.json({ data: entries });
} catch (error) {
return errorResponse(error);
}
}),
);

View File

@@ -0,0 +1,15 @@
import { NextResponse } from 'next/server';
import { withAuth } from '@/lib/api/helpers';
import { getBerthOptions } from '@/lib/services/berths.service';
import { errorResponse } from '@/lib/errors';
// GET /api/v1/berths/options — lightweight list for selects/comboboxes
export const GET = withAuth(async (req, ctx) => {
try {
const options = await getBerthOptions(ctx.portId);
return NextResponse.json({ data: options });
} catch (error) {
return errorResponse(error);
}
});

View File

@@ -0,0 +1,36 @@
import { NextResponse } from 'next/server';
import { withAuth, withPermission } from '@/lib/api/helpers';
import { parseQuery } from '@/lib/api/route-helpers';
import { listBerthsSchema } from '@/lib/validators/berths';
import { listBerths } from '@/lib/services/berths.service';
import { errorResponse } from '@/lib/errors';
// GET /api/v1/berths — list berths for the current port (no POST — import-only)
export const GET = withAuth(
withPermission('berths', 'view', async (req, ctx) => {
try {
const query = parseQuery(req, listBerthsSchema);
const result = await listBerths(ctx.portId, query);
const page = query.page;
const pageSize = query.limit;
const total = result.total;
const totalPages = Math.ceil(total / pageSize);
return NextResponse.json({
data: result.data,
pagination: {
page,
pageSize,
total,
totalPages,
hasNextPage: page < totalPages,
hasPreviousPage: page > 1,
},
});
} catch (error) {
return errorResponse(error);
}
}),
);

View File

@@ -0,0 +1,54 @@
import { NextResponse } from 'next/server';
import { z } from 'zod';
import { withAuth, withPermission } from '@/lib/api/helpers';
import { parseBody } from '@/lib/api/route-helpers';
import { errorResponse } from '@/lib/errors';
import { updateContact, removeContact } from '@/lib/services/clients.service';
const updateContactSchema = z.object({
channel: z.enum(['email', 'phone', 'whatsapp', 'other']).optional(),
value: z.string().min(1).optional(),
label: z.string().optional(),
isPrimary: z.boolean().optional(),
notes: z.string().optional(),
});
export const PATCH = withAuth(
withPermission('clients', 'edit', async (req, ctx, params) => {
try {
const body = await parseBody(req, updateContactSchema);
const contact = await updateContact(
params.contactId!,
params.id!,
ctx.portId,
body,
{
userId: ctx.userId,
portId: ctx.portId,
ipAddress: ctx.ipAddress,
userAgent: ctx.userAgent,
},
);
return NextResponse.json({ data: contact });
} catch (error) {
return errorResponse(error);
}
}),
);
export const DELETE = withAuth(
withPermission('clients', 'edit', async (req, ctx, params) => {
try {
await removeContact(params.contactId!, params.id!, ctx.portId, {
userId: ctx.userId,
portId: ctx.portId,
ipAddress: ctx.ipAddress,
userAgent: ctx.userAgent,
});
return new NextResponse(null, { status: 204 });
} catch (error) {
return errorResponse(error);
}
}),
);

View File

@@ -0,0 +1,43 @@
import { NextResponse } from 'next/server';
import { z } from 'zod';
import { withAuth, withPermission } from '@/lib/api/helpers';
import { parseBody } from '@/lib/api/route-helpers';
import { errorResponse } from '@/lib/errors';
import { listContacts, addContact } from '@/lib/services/clients.service';
const addContactSchema = z.object({
channel: z.enum(['email', 'phone', 'whatsapp', 'other']),
value: z.string().min(1),
label: z.string().optional(),
isPrimary: z.boolean().optional().default(false),
notes: z.string().optional(),
});
export const GET = withAuth(
withPermission('clients', 'view', async (req, ctx, params) => {
try {
const contacts = await listContacts(params.id!, ctx.portId);
return NextResponse.json({ data: contacts });
} catch (error) {
return errorResponse(error);
}
}),
);
export const POST = withAuth(
withPermission('clients', 'edit', async (req, ctx, params) => {
try {
const body = await parseBody(req, addContactSchema);
const contact = await addContact(params.id!, ctx.portId, body, {
userId: ctx.userId,
portId: ctx.portId,
ipAddress: ctx.ipAddress,
userAgent: ctx.userAgent,
});
return NextResponse.json({ data: contact }, { status: 201 });
} catch (error) {
return errorResponse(error);
}
}),
);

View File

@@ -0,0 +1,22 @@
import { NextResponse } from 'next/server';
import { withAuth, withPermission } from '@/lib/api/helpers';
import { errorResponse } from '@/lib/errors';
import { exportClientPdf } from '@/lib/services/record-export';
export const POST = withAuth(
withPermission('clients', 'view', async (req, ctx, params) => {
try {
const pdfBytes = await exportClientPdf(params.id!, ctx.portId);
return new NextResponse(Buffer.from(pdfBytes), {
status: 200,
headers: {
'Content-Type': 'application/pdf',
'Content-Disposition': 'attachment; filename="client-summary.pdf"',
},
});
} catch (error) {
return errorResponse(error);
}
}),
);

View File

@@ -0,0 +1,63 @@
import { NextResponse } from 'next/server';
import { withAuth, withPermission } from '@/lib/api/helpers';
import { parseBody } from '@/lib/api/route-helpers';
import { createAuditLog } from '@/lib/audit';
import { errorResponse, NotFoundError } from '@/lib/errors';
import { updateNoteSchema } from '@/lib/validators/notes';
import * as notesService from '@/lib/services/notes.service';
export const PATCH = withAuth(
withPermission('clients', 'edit', async (req, ctx, params) => {
try {
const clientId = params.id;
const noteId = params.noteId;
if (!clientId) throw new NotFoundError('Client');
if (!noteId) throw new NotFoundError('Note');
const body = await parseBody(req, updateNoteSchema);
const note = await notesService.update(ctx.portId, 'clients', clientId, noteId, body);
void createAuditLog({
userId: ctx.userId,
portId: ctx.portId,
action: 'update',
entityType: 'client_note',
entityId: noteId,
metadata: { clientId },
ipAddress: ctx.ipAddress,
userAgent: ctx.userAgent,
});
return NextResponse.json({ data: note });
} catch (error) {
return errorResponse(error);
}
}),
);
export const DELETE = withAuth(
withPermission('clients', 'edit', async (_req, ctx, params) => {
try {
const clientId = params.id;
const noteId = params.noteId;
if (!clientId) throw new NotFoundError('Client');
if (!noteId) throw new NotFoundError('Note');
await notesService.deleteNote(ctx.portId, 'clients', clientId, noteId);
void createAuditLog({
userId: ctx.userId,
portId: ctx.portId,
action: 'delete',
entityType: 'client_note',
entityId: noteId,
metadata: { clientId },
ipAddress: ctx.ipAddress,
userAgent: ctx.userAgent,
});
return new NextResponse(null, { status: 204 });
} catch (error) {
return errorResponse(error);
}
}),
);

View File

@@ -0,0 +1,55 @@
import { NextResponse } from 'next/server';
import { withAuth, withPermission } from '@/lib/api/helpers';
import { parseBody } from '@/lib/api/route-helpers';
import { createAuditLog } from '@/lib/audit';
import { errorResponse, NotFoundError } from '@/lib/errors';
import { emitToRoom } from '@/lib/socket/server';
import { createNoteSchema } from '@/lib/validators/notes';
import * as notesService from '@/lib/services/notes.service';
export const GET = withAuth(
withPermission('clients', 'view', async (_req, ctx, params) => {
try {
const clientId = params.id;
if (!clientId) throw new NotFoundError('Client');
const notes = await notesService.listForEntity(ctx.portId, 'clients', clientId);
return NextResponse.json({ data: notes });
} catch (error) {
return errorResponse(error);
}
}),
);
export const POST = withAuth(
withPermission('clients', 'edit', async (req, ctx, params) => {
try {
const clientId = params.id;
if (!clientId) throw new NotFoundError('Client');
const body = await parseBody(req, createNoteSchema);
const note = await notesService.create(ctx.portId, 'clients', clientId, ctx.userId, body);
void createAuditLog({
userId: ctx.userId,
portId: ctx.portId,
action: 'create',
entityType: 'client_note',
entityId: note.id,
metadata: { clientId },
ipAddress: ctx.ipAddress,
userAgent: ctx.userAgent,
});
emitToRoom(`client:${clientId}`, 'client:noteAdded', {
clientId,
noteId: note.id,
authorName: note.authorName ?? ctx.user.name,
preview: note.content.slice(0, 100),
});
return NextResponse.json({ data: note }, { status: 201 });
} catch (error) {
return errorResponse(error);
}
}),
);

View File

@@ -0,0 +1,21 @@
import { NextResponse } from 'next/server';
import { withAuth, withPermission } from '@/lib/api/helpers';
import { errorResponse } from '@/lib/errors';
import { deleteRelationship } from '@/lib/services/clients.service';
export const DELETE = withAuth(
withPermission('clients', 'edit', async (req, ctx, params) => {
try {
await deleteRelationship(params.relId!, params.id!, ctx.portId, {
userId: ctx.userId,
portId: ctx.portId,
ipAddress: ctx.ipAddress,
userAgent: ctx.userAgent,
});
return new NextResponse(null, { status: 204 });
} catch (error) {
return errorResponse(error);
}
}),
);

View File

@@ -0,0 +1,47 @@
import { NextResponse } from 'next/server';
import { z } from 'zod';
import { withAuth, withPermission } from '@/lib/api/helpers';
import { parseBody } from '@/lib/api/route-helpers';
import { errorResponse } from '@/lib/errors';
import { listRelationships, createRelationship } from '@/lib/services/clients.service';
const createRelationshipSchema = z.object({
clientBId: z.string().min(1),
relationshipType: z.enum([
'referred_by',
'broker_for',
'family_member',
'same_vessel',
'custom',
]),
description: z.string().optional(),
});
export const GET = withAuth(
withPermission('clients', 'view', async (req, ctx, params) => {
try {
const relationships = await listRelationships(params.id!, ctx.portId);
return NextResponse.json({ data: relationships });
} catch (error) {
return errorResponse(error);
}
}),
);
export const POST = withAuth(
withPermission('clients', 'edit', async (req, ctx, params) => {
try {
const body = await parseBody(req, createRelationshipSchema);
const rel = await createRelationship(params.id!, ctx.portId, body, {
userId: ctx.userId,
portId: ctx.portId,
ipAddress: ctx.ipAddress,
userAgent: ctx.userAgent,
});
return NextResponse.json({ data: rel }, { status: 201 });
} catch (error) {
return errorResponse(error);
}
}),
);

View File

@@ -0,0 +1,21 @@
import { NextResponse } from 'next/server';
import { withAuth, withPermission } from '@/lib/api/helpers';
import { errorResponse } from '@/lib/errors';
import { restoreClient } from '@/lib/services/clients.service';
export const POST = withAuth(
withPermission('clients', 'edit', async (req, ctx, params) => {
try {
await restoreClient(params.id!, ctx.portId, {
userId: ctx.userId,
portId: ctx.portId,
ipAddress: ctx.ipAddress,
userAgent: ctx.userAgent,
});
return NextResponse.json({ success: true });
} catch (error) {
return errorResponse(error);
}
}),
);

View File

@@ -0,0 +1,55 @@
import { NextResponse } from 'next/server';
import { withAuth, withPermission } from '@/lib/api/helpers';
import { parseBody } from '@/lib/api/route-helpers';
import { errorResponse } from '@/lib/errors';
import {
getClientById,
updateClient,
archiveClient,
} from '@/lib/services/clients.service';
import { updateClientSchema } from '@/lib/validators/clients';
export const GET = withAuth(
withPermission('clients', 'view', async (req, ctx, params) => {
try {
const client = await getClientById(params.id!, ctx.portId);
return NextResponse.json({ data: client });
} catch (error) {
return errorResponse(error);
}
}),
);
export const PATCH = withAuth(
withPermission('clients', 'edit', async (req, ctx, params) => {
try {
const body = await parseBody(req, updateClientSchema);
const updated = await updateClient(params.id!, ctx.portId, body, {
userId: ctx.userId,
portId: ctx.portId,
ipAddress: ctx.ipAddress,
userAgent: ctx.userAgent,
});
return NextResponse.json({ data: updated });
} catch (error) {
return errorResponse(error);
}
}),
);
export const DELETE = withAuth(
withPermission('clients', 'delete', async (req, ctx, params) => {
try {
await archiveClient(params.id!, ctx.portId, {
userId: ctx.userId,
portId: ctx.portId,
ipAddress: ctx.ipAddress,
userAgent: ctx.userAgent,
});
return new NextResponse(null, { status: 204 });
} catch (error) {
return errorResponse(error);
}
}),
);

View File

@@ -0,0 +1,28 @@
import { NextResponse } from 'next/server';
import { z } from 'zod';
import { withAuth, withPermission } from '@/lib/api/helpers';
import { parseBody } from '@/lib/api/route-helpers';
import { errorResponse } from '@/lib/errors';
import { setClientTags } from '@/lib/services/clients.service';
const setTagsSchema = z.object({
tagIds: z.array(z.string()),
});
export const PUT = withAuth(
withPermission('clients', 'edit', async (req, ctx, params) => {
try {
const { tagIds } = await parseBody(req, setTagsSchema);
await setClientTags(params.id!, ctx.portId, tagIds, {
userId: ctx.userId,
portId: ctx.portId,
ipAddress: ctx.ipAddress,
userAgent: ctx.userAgent,
});
return NextResponse.json({ success: true });
} catch (error) {
return errorResponse(error);
}
}),
);

View File

@@ -0,0 +1,15 @@
import { NextResponse } from 'next/server';
import { withAuth } from '@/lib/api/helpers';
import { errorResponse } from '@/lib/errors';
import { listClientOptions } from '@/lib/services/clients.service';
export const GET = withAuth(async (req, ctx) => {
try {
const search = req.nextUrl.searchParams.get('search') ?? undefined;
const data = await listClientOptions(ctx.portId, search);
return NextResponse.json({ data });
} catch (error) {
return errorResponse(error);
}
});

View File

@@ -0,0 +1,50 @@
import { NextResponse } from 'next/server';
import { withAuth, withPermission } from '@/lib/api/helpers';
import { parseQuery, parseBody } from '@/lib/api/route-helpers';
import { errorResponse } from '@/lib/errors';
import { listClients, createClient } from '@/lib/services/clients.service';
import { listClientsSchema, createClientSchema } from '@/lib/validators/clients';
export const GET = withAuth(
withPermission('clients', 'view', async (req, ctx) => {
try {
const query = parseQuery(req, listClientsSchema);
const result = await listClients(ctx.portId, query);
const { page, limit } = query;
const totalPages = Math.ceil(result.total / limit);
return NextResponse.json({
data: result.data,
pagination: {
page,
pageSize: limit,
total: result.total,
totalPages,
hasNextPage: page < totalPages,
hasPreviousPage: page > 1,
},
});
} catch (error) {
return errorResponse(error);
}
}),
);
export const POST = withAuth(
withPermission('clients', 'create', async (req, ctx) => {
try {
const body = await parseBody(req, createClientSchema);
const client = await createClient(ctx.portId, body, {
userId: ctx.userId,
portId: ctx.portId,
ipAddress: ctx.ipAddress,
userAgent: ctx.userAgent,
});
return NextResponse.json({ data: client }, { status: 201 });
} catch (error) {
return errorResponse(error);
}
}),
);

View File

@@ -0,0 +1,32 @@
import { NextResponse } from 'next/server';
import { z } from 'zod';
import { withAuth } from '@/lib/api/helpers';
import { errorResponse } from '@/lib/errors';
import { convert } from '@/lib/services/currency';
const convertSchema = z.object({
amount: z.coerce.number().positive(),
from: z.string().length(3),
to: z.string().length(3),
});
export const POST = withAuth(async (req, _ctx) => {
try {
const body = await req.json();
const { amount, from, to } = convertSchema.parse(body);
const result = await convert(amount, from, to);
if (!result) {
return NextResponse.json(
{ error: `Exchange rate not available for ${from}${to}` },
{ status: 422 },
);
}
return NextResponse.json({ data: result });
} catch (error) {
return errorResponse(error);
}
});

View File

@@ -0,0 +1,18 @@
import { NextResponse } from 'next/server';
import { withAuth } from '@/lib/api/helpers';
import { errorResponse } from '@/lib/errors';
import { refreshRates } from '@/lib/services/currency';
export const POST = withAuth(async (_req, ctx) => {
try {
if (!ctx.isSuperAdmin) {
return NextResponse.json({ error: 'Insufficient permissions' }, { status: 403 });
}
await refreshRates();
return NextResponse.json({ data: { success: true } });
} catch (error) {
return errorResponse(error);
}
});

View File

@@ -0,0 +1,15 @@
import { NextResponse } from 'next/server';
import { withAuth } from '@/lib/api/helpers';
import { errorResponse } from '@/lib/errors';
import { db } from '@/lib/db';
import { currencyRates } from '@/lib/db/schema/system';
export const GET = withAuth(async (_req, _ctx) => {
try {
const rates = await db.select().from(currencyRates).orderBy(currencyRates.baseCurrency);
return NextResponse.json({ data: rates });
} catch (error) {
return errorResponse(error);
}
});

View File

@@ -0,0 +1,45 @@
import { NextRequest, NextResponse } from 'next/server';
import { withAuth } from '@/lib/api/helpers';
import { errorResponse, NotFoundError } from '@/lib/errors';
import { setValuesSchema } from '@/lib/validators/custom-fields';
import { getValues, setValues } from '@/lib/services/custom-fields.service';
export const GET = withAuth(async (_req: NextRequest, ctx, params) => {
try {
const { entityId } = params;
if (!entityId) throw new NotFoundError('Entity');
const data = await getValues(entityId, ctx.portId);
return NextResponse.json({ data });
} catch (error) {
return errorResponse(error);
}
});
export const PUT = withAuth(async (req: NextRequest, ctx, params) => {
try {
const { entityId } = params;
if (!entityId) throw new NotFoundError('Entity');
const body = await req.json();
const { values } = setValuesSchema.parse(body);
const result = await setValues(
entityId,
ctx.portId,
ctx.userId,
values as Array<{ fieldId: string; value: unknown }>,
{
userId: ctx.userId,
portId: ctx.portId,
ipAddress: ctx.ipAddress,
userAgent: ctx.userAgent,
},
);
return NextResponse.json({ data: result });
} catch (error) {
return errorResponse(error);
}
});

View File

@@ -0,0 +1,9 @@
import { NextRequest, NextResponse } from 'next/server';
import { withAuth } from '@/lib/api/helpers';
import { getRecentActivity } from '@/lib/services/dashboard.service';
export const GET = withAuth(async (req: NextRequest, ctx) => {
const result = await getRecentActivity(ctx.portId);
return NextResponse.json(result);
});

View File

@@ -0,0 +1,9 @@
import { NextRequest, NextResponse } from 'next/server';
import { withAuth } from '@/lib/api/helpers';
import { getRevenueForecast } from '@/lib/services/dashboard.service';
export const GET = withAuth(async (req: NextRequest, ctx) => {
const result = await getRevenueForecast(ctx.portId);
return NextResponse.json(result);
});

View File

@@ -0,0 +1,9 @@
import { NextRequest, NextResponse } from 'next/server';
import { withAuth } from '@/lib/api/helpers';
import { getKpis } from '@/lib/services/dashboard.service';
export const GET = withAuth(async (req: NextRequest, ctx) => {
const result = await getKpis(ctx.portId);
return NextResponse.json(result);
});

View File

@@ -0,0 +1,9 @@
import { NextRequest, NextResponse } from 'next/server';
import { withAuth } from '@/lib/api/helpers';
import { getPipelineCounts } from '@/lib/services/dashboard.service';
export const GET = withAuth(async (req: NextRequest, ctx) => {
const result = await getPipelineCounts(ctx.portId);
return NextResponse.json(result);
});

View File

@@ -0,0 +1,34 @@
import { NextResponse } from 'next/server';
import { withAuth, withPermission } from '@/lib/api/helpers';
import { parseBody } from '@/lib/api/route-helpers';
import { errorResponse } from '@/lib/errors';
import { generateAndSend } from '@/lib/services/document-templates';
import { generateAndSendSchema } from '@/lib/validators/document-templates';
export const POST = withAuth(
withPermission('documents', 'create', async (req, ctx, params) => {
try {
const body = await parseBody(req, generateAndSendSchema);
const result = await generateAndSend(
params.id!,
ctx.portId,
{
clientId: body.clientId,
interestId: body.interestId,
berthId: body.berthId,
},
body.recipientEmail,
{
userId: ctx.userId,
portId: ctx.portId,
ipAddress: ctx.ipAddress,
userAgent: ctx.userAgent,
},
);
return NextResponse.json({ data: result }, { status: 201 });
} catch (error) {
return errorResponse(error);
}
}),
);

View File

@@ -0,0 +1,34 @@
import { NextResponse } from 'next/server';
import { withAuth, withPermission } from '@/lib/api/helpers';
import { parseBody } from '@/lib/api/route-helpers';
import { errorResponse } from '@/lib/errors';
import { generateAndSign } from '@/lib/services/document-templates';
import { generateAndSignSchema } from '@/lib/validators/document-templates';
export const POST = withAuth(
withPermission('documents', 'create', async (req, ctx, params) => {
try {
const body = await parseBody(req, generateAndSignSchema);
const result = await generateAndSign(
params.id!,
ctx.portId,
{
clientId: body.clientId,
interestId: body.interestId,
berthId: body.berthId,
},
body.signers,
{
userId: ctx.userId,
portId: ctx.portId,
ipAddress: ctx.ipAddress,
userAgent: ctx.userAgent,
},
);
return NextResponse.json({ data: result }, { status: 201 });
} catch (error) {
return errorResponse(error);
}
}),
);

View File

@@ -0,0 +1,24 @@
import { NextResponse } from 'next/server';
import { withAuth, withPermission } from '@/lib/api/helpers';
import { parseBody } from '@/lib/api/route-helpers';
import { errorResponse } from '@/lib/errors';
import { generateFromTemplate } from '@/lib/services/document-templates';
import { generateSchema } from '@/lib/validators/document-templates';
export const POST = withAuth(
withPermission('documents', 'create', async (req, ctx, params) => {
try {
const body = await parseBody(req, generateSchema);
const result = await generateFromTemplate(params.id!, ctx.portId, body, {
userId: ctx.userId,
portId: ctx.portId,
ipAddress: ctx.ipAddress,
userAgent: ctx.userAgent,
});
return NextResponse.json({ data: result }, { status: 201 });
} catch (error) {
return errorResponse(error);
}
}),
);

View File

@@ -0,0 +1,55 @@
import { NextResponse } from 'next/server';
import { withAuth, withPermission } from '@/lib/api/helpers';
import { parseBody } from '@/lib/api/route-helpers';
import { errorResponse } from '@/lib/errors';
import {
getTemplateById,
updateTemplate,
deleteTemplate,
} from '@/lib/services/document-templates';
import { updateTemplateSchema } from '@/lib/validators/document-templates';
export const GET = withAuth(
withPermission('documents', 'view', async (req, ctx, params) => {
try {
const template = await getTemplateById(params.id!, ctx.portId);
return NextResponse.json({ data: template });
} catch (error) {
return errorResponse(error);
}
}),
);
export const PATCH = withAuth(
withPermission('admin', 'manage_forms', async (req, ctx, params) => {
try {
const body = await parseBody(req, updateTemplateSchema);
const updated = await updateTemplate(params.id!, ctx.portId, body, {
userId: ctx.userId,
portId: ctx.portId,
ipAddress: ctx.ipAddress,
userAgent: ctx.userAgent,
});
return NextResponse.json({ data: updated });
} catch (error) {
return errorResponse(error);
}
}),
);
export const DELETE = withAuth(
withPermission('admin', 'manage_forms', async (req, ctx, params) => {
try {
await deleteTemplate(params.id!, ctx.portId, {
userId: ctx.userId,
portId: ctx.portId,
ipAddress: ctx.ipAddress,
userAgent: ctx.userAgent,
});
return new NextResponse(null, { status: 204 });
} catch (error) {
return errorResponse(error);
}
}),
);

View File

@@ -0,0 +1,16 @@
import { NextResponse } from 'next/server';
import { withAuth, withPermission } from '@/lib/api/helpers';
import { errorResponse } from '@/lib/errors';
import { getMergeFields } from '@/lib/services/document-templates';
export const GET = withAuth(
withPermission('documents', 'view', async (req, ctx) => {
try {
const mergeFields = getMergeFields();
return NextResponse.json({ data: mergeFields });
} catch (error) {
return errorResponse(error);
}
}),
);

View File

@@ -0,0 +1,56 @@
import { NextResponse } from 'next/server';
import { withAuth, withPermission } from '@/lib/api/helpers';
import { parseQuery, parseBody } from '@/lib/api/route-helpers';
import { errorResponse } from '@/lib/errors';
import {
listTemplates,
createTemplate,
} from '@/lib/services/document-templates';
import {
listTemplatesSchema,
createTemplateSchema,
} from '@/lib/validators/document-templates';
export const GET = withAuth(
withPermission('documents', 'view', async (req, ctx) => {
try {
const query = parseQuery(req, listTemplatesSchema);
const result = await listTemplates(ctx.portId, query);
const { data, total } = result as { data: unknown[]; total: number };
const page = query.page;
const limit = query.limit;
const totalPages = Math.ceil(total / limit);
return NextResponse.json({
data,
pagination: {
page,
pageSize: limit,
total,
totalPages,
hasNextPage: page < totalPages,
hasPreviousPage: page > 1,
},
});
} catch (error) {
return errorResponse(error);
}
}),
);
export const POST = withAuth(
withPermission('admin', 'manage_forms', async (req, ctx) => {
try {
const body = await parseBody(req, createTemplateSchema);
const result = await createTemplate(ctx.portId, body, {
userId: ctx.userId,
portId: ctx.portId,
ipAddress: ctx.ipAddress,
userAgent: ctx.userAgent,
});
return NextResponse.json({ data: result }, { status: 201 });
} catch (error) {
return errorResponse(error);
}
}),
);

View File

@@ -0,0 +1,16 @@
import { NextResponse } from 'next/server';
import { withAuth, withPermission } from '@/lib/api/helpers';
import { errorResponse } from '@/lib/errors';
import { listDocumentEvents } from '@/lib/services/documents.service';
export const GET = withAuth(
withPermission('documents', 'view', async (req, ctx, params) => {
try {
const events = await listDocumentEvents(params.id!, ctx.portId);
return NextResponse.json({ data: events });
} catch (error) {
return errorResponse(error);
}
}),
);

View File

@@ -0,0 +1,16 @@
import { NextResponse } from 'next/server';
import { withAuth, withPermission } from '@/lib/api/helpers';
import { errorResponse } from '@/lib/errors';
import { sendReminderIfAllowed } from '@/lib/services/document-reminders';
export const POST = withAuth(
withPermission('documents', 'edit', async (req, ctx, params) => {
try {
const sent = await sendReminderIfAllowed(params.id!, ctx.portId);
return NextResponse.json({ data: { sent } });
} catch (error) {
return errorResponse(error);
}
}),
);

View File

@@ -0,0 +1,55 @@
import { NextResponse } from 'next/server';
import { withAuth, withPermission } from '@/lib/api/helpers';
import { parseBody } from '@/lib/api/route-helpers';
import { errorResponse } from '@/lib/errors';
import {
getDocumentById,
updateDocument,
deleteDocument,
} from '@/lib/services/documents.service';
import { updateDocumentSchema } from '@/lib/validators/documents';
export const GET = withAuth(
withPermission('documents', 'view', async (req, ctx, params) => {
try {
const doc = await getDocumentById(params.id!, ctx.portId);
return NextResponse.json({ data: doc });
} catch (error) {
return errorResponse(error);
}
}),
);
export const PATCH = withAuth(
withPermission('documents', 'edit', async (req, ctx, params) => {
try {
const body = await parseBody(req, updateDocumentSchema);
const doc = await updateDocument(params.id!, ctx.portId, body, {
userId: ctx.userId,
portId: ctx.portId,
ipAddress: ctx.ipAddress,
userAgent: ctx.userAgent,
});
return NextResponse.json({ data: doc });
} catch (error) {
return errorResponse(error);
}
}),
);
export const DELETE = withAuth(
withPermission('documents', 'delete', async (req, ctx, params) => {
try {
await deleteDocument(params.id!, ctx.portId, {
userId: ctx.userId,
portId: ctx.portId,
ipAddress: ctx.ipAddress,
userAgent: ctx.userAgent,
});
return new NextResponse(null, { status: 204 });
} catch (error) {
return errorResponse(error);
}
}),
);

View File

@@ -0,0 +1,21 @@
import { NextResponse } from 'next/server';
import { withAuth, withPermission } from '@/lib/api/helpers';
import { errorResponse } from '@/lib/errors';
import { sendForSigning } from '@/lib/services/documents.service';
export const POST = withAuth(
withPermission('documents', 'create', async (req, ctx, params) => {
try {
const doc = await sendForSigning(params.id!, ctx.portId, {
userId: ctx.userId,
portId: ctx.portId,
ipAddress: ctx.ipAddress,
userAgent: ctx.userAgent,
});
return NextResponse.json({ data: doc });
} catch (error) {
return errorResponse(error);
}
}),
);

View File

@@ -0,0 +1,16 @@
import { NextResponse } from 'next/server';
import { withAuth, withPermission } from '@/lib/api/helpers';
import { errorResponse } from '@/lib/errors';
import { listDocumentSigners } from '@/lib/services/documents.service';
export const GET = withAuth(
withPermission('documents', 'view', async (req, ctx, params) => {
try {
const signers = await listDocumentSigners(params.id!, ctx.portId);
return NextResponse.json({ data: signers });
} catch (error) {
return errorResponse(error);
}
}),
);

View File

@@ -0,0 +1,41 @@
import { NextResponse } from 'next/server';
import { withAuth, withPermission } from '@/lib/api/helpers';
import { errorResponse, ValidationError } from '@/lib/errors';
import { uploadSignedManually } from '@/lib/services/documents.service';
export const POST = withAuth(
withPermission('documents', 'edit', async (req, ctx, params) => {
try {
const formData = await req.formData();
const file = formData.get('file') as File | null;
if (!file) {
throw new ValidationError('No file provided');
}
const buffer = Buffer.from(await file.arrayBuffer());
const doc = await uploadSignedManually(
params.id!,
ctx.portId,
{
buffer,
originalName: file.name,
mimeType: file.type || 'application/pdf',
size: file.size,
},
{
userId: ctx.userId,
portId: ctx.portId,
ipAddress: ctx.ipAddress,
userAgent: ctx.userAgent,
},
);
return NextResponse.json({ data: doc });
} catch (error) {
return errorResponse(error);
}
}),
);

View File

@@ -0,0 +1,24 @@
import { NextResponse } from 'next/server';
import { withAuth, withPermission } from '@/lib/api/helpers';
import { parseBody } from '@/lib/api/route-helpers';
import { errorResponse } from '@/lib/errors';
import { generateEoi } from '@/lib/services/documents.service';
import { generateEoiSchema } from '@/lib/validators/documents';
export const POST = withAuth(
withPermission('documents', 'create', async (req, ctx) => {
try {
const body = await parseBody(req, generateEoiSchema);
const doc = await generateEoi(body.interestId, ctx.portId, {
userId: ctx.userId,
portId: ctx.portId,
ipAddress: ctx.ipAddress,
userAgent: ctx.userAgent,
});
return NextResponse.json({ data: doc }, { status: 201 });
} catch (error) {
return errorResponse(error);
}
}),
);

View File

@@ -0,0 +1,50 @@
import { NextResponse } from 'next/server';
import { withAuth, withPermission } from '@/lib/api/helpers';
import { parseQuery, parseBody } from '@/lib/api/route-helpers';
import { errorResponse } from '@/lib/errors';
import { listDocuments, createDocument } from '@/lib/services/documents.service';
import { listDocumentsSchema, createDocumentSchema } from '@/lib/validators/documents';
export const GET = withAuth(
withPermission('documents', 'view', async (req, ctx) => {
try {
const query = parseQuery(req, listDocumentsSchema);
const result = await listDocuments(ctx.portId, query);
const { page, limit } = query;
const totalPages = Math.ceil(result.total / limit);
return NextResponse.json({
data: result.data,
pagination: {
page,
pageSize: limit,
total: result.total,
totalPages,
hasNextPage: page < totalPages,
hasPreviousPage: page > 1,
},
});
} catch (error) {
return errorResponse(error);
}
}),
);
export const POST = withAuth(
withPermission('documents', 'create', async (req, ctx) => {
try {
const body = await parseBody(req, createDocumentSchema);
const doc = await createDocument(ctx.portId, body, {
userId: ctx.userId,
portId: ctx.portId,
ipAddress: ctx.ipAddress,
userAgent: ctx.userAgent,
});
return NextResponse.json({ data: doc }, { status: 201 });
} catch (error) {
return errorResponse(error);
}
}),
);

View File

@@ -0,0 +1,35 @@
import { NextResponse } from 'next/server';
import { withAuth, withPermission } from '@/lib/api/helpers';
import { parseBody } from '@/lib/api/route-helpers';
import { errorResponse } from '@/lib/errors';
import { toggleAccount, disconnectAccount } from '@/lib/services/email-accounts.service';
import { toggleAccountSchema } from '@/lib/validators/email';
export const PATCH = withAuth(
withPermission('email', 'configure_account', async (req, ctx, params) => {
try {
const body = await parseBody(req, toggleAccountSchema);
const account = await toggleAccount(params.accountId!, ctx.userId, body);
return NextResponse.json({ data: account });
} catch (error) {
return errorResponse(error);
}
}),
);
export const DELETE = withAuth(
withPermission('email', 'configure_account', async (_req, ctx, params) => {
try {
await disconnectAccount(params.accountId!, ctx.userId, {
userId: ctx.userId,
portId: ctx.portId,
ipAddress: ctx.ipAddress,
userAgent: ctx.userAgent,
});
return new NextResponse(null, { status: 204 });
} catch (error) {
return errorResponse(error);
}
}),
);

View File

@@ -0,0 +1,17 @@
import { NextResponse } from 'next/server';
import { withAuth, withPermission } from '@/lib/api/helpers';
import { errorResponse } from '@/lib/errors';
import { getQueue } from '@/lib/queue';
export const POST = withAuth(
withPermission('email', 'view', async (_req, _ctx, params) => {
try {
const queue = getQueue('email');
const job = await queue.add('inbox-sync', { accountId: params.accountId! });
return NextResponse.json({ data: { jobId: job.id } }, { status: 202 });
} catch (error) {
return errorResponse(error);
}
}),
);

View File

@@ -0,0 +1,35 @@
import { NextResponse } from 'next/server';
import { withAuth, withPermission } from '@/lib/api/helpers';
import { parseBody } from '@/lib/api/route-helpers';
import { errorResponse } from '@/lib/errors';
import { listAccounts, connectAccount } from '@/lib/services/email-accounts.service';
import { connectAccountSchema } from '@/lib/validators/email';
export const GET = withAuth(
withPermission('email', 'view', async (_req, ctx) => {
try {
const accounts = await listAccounts(ctx.userId, ctx.portId);
return NextResponse.json({ data: accounts });
} catch (error) {
return errorResponse(error);
}
}),
);
export const POST = withAuth(
withPermission('email', 'configure_account', async (req, ctx) => {
try {
const body = await parseBody(req, connectAccountSchema);
const account = await connectAccount(ctx.userId, ctx.portId, body, {
userId: ctx.userId,
portId: ctx.portId,
ipAddress: ctx.ipAddress,
userAgent: ctx.userAgent,
});
return NextResponse.json({ data: account }, { status: 201 });
} catch (error) {
return errorResponse(error);
}
}),
);

View File

@@ -0,0 +1,24 @@
import { NextResponse } from 'next/server';
import { withAuth, withPermission } from '@/lib/api/helpers';
import { parseBody } from '@/lib/api/route-helpers';
import { errorResponse } from '@/lib/errors';
import { sendEmail } from '@/lib/services/email-compose.service';
import { composeEmailSchema } from '@/lib/validators/email';
export const POST = withAuth(
withPermission('email', 'send', async (req, ctx) => {
try {
const body = await parseBody(req, composeEmailSchema);
const result = await sendEmail(ctx.userId, ctx.portId, body, {
userId: ctx.userId,
portId: ctx.portId,
ipAddress: ctx.ipAddress,
userAgent: ctx.userAgent,
});
return NextResponse.json({ data: result }, { status: 201 });
} catch (error) {
return errorResponse(error);
}
}),
);

View File

@@ -0,0 +1,16 @@
import { NextResponse } from 'next/server';
import { withAuth, withPermission } from '@/lib/api/helpers';
import { errorResponse } from '@/lib/errors';
import { getThread } from '@/lib/services/email-threads.service';
export const GET = withAuth(
withPermission('email', 'view', async (_req, ctx, params) => {
try {
const thread = await getThread(params.threadId!, ctx.portId);
return NextResponse.json({ data: thread });
} catch (error) {
return errorResponse(error);
}
}),
);

View File

@@ -0,0 +1,33 @@
import { NextResponse } from 'next/server';
import { withAuth, withPermission } from '@/lib/api/helpers';
import { parseQuery } from '@/lib/api/route-helpers';
import { errorResponse } from '@/lib/errors';
import { listThreads } from '@/lib/services/email-threads.service';
import { listThreadsSchema } from '@/lib/validators/email';
export const GET = withAuth(
withPermission('email', 'view', async (req, ctx) => {
try {
const query = parseQuery(req, listThreadsSchema);
const result = await listThreads(ctx.portId, query);
const { page, limit } = query;
const totalPages = Math.ceil(result.total / limit);
return NextResponse.json({
data: result.data,
pagination: {
page,
pageSize: limit,
total: result.total,
totalPages,
hasNextPage: page < totalPages,
hasPreviousPage: page > 1,
},
});
} catch (error) {
return errorResponse(error);
}
}),
);

View File

@@ -0,0 +1,55 @@
import { NextResponse } from 'next/server';
import { withAuth, withPermission } from '@/lib/api/helpers';
import { parseBody } from '@/lib/api/route-helpers';
import { errorResponse } from '@/lib/errors';
import {
getExpenseById,
updateExpense,
archiveExpense,
} from '@/lib/services/expenses';
import { updateExpenseSchema } from '@/lib/validators/expenses';
export const GET = withAuth(
withPermission('expenses', 'view', async (_req, ctx, params) => {
try {
const expense = await getExpenseById(params.id!, ctx.portId);
return NextResponse.json({ data: expense });
} catch (error) {
return errorResponse(error);
}
}),
);
export const PATCH = withAuth(
withPermission('expenses', 'edit', async (req, ctx, params) => {
try {
const body = await parseBody(req, updateExpenseSchema);
const expense = await updateExpense(params.id!, ctx.portId, body, {
userId: ctx.userId,
portId: ctx.portId,
ipAddress: ctx.ipAddress,
userAgent: ctx.userAgent,
});
return NextResponse.json({ data: expense });
} catch (error) {
return errorResponse(error);
}
}),
);
export const DELETE = withAuth(
withPermission('expenses', 'delete', async (_req, ctx, params) => {
try {
await archiveExpense(params.id!, ctx.portId, {
userId: ctx.userId,
portId: ctx.portId,
ipAddress: ctx.ipAddress,
userAgent: ctx.userAgent,
});
return new NextResponse(null, { status: 204 });
} catch (error) {
return errorResponse(error);
}
}),
);

View File

@@ -0,0 +1,27 @@
import { NextResponse } from 'next/server';
import { withAuth, withPermission } from '@/lib/api/helpers';
import { parseBody } from '@/lib/api/route-helpers';
import { errorResponse } from '@/lib/errors';
import { exportCsv } from '@/lib/services/expense-export';
import { listExpensesSchema } from '@/lib/validators/expenses';
export const POST = withAuth(
withPermission('expenses', 'view', async (req, ctx) => {
try {
const body = await req.json().catch(() => ({}));
const query = listExpensesSchema.parse(body);
const csv = await exportCsv(ctx.portId, query);
return new NextResponse(csv, {
status: 200,
headers: {
'Content-Type': 'text/csv',
'Content-Disposition': `attachment; filename="expenses-${Date.now()}.csv"`,
},
});
} catch (error) {
return errorResponse(error);
}
}),
);

View File

@@ -0,0 +1,28 @@
import { NextResponse } from 'next/server';
import { withAuth } from '@/lib/api/helpers';
import { errorResponse } from '@/lib/errors';
import { exportParentCompany } from '@/lib/services/expense-export';
import { listExpensesSchema } from '@/lib/validators/expenses';
export const POST = withAuth(async (req, ctx) => {
try {
if (!ctx.isSuperAdmin) {
return NextResponse.json({ error: 'Insufficient permissions' }, { status: 403 });
}
const body = await req.json().catch(() => ({}));
const query = listExpensesSchema.parse(body);
const pdf = await exportParentCompany(ctx.portId, query);
return new NextResponse(Buffer.from(pdf), {
status: 200,
headers: {
'Content-Type': 'application/pdf',
'Content-Disposition': `attachment; filename="expenses-parent-company-${Date.now()}.pdf"`,
},
});
} catch (error) {
return errorResponse(error);
}
});

View File

@@ -0,0 +1,26 @@
import { NextResponse } from 'next/server';
import { withAuth, withPermission } from '@/lib/api/helpers';
import { errorResponse } from '@/lib/errors';
import { exportPdf } from '@/lib/services/expense-export';
import { listExpensesSchema } from '@/lib/validators/expenses';
export const POST = withAuth(
withPermission('expenses', 'view', async (req, ctx) => {
try {
const body = await req.json().catch(() => ({}));
const query = listExpensesSchema.parse(body);
const pdf = await exportPdf(ctx.portId, query);
return new NextResponse(Buffer.from(pdf), {
status: 200,
headers: {
'Content-Type': 'application/pdf',
'Content-Disposition': `attachment; filename="expenses-${Date.now()}.pdf"`,
},
});
} catch (error) {
return errorResponse(error);
}
}),
);

View File

@@ -0,0 +1,50 @@
import { NextResponse } from 'next/server';
import { withAuth, withPermission } from '@/lib/api/helpers';
import { parseQuery, parseBody } from '@/lib/api/route-helpers';
import { errorResponse } from '@/lib/errors';
import { listExpenses, createExpense } from '@/lib/services/expenses';
import { listExpensesSchema, createExpenseSchema } from '@/lib/validators/expenses';
export const GET = withAuth(
withPermission('expenses', 'view', async (req, ctx) => {
try {
const query = parseQuery(req, listExpensesSchema);
const result = await listExpenses(ctx.portId, query);
const { page, limit } = query;
const totalPages = Math.ceil(result.total / limit);
return NextResponse.json({
data: result.data,
pagination: {
page,
pageSize: limit,
total: result.total,
totalPages,
hasNextPage: page < totalPages,
hasPreviousPage: page > 1,
},
});
} catch (error) {
return errorResponse(error);
}
}),
);
export const POST = withAuth(
withPermission('expenses', 'create', async (req, ctx) => {
try {
const body = await parseBody(req, createExpenseSchema);
const expense = await createExpense(ctx.portId, body, {
userId: ctx.userId,
portId: ctx.portId,
ipAddress: ctx.ipAddress,
userAgent: ctx.userAgent,
});
return NextResponse.json({ data: expense }, { status: 201 });
} catch (error) {
return errorResponse(error);
}
}),
);

View File

@@ -0,0 +1,27 @@
import { NextResponse } from 'next/server';
import { withAuth, withPermission } from '@/lib/api/helpers';
import { errorResponse } from '@/lib/errors';
import { scanReceipt } from '@/lib/services/receipt-scanner';
export const POST = withAuth(
withPermission('expenses', 'create', async (req, _ctx) => {
try {
const formData = await req.formData();
const file = formData.get('file') as File | null;
if (!file) {
return NextResponse.json({ error: 'No file provided' }, { status: 400 });
}
const buffer = Buffer.from(await file.arrayBuffer());
const mimeType = file.type || 'image/jpeg';
const result = await scanReceipt(buffer, mimeType);
return NextResponse.json({ data: result });
} catch (error) {
return errorResponse(error);
}
}),
);

View File

@@ -0,0 +1,16 @@
import { NextResponse } from 'next/server';
import { withAuth, withPermission } from '@/lib/api/helpers';
import { errorResponse } from '@/lib/errors';
import { getDownloadUrl } from '@/lib/services/files';
export const GET = withAuth(
withPermission('files', 'view', async (req, ctx, params) => {
try {
const result = await getDownloadUrl(params.id!, ctx.portId);
return NextResponse.json({ data: result });
} catch (error) {
return errorResponse(error);
}
}),
);

View File

@@ -0,0 +1,16 @@
import { NextResponse } from 'next/server';
import { withAuth, withPermission } from '@/lib/api/helpers';
import { errorResponse } from '@/lib/errors';
import { getPreviewUrl } from '@/lib/services/files';
export const GET = withAuth(
withPermission('files', 'view', async (req, ctx, params) => {
try {
const result = await getPreviewUrl(params.id!, ctx.portId);
return NextResponse.json({ data: result });
} catch (error) {
return errorResponse(error);
}
}),
);

View File

@@ -0,0 +1,51 @@
import { NextResponse } from 'next/server';
import { withAuth, withPermission } from '@/lib/api/helpers';
import { parseBody } from '@/lib/api/route-helpers';
import { errorResponse } from '@/lib/errors';
import { getFileById, updateFile, deleteFile } from '@/lib/services/files';
import { updateFileSchema } from '@/lib/validators/files';
export const GET = withAuth(
withPermission('files', 'view', async (req, ctx, params) => {
try {
const file = await getFileById(params.id!, ctx.portId);
return NextResponse.json({ data: file });
} catch (error) {
return errorResponse(error);
}
}),
);
export const PATCH = withAuth(
withPermission('files', 'edit', async (req, ctx, params) => {
try {
const body = await parseBody(req, updateFileSchema);
const updated = await updateFile(params.id!, ctx.portId, body, {
userId: ctx.userId,
portId: ctx.portId,
ipAddress: ctx.ipAddress,
userAgent: ctx.userAgent,
});
return NextResponse.json({ data: updated });
} catch (error) {
return errorResponse(error);
}
}),
);
export const DELETE = withAuth(
withPermission('files', 'delete', async (req, ctx, params) => {
try {
await deleteFile(params.id!, ctx.portId, {
userId: ctx.userId,
portId: ctx.portId,
ipAddress: ctx.ipAddress,
userAgent: ctx.userAgent,
});
return new NextResponse(null, { status: 204 });
} catch (error) {
return errorResponse(error);
}
}),
);

View File

@@ -0,0 +1,75 @@
import { NextResponse } from 'next/server';
import { z } from 'zod';
import { withAuth, withPermission } from '@/lib/api/helpers';
import { parseBody } from '@/lib/api/route-helpers';
import { errorResponse, ValidationError } from '@/lib/errors';
import { minioClient } from '@/lib/minio';
import { env } from '@/lib/env';
const renameFolderSchema = z.object({
newPath: z.string().min(1).max(500),
});
function sanitizeFolderPath(raw: string): string {
return raw
.replace(/\x00/g, '')
.replace(/\.\.\//g, '')
.replace(/^\/+/, '')
.replace(/\/+/g, '/');
}
export const PATCH = withAuth(
withPermission('files', 'edit', async (req, ctx, params) => {
try {
const pathSegments = params.path;
const currentPath = Array.isArray(pathSegments)
? (pathSegments as string[]).join('/')
: String(pathSegments);
const body = await parseBody(req, renameFolderSchema);
const safeCurrent = sanitizeFolderPath(currentPath);
const safeNew = sanitizeFolderPath(body.newPath);
if (!safeCurrent || !safeNew) {
throw new ValidationError('Invalid folder path');
}
const oldKey = `${ctx.portSlug}/${safeCurrent}${safeCurrent.endsWith('/') ? '' : '/'}`;
const newKey = `${ctx.portSlug}/${safeNew}${safeNew.endsWith('/') ? '' : '/'}`;
// Create new marker, remove old
await minioClient.putObject(env.MINIO_BUCKET, newKey, Buffer.alloc(0), 0, {
'Content-Type': 'application/x-directory',
});
await minioClient.removeObject(env.MINIO_BUCKET, oldKey);
return NextResponse.json({ data: { path: newKey } });
} catch (error) {
return errorResponse(error);
}
}),
);
export const DELETE = withAuth(
withPermission('files', 'delete', async (req, ctx, params) => {
try {
const pathSegments = params.path;
const currentPath = Array.isArray(pathSegments)
? (pathSegments as string[]).join('/')
: String(pathSegments);
const safePath = sanitizeFolderPath(currentPath);
if (!safePath) {
throw new ValidationError('Invalid folder path');
}
const folderKey = `${ctx.portSlug}/${safePath}${safePath.endsWith('/') ? '' : '/'}`;
await minioClient.removeObject(env.MINIO_BUCKET, folderKey);
return new NextResponse(null, { status: 204 });
} catch (error) {
return errorResponse(error);
}
}),
);

View File

@@ -0,0 +1,42 @@
import { NextResponse } from 'next/server';
import { z } from 'zod';
import { withAuth, withPermission } from '@/lib/api/helpers';
import { parseBody } from '@/lib/api/route-helpers';
import { errorResponse, ValidationError } from '@/lib/errors';
import { minioClient } from '@/lib/minio';
import { env } from '@/lib/env';
const createFolderSchema = z.object({
path: z.string().min(1).max(500),
});
export const POST = withAuth(
withPermission('files', 'create', async (req, ctx) => {
try {
const body = await parseBody(req, createFolderSchema);
// Sanitize path — no null bytes, no path traversal
const safePath = body.path
.replace(/\x00/g, '')
.replace(/\.\.\//g, '')
.replace(/^\/+/, '')
.replace(/\/+/g, '/');
if (!safePath) {
throw new ValidationError('Invalid folder path');
}
const folderKey = `${ctx.portSlug}/${safePath}${safePath.endsWith('/') ? '' : '/'}`;
// Create zero-byte marker object in MinIO
await minioClient.putObject(env.MINIO_BUCKET, folderKey, Buffer.alloc(0), 0, {
'Content-Type': 'application/x-directory',
});
return NextResponse.json({ data: { path: folderKey } }, { status: 201 });
} catch (error) {
return errorResponse(error);
}
}),
);

View File

@@ -0,0 +1,33 @@
import { NextResponse } from 'next/server';
import { withAuth, withPermission } from '@/lib/api/helpers';
import { parseQuery } from '@/lib/api/route-helpers';
import { errorResponse } from '@/lib/errors';
import { listFiles } from '@/lib/services/files';
import { listFilesSchema } from '@/lib/validators/files';
export const GET = withAuth(
withPermission('files', 'view', async (req, ctx) => {
try {
const query = parseQuery(req, listFilesSchema);
const result = await listFiles(ctx.portId, query);
const { page, limit } = query;
const totalPages = Math.ceil(result.total / limit);
return NextResponse.json({
data: result.data,
pagination: {
page,
pageSize: limit,
total: result.total,
totalPages,
hasNextPage: page < totalPages,
hasPreviousPage: page > 1,
},
});
} catch (error) {
return errorResponse(error);
}
}),
);

View File

@@ -0,0 +1,51 @@
import { NextResponse } from 'next/server';
import { withAuth, withPermission } from '@/lib/api/helpers';
import { errorResponse, ValidationError } from '@/lib/errors';
import { uploadFile } from '@/lib/services/files';
import { uploadFileSchema } from '@/lib/validators/files';
export const POST = withAuth(
withPermission('files', 'create', async (req, ctx) => {
try {
const formData = await req.formData();
const file = formData.get('file') as File | null;
if (!file) {
throw new ValidationError('No file provided');
}
const buffer = Buffer.from(await file.arrayBuffer());
const metadata = uploadFileSchema.parse({
filename: (formData.get('filename') as string | null) ?? file.name,
clientId: formData.get('clientId') as string | undefined,
category: formData.get('category') as string | undefined,
entityType: formData.get('entityType') as string | undefined,
entityId: formData.get('entityId') as string | undefined,
});
const result = await uploadFile(
ctx.portId,
ctx.portSlug,
{
buffer,
originalName: file.name,
mimeType: file.type,
size: file.size,
},
metadata,
{
userId: ctx.userId,
portId: ctx.portId,
ipAddress: ctx.ipAddress,
userAgent: ctx.userAgent,
},
);
return NextResponse.json({ data: result }, { status: 201 });
} catch (error) {
return errorResponse(error);
}
}),
);

View File

@@ -0,0 +1,44 @@
import { NextResponse } from 'next/server';
import { z } from 'zod';
import { withAuth, withPermission } from '@/lib/api/helpers';
import { parseBody } from '@/lib/api/route-helpers';
import { errorResponse } from '@/lib/errors';
import { linkBerth, unlinkBerth } from '@/lib/services/interests.service';
const linkBerthSchema = z.object({
berthId: z.string().min(1),
});
export const PUT = withAuth(
withPermission('interests', 'edit', async (req, ctx, params) => {
try {
const body = await parseBody(req, linkBerthSchema);
const interest = await linkBerth(params.id!, ctx.portId, body.berthId, {
userId: ctx.userId,
portId: ctx.portId,
ipAddress: ctx.ipAddress,
userAgent: ctx.userAgent,
});
return NextResponse.json({ data: interest });
} catch (error) {
return errorResponse(error);
}
}),
);
export const DELETE = withAuth(
withPermission('interests', 'edit', async (req, ctx, params) => {
try {
const interest = await unlinkBerth(params.id!, ctx.portId, {
userId: ctx.userId,
portId: ctx.portId,
ipAddress: ctx.ipAddress,
userAgent: ctx.userAgent,
});
return NextResponse.json({ data: interest });
} catch (error) {
return errorResponse(error);
}
}),
);

Some files were not shown because too many files have changed in this diff Show More