Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,16 @@ import { NextResponse, type NextRequest } from "next/server";

import { getCurrentUser } from "@/lib/auth";
import { parseFormSpec } from "@/lib/forms";
import { canManageForms } from "@/lib/guild";
import { canManageForm } from "@/lib/guild";
import { isGuildPro } from "@/lib/plan";

export const runtime = "nodejs";
export const dynamic = "force-dynamic";

/**
* Export a form's definition (structure + settings, not submissions) as a
* portable JSON file. Manager-only and Pro+, mirroring the import endpoint.
* portable JSON file. Requires a guild manager or per-form manager, and Pro+,
* mirroring the import endpoint.
*/
export async function GET(
_request: NextRequest,
Expand All @@ -26,7 +27,7 @@ export async function GET(

const user = await getCurrentUser();
if (!user) return NextResponse.json({ error: "Unauthorized." }, { status: 401 });
if (!(await canManageForms(guildId, user.id))) {
if (!(await canManageForm(guildId, user.id, formId))) {
return NextResponse.json({ error: "Forbidden." }, { status: 403 });
}
if (!(await isGuildPro(guildId))) {
Expand Down
13 changes: 7 additions & 6 deletions apps/web/src/app/api/guilds/[guildId]/forms/[formId]/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,14 @@ import { NextResponse, type NextRequest } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { formInputSchema } from "@/lib/form-input";
import { resolveGuildCategoryId } from "@/lib/forms";
import { canManageForms } from "@/lib/guild";
import { canManageForm } from "@/lib/guild";
import { isGuildPro } from "@/lib/plan";
import { deleteObject } from "@/lib/s3";

export const runtime = "nodejs";
export const dynamic = "force-dynamic";

/** Update an existing form. Requires owner/admin and form ∈ guild. */
/** Update an existing form. Requires a guild manager or per-form manager, form ∈ guild. */
export async function PATCH(
request: NextRequest,
{ params }: { params: Promise<{ guildId: string; formId: string }> },
Expand All @@ -20,7 +20,7 @@ export async function PATCH(

const user = await getCurrentUser();
if (!user) return NextResponse.json({ error: "Unauthorized." }, { status: 401 });
if (!(await canManageForms(guildId, user.id))) {
if (!(await canManageForm(guildId, user.id, formId))) {
return NextResponse.json({ error: "Forbidden." }, { status: 403 });
}

Expand Down Expand Up @@ -83,8 +83,9 @@ export async function PATCH(

/**
* Delete a form and everything under it (versions, submissions, events, files,
* status defs all cascade). Owner/admin only, form ∈ guild. Stored file objects
* are purged from object storage best-effort after the row is gone.
* status defs all cascade). Requires a guild manager or per-form manager, form ∈
* guild. Stored file objects are purged from object storage best-effort after
* the row is gone.
*/
export async function DELETE(
_request: NextRequest,
Expand All @@ -94,7 +95,7 @@ export async function DELETE(

const user = await getCurrentUser();
if (!user) return NextResponse.json({ error: "Unauthorized." }, { status: 401 });
if (!(await canManageForms(guildId, user.id))) {
if (!(await canManageForm(guildId, user.id, formId))) {
return NextResponse.json({ error: "Forbidden." }, { status: 403 });
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,25 @@ export async function PUT(
return NextResponse.json({ error: "Forbidden." }, { status: 403 });
}

const body = (await request.json().catch(() => null)) as { formIds?: unknown } | null;
const requested = Array.isArray(body?.formIds)
? body.formIds.filter((x): x is string => typeof x === "string")
: null;
// Each grant is a form the member may access; `manage` upgrades it from
// review-only to full management of that single form. Legacy `formIds`
// (review-only) is still accepted for compatibility.
const body = (await request.json().catch(() => null)) as {
grants?: unknown;
formIds?: unknown;
} | null;
const requested: { formId: string; manage: boolean }[] | null = Array.isArray(body?.grants)
? body.grants
.filter(
(g): g is { formId: string; manage?: unknown } =>
typeof g === "object" && g !== null && typeof (g as { formId?: unknown }).formId === "string",
)
.map((g) => ({ formId: g.formId, manage: (g as { manage?: unknown }).manage === true }))
: Array.isArray(body?.formIds)
? body.formIds
.filter((x): x is string => typeof x === "string")
.map((formId) => ({ formId, manage: false }))
: null;
if (requested === null) {
return NextResponse.json({ error: "Invalid request." }, { status: 422 });
}
Expand All @@ -41,15 +56,16 @@ export async function PUT(

// Keep only ids that are actually this guild's forms.
const guildForms = await prisma.form.findMany({
where: { guildId, id: { in: requested } },
where: { guildId, id: { in: requested.map((g) => g.formId) } },
select: { id: true },
});
const formIds = guildForms.map((f) => f.id);
const valid = new Set(guildForms.map((f) => f.id));
const grants = requested.filter((g) => valid.has(g.formId));

// Plan member cap: only when this grant newly adds the user to the team.
const currentGrants = await prisma.formReviewer.count({ where: { userId, form: { guildId } } });
const countedBefore = countsTowardTeam(member.role, currentGrants > 0);
const countsAfter = countsTowardTeam(member.role, formIds.length > 0);
const countsAfter = countsTowardTeam(member.role, grants.length > 0);
if (countsAfter && !countedBefore) {
const { memberLimit } = await getGuildPlan(guildId);
if (memberLimit !== null && (await countTeamMembers(guildId)) >= memberLimit) {
Expand All @@ -63,8 +79,12 @@ export async function PUT(
// Replace the grants atomically.
await prisma.$transaction([
prisma.formReviewer.deleteMany({ where: { userId, form: { guildId } } }),
...(formIds.length > 0
? [prisma.formReviewer.createMany({ data: formIds.map((formId) => ({ formId, userId })) })]
...(grants.length > 0
? [
prisma.formReviewer.createMany({
data: grants.map((g) => ({ formId: g.formId, userId, canManage: g.manage })),
}),
]
: []),
]);
return NextResponse.json({ ok: true });
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import {
getStatusOptionsForGuild,
parseFormSpec,
} from "@/lib/forms";
import { canManageForms } from "@/lib/guild";
import { canManageForm } from "@/lib/guild";
import { isGuildPro } from "@/lib/plan";
import { getDict } from "@/i18n";

Expand All @@ -26,7 +26,7 @@ export default async function EditFormPage({
const { guildId, formId } = await params;
const user = await requireUser(`/dashboard/${guildId}/forms/${formId}/edit`);
const t = await getDict();
if (!(await canManageForms(guildId, user.id))) {
if (!(await canManageForm(guildId, user.id, formId))) {
return (
<Card className="p-8">
<p className="text-muted-foreground">{t.dashboard.noPermEdit}</p>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import { FormRenderer } from "@/components/form/form-renderer";
import { requireUser } from "@/lib/auth";
import { brandStyle, logoUrl, parseBranding } from "@/lib/branding";
import { getFormForEdit, parseFormSpec } from "@/lib/forms";
import { canManageForms } from "@/lib/guild";
import { canManageForm } from "@/lib/guild";
import { getDict } from "@/i18n";

export const runtime = "nodejs";
Expand All @@ -31,7 +31,7 @@ export default async function FormPreviewPage({
const dict = await getDict();
const t = dict.form;

if (!(await canManageForms(guildId, user.id))) {
if (!(await canManageForm(guildId, user.id, formId))) {
return (
<Card className="p-8">
<p className="text-muted-foreground">{dict.dashboard.noPermEdit}</p>
Expand Down
16 changes: 10 additions & 6 deletions apps/web/src/app/dashboard/[guildId]/forms/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import { ShareButton } from "@/components/dashboard/share-button";
import { LocalDateTime } from "@/components/public/local-datetime";
import { requireUser } from "@/lib/auth";
import { appBaseUrl } from "@/lib/url";
import { canManageForms, getGuildForms, getReviewScope } from "@/lib/guild";
import { canManageForms, getGuildForms, getManageScope, getReviewScope } from "@/lib/guild";
import { getGuildPlan } from "@/lib/plan";
import { enterpriseEnabled, stripeEnabled } from "@/lib/stripe";
import { getDict } from "@/i18n";
Expand All @@ -36,11 +36,15 @@ export default async function GuildFormsPage({
const { guildId } = await params;
const user = await requireUser(`/dashboard/${guildId}/forms`);
const scope = await getReviewScope(guildId, user.id);
const [forms, canManage, plan] = await Promise.all([
const [forms, canManage, manageScope, plan] = await Promise.all([
getGuildForms(guildId, scope),
canManageForms(guildId, user.id),
getManageScope(guildId, user.id),
getGuildPlan(guildId),
]);
// Whether the viewer may fully manage a given form (guild manager or a per-form
// manage grant). Drives the per-form edit/preview/delete/export-definition buttons.
const manages = (formId: string) => manageScope.all || manageScope.formIds.includes(formId);
const base = appBaseUrl();
const dict = await getDict();
const t = dict.dashboard;
Expand Down Expand Up @@ -206,15 +210,15 @@ export default async function GuildFormsPage({
)}
</div>
)}
{canManage && plan.isPro && (
{manages(form.id) && plan.isPro && (
<a
href={`/api/guilds/${guildId}/forms/${form.id}/definition`}
className="rounded-md border border-border px-3 py-1.5 text-sm font-medium text-muted-foreground transition-colors hover:border-primary/40 hover:text-foreground"
>
{t.formIo.export}
</a>
)}
{canManage && (
{manages(form.id) && (
<Link
href={`/dashboard/${guildId}/forms/${form.id}/preview` as Route}
target="_blank"
Expand All @@ -224,7 +228,7 @@ export default async function GuildFormsPage({
{t.preview}
</Link>
)}
{canManage && (
{manages(form.id) && (
<Link
href={`/dashboard/${guildId}/forms/${form.id}/edit` as Route}
className="rounded-md border border-border px-3 py-1.5 text-sm font-medium text-muted-foreground transition-colors hover:border-primary/40 hover:text-foreground"
Expand Down Expand Up @@ -253,7 +257,7 @@ export default async function GuildFormsPage({
{t.experimentLink}
</Link>
)}
{canManage && (
{manages(form.id) && (
<DeleteFormButton
guildId={guildId}
formId={form.id}
Expand Down
11 changes: 7 additions & 4 deletions apps/web/src/app/dashboard/[guildId]/members/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ export default async function MembersPage({
}),
prisma.formReviewer.findMany({
where: { form: { guildId } },
select: { userId: true, formId: true },
select: { userId: true, formId: true, canManage: true },
}),
prisma.form.findMany({
where: { guildId },
Expand All @@ -47,16 +47,19 @@ export default async function MembersPage({
countTeamMembers(guildId),
]);

const grantsByUser: Record<string, string[]> = {};
for (const g of grants) (grantsByUser[g.userId] ??= []).push(g.formId);
// Per-user, per-form access level: "manage" (full) or "review" (read).
const accessByUser: Record<string, Record<string, "review" | "manage">> = {};
for (const g of grants) {
(accessByUser[g.userId] ??= {})[g.formId] = g.canManage ? "manage" : "review";
}

const rows: MemberRow[] = members
.map((m) => ({
userId: m.user.id,
username: m.user.username,
avatar: m.user.avatar,
role: m.role,
formIds: grantsByUser[m.user.id] ?? [],
access: accessByUser[m.user.id] ?? {},
}))
.sort((a, b) => (ROLE_ORDER[a.role] ?? 9) - (ROLE_ORDER[b.role] ?? 9) || a.username.localeCompare(b.username));

Expand Down
55 changes: 35 additions & 20 deletions apps/web/src/components/members/members-manager.tsx
Original file line number Diff line number Diff line change
@@ -1,18 +1,22 @@
"use client";

import { Button, Card, Checkbox, Field, Input, Select } from "@msk-forms/ui";
import { Button, Card, Field, Input, Select } from "@msk-forms/ui";
import { useRouter } from "next/navigation";
import { useState } from "react";

import { ConfirmDialog } from "@/components/confirm-dialog";
import type { Dictionary } from "@/i18n";

/** Per-form access a member holds: none, review-only, or full management. */
export type FormAccess = "none" | "review" | "manage";

export interface MemberRow {
userId: string;
username: string;
avatar: string | null;
role: string;
formIds: string[];
/** Per-form access level (absent form id = no access). */
access: Record<string, "review" | "manage">;
}

type MembersDict = Dictionary["members"];
Expand All @@ -38,9 +42,9 @@ export function MembersManager({
const [confirmRemove, setConfirmRemove] = useState<MemberRow | null>(null);
const [addId, setAddId] = useState("");
const [addRole, setAddRole] = useState("viewer");
// Local per-user form selection, seeded from props.
const [grants, setGrants] = useState<Record<string, Set<string>>>(
() => Object.fromEntries(members.map((m) => [m.userId, new Set(m.formIds)])),
// Local per-user, per-form access map, seeded from props.
const [access, setAccess] = useState<Record<string, Record<string, "review" | "manage">>>(
() => Object.fromEntries(members.map((m) => [m.userId, { ...m.access }])),
);

const roleLabel: Record<string, string> = {
Expand Down Expand Up @@ -90,14 +94,15 @@ export function MembersManager({
);
}

function toggleForm(m: MemberRow, formId: string) {
const next = new Set(grants[m.userId] ?? []);
if (next.has(formId)) next.delete(formId);
else next.add(formId);
setGrants((g) => ({ ...g, [m.userId]: next }));
function setFormAccess(m: MemberRow, formId: string, level: FormAccess) {
const next = { ...(access[m.userId] ?? {}) };
if (level === "none") delete next[formId];
else next[formId] = level;
setAccess((a) => ({ ...a, [m.userId]: next }));
const grants = Object.entries(next).map(([id, lvl]) => ({ formId: id, manage: lvl === "manage" }));
void call(
`/api/guilds/${guildId}/members/${m.userId}/forms`,
{ method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ formIds: [...next] }) },
{ method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ grants }) },
m.userId,
);
}
Expand Down Expand Up @@ -186,21 +191,31 @@ export function MembersManager({
)}
</div>

{/* Per-form reviewer grants only matter for viewers (reviewers see all). */}
{/* Per-form grants only matter for viewers (reviewers already see all). */}
{m.role === "viewer" && forms.length > 0 && (
<div className="flex flex-col gap-2 rounded-md border border-border bg-muted/30 p-3">
<p className="text-xs font-medium text-foreground">{t.formAccess}</p>
<p className="text-xs text-muted-foreground">{t.formAccessHint}</p>
<div className="flex flex-col gap-1.5">
{forms.map((f) => (
<Checkbox
key={f.id}
id={`${m.userId}-${f.id}`}
label={f.title}
checked={grants[m.userId]?.has(f.id) ?? false}
disabled={busy === m.userId}
onChange={() => toggleForm(m, f.id)}
/>
<div key={f.id} className="flex items-center justify-between gap-2">
<span translate="no" className="min-w-0 truncate text-sm text-foreground">
{f.title}
</span>
<div className="w-40 shrink-0">
<Select
aria-label={f.title}
value={access[m.userId]?.[f.id] ?? "none"}
disabled={busy === m.userId}
onChange={(e) => setFormAccess(m, f.id, e.target.value as FormAccess)}
options={[
{ value: "none", label: t.accessNone },
{ value: "review", label: t.accessReview },
{ value: "manage", label: t.accessManage },
]}
/>
</div>
</div>
))}
</div>
</div>
Expand Down
Loading