36 lines
1.5 KiB
TypeScript
36 lines
1.5 KiB
TypeScript
import { can } from "@wrnexus/authz";
|
|
import { getDb } from "@wrnexus/db";
|
|
import type { Context } from "@wrnexus/core";
|
|
import { ensureCrmWorkspace } from "../lib/workspace.ts";
|
|
|
|
const userId = (ctx: Context) => String((ctx.user as { id?: unknown } | undefined)?.id ?? "");
|
|
|
|
export async function GET(ctx: Context): Promise<Response> {
|
|
if (!(await can(ctx, "contact:read")))
|
|
return Response.json({ error: "Forbidden" }, { status: 403 });
|
|
await ensureCrmWorkspace(userId(ctx));
|
|
const rows = await getDb().all(
|
|
"SELECT id,name,email,company,phone,status,created_at FROM crm_contacts WHERE owner_id = ? ORDER BY name",
|
|
[userId(ctx)],
|
|
);
|
|
return Response.json({ contacts: rows });
|
|
}
|
|
|
|
export async function POST(ctx: Context): Promise<Response> {
|
|
if (!(await can(ctx, "contact:write")))
|
|
return Response.json({ error: "Forbidden" }, { status: 403 });
|
|
const body = (await ctx.req.json()) as Record<string, unknown>;
|
|
const name = String(body.name ?? "").trim();
|
|
const email = String(body.email ?? "")
|
|
.trim()
|
|
.toLowerCase();
|
|
if (!name || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
|
|
return Response.json({ error: "A name and valid email are required" }, { status: 400 });
|
|
}
|
|
const result = await getDb().exec(
|
|
"INSERT INTO crm_contacts (owner_id,name,email,company,phone,status) VALUES (?,?,?,?,?,?)",
|
|
[userId(ctx), name, email, String(body.company ?? ""), String(body.phone ?? ""), "lead"],
|
|
);
|
|
return Response.json({ id: Number(result.lastInsertId), name, email }, { status: 201 });
|
|
}
|