2026-01-06 16:17:12 +08:00
< ? php
namespace App\Http\Controllers ;
use App\Models\Product ;
use App\Models\Vendor ;
use App\Models\PurchaseOrder ;
use App\Models\Warehouse ;
use App\Models\Inventory ;
2026-01-22 15:39:35 +08:00
use App\Models\WarehouseProductSafetyStock ;
2026-01-06 16:17:12 +08:00
use Inertia\Inertia ;
use Illuminate\Http\Request ;
2026-01-22 15:39:35 +08:00
use Illuminate\Support\Facades\DB ;
2026-01-06 16:17:12 +08:00
class DashboardController extends Controller
{
public function index ()
{
2026-01-15 13:56:11 +08:00
$centralDomains = config ( 'tenancy.central_domains' , []);
2026-01-16 09:28:29 +08:00
$demoPort = config ( 'tenancy.demo_tenant_port' );
if (( ! $demoPort || request () -> getPort () != $demoPort ) && in_array ( request () -> getHost (), $centralDomains )) {
2026-01-15 13:56:11 +08:00
return redirect () -> route ( 'landlord.dashboard' );
}
2026-01-22 15:39:35 +08:00
// 計算低庫存數量:各商品在各倉庫的總量 < 安全庫存
$lowStockCount = DB :: table ( 'warehouse_product_safety_stocks as ss' )
-> join ( DB :: raw ( '(SELECT warehouse_id, product_id, SUM(quantity) as total_qty FROM inventories WHERE deleted_at IS NULL GROUP BY warehouse_id, product_id) as inv' ),
function ( $join ) {
$join -> on ( 'ss.warehouse_id' , '=' , 'inv.warehouse_id' )
-> on ( 'ss.product_id' , '=' , 'inv.product_id' );
})
-> whereRaw ( 'inv.total_qty <= ss.safety_stock' )
-> count ();
2026-01-06 16:17:12 +08:00
$stats = [
'productsCount' => Product :: count (),
'vendorsCount' => Vendor :: count (),
'purchaseOrdersCount' => PurchaseOrder :: count (),
'warehousesCount' => Warehouse :: count (),
'totalInventoryValue' => Inventory :: join ( 'products' , 'inventories.product_id' , '=' , 'products.id' )
2026-01-22 15:39:35 +08:00
-> sum ( 'inventories.quantity' ),
2026-01-06 16:17:12 +08:00
'pendingOrdersCount' => PurchaseOrder :: where ( 'status' , 'pending' ) -> count (),
2026-01-22 15:39:35 +08:00
'lowStockCount' => $lowStockCount ,
2026-01-06 16:17:12 +08:00
];
return Inertia :: render ( 'Dashboard' , [
'stats' => $stats ,
]);
}
}