import { useContext } from 'react' import { AccessContext } from './context.js' /** * Everything bootstrap said (GET /api/platform/bootstrap): * { venue, user, permissions (Set), modules (Set), license, languages, bootstrap (raw), refresh() } * permissions: the keys the signed-in user holds, only for modules that are on (superadmin: all). */ export function useAccess() { const ctx = useContext(AccessContext) if (!ctx) throw new Error('useAccess() needs an above it') return ctx } /** Is this module licensed and turned on? */ export function useModule(key) { return useAccess().modules.has(key) } /** * Does the signed-in user hold this key? With a list, ANY of them (like the backend's * require_any); { all: true } for all of them. Hides UI only: the backend always checks too. */ export function useCan(keys, { all = false } = {}) { return can(useAccess().permissions, keys, all) } /** * May the user do it (plan step 4.3)? 'yes' (they hold the key), 'approve' (they don't, but a * manager may approve it with their PIN: show the action, the approval dialog runs when the * server asks) or 'no' (hide it, or show it disabled with the reason). */ export function useAllowed(key) { const { permissions, approvable } = useAccess() return allowed(permissions, approvable, key) } export function allowed(permissions, approvable, key) { if (permissions.has(key)) return 'yes' return approvable?.has(key) ? 'approve' : 'no' } export function can(permissions, keys, all = false) { const list = Array.isArray(keys) ? keys : [keys] if (!list.length) return true return all ? list.every(k => permissions.has(k)) : list.some(k => permissions.has(k)) }