diff --git a/app/Console/Commands/BackfillDropshipBillWeights.php b/app/Console/Commands/BackfillDropshipBillWeights.php new file mode 100644 index 000000000..7f300505b --- /dev/null +++ b/app/Console/Commands/BackfillDropshipBillWeights.php @@ -0,0 +1,76 @@ +option('all') && $this->option('file') === []) { + $this->error('请选择 --file 或 --all'); return self::FAILURE; + } + if (app()->environment('production') && ! env('FINANCE_BATCH_CONTAINER')) { + $this->error('请通过 run-finance-batch.sh 执行'); return self::FAILURE; + } + $company = (int) $this->option('company'); Company::findOrFail($company)->makeCurrent(true); + $lock = Cache::lock('dropship-freight:backfill-weights', 3900); + if (! $lock->get()) { $this->error('重量回补正在执行'); return self::FAILURE; } + $db = DB::connection('business_mirror'); $started = microtime(true); $queries = 0; $sqlMs = 0; + DB::listen(static function ($q) use (&$queries, &$sqlMs) { $queries++; $sqlMs += $q->time; }); + $folder = 'private/dropship-weight/' . gmdate('Ymd-His') . '-' . bin2hex(random_bytes(4)); + try { + foreach ($db->table('dropship_bill_files')->where('status', 'parsed')->whereNotNull('factory_id') + ->when(! $this->option('all'), fn ($q) => $q->whereIn('id', $this->option('file')))->orderBy('id')->lazyById(20) as $file) { + if (($confirmation->state($file->bill_month, $file->factory_id, $company)['status'] ?? '') === 'confirmed') { + $this->line(json_encode(['file' => $file->id, 'skipped' => '厂家已确认'], JSON_UNESCAPED_UNICODE)); continue; + } + $path = Storage::disk('local')->path($file->stored_path); + if (! is_file($path)) throw new \RuntimeException('原件缺失:' . $file->id); + $parsed = $parser->parse($path, pathinfo($path, PATHINFO_EXTENSION))['lines']; + $report = $db->transaction(function () use ($db, $file, $parsed, $folder, $confirmation, $company) { + $db->table('dropship_bill_files')->where('id', $file->id)->lockForUpdate()->first(); + if (($confirmation->state($file->bill_month, $file->factory_id, $company)['status'] ?? '') === 'confirmed') { + return ['file' => $file->id, 'skipped' => '厂家已确认']; + } + $stream = null; $scanned = $filled = $missing = $mismatched = 0; + if ($this->option('apply')) { + Storage::disk('local')->put($folder . '/' . $file->id . '.ndjson', ''); + $stream = fopen(Storage::disk('local')->path($folder . '/' . $file->id . '.ndjson'), 'wb'); + if (! $stream) throw new \RuntimeException('无法创建备份'); + fwrite($stream, json_encode(['file' => $file], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR) . "\n"); + } + try { + foreach ($db->table('dropship_bill_lines')->where('file_id', $file->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->bill_weight !== null) continue; + $source = $parsed[$line->waybill_no] ?? null; + if ($source === null || mb_substr($source['sheet'], 0, 64) !== $line->sheet || $source['row'] !== $line->row_no + || abs($source['amount'] - (float) $line->amount) > 0.0001) { $mismatched++; continue; } + if ($source['weight'] === null) { $missing++; continue; } + $filled++; + if ($this->option('apply')) $db->table('dropship_bill_lines')->where('id', $line->id)->whereNull('bill_weight') + ->update(['bill_weight' => $source['weight']]); + } + } finally { if ($stream) fclose($stream); } + return ['file' => $file->id, 'month' => $file->bill_month, 'factory' => $file->factory_id, + 'scanned' => $scanned, 'filled' => $filled, 'missing' => $missing, 'mismatched' => $mismatched, 'applied' => (bool) $this->option('apply')]; + }); + unset($parsed); $this->line(json_encode($report, 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' => memory_get_peak_usage(true) / 1048576, '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/Http/Controllers/Business/DropshipFreightController.php b/app/Http/Controllers/Business/DropshipFreightController.php index cf3eb4a09..c7aaaebca 100644 --- a/app/Http/Controllers/Business/DropshipFreightController.php +++ b/app/Http/Controllers/Business/DropshipFreightController.php @@ -96,6 +96,9 @@ final class DropshipFreightController extends Controller $result = $this->reconciler->factoryMonth($factory, $month); $status = (string) $request->query('status', ''); $rows = $result['rows']; + if (in_array($status, ['weight_diff', 'price_diff', 'missing_weight'], true)) { + $rows = array_values(array_filter($rows, static fn (array $r): bool => $r['diff_kind'] === $status)); + } $state = $this->confirmations->state($month, (int) $factory->id, self::companyId()); $disputes = $this->confirmations->disputes($month, (int) $factory->id, self::companyId()); $currentDisputes = array_values(array_filter($disputes, fn ($d) => (int) $d['version'] === (int) ($state['version'] ?? 0))); diff --git a/app/Support/DropshipFreight/DropshipExporter.php b/app/Support/DropshipFreight/DropshipExporter.php index 48948369f..0f43acf02 100644 --- a/app/Support/DropshipFreight/DropshipExporter.php +++ b/app/Support/DropshipFreight/DropshipExporter.php @@ -320,6 +320,7 @@ final class DropshipExporter { $result = []; foreach (StatementExporter::FRONT as $label => $field) { + if ($field === 'qc_charge_weight') $result['厂家重量(kg)'] = '_bill_weight'; $result[$label] = $field; if ($field === 'qc_freight') { $result['最终结算运费'] = '_final'; @@ -334,7 +335,9 @@ final class DropshipExporter return match ($field) { '_measured' => $ship['qc_measured_weight'] ?? null, '_unshipped' => null, - '_weight_diff' => null, + '_bill_weight' => $r['bill_weight'], + 'qc_charge_weight' => $r['charge_weight'], + '_weight_diff' => $r['weight_diff'], '_final' => $r['final'] ?? $r['settle'] ?? null, // 运费差 = 厂家运费 − 最终结算运费 '_freight_diff' => $r['bill'] !== null && ($r['final'] ?? $r['settle'] ?? null) !== null diff --git a/app/Support/DropshipFreight/DropshipFreightStore.php b/app/Support/DropshipFreight/DropshipFreightStore.php index 0971bc50e..bc65f3f60 100644 --- a/app/Support/DropshipFreight/DropshipFreightStore.php +++ b/app/Support/DropshipFreight/DropshipFreightStore.php @@ -436,7 +436,7 @@ final class DropshipFreightStore $insert = []; foreach ($chunk as $waybill => $line) { $insert[] = ['file_id' => $fileId, 'factory_id' => $factoryId, 'bill_month' => $file->bill_month, 'waybill_no' => (string) $waybill, - 'amount' => $line['amount'], 'sheet' => mb_substr($line['sheet'], 0, 64), 'row_no' => $line['row']]; + 'amount' => $line['amount'], 'bill_weight' => $line['weight'], 'sheet' => mb_substr($line['sheet'], 0, 64), 'row_no' => $line['row']]; } $db->table('dropship_bill_lines')->insert($insert); } diff --git a/app/Support/DropshipFreight/DropshipReconciler.php b/app/Support/DropshipFreight/DropshipReconciler.php index b9398b34f..b949138b4 100644 --- a/app/Support/DropshipFreight/DropshipReconciler.php +++ b/app/Support/DropshipFreight/DropshipReconciler.php @@ -48,10 +48,12 @@ final class DropshipReconciler { $own = array_flip($own ?? $this->store->ownExpressNames()); $keywords = DropshipFreightStore::splitKeywords((string) $factory->keywords); - $columns = $withSources ? ['waybill_no', 'amount', 'file_id', 'sheet', 'row_no'] : ['waybill_no', 'amount']; + $columns = $withSources ? ['waybill_no', 'amount', 'bill_weight', 'file_id', 'sheet', 'row_no'] : ['waybill_no', 'amount', 'bill_weight']; $lines = $this->store->db()->table('dropship_bill_lines')->where('factory_id', $factory->id)->where('bill_month', $month) ->orderBy('id')->get($columns)->groupBy('waybill_no'); $bill = $lines->map(static fn ($rows): float => round((float) $rows->sum('amount'), 2))->all(); + $weights = $lines->map(static fn ($rows): ?float => $rows->contains(fn ($r) => $r->bill_weight === null) + ? null : round((float) $rows->sum('bill_weight'), 4))->all(); $sources = $withSources ? $lines->map(static fn ($rows): array => ['file_id' => (int) $rows->first()->file_id, 'sheet' => (string) $rows->first()->sheet, 'row_no' => (int) $rows->first()->row_no])->all() : []; unset($lines); @@ -114,7 +116,7 @@ final class DropshipReconciler $note = '换单:实际发出 ' . $swap . '(' . ($i['express'] ?? '无快递名称1') . ')' . ($note !== null ? ';' . $note : '') . ($i === null ? ';新单号发货数据里也查不到' : ''); } - $rows[] = self::row($waybill, $i, $bill[$waybill], $category, $categoryMonth, $note) + ($sources[$waybill] ?? []) + $rows[] = self::row($waybill, $i, $bill[$waybill], $category, $categoryMonth, $note, $weights[$waybill]) + ($sources[$waybill] ?? []) + ['ship_waybill' => $swap ?? $waybill]; } $system = array_values(array_filter($system, static fn (string $w): bool => ! isset($covered[$w]))); @@ -133,13 +135,17 @@ final class DropshipReconciler ? Category::label($status, $month) : (self::LABELS[$status] ?? $status); } - private static function row(string $waybill, ?array $i, ?float $billed, string $status, ?string $statusMonth, ?string $note): array + private static function row(string $waybill, ?array $i, ?float $billed, string $status, ?string $statusMonth, ?string $note, ?float $billWeight = null): array { $calc = $i['calc'] ?? null; $settle = in_array($status, self::PAYABLE, true) ? $calc : null; + $chargeWeight = $i['charge_weight'] ?? null; + $weightDiff = $billWeight !== null && $chargeWeight !== null ? round($billWeight - $chargeWeight, 4) : null; return ['waybill' => $waybill, 'ship_time' => $i['ship_time'] ?? null, 'express' => $i['express'] ?? null, 'warehouse' => $i['warehouse'] ?? null, 'bill' => $billed, 'calc' => $calc, + 'bill_weight' => $billWeight, 'charge_weight' => $chargeWeight, 'weight_diff' => $weightDiff, + 'diff_kind' => $status !== Category::DIFF ? null : ($weightDiff === null ? 'missing_weight' : (abs($weightDiff) > 0.005 ? 'weight_diff' : 'price_diff')), 'settle' => $settle, 'final' => self::final($billed, $settle), 'diff' => $billed !== null && $calc !== null ? round($billed - $calc, 2) : null, 'status' => $status, 'status_month' => $statusMonth, 'label' => self::label($status, $statusMonth), @@ -158,6 +164,7 @@ final class DropshipReconciler $counts = array_fill_keys(array_keys(self::LABELS), 0); $bill = $settle = $calcSettle = 0.0; $billedCount = $over = $under = $capped = 0; + $diffCounts = ['weight_diff' => 0, 'price_diff' => 0, 'missing_weight' => 0]; foreach ($rows as $row) { $counts[$row['status']]++; if ($row['bill'] !== null) { @@ -172,6 +179,7 @@ final class DropshipReconciler } if ($row['status'] === Category::DIFF) { $row['diff'] > 0 ? $over++ : $under++; + $diffCounts[$row['diff_kind'] ?? 'missing_weight']++; } } @@ -180,7 +188,7 @@ final class DropshipReconciler 'keywords' => $factory->keywords, 'billed' => $billedCount, 'bill' => round($bill, 2), 'settle' => round($settle, 2), 'calc_settle' => round($calcSettle, 2), 'capped' => $capped, 'diff' => round($bill - $settle, 2), 'counts' => $counts, 'over' => $over, 'under' => $under, - 'attention' => array_sum(array_intersect_key($counts, array_flip(self::ATTENTION)))]; + 'diff_counts' => $diffCounts, 'attention' => array_sum(array_intersect_key($counts, array_flip(self::ATTENTION)))]; } public static function matches(string $express, array $keywords): bool @@ -271,9 +279,15 @@ final class DropshipReconciler } foreach ($sources as $key => $set) { $total = 0.0; + $weight = 0.0; $weightComplete = true; $ok = true; $status = null; $formulas = []; + foreach (array_keys($set) as $source) { + $freight = $freights[$source] ?? null; + if ($freight === null || $freight->charge_weight === null) $weightComplete = false; + else $weight += (float) $freight->charge_weight; + } foreach (array_keys($set) as $source) { $freight = $freights[$source] ?? null; if ($freight === null || strtoupper((string) $freight->status) !== 'OK' || $freight->freight === null) { @@ -287,6 +301,7 @@ final class DropshipReconciler } } $result[$key]['calc'] = $ok ? round($total, 2) : null; + $result[$key]['charge_weight'] = $weightComplete ? round($weight, 4) : null; $result[$key]['calc_status'] = $ok ? null : $status; $result[$key]['formula'] = $formulas === [] ? null : implode(';', $formulas); } diff --git a/app/Support/DropshipFreight/FactoryBillParser.php b/app/Support/DropshipFreight/FactoryBillParser.php index 30faa6ed0..354d0d270 100644 --- a/app/Support/DropshipFreight/FactoryBillParser.php +++ b/app/Support/DropshipFreight/FactoryBillParser.php @@ -22,6 +22,7 @@ final class FactoryBillParser public const AMOUNT_HEADERS = ['快递运费', '运费', '快递费', '运费金额', '快递费用', '邮费', '快递']; /** 偏远地区单独一列的运费(浩浦等),和运费列相加。 */ public const EXTRA_AMOUNT_HEADERS = ['偏远', '偏远费', '偏远运费', '偏远加收']; + public const WEIGHT_HEADERS = ['计费重量', '结算重量', '厂家重量', '重量', '实际重量']; /** 表名含这些字的不读:货款/记账/退货/拦截/附加费,以及我方自己做的对账表。 */ public const SKIP_SHEET_WORDS = ['记账', '退货', '退回', '拦截', '附加', '违约', '汇总', '入库', '入仓', '报价', '对账', '我代', '我入', '我退', '少算', '未发出', '补款', '补件', '赔']; @@ -32,7 +33,7 @@ final class FactoryBillParser public function __construct(private readonly BillWorkbookReader $reader) {} /** - * @return array{lines:array,sheets:list} + * @return array{lines:array,sheets:list} */ public function parse(string $path, string $extension): array { @@ -71,8 +72,11 @@ final class FactoryBillParser if ($waybill === null || $amount === null) { continue; } - $mine[$waybill] ??= ['amount' => 0.0, 'sheet' => $sheet, 'row' => (int) $rowNumber]; + $mine[$waybill] ??= ['amount' => 0.0, 'weight' => 0.0, 'weight_complete' => true, 'sheet' => $sheet, 'row' => (int) $rowNumber]; $mine[$waybill]['amount'] += $amount; + $weight = $columns['weight'] === null ? null : BillParser::number($row[$columns['weight']] ?? null); + if ($weight === null || $weight < 0) $mine[$waybill]['weight_complete'] = false; + else $mine[$waybill]['weight'] += $weight; } if ($columns === null) { $sheets[] = ['sheet' => $sheet, 'read' => false, 'note' => '没有同时找到单号列和运费列']; @@ -83,6 +87,8 @@ final class FactoryBillParser $repeated = 0; foreach ($mine as $waybill => $line) { $line['amount'] = round($line['amount'], 2); + $line['weight'] = $line['weight_complete'] ? round($line['weight'], 4) : null; + unset($line['weight_complete']); if (abs($line['amount']) < 0.005) { continue; } @@ -97,6 +103,7 @@ final class FactoryBillParser $sheets[] = ['sheet' => $sheet, 'read' => true, 'rows' => $count, 'amount' => round($total, 2), 'note' => '单号列「' . $columns['waybill_header'] . '」、运费列「' . $columns['amount_header'] . '」' . ($columns['extra'] !== [] ? '(加上「' . implode('」「', array_map(static fn (int $i): string => $columns['headers'][$i], $columns['extra'])) . '」)' : '') + . ($columns['weight'] !== null ? ';重量列「' . $columns['headers'][$columns['weight']] . '」' : ';未提供重量列') . ($repeated > 0 ? ';' . $repeated . ' 个单号前面的表已有,没重复算' : '')]; } @@ -116,7 +123,7 @@ final class FactoryBillParser /** * @param array $row - * @return array{waybill:int,amount:int,extra:list,headers:list,waybill_header:string,amount_header:string}|null + * @return array{waybill:int,amount:int,weight:?int,extra:list,headers:list,waybill_header:string,amount_header:string}|null */ public static function findColumns(array $row): ?array { @@ -169,7 +176,14 @@ final class FactoryBillParser } } - return ['waybill' => $waybill, 'amount' => $amount, 'extra' => $extra, 'headers' => array_values($headers), + $weight = null; + foreach (self::WEIGHT_HEADERS as $candidate) { + foreach ($headers as $index => $header) { + $base = preg_replace('/[((]?(?:kg|公斤|千克)[))]?$/iu', '', $header); + if ($base === $candidate) { $weight = (int) $index; break 2; } + } + } + return ['waybill' => $waybill, 'amount' => $amount, 'weight' => $weight, 'extra' => $extra, 'headers' => array_values($headers), 'waybill_header' => $headers[$waybill], 'amount_header' => $headers[$amount]]; } diff --git a/database/migrations/2026_12_06_150000_add_dropship_bill_weight.php b/database/migrations/2026_12_06_150000_add_dropship_bill_weight.php new file mode 100644 index 000000000..61527c88f --- /dev/null +++ b/database/migrations/2026_12_06_150000_add_dropship_bill_weight.php @@ -0,0 +1,19 @@ +table('dropship_bill_lines', function (Blueprint $table): void { + $table->decimal('bill_weight', 14, 4)->nullable()->comment('厂家账单重量kg,同单多行合计,缺失不填零'); + }); + } + + public function down(): void + { + // 保留已回补的厂家重量,应用版本回退不删除业务数据。 + } +}; diff --git a/database/migrations/2026_12_06_150100_index_dropship_shipping_lookup.php b/database/migrations/2026_12_06_150100_index_dropship_shipping_lookup.php new file mode 100644 index 000000000..5a0ade7a4 --- /dev/null +++ b/database/migrations/2026_12_06_150100_index_dropship_shipping_lookup.php @@ -0,0 +1,27 @@ +getDriverName() === 'mysql') { + $connection->statement('ALTER TABLE jst_oms_shipping ADD INDEX jst_shipping_warehouse_time (warehouse_name, ship_time), ADD INDEX jst_shipping_front_no (front_no), ALGORITHM=INPLACE, LOCK=NONE'); + return; + } + $schema->table('jst_oms_shipping', function (Blueprint $table): void { + $table->index(['warehouse_name', 'ship_time'], 'jst_shipping_warehouse_time'); + $table->index('front_no', 'jst_shipping_front_no'); + }); + } + + public function down(): void + { + // 只读查询索引向后兼容,回退应用不重建大表。 + } +}; diff --git a/deploy/finance-batch-imports.json b/deploy/finance-batch-imports.json index 5de45e5d4..87a4aa3b8 100644 --- a/deploy/finance-batch-imports.json +++ b/deploy/finance-batch-imports.json @@ -1,4 +1,5 @@ [ + "dropship-freight:backfill-weights", "courier-bills:match-reverse", "courier-bills:refresh-settlement", "portal-freight:import-pending", diff --git a/deploy/run-finance-batch.sh b/deploy/run-finance-batch.sh index 26c063756..0d8bb65e9 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|courier-bills:refresh-settlement) is_import=1 ;; + portal-freight:import-pending|courier-surcharge:match-bills|courier-bills:match-reverse|courier-bills:refresh-settlement|dropship-freight:backfill-weights) 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/dropship-freight/factory.blade.php b/resources/views/business/pages/courier-payables/dropship-freight/factory.blade.php index 0489c369b..bcc0b0758 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 @@ -62,9 +62,11 @@ $feedbackPageFor = function (string $waybill) use ($dfCurrentDisputes): int { + +

重量差 = 厂家账单重量 − 我方计费重量(公斤)。运费有差时,重量相同归价格差;任一重量缺失归重量待补充。差异分类不改变结算金额。

逐单核算明细

-
-@forelse($dfLines as $r)@empty@endforelse +
快递单号发货 / 快递厂家运费我方核算最终结算差额分类 / 说明厂家反馈
{{ $r['waybill'] }}{{ $r['ship_time'] }}
{{ $r['express'] }}
{{ $money($r['bill']) }}{{ $money($r['calc']) }}{{ $money($r['final']??$r['settle']) }}{{ $r['bill']===null?'':$money($r['bill']-(float)($r['final']??$r['settle'])) }}{{ $r['label'] }}
{{ $r['note'] }}
@if(isset($dfDisputeMap[$r['waybill']])){{ isset($dfDisputeMap[$r['waybill']]['decision'])?'查看处理':'待处理异议' }}@else—@endif
当前筛选没有明细。
+@forelse($dfLines as $r)@foreach(['bill_weight','charge_weight','weight_diff'] as $weightKey)@endforeach@empty@endforelse
快递单号发货 / 快递厂家重量(kg)我方计费重量(kg)重量差(kg)厂家运费我方核算最终结算差额分类 / 说明厂家反馈
{{ $r['waybill'] }}{{ $r['ship_time'] }}
{{ $r['express'] }}
{{ $r[$weightKey]===null?'—':rtrim(rtrim(number_format($r[$weightKey],4,'.',''),'0'),'.') }}{{ $money($r['bill']) }}{{ $money($r['calc']) }}{{ $money($r['final']??$r['settle']) }}{{ $r['bill']===null?'':$money($r['bill']-(float)($r['final']??$r['settle'])) }}{{ $r['label'] }}@if($r['diff_kind'])
{{ ['weight_diff'=>'重量差','price_diff'=>'价格差','missing_weight'=>'重量待补充'][$r['diff_kind']] }}
@endif
{{ $r['note'] }}
@if(isset($dfDisputeMap[$r['waybill']])){{ isset($dfDisputeMap[$r['waybill']]['decision'])?'查看处理':'待处理异议' }}@else—@endif
当前筛选没有明细。
{{ $dfLines->links() }}
@if(($dfSurchargeSummary??collect())->isNotEmpty())

附加费核对

@foreach($dfSurchargeSummary as $fee)@endforeach
项目厂家金额自算金额
{{ $fee->item }}{{ $money($fee->bill) }}{{ $money($fee->self) }}
@endif @include('business.pages.courier-payables.partials.surcharge-matches',['surchargeRows'=>$dfSurchargeRows??null]) diff --git a/tests/Feature/Business/DropshipWeightTest.php b/tests/Feature/Business/DropshipWeightTest.php new file mode 100644 index 000000000..72aadad7f --- /dev/null +++ b/tests/Feature/Business/DropshipWeightTest.php @@ -0,0 +1,101 @@ +parse($path, 'csv')['lines']; + $this->assertEquals(11, $rows['WB0001']['amount']); + $this->assertEquals(5, $rows['WB0001']['weight']); + $this->assertNull($rows['WB0002']['weight']); + $this->assertSame(0.0, $rows['WB0003']['weight']); + $this->assertNull($rows['WB0004']['weight']); + $this->assertNull(FactoryBillParser::findColumns(['单号','运费','我方计费重量','重量差'])['weight']); + } finally { @unlink($path); } + } + + public function test_weight_difference_uses_unique_packages_and_is_visible_in_page_filter_and_export(): void + { + Storage::fake('local'); $store=app(DropshipFreightStore::class); $db=$store->db(); + $id=$store->saveFactory(null,['name'=>'重量测试','warehouse'=>'测试代发仓','keywords'=>'测试']); + $path=tempnam(sys_get_temp_dir(),'weights').'.xlsx';$book=new StreamingWorkbook(); + $book->row('账单',['单号','运费','重量'],true); + foreach([['WB0001',12,5],['WB0002',12,3],['WB0003',8,null],['OLD4',12,2],['WB0005',12,1]] as $row)$book->row('账单',$row); + $handle=fopen($path,'wb');$book->writeTo($handle);fclose($handle); + try { + $file=$store->upload([new UploadedFile($path,'重量测试.xlsx',null,null,true)],'2026-11','测试')[0]; + $shipping=app(ShippingLookup::class)->connection(); + foreach([['WB0001',1,2,5],['WB0001',1,2,5],['WB0001',2,1,5],['WB0002',3,3,10],['WB0003',4,3,10],['NEWB0004',5,2,10],['WB0005',6,3,10]] as $n=>[$no,$source,$weight,$amount]) { + $shipping->table('jst_oms_shipping')->insert(['express_no'=>$no,'source_id'=>$source,'sku_source_id'=>$n+1,'warehouse_name'=>'测试代发仓','express_name1'=>'测试快递','ship_time'=>'2026-11-03 09:00:00','front_no'=>$no==='NEWB0004'?'OLD4':null]); + $shipping->table('jst_oms_shipping_freight')->updateOrInsert(['source_id'=>$source],['charge_weight'=>$weight,'freight'=>$amount,'status'=>'OK']); + } + $factory=collect($store->factories())->firstWhere('id',$id);$result=app(DropshipReconciler::class)->factoryMonth($factory,'2026-11'); + $rows=collect($result['rows'])->keyBy('waybill'); + $this->assertEquals(3,$rows['WB0001']['charge_weight']); + $this->assertEquals(2,$rows['WB0001']['weight_diff']); + $this->assertSame('price_diff',$rows['WB0002']['diff_kind']); + $this->assertSame('missing_weight',$rows['WB0003']['diff_kind']); + $this->assertNull($rows['WB0003']['weight_diff']); + $this->assertEquals(0,$rows['OLD4']['weight_diff']); + $this->assertEquals(-2,$rows['WB0005']['weight_diff']); + $this->assertEquals(48,$result['summary']['settle']); + $this->assertSame(['weight_diff'=>2,'price_diff'=>2,'missing_weight'=>1],$result['summary']['diff_counts']); + $this->user->attachPermission(\App\Models\Auth\Permission::where('name','read-admin-panel')->firstOrFail()); + $this->loginAs(); + $url=route('business.pages.show',['section'=>'courier-payables','page'=>DropshipFreightController::PAGE,'df_view'=>'factory','factory'=>$id,'month'=>'2026-11','status'=>'weight_diff']); + $this->get($url)->assertOk()->assertSeeText('厂家重量(kg)')->assertSeeText('重量差(kg)')->assertSeeText('WB0001')->assertSeeText('WB0005')->assertDontSeeText('WB0002'); + $out=tempnam(sys_get_temp_dir(),'weight-export');$handle=fopen($out,'wb'); + try{app(DropshipExporter::class)->export($factory,'2026-11',$handle);}finally{fclose($handle);} + try{ + $export=IOFactory::load($out);$grid=$export->getSheetByName('对账')->toArray(null,false,false);$headers=array_shift($grid);$weightCol=array_search('重量差',$headers,true);$wbCol=array_search('快递单号',$headers,true); + $w1=collect($grid)->first(fn($r)=>$r[$wbCol]==='WB0001');$this->assertEquals(2,$w1[$weightCol]); + $this->assertNotFalse(array_search('厂家重量(kg)',$headers,true));$export->disconnectWorksheets(); + }finally{@unlink($out);} + $this->assertEquals(5,$db->table('dropship_bill_lines')->where('file_id',$file)->where('waybill_no','WB0001')->value('bill_weight')); + } finally {@unlink($path);} + } + + public function test_backfill_preserves_amounts_and_skips_changed_source_and_is_idempotent(): void + { + Storage::fake('local');$store=app(DropshipFreightStore::class);$db=$store->db(); + $store->saveFactory(null,['name'=>'重量测试','warehouse'=>'测试代发仓','keywords'=>'测试']); + $csv="单号,运费,重量\n";for($i=0;$i<1001;$i++)$csv.="BACK{$i},8,3\n"; + $file=$store->upload([UploadedFile::fake()->createWithContent('重量测试.csv',$csv)],'2026-11','测试')[0]; + $db->table('dropship_bill_lines')->where('file_id',$file)->update(['bill_weight'=>null]); + $db->table('dropship_bill_lines')->where('waybill_no','BACK0')->update(['amount'=>9]); + $this->artisan('dropship-freight:backfill-weights',['--all'=>true])->assertSuccessful(); + $this->assertSame(0,$db->table('dropship_bill_lines')->whereNotNull('bill_weight')->count()); + $this->artisan('dropship-freight:backfill-weights',['--all'=>true,'--apply'=>true])->assertSuccessful(); + $this->assertSame(1000,$db->table('dropship_bill_lines')->whereNotNull('bill_weight')->count()); + $this->assertEquals(8009,$db->table('dropship_bill_lines')->sum('amount')); + $this->assertNull($db->table('dropship_bill_lines')->where('waybill_no','BACK0')->value('bill_weight')); + $this->assertNotEmpty(Storage::disk('local')->allFiles('private/dropship-weight')); + $this->artisan('dropship-freight:backfill-weights',['--all'=>true,'--apply'=>true])->assertSuccessful(); + $this->assertSame(1000,$db->table('dropship_bill_lines')->whereNotNull('bill_weight')->count()); + } + + public function test_backfill_skips_confirmed_factory_bills(): void + { + Storage::fake('local');$store=app(DropshipFreightStore::class);$db=$store->db(); + $id=$store->saveFactory(null,['name'=>'重量测试','warehouse'=>'测试代发仓','keywords'=>'测试']); + $file=$store->upload([UploadedFile::fake()->createWithContent('重量测试.csv',"单号,运费,重量\nCONFIRM1,8,3\n")],'2026-11','测试')[0]; + $db->table('dropship_bill_lines')->where('file_id',$file)->update(['bill_weight'=>null]); + app(\Modules\EcommerceFinance\Services\SupplierPayableOverrideStore::class)->save('dropship-freight-confirm','2026-11|'.$id, + ['status'=>'confirmed','month'=>'2026-11','factory_id'=>$id],(int)$this->company->id,null,'test'); + $this->artisan('dropship-freight:backfill-weights',['--all'=>true,'--company'=>$this->company->id,'--apply'=>true])->assertSuccessful(); + $this->assertNull($db->table('dropship_bill_lines')->value('bill_weight')); + } +}