Refactor order creation logic by introducing CreateOrderService and removing the create method from OrderRepository. Update ProductRepository with stricter type declarations and fix minor typos in comments.

This commit is contained in:
2026-02-05 01:29:10 +05:00
parent d0f962220c
commit eaae8b9be9
5 changed files with 160 additions and 54 deletions

View File

@@ -0,0 +1,76 @@
<?php
namespace Tests\Feature\Services\Order;
use App\Models\Ecommerce\Product\Cart\Cart;
use App\Models\Ecommerce\Product\Product\Product;
use App\Models\User;
use App\Services\Order\CreateOrderService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Event;
use Tests\TestCase;
use App\Events\Ecommerce\Product\Order\OrderCreated;
class CreateOrderServiceTest extends TestCase
{
use RefreshDatabase;
public function test_it_creates_order_successfully()
{
Event::fake();
// 1. Arrange
$user = User::factory()->create();
$product = Product::factory()->create([
'stock' => 10,
'price_amount' => 100,
'cost_amount' => 50,
'name' => 'Test Product'
]);
// Create Cart Item
Cart::factory()->create([
'user_id' => $user->id,
'product_id' => $product->id,
'product_quantity' => 2
]);
$service = new CreateOrderService();
$orderData = [
'user_id' => $user->id,
'status' => 'pending',
'total_amount' => 200
];
// 2. Act
$order = $service->execute($user, $orderData);
// 3. Assert
// Check Order Created
$this->assertDatabaseHas('orders', [
'id' => $order->id,
'user_id' => $user->id,
'total_amount' => 200
]);
// Check Order Items Created
$this->assertDatabaseHas('order_items', [
'order_id' => $order->id,
'product_id' => $product->id,
'quantity' => 2,
'product_name' => 'Test Product'
]);
// Check Stock Deducted (10 - 2 = 8)
$this->assertEquals(8, $product->fresh()->stock);
// Check Cart Cleared
$this->assertDatabaseMissing('carts', [
'user_id' => $user->id
]);
// Check Event Dispatched
Event::assertDispatched(OrderCreated::class);
}
}