Code cleanup

This commit is contained in:
James Cole 2021-03-21 09:15:40 +01:00
parent da1751940e
commit 206845575c
No known key found for this signature in database
GPG Key ID: B5669F9493CDE38D
317 changed files with 7418 additions and 7362 deletions

View File

@ -62,7 +62,7 @@ class CurrencyController extends Controller
*
* @return JsonResponse
*/
public function currenciesWithCode(AutocompleteRequest $request): JsonResponse
public function currencies(AutocompleteRequest $request): JsonResponse
{
$data = $request->getData();
$collection = $this->repository->searchCurrency($data['query'], $data['limit']);
@ -71,8 +71,8 @@ class CurrencyController extends Controller
/** @var TransactionCurrency $currency */
foreach ($collection as $currency) {
$result[] = [
'id' => (string) $currency->id,
'name' => sprintf('%s (%s)', $currency->name, $currency->code),
'id' => (string)$currency->id,
'name' => $currency->name,
'code' => $currency->code,
'symbol' => $currency->symbol,
'decimal_places' => $currency->decimal_places,
@ -87,7 +87,7 @@ class CurrencyController extends Controller
*
* @return JsonResponse
*/
public function currencies(AutocompleteRequest $request): JsonResponse
public function currenciesWithCode(AutocompleteRequest $request): JsonResponse
{
$data = $request->getData();
$collection = $this->repository->searchCurrency($data['query'], $data['limit']);
@ -96,8 +96,8 @@ class CurrencyController extends Controller
/** @var TransactionCurrency $currency */
foreach ($collection as $currency) {
$result[] = [
'id' => (string) $currency->id,
'name' => $currency->name,
'id' => (string)$currency->id,
'name' => sprintf('%s (%s)', $currency->name, $currency->code),
'code' => $currency->code,
'symbol' => $currency->symbol,
'decimal_places' => $currency->decimal_places,

View File

@ -37,10 +37,8 @@ use Illuminate\Http\JsonResponse;
*/
class PiggyBankController extends Controller
{
private PiggyBankRepositoryInterface $piggyRepository;
private AccountRepositoryInterface $accountRepository;
private PiggyBankRepositoryInterface $piggyRepository;
/**
* PiggyBankController constructor.

View File

@ -38,10 +38,8 @@ use Illuminate\Support\Collection;
*/
class TransactionController extends Controller
{
private JournalRepositoryInterface $repository;
private TransactionGroupRepositoryInterface $groupRepository;
private JournalRepositoryInterface $repository;
/**
* TransactionController constructor.
@ -102,7 +100,7 @@ class TransactionController extends Controller
$result = new Collection;
if (is_numeric($data['query'])) {
// search for group, not journal.
$firstResult = $this->groupRepository->find((int) $data['query']);
$firstResult = $this->groupRepository->find((int)$data['query']);
if (null !== $firstResult) {
// group may contain multiple journals, each a result:
foreach ($firstResult->transactionJournals as $journal) {

View File

@ -69,7 +69,7 @@ class TransactionTypeController extends Controller
foreach ($types as $type) {
// different key for consistency.
$array[] = [
'id' =>(string) $type->id,
'id' => (string)$type->id,
'name' => $type->type,
'type' => $type->type,
];

View File

@ -27,6 +27,7 @@ use FireflyIII\Api\V1\Requests\Data\Export\ExportRequest;
use FireflyIII\Support\Export\ExportDataGenerator;
use FireflyIII\User;
use Illuminate\Http\Response as LaravelResponse;
use League\Csv\CannotInsertRecord;
/**
* Class ExportController
@ -59,7 +60,7 @@ class ExportController extends Controller
* @param ExportRequest $request
*
* @return LaravelResponse
* @throws \League\Csv\CannotInsertRecord
* @throws CannotInsertRecord
*/
public function accounts(ExportRequest $request): LaravelResponse
{
@ -69,120 +70,11 @@ class ExportController extends Controller
}
/**
* @param ExportRequest $request
*
* @return LaravelResponse
* @throws \League\Csv\CannotInsertRecord
*/
public function bills(ExportRequest $request): LaravelResponse
{
$this->exporter->setExportBills(true);
return $this->returnExport('bills');
}
/**
* @param ExportRequest $request
*
* @return LaravelResponse
* @throws \League\Csv\CannotInsertRecord
*/
public function budgets(ExportRequest $request): LaravelResponse
{
$this->exporter->setExportBudgets(true);
return $this->returnExport('budgets');
}
/**
* @param ExportRequest $request
*
* @return LaravelResponse
* @throws \League\Csv\CannotInsertRecord
*/
public function categories(ExportRequest $request): LaravelResponse
{
$this->exporter->setExportCategories(true);
return $this->returnExport('categories');
}
/**
* @param ExportRequest $request
*
* @return LaravelResponse
* @throws \League\Csv\CannotInsertRecord
*/
public function piggyBanks(ExportRequest $request): LaravelResponse
{
$this->exporter->setExportPiggies(true);
return $this->returnExport('piggies');
}
/**
* @param ExportRequest $request
*
* @return LaravelResponse
* @throws \League\Csv\CannotInsertRecord
*/
public function recurring(ExportRequest $request): LaravelResponse
{
$this->exporter->setExportRecurring(true);
return $this->returnExport('recurrences');
}
/**
* @param ExportRequest $request
*
* @return LaravelResponse
* @throws \League\Csv\CannotInsertRecord
*/
public function rules(ExportRequest $request): LaravelResponse
{
$this->exporter->setExportRules(true);
return $this->returnExport('rules');
}
/**
* @param ExportRequest $request
*
* @return LaravelResponse
* @throws \League\Csv\CannotInsertRecord
*/
public function tags(ExportRequest $request): LaravelResponse
{
$this->exporter->setExportTags(true);
return $this->returnExport('tags');
}
/**
* @param ExportRequest $request
*
* @return LaravelResponse
* @throws \League\Csv\CannotInsertRecord
*/
public function transactions(ExportRequest $request): LaravelResponse
{
$params = $request->getAll();
$this->exporter->setStart($params['start']);
$this->exporter->setEnd($params['end']);
$this->exporter->setAccounts($params['accounts']);
$this->exporter->setExportTransactions(true);
return $this->returnExport('transactions');
}
/**
* @param string $key
*
* @return LaravelResponse
* @throws \League\Csv\CannotInsertRecord
* @throws CannotInsertRecord
*/
private function returnExport(string $key): LaravelResponse
{
@ -206,4 +98,112 @@ class ExportController extends Controller
return $response;
}
/**
* @param ExportRequest $request
*
* @return LaravelResponse
* @throws CannotInsertRecord
*/
public function bills(ExportRequest $request): LaravelResponse
{
$this->exporter->setExportBills(true);
return $this->returnExport('bills');
}
/**
* @param ExportRequest $request
*
* @return LaravelResponse
* @throws CannotInsertRecord
*/
public function budgets(ExportRequest $request): LaravelResponse
{
$this->exporter->setExportBudgets(true);
return $this->returnExport('budgets');
}
/**
* @param ExportRequest $request
*
* @return LaravelResponse
* @throws CannotInsertRecord
*/
public function categories(ExportRequest $request): LaravelResponse
{
$this->exporter->setExportCategories(true);
return $this->returnExport('categories');
}
/**
* @param ExportRequest $request
*
* @return LaravelResponse
* @throws CannotInsertRecord
*/
public function piggyBanks(ExportRequest $request): LaravelResponse
{
$this->exporter->setExportPiggies(true);
return $this->returnExport('piggies');
}
/**
* @param ExportRequest $request
*
* @return LaravelResponse
* @throws CannotInsertRecord
*/
public function recurring(ExportRequest $request): LaravelResponse
{
$this->exporter->setExportRecurring(true);
return $this->returnExport('recurrences');
}
/**
* @param ExportRequest $request
*
* @return LaravelResponse
* @throws CannotInsertRecord
*/
public function rules(ExportRequest $request): LaravelResponse
{
$this->exporter->setExportRules(true);
return $this->returnExport('rules');
}
/**
* @param ExportRequest $request
*
* @return LaravelResponse
* @throws CannotInsertRecord
*/
public function tags(ExportRequest $request): LaravelResponse
{
$this->exporter->setExportTags(true);
return $this->returnExport('tags');
}
/**
* @param ExportRequest $request
*
* @return LaravelResponse
* @throws CannotInsertRecord
*/
public function transactions(ExportRequest $request): LaravelResponse
{
$params = $request->getAll();
$this->exporter->setStart($params['start']);
$this->exporter->setEnd($params['end']);
$this->exporter->setAccounts($params['accounts']);
$this->exporter->setExportTransactions(true);
return $this->returnExport('transactions');
}
}

View File

@ -44,8 +44,8 @@ class AccountController extends Controller
use ApiSupport;
private CurrencyRepositoryInterface $currencyRepository;
private AccountRepositoryInterface $repository;
private OperationsRepositoryInterface $opsRepository;
private AccountRepositoryInterface $repository;
/**
* AccountController constructor.
@ -72,6 +72,32 @@ class AccountController extends Controller
);
}
/**
* @param GenericRequest $request
*
* @return JsonResponse
*/
public function asset(GenericRequest $request): JsonResponse
{
$start = $request->getStart();
$end = $request->getEnd();
$assetAccounts = $request->getAssetAccounts();
$expenses = $this->opsRepository->sumExpenses($start, $end, $assetAccounts);
$result = [];
/** @var array $expense */
foreach ($expenses as $expense) {
$result[] = [
'difference' => $expense['sum'],
'difference_float' => (float)$expense['sum'],
'currency_id' => (string)$expense['currency_id'],
'currency_code' => $expense['currency_code'],
];
}
return response()->json($result);
}
/**
* @param GenericRequest $request
*
@ -99,30 +125,4 @@ class AccountController extends Controller
return response()->json($result);
}
/**
* @param GenericRequest $request
*
* @return JsonResponse
*/
public function asset(GenericRequest $request): JsonResponse
{
$start = $request->getStart();
$end = $request->getEnd();
$assetAccounts = $request->getAssetAccounts();
$expenses = $this->opsRepository->sumExpenses($start, $end, $assetAccounts);
$result = [];
/** @var array $expense */
foreach ($expenses as $expense) {
$result[] = [
'difference' => $expense['sum'],
'difference_float' => (float)$expense['sum'],
'currency_id' => (string)$expense['currency_id'],
'currency_code' => $expense['currency_code'],
];
}
return response()->json($result);
}
}

View File

@ -36,9 +36,9 @@ use Illuminate\Support\Collection;
*/
class BudgetController extends Controller
{
private NoBudgetRepositoryInterface $noRepository;
private OperationsRepositoryInterface $opsRepository;
private BudgetRepositoryInterface $repository;
private NoBudgetRepositoryInterface $noRepository;
/**
* AccountController constructor.

View File

@ -18,9 +18,9 @@ use Illuminate\Support\Collection;
*/
class CategoryController extends Controller
{
private NoCategoryRepositoryInterface $noRepository;
private OperationsRepositoryInterface $opsRepository;
private CategoryRepositoryInterface $repository;
private NoCategoryRepositoryInterface $noRepository;
/**
* AccountController constructor.

View File

@ -53,6 +53,56 @@ class TagController extends Controller
);
}
/**
* Expenses for no tag filtered by account.
*
* @param GenericRequest $request
*
* @return JsonResponse
*/
public function noTag(GenericRequest $request): JsonResponse
{
$accounts = $request->getAssetAccounts();
$start = $request->getStart();
$end = $request->getEnd();
$response = [];
// collect all expenses in this period (regardless of type) by the given bills and accounts.
$collector = app(GroupCollectorInterface::class);
$collector->setTypes([TransactionType::WITHDRAWAL])->setRange($start, $end)->setSourceAccounts($accounts);
$collector->withoutTags();
$genericSet = $collector->getExtractedJournals();
foreach ($genericSet as $journal) {
$currencyId = (int)$journal['currency_id'];
$foreignCurrencyId = (int)$journal['foreign_currency_id'];
if (0 !== $currencyId) {
$response[$currencyId] = $response[$currencyId] ?? [
'difference' => '0',
'difference_float' => 0,
'currency_id' => (string)$currencyId,
'currency_code' => $journal['currency_code'],
];
$response[$currencyId]['difference'] = bcadd($response[$currencyId]['difference'], $journal['amount']);
$response[$currencyId]['difference_float'] = (float)$response[$currencyId]['difference'];
}
if (0 !== $foreignCurrencyId) {
$response[$foreignCurrencyId] = $response[$foreignCurrencyId] ?? [
'difference' => '0',
'difference_float' => 0,
'currency_id' => (string)$foreignCurrencyId,
'currency_code' => $journal['foreign_currency_code'],
];
$response[$foreignCurrencyId]['difference'] = bcadd($response[$foreignCurrencyId]['difference'], $journal['foreign_amount']);
$response[$foreignCurrencyId]['difference_float'] = (float)$response[$foreignCurrencyId]['difference'];
}
}
return response()->json(array_values($response));
}
/**
* Expenses per tag, possibly filtered by tag and account.
*
@ -120,54 +170,4 @@ class TagController extends Controller
return response()->json(array_values($response));
}
/**
* Expenses for no tag filtered by account.
*
* @param GenericRequest $request
*
* @return JsonResponse
*/
public function noTag(GenericRequest $request): JsonResponse
{
$accounts = $request->getAssetAccounts();
$start = $request->getStart();
$end = $request->getEnd();
$response = [];
// collect all expenses in this period (regardless of type) by the given bills and accounts.
$collector = app(GroupCollectorInterface::class);
$collector->setTypes([TransactionType::WITHDRAWAL])->setRange($start, $end)->setSourceAccounts($accounts);
$collector->withoutTags();
$genericSet = $collector->getExtractedJournals();
foreach ($genericSet as $journal) {
$currencyId = (int)$journal['currency_id'];
$foreignCurrencyId = (int)$journal['foreign_currency_id'];
if (0 !== $currencyId) {
$response[$currencyId] = $response[$currencyId] ?? [
'difference' => '0',
'difference_float' => 0,
'currency_id' => (string)$currencyId,
'currency_code' => $journal['currency_code'],
];
$response[$currencyId]['difference'] = bcadd($response[$currencyId]['difference'], $journal['amount']);
$response[$currencyId]['difference_float'] = (float)$response[$currencyId]['difference'];
}
if (0 !== $foreignCurrencyId) {
$response[$foreignCurrencyId] = $response[$foreignCurrencyId] ?? [
'difference' => '0',
'difference_float' => 0,
'currency_id' => (string)$foreignCurrencyId,
'currency_code' => $journal['foreign_currency_code'],
];
$response[$foreignCurrencyId]['difference'] = bcadd($response[$foreignCurrencyId]['difference'], $journal['foreign_amount']);
$response[$foreignCurrencyId]['difference_float'] = (float)$response[$foreignCurrencyId]['difference'];
}
}
return response()->json(array_values($response));
}
}

View File

@ -45,8 +45,8 @@ class AccountController extends Controller
use ApiSupport;
private CurrencyRepositoryInterface $currencyRepository;
private AccountRepositoryInterface $repository;
private OperationsRepositoryInterface $opsRepository;
private AccountRepositoryInterface $repository;
/**
* AccountController constructor.
@ -73,34 +73,6 @@ class AccountController extends Controller
);
}
/**
* // TOOD same as
* @param GenericRequest $request
*
* @return JsonResponse
*/
public function revenue(GenericRequest $request): JsonResponse
{
$start = $request->getStart();
$end = $request->getEnd();
$assetAccounts = $request->getAssetAccounts();
$revenueAccounts = $request->getRevenueAccounts();
$income = $this->opsRepository->sumIncome($start, $end, $assetAccounts, $revenueAccounts);
$result = [];
/** @var array $entry */
foreach ($income as $entry) {
$result[] = [
'difference' => $entry['sum'],
'difference_float' => (float)$entry['sum'],
'currency_id' => (string)$entry['currency_id'],
'currency_code' => $entry['currency_code'],
];
}
return response()->json($result);
}
/**
* TODO same code as Expense/AccountController.
*
@ -128,4 +100,33 @@ class AccountController extends Controller
return response()->json($result);
}
/**
* // TOOD same as
*
* @param GenericRequest $request
*
* @return JsonResponse
*/
public function revenue(GenericRequest $request): JsonResponse
{
$start = $request->getStart();
$end = $request->getEnd();
$assetAccounts = $request->getAssetAccounts();
$revenueAccounts = $request->getRevenueAccounts();
$income = $this->opsRepository->sumIncome($start, $end, $assetAccounts, $revenueAccounts);
$result = [];
/** @var array $entry */
foreach ($income as $entry) {
$result[] = [
'difference' => $entry['sum'],
'difference_float' => (float)$entry['sum'],
'currency_id' => (string)$entry['currency_id'],
'currency_code' => $entry['currency_code'],
];
}
return response()->json($result);
}
}

View File

@ -19,9 +19,9 @@ use Illuminate\Support\Collection;
*/
class CategoryController extends Controller
{
private NoCategoryRepositoryInterface $noRepository;
private OperationsRepositoryInterface $opsRepository;
private CategoryRepositoryInterface $repository;
private NoCategoryRepositoryInterface $noRepository;
/**
* AccountController constructor.

View File

@ -71,7 +71,9 @@ class PeriodController extends Controller
'currency_id' => (string)$foreignCurrencyId,
'currency_code' => $journal['foreign_currency_code'],
];
$response[$foreignCurrencyId]['difference'] = bcadd($response[$foreignCurrencyId]['difference'], app('steam')->positive($journal['foreign_amount']));
$response[$foreignCurrencyId]['difference'] = bcadd(
$response[$foreignCurrencyId]['difference'], app('steam')->positive($journal['foreign_amount'])
);
$response[$foreignCurrencyId]['difference_float'] = (float)$response[$foreignCurrencyId]['difference'];
}
}

View File

@ -53,6 +53,58 @@ class TagController extends Controller
);
}
/**
* Expenses for no tag filtered by account.
*
* @param GenericRequest $request
*
* @return JsonResponse
*/
public function noTag(GenericRequest $request): JsonResponse
{
$accounts = $request->getAssetAccounts();
$start = $request->getStart();
$end = $request->getEnd();
$response = [];
// collect all expenses in this period (regardless of type) by the given bills and accounts.
$collector = app(GroupCollectorInterface::class);
$collector->setTypes([TransactionType::DEPOSIT])->setRange($start, $end)->setDestinationAccounts($accounts);
$collector->withoutTags();
$genericSet = $collector->getExtractedJournals();
foreach ($genericSet as $journal) {
$currencyId = (int)$journal['currency_id'];
$foreignCurrencyId = (int)$journal['foreign_currency_id'];
if (0 !== $currencyId) {
$response[$currencyId] = $response[$currencyId] ?? [
'difference' => '0',
'difference_float' => 0,
'currency_id' => (string)$currencyId,
'currency_code' => $journal['currency_code'],
];
$response[$currencyId]['difference'] = bcadd($response[$currencyId]['difference'], app('steam')->positive($journal['amount']));
$response[$currencyId]['difference_float'] = (float)$response[$currencyId]['difference'];
}
if (0 !== $foreignCurrencyId) {
$response[$foreignCurrencyId] = $response[$foreignCurrencyId] ?? [
'difference' => '0',
'difference_float' => 0,
'currency_id' => (string)$foreignCurrencyId,
'currency_code' => $journal['foreign_currency_code'],
];
$response[$foreignCurrencyId]['difference'] = bcadd(
$response[$foreignCurrencyId]['difference'], app('steam')->positive($journal['foreign_amount'])
);
$response[$foreignCurrencyId]['difference_float'] = (float)$response[$foreignCurrencyId]['difference'];
}
}
return response()->json(array_values($response));
}
/**
* Expenses per tag, possibly filtered by tag and account.
*
@ -111,7 +163,9 @@ class TagController extends Controller
'currency_id' => (string)$foreignCurrencyId,
'currency_code' => $journal['foreign_currency_code'],
];
$response[$foreignKey]['difference'] = bcadd($response[$foreignKey]['difference'], app('steam')->positive($journal['foreign_amount']));
$response[$foreignKey]['difference'] = bcadd(
$response[$foreignKey]['difference'], app('steam')->positive($journal['foreign_amount'])
);
$response[$foreignKey]['difference_float'] = (float)$response[$foreignKey]['difference'];
}
}
@ -120,54 +174,4 @@ class TagController extends Controller
return response()->json(array_values($response));
}
/**
* Expenses for no tag filtered by account.
*
* @param GenericRequest $request
*
* @return JsonResponse
*/
public function noTag(GenericRequest $request): JsonResponse
{
$accounts = $request->getAssetAccounts();
$start = $request->getStart();
$end = $request->getEnd();
$response = [];
// collect all expenses in this period (regardless of type) by the given bills and accounts.
$collector = app(GroupCollectorInterface::class);
$collector->setTypes([TransactionType::DEPOSIT])->setRange($start, $end)->setDestinationAccounts($accounts);
$collector->withoutTags();
$genericSet = $collector->getExtractedJournals();
foreach ($genericSet as $journal) {
$currencyId = (int)$journal['currency_id'];
$foreignCurrencyId = (int)$journal['foreign_currency_id'];
if (0 !== $currencyId) {
$response[$currencyId] = $response[$currencyId] ?? [
'difference' => '0',
'difference_float' => 0,
'currency_id' => (string)$currencyId,
'currency_code' => $journal['currency_code'],
];
$response[$currencyId]['difference'] = bcadd($response[$currencyId]['difference'], app('steam')->positive($journal['amount']));
$response[$currencyId]['difference_float'] = (float)$response[$currencyId]['difference'];
}
if (0 !== $foreignCurrencyId) {
$response[$foreignCurrencyId] = $response[$foreignCurrencyId] ?? [
'difference' => '0',
'difference_float' => 0,
'currency_id' => (string)$foreignCurrencyId,
'currency_code' => $journal['foreign_currency_code'],
];
$response[$foreignCurrencyId]['difference'] = bcadd($response[$foreignCurrencyId]['difference'], app('steam')->positive($journal['foreign_amount']));
$response[$foreignCurrencyId]['difference_float'] = (float)$response[$foreignCurrencyId]['difference'];
}
}
return response()->json(array_values($response));
}
}

View File

@ -36,9 +36,9 @@ use Illuminate\Support\Collection;
*/
class CategoryController extends Controller
{
private NoCategoryRepositoryInterface $noRepository;
private OperationsRepositoryInterface $opsRepository;
private CategoryRepositoryInterface $repository;
private NoCategoryRepositoryInterface $noRepository;
/**
* AccountController constructor.

View File

@ -71,7 +71,9 @@ class PeriodController extends Controller
'currency_id' => (string)$foreignCurrencyId,
'currency_code' => $journal['foreign_currency_code'],
];
$response[$foreignCurrencyId]['difference'] = bcadd($response[$foreignCurrencyId]['difference'], app('steam')->positive($journal['foreign_amount']));
$response[$foreignCurrencyId]['difference'] = bcadd(
$response[$foreignCurrencyId]['difference'], app('steam')->positive($journal['foreign_amount'])
);
$response[$foreignCurrencyId]['difference_float'] = (float)$response[$foreignCurrencyId]['difference'];
}
}

View File

@ -54,6 +54,58 @@ class TagController extends Controller
);
}
/**
* Expenses for no tag filtered by account.
*
* @param GenericRequest $request
*
* @return JsonResponse
*/
public function noTag(GenericRequest $request): JsonResponse
{
$accounts = $request->getAssetAccounts();
$start = $request->getStart();
$end = $request->getEnd();
$response = [];
// collect all expenses in this period (regardless of type) by the given bills and accounts.
$collector = app(GroupCollectorInterface::class);
$collector->setTypes([TransactionType::TRANSFER])->setRange($start, $end)->setDestinationAccounts($accounts);
$collector->withoutTags();
$genericSet = $collector->getExtractedJournals();
foreach ($genericSet as $journal) {
$currencyId = (int)$journal['currency_id'];
$foreignCurrencyId = (int)$journal['foreign_currency_id'];
if (0 !== $currencyId) {
$response[$currencyId] = $response[$currencyId] ?? [
'difference' => '0',
'difference_float' => 0,
'currency_id' => (string)$currencyId,
'currency_code' => $journal['currency_code'],
];
$response[$currencyId]['difference'] = bcadd($response[$currencyId]['difference'], app('steam')->positive($journal['amount']));
$response[$currencyId]['difference_float'] = (float)$response[$currencyId]['difference'];
}
if (0 !== $foreignCurrencyId) {
$response[$foreignCurrencyId] = $response[$foreignCurrencyId] ?? [
'difference' => '0',
'difference_float' => 0,
'currency_id' => (string)$foreignCurrencyId,
'currency_code' => $journal['foreign_currency_code'],
];
$response[$foreignCurrencyId]['difference'] = bcadd(
$response[$foreignCurrencyId]['difference'], app('steam')->positive($journal['foreign_amount'])
);
$response[$foreignCurrencyId]['difference_float'] = (float)$response[$foreignCurrencyId]['difference'];
}
}
return response()->json(array_values($response));
}
/**
* Transfers per tag, possibly filtered by tag and account.
*
@ -112,7 +164,9 @@ class TagController extends Controller
'currency_id' => (string)$foreignCurrencyId,
'currency_code' => $journal['foreign_currency_code'],
];
$response[$foreignKey]['difference'] = bcadd($response[$foreignKey]['difference'], app('steam')->positive($journal['foreign_amount']));
$response[$foreignKey]['difference'] = bcadd(
$response[$foreignKey]['difference'], app('steam')->positive($journal['foreign_amount'])
);
$response[$foreignKey]['difference_float'] = (float)$response[$foreignKey]['difference'];
}
}
@ -120,54 +174,4 @@ class TagController extends Controller
return response()->json(array_values($response));
}
/**
* Expenses for no tag filtered by account.
*
* @param GenericRequest $request
*
* @return JsonResponse
*/
public function noTag(GenericRequest $request): JsonResponse
{
$accounts = $request->getAssetAccounts();
$start = $request->getStart();
$end = $request->getEnd();
$response = [];
// collect all expenses in this period (regardless of type) by the given bills and accounts.
$collector = app(GroupCollectorInterface::class);
$collector->setTypes([TransactionType::TRANSFER])->setRange($start, $end)->setDestinationAccounts($accounts);
$collector->withoutTags();
$genericSet = $collector->getExtractedJournals();
foreach ($genericSet as $journal) {
$currencyId = (int)$journal['currency_id'];
$foreignCurrencyId = (int)$journal['foreign_currency_id'];
if (0 !== $currencyId) {
$response[$currencyId] = $response[$currencyId] ?? [
'difference' => '0',
'difference_float' => 0,
'currency_id' => (string)$currencyId,
'currency_code' => $journal['currency_code'],
];
$response[$currencyId]['difference'] = bcadd($response[$currencyId]['difference'], app('steam')->positive($journal['amount']));
$response[$currencyId]['difference_float'] = (float)$response[$currencyId]['difference'];
}
if (0 !== $foreignCurrencyId) {
$response[$foreignCurrencyId] = $response[$foreignCurrencyId] ?? [
'difference' => '0',
'difference_float' => 0,
'currency_id' => (string)$foreignCurrencyId,
'currency_code' => $journal['foreign_currency_code'],
];
$response[$foreignCurrencyId]['difference'] = bcadd($response[$foreignCurrencyId]['difference'], app('steam')->positive($journal['foreign_amount']));
$response[$foreignCurrencyId]['difference_float'] = (float)$response[$foreignCurrencyId]['difference'];
}
}
return response()->json(array_values($response));
}
}

View File

@ -119,7 +119,7 @@ class ShowController extends Controller
$manager = $this->getManager();
// types to get, page size:
$pageSize = (int) app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data;
$pageSize = (int)app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data;
// get list of attachments. Count it and split it.
$collection = $this->repository->get();
@ -141,7 +141,6 @@ class ShowController extends Controller
}
/**
* Display the specified resource.
*

View File

@ -67,7 +67,6 @@ class StoreController extends Controller
}
/**
* Store a newly created resource in storage.
*

View File

@ -63,7 +63,6 @@ class UpdateController extends Controller
}
/**
* Update the specified resource in storage.
*

View File

@ -54,6 +54,7 @@ class DestroyController extends Controller
}
);
}
/**
* Remove the specified resource from storage.
*

View File

@ -71,7 +71,7 @@ class ShowController extends Controller
$manager = $this->getManager();
// types to get, page size:
$pageSize = (int) app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data;
$pageSize = (int)app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data;
$start = $this->parameters->get('start');
$end = $this->parameters->get('end');

View File

@ -26,7 +26,6 @@ use FireflyIII\Api\V1\Controllers\Controller;
use FireflyIII\Api\V1\Requests\Models\AvailableBudget\Request;
use FireflyIII\Factory\TransactionCurrencyFactory;
use FireflyIII\Models\AvailableBudget;
use FireflyIII\Models\TransactionCurrency;
use FireflyIII\Repositories\Budget\AvailableBudgetRepositoryInterface;
use FireflyIII\Transformers\AvailableBudgetTransformer;
use FireflyIII\User;
@ -73,7 +72,7 @@ class UpdateController extends Controller
$data = $request->getAll();
// find and validate currency ID
if(array_key_exists('currency_id', $data) || array_key_exists('currency_code', $data)) {
if (array_key_exists('currency_id', $data) || array_key_exists('currency_code', $data)) {
$factory = app(TransactionCurrencyFactory::class);
$currency = $factory->find($data['currency_id'] ?? null, $data['currency_code'] ?? null) ?? app('amount')->getDefaultCurrency();
$currency->enabled = true;

View File

@ -80,7 +80,7 @@ class ListController extends Controller
public function attachments(Bill $bill): JsonResponse
{
$manager = $this->getManager();
$pageSize = (int) app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data;
$pageSize = (int)app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data;
$collection = $this->repository->getAttachments($bill);
$count = $collection->count();
@ -101,7 +101,6 @@ class ListController extends Controller
}
/**
* List all of them.
*
@ -115,7 +114,7 @@ class ListController extends Controller
$manager = $this->getManager();
// types to get, page size:
$pageSize = (int) app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data;
$pageSize = (int)app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data;
// get list of budgets. Count it and split it.
$collection = $this->repository->getRulesForBill($bill);
@ -139,7 +138,6 @@ class ListController extends Controller
}
/**
* Show all transactions.
*
@ -152,7 +150,7 @@ class ListController extends Controller
*/
public function transactions(Request $request, Bill $bill): JsonResponse
{
$pageSize = (int) app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data;
$pageSize = (int)app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data;
$type = $request->get('type') ?? 'default';
$this->parameters->set('type', $type);

View File

@ -25,7 +25,6 @@ namespace FireflyIII\Api\V1\Controllers\Models\Bill;
use FireflyIII\Api\V1\Controllers\Controller;
use FireflyIII\Models\Bill;
use FireflyIII\Repositories\Bill\BillRepositoryInterface;
use FireflyIII\Support\Http\Api\TransactionFilter;
use FireflyIII\Transformers\BillTransformer;
use FireflyIII\User;
use Illuminate\Http\JsonResponse;
@ -74,7 +73,7 @@ class ShowController extends Controller
$this->repository->correctOrder();
$bills = $this->repository->getBills();
$manager = $this->getManager();
$pageSize = (int) app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data;
$pageSize = (int)app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data;
$count = $bills->count();
$bills = $bills->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize);
$paginator = new LengthAwarePaginator($bills, $count, $pageSize, $this->parameters->get('page'));

View File

@ -96,31 +96,6 @@ class ShowController extends Controller
return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE);
}
/**
* @param Request $request
* @param Budget $budget
* @param BudgetLimit $budgetLimit
*
* @return JsonResponse
*/
public function show(Request $request, Budget $budget, BudgetLimit $budgetLimit): JsonResponse
{
if ((int)$budget->id !== (int)$budgetLimit->budget_id) {
throw new FireflyException('20028: The budget limit does not belong to the budget.');
}
// continue!
$manager = $this->getManager();
/** @var BudgetLimitTransformer $transformer */
$transformer = app(BudgetLimitTransformer::class);
$transformer->setParameters($this->parameters);
$resource = new Item($budgetLimit, $transformer, 'budget_limits');
return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE);
}
/**
* Display a listing of the budget limits for this budget..
*
@ -150,4 +125,28 @@ class ShowController extends Controller
return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE);
}
/**
* @param Request $request
* @param Budget $budget
* @param BudgetLimit $budgetLimit
*
* @return JsonResponse
*/
public function show(Request $request, Budget $budget, BudgetLimit $budgetLimit): JsonResponse
{
if ((int)$budget->id !== (int)$budgetLimit->budget_id) {
throw new FireflyException('20028: The budget limit does not belong to the budget.');
}
// continue!
$manager = $this->getManager();
/** @var BudgetLimitTransformer $transformer */
$transformer = app(BudgetLimitTransformer::class);
$transformer->setParameters($this->parameters);
$resource = new Item($budgetLimit, $transformer, 'budget_limits');
return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE);
}
}

View File

@ -28,7 +28,6 @@ use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Models\Budget;
use FireflyIII\Models\BudgetLimit;
use FireflyIII\Repositories\Budget\BudgetLimitRepositoryInterface;
use FireflyIII\Repositories\Budget\BudgetRepositoryInterface;
use FireflyIII\Transformers\BudgetLimitTransformer;
use FireflyIII\User;
use Illuminate\Http\JsonResponse;

View File

@ -74,5 +74,4 @@ class DestroyController extends Controller
}
}

View File

@ -74,7 +74,7 @@ class ShowController extends Controller
$manager = $this->getManager();
// types to get, page size:
$pageSize = (int) app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data;
$pageSize = (int)app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data;
// get list of budgets. Count it and split it.
$collection = $this->repository->getCategories();

View File

@ -61,6 +61,37 @@ class ListController extends Controller
);
}
/**
* List all bills
*
* @param ObjectGroup $objectGroup
*
* @return JsonResponse
* @codeCoverageIgnore
*/
public function bills(ObjectGroup $objectGroup): JsonResponse
{
$manager = $this->getManager();
$pageSize = (int)app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data;
// get list of piggy banks. Count it and split it.
$collection = $this->repository->getBills($objectGroup);
$count = $collection->count();
$bills = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize);
// make paginator:
$paginator = new LengthAwarePaginator($bills, $count, $pageSize, $this->parameters->get('page'));
$paginator->setPath(route('api.v1.currencies.bills', [$objectGroup->id]) . $this->buildParams());
/** @var BillTransformer $transformer */
$transformer = app(BillTransformer::class);
$transformer->setParameters($this->parameters);
$resource = new FractalCollection($bills, $transformer, 'bills');
$resource->setPaginator(new IlluminatePaginatorAdapter($paginator));
return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE);
}
/**
* List all piggies under the object group.
@ -97,36 +128,4 @@ class ListController extends Controller
return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE);
}
/**
* List all bills
*
* @param ObjectGroup $objectGroup
*
* @return JsonResponse
* @codeCoverageIgnore
*/
public function bills(ObjectGroup $objectGroup): JsonResponse
{
$manager = $this->getManager();
$pageSize = (int)app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data;
// get list of piggy banks. Count it and split it.
$collection = $this->repository->getBills($objectGroup);
$count = $collection->count();
$bills = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize);
// make paginator:
$paginator = new LengthAwarePaginator($bills, $count, $pageSize, $this->parameters->get('page'));
$paginator->setPath(route('api.v1.currencies.bills', [$objectGroup->id]) . $this->buildParams());
/** @var BillTransformer $transformer */
$transformer = app(BillTransformer::class);
$transformer->setParameters($this->parameters);
$resource = new FractalCollection($bills, $transformer, 'bills');
$resource->setPaginator(new IlluminatePaginatorAdapter($paginator));
return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE);
}
}

View File

@ -67,7 +67,7 @@ class ListController extends Controller
public function attachments(PiggyBank $piggyBank): JsonResponse
{
$manager = $this->getManager();
$pageSize = (int) app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data;
$pageSize = (int)app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data;
$collection = $this->repository->getAttachments($piggyBank);
$count = $collection->count();
@ -98,7 +98,7 @@ class ListController extends Controller
public function piggyBankEvents(PiggyBank $piggyBank): JsonResponse
{
// types to get, page size:
$pageSize = (int) app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data;
$pageSize = (int)app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data;
$manager = $this->getManager();
$collection = $this->repository->getEvents($piggyBank);

View File

@ -68,7 +68,7 @@ class ShowController extends Controller
{
$manager = $this->getManager();
// types to get, page size:
$pageSize = (int) app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data;
$pageSize = (int)app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data;
// get list of budgets. Count it and split it.
$collection = $this->repository->getPiggyBanks();

View File

@ -61,7 +61,6 @@ class UpdateController extends Controller
}
/**
* Update single recurrence.
*

View File

@ -24,7 +24,6 @@ namespace FireflyIII\Api\V1\Controllers\Models\Rule;
use FireflyIII\Api\V1\Controllers\Controller;
use FireflyIII\Models\Rule;
use FireflyIII\Repositories\Account\AccountRepositoryInterface;
use FireflyIII\Repositories\Rule\RuleRepositoryInterface;
use FireflyIII\User;
use Illuminate\Http\JsonResponse;

View File

@ -24,7 +24,6 @@ namespace FireflyIII\Api\V1\Controllers\Models\Rule;
use FireflyIII\Api\V1\Controllers\Controller;
use FireflyIII\Models\Rule;
use FireflyIII\Repositories\Account\AccountRepositoryInterface;
use FireflyIII\Repositories\Rule\RuleRepositoryInterface;
use FireflyIII\Transformers\RuleTransformer;
use FireflyIII\User;
@ -74,7 +73,7 @@ class ShowController extends Controller
$manager = $this->getManager();
// types to get, page size:
$pageSize = (int) app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data;
$pageSize = (int)app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data;
// get list of budgets. Count it and split it.
$collection = $this->ruleRepository->getAll();
@ -97,7 +96,6 @@ class ShowController extends Controller
}
/**
* List single resource.
*

View File

@ -25,7 +25,6 @@ namespace FireflyIII\Api\V1\Controllers\Models\Tag;
use FireflyIII\Api\V1\Controllers\Controller;
use FireflyIII\Models\Tag;
use FireflyIII\Repositories\Tag\TagRepositoryInterface;
use FireflyIII\Support\Http\Api\TransactionFilter;
use FireflyIII\User;
use Illuminate\Http\JsonResponse;
@ -59,7 +58,6 @@ class DestroyController extends Controller
}
/**
* Delete the resource.
*

View File

@ -42,6 +42,7 @@ use League\Fractal\Resource\Collection as FractalCollection;
class ListController extends Controller
{
use TransactionFilter;
private TagRepositoryInterface $repository;
@ -67,7 +68,6 @@ class ListController extends Controller
}
/**
* @param Tag $tag
*
@ -77,7 +77,7 @@ class ListController extends Controller
public function attachments(Tag $tag): JsonResponse
{
$manager = $this->getManager();
$pageSize = (int) app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data;
$pageSize = (int)app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data;
$collection = $this->repository->getAttachments($tag);
$count = $collection->count();
@ -98,7 +98,6 @@ class ListController extends Controller
}
/**
* Show all transactions.
*
@ -110,7 +109,7 @@ class ListController extends Controller
*/
public function transactions(Request $request, Tag $tag): JsonResponse
{
$pageSize = (int) app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data;
$pageSize = (int)app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data;
$type = $request->get('type') ?? 'default';
$this->parameters->set('type', $type);

View File

@ -25,7 +25,6 @@ namespace FireflyIII\Api\V1\Controllers\Models\Tag;
use FireflyIII\Api\V1\Controllers\Controller;
use FireflyIII\Models\Tag;
use FireflyIII\Repositories\Tag\TagRepositoryInterface;
use FireflyIII\Support\Http\Api\TransactionFilter;
use FireflyIII\Transformers\TagTransformer;
use FireflyIII\User;
use Illuminate\Http\JsonResponse;
@ -73,7 +72,7 @@ class ShowController extends Controller
{
$manager = $this->getManager();
// types to get, page size:
$pageSize = (int) app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data;
$pageSize = (int)app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data;
// get list of budgets. Count it and split it.
$collection = $this->repository->get();
@ -95,7 +94,6 @@ class ShowController extends Controller
}
/**
* List single resource.
*

View File

@ -25,7 +25,6 @@ namespace FireflyIII\Api\V1\Controllers\Models\Tag;
use FireflyIII\Api\V1\Controllers\Controller;
use FireflyIII\Api\V1\Requests\Models\Tag\StoreRequest;
use FireflyIII\Repositories\Tag\TagRepositoryInterface;
use FireflyIII\Support\Http\Api\TransactionFilter;
use FireflyIII\Transformers\TagTransformer;
use FireflyIII\User;
use Illuminate\Http\JsonResponse;
@ -61,7 +60,6 @@ class StoreController extends Controller
}
/**
* Store new object.
*

View File

@ -26,7 +26,6 @@ use FireflyIII\Api\V1\Controllers\Controller;
use FireflyIII\Api\V1\Requests\Models\Tag\UpdateRequest;
use FireflyIII\Models\Tag;
use FireflyIII\Repositories\Tag\TagRepositoryInterface;
use FireflyIII\Support\Http\Api\TransactionFilter;
use FireflyIII\Transformers\TagTransformer;
use FireflyIII\User;
use Illuminate\Http\JsonResponse;
@ -62,7 +61,6 @@ class UpdateController extends Controller
}
/**
* Update a rule.
*

View File

@ -27,7 +27,6 @@ use FireflyIII\Events\DestroyedTransactionGroup;
use FireflyIII\Models\TransactionGroup;
use FireflyIII\Models\TransactionJournal;
use FireflyIII\Repositories\Journal\JournalRepositoryInterface;
use FireflyIII\Support\Http\Api\TransactionFilter;
use FireflyIII\User;
use Illuminate\Http\JsonResponse;

View File

@ -26,8 +26,6 @@ use FireflyIII\Api\V1\Controllers\Controller;
use FireflyIII\Models\TransactionGroup;
use FireflyIII\Models\TransactionJournal;
use FireflyIII\Repositories\Journal\JournalAPIRepositoryInterface;
use FireflyIII\Repositories\Journal\JournalRepositoryInterface;
use FireflyIII\Support\Http\Api\TransactionFilter;
use FireflyIII\Transformers\AttachmentTransformer;
use FireflyIII\Transformers\PiggyBankEventTransformer;
use FireflyIII\Transformers\TransactionLinkTransformer;
@ -76,7 +74,7 @@ class ListController extends Controller
public function attachments(TransactionGroup $transactionGroup): JsonResponse
{
$manager = $this->getManager();
$pageSize = (int) app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data;
$pageSize = (int)app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data;
$collection = new Collection;
foreach ($transactionGroup->transactionJournals as $transactionJournal) {
$collection = $this->journalAPIRepository->getAttachments($transactionJournal)->merge($collection);
@ -110,7 +108,7 @@ class ListController extends Controller
{
$manager = $this->getManager();
$collection = new Collection;
$pageSize = (int) app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data;
$pageSize = (int)app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data;
foreach ($transactionGroup->transactionJournals as $transactionJournal) {
$collection = $this->journalAPIRepository->getPiggyBankEvents($transactionJournal)->merge($collection);
}
@ -130,12 +128,11 @@ class ListController extends Controller
$resource->setPaginator(new IlluminatePaginatorAdapter($paginator));
// /** @var PiggyBankEventTransformer $transformer */
// $transformer = app(PiggyBankEventTransformer::class);
// $transformer->setParameters($this->parameters);
//
// $resource = new FractalCollection($events, $transformer, 'piggy_bank_events');
// /** @var PiggyBankEventTransformer $transformer */
// $transformer = app(PiggyBankEventTransformer::class);
// $transformer->setParameters($this->parameters);
//
// $resource = new FractalCollection($events, $transformer, 'piggy_bank_events');
return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE);
}
@ -151,7 +148,7 @@ class ListController extends Controller
{
$manager = $this->getManager();
$collection = $this->journalAPIRepository->getJournalLinks($transactionJournal);
$pageSize = (int) app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data;
$pageSize = (int)app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data;
$count = $collection->count();
$journalLinks = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize);

View File

@ -94,6 +94,18 @@ class ShowController extends Controller
return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE);
}
/**
* Show a single transaction, by transaction journal.
*
* @param TransactionJournal $transactionJournal
*
* @return JsonResponse
* @codeCoverageIgnore
*/
public function showJournal(TransactionJournal $transactionJournal): JsonResponse
{
return $this->show($transactionJournal->transactionGroup);
}
/**
* Show a single transaction.
@ -130,17 +142,4 @@ class ShowController extends Controller
return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE);
}
/**
* Show a single transaction, by transaction journal.
*
* @param TransactionJournal $transactionJournal
*
* @return JsonResponse
* @codeCoverageIgnore
*/
public function showJournal(TransactionJournal $transactionJournal): JsonResponse
{
return $this->show($transactionJournal->transactionGroup);
}
}

View File

@ -32,8 +32,8 @@ use FireflyIII\Transformers\TransactionGroupTransformer;
use FireflyIII\User;
use Illuminate\Http\JsonResponse;
use League\Fractal\Resource\Item;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Log;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
/**
* Class UpdateController

View File

@ -89,7 +89,7 @@ class ListController extends Controller
// types to get, page size:
$types = $this->mapAccountTypes($this->parameters->get('type'));
$pageSize = (int) app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data;
$pageSize = (int)app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data;
// get list of accounts. Count it and split it.
/** @var AccountRepositoryInterface $accountRepository */
@ -99,7 +99,7 @@ class ListController extends Controller
// filter list on currency preference:
$collection = $unfiltered->filter(
static function (Account $account) use ($currency, $accountRepository) {
$currencyId = (int) $accountRepository->getMetaValue($account, 'currency_id');
$currencyId = (int)$accountRepository->getMetaValue($account, 'currency_id');
return $currencyId === $currency->id;
}
@ -135,7 +135,7 @@ class ListController extends Controller
{
$manager = $this->getManager();
// types to get, page size:
$pageSize = (int) app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data;
$pageSize = (int)app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data;
// get list of available budgets. Count it and split it.
/** @var AvailableBudgetRepositoryInterface $abRepository */
@ -174,7 +174,7 @@ class ListController extends Controller
/** @var BillRepositoryInterface $billRepos */
$billRepos = app(BillRepositoryInterface::class);
$pageSize = (int) app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data;
$pageSize = (int)app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data;
$unfiltered = $billRepos->getBills();
// filter and paginate list:
@ -214,7 +214,7 @@ class ListController extends Controller
$blRepository = app(BudgetLimitRepositoryInterface::class);
$manager = $this->getManager();
$pageSize = (int) app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data;
$pageSize = (int)app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data;
$collection = $blRepository->getAllBudgetLimitsByCurrency($currency, $this->parameters->get('start'), $this->parameters->get('end'));
$count = $collection->count();
$budgetLimits = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize);
@ -243,7 +243,7 @@ class ListController extends Controller
{
$manager = $this->getManager();
// types to get, page size:
$pageSize = (int) app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data;
$pageSize = (int)app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data;
// get list of budgets. Count it and split it.
/** @var RecurringRepositoryInterface $recurringRepos */
@ -294,7 +294,7 @@ class ListController extends Controller
public function rules(TransactionCurrency $currency): JsonResponse
{
$manager = $this->getManager();
$pageSize = (int) app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data;
$pageSize = (int)app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data;
// get list of budgets. Count it and split it.
/** @var RuleRepositoryInterface $ruleRepos */
@ -344,7 +344,7 @@ class ListController extends Controller
*/
public function transactions(Request $request, TransactionCurrency $currency): JsonResponse
{
$pageSize = (int) app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data;
$pageSize = (int)app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data;
$type = $request->get('type') ?? 'default';
$this->parameters->set('type', $type);

View File

@ -50,8 +50,6 @@ class StoreController extends Controller
}
/**
* Store new currency.
*

View File

@ -18,6 +18,7 @@ use League\Fractal\Resource\Item;
class StoreController extends Controller
{
use TransactionFilter;
private JournalRepositoryInterface $journalRepository;
private LinkTypeRepositoryInterface $repository;

View File

@ -49,7 +49,6 @@ class ListController extends Controller
}
/**
* Delete the resource.
*

View File

@ -81,7 +81,6 @@ class ShowController extends Controller
}
/**
* List single resource.
*

View File

@ -47,7 +47,6 @@ class StoreController extends Controller
}
/**
* Store new object.
*

View File

@ -48,7 +48,6 @@ class UpdateController extends Controller
}
/**
* Update object.
*

View File

@ -146,7 +146,7 @@ class BasicController extends Controller
$set = $collector->getExtractedJournals();
/** @var array $transactionJournal */
foreach ($set as $transactionJournal) {
$currencyId = (int) $transactionJournal['currency_id'];
$currencyId = (int)$transactionJournal['currency_id'];
$incomes[$currencyId] = $incomes[$currencyId] ?? '0';
$incomes[$currencyId] = bcadd($incomes[$currencyId], bcmul($transactionJournal['amount'], '-1'));
$sums[$currencyId] = $sums[$currencyId] ?? '0';
@ -168,7 +168,7 @@ class BasicController extends Controller
/** @var array $transactionJournal */
foreach ($set as $transactionJournal) {
$currencyId = (int) $transactionJournal['currency_id'];
$currencyId = (int)$transactionJournal['currency_id'];
$expenses[$currencyId] = $expenses[$currencyId] ?? '0';
$expenses[$currencyId] = bcadd($expenses[$currencyId], $transactionJournal['amount']);
$sums[$currencyId] = $sums[$currencyId] ?? '0';
@ -186,7 +186,7 @@ class BasicController extends Controller
$return[] = [
'key' => sprintf('balance-in-%s', $currency->code),
'title' => trans('firefly.box_balance_in_currency', ['currency' => $currency->symbol]),
'monetary_value' => round((float) $sums[$currencyId] ?? 0, $currency->decimal_places),
'monetary_value' => round((float)$sums[$currencyId] ?? 0, $currency->decimal_places),
'currency_id' => $currency->id,
'currency_code' => $currency->code,
'currency_symbol' => $currency->symbol,
@ -199,7 +199,7 @@ class BasicController extends Controller
$return[] = [
'key' => sprintf('spent-in-%s', $currency->code),
'title' => trans('firefly.box_spent_in_currency', ['currency' => $currency->symbol]),
'monetary_value' => round((float) ($expenses[$currencyId] ?? 0), $currency->decimal_places),
'monetary_value' => round((float)($expenses[$currencyId] ?? 0), $currency->decimal_places),
'currency_id' => $currency->id,
'currency_code' => $currency->code,
'currency_symbol' => $currency->symbol,
@ -211,7 +211,7 @@ class BasicController extends Controller
$return[] = [
'key' => sprintf('earned-in-%s', $currency->code),
'title' => trans('firefly.box_earned_in_currency', ['currency' => $currency->symbol]),
'monetary_value' => round((float) ($incomes[$currencyId] ?? 0), $currency->decimal_places),
'monetary_value' => round((float)($incomes[$currencyId] ?? 0), $currency->decimal_places),
'currency_id' => $currency->id,
'currency_code' => $currency->code,
'currency_symbol' => $currency->symbol,
@ -242,14 +242,14 @@ class BasicController extends Controller
$return = [];
foreach ($paidAmount as $currencyId => $amount) {
$amount = bcmul($amount, '-1');
$currency = $this->currencyRepos->findNull((int) $currencyId);
$currency = $this->currencyRepos->findNull((int)$currencyId);
if (null === $currency) {
continue;
}
$return[] = [
'key' => sprintf('bills-paid-in-%s', $currency->code),
'title' => trans('firefly.box_bill_paid_in_currency', ['currency' => $currency->symbol]),
'monetary_value' => round((float) $amount, $currency->decimal_places),
'monetary_value' => round((float)$amount, $currency->decimal_places),
'currency_id' => $currency->id,
'currency_code' => $currency->code,
'currency_symbol' => $currency->symbol,
@ -262,14 +262,14 @@ class BasicController extends Controller
foreach ($unpaidAmount as $currencyId => $amount) {
$amount = bcmul($amount, '-1');
$currency = $this->currencyRepos->findNull((int) $currencyId);
$currency = $this->currencyRepos->findNull((int)$currencyId);
if (null === $currency) {
continue;
}
$return[] = [
'key' => sprintf('bills-unpaid-in-%s', $currency->code),
'title' => trans('firefly.box_bill_unpaid_in_currency', ['currency' => $currency->symbol]),
'monetary_value' => round((float) $amount, $currency->decimal_places),
'monetary_value' => round((float)$amount, $currency->decimal_places),
'currency_id' => $currency->id,
'currency_code' => $currency->code,
'currency_symbol' => $currency->symbol,
@ -307,20 +307,20 @@ class BasicController extends Controller
$days = $today->diffInDays($end) + 1;
$perDay = '0';
if (0 !== $days && bccomp($leftToSpend, '0') > -1) {
$perDay = bcdiv($leftToSpend, (string) $days);
$perDay = bcdiv($leftToSpend, (string)$days);
}
$return[] = [
'key' => sprintf('left-to-spend-in-%s', $row['currency_code']),
'title' => trans('firefly.box_left_to_spend_in_currency', ['currency' => $row['currency_symbol']]),
'monetary_value' => round((float) $leftToSpend, $row['currency_decimal_places']),
'monetary_value' => round((float)$leftToSpend, $row['currency_decimal_places']),
'currency_id' => $row['currency_id'],
'currency_code' => $row['currency_code'],
'currency_symbol' => $row['currency_symbol'],
'currency_decimal_places' => $row['currency_decimal_places'],
'value_parsed' => app('amount')->formatFlat($row['currency_symbol'], $row['currency_decimal_places'], $leftToSpend, false),
'local_icon' => 'money',
'sub_title' => (string) trans(
'sub_title' => (string)trans(
'firefly.box_spend_per_day',
['amount' => app('amount')->formatFlat(
$row['currency_symbol'],
@ -373,7 +373,7 @@ class BasicController extends Controller
foreach ($netWorthSet as $data) {
/** @var TransactionCurrency $currency */
$currency = $data['currency'];
$amount = round((float) $data['balance'], $currency->decimal_places);
$amount = round((float)$data['balance'], $currency->decimal_places);
if (0.0 === $amount) {
continue;
}

View File

@ -85,6 +85,41 @@ class ConfigurationController extends Controller
return response()->json($return);
}
/**
* Get all config values.
*
* @return array
* @throws FireflyException
*/
private function getDynamicConfiguration(): array
{
$isDemoSite = app('fireflyconfig')->get('is_demo_site');
$updateCheck = app('fireflyconfig')->get('permission_update_check');
$lastCheck = app('fireflyconfig')->get('last_update_check');
$singleUser = app('fireflyconfig')->get('single_user_mode');
return [
'is_demo_site' => null === $isDemoSite ? null : $isDemoSite->data,
'permission_update_check' => null === $updateCheck ? null : (int)$updateCheck->data,
'last_update_check' => null === $lastCheck ? null : (int)$lastCheck->data,
'single_user_mode' => null === $singleUser ? null : $singleUser->data,
];
}
/**
* @return array
*/
private function getStaticConfiguration(): array
{
$list = EitherConfigKey::$static;
$return = [];
foreach ($list as $key) {
$return[$key] = config($key);
}
return $return;
}
/**
* @param string $configKey
*
@ -128,7 +163,7 @@ class ConfigurationController extends Controller
throw new FireflyException('200005: You need the "owner" role to do this.'); // @codeCoverageIgnore
}
$data = $request->getAll();
$shortName = str_replace('configuration.','', $name);
$shortName = str_replace('configuration.', '', $name);
app('fireflyconfig')->set($shortName, $data['value']);
@ -144,41 +179,4 @@ class ConfigurationController extends Controller
return response()->json(['data' => $data])->header('Content-Type', self::CONTENT_TYPE);
}
/**
* @return array
*/
private function getStaticConfiguration(): array
{
$list = EitherConfigKey::$static;
$return = [];
foreach ($list as $key) {
$return[$key] = config($key);
}
return $return;
}
/**
* Get all config values.
*
* @return array
* @throws FireflyException
*/
private function getDynamicConfiguration(): array
{
$isDemoSite = app('fireflyconfig')->get('is_demo_site');
$updateCheck = app('fireflyconfig')->get('permission_update_check');
$lastCheck = app('fireflyconfig')->get('last_update_check');
$singleUser = app('fireflyconfig')->get('single_user_mode');
return [
'is_demo_site' => null === $isDemoSite ? null : $isDemoSite->data,
'permission_update_check' => null === $updateCheck ? null : (int)$updateCheck->data,
'last_update_check' => null === $lastCheck ? null : (int)$lastCheck->data,
'single_user_mode' => null === $singleUser ? null : $singleUser->data,
];
}
}

View File

@ -77,7 +77,7 @@ class UserController extends Controller
{
/** @var User $admin */
$admin = auth()->user();
if($admin->id === $user->id) {
if ($admin->id === $user->id) {
return response()->json([], 500);
}
@ -98,7 +98,7 @@ class UserController extends Controller
public function index(): JsonResponse
{
// user preferences
$pageSize = (int) app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data;
$pageSize = (int)app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data;
$manager = $this->getManager();
// build collection

View File

@ -73,6 +73,26 @@ class PreferencesController extends Controller
}
/**
* Return a single preference by name.
*
* @param Preference $preference
*
* @return JsonResponse
* @codeCoverageIgnore
*/
public function show(Preference $preference): JsonResponse
{
$manager = $this->getManager();
/** @var PreferenceTransformer $transformer */
$transformer = app(PreferenceTransformer::class);
$transformer->setParameters($this->parameters);
$resource = new Item($preference, $transformer, 'preferences');
return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE);
}
/**
* @param PreferenceStoreRequest $request
*
@ -113,24 +133,4 @@ class PreferencesController extends Controller
return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE);
}
/**
* Return a single preference by name.
*
* @param Preference $preference
*
* @return JsonResponse
* @codeCoverageIgnore
*/
public function show(Preference $preference): JsonResponse
{
$manager = $this->getManager();
/** @var PreferenceTransformer $transformer */
$transformer = app(PreferenceTransformer::class);
$transformer->setParameters($this->parameters);
$resource = new Item($preference, $transformer, 'preferences');
return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE);
}
}

View File

@ -29,7 +29,6 @@ use FireflyIII\Models\WebhookAttempt;
use FireflyIII\Models\WebhookMessage;
use FireflyIII\Repositories\Webhook\WebhookRepositoryInterface;
use FireflyIII\Transformers\WebhookAttemptTransformer;
use FireflyIII\Transformers\WebhookMessageTransformer;
use FireflyIII\User;
use Illuminate\Http\JsonResponse;
use Illuminate\Pagination\LengthAwarePaginator;
@ -42,8 +41,8 @@ use League\Fractal\Resource\Item;
*/
class AttemptController extends Controller
{
private WebhookRepositoryInterface $repository;
public const RESOURCE_KEY = 'webhook_attempts';
private WebhookRepositoryInterface $repository;
/**
* @codeCoverageIgnore
@ -108,10 +107,10 @@ class AttemptController extends Controller
*/
public function show(Webhook $webhook, WebhookMessage $message, WebhookAttempt $attempt): JsonResponse
{
if($message->webhook_id !== $webhook->id) {
if ($message->webhook_id !== $webhook->id) {
throw new FireflyException('Webhook and webhook message are no match');
}
if($attempt->webhook_message_id !== $message->id) {
if ($attempt->webhook_message_id !== $message->id) {
throw new FireflyException('Webhook message and webhook attempt are no match');
}

View File

@ -103,12 +103,17 @@ class DestroyController extends Controller
* @return JsonResponse
* @codeCoverageIgnore
*/
public function destroyMessage(Webhook $webhook, WebhookMessage $message): JsonResponse
public function destroyAttempt(Webhook $webhook, WebhookMessage $message, WebhookAttempt $attempt): JsonResponse
{
if ($message->webhook_id !== $webhook->id) {
throw new FireflyException('Webhook and webhook message are no match');
}
$this->repository->destroyMessage($message);
if ($attempt->webhook_message_id !== $message->id) {
throw new FireflyException('Webhook message and webhook attempt are no match');
}
$this->repository->destroyAttempt($attempt);
return response()->json([], 204);
}
@ -121,21 +126,15 @@ class DestroyController extends Controller
* @return JsonResponse
* @codeCoverageIgnore
*/
public function destroyAttempt(Webhook $webhook, WebhookMessage $message, WebhookAttempt $attempt): JsonResponse
public function destroyMessage(Webhook $webhook, WebhookMessage $message): JsonResponse
{
if ($message->webhook_id !== $webhook->id) {
throw new FireflyException('Webhook and webhook message are no match');
}
if($attempt->webhook_message_id !== $message->id) {
throw new FireflyException('Webhook message and webhook attempt are no match');
}
$this->repository->destroyAttempt($attempt);
$this->repository->destroyMessage($message);
return response()->json([], 204);
}
}

View File

@ -99,7 +99,7 @@ class MessageController extends Controller
*/
public function show(Webhook $webhook, WebhookMessage $message): JsonResponse
{
if($message->webhook_id !== $webhook->id) {
if ($message->webhook_id !== $webhook->id) {
throw new FireflyException('Webhook and webhook message are no match');
}

View File

@ -37,21 +37,6 @@ class ExportRequest extends FormRequest
{
use ChecksLogin, ConvertsDataTypes;
/**
* The rules that the incoming request must be matched against.
*
* @return array
*/
public function rules(): array
{
return [
'type' => 'in:csv',
'accounts' => 'min:1',
'start' => 'date|before:end',
'end' => 'date|after:start',
];
}
public function getAll(): array
{
$result = [
@ -77,4 +62,19 @@ class ExportRequest extends FormRequest
return $result;
}
/**
* The rules that the incoming request must be matched against.
*
* @return array
*/
public function rules(): array
{
return [
'type' => 'in:csv',
'accounts' => 'min:1',
'start' => 'date|before:end',
'end' => 'date|after:start',
];
}
}

View File

@ -25,31 +25,110 @@ class GenericRequest extends FormRequest
use ConvertsDataTypes, ChecksLogin;
private Collection $accounts;
private Collection $bills;
private Collection $budgets;
private Collection $categories;
private Collection $bills;
private Collection $tags;
/**
* @return Carbon
* Get all data from the request.
*
* @return array
*/
public function getStart(): Carbon
public function getAll(): array
{
$date = $this->date('start');
$date->startOfDay();
return $date;
return [
'start' => $this->date('start'),
'end' => $this->date('end'),
];
}
/**
* @return Carbon
* @return Collection
*/
public function getEnd(): Carbon
public function getAssetAccounts(): Collection
{
$date = $this->date('end');
$date->endOfDay();
$this->parseAccounts();
$return = new Collection;
/** @var Account $account */
foreach ($this->accounts as $account) {
$type = $account->accountType->type;
if (in_array($type, [AccountType::ASSET, AccountType::LOAN, AccountType::DEBT, AccountType::MORTGAGE])) {
$return->push($account);
}
}
return $date;
return $return;
}
/**
*
*/
private function parseAccounts(): void
{
if (null === $this->accounts) {
$this->accounts = new Collection;
}
if (0 !== $this->accounts->count()) {
return;
}
$repository = app(AccountRepositoryInterface::class);
$repository->setUser(auth()->user());
$array = $this->get('accounts');
if (is_array($array)) {
foreach ($array as $accountId) {
$accountId = (int)$accountId;
$account = $repository->findNull($accountId);
if (null !== $account) {
$this->accounts->push($account);
}
}
}
}
/**
* @return Collection
*/
public function getBills(): Collection
{
$this->parseBills();
return $this->bills;
}
/**
*
*/
private function parseBills(): void
{
if (null === $this->bills) {
$this->bills = new Collection;
}
if (0 !== $this->bills->count()) {
return;
}
$repository = app(BillRepositoryInterface::class);
$repository->setUser(auth()->user());
$array = $this->get('bills');
if (is_array($array)) {
foreach ($array as $billId) {
$billId = (int)$billId;
$bill = $repository->find($billId);
if (null !== $billId) {
$this->bills->push($bill);
}
}
}
}
/**
* @return Collection
*/
public function getBudgets(): Collection
{
$this->parseBudgets();
return $this->budgets;
}
/**
@ -77,16 +156,6 @@ class GenericRequest extends FormRequest
}
}
/**
* @return Collection
*/
public function getBudgets(): Collection
{
$this->parseBudgets();
return $this->budgets;
}
/**
* @return Collection
*/
@ -98,42 +167,39 @@ class GenericRequest extends FormRequest
}
/**
* @return Collection
*
*/
public function getBills(): Collection
private function parseCategories(): void
{
$this->parseBills();
return $this->bills;
if (null === $this->categories) {
$this->categories = new Collection;
}
if (0 !== $this->categories->count()) {
return;
}
$repository = app(CategoryRepositoryInterface::class);
$repository->setUser(auth()->user());
$array = $this->get('categories');
if (is_array($array)) {
foreach ($array as $categoryId) {
$categoryId = (int)$categoryId;
$category = $repository->findNull($categoryId);
if (null !== $categoryId) {
$this->categories->push($category);
}
}
}
}
/**
* @return Collection
* @return Carbon
*/
public function getTags(): Collection
public function getEnd(): Carbon
{
$this->parseTags();
$date = $this->date('end');
$date->endOfDay();
return $this->tags;
}
/**
* @return Collection
*/
public function getAssetAccounts(): Collection
{
$this->parseAccounts();
$return = new Collection;
/** @var Account $account */
foreach ($this->accounts as $account) {
$type = $account->accountType->type;
if (in_array($type, [AccountType::ASSET, AccountType::LOAN, AccountType::DEBT, AccountType::MORTGAGE])) {
$return->push($account);
}
}
return $return;
return $date;
}
/**
@ -173,111 +239,24 @@ class GenericRequest extends FormRequest
}
/**
* Get all data from the request.
*
* @return array
* @return Carbon
*/
public function getAll(): array
public function getStart(): Carbon
{
return [
'start' => $this->date('start'),
'end' => $this->date('end'),
];
$date = $this->date('start');
$date->startOfDay();
return $date;
}
/**
* The rules that the incoming request must be matched against.
*
* @return array
* @return Collection
*/
public function rules(): array
public function getTags(): Collection
{
// this is cheating but it works:
$this->accounts = new Collection;
$this->budgets = new Collection;
$this->categories = new Collection;
$this->bills = new Collection;
$this->tags = new Collection;
$this->parseTags();
return [
'start' => 'required|date',
'end' => 'required|date|after:start',
];
}
/**
*
*/
private function parseAccounts(): void
{
if (null === $this->accounts) {
$this->accounts = new Collection;
}
if (0 !== $this->accounts->count()) {
return;
}
$repository = app(AccountRepositoryInterface::class);
$repository->setUser(auth()->user());
$array = $this->get('accounts');
if (is_array($array)) {
foreach ($array as $accountId) {
$accountId = (int)$accountId;
$account = $repository->findNull($accountId);
if (null !== $account) {
$this->accounts->push($account);
}
}
}
}
/**
*
*/
private function parseBills(): void
{
if (null === $this->bills) {
$this->bills = new Collection;
}
if (0 !== $this->bills->count()) {
return;
}
$repository = app(BillRepositoryInterface::class);
$repository->setUser(auth()->user());
$array = $this->get('bills');
if (is_array($array)) {
foreach ($array as $billId) {
$billId = (int)$billId;
$bill = $repository->find($billId);
if (null !== $billId) {
$this->bills->push($bill);
}
}
}
}
/**
*
*/
private function parseCategories(): void
{
if (null === $this->categories) {
$this->categories = new Collection;
}
if (0 !== $this->categories->count()) {
return;
}
$repository = app(CategoryRepositoryInterface::class);
$repository->setUser(auth()->user());
$array = $this->get('categories');
if (is_array($array)) {
foreach ($array as $categoryId) {
$categoryId = (int)$categoryId;
$category = $repository->findNull($categoryId);
if (null !== $categoryId) {
$this->categories->push($category);
}
}
}
return $this->tags;
}
/**
@ -304,4 +283,24 @@ class GenericRequest extends FormRequest
}
}
}
/**
* The rules that the incoming request must be matched against.
*
* @return array
*/
public function rules(): array
{
// this is cheating but it works:
$this->accounts = new Collection;
$this->budgets = new Collection;
$this->categories = new Collection;
$this->bills = new Collection;
$this->tags = new Collection;
return [
'start' => 'required|date',
'end' => 'required|date|after:start',
];
}
}

View File

@ -45,8 +45,9 @@ class UpdateRequest extends FormRequest
{
$fields = [
'name' => ['name', 'string'],
'notes' => ['notes', 'nlString']
'notes' => ['notes', 'nlString'],
];
return $this->getAllData($fields);
}

View File

@ -44,8 +44,9 @@ class UpdateRequest extends FormRequest
{
$fields = [
'title' => ['title', 'string'],
'order' =>['order', 'integer']
'order' => ['order', 'integer'],
];
return $this->getAllData($fields);
}

View File

@ -76,29 +76,6 @@ class UpdateRequest extends FormRequest
return $return;
}
/**
* Returns the transaction data as it is found in the submitted data. It's a complex method according to code
* standards but it just has a lot of ??-statements because of the fields that may or may not exist.
*
* @return array|null
*/
private function getTransactionData(): ?array
{
$return = [];
// transaction data:
/** @var array $transactions */
$transactions = $this->get('transactions');
if (null === $transactions) {
return null;
}
/** @var array $transaction */
foreach ($transactions as $transaction) {
$return[] = $this->getSingleTransactionData($transaction);
}
return $return;
}
/**
* Returns the repetition data as it is found in the submitted data.
*
@ -140,6 +117,29 @@ class UpdateRequest extends FormRequest
return $return;
}
/**
* Returns the transaction data as it is found in the submitted data. It's a complex method according to code
* standards but it just has a lot of ??-statements because of the fields that may or may not exist.
*
* @return array|null
*/
private function getTransactionData(): ?array
{
$return = [];
// transaction data:
/** @var array $transactions */
$transactions = $this->get('transactions');
if (null === $transactions) {
return null;
}
/** @var array $transaction */
foreach ($transactions as $transaction) {
$return[] = $this->getSingleTransactionData($transaction);
}
return $return;
}
/**
* The rules that the incoming request must be matched against.
*

View File

@ -38,7 +38,6 @@ class TriggerRequest extends FormRequest
use ConvertsDataTypes, ChecksLogin;
/**
* @return array
*/

View File

@ -59,10 +59,10 @@ class UpdateRequest extends FormRequest
$return = $this->getAllData($fields);
$triggers = $this->getRuleTriggers();
$actions = $this->getRuleActions();
if(null !== $triggers) {
if (null !== $triggers) {
$return['triggers'] = $triggers;
}
if(null !== $actions) {
if (null !== $actions) {
$return['actions'] = $actions;
}
@ -82,7 +82,7 @@ class UpdateRequest extends FormRequest
if (is_array($triggers)) {
foreach ($triggers as $trigger) {
$active = array_key_exists('active', $trigger) ? $trigger['active'] : true;
$stopProcessing= array_key_exists('stop_processing', $trigger) ? $trigger['stop_processing'] : false;
$stopProcessing = array_key_exists('stop_processing', $trigger) ? $trigger['stop_processing'] : false;
$return[] = [
'type' => $trigger['type'],
'value' => $trigger['value'],

View File

@ -29,7 +29,6 @@ use Carbon\Carbon;
use FireflyIII\Support\Request\ChecksLogin;
use FireflyIII\Support\Request\ConvertsDataTypes;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Collection;
/**
* Class TestRequest
@ -39,7 +38,6 @@ class TestRequest extends FormRequest
use ConvertsDataTypes, ChecksLogin;
/**
* @return array
*/

View File

@ -38,7 +38,6 @@ class TriggerRequest extends FormRequest
use ConvertsDataTypes, ChecksLogin;
/**
* @return array
*/

View File

@ -59,6 +59,7 @@ class StoreRequest extends FormRequest
'apply_rules' => $this->boolean('apply_rules', true),
'transactions' => $this->getTransactionData(),
];
// TODO location
return $data;
}
@ -79,64 +80,64 @@ class StoreRequest extends FormRequest
$return[] = [
'type' => $this->stringFromValue($object['type']),
'date' => $this->dateFromValue($object['date']),
'order' => $this->integerFromValue((string) $object['order']),
'order' => $this->integerFromValue((string)$object['order']),
'currency_id' => $this->integerFromValue((string) $object['currency_id']),
'currency_id' => $this->integerFromValue((string)$object['currency_id']),
'currency_code' => $this->stringFromValue($object['currency_code']),
// foreign currency info:
'foreign_currency_id' => $this->integerFromValue((string) $object['foreign_currency_id']),
'foreign_currency_code' => $this->stringFromValue((string) $object['foreign_currency_code']),
'foreign_currency_id' => $this->integerFromValue((string)$object['foreign_currency_id']),
'foreign_currency_code' => $this->stringFromValue((string)$object['foreign_currency_code']),
// amount and foreign amount. Cannot be 0.
'amount' => $this->stringFromValue((string) $object['amount']),
'foreign_amount' => $this->stringFromValue((string) $object['foreign_amount']),
'amount' => $this->stringFromValue((string)$object['amount']),
'foreign_amount' => $this->stringFromValue((string)$object['foreign_amount']),
// description.
'description' => $this->stringFromValue($object['description']),
// source of transaction. If everything is null, assume cash account.
'source_id' => $this->integerFromValue((string) $object['source_id']),
'source_name' => $this->stringFromValue((string) $object['source_name']),
'source_iban' => $this->stringFromValue((string) $object['source_iban']),
'source_number' => $this->stringFromValue((string) $object['source_number']),
'source_bic' => $this->stringFromValue((string) $object['source_bic']),
'source_id' => $this->integerFromValue((string)$object['source_id']),
'source_name' => $this->stringFromValue((string)$object['source_name']),
'source_iban' => $this->stringFromValue((string)$object['source_iban']),
'source_number' => $this->stringFromValue((string)$object['source_number']),
'source_bic' => $this->stringFromValue((string)$object['source_bic']),
// destination of transaction. If everything is null, assume cash account.
'destination_id' => $this->integerFromValue((string) $object['destination_id']),
'destination_name' => $this->stringFromValue((string) $object['destination_name']),
'destination_iban' => $this->stringFromValue((string) $object['destination_iban']),
'destination_number' => $this->stringFromValue((string) $object['destination_number']),
'destination_bic' => $this->stringFromValue((string) $object['destination_bic']),
'destination_id' => $this->integerFromValue((string)$object['destination_id']),
'destination_name' => $this->stringFromValue((string)$object['destination_name']),
'destination_iban' => $this->stringFromValue((string)$object['destination_iban']),
'destination_number' => $this->stringFromValue((string)$object['destination_number']),
'destination_bic' => $this->stringFromValue((string)$object['destination_bic']),
// budget info
'budget_id' => $this->integerFromValue((string) $object['budget_id']),
'budget_name' => $this->stringFromValue((string) $object['budget_name']),
'budget_id' => $this->integerFromValue((string)$object['budget_id']),
'budget_name' => $this->stringFromValue((string)$object['budget_name']),
// category info
'category_id' => $this->integerFromValue((string) $object['category_id']),
'category_name' => $this->stringFromValue((string) $object['category_name']),
'category_id' => $this->integerFromValue((string)$object['category_id']),
'category_name' => $this->stringFromValue((string)$object['category_name']),
// journal bill reference. Optional. Will only work for withdrawals
'bill_id' => $this->integerFromValue((string) $object['bill_id']),
'bill_name' => $this->stringFromValue((string) $object['bill_name']),
'bill_id' => $this->integerFromValue((string)$object['bill_id']),
'bill_name' => $this->stringFromValue((string)$object['bill_name']),
// piggy bank reference. Optional. Will only work for transfers
'piggy_bank_id' => $this->integerFromValue((string) $object['piggy_bank_id']),
'piggy_bank_name' => $this->stringFromValue((string) $object['piggy_bank_name']),
'piggy_bank_id' => $this->integerFromValue((string)$object['piggy_bank_id']),
'piggy_bank_name' => $this->stringFromValue((string)$object['piggy_bank_name']),
// some other interesting properties
'reconciled' => $this->convertBoolean((string) $object['reconciled']),
'notes' => $this->nlStringFromValue((string) $object['notes']),
'reconciled' => $this->convertBoolean((string)$object['reconciled']),
'notes' => $this->nlStringFromValue((string)$object['notes']),
'tags' => $this->arrayFromValue($object['tags']),
// all custom fields:
'internal_reference' => $this->stringFromValue((string) $object['internal_reference']),
'external_id' => $this->stringFromValue((string) $object['external_id']),
'internal_reference' => $this->stringFromValue((string)$object['internal_reference']),
'external_id' => $this->stringFromValue((string)$object['external_id']),
'original_source' => sprintf('ff3-v%s|api-v%s', config('firefly.version'), config('firefly.api_version')),
'recurrence_id' => $this->integerFromValue($object['recurrence_id']),
'bunq_payment_id' => $this->stringFromValue((string) $object['bunq_payment_id']),
'external_uri' => $this->stringFromValue((string) $object['external_uri']),
'bunq_payment_id' => $this->stringFromValue((string)$object['bunq_payment_id']),
'external_uri' => $this->stringFromValue((string)$object['external_uri']),
'sepa_cc' => $this->stringFromValue($object['sepa_cc']),
'sepa_ct_op' => $this->stringFromValue($object['sepa_ct_op']),

View File

@ -102,8 +102,8 @@ class StoreRequest extends FormRequest
$journalRepos->setUser($user);
$data = $validator->getData();
$inwardId = (int) ($data['inward_id'] ?? 0);
$outwardId = (int) ($data['outward_id'] ?? 0);
$inwardId = (int)($data['inward_id'] ?? 0);
$outwardId = (int)($data['outward_id'] ?? 0);
$inward = $journalRepos->findNull($inwardId);
$outward = $journalRepos->findNull($outwardId);

View File

@ -23,11 +23,9 @@ declare(strict_types=1);
namespace FireflyIII\Api\V1\Requests\Models\TransactionLinkType;
use FireflyIII\Models\LinkType;
use FireflyIII\Support\Request\ChecksLogin;
use FireflyIII\Support\Request\ConvertsDataTypes;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
/**
* Class StoreRequest

View File

@ -23,7 +23,6 @@ declare(strict_types=1);
namespace FireflyIII\Api\V1\Requests\Models\TransactionLinkType;
use FireflyIII\Models\LinkType;
use FireflyIII\Support\Request\ChecksLogin;
use FireflyIII\Support\Request\ConvertsDataTypes;
use Illuminate\Foundation\Http\FormRequest;
@ -62,6 +61,7 @@ class UpdateRequest extends FormRequest
public function rules(): array
{
$linkType = $this->route()->parameter('linkType');
return [
'name' => [Rule::unique('link_types', 'name')->ignore($linkType->id), 'min:1'],
'outward' => ['different:inward', Rule::unique('link_types', 'outward')->ignore($linkType->id), 'min:1'],

View File

@ -39,7 +39,6 @@ class UpdateRequest extends FormRequest
use ConvertsDataTypes, ChecksLogin;
/**
* Get all data from the request.
*

View File

@ -45,7 +45,7 @@ class PreferenceStoreRequest extends FormRequest
if ('false' === $array['data']) {
$array['data'] = false;
}
if(is_numeric($array['data'])) {
if (is_numeric($array['data'])) {
$array['data'] = (float)$array['data'];
}

View File

@ -45,7 +45,7 @@ class PreferenceUpdateRequest extends FormRequest
if ('false' === $array['data']) {
$array['data'] = false;
}
if(is_numeric($array['data'])) {
if (is_numeric($array['data'])) {
$array['data'] = (float)$array['data'];
}

View File

@ -31,24 +31,23 @@ use Str;
/**
* Class CreateFirstUser
*
* @package FireflyIII\Console\Commands
*/
class CreateFirstUser extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'firefly-iii:create-first-user {email}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Creates a new user and gives admin rights. Outputs the password on the command line. Strictly for testing.';
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'firefly-iii:create-first-user {email}';
private UserRepositoryInterface $repository;
/**
@ -60,12 +59,14 @@ class CreateFirstUser extends Command
{
if ('testing' !== env('APP_ENV', 'local')) {
$this->error('This command only works in the testing environment.');
return 1;
}
$this->stupidLaravel();
$count = $this->repository->count();
if ($count > 0) {
$this->error('Already have more than zero users in DB.');
return 1;
}
$data = [
@ -82,6 +83,7 @@ class CreateFirstUser extends Command
$this->info(sprintf('Created new admin user (ID #%d) with email address "%s" and password "%s".', $user->id, $user->email, $password));
$this->error('Change this password.');
return 0;
}

View File

@ -85,6 +85,26 @@ class DecryptDatabase extends Command
return 0;
}
/**
* @param string $table
* @param array $fields
*/
private function decryptTable(string $table, array $fields): void
{
if ($this->isDecrypted($table)) {
$this->info(sprintf('No decryption required for table "%s".', $table));
return;
}
foreach ($fields as $field) {
$this->decryptField($table, $field);
}
$this->line(sprintf('Decrypted the data in table "%s".', $table));
// mark as decrypted:
$configName = sprintf('is_decrypted_%s', $table);
app('fireflyconfig')->set($configName, true);
}
/**
* @param string $table
*
@ -100,53 +120,12 @@ class DecryptDatabase extends Command
Log::error($e->getMessage());
}
if (null !== $configVar) {
return (bool) $configVar->data;
return (bool)$configVar->data;
}
return false;
}
/**
* Tries to decrypt data. Will only throw an exception when the MAC is invalid.
*
* @param $value
*
* @return string
* @throws FireflyException
*/
private function tryDecrypt($value)
{
try {
$value = Crypt::decrypt($value);
} catch (DecryptException $e) {
if ('The MAC is invalid.' === $e->getMessage()) {
throw new FireflyException($e->getMessage()); // @codeCoverageIgnore
}
}
return $value;
}
/**
* @param string $table
* @param array $fields
*/
private function decryptTable(string $table, array $fields): void
{
if ($this->isDecrypted($table)) {
$this->info(sprintf('No decryption required for table "%s".', $table));
return;
}
foreach ($fields as $field) {
$this->decryptField($table, $field);
}
$this->line(sprintf('Decrypted the data in table "%s".', $table));
// mark as decrypted:
$configName = sprintf('is_decrypted_%s', $table);
app('fireflyconfig')->set($configName, true);
}
/**
* @param string $table
* @param string $field
@ -171,7 +150,7 @@ class DecryptDatabase extends Command
if (null === $original) {
return;
}
$id = (int) $row->id;
$id = (int)$row->id;
$value = '';
try {
@ -186,6 +165,7 @@ class DecryptDatabase extends Command
// A separate routine for preferences table:
if ('preferences' === $table) {
$this->decryptPreferencesRow($id, $value);
return;
}
@ -194,6 +174,27 @@ class DecryptDatabase extends Command
}
}
/**
* Tries to decrypt data. Will only throw an exception when the MAC is invalid.
*
* @param $value
*
* @return string
* @throws FireflyException
*/
private function tryDecrypt($value)
{
try {
$value = Crypt::decrypt($value);
} catch (DecryptException $e) {
if ('The MAC is invalid.' === $e->getMessage()) {
throw new FireflyException($e->getMessage()); // @codeCoverageIgnore
}
}
return $value;
}
/**
* @param int $id
* @param string $value
@ -209,11 +210,12 @@ class DecryptDatabase extends Command
Log::warning($message);
Log::warning($value);
Log::warning($e->getTraceAsString());
return;
}
/** @var Preference $object */
$object = Preference::find((int) $id);
$object = Preference::find((int)$id);
if (null !== $object) {
$object->data = $newValue;
$object->save();

View File

@ -88,6 +88,7 @@ class ScanAttachments extends Command
}
app('telemetry')->feature('system.command.executed', $this->signature);
return 0;
}
}

View File

@ -63,14 +63,6 @@ class MigrateRecurrenceType extends Command
return false; // @codeCoverageIgnore
}
/**
*
*/
private function getInvalidType(): TransactionType
{
return TransactionType::whereType(TransactionType::INVALID)->firstOrCreate(['type' => TransactionType::INVALID]);
}
/**
*
*/
@ -85,14 +77,6 @@ class MigrateRecurrenceType extends Command
}
}
/**
*
*/
private function markAsExecuted(): void
{
app('fireflyconfig')->set(self::CONFIG_NAME, true);
}
private function migrateRecurrence(Recurrence $recurrence): void
{
$originalType = (int)$recurrence->transaction_type_id;
@ -106,4 +90,20 @@ class MigrateRecurrenceType extends Command
}
$this->line(sprintf('Updated recurrence #%d to new transaction type model.', $recurrence->id));
}
/**
*
*/
private function getInvalidType(): TransactionType
{
return TransactionType::whereType(TransactionType::INVALID)->firstOrCreate(['type' => TransactionType::INVALID]);
}
/**
*
*/
private function markAsExecuted(): void
{
app('fireflyconfig')->set(self::CONFIG_NAME, true);
}
}

View File

@ -80,6 +80,53 @@ class UpgradeFireflyInstructions extends Command
return 0;
}
/**
* Render upgrade instructions.
*/
private function updateInstructions(): void
{
/** @var string $version */
$version = config('firefly.version');
$config = config('upgrade.text.upgrade');
$text = '';
foreach (array_keys($config) as $compare) {
// if string starts with:
if (0 === strpos($version, $compare)) {
$text = $config[$compare];
}
}
$this->showLine();
$this->boxed('');
if (null === $text) {
$this->boxed(sprintf('Thank you for updating to Firefly III, v%s', $version));
$this->boxedInfo('There are no extra upgrade instructions.');
$this->boxed('Firefly III should be ready for use.');
$this->boxed('');
$this->showLine();
return;
}
$this->boxed(sprintf('Thank you for updating to Firefly III, v%s!', $version));
$this->boxedInfo($text);
$this->boxed('');
$this->showLine();
}
/**
* Show a line.
*/
private function showLine(): void
{
$line = '+';
for ($i = 0; $i < 78; ++$i) {
$line .= '-';
}
$line .= '+';
$this->line($line);
}
/**
* Show a nice box.
*
@ -140,51 +187,4 @@ class UpgradeFireflyInstructions extends Command
$this->boxed('');
$this->showLine();
}
/**
* Show a line.
*/
private function showLine(): void
{
$line = '+';
for ($i = 0; $i < 78; ++$i) {
$line .= '-';
}
$line .= '+';
$this->line($line);
}
/**
* Render upgrade instructions.
*/
private function updateInstructions(): void
{
/** @var string $version */
$version = config('firefly.version');
$config = config('upgrade.text.upgrade');
$text = '';
foreach (array_keys($config) as $compare) {
// if string starts with:
if (0 === strpos($version, $compare)) {
$text = $config[$compare];
}
}
$this->showLine();
$this->boxed('');
if (null === $text) {
$this->boxed(sprintf('Thank you for updating to Firefly III, v%s', $version));
$this->boxedInfo('There are no extra upgrade instructions.');
$this->boxed('Firefly III should be ready for use.');
$this->boxed('');
$this->showLine();
return;
}
$this->boxed(sprintf('Thank you for updating to Firefly III, v%s!', $version));
$this->boxedInfo($text);
$this->boxed('');
$this->showLine();
}
}

View File

@ -38,12 +38,12 @@ use Log;
trait VerifiesAccessToken
{
/**
* @throws FireflyException
* @return User
* @throws FireflyException
*/
public function getUser(): User
{
$userId = (int) $this->option('user');
$userId = (int)$this->option('user');
/** @var UserRepositoryInterface $repository */
$repository = app(UserRepositoryInterface::class);
$user = $repository->findNull($userId);
@ -70,8 +70,8 @@ trait VerifiesAccessToken
*/
protected function verifyAccessToken(): bool
{
$userId = (int) $this->option('user');
$token = (string) $this->option('token');
$userId = (int)$this->option('user');
$token = (string)$this->option('token');
/** @var UserRepositoryInterface $repository */
$repository = app(UserRepositoryInterface::class);
$user = $repository->findNull($userId);

View File

@ -35,6 +35,7 @@ use Illuminate\Queue\SerializesModels;
class DestroyedTransactionGroup extends Event
{
use SerializesModels;
public TransactionGroup $transactionGroup;

View File

@ -20,6 +20,7 @@
*/
declare(strict_types=1);
namespace FireflyIII\Events;

View File

@ -20,6 +20,7 @@
*/
declare(strict_types=1);
namespace FireflyIII\Events;

View File

@ -128,8 +128,10 @@ class GracefulNotFoundHandler extends ExceptionHandler
case 'transactions.bulk.edit':
if ('POST' === $request->method()) {
$request->session()->reflash();
return redirect(route('index'));
}
return parent::render($request, $exception);
}
@ -148,7 +150,7 @@ class GracefulNotFoundHandler extends ExceptionHandler
/** @var User $user */
$user = auth()->user();
$route = $request->route();
$accountId = (int) $route->parameter('account');
$accountId = (int)$route->parameter('account');
/** @var Account $account */
$account = $user->accounts()->with(['accountType'])->withTrashed()->find($accountId);
if (null === $account) {
@ -163,6 +165,46 @@ class GracefulNotFoundHandler extends ExceptionHandler
return redirect(route('accounts.index', [$shortType]));
}
/**
* @param Throwable $request
* @param Exception $exception
*
* @return RedirectResponse|\Illuminate\Http\Response|Redirector|Response
* @throws Exception
*/
private function handleGroup(Request $request, Throwable $exception)
{
Log::debug('404 page is probably a deleted group. Redirect to overview of group types.');
/** @var User $user */
$user = auth()->user();
$route = $request->route();
$groupId = (int)$route->parameter('transactionGroup');
/** @var TransactionGroup $group */
$group = $user->transactionGroups()->withTrashed()->find($groupId);
if (null === $group) {
Log::error(sprintf('Could not find group %d, so give big fat error.', $groupId));
return parent::render($request, $exception);
}
/** @var TransactionJournal $journal */
$journal = $group->transactionJournals()->withTrashed()->first();
if (null === $journal) {
Log::error(sprintf('Could not find journal for group %d, so give big fat error.', $groupId));
return parent::render($request, $exception);
}
$type = $journal->transactionType->type;
$request->session()->reflash();
if (TransactionType::RECONCILIATION === $type) {
return redirect(route('accounts.index', ['asset']));
}
return redirect(route('transactions.index', [strtolower($type)]));
}
/**
* @param Request $request
* @param Throwable $exception
@ -176,7 +218,7 @@ class GracefulNotFoundHandler extends ExceptionHandler
/** @var User $user */
$user = auth()->user();
$route = $request->route();
$attachmentId = (int) $route->parameter('attachment');
$attachmentId = (int)$route->parameter('attachment');
/** @var Attachment $attachment */
$attachment = $user->attachments()->withTrashed()->find($attachmentId);
if (null === $attachment) {
@ -208,44 +250,4 @@ class GracefulNotFoundHandler extends ExceptionHandler
return parent::render($request, $exception);
}
/**
* @param Throwable $request
* @param Exception $exception
*
* @return RedirectResponse|\Illuminate\Http\Response|Redirector|Response
* @throws Exception
*/
private function handleGroup(Request $request, Throwable $exception)
{
Log::debug('404 page is probably a deleted group. Redirect to overview of group types.');
/** @var User $user */
$user = auth()->user();
$route = $request->route();
$groupId = (int) $route->parameter('transactionGroup');
/** @var TransactionGroup $group */
$group = $user->transactionGroups()->withTrashed()->find($groupId);
if (null === $group) {
Log::error(sprintf('Could not find group %d, so give big fat error.', $groupId));
return parent::render($request, $exception);
}
/** @var TransactionJournal $journal */
$journal = $group->transactionJournals()->withTrashed()->first();
if (null === $journal) {
Log::error(sprintf('Could not find journal for group %d, so give big fat error.', $groupId));
return parent::render($request, $exception);
}
$type = $journal->transactionType->type;
$request->session()->reflash();
if (TransactionType::RECONCILIATION === $type) {
return redirect(route('accounts.index', ['asset']));
}
return redirect(route('transactions.index', [strtolower($type)]));
}
}

View File

@ -36,6 +36,7 @@ use Illuminate\Validation\ValidationException as LaravelValidationException;
use League\OAuth2\Server\Exception\OAuthServerException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Throwable;
/**
* Class Handler
*
@ -87,7 +88,9 @@ class Handler extends ExceptionHandler
);
}
return response()->json(['message' => sprintf('Internal Firefly III Exception: %s', $exception->getMessage()), 'exception' => get_class($exception)], 500);
return response()->json(
['message' => sprintf('Internal Firefly III Exception: %s', $exception->getMessage()), 'exception' => get_class($exception)], 500
);
}
if ($exception instanceof NotFoundHttpException) {
@ -115,9 +118,9 @@ class Handler extends ExceptionHandler
*
* @param Exception $exception
*
* @return void
* @throws Exception
*
* @return void
*/
public function report(Throwable $exception)
{
@ -150,7 +153,7 @@ class Handler extends ExceptionHandler
// create job that will mail.
$ipAddress = request()->ip() ?? '0.0.0.0';
$job = new MailError($userData, (string) config('firefly.site_owner'), $ipAddress, $data);
$job = new MailError($userData, (string)config('firefly.site_owner'), $ipAddress, $data);
dispatch($job);
}

View File

@ -65,6 +65,31 @@ class AccountFactory
}
/**
* @param string $accountName
* @param string $accountType
*
* @return Account
* @throws FireflyException
*/
public function findOrCreate(string $accountName, string $accountType): Account
{
Log::debug(sprintf('Searching for "%s" of type "%s"', $accountName, $accountType));
/** @var AccountType $type */
$type = AccountType::whereType($accountType)->first();
$return = $this->user->accounts->where('account_type_id', $type->id)->where('name', $accountName)->first();
if (null === $return) {
Log::debug('Found nothing. Will create a new one.');
$return = $this->create(
['user_id' => $this->user->id, 'name' => $accountName, 'account_type_id' => $type->id, 'account_type' => null, 'virtual_balance' => '0',
'iban' => null, 'active' => true,]
);
}
return $return;
}
/**
* @param array $data
*
@ -150,52 +175,6 @@ class AccountFactory
return $return;
}
/**
* @param string $accountName
* @param string $accountType
*
* @return Account|null
*/
public function find(string $accountName, string $accountType): ?Account
{
$type = AccountType::whereType($accountType)->first();
return $this->user->accounts()->where('account_type_id', $type->id)->where('name', $accountName)->first();
}
/**
* @param string $accountName
* @param string $accountType
*
* @return Account
* @throws FireflyException
*/
public function findOrCreate(string $accountName, string $accountType): Account
{
Log::debug(sprintf('Searching for "%s" of type "%s"', $accountName, $accountType));
/** @var AccountType $type */
$type = AccountType::whereType($accountType)->first();
$return = $this->user->accounts->where('account_type_id', $type->id)->where('name', $accountName)->first();
if (null === $return) {
Log::debug('Found nothing. Will create a new one.');
$return = $this->create(
['user_id' => $this->user->id, 'name' => $accountName, 'account_type_id' => $type->id, 'account_type' => null, 'virtual_balance' => '0',
'iban' => null, 'active' => true,]
);
}
return $return;
}
/**
* @param User $user
*/
public function setUser(User $user): void
{
$this->user = $user;
}
/**
* @param int|null $accountTypeId
* @param null|string $accountType
@ -234,5 +213,26 @@ class AccountFactory
}
/**
* @param string $accountName
* @param string $accountType
*
* @return Account|null
*/
public function find(string $accountName, string $accountType): ?Account
{
$type = AccountType::whereType($accountType)->first();
return $this->user->accounts()->where('account_type_id', $type->id)->where('name', $accountName)->first();
}
/**
* @param User $user
*/
public function setUser(User $user): void
{
$this->user = $user;
}
}

View File

@ -34,16 +34,6 @@ use Log;
*/
class AccountMetaFactory
{
/**
* @param array $data
*
* @return AccountMeta|null
*/
public function create(array $data): ?AccountMeta
{
return AccountMeta::create($data);
}
/**
* Create update or delete meta data.
*
@ -87,4 +77,14 @@ class AccountMetaFactory
return $entry;
}
/**
* @param array $data
*
* @return AccountMeta|null
*/
public function create(array $data): ?AccountMeta
{
return AccountMeta::create($data);
}
}

View File

@ -40,18 +40,19 @@ class AttachmentFactory
/**
* @param array $data
*
* @throws FireflyException
* @return Attachment|null
* @throws FireflyException
*/
public function create(array $data): ?Attachment
{
// append if necessary.
$model = false === strpos($data['attachable_type'], 'FireflyIII') ? sprintf('FireflyIII\\Models\\%s', $data['attachable_type']) : $data['attachable_type'];
$model = false === strpos($data['attachable_type'], 'FireflyIII') ? sprintf('FireflyIII\\Models\\%s', $data['attachable_type'])
: $data['attachable_type'];
// get journal instead of transaction.
if (Transaction::class === $model) {
/** @var Transaction $transaction */
$transaction = $this->user->transactions()->find((int) $data['attachable_id']);
$transaction = $this->user->transactions()->find((int)$data['attachable_id']);
if (null === $transaction) {
throw new FireflyException('Unexpectedly could not find transaction'); // @codeCoverageIgnore
}
@ -74,7 +75,7 @@ class AttachmentFactory
'uploaded' => 0,
]
);
$notes = (string) ($data['notes'] ?? '');
$notes = (string)($data['notes'] ?? '');
if ('' !== $notes) {
$note = new Note;
$note->noteable()->associate($attachment);

View File

@ -41,8 +41,8 @@ class BudgetFactory
*/
public function find(?int $budgetId, ?string $budgetName): ?Budget
{
$budgetId = (int) $budgetId;
$budgetName = (string) $budgetName;
$budgetId = (int)$budgetId;
$budgetName = (string)$budgetName;
if (0 === $budgetId && '' === $budgetName) {
return null;

View File

@ -37,16 +37,6 @@ class CategoryFactory
{
private User $user;
/**
* @param string $name
*
* @return Category|null
*/
public function findByName(string $name): ?Category
{
return $this->user->categories()->where('name', $name)->first();
}
/**
* @param int|null $categoryId
* @param null|string $categoryName
@ -94,6 +84,16 @@ class CategoryFactory
return null;
}
/**
* @param string $name
*
* @return Category|null
*/
public function findByName(string $name): ?Category
{
return $this->user->categories()->where('name', $name)->first();
}
/**
* @param User $user
*/

View File

@ -42,8 +42,8 @@ class PiggyBankFactory
*/
public function find(?int $piggyBankId, ?string $piggyBankName): ?PiggyBank
{
$piggyBankId = (int) $piggyBankId;
$piggyBankName = (string) $piggyBankName;
$piggyBankId = (int)$piggyBankId;
$piggyBankName = (string)$piggyBankName;
if ('' === $piggyBankName && 0 === $piggyBankId) {
return null;
}

View File

@ -36,6 +36,43 @@ class TagFactory
{
private User $user;
/**
* @param string $tag
*
* @return Tag|null
*/
public function findOrCreate(string $tag): ?Tag
{
$tag = trim($tag);
Log::debug(sprintf('Now in TagFactory::findOrCreate("%s")', $tag));
/** @var Tag $dbTag */
$dbTag = $this->user->tags()->where('tag', $tag)->first();
if (null !== $dbTag) {
Log::debug(sprintf('Tag exists (#%d), return it.', $dbTag->id));
return $dbTag;
}
$newTag = $this->create(
[
'tag' => $tag,
'date' => null,
'description' => null,
'latitude' => null,
'longitude' => null,
'zoom_level' => null,
]
);
if (null === $newTag) {
Log::error(sprintf('TagFactory::findOrCreate("%s") but tag is unexpectedly NULL!', $tag));
return null;
}
Log::debug(sprintf('Created new tag #%d ("%s")', $newTag->id, $newTag->tag));
return $newTag;
}
/**
* @param array $data
*
@ -43,9 +80,9 @@ class TagFactory
*/
public function create(array $data): ?Tag
{
$zoomLevel = 0 === (int) $data['zoom_level'] ? null : (int) $data['zoom_level'];
$latitude = 0.0 === (float) $data['latitude'] ? null : (float) $data['latitude'];
$longitude = 0.0 === (float) $data['longitude'] ? null : (float) $data['longitude'];
$zoomLevel = 0 === (int)$data['zoom_level'] ? null : (int)$data['zoom_level'];
$latitude = 0.0 === (float)$data['latitude'] ? null : (float)$data['latitude'];
$longitude = 0.0 === (float)$data['longitude'] ? null : (float)$data['longitude'];
$array = [
'user_id' => $this->user->id,
'tag' => trim($data['tag']),
@ -70,41 +107,6 @@ class TagFactory
return $tag;
}
/**
* @param string $tag
*
* @return Tag|null
*/
public function findOrCreate(string $tag): ?Tag
{
$tag = trim($tag);
Log::debug(sprintf('Now in TagFactory::findOrCreate("%s")', $tag));
/** @var Tag $dbTag */
$dbTag = $this->user->tags()->where('tag', $tag)->first();
if (null !== $dbTag) {
Log::debug(sprintf('Tag exists (#%d), return it.', $dbTag->id));
return $dbTag;
}
$newTag = $this->create(
[
'tag' => $tag,
'date' => null,
'description' => null,
'latitude' => null,
'longitude' => null,
'zoom_level' => null,
]
);
if (null === $newTag) {
Log::error(sprintf('TagFactory::findOrCreate("%s") but tag is unexpectedly NULL!', $tag));
return null;
}
Log::debug(sprintf('Created new tag #%d ("%s")', $newTag->id, $newTag->tag));
return $newTag;
}
/**
* @param User $user
*/

View File

@ -40,8 +40,8 @@ class TransactionCurrencyFactory
/**
* @param array $data
*
* @throws FireflyException
* @return TransactionCurrency
* @throws FireflyException
*/
public function create(array $data): TransactionCurrency
{
@ -73,8 +73,8 @@ class TransactionCurrencyFactory
*/
public function find(?int $currencyId, ?string $currencyCode): ?TransactionCurrency
{
$currencyCode = (string) $currencyCode;
$currencyId = (int) $currencyId;
$currencyCode = (string)$currencyCode;
$currencyId = (int)$currencyId;
if ('' === $currencyCode && 0 === $currencyId) {
Log::debug('Cannot find anything on empty currency code and empty currency ID!');

View File

@ -62,8 +62,8 @@ class TransactionFactory
* @param string $amount
* @param string|null $foreignAmount
*
* @throws FireflyException
* @return Transaction
* @throws FireflyException
*/
public function createNegative(string $amount, ?string $foreignAmount): Transaction
{
@ -77,14 +77,74 @@ class TransactionFactory
return $this->create(app('steam')->negative($amount), $foreignAmount);
}
/**
* @param string $amount
* @param string|null $foreignAmount
*
* @return Transaction
* @throws FireflyException
*/
private function create(string $amount, ?string $foreignAmount): Transaction
{
$result = null;
if ('' === $foreignAmount) {
$foreignAmount = null;
}
$data = [
'reconciled' => $this->reconciled,
'account_id' => $this->account->id,
'transaction_journal_id' => $this->journal->id,
'description' => null,
'transaction_currency_id' => $this->currency->id,
'amount' => $amount,
'foreign_amount' => null,
'foreign_currency_id' => null,
'identifier' => 0,
];
try {
$result = Transaction::create($data);
// @codeCoverageIgnoreStart
} catch (QueryException $e) {
Log::error(sprintf('Could not create transaction: %s', $e->getMessage()), $data);
Log::error($e->getMessage());
Log::error($e->getTraceAsString());
throw new FireflyException('Query exception when creating transaction.');
}
if (null === $result) {
throw new FireflyException('Transaction is NULL.');
}
// @codeCoverageIgnoreEnd
if (null !== $result) {
Log::debug(
sprintf(
'Created transaction #%d (%s %s, account %s), part of journal #%d',
$result->id,
$this->currency->code,
$amount,
$this->account->name,
$this->journal->id
)
);
// do foreign currency thing: add foreign currency info to $one and $two if necessary.
if (null !== $this->foreignCurrency && null !== $foreignAmount && $this->foreignCurrency->id !== $this->currency->id && '' !== $foreignAmount) {
$result->foreign_currency_id = $this->foreignCurrency->id;
$result->foreign_amount = $foreignAmount;
}
$result->save();
}
return $result;
}
/**
* Create transaction with positive amount (for destination accounts).
*
* @param string $amount
* @param string|null $foreignAmount
*
* @throws FireflyException
* @return Transaction
* @throws FireflyException
*/
public function createPositive(string $amount, ?string $foreignAmount): Transaction
{
@ -157,64 +217,4 @@ class TransactionFactory
{
$this->user = $user;
}
/**
* @param string $amount
* @param string|null $foreignAmount
*
* @throws FireflyException
* @return Transaction
*/
private function create(string $amount, ?string $foreignAmount): Transaction
{
$result = null;
if ('' === $foreignAmount) {
$foreignAmount = null;
}
$data = [
'reconciled' => $this->reconciled,
'account_id' => $this->account->id,
'transaction_journal_id' => $this->journal->id,
'description' => null,
'transaction_currency_id' => $this->currency->id,
'amount' => $amount,
'foreign_amount' => null,
'foreign_currency_id' => null,
'identifier' => 0,
];
try {
$result = Transaction::create($data);
// @codeCoverageIgnoreStart
} catch (QueryException $e) {
Log::error(sprintf('Could not create transaction: %s', $e->getMessage()), $data);
Log::error($e->getMessage());
Log::error($e->getTraceAsString());
throw new FireflyException('Query exception when creating transaction.');
}
if (null === $result) {
throw new FireflyException('Transaction is NULL.');
}
// @codeCoverageIgnoreEnd
if (null !== $result) {
Log::debug(
sprintf(
'Created transaction #%d (%s %s, account %s), part of journal #%d',
$result->id,
$this->currency->code,
$amount,
$this->account->name,
$this->journal->id
)
);
// do foreign currency thing: add foreign currency info to $one and $two if necessary.
if (null !== $this->foreignCurrency && null !== $foreignAmount && $this->foreignCurrency->id !== $this->currency->id && '' !== $foreignAmount) {
$result->foreign_currency_id = $this->foreignCurrency->id;
$result->foreign_amount = $foreignAmount;
}
$result->save();
}
return $result;
}
}

View File

@ -54,8 +54,8 @@ class TransactionGroupFactory
*
* @param array $data
*
* @throws DuplicateTransactionException
* @return TransactionGroup
* @throws DuplicateTransactionException
*/
public function create(array $data): TransactionGroup
{

View File

@ -140,74 +140,6 @@ class TransactionJournalFactory
return $collection;
}
/**
* @param bool $errorOnHash
*/
public function setErrorOnHash(bool $errorOnHash): void
{
$this->errorOnHash = $errorOnHash;
if (true === $errorOnHash) {
Log::info('Will trigger duplication alert for this journal.');
}
}
/**
* Set the user.
*
* @param User $user
*/
public function setUser(User $user): void
{
$this->user = $user;
$this->currencyRepository->setUser($this->user);
$this->tagFactory->setUser($user);
$this->billRepository->setUser($this->user);
$this->budgetRepository->setUser($this->user);
$this->categoryRepository->setUser($this->user);
$this->piggyRepository->setUser($this->user);
$this->accountRepository->setUser($this->user);
}
/**
* @param TransactionJournal $journal
* @param NullArrayObject $data
* @param string $field
*/
protected function storeMeta(TransactionJournal $journal, NullArrayObject $data, string $field): void
{
$set = [
'journal' => $journal,
'name' => $field,
'data' => (string)($data[$field] ?? ''),
];
Log::debug(sprintf('Going to store meta-field "%s", with value "%s".', $set['name'], $set['data']));
/** @var TransactionJournalMetaFactory $factory */
$factory = app(TransactionJournalMetaFactory::class);
$factory->updateOrCreate($set);
}
/**
* Set foreign currency to NULL if it's the same as the normal currency:
*
* @param TransactionCurrency $currency
* @param TransactionCurrency|null $foreignCurrency
*
* @return TransactionCurrency|null
*/
private function compareCurrencies(?TransactionCurrency $currency, ?TransactionCurrency $foreignCurrency): ?TransactionCurrency
{
if (null === $currency) {
return null;
}
if (null !== $foreignCurrency && $foreignCurrency->id === $currency->id) {
return null;
}
return $foreignCurrency;
}
/**
* @param NullArrayObject $row
*
@ -360,6 +292,29 @@ class TransactionJournalFactory
return $journal;
}
/**
* @param NullArrayObject $row
*
* @return string
*/
private function hashArray(NullArrayObject $row): string
{
$dataRow = $row->getArrayCopy();
unset($dataRow['import_hash_v2'], $dataRow['original_source']);
$json = json_encode($dataRow, JSON_THROW_ON_ERROR, 512);
if (false === $json) {
// @codeCoverageIgnoreStart
$json = json_encode((string)microtime(), JSON_THROW_ON_ERROR, 512);
Log::error(sprintf('Could not hash the original row! %s', json_last_error_msg()), $dataRow);
// @codeCoverageIgnoreEnd
}
$hash = hash('sha256', $json);
Log::debug(sprintf('The hash is: %s', $hash), $dataRow);
return $hash;
}
/**
* If this transaction already exists, throw an error.
*
@ -387,6 +342,127 @@ class TransactionJournalFactory
}
}
/**
* @param NullArrayObject $data
*
* @throws FireflyException
*/
private function validateAccounts(NullArrayObject $data): void
{
$transactionType = $data['type'] ?? 'invalid';
$this->accountValidator->setUser($this->user);
$this->accountValidator->setTransactionType($transactionType);
// validate source account.
$sourceId = $data['source_id'] ? (int)$data['source_id'] : null;
$sourceName = $data['source_name'] ? (string)$data['source_name'] : null;
$validSource = $this->accountValidator->validateSource($sourceId, $sourceName, null);
// do something with result:
if (false === $validSource) {
throw new FireflyException(sprintf('Source: %s', $this->accountValidator->sourceError)); // @codeCoverageIgnore
}
Log::debug('Source seems valid.');
// validate destination account
$destinationId = $data['destination_id'] ? (int)$data['destination_id'] : null;
$destinationName = $data['destination_name'] ? (string)$data['destination_name'] : null;
$validDestination = $this->accountValidator->validateDestination($destinationId, $destinationName, null);
// do something with result:
if (false === $validDestination) {
throw new FireflyException(sprintf('Destination: %s', $this->accountValidator->destError)); // @codeCoverageIgnore
}
}
/**
* @param string $type
* @param TransactionCurrency|null $currency
* @param Account $source
* @param Account $destination
*
* @return TransactionCurrency
*/
private function getCurrencyByAccount(string $type, ?TransactionCurrency $currency, Account $source, Account $destination): TransactionCurrency
{
Log::debug('Now ingetCurrencyByAccount()');
switch ($type) {
default:
case TransactionType::WITHDRAWAL:
case TransactionType::TRANSFER:
return $this->getCurrency($currency, $source);
case TransactionType::DEPOSIT:
return $this->getCurrency($currency, $destination);
}
}
/**
* @param TransactionCurrency|null $currency
* @param Account $account
*
* @return TransactionCurrency
*/
private function getCurrency(?TransactionCurrency $currency, Account $account): TransactionCurrency
{
Log::debug('Now in getCurrency()');
$preference = $this->accountRepository->getAccountCurrency($account);
if (null === $preference && null === $currency) {
// return user's default:
return app('amount')->getDefaultCurrencyByUser($this->user);
}
$result = ($preference ?? $currency) ?? app('amount')->getSystemCurrency();
Log::debug(sprintf('Currency is now #%d (%s) because of account #%d (%s)', $result->id, $result->code, $account->id, $account->name));
return $result;
}
/**
* Set foreign currency to NULL if it's the same as the normal currency:
*
* @param TransactionCurrency $currency
* @param TransactionCurrency|null $foreignCurrency
*
* @return TransactionCurrency|null
*/
private function compareCurrencies(?TransactionCurrency $currency, ?TransactionCurrency $foreignCurrency): ?TransactionCurrency
{
if (null === $currency) {
return null;
}
if (null !== $foreignCurrency && $foreignCurrency->id === $currency->id) {
return null;
}
return $foreignCurrency;
}
/**
* @param string $type
* @param TransactionCurrency|null $foreignCurrency
* @param Account $destination
*
* @return TransactionCurrency|null
*/
private function getForeignByAccount(string $type, ?TransactionCurrency $foreignCurrency, Account $destination): ?TransactionCurrency
{
if (TransactionType::TRANSFER === $type) {
return $this->getCurrency($foreignCurrency, $destination);
}
return $foreignCurrency;
}
/**
* @param string $description
*
* @return string
*/
private function getDescription(string $description): string
{
$description = '' === $description ? '(empty description)' : $description;
return substr($description, 0, 255);
}
/**
* Force the deletion of an entire set of transaction journals and their meta object in case of
* an error creating a group.
@ -418,110 +494,6 @@ class TransactionJournalFactory
}
}
/**
* @param TransactionCurrency|null $currency
* @param Account $account
*
* @return TransactionCurrency
*/
private function getCurrency(?TransactionCurrency $currency, Account $account): TransactionCurrency
{
Log::debug('Now in getCurrency()');
$preference = $this->accountRepository->getAccountCurrency($account);
if (null === $preference && null === $currency) {
// return user's default:
return app('amount')->getDefaultCurrencyByUser($this->user);
}
$result = ($preference ?? $currency) ?? app('amount')->getSystemCurrency();
Log::debug(sprintf('Currency is now #%d (%s) because of account #%d (%s)', $result->id, $result->code, $account->id, $account->name));
return $result;
}
/**
* @param string $type
* @param TransactionCurrency|null $currency
* @param Account $source
* @param Account $destination
*
* @return TransactionCurrency
*/
private function getCurrencyByAccount(string $type, ?TransactionCurrency $currency, Account $source, Account $destination): TransactionCurrency
{
Log::debug('Now ingetCurrencyByAccount()');
switch ($type) {
default:
case TransactionType::WITHDRAWAL:
case TransactionType::TRANSFER:
return $this->getCurrency($currency, $source);
case TransactionType::DEPOSIT:
return $this->getCurrency($currency, $destination);
}
}
/**
* @param string $description
*
* @return string
*/
private function getDescription(string $description): string
{
$description = '' === $description ? '(empty description)' : $description;
return substr($description, 0, 255);
}
/**
* @param string $type
* @param TransactionCurrency|null $foreignCurrency
* @param Account $destination
*
* @return TransactionCurrency|null
*/
private function getForeignByAccount(string $type, ?TransactionCurrency $foreignCurrency, Account $destination): ?TransactionCurrency
{
if (TransactionType::TRANSFER === $type) {
return $this->getCurrency($foreignCurrency, $destination);
}
return $foreignCurrency;
}
/**
* @param NullArrayObject $row
*
* @return string
*/
private function hashArray(NullArrayObject $row): string
{
$dataRow = $row->getArrayCopy();
unset($dataRow['import_hash_v2'], $dataRow['original_source']);
$json = json_encode($dataRow, JSON_THROW_ON_ERROR, 512);
if (false === $json) {
// @codeCoverageIgnoreStart
$json = json_encode((string)microtime(), JSON_THROW_ON_ERROR, 512);
Log::error(sprintf('Could not hash the original row! %s', json_last_error_msg()), $dataRow);
// @codeCoverageIgnoreEnd
}
$hash = hash('sha256', $json);
Log::debug(sprintf('The hash is: %s', $hash), $dataRow);
return $hash;
}
/**
* @param TransactionJournal $journal
* @param NullArrayObject $transaction
*/
private function storeMetaFields(TransactionJournal $journal, NullArrayObject $transaction): void
{
foreach ($this->fields as $field) {
$this->storeMeta($journal, $transaction, $field);
}
}
/**
* Link a piggy bank to this journal.
*
@ -549,34 +521,62 @@ class TransactionJournalFactory
}
/**
* @param NullArrayObject $data
*
* @throws FireflyException
* @param TransactionJournal $journal
* @param NullArrayObject $transaction
*/
private function validateAccounts(NullArrayObject $data): void
private function storeMetaFields(TransactionJournal $journal, NullArrayObject $transaction): void
{
$transactionType = $data['type'] ?? 'invalid';
$this->accountValidator->setUser($this->user);
$this->accountValidator->setTransactionType($transactionType);
// validate source account.
$sourceId = $data['source_id'] ? (int)$data['source_id'] : null;
$sourceName = $data['source_name'] ? (string)$data['source_name'] : null;
$validSource = $this->accountValidator->validateSource($sourceId, $sourceName, null);
// do something with result:
if (false === $validSource) {
throw new FireflyException(sprintf('Source: %s', $this->accountValidator->sourceError)); // @codeCoverageIgnore
foreach ($this->fields as $field) {
$this->storeMeta($journal, $transaction, $field);
}
Log::debug('Source seems valid.');
// validate destination account
$destinationId = $data['destination_id'] ? (int)$data['destination_id'] : null;
$destinationName = $data['destination_name'] ? (string)$data['destination_name'] : null;
$validDestination = $this->accountValidator->validateDestination($destinationId, $destinationName, null);
// do something with result:
if (false === $validDestination) {
throw new FireflyException(sprintf('Destination: %s', $this->accountValidator->destError)); // @codeCoverageIgnore
}
/**
* @param TransactionJournal $journal
* @param NullArrayObject $data
* @param string $field
*/
protected function storeMeta(TransactionJournal $journal, NullArrayObject $data, string $field): void
{
$set = [
'journal' => $journal,
'name' => $field,
'data' => (string)($data[$field] ?? ''),
];
Log::debug(sprintf('Going to store meta-field "%s", with value "%s".', $set['name'], $set['data']));
/** @var TransactionJournalMetaFactory $factory */
$factory = app(TransactionJournalMetaFactory::class);
$factory->updateOrCreate($set);
}
/**
* @param bool $errorOnHash
*/
public function setErrorOnHash(bool $errorOnHash): void
{
$this->errorOnHash = $errorOnHash;
if (true === $errorOnHash) {
Log::info('Will trigger duplication alert for this journal.');
}
}
/**
* Set the user.
*
* @param User $user
*/
public function setUser(User $user): void
{
$this->user = $user;
$this->currencyRepository->setUser($this->user);
$this->tagFactory->setUser($user);
$this->billRepository->setUser($this->user);
$this->budgetRepository->setUser($this->user);
$this->categoryRepository->setUser($this->user);
$this->piggyRepository->setUser($this->user);
$this->accountRepository->setUser($this->user);
}

View File

@ -60,7 +60,7 @@ class TransactionJournalMetaFactory
Log::debug('Is a carbon object.');
$value = $data['data']->toW3cString();
}
if ('' === (string) $value) {
if ('' === (string)$value) {
Log::debug('Is an empty string.');
// don't store blank strings.
if (null !== $entry) {

View File

@ -26,7 +26,6 @@ declare(strict_types=1);
namespace FireflyIII\Factory;
use FireflyIII\Models\TransactionType;
use Log;
/**
* Class TransactionTypeFactory

View File

@ -23,7 +23,6 @@ declare(strict_types=1);
namespace FireflyIII\Generator\Chart\Basic;
use FireflyIII\Support\ChartColour;
use Log;
/**
* Class ChartJsGenerator.
@ -51,7 +50,7 @@ class ChartJsGenerator implements GeneratorInterface
$amounts = array_column($data, 'amount');
$next = next($amounts);
$sortFlag = SORT_ASC;
if (!is_bool($next) && 1 === bccomp((string) $next, '0')) {
if (!is_bool($next) && 1 === bccomp((string)$next, '0')) {
$sortFlag = SORT_DESC;
}
array_multisort($amounts, $sortFlag, $data);
@ -60,7 +59,7 @@ class ChartJsGenerator implements GeneratorInterface
$index = 0;
foreach ($data as $key => $valueArray) {
// make larger than 0
$chartData['datasets'][0]['data'][] = (float) app('steam')->positive((string) $valueArray['amount']);
$chartData['datasets'][0]['data'][] = (float)app('steam')->positive((string)$valueArray['amount']);
$chartData['datasets'][0]['backgroundColor'][] = ChartColour::getColour($index);
$chartData['datasets'][0]['currency_symbol'][] = $valueArray['currency_symbol'];
$chartData['labels'][] = $key;
@ -166,7 +165,7 @@ class ChartJsGenerator implements GeneratorInterface
// different sort when values are positive and when they're negative.
asort($data);
$next = next($data);
if (!is_bool($next) && 1 === bccomp((string) $next, '0')) {
if (!is_bool($next) && 1 === bccomp((string)$next, '0')) {
// next is positive, sort other way around.
arsort($data);
}
@ -175,7 +174,7 @@ class ChartJsGenerator implements GeneratorInterface
$index = 0;
foreach ($data as $key => $value) {
// make larger than 0
$chartData['datasets'][0]['data'][] = (float) app('steam')->positive((string) $value);
$chartData['datasets'][0]['data'][] = (float)app('steam')->positive((string)$value);
$chartData['datasets'][0]['backgroundColor'][] = ChartColour::getColour($index);
$chartData['labels'][] = $key;

View File

@ -48,9 +48,9 @@ class MonthReportGenerator implements ReportGeneratorInterface
/**
* Generates the report.
*
* @return string
* @throws FireflyException
* @codeCoverageIgnore
* @return string
*/
public function generate(): string
{
@ -91,78 +91,6 @@ class MonthReportGenerator implements ReportGeneratorInterface
return $result;
}
/**
* Get the audit report.
*
* @param Account $account
* @param Carbon $date
*
* @throws FireflyException
* @return array
*
*/
public function getAuditReport(Account $account, Carbon $date): array
{
/** @var AccountRepositoryInterface $accountRepository */
$accountRepository = app(AccountRepositoryInterface::class);
$accountRepository->setUser($account->user);
/** @var JournalRepositoryInterface $journalRepository */
$journalRepository = app(JournalRepositoryInterface::class);
$journalRepository->setUser($account->user);
/** @var GroupCollectorInterface $collector */
$collector = app(GroupCollectorInterface::class);
$collector->setAccounts(new Collection([$account]))->setRange($this->start, $this->end)->withAccountInformation()
->withBudgetInformation()->withCategoryInformation()->withBillInformation();
$journals = $collector->getExtractedJournals();
$journals = array_reverse($journals, true);
$dayBeforeBalance = app('steam')->balance($account, $date);
$startBalance = $dayBeforeBalance;
$defaultCurrency = app('amount')->getDefaultCurrencyByUser($account->user);
$currency = $accountRepository->getAccountCurrency($account) ?? $defaultCurrency;
foreach ($journals as $index => $journal) {
$journals[$index]['balance_before'] = $startBalance;
$transactionAmount = $journal['amount'];
// make sure amount is in the right "direction".
if ($account->id === $journal['destination_account_id']) {
$transactionAmount = app('steam')->positive($journal['amount']);
}
if ($currency->id === $journal['foreign_currency_id']) {
$transactionAmount = $journal['foreign_amount'];
if ($account->id === $journal['destination_account_id']) {
$transactionAmount = app('steam')->positive($journal['foreign_amount']);
}
}
$newBalance = bcadd($startBalance, $transactionAmount);
$journals[$index]['balance_after'] = $newBalance;
$startBalance = $newBalance;
// add meta dates for each journal.
$journals[$index]['interest_date'] = $journalRepository->getMetaDateById($journal['transaction_journal_id'], 'interest_date');
$journals[$index]['book_date'] = $journalRepository->getMetaDateById($journal['transaction_journal_id'], 'book_date');
$journals[$index]['process_date'] = $journalRepository->getMetaDateById($journal['transaction_journal_id'], 'process_date');
$journals[$index]['due_date'] = $journalRepository->getMetaDateById($journal['transaction_journal_id'], 'due_date');
$journals[$index]['payment_date'] = $journalRepository->getMetaDateById($journal['transaction_journal_id'], 'payment_date');
$journals[$index]['invoice_date'] = $journalRepository->getMetaDateById($journal['transaction_journal_id'], 'invoice_date');
}
$locale = app('steam')->getLocale();
return [
'journals' => $journals,
'currency' => $currency,
'exists' => !empty($journals),
'end' => $this->end->formatLocalized((string) trans('config.month_and_day', [], $locale)),
'endBalance' => app('steam')->balance($account, $this->end),
'dayBefore' => $date->formatLocalized((string) trans('config.month_and_day', [], $locale)),
'dayBeforeBalance' => $dayBeforeBalance,
];
}
/**
* Account collection setter.
*
@ -260,4 +188,77 @@ class MonthReportGenerator implements ReportGeneratorInterface
{
return $this;
}
/**
* Get the audit report.
*
* @param Account $account
* @param Carbon $date
*
* @return array
*
* @throws FireflyException
*/
public function getAuditReport(Account $account, Carbon $date): array
{
/** @var AccountRepositoryInterface $accountRepository */
$accountRepository = app(AccountRepositoryInterface::class);
$accountRepository->setUser($account->user);
/** @var JournalRepositoryInterface $journalRepository */
$journalRepository = app(JournalRepositoryInterface::class);
$journalRepository->setUser($account->user);
/** @var GroupCollectorInterface $collector */
$collector = app(GroupCollectorInterface::class);
$collector->setAccounts(new Collection([$account]))->setRange($this->start, $this->end)->withAccountInformation()
->withBudgetInformation()->withCategoryInformation()->withBillInformation();
$journals = $collector->getExtractedJournals();
$journals = array_reverse($journals, true);
$dayBeforeBalance = app('steam')->balance($account, $date);
$startBalance = $dayBeforeBalance;
$defaultCurrency = app('amount')->getDefaultCurrencyByUser($account->user);
$currency = $accountRepository->getAccountCurrency($account) ?? $defaultCurrency;
foreach ($journals as $index => $journal) {
$journals[$index]['balance_before'] = $startBalance;
$transactionAmount = $journal['amount'];
// make sure amount is in the right "direction".
if ($account->id === $journal['destination_account_id']) {
$transactionAmount = app('steam')->positive($journal['amount']);
}
if ($currency->id === $journal['foreign_currency_id']) {
$transactionAmount = $journal['foreign_amount'];
if ($account->id === $journal['destination_account_id']) {
$transactionAmount = app('steam')->positive($journal['foreign_amount']);
}
}
$newBalance = bcadd($startBalance, $transactionAmount);
$journals[$index]['balance_after'] = $newBalance;
$startBalance = $newBalance;
// add meta dates for each journal.
$journals[$index]['interest_date'] = $journalRepository->getMetaDateById($journal['transaction_journal_id'], 'interest_date');
$journals[$index]['book_date'] = $journalRepository->getMetaDateById($journal['transaction_journal_id'], 'book_date');
$journals[$index]['process_date'] = $journalRepository->getMetaDateById($journal['transaction_journal_id'], 'process_date');
$journals[$index]['due_date'] = $journalRepository->getMetaDateById($journal['transaction_journal_id'], 'due_date');
$journals[$index]['payment_date'] = $journalRepository->getMetaDateById($journal['transaction_journal_id'], 'payment_date');
$journals[$index]['invoice_date'] = $journalRepository->getMetaDateById($journal['transaction_journal_id'], 'invoice_date');
}
$locale = app('steam')->getLocale();
return [
'journals' => $journals,
'currency' => $currency,
'exists' => !empty($journals),
'end' => $this->end->formatLocalized((string)trans('config.month_and_day', [], $locale)),
'endBalance' => app('steam')->balance($account, $this->end),
'dayBefore' => $date->formatLocalized((string)trans('config.month_and_day', [], $locale)),
'dayBeforeBalance' => $dayBeforeBalance,
];
}
}

View File

@ -76,7 +76,7 @@ class MonthReportGenerator implements ReportGeneratorInterface
// render!
try {
return view('reports.category.month', compact('accountIds', 'categoryIds', 'reportType', ))
return view('reports.category.month', compact('accountIds', 'categoryIds', 'reportType',))
->with('start', $this->start)->with('end', $this->end)
->with('categories', $this->categories)
->with('accounts', $this->accounts)

Some files were not shown because too many files have changed in this diff Show More