fix(配件扣款): 自有快递优先扣款并按代发配置识别 #1769

Open
limeng wants to merge 1 commits from fix/limeng-accessory-own-courier-deductions into main
4 changed files with 82 additions and 29 deletions

View File

@ -36,6 +36,14 @@ class SupplierAccessoryFreightRepository
->map(static fn ($group) => $group->map(static fn ($row) => (array) $row)->all());
// 复用代发厂家设置;整月只读一次,且每个快递名只匹配一次(含未命中)。
$factories = $db->table('dropship_factories')->orderBy('id')->get(['warehouse', 'keywords']);
// 和代发对账一致:自有快递以对账分组里的完整快递名称为准,优先于厂家关键字。
$ownCouriers = [];
foreach ($db->table('courier_bill_groups')->get(['express_names']) as $group) {
foreach ((array) json_decode((string) $group->express_names, true, 512, JSON_THROW_ON_ERROR) as $name) {
$name = trim((string) $name);
if ($name !== '') $ownCouriers[$name] = true;
}
}
$dropshipWarehouses = [];
$start = \Carbon\Carbon::createFromFormat('!Y-m', $month);
foreach ($this->shipping->accessoryFreightBatches($start->format('Y-m-d'), $start->copy()->addMonth()->format('Y-m-d')) as $batch) {
@ -48,10 +56,11 @@ class SupplierAccessoryFreightRepository
$candidates = $products->get($barcode, []);
$supplierName = trim((string) ($candidates[0]['supplier_name'] ?? ''));
$courierName = trim((string) ($row['express_name1'] ?? '')) ?: trim((string) ($row['express_name2'] ?? ''));
$isOwnCourier = isset($ownCouriers[$courierName]);
if (!array_key_exists($courierName, $dropshipWarehouses)) {
$dropshipWarehouses[$courierName] = $this->matcher->dropshipWarehouse($courierName, $factories);
$dropshipWarehouses[$courierName] = $isOwnCourier ? null : $this->matcher->dropshipWarehouse($courierName, $factories);
}
yield $this->matcher->match($row, $candidates, $suppliers->get($supplierName, []), $couriers->get($courierName, []), $dropshipWarehouses[$courierName]);
yield $this->matcher->match($row, $candidates, $suppliers->get($supplierName, []), $couriers->get($courierName, []), $dropshipWarehouses[$courierName], $isOwnCourier);
}
}
}

View File

@ -8,7 +8,7 @@ class SupplierAccessoryFreightMatcher
{
public const STATES = ['ready' => '可扣款', 'excluded' => '不扣款', 'pending' => '待核实'];
public function match(array $row, array $products, array $suppliers, array $couriers = [], ?string $dropshipWarehouse = null): array
public function match(array $row, array $products, array $suppliers, array $couriers = [], ?string $dropshipWarehouse = null, bool $isOwnCourier = false): array
{
$result = $this->matchSupplier($row, $products, $suppliers);
$attributes = array_values(array_unique(array_map(static fn ($courier) => trim((string) ($courier['exp_properties'] ?? '')), $couriers)));
@ -20,6 +20,10 @@ class SupplierAccessoryFreightMatcher
$result['reason'] = '外采快递不扣配件运费';
return $result;
}
if ($isOwnCourier) {
if ($result['state'] === 'ready') $result['reason'] = '自有快递,按山东、河北供应商扣除全部配件运费';
return $result;
}
if ($dropshipWarehouse !== null) {
$result['state'] = 'excluded';
$result['deduction_cents'] = 0;
@ -36,16 +40,16 @@ class SupplierAccessoryFreightMatcher
return $result;
}
/** 同一条厂家配置的关键字须同时出现在快递名和代发仓名中。 */
/** 以代发厂家配置的快递关键字识别,不再用仓库名的字样判断归属。自有快递由调用方优先排除。 */
public function dropshipWarehouse(string $courier, iterable $factories): ?string
{
$courier = trim($courier);
if ($courier === '') return null;
foreach ($factories as $factory) {
$warehouse = trim((string) $factory->warehouse);
if (!str_contains($warehouse, '代发仓')) continue;
if ($warehouse === '') continue;
foreach (DropshipFreightStore::splitKeywords((string) $factory->keywords) as $keyword) {
if (str_contains($warehouse, $keyword) && str_contains($courier, $keyword)) return $warehouse;
if (str_contains($courier, $keyword)) return $warehouse;
}
}
return null;

View File

@ -21,7 +21,7 @@
<div><span>待核实</span><strong>{{ number_format($freightSummary['pending']) }}</strong></div>
<div><span>可扣运费合计(元)</span><strong>{{ number_format($freightSummary['amount'] / 100, 2) }}</strong></div>
</div>
<details class="sf-rules"><summary>扣款规则与金额口径</summary><p>仅取所选月份仓库为“常州简尚家居有限公司”的发货包裹。取第一个逗号前的条形码,再去掉最后一个“-”及其后缀,用处理后的条形码匹配商品资料条形码,再按商品供应商名称匹配供应商管理。联系人省为山东、山东省、河北、河北省的供应商,扣除对应包裹全部运费。每个发货包裹只计一次;不需要匹配首发单。外采快递不扣运费;按快递名称匹配工作平台快递资料,快递属性为“工厂”的包裹不扣运费。按代发厂家设置,同一配置的快递关键字同时出现在快递名称和代发仓名称中的,也不扣运费(如“浩浦极兔”与“工厂-河北浩浦代发仓”均包含“浩浦”)。使用快递名称1,为空时使用快递名称2。同名快递属性冲突时待核实;属性为空或未匹配时沿用其余规则。其他省份不扣,未匹配、资料缺失、供应商或省份冲突、运费异常的记录待核实。此处展示扣除明细,不自动入账。</p></details>
<details class="sf-rules"><summary>扣款规则与金额口径</summary><p>仅取所选月份仓库为“常州简尚家居有限公司”的发货包裹。取第一个逗号前的条形码,再去掉最后一个“-”及其后缀,用处理后的条形码匹配商品资料条形码,再按商品供应商名称匹配供应商管理。联系人省为山东、山东省、河北、河北省的供应商,扣除对应包裹全部运费。每个发货包裹只计一次;不需要匹配首发单。外采快递不扣运费;按快递名称匹配工作平台快递资料,快递属性为“工厂”的包裹不扣运费。代发快递按代发厂家设置的快递关键字识别,命中则不扣运费;不再按仓库名称的字样判断。自有快递以“快递账单对账 → 对账分组”中的完整快递名称为准,优先于代发关键字和“工厂”属性,按原供应商及运费规则正常扣款。使用快递名称1,为空时使用快递名称2。同名快递属性冲突时待核实;属性为空或未匹配时沿用其余规则。其他省份不扣,未匹配、资料缺失、供应商或省份冲突、运费异常的记录待核实。此处展示扣除明细,不自动入账。</p></details>
@if($freightError)<div class="sf-error" role="alert">{{ $freightError }}</div>@endif
<section class="sf-panel" aria-label="配件运费扣除明细">
<div class="sf-table-scroll"><table><thead><tr>

View File

@ -37,6 +37,7 @@ class SupplierAccessoryFreightTest extends TestCase
$db->setEventDispatcher(new \Illuminate\Events\Dispatcher($app));
$app->instance('db', $db->getDatabaseManager());
$db->getConnection()->statement('CREATE TABLE dropship_factories (id INTEGER PRIMARY KEY, warehouse TEXT, keywords TEXT)');
$db->getConnection()->statement('CREATE TABLE courier_bill_groups (id INTEGER PRIMARY KEY, express_names TEXT)');
Facade::clearResolvedInstances();
Facade::setFacadeApplication($app);
$app->instance('request', Request::create('/?month=2026-09&state=all'));
@ -126,25 +127,21 @@ class SupplierAccessoryFreightTest extends TestCase
$this->assertSame('同名快递属性冲突,需核实', $row['reason']);
}
public function test_dropship_keyword_must_match_courier_and_warehouse_in_the_same_configuration(): void
public function test_dropship_keywords_identify_courier_without_requiring_the_keyword_in_warehouse_name(): void
{
$matcher = new SupplierAccessoryFreightMatcher;
$factories = [
(object) ['warehouse' => '工厂-河北浩浦代发仓', 'keywords' => ' 浩浦, 浩浦 '],
(object) ['warehouse' => '工厂-河北森卓代发仓', 'keywords' => '四强'],
(object) ['warehouse' => '工厂-普通仓库', 'keywords' => '普通'],
(object) ['warehouse' => '', 'keywords' => '空仓库'],
(object) ['warehouse' => '工厂-空配置代发仓', 'keywords' => ''],
];
$this->assertSame('工厂-河北浩浦代发仓', $matcher->dropshipWarehouse(' 浩浦极兔 ', $factories));
foreach (['', '极兔', '其他极兔', '四强圆通', '普通快递', '空配置极兔'] as $courier) {
$this->assertSame('工厂-河北森卓代发仓', $matcher->dropshipWarehouse('四强圆通', $factories));
foreach (['', '极兔', '其他极兔', '空仓库快递', '空配置极兔'] as $courier) {
$this->assertNull($matcher->dropshipWarehouse($courier, $factories));
}
$this->assertNull($matcher->dropshipWarehouse('浩浦极兔', []));
// 不能将另一条配置的仓库和这条配置的关键字拼成一次命中。
$this->assertNull($matcher->dropshipWarehouse('四强圆通', [
(object) ['warehouse' => '工厂-河北森卓代发仓', 'keywords' => '四强'],
(object) ['warehouse' => '工厂-河北四强代发仓', 'keywords' => '森卓'],
]));
$warehouse = $matcher->dropshipWarehouse('浩浦极兔', $factories);
foreach ([[], [['exp_properties' => '简尚']], [['exp_properties' => '工厂'], ['exp_properties' => '简尚']]] as $couriers) {
$row = $matcher->match($this->row(['express_name1' => '浩浦极兔']),
@ -157,6 +154,29 @@ class SupplierAccessoryFreightTest extends TestCase
}
}
public function test_own_couriers_keep_supplier_deductions_despite_dropship_or_factory_attributes(): void
{
$matcher = new SupplierAccessoryFreightMatcher;
foreach ([[], [['exp_properties' => '工厂']], [['exp_properties' => '工厂'], ['exp_properties' => '简尚']]] as $couriers) {
$row = $matcher->match($this->row(['express_name1' => '河北中通-江三']),
[['name' => '成品', 'supplier_name' => '甲']], [['linkerprovience' => '河北']], $couriers, '工厂-河北江三代发仓', true);
$this->assertSame('ready', $row['state']);
$this->assertSame(1235, $row['deduction_cents']);
$this->assertSame('自有快递,按山东、河北供应商扣除全部配件运费', $row['reason']);
}
foreach ([['products' => [], 'suppliers' => []], ['products' => [['name' => '成品', 'supplier_name' => '甲']], 'suppliers' => []]] as $missing) {
$row = $matcher->match($this->row(), $missing['products'], $missing['suppliers'], [], '工厂-河北江三代发仓', true);
$this->assertSame('pending', $row['state']);
$this->assertSame(0, $row['deduction_cents']);
}
$row = $matcher->match($this->row(), [['name' => '成品', 'supplier_name' => '甲']], [['linkerprovience' => '江苏']], [], null, true);
$this->assertSame('excluded', $row['state']);
$this->assertSame(0, $row['deduction_cents']);
$row = $matcher->match($this->row(['express_name1' => '外采快递']), [], [], [], null, true);
$this->assertSame('excluded', $row['state']);
$this->assertSame('外采快递不扣配件运费', $row['reason']);
}
public function test_other_provinces_zero_invalid_and_equivalent_duplicate_provinces(): void
{
$matcher = new SupplierAccessoryFreightMatcher;
@ -195,6 +215,8 @@ class SupplierAccessoryFreightTest extends TestCase
]);
$connection->table('suppliers')->insert(['scmname' => '商品供应商', 'linkerprovience' => '河北省']);
$connection->table('dropship_factories')->insert(['warehouse' => '工厂-河北浩浦代发仓', 'keywords' => '浩浦']);
$connection->table('dropship_factories')->insert(['warehouse' => '工厂-河北江三代发仓', 'keywords' => '江三']);
$connection->table('courier_bill_groups')->insert(['express_names' => '[" 河北中通-江三 ","工厂快递"]']);
$registry = Mockery::mock(BusinessMirrorDatasetRegistry::class);
foreach ([ProductCatalogMirrorRepository::DATASET_KEY => 'products', SupplierManagementMirrorRepository::DATASET => 'suppliers', CourierInformationMirrorRepository::DATASET_KEY => 'couriers'] as $key => $table) {
$dataset = Mockery::mock(BusinessMirrorDataset::class);
@ -212,18 +234,22 @@ class SupplierAccessoryFreightTest extends TestCase
$this->row(['express_name1' => '补发快递', 'express_name2' => '工厂快递']),
$this->row(['express_name1' => '浩浦极兔']),
$this->row(['express_name1' => '', 'express_name2' => '浩浦极兔']),
$this->row(['express_name1' => '补发快递', 'express_name2' => '浩浦极兔'])];
$this->row(['express_name1' => '补发快递', 'express_name2' => '浩浦极兔']),
$this->row(['express_name1' => '河北中通-江三']),
$this->row(['express_name1' => '', 'express_name2' => '河北中通-江三']),
$this->row(['express_name1' => '浩浦极兔', 'express_name2' => '河北中通-江三']),
$this->row(['express_name1' => '江三圆通'])];
})());
$repo = new SupplierAccessoryFreightRepository($shipping, $registry, $mirror, new SupplierAccessoryFreightMatcher);
$rows = iterator_to_array($repo->rows('2026-09'));
$this->assertCount(7, $rows);
$this->assertCount(11, $rows);
$this->assertSame('商品供应商', $rows[0]['supplier_name']);
$this->assertSame(1235, $rows[0]['deduction_cents']);
$this->assertSame('简尚', $rows[0]['courier_attribute']);
foreach ([1, 2] as $index) {
$this->assertSame('工厂', $rows[$index]['courier_attribute']);
$this->assertSame('excluded', $rows[$index]['state']);
$this->assertSame(0, $rows[$index]['deduction_cents']);
$this->assertSame('ready', $rows[$index]['state']);
$this->assertSame(1235, $rows[$index]['deduction_cents']);
}
$this->assertSame('ready', $rows[3]['state']);
$this->assertSame('简尚', $rows[3]['courier_attribute']);
@ -234,6 +260,15 @@ class SupplierAccessoryFreightTest extends TestCase
}
$this->assertSame('ready', $rows[6]['state']);
$this->assertSame(1235, $rows[6]['deduction_cents']);
foreach ([7, 8] as $index) {
$this->assertSame('ready', $rows[$index]['state']);
$this->assertSame(1235, $rows[$index]['deduction_cents']);
$this->assertStringContainsString('自有快递', $rows[$index]['reason']);
}
foreach ([9, 10] as $index) {
$this->assertSame('excluded', $rows[$index]['state']);
$this->assertSame(0, $rows[$index]['deduction_cents']);
}
}
private function data(): SupplierAccessoryFreightPageData
@ -252,23 +287,24 @@ class SupplierAccessoryFreightTest extends TestCase
$repository = Mockery::mock(SupplierAccessoryFreightRepository::class);
$repository->shouldReceive('rows')->with('2026-09')->andReturnUsing(function () {
$matcher = new SupplierAccessoryFreightMatcher;
foreach (['工厂', '代发', '简尚'] as $attribute) {
yield $matcher->match($this->row(['express_no' => ['工厂' => 'FACTORY-1', '代发' => 'DROPSHIP-1', '简尚' => 'NORMAL-1'][$attribute]]),
foreach (['工厂', '代发', '简尚', '自有'] as $attribute) {
yield $matcher->match($this->row(['express_no' => ['工厂' => 'FACTORY-1', '代发' => 'DROPSHIP-1', '简尚' => 'NORMAL-1', '自有' => 'OWN-1'][$attribute]]),
[['name' => '成品', 'supplier_name' => '甲']], [['linkerprovience' => '河北']], [['exp_properties' => $attribute]],
$attribute === '代发' ? '工厂-河北浩浦代发仓' : null);
in_array($attribute, ['代发', '自有'], true) ? '工厂-河北浩浦代发仓' : null, $attribute === '自有');
}
});
$data = new SupplierAccessoryFreightPageData($repository);
app()->instance('request', Request::create('/?month=2026-09&state=ready'));
$page = $data->page();
$this->assertSame(['all' => 3, 'ready' => 1, 'excluded' => 2, 'pending' => 0, 'amount' => 1235], $page['freightSummary']);
$this->assertCount(1, $page['freightRows']);
$this->assertSame(['all' => 4, 'ready' => 2, 'excluded' => 2, 'pending' => 0, 'amount' => 2470], $page['freightSummary']);
$this->assertCount(2, $page['freightRows']);
$this->assertSame('NORMAL-1', $page['freightRows']->items()[0]['express_no']);
$controller = new \App\Http\Controllers\Business\SupplierAccessoryFreight;
$response = $controller->export($data);
ob_start(); $response->sendContent(); $csv = ob_get_clean();
$this->assertStringNotContainsString('FACTORY-1', $csv);
$this->assertStringNotContainsString('DROPSHIP-1', $csv);
$this->assertStringContainsString('OWN-1', $csv);
app()->instance('request', Request::create('/?month=2026-09&state=excluded&columns=express_no,courier_attribute,deduction,reason'));
$response = $controller->export($data);
ob_start(); $response->sendContent(); $csv = ob_get_clean();
@ -378,6 +414,7 @@ class SupplierAccessoryFreightTest extends TestCase
$connection->table('couriers')->insert(['expname' => sprintf('厂家%02d极兔', $i), 'exp_properties' => '简尚']);
if ($i < 37) $connection->table('dropship_factories')->insert(['warehouse' => sprintf('工厂-河北厂家%02d代发仓', $i), 'keywords' => sprintf('厂家%02d', $i)]);
}
$connection->table('courier_bill_groups')->insert(['express_names' => '["厂家00极兔"]']);
$registry = Mockery::mock(BusinessMirrorDatasetRegistry::class);
foreach ([ProductCatalogMirrorRepository::DATASET_KEY => 'products', SupplierManagementMirrorRepository::DATASET => 'suppliers', CourierInformationMirrorRepository::DATASET_KEY => 'couriers'] as $key => $table) {
$dataset = Mockery::mock(BusinessMirrorDataset::class);
@ -407,14 +444,16 @@ class SupplierAccessoryFreightTest extends TestCase
}
};
$data = new SupplierAccessoryFreightPageData(new SupplierAccessoryFreightRepository($shipping, $registry, $mirror, $matcher));
$ready = intdiv(42625, 79) * 42 + max(0, 42625 % 79 - 37);
$ready = intdiv(42625, 79) * 42 + max(0, 42625 % 79 - 37) + (int) ceil(42625 / 79);
$queries = 0;
$factoryQueries = 0;
$ownQueries = 0;
$sqlMs = 0;
$connection->listen(function ($query) use (&$queries, &$factoryQueries, &$sqlMs) {
$connection->listen(function ($query) use (&$queries, &$factoryQueries, &$ownQueries, &$sqlMs) {
$queries++;
$sqlMs += $query->time;
if (str_contains($query->sql, 'from "dropship_factories"')) $factoryQueries++;
if (str_contains($query->sql, 'from "courier_bill_groups"')) $ownQueries++;
});
$start = microtime(true);
app()->instance('request', Request::create('/?month=2026-09&state=ready'));
@ -428,7 +467,7 @@ class SupplierAccessoryFreightTest extends TestCase
$second = $data->page();
$this->assertCount(50, $second['freightRows']);
$this->assertNotSame($page['freightRows']->items()[0]['express_no'], $second['freightRows']->items()[0]['express_no']);
app()->instance('request', Request::create('/?month=2026-09&state=excluded&express_no=PERF0'));
app()->instance('request', Request::create('/?month=2026-09&state=excluded&express_no=PERF42600'));
$filtered = $data->page();
$this->assertSame(1, $filtered['freightRows']->total());
$this->assertSame(0, $filtered['freightSummary']['amount']);
@ -438,8 +477,9 @@ class SupplierAccessoryFreightTest extends TestCase
$this->assertSame($ready + 1, substr_count($csv, "\n"));
$this->assertSame($ready, substr_count($csv, ',0.10'));
$this->assertSame(4, $factoryQueries);
// 每次读取都包含命中和未命中项;42,625 行只需判断 79 个名称。
$this->assertSame(79 * 4, $matcher->lookups);
$this->assertSame(4, $ownQueries);
// 自有快递优先排除;42,625 行只需判断剩下 78 个名称。
$this->assertSame(78 * 4, $matcher->lookups);
fwrite(STDERR, sprintf("\nACCESSORY_MONTH rows=42625 couriers=79 factories=37 first_second_filter_export=%.3fs php_peak_mb=%.1f queries=%d sql_ms=%.1f rss_peak_mb=%.1f\n",
microtime(true) - $start, memory_get_peak_usage(true) / 1048576, $queries, $sqlMs, (getrusage()['ru_maxrss'] ?? 0) / 1024));
}