diff --git a/app/Business/CourierContractPageData.php b/app/Business/CourierContractPageData.php index a5a5d1e12..1be548e21 100644 --- a/app/Business/CourierContractPageData.php +++ b/app/Business/CourierContractPageData.php @@ -96,6 +96,36 @@ class CourierContractPageData } } + /** @return array 同名快递取最新归档合作合同的日期。 */ + public function datesByCourierNames(array $names): array + { + $names = array_values(array_unique(array_filter(array_map('trim', $names)))); + if ($names === [] || ! Schema::hasTable('business_courier_agreement_signatures')) { + return []; + } + + $dates = []; + foreach (array_chunk($names, 500) as $chunk) { + $signatures = CourierAgreementSignature::query()->where('company_id', (int) company_id()) + ->where('document_type', 'cooperation-contract')->where('status', CourierAgreementSignature::STATUS_ARCHIVED) + ->whereIn('courier_name', $chunk) + ->select(['id', 'courier_name', 'payload', 'document_type', 'status']) + ->orderByDesc('archived_at')->orderByDesc('id')->cursor(); + foreach ($signatures as $signature) { + $name = trim((string) $signature->courier_name); + if (isset($dates[$name]) || ($payload = $signature->archivedCourierContractPayload()) === null) { + continue; + } + $dates[$name] = [ + 'start_date' => $this->date($payload['cooperation_start_date'] ?? null), + 'end_date' => $this->date($payload['cooperation_end_date'] ?? null), + ]; + } + } + + return $dates; + } + private function filters(): array { $search = request()->query('contract_search'); 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/Console/Commands/RefreshCourierSettlement.php b/app/Console/Commands/RefreshCourierSettlement.php index ffa82ed75..0c6187de2 100644 --- a/app/Console/Commands/RefreshCourierSettlement.php +++ b/app/Console/Commands/RefreshCourierSettlement.php @@ -10,8 +10,8 @@ use Illuminate\Support\Facades\{Cache, DB, Storage}; /** 只重新应用结算口径,不重算报价或覆盖人工处理。 */ final class RefreshCourierSettlement extends Command { - protected $signature = 'courier-bills:refresh-settlement {--statement=*} {--all-open} {--company=1} {--apply : 备份后更新未确认账单}'; - protected $description = '按快递提供与核价较低值结算运费和附加费,并更新武进韵达重量差补款'; + protected $signature = 'courier-bills:refresh-settlement {--statement=*} {--all-open} {--express=* : 仅刷新指定快递的运费,保留附加费} {--company=1} {--apply : 备份后更新未确认账单}'; + protected $description = '应用快递运费结算口径(含按核算值结算的例外),并刷新附加费及武进韵达补款'; public function handle(CourierBillMatcher $matcher, WeightDifferenceSubsidy $subsidy): int { @@ -51,11 +51,13 @@ final class RefreshCourierSettlement extends Command } $changed = 0; $decrease = 0.0; $scanned = 0; try { - foreach ($db->table('courier_bill_lines')->where('statement_id', $id)->orderBy('id')->lazyById(500) as $line) { + foreach ($db->table('courier_bill_lines')->where('statement_id', $id) + ->when($this->option('express') !== [], fn ($q) => $q->whereIn('express_name', $this->option('express'))) + ->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); + $amount = CourierBillMatcher::selfAmount((string) $line->category, $line->calc_freight === null ? null : (float) $line->calc_freight, $line->bill_amount, $line->resolution, $line->express_name); 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]); @@ -66,7 +68,7 @@ final class RefreshCourierSettlement extends Command $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) { + if ($this->option('express') === [] && $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), @@ -81,7 +83,7 @@ final class RefreshCourierSettlement extends Command $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, '.', ''); + if ($this->option('express') === [] && $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(); 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/CourierBills/CourierBillMatcher.php b/app/Support/CourierBills/CourierBillMatcher.php index 41499dc9c..1b1de6e18 100644 --- a/app/Support/CourierBills/CourierBillMatcher.php +++ b/app/Support/CourierBills/CourierBillMatcher.php @@ -12,6 +12,9 @@ use RuntimeException; */ final class CourierBillMatcher { + /** 这两家运费按我方核算结算,不能因合并分组而影响同组其他快递。 */ + public const ACTUAL_FREIGHT_EXPRESSES = ['中铁物流', '武进安能']; + private ?AccessoryDeductions $deductions = null; public function __construct( @@ -83,7 +86,7 @@ final class CourierBillMatcher 'calc_freight' => $ship['calc_freight'] ?? null, 'charge_weight' => $ship['charge_weight'] ?? null, 'unshipped_sources' => isset($unshipped[$key]) ? mb_substr(implode('、', $unshipped[$key]), 0, 128) : null, - 'self_amount' => self::selfAmount($category, $ship['calc_freight'] ?? null, $line->bill_amount, $line->resolution), + 'self_amount' => self::selfAmount($category, $ship['calc_freight'] ?? null, $line->bill_amount, $line->resolution, $ship['express_name'] ?? null), ]; } @@ -153,14 +156,15 @@ final class CourierBillMatcher return [Category::DIFF, null]; } - /** 自算金额:处理结果优先;正常应付按快递提供与核算运费较低者结算,缺少核算依据保持空白。 */ - public static function selfAmount(string $category, ?float $calcFreight, mixed $billAmount, ?string $resolution): ?float + /** 人工处理优先;中铁物流、武进安能运费取核算值,其他正常应付取较低值,缺少核算依据保持空白。 */ + public static function selfAmount(string $category, ?float $calcFreight, mixed $billAmount, ?string $resolution, ?string $expressName = null): ?float { return match ($resolution) { 'agree' => $billAmount === null ? null : (float) $billAmount, 'exclude', 'defer' => 0.0, default => in_array($category, [...Category::PAYABLE, Category::PRIOR], true) - ? ($calcFreight !== null && $billAmount !== null ? min($calcFreight, round((float) $billAmount, 2)) : $calcFreight) : 0.0, + ? (in_array(trim((string) $expressName), self::ACTUAL_FREIGHT_EXPRESSES, true) ? $calcFreight + : ($calcFreight !== null && $billAmount !== null ? min($calcFreight, round((float) $billAmount, 2)) : $calcFreight)) : 0.0, }; } @@ -175,14 +179,14 @@ final class CourierBillMatcher $db->transaction(function () use ($db, $statementId, $lineIds, $resolution, $user, &$count): void { foreach (array_chunk($lineIds, 500) as $chunk) { $lines = $db->table('courier_bill_lines')->where('statement_id', $statementId)->whereIn('id', $chunk) - ->get(['id', 'category', 'calc_freight', 'bill_amount']); + ->get(['id', 'category', 'calc_freight', 'bill_amount', 'express_name']); foreach ($lines as $line) { $db->table('courier_bill_lines')->where('id', $line->id)->update([ 'resolution' => $resolution, 'resolved_by' => $resolution === null ? null : $user, 'resolved_at' => $resolution === null ? null : now(), 'self_amount' => self::selfAmount((string) $line->category, - $line->calc_freight === null ? null : (float) $line->calc_freight, $line->bill_amount, $resolution), + $line->calc_freight === null ? null : (float) $line->calc_freight, $line->bill_amount, $resolution, $line->express_name), ]); $count++; } diff --git a/app/Support/CourierBills/PayableSummary.php b/app/Support/CourierBills/PayableSummary.php index 036d12ec0..1efc22dd1 100644 --- a/app/Support/CourierBills/PayableSummary.php +++ b/app/Support/CourierBills/PayableSummary.php @@ -2,6 +2,7 @@ namespace App\Support\CourierBills; +use App\Business\CourierContractPageData; use Illuminate\Database\ConnectionInterface; use Modules\EcommerceFinance\Repositories\CourierInformationMirrorRepository; use RuntimeException; @@ -38,7 +39,10 @@ final class PayableSummary /** 有对账单时由小汇总覆盖的列。 */ private const FROM_STATEMENTS = ['J', 'K', 'L', 'N', 'O', 'P', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT']; - public function __construct(private readonly CourierInformationMirrorRepository $couriers) {} + public function __construct( + private readonly CourierInformationMirrorRepository $couriers, + private readonly CourierContractPageData $contractDates, + ) {} public function db(): ConnectionInterface { @@ -66,6 +70,7 @@ final class PayableSummary report($error); $contracts = []; } + $contractDates = $this->contractDates->datesByCourierNames($stored->pluck('carrier')->all()); $today = now()->toDateString(); $rows = []; foreach ($stored as $row) { @@ -77,6 +82,9 @@ final class PayableSummary $cells['C'] = $contract['company'] !== '' ? $contract['company'] : ($cells['C'] ?? null); $cells['G'] = $contract['body'] !== '' ? $contract['body'] : ($cells['G'] ?? null); } + $dates = $contractDates[$row->carrier] ?? []; + $cells['A'] = $dates['start_date'] ?? ($cells['A'] ?? null); + $cells['B'] = $dates['end_date'] ?? ($cells['B'] ?? null); $mine = $statements[$row->carrier] ?? []; // 导入的汇总里已经有金额(手工做完的月份):以导入为准,对账单算出来的只用来比对; // 新建的月份金额是空的,才用对账单的小汇总填。 @@ -189,6 +197,10 @@ final class PayableSummary throw new RuntimeException(self::COLUMNS[$column] . '须为数字。'); } $cells[$column] = $number; + if ($column === 'S') { + // 手工实付(含 0)优先保留;清空后恢复按应付金额自动带出。 + $cells['_paid_manual'] = $number !== null; + } } else { $cells[$column] = $value === null ? null : mb_substr(trim($value), 0, 500); } diff --git a/app/Support/CourierBills/StatementExporter.php b/app/Support/CourierBills/StatementExporter.php index 21059e9c4..b32dcbb8f 100644 --- a/app/Support/CourierBills/StatementExporter.php +++ b/app/Support/CourierBills/StatementExporter.php @@ -108,8 +108,14 @@ final class StatementExporter $groupCell = static fn (object $line): array => $multi ? [$groupNames[(int) $line->statement_id] ?? ''] : []; [$sources, $original] = $this->originalHeaders($ids); + $front = []; + foreach (self::FRONT as $label => $field) { + $front[$label] = $field; + if ($field === 'qc_freight') $front['结算运费'] = '_settlement'; + } $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]; + $rest['settle_freight'] = '发货数据结算运费'; + $fullHeader = [...$original, ...array_keys($front), ...array_values($rest), '差异原因', '处理结果', ...$tail]; // 原始账单:底文件原封不动;第 2 个及以后的文件按值复制 $originals = $this->writeOriginal($book, $files, $baseFileId); @@ -123,7 +129,7 @@ final class StatementExporter } foreach ($sheets as $name => $filter) { $headerWritten = false; - $this->lines($ids, $filter, function (array $lines) use ($book, $name, $sources, $original, $rest, $fullHeader, $groupCell, $expressNames, &$headerWritten): void { + $this->lines($ids, $filter, function (array $lines) use ($book, $name, $sources, $original, $front, $rest, $fullHeader, $groupCell, $expressNames, &$headerWritten): void { if (! $headerWritten) { $book->row($name, $fullHeader, true); $headerWritten = true; @@ -132,13 +138,16 @@ final class StatementExporter foreach ($lines as $line) { $ship = $details[strtoupper($line->waybill_no)] ?? []; $cells = $this->originalCells($line, $sources, $original); - foreach (self::FRONT as $field) { + foreach ($front as $field) { + if ($field === '_settlement') { + $cells[] = $line->self_amount === null ? null : (float) $line->self_amount; + continue; + } $cells[] = $this->front($field, $line, $ship); } 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)]); diff --git a/app/Support/CourierBills/SummaryMapper.php b/app/Support/CourierBills/SummaryMapper.php index aacfa184f..5e65fe82e 100644 --- a/app/Support/CourierBills/SummaryMapper.php +++ b/app/Support/CourierBills/SummaryMapper.php @@ -126,12 +126,15 @@ final class SummaryMapper ]; } - /** 本月应付 R = K − L − N − O − P + Q + J + I;核对确定 M = K − L。 */ + /** 本月应付 R = K − L − N − O − P + Q + J + I;核对确定 M = K − L;未手工填写时,R > 0 则实付 S = R。 */ public static function totals(array $cells): array { $n = static fn (string $key): float => (float) ($cells[$key] ?? 0); $cells['M'] = round($n('K') - $n('L'), 2); $cells['R'] = round($n('K') - $n('L') - $n('N') - $n('O') - $n('P') + $n('Q') + $n('J') + $n('I'), 2); + if ($cells['R'] > 0 && empty($cells['_paid_manual'])) { + $cells['S'] = $cells['R']; + } return $cells; } 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 6ce519ba1..b010e5087 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/courier-bills/details.blade.php b/resources/views/business/pages/courier-payables/courier-bills/details.blade.php index 7ab59c0d2..47b78121b 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 @@ -29,7 +29,7 @@ 账单月份对账分组负责人快递单号分类 - 快递运费核算运费自算金额差异 + 快递运费核算运费结算运费差异 发货时间发货数据快递名称1处理结果 @@ -63,4 +63,4 @@ 共 {{ number_format($cbLines->total()) }} 条,每页 50 条 {{ $cbLines->links('business.partials.previous-next-pagination') }} -

正常应付运费取快递提供与我方核算的较低金额。处理结果:同意付款 = 自算金额取快递金额;已与快递确认剔除 / 转下月 = 本月自算金额为 0。武进韵达重量多报超过1公斤的正向运费差额,合计后补50%,在小汇总单列。改完对应对账单的小汇总和快递应付汇总自动重算。

+

正常应付运费取快递提供与我方核算的较低金额;中铁物流、武进安能按我方实际核算运费结算。处理结果:同意付款 = 自算金额取快递金额;已与快递确认剔除 / 转下月 = 本月自算金额为 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 a7b34d025..d906614f2 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,7 +47,7 @@

小汇总

-

正常应付运费与已核价附加费取快递提供和我方核算的较低金额,已有手工处理优先。武进韵达:快递重量超过我方计费重量1公斤的单据,快递多报的运费差额合计的50%单列补给快递。

+

正常应付运费与已核价附加费取快递提供和我方核算的较低金额;中铁物流、武进安能的运费按我方实际核算值结算,已有手工处理优先。武进韵达:快递重量超过我方计费重量1公斤的单据,快递多报的运费差额合计的50%单列补给快递。

@@ -111,8 +111,8 @@ @else @if ($open)@endif - - + + @endif @@ -128,10 +128,10 @@ + - diff --git a/resources/views/business/pages/courier-payables/courier-payable-summary.blade.php b/resources/views/business/pages/courier-payables/courier-payable-summary.blade.php index 81b70c065..91049fa15 100644 --- a/resources/views/business/pages/courier-payables/courier-payable-summary.blade.php +++ b/resources/views/business/pages/courier-payables/courier-payable-summary.blade.php @@ -33,8 +33,8 @@ + - @if ($psStatus)@endif @@ -106,7 +106,7 @@
项目快递提供金额自算金额差异归到汇总列
快递单号快递运费快递重量发货时间发货数据快递名称1核算运费计费重量运费差重量差自算金额未发出来源处理结果发货时间发货数据快递名称1核算运费结算运费计费重量运费差重量差未发出来源处理结果
{{ $line->ship_time ? substr((string) $line->ship_time, 0, 16) : '' }} {{ $line->express_name }} {{ $money($line->calc_freight) }}{{ $money($line->self_amount) }} {{ $line->charge_weight === null ? '' : rtrim(rtrim(number_format((float) $line->charge_weight, 3), '0'), '.') }} {{ $line->bill_amount !== null && $line->calc_freight !== null ? $money((float) $line->bill_amount - (float) $line->calc_freight) : '' }} {{ $line->bill_weight !== null && $line->charge_weight !== null ? round((float) $line->bill_weight - (float) $line->charge_weight, 3) : '' }}{{ $money($line->self_amount) }} {{ $line->unshipped_sources }} {{ \App\Support\CourierBills\Category::RESOLUTIONS[$line->resolution] ?? '' }}{{ $line->resolved_by ? ' · ' . $line->resolved_by : '' }}
- +
@endif @@ -148,7 +148,8 @@

已用 10 月 36 份手工对账表里的 42 个小汇总验证:按下面的规则归集,与手工快递汇总表逐行、逐列一致。小汇总里的项目名称决定归到哪一列,依次判断,命中即停。

- + + @@ -167,7 +168,8 @@ - + +
合同开始/截止时间、签订公司、快递公司主体名称取「快递资料」(按承运商名称);快递资料里没有的保留导入值。截止时间早于今天标「已到期」。
合同开始/截止时间优先取「快递资料 → 合同管理」中同名承运商最新归档合作合同的日期;未填写的日期沿用快递资料或导入值。截止时间早于今天标「已到期」。
签订公司、快递公司主体名称取「快递资料」(按承运商名称);快递资料里没有的保留导入值。
月初结余上月「本月应付金额 − 本次实付金额」结转(没填实付按 0 算);可手工改。签署完结后再按工作平台状态自动判断,细则后定。
原单补发配件项目名称含「补发配件」或「配件补发」(排在第一条,「成品补发配件扣快递」也算这里)。
补给快递以「补」开头、含「记账补款」或以「需补」结尾的项目,取正数;名称含「记账」的同时计入「记账补款金额」。不进差异明细。
对账差异金额差异明细 13 列合计 − 违约金 − 借支。
核对确定金额快递提供金额 − 对账差异金额。
本月应付金额快递提供 − 对账差异 − 面单 − 借支 − 赔付 + 其他补款 + 补给快递 + 月初结余。
其他补款、本次实付金额手工填。
其他补款手工填。
本次实付金额本月应付金额大于 0 时默认自动等额带出,可手工修改(含 0);手工值优先保留,清空后恢复自动带出。本月应付金额为 0 或负数时保留原值。
@@ -223,7 +225,7 @@ if (!response.ok) throw new Error((await response.json().catch(() => ({})))?.message || 'save'); await swap(location.href); const next = document.querySelector('[data-ps-status]'); - if (next) next.textContent = '已保存,本月应付已重算。'; + if (next) next.textContent = '已保存,手工实付优先保留,未手工填写的正数应付自动带出实付。'; } catch (error) { input.disabled = false; if (status) status.textContent = '保存失败:' + (error.message === 'save' ? '请刷新后重试' : error.message); 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/CourierBillReconciliationTest.php b/tests/Feature/Business/CourierBillReconciliationTest.php index c29a03218..570780425 100644 --- a/tests/Feature/Business/CourierBillReconciliationTest.php +++ b/tests/Feature/Business/CourierBillReconciliationTest.php @@ -317,7 +317,7 @@ final class CourierBillReconciliationTest extends FeatureTestCase $this->assertSame('13800000000', (string) $recon->getCell('C2')->getValue()); $this->assertNotSame(DataType::TYPE_NUMERIC, $recon->getCell('C2')->getDataType()); $this->assertSame('ZT001', (string) $recon->getCell('G2')->getValue()); // 快递单号(25 列里的第 4 列) - $this->assertEquals(0, $recon->getCell('Q2')->getValue()); // 运费差 = 10 − 核算 10 + $this->assertEquals(0, $recon->getCell('R2')->getValue()); // 运费差 = 10 − 核算 10,核算后新增结算列 $book->disconnectWorksheets(); } diff --git a/tests/Feature/Business/CourierPayableSummaryRulesTest.php b/tests/Feature/Business/CourierPayableSummaryRulesTest.php new file mode 100644 index 000000000..bd02b2775 --- /dev/null +++ b/tests/Feature/Business/CourierPayableSummaryRulesTest.php @@ -0,0 +1,226 @@ +shouldReceive('contractsByName')->andReturn([ + '合同快递' => ['contract_start' => '2025-01-01', 'contract_end' => '2025-12-31', 'company' => '原签订公司', 'body' => '原合同主体'], + ]); + $this->app->instance(CourierInformationMirrorRepository::class, $mirror); + } + + public function test_positive_payables_drive_paid_amount_export_and_next_month_balance(): void + { + $service = app(PayableSummary::class); + $expected = []; + foreach ([ + ['正数快递', ['K' => 2000, 'L' => 50, 'I' => 100.5, 'S' => 1000], 2050.5, 2050.5], + ['一分钱快递', ['K' => 0.01, 'S' => null], 0.01, 0.01], + ['零数快递', ['K' => 0.004, 'S' => 9], 0.0, 9.0], + ['负数快递', ['I' => -50, 'S' => -5], -50.0, -5.0], + ['空值快递', ['I' => -20], -20.0, null], + ] as [$carrier, $cells, $payable, $paid]) { + $this->row($carrier, $cells); + $expected[$carrier] = [$payable, $paid]; + } + $rows = $service->rows('2026-11'); + foreach ($rows as $row) { + [$payable, $paid] = $expected[$row['cells']['H']]; + $this->assertSame($payable, $row['cells']['R']); + $this->assertSame($paid, $row['cells']['S'] ?? null); + } + $stored = json_decode($service->db()->table('courier_payable_summary_rows')->where('carrier', '正数快递')->value('cells'), true); + $this->assertSame(1000, $stored['S']); + + $file = tempnam(sys_get_temp_dir(), 'courier-auto-paid-'); + try { + $handle = fopen($file, 'wb'); + $service->export('2026-11', $handle); + fclose($handle); + $book = IOFactory::load($file); + $sheet = $book->getSheetByName('汇总'); + $this->assertEquals(2050.5, $sheet->getCell('R4')->getValue()); + $this->assertEquals(2050.5, $sheet->getCell('S4')->getValue()); + $this->assertEquals(9, $sheet->getCell('S6')->getValue()); + $this->assertEquals(2054.51, $sheet->getCell('S9')->getValue()); + $book->disconnectWorksheets(); + } finally { + @unlink($file); + } + + $this->assertSame(5, $service->createMonth('2026-12')); + $next = collect($service->rows('2026-12'))->keyBy('cells.H'); + $this->assertSame(0.0, $next['正数快递']['cells']['I']); + $this->assertSame(0.0, $next['一分钱快递']['cells']['I']); + $this->assertSame(-9.0, $next['零数快递']['cells']['I']); + $this->assertSame(-45.0, $next['负数快递']['cells']['I']); + $this->assertSame(-20.0, $next['空值快递']['cells']['I']); + } + + public function test_manual_paid_amount_is_editable_and_survives_recalculation(): void + { + $positive = $this->row('正数快递', ['K' => 100, 'S' => 7]); + $negative = $this->row('负数快递', ['I' => -10, 'S' => 2]); + $this->user->attachPermission(Permission::where('name', 'read-admin-panel')->firstOrFail()); + $this->loginAs(); + foreach (['courier-payables', 'courier-payables-final'] as $section) { + $page = route('business.pages.show', ['section' => $section, 'page' => 'courier-payable-summary', 'month' => '2026-11']); + $response = $this->get($page)->assertOk() + ->assertSee('aria-label="正数快递 本次实付金额"', false) + ->assertSee('aria-label="负数快递 本次实付金额"', false); + $this->assertSame($section === 'courier-payables' ? 102.0 : 7.0, $response->viewData('content')['psTotals']['S']); + $this->withExceptionHandling(); + $this->postJson(route("business.$section.courier-payable-summary.update", ['row' => $positive]), ['column' => 'S', 'value' => '5']) + ->assertOk(); + } + $update = fn (int $id) => route('business.courier-payables.courier-payable-summary.update', ['row' => $id]); + $this->postJson($update($positive), ['column' => 'Q', 'value' => '12.34'])->assertOk(); + $this->postJson($update($negative), ['column' => 'S', 'value' => '-3'])->assertOk(); + $rows = collect(app(PayableSummary::class)->rows('2026-11'))->keyBy('cells.H'); + $this->assertSame(112.34, $rows['正数快递']['cells']['R']); + $this->assertSame(5.0, $rows['正数快递']['cells']['S']); + $this->assertSame(-3.0, $rows['负数快递']['cells']['S']); + + $this->postJson($update($positive), ['column' => 'S', 'value' => 'not-a-number']) + ->assertUnprocessable()->assertJsonValidationErrors('courier_summary'); + $this->assertSame(5.0, app(PayableSummary::class)->rows('2026-11')[0]['cells']['S']); + $this->postJson($update($positive), ['column' => 'S', 'value' => '0'])->assertOk(); + $this->postJson($update($positive), ['column' => 'Q', 'value' => '20'])->assertOk(); + $this->assertSame(0.0, app(PayableSummary::class)->rows('2026-11')[0]['cells']['S']); + $this->postJson($update($positive), ['column' => 'S', 'value' => ''])->assertOk(); + $this->assertSame(120.0, app(PayableSummary::class)->rows('2026-11')[0]['cells']['S']); + $this->postJson($update($positive), ['column' => 'S', 'value' => '25.55'])->assertOk(); + + $file = tempnam(sys_get_temp_dir(), 'courier-manual-paid-'); + try { + $handle = fopen($file, 'wb'); + app(PayableSummary::class)->export('2026-11', $handle); + fclose($handle); + $book = IOFactory::load($file); + $sheet = $book->getSheetByName('汇总'); + $this->assertEquals(25.55, $sheet->getCell('S4')->getValue()); + $this->assertEquals(22.55, $sheet->getCell('S6')->getValue()); + $book->disconnectWorksheets(); + } finally { + @unlink($file); + } + app(PayableSummary::class)->createMonth('2026-12'); + $next = app(PayableSummary::class)->rows('2026-12'); + $this->assertSame(94.45, $next[0]['cells']['I']); + $this->assertSame(94.45, $next[0]['cells']['S']); + $this->assertArrayNotHasKey('_paid_manual', $next[0]['cells']); + } + + public function test_reconciliation_status_filter_combines_with_other_filters_and_updates_totals(): void + { + $this->row('已确认快递', ['K' => 100, 'Y' => '已确认', 'C' => '甲公司', 'D' => '负责人甲', 'E' => '承运']); + $this->row('待处理快递', ['K' => 80, 'C' => '甲公司', 'D' => '负责人甲', 'E' => '承运']); + $this->row('旧账快递', ['I' => -20]); + $this->row('无账单快递', []); + $this->user->attachPermission(Permission::where('name', 'read-admin-panel')->firstOrFail()); + $this->loginAs(); + foreach (['courier-payables', 'courier-payables-final'] as $section) { + $url = route('business.pages.show', ['section' => $section, 'page' => 'courier-payable-summary', 'month' => '2026-11']); + $response = $this->get($url . '&' . http_build_query(['status' => '已确认', 'company' => '甲公司', 'owner' => '负责人甲', 'state' => '承运', 'q' => '快递'])) + ->assertOk()->assertSee('