74 lines
2.2 KiB
TypeScript
74 lines
2.2 KiB
TypeScript
import { useEffect, useState } from "react";
|
|
import {
|
|
fetchMe,
|
|
type ActingContextSelectorProps
|
|
} from "@govoplan/core-webui";
|
|
import {
|
|
fetchActingContexts,
|
|
switchActingContext,
|
|
type ActingContext
|
|
} from "../../api/actingContext";
|
|
|
|
export default function ActingContextSelector({
|
|
settings,
|
|
auth,
|
|
onAuthChange
|
|
}: ActingContextSelectorProps) {
|
|
const [contexts, setContexts] = useState<ActingContext[]>([]);
|
|
const [activeId, setActiveId] = useState<string>("");
|
|
const [busy, setBusy] = useState(false);
|
|
const [error, setError] = useState("");
|
|
|
|
useEffect(() => {
|
|
let active = true;
|
|
void fetchActingContexts(settings)
|
|
.then((response) => {
|
|
if (!active) return;
|
|
setContexts(response.contexts);
|
|
setActiveId(response.active_assignment_id ?? "");
|
|
})
|
|
.catch((reason: unknown) => {
|
|
if (active) setError(reason instanceof Error ? reason.message : "Acting context could not be loaded.");
|
|
});
|
|
return () => {
|
|
active = false;
|
|
};
|
|
}, [settings.apiBaseUrl, settings.accessToken, settings.apiKey, auth.active_tenant?.id, auth.tenant.id]);
|
|
|
|
if (!contexts.length && !activeId) return null;
|
|
|
|
async function selectContext(assignmentId: string) {
|
|
setBusy(true);
|
|
setError("");
|
|
try {
|
|
const response = await switchActingContext(settings, assignmentId || null);
|
|
setContexts(response.contexts);
|
|
setActiveId(response.active_assignment_id ?? "");
|
|
onAuthChange(await fetchMe(settings));
|
|
} catch (reason) {
|
|
setError(reason instanceof Error ? reason.message : "Acting context could not be changed.");
|
|
} finally {
|
|
setBusy(false);
|
|
}
|
|
}
|
|
|
|
return (
|
|
<label className="acting-context-selector" title={error || "Select whose authority is represented by this session."}>
|
|
<span>Acting as</span>
|
|
<select
|
|
aria-label="Acting context"
|
|
value={activeId}
|
|
disabled={busy}
|
|
onChange={(event) => void selectContext(event.target.value)}
|
|
>
|
|
<option value="">Own account</option>
|
|
{contexts.map((context) => (
|
|
<option key={context.assignment_id} value={context.assignment_id}>
|
|
{context.function_id} / {context.organization_unit_id}
|
|
</option>
|
|
))}
|
|
</select>
|
|
</label>
|
|
);
|
|
}
|