Files
co-lite/solvway-admin-portal/app/lib/CompanyScope.tsx
T

94 lines
2.9 KiB
TypeScript

"use client";
import { createContext, useContext, useEffect, useMemo, useState, type ReactNode } from "react";
import { useAdminAuth } from "@/app/lib/AdminAuthContext";
import { listAdminCompanies } from "@/app/lib/services/adminCompanies";
import type { AdminCompany } from "@/app/lib/types";
// A super admin's company picker choice, kept per tab. Staff get no scope at all:
// companyId stays undefined for them, so they never send the query param.
const KEY = "company-scope";
interface CompanyScope {
/** The picked company; undefined for "All companies" and for staff. */
companyId: number | undefined;
setCompanyId: (id: number | undefined) => void;
companies: AdminCompany[];
/** True for a super admin looking at All companies: lists then show a Company column. */
showCompanyColumn: boolean;
/** Company code for a row's companyId ("" when unknown). */
codeOf: (id?: number | null) => string;
}
const Ctx = createContext<CompanyScope>({
companyId: undefined,
setCompanyId: () => {},
companies: [],
showCompanyColumn: false,
codeOf: () => "",
});
export const useCompanyScope = () => useContext(Ctx);
function readStored(): number | undefined {
try {
const n = Number(sessionStorage.getItem(KEY));
return n > 0 ? n : undefined;
} catch {
return undefined;
}
}
export function clearStoredCompany() {
try {
sessionStorage.removeItem(KEY);
} catch {
// Storage blocked: nothing was stored.
}
}
export function CompanyScopeProvider({ children }: { children: ReactNode }) {
const { isSuper } = useAdminAuth();
const [picked, setPicked] = useState<number | undefined>(readStored);
const [companies, setCompanies] = useState<AdminCompany[]>([]);
useEffect(() => {
if (!isSuper) return;
let live = true;
listAdminCompanies()
.then((c) => {
if (!live) return;
setCompanies(c);
// A stored choice that is no longer a company (removed, or another login's) means All companies.
const stored = readStored();
if (stored !== undefined && !c.some((x) => x.id === stored)) {
clearStoredCompany();
setPicked(undefined);
}
})
.catch(() => {});
return () => { live = false; };
}, [isSuper]);
const value = useMemo<CompanyScope>(() => {
const companyId = isSuper ? picked : undefined;
return {
companyId,
setCompanyId: (id) => {
setPicked(id);
try {
if (id === undefined) clearStoredCompany();
else sessionStorage.setItem(KEY, String(id));
} catch {
// Storage blocked: the choice just lasts until reload.
}
},
companies,
showCompanyColumn: !!isSuper && companyId === undefined,
codeOf: (id) => companies.find((c) => c.id === id)?.code ?? "",
};
}, [isSuper, picked, companies]);
return <Ctx.Provider value={value}>{children}</Ctx.Provider>;
}