familyHub/api/chore_review.php

88 lines
2.8 KiB
PHP

<?php
require_once __DIR__ . '/../includes/api_bootstrap.php';
require_once __DIR__ . '/../includes/chore_helpers.php';
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
sendJson(['success' => false, 'error' => 'Method not allowed'], 405);
}
$people = normalizePeopleList(readJsonFile('people.json'));
$actor = requireActivePerson($people);
if (($actor['role'] ?? '') !== ROLE_HEAD || !isHohVerified()) {
sendJson(['success' => false, 'error' => 'Only a verified Head of household can review chores'], 403);
}
$body = readJsonBody();
$id = isset($body['id']) ? trim((string) $body['id']) : '';
$decision = isset($body['decision']) ? trim((string) $body['decision']) : '';
if ($id === '') {
sendJson(['success' => false, 'error' => 'id is required'], 400);
}
if (!in_array($decision, ['approve', 'reject'], true)) {
sendJson(['success' => false, 'error' => 'decision must be approve or reject'], 400);
}
$rawChores = normalizeChoresList(readJsonFile('chores.json'));
$chores = migrateAllChores($rawChores, $people);
$idx = findChoreIndexById($chores, $id);
if ($idx === null) {
sendJson(['success' => false, 'error' => 'Chore not found'], 404);
}
$row = $chores[$idx];
$pending = $row['pending_submission'] ?? null;
if (!is_array($pending)) {
sendJson(['success' => false, 'error' => 'Nothing is waiting for approval on this chore'], 400);
}
if ($decision === 'reject') {
$row['pending_submission'] = null;
$chores[$idx] = migrateLegacyChoreRow($row, $people);
if (!writeJsonFile('chores.json', $chores)) {
sendJson(['success' => false, 'error' => 'Failed to save chores'], 500);
}
sendJson(['success' => true]);
}
$assignees = $row['assignee_ids'] ?? [];
if (!is_array($assignees)) {
$assignees = [];
}
$value = (float) ($row['value'] ?? 0);
$n = count($assignees);
$share = $n > 0 ? round($value / $n, 2) : 0.0;
$row['pending_submission'] = null;
if (($row['schedule'] ?? CHORE_SCHEDULE_ONCE) === CHORE_SCHEDULE_RECURRING) {
$days = (int) ($row['recurrence_days'] ?? 7);
$days = max(1, $days);
$row['due_date'] = gmdate('Y-m-d', time() + ($days * 86400));
$row['status'] = 'active';
} else {
$row['status'] = 'completed';
}
$chores[$idx] = migrateLegacyChoreRow($row, $people);
if (!writeJsonFile('chores.json', $chores)) {
sendJson(['success' => false, 'error' => 'Failed to save chores'], 500);
}
foreach ($people as $pi => $p) {
$pid = (string) ($p['id'] ?? '');
if ($pid === '' || !in_array($pid, $assignees, true)) {
continue;
}
$bal = $p['currency_balance'] ?? 0;
$people[$pi]['currency_balance'] = (is_numeric($bal) ? (float) $bal : 0.0) + $share;
}
if (!writeJsonFile('people.json', $people)) {
sendJson(['success' => false, 'error' => 'Failed to save people balances'], 500);
}
sendJson(['success' => true, 'credited_each' => $share]);