49 lines
1.6 KiB
PHP
49 lines
1.6 KiB
PHP
<?php
|
|
|
|
require_once __DIR__ . '/db.php';
|
|
require_once __DIR__ . '/transaction_service.php';
|
|
|
|
function apply_recurring_transactions_for_month(int $userId, string $ym, bool $skipDuplicates = true): int
|
|
{
|
|
$pdo = db();
|
|
|
|
$stmt = $pdo->prepare("
|
|
SELECT *
|
|
FROM recurring_transactions
|
|
WHERE user_id = ?
|
|
AND is_active = 1
|
|
AND (last_applied_ym IS NULL OR last_applied_ym <> ?)
|
|
ORDER BY id ASC
|
|
");
|
|
$stmt->execute([$userId, $ym]);
|
|
$items = $stmt->fetchAll();
|
|
|
|
$count = 0;
|
|
$lastDay = (int)date('t', strtotime($ym . '-01'));
|
|
|
|
foreach ($items as $item) {
|
|
$day = min((int)$item['day_of_month'], $lastDay);
|
|
$date = sprintf('%s-%02d', $ym, $day);
|
|
|
|
$inserted = create_transaction([
|
|
'user_id' => $userId,
|
|
'account_id' => (int)$item['account_id'],
|
|
'category_id' => (int)$item['category_id'],
|
|
'transaction_type' => $item['transaction_type'],
|
|
'amount' => (float)$item['amount'],
|
|
'transaction_date' => $date,
|
|
'merchant_name' => $item['merchant_name'],
|
|
'description' => $item['description'],
|
|
'related_account_id' => $item['related_account_id'] ? (int)$item['related_account_id'] : null,
|
|
], $skipDuplicates);
|
|
|
|
$stmt2 = $pdo->prepare("UPDATE recurring_transactions SET last_applied_ym = ? WHERE id = ?");
|
|
$stmt2->execute([$ym, $item['id']]);
|
|
|
|
if ($inserted) {
|
|
$count++;
|
|
}
|
|
}
|
|
|
|
return $count;
|
|
} |