Skip to content

Firefly III: a personal finances manager

Code rearrangement.

James Colef3fff6f1c506
diff --git a/app/Console/Commands/UpgradeFireflyInstructions.php b/app/Console/Commands/UpgradeFireflyInstructions.php
index 4fe2ddea56..a61ffaee7b 100644
--- a/app/Console/Commands/UpgradeFireflyInstructions.php
+++ b/app/Console/Commands/UpgradeFireflyInstructions.php
@@ -13,18 +13,17 @@ use Illuminate\Console\Command;
class UpgradeFireflyInstructions extends Command
{
/**
- * The name and signature of the console command.
+ * The console command description.
*
* @var string
*/
- protected $signature = 'firefly:upgrade-instructions';
-
+ protected $description = 'Command description';
/**
- * The console command description.
+ * The name and signature of the console command.
*
* @var string
*/
- protected $description = 'Command description';
+ protected $signature = 'firefly:upgrade-instructions';
/**
* Create a new command instance.
diff --git a/app/Console/Kernel.php b/app/Console/Kernel.php
index 386fd469c7..88960c8a36 100755
--- a/app/Console/Kernel.php
+++ b/app/Console/Kernel.php
@@ -27,7 +27,7 @@ class Kernel extends ConsoleKernel
*/
protected $commands
= [
- UpgradeFireflyInstructions::class
+ UpgradeFireflyInstructions::class,
];
/**
diff --git a/app/Generator/Chart/Account/AccountChartGenerator.php b/app/Generator/Chart/Account/AccountChartGenerator.php
index 5969d86178..5601e86306 100644
--- a/app/Generator/Chart/Account/AccountChartGenerator.php
+++ b/app/Generator/Chart/Account/AccountChartGenerator.php
@@ -21,23 +21,23 @@ interface AccountChartGenerator
*
* @return array
*/
- public function frontpage(Collection $accounts, Carbon $start, Carbon $end);
+ public function expenseAccounts(Collection $accounts, Carbon $start, Carbon $end);
/**
- * @param Account $account
- * @param Carbon $start
- * @param Carbon $end
+ * @param Collection $accounts
+ * @param Carbon $start
+ * @param Carbon $end
*
* @return array
*/
- public function single(Account $account, Carbon $start, Carbon $end);
+ public function frontpage(Collection $accounts, Carbon $start, Carbon $end);
/**
- * @param Collection $accounts
- * @param Carbon $start
- * @param Carbon $end
+ * @param Account $account
+ * @param Carbon $start
+ * @param Carbon $end
*
* @return array
*/
- public function expenseAccounts(Collection $accounts, Carbon $start, Carbon $end);
+ public function single(Account $account, Carbon $start, Carbon $end);
}
diff --git a/app/Generator/Chart/Account/ChartJsAccountChartGenerator.php b/app/Generator/Chart/Account/ChartJsAccountChartGenerator.php
index ef53c4b7bd..b9807954c5 100644
--- a/app/Generator/Chart/Account/ChartJsAccountChartGenerator.php
+++ b/app/Generator/Chart/Account/ChartJsAccountChartGenerator.php
@@ -62,22 +62,6 @@ class ChartJsAccountChartGenerator implements AccountChartGenerator
return $data;
}
- /**
- * @param $array
- * @param $entryId
- *
- * @return string
- */
- protected function isInArray($array, $entryId)
- {
- if (isset($array[$entryId])) {
- return $array[$entryId];
- }
-
- return '0';
- }
-
-
/**
* @param Collection $accounts
* @param Carbon $start
@@ -179,4 +163,19 @@ class ChartJsAccountChartGenerator implements AccountChartGenerator
return array_unique($ids);
}
+
+ /**
+ * @param $array
+ * @param $entryId
+ *
+ * @return string
+ */
+ protected function isInArray($array, $entryId)
+ {
+ if (isset($array[$entryId])) {
+ return $array[$entryId];
+ }
+
+ return '0';
+ }
}
diff --git a/app/Generator/Chart/Budget/ChartJsBudgetChartGenerator.php b/app/Generator/Chart/Budget/ChartJsBudgetChartGenerator.php
index fa25cd857b..65db28db6b 100644
--- a/app/Generator/Chart/Budget/ChartJsBudgetChartGenerator.php
+++ b/app/Generator/Chart/Budget/ChartJsBudgetChartGenerator.php
@@ -107,71 +107,71 @@ class ChartJsBudgetChartGenerator implements BudgetChartGenerator
}
/**
- * @param Collection $budgets
* @param Collection $entries
*
* @return array
*/
- public function year(Collection $budgets, Collection $entries)
+ public function multiYear(Collection $entries)
{
- // language:
- $format = trans('config.month');
-
+ // dataset:
$data = [
+ 'count' => 0,
'labels' => [],
'datasets' => [],
];
-
- foreach ($budgets as $budget) {
- $data['labels'][] = $budget->name;
+ // get labels from one of the budgets (assuming there's at least one):
+ $first = $entries->first();
+ $keys = array_keys($first['budgeted']);
+ foreach ($keys as $year) {
+ $data['labels'][] = strval($year);
}
- /** @var array $entry */
- foreach ($entries as $entry) {
- $array = [
- 'label' => $entry[0]->formatLocalized($format),
- 'data' => [],
- ];
- array_shift($entry);
- $array['data'] = $entry;
- $data['datasets'][] = $array;
+ // then, loop all entries and create datasets:
+ foreach ($entries as $entry) {
+ $name = $entry['name'];
+ $spent = $entry['spent'];
+ $budgeted = $entry['budgeted'];
+ $data['datasets'][] = ['label' => 'Spent on ' . $name, 'data' => array_values($spent)];
+ $data['datasets'][] = ['label' => 'Budgeted for ' . $name, 'data' => array_values($budgeted)];
}
$data['count'] = count($data['datasets']);
return $data;
+
}
/**
+ * @param Collection $budgets
* @param Collection $entries
*
* @return array
*/
- public function multiYear(Collection $entries)
+ public function year(Collection $budgets, Collection $entries)
{
- // dataset:
+ // language:
+ $format = trans('config.month');
+
$data = [
- 'count' => 0,
'labels' => [],
'datasets' => [],
];
- // get labels from one of the budgets (assuming there's at least one):
- $first = $entries->first();
- $keys = array_keys($first['budgeted']);
- foreach ($keys as $year) {
- $data['labels'][] = strval($year);
- }
- // then, loop all entries and create datasets:
+ foreach ($budgets as $budget) {
+ $data['labels'][] = $budget->name;
+ }
+ /** @var array $entry */
foreach ($entries as $entry) {
- $name = $entry['name'];
- $spent = $entry['spent'];
- $budgeted = $entry['budgeted'];
- $data['datasets'][] = ['label' => 'Spent on ' . $name, 'data' => array_values($spent)];
- $data['datasets'][] = ['label' => 'Budgeted for ' . $name, 'data' => array_values($budgeted)];
+ $array = [
+ 'label' => $entry[0]->formatLocalized($format),
+ 'data' => [],
+ ];
+ array_shift($entry);
+ $array['data'] = $entry;
+ $data['datasets'][] = $array;
+
}
$data['count'] = count($data['datasets']);
return $data;
-
}
}
diff --git a/app/Helpers/Attachments/AttachmentHelper.php b/app/Helpers/Attachments/AttachmentHelper.php
index 981a1a0a8a..692287d0f7 100644
--- a/app/Helpers/Attachments/AttachmentHelper.php
+++ b/app/Helpers/Attachments/AttachmentHelper.php
@@ -19,14 +19,14 @@ use Symfony\Component\HttpFoundation\File\UploadedFile;
class AttachmentHelper implements AttachmentHelperInterface
{
- /** @var int */
- protected $maxUploadSize;
- /** @var array */
- protected $allowedMimes;
/** @var MessageBag */
public $errors;
/** @var MessageBag */
public $messages;
+ /** @var array */
+ protected $allowedMimes;
+ /** @var int */
+ protected $maxUploadSize;
/**
*
@@ -51,6 +51,22 @@ class AttachmentHelper implements AttachmentHelperInterface
return $path;
}
+ /**
+ * @return MessageBag
+ */
+ public function getErrors()
+ {
+ return $this->errors;
+ }
+
+ /**
+ * @return MessageBag
+ */
+ public function getMessages()
+ {
+ return $this->messages;
+ }
+
/**
* @param Model $model
*
@@ -98,27 +114,6 @@ class AttachmentHelper implements AttachmentHelperInterface
return false;
}
- /**
- * @param UploadedFile $file
- * @param Model $model
- *
- * @return bool
- */
- protected function validateUpload(UploadedFile $file, Model $model)
- {
- if (!$this->validMime($file)) {
- return false;
- }
- if (!$this->validSize($file)) {
- return false;
- }
- if ($this->hasFile($file, $model)) {
- return false;
- }
-
- return true;
- }
-
/**
* @param UploadedFile $file
* @param Model $model
@@ -205,19 +200,24 @@ class AttachmentHelper implements AttachmentHelperInterface
}
/**
- * @return MessageBag
+ * @param UploadedFile $file
+ * @param Model $model
+ *
+ * @return bool
*/
- public function getErrors()
+ protected function validateUpload(UploadedFile $file, Model $model)
{
- return $this->errors;
- }
+ if (!$this->validMime($file)) {
+ return false;
+ }
+ if (!$this->validSize($file)) {
+ return false;
+ }
+ if ($this->hasFile($file, $model)) {
+ return false;
+ }
- /**
- * @return MessageBag
- */
- public function getMessages()
- {
- return $this->messages;
+ return true;
}
diff --git a/app/Helpers/Attachments/AttachmentHelperInterface.php b/app/Helpers/Attachments/AttachmentHelperInterface.php
index f25971a173..bcc36a642f 100644
--- a/app/Helpers/Attachments/AttachmentHelperInterface.php
+++ b/app/Helpers/Attachments/AttachmentHelperInterface.php
@@ -15,11 +15,11 @@ interface AttachmentHelperInterface
{
/**
- * @param Model $model
+ * @param Attachment $attachment
*
- * @return bool
+ * @return mixed
*/
- public function saveAttachmentsForModel(Model $model);
+ public function getAttachmentLocation(Attachment $attachment);
/**
* @return MessageBag
@@ -32,10 +32,10 @@ interface AttachmentHelperInterface
public function getMessages();
/**
- * @param Attachment $attachment
+ * @param Model $model
*
- * @return mixed
+ * @return bool
*/
- public function getAttachmentLocation(Attachment $attachment);
+ public function saveAttachmentsForModel(Model $model);
}
diff --git a/app/Helpers/Csv/Data.php b/app/Helpers/Csv/Data.php
index 2d6388792b..72593ce30f 100644
--- a/app/Helpers/Csv/Data.php
+++ b/app/Helpers/Csv/Data.php
@@ -15,37 +15,27 @@ class Data
/** @var string */
protected $csvFileContent;
-
- /** @var string */
- protected $delimiter;
-
/** @var string */
protected $csvFileLocation;
-
/** @var string */
protected $dateFormat;
-
+ /** @var string */
+ protected $delimiter;
/** @var bool */
protected $hasHeaders;
-
+ /** @var int */
+ protected $importAccount = 0;
/** @var array */
protected $map = [];
-
/** @var array */
protected $mapped = [];
-
/** @var Reader */
protected $reader;
-
/** @var array */
protected $roles = [];
-
/** @var array */
protected $specifix = [];
- /** @var int */
- protected $importAccount = 0;
-
/**
*/
public function __construct()
@@ -61,67 +51,41 @@ class Data
$this->sessionDelimiter();
}
- protected function sessionHasHeaders()
- {
- if (Session::has('csv-has-headers')) {
- $this->hasHeaders = (bool)Session::get('csv-has-headers');
- }
- }
-
- protected function sessionImportAccount()
- {
- if (Session::has('csv-import-account')) {
- $this->importAccount = intval(Session::get('csv-import-account'));
- }
- }
-
- protected function sessionDateFormat()
- {
- if (Session::has('csv-date-format')) {
- $this->dateFormat = (string)Session::get('csv-date-format');
- }
- }
-
- protected function sessionCsvFileLocation()
- {
- if (Session::has('csv-file')) {
- $this->csvFileLocation = (string)Session::get('csv-file');
- }
- }
-
- protected function sessionMap()
- {
- if (Session::has('csv-map')) {
- $this->map = (array)Session::get('csv-map');
- }
- }
-
- protected function sessionRoles()
+ /**
+ *
+ * @return string
+ */
+ public function getCsvFileContent()
{
- if (Session::has('csv-roles')) {
- $this->roles = (array)Session::get('csv-roles');
- }
+ return $this->csvFileContent;
}
- protected function sessionMapped()
+ /**
+ *
+ * @param string $csvFileContent
+ */
+ public function setCsvFileContent($csvFileContent)
{
- if (Session::has('csv-mapped')) {
- $this->mapped = (array)Session::get('csv-mapped');
- }
+ $this->csvFileContent = $csvFileContent;
}
- protected function sessionSpecifix()
+ /**
+ *
+ * @return string
+ */
+ public function getCsvFileLocation()
{
- if (Session::has('csv-specifix')) {
- $this->specifix = (array)Session::get('csv-specifix');
- }
+ return $this->csvFileLocation;
}
- protected function sessionDelimiter()
+ /**
+ *
+ * @param string $csvFileLocation
+ */
+ public function setCsvFileLocation($csvFileLocation)
{
- if (Session::has('csv-delimiter')) {
- $this->delimiter = Session::get('csv-delimiter');
- }
+ Session::put('csv-file', $csvFileLocation);
+ $this->csvFileLocation = $csvFileLocation;
}
/**
@@ -145,31 +109,21 @@ class Data
/**
*
- * @param int $importAccount
- */
- public function setImportAccount($importAccount)
- {
- Session::put('csv-import-account', $importAccount);
- $this->importAccount = $importAccount;
- }
-
- /**
- *
- * @return bool
+ * @return string
*/
- public function hasHeaders()
+ public function getDelimiter()
{
- return $this->hasHeaders;
+ return $this->delimiter;
}
/**
*
- * @param bool $hasHeaders
+ * @param string $delimiter
*/
- public function setHasHeaders($hasHeaders)
+ public function setDelimiter($delimiter)
{
- Session::put('csv-has-headers', $hasHeaders);
- $this->hasHeaders = $hasHeaders;
+ Session::put('csv-delimiter', $delimiter);
+ $this->delimiter = $delimiter;
}
/**
@@ -228,105 +182,141 @@ class Data
return $this->reader;
}
- protected function loadCsvFile()
- {
- $file = $this->getCsvFileLocation();
- $content = file_get_contents($file);
- $contentDecrypted = Crypt::decrypt($content);
- $this->setCsvFileContent($contentDecrypted);
- }
-
/**
*
- * @return string
+ * @return array
*/
- public function getCsvFileLocation()
+ public function getRoles()
{
- return $this->csvFileLocation;
+ return $this->roles;
}
/**
*
- * @param string $csvFileLocation
+ * @param array $roles
*/
- public function setCsvFileLocation($csvFileLocation)
+ public function setRoles(array $roles)
{
- Session::put('csv-file', $csvFileLocation);
- $this->csvFileLocation = $csvFileLocation;
+ Session::put('csv-roles', $roles);
+ $this->roles = $roles;
}
/**
*
- * @return string
+ * @return array
*/
- public function getCsvFileContent()
+ public function getSpecifix()
{
- return $this->csvFileContent;
+ return is_array($this->specifix) ? $this->specifix : [];
}
/**
*
- * @param string $csvFileContent
+ * @param array $specifix
*/
- public function setCsvFileContent($csvFileContent)
+ public function setSpecifix($specifix)
{
- $this->csvFileContent = $csvFileContent;
+ Session::put('csv-specifix', $specifix);
+ $this->specifix = $specifix;
}
/**
*
- * @return array
+ * @return bool
*/
- public function getRoles()
+ public function hasHeaders()
{
- return $this->roles;
+ return $this->hasHeaders;
}
/**
*
- * @param array $roles
+ * @param bool $hasHeaders
*/
- public function setRoles(array $roles)
+ public function setHasHeaders($hasHeaders)
{
- Session::put('csv-roles', $roles);
- $this->roles = $roles;
+ Session::put('csv-has-headers', $hasHeaders);
+ $this->hasHeaders = $hasHeaders;
}
/**
*
- * @return array
+ * @param int $importAccount
*/
- public function getSpecifix()
+ public function setImportAccount($importAccount)
{
- return is_array($this->specifix) ? $this->specifix : [];
+ Session::put('csv-import-account', $importAccount);
+ $this->importAccount = $importAccount;
}
- /**
- *
- * @param array $specifix
- */
- public function setSpecifix($specifix)
+ protected function loadCsvFile()
{
- Session::put('csv-specifix', $specifix);
- $this->specifix = $specifix;
+ $file = $this->getCsvFileLocation();
+ $content = file_get_contents($file);
+ $contentDecrypted = Crypt::decrypt($content);
+ $this->setCsvFileContent($contentDecrypted);
}
- /**
- *
- * @return string
- */
- public function getDelimiter()
+ protected function sessionCsvFileLocation()
{
- return $this->delimiter;
+ if (Session::has('csv-file')) {
+ $this->csvFileLocation = (string)Session::get('csv-file');
+ }
}
- /**
- *
- * @param string $delimiter
- */
- public function setDelimiter($delimiter)
+ protected function sessionDateFormat()
{
- Session::put('csv-delimiter', $delimiter);
- $this->delimiter = $delimiter;
+ if (Session::has('csv-date-format')) {
+ $this->dateFormat = (string)Session::get('csv-date-format');
+ }
+ }
+
+ protected function sessionDelimiter()
+ {
+ if (Session::has('csv-delimiter')) {
+ $this->delimiter = Session::get('csv-delimiter');
+ }
+ }
+
+ protected function sessionHasHeaders()
+ {
+ if (Session::has('csv-has-headers')) {
+ $this->hasHeaders = (bool)Session::get('csv-has-headers');
+ }
+ }
+
+ protected function sessionImportAccount()
+ {
+ if (Session::has('csv-import-account')) {
+ $this->importAccount = intval(Session::get('csv-import-account'));
+ }
+ }
+
+ protected function sessionMap()
+ {
+ if (Session::has('csv-map')) {
+ $this->map = (array)Session::get('csv-map');
+ }
+ }
+
+ protected function sessionMapped()
+ {
+ if (Session::has('csv-mapped')) {
+ $this->mapped = (array)Session::get('csv-mapped');
+ }
+ }
+
+ protected function sessionRoles()
+ {
+ if (Session::has('csv-roles')) {
+ $this->roles = (array)Session::get('csv-roles');
+ }
+ }
+
+ protected function sessionSpecifix()
+ {
+ if (Session::has('csv-specifix')) {
+ $this->specifix = (array)Session::get('csv-specifix');
+ }
}
}
diff --git a/app/Helpers/Csv/Importer.php b/app/Helpers/Csv/Importer.php
index 936cee2956..2aa4274b26 100644
--- a/app/Helpers/Csv/Importer.php
+++ b/app/Helpers/Csv/Importer.php
@@ -34,6 +34,8 @@ class Importer
protected $importRow;
/** @var int */
protected $imported = 0;
+ /** @var Collection */
+ protected $journals;
/** @var array */
protected $map;
/** @var array */
@@ -45,9 +47,6 @@ class Importer
/** @var array */
protected $specifix = [];
- /** @var Collection */
- protected $journals;
-
/**
* Used by CsvController.
*
@@ -68,6 +67,14 @@ class Importer
return $this->imported;
}
+ /**
+ * @return Collection
+ */
+ public function getJournals()
+ {
+ return $this->journals;
+ }
+
/**
* Used by CsvController
*
@@ -79,14 +86,13 @@ class Importer
}
/**
- * @return Collection
+ * @return array
*/
- public function getJournals()
+ public function getSpecifix()
{
- return $this->journals;
+ return is_array($this->specifix) ? $this->specifix : [];
}
-
/**
* @throws FireflyException
*/
@@ -118,13 +124,109 @@ class Importer
}
/**
- * @param int $index
+ * @param Data $data
+ */
+ public function setData($data)
+ {
+ $this->data = $data;
+ }
+
+ /**
*
- * @return bool
+ * @return TransactionJournal|string
*/
- protected function parseRow($index)
+ protected function createTransactionJournal()
{
- return (($this->data->hasHeaders() && $index >= 1) || !$this->data->hasHeaders());
+ bcscale(2);
+ $date = $this->importData['date'];
+ if (is_null($this->importData['date'])) {
+ $date = $this->importData['date-rent'];
+ }
+
+
+ $transactionType = $this->getTransactionType(); // defaults to deposit
+ $errors = new MessageBag;
+ $journal = TransactionJournal::create(
+ ['user_id' => Auth::user()->id, 'transaction_type_id' => $transactionType->id, 'transaction_currency_id' => $this->importData['currency']->id,
+ 'description' => $this->importData['description'], 'completed' => 0, 'date' => $date, 'bill_id' => $this->importData['bill-id'],]
+ );
+ if ($journal->getErrors()->count() == 0) {
+ // first transaction
+ $accountId = $this->importData['asset-account-object']->id; // create first transaction:
+ $amount = $this->importData['amount'];
+ $transaction = Transaction::create(['transaction_journal_id' => $journal->id, 'account_id' => $accountId, 'amount' => $amount]);
+ $errors = $transaction->getErrors();
+
+ // second transaction
+ $accountId = $this->importData['opposing-account-object']->id; // create second transaction:
+ $amount = bcmul($this->importData['amount'], -1);
+ $transaction = Transaction::create(['transaction_journal_id' => $journal->id, 'account_id' => $accountId, 'amount' => $amount]);
+ $errors = $transaction->getErrors()->merge($errors);
+ }
+ if ($errors->count() == 0) {
+ $journal->completed = 1;
+ $journal->save();
+ } else {
+ $text = join(',', $errors->all());
+
+ return $text;
+ }
+ $this->saveBudget($journal);
+ $this->saveCategory($journal);
+ $this->saveTags($journal);
+
+ // some debug info:
+ $journalId = $journal->id;
+ $type = $journal->getTransactionType();
+ /** @var Account $asset */
+ $asset = $this->importData['asset-account-object'];
+ /** @var Account $opposing */
+ $opposing = $this->importData['opposing-account-object'];
+
+ Log::info('Created journal #' . $journalId . ' of type ' . $type . '!');
+ Log::info('Asset account ****** (#' . $asset->id . ') lost/gained: ' . $this->importData['amount']);
+ Log::info($opposing->accountType->type . ' ****** (#' . $opposing->id . ') lost/gained: ' . bcmul($this->importData['amount'], -1));
+
+ return $journal;
+ }
+
+ /**
+ * @return array
+ */
+ protected function getFiller()
+ {
+ $filler = [];
+ foreach (Config::get('csv.roles') as $role) {
+ if (isset($role['field'])) {
+ $fieldName = $role['field'];
+ $filler[$fieldName] = null;
+ }
+ }
+ // some extra's:
+ $filler['bill-id'] = null;
+ $filler['opposing-account-object'] = null;
+ $filler['asset-account-object'] = null;
+ $filler['amount-modifier'] = '1';
+
+ return $filler;
+
+ }
+
+ /**
+ * @return TransactionType
+ */
+ protected function getTransactionType()
+ {
+ $transactionType = TransactionType::where('type', TransactionType::DEPOSIT)->first();
+ if ($this->importData['amount'] < 0) {
+ $transactionType = TransactionType::where('type', TransactionType::WITHDRAWAL)->first();
+ }
+
+ if (in_array($this->importData['opposing-account-object']->accountType->type, ['Asset account', 'Default account'])) {
+ $transactionType = TransactionType::where('type', TransactionType::TRANSFER)->first();
+ }
+
+ return $transactionType;
}
/**
@@ -171,25 +273,13 @@ class Importer
}
/**
- * @return array
+ * @param int $index
+ *
+ * @return bool
*/
- protected function getFiller()
+ protected function parseRow($index)
{
- $filler = [];
- foreach (Config::get('csv.roles') as $role) {
- if (isset($role['field'])) {
- $fieldName = $role['field'];
- $filler[$fieldName] = null;
- }
- }
- // some extra's:
- $filler['bill-id'] = null;
- $filler['opposing-account-object'] = null;
- $filler['asset-account-object'] = null;
- $filler['amount-modifier'] = '1';
-
- return $filler;
-
+ return (($this->data->hasHeaders() && $index >= 1) || !$this->data->hasHeaders());
}
/**
@@ -222,110 +312,6 @@ class Importer
}
- /**
- * @return array
- */
- public function getSpecifix()
- {
- return is_array($this->specifix) ? $this->specifix : [];
- }
-
- /**
- *
- * @return bool|string
- */
- protected function validateData()
- {
- if (is_null($this->importData['date']) && is_null($this->importData['date-rent'])) {
- return 'No date value for this row.';
- }
- if (is_null($this->importData['opposing-account-object'])) {
- return 'Opposing account is null';
- }
-
- if (!($this->importData['asset-account-object'] instanceof Account)) {
- return 'No asset account to import into.';
- }
-
- return true;
- }
-
- /**
- *
- * @return TransactionJournal|string
- */
- protected function createTransactionJournal()
- {
- bcscale(2);
- $date = $this->importData['date'];
- if (is_null($this->importData['date'])) {
- $date = $this->importData['date-rent'];
- }
-
-
- $transactionType = $this->getTransactionType(); // defaults to deposit
- $errors = new MessageBag;
- $journal = TransactionJournal::create(
- ['user_id' => Auth::user()->id, 'transaction_type_id' => $transactionType->id, 'transaction_currency_id' => $this->importData['currency']->id,
- 'description' => $this->importData['description'], 'completed' => 0, 'date' => $date, 'bill_id' => $this->importData['bill-id'],]
- );
- if ($journal->getErrors()->count() == 0) {
- // first transaction
- $accountId = $this->importData['asset-account-object']->id; // create first transaction:
- $amount = $this->importData['amount'];
- $transaction = Transaction::create(['transaction_journal_id' => $journal->id, 'account_id' => $accountId, 'amount' => $amount]);
- $errors = $transaction->getErrors();
-
- // second transaction
- $accountId = $this->importData['opposing-account-object']->id; // create second transaction:
- $amount = bcmul($this->importData['amount'], -1);
- $transaction = Transaction::create(['transaction_journal_id' => $journal->id, 'account_id' => $accountId, 'amount' => $amount]);
- $errors = $transaction->getErrors()->merge($errors);
- }
- if ($errors->count() == 0) {
- $journal->completed = 1;
- $journal->save();
- } else {
- $text = join(',', $errors->all());
-
- return $text;
- }
- $this->saveBudget($journal);
- $this->saveCategory($journal);
- $this->saveTags($journal);
-
- // some debug info:
- $journalId = $journal->id;
- $type = $journal->getTransactionType();
- /** @var Account $asset */
- $asset = $this->importData['asset-account-object'];
- /** @var Account $opposing */
- $opposing = $this->importData['opposing-account-object'];
-
- Log::info('Created journal #' . $journalId . ' of type ' . $type . '!');
- Log::info('Asset account ****** (#' . $asset->id . ') lost/gained: ' . $this->importData['amount']);
- Log::info($opposing->accountType->type . ' ****** (#' . $opposing->id . ') lost/gained: ' . bcmul($this->importData['amount'], -1));
-
- return $journal;
- }
-
- /**
- * @return TransactionType
- */
- protected function getTransactionType()
- {
- $transactionType = TransactionType::where('type', TransactionType::DEPOSIT)->first();
- if ($this->importData['amount'] < 0) {
- $transactionType = TransactionType::where('type', TransactionType::WITHDRAWAL)->first();
- }
-
- if (in_array($this->importData['opposing-account-object']->accountType->type, ['Asset account', 'Default account'])) {
- $transactionType = TransactionType::where('type', TransactionType::TRANSFER)->first();
- }
-
- return $transactionType;
- }
-
/**
* @param TransactionJournal $journal
*/
@@ -361,11 +347,23 @@ class Importer
}
/**
- * @param Data $data
+ *
+ * @return bool|string
*/
- public function setData($data)
+ protected function validateData()
{
- $this->data = $data;
+ if (is_null($this->importData['date']) && is_null($this->importData['date-rent'])) {
+ return 'No date value for this row.';
+ }
+ if (is_null($this->importData['opposing-account-object'])) {
+ return 'Opposing account is null';
+ }
+
+ if (!($this->importData['asset-account-object'] instanceof Account)) {
+ return 'No asset account to import into.';
+ }
+
+ return true;
}
}
diff --git a/app/Helpers/Csv/Specifix/AbnAmroDescription.php b/app/Helpers/Csv/Specifix/AbnAmroDescription.php
index ecdc75b8bb..b49881e81c 100644
--- a/app/Helpers/Csv/Specifix/AbnAmroDescription.php
+++ b/app/Helpers/Csv/Specifix/AbnAmroDescription.php
@@ -54,8 +54,50 @@ class AbnAmroDescription
$this->row = $row;
}
+ /**
+ * Parses the current description with costs from ABN AMRO itself
+ *
+ * @return boolean true if the description is GEA/BEA-format, false otherwise
+ */
+ protected function parseABNAMRODescription()
+ {
+ // See if the current description is formatted in ABN AMRO format
+ if (preg_match('/ABN AMRO.{24} (.*)/', $this->data['description'], $matches)) {
+ Log::debug('AbnAmroSpecifix: Description is structured as costs from ABN AMRO itself.');
+
+ $this->data['opposing-account-name'] = "ABN AMRO";
+ $this->data['description'] = $matches[1];
+
+ return true;
+ }
+
+ return false;
+ }
+
+ /**
+ * Parses the current description in GEA/BEA format
+ *
+ * @return boolean true if the description is GEA/BEAformat, false otherwise
+ */
+ protected function parseGEABEADescription()
+ {
+ // See if the current description is formatted in GEA/BEA format
+ if (preg_match('/([BG]EA) +(NR:[a-zA-Z:0-9]+) +([0-9.\/]+) +([^,]*)/', $this->data['description'], $matches)) {
+ Log::debug('AbnAmroSpecifix: Description is structured as GEA or BEA format.');
+
+ // description and opposing account will be the same.
+ $this->data['opposing-account-name'] = $matches[4];
+ $this->data['description'] = $matches[4];
+
+ return true;
+ }
+
+ return false;
+ }
+
/**
* Parses the current description in SEPA format
+ *
* @return boolean true if the description is SEPA format, false otherwise
*/
protected function parseSepaDescription()
@@ -94,6 +136,7 @@ class AbnAmroDescription
/**
* Parses the current description in TRTP format
+ *
* @return boolean true if the description is TRTP format, false otherwise
*/
protected function parseTRTPDescription()
@@ -108,9 +151,9 @@ class AbnAmroDescription
switch (strtoupper($key)) {
// is not being used.
-// case 'TRTP':
-// $type = $value;
-// break;
+ // case 'TRTP':
+ // $type = $value;
+ // break;
case 'NAME':
$this->data['opposing-account-name'] = $value;
break;
@@ -131,43 +174,4 @@ class AbnAmroDescription
return false;
}
- /**
- * Parses the current description in GEA/BEA format
- * @return boolean true if the description is GEA/BEAformat, false otherwise
- */
- protected function parseGEABEADescription()
- {
- // See if the current description is formatted in GEA/BEA format
- if (preg_match('/([BG]EA) +(NR:[a-zA-Z:0-9]+) +([0-9.\/]+) +([^,]*)/', $this->data['description'], $matches)) {
- Log::debug('AbnAmroSpecifix: Description is structured as GEA or BEA format.');
-
- // description and opposing account will be the same.
- $this->data['opposing-account-name'] = $matches[4];
- $this->data['description'] = $matches[4];
-
- return true;
- }
-
- return false;
- }
-
- /**
- * Parses the current description with costs from ABN AMRO itself
- * @return boolean true if the description is GEA/BEA-format, false otherwise
- */
- protected function parseABNAMRODescription()
- {
- // See if the current description is formatted in ABN AMRO format
- if (preg_match('/ABN AMRO.{24} (.*)/', $this->data['description'], $matches)) {
- Log::debug('AbnAmroSpecifix: Description is structured as costs from ABN AMRO itself.');
-
- $this->data['opposing-account-name'] = "ABN AMRO";
- $this->data['description'] = $matches[1];
-
- return true;
- }
-
- return false;
- }
-
}
diff --git a/app/Helpers/Csv/Wizard.php b/app/Helpers/Csv/Wizard.php
index 03ed929ce0..bf93c16ec8 100644
--- a/app/Helpers/Csv/Wizard.php
+++ b/app/Helpers/Csv/Wizard.php
@@ -168,17 +168,6 @@ class Wizard implements WizardInterface
}
- /**
- * @param bool $hasHeaders
- * @param int $index
- *
- * @return bool
- */
- protected function useRow($hasHeaders, $index)
- {
- return ($hasHeaders && $index > 1) || !$hasHeaders;
- }
-
/**
* @param array $array
*
@@ -192,4 +181,15 @@ class Wizard implements WizardInterface
return $array;
}
+
+ /**
+ * @param bool $hasHeaders
+ * @param int $index
+ *
+ * @return bool
+ */
+ protected function useRow($hasHeaders, $index)
+ {
+ return ($hasHeaders && $index > 1) || !$hasHeaders;
+ }
}
diff --git a/app/Helpers/Report/ReportHelper.php b/app/Helpers/Report/ReportHelper.php
index 2b13fbe9ae..9cfccfd6f7 100644
--- a/app/Helpers/Report/ReportHelper.php
+++ b/app/Helpers/Report/ReportHelper.php
@@ -35,12 +35,10 @@ use Illuminate\Support\Collection;
class ReportHelper implements ReportHelperInterface
{
- /** @var ReportQueryInterface */
- protected $query;
-
/** @var BudgetRepositoryInterface */
protected $budgetRepository;
-
+ /** @var ReportQueryInterface */
+ protected $query;
/** @var TagRepositoryInterface */
protected $tagRepository;
@@ -60,68 +58,6 @@ class ReportHelper implements ReportHelperInterface
$this->tagRepository = $tagRepository;
}
- /**
- * @param Carbon $start
- * @param Carbon $end
- * @param Collection $accounts
- *
- * @return CategoryCollection
- */
- public function getCategoryReport(Carbon $start, Carbon $end, Collection $accounts)
- {
- $object = new CategoryCollection;
-
- /**
- * GET CATEGORIES:
- */
- /** @var \FireflyIII\Repositories\Category\CategoryRepositoryInterface $repository */
- $repository = app('FireflyIII\Repositories\Category\CategoryRepositoryInterface');
-
- $set = $repository->spentForAccountsPerMonth($accounts, $start, $end);
- foreach ($set as $category) {
- $object->addCategory($category);
- }
-
- return $object;
- }
-
- /**
- * @param Carbon $date
- *
- * @return array
- */
- public function listOfMonths(Carbon $date)
- {
-
- $start = clone $date;
- $end = Carbon::now();
- $months = [];
- while ($start <= $end) {
- $year = $start->year;
-
- if (!isset($months[$year])) {
- $months[$year] = [
- 'start' => Carbon::createFromDate($year, 1, 1)->format('Y-m-d'),
- 'end' => Carbon::createFromDate($year, 12, 31)->format('Y-m-d'),
- 'months' => [],
- ];
- }
-
- $currentEnd = clone $start;
- $currentEnd->endOfMonth();
- $months[$year]['months'][] = [
- 'formatted' => $start->formatLocalized('%B %Y'),
- 'start' => $start->format('Y-m-d'),
- 'end' => $currentEnd->format('Y-m-d'),
- 'month' => $start->month,
- 'year' => $year,
- ];
- $start->addMonth();
- }
-
- return $months;
- }
-
/**
* This method generates a full report for the given period on all
* given accounts
@@ -211,47 +147,86 @@ class ReportHelper implements ReportHelperInterface
}
/**
- * Get a full report on the users incomes during the period for the given accounts.
- *
* @param Carbon $start
* @param Carbon $end
* @param Collection $accounts
*
- * @return Income
+ * @return Balance
*/
- public function getIncomeReport($start, $end, Collection $accounts)
+ public function getBalanceReport(Carbon $start, Carbon $end, Collection $accounts)
{
- $object = new Income;
- $set = $this->query->income($accounts, $start, $end);
+ $balance = new Balance;
- foreach ($set as $entry) {
- $object->addToTotal($entry->journalAmount);
- $object->addOrCreateIncome($entry);
+ // build a balance header:
+ $header = new BalanceHeader;
+ $budgets = $this->budgetRepository->getBudgetsAndLimitsInRange($start, $end);
+ $spentData = $this->budgetRepository->spentPerBudgetPerAccount($budgets, $accounts, $start, $end);
+ foreach ($accounts as $account) {
+ $header->addAccount($account);
}
- return $object;
+ /** @var BudgetModel $budget */
+ foreach ($budgets as $budget) {
+ $balance->addBalanceLine($this->createBalanceLine($budget, $accounts, $spentData));
+ }
+
+ $balance->addBalanceLine($this->createEmptyBalanceLine($accounts, $spentData));
+ $balance->addBalanceLine($this->createTagsBalanceLine($accounts, $start, $end));
+ $balance->addBalanceLine($this->createDifferenceBalanceLine($accounts, $spentData, $start, $end));
+
+ $balance->setBalanceHeader($header);
+
+ return $balance;
}
/**
- * Get a full report on the users expenses during the period for a list of accounts.
+ * This method generates a full report for the given period on all
+ * the users bills and their payments.
+ *
+ * Excludes bills which have not had a payment on the mentioned accounts.
*
* @param Carbon $start
* @param Carbon $end
* @param Collection $accounts
*
- * @return Expense
+ * @return BillCollection
*/
- public function getExpenseReport($start, $end, Collection $accounts)
+ public function getBillReport(Carbon $start, Carbon $end, Collection $accounts)
{
- $object = new Expense;
- $set = $this->query->expense($accounts, $start, $end);
+ /** @var \FireflyIII\Repositories\Bill\BillRepositoryInterface $repository */
+ $repository = app('FireflyIII\Repositories\Bill\BillRepositoryInterface');
+ $bills = $repository->getBillsForAccounts($accounts);
+ $journals = $repository->getAllJournalsInRange($bills, $start, $end);
+ $collection = new BillCollection;
+
+ /** @var Bill $bill */
+ foreach ($bills as $bill) {
+ $billLine = new BillLine;
+ $billLine->setBill($bill);
+ $billLine->setActive(intval($bill->active) == 1);
+ $billLine->setMin($bill->amount_min);
+ $billLine->setMax($bill->amount_max);
+
+ // is hit in period?
+ bcscale(2);
+
+ $entry = $journals->filter(
+ function (TransactionJournal $journal) use ($bill) {
+ return $journal->bill_id == $bill->id;
+ }
+ );
+ if (!is_null($entry->first())) {
+ $billLine->setAmount($entry->first()->journalAmount);
+ $billLine->setHit(true);
+ } else {
+ $billLine->setHit(false);
+ }
+
+ $collection->addBill($billLine);
- foreach ($set as $entry) {
- $object->addToTotal($entry->journalAmount); // can be positive, if it's a transfer
- $object->addOrCreateExpense($entry);
}
- return $object;
+ return $collection;
}
/**
@@ -338,82 +313,105 @@ class ReportHelper implements ReportHelperInterface
* @param Carbon $end
* @param Collection $accounts
*
- * @return Balance
+ * @return CategoryCollection
*/
- public function getBalanceReport(Carbon $start, Carbon $end, Collection $accounts)
+ public function getCategoryReport(Carbon $start, Carbon $end, Collection $accounts)
{
- $balance = new Balance;
+ $object = new CategoryCollection;
- // build a balance header:
- $header = new BalanceHeader;
- $budgets = $this->budgetRepository->getBudgetsAndLimitsInRange($start, $end);
- $spentData = $this->budgetRepository->spentPerBudgetPerAccount($budgets, $accounts, $start, $end);
- foreach ($accounts as $account) {
- $header->addAccount($account);
- }
+ /**
+ * GET CATEGORIES:
+ */
+ /** @var \FireflyIII\Repositories\Category\CategoryRepositoryInterface $repository */
+ $repository = app('FireflyIII\Repositories\Category\CategoryRepositoryInterface');
- /** @var BudgetModel $budget */
- foreach ($budgets as $budget) {
- $balance->addBalanceLine($this->createBalanceLine($budget, $accounts, $spentData));
+ $set = $repository->spentForAccountsPerMonth($accounts, $start, $end);
+ foreach ($set as $category) {
+ $object->addCategory($category);
}
- $balance->addBalanceLine($this->createEmptyBalanceLine($accounts, $spentData));
- $balance->addBalanceLine($this->createTagsBalanceLine($accounts, $start, $end));
- $balance->addBalanceLine($this->createDifferenceBalanceLine($accounts, $spentData, $start, $end));
+ return $object;
+ }
- $balance->setBalanceHeader($header);
+ /**
+ * Get a full report on the users expenses during the period for a list of accounts.
+ *
+ * @param Carbon $start
+ * @param Carbon $end
+ * @param Collection $accounts
+ *
+ * @return Expense
+ */
+ public function getExpenseReport($start, $end, Collection $accounts)
+ {
+ $object = new Expense;
+ $set = $this->query->expense($accounts, $start, $end);
- return $balance;
+ foreach ($set as $entry) {
+ $object->addToTotal($entry->journalAmount); // can be positive, if it's a transfer
+ $object->addOrCreateExpense($entry);
+ }
+
+ return $object;
}
/**
- * This method generates a full report for the given period on all
- * the users bills and their payments.
- *
- * Excludes bills which have not had a payment on the mentioned accounts.
+ * Get a full report on the users incomes during the period for the given accounts.
*
* @param Carbon $start
* @param Carbon $end
* @param Collection $accounts
*
- * @return BillCollection
+ * @return Income
*/
- public function getBillReport(Carbon $start, Carbon $end, Collection $accounts)
+ public function getIncomeReport($start, $end, Collection $accounts)
{
- /** @var \FireflyIII\Repositories\Bill\BillRepositoryInterface $repository */
- $repository = app('FireflyIII\Repositories\Bill\BillRepositoryInterface');
- $bills = $repository->getBillsForAccounts($accounts);
- $journals = $repository->getAllJournalsInRange($bills, $start, $end);
- $collection = new BillCollection;
+ $object = new Income;
+ $set = $this->query->income($accounts, $start, $end);
- /** @var Bill $bill */
- foreach ($bills as $bill) {
- $billLine = new BillLine;
- $billLine->setBill($bill);
- $billLine->setActive(intval($bill->active) == 1);
- $billLine->setMin($bill->amount_min);
- $billLine->setMax($bill->amount_max);
+ foreach ($set as $entry) {
+ $object->addToTotal($entry->journalAmount);
+ $object->addOrCreateIncome($entry);
+ }
- // is hit in period?
- bcscale(2);
+ return $object;
+ }
- $entry = $journals->filter(
- function (TransactionJournal $journal) use ($bill) {
- return $journal->bill_id == $bill->id;
- }
- );
- if (!is_null($entry->first())) {
- $billLine->setAmount($entry->first()->journalAmount);
- $billLine->setHit(true);
- } else {
- $billLine->setHit(false);
- }
+ /**
+ * @param Carbon $date
+ *
+ * @return array
+ */
+ public function listOfMonths(Carbon $date)
+ {
- $collection->addBill($billLine);
+ $start = clone $date;
+ $end = Carbon::now();
+ $months = [];
+ while ($start <= $end) {
+ $year = $start->year;
+
+ if (!isset($months[$year])) {
+ $months[$year] = [
+ 'start' => Carbon::createFromDate($year, 1, 1)->format('Y-m-d'),
+ 'end' => Carbon::createFromDate($year, 12, 31)->format('Y-m-d'),
+ 'months' => [],
+ ];
+ }
+ $currentEnd = clone $start;
+ $currentEnd->endOfMonth();
+ $months[$year]['months'][] = [
+ 'formatted' => $start->formatLocalized('%B %Y'),
+ 'start' => $start->format('Y-m-d'),
+ 'end' => $currentEnd->format('Y-m-d'),
+ 'month' => $start->month,
+ 'year' => $year,
+ ];
+ $start->addMonth();
}
- return $collection;
+ return $months;
}
/**
@@ -481,12 +479,19 @@ class ReportHelper implements ReportHelperInterface
/**
* @param Collection $accounts
* @param Collection $spentData
+ * @param Carbon $start
+ * @param Carbon $end
+ *
+ * @SuppressWarnings(PHPMD.CyclomaticComplexity)
*
* @return BalanceLine
*/
- private function createEmptyBalanceLine(Collection $accounts, Collection $spentData)
+ private function createDifferenceBalanceLine(Collection $accounts, Collection $spentData, Carbon $start, Carbon $end)
{
- $empty = new BalanceLine;
+ $diff = new BalanceLine;
+ $tagsLeft = $this->tagRepository->allCoveredByBalancingActs($accounts, $start, $end);
+
+ $diff->setRole(BalanceLine::ROLE_DIFFROLE);
foreach ($accounts as $account) {
$entry = $spentData->filter(
@@ -498,82 +503,76 @@ class ReportHelper implements ReportHelperInterface
if (!is_null($entry->first())) {
$spent = $entry->first()->spent;
}
+ $leftEntry = $tagsLeft->filter(
+ function (Tag $tag) use ($account) {
+ return $tag->account_id == $account->id;
+ }
+ );
+ $left = 0;
+ if (!is_null($leftEntry->first())) {
+ $left = $leftEntry->first()->sum;
+ }
+ bcscale(2);
+ $diffValue = bcadd($spent, $left);
- // budget
- $budgetEntry = new BalanceEntry;
- $budgetEntry->setAccount($account);
- $budgetEntry->setSpent($spent);
- $empty->addBalanceEntry($budgetEntry);
+ // difference:
+ $diffEntry = new BalanceEntry;
+ $diffEntry->setAccount($account);
+ $diffEntry->setSpent($diffValue);
+ $diff->addBalanceEntry($diffEntry);
}
- return $empty;
+ return $diff;
}
/**
* @param Collection $accounts
- * @param Carbon $start
- * @param Carbon $end
+ * @param Collection $spentData
*
* @return BalanceLine
*/
- private function createTagsBalanceLine(Collection $accounts, Carbon $start, Carbon $end)
+ private function createEmptyBalanceLine(Collection $accounts, Collection $spentData)
{
- $tags = new BalanceLine;
- $tagsLeft = $this->tagRepository->allCoveredByBalancingActs($accounts, $start, $end);
-
- $tags->setRole(BalanceLine::ROLE_TAGROLE);
+ $empty = new BalanceLine;
foreach ($accounts as $account) {
- $leftEntry = $tagsLeft->filter(
- function (Tag $tag) use ($account) {
- return $tag->account_id == $account->id;
+ $entry = $spentData->filter(
+ function (TransactionJournal $model) use ($account) {
+ return $model->account_id == $account->id && is_null($model->budget_id);
}
);
- $left = 0;
- if (!is_null($leftEntry->first())) {
- $left = $leftEntry->first()->sum;
+ $spent = 0;
+ if (!is_null($entry->first())) {
+ $spent = $entry->first()->spent;
}
- bcscale(2);
- // balanced by tags
- $tagEntry = new BalanceEntry;
- $tagEntry->setAccount($account);
- $tagEntry->setLeft($left);
- $tags->addBalanceEntry($tagEntry);
+ // budget
+ $budgetEntry = new BalanceEntry;
+ $budgetEntry->setAccount($account);
+ $budgetEntry->setSpent($spent);
+ $empty->addBalanceEntry($budgetEntry);
}
- return $tags;
+ return $empty;
}
/**
* @param Collection $accounts
- * @param Collection $spentData
* @param Carbon $start
* @param Carbon $end
*
- * @SuppressWarnings(PHPMD.CyclomaticComplexity)
- *
* @return BalanceLine
*/
- private function createDifferenceBalanceLine(Collection $accounts, Collection $spentData, Carbon $start, Carbon $end)
+ private function createTagsBalanceLine(Collection $accounts, Carbon $start, Carbon $end)
{
- $diff = new BalanceLine;
+ $tags = new BalanceLine;
$tagsLeft = $this->tagRepository->allCoveredByBalancingActs($accounts, $start, $end);
- $diff->setRole(BalanceLine::ROLE_DIFFROLE);
+ $tags->setRole(BalanceLine::ROLE_TAGROLE);
foreach ($accounts as $account) {
- $entry = $spentData->filter(
- function (TransactionJournal $model) use ($account) {
- return $model->account_id == $account->id && is_null($model->budget_id);
- }
- );
- $spent = 0;
- if (!is_null($entry->first())) {
- $spent = $entry->first()->spent;
- }
$leftEntry = $tagsLeft->filter(
function (Tag $tag) use ($account) {
return $tag->account_id == $account->id;
@@ -584,16 +583,15 @@ class ReportHelper implements ReportHelperInterface
$left = $leftEntry->first()->sum;
}
bcscale(2);
- $diffValue = bcadd($spent, $left);
- // difference:
- $diffEntry = new BalanceEntry;
- $diffEntry->setAccount($account);
- $diffEntry->setSpent($diffValue);
- $diff->addBalanceEntry($diffEntry);
+ // balanced by tags
+ $tagEntry = new BalanceEntry;
+ $tagEntry->setAccount($account);
+ $tagEntry->setLeft($left);
+ $tags->addBalanceEntry($tagEntry);
}
- return $diff;
+ return $tags;
}
}
diff --git a/app/Helpers/Report/ReportHelperInterface.php b/app/Helpers/Report/ReportHelperInterface.php
index f52036cac2..9759d755d7 100644
--- a/app/Helpers/Report/ReportHelperInterface.php
+++ b/app/Helpers/Report/ReportHelperInterface.php
@@ -33,27 +33,27 @@ interface ReportHelperInterface
public function getAccountReport(Carbon $start, Carbon $end, Collection $accounts);
/**
- * This method generates a full report for the given period on all
- * the users bills and their payments.
- *
- * Excludes bills which have not had a payment on the mentioned accounts.
- *
* @param Carbon $start
* @param Carbon $end
* @param Collection $accounts
*
- * @return BillCollection
+ * @return Balance
*/
- public function getBillReport(Carbon $start, Carbon $end, Collection $accounts);
+ public function getBalanceReport(Carbon $start, Carbon $end, Collection $accounts);
/**
+ * This method generates a full report for the given period on all
+ * the users bills and their payments.
+ *
+ * Excludes bills which have not had a payment on the mentioned accounts.
+ *
* @param Carbon $start
* @param Carbon $end
* @param Collection $accounts
*
- * @return Balance
+ * @return BillCollection
*/
- public function getBalanceReport(Carbon $start, Carbon $end, Collection $accounts);
+ public function getBillReport(Carbon $start, Carbon $end, Collection $accounts);
/**
* @param Carbon $start
diff --git a/app/Helpers/Report/ReportQuery.php b/app/Helpers/Report/ReportQuery.php
index 0180571484..24027b2e0c 100644
--- a/app/Helpers/Report/ReportQuery.php
+++ b/app/Helpers/Report/ReportQuery.php
@@ -17,51 +17,6 @@ use Illuminate\Support\Collection;
class ReportQuery implements ReportQueryInterface
{
- /**
- * Returns an array of the amount of money spent in the given accounts (on withdrawals, opening balances and transfers)
- * grouped by month like so: "2015-01" => '123.45'
- *
- * @param Collection $accounts
- * @param Carbon $start
- * @param Carbon $end
- *
- * @return array
- */
- public function spentPerMonth(Collection $accounts, Carbon $start, Carbon $end)
- {
- $ids = $accounts->pluck('id')->toArray();
- $query = Auth::user()->transactionjournals()
- ->leftJoin(
- 'transactions AS t_from', function (JoinClause $join) {
- $join->on('transaction_journals.id', '=', 't_from.transaction_journal_id')->where('t_from.amount', '<', 0);
- }
- )
- ->leftJoin(
- 'transactions AS t_to', function (JoinClause $join) {
- $join->on('transaction_journals.id', '=', 't_to.transaction_journal_id')->where('t_to.amount', '>', 0);
- }
- )
- ->whereIn('t_from.account_id', $ids)
- ->whereNotIn('t_to.account_id', $ids)
- ->after($start)
- ->before($end)
- ->transactionTypes([TransactionType::WITHDRAWAL, TransactionType::TRANSFER, TransactionType::OPENING_BALANCE])
- ->groupBy('dateFormatted')
- ->get(
- [
- DB::Raw('DATE_FORMAT(`transaction_journals`.`date`,"%Y-%m") AS `dateFormatted`'),
- DB::Raw('SUM(`t_from`.`amount`) AS `sum`'),
- ]
- );
- $array = [];
- foreach ($query as $result) {
- $array[$result->dateFormatted] = $result->sum;
- }
-
- return $array;
-
- }
-
/**
* Returns an array of the amount of money spent in the given accounts (on withdrawals, opening balances and transfers)
* grouped by month like so: "2015-01" => '123.45'
@@ -107,7 +62,7 @@ class ReportQuery implements ReportQueryInterface
}
/**
- * This method returns all the "in" transaction journals for the given account and given period. The amount
+ * This method returns all the "out" transaction journals for the given account and given period. The amount
* is stored in "journalAmount".
*
* @param Collection $accounts
@@ -116,7 +71,7 @@ class ReportQuery implements ReportQueryInterface
*
* @return Collection
*/
- public function income(Collection $accounts, Carbon $start, Carbon $end)
+ public function expense(Collection $accounts, Carbon $start, Carbon $end)
{
$ids = $accounts->pluck('id')->toArray();
$set = Auth::user()->transactionjournals()
@@ -130,19 +85,19 @@ class ReportQuery implements ReportQueryInterface
$join->on('t_to.transaction_journal_id', '=', 'transaction_journals.id')->where('t_to.amount', '>', 0);
}
)
- ->leftJoin('accounts', 't_from.account_id', '=', 'accounts.id')
- ->transactionTypes([TransactionType::DEPOSIT, TransactionType::TRANSFER, TransactionType::OPENING_BALANCE])
+ ->leftJoin('accounts', 't_to.account_id', '=', 'accounts.id')
+ ->transactionTypes([TransactionType::WITHDRAWAL, TransactionType::TRANSFER, TransactionType::OPENING_BALANCE])
->before($end)
->after($start)
- ->whereIn('t_to.account_id', $ids)
- ->whereNotIn('t_from.account_id', $ids)
- ->get(['transaction_journals.*', 't_to.amount as journalAmount', 'accounts.id as account_id', 'accounts.name as account_name']);
+ ->whereIn('t_from.account_id', $ids)
+ ->whereNotIn('t_to.account_id', $ids)
+ ->get(['transaction_journals.*', 't_from.amount as journalAmount', 'accounts.id as account_id', 'accounts.name as account_name']);
return $set;
}
/**
- * This method returns all the "out" transaction journals for the given account and given period. The amount
+ * This method returns all the "in" transaction journals for the given account and given period. The amount
* is stored in "journalAmount".
*
* @param Collection $accounts
@@ -151,7 +106,7 @@ class ReportQuery implements ReportQueryInterface
*
* @return Collection
*/
- public function expense(Collection $accounts, Carbon $start, Carbon $end)
+ public function income(Collection $accounts, Carbon $start, Carbon $end)
{
$ids = $accounts->pluck('id')->toArray();
$set = Auth::user()->transactionjournals()
@@ -165,14 +120,59 @@ class ReportQuery implements ReportQueryInterface
$join->on('t_to.transaction_journal_id', '=', 'transaction_journals.id')->where('t_to.amount', '>', 0);
}
)
- ->leftJoin('accounts', 't_to.account_id', '=', 'accounts.id')
- ->transactionTypes([TransactionType::WITHDRAWAL, TransactionType::TRANSFER, TransactionType::OPENING_BALANCE])
+ ->leftJoin('accounts', 't_from.account_id', '=', 'accounts.id')
+ ->transactionTypes([TransactionType::DEPOSIT, TransactionType::TRANSFER, TransactionType::OPENING_BALANCE])
->before($end)
->after($start)
- ->whereIn('t_from.account_id', $ids)
- ->whereNotIn('t_to.account_id', $ids)
- ->get(['transaction_journals.*', 't_from.amount as journalAmount', 'accounts.id as account_id', 'accounts.name as account_name']);
+ ->whereIn('t_to.account_id', $ids)
+ ->whereNotIn('t_from.account_id', $ids)
+ ->get(['transaction_journals.*', 't_to.amount as journalAmount', 'accounts.id as account_id', 'accounts.name as account_name']);
return $set;
}
+
+ /**
+ * Returns an array of the amount of money spent in the given accounts (on withdrawals, opening balances and transfers)
+ * grouped by month like so: "2015-01" => '123.45'
+ *
+ * @param Collection $accounts
+ * @param Carbon $start
+ * @param Carbon $end
+ *
+ * @return array
+ */
+ public function spentPerMonth(Collection $accounts, Carbon $start, Carbon $end)
+ {
+ $ids = $accounts->pluck('id')->toArray();
+ $query = Auth::user()->transactionjournals()
+ ->leftJoin(
+ 'transactions AS t_from', function (JoinClause $join) {
+ $join->on('transaction_journals.id', '=', 't_from.transaction_journal_id')->where('t_from.amount', '<', 0);
+ }
+ )
+ ->leftJoin(
+ 'transactions AS t_to', function (JoinClause $join) {
+ $join->on('transaction_journals.id', '=', 't_to.transaction_journal_id')->where('t_to.amount', '>', 0);
+ }
+ )
+ ->whereIn('t_from.account_id', $ids)
+ ->whereNotIn('t_to.account_id', $ids)
+ ->after($start)
+ ->before($end)
+ ->transactionTypes([TransactionType::WITHDRAWAL, TransactionType::TRANSFER, TransactionType::OPENING_BALANCE])
+ ->groupBy('dateFormatted')
+ ->get(
+ [
+ DB::Raw('DATE_FORMAT(`transaction_journals`.`date`,"%Y-%m") AS `dateFormatted`'),
+ DB::Raw('SUM(`t_from`.`amount`) AS `sum`'),
+ ]
+ );
+ $array = [];
+ foreach ($query as $result) {
+ $array[$result->dateFormatted] = $result->sum;
+ }
+
+ return $array;
+
+ }
}
diff --git a/app/Repositories/Account/AccountRepository.php b/app/Repositories/Account/AccountRepository.php
index 6a9ebf260b..95f7dc6ec3 100644
--- a/app/Repositories/Account/AccountRepository.php
+++ b/app/Repositories/Account/AccountRepository.php
@@ -61,6 +61,18 @@ class AccountRepository implements AccountRepositoryInterface
return true;
}
+ /**
+ * @deprecated
+ *
+ * @param $accountId
+ *
+ * @return Account
+ */
+ public function find($accountId)
+ {
+ return Auth::user()->accounts()->findOrNew($accountId);
+ }
+
/**
* @param array $types
*
@@ -84,7 +96,6 @@ class AccountRepository implements AccountRepositoryInterface
return $result;
}
-
/**
* This method returns the users credit cards, along with some basic information about the
* balance they have on their CC. To be used in the JSON boxes on the front page that say
@@ -465,29 +476,6 @@ class AccountRepository implements AccountRepositoryInterface
return $newAccount;
}
- /**
- * @param Account $account
- * @param array $data
- */
- protected function storeMetadata(Account $account, array $data)
- {
- $validFields = ['accountRole', 'ccMonthlyPaymentDate', 'ccType'];
- foreach ($validFields as $field) {
- if (isset($data[$field])) {
- $metaData = new AccountMeta(
- [
- 'account_id' => $account->id,
- 'name' => $field,
- 'data' => $data[$field],
- ]
- );
- $metaData->save();
- }
-
-
- }
- }
-
/**
* @param Account $account
* @param Account $opposing
@@ -536,33 +524,24 @@ class AccountRepository implements AccountRepositoryInterface
/**
* @param Account $account
* @param array $data
- *
*/
- protected function updateMetadata(Account $account, array $data)
+ protected function storeMetadata(Account $account, array $data)
{
$validFields = ['accountRole', 'ccMonthlyPaymentDate', 'ccType'];
-
foreach ($validFields as $field) {
- $entry = $account->accountMeta()->where('name', $field)->first();
-
if (isset($data[$field])) {
- // update if new data is present:
- if (!is_null($entry)) {
- $entry->data = $data[$field];
- $entry->save();
- } else {
- $metaData = new AccountMeta(
- [
- 'account_id' => $account->id,
- 'name' => $field,
- 'data' => $data[$field],
- ]
- );
- $metaData->save();
- }
+ $metaData = new AccountMeta(
+ [
+ 'account_id' => $account->id,
+ 'name' => $field,
+ 'data' => $data[$field],
+ ]
+ );
+ $metaData->save();
}
- }
+
+ }
}
/**
@@ -592,14 +571,34 @@ class AccountRepository implements AccountRepositoryInterface
}
/**
- * @deprecated
- *
- * @param $accountId
+ * @param Account $account
+ * @param array $data
*
- * @return Account
*/
- public function find($accountId)
+ protected function updateMetadata(Account $account, array $data)
{
- return Auth::user()->accounts()->findOrNew($accountId);
+ $validFields = ['accountRole', 'ccMonthlyPaymentDate', 'ccType'];
+
+ foreach ($validFields as $field) {
+ $entry = $account->accountMeta()->where('name', $field)->first();
+
+ if (isset($data[$field])) {
+ // update if new data is present:
+ if (!is_null($entry)) {
+ $entry->data = $data[$field];
+ $entry->save();
+ } else {
+ $metaData = new AccountMeta(
+ [
+ 'account_id' => $account->id,
+ 'name' => $field,
+ 'data' => $data[$field],
+ ]
+ );
+ $metaData->save();
+ }
+ }
+ }
+
}
}
diff --git a/app/Repositories/Account/AccountRepositoryInterface.php b/app/Repositories/Account/AccountRepositoryInterface.php
index b18ffb2807..628aca2d15 100644
--- a/app/Repositories/Account/AccountRepositoryInterface.php
+++ b/app/Repositories/Account/AccountRepositoryInterface.php
@@ -24,15 +24,6 @@ interface AccountRepositoryInterface
*/
public function countAccounts(array $types);
- /**
- * @param $accountId
- *
- * @deprecated
- *
- * @return Account
- */
- public function find($accountId);
-
/**
* @param Account $account
* @param Account $moveTo
@@ -42,19 +33,20 @@ interface AccountRepositoryInterface
public function destroy(Account $account, Account $moveTo = null);
/**
- * @param array $types
+ * @param $accountId
*
- * @return Collection
+ * @deprecated
+ *
+ * @return Account
*/
- public function getAccounts(array $types);
+ public function find($accountId);
/**
- * @param TransactionJournal $journal
- * @param Account $account
+ * @param array $types
*
- * @return Transaction
+ * @return Collection
*/
- public function getFirstTransaction(TransactionJournal $journal, Account $account);
+ public function getAccounts(array $types);
/**
* This method returns the users credit cards, along with some basic information about the
@@ -70,11 +62,12 @@ interface AccountRepositoryInterface
public function getCreditCards(Carbon $date);
/**
- * Get the accounts of a user that have piggy banks connected to them.
+ * @param TransactionJournal $journal
+ * @param Account $account
*
- * @return Collection
+ * @return Transaction
*/
- public function getPiggyBankAccounts();
+ public function getFirstTransaction(TransactionJournal $journal, Account $account);
/**
* @param Preference $preference
@@ -101,9 +94,11 @@ interface AccountRepositoryInterface
public function getJournals(Account $account, $page);
/**
- * @return string
+ * Get the accounts of a user that have piggy banks connected to them.
+ *
+ * @return Collection
*/
- public function sumOfEverything();
+ public function getPiggyBankAccounts();
/**
* Get savings accounts and the balance difference in the period.
@@ -134,6 +129,11 @@ interface AccountRepositoryInterface
*/
public function store(array $data);
+ /**
+ * @return string
+ */
+ public function sumOfEverything();
+
/**
* @param Account $account
* @param array $data
diff --git a/app/Repositories/RuleGroup/RuleGroupRepository.php b/app/Repositories/RuleGroup/RuleGroupRepository.php
index 4593d1d1fe..b42ee7779e 100644
--- a/app/Repositories/RuleGroup/RuleGroupRepository.php
+++ b/app/Repositories/RuleGroup/RuleGroupRepository.php
@@ -46,6 +46,13 @@ class RuleGroupRepository implements RuleGroupRepositoryInterface
return true;
}
+ /**
+ * @return Collection
+ */
+ public function get()
+ {
+ return Auth::user()->ruleGroups()->orderBy('order', 'ASC')->get();
+ }
/**
* @return int
@@ -57,32 +64,23 @@ class RuleGroupRepository implements RuleGroupRepositoryInterface
return intval($entry);
}
- /**
- * @return Collection
- */
- public function get()
- {
- return Auth::user()->ruleGroups()->orderBy('order', 'ASC')->get();
- }
-
-
/**
* @param RuleGroup $ruleGroup
*
* @return bool
*/
- public function moveUp(RuleGroup $ruleGroup)
+ public function moveDown(RuleGroup $ruleGroup)
{
$order = $ruleGroup->order;
- // find the rule with order-1 and give it order+1
- $other = Auth::user()->ruleGroups()->where('order', ($order - 1))->first();
+ // find the rule with order+1 and give it order-1
+ $other = Auth::user()->ruleGroups()->where('order', ($order + 1))->first();
if ($other) {
- $other->order = ($other->order + 1);
+ $other->order = ($other->order - 1);
$other->save();
}
- $ruleGroup->order = ($ruleGroup->order - 1);
+ $ruleGroup->order = ($ruleGroup->order + 1);
$ruleGroup->save();
$this->resetRuleGroupOrder();
}
@@ -92,23 +90,22 @@ class RuleGroupRepository implements RuleGroupRepositoryInterface
*
* @return bool
*/
- public function moveDown(RuleGroup $ruleGroup)
+ public function moveUp(RuleGroup $ruleGroup)
{
$order = $ruleGroup->order;
- // find the rule with order+1 and give it order-1
- $other = Auth::user()->ruleGroups()->where('order', ($order + 1))->first();
+ // find the rule with order-1 and give it order+1
+ $other = Auth::user()->ruleGroups()->where('order', ($order - 1))->first();
if ($other) {
- $other->order = ($other->order - 1);
+ $other->order = ($other->order + 1);
$other->save();
}
- $ruleGroup->order = ($ruleGroup->order + 1);
+ $ruleGroup->order = ($ruleGroup->order - 1);
$ruleGroup->save();
$this->resetRuleGroupOrder();
}
-
/**
* @return bool
*/
diff --git a/app/Repositories/RuleGroup/RuleGroupRepositoryInterface.php b/app/Repositories/RuleGroup/RuleGroupRepositoryInterface.php
index f1dd3f317b..fbb36df7c4 100644
--- a/app/Repositories/RuleGroup/RuleGroupRepositoryInterface.php
+++ b/app/Repositories/RuleGroup/RuleGroupRepositoryInterface.php
@@ -21,30 +21,29 @@ interface RuleGroupRepositoryInterface
*/
public function destroy(RuleGroup $ruleGroup, RuleGroup $moveTo = null);
-
/**
- * @return int
+ * @return Collection
*/
- public function getHighestOrderRuleGroup();
+ public function get();
/**
- * @return Collection
+ * @return int
*/
- public function get();
+ public function getHighestOrderRuleGroup();
/**
* @param RuleGroup $ruleGroup
*
* @return bool
*/
- public function moveUp(RuleGroup $ruleGroup);
+ public function moveDown(RuleGroup $ruleGroup);
/**
* @param RuleGroup $ruleGroup
*
* @return bool
*/
- public function moveDown(RuleGroup $ruleGroup);
+ public function moveUp(RuleGroup $ruleGroup);
/**
* @return bool