From 5349a3c8a515fe4031d5cf17f83b0067dbd1f29d Mon Sep 17 00:00:00 2001 From: limeng <1131177064@qq.com> Date: Fri, 4 Dec 2026 12:27:08 +0800 Subject: [PATCH] =?UTF-8?q?feat(=E9=99=84=E5=8A=A0=E8=B4=B9=E5=AF=B9?= =?UTF-8?q?=E8=B4=A6):=20=E6=8C=89=E8=B4=A6=E5=8D=95=E5=8C=B9=E9=85=8D?= =?UTF-8?q?=E8=87=AA=E7=AE=97=E9=87=91=E9=A2=9D=E5=92=8C=E5=95=86=E5=93=81?= =?UTF-8?q?=E4=BF=A1=E6=81=AF=20(#1728)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Console/Commands/MatchBillSurcharges.php | 50 ++++ .../Business/CourierBillController.php | 5 +- .../Business/DropshipFreightController.php | 7 +- app/Support/CourierBills/BillParser.php | 2 +- .../CourierBills/CourierBillMatcher.php | 37 ++- app/Support/CourierBills/CourierBillStore.php | 3 +- .../CourierBills/FreightBillTemplate.php | 21 ++ .../CourierBills/StatementExporter.php | 3 +- .../SurchargeSettlementMatcher.php | 214 ++++++++++++++++++ .../DropshipFreight/DropshipExporter.php | 16 +- app/Support/DropshipFreight/DropshipFees.php | 27 +++ .../DropshipFreight/DropshipFreightStore.php | 23 ++ ...4_150000_create_bill_surcharge_matches.php | 43 ++++ deploy/activate-incremental-release.sh | 1 + deploy/activate-release.sh | 1 + deploy/finance-batch-imports.json | 1 + deploy/run-finance-batch.sh | 2 +- docs/附加费账单匹配.md | 11 + .../courier-bills/page.blade.php | 2 +- .../courier-bills/statement.blade.php | 2 + .../dropship-freight/factory.blade.php | 10 + .../dropship-freight/overview.blade.php | 2 +- .../partials/surcharge-matches.blade.php | 17 ++ .../Business/BillSurchargeMatchingTest.php | 172 ++++++++++++++ .../CourierBillReconciliationTest.php | 2 +- .../Feature/Business/DropshipFreightTest.php | 12 +- 26 files changed, 670 insertions(+), 16 deletions(-) create mode 100644 app/Console/Commands/MatchBillSurcharges.php create mode 100644 app/Support/CourierBills/SurchargeSettlementMatcher.php create mode 100644 database/migrations/2026_12_04_150000_create_bill_surcharge_matches.php create mode 100644 docs/附加费账单匹配.md create mode 100644 resources/views/business/pages/courier-payables/partials/surcharge-matches.blade.php create mode 100644 tests/Feature/Business/BillSurchargeMatchingTest.php diff --git a/app/Console/Commands/MatchBillSurcharges.php b/app/Console/Commands/MatchBillSurcharges.php new file mode 100644 index 000000000..a31cb3e15 --- /dev/null +++ b/app/Console/Commands/MatchBillSurcharges.php @@ -0,0 +1,50 @@ +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();} + } +} diff --git a/app/Http/Controllers/Business/CourierBillController.php b/app/Http/Controllers/Business/CourierBillController.php index ab33647fd..63a9109de 100644 --- a/app/Http/Controllers/Business/CourierBillController.php +++ b/app/Http/Controllers/Business/CourierBillController.php @@ -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|null */ diff --git a/app/Http/Controllers/Business/DropshipFreightController.php b/app/Http/Controllers/Business/DropshipFreightController.php index 17c44721e..dac6315fa 100644 --- a/app/Http/Controllers/Business/DropshipFreightController.php +++ b/app/Http/Controllers/Business/DropshipFreightController.php @@ -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 diff --git a/app/Support/CourierBills/BillParser.php b/app/Support/CourierBills/BillParser.php index 73e70d2ed..c5eea09c1 100644 --- a/app/Support/CourierBills/BillParser.php +++ b/app/Support/CourierBills/BillParser.php @@ -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 { diff --git a/app/Support/CourierBills/CourierBillMatcher.php b/app/Support/CourierBills/CourierBillMatcher.php index ce37bee88..957881951 100644 --- a/app/Support/CourierBills/CourierBillMatcher.php +++ b/app/Support/CourierBills/CourierBillMatcher.php @@ -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 diff --git a/app/Support/CourierBills/CourierBillStore.php b/app/Support/CourierBills/CourierBillStore.php index 28a5f8d51..4b8aff37d 100644 --- a/app/Support/CourierBills/CourierBillStore.php +++ b/app/Support/CourierBills/CourierBillStore.php @@ -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) { diff --git a/app/Support/CourierBills/FreightBillTemplate.php b/app/Support/CourierBills/FreightBillTemplate.php index 3c3d2b3eb..56797b7bc 100644 --- a/app/Support/CourierBills/FreightBillTemplate.php +++ b/app/Support/CourierBills/FreightBillTemplate.php @@ -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 { diff --git a/app/Support/CourierBills/StatementExporter.php b/app/Support/CourierBills/StatementExporter.php index c41f2698a..8481dd42e 100644 --- a/app/Support/CourierBills/StatementExporter.php +++ b/app/Support/CourierBills/StatementExporter.php @@ -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); } diff --git a/app/Support/CourierBills/SurchargeSettlementMatcher.php b/app/Support/CourierBills/SurchargeSettlementMatcher.php new file mode 100644 index 000000000..ceac3dd90 --- /dev/null +++ b/app/Support/CourierBills/SurchargeSettlementMatcher.php @@ -0,0 +1,214 @@ +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]); + }); + } +} diff --git a/app/Support/DropshipFreight/DropshipExporter.php b/app/Support/DropshipFreight/DropshipExporter.php index 66db365a2..2a1e535c5 100644 --- a/app/Support/DropshipFreight/DropshipExporter.php +++ b/app/Support/DropshipFreight/DropshipExporter.php @@ -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 { diff --git a/app/Support/DropshipFreight/DropshipFees.php b/app/Support/DropshipFreight/DropshipFees.php index 6072126cb..eb0bfc111 100644 --- a/app/Support/DropshipFreight/DropshipFees.php +++ b/app/Support/DropshipFreight/DropshipFees.php @@ -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) { diff --git a/app/Support/DropshipFreight/DropshipFreightStore.php b/app/Support/DropshipFreight/DropshipFreightStore.php index 3ab8ad4f0..0971bc50e 100644 --- a/app/Support/DropshipFreight/DropshipFreightStore.php +++ b/app/Support/DropshipFreight/DropshipFreightStore.php @@ -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); } /** 文件名里出现厂家名、关键字或代发仓核心名,取最长命中的那家。 */ diff --git a/database/migrations/2026_12_04_150000_create_bill_surcharge_matches.php b/database/migrations/2026_12_04_150000_create_bill_surcharge_matches.php new file mode 100644 index 000000000..47d362753 --- /dev/null +++ b/database/migrations/2026_12_04_150000_create_bill_surcharge_matches.php @@ -0,0 +1,43 @@ +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'); + } +}; diff --git a/deploy/activate-incremental-release.sh b/deploy/activate-incremental-release.sh index 722a2df47..c8571f707 100644 --- a/deploy/activate-incremental-release.sh +++ b/deploy/activate-incremental-release.sh @@ -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 diff --git a/deploy/activate-release.sh b/deploy/activate-release.sh index 02dac4896..ca9f33636 100644 --- a/deploy/activate-release.sh +++ b/deploy/activate-release.sh @@ -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 diff --git a/deploy/finance-batch-imports.json b/deploy/finance-batch-imports.json index b5413e615..89a0de301 100644 --- a/deploy/finance-batch-imports.json +++ b/deploy/finance-batch-imports.json @@ -1,5 +1,6 @@ [ "portal-freight:import-pending", + "courier-surcharge:match-bills", "planting-reimbursement:auto-confirm", "jushuitan:apply-shipping-corrections", "actual-tax:import", diff --git a/deploy/run-finance-batch.sh b/deploy/run-finance-batch.sh index 10c3fc2e5..98bfad32a 100644 --- a/deploy/run-finance-batch.sh +++ b/deploy/run-finance-batch.sh @@ -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) ;; diff --git a/docs/附加费账单匹配.md b/docs/附加费账单匹配.md new file mode 100644 index 000000000..78fb01a40 --- /dev/null +++ b/docs/附加费账单匹配.md @@ -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 忽略的私有目录。 diff --git a/resources/views/business/pages/courier-payables/courier-bills/page.blade.php b/resources/views/business/pages/courier-payables/courier-bills/page.blade.php index 1976b51c0..60b37f4dc 100644 --- a/resources/views/business/pages/courier-payables/courier-bills/page.blade.php +++ b/resources/views/business/pages/courier-payables/courier-bills/page.blade.php @@ -9,7 +9,7 @@

快递账单对账

-

上传账单 → 自动对账 → 逐家核对 → 确认结算。小汇总按财务规则归集到「快递应付汇总」。第一期只核运费,附加费等在对账单里手工加行。

+

上传账单 → 自动对账 → 逐家核对 → 确认结算。小汇总按财务规则归集到「快递应付汇总」。附加费按账单单号、费用类型和快递归属匹配结算金额。

去快递应付汇总 diff --git a/resources/views/business/pages/courier-payables/courier-bills/statement.blade.php b/resources/views/business/pages/courier-payables/courier-bills/statement.blade.php index 203b8d253..a1b26cddb 100644 --- a/resources/views/business/pages/courier-payables/courier-bills/statement.blade.php +++ b/resources/views/business/pages/courier-payables/courier-bills/statement.blade.php @@ -149,6 +149,8 @@ +@include('business.pages.courier-payables.partials.surcharge-matches', ['surchargeRows' => $cbSurchargeRows ?? null]) +

账单文件

diff --git a/resources/views/business/pages/courier-payables/dropship-freight/factory.blade.php b/resources/views/business/pages/courier-payables/dropship-freight/factory.blade.php index aaa4ffc0e..3015c3878 100644 --- a/resources/views/business/pages/courier-payables/dropship-freight/factory.blade.php +++ b/resources/views/business/pages/courier-payables/dropship-freight/factory.blade.php @@ -41,6 +41,16 @@ @endif
+@if (($dfSurchargeSummary ?? collect())->isNotEmpty()) +
+

附加费小汇总

+ + @foreach ($dfSurchargeSummary as $fee)@endforeach +
项目厂家提供金额自算金额差额
{{ $fee->item }}{{ $money($fee->bill) }}{{ $money($fee->self) }}{{ $fee->self === null ? '—' : $money((float)$fee->bill - (float)$fee->self) }}
+
+@endif +@include('business.pages.courier-payables.partials.surcharge-matches', ['surchargeRows' => $dfSurchargeRows ?? null]) +