快递应付:新增配件补发扣款匹配界面 #353

Merged
limeng merged 1 commits from feature/limeng-accessory-reship-deductions into main 2026-10-16 21:36:04 +08:00
11 changed files with 377 additions and 0 deletions

View File

@ -0,0 +1,29 @@
<?php
namespace App\Http\Controllers\Business;
use Illuminate\Routing\Controller;
use Modules\EcommerceFinance\View\AccessoryReshipPageData;
class AccessoryReshipDeductions extends Controller
{
public function export(AccessoryReshipPageData $data)
{
$filters = $data->filters();
// 先完成读取,失败时返回正常错误,避免下载半份扣款清单。
$file = tmpfile();
if ($file === false) abort(500, '无法创建导出文件。');
fwrite($file, "\xEF\xBB\xBF");
fputcsv($file, ['交易单号','补发快递单号','补发快递','补发时间','原始条形码','处理后条形码','补发运费','匹配状态','首发快递公司(候选)','首发快递单号(候选)','首发所属月份(候选)','扣款金额','说明']);
foreach ($data->rows($filters) as $row) {
if ($filters['match_status'] !== 'all' && $row['status'] !== $filters['match_status']) continue;
$values = [$row['trade_no'], $row['express_no'], ($row['express_name1'] ?: ($row['express_name2'] ?? '')), $row['ship_time'], $row['barcode'], $row['normalized_barcode'], $row['freight'], $row['status'] === 'matched' ? '可扣款' : '未匹配不扣款', implode(' / ', array_column($row['matches'], 'courier')), implode(' / ', array_column($row['matches'], 'express_no')), implode(' / ', array_column($row['matches'], 'month')), $row['deduction_cents'] === null ? '' : number_format($row['deduction_cents'] / 100, 2, '.', ''), $row['freight_cents'] === null ? '运费缺失或异常,待核实' : (count($row['matches']) > 1 ? '多候选待确认归属;运费只计一次' : '')];
fputcsv($file, array_map(static function ($value) {
$value = (string) $value;
return preg_match('/^[=+\-@\t\r\n]/u', $value) ? "'" . $value : $value;
}, $values));
}
rewind($file);
return response()->streamDownload(function () use ($file) { fpassthru($file); fclose($file); }, '配件补发扣款-' . $filters['month'] . '.csv', ['Content-Type' => 'text/csv; charset=UTF-8']);
}
}

View File

@ -3272,6 +3272,7 @@ class Pages extends Controller
'courier-surcharge' => $this->contentForCourierSurcharge($tab),
'courier-surcharge-settlement' => $this->contentForCourierSurchargeSettlementPage(),
'freight-difference', 'other-surcharge-summary', 'return-fee' => $this->contentForCourierPayableSummary($page),
'accessory-reship-deductions' => app(\Modules\EcommerceFinance\View\AccessoryReshipPageData::class)->page(),
'shipping-data' => $this->contentForShippingData(),
'return-pickup-management' => $this->contentForReturnPickupManagement(),
'withdrawal-management' => $this->contentForWithdrawalManagement(),

View File

@ -656,6 +656,7 @@ $navigation = [
['slug' => 'agreement-signing', 'title' => '协议签署'],
['slug' => 'freight-reconciliation', 'title' => '运费对账'],
['slug' => 'shipping-data', 'title' => '发货数据'],
['slug' => 'accessory-reship-deductions', 'title' => '配件补发扣款'],
['slug' => 'third-party-warehouse-storage', 'title' => '三方仓进销存'],
['slug' => 'bookkeeping-details', 'title' => '记账明细'],
['slug' => 'compensation-details', 'title' => '赔偿明细'],
@ -720,6 +721,7 @@ $navigation = [
],
['slug' => 'freight-reconciliation', 'title' => '运费对账'],
['slug' => 'shipping-data', 'title' => '发货数据'],
['slug' => 'accessory-reship-deductions', 'title' => '配件补发扣款'],
['slug' => 'return-pickup-management', 'title' => '退货取件管理'],
['slug' => 'third-party-warehouse-storage', 'title' => '三方仓进销存'],
['slug' => 'warehouse-freight', 'title' => '仓储费'],

View File

@ -0,0 +1,19 @@
# 配件补发扣款
入口:快递应付 → 配件补发扣款。
选择业务年月后,读取发货数据中仓库为“常州简尚家居有限公司”的本月包裹,按现有发货数据的 source_id 合并口径汇总补发运费。配件条形码按明细顺序取第一个英文逗号前的值,去掉最后一个短横线及其后内容;首发条码只拆分英文逗号,不删除后缀。
首发候选限定业务月及前两个月(支持跨年)、仓库不为配件仓库、快递单号非空。使用完整交易单号和条码精确匹配。一个补发包裹始终只展示一行,重复候选去重;多首发候选仍归为可扣款,保留快递名称、快递单号和年月供核对,运费只统计一次。
金额来自发货数据的 freight,使用分汇总;缺失、负数或非数字运费显示待核实,不以零代替。页面提供可扣款、未匹配、全部三类局部切换和分页,CSV导出覆盖当前分类全部记录,不受分页限制。导出继承后台登录、公司上下文和本页权限,防止表格公式注入。
本版为匹配和扣款核对清单,不生成应付账记账记录;多候选的扣款归属尚需业务核对。本次无数据库迁移,无上游写入,无财务数据修改。
验证:
- AccessoryReshipMatcherTest:首个配件条码、最后一个后缀、完整首发条码、交易单号、多候选去重、空单号、运费异常、精确金额。
- AccessoryReshipPageDataTest:跨年三个月窗口、分页、汇总及多候选不重复计费。
- 实际Blade页面检查:分类局部切换、分页、多候选提示、异常金额及手机/桌面布局。
- 导出检查:路由优先级、本页权限、后台鉴权、UTF-8 BOM及公式保护。
- 使用现有数据连接进行了真实业务月份只读匹配及性能验证。

View File

@ -67,6 +67,30 @@ class ShippingOrderRepository
return ['data' => $rows, 'total' => $total];
}
/** 仅批量读取本月配件及其交易单号对应的三个月首发候选;复用发货数据合并口径。 */
public function accessoryReshipBatches(string $monthStart, string $nextMonth, string $windowStart): \Generator
{
$last = null;
while (true) {
$query = $this->db->table('jst_oms_shipping')
->where('warehouse_name', \Modules\EcommerceFinance\Services\AccessoryReshipMatcher::WAREHOUSE)
->where('ship_time', '>=', $monthStart)->where('ship_time', '<', $nextMonth);
if ($last !== null) $query->where('source_id', '>', $last);
// 指定条码顺序,保证“第一个条码”在重复匹配时稳定。
$select = 'source_id, MAX(express_no) as express_no, MAX(trade_no) as trade_no, MAX(express_name1) as express_name1, MAX(express_name2) as express_name2, MAX(ship_time) as ship_time, SUM(freight) as freight, GROUP_CONCAT(DISTINCT barcode ORDER BY id SEPARATOR \',\' ) as barcode';
$accessories = $query->groupBy('source_id')->selectRaw($select)->orderBy('source_id')->limit(1000)->get()->map(fn ($row) => (array) $row)->all();
if ($accessories === []) return;
$trades = array_values(array_unique(array_filter(array_column($accessories, 'trade_no'), static fn ($trade) => trim((string) $trade) !== '')));
$originals = $trades === [] ? [] : $this->db->table('jst_oms_shipping')
->where('warehouse_name', '<>', \Modules\EcommerceFinance\Services\AccessoryReshipMatcher::WAREHOUSE)
->where('ship_time', '>=', $windowStart)->where('ship_time', '<', $nextMonth)
->whereIn('trade_no', $trades)->whereNotNull('express_no')->where('express_no', '<>', '')
->select(['trade_no', 'barcode', 'express_no', 'express_name1', 'express_name2', 'ship_time', 'warehouse_name'])
->get()->map(fn ($row) => (array) $row)->all();
yield compact('accessories', 'originals');
$last = $accessories[array_key_last($accessories)]['source_id'];
}
}
/** 明细口径:无尺寸(0)的长宽高/体积显示为空白,对齐工作平台导出明细(合并保持 0)。 */
private function detailRow(array $r): array
{

View File

@ -0,0 +1,60 @@
<?php
namespace Modules\EcommerceFinance\Services;
/** 配件只处理第一个条码;成品逐个完整条码匹配。金额使用分,避免浮点累计。 */
class AccessoryReshipMatcher
{
public const WAREHOUSE = '常州简尚家居有限公司';
public static function barcode(string $value): string
{
$first = trim(explode(',', $value)[0]);
$position = strrpos($first, '-');
return $position === false ? $first : substr($first, 0, $position);
}
public static function cents(mixed $value): ?int
{
if (!preg_match('/^\d+(?:\.\d+)?$/', trim((string) $value))) {
return null;
}
[$whole, $decimal] = array_pad(explode('.', trim((string) $value), 2), 2, '');
return (int) $whole * 100 + (int) substr(str_pad($decimal, 2, '0'), 0, 2) + (strlen($decimal) > 2 && (int) $decimal[2] >= 5 ? 1 : 0);
}
public function match(array $accessories, iterable $originals): array
{
$index = [];
foreach ($originals as $original) {
if (trim((string) ($original['warehouse_name'] ?? '')) === self::WAREHOUSE || trim((string) ($original['express_no'] ?? '')) === '') continue;
$trade = trim((string) ($original['trade_no'] ?? ''));
if ($trade === '') continue;
foreach (explode(',', (string) ($original['barcode'] ?? '')) as $barcode) {
$barcode = trim($barcode);
if ($barcode === '') continue;
$key = json_encode([$trade, $barcode]);
$identity = json_encode([$original['express_no'], $original['express_name1'] ?? '', substr((string) $original['ship_time'], 0, 7)]);
$index[$key][$identity] = [
'express_no' => $original['express_no'],
'courier' => ($original['express_name1'] ?? '') ?: ($original['express_name2'] ?? ''),
'month' => substr((string) $original['ship_time'], 0, 7),
];
}
}
$result = [];
foreach ($accessories as $row) {
$barcode = self::barcode((string) ($row['barcode'] ?? ''));
$trade = trim((string) ($row['trade_no'] ?? ''));
$matches = ($barcode !== '' && $trade !== '') ? array_values($index[json_encode([$trade, $barcode])] ?? []) : [];
$row['normalized_barcode'] = $barcode;
$row['matches'] = $matches;
$row['status'] = $matches === [] ? 'unmatched' : 'matched';
$row['freight_cents'] = self::cents($row['freight'] ?? null);
// 多候选仍属于可扣款;保持一条补发记录,运费不随候选数量放大。
$row['deduction_cents'] = $matches === [] ? 0 : $row['freight_cents'];
$result[] = $row;
}
return $result;
}
}

View File

@ -0,0 +1,55 @@
<?php
namespace Modules\EcommerceFinance\View;
use Illuminate\Pagination\LengthAwarePaginator;
use Modules\EcommerceFinance\Repositories\ShippingOrderRepository;
use Modules\EcommerceFinance\Services\AccessoryReshipMatcher;
class AccessoryReshipPageData
{
public function __construct(private ShippingOrderRepository $shipping, private AccessoryReshipMatcher $matcher) {}
public function filters(): array
{
$month = request()->query('month', now()->format('Y-m'));
abort_unless(is_string($month) && preg_match('/^\d{4}-(0[1-9]|1[0-2])$/', $month) && (int) substr($month, 0, 4) >= 2000, 422, '请选择有效业务月份。');
$status = request()->query('match_status', 'matched');
return ['month' => $month, 'match_status' => in_array($status, ['matched', 'unmatched', 'all'], true) ? $status : 'matched'];
}
public function rows(array $filters): \Generator
{
$start = \Carbon\Carbon::createFromFormat('!Y-m', $filters['month']);
foreach ($this->shipping->accessoryReshipBatches($start->format('Y-m-d'), $start->copy()->addMonth()->format('Y-m-d'), $start->copy()->subMonths(2)->format('Y-m-d')) as $batch) {
foreach ($this->matcher->match($batch['accessories'], $batch['originals']) as $row) yield $row;
}
}
public function page(): array
{
$filters = $this->filters();
$page = max(1, (int) request('page', 1));
$summary = ['all' => 0, 'matched' => 0, 'unmatched' => 0, 'amount' => 0, 'invalid_amount' => 0, 'ambiguous' => 0];
$items = []; $total = 0; $error = null;
try {
foreach ($this->rows($filters) as $row) {
$summary['all']++; $summary[$row['status']]++;
if ($row['status'] === 'matched') {
$summary['amount'] += $row['deduction_cents'] ?? 0;
if ($row['deduction_cents'] === null) $summary['invalid_amount']++;
if (count($row['matches']) > 1) $summary['ambiguous']++;
}
if ($filters['match_status'] !== 'all' && $filters['match_status'] !== $row['status']) continue;
if ($total >= ($page - 1) * 50 && count($items) < 50) $items[] = $row;
$total++;
}
} catch (\Throwable $exception) {
report($exception); $error = '发货数据暂时无法读取,请检查数据连接或同步状态后重试。';
$items = []; $total = 0;
$summary = array_fill_keys(array_keys($summary), 0);
}
return ['view' => 'business.pages.courier-payables.accessory-reship-deductions', 'reshipFilters' => $filters, 'reshipSummary' => $summary, 'reshipError' => $error,
'reshipRows' => new LengthAwarePaginator($items, $total, 50, $page, ['path' => request()->url(), 'query' => request()->except('page')])];
}
}

View File

@ -0,0 +1,75 @@
@php
$filters = $reshipFilters;
$summary = $reshipSummary;
$labels = ['matched' => '可扣款项', 'unmatched' => '未匹配项', 'all' => '全部配件单'];
$startMonth = \Carbon\Carbon::createFromFormat('!Y-m', $filters['month'])->subMonths(2)->format('Y年n月');
@endphp
<div class="reship-page">
<div class="reship-heading"><div><h2>配件补发扣款</h2><p>按交易单号及条形码匹配首发快递,核算配件补发运费。</p></div><span class="reship-tag">快递应付</span></div>
<form method="GET" class="reship-toolbar">
<label>业务月份<input type="month" name="month" value="{{ $filters['month'] }}" min="2000-01" required></label>
<input type="hidden" name="match_status" value="{{ $filters['match_status'] }}">
<button type="submit" class="reship-primary">提取并匹配</button>
@if (!$reshipError)<a class="reship-button" href="{{ route('business.accessory-reship-deductions.export', $filters) }}">导出当前分类</a>@endif
<span class="reship-range">匹配范围:{{ $startMonth }} 至 {{ \Carbon\Carbon::createFromFormat('!Y-m', $filters['month'])->format('Y年n月') }}</span>
</form>
<div class="reship-metrics">
@foreach (['all' => '配件单数', 'matched' => '可扣款单数', 'unmatched' => '未匹配单数'] as $key => $label)
<div><span>{{ $label }}</span><strong>{{ $reshipError ? '—' : number_format($summary[$key]) }}</strong></div>
@endforeach
<div><span>可扣款总额(运费仅计一次)</span><strong>{{ $reshipError ? '—' : '¥ ' . number_format($summary['amount'] / 100, 2) }}</strong></div>
</div>
<details class="reship-rules"><summary>匹配规则与扣款口径</summary><p>配件仓库:常州简尚家居有限公司。配件条码取第一个英文逗号前的内容,再去掉最后一个“-”及其后内容。首发仓库排除该仓库,首发多个条码拆分后按完整条码匹配。仅匹配到首发快递单号的记录列为可扣款,金额取补发发货数据中的运费。</p><p>本页生成扣款核对清单,尚未记入应付账。多首发候选需确认归属,运费缺失或异常需核实;重复匹配不会新增扣款记录。</p></details>
@if ($reshipError)<div class="reship-error" role="alert">{{ $reshipError }}</div>@endif
@if ($summary['ambiguous'] || $summary['invalid_amount'])<div class="reship-notice" role="status">多首发候选 {{ $summary['ambiguous'] }} 单,需确认归属;运费异常 {{ $summary['invalid_amount'] }} 单,暂未计入总额。</div>@endif
<section class="reship-panel" data-finance-table-surface>
<nav class="reship-tabs" aria-label="匹配分类">
@foreach ($labels as $key => $label)
<a href="{{ request()->fullUrlWithQuery(['match_status' => $key, 'page' => null]) }}" data-reship-tab="{{ $key }}" class="{{ $filters['match_status'] === $key ? 'is-active' : '' }}" @if ($filters['match_status'] === $key) aria-current="page" @endif>{{ $label }} <span>{{ $summary[$key] }}</span></a>
@endforeach
</nav>
<div class="reship-table-scroll"><table><thead><tr>
@foreach (['交易单号','补发快递单号','补发快递','补发日期','原始条形码','处理后条形码','补发运费','匹配状态','首发快递 / 单号 / 所属月份','可扣金额','说明'] as $heading)<th>{{ $heading }}</th>@endforeach
</tr></thead><tbody>
@forelse ($reshipRows as $row)
<tr><td>{{ $row['trade_no'] }}</td><td>{{ $row['express_no'] }}</td><td>{{ $row['express_name1'] ?: $row['express_name2'] }}</td><td>{{ substr((string) $row['ship_time'], 0, 10) }}</td><td class="reship-barcode">{{ $row['barcode'] }}</td><td>{{ $row['normalized_barcode'] }}</td><td class="reship-money">{{ $row['freight_cents'] === null ? '待核实' : number_format($row['freight_cents'] / 100, 2) }}</td><td><span class="reship-status {{ $row['status'] }}">{{ $row['status'] === 'matched' ? '可扣款' : '未匹配不扣款' }}</span></td><td>
@forelse ($row['matches'] as $match)<div class="reship-candidate">{{ $match['courier'] ?: '快递名称待核实' }}<br>{{ $match['express_no'] }} <span>({{ $match['month'] }})</span></div>@empty — @endforelse
</td><td class="reship-money">{{ $row['deduction_cents'] === null ? '待核实' : number_format($row['deduction_cents'] / 100, 2) }}</td><td>{{ $row['freight_cents'] === null ? '运费缺失或异常' : (count($row['matches']) > 1 ? '多候选,确认归属后扣款;仅计一次' : ($row['status'] === 'unmatched' ? '三个月内未匹配首发快递单号' : '待核对')) }}</td></tr>
@empty<tr><td colspan="11" class="reship-empty">{{ $reshipError ?: '当前月份及分类暂无记录,请调整业务月份或分类。' }}</td></tr>@endforelse
</tbody></table></div>
<div class="reship-footer">当前分类共 {{ number_format($reshipRows->total()) }} 单,每页50单 {{ $reshipRows->links() }}</div>
</section>
</div>
<style>
.reship-page{color:var(--vip-content-ink,#171717);font-size:13px}.reship-heading{display:flex;justify-content:space-between;align-items:center;margin-bottom:16px}.reship-heading h2{font-size:16px;font-weight:600;margin:0 0 6px}.reship-heading p,.reship-range{color:#595959;font-size:12px}.reship-tag,.reship-status{padding:4px 8px;border-radius:4px;background:#F7F0DE;color:#856632;font-size:12px}.reship-toolbar{display:flex;flex-wrap:wrap;align-items:flex-end;gap:12px;margin-bottom:16px}.reship-toolbar label{display:grid;gap:6px;font-size:12px}.reship-toolbar input,.reship-button,.reship-toolbar button{height:34px;padding:0 12px;border:1px solid #D8D2C7;border-radius:8px;background:#fff;color:#171717}.reship-button{display:inline-flex;align-items:center;text-decoration:none}.reship-toolbar .reship-primary{background:#856632;border-color:#856632;color:#fff}.reship-range{align-self:center;padding-top:18px}.reship-metrics{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:12px;margin-bottom:16px}.reship-metrics>div{padding:16px;background:#fff;border:1px solid #D8D2C7;border-radius:12px}.reship-metrics span{display:block;font-size:12px;color:#595959}.reship-metrics strong{display:block;margin-top:8px;font-size:22px;font-variant-numeric:tabular-nums}.reship-metrics>div:last-child strong{color:#856632}.reship-rules{margin:12px 0;color:#595959;font-size:12px}.reship-rules summary{cursor:pointer;color:#856632}.reship-rules p{margin:8px 0;line-height:1.7}.reship-error,.reship-notice{padding:12px;margin:12px 0;border-radius:8px;background:#F7F0DE;color:#935F07}.reship-error{color:#B80000}.reship-panel{border:1px solid #D8D2C7;border-radius:12px;background:#fff;overflow:hidden}.reship-tabs{display:flex;gap:24px;padding:0 16px;border-bottom:1px solid #D8D2C7}.reship-tabs a{padding:13px 0;color:#595959;text-decoration:none}.reship-tabs a.is-active{color:#856632;border-bottom:2px solid #856632}.reship-tabs span{font-size:11px;margin-left:5px}.reship-table-scroll{overflow-x:auto}.reship-page table{width:100%;border-collapse:collapse;font-size:12px}.reship-page th,.reship-page td{padding:12px;text-align:left;vertical-align:top;border-bottom:1px solid #D8D2C7}.reship-page th{white-space:nowrap;background:#F7F0DE;font-weight:500;color:#595959}.reship-page td{min-width:110px;overflow-wrap:anywhere}.reship-page td.reship-barcode{min-width:200px;max-width:300px}.reship-page td.reship-money{text-align:right;white-space:nowrap;font-variant-numeric:tabular-nums}.reship-status{display:inline-block;white-space:nowrap}.reship-status.matched{background:#eef3e9;color:#53793E}.reship-status.unmatched{background:#f1efeb;color:#595959}.reship-candidate{min-width:220px;margin-bottom:6px;line-height:1.7}.reship-candidate span{color:#595959}.reship-page td.reship-empty{text-align:center;padding:60px 16px;color:#595959}.reship-footer{padding:12px 16px;color:#595959;font-size:12px}.reship-footer nav{margin-top:12px}@media(max-width:700px){.reship-metrics{grid-template-columns:repeat(2,minmax(0,1fr))}.reship-range{width:100%;padding:0}.reship-tabs{gap:14px}.reship-metrics strong{font-size:19px}}
</style>
@push('body_end')
<script>
(() => {
// 分类在当前页面局部切换,保留页面外壳和快递应付导航。
const root = document.querySelector('.reship-page');
if (!root) return;
document.addEventListener('click', async event => {
const link = event.target.closest('[data-reship-tab]');
if (!link || event.ctrlKey || event.metaKey || event.shiftKey || event.altKey || event.button !== 0) return;
event.preventDefault();
const current = document.querySelector('.reship-page');
if (current.getAttribute('aria-busy') === 'true') return;
current.setAttribute('aria-busy', 'true');
try {
const response = await fetch(link.href, {headers: {'X-Requested-With': 'XMLHttpRequest'}});
if (!response.ok) throw new Error('load');
const doc = new DOMParser().parseFromString(await response.text(), 'text/html');
const next = doc.querySelector('.reship-page');
if (!next) throw new Error('load');
current.replaceWith(next);
history.replaceState({}, '', link.href);
} catch (_) {
current.removeAttribute('aria-busy');
const error = document.createElement('div'); error.className = 'reship-error'; error.setAttribute('role', 'alert'); error.textContent = '分类加载失败,请重试。';
current.prepend(error);
}
});
})();
</script>
@endpush

View File

@ -405,6 +405,10 @@ Route::get('workspace/courier-payables/courier-information/export', 'Business\Pa
->middleware('business.page:courier-payables,courier-information')
->name('business.courier-payables.courier-information.export');
Route::get('workspace/courier-payables/accessory-reship-deductions/export', [\App\Http\Controllers\Business\AccessoryReshipDeductions::class, 'export'])
->middleware('business.page:courier-payables,accessory-reship-deductions')
->name('business.accessory-reship-deductions.export');
Route::get('workspace/courier-payables/shipping-data/export', 'Business\Pages@exportShippingData')
->middleware('business.page:courier-payables,shipping-data')
->name('business.courier-payables.shipping-data.export');

View File

@ -0,0 +1,62 @@
<?php
namespace Tests\Unit;
use Modules\EcommerceFinance\Services\AccessoryReshipMatcher;
use PHPUnit\Framework\TestCase;
require_once dirname(__DIR__, 2) . '/modules/EcommerceFinance/Services/AccessoryReshipMatcher.php';
class AccessoryReshipMatcherTest extends TestCase
{
private function original(array $changes = []): array
{
return array_replace(['trade_no' => 'T001', 'warehouse_name' => '成品仓', 'barcode' => 'GBGJ-SJ038024N1410V02,OTHER-SKU', 'express_no' => 'SF001', 'express_name1' => '首发快递', 'ship_time' => '2026-08-01 12:00:00'], $changes);
}
private function accessory(array $changes = []): array
{
return array_replace(['trade_no' => 'T001', 'barcode' => 'GBGJ-SJ038024N1410V02-10,OTHER-SKU-2', 'freight' => '12.30'], $changes);
}
public function test_first_accessory_barcode_and_last_suffix_only(): void
{
$this->assertSame('GBGJ-SJ038024N1410V02', AccessoryReshipMatcher::barcode('GBGJ-SJ038024N1410V02-10,GBGJ-SJ038024N1410V02-2,GBGJ-SJ038024N1410V02-7'));
$this->assertSame('ABC', AccessoryReshipMatcher::barcode('ABC'));
$this->assertSame('', AccessoryReshipMatcher::barcode(''));
}
public function test_exact_trade_and_split_original_barcodes_without_normalizing_original(): void
{
$matcher = new AccessoryReshipMatcher;
$result = $matcher->match([$this->accessory(), $this->accessory(['barcode' => 'OTHER-SKU-2']), $this->accessory(['trade_no' => 'T002'])], [$this->original()]);
$this->assertSame(['matched', 'matched', 'unmatched'], array_column($result, 'status'));
$this->assertSame(1230, $result[0]['deduction_cents']);
$this->assertSame('2026-08', $result[0]['matches'][0]['month']);
$this->assertSame('unmatched', $matcher->match([$this->accessory()], [$this->original(['barcode' => 'GBGJ-SJ038024N1410V02-10'])])[0]['status']);
}
public function test_blank_waybill_accessory_warehouse_and_empty_keys_do_not_qualify(): void
{
$matcher = new AccessoryReshipMatcher;
$result = $matcher->match([$this->accessory(), $this->accessory(['trade_no' => '']), $this->accessory(['barcode' => ''])], [$this->original(['express_no' => ' ']), $this->original(['warehouse_name' => AccessoryReshipMatcher::WAREHOUSE])]);
$this->assertSame(['unmatched', 'unmatched', 'unmatched'], array_column($result, 'status'));
$this->assertSame([0, 0, 0], array_column($result, 'deduction_cents'));
}
public function test_multiple_matches_keep_one_deduction_and_deduplicate_same_waybill(): void
{
$matcher = new AccessoryReshipMatcher;
$originals = [$this->original(), $this->original(), $this->original(['express_no' => 'YTO002', 'express_name1' => '另一快递', 'ship_time' => '2026-09-01'])];
$result = $matcher->match([$this->accessory()], $originals);
$this->assertCount(1, $result);
$this->assertCount(2, $result[0]['matches']);
$this->assertSame(1230, $result[0]['deduction_cents']);
$this->assertSame($result, $matcher->match([$this->accessory()], $originals));
}
public function test_invalid_amount_stays_matched_but_cannot_supply_amount(): void
{
foreach ([null, '', '-2.00', 'abc'] as $value) {
$row = (new AccessoryReshipMatcher)->match([$this->accessory(['freight' => $value])], [$this->original()])[0];
$this->assertSame('matched', $row['status']);
$this->assertNull($row['deduction_cents']);
}
$this->assertSame(1230, AccessoryReshipMatcher::cents('12.3000'));
$this->assertSame(1240, AccessoryReshipMatcher::cents('12.395'));
$this->assertSame(0, AccessoryReshipMatcher::cents('0.00'));
}
}

View File

@ -0,0 +1,46 @@
<?php
namespace Tests\Unit;
use Illuminate\Container\Container;
use Illuminate\Http\Request;
use Modules\EcommerceFinance\Repositories\ShippingOrderRepository;
use Modules\EcommerceFinance\Services\AccessoryReshipMatcher;
use Modules\EcommerceFinance\View\AccessoryReshipPageData;
use PHPUnit\Framework\TestCase;
use Mockery;
require_once dirname(__DIR__, 2) . '/modules/EcommerceFinance/Repositories/ShippingOrderRepository.php';
require_once dirname(__DIR__, 2) . '/modules/EcommerceFinance/Services/AccessoryReshipMatcher.php';
require_once dirname(__DIR__, 2) . '/modules/EcommerceFinance/View/AccessoryReshipPageData.php';
class AccessoryReshipPageDataTest extends TestCase
{
protected function tearDown(): void { Mockery::close(); parent::tearDown(); }
public function test_january_uses_current_month_and_previous_two_months(): void
{
$repo = Mockery::mock(ShippingOrderRepository::class);
$repo->shouldReceive('accessoryReshipBatches')->once()->with('2026-01-01', '2026-02-01', '2025-11-01')->andReturn((function () { yield ['accessories' => [['trade_no' => '001', 'barcode' => 'SKU-1', 'freight' => '2.50']], 'originals' => []]; })());
$data = new AccessoryReshipPageData($repo, new AccessoryReshipMatcher);
$rows = iterator_to_array($data->rows(['month' => '2026-01']));
$this->assertSame('unmatched', $rows[0]['status']);
$this->assertSame(0, $rows[0]['deduction_cents']);
}
public function test_summary_does_not_duplicate_candidate_freight_and_paginates(): void
{
$request = Request::create('/workspace/courier-payables/accessory-reship-deductions?month=2026-09&match_status=all&page=2');
Container::getInstance()->instance('request', $request);
$accessories = [];
for ($i = 0; $i < 105; $i++) $accessories[] = ['trade_no' => '001', 'barcode' => 'SKU-1', 'freight' => '0.10'];
$original = ['trade_no' => '001', 'barcode' => 'SKU', 'express_no' => 'FIRST', 'express_name1' => '快递', 'ship_time' => '2026-08-01', 'warehouse_name' => '成品仓'];
$repo = Mockery::mock(ShippingOrderRepository::class);
$repo->shouldReceive('accessoryReshipBatches')->andReturn((function () use ($accessories, $original) { yield ['accessories' => $accessories, 'originals' => [$original, array_replace($original, ['express_no' => 'SECOND'])]]; })());
$data = (new AccessoryReshipPageData($repo, new AccessoryReshipMatcher))->page();
$this->assertCount(50, $data['reshipRows']);
$this->assertSame(105, $data['reshipRows']->total());
$this->assertSame(105, $data['reshipSummary']['matched']);
$this->assertSame(1050, $data['reshipSummary']['amount']);
$this->assertSame(105, $data['reshipSummary']['ambiguous']);
}
}