import { useEffect, useMemo, useState } from 'react'; import { Link } from 'react-router'; // import { Button, Card, CardFooter, CardHeader, Col, Container, Dropdown, FormCheck, Modal, ModalBody, ModalFooter, ModalHeader, Row } from 'react-bootstrap'; import { Button, Card, CardFooter, CardHeader, Col, Container, Modal, ModalBody, ModalFooter, ModalHeader, Row } from 'react-bootstrap'; import { createColumnHelper, getCoreRowModel, getSortedRowModel, useReactTable } from '@tanstack/react-table'; import { LuSearch } from 'react-icons/lu'; import { TbEdit, TbPlus, TbTrash } from 'react-icons/tb'; import PageBreadcrumb from '@/components/PageBreadcrumb'; import DataTable from '@/components/table/DataTable'; import DeleteConfirmationModal from '@/components/table/DeleteConfirmationModal'; import TablePagination from '@/components/table/TablePagination'; import { useAuth } from '@/context/useAuthContext'; import { api } from '@/lib/api'; import { showDate } from '@/lib/dates'; function formatDate(value) { return showDate(value); } export default function CohortsPage() { const { can, user } = useAuth(); const isVirtualPrt = user?.role?.systemKey === 'educator'; const canFor = (createdAs, action) => ( (createdAs || 'cohorts') === 'manual_cohorts' ? can('prt_cohorts', action) : can('cohorts', action) ); const [items, setItems] = useState([]); const [total, setTotal] = useState(0); const [page, setPage] = useState(0); const [pageSize] = useState(10); const [search, setSearch] = useState(''); const [query, setQuery] = useState(''); const [status, setStatus] = useState(''); const [deleteId, setDeleteId] = useState(null); const [waCohort, setWaCohort] = useState(null); const [waError, setWaError] = useState(''); const [waBusy, setWaBusy] = useState(''); /* Status is changed inside the cohort's Edit page now. const [statusEdit, setStatusEdit] = useState(null); const [statusTargets, setStatusTargets] = useState([]); */ const columnHelper = createColumnHelper(); /* Status is changed inside the cohort's Edit page now. // Opens the status window; cancelling also loads live cohorts the patients can move into. const openStatus = async (cohort, status) => { setStatusEdit({ cohort, status, patientAction: 'pool', targetCohortId: '', error: '', busy: false }); if (status !== 'cancelled') return; const data = await api('/api/cohorts?status=active&limit=100').catch(() => ({ items: [] })); setStatusTargets((data.items || []).filter((item) => item.id !== cohort.id && ['active', 'confirmed'].includes(item.status))); }; */ const load = async () => { const params = new URLSearchParams({ search: query, page: String(page + 1), limit: String(pageSize), }); if (status) params.set('status', status); const data = await api(`/api/cohorts?${params}`); setItems(data.items || []); setTotal(data.total || 0); }; useEffect(() => { load().catch(() => {}); }, [page, query, status]); const columns = useMemo(() => [ columnHelper.accessor('name', { header: 'Cohort', cell: ({ row }) => ( canFor(row.original.createdAs, 'edit') ? {row.original.name} : {row.original.name} ), }), columnHelper.accessor((r) => formatDate(r.startDate), { id: 'startDate', header: 'Start date' }), columnHelper.accessor('slot', { header: 'Slot' }), columnHelper.accessor((r) => (r.virtualPrt ? `${r.virtualPrt.firstName} ${r.virtualPrt.lastName}` : ''), { id: 'virtualPrt', header: 'Virtual PRT', }), columnHelper.accessor((r) => r.status || 'active', { id: 'status', header: 'Status', cell: ({ getValue }) => {getValue()}, }), columnHelper.accessor((r) => r.diseaseType || '—', { id: 'diseaseType', header: 'Category' }), columnHelper.accessor('patientCount', { header: 'Patients' }), // columnHelper.accessor((r) => `${r.sessionsCompleted || 0} of ${r.sessionsPlanned || 0}`, { // columnHelper.accessor((r) => `${r.sessionsCompleted || 0} held`, { // sessions are created daily now columnHelper.accessor((r) => r.sessionsCompleted || 0, { // completed sessions id: 'sessions', header: 'Sessions', }), columnHelper.accessor((r) => r.whatsapp?.status || '—', { id: 'whatsapp', header: 'WhatsApp', cell: ({ row, getValue }) => ( ), }), { // header: 'Cohort actions', header: 'Actions', cell: ({ row }) => (
{/* Status dropdown replaced by the Actions menu below. {canFor(row.original.createdAs, 'edit') && row.original.status !== 'proposed' ? ( ) : null} */} {/* Status is changed inside the cohort's Edit page now. {canFor(row.original.createdAs, 'edit') && row.original.status !== 'proposed' ? ( Cohort action {!['active', 'confirmed'].includes(row.original.status) ? ( openStatus(row.original, 'active')}>Active ) : null} {row.original.status !== 'completed' ? ( openStatus(row.original, 'completed')}>Completed ) : null} {row.original.status !== 'cancelled' ? ( openStatus(row.original, 'cancelled')}>Cancelled ) : null} ) : null} */} {canFor(row.original.createdAs, 'edit') ? : null} {canFor(row.original.createdAs, 'delete') ? ( ) : null}
), }, ], [can]); const table = useReactTable({ data: items, columns, getCoreRowModel: getCoreRowModel(), getSortedRowModel: getSortedRowModel(), }); const start = total === 0 ? 0 : page * pageSize + 1; const end = Math.min((page + 1) * pageSize, total); return (
{ e.preventDefault(); setPage(0); setQuery(search); }}>
setSearch(e.target.value)} />
{can('prt_cohorts', 'add') ? ( Add PRT cohorts ) : null} {can('cohorts', 'add') && !isVirtualPrt ? ( New cohort ) : null}
{total > 0 && ( setPage((p) => Math.max(0, p - 1))} canPreviousPage={page > 0} pageCount={Math.ceil(total / pageSize)} pageIndex={page} setPageIndex={setPage} nextPage={() => setPage((p) => p + 1)} canNextPage={(page + 1) * pageSize < total} /> )}
setWaCohort(null)}>
WhatsApp · {waCohort?.name}
{waError ?
{waError}
: null}

Status: {waCohort?.whatsapp?.status || 'not created'}

{waCohort?.whatsapp?.error ?

{waCohort.whatsapp.error}

: null} {waCohort?.whatsapp?.inviteUrl ?

Invite link

: null}
    {(waCohort?.patients || []).map((patient) => { const member = (waCohort.whatsapp?.members || []).find((item) => item.patientId === patient.id); return (
  • {patient.name} · {patient.whatsappOptOut ? 'opted out' : (member?.status || 'not synced')} {member?.error ? ` · ${member.error}` : ''} {can('onboarding', 'edit') ? ( ) : null}
  • ); })}
{!(waCohort?.patients || []).length ?
No patients on this cohort.
: null}
{canFor(waCohort?.createdAs, 'edit') ? ( <> {['active', 'confirmed'].includes(waCohort?.status) ? ( ) : null} ) : null}
{/* Status is changed inside the cohort's Edit page now. setStatusEdit(null)}>
Set {statusEdit?.cohort?.name} to {statusEdit?.status}
{statusEdit?.error ?
{statusEdit.error}
: null} {statusEdit?.status === 'cancelled' ? ( <>

Upcoming sessions stop. Where should the patients go?

setStatusEdit((s) => ({ ...s, patientAction: 'pool' }))} /> setStatusEdit((s) => ({ ...s, patientAction: 'move' }))} /> {statusEdit.patientAction === 'move' ? ( ) : null} ) : (

This cohort will be marked {statusEdit?.status}.

)}
*/} setDeleteId(null)} itemName="cohort" selectedCount={1} onConfirm={async () => { await api(`/api/cohorts/${deleteId}`, { method: 'DELETE' }); setDeleteId(null); await load(); }} />
); }