74 lines
2.0 KiB
PHP
74 lines
2.0 KiB
PHP
<?php
|
|||
|
|
declare(strict_types=1);
|
||
|
|
|
||
|
|
namespace App\Controllers;
|
||
|
|
|
||
|
|
use App\Access;
|
||
|
|
use App\Expenses;
|
||
|
|
use App\Database;
|
||
|
|
|
||
|
|
/**
|
||
|
|
* 花销记账:一笔花销挂在执行/计划节点上,按人分摊
|
||
|
|
*/
|
||
|
|
class ExpenseController
|
||
|
|
{
|
||
|
|
public function store(): void
|
||
|
|
{
|
||
|
|
csrf_check();
|
||
|
|
|
||
|
|
$nodeId = (int)($_POST['node_id'] ?? 0);
|
||
|
|
$node = Access::node($nodeId); // 归属校验,非本家庭一律 404
|
||
|
|
|
||
|
|
$splitIds = $_POST['split_user_ids'] ?? [];
|
||
|
|
if (!is_array($splitIds)) {
|
||
|
|
$splitIds = [$splitIds];
|
||
|
|
}
|
||
|
|
$splitIds = array_map('intval', $splitIds);
|
||
|
|
|
||
|
|
$result = Expenses::create(
|
||
|
|
$nodeId,
|
||
|
|
(int)($_POST['payer_user_id'] ?? 0),
|
||
|
|
(string)($_POST['total_amount'] ?? ''),
|
||
|
|
(string)($_POST['currency'] ?? 'CNY'),
|
||
|
|
(string)($_POST['category'] ?? '其他'),
|
||
|
|
(string)($_POST['description'] ?? ''),
|
||
|
|
(string)($_POST['is_budget'] ?? '0') === '1',
|
||
|
|
$splitIds
|
||
|
|
);
|
||
|
|
|
||
|
|
if ($result['ok']) {
|
||
|
|
$n = count($splitIds) > 0 ? count($splitIds) : 1;
|
||
|
|
flash('error', '已记一笔,按 ' . $n . ' 人分摊');
|
||
|
|
} else {
|
||
|
|
flash('error', (string)$result['error']);
|
||
|
|
}
|
||
|
|
|
||
|
|
redirect('nodes/show', ['id' => (int)$node['id']], 'expenses');
|
||
|
|
}
|
||
|
|
|
||
|
|
public function destroy(): void
|
||
|
|
{
|
||
|
|
csrf_check();
|
||
|
|
|
||
|
|
$id = (int)($_POST['id'] ?? 0);
|
||
|
|
|
||
|
|
$stmt = Database::get()->prepare('
|
||
|
|
SELECT e.id, tn.id AS node_id
|
||
|
|
FROM expenses e
|
||
|
|
JOIN trip_nodes tn ON tn.id = e.trip_node_id
|
||
|
|
JOIN activities a ON a.id = tn.activity_id
|
||
|
|
WHERE e.id = ? AND a.family_id = ?');
|
||
|
|
$stmt->execute([$id, Access::familyId()]);
|
||
|
|
$row = $stmt->fetch();
|
||
|
|
if (!$row) {
|
||
|
|
http_response_code(404);
|
||
|
|
exit('花销记录不存在');
|
||
|
|
}
|
||
|
|
|
||
|
|
Expenses::delete($id);
|
||
|
|
|
||
|
|
flash('error', '已删除这笔花销');
|
||
|
|
redirect('nodes/show', ['id' => (int)$row['node_id']], 'expenses');
|
||
|
|
}
|
||
|
|
}
|