Files
firefly-iii/app/Repositories/PiggyBank/ModifiesPiggyBanks.php

368 lines
15 KiB
PHP
Raw Normal View History

2020-03-21 14:20:40 +01:00
<?php
2020-06-30 19:05:35 +02:00
2020-03-21 14:20:40 +01:00
/**
* ModifiesPiggyBanks.php
* Copyright (c) 2020 james@firefly-iii.org
*
* This file is part of Firefly III (https://github.com/firefly-iii).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
2020-06-30 19:05:35 +02:00
declare(strict_types=1);
2020-03-21 14:20:40 +01:00
namespace FireflyIII\Repositories\PiggyBank;
2021-07-04 07:58:11 +02:00
use FireflyIII\Events\Model\PiggyBank\ChangedAmount;
2020-03-21 14:20:40 +01:00
use FireflyIII\Exceptions\FireflyException;
2024-12-01 18:16:48 +01:00
use FireflyIII\Factory\PiggyBankFactory;
2024-12-14 17:32:03 +01:00
use FireflyIII\Models\Account;
2020-03-21 14:20:40 +01:00
use FireflyIII\Models\Note;
use FireflyIII\Models\PiggyBank;
2024-12-22 13:19:23 +01:00
use FireflyIII\Models\Transaction;
2020-03-21 14:20:40 +01:00
use FireflyIII\Models\TransactionJournal;
2020-06-07 11:31:01 +02:00
use FireflyIII\Repositories\ObjectGroup\CreatesObjectGroups;
2024-12-20 05:20:37 +01:00
use FireflyIII\Support\Http\Api\ExchangeRateConverter;
2024-12-14 17:32:03 +01:00
use Illuminate\Support\Facades\Log;
2020-03-21 14:20:40 +01:00
/**
* Trait ModifiesPiggyBanks
*/
trait ModifiesPiggyBanks
{
2020-06-07 11:31:01 +02:00
use CreatesObjectGroups;
2020-12-02 06:41:42 +01:00
2024-12-22 13:19:23 +01:00
public function addAmountToPiggyBank(PiggyBank $piggyBank, string $amount, TransactionJournal $journal): void
2023-06-21 12:34:58 +02:00
{
2024-12-22 13:19:23 +01:00
Log::debug(sprintf('addAmountToPiggyBank: %s', $amount));
2023-06-21 12:34:58 +02:00
if (-1 === bccomp($amount, '0')) {
2024-12-22 13:19:23 +01:00
/** @var Transaction $source */
$source = $journal->transactions()->with(['account'])->where('amount', '<', 0)->first();
2024-12-15 08:50:57 +01:00
Log::debug('Remove amount.');
2024-12-22 13:19:23 +01:00
$this->removeAmount($piggyBank, $source->account, bcmul($amount, '-1'), $journal);
2023-06-21 12:34:58 +02:00
}
if (1 === bccomp($amount, '0')) {
2024-12-22 13:19:23 +01:00
/** @var Transaction $destination */
$destination = $journal->transactions()->with(['account'])->where('amount', '>', 0)->first();
2024-12-15 08:50:57 +01:00
Log::debug('Add amount.');
2024-12-22 13:19:23 +01:00
$this->addAmount($piggyBank, $destination->account, $amount, $journal);
2023-06-21 12:34:58 +02:00
}
}
public function removeAmount(PiggyBank $piggyBank, Account $account, string $amount, ?TransactionJournal $journal = null): bool
2023-06-21 12:34:58 +02:00
{
2024-12-20 05:20:37 +01:00
$currentAmount = $this->getCurrentAmount($piggyBank, $account);
$pivot = $piggyBank->accounts()->where('accounts.id', $account->id)->first()->pivot;
$pivot->current_amount = bcsub($currentAmount, $amount);
$pivot->native_current_amount = null;
// also update native_current_amount.
2025-01-05 07:31:26 +01:00
$userCurrency = app('amount')->getDefaultCurrencyByUserGroup($this->user->userGroup);
2024-12-20 05:20:37 +01:00
if ($userCurrency->id !== $piggyBank->transaction_currency_id) {
2025-01-05 07:31:26 +01:00
$converter = new ExchangeRateConverter();
2024-12-20 05:20:37 +01:00
$converter->setIgnoreSettings(true);
$pivot->native_current_amount = $converter->convert($piggyBank->transactionCurrency, $userCurrency, today(), $pivot->current_amount);
}
2024-12-14 17:32:03 +01:00
$pivot->save();
2023-06-21 12:34:58 +02:00
2024-12-15 08:50:57 +01:00
Log::debug('ChangedAmount: removeAmount [a]: Trigger change for negative amount.');
event(new ChangedAmount($piggyBank, bcmul($amount, '-1'), $journal, null));
2023-06-21 12:34:58 +02:00
return true;
}
2024-12-14 17:32:03 +01:00
public function addAmount(PiggyBank $piggyBank, Account $account, string $amount, ?TransactionJournal $journal = null): bool
{
$currentAmount = $this->getCurrentAmount($piggyBank, $account);
$pivot = $piggyBank->accounts()->where('accounts.id', $account->id)->first()->pivot;
$pivot->current_amount = bcadd($currentAmount, $amount);
2024-12-20 05:20:37 +01:00
$pivot->native_current_amount = null;
// also update native_current_amount.
2025-01-05 07:31:26 +01:00
$userCurrency = app('amount')->getDefaultCurrencyByUserGroup($this->user->userGroup);
2024-12-20 05:20:37 +01:00
if ($userCurrency->id !== $piggyBank->transaction_currency_id) {
2025-01-05 07:31:26 +01:00
$converter = new ExchangeRateConverter();
2024-12-20 05:20:37 +01:00
$converter->setIgnoreSettings(true);
$pivot->native_current_amount = $converter->convert($piggyBank->transactionCurrency, $userCurrency, today(), $pivot->current_amount);
}
2024-12-14 17:32:03 +01:00
$pivot->save();
2022-12-29 19:42:26 +01:00
2024-12-15 08:50:57 +01:00
Log::debug('ChangedAmount: addAmount [b]: Trigger change for positive amount.');
event(new ChangedAmount($piggyBank, $amount, $journal, null));
2022-12-29 19:42:26 +01:00
return true;
2020-03-21 14:20:40 +01:00
}
2024-12-14 17:32:03 +01:00
public function canAddAmount(PiggyBank $piggyBank, Account $account, string $amount): bool
2020-03-21 14:20:40 +01:00
{
2024-12-14 17:32:03 +01:00
Log::debug('Now in canAddAmount');
$today = today(config('app.timezone'))->endOfDay();
$leftOnAccount = $this->leftOnAccount($piggyBank, $account, $today);
$savedSoFar = $this->getCurrentAmount($piggyBank);
2022-03-27 18:30:46 +02:00
$maxAmount = $leftOnAccount;
2024-12-14 17:32:03 +01:00
2024-12-15 08:50:57 +01:00
Log::debug(sprintf('Left on account: %s on %s', $leftOnAccount, $today->format('Y-m-d H:i:s')));
Log::debug(sprintf('Saved so far: %s', $savedSoFar));
2024-12-14 17:32:03 +01:00
2024-11-30 16:02:30 +01:00
if (0 !== bccomp($piggyBank->target_amount, '0')) {
$leftToSave = bcsub($piggyBank->target_amount, $savedSoFar);
2022-03-27 18:30:46 +02:00
$maxAmount = 1 === bccomp($leftOnAccount, $leftToSave) ? $leftToSave : $leftOnAccount;
2024-12-15 08:50:57 +01:00
Log::debug(sprintf('Left to save: %s', $leftToSave));
Log::debug(sprintf('Maximum amount: %s', $maxAmount));
2022-03-27 18:30:46 +02:00
}
2025-01-05 07:31:26 +01:00
$compare = bccomp($amount, $maxAmount);
$result = $compare <= 0;
2020-03-21 14:20:40 +01:00
2024-12-15 08:50:57 +01:00
Log::debug(sprintf('Compare <= 0? %d, so canAddAmount is %s', $compare, var_export($result, true)));
2020-03-21 14:20:40 +01:00
return $result;
}
2024-12-14 17:32:03 +01:00
public function canRemoveAmount(PiggyBank $piggyBank, Account $account, string $amount): bool
2020-03-21 14:20:40 +01:00
{
2024-12-14 17:32:03 +01:00
$savedSoFar = $this->getCurrentAmount($piggyBank, $account);
2020-03-21 14:20:40 +01:00
return bccomp($amount, $savedSoFar) <= 0;
}
/**
2023-12-20 19:35:52 +01:00
* @throws \Exception
2020-03-21 14:20:40 +01:00
*/
public function destroy(PiggyBank $piggyBank): bool
{
2020-06-07 16:38:15 +02:00
$piggyBank->objectGroups()->sync([]);
2020-03-21 14:20:40 +01:00
$piggyBank->delete();
return true;
}
2022-03-29 14:59:58 +02:00
public function removeObjectGroup(PiggyBank $piggyBank): PiggyBank
2021-03-21 09:15:40 +01:00
{
2022-03-29 14:59:58 +02:00
$piggyBank->objectGroups()->sync([]);
return $piggyBank;
2021-03-21 09:15:40 +01:00
}
2020-03-21 14:20:40 +01:00
public function setCurrentAmount(PiggyBank $piggyBank, string $amount): PiggyBank
{
2025-01-05 07:31:26 +01:00
$repetition = $this->getRepetition($piggyBank);
2020-03-21 14:20:40 +01:00
if (null === $repetition) {
return $piggyBank;
}
2025-01-05 07:31:26 +01:00
$max = $piggyBank->target_amount;
2024-11-30 16:02:30 +01:00
if (1 === bccomp($amount, $max) && 0 !== bccomp($piggyBank->target_amount, '0')) {
2020-03-21 14:20:40 +01:00
$amount = $max;
}
2024-12-14 05:45:54 +01:00
$difference = bcsub($amount, $repetition->current_amount);
2024-11-30 16:02:30 +01:00
$repetition->current_amount = $amount;
2020-03-21 14:20:40 +01:00
$repetition->save();
if (-1 === bccomp($difference, '0')) {
2024-12-15 08:50:57 +01:00
Log::debug('ChangedAmount: addAmount [c]: Trigger change for negative amount.');
event(new ChangedAmount($piggyBank, $difference, null, null));
}
if (1 === bccomp($difference, '0')) {
2024-12-15 08:50:57 +01:00
Log::debug('ChangedAmount: addAmount [d]: Trigger change for positive amount.');
event(new ChangedAmount($piggyBank, $difference, null, null));
}
2020-03-21 14:20:40 +01:00
return $piggyBank;
}
2021-03-12 06:20:01 +01:00
public function setObjectGroup(PiggyBank $piggyBank, string $objectGroupTitle): PiggyBank
{
$objectGroup = $this->findOrCreateObjectGroup($objectGroupTitle);
if (null !== $objectGroup) {
$piggyBank->objectGroups()->sync([$objectGroup->id]);
}
return $piggyBank;
}
2023-05-29 13:56:55 +02:00
/**
2020-12-02 06:41:42 +01:00
* @throws FireflyException
2020-03-21 14:20:40 +01:00
*/
public function store(array $data): PiggyBank
{
$factory = new PiggyBankFactory();
$factory->user = $this->user;
2024-12-14 05:45:54 +01:00
2024-12-01 18:16:48 +01:00
return $factory->store($data);
2020-03-21 14:20:40 +01:00
}
2020-10-27 06:53:33 +01:00
public function update(PiggyBank $piggyBank, array $data): PiggyBank
{
2025-01-05 07:31:26 +01:00
$piggyBank = $this->updateProperties($piggyBank, $data);
2021-03-14 06:20:23 +01:00
if (array_key_exists('notes', $data)) {
2024-12-20 05:20:37 +01:00
$this->updateNote($piggyBank, (string) $data['notes']);
2021-03-14 06:20:23 +01:00
}
2020-03-21 14:20:40 +01:00
2020-06-30 20:33:08 +02:00
// update the order of the piggy bank:
2025-01-05 07:31:26 +01:00
$oldOrder = $piggyBank->order;
$newOrder = (int) ($data['order'] ?? $oldOrder);
2020-06-30 20:33:08 +02:00
if ($oldOrder !== $newOrder) {
2021-03-14 06:20:23 +01:00
$this->setOrder($piggyBank, $newOrder);
2020-06-30 20:33:08 +02:00
}
2024-12-14 17:32:03 +01:00
// update the accounts
$factory = new PiggyBankFactory();
2024-12-14 17:32:03 +01:00
$factory->user = $this->user;
$factory->linkToAccountIds($piggyBank, $data['accounts']);
2024-12-15 08:50:57 +01:00
// if the piggy bank is now smaller than the sum of the money saved,
// remove money from all accounts until the piggy bank is the right amount.
2024-12-14 17:32:03 +01:00
$currentAmount = $this->getCurrentAmount($piggyBank);
2024-12-15 08:50:57 +01:00
if (1 === bccomp($currentAmount, $piggyBank->target_amount) && 0 !== bccomp($piggyBank->target_amount, '0')) {
Log::debug(sprintf('Current amount is %s, target amount is %s', $currentAmount, $piggyBank->target_amount));
$difference = bcsub($piggyBank->target_amount, $currentAmount);
// an amount will be removed, create "negative" event:
2024-12-15 08:50:57 +01:00
Log::debug(sprintf('ChangedAmount: is triggered with difference "%s"', $difference));
event(new ChangedAmount($piggyBank, $difference, null, null));
2020-03-21 14:20:40 +01:00
2024-12-14 17:32:03 +01:00
// question is, from which account(s) to remove the difference?
// solution: just start from the top until there is no more money left to remove.
$this->removeAmountFromAll($piggyBank, app('steam')->positive($difference));
2020-03-21 14:20:40 +01:00
}
2020-06-30 19:05:35 +02:00
// update using name:
2021-03-14 06:20:23 +01:00
if (array_key_exists('object_group_title', $data)) {
2024-12-20 05:20:37 +01:00
$objectGroupTitle = (string) $data['object_group_title'];
2020-12-02 06:41:42 +01:00
if ('' !== $objectGroupTitle) {
$objectGroup = $this->findOrCreateObjectGroup($objectGroupTitle);
if (null !== $objectGroup) {
$piggyBank->objectGroups()->sync([$objectGroup->id]);
$piggyBank->save();
}
return $piggyBank;
}
2023-11-05 16:55:16 +01:00
$piggyBank->objectGroups()->sync([]);
$piggyBank->save();
2020-06-30 19:05:35 +02:00
}
2020-10-20 04:42:44 +02:00
2020-06-30 19:05:35 +02:00
// try also with ID:
2020-12-02 06:41:42 +01:00
if (array_key_exists('object_group_id', $data)) {
2024-12-20 05:20:37 +01:00
$objectGroupId = (int) ($data['object_group_id'] ?? 0);
2020-12-02 06:41:42 +01:00
if (0 !== $objectGroupId) {
$objectGroup = $this->findObjectGroupById($objectGroupId);
if (null !== $objectGroup) {
$piggyBank->objectGroups()->sync([$objectGroup->id]);
$piggyBank->save();
}
return $piggyBank;
2020-06-07 11:31:01 +02:00
}
}
2020-03-21 14:20:40 +01:00
return $piggyBank;
}
2021-03-12 06:20:01 +01:00
private function updateProperties(PiggyBank $piggyBank, array $data): PiggyBank
{
if (array_key_exists('name', $data) && '' !== $data['name']) {
$piggyBank->name = $data['name'];
}
2024-12-14 17:32:03 +01:00
if (array_key_exists('target_amount', $data) && '' !== $data['target_amount']) {
$piggyBank->target_amount = $data['target_amount'];
2021-03-12 06:20:01 +01:00
}
2024-12-14 17:32:03 +01:00
if (array_key_exists('target_amount', $data) && '' === $data['target_amount']) {
2024-11-30 16:02:30 +01:00
$piggyBank->target_amount = '0';
2022-12-24 05:48:04 +01:00
}
2024-12-14 17:32:03 +01:00
if (array_key_exists('target_date', $data) && '' !== $data['target_date']) {
$piggyBank->target_date = $data['target_date'];
$piggyBank->target_date_tz = $data['target_date']?->format('e');
2021-03-12 06:20:01 +01:00
}
2024-12-14 17:32:03 +01:00
if (array_key_exists('start_date', $data)) {
$piggyBank->start_date = $data['start_date'];
$piggyBank->start_date_tz = $data['target_date']?->format('e');
2020-06-30 20:33:08 +02:00
}
2021-03-14 06:20:23 +01:00
$piggyBank->save();
2020-06-30 20:33:08 +02:00
2021-03-14 06:20:23 +01:00
return $piggyBank;
2020-06-30 20:33:08 +02:00
}
2024-12-22 08:43:12 +01:00
public function updateNote(PiggyBank $piggyBank, string $note): void
{
if ('' === $note) {
$dbNote = $piggyBank->notes()->first();
$dbNote?->delete();
return;
}
2025-01-05 07:31:26 +01:00
$dbNote = $piggyBank->notes()->first();
2024-12-22 08:43:12 +01:00
if (null === $dbNote) {
$dbNote = new Note();
$dbNote->noteable()->associate($piggyBank);
}
$dbNote->text = trim($note);
$dbNote->save();
}
public function setOrder(PiggyBank $piggyBank, int $newOrder): bool
{
2025-01-05 07:31:26 +01:00
$oldOrder = $piggyBank->order;
2024-12-22 08:43:12 +01:00
// Log::debug(sprintf('Will move piggy bank #%d ("%s") from %d to %d', $piggyBank->id, $piggyBank->name, $oldOrder, $newOrder));
if ($newOrder > $oldOrder) {
PiggyBank::leftJoin('account_piggy_bank', 'account_piggy_bank.piggy_bank_id', '=', 'piggy_banks.id')
2025-01-05 07:31:26 +01:00
->leftJoin('accounts', 'accounts.id', '=', 'account_piggy_bank.account_id')
->where('accounts.user_id', $this->user->id)
->where('piggy_banks.order', '<=', $newOrder)->where('piggy_banks.order', '>', $oldOrder)
->where('piggy_banks.id', '!=', $piggyBank->id)
->distinct()->decrement('piggy_banks.order')
;
2024-12-22 08:43:12 +01:00
$piggyBank->order = $newOrder;
Log::debug(sprintf('[1] Order of piggy #%d ("%s") from %d to %d', $piggyBank->id, $piggyBank->name, $oldOrder, $newOrder));
$piggyBank->save();
return true;
}
PiggyBank::leftJoin('account_piggy_bank', 'account_piggy_bank.piggy_bank_id', '=', 'piggy_banks.id')
2025-01-05 07:31:26 +01:00
->leftJoin('accounts', 'accounts.id', '=', 'account_piggy_bank.account_id')
->where('accounts.user_id', $this->user->id)
->where('piggy_banks.order', '>=', $newOrder)->where('piggy_banks.order', '<', $oldOrder)
->where('piggy_banks.id', '!=', $piggyBank->id)
->distinct()->increment('piggy_banks.order')
;
2024-12-22 08:43:12 +01:00
$piggyBank->order = $newOrder;
Log::debug(sprintf('[2] Order of piggy #%d ("%s") from %d to %d', $piggyBank->id, $piggyBank->name, $oldOrder, $newOrder));
$piggyBank->save();
return true;
}
public function removeAmountFromAll(PiggyBank $piggyBank, string $amount): void
{
foreach ($piggyBank->accounts as $account) {
$current = $account->pivot->current_amount;
// if this account contains more than the amount, remove the amount and return.
if (1 === bccomp($current, $amount)) {
$this->removeAmount($piggyBank, $account, $amount);
return;
}
// if this account contains less than the amount, remove the current amount, update the amount and continue.
2025-01-04 08:42:06 +01:00
$this->removeAmount($piggyBank, $account, $current);
2025-01-05 07:31:26 +01:00
$amount = bcsub($amount, $current);
2024-12-22 08:43:12 +01:00
}
}
2020-05-01 17:47:56 +02:00
}