diff --git a/app/Console/Commands/RefreshCourierSettlement.php b/app/Console/Commands/RefreshCourierSettlement.php new file mode 100644 index 000000000..ffa82ed75 --- /dev/null +++ b/app/Console/Commands/RefreshCourierSettlement.php @@ -0,0 +1,114 @@ +option('all-open') && $this->option('statement') === []) { + $this->error('请选择对账单或 --all-open'); + return self::FAILURE; + } + if (app()->environment('production') && ! env('FINANCE_BATCH_CONTAINER')) { + $this->error('请通过 run-finance-batch.sh 执行'); + return self::FAILURE; + } + Company::findOrFail((int) $this->option('company'))->makeCurrent(true); + $lock = Cache::lock('courier-bills:refresh-settlement', 3900); + if (! $lock->get()) { $this->error('结算刷新正在运行'); return self::FAILURE; } + $started = microtime(true); + $queries = 0; $sqlMs = 0.0; + DB::listen(static function ($query) use (&$queries, &$sqlMs): void { $queries++; $sqlMs += $query->time; }); + $db = CourierBillMatcher::db(); + $folder = 'private/courier-settlement/' . gmdate('Ymd-His') . '-' . bin2hex(random_bytes(4)); + try { + $ids = $db->table('courier_bill_statements')->where('status', '<>', 'confirmed') + ->when(! $this->option('all-open'), fn ($q) => $q->whereIn('id', $this->option('statement'))) + ->where('line_count', '>', 0)->orderBy('id')->pluck('id'); + foreach ($ids as $id) { + $result = $db->transaction(function () use ($db, $id, $matcher, $subsidy, $folder) { + $statement = $db->table('courier_bill_statements')->where('id', $id)->lockForUpdate()->first(); + if (! $statement || $statement->status === 'confirmed') return ['statement' => $id, 'skipped' => true]; + $beforeSummary = $db->table('courier_bill_summary_items')->where('statement_id', $id)->orderBy('id')->get(); + $beforeFees = $db->table('bill_surcharge_matches')->where('scope', 'courier')->where('owner_id', $id)->orderBy('id')->get(); + $stream = null; + if ($this->option('apply')) { + $path = $folder . '/' . $id . '.ndjson'; + Storage::disk('local')->put($path, ''); + $stream = fopen(Storage::disk('local')->path($path), 'wb'); + if (! $stream) throw new \RuntimeException('无法保存备份'); + fwrite($stream, json_encode(['statement' => $statement, 'summary' => $beforeSummary, 'surcharges' => $beforeFees], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR) . "\n"); + } + $changed = 0; $decrease = 0.0; $scanned = 0; + try { + foreach ($db->table('courier_bill_lines')->where('statement_id', $id)->orderBy('id')->lazyById(500) as $line) { + $scanned++; + if ($stream) fwrite($stream, json_encode(['line' => $line], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR) . "\n"); + if ($line->resolution !== null || ! in_array($line->category, [...Category::PAYABLE, Category::PRIOR], true)) continue; + $amount = CourierBillMatcher::selfAmount((string) $line->category, $line->calc_freight === null ? null : (float) $line->calc_freight, $line->bill_amount, $line->resolution); + if (($amount === null) === ($line->self_amount === null) && ($amount === null || abs($amount - (float) $line->self_amount) < 0.00001)) continue; + $changed++; $decrease += (float) $line->self_amount - (float) $amount; + if ($this->option('apply')) $db->table('courier_bill_lines')->where('id', $line->id)->update(['self_amount' => $amount]); + } + } finally { if ($stream) fclose($stream); } + $weight = $subsidy->summary((int) $id); + $existing = $beforeSummary->firstWhere('label', WeightDifferenceSubsidy::LABEL); + $subsidyChanged = ! ($existing?->manual) && abs((float) ($existing?->self_amount ?? 0) - $weight['amount']) > 0.00001; + $feeChanges = 0; $feeDecrease = 0.0; + foreach ($beforeFees as $fee) { + if ($fee->self_amount !== null && $fee->bill_amount !== null && (float) $fee->bill_amount < (float) $fee->self_amount) { + $feeChanges++; $feeDecrease += (float) $fee->self_amount - round((float) $fee->bill_amount, 2); + if ($this->option('apply')) $db->table('bill_surcharge_matches')->where('id', $fee->id)->update([ + 'self_amount' => round((float) $fee->bill_amount, 2), + 'match_note' => $fee->match_note . ';快递提供金额较低,按快递金额结算', + ]); + } + } + if ($this->option('apply') && ($changed > 0 || $subsidyChanged || $feeChanges > 0)) { + $matcher->refreshSummary((int) $id, false); + // 只允许报价核价金额按较低的快递提供金额下调。 + $fields = ['file_id', 'sheet', 'row_no', 'waybill_no', 'item', 'bill_amount', 'self_amount']; + $normalize = static fn ($rows) => $rows->map(fn ($r) => array_intersect_key((array) $r, array_flip($fields)))->sortBy(fn ($r) => json_encode($r))->values()->all(); + $expectedFees = $beforeFees->map(function ($fee) { + $copy = clone $fee; + if ($copy->self_amount !== null && $copy->bill_amount !== null && (float) $copy->bill_amount < (float) $copy->self_amount) $copy->self_amount = number_format((float) $copy->bill_amount, 2, '.', ''); + return $copy; + }); + $afterFees = $db->table('bill_surcharge_matches')->where('scope', 'courier')->where('owner_id', $id)->get(); + if ($normalize($expectedFees) != $normalize($afterFees)) throw new \RuntimeException('附加费来源发生变化,本张账单已回退'); + $protected = static fn ($rows) => $rows->filter(fn ($r) => $r->manual || ($r->label !== WeightDifferenceSubsidy::LABEL + && in_array(SummaryMapper::classify($r->label), ['AL', 'supplement'], true))) + ->map(fn ($r) => [$r->label, $r->bill_amount === null ? null : (float) $r->bill_amount, + $r->self_amount === null ? null : (float) $r->self_amount, (bool) $r->manual]) + ->sortBy(fn ($r) => json_encode($r))->values()->all(); + if ($protected($beforeSummary) != $protected($db->table('courier_bill_summary_items')->where('statement_id', $id)->get())) { + throw new \RuntimeException('人工金额、配件扣款或补记账发生变化,本张账单已回退'); + } + } + return ['statement' => $id, 'month' => $statement->bill_month, 'scanned' => $scanned, + 'changed' => $changed, 'settlement_decrease' => round($decrease, 2), 'weight_subsidy' => $weight, + 'fee_changes' => $feeChanges, 'fee_decrease' => round($feeDecrease, 2), + 'applied' => (bool) $this->option('apply')]; + }); + $this->line(json_encode($result, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR)); + } + $this->info(json_encode(['backup' => $this->option('apply') ? $folder : null, + 'seconds' => round(microtime(true) - $started, 3), 'peak_mib' => round(memory_get_peak_usage(true) / 1048576, 2), + 'queries' => $queries, 'sql_ms' => round($sqlMs, 2)], JSON_UNESCAPED_UNICODE)); + return self::SUCCESS; + } catch (\Throwable $e) { + report($e); $this->error($e->getMessage()); + return self::FAILURE; + } finally { $lock->release(); } + } +} diff --git a/app/Support/CourierBills/CourierBillMatcher.php b/app/Support/CourierBills/CourierBillMatcher.php index 9364517fc..41499dc9c 100644 --- a/app/Support/CourierBills/CourierBillMatcher.php +++ b/app/Support/CourierBills/CourierBillMatcher.php @@ -153,13 +153,14 @@ final class CourierBillMatcher return [Category::DIFF, null]; } - /** 自算金额:处理结果优先;否则一致类和前月补提供按核算运费,其余为 0。 */ + /** 自算金额:处理结果优先;正常应付按快递提供与核算运费较低者结算,缺少核算依据保持空白。 */ public static function selfAmount(string $category, ?float $calcFreight, mixed $billAmount, ?string $resolution): ?float { return match ($resolution) { 'agree' => $billAmount === null ? null : (float) $billAmount, 'exclude', 'defer' => 0.0, - default => in_array($category, [...Category::PAYABLE, Category::PRIOR], true) ? $calcFreight : 0.0, + default => in_array($category, [...Category::PAYABLE, Category::PRIOR], true) + ? ($calcFreight !== null && $billAmount !== null ? min($calcFreight, round((float) $billAmount, 2)) : $calcFreight) : 0.0, }; } @@ -196,7 +197,7 @@ final class CourierBillMatcher * 重建自动小汇总行(手工行保留)。项目名称照财务习惯写,保证归集规则落到正确的列: * 「X月运费」→ 成品;「跨月订单-X月,本月不结算」「快递不符(未匹配本快递发货数据)」→ 匹配不到。 */ - public function refreshSummary(int $statementId): void + public function refreshSummary(int $statementId, bool $refreshSources = true): void { $db = self::db(); $month = (string) $db->table('courier_bill_statements')->where('id', $statementId)->value('bill_month'); @@ -255,17 +256,32 @@ final class CourierBillMatcher } } uasort($items, static fn (array $a, array $b): int => $a['sort'] <=> $b['sort']); - $this->addAccessoryDeduction($statementId, $month, $items); + if ($refreshSources) { + $this->addAccessoryDeduction($statementId, $month, $items); + } else { + // 仅调整结算口径时,沿用已保存的配件扣款和补记账,不重新读取来源。 + foreach ($db->table('courier_bill_summary_items')->where('statement_id', $statementId)->where('manual', false)->get() as $saved) { + if ($saved->label !== WeightDifferenceSubsidy::LABEL && in_array(SummaryMapper::classify($saved->label), ['AL', 'supplement'], true)) { + $items[$saved->label] = ['bill' => $saved->bill_amount, 'self' => $saved->self_amount, 'sort' => $saved->sort]; + $kinds[$saved->label] = 'saved'; + } + } + } $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(); + $subsidy = app(WeightDifferenceSubsidy::class)->summary($statementId); + if ($subsidy['count'] > 0 && ! isset($manualLabels[WeightDifferenceSubsidy::LABEL])) { + $items[WeightDifferenceSubsidy::LABEL] = ['bill' => null, 'self' => $subsidy['amount'], 'sort' => 9200]; + $kinds[WeightDifferenceSubsidy::LABEL] = 'weight-subsidy'; + } $kinds['配件补发扣款'] = 'accessory'; $surchargeMatcher=app(SurchargeSettlementMatcher::class); - $surchargeMatcher->courier($statementId); + if ($refreshSources) $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); + if ($refreshSources) $this->addRebooks($statementId, $template, $manualLabels, $items, $kinds); $sort = 8000; foreach ($fees as $item => $sum) { if (($template !== null || ! isset($manualLabels[$item])) && ! isset($items[$item])) { @@ -301,7 +317,7 @@ final class CourierBillMatcher foreach ($items as $name => $item) { $db->table('courier_bill_summary_items')->insert([ 'statement_id' => $statementId, 'label' => $name, 'bill_amount' => $item['bill'] === null ? null : round($item['bill'], 4), - 'self_amount' => round($item['self'], 2), 'manual' => false, 'sort' => ++$sort, + 'self_amount' => $item['self'] === null ? null : round($item['self'], 2), 'manual' => false, 'sort' => ++$sort, ]); } } diff --git a/app/Support/CourierBills/StatementExporter.php b/app/Support/CourierBills/StatementExporter.php index 75df8ebe9..21059e9c4 100644 --- a/app/Support/CourierBills/StatementExporter.php +++ b/app/Support/CourierBills/StatementExporter.php @@ -109,7 +109,7 @@ final class StatementExporter [$sources, $original] = $this->originalHeaders($ids); $rest = array_diff_key(ShippingLookup::COLUMNS, array_flip(array_filter(self::FRONT, static fn ($f) => $f[0] !== '_'))); - $fullHeader = [...$original, ...array_keys(self::FRONT), ...array_values($rest), '差异原因', '处理结果', ...$tail]; + $fullHeader = [...$original, ...array_keys(self::FRONT), ...array_values($rest), '结算运费', '差异原因', '处理结果', ...$tail]; // 原始账单:底文件原封不动;第 2 个及以后的文件按值复制 $originals = $this->writeOriginal($book, $files, $baseFileId); @@ -138,6 +138,7 @@ final class StatementExporter foreach (array_keys($rest) as $field) { $cells[] = self::value($field, $ship[$field] ?? null); } + $cells[] = $line->self_amount === null ? null : (float) $line->self_amount; $cells[] = CourierBillMatcher::diffReason((string) $line->category, $line->bill_weight, $line->charge_weight); $cells[] = Category::RESOLUTIONS[$line->resolution] ?? null; $book->row($name, [...$cells, ...$groupCell($line)]); @@ -180,6 +181,21 @@ final class StatementExporter }); $this->writeRebooks($book, $ids, $tail, $groupNames, $multi); + $subsidy = app(WeightDifferenceSubsidy::class); + foreach ($ids as $id) { + if (! $db->table('courier_bill_summary_items')->where('statement_id', $id)->where('label', WeightDifferenceSubsidy::LABEL)->where('manual', false)->exists()) continue; + $summary = $subsidy->summary($id); + if ($summary['count'] === 0) continue; + $sheet = '重量差补款-' . $id; + $book->row($sheet, ['快递单号', '快递重量', '我方计费重量', '重量差(快递-我方)', '快递运费', '核算运费', '可补运费差额'], true); + foreach ($subsidy->query($id)->orderBy('id')->lazyById(500) as $line) { + $book->row($sheet, [$line->waybill_no, (float) $line->bill_weight, (float) $line->charge_weight, + round((float) $line->bill_weight - (float) $line->charge_weight, 4), (float) $line->bill_amount, + (float) $line->calc_freight, round((float) $line->bill_amount - (float) $line->calc_freight, 4)]); + } + $book->row($sheet, ['差额合计', null, null, null, null, null, $summary['difference']], true); + $book->row($sheet, ['差额合计×50%,补给快递', null, null, null, null, null, $summary['amount']], true); + } 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/SummaryTemplate.php b/app/Support/CourierBills/SummaryTemplate.php index 08018456f..224bc9e05 100644 --- a/app/Support/CourierBills/SummaryTemplate.php +++ b/app/Support/CourierBills/SummaryTemplate.php @@ -52,7 +52,7 @@ final class SummaryTemplate $index = []; foreach ($template as $label) { $key = self::normalize($label); - if ($key === '') { + if ($key === '' || ($key === WeightDifferenceSubsidy::LABEL && ! isset($auto[$key]))) { continue; } // 手工小汇总里同名的行可以有两行(如一正一负的车费),都留着;系统金额只填第一行 @@ -97,7 +97,7 @@ final class SummaryTemplate $result = []; foreach ($labels as $label) { $label = trim((string) $label); - if ($label !== '' && ! preg_match(self::TRANSIENT, $label)) { + if ($label !== '' && $label !== WeightDifferenceSubsidy::LABEL && ! preg_match(self::TRANSIENT, $label)) { $result[] = self::roll($label, $delta); } } diff --git a/app/Support/CourierBills/SurchargeSettlementMatcher.php b/app/Support/CourierBills/SurchargeSettlementMatcher.php index bfee608ac..5d32a9fbe 100644 --- a/app/Support/CourierBills/SurchargeSettlementMatcher.php +++ b/app/Support/CourierBills/SurchargeSettlementMatcher.php @@ -208,6 +208,10 @@ class SurchargeSettlementMatcher $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))))); } diff --git a/app/Support/CourierBills/WeightDifferenceSubsidy.php b/app/Support/CourierBills/WeightDifferenceSubsidy.php new file mode 100644 index 000000000..7ef51fefa --- /dev/null +++ b/app/Support/CourierBills/WeightDifferenceSubsidy.php @@ -0,0 +1,29 @@ +table('courier_bill_lines') + ->where('statement_id', $statementId)->where('express_name', '武进韵达') + ->whereIn('category', [...Category::PAYABLE, Category::PRIOR])->whereNull('resolution') + ->whereRaw('bill_weight - charge_weight > 1') + ->whereColumn('bill_amount', '>', 'calc_freight'); + } + + /** 按差额合计计算一半,再四舍五入到分,避免逐行四舍五入累积误差。 */ + public function summary(int $statementId): array + { + $sum = $this->query($statementId)->selectRaw('COUNT(*) AS n, SUM(bill_amount - calc_freight) AS difference')->first(); + + return ['count' => (int) $sum->n, 'difference' => round((float) $sum->difference, 4), + 'amount' => round((float) $sum->difference / 2, 2)]; + } +} diff --git a/deploy/finance-batch-imports.json b/deploy/finance-batch-imports.json index bc261415c..5de45e5d4 100644 --- a/deploy/finance-batch-imports.json +++ b/deploy/finance-batch-imports.json @@ -1,5 +1,6 @@ [ "courier-bills:match-reverse", + "courier-bills:refresh-settlement", "portal-freight:import-pending", "courier-surcharge:match-bills", "planting-reimbursement:auto-confirm", diff --git a/deploy/run-finance-batch.sh b/deploy/run-finance-batch.sh index 10324440a..26c063756 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|courier-surcharge:match-bills|courier-bills:match-reverse) is_import=1 ;; + portal-freight:import-pending|courier-surcharge:match-bills|courier-bills:match-reverse|courier-bills:refresh-settlement) 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/resources/views/business/pages/courier-payables/courier-bills/details.blade.php b/resources/views/business/pages/courier-payables/courier-bills/details.blade.php index 973f49240..7ab59c0d2 100644 --- a/resources/views/business/pages/courier-payables/courier-bills/details.blade.php +++ b/resources/views/business/pages/courier-payables/courier-bills/details.blade.php @@ -63,4 +63,4 @@ 共 {{ number_format($cbLines->total()) }} 条,每页 50 条 {{ $cbLines->links('business.partials.previous-next-pagination') }} -
处理结果:同意付款 = 自算金额取快递金额;已与快递确认剔除 / 转下月 = 本月自算金额为 0。改完对应对账单的小汇总和快递应付汇总自动重算。
+正常应付运费取快递提供与我方核算的较低金额。处理结果:同意付款 = 自算金额取快递金额;已与快递确认剔除 / 转下月 = 本月自算金额为 0。武进韵达重量多报超过1公斤的正向运费差额,合计后补50%,在小汇总单列。改完对应对账单的小汇总和快递应付汇总自动重算。
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 4ef734baa..a7b34d025 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 @@ -47,6 +47,7 @@正常应付运费与已核价附加费取快递提供和我方核算的较低金额,已有手工处理优先。武进韵达:快递重量超过我方计费重量1公斤的单据,快递多报的运费差额合计的50%单列补给快递。
| 项目 | 快递提供金额 | 自算金额 | 差异 | 归到汇总列 |
|---|
| {{ $label }} | @endforeach
|---|