177 lines
5.6 KiB
TypeScript
177 lines
5.6 KiB
TypeScript
import { NextRequest, NextResponse } from 'next/server';
|
|
import { z } from 'zod';
|
|
import { listRecentActivitiesForContext } from '@/features/crm/activities/server/timeline-service';
|
|
import { auditDelete, auditUpdate } from '@/features/foundation/audit-log/service';
|
|
import {
|
|
auditCrmSecurityEvent,
|
|
buildCrmSecurityContext
|
|
} from '@/features/crm/security/server/service';
|
|
import {
|
|
getCustomerActivity,
|
|
getCustomerDetail,
|
|
getCustomerOwnerHistory,
|
|
softDeleteCustomer,
|
|
updateCustomer
|
|
} from '@/features/crm/customers/server/service';
|
|
import { customerSchema } from '@/features/crm/customers/schemas/customer.schema';
|
|
import { PERMISSIONS } from '@/lib/auth/rbac';
|
|
import { AuthError, requireOrganizationAccess } from '@/lib/auth/session';
|
|
|
|
type Params = {
|
|
params: Promise<{ id: string }>;
|
|
};
|
|
|
|
const customerRequestSchema = customerSchema.extend({
|
|
branchId: z.string().nullable().optional(),
|
|
leadChannel: z.string().nullable().optional(),
|
|
customerGroup: z.string().nullable().optional(),
|
|
customerSubGroup: z.string().nullable().optional()
|
|
});
|
|
|
|
export async function GET(_request: NextRequest, { params }: Params) {
|
|
try {
|
|
const { id } = await params;
|
|
const { organization, session, membership } = await requireOrganizationAccess({
|
|
permission: PERMISSIONS.crmCustomerRead
|
|
});
|
|
const accessContext = buildCrmSecurityContext({
|
|
organizationId: organization.id,
|
|
userId: session.user.id,
|
|
membership
|
|
});
|
|
const [customer, activity, ownerHistory, recentActivities] = await Promise.all([
|
|
getCustomerDetail(id, organization.id, accessContext),
|
|
getCustomerActivity(id, organization.id),
|
|
getCustomerOwnerHistory(id, organization.id, accessContext),
|
|
listRecentActivitiesForContext({
|
|
organizationId: organization.id,
|
|
entityType: 'customer',
|
|
entityId: id,
|
|
context: accessContext,
|
|
limit: 6
|
|
})
|
|
]);
|
|
|
|
return NextResponse.json({
|
|
success: true,
|
|
time: new Date().toISOString(),
|
|
message: 'Customer loaded successfully',
|
|
customer,
|
|
activity,
|
|
recentActivities,
|
|
ownerHistory
|
|
});
|
|
} catch (error) {
|
|
if (error instanceof AuthError) {
|
|
if (error.status === 403) {
|
|
const access = await requireOrganizationAccess({
|
|
permission: PERMISSIONS.crmCustomerRead
|
|
}).catch(() => null);
|
|
|
|
if (access) {
|
|
await auditCrmSecurityEvent({
|
|
organizationId: access.organization.id,
|
|
userId: access.session.user.id,
|
|
action: 'customer_scope_violation',
|
|
entityType: 'crm_customer',
|
|
entityId: (await params).id,
|
|
reason: 'Customer detail visibility denied'
|
|
});
|
|
}
|
|
}
|
|
return NextResponse.json({ message: error.message }, { status: error.status });
|
|
}
|
|
|
|
console.error('GET /api/crm/customers/[id] failed', error);
|
|
|
|
return NextResponse.json({ message: 'Unable to load customer' }, { status: 500 });
|
|
}
|
|
}
|
|
|
|
export async function PATCH(request: NextRequest, { params }: Params) {
|
|
try {
|
|
const { id } = await params;
|
|
const { organization, session, membership } = await requireOrganizationAccess({
|
|
permission: PERMISSIONS.crmCustomerUpdate
|
|
});
|
|
const payload = customerRequestSchema.parse(await request.json());
|
|
const accessContext = buildCrmSecurityContext({
|
|
organizationId: organization.id,
|
|
userId: session.user.id,
|
|
membership
|
|
});
|
|
const before = await getCustomerDetail(id, organization.id, accessContext);
|
|
const updated = await updateCustomer(id, organization.id, session.user.id, payload, accessContext);
|
|
|
|
await auditUpdate({
|
|
organizationId: organization.id,
|
|
branchId: updated.branchId,
|
|
userId: session.user.id,
|
|
entityType: 'crm_customer',
|
|
entityId: id,
|
|
beforeData: before,
|
|
afterData: updated
|
|
});
|
|
|
|
return NextResponse.json({
|
|
success: true,
|
|
message: 'Customer updated successfully',
|
|
customer: updated
|
|
});
|
|
} catch (error) {
|
|
if (error instanceof AuthError) {
|
|
return NextResponse.json({ message: error.message }, { status: error.status });
|
|
}
|
|
|
|
if (error instanceof z.ZodError) {
|
|
return NextResponse.json(
|
|
{ message: error.issues[0]?.message ?? 'Invalid payload' },
|
|
{ status: 400 }
|
|
);
|
|
}
|
|
|
|
console.error('PATCH /api/crm/customers/[id] failed', error);
|
|
|
|
return NextResponse.json({ message: 'Unable to update customer' }, { status: 500 });
|
|
}
|
|
}
|
|
|
|
export async function DELETE(_request: NextRequest, { params }: Params) {
|
|
try {
|
|
const { id } = await params;
|
|
const { organization, session, membership } = await requireOrganizationAccess({
|
|
permission: PERMISSIONS.crmCustomerDelete
|
|
});
|
|
const accessContext = buildCrmSecurityContext({
|
|
organizationId: organization.id,
|
|
userId: session.user.id,
|
|
membership
|
|
});
|
|
const before = await getCustomerDetail(id, organization.id, accessContext);
|
|
const updated = await softDeleteCustomer(id, organization.id, session.user.id, accessContext);
|
|
|
|
await auditDelete({
|
|
organizationId: organization.id,
|
|
branchId: updated.branchId,
|
|
userId: session.user.id,
|
|
entityType: 'crm_customer',
|
|
entityId: id,
|
|
beforeData: before,
|
|
afterData: updated
|
|
});
|
|
|
|
return NextResponse.json({
|
|
success: true,
|
|
message: 'Customer deleted successfully'
|
|
});
|
|
} catch (error) {
|
|
if (error instanceof AuthError) {
|
|
return NextResponse.json({ message: error.message }, { status: error.status });
|
|
}
|
|
|
|
console.error('DELETE /api/crm/customers/[id] failed', error);
|
|
|
|
return NextResponse.json({ message: 'Unable to delete customer' }, { status: 500 });
|
|
}
|
|
}
|