Skip to content

Firefly III: a personal finances manager

Fixed a bug where categories would be created even though they already existed.

James Cole339c3525056d
diff --git a/app/Models/Category.php b/app/Models/Category.php
index 91674b7f87..60a8198571 100644
--- a/app/Models/Category.php
+++ b/app/Models/Category.php
@@ -3,7 +3,7 @@
use Crypt;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
-
+use App;
/**
* Class Category
*
@@ -31,6 +31,39 @@ class Category extends Model
return $this->belongsToMany('FireflyIII\Models\TransactionJournal', 'category_transaction_journal', 'category_id');
}
+ /**
+ * @param array $fields
+ *
+ * @return Account|null
+ */
+ public static function firstOrCreateEncrypted(array $fields)
+ {
+ // everything but the name:
+ $query = Category::orderBy('id');
+ foreach ($fields as $name => $value) {
+ if ($name != 'name') {
+ $query->where($name, $value);
+ }
+ }
+ $set = $query->get(['categories.*']);
+ /** @var Category $category */
+ foreach ($set as $category) {
+ if ($category->name == $fields['name']) {
+ return $category;
+ }
+ }
+ // create it!
+ $category = Category::create($fields);
+ if (is_null($category->id)) {
+ // could not create account:
+ App::abort(500, 'Could not create new category with data: ' . json_encode($fields));
+
+ }
+
+ return $category;
+
+ }
+
/**
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
diff --git a/app/Repositories/Journal/JournalRepository.php b/app/Repositories/Journal/JournalRepository.php
index fdda6ae3d4..eb1c8db19d 100644
--- a/app/Repositories/Journal/JournalRepository.php
+++ b/app/Repositories/Journal/JournalRepository.php
@@ -140,7 +140,7 @@ class JournalRepository implements JournalRepositoryInterface
// store or get category
if (strlen($data['category']) > 0) {
- $category = Category::firstOrCreate(['name' => $data['category'], 'user_id' => $data['user']]);
+ $category = Category::firstOrCreateEncrypted(['name' => $data['category'], 'user_id' => $data['user']]);
$journal->categories()->save($category);
}
@@ -193,7 +193,7 @@ class JournalRepository implements JournalRepositoryInterface
// unlink all categories, recreate them:
$journal->categories()->detach();
if (strlen($data['category']) > 0) {
- $category = Category::firstOrCreate(['name' => $data['category'], 'user_id' => $data['user']]);
+ $category = Category::firstOrCreateEncrypted(['name' => $data['category'], 'user_id' => $data['user']]);
$journal->categories()->save($category);
}