84 lines
2.5 KiB
PHP
84 lines
2.5 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;
|
|
}
|
|
|
|
// Random Historical Data (Last 1 Year)
|
|
Order::factory(50)->create()->each(fn ($order) => $this->createOrderWithItems($order, $users, $products));
|
|
|
|
// Data Kemarin
|
|
Order::factory(rand(5, 15))->create([
|
|
'created_at' => now()->subDay()->setHour(rand(8, 20)),
|
|
])->each(fn ($order) => $this->createOrderWithItems($order, $users, $products));
|
|
|
|
// Data Hari Ini
|
|
Order::factory(rand(5, 15))->create([
|
|
'created_at' => now()->setHour(rand(8, 20)),
|
|
])->each(fn ($order) => $this->createOrderWithItems($order, $users, $products));
|
|
}
|
|
|
|
/**
|
|
* Helper method to create items for an order and update order totals.
|
|
*/
|
|
private function createOrderWithItems(Order $order, $users, $products): void
|
|
{
|
|
$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 cogs is 70% of price for simulation
|
|
$cogs = intval($price * 0.7);
|
|
$totalOrderHpp += ($cogs * $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([
|
|
'cogs' => $totalOrderHpp,
|
|
'subtotal' => $totalOrderPrice,
|
|
'discount' => $discount,
|
|
'total' => $finalTotal,
|
|
'payment' => $finalTotal, // Assume fully paid
|
|
]);
|
|
}
|
|
}
|