diff --git a/app/Jobs/ImportProfession.php b/app/Jobs/ImportProfession.php index 05f33d1..16d5209 100644 --- a/app/Jobs/ImportProfession.php +++ b/app/Jobs/ImportProfession.php @@ -161,8 +161,12 @@ class ImportProfession implements ShouldQueue protected function getRecipe(Spell $spell, ?Item $crafted, Profession $profession, $data) { + // Find by spell_id or fallback to craft->name if null. $recipe = $profession->recipes() ->where('spell_id', $spell->id) + ->orWhereHas('craft', function($q) use ($data) { + $q->where('name', $data->name); + }) ->first(); // Create if not found. @@ -176,9 +180,17 @@ class ImportProfession implements ShouldQueue 'category_id' => $category->id ]); } - // Update with crafted item :) - else if ($crafted) { - $recipe->craft()->associate($crafted); + // Existing record. + else { + // Update with crafted item :) + if (!$recipe->craft && $crafted) { + $recipe->craft()->associate($crafted); + } + + // Update spell if it dont exist. + if (!$recipe->spell) { + $recipe->spell()->associate($spell); + } } // Insert/Update Reagents diff --git a/tests/Feature/ProfessionImportTest.php b/tests/Feature/ProfessionImportTest.php index dcbe1cf..3830dd3 100644 --- a/tests/Feature/ProfessionImportTest.php +++ b/tests/Feature/ProfessionImportTest.php @@ -10,6 +10,8 @@ use App\Models\User; use App\Models\Character; use App\Models\CharacterProfession; use App\Models\Profession; +use App\Models\Item; +use App\Models\Recipe; use App\Jobs\ImportProfession; class ProfessionImportTest extends TestCase @@ -210,4 +212,42 @@ class ProfessionImportTest extends TestCase $this->assertEquals('Nexus Crystal', $recipes[1]->reagents[0]->name); $this->assertEquals(1, $recipes[1]->reagents[0]->quantity); } + + public function test_import_does_not_create_duplicate_recipes_if_spell_relationship_is_missing() + { + $character = Character::factory()->create([ 'name' => 'Duplicated']); + $profession = Profession::factory()->create([ 'name' => 'My Unique Profession' ]); + $item = Item::factory()->create(['name' => 'Unique Recipe']); + + $recipe = Recipe::factory() + ->for($profession) + ->for($item, 'craft') + ->create(['spell_id' => null]); + + $data = (object) [ + "player" => $character->name, + "profession" => (object) [ + "name" => $profession->name, + "level" => 375, + "maxLevel" => 375, + "recipes" => [ + (object) [ + "name" => $item->name, + "num" => 0, + "categorie" => "none", + "items" => [], + "spellId" => 1337 + ] + ] + ] + ]; + + ImportProfession::dispatch($character, $data); + + $this->assertEquals(1, Recipe::count()); + $this->assertDatabaseHas('recipes', [ + 'spell_id' => 1337, + 'item_id' => $item->id, + ]); + } }