CaiWuXiTong/modules/EcommerceFinance/Repositories/SupplierPayableForecastSummaryRepository.php
苏木 bf8778bfcd feat(供应商货款预估): 接入本月汇总表 (#1559)
Co-authored-by: 苏木 <594326199@qq.com>
Co-committed-by: 苏木 <594326199@qq.com>
2026-11-30 13:56:12 +08:00

355 lines
13 KiB
PHP

<?php
namespace Modules\EcommerceFinance\Repositories;
use Illuminate\Database\ConnectionInterface;
use Illuminate\Database\DatabaseManager;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Schema;
class SupplierPayableForecastSummaryRepository
{
/**
* 仅用于补齐供应商主体和本月扣款资料;货款、退货金额始终来自预估明细。
*/
public const METADATA_DATASET = 'jiansun.dbo.fys_supplierPaymentSummary';
public const METADATA_TABLE = 'js_supplier_payment_summary';
private readonly ConnectionInterface $connection;
private readonly string $connectionName;
public function __construct(
DatabaseManager $database,
private readonly SupplierPayableForecastRepository $details,
) {
$this->connectionName = (string) config('upstream_mirrors.connection', 'business_mirror');
$this->connection = $database->connection($this->connectionName);
}
/**
* @param array{month?:string,keyword?:string} $filters
* @return array{
* ready:bool,
* sync_status:array<string,mixed>,
* months:list<string>,
* filters:array{month:string,keyword:string},
* total:int,
* rows:list<array<string,mixed>>,
* page:int,
* per_page:int,
* totals:array{subtotal:float,supplier_balance:float,goods_amount:float,return_amount:float}
* }
*/
public function paginate(array $filters, int $page, int $perPage = 20): array
{
$syncStatus = $this->syncStatus();
$months = $this->availableMonths();
$month = $this->resolveMonth((string) ($filters['month'] ?? ''), $months);
$keyword = mb_substr(trim((string) ($filters['keyword'] ?? '')), 0, 120);
$perPage = min(max($perPage, 1), 100);
$page = max($page, 1);
$result = [
'ready' => $syncStatus['ready'],
'sync_status' => $syncStatus,
'months' => $months,
'filters' => ['month' => $month, 'keyword' => $keyword],
'total' => 0,
'rows' => [],
'page' => 1,
'per_page' => $perPage,
'totals' => [
'subtotal' => 0.0,
'supplier_balance' => 0.0,
'goods_amount' => 0.0,
'return_amount' => 0.0,
],
];
if (! $syncStatus['ready'] || $month === '') {
return $result;
}
[$dateFrom, $dateTo] = $this->monthWindow($month);
if ($dateTo === null || Carbon::parse($dateTo)->lt(Carbon::parse($dateFrom))) {
return $result;
}
$goodsStatus = $this->details->syncStatus();
$returnStatus = $this->details->returnSyncStatus();
$goodsAmounts = $goodsStatus['ready']
? $this->details->goodsAmountsBySupplier([
'date_from' => $dateFrom,
'date_to' => $dateTo,
'keyword' => '',
])
: [];
$returnAmounts = $returnStatus['ready']
? $this->details->returnAmountsBySupplier([
'date_from' => $dateFrom,
'date_to' => $dateTo,
'keyword' => '',
])
: [];
$suppliers = array_values(array_unique(array_merge(
array_keys($goodsAmounts),
array_keys($returnAmounts),
)));
if ($suppliers === []) {
return $result;
}
$currentMetadata = $this->metadataForMonth($month);
$companyMap = $this->latestCompanyMap($suppliers);
$rows = [];
foreach ($suppliers as $supplier) {
$metadata = $currentMetadata[$supplier] ?? [];
$company = trim((string) ($metadata['company'] ?? ''));
if ($company === '') {
$company = $companyMap[$supplier] ?? '';
}
if ($keyword !== ''
&& mb_stripos($supplier, $keyword, 0, 'UTF-8') === false
&& mb_stripos($company, $keyword, 0, 'UTF-8') === false) {
continue;
}
$goodsAmount = $this->money($goodsAmounts[$supplier] ?? 0);
$returnAmount = $this->money($returnAmounts[$supplier] ?? 0);
$subtotal = $this->money($goodsAmount - $returnAmount);
$expressFreight = $this->money($metadata['express_freight'] ?? 0);
$advanceLoan = $this->money($metadata['advance_loan'] ?? 0);
$invoiceDeduction = $this->money($metadata['invoice_deduction'] ?? 0);
$boardDeduction = $this->money($metadata['board_deduction'] ?? 0);
$estimatedBoardDeduction = 0.0;
$sampleDeduction = $this->money($metadata['sample_deduction'] ?? 0);
$unpricedAdjustment = $this->money($metadata['unpriced_adjustment'] ?? 0);
$rows[] = [
'month' => $month,
'company' => $company,
'supplier' => $supplier,
'express_freight' => $expressFreight,
'goods_amount' => $goodsAmount,
'return_amount' => $returnAmount,
'advance_loan' => $advanceLoan,
'subtotal' => $subtotal,
'invoice_deduction' => $invoiceDeduction,
'board_deduction' => $boardDeduction,
'estimated_board_deduction' => $estimatedBoardDeduction,
'sample_deduction' => $sampleDeduction,
'estimated_amount' => null,
'unpriced_adjustment' => $unpricedAdjustment,
'supplier_balance' => $this->money(
$expressFreight
- $advanceLoan
+ $subtotal
- $invoiceDeduction
- $boardDeduction
- $estimatedBoardDeduction
- $sampleDeduction
+ $unpricedAdjustment,
),
];
}
usort($rows, static function (array $left, array $right): int {
return [$left['company'], $left['supplier']] <=> [$right['company'], $right['supplier']];
});
$total = count($rows);
$lastPage = max((int) ceil($total / $perPage), 1);
$page = min($page, $lastPage);
$totals = [
'subtotal' => $this->money(array_sum(array_column($rows, 'subtotal'))),
'supplier_balance' => $this->money(array_sum(array_column($rows, 'supplier_balance'))),
'goods_amount' => $this->money(array_sum(array_column($rows, 'goods_amount'))),
'return_amount' => $this->money(array_sum(array_column($rows, 'return_amount'))),
];
return array_replace($result, [
'total' => $total,
'rows' => array_slice($rows, ($page - 1) * $perPage, $perPage),
'page' => $page,
'totals' => $totals,
]);
}
/**
* @return array{
* ready:bool,
* code:string,
* status:string,
* last_succeeded_at:?string
* }
*/
public function syncStatus(): array
{
$goods = $this->details->syncStatus();
$returns = $this->details->returnSyncStatus();
$ready = $goods['ready'] || $returns['ready'];
$initializing = $goods['code'] === 'initializing' || $returns['code'] === 'initializing';
$succeededAt = array_filter([
$goods['last_succeeded_at'] ?? null,
$returns['last_succeeded_at'] ?? null,
], static fn (mixed $value): bool => $value !== null && $value !== '');
return [
'ready' => $ready,
'code' => $ready ? 'ready' : ($initializing ? 'initializing' : 'pending'),
'status' => $ready ? 'ready' : ($initializing ? 'running' : 'pending'),
'last_succeeded_at' => $succeededAt === [] ? null : max($succeededAt),
];
}
/** @return list<string> */
public function availableMonths(): array
{
$start = Carbon::createFromFormat(
'!Y-m-d',
SupplierPayableForecastRepository::DEFAULT_FROM,
'Asia/Shanghai',
)->startOfMonth();
$current = now('Asia/Shanghai')->startOfMonth();
if ($start->gt($current)) {
return [$current->format('Y-m')];
}
$months = [];
while ($start->lte($current)) {
$months[] = $start->format('Y-m');
$start->addMonthNoOverflow();
}
return array_reverse($months);
}
/** @param list<string> $months */
private function resolveMonth(string $requested, array $months): string
{
$requested = trim($requested);
if (preg_match('/^\d{4}-(0[1-9]|1[0-2])$/D', $requested) === 1
&& in_array($requested, $months, true)) {
return $requested;
}
return $months[0] ?? '';
}
/** @return array{0:string,1:?string} */
private function monthWindow(string $month): array
{
$start = Carbon::createFromFormat('!Y-m-d H:i:s', $month . '-01 00:00:00', 'Asia/Shanghai');
$closedThrough = now('Asia/Shanghai')->subDay()->endOfDay();
$monthEnd = $start->copy()->endOfMonth()->endOfDay();
$end = $monthEnd->gt($closedThrough) ? $closedThrough : $monthEnd;
if ($end->lt($start)) {
return [$start->format('Y-m-d H:i:s'), null];
}
return [$start->format('Y-m-d H:i:s'), $end->format('Y-m-d H:i:s')];
}
/**
* @return array<string,array{
* company:string,
* express_freight:mixed,
* advance_loan:mixed,
* invoice_deduction:mixed,
* board_deduction:mixed,
* sample_deduction:mixed,
* unpriced_adjustment:mixed
* }>
*/
private function metadataForMonth(string $month): array
{
if (! Schema::connection($this->connectionName)->hasTable(self::METADATA_TABLE)) {
return [];
}
$rows = $this->connection->table(self::METADATA_TABLE)
->where('Month', $month)
->selectRaw('TRIM(supplier) AS supplier, TRIM(company) AS company')
->selectRaw('COALESCE(SUM(ExpFieght), 0) AS express_freight')
->selectRaw('COALESCE(SUM(advloan), 0) AS advance_loan')
->selectRaw('COALESCE(SUM(invoiceDct), 0) AS invoice_deduction')
->selectRaw('COALESCE(SUM(boardDct), 0) AS board_deduction')
->selectRaw('COALESCE(SUM(specimenDct), 0) AS sample_deduction')
->selectRaw('COALESCE(SUM(unpriced), 0) AS unpriced_adjustment')
->groupByRaw('TRIM(supplier), TRIM(company)')
->get();
$metadata = [];
foreach ($rows as $row) {
$supplier = trim((string) ($row->supplier ?? ''));
if ($supplier === '') {
continue;
}
$entry = $metadata[$supplier] ?? [
'company' => '',
'express_freight' => 0.0,
'advance_loan' => 0.0,
'invoice_deduction' => 0.0,
'board_deduction' => 0.0,
'sample_deduction' => 0.0,
'unpriced_adjustment' => 0.0,
];
$company = trim((string) ($row->company ?? ''));
if ($entry['company'] === '' && $company !== '') {
$entry['company'] = $company;
}
foreach ([
'express_freight',
'advance_loan',
'invoice_deduction',
'board_deduction',
'sample_deduction',
'unpriced_adjustment',
] as $field) {
$entry[$field] = (float) $entry[$field] + (float) ($row->{$field} ?? 0);
}
$metadata[$supplier] = $entry;
}
return $metadata;
}
/**
* @param list<string> $suppliers
* @return array<string,string>
*/
private function latestCompanyMap(array $suppliers): array
{
if ($suppliers === [] || ! Schema::connection($this->connectionName)->hasTable(self::METADATA_TABLE)) {
return [];
}
$rows = $this->connection->table(self::METADATA_TABLE)
->whereIn('supplier', $suppliers)
->whereNotNull('company')
->where('company', '!=', '')
->orderByDesc('Month')
->orderByDesc('id')
->get(['supplier', 'company']);
$companies = [];
foreach ($rows as $row) {
$supplier = trim((string) ($row->supplier ?? ''));
if ($supplier !== '' && ! isset($companies[$supplier])) {
$companies[$supplier] = trim((string) ($row->company ?? ''));
}
}
return $companies;
}
private function money(mixed $value): float
{
$number = round((float) ($value ?? 0), 2);
return abs($number) < 0.005 ? 0.0 : $number;
}
}