83 lines
2.8 KiB
TypeScript
83 lines
2.8 KiB
TypeScript
import { NextRequest, NextResponse } from 'next/server';
|
|
import { z } from 'zod';
|
|
import { auditAction } from '@/features/foundation/audit-log/service';
|
|
import { getEnquiryDetail, reassignEnquiryToUser } from '@/features/crm/enquiries/server/service';
|
|
import { PERMISSIONS } from '@/lib/auth/rbac';
|
|
import { AuthError, requireOrganizationAccess } from '@/lib/auth/session';
|
|
import { enquiryAssignmentRequestSchema } from '../_schemas';
|
|
|
|
type Params = {
|
|
params: Promise<{ id: string }>;
|
|
};
|
|
|
|
export async function POST(request: NextRequest, { params }: Params) {
|
|
try {
|
|
const { id } = await params;
|
|
const { organization, session, membership } = await requireOrganizationAccess({
|
|
permission: PERMISSIONS.crmEnquiryReassign
|
|
});
|
|
const payload = enquiryAssignmentRequestSchema.parse(await request.json());
|
|
const accessContext = {
|
|
organizationId: organization.id,
|
|
userId: session.user.id,
|
|
membershipRole: membership.role,
|
|
businessRole: membership.businessRole,
|
|
permissions: membership.permissions ?? [],
|
|
branchScopeIds: membership.branchScopeIds ?? [],
|
|
productTypeScopeIds: membership.productTypeScopeIds ?? [],
|
|
ownershipScope: membership.ownershipScope ?? 'organization',
|
|
branchScopeMode: membership.branchScopeMode === 'assigned' ? 'assigned' : 'all',
|
|
productScopeMode: membership.productScopeMode === 'assigned' ? 'assigned' : 'all'
|
|
};
|
|
const before = await getEnquiryDetail(id, organization.id, accessContext);
|
|
const updated = await reassignEnquiryToUser(
|
|
id,
|
|
organization.id,
|
|
session.user.id,
|
|
payload,
|
|
accessContext
|
|
);
|
|
|
|
await auditAction({
|
|
organizationId: organization.id,
|
|
branchId: updated.branchId,
|
|
userId: session.user.id,
|
|
entityType: 'crm_enquiry',
|
|
entityId: id,
|
|
action: 'reassign',
|
|
beforeData: {
|
|
oldAssignedToUserId: before.assignedToUserId,
|
|
oldPipelineStage: before.pipelineStage
|
|
},
|
|
afterData: {
|
|
newAssignedToUserId: updated.assignedToUserId,
|
|
newPipelineStage: updated.pipelineStage,
|
|
remark: updated.assignmentRemark
|
|
}
|
|
});
|
|
|
|
return NextResponse.json({
|
|
success: true,
|
|
message: 'Enquiry reassigned successfully',
|
|
enquiry: 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 }
|
|
);
|
|
}
|
|
|
|
if (error instanceof Error) {
|
|
return NextResponse.json({ message: error.message }, { status: 400 });
|
|
}
|
|
|
|
return NextResponse.json({ message: 'Unable to reassign enquiry' }, { status: 500 });
|
|
}
|
|
}
|