fixed wrong session creates and cohorts name add

This commit is contained in:
Abhijit 2026-11-23 16:54:59 +05:30
parent a49f3267b9
commit 68dfb72384
5 changed files with 124 additions and 75 deletions

View File

@ -207,7 +207,7 @@ export function cohortRoutes(server) {
} catch (err) { } catch (err) {
throw Boom.badRequest(err.message); throw Boom.badRequest(err.message);
} }
const name = buildCohortName({ slot, language, startDate }); const name = String(request.payload.name || '').trim() || buildCohortName({ slot, language, startDate });
let createdIds = []; let createdIds = [];
const cohort = await Cohort.create({ const cohort = await Cohort.create({
name, name,
@ -328,7 +328,7 @@ export function cohortRoutes(server) {
} catch (err) { } catch (err) {
throw Boom.badRequest(err.message); throw Boom.badRequest(err.message);
} }
cohort.name = buildCohortName({ slot, language, startDate }); cohort.name = String(request.payload.name || '').trim() || buildCohortName({ slot, language, startDate });
cohort.startDate = ymdToDate(startDate); cohort.startDate = ymdToDate(startDate);
cohort.slot = slot; cohort.slot = slot;
cohort.language = language; cohort.language = language;

View File

@ -16,6 +16,7 @@ import {
toYmd, toYmd,
todayYmd, todayYmd,
upcomingSessionDates, upcomingSessionDates,
intervalWeekdays,
scheduleSessionCount, scheduleSessionCount,
scheduleWeekdays, scheduleWeekdays,
weekdayOf, weekdayOf,
@ -296,15 +297,16 @@ export async function ensureSessionRecords(cohort) {
const ALL_WEEKDAYS = [1, 2, 3, 4, 5, 6]; const ALL_WEEKDAYS = [1, 2, 3, 4, 5, 6];
// Days this cohort meets. An extra schedule wins. All weekdays is Monday–Saturday. Otherwise the repeat interval. // Days this cohort meets. Extra schedule wins; all-weekdays is Mon–Sat; Normal uses fixed interval days from start.
export async function meetingWeekdays(cohort) { export async function meetingWeekdays(cohort) {
const scheduled = await scheduleWeekdays(cohort?.scheduleId); const scheduled = await scheduleWeekdays(cohort?.scheduleId);
if (scheduled) return scheduled; if (scheduled) return scheduled;
if (cohort?.sixDayWeek) return ALL_WEEKDAYS; if (cohort?.sixDayWeek) return ALL_WEEKDAYS;
return null; const settings = await getAppSettings();
return intervalWeekdays(toYmd(cohort?.startDate), settings.repeatIntervalDays);
} }
// Next date for an extra schedule, skipping unticked days, Sunday, holiday, and leave. // Next meeting day on the cohort's weekday set, skipping Sunday, holiday, and leave.
async function nextWeekdayAppendDate(cohort, weekdays) { async function nextWeekdayAppendDate(cohort, weekdays) {
const settings = await getAppSettings(); const settings = await getAppSettings();
const allowed = new Set(weekdays.map(Number)); const allowed = new Set(weekdays.map(Number));
@ -326,27 +328,10 @@ async function nextWeekdayAppendDate(cohort, weekdays) {
return cursor; return cursor;
} }
// Next date after the last session. A schedule or all-weekdays uses those days. Otherwise the repeat interval. // Next date after the last session on this cohort's meeting days.
export async function nextAppendDate(cohort) { export async function nextAppendDate(cohort) {
const weekdays = await meetingWeekdays(cohort); const weekdays = await meetingWeekdays(cohort);
if (weekdays) return nextWeekdayAppendDate(cohort, weekdays); return nextWeekdayAppendDate(cohort, weekdays.length ? weekdays : ALL_WEEKDAYS);
const settings = await getAppSettings();
const interval = Math.max(1, Number(settings.repeatIntervalDays) || 2);
const last = await CohortSession.findOne({ cohort: cohort._id }).sort({ date: -1, index: -1 });
let cursor = last?.date ? addDays(last.date, interval) : toYmd(cohort.startDate);
const horizon = addDays(cursor, interval * 80);
const holidays = settings.skipHolidays !== false
? await holidayDatesBetween(cursor, horizon, cohort.language)
: new Set();
const prtId = cohort.virtualPrt?._id || cohort.virtualPrt;
for (let guard = 0; guard < 400; guard += 1) {
const sundayBlocked = weekdayOf(cursor) === 0;
const holidayBlocked = settings.skipHolidays !== false && holidays.has(cursor);
const leaveBlocked = settings.skipPrtLeave !== false && await leaveCoversDate(prtId, cursor);
if (!sundayBlocked && !holidayBlocked && !leaveBlocked) return cursor;
cursor = addDays(cursor, interval);
}
return cursor;
} }
// True when the cohort may meet on this date: its meeting days if set, never Sunday, and not a holiday or PRT leave. // True when the cohort may meet on this date: its meeting days if set, never Sunday, and not a holiday or PRT leave.

View File

@ -148,16 +148,28 @@ export function slotDateTimes(date, slot, durationMinutes = 60) {
return { startTime, endTime, start, end }; return { startTime, endTime, start, end };
} }
// True when the date is on the Normal interval and is not Sunday, a holiday, or leave. // Fixed Mon–Sat meeting days for Normal interval. Start Tue + interval 2 → Tue/Thu/Sat every week.
export function intervalWeekdays(startYmd, interval = 2) {
const startDow = weekdayOf(startYmd);
if (!startYmd || startDow === 0) return [];
const step = Math.max(1, Number(interval) || 2);
const days = [];
let day = startDow;
for (let guard = 0; guard < 6; guard += 1) {
days.push(day);
day = ((day - 1 + step) % 6) + 1; // step on Mon–Sat only, never Sunday
if (day === startDow) break;
}
return days.sort((a, b) => a - b);
}
// True when the date is on the Normal weekday set and is not Sunday, a holiday, or leave.
export async function isCohortSessionOn(startYmd, virtualPrtId, targetYmd, language) { export async function isCohortSessionOn(startYmd, virtualPrtId, targetYmd, language) {
if (!startYmd || !targetYmd || targetYmd < startYmd) return false; if (!startYmd || !targetYmd || targetYmd < startYmd) return false;
if (weekdayOf(targetYmd) === 0) return false; if (weekdayOf(targetYmd) === 0) return false;
const settings = await getAppSettings(); const settings = await getAppSettings();
const interval = Math.max(1, Number(settings.repeatIntervalDays) || 2); const allowed = intervalWeekdays(startYmd, settings.repeatIntervalDays);
const start = parseYmd(startYmd); if (!allowed.includes(weekdayOf(targetYmd))) return false;
const target = parseYmd(targetYmd);
const diff = Math.round((target - start) / 86400000);
if (diff < 0 || diff % interval !== 0) return false;
if (settings.skipHolidays !== false) { if (settings.skipHolidays !== false) {
const holidays = await holidayDatesBetween(targetYmd, targetYmd, language); const holidays = await holidayDatesBetween(targetYmd, targetYmd, language);
if (holidays.has(targetYmd)) return false; if (holidays.has(targetYmd)) return false;
@ -168,24 +180,26 @@ export async function isCohortSessionOn(startYmd, virtualPrtId, targetYmd, langu
const RRULE_DAYS = ['SU', 'MO', 'TU', 'WE', 'TH', 'FR', 'SA']; const RRULE_DAYS = ['SU', 'MO', 'TU', 'WE', 'TH', 'FR', 'SA'];
// Builds meeting dates. Normal uses the interval. An extra schedule uses its weekdays. Sunday, holiday, and leave are skipped. // Builds meeting dates from weekdays (or Normal interval days from start). Sunday, holiday, and leave are skipped.
export async function upcomingSessionDates(startYmd, virtualPrtId, count, language, weekdays = null) { export async function upcomingSessionDates(startYmd, virtualPrtId, count, language, weekdays = null) {
const settings = await getAppSettings(); const settings = await getAppSettings();
const needed = Math.min(Math.max(Number(count) || settings.upcomingSessionCount || 30, 1), 60); const needed = Math.min(Math.max(Number(count) || settings.upcomingSessionCount || 30, 1), 60);
const allowed = Array.isArray(weekdays) && weekdays.length ? new Set(weekdays.map(Number)) : null; const days = Array.isArray(weekdays) && weekdays.length
const interval = allowed ? 1 : Math.max(1, Number(settings.repeatIntervalDays) || 2); ? weekdays.map(Number)
const horizon = addDays(startYmd, needed * interval * 8); : intervalWeekdays(startYmd, settings.repeatIntervalDays);
const allowed = new Set(days.filter((day) => day >= 1 && day <= 6));
const horizon = addDays(startYmd, needed * 8);
const holidays = settings.skipHolidays !== false ? await holidayDatesBetween(startYmd, horizon, language) : new Set(); const holidays = settings.skipHolidays !== false ? await holidayDatesBetween(startYmd, horizon, language) : new Set();
const dates = []; const dates = [];
let cursor = startYmd; let cursor = startYmd;
let guard = 0; let guard = 0;
while (dates.length < needed && guard < 400) { while (dates.length < needed && guard < 400) {
const sundayBlocked = weekdayOf(cursor) === 0; const sundayBlocked = weekdayOf(cursor) === 0;
const weekdayBlocked = allowed ? !allowed.has(weekdayOf(cursor)) : false; const weekdayBlocked = allowed.size ? !allowed.has(weekdayOf(cursor)) : false;
const holidayBlocked = settings.skipHolidays !== false && holidays.has(cursor); const holidayBlocked = settings.skipHolidays !== false && holidays.has(cursor);
const leaveBlocked = settings.skipPrtLeave !== false && await leaveCoversDate(virtualPrtId, cursor); const leaveBlocked = settings.skipPrtLeave !== false && await leaveCoversDate(virtualPrtId, cursor);
if (!weekdayBlocked && !sundayBlocked && !holidayBlocked && !leaveBlocked) dates.push(cursor); if (!weekdayBlocked && !sundayBlocked && !holidayBlocked && !leaveBlocked) dates.push(cursor);
cursor = addDays(cursor, interval); cursor = addDays(cursor, 1);
guard += 1; guard += 1;
} }
return dates; return dates;

View File

@ -57,6 +57,7 @@ export default function CohortForm() {
const [saving, setSaving] = useState(false); const [saving, setSaving] = useState(false);
const [statusValue, setStatusValue] = useState(null); const [statusValue, setStatusValue] = useState(null);
const [statusWarnings, setStatusWarnings] = useState([]); const [statusWarnings, setStatusWarnings] = useState([]);
const [nameCustom, setNameCustom] = useState(false); // true after the user edits the auto name
const { settings } = useSettings(); const { settings } = useSettings();
const startWeekdays = settings?.cohortStartWeekdays || [1, 2]; const startWeekdays = settings?.cohortStartWeekdays || [1, 2];
const schedules = settings?.cohortSchedules || []; const schedules = settings?.cohortSchedules || [];
@ -83,9 +84,11 @@ export default function CohortForm() {
let active = true; let active = true;
api(`/api/cohorts/${id}`).then((c) => { api(`/api/cohorts/${id}`).then((c) => {
if (!active) return; if (!active) return;
const startDate = c.startDate ? String(c.startDate).slice(0, 10) : '';
const autoName = buildCohortName({ slot: c.slot || '', language: c.language || '', startDate });
setForm({ setForm({
name: c.name || '', name: c.name || '',
startDate: c.startDate ? String(c.startDate).slice(0, 10) : '', startDate,
slot: c.slot || '', slot: c.slot || '',
virtualPrt: c.virtualPrt?.id || '', virtualPrt: c.virtualPrt?.id || '',
language: c.language || '', language: c.language || '',
@ -93,6 +96,7 @@ export default function CohortForm() {
scheduleId: c.scheduleId || '', scheduleId: c.scheduleId || '',
patients: (c.patients || []).map((p) => p.id), patients: (c.patients || []).map((p) => p.id),
}); });
setNameCustom(Boolean(c.name && c.name !== autoName));
setSelectedDetails((c.patients || []).map((p) => ({ id: p.id, name: p.name, mobile: p.mobile, whatsappOptOut: p.whatsappOptOut }))); setSelectedDetails((c.patients || []).map((p) => ({ id: p.id, name: p.name, mobile: p.mobile, whatsappOptOut: p.whatsappOptOut })));
setStatusValue(cohortStatusValue(c)); setStatusValue(cohortStatusValue(c));
// setSessionSummary({ completed: c.sessionsCompleted || 0, planned: c.sessionsPlanned || 0 }); // setSessionSummary({ completed: c.sessionsCompleted || 0, planned: c.sessionsPlanned || 0 });
@ -124,12 +128,12 @@ export default function CohortForm() {
language, language,
startDate: form.startDate, startDate: form.startDate,
}); });
setForm((current) => ( setForm((current) => {
current.name === name && current.language === language const next = { ...current, language };
? current if (!nameCustom) next.name = name;
: { ...current, name, language } return current.name === next.name && current.language === next.language ? current : next;
)); });
}, [form.slot, form.startDate, form.virtualPrt, form.language, prts]); }, [form.slot, form.startDate, form.virtualPrt, form.language, prts, nameCustom]);
const visiblePatients = useMemo(() => { const visiblePatients = useMemo(() => {
const seen = new Set(); const seen = new Set();
@ -218,10 +222,25 @@ export default function CohortForm() {
</p> </p>
<form onSubmit={save}> <form onSubmit={save}>
<Row className="g-3"> <Row className="g-3">
<Col md={6}> <Col md={3}>
<FormLabel>Cohort name</FormLabel> <FormLabel>Cohort name</FormLabel>
<FormControl value={form.name} readOnly plaintext={false} placeholder="Created from slot, PRT language, and start day" /> <FormControl
<div className="form-text">Auto-created as timeslot - language weekday.</div> value={form.name}
onChange={(e) => {
setNameCustom(true);
setForm((f) => ({ ...f, name: e.target.value }));
}}
onBlur={() => {
if (form.name.trim()) return;
setNameCustom(false); // empty on leave → restore auto name from slot / language / date
}}
placeholder="Created from slot, language, and start day"
/>
<div className="form-text">
{nameCustom
? 'Custom name — saved as typed. Clear the field and leave it to restore the default.'
: 'Auto-filled from timeslot, language, and start day. Edit to set a custom name.'}
</div>
</Col> </Col>
<Col md={3}> <Col md={3}>
<FormLabel>Schedule</FormLabel> <FormLabel>Schedule</FormLabel>
@ -256,7 +275,7 @@ export default function CohortForm() {
/> />
</Col> </Col>
{isEdit && statusValue && statusValue.original !== 'proposed' ? ( {isEdit && statusValue && statusValue.original !== 'proposed' ? (
<Col md={6}> <Col md={3}>
<CohortStatusField cohortId={id} value={statusValue} onChange={setStatusValue} /> <CohortStatusField cohortId={id} value={statusValue} onChange={setStatusValue} />
</Col> </Col>
) : null} ) : null}
@ -275,7 +294,7 @@ export default function CohortForm() {
))} ))}
</select> </select>
</Col> </Col>
<Col md={6}> <Col md={3}>
<FormLabel>Category</FormLabel> <FormLabel>Category</FormLabel>
<select className="form-select" value={form.diseaseType} onChange={(e) => setForm((f) => ({ ...f, diseaseType: e.target.value }))}> <select className="form-select" value={form.diseaseType} onChange={(e) => setForm((f) => ({ ...f, diseaseType: e.target.value }))}>
<option value="">Any / not set</option> <option value="">Any / not set</option>
@ -284,7 +303,7 @@ export default function CohortForm() {
))} ))}
</select> </select>
</Col> </Col>
<Col md={6}> <Col md={3}>
<FormLabel>Language</FormLabel> <FormLabel>Language</FormLabel>
<select <select
className="form-select" className="form-select"

View File

@ -9,7 +9,7 @@ import PageBreadcrumb from '@/components/PageBreadcrumb';
import SlotSelect from '@/components/SlotSelect'; import SlotSelect from '@/components/SlotSelect';
import { useAuth } from '@/context/useAuthContext'; import { useAuth } from '@/context/useAuthContext';
// import { formatInterval, useSettings } from '@/hooks/useSettings'; // formatInterval was only for the session preview // import { formatInterval, useSettings } from '@/hooks/useSettings'; // formatInterval was only for the session preview
import { useSettings } from '@/hooks/useSettings'; import { buildCohortName, useSettings } from '@/hooks/useSettings';
import { api } from '@/lib/api'; import { api } from '@/lib/api';
import CohortStatusField, { CohortStatusConfirm, cohortStatusError, cohortStatusValue, cohortStatusWarnings, saveCohortStatus } from '@/components/CohortStatusField'; import CohortStatusField, { CohortStatusConfirm, cohortStatusError, cohortStatusValue, cohortStatusWarnings, saveCohortStatus } from '@/components/CohortStatusField';
import { isMobileNumber, mobileDigits } from '@/lib/mobile'; import { isMobileNumber, mobileDigits } from '@/lib/mobile';
@ -72,6 +72,8 @@ export default function PrtCohortForm() {
const [startDate, setStartDate] = useState(''); const [startDate, setStartDate] = useState('');
const [language, setLanguage] = useState(''); const [language, setLanguage] = useState('');
const [diseaseType, setDiseaseType] = useState(''); const [diseaseType, setDiseaseType] = useState('');
const [name, setName] = useState('');
const [nameCustom, setNameCustom] = useState(false); // true after the user edits the auto name
const [rows, setRows] = useState([]); const [rows, setRows] = useState([]);
const [error, setError] = useState(''); const [error, setError] = useState('');
const [saving, setSaving] = useState(false); const [saving, setSaving] = useState(false);
@ -104,10 +106,14 @@ export default function PrtCohortForm() {
let active = true; let active = true;
api(`/api/cohorts/${id}`).then((cohort) => { api(`/api/cohorts/${id}`).then((cohort) => {
if (!active) return; if (!active) return;
const start = cohort.startDate ? String(cohort.startDate).slice(0, 10) : '';
const autoName = buildCohortName({ slot: cohort.slot || '', language: cohort.language || '', startDate: start });
setSlot(cohort.slot || ''); setSlot(cohort.slot || '');
setStartDate(cohort.startDate ? String(cohort.startDate).slice(0, 10) : ''); setStartDate(start);
setLanguage(cohort.language || ''); setLanguage(cohort.language || '');
setDiseaseType(cohort.diseaseType || ''); setDiseaseType(cohort.diseaseType || '');
setName(cohort.name || '');
setNameCustom(Boolean(cohort.name && cohort.name !== autoName));
setVirtualPrt(cohort.virtualPrt?.id || ''); setVirtualPrt(cohort.virtualPrt?.id || '');
setSixDayWeek(cohort.sixDayWeek ? 'yes' : 'no'); setSixDayWeek(cohort.sixDayWeek ? 'yes' : 'no');
setStatusValue(cohortStatusValue(cohort)); setStatusValue(cohortStatusValue(cohort));
@ -134,6 +140,11 @@ export default function PrtCohortForm() {
return () => { active = false; }; return () => { active = false; };
}, [id, isEdit]); }, [id, isEdit]);
useEffect(() => {
if (nameCustom) return;
setName(buildCohortName({ slot, language: chosenLanguage, startDate }));
}, [slot, startDate, chosenLanguage, nameCustom]);
const chooseSixDay = (value) => { const chooseSixDay = (value) => {
setSixDayWeek(value); setSixDayWeek(value);
if (!startDate) return; if (!startDate) return;
@ -216,6 +227,7 @@ export default function PrtCohortForm() {
} }
setSaving(true); setSaving(true);
const payload = { const payload = {
name: name.trim(),
startDate, startDate,
slot, slot,
virtualPrt: prtId, virtualPrt: prtId,
@ -264,24 +276,26 @@ export default function PrtCohortForm() {
{error ? <div className="alert alert-danger">{error}</div> : null} {error ? <div className="alert alert-danger">{error}</div> : null}
<form onSubmit={save}> <form onSubmit={save}>
<Row className="g-3"> <Row className="g-3">
{!isVirtualPrt ? ( <Col md={3}>
<Col md={6}> <FormLabel>Cohort name</FormLabel>
<FormLabel>Virtual PRT</FormLabel> <FormControl
<select value={name}
className="form-select" onChange={(e) => {
value={virtualPrt} setNameCustom(true);
onChange={(e) => { setVirtualPrt(e.target.value); setLanguage(''); }} setName(e.target.value);
required }}
> onBlur={() => {
<option value="">Select PRT</option> if (name.trim()) return;
{prts.map((item) => ( setNameCustom(false); // empty on leave → restore auto name from slot / language / date
<option key={item.id} value={item.id}> }}
{item.firstName} {item.lastName}{prtLanguages(item).length ? ` (${prtLanguages(item).join(', ')})` : ''} placeholder="Created from slot, language, and start day"
</option> />
))} <div className="form-text">
</select> {nameCustom
</Col> ? 'Custom name — saved as typed. Clear the field and leave it to restore the default.'
) : null} : 'Auto-filled from timeslot, language, and start day. Edit to set a custom name.'}
</div>
</Col>
<Col md={3}> <Col md={3}>
<FormLabel>Slot</FormLabel> <FormLabel>Slot</FormLabel>
<SlotSelect value={slot} onChange={setSlot} required /> <SlotSelect value={slot} onChange={setSlot} required />
@ -318,13 +332,25 @@ export default function PrtCohortForm() {
placeholder={sixDayWeek === 'yes' ? 'Any day except Sunday' : (sixDayWeek === 'no' ? 'Monday or Tuesday' : 'Choose all weekdays first')} placeholder={sixDayWeek === 'yes' ? 'Any day except Sunday' : (sixDayWeek === 'no' ? 'Monday or Tuesday' : 'Choose all weekdays first')}
/> />
</Col> </Col>
{isEdit && statusValue && statusValue.original !== 'proposed' ? ( {!isVirtualPrt ? (
<Col md={6}> <Col md={3}>
<CohortStatusField cohortId={id} value={statusValue} onChange={setStatusValue} /> <FormLabel>Virtual PRT</FormLabel>
<select
className="form-select"
value={virtualPrt}
onChange={(e) => { setVirtualPrt(e.target.value); setLanguage(''); }}
required
>
<option value="">Select PRT</option>
{prts.map((item) => (
<option key={item.id} value={item.id}>
{item.firstName} {item.lastName}{prtLanguages(item).length ? ` (${prtLanguages(item).join(', ')})` : ''}
</option>
))}
</select>
</Col> </Col>
) : null} ) : null}
<div className="w-100" /> <Col md={3}>
<Col md={6}>
<FormLabel>Category</FormLabel> <FormLabel>Category</FormLabel>
<select className="form-select" value={diseaseType} onChange={(e) => setDiseaseType(e.target.value)}> <select className="form-select" value={diseaseType} onChange={(e) => setDiseaseType(e.target.value)}>
<option value="">Any / not set</option> <option value="">Any / not set</option>
@ -333,7 +359,7 @@ export default function PrtCohortForm() {
))} ))}
</select> </select>
</Col> </Col>
<Col md={6}> <Col md={3}>
<FormLabel>Language</FormLabel> <FormLabel>Language</FormLabel>
<select <select
className="form-select" className="form-select"
@ -350,6 +376,11 @@ export default function PrtCohortForm() {
))} ))}
</select> </select>
</Col> </Col>
{isEdit && statusValue && statusValue.original !== 'proposed' ? (
<Col md={3}>
<CohortStatusField cohortId={id} value={statusValue} onChange={setStatusValue} />
</Col>
) : null}
<Col xs={12}> <Col xs={12}>
<div className="d-flex justify-content-between align-items-center mb-2"> <div className="d-flex justify-content-between align-items-center mb-2">
<FormLabel className="mb-0">Patients</FormLabel> <FormLabel className="mb-0">Patients</FormLabel>