CaiWuXiTong/app/Support/CourierBills/SurchargeSettlementMatcher.php

242 lines
17 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?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) ?? '';
if (str_contains($type, '拦截费')) return '拦截费';
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','已计算');
$window=BillSurchargeQuoteCalculator::window($month);$end=$window['until'];
if($db->getSchemaBuilder()->hasColumn('courier_surcharge_settlement_rows','source_created_at')){
$sourceQuery->whereRaw('COALESCE(source_created_at,shipped_at) >= ?',[$window['from']])->whereRaw('COALESCE(source_created_at,shipped_at) < ?',[$end]);
}else{$sourceQuery->where('shipped_at','>=',$window['from'])->where('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):[];
$allowedCouriers=$names;
if($factory){
$keywords=DropshipFreightStore::splitKeywords($factory->keywords);
foreach($ships as $ship)foreach(array_keys($ship['pairs'][$factory->warehouse]??[]) as $express)
if(!isset($own[$express])&&array_filter($keywords,fn($k)=>str_contains($express,$k))!==[])$allowedCouriers[]=$express;
}
$calculated=app(BillSurchargeQuoteCalculator::class)->calculate($input,$scope,$month,array_values(array_unique($allowedCouriers)));
$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']='无法确认该单属于本厂家代发快递及仓库';
}
$window=BillSurchargeQuoteCalculator::window($month);
$rows=array_values(array_filter($rows,function($r)use($allowed,$window){
$date=substr((string)($r->source_created_at??$r->shipped_at??''),0,10);
$shipped=substr((string)($r->shipped_at??''),0,10);
return in_array($r->courier_name,$allowed,true)&&$date!==''&&$date>=$window['from']&&$date<$window['until']
&&($shipped===''||($shipped>=$window['from']&&$shipped<$window['until']));
}));
$priced=array_values(array_filter($calculated['rows'][$wb][$type]??[],fn($r)=>in_array($r->courier_name,$allowed,true)));
// 已支持的报价按票核价优先,避免同单号多张出库记录把每票费用重复累加。
if(array_key_exists($type,$calculated['rows'][$wb]??[]))$rows=$priced;
if($rows===[]){
if(isset($calculated['notes'][$wb][$type])&&(!$factory||$allowed!==[]))$row['match_note']=$calculated['notes'][$wb][$type];
if(!$factory||$allowed!==[])$row=array_replace($row,$calculated['metadata'][$wb]??[]);
}
$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?';已扣除其他账单已计入费用':'');
$evidence=array_values(array_unique(array_filter(array_map(fn($r)=>$r->evidence??null,$rows))));
if($evidence!==[])$row['match_note'].=';'.implode(';',$evidence);
if ($scope === 'courier' && $row['bill_amount'] !== null && (float) $row['bill_amount'] < $row['self_amount']) {
$row['self_amount'] = round((float) $row['bill_amount'], 2);
$row['match_note'] .= ';快递提供金额较低,按快递金额结算';
}
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]??[])!==[]&&!isset($calculated['notes'][$wb][$type])) $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]);
});
}
}