added prt names and patient exports

This commit is contained in:
Abhijit 2026-11-23 13:20:03 +05:30
parent f7b45acb96
commit a49f3267b9
7 changed files with 167 additions and 36 deletions

View File

@ -18,6 +18,7 @@ import { notifyPaymentReview } from '../services/notify.js';
import { attendanceProgress, ensureSessionRecords, patientProgramStats, patientVitalsRows, savePatientVitals } from '../services/programSessions.js';
import { assertConfiguredSlot, getAppSettings, slotLabel } from '../services/settings.js';
import { toYmd, weekdayOf } from '../services/schedule.js';
import { toDmy } from '../services/whatsappFormat.js';
const objectId = Joi.string().hex().length(24);
function textField(payload, key) {
@ -224,6 +225,52 @@ function mergeFilters(...parts) {
return { $and: filters };
}
function csvEscape(value) {
const text = value == null ? '' : String(value);
if (/[",\n]/.test(text)) return `"${text.replace(/"/g, '""')}"`;
return text;
}
function toCsv(rows) {
return rows.map((row) => row.map(csvEscape).join(',')).join('\n');
}
function patientStatusLabel(status) {
return normalizePatientStatus(status) === 'deactivated' ? 'Deactivated' : 'Active';
}
async function onboardingListFilter(request) {
const { search = '', reviewStatus, list, paymentStatus, diseaseType, onboardedBy } = request.query;
const extra = {};
if (reviewStatus) extra.reviewStatus = reviewStatus;
if (list === 'pending') extra.reviewStatus = 'pending';
if (list === 'confirmed') extra.reviewStatus = 'confirmed';
if (list === 'rejected') extra.reviewStatus = 'rejected';
if (list === 'assigned') {
extra.reviewStatus = 'confirmed';
extra.matchingStatus = 'assigned';
}
if (list === 'pool') {
extra.reviewStatus = 'confirmed';
extra.matchingStatus = { $in: ['unassigned', 'held'] };
extra.cohort = null;
}
if (paymentStatus) extra.paymentStatus = String(paymentStatus).trim();
if (diseaseType) extra.diseaseType = String(diseaseType).trim();
if (onboardedBy && objectId.validate(onboardedBy).error == null) extra.onboardedBy = onboardedBy;
const searchFilter = {};
if (search) {
const term = String(search).trim();
const mobileHash = hashMobile(term);
const nameHash = hashName(term);
searchFilter.$or = [];
if (mobileHash) searchFilter.$or.push({ mobileHash });
if (nameHash) searchFilter.$or.push({ nameHash });
if (!searchFilter.$or.length) searchFilter.$or.push({ _id: null });
}
return mergeFilters(await onboardingScopeFilter(request), extra, searchFilter);
}
async function findOnboarded(request) {
const item = await OnboardedPatient.findOne(mergeFilters(
{ _id: request.params.id },
@ -242,35 +289,8 @@ export function onboardingRoutes(server) {
path: '/api/onboarding',
options: { pre: [{ method: requirePermission('onboarding', 'view') }] },
handler: async (request) => {
const { search = '', page = 1, limit = 20, reviewStatus, list, paymentStatus, diseaseType, onboardedBy } = request.query;
const extra = {};
if (reviewStatus) extra.reviewStatus = reviewStatus;
if (list === 'pending') extra.reviewStatus = 'pending';
if (list === 'confirmed') extra.reviewStatus = 'confirmed';
if (list === 'rejected') extra.reviewStatus = 'rejected';
if (list === 'assigned') {
extra.reviewStatus = 'confirmed';
extra.matchingStatus = 'assigned';
}
if (list === 'pool') {
extra.reviewStatus = 'confirmed';
extra.matchingStatus = { $in: ['unassigned', 'held'] };
extra.cohort = null;
}
if (paymentStatus) extra.paymentStatus = String(paymentStatus).trim();
if (diseaseType) extra.diseaseType = String(diseaseType).trim();
if (onboardedBy && objectId.validate(onboardedBy).error == null) extra.onboardedBy = onboardedBy;
const searchFilter = {};
if (search) {
const term = String(search).trim();
const mobileHash = hashMobile(term);
const nameHash = hashName(term);
searchFilter.$or = [];
if (mobileHash) searchFilter.$or.push({ mobileHash });
if (nameHash) searchFilter.$or.push({ nameHash });
if (!searchFilter.$or.length) searchFilter.$or.push({ _id: null });
}
const filter = mergeFilters(await onboardingScopeFilter(request), extra, searchFilter);
const { page = 1, limit = 20 } = request.query;
const filter = await onboardingListFilter(request);
const skip = (Number(page) - 1) * Number(limit);
const [items, total] = await Promise.all([
OnboardedPatient.find(filter)
@ -303,6 +323,46 @@ export function onboardingRoutes(server) {
},
});
server.route({
method: 'GET',
path: '/api/onboarding/export',
options: { pre: [{ method: requirePermission('onboarding', 'view') }] },
handler: async (request, h) => {
await writeAudit(request, { action: 'onboarding.exported', resourceType: 'onboardedPatient', resourceId: '' });
const items = await OnboardedPatient.find(await onboardingListFilter(request))
.populate('onboardedBy', 'firstName lastName email')
.populate('cohort', 'name startDate slot language')
.sort({ createdAt: -1 });
const stats = await patientProgramStats(items.map((item) => item._id));
const rows = [
['Patient ID', 'Name', 'Mobile', 'Cohort', 'Category', 'Start date', 'Slot', 'Payment', 'Sessions completed', 'Sessions paid', 'Patient status', 'Review', 'Added by'],
...items.map((item) => {
const patient = toOnboardedPatientDto(item);
const progress = stats.get(String(item._id)) || {};
const start = progress.firstDate || patient.cohort?.startDate || (patient.sessionDate ? toYmd(patient.sessionDate) : '');
return [
patient.id,
patient.name,
patient.mobile,
patient.cohort?.name || (patient.matchingStatus === 'held' ? 'Held' : 'Pool'),
patient.diseaseType,
start ? toDmy(start) : '',
patient.slot,
patient.paymentStatus,
progress.completed || 0,
patient.sessionsPaid,
patientStatusLabel(patient.patientStatus),
patient.reviewStatus === 'confirmed' ? 'Confirmed' : (patient.reviewStatus === 'rejected' ? 'Rejected' : 'Pending'),
patient.onboardedBy ? `${patient.onboardedBy.firstName || ''} ${patient.onboardedBy.lastName || ''}`.trim() : '',
];
}),
];
return h.response(toCsv(rows))
.type('text/csv')
.header('content-disposition', 'attachment; filename="patients.csv"');
},
});
server.route({
method: 'GET',
path: '/api/onboarding/available-cohorts',

View File

@ -11,6 +11,7 @@ import { toYmd } from '../services/schedule.js';
import { toDmy } from '../services/whatsappFormat.js';
import { readOnboardedPii } from '../services/cryptoPii.js';
import { writeAudit } from '../services/audit.js';
import { normalizePatientStatus } from '../utils/serialize.js';
// import { env } from '../config/env.js'; // was for the Recorded at column
const objectId = Joi.string().hex().length(24);
@ -96,6 +97,10 @@ async function previousPrtNames(patients, held) {
const currentPrtName = (patient) => (patient.assignedEducator ? `${patient.assignedEducator.firstName} ${patient.assignedEducator.lastName}` : '');
function patientStatusLabel(patient) {
return normalizePatientStatus(patient?.patientStatus) === 'deactivated' ? 'Deactivated' : 'Active';
}
export function reportRoutes(server) {
server.route({
method: 'GET',
@ -497,7 +502,7 @@ export function reportRoutes(server) {
const widest = allMarks.reduce((max, marks) => Math.max(max, marks.length), 0);
const headers = [
// 'Name', 'Mobile', 'Disease', 'Cohort', 'PRT',
'Name', 'Mobile', 'Disease', 'Cohort', 'Current PRT',
'Name', 'Mobile', 'Disease', 'Cohort', 'Status', 'Current PRT',
'Previous PRT',
'Start date', 'First session', 'Completed', ...Array.from({ length: widest }, (_, index) => `Session ${index + 1}`),
];
@ -511,6 +516,7 @@ export function reportRoutes(server) {
pii.mobile,
patient.diseaseType || '',
patient.cohort?.name || '',
patientStatusLabel(patient),
patient.assignedEducator ? `${patient.assignedEducator.firstName} ${patient.assignedEducator.lastName}` : '',
// prevNames.get(prevPrtIds.get(String(patient._id))) || '',
previousPrt.get(String(patient._id)) || '',

View File

@ -36,7 +36,11 @@ export default function CohortStatusField({ cohortId, value, onChange }) {
{value.patientAction === 'move' ? (
<select className="form-select mt-2" value={value.targetCohortId} onChange={(e) => set({ targetCohortId: e.target.value })}>
<option value="">Select cohort</option>
{targets.map((item) => <option key={item.id} value={item.id}>{item.name} · {item.patientCount} patients</option>)}
{targets.map((item) => {
const prt = [item.virtualPrt?.firstName, item.virtualPrt?.lastName].filter(Boolean).join(' ');
const label = [item.name, prt, `${item.patientCount} patients`].filter(Boolean).join(' · ');
return <option key={item.id} value={item.id}>{label}</option>;
})}
</select>
) : null}
</div>

View File

@ -256,7 +256,7 @@ export default function CohortForm() {
/>
</Col>
{isEdit && statusValue && statusValue.original !== 'proposed' ? (
<Col md={3}>
<Col md={6}>
<CohortStatusField cohortId={id} value={statusValue} onChange={setStatusValue} />
</Col>
) : null}

View File

@ -319,7 +319,7 @@ export default function PrtCohortForm() {
/>
</Col>
{isEdit && statusValue && statusValue.original !== 'proposed' ? (
<Col md={3}>
<Col md={6}>
<CohortStatusField cohortId={id} value={statusValue} onChange={setStatusValue} />
</Col>
) : null}

View File

@ -52,7 +52,12 @@ async function loadScreenshot(id) {
return { url: URL.createObjectURL(blob), blob: true };
}
const emptyMigrate = { id: '', cohortId: '', warnings: [], error: '', busy: false };
const emptyMigrate = { id: '', cohortId: '', prtId: '', warnings: [], error: '', busy: false };
function prtName(prt) {
if (!prt) return '';
return `${prt.firstName || ''} ${prt.lastName || ''}`.trim();
}
export default function OnboardingPage() {
const { can, permissions, user } = useAuth();
@ -75,6 +80,7 @@ export default function OnboardingPage() {
const [migrate, setMigrate] = useState(emptyMigrate);
const [vitalsPatient, setVitalsPatient] = useState(null);
const [cohorts, setCohorts] = useState([]);
const [prts, setPrts] = useState([]);
const [deleteId, setDeleteId] = useState(null);
const [busyId, setBusyId] = useState(null);
const [receipt, setReceipt] = useState({ url: '', title: '', loading: false });
@ -119,8 +125,14 @@ export default function OnboardingPage() {
useEffect(() => {
if (!canReview) return;
api('/api/onboarding/available-cohorts').then((data) => setCohorts(data.items || [])).catch(() => {});
api('/api/users/virtual-prts').then((data) => setPrts(data.items || [])).catch(() => {});
}, [canReview]);
const moveCohorts = useMemo(() => {
if (!migrate.prtId) return cohorts;
return cohorts.filter((cohort) => cohort.virtualPrt?.id === migrate.prtId);
}, [cohorts, migrate.prtId]);
const closeReceipt = () => {
if (receipt.blob && receipt.url) URL.revokeObjectURL(receipt.url);
setReceipt({ url: '', title: '', loading: false, blob: false });
@ -326,6 +338,36 @@ export default function OnboardingPage() {
))}
</select>
</form>
<Button
type="button"
variant="outline-primary"
className="flex-shrink-0"
onClick={() => {
const params = new URLSearchParams();
if (query) params.set('search', query);
if (list) params.set('list', list);
if (paymentStatus) params.set('paymentStatus', paymentStatus);
if (category) params.set('diseaseType', category);
if (addedBy) params.set('onboardedBy', addedBy);
const suffix = params.toString() ? `?${params}` : '';
fetch(`/api/onboarding/export${suffix}`, { credentials: 'include' })
.then((res) => {
if (!res.ok) throw new Error('Could not export patients.');
return res.blob();
})
.then((blob) => {
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = 'patients.csv';
link.click();
URL.revokeObjectURL(url);
})
.catch((err) => window.alert(err.message));
}}
>
Export CSV
</Button>
{can('onboarding', 'add') ? (
<Link className="btn btn-success flex-shrink-0" to="/onboarding/new">
<TbPlus className="me-1" /> Add patient
@ -416,10 +458,27 @@ export default function OnboardingPage() {
<ModalHeader closeButton><h5 className="modal-title">Move patient</h5></ModalHeader>
<ModalBody>
{migrate.error ? <div className="alert alert-danger">{migrate.error}</div> : null}
<label className="form-label">Virtual PRT</label>
<select
className="form-select mb-3"
value={migrate.prtId}
onChange={(e) => {
const prtId = e.target.value;
setMigrate((current) => {
const kept = !prtId || cohorts.some((cohort) => cohort.id === current.cohortId && cohort.virtualPrt?.id === prtId);
return { ...current, prtId, cohortId: kept ? current.cohortId : '', warnings: [], error: '' };
});
}}
>
<option value="">All Virtual PRTs</option>
{prts.map((prt) => <option key={prt.id} value={prt.id}>{prtName(prt)}</option>)}
</select>
<label className="form-label">Target cohort</label>
<select className="form-select" value={migrate.cohortId} onChange={(e) => setMigrate((current) => ({ ...current, cohortId: e.target.value, warnings: [], error: '' }))}>
<option value="">Select cohort</option>
{cohorts.map((cohort) => <option key={cohort.id} value={cohort.id}>{cohort.name}</option>)}
{moveCohorts.map((cohort) => (
<option key={cohort.id} value={cohort.id}>{cohort.name}{prtName(cohort.virtualPrt) ? ` · ${prtName(cohort.virtualPrt)}` : ''}</option>
))}
</select>
<div className="form-text">The patient takes this cohort's slot, day and PRT.</div>
{migrate.warnings.length ? (

View File

@ -41,6 +41,7 @@ export default function ProgramSessionsPage() {
<thead>
<tr>
<th>Date</th>
<th>PRT</th>
<th>Cohort</th>
<th>Slot</th>
<th>Status</th>
@ -52,6 +53,7 @@ export default function ProgramSessionsPage() {
{items.map((session) => (
<tr key={session.id}>
<td>{showDate(session.date)} #{session.index}</td>
<td>{[session.cohort?.virtualPrt?.firstName, session.cohort?.virtualPrt?.lastName].filter(Boolean).join(' ') || '—'}</td>
<td>{session.cohort?.name || '—'}</td>
<td>{session.slot}</td>
<td className="text-capitalize">{session.status}</td>
@ -89,7 +91,7 @@ export default function ProgramSessionsPage() {
</td>
</tr>
))}
{!items.length ? <tr><td colSpan={6} className="text-muted">No sessions this week.</td></tr> : null}
{!items.length ? <tr><td colSpan={7} className="text-muted">No sessions this week.</td></tr> : null}
</tbody>
</Table>
</CardBody>