CaiWuXiTong/modules/EcommerceFinance/View/BillOffsetPageData.php

78 lines
2.7 KiB
PHP

<?php
namespace Modules\EcommerceFinance\View;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Collection;
use Modules\EcommerceFinance\Repositories\BillOffsetMirrorRepository;
use Throwable;
class BillOffsetPageData
{
public function __construct(private readonly BillOffsetMirrorRepository $bills)
{
}
/** @return array<string,mixed> */
public function page(): array
{
$filters = [
'from' => $this->date(request('from')) ?: now()->subDays(6)->toDateString(),
'to' => $this->date(request('to')) ?: now()->toDateString(),
'order_no' => $this->text(request('order_no')),
'shop_name' => $this->text(request('shop_name')),
'sku_id' => $this->text(request('sku_id')),
];
$page = max((int) request('page', 1), 1);
$limit = min(max((int) setting('default.list_limit', 25), 1), 100);
$rows = new LengthAwarePaginator([], 0, $limit, $page, [
'path' => request()->url(),
'query' => request()->except('page'),
]);
$summary = ['amount' => 0.0, 'count' => 0];
$sync = ['status' => 'unavailable', 'last_succeeded_at' => null];
$error = null;
try {
$result = $this->bills->paginate($filters, $page, $limit);
$rows = new LengthAwarePaginator(
Collection::make($result['data'] ?? []),
(int) ($result['total'] ?? 0),
$limit,
$page,
['path' => request()->url(), 'query' => request()->except('page')],
);
$summary = $result['summary'] ?? $summary;
$sync = $result['sync'] ?? $sync;
} catch (Throwable $exception) {
if (! str_contains($exception->getMessage(), 'bill_offset_mirror_not_ready')) {
report($exception);
}
$error = '账单冲减镜像尚未完成首次同步,当前不把空镜像解释为没有数据。';
}
return [
'view' => 'business.pages.order-data.bill-offset',
'billOffsetRows' => $rows,
'billOffsetFilters' => $filters,
'billOffsetSummary' => $summary,
'billOffsetSync' => $sync,
'billOffsetError' => $error,
];
}
private function text(mixed $value): string
{
return mb_substr(trim((string) $value), 0, 100);
}
private function date(mixed $value): string
{
$value = trim((string) $value);
if (preg_match('/^(\d{4})-(\d{2})-(\d{2})$/', $value, $matches) !== 1) {
return '';
}
return checkdate((int) $matches[2], (int) $matches[3], (int) $matches[1]) ? $value : '';
}
}