fix(代发运费): 补齐重量差并优化仓库查询 (#1777)
This commit is contained in:
parent
882447989d
commit
31bd498aea
76
app/Console/Commands/BackfillDropshipBillWeights.php
Normal file
76
app/Console/Commands/BackfillDropshipBillWeights.php
Normal file
@ -0,0 +1,76 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Models\Common\Company;
|
||||
use App\Support\DropshipFreight\{DropshipConfirmation, FactoryBillParser};
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\{Cache, DB, Storage};
|
||||
|
||||
/** 只从已上传原件回补缺失重量,不重导运费、附加费或确认记录。 */
|
||||
final class BackfillDropshipBillWeights extends Command
|
||||
{
|
||||
protected $signature = 'dropship-freight:backfill-weights {--file=*} {--all} {--company=1} {--apply}';
|
||||
protected $description = '预演或备份回补厂家原账单重量,保留所有已有金额';
|
||||
|
||||
public function handle(FactoryBillParser $parser, DropshipConfirmation $confirmation): int
|
||||
{
|
||||
if (! $this->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(); }
|
||||
}
|
||||
}
|
||||
@ -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)));
|
||||
|
||||
@ -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
|
||||
|
||||
@ -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);
|
||||
}
|
||||
|
||||
@ -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);
|
||||
}
|
||||
|
||||
@ -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<string,array{amount:float,sheet:string,row:int}>,sheets:list<array{sheet:string,read:bool,note:string,rows?:int,amount?:float}>}
|
||||
* @return array{lines:array<string,array{amount:float,weight:?float,sheet:string,row:int}>,sheets:list<array{sheet:string,read:bool,note:string,rows?:int,amount?:float}>}
|
||||
*/
|
||||
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<int,string> $row
|
||||
* @return array{waybill:int,amount:int,extra:list<int>,headers:list<string>,waybill_header:string,amount_header:string}|null
|
||||
* @return array{waybill:int,amount:int,weight:?int,extra:list<int>,headers:list<string>,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]];
|
||||
}
|
||||
|
||||
|
||||
@ -0,0 +1,19 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration {
|
||||
public function up(): void
|
||||
{
|
||||
Schema::connection('business_mirror')->table('dropship_bill_lines', function (Blueprint $table): void {
|
||||
$table->decimal('bill_weight', 14, 4)->nullable()->comment('厂家账单重量kg,同单多行合计,缺失不填零');
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
// 保留已回补的厂家重量,应用版本回退不删除业务数据。
|
||||
}
|
||||
};
|
||||
@ -0,0 +1,27 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
return new class extends Migration {
|
||||
public function up(): void
|
||||
{
|
||||
$schema = Schema::connection(config('jushuitan.connection', 'jushuitan_local'));
|
||||
$connection = DB::connection(config('jushuitan.connection', 'jushuitan_local'));
|
||||
if ($connection->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
|
||||
{
|
||||
// 只读查询索引向后兼容,回退应用不重建大表。
|
||||
}
|
||||
};
|
||||
@ -1,4 +1,5 @@
|
||||
[
|
||||
"dropship-freight:backfill-weights",
|
||||
"courier-bills:match-reverse",
|
||||
"courier-bills:refresh-settlement",
|
||||
"portal-freight:import-pending",
|
||||
|
||||
@ -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) ;;
|
||||
|
||||
@ -62,9 +62,11 @@ $feedbackPageFor = function (string $waybill) use ($dfCurrentDisputes): int {
|
||||
</section>
|
||||
<nav class="cbr-tabs" aria-label="按状态查看"><a data-cbr-tab href="{{ $pageUrl($base) }}" class="{{ $dfStatus===''?'is-active':'' }}">全部 {{ array_sum($s['counts']) }}</a><a data-cbr-tab href="{{ $pageUrl($base+['status'=>'attention']) }}" class="{{ $dfStatus==='attention'?'is-active':'' }}">要看的 {{ $s['attention'] }}</a><a data-cbr-tab href="{{ $pageUrl($base+['status'=>'disputed']) }}" class="{{ $dfStatus==='disputed'?'is-active':'' }}">厂家异议 {{ count($dfCurrentDisputes) }}</a>
|
||||
@foreach(\App\Support\DropshipFreight\DropshipReconciler::LABELS as $key=>$label)@if($s['counts'][$key])<a data-cbr-tab href="{{ $pageUrl($base+['status'=>$key]) }}" class="{{ $dfStatus===$key?'is-active':'' }}">{{ $label }} {{ $s['counts'][$key] }}</a>@endif@endforeach</nav>
|
||||
<nav class="cbr-tabs" aria-label="运费差异原因">@foreach(['weight_diff'=>'重量差','price_diff'=>'价格差','missing_weight'=>'重量待补充'] as $key=>$label)<a data-cbr-tab href="{{ $pageUrl($base+['status'=>$key]) }}" class="{{ $dfStatus===$key?'is-active':'' }}">{{ $label }} {{ $s['diff_counts'][$key] }}</a>@endforeach</nav>
|
||||
<p class="cbr-muted">重量差 = 厂家账单重量 − 我方计费重量(公斤)。运费有差时,重量相同归价格差;任一重量缺失归重量待补充。差异分类不改变结算金额。</p>
|
||||
<section class="cbr-panel"><h3>逐单核算明细</h3><form method="GET" action="{{ $pageUrl() }}" class="cbr-form cbr-panel-body" data-cbr-filter><input type="hidden" name="df_view" value="factory"><input type="hidden" name="factory" value="{{ $dfFactory->id }}"><input type="hidden" name="month" value="{{ $month }}"><input type="hidden" name="status" value="{{ $dfStatus }}"><input name="q" value="{{ $dfSearch }}" placeholder="搜索快递单号" aria-label="搜索快递单号"><button>搜索</button></form>
|
||||
<div class="cbr-scroll"><table><thead><tr><th>快递单号</th><th>发货 / 快递</th><th class="num">厂家运费</th><th class="num">我方核算</th><th class="num">最终结算</th><th class="num">差额</th><th>分类 / 说明</th><th>厂家反馈</th></tr></thead><tbody>
|
||||
@forelse($dfLines as $r)<tr><td>{{ $r['waybill'] }}</td><td>{{ $r['ship_time'] }}<div class="cbr-muted">{{ $r['express'] }}</div></td><td class="num">{{ $money($r['bill']) }}</td><td class="num">{{ $money($r['calc']) }}</td><td class="num">{{ $money($r['final']??$r['settle']) }}</td><td class="num cbr-diff">{{ $r['bill']===null?'':$money($r['bill']-(float)($r['final']??$r['settle'])) }}</td><td class="wrap">{{ $r['label'] }}<div class="cbr-muted">{{ $r['note'] }}</div></td><td>@if(isset($dfDisputeMap[$r['waybill']]))<a data-cbr-tab href="{{ $pageUrl(array_merge($base, request()->query(), ['feedback_page' => $feedbackPageFor((string)$r['waybill'])])) }}#feedback-{{ md5($r['waybill']) }}">{{ isset($dfDisputeMap[$r['waybill']]['decision'])?'查看处理':'待处理异议' }}</a>@else<span class="cbr-muted">—</span>@endif</td></tr>@empty<tr><td colspan="8">当前筛选没有明细。</td></tr>@endforelse
|
||||
<div class="cbr-scroll"><table><thead><tr><th>快递单号</th><th>发货 / 快递</th><th class="num">厂家重量(kg)</th><th class="num">我方计费重量(kg)</th><th class="num">重量差(kg)</th><th class="num">厂家运费</th><th class="num">我方核算</th><th class="num">最终结算</th><th class="num">差额</th><th>分类 / 说明</th><th>厂家反馈</th></tr></thead><tbody>
|
||||
@forelse($dfLines as $r)<tr><td>{{ $r['waybill'] }}</td><td>{{ $r['ship_time'] }}<div class="cbr-muted">{{ $r['express'] }}</div></td>@foreach(['bill_weight','charge_weight','weight_diff'] as $weightKey)<td class="num">{{ $r[$weightKey]===null?'—':rtrim(rtrim(number_format($r[$weightKey],4,'.',''),'0'),'.') }}</td>@endforeach<td class="num">{{ $money($r['bill']) }}</td><td class="num">{{ $money($r['calc']) }}</td><td class="num">{{ $money($r['final']??$r['settle']) }}</td><td class="num cbr-diff">{{ $r['bill']===null?'':$money($r['bill']-(float)($r['final']??$r['settle'])) }}</td><td class="wrap">{{ $r['label'] }}@if($r['diff_kind'])<div class="cbr-muted">{{ ['weight_diff'=>'重量差','price_diff'=>'价格差','missing_weight'=>'重量待补充'][$r['diff_kind']] }}</div>@endif<div class="cbr-muted">{{ $r['note'] }}</div></td><td>@if(isset($dfDisputeMap[$r['waybill']]))<a data-cbr-tab href="{{ $pageUrl(array_merge($base, request()->query(), ['feedback_page' => $feedbackPageFor((string)$r['waybill'])])) }}#feedback-{{ md5($r['waybill']) }}">{{ isset($dfDisputeMap[$r['waybill']]['decision'])?'查看处理':'待处理异议' }}</a>@else<span class="cbr-muted">—</span>@endif</td></tr>@empty<tr><td colspan="11">当前筛选没有明细。</td></tr>@endforelse
|
||||
</tbody></table></div><div class="cbr-pager">{{ $dfLines->links() }}</div></section>
|
||||
@if(($dfSurchargeSummary??collect())->isNotEmpty())<section class="cbr-panel"><h3>附加费核对</h3><div class="cbr-scroll"><table><thead><tr><th>项目</th><th>厂家金额</th><th>自算金额</th></tr></thead><tbody>@foreach($dfSurchargeSummary as $fee)<tr><td>{{ $fee->item }}</td><td>{{ $money($fee->bill) }}</td><td>{{ $money($fee->self) }}</td></tr>@endforeach</tbody></table></div></section>@endif
|
||||
@include('business.pages.courier-payables.partials.surcharge-matches',['surchargeRows'=>$dfSurchargeRows??null])
|
||||
|
||||
101
tests/Feature/Business/DropshipWeightTest.php
Normal file
101
tests/Feature/Business/DropshipWeightTest.php
Normal file
@ -0,0 +1,101 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Business;
|
||||
|
||||
use App\Http\Controllers\Business\DropshipFreightController;
|
||||
use App\Support\CourierBills\{ShippingLookup, StreamingWorkbook};
|
||||
use App\Support\DropshipFreight\{DropshipExporter, DropshipFreightStore, DropshipReconciler, FactoryBillParser};
|
||||
use Illuminate\Http\UploadedFile;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use PhpOffice\PhpSpreadsheet\IOFactory;
|
||||
use Tests\Feature\FeatureTestCase;
|
||||
|
||||
class DropshipWeightTest extends FeatureTestCase
|
||||
{
|
||||
public function test_parser_sums_weight_without_treating_partial_missing_as_zero_or_reading_system_weight(): void
|
||||
{
|
||||
$path = tempnam(sys_get_temp_dir(), 'weight') . '.csv';
|
||||
file_put_contents($path, "单号,运费,计费重量(kg),我方重量\nWB0001,5,2,99\nWB0001,6,3,99\nWB0002,5,2,99\nWB0002,6,,99\nWB0003,8,0,99\nWB0004,8,-1,99\n");
|
||||
try {
|
||||
$rows = app(FactoryBillParser::class)->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'));
|
||||
}
|
||||
}
|
||||
Loading…
x
Reference in New Issue
Block a user