Add Roles & Admin/Super-Admin interface
Per organized-ideas.md §6: role assignment, account ban/unban/delete, and direct Admin/Super-Admin CRUD of public catalog entries outside the submission workflow. Backend: - list_users_for_admin(): Super-Admin-gated SECURITY DEFINER function joining profiles + auth.users (username, email, role, banned_until) — auth.users isn't exposed through PostgREST, so this is the only way to list accounts at all. - New Edge Function admin-user-action (ban/unban/delete), using @supabase/server's `auth: 'user'` mode to verify the caller's JWT, then Supabase Auth's Admin API for the actual mutation. This is deliberately an Edge Function rather than a Postgres function like everything else in this codebase: touching auth.users needs the Admin API, the stable documented interface, not a direct write to a schema Supabase manages internally. Self-action guard; verify_jwt = true at the gateway on top of the function's own JWT verification. - 5 new pgTAP tests (43/43 total) for list_users_for_admin (Super-Admin-only, even regular Admins get 42501). - CatalogRepository gains admin* methods (direct edit of a public port/cable/ device entry, plus adminUnpublish which flips is_public rather than deleting) — the update methods were already ownership-agnostic (RLS's is_admin() clause is what actually permits it), so these are thin aliases, not duplicated logic. Frontend: - authStore/AdminUserRepository: minimal role plumbing, shared UserRole type. - adminUserStore + AdminUsersModal: list/role-dropdown/ban/unban/delete, gated to Super Admin only via a new "Manage Users" TopBar button. - PortTypeManager/CableTypeManager/DevicePalette: built-in entries now show direct "Edit"/"Unpublish" for Admins (regular Admin included, per §6's capability table — not Super-Admin-exclusive) instead of "Suggest edit"; unpublish reuses the review-queue's impact-check RPC before confirming. - DeviceTemplateEditor gains an `adminMode` save path alongside its existing submissionMode/resubmitId ones. Verified: tsc -b and oxlint clean; supabase db reset + 43/43 pgTAP tests pass; confirmed both new privileged endpoints (the SQL function and the Edge Function) actually work through the real REST API via live curl calls — signup, email confirm, role promotion, ban/unban/delete round trips, self-action guard, non-super-admin rejection, and verify_jwt=true compatibility all exercised directly, not just asserted.
This commit is contained in:
@@ -0,0 +1,137 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import type { AdminUserSummary, UserRole } from '../../data/AdminUserRepository'
|
||||
import { useAdminUserStore } from '../../state/adminUserStore'
|
||||
import { useAuthStore } from '../../state/authStore'
|
||||
import Modal from '../common/Modal'
|
||||
|
||||
const ROLE_OPTIONS: UserRole[] = ['regular', 'admin', 'super_admin']
|
||||
|
||||
function formatDate(iso: string): string {
|
||||
return new Date(iso).toLocaleDateString(undefined, { dateStyle: 'medium' })
|
||||
}
|
||||
|
||||
function isBanned(user: AdminUserSummary): boolean {
|
||||
return !!user.bannedUntil && new Date(user.bannedUntil).getTime() > Date.now()
|
||||
}
|
||||
|
||||
export default function AdminUsersModal({ onClose }: { onClose: () => void }) {
|
||||
const currentUserId = useAuthStore((s) => s.userId)
|
||||
const users = useAdminUserStore((s) => s.users)
|
||||
const loadUsers = useAdminUserStore((s) => s.loadUsers)
|
||||
const updateRole = useAdminUserStore((s) => s.updateRole)
|
||||
const banUser = useAdminUserStore((s) => s.banUser)
|
||||
const unbanUser = useAdminUserStore((s) => s.unbanUser)
|
||||
const deleteUser = useAdminUserStore((s) => s.deleteUser)
|
||||
const [busyId, setBusyId] = useState<string | null>(null)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
loadUsers()
|
||||
}, [loadUsers])
|
||||
|
||||
const runAction = async (userId: string, action: () => Promise<void>) => {
|
||||
setError(null)
|
||||
setBusyId(userId)
|
||||
try {
|
||||
await action()
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Something went wrong.')
|
||||
} finally {
|
||||
setBusyId(null)
|
||||
}
|
||||
}
|
||||
|
||||
const handleRoleChange = (user: AdminUserSummary, role: UserRole) => {
|
||||
if (user.id === currentUserId && role !== 'super_admin') {
|
||||
const confirmed = window.confirm(
|
||||
`Change your own role to "${role}"? You'll lose Super Admin access immediately — another Super Admin (or direct DB access) would be needed to undo this.`,
|
||||
)
|
||||
if (!confirmed) return
|
||||
}
|
||||
runAction(user.id, () => updateRole(user.id, role))
|
||||
}
|
||||
|
||||
const handleBanToggle = (user: AdminUserSummary) => {
|
||||
const banned = isBanned(user)
|
||||
const confirmed = window.confirm(
|
||||
banned ? `Unban "${user.username}"? They'll be able to sign in again.` : `Ban "${user.username}"? This blocks sign-in but keeps their data intact — reversible.`,
|
||||
)
|
||||
if (!confirmed) return
|
||||
runAction(user.id, () => (banned ? unbanUser(user.id) : banUser(user.id)))
|
||||
}
|
||||
|
||||
const handleDelete = (user: AdminUserSummary) => {
|
||||
const confirmed = window.confirm(
|
||||
`Permanently delete "${user.username}"? This deletes their account AND all their diagrams and private catalog entries. This cannot be undone.`,
|
||||
)
|
||||
if (!confirmed) return
|
||||
runAction(user.id, () => deleteUser(user.id))
|
||||
}
|
||||
|
||||
return (
|
||||
<Modal title="Manage Users" onClose={onClose} width="max-w-2xl">
|
||||
{error && <p className="mb-2 rounded bg-red-50 px-2 py-1.5 text-xs text-red-700">{error}</p>}
|
||||
<div className="space-y-1.5">
|
||||
{users.map((user) => {
|
||||
const busy = busyId === user.id
|
||||
const self = user.id === currentUserId
|
||||
const banned = isBanned(user)
|
||||
return (
|
||||
<div key={user.id} className="flex items-center justify-between gap-2 rounded border border-slate-200 bg-white px-2.5 py-1.5 text-xs">
|
||||
<div className="min-w-0">
|
||||
<div className="flex items-center gap-1.5">
|
||||
<span className="font-medium text-slate-700">{user.username}</span>
|
||||
{self && (
|
||||
<span className="rounded bg-indigo-50 px-1.5 py-0.5 text-[10px] font-medium text-indigo-600">You</span>
|
||||
)}
|
||||
{banned && (
|
||||
<span className="rounded bg-red-50 px-1.5 py-0.5 text-[10px] font-medium text-red-600">Banned</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="truncate text-[10px] text-slate-400">
|
||||
{user.email} · joined {formatDate(user.createdAt)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex shrink-0 items-center gap-1.5">
|
||||
<select
|
||||
value={user.role}
|
||||
disabled={busy}
|
||||
onChange={(e) => handleRoleChange(user, e.target.value as UserRole)}
|
||||
className="rounded border border-slate-300 px-1 py-1 text-[11px] disabled:opacity-50"
|
||||
>
|
||||
{ROLE_OPTIONS.map((r) => (
|
||||
<option key={r} value={r}>
|
||||
{r}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<button
|
||||
onClick={() => handleBanToggle(user)}
|
||||
disabled={busy || self}
|
||||
title={self ? "You can't ban your own account" : undefined}
|
||||
className="rounded bg-slate-100 px-2 py-1 text-[11px] font-medium text-slate-600 hover:bg-amber-50 hover:text-amber-700 disabled:cursor-not-allowed disabled:opacity-40"
|
||||
>
|
||||
{banned ? 'Unban' : 'Ban'}
|
||||
</button>
|
||||
<button
|
||||
onClick={() => handleDelete(user)}
|
||||
disabled={busy || self}
|
||||
title={self ? "You can't delete your own account" : undefined}
|
||||
className="rounded bg-slate-100 px-2 py-1 text-[11px] font-medium text-slate-600 hover:bg-red-50 hover:text-red-600 disabled:cursor-not-allowed disabled:opacity-40"
|
||||
>
|
||||
Delete
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
{users.length === 0 && <p className="py-2 text-center text-xs italic text-slate-400">No users found.</p>}
|
||||
</div>
|
||||
<div className="mt-4 flex justify-end border-t border-slate-100 pt-3">
|
||||
<button onClick={onClose} className="rounded px-3 py-1.5 text-xs text-slate-600 hover:bg-slate-100">
|
||||
Close
|
||||
</button>
|
||||
</div>
|
||||
</Modal>
|
||||
)
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import { useAdminReviewStore } from '../../state/adminReviewStore'
|
||||
import { useAuthStore } from '../../state/authStore'
|
||||
import { useProjectStore } from '../../state/projectStore'
|
||||
import { useSubmissionStore } from '../../state/submissionStore'
|
||||
import AdminUsersModal from '../admin/AdminUsersModal'
|
||||
import AdminReviewModal from '../submissions/AdminReviewModal'
|
||||
import MySubmissionsModal from '../submissions/MySubmissionsModal'
|
||||
import DiagramManagerModal from './DiagramManagerModal'
|
||||
@@ -37,11 +38,13 @@ export default function TopBar() {
|
||||
const username = useAuthStore((s) => s.username)
|
||||
const role = useAuthStore((s) => s.role)
|
||||
const isAdmin = role === 'admin' || role === 'super_admin'
|
||||
const isSuperAdmin = role === 'super_admin'
|
||||
const adminPendingCount = useAdminReviewStore((s) => s.allSubmissions.filter((sub) => sub.status === 'pending').length)
|
||||
const fileInputRef = useRef<HTMLInputElement>(null)
|
||||
const [diagramManagerOpen, setDiagramManagerOpen] = useState(false)
|
||||
const [submissionsOpen, setSubmissionsOpen] = useState(false)
|
||||
const [adminReviewOpen, setAdminReviewOpen] = useState(false)
|
||||
const [adminUsersOpen, setAdminUsersOpen] = useState(false)
|
||||
|
||||
const pendingSubmissionCount = useMemo(
|
||||
() => mySubmissions.filter((s) => s.status === 'pending').length,
|
||||
@@ -121,6 +124,14 @@ export default function TopBar() {
|
||||
)}
|
||||
</button>
|
||||
)}
|
||||
{isSuperAdmin && (
|
||||
<button
|
||||
onClick={() => setAdminUsersOpen(true)}
|
||||
className="rounded px-2.5 py-1.5 text-xs text-slate-600 hover:bg-slate-100"
|
||||
>
|
||||
Manage Users
|
||||
</button>
|
||||
)}
|
||||
<button onClick={handleImportClick} className="rounded px-2.5 py-1.5 text-xs text-slate-600 hover:bg-slate-100">
|
||||
Import
|
||||
</button>
|
||||
@@ -142,6 +153,7 @@ export default function TopBar() {
|
||||
{diagramManagerOpen && <DiagramManagerModal onClose={() => setDiagramManagerOpen(false)} />}
|
||||
{submissionsOpen && <MySubmissionsModal onClose={() => setSubmissionsOpen(false)} />}
|
||||
{adminReviewOpen && <AdminReviewModal onClose={() => setAdminReviewOpen(false)} />}
|
||||
{adminUsersOpen && <AdminUsersModal onClose={() => setAdminUsersOpen(false)} />}
|
||||
</header>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -2,6 +2,8 @@ import { useMemo, useState } from 'react'
|
||||
import { allCableTypes, allPortTypes } from '../../domain/project'
|
||||
import type { CableType, PortType } from '../../domain/types'
|
||||
import { cableTypeToRow } from '../../data/catalogRowMapping'
|
||||
import { useAdminReviewStore } from '../../state/adminReviewStore'
|
||||
import { useAuthStore } from '../../state/authStore'
|
||||
import { useCatalogStore } from '../../state/catalogStore'
|
||||
import { useSubmissionStore } from '../../state/submissionStore'
|
||||
import { resolveCableTypeFields, type CableTypeFormFields } from './cableTypeFormFields'
|
||||
@@ -129,11 +131,17 @@ export default function CableTypesPanel() {
|
||||
const catalog = useCatalogStore((s) => s.catalog)
|
||||
const addCustomCableType = useCatalogStore((s) => s.addCustomCableType)
|
||||
const updateCustomCableType = useCatalogStore((s) => s.updateCustomCableType)
|
||||
const adminUpdateCableType = useCatalogStore((s) => s.adminUpdateCableType)
|
||||
const adminUnpublish = useCatalogStore((s) => s.adminUnpublish)
|
||||
const mySubmissions = useSubmissionStore((s) => s.mySubmissions)
|
||||
const submitForReview = useSubmissionStore((s) => s.submitForReview)
|
||||
const getUsageImpact = useAdminReviewStore((s) => s.getUsageImpact)
|
||||
const role = useAuthStore((s) => s.role)
|
||||
const isAdmin = role === 'admin' || role === 'super_admin'
|
||||
const [creating, setCreating] = useState(false)
|
||||
const [editingId, setEditingId] = useState<string | null>(null)
|
||||
const [suggestingId, setSuggestingId] = useState<string | null>(null)
|
||||
const [adminEditingId, setAdminEditingId] = useState<string | null>(null)
|
||||
|
||||
const portTypes = useMemo(
|
||||
() => [...allPortTypes(catalog)].sort((a, b) => a.name.localeCompare(b.name)),
|
||||
@@ -185,6 +193,24 @@ export default function CableTypesPanel() {
|
||||
setSuggestingId(null)
|
||||
}
|
||||
|
||||
const handleAdminSave = (id: string, fields: CableTypeFormFields) => {
|
||||
const resolved = resolveCableTypeFields(fields, portTypes)
|
||||
if (!resolved) return
|
||||
adminUpdateCableType(id, resolved)
|
||||
setAdminEditingId(null)
|
||||
}
|
||||
|
||||
const handleUnpublish = async (ct: CableType) => {
|
||||
const impact = await getUsageImpact('cable_type', ct.id)
|
||||
const impactNote =
|
||||
impact.diagramCount > 0
|
||||
? `\n\nUsed in ${impact.diagramCount} diagram${impact.diagramCount === 1 ? '' : 's'}: ${impact.sample.map((s) => `${s.name} (${s.ownerUsername})`).join(', ')}${impact.diagramCount > impact.sample.length ? ', …' : ''}. Existing diagrams keep working — this only removes it from new use.`
|
||||
: '\n\nNot currently used in any diagram.'
|
||||
const confirmed = window.confirm(`Unpublish "${ct.name}" from the public catalog?${impactNote}`)
|
||||
if (!confirmed) return
|
||||
adminUnpublish('cable_type', ct.id)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
@@ -263,22 +289,52 @@ export default function CableTypesPanel() {
|
||||
Built-in ({builtInTypes.length})
|
||||
</h4>
|
||||
<div className="max-h-64 space-y-1 overflow-y-auto rounded border border-slate-200 p-1.5">
|
||||
{builtInTypes.map((ct) =>
|
||||
suggestingId === ct.id ? (
|
||||
<div key={ct.id} className="mb-1.5">
|
||||
<CableTypeForm
|
||||
initial={ct}
|
||||
portTypes={portTypes}
|
||||
onCancel={() => setSuggestingId(null)}
|
||||
onSave={(fields) => handleSuggestEdit(ct.id, fields)}
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
{builtInTypes.map((ct) => {
|
||||
if (isAdmin && adminEditingId === ct.id) {
|
||||
return (
|
||||
<div key={ct.id} className="mb-1.5">
|
||||
<CableTypeForm
|
||||
initial={ct}
|
||||
portTypes={portTypes}
|
||||
onCancel={() => setAdminEditingId(null)}
|
||||
onSave={(fields) => handleAdminSave(ct.id, fields)}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
if (!isAdmin && suggestingId === ct.id) {
|
||||
return (
|
||||
<div key={ct.id} className="mb-1.5">
|
||||
<CableTypeForm
|
||||
initial={ct}
|
||||
portTypes={portTypes}
|
||||
onCancel={() => setSuggestingId(null)}
|
||||
onSave={(fields) => handleSuggestEdit(ct.id, fields)}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
return (
|
||||
<div key={ct.id} className="flex items-center justify-between gap-2 px-1 py-0.5 text-[11px] text-slate-500">
|
||||
<span className="min-w-0 truncate">
|
||||
{ct.name} <span className="text-slate-400">· {describeEnds(ct)}</span>
|
||||
</span>
|
||||
{pendingEntityIds.has(ct.id) ? (
|
||||
{isAdmin ? (
|
||||
<div className="flex shrink-0 items-center gap-1">
|
||||
<button
|
||||
onClick={() => setAdminEditingId(ct.id)}
|
||||
className="rounded bg-slate-100 px-1.5 py-0.5 text-[10px] font-medium text-slate-500 hover:bg-indigo-100 hover:text-indigo-700"
|
||||
>
|
||||
Edit
|
||||
</button>
|
||||
<button
|
||||
onClick={() => handleUnpublish(ct)}
|
||||
className="rounded bg-slate-100 px-1.5 py-0.5 text-[10px] font-medium text-slate-500 hover:bg-red-50 hover:text-red-600"
|
||||
>
|
||||
Unpublish
|
||||
</button>
|
||||
</div>
|
||||
) : pendingEntityIds.has(ct.id) ? (
|
||||
<span className="shrink-0 rounded bg-amber-50 px-1.5 py-0.5 text-[10px] font-medium text-amber-600">
|
||||
Edit pending review
|
||||
</span>
|
||||
@@ -291,11 +347,13 @@ export default function CableTypesPanel() {
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
),
|
||||
)}
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
<p className="mt-1 text-[10px] text-slate-400">
|
||||
Built-in cable types can't be edited directly — "Suggest edit" sends a proposed change to Admins for review.
|
||||
{isAdmin
|
||||
? 'As an Admin, you can edit or unpublish public cable types directly.'
|
||||
: 'Built-in cable types can\'t be edited directly — "Suggest edit" sends a proposed change to Admins for review.'}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -2,6 +2,8 @@ import { useMemo, useState } from 'react'
|
||||
import { deviceTemplateToRow } from '../../data/catalogRowMapping'
|
||||
import { allDeviceCategories, allDeviceTemplates, hiddenDeviceTemplates } from '../../domain/project'
|
||||
import type { DeviceTemplate } from '../../domain/types'
|
||||
import { useAdminReviewStore } from '../../state/adminReviewStore'
|
||||
import { useAuthStore } from '../../state/authStore'
|
||||
import { useCatalogStore } from '../../state/catalogStore'
|
||||
import { useProjectStore } from '../../state/projectStore'
|
||||
import { useSubmissionStore } from '../../state/submissionStore'
|
||||
@@ -10,7 +12,11 @@ import Chevron from '../common/Chevron'
|
||||
import ConnectorLibraryModal from './ConnectorLibraryModal'
|
||||
import DeviceTemplateEditor from './DeviceTemplateEditor'
|
||||
|
||||
type EditorTarget = { mode: 'new' } | { mode: 'edit'; template: DeviceTemplate } | { mode: 'suggestEdit'; template: DeviceTemplate }
|
||||
type EditorTarget =
|
||||
| { mode: 'new' }
|
||||
| { mode: 'edit'; template: DeviceTemplate }
|
||||
| { mode: 'suggestEdit'; template: DeviceTemplate }
|
||||
| { mode: 'adminEdit'; template: DeviceTemplate }
|
||||
|
||||
export default function DevicePalette() {
|
||||
const project = useProjectStore((s) => s.project)
|
||||
@@ -20,8 +26,12 @@ export default function DevicePalette() {
|
||||
const removeCustomDeviceTemplate = useCatalogStore((s) => s.removeCustomDeviceTemplate)
|
||||
const hidePublicDeviceTemplate = useCatalogStore((s) => s.hidePublicDeviceTemplate)
|
||||
const restorePublicDeviceTemplate = useCatalogStore((s) => s.restorePublicDeviceTemplate)
|
||||
const adminUnpublish = useCatalogStore((s) => s.adminUnpublish)
|
||||
const mySubmissions = useSubmissionStore((s) => s.mySubmissions)
|
||||
const submitForReview = useSubmissionStore((s) => s.submitForReview)
|
||||
const getUsageImpact = useAdminReviewStore((s) => s.getUsageImpact)
|
||||
const role = useAuthStore((s) => s.role)
|
||||
const isAdmin = role === 'admin' || role === 'super_admin'
|
||||
const [editorTarget, setEditorTarget] = useState<EditorTarget | null>(null)
|
||||
const [portTypesOpen, setPortTypesOpen] = useState(false)
|
||||
const [hiddenListOpen, setHiddenListOpen] = useState(false)
|
||||
@@ -99,6 +109,17 @@ export default function DevicePalette() {
|
||||
submitForReview('device_template', template.id, deviceTemplateToRow(template))
|
||||
}
|
||||
|
||||
const handleUnpublish = async (template: DeviceTemplate) => {
|
||||
const impact = await getUsageImpact('device_template', template.id)
|
||||
const impactNote =
|
||||
impact.diagramCount > 0
|
||||
? `\n\nUsed in ${impact.diagramCount} diagram${impact.diagramCount === 1 ? '' : 's'}: ${impact.sample.map((s) => `${s.name} (${s.ownerUsername})`).join(', ')}${impact.diagramCount > impact.sample.length ? ', …' : ''}. Existing diagrams keep working — this only removes it from new use.`
|
||||
: '\n\nNot currently used in any diagram.'
|
||||
const confirmed = window.confirm(`Unpublish "${template.name}" from the public catalog?${impactNote}`)
|
||||
if (!confirmed) return
|
||||
adminUnpublish('device_template', template.id)
|
||||
}
|
||||
|
||||
return (
|
||||
<aside className="flex h-full w-64 shrink-0 flex-col border-r border-slate-200 bg-slate-50">
|
||||
<div className="flex items-center justify-between border-b border-slate-200 px-3 py-2">
|
||||
@@ -169,6 +190,23 @@ export default function DevicePalette() {
|
||||
>
|
||||
⇪
|
||||
</button>
|
||||
) : isAdmin ? (
|
||||
<>
|
||||
<button
|
||||
onClick={() => setEditorTarget({ mode: 'adminEdit', template })}
|
||||
title="Edit this public device directly"
|
||||
className="rounded bg-slate-100 px-1.5 py-0.5 text-slate-500 hover:bg-indigo-100 hover:text-indigo-700"
|
||||
>
|
||||
✎
|
||||
</button>
|
||||
<button
|
||||
onClick={() => handleUnpublish(template)}
|
||||
title="Unpublish from the public catalog"
|
||||
className="rounded bg-slate-100 px-1.5 py-0.5 text-slate-500 hover:bg-red-50 hover:text-red-600"
|
||||
>
|
||||
⛔
|
||||
</button>
|
||||
</>
|
||||
) : (
|
||||
<button
|
||||
onClick={() => setEditorTarget({ mode: 'suggestEdit', template })}
|
||||
@@ -243,6 +281,7 @@ export default function DevicePalette() {
|
||||
<DeviceTemplateEditor
|
||||
template={editorTarget.mode === 'new' ? undefined : editorTarget.template}
|
||||
submissionMode={editorTarget.mode === 'suggestEdit'}
|
||||
adminMode={editorTarget.mode === 'adminEdit'}
|
||||
onClose={() => setEditorTarget(null)}
|
||||
onSaved={(categoryId) => expandCategory(categoryId)}
|
||||
/>
|
||||
|
||||
@@ -24,6 +24,7 @@ function nextDraftKey() {
|
||||
export default function DeviceTemplateEditor({
|
||||
template,
|
||||
submissionMode = false,
|
||||
adminMode = false,
|
||||
resubmitId,
|
||||
onClose,
|
||||
onSaved,
|
||||
@@ -34,10 +35,14 @@ export default function DeviceTemplateEditor({
|
||||
* a suggested edit for Admin review instead of mutating it directly
|
||||
* (which RLS wouldn't allow anyway). */
|
||||
submissionMode?: boolean
|
||||
/** When true, saves directly to the public entry (organized-ideas.md §6:
|
||||
* Admin/Super-Admin can CRUD public entries without going through the
|
||||
* submission workflow). Takes precedence over `submissionMode`. */
|
||||
adminMode?: boolean
|
||||
/** When set, saving revises this existing submission (of your own,
|
||||
* pending or rejected) instead of creating a new one — see
|
||||
* MySubmissionsModal's "Edit & resubmit". Takes precedence over
|
||||
* `submissionMode` if both are somehow set. */
|
||||
* `submissionMode`/`adminMode` if somehow more than one is set. */
|
||||
resubmitId?: string
|
||||
onClose: () => void
|
||||
/** Called with the template's category id right before closing, so the
|
||||
@@ -47,6 +52,7 @@ export default function DeviceTemplateEditor({
|
||||
const catalog = useCatalogStore((s) => s.catalog)
|
||||
const addCustomDeviceTemplate = useCatalogStore((s) => s.addCustomDeviceTemplate)
|
||||
const updateCustomDeviceTemplate = useCatalogStore((s) => s.updateCustomDeviceTemplate)
|
||||
const adminUpdateDeviceTemplate = useCatalogStore((s) => s.adminUpdateDeviceTemplate)
|
||||
const addCustomPortType = useCatalogStore((s) => s.addCustomPortType)
|
||||
const submitForReview = useSubmissionStore((s) => s.submitForReview)
|
||||
const resubmit = useSubmissionStore((s) => s.resubmit)
|
||||
@@ -141,6 +147,8 @@ export default function DeviceTemplateEditor({
|
||||
}
|
||||
if (resubmitId) {
|
||||
resubmit(resubmitId, deviceTemplateToRow(fields))
|
||||
} else if (adminMode && template) {
|
||||
adminUpdateDeviceTemplate(template.id, fields)
|
||||
} else if (submissionMode && template) {
|
||||
submitForReview('device_template', template.id, deviceTemplateToRow(fields))
|
||||
} else if (template) {
|
||||
@@ -154,7 +162,17 @@ export default function DeviceTemplateEditor({
|
||||
|
||||
return (
|
||||
<Modal
|
||||
title={resubmitId ? 'Revise Submission' : submissionMode ? 'Suggest an Edit' : template ? 'Edit Custom Device' : 'New Custom Device'}
|
||||
title={
|
||||
resubmitId
|
||||
? 'Revise Submission'
|
||||
: adminMode
|
||||
? 'Edit Public Device'
|
||||
: submissionMode
|
||||
? 'Suggest an Edit'
|
||||
: template
|
||||
? 'Edit Custom Device'
|
||||
: 'New Custom Device'
|
||||
}
|
||||
onClose={onClose}
|
||||
width="max-w-xl"
|
||||
>
|
||||
@@ -350,7 +368,15 @@ export default function DeviceTemplateEditor({
|
||||
disabled={!canSave}
|
||||
className="rounded bg-indigo-600 px-3 py-1.5 text-xs font-medium text-white hover:bg-indigo-500 disabled:cursor-not-allowed disabled:opacity-40"
|
||||
>
|
||||
{resubmitId ? 'Resubmit' : submissionMode ? 'Submit for review' : template ? 'Save changes' : 'Save device'}
|
||||
{resubmitId
|
||||
? 'Resubmit'
|
||||
: adminMode
|
||||
? 'Save changes'
|
||||
: submissionMode
|
||||
? 'Submit for review'
|
||||
: template
|
||||
? 'Save changes'
|
||||
: 'Save device'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -3,6 +3,8 @@ import { PORT_CATEGORIES } from '../../domain/constants'
|
||||
import { allPortTypes, expandCompatibleFamilyIds } from '../../domain/project'
|
||||
import type { PortType } from '../../domain/types'
|
||||
import { portTypeToRow } from '../../data/catalogRowMapping'
|
||||
import { useAdminReviewStore } from '../../state/adminReviewStore'
|
||||
import { useAuthStore } from '../../state/authStore'
|
||||
import { useCatalogStore } from '../../state/catalogStore'
|
||||
import { useSubmissionStore } from '../../state/submissionStore'
|
||||
|
||||
@@ -105,10 +107,16 @@ export function PortTypeForm({
|
||||
export default function PortTypesPanel() {
|
||||
const catalog = useCatalogStore((s) => s.catalog)
|
||||
const updateCustomPortType = useCatalogStore((s) => s.updateCustomPortType)
|
||||
const adminUpdatePortType = useCatalogStore((s) => s.adminUpdatePortType)
|
||||
const adminUnpublish = useCatalogStore((s) => s.adminUnpublish)
|
||||
const mySubmissions = useSubmissionStore((s) => s.mySubmissions)
|
||||
const submitForReview = useSubmissionStore((s) => s.submitForReview)
|
||||
const getUsageImpact = useAdminReviewStore((s) => s.getUsageImpact)
|
||||
const role = useAuthStore((s) => s.role)
|
||||
const isAdmin = role === 'admin' || role === 'super_admin'
|
||||
const [editingId, setEditingId] = useState<string | null>(null)
|
||||
const [suggestingId, setSuggestingId] = useState<string | null>(null)
|
||||
const [adminEditingId, setAdminEditingId] = useState<string | null>(null)
|
||||
|
||||
const allTypes = useMemo(
|
||||
() => [...allPortTypes(catalog)].sort((a, b) => a.name.localeCompare(b.name)),
|
||||
@@ -144,6 +152,22 @@ export default function PortTypesPanel() {
|
||||
setSuggestingId(null)
|
||||
}
|
||||
|
||||
const handleAdminSave = (id: string, fields: Omit<PortType, 'id' | 'custom'>) => {
|
||||
adminUpdatePortType(id, fields)
|
||||
setAdminEditingId(null)
|
||||
}
|
||||
|
||||
const handleUnpublish = async (pt: PortType) => {
|
||||
const impact = await getUsageImpact('port_type', pt.id)
|
||||
const impactNote =
|
||||
impact.diagramCount > 0
|
||||
? `\n\nUsed in ${impact.diagramCount} diagram${impact.diagramCount === 1 ? '' : 's'}: ${impact.sample.map((s) => `${s.name} (${s.ownerUsername})`).join(', ')}${impact.diagramCount > impact.sample.length ? ', …' : ''}. Existing diagrams keep working — this only removes it from new use.`
|
||||
: '\n\nNot currently used in any diagram.'
|
||||
const confirmed = window.confirm(`Unpublish "${pt.name}" from the public catalog?${impactNote}`)
|
||||
if (!confirmed) return
|
||||
adminUnpublish('port_type', pt.id)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
@@ -213,16 +237,30 @@ export default function PortTypesPanel() {
|
||||
Built-in ({builtInTypes.length})
|
||||
</h4>
|
||||
<div className="max-h-64 space-y-1 overflow-y-auto rounded border border-slate-200 p-1.5">
|
||||
{builtInTypes.map((pt) =>
|
||||
suggestingId === pt.id ? (
|
||||
<PortTypeForm
|
||||
key={pt.id}
|
||||
portType={pt}
|
||||
allTypes={allTypes}
|
||||
onCancel={() => setSuggestingId(null)}
|
||||
onSave={(fields) => handleSuggestEdit(pt.id, fields)}
|
||||
/>
|
||||
) : (
|
||||
{builtInTypes.map((pt) => {
|
||||
if (isAdmin && adminEditingId === pt.id) {
|
||||
return (
|
||||
<PortTypeForm
|
||||
key={pt.id}
|
||||
portType={pt}
|
||||
allTypes={allTypes}
|
||||
onCancel={() => setAdminEditingId(null)}
|
||||
onSave={(fields) => handleAdminSave(pt.id, fields)}
|
||||
/>
|
||||
)
|
||||
}
|
||||
if (!isAdmin && suggestingId === pt.id) {
|
||||
return (
|
||||
<PortTypeForm
|
||||
key={pt.id}
|
||||
portType={pt}
|
||||
allTypes={allTypes}
|
||||
onCancel={() => setSuggestingId(null)}
|
||||
onSave={(fields) => handleSuggestEdit(pt.id, fields)}
|
||||
/>
|
||||
)
|
||||
}
|
||||
return (
|
||||
<div key={pt.id} className="flex items-center justify-between gap-2 px-1 py-0.5 text-[11px] text-slate-500">
|
||||
<span className="min-w-0 truncate">
|
||||
{pt.name}
|
||||
@@ -230,7 +268,22 @@ export default function PortTypesPanel() {
|
||||
<span className="text-slate-400"> · also fits: {describeCompatibility(pt)}</span>
|
||||
)}
|
||||
</span>
|
||||
{pendingEntityIds.has(pt.id) ? (
|
||||
{isAdmin ? (
|
||||
<div className="flex shrink-0 items-center gap-1">
|
||||
<button
|
||||
onClick={() => setAdminEditingId(pt.id)}
|
||||
className="rounded bg-slate-100 px-1.5 py-0.5 text-[10px] font-medium text-slate-500 hover:bg-indigo-100 hover:text-indigo-700"
|
||||
>
|
||||
Edit
|
||||
</button>
|
||||
<button
|
||||
onClick={() => handleUnpublish(pt)}
|
||||
className="rounded bg-slate-100 px-1.5 py-0.5 text-[10px] font-medium text-slate-500 hover:bg-red-50 hover:text-red-600"
|
||||
>
|
||||
Unpublish
|
||||
</button>
|
||||
</div>
|
||||
) : pendingEntityIds.has(pt.id) ? (
|
||||
<span className="shrink-0 rounded bg-amber-50 px-1.5 py-0.5 text-[10px] font-medium text-amber-600">
|
||||
Edit pending review
|
||||
</span>
|
||||
@@ -243,11 +296,13 @@ export default function PortTypesPanel() {
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
),
|
||||
)}
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
<p className="mt-1 text-[10px] text-slate-400">
|
||||
Built-in connector types can't be edited directly — "Suggest edit" sends a proposed change to Admins for review.
|
||||
{isAdmin
|
||||
? 'As an Admin, you can edit or unpublish public connector types directly.'
|
||||
: 'Built-in connector types can\'t be edited directly — "Suggest edit" sends a proposed change to Admins for review.'}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
/** A user's role — mirrors `profiles.role`'s check constraint. Defined here
|
||||
* (data layer) rather than in state/authStore.ts so both that store and
|
||||
* this repository share one definition without state importing from data
|
||||
* in the wrong direction. */
|
||||
export type UserRole = 'regular' | 'admin' | 'super_admin'
|
||||
|
||||
export interface AdminUserSummary {
|
||||
id: string
|
||||
username: string
|
||||
email: string
|
||||
role: UserRole
|
||||
/** Set (a future timestamp) while banned; undefined otherwise. */
|
||||
bannedUntil?: string
|
||||
createdAt: string
|
||||
}
|
||||
|
||||
/** Storage abstraction for Super-Admin user management (organized-ideas.md
|
||||
* §6's "CRUD user accounts"). Listing and role changes are plain
|
||||
* RLS/privileged-function reads and writes; ban/unban/delete go through
|
||||
* the admin-user-action Edge Function since those specifically need
|
||||
* Supabase Auth's Admin API — see that function's own header comment for
|
||||
* why this can't just be another SQL function like the rest. */
|
||||
export interface AdminUserRepository {
|
||||
listUsers(): Promise<AdminUserSummary[]>
|
||||
updateRole(userId: string, role: UserRole): Promise<void>
|
||||
/** Reversible — blocks login without touching the account's data. */
|
||||
banUser(userId: string): Promise<void>
|
||||
unbanUser(userId: string): Promise<void>
|
||||
/** Irreversible — cascades to the user's profile, diagrams, and owned
|
||||
* private catalog entries via their existing foreign keys. */
|
||||
deleteUser(userId: string): Promise<void>
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import type { CatalogEntityType } from './SubmissionRepository'
|
||||
import type { Catalog, CableType, DeviceCategoryDef, DeviceTemplate, PortType } from '../domain/types'
|
||||
|
||||
/**
|
||||
@@ -7,10 +8,14 @@ import type { Catalog, CableType, DeviceCategoryDef, DeviceTemplate, PortType }
|
||||
* entries plus their own private ones); RLS does that filtering server-side,
|
||||
* so implementations don't need to filter client-side.
|
||||
*
|
||||
* Only covers the "read + manage your own private entries" surface for now.
|
||||
* Submitting a private entry for public review/promotion is a separate,
|
||||
* not-yet-built workflow (organized-ideas.md §3/§9) — these `add*`/`update*`
|
||||
* methods always create or edit is_public = false rows you own.
|
||||
* The `add*`/`update*` methods always create or edit an `is_public = false`
|
||||
* row you own — that's the regular-user "own private catalog" surface.
|
||||
* Getting an entry into the public catalog otherwise goes through the
|
||||
* submission/review workflow (organized-ideas.md §3), except for the
|
||||
* `admin*` methods below: per §6's capability table, an Admin/Super-Admin
|
||||
* can also CRUD public entries directly, without a submission — those
|
||||
* bypass ownership entirely (RLS's `is_admin()` clause is what actually
|
||||
* allows it) and only ever touch already-public rows.
|
||||
*/
|
||||
export interface CatalogRepository {
|
||||
/** Everything visible to the current user: public entries plus their own private ones. */
|
||||
@@ -27,4 +32,16 @@ export interface CatalogRepository {
|
||||
addDeviceTemplate(template: Omit<DeviceTemplate, 'id' | 'custom'>): Promise<DeviceTemplate>
|
||||
updateDeviceTemplate(id: string, patch: Partial<Omit<DeviceTemplate, 'id' | 'custom'>>): Promise<void>
|
||||
removeDeviceTemplate(id: string): Promise<void>
|
||||
|
||||
/** Admin/Super-Admin direct edit of an already-public port/cable/device
|
||||
* entry — same underlying write as approving a submission, minus the
|
||||
* submission. */
|
||||
adminUpdatePortType(id: string, patch: Partial<Omit<PortType, 'id' | 'custom'>>): Promise<void>
|
||||
adminUpdateCableType(id: string, patch: Partial<Omit<CableType, 'id' | 'custom'>>): Promise<void>
|
||||
adminUpdateDeviceTemplate(id: string, patch: Partial<Omit<DeviceTemplate, 'id' | 'custom'>>): Promise<void>
|
||||
/** Unpublishes a public entry (is_public -> false) rather than deleting
|
||||
* it — organized-ideas.md §3's "public catalog entries are never hard-
|
||||
* deleted, only hidden/unpublished". Existing diagrams that reference it
|
||||
* by id are unaffected; it just stops being offered for new use. */
|
||||
adminUnpublish(entityType: CatalogEntityType, id: string): Promise<void>
|
||||
}
|
||||
|
||||
@@ -1,16 +1,10 @@
|
||||
import { v4 as uuid } from 'uuid'
|
||||
import type { AdminSubmissionRepository, UsageImpact, UsageImpactSample } from './AdminSubmissionRepository'
|
||||
import { CATALOG_TABLE_BY_ENTITY_TYPE } from './catalogRowMapping'
|
||||
import type { CatalogSubmission } from './SubmissionRepository'
|
||||
import { supabase } from './supabaseClient'
|
||||
import { toSubmission, type SubmissionRow } from './submissionRowMapping'
|
||||
|
||||
const TABLE_BY_ENTITY_TYPE: Record<CatalogSubmission['entityType'], string> = {
|
||||
device_template: 'device_templates',
|
||||
port_type: 'port_types',
|
||||
cable_type: 'cable_types',
|
||||
device_category: 'device_categories',
|
||||
}
|
||||
|
||||
interface ProposedDeviceTemplatePort {
|
||||
name: string
|
||||
direction: string
|
||||
@@ -45,7 +39,7 @@ export class SupabaseAdminSubmissionRepository implements AdminSubmissionReposit
|
||||
// `ports` (device_template only) isn't a column on device_templates
|
||||
// itself; pull it out and replace device_template_ports separately.
|
||||
const { ports, ...rowPatch } = submission.proposedData as Record<string, unknown> & { ports?: ProposedDeviceTemplatePort[] }
|
||||
const table = TABLE_BY_ENTITY_TYPE[submission.entityType]
|
||||
const table = CATALOG_TABLE_BY_ENTITY_TYPE[submission.entityType]
|
||||
const { error } = await supabase
|
||||
.from(table)
|
||||
.update({ ...rowPatch, is_public: true, owner_id: null })
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
import { FunctionsHttpError } from '@supabase/supabase-js'
|
||||
import type { AdminUserRepository, AdminUserSummary, UserRole } from './AdminUserRepository'
|
||||
import { supabase } from './supabaseClient'
|
||||
|
||||
interface UserRow {
|
||||
id: string
|
||||
username: string
|
||||
email: string
|
||||
role: UserRole
|
||||
banned_until: string | null
|
||||
created_at: string
|
||||
}
|
||||
|
||||
function toSummary(row: UserRow): AdminUserSummary {
|
||||
return {
|
||||
id: row.id,
|
||||
username: row.username,
|
||||
email: row.email,
|
||||
role: row.role,
|
||||
bannedUntil: row.banned_until ?? undefined,
|
||||
createdAt: row.created_at,
|
||||
}
|
||||
}
|
||||
|
||||
type UserAction = 'ban' | 'unban' | 'delete'
|
||||
|
||||
/** Backs the app with list_users_for_admin (read), a direct profiles.role
|
||||
* update, and the admin-user-action Edge Function (ban/unban/delete). */
|
||||
export class SupabaseAdminUserRepository implements AdminUserRepository {
|
||||
async listUsers(): Promise<AdminUserSummary[]> {
|
||||
const { data, error } = await supabase.rpc('list_users_for_admin')
|
||||
if (error) {
|
||||
console.error('Failed to list users from Supabase', error)
|
||||
return []
|
||||
}
|
||||
return ((data ?? []) as UserRow[]).map(toSummary)
|
||||
}
|
||||
|
||||
async updateRole(userId: string, role: UserRole): Promise<void> {
|
||||
const { error } = await supabase.from('profiles').update({ role }).eq('id', userId)
|
||||
if (error) console.error('Failed to update user role in Supabase', error)
|
||||
}
|
||||
|
||||
private async invokeUserAction(action: UserAction, userId: string): Promise<void> {
|
||||
const { error } = await supabase.functions.invoke('admin-user-action', { body: { action, userId } })
|
||||
if (!error) return
|
||||
|
||||
// The function returns its actual reason (e.g. "Only a Super Admin can
|
||||
// manage user accounts.") in the JSON body on a non-2xx response —
|
||||
// surface that instead of supabase-js's generic "Edge Function
|
||||
// returned a non-2xx status code" wrapper.
|
||||
if (error instanceof FunctionsHttpError) {
|
||||
const body = await error.context.json().catch(() => null)
|
||||
const message = typeof body?.error === 'string' ? body.error : error.message
|
||||
console.error(`Failed to ${action} user`, message)
|
||||
throw new Error(message)
|
||||
}
|
||||
console.error(`Failed to ${action} user`, error)
|
||||
throw error
|
||||
}
|
||||
|
||||
banUser(userId: string): Promise<void> {
|
||||
return this.invokeUserAction('ban', userId)
|
||||
}
|
||||
|
||||
unbanUser(userId: string): Promise<void> {
|
||||
return this.invokeUserAction('unban', userId)
|
||||
}
|
||||
|
||||
deleteUser(userId: string): Promise<void> {
|
||||
return this.invokeUserAction('delete', userId)
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,8 @@
|
||||
import { v4 as uuid } from 'uuid'
|
||||
import type { Catalog, CableType, DeviceCategoryDef, DeviceTemplate, Port, PortType } from '../domain/types'
|
||||
import { cableTypeToRow, deviceTemplateToRow, portTypeToRow } from './catalogRowMapping'
|
||||
import { CATALOG_TABLE_BY_ENTITY_TYPE, cableTypeToRow, deviceTemplateToRow, portTypeToRow } from './catalogRowMapping'
|
||||
import type { CatalogRepository } from './CatalogRepository'
|
||||
import type { CatalogEntityType } from './SubmissionRepository'
|
||||
import { supabase } from './supabaseClient'
|
||||
|
||||
interface DeviceCategoryRow {
|
||||
@@ -260,4 +261,28 @@ export class SupabaseCatalogRepository implements CatalogRepository {
|
||||
const { error } = await supabase.from('device_templates').delete().eq('id', id)
|
||||
if (error) console.error('Failed to remove device template from Supabase', error)
|
||||
}
|
||||
|
||||
// The update* methods above never check ownership themselves — RLS does,
|
||||
// server-side, based on the caller's identity — so an Admin/Super-Admin
|
||||
// direct edit of a public entry is *exactly* the same write, just
|
||||
// permitted by a different branch of the same policy (`is_admin()`
|
||||
// instead of "owns it and it's still private"). These are aliases, not
|
||||
// separate logic, so the two paths can't drift apart.
|
||||
adminUpdatePortType(id: string, patch: Partial<Omit<PortType, 'id' | 'custom'>>): Promise<void> {
|
||||
return this.updatePortType(id, patch)
|
||||
}
|
||||
|
||||
adminUpdateCableType(id: string, patch: Partial<Omit<CableType, 'id' | 'custom'>>): Promise<void> {
|
||||
return this.updateCableType(id, patch)
|
||||
}
|
||||
|
||||
adminUpdateDeviceTemplate(id: string, patch: Partial<Omit<DeviceTemplate, 'id' | 'custom'>>): Promise<void> {
|
||||
return this.updateDeviceTemplate(id, patch)
|
||||
}
|
||||
|
||||
async adminUnpublish(entityType: CatalogEntityType, id: string): Promise<void> {
|
||||
const table = CATALOG_TABLE_BY_ENTITY_TYPE[entityType]
|
||||
const { error } = await supabase.from(table).update({ is_public: false }).eq('id', id)
|
||||
if (error) console.error('Failed to unpublish catalog entry in Supabase', error)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import type { CatalogEntityType } from './SubmissionRepository'
|
||||
import type { CableType, DeviceTemplate, PortType } from '../domain/types'
|
||||
|
||||
/**
|
||||
@@ -10,6 +11,16 @@ import type { CableType, DeviceTemplate, PortType } from '../domain/types'
|
||||
* step an Admin's approval action would otherwise have to duplicate.
|
||||
*/
|
||||
|
||||
/** Which table backs each catalog entity type — shared by
|
||||
* SupabaseAdminSubmissionRepository (approving into the right table) and
|
||||
* SupabaseCatalogRepository (direct Admin unpublish). */
|
||||
export const CATALOG_TABLE_BY_ENTITY_TYPE: Record<CatalogEntityType, string> = {
|
||||
device_template: 'device_templates',
|
||||
port_type: 'port_types',
|
||||
cable_type: 'cable_types',
|
||||
device_category: 'device_categories',
|
||||
}
|
||||
|
||||
export function portTypeToRow(portType: Omit<PortType, 'id' | 'custom'>): Record<string, unknown> {
|
||||
return {
|
||||
name: portType.name,
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
import { create } from 'zustand'
|
||||
import type { AdminUserRepository, AdminUserSummary, UserRole } from '../data/AdminUserRepository'
|
||||
import { SupabaseAdminUserRepository } from '../data/SupabaseAdminUserRepository'
|
||||
|
||||
const repository: AdminUserRepository = new SupabaseAdminUserRepository()
|
||||
|
||||
interface AdminUserStoreState {
|
||||
users: AdminUserSummary[]
|
||||
isLoaded: boolean
|
||||
|
||||
loadUsers: () => Promise<void>
|
||||
updateRole: (userId: string, role: UserRole) => Promise<void>
|
||||
banUser: (userId: string) => Promise<void>
|
||||
unbanUser: (userId: string) => Promise<void>
|
||||
deleteUser: (userId: string) => Promise<void>
|
||||
}
|
||||
|
||||
export const useAdminUserStore = create<AdminUserStoreState>((set) => ({
|
||||
users: [],
|
||||
isLoaded: false,
|
||||
|
||||
loadUsers: async () => {
|
||||
const users = await repository.listUsers()
|
||||
set({ users, isLoaded: true })
|
||||
},
|
||||
|
||||
updateRole: async (userId, role) => {
|
||||
await repository.updateRole(userId, role)
|
||||
set((state) => ({ users: state.users.map((u) => (u.id === userId ? { ...u, role } : u)) }))
|
||||
},
|
||||
|
||||
banUser: async (userId) => {
|
||||
await repository.banUser(userId)
|
||||
// Re-fetch rather than guessing bannedUntil client-side — the Edge
|
||||
// Function is the one place that actually knows the real value.
|
||||
const users = await repository.listUsers()
|
||||
set({ users })
|
||||
},
|
||||
|
||||
unbanUser: async (userId) => {
|
||||
await repository.unbanUser(userId)
|
||||
const users = await repository.listUsers()
|
||||
set({ users })
|
||||
},
|
||||
|
||||
deleteUser: async (userId) => {
|
||||
await repository.deleteUser(userId)
|
||||
set((state) => ({ users: state.users.filter((u) => u.id !== userId) }))
|
||||
},
|
||||
}))
|
||||
@@ -1,7 +1,8 @@
|
||||
import { create } from 'zustand'
|
||||
import type { UserRole } from '../data/AdminUserRepository'
|
||||
import { supabase } from '../data/supabaseClient'
|
||||
|
||||
export type UserRole = 'regular' | 'admin' | 'super_admin'
|
||||
export type { UserRole }
|
||||
|
||||
interface AuthStoreState {
|
||||
userId: string | null
|
||||
@@ -10,9 +11,10 @@ interface AuthStoreState {
|
||||
isLoaded: boolean
|
||||
|
||||
/** One-time fetch of your own profile — nothing else in the app changes
|
||||
* your own username or role while you're signed in (role changes are an
|
||||
* Admin/Super-Admin-only action on someone else's account, see
|
||||
* organized-ideas.md §6, not yet built), so there's no need to keep this live. */
|
||||
* your own username while you're signed in, and your own role changing
|
||||
* (a Super-Admin-only action on someone else's account, see
|
||||
* organized-ideas.md §6) isn't something you'd do to yourself, so
|
||||
* there's no need to keep this live. */
|
||||
load: () => Promise<void>
|
||||
}
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@ import type { CableType, Catalog, DeviceTemplate, PortType } from '../domain/typ
|
||||
import type { CatalogRepository } from '../data/CatalogRepository'
|
||||
import { cableTypeToRow, deviceTemplateToRow, portTypeToRow } from '../data/catalogRowMapping'
|
||||
import { SupabaseCatalogRepository } from '../data/SupabaseCatalogRepository'
|
||||
import type { CatalogEntityType } from '../data/SubmissionRepository'
|
||||
import { useSubmissionStore } from './submissionStore'
|
||||
|
||||
const repository: CatalogRepository = new SupabaseCatalogRepository()
|
||||
@@ -51,6 +52,16 @@ interface CatalogStoreState {
|
||||
|
||||
hidePublicDeviceTemplate: (id: string) => void
|
||||
restorePublicDeviceTemplate: (id: string) => void
|
||||
|
||||
/** Admin/Super-Admin direct edit of an already-public entry, per
|
||||
* organized-ideas.md §6 — bypasses the submission/review workflow
|
||||
* entirely (RLS's is_admin() clause is what actually permits it). */
|
||||
adminUpdatePortType: (id: string, patch: Partial<Omit<PortType, 'id' | 'custom'>>) => Promise<void>
|
||||
adminUpdateCableType: (id: string, patch: Partial<Omit<CableType, 'id' | 'custom'>>) => Promise<void>
|
||||
adminUpdateDeviceTemplate: (id: string, patch: Partial<Omit<DeviceTemplate, 'id' | 'custom'>>) => Promise<void>
|
||||
/** Unpublishes (is_public -> false) rather than deletes — see
|
||||
* CatalogRepository.adminUnpublish. */
|
||||
adminUnpublish: (entityType: CatalogEntityType, id: string) => Promise<void>
|
||||
}
|
||||
|
||||
export const useCatalogStore = create<CatalogStoreState>((set, get) => ({
|
||||
@@ -140,4 +151,31 @@ export const useCatalogStore = create<CatalogStoreState>((set, get) => ({
|
||||
saveHiddenPublicIds(next)
|
||||
set({ hiddenPublicDeviceTemplateIds: next })
|
||||
},
|
||||
|
||||
// Re-fetch the whole catalog after each of these rather than patching
|
||||
// locally — device_template edits also touch device_template_ports, and
|
||||
// unpublish changes which rows even show up (custom flips true for the
|
||||
// Admin who did it, since is_admin() is the only thing still granting
|
||||
// them visibility — see adminUnpublish's own comment). Simplest correct
|
||||
// thing, and Admin actions here are infrequent enough that the extra
|
||||
// round trip doesn't matter.
|
||||
adminUpdatePortType: async (id, patch) => {
|
||||
await repository.adminUpdatePortType(id, patch)
|
||||
await get().loadCatalog()
|
||||
},
|
||||
|
||||
adminUpdateCableType: async (id, patch) => {
|
||||
await repository.adminUpdateCableType(id, patch)
|
||||
await get().loadCatalog()
|
||||
},
|
||||
|
||||
adminUpdateDeviceTemplate: async (id, patch) => {
|
||||
await repository.adminUpdateDeviceTemplate(id, patch)
|
||||
await get().loadCatalog()
|
||||
},
|
||||
|
||||
adminUnpublish: async (entityType, id) => {
|
||||
await repository.adminUnpublish(entityType, id)
|
||||
await get().loadCatalog()
|
||||
},
|
||||
}))
|
||||
|
||||
Reference in New Issue
Block a user