feat(供应商对账): 增加财务端对账进度汇总 (#1711)

财务端新增对账进度汇总,并支持展开查看需要对账、已确认、有差异和未上传账单的厂家名单。
Co-authored-by: 苏木 <594326199@qq.com>
Co-committed-by: 苏木 <594326199@qq.com>
This commit is contained in:
苏木 2026-12-03 18:33:29 +08:00 committed by sumu
parent d7b664ad53
commit aadf5682e2
6 changed files with 472 additions and 0 deletions

View File

@ -324,6 +324,116 @@ class SupplierPayableOverrideStore
->all();
}
/**
* 按厂家汇总指定筛选范围的数量和金额,供财务端进度概览使用。
*
* @return array<string,array{rows:int,qty:float,amount:float}>
*/
public function summarizeBySupplierForFilters(
string $dataset,
int $companyId,
string $month = '',
string $reconciler = '',
): array {
$connection = $this->connection();
$query = $connection->table('supplier_payable_overrides')
->where('company_id', $companyId)
->where('dataset', $dataset);
if ($month !== '') {
$this->whereMonth($query, $connection, $month, false);
}
if ($reconciler !== '') {
$query->where('values->reconciler', $reconciler);
}
$supplierExpression = $this->jsonStringExpression($connection, 'supplier');
$qtyExpression = $this->jsonNumberExpression($connection, 'qty');
$amountExpression = $this->jsonNumberExpression($connection, 'amount');
$rows = $query
->selectRaw("{$supplierExpression} AS supplier_name")
->selectRaw('COUNT(*) AS row_count')
->selectRaw("SUM({$qtyExpression}) AS qty_total")
->selectRaw("SUM({$amountExpression}) AS amount_total")
->groupByRaw($supplierExpression)
->get();
$result = [];
foreach ($rows as $row) {
$supplier = trim((string) ($row->supplier_name ?? ''));
if ($supplier === '') {
continue;
}
$result[$supplier] = [
'rows' => (int) ($row->row_count ?? 0),
'qty' => round((float) ($row->qty_total ?? 0), 4),
'amount' => round((float) ($row->amount_total ?? 0), 2),
];
}
ksort($result, SORT_NATURAL | SORT_FLAG_CASE);
return $result;
}
/**
* 按数据集前缀和业务月份批量汇总,供厂家对账单月度进度统计使用。
*
* @return array<string,array{rows:int,qty:float,amount:float}>
*/
public function summarizeByDatasetPrefixForMonth(
string $prefix,
int $companyId,
string $month = '',
string $monthField = 'createdAt',
string $qtyField = 'qty',
string $amountField = 'amount',
): array {
if ($prefix === ''
|| preg_match('/^[A-Za-z0-9_]+$/', $monthField) !== 1
|| preg_match('/^[A-Za-z0-9_]+$/', $qtyField) !== 1
|| preg_match('/^[A-Za-z0-9_]+$/', $amountField) !== 1) {
return [];
}
if ($month !== '' && preg_match('/^\d{4}-(0[1-9]|1[0-2])$/', $month) !== 1) {
return [];
}
$connection = $this->connection();
$query = $connection->table('supplier_payable_overrides')
->where('company_id', $companyId)
->where('dataset', 'like', addcslashes($prefix, '%_\\') . '%');
if ($month !== '') {
$query->whereRaw(
$this->jsonMonthExpression($connection, $monthField) . ' = ?',
[$month],
);
}
$qtyExpression = $this->jsonNumberExpression($connection, $qtyField);
$amountExpression = $this->jsonNumberExpression($connection, $amountField);
$rows = $query
->select('dataset')
->selectRaw('COUNT(*) AS row_count')
->selectRaw("SUM({$qtyExpression}) AS qty_total")
->selectRaw("SUM({$amountExpression}) AS amount_total")
->groupBy('dataset')
->get();
$result = [];
foreach ($rows as $row) {
$dataset = trim((string) ($row->dataset ?? ''));
if ($dataset === '') {
continue;
}
$result[$dataset] = [
'rows' => (int) ($row->row_count ?? 0),
'qty' => round((float) ($row->qty_total ?? 0), 4),
'amount' => round((float) ($row->amount_total ?? 0), 2),
];
}
return $result;
}
/**
* 只读取指定账期仍未定价的记录,避免月度自动定价把整张对账宽表载入内存。
*
@ -917,6 +1027,31 @@ class SupplierPayableOverrideStore
. 'ELSE ' . $summaryMonth . ' END';
}
private function jsonStringExpression(ConnectionInterface $connection, string $field): string
{
return $connection->getDriverName() === 'mysql'
? "TRIM(JSON_UNQUOTE(JSON_EXTRACT(`values`, '$.{$field}')))"
: "TRIM(json_extract(\"values\", '$.{$field}'))";
}
private function jsonNumberExpression(ConnectionInterface $connection, string $field): string
{
$text = $this->jsonStringExpression($connection, $field);
return $connection->getDriverName() === 'mysql'
? "CAST(COALESCE(NULLIF({$text}, ''), '0') AS DECIMAL(20,4))"
: "CAST(COALESCE(NULLIF({$text}, ''), '0') AS REAL)";
}
private function jsonMonthExpression(ConnectionInterface $connection, string $field): string
{
$text = $this->jsonStringExpression($connection, $field);
return $connection->getDriverName() === 'mysql'
? "LEFT(REPLACE(REPLACE(NULLIF(NULLIF({$text}, 'null'), ''), '/', '-'), '.', '-'), 7)"
: "substr(replace(replace(NULLIF(NULLIF({$text}, 'null'), ''), '/', '-'), '.', '-'), 1, 7)";
}
private function whereSupplier(\Illuminate\Database\Query\Builder $query, string $supplier): void
{
if ($this->supportsSupplierNameIndex()) {

View File

@ -77,6 +77,33 @@ class SupplierStatementStore
return false;
}
/**
* 按厂家汇总当前对账单在业务月份内的行数、数量和金额。
*
* @return array<string,array{rows:int,qty:float,amount:float}>
*/
public function totalsBySupplierForMonth(string $month, int $companyId): array
{
$datasets = $this->store->summarizeByDatasetPrefixForMonth(
self::PREFIX,
$companyId,
$month,
'createdAt',
'qty',
'amount',
);
$result = [];
foreach ($datasets as $dataset => $totals) {
$supplier = trim(substr($dataset, strlen(self::PREFIX)));
if ($supplier !== '') {
$result[$supplier] = $totals;
}
}
ksort($result, SORT_NATURAL | SORT_FLAG_CASE);
return $result;
}
/** @return list<string> 已经上传过对账单的厂家名称 */
public function uploadedSuppliers(int $companyId): array
{

View File

@ -135,6 +135,35 @@ class SupplierSummaryConfirmation
], $companyId);
}
/**
* 已经成功发送过货款确认的厂家;待厂家确认和厂家已确认都计入。
*
* @return list<string>
*/
public function sentSupplierNames(string $month, int $companyId): array
{
$suppliers = [];
foreach ($this->store->listRows(self::DATASET, $companyId) as $record) {
$recordMonth = trim((string) ($record['month'] ?? ''));
if ($month !== '' && $recordMonth !== $month) {
continue;
}
$supplier = trim((string) ($record['supplier'] ?? ''));
$status = trim((string) ($record['status'] ?? ''));
if ($supplier !== '' && in_array($status, [
self::STATUS_PENDING,
self::STATUS_CONFIRMED,
], true)) {
$suppliers[$supplier] = true;
}
}
$suppliers = array_keys($suppliers);
sort($suppliers, SORT_NATURAL | SORT_FLAG_CASE);
return $suppliers;
}
public function companyIdFromOutTrackId(string $outTrackId): ?int
{
if (preg_match('/^supplier-summary-c(\d+)-[a-f0-9]{16,128}$/', strtolower($outTrackId), $matches) !== 1) {

View File

@ -153,6 +153,15 @@ class SupplierReconciliationPageData
);
}
$reconciliationOverview = $selected === ''
? $this->financeReconciliationOverview(
$supplierNames,
$companyId,
$month,
$reconciler,
)
: null;
$returnLatestMonths = [];
$returnDisplayMonths = [];
$returnCounts = [];
@ -217,6 +226,7 @@ class SupplierReconciliationPageData
'supplierPerPage' => self::SUPPLIER_PER_PAGE,
'supplierQuery' => $supplierQuery,
'supplierNotFound' => $supplierNotFound,
'reconciliationOverview' => $reconciliationOverview,
'uploads' => $uploads,
'months' => $months,
'month' => $month,
@ -250,6 +260,83 @@ class SupplierReconciliationPageData
];
}
/**
* 财务端当前筛选范围的对账进度概览。
*
* @param list<string> $supplierNames
* @return array{
* month:string,
* total:array{count:int,suppliers:list<string>},
* confirmed:array{count:int,suppliers:list<string>},
* difference:array{count:int,suppliers:list<string>},
* not_uploaded:array{count:int,suppliers:list<string>}
* }
*/
private function financeReconciliationOverview(
array $supplierNames,
int $companyId,
string $month,
string $reconciler,
): array {
$mineDataset = PayablesFinalActions::DATASET_PREFIX . 'supplier:payment-reconciliation';
$mineTotals = $this->store->summarizeBySupplierForFilters(
$mineDataset,
$companyId,
$month,
$reconciler,
);
$supplierScope = array_fill_keys($supplierNames, true);
$reconciliationSuppliers = array_values(array_filter(
array_keys($mineTotals),
static fn (string $supplier): bool => isset($supplierScope[$supplier]),
));
sort($reconciliationSuppliers, SORT_NATURAL | SORT_FLAG_CASE);
$statementTotals = $this->statements->totalsBySupplierForMonth($month, $companyId);
$sentSuppliers = array_fill_keys(
$this->summaryConfirmations->sentSupplierNames($month, $companyId),
true,
);
$confirmed = [];
$differences = [];
$notUploaded = [];
foreach ($reconciliationSuppliers as $supplier) {
if (isset($sentSuppliers[$supplier])) {
$confirmed[] = $supplier;
}
$theirs = $statementTotals[$supplier] ?? null;
if ($theirs === null || (int) ($theirs['rows'] ?? 0) === 0) {
$notUploaded[] = $supplier;
continue;
}
$mine = $mineTotals[$supplier];
if (abs((float) $mine['qty'] - (float) $theirs['qty']) >= 0.005
|| abs((float) $mine['amount'] - (float) $theirs['amount']) >= 0.005) {
$differences[] = $supplier;
}
}
$payload = static function (array $suppliers): array {
sort($suppliers, SORT_NATURAL | SORT_FLAG_CASE);
return [
'count' => count($suppliers),
'suppliers' => array_values($suppliers),
];
};
return [
'month' => $month,
'total' => $payload($reconciliationSuppliers),
'confirmed' => $payload($confirmed),
'difference' => $payload($differences),
'not_uploaded' => $payload($notUploaded),
];
}
/** @return array<string,mixed> */
public function supplierData(): array
{

View File

@ -20,6 +20,24 @@
.supplier-reconciliation-page .sr-button.is-small { height: 26px; padding: 0 9px; font-size: .75rem; }
.supplier-reconciliation-page .sr-list-actions { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; }
.supplier-reconciliation-page .sr-list-actions form { margin: 0; }
.supplier-reconciliation-page .sr-overview { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 8px; }
.supplier-reconciliation-page .sr-overview-stat { min-width: 0; border: 1px solid var(--vip-border, #D8D2C7); border-radius: 8px; background: #fff; }
.supplier-reconciliation-page .sr-overview-stat summary { display: grid; gap: 3px; padding: 10px 12px; cursor: pointer; list-style: none; }
.supplier-reconciliation-page .sr-overview-stat summary::-webkit-details-marker { display: none; }
.supplier-reconciliation-page .sr-overview-stat summary::after { content: "点击查看明细"; margin-top: 2px; color: var(--vip-content-accent-dark, #856632); font-size: .6875rem; font-weight: 600; }
.supplier-reconciliation-page .sr-overview-stat[open] summary::after { content: "收起明细"; }
.supplier-reconciliation-page .sr-overview-stat.is-confirmed summary { border-top: 3px solid #53793E; }
.supplier-reconciliation-page .sr-overview-stat.is-difference summary { border-top: 3px solid #935F07; }
.supplier-reconciliation-page .sr-overview-stat.is-missing summary { border-top: 3px solid #006395; }
.supplier-reconciliation-page .sr-overview-stat.is-total summary { border-top: 3px solid var(--vip-content-accent, #B9954F); }
.supplier-reconciliation-page .sr-overview-label { color: #5B5343; font-size: .75rem; font-weight: 600; }
.supplier-reconciliation-page .sr-overview-value { color: var(--vip-content-ink, #171717); font-size: 1.375rem; font-weight: 700; line-height: 1.2; font-variant-numeric: tabular-nums; }
.supplier-reconciliation-page .sr-overview-detail { max-height: 18rem; overflow: auto; padding: 9px 12px 12px; border-top: 1px solid #EFEAE0; }
.supplier-reconciliation-page .sr-overview-names { display: flex; flex-wrap: wrap; gap: 6px; margin: 0; padding: 0; list-style: none; }
.supplier-reconciliation-page .sr-overview-name { display: inline-flex; min-height: 26px; align-items: center; padding: 0 8px; border: 1px solid #DED3BD; border-radius: 999px; background: #FCFAF5; color: var(--vip-content-accent-dark, #856632); font-size: .75rem; font-weight: 600; text-decoration: none; }
.supplier-reconciliation-page .sr-overview-name:hover,
.supplier-reconciliation-page .sr-overview-name:focus-visible { border-color: var(--vip-content-accent-dark, #856632); background: var(--vip-content-accent-soft, #F7F0DE); }
.supplier-reconciliation-page .sr-overview-empty { color: var(--vip-content-muted, #595959); font-size: .75rem; }
.supplier-reconciliation-page .sr-batch-toolbar { display: flex; flex-wrap: wrap; align-items: center; gap: 10px 16px; padding: 10px 12px; border: 1px solid #E4DCCB; border-radius: 8px; background: var(--vip-content-accent-soft, #F7F0DE); }
.supplier-reconciliation-page .sr-batch-selection { display: flex; align-items: center; gap: 7px; color: #5B5343; font-size: .8125rem; font-weight: 600; }
.supplier-reconciliation-page .sr-batch-selection input { width: 15px; height: 15px; accent-color: var(--vip-content-accent-dark, #856632); }
@ -132,9 +150,13 @@
@media (max-width: 900px) {
.supplier-reconciliation-page .sr-robot-form { grid-template-columns: minmax(0, 1fr); }
.supplier-reconciliation-page .sr-detail-actions { width: 100%; margin-left: 0; }
.supplier-reconciliation-page .sr-overview { grid-template-columns: repeat(2, minmax(0, 1fr)); }
.supplier-reconciliation-page .sr-summary-push { grid-template-columns: minmax(0, 1fr); }
.supplier-reconciliation-page .sr-push-basis-values { grid-template-columns: minmax(0, 1fr); }
}
@media (max-width: 560px) {
.supplier-reconciliation-page .sr-overview { grid-template-columns: minmax(0, 1fr); }
}
.supplier-reconciliation-page .sr-empty { padding: 28px; border: 1px dashed var(--vip-border, #D8D2C7); border-radius: 8px; color: var(--vip-content-muted, #595959); font-size: .8125rem; text-align: center; }
</style>
@ -374,12 +396,73 @@
整月退货会包含待确认、已确认和异议中记录,钉钉群发送汇总和明细表格链接,不再在群内堆叠明细。勾选本页多家已配置机器人的厂家后,可批量推送。
</p>
@php
$overviewDetailUrl = fn (string $supplier): string => route('business.pages.show', array_filter([
'section' => $section['slug'],
'page' => $page['slug'],
'month' => $month,
'reconciler' => $reconciler,
'supplier' => $supplier,
'supplier_page' => $supplierPage > 1 ? $supplierPage : null,
], static fn (mixed $value): bool => $value !== '' && $value !== null));
$overviewCards = [
[
'key' => 'total',
'label' => '需要对账厂家',
'className' => 'is-total',
'data' => $reconciliationOverview['total'],
],
[
'key' => 'confirmed',
'label' => '已确认(发送即计入)',
'className' => 'is-confirmed',
'data' => $reconciliationOverview['confirmed'],
],
[
'key' => 'difference',
'label' => '有差异',
'className' => 'is-difference',
'data' => $reconciliationOverview['difference'],
],
[
'key' => 'not_uploaded',
'label' => '未上传账单',
'className' => 'is-missing',
'data' => $reconciliationOverview['not_uploaded'],
],
];
$batchEligibleCount = count(array_filter(
$supplierListRows,
fn (string $supplier): bool => (int) ($returnCounts[$supplier] ?? 0) > 0
&& (bool) ($robotConfigurations[$supplier]['configured'] ?? false),
));
@endphp
<div class="sr-overview" aria-label="{{ $reconciliationOverview['month'] !== '' ? $reconciliationOverview['month'] : '全部月份' }}供应商对账进度">
@foreach ($overviewCards as $card)
<details class="sr-overview-stat {{ $card['className'] }}" data-overview="{{ $card['key'] }}">
<summary>
<span class="sr-overview-label">{{ $card['label'] }}</span>
<strong class="sr-overview-value">{{ number_format((int) ($card['data']['count'] ?? 0)) }} 家</strong>
</summary>
<div class="sr-overview-detail">
@if (($card['data']['suppliers'] ?? []) !== [])
<ul class="sr-overview-names">
@foreach ($card['data']['suppliers'] as $overviewSupplier)
<li>
<a class="sr-overview-name" href="{{ $overviewDetailUrl($overviewSupplier) }}">{{ $overviewSupplier }}</a>
</li>
@endforeach
</ul>
@else
<span class="sr-overview-empty">当前筛选范围没有厂家。</span>
@endif
</div>
</details>
@endforeach
</div>
<p class="sr-hint">
统计跟随月份和对账人筛选;需要对账厂家按当前账期我方货款对账数据统计,“有差异”按双方数量或金额合计不一致统计,
“未上传账单”按账单业务日期所属月份判断;已确认按“货款确认已成功发送”计数,厂家后续是否点击确认不影响这里。
</p>
<form id="batch-return-push-form"
method="POST"
action="{{ route('business.supplier-reconciliation.push-returns-batch') }}">

View File

@ -65,6 +65,117 @@ class SupplierReconciliationTest extends FeatureTestCase
->assertSeeText('下载对账单模板');
}
public function test_finance_page_overview_counts_and_links_supplier_details(): void
{
$companyId = (int) $this->company->id;
$store = app(SupplierPayableOverrideStore::class);
foreach ([
'汇总厂家甲' => ['qty' => '2', 'amount' => '200'],
'汇总厂家乙' => ['qty' => '3', 'amount' => '300'],
'汇总厂家丙' => ['qty' => '4', 'amount' => '400'],
'汇总厂家丁' => ['qty' => '5', 'amount' => '500'],
] as $supplier => $amounts) {
$store->save(
'final:supplier:payment-reconciliation',
'overview:' . $supplier,
[
'summary_month' => '2026-11',
'purchaseNo' => 'OVERVIEW-' . md5($supplier),
'date' => '2026-11-30',
'supplier' => $supplier,
'skuCode' => 'OVERVIEW-' . $supplier,
'productCode' => 'OVERVIEW-' . $supplier,
'qty' => $amounts['qty'],
'unitPrice' => '100',
'amount' => $amounts['amount'],
],
$companyId,
null,
);
}
$this->seedStatement('汇总厂家甲', [
array_merge($this->statementRow('OVERVIEW-汇总厂家甲', '100', '2', '200'), [
'purchaseNo' => 'OVERVIEW-' . md5('汇总厂家甲'),
'createdAt' => '2026-11-30',
'supplier' => '汇总厂家甲',
]),
]);
$this->seedStatement('汇总厂家乙', [
array_merge($this->statementRow('OVERVIEW-汇总厂家乙', '80', '3', '240'), [
'purchaseNo' => 'OVERVIEW-' . md5('汇总厂家乙'),
'createdAt' => '2026-11-30',
'supplier' => '汇总厂家乙',
]),
]);
$confirmations = app(SupplierSummaryConfirmation::class);
foreach (['甲', '乙'] as $suffix) {
$supplier = '汇总厂家' . $suffix;
$requestId = 'supplier-summary-c' . $companyId . '-' . substr(hash('sha256', $supplier), 0, 32);
$confirmations->create(
$requestId,
$supplier,
'2026-11',
'settlement',
(float) ($suffix === '甲' ? 2 : 3),
(float) ($suffix === '甲' ? 200 : 300),
$companyId,
null,
);
$confirmations->markSent($requestId, $companyId);
}
$failedRequest = 'supplier-summary-c' . $companyId . '-' . substr(hash('sha256', '汇总厂家丙'), 0, 32);
$confirmations->create(
$failedRequest,
'汇总厂家丙',
'2026-11',
'settlement',
4,
400,
$companyId,
null,
);
$confirmations->markFailed($failedRequest, $companyId, '测试发送失败');
$pendingRequest = 'supplier-summary-c' . $companyId . '-' . substr(hash('sha256', '汇总厂家丁'), 0, 32);
$confirmations->create(
$pendingRequest,
'汇总厂家丁',
'2026-11',
'settlement',
5,
500,
$companyId,
null,
);
$response = $this->loginAs()->get(route('business.pages.show', [
'section' => 'supplier-reconciliation',
'page' => 'finance-data',
'month' => '2026-11',
]))->assertOk();
$html = (string) $response->getContent();
$section = static function (string $key) use ($html): string {
preg_match(
'/<details class="sr-overview-stat [^"]*" data-overview="' . preg_quote($key, '/') . '">(.*?)<\/details>/s',
$html,
$matches,
);
return (string) ($matches[1] ?? '');
};
$this->assertStringContainsString('4 家', $section('total'));
$this->assertStringContainsString('2 家', $section('confirmed'));
$this->assertStringContainsString('1 家', $section('difference'));
$this->assertStringContainsString('2 家', $section('not_uploaded'));
$this->assertStringContainsString('汇总厂家甲', $section('confirmed'));
$this->assertStringContainsString('汇总厂家乙', $section('confirmed'));
$this->assertStringContainsString('汇总厂家乙', $section('difference'));
$this->assertStringContainsString('汇总厂家丙', $section('not_uploaded'));
$this->assertStringContainsString('汇总厂家丁', $section('not_uploaded'));
}
public function test_comparison_prefers_express_before_barcode_quantity(): void
{
$companyId = (int) $this->company->id;