feat(bulk): synchronous bulk action endpoints + UI on interests/clients/yachts

Until now the only bulk action anywhere was Archive on the interests
list — implemented as parallel fan-out with no per-row failure
reporting. The bulk BullMQ worker was a TODO stub with no producers.

- bulk-helpers.runBulk wraps a per-row loop and returns
  {results, summary} for the caller. Page-size capped at 100.
- New endpoints: /api/v1/{interests,clients,yachts,companies}/bulk
  with a Zod discriminated union over the action. Interests support
  change_stage + add_tag + remove_tag + archive; clients/yachts/companies
  support archive + add_tag + remove_tag. Each action is permission-gated
  individually (delete vs edit vs change_stage).
- interest-list, client-list, yacht-list expose the new actions in the
  bulk-action toolbar with dialogs for stage / tag selection. Failure
  summaries surface via window.confirm.
- bulkWorker stub gets a docblock explaining the v1 sync-only choice
  and what the queue is reserved for (CSV imports, port-wide migrations,
  bulk emails to >100 recipients).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
Matt Ciaccio
2026-05-06 14:58:34 +02:00
parent c90876abad
commit 3f6a8aa3b8
9 changed files with 827 additions and 17 deletions

View File

@@ -0,0 +1,76 @@
import { NextResponse } from 'next/server';
import { z } from 'zod';
import { eq, and } from 'drizzle-orm';
import { withAuth } from '@/lib/api/helpers';
import { parseBody } from '@/lib/api/route-helpers';
import { runBulk } from '@/lib/api/bulk-helpers';
import { db } from '@/lib/db';
import { clients, clientTags } from '@/lib/db/schema/clients';
import { archiveClient, setClientTags } from '@/lib/services/clients.service';
import { errorResponse } from '@/lib/errors';
const bulkSchema = z.discriminatedUnion('action', [
z.object({
action: z.literal('archive'),
ids: z.array(z.string().min(1)).min(1).max(100),
}),
z.object({
action: z.literal('add_tag'),
ids: z.array(z.string().min(1)).min(1).max(100),
tagId: z.string().min(1),
}),
z.object({
action: z.literal('remove_tag'),
ids: z.array(z.string().min(1)).min(1).max(100),
tagId: z.string().min(1),
}),
]);
const PERMISSION_BY_ACTION = {
archive: 'delete' as const,
add_tag: 'edit' as const,
remove_tag: 'edit' as const,
};
export const POST = withAuth(async (req, ctx) => {
let body: z.infer<typeof bulkSchema>;
try {
body = await parseBody(req, bulkSchema);
} catch (error) {
return errorResponse(error);
}
const allowed = ctx.isSuperAdmin
? true
: !!ctx.permissions?.clients?.[PERMISSION_BY_ACTION[body.action]];
if (!allowed) return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
const meta = {
userId: ctx.userId,
portId: ctx.portId,
ipAddress: ctx.ipAddress,
userAgent: ctx.userAgent,
};
const { results, summary } = await runBulk(body.ids, async (id) => {
if (body.action === 'archive') {
await archiveClient(id, ctx.portId, meta);
return;
}
const client = await db.query.clients.findFirst({
where: and(eq(clients.id, id), eq(clients.portId, ctx.portId)),
});
if (!client) throw new Error('Client not found');
const existing = await db
.select({ tagId: clientTags.tagId })
.from(clientTags)
.where(eq(clientTags.clientId, id));
const current = new Set(existing.map((t) => t.tagId));
if (body.action === 'add_tag') current.add(body.tagId);
else current.delete(body.tagId);
await setClientTags(id, ctx.portId, Array.from(current), meta);
});
return NextResponse.json({ data: { results, summary } });
});

View File

@@ -0,0 +1,76 @@
import { NextResponse } from 'next/server';
import { z } from 'zod';
import { eq, and } from 'drizzle-orm';
import { withAuth } from '@/lib/api/helpers';
import { parseBody } from '@/lib/api/route-helpers';
import { runBulk } from '@/lib/api/bulk-helpers';
import { db } from '@/lib/db';
import { companies, companyTags } from '@/lib/db/schema/companies';
import { archiveCompany, setCompanyTags } from '@/lib/services/companies.service';
import { errorResponse } from '@/lib/errors';
const bulkSchema = z.discriminatedUnion('action', [
z.object({
action: z.literal('archive'),
ids: z.array(z.string().min(1)).min(1).max(100),
}),
z.object({
action: z.literal('add_tag'),
ids: z.array(z.string().min(1)).min(1).max(100),
tagId: z.string().min(1),
}),
z.object({
action: z.literal('remove_tag'),
ids: z.array(z.string().min(1)).min(1).max(100),
tagId: z.string().min(1),
}),
]);
const PERMISSION_BY_ACTION = {
archive: 'delete' as const,
add_tag: 'edit' as const,
remove_tag: 'edit' as const,
};
export const POST = withAuth(async (req, ctx) => {
let body: z.infer<typeof bulkSchema>;
try {
body = await parseBody(req, bulkSchema);
} catch (error) {
return errorResponse(error);
}
const allowed = ctx.isSuperAdmin
? true
: !!ctx.permissions?.companies?.[PERMISSION_BY_ACTION[body.action]];
if (!allowed) return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
const meta = {
userId: ctx.userId,
portId: ctx.portId,
ipAddress: ctx.ipAddress,
userAgent: ctx.userAgent,
};
const { results, summary } = await runBulk(body.ids, async (id) => {
if (body.action === 'archive') {
await archiveCompany(id, ctx.portId, meta);
return;
}
const company = await db.query.companies.findFirst({
where: and(eq(companies.id, id), eq(companies.portId, ctx.portId)),
});
if (!company) throw new Error('Company not found');
const existing = await db
.select({ tagId: companyTags.tagId })
.from(companyTags)
.where(eq(companyTags.companyId, id));
const current = new Set(existing.map((t) => t.tagId));
if (body.action === 'add_tag') current.add(body.tagId);
else current.delete(body.tagId);
await setCompanyTags(id, ctx.portId, Array.from(current), meta);
});
return NextResponse.json({ data: { results, summary } });
});

View File

@@ -0,0 +1,135 @@
import { NextResponse } from 'next/server';
import { z } from 'zod';
import { eq, and, inArray } from 'drizzle-orm';
import { withAuth, withPermission } from '@/lib/api/helpers';
import { parseBody } from '@/lib/api/route-helpers';
import { db } from '@/lib/db';
import { interests } from '@/lib/db/schema/interests';
import { interestTags } from '@/lib/db/schema/interests';
import {
archiveInterest,
changeInterestStage,
setInterestTags,
} from '@/lib/services/interests.service';
import { PIPELINE_STAGES } from '@/lib/constants';
import { errorResponse } from '@/lib/errors';
/**
* Synchronous bulk endpoint for the interests list.
*
* Per-row loop is fine for the page-size cap (100 rows max). Larger jobs
* (CSV imports, port-wide migrations) belong on the BullMQ `bulk` queue —
* see src/lib/queue/workers/bulk.ts. The synchronous path gives the user
* instant feedback and a per-row failure list, which the queue can't.
*/
const bulkSchema = z.discriminatedUnion('action', [
z.object({
action: z.literal('change_stage'),
ids: z.array(z.string().min(1)).min(1).max(100),
pipelineStage: z.enum(PIPELINE_STAGES),
}),
z.object({
action: z.literal('add_tag'),
ids: z.array(z.string().min(1)).min(1).max(100),
tagId: z.string().min(1),
}),
z.object({
action: z.literal('remove_tag'),
ids: z.array(z.string().min(1)).min(1).max(100),
tagId: z.string().min(1),
}),
z.object({
action: z.literal('archive'),
ids: z.array(z.string().min(1)).min(1).max(100),
}),
]);
interface RowResult {
id: string;
ok: boolean;
error?: string;
}
const PERMISSION_BY_ACTION: Record<
z.infer<typeof bulkSchema>['action'],
{ resource: 'interests'; action: 'change_stage' | 'edit' | 'delete' }
> = {
change_stage: { resource: 'interests', action: 'change_stage' },
add_tag: { resource: 'interests', action: 'edit' },
remove_tag: { resource: 'interests', action: 'edit' },
archive: { resource: 'interests', action: 'delete' },
};
export const POST = withAuth(async (req, ctx) => {
let body: z.infer<typeof bulkSchema>;
try {
body = await parseBody(req, bulkSchema);
} catch (error) {
return errorResponse(error);
}
// Per-action permission check (mirrors the per-row endpoints).
const perm = PERMISSION_BY_ACTION[body.action];
const allowed = ctx.isSuperAdmin ? true : !!ctx.permissions?.[perm.resource]?.[perm.action];
if (!allowed) {
return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
}
const meta = {
userId: ctx.userId,
portId: ctx.portId,
ipAddress: ctx.ipAddress,
userAgent: ctx.userAgent,
};
const results: RowResult[] = [];
for (const id of body.ids) {
try {
if (body.action === 'change_stage') {
await changeInterestStage(id, ctx.portId, { pipelineStage: body.pipelineStage }, meta);
} else if (body.action === 'archive') {
await archiveInterest(id, ctx.portId, meta);
} else if (body.action === 'add_tag' || body.action === 'remove_tag') {
// Tenant gate: load the existing interest tag set, mutate, save.
const interest = await db.query.interests.findFirst({
where: and(eq(interests.id, id), eq(interests.portId, ctx.portId)),
});
if (!interest) {
results.push({ id, ok: false, error: 'Interest not found' });
continue;
}
const existingTags = await db
.select({ tagId: interestTags.tagId })
.from(interestTags)
.where(eq(interestTags.interestId, id));
const current = new Set(existingTags.map((t) => t.tagId));
if (body.action === 'add_tag') current.add(body.tagId);
else current.delete(body.tagId);
await setInterestTags(id, ctx.portId, Array.from(current), meta);
}
results.push({ id, ok: true });
} catch (err) {
results.push({
id,
ok: false,
error: err instanceof Error ? err.message : 'unknown error',
});
}
}
const summary = {
total: results.length,
succeeded: results.filter((r) => r.ok).length,
failed: results.filter((r) => !r.ok).length,
};
return NextResponse.json({ data: { results, summary } });
});
// Keep a single import alive (linter); used in the Drizzle inArray pattern below
// in case a future caller wants set-based ops instead of per-row loops.
void inArray;
void withPermission;

View File

@@ -0,0 +1,76 @@
import { NextResponse } from 'next/server';
import { z } from 'zod';
import { eq, and } from 'drizzle-orm';
import { withAuth } from '@/lib/api/helpers';
import { parseBody } from '@/lib/api/route-helpers';
import { runBulk } from '@/lib/api/bulk-helpers';
import { db } from '@/lib/db';
import { yachts, yachtTags } from '@/lib/db/schema/yachts';
import { archiveYacht, setYachtTags } from '@/lib/services/yachts.service';
import { errorResponse } from '@/lib/errors';
const bulkSchema = z.discriminatedUnion('action', [
z.object({
action: z.literal('archive'),
ids: z.array(z.string().min(1)).min(1).max(100),
}),
z.object({
action: z.literal('add_tag'),
ids: z.array(z.string().min(1)).min(1).max(100),
tagId: z.string().min(1),
}),
z.object({
action: z.literal('remove_tag'),
ids: z.array(z.string().min(1)).min(1).max(100),
tagId: z.string().min(1),
}),
]);
const PERMISSION_BY_ACTION = {
archive: 'delete' as const,
add_tag: 'edit' as const,
remove_tag: 'edit' as const,
};
export const POST = withAuth(async (req, ctx) => {
let body: z.infer<typeof bulkSchema>;
try {
body = await parseBody(req, bulkSchema);
} catch (error) {
return errorResponse(error);
}
const allowed = ctx.isSuperAdmin
? true
: !!ctx.permissions?.yachts?.[PERMISSION_BY_ACTION[body.action]];
if (!allowed) return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
const meta = {
userId: ctx.userId,
portId: ctx.portId,
ipAddress: ctx.ipAddress,
userAgent: ctx.userAgent,
};
const { results, summary } = await runBulk(body.ids, async (id) => {
if (body.action === 'archive') {
await archiveYacht(id, ctx.portId, meta);
return;
}
const yacht = await db.query.yachts.findFirst({
where: and(eq(yachts.id, id), eq(yachts.portId, ctx.portId)),
});
if (!yacht) throw new Error('Yacht not found');
const existing = await db
.select({ tagId: yachtTags.tagId })
.from(yachtTags)
.where(eq(yachtTags.yachtId, id));
const current = new Set(existing.map((t) => t.tagId));
if (body.action === 'add_tag') current.add(body.tagId);
else current.delete(body.tagId);
await setYachtTags(id, ctx.portId, Array.from(current), meta);
});
return NextResponse.json({ data: { results, summary } });
});