66 lines
1.9 KiB
PHP
66 lines
1.9 KiB
PHP
<?php
|
|
|
|
namespace Database\Seeders;
|
|
|
|
use App\Models\Order;
|
|
use App\Models\OrderItem;
|
|
use App\Models\Product;
|
|
use App\Models\User;
|
|
use Illuminate\Database\Seeder;
|
|
|
|
class OrderSeeder extends Seeder
|
|
{
|
|
/**
|
|
* Run the database seeds.
|
|
*/
|
|
public function run(): void
|
|
{
|
|
$users = User::all();
|
|
$products = Product::all();
|
|
|
|
if ($users->isEmpty() || $products->isEmpty()) {
|
|
return;
|
|
}
|
|
|
|
Order::factory(100)->create()->each(function ($order) use ($users, $products) {
|
|
$itemsCount = rand(1, 4);
|
|
$totalOrderPrice = 0;
|
|
$totalOrderHpp = 0;
|
|
|
|
for ($i = 0; $i < $itemsCount; $i++) {
|
|
$product = $products->random();
|
|
$qty = rand(1, 5);
|
|
$price = rand(100000, 300000);
|
|
$itemTotal = $qty * $price;
|
|
|
|
// Assuming hpp is 70% of price for simulation
|
|
$hpp = intval($price * 0.7);
|
|
$totalOrderHpp += ($hpp * $qty);
|
|
|
|
OrderItem::factory()->create([
|
|
'order_id' => $order->id,
|
|
'user_id' => $users->random()->id,
|
|
'product_id' => $product->id,
|
|
'qty' => $qty,
|
|
'price' => $price,
|
|
'total' => $itemTotal,
|
|
'created_at' => $order->created_at,
|
|
]);
|
|
|
|
$product->decrement('stock', $qty);
|
|
$totalOrderPrice += $itemTotal;
|
|
}
|
|
|
|
$discount = rand(0, 1) ? rand(5000, 20000) : 0;
|
|
$finalTotal = max(0, $totalOrderPrice - $discount);
|
|
|
|
$order->update([
|
|
'hpp' => $totalOrderHpp,
|
|
'discount' => $discount,
|
|
'total' => $finalTotal,
|
|
'payment' => $finalTotal, // Assume fully paid
|
|
]);
|
|
});
|
|
}
|
|
}
|