Initial commit: Port Nimara CRM (Layers 0-4)
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:
18
src/app/api/v1/admin/connections/route.ts
Normal file
18
src/app/api/v1/admin/connections/route.ts
Normal 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);
|
||||
}
|
||||
});
|
||||
69
src/app/api/v1/admin/custom-fields/[fieldId]/route.ts
Normal file
69
src/app/api/v1/admin/custom-fields/[fieldId]/route.ts
Normal 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);
|
||||
}
|
||||
},
|
||||
),
|
||||
);
|
||||
43
src/app/api/v1/admin/custom-fields/route.ts
Normal file
43
src/app/api/v1/admin/custom-fields/route.ts
Normal 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);
|
||||
}
|
||||
}),
|
||||
);
|
||||
21
src/app/api/v1/admin/errors/route.ts
Normal file
21
src/app/api/v1/admin/errors/route.ts
Normal 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);
|
||||
}
|
||||
});
|
||||
18
src/app/api/v1/admin/health/route.ts
Normal file
18
src/app/api/v1/admin/health/route.ts
Normal 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);
|
||||
}
|
||||
});
|
||||
@@ -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);
|
||||
}
|
||||
});
|
||||
29
src/app/api/v1/admin/queues/[queueName]/[jobId]/route.ts
Normal file
29
src/app/api/v1/admin/queues/[queueName]/[jobId]/route.ts
Normal 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);
|
||||
}
|
||||
});
|
||||
35
src/app/api/v1/admin/queues/[queueName]/route.ts
Normal file
35
src/app/api/v1/admin/queues/[queueName]/route.ts
Normal 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);
|
||||
}
|
||||
});
|
||||
18
src/app/api/v1/admin/queues/route.ts
Normal file
18
src/app/api/v1/admin/queues/route.ts
Normal 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);
|
||||
}
|
||||
});
|
||||
30
src/app/api/v1/admin/roles/[id]/route.ts
Normal file
30
src/app/api/v1/admin/roles/[id]/route.ts
Normal 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);
|
||||
}
|
||||
}),
|
||||
);
|
||||
19
src/app/api/v1/admin/roles/route.ts
Normal file
19
src/app/api/v1/admin/roles/route.ts
Normal 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);
|
||||
}
|
||||
}),
|
||||
);
|
||||
@@ -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);
|
||||
}
|
||||
}),
|
||||
);
|
||||
78
src/app/api/v1/admin/templates/[templateId]/route.ts
Normal file
78
src/app/api/v1/admin/templates/[templateId]/route.ts
Normal 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);
|
||||
}
|
||||
}),
|
||||
);
|
||||
@@ -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);
|
||||
}
|
||||
}),
|
||||
);
|
||||
77
src/app/api/v1/admin/templates/preview/route.ts
Normal file
77
src/app/api/v1/admin/templates/preview/route.ts
Normal 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;
|
||||
}
|
||||
50
src/app/api/v1/admin/templates/route.ts
Normal file
50
src/app/api/v1/admin/templates/route.ts
Normal 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);
|
||||
}
|
||||
}),
|
||||
);
|
||||
25
src/app/api/v1/admin/users/options/route.ts
Normal file
25
src/app/api/v1/admin/users/options/route.ts
Normal 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);
|
||||
}
|
||||
});
|
||||
40
src/app/api/v1/admin/users/route.ts
Normal file
40
src/app/api/v1/admin/users/route.ts
Normal 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);
|
||||
}
|
||||
}),
|
||||
);
|
||||
@@ -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);
|
||||
}
|
||||
}),
|
||||
);
|
||||
@@ -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);
|
||||
}
|
||||
}),
|
||||
);
|
||||
64
src/app/api/v1/admin/webhooks/[webhookId]/route.ts
Normal file
64
src/app/api/v1/admin/webhooks/[webhookId]/route.ts
Normal 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);
|
||||
}
|
||||
}),
|
||||
);
|
||||
27
src/app/api/v1/admin/webhooks/[webhookId]/test/route.ts
Normal file
27
src/app/api/v1/admin/webhooks/[webhookId]/test/route.ts
Normal 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);
|
||||
}
|
||||
}),
|
||||
);
|
||||
39
src/app/api/v1/admin/webhooks/route.ts
Normal file
39
src/app/api/v1/admin/webhooks/route.ts
Normal 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);
|
||||
}
|
||||
}),
|
||||
);
|
||||
24
src/app/api/v1/ai/email-draft/[jobId]/route.ts
Normal file
24
src/app/api/v1/ai/email-draft/[jobId]/route.ts
Normal 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);
|
||||
}
|
||||
});
|
||||
38
src/app/api/v1/ai/email-draft/route.ts
Normal file
38
src/app/api/v1/ai/email-draft/route.ts
Normal 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);
|
||||
}
|
||||
});
|
||||
28
src/app/api/v1/ai/interest-score/bulk/route.ts
Normal file
28
src/app/api/v1/ai/interest-score/bulk/route.ts
Normal 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);
|
||||
}
|
||||
});
|
||||
32
src/app/api/v1/ai/interest-score/route.ts
Normal file
32
src/app/api/v1/ai/interest-score/route.ts
Normal 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);
|
||||
}
|
||||
});
|
||||
22
src/app/api/v1/berths/[id]/export-pdf/route.ts
Normal file
22
src/app/api/v1/berths/[id]/export-pdf/route.ts
Normal 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);
|
||||
}
|
||||
}),
|
||||
);
|
||||
37
src/app/api/v1/berths/[id]/maintenance/route.ts
Normal file
37
src/app/api/v1/berths/[id]/maintenance/route.ts
Normal 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);
|
||||
}
|
||||
}),
|
||||
);
|
||||
37
src/app/api/v1/berths/[id]/route.ts
Normal file
37
src/app/api/v1/berths/[id]/route.ts
Normal 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);
|
||||
}
|
||||
}),
|
||||
);
|
||||
25
src/app/api/v1/berths/[id]/status/route.ts
Normal file
25
src/app/api/v1/berths/[id]/status/route.ts
Normal 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);
|
||||
}
|
||||
}),
|
||||
);
|
||||
29
src/app/api/v1/berths/[id]/tags/route.ts
Normal file
29
src/app/api/v1/berths/[id]/tags/route.ts
Normal 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);
|
||||
}
|
||||
}),
|
||||
);
|
||||
90
src/app/api/v1/berths/[id]/waiting-list/route.ts
Normal file
90
src/app/api/v1/berths/[id]/waiting-list/route.ts
Normal 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);
|
||||
}
|
||||
}),
|
||||
);
|
||||
15
src/app/api/v1/berths/options/route.ts
Normal file
15
src/app/api/v1/berths/options/route.ts
Normal 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);
|
||||
}
|
||||
});
|
||||
36
src/app/api/v1/berths/route.ts
Normal file
36
src/app/api/v1/berths/route.ts
Normal 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);
|
||||
}
|
||||
}),
|
||||
);
|
||||
54
src/app/api/v1/clients/[id]/contacts/[contactId]/route.ts
Normal file
54
src/app/api/v1/clients/[id]/contacts/[contactId]/route.ts
Normal 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);
|
||||
}
|
||||
}),
|
||||
);
|
||||
43
src/app/api/v1/clients/[id]/contacts/route.ts
Normal file
43
src/app/api/v1/clients/[id]/contacts/route.ts
Normal 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);
|
||||
}
|
||||
}),
|
||||
);
|
||||
22
src/app/api/v1/clients/[id]/export-pdf/route.ts
Normal file
22
src/app/api/v1/clients/[id]/export-pdf/route.ts
Normal 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);
|
||||
}
|
||||
}),
|
||||
);
|
||||
63
src/app/api/v1/clients/[id]/notes/[noteId]/route.ts
Normal file
63
src/app/api/v1/clients/[id]/notes/[noteId]/route.ts
Normal 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);
|
||||
}
|
||||
}),
|
||||
);
|
||||
55
src/app/api/v1/clients/[id]/notes/route.ts
Normal file
55
src/app/api/v1/clients/[id]/notes/route.ts
Normal 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);
|
||||
}
|
||||
}),
|
||||
);
|
||||
21
src/app/api/v1/clients/[id]/relationships/[relId]/route.ts
Normal file
21
src/app/api/v1/clients/[id]/relationships/[relId]/route.ts
Normal 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);
|
||||
}
|
||||
}),
|
||||
);
|
||||
47
src/app/api/v1/clients/[id]/relationships/route.ts
Normal file
47
src/app/api/v1/clients/[id]/relationships/route.ts
Normal 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);
|
||||
}
|
||||
}),
|
||||
);
|
||||
21
src/app/api/v1/clients/[id]/restore/route.ts
Normal file
21
src/app/api/v1/clients/[id]/restore/route.ts
Normal 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);
|
||||
}
|
||||
}),
|
||||
);
|
||||
55
src/app/api/v1/clients/[id]/route.ts
Normal file
55
src/app/api/v1/clients/[id]/route.ts
Normal 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);
|
||||
}
|
||||
}),
|
||||
);
|
||||
28
src/app/api/v1/clients/[id]/tags/route.ts
Normal file
28
src/app/api/v1/clients/[id]/tags/route.ts
Normal 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);
|
||||
}
|
||||
}),
|
||||
);
|
||||
15
src/app/api/v1/clients/options/route.ts
Normal file
15
src/app/api/v1/clients/options/route.ts
Normal 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);
|
||||
}
|
||||
});
|
||||
50
src/app/api/v1/clients/route.ts
Normal file
50
src/app/api/v1/clients/route.ts
Normal 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);
|
||||
}
|
||||
}),
|
||||
);
|
||||
32
src/app/api/v1/currency/convert/route.ts
Normal file
32
src/app/api/v1/currency/convert/route.ts
Normal 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);
|
||||
}
|
||||
});
|
||||
18
src/app/api/v1/currency/rates/refresh/route.ts
Normal file
18
src/app/api/v1/currency/rates/refresh/route.ts
Normal 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);
|
||||
}
|
||||
});
|
||||
15
src/app/api/v1/currency/rates/route.ts
Normal file
15
src/app/api/v1/currency/rates/route.ts
Normal 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);
|
||||
}
|
||||
});
|
||||
45
src/app/api/v1/custom-fields/[entityId]/route.ts
Normal file
45
src/app/api/v1/custom-fields/[entityId]/route.ts
Normal 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);
|
||||
}
|
||||
});
|
||||
9
src/app/api/v1/dashboard/activity/route.ts
Normal file
9
src/app/api/v1/dashboard/activity/route.ts
Normal 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);
|
||||
});
|
||||
9
src/app/api/v1/dashboard/forecast/route.ts
Normal file
9
src/app/api/v1/dashboard/forecast/route.ts
Normal 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);
|
||||
});
|
||||
9
src/app/api/v1/dashboard/kpis/route.ts
Normal file
9
src/app/api/v1/dashboard/kpis/route.ts
Normal 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);
|
||||
});
|
||||
9
src/app/api/v1/dashboard/pipeline/route.ts
Normal file
9
src/app/api/v1/dashboard/pipeline/route.ts
Normal 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);
|
||||
});
|
||||
@@ -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);
|
||||
}
|
||||
}),
|
||||
);
|
||||
@@ -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);
|
||||
}
|
||||
}),
|
||||
);
|
||||
24
src/app/api/v1/document-templates/[id]/generate/route.ts
Normal file
24
src/app/api/v1/document-templates/[id]/generate/route.ts
Normal 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);
|
||||
}
|
||||
}),
|
||||
);
|
||||
55
src/app/api/v1/document-templates/[id]/route.ts
Normal file
55
src/app/api/v1/document-templates/[id]/route.ts
Normal 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);
|
||||
}
|
||||
}),
|
||||
);
|
||||
16
src/app/api/v1/document-templates/merge-fields/route.ts
Normal file
16
src/app/api/v1/document-templates/merge-fields/route.ts
Normal 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);
|
||||
}
|
||||
}),
|
||||
);
|
||||
56
src/app/api/v1/document-templates/route.ts
Normal file
56
src/app/api/v1/document-templates/route.ts
Normal 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);
|
||||
}
|
||||
}),
|
||||
);
|
||||
16
src/app/api/v1/documents/[id]/events/route.ts
Normal file
16
src/app/api/v1/documents/[id]/events/route.ts
Normal 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);
|
||||
}
|
||||
}),
|
||||
);
|
||||
16
src/app/api/v1/documents/[id]/remind/route.ts
Normal file
16
src/app/api/v1/documents/[id]/remind/route.ts
Normal 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);
|
||||
}
|
||||
}),
|
||||
);
|
||||
55
src/app/api/v1/documents/[id]/route.ts
Normal file
55
src/app/api/v1/documents/[id]/route.ts
Normal 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);
|
||||
}
|
||||
}),
|
||||
);
|
||||
21
src/app/api/v1/documents/[id]/send/route.ts
Normal file
21
src/app/api/v1/documents/[id]/send/route.ts
Normal 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);
|
||||
}
|
||||
}),
|
||||
);
|
||||
16
src/app/api/v1/documents/[id]/signers/route.ts
Normal file
16
src/app/api/v1/documents/[id]/signers/route.ts
Normal 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);
|
||||
}
|
||||
}),
|
||||
);
|
||||
41
src/app/api/v1/documents/[id]/upload-signed/route.ts
Normal file
41
src/app/api/v1/documents/[id]/upload-signed/route.ts
Normal 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);
|
||||
}
|
||||
}),
|
||||
);
|
||||
24
src/app/api/v1/documents/generate-eoi/route.ts
Normal file
24
src/app/api/v1/documents/generate-eoi/route.ts
Normal 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);
|
||||
}
|
||||
}),
|
||||
);
|
||||
50
src/app/api/v1/documents/route.ts
Normal file
50
src/app/api/v1/documents/route.ts
Normal 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);
|
||||
}
|
||||
}),
|
||||
);
|
||||
35
src/app/api/v1/email/accounts/[accountId]/route.ts
Normal file
35
src/app/api/v1/email/accounts/[accountId]/route.ts
Normal 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);
|
||||
}
|
||||
}),
|
||||
);
|
||||
17
src/app/api/v1/email/accounts/[accountId]/sync/route.ts
Normal file
17
src/app/api/v1/email/accounts/[accountId]/sync/route.ts
Normal 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);
|
||||
}
|
||||
}),
|
||||
);
|
||||
35
src/app/api/v1/email/accounts/route.ts
Normal file
35
src/app/api/v1/email/accounts/route.ts
Normal 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);
|
||||
}
|
||||
}),
|
||||
);
|
||||
24
src/app/api/v1/email/compose/route.ts
Normal file
24
src/app/api/v1/email/compose/route.ts
Normal 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);
|
||||
}
|
||||
}),
|
||||
);
|
||||
16
src/app/api/v1/email/threads/[threadId]/route.ts
Normal file
16
src/app/api/v1/email/threads/[threadId]/route.ts
Normal 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);
|
||||
}
|
||||
}),
|
||||
);
|
||||
33
src/app/api/v1/email/threads/route.ts
Normal file
33
src/app/api/v1/email/threads/route.ts
Normal 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);
|
||||
}
|
||||
}),
|
||||
);
|
||||
55
src/app/api/v1/expenses/[id]/route.ts
Normal file
55
src/app/api/v1/expenses/[id]/route.ts
Normal 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);
|
||||
}
|
||||
}),
|
||||
);
|
||||
27
src/app/api/v1/expenses/export/csv/route.ts
Normal file
27
src/app/api/v1/expenses/export/csv/route.ts
Normal 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);
|
||||
}
|
||||
}),
|
||||
);
|
||||
28
src/app/api/v1/expenses/export/parent-company/route.ts
Normal file
28
src/app/api/v1/expenses/export/parent-company/route.ts
Normal 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);
|
||||
}
|
||||
});
|
||||
26
src/app/api/v1/expenses/export/pdf/route.ts
Normal file
26
src/app/api/v1/expenses/export/pdf/route.ts
Normal 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);
|
||||
}
|
||||
}),
|
||||
);
|
||||
50
src/app/api/v1/expenses/route.ts
Normal file
50
src/app/api/v1/expenses/route.ts
Normal 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);
|
||||
}
|
||||
}),
|
||||
);
|
||||
27
src/app/api/v1/expenses/scan-receipt/route.ts
Normal file
27
src/app/api/v1/expenses/scan-receipt/route.ts
Normal 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);
|
||||
}
|
||||
}),
|
||||
);
|
||||
16
src/app/api/v1/files/[id]/download/route.ts
Normal file
16
src/app/api/v1/files/[id]/download/route.ts
Normal 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);
|
||||
}
|
||||
}),
|
||||
);
|
||||
16
src/app/api/v1/files/[id]/preview/route.ts
Normal file
16
src/app/api/v1/files/[id]/preview/route.ts
Normal 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);
|
||||
}
|
||||
}),
|
||||
);
|
||||
51
src/app/api/v1/files/[id]/route.ts
Normal file
51
src/app/api/v1/files/[id]/route.ts
Normal 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);
|
||||
}
|
||||
}),
|
||||
);
|
||||
75
src/app/api/v1/files/folders/[...path]/route.ts
Normal file
75
src/app/api/v1/files/folders/[...path]/route.ts
Normal 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);
|
||||
}
|
||||
}),
|
||||
);
|
||||
42
src/app/api/v1/files/folders/route.ts
Normal file
42
src/app/api/v1/files/folders/route.ts
Normal 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);
|
||||
}
|
||||
}),
|
||||
);
|
||||
33
src/app/api/v1/files/route.ts
Normal file
33
src/app/api/v1/files/route.ts
Normal 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);
|
||||
}
|
||||
}),
|
||||
);
|
||||
51
src/app/api/v1/files/upload/route.ts
Normal file
51
src/app/api/v1/files/upload/route.ts
Normal 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);
|
||||
}
|
||||
}),
|
||||
);
|
||||
44
src/app/api/v1/interests/[id]/berth/route.ts
Normal file
44
src/app/api/v1/interests/[id]/berth/route.ts
Normal 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);
|
||||
}
|
||||
}),
|
||||
);
|
||||
22
src/app/api/v1/interests/[id]/export-pdf/route.ts
Normal file
22
src/app/api/v1/interests/[id]/export-pdf/route.ts
Normal file
@@ -0,0 +1,22 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
|
||||
import { withAuth, withPermission } from '@/lib/api/helpers';
|
||||
import { errorResponse } from '@/lib/errors';
|
||||
import { exportInterestPdf } from '@/lib/services/record-export';
|
||||
|
||||
export const POST = withAuth(
|
||||
withPermission('interests', 'view', async (req, ctx, params) => {
|
||||
try {
|
||||
const pdfBytes = await exportInterestPdf(params.id!, ctx.portId);
|
||||
return new NextResponse(Buffer.from(pdfBytes), {
|
||||
status: 200,
|
||||
headers: {
|
||||
'Content-Type': 'application/pdf',
|
||||
'Content-Disposition': 'attachment; filename="interest-summary.pdf"',
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
}),
|
||||
);
|
||||
63
src/app/api/v1/interests/[id]/notes/[noteId]/route.ts
Normal file
63
src/app/api/v1/interests/[id]/notes/[noteId]/route.ts
Normal 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('interests', 'edit', async (req, ctx, params) => {
|
||||
try {
|
||||
const interestId = params.id;
|
||||
const noteId = params.noteId;
|
||||
if (!interestId) throw new NotFoundError('Interest');
|
||||
if (!noteId) throw new NotFoundError('Note');
|
||||
const body = await parseBody(req, updateNoteSchema);
|
||||
const note = await notesService.update(ctx.portId, 'interests', interestId, noteId, body);
|
||||
|
||||
void createAuditLog({
|
||||
userId: ctx.userId,
|
||||
portId: ctx.portId,
|
||||
action: 'update',
|
||||
entityType: 'interest_note',
|
||||
entityId: noteId,
|
||||
metadata: { interestId },
|
||||
ipAddress: ctx.ipAddress,
|
||||
userAgent: ctx.userAgent,
|
||||
});
|
||||
|
||||
return NextResponse.json({ data: note });
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
export const DELETE = withAuth(
|
||||
withPermission('interests', 'edit', async (_req, ctx, params) => {
|
||||
try {
|
||||
const interestId = params.id;
|
||||
const noteId = params.noteId;
|
||||
if (!interestId) throw new NotFoundError('Interest');
|
||||
if (!noteId) throw new NotFoundError('Note');
|
||||
await notesService.deleteNote(ctx.portId, 'interests', interestId, noteId);
|
||||
|
||||
void createAuditLog({
|
||||
userId: ctx.userId,
|
||||
portId: ctx.portId,
|
||||
action: 'delete',
|
||||
entityType: 'interest_note',
|
||||
entityId: noteId,
|
||||
metadata: { interestId },
|
||||
ipAddress: ctx.ipAddress,
|
||||
userAgent: ctx.userAgent,
|
||||
});
|
||||
|
||||
return new NextResponse(null, { status: 204 });
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
}),
|
||||
);
|
||||
55
src/app/api/v1/interests/[id]/notes/route.ts
Normal file
55
src/app/api/v1/interests/[id]/notes/route.ts
Normal 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('interests', 'view', async (_req, ctx, params) => {
|
||||
try {
|
||||
const interestId = params.id;
|
||||
if (!interestId) throw new NotFoundError('Interest');
|
||||
const notes = await notesService.listForEntity(ctx.portId, 'interests', interestId);
|
||||
return NextResponse.json({ data: notes });
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
export const POST = withAuth(
|
||||
withPermission('interests', 'edit', async (req, ctx, params) => {
|
||||
try {
|
||||
const interestId = params.id;
|
||||
if (!interestId) throw new NotFoundError('Interest');
|
||||
const body = await parseBody(req, createNoteSchema);
|
||||
const note = await notesService.create(ctx.portId, 'interests', interestId, ctx.userId, body);
|
||||
|
||||
void createAuditLog({
|
||||
userId: ctx.userId,
|
||||
portId: ctx.portId,
|
||||
action: 'create',
|
||||
entityType: 'interest_note',
|
||||
entityId: note.id,
|
||||
metadata: { interestId },
|
||||
ipAddress: ctx.ipAddress,
|
||||
userAgent: ctx.userAgent,
|
||||
});
|
||||
|
||||
emitToRoom(`interest:${interestId}`, 'interest:noteAdded', {
|
||||
interestId,
|
||||
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);
|
||||
}
|
||||
}),
|
||||
);
|
||||
@@ -0,0 +1,22 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
|
||||
import { withAuth, withPermission } from '@/lib/api/helpers';
|
||||
import { errorResponse } from '@/lib/errors';
|
||||
import { generateRecommendations } from '@/lib/services/recommendations';
|
||||
|
||||
// POST /api/v1/interests/[id]/recommendations/generate
|
||||
export const POST = withAuth(
|
||||
withPermission('interests', 'edit', async (req, ctx, params) => {
|
||||
try {
|
||||
const recommendations = await generateRecommendations(params.id!, ctx.portId, {
|
||||
userId: ctx.userId,
|
||||
portId: ctx.portId,
|
||||
ipAddress: ctx.ipAddress,
|
||||
userAgent: ctx.userAgent,
|
||||
});
|
||||
return NextResponse.json({ data: recommendations });
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
}),
|
||||
);
|
||||
39
src/app/api/v1/interests/[id]/recommendations/route.ts
Normal file
39
src/app/api/v1/interests/[id]/recommendations/route.ts
Normal file
@@ -0,0 +1,39 @@
|
||||
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 { listRecommendations, addManualRecommendation } from '@/lib/services/recommendations';
|
||||
|
||||
const addManualSchema = z.object({ berthId: z.string().min(1) });
|
||||
|
||||
// GET /api/v1/interests/[id]/recommendations
|
||||
export const GET = withAuth(
|
||||
withPermission('interests', 'view', async (req, ctx, params) => {
|
||||
try {
|
||||
const recommendations = await listRecommendations(params.id!, ctx.portId);
|
||||
return NextResponse.json({ data: recommendations });
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
// POST /api/v1/interests/[id]/recommendations — add manual recommendation
|
||||
export const POST = withAuth(
|
||||
withPermission('interests', 'edit', async (req, ctx, params) => {
|
||||
try {
|
||||
const body = await parseBody(req, addManualSchema);
|
||||
const rec = await addManualRecommendation(params.id!, ctx.portId, body.berthId, {
|
||||
userId: ctx.userId,
|
||||
portId: ctx.portId,
|
||||
ipAddress: ctx.ipAddress,
|
||||
userAgent: ctx.userAgent,
|
||||
});
|
||||
return NextResponse.json({ data: rec }, { status: 201 });
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
}),
|
||||
);
|
||||
21
src/app/api/v1/interests/[id]/restore/route.ts
Normal file
21
src/app/api/v1/interests/[id]/restore/route.ts
Normal file
@@ -0,0 +1,21 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
|
||||
import { withAuth, withPermission } from '@/lib/api/helpers';
|
||||
import { errorResponse } from '@/lib/errors';
|
||||
import { restoreInterest } from '@/lib/services/interests.service';
|
||||
|
||||
export const POST = withAuth(
|
||||
withPermission('interests', 'edit', async (req, ctx, params) => {
|
||||
try {
|
||||
await restoreInterest(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);
|
||||
}
|
||||
}),
|
||||
);
|
||||
55
src/app/api/v1/interests/[id]/route.ts
Normal file
55
src/app/api/v1/interests/[id]/route.ts
Normal 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 {
|
||||
getInterestById,
|
||||
updateInterest,
|
||||
archiveInterest,
|
||||
} from '@/lib/services/interests.service';
|
||||
import { updateInterestSchema } from '@/lib/validators/interests';
|
||||
|
||||
export const GET = withAuth(
|
||||
withPermission('interests', 'view', async (req, ctx, params) => {
|
||||
try {
|
||||
const interest = await getInterestById(params.id!, ctx.portId);
|
||||
return NextResponse.json({ data: interest });
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
export const PATCH = withAuth(
|
||||
withPermission('interests', 'edit', async (req, ctx, params) => {
|
||||
try {
|
||||
const body = await parseBody(req, updateInterestSchema);
|
||||
const interest = await updateInterest(params.id!, ctx.portId, body, {
|
||||
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', 'delete', async (req, ctx, params) => {
|
||||
try {
|
||||
await archiveInterest(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);
|
||||
}
|
||||
}),
|
||||
);
|
||||
24
src/app/api/v1/interests/[id]/stage/route.ts
Normal file
24
src/app/api/v1/interests/[id]/stage/route.ts
Normal 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 { changeInterestStage } from '@/lib/services/interests.service';
|
||||
import { changeStageSchema } from '@/lib/validators/interests';
|
||||
|
||||
export const PATCH = withAuth(
|
||||
withPermission('interests', 'change_stage', async (req, ctx, params) => {
|
||||
try {
|
||||
const body = await parseBody(req, changeStageSchema);
|
||||
const interest = await changeInterestStage(params.id!, ctx.portId, body, {
|
||||
userId: ctx.userId,
|
||||
portId: ctx.portId,
|
||||
ipAddress: ctx.ipAddress,
|
||||
userAgent: ctx.userAgent,
|
||||
});
|
||||
return NextResponse.json({ data: interest });
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
}),
|
||||
);
|
||||
28
src/app/api/v1/interests/[id]/tags/route.ts
Normal file
28
src/app/api/v1/interests/[id]/tags/route.ts
Normal 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 { setInterestTags } from '@/lib/services/interests.service';
|
||||
|
||||
const setTagsSchema = z.object({
|
||||
tagIds: z.array(z.string()),
|
||||
});
|
||||
|
||||
export const PUT = withAuth(
|
||||
withPermission('interests', 'edit', async (req, ctx, params) => {
|
||||
try {
|
||||
const body = await parseBody(req, setTagsSchema);
|
||||
const result = await setInterestTags(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);
|
||||
}
|
||||
}),
|
||||
);
|
||||
113
src/app/api/v1/interests/[id]/timeline/route.ts
Normal file
113
src/app/api/v1/interests/[id]/timeline/route.ts
Normal file
@@ -0,0 +1,113 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { and, eq, desc, inArray } from 'drizzle-orm';
|
||||
|
||||
import { withAuth, withPermission } from '@/lib/api/helpers';
|
||||
import { errorResponse, NotFoundError } from '@/lib/errors';
|
||||
import { db } from '@/lib/db';
|
||||
import { interests } from '@/lib/db/schema/interests';
|
||||
import { auditLogs } from '@/lib/db/schema/system';
|
||||
import { documents, documentEvents } from '@/lib/db/schema/documents';
|
||||
|
||||
interface TimelineEvent {
|
||||
id: string;
|
||||
type: 'audit' | 'document_event';
|
||||
action: string;
|
||||
description: string;
|
||||
userId: string | null;
|
||||
createdAt: Date;
|
||||
metadata: Record<string, unknown>;
|
||||
}
|
||||
|
||||
// GET /api/v1/interests/[id]/timeline
|
||||
export const GET = withAuth(
|
||||
withPermission('interests', 'view', async (req, ctx, params) => {
|
||||
try {
|
||||
const interestId = params.id!;
|
||||
|
||||
const interest = await db.query.interests.findFirst({
|
||||
where: and(eq(interests.id, interestId), eq(interests.portId, ctx.portId)),
|
||||
});
|
||||
if (!interest) throw new NotFoundError('Interest');
|
||||
|
||||
// Fetch audit logs for this interest
|
||||
const auditRows = await db
|
||||
.select()
|
||||
.from(auditLogs)
|
||||
.where(
|
||||
and(
|
||||
eq(auditLogs.entityType, 'interest'),
|
||||
eq(auditLogs.entityId, interestId),
|
||||
),
|
||||
)
|
||||
.orderBy(desc(auditLogs.createdAt))
|
||||
.limit(50);
|
||||
|
||||
// Fetch document events for documents linked to this interest
|
||||
const interestDocs = await db
|
||||
.select({ id: documents.id, title: documents.title })
|
||||
.from(documents)
|
||||
.where(eq(documents.interestId, interestId));
|
||||
|
||||
const docIds = interestDocs.map((d) => d.id);
|
||||
const docEventRows =
|
||||
docIds.length > 0
|
||||
? await db
|
||||
.select({
|
||||
id: documentEvents.id,
|
||||
documentId: documentEvents.documentId,
|
||||
eventType: documentEvents.eventType,
|
||||
eventData: documentEvents.eventData,
|
||||
createdAt: documentEvents.createdAt,
|
||||
})
|
||||
.from(documentEvents)
|
||||
.where(inArray(documentEvents.documentId, docIds))
|
||||
.orderBy(desc(documentEvents.createdAt))
|
||||
.limit(50)
|
||||
: [];
|
||||
|
||||
const docTitles = Object.fromEntries(interestDocs.map((d) => [d.id, d.title]));
|
||||
|
||||
// Union and sort
|
||||
const auditEvents: TimelineEvent[] = auditRows.map((row) => ({
|
||||
id: row.id,
|
||||
type: 'audit',
|
||||
action: row.action,
|
||||
description: buildAuditDescription(row.action, row.newValue as Record<string, unknown> | null),
|
||||
userId: row.userId,
|
||||
createdAt: row.createdAt,
|
||||
metadata: (row.metadata as Record<string, unknown>) ?? {},
|
||||
}));
|
||||
|
||||
const docEvents: TimelineEvent[] = docEventRows.map((row) => ({
|
||||
id: row.id,
|
||||
type: 'document_event',
|
||||
action: row.eventType,
|
||||
description: `Document "${docTitles[row.documentId] ?? row.documentId}": ${row.eventType}`,
|
||||
userId: null,
|
||||
createdAt: row.createdAt,
|
||||
metadata: (row.eventData as Record<string, unknown>) ?? {},
|
||||
}));
|
||||
|
||||
const allEvents = [...auditEvents, ...docEvents];
|
||||
allEvents.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());
|
||||
|
||||
return NextResponse.json({ data: allEvents.slice(0, 50) });
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
function buildAuditDescription(
|
||||
action: string,
|
||||
newValue: Record<string, unknown> | null,
|
||||
): string {
|
||||
if (action === 'create') return 'Interest created';
|
||||
if (action === 'archive') return 'Interest archived';
|
||||
if (action === 'restore') return 'Interest restored';
|
||||
if (action === 'update' && newValue?.pipelineStage) {
|
||||
return `Stage changed to "${newValue.pipelineStage}"`;
|
||||
}
|
||||
if (action === 'update') return 'Interest updated';
|
||||
return action;
|
||||
}
|
||||
50
src/app/api/v1/interests/route.ts
Normal file
50
src/app/api/v1/interests/route.ts
Normal 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 { listInterests, createInterest } from '@/lib/services/interests.service';
|
||||
import { listInterestsSchema, createInterestSchema } from '@/lib/validators/interests';
|
||||
|
||||
export const GET = withAuth(
|
||||
withPermission('interests', 'view', async (req, ctx) => {
|
||||
try {
|
||||
const query = parseQuery(req, listInterestsSchema);
|
||||
const result = await listInterests(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('interests', 'create', async (req, ctx) => {
|
||||
try {
|
||||
const body = await parseBody(req, createInterestSchema);
|
||||
const interest = await createInterest(ctx.portId, body, {
|
||||
userId: ctx.userId,
|
||||
portId: ctx.portId,
|
||||
ipAddress: ctx.ipAddress,
|
||||
userAgent: ctx.userAgent,
|
||||
});
|
||||
return NextResponse.json({ data: interest }, { status: 201 });
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
}),
|
||||
);
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user