feat(代发对账): 明细上方显示账单小汇总 #1767

Closed
limeng wants to merge 1 commits from feature/limeng-dropship-detail-summary into main
5 changed files with 155 additions and 84 deletions

View File

@ -5,6 +5,7 @@ namespace App\Http\Controllers\Business;
use App\Support\CourierBills\Category;
use App\Support\CourierBills\StreamingWorkbook;
use App\Support\DropshipFreight\DropshipConfirmation;
use App\Support\DropshipFreight\DropshipBillSummary;
use App\Support\DropshipFreight\DropshipExporter;
use App\Support\DropshipFreight\DropshipFees;
use App\Support\DropshipFreight\DropshipFreightStore;
@ -117,6 +118,7 @@ final class DropshipFreightController extends Controller
$files = $this->store->db()->table('dropship_bill_files')->where('factory_id', $factory->id)->where('bill_month', $month)->orderBy('id')->get();
return ['dfFactory' => $factory, 'dfSummary' => $result['summary'], 'dfLines' => $paginator, 'dfStatus' => $status, 'dfFiles' => $files,
'dfBillSummary' => app(DropshipBillSummary::class)->build($factory, $month, $result['rows']),
'dfState' => $state, 'dfDisputes' => $disputes, 'dfCurrentDisputes' => $currentDisputes, 'dfDisputeMap' => $disputeMap,
'dfSearch' => $search, 'dfFactoryStates' => $this->confirmations->states($month,self::companyId()), 'dfHistory' => $this->confirmations->history($month, (int)$factory->id, self::companyId()),
'dfFeesDetail' => app(DropshipFees::class)->rows($month, [(int)$factory->id => $result['summary']['settle']], self::companyId())[(int)$factory->id],

View File

@ -0,0 +1,104 @@
<?php
namespace App\Support\DropshipFreight;
use App\Support\CourierBills\Category;
/** 明细页面与导出共用的小汇总;分类及金额沿用原导出口径。 */
final class DropshipBillSummary
{
public const FEE_LABEL = '厂家账单-附加费';
public function __construct(private readonly DropshipFreightStore $store) {}
/** @param list<array<string,mixed>> $rows 未按页面筛选的整月核算结果 */
public function build(object $factory, string $month, array $rows): array
{
$template = $this->store->summaryTemplate($factory, $month);
$billTotal = $settleTotal = null;
$extras = [];
foreach ([Category::MISMATCH, Category::DUPLICATE, Category::UNMATCHED, Category::UNSHIPPED] as $category) {
$extras[DropshipReconciler::LABELS[$category]] = null;
}
foreach ($rows as $r) {
if ($r['bill'] === null) {
continue;
}
if (in_array($r['status'], DropshipReconciler::PAYABLE, true)) {
$billTotal = (float) $billTotal + (float) $r['bill'];
$final = $r['final'] ?? $r['settle'];
if ($final !== null) {
$settleTotal = (float) $settleTotal + (float) $final;
}
} elseif ($r['status'] === Category::LATER) {
$label = Category::label(Category::LATER, (string) $r['status_month']);
$extras[$label] = (float) ($extras[$label] ?? 0) + (float) $r['bill'];
} elseif (array_key_exists($label = DropshipReconciler::LABELS[$r['status']] ?? '', $extras)) {
$extras[$label] = (float) $extras[$label] + (float) $r['bill'];
}
}
$extras = array_filter($extras, static fn ($v): bool => $v !== null);
// 对方附加费保留原金额,自算合计读取同月逐票匹配结果。
$fee = 0.0;
$hasFee = false;
foreach ($this->store->db()->table('dropship_bill_files')->where('factory_id', $factory->id)->where('bill_month', $month)
->where('status', 'parsed')->get(['id', 'stored_path', 'sheets']) as $file) {
$fees = $this->store->feesFor($file);
if ($fees !== []) {
$fee += array_sum($fees);
$hasFee = true;
}
}
// 上月手工汇总里的分类行(快递不符、未发出、跨月订单-X月……)这个月没有就不留空行
$labels = array_values(array_filter($template['labels'], static fn (string $l): bool => array_key_exists(trim($l), $extras)
|| ! preg_match('/^(快递不符|重复|匹配不到|未发出|跨月订单)/u', trim($l))));
if (! $hasFee) {
$labels = array_values(array_filter($labels, static fn (string $l): bool => ! str_contains($l, '附加费')));
}
if (($billTotal !== null || $settleTotal !== null || $extras !== []) && ! array_filter($labels, [DropshipSummaryTemplate::class, 'isFreight'])) {
array_unshift($labels, '运费');
}
foreach (array_keys($extras) as $label) {
if (! in_array($label, array_map('trim', $labels), true)) {
$labels[] = $label;
}
}
$feeLabel = null;
if ($hasFee) {
$feeLabel = collect($labels)->first(static fn (string $l): bool => str_contains($l, '附加费')) ?? self::FEE_LABEL;
if (! in_array($feeLabel, $labels, true)) {
$labels[] = $feeLabel;
}
}
$items = [];
$sums = ['bill' => 0.0, 'settle' => 0.0];
foreach (array_values($labels) as $label) {
[$bill, $settle] = match (true) {
DropshipSummaryTemplate::isFreight($label) => [$billTotal === null ? null : round($billTotal, 2), $settleTotal === null ? null : round($settleTotal, 2)],
array_key_exists(trim($label), $extras) => [round($extras[trim($label)], 2), 0.0],
$label === $feeLabel => [round($fee, 2), $this->surchargeSelf((int) $factory->id, $month)],
default => [null, null],
};
$items[] = ['label' => $label, 'bill' => $bill, 'settle' => $settle,
'diff' => $bill === null && $settle === null ? null : round((float) $bill - (float) $settle, 2)];
$sums['bill'] += (float) $bill;
$sums['settle'] += (float) $settle;
}
$sums = array_map(static fn (float $value): float => round($value, 2), $sums);
$sums['diff'] = round($sums['bill'] - $sums['settle'], 2);
return ['title' => $template['title'], 'headers' => array_slice(array_pad($template['headers'], 3, ''), 0, 3),
'rows' => $items, 'total_label' => $template['total'], 'totals' => $sums];
}
private function surchargeSelf(int $factoryId, string $month): ?float
{
$matcher = app(\App\Support\CourierBills\SurchargeSettlementMatcher::class);
if (! $matcher->ready()) return null;
if (! $this->store->db()->table('dropship_bill_surcharges')->where('factory_id', $factoryId)->where('bill_month', $month)->exists()) return null;
$state = app(DropshipConfirmation::class)->state($month, $factoryId, (int) (company_id() ?: 1));
if (($state['status'] ?? '') === 'confirmed') return null;
return round((float) $matcher->query('dropship', $factoryId, $month)->sum('self_amount'), 2);
}
}

View File

@ -22,7 +22,7 @@ use RuntimeException;
final class DropshipExporter
{
/** 小汇总里放厂家附加费表金额的那一行(手工汇总里已有带「附加费」的类目就填那一行)。 */
public const FEE_LABEL = '厂家账单-附加费';
public const FEE_LABEL = DropshipBillSummary::FEE_LABEL;
private const CHUNK = 500;
public function __construct(
@ -151,80 +151,16 @@ final class DropshipExporter
*/
private function writeSummary(StreamingWorkbook $book, object $factory, string $month, array $rows): void
{
$template = $this->store->summaryTemplate($factory, $month);
$billTotal = $settleTotal = null;
$extras = [];
foreach ([Category::MISMATCH, Category::DUPLICATE, Category::UNMATCHED, Category::UNSHIPPED] as $category) {
$extras[DropshipReconciler::LABELS[$category]] = null;
$summary = app(DropshipBillSummary::class)->build($factory, $month, $rows);
$book->row('汇总', [$summary['title'], ...$summary['headers']], true);
foreach ($summary['rows'] as $index => $item) {
$book->row('汇总', [$item['label'], $item['bill'], $item['settle'], self::diff($index + 2, $item['bill'], $item['settle'])]);
}
foreach ($rows as $r) {
if ($r['bill'] === null) {
continue;
}
if (in_array($r['status'], DropshipReconciler::PAYABLE, true)) {
$billTotal = (float) $billTotal + (float) $r['bill'];
$final = $r['final'] ?? $r['settle'];
if ($final !== null) {
$settleTotal = (float) $settleTotal + (float) $final;
}
} elseif ($r['status'] === Category::LATER) {
$label = Category::label(Category::LATER, (string) $r['status_month']);
$extras[$label] = (float) ($extras[$label] ?? 0) + (float) $r['bill'];
} elseif (array_key_exists($label = DropshipReconciler::LABELS[$r['status']] ?? '', $extras)) {
$extras[$label] = (float) $extras[$label] + (float) $r['bill'];
}
}
$extras = array_filter($extras, static fn ($v): bool => $v !== null);
// 对方附加费保留原金额,自算合计读取同月逐票匹配结果。
$fee = 0.0;
$hasFee = false;
foreach ($this->store->db()->table('dropship_bill_files')->where('factory_id', $factory->id)->where('bill_month', $month)
->where('status', 'parsed')->get(['id', 'stored_path', 'sheets']) as $file) {
$fees = $this->store->feesFor($file);
if ($fees !== []) {
$fee += array_sum($fees);
$hasFee = true;
}
}
// 上月手工汇总里的分类行(快递不符、未发出、跨月订单-X月……)这个月没有就不留空行
$labels = array_values(array_filter($template['labels'], static fn (string $l): bool => array_key_exists(trim($l), $extras)
|| ! preg_match('/^(快递不符|重复|匹配不到|未发出|跨月订单)/u', trim($l))));
if (! $hasFee) {
$labels = array_values(array_filter($labels, static fn (string $l): bool => ! str_contains($l, '附加费')));
}
if (($billTotal !== null || $settleTotal !== null || $extras !== []) && ! array_filter($labels, [DropshipSummaryTemplate::class, 'isFreight'])) {
array_unshift($labels, '运费');
}
foreach (array_keys($extras) as $label) {
if (! in_array($label, array_map('trim', $labels), true)) {
$labels[] = $label;
}
}
$feeLabel = null;
if ($hasFee) {
$feeLabel = collect($labels)->first(static fn (string $l): bool => str_contains($l, '附加费')) ?? self::FEE_LABEL;
if (! in_array($feeLabel, $labels, true)) {
$labels[] = $feeLabel;
}
}
$book->row('汇总', [$template['title'], ...array_slice(array_pad($template['headers'], 3, ''), 0, 3)], true);
$sums = [0.0, 0.0];
foreach (array_values($labels) as $index => $label) {
$n = $index + 2;
[$bill, $settle] = match (true) {
DropshipSummaryTemplate::isFreight($label) => [$billTotal === null ? null : round($billTotal, 2), $settleTotal === null ? null : round($settleTotal, 2)],
array_key_exists(trim($label), $extras) => [round($extras[trim($label)], 2), 0.0],
$label === $feeLabel => [round($fee, 2), $this->surchargeSelf((int)$factory->id,$month)],
default => [null, null],
};
$sums[0] += (float) $bill;
$sums[1] += (float) $settle;
$book->row('汇总', [$label, $bill, $settle, self::diff($n, $bill, $settle)]);
}
$last = count($labels) + 1;
$last = count($summary['rows']) + 1;
$n = $last + 1;
$book->row('汇总', [$template['total'], new XlsxFormula('SUM(B2:B' . $last . ')', round($sums[0], 2)),
new XlsxFormula('SUM(C2:C' . $last . ')', round($sums[1], 2)), new XlsxFormula('N(B' . $n . ')-N(C' . $n . ')', round($sums[0] - $sums[1], 2))], true);
$book->row('汇总', [$summary['total_label'], new XlsxFormula('SUM(B2:B' . $last . ')', $summary['totals']['bill']),
new XlsxFormula('SUM(C2:C' . $last . ')', $summary['totals']['settle']),
new XlsxFormula('N(B' . $n . ')-N(C' . $n . ')', $summary['totals']['diff'])], true);
}
private static function diff(int $row, ?float $bill, ?float $settle): XlsxFormula
@ -233,17 +169,6 @@ final class DropshipExporter
$bill === null && $settle === null ? '' : round((float) $bill - (float) $settle, 2));
}
private function surchargeSelf(int $factoryId,string $month): ?float
{
$matcher=app(\App\Support\CourierBills\SurchargeSettlementMatcher::class);
if(!$matcher->ready())return null;
if(!$this->store->db()->table('dropship_bill_surcharges')->where('factory_id',$factoryId)->where('bill_month',$month)->exists())return null;
$state=app(DropshipConfirmation::class)->state($month,$factoryId,(int)(company_id()?:1));
if(($state['status']??'')==='confirmed')return null;
$sum=$matcher->query('dropship',$factoryId,$month)->sum('self_amount');
return round((float)$sum,2);
}
/** 原账单的表名:「厂家账单」;第 2 个文件起「厂家账单2」;一个文件几张表的加「-原表名」。 */
private static function originalName(int $fileIndex, string $sheet, int $sheetCount): string
{

View File

@ -45,6 +45,21 @@ $feedbackPageFor = function (string $waybill) use ($dfCurrentDisputes): int {
</section>
<div class="fc-steps" aria-label="确认流程"><span class="{{ $s['billed']?'done':'' }}">1 账单已上传</span><span class="{{ !empty($state['checked_at'])?'done':'active' }}">2 财务核对完成</span><span class="{{ !empty($state['pushed_at'])?'done':'' }}">3 推送厂家群</span><span class="{{ ($state['status']??'')==='confirmed'?'done':(($state['status']??'')==='disputed'?'active':'') }}">4 {{ ($state['status']??'')==='disputed'?'异议复核中':'厂家确认' }}</span></div>
<div class="fc-workspace"><div>
<section class="cbr-panel" aria-label="小汇总" data-df-bill-summary>
<h3>小汇总</h3>
<p class="cbr-muted cbr-panel-body">{{ $dfBillSummary['title'] }} · 按整月汇总,与导出账单一致;不随下方筛选或翻页改变。</p>
<div class="cbr-scroll"><table>
<thead><tr><th>项目</th><th class="num">{{ $dfBillSummary['headers'][0] ?: '厂家金额' }}</th><th class="num">{{ $dfBillSummary['headers'][1] ?: '自算金额' }}</th><th class="num">{{ $dfBillSummary['headers'][2] ?: '差异' }}</th></tr></thead>
<tbody>
@forelse($dfBillSummary['rows'] as $item)
<tr><td>{{ $item['label'] }}</td><td class="num">{{ $money($item['bill']) }}</td><td class="num">{{ $money($item['settle']) }}</td><td class="num {{ $item['diff'] != 0 ? 'cbr-diff' : '' }}">{{ $money($item['diff']) }}</td></tr>
@empty
<tr><td colspan="4" class="cbr-empty">本月没有小汇总项目。</td></tr>
@endforelse
</tbody>
<tfoot><tr><td>{{ $dfBillSummary['total_label'] }}</td><td class="num">{{ $money($dfBillSummary['totals']['bill']) }}</td><td class="num">{{ $money($dfBillSummary['totals']['settle']) }}</td><td class="num {{ $dfBillSummary['totals']['diff'] != 0 ? 'cbr-diff' : '' }}">{{ $money($dfBillSummary['totals']['diff']) }}</td></tr></tfoot>
</table></div>
</section>
<nav class="cbr-tabs" aria-label="按状态查看"><a data-cbr-tab href="{{ $pageUrl($base) }}" class="{{ $dfStatus===''?'is-active':'' }}">全部 {{ array_sum($s['counts']) }}</a><a data-cbr-tab href="{{ $pageUrl($base+['status'=>'attention']) }}" class="{{ $dfStatus==='attention'?'is-active':'' }}">要看的 {{ $s['attention'] }}</a><a data-cbr-tab href="{{ $pageUrl($base+['status'=>'disputed']) }}" class="{{ $dfStatus==='disputed'?'is-active':'' }}">厂家异议 {{ count($dfCurrentDisputes) }}</a>
@foreach(\App\Support\DropshipFreight\DropshipReconciler::LABELS as $key=>$label)@if($s['counts'][$key])<a data-cbr-tab href="{{ $pageUrl($base+['status'=>$key]) }}" class="{{ $dfStatus===$key?'is-active':'' }}">{{ $label }} {{ $s['counts'][$key] }}</a>@endif@endforeach</nav>
<section class="cbr-panel"><h3>逐单核算明细</h3><form method="GET" action="{{ $pageUrl() }}" class="cbr-form cbr-panel-body" data-cbr-filter><input type="hidden" name="df_view" value="factory"><input type="hidden" name="factory" value="{{ $dfFactory->id }}"><input type="hidden" name="month" value="{{ $month }}"><input type="hidden" name="status" value="{{ $dfStatus }}"><input name="q" value="{{ $dfSearch }}" placeholder="搜索快递单号" aria-label="搜索快递单号"><button>搜索</button></form>

View File

@ -200,6 +200,27 @@ final class DropshipFreightTest extends FeatureTestCase
$this->assertEquals([[23, 0], [3, 0], [4, 0]], [array_slice($summary[4], 1, 2), array_slice($summary[5], 1, 2), array_slice($summary[6], 1, 2)]);
$this->assertSame('=SUM(B2:B7)', $sheet->getCell('B8')->getValue()); // 合计是公式,手工填了跟着算
$this->assertEquals(63, $sheet->getCell('B8')->getCalculatedValue());
// 页面小汇总和导出逐项一致,放在逐单明细上方,筛选/翻页不影响整月金额。
$detailUrl = $page(['df_view' => 'factory', 'factory' => $factory->id, 'month' => '2026-10']);
$summaryRows = array_map(static fn (array $r): array => [
(string) $r[0], $r[1] === null ? '' : number_format((float) $r[1], 2),
$r[2] === null ? '' : number_format((float) $r[2], 2),
$r[1] === null && $r[2] === null ? '' : number_format((float) $r[1] - (float) $r[2], 2),
], array_slice($summary, 1, 6));
$summaryRows[] = ['汇总', '63.00', '28.00', '35.00'];
foreach ([[], ['status' => 'attention'], ['q' => '773444000002'], ['page' => 2]] as $filter) {
$response = $this->get($detailUrl . '&' . http_build_query($filter))->assertOk();
$html = (string) $response->getContent();
$this->assertLessThan(strpos($html, '逐单核算明细'), strpos($html, 'data-df-bill-summary'));
$dom = new \DOMDocument();
@$dom->loadHTML('<?xml encoding="utf-8" ?>' . $html);
$xpath = new \DOMXPath($dom);
$actual = [];
foreach ($xpath->query('//*[@data-df-bill-summary]//tbody/tr | //*[@data-df-bill-summary]//tfoot/tr') as $tr) {
$actual[] = array_map(static fn ($cell): string => trim($cell->textContent), iterator_to_array($tr->getElementsByTagName('td')));
}
$this->assertSame($summaryRows, $actual);
}
$sheet->setCellValue('C4', -100);
$this->assertEquals(100, $sheet->getCell('D4')->getCalculatedValue());
$this->assertEquals(-72, $sheet->getCell('C8')->getCalculatedValue());
@ -482,6 +503,10 @@ final class DropshipFreightTest extends FeatureTestCase
$this->assertSame('运费', (string) $book->getSheetByName('汇总')->getCell('A2')->getValue());
$this->assertEquals(6, $book->getSheetByName('汇总')->getCell('B2')->getValue());
$this->assertNull($book->getSheetByName('汇总')->getCell('C2')->getValue());
$summary = app(\App\Support\DropshipFreight\DropshipBillSummary::class)->build(
collect($store->factories())->sole(), '2026-11', app(DropshipReconciler::class)->factoryMonth(collect($store->factories())->sole(), '2026-11')['rows']);
$this->assertNull($summary['rows'][0]['settle']);
$this->assertSame(6.0, $summary['rows'][0]['diff']);
} finally {
$book?->disconnectWorksheets();
@unlink($input);