fixed wrong session creates and cohorts name add
This commit is contained in:
parent
a49f3267b9
commit
68dfb72384
|
|
@ -207,7 +207,7 @@ export function cohortRoutes(server) {
|
|||
} catch (err) {
|
||||
throw Boom.badRequest(err.message);
|
||||
}
|
||||
const name = buildCohortName({ slot, language, startDate });
|
||||
const name = String(request.payload.name || '').trim() || buildCohortName({ slot, language, startDate });
|
||||
let createdIds = [];
|
||||
const cohort = await Cohort.create({
|
||||
name,
|
||||
|
|
@ -328,7 +328,7 @@ export function cohortRoutes(server) {
|
|||
} catch (err) {
|
||||
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.slot = slot;
|
||||
cohort.language = language;
|
||||
|
|
|
|||
|
|
@ -16,6 +16,7 @@ import {
|
|||
toYmd,
|
||||
todayYmd,
|
||||
upcomingSessionDates,
|
||||
intervalWeekdays,
|
||||
scheduleSessionCount,
|
||||
scheduleWeekdays,
|
||||
weekdayOf,
|
||||
|
|
@ -296,15 +297,16 @@ export async function ensureSessionRecords(cohort) {
|
|||
|
||||
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) {
|
||||
const scheduled = await scheduleWeekdays(cohort?.scheduleId);
|
||||
if (scheduled) return scheduled;
|
||||
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) {
|
||||
const settings = await getAppSettings();
|
||||
const allowed = new Set(weekdays.map(Number));
|
||||
|
|
@ -326,27 +328,10 @@ async function nextWeekdayAppendDate(cohort, weekdays) {
|
|||
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) {
|
||||
const weekdays = await meetingWeekdays(cohort);
|
||||
if (weekdays) return nextWeekdayAppendDate(cohort, 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;
|
||||
return nextWeekdayAppendDate(cohort, weekdays.length ? weekdays : ALL_WEEKDAYS);
|
||||
}
|
||||
|
||||
// True when the cohort may meet on this date: its meeting days if set, never Sunday, and not a holiday or PRT leave.
|
||||
|
|
|
|||
|
|
@ -148,16 +148,28 @@ export function slotDateTimes(date, slot, durationMinutes = 60) {
|
|||
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) {
|
||||
if (!startYmd || !targetYmd || targetYmd < startYmd) return false;
|
||||
if (weekdayOf(targetYmd) === 0) return false;
|
||||
const settings = await getAppSettings();
|
||||
const interval = Math.max(1, Number(settings.repeatIntervalDays) || 2);
|
||||
const start = parseYmd(startYmd);
|
||||
const target = parseYmd(targetYmd);
|
||||
const diff = Math.round((target - start) / 86400000);
|
||||
if (diff < 0 || diff % interval !== 0) return false;
|
||||
const allowed = intervalWeekdays(startYmd, settings.repeatIntervalDays);
|
||||
if (!allowed.includes(weekdayOf(targetYmd))) return false;
|
||||
if (settings.skipHolidays !== false) {
|
||||
const holidays = await holidayDatesBetween(targetYmd, targetYmd, language);
|
||||
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'];
|
||||
|
||||
// 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) {
|
||||
const settings = await getAppSettings();
|
||||
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 interval = allowed ? 1 : Math.max(1, Number(settings.repeatIntervalDays) || 2);
|
||||
const horizon = addDays(startYmd, needed * interval * 8);
|
||||
const days = Array.isArray(weekdays) && weekdays.length
|
||||
? weekdays.map(Number)
|
||||
: 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 dates = [];
|
||||
let cursor = startYmd;
|
||||
let guard = 0;
|
||||
while (dates.length < needed && guard < 400) {
|
||||
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 leaveBlocked = settings.skipPrtLeave !== false && await leaveCoversDate(virtualPrtId, cursor);
|
||||
if (!weekdayBlocked && !sundayBlocked && !holidayBlocked && !leaveBlocked) dates.push(cursor);
|
||||
cursor = addDays(cursor, interval);
|
||||
cursor = addDays(cursor, 1);
|
||||
guard += 1;
|
||||
}
|
||||
return dates;
|
||||
|
|
|
|||
|
|
@ -57,6 +57,7 @@ export default function CohortForm() {
|
|||
const [saving, setSaving] = useState(false);
|
||||
const [statusValue, setStatusValue] = useState(null);
|
||||
const [statusWarnings, setStatusWarnings] = useState([]);
|
||||
const [nameCustom, setNameCustom] = useState(false); // true after the user edits the auto name
|
||||
const { settings } = useSettings();
|
||||
const startWeekdays = settings?.cohortStartWeekdays || [1, 2];
|
||||
const schedules = settings?.cohortSchedules || [];
|
||||
|
|
@ -83,9 +84,11 @@ export default function CohortForm() {
|
|||
let active = true;
|
||||
api(`/api/cohorts/${id}`).then((c) => {
|
||||
if (!active) return;
|
||||
const startDate = c.startDate ? String(c.startDate).slice(0, 10) : '';
|
||||
const autoName = buildCohortName({ slot: c.slot || '', language: c.language || '', startDate });
|
||||
setForm({
|
||||
name: c.name || '',
|
||||
startDate: c.startDate ? String(c.startDate).slice(0, 10) : '',
|
||||
startDate,
|
||||
slot: c.slot || '',
|
||||
virtualPrt: c.virtualPrt?.id || '',
|
||||
language: c.language || '',
|
||||
|
|
@ -93,6 +96,7 @@ export default function CohortForm() {
|
|||
scheduleId: c.scheduleId || '',
|
||||
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 })));
|
||||
setStatusValue(cohortStatusValue(c));
|
||||
// setSessionSummary({ completed: c.sessionsCompleted || 0, planned: c.sessionsPlanned || 0 });
|
||||
|
|
@ -124,12 +128,12 @@ export default function CohortForm() {
|
|||
language,
|
||||
startDate: form.startDate,
|
||||
});
|
||||
setForm((current) => (
|
||||
current.name === name && current.language === language
|
||||
? current
|
||||
: { ...current, name, language }
|
||||
));
|
||||
}, [form.slot, form.startDate, form.virtualPrt, form.language, prts]);
|
||||
setForm((current) => {
|
||||
const next = { ...current, language };
|
||||
if (!nameCustom) next.name = name;
|
||||
return current.name === next.name && current.language === next.language ? current : next;
|
||||
});
|
||||
}, [form.slot, form.startDate, form.virtualPrt, form.language, prts, nameCustom]);
|
||||
|
||||
const visiblePatients = useMemo(() => {
|
||||
const seen = new Set();
|
||||
|
|
@ -218,10 +222,25 @@ export default function CohortForm() {
|
|||
</p>
|
||||
<form onSubmit={save}>
|
||||
<Row className="g-3">
|
||||
<Col md={6}>
|
||||
<Col md={3}>
|
||||
<FormLabel>Cohort name</FormLabel>
|
||||
<FormControl value={form.name} readOnly plaintext={false} placeholder="Created from slot, PRT language, and start day" />
|
||||
<div className="form-text">Auto-created as timeslot - language weekday.</div>
|
||||
<FormControl
|
||||
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 md={3}>
|
||||
<FormLabel>Schedule</FormLabel>
|
||||
|
|
@ -256,7 +275,7 @@ export default function CohortForm() {
|
|||
/>
|
||||
</Col>
|
||||
{isEdit && statusValue && statusValue.original !== 'proposed' ? (
|
||||
<Col md={6}>
|
||||
<Col md={3}>
|
||||
<CohortStatusField cohortId={id} value={statusValue} onChange={setStatusValue} />
|
||||
</Col>
|
||||
) : null}
|
||||
|
|
@ -275,7 +294,7 @@ export default function CohortForm() {
|
|||
))}
|
||||
</select>
|
||||
</Col>
|
||||
<Col md={6}>
|
||||
<Col md={3}>
|
||||
<FormLabel>Category</FormLabel>
|
||||
<select className="form-select" value={form.diseaseType} onChange={(e) => setForm((f) => ({ ...f, diseaseType: e.target.value }))}>
|
||||
<option value="">Any / not set</option>
|
||||
|
|
@ -284,7 +303,7 @@ export default function CohortForm() {
|
|||
))}
|
||||
</select>
|
||||
</Col>
|
||||
<Col md={6}>
|
||||
<Col md={3}>
|
||||
<FormLabel>Language</FormLabel>
|
||||
<select
|
||||
className="form-select"
|
||||
|
|
|
|||
|
|
@ -9,7 +9,7 @@ import PageBreadcrumb from '@/components/PageBreadcrumb';
|
|||
import SlotSelect from '@/components/SlotSelect';
|
||||
import { useAuth } from '@/context/useAuthContext';
|
||||
// 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 CohortStatusField, { CohortStatusConfirm, cohortStatusError, cohortStatusValue, cohortStatusWarnings, saveCohortStatus } from '@/components/CohortStatusField';
|
||||
import { isMobileNumber, mobileDigits } from '@/lib/mobile';
|
||||
|
|
@ -72,6 +72,8 @@ export default function PrtCohortForm() {
|
|||
const [startDate, setStartDate] = useState('');
|
||||
const [language, setLanguage] = 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 [error, setError] = useState('');
|
||||
const [saving, setSaving] = useState(false);
|
||||
|
|
@ -104,10 +106,14 @@ export default function PrtCohortForm() {
|
|||
let active = true;
|
||||
api(`/api/cohorts/${id}`).then((cohort) => {
|
||||
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 || '');
|
||||
setStartDate(cohort.startDate ? String(cohort.startDate).slice(0, 10) : '');
|
||||
setStartDate(start);
|
||||
setLanguage(cohort.language || '');
|
||||
setDiseaseType(cohort.diseaseType || '');
|
||||
setName(cohort.name || '');
|
||||
setNameCustom(Boolean(cohort.name && cohort.name !== autoName));
|
||||
setVirtualPrt(cohort.virtualPrt?.id || '');
|
||||
setSixDayWeek(cohort.sixDayWeek ? 'yes' : 'no');
|
||||
setStatusValue(cohortStatusValue(cohort));
|
||||
|
|
@ -134,6 +140,11 @@ export default function PrtCohortForm() {
|
|||
return () => { active = false; };
|
||||
}, [id, isEdit]);
|
||||
|
||||
useEffect(() => {
|
||||
if (nameCustom) return;
|
||||
setName(buildCohortName({ slot, language: chosenLanguage, startDate }));
|
||||
}, [slot, startDate, chosenLanguage, nameCustom]);
|
||||
|
||||
const chooseSixDay = (value) => {
|
||||
setSixDayWeek(value);
|
||||
if (!startDate) return;
|
||||
|
|
@ -216,6 +227,7 @@ export default function PrtCohortForm() {
|
|||
}
|
||||
setSaving(true);
|
||||
const payload = {
|
||||
name: name.trim(),
|
||||
startDate,
|
||||
slot,
|
||||
virtualPrt: prtId,
|
||||
|
|
@ -264,24 +276,26 @@ export default function PrtCohortForm() {
|
|||
{error ? <div className="alert alert-danger">{error}</div> : null}
|
||||
<form onSubmit={save}>
|
||||
<Row className="g-3">
|
||||
{!isVirtualPrt ? (
|
||||
<Col md={6}>
|
||||
<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>
|
||||
) : null}
|
||||
<Col md={3}>
|
||||
<FormLabel>Cohort name</FormLabel>
|
||||
<FormControl
|
||||
value={name}
|
||||
onChange={(e) => {
|
||||
setNameCustom(true);
|
||||
setName(e.target.value);
|
||||
}}
|
||||
onBlur={() => {
|
||||
if (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 md={3}>
|
||||
<FormLabel>Slot</FormLabel>
|
||||
<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')}
|
||||
/>
|
||||
</Col>
|
||||
{isEdit && statusValue && statusValue.original !== 'proposed' ? (
|
||||
<Col md={6}>
|
||||
<CohortStatusField cohortId={id} value={statusValue} onChange={setStatusValue} />
|
||||
{!isVirtualPrt ? (
|
||||
<Col md={3}>
|
||||
<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>
|
||||
) : null}
|
||||
<div className="w-100" />
|
||||
<Col md={6}>
|
||||
<Col md={3}>
|
||||
<FormLabel>Category</FormLabel>
|
||||
<select className="form-select" value={diseaseType} onChange={(e) => setDiseaseType(e.target.value)}>
|
||||
<option value="">Any / not set</option>
|
||||
|
|
@ -333,7 +359,7 @@ export default function PrtCohortForm() {
|
|||
))}
|
||||
</select>
|
||||
</Col>
|
||||
<Col md={6}>
|
||||
<Col md={3}>
|
||||
<FormLabel>Language</FormLabel>
|
||||
<select
|
||||
className="form-select"
|
||||
|
|
@ -350,6 +376,11 @@ export default function PrtCohortForm() {
|
|||
))}
|
||||
</select>
|
||||
</Col>
|
||||
{isEdit && statusValue && statusValue.original !== 'proposed' ? (
|
||||
<Col md={3}>
|
||||
<CohortStatusField cohortId={id} value={statusValue} onChange={setStatusValue} />
|
||||
</Col>
|
||||
) : null}
|
||||
<Col xs={12}>
|
||||
<div className="d-flex justify-content-between align-items-center mb-2">
|
||||
<FormLabel className="mb-0">Patients</FormLabel>
|
||||
|
|
|
|||
Loading…
Reference in New Issue