修复退回附加费跨月匹配与补记账自动更新 #1792

Open
limeng wants to merge 1 commits from fix/limeng-surcharge-return-matching into main
14 changed files with 306 additions and 43 deletions

View File

@ -4,6 +4,7 @@ namespace App\Console\Commands;
use App\Support\CourierBills\CourierBillMatcher;
use App\Support\CourierBills\SurchargeSettlementMatcher;
use App\Support\CourierBills\Rebooks;
use App\Support\DropshipFreight\DropshipConfirmation;
use App\Support\DropshipFreight\DropshipFreightStore;
use Illuminate\Console\Command;
@ -16,16 +17,33 @@ class MatchBillSurcharges extends Command
{
public const AUTO_MATCH_HOLDS = 'bill-surcharge-auto-match-holds';
protected $signature='courier-surcharge:match-bills {--month= : 账单月份 YYYY-MM,默认上月} {--statement=* : 指定快递对账单} {--factory=* : 指定代发厂家} {--all : 匹配该月全部未确认账单} {--existing-only : 只更新已建立附加费匹配的账单} {--company=1}';
protected $signature='courier-surcharge:match-bills {--month= : 账单月份 YYYY-MM,默认上月} {--all-months : 刷新全部已有账期,需同时指定 --all --existing-only} {--refresh-rebooks : 同时刷新未确认账单的补记账汇总} {--statement=* : 指定快递对账单} {--factory=* : 指定代发厂家} {--all : 匹配该月全部未确认账单} {--existing-only : 只更新已建立附加费匹配的账单} {--company=1}';
protected $description='匹配指定月份账单的附加费金额及商品信息,已确认账单不变';
public function handle(SurchargeSettlementMatcher $matcher): int
{
\App\Models\Common\Company::findOrFail((int) $this->option('company'))->makeCurrent();
if ($this->option('all-months')) {
if (! $this->option('all') || ! $this->option('existing-only') || $this->option('month')) {
$this->error('--all-months 需要 --all --existing-only,且不能指定 --month');
return self::FAILURE;
}
$months = DB::connection('business_mirror')->table(SurchargeSettlementMatcher::TABLE)->select('bill_month')
->union(DB::connection('business_mirror')->table('courier_bill_statements')->select('bill_month')->where('status', '<>', 'confirmed'))
->orderBy('bill_month')->pluck('bill_month');
foreach ($months as $month) {
$status = $this->call(self::class, ['--month' => $month, '--all' => true,
'--existing-only' => true, '--refresh-rebooks' => (bool) $this->option('refresh-rebooks'), '--company' => $this->option('company')]);
if ($status !== self::SUCCESS) return $status;
}
return self::SUCCESS;
}
$month=(string)($this->option('month')?:now('Asia/Shanghai')->subMonthNoOverflow()->format('Y-m'));
if(!preg_match('/^\d{4}-(0[1-9]|1[0-2])$/D',$month)){$this->error('请填写有效账单月份 YYYY-MM');return self::FAILURE;}
if(!$this->option('all')&&$this->option('statement')===[]&&$this->option('factory')===[]){$this->error('请选择对账单、厂家或 --all');return self::FAILURE;}
if(app()->environment('production')&&!env('FINANCE_BATCH_CONTAINER')){$this->error('请通过 run-finance-batch.sh 执行。');return self::FAILURE;}
$lock=Cache::lock('bill-surcharge-matching',3900);if(!$lock->get()){$this->error('附加费匹配正在运行');return self::FAILURE;}
$started = microtime(true);
try{
$db=DB::connection('business_mirror');$statements=[];$factories=[];
$holds=[];
@ -51,7 +69,24 @@ class MatchBillSurcharges extends Command
$matcher->dropship((int)$id,$month);$this->line('代发厂家 #'.$id.' 附加费已匹配');
}
}
$this->info('附加费匹配完成:'.$month.';快递对账单 '.count($statements).' 张,代发厂家 '.count($factories).' 家。');return self::SUCCESS;
if ($this->option('refresh-rebooks')) {
foreach ($db->table('courier_bill_statements')->where('bill_month', $month)->where('status', '<>', 'confirmed')
->when(! $this->option('all'), fn ($q) => $q->whereIn('id', array_map('intval', $this->option('statement'))))->orderBy('id')->pluck('id') as $id) {
$db->transaction(function () use ($db, $id): void {
$statement = $db->table('courier_bill_statements')->where('id', $id)->lockForUpdate()->first();
if (! $statement || $statement->status === 'confirmed') return;
$items = $db->table('courier_bill_summary_items')->where('statement_id', $id)->get();
foreach (app(Rebooks::class)->summaryItems((int) $id, $items) as $item) {
if (! $item->manual && Rebooks::isRebookLabel($item->label)) {
$db->table('courier_bill_summary_items')->where('id', $item->id)->update(['self_amount' => $item->self_amount]);
}
}
});
}
}
$this->info('附加费匹配完成:'.$month.';快递对账单 '.count($statements).' 张,代发厂家 '.count($factories).' 家。');
$this->line(sprintf('耗时 %.2f 秒,PHP 峰值 %.2f MiB。', microtime(true) - $started, memory_get_peak_usage(true) / 1048576));
return self::SUCCESS;
}catch(Throwable $e){report($e);$this->error('附加费匹配失败:'.$e->getMessage());return self::FAILURE;}
finally{$lock->release();}
}

View File

@ -9,7 +9,7 @@ use Throwable;
class SyncReturnedParcels extends Command
{
protected $signature = 'business-mirror:sync-returned-parcels {--from= : 进仓开始日期(含)} {--to= : 进仓结束日期(含)} {--deduplicate : 只合并现有镜像中两来源相同的售后商品,不读取上游}';
protected $signature = 'business-mirror:sync-returned-parcels {--from= : 进仓开始日期(含)} {--to= : 进仓结束日期(含)} {--deduplicate : 只合并现有镜像中两来源相同的售后商品,不读取上游} {--match-surcharges : 同步成功后刷新已有未确认账单附加费}';
protected $description = '同步聚水潭售后退货退款到快递应付退回件明细';
public function handle(ReturnedParcelSynchronizer $synchronizer): int
@ -44,6 +44,10 @@ class SyncReturnedParcels extends Command
$result = $synchronizer->sync($from, $to, fn (int $n, int $total) => $this->line("已扫描 {$n} / {$total} 行"));
$this->info(sprintf('退回件同步完成:%s 至 %s,%d 条商品明细,耗时 %.2f 秒,PHP 峰值 %.2f MiB。',
$from, $to, $result['rows'], $result['seconds'], $result['peak_mb']));
if ($this->option('match-surcharges')) {
// 新退回可能属于更早账期,沿用既有确认和人工保留保护。
return $this->call(MatchBillSurcharges::class, ['--all' => true, '--existing-only' => true, '--all-months' => true, '--refresh-rebooks' => true]);
}
return self::SUCCESS;
} catch (Throwable $exception) {
report($exception);

View File

@ -18,7 +18,7 @@ final class BillSurchargeQuoteCalculator
return implode('|', [$ruleId, $month, strtoupper(trim($waybill)), $workOrder]);
}
/** 所有附加费均按自然月含账单当月,匹配最近3个月。 */
/** 发货、查件工单按账单当月及前两个月匹配;退回进仓不受此窗口限制。 */
public static function window(string $month): array
{
$start = Carbon::parse($month . '-01')->startOfMonth();
@ -42,7 +42,7 @@ final class BillSurchargeQuoteCalculator
|| ($r->mode === '取发出运费' && trim($r->condition) === '查件扣单并且买家原因'));
$workOrders = $needsService ? $this->workOrders($waybills, $month) : [];
$returns = $rules->contains(fn ($r) => $r->mode === '固定单价' && str_contains($r->condition, '已退回'))
? $this->receivedReturns($workOrders, $month) : [];
? $this->receivedReturns($workOrders, $waybills) : [];
$confirmations = $this->buyerConfirmations($rules, $workOrders, $month);
$rows = $notes = $metadata = [];
$window = self::window($month);
@ -77,8 +77,10 @@ final class BillSurchargeQuoteCalculator
'platform_product_id' => $ship['item_id'] ?? null, 'product_code' => $ship['barcode'] ?? null,
'shop_name' => $ship['shop_name'] ?? null, 'online_order_no' => $ship['trade_no'] ?? null,
'source_kind' => 'bill_quote', 'source_key' => $wb . '|' . $type, 'outbound_io_id' => null];
$feeReturns = $returns;
if (isset($returns['waybill:' . $wb])) $feeReturns['_waybill'] = $returns['waybill:' . $wb];
$result = $this->price($rule, $type, $ship, $freights[$wb] ?? [], $workOrders[$wb] ?? [],
$confirmations[$rule->id][$wb] ?? [], $returns);
$confirmations[$rule->id][$wb] ?? [], $feeReturns);
if (is_string($result)) { $notes[$wb][$type] = '报价 #' . $rule->id . ':' . $result; continue; }
foreach ($result as $price) $rows[$wb][$type][] = (object) array_replace($base, $price,
['settlement_status' => '已计算', 'evidence' => '报价 #' . $rule->id . ';' . $price['evidence']]);
@ -218,8 +220,8 @@ final class BillSurchargeQuoteCalculator
if (! $reason['eligible']) return [['settlement_amount' => 0, 'evidence' => $reason['evidence']]];
$evidence = $reason['evidence'];
if (str_contains($condition, '已退回')) {
$received = $returns[$reason['order_id']] ?? null;
if ($received === null) return '未找到对应订单在匹配范围内的有效退回进仓明细,待核实';
$received = $returns['_waybill'] ?? $returns[$reason['order_id']] ?? null;
if ($received === null) return '未找到对应订单的有效退回进仓明细,待核实';
$evidence .= ';退回进仓 ' . $received;
}
} elseif (preg_match('/^查件类型\/查件原因是([^\/]+)\/([^\/]+)$/u', $condition, $path)) {
@ -273,8 +275,8 @@ final class BillSurchargeQuoteCalculator
. '固定单价 ' . number_format($amount, 2, '.', '') . ' 元/单,按票计一次']];
}
/** 只按本批工单订单ID关联已有售后镜像,使用o_id/as_id索引,不扫描退回件全表。 */
private function receivedReturns(array $orders, string $month): array
/** 按本批订单索引查询最新普通/淘系退回件,旧售后镜像补充历史;不限制进仓日期。 */
private function receivedReturns(array $orders, array $waybills): array
{
$ids = [];
foreach ($orders as $records) foreach ($records as $order) {
@ -282,16 +284,40 @@ final class BillSurchargeQuoteCalculator
$id = trim((string) ($fields['o_id'] ?? ''));
if (ctype_digit($id) && $id !== '0') $ids[$id] = true;
}
if ($ids === []) return [];
$db = DB::connection(config('upstream_mirrors.connection', 'business_mirror'));
if (! $db->getSchemaBuilder()->hasTable('ops_jst_return_refund_info') || ! $db->getSchemaBuilder()->hasTable('ops_jst_return_refund_item')) return [];
$schema = $db->getSchemaBuilder();
$hasReturnedParcels = $schema->hasTable('courier_returned_parcels');
$legacySources = array_filter([
['ops_jst_return_refund_info', 'ops_jst_return_refund_item'],
['ops_jst_qmcust_refunds', 'ops_jst_qmcust_refund_items'],
], fn ($tables) => $schema->hasTable($tables[0]) && $schema->hasTable($tables[1]));
$result = [];
foreach (array_chunk(array_keys($ids), 300) as $chunk) {
$rows = $db->table('ops_jst_return_refund_info as h')->join('ops_jst_return_refund_item as i', 'i.as_id', '=', 'h.as_id')
->whereIn('h.o_id', $chunk)->where('i.r_qty', '>', 0)
->where('i.receive_date', '>=', self::window($month)['from'])->where('i.receive_date', '<', self::window($month)['until'])
->select('h.o_id')->selectRaw('MIN(' . $db->getQueryGrammar()->wrap('i.receive_date') . ') AS received_at')->groupBy('h.o_id')->get();
foreach ($rows as $row) $result[(string) $row->o_id] = $row->received_at;
if ($hasReturnedParcels) {
$rows = $db->table('courier_returned_parcels')->whereIn('order_id', array_map('strval', $chunk))
->where('returned_qty', '>', 0)->whereNotNull('received_at')
->select('order_id', 'waybill')->selectRaw('MIN(received_at) AS received_at')
->groupBy('order_id', 'waybill')->orderBy('received_at')->get();
foreach ($rows as $row) $result[(string) $row->order_id] ??= $row->received_at
. (trim((string) $row->waybill) !== '' ? ';退回单号 ' . $row->waybill : '');
}
foreach ($legacySources as [$header, $items]) {
$remaining = array_values(array_filter($chunk, fn ($id) => ! isset($result[(string) $id])));
if ($remaining === []) break;
$rows = $db->table($header . ' as h')->join($items . ' as i', 'i.as_id', '=', 'h.as_id')
->whereIn('h.o_id', $remaining)->where('i.r_qty', '>', 0)->whereNotNull('i.receive_date')
->select('h.o_id')->selectRaw('MIN(' . $db->getQueryGrammar()->wrap('i.receive_date') . ') AS received_at')->groupBy('h.o_id')->get();
foreach ($rows as $row) $result[(string) $row->o_id] = $row->received_at;
}
}
if ($hasReturnedParcels) {
$query = $db->table('courier_returned_parcels')->where('returned_qty', '>', 0)->whereNotNull('received_at');
foreach (WaybillMatch::find($query, 'waybill', $waybills, ['waybill', 'received_at']) as $number => $match) {
$records = $match['rows'];
usort($records, fn ($a, $b) => $a->received_at <=> $b->received_at);
$result['waybill:' . strtoupper($number)] = $records[0]->received_at . ';退回单号 ' . $records[0]->waybill
. ($match['exact'] ? '(精确匹配)' : '(模糊匹配:格式或T前缀)');
}
}
return $result;
}

View File

@ -13,32 +13,28 @@ final class RebookReturns
$wanted = [];
foreach ($rows as $row) {
foreach (self::numbers($row) as $number) {
$wanted[self::key($number)] = true;
$wanted[$number] = true;
}
}
$db = Rebooks::db();
$available = $wanted !== [] && Schema::connection($db->getName())->hasTable('courier_returned_parcels');
$found = [];
if ($available) {
// 按主键分批读取窄列,一次遍历,不能对每个工单循环模糊扫全表。
foreach ($db->table('courier_returned_parcels')->where('returned_qty', '>', 0)
->select(['source_id', 'waybill', 'received_at'])->lazyById(1000, 'source_id') as $record) {
$key = self::key((string) $record->waybill);
if ($key !== null && isset($wanted[$key])) {
$found[$key][] = ['waybill' => trim((string) $record->waybill), 'received_at' => (string) $record->received_at];
}
}
// 按实际单号查询,两来源相同的 source_id 不再影响匹配。
$found = WaybillMatch::find($db->table('courier_returned_parcels')->where('returned_qty', '>', 0)
->whereNotNull('received_at'), 'waybill', array_keys($wanted), ['waybill', 'received_at']);
}
foreach ($rows as &$row) {
$exact = $fuzzy = [];
foreach (self::numbers($row) as $number) {
foreach ($found[self::key($number)] ?? [] as $record) {
$fuzzy[] = $record;
if ($number === $record['waybill']) {
$exact[] = $record;
}
$match = $found[$number] ?? [];
foreach ($match['rows'] ?? [] as $record) {
$value = ['waybill' => $record->waybill, 'received_at' => $record->received_at];
if ($match['exact']) $exact[] = $value;
else $fuzzy[] = $value;
}
}
$fuzzy = $exact === [] ? WaybillMatch::uniqueFuzzy($fuzzy) : [];
$matches = $exact ?: $fuzzy;
$analysis = trim((string) ($row['analysis'] ?? ''));
$historicReturn = str_contains($analysis, '已退回') || str_contains($analysis, '原单退回改0') || str_contains($analysis, '换单退回');
@ -73,8 +69,6 @@ final class RebookReturns
private static function key(string $number): ?string
{
$number = Waybill::normalize(mb_convert_kana($number, 'as'));
return $number === null ? null : (preg_match('/^T\d{10,30}$/', $number) ? substr($number, 1) : $number);
return WaybillMatch::key($number);
}
}

View File

@ -0,0 +1,71 @@
<?php
namespace App\Support\CourierBills;
/** Only formatting and the established numeric T prefix may be treated as equivalent. */
final class WaybillMatch
{
/** Indexed exact lookup first; formatting fallback only receives unresolved numbers. */
public static function find($query, string $column, array $numbers, array $columns): array
{
$result = [];
$numbers = array_values(array_unique(array_map('strval', $numbers)));
foreach (array_chunk($numbers, 300) as $chunk) {
foreach ((clone $query)->whereIn($column, $chunk)->get($columns) as $row) {
$actual = (string) $row->{$column};
if (in_array($actual, $chunk, true)) {
$result[$actual]['exact'] = true;
$result[$actual]['rows'][] = $row;
}
}
}
$pending = [];
foreach ($numbers as $number) if (! isset($result[$number]) && ($key = self::key($number)) !== null) $pending[$key][] = $number;
$expression = self::expression($query, $column);
foreach (array_chunk(array_keys($pending), 300) as $keys) {
$variants = $keys;
foreach ($keys as $key) {
if (ctype_digit((string) $key)) {
$variants[] = 'T' . $key;
$variants[] = $key . '.0';
}
}
$found = [];
foreach ((clone $query)->whereIn($query->getConnection()->raw($expression), array_map('strval', $variants))->get($columns) as $row) {
$key = self::key((string) $row->{$column});
if ($key !== null && isset($pending[$key])) $found[$key][] = $row;
}
foreach ($found as $key => $rows) {
if (count(array_unique(array_map(fn ($r) => Waybill::normalize(mb_convert_kana((string) $r->{$column}, 'as')), $rows))) !== 1) continue;
foreach ($pending[$key] as $number) $result[$number] = ['exact' => false, 'rows' => $rows];
}
}
return $result;
}
public static function expression($query, string $column): string
{
$expression = $query->getGrammar()->wrap($column);
foreach ([" ", "\t", "\r", "\n", "'", '@', '`', ''', ' '] as $remove) {
$literal = str_replace("'", "''", $remove);
$expression = "REPLACE({$expression}, '{$literal}', '')";
}
return 'UPPER(' . $expression . ')';
}
public static function key(string $number): ?string
{
$number = Waybill::normalize(mb_convert_kana($number, 'as'));
return $number === null ? null : (preg_match('/^T\d{10,30}$/', $number) ? substr($number, 1) : $number);
}
public static function uniqueFuzzy(array $records): array
{
$keys = [];
foreach ($records as $record) {
$number = Waybill::normalize(mb_convert_kana((string) $record['waybill'], 'as'));
if ($number !== null) $keys[$number] = true;
}
return count($keys) === 1 ? $records : [];
}
}

View File

@ -2,6 +2,7 @@
namespace App\Support;
use App\Support\CourierBills\WaybillMatch;
use Illuminate\Support\Facades\DB;
use RuntimeException;
use Throwable;
@ -81,11 +82,12 @@ final class UnshippedWaybills
public function unshippedSources(array $waybills): array
{
$result = [];
foreach (array_chunk(array_unique(array_filter(array_map(self::normalize(...), $waybills),
fn ($number) => $number !== '' && !self::isPlaceholder($number))), 500) as $chunk) {
foreach ($this->results()->whereIn('waybill_no', $chunk)->distinct()->get(['waybill_no', 'source']) as $row) {
$numbers = array_values(array_unique(array_filter(array_map(self::normalize(...), $waybills),
fn ($number) => $number !== '' && !self::isPlaceholder($number))));
foreach (WaybillMatch::find($this->results(), 'waybill_no', $numbers, ['waybill_no', 'source']) as $number => $match) {
foreach ($match['rows'] as $row) {
$label = self::label($row->source);
$result[$row->waybill_no][$label] = $label;
$result[$number][$label] = $label;
}
}

View File

@ -0,0 +1,24 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
$schema = Schema::connection(config('upstream_mirrors.connection', 'business_mirror'));
if ($schema->hasTable('courier_returned_parcels') && ! $schema->hasIndex('courier_returned_parcels', 'returned_parcel_order_received')) {
$schema->table('courier_returned_parcels', fn (Blueprint $table) => $table->index(['order_id', 'received_at'], 'returned_parcel_order_received'));
}
}
public function down(): void
{
$schema = Schema::connection(config('upstream_mirrors.connection', 'business_mirror'));
if ($schema->hasTable('courier_returned_parcels') && $schema->hasIndex('courier_returned_parcels', 'returned_parcel_order_received')) {
$schema->table('courier_returned_parcels', fn (Blueprint $table) => $table->dropIndex('returned_parcel_order_received'));
}
}
};

View File

@ -248,7 +248,7 @@ CRON_TZ=Asia/Shanghai
15 10 * * * root /usr/bin/flock -n /run/caiwu-inventory-warehouse-alert.lock /usr/bin/docker exec -u www-data caiwu_app php artisan inventory:sync-warehouse-mapping-alert --quiet >/dev/null 2>&1
# 退款待确认四张副本库镜像每天 06:00 在独立批容器完整跑完一轮,确保 10:00 前完成。
0 6 * * * root /bin/sh /opt/caiwuxitong/run-finance-batch.sh business-mirror:sync-tables --daily-only --max-batches=0 --quiet >/dev/null 2>&1
0 10,16 * * * root /bin/sh /opt/caiwuxitong/run-finance-batch.sh business-mirror:sync-returned-parcels >>/opt/caiwuxitong/runtime/returned-parcels-sync.log 2>&1
0 10,16 * * * root /bin/sh /opt/caiwuxitong/run-finance-batch.sh business-mirror:sync-returned-parcels --match-surcharges >>/opt/caiwuxitong/runtime/returned-parcels-sync.log 2>&1
*/2 * * * * root /usr/bin/flock -n /run/caiwu-esign-polling.lock /usr/bin/docker exec -u www-data caiwu_app php artisan esign:poll-signatures --quiet >/dev/null 2>&1
# 钉钉入驻审批通过后回传内部快递资料;与上游全量同步分开,单轮最多25单、115秒。
*/2 * * * * root /usr/bin/flock -n /run/caiwu-courier-profile-sync.lock /usr/bin/timeout 115 /usr/bin/docker exec -u www-data caiwu_app php artisan courier-onboarding:sync-dingtalk-profiles --limit=25 --quiet >/dev/null 2>&1

View File

@ -252,7 +252,7 @@ CRON_TZ=Asia/Shanghai
15 10 * * * root /usr/bin/flock -n /run/caiwu-inventory-warehouse-alert.lock /usr/bin/docker exec -u www-data caiwu_app php artisan inventory:sync-warehouse-mapping-alert --quiet >/dev/null 2>&1
# 退款待确认四张副本库镜像每天 06:00 在独立批容器完整跑完一轮,确保 10:00 前完成。
0 6 * * * root /bin/sh /opt/caiwuxitong/run-finance-batch.sh business-mirror:sync-tables --daily-only --max-batches=0 --quiet >/dev/null 2>&1
0 10,16 * * * root /bin/sh /opt/caiwuxitong/run-finance-batch.sh business-mirror:sync-returned-parcels >>/opt/caiwuxitong/runtime/returned-parcels-sync.log 2>&1
0 10,16 * * * root /bin/sh /opt/caiwuxitong/run-finance-batch.sh business-mirror:sync-returned-parcels --match-surcharges >>/opt/caiwuxitong/runtime/returned-parcels-sync.log 2>&1
*/2 * * * * root /usr/bin/flock -n /run/caiwu-esign-polling.lock /usr/bin/docker exec -u www-data caiwu_app php artisan esign:poll-signatures --quiet >/dev/null 2>&1
# 钉钉入驻审批通过后回传内部快递资料;与上游全量同步分开,单轮最多25单、115秒。
*/2 * * * * root /usr/bin/flock -n /run/caiwu-courier-profile-sync.lock /usr/bin/timeout 115 /usr/bin/docker exec -u www-data caiwu_app php artisan courier-onboarding:sync-dingtalk-profiles --limit=25 --quiet >/dev/null 2>&1

View File

@ -38,6 +38,8 @@
两来源存在重叠:售后号、售后商品明细号、商品编码、进仓时间和实退数量全部相同才视为同一商品行,完整核对各源数量后保留普通来源行,淘系独有行正常发布。可用同命令加 `--deduplicate` 在独立批容器内仅校准现有派生结果,不重读上游;执行前备份镜像。
附加费“已退回”条件读取此镜像的普通、淘系有效进仓记录,并按订单关联、既有两类售后镜像补充历史;进仓日期不受账期限制,仍要求实退数量大于零、进仓日期非空。退回与未发出单号先精确查询,只对剩余单号处理格式和数字 T 前缀差异,多候选不自动归为同票。订单查询使用 `returned_parcel_order_received` 索引。每天 10:00、16:00 同步带 `--match-surcharges`,成功后通过 `courier-surcharge:match-bills --all --existing-only --all-months --refresh-rebooks` 刷新已有未确认账单的附加费和补记账汇总,保留已确认账单、人工金额与暂停自动匹配设置;同步失败不触发重算。补记账也按实际单号查询,不再依赖跨来源重复的行编号游标,进仓日期同样不限账期。
“未发出明细”每日 07:10 通过 `courier:sync-unshipped-waybills` 在同一受限批入口刷新。先完成上述退回件快照,再分别获取普通、淘系现场拦截的原订单发出单号;不因其他全量退款镜像失败而阻断。仓内未发从当前 `operations_replica/rpt.jst_workOrderInfo` 按 `Id` 每批读取 5,000 个类型索引,再按匹配类型的明确 ID 读取业务字段;不恢复退役 `jiansun` 连接。派生暂存 `courier_unshipped_stage` 及数据集 `derived.courier-unshipped-warehouse` 保留断点,完整后才发布,历史导入保留。`--max-batches` 可控制单轮批数,`--source` 可指定来源,刚完成退回件校准时可用 `--skip-returned`。换单除人工操作日志外,还读取发货镜像明确记录的 `front_no`;该依据时间是发货时间,不冒充换单操作时间,也不把国际物流号当旧单号。无历史导入且退回件覆盖不足时拒绝发布拦截结果,避免把不完整范围当全量。
| 状态 | 说明 |

View File

@ -129,6 +129,7 @@ class BillSurchargeMatchingTest extends FeatureTestCase
$this->artisan('courier-surcharge:match-bills',['--month'=>'2026-11'])->assertFailed();
$this->artisan('courier-surcharge:match-bills',['--month'=>'2026-13','--all'=>true])->assertFailed();
$this->artisan('courier-surcharge:match-bills',['--month'=>'2026-11','--all'=>true])->assertSuccessful();
$this->artisan('courier-surcharge:match-bills',['--all-months'=>true])->assertFailed();
}
public function test_daily_refresh_does_not_enable_legacy_bills_and_only_new_sources_are_counted(): void
@ -155,6 +156,11 @@ class BillSurchargeMatchingTest extends FeatureTestCase
$this->artisan('courier-surcharge:match-bills',['--month'=>'2026-11','--all'=>true,'--existing-only'=>true])->assertSuccessful();
$this->assertEquals(4.25,$matcher->query('courier',$ids[1])->value('self_amount'));
$matcher->courier($ids[0]);$this->assertEquals(10,$matcher->query('courier',$ids[0])->value('self_amount'));
$db->table('courier_bill_statements')->where('id',$ids[1])->update(['status'=>'confirmed']);
$db->table('courier_surcharge_settlement_rows')->where('source_key','GD-NEW')->update(['settlement_amount'=>5.25]);
$this->artisan('courier-surcharge:match-bills',['--all-months'=>true,'--all'=>true,'--existing-only'=>true])->assertSuccessful();
$this->assertEquals(4.25,$matcher->query('courier',$ids[1])->value('self_amount'));
$this->assertEquals(10,$matcher->query('courier',$ids[0])->value('self_amount'));
}
public function test_dropship_rejects_a_matching_courier_from_another_factory_warehouse(): void
@ -380,8 +386,9 @@ class BillSurchargeMatchingTest extends FeatureTestCase
$schema->create('ops_jst_return_refund_info',function(Blueprint $t){$t->integer('as_id');$t->integer('o_id')->index();});
$schema->create('ops_jst_return_refund_item',function(Blueprint $t){$t->integer('as_id')->index();$t->integer('r_qty');$t->dateTime('receive_date')->nullable();});
$cases=[['FIXRET001','扣单/买家-不想要','2026-09-01 00:00:00',1,30],['FIXRET002','扣单/买家-不想要',null,0,null],
['FIXRET003','扣单/快递-破损','2026-11-01',1,0],['FIXRET004','扣单/买家-不想要','2026-12-01',1,null],
['FIXRET005','扣单/买家-不想要','2026-08-31 23:59:59',1,null],['FIXRET006','扣单/买家-不想要','2026-11-30 23:59:59',0,null]];
['FIXRET003','扣单/快递-破损','2026-11-01',1,0],['FIXRET004','扣单/买家-不想要','2026-12-01',1,30],
['FIXRET005','扣单/买家-不想要','2026-08-31 23:59:59',1,30],['FIXRET006','扣单/买家-不想要','2026-11-30 23:59:59',0,null],
['FIXRET007','扣单/买家-不想要',null,1,null]];
$input=[];
foreach($cases as $i=>[$no,$reason,$received,$qty,$amount]){
$this->ship($no,'测试固定');$this->workOrder($no,'测试固定','','',null,'2026-11-03',$reason,'WAIT_CONFIRM',$i+1);
@ -402,6 +409,59 @@ class BillSurchargeMatchingTest extends FeatureTestCase
$this->assertStringContainsString('退回进仓',$missing['notes']['FIXRET001']['拦截费']);
}
public function test_return_matching_uses_latest_regular_and_taobao_parcels_and_keeps_buyer_checks(): void
{
$this->quote('测试退回','拦截费','固定单价','30元/单','查件扣单并且买家原因已退回的');
$db=DB::connection('business_mirror');$schema=Schema::connection('business_mirror');
// The recent parcel mirror must work even when the old ordinary after-sales mirror is absent.
$schema->dropIfExists('courier_returned_parcels');
$schema->create('courier_returned_parcels',function(Blueprint $t){
$t->integer('source_id');$t->string('source_kind');$t->string('order_id')->index();
$t->string('waybill')->nullable();$t->dateTime('received_at')->nullable();$t->integer('returned_qty');
});
$cases=[['NEWREG01','regular','2026-12-04',1,'扣单/买家-不想要',30],
['NEWTAO01','taobao','2026-12-05',1,'扣单/买家-不想要',30],
['NEWZERO1','regular','2026-12-05',0,'扣单/买家-不想要',null],
['NEWNULL1','regular',null,1,'扣单/买家-不想要',null],
['NEWDAMAGE','taobao','2026-12-05',1,'扣单/快递-破损',0]];
$input=[];
foreach($cases as $i=>[$no,$kind,$date,$qty,$reason,$amount]){
$this->ship($no,'测试退回');$this->workOrder($no,'测试退回','','',null,'2026-11-03',$reason,'WAIT_CONFIRM',$i+1);
$db->table('courier_returned_parcels')->insert(['source_id'=>$i+1,'source_kind'=>$kind,'order_id'=>(string)($i+1),
'waybill'=>'RETURN-'.$no,'received_at'=>$date,'returned_qty'=>$qty]);
$input[]=['waybill_no'=>$no,'item'=>'拦截费'];
}
$db->table('courier_returned_parcels')->insert(['source_id'=>100,'source_kind'=>'taobao','order_id'=>'1',
'waybill'=>'RETURN-NEWREG01','received_at'=>'2026-12-06','returned_qty'=>2]);
$result=app(\App\Support\CourierBills\BillSurchargeQuoteCalculator::class)->calculate($input,'dropship','2026-11',['测试退回']);
foreach($cases as [$no,$kind,$date,$qty,$reason,$amount]){
if($amount===null)$this->assertSame([],$result['rows'][$no]['拦截费']);
else {$this->assertCount(1,$result['rows'][$no]['拦截费']);$this->assertEquals($amount,$result['rows'][$no]['拦截费'][0]->settlement_amount);}
}
$this->assertStringContainsString('退回单号 RETURN-NEWTAO01',$result['rows']['NEWTAO01']['拦截费'][0]->evidence);
}
public function test_return_waybill_exact_match_precedes_fuzzy_and_does_not_need_order_id(): void
{
$this->quote('测试退回','拦截费','固定单价','30元/单','查件扣单并且买家原因已退回的');
$db=DB::connection('business_mirror');$schema=Schema::connection('business_mirror');
$schema->dropIfExists('courier_returned_parcels');
$schema->create('courier_returned_parcels',function(Blueprint $t){
$t->integer('source_id');$t->string('order_id')->nullable();$t->string('waybill');$t->dateTime('received_at');$t->integer('returned_qty');
});
foreach(['123456789012','223456789012','323456789012'] as $no){
$this->ship($no,'测试退回');$this->workOrder($no,'测试退回','','',null,'2026-11-03','扣单/买家-不想要');
}
foreach(['123456789012','T123456789012',"'T223456789012",'3323456789012'] as $i=>$no){
$db->table('courier_returned_parcels')->insert(['source_id'=>$i+1,'waybill'=>$no,'received_at'=>'2026-12-06','returned_qty'=>1]);
}
$input=array_map(fn($no)=>['waybill_no'=>$no,'item'=>'拦截费'],['123456789012','223456789012','323456789012']);
$r=app(\App\Support\CourierBills\BillSurchargeQuoteCalculator::class)->calculate($input,'dropship','2026-11',['测试退回']);
$this->assertStringContainsString('(精确匹配)',$r['rows']['123456789012']['拦截费'][0]->evidence);
$this->assertStringContainsString('模糊匹配',$r['rows']['223456789012']['拦截费'][0]->evidence);
$this->assertSame([],$r['rows']['323456789012']['拦截费']);
}
public function test_fixed_customer_approval_uses_quote_price_and_enforces_type_courier_status(): void
{
$this->quote('测试固定','改地址','固定单价','30元/单','改地址客服回复通过');

View File

@ -10,6 +10,25 @@ use Tests\Feature\FeatureTestCase;
final class CourierRebookReturnReviewTest extends FeatureTestCase
{
public function test_return_cursor_does_not_skip_taobao_row_sharing_a_batch_boundary_id(): void
{
$schema=Schema::connection('business_mirror');$schema->dropIfExists('courier_returned_parcels');
$schema->create('courier_returned_parcels',function($table):void{
$table->string('source_kind');$table->integer('source_id');$table->primary(['source_kind','source_id']);
$table->string('waybill');$table->dateTime('received_at');$table->integer('returned_qty');
});
$rows=[];
for($id=1;$id<=1000;$id++)$rows[]=['source_kind'=>'regular','source_id'=>$id,'waybill'=>'UNRELATED'.$id,'received_at'=>'2026-11-01','returned_qty'=>1];
foreach(array_chunk($rows,200) as $chunk)Rebooks::db()->table('courier_returned_parcels')->insert($chunk);
Rebooks::db()->table('courier_returned_parcels')->insert(['source_kind'=>'taobao','source_id'=>1000,
'waybill'=>'RETURN-BOUNDARY','received_at'=>'2026-12-06','returned_qty'=>1]);
$result=app(\App\Support\CourierBills\RebookReturns::class)->annotate([
['tracking_no'=>'RETURN-BOUNDARY','analysis'=>'未退回','bookkeeping_reason'=>'买家原因'],
]);
$this->assertSame('已退回',$result[0]['_return_status']);
$this->assertSame(0.0,$result[0]['_return_current']);
}
public function test_four_carrier_names_returns_fuzzy_match_and_prior_refund_are_accounted_once(): void
{
$db = Rebooks::db();
@ -80,6 +99,10 @@ final class CourierRebookReturnReviewTest extends FeatureTestCase
$this->assertEquals(185, $db->table('courier_bill_summary_items')->where('statement_id', $id)->value('self_amount'));
$this->assertEquals(185, $db->table('courier_bill_rebooks')->where('statement_id', $id)->sum('amount'));
$this->assertCount(2, app(Rebooks::class)->forStatement($id)['rows']);
$db->table('courier_returned_parcels')->delete();
$this->artisan('courier-surcharge:match-bills',['--all'=>true,'--existing-only'=>true,'--all-months'=>true,'--refresh-rebooks'=>true])->assertSuccessful();
$this->assertEquals(185,$db->table('courier_bill_summary_items')->where('statement_id',$id)->value('self_amount'));
$this->assertEquals(185,$db->table('courier_bill_rebooks')->where('statement_id',$id)->sum('amount'));
}
public function test_automatic_refund_preserves_per_product_costs_and_holds_missing_costs(): void

View File

@ -197,7 +197,7 @@ class ReturnedParcelsTest extends FeatureTestCase
{
foreach (['activate-release.sh','activate-incremental-release.sh'] as $file) {
$text=file_get_contents(base_path('deploy/'.$file));
$this->assertStringContainsString('0 10,16 * * * root /bin/sh /opt/caiwuxitong/run-finance-batch.sh business-mirror:sync-returned-parcels', $text);
$this->assertStringContainsString('0 10,16 * * * root /bin/sh /opt/caiwuxitong/run-finance-batch.sh business-mirror:sync-returned-parcels --match-surcharges', $text);
}
$this->assertStringContainsString('/usr/bin/timeout 1800', file_get_contents(base_path('deploy/run-finance-batch.sh')));
}
@ -233,6 +233,13 @@ class ReturnedParcelsTest extends FeatureTestCase
$this->artisan('business-mirror:sync-returned-parcels', ['--from'=>'2026-02-30','--to'=>'2026-12-02'])->assertFailed();
$this->artisan('business-mirror:sync-returned-parcels', ['--from'=>'2026-11-01','--to'=>'2026-10-01'])->assertFailed();
}
public function test_successful_sync_can_refresh_existing_bills_in_the_same_batch(): void
{
$this->app->instance(ReturnedParcelSynchronizer::class,$this->synchronizer([$this->item(1)]));
$this->artisan('business-mirror:sync-returned-parcels',['--from'=>'2026-10-01','--to'=>'2026-12-02','--match-surcharges'=>true])->assertSuccessful();
$this->assertSame(1,DB::connection('business_mirror')->table(ReturnedParcelSynchronizer::TABLE)->count());
}
}
class ReturnedParcelFakeSynchronizer extends ReturnedParcelSynchronizer

View File

@ -11,6 +11,21 @@ use Tests\Feature\FeatureTestCase;
final class UnshippedWaybillsTest extends FeatureTestCase
{
public function test_exact_unshipped_match_precedes_format_and_t_prefix_fallback(): void
{
$service=app(UnshippedWaybills::class);
foreach ([['123456789012','warehouse'],['T123456789012','replacement'],["'T223456789012",'replacement'],
[' @DPK777 ','warehouse'],['123456789013','warehouse'],['T123456789013','replacement']] as $i=>[$number,$source]) {
$service->results()->insert(['waybill_no'=>$number,'source'=>$source,'evidence_no'=>'fuzzy-'.$i,'evidence_time'=>'2026-12-01']);
}
$result=$service->unshippedSources(['123456789012','223456789012','DPK777',' @123456789013.0 ','123456789014']);
$this->assertSame(['仓内未发'],$result['123456789012']);
$this->assertSame(['换单未发出'],$result['223456789012']);
$this->assertSame(['仓内未发'],$result['DPK777']);
$this->assertArrayNotHasKey('123456789013.0',$result);
$this->assertArrayNotHasKey('123456789014',$result);
}
public function test_remark_parser_and_daily_production_cron(): void
{
$this->assertSame([