feat(附加费对账): 按账单匹配结算金额与商品信息

This commit is contained in:
limeng 2026-12-04 12:26:25 +08:00
parent ebcec21bd1
commit aa51030b86
26 changed files with 670 additions and 16 deletions

View File

@ -0,0 +1,50 @@
<?php
namespace App\Console\Commands;
use App\Support\CourierBills\CourierBillMatcher;
use App\Support\CourierBills\SurchargeSettlementMatcher;
use App\Support\DropshipFreight\DropshipConfirmation;
use App\Support\DropshipFreight\DropshipFreightStore;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Throwable;
class MatchBillSurcharges extends Command
{
protected $signature='courier-surcharge:match-bills {--month= : 账单月份 YYYY-MM,默认上月} {--statement=* : 指定快递对账单} {--factory=* : 指定代发厂家} {--all : 匹配该月全部未确认账单} {--existing-only : 只更新已建立附加费匹配的账单} {--company=1}';
protected $description='匹配指定月份账单的附加费金额及商品信息,已确认账单不变';
public function handle(SurchargeSettlementMatcher $matcher): int
{
$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;}
try{
$db=DB::connection('business_mirror');$statements=[];$factories=[];
if($this->option('all')||$this->option('statement')!==[]){
$statements=$db->table('courier_bill_statements')->where('bill_month',$month)->where('status','<>','confirmed')
->when($this->option('existing-only'),fn($q)=>$q->whereIn('id',$db->table(SurchargeSettlementMatcher::TABLE)->where('scope','courier')->where('bill_month',$month)->select('owner_id')))
->when(!$this->option('all'),fn($q)=>$q->whereIn('id',array_map('intval',$this->option('statement'))))->orderBy('id')->pluck('id')->all();
foreach($statements as $id){app(CourierBillMatcher::class)->refreshSurchargeSummary((int)$id);$this->line('快递对账单 #'.$id.' 附加费已匹配');}
}
if($this->option('all')||$this->option('factory')!==[]){
$store=app(DropshipFreightStore::class);
$factories=$db->table('dropship_bill_files')->where('bill_month',$month)->where('status','parsed')->whereNotNull('factory_id')
->when($this->option('existing-only'),fn($q)=>$q->whereIn('factory_id',$db->table('dropship_bill_surcharges')->where('bill_month',$month)->select('factory_id')))
->when(!$this->option('all'),fn($q)=>$q->whereIn('factory_id',array_map('intval',$this->option('factory'))))->distinct()->pluck('factory_id')->all();
foreach($factories as $id){
$state=app(DropshipConfirmation::class)->state($month,(int)$id,(int)$this->option('company'));
if(($state['status']??'')==='confirmed'){$this->line('厂家 #'.$id.' 已确认,跳过');continue;}
$db->transaction(function()use($db,$store,$id,$month){foreach($db->table('dropship_bill_files')->where('factory_id',$id)->where('bill_month',$month)->where('status','parsed')->get() as $file)$store->storeSurchargeRows($file,(int)$id);});
$matcher->dropship((int)$id,$month);$this->line('代发厂家 #'.$id.' 附加费已匹配');
}
}
$this->info('附加费匹配完成:'.$month.';快递对账单 '.count($statements).' 张,代发厂家 '.count($factories).' 家。');return self::SUCCESS;
}catch(Throwable $e){report($e);$this->error('附加费匹配失败:'.$e->getMessage());return self::FAILURE;}
finally{$lock->release();}
}
}

View File

@ -121,6 +121,7 @@ final class CourierBillController extends Controller
'calc_freight', 'charge_weight', 'self_amount', 'resolution', 'resolved_by', 'unshipped_sources', 'category', 'category_month'], 'page')->withQueryString();
}
$items = $db->table('courier_bill_summary_items')->where('statement_id', $statement->id)->orderBy('sort')->get();
$items=app(\App\Support\CourierBills\SurchargeSettlementMatcher::class)->summaryItems((int)$statement->id,$items);
$fileIds = $db->table('courier_bill_lines')->where('statement_id', $statement->id)->distinct()->pluck('file_id');
$files = $db->table('courier_bill_files')->where(fn ($q) => $q->where('statement_id', $statement->id)->orWhereIn('id', $fileIds))->orderBy('id')->get();
$shippingSync = null;
@ -136,7 +137,9 @@ final class CourierBillController extends Controller
return ['cbRelated' => collect($related)->map(fn ($id) => ['id' => $id, 'name' => $relatedNames[$id] ?? ''])->all(),
'cbStatement' => $statement, 'cbGroup' => $group, 'cbTabs' => $tabs, 'cbTab' => $tab, 'cbLines' => $lines,
'cbItems' => $items, 'cbFiles' => $files, 'cbShippingSync' => $shippingSync,
'cbFeeLabels' => $this->matcher->feeLabels((int) $statement->id), 'cbRebook' => $this->rebookSummary((int) $statement->id)];
'cbFeeLabels' => $this->matcher->feeLabels((int) $statement->id), 'cbRebook' => $this->rebookSummary((int) $statement->id),
'cbSurchargeRows' => app(\App\Support\CourierBills\SurchargeSettlementMatcher::class)->ready()
? app(\App\Support\CourierBills\SurchargeSettlementMatcher::class)->query('courier',(int)$statement->id)->orderBy('id')->paginate(50,['*'],'fee_page')->withQueryString() : null];
}
/** 单家对账单上的补记账说明:补几个月、本期补几单多少、还有几单待复核。 @return array<string,mixed>|null */

View File

@ -108,7 +108,12 @@ final class DropshipFreightController extends Controller
return ['dfFactory' => $factory, 'dfSummary' => $result['summary'], 'dfLines' => $paginator, 'dfStatus' => $status, 'dfFiles' => $files,
'dfState' => $this->confirmations->state($month, (int) $factory->id, self::companyId()),
'dfDisputes' => $this->confirmations->disputes($month, (int) $factory->id, self::companyId()),
'dfRobot' => app(SupplierDingTalkNotifier::class)->configuration((string) $factory->name)];
'dfRobot' => app(SupplierDingTalkNotifier::class)->configuration((string) $factory->name),
'dfSurchargeRows' => app(\App\Support\CourierBills\SurchargeSettlementMatcher::class)->ready()
? app(\App\Support\CourierBills\SurchargeSettlementMatcher::class)->query('dropship',(int)$factory->id,$month)->orderBy('id')->paginate(50,['*'],'fee_page')->withQueryString() : null,
'dfSurchargeSummary' => app(\App\Support\CourierBills\SurchargeSettlementMatcher::class)->ready()
? app(\App\Support\CourierBills\SurchargeSettlementMatcher::class)->query('dropship',(int)$factory->id,$month)
->selectRaw('item,SUM(bill_amount) AS bill,SUM(self_amount) AS self')->groupBy('item')->get() : collect()];
}
private function uploadData(string $month): array

View File

@ -169,7 +169,7 @@ final class BillParser
}
$amount = preg_replace('/\s+/u', '', (string) ($row[$found['amount']] ?? '')) ?? '';
if (self::containsAny($named, self::SURCHARGE_SHEET_WORDS) || self::containsAny($amount, self::SURCHARGE_AMOUNT_WORDS)) {
$skip[$sheet] = ['附加费表:只读金额进小汇总,没有逐单核对', (int) $rowNumber, $found['waybill'], $found['amount'], $found['item'], $amount];
$skip[$sheet] = ['附加费表:按单号和费用类型匹配结算', (int) $rowNumber, $found['waybill'], $found['amount'], $found['item'], $amount];
} elseif (str_contains($amount, '运费') || $found['item'] !== null || trim((string) ($overrides['amount_header'] ?? '')) !== '') {
$freight[] = $sheet;
} else {

View File

@ -254,14 +254,17 @@ final class CourierBillMatcher
$manualLabels = $db->table('courier_bill_summary_items')->where('statement_id', $statementId)->where('manual', true)->pluck('label')
->map(static fn ($label): string => preg_replace('/\s+/u', '', (string) $label) ?? '')->flip();
$kinds['配件补发扣款'] = 'accessory';
$surchargeMatcher=app(SurchargeSettlementMatcher::class);
$surchargeMatcher->courier($statementId);
$matchedFees=$surchargeMatcher->ready()?$surchargeMatcher->query('courier',$statementId)
->selectRaw('summary_label, SUM(self_amount) AS amount')->groupBy('summary_label')->pluck('amount','summary_label')->all():[];
$fees = $this->surchargeItems($statementId);
$template = $this->templateFor($statementId);
$this->addRebooks($statementId, $template, $manualLabels, $items, $kinds);
$sort = 8000;
foreach ($fees as $item => $sum) {
if (($template !== null || ! isset($manualLabels[$item])) && ! isset($items[$item])) {
// 附加费不逐单核对:自算先放 0,手工核对后在小汇总里回填
$items[$item] = ['bill' => $sum, 'self' => 0.0, 'sort' => $sort++];
$items[$item] = ['bill' => $sum, 'self' => isset($matchedFees[$item]) ? (float)$matchedFees[$item] : 0.0, 'sort' => $sort++];
$kinds[$item] = 'fee';
}
}
@ -303,6 +306,34 @@ final class CourierBillMatcher
'line_count' => (int) $totals->line_count, 'bill_amount' => round((float) $totals->bill, 2), 'updated_at' => now(),
]);
}
/** 历史账单补接附加费时只更新费用行,保留原运费与手工小汇总。 */
public function refreshSurchargeSummary(int $statementId): void
{
$db=self::db();
$db->transaction(function()use($db,$statementId):void{
$statement=$db->table('courier_bill_statements')->where('id',$statementId)->lockForUpdate()->first();
if(!$statement||$statement->status==='confirmed')return;
$matcher=app(SurchargeSettlementMatcher::class);$matcher->courier($statementId);
if(!$matcher->ready())return;
$sums=$matcher->query('courier',$statementId)->selectRaw('summary_label,SUM(bill_amount) AS bill,SUM(self_amount) AS self')
->groupBy('summary_label')->get();
$auto=[];foreach($sums as $sum)$auto[$sum->summary_label]=['bill'=>(float)$sum->bill,'self'=>(float)$sum->self,'kind'=>'fee'];
$template=$this->templateFor($statementId);
$rows=$template===null?array_map(fn($label,$v)=>['label'=>$label]+$v,array_keys($auto),array_values($auto))
:array_values(array_filter(SummaryTemplate::apply($template,$auto,(int)substr($statement->bill_month,5,2)),fn($r)=>$r['fee']));
foreach($rows as $row){
$existing=$db->table('courier_bill_summary_items')->where('statement_id',$statementId)->where('label',$row['label'])->orderBy('id')->first();
if($existing){
if(!$existing->manual)$db->table('courier_bill_summary_items')->where('id',$existing->id)->update(['self_amount'=>round((float)$row['self'],2)]);
}else{
$sort=(int)$db->table('courier_bill_summary_items')->where('statement_id',$statementId)->max('sort')+1;
$db->table('courier_bill_summary_items')->insert(['statement_id'=>$statementId,'label'=>$row['label'],
'bill_amount'=>$row['bill'],'self_amount'=>round((float)$row['self'],2),'manual'=>false,'sort'=>$sort]);
}
}
});
}
/**
* 「配件补发扣款」页里本月首发快递属于这个分组的可扣款金额,作为一行自动小汇总(快递金额空、自算为负)。
* 已经手工加了配件补发扣款类的行时不再自动加,免得扣两次。
@ -411,7 +442,7 @@ final class CourierBillMatcher
/**
* 这张对账单分到的附加费:一张附加费表一行,名字就用快递账单里的表名(如「山东中通快运加收&上楼费」),方便和账单对应;
* 运费表里用「费用项目」分出来的附加费行,没有单独的表名,按费用项目合计。快递开的金额,自算先放 0,不逐单核对。
* 运费表里用「费用项目」分出来的附加费行,没有单独的表名,按费用项目合计;自算另取逐票匹配结果。
* 合并账单里的附加费按单号的快递名称1 归到对应分组;查不到的归文件所属的那张对账单。
*
* @return array<string,float>

View File

@ -423,6 +423,7 @@ final class CourierBillStore
$db->transaction(function () use ($db, $file): void {
$db->table('courier_bill_lines')->where('file_id', $file->id)->delete();
$db->table('courier_bill_surcharges')->where('file_id', $file->id)->delete();
if(app(SurchargeSettlementMatcher::class)->ready())$db->table(SurchargeSettlementMatcher::TABLE)->where('scope','courier')->where('file_id',$file->id)->delete();
$db->table('courier_bill_files')->where('id', $file->id)->delete();
});
Storage::disk(self::DISK)->delete($file->stored_path);
@ -628,7 +629,7 @@ final class CourierBillStore
$notes[] = '没有找到含单号和运费列的工作表';
}
if ($feeCount > 0) {
$notes[] = '附加费只读了金额进小汇总,没有逐单核对:' . $feeCount . ' 行,合计 ' . number_format($feeTotal, 2);
$notes[] = '附加费已按单号和费用类型匹配结算表:' . $feeCount . ' 行,对方合计 ' . number_format($feeTotal, 2);
}
$unread = [];
foreach ($sheets as $sheet) {

View File

@ -112,6 +112,27 @@ final class FreightBillTemplate
return $result;
}
/** 逐行保留单号与类型,不能只汇总账单金额后丢失匹配依据。 */
public function surchargeRows(string $path,string $extension): \Generator
{
foreach($this->reader->sheets($path,$extension) as $name=>$rows){
if(!str_contains(trim((string)$name),self::SURCHARGE_SHEET))continue;
$header=false;
foreach($rows as $number=>$row){
$cells=array_slice(array_map(static fn($v):string=>trim((string)$v),$row),0,3);
if(implode('',$cells)==='')continue;
if(!$header){
if(array_values(self::trimTail($cells))!==self::SURCHARGE_HEADERS)throw new RuntimeException('附加费表头不符合模板,无法逐单核对。');
$header=true;continue;
}
if(in_array($cells[0]??'',self::TOTAL_WORDS,true))continue;
$waybill=Waybill::normalize($cells[0]??'');$amount=BillParser::number($cells[1]??null);$type=$cells[2]??'';
if($waybill===null||$amount===null||$type==='')throw new RuntimeException('附加费第 '.$number.' 行缺少完整单号、金额或类型。');
yield ['sheet'=>(string)$name,'row_no'=>(int)$number,'waybill_no'=>$waybill,'item'=>$type,'amount'=>$amount];
}
}
}
/** @return array{rows:int,waybills:int,amount:float} */
private function validateBill(?iterable $rows): array
{

View File

@ -91,7 +91,7 @@ final class StatementExporter
$book->row('汇总', [$group->name . ' ' . $statement->bill_month, '快递提供金额', '自算金额', '差异'], true);
$bill = 0.0;
$self = 0.0;
foreach ($db->table('courier_bill_summary_items')->where('statement_id', $id)->orderBy('sort')->get() as $item) {
foreach (app(SurchargeSettlementMatcher::class)->summaryItems($id,$db->table('courier_bill_summary_items')->where('statement_id', $id)->orderBy('sort')->get()) as $item) {
$b = $item->bill_amount === null ? null : (float) $item->bill_amount;
$s = $item->self_amount === null ? null : (float) $item->self_amount;
$book->row('汇总', [$item->label, $b, $s, round((float) $b - (float) $s, 2)]);
@ -176,6 +176,7 @@ final class StatementExporter
});
$this->writeRebooks($book, $ids, $tail, $groupNames, $multi);
foreach($ids as $id) app(SurchargeSettlementMatcher::class)->write($book,'courier',$id);
$this->writeNotes($book, $ids, $originals);
$book->writeTo($output);
}

View File

@ -0,0 +1,214 @@
<?php
namespace App\Support\CourierBills;
use App\Support\DropshipFreight\DropshipFreightStore;
use Illuminate\Support\Facades\DB;
use RuntimeException;
/** 按账单月份归集,逐票/费用类型匹配结算表;不改来源报价和费用。 */
class SurchargeSettlementMatcher
{
public const TABLE = 'bill_surcharge_matches';
public const HEADERS = ['账单月份','来源工作表','原始行号','快递单号','附加费类型','对方金额','自算金额','差额','匹配状态','快递名称','平台商品ID','商品编码','店铺名称','线上订单号','说明'];
public function ready(): bool
{
return DB::connection('business_mirror')->getSchemaBuilder()->hasTable(self::TABLE);
}
public static function type(string $type): string
{
$type = preg_replace('/\s+/u', '', $type) ?? '';
return match ($type) {
'改地址费','改址费','改址' => '改地址',
'上楼','直客上楼费' => '上楼费', '超长' => '超长费',
'退件费','退货费','退回运费' => '退回费', '拦截' => '拦截费',
'派送费','派件费','直客派送费' => '送货费', '保价费' => '保费',
'入仓费' => '进仓费', '直客超区费' => '超区费', default => $type,
};
}
/** 不刷新已确认账单;只更新附加费派生匹配记录。 */
public function courier(int $id): void
{
if (! $this->ready()) return;
$db = DB::connection('business_mirror');
$s = $db->table('courier_bill_statements')->find($id);
if (! $s || $s->status === 'confirmed') return;
$group = $db->table('courier_bill_groups')->find($s->group_id);
$names = (array) json_decode($group->express_names, true);
$files = $db->table('courier_bill_lines')->where('statement_id', $id)->distinct()->pluck('file_id')
->merge($db->table('courier_bill_files')->where('statement_id', $id)->pluck('id'))->unique()->all();
$seen = [];
$db->transaction(function () use ($db, $s, $id, $names, $files, &$seen): void {
if($db->table('courier_bill_statements')->where('id',$id)->lockForUpdate()->value('status')==='confirmed')return;
$db->table(self::TABLE)->where('scope','courier')->where('owner_id',$id)->delete();
foreach ($files as $fileId) {
$file = $db->table('courier_bill_files')->find($fileId);
if (! $file || $file->status !== 'parsed') continue;
$shared = $db->table('courier_bill_lines')->where('file_id',$fileId)->distinct()->pluck('statement_id')
->push($file->statement_id)->filter()->unique()->values()->all();
$ownership = [];
if (count($shared)>1) {
foreach ($db->table('courier_bill_statements as s')->join('courier_bill_groups as g','g.id','=','s.group_id')
->whereIn('s.id',$shared)->orderBy('s.id')->get(['s.id','g.express_names']) as $owner) {
foreach ((array) json_decode($owner->express_names,true) as $name) $ownership[trim($name)] ??= (int)$owner->id;
}
}
$joint = isset(json_decode($file->extra_group_ids ?? '[]',true)['joint_upload']);
$freightSheets=$db->table('courier_bill_lines')->where('file_id',$fileId)->distinct()->pluck('sheet')->flip()->all();
$db->table('courier_bill_surcharges')->where('file_id',$fileId)->orderBy('id')->chunkById(300,
function ($fees) use ($db,$s,$id,$names,$file,$joint,$ownership,$freightSheets,&$seen): void {
$ships=$ownership!==[]&&!$joint?$this->ships($fees->pluck('waybill_no')->all()):[];
$assigned=$joint?$db->table('courier_bill_lines')->where('file_id',$file->id)->whereIn('waybill_no',$fees->pluck('waybill_no'))
->pluck('statement_id','waybill_no')->all():[];
$input=[];
foreach($fees as $f){
$ship=$ships[strtoupper($f->waybill_no)]??[];
$owner=$joint?($assigned[$f->waybill_no]??0):($ownership[$ship['express']??'']??$file->statement_id);
if((int)$owner!==$id)continue;
$label=isset($freightSheets[$f->sheet])||trim($f->sheet)===''?$f->item:$f->sheet;
$input[]=['file_id'=>$f->file_id,'sheet'=>$f->sheet,'row_no'=>$f->row_no,'waybill_no'=>$f->waybill_no,
'item'=>$f->item,'amount'=>$f->amount,'label'=>preg_replace('/\s+/u','',$label)];
}
$this->storeMatches('courier',$id,$s->bill_month,$input,$names,null,$seen);
});
}
});
}
/** 页面只叠加附加费自算值;已确认对账单继续读取确认时保存的金额。 */
public function summaryItems(int $id,iterable $items): \Illuminate\Support\Collection
{
$items=collect($items);$db=DB::connection('business_mirror');
if(!$this->ready()||$db->table('courier_bill_statements')->where('id',$id)->value('status')==='confirmed')return $items;
$sums=$this->query('courier',$id)->selectRaw('summary_label,SUM(self_amount) AS amount')->groupBy('summary_label')->pluck('amount','summary_label')->all();
if($sums===[])return $items;
$month=(int)substr((string)$db->table('courier_bill_statements')->where('id',$id)->value('bill_month'),5,2);
$labels=$items->pluck('label')->all();$auto=[];
foreach($sums as $label=>$amount)$auto[$label]=['bill'=>null,'self'=>$amount===null?null:(float)$amount,'kind'=>'fee'];
$mapped=SummaryTemplate::apply($labels,$auto,$month);$byLabel=[];
foreach($mapped as $row)if($row['fee'])$byLabel[$row['label']]=$row['self'];
return $items->map(function($item)use($byLabel){
$copy=clone $item;if(!$copy->manual&&array_key_exists($copy->label,$byLabel))$copy->self_amount=$byLabel[$copy->label];return $copy;
});
}
public function dropship(int $factoryId, string $month): void
{
if (! $this->ready()) return;
$db=DB::connection('business_mirror');$factory=$db->table('dropship_factories')->find($factoryId);
if(!$factory)throw new RuntimeException('厂家不存在');
$state=app(\App\Support\DropshipFreight\DropshipConfirmation::class)->state($month,$factoryId,(int)(company_id()?:1));
if(($state['status']??'')==='confirmed')return;
$seen=[];
$db->transaction(function () use($db,$factory,$factoryId,$month,&$seen): void {
$db->table(self::TABLE)->where('scope','dropship')->where('owner_id',$factoryId)->where('bill_month',$month)->delete();
$db->table('dropship_bill_surcharges as f')->join('dropship_bill_files as b','b.id','=','f.file_id')->where('b.status','parsed')
->where('f.factory_id',$factoryId)->where('f.bill_month',$month)->select('f.*')->orderBy('f.id')
->chunkById(300,function($fees)use($factory,$factoryId,$month,&$seen):void{
$input=array_map(fn($f)=>['file_id'=>$f->file_id,'sheet'=>$f->sheet,'row_no'=>$f->row_no,'waybill_no'=>$f->waybill_no,
'item'=>$f->item,'amount'=>$f->amount,'label'=>$f->item],$fees->all());
$this->storeMatches('dropship',$factoryId,$month,$input,[],$factory,$seen);
},'f.id','id');
});
}
private function ships(array $waybills): array
{
$db=DB::connection(config('jushuitan.connection','business_mirror'));
if(!$db->getSchemaBuilder()->hasTable('jst_oms_shipping'))return [];
$result=[];
foreach($db->table('jst_oms_shipping')->whereIn('express_no',array_unique($waybills))->orderBy('id')
->get(['express_no','express_name1','warehouse_name']) as $r){
$key=strtoupper($r->express_no);
$result[$key]['express']=$r->express_name1;
$result[$key]['pairs'][$r->warehouse_name][$r->express_name1]=true;
}
return $result;
}
private function storeMatches(string $scope,int $owner,string $month,array $input,array $names,?object $factory,array &$seen): void
{
if($input===[])return;
$db=DB::connection('business_mirror');$waybills=array_values(array_unique(array_column($input,'waybill_no')));
$source=[];
if($db->getSchemaBuilder()->hasTable('courier_surcharge_settlement_rows')){
$sourceQuery=$db->table('courier_surcharge_settlement_rows')->whereIn('waybill',$waybills)->where('settlement_status','已计算');
$end=date('Y-m-d',strtotime($month.'-01 +1 month'));
if($db->getSchemaBuilder()->hasColumn('courier_surcharge_settlement_rows','source_created_at')){
$sourceQuery->where(fn($q)=>$q->whereRaw('COALESCE(source_created_at,shipped_at) < ?',[$end])->orWhere(fn($q)=>$q->whereNull('source_created_at')->whereNull('shipped_at')));
}else{$sourceQuery->where(fn($q)=>$q->whereNull('shipped_at')->orWhere('shipped_at','<',$end));}
foreach($sourceQuery
->orderBy('id')->get() as $r)$source[strtoupper($r->waybill)][self::type($r->surcharge_type)][]=$r;
}
$prior=[];
foreach($db->table(self::TABLE)->whereIn('waybill_no',$waybills)
->where(fn($q)=>$q->where('scope','<>',$scope)->orWhere('owner_id','<>',$owner)->orWhere('bill_month','<>',$month))
->where('match_status','已匹配')->get(['settlement_ids','bill_month']) as $r)
foreach(json_decode($r->settlement_ids??'[]',true)?:[] as $sid)$prior[$sid]=$r->bill_month;
$ships=$factory?$this->ships($waybills):[];
$own=$factory?array_fill_keys(app(DropshipFreightStore::class)->ownExpressNames(),true):[];
$output=[];
foreach($input as $f){
$type=self::type($f['item']);$wb=strtoupper($f['waybill_no']);$rows=$source[$wb][$type]??[];
$row=['scope'=>$scope,'owner_id'=>$owner,'file_id'=>$f['file_id'],'sheet'=>$f['sheet'],'row_no'=>$f['row_no'],
'bill_month'=>$month,'waybill_no'=>$wb,'item'=>$type,'summary_label'=>$f['label'],'bill_amount'=>$f['amount'],'self_amount'=>null,
'courier_name'=>null,'platform_product_id'=>null,'product_code'=>null,'shop_name'=>null,'online_order_no'=>null,
'match_status'=>'未匹配','match_note'=>'结算表没有对应的单号及费用类型','settlement_ids'=>null,'matched_at'=>now()];
$allowed=$names;
if($factory){
$ship=$ships[$wb]??[];
$keywords=DropshipFreightStore::splitKeywords($factory->keywords);
$allowed=array_values(array_filter(array_keys($ship['pairs'][$factory->warehouse]??[]),fn($express)=>
!isset($own[$express])&&array_filter($keywords,fn($k)=>str_contains($express,$k))!==[]));
$belongs=$allowed!==[];
if(!$belongs)$row['match_note']='无法确认该单属于本厂家代发快递及仓库';
}
$rows=array_values(array_filter($rows,fn($r)=>in_array($r->courier_name,$allowed,true)));
$identity=$wb.'|'.$type;
if(isset($seen[$identity])){$row['self_amount']=0;$row['match_status']='重复';$row['match_note']='本月账单已提供该单号及费用类型,不重复结算';}
elseif($rows!==[]){
$unique=[];
foreach($rows as $r){
$identityKey=($r->source_key??'')!==''?'source:'.$r->source_key:'rule:'.$r->rule_id.'|'.($r->outbound_io_id??'');
$unique[$r->courier_name.'|'.($r->source_kind??'').'|'.$identityKey]=$r;
}
$rows=array_values($unique);
$keyOf=fn($r)=>hash('sha256',implode('|',[$r->courier_name,$wb,$type,
$r->source_kind??'', trim((string)($r->source_key??''))!==''?'source:'.$r->source_key:'rule:'.$r->rule_id.'|'.($r->outbound_io_id??'')]));
$notPaid=array_values(array_filter($rows,fn($r)=>!isset($prior[$keyOf($r)])));
if($notPaid===[]){$row['self_amount']=0;$row['match_status']='历史已计入';$row['match_note']='对应费用已计入其他账单,不能重复结算';$seen[$identity]=true;}
else {
$partlyPaid=count($notPaid)!==count($rows);$rows=$notPaid;
$seen[$identity]=true;$row['self_amount']=round(array_sum(array_map(fn($r)=>(float)$r->settlement_amount,$rows)),2);
$row['match_status']='已匹配';$row['settlement_ids']=json_encode(array_map($keyOf,$rows));
$row['match_note']='按单号、费用类型及快递匹配;归入'.$month.'账单'.($partlyPaid?';已扣除其他账单已计入费用':'');
foreach(['courier_name','platform_product_id','product_code','shop_name','online_order_no'] as $key)
$row[$key]=implode('、',array_values(array_unique(array_filter(array_map(fn($r)=>trim((string)($r->$key??'')),$rows)))));
}
} elseif($rows===[] && ($source[$wb]??[])!==[]) $row['match_note']='单号存在,但费用类型或快递归属不符';
$output[]=$row;
}
$db->table(self::TABLE)->insert($output);
}
public function query(string $scope,int $owner,?string $month=null)
{
return DB::connection('business_mirror')->table(self::TABLE)->where('scope',$scope)->where('owner_id',$owner)
->when($month,fn($q)=>$q->where('bill_month',$month));
}
public function write(StreamingWorkbook $book,string $scope,int $owner,?string $month=null): void
{
if(!$this->ready()||!$this->query($scope,$owner,$month)->exists())return;
$sheet='附加费核对'.($scope==='courier'?'-'.$owner:'');$book->row($sheet,self::HEADERS,true);
$this->query($scope,$owner,$month)->orderBy('id')->chunkById(300,function($rows)use($book,$sheet){
foreach($rows as $r)$book->row($sheet,[$r->bill_month,$r->sheet,$r->row_no,$r->waybill_no,$r->item,
$r->bill_amount===null?null:(float)$r->bill_amount,$r->self_amount===null?null:(float)$r->self_amount,
$r->self_amount===null?null:round((float)$r->bill_amount-$r->self_amount,2),$r->match_status,$r->courier_name,
$r->platform_product_id,$r->product_code,$r->shop_name,$r->online_order_no,$r->match_note]);
});
}
}

View File

@ -138,6 +138,7 @@ final class DropshipExporter
}
$this->writeNotes($book, $rows, $originals);
app(\App\Support\CourierBills\SurchargeSettlementMatcher::class)->write($book,'dropship',(int)$factory->id,$month);
$book->writeTo($output);
}
@ -174,7 +175,7 @@ final class DropshipExporter
}
}
$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)
@ -213,7 +214,7 @@ final class DropshipExporter
[$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), null],
$label === $feeLabel => [round($fee, 2), $this->surchargeSelf((int)$factory->id,$month)],
default => [null, null],
};
$sums[0] += (float) $bill;
@ -232,6 +233,17 @@ 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

@ -112,6 +112,33 @@ final class DropshipFees
public function auto(string $month): array
{
$result = [];
$matcher=app(\App\Support\CourierBills\SurchargeSettlementMatcher::class);
$indexed=$matcher->ready()?$this->store->db()->table('dropship_bill_surcharges')->where('bill_month',$month)->distinct()->pluck('factory_id')->all():[];
$hasMatchedFiles=$indexed!==[];
if($hasMatchedFiles){
$rows=$this->store->db()->table($matcher::TABLE)->where('scope','dropship')->where('bill_month',$month)
->selectRaw('owner_id,item,SUM(self_amount) AS amount')->groupBy('owner_id','item')->get();
foreach($rows as $row){
if($row->amount===null)continue;
$key=self::classify($row->item);$id=(int)$row->owner_id;
if($key===null)$result[$id]['other'][$row->item]=(float)$row->amount;
else $result[$id]['fees'][$key]=($result[$id]['fees'][$key]??0)+(float)$row->amount;
}
// 已确认账期维持原自动值,不因接入新的核对方式重写已确认金额。
$states=app(DropshipConfirmation::class)->states($month,(int)(company_id()?:1));
$confirmed=array_keys(array_filter($states,fn($s)=>($s['status']??'')==='confirmed'));
foreach($confirmed as $id)unset($result[$id]);
$legacy=$this->store->db()->table('dropship_bill_files')->where('bill_month',$month)->where('status','parsed')
->where(fn($q)=>$q->whereNotIn('factory_id',$indexed)->orWhereIn('factory_id',$confirmed));
foreach($legacy->get(['id','factory_id','stored_path','sheets']) as $file){
foreach($this->store->feesFor($file) as $type=>$amount){
$key=self::classify($type);$id=(int)$file->factory_id;
if($key===null)$result[$id]['other'][$type]=($result[$id]['other'][$type]??0)+$amount;
else $result[$id]['fees'][$key]=($result[$id]['fees'][$key]??0)+$amount;
}
}
return $result;
}
$files = $this->store->db()->table('dropship_bill_files')->where('bill_month', $month)->where('status', 'parsed')
->whereNotNull('factory_id')->get(['id', 'factory_id', 'stored_path', 'sheets']);
foreach ($files as $file) {

View File

@ -6,6 +6,7 @@ use App\Support\CourierBills\BillWorkbookReader;
use App\Support\CourierBills\CourierBillStore;
use App\Support\CourierBills\FreightBillTemplate;
use App\Support\CourierBills\ShippingLookup;
use App\Support\CourierBills\SurchargeSettlementMatcher;
use Illuminate\Database\ConnectionInterface;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\DB;
@ -84,6 +85,21 @@ final class DropshipFreightStore
return $sheets;
}
/** 新上传时在已有事务内保存;历史文件通过受限批处理命令回读。 */
public function storeSurchargeRows(object $file,int $factoryId): void
{
if(!app(SurchargeSettlementMatcher::class)->ready())return;
$db=$this->db();
$db->table('dropship_bill_surcharges')->where('file_id',$file->id)->delete();
$rows=[];
foreach((new FreightBillTemplate(new BillWorkbookReader()))->surchargeRows(
Storage::disk(self::DISK)->path($file->stored_path),pathinfo($file->stored_path,PATHINFO_EXTENSION)) as $row){
$rows[]=$row+['file_id'=>$file->id,'factory_id'=>$factoryId,'bill_month'=>$file->bill_month];
if(count($rows)>=300){$db->table('dropship_bill_surcharges')->insert($rows);$rows=[];}
}
if($rows!==[])$db->table('dropship_bill_surcharges')->insert($rows);
}
public function db(): ConnectionInterface
{
return DB::connection('business_mirror');
@ -258,9 +274,14 @@ final class DropshipFreightStore
}
$this->db()->transaction(function () use ($file): void {
$this->db()->table('dropship_bill_lines')->where('file_id', $file->id)->delete();
if(app(SurchargeSettlementMatcher::class)->ready()){
$this->db()->table('dropship_bill_surcharges')->where('file_id',$file->id)->delete();
$this->db()->table(SurchargeSettlementMatcher::TABLE)->where('scope','dropship')->where('file_id',$file->id)->delete();
}
$this->db()->table('dropship_bill_files')->where('id', $file->id)->delete();
});
Storage::disk(self::DISK)->delete($file->stored_path);
if($file->factory_id!==null)app(SurchargeSettlementMatcher::class)->dropship((int)$file->factory_id,$file->bill_month);
}
/**
@ -409,6 +430,7 @@ final class DropshipFreightStore
$lines = array_diff_key($lines, array_flip($others));
}
$db->transaction(function () use ($db, $fileId, $factoryId, $file, $lines, $result, $notes): void {
$this->storeSurchargeRows($file,$factoryId);
$db->table('dropship_bill_lines')->where('file_id', $fileId)->delete();
foreach (array_chunk($lines, 500, true) as $chunk) {
$insert = [];
@ -427,6 +449,7 @@ final class DropshipFreightStore
'updated_at' => now(),
]);
});
app(SurchargeSettlementMatcher::class)->dropship($factoryId,$file->bill_month);
}
/** 文件名里出现厂家名、关键字或代发仓核心名,取最长命中的那家。 */

View File

@ -0,0 +1,43 @@
<?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
{
$s = Schema::connection('business_mirror');
if (! $s->hasTable('bill_surcharge_matches')) {
$s->create('bill_surcharge_matches', function (Blueprint $t): void {
$t->id(); $t->string('scope', 16); $t->unsignedBigInteger('owner_id');
$t->unsignedBigInteger('file_id'); $t->string('sheet', 100); $t->unsignedInteger('row_no');
$t->string('bill_month', 7); $t->string('waybill_no', 96); $t->string('item', 100);
$t->string('summary_label', 100);
$t->decimal('bill_amount', 16, 4)->nullable(); $t->decimal('self_amount', 16, 2)->nullable();
$t->string('courier_name', 191)->nullable();
foreach (['platform_product_id','product_code','shop_name','online_order_no'] as $k) $t->text($k)->nullable();
$t->string('match_status', 40); $t->text('match_note')->nullable();
$t->text('settlement_ids')->nullable(); $t->timestamp('matched_at')->nullable();
$t->unique(['scope','owner_id','file_id','sheet','row_no'], 'bill_surcharge_source_unique');
$t->index(['scope','owner_id','id'], 'bill_surcharge_owner');
$t->index(['waybill_no','item','bill_month'], 'bill_surcharge_history');
});
}
if (! $s->hasTable('dropship_bill_surcharges')) {
$s->create('dropship_bill_surcharges', function (Blueprint $t): void {
$t->id(); $t->unsignedBigInteger('file_id')->index(); $t->unsignedBigInteger('factory_id');
$t->string('bill_month', 7); $t->string('sheet', 100); $t->unsignedInteger('row_no');
$t->string('waybill_no', 96); $t->string('item', 100); $t->decimal('amount', 16, 4)->nullable();
$t->index(['factory_id','bill_month','id'], 'dropship_surcharge_month');
});
}
}
public function down(): void
{
Schema::connection('business_mirror')->dropIfExists('bill_surcharge_matches');
Schema::connection('business_mirror')->dropIfExists('dropship_bill_surcharges');
}
};

View File

@ -286,6 +286,7 @@ CRON_TZ=Asia/Shanghai
40 6 * * 1 root /usr/bin/flock -w 3600 /run/caiwu-upstream-sync.lock /bin/sh -c '/usr/bin/docker exec -u www-data caiwu_app php artisan courier-surcharge:pull-overlength --days=90 --quiet; /usr/bin/docker exec -u www-data caiwu_app php artisan courier-surcharge:pull-return --days=90 --quiet' >/dev/null 2>&1
# 客服核实费用按报价生效日校准,覆盖历史工单后补审核与撤销;独立容器保留失败日志。
45 6 * * * root /bin/sh /opt/caiwuxitong/run-finance-batch.sh courier-surcharge:pull-customer-service --courier='常州中通快运' >>/opt/caiwuxitong/runtime/surcharge-customer-service-sync.log 2>&1
5 7 * * * root /bin/sh /opt/caiwuxitong/run-finance-batch.sh courier-surcharge:match-bills --all --existing-only >>/opt/caiwuxitong/runtime/bill-surcharge-matching.log 2>&1
EOF
chmod 644 /etc/cron.d/caiwu-jiansun-snapshots

View File

@ -290,6 +290,7 @@ CRON_TZ=Asia/Shanghai
40 6 * * 1 root /usr/bin/flock -w 3600 /run/caiwu-upstream-sync.lock /bin/sh -c '/usr/bin/docker exec -u www-data caiwu_app php artisan courier-surcharge:pull-overlength --days=90 --quiet; /usr/bin/docker exec -u www-data caiwu_app php artisan courier-surcharge:pull-return --days=90 --quiet' >/dev/null 2>&1
# 客服核实费用按报价生效日校准,覆盖历史工单后补审核与撤销;独立容器保留失败日志。
45 6 * * * root /bin/sh /opt/caiwuxitong/run-finance-batch.sh courier-surcharge:pull-customer-service --courier='常州中通快运' >>/opt/caiwuxitong/runtime/surcharge-customer-service-sync.log 2>&1
5 7 * * * root /bin/sh /opt/caiwuxitong/run-finance-batch.sh courier-surcharge:match-bills --all --existing-only >>/opt/caiwuxitong/runtime/bill-surcharge-matching.log 2>&1
EOF
chmod 644 /etc/cron.d/caiwu-jiansun-snapshots

View File

@ -1,5 +1,6 @@
[
"portal-freight:import-pending",
"courier-surcharge:match-bills",
"planting-reimbursement:auto-confirm",
"jushuitan:apply-shipping-corrections",
"actual-tax:import",

View File

@ -8,7 +8,7 @@ is_import=0
CAIWU_BATCH_CALLER_DIR="$PWD"
export CAIWU_BATCH_CALLER_DIR
case "${1:-}" in
portal-freight:import-pending) is_import=1 ;;
portal-freight:import-pending|courier-surcharge:match-bills) is_import=1 ;;
planting-reimbursement:auto-confirm) is_import=1 ;;
jushuitan:apply-shipping-corrections|*:import|*:import-*|*:import:*|payables:final-import|payables:unpriced-cycle|payables:unpriced-cycle:auto|product:monthly-weighted-average:base|planting-details:sync-work-orders|jst-order-labels:sync-daily) is_import=1 ;;
jushuitan:align-weights|jushuitan:calc-freight|courier:sync-unshipped-waybills|courier:seed-unshipped-history|business-mirror:sync-returned-parcels|courier-surcharge:pull-customer-service) ;;

View File

@ -0,0 +1,11 @@
# 附加费账单匹配
快递账单和代发账单以账单月份归集附加费。按完整快递单号、规范化费用类型、快递归属匹配 `courier_surcharge_settlement_rows` 中“已计算”的金额;允许匹配以前月份费用,不把账单金额当自算金额。客服费用以工单创建时间、其他费用以发货时间确定上界,不取账期之后的费用。
新文件导入时自动匹配,已有账单可用 `courier-surcharge:match-bills --month=2026-11 --statement=11` 或 `--factory=厂家ID` 校准,也可 `--all` 处理当月未确认账单。命令省略月份时取北京时间上月,生产每天 07:05 使用 `--all --existing-only` 更新已经建立匹配的账单;首次历史回补单独确认,部署和定时任务不会自动启用旧账单。命令必须走 `run-finance-batch.sh`,共用上游互斥锁和独立批容器,PHP 512 MiB、容器 1 GiB、最长 3600 秒,失败按同范围重跑。每份账单的更新在事务内;不改已确认快递账单或厂家确认状态,不重算原运费行,手工小汇总优先。
`bill_surcharge_matches` 保存来源文件/工作表/行号、账期、单号、类型、对方金额、自算金额、状态、商品/店铺/订单信息和稳定费用来源标识。`dropship_bill_surcharges` 保存厂家原始附加费行。Excel 使用项目现有流式读取器,每批匹配 300 行,来源按单号索引查询,明细页面 50 行分页,导出逐批写入“附加费核对”子表。类型只使用明确同义词(如改地址费→改地址),不把不明类型猜成其他费用。
同一账期重复提供的单号+费用类型只计一次;同一费用来源已被其他账单计入时不再计入,仅新出现的费用来源可继续计入。同一单号不同费用类型分别核对;匹配不到或快递归属不符时自算金额留空并显示原因。代发还要求发货仓库及快递名称同时属于该厂家,排除自有快递。多个商品信息去重后展示,金额按票汇总,不乘商品数。
查询/校准不会写上游报价或来源费用;删除账单文件时清除其派生匹配结果。真实账单、备份与生产日志保留在 Git 忽略的私有目录。

View File

@ -9,7 +9,7 @@
<div class="cbr-heading">
<div>
<h2>快递账单对账</h2>
<p>上传账单 → 自动对账 → 逐家核对 → 确认结算。小汇总按财务规则归集到「快递应付汇总」。第一期只核运费,附加费等在对账单里手工加行。</p>
<p>上传账单 → 自动对账 → 逐家核对 → 确认结算。小汇总按财务规则归集到「快递应付汇总」。附加费按账单单号、费用类型和快递归属匹配结算金额。</p>
</div>
<div class="cbr-form">
<a class="cbr-button" href="{{ route('business.pages.show', ['section' => $cbSection, 'page' => 'courier-payable-summary', 'month' => $month]) }}">去快递应付汇总</a>

View File

@ -149,6 +149,8 @@
</form>
</section>
@include('business.pages.courier-payables.partials.surcharge-matches', ['surchargeRows' => $cbSurchargeRows ?? null])
<section class="cbr-panel" aria-label="账单文件">
<h3>账单文件</h3>
<div class="cbr-scroll">

View File

@ -41,6 +41,16 @@
@endif
</section>
@if (($dfSurchargeSummary ?? collect())->isNotEmpty())
<section class="cbr-panel" aria-label="附加费小汇总">
<h3>附加费小汇总</h3><div class="cbr-scroll"><table>
<thead><tr><th>项目</th><th class="num">厂家提供金额</th><th class="num">自算金额</th><th class="num">差额</th></tr></thead>
<tbody>@foreach ($dfSurchargeSummary as $fee)<tr><td>{{ $fee->item }}</td><td class="num">{{ $money($fee->bill) }}</td><td class="num">{{ $money($fee->self) }}</td><td class="num">{{ $fee->self === null ? '—' : $money((float)$fee->bill - (float)$fee->self) }}</td></tr>@endforeach</tbody>
</table></div>
</section>
@endif
@include('business.pages.courier-payables.partials.surcharge-matches', ['surchargeRows' => $dfSurchargeRows ?? null])
<nav class="cbr-tabs" aria-label="按状态看">
<a data-cbr-tab href="{{ $pageUrl(['df_view' => 'factory', 'factory' => $dfFactory->id, 'month' => $month]) }}" class="{{ $dfStatus === '' ? 'is-active' : '' }}">全部<span>{{ array_sum($s['counts']) }}</span></a>
<a data-cbr-tab href="{{ $pageUrl(['df_view' => 'factory', 'factory' => $dfFactory->id, 'month' => $month, 'status' => 'attention']) }}" class="{{ $dfStatus === 'attention' ? 'is-active' : '' }}">要看的<span>{{ $s['attention'] }}</span></a>

View File

@ -52,7 +52,7 @@
@endforeach
<label>备注<input type="text" name="note" maxlength="255" value="{{ $fee['note'] }}"></label>
<button type="submit">保存</button>
<span class="cbr-muted">空着 = 用厂家附加费表自动带入的值。</span>
<span class="cbr-muted">空着 = 用厂家附加费单号匹配结算表的自算金额。</span>
</form>
</details>
</td>

View File

@ -0,0 +1,17 @@
@if ($surchargeRows !== null && $surchargeRows->total() > 0)
<section class="cbr-panel" aria-label="附加费核对明细">
<h3>附加费核对明细</h3>
<p class="cbr-muted cbr-panel-body">按账单月份归集,以单号、附加费类型和快递归属匹配结算金额,可匹配以前月份的费用。未匹配的金额留空,重复费用不再计入;不会将对方金额作为自算金额。</p>
<div class="cbr-scroll"><table>
<thead><tr>@foreach (['来源工作表','快递单号','附加费类型','对方金额','自算金额','差额','匹配状态','快递名称','平台商品ID','商品编码','店铺名称','线上订单号','说明'] as $label)<th scope="col">{{ $label }}</th>@endforeach</tr></thead>
<tbody>@foreach ($surchargeRows as $fee)<tr>
<td>{{ $fee->sheet }} · {{ $fee->row_no }}</td><td>{{ $fee->waybill_no }}</td><td>{{ $fee->item }}</td>
<td class="num">{{ $money($fee->bill_amount) }}</td><td class="num">{{ $money($fee->self_amount) }}</td>
<td class="num">{{ $fee->self_amount === null ? '—' : $money((float)$fee->bill_amount - (float)$fee->self_amount) }}</td>
<td>{{ $fee->match_status }}</td><td>{{ $fee->courier_name ?: '—' }}</td><td>{{ $fee->platform_product_id ?: '—' }}</td>
<td>{{ $fee->product_code ?: '—' }}</td><td>{{ $fee->shop_name ?: '—' }}</td><td>{{ $fee->online_order_no ?: '—' }}</td><td class="wrap">{{ $fee->match_note }}</td>
</tr>@endforeach</tbody>
</table></div>
<div class="cbr-footer cbr-pager">共 {{ number_format($surchargeRows->total()) }} 条 {{ $surchargeRows->links('business.partials.previous-next-pagination') }}</div>
</section>
@endif

View File

@ -0,0 +1,172 @@
<?php
namespace Tests\Feature\Business;
use App\Support\CourierBills\CourierBillStore;
use App\Support\CourierBills\CourierBillMatcher;
use App\Support\CourierBills\ShippingLookup;
use App\Support\CourierBills\SurchargeSettlementMatcher;
use App\Support\CourierBills\StatementExporter;
use App\Support\DropshipFreight\DropshipFreightStore;
use App\Support\DropshipFreight\DropshipExporter;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Storage;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\IOFactory;
use Tests\Feature\FeatureTestCase;
class BillSurchargeMatchingTest extends FeatureTestCase
{
private array $temp=[];
protected function setUp(): void
{
parent::setUp();Storage::fake('local');
self::createSettlementTable();
}
public static function createSettlementTable(): void
{
$s=Schema::connection('business_mirror');
if($s->hasTable('courier_surcharge_settlement_rows'))return;
$s->create('courier_surcharge_settlement_rows',function(Blueprint $t):void{
$t->id();$t->integer('rule_id')->default(1);$t->integer('outbound_io_id')->nullable();
foreach(['courier_name','waybill','surcharge_type','settlement_status','platform_product_id','product_code','shop_name','online_order_no','source_kind','source_key'] as $key)$t->string($key)->nullable();
$t->decimal('settlement_amount',16,2);$t->dateTime('shipped_at')->nullable();$t->dateTime('pulled_at')->nullable();$t->dateTime('source_created_at')->nullable();
$t->index(['waybill']);
});
}
private function fee(string $waybill,string $type,float $amount,string $courier='常州中通快运',string $date='2026-10-02'): void
{
DB::connection('business_mirror')->table('courier_surcharge_settlement_rows')->insert([
'waybill'=>$waybill,'surcharge_type'=>$type,'settlement_amount'=>$amount,'courier_name'=>$courier,
'settlement_status'=>'已计算','shipped_at'=>$date.' 12:00:00','source_key'=>'GD-'.$waybill.'-'.$type,
'source_kind'=>'work_order_customer_service','platform_product_id'=>'12345678901234567890',
'product_code'=>'SKU-TEST','shop_name'=>'测试店铺','online_order_no'=>'123456789012345678901']);
}
private function ship(string $no,string $courier,string $warehouse='测试仓'): void
{
$db=app(ShippingLookup::class)->connection();
$id=$db->table('jst_oms_shipping')->insertGetId(['express_no'=>$no,'express_name1'=>$courier,'warehouse_name'=>$warehouse,'ship_time'=>'2026-11-02 12:00:00']);
$db->table('jst_oms_shipping')->where('id',$id)->update(['source_id'=>$id]);
$db->table('jst_oms_shipping_freight')->insert(['source_id'=>$id,'freight'=>10,'status'=>'OK']);
}
private function book(array $sheets): string
{
$book=new Spreadsheet();$book->removeSheetByIndex(0);
foreach($sheets as $name=>$rows){$sheet=$book->createSheet();$sheet->setTitle($name);
foreach($rows as $r=>$row)foreach($row as $c=>$value)if($value!==null)$sheet->setCellValueExplicit([$c+1,$r+1],$value,is_string($value)?'s':'n');}
$path=tempnam(sys_get_temp_dir(),'fee_bill_').'.xlsx';$this->temp[]=$path;(new Xlsx($book))->save($path);$book->disconnectWorksheets();return $path;
}
public function test_courier_import_matches_prior_month_fees_and_preserves_metadata_and_duplicates(): void
{
$store=app(CourierBillStore::class);$store->saveGroup(null,['name'=>'常州中通快运','express_names'=>['常州中通快运']]);
foreach(['001234567890','001234567891','001234567892','001234567893'] as $no)$this->ship($no,'常州中通快运');
$this->fee('001234567890','上楼费',13.44);$this->fee('001234567891','改地址',5);
$this->fee('001234567892','上楼费',99,'别家快递');$this->fee('001234567893','上楼费',88,'常州中通快运','2026-12-01');
$path=$this->book(['账单'=>[['单号','运费'],['001234567890',10],['001234567891',10],['001234567892',10],['001234567893',10]],
'附加费'=>[['快递单号','附加费金额','附加费类型'],['001234567890',20,'上楼费'],['001234567890',20,'上楼费'],['001234567891',8,'改地址费'],['001234567892',99,'上楼费'],['001234567893',88,'上楼费']]]);
$fileId=$store->upload([new UploadedFile($path,'常州中通快运11月.xlsx',null,null,true)],'2026-11',[],'测试')[0];
$db=$store->db();$id=(int)$db->table('courier_bill_files')->where('id',$fileId)->value('statement_id');
$matches=app(SurchargeSettlementMatcher::class)->query('courier',$id)->orderBy('id')->get();
$this->assertSame(['已匹配','重复','已匹配','未匹配','未匹配'],$matches->pluck('match_status')->all());
$this->assertEquals(18.44,round($matches->sum('self_amount'),2));$this->assertSame('12345678901234567890',$matches[0]->platform_product_id);
$this->assertSame('SKU-TEST',$matches[0]->product_code);$this->assertSame('测试店铺',$matches[0]->shop_name);
$this->assertSame('123456789012345678901',$matches[0]->online_order_no);
$this->assertEquals(18.44,$db->table('courier_bill_summary_items')->where('statement_id',$id)->where('label','附加费')->value('self_amount'));
$store->rematch($id);$this->assertSame(5,app(SurchargeSettlementMatcher::class)->query('courier',$id)->count());
$this->assertEquals(18.44,round((float)app(SurchargeSettlementMatcher::class)->query('courier',$id)->sum('self_amount'),2));
$out=tempnam(sys_get_temp_dir(),'fees_out');$this->temp[]=$out;$h=fopen($out,'wb');app(StatementExporter::class)->export($id,$h);fclose($h);
$book=IOFactory::load($out);$sheet=$book->getSheetByName('附加费核对-'.$id);$this->assertNotNull($sheet);
$cell=$sheet->getCell('K2')->getValue();
$this->assertSame('12345678901234567890',$cell instanceof \PhpOffice\PhpSpreadsheet\RichText\RichText?$cell->getPlainText():$cell);$book->disconnectWorksheets();
$db->table('courier_bill_summary_items')->where('statement_id',$id)->where('label','11月运费')->update(['self_amount'=>123.45]);
$db->table('courier_bill_summary_items')->where('statement_id',$id)->where('label','附加费')->update(['manual'=>true,'self_amount'=>17.12]);
app(CourierBillMatcher::class)->refreshSurchargeSummary($id);
$this->assertEquals(123.45,$db->table('courier_bill_summary_items')->where('statement_id',$id)->where('label','11月运费')->value('self_amount'));
$this->assertEquals(17.12,$db->table('courier_bill_summary_items')->where('statement_id',$id)->where('label','附加费')->value('self_amount'));
$this->user->attachPermission(\App\Models\Auth\Permission::where('name','read-admin-panel')->firstOrFail());
$this->loginAs()->get(route('business.pages.show',['section'=>'courier-payables-final','page'=>'courier-bill-reconciliation','cb_view'=>'statement','statement'=>$id]))
->assertOk()->assertSeeText('附加费核对明细')->assertSeeText('SKU-TEST')->assertSeeText('12345678901234567890');
}
public function test_dropship_import_uses_system_fee_not_factory_quote_and_checks_warehouse(): void
{
$store=app(DropshipFreightStore::class);$id=$store->saveFactory(null,['name'=>'测试代发','warehouse'=>'工厂-测试代发仓','keywords'=>'代发快递']);
$this->ship('YT0012345678','测试代发快递','工厂-测试代发仓');$this->fee('YT0012345678','改地址',4.25,'测试代发快递');
$path=$this->book(['账单'=>[['单号','运费'],['YT0012345678',10]],'附加费'=>[['快递单号','附加费金额','附加费类型'],['YT0012345678',50,'改地址费']]]);
$store->uploadFor('测试代发11月.xlsx',$path,'2026-11',$id,'测试');
$row=app(SurchargeSettlementMatcher::class)->query('dropship',$id,'2026-11')->first();
$this->assertEquals(50,$row->bill_amount);$this->assertEquals(4.25,$row->self_amount);
$auto=app(\App\Support\DropshipFreight\DropshipFees::class)->auto('2026-11');$this->assertEquals(4.25,$auto[$id]['fees']['readdress']);
$out=tempnam(sys_get_temp_dir(),'df_out');$this->temp[]=$out;$h=fopen($out,'wb');app(DropshipExporter::class)->export(collect($store->factories())->sole(),'2026-11',$h);fclose($h);
$book=IOFactory::load($out);$this->assertNotNull($book->getSheetByName('附加费核对'));$summary=$book->getSheetByName('汇总')->toArray(null,false,false);$feeRow=current(array_filter($summary,fn($r)=>$r[0]==='厂家账单-附加费'));$this->assertEquals(4.25,$feeRow[2]);$book->disconnectWorksheets();
}
public function test_other_month_cannot_pay_the_same_settlement_again_and_confirmed_is_frozen(): void
{
$db=DB::connection('business_mirror');$store=app(CourierBillStore::class);$group=$store->saveGroup(null,['name'=>'常州中通快运','express_names'=>['常州中通快运']]);
$this->fee('HISTORY1234','上楼费',10);
foreach(['2026-10','2026-11'] as $month){$sid=$db->table('courier_bill_statements')->insertGetId(['group_id'=>$group,'bill_month'=>$month,'status'=>'open','created_at'=>now(),'updated_at'=>now()]);
$fid=$db->table('courier_bill_files')->insertGetId(['statement_id'=>$sid,'bill_month'=>$month,'group_id'=>$group,'original_name'=>'test','stored_path'=>'test','status'=>'parsed','created_at'=>now(),'updated_at'=>now()]);
$db->table('courier_bill_surcharges')->insert(['file_id'=>$fid,'sheet'=>'上楼费','row_no'=>2,'waybill_no'=>'HISTORY1234','item'=>'上楼费','amount'=>50]);
app(SurchargeSettlementMatcher::class)->courier($sid);$last=$sid;}
$row=app(SurchargeSettlementMatcher::class)->query('courier',$last)->first();$this->assertSame('历史已计入',$row->match_status);$this->assertEquals(0,$row->self_amount);
$db->table('courier_bill_statements')->where('id',$last)->update(['status'=>'confirmed']);
$db->table('courier_surcharge_settlement_rows')->update(['settlement_amount'=>123]);app(SurchargeSettlementMatcher::class)->courier($last);
$this->assertEquals(0,app(SurchargeSettlementMatcher::class)->query('courier',$last)->value('self_amount'));
}
public function test_monthly_surcharge_batch_defaults_to_previous_month_and_requires_a_scope(): void
{
$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();
}
public function test_daily_refresh_does_not_enable_legacy_bills_and_only_new_sources_are_counted(): void
{
$db=DB::connection('business_mirror');$store=app(CourierBillStore::class);
$group=$store->saveGroup(null,['name'=>'常州中通快运','express_names'=>['常州中通快运']]);
$this->fee('PARTIAL1234','上楼费',10);
$ids=[];
foreach(['2026-10','2026-11'] as $month){
$sid=$db->table('courier_bill_statements')->insertGetId(['group_id'=>$group,'bill_month'=>$month,'status'=>'open','created_at'=>now(),'updated_at'=>now()]);
$fid=$db->table('courier_bill_files')->insertGetId(['statement_id'=>$sid,'bill_month'=>$month,'group_id'=>$group,'original_name'=>'test','stored_path'=>'test','status'=>'parsed','created_at'=>now(),'updated_at'=>now()]);
$db->table('courier_bill_surcharges')->insert(['file_id'=>$fid,'sheet'=>'上楼费','row_no'=>2,'waybill_no'=>'PARTIAL1234','item'=>'上楼费','amount'=>20]);
$ids[]=$sid;
}
$matcher=app(SurchargeSettlementMatcher::class);$matcher->courier($ids[0]);
$this->artisan('courier-surcharge:match-bills',['--month'=>'2026-11','--all'=>true,'--existing-only'=>true])->assertSuccessful();
$this->assertSame(0,$matcher->query('courier',$ids[1])->count());
$source=(array)$db->table('courier_surcharge_settlement_rows')->first();unset($source['id']);
$source['source_key']='GD-NEW';$source['settlement_amount']=3.25;$source['shipped_at']='2026-11-05 12:00:00';
$db->table('courier_surcharge_settlement_rows')->insert($source);
$matcher->courier($ids[1]);$row=$matcher->query('courier',$ids[1])->first();
$this->assertEquals(3.25,$row->self_amount);$this->assertStringContainsString('已扣除',$row->match_note);
$db->table('courier_surcharge_settlement_rows')->where('source_key','GD-NEW')->update(['settlement_amount'=>4.25]);
$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'));
}
public function test_dropship_rejects_a_matching_courier_from_another_factory_warehouse(): void
{
$store=app(DropshipFreightStore::class);$id=$store->saveFactory(null,['name'=>'本厂','warehouse'=>'本厂仓','keywords'=>'代发快递']);
$this->ship('WRONG12345','测试代发快递','其他厂仓');$this->fee('WRONG12345','改地址',15,'测试代发快递');
$db=$store->db();$file=$db->table('dropship_bill_files')->insertGetId(['factory_id'=>$id,'bill_month'=>'2026-11','original_name'=>'test.xlsx','stored_path'=>'test.xlsx','status'=>'parsed','created_at'=>now(),'updated_at'=>now()]);
$db->table('dropship_bill_surcharges')->insert(['factory_id'=>$id,'file_id'=>$file,'bill_month'=>'2026-11','sheet'=>'附加费','row_no'=>2,'waybill_no'=>'WRONG12345','item'=>'改地址','amount'=>30]);
app(SurchargeSettlementMatcher::class)->dropship($id,'2026-11');
$row=app(SurchargeSettlementMatcher::class)->query('dropship',$id,'2026-11')->first();
$this->assertNull($row->self_amount);$this->assertSame('未匹配',$row->match_status);
}
protected function tearDown(): void {foreach($this->temp as $path)@unlink($path);parent::tearDown();}
}

View File

@ -696,7 +696,7 @@ final class CourierBillReconciliationTest extends FeatureTestCase
$id = $store->upload([new UploadedFile($path, '河北中通-江三10月.xlsx', null, null, true)], '2026-10', [], 'tester')[0];
$file = $store->db()->table('courier_bill_files')->find($id);
$this->assertSame(2, (int) $file->row_count);
$this->assertSame('附加费只读了金额进小汇总,没有逐单核对:2 行,合计 10.00;没读入:退货数据(没找到单号列,2 行)', $file->message);
$this->assertSame('附加费已按单号和费用类型匹配结算表:2 行,对方合计 10.00;没读入:退货数据(没找到单号列,2 行)', $file->message);
// 附加费一张表一行,名字用账单里的表名;快递金额照读,自算先放 0
$fees = $store->db()->table('courier_bill_summary_items')->where('statement_id', $file->statement_id)->where('manual', false)
->whereNotIn('label', ['10月运费'])->orderBy('sort')->get()->map(fn ($i) => [$i->label, (float) $i->bill_amount, (float) $i->self_amount])->all();

View File

@ -393,6 +393,14 @@ final class DropshipFreightTest extends FeatureTestCase
'附加费' => [['快递单号', '附加费金额', '附加费类型'], ['773444000001', 3, '退回费'], ['773444000002', 2, '拦截费'], ['773444000002', 1.5, '上楼费']]]);
app(DropshipFreightStore::class)->uploadFor('卿德客11月.xlsx', $path, '2026-11', $id, '测试');
// 自算来自结算表;厂家提供金额不能当作系统已核对金额。
BillSurchargeMatchingTest::createSettlementTable();
foreach([['773444000001','退回费',3],['773444000002','拦截费',2],['773444000002','上楼费',1.5]] as [$wb,$type,$amount]){
$db->table('courier_surcharge_settlement_rows')->insert(['waybill'=>$wb,'surcharge_type'=>$type,
'courier_name'=>'卿德客申通','settlement_amount'=>$amount,'settlement_status'=>'已计算','shipped_at'=>'2026-11-01 00:00:00']);
}
app(\App\Support\CourierBills\SurchargeSettlementMatcher::class)->dropship($id,'2026-11');
$fees = app(\App\Support\DropshipFreight\DropshipFees::class);
$row = $fees->rows('2026-11', [$id => 13.0], (int) $this->company->id)[$id];
$this->assertEquals(['freight' => 13, 'returned' => 3, 'intercept' => 2], array_filter($row['values']));
@ -441,9 +449,9 @@ final class DropshipFreightTest extends FeatureTestCase
$this->assertSame(['运费', '记账', '厂家账单-附加费', '合计'], array_column(array_slice($summary, 1, 4), 0));
$this->assertEquals([13, 13], array_slice($summary[1], 1, 2));
$this->assertEquals(6.5, $summary[3][1]);
$this->assertNull($summary[3][2]);
$this->assertEquals(6.5,$summary[3][2]);
$this->assertEquals(19.5, $sheet->getCell('B5')->getCalculatedValue());
$this->assertEquals(6.5, $sheet->getCell('D5')->getCalculatedValue());
$this->assertEquals(0, $sheet->getCell('D5')->getCalculatedValue());
$book->disconnectWorksheets();
@unlink($out);
$file = $db->table('dropship_bill_files')->first();