refactor: standardize variable naming in query closures across service classes for improved readability

This commit is contained in:
Yoga Pangestu 2026-06-22 12:53:09 +07:00
parent f83def0e8a
commit f38f61fe45
8 changed files with 60 additions and 59 deletions

View File

@ -99,8 +99,8 @@ public function destroy(Role $role): RedirectResponse
try { try {
$this->roleService->delete($role); $this->roleService->delete($role);
$this->flashDeleted('Role'); $this->flashDeleted('Role');
} catch (\InvalidArgumentException $e) { } catch (\InvalidArgumentException $exception) {
$this->flashError($e->getMessage()); $this->flashError($exception->getMessage());
} }
return redirect()->route('admin.system.roles.index'); return redirect()->route('admin.system.roles.index');

View File

@ -6,6 +6,7 @@
use App\Models\SystemConfiguration; use App\Models\SystemConfiguration;
use App\Support\Media\MediaPresenter; use App\Support\Media\MediaPresenter;
use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Foundation\Queue\Queueable; use Illuminate\Foundation\Queue\Queueable;
use Minishlink\WebPush\Subscription; use Minishlink\WebPush\Subscription;
use Minishlink\WebPush\WebPush; use Minishlink\WebPush\WebPush;
@ -91,8 +92,8 @@ private function resolveSubscriptions()
if ($this->userId !== null) { if ($this->userId !== null) {
$query->where('user_id', $this->userId); $query->where('user_id', $this->userId);
} elseif (! empty($this->roles)) { } elseif (! empty($this->roles)) {
$query->whereHas('user', function ($q): void { $query->whereHas('user', function (Builder $userQuery): void {
$q->whereHas('roles', fn ($r) => $r->whereIn('name', $this->roles)); $userQuery->whereHas('roles', fn (Builder $roleQuery) => $roleQuery->whereIn('name', $this->roles));
}); });
} }

View File

@ -112,7 +112,7 @@ public function openCurrentPeriod(?User $closedBy = null): PayrollPeriod
{ {
$user = $closedBy $user = $closedBy
?? auth()->user() ?? auth()->user()
?? User::query()->whereHas('roles', fn ($q) => $q->whereIn('name', [Role::DEVELOPER->value, Role::OWNER->value]))->first() ?? User::query()->whereHas('roles', fn (Builder $roleQuery) => $roleQuery->whereIn('name', [Role::DEVELOPER->value, Role::OWNER->value]))->first()
?? User::query()->first(); ?? User::query()->first();
$period = DB::transaction(function () use ($user): PayrollPeriod { $period = DB::transaction(function () use ($user): PayrollPeriod {

View File

@ -902,7 +902,7 @@ private function formatQuantityInput(float $value): string
private function appendCostPreview(Cutting $cutting): void private function appendCostPreview(Cutting $cutting): void
{ {
$cutting->setAttribute('total_result_pieces', (int) $cutting->results->sum('cutting_result')); $cutting->setAttribute('total_result_pieces', (int) $cutting->results->sum('cutting_result'));
$cutting->setAttribute('total_material_usage', (float) $cutting->materials->sum(fn (CuttingMaterial $m) => (float) $m->material_usage - (float) $m->remaining_material)); $cutting->setAttribute('total_material_usage', (float) $cutting->materials->sum(fn (CuttingMaterial $material) => (float) $material->material_usage - (float) $material->remaining_material));
$totalMaterialCost = $cutting->total_material_cost ?? $this->calculateTotalMaterialCost($cutting); $totalMaterialCost = $cutting->total_material_cost ?? $this->calculateTotalMaterialCost($cutting);
$sewingCost = (int) ($cutting->sewing_cost ?? 0); $sewingCost = (int) ($cutting->sewing_cost ?? 0);

View File

@ -101,7 +101,7 @@ public function marketingOptions(): array
{ {
return User::query() return User::query()
->active() ->active()
->whereHas('roles', fn ($q) => $q->where('name', 'marketing')) ->whereHas('roles', fn (Builder $roleQuery) => $roleQuery->where('name', 'marketing'))
->with('profile:user_id,full_name') ->with('profile:user_id,full_name')
->orderBy('username') ->orderBy('username')
->get(['id', 'username']) ->get(['id', 'username'])

View File

@ -45,10 +45,10 @@ public function paginateForIndex(array $tableQuery, string $isActive, string $ca
$query->whereHas('categories', fn (Builder $query) => $query->where('categories.id', $categoryId)); $query->whereHas('categories', fn (Builder $query) => $query->where('categories.id', $categoryId));
}) })
->when($stockStatus === 'out_of_stock', function (Builder $query): void { ->when($stockStatus === 'out_of_stock', function (Builder $query): void {
$query->whereHas('variants', fn (Builder $q) => $q->where('stock', '<=', 0)); $query->whereHas('variants', fn (Builder $variantQuery) => $variantQuery->where('stock', '<=', 0));
}) })
->when($stockStatus === 'low_stock', function (Builder $query): void { ->when($stockStatus === 'low_stock', function (Builder $query): void {
$query->whereHas('variants', fn (Builder $q) => $q->where('stock', '>', 0)->where('stock', '<', ProductVariant::minStock())); $query->whereHas('variants', fn (Builder $variantQuery) => $variantQuery->where('stock', '>', 0)->where('stock', '<', ProductVariant::minStock()));
}); });
$this->applySorting($query, $tableQuery['sort'], $tableQuery['direction']); $this->applySorting($query, $tableQuery['sort'], $tableQuery['direction']);

View File

@ -39,14 +39,14 @@ public function paginateForIndex(array $tableQuery, string $isActive, string $st
}) })
->when($isActive !== '', fn (Builder $query) => $query->where('is_active', $isActive === '1')) ->when($isActive !== '', fn (Builder $query) => $query->where('is_active', $isActive === '1'))
->when($stockStatus === 'out_of_stock', function (Builder $query): void { ->when($stockStatus === 'out_of_stock', function (Builder $query): void {
$query->whereHas('prices', fn (Builder $q) => $q->where('stock', '<=', 0)); $query->whereHas('prices', fn (Builder $priceQuery) => $priceQuery->where('stock', '<=', 0));
}) })
->when($stockStatus === 'low_stock', function (Builder $query): void { ->when($stockStatus === 'low_stock', function (Builder $query): void {
$query->whereHas('prices', function (Builder $q): void { $query->whereHas('prices', function (Builder $priceQuery): void {
$q->where('stock', '>', 0)->where(function (Builder $q): void { $priceQuery->where('stock', '>', 0)->where(function (Builder $priceQuery): void {
foreach (RawMaterialUnit::cases() as $unit) { foreach (RawMaterialUnit::cases() as $unit) {
$q->orWhere(function (Builder $q) use ($unit): void { $priceQuery->orWhere(function (Builder $priceQuery) use ($unit): void {
$q->whereHas('rawMaterial', fn (Builder $rm) => $rm->where('unit', $unit)) $priceQuery->whereHas('rawMaterial', fn (Builder $rawMaterialQuery) => $rawMaterialQuery->where('unit', $unit))
->where('stock', '<', $unit->minStock()); ->where('stock', '<', $unit->minStock());
}); });
} }

View File

@ -31,11 +31,11 @@ class DashboardService
{ {
public function getRawMaterialStock(): array public function getRawMaterialStock(): array
{ {
$data = RawMaterialPrice::query() $stockSummary = RawMaterialPrice::query()
->selectRaw('SUM(stock) as total_stock, SUM(stock * price) as total_value') ->selectRaw('SUM(stock) as total_stock, SUM(stock * price) as total_value')
->first(); ->first();
$byUnit = RawMaterialPrice::query() $stockByUnit = RawMaterialPrice::query()
->join('raw_materials', 'raw_material_prices.raw_material_id', '=', 'raw_materials.id') ->join('raw_materials', 'raw_material_prices.raw_material_id', '=', 'raw_materials.id')
->selectRaw('raw_materials.unit, SUM(raw_material_prices.stock) as total_stock') ->selectRaw('raw_materials.unit, SUM(raw_material_prices.stock) as total_stock')
->groupBy('raw_materials.unit') ->groupBy('raw_materials.unit')
@ -46,19 +46,19 @@ public function getRawMaterialStock(): array
->toArray(); ->toArray();
return [ return [
'total_stock' => (float) ($data->total_stock ?? 0), 'total_stock' => (float) ($stockSummary->total_stock ?? 0),
'total_value' => (int) ($data->total_value ?? 0), 'total_value' => (int) ($stockSummary->total_value ?? 0),
'by_unit' => $byUnit, 'by_unit' => $stockByUnit,
]; ];
} }
public function getProductStock(): array public function getProductStock(): array
{ {
$data = ProductVariant::query() $variantSummary = ProductVariant::query()
->selectRaw('SUM(stock) as total_stock, SUM(reject_stock) as total_reject, COUNT(*) as total_variants') ->selectRaw('SUM(stock) as total_stock, SUM(reject_stock) as total_reject, COUNT(*) as total_variants')
->first(); ->first();
$totalStock = (int) ($data->total_stock ?? 0); $totalStock = (int) ($variantSummary->total_stock ?? 0);
$totalValue = Cutting::query() $totalValue = Cutting::query()
->whereNotNull('cost_per_unit') ->whereNotNull('cost_per_unit')
@ -71,9 +71,9 @@ public function getProductStock(): array
return [ return [
'total_stock' => $totalStock, 'total_stock' => $totalStock,
'total_reject' => (int) ($data->total_reject ?? 0), 'total_reject' => (int) ($variantSummary->total_reject ?? 0),
'total_value' => (int) ($totalValue ?? 0), 'total_value' => (int) ($totalValue ?? 0),
'total_variants' => (int) ($data->total_variants ?? 0), 'total_variants' => (int) ($variantSummary->total_variants ?? 0),
'total_products' => $totalProducts, 'total_products' => $totalProducts,
'total_categories' => $totalCategories, 'total_categories' => $totalCategories,
]; ];
@ -170,14 +170,14 @@ public function getTopProducts(): array
public function getPurchaseSummary(): array public function getPurchaseSummary(): array
{ {
$data = Purchase::query() $purchaseSummary = Purchase::query()
->selectRaw('COUNT(*) as total_purchases, SUM(total) as total_spent, SUM(discount) as total_discount') ->selectRaw('COUNT(*) as total_purchases, SUM(total) as total_spent, SUM(discount) as total_discount')
->first(); ->first();
return [ return [
'total_purchases' => (int) ($data->total_purchases ?? 0), 'total_purchases' => (int) ($purchaseSummary->total_purchases ?? 0),
'total_spent' => (int) ($data->total_spent ?? 0), 'total_spent' => (int) ($purchaseSummary->total_spent ?? 0),
'total_discount' => (int) ($data->total_discount ?? 0), 'total_discount' => (int) ($purchaseSummary->total_discount ?? 0),
]; ];
} }
@ -272,7 +272,7 @@ public function getOrderStats(): array
public function getRevenueSummary(): array public function getRevenueSummary(): array
{ {
$data = Order::completed() $revenueSummary = Order::completed()
->selectRaw('SUM(total_amount) as total_revenue, SUM(discount) as total_discount, SUM(shipping_cost) as total_shipping, COUNT(*) as total_orders, AVG(total_amount) as avg_order') ->selectRaw('SUM(total_amount) as total_revenue, SUM(discount) as total_discount, SUM(shipping_cost) as total_shipping, COUNT(*) as total_orders, AVG(total_amount) as avg_order')
->first(); ->first();
@ -282,13 +282,13 @@ public function getRevenueSummary(): array
->sum(fn ($order) => (int) ($order->marketplace_settings_snapshot['total_fee_amount'] ?? 0)); ->sum(fn ($order) => (int) ($order->marketplace_settings_snapshot['total_fee_amount'] ?? 0));
return [ return [
'total_revenue' => (int) ($data->total_revenue ?? 0), 'total_revenue' => (int) ($revenueSummary->total_revenue ?? 0),
'total_discount' => (int) ($data->total_discount ?? 0), 'total_discount' => (int) ($revenueSummary->total_discount ?? 0),
'total_marketplace_fees' => $totalMarketplaceFees, 'total_marketplace_fees' => $totalMarketplaceFees,
'total_potongan' => (int) ($data->total_discount ?? 0) + $totalMarketplaceFees, 'total_potongan' => (int) ($revenueSummary->total_discount ?? 0) + $totalMarketplaceFees,
'total_shipping' => (int) ($data->total_shipping ?? 0), 'total_shipping' => (int) ($revenueSummary->total_shipping ?? 0),
'total_orders' => (int) ($data->total_orders ?? 0), 'total_orders' => (int) ($revenueSummary->total_orders ?? 0),
'avg_order' => (int) ($data->avg_order ?? 0), 'avg_order' => (int) ($revenueSummary->avg_order ?? 0),
]; ];
} }
@ -327,8 +327,8 @@ public function getCashAccounts(): array
public function getMonthlyCashFlow(): array public function getMonthlyCashFlow(): array
{ {
$months = collect(); $months = collect();
for ($i = 5; $i >= 0; $i--) { for ($monthOffset = 5; $monthOffset >= 0; $monthOffset--) {
$date = Carbon::now()->subMonths($i); $date = Carbon::now()->subMonths($monthOffset);
$months->push([ $months->push([
'year' => $date->year, 'year' => $date->year,
'month' => $date->month, 'month' => $date->month,
@ -340,7 +340,7 @@ public function getMonthlyCashFlow(): array
$start = Carbon::create($month['year'], $month['month'], 1)->startOfMonth(); $start = Carbon::create($month['year'], $month['month'], 1)->startOfMonth();
$end = $start->copy()->endOfMonth(); $end = $start->copy()->endOfMonth();
$data = CashTransaction::query() $monthlyTransactions = CashTransaction::query()
->whereBetween('created_at', [$start, $end]) ->whereBetween('created_at', [$start, $end])
->selectRaw(" ->selectRaw("
COALESCE(SUM(CASE WHEN type = 'deposit' THEN amount ELSE 0 END), 0) as deposits, COALESCE(SUM(CASE WHEN type = 'deposit' THEN amount ELSE 0 END), 0) as deposits,
@ -350,8 +350,8 @@ public function getMonthlyCashFlow(): array
return [ return [
'label' => $month['label'], 'label' => $month['label'],
'deposits' => (int) $data->deposits, 'deposits' => (int) $monthlyTransactions->deposits,
'withdrawals' => (int) $data->withdrawals, 'withdrawals' => (int) $monthlyTransactions->withdrawals,
]; ];
}); });
@ -360,14 +360,14 @@ public function getMonthlyCashFlow(): array
public function getMonthlyExpenses(Carbon $startOfMonth, Carbon $endOfMonth): array public function getMonthlyExpenses(Carbon $startOfMonth, Carbon $endOfMonth): array
{ {
$data = Expense::query() $monthlyExpenses = Expense::query()
->whereBetween('created_at', [$startOfMonth, $endOfMonth]) ->whereBetween('created_at', [$startOfMonth, $endOfMonth])
->selectRaw('COALESCE(SUM(amount), 0) as total, COUNT(*) as count') ->selectRaw('COALESCE(SUM(amount), 0) as total, COUNT(*) as count')
->first(); ->first();
return [ return [
'total' => (int) ($data->total ?? 0), 'total' => (int) ($monthlyExpenses->total ?? 0),
'count' => (int) ($data->count ?? 0), 'count' => (int) ($monthlyExpenses->count ?? 0),
]; ];
} }
@ -447,9 +447,9 @@ public function getPayrollSummary(Carbon $startOfMonth, Carbon $endOfMonth): arr
public function getLeaveRequestSummary(Carbon $startOfMonth, Carbon $endOfMonth): array public function getLeaveRequestSummary(Carbon $startOfMonth, Carbon $endOfMonth): array
{ {
$data = LeaveRequest::query() $leaveRequestSummary = LeaveRequest::query()
->where(function ($q) use ($startOfMonth, $endOfMonth) { ->where(function ($query) use ($startOfMonth, $endOfMonth) {
$q->whereBetween('start_date', [$startOfMonth, $endOfMonth]) $query->whereBetween('start_date', [$startOfMonth, $endOfMonth])
->orWhereBetween('end_date', [$startOfMonth, $endOfMonth]); ->orWhereBetween('end_date', [$startOfMonth, $endOfMonth]);
}) })
->selectRaw(" ->selectRaw("
@ -461,10 +461,10 @@ public function getLeaveRequestSummary(Carbon $startOfMonth, Carbon $endOfMonth)
->first(); ->first();
return [ return [
'total' => (int) ($data->total ?? 0), 'total' => (int) ($leaveRequestSummary->total ?? 0),
'pending' => (int) ($data->pending_count ?? 0), 'pending' => (int) ($leaveRequestSummary->pending_count ?? 0),
'approved' => (int) ($data->approved_count ?? 0), 'approved' => (int) ($leaveRequestSummary->approved_count ?? 0),
'rejected' => (int) ($data->rejected_count ?? 0), 'rejected' => (int) ($leaveRequestSummary->rejected_count ?? 0),
]; ];
} }
@ -509,8 +509,8 @@ public function getAttendanceToday(): array
public function getMonthlyRevenueTrend(): array public function getMonthlyRevenueTrend(): array
{ {
$months = collect(); $months = collect();
for ($i = 5; $i >= 0; $i--) { for ($monthOffset = 5; $monthOffset >= 0; $monthOffset--) {
$date = Carbon::now()->subMonths($i); $date = Carbon::now()->subMonths($monthOffset);
$months->push([ $months->push([
'year' => $date->year, 'year' => $date->year,
'month' => $date->month, 'month' => $date->month,
@ -522,15 +522,15 @@ public function getMonthlyRevenueTrend(): array
$start = Carbon::create($month['year'], $month['month'], 1)->startOfMonth(); $start = Carbon::create($month['year'], $month['month'], 1)->startOfMonth();
$end = $start->copy()->endOfMonth(); $end = $start->copy()->endOfMonth();
$data = Order::completed() $monthlyRevenue = Order::completed()
->whereBetween('created_at', [$start, $end]) ->whereBetween('created_at', [$start, $end])
->selectRaw('COALESCE(SUM(total_amount), 0) as total, COUNT(*) as count') ->selectRaw('COALESCE(SUM(total_amount), 0) as total, COUNT(*) as count')
->first(); ->first();
return [ return [
'label' => $month['label'], 'label' => $month['label'],
'total' => (int) $data->total, 'total' => (int) $monthlyRevenue->total,
'count' => (int) $data->count, 'count' => (int) $monthlyRevenue->count,
]; ];
}); });
@ -540,8 +540,8 @@ public function getMonthlyRevenueTrend(): array
public function getMonthlyPurchaseTrend(): array public function getMonthlyPurchaseTrend(): array
{ {
$months = collect(); $months = collect();
for ($i = 5; $i >= 0; $i--) { for ($monthOffset = 5; $monthOffset >= 0; $monthOffset--) {
$date = Carbon::now()->subMonths($i); $date = Carbon::now()->subMonths($monthOffset);
$months->push([ $months->push([
'year' => $date->year, 'year' => $date->year,
'month' => $date->month, 'month' => $date->month,
@ -553,15 +553,15 @@ public function getMonthlyPurchaseTrend(): array
$start = Carbon::create($month['year'], $month['month'], 1)->startOfMonth(); $start = Carbon::create($month['year'], $month['month'], 1)->startOfMonth();
$end = $start->copy()->endOfMonth(); $end = $start->copy()->endOfMonth();
$data = Purchase::query() $monthlyPurchases = Purchase::query()
->whereBetween('created_at', [$start, $end]) ->whereBetween('created_at', [$start, $end])
->selectRaw('COALESCE(SUM(total), 0) as total, COUNT(*) as count') ->selectRaw('COALESCE(SUM(total), 0) as total, COUNT(*) as count')
->first(); ->first();
return [ return [
'label' => $month['label'], 'label' => $month['label'],
'total' => (int) $data->total, 'total' => (int) $monthlyPurchases->total,
'count' => (int) $data->count, 'count' => (int) $monthlyPurchases->count,
]; ];
}); });