task-d.5.3
This commit is contained in:
62
src/app/api/crm/leads/[id]/assign/route.ts
Normal file
62
src/app/api/crm/leads/[id]/assign/route.ts
Normal file
@@ -0,0 +1,62 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { z } from 'zod';
|
||||
import { assignLeadSchema } from '@/features/crm/leads/schemas/lead.schema';
|
||||
import { assignLead } from '@/features/crm/leads/server/assignment.service';
|
||||
import { buildLeadAccessContext } from '@/features/crm/leads/server/service';
|
||||
import { PERMISSIONS } from '@/lib/auth/rbac';
|
||||
import { AuthError, requireOrganizationAccess } from '@/lib/auth/session';
|
||||
|
||||
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.crmLeadAssign
|
||||
});
|
||||
const payload = assignLeadSchema.parse(await request.json());
|
||||
const accessContext = buildLeadAccessContext({
|
||||
organizationId: organization.id,
|
||||
userId: session.user.id,
|
||||
membership
|
||||
});
|
||||
|
||||
const result = await assignLead(
|
||||
organization.id,
|
||||
session.user.id,
|
||||
{
|
||||
leadId: id,
|
||||
salesOwnerId: payload.salesOwnerId,
|
||||
assignmentRemark: payload.assignmentRemark
|
||||
},
|
||||
accessContext
|
||||
);
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
message: 'Lead assigned successfully',
|
||||
leadId: result.leadId,
|
||||
enquiryId: result.enquiryId,
|
||||
enquiryCode: result.enquiryCode
|
||||
});
|
||||
} 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 assign lead' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user