From 339c3525056d5e19c9865b8433e6d841ee96ac6c Mon Sep 17 00:00:00 2001 From: James Cole Date: Thu, 9 Apr 2015 17:46:47 +0200 Subject: [PATCH] Fixed a bug where categories would be created even though they already existed. --- app/Models/Category.php | 35 ++++++++++++++++++- .../Journal/JournalRepository.php | 4 +-- 2 files changed, 36 insertions(+), 3 deletions(-) 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); }