store-manage/app/Services/StatisticService.php

45 lines
1.5 KiB
PHP

<?php
namespace App\Services;
use App\Admin\Filters\LedgerFilter;
use App\Admin\Filters\StoreFilter;
use App\Models\Ledger;
use App\Models\Store;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;
class StatisticService
{
/**
* 门店统计
*/
public function stores(array $input = [], array $sorts = []): array
{
$storeLedgerStats = Ledger::select(['store_id', DB::raw('SUM(sales) as sales'), DB::raw('SUM(expenditure) as expenditure')])
->filter(Arr::only($input, ['date_range', 'start_at', 'end_at']), LedgerFilter::class)
->groupBy('store_id');
$stores = Store::filter(Arr::only($input, ['store_id', 'region']), StoreFilter::class)
->leftJoinSub($storeLedgerStats, 'store_ledger_stats', fn ($join) => $join->on('stores.id', '=', 'store_ledger_stats.store_id'))
->when($sorts, function ($query, $sorts) {
foreach ($sorts as $sort) {
$query->orderBy($sort[0], $sort[1]);
}
})
->get();
return $stores->map(function (Store $store, $key) {
return [
'ranking' => $key + 1,
'store' => [
'id' => $store->id,
'title' => $store->title,
],
'sales' => trim_zeros($store->sales ?: 0),
'expenditure' => trim_zeros($store->expenditure ?: 0),
];
})->all();
}
}