Session 6.3

This commit is contained in:
2026-04-10 21:56:31 +02:00
parent f20d5f09ae
commit 94bfd25553
24 changed files with 2398 additions and 104 deletions

View File

@@ -0,0 +1,81 @@
import { NextResponse } from "next/server";
import { requirePlatformRole } from "@/lib/session";
import { getTenantRequestById, updateTenantRequestStatus } from "@/lib/db";
import { createTenant } from "@/lib/k8s";
/**
* POST /api/admin/requests/[id]/approve
* Approve a tenant request: create the PiecedTenant CR and update status.
*/
export async function POST(
request: Request,
{ params }: { params: Promise<{ id: string }> }
) {
try {
await requirePlatformRole();
} catch {
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
}
const { id } = await params;
const body = await request.json().catch(() => ({}));
const adminNotes = body.adminNotes as string | undefined;
const tenantRequest = await getTenantRequestById(id);
if (!tenantRequest) {
return NextResponse.json(
{ error: "Request not found" },
{ status: 404 }
);
}
if (tenantRequest.status !== "pending") {
return NextResponse.json(
{ error: `Request is already ${tenantRequest.status}` },
{ status: 400 }
);
}
// Derive tenant name from company name: lowercase, alphanumeric + hyphens
const tenantName = tenantRequest.companyName
.toLowerCase()
.replace(/[^a-z0-9]+/g, "-")
.replace(/^-|-$/g, "")
.slice(0, 63) || `tenant-${tenantRequest.id.slice(0, 8)}`;
try {
// Create the PiecedTenant CR
await createTenant(
tenantName,
{
displayName: tenantRequest.companyName,
agentName: tenantRequest.agentName,
packages: tenantRequest.packages,
workspaceFiles: tenantRequest.soulMd
? { "SOUL.md": tenantRequest.soulMd }
: undefined,
},
{
"pieced.ch/zitadel-org-id": tenantRequest.zitadelOrgId,
}
);
// Update request status
const updated = await updateTenantRequestStatus(id, "provisioning", {
adminNotes,
tenantName,
});
return NextResponse.json({
message: "Tenant approved and provisioning started.",
request: updated,
tenantName,
});
} catch (e: any) {
console.error("Failed to create tenant:", e);
return NextResponse.json(
{ error: `Failed to create tenant: ${e.message}` },
{ status: 500 }
);
}
}

View File

@@ -0,0 +1,43 @@
import { NextResponse } from "next/server";
import { requirePlatformRole } from "@/lib/session";
import { getTenantRequestById, updateTenantRequestStatus } from "@/lib/db";
/**
* POST /api/admin/requests/[id]/reject
* Reject a tenant request.
*/
export async function POST(
request: Request,
{ params }: { params: Promise<{ id: string }> }
) {
try {
await requirePlatformRole();
} catch {
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
}
const { id } = await params;
const body = await request.json().catch(() => ({}));
const adminNotes = body.adminNotes as string | undefined;
const tenantRequest = await getTenantRequestById(id);
if (!tenantRequest) {
return NextResponse.json({ error: "Request not found" }, { status: 404 });
}
if (tenantRequest.status !== "pending") {
return NextResponse.json(
{ error: `Request is already ${tenantRequest.status}` },
{ status: 400 }
);
}
const updated = await updateTenantRequestStatus(id, "rejected", {
adminNotes,
});
return NextResponse.json({
message: "Request rejected.",
request: updated,
});
}

View File

@@ -0,0 +1,21 @@
import { NextResponse } from "next/server";
import { requirePlatformRole } from "@/lib/session";
import { listTenantRequests } from "@/lib/db";
/**
* GET /api/admin/requests
* List all tenant requests. Optionally filter by ?status=pending
*/
export async function GET(request: Request) {
try {
await requirePlatformRole();
} catch {
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
}
const { searchParams } = new URL(request.url);
const status = searchParams.get("status") as any;
const requests = await listTenantRequests(status || undefined);
return NextResponse.json(requests);
}

View File

@@ -0,0 +1,145 @@
import { NextResponse } from "next/server";
import { getSessionUser } from "@/lib/session";
import {
createTenantRequest,
getTenantRequestByOrgId,
} from "@/lib/db";
import { getTenant, listTenants } from "@/lib/k8s";
import type { OnboardingInput } from "@/types";
import { z } from "zod";
const onboardingSchema = z.object({
agentName: z.string().min(1).max(50),
soulMd: z.string().max(10_000).optional(),
packages: z.array(z.string()).optional(),
billingAddress: z.object({
company: z.string().optional(),
street: z.string().optional(),
city: z.string().optional(),
postalCode: z.string().optional(),
country: z.string().optional(),
}),
billingNotes: z.string().max(2000).optional(),
});
/**
* GET /api/onboarding
* Returns the current onboarding status for the logged-in user's org.
* Used by the wizard/provisioning UI to poll state.
*/
export async function GET() {
const user = await getSessionUser();
if (!user)
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
// Check if tenant already exists
const allTenants = await listTenants();
const myTenant = allTenants.find(
(t) => t.metadata.labels?.["pieced.ch/zitadel-org-id"] === user.orgId
);
if (myTenant) {
return NextResponse.json({
state: "provisioned",
tenant: {
name: myTenant.metadata.name,
phase: myTenant.status?.phase ?? "Pending",
message: myTenant.status?.message,
conditions: myTenant.status?.conditions,
},
});
}
// Check if there's a pending request
const request = await getTenantRequestByOrgId(user.orgId);
if (!request) {
return NextResponse.json({ state: "no_request" });
}
// If approved and tenant_name set, check provisioning status
if (
request.status === "provisioning" &&
request.tenantName
) {
const tenant = await getTenant(request.tenantName);
if (tenant) {
return NextResponse.json({
state: "provisioning",
request,
tenant: {
name: tenant.metadata.name,
phase: tenant.status?.phase ?? "Pending",
message: tenant.status?.message,
conditions: tenant.status?.conditions,
},
});
}
}
return NextResponse.json({
state: request.status,
request,
});
}
/**
* POST /api/onboarding
* Submit the onboarding wizard. Creates a tenant_request with status "pending".
* The actual PiecedTenant CR is NOT created yet — admin approval required.
*/
export async function POST(request: Request) {
const user = await getSessionUser();
if (!user)
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
// Check for existing request
const existing = await getTenantRequestByOrgId(user.orgId);
if (existing) {
return NextResponse.json(
{ error: "Onboarding request already submitted.", request: existing },
{ status: 409 }
);
}
// Check for existing tenant
const allTenants = await listTenants();
const myTenant = allTenants.find(
(t) => t.metadata.labels?.["pieced.ch/zitadel-org-id"] === user.orgId
);
if (myTenant) {
return NextResponse.json(
{ error: "Tenant already exists." },
{ status: 409 }
);
}
const body = await request.json();
const parsed = onboardingSchema.safeParse(body);
if (!parsed.success) {
return NextResponse.json(
{ error: "Validation failed", details: parsed.error.flatten() },
{ status: 400 }
);
}
const input: OnboardingInput = parsed.data;
const tenantRequest = await createTenantRequest({
zitadelOrgId: user.orgId,
zitadelUserId: user.id,
companyName: user.orgName,
contactName: user.name || user.email,
contactEmail: user.email,
agentName: input.agentName,
soulMd: input.soulMd,
packages: input.packages ?? [],
billingAddress: input.billingAddress,
billingNotes: input.billingNotes,
});
return NextResponse.json(
{ message: "Onboarding request submitted.", request: tenantRequest },
{ status: 201 }
);
}

View File

@@ -0,0 +1,70 @@
import { NextResponse } from "next/server";
import { registerCustomer } from "@/lib/zitadel";
import type { RegistrationInput } from "@/types";
import { z } from "zod";
const registrationSchema = z.object({
companyName: z.string().min(2).max(100),
givenName: z.string().min(1).max(100),
familyName: z.string().min(1).max(100),
email: z.string().email(),
preferredLanguage: z.enum(["en", "de", "fr", "it"]).optional(),
});
export async function POST(request: Request) {
try {
const body = await request.json();
const parsed = registrationSchema.safeParse(body);
if (!parsed.success) {
return NextResponse.json(
{ error: "Validation failed", details: parsed.error.flatten() },
{ status: 400 }
);
}
const input: RegistrationInput = parsed.data;
const result = await registerCustomer({
companyName: input.companyName,
email: input.email,
givenName: input.givenName,
familyName: input.familyName,
preferredLanguage: input.preferredLanguage,
});
return NextResponse.json(
{
orgId: result.orgId,
userId: result.userId,
message: "Registration successful. You will receive an invitation email to set your password.",
},
{ status: 201 }
);
} catch (e: any) {
console.error("Registration failed:", e);
const zitadelMessage = extractZitadelMessage(e.message);
return NextResponse.json(
{ error: zitadelMessage || "Registration failed. Please try again." },
{ status: e.statusCode || 500 }
);
}
}
/**
* ZITADEL errors come as:
* "ZITADEL POST /path: 400 {"code":3, "message":"..."}"
* Extract the human-readable "message" field.
*/
function extractZitadelMessage(errorMsg: string): string | null {
try {
const jsonStart = errorMsg.indexOf("{");
if (jsonStart === -1) return null;
const json = JSON.parse(errorMsg.slice(jsonStart));
return json.message || null;
} catch {
return null;
}
}