diff --git a/client/src/components/ChoreWidget.jsx b/client/src/components/ChoreWidget.jsx index 506e1aa1..8d7ce925 100644 --- a/client/src/components/ChoreWidget.jsx +++ b/client/src/components/ChoreWidget.jsx @@ -24,6 +24,7 @@ import { ListItemText, ListItemIcon, List, + ListItem, ListItemButton, ListItemAvatar, Radio, @@ -41,7 +42,8 @@ import { API_BASE_URL } from '../utils/apiConfig.js'; import { pinErrorText } from '../utils/pinErrors.js'; import { getDeviceApiBase } from '../utils/deviceName.js'; import { fetchPinRemembered, setPinRemembered, shouldPromptForPin } from '../utils/adminPinDevice.js'; -import { shouldShowChoreToday, getTodayDateString, getDueDateStatus, formatDueDate, hasOutstandingBonusChore, canClaimBonusChore, countsTowardDailyBonus, getTransferTargets } from '../utils/choreHelpers.js'; +import { shouldShowChoreToday, getTodayDateString, getDueDateStatus, formatDueDate, hasOutstandingBonusChore, canClaimBonusChore, countsTowardDailyBonus, getTransferTargets, splitStars, splitShareFor, splitShareDoneFor, splitHasTickedShare, isSplitSchedule } from '../utils/choreHelpers.js'; +import { createPressHold } from '../utils/pressHold.js'; import { filterVisibleUsers, toggleHiddenUserId, pruneHiddenUserIds } from '../utils/choreUserVisibility.js'; import { isControlHidden } from '../utils/displayControls.js'; import { subscribePluginEvents } from '../utils/pluginEventBridge.js'; @@ -172,6 +174,13 @@ const ChoreWidget = ({ refreshNonce = 0, hiddenControls = [] }) => { // Long-press / right-click chore menu and its follow-up dialogs (issue #122). const [choreMenu, setChoreMenu] = useState({ position: null, schedule: null }); const [transferDialog, setTransferDialog] = useState({ open: false, schedule: null, targetUserId: null, mode: 'keep', bonus: 1 }); + // Splitting a bonus chore's Stars among several people: long-press a + // bonus card to open the picker, pick at least two people, and each gets + // their share. `result` holds the confirmed split to show in the dialog. + const [splitDialog, setSplitDialog] = useState({ open: false, schedule: null, userIds: [], result: null }); + const splitPressHoldRef = useRef(null); + const splitHoldFiredRef = useRef(false); + const splitDialogOpenedAtRef = useRef(0); const [columnsRef, columnsFadeSx] = useEdgeFade(); const [snoozeDialog, setSnoozeDialog] = useState({ open: false, schedule: null, until: '' }); const [historyDialog, setHistoryDialog] = useState({ open: false, schedule: null }); @@ -204,6 +213,7 @@ const ChoreWidget = ({ refreshNonce = 0, hiddenControls = [] }) => { // at all. const hideAddChore = isControlHidden(hiddenControls, 'core:addChore'); const hideTransferChore = isControlHidden(hiddenControls, 'core:transferChore'); + const hideSplitChore = isControlHidden(hiddenControls, 'core:splitChore'); const hideSnoozeChore = isControlHidden(hiddenControls, 'core:snoozeChore'); const hidePrizeApproval = isControlHidden(hiddenControls, 'core:prizeApproval'); const hideQuickSpend = isControlHidden(hiddenControls, 'core:quickSpend'); @@ -221,6 +231,9 @@ const ChoreWidget = ({ refreshNonce = 0, hiddenControls = [] }) => { if (hideTransferChore) { setTransferDialog((prev) => (prev.open ? { ...prev, open: false } : prev)); } + if (hideSplitChore) { + setSplitDialog((prev) => (prev.open ? { ...prev, open: false } : prev)); + } if (hideSnoozeChore) { setSnoozeDialog((prev) => (prev.open ? { ...prev, open: false } : prev)); } @@ -232,7 +245,7 @@ const ChoreWidget = ({ refreshNonce = 0, hiddenControls = [] }) => { if (hideTransferChore && hideSnoozeChore) { setChoreMenu((prev) => (prev.position ? { position: null, schedule: null } : prev)); } - }, [hideAddChore, hideTransferChore, hideSnoozeChore, hideQuickSpend]); + }, [hideAddChore, hideTransferChore, hideSplitChore, hideSnoozeChore, hideQuickSpend]); useEffect(() => { fetchData(); @@ -741,14 +754,18 @@ const ChoreWidget = ({ refreshNonce = 0, hiddenControls = [] }) => { } // A tap already in flight for this chore: ignore the second one rather // than POSTing twice (the second would 409 and snap the row back). - if (pendingToggles[schedule.id] !== undefined) return; + // A split schedule shows in several columns at once: one person's tap + // must not block another's, so the in-flight tap is keyed by schedule + // AND person. + const pendingKey = `${schedule.id}:${schedule.user_id}`; + if (pendingToggles[pendingKey] !== undefined) return; const today = getTodayDateString(); // Flip the row now; the server round-trip happens behind it. No // full-screen spinner: a checkbox tap should never block the widget. - setPendingToggles((prev) => ({ ...prev, [schedule.id]: !isCompleted })); + setPendingToggles((prev) => ({ ...prev, [pendingKey]: !isCompleted })); const clearPending = () => setPendingToggles((prev) => { const next = { ...prev }; - delete next[schedule.id]; + delete next[pendingKey]; return next; }); try { @@ -817,6 +834,57 @@ const ChoreWidget = ({ refreshNonce = 0, hiddenControls = [] }) => { } }; + // ---- Splitting a bonus chore's Stars ------------------------------------ + // Long-press a bonus card (or right-click it) to open the picker: tick + // the people sharing the chore and each gets their share, the leftover + // Stars going one each to the first people picked. Confirming posts to + // the split route, which keeps the one pool schedule and records the + // split on it — the card then shows in each person's column, and each + // person ticks their own share. The result stays in the dialog — there + // is no toast system on the dashboard — until Done closes it. + const openSplitDialog = (schedule) => { + if (!schedule || hideSplitChore) return; + splitDialogOpenedAtRef.current = Date.now(); + setSplitDialog((prev) => (prev.open ? prev : { open: true, schedule, userIds: [], result: null })); + }; + + const closeSplitDialog = () => setSplitDialog({ open: false, schedule: null, userIds: [], result: null }); + + const toggleBonusSplitUser = (userId) => { + setSplitDialog((prev) => ({ + ...prev, + userIds: prev.userIds.includes(userId) + ? prev.userIds.filter((id) => id !== userId) + : [...prev.userIds, userId], + })); + }; + + const confirmSplit = async () => { + const { schedule, userIds } = splitDialog; + if (!schedule || userIds.length < 2) return; + try { + setIsLoading(true); + const response = await axios.post(`${API_BASE_URL}/api/chore-schedules/${schedule.id}/split-assign`, { userIds }); + const updated = response.data?.schedule; + await fetchData(); + // The split rides on the one schedule: read the shares back from it + // rather than assuming the picker preview, so the dialog shows + // exactly what the server recorded. + const ids = updated?.split_user_ids || userIds; + const shares = updated?.split_shares || splitStars(schedule.clam_value, userIds.length); + const parts = ids.map((id, index) => ({ + username: users.find((u) => u.id === id)?.username || '?', + stars: shares[index], + })); + setSplitDialog((prev) => ({ ...prev, result: { total: schedule.clam_value, parts } })); + } catch (error) { + console.error('Error splitting bonus chore:', error); + alert(error.response?.data?.error || t('chores:bonus.splitFailed')); + } finally { + setIsLoading(false); + } + }; + const reassignChore = async (scheduleId, newUserId, extraFields = {}) => { const schedule = schedules.find(s => s.id === scheduleId); if (!schedule || schedule.user_id === newUserId) { @@ -851,8 +919,14 @@ const ChoreWidget = ({ refreshNonce = 0, hiddenControls = [] }) => { // Control Limits fold in here rather than only at the MenuItem: hiding both // items but still opening the menu leaves an empty popover over the chore, // which reads as a bug and has to be dismissed before anything else works. + // A split with a ticked share is locked (issue #407): moving it would + // pay the ticked share plus the whole chore, so Transfer is hidden + // here as well as at the MenuItem — the server refuses it either way. + // The lock reads the server's split_done_user_ids, so a share ticked + // yesterday still locks it today. const canTransfer = !hideTransferChore && schedule.transferable !== 0 + && !splitHasTickedShare(schedule, history) && getTransferTargets(users, schedule.user_id, '', schedule).length > 0; const canSnooze = !hideSnoozeChore && schedule.can_snooze !== 0; // History is one person's record, so an unassigned bonus chore has none. @@ -925,6 +999,65 @@ const ChoreWidget = ({ refreshNonce = 0, hiddenControls = [] }) => { } }; + // ---- Press-and-hold on a bonus card: the split picker ------------------- + // The chore menu's timer is touch-only (mouse users right-click); a + // bonus card's hold works for touch and mouse alike, so a desktop hold + // reaches the same picker. The pressHold util (utils/pressHold.js) + // cancels on a slide, and the release after a hold is swallowed below + // so it cannot also claim the chore. + const getSplitPressHold = () => { + if (!splitPressHoldRef.current) { + splitPressHoldRef.current = createPressHold({ + onHold: (schedule) => { + splitHoldFiredRef.current = true; + openSplitDialog(schedule); + }, + }); + } + return splitPressHoldRef.current; + }; + + const handleBonusCardPointerDown = (event, schedule) => { + if (hideSplitChore) return; + splitHoldFiredRef.current = false; + getSplitPressHold().down(event.clientX, event.clientY, schedule); + }; + + const handleBonusCardPointerMove = (event) => { + getSplitPressHold().move(event.clientX, event.clientY); + }; + + const handleBonusCardPointerEnd = () => { + getSplitPressHold().up(); + }; + + const handleBonusCardPointerCancel = () => { + getSplitPressHold().cancel(); + }; + + const handleBonusCardContextMenu = (event, schedule) => { + // Hidden means NOT RENDERED: the hold never starts, and right-click + // falls through to the native menu instead of opening the picker. + if (hideSplitChore) return; + // Always suppress the native browser menu on bonus cards so right-click + // (and Android long-press) opens the split picker instead. A + // long-press-generated contextmenu (button 0) follows the hold that + // already opened the picker; the open guard in openSplitDialog drops it. + event.preventDefault(); + if (event.button !== 2) { + splitHoldFiredRef.current = true; + } + openSplitDialog(schedule); + }; + + const handleBonusCardClickCapture = (event) => { + if (splitHoldFiredRef.current) { + event.preventDefault(); + event.stopPropagation(); + splitHoldFiredRef.current = false; + } + }; + // Mirrors the server's daily-bonus rule: a user's day is complete when they // have at least one regular (zero-clam) chore today and none are open. A // follow-up handed out today doesn't count yet (issue #241). @@ -1097,23 +1230,36 @@ const ChoreWidget = ({ refreshNonce = 0, hiddenControls = [] }) => { const getUserChoresForToday = (userId) => { return schedules .filter(schedule => { - if (schedule.user_id !== userId) return false; + // A split schedule shows in every selected person's column: the + // card is the same chore, stamped below with this person's share. + const splitShare = splitShareFor(schedule, userId); + if (schedule.user_id !== userId && splitShare === null) return false; if (!schedule.visible) return false; return shouldShowChoreToday(schedule); }) .map(schedule => { const today = getTodayDateString(); - const pending = pendingToggles[schedule.id]; + const pending = pendingToggles[`${schedule.id}:${userId}`]; + // A split share is done once the member ticks it — on or after the + // split's claim date, which the server attaches as + // split_done_user_ids, so a share ticked yesterday still shows as + // done today (issue #407). Today's history alone cannot see it. const completed = pending !== undefined ? pending : history.some(h => h.chore_schedule_id === schedule.id && h.user_id === userId && h.date === today - ); + ) || splitShareDoneFor(schedule, userId, history, today); + // A split card belongs to this column's person: ticking it is + // theirs, and the Stars shown are their share — the chore's full + // Stars stay on the pool card only. + const splitShare = splitShareFor(schedule, userId); return { ...schedule, + user_id: userId, + ...(splitShare !== null ? { split_share: splitShare } : {}), completed, pending: pending !== undefined, id: schedule.id @@ -1126,7 +1272,9 @@ const ChoreWidget = ({ refreshNonce = 0, hiddenControls = [] }) => { }; const getAvailableBonusChores = () => { - return getBonusChores().filter(schedule => schedule.user_id === null || schedule.user_id === 0); + // A split chore is no longer in the pool: it is already claimed, one + // share per person, and shows in each person's column instead. + return getBonusChores().filter(schedule => (schedule.user_id === null || schedule.user_id === 0) && !isSplitSchedule(schedule)); }; // `size` and `badge`: the column header draws a smaller avatar and shows the @@ -1343,7 +1491,7 @@ const ChoreWidget = ({ refreshNonce = 0, hiddenControls = [] }) => { chips: the title stays the loudest thing in the row. */} {schedule.clam_value > 0 && ( - {t('common:points.gain', { amount: schedule.clam_value })} + {t('common:points.gain', { amount: schedule.split_share ?? schedule.clam_value })} )} {timeText && (expired ? ( @@ -1706,12 +1854,23 @@ const ChoreWidget = ({ refreshNonce = 0, hiddenControls = [] }) => { availableBonusChores.map(schedule => ( handleBonusCardContextMenu(e, schedule)} + onPointerDown={(e) => handleBonusCardPointerDown(e, schedule)} + onPointerMove={handleBonusCardPointerMove} + onPointerUp={handleBonusCardPointerEnd} + onPointerLeave={handleBonusCardPointerCancel} + onPointerCancel={handleBonusCardPointerCancel} + onClickCapture={handleBonusCardClickCapture} sx={{ p: 1, border: '1px solid var(--accent)', borderRadius: 'var(--hg-radius-sm)', mb: 1, - bgcolor: 'rgba(var(--accent-rgb), 0.1)' + bgcolor: 'rgba(var(--accent-rgb), 0.1)', + // Keep a hold from triggering text selection / iOS callout. + userSelect: 'none', + WebkitUserSelect: 'none', + WebkitTouchCallout: 'none' }} > @@ -2088,7 +2247,7 @@ const ChoreWidget = ({ refreshNonce = 0, hiddenControls = [] }) => { anchorReference="anchorPosition" anchorPosition={choreMenu.position || undefined} > - {!hideTransferChore && choreMenu.schedule?.transferable !== 0 && getTransferTargets(users, choreMenu.schedule?.user_id, '', choreMenu.schedule).length > 0 && ( + {!hideTransferChore && choreMenu.schedule?.transferable !== 0 && !splitHasTickedShare(choreMenu.schedule, history) && getTransferTargets(users, choreMenu.schedule?.user_id, '', choreMenu.schedule).length > 0 && ( @@ -2182,6 +2341,106 @@ const ChoreWidget = ({ refreshNonce = 0, hiddenControls = [] }) => { + {/* Split a bonus chore's Stars among several people */} + { + // A hold opens the picker while the finger is still down; the + // release fires a click that lands on the backdrop and would + // close it instantly. Ignore backdrop clicks right after opening. + if (reason === 'backdropClick' && Date.now() - splitDialogOpenedAtRef.current < 700) { + return; + } + closeSplitDialog(); + }} + maxWidth="xs" + fullWidth + > + + {splitDialog.result + ? t('chores:bonus.splitDone', { total: splitDialog.result.total }) + : t('chores:bonus.splitTitle', { title: splitDialog.schedule?.title })} + + + {splitDialog.result ? ( + <> + + {splitDialog.result.parts.map((part, index) => ( + + + + ))} + + + {t('chores:bonus.splitUndoHint')} + + + ) : ( + <> + + {t('chores:bonus.splitHint')} + + + {/* Only the people it is offered to (issue #403): the + server refuses anyone else with CHORE_NOT_OFFERED, so + they are left out here rather than shown and refused. */} + {users.filter((user) => canClaimBonusChore(splitDialog.schedule, user.id)).map((user) => { + const selectedIndex = splitDialog.userIds.indexOf(user.id); + const selected = selectedIndex !== -1; + const shares = splitStars(splitDialog.schedule?.clam_value || 0, splitDialog.userIds.length); + const share = selected ? shares[selectedIndex] : null; + // A share of 0 Stars is not a bonus chore: no more picks + // once the people count reaches the Stars, so the + // server's 0-Star refusal is never the first thing a + // picker sees. + const atCap = !selected && splitDialog.userIds.length >= (splitDialog.schedule?.clam_value || 0); + // Someone holding an open bonus chore cannot take + // another one — the server refuses them the same way. + const alreadyHasBonus = !selected && hasOutstandingBonusChore(schedules, history, user.id, getTodayDateString()); + const disabled = atCap || alreadyHasBonus; + return ( + toggleBonusSplitUser(user.id)}> + + + {user.username?.charAt(0).toUpperCase()} + + + + + + ); + })} + + + {splitDialog.userIds.length < 2 + ? t('chores:bonus.splitNeedTwo') + : t('chores:bonus.splitPreview', { total: splitDialog.schedule?.clam_value || 0, count: splitDialog.userIds.length })} + + + )} + + + {splitDialog.result ? ( + + ) : ( + <> + + + + )} + + + {/* Snooze chore dialog */} schedule.user_id === userId - && (schedule.clam_value || 0) > 0 - && shouldShowChoreToday(schedule, today)) - .some((schedule) => !history.some((entry) => entry.chore_schedule_id === schedule.id - && entry.user_id === userId - && entry.date === today)); + .filter((schedule) => { + // A split share open today counts the same as an assigned bonus + // chore: the person is holding it until they tick their own share. + const inSplit = isSplitSchedule(schedule) && parseSplitUserIds(schedule.split_user_ids)?.includes(Number(userId)); + return (schedule.user_id === userId || inSplit) + && (schedule.clam_value || 0) > 0 + && shouldShowChoreToday(schedule, today); + }) + .some((schedule) => { + // A split share is done once the member ticks it — on or after the + // split's claim date, which the server attaches as + // split_done_user_ids, so a share ticked yesterday does not block + // a claim tomorrow (issue #407). + const inSplit = isSplitSchedule(schedule) && parseSplitUserIds(schedule.split_user_ids)?.includes(Number(userId)); + if (inSplit) return !splitShareDoneFor(schedule, userId, history, today); + return !history.some((entry) => entry.chore_schedule_id === schedule.id + && entry.user_id === userId + && entry.date === today); + }); +} + +// A split bonus chore (issue #407) rides on the one pool schedule as two +// parallel lists, modelled on prize_offers.split_user_ids: `split_user_ids` +// who shares it and `split_shares` how many Stars each gets, in the same +// order. NULL is not split. Both parse leniently: a stored value that is +// not a list of ids / shares is treated as no split. +export function parseSplitUserIds(stored) { + if (stored === null || stored === undefined || stored === '') return null; + let list = stored; + if (typeof stored === 'string') { + try { list = JSON.parse(stored); } catch { return null; } + } + if (!Array.isArray(list)) return null; + const ids = [...new Set(list.filter((id) => Number.isInteger(id) && id > 0))]; + return ids.length > 0 ? ids : null; +} + +export function parseSplitShares(stored) { + if (stored === null || stored === undefined || stored === '') return null; + let list = stored; + if (typeof stored === 'string') { + try { list = JSON.parse(stored); } catch { return null; } + } + if (!Array.isArray(list)) return null; + const shares = list.filter((share) => Number.isInteger(share) && share >= 0); + return shares.length === list.length ? shares : null; +} + +export function isSplitSchedule(schedule) { + return parseSplitUserIds(schedule?.split_user_ids) !== null; +} + +// The Stars a person earns for ticking a schedule: their share of a split, +// or null when it is not split (or they are not in it). +export function splitShareFor(schedule, userId) { + const ids = parseSplitUserIds(schedule?.split_user_ids); + if (ids === null) return null; + const index = ids.indexOf(Number(userId)); + if (index === -1) return null; + const shares = parseSplitShares(schedule.split_shares); + if (shares === null || shares.length !== ids.length) return null; + return shares[index]; +} + +// Whether a split member's share is done (issue #407): the server attaches +// the members whose share is done (`split_done_user_ids`, a completion on +// or after the split's claim date), so a share ticked yesterday still reads +// as done tomorrow. Without it — an older server — fall back to today's +// history, which is all the dashboard fetches. +export function splitShareDoneFor(schedule, userId, history, today = getTodayDateString()) { + if (!isSplitSchedule(schedule)) return false; + if (Array.isArray(schedule.split_done_user_ids)) return schedule.split_done_user_ids.includes(Number(userId)); + return history.some((entry) => entry.chore_schedule_id === schedule.id + && entry.user_id === userId + && entry.kind === 'completion' + && entry.date === today); +} + +// Whether any share of a split has been ticked (issue #407): the split is +// locked once a share is ticked, so the dashboard hides Transfer for it. +// Reads the server's `split_done_user_ids` when present, so a share ticked +// yesterday still locks the split tomorrow; without it, falls back to +// today's history. +export function splitHasTickedShare(schedule, history, today = getTodayDateString()) { + if (!isSplitSchedule(schedule)) return false; + if (Array.isArray(schedule.split_done_user_ids)) return schedule.split_done_user_ids.length > 0; + return splitHasTickedShareToday(schedule, history, today); +} + +// Whether any share of a split has been ticked today (issue #407): the +// split is locked once a share is ticked, so the dashboard hides Transfer +// for it. `history` is today's history rows; a tick from an earlier day is +// invisible here, which is what `splitHasTickedShare` (above, reading the +// server's `split_done_user_ids`) is for. +export function splitHasTickedShareToday(schedule, history, today = getTodayDateString()) { + if (!isSplitSchedule(schedule)) return false; + return history.some((entry) => entry.chore_schedule_id === schedule.id + && entry.kind === 'completion' + && entry.date === today); } /** @@ -98,6 +191,21 @@ export function claimUserIdsToSave(picked, people, { bonus, nobody }) { return picked; } +/** + * Splitting a bonus chore's Stars among `count` people: the base share is + * the floor of the total over the people, and the leftover Stars go one + * each to the first people in the order given — 10 over 2 is [5, 5], 7 + * over 2 is [4, 3], 10 over 3 is [4, 3, 3]. The server runs the same + * rule (index.js splitStars), so the picker shows exactly what the + * split will assign. Returns one amount per person, in selection order. + */ +export function splitStars(total, count) { + if (!Number.isInteger(count) || count < 1) return []; + const base = Math.floor(total / count); + const remainder = total % count; + return Array.from({ length: count }, (_, i) => base + (i < remainder ? 1 : 0)); +} + export function getTodayDateString() { const tz = getServerTimezoneSync(); const today = new Date(); diff --git a/client/src/utils/choreHelpers.test.js b/client/src/utils/choreHelpers.test.js index b708ba6f..76d50b21 100644 --- a/client/src/utils/choreHelpers.test.js +++ b/client/src/utils/choreHelpers.test.js @@ -5,7 +5,7 @@ vi.mock('./timezone.js', () => ({ getServerTimezoneSync: () => zones.server, })); -import { shouldShowChoreToday, convertDaysToCrontab, getDueDateStatus, formatDueDate, hasOutstandingBonusChore, canClaimBonusChore, claimUserIdsToSave, compareByKey, countsTowardDailyBonus, ringsToday, getTransferTargets } from './choreHelpers.js'; +import { shouldShowChoreToday, convertDaysToCrontab, getDueDateStatus, formatDueDate, hasOutstandingBonusChore, canClaimBonusChore, claimUserIdsToSave, compareByKey, countsTowardDailyBonus, ringsToday, getTransferTargets, splitStars, parseSplitUserIds, parseSplitShares, isSplitSchedule, splitShareFor, splitShareDoneFor, splitHasTickedShare, splitHasTickedShareToday } from './choreHelpers.js'; // Issue #241: a follow-up counts toward the daily bonus from the day after it // was handed out, as the server's getTodaysRegularChoresForUser does. @@ -224,7 +224,7 @@ describe('hasOutstandingBonusChore', () => { const TODAY = '2026-09-06'; const bonus = (id, crontab) => ({ id, user_id: 4, visible: 1, clam_value: 1, crontab }); - const done = (id) => ({ chore_schedule_id: id, user_id: 4, date: TODAY }); + const done = (id) => ({ chore_schedule_id: id, user_id: 4, date: TODAY, kind: 'completion' }); it('does not block on a bonus chore that is not due today', () => { // Thursday-only chore, uncompleted, on a Sunday: nothing is outstanding. @@ -265,6 +265,126 @@ describe('hasOutstandingBonusChore', () => { it('treats a one-off schedule with no crontab as due today', () => { expect(hasOutstandingBonusChore([bonus(41, null)], [], 4, TODAY)).toBe(true); }); + + it('blocks on a split share open today', () => { + // A split schedule is unassigned, but the person in it is holding + // a share until they tick it. + const split = { id: 50, user_id: null, visible: 1, clam_value: 6, crontab: null, split_user_ids: [4, 3], split_shares: [3, 3] }; + expect(hasOutstandingBonusChore([split], [], 4, TODAY)).toBe(true); + }); + + it('does not block once the person ticked their split share', () => { + const split = { id: 50, user_id: null, visible: 1, clam_value: 6, crontab: null, split_user_ids: [4, 3], split_shares: [3, 3] }; + expect(hasOutstandingBonusChore([split], [done(50)], 4, TODAY)).toBe(false); + }); + + it('does not block on a split share the server says is done, even with no history row', () => { + // A share ticked yesterday: today's history does not see it, but the + // server attaches split_done_user_ids, so the person is free again. + const split = { id: 50, user_id: null, visible: 1, clam_value: 6, crontab: null, split_user_ids: [4, 3], split_shares: [3, 3], split_done_user_ids: [4] }; + expect(hasOutstandingBonusChore([split], [], 4, TODAY)).toBe(false); + }); + + it('still blocks when only the other person ticked their split share', () => { + const split = { id: 50, user_id: null, visible: 1, clam_value: 6, crontab: null, split_user_ids: [4, 3], split_shares: [3, 3], split_done_user_ids: [3] }; + expect(hasOutstandingBonusChore([split], [], 4, TODAY)).toBe(true); + }); + + it('does not block a person who is not in the split', () => { + const split = { id: 50, user_id: null, visible: 1, clam_value: 6, crontab: null, split_user_ids: [3, 2], split_shares: [3, 3] }; + expect(hasOutstandingBonusChore([split], [], 4, TODAY)).toBe(false); + }); +}); + +describe('split helpers', () => { + const split = (userIds, shares) => ({ id: 50, user_id: null, visible: 1, clam_value: 6, crontab: null, split_user_ids: userIds, split_shares: shares }); + + it('parses split user ids from an array or a JSON string', () => { + expect(parseSplitUserIds([4, 3])).toEqual([4, 3]); + expect(parseSplitUserIds('[4, 3]')).toEqual([4, 3]); + expect(parseSplitUserIds(null)).toBeNull(); + expect(parseSplitUserIds(undefined)).toBeNull(); + expect(parseSplitUserIds('')).toBeNull(); + expect(parseSplitUserIds('not json')).toBeNull(); + expect(parseSplitUserIds(4)).toBeNull(); + expect(parseSplitUserIds([])).toBeNull(); + }); + + it('drops bad ids and dedupes, and gives up when none are left', () => { + expect(parseSplitUserIds([4, 'x', 0, -1, 4, 3])).toEqual([4, 3]); + expect(parseSplitUserIds(['x', 0])).toBeNull(); + }); + + it('parses split shares from an array or a JSON string', () => { + expect(parseSplitShares([4, 3])).toEqual([4, 3]); + expect(parseSplitShares('[4, 3]')).toEqual([4, 3]); + expect(parseSplitShares(null)).toBeNull(); + expect(parseSplitShares('not json')).toBeNull(); + }); + + it('refuses shares with a bad entry rather than misaligning them', () => { + expect(parseSplitShares([4, 'x'])).toBeNull(); + expect(parseSplitShares([4, -1])).toBeNull(); + }); + + it('recognises a split schedule and nothing else', () => { + expect(isSplitSchedule(split([4, 3], [3, 3]))).toBe(true); + expect(isSplitSchedule(split('[4, 3]', '[3, 3]'))).toBe(true); + expect(isSplitSchedule({ ...split([4, 3], [3, 3]), split_user_ids: null })).toBe(false); + expect(isSplitSchedule({ id: 1, user_id: 4 })).toBe(false); + expect(isSplitSchedule(null)).toBe(false); + }); + + it('hands each person their own share', () => { + const schedule = split([4, 3], [4, 3]); + expect(splitShareFor(schedule, 4)).toBe(4); + expect(splitShareFor(schedule, 3)).toBe(3); + expect(splitShareFor(schedule, 2)).toBeNull(); + expect(splitShareFor({ ...schedule, split_user_ids: null }, 4)).toBeNull(); + }); + + it('refuses a share when the lists do not line up', () => { + expect(splitShareFor(split([4, 3], [4]), 4)).toBeNull(); + expect(splitShareFor(split([4, 3], [4, 'x']), 4)).toBeNull(); + }); + + it('says a split is locked once any share is ticked today', () => { + const schedule = split([4, 3], [4, 3]); + const today = '2026-09-06'; + const ticked = (userId, date = today, kind = 'completion') => ({ chore_schedule_id: 50, user_id: userId, date, kind }); + expect(splitHasTickedShareToday(schedule, [], today)).toBe(false); + expect(splitHasTickedShareToday(schedule, [ticked(4)], today)).toBe(true); + expect(splitHasTickedShareToday(schedule, [ticked(3)], today)).toBe(true); + // Another day's tick, or a row that is not a completion, locks nothing. + expect(splitHasTickedShareToday(schedule, [ticked(4, '2026-09-05')], today)).toBe(false); + expect(splitHasTickedShareToday(schedule, [ticked(4, today, 'missed')], today)).toBe(false); + // A tick on another chore, or a schedule that is not split, is not a lock. + expect(splitHasTickedShareToday(schedule, [{ ...ticked(4), chore_schedule_id: 51 }], today)).toBe(false); + expect(splitHasTickedShareToday({ ...schedule, split_user_ids: null }, [ticked(4)], today)).toBe(false); + expect(splitHasTickedShareToday(null, [ticked(4)], today)).toBe(false); + }); + + it('says a share is done per person, from the server list when present', () => { + const schedule = split([4, 3], [4, 3]); + const today = '2026-09-06'; + const ticked = (userId, date = today, kind = 'completion') => ({ chore_schedule_id: 50, user_id: userId, date, kind }); + // The server's list is the whole answer: a share ticked yesterday + // still reads as done, and the other person's share as open. + const done = { ...schedule, split_done_user_ids: [4] }; + expect(splitShareDoneFor(done, 4, [], today)).toBe(true); + expect(splitShareDoneFor(done, 3, [], today)).toBe(false); + expect(splitHasTickedShare(done, [], today)).toBe(true); + expect(splitHasTickedShare({ ...schedule, split_done_user_ids: [] }, [], today)).toBe(false); + // Without the list — an older server — today's history decides. + expect(splitShareDoneFor(schedule, 4, [ticked(4)], today)).toBe(true); + expect(splitShareDoneFor(schedule, 4, [ticked(4, '2026-09-05')], today)).toBe(false); + expect(splitShareDoneFor(schedule, 4, [], today)).toBe(false); + expect(splitHasTickedShare(schedule, [ticked(3)], today)).toBe(true); + expect(splitHasTickedShare(schedule, [], today)).toBe(false); + // Not a split, or nobody in it, is never done or locked. + expect(splitShareDoneFor({ ...schedule, split_user_ids: null }, 4, [ticked(4)], today)).toBe(false); + expect(splitShareDoneFor(schedule, 2, [ticked(4)], today)).toBe(false); + }); }); describe('compareByKey', () => { @@ -460,3 +580,33 @@ describe('getTransferTargets', () => { expect(targets.filter((t) => t.id === 0)).toEqual([{ id: 0, username: BONUS, isBonus: true }]); }); }); + +describe('splitStars', () => { + it('splits evenly when the total divides', () => { + expect(splitStars(10, 2)).toEqual([5, 5]); + expect(splitStars(9, 3)).toEqual([3, 3, 3]); + expect(splitStars(4, 4)).toEqual([1, 1, 1, 1]); + }); + + it('gives the leftover Stars one each to the first people', () => { + expect(splitStars(7, 2)).toEqual([4, 3]); + expect(splitStars(10, 3)).toEqual([4, 3, 3]); + expect(splitStars(11, 3)).toEqual([4, 4, 3]); + expect(splitStars(1, 2)).toEqual([1, 0]); + }); + + it('always hands out exactly the total', () => { + for (const total of [0, 1, 2, 5, 7, 10, 13]) { + for (const count of [1, 2, 3, 4, 5]) { + const shares = splitStars(total, count); + expect(shares).toHaveLength(count); + expect(shares.reduce((sum, share) => sum + share, 0)).toBe(total); + } + } + }); + + it('returns no shares without people', () => { + expect(splitStars(10, 0)).toEqual([]); + expect(splitStars(10, -1)).toEqual([]); + }); +}); diff --git a/client/src/utils/displayControls.js b/client/src/utils/displayControls.js index db55320b..61ba7138 100644 --- a/client/src/utils/displayControls.js +++ b/client/src/utils/displayControls.js @@ -31,6 +31,7 @@ export const CONTROL_LIMITS_DEFAULT_KEY = 'DISPLAY_CONTROL_LIMITS_DEFAULT'; export const CORE_CONTROLS = [ { id: 'core:addChore', labelKey: 'admin:controls.items.addChore' }, { id: 'core:transferChore', labelKey: 'admin:controls.items.transferChore' }, + { id: 'core:splitChore', labelKey: 'admin:controls.items.splitChore' }, { id: 'core:snoozeChore', labelKey: 'admin:controls.items.snoozeChore' }, { id: 'core:prizeApproval', labelKey: 'admin:controls.items.prizeApproval' }, { id: 'core:quickSpend', labelKey: 'admin:controls.items.quickSpend' }, diff --git a/client/src/utils/displayControls.test.js b/client/src/utils/displayControls.test.js index d7129eea..3c641d4e 100644 --- a/client/src/utils/displayControls.test.js +++ b/client/src/utils/displayControls.test.js @@ -32,6 +32,7 @@ describe('constants', () => { expect(CORE_IDS).toEqual([ 'core:addChore', 'core:transferChore', + 'core:splitChore', 'core:snoozeChore', 'core:prizeApproval', 'core:quickSpend', diff --git a/docs/reference/backend-api.md b/docs/reference/backend-api.md index bdb0b5b1..9c5a2145 100644 --- a/docs/reference/backend-api.md +++ b/docs/reference/backend-api.md @@ -63,7 +63,9 @@ Runs at local midnight and also exposed manually via save — days off never count as missed). - Prunes completed one-time chore schedules (completion = a `kind='completion'` row; a missed row never counts) and orphaned chores. -- Resets day-to-day **bonus** chores back to unassigned. +- Resets day-to-day **bonus** chores back to unassigned. A split bonus + chore returns to one chore in the pool — except a half-done one-time + split, which stays split until every share is ticked (issue #407). - Generates one-time child instances for `until-completed` / `once-completed` "sticky" schedules whose cron fires that day (using `cron-parser`). @@ -219,16 +221,16 @@ Every recipient (a device's browser push, an ntfy topic, a Home Assistant phone) | GET/POST | `/api/chores` | List / create chore definitions. Each listed chore carries `followups: [{ id, followup_chore_id, title }]`. `claim_user_ids` is who a bonus chore is offered to (issue #403): a list of user ids, `null` (the default) for everyone, or `[]` for nobody; an unknown id answers **400**. | | PATCH/DELETE | `/api/chores/:id` | Update / delete a chore. PATCH changes `claim_user_ids` only when it is sent. Deleting removes its follow-up rules and any rule that names it. | | GET/PUT | `/api/chores/:id/followups` | A chore's follow-ups (issue #241). PUT replaces them with `{ followups: [{ followup_chore_id, user_ids, delay_minutes }] }`: at most 3, not the chore itself, no loops, at least one person, delay 0–10080 minutes. | -| GET/POST | `/api/chore-schedules` | List (filter by `user_id`, `visible`, `usage`, `chore_id`) / create. `duration` is `day-of` (default), `until-completed`, `once-completed` (with an `interval` such as `3d`) or `any-day` (once in a period, any day: `interval` is its period, one of `1w`, `2w`, `1m`, `3m`, `6m`, `1y`, default `1w`; its crontab is set to `0 0 * * *` whatever is sent). `weekly` is accepted as `any-day` every `1w`. `week_interval` (2, 3 or 4, or null for every week) and `week_anchor` (`YYYY-MM-DD`, stored as its week's Sunday; this week when left out) make a schedule every few weeks on its days (issue #401): only with a days-of-the-week crontab on a `day-of` or `until-completed` schedule, **400** otherwise. A PATCH that changes the crontab or duration so that it can't have one, without sending them, drops it; one that only changes the days keeps it. Each row carries `parent_duration`, the duration of the schedule a sticky chore's card came from (an `any-day` card is due on its `due_date`, its period's last day). Each row also carries its chore's `claim_user_ids` (read-only here; it is set on the chore). Accepts `due_time` (`HH:MM`), `sound`, `sound_enabled`, `reminder_interval_minutes` for due-time sounds, and `due_date` (`YYYY-MM-DD`) for calendar deadlines. `expire_minutes` (one of 0, 15, 30, 60, 120, 180, 240, 360, 480, 720, or null) makes it expire that long after its due time; it needs a `due_time` (400 otherwise), and clearing the due time clears it. PATCH `user_id` reassigns a chore and re-checks the daily bonus for both owners; with `transfer: true` (the dashboard's Transfer dialog) it answers **403** (`code: "CHORE_NOT_OFFERED"`) when a bonus chore's `claim_user_ids` does not include the new person, while an admin's assignment, sent without it, is not held to the list. Taking a chore off someone's day (deleting its schedule or chore, hiding it, moving it to other days, snoozing it, giving the chore clams, or deleting a routine) re-checks their bonus too, and pays it if the rest of the day is done; it never takes a bonus back (issue #298). Deleting an `any-day` schedule, or PATCHing it to another duration, removes its not-yet-done card. PATCHing a repeating schedule's crontab to null (one-time) sets `one_time_after_history_id`, so only completions logged after it mark the one-time chore done. | +| GET/POST | `/api/chore-schedules` | List (filter by `user_id`, `visible`, `usage`, `chore_id`) / create. `duration` is `day-of` (default), `until-completed`, `once-completed` (with an `interval` such as `3d`) or `any-day` (once in a period, any day: `interval` is its period, one of `1w`, `2w`, `1m`, `3m`, `6m`, `1y`, default `1w`; its crontab is set to `0 0 * * *` whatever is sent). `weekly` is accepted as `any-day` every `1w`. `week_interval` (2, 3 or 4, or null for every week) and `week_anchor` (`YYYY-MM-DD`, stored as its week's Sunday; this week when left out) make a schedule every few weeks on its days (issue #401): only with a days-of-the-week crontab on a `day-of` or `until-completed` schedule, **400** otherwise. A PATCH that changes the crontab or duration so that it can't have one, without sending them, drops it; one that only changes the days keeps it. Each row carries `parent_duration`, the duration of the schedule a sticky chore's card came from (an `any-day` card is due on its `due_date`, its period's last day). Each row also carries its chore's `claim_user_ids` (read-only here; it is set on the chore). A split schedule also carries `split_user_ids` / `split_shares` and `split_done_user_ids`, the split members whose share is done (a completion on or after the split's claim date), so the dashboard shows a share ticked yesterday as done today (issue #407). Accepts `due_time` (`HH:MM`), `sound`, `sound_enabled`, `reminder_interval_minutes` for due-time sounds, and `due_date` (`YYYY-MM-DD`) for calendar deadlines. `expire_minutes` (one of 0, 15, 30, 60, 120, 180, 240, 360, 480, 720, or null) makes it expire that long after its due time; it needs a `due_time` (400 otherwise), and clearing the due time clears it. PATCH `user_id` reassigns a chore and re-checks the daily bonus for both owners; with `transfer: true` (the dashboard's Transfer dialog) it answers **403** (`code: "CHORE_NOT_OFFERED"`) when a bonus chore's `claim_user_ids` does not include the new person, while an admin's assignment, sent without it, is not held to the list. PATCH `user_id` on a split schedule answers **409** once any share of the split has been ticked, but only when `user_id` actually moves it: resending the current one (the schedule dialog does, on every save) is not a move, so it neither ends the split nor answers 409 — while `0`, the Transfer dialog's explicit back-to-the-pool, still counts as a move (issue #407). The split is locked because releasing it to the pool or handing it to one person would pay the ticked share plus the whole chore. Taking a chore off someone's day (deleting its schedule or chore, hiding it, moving it to other days, snoozing it, giving the chore clams, or deleting a routine) re-checks their bonus too, and pays it if the rest of the day is done; it never takes a bonus back (issue #298). Deleting an `any-day` schedule, or PATCHing it to another duration, removes its not-yet-done card. PATCHing a repeating schedule's crontab to null (one-time) sets `one_time_after_history_id`, so only completions logged after it mark the one-time chore done. | | GET/PATCH/DELETE | `/api/chore-schedules/:id` | Single schedule CRUD. | -| POST | `/api/chore-schedules/:id/claim` | Claim a bonus chore from the pool for a kid: body `{ user_id }`. Records the claim date on the schedule (`pool_claimed_on`); the nightly job returns only schedules carrying that marker to the pool, and clears it as it goes. Answers **409** when the chore is already assigned, not visible, pays no clams, or the kid already has an open bonus chore, and **403** (`code: "CHORE_NOT_OFFERED"`) when the chore's `claim_user_ids` does not include the kid. An admin assigning the same chore with PATCH sets no marker. | +| POST | `/api/chore-schedules/:id/claim` | Claim a bonus chore from the pool for a kid: body `{ user_id }`. Records the claim date on the schedule (`pool_claimed_on`); the nightly job returns only schedules carrying that marker to the pool, and clears it as it goes. Answers **409** when the chore is already assigned, already split among several people, not visible, pays no clams, or the kid already has an open bonus chore, and **403** (`code: "CHORE_NOT_OFFERED"`) when the chore's `claim_user_ids` does not include the kid. An admin assigning the same chore with PATCH sets no marker. | | POST | `/api/chore-schedules/bulk` | Bulk create schedules. | | GET/POST | `/api/chore-history` | Query / add history entries. | | GET | `/api/chore-history/user/:userId` | History for a user. | | GET | `/api/chore-history/summary/:userId` | Summary/aggregate for a user. | | GET | `/api/chore-history/recent` | Recent (last 7 days) completions. | | DELETE | `/api/chore-history/:id` | Delete a history entry. | -| POST | `/api/chores/complete` | Mark a chore complete (awards clams / daily bonus). A completion dated today hands out the chore's follow-ups; the response lists them in `followups_created`. Past its expiry it answers **403** `{ code: 'CHORE_EXPIRED' }` unless the body has `parent_approved: true`; that completion is marked `approved_late` in the history. | +| POST | `/api/chores/complete` | Mark a chore complete (awards clams / daily bonus). A completion dated today hands out the chore's follow-ups; the response lists them in `followups_created`. Completing a split chore as someone not in the split answers **409**, and so does a split member ticking a share they have already completed (a completion on or after the split's claim date, not just today) (issue #407). Past its expiry it answers **403** `{ code: 'CHORE_EXPIRED' }` unless the body has `parent_approved: true`; that completion is marked `approved_late` in the history. | | POST | `/api/chores/uncomplete` | Undo a completion, and remove the follow-ups it handed out that nobody has done (`followups_removed`). | | GET | `/api/routines` | Routines (`{ routines, steps, imported }`): each with its `steps` (step ids, in order), `days`, `trigger` ('days' or 'calendar') and its `chore_id` / `schedule_id`. `imported` is the one-time import from the Routines plugin, if any. The chores and schedules lists carry `routine_id` on a routine's own. Those are changed through the routine: `PATCH /api/chores/:id`, a new schedule for its chore (`POST /api/chore-schedules`, `/bulk`), and a `PATCH /api/chore-schedules/:id` touching its chore, person, days, time, duration, due date or expiry answer 409 with `routine_id`. | | POST/PATCH/DELETE | `/api/routines`, `/api/routines/:id` | Create (makes the routine's chore and schedule), edit in place (the chore and schedules are updated, not replaced), delete (deletes its chore; history stays). Body: `name, icon, user_id, trigger, days, match_text, whole_word, calendar_source_ids, lead_minutes, steps, start_time, end_time, milestone_every, milestone_clams`. Creating with `user_ids: [...]` instead of `user_id` makes the routine for each person, one each (all or none), and answers `{ routines }`. | diff --git a/server/index.js b/server/index.js index d06484f6..d5e9f38c 100644 --- a/server/index.js +++ b/server/index.js @@ -2638,7 +2638,7 @@ async function dailyBackgroundProcessing() { // next period starts fresh, and an undone one was logged as one miss on // its last day, above (services/anyDayChores.js). const schedulesToPrune = db.prepare(` - SELECT cs.id, cs.chore_id, cs.user_id, cs.parent_schedule_id, c.title + SELECT cs.id, cs.chore_id, cs.user_id, cs.parent_schedule_id, cs.split_user_ids, cs.one_time_after_history_id, c.title FROM chore_schedules cs JOIN chores c ON cs.chore_id = c.id LEFT JOIN chore_schedules ps ON ps.id = cs.parent_schedule_id @@ -2653,7 +2653,22 @@ async function dailyBackgroundProcessing() { ) OR (ps.duration = 'any-day' AND cs.due_date IS NOT NULL AND cs.due_date < ?) ) - `).all(today); + `).all(today).filter((schedule) => { + // A split schedule is done only when every person in the split has + // ticked their share: one person's completion must not prune the + // schedule out from under the others (issue #407). A partially done + // split is left for the split return below, which keeps it split + // while a share is still open; a fully done one is pruned here + // like any completed one-time chore. + const ids = parseSplitUserIds(schedule.split_user_ids); + if (ids === null) return true; + const completed = new Set(db.prepare(` + SELECT user_id FROM chore_history + WHERE chore_schedule_id = ? AND kind = 'completion' + AND (? IS NULL OR id > ?) + `).all(schedule.id, schedule.one_time_after_history_id, schedule.one_time_after_history_id).map((row) => row.user_id)); + return ids.every((id) => completed.has(id)); + }); console.log(`Found ${schedulesToPrune.length} completed one-time chores to prune`); // A sticky chore's card keeps its history with the chore: the rows move @@ -2772,6 +2787,50 @@ async function dailyBackgroundProcessing() { returnedBonusSchedules: claimedBonusSchedules, } + // A split bonus chore returns to one chore in the pool every night. + // It is unassigned (user_id NULL), so neither of the returns above + // catches it: the split is what marks it, so the split is cleared + // here along with the claim marker. A share already ticked today + // stays earned — only the open split is cleared, never the history. + // A half-done ONE-TIME split does not return (issue #407): while any + // share is ticked and another is still open, clearing the split + // would put the whole chore back in the pool, and the next night the + // prune would take it as "done" on the one ticked share. It stays + // split until every share is ticked, when the prune takes it as it + // already does; untouched, it returns like any other split. A + // recurring split still returns every night — tomorrow is a new day + // of the chore, worth its full Stars again. + const splitBonusSchedules = db.prepare(` + SELECT cs.id, + cs.crontab, + cs.split_user_ids, + cs.pool_claimed_on, + c.title + FROM chore_schedules cs + JOIN chores c ON cs.chore_id = c.id + WHERE cs.visible = 1 + AND c.clam_value > 0 + AND cs.pool_claimed_on IS NOT NULL + AND cs.split_user_ids IS NOT NULL; + `).all(); + console.log(`Found ${splitBonusSchedules.length} split bonus chores to return to the pool`); + let returnedSplitCount = 0; + const returnedSplitSchedules = []; + for (const schedule of splitBonusSchedules) { + if (!schedule.crontab && splitHasTickedShare(schedule)) { + console.log(`Keeping split schedule ID ${schedule.id}: "${schedule.title}" with the split — a share is ticked and another is still open`); + continue; + } + db.prepare('UPDATE chore_schedules SET split_user_ids = NULL, split_shares = NULL, pool_claimed_on = NULL WHERE id = ?').run(schedule.id); + console.log(`Returned schedule ID ${schedule.id}: "${schedule.title}" to the bonus pool (split cleared)`); + returnedSplitCount++; + returnedSplitSchedules.push(schedule); + } + results = { + ...results, + returnedSplitSchedulesCount: returnedSplitCount, + returnedSplitSchedules, + } // Sticky schedules: today's one-time child for each until-completed and // once-completed parent that fires today and has none open yet. @@ -3599,8 +3658,18 @@ fastify.delete('/api/chores/:id', async (request, reply) => { // Chore Schedules routes // A schedule row as the API sends it: `claim_user_ids` is its chore's list of // who it is offered to, or null for everyone (issue #403, -// utils/choreClaimers.js). -const withClaimUserIds = (row) => ({ ...row, claim_user_ids: choreClaimers.parseClaimUserIds(row.claim_user_ids) }); +// utils/choreClaimers.js); `split_user_ids` / `split_shares` are the split +// (issue #407), parallel lists or null when the chore is not split, and +// `split_done_user_ids` the split members whose share is done (a completion +// on or after the split's claim date), so the dashboard shows a share +// ticked yesterday as done today and hides Transfer for a locked split. +const withScheduleLists = (row) => ({ + ...row, + claim_user_ids: choreClaimers.parseClaimUserIds(row.claim_user_ids), + split_user_ids: parseSplitUserIds(row.split_user_ids), + split_shares: parseSplitShares(row.split_shares), + split_done_user_ids: splitDoneUserIds(row), +}); fastify.get('/api/chore-schedules', async (request, reply) => { try { @@ -3644,7 +3713,7 @@ fastify.get('/api/chore-schedules', async (request, reply) => { } const rows = db.prepare(query).all(...params); - return rows.map(withClaimUserIds); + return rows.map(withScheduleLists); } catch (error) { console.error('Error fetching chore schedules:', error); reply.status(500).send({ error: 'Failed to fetch chore schedules' }); @@ -3658,7 +3727,7 @@ fastify.get('/api/chore-schedules/:id', async (request, reply) => { if (!row) { return reply.status(404).send({ error: 'Schedule not found' }); } - return withClaimUserIds(row); + return withScheduleLists(row); } catch (error) { console.error('Error fetching schedule:', error); reply.status(500).send({ error: 'Failed to fetch schedule' }); @@ -3891,11 +3960,24 @@ fastify.patch('/api/chore-schedules/:id', async (request, reply) => { } } - const existingSchedule = db.prepare('SELECT id, chore_id, user_id, crontab, duration, interval, snoozed_until, due_time, expire_minutes, created_at, week_interval, week_anchor FROM chore_schedules WHERE id = ?').get(id); + const existingSchedule = db.prepare('SELECT id, chore_id, user_id, crontab, duration, interval, snoozed_until, due_time, expire_minutes, created_at, week_interval, week_anchor, split_user_ids, split_shares, pool_claimed_on FROM chore_schedules WHERE id = ?').get(id); if (!existingSchedule) { return reply.status(404).send({ error: 'Schedule not found' }); } + // `user_id` counts as a move only when it differs from the schedule's + // current one (issue #407): the schedule dialog sends `user_id` with + // every save, so an untouched split would otherwise read as a move — + // quietly ending the split, or answering 409 once a share is ticked, + // though nobody moved it. `null` is "no assignee" as the dialog sends + // it; `0` is the Transfer dialog's explicit "back to the pool", which + // IS a move even for a split schedule that already has no assignee. + const nextUserId = user_id === undefined ? existingSchedule.user_id : (Number(user_id) || null); + const isMove = user_id !== undefined && (user_id === 0 || user_id === '0' || nextUserId !== existingSchedule.user_id); + if (isMove && splitHasTickedShare(existingSchedule)) { + return reply.status(409).send({ error: 'This split chore cannot be moved once a share has been completed' }); + } + // A transfer from the dashboard (`transfer: true`, the widget's Transfer // dialog) is held to the chore's "who can take this" list, as a claim // is: otherwise a kid could claim a bonus chore and hand it to someone @@ -3980,12 +4062,19 @@ fastify.patch('/api/chore-schedules/:id', async (request, reply) => { } if (chore_id !== undefined) { updates.push('chore_id = ?'); params.push(chore_id); } - if (user_id !== undefined) { - updates.push('user_id = ?'); params.push(user_id || null); + // Only a real move reassigns: resending the current `user_id` (the + // schedule dialog does, on every save) leaves the assignment — and a + // split — exactly as it was (issue #407). + if (isMove) { + updates.push('user_id = ?'); params.push(nextUserId); // Back to the pool: the claim is over, so the marker goes with it. // Any other move keeps the marker — a claimed chore transferred to // another kid still returns at the nightly cleanup. - if (!user_id) updates.push('pool_claimed_on = NULL'); + if (!nextUserId) updates.push('pool_claimed_on = NULL'); + // A split ends when the chore moves: back to the pool releases the + // whole split, and handing it to one person gives them the whole + // chore at its full Stars. + if (existingSchedule.split_user_ids) updates.push('split_user_ids = NULL', 'split_shares = NULL'); } if (crontab !== undefined) { updates.push('crontab = ?'); params.push(crontab || null); } // Made one-time: what it was done before doesn't make it done now (the @@ -4050,22 +4139,19 @@ fastify.patch('/api/chore-schedules/:id', async (request, reply) => { // daily bonus. The alternative "keep reward" choice persists // `transfer_bonus_clams` (threaded above), paid out when the moved chore is // completed. - if (user_id !== undefined) { + if (isMove) { const previousUserId = existingSchedule.user_id; - const nextUserId = user_id || null; - if (previousUserId !== nextUserId) { - const today = getTodayLocalDateString(); - if (previousUserId) { - awardDailyRegularBonusIfDue(previousUserId, today); - } - if (nextUserId) { - if (revoke_daily_bonus === true) { - revokeDailyRegularBonus(nextUserId, today); - } - // Revoke-then-award is idempotent: if the receiver's due set is - // somehow still complete, the bonus is immediately re-awarded. - awardDailyRegularBonusIfDue(nextUserId, today); + const today = getTodayLocalDateString(); + if (previousUserId) { + awardDailyRegularBonusIfDue(previousUserId, today); + } + if (nextUserId) { + if (revoke_daily_bonus === true) { + revokeDailyRegularBonus(nextUserId, today); } + // Revoke-then-award is idempotent: if the receiver's due set is + // somehow still complete, the bonus is immediately re-awarded. + awardDailyRegularBonusIfDue(nextUserId, today); } } @@ -4111,6 +4197,128 @@ fastify.patch('/api/chore-schedules/:id', async (request, reply) => { } }); +// A split bonus chore (issue #407) rides on the one pool schedule as two +// parallel JSON lists, modelled on prize_offers.split_user_ids: +// `split_user_ids` who shares it and `split_shares` how many Stars each +// gets, in the same order. NULL is not split. Both parse leniently: a +// stored value that is not a list of ids / shares is treated as no split, +// so a half-written row can never hand out a share to the wrong person. +function parseSplitUserIds(stored) { + if (stored === null || stored === undefined || stored === '') return null; + let list = stored; + if (typeof stored === 'string') { + try { list = JSON.parse(stored); } catch { return null; } + } + if (!Array.isArray(list)) return null; + const ids = [...new Set(list.filter((id) => Number.isInteger(id) && id > 0))]; + return ids.length > 0 ? ids : null; +} + +function parseSplitShares(stored) { + if (stored === null || stored === undefined || stored === '') return null; + let list = stored; + if (typeof stored === 'string') { + try { list = JSON.parse(stored); } catch { return null; } + } + if (!Array.isArray(list)) return null; + const shares = list.filter((share) => Number.isInteger(share) && share >= 0); + return shares.length === list.length ? shares : null; +} + +// One open bonus chore per kid, shared by the claim route and the split +// route: an assigned bonus chore due today that is not completed today +// blocks another claim — and a split share open today counts the same, so +// a second display cannot race past it. The widget runs the same test +// first (choreHelpers.hasOutstandingBonusChore); only the server sees +// every display. The routine check lives beside this, not in it: a +// routine's schedules are refused by the caller, never counted here. +function hasOutstandingBonusChore(userId, today) { + const now = new Date(); + const assigned = db.prepare(` + SELECT cs.*, c.clam_value + FROM chore_schedules cs JOIN chores c ON cs.chore_id = c.id + WHERE cs.user_id = ? AND cs.visible = 1 AND c.clam_value > 0 + `).all(userId); + // A split schedule is unassigned (user_id NULL) but claimed for several + // people; each person in it holds an open bonus chore until they tick + // their own share. + const split = db.prepare(` + SELECT cs.*, c.clam_value + FROM chore_schedules cs JOIN chores c ON cs.chore_id = c.id + WHERE cs.visible = 1 AND c.clam_value > 0 AND cs.split_user_ids IS NOT NULL + `).all().filter((row) => { + const ids = parseSplitUserIds(row.split_user_ids); + return ids !== null && ids.includes(Number(userId)); + }); + const completions = db.prepare(` + SELECT chore_schedule_id, date FROM chore_history + WHERE user_id = ? AND kind = 'completion' + `).all(userId); + const completedToday = new Set(completions.filter((row) => row.date === today).map((row) => row.chore_schedule_id)); + const outstanding = (row, isSplit) => { + if (isSplit) { + // A split share is done once the member ticks it — on or after the + // split's claim date, not just today (issue #407): a half-done + // one-time split stays split past midnight, so a today-only check + // would count a finished share as open and block the next claim. + const since = row.pool_claimed_on || today; + if (completions.some((completion) => completion.chore_schedule_id === row.id && completion.date >= since)) return false; + } else if (completedToday.has(row.id)) return false; + if (row.snoozed_until && new Date(row.snoozed_until) > now) return false; + if (!row.crontab) return true; + try { + return scheduleFiresOnDate(row, today); + } catch { + return false; + } + }; + return assigned.some((row) => outstanding(row, false)) || split.some((row) => outstanding(row, true)); +} + +// The Stars a person earns for ticking a schedule: their share of a split, +// or the chore's full Stars when it is not split. Someone not in a split +// never reaches here — completing refuses them first (below). +function splitShareForUser(schedule, userId) { + const ids = parseSplitUserIds(schedule.split_user_ids); + if (ids === null) return null; + const index = ids.indexOf(Number(userId)); + if (index === -1) return null; + const shares = parseSplitShares(schedule.split_shares); + if (shares === null || shares.length !== ids.length) return null; + return shares[index]; +} + +// The split members whose share is done (issue #407): a completion by +// them on this schedule on or after the split's claim date. One rule for +// "this member's share is done", used by completing, the one-open-bonus +// check, the dashboard's done state and the Transfer lock. The date is +// the split's, not today's: a half-done one-time split stays split past +// midnight, so a member who ticked yesterday must still read as done +// tomorrow — otherwise they could tick the same share again and the +// dashboard would show their card as not done. +function splitDoneUserIds(schedule) { + const ids = parseSplitUserIds(schedule.split_user_ids); + if (ids === null) return []; + const since = schedule.pool_claimed_on || getTodayLocalDateString(); + const completed = db.prepare(` + SELECT user_id FROM chore_history + WHERE chore_schedule_id = ? AND kind = 'completion' AND date >= ? + `).all(schedule.id, since).map((row) => row.user_id); + return ids.filter((id) => completed.includes(Number(id))); +} + +// Whether any share of a split has been ticked since the split was made +// (issue #407): a completion by a split member on or after the split's +// claim date locks the split — it can no longer be handed to one person +// or released to the pool, or the ticked share plus the whole chore +// would pay out more than the chore is worth. The date is the split's, +// not today's: a half-done one-time split stays split past midnight +// (the nightly return below), so a today-only check would leave the +// same hole open the next day. +function splitHasTickedShare(schedule) { + return splitDoneUserIds(schedule).length > 0; +} + // Claiming a bonus chore from the pool is its own route, not a plain // assignment: the widget used to claim with PATCH /api/chore-schedules/:id // {user_id, visible: 1}, the same request an admin uses to assign a chore @@ -4151,6 +4359,13 @@ fastify.post('/api/chore-schedules/:id/claim', async (request, reply) => { if (schedule.user_id !== null) { return reply.status(409).send({ error: 'This chore is already assigned' }); } + // A split chore is already claimed, one share per person (issue #407): + // a stale display still showing it in the pool must not claim it on + // top of the split, or the claimer would hold a chore they cannot tick + // and the nightly return would never take it back. + if (parseSplitUserIds(schedule.split_user_ids) !== null) { + return reply.status(409).send({ error: 'This chore is already split among several people' }); + } if (!schedule.visible) { return reply.status(409).send({ error: 'This chore is not available to claim' }); } @@ -4171,27 +4386,7 @@ fastify.post('/api/chore-schedules/:id/claim', async (request, reply) => { // the widget runs first (hasOutstandingBonusChore), here so a second // display cannot race past it. const today = getTodayLocalDateString(); - const assigned = db.prepare(` - SELECT cs.*, c.clam_value - FROM chore_schedules cs JOIN chores c ON cs.chore_id = c.id - WHERE cs.user_id = ? AND cs.visible = 1 AND c.clam_value > 0 - `).all(parsedUserId); - const completedToday = new Set(db.prepare(` - SELECT chore_schedule_id FROM chore_history - WHERE user_id = ? AND date = ? AND kind = 'completion' - `).all(parsedUserId, today).map((row) => row.chore_schedule_id)); - const now = new Date(); - const outstanding = assigned.some((row) => { - if (completedToday.has(row.id)) return false; - if (row.snoozed_until && new Date(row.snoozed_until) > now) return false; - if (!row.crontab) return true; - try { - return scheduleFiresOnDate(row, today); - } catch { - return false; - } - }); - if (outstanding) { + if (hasOutstandingBonusChore(parsedUserId, today)) { return reply.status(409).send({ error: 'This person already has an outstanding bonus chore' }); } @@ -4201,7 +4396,7 @@ fastify.post('/api/chore-schedules/:id/claim', async (request, reply) => { // daily "all regular chores done" bonus is re-checked for the new // owner, as PATCH does. awardDailyRegularBonusIfDue(parsedUserId, today); - return withClaimUserIds(db.prepare(` + return withScheduleLists(db.prepare(` SELECT cs.*, c.title, c.description, c.clam_value, c.icon, c.claim_user_ids FROM chore_schedules cs JOIN chores c ON cs.chore_id = c.id WHERE cs.id = ? @@ -4212,6 +4407,130 @@ fastify.post('/api/chore-schedules/:id/claim', async (request, reply) => { } }); +// Splitting a bonus chore's Stars: the base share is the floor of the +// total over the people, and the leftover Stars go one each to the first +// people in the order given — 10 over 2 is 5 and 5, 7 over 2 is 4 and 3, +// 10 over 3 is 4, 3 and 3. The same rule runs in the widget +// (utils/choreHelpers.js splitStars) so the picker shows exactly what the +// server will assign. +function splitStars(total, count) { + const base = Math.floor(total / count); + const remainder = total % count; + return Array.from({ length: count }, (_, i) => base + (i < remainder ? 1 : 0)); +} + +// Splitting a bonus chore from the pool among several people. The one pool +// schedule stays put: the split rides on it as `split_user_ids` / +// `split_shares` (two parallel JSON lists, modelled on +// prize_offers.split_user_ids), with the claim marker carrying today's +// date, so the nightly cleanup returns it to one chore again. Each +// person's share is theirs to tick — completing writes their share to +// their history row (chore_history.clam_value is already per row), so the +// chore keeps its definition, icon, follow-ups, list and history. At +// least two people are required — one person claiming is the claim route, +// not a split — and a split is refused when any share would be 0 Stars +// (more people than Stars). +fastify.post('/api/chore-schedules/:id/split-assign', async (request, reply) => { + const { id } = request.params; + const userIds = request.body?.userIds; + if (!Array.isArray(userIds) || userIds.length < 2) { + return reply.status(400).send({ error: 'userIds must list at least two people to split a bonus chore' }); + } + const parsedUserIds = []; + for (const raw of userIds) { + const parsed = parseInt(raw, 10); + if (Number.isNaN(parsed) || parsed <= 0) { + return reply.status(400).send({ error: 'userIds must be household user ids' }); + } + if (!parsedUserIds.includes(parsed)) parsedUserIds.push(parsed); + } + if (parsedUserIds.length < 2) { + return reply.status(400).send({ error: 'userIds must list at least two different people to split a bonus chore' }); + } + try { + for (const userId of parsedUserIds) { + const user = db.prepare('SELECT id FROM users WHERE id = ?').get(userId); + if (!user) { + return reply.status(404).send({ error: `User not found: ${userId}` }); + } + } + const schedule = db.prepare(` + SELECT cs.*, c.title, c.description, c.clam_value, c.icon, c.claim_user_ids + FROM chore_schedules cs JOIN chores c ON cs.chore_id = c.id + WHERE cs.id = ? + `).get(id); + if (!schedule) { + return reply.status(404).send({ error: 'Schedule not found' }); + } + // A routine's schedules belong to the routine: assigning one by hand + // is refused on PATCH the same way. + const owner = routineOwning(schedule.chore_id); + if (owner) return refuseRoutineEdit(reply, owner); + if (schedule.user_id !== null) { + return reply.status(409).send({ error: 'This chore is already assigned' }); + } + // Already split: a stale display still showing it in the pool must not + // split it again on top of the first split (issue #407) — the new split + // would reset the claim date, so the first split's ticked shares would + // read as open again. + if (parseSplitUserIds(schedule.split_user_ids) !== null) { + return reply.status(409).send({ error: 'This chore is already split among several people' }); + } + if (!schedule.visible) { + return reply.status(409).send({ error: 'This chore is not available to split' }); + } + if (!(schedule.clam_value > 0)) { + return reply.status(409).send({ error: 'Only bonus chores can be split from the pool' }); + } + // A share of 0 Stars is not a bonus chore: splitting fewer Stars + // than people would hand someone a 0-Star copy that counts toward + // their daily bonus and never returns to the pool. + if (parsedUserIds.length > schedule.clam_value) { + return reply.status(400).send({ error: `Splitting ${schedule.clam_value} Stars among ${parsedUserIds.length} people would leave someone with 0 Stars` }); + } + // Offered to some people only (issue #403): every person in the split + // must be on the chore's list, as a claim is. Checked here as well as + // in the widget, so another display or a direct request can't get + // past it. + for (const userId of parsedUserIds) { + if (!choreClaimers.mayClaim(schedule.claim_user_ids, userId)) { + return reply.status(403).send({ error: 'This chore is not offered to this person', code: 'CHORE_NOT_OFFERED' }); + } + } + + // One open bonus chore per kid, the same test the claim route runs: + // an assigned bonus chore due today that is not completed today blocks + // the split for that person, so a second display cannot race past it. + const today = getTodayLocalDateString(); + for (const userId of parsedUserIds) { + if (hasOutstandingBonusChore(userId, today)) { + const name = db.prepare('SELECT username FROM users WHERE id = ?').get(userId)?.username || userId; + return reply.status(409).send({ error: `${name} already has an outstanding bonus chore` }); + } + } + + const amounts = splitStars(schedule.clam_value, parsedUserIds.length); + // One schedule, one update: the split never leaves half the family + // assigned, and there is nothing else to collect on undo. + db.prepare('UPDATE chore_schedules SET pool_claimed_on = ?, split_user_ids = ?, split_shares = ? WHERE id = ?') + .run(today, JSON.stringify(parsedUserIds), JSON.stringify(amounts), id); + // Splitting assigns someone's set the same way claiming does: the + // daily "all regular chores done" bonus is re-checked for each new + // holder, as the claim route does. + for (const userId of parsedUserIds) { + awardDailyRegularBonusIfDue(userId, today); + } + return { success: true, schedule: withScheduleLists(db.prepare(` + SELECT cs.*, c.title, c.description, c.clam_value, c.icon, c.claim_user_ids + FROM chore_schedules cs JOIN chores c ON cs.chore_id = c.id + WHERE cs.id = ? + `).get(id)) }; + } catch (error) { + console.error('Error splitting schedule:', error); + reply.status(500).send({ error: 'Failed to split bonus chore' }); + } +}); + fastify.delete('/api/chore-schedules/:id', async (request, reply) => { const { id } = request.params; try { @@ -4711,6 +5030,24 @@ function completeChoreSchedule(input) { return { status: 400, error: 'Schedule is not visible' }; } + // Only people in the split can tick it (issue #407): anyone else would + // earn the chore's full Stars on top of the shares already paid out. + // The card is no longer in the pool, so the dashboard cannot reach + // this — but the API can, and a 409 closes it. + const splitIds = parseSplitUserIds(schedule.split_user_ids); + if (splitIds !== null && !splitIds.includes(Number(user_id))) { + return { status: 409, error: 'Only people in the split can complete this chore' }; + } + + // A split member's share is done once they tick it — on or after the + // split's claim date, not just today (issue #407): a half-done one-time + // split stays split past midnight, so a today-only duplicate check + // would let them tick the same share again tomorrow and pay the chore + // twice over. The per-date check below still catches a same-day tick. + if (splitIds !== null && splitDoneUserIds(schedule).includes(Number(user_id))) { + return { status: 409, error: 'This person has already completed their share of the split' }; + } + // A 'missed' row must not block completion (retroactive catch-up is // legitimate); it is replaced by the completion below (issue #72). const existing = db.prepare("SELECT id FROM chore_history WHERE chore_schedule_id = ? AND user_id = ? AND date = ? AND kind <> 'missed'").get(chore_schedule_id, user_id, date); @@ -4727,10 +5064,15 @@ function completeChoreSchedule(input) { // One transaction: the completion and the follow-ups it hands on are // written together or not at all (issue #241). + // A split share earns only that person's share: the history row carries + // their Stars, not the chore's full Stars (issue #407). The chore's + // follow-ups are still handed on per their rule, guarded per person + // against duplicates (createFollowupsForCompletion). + const earnedClams = splitShareForUser(schedule, user_id) ?? schedule.clam_value; const recordCompletion = db.transaction(() => { db.prepare("DELETE FROM chore_history WHERE chore_schedule_id = ? AND user_id = ? AND date = ? AND kind = 'missed'").run(chore_schedule_id, user_id, date); db.prepare("INSERT INTO chore_history (user_id, chore_schedule_id, date, clam_value, title, kind, approved_late) VALUES (?, ?, ?, ?, ?, 'completion', ?)") - .run(user_id, chore_schedule_id, date, schedule.clam_value, schedule.title, late ? 1 : 0); + .run(user_id, chore_schedule_id, date, earnedClams, schedule.title, late ? 1 : 0); // Pay out a pending transfer bonus (attached by the parent when moving // this chore to a kid whose day was already complete) and clear it so it @@ -4767,7 +5109,7 @@ function completeChoreSchedule(input) { userId: user_id, choreId: schedule.chore_id, scheduleId: chore_schedule_id, - clamValue: schedule.clam_value, + clamValue: earnedClams, date, }); diff --git a/server/migrations/registry.js b/server/migrations/registry.js index 9e0c16e6..028024ce 100644 --- a/server/migrations/registry.js +++ b/server/migrations/registry.js @@ -46,4 +46,5 @@ module.exports = [ { schemaId: 43, migrationPath: './migrations/schema43-pluginPermissionGrants', }, { schemaId: 44, migrationPath: './migrations/schema44-choreClaimUsers', }, { schemaId: 45, migrationPath: './migrations/schema45-weekRhythm', }, + { schemaId: 46, migrationPath: './migrations/schema46-choreSplit', }, ]; diff --git a/server/migrations/schema46-choreSplit.js b/server/migrations/schema46-choreSplit.js new file mode 100644 index 00000000..bdcf0a7e --- /dev/null +++ b/server/migrations/schema46-choreSplit.js @@ -0,0 +1,43 @@ +const context = globalThis.__HOMEGLOW_SCHEMA_MIGRATION_CONTEXT; + +if (!context || !context.db) { + throw new Error('Schema migration context is missing for migration'); +} + +const { db, schemaIdKey, targetSchemaId } = context; + +try { + console.log(`=== Starting chore split schema migration to version ${targetSchemaId} ===`); + + db.exec('BEGIN'); + try { + // Splitting a bonus chore keeps the one pool schedule: the split + // rides on it as two parallel JSON lists (issue #407), modelled on + // prize_offers.split_user_ids — `split_user_ids` who shares it and + // `split_shares` how many Stars each gets, in the same order. + // NULL is not split. The nightly return clears both along with + // the claim marker, so tomorrow it is one chore in the pool again. + const columns = db.prepare('PRAGMA table_info(chore_schedules)').all().map((c) => c.name); + if (!columns.includes('split_user_ids')) { + db.exec('ALTER TABLE chore_schedules ADD COLUMN split_user_ids TEXT'); + } + if (!columns.includes('split_shares')) { + db.exec('ALTER TABLE chore_schedules ADD COLUMN split_shares TEXT'); + } + + db.prepare('INSERT OR REPLACE INTO settings (key, value) VALUES (?, ?)').run( + schemaIdKey, + String(targetSchemaId) + ); + + db.exec('COMMIT'); + console.log(`=== Chore split schema migration completed (version ${targetSchemaId}) ===`); + } catch (migrationError) { + db.exec('ROLLBACK'); + throw migrationError; + } +} catch (error) { + console.error('=== Chore split schema migration failed ==='); + console.error('Error:', error); + throw error; +} diff --git a/server/tests/bonusChoreSplitAssign.test.js b/server/tests/bonusChoreSplitAssign.test.js new file mode 100644 index 00000000..e319fb2d --- /dev/null +++ b/server/tests/bonusChoreSplitAssign.test.js @@ -0,0 +1,695 @@ +// Splitting a bonus chore from the pool among several people, and undoing +// the split by returning the chore to the pool. A split keeps the ONE pool +// schedule: the split rides on it as `split_user_ids` / `split_shares` +// (migration schema46), so the chore keeps its definition, icon, follow-ups, +// list and history. The card shows in each selected person's column, each +// person ticks their own share, and completing writes their share to their +// history row. Back to the pool releases the whole split — but only while +// nobody has ticked: once a share is ticked the split is locked, or the +// ticked share plus the whole chore would pay out more than the chore is +// worth. The nightly return clears an untouched split, so tomorrow it is +// one chore again; a half-done one-time split stays split until every +// share is ticked, when the prune takes it. Only people in the split can +// tick it. A real HomeGlow server on a throwaway database, like +// bonusChoreReturnToPool.test.js. +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { spawn } = require('node:child_process'); +const fs = require('node:fs'); +const path = require('node:path'); +const { freePort } = require('./freePort'); + +const serverDir = path.resolve(__dirname, '..'); +const tmpDir = path.resolve(__dirname, '.tmp'); +const testDbPath = path.join(tmpDir, `bonus-chore-split-assign-${process.pid}-${Date.now()}.db`); +const keepTestArtifacts = process.env.HOMEGLOW_TEST_KEEP_ARTIFACTS === '1'; +let baseUrl; +let serverProcess; +let serverLogs = ''; + +const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); +async function api(pathname, options = {}) { + const headers = { ...(options.headers || {}) }; + if (options.body !== undefined && typeof options.body === 'string') headers['Content-Type'] = 'application/json'; + const response = await fetch(`${baseUrl}${pathname}`, { ...options, headers }); + const text = await response.text(); + let body; + try { body = text ? JSON.parse(text) : null; } catch { body = text; } + return { status: response.status, body }; +} +const post = (p, body) => api(p, { method: 'POST', body: JSON.stringify(body) }); +const patch = (p, body) => api(p, { method: 'PATCH', body: JSON.stringify(body) }); +const nightly = () => api('/api/system/backgroundTasks'); + +// The server runs in UTC here, so "today" is the UTC date. +const shift = (days) => new Date(Date.now() + days * 86400000).toISOString().slice(0, 10); +const today = shift(0); + +test.before(async () => { + fs.mkdirSync(tmpDir, { recursive: true }); + const port = await freePort(); + baseUrl = `http://127.0.0.1:${port}`; + serverProcess = spawn(process.execPath, ['index.js'], { + cwd: serverDir, + env: { + ...process.env, PORT: String(port), DB_PATH: testDbPath, TZ: 'UTC', + ENCRYPTION_KEY: Buffer.alloc(32, 9).toString('base64'), + HOMEGLOW_DISABLE_BACKGROUND_JOBS: '1', HOMEGLOW_DISABLE_CALENDAR_SYNC: '1', HOMEGLOW_DISABLE_UPDATE_CHECK: '1', + }, + stdio: ['ignore', 'pipe', 'pipe'], + }); + serverProcess.stdout.on('data', (chunk) => { serverLogs += chunk; }); + serverProcess.stderr.on('data', (chunk) => { serverLogs += chunk; }); + const start = Date.now(); + while (Date.now() - start < 30000) { + try { if ((await fetch(`${baseUrl}/api/test`)).ok) break; } catch { /* starting */ } + await delay(250); + } +}); + +const stopServer = () => new Promise((resolve) => { + if (!serverProcess || serverProcess.exitCode !== null) return resolve(); + serverProcess.once('close', resolve); + serverProcess.kill(); + setTimeout(resolve, 5000); +}); + +test.after(async () => { + await stopServer(); + if (process.exitCode && serverLogs) console.error(serverLogs.slice(-4000)); + if (!keepTestArtifacts) { + for (const suffix of ['', '-wal', '-shm']) fs.rmSync(`${testDbPath}${suffix}`, { force: true }); + } +}); + +const scheduleById = async (id) => (await api('/api/chore-schedules')).body.find((s) => s.id === id); +// In the pool means unassigned and not split: a split chore is already +// claimed, one share per person, and shows in each person's column instead. +const poolChores = async () => (await api('/api/chore-schedules')).body.filter((s) => s.user_id === null && s.visible === 1 && (s.clam_value || 0) > 0 && !s.split_user_ids); +const historyOf = async (userId, date = today) => (await api(`/api/chore-history?user_id=${userId}&date=${date}`)).body; + +let people = 0; +async function makeKid(username) { + people += 1; + return (await post('/api/users', { username: username || `Kid ${people}`, email: `kid${people}@example.com` })).body.id; +} +// A bonus chore sitting in the pool: unassigned, visible, paying Stars. +// crontab omitted for a one-time chore. `choreFields` go on the chore +// (the claimers list lives there). +async function makePoolChore({ title, clamValue, crontab = null, description = null, choreFields = {} }) { + const chore = (await post('/api/chores', { title, description, clam_value: clamValue, ...choreFields })).body.id; + const body = { chore_id: chore, user_id: null }; + if (crontab) body.crontab = crontab; + const made = await post('/api/chore-schedules', body); + assert.equal(made.status, 200, JSON.stringify(made.body)); + return { chore, scheduleId: made.body.id }; +} +async function splitSchedule(scheduleId, userIds) { + return post(`/api/chore-schedules/${scheduleId}/split-assign`, { userIds }); +} +async function completeSchedule(scheduleId, userId, date = today) { + const completed = await post('/api/chores/complete', { chore_schedule_id: scheduleId, user_id: userId, date }); + assert.equal(completed.status, 200, JSON.stringify(completed.body)); + return completed.body; +} + +test('splitting a 10-Star bonus chore between two people gives 5 each and keeps the one pool schedule', async () => { + const { scheduleId } = await makePoolChore({ title: 'Wash the car', clamValue: 10, description: 'Inside and out' }); + const emmett = await makeKid('Emmett'); + const brynn = await makeKid('Brynn'); + + const split = await splitSchedule(scheduleId, [emmett, brynn]); + assert.equal(split.status, 200, JSON.stringify(split.body)); + assert.equal(split.body.success, true); + + // The same schedule, not a copy: still unassigned, still worth its full + // Stars, carrying the split as two parallel lists in selection order. + const updated = split.body.schedule; + assert.equal(updated.id, scheduleId); + assert.equal(updated.user_id, null); + assert.equal(updated.clam_value, 10); + assert.equal(updated.title, 'Wash the car'); + assert.equal(updated.description, 'Inside and out'); + assert.equal(updated.pool_claimed_on, today); + assert.deepEqual(updated.split_user_ids, [emmett, brynn]); + assert.deepEqual(updated.split_shares, [5, 5]); + + // The schedule is still the one schedule, and it is no longer in the + // pool: it is claimed, one share per person. + const after = await scheduleById(scheduleId); + assert.equal(after.id, scheduleId); + assert.deepEqual(after.split_user_ids, [emmett, brynn]); + assert.deepEqual((await poolChores()).filter((s) => s.title === 'Wash the car'), []); +}); + +test('the remainder goes one Star each to the first people in selection order', async () => { + // Fresh kids per split: a kid holding an open bonus chore cannot take + // another one, so each case gets its own people. + const first = await makeKid('First'); + const second = await makeKid('Second'); + + // 7 over 2 is 4 and 3: the first person picked gets the extra Star. + const seven = await makePoolChore({ title: 'Rake the leaves', clamValue: 7 }); + const splitSeven = await splitSchedule(seven.scheduleId, [first, second]); + assert.equal(splitSeven.status, 200, JSON.stringify(splitSeven.body)); + assert.deepEqual(splitSeven.body.schedule.split_shares, [4, 3]); + assert.deepEqual(splitSeven.body.schedule.split_user_ids, [first, second]); + + // 10 over 3 is 4, 3 and 3. + const third = await makeKid('Third'); + const fourth = await makeKid('Fourth'); + const fifth = await makeKid('Fifth'); + const ten = await makePoolChore({ title: 'Clean the garage', clamValue: 10 }); + const splitTen = await splitSchedule(ten.scheduleId, [third, fourth, fifth]); + assert.equal(splitTen.status, 200, JSON.stringify(splitTen.body)); + assert.deepEqual(splitTen.body.schedule.split_shares, [4, 3, 3]); + assert.deepEqual(splitTen.body.schedule.split_user_ids, [third, fourth, fifth]); + + // The order given decides who gets the extra Star, not the user id: + // the second person picked first gets 4 here. + const sixth = await makeKid('Sixth'); + const seventh = await makeKid('Seventh'); + const sevenAgain = await makePoolChore({ title: 'Mop the floor', clamValue: 7 }); + const splitReversed = await splitSchedule(sevenAgain.scheduleId, [seventh, sixth]); + assert.equal(splitReversed.status, 200, JSON.stringify(splitReversed.body)); + assert.deepEqual(splitReversed.body.schedule.split_shares, [4, 3]); + assert.deepEqual(splitReversed.body.schedule.split_user_ids, [seventh, sixth]); +}); + +test('splitting needs at least two different people', async () => { + const { scheduleId } = await makePoolChore({ title: 'Dust the shelves', clamValue: 6 }); + const kid = await makeKid('Solo'); + + const one = await splitSchedule(scheduleId, [kid]); + assert.equal(one.status, 400, JSON.stringify(one.body)); + const none = await splitSchedule(scheduleId, []); + assert.equal(none.status, 400, JSON.stringify(none.body)); + const sameTwice = await splitSchedule(scheduleId, [kid, kid]); + assert.equal(sameTwice.status, 400, JSON.stringify(sameTwice.body)); + const notArray = await post(`/api/chore-schedules/${scheduleId}/split-assign`, { userIds: kid }); + assert.equal(notArray.status, 400, JSON.stringify(notArray.body)); + + // The pool chore is untouched by the rejected splits. + const after = await scheduleById(scheduleId); + assert.equal(after.user_id, null); + assert.equal(after.clam_value, 6); + assert.equal(after.split_user_ids, null); + assert.equal(after.split_shares, null); + assert.equal(after.pool_claimed_on, null); +}); + +test('splitting rejects an unknown person, an assigned chore, and a non-bonus chore', async () => { + const { scheduleId } = await makePoolChore({ title: 'Vacuum the stairs', clamValue: 4 }); + const kid = await makeKid('Real'); + const ghost = await splitSchedule(scheduleId, [kid, 999999]); + assert.equal(ghost.status, 404, JSON.stringify(ghost.body)); + + // Already assigned (claimed) is not a pool chore any more. + const claimed = await makePoolChore({ title: 'Take out trash', clamValue: 4 }); + const claimer = await makeKid('Claimer'); + const claimedRes = await post(`/api/chore-schedules/${claimed.scheduleId}/claim`, { user_id: claimer }); + assert.equal(claimedRes.status, 200, JSON.stringify(claimedRes.body)); + const assigned = await splitSchedule(claimed.scheduleId, [kid, claimer]); + assert.equal(assigned.status, 409, JSON.stringify(assigned.body)); + + // A chore worth no Stars is not a bonus chore. + const free = await makePoolChore({ title: 'Make bed', clamValue: 0 }); + const notBonus = await splitSchedule(free.scheduleId, [kid, claimer]); + assert.equal(notBonus.status, 409, JSON.stringify(notBonus.body)); + + // An unknown schedule id is a 404. + const missing = await splitSchedule(999999, [kid, claimer]); + assert.equal(missing.status, 404, JSON.stringify(missing.body)); + + // None of the rejected splits left a mark on the pool chore. + const after = await scheduleById(scheduleId); + assert.equal(after.split_user_ids, null); + assert.equal(after.pool_claimed_on, null); +}); + +test('splitting refuses when any share would be 0 Stars', async () => { + const kid = await makeKid('One'); + const other = await makeKid('Two'); + const third = await makeKid('Three'); + const fourth = await makeKid('Fourth'); + + // 3 Stars among 4 people would leave someone with 0: not a bonus chore + // for them, and a 0-Star copy would never return to the pool. + const three = await makePoolChore({ title: 'Wipe the table', clamValue: 3 }); + const tooMany = await splitSchedule(three.scheduleId, [kid, other, third, fourth]); + assert.equal(tooMany.status, 400, JSON.stringify(tooMany.body)); + assert.match(tooMany.body.error, /0 Stars/); + assert.equal((await scheduleById(three.scheduleId)).split_user_ids, null); + + // 2 Stars among 3 is the same refusal. + const two = await makePoolChore({ title: 'Feed the dog', clamValue: 2 }); + const tooManyAgain = await splitSchedule(two.scheduleId, [kid, other, third]); + assert.equal(tooManyAgain.status, 400, JSON.stringify(tooManyAgain.body)); + assert.equal((await scheduleById(two.scheduleId)).split_user_ids, null); + + // Exactly as many people as Stars is fine: 1 Star each. + const even = await makePoolChore({ title: 'Water the fern', clamValue: 3 }); + const split = await splitSchedule(even.scheduleId, [kid, other, third]); + assert.equal(split.status, 200, JSON.stringify(split.body)); + assert.deepEqual(split.body.schedule.split_shares, [1, 1, 1]); +}); + +test('splitting refuses a person the chore is not offered to', async () => { + const listed = await makeKid('Listed'); + const other = await makeKid('Other'); + const { scheduleId } = await makePoolChore({ + title: 'Wash the car', clamValue: 6, choreFields: { claim_user_ids: [listed] }, + }); + + // The claimers list is the same rule a claim follows (issue #403): + // someone not on it gets a 403 with the same code. + const refused = await splitSchedule(scheduleId, [listed, other]); + assert.equal(refused.status, 403, JSON.stringify(refused.body)); + assert.equal(refused.body.code, 'CHORE_NOT_OFFERED'); + assert.equal((await scheduleById(scheduleId)).split_user_ids, null); + + // The listed person alone cannot split either — two people are required — + // but two listed people go through. + const second = await makeKid('Second'); + const { scheduleId: secondId, chore } = await makePoolChore({ + title: 'Rake the leaves', clamValue: 6, choreFields: { claim_user_ids: [listed, second] }, + }); + assert.equal(chore > 0, true); + const split = await splitSchedule(secondId, [listed, second]); + assert.equal(split.status, 200, JSON.stringify(split.body)); + assert.deepEqual(split.body.schedule.split_user_ids, [listed, second]); +}); + +test('splitting rejects a person who already has an open bonus chore', async () => { + const first = await makePoolChore({ title: 'Sweep the porch', clamValue: 2 }); + const second = await makePoolChore({ title: 'Water the plants', clamValue: 6 }); + const greedy = await makeKid('Greedy'); + const other = await makeKid('Other'); + const claimed = await post(`/api/chore-schedules/${first.scheduleId}/claim`, { user_id: greedy }); + assert.equal(claimed.status, 200, JSON.stringify(claimed.body)); + + // Greedy's outstanding bonus chore blocks the split for everyone in it. + const blocked = await splitSchedule(second.scheduleId, [greedy, other]); + assert.equal(blocked.status, 409, JSON.stringify(blocked.body)); + assert.match(blocked.body.error, /Greedy/); + // Nothing was split and the pool chore is still there. + assert.equal((await scheduleById(second.scheduleId)).split_user_ids, null); + assert.deepEqual((await poolChores()).filter((s) => s.title === 'Water the plants').map((s) => s.id), [second.scheduleId]); + + // Once Greedy's first chore is done today, the same split goes through. + await completeSchedule(first.scheduleId, greedy); + const split = await splitSchedule(second.scheduleId, [greedy, other]); + assert.equal(split.status, 200, JSON.stringify(split.body)); + assert.deepEqual(split.body.schedule.split_shares, [3, 3]); +}); + +test('each person ticks their own share and earns only that share', async () => { + const { scheduleId } = await makePoolChore({ title: 'Polish the silver', clamValue: 7 }); + const emmett = await makeKid('Emmett'); + const brynn = await makeKid('Brynn'); + const split = await splitSchedule(scheduleId, [emmett, brynn]); + assert.equal(split.status, 200, JSON.stringify(split.body)); + assert.deepEqual(split.body.schedule.split_shares, [4, 3]); + + // The same schedule id, ticked once per person: each history row carries + // that person's share, not the chore's full Stars. + await completeSchedule(scheduleId, emmett); + const emmettHistory = await historyOf(emmett); + assert.equal(emmettHistory.length, 1); + assert.equal(emmettHistory[0].chore_schedule_id, scheduleId); + assert.equal(emmettHistory[0].clam_value, 4); + assert.equal(emmettHistory[0].kind, 'completion'); + + await completeSchedule(scheduleId, brynn); + const brynnHistory = await historyOf(brynn); + assert.equal(brynnHistory.length, 1); + assert.equal(brynnHistory[0].chore_schedule_id, scheduleId); + assert.equal(brynnHistory[0].clam_value, 3); + + // The chore itself is unchanged: one schedule, still worth 7 Stars. + const after = await scheduleById(scheduleId); + assert.equal(after.clam_value, 7); + assert.deepEqual(after.split_user_ids, [emmett, brynn]); +}); + +test('a split share counts as an outstanding bonus chore', async () => { + const { scheduleId } = await makePoolChore({ title: 'Wash the windows', clamValue: 6 }); + const emmett = await makeKid('Emmett'); + const brynn = await makeKid('Brynn'); + const split = await splitSchedule(scheduleId, [emmett, brynn]); + assert.equal(split.status, 200, JSON.stringify(split.body)); + + // Emmett is holding a share, so he cannot claim another bonus chore + // and cannot be split into another one either. + const other = await makePoolChore({ title: 'Mop the floor', clamValue: 4 }); + const claimBlocked = await post(`/api/chore-schedules/${other.scheduleId}/claim`, { user_id: emmett }); + assert.equal(claimBlocked.status, 409, JSON.stringify(claimBlocked.body)); + const third = await makePoolChore({ title: 'Dust the shelves', clamValue: 4 }); + const splitBlocked = await splitSchedule(third.scheduleId, [emmett, brynn]); + assert.equal(splitBlocked.status, 409, JSON.stringify(splitBlocked.body)); + + // Once Emmett ticks his share, he is free again — Brynn's open share + // does not block him. + await completeSchedule(scheduleId, emmett); + const claim = await post(`/api/chore-schedules/${other.scheduleId}/claim`, { user_id: emmett }); + assert.equal(claim.status, 200, JSON.stringify(claim.body)); + assert.equal((await scheduleById(other.scheduleId)).user_id, emmett); +}); + +test('back to the pool releases the whole split', async () => { + const { scheduleId } = await makePoolChore({ title: 'Wash the windows', clamValue: 10 }); + const emmett = await makeKid('Emmett'); + const brynn = await makeKid('Brynn'); + const calla = await makeKid('Calla'); + const split = await splitSchedule(scheduleId, [emmett, brynn, calla]); + assert.equal(split.status, 200, JSON.stringify(split.body)); + assert.deepEqual(split.body.schedule.split_shares, [4, 3, 3]); + + // Transferring the chore back to the pool (the Transfer dialog's pool + // target: user_id 0) releases the whole split at once — one child + // sending it back does not leave the others holding their parts. + const returned = await patch(`/api/chore-schedules/${scheduleId}`, { user_id: 0, visible: 1 }); + assert.equal(returned.status, 200, JSON.stringify(returned.body)); + assert.deepEqual(returned.body, { success: true }); + + // One pool chore again, worth its full Stars, with no split on it. + const after = await scheduleById(scheduleId); + assert.equal(after.user_id, null); + assert.equal(after.pool_claimed_on, null); + assert.equal(after.split_user_ids, null); + assert.equal(after.split_shares, null); + assert.equal(after.clam_value, 10); + assert.deepEqual((await poolChores()).filter((s) => s.title === 'Wash the windows').map((s) => s.id), [scheduleId]); + + // ...and it can be claimed or re-split from the pool again. + const reclaimed = await post(`/api/chore-schedules/${scheduleId}/claim`, { user_id: brynn }); + assert.equal(reclaimed.status, 200, JSON.stringify(reclaimed.body)); + assert.equal((await scheduleById(scheduleId)).user_id, brynn); +}); + +test('a split locks once a share is ticked: it cannot be released or handed to one person', async () => { + const { scheduleId } = await makePoolChore({ title: 'Polish the silver', clamValue: 7 }); + const emmett = await makeKid('Emmett'); + const brynn = await makeKid('Brynn'); + const calla = await makeKid('Calla'); + const split = await splitSchedule(scheduleId, [emmett, brynn]); + assert.equal(split.status, 200, JSON.stringify(split.body)); + assert.deepEqual(split.body.schedule.split_shares, [4, 3]); + + // Emmett does his share today; its Stars are earned. + await completeSchedule(scheduleId, emmett); + assert.equal((await historyOf(emmett))[0].clam_value, 4); + + // Brynn sending the chore back to the pool would put the whole 7-Star + // chore back up for grabs on top of Emmett's 4: refused. + const returned = await patch(`/api/chore-schedules/${scheduleId}`, { user_id: 0, visible: 1 }); + assert.equal(returned.status, 409, JSON.stringify(returned.body)); + // Handing it to one person is the same overpay: refused too. + const handed = await patch(`/api/chore-schedules/${scheduleId}`, { user_id: calla, visible: 1 }); + assert.equal(handed.status, 409, JSON.stringify(handed.body)); + + // The split is untouched by the refused moves, and the ticked share + // stays earned; Brynn's share is still open. + const after = await scheduleById(scheduleId); + assert.equal(after.user_id, null); + assert.deepEqual(after.split_user_ids, [emmett, brynn]); + assert.deepEqual(after.split_shares, [4, 3]); + assert.equal((await historyOf(emmett)).length, 1); + assert.equal((await historyOf(emmett))[0].clam_value, 4); + assert.equal((await historyOf(brynn)).length, 0); +}); + +test('a split nobody has ticked can still be handed to one person', async () => { + const { scheduleId } = await makePoolChore({ title: 'Wash the windows', clamValue: 10 }); + const emmett = await makeKid('Emmett'); + const brynn = await makeKid('Brynn'); + const calla = await makeKid('Calla'); + const split = await splitSchedule(scheduleId, [emmett, brynn]); + assert.equal(split.status, 200, JSON.stringify(split.body)); + + // Before anyone has ticked, handing the whole chore to one person is + // fine: nothing has been paid out yet. + const handed = await patch(`/api/chore-schedules/${scheduleId}`, { user_id: calla, visible: 1 }); + assert.equal(handed.status, 200, JSON.stringify(handed.body)); + const after = await scheduleById(scheduleId); + assert.equal(after.user_id, calla); + assert.equal(after.split_user_ids, null); + assert.equal(after.split_shares, null); + assert.equal(after.clam_value, 10); +}); + +test('only people in the split can tick it', async () => { + const { scheduleId } = await makePoolChore({ title: 'Sweep the porch', clamValue: 10 }); + const ava = await makeKid('Ava'); + const ben = await makeKid('Ben'); + const cal = await makeKid('Cal'); + const split = await splitSchedule(scheduleId, [ava, ben]); + assert.equal(split.status, 200, JSON.stringify(split.body)); + assert.deepEqual(split.body.schedule.split_shares, [5, 5]); + + // Cal is not in the split: ticking it would earn him the full 10 Stars + // on top of Ava's and Ben's shares. Refused, with nothing recorded. + const refused = await post('/api/chores/complete', { chore_schedule_id: scheduleId, user_id: cal, date: today }); + assert.equal(refused.status, 409, JSON.stringify(refused.body)); + assert.match(refused.body.error, /Only people in the split/); + assert.equal((await historyOf(cal)).length, 0); + + // The split members can still tick their own shares. + await completeSchedule(scheduleId, ava); + assert.equal((await historyOf(ava))[0].clam_value, 5); + await completeSchedule(scheduleId, ben); + assert.equal((await historyOf(ben))[0].clam_value, 5); +}); + +test('the nightly return clears the split, so tomorrow it is one chore again', async () => { + // A one-time split... + const { scheduleId } = await makePoolChore({ title: 'Wash the car', clamValue: 6 }); + const emmett = await makeKid('Emmett'); + const brynn = await makeKid('Brynn'); + const split = await splitSchedule(scheduleId, [emmett, brynn]); + assert.equal(split.status, 200, JSON.stringify(split.body)); + + // ...and a recurring split, which the one-time reset and the claimed + // recurring return both miss: it is unassigned, so neither catches it. + // Fresh kids here: the first split already has Emmett and Brynn holding + // an open share, so they cannot take another one. + const recurringEmmett = await makeKid('Recurring Emmett'); + const recurringBrynn = await makeKid('Recurring Brynn'); + const recurring = await makePoolChore({ title: 'Take out trash', clamValue: 4, crontab: '0 0 * * *' }); + const recurringSplit = await splitSchedule(recurring.scheduleId, [recurringEmmett, recurringBrynn]); + assert.equal(recurringSplit.status, 200, JSON.stringify(recurringSplit.body)); + + await nightly(); + + for (const id of [scheduleId, recurring.scheduleId]) { + const after = await scheduleById(id); + assert.equal(after.user_id, null); + assert.equal(after.pool_claimed_on, null); + assert.equal(after.split_user_ids, null); + assert.equal(after.split_shares, null); + } + assert.deepEqual((await poolChores()).filter((s) => s.id === scheduleId || s.id === recurring.scheduleId).map((s) => s.id).sort(), [scheduleId, recurring.scheduleId].sort()); + + // A share ticked before the return stays earned — and for a one-time + // split, the split itself stays too: with one share ticked and the + // other still open, returning it to the pool would put the whole + // chore back up for grabs and let the prune take it as "done" on the + // one ticked share. + const third = await makePoolChore({ title: 'Sweep the porch', clamValue: 6 }); + await splitSchedule(third.scheduleId, [emmett, brynn]); + await completeSchedule(third.scheduleId, emmett); + await nightly(); + assert.equal((await historyOf(emmett)).filter((h) => h.chore_schedule_id === third.scheduleId).length, 1); + assert.equal((await historyOf(emmett)).filter((h) => h.chore_schedule_id === third.scheduleId)[0].clam_value, 3); + const thirdAfter = await scheduleById(third.scheduleId); + assert.deepEqual(thirdAfter.split_user_ids, [emmett, brynn]); + assert.deepEqual(thirdAfter.split_shares, [3, 3]); + assert.equal(thirdAfter.pool_claimed_on, today); + assert.equal(thirdAfter.user_id, null); + + // A recurring split is different: tomorrow is a new day of the chore, + // worth its full Stars again, so a ticked share does not hold it back + // from returning. + const recurringHalf = await makePoolChore({ title: 'Feed the cat', clamValue: 4, crontab: '0 0 * * *' }); + await splitSchedule(recurringHalf.scheduleId, [recurringEmmett, recurringBrynn]); + await completeSchedule(recurringHalf.scheduleId, recurringEmmett); + await nightly(); + const recurringHalfAfter = await scheduleById(recurringHalf.scheduleId); + assert.equal(recurringHalfAfter.split_user_ids, null); + assert.equal(recurringHalfAfter.pool_claimed_on, null); + assert.equal((await historyOf(recurringEmmett)).filter((h) => h.chore_schedule_id === recurringHalf.scheduleId).length, 1); +}); + +test('the nightly prune only takes a split once every share is ticked', async () => { + const emmett = await makeKid('Emmett'); + const brynn = await makeKid('Brynn'); + + // Both shares ticked: the one-time chore is done, so the nightly prune + // takes the schedule (and its chore) like any completed one-time chore. + const done = await makePoolChore({ title: 'Wash the car', clamValue: 6 }); + await splitSchedule(done.scheduleId, [emmett, brynn]); + await completeSchedule(done.scheduleId, emmett); + await completeSchedule(done.scheduleId, brynn); + await nightly(); + assert.equal(await scheduleById(done.scheduleId), undefined); + + // Only one share ticked: the schedule stays, and the split stays with + // it — the other share is still open, so returning it to the pool + // would let the next night prune it as "done" on the one ticked share. + const halfDone = await makePoolChore({ title: 'Take out trash', clamValue: 6 }); + await splitSchedule(halfDone.scheduleId, [emmett, brynn]); + await completeSchedule(halfDone.scheduleId, emmett); + await nightly(); + const after = await scheduleById(halfDone.scheduleId); + assert.equal(after.user_id, null); + assert.deepEqual(after.split_user_ids, [emmett, brynn]); + assert.deepEqual(after.split_shares, [3, 3]); + assert.equal(after.clam_value, 6); + assert.deepEqual((await poolChores()).filter((s) => s.id === halfDone.scheduleId).map((s) => s.id), []); + // ...and the ticked share is still earned, by schedule if not by id: + // the history row survives the night. + assert.equal((await historyOf(emmett)).filter((h) => h.chore_schedule_id === halfDone.scheduleId).length, 1); + + // Night 2, still untouched by Brynn: the split survives again, with + // Brynn's share still open — it is not pruned and not back in the pool. + await nightly(); + const nightTwo = await scheduleById(halfDone.scheduleId); + assert.deepEqual(nightTwo.split_user_ids, [emmett, brynn]); + assert.deepEqual((await poolChores()).filter((s) => s.id === halfDone.scheduleId).map((s) => s.id), []); + + // Once Brynn ticks her share too, the next night prunes the schedule + // (and its chore) like any completed one-time chore. + await completeSchedule(halfDone.scheduleId, brynn); + await nightly(); + assert.equal(await scheduleById(halfDone.scheduleId), undefined); +}); + +test('returning a non-split chore to the pool is unchanged', async () => { + const { scheduleId } = await makePoolChore({ title: 'Sort the laundry', clamValue: 2 }); + const kid = await makeKid('Mover'); + const claimed = await post(`/api/chore-schedules/${scheduleId}/claim`, { user_id: kid }); + assert.equal(claimed.status, 200, JSON.stringify(claimed.body)); + + const returned = await patch(`/api/chore-schedules/${scheduleId}`, { user_id: 0, visible: 1 }); + assert.equal(returned.status, 200, JSON.stringify(returned.body)); + assert.deepEqual(returned.body, { success: true }); + const after = await scheduleById(scheduleId); + assert.equal(after.user_id, null); + assert.equal(after.pool_claimed_on, null); + // ...and it can be claimed again afterwards. + await post(`/api/chore-schedules/${scheduleId}/claim`, { user_id: kid }); + assert.equal((await scheduleById(scheduleId)).user_id, kid); + await nightly(); + assert.equal((await scheduleById(scheduleId)).user_id, null); +}); + +test('a member cannot tick the same share twice, even on a later date', async () => { + const { scheduleId } = await makePoolChore({ title: 'Wash the car', clamValue: 10 }); + const ava = await makeKid('Ava'); + const ben = await makeKid('Ben'); + const split = await splitSchedule(scheduleId, [ava, ben]); + assert.equal(split.status, 200, JSON.stringify(split.body)); + assert.deepEqual(split.body.schedule.split_shares, [5, 5]); + + // Ava ticks her share today. + await completeSchedule(scheduleId, ava); + assert.equal((await historyOf(ava)).filter((h) => h.chore_schedule_id === scheduleId).length, 1); + + // The row says so: Ava's share is done, Ben's is still open. + const afterTick = await scheduleById(scheduleId); + assert.deepEqual(afterTick.split_done_user_ids, [ava]); + + // Tomorrow she ticks again: refused — the share is done since the split + // was made, not just for today. Nothing more is paid out. + const tomorrow = shift(1); + const again = await post('/api/chores/complete', { chore_schedule_id: scheduleId, user_id: ava, date: tomorrow }); + assert.equal(again.status, 409, JSON.stringify(again.body)); + assert.match(again.body.error, /already completed their share/); + assert.equal((await historyOf(ava)).filter((h) => h.chore_schedule_id === scheduleId).length, 1); + assert.equal((await historyOf(ava, tomorrow)).length, 0); + + // Ben's share is still open: he can tick tomorrow, for his 5 only. + const benTomorrow = await post('/api/chores/complete', { chore_schedule_id: scheduleId, user_id: ben, date: tomorrow }); + assert.equal(benTomorrow.status, 200, JSON.stringify(benTomorrow.body)); + assert.equal((await historyOf(ben, tomorrow))[0].clam_value, 5); + assert.deepEqual((await scheduleById(scheduleId)).split_done_user_ids, [ava, ben]); +}); + +test('claiming a split chore is refused', async () => { + const { scheduleId } = await makePoolChore({ title: 'Sweep the porch', clamValue: 10 }); + const ava = await makeKid('Ava'); + const ben = await makeKid('Ben'); + const cal = await makeKid('Cal'); + const split = await splitSchedule(scheduleId, [ava, ben]); + assert.equal(split.status, 200, JSON.stringify(split.body)); + + // A stale display still showing it in the pool cannot claim it on top + // of the split: Cal would hold a chore he cannot tick. + const claimed = await post(`/api/chore-schedules/${scheduleId}/claim`, { user_id: cal }); + assert.equal(claimed.status, 409, JSON.stringify(claimed.body)); + assert.match(claimed.body.error, /already split/); + + // The split is untouched, and Cal holds nothing. + const after = await scheduleById(scheduleId); + assert.equal(after.user_id, null); + assert.deepEqual(after.split_user_ids, [ava, ben]); + assert.deepEqual(after.split_shares, [5, 5]); + assert.equal((await historyOf(cal)).length, 0); + + // The split members can still tick their own shares. + await completeSchedule(scheduleId, ava); + assert.equal((await historyOf(ava))[0].clam_value, 5); +}); + +test('an admin PATCH that resends the same user_id keeps the split', async () => { + const { scheduleId } = await makePoolChore({ title: 'Wash the windows', clamValue: 10 }); + const ava = await makeKid('Ava'); + const ben = await makeKid('Ben'); + const split = await splitSchedule(scheduleId, [ava, ben]); + assert.equal(split.status, 200, JSON.stringify(split.body)); + + // The schedule dialog sends user_id with every save: resending the + // split's own (null, the pool) while changing the due time is not a + // move, so the split survives the save. + const saved = await patch(`/api/chore-schedules/${scheduleId}`, { user_id: null, visible: 1, due_time: '18:00' }); + assert.equal(saved.status, 200, JSON.stringify(saved.body)); + const afterSave = await scheduleById(scheduleId); + assert.deepEqual(afterSave.split_user_ids, [ava, ben]); + assert.deepEqual(afterSave.split_shares, [5, 5]); + assert.equal(afterSave.pool_claimed_on, today); + assert.equal(afterSave.due_time, '18:00'); + + // The same save once a share is ticked is not refused either — nobody + // moved it — and the split still stands. + await completeSchedule(scheduleId, ava); + const savedAgain = await patch(`/api/chore-schedules/${scheduleId}`, { user_id: null, visible: 1, due_time: '19:00' }); + assert.equal(savedAgain.status, 200, JSON.stringify(savedAgain.body)); + const afterSecondSave = await scheduleById(scheduleId); + assert.deepEqual(afterSecondSave.split_user_ids, [ava, ben]); + assert.equal(afterSecondSave.due_time, '19:00'); + + // A real move after a tick is still refused: the lock is about moving, + // not about saving. + const moved = await patch(`/api/chore-schedules/${scheduleId}`, { user_id: 0, visible: 1 }); + assert.equal(moved.status, 409, JSON.stringify(moved.body)); +}); + +test('splitting an already-split chore is refused', async () => { + const { scheduleId } = await makePoolChore({ title: 'Mop the floor', clamValue: 10 }); + const ava = await makeKid('Ava'); + const ben = await makeKid('Ben'); + const cal = await makeKid('Cal'); + const split = await splitSchedule(scheduleId, [ava, ben]); + assert.equal(split.status, 200, JSON.stringify(split.body)); + + // A stale display still showing it in the pool cannot split it again: + // the new split would reset the claim date and reopen ticked shares. + const again = await splitSchedule(scheduleId, [ava, cal]); + assert.equal(again.status, 409, JSON.stringify(again.body)); + assert.match(again.body.error, /already split/); + + const after = await scheduleById(scheduleId); + assert.deepEqual(after.split_user_ids, [ava, ben]); + assert.deepEqual(after.split_shares, [5, 5]); + assert.equal(after.pool_claimed_on, today); +});