|
| 1 | +import { useState, useEffect, useMemo, useCallback } from 'react' |
| 2 | +import { Button, Chip, SvgIcon, Tooltip } from '@mui/material' |
| 3 | +import { Stack } from '@mui/system' |
| 4 | +import { Sync, CloudDone, Bolt } from '@mui/icons-material' |
| 5 | +import { useSettings } from '../../hooks/use-settings' |
| 6 | +import { useDialog } from '../../hooks/use-dialog' |
| 7 | +import { CippApiDialog } from './CippApiDialog' |
| 8 | +import { CippQueueTracker } from '../CippTable/CippQueueTracker' |
| 9 | + |
| 10 | +/** |
| 11 | + * Hook + UI component that encapsulates all CIPP Reporting DB cache/live mode logic. |
| 12 | + * |
| 13 | + * @param {Object} config |
| 14 | + * @param {string} config.apiUrl - Base API URL without query params (e.g. "/api/ListMailboxes") |
| 15 | + * @param {string} config.queryKey - Base query key (e.g. "ListMailboxes") |
| 16 | + * @param {string} config.cacheName - Cache type name for sync (e.g. "Mailboxes", "IntunePolicies") |
| 17 | + * @param {string} config.syncTitle - Title for the sync dialog (e.g. "Sync Mailboxes") |
| 18 | + * @param {string} [config.syncConfirmText] - Custom confirm text. Default auto-generated from cacheName + tenant. |
| 19 | + * @param {Object} [config.syncData] - Extra data to pass to ExecCIPPDBCache. Merged with { Name: cacheName }. |
| 20 | + * @param {boolean} [config.allowToggle=true] - Whether the user can toggle between cached and live. False = always cached. |
| 21 | + * @param {boolean} [config.defaultCached=true] - Initial cached state (when toggle is allowed). |
| 22 | + * @param {string[]} [config.cacheColumns=["CacheTimestamp"]] - Extra columns to show when in cached mode. |
| 23 | + * @param {string} [config.tenantColumn="Tenant"] - Column name for tenant (shown in AllTenants mode). |
| 24 | + * @param {Object} [config.apiData] - Additional static API data to merge (e.g. extra params). |
| 25 | + * |
| 26 | + * @returns {Object} |
| 27 | + * - useReportDB {boolean} - Current cache mode |
| 28 | + * - setUseReportDB {Function} - Manual override (rarely needed) |
| 29 | + * - isAllTenants {boolean} - Whether AllTenants is selected |
| 30 | + * - resolvedApiUrl {string} - API URL with ?UseReportDB=true appended when needed |
| 31 | + * - resolvedApiData {Object|undefined} - Merged apiData (for pages that use apiData instead of URL params) |
| 32 | + * - resolvedQueryKey {string} - Query key including tenant and cache mode |
| 33 | + * - cacheColumns {string[]} - Columns to prepend/append when cached (includes Tenant for AllTenants) |
| 34 | + * - controls {JSX.Element} - Ready-to-render JSX for the cache toggle, sync button, and queue tracker |
| 35 | + * - syncDialog {JSX.Element} - The CippApiDialog element to render alongside CippTablePage |
| 36 | + */ |
| 37 | +export function useCippReportDB(config) { |
| 38 | + const { |
| 39 | + apiUrl, |
| 40 | + queryKey, |
| 41 | + cacheName, |
| 42 | + syncTitle, |
| 43 | + syncConfirmText, |
| 44 | + syncData, |
| 45 | + allowToggle = true, |
| 46 | + defaultCached = true, |
| 47 | + cacheColumns = ['CacheTimestamp'], |
| 48 | + tenantColumn = 'Tenant', |
| 49 | + apiData: extraApiData, |
| 50 | + } = config |
| 51 | + |
| 52 | + const currentTenant = useSettings().currentTenant |
| 53 | + const isAllTenants = currentTenant === 'AllTenants' |
| 54 | + const dialog = useDialog() |
| 55 | + const [syncQueueId, setSyncQueueId] = useState(null) |
| 56 | + const [useReportDB, setUseReportDB] = useState(defaultCached) |
| 57 | + |
| 58 | + // Reset to default whenever tenant changes; AllTenants always forces cached |
| 59 | + useEffect(() => { |
| 60 | + if (isAllTenants) { |
| 61 | + setUseReportDB(true) |
| 62 | + } else { |
| 63 | + setUseReportDB(defaultCached) |
| 64 | + } |
| 65 | + }, [currentTenant, isAllTenants, defaultCached]) |
| 66 | + |
| 67 | + // Whether the toggle is actually clickable |
| 68 | + const canToggle = allowToggle && !isAllTenants |
| 69 | + |
| 70 | + // Resolved API URL — append UseReportDB param when cached |
| 71 | + const resolvedApiUrl = useMemo(() => { |
| 72 | + if (!useReportDB) return apiUrl |
| 73 | + const sep = apiUrl.includes('?') ? '&' : '?' |
| 74 | + return `${apiUrl}${sep}UseReportDB=true` |
| 75 | + }, [apiUrl, useReportDB]) |
| 76 | + |
| 77 | + // Keep mode flag in the URL only; CippTablePage merges apiData into query params. |
| 78 | + const resolvedApiData = useMemo(() => { |
| 79 | + if (!extraApiData) return undefined |
| 80 | + return { |
| 81 | + ...extraApiData, |
| 82 | + } |
| 83 | + }, [extraApiData]) |
| 84 | + |
| 85 | + // Query key that includes tenant + mode for proper cache separation |
| 86 | + const resolvedQueryKey = useMemo(() => { |
| 87 | + return `${queryKey}-${currentTenant}-${useReportDB}` |
| 88 | + }, [queryKey, currentTenant, useReportDB]) |
| 89 | + |
| 90 | + // Extra columns to show when in cached mode |
| 91 | + const extraColumns = useMemo(() => { |
| 92 | + const cols = [] |
| 93 | + if (useReportDB && isAllTenants) { |
| 94 | + cols.push(tenantColumn) |
| 95 | + } |
| 96 | + if (useReportDB) { |
| 97 | + cols.push(...cacheColumns) |
| 98 | + } |
| 99 | + return cols |
| 100 | + }, [useReportDB, isAllTenants, tenantColumn, cacheColumns]) |
| 101 | + |
| 102 | + const handleSyncSuccess = useCallback((result) => { |
| 103 | + if (result?.Metadata?.QueueId) { |
| 104 | + setSyncQueueId(result.Metadata.QueueId) |
| 105 | + } |
| 106 | + }, []) |
| 107 | + |
| 108 | + // Tooltip text |
| 109 | + const tooltipText = !allowToggle |
| 110 | + ? 'This page always uses cached data from the CIPP reporting database.' |
| 111 | + : isAllTenants |
| 112 | + ? 'AllTenants always uses cached data' |
| 113 | + : useReportDB |
| 114 | + ? 'Showing cached data — click to switch to live' |
| 115 | + : 'Showing live data — click to switch to cache' |
| 116 | + |
| 117 | + const confirmText = |
| 118 | + syncConfirmText || |
| 119 | + `Run ${cacheName} cache sync for ${currentTenant}? This will update data immediately.` |
| 120 | + |
| 121 | + // The controls JSX |
| 122 | + const controls = ( |
| 123 | + <Stack direction="row" spacing={1} alignItems="center"> |
| 124 | + {useReportDB && ( |
| 125 | + <> |
| 126 | + <CippQueueTracker |
| 127 | + queueId={syncQueueId} |
| 128 | + queryKey={resolvedQueryKey} |
| 129 | + title={syncTitle} |
| 130 | + /> |
| 131 | + <Button |
| 132 | + startIcon={ |
| 133 | + <SvgIcon fontSize="small"> |
| 134 | + <Sync /> |
| 135 | + </SvgIcon> |
| 136 | + } |
| 137 | + size="xs" |
| 138 | + onClick={dialog.handleOpen} |
| 139 | + disabled={isAllTenants} |
| 140 | + > |
| 141 | + Sync |
| 142 | + </Button> |
| 143 | + </> |
| 144 | + )} |
| 145 | + <Tooltip title={tooltipText}> |
| 146 | + <span> |
| 147 | + <Chip |
| 148 | + icon={useReportDB ? <CloudDone /> : <Bolt />} |
| 149 | + label={useReportDB ? 'Cached' : 'Live'} |
| 150 | + color="primary" |
| 151 | + size="small" |
| 152 | + onClick={canToggle ? () => setUseReportDB((prev) => !prev) : undefined} |
| 153 | + clickable={canToggle} |
| 154 | + disabled={!canToggle} |
| 155 | + variant="outlined" |
| 156 | + /> |
| 157 | + </span> |
| 158 | + </Tooltip> |
| 159 | + </Stack> |
| 160 | + ) |
| 161 | + |
| 162 | + // The sync dialog JSX — render alongside the table page |
| 163 | + const syncDialogElement = ( |
| 164 | + <CippApiDialog |
| 165 | + createDialog={dialog} |
| 166 | + title={syncTitle} |
| 167 | + fields={[]} |
| 168 | + api={{ |
| 169 | + type: 'GET', |
| 170 | + url: '/api/ExecCIPPDBCache', |
| 171 | + confirmText, |
| 172 | + relatedQueryKeys: [`${queryKey}-${currentTenant}-true`], |
| 173 | + data: { |
| 174 | + Name: cacheName, |
| 175 | + ...(syncData || {}), |
| 176 | + }, |
| 177 | + onSuccess: handleSyncSuccess, |
| 178 | + }} |
| 179 | + /> |
| 180 | + ) |
| 181 | + |
| 182 | + return { |
| 183 | + useReportDB, |
| 184 | + setUseReportDB, |
| 185 | + isAllTenants, |
| 186 | + resolvedApiUrl, |
| 187 | + resolvedApiData, |
| 188 | + resolvedQueryKey, |
| 189 | + cacheColumns: extraColumns, |
| 190 | + controls, |
| 191 | + syncDialog: syncDialogElement, |
| 192 | + } |
| 193 | +} |
0 commit comments