merge new_starr_app@qas history into apps/web
git-subtree-dir: apps/web git-subtree-mainline:eaa6d2276agit-subtree-split:459af9d46a
This commit is contained in:
@@ -0,0 +1,73 @@
|
||||
import { Tabs, TabsList, TabsTrigger, } from "@/components/custom/original-tabs";
|
||||
import { ScrollArea, ScrollBar } from "@/components/ui/scroll-area";
|
||||
import { useNavigate, useLocation } from "react-router-dom";
|
||||
import { useState, useEffect } from "react";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
export default function AdminSideTabs() {
|
||||
const navigate = useNavigate();
|
||||
const location = useLocation();
|
||||
const path = location.pathname;
|
||||
|
||||
const tabItems = [
|
||||
{ value: "tab-1", label: "Dashboard", paths: ["/admin"] },
|
||||
{ value: "tab-2", label: "User Management", paths: ["users"] },
|
||||
{ value: "tab-3", label: "Content Management", paths: ["content", "courses", "units", "lessons"] },
|
||||
{ value: "tab-5", label: "Site Content", paths: ["contents"] },
|
||||
]
|
||||
|
||||
const getTabValue = () => {
|
||||
// ← exact match for /admin only
|
||||
const isDashboard = path === '/admin'
|
||||
if (isDashboard) return "tab-1"
|
||||
|
||||
const found = tabItems.slice(1).find(item =>
|
||||
item.paths.some(p => p && path.includes(p))
|
||||
)
|
||||
return found ? found.value : ""
|
||||
}
|
||||
|
||||
const [value, setValue] = useState(getTabValue());
|
||||
|
||||
const handleTabChange = (val) => {
|
||||
setValue(val)
|
||||
const tab = tabItems.find(t => t.value === val)
|
||||
const primaryPath = tab?.paths?.[0]
|
||||
|
||||
// ← no adminId, just /admin/users etc.
|
||||
const targetPath = primaryPath && primaryPath !== '/admin'
|
||||
? `/admin/${primaryPath}`
|
||||
: `/admin`
|
||||
|
||||
navigate(targetPath)
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
setValue(getTabValue());
|
||||
}, [path]);
|
||||
|
||||
return (
|
||||
<div className="w-full">
|
||||
<Tabs value={value} onValueChange={handleTabChange}>
|
||||
<ScrollArea className="max-w-full overflow-x-auto border-b w-full">
|
||||
<TabsList
|
||||
className={cn(
|
||||
"bg-background rounded-none justify-start mx-2 my-1 flex gap-1"
|
||||
)}
|
||||
>
|
||||
{tabItems.map((tab) => (
|
||||
<TabsTrigger
|
||||
key={tab.value}
|
||||
value={tab.value}
|
||||
className="data-[state=active]:bg-muted data-[state=active]:shadow-none hover:bg-muted text-muted-foreground data-[state=active]:text-foreground"
|
||||
>
|
||||
{tab.label}
|
||||
</TabsTrigger>
|
||||
))}
|
||||
</TabsList>
|
||||
<ScrollBar orientation="horizontal" />
|
||||
</ScrollArea>
|
||||
</Tabs>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,200 @@
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { toast } from "sonner";
|
||||
|
||||
import api from "@/utils/api.util";
|
||||
import { useAdvertisements } from "@/contexts/AdminAdvertisementContext";
|
||||
import { useAuth } from "@/contexts/AuthContext";
|
||||
|
||||
import DataTable from "@/components/generic/Table/DataTable";
|
||||
import { FilterSheet } from "@/components/generic/Sheet/FilterSheet";
|
||||
import { RestoreDialog } from "@/components/generic/Dialogs/RestoreDialog";
|
||||
import { PermanentDeleteDialog } from "@/components/generic/Dialogs/PermanentDeleteDialog";
|
||||
|
||||
import { buildDataColumns, columnPinning } from "../../config/advertisements/archive/columns.config";
|
||||
import { buildToolbarActions } from "../../config/advertisements/archive/toolbar.config";
|
||||
import { buildRowActions } from "../../config/advertisements/archive/rowActions.config";
|
||||
import { buildSelectionActions } from "../../config/advertisements/archive/selection.config";
|
||||
|
||||
import { getTimestamp } from "@/utils/timestamp.util";
|
||||
import { useDateFormat } from "@/hooks/useDateFormat";
|
||||
import { formatGeneratedBy } from "@/utils/generatedBy.util";
|
||||
|
||||
export default function ArchivedAdvertisementsTable() {
|
||||
const [restoreTarget, setRestoreTarget] = useState(null);
|
||||
const [restoreIds, setRestoreIds] = useState(null);
|
||||
const [deleteTarget, setDeleteTarget] = useState(null);
|
||||
const [deleteIds, setDeleteIds] = useState(null);
|
||||
|
||||
const tableRefsRef = useRef({
|
||||
getFilters: () => [],
|
||||
getSort: () => [],
|
||||
resetSelection: () => {},
|
||||
setFilters: () => {},
|
||||
});
|
||||
|
||||
const navigate = useNavigate();
|
||||
const { fmtDateTime } = useDateFormat();
|
||||
const { user: currentUser } = useAuth();
|
||||
|
||||
const {
|
||||
advertisements, attributes, pagination, setPagination, loading,
|
||||
fetchArchivedAdvertisements, restoreAdvertisement, restoreAdvertisements,
|
||||
permanentlyDeleteAdvertisement, permanentlyDeleteAdvertisements,
|
||||
fetchAdvertisementFieldValues,
|
||||
} = useAdvertisements();
|
||||
|
||||
useEffect(() => {
|
||||
fetchArchivedAdvertisements({ page: 1, limit: pagination?.limit ?? 10 });
|
||||
}, []);
|
||||
|
||||
const handleRefsReady = (refs) => {
|
||||
tableRefsRef.current = refs;
|
||||
};
|
||||
|
||||
const exportConfig = {
|
||||
allData: advertisements,
|
||||
attributes,
|
||||
filename: `${getTimestamp()}_ArchivedAds`,
|
||||
sheetName: "Archived Ads",
|
||||
generatedBy: formatGeneratedBy(currentUser),
|
||||
};
|
||||
|
||||
const rowActions = buildRowActions({
|
||||
onRestore: (row) => setRestoreTarget(row),
|
||||
onDelete: (row) => setDeleteTarget(row),
|
||||
});
|
||||
|
||||
// "Remove Expired" — the expireAdvertisements cron already auto-archives
|
||||
// (soft-deletes) any ad past its end_date and stamps status: 'expired' on
|
||||
// it before doing so, so this only ever targets naturally-expired ads,
|
||||
// never ones an admin manually archived while still active/scheduled.
|
||||
const handleRemoveExpired = async () => {
|
||||
const { data } = await api.get("/admin/advertisements/archived", {
|
||||
params: { page: 1, limit: 1000, filters: JSON.stringify([{ id: "status", value: "expired" }]) },
|
||||
});
|
||||
const ids = (data?.data?.data ?? []).map((a) => a.advertisement_id);
|
||||
if (!ids.length) {
|
||||
toast("No expired advertisements to remove.");
|
||||
return;
|
||||
}
|
||||
setDeleteIds(ids);
|
||||
};
|
||||
|
||||
const toolbarActions = buildToolbarActions({
|
||||
fetchAdvertisements: fetchArchivedAdvertisements,
|
||||
pagination,
|
||||
exportConfig,
|
||||
navigate,
|
||||
getFilters: () => tableRefsRef.current.getFilters(),
|
||||
getSort: () => tableRefsRef.current.getSort(),
|
||||
getTableInstance: () => tableRefsRef.current.tableInstance,
|
||||
onRemoveExpired: handleRemoveExpired,
|
||||
});
|
||||
|
||||
const selectionActions = buildSelectionActions({
|
||||
exportConfig,
|
||||
onSingleRestore: (row) => setRestoreTarget(row),
|
||||
onBulkRestore: (ids) => setRestoreIds(ids),
|
||||
onSingleDelete: (row) => setDeleteTarget(row),
|
||||
onBulkDelete: (ids) => setDeleteIds(ids),
|
||||
getTableInstance: () => tableRefsRef.current.tableInstance,
|
||||
});
|
||||
|
||||
const columns = useMemo(
|
||||
() => buildDataColumns(attributes, rowActions, fmtDateTime),
|
||||
[attributes, fmtDateTime]
|
||||
);
|
||||
|
||||
const handleRestoreSuccess = () => {
|
||||
setRestoreTarget(null);
|
||||
setRestoreIds(null);
|
||||
tableRefsRef.current.resetSelection?.();
|
||||
fetchArchivedAdvertisements({ page: 1, limit: pagination?.limit ?? 10 });
|
||||
};
|
||||
|
||||
const handleDeleteSuccess = () => {
|
||||
setDeleteTarget(null);
|
||||
setDeleteIds(null);
|
||||
tableRefsRef.current.resetSelection?.();
|
||||
fetchArchivedAdvertisements({ page: 1, limit: pagination?.limit ?? 10 });
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<DataTable
|
||||
title="Archived Ads"
|
||||
data={advertisements}
|
||||
columns={columns}
|
||||
attributes={attributes}
|
||||
pagination={pagination}
|
||||
setPagination={setPagination}
|
||||
loading={loading}
|
||||
onFetch={fetchArchivedAdvertisements}
|
||||
onFetchFilterData={fetchAdvertisementFieldValues}
|
||||
onRefsReady={handleRefsReady}
|
||||
renderFilterSheet={({ open, onOpenChange, column, attr, data, loading }) => (
|
||||
<FilterSheet
|
||||
open={open}
|
||||
onOpenChange={onOpenChange}
|
||||
column={column}
|
||||
attr={attr}
|
||||
data={data}
|
||||
loading={loading}
|
||||
/>
|
||||
)}
|
||||
columnPinning={columnPinning}
|
||||
toolbarActions={toolbarActions}
|
||||
selectionActions={selectionActions}
|
||||
recordLabel="archived ad"
|
||||
emptyMessage="No archived ads found."
|
||||
/>
|
||||
|
||||
{/* ── Single restore ── */}
|
||||
<RestoreDialog
|
||||
open={!!restoreTarget}
|
||||
onOpenChange={(v) => !v && setRestoreTarget(null)}
|
||||
entity={restoreTarget}
|
||||
entityLabel="Ad"
|
||||
getName={(a) => a?.headline ?? a?.badge_labels?.[0] ?? "this ad"}
|
||||
onRestore={(a) => restoreAdvertisement(a?.advertisement_id)}
|
||||
loading={loading}
|
||||
onSuccess={handleRestoreSuccess}
|
||||
/>
|
||||
|
||||
{/* ── Bulk restore ── */}
|
||||
<RestoreDialog
|
||||
open={!!restoreIds}
|
||||
onOpenChange={(v) => !v && setRestoreIds(null)}
|
||||
ids={restoreIds ?? []}
|
||||
entityLabel="Ad"
|
||||
onRestore={(ids) => restoreAdvertisements(ids)}
|
||||
loading={loading}
|
||||
onSuccess={handleRestoreSuccess}
|
||||
/>
|
||||
|
||||
{/* ── Single permanent delete ── */}
|
||||
<PermanentDeleteDialog
|
||||
open={!!deleteTarget}
|
||||
onOpenChange={(v) => !v && setDeleteTarget(null)}
|
||||
entity={deleteTarget}
|
||||
entityLabel="Ad"
|
||||
getName={(a) => a?.headline ?? a?.badge_labels?.[0] ?? "this ad"}
|
||||
onDelete={(a) => permanentlyDeleteAdvertisement(a?.advertisement_id)}
|
||||
loading={loading}
|
||||
onSuccess={handleDeleteSuccess}
|
||||
/>
|
||||
|
||||
{/* ── Bulk permanent delete ── */}
|
||||
<PermanentDeleteDialog
|
||||
open={!!deleteIds}
|
||||
onOpenChange={(v) => !v && setDeleteIds(null)}
|
||||
ids={deleteIds ?? []}
|
||||
entityLabel="Ad"
|
||||
onDelete={(ids) => permanentlyDeleteAdvertisements(ids)}
|
||||
loading={loading}
|
||||
onSuccess={handleDeleteSuccess}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
|
||||
import { useAssets } from "@/contexts/AdminAssetsContext";
|
||||
import { useAuth } from "@/contexts/AuthContext";
|
||||
|
||||
import DataTable from "@/components/generic/Table/DataTable";
|
||||
import { FilterSheet } from "@/components/generic/Sheet/FilterSheet";
|
||||
import { RestoreDialog } from "@/components/generic/Dialogs/RestoreDialog";
|
||||
import { PermanentDeleteDialog } from "@/components/generic/Dialogs/PermanentDeleteDialog";
|
||||
|
||||
import { buildDataColumns, columnPinning } from "../../config/assets/archive/columns.config";
|
||||
import { buildToolbarActions } from "../../config/assets/archive/toolbar.config";
|
||||
import { buildRowActions } from "../../config/assets/archive/rowActions.config";
|
||||
import { buildSelectionActions } from "../../config/assets/archive/selection.config";
|
||||
|
||||
import { getTimestamp } from "@/utils/timestamp.util";
|
||||
import { formatGeneratedBy } from "@/utils/generatedBy.util";
|
||||
|
||||
export default function ArchivedAssetsTable() {
|
||||
const [restoreTarget, setRestoreTarget] = useState(null);
|
||||
const [restoreIds, setRestoreIds] = useState(null);
|
||||
const [deleteTarget, setDeleteTarget] = useState(null);
|
||||
const [deleteIds, setDeleteIds] = useState(null);
|
||||
|
||||
const tableRefsRef = useRef({
|
||||
getFilters: () => [],
|
||||
getSort: () => [],
|
||||
resetSelection: () => {},
|
||||
setFilters: () => {},
|
||||
});
|
||||
|
||||
const navigate = useNavigate();
|
||||
|
||||
const { user: currentUser } = useAuth();
|
||||
|
||||
const {
|
||||
assets, attributes, pagination, setPagination, loading,
|
||||
fetchArchivedAssets, restoreAsset, restoreAssets, fetchAssetFieldValues,
|
||||
permanentlyDeleteAsset, permanentlyDeleteAssets
|
||||
} = useAssets();
|
||||
|
||||
useEffect(() => {
|
||||
fetchArchivedAssets({ page: 1, limit: pagination?.limit ?? 10 });
|
||||
}, []);
|
||||
|
||||
const handleRefsReady = (refs) => {
|
||||
tableRefsRef.current = refs;
|
||||
};
|
||||
|
||||
const exportConfig = {
|
||||
allData: assets,
|
||||
attributes,
|
||||
filename: `${getTimestamp()}_ArchivedFiles`,
|
||||
sheetName: "Archived Files",
|
||||
generatedBy: formatGeneratedBy(currentUser),
|
||||
};
|
||||
|
||||
const rowActions = buildRowActions({
|
||||
onRestore: (row) => setRestoreTarget(row),
|
||||
onDelete: (row) => setDeleteTarget(row),
|
||||
});
|
||||
|
||||
const toolbarActions = buildToolbarActions({
|
||||
fetchAssets: fetchArchivedAssets,
|
||||
pagination,
|
||||
exportConfig,
|
||||
navigate,
|
||||
getFilters: () => tableRefsRef.current.getFilters(),
|
||||
getSort: () => tableRefsRef.current.getSort(),
|
||||
getTableInstance: () => tableRefsRef.current.tableInstance,
|
||||
});
|
||||
|
||||
const selectionActions = buildSelectionActions({
|
||||
exportConfig,
|
||||
onSingleRestore: (row) => setRestoreTarget(row),
|
||||
onBulkRestore: (ids) => setRestoreIds(ids),
|
||||
onSingleDelete: (row) => setDeleteTarget(row),
|
||||
onBulkDelete: (ids) => setDeleteIds(ids),
|
||||
getTableInstance: () => tableRefsRef.current.tableInstance,
|
||||
});
|
||||
|
||||
const columns = useMemo(
|
||||
() => buildDataColumns(attributes, rowActions),
|
||||
[attributes]
|
||||
);
|
||||
|
||||
const handleRestoreSuccess = () => {
|
||||
setRestoreTarget(null);
|
||||
setRestoreIds(null);
|
||||
tableRefsRef.current.resetSelection?.();
|
||||
fetchArchivedAssets({ page: 1, limit: pagination?.limit ?? 10 });
|
||||
};
|
||||
|
||||
const handleDeleteSuccess = () => {
|
||||
setDeleteTarget(null);
|
||||
setDeleteIds(null);
|
||||
tableRefsRef.current.resetSelection?.();
|
||||
fetchArchivedAssets({ page: 1, limit: pagination?.limit ?? 10 });
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<DataTable
|
||||
title="Archived Files"
|
||||
data={assets}
|
||||
columns={columns}
|
||||
attributes={attributes}
|
||||
pagination={pagination}
|
||||
setPagination={setPagination}
|
||||
loading={loading}
|
||||
onFetch={fetchArchivedAssets}
|
||||
onFetchFilterData={fetchAssetFieldValues}
|
||||
onRefsReady={handleRefsReady}
|
||||
renderFilterSheet={({ open, onOpenChange, column, attr, data, loading }) => (
|
||||
<FilterSheet
|
||||
open={open}
|
||||
onOpenChange={onOpenChange}
|
||||
column={column}
|
||||
attr={attr}
|
||||
data={data}
|
||||
loading={loading}
|
||||
/>
|
||||
)}
|
||||
columnPinning={columnPinning}
|
||||
toolbarActions={toolbarActions}
|
||||
selectionActions={selectionActions}
|
||||
recordLabel="archived file"
|
||||
emptyMessage="No archived files found."
|
||||
/>
|
||||
|
||||
{/* ── Single restore ── */}
|
||||
<RestoreDialog
|
||||
open={!!restoreTarget}
|
||||
onOpenChange={(v) => !v && setRestoreTarget(null)}
|
||||
entity={restoreTarget}
|
||||
entityLabel="File"
|
||||
getName={(a) => a?.display_name ?? a?.original_name}
|
||||
onRestore={(a) => restoreAsset(a?.asset_id)}
|
||||
loading={loading}
|
||||
onSuccess={handleRestoreSuccess}
|
||||
/>
|
||||
|
||||
{/* ── Bulk restore ── */}
|
||||
<RestoreDialog
|
||||
open={!!restoreIds}
|
||||
onOpenChange={(v) => !v && setRestoreIds(null)}
|
||||
ids={restoreIds ?? []}
|
||||
entityLabel="File"
|
||||
onRestore={(ids) => restoreAssets(ids)}
|
||||
loading={loading}
|
||||
onSuccess={handleRestoreSuccess}
|
||||
/>
|
||||
|
||||
{/* ── Single permanent delete ── */}
|
||||
<PermanentDeleteDialog
|
||||
open={!!deleteTarget}
|
||||
onOpenChange={(v) => !v && setDeleteTarget(null)}
|
||||
entity={deleteTarget}
|
||||
entityLabel="File"
|
||||
getName={(a) => a?.display_name ?? a?.original_name}
|
||||
onDelete={(a) => permanentlyDeleteAsset(a?.asset_id)}
|
||||
loading={loading}
|
||||
onSuccess={handleDeleteSuccess}
|
||||
/>
|
||||
|
||||
{/* ── Bulk permanent delete ── */}
|
||||
<PermanentDeleteDialog
|
||||
open={!!deleteIds}
|
||||
onOpenChange={(v) => !v && setDeleteIds(null)}
|
||||
ids={deleteIds ?? []}
|
||||
entityLabel="File"
|
||||
onDelete={(ids) => permanentlyDeleteAssets(ids)}
|
||||
loading={loading}
|
||||
onSuccess={handleDeleteSuccess}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
// modules/admin/components/assets/AssetsTable.jsx
|
||||
|
||||
import { useMemo, useRef, useState } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
|
||||
import { useAssets } from "@/contexts/AdminAssetsContext";
|
||||
import { useAuth } from "@/contexts/AuthContext";
|
||||
|
||||
import DataTable from "@/components/generic/Table/DataTable";
|
||||
import { FilterSheet } from "@/components/generic/Sheet/FilterSheet";
|
||||
import { ArchiveDialog } from "@/components/generic/Dialogs/ArchiveDialog";
|
||||
|
||||
import { buildDataColumns, columnPinning } from "../../config/assets/columns.config";
|
||||
import { buildToolbarActions } from "../../config/assets/toolbar.config";
|
||||
import { buildSelectionActions } from "../../config/assets/selection.config";
|
||||
import { buildRowActions } from "../../config/assets/rowActions.config";
|
||||
|
||||
import { getTimestamp } from "@/utils/timestamp.util";
|
||||
import { formatGeneratedBy } from "@/utils/generatedBy.util";
|
||||
|
||||
export default function AssetsTable() {
|
||||
const [archiveTarget, setArchiveTarget] = useState(null);
|
||||
const [archiveIds, setArchiveIds] = useState(null);
|
||||
|
||||
const tableRefsRef = useRef({
|
||||
getFilters: () => [],
|
||||
getSort: () => [],
|
||||
resetSelection: () => { },
|
||||
setFilters: () => { },
|
||||
});
|
||||
|
||||
const navigate = useNavigate();
|
||||
|
||||
const { user: currentUser } = useAuth();
|
||||
|
||||
const {
|
||||
assets, attributes, pagination, setPagination, loading,
|
||||
fetchAssets, archiveAsset, archiveAssets, fetchAssetFieldValues
|
||||
} = useAssets();
|
||||
|
||||
const handleRefsReady = (refs) => {
|
||||
tableRefsRef.current = refs;
|
||||
};
|
||||
|
||||
const exportConfig = {
|
||||
allData: assets,
|
||||
attributes,
|
||||
filename: `${getTimestamp()}_Files`,
|
||||
sheetName: "Files",
|
||||
generatedBy: formatGeneratedBy(currentUser),
|
||||
};
|
||||
|
||||
const resolveViewPath = (row) => {
|
||||
switch (row.file_type) {
|
||||
case "video": return `view/video/${row.asset_id}`;
|
||||
case "image": return `view/image/${row.asset_id}`;
|
||||
case "document": return `view/document/${row.asset_id}`;
|
||||
case "audio": return `view/audio/${row.asset_id}`;
|
||||
default: return `view/image/${row.asset_id}`;
|
||||
}
|
||||
};
|
||||
|
||||
const rowActions = buildRowActions({
|
||||
onView: (row) => navigate(resolveViewPath(row)),
|
||||
onArchive: (row) => setArchiveTarget(row),
|
||||
});
|
||||
|
||||
const toolbarActions = buildToolbarActions({
|
||||
fetchAssets, pagination, exportConfig, navigate,
|
||||
getFilters: () => tableRefsRef.current.getFilters(),
|
||||
getSort: () => tableRefsRef.current.getSort(),
|
||||
getTableInstance: () => tableRefsRef.current.tableInstance,
|
||||
});
|
||||
|
||||
const selectionActions = buildSelectionActions({
|
||||
exportConfig,
|
||||
onArchive: (row) => setArchiveTarget(row),
|
||||
onArchiveMany: (ids) => setArchiveIds(ids),
|
||||
getTableInstance: () => tableRefsRef.current.tableInstance,
|
||||
});
|
||||
|
||||
const columns = useMemo(
|
||||
() => buildDataColumns(attributes, rowActions),
|
||||
[attributes]
|
||||
);
|
||||
|
||||
const handleArchiveSuccess = () => {
|
||||
setArchiveTarget(null);
|
||||
setArchiveIds(null);
|
||||
tableRefsRef.current.resetSelection?.();
|
||||
fetchAssets({ page: 1, limit: pagination?.limit ?? 10 });
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<DataTable
|
||||
title="Files"
|
||||
data={assets}
|
||||
columns={columns}
|
||||
attributes={attributes}
|
||||
pagination={pagination}
|
||||
setPagination={setPagination}
|
||||
loading={loading}
|
||||
onFetch={fetchAssets}
|
||||
onFetchFilterData={fetchAssetFieldValues}
|
||||
onRefsReady={handleRefsReady}
|
||||
renderFilterSheet={({ open, onOpenChange, column, attr, data, loading }) => (
|
||||
<FilterSheet
|
||||
open={open}
|
||||
onOpenChange={onOpenChange}
|
||||
column={column}
|
||||
attr={attr}
|
||||
data={data}
|
||||
loading={loading}
|
||||
/>
|
||||
)}
|
||||
columnPinning={columnPinning}
|
||||
toolbarActions={toolbarActions}
|
||||
selectionActions={selectionActions}
|
||||
recordLabel="file"
|
||||
emptyMessage="No files match the current filters."
|
||||
/>
|
||||
|
||||
{/* ── Single archive ── */}
|
||||
<ArchiveDialog
|
||||
open={!!archiveTarget}
|
||||
onOpenChange={(v) => !v && setArchiveTarget(null)}
|
||||
entity={archiveTarget}
|
||||
entityLabel="File"
|
||||
getName={(a) => a?.display_name ?? a?.original_name}
|
||||
onArchive={(a) => archiveAsset(a?.asset_id)}
|
||||
loading={loading}
|
||||
onSuccess={handleArchiveSuccess}
|
||||
/>
|
||||
|
||||
{/* ── Bulk archive ── */}
|
||||
<ArchiveDialog
|
||||
open={!!archiveIds}
|
||||
onOpenChange={(v) => !v && setArchiveIds(null)}
|
||||
ids={archiveIds ?? []}
|
||||
entityLabel="File"
|
||||
onArchive={(ids) => archiveAssets(ids)}
|
||||
loading={loading}
|
||||
onSuccess={handleArchiveSuccess}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
import { useCallback, useMemo, useRef, useState } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
|
||||
import { useCategories } from "@/contexts/AdminCategoriesContext";
|
||||
import { useAuth } from "@/contexts/AuthContext";
|
||||
|
||||
import DataTable from "@/components/generic/Table/DataTable";
|
||||
import { FilterSheet } from "@/components/generic/Sheet/FilterSheet";
|
||||
import { PermanentDeleteDialog } from "@/components/generic/Dialogs/PermanentDeleteDialog";
|
||||
|
||||
import { buildDataColumns, columnPinning } from "../../config/categories/columns.config";
|
||||
import { buildToolbarActions } from "../../config/categories/archive/toolbar.config";
|
||||
import { buildSelectionActions } from "../../config/categories/archive/selection.config";
|
||||
import { buildRowActions } from "../../config/categories/archive/rowActions.config";
|
||||
|
||||
import { getTimestamp } from "@/utils/timestamp.util";
|
||||
import { formatGeneratedBy } from "@/utils/generatedBy.util";
|
||||
|
||||
export default function ArchivedCategoriesTable() {
|
||||
const navigate = useNavigate();
|
||||
const { user: currentUser } = useAuth();
|
||||
|
||||
const {
|
||||
categories, categoryAttributes, categoryPagination, setCategoryPagination,
|
||||
loading, fetchCategories, restoreCategory, bulkRestoreCategories,
|
||||
fetchCategoryPermanentDeleteImpact, permanentlyDeleteCategory, bulkPermanentlyDeleteCategories,
|
||||
} = useCategories();
|
||||
|
||||
const [deleteTarget, setDeleteTarget] = useState(null);
|
||||
const [deleteIds, setDeleteIds] = useState(null);
|
||||
|
||||
const tableRefsRef = useRef({
|
||||
getFilters: () => [],
|
||||
getSort: () => [],
|
||||
resetSelection: () => {},
|
||||
tableInstance: null,
|
||||
});
|
||||
|
||||
const handleRefsReady = (refs) => { tableRefsRef.current = refs; };
|
||||
|
||||
const fetchArchived = useCallback(
|
||||
(params) => fetchCategories({ ...params, archived: true }),
|
||||
[fetchCategories]
|
||||
);
|
||||
|
||||
const refetch = () => {
|
||||
tableRefsRef.current.resetSelection?.();
|
||||
fetchArchived({
|
||||
page: 1,
|
||||
limit: categoryPagination?.limit ?? 10,
|
||||
filters: tableRefsRef.current.getFilters(),
|
||||
sort: tableRefsRef.current.getSort(),
|
||||
});
|
||||
};
|
||||
|
||||
const rowActions = buildRowActions({
|
||||
onRestore: async (row) => { await restoreCategory(row.id); refetch(); },
|
||||
onDelete: (row) => setDeleteTarget(row),
|
||||
});
|
||||
|
||||
const exportConfig = useMemo(() => ({
|
||||
allData: categories,
|
||||
attributes: categoryAttributes,
|
||||
filename: `${getTimestamp()}_ArchivedCategories`,
|
||||
sheetName: "Archived Categories",
|
||||
generatedBy: formatGeneratedBy(currentUser),
|
||||
}), [categories, categoryAttributes, currentUser]);
|
||||
|
||||
const toolbarActions = buildToolbarActions({
|
||||
fetchCategories: fetchArchived,
|
||||
pagination: categoryPagination,
|
||||
exportConfig,
|
||||
navigate,
|
||||
getFilters: () => tableRefsRef.current.getFilters(),
|
||||
getSort: () => tableRefsRef.current.getSort(),
|
||||
getTableInstance: () => tableRefsRef.current.tableInstance,
|
||||
});
|
||||
|
||||
const selectionActions = buildSelectionActions({
|
||||
onRestore: async (row) => { await restoreCategory(row.id); refetch(); },
|
||||
onRestoreMany: async (ids) => { await bulkRestoreCategories(ids); refetch(); },
|
||||
onDelete: (row) => setDeleteTarget(row),
|
||||
onDeleteMany: (ids) => setDeleteIds(ids),
|
||||
});
|
||||
|
||||
const columns = useMemo(
|
||||
() => buildDataColumns(categoryAttributes, rowActions),
|
||||
[categoryAttributes, rowActions]
|
||||
);
|
||||
|
||||
const handleDeleteSuccess = () => {
|
||||
setDeleteTarget(null);
|
||||
setDeleteIds(null);
|
||||
refetch();
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<DataTable
|
||||
title="Archived Categories"
|
||||
data={categories}
|
||||
columns={columns}
|
||||
attributes={categoryAttributes}
|
||||
pagination={categoryPagination}
|
||||
setPagination={setCategoryPagination}
|
||||
loading={loading}
|
||||
onFetch={fetchArchived}
|
||||
onFetchFilterData={async () => []}
|
||||
onRefsReady={handleRefsReady}
|
||||
renderFilterSheet={({ open, onOpenChange, column, attr, data, loading }) => (
|
||||
<FilterSheet
|
||||
open={open}
|
||||
onOpenChange={onOpenChange}
|
||||
column={column}
|
||||
attr={attr}
|
||||
data={data}
|
||||
loading={loading}
|
||||
/>
|
||||
)}
|
||||
columnPinning={columnPinning}
|
||||
toolbarActions={toolbarActions}
|
||||
selectionActions={selectionActions}
|
||||
recordLabel="category"
|
||||
emptyMessage="No archived categories."
|
||||
/>
|
||||
|
||||
{/* Single permanent delete */}
|
||||
<PermanentDeleteDialog
|
||||
open={!!deleteTarget}
|
||||
onOpenChange={(v) => !v && setDeleteTarget(null)}
|
||||
entity={deleteTarget}
|
||||
entityLabel="Category"
|
||||
getName={(r) => r?.name}
|
||||
onDelete={(entity) => permanentlyDeleteCategory(entity?.id)}
|
||||
onImpactCheck={() => fetchCategoryPermanentDeleteImpact(deleteTarget?.id)}
|
||||
loading={loading}
|
||||
onSuccess={handleDeleteSuccess}
|
||||
/>
|
||||
|
||||
{/* Bulk permanent delete */}
|
||||
<PermanentDeleteDialog
|
||||
open={!!deleteIds}
|
||||
onOpenChange={(v) => !v && setDeleteIds(null)}
|
||||
ids={deleteIds ?? []}
|
||||
entityLabel="Category"
|
||||
onDelete={({ ids }) => bulkPermanentlyDeleteCategories(ids)}
|
||||
loading={loading}
|
||||
onSuccess={handleDeleteSuccess}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
import { useMemo, useRef } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
|
||||
import { useCategories } from "@/contexts/AdminCategoriesContext";
|
||||
import { useAuth } from "@/contexts/AuthContext";
|
||||
|
||||
import DataTable from "@/components/generic/Table/DataTable";
|
||||
import { FilterSheet } from "@/components/generic/Sheet/FilterSheet";
|
||||
|
||||
import { buildDataColumns, columnPinning } from "../../config/categories/columns.config";
|
||||
import { buildToolbarActions } from "../../config/categories/toolbar.config";
|
||||
import { buildSelectionActions } from "../../config/categories/selection.config";
|
||||
import { buildRowActions } from "../../config/categories/rowActions.config";
|
||||
|
||||
import { getTimestamp } from "@/utils/timestamp.util";
|
||||
import { formatGeneratedBy } from "@/utils/generatedBy.util";
|
||||
|
||||
export default function CategoriesTable() {
|
||||
const navigate = useNavigate();
|
||||
const { user: currentUser } = useAuth();
|
||||
|
||||
const {
|
||||
categories, categoryAttributes, categoryPagination, setCategoryPagination,
|
||||
loading, fetchCategories, archiveCategory, bulkArchiveCategories,
|
||||
} = useCategories();
|
||||
|
||||
const tableRefsRef = useRef({
|
||||
getFilters: () => [],
|
||||
getSort: () => [],
|
||||
resetSelection: () => {},
|
||||
tableInstance: null,
|
||||
});
|
||||
|
||||
const handleRefsReady = (refs) => { tableRefsRef.current = refs; };
|
||||
|
||||
const refetch = () => {
|
||||
tableRefsRef.current.resetSelection?.();
|
||||
fetchCategories({
|
||||
page: 1,
|
||||
limit: categoryPagination?.limit ?? 10,
|
||||
filters: tableRefsRef.current.getFilters(),
|
||||
sort: tableRefsRef.current.getSort(),
|
||||
});
|
||||
};
|
||||
|
||||
const rowActions = buildRowActions({
|
||||
navigate,
|
||||
onArchive: async (row) => { await archiveCategory(row.id); refetch(); },
|
||||
});
|
||||
|
||||
const exportConfig = useMemo(() => ({
|
||||
allData: categories,
|
||||
attributes: categoryAttributes,
|
||||
filename: `${getTimestamp()}_Categories`,
|
||||
sheetName: "Categories",
|
||||
generatedBy: formatGeneratedBy(currentUser),
|
||||
}), [categories, categoryAttributes, currentUser]);
|
||||
|
||||
const toolbarActions = buildToolbarActions({
|
||||
fetchCategories,
|
||||
pagination: categoryPagination,
|
||||
exportConfig,
|
||||
navigate,
|
||||
getFilters: () => tableRefsRef.current.getFilters(),
|
||||
getSort: () => tableRefsRef.current.getSort(),
|
||||
getTableInstance: () => tableRefsRef.current.tableInstance,
|
||||
});
|
||||
|
||||
const selectionActions = buildSelectionActions({
|
||||
onArchive: async (row) => { await archiveCategory(row.id); refetch(); },
|
||||
onArchiveMany: async (ids) => { await bulkArchiveCategories(ids); refetch(); },
|
||||
});
|
||||
|
||||
const columns = useMemo(
|
||||
() => buildDataColumns(categoryAttributes, rowActions),
|
||||
[categoryAttributes, rowActions]
|
||||
);
|
||||
|
||||
return (
|
||||
<DataTable
|
||||
title="Categories"
|
||||
data={categories}
|
||||
columns={columns}
|
||||
attributes={categoryAttributes}
|
||||
pagination={categoryPagination}
|
||||
setPagination={setCategoryPagination}
|
||||
loading={loading}
|
||||
onFetch={fetchCategories}
|
||||
onFetchFilterData={async () => []}
|
||||
onRefsReady={handleRefsReady}
|
||||
renderFilterSheet={({ open, onOpenChange, column, attr, data, loading }) => (
|
||||
<FilterSheet
|
||||
open={open}
|
||||
onOpenChange={onOpenChange}
|
||||
column={column}
|
||||
attr={attr}
|
||||
data={data}
|
||||
loading={loading}
|
||||
/>
|
||||
)}
|
||||
columnPinning={columnPinning}
|
||||
toolbarActions={toolbarActions}
|
||||
selectionActions={selectionActions}
|
||||
recordLabel="category"
|
||||
emptyMessage="No categories yet. Add one to get started."
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
// modules/admin/components/courses/AchievementsBuilder.jsx
|
||||
// The "Achievements" sub-section of the Rewards step: pick an existing
|
||||
// achievement from the registry or define a new one — same New/Attach
|
||||
// pattern as RoadmapBuilder's Units section. A course carries at most one
|
||||
// achievement.
|
||||
|
||||
import { useState } from "react";
|
||||
import * as LucideIcons from "lucide-react";
|
||||
import { Plus, Link2, Trophy, BadgeCheck, Trash2 } from "lucide-react";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import AttachAchievementDialog from "./AttachAchievementDialog";
|
||||
import CreateAchievementDialog from "./CreateAchievementDialog";
|
||||
|
||||
export default function AchievementsBuilder({ achievementKeys, onAchievementKeysChange, registry, onRegistryChange }) {
|
||||
const [attachOpen, setAttachOpen] = useState(false);
|
||||
const [createOpen, setCreateOpen] = useState(false);
|
||||
|
||||
const selected = registry.find((a) => a.key === achievementKeys[0]) ?? null;
|
||||
|
||||
const handleAttach = (key) => onAchievementKeysChange([key]);
|
||||
|
||||
const handleCreated = (achievement) => {
|
||||
onRegistryChange([...registry, achievement]);
|
||||
onAchievementKeysChange([achievement.key]);
|
||||
};
|
||||
|
||||
const declineAchievement = () => {
|
||||
onAchievementKeysChange([]);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="border-t pt-4">
|
||||
<div className="flex items-start justify-between gap-3 pb-3 mb-3 border-b">
|
||||
<div className="space-y-0.5">
|
||||
<h2 className="text-sm font-semibold">Achievements</h2>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Attach an existing achievement from the registry, or define a new one from scratch.
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-2 shrink-0">
|
||||
|
||||
<Button type="button" variant="outline" size="sm" onClick={() => setAttachOpen(true)}>
|
||||
<Link2 /> Select
|
||||
</Button>
|
||||
<Button type="button" variant="outline" size="sm" onClick={() => setCreateOpen(true)}>
|
||||
<Plus /> Create
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{!selected ? (
|
||||
<div className="flex flex-col items-center justify-center gap-2 py-8 text-center">
|
||||
<Trophy className="h-7 w-7 text-muted-foreground" />
|
||||
<p className="text-sm font-medium">No achievement selected</p>
|
||||
<Button type="button" variant="ghost" size="sm" className="text-muted-foreground" onClick={declineAchievement}>
|
||||
Actually, skip achievements
|
||||
</Button>
|
||||
</div>
|
||||
) : (
|
||||
<div className="rounded-md border px-3 py-2.5 flex items-center gap-3">
|
||||
{(() => {
|
||||
const Icon = LucideIcons[selected.icon] ?? Trophy;
|
||||
return <Icon className="h-4 w-4 text-muted-foreground shrink-0" />;
|
||||
})()}
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="text-sm font-medium truncate">{selected.label}</p>
|
||||
{selected.description && (
|
||||
<p className="text-xs text-muted-foreground truncate">{selected.description}</p>
|
||||
)}
|
||||
</div>
|
||||
<Badge variant="outline" className="text-[10px] shrink-0 capitalize gap-1">
|
||||
{selected.type === "badge" ? <Trophy className="h-2.5 w-2.5" /> : <BadgeCheck className="h-2.5 w-2.5" />}
|
||||
{selected.type}
|
||||
</Badge>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="text-muted-foreground hover:text-destructive shrink-0 h-7 w-7"
|
||||
onClick={() => onAchievementKeysChange([])}
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<AttachAchievementDialog
|
||||
open={attachOpen}
|
||||
onOpenChange={setAttachOpen}
|
||||
registry={registry}
|
||||
selectedKey={achievementKeys[0] ?? null}
|
||||
onAttach={handleAttach}
|
||||
/>
|
||||
<CreateAchievementDialog
|
||||
open={createOpen}
|
||||
onOpenChange={setCreateOpen}
|
||||
onCreated={handleCreated}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
import { useMemo, useRef, useState } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
|
||||
import { useCourses } from "@/contexts/AdminCoursesContext";
|
||||
import { useAuth } from "@/contexts/AuthContext";
|
||||
|
||||
import DataTable from "@/components/generic/Table/DataTable";
|
||||
import { FilterSheet } from "@/components/generic/Sheet/FilterSheet";
|
||||
import { RestoreDialog } from "@/components/generic/Dialogs/RestoreDialog";
|
||||
import { PermanentDeleteDialog } from "@/components/generic/Dialogs/PermanentDeleteDialog";
|
||||
|
||||
import { buildDataColumns, columnPinning } from "../../config/courses/archive/columns.config";
|
||||
import { buildToolbarActions } from "../../config/courses/archive/toolbar.config";
|
||||
import { buildSelectionActions } from "../../config/courses/archive/selection.config";
|
||||
import { buildRowActions } from "../../config/courses/archive/rowActions.config";
|
||||
|
||||
import { getTimestamp } from "@/utils/timestamp.util";
|
||||
import { formatGeneratedBy } from "@/utils/generatedBy.util";
|
||||
|
||||
export default function ArchivedCoursesTable() {
|
||||
const [restoreTarget, setRestoreTarget] = useState(null);
|
||||
const [restoreIds, setRestoreIds] = useState(null);
|
||||
const [deleteTarget, setDeleteTarget] = useState(null);
|
||||
const [deleteIds, setDeleteIds] = useState(null);
|
||||
|
||||
const tableRefsRef = useRef({
|
||||
getFilters: () => [],
|
||||
getSort: () => [],
|
||||
resetSelection: () => { },
|
||||
setFilters: () => { },
|
||||
});
|
||||
|
||||
const navigate = useNavigate();
|
||||
|
||||
const { user: currentUser } = useAuth();
|
||||
|
||||
const {
|
||||
courses, attributes, pagination, setPagination, loading, fetchArchivedCourses,
|
||||
restoreCourse, restoreCourses,
|
||||
permanentlyDeleteCourse, permanentlyDeleteCourses, fetchCoursePermanentDeleteImpact,
|
||||
} = useCourses();
|
||||
|
||||
const handleRefsReady = (refs) => {
|
||||
tableRefsRef.current = refs;
|
||||
};
|
||||
|
||||
const exportConfig = {
|
||||
allData: courses,
|
||||
attributes,
|
||||
filename: `${getTimestamp()}_ArchivedCourses`,
|
||||
sheetName: "Archived Courses",
|
||||
generatedBy: formatGeneratedBy(currentUser),
|
||||
};
|
||||
|
||||
const rowActions = useMemo(() => buildRowActions({
|
||||
navigate,
|
||||
onRestore: (row) => setRestoreTarget(row),
|
||||
onDelete: (row) => setDeleteTarget(row),
|
||||
}), []);
|
||||
|
||||
const toolbarActions = buildToolbarActions({
|
||||
fetchArchivedCourses,
|
||||
pagination,
|
||||
exportConfig,
|
||||
navigate,
|
||||
getFilters: () => tableRefsRef.current.getFilters(),
|
||||
getSort: () => tableRefsRef.current.getSort(),
|
||||
getTableInstance: () => tableRefsRef.current.tableInstance,
|
||||
});
|
||||
|
||||
const selectionActions = buildSelectionActions({
|
||||
exportConfig,
|
||||
restoreCourse: (row) => setRestoreTarget(row), // single
|
||||
restoreCourses: (ids) => setRestoreIds(ids), // bulk
|
||||
deleteCourse: (row) => setDeleteTarget(row),
|
||||
deleteCourses: (ids) => setDeleteIds(ids),
|
||||
getTableInstance: () => tableRefsRef.current.tableInstance,
|
||||
});
|
||||
|
||||
const columns = useMemo(
|
||||
() => buildDataColumns(attributes, rowActions),
|
||||
[attributes]
|
||||
);
|
||||
|
||||
const handleRestoreSuccess = () => {
|
||||
setRestoreTarget(null);
|
||||
setRestoreIds(null);
|
||||
tableRefsRef.current.resetSelection?.();
|
||||
fetchArchivedCourses({ page: 1, limit: pagination?.limit ?? 10 });
|
||||
};
|
||||
|
||||
const handleDeleteSuccess = () => {
|
||||
setDeleteTarget(null);
|
||||
setDeleteIds(null);
|
||||
tableRefsRef.current.resetSelection?.();
|
||||
fetchArchivedCourses({ page: 1, limit: pagination?.limit ?? 10 });
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<DataTable
|
||||
title="Archived Courses"
|
||||
data={courses}
|
||||
columns={columns}
|
||||
attributes={attributes}
|
||||
pagination={pagination}
|
||||
setPagination={setPagination}
|
||||
loading={loading}
|
||||
onFetch={fetchArchivedCourses}
|
||||
onFetchFilterData={() => []}
|
||||
onRefsReady={handleRefsReady}
|
||||
renderFilterSheet={({ open, onOpenChange, column, attr, data, loading }) => (
|
||||
<FilterSheet
|
||||
open={open}
|
||||
onOpenChange={onOpenChange}
|
||||
column={column}
|
||||
attr={attr}
|
||||
data={data}
|
||||
loading={loading}
|
||||
/>
|
||||
)}
|
||||
columnPinning={columnPinning}
|
||||
toolbarActions={toolbarActions}
|
||||
selectionActions={selectionActions}
|
||||
recordLabel="course"
|
||||
emptyMessage="No courses found."
|
||||
/>
|
||||
|
||||
{/* Single restore */}
|
||||
<RestoreDialog
|
||||
open={!!restoreTarget}
|
||||
onOpenChange={(v) => !v && setRestoreTarget(null)}
|
||||
entity={restoreTarget}
|
||||
entityLabel="Course"
|
||||
getName={(c) => c?.title}
|
||||
onRestore={(c) => restoreCourse(c?.course_id)}
|
||||
loading={loading}
|
||||
onSuccess={handleRestoreSuccess}
|
||||
/>
|
||||
|
||||
{/* Bulk restore */}
|
||||
<RestoreDialog
|
||||
open={!!restoreIds}
|
||||
onOpenChange={(v) => !v && setRestoreIds(null)}
|
||||
ids={restoreIds ?? []}
|
||||
entityLabel="Course"
|
||||
onRestore={restoreCourses}
|
||||
loading={loading}
|
||||
onSuccess={handleRestoreSuccess}
|
||||
/>
|
||||
|
||||
{/* Single permanent delete */}
|
||||
<PermanentDeleteDialog
|
||||
open={!!deleteTarget}
|
||||
onOpenChange={(v) => !v && setDeleteTarget(null)}
|
||||
entity={deleteTarget}
|
||||
entityLabel="Course"
|
||||
getName={(c) => c?.title}
|
||||
onDelete={(c) => permanentlyDeleteCourse(c?.course_id)}
|
||||
onImpactCheck={() => fetchCoursePermanentDeleteImpact(deleteTarget?.course_id)}
|
||||
loading={loading}
|
||||
onSuccess={handleDeleteSuccess}
|
||||
/>
|
||||
|
||||
{/* Bulk permanent delete */}
|
||||
<PermanentDeleteDialog
|
||||
open={!!deleteIds}
|
||||
onOpenChange={(v) => !v && setDeleteIds(null)}
|
||||
ids={deleteIds ?? []}
|
||||
entityLabel="Course"
|
||||
onDelete={permanentlyDeleteCourses}
|
||||
loading={loading}
|
||||
onSuccess={handleDeleteSuccess}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
import { useMemo, useRef, useState, useEffect, useCallback } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
|
||||
import { useCourses } from "@/contexts/AdminCoursesContext";
|
||||
import { useAuth } from "@/contexts/AuthContext";
|
||||
|
||||
import DataTable from "@/components/generic/Table/DataTable";
|
||||
import { FilterSheet } from "@/components/generic/Sheet/FilterSheet";
|
||||
import { RestoreDialog } from "@/components/generic/Dialogs/RestoreDialog";
|
||||
import { PermanentDeleteDialog } from "@/components/generic/Dialogs/PermanentDeleteDialog";
|
||||
|
||||
import { buildDataColumns, columnPinning } from "../../config/courses/lessons/archive/columns.config";
|
||||
import { buildToolbarActions } from "../../config/courses/lessons/archive/toolbar.config";
|
||||
import { buildSelectionActions } from "../../config/courses/lessons/archive/selection.config";
|
||||
import { buildRowActions } from "../../config/courses/lessons/archive/rowActions.config";
|
||||
|
||||
import { getTimestamp } from "@/utils/timestamp.util";
|
||||
import { formatGeneratedBy } from "@/utils/generatedBy.util";
|
||||
|
||||
export default function ArchivedLessonsTable({ courseId, unitId }) {
|
||||
const [restoreTarget, setRestoreTarget] = useState(null);
|
||||
const [restoreIds, setRestoreIds] = useState(null);
|
||||
const [deleteTarget, setDeleteTarget] = useState(null);
|
||||
const [deleteIds, setDeleteIds] = useState(null);
|
||||
|
||||
const tableRefsRef = useRef({
|
||||
getFilters: () => [],
|
||||
getSort: () => [],
|
||||
resetSelection: () => { },
|
||||
setFilters: () => { },
|
||||
});
|
||||
|
||||
const navigate = useNavigate();
|
||||
|
||||
const { user: currentUser } = useAuth();
|
||||
|
||||
const {
|
||||
course, unit, lessons, attributes, pagination, setPagination, loading,
|
||||
fetchArchivedLessons, restoreLesson, restoreLessons, fetchLessonFieldValues,
|
||||
permanentlyDeleteLesson, permanentlyDeleteLessons
|
||||
} = useCourses();
|
||||
|
||||
const handleRefsReady = (refs) => {
|
||||
tableRefsRef.current = refs;
|
||||
};
|
||||
|
||||
const exportConfig = {
|
||||
allData: lessons,
|
||||
attributes,
|
||||
filename: `${getTimestamp()}_${course?.title}_${unit?.title}_Lessons`,
|
||||
sheetName: "Archived Lessons",
|
||||
generatedBy: formatGeneratedBy(currentUser),
|
||||
};
|
||||
|
||||
const handleFetch = useCallback(
|
||||
(params) => fetchArchivedLessons(courseId, unitId, params),
|
||||
[courseId, unitId]
|
||||
);
|
||||
|
||||
const rowActions = useMemo(() => buildRowActions({
|
||||
navigate,
|
||||
onRestore: (row) => setRestoreTarget(row),
|
||||
onDelete: (row) => setDeleteTarget(row),
|
||||
}), [courseId, unitId]);
|
||||
|
||||
const toolbarActions = buildToolbarActions({
|
||||
fetchArchivedLessons: (params) => fetchArchivedLessons(courseId, unitId, params),
|
||||
pagination,
|
||||
exportConfig,
|
||||
navigate,
|
||||
courseId,
|
||||
unitId,
|
||||
getFilters: () => tableRefsRef.current.getFilters(),
|
||||
getSort: () => tableRefsRef.current.getSort(),
|
||||
getTableInstance: () => tableRefsRef.current.tableInstance,
|
||||
});
|
||||
|
||||
const selectionActions = buildSelectionActions({
|
||||
exportConfig,
|
||||
restoreLesson: (row) => setRestoreTarget(row), // single
|
||||
restoreLessons: (ids) => setRestoreIds(ids), // bulk
|
||||
deleteLesson: (row) => setDeleteTarget(row),
|
||||
deleteLessons: (ids) => setDeleteIds(ids),
|
||||
getTableInstance: () => tableRefsRef.current.tableInstance,
|
||||
});
|
||||
|
||||
const columns = useMemo(
|
||||
() => buildDataColumns(attributes, rowActions),
|
||||
[attributes, rowActions]
|
||||
);
|
||||
|
||||
const handleRestoreSuccess = () => {
|
||||
setRestoreTarget(null);
|
||||
setRestoreIds(null);
|
||||
tableRefsRef.current.resetSelection?.();
|
||||
fetchArchivedLessons(courseId, unitId, { page: 1, limit: pagination?.limit ?? 10 });
|
||||
};
|
||||
|
||||
const handleDeleteSuccess = () => {
|
||||
setDeleteTarget(null);
|
||||
setDeleteIds(null);
|
||||
tableRefsRef.current.resetSelection?.();
|
||||
fetchArchivedLessons(courseId, unitId, { page: 1, limit: pagination?.limit ?? 10 });
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<DataTable
|
||||
title="Archived Lessons"
|
||||
data={lessons}
|
||||
columns={columns}
|
||||
attributes={attributes}
|
||||
pagination={pagination}
|
||||
setPagination={setPagination}
|
||||
loading={loading}
|
||||
onFetch={handleFetch}
|
||||
onFetchFilterData={(field) => fetchLessonFieldValues(courseId, unitId, field)}
|
||||
onRefsReady={handleRefsReady}
|
||||
renderFilterSheet={({ open, onOpenChange, column, attr, data, loading }) => (
|
||||
<FilterSheet
|
||||
open={open}
|
||||
onOpenChange={onOpenChange}
|
||||
column={column}
|
||||
attr={attr}
|
||||
data={data}
|
||||
loading={loading}
|
||||
/>
|
||||
)}
|
||||
columnPinning={columnPinning}
|
||||
toolbarActions={toolbarActions}
|
||||
selectionActions={selectionActions}
|
||||
recordLabel="lesson"
|
||||
emptyMessage="No lessons found."
|
||||
/>
|
||||
|
||||
{/* Single restore */}
|
||||
<RestoreDialog
|
||||
open={!!restoreTarget}
|
||||
onOpenChange={(v) => !v && setRestoreTarget(null)}
|
||||
entity={restoreTarget}
|
||||
entityLabel="Lesson"
|
||||
getName={(c) => c?.title}
|
||||
onRestore={(c) => restoreLesson(courseId, unitId, c?.lesson_id)}
|
||||
loading={loading}
|
||||
onSuccess={handleRestoreSuccess}
|
||||
/>
|
||||
|
||||
{/* Bulk restore */}
|
||||
<RestoreDialog
|
||||
open={!!restoreIds}
|
||||
onOpenChange={(v) => !v && setRestoreIds(null)}
|
||||
ids={restoreIds ?? []}
|
||||
entityLabel="Lesson"
|
||||
onRestore={(ids) => restoreLessons(courseId, unitId, ids)}
|
||||
loading={loading}
|
||||
onSuccess={handleRestoreSuccess}
|
||||
/>
|
||||
|
||||
{/* Single permanent delete */}
|
||||
<PermanentDeleteDialog
|
||||
open={!!deleteTarget}
|
||||
onOpenChange={(v) => !v && setDeleteTarget(null)}
|
||||
entity={deleteTarget}
|
||||
entityLabel="Lesson"
|
||||
getName={(c) => c?.title}
|
||||
onDelete={(c) => permanentlyDeleteLesson(courseId, unitId, c?.lesson_id)}
|
||||
loading={loading}
|
||||
onSuccess={handleDeleteSuccess}
|
||||
/>
|
||||
|
||||
{/* Bulk permanent delete */}
|
||||
<PermanentDeleteDialog
|
||||
open={!!deleteIds}
|
||||
onOpenChange={(v) => !v && setDeleteIds(null)}
|
||||
ids={deleteIds ?? []}
|
||||
entityLabel="Lesson"
|
||||
onDelete={(ids) => permanentlyDeleteLessons(courseId, unitId, ids)}
|
||||
loading={loading}
|
||||
onSuccess={handleDeleteSuccess}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
import { useMemo, useRef, useState, useCallback } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
|
||||
import { useCourses } from "@/contexts/AdminCoursesContext";
|
||||
import { useAuth } from "@/contexts/AuthContext";
|
||||
|
||||
import DataTable from "@/components/generic/Table/DataTable";
|
||||
import { FilterSheet } from "@/components/generic/Sheet/FilterSheet";
|
||||
import { RestoreDialog } from "@/components/generic/Dialogs/RestoreDialog";
|
||||
import { PermanentDeleteDialog } from "@/components/generic/Dialogs/PermanentDeleteDialog";
|
||||
|
||||
import { buildDataColumns, columnPinning } from "../../config/courses/units/archive/columns.config";
|
||||
import { buildToolbarActions } from "../../config/courses/units/archive/toolbar.config";
|
||||
import { buildSelectionActions } from "../../config/courses/units/archive/selection.config";
|
||||
import { buildRowActions } from "../../config/courses/units/archive/rowActions.config";
|
||||
|
||||
import { getTimestamp } from "@/utils/timestamp.util";
|
||||
import { formatGeneratedBy } from "@/utils/generatedBy.util";
|
||||
|
||||
export default function ArchivedUnitsTable({ courseId }) {
|
||||
const [restoreTarget, setRestoreTarget] = useState(null);
|
||||
const [restoreIds, setRestoreIds] = useState(null);
|
||||
const [deleteTarget, setDeleteTarget] = useState(null);
|
||||
const [deleteIds, setDeleteIds] = useState(null);
|
||||
|
||||
const tableRefsRef = useRef({
|
||||
getFilters: () => [],
|
||||
getSort: () => [],
|
||||
resetSelection: () => { },
|
||||
setFilters: () => { },
|
||||
});
|
||||
|
||||
const navigate = useNavigate();
|
||||
|
||||
const { user: currentUser } = useAuth();
|
||||
|
||||
const {
|
||||
course, units, attributes, pagination, setPagination, loading,
|
||||
fetchArchivedUnits, restoreUnit, restoreUnits, fetchUnitFieldValues,
|
||||
permanentlyDeleteUnit, permanentlyDeleteUnits, fetchUnitPermanentDeleteImpact,
|
||||
} = useCourses();
|
||||
|
||||
const handleRefsReady = (refs) => {
|
||||
tableRefsRef.current = refs;
|
||||
};
|
||||
|
||||
const exportConfig = {
|
||||
allData: units,
|
||||
attributes,
|
||||
filename: `${getTimestamp()}_${course?.title}_ArchivedUnits`,
|
||||
sheetName: "Archived Units",
|
||||
generatedBy: formatGeneratedBy(currentUser),
|
||||
};
|
||||
|
||||
const handleFetch = useCallback(
|
||||
(params) => fetchArchivedUnits(courseId, params),
|
||||
[courseId]
|
||||
);
|
||||
|
||||
const rowActions = useMemo(() => buildRowActions({
|
||||
onRestore: (row) => setRestoreTarget(row),
|
||||
onDelete: (row) => setDeleteTarget(row),
|
||||
}), [courseId]);
|
||||
|
||||
const toolbarActions = buildToolbarActions({
|
||||
fetchArchivedUnits: (params) => fetchArchivedUnits(courseId, params),
|
||||
pagination,
|
||||
exportConfig,
|
||||
navigate,
|
||||
courseId,
|
||||
getFilters: () => tableRefsRef.current.getFilters(),
|
||||
getSort: () => tableRefsRef.current.getSort(),
|
||||
getTableInstance: () => tableRefsRef.current.tableInstance,
|
||||
});
|
||||
|
||||
const selectionActions = buildSelectionActions({
|
||||
exportConfig,
|
||||
restoreUnit: (row) => setRestoreTarget(row), // single
|
||||
restoreUnits: (ids) => setRestoreIds(ids), // bulk
|
||||
deleteUnit: (row) => setDeleteTarget(row),
|
||||
deleteUnits: (ids) => setDeleteIds(ids),
|
||||
getTableInstance: () => tableRefsRef.current.tableInstance,
|
||||
});
|
||||
|
||||
const columns = useMemo(
|
||||
() => buildDataColumns(attributes, rowActions),
|
||||
[attributes]
|
||||
);
|
||||
|
||||
const handleRestoreSuccess = () => {
|
||||
setRestoreTarget(null);
|
||||
setRestoreIds(null);
|
||||
tableRefsRef.current.resetSelection?.();
|
||||
fetchArchivedUnits(courseId, { page: 1, limit: pagination?.limit ?? 10 });
|
||||
};
|
||||
|
||||
const handleDeleteSuccess = () => {
|
||||
setDeleteTarget(null);
|
||||
setDeleteIds(null);
|
||||
tableRefsRef.current.resetSelection?.();
|
||||
fetchArchivedUnits(courseId, { page: 1, limit: pagination?.limit ?? 10 });
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<DataTable
|
||||
title="Archvied Units"
|
||||
data={units}
|
||||
columns={columns}
|
||||
attributes={attributes}
|
||||
pagination={pagination}
|
||||
setPagination={setPagination}
|
||||
loading={loading}
|
||||
onFetch={handleFetch}
|
||||
onFetchFilterData={(field) => fetchUnitFieldValues(courseId, field)}
|
||||
onRefsReady={handleRefsReady}
|
||||
renderFilterSheet={({ open, onOpenChange, column, attr, data, loading }) => (
|
||||
<FilterSheet
|
||||
open={open}
|
||||
onOpenChange={onOpenChange}
|
||||
column={column}
|
||||
attr={attr}
|
||||
data={data}
|
||||
loading={loading}
|
||||
/>
|
||||
)}
|
||||
columnPinning={columnPinning}
|
||||
toolbarActions={toolbarActions}
|
||||
selectionActions={selectionActions}
|
||||
recordLabel="unit"
|
||||
emptyMessage="No units found."
|
||||
/>
|
||||
|
||||
{/* Single restore */}
|
||||
<RestoreDialog
|
||||
open={!!restoreTarget}
|
||||
onOpenChange={(v) => !v && setRestoreTarget(null)}
|
||||
entity={restoreTarget}
|
||||
entityLabel="Unit"
|
||||
getName={(c) => c?.title}
|
||||
onRestore={(c) => restoreUnit(courseId, c?.unit_id)}
|
||||
loading={loading}
|
||||
onSuccess={handleRestoreSuccess}
|
||||
/>
|
||||
|
||||
{/* Bulk restore */}
|
||||
<RestoreDialog
|
||||
open={!!restoreIds}
|
||||
onOpenChange={(v) => !v && setRestoreIds(null)}
|
||||
ids={restoreIds ?? []}
|
||||
entityLabel="Unit"
|
||||
onRestore={(ids) => restoreUnits(courseId, ids)}
|
||||
loading={loading}
|
||||
onSuccess={handleRestoreSuccess}
|
||||
/>
|
||||
|
||||
{/* Single permanent delete */}
|
||||
<PermanentDeleteDialog
|
||||
open={!!deleteTarget}
|
||||
onOpenChange={(v) => !v && setDeleteTarget(null)}
|
||||
entity={deleteTarget}
|
||||
entityLabel="Unit"
|
||||
getName={(c) => c?.title}
|
||||
onDelete={(c) => permanentlyDeleteUnit(courseId, c?.unit_id)}
|
||||
onImpactCheck={() => fetchUnitPermanentDeleteImpact(courseId, deleteTarget?.unit_id)}
|
||||
loading={loading}
|
||||
onSuccess={handleDeleteSuccess}
|
||||
/>
|
||||
|
||||
{/* Bulk permanent delete */}
|
||||
<PermanentDeleteDialog
|
||||
open={!!deleteIds}
|
||||
onOpenChange={(v) => !v && setDeleteIds(null)}
|
||||
ids={deleteIds ?? []}
|
||||
entityLabel="Unit"
|
||||
onDelete={(ids) => permanentlyDeleteUnits(courseId, ids)}
|
||||
loading={loading}
|
||||
onSuccess={handleDeleteSuccess}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,804 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { Plus, Save, ClipboardList, ChevronUp, ChevronDown, AlertTriangle, Trash2, X } from "lucide-react";
|
||||
|
||||
import { toast } from "sonner";
|
||||
import { useCourses } from "@/contexts/AdminCoursesContext";
|
||||
import { useAuth } from "@/contexts/AuthContext";
|
||||
import { useUnsavedChangesGuard } from "@/hooks/useUnsavedChangesGuard";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Spinner } from "@/components/ui/spinner";
|
||||
import { Checkbox } from "@/components/ui/checkbox";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { QuestionCard, makeQuestion } from "./QuestionEditor";
|
||||
import api from "@/utils/api.util";
|
||||
|
||||
// ── Dirty-check snapshot ──────────────────────────────────────────────────────
|
||||
|
||||
function snapAssessment({ title, passingScore, timeLimit, isRequired, maxQuestions, maxAttempts, cooldownHours, shuffleQuestions, questions }) {
|
||||
return JSON.stringify({
|
||||
title, passingScore, timeLimit, isRequired, maxQuestions, maxAttempts, cooldownHours, shuffleQuestions,
|
||||
questions: questions.map((q) => ({
|
||||
question_id: q.question_id ?? null,
|
||||
question: q.question,
|
||||
type: q.type,
|
||||
points: q.points ?? 1,
|
||||
options: (q.options ?? []).map((o) => ({
|
||||
option_id: o.option_id ?? null,
|
||||
text: o.text,
|
||||
is_correct: o.is_correct,
|
||||
})),
|
||||
})),
|
||||
});
|
||||
}
|
||||
|
||||
// ── Server row → form state ──────────────────────────────────────────────────
|
||||
|
||||
function toFormState(a) {
|
||||
return {
|
||||
title: a?.title ?? "",
|
||||
passingScore: a?.passing_score ?? 70,
|
||||
timeLimit: a?.time_limit_minutes ?? "",
|
||||
isRequired: a?.is_required === true || a?.is_required === 1,
|
||||
maxQuestions: a?.max_questions ?? "",
|
||||
maxAttempts: a?.max_attempts ?? 3,
|
||||
cooldownHours: a?.cooldown_hours ?? 24,
|
||||
shuffleQuestions: a?.shuffle_questions === true || a?.shuffle_questions === 1,
|
||||
questions: (a?.questions ?? []).map((q) => ({ ...q, _tempId: q.question_id, options: q.options ?? [] })),
|
||||
};
|
||||
}
|
||||
|
||||
// ── Validation ────────────────────────────────────────────────────────────────
|
||||
|
||||
function validate(questions) {
|
||||
const errors = {};
|
||||
questions.forEach((q, i) => {
|
||||
const qErr = {};
|
||||
if (!q.question?.trim()) qErr.question = "Question text is required.";
|
||||
const correctCount = q.options.filter((o) => o.is_correct).length;
|
||||
if (correctCount === 0) qErr.options = "At least one correct answer is required.";
|
||||
if (q.options.some((o) => !o.text?.trim())) qErr.options = "All option texts are required.";
|
||||
if (Object.keys(qErr).length) errors[i] = qErr;
|
||||
});
|
||||
return errors;
|
||||
}
|
||||
|
||||
// ── Jump to input ─────────────────────────────────────────────────────────────
|
||||
|
||||
function JumpToInput({ max, onJump }) {
|
||||
const [val, setVal] = useState("");
|
||||
|
||||
const handleJump = () => {
|
||||
const n = parseInt(val, 10);
|
||||
if (!isNaN(n) && n >= 1 && n <= max) {
|
||||
onJump(n - 1);
|
||||
setVal("");
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex gap-1">
|
||||
<Input
|
||||
type="number"
|
||||
min={1}
|
||||
max={max}
|
||||
value={val}
|
||||
onChange={(e) => setVal(e.target.value)}
|
||||
onKeyDown={(e) => e.key === "Enter" && handleJump()}
|
||||
placeholder={`1–${max}`}
|
||||
className="h-7 text-xs"
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant="outline"
|
||||
className="h-7 px-2 text-xs shrink-0"
|
||||
onClick={handleJump}
|
||||
>
|
||||
Go
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ── Question Navigator ────────────────────────────────────────────────────────
|
||||
|
||||
const TYPE_LABEL = {
|
||||
multiple_choice: "MC",
|
||||
multi_select: "MS",
|
||||
true_false: "TF",
|
||||
};
|
||||
|
||||
function QuestionNavigator({ questions, activeIndex, onJump, onMove, navItemRefs, navContainerRef, errors }) {
|
||||
return (
|
||||
<div className="flex flex-col rounded-lg border bg-card overflow-hidden">
|
||||
|
||||
{/* Header */}
|
||||
<div className="px-3 py-3 border-b shrink-0">
|
||||
<p className="text-xs font-medium text-muted-foreground uppercase tracking-wide">
|
||||
Questions
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground mt-0.5">
|
||||
{questions.length} total
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Scrollable list */}
|
||||
<div ref={navContainerRef} className="max-h-96 overflow-y-auto py-2">
|
||||
{questions.length === 0 ? (
|
||||
<p className="text-xs text-muted-foreground text-center py-8 px-3">
|
||||
No questions yet.
|
||||
</p>
|
||||
) : (
|
||||
<div className="space-y-0.5 px-2">
|
||||
{questions.map((q, i) => {
|
||||
const isActive = i === activeIndex;
|
||||
const hasError = !!errors?.[i];
|
||||
const typeLabel = TYPE_LABEL[q.type] ?? "Q";
|
||||
|
||||
return (
|
||||
<div
|
||||
key={q._tempId ?? q.question_id ?? i}
|
||||
ref={(el) => (navItemRefs.current[i] = el)}
|
||||
onClick={() => onJump(i)}
|
||||
className={cn(
|
||||
"group flex items-center gap-1.5 rounded-md px-2 py-1.5 cursor-pointer transition-colors",
|
||||
isActive
|
||||
? "bg-primary/10 text-primary"
|
||||
: hasError
|
||||
? "bg-destructive/10 text-destructive hover:bg-destructive/20"
|
||||
: "hover:bg-muted text-foreground"
|
||||
)}
|
||||
>
|
||||
{/* Number badge */}
|
||||
<span className={cn(
|
||||
"flex h-5 w-5 shrink-0 items-center justify-center rounded text-[10px] font-semibold",
|
||||
isActive
|
||||
? "bg-primary text-primary-foreground"
|
||||
: hasError
|
||||
? "bg-destructive text-destructive-foreground"
|
||||
: "bg-muted-foreground/20 text-muted-foreground"
|
||||
)}>
|
||||
{i + 1}
|
||||
</span>
|
||||
|
||||
{/* Type */}
|
||||
<span className="text-[10px] font-medium text-muted-foreground shrink-0 w-5">
|
||||
{typeLabel}
|
||||
</span>
|
||||
|
||||
{/* Question preview */}
|
||||
<span className="flex-1 text-xs truncate min-w-0">
|
||||
{q.question?.trim()
|
||||
? q.question.trim()
|
||||
: <span className="italic text-muted-foreground">Untitled</span>
|
||||
}
|
||||
</span>
|
||||
|
||||
{/* Move buttons — show on hover */}
|
||||
<div className="hidden group-hover:flex items-center gap-0.5 shrink-0">
|
||||
<button
|
||||
type="button"
|
||||
onClick={(e) => { e.stopPropagation(); onMove(i, "up"); }}
|
||||
disabled={i === 0}
|
||||
className="h-4 w-4 flex items-center justify-center rounded hover:bg-muted-foreground/20 disabled:opacity-30 transition-colors"
|
||||
>
|
||||
<ChevronUp className="h-3 w-3" />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={(e) => { e.stopPropagation(); onMove(i, "down"); }}
|
||||
disabled={i === questions.length - 1}
|
||||
className="h-4 w-4 flex items-center justify-center rounded hover:bg-muted-foreground/20 disabled:opacity-30 transition-colors"
|
||||
>
|
||||
<ChevronDown className="h-3 w-3" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Jump to — only when enough questions */}
|
||||
{questions.length > 5 && (
|
||||
<div className="px-3 py-3 border-t shrink-0 space-y-1.5">
|
||||
<p className="text-xs text-muted-foreground">Jump to question</p>
|
||||
<JumpToInput max={questions.length} onJump={onJump} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ── Main ──────────────────────────────────────────────────────────────────────
|
||||
|
||||
export default function AssessmentEditor({ courseId, onSaved, onCancel }) {
|
||||
const {
|
||||
createAssessment, updateAssessment,
|
||||
bulkSyncAssessmentQuestions,
|
||||
loading,
|
||||
} = useCourses();
|
||||
|
||||
const [localAssessment, setLocalAssessment] = useState(null);
|
||||
const { user } = useAuth();
|
||||
|
||||
const DRAFT_KEY = `draftAssessment_${courseId}`;
|
||||
const [draftInfo, setDraftInfo] = useState(null); // { savedAt } — non-null while an unsaved local draft exists
|
||||
|
||||
const [initializing, setInitializing] = useState(true);
|
||||
const [questions, setQuestions] = useState([]);
|
||||
const [errors, setErrors] = useState({});
|
||||
const [activeIndex, setActiveIndex] = useState(0);
|
||||
|
||||
const [title, setTitle] = useState("");
|
||||
const [passingScore, setPassingScore] = useState(70);
|
||||
const [timeLimit, setTimeLimit] = useState("");
|
||||
const [isRequired, setIsRequired] = useState(false);
|
||||
const [maxQuestions, setMaxQuestions] = useState("");
|
||||
const [maxAttempts, setMaxAttempts] = useState(3);
|
||||
const [cooldownHours, setCooldownHours] = useState(24);
|
||||
const [shuffleQuestions, setShuffleQuestions] = useState(false);
|
||||
|
||||
// ── Update confirmation dialog ─────────────────────────────────────────────
|
||||
const [confirmOpen, setConfirmOpen] = useState(false);
|
||||
const [inProgressCount, setInProgressCount] = useState(0);
|
||||
const [confirmLoading, setConfirmLoading] = useState(false);
|
||||
const pendingSaveRef = useRef(null); // stores the meta+questions payload until confirmed
|
||||
const initialSnapshot = useRef(null);
|
||||
const originalQuestionIdsRef = useRef([]); // ids loaded from the server — used to detect a full-pool wipe on save
|
||||
|
||||
const questionRefs = useRef([]);
|
||||
const navItemRefs = useRef([]);
|
||||
const navContainerRef = useRef(null);
|
||||
|
||||
// ── Fetch — silently treat 404 as "no assessment yet" (create mode) ─────────
|
||||
useEffect(() => {
|
||||
(async () => {
|
||||
try {
|
||||
const { data } = await api.get(`/admin/courses/${courseId}/assessment`);
|
||||
const result = data?.data?.data ?? null;
|
||||
setLocalAssessment(result);
|
||||
} catch (err) {
|
||||
if (err?.response?.status !== 404) {
|
||||
toast(err?.response?.data?.message ?? "Could not load assessment.");
|
||||
}
|
||||
} finally {
|
||||
setInitializing(false);
|
||||
}
|
||||
})();
|
||||
}, [courseId]);
|
||||
|
||||
// ── Seed ──────────────────────────────────────────────────────────────────
|
||||
useEffect(() => {
|
||||
if (!localAssessment) return;
|
||||
const s = toFormState(localAssessment);
|
||||
setTitle(s.title); setPassingScore(s.passingScore); setTimeLimit(s.timeLimit); setIsRequired(s.isRequired);
|
||||
setMaxQuestions(s.maxQuestions); setMaxAttempts(s.maxAttempts); setCooldownHours(s.cooldownHours);
|
||||
setShuffleQuestions(s.shuffleQuestions); setQuestions(s.questions);
|
||||
initialSnapshot.current = snapAssessment(s);
|
||||
originalQuestionIdsRef.current = s.questions.map((q) => q.question_id).filter(Boolean);
|
||||
}, [localAssessment]);
|
||||
|
||||
// ── Restore an unsaved local draft (survives a reload before Save Assessment) ─
|
||||
useEffect(() => {
|
||||
if (initializing) return;
|
||||
const raw = localStorage.getItem(DRAFT_KEY);
|
||||
if (!raw) return;
|
||||
try {
|
||||
const draft = JSON.parse(raw);
|
||||
if (!draft?.questions) return;
|
||||
setTitle(draft.title ?? "");
|
||||
setPassingScore(draft.passingScore ?? 70);
|
||||
setTimeLimit(draft.timeLimit ?? "");
|
||||
setIsRequired(draft.isRequired ?? false);
|
||||
setMaxQuestions(draft.maxQuestions ?? "");
|
||||
setMaxAttempts(draft.maxAttempts ?? 3);
|
||||
setCooldownHours(draft.cooldownHours ?? 24);
|
||||
setShuffleQuestions(draft.shuffleQuestions ?? false);
|
||||
setQuestions(draft.questions ?? []);
|
||||
setDraftInfo({ savedAt: draft.savedAt });
|
||||
toast("Restored an unsaved draft from this browser.");
|
||||
} catch {
|
||||
localStorage.removeItem(DRAFT_KEY);
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [initializing]);
|
||||
|
||||
// ── Scroll to keep active nav item visible ─────────────────────────────────
|
||||
useEffect(() => {
|
||||
const item = navItemRefs.current[activeIndex];
|
||||
const container = navContainerRef.current;
|
||||
if (!item || !container) return;
|
||||
|
||||
const itemTop = item.offsetTop;
|
||||
const itemBottom = itemTop + item.offsetHeight;
|
||||
const viewTop = container.scrollTop;
|
||||
const viewBottom = viewTop + container.clientHeight;
|
||||
|
||||
if (itemTop < viewTop) {
|
||||
container.scrollTop = itemTop;
|
||||
} else if (itemBottom > viewBottom) {
|
||||
container.scrollTop = itemBottom - container.clientHeight;
|
||||
}
|
||||
}, [activeIndex]);
|
||||
|
||||
// ── IntersectionObserver — highlight nav as user scrolls ──────────────────
|
||||
useEffect(() => {
|
||||
if (!questions.length) return;
|
||||
const observers = [];
|
||||
|
||||
questionRefs.current.forEach((el, i) => {
|
||||
if (!el) return;
|
||||
const observer = new IntersectionObserver(
|
||||
([entry]) => { if (entry.isIntersecting) setActiveIndex(i); },
|
||||
{ rootMargin: "-20% 0px -70% 0px", threshold: 0 }
|
||||
);
|
||||
observer.observe(el);
|
||||
observers.push(observer);
|
||||
});
|
||||
|
||||
return () => observers.forEach((o) => o.disconnect());
|
||||
}, [questions.length]);
|
||||
|
||||
// ── Scroll helper — a generous scroll-margin-top on each question keeps it
|
||||
// clear of the page's sticky navbar/tab-bar above without needing to
|
||||
// measure their heights.
|
||||
const scrollToQuestion = (index) => {
|
||||
questionRefs.current[index]?.scrollIntoView({ behavior: "smooth", block: "start" });
|
||||
};
|
||||
|
||||
// ── Question actions ───────────────────────────────────────────────────────
|
||||
const addQuestion = (type = "multiple_choice") => {
|
||||
setQuestions((prev) => {
|
||||
const next = [...prev, { ...makeQuestion(type), order_index: prev.length }];
|
||||
setTimeout(() => {
|
||||
const idx = next.length - 1;
|
||||
setActiveIndex(idx);
|
||||
scrollToQuestion(idx);
|
||||
}, 50);
|
||||
return next;
|
||||
});
|
||||
};
|
||||
|
||||
const updateQuestion = (index, updated) => {
|
||||
setQuestions((prev) => prev.map((q, i) => i === index ? updated : q));
|
||||
setErrors((prev) => { const e = { ...prev }; delete e[index]; return e; });
|
||||
};
|
||||
|
||||
const removeQuestion = (index) => {
|
||||
setQuestions((prev) => prev.filter((_, i) => i !== index));
|
||||
setActiveIndex((prev) => Math.max(0, prev >= index ? prev - 1 : prev));
|
||||
};
|
||||
|
||||
const moveQuestion = (index, direction) => {
|
||||
setQuestions((prev) => {
|
||||
const next = [...prev];
|
||||
const swapIndex = direction === "up" ? index - 1 : index + 1;
|
||||
if (swapIndex < 0 || swapIndex >= next.length) return prev;
|
||||
[next[index], next[swapIndex]] = [next[swapIndex], next[index]];
|
||||
return next;
|
||||
});
|
||||
const newIndex = direction === "up" ? index - 1 : index + 1;
|
||||
setActiveIndex(newIndex);
|
||||
setTimeout(() => scrollToQuestion(newIndex), 50);
|
||||
};
|
||||
|
||||
const jumpTo = (index) => {
|
||||
setActiveIndex(index);
|
||||
scrollToQuestion(index);
|
||||
};
|
||||
|
||||
const totalPoints = questions.reduce((sum, q) => sum + (q.points ?? 1), 0);
|
||||
|
||||
// ── Dirty tracking ─────────────────────────────────────────────────────────
|
||||
const isDirty = initialSnapshot.current === null
|
||||
? questions.length > 0
|
||||
: snapAssessment({ title, passingScore, timeLimit, isRequired, maxQuestions, maxAttempts, cooldownHours, shuffleQuestions, questions }) !== initialSnapshot.current;
|
||||
|
||||
const { dialog: unsavedChangesDialog } = useUnsavedChangesGuard(isDirty);
|
||||
|
||||
// ── Auto-save unsaved changes to localStorage as a draft ───────────────────
|
||||
useEffect(() => {
|
||||
if (initializing) return;
|
||||
const timer = setTimeout(() => {
|
||||
if (isDirty) {
|
||||
const payload = { title, passingScore, timeLimit, isRequired, maxQuestions, maxAttempts, cooldownHours, shuffleQuestions, questions, savedAt: Date.now() };
|
||||
try {
|
||||
localStorage.setItem(DRAFT_KEY, JSON.stringify(payload));
|
||||
setDraftInfo({ savedAt: payload.savedAt });
|
||||
} catch {
|
||||
// localStorage full/unavailable — draft persistence is best-effort only.
|
||||
}
|
||||
} else {
|
||||
localStorage.removeItem(DRAFT_KEY);
|
||||
setDraftInfo(null);
|
||||
}
|
||||
}, 400);
|
||||
return () => clearTimeout(timer);
|
||||
}, [initializing, isDirty, title, passingScore, timeLimit, isRequired, maxQuestions, maxAttempts, cooldownHours, shuffleQuestions, questions, DRAFT_KEY]);
|
||||
|
||||
// ── Clear draft — discards the local draft and reverts to the last loaded state ─
|
||||
const handleClearDraft = () => {
|
||||
localStorage.removeItem(DRAFT_KEY);
|
||||
setDraftInfo(null);
|
||||
const s = toFormState(localAssessment);
|
||||
setTitle(s.title); setPassingScore(s.passingScore); setTimeLimit(s.timeLimit); setIsRequired(s.isRequired);
|
||||
setMaxQuestions(s.maxQuestions); setMaxAttempts(s.maxAttempts); setCooldownHours(s.cooldownHours);
|
||||
setShuffleQuestions(s.shuffleQuestions); setQuestions(s.questions);
|
||||
setErrors({});
|
||||
toast("Draft cleared.");
|
||||
};
|
||||
|
||||
// ── Save ───────────────────────────────────────────────────────────────────
|
||||
const handleSave = async () => {
|
||||
const errs = validate(questions);
|
||||
if (Object.keys(errs).length) {
|
||||
setErrors(errs);
|
||||
jumpTo(parseInt(Object.keys(errs)[0], 10));
|
||||
return;
|
||||
}
|
||||
|
||||
const assessmentId = localAssessment?.assessment_id;
|
||||
const meta = {
|
||||
title: title || "Course Assessment",
|
||||
passing_score: passingScore,
|
||||
time_limit_minutes: timeLimit ? parseInt(timeLimit) : null,
|
||||
is_required: isRequired,
|
||||
max_questions: maxQuestions ? parseInt(maxQuestions) : null,
|
||||
max_attempts: parseInt(maxAttempts) || 3,
|
||||
cooldown_hours: parseInt(cooldownHours) || 24,
|
||||
shuffle_questions: shuffleQuestions,
|
||||
updatedBy: user?.user_id,
|
||||
createdBy: user?.user_id,
|
||||
};
|
||||
|
||||
// New assessment — no students can be in progress yet, save directly.
|
||||
if (!assessmentId) {
|
||||
await executeSave(null, meta);
|
||||
return;
|
||||
}
|
||||
|
||||
// Existing assessment — fetch in_progress count then show mandatory confirmation.
|
||||
setConfirmLoading(true);
|
||||
try {
|
||||
const { data } = await api.get(`/admin/courses/${courseId}/assessment/${assessmentId}/sessions`);
|
||||
const count = (data?.data?.sessions ?? []).filter((s) => s.status === 'in_progress').length;
|
||||
setInProgressCount(count);
|
||||
} catch {
|
||||
setInProgressCount(0);
|
||||
} finally {
|
||||
setConfirmLoading(false);
|
||||
}
|
||||
pendingSaveRef.current = { assessmentId, meta };
|
||||
setConfirmOpen(true);
|
||||
};
|
||||
|
||||
const executeSave = async (assessmentId, meta) => {
|
||||
let id = assessmentId;
|
||||
if (!id) {
|
||||
const res = await createAssessment(courseId, meta);
|
||||
// res is the raw response body: { status, message, data: { data: assessment } }
|
||||
// (createAssessment() itself unwraps the same object as data?.data?.data to get
|
||||
// the assessment row — this needs the same two levels, not three).
|
||||
id = res?.data?.data?.assessment_id;
|
||||
if (!id) return;
|
||||
setLocalAssessment((prev) => ({ ...prev, assessment_id: id }));
|
||||
} else {
|
||||
await updateAssessment(courseId, id, meta);
|
||||
}
|
||||
|
||||
// A save that keeps none of the previously-loaded question ids would archive the
|
||||
// entire existing pool in one call — could be a deliberate "start over", but is
|
||||
// exactly the signature of a stale/incomplete state bug. Require explicit confirmation.
|
||||
const retainedIds = questions.map((q) => q.question_id).filter(Boolean);
|
||||
const wipesPool = originalQuestionIdsRef.current.length > 0 && retainedIds.length === 0;
|
||||
if (wipesPool && !window.confirm(
|
||||
`This will permanently remove all ${originalQuestionIdsRef.current.length} existing question(s) from this assessment. Continue?`
|
||||
)) {
|
||||
return;
|
||||
}
|
||||
|
||||
await bulkSyncAssessmentQuestions(courseId, id, questions, user?.user_id, wipesPool);
|
||||
|
||||
initialSnapshot.current = snapAssessment({ title, passingScore, timeLimit, isRequired, maxQuestions, maxAttempts, cooldownHours, shuffleQuestions, questions });
|
||||
localStorage.removeItem(DRAFT_KEY);
|
||||
setDraftInfo(null);
|
||||
onSaved?.();
|
||||
};
|
||||
|
||||
const handleConfirmSave = async () => {
|
||||
const { assessmentId, meta } = pendingSaveRef.current ?? {};
|
||||
if (!assessmentId) return;
|
||||
await executeSave(assessmentId, meta);
|
||||
pendingSaveRef.current = null;
|
||||
setConfirmOpen(false);
|
||||
};
|
||||
|
||||
// ── Render ─────────────────────────────────────────────────────────────────
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
|
||||
{/* ── Toolbar ── */}
|
||||
<div className="flex items-center gap-2 rounded-lg border bg-card px-4 py-3">
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="text-sm font-semibold flex items-center gap-1.5">
|
||||
<ClipboardList className="h-4 w-4 text-muted-foreground" />
|
||||
{localAssessment ? "Modify Assessment" : "Create Assessment"}
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{questions.length} question{questions.length !== 1 ? "s" : ""} · {totalPoints} total point{totalPoints !== 1 ? "s" : ""}
|
||||
</p>
|
||||
</div>
|
||||
{draftInfo && (
|
||||
<div className="hidden sm:flex items-center gap-3 text-xs text-muted-foreground">
|
||||
<span className="inline-flex items-center gap-1.5 text-sm">
|
||||
<span className="size-2 rounded-full bg-amber-500" />
|
||||
Draft saved {new Date(draftInfo.savedAt).toLocaleTimeString()}
|
||||
</span>
|
||||
<Button type="button" variant="outline" size="sm" onClick={handleClearDraft}>
|
||||
<Trash2 className="h-3.5 w-3.5" />
|
||||
Clear draft
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
{onCancel && (
|
||||
<Button type="button" variant="ghost" size="sm" onClick={onCancel}>
|
||||
<X className="h-3.5 w-3.5 mr-1" />
|
||||
Cancel
|
||||
</Button>
|
||||
)}
|
||||
<Button onClick={handleSave} disabled={loading || confirmLoading || !isDirty}>
|
||||
{(loading || confirmLoading) ? <Spinner className="h-4 w-4 mr-2" /> : <Save className="h-4 w-4 mr-2" />}
|
||||
Save Assessment
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* ── Split layout ── */}
|
||||
<div className="flex flex-col lg:flex-row gap-6 items-start">
|
||||
|
||||
{/* LEFT — Navigator (desktop only) */}
|
||||
<div className="hidden lg:block w-64 shrink-0">
|
||||
<QuestionNavigator
|
||||
questions={questions}
|
||||
activeIndex={activeIndex}
|
||||
onJump={jumpTo}
|
||||
onMove={moveQuestion}
|
||||
navItemRefs={navItemRefs}
|
||||
navContainerRef={navContainerRef}
|
||||
errors={errors}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* RIGHT — Main content */}
|
||||
<div className="flex-1 min-w-0 w-full">
|
||||
{initializing ? (
|
||||
<div className="flex items-center justify-center py-20">
|
||||
<Spinner className="h-6 w-6" />
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-6 pb-16">
|
||||
|
||||
{/* ── Settings ── */}
|
||||
<div className="rounded-lg border bg-card p-6 space-y-5">
|
||||
<p className="text-sm font-medium">Settings</p>
|
||||
|
||||
<div className="space-y-1.5">
|
||||
<Label>Title</Label>
|
||||
<Input
|
||||
value={title}
|
||||
onChange={(e) => setTitle(e.target.value)}
|
||||
placeholder="Course Assessment"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div className="space-y-1.5">
|
||||
<Label>Passing Score (%)</Label>
|
||||
<Input
|
||||
type="number"
|
||||
min={0}
|
||||
max={100}
|
||||
value={passingScore}
|
||||
onChange={(e) => setPassingScore(parseInt(e.target.value) || 0)}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label>
|
||||
Time Limit{" "}
|
||||
<span className="text-muted-foreground font-normal text-xs">(mins, blank = none)</span>
|
||||
</Label>
|
||||
<Input
|
||||
type="number"
|
||||
min={1}
|
||||
value={timeLimit}
|
||||
onChange={(e) => setTimeLimit(e.target.value)}
|
||||
placeholder="No limit"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label>
|
||||
Max Questions{" "}
|
||||
<span className="text-muted-foreground font-normal text-xs">(blank = show all)</span>
|
||||
</Label>
|
||||
<Input
|
||||
type="number" min={1} max={questions.length || undefined}
|
||||
value={maxQuestions}
|
||||
onChange={(e) => setMaxQuestions(e.target.value)}
|
||||
placeholder={`All (${questions.length})`}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label>
|
||||
Max Failed Attempts{" "}
|
||||
<span className="text-muted-foreground font-normal text-xs">before cooldown</span>
|
||||
</Label>
|
||||
<Input
|
||||
type="number" min={1}
|
||||
value={maxAttempts}
|
||||
onChange={(e) => setMaxAttempts(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label>
|
||||
Cooldown{" "}
|
||||
<span className="text-muted-foreground font-normal text-xs">(hours after max fails)</span>
|
||||
</Label>
|
||||
<Input
|
||||
type="number" min={1}
|
||||
value={cooldownHours}
|
||||
onChange={(e) => setCooldownHours(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1">
|
||||
<div className="flex items-center gap-3">
|
||||
<Checkbox id="assessment_required" checked={isRequired === true} disabled />
|
||||
<Label htmlFor="assessment_required" className="text-muted-foreground">
|
||||
Required to complete course
|
||||
</Label>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground pl-7">
|
||||
Derived from this course's Completion Requirements — add or remove a "Pass the Quiz"
|
||||
requirement on the Requirements step of the course editor to change this.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-3">
|
||||
<Checkbox
|
||||
id="assessment_shuffle"
|
||||
checked={shuffleQuestions === true}
|
||||
onCheckedChange={(val) => setShuffleQuestions(val)}
|
||||
/>
|
||||
<Label htmlFor="assessment_shuffle" className="cursor-pointer">
|
||||
Shuffle question order for each attempt
|
||||
</Label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{maxQuestions && parseInt(maxQuestions) < questions.length && (
|
||||
<p className="text-xs text-muted-foreground bg-muted rounded-md px-3 py-2">
|
||||
Takers will see <strong>{maxQuestions}</strong> randomly selected questions
|
||||
out of <strong>{questions.length}</strong> in the pool.
|
||||
</p>
|
||||
)}
|
||||
|
||||
{/* ── Questions ── */}
|
||||
<div className="space-y-4">
|
||||
{questions.length === 0 ? (
|
||||
<div className="rounded-lg border border-dashed bg-card p-12 flex flex-col items-center gap-3 text-center">
|
||||
<ClipboardList className="h-8 w-8 text-muted-foreground/40" />
|
||||
<p className="text-sm text-muted-foreground">
|
||||
No questions yet. Add one below.
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
questions.map((q, i) => (
|
||||
<div
|
||||
key={q._tempId ?? q.question_id ?? i}
|
||||
ref={(el) => (questionRefs.current[i] = el)}
|
||||
style={{ scrollMarginTop: "calc(var(--navbar-h, 64px) + 180px)" }}
|
||||
onClick={() => setActiveIndex(i)}
|
||||
>
|
||||
<QuestionCard
|
||||
question={q}
|
||||
index={i}
|
||||
onChange={(updated) => updateQuestion(i, updated)}
|
||||
onRemove={() => removeQuestion(i)}
|
||||
error={errors[i]}
|
||||
/>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* ── Add question ── */}
|
||||
<div className="rounded-lg border bg-card p-4">
|
||||
<p className="text-xs text-muted-foreground uppercase tracking-wide font-medium mb-3">
|
||||
Add Question
|
||||
</p>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{[
|
||||
{ type: "multiple_choice", label: "Multiple Choice" },
|
||||
{ type: "multi_select", label: "Multi Select" },
|
||||
{ type: "true_false", label: "True / False" },
|
||||
].map(({ type, label }) => (
|
||||
<Button
|
||||
key={type}
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => addQuestion(type)}
|
||||
>
|
||||
<Plus className="h-3.5 w-3.5 mr-1" />
|
||||
{label}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* ── Update confirmation dialog ── */}
|
||||
{confirmOpen && (
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm p-4">
|
||||
<div className="bg-background rounded-xl border shadow-xl w-full max-w-md p-6 space-y-5">
|
||||
<div className="flex items-start gap-3">
|
||||
<div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-full bg-amber-500/10">
|
||||
<AlertTriangle className="h-5 w-5 text-amber-500" />
|
||||
</div>
|
||||
<div>
|
||||
<h2 className="text-base font-semibold">Save Assessment Changes?</h2>
|
||||
<p className="text-sm text-muted-foreground mt-1">
|
||||
Changes will take effect immediately for all students.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{inProgressCount > 0 && (
|
||||
<div className="rounded-lg border border-amber-500/30 bg-amber-500/5 px-4 py-3 flex items-center gap-2">
|
||||
<AlertTriangle className="h-4 w-4 text-amber-500 shrink-0" />
|
||||
<p className="text-sm text-amber-700 dark:text-amber-400 font-medium">
|
||||
{inProgressCount} student{inProgressCount !== 1 ? "s are" : " is"} currently taking this assessment.
|
||||
Saving now will affect their ongoing session.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<ul className="text-sm text-muted-foreground space-y-1 pl-1">
|
||||
<li>• New passing score applies to future submissions only.</li>
|
||||
<li>• Changing the time limit does not affect already-started sessions.</li>
|
||||
<li>• Adding or removing questions affects any student not yet on that question.</li>
|
||||
</ul>
|
||||
|
||||
<div className="flex gap-3 justify-end pt-1">
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => { setConfirmOpen(false); pendingSaveRef.current = null; }}
|
||||
disabled={loading}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
onClick={handleConfirmSave}
|
||||
disabled={loading}
|
||||
>
|
||||
{loading ? <Spinner className="h-4 w-4 mr-2" /> : null}
|
||||
Save Anyway
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{unsavedChangesDialog}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,470 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import {
|
||||
ClipboardList, NotebookPen,
|
||||
CheckCircle2, Circle, Users, Activity,
|
||||
ChevronDown, ChevronUp,
|
||||
} from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
|
||||
import { useCourses } from "@/contexts/AdminCoursesContext";
|
||||
import api from "@/utils/api.util";
|
||||
import { useDateFormat } from "@/hooks/useDateFormat";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Separator } from "@/components/ui/separator";
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
|
||||
// ─── Helpers ──────────────────────────────────────────────────────────────────
|
||||
|
||||
function InfoRow({ label, children }) {
|
||||
return (
|
||||
<div className="flex flex-col gap-0.5">
|
||||
<span className="text-xs text-muted-foreground uppercase tracking-wide">{label}</span>
|
||||
<span className="text-sm font-medium">{children ?? <span className="italic text-muted-foreground">—</span>}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function SectionCard({ title, children }) {
|
||||
return (
|
||||
<div className="rounded-lg border bg-card p-5 space-y-4">
|
||||
{title && (<><h2 className="text-sm font-semibold">{title}</h2><Separator /></>)}
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function StatCard({ label, value, color = "default" }) {
|
||||
const colors = {
|
||||
default: "bg-card border",
|
||||
green: "bg-green-500/5 border-green-500/20",
|
||||
red: "bg-red-500/5 border-red-500/20",
|
||||
blue: "bg-blue-500/5 border-blue-500/20",
|
||||
amber: "bg-amber-500/5 border-amber-500/20",
|
||||
};
|
||||
return (
|
||||
<div className={`rounded-lg border p-4 text-center ${colors[color]}`}>
|
||||
<p className="text-2xl font-bold">{value ?? 0}</p>
|
||||
<p className="text-xs text-muted-foreground mt-0.5">{label}</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const TYPE_LABELS = {
|
||||
multiple_choice: "Multiple Choice",
|
||||
multi_select: "Multi Select",
|
||||
true_false: "True / False",
|
||||
};
|
||||
|
||||
function QuestionView({ question, index }) {
|
||||
return (
|
||||
<div className="rounded-lg border bg-card p-5 space-y-3">
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<div className="flex items-start gap-2 min-w-0">
|
||||
<span className="flex h-6 w-6 shrink-0 items-center justify-center rounded bg-muted text-xs font-semibold text-muted-foreground mt-0.5">
|
||||
{index + 1}
|
||||
</span>
|
||||
<p className="text-sm font-medium leading-snug">
|
||||
{question.question?.trim() || <span className="italic text-muted-foreground">Untitled</span>}
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-2 shrink-0">
|
||||
<Badge variant="outline" className="text-xs">{TYPE_LABELS[question.type] ?? question.type}</Badge>
|
||||
<span className="text-xs text-muted-foreground whitespace-nowrap">
|
||||
{question.points ?? 1} pt{(question.points ?? 1) !== 1 ? "s" : ""}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
{question.type === "multi_select" && (() => {
|
||||
const cnt = (question.options ?? []).filter((o) => o.is_correct).length;
|
||||
return cnt > 0 ? (
|
||||
<p className="text-xs font-medium text-blue-600 dark:text-blue-400 pl-8">
|
||||
Students select {cnt} answer{cnt !== 1 ? "s" : ""}
|
||||
</p>
|
||||
) : null;
|
||||
})()}
|
||||
<ul className="space-y-1.5 pl-8">
|
||||
{(question.options ?? []).map((opt, oi) => (
|
||||
<li key={opt.option_id ?? oi} className="flex items-center gap-2 text-sm">
|
||||
{opt.is_correct ? (
|
||||
<CheckCircle2 className="h-4 w-4 text-green-500 shrink-0" />
|
||||
) : (
|
||||
<Circle className="h-4 w-4 text-muted-foreground/40 shrink-0" />
|
||||
)}
|
||||
<span className={opt.is_correct ? "font-medium text-green-700 dark:text-green-400" : "text-muted-foreground"}>
|
||||
{opt.text}
|
||||
</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Completions tab ──────────────────────────────────────────────────────────
|
||||
|
||||
function CompletionRow({ row }) {
|
||||
const { fmtDate, fmtDateTime } = useDateFormat();
|
||||
const [open, setOpen] = useState(false);
|
||||
return (
|
||||
<>
|
||||
<tr
|
||||
className="border-b transition-colors hover:bg-muted/40 cursor-pointer"
|
||||
onClick={() => setOpen((v) => !v)}
|
||||
>
|
||||
<td className="px-4 py-3">
|
||||
<div>
|
||||
<div className="flex items-center gap-1.5">
|
||||
<p className="text-sm font-medium">{row.full_name ?? "Unknown User"}</p>
|
||||
{row.deleted && (
|
||||
<Badge variant="outline" className="text-[10px] px-1.5 py-0 h-[18px] leading-none text-muted-foreground border-muted-foreground/30 shrink-0">
|
||||
Deleted
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">{row.email ?? "—"}</p>
|
||||
</div>
|
||||
</td>
|
||||
<td className="px-4 py-3 text-center text-sm">{row.attempt_count}</td>
|
||||
<td className="px-4 py-3 text-center">
|
||||
<span className="text-sm font-semibold">{row.best_score}%</span>
|
||||
</td>
|
||||
<td className="px-4 py-3 text-center">
|
||||
{row.passed ? (
|
||||
<Badge className="bg-green-500/10 text-green-700 dark:text-green-400 border-green-500/20">Passed</Badge>
|
||||
) : (
|
||||
<Badge variant="outline" className="text-red-600 dark:text-red-400 border-red-500/20">Not yet</Badge>
|
||||
)}
|
||||
</td>
|
||||
<td className="px-4 py-3 text-xs text-muted-foreground whitespace-nowrap">
|
||||
{row.latest_at ? fmtDate(row.latest_at) : "—"}
|
||||
</td>
|
||||
<td className="px-4 py-3 text-center">
|
||||
{open ? <ChevronUp className="h-4 w-4 mx-auto text-muted-foreground" /> : <ChevronDown className="h-4 w-4 mx-auto text-muted-foreground" />}
|
||||
</td>
|
||||
</tr>
|
||||
{open && (
|
||||
<tr className="bg-muted/30">
|
||||
<td colSpan={6} className="px-6 py-3">
|
||||
<table className="w-full text-xs">
|
||||
<thead>
|
||||
<tr className="text-muted-foreground border-b">
|
||||
<th className="text-left py-1 font-medium">Attempt</th>
|
||||
<th className="text-center py-1 font-medium">Score</th>
|
||||
<th className="text-center py-1 font-medium">Points</th>
|
||||
<th className="text-center py-1 font-medium">Result</th>
|
||||
<th className="text-left py-1 font-medium">Date</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{(row.attempts ?? []).map((a) => (
|
||||
<tr key={a.attempt_id} className="border-b border-border/50 last:border-0">
|
||||
<td className="py-1.5 text-muted-foreground">#{a.attempt_number}</td>
|
||||
<td className="py-1.5 text-center font-semibold">{a.score}%</td>
|
||||
<td className="py-1.5 text-center text-muted-foreground">{a.earned_points}/{a.total_points}</td>
|
||||
<td className="py-1.5 text-center">
|
||||
{a.passed
|
||||
? <span className="text-green-600 dark:text-green-400 font-medium">Pass</span>
|
||||
: <span className="text-red-500 font-medium">Fail</span>}
|
||||
</td>
|
||||
<td className="py-1.5 text-muted-foreground">{fmtDateTime(a.createdAt)}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</td>
|
||||
</tr>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function CompletionsTab({ completions, loading }) {
|
||||
if (loading) return <div className="space-y-3">{[...Array(3)].map((_, i) => <Skeleton key={i} className="h-12 w-full rounded-lg" />)}</div>;
|
||||
|
||||
if (!completions) return (
|
||||
<div className="rounded-lg border border-dashed bg-card p-12 text-center">
|
||||
<p className="text-sm text-muted-foreground">No data yet.</p>
|
||||
</div>
|
||||
);
|
||||
|
||||
const { summary, completions: rows } = completions;
|
||||
|
||||
return (
|
||||
<div className="space-y-5">
|
||||
<div className="grid grid-cols-2 sm:grid-cols-5 gap-3">
|
||||
<StatCard label="Total Takers" value={summary.total_takers} />
|
||||
<StatCard label="Passed" value={summary.passed_count} color="green" />
|
||||
<StatCard label="Failed" value={summary.failed_count} color="red" />
|
||||
<StatCard label="Pass Rate" value={`${summary.pass_rate}%`} color="blue" />
|
||||
<StatCard label="Avg Score" value={`${summary.avg_score}%`} />
|
||||
</div>
|
||||
|
||||
{rows.length === 0 ? (
|
||||
<div className="rounded-lg border border-dashed bg-card p-10 text-center">
|
||||
<p className="text-sm text-muted-foreground">No one has attempted this assessment yet.</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="rounded-lg border bg-card overflow-hidden">
|
||||
<table className="w-full">
|
||||
<thead className="bg-muted/50 border-b">
|
||||
<tr>
|
||||
<th className="text-left px-4 py-2.5 text-xs font-semibold text-muted-foreground uppercase tracking-wide">Student</th>
|
||||
<th className="text-center px-4 py-2.5 text-xs font-semibold text-muted-foreground uppercase tracking-wide">Attempts</th>
|
||||
<th className="text-center px-4 py-2.5 text-xs font-semibold text-muted-foreground uppercase tracking-wide">Best Score</th>
|
||||
<th className="text-center px-4 py-2.5 text-xs font-semibold text-muted-foreground uppercase tracking-wide">Status</th>
|
||||
<th className="text-left px-4 py-2.5 text-xs font-semibold text-muted-foreground uppercase tracking-wide">Last Attempt</th>
|
||||
<th className="w-8" />
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{rows.map((row) => <CompletionRow key={row.user_id} row={row} />)}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Sessions tab ─────────────────────────────────────────────────────────────
|
||||
|
||||
const SESSION_BADGE = {
|
||||
completed: "bg-green-500/10 text-green-700 dark:text-green-400 border-green-500/20",
|
||||
expired: "bg-red-500/10 text-red-600 dark:text-red-400 border-red-500/20",
|
||||
in_progress: "bg-amber-500/10 text-amber-700 dark:text-amber-400 border-amber-500/20",
|
||||
};
|
||||
|
||||
function fmtDuration(secs) {
|
||||
if (secs == null) return "—";
|
||||
if (secs < 60) return `${secs}s`;
|
||||
const m = Math.floor(secs / 60);
|
||||
const s = secs % 60;
|
||||
return s > 0 ? `${m}m ${s}s` : `${m}m`;
|
||||
}
|
||||
|
||||
function SessionsTab({ sessions, loading }) {
|
||||
const { fmtDateTime } = useDateFormat();
|
||||
if (loading) return <div className="space-y-3">{[...Array(4)].map((_, i) => <Skeleton key={i} className="h-10 w-full rounded-lg" />)}</div>;
|
||||
|
||||
if (!sessions) return (
|
||||
<div className="rounded-lg border border-dashed bg-card p-12 text-center">
|
||||
<p className="text-sm text-muted-foreground">No data yet.</p>
|
||||
</div>
|
||||
);
|
||||
|
||||
const { summary, sessions: rows } = sessions;
|
||||
|
||||
return (
|
||||
<div className="space-y-5">
|
||||
<div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
|
||||
<StatCard label="Total Sessions" value={summary.total} />
|
||||
<StatCard label="Completed" value={summary.completed} color="green" />
|
||||
<StatCard label="Expired" value={summary.expired} color="red" />
|
||||
<StatCard label="In Progress" value={summary.in_progress} color="amber" />
|
||||
</div>
|
||||
|
||||
{rows.length === 0 ? (
|
||||
<div className="rounded-lg border border-dashed bg-card p-10 text-center">
|
||||
<p className="text-sm text-muted-foreground">No sessions recorded yet.</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="rounded-lg border bg-card overflow-hidden">
|
||||
<table className="w-full">
|
||||
<thead className="bg-muted/50 border-b">
|
||||
<tr>
|
||||
<th className="text-left px-4 py-2.5 text-xs font-semibold text-muted-foreground uppercase tracking-wide">Student</th>
|
||||
<th className="text-center px-4 py-2.5 text-xs font-semibold text-muted-foreground uppercase tracking-wide">Status</th>
|
||||
<th className="text-left px-4 py-2.5 text-xs font-semibold text-muted-foreground uppercase tracking-wide">Started</th>
|
||||
<th className="text-left px-4 py-2.5 text-xs font-semibold text-muted-foreground uppercase tracking-wide">Expires At</th>
|
||||
<th className="text-center px-4 py-2.5 text-xs font-semibold text-muted-foreground uppercase tracking-wide">Time Spent</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{rows.map((s) => (
|
||||
<tr key={s.session_id} className="border-b last:border-0 hover:bg-muted/30 transition-colors">
|
||||
<td className="px-4 py-3">
|
||||
<div className="flex items-center gap-1.5">
|
||||
<p className="text-sm font-medium">{s.full_name ?? "Unknown User"}</p>
|
||||
{s.deleted && (
|
||||
<Badge variant="outline" className="text-[10px] px-1.5 py-0 h-[18px] leading-none text-muted-foreground border-muted-foreground/30 shrink-0">
|
||||
Deleted
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">{s.email ?? "—"}</p>
|
||||
</td>
|
||||
<td className="px-4 py-3 text-center">
|
||||
<Badge className={SESSION_BADGE[s.status] ?? ""}>
|
||||
{s.status === 'in_progress' ? 'In Progress' : s.status.charAt(0).toUpperCase() + s.status.slice(1)}
|
||||
</Badge>
|
||||
</td>
|
||||
<td className="px-4 py-3 text-xs text-muted-foreground whitespace-nowrap">
|
||||
{fmtDateTime(s.started_at)}
|
||||
</td>
|
||||
<td className="px-4 py-3 text-xs text-muted-foreground whitespace-nowrap">
|
||||
{s.expires_at ? fmtDateTime(s.expires_at) : "—"}
|
||||
</td>
|
||||
<td className="px-4 py-3 text-center text-sm">{fmtDuration(s.time_spent_seconds)}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function LoadingSkeleton() {
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<Skeleton className="h-32 w-full rounded-lg" />
|
||||
{[...Array(3)].map((_, i) => <Skeleton key={i} className="h-24 w-full rounded-lg" />)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Main ──────────────────────────────────────────────────────────────────────
|
||||
|
||||
const TABS = [
|
||||
{ key: "questions", label: "Questions", icon: ClipboardList },
|
||||
{ key: "completions", label: "Completions", icon: Users },
|
||||
{ key: "sessions", label: "Sessions", icon: Activity },
|
||||
];
|
||||
|
||||
export default function AssessmentOverview({ courseId, onModify }) {
|
||||
const {
|
||||
fetchAssessmentCompletions, fetchAssessmentSessions,
|
||||
completions, sessions,
|
||||
loading,
|
||||
} = useCourses();
|
||||
|
||||
const [localAssessment, setLocalAssessment] = useState(null);
|
||||
const [initializing, setInitializing] = useState(true);
|
||||
const [activeTab, setActiveTab] = useState("questions");
|
||||
|
||||
useEffect(() => {
|
||||
(async () => {
|
||||
setInitializing(true);
|
||||
try {
|
||||
const { data } = await api.get(`/admin/courses/${courseId}/assessment`);
|
||||
setLocalAssessment(data?.data?.data ?? null);
|
||||
} catch (err) {
|
||||
if (err?.response?.status !== 404) {
|
||||
toast(err?.response?.data?.message ?? "Could not load assessment.");
|
||||
}
|
||||
} finally {
|
||||
setInitializing(false);
|
||||
}
|
||||
})();
|
||||
}, [courseId]);
|
||||
|
||||
// Lazy-load completions/sessions the first time each tab is opened
|
||||
useEffect(() => {
|
||||
if (!localAssessment?.assessment_id) return;
|
||||
if (activeTab === "completions") fetchAssessmentCompletions(courseId, localAssessment.assessment_id);
|
||||
if (activeTab === "sessions") fetchAssessmentSessions(courseId, localAssessment.assessment_id);
|
||||
}, [activeTab, localAssessment?.assessment_id]);
|
||||
|
||||
const questions = localAssessment?.questions ?? [];
|
||||
const totalPoints = questions.reduce((sum, q) => sum + (q.points ?? 1), 0);
|
||||
|
||||
return (
|
||||
<div className="space-y-5">
|
||||
|
||||
{/* ── Toolbar ── */}
|
||||
<div className="flex items-center gap-2 rounded-lg border bg-card px-4 py-3">
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="text-sm font-semibold flex items-center gap-1.5">
|
||||
<ClipboardList className="h-4 w-4 text-muted-foreground" />
|
||||
Assessment
|
||||
</p>
|
||||
{localAssessment && (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{questions.length} question{questions.length !== 1 ? "s" : ""} · {totalPoints} total point{totalPoints !== 1 ? "s" : ""}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
{localAssessment && (
|
||||
<Button variant="outline" size="sm" onClick={onModify}>
|
||||
<NotebookPen className="h-4 w-4 mr-2" />
|
||||
Modify Assessment
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* ── Sub-tabs ── */}
|
||||
{localAssessment && (
|
||||
<div className="flex gap-1 border-b">
|
||||
{TABS.map(({ key, label, icon: Icon }) => (
|
||||
<button
|
||||
key={key}
|
||||
onClick={() => setActiveTab(key)}
|
||||
className={`flex items-center gap-1.5 px-4 py-2.5 text-sm font-medium border-b-2 transition-colors
|
||||
${activeTab === key
|
||||
? "border-primary text-primary"
|
||||
: "border-transparent text-muted-foreground hover:text-foreground"}`}
|
||||
>
|
||||
<Icon className="h-3.5 w-3.5" />
|
||||
{label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* ── Content ── */}
|
||||
{initializing || (loading && !localAssessment) ? (
|
||||
<LoadingSkeleton />
|
||||
) : !localAssessment ? (
|
||||
<div className="rounded-lg border border-dashed bg-card p-12 flex flex-col items-center gap-3 text-center">
|
||||
<ClipboardList className="h-8 w-8 text-muted-foreground/40" />
|
||||
<p className="text-sm text-muted-foreground">No assessment has been created for this course yet.</p>
|
||||
<Button size="sm" variant="outline" onClick={onModify}>
|
||||
<NotebookPen className="h-4 w-4 mr-2" />
|
||||
Create Assessment
|
||||
</Button>
|
||||
</div>
|
||||
) : activeTab === "questions" ? (
|
||||
<>
|
||||
<SectionCard title="Settings">
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<InfoRow label="Title">{localAssessment.title || "Course Assessment"}</InfoRow>
|
||||
<InfoRow label="Required">
|
||||
<Badge variant={localAssessment.is_required ? "default" : "secondary"} className="mt-0.5">
|
||||
{localAssessment.is_required ? "Required" : "Optional"}
|
||||
</Badge>
|
||||
</InfoRow>
|
||||
<InfoRow label="Passing Score">{localAssessment.passing_score ?? 70}%</InfoRow>
|
||||
<InfoRow label="Time Limit">
|
||||
{localAssessment.time_limit_minutes ? `${localAssessment.time_limit_minutes} mins` : "No limit"}
|
||||
</InfoRow>
|
||||
<InfoRow label="Questions in Pool">{questions.length}</InfoRow>
|
||||
<InfoRow label="Max Shown per Attempt">
|
||||
{localAssessment.max_questions ? `${localAssessment.max_questions} (random)` : `All (${questions.length})`}
|
||||
</InfoRow>
|
||||
<InfoRow label="Total Points">{totalPoints}</InfoRow>
|
||||
<InfoRow label="Max Failed Attempts">{localAssessment.max_attempts ?? 3}</InfoRow>
|
||||
<InfoRow label="Cooldown After Fails">{localAssessment.cooldown_hours ?? 24}h</InfoRow>
|
||||
</div>
|
||||
</SectionCard>
|
||||
|
||||
<div className="space-y-3">
|
||||
<p className="text-xs font-semibold uppercase tracking-widest text-muted-foreground px-1">Questions</p>
|
||||
{questions.length === 0 ? (
|
||||
<div className="rounded-lg border border-dashed bg-card p-10 flex flex-col items-center gap-2 text-center">
|
||||
<p className="text-sm text-muted-foreground">No questions added yet.</p>
|
||||
</div>
|
||||
) : (
|
||||
questions.map((q, i) => <QuestionView key={q.question_id ?? i} question={q} index={i} />)
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
) : activeTab === "completions" ? (
|
||||
<CompletionsTab completions={completions} loading={loading} />
|
||||
) : (
|
||||
<SessionsTab sessions={sessions} loading={loading} />
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
// modules/admin/components/courses/AttachAchievementDialog.jsx
|
||||
// Pick a single achievement from the global registry — the attach-existing
|
||||
// counterpart to CreateAchievementDialog's create-new flow. A course carries
|
||||
// at most one achievement, so selection behaves like a radio, not a checklist.
|
||||
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { Search, Link2, Trophy, BadgeCheck } from "lucide-react";
|
||||
import * as LucideIcons from "lucide-react";
|
||||
|
||||
import {
|
||||
Dialog, DialogContent, DialogDescription, DialogFooter,
|
||||
DialogHeader, DialogTitle,
|
||||
} from "@/components/ui/dialog";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { ScrollArea } from "@/components/ui/scroll-area";
|
||||
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
|
||||
|
||||
export default function AttachAchievementDialog({ open, onOpenChange, registry = [], selectedKey, onAttach }) {
|
||||
const [query, setQuery] = useState("");
|
||||
const [picked, setPicked] = useState(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
setQuery("");
|
||||
setPicked(selectedKey ?? null);
|
||||
}
|
||||
}, [open, selectedKey]);
|
||||
|
||||
const candidates = useMemo(() => {
|
||||
const q = query.trim().toLowerCase();
|
||||
return registry
|
||||
.filter((a) => a.is_active !== false)
|
||||
.filter((a) => !q || a.label?.toLowerCase().includes(q));
|
||||
}, [registry, query]);
|
||||
|
||||
const handleAttach = () => {
|
||||
if (!picked) return;
|
||||
onAttach(picked);
|
||||
onOpenChange(false);
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="sm:max-w-xl">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<Link2 className="h-4 w-4" /> Attach Achievement
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
Pick one achievement from the registry to award learners who complete this course.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="relative">
|
||||
<Search className="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
|
||||
<Input
|
||||
placeholder="Search achievements..."
|
||||
className="pl-8"
|
||||
value={query}
|
||||
onChange={(e) => setQuery(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<ScrollArea className="h-64 rounded-md border">
|
||||
{candidates.length === 0 ? (
|
||||
<p className="text-sm text-muted-foreground text-center py-10">
|
||||
{query ? "No achievements match your search." : "No achievements in the registry yet."}
|
||||
</p>
|
||||
) : (
|
||||
<RadioGroup value={picked ?? ""} onValueChange={setPicked} className="divide-y gap-0">
|
||||
{candidates.map((a) => {
|
||||
const Icon = LucideIcons[a.icon] ?? Trophy;
|
||||
return (
|
||||
<label
|
||||
key={a.key}
|
||||
htmlFor={`ach-${a.key}`}
|
||||
className="flex items-center gap-3 px-3 py-2.5 hover:bg-muted/60 cursor-pointer"
|
||||
>
|
||||
<RadioGroupItem value={a.key} id={`ach-${a.key}`} />
|
||||
<Icon className="h-4 w-4 text-muted-foreground shrink-0" />
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="text-sm font-medium truncate">{a.label}</p>
|
||||
{a.description && (
|
||||
<p className="text-xs text-muted-foreground truncate">{a.description}</p>
|
||||
)}
|
||||
</div>
|
||||
<Badge variant="outline" className="text-[10px] shrink-0 capitalize gap-1">
|
||||
{a.type === "badge" ? <Trophy className="h-2.5 w-2.5" /> : <BadgeCheck className="h-2.5 w-2.5" />}
|
||||
{a.type}
|
||||
</Badge>
|
||||
</label>
|
||||
);
|
||||
})}
|
||||
</RadioGroup>
|
||||
)}
|
||||
</ScrollArea>
|
||||
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => onOpenChange(false)}>Cancel</Button>
|
||||
<Button onClick={handleAttach} disabled={!picked}>Attach</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { Plus, Trash2, GripVertical, BookOpenCheck, Save, Info } from "lucide-react";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Card, CardContent } from "@/components/ui/card";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger } from "@/components/ui/select";
|
||||
import { Spinner } from "@/components/ui/spinner";
|
||||
import { TYPE_DEFS, DEFAULT_BEHAVIOR_TEXT } from "./completionRequirementTypes";
|
||||
|
||||
function createRequirement(type) {
|
||||
return { _key: crypto.randomUUID(), type, min_percent: 100, button_label: "", is_required: true };
|
||||
}
|
||||
|
||||
/**
|
||||
* Self-contained editor for one entity's CompletionRequirement rows — fetches on mount,
|
||||
* saves via its own button (matches EditCourse.jsx's per-section-save convention, not a
|
||||
* bundled page-level submit). Works for both nested (courseId present) and standalone
|
||||
* library (courseId omitted) entities — fetchFn/syncFn + args resolve that server-side.
|
||||
*/
|
||||
export default function CompletionRequirementBuilder({ entityType, fetchFn, syncFn, args = [] }) {
|
||||
const [items, setItems] = useState([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [dirty, setDirty] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
fetchFn(...args).then((rows) => {
|
||||
if (!active) return;
|
||||
setItems((rows ?? []).map((r) => ({ _key: crypto.randomUUID(), ...r })));
|
||||
setLoading(false);
|
||||
setDirty(false);
|
||||
});
|
||||
return () => { active = false; };
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [...args]);
|
||||
|
||||
const availableTypes = Object.entries(TYPE_DEFS)
|
||||
.filter(([, def]) => def.entityTypes.includes(entityType))
|
||||
.map(([value, def]) => ({ value, ...def }));
|
||||
|
||||
const usedTypes = new Set(items.map((i) => i.type));
|
||||
const addableTypes = availableTypes.filter((t) => !usedTypes.has(t.value));
|
||||
|
||||
const update = (key, patch) => {
|
||||
setItems((prev) => prev.map((i) => (i._key === key ? { ...i, ...patch } : i)));
|
||||
setDirty(true);
|
||||
};
|
||||
const addItem = (type) => {
|
||||
setItems((prev) => [...prev, createRequirement(type)]);
|
||||
setDirty(true);
|
||||
};
|
||||
const removeItem = (key) => {
|
||||
setItems((prev) => prev.filter((i) => i._key !== key));
|
||||
setDirty(true);
|
||||
};
|
||||
|
||||
const handleSave = async () => {
|
||||
setSaving(true);
|
||||
const clean = items.map(({ _key, ...r }) => r);
|
||||
const result = await syncFn(...args, clean);
|
||||
if (result) {
|
||||
setItems(result.map((r) => ({ _key: crypto.randomUUID(), ...r })));
|
||||
setDirty(false);
|
||||
}
|
||||
setSaving(false);
|
||||
};
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="flex items-center justify-center py-8 text-muted-foreground">
|
||||
<Spinner className="size-5" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
{items.length === 0 && (
|
||||
<p className="flex items-start gap-2 text-sm text-muted-foreground py-4 px-3 border border-dashed rounded-lg">
|
||||
<Info className="size-4 shrink-0 mt-0.5" />
|
||||
<span>
|
||||
No completion requirements configured — by default, {DEFAULT_BEHAVIOR_TEXT[entityType]}.
|
||||
Add a requirement below to override this.
|
||||
</span>
|
||||
</p>
|
||||
)}
|
||||
|
||||
{items.map((item, idx) => {
|
||||
const def = TYPE_DEFS[item.type];
|
||||
const Icon = def?.icon ?? BookOpenCheck;
|
||||
return (
|
||||
<Card key={item._key}>
|
||||
<CardContent className="pt-4 pb-4 space-y-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<GripVertical className="h-4 w-4 text-muted-foreground shrink-0" />
|
||||
<Badge variant="outline" className="text-xs gap-1 shrink-0">
|
||||
<Icon className="h-3 w-3" />
|
||||
{idx + 1}
|
||||
</Badge>
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="text-sm font-medium truncate">{def?.label ?? item.type}</p>
|
||||
<p className="text-xs text-muted-foreground truncate">{def?.describe(entityType)}</p>
|
||||
</div>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-8 w-8 shrink-0 text-destructive hover:text-destructive"
|
||||
onClick={() => removeItem(item._key)}
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{item.type === "watch_percent" && (
|
||||
<div className="pl-7 flex items-center gap-2 max-w-48">
|
||||
<Input
|
||||
type="number"
|
||||
min={1}
|
||||
max={100}
|
||||
value={item.min_percent ?? 100}
|
||||
onChange={(e) => update(item._key, { min_percent: Math.min(100, Math.max(1, parseInt(e.target.value) || 1)) })}
|
||||
className="h-8 text-sm"
|
||||
/>
|
||||
<Label className="text-xs text-muted-foreground whitespace-nowrap">% watched required</Label>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{item.type === "manual_complete" && (
|
||||
<div className="pl-7 space-y-1 max-w-64">
|
||||
<Label className="text-xs">Button label (optional)</Label>
|
||||
<Input
|
||||
placeholder='Defaults to "Mark Complete"'
|
||||
value={item.button_label ?? ""}
|
||||
onChange={(e) => update(item._key, { button_label: e.target.value })}
|
||||
className="h-8 text-sm"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
})}
|
||||
|
||||
{addableTypes.length > 0 && (
|
||||
<Select value="" onValueChange={(v) => addItem(v)}>
|
||||
<SelectTrigger className="h-9 w-full text-sm">
|
||||
<span className="flex items-center gap-2 text-muted-foreground">
|
||||
<Plus className="h-4 w-4" />
|
||||
Add Requirement
|
||||
</span>
|
||||
</SelectTrigger>
|
||||
<SelectContent position="popper" sideOffset={4}>
|
||||
{addableTypes.map((t) => (
|
||||
<SelectItem key={t.value} value={t.value}>
|
||||
<span className="flex items-center gap-2">
|
||||
<t.icon className="h-3.5 w-3.5" />
|
||||
{t.label}
|
||||
</span>
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
)}
|
||||
|
||||
<div className="flex justify-end pt-1">
|
||||
<Button type="button" size="sm" className="gap-2" onClick={handleSave} disabled={saving || !dirty}>
|
||||
{saving ? <Spinner className="size-4" /> : <Save className="size-4" />}
|
||||
Save Requirements
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import { useState } from "react";
|
||||
import AssessmentOverview from "./AssessmentOverview";
|
||||
import AssessmentEditor from "./AssessmentEditor";
|
||||
|
||||
export default function CourseAssessmentPanel({ courseId }) {
|
||||
const [mode, setMode] = useState("overview"); // "overview" | "edit"
|
||||
const [overviewKey, setOverviewKey] = useState(0); // bump to force AssessmentOverview to refetch
|
||||
|
||||
const backToOverview = () => {
|
||||
setOverviewKey((k) => k + 1);
|
||||
setMode("overview");
|
||||
};
|
||||
|
||||
if (mode === "edit") {
|
||||
return (
|
||||
<AssessmentEditor
|
||||
courseId={courseId}
|
||||
onSaved={backToOverview}
|
||||
onCancel={backToOverview}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<AssessmentOverview
|
||||
key={overviewKey}
|
||||
courseId={courseId}
|
||||
onModify={() => setMode("edit")}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
const BADGE_GRADIENTS = {
|
||||
// ── Original 12 ──────────────────────────────────────────────────────────────
|
||||
purple: "linear-gradient(145deg, #a855f7cc 0%, #7e22cebf 55%, #3b0764b3 100%)",
|
||||
green: "linear-gradient(145deg, #4ade80cc 0%, #15803dbf 55%, #14532db3 100%)",
|
||||
rose: "linear-gradient(145deg, #fb7185cc 0%, #be123cbf 55%, #4c0519b3 100%)",
|
||||
amber: "linear-gradient(145deg, #fbbf24cc 0%, #d97706bf 55%, #78350fb3 100%)",
|
||||
sky: "linear-gradient(145deg, #38bdf8cc 0%, #0369a1bf 55%, #0c4a6eb3 100%)",
|
||||
indigo: "linear-gradient(145deg, #818cf8cc 0%, #4338cabf 55%, #1e1b4bb3 100%)",
|
||||
teal: "linear-gradient(145deg, #2dd4bfcc 0%, #0f766ebf 55%, #042f2eb3 100%)",
|
||||
orange: "linear-gradient(145deg, #fb923ccc 0%, #c2410cbf 55%, #431407b3 100%)",
|
||||
pink: "linear-gradient(145deg, #f472b6cc 0%, #be185dbf 55%, #500724b3 100%)",
|
||||
cyan: "linear-gradient(145deg, #22d3eecc 0%, #0e7490bf 55%, #083344b3 100%)",
|
||||
lime: "linear-gradient(145deg, #a3e635cc 0%, #4d7c0fbf 55%, #1a2e05b3 100%)",
|
||||
slate: "linear-gradient(145deg, #94a3b8cc 0%, #475569bf 55%, #0f172ab3 100%)",
|
||||
// ── Extended 18 ──────────────────────────────────────────────────────────────
|
||||
red: "linear-gradient(145deg, #f87171cc 0%, #b91c1cbf 55%, #450a0ab3 100%)",
|
||||
yellow: "linear-gradient(145deg, #fde047cc 0%, #a16207bf 55%, #3d1f00b3 100%)",
|
||||
violet: "linear-gradient(145deg, #a78bfacc 0%, #6d28d9bf 55%, #2e1065b3 100%)",
|
||||
fuchsia: "linear-gradient(145deg, #e879f9cc 0%, #a21cafbf 55%, #4a044eb3 100%)",
|
||||
emerald: "linear-gradient(145deg, #34d399cc 0%, #047857bf 55%, #064e3bb3 100%)",
|
||||
blue: "linear-gradient(145deg, #60a5facc 0%, #1d4ed8bf 55%, #1e3a8ab3 100%)",
|
||||
zinc: "linear-gradient(145deg, #a1a1aacc 0%, #3f3f46bf 55%, #18181bb3 100%)",
|
||||
stone: "linear-gradient(145deg, #d6d3d1cc 0%, #57534ebf 55%, #1c1917b3 100%)",
|
||||
brown: "linear-gradient(145deg, #d97706cc 0%, #7c2d12bf 55%, #1c0902b3 100%)",
|
||||
gold: "linear-gradient(145deg, #fcd34dcc 0%, #b45309bf 55%, #451a03b3 100%)",
|
||||
navy: "linear-gradient(145deg, #93c5fdcc 0%, #1e40afbf 55%, #0f172ab3 100%)",
|
||||
forest: "linear-gradient(145deg, #86efaccc 0%, #166534bf 55%, #052e16b3 100%)",
|
||||
wine: "linear-gradient(145deg, #fda4afcc 0%, #9f1239bf 55%, #3b0014b3 100%)",
|
||||
charcoal: "linear-gradient(145deg, #9ca3afcc 0%, #374151bf 55%, #111827b3 100%)",
|
||||
midnight: "linear-gradient(145deg, #818cf8cc 0%, #312e81bf 55%, #0d0c1db3 100%)",
|
||||
lavender: "linear-gradient(145deg, #ddd6fecc 0%, #7c3aedbf 55%, #2e1065b3 100%)",
|
||||
salmon: "linear-gradient(145deg, #fca5a5cc 0%, #e11d48bf 55%, #4c0519b3 100%)",
|
||||
mint: "linear-gradient(145deg, #a7f3d0cc 0%, #059669bf 55%, #022c22b3 100%)",
|
||||
};
|
||||
|
||||
const SOLID_GRADIENTS = {
|
||||
// ── Original 12 ──────────────────────────────────────────────────────────────
|
||||
purple: "linear-gradient(145deg, #a855f7 0%, #7e22ce 55%, #3b0764 100%)",
|
||||
green: "linear-gradient(145deg, #4ade80 0%, #15803d 55%, #14532d 100%)",
|
||||
rose: "linear-gradient(145deg, #fb7185 0%, #be123c 55%, #4c0519 100%)",
|
||||
amber: "linear-gradient(145deg, #fbbf24 0%, #d97706 55%, #78350f 100%)",
|
||||
sky: "linear-gradient(145deg, #38bdf8 0%, #0369a1 55%, #0c4a6e 100%)",
|
||||
indigo: "linear-gradient(145deg, #818cf8 0%, #4338ca 55%, #1e1b4b 100%)",
|
||||
teal: "linear-gradient(145deg, #2dd4bf 0%, #0f766e 55%, #042f2e 100%)",
|
||||
orange: "linear-gradient(145deg, #fb923c 0%, #c2410c 55%, #431407 100%)",
|
||||
pink: "linear-gradient(145deg, #f472b6 0%, #be185d 55%, #500724 100%)",
|
||||
cyan: "linear-gradient(145deg, #22d3ee 0%, #0e7490 55%, #083344 100%)",
|
||||
lime: "linear-gradient(145deg, #a3e635 0%, #4d7c0f 55%, #1a2e05 100%)",
|
||||
slate: "linear-gradient(145deg, #94a3b8 0%, #475569 55%, #0f172a 100%)",
|
||||
// ── Extended 18 ──────────────────────────────────────────────────────────────
|
||||
red: "linear-gradient(145deg, #f87171 0%, #b91c1c 55%, #450a0a 100%)",
|
||||
yellow: "linear-gradient(145deg, #fde047 0%, #a16207 55%, #3d1f00 100%)",
|
||||
violet: "linear-gradient(145deg, #a78bfa 0%, #6d28d9 55%, #2e1065 100%)",
|
||||
fuchsia: "linear-gradient(145deg, #e879f9 0%, #a21caf 55%, #4a044e 100%)",
|
||||
emerald: "linear-gradient(145deg, #34d399 0%, #047857 55%, #064e3b 100%)",
|
||||
blue: "linear-gradient(145deg, #60a5fa 0%, #1d4ed8 55%, #1e3a8a 100%)",
|
||||
zinc: "linear-gradient(145deg, #a1a1aa 0%, #3f3f46 55%, #18181b 100%)",
|
||||
stone: "linear-gradient(145deg, #d6d3d1 0%, #57534e 55%, #1c1917 100%)",
|
||||
brown: "linear-gradient(145deg, #d97706 0%, #7c2d12 55%, #1c0902 100%)",
|
||||
gold: "linear-gradient(145deg, #fcd34d 0%, #b45309 55%, #451a03 100%)",
|
||||
navy: "linear-gradient(145deg, #93c5fd 0%, #1e40af 55%, #0f172a 100%)",
|
||||
forest: "linear-gradient(145deg, #86efac 0%, #166534 55%, #052e16 100%)",
|
||||
wine: "linear-gradient(145deg, #fda4af 0%, #9f1239 55%, #3b0014 100%)",
|
||||
charcoal: "linear-gradient(145deg, #9ca3af 0%, #374151 55%, #111827 100%)",
|
||||
midnight: "linear-gradient(145deg, #818cf8 0%, #312e81 55%, #0d0c1d 100%)",
|
||||
lavender: "linear-gradient(145deg, #ddd6fe 0%, #7c3aed 55%, #2e1065 100%)",
|
||||
salmon: "linear-gradient(145deg, #fca5a5 0%, #e11d48 55%, #4c0519 100%)",
|
||||
mint: "linear-gradient(145deg, #a7f3d0 0%, #059669 55%, #022c22 100%)",
|
||||
};
|
||||
|
||||
export default function CourseBadge({ title = "Course Title", level, color = "purple", imageUrl, mini = false }) {
|
||||
const levelLabel = level
|
||||
? `${level.charAt(0).toUpperCase()}${level.slice(1)} Level`
|
||||
: null;
|
||||
|
||||
// ── Mini variant: just the gradient + logo mark, no text/line ──────────────
|
||||
if (mini) {
|
||||
return (
|
||||
<div className="relative w-12 h-12 rounded-xl overflow-hidden flex-shrink-0 select-none shadow-md">
|
||||
{imageUrl ? (
|
||||
<>
|
||||
<div
|
||||
className="absolute inset-0"
|
||||
style={{
|
||||
backgroundImage: `url(${imageUrl})`,
|
||||
backgroundSize: "cover",
|
||||
backgroundPosition: "center",
|
||||
}}
|
||||
/>
|
||||
<div
|
||||
className="absolute inset-0"
|
||||
style={{ background: BADGE_GRADIENTS[color] ?? BADGE_GRADIENTS.purple }}
|
||||
/>
|
||||
</>
|
||||
) : (
|
||||
<div
|
||||
className="absolute inset-0"
|
||||
style={{ background: SOLID_GRADIENTS[color] ?? SOLID_GRADIENTS.purple }}
|
||||
/>
|
||||
)}
|
||||
{/* HIDE OUR LOGO */}
|
||||
{/* <div className="relative h-full flex items-center justify-center">
|
||||
<img src="/philpro-white-single.png" alt="Philpro" className="h-5 w-5 object-contain drop-shadow" />
|
||||
</div> */}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="relative w-44 h-48 rounded-2xl overflow-hidden flex-shrink-0 select-none shadow-lg">
|
||||
|
||||
{/* ── Layer 1: Background — image when set, solid gradient otherwise ── */}
|
||||
{imageUrl ? (
|
||||
<div
|
||||
className="absolute inset-0"
|
||||
style={{
|
||||
backgroundImage: `url(${imageUrl})`,
|
||||
backgroundSize: "cover",
|
||||
backgroundPosition: "center",
|
||||
}}
|
||||
/>
|
||||
) : (
|
||||
<div
|
||||
className="absolute inset-0"
|
||||
style={{ background: SOLID_GRADIENTS[color] ?? SOLID_GRADIENTS.purple }}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* ── Layer 2: Gradient colour overlay on top of the image ── */}
|
||||
{imageUrl && (
|
||||
<div
|
||||
className="absolute inset-0"
|
||||
style={{ background: BADGE_GRADIENTS[color] ?? BADGE_GRADIENTS.purple }}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* ── Layer 3: Soft glow in the upper-right corner (always present) ── */}
|
||||
<div
|
||||
className="absolute -top-6 -right-6 w-28 h-28 rounded-full pointer-events-none"
|
||||
style={{
|
||||
background: "radial-gradient(circle, rgba(255,255,255,0.15), transparent 70%)",
|
||||
}}
|
||||
/>
|
||||
|
||||
{/* ── Layer 4: Content ── */}
|
||||
<div className="relative flex flex-col justify-between h-full p-3.5">
|
||||
<div className="flex-1 flex flex-col justify-center gap-1.5 pr-2">
|
||||
<p className="text-white font-bold text-sm leading-snug line-clamp-4 drop-shadow">
|
||||
{title}
|
||||
</p>
|
||||
{levelLabel && (
|
||||
<p className="text-white/60 text-[9.5px] font-semibold uppercase tracking-widest drop-shadow">
|
||||
{levelLabel}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<div className="border-t border-white/20 mb-2" />
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<img
|
||||
src="/philpro-white-single.png"
|
||||
alt="Philpro"
|
||||
className="h-5 object-contain drop-shadow"
|
||||
/>
|
||||
<span className="text-white/75 text-[8.5px] font-bold uppercase tracking-[0.12em] text-right leading-tight drop-shadow">
|
||||
Course<br />Completion
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
import { useState, useEffect, useCallback } from "react";
|
||||
import { UserPlus, Check, ChevronsUpDown, Loader2 } from "lucide-react";
|
||||
import api from "@/utils/api.util";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Checkbox } from "@/components/ui/checkbox";
|
||||
import {
|
||||
Popover,
|
||||
PopoverContent,
|
||||
PopoverTrigger,
|
||||
} from "@/components/ui/popover";
|
||||
import {
|
||||
Command,
|
||||
CommandEmpty,
|
||||
CommandGroup,
|
||||
CommandInput,
|
||||
CommandItem,
|
||||
CommandList,
|
||||
CommandSeparator,
|
||||
} from "@/components/ui/command";
|
||||
|
||||
const ROLE_COLORS = {
|
||||
admin: "bg-red-100 text-red-700 border-red-200",
|
||||
staff: "bg-green-100 text-green-700 border-green-200",
|
||||
};
|
||||
|
||||
function getFullName(u) {
|
||||
return u?.personal_info?.name?.full_name?.trim() || u?.email || "Unknown";
|
||||
}
|
||||
|
||||
/**
|
||||
* Props:
|
||||
* added — current instructor list [{ user_id, display_name, ... }]
|
||||
* onAdd(inst) — called with { user_id, display_name } to add one instructor
|
||||
* onToggleLinked(user_id) — remove a linked user by their user_id
|
||||
*/
|
||||
export default function CourseInstructorPicker({ added = [], onAdd, onToggleLinked }) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const [users, setUsers] = useState([]);
|
||||
const [loadingUsers, setLoadingUsers] = useState(false);
|
||||
const [externalName, setExternalName] = useState("");
|
||||
|
||||
const linkedIds = new Set(added.filter(i => i.user_id).map(i => String(i.user_id)));
|
||||
|
||||
const loadUsers = useCallback(async () => {
|
||||
if (users.length) return;
|
||||
setLoadingUsers(true);
|
||||
try {
|
||||
const { data } = await api.get("/admin/users", {
|
||||
params: { limit: 200 },
|
||||
});
|
||||
const rows = data?.data?.data ?? [];
|
||||
setUsers(rows.filter(u => u.acc_type === "staff" || u.acc_type === "admin"));
|
||||
} catch {
|
||||
// silently ignore — user can still add external
|
||||
} finally {
|
||||
setLoadingUsers(false);
|
||||
}
|
||||
}, [users.length]);
|
||||
|
||||
useEffect(() => {
|
||||
if (open) loadUsers();
|
||||
}, [open, loadUsers]);
|
||||
|
||||
const toggleUser = (u) => {
|
||||
const uid = String(u.user_id);
|
||||
if (linkedIds.has(uid)) {
|
||||
onToggleLinked(u.user_id);
|
||||
} else {
|
||||
onAdd({ user_id: u.user_id, display_name: getFullName(u) });
|
||||
}
|
||||
};
|
||||
|
||||
const addExternal = () => {
|
||||
const name = externalName.trim();
|
||||
if (!name) return;
|
||||
onAdd({ user_id: null, display_name: name });
|
||||
setExternalName("");
|
||||
};
|
||||
|
||||
return (
|
||||
<Popover open={open} onOpenChange={setOpen}>
|
||||
<PopoverTrigger asChild className="w-full">
|
||||
<Button type="button" variant="outline" size="sm" className="w-full justify-between">
|
||||
<span className="flex items-center gap-1.5">
|
||||
<UserPlus className="h-3.5 w-3.5" />
|
||||
Add Instructor
|
||||
</span>
|
||||
<ChevronsUpDown className="h-3 w-3 text-muted-foreground" />
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
|
||||
<PopoverContent className="w-[var(--radix-popover-trigger-width)] p-0" align="start">
|
||||
<Command>
|
||||
<CommandInput placeholder="Search by name or email…" />
|
||||
<CommandList>
|
||||
|
||||
{/* ── Staff / Admin accounts ── */}
|
||||
<CommandGroup heading="Staff & Admin Accounts">
|
||||
{loadingUsers && (
|
||||
<CommandItem disabled>
|
||||
<Loader2 className="h-3.5 w-3.5 mr-2 animate-spin" />
|
||||
Loading users…
|
||||
</CommandItem>
|
||||
)}
|
||||
{!loadingUsers && users.length === 0 && (
|
||||
<CommandEmpty>No staff or admin accounts found.</CommandEmpty>
|
||||
)}
|
||||
{users.map((u) => {
|
||||
const uid = String(u.user_id);
|
||||
const checked = linkedIds.has(uid);
|
||||
const name = getFullName(u);
|
||||
return (
|
||||
<CommandItem
|
||||
key={uid}
|
||||
value={`${name} ${u.email}`}
|
||||
onSelect={() => toggleUser(u)}
|
||||
className="gap-2"
|
||||
>
|
||||
<Checkbox checked={checked} className="pointer-events-none" />
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="text-sm truncate">{name}</p>
|
||||
<p className="text-xs text-muted-foreground truncate">{u.email}</p>
|
||||
</div>
|
||||
<Badge
|
||||
variant="outline"
|
||||
className={`text-[10px] shrink-0 ${ROLE_COLORS[u.acc_type] ?? ""}`}
|
||||
>
|
||||
{u.acc_type}
|
||||
</Badge>
|
||||
{checked && <Check className="h-3.5 w-3.5 text-primary shrink-0" />}
|
||||
</CommandItem>
|
||||
);
|
||||
})}
|
||||
</CommandGroup>
|
||||
|
||||
<CommandSeparator />
|
||||
|
||||
{/* ── External (no account) ── */}
|
||||
<CommandGroup heading="External (no account)">
|
||||
<div className="px-2 py-1.5 flex gap-2">
|
||||
<Input
|
||||
placeholder="Display name"
|
||||
value={externalName}
|
||||
onChange={(e) => setExternalName(e.target.value)}
|
||||
onKeyDown={(e) => e.key === "Enter" && (e.preventDefault(), addExternal())}
|
||||
className="h-8 text-sm"
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
className="h-8 px-3 shrink-0"
|
||||
disabled={!externalName.trim()}
|
||||
onClick={addExternal}
|
||||
>
|
||||
Add
|
||||
</Button>
|
||||
</div>
|
||||
</CommandGroup>
|
||||
|
||||
</CommandList>
|
||||
</Command>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,217 @@
|
||||
import { useState } from 'react';
|
||||
import { Plus, Trash2, GripVertical, ChevronsUpDown, BookOpen, Layers, FileText, Link2, Unlink } from 'lucide-react';
|
||||
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
|
||||
import { Command, CommandInput, CommandList, CommandEmpty, CommandGroup, CommandItem } from '@/components/ui/command';
|
||||
|
||||
// ─── Prerequisite type config ──────────────────────────────────────────────────
|
||||
// idKey is the numeric FK field each flat list carries (course_id/unit_id/
|
||||
// lesson_id) — CoursePrerequisite.ref_id is a BIGINT FK, not a uuid, so the
|
||||
// picker must select on the numeric id even though the list is keyed/searched
|
||||
// by uuid for React purposes.
|
||||
const REF_TYPES = [
|
||||
{ value: 'course', label: 'Course', icon: BookOpen, idKey: 'course_id' },
|
||||
{ value: 'unit', label: 'Unit', icon: Layers, idKey: 'unit_id' },
|
||||
{ value: 'lesson', label: 'Lesson', icon: FileText, idKey: 'lesson_id' },
|
||||
];
|
||||
const TYPE_MAP = Object.fromEntries(REF_TYPES.map((t) => [t.value, t]));
|
||||
|
||||
// ─── Course binding indicator (units/lessons may sit under 0..N courses) ──────
|
||||
function BindingLine({ courses = [] }) {
|
||||
if (!courses.length) {
|
||||
return (
|
||||
<span className="flex items-center gap-1 text-xs italic text-muted-foreground truncate">
|
||||
<Unlink className="size-3 shrink-0" />
|
||||
Standalone
|
||||
</span>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<span className="flex items-center gap-1 text-xs text-muted-foreground truncate">
|
||||
<Link2 className="size-3 shrink-0" />
|
||||
<span className="truncate">{courses.map((c) => c.title).join(', ')}</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Custom content picker — own Dialog rather than an anchored Popover ───────
|
||||
function ContentPicker({ value, options, idKey, placeholder = 'Select…', dialogTitle, onSelect, renderTrigger, renderItem }) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const selected = options.find((o) => String(o[idKey]) === String(value));
|
||||
|
||||
const searchValue = (o) => {
|
||||
const courseNames = (o.courses ?? []).map((c) => c.title).join(' ');
|
||||
return `${o.title ?? ''} ${courseNames}`.trim() || String(o[idKey]);
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
role="combobox"
|
||||
aria-expanded={open}
|
||||
className="h-auto min-h-8 w-full justify-between text-sm font-normal py-1.5 px-3"
|
||||
onClick={() => setOpen(true)}
|
||||
>
|
||||
{selected
|
||||
? renderTrigger(selected)
|
||||
: <span className="text-muted-foreground">{placeholder}</span>}
|
||||
<ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
|
||||
</Button>
|
||||
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogContent className="top-[15%] translate-y-0 flex flex-col max-h-[70vh] overflow-hidden rounded-xl! p-0 gap-0 sm:max-w-md">
|
||||
<DialogHeader className="px-4 pt-4 pb-3 border-b pr-10">
|
||||
<DialogTitle className="text-sm">{dialogTitle ?? placeholder}</DialogTitle>
|
||||
</DialogHeader>
|
||||
<Command className="flex-1 min-h-0 rounded-none! bg-transparent p-0" loop>
|
||||
<CommandInput placeholder="Search…" />
|
||||
<CommandList className="max-h-[50vh]">
|
||||
<CommandEmpty>No results found.</CommandEmpty>
|
||||
<CommandGroup>
|
||||
{options.map((o) => (
|
||||
<CommandItem
|
||||
key={o[idKey]}
|
||||
value={searchValue(o)}
|
||||
onSelect={() => { onSelect(o); setOpen(false); }}
|
||||
className="p-0"
|
||||
>
|
||||
{renderItem(o)}
|
||||
</CommandItem>
|
||||
))}
|
||||
</CommandGroup>
|
||||
</CommandList>
|
||||
</Command>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function createPrereq(type = 'course') {
|
||||
return { _key: crypto.randomUUID(), ref_type: type, ref_id: '', title: '' };
|
||||
}
|
||||
|
||||
// ─── CoursePrerequisiteBuilder ─────────────────────────────────────────────────
|
||||
// value: [{ prereq_id?, ref_type, ref_id, title? }]
|
||||
export default function CoursePrerequisiteBuilder({ value = [], onChange, courses = [], units = [], lessons = [], excludeCourseId }) {
|
||||
const [items, setItems] = useState(
|
||||
value.length > 0
|
||||
? value.map((v) => ({ _key: crypto.randomUUID(), ...v }))
|
||||
: []
|
||||
);
|
||||
|
||||
const filteredCourses = courses.filter((c) => String(c.course_id) !== String(excludeCourseId));
|
||||
const optionsFor = { course: filteredCourses, unit: units, lesson: lessons };
|
||||
|
||||
const emit = (next) => {
|
||||
setItems(next);
|
||||
onChange?.(next.map(({ _key, ...r }) => r));
|
||||
};
|
||||
|
||||
const addItem = () => emit([...items, createPrereq('course')]);
|
||||
const removeItem = (key) => emit(items.filter((i) => i._key !== key));
|
||||
const updateItem = (key, patch) =>
|
||||
emit(items.map((i) => (i._key === key ? { ...i, ...patch } : i)));
|
||||
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
{items.length === 0 && (
|
||||
<p className="text-sm text-muted-foreground text-center py-6 border border-dashed rounded-lg">
|
||||
No prerequisites added. Learners can start this course freely.
|
||||
</p>
|
||||
)}
|
||||
|
||||
{items.map((item, idx) => {
|
||||
const typeDef = TYPE_MAP[item.ref_type];
|
||||
const Icon = typeDef?.icon ?? BookOpen;
|
||||
const options = optionsFor[item.ref_type] ?? [];
|
||||
|
||||
return (
|
||||
<Card key={item._key}>
|
||||
<CardContent className="pt-4 pb-4 space-y-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<GripVertical className="h-4 w-4 text-muted-foreground shrink-0" />
|
||||
<Badge variant="outline" className="text-xs gap-1 shrink-0">
|
||||
<Icon className="h-3 w-3" />
|
||||
{idx + 1}
|
||||
</Badge>
|
||||
|
||||
<Select
|
||||
value={item.ref_type}
|
||||
onValueChange={(v) => updateItem(item._key, { ref_type: v, ref_id: '', title: '' })}
|
||||
>
|
||||
<SelectTrigger className="h-8 text-sm w-32 shrink-0">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{REF_TYPES.map((t) => (
|
||||
<SelectItem key={t.value} value={t.value}>
|
||||
<span className="flex items-center gap-2">
|
||||
<t.icon className="h-3.5 w-3.5" />
|
||||
{t.label}
|
||||
</span>
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
|
||||
<div className="flex-1 min-w-0">
|
||||
<ContentPicker
|
||||
value={item.ref_id}
|
||||
options={options}
|
||||
idKey={typeDef.idKey}
|
||||
placeholder={`Select a ${typeDef.label.toLowerCase()}`}
|
||||
dialogTitle={`Select a ${typeDef.label.toLowerCase()}`}
|
||||
onSelect={(o) => updateItem(item._key, { ref_id: o[typeDef.idKey], title: o.title })}
|
||||
renderTrigger={(o) => (
|
||||
<div className="flex items-center gap-2 min-w-0 flex-1">
|
||||
{item.ref_type !== 'course' && (
|
||||
<div className="flex flex-col items-start flex-1 min-w-0">
|
||||
<BindingLine courses={o.courses} />
|
||||
<span className="text-sm leading-tight truncate">{o.title}</span>
|
||||
</div>
|
||||
)}
|
||||
{item.ref_type === 'course' && (
|
||||
<span className="flex-1 truncate text-sm">{o.title}</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
renderItem={(o) => (
|
||||
<div className="flex items-center gap-2 px-3 py-2 w-full">
|
||||
<div className="flex flex-col flex-1 min-w-0">
|
||||
<span className="text-sm leading-tight truncate">{o.title}</span>
|
||||
{item.ref_type !== 'course' && <BindingLine courses={o.courses} />}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-8 w-8 shrink-0 text-destructive hover:text-destructive"
|
||||
onClick={() => removeItem(item._key)}
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
})}
|
||||
|
||||
<Button type="button" variant="outline" size="sm" className="w-full gap-2" onClick={addItem}>
|
||||
<Plus className="h-4 w-4" />
|
||||
Add Prerequisite
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,378 @@
|
||||
import { useEffect, useState, useMemo } from 'react';
|
||||
import {
|
||||
CheckCircle2, Circle, BookOpen, Users, Search, RefreshCcw, AlertTriangle
|
||||
} from 'lucide-react';
|
||||
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import { Separator } from '@/components/ui/separator';
|
||||
import { ScrollArea } from '@/components/ui/scroll-area';
|
||||
import {
|
||||
Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter, DialogClose,
|
||||
} from '@/components/ui/dialog';
|
||||
import { TablePagination } from '@/components/generic/Table/TablePagination';
|
||||
import { useAdminCourseReadingProgress } from '@/contexts/AdminCourseReadingProgressContext';
|
||||
import { useDateFormat } from '@/hooks/useDateFormat';
|
||||
import { streamUrl } from '@/utils/media.util';
|
||||
|
||||
// ─── Helpers ──────────────────────────────────────────────────────────────────
|
||||
|
||||
function StatusBadge({ status }) {
|
||||
if (!status) return <Badge variant="outline" className="text-muted-foreground text-xs">Not started</Badge>;
|
||||
return status === 'completed'
|
||||
? <Badge variant="outline" className="text-emerald-600 border-emerald-400 text-xs">Completed</Badge>
|
||||
: <Badge><RefreshCcw />In Progress</Badge>;
|
||||
}
|
||||
|
||||
function ProgressBar({ value, total, className = '' }) {
|
||||
const pct = total > 0 ? Math.round((value / total) * 100) : 0;
|
||||
return (
|
||||
<div className={`flex items-center gap-2 ${className}`}>
|
||||
<div className="flex-1 h-1.5 rounded-full bg-muted overflow-hidden">
|
||||
<div
|
||||
className="h-full bg-emerald-500 transition-all duration-300"
|
||||
style={{ width: `${pct}%` }}
|
||||
/>
|
||||
</div>
|
||||
<span className="text-xs text-muted-foreground tabular-nums whitespace-nowrap">
|
||||
{value} / {total}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Only relevant once reading is fully done but the course still isn't 'completed' —
|
||||
// i.e. a still-unpassed unit quiz and/or course assessment is what's blocking it.
|
||||
function PendingNotice({ entry }) {
|
||||
const readingDone = entry.lessons_total > 0 && entry.lessons_completed === entry.lessons_total;
|
||||
if (!readingDone || entry.course_status === 'completed') return null;
|
||||
if (!entry.quizzes_pending && !entry.assessment_pending) return null;
|
||||
|
||||
const parts = [];
|
||||
if (entry.quizzes_pending > 0) {
|
||||
parts.push(`${entry.quizzes_pending} quiz${entry.quizzes_pending === 1 ? '' : 'zes'} needed`);
|
||||
}
|
||||
if (entry.assessment_pending) parts.push('Assessment needed');
|
||||
|
||||
return (
|
||||
<p className="flex items-center gap-1.5 text-xs text-amber-700 dark:text-amber-400">
|
||||
<AlertTriangle className="size-3.5 shrink-0" />
|
||||
{parts.join(' · ')}
|
||||
</p>
|
||||
);
|
||||
}
|
||||
|
||||
function UserAvatar({ name, email, avatarUrl }) {
|
||||
const initials = name
|
||||
? name.split(' ').map((n) => n[0]).slice(0, 2).join('').toUpperCase()
|
||||
: (email?.[0] ?? '?').toUpperCase();
|
||||
return (
|
||||
<Avatar className="size-9 shrink-0">
|
||||
<AvatarImage src={avatarUrl ?? undefined} alt={name ?? email} />
|
||||
<AvatarFallback className="text-xs font-semibold bg-secondary text-secondary-foreground">
|
||||
{initials}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Dialog: full breakdown for one user ─────────────────────────────────────
|
||||
|
||||
function UserDetailDialog({ open, onOpenChange, entry, courseId }) {
|
||||
const { detailCache, detailLoading, fetchUserReadingProgress } = useAdminCourseReadingProgress();
|
||||
const { fmtDate, fmtDateShort } = useDateFormat();
|
||||
const breakdown = entry ? detailCache[entry.user_id] : null;
|
||||
|
||||
useEffect(() => {
|
||||
if (open && entry && !breakdown) {
|
||||
fetchUserReadingProgress(courseId, entry.user_id);
|
||||
}
|
||||
}, [open, entry]);
|
||||
|
||||
const lastSeen = entry?.last_accessed_at ? fmtDate(entry.last_accessed_at) : '—';
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="sm:max-w-lg">
|
||||
<DialogHeader>
|
||||
<div className="flex items-center gap-3">
|
||||
{entry && <UserAvatar name={entry.user.full_name} email={entry.user.email} avatarUrl={streamUrl(entry.user.avatar_stream_token)} />}
|
||||
<div className="min-w-0">
|
||||
<DialogTitle className="truncate">
|
||||
{entry?.user.full_name ?? <span className="italic text-muted-foreground">No name</span>}
|
||||
</DialogTitle>
|
||||
<DialogDescription className="truncate">{entry?.user.email}</DialogDescription>
|
||||
</div>
|
||||
</div>
|
||||
</DialogHeader>
|
||||
|
||||
{/* ── Meta strip ── */}
|
||||
{entry && (
|
||||
<div className="flex items-center gap-3 flex-wrap">
|
||||
<StatusBadge status={entry.course_status} />
|
||||
<span className="text-xs">Last seen {lastSeen}</span>
|
||||
<span className="text-xs text-muted-foreground ml-auto">
|
||||
{entry.lessons_completed} / {entry.lessons_total} lessons
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{entry && <PendingNotice entry={entry} />}
|
||||
|
||||
{/* ── Progress bar ── */}
|
||||
{entry && (
|
||||
<ProgressBar value={entry.lessons_completed} total={entry.lessons_total} />
|
||||
)}
|
||||
|
||||
<Separator />
|
||||
|
||||
{/* ── Unit / lesson breakdown — fills remaining height and scrolls ── */}
|
||||
<ScrollArea className="max-h-[50vh] pr-2">
|
||||
{detailLoading && !breakdown ? (
|
||||
<div className="space-y-3 py-1">
|
||||
{[...Array(4)].map((_, i) => (
|
||||
<div key={i} className="space-y-1.5">
|
||||
<Skeleton className="h-4 w-48" />
|
||||
<Skeleton className="h-3 w-36 ml-5" />
|
||||
<Skeleton className="h-3 w-40 ml-5" />
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : breakdown?.length ? (
|
||||
<div className="space-y-4 py-1">
|
||||
{breakdown.map((unit, ui) => (
|
||||
<div key={unit.unit_id} className="space-y-2">
|
||||
{/* Unit header */}
|
||||
<div className="flex items-center gap-2">
|
||||
{unit.status === 'completed'
|
||||
? <CheckCircle2 className="size-4 text-emerald-500 shrink-0" />
|
||||
: unit.status === 'in_progress'
|
||||
? <Circle className="size-4 text-amber-400 shrink-0" />
|
||||
: <Circle className="size-4 text-muted-foreground/30 shrink-0" />
|
||||
}
|
||||
<span className="text-sm font-semibold truncate flex-1">
|
||||
Unit {ui + 1}: {unit.title}
|
||||
</span>
|
||||
{unit.status && <StatusBadge status={unit.status} />}
|
||||
</div>
|
||||
|
||||
{/* Lesson rows */}
|
||||
<div className="ml-6 space-y-1.5 border-l pl-3">
|
||||
{unit.lessons.map((lesson) => (
|
||||
<div key={lesson.lesson_id} className="flex items-center gap-2">
|
||||
{lesson.status === 'completed'
|
||||
? <CheckCircle2 className="size-3 text-emerald-500 shrink-0" />
|
||||
: lesson.status === 'in_progress'
|
||||
? <Circle className="size-3 text-amber-400 shrink-0" />
|
||||
: <Circle className="size-3 text-muted-foreground/25 shrink-0" />
|
||||
}
|
||||
<span className={`text-xs truncate flex-1 ${lesson.status ? 'text-foreground' : 'text-muted-foreground'}`}>
|
||||
{lesson.title}
|
||||
</span>
|
||||
{lesson.status === 'completed' && lesson.completed_at && (
|
||||
<span className="text-xs text-muted-foreground whitespace-nowrap shrink-0">
|
||||
{fmtDateShort(lesson.completed_at)}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<p className="text-sm text-muted-foreground py-4 text-center">No lesson data available.</p>
|
||||
)}
|
||||
</ScrollArea>
|
||||
|
||||
<DialogFooter showCloseButton>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
// ─── User summary card ────────────────────────────────────────────────────────
|
||||
|
||||
function UserCard({ entry, onOpen }) {
|
||||
const { fmtDate } = useDateFormat();
|
||||
const lastSeen = entry.last_accessed_at ? fmtDate(entry.last_accessed_at) : '—';
|
||||
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onOpen(entry)}
|
||||
className="bg-background w-full text-left border rounded-lg p-4 flex items-center gap-3 hover:bg-accent/10 transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||||
>
|
||||
<UserAvatar name={entry.user.full_name} email={entry.user.email} avatarUrl={streamUrl(entry.user.avatar_stream_token)} />
|
||||
|
||||
<div className="flex-1 min-w-0 space-y-1">
|
||||
<div className="flex items-center gap-2 min-w-0">
|
||||
<span className="text-sm font-medium truncate flex-1">
|
||||
{entry.user.full_name ?? <span className="italic text-muted-foreground">No name</span>}
|
||||
</span>
|
||||
<StatusBadge status={entry.course_status} />
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground truncate">{entry.user.email}</p>
|
||||
<PendingNotice entry={entry} />
|
||||
<ProgressBar value={entry.lessons_completed} total={entry.lessons_total} />
|
||||
<p className="text-xs">Last seen {lastSeen}</p>
|
||||
</div>
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Main component ───────────────────────────────────────────────────────────
|
||||
|
||||
export default function CourseReadingProgressList({ courseId }) {
|
||||
const { progressList, listLoading, fetchCourseReadingProgress } = useAdminCourseReadingProgress();
|
||||
|
||||
const [searchInput, setSearchInput] = useState('');
|
||||
const [query, setQuery] = useState('');
|
||||
const [page, setPage] = useState(1);
|
||||
const [pageSize, setPageSize] = useState(10);
|
||||
const [dialogEntry, setDialogEntry] = useState(null);
|
||||
|
||||
useEffect(() => {
|
||||
fetchCourseReadingProgress(courseId);
|
||||
}, [courseId]);
|
||||
|
||||
const handleSearchSubmit = (e) => {
|
||||
e.preventDefault();
|
||||
setQuery(searchInput.trim());
|
||||
setPage(1);
|
||||
};
|
||||
|
||||
// ── Filter ────────────────────────────────────────────────────────────────
|
||||
const filtered = useMemo(() => {
|
||||
const q = query.trim().toLowerCase();
|
||||
if (!q) return progressList;
|
||||
return progressList.filter((e) =>
|
||||
e.user.full_name?.toLowerCase().includes(q) ||
|
||||
e.user.email?.toLowerCase().includes(q)
|
||||
);
|
||||
}, [progressList, query]);
|
||||
|
||||
// ── Paginate ──────────────────────────────────────────────────────────────
|
||||
const totalPages = Math.max(1, Math.ceil(filtered.length / pageSize));
|
||||
const paginated = filtered.slice((page - 1) * pageSize, page * pageSize);
|
||||
const pagination = {
|
||||
page,
|
||||
limit: pageSize,
|
||||
totalPages,
|
||||
totalRecords: filtered.length,
|
||||
hasPrevPage: page > 1,
|
||||
hasNextPage: page < totalPages,
|
||||
};
|
||||
|
||||
const handlePageChange = (p) => setPage(p);
|
||||
const handlePageSizeChange = (size) => { setPageSize(size); setPage(1); };
|
||||
|
||||
const completedCount = progressList.filter((e) => e.course_status === 'completed').length;
|
||||
const inProgressCount = progressList.length - completedCount;
|
||||
|
||||
// ── Loading skeleton ──────────────────────────────────────────────────────
|
||||
if (listLoading) {
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<Skeleton className="h-9 w-full rounded-md" />
|
||||
{[...Array(4)].map((_, i) => (
|
||||
<div key={i} className="border rounded-lg p-4 flex items-center gap-3">
|
||||
<Skeleton className="size-9 rounded-full shrink-0" />
|
||||
<div className="flex-1 space-y-2">
|
||||
<Skeleton className="h-3.5 w-40" />
|
||||
<Skeleton className="h-3 w-56" />
|
||||
<Skeleton className="h-1.5 w-full rounded-full" />
|
||||
</div>
|
||||
<Skeleton className="h-5 w-20 rounded-full shrink-0" />
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ── Empty state ───────────────────────────────────────────────────────────
|
||||
if (!progressList.length) {
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center py-10 text-center gap-2">
|
||||
<BookOpen className="size-8 text-muted-foreground/40" />
|
||||
<p className="text-sm text-muted-foreground">No students have started reading this course yet.</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{/* ── Summary strip ── */}
|
||||
<div className="flex items-center gap-4 flex-wrap text-sm">
|
||||
<span className="flex items-center gap-1.5">
|
||||
<Users className="size-3.5" />
|
||||
{progressList.length} enrolled
|
||||
</span>
|
||||
<span className="flex items-center gap-1.5">
|
||||
<CheckCircle2 className="size-3.5 text-emerald-500" />
|
||||
{completedCount} completed
|
||||
</span>
|
||||
<span className="flex items-center gap-1.5">
|
||||
<Circle className="size-3.5 text-amber-400" />
|
||||
{inProgressCount} in progress
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* ── Search ── */}
|
||||
<form onSubmit={handleSearchSubmit} className="flex items-center gap-2">
|
||||
<div className="relative flex-1">
|
||||
<Search className="absolute left-3 top-1/2 -translate-y-1/2 size-4 text-muted-foreground pointer-events-none" />
|
||||
<Input
|
||||
placeholder="Search by name or email…"
|
||||
value={searchInput}
|
||||
onChange={(e) => setSearchInput(e.target.value.slice(0, 50))}
|
||||
maxLength={50}
|
||||
className="bg-background pl-9 pr-16"
|
||||
/>
|
||||
<span className={`absolute right-3 top-1/2 -translate-y-1/2 text-xs tabular-nums pointer-events-none ${searchInput.length >= 50 ? 'text-destructive' : 'text-muted-foreground'}`}>
|
||||
{searchInput.length}/50
|
||||
</span>
|
||||
</div>
|
||||
<Button type="submit" variant="outline" className="shrink-0">
|
||||
<Search className="size-4" />
|
||||
Search
|
||||
</Button>
|
||||
</form>
|
||||
|
||||
{/* ── List ── */}
|
||||
{filtered.length === 0 ? (
|
||||
<p className="text-sm text-muted-foreground text-center py-6">No results for "{query}".</p>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
{paginated.map((entry) => (
|
||||
<UserCard
|
||||
key={entry.user_id}
|
||||
entry={entry}
|
||||
onOpen={setDialogEntry}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* ── Pagination ── */}
|
||||
<TablePagination
|
||||
pagination={pagination}
|
||||
onPageChange={handlePageChange}
|
||||
rowCount={paginated.length}
|
||||
onPageSizeChange={handlePageSizeChange}
|
||||
recordLabel="student"
|
||||
/>
|
||||
|
||||
{/* ── Detail Dialog ── */}
|
||||
<UserDetailDialog
|
||||
open={!!dialogEntry}
|
||||
onOpenChange={(v) => { if (!v) setDialogEntry(null); }}
|
||||
entry={dialogEntry}
|
||||
courseId={courseId}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
import { useMemo, useRef, useState, useEffect } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import api from "@/utils/api.util";
|
||||
|
||||
import { useCourses } from "@/contexts/AdminCoursesContext";
|
||||
import { useAuth } from "@/contexts/AuthContext";
|
||||
|
||||
import DataTable from "@/components/generic/Table/DataTable";
|
||||
import { FilterSheet } from "@/components/generic/Sheet/FilterSheet";
|
||||
import { ArchiveDialog } from "@/components/generic/Dialogs/ArchiveDialog";
|
||||
|
||||
import { buildDataColumns, columnPinning } from "../../config/courses/columns.config";
|
||||
import { buildToolbarActions } from "../../config/courses/toolbar.config";
|
||||
import { buildSelectionActions } from "../../config/courses/selection.config";
|
||||
import { buildRowActions } from "../../config/courses/rowActions.config";
|
||||
|
||||
import { getTimestamp } from "@/utils/timestamp.util";
|
||||
import { formatGeneratedBy } from "@/utils/generatedBy.util";
|
||||
|
||||
export default function CoursesTable() {
|
||||
const [archiveTarget, setArchiveTarget] = useState(null);
|
||||
const [archiveIds, setArchiveIds] = useState(null);
|
||||
|
||||
const tableRefsRef = useRef({
|
||||
getFilters: () => [],
|
||||
getSort: () => [],
|
||||
resetSelection: () => { },
|
||||
setFilters: () => { },
|
||||
});
|
||||
|
||||
const navigate = useNavigate();
|
||||
|
||||
const { user: currentUser } = useAuth();
|
||||
|
||||
const { courses, attributes, pagination, setPagination, loading, fetchCourses, reorderCourses, archiveCourse, archiveCourses, fetchCourseFieldValues } = useCourses();
|
||||
|
||||
const handleRefsReady = (refs) => {
|
||||
tableRefsRef.current = refs;
|
||||
};
|
||||
|
||||
const [tierCategories, setTierCategories] = useState([]);
|
||||
useEffect(() => {
|
||||
api.get("/admin/tiers/categories")
|
||||
.then(({ data }) => setTierCategories(data.data ?? []))
|
||||
.catch(() => {});
|
||||
}, []);
|
||||
const tierMap = useMemo(
|
||||
() => Object.fromEntries(tierCategories.map((c) => [c.slug, c])),
|
||||
[tierCategories]
|
||||
);
|
||||
|
||||
const exportConfig = {
|
||||
allData: courses,
|
||||
attributes,
|
||||
filename: `${getTimestamp()}_Courses`,
|
||||
sheetName: "Courses",
|
||||
generatedBy: formatGeneratedBy(currentUser),
|
||||
};
|
||||
|
||||
// Reorder — swaps this row with its neighbor in the currently displayed
|
||||
// (order_index-sorted) list, then persists the new order_index set.
|
||||
const handleMove = async (row, direction) => {
|
||||
const idx = courses.findIndex((c) => c.course_id === row.course_id);
|
||||
const swapIdx = idx + direction;
|
||||
if (idx < 0 || swapIdx < 0 || swapIdx >= courses.length) return;
|
||||
|
||||
const reordered = [...courses];
|
||||
[reordered[idx], reordered[swapIdx]] = [reordered[swapIdx], reordered[idx]];
|
||||
|
||||
const ok = await reorderCourses(reordered.map((c) => c.course_id));
|
||||
if (ok) fetchCourses({ page: 1, limit: pagination?.limit ?? 10 });
|
||||
};
|
||||
|
||||
const rowActions = buildRowActions({
|
||||
onView: (row) => navigate(`/admin/courses/${row.course_id}/view`),
|
||||
onEdit: (row) => navigate(`/admin/courses/${row.course_id}/edit`),
|
||||
onArchive: (row) => setArchiveTarget(row),
|
||||
onMoveUp: (row) => handleMove(row, -1),
|
||||
onMoveDown: (row) => handleMove(row, 1),
|
||||
courses,
|
||||
});
|
||||
|
||||
const toolbarActions = buildToolbarActions({
|
||||
fetchCourses,
|
||||
pagination,
|
||||
exportConfig,
|
||||
navigate,
|
||||
getFilters: () => tableRefsRef.current.getFilters(),
|
||||
getSort: () => tableRefsRef.current.getSort(),
|
||||
getTableInstance: () => tableRefsRef.current.tableInstance,
|
||||
});
|
||||
|
||||
const selectionActions = buildSelectionActions({
|
||||
exportConfig,
|
||||
onArchive: (row) => setArchiveTarget(row),
|
||||
onArchiveMany: (ids) => setArchiveIds(ids),
|
||||
getTableInstance: () => tableRefsRef.current.tableInstance,
|
||||
});
|
||||
|
||||
const columns = useMemo(
|
||||
() => buildDataColumns(attributes, rowActions, tierMap),
|
||||
[attributes, rowActions, tierMap]
|
||||
);
|
||||
|
||||
const handleArchiveSuccess = () => {
|
||||
setArchiveTarget(null);
|
||||
setArchiveIds(null);
|
||||
tableRefsRef.current.resetSelection?.();
|
||||
fetchCourses({ page: 1, limit: pagination?.limit ?? 10 });
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<DataTable
|
||||
title="Courses"
|
||||
data={courses}
|
||||
columns={columns}
|
||||
attributes={attributes}
|
||||
pagination={pagination}
|
||||
setPagination={setPagination}
|
||||
loading={loading}
|
||||
onFetch={fetchCourses}
|
||||
onFetchFilterData={fetchCourseFieldValues}
|
||||
onRefsReady={handleRefsReady}
|
||||
renderFilterSheet={({ open, onOpenChange, column, attr, data, loading }) => (
|
||||
<FilterSheet
|
||||
open={open}
|
||||
onOpenChange={onOpenChange}
|
||||
column={column}
|
||||
attr={attr}
|
||||
data={data}
|
||||
loading={loading}
|
||||
/>
|
||||
)}
|
||||
columnPinning={columnPinning}
|
||||
toolbarActions={toolbarActions}
|
||||
selectionActions={selectionActions}
|
||||
recordLabel="course"
|
||||
emptyMessage="No courses found."
|
||||
/>
|
||||
|
||||
{/* ── Single archive ── */}
|
||||
<ArchiveDialog
|
||||
open={!!archiveTarget}
|
||||
onOpenChange={(v) => !v && setArchiveTarget(null)}
|
||||
entity={archiveTarget}
|
||||
entityLabel="Course"
|
||||
getName={(c) => c?.title}
|
||||
onArchive={(c) => archiveCourse(c?.course_id)}
|
||||
loading={loading}
|
||||
onSuccess={handleArchiveSuccess}
|
||||
onImpactCheck={async () => {
|
||||
const { data } = await api.get(
|
||||
`/admin/courses/${archiveTarget?.course_id}/archive-impact`
|
||||
);
|
||||
const { activeCount, totalCount } = data?.data ?? {};
|
||||
return [
|
||||
{ label: "student(s) are currently taking this course", count: activeCount ?? 0 },
|
||||
{ label: "student(s) have progress in this course", count: totalCount ?? 0 },
|
||||
];
|
||||
}}
|
||||
/>
|
||||
|
||||
{/* ── Bulk archive ── */}
|
||||
<ArchiveDialog
|
||||
open={!!archiveIds}
|
||||
onOpenChange={(v) => !v && setArchiveIds(null)}
|
||||
ids={archiveIds ?? []}
|
||||
entityLabel="Course"
|
||||
onArchive={(ids) => archiveCourses(ids)}
|
||||
loading={loading}
|
||||
onSuccess={handleArchiveSuccess}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
// modules/admin/components/courses/CreateAchievementDialog.jsx
|
||||
// Lightweight "define a brand-new achievement and select it for this course"
|
||||
// dialog — the create-new counterpart to AttachAchievementDialog's
|
||||
// attach-existing flow. Achievements are a global registry (not per-course
|
||||
// drafts), so this posts immediately instead of deferring to wizard finish.
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { X } from "lucide-react";
|
||||
|
||||
import { BADGE_ICON_OPTIONS } from "@/modules/admin/pages/tiers/EditTierCategory";
|
||||
import api from "@/utils/api.util";
|
||||
import { toast } from "sonner";
|
||||
import {
|
||||
Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter, DialogClose,
|
||||
} from "@/components/ui/dialog";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Spinner } from "@/components/ui/spinner";
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||
|
||||
const TRIGGER_OPTIONS = [
|
||||
{ value: "auth", label: "Auth (registration / login)" },
|
||||
{ value: "tier", label: "Subscription (plan purchase)" },
|
||||
{ value: "course", label: "Course (lessons / quizzes)" },
|
||||
{ value: "profile", label: "Profile completion" },
|
||||
{ value: "social", label: "Social (referrals / community)" },
|
||||
{ value: "manual", label: "Manual (admin-granted only)" },
|
||||
];
|
||||
|
||||
const emptyForm = { key: "", type: "badge", label: "", description: "", icon: null, trigger: "manual", is_active: true };
|
||||
|
||||
export default function CreateAchievementDialog({ open, onOpenChange, onCreated }) {
|
||||
const [form, setForm] = useState(emptyForm);
|
||||
const [errors, setErrors] = useState({});
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (open) { setForm(emptyForm); setErrors({}); }
|
||||
}, [open]);
|
||||
|
||||
const set = (field) => (value) => setForm((prev) => ({ ...prev, [field]: value }));
|
||||
|
||||
const validate = () => {
|
||||
const e = {};
|
||||
if (!form.key.trim()) e.key = "Key is required.";
|
||||
else if (!/^[a-z0-9_]+$/.test(form.key)) e.key = "Key must be lowercase letters, numbers or underscores.";
|
||||
if (!form.label.trim()) e.label = "Label is required.";
|
||||
setErrors(e);
|
||||
return !Object.keys(e).length;
|
||||
};
|
||||
|
||||
const handleCreate = async () => {
|
||||
if (!validate()) return;
|
||||
setLoading(true);
|
||||
try {
|
||||
const { data } = await api.post("/admin/achievements", {
|
||||
key: form.key.trim(),
|
||||
type: form.type,
|
||||
label: form.label.trim(),
|
||||
description: form.description.trim() || null,
|
||||
icon: form.icon || null,
|
||||
trigger: form.trigger || null,
|
||||
is_active: form.is_active,
|
||||
});
|
||||
toast("Achievement created.");
|
||||
onCreated?.(data.data);
|
||||
onOpenChange(false);
|
||||
} catch (err) {
|
||||
toast(err?.response?.data?.message ?? "Could not create achievement.");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="sm:max-w-lg">
|
||||
<DialogHeader>
|
||||
<DialogTitle>New Achievement</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="space-y-4 max-h-[70vh] overflow-y-auto pr-1">
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="ach_key">Key <span className="text-destructive">*</span></Label>
|
||||
<Input
|
||||
id="ach_key"
|
||||
value={form.key}
|
||||
onChange={(e) => set("key")(e.target.value.toLowerCase())}
|
||||
placeholder="e.g. course_marathon"
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">Lowercase, no spaces. Cannot be changed after creation.</p>
|
||||
{errors.key && <p className="text-sm text-destructive">{errors.key}</p>}
|
||||
</div>
|
||||
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="ach_label">Label <span className="text-destructive">*</span></Label>
|
||||
<Input id="ach_label" value={form.label} onChange={(e) => set("label")(e.target.value)} placeholder="e.g. Course Marathon" />
|
||||
{errors.label && <p className="text-sm text-destructive">{errors.label}</p>}
|
||||
</div>
|
||||
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="ach_description">Description</Label>
|
||||
<Textarea id="ach_description" rows={2} value={form.description} onChange={(e) => set("description")(e.target.value)} placeholder="What does a learner do to earn this?" />
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div className="space-y-1.5">
|
||||
<Label>Type</Label>
|
||||
<Select value={form.type} onValueChange={set("type")}>
|
||||
<SelectTrigger><SelectValue /></SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="badge">Badge</SelectItem>
|
||||
<SelectItem value="milestone">Milestone</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label>Trigger</Label>
|
||||
<Select value={form.trigger} onValueChange={set("trigger")}>
|
||||
<SelectTrigger><SelectValue /></SelectTrigger>
|
||||
<SelectContent>
|
||||
{TRIGGER_OPTIONS.map((opt) => (
|
||||
<SelectItem key={opt.value} value={opt.value}>{opt.label}</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1.5">
|
||||
<Label>Icon</Label>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => set("icon")(null)}
|
||||
className={`flex items-center justify-center w-8 h-8 rounded-lg border-2 text-xs text-muted-foreground transition-all ${!form.icon ? "border-foreground bg-muted scale-105" : "border-border hover:border-muted-foreground"}`}
|
||||
title="No icon"
|
||||
>
|
||||
<X className="size-3.5" />
|
||||
</button>
|
||||
{BADGE_ICON_OPTIONS.map(({ name, icon: Icon }) => {
|
||||
const selected = form.icon === name;
|
||||
return (
|
||||
<button
|
||||
key={name}
|
||||
type="button"
|
||||
title={name}
|
||||
onClick={() => set("icon")(name)}
|
||||
className={`flex items-center justify-center w-8 h-8 rounded-lg border-2 transition-all ${selected ? "bg-secondary text-secondary-foreground border-foreground scale-105" : "border-border hover:border-muted-foreground"}`}
|
||||
>
|
||||
<Icon className="size-4" />
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-3">
|
||||
<Switch id="ach_is_active" checked={form.is_active} onCheckedChange={set("is_active")} />
|
||||
<Label htmlFor="ach_is_active">Active</Label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<DialogClose asChild>
|
||||
<Button type="button" variant="outline" disabled={loading}>Cancel</Button>
|
||||
</DialogClose>
|
||||
<Button type="button" onClick={handleCreate} disabled={loading}>
|
||||
{loading && <Spinner className="h-4 w-4 mr-2" />}
|
||||
Create Achievement
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
// modules/admin/components/courses/CreateLessonDialog.jsx
|
||||
// Lightweight "create a brand-new lesson and attach it to this unit" dialog —
|
||||
// the create-new counterpart to AttachLessonsDialog's attach-existing flow.
|
||||
|
||||
import { useEffect } from "react";
|
||||
import { useForm, useFieldArray } from "react-hook-form";
|
||||
import { z } from "zod";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { Plus, Trash2 } from "lucide-react";
|
||||
|
||||
import { useCourses } from "@/contexts/AdminCoursesContext";
|
||||
import { useAuth } from "@/contexts/AuthContext";
|
||||
import {
|
||||
Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter, DialogClose,
|
||||
} from "@/components/ui/dialog";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Spinner } from "@/components/ui/spinner";
|
||||
|
||||
const schema = z.object({
|
||||
title: z.string().min(1, "Title is required."),
|
||||
description: z.string().optional(),
|
||||
order: z.coerce.number().min(0).default(0),
|
||||
objectives: z.array(z.object({ value: z.string().min(1, "Objective cannot be empty.") })).default([]),
|
||||
});
|
||||
|
||||
export default function CreateLessonDialog({ open, onOpenChange, courseId, unitId, nextOrder = 0, onCreated, draftMode = false }) {
|
||||
const { createLesson, loading } = useCourses();
|
||||
const { user } = useAuth();
|
||||
|
||||
const { register, handleSubmit, reset, control, formState: { errors } } = useForm({
|
||||
resolver: zodResolver(schema),
|
||||
defaultValues: { title: "", description: "", order: nextOrder, objectives: [] },
|
||||
});
|
||||
|
||||
const { fields, append, remove } = useFieldArray({ control, name: "objectives" });
|
||||
|
||||
useEffect(() => {
|
||||
if (open) reset({ title: "", description: "", order: nextOrder, objectives: [] });
|
||||
}, [open, nextOrder, reset]);
|
||||
|
||||
const onValid = async (values) => {
|
||||
const objectives = values.objectives.map((o) => o.value);
|
||||
|
||||
if (draftMode) {
|
||||
onCreated?.({
|
||||
lesson_id: null,
|
||||
key: crypto.randomUUID(),
|
||||
title: values.title,
|
||||
description: values.description,
|
||||
order_index: values.order,
|
||||
objectives,
|
||||
});
|
||||
onOpenChange(false);
|
||||
return;
|
||||
}
|
||||
|
||||
const result = await createLesson(courseId, unitId, {
|
||||
...values,
|
||||
objectives,
|
||||
createdBy: user?.user_id,
|
||||
});
|
||||
const lesson = result?.data?.data ?? null;
|
||||
if (!lesson) return;
|
||||
onCreated?.(lesson);
|
||||
onOpenChange(false);
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="sm:max-w-[440px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle>New Lesson</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<form
|
||||
onSubmit={(e) => {
|
||||
// Dialog content is portalled out of the DOM, but React still bubbles
|
||||
// synthetic events through the React tree — without this, submitting
|
||||
// here also fires the wizard's outer <form onSubmit>, advancing the step.
|
||||
e.stopPropagation();
|
||||
handleSubmit(onValid)(e);
|
||||
}}
|
||||
className="space-y-4"
|
||||
>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="lesson_title">
|
||||
Title <span className="text-destructive">*</span>
|
||||
</Label>
|
||||
<Input id="lesson_title" placeholder="e.g. Welcome to the Course" {...register("title")} />
|
||||
{errors.title && <p className="text-sm text-destructive">{errors.title.message}</p>}
|
||||
</div>
|
||||
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="lesson_description">Description</Label>
|
||||
<Textarea id="lesson_description" placeholder="Optional lesson description" rows={3} {...register("description")} />
|
||||
</div>
|
||||
|
||||
<div className="space-y-1.5 max-w-[120px]">
|
||||
<Label htmlFor="lesson_order">Order</Label>
|
||||
<Input id="lesson_order" type="number" min={0} {...register("order")} />
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center justify-between">
|
||||
<Label className="text-xs text-muted-foreground">Objectives</Label>
|
||||
<Button type="button" variant="outline" size="sm" onClick={() => append({ value: "" })}>
|
||||
<Plus className="h-3.5 w-3.5 mr-1" /> Add
|
||||
</Button>
|
||||
</div>
|
||||
{fields.map((field, index) => (
|
||||
<div key={field.id} className="flex items-start gap-2">
|
||||
<div className="flex-1 space-y-1">
|
||||
<Input placeholder={`Objective ${index + 1}`} {...register(`objectives.${index}.value`)} />
|
||||
{errors.objectives?.[index]?.value && (
|
||||
<p className="text-xs text-destructive">{errors.objectives[index].value.message}</p>
|
||||
)}
|
||||
</div>
|
||||
<Button
|
||||
type="button" variant="ghost" size="icon"
|
||||
className="mt-0.5 text-muted-foreground hover:text-destructive"
|
||||
onClick={() => remove(index)}
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<DialogClose asChild>
|
||||
<Button type="button" variant="outline" disabled={loading}>Cancel</Button>
|
||||
</DialogClose>
|
||||
<Button type="submit" disabled={loading}>
|
||||
{loading && <Spinner className="h-4 w-4 mr-2" />}
|
||||
Create Lesson
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
// modules/admin/components/courses/CreateUnitDialog.jsx
|
||||
// Lightweight "create a brand-new unit and attach it to this course" dialog —
|
||||
// the create-new counterpart to AttachUnitsDialog's attach-existing flow.
|
||||
// Two steps (Details -> Completion Requirements) to match the other two
|
||||
// create-unit surfaces (AddUnit.jsx, AddLibraryUnit.jsx) — same capability,
|
||||
// just condensed into a dialog since this one runs inline in a wizard.
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { z } from "zod";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { ChevronLeft } from "lucide-react";
|
||||
|
||||
import { useCourses } from "@/contexts/AdminCoursesContext";
|
||||
import { useAuth } from "@/contexts/AuthContext";
|
||||
import {
|
||||
Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter, DialogClose,
|
||||
} from "@/components/ui/dialog";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Spinner } from "@/components/ui/spinner";
|
||||
import DraftRequirementsEditor from "./DraftRequirementsEditor";
|
||||
|
||||
const schema = z.object({
|
||||
title: z.string().min(1, "Title is required."),
|
||||
description: z.string().optional(),
|
||||
order: z.coerce.number().min(0).default(0),
|
||||
});
|
||||
|
||||
export default function CreateUnitDialog({ open, onOpenChange, courseId, nextOrder = 0, onCreated, draftMode = false }) {
|
||||
const { createUnit, syncUnitRequirements, loading } = useCourses();
|
||||
const { user } = useAuth();
|
||||
|
||||
const [step, setStep] = useState(0);
|
||||
const [requirements, setRequirements] = useState([]);
|
||||
|
||||
const { register, handleSubmit, trigger, reset, formState: { errors } } = useForm({
|
||||
resolver: zodResolver(schema),
|
||||
defaultValues: { title: "", description: "", order: nextOrder },
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
reset({ title: "", description: "", order: nextOrder });
|
||||
setStep(0);
|
||||
setRequirements([]);
|
||||
}
|
||||
}, [open, nextOrder, reset]);
|
||||
|
||||
const handleNext = async () => {
|
||||
const valid = await trigger();
|
||||
if (valid) setStep(1);
|
||||
};
|
||||
|
||||
const onValid = async (values) => {
|
||||
const clean = requirements.map(({ _key, ...r }) => r);
|
||||
|
||||
if (draftMode) {
|
||||
onCreated?.({
|
||||
unit_id: null,
|
||||
key: crypto.randomUUID(),
|
||||
title: values.title,
|
||||
description: values.description,
|
||||
order_index: values.order,
|
||||
lessons: [],
|
||||
requirements: clean,
|
||||
});
|
||||
onOpenChange(false);
|
||||
return;
|
||||
}
|
||||
|
||||
const result = await createUnit(courseId, { ...values, createdBy: user?.user_id });
|
||||
const unit = result?.data?.data ?? null;
|
||||
if (!unit) return;
|
||||
|
||||
if (clean.length > 0) {
|
||||
await syncUnitRequirements(courseId, unit.unit_id, clean);
|
||||
}
|
||||
|
||||
onCreated?.(unit);
|
||||
onOpenChange(false);
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="sm:max-w-[440px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle>New Unit</DialogTitle>
|
||||
<DialogDescription>
|
||||
Creates a new unit in the shared Units Library and attaches it to this course.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<form
|
||||
onSubmit={(e) => {
|
||||
// Dialog content is portalled out of the DOM, but React still bubbles
|
||||
// synthetic events through the React tree — without this, submitting
|
||||
// here also fires the wizard's outer <form onSubmit>, advancing the step.
|
||||
e.stopPropagation();
|
||||
handleSubmit(onValid)(e);
|
||||
}}
|
||||
className="space-y-4"
|
||||
>
|
||||
{step === 0 && (
|
||||
<>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="unit_title">
|
||||
Title <span className="text-destructive">*</span>
|
||||
</Label>
|
||||
<Input id="unit_title" placeholder="e.g. Getting Started" {...register("title")} />
|
||||
{errors.title && <p className="text-sm text-destructive">{errors.title.message}</p>}
|
||||
</div>
|
||||
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="unit_description">Description</Label>
|
||||
<Textarea id="unit_description" placeholder="Optional unit description" rows={3} {...register("description")} />
|
||||
</div>
|
||||
|
||||
<div className="space-y-1.5 max-w-[120px]">
|
||||
<Label htmlFor="unit_order">Order</Label>
|
||||
<Input id="unit_order" type="number" min={0} {...register("order")} />
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
{step === 1 && (
|
||||
<div className="space-y-3">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Configure how learners complete this unit — optional, sensible defaults apply automatically.
|
||||
</p>
|
||||
<DraftRequirementsEditor entityType="unit" items={requirements} onChange={setRequirements} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
<DialogFooter>
|
||||
{step === 0 ? (
|
||||
<>
|
||||
<DialogClose asChild>
|
||||
<Button type="button" variant="outline" disabled={loading}>Cancel</Button>
|
||||
</DialogClose>
|
||||
<Button type="button" onClick={handleNext}>Next</Button>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Button type="button" variant="outline" onClick={() => setStep(0)} disabled={loading}>
|
||||
<ChevronLeft className="h-4 w-4 mr-1" />
|
||||
Back
|
||||
</Button>
|
||||
<Button type="submit" disabled={loading}>
|
||||
{loading && <Spinner className="h-4 w-4 mr-2" />}
|
||||
Create Unit
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
import { Plus, Trash2, GripVertical, BookOpenCheck, ListChecks, Info } from "lucide-react";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Card, CardContent } from "@/components/ui/card";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger } from "@/components/ui/select";
|
||||
import { TYPE_DEFS, DEFAULT_BEHAVIOR_TEXT } from "./completionRequirementTypes";
|
||||
|
||||
function createRequirement(type) {
|
||||
return { _key: crypto.randomUUID(), type, min_percent: 100, button_label: "", is_required: true };
|
||||
}
|
||||
|
||||
/**
|
||||
* Draft-only requirements editor for creation wizards — no fetch, no
|
||||
* independent save. The parent wizard holds `items` in local state and only
|
||||
* persists them (via its own sync call) together with the rest of the entity
|
||||
* when the wizard's final Create/Finish action fires — the entity doesn't
|
||||
* exist yet while this renders, so there's nothing to fetch or save against
|
||||
* until then. Mirrors CompletionRequirementBuilder's item UI, minus the
|
||||
* loading/save plumbing that assumes an already-existing entity.
|
||||
*/
|
||||
export default function DraftRequirementsEditor({ entityType, items, onChange, blockTypes }) {
|
||||
// blockTypes (optional) — the actual block types currently on this lesson's page
|
||||
// (e.g. ["video", "text"]). When provided, requirement types that need a specific
|
||||
// block (watch_video needs "video", listen_audio needs "audio") only show up once
|
||||
// that block actually exists — "detection" rather than always offering them.
|
||||
const availableTypes = Object.entries(TYPE_DEFS)
|
||||
.filter(([, def]) => def.entityTypes.includes(entityType))
|
||||
.filter(([, def]) => !blockTypes || !def.requiresBlockTypes || def.requiresBlockTypes.some((bt) => blockTypes.includes(bt)))
|
||||
.map(([value, def]) => ({ value, ...def }));
|
||||
|
||||
const usedTypes = new Set(items.map((i) => i.type));
|
||||
const addableTypes = availableTypes.filter((t) => !usedTypes.has(t.value));
|
||||
|
||||
const update = (key, patch) => onChange(items.map((i) => (i._key === key ? { ...i, ...patch } : i)));
|
||||
const addItem = (type) => onChange([...items, createRequirement(type)]);
|
||||
const removeItem = (key) => onChange(items.filter((i) => i._key !== key));
|
||||
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
{items.length === 0 && (
|
||||
<p className="flex items-start gap-2 text-sm text-muted-foreground py-4 px-3 border border-dashed rounded-lg">
|
||||
<Info className="size-4 shrink-0 mt-0.5" />
|
||||
<span>
|
||||
No completion requirements configured — by default, {DEFAULT_BEHAVIOR_TEXT[entityType]}.
|
||||
Add a requirement below to override this.
|
||||
</span>
|
||||
</p>
|
||||
)}
|
||||
|
||||
{items.map((item, idx) => {
|
||||
const def = TYPE_DEFS[item.type];
|
||||
const Icon = def?.icon ?? BookOpenCheck;
|
||||
return (
|
||||
<Card key={item._key}>
|
||||
<CardContent className="pt-4 pb-4 space-y-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<GripVertical className="h-4 w-4 text-muted-foreground shrink-0" />
|
||||
<Badge variant="outline" className="text-xs gap-1 shrink-0">
|
||||
<Icon className="h-3 w-3" />
|
||||
{idx + 1}
|
||||
</Badge>
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="text-sm font-medium truncate">{def?.label ?? item.type}</p>
|
||||
<p className="text-xs text-muted-foreground truncate">{def?.describe(entityType)}</p>
|
||||
</div>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-8 w-8 shrink-0 text-destructive hover:text-destructive"
|
||||
onClick={() => removeItem(item._key)}
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{item.type === "watch_percent" && (
|
||||
<div className="pl-7 flex items-center gap-2 max-w-48">
|
||||
<Input
|
||||
type="number"
|
||||
min={1}
|
||||
max={100}
|
||||
value={item.min_percent ?? 100}
|
||||
onChange={(e) => update(item._key, { min_percent: Math.min(100, Math.max(1, parseInt(e.target.value) || 1)) })}
|
||||
className="h-8 text-sm"
|
||||
/>
|
||||
<Label className="text-xs text-muted-foreground whitespace-nowrap">% watched required</Label>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{item.type === "manual_complete" && (
|
||||
<div className="pl-7 space-y-1 max-w-64">
|
||||
<Label className="text-xs">Button label (optional)</Label>
|
||||
<Input
|
||||
placeholder='Defaults to "Mark Complete"'
|
||||
value={item.button_label ?? ""}
|
||||
onChange={(e) => update(item._key, { button_label: e.target.value })}
|
||||
className="h-8 text-sm"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
})}
|
||||
|
||||
{addableTypes.length > 0 && (
|
||||
<Select value="" onValueChange={(v) => addItem(v)}>
|
||||
<SelectTrigger className="h-9 w-full text-sm">
|
||||
<span className="flex items-center gap-2 text-muted-foreground">
|
||||
<Plus className="h-4 w-4" />
|
||||
Add Requirement
|
||||
</span>
|
||||
</SelectTrigger>
|
||||
<SelectContent position="popper" sideOffset={4}>
|
||||
{addableTypes.map((t) => (
|
||||
<SelectItem key={t.value} value={t.value}>
|
||||
<span className="flex items-center gap-2">
|
||||
<t.icon className="h-3.5 w-3.5" />
|
||||
{t.label}
|
||||
</span>
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Read-only summary of a draft requirements array for a wizard's Review step
|
||||
* — reads directly from local state (no fetch), since nothing has been
|
||||
* persisted yet at that point.
|
||||
*/
|
||||
export function DraftRequirementsSummary({ entityType, items }) {
|
||||
const describeValue = (r) => {
|
||||
if (r.type === "watch_percent") return `${r.min_percent}% watched`;
|
||||
if (r.type === "manual_complete") return r.button_label || "Mark Complete";
|
||||
return "Required";
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="border border-border rounded-lg p-4 space-y-1">
|
||||
<div className="flex items-center gap-2 mb-3">
|
||||
<ListChecks className="h-4 w-4 text-muted-foreground" />
|
||||
<span className="text-sm font-medium">Completion Requirements</span>
|
||||
</div>
|
||||
{items.length === 0 ? (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
None added — default behavior applies ({DEFAULT_BEHAVIOR_TEXT[entityType]}).
|
||||
</p>
|
||||
) : (
|
||||
items.map((r) => (
|
||||
<div key={r._key ?? r.type} className="flex justify-between py-1.5 text-sm">
|
||||
<span className="text-muted-foreground min-w-[140px]">{TYPE_DEFS[r.type]?.label ?? r.type}</span>
|
||||
<span className="text-foreground text-right">{describeValue(r)}</span>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,235 @@
|
||||
/* A similar strategy to BlockList.jsx so this will applies
|
||||
to Client side */
|
||||
|
||||
import { Eye, ImageIcon, VideoIcon, ZoomIn } from "lucide-react";
|
||||
import { PhotoProvider, PhotoView } from "react-photo-view";
|
||||
import { VideoBlock } from "@/components/generic/Blocks/Client/VideoBlock";
|
||||
import { TextVideoBlock } from "@/components/generic/Blocks/Client/TextVideoBlock";
|
||||
import { TextImageBlock } from "@/components/generic/Blocks/Client/TextImageBlock";
|
||||
import { ImageBlock } from "@/components/generic/Blocks/Client/ImageBlock";
|
||||
import { TextBlock } from "@/components/generic/Blocks/Client/TextBlock";
|
||||
import { AudioBlock } from "@/components/generic/Blocks/Client/AudioBlock";
|
||||
import { CodeBlock } from "@/components/generic/Blocks/Client/CodeBlock";
|
||||
import { MarkdownBlock } from "@/components/generic/Blocks/Client/MarkdownBlock";
|
||||
|
||||
export function LessonHeader({ lesson }) {
|
||||
if (!lesson) return null;
|
||||
return (
|
||||
<div className="space-y-3 pb-2 sm:space-y-4">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold leading-tight mb-1 sm:text-3xl sm:leading-[1.2]">
|
||||
{lesson.title}
|
||||
</h1>
|
||||
{lesson.description && (
|
||||
<p className="mt-1 leading-relaxed text-sm text-muted-foreground sm:text-base sm:leading-[1.75] sm:text-justify">
|
||||
{lesson.description}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{lesson.objectives?.length > 0 && (
|
||||
<div className="rounded-lg border p-3 space-y-2 sm:p-4 sm:space-y-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="h-7 w-7 rounded-md bg-green-100 flex items-center justify-center shrink-0 sm:h-8 sm:w-8">
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
className="h-3.5 w-3.5 text-green-600 sm:h-4 sm:w-4"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth={2}
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
>
|
||||
<circle cx="12" cy="12" r="10" />
|
||||
<circle cx="12" cy="12" r="6" />
|
||||
<circle cx="12" cy="12" r="2" />
|
||||
</svg>
|
||||
</div>
|
||||
<p className="text-xs font-semibold sm:text-sm">Objective</p>
|
||||
</div>
|
||||
<ul className="space-y-1 list-disc list-inside sm:space-y-1.5">
|
||||
{lesson.objectives.map((o) => (
|
||||
<li key={o.objective_id} className="text-xs text-muted-foreground sm:text-sm">
|
||||
{o.text}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Zoomable image wrapper ───────────────────────────────────────────────────
|
||||
// Must be rendered inside a <PhotoProvider>. Shows a subtle zoom hint on hover.
|
||||
|
||||
export function ZoomableImage({ url, alt }) {
|
||||
if (!url) return null;
|
||||
return (
|
||||
<PhotoView src={url}>
|
||||
<div className="relative group cursor-zoom-in">
|
||||
<img
|
||||
src={url}
|
||||
alt={alt ?? ""}
|
||||
className="w-full rounded-md object-cover aspect-video"
|
||||
draggable={false}
|
||||
/>
|
||||
{/* Zoom hint badge — fades in on hover */}
|
||||
<div className="absolute top-4 right-4 opacity-0 group-hover:opacity-100 transition-opacity duration-200 pointer-events-none">
|
||||
<div className="flex items-center gap-1 bg-secondary text-sm px-2 py-1 rounded-full border">
|
||||
<ZoomIn className="size-4" />
|
||||
<span>Zoom</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</PhotoView>
|
||||
);
|
||||
}
|
||||
|
||||
export function PreviewImage({ url, alt }) {
|
||||
if (!url) {
|
||||
return (
|
||||
<div className="flex items-center justify-center aspect-video rounded-lg border border-dashed text-xs text-muted-foreground bg-muted/20 gap-1.5">
|
||||
<ImageIcon className="h-4 w-4" />
|
||||
No image
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return <ZoomableImage url={url} alt={alt} />;
|
||||
}
|
||||
|
||||
export function PreviewVideo({ url, thumb }) {
|
||||
if (!url) {
|
||||
return (
|
||||
<div className="flex items-center justify-center aspect-video rounded-lg border border-dashed text-xs text-muted-foreground bg-muted/20 gap-1.5">
|
||||
<VideoIcon className="h-4 w-4" />
|
||||
No video
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<div className="relative rounded-md overflow-hidden aspect-video bg-muted">
|
||||
{thumb ? (
|
||||
<img src={thumb} alt="Video thumbnail" className="w-full h-full object-cover" />
|
||||
) : (
|
||||
<div className="w-full h-full flex items-center justify-center">
|
||||
<VideoIcon className="h-8 w-8 text-muted-foreground/40 sm:h-10 sm:w-10" />
|
||||
</div>
|
||||
)}
|
||||
<div className="absolute inset-0 flex items-center justify-center pointer-events-none">
|
||||
<div className="h-8 w-8 rounded-full bg-black/50 flex items-center justify-center sm:h-10 sm:w-10">
|
||||
<VideoIcon className="h-4 w-4 text-white sm:h-5 sm:w-5" />
|
||||
</div>
|
||||
</div>
|
||||
<div className="absolute bottom-0 inset-x-0 bg-black/60 px-2 py-1">
|
||||
<p className="text-white text-[9px] truncate sm:text-[10px]">{url}</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// onWatchProgress(percent, { blockId, blockType }) — only meaningful for video/audio
|
||||
// blocks; optional, undefined in admin preview mode (only the client reader passes it,
|
||||
// for watch_percent/watch_video/listen_audio tracking). PreviewBlock (not VideoBlock/
|
||||
// AudioBlock themselves) attaches the block's own id/type to each call, since a lesson
|
||||
// can have several blocks of the same type and watch_video/listen_audio need to know
|
||||
// which specific one just reported progress.
|
||||
export function PreviewBlock({ block, onWatchProgress, resumeMap, antiSkipEnabled }) {
|
||||
const { id, type, content } = block;
|
||||
const withBlockMeta = onWatchProgress
|
||||
? (percent) => onWatchProgress(percent, { blockId: id, blockType: type })
|
||||
: undefined;
|
||||
const resumePercent = resumeMap?.[id];
|
||||
|
||||
switch (type) {
|
||||
case "text":
|
||||
return <TextBlock blockId={id} content={content} readOnly />;
|
||||
case "image":
|
||||
return <ImageBlock content={content} readOnly />;
|
||||
case "text-image":
|
||||
return <TextImageBlock blockId={id} content={content} readOnly />;
|
||||
case "video":
|
||||
return <VideoBlock content={content} readOnly onWatchProgress={withBlockMeta} resumePercent={resumePercent} antiSkipEnabled={antiSkipEnabled} />;
|
||||
case "text-video":
|
||||
return <TextVideoBlock blockId={id} content={content} readOnly onWatchProgress={withBlockMeta} resumePercent={resumePercent} antiSkipEnabled={antiSkipEnabled} />;
|
||||
case "audio":
|
||||
return <AudioBlock content={content} onWatchProgress={withBlockMeta} resumePercent={resumePercent} antiSkipEnabled={antiSkipEnabled} />;
|
||||
case "code":
|
||||
return <CodeBlock content={content} />;
|
||||
case "markdown":
|
||||
return <MarkdownBlock content={content} />;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// ─── PreviewContent ───────────────────────────────────────────────────────────
|
||||
// PhotoProvider wraps ALL blocks so images across the whole lesson share
|
||||
// one lightbox session — users can swipe between them naturally.
|
||||
|
||||
// Only these completion-requirement types gate video/audio behind the anti-skip
|
||||
// seek-cap — everything else (or no requirement configured) allows free seeking.
|
||||
const WATCH_TYPE_REQUIREMENTS = ["watch_percent", "watch_video", "listen_audio"];
|
||||
|
||||
export function PreviewContent({ lesson, blocks, empty = "No content yet.", showHeader = true, onWatchProgress }) {
|
||||
const resumeMap = lesson?.resume_positions;
|
||||
const antiSkipEnabled = WATCH_TYPE_REQUIREMENTS.includes(lesson?.completion?.type);
|
||||
return (
|
||||
<PhotoProvider
|
||||
speed={() => 300}
|
||||
easing={(type) => (type === 2 ? "cubic-bezier(0.36, 0, 0.66, -0.56)" : "cubic-bezier(0.34, 1.56, 0.64, 1)")}
|
||||
toolbarRender={({ onScale, scale, rotate, onRotate }) => (
|
||||
<div className="flex items-center gap-3 px-2">
|
||||
<button
|
||||
onClick={() => onScale(scale + 0.5)}
|
||||
className="text-white/80 hover:text-white transition-colors"
|
||||
title="Zoom in"
|
||||
>
|
||||
<ZoomIn className="h-5 w-5" />
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
>
|
||||
{showHeader && <LessonHeader lesson={lesson} />}
|
||||
{blocks.length === 0 ? (
|
||||
<div className="flex flex-col items-center justify-center gap-2 py-10 text-sm text-muted-foreground sm:py-16">
|
||||
<Eye className="h-6 w-6 opacity-20 sm:h-8 sm:w-8" />
|
||||
<p>{empty}</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-4 sm:space-y-5">
|
||||
{blocks.map((block) => (
|
||||
<div key={block.id}>
|
||||
<PreviewBlock block={block} onWatchProgress={onWatchProgress} resumeMap={resumeMap} antiSkipEnabled={antiSkipEnabled} />
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</PhotoProvider>
|
||||
);
|
||||
}
|
||||
|
||||
export function PreviewChrome({ title, children, showChrome = true }) {
|
||||
if (!showChrome) {
|
||||
return <>{children}</>;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="rounded-xl border bg-card shadow-sm overflow-hidden">
|
||||
<div className="flex items-center gap-1.5 px-3 py-2 bg-muted/60 border-b">
|
||||
<span className="hidden h-2.5 w-2.5 rounded-full bg-red-400 sm:inline-block" />
|
||||
<span className="hidden h-2.5 w-2.5 rounded-full bg-yellow-400 sm:inline-block" />
|
||||
<span className="hidden h-2.5 w-2.5 rounded-full bg-green-400 sm:inline-block" />
|
||||
<div className="flex-1 sm:mx-3 h-5 rounded bg-background/60 border text-[10px]
|
||||
flex items-center px-2 text-muted-foreground/60 truncate">
|
||||
{title ?? "Lesson Preview"}
|
||||
</div>
|
||||
<Eye className="h-3.5 w-3.5 text-muted-foreground/60 shrink-0" />
|
||||
</div>
|
||||
<div className="p-3 sm:p-5">
|
||||
{children}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
import { useMemo, useRef, useState, useCallback, useEffect } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import api from "@/utils/api.util";
|
||||
|
||||
import { useCourses } from "@/contexts/AdminCoursesContext";
|
||||
import { useAuth } from "@/contexts/AuthContext";
|
||||
|
||||
import DataTable from "@/components/generic/Table/DataTable";
|
||||
import { FilterSheet } from "@/components/generic/Sheet/FilterSheet";
|
||||
import { ArchiveDialog } from "@/components/generic/Dialogs/ArchiveDialog";
|
||||
|
||||
import { buildDataColumns, columnPinning } from "../../config/courses/lessons/columns.config";
|
||||
import { buildToolbarActions } from "../../config/courses/lessons/toolbar.config";
|
||||
import { buildSelectionActions } from "../../config/courses/lessons/selection.config";
|
||||
import { buildRowActions } from "../../config/courses/lessons/rowActions.config";
|
||||
|
||||
import { getTimestamp } from "@/utils/timestamp.util";
|
||||
import { formatGeneratedBy } from "@/utils/generatedBy.util";
|
||||
|
||||
export default function LessonsTable({ courseId, unitId }) {
|
||||
const [archiveTarget, setArchiveTarget] = useState(null);
|
||||
const [archiveIds, setArchiveIds] = useState(null);
|
||||
|
||||
const tableRefsRef = useRef({
|
||||
getFilters: () => [],
|
||||
getSort: () => [],
|
||||
resetSelection: () => { },
|
||||
setFilters: () => { },
|
||||
});
|
||||
|
||||
const navigate = useNavigate();
|
||||
|
||||
const { user: currentUser } = useAuth();
|
||||
|
||||
const {
|
||||
course, unit, lessons, attributes, pagination, setPagination, loading,
|
||||
fetchLessons, archiveLesson, archiveLessons, fetchLessonFieldValues
|
||||
} = useCourses();
|
||||
|
||||
const handleRefsReady = (refs) => {
|
||||
tableRefsRef.current = refs;
|
||||
};
|
||||
|
||||
const [tierCategories, setTierCategories] = useState([]);
|
||||
useEffect(() => {
|
||||
api.get("/admin/tiers/categories")
|
||||
.then(({ data }) => setTierCategories(data.data ?? []))
|
||||
.catch(() => {});
|
||||
}, []);
|
||||
const tierMap = useMemo(
|
||||
() => Object.fromEntries(tierCategories.map((c) => [c.slug, c])),
|
||||
[tierCategories]
|
||||
);
|
||||
|
||||
const exportConfig = {
|
||||
allData: lessons,
|
||||
attributes,
|
||||
filename: `${getTimestamp()}_${course?.title}_${unit?.title}_Lessons`,
|
||||
sheetName: "Lessons",
|
||||
generatedBy: formatGeneratedBy(currentUser),
|
||||
};
|
||||
|
||||
const handleFetch = useCallback(
|
||||
(params) => fetchLessons(courseId, unitId, params),
|
||||
[courseId, unitId]
|
||||
);
|
||||
|
||||
const rowActions = useMemo(() => buildRowActions({
|
||||
onView: (row) => navigate(`/admin/courses/${courseId}/units/${unitId}/lessons/${row.lesson_id}/view`),
|
||||
onArchive: (row) => setArchiveTarget(row),
|
||||
}), [courseId, unitId]);
|
||||
|
||||
const toolbarActions = buildToolbarActions({
|
||||
fetchLessons: (params) => fetchLessons(courseId, unitId, params),
|
||||
pagination,
|
||||
exportConfig,
|
||||
navigate,
|
||||
courseId,
|
||||
unitId,
|
||||
getFilters: () => tableRefsRef.current.getFilters(),
|
||||
getSort: () => tableRefsRef.current.getSort(),
|
||||
getTableInstance: () => tableRefsRef.current.tableInstance,
|
||||
});
|
||||
|
||||
const selectionActions = buildSelectionActions({
|
||||
exportConfig,
|
||||
onArchive: (row) => setArchiveTarget(row),
|
||||
onArchiveMany: (ids) => setArchiveIds(ids),
|
||||
getTableInstance: () => tableRefsRef.current.tableInstance,
|
||||
});
|
||||
|
||||
const columns = useMemo(
|
||||
() => buildDataColumns(attributes, rowActions, tierMap, unit?.subscription, course?.subscription),
|
||||
[attributes, rowActions, tierMap, unit?.subscription, course?.subscription]
|
||||
);
|
||||
|
||||
const handleArchiveSuccess = () => {
|
||||
setArchiveTarget(null);
|
||||
setArchiveIds(null);
|
||||
tableRefsRef.current.resetSelection?.();
|
||||
fetchLessons(courseId, unitId, { page: 1, limit: pagination?.limit ?? 10 });
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<DataTable
|
||||
title="Lessons"
|
||||
data={lessons}
|
||||
columns={columns}
|
||||
attributes={attributes}
|
||||
pagination={pagination}
|
||||
setPagination={setPagination}
|
||||
loading={loading}
|
||||
onFetch={handleFetch}
|
||||
onFetchFilterData={(field) => fetchLessonFieldValues(courseId, unitId, field)}
|
||||
onRefsReady={handleRefsReady}
|
||||
renderFilterSheet={({ open, onOpenChange, column, attr, data, loading }) => (
|
||||
<FilterSheet
|
||||
open={open}
|
||||
onOpenChange={onOpenChange}
|
||||
column={column}
|
||||
attr={attr}
|
||||
data={data}
|
||||
loading={loading}
|
||||
/>
|
||||
)}
|
||||
columnPinning={columnPinning}
|
||||
toolbarActions={toolbarActions}
|
||||
selectionActions={selectionActions}
|
||||
recordLabel="lesson"
|
||||
emptyMessage="No lessons found."
|
||||
/>
|
||||
|
||||
{/* ── Single archive ── */}
|
||||
<ArchiveDialog
|
||||
open={!!archiveTarget}
|
||||
onOpenChange={(v) => !v && setArchiveTarget(null)}
|
||||
entity={archiveTarget}
|
||||
entityLabel="Lesson"
|
||||
getName={(c) => c?.title}
|
||||
onArchive={(c) => archiveLesson(courseId, unitId, c?.lesson_id)}
|
||||
loading={loading}
|
||||
onSuccess={handleArchiveSuccess}
|
||||
/>
|
||||
|
||||
{/* ── Bulk archive ── */}
|
||||
<ArchiveDialog
|
||||
open={!!archiveIds}
|
||||
onOpenChange={(v) => !v && setArchiveIds(null)}
|
||||
ids={archiveIds ?? []}
|
||||
entityLabel="Lesson"
|
||||
onArchive={(ids) => archiveLessons(courseId, unitId, ids)}
|
||||
loading={loading}
|
||||
onSuccess={handleArchiveSuccess}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,281 @@
|
||||
import { useState } from "react";
|
||||
import { Plus, Trash2, GripVertical, CheckCircle2, Circle } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
const QUESTION_TYPES = [
|
||||
{ value: "true_false", label: "True / False" },
|
||||
{ value: "multiple_choice", label: "Multiple Choice (1 correct)" },
|
||||
{ value: "multi_select", label: "Multi Select (multiple correct)" },
|
||||
];
|
||||
|
||||
function FieldError({ message }) {
|
||||
if (!message) return null;
|
||||
return <p className="text-xs text-destructive mt-1">{message}</p>;
|
||||
}
|
||||
|
||||
// ── Single Option Row ─────────────────────────────────────────────────────────
|
||||
function OptionRow({ option, index, questionType, onUpdate, onRemove, onToggleCorrect }) {
|
||||
const isCorrect = option.is_correct;
|
||||
|
||||
return (
|
||||
<div className={cn(
|
||||
"flex items-center gap-2 rounded-lg border px-3 py-2 transition-colors",
|
||||
isCorrect ? "border-green-300 bg-green-50/60" : "border-border bg-background"
|
||||
)}>
|
||||
<GripVertical className="h-4 w-4 text-muted-foreground/40 shrink-0" />
|
||||
|
||||
{/* Correct toggle */}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onToggleCorrect(index)}
|
||||
className="shrink-0"
|
||||
title={isCorrect ? "Mark as incorrect" : "Mark as correct"}
|
||||
>
|
||||
{isCorrect
|
||||
? <CheckCircle2 className="h-4 w-4 text-green-600" />
|
||||
: <Circle className="h-4 w-4 text-muted-foreground" />
|
||||
}
|
||||
</button>
|
||||
|
||||
<Input
|
||||
value={option.text}
|
||||
onChange={(e) => onUpdate(index, { ...option, text: e.target.value })}
|
||||
placeholder={`Option ${index + 1}`}
|
||||
className="flex-1 border-0 shadow-none focus-visible:ring-0 p-0 h-auto text-sm"
|
||||
/>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onRemove(index)}
|
||||
className="shrink-0 text-muted-foreground hover:text-destructive transition-colors"
|
||||
>
|
||||
<Trash2 className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ── Question Card ─────────────────────────────────────────────────────────────
|
||||
export function QuestionCard({ question, index, onChange, onRemove, error }) {
|
||||
const updateField = (field, value) => onChange({ ...question, [field]: value });
|
||||
|
||||
const updateOption = (i, updated) => {
|
||||
const options = [...question.options];
|
||||
options[i] = updated;
|
||||
onChange({ ...question, options });
|
||||
};
|
||||
|
||||
const toggleCorrect = (i) => {
|
||||
const options = question.options.map((o, idx) => {
|
||||
if (question.type === "multiple_choice" || question.type === "true_false") {
|
||||
// single correct — deselect all others
|
||||
return { ...o, is_correct: idx === i };
|
||||
}
|
||||
// multi_select — toggle individual
|
||||
return idx === i ? { ...o, is_correct: !o.is_correct } : o;
|
||||
});
|
||||
onChange({ ...question, options });
|
||||
};
|
||||
|
||||
const addOption = () => {
|
||||
onChange({
|
||||
...question,
|
||||
options: [
|
||||
...question.options,
|
||||
{ text: "", is_correct: false, order_index: question.options.length },
|
||||
],
|
||||
});
|
||||
};
|
||||
|
||||
const removeOption = (i) => {
|
||||
onChange({
|
||||
...question,
|
||||
options: question.options.filter((_, idx) => idx !== i),
|
||||
});
|
||||
};
|
||||
|
||||
const handleTypeChange = (type) => {
|
||||
// Reset options based on type
|
||||
const defaultOptions =
|
||||
type === "true_false"
|
||||
? [
|
||||
{ text: "True", is_correct: true, order_index: 0 },
|
||||
{ text: "False", is_correct: false, order_index: 1 },
|
||||
]
|
||||
: question.options.map((o) => ({ ...o, is_correct: false }));
|
||||
|
||||
onChange({ ...question, type, options: defaultOptions });
|
||||
};
|
||||
|
||||
const correctCount = question.options.filter((o) => o.is_correct).length;
|
||||
|
||||
return (
|
||||
<div className="rounded-xl border bg-card shadow-sm overflow-hidden">
|
||||
{/* Card header */}
|
||||
<div className="flex items-center justify-between px-4 py-3 bg-muted/40 border-b">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="flex h-6 w-6 items-center justify-center rounded-full bg-primary/10 text-primary text-xs font-semibold">
|
||||
{index + 1}
|
||||
</span>
|
||||
<Select value={question.type} onValueChange={handleTypeChange}>
|
||||
<SelectTrigger className="h-7 text-xs border-0 bg-transparent shadow-none w-auto gap-1 px-1">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{QUESTION_TYPES.map((t) => (
|
||||
<SelectItem key={t.value} value={t.value} className="text-xs">
|
||||
{t.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<Badge variant="secondary" className="text-xs">
|
||||
{question.points ?? 1} pt{(question.points ?? 1) !== 1 ? "s" : ""}
|
||||
</Badge>
|
||||
{correctCount > 0 && (
|
||||
<Badge variant="outline" className="text-xs text-green-600 border-green-300">
|
||||
{correctCount} correct
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={onRemove}
|
||||
className="h-7 w-7 text-muted-foreground hover:text-destructive"
|
||||
>
|
||||
<Trash2 className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="p-4 space-y-4">
|
||||
{/* Question text */}
|
||||
<div className="space-y-1.5">
|
||||
<Label className="text-xs text-muted-foreground uppercase tracking-wide">Question</Label>
|
||||
<Textarea
|
||||
value={question.question}
|
||||
onChange={(e) => updateField("question", e.target.value)}
|
||||
placeholder="Enter your question here…"
|
||||
rows={2}
|
||||
className="resize-none"
|
||||
/>
|
||||
<FieldError message={error?.question} />
|
||||
</div>
|
||||
|
||||
{/* Options */}
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="space-y-0.5">
|
||||
<Label className="text-xs text-muted-foreground uppercase tracking-wide">
|
||||
Options
|
||||
<span className="ml-1 normal-case text-muted-foreground/60">
|
||||
— click circle to mark correct
|
||||
</span>
|
||||
</Label>
|
||||
{question.type === "multi_select" && correctCount > 0 && (
|
||||
<p className="text-xs text-blue-600 dark:text-blue-400">
|
||||
Students must select {correctCount} answer{correctCount !== 1 ? "s" : ""}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
{question.type !== "true_false" && (
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={addOption}
|
||||
className="h-6 text-xs gap-1"
|
||||
>
|
||||
<Plus className="h-3 w-3" />
|
||||
Add option
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
{question.options.map((option, i) => (
|
||||
<OptionRow
|
||||
key={i}
|
||||
option={option}
|
||||
index={i}
|
||||
questionType={question.type}
|
||||
onUpdate={updateOption}
|
||||
onRemove={removeOption}
|
||||
onToggleCorrect={toggleCorrect}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
<FieldError message={error?.options} />
|
||||
</div>
|
||||
|
||||
{/* Points + Explanation row */}
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div className="space-y-1.5">
|
||||
<Label className="text-xs text-muted-foreground uppercase tracking-wide">Points</Label>
|
||||
<Input
|
||||
type="number"
|
||||
min={1}
|
||||
value={question.points ?? 1}
|
||||
onChange={(e) => updateField("points", parseInt(e.target.value) || 1)}
|
||||
className="h-8 text-sm"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label className="text-xs text-muted-foreground uppercase tracking-wide">
|
||||
Explanation <span className="normal-case text-muted-foreground/60">(optional)</span>
|
||||
</Label>
|
||||
<Input
|
||||
value={question.explanation ?? ""}
|
||||
onChange={(e) => updateField("explanation", e.target.value)}
|
||||
placeholder="Shown after answer"
|
||||
className="h-8 text-sm"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ── Make a blank question ─────────────────────────────────────────────────────
|
||||
export function makeQuestion(type = "multiple_choice") {
|
||||
const defaultOptions = {
|
||||
true_false: [
|
||||
{ text: "True", is_correct: true, order_index: 0 },
|
||||
{ text: "False", is_correct: false, order_index: 1 },
|
||||
],
|
||||
multiple_choice: [
|
||||
{ text: "", is_correct: true, order_index: 0 },
|
||||
{ text: "", is_correct: false, order_index: 1 },
|
||||
{ text: "", is_correct: false, order_index: 2 },
|
||||
],
|
||||
multi_select: [
|
||||
{ text: "", is_correct: true, order_index: 0 },
|
||||
{ text: "", is_correct: true, order_index: 1 },
|
||||
{ text: "", is_correct: false, order_index: 2 },
|
||||
],
|
||||
};
|
||||
|
||||
return {
|
||||
_tempId: crypto.randomUUID(),
|
||||
type,
|
||||
question: "",
|
||||
explanation: "",
|
||||
points: 1,
|
||||
order_index: 0,
|
||||
options: defaultOptions[type] ?? [],
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,306 @@
|
||||
// modules/admin/components/courses/RoadmapBuilder.jsx
|
||||
// The "Roadmap" step content for AddCourse: compose a course's units — and
|
||||
// each unit's lessons — by attaching existing library content or creating
|
||||
// new items inline. Fully controlled/draft: nothing here ever calls the API.
|
||||
// All picks just mutate the `units` array the parent wizard holds in memory;
|
||||
// the whole roadmap is written in one shot when the wizard is finished.
|
||||
|
||||
import { useState, useMemo } from "react";
|
||||
import {
|
||||
ChevronRight, ChevronDown, Plus, Link2, Trash2, BookOpen, AlertTriangle,
|
||||
} from "lucide-react";
|
||||
|
||||
import { useLibrary } from "@/contexts/AdminLibraryContext";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import {
|
||||
AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent,
|
||||
AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle,
|
||||
} from "@/components/ui/alert-dialog";
|
||||
import AttachUnitsDialog from "../library/AttachUnitsDialog";
|
||||
import AttachLessonsDialog from "../library/AttachLessonsDialog";
|
||||
import CreateUnitDialog from "./CreateUnitDialog";
|
||||
import CreateLessonDialog from "./CreateLessonDialog";
|
||||
|
||||
export default function RoadmapBuilder({ units, onUnitsChange }) {
|
||||
const { unitsFlat, lessonsFlat } = useLibrary();
|
||||
|
||||
const [expanded, setExpanded] = useState(() => new Set());
|
||||
|
||||
const [createUnitOpen, setCreateUnitOpen] = useState(false);
|
||||
const [attachUnitOpen, setAttachUnitOpen] = useState(false);
|
||||
const [createLessonUnitKey, setCreateLessonUnitKey] = useState(null);
|
||||
const [attachLessonUnitKey, setAttachLessonUnitKey] = useState(null);
|
||||
const [removeUnitTarget, setRemoveUnitTarget] = useState(null);
|
||||
const [removeLessonTarget, setRemoveLessonTarget] = useState(null);
|
||||
|
||||
const toggleExpand = (key) => {
|
||||
setExpanded((prev) => {
|
||||
const next = new Set(prev);
|
||||
if (next.has(key)) next.delete(key);
|
||||
else next.add(key);
|
||||
return next;
|
||||
});
|
||||
};
|
||||
|
||||
const attachedUnitIds = useMemo(
|
||||
() => units.map((u) => u.unit_id).filter(Boolean),
|
||||
[units]
|
||||
);
|
||||
|
||||
const handleAttachUnits = (unitIds) => {
|
||||
const picked = unitIds
|
||||
.map((id) => unitsFlat.find((u) => u.unit_id === id))
|
||||
.filter(Boolean)
|
||||
.map((u) => ({
|
||||
key: crypto.randomUUID(),
|
||||
unit_id: u.unit_id,
|
||||
title: u.title,
|
||||
description: u.description ?? "",
|
||||
existing_lesson_count: u.lesson_count ?? 0,
|
||||
lessons: [],
|
||||
}));
|
||||
onUnitsChange([...units, ...picked]);
|
||||
};
|
||||
|
||||
const handleUnitCreated = (draftUnit) => {
|
||||
onUnitsChange([...units, draftUnit]);
|
||||
setExpanded((prev) => new Set(prev).add(draftUnit.key));
|
||||
};
|
||||
|
||||
const handleAttachLessons = (unitKey, lessonIds) => {
|
||||
const picked = lessonIds
|
||||
.map((id) => lessonsFlat.find((l) => l.lesson_id === id))
|
||||
.filter(Boolean)
|
||||
.map((l) => ({
|
||||
key: crypto.randomUUID(),
|
||||
lesson_id: l.lesson_id,
|
||||
title: l.title,
|
||||
description: l.description ?? "",
|
||||
objectives: [],
|
||||
}));
|
||||
onUnitsChange(units.map((u) =>
|
||||
u.key === unitKey ? { ...u, lessons: [...u.lessons, ...picked] } : u
|
||||
));
|
||||
};
|
||||
|
||||
const handleLessonCreated = (unitKey, draftLesson) => {
|
||||
onUnitsChange(units.map((u) =>
|
||||
u.key === unitKey ? { ...u, lessons: [...u.lessons, draftLesson] } : u
|
||||
));
|
||||
};
|
||||
|
||||
const confirmRemoveUnit = () => {
|
||||
if (!removeUnitTarget) return;
|
||||
onUnitsChange(units.filter((u) => u.key !== removeUnitTarget.key));
|
||||
setRemoveUnitTarget(null);
|
||||
};
|
||||
|
||||
const confirmRemoveLesson = () => {
|
||||
if (!removeLessonTarget) return;
|
||||
const { unitKey, lesson } = removeLessonTarget;
|
||||
onUnitsChange(units.map((u) =>
|
||||
u.key === unitKey ? { ...u, lessons: u.lessons.filter((l) => l.key !== lesson.key) } : u
|
||||
));
|
||||
setRemoveLessonTarget(null);
|
||||
};
|
||||
|
||||
const attachLessonUnit = units.find((u) => u.key === attachLessonUnitKey);
|
||||
|
||||
return (
|
||||
<div className="rounded-lg border bg-card p-6 space-y-5">
|
||||
<div className="flex items-start justify-between gap-3 pb-1 border-b">
|
||||
<div className="space-y-0.5">
|
||||
<h2 className="text-sm font-semibold">Course Roadmap</h2>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Add units to structure this course. Attach existing library units to reuse content, or create new ones from scratch.
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-2 shrink-0">
|
||||
<Button type="button" variant="outline" size="sm" onClick={() => setAttachUnitOpen(true)}>
|
||||
<Link2 className="h-3.5 w-3.5 mr-1.5" /> Select
|
||||
</Button>
|
||||
<Button type="button" variant="outline" size="sm" onClick={() => setCreateUnitOpen(true)}>
|
||||
<Plus className="h-3.5 w-3.5 mr-1.5" /> Create
|
||||
</Button>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{units.length === 0 ? (
|
||||
<div className="flex flex-col items-center justify-center gap-3 py-10 text-center">
|
||||
<BookOpen className="h-8 w-8 text-muted-foreground" />
|
||||
<p className="text-sm font-medium">No units yet</p>
|
||||
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
{units.map((unit, index) => {
|
||||
const isOpen = expanded.has(unit.key);
|
||||
const isAttached = !!unit.unit_id;
|
||||
return (
|
||||
<div key={unit.key} className="rounded-md border">
|
||||
<div className="flex items-center gap-2 px-3 py-2.5">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => toggleExpand(unit.key)}
|
||||
className="flex items-center gap-2 flex-1 min-w-0 text-left"
|
||||
>
|
||||
{isOpen ? (
|
||||
<ChevronDown className="h-4 w-4 text-muted-foreground shrink-0" />
|
||||
) : (
|
||||
<ChevronRight className="h-4 w-4 text-muted-foreground shrink-0" />
|
||||
)}
|
||||
<span className="text-xs text-muted-foreground shrink-0">{index + 1}</span>
|
||||
<span className="text-sm font-medium truncate">{unit.title}</span>
|
||||
{isAttached ? (
|
||||
<Badge variant="outline" className="text-[10px] shrink-0">
|
||||
{unit.existing_lesson_count} existing lesson{unit.existing_lesson_count === 1 ? "" : "s"}
|
||||
</Badge>
|
||||
) : (
|
||||
<Badge variant="secondary" className="text-[10px] shrink-0">new</Badge>
|
||||
)}
|
||||
{unit.lessons.length > 0 && (
|
||||
<Badge variant="outline" className="text-[10px] shrink-0">
|
||||
+{unit.lessons.length} added
|
||||
</Badge>
|
||||
)}
|
||||
</button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="text-muted-foreground hover:text-destructive shrink-0"
|
||||
onClick={() => setRemoveUnitTarget(unit)}
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{isOpen && (
|
||||
<div className="border-t bg-muted/30 px-3 py-3 space-y-2">
|
||||
{isAttached && (
|
||||
<p className="text-xs text-muted-foreground py-1">
|
||||
This unit already has {unit.existing_lesson_count} lesson{unit.existing_lesson_count === 1 ? "" : "s"} in the library. Any lessons you add below are appended on top.
|
||||
</p>
|
||||
)}
|
||||
{unit.lessons.length === 0 && !isAttached && (
|
||||
<p className="text-xs text-muted-foreground py-1">No lessons in this unit yet.</p>
|
||||
)}
|
||||
{unit.lessons.map((lesson, lIndex) => (
|
||||
<div key={lesson.key} className="flex items-center gap-2 pl-1">
|
||||
<span className="text-xs text-muted-foreground w-4 shrink-0">{lIndex + 1}.</span>
|
||||
<span className="text-sm flex-1 truncate">{lesson.title}</span>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-7 w-7 text-muted-foreground hover:text-destructive shrink-0"
|
||||
onClick={() => setRemoveLessonTarget({ unitKey: unit.key, lesson })}
|
||||
>
|
||||
<Trash2 className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
<div className="flex items-center gap-2 pt-1">
|
||||
<Button
|
||||
type="button" variant="outline" size="sm" className="h-7 text-xs"
|
||||
onClick={() => setAttachLessonUnitKey(unit.key)}
|
||||
>
|
||||
<Link2 className="h-3 w-3 mr-1" /> Select Lesson
|
||||
</Button>
|
||||
<Button
|
||||
type="button" variant="outline" size="sm" className="h-7 text-xs"
|
||||
onClick={() => setCreateLessonUnitKey(unit.key)}
|
||||
>
|
||||
<Plus className="h-3 w-3 mr-1" /> Create Lesson
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{units.length === 0 && (
|
||||
<div className="flex items-center gap-2 text-xs text-amber-700 dark:text-amber-400">
|
||||
<AlertTriangle className="h-3.5 w-3.5 shrink-0" />
|
||||
Add at least one unit so learners have content to see.
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* ── Create / Attach dialogs (draft mode — nothing here hits the API) ── */}
|
||||
<CreateUnitDialog
|
||||
open={createUnitOpen}
|
||||
onOpenChange={setCreateUnitOpen}
|
||||
nextOrder={units.length}
|
||||
onCreated={handleUnitCreated}
|
||||
draftMode
|
||||
/>
|
||||
<AttachUnitsDialog
|
||||
open={attachUnitOpen}
|
||||
onOpenChange={setAttachUnitOpen}
|
||||
attachedUnitIds={attachedUnitIds}
|
||||
onAttach={handleAttachUnits}
|
||||
/>
|
||||
<CreateLessonDialog
|
||||
open={!!createLessonUnitKey}
|
||||
onOpenChange={(v) => !v && setCreateLessonUnitKey(null)}
|
||||
nextOrder={(units.find((u) => u.key === createLessonUnitKey)?.lessons ?? []).length}
|
||||
onCreated={(lesson) => handleLessonCreated(createLessonUnitKey, lesson)}
|
||||
draftMode
|
||||
/>
|
||||
<AttachLessonsDialog
|
||||
open={!!attachLessonUnitKey}
|
||||
onOpenChange={(v) => !v && setAttachLessonUnitKey(null)}
|
||||
attachedLessonIds={(attachLessonUnit?.lessons ?? []).map((l) => l.lesson_id).filter(Boolean)}
|
||||
onAttach={(lessonIds) => handleAttachLessons(attachLessonUnitKey, lessonIds)}
|
||||
/>
|
||||
|
||||
{/* ── Remove confirmations ── */}
|
||||
<AlertDialog open={!!removeUnitTarget} onOpenChange={(v) => !v && setRemoveUnitTarget(null)}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Remove unit from roadmap</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
Remove <span className="font-medium text-foreground">{removeUnitTarget?.title}</span> from this course's
|
||||
roadmap? Nothing has been saved yet, so this just drops it from the draft.
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Cancel</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
onClick={confirmRemoveUnit}
|
||||
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
|
||||
>
|
||||
Remove
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
|
||||
<AlertDialog open={!!removeLessonTarget} onOpenChange={(v) => !v && setRemoveLessonTarget(null)}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Remove lesson from unit</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
Remove <span className="font-medium text-foreground">{removeLessonTarget?.lesson?.title}</span> from this
|
||||
unit? Nothing has been saved yet, so this just drops it from the draft.
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Cancel</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
onClick={confirmRemoveLesson}
|
||||
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
|
||||
>
|
||||
Remove
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
import { useMemo, useRef, useState, useCallback, useEffect } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import api from "@/utils/api.util";
|
||||
|
||||
import { useCourses } from "@/contexts/AdminCoursesContext";
|
||||
import { useAuth } from "@/contexts/AuthContext";
|
||||
|
||||
import DataTable from "@/components/generic/Table/DataTable";
|
||||
import { FilterSheet } from "@/components/generic/Sheet/FilterSheet";
|
||||
import { ArchiveDialog } from "@/components/generic/Dialogs/ArchiveDialog";
|
||||
|
||||
import { buildDataColumns, columnPinning } from "../../config/courses/units/columns.config";
|
||||
import { buildToolbarActions } from "../../config/courses/units/toolbar.config";
|
||||
import { buildSelectionActions } from "../../config/courses/units/selection.config";
|
||||
import { buildRowActions } from "../../config/courses/units/rowActions.config";
|
||||
|
||||
import { getTimestamp } from "@/utils/timestamp.util";
|
||||
import { formatGeneratedBy } from "@/utils/generatedBy.util";
|
||||
|
||||
export default function UnitsTable({ courseId, returnTo }) {
|
||||
const [archiveTarget, setArchiveTarget] = useState(null);
|
||||
const [archiveIds, setArchiveIds] = useState(null);
|
||||
|
||||
const tableRefsRef = useRef({
|
||||
getFilters: () => [],
|
||||
getSort: () => [],
|
||||
resetSelection: () => { },
|
||||
setFilters: () => { },
|
||||
});
|
||||
|
||||
const navigate = useNavigate();
|
||||
|
||||
const { user: currentUser } = useAuth();
|
||||
|
||||
const {
|
||||
course, units, attributes, pagination, setPagination, loading,
|
||||
fetchUnits, archiveUnit, archiveUnits, fetchUnitFieldValues
|
||||
} = useCourses();
|
||||
|
||||
const handleRefsReady = (refs) => {
|
||||
tableRefsRef.current = refs;
|
||||
};
|
||||
|
||||
const [tierCategories, setTierCategories] = useState([]);
|
||||
useEffect(() => {
|
||||
api.get("/admin/tiers/categories")
|
||||
.then(({ data }) => setTierCategories(data.data ?? []))
|
||||
.catch(() => {});
|
||||
}, []);
|
||||
const tierMap = useMemo(
|
||||
() => Object.fromEntries(tierCategories.map((c) => [c.slug, c])),
|
||||
[tierCategories]
|
||||
);
|
||||
|
||||
const exportConfig = {
|
||||
allData: units,
|
||||
attributes,
|
||||
filename: `${getTimestamp()}_${course?.title}_Units`,
|
||||
sheetName: "Units",
|
||||
generatedBy: formatGeneratedBy(currentUser),
|
||||
};
|
||||
|
||||
const handleFetch = useCallback(
|
||||
(params) => fetchUnits(courseId, params),
|
||||
[courseId]
|
||||
);
|
||||
|
||||
const rowActions = useMemo(() => buildRowActions({
|
||||
onView: (row) => navigate(`/admin/courses/${courseId}/units/${row.unit_id}/view`),
|
||||
onArchive: (row) => setArchiveTarget(row),
|
||||
}), [courseId]);
|
||||
|
||||
const toolbarActions = buildToolbarActions({
|
||||
fetchUnits: (params) => fetchUnits(courseId, params),
|
||||
pagination,
|
||||
exportConfig,
|
||||
navigate,
|
||||
courseId,
|
||||
returnTo,
|
||||
getFilters: () => tableRefsRef.current.getFilters(),
|
||||
getSort: () => tableRefsRef.current.getSort(),
|
||||
getTableInstance: () => tableRefsRef.current.tableInstance,
|
||||
});
|
||||
|
||||
const selectionActions = buildSelectionActions({
|
||||
exportConfig,
|
||||
onArchive: (row) => setArchiveTarget(row),
|
||||
onArchiveMany: (ids) => setArchiveIds(ids),
|
||||
getTableInstance: () => tableRefsRef.current.tableInstance,
|
||||
});
|
||||
|
||||
const columns = useMemo(
|
||||
() => buildDataColumns(attributes, rowActions, tierMap, course?.subscription),
|
||||
[attributes, rowActions, tierMap, course?.subscription]
|
||||
);
|
||||
|
||||
const handleArchiveSuccess = () => {
|
||||
setArchiveTarget(null);
|
||||
setArchiveIds(null);
|
||||
tableRefsRef.current.resetSelection?.();
|
||||
fetchUnits(courseId, { page: 1, limit: pagination?.limit ?? 10 });
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<DataTable
|
||||
title="Units"
|
||||
data={units}
|
||||
columns={columns}
|
||||
attributes={attributes}
|
||||
pagination={pagination}
|
||||
setPagination={setPagination}
|
||||
loading={loading}
|
||||
onFetch={handleFetch}
|
||||
onFetchFilterData={(field) => fetchUnitFieldValues(courseId, field)}
|
||||
onRefsReady={handleRefsReady}
|
||||
renderFilterSheet={({ open, onOpenChange, column, attr, data, loading }) => (
|
||||
<FilterSheet
|
||||
open={open}
|
||||
onOpenChange={onOpenChange}
|
||||
column={column}
|
||||
attr={attr}
|
||||
data={data}
|
||||
loading={loading}
|
||||
/>
|
||||
)}
|
||||
columnPinning={columnPinning}
|
||||
toolbarActions={toolbarActions}
|
||||
selectionActions={selectionActions}
|
||||
recordLabel="unit"
|
||||
emptyMessage="No units found."
|
||||
/>
|
||||
|
||||
{/* ── Single archive ── */}
|
||||
<ArchiveDialog
|
||||
open={!!archiveTarget}
|
||||
onOpenChange={(v) => !v && setArchiveTarget(null)}
|
||||
entity={archiveTarget}
|
||||
entityLabel="Unit"
|
||||
getName={(c) => c?.title}
|
||||
onArchive={(c) => archiveUnit(courseId, c?.unit_id)}
|
||||
loading={loading}
|
||||
onSuccess={handleArchiveSuccess}
|
||||
onImpactCheck={async () => {
|
||||
const { data } = await api.get(
|
||||
`/admin/courses/${courseId}/units/${archiveTarget?.unit_id}/archive-impact`
|
||||
);
|
||||
const { completionCount, progressCount } = data?.data ?? {};
|
||||
return [
|
||||
{ label: "student(s) have completed this unit", count: completionCount ?? 0 },
|
||||
{ label: "student(s) have reading progress in this unit", count: progressCount ?? 0 },
|
||||
];
|
||||
}}
|
||||
/>
|
||||
|
||||
{/* ── Bulk archive ── */}
|
||||
<ArchiveDialog
|
||||
open={!!archiveIds}
|
||||
onOpenChange={(v) => !v && setArchiveIds(null)}
|
||||
ids={archiveIds ?? []}
|
||||
entityLabel="Unit"
|
||||
onArchive={(ids) => archiveUnits(courseId, ids)}
|
||||
loading={loading}
|
||||
onSuccess={handleArchiveSuccess}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
import { BookOpenCheck, ClipboardCheck, PlayCircle, Video, Headphones, MousePointerClick } from "lucide-react";
|
||||
|
||||
// ─── Requirement type config ──────────────────────────────────────────────────
|
||||
// Mirrors utils/courses/completion_requirements.registry.js's VALID_ENTITY_TYPES
|
||||
// on the backend — keep in sync if a new type is added there.
|
||||
// Split out of CompletionRequirementBuilder.jsx (rather than exported from
|
||||
// there) so both it and other views (e.g. wizard Review steps) can import
|
||||
// these without tripping the react-refresh/only-export-components rule,
|
||||
// which requires component files to export components only.
|
||||
export const TYPE_DEFS = {
|
||||
read_all_content: {
|
||||
label: "Read / View All Content",
|
||||
icon: BookOpenCheck,
|
||||
entityTypes: ["course", "unit", "lesson"],
|
||||
describe: (entityType) =>
|
||||
entityType === "lesson"
|
||||
? "Learner must read through this lesson's content."
|
||||
: entityType === "unit"
|
||||
? "Every lesson in this unit must be completed."
|
||||
: "Every unit in this course must be completed.",
|
||||
},
|
||||
pass_quiz: {
|
||||
label: "Pass the Quiz",
|
||||
icon: ClipboardCheck,
|
||||
entityTypes: ["unit", "course"],
|
||||
describe: (entityType) =>
|
||||
entityType === "unit"
|
||||
? "Learner must pass this unit's quiz."
|
||||
: "Learner must pass the course's final assessment.",
|
||||
},
|
||||
watch_percent: {
|
||||
label: "Watch % of Video/Audio",
|
||||
icon: PlayCircle,
|
||||
entityTypes: ["lesson"],
|
||||
// Either block type satisfies this one — it's one aggregate percent across
|
||||
// whichever is playing, unlike watch_video/listen_audio below. text-video counts
|
||||
// as video — same <video> element under the hood, just paired with text.
|
||||
requiresBlockTypes: ["video", "audio", "text-video"],
|
||||
describe: () => "Learner must watch at least the configured percentage of the lesson's video/audio content.",
|
||||
},
|
||||
watch_video: {
|
||||
label: "Finish Watching the Full Video",
|
||||
icon: Video,
|
||||
entityTypes: ["lesson"],
|
||||
requiresBlockTypes: ["video", "text-video"],
|
||||
describe: () => "Learner must watch every video block on this lesson all the way through (100%).",
|
||||
},
|
||||
listen_audio: {
|
||||
label: "Finish Listening to the Full Audio",
|
||||
icon: Headphones,
|
||||
entityTypes: ["lesson"],
|
||||
requiresBlockTypes: ["audio"],
|
||||
describe: () => "Learner must listen to every audio block on this lesson all the way through (100%).",
|
||||
},
|
||||
manual_complete: {
|
||||
label: 'Manual "Mark Complete"',
|
||||
icon: MousePointerClick,
|
||||
entityTypes: ["course", "unit", "lesson"],
|
||||
describe: () => "Learner clicks a button to self-report completion — no automatic tracking.",
|
||||
},
|
||||
};
|
||||
|
||||
export const DEFAULT_BEHAVIOR_TEXT = {
|
||||
lesson: "the learner reading through the content marks it complete",
|
||||
unit: "every lesson in the unit must be completed",
|
||||
course: "every unit must be completed and the course assessment (if any) must be passed",
|
||||
};
|
||||
@@ -0,0 +1,176 @@
|
||||
import { useMemo, useRef, useState, useCallback } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
|
||||
import { useLibrary } from "@/contexts/AdminLibraryContext";
|
||||
import { useAuth } from "@/contexts/AuthContext";
|
||||
|
||||
import DataTable from "@/components/generic/Table/DataTable";
|
||||
import { FilterSheet } from "@/components/generic/Sheet/FilterSheet";
|
||||
import { RestoreDialog } from "@/components/generic/Dialogs/RestoreDialog";
|
||||
import { PermanentDeleteDialog } from "@/components/generic/Dialogs/PermanentDeleteDialog";
|
||||
|
||||
import { buildDataColumns, columnPinning } from "../../config/library/lessons/columns.config";
|
||||
import { buildArchivedToolbarActions } from "../../config/library/lessons/toolbar.config";
|
||||
import { buildArchivedSelectionActions } from "../../config/library/lessons/selection.config";
|
||||
import { buildArchivedRowActions } from "../../config/library/lessons/rowActions.config";
|
||||
|
||||
import { getTimestamp } from "@/utils/timestamp.util";
|
||||
import { formatGeneratedBy } from "@/utils/generatedBy.util";
|
||||
|
||||
export default function ArchivedLessonLibraryTable() {
|
||||
const [restoreTarget, setRestoreTarget] = useState(null);
|
||||
const [restoreIds, setRestoreIds] = useState(null);
|
||||
const [deleteTarget, setDeleteTarget] = useState(null);
|
||||
const [deleteIds, setDeleteIds] = useState(null);
|
||||
|
||||
const tableRefsRef = useRef({
|
||||
getFilters: () => [],
|
||||
getSort: () => [],
|
||||
resetSelection: () => { },
|
||||
setFilters: () => { },
|
||||
});
|
||||
|
||||
const navigate = useNavigate();
|
||||
|
||||
const { user: currentUser } = useAuth();
|
||||
|
||||
const {
|
||||
lessons, attributes, pagination, setPagination, loading,
|
||||
fetchArchivedLessons, restoreLesson, restoreLessons,
|
||||
permanentlyDeleteLesson, permanentlyDeleteLessons,
|
||||
fetchLessonFieldValues, fetchLessonPermanentDeleteImpact,
|
||||
} = useLibrary();
|
||||
|
||||
const handleRefsReady = (refs) => {
|
||||
tableRefsRef.current = refs;
|
||||
};
|
||||
|
||||
const exportConfig = {
|
||||
allData: lessons,
|
||||
attributes,
|
||||
filename: `${getTimestamp()}_ArchivedLessonLibrary`,
|
||||
sheetName: "Archived Lessons",
|
||||
generatedBy: formatGeneratedBy(currentUser),
|
||||
};
|
||||
|
||||
const handleFetch = useCallback((params) => fetchArchivedLessons(params), [fetchArchivedLessons]);
|
||||
|
||||
const rowActions = useMemo(() => buildArchivedRowActions({
|
||||
onRestore: (row) => setRestoreTarget(row),
|
||||
onDelete: (row) => setDeleteTarget(row),
|
||||
}), []);
|
||||
|
||||
const toolbarActions = buildArchivedToolbarActions({
|
||||
fetchArchivedLessons,
|
||||
pagination,
|
||||
exportConfig,
|
||||
navigate,
|
||||
getFilters: () => tableRefsRef.current.getFilters(),
|
||||
getSort: () => tableRefsRef.current.getSort(),
|
||||
getTableInstance: () => tableRefsRef.current.tableInstance,
|
||||
});
|
||||
|
||||
const selectionActions = buildArchivedSelectionActions({
|
||||
exportConfig,
|
||||
onRestore: (row) => setRestoreTarget(row),
|
||||
onRestoreMany: (ids) => setRestoreIds(ids),
|
||||
onDelete: (row) => setDeleteTarget(row),
|
||||
onDeleteMany: (ids) => setDeleteIds(ids),
|
||||
getTableInstance: () => tableRefsRef.current.tableInstance,
|
||||
});
|
||||
|
||||
const columns = useMemo(
|
||||
() => buildDataColumns(attributes, rowActions),
|
||||
[attributes, rowActions]
|
||||
);
|
||||
|
||||
const refresh = () => {
|
||||
setRestoreTarget(null);
|
||||
setRestoreIds(null);
|
||||
setDeleteTarget(null);
|
||||
setDeleteIds(null);
|
||||
tableRefsRef.current.resetSelection?.();
|
||||
fetchArchivedLessons({ page: 1, limit: pagination?.limit ?? 10 });
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<DataTable
|
||||
title="Archived Lessons"
|
||||
data={lessons}
|
||||
columns={columns}
|
||||
attributes={attributes}
|
||||
pagination={pagination}
|
||||
setPagination={setPagination}
|
||||
loading={loading}
|
||||
onFetch={handleFetch}
|
||||
onFetchFilterData={(field) => fetchLessonFieldValues(field)}
|
||||
onRefsReady={handleRefsReady}
|
||||
renderFilterSheet={({ open, onOpenChange, column, attr, data, loading }) => (
|
||||
<FilterSheet
|
||||
open={open}
|
||||
onOpenChange={onOpenChange}
|
||||
column={column}
|
||||
attr={attr}
|
||||
data={data}
|
||||
loading={loading}
|
||||
/>
|
||||
)}
|
||||
columnPinning={columnPinning}
|
||||
toolbarActions={toolbarActions}
|
||||
selectionActions={selectionActions}
|
||||
recordLabel="lesson"
|
||||
emptyMessage="No archived lessons."
|
||||
/>
|
||||
|
||||
{/* ── Restore ── */}
|
||||
<RestoreDialog
|
||||
open={!!restoreTarget}
|
||||
onOpenChange={(v) => !v && setRestoreTarget(null)}
|
||||
entity={restoreTarget}
|
||||
entityLabel="Lesson"
|
||||
getName={(l) => l?.title}
|
||||
onRestore={(l) => restoreLesson(l?.lesson_id)}
|
||||
loading={loading}
|
||||
onSuccess={refresh}
|
||||
/>
|
||||
<RestoreDialog
|
||||
open={!!restoreIds}
|
||||
onOpenChange={(v) => !v && setRestoreIds(null)}
|
||||
ids={restoreIds ?? []}
|
||||
entityLabel="Lesson"
|
||||
onRestore={(ids) => restoreLessons(ids)}
|
||||
loading={loading}
|
||||
onSuccess={refresh}
|
||||
/>
|
||||
|
||||
{/* ── Permanent delete ── */}
|
||||
<PermanentDeleteDialog
|
||||
open={!!deleteTarget}
|
||||
onOpenChange={(v) => !v && setDeleteTarget(null)}
|
||||
entity={deleteTarget}
|
||||
entityLabel="Lesson"
|
||||
getName={(l) => l?.title}
|
||||
onDelete={(l) => permanentlyDeleteLesson(l?.lesson_id)}
|
||||
loading={loading}
|
||||
onSuccess={refresh}
|
||||
onImpactCheck={async () => {
|
||||
const impact = await fetchLessonPermanentDeleteImpact(deleteTarget?.lesson_id);
|
||||
const { unitCount } = impact?.data ?? impact ?? {};
|
||||
return [
|
||||
{ label: "unit attachment(s) will be removed", count: unitCount ?? 0 },
|
||||
];
|
||||
}}
|
||||
/>
|
||||
<PermanentDeleteDialog
|
||||
open={!!deleteIds}
|
||||
onOpenChange={(v) => !v && setDeleteIds(null)}
|
||||
ids={deleteIds ?? []}
|
||||
entityLabel="Lesson"
|
||||
onDelete={(ids) => permanentlyDeleteLessons(ids)}
|
||||
loading={loading}
|
||||
onSuccess={refresh}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
import { useMemo, useRef, useState, useCallback } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
|
||||
import { useLibrary } from "@/contexts/AdminLibraryContext";
|
||||
import { useAuth } from "@/contexts/AuthContext";
|
||||
|
||||
import DataTable from "@/components/generic/Table/DataTable";
|
||||
import { FilterSheet } from "@/components/generic/Sheet/FilterSheet";
|
||||
import { RestoreDialog } from "@/components/generic/Dialogs/RestoreDialog";
|
||||
import { PermanentDeleteDialog } from "@/components/generic/Dialogs/PermanentDeleteDialog";
|
||||
|
||||
import { buildDataColumns, columnPinning } from "../../config/library/units/columns.config";
|
||||
import { buildArchivedToolbarActions } from "../../config/library/units/toolbar.config";
|
||||
import { buildArchivedSelectionActions } from "../../config/library/units/selection.config";
|
||||
import { buildArchivedRowActions } from "../../config/library/units/rowActions.config";
|
||||
|
||||
import { getTimestamp } from "@/utils/timestamp.util";
|
||||
import { formatGeneratedBy } from "@/utils/generatedBy.util";
|
||||
|
||||
export default function ArchivedUnitLibraryTable() {
|
||||
const [restoreTarget, setRestoreTarget] = useState(null);
|
||||
const [restoreIds, setRestoreIds] = useState(null);
|
||||
const [deleteTarget, setDeleteTarget] = useState(null);
|
||||
const [deleteIds, setDeleteIds] = useState(null);
|
||||
|
||||
const tableRefsRef = useRef({
|
||||
getFilters: () => [],
|
||||
getSort: () => [],
|
||||
resetSelection: () => { },
|
||||
setFilters: () => { },
|
||||
});
|
||||
|
||||
const navigate = useNavigate();
|
||||
|
||||
const { user: currentUser } = useAuth();
|
||||
|
||||
const {
|
||||
units, attributes, pagination, setPagination, loading,
|
||||
fetchArchivedUnits, restoreUnit, restoreUnits,
|
||||
permanentlyDeleteUnit, permanentlyDeleteUnits,
|
||||
fetchUnitFieldValues, fetchUnitPermanentDeleteImpact,
|
||||
} = useLibrary();
|
||||
|
||||
const handleRefsReady = (refs) => {
|
||||
tableRefsRef.current = refs;
|
||||
};
|
||||
|
||||
const exportConfig = {
|
||||
allData: units,
|
||||
attributes,
|
||||
filename: `${getTimestamp()}_ArchivedUnitLibrary`,
|
||||
sheetName: "Archived Units",
|
||||
generatedBy: formatGeneratedBy(currentUser),
|
||||
};
|
||||
|
||||
const handleFetch = useCallback((params) => fetchArchivedUnits(params), [fetchArchivedUnits]);
|
||||
|
||||
const rowActions = useMemo(() => buildArchivedRowActions({
|
||||
onRestore: (row) => setRestoreTarget(row),
|
||||
onDelete: (row) => setDeleteTarget(row),
|
||||
}), []);
|
||||
|
||||
const toolbarActions = buildArchivedToolbarActions({
|
||||
fetchArchivedUnits,
|
||||
pagination,
|
||||
exportConfig,
|
||||
navigate,
|
||||
getFilters: () => tableRefsRef.current.getFilters(),
|
||||
getSort: () => tableRefsRef.current.getSort(),
|
||||
getTableInstance: () => tableRefsRef.current.tableInstance,
|
||||
});
|
||||
|
||||
const selectionActions = buildArchivedSelectionActions({
|
||||
exportConfig,
|
||||
onRestore: (row) => setRestoreTarget(row),
|
||||
onRestoreMany: (ids) => setRestoreIds(ids),
|
||||
onDelete: (row) => setDeleteTarget(row),
|
||||
onDeleteMany: (ids) => setDeleteIds(ids),
|
||||
getTableInstance: () => tableRefsRef.current.tableInstance,
|
||||
});
|
||||
|
||||
const columns = useMemo(
|
||||
() => buildDataColumns(attributes, rowActions),
|
||||
[attributes, rowActions]
|
||||
);
|
||||
|
||||
const refresh = () => {
|
||||
setRestoreTarget(null);
|
||||
setRestoreIds(null);
|
||||
setDeleteTarget(null);
|
||||
setDeleteIds(null);
|
||||
tableRefsRef.current.resetSelection?.();
|
||||
fetchArchivedUnits({ page: 1, limit: pagination?.limit ?? 10 });
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<DataTable
|
||||
title="Archived Units"
|
||||
data={units}
|
||||
columns={columns}
|
||||
attributes={attributes}
|
||||
pagination={pagination}
|
||||
setPagination={setPagination}
|
||||
loading={loading}
|
||||
onFetch={handleFetch}
|
||||
onFetchFilterData={(field) => fetchUnitFieldValues(field)}
|
||||
onRefsReady={handleRefsReady}
|
||||
renderFilterSheet={({ open, onOpenChange, column, attr, data, loading }) => (
|
||||
<FilterSheet
|
||||
open={open}
|
||||
onOpenChange={onOpenChange}
|
||||
column={column}
|
||||
attr={attr}
|
||||
data={data}
|
||||
loading={loading}
|
||||
/>
|
||||
)}
|
||||
columnPinning={columnPinning}
|
||||
toolbarActions={toolbarActions}
|
||||
selectionActions={selectionActions}
|
||||
recordLabel="unit"
|
||||
emptyMessage="No archived units."
|
||||
/>
|
||||
|
||||
{/* ── Restore ── */}
|
||||
<RestoreDialog
|
||||
open={!!restoreTarget}
|
||||
onOpenChange={(v) => !v && setRestoreTarget(null)}
|
||||
entity={restoreTarget}
|
||||
entityLabel="Unit"
|
||||
getName={(u) => u?.title}
|
||||
onRestore={(u) => restoreUnit(u?.unit_id)}
|
||||
loading={loading}
|
||||
onSuccess={refresh}
|
||||
/>
|
||||
<RestoreDialog
|
||||
open={!!restoreIds}
|
||||
onOpenChange={(v) => !v && setRestoreIds(null)}
|
||||
ids={restoreIds ?? []}
|
||||
entityLabel="Unit"
|
||||
onRestore={(ids) => restoreUnits(ids)}
|
||||
loading={loading}
|
||||
onSuccess={refresh}
|
||||
/>
|
||||
|
||||
{/* ── Permanent delete ── */}
|
||||
<PermanentDeleteDialog
|
||||
open={!!deleteTarget}
|
||||
onOpenChange={(v) => !v && setDeleteTarget(null)}
|
||||
entity={deleteTarget}
|
||||
entityLabel="Unit"
|
||||
getName={(u) => u?.title}
|
||||
onDelete={(u) => permanentlyDeleteUnit(u?.unit_id)}
|
||||
loading={loading}
|
||||
onSuccess={refresh}
|
||||
onImpactCheck={async () => {
|
||||
const impact = await fetchUnitPermanentDeleteImpact(deleteTarget?.unit_id);
|
||||
const { lessonCount, courseCount } = impact?.data ?? impact ?? {};
|
||||
return [
|
||||
{ label: "lesson attachment(s) will be removed", count: lessonCount ?? 0 },
|
||||
{ label: "course attachment(s) will be removed", count: courseCount ?? 0 },
|
||||
];
|
||||
}}
|
||||
/>
|
||||
<PermanentDeleteDialog
|
||||
open={!!deleteIds}
|
||||
onOpenChange={(v) => !v && setDeleteIds(null)}
|
||||
ids={deleteIds ?? []}
|
||||
entityLabel="Unit"
|
||||
onDelete={(ids) => permanentlyDeleteUnits(ids)}
|
||||
loading={loading}
|
||||
onSuccess={refresh}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
// AttachCoursesDialog — pick existing Courses and attach this Unit to them.
|
||||
// Mirror of AttachUnitsDialog, run in the opposite direction: a unit can be
|
||||
// attached to more than one course, so selection is multi-select here too.
|
||||
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { Search, Link2 } from "lucide-react";
|
||||
|
||||
import { useCourses } from "@/contexts/AdminCoursesContext";
|
||||
import {
|
||||
Dialog, DialogContent, DialogDescription, DialogFooter,
|
||||
DialogHeader, DialogTitle,
|
||||
} from "@/components/ui/dialog";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Checkbox } from "@/components/ui/checkbox";
|
||||
import { ScrollArea } from "@/components/ui/scroll-area";
|
||||
import { Spinner } from "@/components/ui/spinner";
|
||||
import { formatDuration } from "@/utils/timestamp.util";
|
||||
|
||||
export default function AttachCoursesDialog({ open, onOpenChange, attachedCourseIds = [], onAttach, loading }) {
|
||||
const { fetchCoursesFlat, loading: coursesLoading } = useCourses();
|
||||
const [courses, setCourses] = useState([]);
|
||||
const [query, setQuery] = useState("");
|
||||
const [selected, setSelected] = useState([]);
|
||||
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
setSelected([]);
|
||||
setQuery("");
|
||||
fetchCoursesFlat().then((c) => setCourses(c ?? []));
|
||||
}
|
||||
}, [open, fetchCoursesFlat]);
|
||||
|
||||
const attachedSet = useMemo(
|
||||
() => new Set(attachedCourseIds.map(String)),
|
||||
[attachedCourseIds]
|
||||
);
|
||||
|
||||
const candidates = useMemo(() => {
|
||||
const q = query.trim().toLowerCase();
|
||||
return (courses ?? [])
|
||||
.filter((c) => !attachedSet.has(String(c.course_id)))
|
||||
.filter((c) => !q || c.title?.toLowerCase().includes(q));
|
||||
}, [courses, attachedSet, query]);
|
||||
|
||||
const toggle = (courseId) =>
|
||||
setSelected((prev) =>
|
||||
prev.includes(courseId) ? prev.filter((id) => id !== courseId) : [...prev, courseId]
|
||||
);
|
||||
|
||||
const handleAttach = async () => {
|
||||
if (!selected.length) return;
|
||||
await onAttach(selected);
|
||||
onOpenChange(false);
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="sm:max-w-lg">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<Link2 className="h-4 w-4" /> Select Courses
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
Attach this unit to one or more existing courses without copying it.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="relative">
|
||||
<Search className="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
|
||||
<Input
|
||||
placeholder="Search courses..."
|
||||
className="pl-8"
|
||||
value={query}
|
||||
onChange={(e) => setQuery(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<ScrollArea className="h-64 rounded-md border">
|
||||
{coursesLoading ? (
|
||||
<div className="flex items-center justify-center h-full py-10">
|
||||
<Spinner className="h-5 w-5" />
|
||||
</div>
|
||||
) : candidates.length === 0 ? (
|
||||
<p className="text-sm text-muted-foreground text-center py-10">
|
||||
{query ? "No courses match your search." : "This unit is already attached to every course."}
|
||||
</p>
|
||||
) : (
|
||||
<div className="divide-y">
|
||||
{candidates.map((c) => (
|
||||
<label
|
||||
key={c.course_id}
|
||||
className="flex items-center gap-3 px-3 py-2.5 hover:bg-muted/60 cursor-pointer"
|
||||
>
|
||||
<Checkbox
|
||||
checked={selected.includes(c.course_id)}
|
||||
onCheckedChange={() => toggle(c.course_id)}
|
||||
/>
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="text-sm font-medium w-64 truncate" title={c.title}>
|
||||
{c.title}
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground truncate">
|
||||
{formatDuration(c.duration_seconds ?? 0)}
|
||||
</p>
|
||||
</div>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</ScrollArea>
|
||||
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => onOpenChange(false)} disabled={loading}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button onClick={handleAttach} disabled={loading || !selected.length}>
|
||||
{loading && <Spinner className="h-4 w-4 mr-2" />}
|
||||
Attach {selected.length > 0 ? `(${selected.length})` : ""}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
// AttachLessonToUnitsDialog — pick existing Units and attach this Lesson to them.
|
||||
// Reverse direction of AttachLessonsDialog: unit_lessons has no exclusivity,
|
||||
// so a Lesson can freely belong to several Units at once (multi-select).
|
||||
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { Search, Link2 } from "lucide-react";
|
||||
|
||||
import { useLibrary } from "@/contexts/AdminLibraryContext";
|
||||
import {
|
||||
Dialog, DialogContent, DialogDescription, DialogFooter,
|
||||
DialogHeader, DialogTitle,
|
||||
} from "@/components/ui/dialog";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Checkbox } from "@/components/ui/checkbox";
|
||||
import { ScrollArea } from "@/components/ui/scroll-area";
|
||||
import { Spinner } from "@/components/ui/spinner";
|
||||
import { formatDuration } from "@/utils/timestamp.util";
|
||||
|
||||
export default function AttachLessonToUnitsDialog({ open, onOpenChange, attachedUnitIds = [], onAttach, loading }) {
|
||||
const { unitsFlat, fetchUnitsFlat, loading: libraryLoading } = useLibrary();
|
||||
const [query, setQuery] = useState("");
|
||||
const [selected, setSelected] = useState([]);
|
||||
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
setSelected([]);
|
||||
setQuery("");
|
||||
fetchUnitsFlat();
|
||||
}
|
||||
}, [open, fetchUnitsFlat]);
|
||||
|
||||
const attachedSet = useMemo(
|
||||
() => new Set(attachedUnitIds.map(String)),
|
||||
[attachedUnitIds]
|
||||
);
|
||||
|
||||
const candidates = useMemo(() => {
|
||||
const q = query.trim().toLowerCase();
|
||||
return (unitsFlat ?? [])
|
||||
.filter((u) => !attachedSet.has(String(u.unit_id)))
|
||||
.filter((u) => !q || u.title?.toLowerCase().includes(q));
|
||||
}, [unitsFlat, attachedSet, query]);
|
||||
|
||||
const toggle = (unitId) =>
|
||||
setSelected((prev) =>
|
||||
prev.includes(unitId) ? prev.filter((id) => id !== unitId) : [...prev, unitId]
|
||||
);
|
||||
|
||||
const handleAttach = async () => {
|
||||
if (!selected.length) return;
|
||||
await onAttach(selected);
|
||||
onOpenChange(false);
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="sm:max-w-lg">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<Link2 className="h-4 w-4" /> Select Units
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
Attach this lesson to one or more existing units without copying it.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="relative">
|
||||
<Search className="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
|
||||
<Input
|
||||
placeholder="Search units..."
|
||||
className="pl-8"
|
||||
value={query}
|
||||
onChange={(e) => setQuery(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<ScrollArea className="h-64 rounded-md border">
|
||||
{libraryLoading ? (
|
||||
<div className="flex items-center justify-center h-full py-10">
|
||||
<Spinner className="h-5 w-5" />
|
||||
</div>
|
||||
) : candidates.length === 0 ? (
|
||||
<p className="text-sm text-muted-foreground text-center py-10">
|
||||
{query ? "No units match your search." : "This lesson is already attached to every unit."}
|
||||
</p>
|
||||
) : (
|
||||
<div className="divide-y">
|
||||
{candidates.map((u) => (
|
||||
<label
|
||||
key={u.unit_id}
|
||||
className="flex items-center gap-3 px-3 py-2.5 hover:bg-muted/60 cursor-pointer"
|
||||
>
|
||||
<Checkbox
|
||||
checked={selected.includes(u.unit_id)}
|
||||
onCheckedChange={() => toggle(u.unit_id)}
|
||||
/>
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="text-sm font-medium w-64 truncate" title={u.title}>
|
||||
{u.title}
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground truncate">
|
||||
{formatDuration(u.duration_seconds ?? 0)}
|
||||
</p>
|
||||
</div>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</ScrollArea>
|
||||
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => onOpenChange(false)} disabled={loading}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button onClick={handleAttach} disabled={loading || !selected.length}>
|
||||
{loading && <Spinner className="h-4 w-4 mr-2" />}
|
||||
Attach {selected.length > 0 ? `(${selected.length})` : ""}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
// AttachLessonsDialog — pick existing library Lessons and attach them to a Unit.
|
||||
// Junction revamp: attaching creates unit_lessons rows; the Lessons stay standalone.
|
||||
//
|
||||
// Clicking a row previews that lesson's existing Page Builder blocks on the right,
|
||||
// independent of the checkbox — so admins can see what they're attaching before
|
||||
// committing. Preview fetches go through `api` directly rather than the shared
|
||||
// AdminLibraryContext `fetchLesson`, since that setter writes into a single global
|
||||
// `lesson` slot that other mounted pages may depend on.
|
||||
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { Search, Link2, Eye } from "lucide-react";
|
||||
|
||||
import { useLibrary } from "@/contexts/AdminLibraryContext";
|
||||
import api from "@/utils/api.util";
|
||||
import {
|
||||
Dialog, DialogContent, DialogDescription, DialogFooter,
|
||||
DialogHeader, DialogTitle,
|
||||
} from "@/components/ui/dialog";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Checkbox } from "@/components/ui/checkbox";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { ScrollArea } from "@/components/ui/scroll-area";
|
||||
import { Spinner } from "@/components/ui/spinner";
|
||||
import { formatDuration } from "@/utils/timestamp.util";
|
||||
import { PreviewChrome, PreviewContent } from "../courses/LessonsPreview";
|
||||
|
||||
export default function AttachLessonsDialog({ open, onOpenChange, attachedLessonIds = [], onAttach, loading }) {
|
||||
const { lessonsFlat, fetchLessonsFlat, loading: libraryLoading } = useLibrary();
|
||||
const [query, setQuery] = useState("");
|
||||
const [selected, setSelected] = useState([]);
|
||||
|
||||
const [previewLessonId, setPreviewLessonId] = useState(null);
|
||||
const [previewLoading, setPreviewLoading] = useState(false);
|
||||
const [previewCache, setPreviewCache] = useState({});
|
||||
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
setSelected([]);
|
||||
setQuery("");
|
||||
setPreviewLessonId(null);
|
||||
setPreviewCache({});
|
||||
fetchLessonsFlat();
|
||||
}
|
||||
}, [open, fetchLessonsFlat]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!previewLessonId || previewLessonId in previewCache) return;
|
||||
let cancelled = false;
|
||||
setPreviewLoading(true);
|
||||
api.get(`/admin/lessons/${previewLessonId}`)
|
||||
.then((resp) => {
|
||||
if (cancelled) return;
|
||||
setPreviewCache((prev) => ({ ...prev, [previewLessonId]: resp.data?.data?.data ?? null }));
|
||||
})
|
||||
.catch(() => {
|
||||
if (cancelled) return;
|
||||
setPreviewCache((prev) => ({ ...prev, [previewLessonId]: null }));
|
||||
})
|
||||
.finally(() => {
|
||||
if (!cancelled) setPreviewLoading(false);
|
||||
});
|
||||
return () => { cancelled = true; };
|
||||
}, [previewLessonId, previewCache]);
|
||||
|
||||
const previewLesson = previewLessonId ? previewCache[previewLessonId] : null;
|
||||
const previewBlocks = previewLesson?.page?.blocks ?? [];
|
||||
|
||||
const attachedSet = useMemo(
|
||||
() => new Set(attachedLessonIds.map(String)),
|
||||
[attachedLessonIds]
|
||||
);
|
||||
|
||||
const candidates = useMemo(() => {
|
||||
const q = query.trim().toLowerCase();
|
||||
return (lessonsFlat ?? [])
|
||||
.filter((l) => !attachedSet.has(String(l.lesson_id)))
|
||||
.filter((l) => !q || l.title?.toLowerCase().includes(q));
|
||||
}, [lessonsFlat, attachedSet, query]);
|
||||
|
||||
const toggle = (lessonId) =>
|
||||
setSelected((prev) =>
|
||||
prev.includes(lessonId) ? prev.filter((id) => id !== lessonId) : [...prev, lessonId]
|
||||
);
|
||||
|
||||
const handleAttach = async () => {
|
||||
if (!selected.length) return;
|
||||
await onAttach(selected);
|
||||
onOpenChange(false);
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="sm:max-w-3xl">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<Link2 className="h-4 w-4" /> Select Lessons
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
Lessons live independently in the library — attaching adds them to this unit without copying.
|
||||
Click a lesson to preview its content.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="grid gap-4 sm:grid-cols-[280px_1fr]">
|
||||
<div className="space-y-2 min-w-0">
|
||||
<div className="relative">
|
||||
<Search className="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
|
||||
<Input
|
||||
placeholder="Search lessons..."
|
||||
className="pl-8"
|
||||
value={query}
|
||||
onChange={(e) => setQuery(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<ScrollArea className="h-80 rounded-md border">
|
||||
{libraryLoading ? (
|
||||
<div className="flex items-center justify-center h-full py-10">
|
||||
<Spinner className="h-5 w-5" />
|
||||
</div>
|
||||
) : candidates.length === 0 ? (
|
||||
<p className="text-sm text-muted-foreground text-center py-10 px-3">
|
||||
{query ? "No lessons match your search." : "Every library lesson is already attached."}
|
||||
</p>
|
||||
) : (
|
||||
<div className="divide-y">
|
||||
{candidates.map((l) => (
|
||||
<div
|
||||
key={l.lesson_id}
|
||||
onClick={() => {
|
||||
toggle(l.lesson_id);
|
||||
setPreviewLessonId(l.lesson_id);
|
||||
}}
|
||||
className={`flex items-center gap-3 px-3 py-2.5 cursor-pointer select-none hover:bg-muted/60 ${
|
||||
previewLessonId === l.lesson_id ? "bg-muted" : ""
|
||||
}`}
|
||||
>
|
||||
<Checkbox
|
||||
checked={selected.includes(l.lesson_id)}
|
||||
onCheckedChange={() => {
|
||||
toggle(l.lesson_id);
|
||||
setPreviewLessonId(l.lesson_id);
|
||||
}}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
/>
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="text-sm font-medium truncate">{l.title}</p>
|
||||
<p className="text-xs text-muted-foreground truncate">
|
||||
{formatDuration(l.duration_seconds ?? 0)}
|
||||
</p>
|
||||
</div>
|
||||
{Number(l.unit_count) > 0 ? (
|
||||
<Badge variant="secondary" className="text-xs shrink-0">
|
||||
{l.unit_count}
|
||||
</Badge>
|
||||
) : (
|
||||
<Badge variant="outline" className="text-xs shrink-0 text-muted-foreground">new</Badge>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</ScrollArea>
|
||||
</div>
|
||||
|
||||
<div className="min-w-0">
|
||||
<ScrollArea className="h-80 rounded-md border">
|
||||
<div className="p-3">
|
||||
{!previewLessonId ? (
|
||||
<div className="flex flex-col items-center justify-center gap-2 h-64 text-sm text-muted-foreground">
|
||||
<Eye className="h-6 w-6 opacity-20" />
|
||||
<p>Click a lesson to preview its content.</p>
|
||||
</div>
|
||||
) : previewLoading ? (
|
||||
<div className="flex items-center justify-center h-64">
|
||||
<Spinner className="h-5 w-5" />
|
||||
</div>
|
||||
) : (
|
||||
<PreviewChrome title={previewLesson?.title}>
|
||||
<PreviewContent
|
||||
lesson={previewLesson}
|
||||
blocks={previewBlocks}
|
||||
showHeader={false}
|
||||
empty="No content blocks yet."
|
||||
/>
|
||||
</PreviewChrome>
|
||||
)}
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => onOpenChange(false)} disabled={loading}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button onClick={handleAttach} disabled={loading || !selected.length}>
|
||||
{loading && <Spinner className="h-4 w-4 mr-2" />}
|
||||
Select {selected.length > 0 ? `(${selected.length})` : ""}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
// AttachUnitsDialog — pick existing library Units and attach them to a Course.
|
||||
// Junction revamp: attaching creates course_units rows; the Units stay standalone.
|
||||
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { Search, Link2 } from "lucide-react";
|
||||
|
||||
import { useLibrary } from "@/contexts/AdminLibraryContext";
|
||||
import {
|
||||
Dialog, DialogContent, DialogDescription, DialogFooter,
|
||||
DialogHeader, DialogTitle,
|
||||
} from "@/components/ui/dialog";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Checkbox } from "@/components/ui/checkbox";
|
||||
import { ScrollArea } from "@/components/ui/scroll-area";
|
||||
import { Spinner } from "@/components/ui/spinner";
|
||||
import { formatDuration } from "@/utils/timestamp.util";
|
||||
|
||||
export default function AttachUnitsDialog({ open, onOpenChange, attachedUnitIds = [], onAttach, loading }) {
|
||||
const { unitsFlat, fetchUnitsFlat, loading: libraryLoading } = useLibrary();
|
||||
const [query, setQuery] = useState("");
|
||||
const [selected, setSelected] = useState([]);
|
||||
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
setSelected([]);
|
||||
setQuery("");
|
||||
fetchUnitsFlat();
|
||||
}
|
||||
}, [open, fetchUnitsFlat]);
|
||||
|
||||
const attachedSet = useMemo(
|
||||
() => new Set(attachedUnitIds.map(String)),
|
||||
[attachedUnitIds]
|
||||
);
|
||||
|
||||
const candidates = useMemo(() => {
|
||||
const q = query.trim().toLowerCase();
|
||||
return (unitsFlat ?? [])
|
||||
.filter((u) => !attachedSet.has(String(u.unit_id)))
|
||||
.filter((u) => !q || u.title?.toLowerCase().includes(q));
|
||||
}, [unitsFlat, attachedSet, query]);
|
||||
|
||||
const toggle = (unitId) => {
|
||||
setSelected((prev) =>
|
||||
prev.includes(unitId) ? prev.filter((id) => id !== unitId) : [...prev, unitId]
|
||||
);
|
||||
};
|
||||
|
||||
const duplicatingCount = useMemo(
|
||||
() => candidates.filter((u) => selected.includes(u.unit_id) && Number(u.course_count) > 0).length,
|
||||
[candidates, selected]
|
||||
);
|
||||
|
||||
const handleAttach = async () => {
|
||||
if (!selected.length) return;
|
||||
await onAttach(selected);
|
||||
onOpenChange(false);
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="sm:max-w-lg">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<Link2 className="h-4 w-4" /> Select Units
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
Units live independently in the library — attaching adds them to this course without copying.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="relative">
|
||||
<Search className="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
|
||||
<Input
|
||||
placeholder="Search units..."
|
||||
className="pl-8"
|
||||
value={query}
|
||||
onChange={(e) => setQuery(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<ScrollArea className="h-64 rounded-md border">
|
||||
{libraryLoading ? (
|
||||
<div className="flex items-center justify-center h-full py-10">
|
||||
<Spinner className="h-5 w-5" />
|
||||
</div>
|
||||
) : candidates.length === 0 ? (
|
||||
<p className="text-sm text-muted-foreground text-center py-10">
|
||||
{query ? "No units match your search." : "Every library unit is already attached."}
|
||||
</p>
|
||||
) : (
|
||||
<div className="divide-y">
|
||||
{candidates.map((u) => {
|
||||
const blocked = Number(u.course_count) > 0;
|
||||
const isSelected = selected.includes(u.unit_id);
|
||||
return (
|
||||
<label
|
||||
key={u.unit_id}
|
||||
title={blocked ? `Currently in "${u.course_title}" — selecting it will attach a copy to this course.` : undefined}
|
||||
className="flex items-center gap-3 px-3 py-2.5 hover:bg-muted/60 cursor-pointer"
|
||||
>
|
||||
<Checkbox
|
||||
checked={isSelected}
|
||||
onCheckedChange={() => toggle(u.unit_id)}
|
||||
/>
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="text-sm font-medium w-64 truncate" title={u.title}>
|
||||
{u.title}
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground truncate">
|
||||
{u.lesson_count ?? 0} lesson{(u.lesson_count ?? 0) === 1 ? "" : "s"} · {formatDuration(u.duration_seconds ?? 0)}
|
||||
</p>
|
||||
</div>
|
||||
</label>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</ScrollArea>
|
||||
|
||||
{duplicatingCount > 0 && (
|
||||
<p className="text-xs text-amber-700 dark:text-amber-400">
|
||||
{duplicatingCount} of the selected unit{duplicatingCount !== 1 ? "s are" : " is"} already in another course
|
||||
— attaching will create {duplicatingCount !== 1 ? "copies" : "a copy"} of {duplicatingCount !== 1 ? "them" : "it"} here.
|
||||
</p>
|
||||
)}
|
||||
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => onOpenChange(false)} disabled={loading}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button onClick={handleAttach} disabled={loading || !selected.length}>
|
||||
{loading && <Spinner className="h-4 w-4 mr-2" />}
|
||||
{duplicatingCount > 0 ? "Attach & Duplicate" : "Attach"} {selected.length > 0 ? `(${selected.length})` : ""}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
import { useMemo, useRef, useState, useCallback, useEffect } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
|
||||
import { useLibrary } from "@/contexts/AdminLibraryContext";
|
||||
import { useAuth } from "@/contexts/AuthContext";
|
||||
|
||||
import DataTable from "@/components/generic/Table/DataTable";
|
||||
import { FilterSheet } from "@/components/generic/Sheet/FilterSheet";
|
||||
import { ArchiveDialog } from "@/components/generic/Dialogs/ArchiveDialog";
|
||||
|
||||
import { buildDataColumns, columnPinning } from "../../config/library/lessons/columns.config";
|
||||
import { buildToolbarActions } from "../../config/library/lessons/toolbar.config";
|
||||
import { buildSelectionActions } from "../../config/library/lessons/selection.config";
|
||||
import { buildRowActions } from "../../config/library/lessons/rowActions.config";
|
||||
|
||||
import api from "@/utils/api.util";
|
||||
import { getTimestamp } from "@/utils/timestamp.util";
|
||||
import { formatGeneratedBy } from "@/utils/generatedBy.util";
|
||||
|
||||
export default function LessonLibraryTable() {
|
||||
const [archiveTarget, setArchiveTarget] = useState(null);
|
||||
const [archiveIds, setArchiveIds] = useState(null);
|
||||
|
||||
const tableRefsRef = useRef({
|
||||
getFilters: () => [],
|
||||
getSort: () => [],
|
||||
resetSelection: () => { },
|
||||
setFilters: () => { },
|
||||
});
|
||||
|
||||
const navigate = useNavigate();
|
||||
|
||||
const { user: currentUser } = useAuth();
|
||||
|
||||
const {
|
||||
lessons, attributes, pagination, setPagination, loading,
|
||||
fetchLessons, archiveLesson, archiveLessons,
|
||||
fetchLessonFieldValues,
|
||||
} = useLibrary();
|
||||
|
||||
const handleRefsReady = (refs) => {
|
||||
tableRefsRef.current = refs;
|
||||
};
|
||||
|
||||
const [tierCategories, setTierCategories] = useState([]);
|
||||
useEffect(() => {
|
||||
api.get("/admin/tiers/categories")
|
||||
.then(({ data }) => setTierCategories(data.data ?? []))
|
||||
.catch(() => {});
|
||||
}, []);
|
||||
const tierMap = useMemo(
|
||||
() => Object.fromEntries(tierCategories.map((c) => [c.slug, c])),
|
||||
[tierCategories]
|
||||
);
|
||||
|
||||
const exportConfig = {
|
||||
allData: lessons,
|
||||
attributes,
|
||||
filename: `${getTimestamp()}_LessonLibrary`,
|
||||
sheetName: "Lessons",
|
||||
generatedBy: formatGeneratedBy(currentUser),
|
||||
};
|
||||
|
||||
const handleFetch = useCallback((params) => fetchLessons(params), [fetchLessons]);
|
||||
|
||||
const rowActions = useMemo(() => buildRowActions({
|
||||
onView: (row) => navigate(`/admin/lessons/${row.lesson_id}/view`),
|
||||
onEdit: (row) => navigate(`/admin/lessons/${row.lesson_id}/edit`),
|
||||
onBuildPage: (row) => navigate(`/admin/lessons/${row.lesson_id}/page`),
|
||||
onViewPage: (row) => navigate(`/admin/lessons/${row.lesson_id}/page/view`),
|
||||
onArchive: (row) => setArchiveTarget(row),
|
||||
}), [navigate]);
|
||||
|
||||
const toolbarActions = buildToolbarActions({
|
||||
fetchLessons,
|
||||
pagination,
|
||||
exportConfig,
|
||||
navigate,
|
||||
getFilters: () => tableRefsRef.current.getFilters(),
|
||||
getSort: () => tableRefsRef.current.getSort(),
|
||||
getTableInstance: () => tableRefsRef.current.tableInstance,
|
||||
});
|
||||
|
||||
const selectionActions = buildSelectionActions({
|
||||
exportConfig,
|
||||
onArchive: (row) => setArchiveTarget(row),
|
||||
onArchiveMany: (ids) => setArchiveIds(ids),
|
||||
getTableInstance: () => tableRefsRef.current.tableInstance,
|
||||
});
|
||||
|
||||
const columns = useMemo(
|
||||
() => buildDataColumns(attributes, rowActions, tierMap),
|
||||
[attributes, rowActions, tierMap]
|
||||
);
|
||||
|
||||
const handleArchiveSuccess = () => {
|
||||
setArchiveTarget(null);
|
||||
setArchiveIds(null);
|
||||
tableRefsRef.current.resetSelection?.();
|
||||
fetchLessons({ page: 1, limit: pagination?.limit ?? 10 });
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<DataTable
|
||||
title="Lesson Library"
|
||||
data={lessons}
|
||||
columns={columns}
|
||||
attributes={attributes}
|
||||
pagination={pagination}
|
||||
setPagination={setPagination}
|
||||
loading={loading}
|
||||
onFetch={handleFetch}
|
||||
onFetchFilterData={(field) => fetchLessonFieldValues(field)}
|
||||
onRefsReady={handleRefsReady}
|
||||
renderFilterSheet={({ open, onOpenChange, column, attr, data, loading }) => (
|
||||
<FilterSheet
|
||||
open={open}
|
||||
onOpenChange={onOpenChange}
|
||||
column={column}
|
||||
attr={attr}
|
||||
data={data}
|
||||
loading={loading}
|
||||
/>
|
||||
)}
|
||||
columnPinning={columnPinning}
|
||||
toolbarActions={toolbarActions}
|
||||
selectionActions={selectionActions}
|
||||
recordLabel="lesson"
|
||||
emptyMessage="No lessons in the library yet."
|
||||
/>
|
||||
|
||||
{/* ── Single archive ── */}
|
||||
<ArchiveDialog
|
||||
open={!!archiveTarget}
|
||||
onOpenChange={(v) => !v && setArchiveTarget(null)}
|
||||
entity={archiveTarget}
|
||||
entityLabel="Lesson"
|
||||
getName={(l) => l?.title}
|
||||
onArchive={(l) => archiveLesson(l?.lesson_id)}
|
||||
loading={loading}
|
||||
onSuccess={handleArchiveSuccess}
|
||||
/>
|
||||
|
||||
{/* ── Bulk archive ── */}
|
||||
<ArchiveDialog
|
||||
open={!!archiveIds}
|
||||
onOpenChange={(v) => !v && setArchiveIds(null)}
|
||||
ids={archiveIds ?? []}
|
||||
entityLabel="Lesson"
|
||||
onArchive={(ids) => archiveLessons(ids)}
|
||||
loading={loading}
|
||||
onSuccess={handleArchiveSuccess}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
import { useMemo, useRef, useState, useCallback, useEffect } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
|
||||
import { useLibrary } from "@/contexts/AdminLibraryContext";
|
||||
import { useAuth } from "@/contexts/AuthContext";
|
||||
|
||||
import DataTable from "@/components/generic/Table/DataTable";
|
||||
import { FilterSheet } from "@/components/generic/Sheet/FilterSheet";
|
||||
import { ArchiveDialog } from "@/components/generic/Dialogs/ArchiveDialog";
|
||||
|
||||
import { buildDataColumns, columnPinning } from "../../config/library/units/columns.config";
|
||||
import { buildToolbarActions } from "../../config/library/units/toolbar.config";
|
||||
import { buildSelectionActions } from "../../config/library/units/selection.config";
|
||||
import { buildRowActions } from "../../config/library/units/rowActions.config";
|
||||
|
||||
import api from "@/utils/api.util";
|
||||
import { getTimestamp } from "@/utils/timestamp.util";
|
||||
import { formatGeneratedBy } from "@/utils/generatedBy.util";
|
||||
|
||||
export default function UnitLibraryTable() {
|
||||
const [archiveTarget, setArchiveTarget] = useState(null);
|
||||
const [archiveIds, setArchiveIds] = useState(null);
|
||||
|
||||
const tableRefsRef = useRef({
|
||||
getFilters: () => [],
|
||||
getSort: () => [],
|
||||
resetSelection: () => { },
|
||||
setFilters: () => { },
|
||||
});
|
||||
|
||||
const navigate = useNavigate();
|
||||
|
||||
const { user: currentUser } = useAuth();
|
||||
|
||||
const {
|
||||
units, attributes, pagination, setPagination, loading,
|
||||
fetchUnits, archiveUnit, archiveUnits,
|
||||
fetchUnitFieldValues, fetchUnitArchiveImpact,
|
||||
} = useLibrary();
|
||||
|
||||
const handleRefsReady = (refs) => {
|
||||
tableRefsRef.current = refs;
|
||||
};
|
||||
|
||||
const [tierCategories, setTierCategories] = useState([]);
|
||||
useEffect(() => {
|
||||
api.get("/admin/tiers/categories")
|
||||
.then(({ data }) => setTierCategories(data.data ?? []))
|
||||
.catch(() => {});
|
||||
}, []);
|
||||
const tierMap = useMemo(
|
||||
() => Object.fromEntries(tierCategories.map((c) => [c.slug, c])),
|
||||
[tierCategories]
|
||||
);
|
||||
|
||||
const exportConfig = {
|
||||
allData: units,
|
||||
attributes,
|
||||
filename: `${getTimestamp()}_UnitLibrary`,
|
||||
sheetName: "Units",
|
||||
generatedBy: formatGeneratedBy(currentUser),
|
||||
};
|
||||
|
||||
const handleFetch = useCallback((params) => fetchUnits(params), [fetchUnits]);
|
||||
|
||||
const rowActions = useMemo(() => buildRowActions({
|
||||
onView: (row) => navigate(`/admin/units/${row.unit_id}/view`),
|
||||
onEdit: (row) => navigate(`/admin/units/${row.unit_id}/edit`),
|
||||
onManageLessons: (row) => navigate(`/admin/units/${row.unit_id}/view`),
|
||||
onQuiz: (row) => navigate(`/admin/units/${row.unit_id}/quiz/edit`),
|
||||
onViewQuiz: (row) => navigate(`/admin/units/${row.unit_id}/quiz/view`),
|
||||
onArchive: (row) => setArchiveTarget(row),
|
||||
}), [navigate]);
|
||||
|
||||
const toolbarActions = buildToolbarActions({
|
||||
fetchUnits,
|
||||
pagination,
|
||||
exportConfig,
|
||||
navigate,
|
||||
getFilters: () => tableRefsRef.current.getFilters(),
|
||||
getSort: () => tableRefsRef.current.getSort(),
|
||||
getTableInstance: () => tableRefsRef.current.tableInstance,
|
||||
});
|
||||
|
||||
const selectionActions = buildSelectionActions({
|
||||
exportConfig,
|
||||
onArchive: (row) => setArchiveTarget(row),
|
||||
onArchiveMany: (ids) => setArchiveIds(ids),
|
||||
getTableInstance: () => tableRefsRef.current.tableInstance,
|
||||
});
|
||||
|
||||
const columns = useMemo(
|
||||
() => buildDataColumns(attributes, rowActions, tierMap),
|
||||
[attributes, rowActions, tierMap]
|
||||
);
|
||||
|
||||
const handleArchiveSuccess = () => {
|
||||
setArchiveTarget(null);
|
||||
setArchiveIds(null);
|
||||
tableRefsRef.current.resetSelection?.();
|
||||
fetchUnits({ page: 1, limit: pagination?.limit ?? 10 });
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<DataTable
|
||||
title="Unit Library"
|
||||
data={units}
|
||||
columns={columns}
|
||||
attributes={attributes}
|
||||
pagination={pagination}
|
||||
setPagination={setPagination}
|
||||
loading={loading}
|
||||
onFetch={handleFetch}
|
||||
onFetchFilterData={(field) => fetchUnitFieldValues(field)}
|
||||
onRefsReady={handleRefsReady}
|
||||
renderFilterSheet={({ open, onOpenChange, column, attr, data, loading }) => (
|
||||
<FilterSheet
|
||||
open={open}
|
||||
onOpenChange={onOpenChange}
|
||||
column={column}
|
||||
attr={attr}
|
||||
data={data}
|
||||
loading={loading}
|
||||
/>
|
||||
)}
|
||||
columnPinning={columnPinning}
|
||||
toolbarActions={toolbarActions}
|
||||
selectionActions={selectionActions}
|
||||
recordLabel="unit"
|
||||
emptyMessage="No units in the library yet."
|
||||
/>
|
||||
|
||||
{/* ── Single archive ── */}
|
||||
<ArchiveDialog
|
||||
open={!!archiveTarget}
|
||||
onOpenChange={(v) => !v && setArchiveTarget(null)}
|
||||
entity={archiveTarget}
|
||||
entityLabel="Unit"
|
||||
getName={(u) => u?.title}
|
||||
onArchive={(u) => archiveUnit(u?.unit_id)}
|
||||
loading={loading}
|
||||
onSuccess={handleArchiveSuccess}
|
||||
onImpactCheck={async () => {
|
||||
const impact = await fetchUnitArchiveImpact(archiveTarget?.unit_id);
|
||||
const { completionCount, progressCount, courseCount } = impact?.data ?? impact ?? {};
|
||||
return [
|
||||
{ label: "student(s) have completed this unit", count: completionCount ?? 0 },
|
||||
{ label: "student(s) have reading progress in this unit", count: progressCount ?? 0 },
|
||||
{ label: "course(s) currently include this unit", count: courseCount ?? 0 },
|
||||
];
|
||||
}}
|
||||
/>
|
||||
|
||||
{/* ── Bulk archive ── */}
|
||||
<ArchiveDialog
|
||||
open={!!archiveIds}
|
||||
onOpenChange={(v) => !v && setArchiveIds(null)}
|
||||
ids={archiveIds ?? []}
|
||||
entityLabel="Unit"
|
||||
onArchive={(ids) => archiveUnits(ids)}
|
||||
loading={loading}
|
||||
onSuccess={handleArchiveSuccess}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
+179
@@ -0,0 +1,179 @@
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
|
||||
import { useNotificationBroadcasts } from "@/contexts/AdminNotificationBroadcastContext";
|
||||
import { useAuth } from "@/contexts/AuthContext";
|
||||
|
||||
import DataTable from "@/components/generic/Table/DataTable";
|
||||
import { FilterSheet } from "@/components/generic/Sheet/FilterSheet";
|
||||
import { RestoreDialog } from "@/components/generic/Dialogs/RestoreDialog";
|
||||
import { PermanentDeleteDialog } from "@/components/generic/Dialogs/PermanentDeleteDialog";
|
||||
|
||||
import { buildDataColumns, columnPinning } from "../../config/notifications/archive/columns.config";
|
||||
import { buildToolbarActions } from "../../config/notifications/archive/toolbar.config";
|
||||
import { buildRowActions } from "../../config/notifications/archive/rowActions.config";
|
||||
import { buildSelectionActions } from "../../config/notifications/archive/selection.config";
|
||||
|
||||
import { getTimestamp } from "@/utils/timestamp.util";
|
||||
import { formatGeneratedBy } from "@/utils/generatedBy.util";
|
||||
|
||||
export default function ArchivedNotificationBroadcastsTable() {
|
||||
const [restoreTarget, setRestoreTarget] = useState(null);
|
||||
const [restoreIds, setRestoreIds] = useState(null);
|
||||
const [deleteTarget, setDeleteTarget] = useState(null);
|
||||
const [deleteIds, setDeleteIds] = useState(null);
|
||||
|
||||
const tableRefsRef = useRef({
|
||||
getFilters: () => [],
|
||||
getSort: () => [],
|
||||
resetSelection: () => {},
|
||||
setFilters: () => {},
|
||||
});
|
||||
|
||||
const navigate = useNavigate();
|
||||
|
||||
const { user: currentUser } = useAuth();
|
||||
|
||||
const {
|
||||
broadcasts, attributes, pagination, setPagination, loading,
|
||||
fetchArchivedBroadcasts, restoreBroadcast, restoreBroadcasts,
|
||||
permanentlyDeleteBroadcast, permanentlyDeleteBroadcasts,
|
||||
} = useNotificationBroadcasts();
|
||||
|
||||
useEffect(() => {
|
||||
fetchArchivedBroadcasts({ page: 1, limit: pagination?.limit ?? 10 });
|
||||
}, []);
|
||||
|
||||
const handleRefsReady = (refs) => {
|
||||
tableRefsRef.current = refs;
|
||||
};
|
||||
|
||||
const exportConfig = {
|
||||
allData: broadcasts,
|
||||
attributes,
|
||||
filename: `${getTimestamp()}_ArchivedNotificationBroadcasts`,
|
||||
sheetName: "Archived Alerts",
|
||||
generatedBy: formatGeneratedBy(currentUser),
|
||||
};
|
||||
|
||||
const rowActions = buildRowActions({
|
||||
onRestore: (row) => setRestoreTarget(row),
|
||||
onDelete: (row) => setDeleteTarget(row),
|
||||
});
|
||||
|
||||
const toolbarActions = buildToolbarActions({
|
||||
fetchBroadcasts: fetchArchivedBroadcasts,
|
||||
pagination,
|
||||
exportConfig,
|
||||
navigate,
|
||||
getFilters: () => tableRefsRef.current.getFilters(),
|
||||
getSort: () => tableRefsRef.current.getSort(),
|
||||
getTableInstance: () => tableRefsRef.current.tableInstance,
|
||||
});
|
||||
|
||||
const selectionActions = buildSelectionActions({
|
||||
exportConfig,
|
||||
onSingleRestore: (row) => setRestoreTarget(row),
|
||||
onBulkRestore: (ids) => setRestoreIds(ids),
|
||||
onSingleDelete: (row) => setDeleteTarget(row),
|
||||
onBulkDelete: (ids) => setDeleteIds(ids),
|
||||
getTableInstance: () => tableRefsRef.current.tableInstance,
|
||||
});
|
||||
|
||||
const columns = useMemo(
|
||||
() => buildDataColumns(attributes, rowActions),
|
||||
[attributes]
|
||||
);
|
||||
|
||||
const handleRestoreSuccess = () => {
|
||||
setRestoreTarget(null);
|
||||
setRestoreIds(null);
|
||||
tableRefsRef.current.resetSelection?.();
|
||||
fetchArchivedBroadcasts({ page: 1, limit: pagination?.limit ?? 10 });
|
||||
};
|
||||
|
||||
const handleDeleteSuccess = () => {
|
||||
setDeleteTarget(null);
|
||||
setDeleteIds(null);
|
||||
tableRefsRef.current.resetSelection?.();
|
||||
fetchArchivedBroadcasts({ page: 1, limit: pagination?.limit ?? 10 });
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<DataTable
|
||||
title="Archived Alerts"
|
||||
data={broadcasts}
|
||||
columns={columns}
|
||||
attributes={attributes}
|
||||
pagination={pagination}
|
||||
setPagination={setPagination}
|
||||
loading={loading}
|
||||
onFetch={fetchArchivedBroadcasts}
|
||||
onFetchFilterData={() => Promise.resolve([])}
|
||||
onRefsReady={handleRefsReady}
|
||||
renderFilterSheet={({ open, onOpenChange, column, attr, data, loading }) => (
|
||||
<FilterSheet
|
||||
open={open}
|
||||
onOpenChange={onOpenChange}
|
||||
column={column}
|
||||
attr={attr}
|
||||
data={data}
|
||||
loading={loading}
|
||||
/>
|
||||
)}
|
||||
columnPinning={columnPinning}
|
||||
toolbarActions={toolbarActions}
|
||||
selectionActions={selectionActions}
|
||||
recordLabel="archived alert"
|
||||
emptyMessage="No archived alerts found."
|
||||
/>
|
||||
|
||||
{/* ── Single restore ── */}
|
||||
<RestoreDialog
|
||||
open={!!restoreTarget}
|
||||
onOpenChange={(v) => !v && setRestoreTarget(null)}
|
||||
entity={restoreTarget}
|
||||
entityLabel="Alert"
|
||||
getName={(b) => b?.title ?? "this alert"}
|
||||
onRestore={(b) => restoreBroadcast(b?.broadcast_id)}
|
||||
loading={loading}
|
||||
onSuccess={handleRestoreSuccess}
|
||||
/>
|
||||
|
||||
{/* ── Bulk restore ── */}
|
||||
<RestoreDialog
|
||||
open={!!restoreIds}
|
||||
onOpenChange={(v) => !v && setRestoreIds(null)}
|
||||
ids={restoreIds ?? []}
|
||||
entityLabel="Alert"
|
||||
onRestore={(ids) => restoreBroadcasts(ids)}
|
||||
loading={loading}
|
||||
onSuccess={handleRestoreSuccess}
|
||||
/>
|
||||
|
||||
{/* ── Single permanent delete ── */}
|
||||
<PermanentDeleteDialog
|
||||
open={!!deleteTarget}
|
||||
onOpenChange={(v) => !v && setDeleteTarget(null)}
|
||||
entity={deleteTarget}
|
||||
entityLabel="Alert"
|
||||
getName={(b) => b?.title ?? "this alert"}
|
||||
onDelete={(b) => permanentlyDeleteBroadcast(b?.broadcast_id)}
|
||||
loading={loading}
|
||||
onSuccess={handleDeleteSuccess}
|
||||
/>
|
||||
|
||||
{/* ── Bulk permanent delete ── */}
|
||||
<PermanentDeleteDialog
|
||||
open={!!deleteIds}
|
||||
onOpenChange={(v) => !v && setDeleteIds(null)}
|
||||
ids={deleteIds ?? []}
|
||||
entityLabel="Alert"
|
||||
onDelete={(ids) => permanentlyDeleteBroadcasts(ids)}
|
||||
loading={loading}
|
||||
onSuccess={handleDeleteSuccess}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
import { useMemo, useRef, useState } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
|
||||
import { useAdminTask } from "@/contexts/AdminTaskContext";
|
||||
import { useAuth } from "@/contexts/AuthContext";
|
||||
|
||||
import DataTable from "@/components/generic/Table/DataTable";
|
||||
import { FilterSheet } from "@/components/generic/Sheet/FilterSheet";
|
||||
import { RestoreDialog } from "@/components/generic/Dialogs/RestoreDialog";
|
||||
import { PermanentDeleteDialog } from "@/components/generic/Dialogs/PermanentDeleteDialog";
|
||||
|
||||
import { buildDataColumns, columnPinning } from "@/modules/admin/config/task_list/archive/columns.config";
|
||||
import { buildToolbarActions } from "@/modules/admin/config/task_list/archive/toolbar.config";
|
||||
import { buildSelectionActions } from "@/modules/admin/config/task_list/archive/selection.config";
|
||||
import { buildRowActions } from "@/modules/admin/config/task_list/archive/rowActions.config";
|
||||
|
||||
import { getTimestamp } from "@/utils/timestamp.util";
|
||||
import { formatGeneratedBy } from "@/utils/generatedBy.util";
|
||||
|
||||
export default function ArchiveTaskListTable() {
|
||||
const navigate = useNavigate();
|
||||
|
||||
const { user: currentUser } = useAuth();
|
||||
|
||||
const {
|
||||
taskLists, attributes, pagination, loading,
|
||||
fetchArchivedTaskLists,
|
||||
restoreTaskList,
|
||||
bulkRestoreTaskLists,
|
||||
permanentlyDeleteTaskList,
|
||||
bulkPermanentlyDeleteTaskLists,
|
||||
fetchTaskListPermanentDeleteImpact,
|
||||
} = useAdminTask();
|
||||
|
||||
const [restoreTarget, setRestoreTarget] = useState(null);
|
||||
const [restoreIds, setRestoreIds] = useState(null);
|
||||
const [deleteTarget, setDeleteTarget] = useState(null);
|
||||
const [deleteIds, setDeleteIds] = useState(null);
|
||||
|
||||
const tableRefsRef = useRef({
|
||||
getFilters: () => [],
|
||||
getSort: () => [],
|
||||
resetSelection: () => { },
|
||||
tableInstance: null,
|
||||
});
|
||||
|
||||
const handleRefsReady = (refs) => {
|
||||
tableRefsRef.current = refs;
|
||||
};
|
||||
|
||||
const handleSuccess = () => {
|
||||
setRestoreTarget(null);
|
||||
setRestoreIds(null);
|
||||
tableRefsRef.current.resetSelection?.();
|
||||
fetchArchivedTaskLists({
|
||||
page: 1,
|
||||
limit: pagination?.limit ?? 10,
|
||||
filters: tableRefsRef.current.getFilters(),
|
||||
sort: tableRefsRef.current.getSort(),
|
||||
});
|
||||
};
|
||||
|
||||
const handleDeleteSuccess = () => {
|
||||
setDeleteTarget(null);
|
||||
setDeleteIds(null);
|
||||
tableRefsRef.current.resetSelection?.();
|
||||
fetchArchivedTaskLists({
|
||||
page: 1,
|
||||
limit: pagination?.limit ?? 10,
|
||||
filters: tableRefsRef.current.getFilters(),
|
||||
sort: tableRefsRef.current.getSort(),
|
||||
});
|
||||
};
|
||||
|
||||
const exportConfig = {
|
||||
allData: taskLists,
|
||||
attributes,
|
||||
filename: `${getTimestamp()}_ArchivedTaskLists`,
|
||||
sheetName: "Archived Task Lists",
|
||||
generatedBy: formatGeneratedBy(currentUser),
|
||||
};
|
||||
|
||||
const rowActions = buildRowActions({
|
||||
navigate,
|
||||
onRestore: (row) => setRestoreTarget(row),
|
||||
onDelete: (row) => setDeleteTarget(row),
|
||||
});
|
||||
|
||||
const toolbarActions = buildToolbarActions({
|
||||
getSort: () => tableRefsRef.current.getSort(),
|
||||
fetchArchivedTaskLists,
|
||||
pagination,
|
||||
exportConfig,
|
||||
getFilters: () => tableRefsRef.current.getFilters(),
|
||||
getTableInstance: () => tableRefsRef.current.tableInstance,
|
||||
});
|
||||
|
||||
const selectionActions = buildSelectionActions({
|
||||
exportConfig,
|
||||
onBulkRestore: (ids) => setRestoreIds(ids),
|
||||
onBulkDelete: (ids) => setDeleteIds(ids),
|
||||
getTableInstance: () => tableRefsRef.current.tableInstance,
|
||||
});
|
||||
|
||||
const columns = useMemo(
|
||||
() => buildDataColumns(attributes, rowActions),
|
||||
[attributes, rowActions]
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
<DataTable
|
||||
title="Archived Task Lists"
|
||||
data={taskLists}
|
||||
columns={columns}
|
||||
attributes={attributes}
|
||||
pagination={pagination}
|
||||
loading={loading}
|
||||
onFetch={fetchArchivedTaskLists}
|
||||
onFetchFilterData={() => []}
|
||||
onRefsReady={handleRefsReady}
|
||||
renderFilterSheet={({ open, onOpenChange, column, attr, data, loading }) => (
|
||||
<FilterSheet
|
||||
open={open}
|
||||
onOpenChange={onOpenChange}
|
||||
column={column}
|
||||
attr={attr}
|
||||
data={data}
|
||||
loading={loading}
|
||||
/>
|
||||
)}
|
||||
columnPinning={columnPinning}
|
||||
toolbarActions={toolbarActions}
|
||||
selectionActions={selectionActions}
|
||||
recordLabel="archived task list"
|
||||
emptyMessage="No archived task lists found."
|
||||
/>
|
||||
|
||||
{/* Single restore */}
|
||||
<RestoreDialog
|
||||
open={!!restoreTarget}
|
||||
onOpenChange={(v) => !v && setRestoreTarget(null)}
|
||||
entity={restoreTarget}
|
||||
entityLabel="Task List"
|
||||
getName={(r) => r?.name}
|
||||
onRestore={(r) => restoreTaskList(r?.task_list_id)}
|
||||
loading={loading}
|
||||
onSuccess={handleSuccess}
|
||||
/>
|
||||
|
||||
{/* Bulk restore */}
|
||||
<RestoreDialog
|
||||
open={!!restoreIds}
|
||||
onOpenChange={(v) => !v && setRestoreIds(null)}
|
||||
ids={restoreIds ?? []}
|
||||
entityLabel="Task List"
|
||||
onRestore={({ ids }) => bulkRestoreTaskLists(ids)}
|
||||
loading={loading}
|
||||
onSuccess={handleSuccess}
|
||||
/>
|
||||
|
||||
{/* Single permanent delete */}
|
||||
<PermanentDeleteDialog
|
||||
open={!!deleteTarget}
|
||||
onOpenChange={(v) => !v && setDeleteTarget(null)}
|
||||
entity={deleteTarget}
|
||||
entityLabel="Task List"
|
||||
getName={(r) => r?.name}
|
||||
onDelete={(r) => permanentlyDeleteTaskList(r?.task_list_id)}
|
||||
onImpactCheck={() => fetchTaskListPermanentDeleteImpact(deleteTarget?.task_list_id)}
|
||||
loading={loading}
|
||||
onSuccess={handleDeleteSuccess}
|
||||
/>
|
||||
|
||||
{/* Bulk permanent delete */}
|
||||
<PermanentDeleteDialog
|
||||
open={!!deleteIds}
|
||||
onOpenChange={(v) => !v && setDeleteIds(null)}
|
||||
ids={deleteIds ?? []}
|
||||
entityLabel="Task List"
|
||||
onDelete={({ ids }) => bulkPermanentlyDeleteTaskLists(ids)}
|
||||
loading={loading}
|
||||
onSuccess={handleDeleteSuccess}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,299 @@
|
||||
import { useMemo, useRef, useState, useCallback, useEffect } from "react";
|
||||
import { useNavigate, useParams } from "react-router-dom";
|
||||
|
||||
import { useAdminTask } from "@/contexts/AdminTaskContext";
|
||||
import { useAuth } from "@/contexts/AuthContext";
|
||||
|
||||
import DataTable from "@/components/generic/Table/DataTable";
|
||||
import { FilterSheet } from "@/components/generic/Sheet/FilterSheet";
|
||||
import { RestoreDialog } from "@/components/generic/Dialogs/RestoreDialog";
|
||||
import { PermanentDeleteDialog } from "@/components/generic/Dialogs/PermanentDeleteDialog";
|
||||
|
||||
import { buildDataColumns, columnPinning } from "@/modules/admin/config/task_list/task/archive/columns.config";
|
||||
import { buildToolbarActions } from "@/modules/admin/config/task_list/task/archive/toolbar.config";
|
||||
import { buildSelectionActions } from "@/modules/admin/config/task_list/task/archive/selection.config";
|
||||
import { buildRowActions } from "@/modules/admin/config/task_list/task/archive/rowActions.config";
|
||||
|
||||
import { getTimestamp } from "@/utils/timestamp.util";
|
||||
import { formatGeneratedBy } from "@/utils/generatedBy.util";
|
||||
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog';
|
||||
import { formatDate } from "@/utils/table.util";
|
||||
import { ListTodo, Users } from "lucide-react";
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
|
||||
export default function ArchivedTaskTable() {
|
||||
const navigate = useNavigate();
|
||||
const { taskListId } = useParams();
|
||||
|
||||
const { user: currentUser } = useAuth();
|
||||
|
||||
const {
|
||||
taskList, tasks, attributes, pagination, loading,
|
||||
fetchTaskList, fetchArchivedTasks, fetchTaskFieldValues,
|
||||
restoreTask,
|
||||
bulkRestoreTasks,
|
||||
permanentlyDeleteTask,
|
||||
bulkPermanentlyDeleteTasks,
|
||||
} = useAdminTask();
|
||||
|
||||
const [restoreTarget, setRestoreTarget] = useState(null);
|
||||
const [restoreIds, setRestoreIds] = useState(null);
|
||||
const [deleteTarget, setDeleteTarget] = useState(null);
|
||||
const [deleteIds, setDeleteIds] = useState(null);
|
||||
const [showGroupsDialog, setShowGroupsDialog] = useState(false);
|
||||
|
||||
const tableRefsRef = useRef({
|
||||
getFilters: () => [],
|
||||
getSort: () => [],
|
||||
resetSelection: () => { },
|
||||
tableInstance: null,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
fetchTaskList(taskListId);
|
||||
fetchArchivedTasks(taskListId, { page: 1, limit: 10 });
|
||||
}, [taskListId]);
|
||||
|
||||
const handleRefsReady = (refs) => {
|
||||
tableRefsRef.current = refs;
|
||||
};
|
||||
|
||||
// ── Stable fetch callback — won't change on every render ─────────────────
|
||||
const handleFetch = useCallback(
|
||||
(params) => fetchArchivedTasks(taskListId, params),
|
||||
[taskListId]
|
||||
);
|
||||
|
||||
const handleSuccess = () => {
|
||||
setRestoreTarget(null);
|
||||
setRestoreIds(null);
|
||||
tableRefsRef.current.resetSelection?.();
|
||||
fetchArchivedTasks(taskListId, {
|
||||
page: 1,
|
||||
limit: pagination?.limit ?? 10,
|
||||
filters: tableRefsRef.current.getFilters(),
|
||||
sort: tableRefsRef.current.getSort(),
|
||||
});
|
||||
};
|
||||
|
||||
const handleDeleteSuccess = () => {
|
||||
setDeleteTarget(null);
|
||||
setDeleteIds(null);
|
||||
tableRefsRef.current.resetSelection?.();
|
||||
fetchArchivedTasks(taskListId, {
|
||||
page: 1,
|
||||
limit: pagination?.limit ?? 10,
|
||||
filters: tableRefsRef.current.getFilters(),
|
||||
sort: tableRefsRef.current.getSort(),
|
||||
});
|
||||
};
|
||||
|
||||
const exportConfig = useMemo(() => ({
|
||||
allData: tasks,
|
||||
attributes,
|
||||
filename: `${getTimestamp()}_ArchivedTasks`,
|
||||
sheetName: "Archived Tasks",
|
||||
generatedBy: formatGeneratedBy(currentUser),
|
||||
}), [tasks, attributes, currentUser]);
|
||||
|
||||
const rowActions = useMemo(() => buildRowActions({
|
||||
navigate,
|
||||
onRestore: (row) => setRestoreTarget(row),
|
||||
onDelete: (row) => setDeleteTarget(row),
|
||||
}), [navigate]);
|
||||
|
||||
const toolbarActions = useMemo(() => buildToolbarActions({
|
||||
fetchArchivedTasks: handleFetch, taskListId,
|
||||
navigate, pagination, exportConfig,
|
||||
getFilters: () => tableRefsRef.current.getFilters(),
|
||||
getSort: () => tableRefsRef.current.getSort(),
|
||||
getTableInstance: () => tableRefsRef.current.tableInstance,
|
||||
}), [taskListId, navigate, handleFetch, pagination, exportConfig]);
|
||||
|
||||
const selectionActions = useMemo(() => buildSelectionActions({
|
||||
exportConfig,
|
||||
onBulkRestore: (ids) => setRestoreIds(ids), // ← was onRestoreMany
|
||||
onBulkDelete: (ids) => setDeleteIds(ids),
|
||||
getTableInstance: () => tableRefsRef.current.tableInstance,
|
||||
}), [exportConfig]);
|
||||
|
||||
const columns = useMemo(
|
||||
() => buildDataColumns(attributes, rowActions),
|
||||
[attributes, rowActions]
|
||||
);
|
||||
|
||||
const assignedGroups = taskList?.groups ?? [];
|
||||
const totalTasks = pagination?.totalRecords ?? 0;
|
||||
const hasOverflow = assignedGroups.length > 1;
|
||||
const formattedCreated = taskList?.createdAt ? formatDate(taskList.createdAt) : '—';
|
||||
const formattedUpdated = taskList?.updatedAt ? formatDate(taskList.updatedAt) : '—';
|
||||
|
||||
return (
|
||||
<>
|
||||
|
||||
{/* ── Detail card ───────────────────────────────────────────────── */}
|
||||
<div className="bg-card border rounded-xl p-5 flex flex-col gap-4 w-full mb-4">
|
||||
<div className="flex items-start justify-between gap-4">
|
||||
<div className="flex flex-col gap-1 min-w-0">
|
||||
{taskList
|
||||
? <h1 className="text-lg font-medium leading-none">{taskList.name}</h1>
|
||||
: <Skeleton className="h-5 w-48" />
|
||||
}
|
||||
{taskList
|
||||
? <p className="text-sm text-muted-foreground mt-1">{taskList.description ?? '—'}</p>
|
||||
: <Skeleton className="h-4 w-72 mt-1" />
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
|
||||
<div className="bg-muted rounded-lg px-3 py-2">
|
||||
<span className="block text-[11px] uppercase tracking-wide text-muted-foreground mb-1">Tasks</span>
|
||||
<span className="text-sm font-medium flex items-center gap-1.5">
|
||||
<ListTodo className="size-3.5 text-muted-foreground" />
|
||||
{taskList ? totalTasks : <Skeleton className="h-4 w-8 inline-block" />}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="bg-muted rounded-lg px-3 py-2">
|
||||
<span className="block text-[11px] uppercase tracking-wide text-muted-foreground mb-1">Groups</span>
|
||||
{taskList ? (
|
||||
taskList.group_count > 0 ? (
|
||||
<div className="font-medium flex items-center gap-2">
|
||||
<Users className="size-3.5 text-muted-foreground shrink-0" />
|
||||
<span className="text-sm font-medium">{taskList.group_count}</span>
|
||||
{hasOverflow && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowGroupsDialog(true)}
|
||||
className="text-xs text-primary hover:underline underline-offset-2 shrink-0"
|
||||
>
|
||||
+{taskList.group_count - 1} more
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
) : <span className="text-sm font-medium">0</span>
|
||||
) : <Skeleton className="h-4 w-8 inline-block" />}
|
||||
</div>
|
||||
|
||||
<div className="bg-muted rounded-lg px-3 py-2">
|
||||
<span className="block text-[11px] uppercase tracking-wide text-muted-foreground mb-1">Created</span>
|
||||
<span className="text-sm font-medium">
|
||||
{taskList ? formattedCreated : <Skeleton className="h-4 w-20 inline-block" />}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="bg-muted rounded-lg px-3 py-2">
|
||||
<span className="block text-[11px] uppercase tracking-wide text-muted-foreground mb-1">Last Updated</span>
|
||||
<span className="text-sm font-medium">
|
||||
{taskList ? formattedUpdated : <Skeleton className="h-4 w-20 inline-block" />}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
<DataTable
|
||||
title="Archived Tasks"
|
||||
data={tasks}
|
||||
columns={columns}
|
||||
attributes={attributes}
|
||||
pagination={pagination}
|
||||
loading={loading}
|
||||
onFetch={handleFetch}
|
||||
onFetchFilterData={(field) => fetchTaskFieldValues(taskListId, field)}
|
||||
onRefsReady={handleRefsReady}
|
||||
renderFilterSheet={({ open, onOpenChange, column, attr, data, loading }) => (
|
||||
<FilterSheet
|
||||
open={open}
|
||||
onOpenChange={onOpenChange}
|
||||
column={column}
|
||||
attr={attr}
|
||||
data={data}
|
||||
loading={loading}
|
||||
/>
|
||||
)}
|
||||
columnPinning={columnPinning}
|
||||
toolbarActions={toolbarActions}
|
||||
selectionActions={selectionActions}
|
||||
recordLabel="archived task"
|
||||
emptyMessage="No archived tasks found."
|
||||
/>
|
||||
|
||||
{/* Single restore */}
|
||||
<RestoreDialog
|
||||
open={!!restoreTarget}
|
||||
onOpenChange={(v) => !v && setRestoreTarget(null)}
|
||||
entity={restoreTarget}
|
||||
entityLabel="Task"
|
||||
getName={(r) => r?.name}
|
||||
onRestore={(r) => restoreTask(taskListId, r?.task_id)}
|
||||
loading={loading}
|
||||
onSuccess={handleSuccess}
|
||||
/>
|
||||
|
||||
{/* Bulk restore */}
|
||||
<RestoreDialog
|
||||
open={!!restoreIds}
|
||||
onOpenChange={(v) => !v && setRestoreIds(null)}
|
||||
ids={restoreIds ?? []}
|
||||
entityLabel="Task"
|
||||
onRestore={({ ids }) => bulkRestoreTasks(taskListId, ids)}
|
||||
loading={loading}
|
||||
onSuccess={handleSuccess}
|
||||
/>
|
||||
|
||||
{/* Single permanent delete */}
|
||||
<PermanentDeleteDialog
|
||||
open={!!deleteTarget}
|
||||
onOpenChange={(v) => !v && setDeleteTarget(null)}
|
||||
entity={deleteTarget}
|
||||
entityLabel="Task"
|
||||
getName={(r) => r?.name}
|
||||
onDelete={(r) => permanentlyDeleteTask(taskListId, r?.task_id)}
|
||||
loading={loading}
|
||||
onSuccess={handleDeleteSuccess}
|
||||
/>
|
||||
|
||||
{/* Bulk permanent delete */}
|
||||
<PermanentDeleteDialog
|
||||
open={!!deleteIds}
|
||||
onOpenChange={(v) => !v && setDeleteIds(null)}
|
||||
ids={deleteIds ?? []}
|
||||
entityLabel="Task"
|
||||
onDelete={({ ids }) => bulkPermanentlyDeleteTasks(taskListId, ids)}
|
||||
loading={loading}
|
||||
onSuccess={handleDeleteSuccess}
|
||||
/>
|
||||
|
||||
<Dialog open={showGroupsDialog} onOpenChange={setShowGroupsDialog}>
|
||||
<DialogContent className="max-w-sm">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<Users className="h-4 w-4 text-muted-foreground" />
|
||||
Assigned Groups
|
||||
<Badge variant="secondary" className="ml-1 text-xs">
|
||||
{assignedGroups.length}
|
||||
</Badge>
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
<div className="flex flex-wrap gap-2 pt-1">
|
||||
{assignedGroups.map((g) => (
|
||||
<Badge key={g.group_id} variant="secondary" className="gap-1.5 text-xs py-1 px-2">
|
||||
<Users className="h-3 w-3" />
|
||||
{g.name}
|
||||
</Badge>
|
||||
))}
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
import { useMemo, useRef, useState, useCallback } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
|
||||
import { useAdminTask } from "@/contexts/AdminTaskContext";
|
||||
import { useAuth } from "@/contexts/AuthContext";
|
||||
|
||||
import DataTable from "@/components/generic/Table/DataTable";
|
||||
import { FilterSheet } from "@/components/generic/Sheet/FilterSheet";
|
||||
import { ArchiveDialog } from "@/components/generic/Dialogs/ArchiveDialog";
|
||||
import { RestoreDialog } from "@/components/generic/Dialogs/RestoreDialog";
|
||||
|
||||
import { buildDataColumns, columnPinning } from "../../config/task_list/columns.config";
|
||||
import { buildToolbarActions } from "../../config/task_list/toolbar.config";
|
||||
import { buildSelectionActions } from "../../config/task_list/selection.config";
|
||||
import { buildRowActions } from "../../config/task_list/rowActions.config";
|
||||
|
||||
import { getTimestamp } from "@/utils/timestamp.util";
|
||||
import { formatGeneratedBy } from "@/utils/generatedBy.util";
|
||||
|
||||
export default function TaskListTable() {
|
||||
const navigate = useNavigate();
|
||||
|
||||
const { user: currentUser } = useAuth();
|
||||
|
||||
const {
|
||||
taskLists, attributes, pagination, loading,
|
||||
fetchTaskLists, fetchArchivedTaskLists, fetchTaskListFieldValues,
|
||||
archiveTaskList, restoreTaskList,
|
||||
bulkArchiveTaskLists, bulkRestoreTaskLists,
|
||||
} = useAdminTask();
|
||||
|
||||
const [showArchived, setShowArchived] = useState(false);
|
||||
const [archiveTarget, setArchiveTarget] = useState(null);
|
||||
const [restoreTarget, setRestoreTarget] = useState(null);
|
||||
const [archiveIds, setArchiveIds] = useState(null);
|
||||
const [restoreIds, setRestoreIds] = useState(null);
|
||||
|
||||
const tableRefsRef = useRef({
|
||||
getFilters: () => [],
|
||||
getSort: () => [],
|
||||
resetSelection: () => { },
|
||||
tableInstance: null,
|
||||
});
|
||||
|
||||
const handleRefsReady = (refs) => {
|
||||
tableRefsRef.current = refs;
|
||||
};
|
||||
|
||||
// ── Toggle archived view ──────────────────────────────────────────────────
|
||||
const handleToggleArchived = useCallback(() => {
|
||||
const next = !showArchived;
|
||||
setShowArchived(next);
|
||||
fetchTaskLists({
|
||||
page: 1,
|
||||
limit: pagination?.limit ?? 10,
|
||||
filters: tableRefsRef.current.getFilters(),
|
||||
sort: tableRefsRef.current.getSort(),
|
||||
archived: next,
|
||||
});
|
||||
}, [showArchived, pagination, fetchTaskLists, fetchArchivedTaskLists]);
|
||||
|
||||
// ── Refetch helper ────────────────────────────────────────────────────────
|
||||
const handleSuccess = () => {
|
||||
setArchiveTarget(null);
|
||||
setRestoreTarget(null);
|
||||
setArchiveIds(null);
|
||||
setRestoreIds(null);
|
||||
tableRefsRef.current.resetSelection?.();
|
||||
const fetcher = showArchived ? fetchArchivedTaskLists : fetchTaskLists;
|
||||
fetcher({
|
||||
page: 1,
|
||||
limit: pagination?.limit ?? 10,
|
||||
filters: tableRefsRef.current.getFilters(),
|
||||
sort: tableRefsRef.current.getSort(),
|
||||
});
|
||||
};
|
||||
|
||||
// ── Export config ─────────────────────────────────────────────────────────
|
||||
const exportConfig = useMemo(() => ({
|
||||
allData: taskLists,
|
||||
attributes,
|
||||
filename: `${getTimestamp()}_TaskLists`,
|
||||
sheetName: "Task Lists",
|
||||
generatedBy: formatGeneratedBy(currentUser),
|
||||
}), [taskLists, attributes, currentUser]);
|
||||
|
||||
// ── Row actions ───────────────────────────────────────────────────────────
|
||||
const rowActions = buildRowActions({
|
||||
navigate,
|
||||
onArchive: (row) => setArchiveTarget(row),
|
||||
onRestore: (row) => setRestoreTarget(row),
|
||||
showArchived,
|
||||
});
|
||||
|
||||
// ── Toolbar ───────────────────────────────────────────────────────────────
|
||||
const toolbarActions = buildToolbarActions({
|
||||
fetchTaskLists, fetchArchivedTaskLists, pagination, navigate,
|
||||
exportConfig,
|
||||
showArchived,
|
||||
onToggleArchived: handleToggleArchived,
|
||||
getFilters: () => tableRefsRef.current.getFilters(),
|
||||
getSort: () => tableRefsRef.current.getSort(),
|
||||
getTableInstance: () => tableRefsRef.current.tableInstance,
|
||||
});
|
||||
|
||||
// ── Selection ─────────────────────────────────────────────────────────────
|
||||
const selectionActions = buildSelectionActions({
|
||||
exportConfig,
|
||||
showArchived,
|
||||
onBulkArchive: (ids) => setArchiveIds(ids),
|
||||
onBulkRestore: (ids) => setRestoreIds(ids),
|
||||
getTableInstance: () => tableRefsRef.current.tableInstance,
|
||||
});
|
||||
|
||||
// ── Columns ───────────────────────────────────────────────────────────────
|
||||
const columns = useMemo(
|
||||
() => buildDataColumns(attributes, rowActions),
|
||||
[attributes, rowActions]
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
<DataTable
|
||||
title="Task Lists"
|
||||
data={taskLists}
|
||||
columns={columns}
|
||||
attributes={attributes}
|
||||
pagination={pagination}
|
||||
loading={loading}
|
||||
onFetch={fetchTaskLists}
|
||||
onFetchFilterData={fetchTaskListFieldValues}
|
||||
onRefsReady={handleRefsReady}
|
||||
renderFilterSheet={({ open, onOpenChange, column, attr, data, loading }) => (
|
||||
<FilterSheet
|
||||
open={open}
|
||||
onOpenChange={onOpenChange}
|
||||
column={column}
|
||||
attr={attr}
|
||||
data={data}
|
||||
loading={loading}
|
||||
/>
|
||||
)}
|
||||
columnPinning={columnPinning}
|
||||
toolbarActions={toolbarActions}
|
||||
selectionActions={selectionActions}
|
||||
recordLabel="task list"
|
||||
emptyMessage="No task lists found."
|
||||
/>
|
||||
|
||||
{/* Single archive */}
|
||||
<ArchiveDialog
|
||||
open={!!archiveTarget}
|
||||
onOpenChange={(v) => !v && setArchiveTarget(null)}
|
||||
entity={archiveTarget}
|
||||
entityLabel="Task List"
|
||||
getName={(r) => r?.name}
|
||||
onArchive={(entity) => archiveTaskList(entity?.task_list_id)}
|
||||
loading={loading}
|
||||
onSuccess={handleSuccess}
|
||||
/>
|
||||
|
||||
{/* Single restore */}
|
||||
<RestoreDialog
|
||||
open={!!restoreTarget}
|
||||
onOpenChange={(v) => !v && setRestoreTarget(null)}
|
||||
entity={restoreTarget}
|
||||
entityLabel="Task List"
|
||||
getName={(r) => r?.name}
|
||||
onRestore={(entity) => restoreTaskList(entity?.task_list_id)}
|
||||
loading={loading}
|
||||
onSuccess={handleSuccess}
|
||||
/>
|
||||
|
||||
{/* Bulk archive */}
|
||||
<ArchiveDialog
|
||||
open={!!archiveIds}
|
||||
onOpenChange={(v) => !v && setArchiveIds(null)}
|
||||
ids={archiveIds ?? []}
|
||||
entityLabel="Task List"
|
||||
onArchive={({ ids }) => bulkArchiveTaskLists(ids)}
|
||||
loading={loading}
|
||||
onSuccess={handleSuccess}
|
||||
/>
|
||||
|
||||
{/* Bulk restore */}
|
||||
<RestoreDialog
|
||||
open={!!restoreIds}
|
||||
onOpenChange={(v) => !v && setRestoreIds(null)}
|
||||
ids={restoreIds ?? []}
|
||||
entityLabel="Task List"
|
||||
onRestore={({ ids }) => bulkRestoreTaskLists(ids)}
|
||||
loading={loading}
|
||||
onSuccess={handleSuccess}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,234 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
|
||||
import { useAdminTask } from '@/contexts/AdminTaskContext';
|
||||
import { useAuth } from '@/contexts/AuthContext';
|
||||
|
||||
import DataTable from '@/components/generic/Table/DataTable';
|
||||
import { FilterSheet } from "@/components/generic/Sheet/FilterSheet";
|
||||
import { ArchiveDialog } from '@/components/generic/Dialogs/ArchiveDialog';
|
||||
import { RestoreDialog } from '@/components/generic/Dialogs/RestoreDialog';
|
||||
import { Spinner } from '@/components/ui/spinner';
|
||||
import {
|
||||
AlertDialog, AlertDialogAction, AlertDialogCancel,
|
||||
AlertDialogContent, AlertDialogDescription,
|
||||
AlertDialogFooter, AlertDialogHeader, AlertDialogTitle,
|
||||
} from '@/components/ui/alert-dialog';
|
||||
import { TriangleAlert } from 'lucide-react';
|
||||
|
||||
import { buildDataColumns, columnPinning } from '@/modules/admin/config/task_list/task/columns.config';
|
||||
import { buildToolbarActions } from '@/modules/admin/config/task_list/task/toolbar.config';
|
||||
import { buildSelectionActions } from '@/modules/admin/config/task_list/task/selection.config';
|
||||
import { buildRowActions } from '@/modules/admin/config/task_list/task/rowActions.config';
|
||||
import { getTimestamp } from '@/utils/timestamp.util';
|
||||
import { formatGeneratedBy } from '@/utils/generatedBy.util';
|
||||
|
||||
export default function TasksTable({ taskListId }) {
|
||||
const navigate = useNavigate();
|
||||
|
||||
const { user: currentUser } = useAuth();
|
||||
|
||||
const {
|
||||
tasks, attributes, pagination, loading,
|
||||
fetchTasks, fetchArchivedTasks,
|
||||
archiveTask, restoreTask, fetchTaskFieldValues,
|
||||
bulkArchiveTasks, bulkRestoreTasks, reorderTasks,
|
||||
} = useAdminTask();
|
||||
|
||||
const [showArchived, setShowArchived] = useState(false);
|
||||
const [archiveTarget, setArchiveTarget] = useState(null);
|
||||
const [restoreTarget, setRestoreTarget] = useState(null);
|
||||
const [bulkArchiveIds, setBulkArchiveIds] = useState(null);
|
||||
const [bulkRestoreIds, setBulkRestoreIds] = useState(null);
|
||||
|
||||
const tableRefsRef = useRef({
|
||||
getFilters: () => [], getSort: () => [], resetSelection: () => { }, tableInstance: null,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
fetchTasks(taskListId, { page: 1, limit: 10 });
|
||||
}, [taskListId]);
|
||||
|
||||
const handleRefsReady = (refs) => { tableRefsRef.current = refs; };
|
||||
|
||||
const handleFetch = useCallback((params) => {
|
||||
const fetcher = showArchived ? fetchArchivedTasks : fetchTasks;
|
||||
return fetcher(taskListId, params);
|
||||
}, [fetchTasks, fetchArchivedTasks, taskListId, showArchived]);
|
||||
|
||||
const handleToggleArchived = () => {
|
||||
const next = !showArchived;
|
||||
setShowArchived(next);
|
||||
const fetcher = next ? fetchArchivedTasks : fetchTasks;
|
||||
fetcher(taskListId, {
|
||||
page: 1,
|
||||
limit: pagination?.limit ?? 10,
|
||||
filters: tableRefsRef.current.getFilters(),
|
||||
sort: tableRefsRef.current.getSort(),
|
||||
});
|
||||
};
|
||||
|
||||
const afterMutation = () => {
|
||||
tableRefsRef.current.resetSelection?.();
|
||||
const fetcher = showArchived ? fetchArchivedTasks : fetchTasks;
|
||||
fetcher(taskListId, {
|
||||
page: 1,
|
||||
limit: pagination?.limit ?? 10,
|
||||
filters: tableRefsRef.current.getFilters(),
|
||||
sort: tableRefsRef.current.getSort(),
|
||||
});
|
||||
};
|
||||
|
||||
const exportConfig = useMemo(() => ({
|
||||
allData: tasks,
|
||||
attributes,
|
||||
filename: `${getTimestamp()}_Tasks`,
|
||||
sheetName: "Tasks",
|
||||
generatedBy: formatGeneratedBy(currentUser),
|
||||
}), [tasks, attributes, currentUser]);
|
||||
|
||||
// ── Reorder — swaps this row with its neighbor in the currently displayed
|
||||
// (unfiltered/default-sorted) list, then persists the new order_index set.
|
||||
const handleMove = async (row, direction) => {
|
||||
const idx = tasks.findIndex((t) => t.task_id === row.task_id);
|
||||
const swapIdx = idx + direction;
|
||||
if (idx < 0 || swapIdx < 0 || swapIdx >= tasks.length) return;
|
||||
|
||||
const reordered = [...tasks];
|
||||
[reordered[idx], reordered[swapIdx]] = [reordered[swapIdx], reordered[idx]];
|
||||
|
||||
const ok = await reorderTasks(taskListId, reordered.map((t) => t.task_id));
|
||||
if (ok) afterMutation();
|
||||
};
|
||||
|
||||
const rowActions = buildRowActions({
|
||||
navigate,
|
||||
taskListId,
|
||||
onArchive: (row) => setArchiveTarget(row),
|
||||
onRestore: (row) => setRestoreTarget(row),
|
||||
onMoveUp: (row) => handleMove(row, -1),
|
||||
onMoveDown: (row) => handleMove(row, 1),
|
||||
showArchived,
|
||||
tasks,
|
||||
});
|
||||
|
||||
const toolbarActions = buildToolbarActions({
|
||||
fetchTasks, fetchArchivedTasks, taskListId,
|
||||
pagination, navigate, exportConfig,
|
||||
showArchived, onToggleArchived: handleToggleArchived,
|
||||
getFilters: () => tableRefsRef.current.getFilters(),
|
||||
getSort: () => tableRefsRef.current.getSort(),
|
||||
getTableInstance: () => tableRefsRef.current.tableInstance,
|
||||
});
|
||||
|
||||
const selectionActions = buildSelectionActions({
|
||||
showArchived,
|
||||
onBulkArchive: (ids) => setBulkArchiveIds(ids),
|
||||
onBulkRestore: (ids) => setBulkRestoreIds(ids),
|
||||
getTableInstance: () => tableRefsRef.current.tableInstance,
|
||||
});
|
||||
|
||||
const columns = useMemo(() => buildDataColumns(attributes, rowActions), [attributes, rowActions]);
|
||||
|
||||
return (
|
||||
<>
|
||||
<DataTable
|
||||
columns={columns}
|
||||
data={tasks}
|
||||
pagination={pagination}
|
||||
loading={loading}
|
||||
onFetch={handleFetch}
|
||||
onFetchFilterData={(field) => fetchTaskFieldValues(taskListId, field)}
|
||||
toolbarActions={toolbarActions}
|
||||
selectionActions={selectionActions}
|
||||
columnPinning={columnPinning}
|
||||
onRefsReady={handleRefsReady}
|
||||
recordLabel="task"
|
||||
emptyMessage="No tasks in this list yet."
|
||||
renderFilterSheet={({ open, onOpenChange, column, attr, data, loading }) => (
|
||||
<FilterSheet
|
||||
open={open}
|
||||
onOpenChange={onOpenChange}
|
||||
column={column}
|
||||
attr={attr}
|
||||
data={data}
|
||||
loading={loading}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
|
||||
{/* ── Single archive ────────────────────────────────────────────── */}
|
||||
<AlertDialog open={!!archiveTarget} onOpenChange={(v) => !v && setArchiveTarget(null)}>
|
||||
<AlertDialogContent className="sm:max-w-sm">
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Archive Task</AlertDialogTitle>
|
||||
<AlertDialogDescription asChild>
|
||||
<div className="space-y-3">
|
||||
<p>
|
||||
Are you sure you want to archive{' '}
|
||||
<span className="font-medium text-foreground">{archiveTarget?.name}</span>?
|
||||
This will deactivate the record immediately.
|
||||
</p>
|
||||
<div className="flex items-start gap-2 rounded-md border border-amber-300 dark:border-amber-700 bg-amber-50 dark:bg-amber-950/40 px-3 py-2.5 text-amber-800 dark:text-amber-300 text-sm">
|
||||
<TriangleAlert className="size-4 mt-0.5 shrink-0" />
|
||||
<p>
|
||||
Check if users have already completed this task before archiving.
|
||||
Review the <span className="font-medium">Completions</span> tab to avoid losing track of submitted work.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel disabled={loading}>Cancel</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
disabled={loading}
|
||||
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
|
||||
onClick={async () => {
|
||||
const ok = await archiveTask(taskListId, archiveTarget?.task_id);
|
||||
if (ok) { setArchiveTarget(null); afterMutation(); }
|
||||
}}
|
||||
>
|
||||
{loading && <Spinner className="size-4 mr-2" />}
|
||||
Archive
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
|
||||
{/* ── Single restore ────────────────────────────────────────────── */}
|
||||
<RestoreDialog
|
||||
open={!!restoreTarget}
|
||||
onOpenChange={(v) => !v && setRestoreTarget(null)}
|
||||
entity={restoreTarget}
|
||||
entityLabel="Task"
|
||||
getName={(r) => r?.name}
|
||||
onRestore={(entity) => restoreTask(taskListId, entity?.task_id)}
|
||||
loading={loading}
|
||||
onSuccess={afterMutation}
|
||||
/>
|
||||
|
||||
{/* ── Bulk archive ──────────────────────────────────────────────── */}
|
||||
<ArchiveDialog
|
||||
open={!!bulkArchiveIds}
|
||||
onOpenChange={(v) => !v && setBulkArchiveIds(null)}
|
||||
ids={bulkArchiveIds ?? []}
|
||||
entityLabel="Task"
|
||||
onArchive={({ ids }) => bulkArchiveTasks(taskListId, ids)}
|
||||
loading={loading}
|
||||
onSuccess={afterMutation}
|
||||
/>
|
||||
|
||||
{/* ── Bulk restore ──────────────────────────────────────────────── */}
|
||||
<RestoreDialog
|
||||
open={!!bulkRestoreIds}
|
||||
onOpenChange={(v) => !v && setBulkRestoreIds(null)}
|
||||
ids={bulkRestoreIds ?? []}
|
||||
entityLabel="Task"
|
||||
onRestore={({ ids }) => bulkRestoreTasks(taskListId, ids)}
|
||||
loading={loading}
|
||||
onSuccess={afterMutation}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
import { useMemo, useRef, useState, useCallback } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
|
||||
import { useTiers } from "@/contexts/AdminTiersContext";
|
||||
import { useAuth } from "@/contexts/AuthContext";
|
||||
|
||||
import DataTable from "@/components/generic/Table/DataTable";
|
||||
import { FilterSheet } from "@/components/generic/Sheet/FilterSheet";
|
||||
import { RestoreDialog } from "@/components/generic/Dialogs/RestoreDialog";
|
||||
import { PermanentDeleteDialog } from "@/components/generic/Dialogs/PermanentDeleteDialog";
|
||||
|
||||
import { buildDataColumns, columnPinning } from "../../config/tiers/plans/archive/columns.config";
|
||||
import { buildToolbarActions } from "../../config/tiers/plans/archive/toolbar.config";
|
||||
import { buildSelectionActions } from "../../config/tiers/plans/archive/selection.config";
|
||||
import { buildRowActions } from "../../config/tiers/plans/archive/rowActions.config";
|
||||
|
||||
import { getTimestamp } from "@/utils/timestamp.util";
|
||||
import { formatGeneratedBy } from "@/utils/generatedBy.util";
|
||||
|
||||
export default function ArchivedTierPlansTable() {
|
||||
const navigate = useNavigate();
|
||||
|
||||
const { user: currentUser } = useAuth();
|
||||
|
||||
const {
|
||||
plans, planAttributes, planPagination, setPlanPagination,
|
||||
loading, fetchPlans, restorePlan, bulkRestorePlans,
|
||||
permanentlyDeletePlan, bulkPermanentlyDeletePlans, fetchPlanPermanentDeleteImpact,
|
||||
} = useTiers();
|
||||
|
||||
const [restoreTarget, setRestoreTarget] = useState(null);
|
||||
const [restoreIds, setRestoreIds] = useState(null);
|
||||
const [deleteTarget, setDeleteTarget] = useState(null);
|
||||
const [deleteIds, setDeleteIds] = useState(null);
|
||||
|
||||
const tableRefsRef = useRef({
|
||||
getFilters: () => [],
|
||||
getSort: () => [],
|
||||
resetSelection: () => {},
|
||||
tableInstance: null,
|
||||
});
|
||||
|
||||
const handleRefsReady = (refs) => { tableRefsRef.current = refs; };
|
||||
|
||||
const fetchArchived = useCallback(
|
||||
(params) => fetchPlans({ ...params, archived: true }),
|
||||
[fetchPlans]
|
||||
);
|
||||
|
||||
const exportConfig = useMemo(() => ({
|
||||
allData: plans,
|
||||
attributes: planAttributes,
|
||||
filename: `${getTimestamp()}_ArchivedTierPlans`,
|
||||
sheetName: "Archived Subscriptions",
|
||||
generatedBy: formatGeneratedBy(currentUser),
|
||||
}), [plans, planAttributes, currentUser]);
|
||||
|
||||
const rowActions = buildRowActions({
|
||||
navigate,
|
||||
onRestore: (row) => setRestoreTarget(row),
|
||||
onDelete: (row) => setDeleteTarget(row),
|
||||
});
|
||||
|
||||
const toolbarActions = buildToolbarActions({
|
||||
fetchPlans: fetchArchived,
|
||||
pagination: planPagination,
|
||||
exportConfig,
|
||||
navigate,
|
||||
getFilters: () => tableRefsRef.current.getFilters(),
|
||||
getSort: () => tableRefsRef.current.getSort(),
|
||||
getTableInstance: () => tableRefsRef.current.tableInstance,
|
||||
});
|
||||
|
||||
const selectionActions = buildSelectionActions({
|
||||
exportConfig,
|
||||
onRestore: (row) => setRestoreTarget(row),
|
||||
onRestoreMany: (ids) => setRestoreIds(ids),
|
||||
onDelete: (row) => setDeleteTarget(row),
|
||||
onDeleteMany: (ids) => setDeleteIds(ids),
|
||||
getTableInstance: () => tableRefsRef.current.tableInstance,
|
||||
});
|
||||
|
||||
const columns = useMemo(
|
||||
() => buildDataColumns(planAttributes, rowActions),
|
||||
[planAttributes, rowActions]
|
||||
);
|
||||
|
||||
const handleRestoreSuccess = () => {
|
||||
setRestoreTarget(null);
|
||||
setRestoreIds(null);
|
||||
tableRefsRef.current.resetSelection?.();
|
||||
fetchArchived({
|
||||
page: 1,
|
||||
limit: planPagination?.limit ?? 10,
|
||||
filters: tableRefsRef.current.getFilters(),
|
||||
sort: tableRefsRef.current.getSort(),
|
||||
});
|
||||
};
|
||||
|
||||
const handleDeleteSuccess = () => {
|
||||
setDeleteTarget(null);
|
||||
setDeleteIds(null);
|
||||
tableRefsRef.current.resetSelection?.();
|
||||
fetchArchived({
|
||||
page: 1,
|
||||
limit: planPagination?.limit ?? 10,
|
||||
filters: tableRefsRef.current.getFilters(),
|
||||
sort: tableRefsRef.current.getSort(),
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<DataTable
|
||||
title="Archived Plans"
|
||||
data={plans}
|
||||
columns={columns}
|
||||
attributes={planAttributes}
|
||||
pagination={planPagination}
|
||||
setPagination={setPlanPagination}
|
||||
loading={loading}
|
||||
onFetch={fetchArchived}
|
||||
onFetchFilterData={async () => []}
|
||||
onRefsReady={handleRefsReady}
|
||||
renderFilterSheet={({ open, onOpenChange, column, attr, data, loading }) => (
|
||||
<FilterSheet
|
||||
open={open}
|
||||
onOpenChange={onOpenChange}
|
||||
column={column}
|
||||
attr={attr}
|
||||
data={data}
|
||||
loading={loading}
|
||||
/>
|
||||
)}
|
||||
columnPinning={columnPinning}
|
||||
toolbarActions={toolbarActions}
|
||||
selectionActions={selectionActions}
|
||||
recordLabel="plan"
|
||||
emptyMessage="No archived plans found."
|
||||
/>
|
||||
|
||||
<RestoreDialog
|
||||
open={!!restoreTarget}
|
||||
onOpenChange={(v) => !v && setRestoreTarget(null)}
|
||||
entity={restoreTarget}
|
||||
entityLabel="Plan"
|
||||
getName={(r) => r?.label}
|
||||
onRestore={(entity) => restorePlan(entity?.plan_id)}
|
||||
loading={loading}
|
||||
onSuccess={handleRestoreSuccess}
|
||||
/>
|
||||
|
||||
<RestoreDialog
|
||||
open={!!restoreIds}
|
||||
onOpenChange={(v) => !v && setRestoreIds(null)}
|
||||
ids={restoreIds ?? []}
|
||||
entityLabel="Plan"
|
||||
onRestore={({ ids }) => bulkRestorePlans(ids)}
|
||||
loading={loading}
|
||||
onSuccess={handleRestoreSuccess}
|
||||
/>
|
||||
|
||||
{/* Single permanent delete — also auto-revokes any remaining active
|
||||
subscribers (no refund) and deletes payment records, both handled
|
||||
server-side as part of the delete itself. */}
|
||||
<PermanentDeleteDialog
|
||||
open={!!deleteTarget}
|
||||
onOpenChange={(v) => !v && setDeleteTarget(null)}
|
||||
entity={deleteTarget}
|
||||
entityLabel="Plan"
|
||||
getName={(r) => r?.label}
|
||||
onDelete={(entity) => permanentlyDeletePlan(entity?.plan_id)}
|
||||
onImpactCheck={() => fetchPlanPermanentDeleteImpact(deleteTarget?.plan_id)}
|
||||
loading={loading}
|
||||
onSuccess={handleDeleteSuccess}
|
||||
/>
|
||||
|
||||
{/* Bulk permanent delete */}
|
||||
<PermanentDeleteDialog
|
||||
open={!!deleteIds}
|
||||
onOpenChange={(v) => !v && setDeleteIds(null)}
|
||||
ids={deleteIds ?? []}
|
||||
entityLabel="Plan"
|
||||
onDelete={({ ids }) => bulkPermanentlyDeletePlans(ids)}
|
||||
loading={loading}
|
||||
onSuccess={handleDeleteSuccess}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
// BundlesCell — Tier Plans table cell showing the bundled content count for a
|
||||
// plan. A bundle is single-type (Tier Plans v2), so only one of
|
||||
// courseCount/unitCount/lessonCount is ever non-zero — show that one.
|
||||
|
||||
import { BookOpen, Book, BookOpenCheck } from "lucide-react";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
|
||||
const BUNDLE_KINDS = [
|
||||
{ key: "courseCount", icon: BookOpen, singular: "course", plural: "courses" },
|
||||
{ key: "unitCount", icon: Book, singular: "unit", plural: "units" },
|
||||
{ key: "lessonCount", icon: BookOpenCheck, singular: "lesson", plural: "lessons" },
|
||||
];
|
||||
|
||||
export default function BundlesCell({ plan }) {
|
||||
const active = BUNDLE_KINDS.find((k) => parseInt(plan[k.key] ?? 0, 10) > 0) ?? BUNDLE_KINDS[0];
|
||||
const count = parseInt(plan[active.key] ?? 0, 10);
|
||||
const Icon = active.icon;
|
||||
|
||||
return (
|
||||
<div className="flex items-center gap-1.5">
|
||||
<Icon className="h-3.5 w-3.5 text-muted-foreground" />
|
||||
<Badge variant="secondary" className="text-xs font-medium tabular-nums">
|
||||
{count} {count === 1 ? active.singular : active.plural}
|
||||
</Badge>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
import { useState, useEffect, useMemo } from "react";
|
||||
import { ChevronsUpDown, BookOpen } from "lucide-react";
|
||||
import api from "@/utils/api.util";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Checkbox } from "@/components/ui/checkbox";
|
||||
import { ScrollArea } from "@/components/ui/scroll-area";
|
||||
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
|
||||
import { Command, CommandInput, CommandEmpty, CommandList, CommandItem } from "@/components/ui/command";
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
|
||||
/**
|
||||
* CoursePicker
|
||||
*
|
||||
* Props:
|
||||
* subscription — tier slug ("premium"). Null/undefined = hidden.
|
||||
* selectedIds — Set<string> of selected course_id strings (managed by parent)
|
||||
* onChange — (Set<string>) => void
|
||||
*
|
||||
* A course may already belong to any number of other plans — that's allowed
|
||||
* (Tier Plans v2, silent duplication across bundles is intentional), so
|
||||
* there's no conflict state to surface or resolve here.
|
||||
*
|
||||
* AddPlan starts with no courses selected; the admin picks specific ones
|
||||
* directly in the dropdown. EditPlan preserves whatever was already assigned.
|
||||
*/
|
||||
export function CoursePicker({ subscription, selectedIds, onChange }) {
|
||||
const [courses, setCourses] = useState([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [popoverOpen, setPopoverOpen] = useState(false);
|
||||
const [search, setSearch] = useState("");
|
||||
|
||||
useEffect(() => {
|
||||
if (!subscription) { setCourses([]); return; }
|
||||
setLoading(true);
|
||||
setSearch("");
|
||||
|
||||
api.get(`/admin/courses/by-subscription?slug=${encodeURIComponent(subscription)}`)
|
||||
.then(({ data }) => {
|
||||
const loaded = data.data ?? [];
|
||||
setCourses(loaded);
|
||||
// AddPlan starts with none selected; EditPlan keeps its existing selection as-is.
|
||||
})
|
||||
.catch(() => setCourses([]))
|
||||
.finally(() => setLoading(false));
|
||||
}, [subscription]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
const filtered = useMemo(() => {
|
||||
const q = search.toLowerCase();
|
||||
if (!q) return courses;
|
||||
return courses.filter(
|
||||
(c) =>
|
||||
c.title?.toLowerCase().includes(q) ||
|
||||
c.description?.toLowerCase().includes(q)
|
||||
);
|
||||
}, [courses, search]);
|
||||
|
||||
const toggle = (id) => {
|
||||
const next = new Set(selectedIds);
|
||||
if (next.has(id)) next.delete(id);
|
||||
else next.add(id);
|
||||
onChange(next);
|
||||
};
|
||||
|
||||
const checkAll = () => onChange(new Set(courses.map((c) => String(c.course_id))));
|
||||
const resetAll = () => onChange(new Set());
|
||||
|
||||
const total = courses.length;
|
||||
const selectedCount = selectedIds.size;
|
||||
|
||||
if (!subscription) return null;
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
|
||||
{loading ? (
|
||||
<div className="flex gap-2">
|
||||
<Skeleton className="h-8 w-full" />
|
||||
</div>
|
||||
) : total === 0 ? (
|
||||
<div className="flex items-center gap-2 rounded-lg border border-dashed p-4 text-sm text-muted-foreground">
|
||||
<BookOpen className="size-4 shrink-0" />
|
||||
No <span className="capitalize mx-1 font-medium">{subscription}</span> courses found. Add courses with this subscription first.
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-1.5">
|
||||
<Popover open={popoverOpen} onOpenChange={setPopoverOpen}>
|
||||
<PopoverTrigger asChild>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="w-full justify-between gap-2"
|
||||
>
|
||||
{selectedCount === 0
|
||||
? "No courses selected"
|
||||
: `${selectedCount} of ${total} course${total !== 1 ? "s" : ""} selected`
|
||||
}
|
||||
<ChevronsUpDown className="size-4 opacity-50 shrink-0" />
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
|
||||
<PopoverContent className="w-[var(--radix-popover-trigger-width)] p-0" align="start">
|
||||
<Command shouldFilter={false}>
|
||||
<CommandInput
|
||||
placeholder="Search courses…"
|
||||
value={search}
|
||||
onValueChange={setSearch}
|
||||
/>
|
||||
<CommandList>
|
||||
{filtered.length === 0 ? (
|
||||
<CommandEmpty>No courses match your search.</CommandEmpty>
|
||||
) : (
|
||||
<ScrollArea className="h-64">
|
||||
{filtered.map((course) => {
|
||||
const id = String(course.course_id);
|
||||
const checked = selectedIds.has(id);
|
||||
return (
|
||||
<CommandItem
|
||||
key={id}
|
||||
value={id}
|
||||
onSelect={() => toggle(id)}
|
||||
className="flex items-start gap-3 px-3 py-2.5 cursor-pointer"
|
||||
>
|
||||
<Checkbox
|
||||
checked={checked}
|
||||
onCheckedChange={() => toggle(id)}
|
||||
className="mt-0.5 shrink-0"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
/>
|
||||
<div className="flex flex-col gap-0.5 min-w-0">
|
||||
<span className="text-sm font-medium leading-snug">{course.title}</span>
|
||||
{course.description && (
|
||||
<span className="text-xs text-muted-foreground line-clamp-1">
|
||||
{course.description}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</CommandItem>
|
||||
);
|
||||
})}
|
||||
</ScrollArea>
|
||||
)}
|
||||
</CommandList>
|
||||
|
||||
{/* Popover footer */}
|
||||
<div className="border-t px-3 py-2 flex items-center justify-between gap-2">
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{selectedCount} of {total} selected
|
||||
</span>
|
||||
<div className="flex items-center gap-2">
|
||||
<Checkbox
|
||||
checked={selectedCount === total ? true : selectedCount > 0 ? "indeterminate" : false}
|
||||
onCheckedChange={(v) => v ? checkAll() : resetAll()}
|
||||
/>
|
||||
<span className="text-xs text-muted-foreground select-none">
|
||||
{selectedCount === total ? "Deselect all" : "Select all"}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</Command>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
|
||||
{selectedCount === 0 && (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Select at least one course to bundle with this plan.
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import { useState } from "react";
|
||||
import { ChevronsUpDown } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
|
||||
import {
|
||||
Command, CommandEmpty, CommandGroup,
|
||||
CommandInput, CommandItem, CommandList,
|
||||
} from "@/components/ui/command";
|
||||
import { ScrollArea } from "@/components/ui/scroll-area";
|
||||
|
||||
export function CurrencyPicker({ value, currencies, onValueChange }) {
|
||||
const [open, setOpen] = useState(false);
|
||||
|
||||
const selected = currencies.find((c) => c.code === value);
|
||||
const label = selected ? `${selected.code} — ${selected.name}` : "Select currency";
|
||||
|
||||
return (
|
||||
<Popover open={open} onOpenChange={setOpen}>
|
||||
<PopoverTrigger asChild>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
role="combobox"
|
||||
aria-expanded={open}
|
||||
className="w-full justify-between font-normal"
|
||||
>
|
||||
<span className="truncate">{label}</span>
|
||||
<ChevronsUpDown className="ml-2 size-4 shrink-0 opacity-50" />
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent
|
||||
align="start"
|
||||
className="w-[--radix-popover-trigger-width] p-0"
|
||||
>
|
||||
<Command>
|
||||
<CommandInput placeholder="Search currency…" />
|
||||
<ScrollArea className="h-64">
|
||||
<CommandList className="max-h-none">
|
||||
<CommandEmpty>No currency found.</CommandEmpty>
|
||||
<CommandGroup>
|
||||
{currencies.map((c) => (
|
||||
<CommandItem
|
||||
key={c.code}
|
||||
value={`${c.code} ${c.name}`}
|
||||
data-checked={value === c.code}
|
||||
onSelect={() => {
|
||||
onValueChange(c.code);
|
||||
setOpen(false);
|
||||
}}
|
||||
>
|
||||
{c.code} — {c.name}
|
||||
</CommandItem>
|
||||
))}
|
||||
</CommandGroup>
|
||||
</CommandList>
|
||||
</ScrollArea>
|
||||
</Command>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
import { useState, useEffect, useMemo } from "react";
|
||||
import { ChevronsUpDown, FileText } from "lucide-react";
|
||||
import api from "@/utils/api.util";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Checkbox } from "@/components/ui/checkbox";
|
||||
import { ScrollArea } from "@/components/ui/scroll-area";
|
||||
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
|
||||
import { Command, CommandInput, CommandEmpty, CommandList, CommandItem } from "@/components/ui/command";
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
|
||||
/**
|
||||
* LessonPicker — mirrors CoursePicker.jsx exactly, for bundling standalone
|
||||
* Lessons (their own `subscription` field) into a tier plan.
|
||||
*
|
||||
* Props: same contract as CoursePicker (subscription, selectedIds, onChange)
|
||||
* — see CoursePicker.jsx for the full doc comment, not repeated here.
|
||||
* A lesson may already belong to any number of other plans — that's
|
||||
* allowed (Tier Plans v2, silent duplication across bundles is intentional),
|
||||
* so there's no conflict state to surface or resolve here.
|
||||
*
|
||||
* AddPlan starts with no lessons selected; the admin picks specific ones
|
||||
* directly in the dropdown. EditPlan preserves whatever was already assigned.
|
||||
*/
|
||||
export function LessonPicker({ subscription, selectedIds, onChange }) {
|
||||
const [lessons, setLessons] = useState([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [popoverOpen, setPopoverOpen] = useState(false);
|
||||
const [search, setSearch] = useState("");
|
||||
|
||||
useEffect(() => {
|
||||
if (!subscription) { setLessons([]); return; }
|
||||
setLoading(true);
|
||||
setSearch("");
|
||||
|
||||
api.get(`/admin/lessons/by-subscription?slug=${encodeURIComponent(subscription)}`)
|
||||
.then(({ data }) => {
|
||||
const loaded = data.data ?? [];
|
||||
setLessons(loaded);
|
||||
// AddPlan starts with none selected; EditPlan keeps its existing selection as-is.
|
||||
})
|
||||
.catch(() => setLessons([]))
|
||||
.finally(() => setLoading(false));
|
||||
}, [subscription]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
const filtered = useMemo(() => {
|
||||
const q = search.toLowerCase();
|
||||
if (!q) return lessons;
|
||||
return lessons.filter(
|
||||
(l) =>
|
||||
l.title?.toLowerCase().includes(q) ||
|
||||
l.description?.toLowerCase().includes(q)
|
||||
);
|
||||
}, [lessons, search]);
|
||||
|
||||
const toggle = (id) => {
|
||||
const next = new Set(selectedIds);
|
||||
if (next.has(id)) next.delete(id);
|
||||
else next.add(id);
|
||||
onChange(next);
|
||||
};
|
||||
|
||||
const checkAll = () => onChange(new Set(lessons.map((l) => String(l.lesson_id))));
|
||||
const resetAll = () => onChange(new Set());
|
||||
|
||||
const total = lessons.length;
|
||||
const selectedCount = selectedIds.size;
|
||||
|
||||
if (!subscription) return null;
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
|
||||
{loading ? (
|
||||
<div className="flex gap-2">
|
||||
<Skeleton className="h-8 w-full" />
|
||||
</div>
|
||||
) : total === 0 ? (
|
||||
<div className="flex items-center gap-2 rounded-lg border border-dashed p-4 text-sm text-muted-foreground">
|
||||
<FileText className="size-4 shrink-0" />
|
||||
No <span className="capitalize mx-1 font-medium">{subscription}</span> lessons found. Add lessons with this subscription first.
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-1.5">
|
||||
<Popover open={popoverOpen} onOpenChange={setPopoverOpen}>
|
||||
<PopoverTrigger asChild>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="w-full justify-between gap-2"
|
||||
>
|
||||
{selectedCount === 0
|
||||
? "No lessons selected"
|
||||
: `${selectedCount} of ${total} lesson${total !== 1 ? "s" : ""} selected`
|
||||
}
|
||||
<ChevronsUpDown className="size-4 opacity-50 shrink-0" />
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
|
||||
<PopoverContent className="w-[var(--radix-popover-trigger-width)] p-0" align="start">
|
||||
<Command shouldFilter={false}>
|
||||
<CommandInput
|
||||
placeholder="Search lessons…"
|
||||
value={search}
|
||||
onValueChange={setSearch}
|
||||
/>
|
||||
<CommandList>
|
||||
{filtered.length === 0 ? (
|
||||
<CommandEmpty>No lessons match your search.</CommandEmpty>
|
||||
) : (
|
||||
<ScrollArea className="h-64">
|
||||
{filtered.map((lesson) => {
|
||||
const id = String(lesson.lesson_id);
|
||||
const checked = selectedIds.has(id);
|
||||
return (
|
||||
<CommandItem
|
||||
key={id}
|
||||
value={id}
|
||||
onSelect={() => toggle(id)}
|
||||
className="flex items-start gap-3 px-3 py-2.5 cursor-pointer"
|
||||
>
|
||||
<Checkbox
|
||||
checked={checked}
|
||||
onCheckedChange={() => toggle(id)}
|
||||
className="mt-0.5 shrink-0"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
/>
|
||||
<div className="flex flex-col gap-0.5 min-w-0">
|
||||
<span className="text-sm font-medium leading-snug">{lesson.title}</span>
|
||||
{lesson.description && (
|
||||
<span className="text-xs text-muted-foreground line-clamp-1">
|
||||
{lesson.description}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</CommandItem>
|
||||
);
|
||||
})}
|
||||
</ScrollArea>
|
||||
)}
|
||||
</CommandList>
|
||||
|
||||
{/* Popover footer */}
|
||||
<div className="border-t px-3 py-2 flex items-center justify-between gap-2">
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{selectedCount} of {total} selected
|
||||
</span>
|
||||
<div className="flex items-center gap-2">
|
||||
<Checkbox
|
||||
checked={selectedCount === total ? true : selectedCount > 0 ? "indeterminate" : false}
|
||||
onCheckedChange={(v) => v ? checkAll() : resetAll()}
|
||||
/>
|
||||
<span className="text-xs text-muted-foreground select-none">
|
||||
{selectedCount === total ? "Deselect all" : "Select all"}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</Command>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
|
||||
{selectedCount === 0 && (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Select at least one lesson to bundle with this plan.
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
import { useMemo, useRef, useCallback, useEffect, useState } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { useTiers } from "@/contexts/AdminTiersContext";
|
||||
import { useAuth } from "@/contexts/AuthContext";
|
||||
import { useDateFormat } from "@/hooks/useDateFormat";
|
||||
import api from "@/utils/api.util";
|
||||
import DataTable from "@/components/generic/Table/DataTable";
|
||||
import { FilterSheet } from "@/components/generic/Sheet/FilterSheet";
|
||||
import { buildDataColumns, columnPinning } from "../../config/tiers/payments/columns.config";
|
||||
import { buildToolbarActions } from "../../config/tiers/payments/toolbar.config";
|
||||
import { buildSelectionActions } from "../../config/tiers/payments/selection.config";
|
||||
import { buildRowActions } from "../../config/tiers/payments/rowActions.config";
|
||||
import { getTimestamp } from "@/utils/timestamp.util";
|
||||
import { formatGeneratedBy } from "@/utils/generatedBy.util";
|
||||
|
||||
export default function PaymentsTable({ planId = null }) {
|
||||
const tableRefsRef = useRef({
|
||||
getFilters: () => [],
|
||||
getSort: () => [],
|
||||
resetSelection: () => { },
|
||||
setFilters: () => { },
|
||||
});
|
||||
|
||||
const navigate = useNavigate();
|
||||
const { fmtDateTime } = useDateFormat();
|
||||
const { user: currentUser } = useAuth();
|
||||
|
||||
const {
|
||||
payments, paymentAttributes,
|
||||
paymentPagination, setPaymentPagination,
|
||||
loading, fetchPayments,
|
||||
} = useTiers();
|
||||
|
||||
const [tierCategories, setTierCategories] = useState([]);
|
||||
const tierMap = useMemo(() => Object.fromEntries(tierCategories.map((c) => [c.slug, c])), [tierCategories]);
|
||||
|
||||
useEffect(() => {
|
||||
api.get("/admin/tiers/categories").then(({ data }) => setTierCategories(data.data ?? [])).catch(() => {});
|
||||
}, []);
|
||||
|
||||
const exportConfig = {
|
||||
allData: payments,
|
||||
attributes: paymentAttributes,
|
||||
filename: `${getTimestamp()}_Payments`,
|
||||
sheetName: "Payments",
|
||||
generatedBy: formatGeneratedBy(currentUser),
|
||||
};
|
||||
|
||||
const rowActions = useMemo(() => buildRowActions({
|
||||
onView: (row) => navigate(`/admin/tiers/payments/${row.payment_id}/view`),
|
||||
}), []);
|
||||
|
||||
const toolbarActions = buildToolbarActions({
|
||||
fetchPayments,
|
||||
pagination: paymentPagination,
|
||||
exportConfig,
|
||||
getFilters: () => tableRefsRef.current.getFilters(),
|
||||
getSort: () => tableRefsRef.current.getSort(),
|
||||
getTableInstance: () => tableRefsRef.current.tableInstance,
|
||||
});
|
||||
|
||||
const selectionActions = buildSelectionActions({
|
||||
exportConfig,
|
||||
getTableInstance: () => tableRefsRef.current.tableInstance,
|
||||
});
|
||||
|
||||
const columns = useMemo(
|
||||
() => buildDataColumns(paymentAttributes, rowActions, fmtDateTime, tierMap),
|
||||
[paymentAttributes, fmtDateTime, tierMap]
|
||||
);
|
||||
|
||||
// Pass planId as a locked filter to DataTable's onFetch
|
||||
const handleFetch = useCallback((params = {}) => {
|
||||
const baseFilters = planId
|
||||
? [{ id: "plan_id", value: planId }, ...(params.filters ?? [])]
|
||||
: (params.filters ?? []);
|
||||
fetchPayments({ ...params, filters: baseFilters });
|
||||
}, [planId, fetchPayments]);
|
||||
|
||||
return (
|
||||
<DataTable
|
||||
title="Payments"
|
||||
data={payments}
|
||||
columns={columns}
|
||||
attributes={paymentAttributes}
|
||||
pagination={paymentPagination}
|
||||
setPagination={setPaymentPagination}
|
||||
loading={loading}
|
||||
onFetch={handleFetch}
|
||||
onFetchFilterData={async () => []}
|
||||
onRefsReady={(refs) => { tableRefsRef.current = refs; }}
|
||||
renderFilterSheet={({ open, onOpenChange, column, attr, data, loading }) => (
|
||||
<FilterSheet
|
||||
open={open}
|
||||
onOpenChange={onOpenChange}
|
||||
column={column}
|
||||
attr={attr}
|
||||
data={data}
|
||||
loading={loading}
|
||||
/>
|
||||
)}
|
||||
columnPinning={columnPinning}
|
||||
toolbarActions={toolbarActions}
|
||||
selectionActions={selectionActions}
|
||||
recordLabel="payment"
|
||||
emptyMessage="No payments found."
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
import { useMemo, useRef, useState, useEffect } from "react";
|
||||
import { useNavigate, Link } from "react-router-dom";
|
||||
import { Layers } from "lucide-react";
|
||||
|
||||
import { useTiers } from "@/contexts/AdminTiersContext";
|
||||
import { useAuth } from "@/contexts/AuthContext";
|
||||
import api from "@/utils/api.util";
|
||||
|
||||
import DataTable from "@/components/generic/Table/DataTable";
|
||||
import { FilterSheet } from "@/components/generic/Sheet/FilterSheet";
|
||||
import { ArchiveDialog } from "@/components/generic/Dialogs/ArchiveDialog";
|
||||
|
||||
import { buildDataColumns, columnPinning } from "../../config/tiers/plans/columns.config";
|
||||
import { buildToolbarActions } from "../../config/tiers/plans/toolbar.config";
|
||||
import { buildSelectionActions } from "../../config/tiers/plans/selection.config";
|
||||
import { buildRowActions } from "../../config/tiers/plans/rowActions.config";
|
||||
|
||||
import { getTimestamp } from "@/utils/timestamp.util";
|
||||
import { formatGeneratedBy } from "@/utils/generatedBy.util";
|
||||
|
||||
export default function TierPlansTable() {
|
||||
const navigate = useNavigate();
|
||||
|
||||
const { user: currentUser } = useAuth();
|
||||
|
||||
const {
|
||||
plans, planAttributes, planPagination, setPlanPagination,
|
||||
loading, fetchPlans, deletePlan, bulkDeletePlans,
|
||||
} = useTiers();
|
||||
|
||||
const [hasAvailableCategories, setHasAvailableCategories] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
api.get("/admin/tiers/categories")
|
||||
.then(({ data }) => {
|
||||
const available = (data.data ?? []).filter((c) => !c.is_default && c.is_active);
|
||||
setHasAvailableCategories(available.length > 0);
|
||||
})
|
||||
.catch(() => {});
|
||||
}, []);
|
||||
|
||||
const [archiveTarget, setArchiveTarget] = useState(null);
|
||||
const [archiveIds, setArchiveIds] = useState(null);
|
||||
|
||||
const tableRefsRef = useRef({
|
||||
getFilters: () => [],
|
||||
getSort: () => [],
|
||||
resetSelection: () => {},
|
||||
tableInstance: null,
|
||||
});
|
||||
|
||||
const handleRefsReady = (refs) => { tableRefsRef.current = refs; };
|
||||
|
||||
const handleSuccess = () => {
|
||||
setArchiveTarget(null);
|
||||
setArchiveIds(null);
|
||||
tableRefsRef.current.resetSelection?.();
|
||||
fetchPlans({
|
||||
page: 1,
|
||||
limit: planPagination?.limit ?? 10,
|
||||
filters: tableRefsRef.current.getFilters(),
|
||||
sort: tableRefsRef.current.getSort(),
|
||||
});
|
||||
};
|
||||
|
||||
const exportConfig = useMemo(() => ({
|
||||
allData: plans,
|
||||
attributes: planAttributes,
|
||||
filename: `${getTimestamp()}_TierPlans`,
|
||||
sheetName: "Subscriptions",
|
||||
generatedBy: formatGeneratedBy(currentUser),
|
||||
}), [plans, planAttributes, currentUser]);
|
||||
|
||||
const rowActions = buildRowActions({
|
||||
navigate,
|
||||
onArchive: (row) => setArchiveTarget(row),
|
||||
});
|
||||
|
||||
const toolbarActions = buildToolbarActions({
|
||||
fetchPlans,
|
||||
pagination: planPagination,
|
||||
exportConfig,
|
||||
navigate,
|
||||
hasAvailableCategories,
|
||||
getFilters: () => tableRefsRef.current.getFilters(),
|
||||
getSort: () => tableRefsRef.current.getSort(),
|
||||
getTableInstance: () => tableRefsRef.current.tableInstance,
|
||||
});
|
||||
|
||||
const selectionActions = buildSelectionActions({
|
||||
exportConfig,
|
||||
onArchive: (row) => setArchiveTarget(row),
|
||||
onArchiveMany: (ids) => setArchiveIds(ids),
|
||||
getTableInstance: () => tableRefsRef.current.tableInstance,
|
||||
});
|
||||
|
||||
const columns = useMemo(
|
||||
() => buildDataColumns(planAttributes, rowActions),
|
||||
[planAttributes, rowActions]
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
{!hasAvailableCategories && (
|
||||
<div className="rounded-lg border bg-card p-4 flex items-start gap-3 mb-4">
|
||||
<Layers className="h-4 w-4 text-muted-foreground mt-0.5 shrink-0" />
|
||||
<p className="text-sm text-muted-foreground">
|
||||
No subscription categories defined.{" "}
|
||||
<Link to="/admin/tiers/categories/add" className="underline text-primary font-medium">
|
||||
Add a subscription category
|
||||
</Link>{" "}
|
||||
before creating plans.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
<DataTable
|
||||
title="Subscriptions"
|
||||
data={plans}
|
||||
columns={columns}
|
||||
attributes={planAttributes}
|
||||
pagination={planPagination}
|
||||
setPagination={setPlanPagination}
|
||||
loading={loading}
|
||||
onFetch={fetchPlans}
|
||||
onFetchFilterData={async () => []}
|
||||
onRefsReady={handleRefsReady}
|
||||
renderFilterSheet={({ open, onOpenChange, column, attr, data, loading }) => (
|
||||
<FilterSheet
|
||||
open={open}
|
||||
onOpenChange={onOpenChange}
|
||||
column={column}
|
||||
attr={attr}
|
||||
data={data}
|
||||
loading={loading}
|
||||
/>
|
||||
)}
|
||||
columnPinning={columnPinning}
|
||||
toolbarActions={toolbarActions}
|
||||
selectionActions={selectionActions}
|
||||
recordLabel="plan"
|
||||
emptyMessage="No subscriptions found."
|
||||
/>
|
||||
|
||||
{/* Single archive — always force-revokes current subscribers' access (no refund), handled server-side */}
|
||||
<ArchiveDialog
|
||||
open={!!archiveTarget}
|
||||
onOpenChange={(v) => !v && setArchiveTarget(null)}
|
||||
entity={archiveTarget}
|
||||
entityLabel="Plan"
|
||||
getName={(r) => r?.label}
|
||||
onArchive={(entity) => deletePlan(entity?.plan_id)}
|
||||
loading={loading}
|
||||
onSuccess={handleSuccess}
|
||||
onImpactCheck={async () => {
|
||||
const { data } = await api.get(`/admin/tiers/${archiveTarget?.plan_id}/impact`);
|
||||
return [{ label: "active subscriber(s) on this plan — access will be revoked, no refund", count: data.data?.active_subscriber_count ?? 0 }];
|
||||
}}
|
||||
/>
|
||||
|
||||
{/* Bulk archive */}
|
||||
<ArchiveDialog
|
||||
open={!!archiveIds}
|
||||
onOpenChange={(v) => !v && setArchiveIds(null)}
|
||||
ids={archiveIds ?? []}
|
||||
entityLabel="Plan"
|
||||
onArchive={({ ids }) => bulkDeletePlans(ids)}
|
||||
loading={loading}
|
||||
onSuccess={handleSuccess}
|
||||
/>
|
||||
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
import { useState, useEffect, useMemo } from "react";
|
||||
import { ChevronsUpDown, BookOpen } from "lucide-react";
|
||||
import api from "@/utils/api.util";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Checkbox } from "@/components/ui/checkbox";
|
||||
import { ScrollArea } from "@/components/ui/scroll-area";
|
||||
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
|
||||
import { Command, CommandInput, CommandEmpty, CommandList, CommandItem } from "@/components/ui/command";
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
|
||||
/**
|
||||
* UnitPicker — mirrors CoursePicker.jsx exactly, for bundling standalone
|
||||
* Units (their own `subscription` field) into a tier plan.
|
||||
*
|
||||
* Props: same contract as CoursePicker (subscription, selectedIds, onChange)
|
||||
* — see CoursePicker.jsx for the full doc comment, not repeated here.
|
||||
* A unit may already belong to any number of other plans — that's
|
||||
* allowed (Tier Plans v2, silent duplication across bundles is intentional),
|
||||
* so there's no conflict state to surface or resolve here.
|
||||
*
|
||||
* AddPlan starts with no units selected; the admin picks specific ones
|
||||
* directly in the dropdown. EditPlan preserves whatever was already assigned.
|
||||
*/
|
||||
export function UnitPicker({ subscription, selectedIds, onChange }) {
|
||||
const [units, setUnits] = useState([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [popoverOpen, setPopoverOpen] = useState(false);
|
||||
const [search, setSearch] = useState("");
|
||||
|
||||
useEffect(() => {
|
||||
if (!subscription) { setUnits([]); return; }
|
||||
setLoading(true);
|
||||
setSearch("");
|
||||
|
||||
api.get(`/admin/units/by-subscription?slug=${encodeURIComponent(subscription)}`)
|
||||
.then(({ data }) => {
|
||||
const loaded = data.data ?? [];
|
||||
setUnits(loaded);
|
||||
// AddPlan starts with none selected; EditPlan keeps its existing selection as-is.
|
||||
})
|
||||
.catch(() => setUnits([]))
|
||||
.finally(() => setLoading(false));
|
||||
}, [subscription]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
const filtered = useMemo(() => {
|
||||
const q = search.toLowerCase();
|
||||
if (!q) return units;
|
||||
return units.filter(
|
||||
(u) =>
|
||||
u.title?.toLowerCase().includes(q) ||
|
||||
u.description?.toLowerCase().includes(q)
|
||||
);
|
||||
}, [units, search]);
|
||||
|
||||
const toggle = (id) => {
|
||||
const next = new Set(selectedIds);
|
||||
if (next.has(id)) next.delete(id);
|
||||
else next.add(id);
|
||||
onChange(next);
|
||||
};
|
||||
|
||||
const checkAll = () => onChange(new Set(units.map((u) => String(u.unit_id))));
|
||||
const resetAll = () => onChange(new Set());
|
||||
|
||||
const total = units.length;
|
||||
const selectedCount = selectedIds.size;
|
||||
|
||||
if (!subscription) return null;
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
|
||||
{loading ? (
|
||||
<div className="flex gap-2">
|
||||
<Skeleton className="h-8 w-full" />
|
||||
</div>
|
||||
) : total === 0 ? (
|
||||
<div className="flex items-center gap-2 rounded-lg border border-dashed p-4 text-sm text-muted-foreground">
|
||||
<BookOpen className="size-4 shrink-0" />
|
||||
No <span className="capitalize mx-1 font-medium">{subscription}</span> units found. Add units with this subscription first.
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-1.5">
|
||||
<Popover open={popoverOpen} onOpenChange={setPopoverOpen}>
|
||||
<PopoverTrigger asChild>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="w-full justify-between gap-2"
|
||||
>
|
||||
{selectedCount === 0
|
||||
? "No units selected"
|
||||
: `${selectedCount} of ${total} unit${total !== 1 ? "s" : ""} selected`
|
||||
}
|
||||
<ChevronsUpDown className="size-4 opacity-50 shrink-0" />
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
|
||||
<PopoverContent className="w-[var(--radix-popover-trigger-width)] p-0" align="start">
|
||||
<Command shouldFilter={false}>
|
||||
<CommandInput
|
||||
placeholder="Search units…"
|
||||
value={search}
|
||||
onValueChange={setSearch}
|
||||
/>
|
||||
<CommandList>
|
||||
{filtered.length === 0 ? (
|
||||
<CommandEmpty>No units match your search.</CommandEmpty>
|
||||
) : (
|
||||
<ScrollArea className="h-64">
|
||||
{filtered.map((unit) => {
|
||||
const id = String(unit.unit_id);
|
||||
const checked = selectedIds.has(id);
|
||||
return (
|
||||
<CommandItem
|
||||
key={id}
|
||||
value={id}
|
||||
onSelect={() => toggle(id)}
|
||||
className="flex items-start gap-3 px-3 py-2.5 cursor-pointer"
|
||||
>
|
||||
<Checkbox
|
||||
checked={checked}
|
||||
onCheckedChange={() => toggle(id)}
|
||||
className="mt-0.5 shrink-0"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
/>
|
||||
<div className="flex flex-col gap-0.5 min-w-0">
|
||||
<span className="text-sm font-medium leading-snug">{unit.title}</span>
|
||||
{unit.description && (
|
||||
<span className="text-xs text-muted-foreground line-clamp-1">
|
||||
{unit.description}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</CommandItem>
|
||||
);
|
||||
})}
|
||||
</ScrollArea>
|
||||
)}
|
||||
</CommandList>
|
||||
|
||||
{/* Popover footer */}
|
||||
<div className="border-t px-3 py-2 flex items-center justify-between gap-2">
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{selectedCount} of {total} selected
|
||||
</span>
|
||||
<div className="flex items-center gap-2">
|
||||
<Checkbox
|
||||
checked={selectedCount === total ? true : selectedCount > 0 ? "indeterminate" : false}
|
||||
onCheckedChange={(v) => v ? checkAll() : resetAll()}
|
||||
/>
|
||||
<span className="text-xs text-muted-foreground select-none">
|
||||
{selectedCount === total ? "Deselect all" : "Select all"}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</Command>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
|
||||
{selectedCount === 0 && (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Select at least one unit to bundle with this plan.
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
// modules/admin/components/user_groups/AddGroupDialog.jsx
|
||||
|
||||
import { useForm } from "react-hook-form";
|
||||
import { z } from "zod";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogFooter,
|
||||
DialogClose,
|
||||
} from "@/components/ui/dialog";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Label } from "@/components/ui/label";
|
||||
|
||||
const schema = z.object({
|
||||
name: z.string().min(1, "Name is required."),
|
||||
description: z.string().min(1, "Description is required."),
|
||||
group_code: z
|
||||
.string()
|
||||
.max(50, "Group code must be 50 characters or less.")
|
||||
.regex(/^[A-Z0-9\-]*$/, "Only uppercase letters, numbers, and hyphens allowed.")
|
||||
.optional()
|
||||
.or(z.literal("")),
|
||||
});
|
||||
|
||||
/**
|
||||
* Dialog for creating a new group.
|
||||
* Matches context: createGroup({ name, description, group_code })
|
||||
*
|
||||
* group_code is optional — if left blank the backend auto-generates one.
|
||||
*
|
||||
* @param {Object} props
|
||||
* @param {boolean} props.open
|
||||
* @param {Function} props.onOpenChange
|
||||
* @param {Function} props.onSubmit Called with { name, description, group_code? }
|
||||
* @param {boolean} [props.loading]
|
||||
*/
|
||||
export function AddGroupDialog({ open, onOpenChange, onSubmit, loading }) {
|
||||
const {
|
||||
register,
|
||||
handleSubmit,
|
||||
reset,
|
||||
watch,
|
||||
setValue,
|
||||
formState: { errors },
|
||||
} = useForm({
|
||||
resolver: zodResolver(schema),
|
||||
defaultValues: { name: "", description: "", group_code: "" },
|
||||
});
|
||||
|
||||
async function onValid({ name, description, group_code }) {
|
||||
await onSubmit({
|
||||
name,
|
||||
description,
|
||||
// omit group_code entirely if blank — backend will auto-generate
|
||||
...(group_code ? { group_code } : {}),
|
||||
});
|
||||
reset();
|
||||
}
|
||||
|
||||
function handleClose() {
|
||||
reset();
|
||||
onOpenChange(false);
|
||||
}
|
||||
|
||||
// Auto-uppercase as user types
|
||||
function handleGroupCodeChange(e) {
|
||||
setValue("group_code", e.target.value.toUpperCase().replace(/[^A-Z0-9\-]/g, ""), {
|
||||
shouldValidate: true,
|
||||
});
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={handleClose}>
|
||||
<DialogContent className="sm:max-w-[440px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Add group</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<form onSubmit={handleSubmit(onValid)} className="space-y-4">
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="name">
|
||||
Name <span className="text-destructive">*</span>
|
||||
</Label>
|
||||
<Input
|
||||
id="name"
|
||||
placeholder="Group name"
|
||||
{...register("name")}
|
||||
/>
|
||||
{errors.name && (
|
||||
<p className="text-sm text-destructive">{errors.name.message}</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="description">
|
||||
Description <span className="text-destructive">*</span>
|
||||
</Label>
|
||||
<Textarea
|
||||
id="description"
|
||||
placeholder="Brief description of this group"
|
||||
className="resize-none"
|
||||
rows={3}
|
||||
{...register("description")}
|
||||
/>
|
||||
{errors.description && (
|
||||
<p className="text-sm text-destructive">{errors.description.message}</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="group_code" className="flex items-center gap-2">
|
||||
Group code
|
||||
<span className="text-xs font-normal text-muted-foreground">(auto-generated if blank)</span>
|
||||
</Label>
|
||||
<Input
|
||||
id="group_code"
|
||||
placeholder="e.g. SALES-2025"
|
||||
{...register("group_code")}
|
||||
onChange={handleGroupCodeChange}
|
||||
/>
|
||||
{errors.group_code && (
|
||||
<p className="text-sm text-destructive">{errors.group_code.message}</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<DialogClose asChild>
|
||||
<Button type="button" variant="outline" disabled={loading}>Cancel</Button>
|
||||
</DialogClose>
|
||||
<Button type="submit" disabled={loading}>
|
||||
{loading ? "Creating..." : "Add group"}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
import { useMemo, useRef, useState } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
|
||||
import { useUserGroups } from "@/contexts/AdminUserGroupContext";
|
||||
import { useAuth } from "@/contexts/AuthContext";
|
||||
import DataTable from "@/components/generic/Table/DataTable";
|
||||
import { FilterSheet } from "@/components/generic/Sheet/FilterSheet";
|
||||
import { RestoreDialog } from "@/components/generic/Dialogs/RestoreDialog";
|
||||
import { PermanentDeleteDialog } from "@/components/generic/Dialogs/PermanentDeleteDialog";
|
||||
|
||||
import { buildDataColumns, columnPinning } from "../../config/user_groups/archive/columns.config";
|
||||
import { buildToolbarActions } from "../../config/user_groups/archive/toolbar.config";
|
||||
import { buildSelectionActions } from "../../config/user_groups/archive/selection.config";
|
||||
import { buildRowActions } from "../../config/user_groups/archive/rowActions.config";
|
||||
|
||||
import { getTimestamp } from "@/utils/timestamp.util";
|
||||
import { formatGeneratedBy } from "@/utils/generatedBy.util";
|
||||
|
||||
export default function ArchiveGroupTable() {
|
||||
const [restoreTarget, setRestoreTarget] = useState(null); // single: row object
|
||||
const [restoreIds, setRestoreIds] = useState(null); // bulk: array of ids
|
||||
const [deleteTarget, setDeleteTarget] = useState(null);
|
||||
const [deleteIds, setDeleteIds] = useState(null);
|
||||
const tableRefsRef = useRef({ getFilters: () => [], getSort: () => [], resetSelection: () => {} });
|
||||
const navigate = useNavigate();
|
||||
const { user: currentUser } = useAuth();
|
||||
|
||||
const {
|
||||
groups,
|
||||
attributes,
|
||||
pagination,
|
||||
setPagination,
|
||||
loading,
|
||||
fetchGroupFieldValues,
|
||||
fetchArchivedGroups,
|
||||
restoreGroup,
|
||||
restoreGroups,
|
||||
permanentlyDeleteGroup,
|
||||
permanentlyDeleteGroups,
|
||||
} = useUserGroups();
|
||||
|
||||
const exportConfig = {
|
||||
allData: groups,
|
||||
attributes,
|
||||
filename: `${getTimestamp()}_ArchivedUserGroups`,
|
||||
sheetName: "ArchivedUserGroups",
|
||||
generatedBy: formatGeneratedBy(currentUser),
|
||||
};
|
||||
|
||||
const rowActions = buildRowActions({
|
||||
navigate,
|
||||
onRestore: (row) => setRestoreTarget(row),
|
||||
onDelete: (row) => setDeleteTarget(row),
|
||||
});
|
||||
|
||||
const toolbarActions = buildToolbarActions({
|
||||
fetchArchivedGroups, pagination, exportConfig, navigate,
|
||||
getFilters: () => tableRefsRef.current.getFilters(),
|
||||
getSort: () => tableRefsRef.current.getSort(),
|
||||
getTableInstance: () => tableRefsRef.current.tableInstance,
|
||||
});
|
||||
|
||||
const selectionActions = buildSelectionActions({
|
||||
exportConfig,
|
||||
restoreGroup: (row) => setRestoreTarget(row), // single
|
||||
restoreGroups: (ids) => setRestoreIds(ids), // bulk
|
||||
deleteGroup: (row) => setDeleteTarget(row),
|
||||
deleteGroups: (ids) => setDeleteIds(ids),
|
||||
getTableInstance: () => tableRefsRef.current.tableInstance,
|
||||
});
|
||||
|
||||
const columns = useMemo(() => buildDataColumns(attributes, rowActions), [attributes]);
|
||||
|
||||
const handleRestoreSuccess = () => {
|
||||
setRestoreTarget(null);
|
||||
setRestoreIds(null);
|
||||
tableRefsRef.current.resetSelection?.();
|
||||
fetchArchivedGroups({ page: 1, limit: pagination.limit });
|
||||
};
|
||||
|
||||
const handleDeleteSuccess = () => {
|
||||
setDeleteTarget(null);
|
||||
setDeleteIds(null);
|
||||
tableRefsRef.current.resetSelection?.();
|
||||
fetchArchivedGroups({ page: 1, limit: pagination.limit });
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<DataTable
|
||||
title="User Groups"
|
||||
data={groups}
|
||||
columns={columns}
|
||||
attributes={attributes}
|
||||
pagination={pagination}
|
||||
setPagination={setPagination}
|
||||
loading={loading}
|
||||
onFetch={fetchArchivedGroups}
|
||||
onFetchFilterData={fetchGroupFieldValues}
|
||||
onRefsReady={(refs) => tableRefsRef.current = refs}
|
||||
renderFilterSheet={({ open, onOpenChange, column, attr, data, loading }) => (
|
||||
<FilterSheet
|
||||
open={open}
|
||||
onOpenChange={onOpenChange}
|
||||
column={column}
|
||||
attr={attr}
|
||||
data={data}
|
||||
loading={loading}
|
||||
/>
|
||||
)}
|
||||
columnPinning={columnPinning}
|
||||
toolbarActions={toolbarActions}
|
||||
selectionActions={selectionActions}
|
||||
recordLabel="group"
|
||||
emptyMessage="No archived groups match the current filters."
|
||||
/>
|
||||
|
||||
{/* Single restore */}
|
||||
<RestoreDialog
|
||||
open={!!restoreTarget}
|
||||
onOpenChange={(v) => !v && setRestoreTarget(null)}
|
||||
entity={restoreTarget}
|
||||
entityLabel="Group"
|
||||
getName={(g) => g?.name}
|
||||
onRestore={(g) => restoreGroup(g?.group_id)}
|
||||
loading={loading}
|
||||
onSuccess={handleRestoreSuccess}
|
||||
/>
|
||||
|
||||
{/* Bulk restore */}
|
||||
<RestoreDialog
|
||||
open={!!restoreIds}
|
||||
onOpenChange={(v) => !v && setRestoreIds(null)}
|
||||
ids={restoreIds ?? []}
|
||||
entityLabel="Group"
|
||||
onRestore={restoreGroups}
|
||||
loading={loading}
|
||||
onSuccess={handleRestoreSuccess}
|
||||
/>
|
||||
|
||||
{/* Single permanent delete */}
|
||||
<PermanentDeleteDialog
|
||||
open={!!deleteTarget}
|
||||
onOpenChange={(v) => !v && setDeleteTarget(null)}
|
||||
entity={deleteTarget}
|
||||
entityLabel="Group"
|
||||
getName={(g) => g?.name}
|
||||
onDelete={(g) => permanentlyDeleteGroup(g?.group_id)}
|
||||
loading={loading}
|
||||
onSuccess={handleDeleteSuccess}
|
||||
/>
|
||||
|
||||
{/* Bulk permanent delete */}
|
||||
<PermanentDeleteDialog
|
||||
open={!!deleteIds}
|
||||
onOpenChange={(v) => !v && setDeleteIds(null)}
|
||||
ids={deleteIds ?? []}
|
||||
entityLabel="Group"
|
||||
onDelete={permanentlyDeleteGroups}
|
||||
loading={loading}
|
||||
onSuccess={handleDeleteSuccess}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
// modules/admin/components/user_groups/EditGroupDialog.jsx
|
||||
|
||||
import { useForm } from "react-hook-form";
|
||||
import { z } from "zod";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogFooter,
|
||||
DialogClose,
|
||||
} from "@/components/ui/dialog";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Label } from "@/components/ui/label";
|
||||
|
||||
const schema = z.object({
|
||||
name: z.string().min(1, "Name is required."),
|
||||
description: z.string().min(1, "Description is required."),
|
||||
group_code: z
|
||||
.string()
|
||||
.min(1, "Group code is required.")
|
||||
.max(50, "Group code must be 50 characters or less.")
|
||||
.regex(/^[A-Z0-9\-]+$/, "Only uppercase letters, numbers, and hyphens allowed."),
|
||||
});
|
||||
|
||||
/**
|
||||
* Dialog for editing a group's name, description, and group_code.
|
||||
* Matches context: updateGroup(gid, { name, description, group_code })
|
||||
*
|
||||
* `group` is the full row object from the table — pre-fills all fields.
|
||||
* `values` re-syncs whenever `group` prop changes.
|
||||
*
|
||||
* @param {Object} props
|
||||
* @param {boolean} props.open
|
||||
* @param {Function} props.onOpenChange
|
||||
* @param {Object} props.group Row object: { group_id, name, description, group_code, ... }
|
||||
* @param {Function} props.onSubmit Called with { name, description, group_code }
|
||||
* @param {boolean} [props.loading]
|
||||
*/
|
||||
export function EditGroupDialog({ open, onOpenChange, group, onSubmit, loading }) {
|
||||
const {
|
||||
register,
|
||||
handleSubmit,
|
||||
reset,
|
||||
setValue,
|
||||
formState: { errors },
|
||||
} = useForm({
|
||||
resolver: zodResolver(schema),
|
||||
values: {
|
||||
name: group?.name ?? "",
|
||||
description: group?.description ?? "",
|
||||
group_code: group?.group_code ?? "",
|
||||
},
|
||||
});
|
||||
|
||||
async function onValid(values) {
|
||||
await onSubmit(values);
|
||||
}
|
||||
|
||||
function handleClose() {
|
||||
reset();
|
||||
onOpenChange(false);
|
||||
}
|
||||
|
||||
// Auto-uppercase as user types
|
||||
function handleGroupCodeChange(e) {
|
||||
setValue("group_code", e.target.value.toUpperCase().replace(/[^A-Z0-9\-]/g, ""), {
|
||||
shouldValidate: true,
|
||||
});
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={handleClose}>
|
||||
<DialogContent className="sm:max-w-[440px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Edit group</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<form onSubmit={handleSubmit(onValid)} className="space-y-4">
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="edit-name">
|
||||
Name <span className="text-destructive">*</span>
|
||||
</Label>
|
||||
<Input
|
||||
id="edit-name"
|
||||
{...register("name")}
|
||||
/>
|
||||
{errors.name && (
|
||||
<p className="text-sm text-destructive">{errors.name.message}</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="edit-description">
|
||||
Description <span className="text-destructive">*</span>
|
||||
</Label>
|
||||
<Textarea
|
||||
id="edit-description"
|
||||
className="resize-none"
|
||||
rows={3}
|
||||
{...register("description")}
|
||||
/>
|
||||
{errors.description && (
|
||||
<p className="text-sm text-destructive">{errors.description.message}</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="edit-group_code">
|
||||
Group code <span className="text-destructive">*</span>
|
||||
</Label>
|
||||
<Input
|
||||
id="edit-group_code"
|
||||
placeholder="e.g. SALES-2025"
|
||||
{...register("group_code")}
|
||||
onChange={handleGroupCodeChange}
|
||||
/>
|
||||
{errors.group_code && (
|
||||
<p className="text-sm text-destructive">{errors.group_code.message}</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<DialogClose asChild>
|
||||
<Button type="button" variant="outline" disabled={loading}>Cancel</Button>
|
||||
</DialogClose>
|
||||
<Button type="submit" disabled={loading}>
|
||||
{loading ? "Saving..." : "Save changes"}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,210 @@
|
||||
// modules/admin/components/user_groups/GroupTable.jsx
|
||||
|
||||
import { useMemo, useRef, useState, useEffect } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
|
||||
import { useUserGroups } from "@/contexts/AdminUserGroupContext";
|
||||
import { useDashboard } from "@/contexts/AdminDashboardContext";
|
||||
import { useAuth } from "@/contexts/AuthContext";
|
||||
|
||||
import DataTable from "@/components/generic/Table/DataTable";
|
||||
import { FilterSheet } from "@/components/generic/Sheet/FilterSheet";
|
||||
import { ArchiveDialog } from "@/components/generic/Dialogs/ArchiveDialog";
|
||||
import { TableDashboard } from "@/components/generic/Dashboard/TableDashboard";
|
||||
import { AddGroupDialog } from "./AddGroupDialog";
|
||||
import { EditGroupDialog } from "./EditGroupDialog";
|
||||
|
||||
import { buildDataColumns, columnPinning } from "../../config/user_groups/columns.config";
|
||||
import { buildToolbarActions } from "../../config/user_groups/toolbar.config";
|
||||
import { buildSelectionActions } from "../../config/user_groups/selection.config";
|
||||
import { buildRowActions } from "../../config/user_groups/rowActions.config";
|
||||
|
||||
import { GROUP_STAT_MAP } from "@/data/adminDashboard.data";
|
||||
import { getTimestamp } from "@/utils/timestamp.util";
|
||||
import { formatGeneratedBy } from "@/utils/generatedBy.util";
|
||||
|
||||
export default function GroupTable() {
|
||||
const [createOpen, setCreateOpen] = useState(false);
|
||||
const [editTarget, setEditTarget] = useState(null);
|
||||
const [archiveTarget, setArchiveTarget] = useState(null);
|
||||
const [archiveIds, setArchiveIds] = useState(null);
|
||||
|
||||
const tableRefsRef = useRef({
|
||||
getFilters: () => [],
|
||||
getSort: () => [],
|
||||
resetSelection: () => { },
|
||||
setFilters: () => { },
|
||||
});
|
||||
|
||||
const navigate = useNavigate();
|
||||
|
||||
const { user: currentUser } = useAuth();
|
||||
|
||||
const {
|
||||
groups, attributes, pagination, setPagination, loading,
|
||||
fetchGroups, fetchGroupFieldValues,
|
||||
createGroup, updateGroup, deactivateGroup, deactivateGroups,
|
||||
} = useUserGroups();
|
||||
|
||||
const { groupsDashboard, fetchGroupsDashboard } = useDashboard();
|
||||
|
||||
useEffect(() => {
|
||||
fetchGroupsDashboard();
|
||||
}, []);
|
||||
|
||||
// ─── Keep activeFilters in sync for highlight ─────────────────────────────
|
||||
const handleRefsReady = (refs) => {
|
||||
tableRefsRef.current = refs; // ← no override needed
|
||||
};
|
||||
|
||||
const exportConfig = {
|
||||
allData: groups,
|
||||
attributes,
|
||||
filename: `${getTimestamp()}_UserGroups`,
|
||||
sheetName: "UserGroups",
|
||||
generatedBy: formatGeneratedBy(currentUser),
|
||||
};
|
||||
|
||||
const rowActions = buildRowActions({
|
||||
navigate,
|
||||
onEdit: (row) => setEditTarget(row),
|
||||
onArchive: (row) => setArchiveTarget(row),
|
||||
});
|
||||
|
||||
const toolbarActions = buildToolbarActions({
|
||||
fetchGroups, pagination, exportConfig, navigate,
|
||||
onAddGroup: () => setCreateOpen(true),
|
||||
getFilters: () => tableRefsRef.current.getFilters(),
|
||||
getSort: () => tableRefsRef.current.getSort(),
|
||||
getTableInstance: () => tableRefsRef.current.tableInstance,
|
||||
});
|
||||
|
||||
const selectionActions = buildSelectionActions({
|
||||
exportConfig,
|
||||
archiveGroup: (row) => setArchiveTarget(row),
|
||||
archiveGroups: (ids) => setArchiveIds(ids),
|
||||
getTableInstance: () => tableRefsRef.current.tableInstance,
|
||||
});
|
||||
|
||||
const columns = useMemo(
|
||||
() => buildDataColumns(attributes, rowActions),
|
||||
[attributes],
|
||||
);
|
||||
|
||||
const handleArchiveSuccess = () => {
|
||||
setArchiveTarget(null);
|
||||
setArchiveIds(null);
|
||||
tableRefsRef.current.resetSelection?.();
|
||||
fetchGroups({ page: 1, limit: pagination.limit });
|
||||
fetchGroupsDashboard();
|
||||
};
|
||||
|
||||
// ─── Attach filterId/filterValue (or onClick) to each stat ────────────────
|
||||
// "inactive" groups are effectively archived groups (deactivateGroup sets
|
||||
// is_active=false and soft-deletes in the same action), so route straight
|
||||
// to the archived groups page instead of toggling an in-table filter.
|
||||
const dashboardStats = (groupsDashboard?.stats ?? []).map((s) => ({
|
||||
...s,
|
||||
filterId: s.key === "active" ? "is_active" : null,
|
||||
filterValue: s.key === "active" ? ["true"] : null,
|
||||
onClick: s.key === "inactive" ? () => navigate("/admin/groups/archived") : undefined,
|
||||
}));
|
||||
|
||||
// ─── top_groups bar has no filterable column in this table ────────────────
|
||||
const dashboardBreakdowns = (groupsDashboard?.breakdowns ?? []).map((b) => ({
|
||||
...b,
|
||||
filterId: null,
|
||||
}));
|
||||
|
||||
return (
|
||||
<>
|
||||
{/* ── Dashboard strip ── */}
|
||||
{groupsDashboard && ( // ← was dashboard?.groups
|
||||
<TableDashboard
|
||||
stats={dashboardStats}
|
||||
breakdowns={dashboardBreakdowns}
|
||||
statMap={GROUP_STAT_MAP}
|
||||
tableRefsRef={tableRefsRef}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* ── Data table ── */}
|
||||
<DataTable
|
||||
title="User Groups"
|
||||
data={groups}
|
||||
columns={columns}
|
||||
attributes={attributes}
|
||||
pagination={pagination}
|
||||
setPagination={setPagination}
|
||||
loading={loading}
|
||||
onFetch={fetchGroups}
|
||||
onFetchFilterData={fetchGroupFieldValues}
|
||||
onRefsReady={handleRefsReady}
|
||||
renderFilterSheet={({ open, onOpenChange, column, attr, data, loading }) => (
|
||||
<FilterSheet
|
||||
open={open}
|
||||
onOpenChange={onOpenChange}
|
||||
column={column}
|
||||
attr={attr}
|
||||
data={data}
|
||||
loading={loading}
|
||||
/>
|
||||
)}
|
||||
columnPinning={columnPinning}
|
||||
toolbarActions={toolbarActions}
|
||||
selectionActions={selectionActions}
|
||||
recordLabel="group"
|
||||
emptyMessage="No user groups match the current filters."
|
||||
/>
|
||||
|
||||
{/* Add group */}
|
||||
<AddGroupDialog
|
||||
open={createOpen}
|
||||
onOpenChange={setCreateOpen}
|
||||
loading={loading}
|
||||
onSubmit={async (values) => {
|
||||
await createGroup(values);
|
||||
setCreateOpen(false);
|
||||
fetchGroups({ page: 1, limit: pagination.limit });
|
||||
fetchGroupsDashboard();
|
||||
}}
|
||||
/>
|
||||
|
||||
{/* Edit group */}
|
||||
<EditGroupDialog
|
||||
open={!!editTarget}
|
||||
onOpenChange={(v) => !v && setEditTarget(null)}
|
||||
group={editTarget}
|
||||
loading={loading}
|
||||
onSubmit={async (values) => {
|
||||
await updateGroup(editTarget?.group_id, values);
|
||||
setEditTarget(null);
|
||||
fetchGroups({ page: 1, limit: pagination.limit });
|
||||
}}
|
||||
/>
|
||||
|
||||
{/* Single archive */}
|
||||
<ArchiveDialog
|
||||
open={!!archiveTarget}
|
||||
onOpenChange={(v) => !v && setArchiveTarget(null)}
|
||||
entity={archiveTarget}
|
||||
entityLabel="Group"
|
||||
getName={(g) => g?.name}
|
||||
onArchive={(g) => deactivateGroup(g?.group_id)}
|
||||
loading={loading}
|
||||
onSuccess={handleArchiveSuccess}
|
||||
/>
|
||||
|
||||
{/* Bulk archive */}
|
||||
<ArchiveDialog
|
||||
open={!!archiveIds}
|
||||
onOpenChange={(v) => !v && setArchiveIds(null)}
|
||||
ids={archiveIds ?? []}
|
||||
entityLabel="Group"
|
||||
onArchive={deactivateGroups}
|
||||
loading={loading}
|
||||
onSuccess={handleArchiveSuccess}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
import { useMemo, useRef, useState } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
|
||||
import { useUsers } from "@/contexts/AdminUserContext";
|
||||
import { useAuth } from "@/contexts/AuthContext";
|
||||
import DataTable from "@/components/generic/Table/DataTable";
|
||||
import { FilterSheet } from "@/components/generic/Sheet/FilterSheet";
|
||||
import { RestoreDialog } from "@/components/generic/Dialogs/RestoreDialog";
|
||||
import { PermanentDeleteDialog } from "@/components/generic/Dialogs/PermanentDeleteDialog";
|
||||
|
||||
import { buildUserColumns, columnPinning } from "../../config/users/archive/columns.config";
|
||||
import { buildToolbarActions } from "../../config/users/archive/toolbar.config";
|
||||
import { buildSelectionActions } from "../../config/users/archive/selection.config";
|
||||
import { buildRowActions } from "../../config/users/archive/rowActions.config";
|
||||
|
||||
import { getTimestamp } from "@/utils/timestamp.util";
|
||||
import { formatGeneratedBy } from "@/utils/generatedBy.util";
|
||||
|
||||
export default function ArchiveGroupTable() {
|
||||
const [restoreTarget, setRestoreTarget] = useState(null); // single: row object
|
||||
const [restoreIds, setRestoreIds] = useState(null); // bulk: array of ids
|
||||
const [deleteTarget, setDeleteTarget] = useState(null);
|
||||
const [deleteIds, setDeleteIds] = useState(null);
|
||||
const tableRefsRef = useRef({ getFilters: () => [], getSort: () => [], resetSelection: () => { } });
|
||||
const navigate = useNavigate();
|
||||
const { user: currentUser } = useAuth();
|
||||
|
||||
const {
|
||||
users,
|
||||
attributes,
|
||||
pagination,
|
||||
setPagination,
|
||||
loading,
|
||||
fetchArchivedUsers,
|
||||
fetchUserFieldValues,
|
||||
restoreUser,
|
||||
restoreUsers,
|
||||
permanentlyDeleteUser,
|
||||
permanentlyDeleteUsers
|
||||
} = useUsers();
|
||||
|
||||
// Shared export config — passed into toolbar + selection configs
|
||||
const exportConfig = {
|
||||
allData: users,
|
||||
attributes,
|
||||
filename: `${getTimestamp()}_ArchivedUserGroups`,
|
||||
sheetName: "ArchivedUserGroups",
|
||||
generatedBy: formatGeneratedBy(currentUser),
|
||||
};
|
||||
|
||||
const rowActions = buildRowActions({
|
||||
navigate,
|
||||
onRestore: (row) => setRestoreTarget(row),
|
||||
onDelete: (row) => setDeleteTarget(row),
|
||||
});
|
||||
const toolbarActions = buildToolbarActions({
|
||||
fetchArchivedUsers, pagination, exportConfig, navigate,
|
||||
getFilters: () => tableRefsRef.current.getFilters(),
|
||||
getSort: () => tableRefsRef.current.getSort(),
|
||||
getTableInstance: () => tableRefsRef.current.tableInstance,
|
||||
});
|
||||
const selectionActions = buildSelectionActions({
|
||||
exportConfig,
|
||||
restoreUser: (row) => setRestoreTarget(row),
|
||||
restoreUsers: (ids) => setRestoreIds(ids),
|
||||
onDeleteUser: (row) => setDeleteTarget(row),
|
||||
onDeleteUsers: (ids) => setDeleteIds(ids),
|
||||
getTableInstance: () => tableRefsRef.current.tableInstance,
|
||||
});
|
||||
|
||||
const columns = useMemo(() => buildUserColumns(attributes, rowActions), [attributes]);
|
||||
|
||||
const handleRestoreSuccess = () => {
|
||||
setRestoreTarget(null);
|
||||
setRestoreIds(null);
|
||||
tableRefsRef.current.resetSelection?.(); // ← clear selection
|
||||
fetchArchivedUsers({ page: 1, limit: pagination.limit });
|
||||
};
|
||||
|
||||
const handleDeleteSuccess = () => {
|
||||
setDeleteTarget(null);
|
||||
setDeleteIds(null);
|
||||
tableRefsRef.current.resetSelection?.();
|
||||
fetchArchivedUsers({ page: 1, limit: pagination.limit });
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<DataTable
|
||||
title="Archived Users"
|
||||
data={users}
|
||||
columns={columns}
|
||||
attributes={attributes}
|
||||
pagination={pagination}
|
||||
setPagination={setPagination}
|
||||
loading={loading}
|
||||
onFetch={fetchArchivedUsers}
|
||||
onFetchFilterData={fetchUserFieldValues}
|
||||
onRefsReady={(refs) => tableRefsRef.current = refs}
|
||||
renderFilterSheet={({ open, onOpenChange, column, attr, data, loading }) => (
|
||||
<FilterSheet
|
||||
open={open}
|
||||
onOpenChange={onOpenChange}
|
||||
column={column}
|
||||
attr={attr}
|
||||
data={data}
|
||||
loading={loading}
|
||||
/>
|
||||
)}
|
||||
columnPinning={columnPinning}
|
||||
toolbarActions={toolbarActions}
|
||||
selectionActions={selectionActions}
|
||||
recordLabel="user"
|
||||
emptyMessage="No users match the current filters."
|
||||
/>
|
||||
|
||||
{/* Single restore */}
|
||||
<RestoreDialog
|
||||
open={!!restoreTarget}
|
||||
onOpenChange={(v) => !v && setRestoreTarget(null)}
|
||||
entity={restoreTarget}
|
||||
entityLabel="User"
|
||||
getName={(u) => u?.personal_info?.name?.full_name ?? u?.email}
|
||||
onRestore={(u) => restoreUser(u?.user_id)}
|
||||
loading={loading}
|
||||
onSuccess={handleRestoreSuccess}
|
||||
/>
|
||||
|
||||
{/* Bulk restore */}
|
||||
<RestoreDialog
|
||||
open={!!restoreIds}
|
||||
onOpenChange={(v) => !v && setRestoreIds(null)}
|
||||
ids={restoreIds ?? []}
|
||||
entityLabel="User"
|
||||
onRestore={restoreUsers}
|
||||
loading={loading}
|
||||
onSuccess={handleRestoreSuccess}
|
||||
/>
|
||||
|
||||
{/* Single permanent delete */}
|
||||
<PermanentDeleteDialog
|
||||
open={!!deleteTarget}
|
||||
onOpenChange={(v) => !v && setDeleteTarget(null)}
|
||||
entity={deleteTarget}
|
||||
entityLabel="User"
|
||||
getName={(u) => u?.personal_info?.name?.full_name ?? u?.email}
|
||||
onDelete={(u) => permanentlyDeleteUser(u?.user_id)}
|
||||
loading={loading}
|
||||
onSuccess={handleDeleteSuccess}
|
||||
/>
|
||||
|
||||
{/* Bulk permanent delete */}
|
||||
<PermanentDeleteDialog
|
||||
open={!!deleteIds}
|
||||
onOpenChange={(v) => !v && setDeleteIds(null)}
|
||||
ids={deleteIds ?? []}
|
||||
entityLabel="User"
|
||||
onDelete={permanentlyDeleteUsers}
|
||||
loading={loading}
|
||||
onSuccess={handleDeleteSuccess}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,281 @@
|
||||
// modules/admin/components/users/UsersTable.jsx
|
||||
|
||||
import { useMemo, useRef, useState, useEffect } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
|
||||
import { useUsers } from "@/contexts/AdminUserContext";
|
||||
import { useDashboard } from "@/contexts/AdminDashboardContext";
|
||||
import { useAuth } from "@/contexts/AuthContext";
|
||||
|
||||
import DataTable from "@/components/generic/Table/DataTable";
|
||||
import { FilterSheet } from "@/components/generic/Sheet/FilterSheet";
|
||||
import { ArchiveDialog } from "@/components/generic/Dialogs/ArchiveDialog";
|
||||
import { BanUserDialog } from "@/components/generic/Dialogs/BanUserDialog";
|
||||
import { UnbanDialog } from "@/components/generic/Dialogs/UnbanDialog";
|
||||
import { MakeAdminDialog } from "@/components/generic/Dialogs/MakeAdminDialog";
|
||||
import { DemoteAdminDialog } from "@/components/generic/Dialogs/DemoteAdminDialog";
|
||||
import { TableDashboard } from "@/components/generic/Dashboard/TableDashboard";
|
||||
|
||||
import { buildDataColumns, columnPinning } from "../../config/users/columns.config";
|
||||
import { buildToolbarActions } from "../../config/users/toolbar.config";
|
||||
import { buildSelectionActions } from "../../config/users/selection.config";
|
||||
import { buildRowActions } from "../../config/users/rowActions.config";
|
||||
|
||||
import { USER_STAT_MAP } from "@/data/adminDashboard.data";
|
||||
import { getTimestamp } from "@/utils/timestamp.util";
|
||||
import { formatGeneratedBy } from "@/utils/generatedBy.util";
|
||||
|
||||
export default function UsersTable() {
|
||||
const [archiveTarget, setArchiveTarget] = useState(null);
|
||||
const [archiveIds, setArchiveIds] = useState(null);
|
||||
const [banTarget, setBanTarget] = useState(null);
|
||||
const [banIds, setBanIds] = useState(null);
|
||||
const [unbanTarget, setUnbanTarget] = useState(null);
|
||||
const [unbanIds, setUnbanIds] = useState(null);
|
||||
const [makeAdminTarget, setMakeAdminTarget] = useState(null);
|
||||
const [demoteAdminTarget, setDemoteAdminTarget] = useState(null);
|
||||
|
||||
const tableRefsRef = useRef({
|
||||
getFilters: () => [],
|
||||
getSort: () => [],
|
||||
resetSelection: () => { },
|
||||
setFilters: () => { },
|
||||
});
|
||||
|
||||
const navigate = useNavigate();
|
||||
|
||||
const { user: currentUser } = useAuth();
|
||||
|
||||
const {
|
||||
users, attributes, pagination, setPagination, loading,
|
||||
fetchUsers, fetchUserFieldValues, deactivateUser, deactivateUsers,
|
||||
banUser, unbanUser, bulkBanUsers, bulkUnbanUsers, makeAdmin, demoteAdmin,
|
||||
} = useUsers();
|
||||
|
||||
const { usersDashboard, fetchUsersDashboard } = useDashboard();
|
||||
|
||||
useEffect(() => {
|
||||
fetchUsersDashboard();
|
||||
}, []);
|
||||
|
||||
// ─── Keep activeFilters in sync so TableDashboard can highlight active ────
|
||||
const handleRefsReady = (refs) => {
|
||||
tableRefsRef.current = refs; // ← just store directly, no override needed
|
||||
};
|
||||
|
||||
const exportConfig = {
|
||||
allData: users,
|
||||
attributes,
|
||||
filename: `${getTimestamp()}_Users`,
|
||||
sheetName: "Users",
|
||||
title: "Users",
|
||||
generatedBy: formatGeneratedBy(currentUser),
|
||||
};
|
||||
|
||||
const rowActions = buildRowActions({
|
||||
navigate,
|
||||
onArchive: (row) => setArchiveTarget(row),
|
||||
onBan: (row) => setBanTarget(row),
|
||||
onUnban: (row) => setUnbanTarget(row),
|
||||
onMakeAdmin: (row) => setMakeAdminTarget(row),
|
||||
onDemoteAdmin: (row) => setDemoteAdminTarget(row),
|
||||
currentUserId: currentUser?.user_id,
|
||||
});
|
||||
const toolbarActions = buildToolbarActions({
|
||||
fetchUsers, pagination, exportConfig, navigate,
|
||||
getFilters: () => tableRefsRef.current.getFilters(),
|
||||
getSort: () => tableRefsRef.current.getSort(),
|
||||
getTableInstance: () => tableRefsRef.current.tableInstance,
|
||||
});
|
||||
const selectionActions = buildSelectionActions({
|
||||
exportConfig,
|
||||
archiveUser: (row) => setArchiveTarget(row),
|
||||
archiveUsers: (ids) => setArchiveIds(ids),
|
||||
banUsers: (ids) => setBanIds(ids),
|
||||
unbanUsers: (ids) => setUnbanIds(ids),
|
||||
getTableInstance: () => tableRefsRef.current.tableInstance,
|
||||
});
|
||||
|
||||
const columns = useMemo(() => buildDataColumns(attributes, rowActions), [attributes]);
|
||||
|
||||
const handleArchiveSuccess = () => {
|
||||
setArchiveTarget(null);
|
||||
setArchiveIds(null);
|
||||
tableRefsRef.current.resetSelection?.();
|
||||
fetchUsers({ page: 1, limit: pagination.limit });
|
||||
fetchUsersDashboard();
|
||||
};
|
||||
|
||||
const handleBanSuccess = () => {
|
||||
setBanTarget(null);
|
||||
setBanIds(null);
|
||||
tableRefsRef.current.resetSelection?.();
|
||||
fetchUsers({ page: 1, limit: pagination.limit });
|
||||
};
|
||||
|
||||
const handleUnbanSuccess = () => {
|
||||
setUnbanTarget(null);
|
||||
setUnbanIds(null);
|
||||
tableRefsRef.current.resetSelection?.();
|
||||
fetchUsers({ page: 1, limit: pagination.limit });
|
||||
};
|
||||
|
||||
const handleMakeAdminSuccess = () => {
|
||||
setMakeAdminTarget(null);
|
||||
fetchUsers({ page: 1, limit: pagination.limit });
|
||||
};
|
||||
|
||||
const handleDemoteAdminSuccess = () => {
|
||||
setDemoteAdminTarget(null);
|
||||
fetchUsers({ page: 1, limit: pagination.limit });
|
||||
};
|
||||
|
||||
// ─── Attach filterId/filterValue (or onClick) to each stat ────────────────
|
||||
const statsWithFilter = (usersDashboard?.stats ?? []).map((s) => ({
|
||||
...s,
|
||||
filterId: s.key === "active" ? "is_active" : null,
|
||||
filterValue: s.key === "active" ? ["true"] : null,
|
||||
onClick: s.key === "inactive" ? () => navigate("/admin/users/archived") : undefined,
|
||||
}));
|
||||
|
||||
// ─── Attach filterId to each breakdown so clicking a slice filters ────────
|
||||
const dashboardBreakdowns = (usersDashboard?.breakdowns ?? []).map((b) => ({
|
||||
...b,
|
||||
filterId: b.key === "acc_type" ? "acc_type"
|
||||
: b.key === "reg_type" ? "reg_type"
|
||||
: null,
|
||||
}));
|
||||
|
||||
return (
|
||||
<>
|
||||
{/* ── Dashboard strip ── */}
|
||||
{usersDashboard && (
|
||||
<TableDashboard
|
||||
stats={statsWithFilter}
|
||||
breakdowns={dashboardBreakdowns}
|
||||
statMap={USER_STAT_MAP}
|
||||
tableRefsRef={tableRefsRef}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* ── Data table ── */}
|
||||
<DataTable
|
||||
title="Users"
|
||||
data={users}
|
||||
columns={columns}
|
||||
attributes={attributes}
|
||||
pagination={pagination}
|
||||
setPagination={setPagination}
|
||||
loading={loading}
|
||||
onFetch={fetchUsers}
|
||||
onFetchFilterData={fetchUserFieldValues}
|
||||
onRefsReady={handleRefsReady}
|
||||
renderFilterSheet={({ open, onOpenChange, column, attr, data, loading }) => (
|
||||
<FilterSheet
|
||||
open={open}
|
||||
onOpenChange={onOpenChange}
|
||||
column={column}
|
||||
attr={attr}
|
||||
data={data}
|
||||
loading={loading}
|
||||
/>
|
||||
)}
|
||||
columnPinning={columnPinning}
|
||||
toolbarActions={toolbarActions}
|
||||
selectionActions={selectionActions}
|
||||
recordLabel="user"
|
||||
emptyMessage="No users match the current filters."
|
||||
enableRowSelection={(row) => row.original.user_id !== currentUser?.user_id}
|
||||
/>
|
||||
|
||||
{/* Single archive */}
|
||||
<ArchiveDialog
|
||||
open={!!archiveTarget}
|
||||
onOpenChange={(v) => !v && setArchiveTarget(null)}
|
||||
entity={archiveTarget}
|
||||
entityLabel="User"
|
||||
getName={(u) => u?.personal_info?.name?.full_name ?? u?.email}
|
||||
onArchive={(u) => deactivateUser(u?.user_id)}
|
||||
loading={loading}
|
||||
onSuccess={handleArchiveSuccess}
|
||||
/>
|
||||
|
||||
{/* Bulk archive */}
|
||||
<ArchiveDialog
|
||||
open={!!archiveIds}
|
||||
onOpenChange={(v) => !v && setArchiveIds(null)}
|
||||
ids={archiveIds ?? []}
|
||||
entityLabel="User"
|
||||
onArchive={deactivateUsers}
|
||||
loading={loading}
|
||||
onSuccess={handleArchiveSuccess}
|
||||
/>
|
||||
|
||||
{/* Single ban */}
|
||||
<BanUserDialog
|
||||
open={!!banTarget}
|
||||
onOpenChange={(v) => !v && setBanTarget(null)}
|
||||
entity={banTarget}
|
||||
entityLabel="User"
|
||||
getName={(u) => u?.personal_info?.name?.full_name ?? u?.email}
|
||||
onBan={(payload) => banUser(banTarget?.user_id, payload)}
|
||||
loading={loading}
|
||||
onSuccess={handleBanSuccess}
|
||||
/>
|
||||
|
||||
{/* Bulk ban */}
|
||||
<BanUserDialog
|
||||
open={!!banIds}
|
||||
onOpenChange={(v) => !v && setBanIds(null)}
|
||||
ids={banIds ?? []}
|
||||
entityLabel="User"
|
||||
onBan={(payload) => bulkBanUsers({ ids: banIds, ...payload })}
|
||||
loading={loading}
|
||||
onSuccess={handleBanSuccess}
|
||||
/>
|
||||
|
||||
{/* Single unban */}
|
||||
<UnbanDialog
|
||||
open={!!unbanTarget}
|
||||
onOpenChange={(v) => !v && setUnbanTarget(null)}
|
||||
entity={unbanTarget}
|
||||
entityLabel="User"
|
||||
getName={(u) => u?.personal_info?.name?.full_name ?? u?.email}
|
||||
onUnban={(payload) => unbanUser(unbanTarget?.user_id, payload)}
|
||||
loading={loading}
|
||||
onSuccess={handleUnbanSuccess}
|
||||
/>
|
||||
|
||||
{/* Bulk unban */}
|
||||
<UnbanDialog
|
||||
open={!!unbanIds}
|
||||
onOpenChange={(v) => !v && setUnbanIds(null)}
|
||||
ids={unbanIds ?? []}
|
||||
entityLabel="User"
|
||||
onUnban={(payload) => bulkUnbanUsers({ ids: unbanIds, ...payload })}
|
||||
loading={loading}
|
||||
onSuccess={handleUnbanSuccess}
|
||||
/>
|
||||
|
||||
{/* Make admin */}
|
||||
<MakeAdminDialog
|
||||
open={!!makeAdminTarget}
|
||||
onOpenChange={(v) => !v && setMakeAdminTarget(null)}
|
||||
entity={makeAdminTarget}
|
||||
onMakeAdmin={(u) => makeAdmin(u?.user_id)}
|
||||
loading={loading}
|
||||
onSuccess={handleMakeAdminSuccess}
|
||||
/>
|
||||
|
||||
{/* Demote admin */}
|
||||
<DemoteAdminDialog
|
||||
open={!!demoteAdminTarget}
|
||||
onOpenChange={(v) => !v && setDemoteAdminTarget(null)}
|
||||
entity={demoteAdminTarget}
|
||||
onDemoteAdmin={(u) => demoteAdmin(u?.user_id)}
|
||||
loading={loading}
|
||||
onSuccess={handleDemoteAdminSuccess}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
// config/advertisements/archive/columns.config.jsx
|
||||
|
||||
import { buildColumns } from "@/utils/table.util";
|
||||
import { buildSelectionColumn } from "@/components/generic/Table/buildSelectionColumn";
|
||||
import { buildRowActionsColumn } from "@/components/generic/Table/buildRowActionsColumn";
|
||||
|
||||
export const columnPinning = {
|
||||
right: ["actions"],
|
||||
left: [],
|
||||
};
|
||||
|
||||
const DATE_TIME_FIELDS = ["start_date", "end_date", "createdAt", "updatedAt", "deletedAt"];
|
||||
|
||||
/**
|
||||
* Builds the full column array for the Archived Advertisements table.
|
||||
*
|
||||
* @param {Array} attributes Field definitions from the server (drives data columns)
|
||||
* @param {Array} rowActions Row-level kebab action definitions
|
||||
* @param {Function} [fmtDateTime] - date+time formatter (from useDateFormat), falls back to a plain locale string
|
||||
* @returns {Array} TanStack column definitions
|
||||
*/
|
||||
export function buildDataColumns(attributes, rowActions, fmtDateTime = (v) => v ? new Date(v).toLocaleString() : "—") {
|
||||
const visibleAttributes = attributes.filter((a) => !a.hidden);
|
||||
|
||||
// Ad scheduling is time-sensitive — the default date-only cell renderer
|
||||
// drops the time-of-day, so these fields get an explicit date+time cell.
|
||||
const cellOverrides = Object.fromEntries(
|
||||
DATE_TIME_FIELDS.map((field) => [
|
||||
field,
|
||||
(info) => <span className="text-xs text-muted-foreground">{fmtDateTime(info.getValue())}</span>,
|
||||
])
|
||||
);
|
||||
|
||||
return [
|
||||
buildSelectionColumn(),
|
||||
...buildColumns(visibleAttributes, { cellOverrides }),
|
||||
buildRowActionsColumn(rowActions, { dropdownLabel: "Ad Actions" }),
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
// config/advertisements/archive/rowActions.config.jsx
|
||||
import { RotateCcw, Trash2 } from "lucide-react";
|
||||
|
||||
/**
|
||||
* @param {Object} deps
|
||||
* @param {Function} deps.onRestore (row) => void — open restore dialog
|
||||
* @param {Function} deps.onDelete (row) => void — open permanent-delete dialog
|
||||
*/
|
||||
export function buildRowActions({ onRestore, onDelete }) {
|
||||
return [
|
||||
{
|
||||
key: "restore",
|
||||
label: "Restore",
|
||||
className: "text-emerald-600 focus:text-emerald-600",
|
||||
icon: <RotateCcw className="h-3.5 w-3.5" />,
|
||||
onClick: (row) => onRestore(row),
|
||||
},
|
||||
{
|
||||
key: "delete",
|
||||
label: "Delete",
|
||||
className: "text-destructive focus:text-destructive",
|
||||
icon: <Trash2 className="h-3.5 w-3.5" />,
|
||||
onClick: (row) => onDelete(row),
|
||||
},
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
// config/advertisements/archive/selection.config.jsx
|
||||
import { Download, ArchiveRestore, Trash2 } from "lucide-react";
|
||||
import { exportTableToExcel } from "@/utils/excel.util";
|
||||
|
||||
export function buildSelectionActions({ exportConfig, onSingleRestore, onBulkRestore, onSingleDelete, onBulkDelete, getTableInstance }) {
|
||||
return [
|
||||
{
|
||||
key: "export-selected",
|
||||
label: "Export",
|
||||
icon: <Download className="h-3.5 w-3.5" />,
|
||||
onClick: (rows, table) =>
|
||||
exportTableToExcel({
|
||||
...exportConfig,
|
||||
selectedRows: rows,
|
||||
tableInstance: table ?? getTableInstance(),
|
||||
}),
|
||||
},
|
||||
{
|
||||
key: "restore-selected",
|
||||
label: "Restore",
|
||||
icon: <ArchiveRestore className="h-3.5 w-3.5" />,
|
||||
className: "text-emerald-600 border-emerald-600/40 hover:bg-emerald-600/10 hover:text-emerald-700",
|
||||
onClick: (rows) => {
|
||||
const ids = rows.map((r) => r.advertisement_id);
|
||||
ids.length === 1
|
||||
? onSingleRestore(rows[0])
|
||||
: onBulkRestore(ids);
|
||||
},
|
||||
},
|
||||
{
|
||||
key: "delete-selected",
|
||||
label: "Delete",
|
||||
icon: <Trash2 className="h-3.5 w-3.5" />,
|
||||
className: "text-destructive border-destructive/40 hover:bg-destructive/10 hover:text-destructive",
|
||||
onClick: (rows) => {
|
||||
const ids = rows.map((r) => r.advertisement_id);
|
||||
ids.length === 1
|
||||
? onSingleDelete(rows[0])
|
||||
: onBulkDelete(ids);
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
// config/advertisements/archive/toolbar.config.jsx
|
||||
import { RefreshCw, Download, Ban } from "lucide-react";
|
||||
import { exportTableToExcel } from "@/utils/excel.util";
|
||||
|
||||
/**
|
||||
* @param {Object} deps
|
||||
* @param {Function} deps.fetchAdvertisements
|
||||
* @param {Object} deps.pagination
|
||||
* @param {Object} deps.exportConfig
|
||||
* @param {Function} deps.navigate
|
||||
* @param {Function} deps.getFilters
|
||||
* @param {Function} deps.getSort
|
||||
* @param {Function} deps.getTableInstance
|
||||
* @param {Function} [deps.onRemoveExpired] - triggers the "Remove Expired" bulk-purge flow
|
||||
*/
|
||||
export function buildToolbarActions({ fetchAdvertisements, pagination, exportConfig, navigate, getFilters, getSort, getTableInstance, onRemoveExpired }) {
|
||||
return [
|
||||
{
|
||||
key: "refresh",
|
||||
type: "button",
|
||||
icon: <RefreshCw className="h-3.5 w-3.5" />,
|
||||
label: "Refresh",
|
||||
onClick: () =>
|
||||
fetchAdvertisements({
|
||||
page: 1,
|
||||
limit: pagination.limit,
|
||||
filters: getFilters(),
|
||||
sort: getSort(),
|
||||
}),
|
||||
},
|
||||
{
|
||||
key: "export",
|
||||
type: "button",
|
||||
icon: <Download className="h-3.5 w-3.5" />,
|
||||
label: "Export",
|
||||
onClick: (table) =>
|
||||
exportTableToExcel({
|
||||
...exportConfig,
|
||||
tableInstance: table ?? getTableInstance(),
|
||||
}),
|
||||
},
|
||||
...(onRemoveExpired ? [{
|
||||
key: "remove-expired",
|
||||
type: "button",
|
||||
icon: <Ban className="h-3.5 w-3.5" />,
|
||||
label: "Remove Expired",
|
||||
className: "text-destructive border-destructive/40 hover:bg-destructive/10 hover:text-destructive",
|
||||
onClick: onRemoveExpired,
|
||||
}] : []),
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
// config/columns.config.jsx
|
||||
// Column definitions and pinning config for the Users table.
|
||||
|
||||
import { buildColumns } from "@/utils/table.util";
|
||||
import { buildSelectionColumn } from "@/components/generic/Table/buildSelectionColumn";
|
||||
import { buildRowActionsColumn } from "@/components/generic/Table/buildRowActionsColumn";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Users } from "lucide-react";
|
||||
import { formatFileSize } from "@/utils/format.util";
|
||||
|
||||
export const columnPinning = {
|
||||
right: ["actions"],
|
||||
left: [],
|
||||
};
|
||||
|
||||
// ─── Custom cell overrides ────────────────────────────────────────────────────
|
||||
const cellOverrides = {
|
||||
// memberCount: (info) => {
|
||||
// const count = parseInt(info.getValue() ?? 0, 10);
|
||||
// return (
|
||||
// <div className="flex items-center gap-1.5">
|
||||
// <Users className="h-3.5 w-3.5 text-muted-foreground" />
|
||||
// <Badge variant="secondary" className="text-xs font-medium tabular-nums">
|
||||
// {count} {count === 1 ? "member" : "members"}
|
||||
// </Badge>
|
||||
// </div>
|
||||
// );
|
||||
// },
|
||||
file_size: (info) => (
|
||||
<span className="font-mono text-xs font-semibold text-muted-foreground">
|
||||
{formatFileSize(info.getValue()) ?? "-"}
|
||||
</span>
|
||||
),
|
||||
};
|
||||
|
||||
/**
|
||||
* Builds the full column array for the Users table.
|
||||
*
|
||||
* @param {Array} attributes Field definitions from the server (drives data columns)
|
||||
* @param {Array} rowActions Row-level kebab action definitions
|
||||
* @returns {Array} TanStack column definitions
|
||||
*/
|
||||
export function buildDataColumns(attributes, rowActions) {
|
||||
const visibleAttributes = attributes.filter((a) => !a.hidden);
|
||||
|
||||
return [
|
||||
buildSelectionColumn(),
|
||||
...buildColumns(visibleAttributes, { cellOverrides }),
|
||||
buildRowActionsColumn(rowActions, { dropdownLabel: "File Actions" }),
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
// modules/admin/config/assets/rowActions.config.jsx
|
||||
import { RotateCcw, Trash2 } from "lucide-react";
|
||||
|
||||
/**
|
||||
* @param {Object} deps
|
||||
* @param {Function} deps.onView (row) → void — navigate to view page
|
||||
* @param {Function} deps.onEdit (row) → void — navigate to edit page
|
||||
* @param {Function} deps.onArchive (row) → void — open archive dialog
|
||||
*/
|
||||
export function buildRowActions({ onRestore, onDelete }) {
|
||||
return [
|
||||
{
|
||||
key: "restore",
|
||||
label: "Restore",
|
||||
className: "text-emerald-600 focus:text-emerald-600",
|
||||
icon: <RotateCcw className="h-3.5 w-3.5" />,
|
||||
onClick: (row) => onRestore(row),
|
||||
hidden: (row) => row.is_active,
|
||||
},
|
||||
{
|
||||
key: "delete",
|
||||
label: "Delete",
|
||||
className: "text-destructive focus:text-destructive",
|
||||
icon: <Trash2 className="h-3.5 w-3.5" />,
|
||||
onClick: (row) => onDelete(row),
|
||||
},
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
// config/assets/archive/selection.config.jsx
|
||||
import { Download, ArchiveRestore, Trash2 } from "lucide-react";
|
||||
import { exportTableToExcel } from "@/utils/excel.util";
|
||||
|
||||
export function buildSelectionActions({ exportConfig, onSingleRestore, onBulkRestore, onSingleDelete, onBulkDelete, getTableInstance }) {
|
||||
return [
|
||||
{
|
||||
key: "export-selected",
|
||||
label: "Export",
|
||||
icon: <Download className="h-3.5 w-3.5" />,
|
||||
onClick: (rows, table) =>
|
||||
exportTableToExcel({
|
||||
...exportConfig,
|
||||
selectedRows: rows,
|
||||
tableInstance: table ?? getTableInstance(),
|
||||
}),
|
||||
},
|
||||
{
|
||||
key: "restore-selected",
|
||||
label: "Restore",
|
||||
icon: <ArchiveRestore className="h-3.5 w-3.5" />,
|
||||
className: "text-emerald-600 border-emerald-600/40 hover:bg-emerald-600/10 hover:text-emerald-700",
|
||||
onClick: (rows) => {
|
||||
const ids = rows.map((r) => r.asset_id);
|
||||
ids.length === 1
|
||||
? onSingleRestore(rows[0])
|
||||
: onBulkRestore(ids);
|
||||
},
|
||||
},
|
||||
{
|
||||
key: "delete-selected",
|
||||
label: "Delete",
|
||||
icon: <Trash2 className="h-3.5 w-3.5" />,
|
||||
className: "text-destructive border-destructive/40 hover:bg-destructive/10 hover:text-destructive",
|
||||
onClick: (rows) => {
|
||||
const ids = rows.map((r) => r.asset_id);
|
||||
ids.length === 1
|
||||
? onSingleDelete(rows[0])
|
||||
: onBulkDelete(ids);
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
// ─── config/toolbar.config.jsx ────────────────────────────────────────────────
|
||||
import { RefreshCw, Download, Plus, Archive } from "lucide-react";
|
||||
import { exportTableToExcel } from "@/utils/excel.util";
|
||||
|
||||
/**
|
||||
* @param {Object} deps
|
||||
* @param {Function} deps.fetchAssets
|
||||
* @param {Object} deps.pagination
|
||||
* @param {Object} deps.exportConfig
|
||||
* @param {Function} deps.navigate
|
||||
* @param {Function} deps.getFilters
|
||||
* @param {Function} deps.getSort
|
||||
* @param {Function} deps.getTableInstance
|
||||
*/
|
||||
export function buildToolbarActions({ fetchAssets, pagination, exportConfig, navigate, getFilters, getSort, getTableInstance }) {
|
||||
return [
|
||||
{
|
||||
key: "refresh",
|
||||
type: "button",
|
||||
icon: <RefreshCw className="h-3.5 w-3.5" />,
|
||||
label: "Refresh",
|
||||
onClick: () =>
|
||||
fetchAssets({
|
||||
page: 1,
|
||||
limit: pagination.limit,
|
||||
filters: getFilters(),
|
||||
sort: getSort(),
|
||||
}),
|
||||
},
|
||||
{
|
||||
key: "export",
|
||||
type: "button",
|
||||
icon: <Download className="h-3.5 w-3.5" />,
|
||||
label: "Export",
|
||||
onClick: (table) =>
|
||||
exportTableToExcel({
|
||||
...exportConfig,
|
||||
tableInstance: table ?? getTableInstance(),
|
||||
}),
|
||||
},
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
// config/columns.config.jsx
|
||||
// Column definitions and pinning config for the Users table.
|
||||
|
||||
import { buildColumns } from "@/utils/table.util";
|
||||
import { buildSelectionColumn } from "@/components/generic/Table/buildSelectionColumn";
|
||||
import { buildRowActionsColumn } from "@/components/generic/Table/buildRowActionsColumn";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Users } from "lucide-react";
|
||||
import { formatFileSize } from "@/utils/format.util";
|
||||
|
||||
export const columnPinning = {
|
||||
right: ["actions"],
|
||||
left: [],
|
||||
};
|
||||
|
||||
// ─── Custom cell overrides ────────────────────────────────────────────────────
|
||||
const cellOverrides = {
|
||||
// memberCount: (info) => {
|
||||
// const count = parseInt(info.getValue() ?? 0, 10);
|
||||
// return (
|
||||
// <div className="flex items-center gap-1.5">
|
||||
// <Users className="h-3.5 w-3.5 text-muted-foreground" />
|
||||
// <Badge variant="secondary" className="text-xs font-medium tabular-nums">
|
||||
// {count} {count === 1 ? "member" : "members"}
|
||||
// </Badge>
|
||||
// </div>
|
||||
// );
|
||||
// },
|
||||
file_size: (info) => (
|
||||
<span className="font-mono text-xs font-semibold text-muted-foreground">
|
||||
{formatFileSize(info.getValue()) ?? "-"}
|
||||
</span>
|
||||
),
|
||||
};
|
||||
|
||||
/**
|
||||
* Builds the full column array for the Users table.
|
||||
*
|
||||
* @param {Array} attributes Field definitions from the server (drives data columns)
|
||||
* @param {Array} rowActions Row-level kebab action definitions
|
||||
* @returns {Array} TanStack column definitions
|
||||
*/
|
||||
export function buildDataColumns(attributes, rowActions) {
|
||||
const visibleAttributes = attributes.filter((a) => !a.hidden);
|
||||
|
||||
return [
|
||||
buildSelectionColumn(),
|
||||
...buildColumns(visibleAttributes, { cellOverrides }),
|
||||
buildRowActionsColumn(rowActions, { dropdownLabel: "File Actions" }),
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
// modules/admin/config/assets/rowActions.config.jsx
|
||||
|
||||
import { Eye, Archive } from "lucide-react";
|
||||
|
||||
/**
|
||||
* @param {Object} deps
|
||||
* @param {Function} deps.onView (row) → void — navigate to view page
|
||||
* @param {Function} deps.onArchive (row) → void — open archive dialog
|
||||
*/
|
||||
export function buildRowActions({ onView, onArchive }) {
|
||||
return [
|
||||
{
|
||||
key: "view",
|
||||
label: "View Info",
|
||||
icon: <Eye className="h-3.5 w-3.5" />,
|
||||
onClick: (row) => onView(row),
|
||||
},
|
||||
{
|
||||
key: "archive",
|
||||
label: "Archive",
|
||||
icon: <Archive className="h-3.5 w-3.5" />,
|
||||
className: "text-destructive",
|
||||
onClick: (row) => onArchive(row),
|
||||
separator: true
|
||||
},
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
// config/selection.config.jsx
|
||||
import { Download, Archive, Trash2 } from "lucide-react";
|
||||
import { exportTableToExcel } from "@/utils/excel.util";
|
||||
|
||||
/**
|
||||
* @param {Object} deps
|
||||
* @param {Object} deps.exportConfig
|
||||
* @param {Function} deps.onArchive (row) → void single archive dialog
|
||||
* @param {Function} deps.onArchiveMany (ids[]) → void bulk archive dialog
|
||||
* @param {Function} deps.getTableInstance
|
||||
*/
|
||||
export function buildSelectionActions({ exportConfig, onArchive, onArchiveMany, getTableInstance, }) {
|
||||
return [
|
||||
{
|
||||
key: "export-selected",
|
||||
label: "Export",
|
||||
icon: <Download className="h-3.5 w-3.5" />,
|
||||
onClick: (rows, table) =>
|
||||
exportTableToExcel({
|
||||
...exportConfig,
|
||||
selectedRows: rows,
|
||||
tableInstance: table ?? getTableInstance(),
|
||||
}),
|
||||
},
|
||||
{
|
||||
key: "archive-selected",
|
||||
label: "Archive",
|
||||
icon: <Archive className="h-3.5 w-3.5" />,
|
||||
className: "text-destructive border-destructive/40 hover:bg-destructive/10 hover:text-destructive",
|
||||
onClick: (rows) => {
|
||||
const ids = rows.map((r) => r.asset_id);
|
||||
ids.length === 1
|
||||
? onArchive(rows[0])
|
||||
: onArchiveMany(ids);
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
// ─── config/toolbar.config.jsx ────────────────────────────────────────────────
|
||||
import { RefreshCw, Download, Plus, Archive, UploadCloud } from "lucide-react";
|
||||
import { exportTableToExcel } from "@/utils/excel.util";
|
||||
|
||||
/**
|
||||
* @param {Object} deps
|
||||
* @param {Function} deps.fetchAssets
|
||||
* @param {Object} deps.pagination
|
||||
* @param {Object} deps.exportConfig
|
||||
* @param {Function} deps.navigate
|
||||
* @param {Function} deps.getFilters
|
||||
* @param {Function} deps.getSort
|
||||
* @param {Function} deps.getTableInstance
|
||||
*/
|
||||
export function buildToolbarActions({ fetchAssets, pagination, exportConfig, navigate, getFilters, getSort, getTableInstance }) {
|
||||
return [
|
||||
{
|
||||
key: "refresh",
|
||||
type: "button",
|
||||
icon: <RefreshCw className="h-3.5 w-3.5" />,
|
||||
label: "Refresh",
|
||||
onClick: () =>
|
||||
fetchAssets({
|
||||
page: 1,
|
||||
limit: pagination.limit,
|
||||
filters: getFilters(),
|
||||
sort: getSort(),
|
||||
}),
|
||||
},
|
||||
{
|
||||
key: "export",
|
||||
type: "button",
|
||||
icon: <Download className="h-3.5 w-3.5" />,
|
||||
label: "Export",
|
||||
onClick: (table) =>
|
||||
exportTableToExcel({
|
||||
...exportConfig,
|
||||
tableInstance: table ?? getTableInstance(),
|
||||
}),
|
||||
},
|
||||
{
|
||||
key: "add-asset",
|
||||
type: "button",
|
||||
icon: <Plus className="h-3.5 w-3.5" />,
|
||||
label: "Add File",
|
||||
variant: "default",
|
||||
className: "text-primary-foreground",
|
||||
onClick: () => navigate("add"),
|
||||
},
|
||||
{
|
||||
key: "bulk-upload",
|
||||
type: "button",
|
||||
icon: <UploadCloud className="h-3.5 w-3.5" />,
|
||||
label: "Bulk Upload",
|
||||
variant: "secondary",
|
||||
className: "border border-border",
|
||||
onClick: () => navigate("add/bulk"),
|
||||
},
|
||||
{
|
||||
key: "archived-users",
|
||||
type: "button",
|
||||
icon: <Archive className="h-3.5 w-3.5" />,
|
||||
label: "Archived Files",
|
||||
variant: "secondary",
|
||||
className: "border border-border",
|
||||
onClick: () => navigate("/admin/assets/archived"),
|
||||
},
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import { RotateCcw, Trash2 } from "lucide-react";
|
||||
|
||||
export function buildRowActions({ onRestore, onDelete }) {
|
||||
return [
|
||||
{
|
||||
key: "restore",
|
||||
label: "Restore",
|
||||
icon: <RotateCcw className="h-3.5 w-3.5" />,
|
||||
className: "text-emerald-600",
|
||||
onClick: (row) => onRestore(row),
|
||||
},
|
||||
{
|
||||
key: "delete",
|
||||
label: "Delete",
|
||||
icon: <Trash2 className="h-3.5 w-3.5" />,
|
||||
className: "text-destructive focus:text-destructive",
|
||||
onClick: (row) => onDelete(row),
|
||||
separator: true,
|
||||
},
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import { RotateCcw, Trash2 } from "lucide-react";
|
||||
|
||||
export function buildSelectionActions({ onRestore, onRestoreMany, onDelete, onDeleteMany }) {
|
||||
return [
|
||||
{
|
||||
key: "restore-selected",
|
||||
label: "Restore",
|
||||
icon: <RotateCcw className="h-3.5 w-3.5" />,
|
||||
className: "text-emerald-600 border-emerald-200 hover:bg-emerald-50",
|
||||
onClick: (rows) => {
|
||||
const ids = rows.map((r) => r.id);
|
||||
ids.length === 1 ? onRestore(rows[0]) : onRestoreMany(ids);
|
||||
},
|
||||
},
|
||||
{
|
||||
key: "delete-selected",
|
||||
label: "Delete",
|
||||
icon: <Trash2 className="h-3.5 w-3.5" />,
|
||||
className: "text-destructive border-destructive/40 hover:bg-destructive/10 hover:text-destructive",
|
||||
onClick: (rows) => {
|
||||
const ids = rows.map((r) => r.id);
|
||||
ids.length === 1 ? onDelete(rows[0]) : onDeleteMany(ids);
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import { RefreshCw, Download, ArchiveRestore } from "lucide-react";
|
||||
import { exportTableToExcel } from "@/utils/excel.util";
|
||||
|
||||
export function buildToolbarActions({ fetchCategories, pagination, exportConfig, navigate, getFilters, getSort, getTableInstance }) {
|
||||
return [
|
||||
{
|
||||
key: "refresh",
|
||||
type: "button",
|
||||
label: "Refresh",
|
||||
icon: <RefreshCw className="h-3.5 w-3.5" />,
|
||||
variant: "outline",
|
||||
onClick: () => fetchCategories({
|
||||
page: 1,
|
||||
limit: pagination?.limit ?? 10,
|
||||
filters: getFilters(),
|
||||
sort: getSort(),
|
||||
archived: true,
|
||||
}),
|
||||
},
|
||||
{
|
||||
key: "export",
|
||||
type: "button",
|
||||
label: "Export",
|
||||
icon: <Download className="h-3.5 w-3.5" />,
|
||||
variant: "outline",
|
||||
onClick: () => exportTableToExcel({
|
||||
...exportConfig,
|
||||
tableInstance: getTableInstance(),
|
||||
}),
|
||||
},
|
||||
{
|
||||
key: "active",
|
||||
type: "button",
|
||||
label: "Active Categories",
|
||||
icon: <ArchiveRestore className="h-3.5 w-3.5" />,
|
||||
variant: "secondary",
|
||||
className: "border border-border",
|
||||
onClick: () => navigate("/admin/courses/categories"),
|
||||
},
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { buildColumns } from "@/utils/table.util";
|
||||
import { buildSelectionColumn } from "@/components/generic/Table/buildSelectionColumn";
|
||||
import { buildRowActionsColumn } from "@/components/generic/Table/buildRowActionsColumn";
|
||||
|
||||
export const columnPinning = {
|
||||
right: ["actions"],
|
||||
left: [],
|
||||
};
|
||||
|
||||
export function buildDataColumns(attributes, rowActions) {
|
||||
const visibleAttributes = attributes.filter((a) => !a.hidden);
|
||||
const dataColumns = buildColumns(visibleAttributes);
|
||||
|
||||
return [
|
||||
buildSelectionColumn(),
|
||||
...dataColumns,
|
||||
buildRowActionsColumn(rowActions, { dropdownLabel: "Category Actions" }),
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { Pencil, Trash2 } from "lucide-react";
|
||||
|
||||
export function buildRowActions({ navigate, onArchive }) {
|
||||
return [
|
||||
{
|
||||
key: "edit",
|
||||
label: "Edit",
|
||||
icon: <Pencil className="h-3.5 w-3.5" />,
|
||||
onClick: (row) => navigate(`/admin/courses/categories/${row.id}/edit`),
|
||||
},
|
||||
{
|
||||
key: "archive",
|
||||
label: "Archive",
|
||||
icon: <Trash2 className="h-3.5 w-3.5" />,
|
||||
className: "text-destructive",
|
||||
onClick: (row) => onArchive(row),
|
||||
separator: true,
|
||||
},
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { Archive } from "lucide-react";
|
||||
|
||||
export function buildSelectionActions({ onArchive, onArchiveMany }) {
|
||||
return [
|
||||
{
|
||||
key: "archive-selected",
|
||||
label: "Archive",
|
||||
icon: <Archive className="h-3.5 w-3.5" />,
|
||||
className: "text-destructive border-destructive/40 hover:bg-destructive/10 hover:text-destructive",
|
||||
onClick: (rows) => {
|
||||
const ids = rows.map((r) => r.id);
|
||||
ids.length === 1 ? onArchive(rows[0]) : onArchiveMany(ids);
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import { Plus, RefreshCw, Download, Archive } from "lucide-react";
|
||||
import { exportTableToExcel } from "@/utils/excel.util";
|
||||
|
||||
export function buildToolbarActions({ fetchCategories, pagination, exportConfig, navigate, getFilters, getSort, getTableInstance }) {
|
||||
return [
|
||||
{
|
||||
key: "refresh",
|
||||
type: "button",
|
||||
label: "Refresh",
|
||||
icon: <RefreshCw className="h-3.5 w-3.5" />,
|
||||
variant: "outline",
|
||||
onClick: () => fetchCategories({
|
||||
page: 1,
|
||||
limit: pagination?.limit ?? 10,
|
||||
filters: getFilters(),
|
||||
sort: getSort(),
|
||||
}),
|
||||
},
|
||||
{
|
||||
key: "export",
|
||||
type: "button",
|
||||
label: "Export",
|
||||
icon: <Download className="h-3.5 w-3.5" />,
|
||||
variant: "outline",
|
||||
onClick: () => exportTableToExcel({
|
||||
...exportConfig,
|
||||
tableInstance: getTableInstance(),
|
||||
}),
|
||||
},
|
||||
{
|
||||
key: "create",
|
||||
type: "button",
|
||||
label: "Add Category",
|
||||
icon: <Plus className="h-3.5 w-3.5" />,
|
||||
variant: "default",
|
||||
onClick: () => navigate("/admin/courses/categories/add"),
|
||||
},
|
||||
{
|
||||
key: "archived",
|
||||
type: "button",
|
||||
label: "Archived",
|
||||
icon: <Archive className="h-3.5 w-3.5" />,
|
||||
variant: "secondary",
|
||||
className: "border border-border",
|
||||
onClick: () => navigate("/admin/courses/categories/archived"),
|
||||
},
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
// config/columns.config.jsx
|
||||
// Column definitions and pinning config for the Users table.
|
||||
|
||||
import { buildColumns } from "@/utils/table.util";
|
||||
import { buildSelectionColumn } from "@/components/generic/Table/buildSelectionColumn";
|
||||
import { buildRowActionsColumn } from "@/components/generic/Table/buildRowActionsColumn";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Book, BookOpenCheck, Clock } from "lucide-react";
|
||||
import { formatDuration } from "@/utils/timestamp.util";
|
||||
|
||||
export const columnPinning = {
|
||||
right: ["actions"],
|
||||
left: [],
|
||||
};
|
||||
|
||||
|
||||
// ─── Custom cell overrides ────────────────────────────────────────────────────
|
||||
const cellOverrides = {
|
||||
unitCount: (info) => {
|
||||
const count = parseInt(info.getValue() ?? 0, 10);
|
||||
return (
|
||||
<div className="flex items-center gap-1.5">
|
||||
<Book className="h-3.5 w-3.5 text-muted-foreground" />
|
||||
<Badge variant="secondary" className="text-xs font-medium tabular-nums">
|
||||
{count} {count === 1 ? "unit" : "units"}
|
||||
</Badge>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
lessonCount: (info) => {
|
||||
const count = parseInt(info.getValue() ?? 0, 10);
|
||||
return (
|
||||
<div className="flex items-center gap-1.5">
|
||||
<BookOpenCheck className="h-3.5 w-3.5 text-muted-foreground" />
|
||||
<Badge variant="secondary" className="text-xs font-medium tabular-nums">
|
||||
{count} {count === 1 ? "lesson" : "lessons"}
|
||||
</Badge>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
duration_seconds: (info) => {
|
||||
const seconds = parseInt(info.getValue() ?? 0, 10);
|
||||
|
||||
return (
|
||||
<div className="flex items-center gap-1.5">
|
||||
<Clock className="h-3.5 w-3.5 text-muted-foreground" />
|
||||
<Badge variant="secondary" className="text-xs font-medium tabular-nums">
|
||||
{formatDuration(seconds)}
|
||||
</Badge>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* Builds the full column array for the Users table.
|
||||
*
|
||||
* @param {Array} attributes Field definitions from the server (drives data columns)
|
||||
* @param {Array} rowActions Row-level kebab action definitions
|
||||
* @returns {Array} TanStack column definitions
|
||||
*/
|
||||
export function buildDataColumns(attributes, rowActions) {
|
||||
const visibleAttributes = attributes.filter((a) => !a.hidden);
|
||||
|
||||
return [
|
||||
buildSelectionColumn(),
|
||||
...buildColumns(visibleAttributes, { cellOverrides }),
|
||||
buildRowActionsColumn(rowActions, { dropdownLabel: "Course Actions" }),
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
// modules/admin/config/assets/rowActions.config.jsx
|
||||
import { RotateCcw, Trash2 } from "lucide-react";
|
||||
|
||||
/**
|
||||
* @param {Object} deps
|
||||
* @param {Function} deps.onView (row) → void — navigate to view page
|
||||
* @param {Function} deps.onEdit (row) → void — navigate to edit page
|
||||
* @param {Function} deps.onArchive (row) → void — open archive dialog
|
||||
*/
|
||||
export function buildRowActions({ onRestore, onDelete }) {
|
||||
return [
|
||||
{
|
||||
key: "restore",
|
||||
label: "Restore",
|
||||
className: "text-emerald-600 focus:text-emerald-600",
|
||||
icon: <RotateCcw className="h-3.5 w-3.5" />,
|
||||
onClick: (row) => onRestore(row),
|
||||
},
|
||||
{
|
||||
key: "delete",
|
||||
label: "Delete",
|
||||
className: "text-destructive focus:text-destructive",
|
||||
icon: <Trash2 className="h-3.5 w-3.5" />,
|
||||
onClick: (row) => onDelete(row),
|
||||
},
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
// config/assets/archive/selection.config.jsx
|
||||
import { Download, ArchiveRestore, Trash2 } from "lucide-react";
|
||||
import { exportTableToExcel } from "@/utils/excel.util";
|
||||
|
||||
export function buildSelectionActions({ exportConfig, restoreCourse, restoreCourses, deleteCourse, deleteCourses, getTableInstance }) {
|
||||
return [
|
||||
{
|
||||
key: "export-selected",
|
||||
label: "Export",
|
||||
icon: <Download className="h-3.5 w-3.5" />,
|
||||
onClick: (rows, table) =>
|
||||
exportTableToExcel({
|
||||
...exportConfig,
|
||||
selectedRows: rows,
|
||||
tableInstance: table ?? getTableInstance(),
|
||||
}),
|
||||
},
|
||||
{
|
||||
key: "restore-selected",
|
||||
label: "Restore",
|
||||
icon: <ArchiveRestore className="h-3.5 w-3.5" />,
|
||||
className: "text-emerald-600 border-emerald-600/40 hover:bg-emerald-600/10 hover:text-emerald-700",
|
||||
onClick: (rows) => {
|
||||
const ids = rows.map((r) => r.course_id);
|
||||
ids.length === 1
|
||||
? restoreCourse(rows[0])
|
||||
: restoreCourses(ids);
|
||||
},
|
||||
},
|
||||
{
|
||||
key: "delete-selected",
|
||||
label: "Delete",
|
||||
icon: <Trash2 className="h-3.5 w-3.5" />,
|
||||
className: "text-destructive border-destructive/40 hover:bg-destructive/10 hover:text-destructive",
|
||||
onClick: (rows) => {
|
||||
const ids = rows.map((r) => r.course_id);
|
||||
ids.length === 1
|
||||
? deleteCourse(rows[0])
|
||||
: deleteCourses(ids);
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import { Plus, RefreshCw, Download, Archive } from "lucide-react";
|
||||
import { exportTableToExcel } from "@/utils/excel.util";
|
||||
|
||||
export function buildToolbarActions({
|
||||
fetchArchivedCourses,
|
||||
pagination,
|
||||
exportConfig,
|
||||
navigate,
|
||||
getFilters,
|
||||
getSort,
|
||||
getTableInstance,
|
||||
}) {
|
||||
return [
|
||||
{
|
||||
key: "refresh",
|
||||
type: "button",
|
||||
label: "Refresh",
|
||||
icon: <RefreshCw className="h-3.5 w-3.5" />,
|
||||
variant: "outline",
|
||||
onClick: () => fetchArchivedCourses({
|
||||
page: 1,
|
||||
limit: pagination?.limit ?? 10,
|
||||
filters: getFilters(),
|
||||
sort: getSort(),
|
||||
}),
|
||||
},
|
||||
{
|
||||
key: "export",
|
||||
type: "button",
|
||||
label: "Export",
|
||||
icon: <Download className="h-3.5 w-3.5" />,
|
||||
variant: "outline",
|
||||
onClick: () => exportTableToExcel({
|
||||
...exportConfig,
|
||||
tableInstance: getTableInstance(),
|
||||
}),
|
||||
},
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
// config/columns.config.jsx
|
||||
// Column definitions and pinning config for the Users table.
|
||||
|
||||
import { buildColumns } from "@/utils/table.util";
|
||||
import { buildSelectionColumn } from "@/components/generic/Table/buildSelectionColumn";
|
||||
import { buildRowActionsColumn } from "@/components/generic/Table/buildRowActionsColumn";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Book, BookOpenCheck, Clock, Tag } from "lucide-react";
|
||||
import * as LucideIcons from "lucide-react";
|
||||
import { formatDuration } from "@/utils/timestamp.util";
|
||||
import { resolveTierBadge } from "@/utils/tierBadge.util";
|
||||
|
||||
export const columnPinning = {
|
||||
right: ["actions"],
|
||||
left: [],
|
||||
};
|
||||
|
||||
|
||||
// ─── Custom cell overrides ────────────────────────────────────────────────────
|
||||
function buildCellOverrides(tierMap) {
|
||||
return {
|
||||
unitCount: (info) => {
|
||||
const count = parseInt(info.getValue() ?? 0, 10);
|
||||
return (
|
||||
<div className="flex items-center gap-1.5">
|
||||
<Book className="h-3.5 w-3.5 text-muted-foreground" />
|
||||
<Badge variant="secondary" className="text-xs font-medium tabular-nums">
|
||||
{count} {count === 1 ? "unit" : "units"}
|
||||
</Badge>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
lessonCount: (info) => {
|
||||
const count = parseInt(info.getValue() ?? 0, 10);
|
||||
return (
|
||||
<div className="flex items-center gap-1.5">
|
||||
<BookOpenCheck className="h-3.5 w-3.5 text-muted-foreground" />
|
||||
<Badge variant="secondary" className="text-xs font-medium tabular-nums">
|
||||
{count} {count === 1 ? "lesson" : "lessons"}
|
||||
</Badge>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
duration_seconds: (info) => {
|
||||
const seconds = parseInt(info.getValue() ?? 0, 10);
|
||||
|
||||
return (
|
||||
<div className="flex items-center gap-1.5">
|
||||
<Clock className="h-3.5 w-3.5 text-muted-foreground" />
|
||||
<Badge variant="secondary" className="text-xs font-medium tabular-nums">
|
||||
{formatDuration(seconds)}
|
||||
</Badge>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
subscription: (info) => {
|
||||
const slug = info.getValue();
|
||||
if (!slug) return <span className="text-muted-foreground/40">-</span>;
|
||||
|
||||
const { label, cls } = resolveTierBadge(slug, tierMap);
|
||||
const Icon = LucideIcons[tierMap[slug]?.badge_icon] ?? Tag;
|
||||
return (
|
||||
<Badge className={cls}>
|
||||
<Icon className="size-3" />
|
||||
{label}
|
||||
</Badge>
|
||||
);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds the full column array for the Users table.
|
||||
*
|
||||
* @param {Array} attributes Field definitions from the server (drives data columns)
|
||||
* @param {Array} rowActions Row-level kebab action definitions
|
||||
* @param {Object} tierMap slug → tier category, for colored Subscription badges
|
||||
* @returns {Array} TanStack column definitions
|
||||
*/
|
||||
export function buildDataColumns(attributes, rowActions, tierMap = {}) {
|
||||
const visibleAttributes = attributes.filter((a) => !a.hidden);
|
||||
const cellOverrides = buildCellOverrides(tierMap);
|
||||
|
||||
return [
|
||||
buildSelectionColumn(),
|
||||
...buildColumns(visibleAttributes, { cellOverrides }),
|
||||
buildRowActionsColumn(rowActions, { dropdownLabel: "Course Actions" }),
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
// config/columns.config.jsx
|
||||
// Column definitions and pinning config for the Users table.
|
||||
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Clock } from "lucide-react";
|
||||
import { buildColumns } from "@/utils/table.util";
|
||||
import { buildSelectionColumn } from "@/components/generic/Table/buildSelectionColumn";
|
||||
import { buildRowActionsColumn } from "@/components/generic/Table/buildRowActionsColumn";
|
||||
import { formatDuration } from "@/utils/timestamp.util";
|
||||
|
||||
export const columnPinning = {
|
||||
right: ["actions"],
|
||||
left: [],
|
||||
};
|
||||
|
||||
// ─── Custom cell overrides ────────────────────────────────────────────────────
|
||||
const cellOverrides = {
|
||||
duration_seconds: (info) => {
|
||||
const seconds = parseInt(info.getValue() ?? 0, 10);
|
||||
|
||||
return (
|
||||
<div className="flex items-center gap-1.5">
|
||||
<Clock className="h-3.5 w-3.5 text-muted-foreground" />
|
||||
<Badge variant="secondary" className="text-xs font-medium tabular-nums">
|
||||
{formatDuration(seconds)}
|
||||
</Badge>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* Builds the full column array for the Users table.
|
||||
*
|
||||
* @param {Array} attributes Field definitions from the server (drives data columns)
|
||||
* @param {Array} rowActions Row-level kebab action definitions
|
||||
* @returns {Array} TanStack column definitions
|
||||
*/
|
||||
export function buildDataColumns(attributes, rowActions) {
|
||||
const visibleAttributes = attributes.filter((a) => !a.hidden);
|
||||
|
||||
return [
|
||||
buildSelectionColumn(),
|
||||
...buildColumns(visibleAttributes, { cellOverrides }),
|
||||
buildRowActionsColumn(rowActions, { dropdownLabel: "Lesson Actions" }),
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
// modules/admin/config/assets/rowActions.config.jsx
|
||||
import { RotateCcw, Trash2 } from "lucide-react";
|
||||
|
||||
/**
|
||||
* @param {Object} deps
|
||||
* @param {Function} deps.onView (row) → void — navigate to view page
|
||||
* @param {Function} deps.onEdit (row) → void — navigate to edit page
|
||||
* @param {Function} deps.onArchive (row) → void — open archive dialog
|
||||
*/
|
||||
export function buildRowActions({ onRestore, onDelete }) {
|
||||
return [
|
||||
{
|
||||
key: "restore",
|
||||
label: "Restore",
|
||||
className: "text-emerald-600 focus:text-emerald-600",
|
||||
icon: <RotateCcw className="h-3.5 w-3.5" />,
|
||||
onClick: (row) => onRestore(row),
|
||||
},
|
||||
{
|
||||
key: "delete",
|
||||
label: "Delete",
|
||||
className: "text-destructive focus:text-destructive",
|
||||
icon: <Trash2 className="h-3.5 w-3.5" />,
|
||||
onClick: (row) => onDelete(row),
|
||||
},
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
// config/assets/archive/selection.config.jsx
|
||||
import { Download, ArchiveRestore, Trash2 } from "lucide-react";
|
||||
import { exportTableToExcel } from "@/utils/excel.util";
|
||||
|
||||
export function buildSelectionActions({ exportConfig, restoreLesson, restoreLessons, deleteLesson, deleteLessons, getTableInstance }) {
|
||||
return [
|
||||
{
|
||||
key: "export-selected",
|
||||
label: "Export",
|
||||
icon: <Download className="h-3.5 w-3.5" />,
|
||||
onClick: (rows, table) =>
|
||||
exportTableToExcel({
|
||||
...exportConfig,
|
||||
selectedRows: rows,
|
||||
tableInstance: table ?? getTableInstance(),
|
||||
}),
|
||||
},
|
||||
{
|
||||
key: "restore-selected",
|
||||
label: "Restore",
|
||||
icon: <ArchiveRestore className="h-3.5 w-3.5" />,
|
||||
className: "text-emerald-600 border-emerald-600/40 hover:bg-emerald-600/10 hover:text-emerald-700",
|
||||
onClick: (rows) => {
|
||||
const ids = rows.map((r) => r.lesson_id);
|
||||
ids.length === 1
|
||||
? restoreLesson(rows[0])
|
||||
: restoreLessons(ids);
|
||||
},
|
||||
},
|
||||
{
|
||||
key: "delete-selected",
|
||||
label: "Delete",
|
||||
icon: <Trash2 className="h-3.5 w-3.5" />,
|
||||
className: "text-destructive border-destructive/40 hover:bg-destructive/10 hover:text-destructive",
|
||||
onClick: (rows) => {
|
||||
const ids = rows.map((r) => r.lesson_id);
|
||||
ids.length === 1
|
||||
? deleteLesson(rows[0])
|
||||
: deleteLessons(ids);
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import { Plus, RefreshCw, Download, Archive } from "lucide-react";
|
||||
import { exportTableToExcel } from "@/utils/excel.util";
|
||||
|
||||
export function buildToolbarActions({
|
||||
fetchArchivedLessons,
|
||||
pagination,
|
||||
exportConfig,
|
||||
navigate,
|
||||
getFilters,
|
||||
getSort,
|
||||
getTableInstance,
|
||||
}) {
|
||||
return [
|
||||
{
|
||||
key: "refresh",
|
||||
type: "button",
|
||||
label: "Refresh",
|
||||
icon: <RefreshCw className="h-3.5 w-3.5" />,
|
||||
variant: "outline",
|
||||
onClick: () => fetchArchivedLessons({
|
||||
page: 1,
|
||||
limit: pagination?.limit ?? 10,
|
||||
filters: getFilters(),
|
||||
sort: getSort(),
|
||||
}),
|
||||
},
|
||||
{
|
||||
key: "export",
|
||||
type: "button",
|
||||
label: "Export",
|
||||
icon: <Download className="h-3.5 w-3.5" />,
|
||||
variant: "outline",
|
||||
onClick: () => exportTableToExcel({
|
||||
...exportConfig,
|
||||
tableInstance: getTableInstance(),
|
||||
}),
|
||||
},
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
// config/columns.config.jsx
|
||||
// Column definitions and pinning config for the Users table.
|
||||
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Clock, Tag } from "lucide-react";
|
||||
import * as LucideIcons from "lucide-react";
|
||||
import { buildColumns } from "@/utils/table.util";
|
||||
import { buildSelectionColumn } from "@/components/generic/Table/buildSelectionColumn";
|
||||
import { buildRowActionsColumn } from "@/components/generic/Table/buildRowActionsColumn";
|
||||
import { formatDuration } from "@/utils/timestamp.util";
|
||||
import { resolveTierBadge } from "@/utils/tierBadge.util";
|
||||
|
||||
export const columnPinning = {
|
||||
right: ["actions"],
|
||||
left: [],
|
||||
};
|
||||
|
||||
// ─── Custom cell overrides ────────────────────────────────────────────────────
|
||||
function buildCellOverrides(tierMap, unitSubscription, courseSubscription) {
|
||||
return {
|
||||
duration_seconds: (info) => {
|
||||
const seconds = parseInt(info.getValue() ?? 0, 10);
|
||||
|
||||
return (
|
||||
<div className="flex items-center gap-1.5">
|
||||
<Clock className="h-3.5 w-3.5 text-muted-foreground" />
|
||||
<Badge variant="secondary" className="text-xs font-medium tabular-nums">
|
||||
{formatDuration(seconds)}
|
||||
</Badge>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
subscription: (info) => {
|
||||
const slug = info.getValue() || unitSubscription || courseSubscription;
|
||||
if (!slug) return <span className="text-muted-foreground/40">-</span>;
|
||||
|
||||
const { label, cls } = resolveTierBadge(slug, tierMap);
|
||||
const Icon = LucideIcons[tierMap[slug]?.badge_icon] ?? Tag;
|
||||
return (
|
||||
<Badge className={cls}>
|
||||
<Icon className="size-3" />
|
||||
{label}
|
||||
</Badge>
|
||||
);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds the full column array for the Users table.
|
||||
*
|
||||
* @param {Array} attributes Field definitions from the server (drives data columns)
|
||||
* @param {Array} rowActions Row-level kebab action definitions
|
||||
* @param {Object} tierMap slug → tier category, for colored Subscription badges
|
||||
* @param {string} unitSubscription Parent unit's tier, used when the lesson has no direct tier of its own
|
||||
* @param {string} courseSubscription Parent course's tier, used when neither the lesson nor the unit has one
|
||||
* @returns {Array} TanStack column definitions
|
||||
*/
|
||||
export function buildDataColumns(attributes, rowActions, tierMap = {}, unitSubscription = null, courseSubscription = null) {
|
||||
const visibleAttributes = attributes.filter((a) => !a.hidden);
|
||||
const cellOverrides = buildCellOverrides(tierMap, unitSubscription, courseSubscription);
|
||||
|
||||
return [
|
||||
buildSelectionColumn(),
|
||||
...buildColumns(visibleAttributes, { cellOverrides }),
|
||||
buildRowActionsColumn(rowActions, { dropdownLabel: "Lesson Actions" }),
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { Eye, Archive } from "lucide-react";
|
||||
|
||||
export function buildRowActions({ onView, onArchive }) {
|
||||
return [
|
||||
{
|
||||
key: "view",
|
||||
label: "View Lesson",
|
||||
icon: <Eye className="h-3.5 w-3.5" />,
|
||||
onClick: (row) => onView(row),
|
||||
},
|
||||
{
|
||||
key: "archive",
|
||||
label: "Archive",
|
||||
icon: <Archive className="h-3.5 w-3.5" />,
|
||||
className: "text-destructive",
|
||||
onClick: (row) => onArchive(row),
|
||||
separator: true
|
||||
},
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import { Download, Archive } from "lucide-react";
|
||||
import { exportTableToExcel } from "@/utils/excel.util";
|
||||
|
||||
export function buildSelectionActions({ exportConfig, onArchive, onArchiveMany, getTableInstance }) {
|
||||
return [
|
||||
{
|
||||
key: "export-selected",
|
||||
label: "Export",
|
||||
icon: <Download className="h-3.5 w-3.5" />,
|
||||
onClick: (rows, table) =>
|
||||
exportTableToExcel({
|
||||
...exportConfig,
|
||||
selectedRows: rows,
|
||||
tableInstance: table ?? getTableInstance(),
|
||||
}),
|
||||
},
|
||||
{
|
||||
key: "archive-selected",
|
||||
label: "Archive",
|
||||
icon: <Archive className="h-3.5 w-3.5" />,
|
||||
className: "text-destructive border-destructive/40 hover:bg-destructive/10 hover:text-destructive",
|
||||
onClick: (rows) => {
|
||||
const ids = rows.map((r) => r.lesson_id);
|
||||
ids.length === 1
|
||||
? onArchive(rows[0])
|
||||
: onArchiveMany(ids);
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
// config/courses/lessons/toolbar.config.jsx
|
||||
|
||||
import { Plus, RefreshCw, Download, Archive } from "lucide-react";
|
||||
import { exportTableToExcel } from "@/utils/excel.util";
|
||||
|
||||
export function buildToolbarActions({
|
||||
fetchLessons,
|
||||
pagination,
|
||||
exportConfig,
|
||||
navigate,
|
||||
courseId,
|
||||
unitId,
|
||||
getFilters,
|
||||
getSort,
|
||||
getTableInstance,
|
||||
}) {
|
||||
return [
|
||||
{
|
||||
key: "refresh",
|
||||
type: "button",
|
||||
label: "Refresh",
|
||||
icon: <RefreshCw className="h-3.5 w-3.5" />,
|
||||
variant: "outline",
|
||||
onClick: () => fetchLessons({
|
||||
page: 1,
|
||||
limit: pagination?.limit ?? 10,
|
||||
filters: getFilters(),
|
||||
sort: getSort(),
|
||||
}),
|
||||
},
|
||||
{
|
||||
key: "export",
|
||||
type: "button",
|
||||
label: "Export",
|
||||
icon: <Download className="h-3.5 w-3.5" />,
|
||||
variant: "outline",
|
||||
onClick: () => exportTableToExcel({
|
||||
...exportConfig,
|
||||
tableInstance: getTableInstance(),
|
||||
}),
|
||||
},
|
||||
{
|
||||
key: "create",
|
||||
type: "button",
|
||||
label: "New Lesson",
|
||||
icon: <Plus className="h-3.5 w-3.5" />,
|
||||
variant: "default",
|
||||
onClick: () => navigate(
|
||||
`/admin/courses/${courseId}/units/${unitId}/lessons/add`
|
||||
),
|
||||
},
|
||||
{
|
||||
key: "archived-lessons",
|
||||
type: "button",
|
||||
icon: <Archive className="h-3.5 w-3.5" />,
|
||||
label: "Archived Lessons",
|
||||
variant: "secondary",
|
||||
className: "border border-border",
|
||||
onClick: () => navigate(`/admin/courses/${courseId}/units/${unitId}/lessons/archived`),
|
||||
},
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import { Eye, Archive, ArrowUp, ArrowDown } from "lucide-react";
|
||||
|
||||
export function buildRowActions({ onView, onEdit, onArchive, onMoveUp, onMoveDown, courses = [] }) {
|
||||
return [
|
||||
{
|
||||
key: "view",
|
||||
label: "View Info",
|
||||
icon: <Eye className="h-3.5 w-3.5" />,
|
||||
onClick: (row) => onView(row),
|
||||
},
|
||||
{
|
||||
key: "move-up",
|
||||
label: "Move Up",
|
||||
icon: <ArrowUp className="h-3.5 w-3.5" />,
|
||||
onClick: (row) => onMoveUp(row),
|
||||
separator: true,
|
||||
disabled: (row) => courses.findIndex((c) => c.course_id === row.course_id) <= 0,
|
||||
},
|
||||
{
|
||||
key: "move-down",
|
||||
label: "Move Down",
|
||||
icon: <ArrowDown className="h-3.5 w-3.5" />,
|
||||
onClick: (row) => onMoveDown(row),
|
||||
disabled: (row) => courses.findIndex((c) => c.course_id === row.course_id) >= courses.length - 1,
|
||||
},
|
||||
{
|
||||
key: "archive",
|
||||
label: "Archive Course",
|
||||
icon: <Archive className="h-3.5 w-3.5" />,
|
||||
className: "text-destructive",
|
||||
onClick: (row) => onArchive(row),
|
||||
separator: true,
|
||||
},
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import { Download, Archive } from "lucide-react";
|
||||
import { exportTableToExcel } from "@/utils/excel.util";
|
||||
|
||||
export function buildSelectionActions({ exportConfig, onArchive, onArchiveMany, getTableInstance }) {
|
||||
return [
|
||||
{
|
||||
key: "export-selected",
|
||||
label: "Export",
|
||||
icon: <Download className="h-3.5 w-3.5" />,
|
||||
onClick: (rows, table) =>
|
||||
exportTableToExcel({
|
||||
...exportConfig,
|
||||
selectedRows: rows,
|
||||
tableInstance: table ?? getTableInstance(),
|
||||
}),
|
||||
},
|
||||
{
|
||||
key: "archive-selected",
|
||||
label: "Archive",
|
||||
icon: <Archive className="h-3.5 w-3.5" />,
|
||||
className: "text-destructive border-destructive/40 hover:bg-destructive/10 hover:text-destructive",
|
||||
onClick: (rows) => {
|
||||
const ids = rows.map((r) => r.course_id);
|
||||
ids.length === 1
|
||||
? onArchive(rows[0])
|
||||
: onArchiveMany(ids);
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
import { Plus, RefreshCw, Download, Archive, ArrowUpAZIcon } from "lucide-react";
|
||||
import { exportTableToExcel } from "@/utils/excel.util";
|
||||
|
||||
export function buildToolbarActions({
|
||||
fetchCourses,
|
||||
pagination,
|
||||
exportConfig,
|
||||
navigate,
|
||||
getFilters,
|
||||
getSort,
|
||||
getTableInstance,
|
||||
}) {
|
||||
return [
|
||||
{
|
||||
key: "refresh",
|
||||
type: "button",
|
||||
label: "Refresh",
|
||||
icon: <RefreshCw className="h-3.5 w-3.5" />,
|
||||
variant: "outline",
|
||||
onClick: () => fetchCourses({
|
||||
page: 1,
|
||||
limit: pagination?.limit ?? 10,
|
||||
filters: getFilters(),
|
||||
sort: getSort(),
|
||||
}),
|
||||
},
|
||||
{
|
||||
key: "export",
|
||||
type: "button",
|
||||
label: "Export",
|
||||
icon: <Download className="h-3.5 w-3.5" />,
|
||||
variant: "outline",
|
||||
onClick: () => exportTableToExcel({
|
||||
...exportConfig,
|
||||
tableInstance: getTableInstance(),
|
||||
}),
|
||||
},
|
||||
{
|
||||
key: "create",
|
||||
type: "button",
|
||||
label: "New Course",
|
||||
icon: <Plus className="h-3.5 w-3.5" />,
|
||||
variant: "default",
|
||||
onClick: () => navigate("/admin/courses/add"),
|
||||
},
|
||||
{
|
||||
key: "categories",
|
||||
type: "button",
|
||||
label: "Categories",
|
||||
icon: <ArrowUpAZIcon className="h-3.5 w-3.5" />,
|
||||
variant: "default",
|
||||
onClick: () => navigate("/admin/courses/categories"),
|
||||
},
|
||||
{
|
||||
key: "archived-courses",
|
||||
type: "button",
|
||||
icon: <Archive className="h-3.5 w-3.5" />,
|
||||
label: "Archived Courses",
|
||||
variant: "secondary",
|
||||
className: "border border-border",
|
||||
onClick: () => navigate("/admin/courses/archived"),
|
||||
},
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
// config/columns.config.jsx
|
||||
// Column definitions and pinning config for the Users table.
|
||||
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Clock } from "lucide-react";
|
||||
import { buildColumns } from "@/utils/table.util";
|
||||
import { buildSelectionColumn } from "@/components/generic/Table/buildSelectionColumn";
|
||||
import { buildRowActionsColumn } from "@/components/generic/Table/buildRowActionsColumn";
|
||||
import { formatDuration } from "@/utils/timestamp.util";
|
||||
|
||||
export const columnPinning = {
|
||||
right: ["actions"],
|
||||
left: [],
|
||||
};
|
||||
|
||||
// ─── Custom cell overrides ────────────────────────────────────────────────────
|
||||
const cellOverrides = {
|
||||
duration_seconds: (info) => {
|
||||
const seconds = parseInt(info.getValue() ?? 0, 10);
|
||||
|
||||
return (
|
||||
<div className="flex items-center gap-1.5">
|
||||
<Clock className="h-3.5 w-3.5 text-muted-foreground" />
|
||||
<Badge variant="secondary" className="text-xs font-medium tabular-nums">
|
||||
{formatDuration(seconds)}
|
||||
</Badge>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* Builds the full column array for the Users table.
|
||||
*
|
||||
* @param {Array} attributes Field definitions from the server (drives data columns)
|
||||
* @param {Array} rowActions Row-level kebab action definitions
|
||||
* @returns {Array} TanStack column definitions
|
||||
*/
|
||||
export function buildDataColumns(attributes, rowActions) {
|
||||
const visibleAttributes = attributes.filter((a) => !a.hidden);
|
||||
|
||||
return [
|
||||
buildSelectionColumn(),
|
||||
...buildColumns(visibleAttributes, { cellOverrides }),
|
||||
buildRowActionsColumn(rowActions, { dropdownLabel: "Unit Actions" }),
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
// modules/admin/config/assets/rowActions.config.jsx
|
||||
import { RotateCcw, Trash2 } from "lucide-react";
|
||||
|
||||
/**
|
||||
* @param {Object} deps
|
||||
* @param {Function} deps.onView (row) → void — navigate to view page
|
||||
* @param {Function} deps.onEdit (row) → void — navigate to edit page
|
||||
* @param {Function} deps.onArchive (row) → void — open archive dialog
|
||||
*/
|
||||
export function buildRowActions({ onRestore, onDelete }) {
|
||||
return [
|
||||
{
|
||||
key: "restore",
|
||||
label: "Restore",
|
||||
className: "text-emerald-600 focus:text-emerald-600",
|
||||
icon: <RotateCcw className="h-3.5 w-3.5" />,
|
||||
onClick: (row) => onRestore(row),
|
||||
},
|
||||
{
|
||||
key: "delete",
|
||||
label: "Delete",
|
||||
className: "text-destructive focus:text-destructive",
|
||||
icon: <Trash2 className="h-3.5 w-3.5" />,
|
||||
onClick: (row) => onDelete(row),
|
||||
},
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
// config/assets/archive/selection.config.jsx
|
||||
import { Download, ArchiveRestore, Trash2 } from "lucide-react";
|
||||
import { exportTableToExcel } from "@/utils/excel.util";
|
||||
|
||||
export function buildSelectionActions({ exportConfig, restoreUnit, restoreUnits, deleteUnit, deleteUnits, getTableInstance }) {
|
||||
return [
|
||||
{
|
||||
key: "export-selected",
|
||||
label: "Export",
|
||||
icon: <Download className="h-3.5 w-3.5" />,
|
||||
onClick: (rows, table) =>
|
||||
exportTableToExcel({
|
||||
...exportConfig,
|
||||
selectedRows: rows,
|
||||
tableInstance: table ?? getTableInstance(),
|
||||
}),
|
||||
},
|
||||
{
|
||||
key: "restore-selected",
|
||||
label: "Restore",
|
||||
icon: <ArchiveRestore className="h-3.5 w-3.5" />,
|
||||
className: "text-emerald-600 border-emerald-600/40 hover:bg-emerald-600/10 hover:text-emerald-700",
|
||||
onClick: (rows) => {
|
||||
const ids = rows.map((r) => r.unit_id);
|
||||
ids.length === 1
|
||||
? restoreUnit(rows[0])
|
||||
: restoreUnits(ids);
|
||||
},
|
||||
},
|
||||
{
|
||||
key: "delete-selected",
|
||||
label: "Delete",
|
||||
icon: <Trash2 className="h-3.5 w-3.5" />,
|
||||
className: "text-destructive border-destructive/40 hover:bg-destructive/10 hover:text-destructive",
|
||||
onClick: (rows) => {
|
||||
const ids = rows.map((r) => r.unit_id);
|
||||
ids.length === 1
|
||||
? deleteUnit(rows[0])
|
||||
: deleteUnits(ids);
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import { Plus, RefreshCw, Download, Archive } from "lucide-react";
|
||||
import { exportTableToExcel } from "@/utils/excel.util";
|
||||
|
||||
export function buildToolbarActions({
|
||||
fetchArchivedUnits,
|
||||
pagination,
|
||||
exportConfig,
|
||||
navigate,
|
||||
getFilters,
|
||||
getSort,
|
||||
getTableInstance,
|
||||
}) {
|
||||
return [
|
||||
{
|
||||
key: "refresh",
|
||||
type: "button",
|
||||
label: "Refresh",
|
||||
icon: <RefreshCw className="h-3.5 w-3.5" />,
|
||||
variant: "outline",
|
||||
onClick: () => fetchArchivedUnits({
|
||||
page: 1,
|
||||
limit: pagination?.limit ?? 10,
|
||||
filters: getFilters(),
|
||||
sort: getSort(),
|
||||
}),
|
||||
},
|
||||
{
|
||||
key: "export",
|
||||
type: "button",
|
||||
label: "Export",
|
||||
icon: <Download className="h-3.5 w-3.5" />,
|
||||
variant: "outline",
|
||||
onClick: () => exportTableToExcel({
|
||||
...exportConfig,
|
||||
tableInstance: getTableInstance(),
|
||||
}),
|
||||
},
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
// config/columns.config.jsx
|
||||
// Column definitions and pinning config for the Users table.
|
||||
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Clock, Tag } from "lucide-react";
|
||||
import * as LucideIcons from "lucide-react";
|
||||
import { buildColumns } from "@/utils/table.util";
|
||||
import { buildSelectionColumn } from "@/components/generic/Table/buildSelectionColumn";
|
||||
import { buildRowActionsColumn } from "@/components/generic/Table/buildRowActionsColumn";
|
||||
import { formatDuration } from "@/utils/timestamp.util";
|
||||
import { resolveTierBadge } from "@/utils/tierBadge.util";
|
||||
|
||||
export const columnPinning = {
|
||||
right: ["actions"],
|
||||
left: [],
|
||||
};
|
||||
|
||||
// ─── Custom cell overrides ────────────────────────────────────────────────────
|
||||
function buildCellOverrides(tierMap, courseSubscription) {
|
||||
return {
|
||||
duration_seconds: (info) => {
|
||||
const seconds = parseInt(info.getValue() ?? 0, 10);
|
||||
|
||||
return (
|
||||
<div className="flex items-center gap-1.5">
|
||||
<Clock className="h-3.5 w-3.5 text-muted-foreground" />
|
||||
<Badge variant="secondary" className="text-xs font-medium tabular-nums">
|
||||
{formatDuration(seconds)}
|
||||
</Badge>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
subscription: (info) => {
|
||||
const slug = info.getValue() || courseSubscription;
|
||||
if (!slug) return <span className="text-muted-foreground/40">-</span>;
|
||||
|
||||
const { label, cls } = resolveTierBadge(slug, tierMap);
|
||||
const Icon = LucideIcons[tierMap[slug]?.badge_icon] ?? Tag;
|
||||
return (
|
||||
<Badge className={cls}>
|
||||
<Icon className="size-3" />
|
||||
{label}
|
||||
</Badge>
|
||||
);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds the full column array for the Users table.
|
||||
*
|
||||
* @param {Array} attributes Field definitions from the server (drives data columns)
|
||||
* @param {Array} rowActions Row-level kebab action definitions
|
||||
* @param {Object} tierMap slug → tier category, for colored Subscription badges
|
||||
* @param {string} courseSubscription Parent course's tier, used when the unit has no direct tier of its own
|
||||
* @returns {Array} TanStack column definitions
|
||||
*/
|
||||
export function buildDataColumns(attributes, rowActions, tierMap = {}, courseSubscription = null) {
|
||||
const visibleAttributes = attributes.filter((a) => !a.hidden);
|
||||
const cellOverrides = buildCellOverrides(tierMap, courseSubscription);
|
||||
|
||||
return [
|
||||
buildSelectionColumn(),
|
||||
...buildColumns(visibleAttributes, { cellOverrides }),
|
||||
buildRowActionsColumn(rowActions, { dropdownLabel: "Unit Actions" }),
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { Eye, Archive } from "lucide-react";
|
||||
|
||||
export function buildRowActions({ onView, onArchive }) {
|
||||
return [
|
||||
{
|
||||
key: "view",
|
||||
label: "View Info",
|
||||
icon: <Eye className="h-3.5 w-3.5" />,
|
||||
onClick: (row) => onView(row),
|
||||
},
|
||||
{
|
||||
key: "archive",
|
||||
label: "Archive",
|
||||
icon: <Archive className="h-3.5 w-3.5" />,
|
||||
className: "text-destructive",
|
||||
onClick: (row) => onArchive(row),
|
||||
separator: true,
|
||||
},
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import { Download, Archive } from "lucide-react";
|
||||
import { exportTableToExcel } from "@/utils/excel.util";
|
||||
|
||||
export function buildSelectionActions({ exportConfig, onArchive, onArchiveMany, getTableInstance }) {
|
||||
return [
|
||||
{
|
||||
key: "export-selected",
|
||||
label: "Export",
|
||||
icon: <Download className="h-3.5 w-3.5" />,
|
||||
onClick: (rows, table) =>
|
||||
exportTableToExcel({
|
||||
...exportConfig,
|
||||
selectedRows: rows,
|
||||
tableInstance: table ?? getTableInstance(),
|
||||
}),
|
||||
},
|
||||
{
|
||||
key: "archive-selected",
|
||||
label: "Archive",
|
||||
icon: <Archive className="h-3.5 w-3.5" />,
|
||||
className: "text-destructive border-destructive/40 hover:bg-destructive/10 hover:text-destructive",
|
||||
onClick: (rows) => {
|
||||
const ids = rows.map((r) => r.unit_id);
|
||||
ids.length === 1
|
||||
? onArchive(rows[0])
|
||||
: onArchiveMany(ids);
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
import { Plus, RefreshCw, Download, Archive } from "lucide-react";
|
||||
import { exportTableToExcel } from "@/utils/excel.util";
|
||||
|
||||
export function buildToolbarActions({
|
||||
fetchUnits,
|
||||
pagination,
|
||||
exportConfig,
|
||||
navigate,
|
||||
courseId,
|
||||
returnTo,
|
||||
getFilters,
|
||||
getSort,
|
||||
getTableInstance,
|
||||
}) {
|
||||
return [
|
||||
{
|
||||
key: "refresh",
|
||||
type: "button",
|
||||
label: "Refresh",
|
||||
icon: <RefreshCw className="h-3.5 w-3.5" />,
|
||||
variant: "outline",
|
||||
onClick: () => fetchUnits({
|
||||
page: 1,
|
||||
limit: pagination?.limit ?? 10,
|
||||
filters: getFilters(),
|
||||
sort: getSort(),
|
||||
}),
|
||||
},
|
||||
{
|
||||
key: "export",
|
||||
type: "button",
|
||||
label: "Export",
|
||||
icon: <Download className="h-3.5 w-3.5" />,
|
||||
variant: "outline",
|
||||
onClick: () => exportTableToExcel({
|
||||
...exportConfig,
|
||||
tableInstance: getTableInstance(),
|
||||
}),
|
||||
},
|
||||
{
|
||||
key: "create",
|
||||
type: "button",
|
||||
label: "New Unit",
|
||||
icon: <Plus className="h-3.5 w-3.5" />,
|
||||
variant: "default",
|
||||
onClick: () => navigate(`/admin/courses/${courseId}/units/add`, returnTo ? { state: { returnTo } } : undefined),
|
||||
},
|
||||
{
|
||||
key: "archived-units",
|
||||
type: "button",
|
||||
icon: <Archive className="h-3.5 w-3.5" />,
|
||||
label: "Archived Units",
|
||||
variant: "secondary",
|
||||
className: "border border-border",
|
||||
onClick: () => navigate(`/admin/courses/${courseId}/units/archived`),
|
||||
},
|
||||
];
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user