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,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>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user