From 8b5d6e463a7b8356e3085dc3c5065e323a138109 Mon Sep 17 00:00:00 2001 From: adamecker Date: Sat, 28 Nov 2026 20:51:31 +0000 Subject: [PATCH 1/5] Split a bonus chore's Stars among several people MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Long-press (or right-click) a bonus chore card to open a picker of household users. Tick at least two people and each gets their share of the chore's Stars β€” floor(N/k) each, with the leftover Stars going one each to the first people picked. Confirming creates one copy of the chore per person, worth that person's share, and consumes the pool chore; each copy carries a shared split_group_id so the split can be undone by transferring any part back to the pool (every still-open part comes back as its own pool chore). - POST /api/chore-schedules/:id/split-assign validates the pool bonus chore, the users, and the one-open-bonus rule, then creates the copies in a transaction. - PATCH returning a split part to the pool returns all still-open parts of that split group; completed parts stay completed. - Migration schema44 adds chore_schedules.split_group_id. - Client: press-and-hold (touch and mouse) on bonus cards via the shared createPressHold util, a picker dialog with a live per-person preview, and the split result shown in the dialog. - Tests: 8 new server tests (splits, remainders, validation, the one-open-bonus rule, group return on undo) and splitStars unit tests. Generated with Muse AI πŸ€– --- client/src/components/ChoreWidget.jsx | 209 +++++++++++++- client/src/i18n/locales/en/chores.json | 10 +- client/src/i18n/locales/es/chores.json | 10 +- client/src/utils/choreHelpers.js | 15 + client/src/utils/choreHelpers.test.js | 32 ++- server/index.js | 195 ++++++++++++- server/migrations/registry.js | 1 + server/migrations/schema46-splitGroupId.js | 42 +++ server/tests/bonusChoreSplitAssign.test.js | 309 +++++++++++++++++++++ 9 files changed, 816 insertions(+), 7 deletions(-) create mode 100644 server/migrations/schema46-splitGroupId.js create mode 100644 server/tests/bonusChoreSplitAssign.test.js diff --git a/client/src/components/ChoreWidget.jsx b/client/src/components/ChoreWidget.jsx index 506e1aa1..d469548b 100644 --- a/client/src/components/ChoreWidget.jsx +++ b/client/src/components/ChoreWidget.jsx @@ -41,7 +41,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 } 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 +173,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 }); @@ -817,6 +825,51 @@ 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 hands each person their own copy and consumes + // the pool chore. The result stays in the dialog β€” there is no toast + // system on the dashboard β€” until Done closes it. + const openSplitDialog = (schedule) => { + if (!schedule) 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 created = response.data?.schedules || []; + await fetchData(); + const parts = created.map((row) => ({ + username: users.find((u) => u.id === row.user_id)?.username || '?', + stars: row.clam_value, + })); + 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) { @@ -925,6 +978,61 @@ 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) => { + 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) => { + // 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). @@ -1706,12 +1814,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' }} > @@ -2182,6 +2301,92 @@ 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')} + + + {users.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; + 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 */} 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..6ad0dda5 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 } 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. @@ -460,3 +460,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/server/index.js b/server/index.js index d06484f6..06de8dff 100644 --- a/server/index.js +++ b/server/index.js @@ -3891,7 +3891,7 @@ 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_group_id FROM chore_schedules WHERE id = ?').get(id); if (!existingSchedule) { return reply.status(404).send({ error: 'Schedule not found' }); } @@ -4069,6 +4069,21 @@ fastify.patch('/api/chore-schedules/:id', async (request, reply) => { } } + // Returning one part of a split to the bonus pool returns every + // still-open part of that split with it β€” that is how a split is + // undone. The update above already returned this schedule itself; + // the rest of its group goes here, and losing a chore re-checks each + // holder's daily bonus the same way the reassignment above does. + let returnedSplitScheduleIds = []; + if (user_id !== undefined && !user_id && existingSchedule.user_id !== null && existingSchedule.split_group_id) { + const today = getTodayLocalDateString(); + const returned = returnSplitGroupToPool(existingSchedule.split_group_id, Number(id), today); + returnedSplitScheduleIds = returned.map((row) => row.id); + for (const row of returned) { + awardDailyRegularBonusIfDue(row.user_id, today); + } + } + // No longer any-day: its open card goes, rather than staying on as a // one-time chore due every day (dropOpenAnyDayCards). Below, the new // timing makes its own card if it needs one. @@ -4104,7 +4119,9 @@ fastify.patch('/api/chore-schedules/:id', async (request, reply) => { spawnStickyChildren(getTodayLocalDateString(), [Number(id)]); } - return { success: true }; + return returnedSplitScheduleIds.length > 0 + ? { success: true, returnedSplitScheduleIds } + : { success: true }; } catch (error) { console.error('Error updating schedule:', error); reply.status(500).send({ error: 'Failed to update schedule' }); @@ -4212,6 +4229,180 @@ 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)); +} + +// Undoing a split: returning one part of a split to the bonus pool returns +// every still-open part of that split with it, each as its own pool chore +// worth its split Stars. A part already completed today stays put β€” its +// Stars are already earned and cannot come back. Only the other members +// are touched here; the schedule the caller is already returning is +// handled by the PATCH itself. +function returnSplitGroupToPool(splitGroupId, excludeScheduleId, today) { + if (!splitGroupId) return []; + const members = db.prepare(` + SELECT cs.id, cs.user_id + FROM chore_schedules cs + WHERE cs.split_group_id = ? AND cs.id != ? AND cs.user_id IS NOT NULL AND cs.visible = 1 + `).all(splitGroupId, excludeScheduleId); + const returned = []; + const reset = db.prepare('UPDATE chore_schedules SET user_id = NULL, pool_claimed_on = NULL, transfer_bonus_clams = 0 WHERE id = ?'); + for (const member of members) { + const completed = db.prepare(` + SELECT 1 FROM chore_history + WHERE chore_schedule_id = ? AND user_id = ? AND date = ? AND kind = 'completion' + `).get(member.id, member.user_id, today); + if (completed) continue; + reset.run(member.id); + returned.push({ id: member.id, user_id: member.user_id }); + } + return returned; +} + +// Splitting a bonus chore from the pool among several people. Each person +// gets their own copy of the chore β€” same title and description, their +// share of the Stars on its own chores row β€” assigned to them, so the +// existing single-user completion and claim logic applies unchanged. The +// copies carry the claim marker (pool_claimed_on) and the split marker +// (split_group_id, one uuid for the whole split), so the nightly cleanup +// treats them like claimed bonus chores and a transfer of any part back +// to the pool returns the still-open parts with it. The original pool +// schedule is deleted; its chores row, now orphaned, is pruned by the +// nightly cleanup. At least two people are required β€” one person claiming +// is the claim route, not a split. +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 + 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' }); + } + 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' }); + } + + // 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(); + const now = new Date(); + for (const userId of parsedUserIds) { + 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); + const completedToday = new Set(db.prepare(` + SELECT chore_schedule_id FROM chore_history + WHERE user_id = ? AND date = ? AND kind = 'completion' + `).all(userId, today).map((row) => row.chore_schedule_id)); + 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 cronFiresOnDate(row.crontab, today); + } catch { + return false; + } + }); + if (outstanding) { + 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); + const splitGroupId = crypto.randomUUID(); + // One copy per person, all or none: a split never leaves half the + // family assigned. + const createCopies = db.transaction(() => { + const createdIds = []; + for (let i = 0; i < parsedUserIds.length; i++) { + const choreInfo = db.prepare('INSERT INTO chores (title, description, clam_value, icon) VALUES (?, ?, ?, ?)') + .run(schedule.title, schedule.description, amounts[i], schedule.icon); + const scheduleInfo = db.prepare(` + INSERT INTO chore_schedules + (chore_id, user_id, crontab, duration, visible, interval, parent_schedule_id, + due_time, sound, sound_enabled, reminder_interval_minutes, due_date, + transferable, can_snooze, snoozed_until, expire_minutes, pool_claimed_on, split_group_id) + VALUES (?, ?, ?, ?, 1, ?, NULL, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + `).run( + choreInfo.lastInsertRowid, parsedUserIds[i], schedule.crontab, schedule.duration, + schedule.interval, schedule.due_time, schedule.sound, schedule.sound_enabled, + schedule.reminder_interval_minutes, schedule.due_date, schedule.transferable, + schedule.can_snooze, schedule.snoozed_until, schedule.expire_minutes, + today, splitGroupId + ); + createdIds.push(scheduleInfo.lastInsertRowid); + } + db.prepare('DELETE FROM chore_schedules WHERE id = ?').run(id); + return createdIds; + }); + const createdIds = createCopies(); + // Splitting assigns someone's set the same way claiming does: the + // daily "all regular chores done" bonus is re-checked for each new + // owner, as the claim route does. + for (const userId of parsedUserIds) { + awardDailyRegularBonusIfDue(userId, today); + } + const created = db.prepare(` + SELECT cs.*, c.title, c.description, c.clam_value, c.icon + FROM chore_schedules cs JOIN chores c ON cs.chore_id = c.id + WHERE cs.id IN (${createdIds.map(() => '?').join(',')}) + `).all(...createdIds); + const byId = new Map(created.map((row) => [row.id, row])); + return { success: true, splitGroupId, schedules: createdIds.map((createdId) => byId.get(createdId)) }; + } 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 { diff --git a/server/migrations/registry.js b/server/migrations/registry.js index 9e0c16e6..699cf8dd 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-splitGroupId', }, ]; diff --git a/server/migrations/schema46-splitGroupId.js b/server/migrations/schema46-splitGroupId.js new file mode 100644 index 00000000..6a5f42c7 --- /dev/null +++ b/server/migrations/schema46-splitGroupId.js @@ -0,0 +1,42 @@ +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 split group marker schema migration to version ${targetSchemaId} ===`); + + db.exec('BEGIN'); + try { + // Splitting a bonus chore from the pool hands each selected person + // their own copy, worth their share of the Stars. The copies share + // one marker (split_group_id, a uuid minted by the split route) so + // the whole split can be found again later: transferring any one + // part back to the bonus pool returns every still-open part with + // it, which is how a split is undone. Parts already completed stay + // put β€” their Stars are already earned. NULL for every schedule + // that did not come out of a split. + const columns = db.prepare('PRAGMA table_info(chore_schedules)').all().map((c) => c.name); + if (!columns.includes('split_group_id')) { + db.exec('ALTER TABLE chore_schedules ADD COLUMN split_group_id TEXT'); + } + + db.prepare('INSERT OR REPLACE INTO settings (key, value) VALUES (?, ?)').run( + schemaIdKey, + String(targetSchemaId) + ); + + db.exec('COMMIT'); + console.log(`=== Split group marker schema migration completed (version ${targetSchemaId}) ===`); + } catch (migrationError) { + db.exec('ROLLBACK'); + throw migrationError; + } +} catch (error) { + console.error('=== Split group marker 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..49b41cb9 --- /dev/null +++ b/server/tests/bonusChoreSplitAssign.test.js @@ -0,0 +1,309 @@ +// Splitting a bonus chore from the pool among several people, and undoing +// the split by returning one part to the pool. A split hands each selected +// person their own copy of the chore β€” same title and description, their +// share of the Stars β€” and consumes the original pool schedule. The copies +// share one marker (split_group_id, migration schema44), so returning any +// one part to the pool returns every still-open part with it; a part +// already completed stays put, its Stars already earned. 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); +const poolChores = async () => (await api('/api/chore-schedules')).body.filter((s) => s.user_id === null && s.visible === 1 && (s.clam_value || 0) > 0); + +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. +async function makePoolChore({ title, clamValue, crontab = null, description = null }) { + const chore = (await post('/api/chores', { title, description, clam_value: clamValue })).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 consumes the pool chore', 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); + assert.equal(typeof split.body.splitGroupId, 'string'); + assert.equal(split.body.schedules.length, 2); + + // Each person has their own copy, worth their share, in selection order. + const [first, second] = split.body.schedules; + assert.equal(first.user_id, emmett); + assert.equal(first.clam_value, 5); + assert.equal(first.title, 'Wash the car'); + assert.equal(first.description, 'Inside and out'); + assert.equal(first.pool_claimed_on, today); + assert.equal(second.user_id, brynn); + assert.equal(second.clam_value, 5); + assert.equal(second.pool_claimed_on, today); + // One shared marker for the whole split. + assert.equal(first.split_group_id, split.body.splitGroupId); + assert.equal(second.split_group_id, split.body.splitGroupId); + assert.equal(first.split_group_id, second.split_group_id); + + // The original pool schedule is gone: it is not in the pool any more, + // and the list no longer carries it at all. + assert.equal(await scheduleById(scheduleId), undefined); + 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.schedules.map((s) => s.clam_value), [4, 3]); + + // 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.schedules.map((s) => s.clam_value), [4, 3, 3]); + assert.deepEqual(splitTen.body.schedules.map((s) => s.user_id), [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.schedules.map((s) => [s.user_id, s.clam_value]), [[seventh, 4], [sixth, 3]]); +}); + +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); +}); + +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)); +}); + +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 created and the pool chore is still there. + assert.equal((await scheduleById(second.scheduleId)).user_id, 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.schedules.map((s) => s.clam_value), [3, 3]); +}); + +test('returning one split part to the pool returns all still-open parts', 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)); + const [emmettPart, brynnPart, callaPart] = split.body.schedules; + assert.deepEqual(split.body.schedules.map((s) => s.clam_value), [4, 3, 3]); + + // Transferring Emmett's part back to the pool (the Transfer dialog's + // pool target: user_id 0) returns Brynn's and Calla's open parts too. + const returned = await patch(`/api/chore-schedules/${emmettPart.id}`, { user_id: 0, visible: 1 }); + assert.equal(returned.status, 200, JSON.stringify(returned.body)); + assert.deepEqual(returned.body.returnedSplitScheduleIds.sort(), [brynnPart.id, callaPart.id].sort()); + + // Each part is its own pool chore now, worth its split Stars β€” the + // split is undone without recombining anything. + for (const part of [emmettPart, brynnPart, callaPart]) { + const after = await scheduleById(part.id); + assert.equal(after.user_id, null); + assert.equal(after.pool_claimed_on, null); + } + const pool = (await poolChores()).filter((s) => s.title === 'Wash the windows'); + assert.deepEqual(pool.map((s) => s.clam_value).sort(), [3, 3, 4]); + assert.deepEqual(pool.map((s) => s.split_group_id), [split.body.splitGroupId, split.body.splitGroupId, split.body.splitGroupId]); + + // ...and the parts can be claimed or re-split from the pool again. + const reclaimed = await post(`/api/chore-schedules/${brynnPart.id}/claim`, { user_id: brynn }); + assert.equal(reclaimed.status, 200, JSON.stringify(reclaimed.body)); + assert.equal((await scheduleById(brynnPart.id)).user_id, brynn); +}); + +test('a completed split part is not returned to the pool', 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)); + const [emmettPart, brynnPart] = split.body.schedules; + assert.deepEqual(split.body.schedules.map((s) => s.clam_value), [4, 3]); + + // Emmett does his part today; its Stars are earned. + await completeSchedule(emmettPart.id, emmett); + + // Brynn decides not to help and sends her part back. Only hers moves: + // Emmett's completed part stays assigned to him. + const returned = await patch(`/api/chore-schedules/${brynnPart.id}`, { user_id: 0, visible: 1 }); + assert.equal(returned.status, 200, JSON.stringify(returned.body)); + assert.deepEqual(returned.body.returnedSplitScheduleIds || [], []); + assert.equal((await scheduleById(brynnPart.id)).user_id, null); + const emmettAfter = await scheduleById(emmettPart.id); + assert.equal(emmettAfter.user_id, emmett); + assert.equal(emmettAfter.clam_value, 4); +}); + +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.equal(returned.body.returnedSplitScheduleIds, undefined); + 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); +}); From 3a3a36257e11a4e55b5607c030079dd6710db4bc Mon Sep 17 00:00:00 2001 From: adamecker Date: Sat, 28 Nov 2026 21:14:26 +0000 Subject: [PATCH 2/5] Fix missing ListItem import in the split-result dialog MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The result view renders each person's share in a ListItem, but ListItem was never imported β€” confirming a split threw ReferenceError: ListItem is not defined and the dialog closed without showing the result. The split itself succeeded server-side; only the result display crashed. Generated with Muse AI πŸ€– --- client/src/components/ChoreWidget.jsx | 1 + 1 file changed, 1 insertion(+) diff --git a/client/src/components/ChoreWidget.jsx b/client/src/components/ChoreWidget.jsx index d469548b..185c545d 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, From 6ff9fa8db9be74e67e3614c79aabeeb4d5698488 Mon Sep 17 00:00:00 2001 From: adamecker Date: Sun, 29 Nov 2026 01:51:55 +0000 Subject: [PATCH 3/5] Rework split to keep the one pool schedule (issue #407) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The split now rides on the one pool schedule as split_user_ids / split_shares (modelled on prize_offers.split_user_ids) instead of copying the chore per person. The card shows in each selected person's column, each person ticks their own share, and completing writes their share to their history row β€” so the chore keeps its definition, icon, follow-ups, list and history. The nightly return clears the split, so tomorrow it is one chore again, and back to the pool releases the whole split while shares already ticked stay earned. A split is refused when any share would be 0 Stars, everyone in it must be on the chore's claimers list, the split control is hideable like Transfer, and the one-open-bonus check is one shared helper used by the claim and split routes. The nightly prune only takes a split once every share is ticked. Generated with Muse AI πŸ€– --- client/src/components/ChoreWidget.jsx | 83 +++-- client/src/i18n/locales/en/admin.json | 1 + client/src/i18n/locales/en/chores.json | 2 +- client/src/i18n/locales/es/admin.json | 1 + client/src/i18n/locales/es/chores.json | 2 +- client/src/utils/choreHelpers.js | 54 +++- client/src/utils/choreHelpers.test.js | 72 ++++- client/src/utils/displayControls.js | 1 + client/src/utils/displayControls.test.js | 1 + server/index.js | 332 +++++++++++--------- server/migrations/registry.js | 2 +- server/migrations/schema46-choreSplit.js | 43 +++ server/migrations/schema46-splitGroupId.js | 42 --- server/tests/bonusChoreSplitAssign.test.js | 336 ++++++++++++++++----- 14 files changed, 686 insertions(+), 286 deletions(-) create mode 100644 server/migrations/schema46-choreSplit.js delete mode 100644 server/migrations/schema46-splitGroupId.js diff --git a/client/src/components/ChoreWidget.jsx b/client/src/components/ChoreWidget.jsx index 185c545d..0143b14a 100644 --- a/client/src/components/ChoreWidget.jsx +++ b/client/src/components/ChoreWidget.jsx @@ -42,7 +42,7 @@ 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, splitStars } from '../utils/choreHelpers.js'; +import { shouldShowChoreToday, getTodayDateString, getDueDateStatus, formatDueDate, hasOutstandingBonusChore, canClaimBonusChore, countsTowardDailyBonus, getTransferTargets, splitStars, splitShareFor, 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'; @@ -213,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'); @@ -230,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)); } @@ -241,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(); @@ -750,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 { @@ -830,11 +838,12 @@ const ChoreWidget = ({ refreshNonce = 0, hiddenControls = [] }) => { // 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 hands each person their own copy and consumes - // the pool chore. The result stays in the dialog β€” there is no toast - // system on the dashboard β€” until Done closes it. + // 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) return; + if (!schedule || hideSplitChore) return; splitDialogOpenedAtRef.current = Date.now(); setSplitDialog((prev) => (prev.open ? prev : { open: true, schedule, userIds: [], result: null })); }; @@ -856,11 +865,16 @@ const ChoreWidget = ({ refreshNonce = 0, hiddenControls = [] }) => { try { setIsLoading(true); const response = await axios.post(`${API_BASE_URL}/api/chore-schedules/${schedule.id}/split-assign`, { userIds }); - const created = response.data?.schedules || []; + const updated = response.data?.schedule; await fetchData(); - const parts = created.map((row) => ({ - username: users.find((u) => u.id === row.user_id)?.username || '?', - stars: row.clam_value, + // 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) { @@ -998,6 +1012,7 @@ const ChoreWidget = ({ refreshNonce = 0, hiddenControls = [] }) => { }; const handleBonusCardPointerDown = (event, schedule) => { + if (hideSplitChore) return; splitHoldFiredRef.current = false; getSplitPressHold().down(event.clientX, event.clientY, schedule); }; @@ -1015,6 +1030,9 @@ const ChoreWidget = ({ refreshNonce = 0, hiddenControls = [] }) => { }; 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 @@ -1206,13 +1224,16 @@ 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}`]; const completed = pending !== undefined ? pending : history.some(h => @@ -1221,8 +1242,14 @@ const ChoreWidget = ({ refreshNonce = 0, hiddenControls = [] }) => { h.date === 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 @@ -1235,7 +1262,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 @@ -1452,7 +1481,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 ? ( @@ -2345,13 +2374,25 @@ const ChoreWidget = ({ refreshNonce = 0, hiddenControls = [] }) => { {t('chores:bonus.splitHint')} - {users.map((user) => { + {/* 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)}> + toggleBonusSplitUser(user.id)}> {user.username?.charAt(0).toUpperCase()} @@ -2359,7 +2400,9 @@ const ChoreWidget = ({ refreshNonce = 0, hiddenControls = [] }) => { diff --git a/client/src/i18n/locales/en/admin.json b/client/src/i18n/locales/en/admin.json index bc057dba..0e24261d 100644 --- a/client/src/i18n/locales/en/admin.json +++ b/client/src/i18n/locales/en/admin.json @@ -532,6 +532,7 @@ "items": { "addChore": "Add a chore", "transferChore": "Transfer a chore to someone else", + "splitChore": "Split a bonus chore's Stars among several people", "snoozeChore": "Snooze a chore", "prizeApproval": "Approve or decline prize requests", "quickSpend": "Spend {{points}} from a profile", diff --git a/client/src/i18n/locales/en/chores.json b/client/src/i18n/locales/en/chores.json index 6bf77383..dc37b7f6 100644 --- a/client/src/i18n/locales/en/chores.json +++ b/client/src/i18n/locales/en/chores.json @@ -116,7 +116,7 @@ "splitConfirm": "Split", "splitFailed": "Failed to split bonus chore", "splitDone": "Split {{total}} {{pointsIcon}}", - "splitUndoHint": "To undo a split, transfer any part back to the bonus pool β€” every part that is still open comes back with it." + "splitUndoHint": "To undo a split, transfer the chore back to the bonus pool β€” the whole split comes back, and any share already ticked stays earned." }, "transfer": { "menuItem": "Transfer chore", diff --git a/client/src/i18n/locales/es/admin.json b/client/src/i18n/locales/es/admin.json index 3d04109d..c394f4a4 100644 --- a/client/src/i18n/locales/es/admin.json +++ b/client/src/i18n/locales/es/admin.json @@ -532,6 +532,7 @@ "items": { "addChore": "AΓ±adir una tarea", "transferChore": "Transferir una tarea a otra persona", + "splitChore": "Repartir las Estrellas de una tarea extra entre varias personas", "snoozeChore": "Posponer una tarea", "prizeApproval": "Aprobar o rechazar solicitudes de premios", "quickSpend": "Gastar {{points}} desde un perfil", diff --git a/client/src/i18n/locales/es/chores.json b/client/src/i18n/locales/es/chores.json index f2c8fce4..1aabbec5 100644 --- a/client/src/i18n/locales/es/chores.json +++ b/client/src/i18n/locales/es/chores.json @@ -116,7 +116,7 @@ "splitConfirm": "Dividir", "splitFailed": "No se pudo dividir la tarea extra", "splitDone": "Dividido: {{total}} {{pointsIcon}}", - "splitUndoHint": "Para deshacer una divisiΓ³n, transfiere cualquier parte de vuelta al panel de tareas extra: todas las partes que sigan abiertas vuelven con ella." + "splitUndoHint": "Para deshacer una divisiΓ³n, transfiere la tarea de vuelta al panel de tareas extra: toda la divisiΓ³n vuelve, y las partes ya marcadas quedan ganadas." }, "transfer": { "menuItem": "Transferir tarea", diff --git a/client/src/utils/choreHelpers.js b/client/src/utils/choreHelpers.js index 24748e96..9c3152dd 100644 --- a/client/src/utils/choreHelpers.js +++ b/client/src/utils/choreHelpers.js @@ -62,14 +62,62 @@ export function ringsToday(schedule, today = getTodayDateString()) { export function hasOutstandingBonusChore(schedules, history, userId, today) { return schedules - .filter((schedule) => schedule.user_id === userId - && (schedule.clam_value || 0) > 0 - && shouldShowChoreToday(schedule, 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) => !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 bonus chore is offered to `userId` (issue #403): whether they * may claim it from the pool, or be handed it with Transfer. A schedule diff --git a/client/src/utils/choreHelpers.test.js b/client/src/utils/choreHelpers.test.js index 6ad0dda5..109fc0ef 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, splitStars } from './choreHelpers.js'; +import { shouldShowChoreToday, convertDaysToCrontab, getDueDateStatus, formatDueDate, hasOutstandingBonusChore, canClaimBonusChore, claimUserIdsToSave, compareByKey, countsTowardDailyBonus, ringsToday, getTransferTargets, splitStars, parseSplitUserIds, parseSplitShares, isSplitSchedule, splitShareFor } 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. @@ -265,6 +265,76 @@ 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 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(); + }); }); describe('compareByKey', () => { 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/server/index.js b/server/index.js index 06de8dff..a920aa09 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 clears it back to + // one pool chore; 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,34 @@ async function dailyBackgroundProcessing() { returnedBonusSchedules: claimedBonusSchedules, } + // A split bonus chore returns to one chore in the pool every night, + // done or not β€” the same as the returns above. It is unassigned + // (user_id NULL), so neither of them 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. + const splitBonusSchedules = db.prepare(` + SELECT cs.id, + 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; + for (const schedule of splitBonusSchedules) { + 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++; + } + results = { + ...results, + returnedSplitSchedulesCount: returnedSplitCount, + returnedSplitSchedules: splitBonusSchedules, + } // 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 +3642,14 @@ 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. +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), +}); fastify.get('/api/chore-schedules', async (request, reply) => { try { @@ -3644,7 +3693,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 +3707,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,7 +3940,7 @@ 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, split_group_id 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 FROM chore_schedules WHERE id = ?').get(id); if (!existingSchedule) { return reply.status(404).send({ error: 'Schedule not found' }); } @@ -3986,6 +4035,10 @@ fastify.patch('/api/chore-schedules/:id', async (request, reply) => { // 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'); + // 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 @@ -4069,21 +4122,6 @@ fastify.patch('/api/chore-schedules/:id', async (request, reply) => { } } - // Returning one part of a split to the bonus pool returns every - // still-open part of that split with it β€” that is how a split is - // undone. The update above already returned this schedule itself; - // the rest of its group goes here, and losing a chore re-checks each - // holder's daily bonus the same way the reassignment above does. - let returnedSplitScheduleIds = []; - if (user_id !== undefined && !user_id && existingSchedule.user_id !== null && existingSchedule.split_group_id) { - const today = getTodayLocalDateString(); - const returned = returnSplitGroupToPool(existingSchedule.split_group_id, Number(id), today); - returnedSplitScheduleIds = returned.map((row) => row.id); - for (const row of returned) { - awardDailyRegularBonusIfDue(row.user_id, today); - } - } - // No longer any-day: its open card goes, rather than staying on as a // one-time chore due every day (dropOpenAnyDayCards). Below, the new // timing makes its own card if it needs one. @@ -4119,15 +4157,95 @@ fastify.patch('/api/chore-schedules/:id', async (request, reply) => { spawnStickyChildren(getTodayLocalDateString(), [Number(id)]); } - return returnedSplitScheduleIds.length > 0 - ? { success: true, returnedSplitScheduleIds } - : { success: true }; + return { success: true }; } catch (error) { console.error('Error updating schedule:', error); reply.status(500).send({ error: 'Failed to update schedule' }); } }); +// 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 completedToday = new Set(db.prepare(` + SELECT chore_schedule_id FROM chore_history + WHERE user_id = ? AND date = ? AND kind = 'completion' + `).all(userId, today).map((row) => row.chore_schedule_id)); + const outstanding = (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; + } + }; + return assigned.some(outstanding) || split.some(outstanding); +} + +// 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 (or they are not in it). +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]; +} + // 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 @@ -4188,27 +4306,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' }); } @@ -4218,7 +4316,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 = ? @@ -4241,44 +4339,17 @@ function splitStars(total, count) { return Array.from({ length: count }, (_, i) => base + (i < remainder ? 1 : 0)); } -// Undoing a split: returning one part of a split to the bonus pool returns -// every still-open part of that split with it, each as its own pool chore -// worth its split Stars. A part already completed today stays put β€” its -// Stars are already earned and cannot come back. Only the other members -// are touched here; the schedule the caller is already returning is -// handled by the PATCH itself. -function returnSplitGroupToPool(splitGroupId, excludeScheduleId, today) { - if (!splitGroupId) return []; - const members = db.prepare(` - SELECT cs.id, cs.user_id - FROM chore_schedules cs - WHERE cs.split_group_id = ? AND cs.id != ? AND cs.user_id IS NOT NULL AND cs.visible = 1 - `).all(splitGroupId, excludeScheduleId); - const returned = []; - const reset = db.prepare('UPDATE chore_schedules SET user_id = NULL, pool_claimed_on = NULL, transfer_bonus_clams = 0 WHERE id = ?'); - for (const member of members) { - const completed = db.prepare(` - SELECT 1 FROM chore_history - WHERE chore_schedule_id = ? AND user_id = ? AND date = ? AND kind = 'completion' - `).get(member.id, member.user_id, today); - if (completed) continue; - reset.run(member.id); - returned.push({ id: member.id, user_id: member.user_id }); - } - return returned; -} - -// Splitting a bonus chore from the pool among several people. Each person -// gets their own copy of the chore β€” same title and description, their -// share of the Stars on its own chores row β€” assigned to them, so the -// existing single-user completion and claim logic applies unchanged. The -// copies carry the claim marker (pool_claimed_on) and the split marker -// (split_group_id, one uuid for the whole split), so the nightly cleanup -// treats them like claimed bonus chores and a transfer of any part back -// to the pool returns the still-open parts with it. The original pool -// schedule is deleted; its chores row, now orphaned, is pruned by the -// nightly cleanup. At least two people are required β€” one person claiming -// is the claim route, not a split. +// 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; @@ -4304,7 +4375,7 @@ fastify.post('/api/chore-schedules/:id/split-assign', async (request, reply) => } } const schedule = db.prepare(` - SELECT cs.*, c.title, c.description, c.clam_value, c.icon + 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); @@ -4324,79 +4395,49 @@ fastify.post('/api/chore-schedules/:id/split-assign', async (request, reply) => 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(); - const now = new Date(); for (const userId of parsedUserIds) { - 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); - const completedToday = new Set(db.prepare(` - SELECT chore_schedule_id FROM chore_history - WHERE user_id = ? AND date = ? AND kind = 'completion' - `).all(userId, today).map((row) => row.chore_schedule_id)); - 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 cronFiresOnDate(row.crontab, today); - } catch { - return false; - } - }); - if (outstanding) { + 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); - const splitGroupId = crypto.randomUUID(); - // One copy per person, all or none: a split never leaves half the - // family assigned. - const createCopies = db.transaction(() => { - const createdIds = []; - for (let i = 0; i < parsedUserIds.length; i++) { - const choreInfo = db.prepare('INSERT INTO chores (title, description, clam_value, icon) VALUES (?, ?, ?, ?)') - .run(schedule.title, schedule.description, amounts[i], schedule.icon); - const scheduleInfo = db.prepare(` - INSERT INTO chore_schedules - (chore_id, user_id, crontab, duration, visible, interval, parent_schedule_id, - due_time, sound, sound_enabled, reminder_interval_minutes, due_date, - transferable, can_snooze, snoozed_until, expire_minutes, pool_claimed_on, split_group_id) - VALUES (?, ?, ?, ?, 1, ?, NULL, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) - `).run( - choreInfo.lastInsertRowid, parsedUserIds[i], schedule.crontab, schedule.duration, - schedule.interval, schedule.due_time, schedule.sound, schedule.sound_enabled, - schedule.reminder_interval_minutes, schedule.due_date, schedule.transferable, - schedule.can_snooze, schedule.snoozed_until, schedule.expire_minutes, - today, splitGroupId - ); - createdIds.push(scheduleInfo.lastInsertRowid); - } - db.prepare('DELETE FROM chore_schedules WHERE id = ?').run(id); - return createdIds; - }); - const createdIds = createCopies(); + // 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 - // owner, as the claim route does. + // holder, as the claim route does. for (const userId of parsedUserIds) { awardDailyRegularBonusIfDue(userId, today); } - const created = db.prepare(` - SELECT cs.*, c.title, c.description, c.clam_value, c.icon + 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 IN (${createdIds.map(() => '?').join(',')}) - `).all(...createdIds); - const byId = new Map(created.map((row) => [row.id, row])); - return { success: true, splitGroupId, schedules: createdIds.map((createdId) => byId.get(createdId)) }; + WHERE cs.id = ? + `).get(id)) }; } catch (error) { console.error('Error splitting schedule:', error); reply.status(500).send({ error: 'Failed to split bonus chore' }); @@ -4918,10 +4959,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 @@ -4958,7 +5004,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 699cf8dd..028024ce 100644 --- a/server/migrations/registry.js +++ b/server/migrations/registry.js @@ -46,5 +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-splitGroupId', }, + { 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/migrations/schema46-splitGroupId.js b/server/migrations/schema46-splitGroupId.js deleted file mode 100644 index 6a5f42c7..00000000 --- a/server/migrations/schema46-splitGroupId.js +++ /dev/null @@ -1,42 +0,0 @@ -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 split group marker schema migration to version ${targetSchemaId} ===`); - - db.exec('BEGIN'); - try { - // Splitting a bonus chore from the pool hands each selected person - // their own copy, worth their share of the Stars. The copies share - // one marker (split_group_id, a uuid minted by the split route) so - // the whole split can be found again later: transferring any one - // part back to the bonus pool returns every still-open part with - // it, which is how a split is undone. Parts already completed stay - // put β€” their Stars are already earned. NULL for every schedule - // that did not come out of a split. - const columns = db.prepare('PRAGMA table_info(chore_schedules)').all().map((c) => c.name); - if (!columns.includes('split_group_id')) { - db.exec('ALTER TABLE chore_schedules ADD COLUMN split_group_id TEXT'); - } - - db.prepare('INSERT OR REPLACE INTO settings (key, value) VALUES (?, ?)').run( - schemaIdKey, - String(targetSchemaId) - ); - - db.exec('COMMIT'); - console.log(`=== Split group marker schema migration completed (version ${targetSchemaId}) ===`); - } catch (migrationError) { - db.exec('ROLLBACK'); - throw migrationError; - } -} catch (error) { - console.error('=== Split group marker schema migration failed ==='); - console.error('Error:', error); - throw error; -} diff --git a/server/tests/bonusChoreSplitAssign.test.js b/server/tests/bonusChoreSplitAssign.test.js index 49b41cb9..e17eda33 100644 --- a/server/tests/bonusChoreSplitAssign.test.js +++ b/server/tests/bonusChoreSplitAssign.test.js @@ -1,11 +1,13 @@ // Splitting a bonus chore from the pool among several people, and undoing -// the split by returning one part to the pool. A split hands each selected -// person their own copy of the chore β€” same title and description, their -// share of the Stars β€” and consumes the original pool schedule. The copies -// share one marker (split_group_id, migration schema44), so returning any -// one part to the pool returns every still-open part with it; a part -// already completed stays put, its Stars already earned. A real HomeGlow -// server on a throwaway database, like bonusChoreReturnToPool.test.js. +// 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; a share already +// ticked stays earned. The nightly return clears the split, so tomorrow it +// is one chore again. 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'); @@ -77,7 +79,10 @@ test.after(async () => { }); const scheduleById = async (id) => (await api('/api/chore-schedules')).body.find((s) => s.id === id); -const poolChores = async () => (await api('/api/chore-schedules')).body.filter((s) => s.user_id === null && s.visible === 1 && (s.clam_value || 0) > 0); +// 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) { @@ -85,9 +90,10 @@ async function makeKid(username) { 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. -async function makePoolChore({ title, clamValue, crontab = null, description = null }) { - const chore = (await post('/api/chores', { title, description, clam_value: clamValue })).body.id; +// 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); @@ -103,7 +109,7 @@ async function completeSchedule(scheduleId, userId, date = today) { return completed.body; } -test('splitting a 10-Star bonus chore between two people gives 5 each and consumes the pool chore', async () => { +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'); @@ -111,27 +117,24 @@ test('splitting a 10-Star bonus chore between two people gives 5 each and consum const split = await splitSchedule(scheduleId, [emmett, brynn]); assert.equal(split.status, 200, JSON.stringify(split.body)); assert.equal(split.body.success, true); - assert.equal(typeof split.body.splitGroupId, 'string'); - assert.equal(split.body.schedules.length, 2); - - // Each person has their own copy, worth their share, in selection order. - const [first, second] = split.body.schedules; - assert.equal(first.user_id, emmett); - assert.equal(first.clam_value, 5); - assert.equal(first.title, 'Wash the car'); - assert.equal(first.description, 'Inside and out'); - assert.equal(first.pool_claimed_on, today); - assert.equal(second.user_id, brynn); - assert.equal(second.clam_value, 5); - assert.equal(second.pool_claimed_on, today); - // One shared marker for the whole split. - assert.equal(first.split_group_id, split.body.splitGroupId); - assert.equal(second.split_group_id, split.body.splitGroupId); - assert.equal(first.split_group_id, second.split_group_id); - - // The original pool schedule is gone: it is not in the pool any more, - // and the list no longer carries it at all. - assert.equal(await scheduleById(scheduleId), undefined); + + // 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'), []); }); @@ -145,7 +148,8 @@ test('the remainder goes one Star each to the first people in selection order', 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.schedules.map((s) => s.clam_value), [4, 3]); + 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'); @@ -154,8 +158,8 @@ test('the remainder goes one Star each to the first people in selection order', 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.schedules.map((s) => s.clam_value), [4, 3, 3]); - assert.deepEqual(splitTen.body.schedules.map((s) => s.user_id), [third, fourth, fifth]); + 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. @@ -164,7 +168,8 @@ test('the remainder goes one Star each to the first people in selection order', 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.schedules.map((s) => [s.user_id, s.clam_value]), [[seventh, 4], [sixth, 3]]); + 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 () => { @@ -184,6 +189,9 @@ test('splitting needs at least two different people', async () => { 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 () => { @@ -208,6 +216,64 @@ test('splitting rejects an unknown person, an assigned chore, and a non-bonus ch // 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 () => { @@ -222,71 +288,193 @@ test('splitting rejects a person who already has an open bonus chore', async () 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 created and the pool chore is still there. - assert.equal((await scheduleById(second.scheduleId)).user_id, null); + // 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.schedules.map((s) => s.clam_value), [3, 3]); + 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('returning one split part to the pool returns all still-open parts', async () => { +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)); - const [emmettPart, brynnPart, callaPart] = split.body.schedules; - assert.deepEqual(split.body.schedules.map((s) => s.clam_value), [4, 3, 3]); + assert.deepEqual(split.body.schedule.split_shares, [4, 3, 3]); - // Transferring Emmett's part back to the pool (the Transfer dialog's - // pool target: user_id 0) returns Brynn's and Calla's open parts too. - const returned = await patch(`/api/chore-schedules/${emmettPart.id}`, { user_id: 0, visible: 1 }); + // 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.returnedSplitScheduleIds.sort(), [brynnPart.id, callaPart.id].sort()); + assert.deepEqual(returned.body, { success: true }); - // Each part is its own pool chore now, worth its split Stars β€” the - // split is undone without recombining anything. - for (const part of [emmettPart, brynnPart, callaPart]) { - const after = await scheduleById(part.id); - assert.equal(after.user_id, null); - assert.equal(after.pool_claimed_on, null); - } - const pool = (await poolChores()).filter((s) => s.title === 'Wash the windows'); - assert.deepEqual(pool.map((s) => s.clam_value).sort(), [3, 3, 4]); - assert.deepEqual(pool.map((s) => s.split_group_id), [split.body.splitGroupId, split.body.splitGroupId, split.body.splitGroupId]); + // 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 the parts can be claimed or re-split from the pool again. - const reclaimed = await post(`/api/chore-schedules/${brynnPart.id}/claim`, { user_id: brynn }); + // ...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(brynnPart.id)).user_id, brynn); + assert.equal((await scheduleById(scheduleId)).user_id, brynn); }); -test('a completed split part is not returned to the pool', async () => { +test('a completed share stays earned when the split is released', 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)); - const [emmettPart, brynnPart] = split.body.schedules; - assert.deepEqual(split.body.schedules.map((s) => s.clam_value), [4, 3]); + assert.deepEqual(split.body.schedule.split_shares, [4, 3]); - // Emmett does his part today; its Stars are earned. - await completeSchedule(emmettPart.id, emmett); + // Emmett does his share today; its Stars are earned. + await completeSchedule(scheduleId, emmett); + assert.equal((await historyOf(emmett))[0].clam_value, 4); - // Brynn decides not to help and sends her part back. Only hers moves: - // Emmett's completed part stays assigned to him. - const returned = await patch(`/api/chore-schedules/${brynnPart.id}`, { user_id: 0, visible: 1 }); + // Brynn decides not to help and sends the chore back. The whole split + // is released β€” and Emmett's earned share stays put in his history. + 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.returnedSplitScheduleIds || [], []); - assert.equal((await scheduleById(brynnPart.id)).user_id, null); - const emmettAfter = await scheduleById(emmettPart.id); - assert.equal(emmettAfter.user_id, emmett); - assert.equal(emmettAfter.clam_value, 4); + const after = await scheduleById(scheduleId); + assert.equal(after.user_id, null); + assert.equal(after.split_user_ids, null); + assert.equal(after.split_shares, null); + assert.equal((await historyOf(emmett)).length, 1); + assert.equal((await historyOf(emmett))[0].clam_value, 4); + assert.equal((await historyOf(brynn)).length, 0); +}); + +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: the nightly clear + // takes the open split, never the history. + 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); + assert.equal((await scheduleById(third.scheduleId)).split_user_ids, null); +}); + +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, the split is cleared, and + // the chore is one pool chore again β€” the other share is still open. + 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.equal(after.split_user_ids, null); + assert.equal(after.clam_value, 6); + assert.deepEqual((await poolChores()).filter((s) => s.id === halfDone.scheduleId).map((s) => s.id), [halfDone.scheduleId]); + // ...and the ticked share is still earned, by schedule if not by id: + // the history row survives the return. + assert.equal((await historyOf(emmett)).filter((h) => h.chore_schedule_id === halfDone.scheduleId).length, 1); }); test('returning a non-split chore to the pool is unchanged', async () => { @@ -297,7 +485,7 @@ test('returning a non-split chore to the pool is unchanged', async () => { const returned = await patch(`/api/chore-schedules/${scheduleId}`, { user_id: 0, visible: 1 }); assert.equal(returned.status, 200, JSON.stringify(returned.body)); - assert.equal(returned.body.returnedSplitScheduleIds, undefined); + assert.deepEqual(returned.body, { success: true }); const after = await scheduleById(scheduleId); assert.equal(after.user_id, null); assert.equal(after.pool_claimed_on, null); From 982144868b575342c292cf49af7fc544ec5149e4 Mon Sep 17 00:00:00 2001 From: adamecker Date: Sun, 29 Nov 2026 18:09:40 +0000 Subject: [PATCH 4/5] Lock a split once a share is ticked; keep half-done one-time splits; refuse non-members (issue #407) - PATCH /api/chore-schedules/:id with user_id on a split schedule answers 409 once any share is ticked, and the widget hides Transfer for it; before anyone ticks, moving the split is unchanged. - The nightly return leaves a half-done one-time split split until every share is ticked, when the prune takes it; untouched splits and recurring splits still return to the pool. - POST /api/chores/complete from someone not in the split answers 409. --- client/src/components/ChoreWidget.jsx | 8 +- client/src/utils/choreHelpers.js | 11 ++ client/src/utils/choreHelpers.test.js | 18 ++- docs/reference/backend-api.md | 8 +- server/index.js | 78 +++++++++++-- server/tests/bonusChoreSplitAssign.test.js | 121 ++++++++++++++++++--- 6 files changed, 209 insertions(+), 35 deletions(-) diff --git a/client/src/components/ChoreWidget.jsx b/client/src/components/ChoreWidget.jsx index 0143b14a..948bceed 100644 --- a/client/src/components/ChoreWidget.jsx +++ b/client/src/components/ChoreWidget.jsx @@ -42,7 +42,7 @@ 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, splitStars, splitShareFor, isSplitSchedule } from '../utils/choreHelpers.js'; +import { shouldShowChoreToday, getTodayDateString, getDueDateStatus, formatDueDate, hasOutstandingBonusChore, canClaimBonusChore, countsTowardDailyBonus, getTransferTargets, splitStars, splitShareFor, splitHasTickedShareToday, 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'; @@ -919,8 +919,12 @@ 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. const canTransfer = !hideTransferChore && schedule.transferable !== 0 + && !splitHasTickedShareToday(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. @@ -2237,7 +2241,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 && !splitHasTickedShareToday(choreMenu.schedule, history) && getTransferTargets(users, choreMenu.schedule?.user_id, '', choreMenu.schedule).length > 0 && ( diff --git a/client/src/utils/choreHelpers.js b/client/src/utils/choreHelpers.js index 9c3152dd..74025818 100644 --- a/client/src/utils/choreHelpers.js +++ b/client/src/utils/choreHelpers.js @@ -118,6 +118,17 @@ export function splitShareFor(schedule, userId) { return shares[index]; } +// 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; the server is the backstop +// for a tick from an earlier day, which this history does not see. +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); +} + /** * Whether a bonus chore is offered to `userId` (issue #403): whether they * may claim it from the pool, or be handed it with Transfer. A schedule diff --git a/client/src/utils/choreHelpers.test.js b/client/src/utils/choreHelpers.test.js index 109fc0ef..a56ead8e 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, splitStars, parseSplitUserIds, parseSplitShares, isSplitSchedule, splitShareFor } from './choreHelpers.js'; +import { shouldShowChoreToday, convertDaysToCrontab, getDueDateStatus, formatDueDate, hasOutstandingBonusChore, canClaimBonusChore, claimUserIdsToSave, compareByKey, countsTowardDailyBonus, ringsToday, getTransferTargets, splitStars, parseSplitUserIds, parseSplitShares, isSplitSchedule, splitShareFor, 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. @@ -335,6 +335,22 @@ describe('split helpers', () => { 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); + }); }); describe('compareByKey', () => { diff --git a/docs/reference/backend-api.md b/docs/reference/backend-api.md index bdb0b5b1..c5fe968c 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,7 +221,7 @@ 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). 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: the split is locked, and releasing it to the pool or handing it to one person would pay the ticked share plus the whole chore (issue #407). 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/bulk` | Bulk create schedules. | @@ -228,7 +230,7 @@ Every recipient (a device's browser push, an ntfy topic, a Home Assistant phone) | 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** (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 a920aa09..566e5f32 100644 --- a/server/index.js +++ b/server/index.js @@ -2657,9 +2657,9 @@ async function dailyBackgroundProcessing() { // 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 clears it back to - // one pool chore; a fully done one is pruned here like any completed - // one-time chore. + // 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(` @@ -2787,14 +2787,24 @@ async function dailyBackgroundProcessing() { returnedBonusSchedules: claimedBonusSchedules, } - // A split bonus chore returns to one chore in the pool every night, - // done or not β€” the same as the returns above. It is unassigned - // (user_id NULL), so neither of them 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 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 @@ -2805,15 +2815,21 @@ async function dailyBackgroundProcessing() { `).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: splitBonusSchedules, + returnedSplitSchedules, } // Sticky schedules: today's one-time child for each until-completed and @@ -3940,11 +3956,20 @@ 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, split_user_ids, split_shares 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' }); } + // Once any share of a split is ticked, the split is locked (issue + // #407): releasing it to the pool or handing it to one person would + // pay the ticked share plus the whole chore. Only a move (user_id) + // is refused β€” editing the timing or snoozing a locked split is + // still fine, and a split nobody has ticked moves as before. + if (user_id !== undefined && 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 @@ -4235,7 +4260,8 @@ function hasOutstandingBonusChore(userId, today) { } // 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 (or they are not in it). +// 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; @@ -4246,6 +4272,25 @@ function splitShareForUser(schedule, userId) { return shares[index]; } +// 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) { + const ids = parseSplitUserIds(schedule.split_user_ids); + if (ids === null) return false; + 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 completed.some((userId) => ids.includes(Number(userId))); +} + // 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 @@ -4943,6 +4988,15 @@ 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 '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); diff --git a/server/tests/bonusChoreSplitAssign.test.js b/server/tests/bonusChoreSplitAssign.test.js index e17eda33..9e2d7200 100644 --- a/server/tests/bonusChoreSplitAssign.test.js +++ b/server/tests/bonusChoreSplitAssign.test.js @@ -4,9 +4,13 @@ // (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; a share already -// ticked stays earned. The nightly return clears the split, so tomorrow it -// is one chore again. A real HomeGlow server on a throwaway database, like +// 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'); @@ -383,10 +387,11 @@ test('back to the pool releases the whole split', async () => { assert.equal((await scheduleById(scheduleId)).user_id, brynn); }); -test('a completed share stays earned when the split is released', async () => { +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]); @@ -395,19 +400,67 @@ test('a completed share stays earned when the split is released', async () => { await completeSchedule(scheduleId, emmett); assert.equal((await historyOf(emmett))[0].clam_value, 4); - // Brynn decides not to help and sends the chore back. The whole split - // is released β€” and Emmett's earned share stays put in his history. + // 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, 200, JSON.stringify(returned.body)); + 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.equal(after.split_user_ids, null); - assert.equal(after.split_shares, 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 }); @@ -437,15 +490,34 @@ test('the nightly return clears the split, so tomorrow it is one chore again', a } 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: the nightly clear - // takes the open split, never the history. + // 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); - assert.equal((await scheduleById(third.scheduleId)).split_user_ids, null); + 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 () => { @@ -461,20 +533,35 @@ test('the nightly prune only takes a split once every share is ticked', async () await nightly(); assert.equal(await scheduleById(done.scheduleId), undefined); - // Only one share ticked: the schedule stays, the split is cleared, and - // the chore is one pool chore again β€” the other share is still open. + // 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.equal(after.split_user_ids, 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), [halfDone.scheduleId]); + 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 return. + // 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 () => { From 36204376abb6be2ba64f9ff5aa5b5323275f4771 Mon Sep 17 00:00:00 2001 From: adamecker Date: Mon, 30 Nov 2026 06:00:56 -0800 Subject: [PATCH 5/5] A split share stays done past midnight; stale displays cannot claim or re-split; admin saves do not move a split (issue #407) --- client/src/components/ChoreWidget.jsx | 14 ++- client/src/utils/choreHelpers.js | 44 ++++++- client/src/utils/choreHelpers.test.js | 38 +++++- docs/reference/backend-api.md | 6 +- server/index.js | 129 ++++++++++++++------- server/tests/bonusChoreSplitAssign.test.js | 111 ++++++++++++++++++ 6 files changed, 289 insertions(+), 53 deletions(-) diff --git a/client/src/components/ChoreWidget.jsx b/client/src/components/ChoreWidget.jsx index 948bceed..8d7ce925 100644 --- a/client/src/components/ChoreWidget.jsx +++ b/client/src/components/ChoreWidget.jsx @@ -42,7 +42,7 @@ 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, splitStars, splitShareFor, splitHasTickedShareToday, isSplitSchedule } 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'; @@ -922,9 +922,11 @@ const ChoreWidget = ({ refreshNonce = 0, hiddenControls = [] }) => { // 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 - && !splitHasTickedShareToday(schedule, history) + && !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. @@ -1238,13 +1240,17 @@ const ChoreWidget = ({ refreshNonce = 0, hiddenControls = [] }) => { .map(schedule => { const today = getTodayDateString(); 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 @@ -2241,7 +2247,7 @@ const ChoreWidget = ({ refreshNonce = 0, hiddenControls = [] }) => { anchorReference="anchorPosition" anchorPosition={choreMenu.position || undefined} > - {!hideTransferChore && choreMenu.schedule?.transferable !== 0 && !splitHasTickedShareToday(choreMenu.schedule, history) && 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 && ( diff --git a/client/src/utils/choreHelpers.js b/client/src/utils/choreHelpers.js index 74025818..f0c3948a 100644 --- a/client/src/utils/choreHelpers.js +++ b/client/src/utils/choreHelpers.js @@ -70,9 +70,17 @@ export function hasOutstandingBonusChore(schedules, history, userId, today) { && (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)); + .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 @@ -118,10 +126,36 @@ export function splitShareFor(schedule, userId) { 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; the server is the backstop -// for a tick from an earlier day, which this history does not see. +// 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 diff --git a/client/src/utils/choreHelpers.test.js b/client/src/utils/choreHelpers.test.js index a56ead8e..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, splitStars, parseSplitUserIds, parseSplitShares, isSplitSchedule, splitShareFor, splitHasTickedShareToday } 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. @@ -278,6 +278,18 @@ describe('hasOutstandingBonusChore', () => { 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); @@ -351,6 +363,28 @@ describe('split helpers', () => { 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', () => { diff --git a/docs/reference/backend-api.md b/docs/reference/backend-api.md index c5fe968c..9c5a2145 100644 --- a/docs/reference/backend-api.md +++ b/docs/reference/backend-api.md @@ -221,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. PATCH `user_id` on a split schedule answers **409** once any share of the split has been ticked: the split is locked, and releasing it to the pool or handing it to one person would pay the ticked share plus the whole chore (issue #407). 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`. Completing a split chore as someone not in the split answers **409** (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/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 566e5f32..d5e9f38c 100644 --- a/server/index.js +++ b/server/index.js @@ -3659,12 +3659,16 @@ fastify.delete('/api/chores/:id', async (request, reply) => { // 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); `split_user_ids` / `split_shares` are the split -// (issue #407), parallel lists or null when the chore is not 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) => { @@ -3961,12 +3965,16 @@ fastify.patch('/api/chore-schedules/:id', async (request, reply) => { return reply.status(404).send({ error: 'Schedule not found' }); } - // Once any share of a split is ticked, the split is locked (issue - // #407): releasing it to the pool or handing it to one person would - // pay the ticked share plus the whole chore. Only a move (user_id) - // is refused β€” editing the timing or snoozing a locked split is - // still fine, and a split nobody has ticked moves as before. - if (user_id !== undefined && splitHasTickedShare(existingSchedule)) { + // `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' }); } @@ -4054,12 +4062,15 @@ 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. @@ -4128,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); } } @@ -4242,12 +4250,20 @@ function hasOutstandingBonusChore(userId, today) { const ids = parseSplitUserIds(row.split_user_ids); return ids !== null && ids.includes(Number(userId)); }); - const completedToday = new Set(db.prepare(` - SELECT chore_schedule_id FROM chore_history - WHERE user_id = ? AND date = ? AND kind = 'completion' - `).all(userId, today).map((row) => row.chore_schedule_id)); - const outstanding = (row) => { - if (completedToday.has(row.id)) return false; + 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 { @@ -4256,7 +4272,7 @@ function hasOutstandingBonusChore(userId, today) { return false; } }; - return assigned.some(outstanding) || split.some(outstanding); + 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, @@ -4272,6 +4288,25 @@ function splitShareForUser(schedule, userId) { 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 @@ -4281,14 +4316,7 @@ function splitShareForUser(schedule, userId) { // (the nightly return below), so a today-only check would leave the // same hole open the next day. function splitHasTickedShare(schedule) { - const ids = parseSplitUserIds(schedule.split_user_ids); - if (ids === null) return false; - 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 completed.some((userId) => ids.includes(Number(userId))); + return splitDoneUserIds(schedule).length > 0; } // Claiming a bonus chore from the pool is its own route, not a plain @@ -4331,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' }); } @@ -4434,6 +4469,13 @@ fastify.post('/api/chore-schedules/:id/split-assign', async (request, reply) => 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' }); } @@ -4997,6 +5039,15 @@ function completeChoreSchedule(input) { 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); diff --git a/server/tests/bonusChoreSplitAssign.test.js b/server/tests/bonusChoreSplitAssign.test.js index 9e2d7200..e319fb2d 100644 --- a/server/tests/bonusChoreSplitAssign.test.js +++ b/server/tests/bonusChoreSplitAssign.test.js @@ -582,3 +582,114 @@ test('returning a non-split chore to the pool is unchanged', async () => { 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); +});