Files
firefly-iii/app/Repositories/Bill/BillRepository.php

805 lines
26 KiB
PHP
Raw Normal View History

2015-02-25 15:19:14 +01:00
<?php
/**
* BillRepository.php
2020-02-16 14:00:57 +01:00
* Copyright (c) 2019 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.
2017-10-21 08:40:00 +02:00
*
* This program is distributed in the hope that it will be useful,
2017-10-21 08:40:00 +02:00
* 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.
2017-10-21 08:40:00 +02:00
*
* 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/>.
*/
declare(strict_types=1);
2015-02-25 15:19:14 +01:00
namespace FireflyIII\Repositories\Bill;
use Carbon\Carbon;
2015-05-08 14:00:49 +02:00
use DB;
2019-10-30 20:02:21 +01:00
use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Factory\BillFactory;
2020-05-07 06:44:01 +02:00
use FireflyIII\Models\Attachment;
2015-02-25 15:19:14 +01:00
use FireflyIII\Models\Bill;
2018-04-29 07:46:03 +02:00
use FireflyIII\Models\Note;
2016-10-21 06:26:12 +02:00
use FireflyIII\Models\Transaction;
2015-02-25 15:19:14 +01:00
use FireflyIII\Models\TransactionJournal;
use FireflyIII\Repositories\Journal\JournalRepositoryInterface;
2020-07-01 06:33:21 +02:00
use FireflyIII\Repositories\ObjectGroup\CreatesObjectGroups;
use FireflyIII\Services\Internal\Destroy\BillDestroyService;
use FireflyIII\Services\Internal\Update\BillUpdateService;
2016-10-20 21:40:45 +02:00
use FireflyIII\Support\CacheProperties;
2016-03-03 08:40:25 +01:00
use FireflyIII\User;
2015-12-26 09:39:35 +01:00
use Illuminate\Database\Query\JoinClause;
use Illuminate\Pagination\LengthAwarePaginator;
2015-04-05 18:20:06 +02:00
use Illuminate\Support\Collection;
2016-10-20 21:40:45 +02:00
use Log;
2020-05-07 06:44:01 +02:00
use Storage;
2015-02-25 15:19:14 +01:00
/**
2017-11-15 12:25:49 +01:00
* Class BillRepository.
2019-08-17 10:47:29 +02:00
*
2015-02-25 15:19:14 +01:00
*/
class BillRepository implements BillRepositoryInterface
{
2020-07-01 06:33:21 +02:00
use CreatesObjectGroups;
2020-08-06 20:08:04 +02:00
2020-07-11 15:13:15 +02:00
private User $user;
2016-03-03 08:40:25 +01:00
2015-04-05 18:20:06 +02:00
/**
* @param Bill $bill
*
2016-04-06 09:27:45 +02:00
* @return bool
2017-12-22 18:32:43 +01:00
*
2018-04-02 15:10:40 +02:00
2015-04-05 18:20:06 +02:00
*/
2016-02-06 18:59:48 +01:00
public function destroy(Bill $bill): bool
2015-04-05 18:20:06 +02:00
{
/** @var BillDestroyService $service */
$service = app(BillDestroyService::class);
$service->destroy($bill);
2016-02-06 18:59:48 +01:00
return true;
2015-04-05 18:20:06 +02:00
}
2016-04-01 13:07:19 +02:00
/**
* Find a bill by ID.
*
* @param int $billId
*
* @return Bill
*/
2018-02-16 15:19:19 +01:00
public function find(int $billId): ?Bill
2016-04-01 13:07:19 +02:00
{
2018-04-02 15:10:40 +02:00
return $this->user->bills()->find($billId);
2016-04-01 13:07:19 +02:00
}
/**
* Find bill by parameters.
*
* @param int|null $billId
* @param string|null $billName
*
* @return Bill|null
*/
2019-05-04 20:58:43 +02:00
public function findBill(?int $billId, ?string $billName): ?Bill
{
if (null !== $billId) {
2020-11-11 19:14:05 +01:00
$searchResult = $this->find((int)$billId);
if (null !== $searchResult) {
Log::debug(sprintf('Found bill based on #%d, will return it.', $billId));
return $searchResult;
}
}
if (null !== $billName) {
2020-11-11 19:14:05 +01:00
$searchResult = $this->findByName((string)$billName);
if (null !== $searchResult) {
Log::debug(sprintf('Found bill based on "%s", will return it.', $billName));
return $searchResult;
}
}
Log::debug('Found nothing');
return null;
}
2016-07-23 21:37:06 +02:00
/**
* Find a bill by name.
*
* @param string $name
*
* @return Bill
*/
2018-02-16 15:19:19 +01:00
public function findByName(string $name): ?Bill
2016-07-23 21:37:06 +02:00
{
$bills = $this->user->bills()->get(['bills.*']);
2016-07-23 21:37:06 +02:00
2019-08-03 19:17:59 +02:00
// TODO no longer need to loop like this
2016-07-23 21:37:06 +02:00
/** @var Bill $bill */
foreach ($bills as $bill) {
if ($bill->name === $name) {
return $bill;
}
}
2018-02-16 15:19:19 +01:00
return null;
2016-07-23 21:37:06 +02:00
}
2016-01-20 15:21:27 +01:00
/**
* @return Collection
*/
2016-02-06 18:59:48 +01:00
public function getActiveBills(): Collection
2016-01-20 15:21:27 +01:00
{
2020-10-23 19:11:25 +02:00
return $this->user->bills()
2016-03-03 08:40:25 +01:00
->where('active', 1)
2019-05-04 20:58:43 +02:00
->orderBy('bills.name', 'ASC')
->get(['bills.*', DB::raw('((bills.amount_min + bills.amount_max) / 2) AS expectedAmount'),]);
2016-01-20 15:21:27 +01:00
}
2018-12-09 13:09:43 +01:00
/**
* Get all attachments.
*
* @param Bill $bill
*
* @return Collection
*/
public function getAttachments(Bill $bill): Collection
{
2020-05-07 06:44:01 +02:00
$set = $bill->attachments()->get();
/** @var Storage $disk */
$disk = Storage::disk('upload');
2020-10-23 19:11:25 +02:00
return $set->each(
2020-05-07 06:44:01 +02:00
static function (Attachment $attachment) use ($disk) {
$notes = $attachment->notes()->first();
$attachment->file_exists = $disk->exists($attachment->fileName());
$attachment->notes = $notes ? $notes->text : '';
return $attachment;
}
);
2018-12-09 13:09:43 +01:00
}
2015-04-05 18:20:06 +02:00
/**
* @return Collection
*/
2016-02-06 18:59:48 +01:00
public function getBills(): Collection
2015-04-05 18:20:06 +02:00
{
/** @var Collection $set */
2020-06-30 20:33:08 +02:00
return $this->user->bills()
->orderBy('order', 'ASC')
->orderBy('active', 'DESC')
->orderBy('name', 'ASC')->get();
2015-04-05 18:20:06 +02:00
}
/**
* @param Collection $accounts
*
* @return Collection
*/
2016-02-06 18:59:48 +01:00
public function getBillsForAccounts(Collection $accounts): Collection
{
2019-08-27 10:25:23 +02:00
$fields = ['bills.id', 'bills.created_at', 'bills.updated_at', 'bills.deleted_at', 'bills.user_id', 'bills.name', 'bills.amount_min',
'bills.amount_max', 'bills.date', 'bills.transaction_currency_id', 'bills.repeat_freq', 'bills.skip', 'bills.automatch', 'bills.active',];
$ids = $accounts->pluck('id')->toArray();
2020-11-11 19:14:05 +01:00
2020-10-23 19:11:25 +02:00
return $this->user->bills()
2020-11-11 19:14:05 +01:00
->leftJoin(
'transaction_journals',
static function (JoinClause $join) {
$join->on('transaction_journals.bill_id', '=', 'bills.id')->whereNull('transaction_journals.deleted_at');
}
)
->leftJoin(
'transactions',
static function (JoinClause $join) {
$join->on('transaction_journals.id', '=', 'transactions.transaction_journal_id')->where('transactions.amount', '<', 0);
}
)
->whereIn('transactions.account_id', $ids)
->whereNull('transaction_journals.deleted_at')
->orderBy('bills.active', 'DESC')
->orderBy('bills.name', 'ASC')
->groupBy($fields)
->get($fields);
}
2016-01-20 15:21:27 +01:00
/**
* Get the total amount of money paid for the users active bills in the date range given.
2016-10-21 06:26:12 +02:00
* This amount will be negative (they're expenses). This method is equal to
* getBillsUnpaidInRange. So the debug comments are gone.
2016-01-20 15:21:27 +01:00
*
* @param Carbon $start
* @param Carbon $end
*
* @return string
*/
2016-02-06 18:59:48 +01:00
public function getBillsPaidInRange(Carbon $start, Carbon $end): string
2016-01-20 15:21:27 +01:00
{
2016-10-21 06:26:12 +02:00
$bills = $this->getActiveBills();
$sum = '0';
2016-01-20 15:21:27 +01:00
/** @var Bill $bill */
foreach ($bills as $bill) {
2016-10-21 13:20:51 +02:00
/** @var Collection $set */
$set = $bill->transactionJournals()->after($start)->before($end)->get(['transaction_journals.*']);
if ($set->count() > 0) {
$journalIds = $set->pluck('id')->toArray();
2020-11-11 19:14:05 +01:00
$amount = (string)Transaction::whereIn('transaction_journal_id', $journalIds)->where('amount', '<', 0)->sum('amount');
2016-10-21 13:20:51 +02:00
$sum = bcadd($sum, $amount);
Log::debug(sprintf('Total > 0, so add to sum %f, which becomes %f', $amount, $sum));
2016-01-20 15:21:27 +01:00
}
}
2016-10-21 06:26:12 +02:00
return $sum;
2016-01-20 15:21:27 +01:00
}
2018-08-28 05:21:23 +02:00
/**
* Get the total amount of money paid for the users active bills in the date range given,
* grouped per currency.
*
* @param Carbon $start
* @param Carbon $end
*
* @return array
*/
public function getBillsPaidInRangePerCurrency(Carbon $start, Carbon $end): array
{
$bills = $this->getActiveBills();
$return = [];
/** @var Bill $bill */
foreach ($bills as $bill) {
/** @var Collection $set */
$set = $bill->transactionJournals()->after($start)->before($end)->get(['transaction_journals.*']);
2020-11-11 19:14:05 +01:00
$currencyId = (int)$bill->transaction_currency_id;
2018-08-28 05:21:23 +02:00
if ($set->count() > 0) {
$journalIds = $set->pluck('id')->toArray();
2020-11-11 19:14:05 +01:00
$amount = (string)Transaction::whereIn('transaction_journal_id', $journalIds)->where('amount', '<', 0)->sum('amount');
2018-08-28 05:21:23 +02:00
$return[$currencyId] = $return[$currencyId] ?? '0';
$return[$currencyId] = bcadd($amount, $return[$currencyId]);
Log::debug(sprintf('Total > 0, so add to sum %f, which becomes %f (currency %d)', $amount, $return[$currencyId], $currencyId));
}
}
return $return;
}
2016-01-20 15:21:27 +01:00
/**
* Get the total amount of money due for the users active bills in the date range given. This amount will be positive.
*
* @param Carbon $start
* @param Carbon $end
*
* @return string
*/
2016-02-06 18:59:48 +01:00
public function getBillsUnpaidInRange(Carbon $start, Carbon $end): string
2016-01-20 15:21:27 +01:00
{
2016-10-21 06:26:12 +02:00
$bills = $this->getActiveBills();
$sum = '0';
2016-01-20 15:21:27 +01:00
/** @var Bill $bill */
foreach ($bills as $bill) {
2016-10-21 13:20:51 +02:00
Log::debug(sprintf('Now at bill #%d (%s)', $bill->id, $bill->name));
$dates = $this->getPayDatesInRange($bill, $start, $end);
$count = $bill->transactionJournals()->after($start)->before($end)->count();
$total = $dates->count() - $count;
2016-10-21 06:26:12 +02:00
2016-10-21 13:20:51 +02:00
Log::debug(sprintf('Dates = %d, journalCount = %d, total = %d', $dates->count(), $count, $total));
if ($total > 0) {
$average = bcdiv(bcadd($bill->amount_max, $bill->amount_min), '2');
2020-11-11 19:14:05 +01:00
$multi = bcmul($average, (string)$total);
2016-10-21 13:20:51 +02:00
$sum = bcadd($sum, $multi);
Log::debug(sprintf('Total > 0, so add to sum %f, which becomes %f', $multi, $sum));
2016-01-20 15:21:27 +01:00
}
}
2016-10-21 06:26:12 +02:00
return $sum;
2016-01-20 15:21:27 +01:00
}
2018-08-28 05:21:23 +02:00
/**
* Get the total amount of money due for the users active bills in the date range given.
*
* @param Carbon $start
* @param Carbon $end
*
* @return array
*/
public function getBillsUnpaidInRangePerCurrency(Carbon $start, Carbon $end): array
{
$bills = $this->getActiveBills();
$return = [];
/** @var Bill $bill */
foreach ($bills as $bill) {
Log::debug(sprintf('Now at bill #%d (%s)', $bill->id, $bill->name));
$dates = $this->getPayDatesInRange($bill, $start, $end);
$count = $bill->transactionJournals()->after($start)->before($end)->count();
$total = $dates->count() - $count;
2020-11-11 19:14:05 +01:00
$currencyId = (int)$bill->transaction_currency_id;
2018-08-28 05:21:23 +02:00
Log::debug(sprintf('Dates = %d, journalCount = %d, total = %d', $dates->count(), $count, $total));
if ($total > 0) {
$average = bcdiv(bcadd($bill->amount_max, $bill->amount_min), '2');
2020-11-11 19:14:05 +01:00
$multi = bcmul($average, (string)$total);
2018-08-28 05:21:23 +02:00
$return[$currencyId] = $return[$currencyId] ?? '0';
$return[$currencyId] = bcadd($return[$currencyId], $multi);
Log::debug(sprintf('Total > 0, so add to sum %f, which becomes %f (for currency %d)', $multi, $return[$currencyId], $currencyId));
}
}
return $return;
}
2018-05-07 20:35:14 +02:00
/**
* Get all bills with these ID's.
*
* @param array $billIds
*
* @return Collection
*/
public function getByIds(array $billIds): Collection
{
return $this->user->bills()->whereIn('id', $billIds)->get();
}
2018-04-29 07:46:03 +02:00
/**
* Get text or return empty string.
*
* @param Bill $bill
*
* @return string
*/
public function getNoteText(Bill $bill): string
{
/** @var Note $note */
$note = $bill->notes()->first();
if (null !== $note) {
2020-11-11 19:14:05 +01:00
return (string)$note->text;
2018-04-29 07:46:03 +02:00
}
return '';
}
2016-07-23 21:37:06 +02:00
/**
2016-10-23 14:56:05 +02:00
* @param Bill $bill
2016-07-23 21:37:06 +02:00
*
2020-08-06 20:08:04 +02:00
* @return array
2016-07-23 21:37:06 +02:00
*/
2020-08-06 20:08:04 +02:00
public function getOverallAverage(Bill $bill): array
2016-07-23 21:37:06 +02:00
{
/** @var JournalRepositoryInterface $repos */
$repos = app(JournalRepositoryInterface::class);
$repos->setUser($this->user);
2020-08-06 20:08:04 +02:00
// get and sort on currency
2020-11-11 19:14:05 +01:00
$result = [];
$journals = $bill->transactionJournals()->get();
2020-08-06 20:08:04 +02:00
2016-07-23 21:37:06 +02:00
/** @var TransactionJournal $journal */
foreach ($journals as $journal) {
2020-08-06 20:08:04 +02:00
/** @var Transaction $transaction */
$transaction = $journal->transactions()->where('amount', '<', 0)->first();
2020-11-11 19:14:05 +01:00
$currencyId = (int)$journal->transaction_currency_id;
2020-08-06 20:08:04 +02:00
$currency = $journal->transactionCurrency;
$result[$currencyId] = $result[$currencyId] ?? [
'sum' => '0',
'count' => 0,
'avg' => '0',
'currency_id' => $currency->id,
'currency_code' => $currency->code,
'currency_symbol' => $currency->symbol,
'currency_decimal_places' => $currency->decimal_places,
];
$result[$currencyId]['sum'] = bcadd($result[$currencyId]['sum'], $transaction->amount);
$result[$currencyId]['count']++;
2016-07-23 21:37:06 +02:00
}
2020-08-06 20:08:04 +02:00
// after loop, re-loop for avg.
/**
* @var int $currencyId
* @var array $arr
*/
foreach ($result as $currencyId => $arr) {
2020-11-11 19:14:05 +01:00
$result[$currencyId]['avg'] = bcdiv($arr['sum'], (string)$arr['count']);
2020-08-06 20:08:04 +02:00
}
2020-11-11 19:14:05 +01:00
2020-08-06 20:08:04 +02:00
return $result;
2016-07-23 21:37:06 +02:00
}
/**
* @param int $size
*
* @return LengthAwarePaginator
*/
public function getPaginator(int $size): LengthAwarePaginator
{
2019-08-23 06:40:48 +02:00
return $this->user->bills()
->orderBy('active', 'DESC')
->orderBy('name', 'ASC')->paginate($size);
}
2016-10-23 14:56:05 +02:00
/**
2017-06-28 15:45:28 +02:00
* The "paid dates" list is a list of dates of transaction journals that are linked to this bill.
*
2016-10-23 14:56:05 +02:00
* @param Bill $bill
* @param Carbon $start
* @param Carbon $end
*
* @return Collection
*/
public function getPaidDatesInRange(Bill $bill, Carbon $start, Carbon $end): Collection
{
2020-01-09 19:52:47 +01:00
Log::debug('Now in getPaidDatesInRange()');
2020-11-11 19:14:05 +01:00
return $bill->transactionJournals()
->before($end)->after($start)->get(
2019-08-21 18:01:57 +02:00
[
'transaction_journals.id', 'transaction_journals.date',
'transaction_journals.transaction_group_id',
]
);
2016-10-23 14:56:05 +02:00
}
2016-10-21 13:20:51 +02:00
/**
* Between start and end, tells you on which date(s) the bill is expected to hit.
*
* @param Bill $bill
* @param Carbon $start
* @param Carbon $end
*
* @return Collection
*/
public function getPayDatesInRange(Bill $bill, Carbon $start, Carbon $end): Collection
{
2018-08-06 19:14:30 +02:00
$set = new Collection;
2016-10-21 13:20:51 +02:00
$currentStart = clone $start;
2021-02-22 18:40:46 +01:00
//Log::debug(sprintf('Now at bill "%s" (%s)', $bill->name, $bill->repeat_freq));
//Log::debug(sprintf('First currentstart is %s', $currentStart->format('Y-m-d')));
2016-10-21 13:20:51 +02:00
while ($currentStart <= $end) {
Log::debug(sprintf('Currentstart is now %s.', $currentStart->format('Y-m-d')));
$nextExpectedMatch = $this->nextDateMatch($bill, $currentStart);
2021-02-22 18:40:46 +01:00
//Log::debug(sprintf('Next Date match after %s is %s', $currentStart->format('Y-m-d'), $nextExpectedMatch->format('Y-m-d')));
2018-07-23 21:49:15 +02:00
if ($nextExpectedMatch > $end) {// If nextExpectedMatch is after end, we continue
2016-10-21 13:20:51 +02:00
break;
}
$set->push(clone $nextExpectedMatch);
2021-02-22 18:40:46 +01:00
//Log::debug(sprintf('Now %d dates in set.', $set->count()));
2016-10-21 13:20:51 +02:00
$nextExpectedMatch->addDay();
2021-02-22 18:40:46 +01:00
//Log::debug(sprintf('Currentstart (%s) has become %s.', $currentStart->format('Y-m-d'), $nextExpectedMatch->format('Y-m-d')));
2016-10-21 13:20:51 +02:00
$currentStart = clone $nextExpectedMatch;
}
$simple = $set->each(
2019-08-27 10:25:23 +02:00
static function (Carbon $date) {
2016-10-21 13:20:51 +02:00
return $date->format('Y-m-d');
}
);
2021-02-22 18:40:46 +01:00
//Log::debug(sprintf('Found dates between %s and %s:', $start->format('Y-m-d'), $end->format('Y-m-d')), $simple->toArray());
2016-10-21 13:20:51 +02:00
return $set;
}
2018-04-14 09:59:04 +02:00
/**
* Return all rules for one bill
*
* @param Bill $bill
*
* @return Collection
*/
public function getRulesForBill(Bill $bill): Collection
{
return $this->user->rules()
->leftJoin('rule_actions', 'rule_actions.rule_id', '=', 'rules.id')
->where('rule_actions.action_type', 'link_to_bill')
->where('rule_actions.action_value', $bill->name)
->get(['rules.*']);
}
2018-04-08 17:36:37 +02:00
/**
* Return all rules related to the bills in the collection, in an associative array:
* 5= billid
*
* 5 => [['id' => 1, 'title' => 'Some rule'],['id' => 2, 'title' => 'Some other rule']]
*
* @param Collection $collection
*
* @return array
*/
public function getRulesForBills(Collection $collection): array
{
$rules = $this->user->rules()
->leftJoin('rule_actions', 'rule_actions.rule_id', '=', 'rules.id')
->where('rule_actions.action_type', 'link_to_bill')
2018-05-07 20:35:14 +02:00
->get(['rules.id', 'rules.title', 'rule_actions.action_value', 'rules.active']);
2018-04-08 17:36:37 +02:00
$array = [];
foreach ($rules as $rule) {
$array[$rule->action_value] = $array[$rule->action_value] ?? [];
2018-05-07 20:35:14 +02:00
$array[$rule->action_value][] = ['id' => $rule->id, 'title' => $rule->title, 'active' => $rule->active];
2018-04-08 17:36:37 +02:00
}
$return = [];
foreach ($collection as $bill) {
$return[$bill->id] = $array[$bill->name] ?? [];
}
return $return;
}
2016-07-23 21:37:06 +02:00
/**
* @param Bill $bill
* @param Carbon $date
*
2020-08-06 20:08:04 +02:00
* @return array
2016-07-23 21:37:06 +02:00
*/
2020-08-06 20:08:04 +02:00
public function getYearAverage(Bill $bill, Carbon $date): array
2016-07-23 21:37:06 +02:00
{
/** @var JournalRepositoryInterface $repos */
$repos = app(JournalRepositoryInterface::class);
$repos->setUser($this->user);
2020-08-06 20:08:04 +02:00
// get and sort on currency
$result = [];
$journals = $bill->transactionJournals()
->where('date', '>=', $date->year . '-01-01 00:00:00')
->where('date', '<=', $date->year . '-12-31 23:59:59')
2016-07-23 21:37:06 +02:00
->get();
2020-08-06 20:08:04 +02:00
2016-07-23 21:37:06 +02:00
/** @var TransactionJournal $journal */
foreach ($journals as $journal) {
2020-08-06 20:08:04 +02:00
/** @var Transaction $transaction */
2020-11-11 19:14:05 +01:00
$transaction = $journal->transactions()->where('amount', '<', 0)->first();
if (null === $transaction) {
continue;
}
$currencyId = (int)$journal->transaction_currency_id;
2020-08-06 20:08:04 +02:00
$currency = $journal->transactionCurrency;
$result[$currencyId] = $result[$currencyId] ?? [
'sum' => '0',
'count' => 0,
'avg' => '0',
'currency_id' => $currency->id,
'currency_code' => $currency->code,
'currency_symbol' => $currency->symbol,
'currency_decimal_places' => $currency->decimal_places,
];
$result[$currencyId]['sum'] = bcadd($result[$currencyId]['sum'], $transaction->amount);
$result[$currencyId]['count']++;
2016-07-23 21:37:06 +02:00
}
2020-08-06 20:08:04 +02:00
// after loop, re-loop for avg.
/**
* @var int $currencyId
* @var array $arr
*/
foreach ($result as $currencyId => $arr) {
2020-11-11 19:14:05 +01:00
$result[$currencyId]['avg'] = bcdiv($arr['sum'], (string)$arr['count']);
2020-08-06 20:08:04 +02:00
}
2020-11-11 19:14:05 +01:00
2020-08-06 20:08:04 +02:00
return $result;
2016-07-23 21:37:06 +02:00
}
2018-04-14 09:59:04 +02:00
/**
* Link a set of journals to a bill.
*
2019-08-21 18:01:57 +02:00
* @param Bill $bill
2019-07-21 17:15:06 +02:00
* @param array $transactions
2018-04-14 09:59:04 +02:00
*/
2019-07-21 17:15:06 +02:00
public function linkCollectionToBill(Bill $bill, array $transactions): void
2018-04-14 09:59:04 +02:00
{
2018-04-14 23:25:28 +02:00
/** @var Transaction $transaction */
foreach ($transactions as $transaction) {
2020-11-11 19:14:05 +01:00
$journal = $bill->user->transactionJournals()->find((int)$transaction['transaction_journal_id']);
2018-04-14 23:23:47 +02:00
$journal->bill_id = $bill->id;
$journal->save();
Log::debug(sprintf('Linked journal #%d to bill #%d', $journal->id, $bill->id));
}
2018-04-14 09:59:04 +02:00
}
2015-02-25 15:19:14 +01:00
/**
2016-10-21 06:26:12 +02:00
* Given a bill and a date, this method will tell you at which moment this bill expects its next
* transaction. Whether or not it is there already, is not relevant.
*
* @param Bill $bill
* @param Carbon $date
*
* @return \Carbon\Carbon
*/
public function nextDateMatch(Bill $bill, Carbon $date): Carbon
{
$cache = new CacheProperties;
$cache->addProperty($bill->id);
$cache->addProperty('nextDateMatch');
$cache->addProperty($date);
if ($cache->has()) {
2017-03-04 11:19:44 +01:00
return $cache->get(); // @codeCoverageIgnore
2016-10-21 06:26:12 +02:00
}
// find the most recent date for this bill NOT in the future. Cache this date:
$start = clone $bill->date;
2016-10-21 13:20:51 +02:00
while ($start < $date) {
$start = app('navigation')->addPeriod($start, $bill->repeat_freq, $bill->skip);
2016-10-21 06:26:12 +02:00
}
$end = app('navigation')->addPeriod($start, $bill->repeat_freq, $bill->skip);
2016-10-21 13:20:51 +02:00
Log::debug('nextDateMatch: Final start is ' . $start->format('Y-m-d'));
Log::debug('nextDateMatch: Matching end is ' . $end->format('Y-m-d'));
2016-10-21 06:26:12 +02:00
$cache->store($start);
return $start;
}
/**
* Given the date in $date, this method will return a moment in the future where the bill is expected to be paid.
*
2016-10-20 21:40:45 +02:00
* @param Bill $bill
* @param Carbon $date
2015-02-25 15:19:14 +01:00
*
2016-10-20 21:40:45 +02:00
* @return Carbon
2015-02-25 15:19:14 +01:00
*/
2016-10-20 21:40:45 +02:00
public function nextExpectedMatch(Bill $bill, Carbon $date): Carbon
2015-02-25 15:19:14 +01:00
{
2016-10-20 21:40:45 +02:00
$cache = new CacheProperties;
$cache->addProperty($bill->id);
$cache->addProperty('nextExpectedMatch');
2016-10-21 06:26:12 +02:00
$cache->addProperty($date);
2016-10-20 21:40:45 +02:00
if ($cache->has()) {
2017-03-04 11:19:44 +01:00
return $cache->get(); // @codeCoverageIgnore
2015-02-25 15:19:14 +01:00
}
2016-10-20 21:40:45 +02:00
// find the most recent date for this bill NOT in the future. Cache this date:
$start = clone $bill->date;
Log::debug('nextExpectedMatch: Start is ' . $start->format('Y-m-d'));
2016-10-20 21:40:45 +02:00
2016-10-21 07:29:25 +02:00
while ($start < $date) {
Log::debug(sprintf('$start (%s) < $date (%s)', $start->format('Y-m-d'), $date->format('Y-m-d')));
$start = app('navigation')->addPeriod($start, $bill->repeat_freq, $bill->skip);
2016-10-20 21:40:45 +02:00
Log::debug('Start is now ' . $start->format('Y-m-d'));
2016-10-21 07:29:25 +02:00
}
2016-10-20 21:40:45 +02:00
$end = app('navigation')->addPeriod($start, $bill->repeat_freq, $bill->skip);
2016-10-20 21:40:45 +02:00
// see if the bill was paid in this period.
$journalCount = $bill->transactionJournals()->before($end)->after($start)->count();
if ($journalCount > 0) {
// this period had in fact a bill. The new start is the current end, and we create a new end.
2016-10-21 06:26:12 +02:00
Log::debug(sprintf('Journal count is %d, so start becomes %s', $journalCount, $end->format('Y-m-d')));
2016-10-20 21:40:45 +02:00
$start = clone $end;
$end = app('navigation')->addPeriod($start, $bill->repeat_freq, $bill->skip);
2015-02-25 15:19:14 +01:00
}
2016-10-21 07:29:25 +02:00
Log::debug('nextExpectedMatch: Final start is ' . $start->format('Y-m-d'));
Log::debug('nextExpectedMatch: Matching end is ' . $end->format('Y-m-d'));
2016-10-20 21:40:45 +02:00
$cache->store($start);
2015-02-25 15:19:14 +01:00
2016-10-20 21:40:45 +02:00
return $start;
2015-02-25 15:19:14 +01:00
}
2019-03-02 14:12:09 +01:00
/**
* @param string $query
2020-08-06 20:08:04 +02:00
* @param int $limit
2019-03-02 14:12:09 +01:00
*
* @return Collection
*/
2020-07-21 06:22:29 +02:00
public function searchBill(string $query, int $limit): Collection
2019-03-02 14:12:09 +01:00
{
$query = sprintf('%%%s%%', $query);
2020-07-21 06:22:29 +02:00
return $this->user->bills()->where('name', 'LIKE', $query)->take($limit)->get();
2019-03-02 14:12:09 +01:00
}
2017-01-30 16:46:30 +01:00
/**
* @param User $user
*/
2018-07-22 18:50:27 +02:00
public function setUser(User $user): void
2017-01-30 16:46:30 +01:00
{
$this->user = $user;
}
2015-02-25 15:19:14 +01:00
/**
* @param array $data
*
2019-10-30 20:02:21 +01:00
* @return Bill
* @throws FireflyException
2015-02-25 15:19:14 +01:00
*/
2019-10-30 20:02:21 +01:00
public function store(array $data): Bill
2015-02-25 15:19:14 +01:00
{
/** @var BillFactory $factory */
$factory = app(BillFactory::class);
$factory->setUser($this->user);
2015-02-25 15:19:14 +01:00
2018-04-02 15:10:40 +02:00
return $factory->create($data);
2015-02-25 15:19:14 +01:00
}
/**
* @param Bill $bill
* @param array $data
*
* @return Bill
2015-02-25 15:19:14 +01:00
*/
2016-02-06 18:59:48 +01:00
public function update(Bill $bill, array $data): Bill
2015-02-25 15:19:14 +01:00
{
/** @var BillUpdateService $service */
$service = app(BillUpdateService::class);
2017-11-25 20:54:42 +01:00
return $service->update($bill, $data);
2015-02-25 15:19:14 +01:00
}
2019-09-23 17:11:01 +02:00
/**
* @param Bill $bill
*/
public function unlinkAll(Bill $bill): void
{
$this->user->transactionJournals()->where('bill_id', $bill->id)->update(['bill_id' => null]);
}
2020-06-30 20:33:08 +02:00
/**
* Correct order of piggies in case of issues.
*/
public function correctOrder(): void
{
$set = $this->user->bills()->orderBy('order', 'ASC')->get();
$current = 1;
foreach ($set as $bill) {
2020-11-11 19:14:05 +01:00
if ((int)$bill->order !== $current) {
2020-06-30 20:33:08 +02:00
$bill->order = $current;
$bill->save();
}
$current++;
}
}
2020-07-01 06:33:21 +02:00
/**
* @inheritDoc
*/
public function setObjectGroup(Bill $bill, string $objectGroupTitle): Bill
{
$objectGroup = $this->findOrCreateObjectGroup($objectGroupTitle);
if (null !== $objectGroup) {
$bill->objectGroups()->sync([$objectGroup->id]);
}
return $bill;
}
/**
* @inheritDoc
*/
public function removeObjectGroup(Bill $bill): Bill
{
$bill->objectGroups()->sync([]);
return $bill;
}
/**
* @inheritDoc
*/
public function setOrder(Bill $bill, int $order): void
{
$bill->order = $order;
$bill->save();
}
2020-07-11 15:13:15 +02:00
/**
* @inheritDoc
*/
public function destroyAll(): void
{
$this->user->bills()->delete();
}
2015-02-25 15:19:14 +01:00
}