Merge remote-tracking branch 'origin/main' into fix/limeng-unshipped-sync-recovery
This commit is contained in:
commit
953960c57b
@ -96,6 +96,36 @@ class CourierContractPageData
|
||||
}
|
||||
}
|
||||
|
||||
/** @return array<string,array{start_date:?string,end_date:?string}> 同名快递取最新归档合作合同的日期。 */
|
||||
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');
|
||||
|
||||
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(); }
|
||||
}
|
||||
}
|
||||
@ -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();
|
||||
|
||||
@ -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)));
|
||||
|
||||
@ -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++;
|
||||
}
|
||||
|
||||
@ -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);
|
||||
}
|
||||
|
||||
@ -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)]);
|
||||
|
||||
@ -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;
|
||||
}
|
||||
|
||||
@ -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) ;;
|
||||
|
||||
@ -29,7 +29,7 @@
|
||||
<thead><tr>
|
||||
<th scope="col"><input type="checkbox" data-cbr-check-all aria-label="全选本页"></th>
|
||||
<th scope="col">账单月份</th><th scope="col">对账分组</th><th scope="col">负责人</th><th scope="col">快递单号</th><th scope="col">分类</th>
|
||||
<th scope="col" class="num">快递运费</th><th scope="col" class="num">核算运费</th><th scope="col" class="num">自算金额</th><th scope="col" class="num">差异</th>
|
||||
<th scope="col" class="num">快递运费</th><th scope="col" class="num">核算运费</th><th scope="col" class="num">结算运费</th><th scope="col" class="num">差异</th>
|
||||
<th scope="col">发货时间</th><th scope="col">发货数据快递名称1</th><th scope="col">处理结果</th><th scope="col"></th>
|
||||
</tr></thead>
|
||||
<tbody>
|
||||
@ -63,4 +63,4 @@
|
||||
<span class="cbr-pager">共 {{ number_format($cbLines->total()) }} 条,每页 50 条 {{ $cbLines->links('business.partials.previous-next-pagination') }}</span>
|
||||
</div>
|
||||
</form>
|
||||
<p class="cbr-muted">正常应付运费取快递提供与我方核算的较低金额。处理结果:同意付款 = 自算金额取快递金额;已与快递确认剔除 / 转下月 = 本月自算金额为 0。武进韵达重量多报超过1公斤的正向运费差额,合计后补50%,在小汇总单列。改完对应对账单的小汇总和快递应付汇总自动重算。</p>
|
||||
<p class="cbr-muted">正常应付运费取快递提供与我方核算的较低金额;中铁物流、武进安能按我方实际核算运费结算。处理结果:同意付款 = 自算金额取快递金额;已与快递确认剔除 / 转下月 = 本月自算金额为 0。武进韵达重量多报超过1公斤的正向运费差额,合计后补50%,在小汇总单列。改完对应对账单的小汇总和快递应付汇总自动重算。</p>
|
||||
|
||||
@ -47,7 +47,7 @@
|
||||
<div class="fc-workspace"><div>
|
||||
<section class="cbr-panel" aria-label="小汇总">
|
||||
<h3>小汇总</h3>
|
||||
<p class="cbr-muted cbr-panel-body">正常应付运费与已核价附加费取快递提供和我方核算的较低金额,已有手工处理优先。武进韵达:快递重量超过我方计费重量1公斤的单据,快递多报的运费差额合计的50%单列补给快递。</p>
|
||||
<p class="cbr-muted cbr-panel-body">正常应付运费与已核价附加费取快递提供和我方核算的较低金额;中铁物流、武进安能的运费按我方实际核算值结算,已有手工处理优先。武进韵达:快递重量超过我方计费重量1公斤的单据,快递多报的运费差额合计的50%单列补给快递。</p>
|
||||
<div class="cbr-scroll">
|
||||
<table>
|
||||
<thead><tr><th scope="col">项目</th><th scope="col" class="num">快递提供金额</th><th scope="col" class="num">自算金额</th><th scope="col" class="num">差异</th><th scope="col">归到汇总列</th><th scope="col"></th></tr></thead>
|
||||
@ -111,8 +111,8 @@
|
||||
@else
|
||||
@if ($open)<th scope="col"><input type="checkbox" data-cbr-check-all aria-label="全选本页"></th>@endif
|
||||
<th scope="col">快递单号</th><th scope="col" class="num">快递运费</th><th scope="col" class="num">快递重量</th>
|
||||
<th scope="col">发货时间</th><th scope="col">发货数据快递名称1</th><th scope="col" class="num">核算运费</th><th scope="col" class="num">计费重量</th>
|
||||
<th scope="col" class="num">运费差</th><th scope="col" class="num">重量差</th><th scope="col" class="num">自算金额</th><th scope="col">未发出来源</th><th scope="col">处理结果</th>
|
||||
<th scope="col">发货时间</th><th scope="col">发货数据快递名称1</th><th scope="col" class="num">核算运费</th><th scope="col" class="num">结算运费</th><th scope="col" class="num">计费重量</th>
|
||||
<th scope="col" class="num">运费差</th><th scope="col" class="num">重量差</th><th scope="col">未发出来源</th><th scope="col">处理结果</th>
|
||||
@endif
|
||||
</tr></thead>
|
||||
<tbody>
|
||||
@ -128,10 +128,10 @@
|
||||
<td>{{ $line->ship_time ? substr((string) $line->ship_time, 0, 16) : '' }}</td>
|
||||
<td>{{ $line->express_name }}</td>
|
||||
<td class="num">{{ $money($line->calc_freight) }}</td>
|
||||
<td class="num">{{ $money($line->self_amount) }}</td>
|
||||
<td class="num">{{ $line->charge_weight === null ? '' : rtrim(rtrim(number_format((float) $line->charge_weight, 3), '0'), '.') }}</td>
|
||||
<td class="num cbr-diff">{{ $line->bill_amount !== null && $line->calc_freight !== null ? $money((float) $line->bill_amount - (float) $line->calc_freight) : '' }}</td>
|
||||
<td class="num">{{ $line->bill_weight !== null && $line->charge_weight !== null ? round((float) $line->bill_weight - (float) $line->charge_weight, 3) : '' }}</td>
|
||||
<td class="num">{{ $money($line->self_amount) }}</td>
|
||||
<td>{{ $line->unshipped_sources }}</td>
|
||||
<td>{{ \App\Support\CourierBills\Category::RESOLUTIONS[$line->resolution] ?? '' }}{{ $line->resolved_by ? ' · ' . $line->resolved_by : '' }}</td>
|
||||
</tr>
|
||||
|
||||
@ -33,8 +33,8 @@
|
||||
<label>签订公司<select name="company"><option value="">全部</option>@foreach ($psCompanies ?? [] as $v)<option @selected(request('company') === $v)>{{ $v }}</option>@endforeach</select></label>
|
||||
<label>负责人<select name="owner"><option value="">全部</option>@foreach ($psOwners ?? [] as $v)<option @selected(request('owner') === $v)>{{ $v }}</option>@endforeach</select></label>
|
||||
<label>承运状态<select name="state"><option value="">全部</option>@foreach (['承运', '停运'] as $v)<option @selected(request('state') === $v)>{{ $v }}</option>@endforeach</select></label>
|
||||
<label>对账状态<select name="status"><option value="">全部</option>@foreach (\App\Http\Controllers\Business\CourierPayableSummaryController::STATUSES as $status)<option value="{{ $status }}" @selected($psStatus === $status)>{{ $status === '已确认' ? '核对无误' : $status }}</option>@endforeach</select></label>
|
||||
<label>搜索<input type="search" name="q" value="{{ request('q') }}" placeholder="承运商或快递公司主体"></label>
|
||||
@if ($psStatus)<input type="hidden" name="status" value="{{ $psStatus }}">@endif
|
||||
<button type="submit">查询</button>
|
||||
</form>
|
||||
|
||||
@ -106,7 +106,7 @@
|
||||
</tfoot>
|
||||
</table>
|
||||
</div>
|
||||
<div class="cbr-footer"><span role="status" data-ps-status>负责人、承运状态、月初结余、其他补款、本次实付、备注、仓库可直接改,改完自动保存。</span></div>
|
||||
<div class="cbr-footer"><span role="status" data-ps-status>本次实付默认按正数应付金额带出,可手工修改;清空后恢复自动带出。负责人、承运状态、月初结余、其他补款、备注、仓库也可直接改,改完自动保存。</span></div>
|
||||
</section>
|
||||
@endif
|
||||
|
||||
@ -148,7 +148,8 @@
|
||||
<p>已用 10 月 36 份手工对账表里的 42 个小汇总验证:按下面的规则归集,与手工快递汇总表逐行、逐列一致。小汇总里的项目名称决定归到哪一列,依次判断,命中即停。</p>
|
||||
<table>
|
||||
<tbody>
|
||||
<tr><td>合同开始/截止时间、签订公司、快递公司主体名称</td><td>取「快递资料」(按承运商名称);快递资料里没有的保留导入值。截止时间早于今天标「已到期」。</td></tr>
|
||||
<tr><td>合同开始/截止时间</td><td>优先取「快递资料 → 合同管理」中同名承运商最新归档合作合同的日期;未填写的日期沿用快递资料或导入值。截止时间早于今天标「已到期」。</td></tr>
|
||||
<tr><td>签订公司、快递公司主体名称</td><td>取「快递资料」(按承运商名称);快递资料里没有的保留导入值。</td></tr>
|
||||
<tr><td>月初结余</td><td>上月「本月应付金额 − 本次实付金额」结转(没填实付按 0 算);可手工改。签署完结后再按工作平台状态自动判断,细则后定。</td></tr>
|
||||
<tr><td>原单补发配件</td><td>项目名称含「补发配件」或「配件补发」(排在第一条,「成品补发配件扣快递」也算这里)。</td></tr>
|
||||
<tr><td>补给快递</td><td>以「补」开头、含「记账补款」或以「需补」结尾的项目,取正数;名称含「记账」的同时计入「记账补款金额」。不进差异明细。</td></tr>
|
||||
@ -167,7 +168,8 @@
|
||||
<tr><td>对账差异金额</td><td>差异明细 13 列合计 − 违约金 − 借支。</td></tr>
|
||||
<tr><td>核对确定金额</td><td>快递提供金额 − 对账差异金额。</td></tr>
|
||||
<tr><td>本月应付金额</td><td>快递提供 − 对账差异 − 面单 − 借支 − 赔付 + 其他补款 + 补给快递 + 月初结余。</td></tr>
|
||||
<tr><td>其他补款、本次实付金额</td><td>手工填。</td></tr>
|
||||
<tr><td>其他补款</td><td>手工填。</td></tr>
|
||||
<tr><td>本次实付金额</td><td>本月应付金额大于 0 时默认自动等额带出,可手工修改(含 0);手工值优先保留,清空后恢复自动带出。本月应付金额为 0 或负数时保留原值。</td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</details>
|
||||
@ -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);
|
||||
|
||||
@ -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])
|
||||
|
||||
@ -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();
|
||||
}
|
||||
|
||||
|
||||
226
tests/Feature/Business/CourierPayableSummaryRulesTest.php
Normal file
226
tests/Feature/Business/CourierPayableSummaryRulesTest.php
Normal file
@ -0,0 +1,226 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Business;
|
||||
|
||||
use App\Models\Auth\Permission;
|
||||
use App\Models\Business\CourierAgreementSignature;
|
||||
use App\Support\CourierBills\PayableSummary;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Mockery;
|
||||
use Modules\EcommerceFinance\Repositories\CourierInformationMirrorRepository;
|
||||
use PhpOffice\PhpSpreadsheet\IOFactory;
|
||||
use Tests\Feature\FeatureTestCase;
|
||||
|
||||
final class CourierPayableSummaryRulesTest extends FeatureTestCase
|
||||
{
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
Storage::fake('local');
|
||||
$mirror = Mockery::mock(CourierInformationMirrorRepository::class);
|
||||
$mirror->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('<select name="status">', false)->assertSeeText('核对无误')
|
||||
->assertSee('value="已确认" selected', false)->assertDontSee('type="hidden" name="status"', false);
|
||||
$data = $response->viewData('content');
|
||||
$this->assertCount(1, $data['psRows']);
|
||||
$this->assertSame('已确认快递', $data['psRows'][0]['cells']['H']);
|
||||
$this->assertSame(100.0, $data['psTotals']['S']);
|
||||
$this->assertSame(4, $data['psAll']);
|
||||
foreach (['待处理', '旧账挂账', '本月无账单'] as $status) {
|
||||
$filtered = $this->get($url . '&' . http_build_query(['status' => $status]))->assertOk()->viewData('content');
|
||||
$this->assertCount(1, $filtered['psRows']);
|
||||
$this->assertSame($status, $filtered['psRows'][0]['status']);
|
||||
}
|
||||
$this->assertCount(4, $this->get($url . '&status=')->assertOk()->viewData('content')['psRows']);
|
||||
$empty = $this->get($url . '&' . http_build_query(['status' => '已确认', 'q' => '不存在']))->assertOk();
|
||||
$empty->assertSeeText('当前条件下没有承运商。');
|
||||
$this->assertSame(0, $empty->viewData('content')['psTotals']['S']);
|
||||
}
|
||||
}
|
||||
|
||||
public function test_contract_management_dates_override_mirror_with_tenant_and_archive_boundaries(): void
|
||||
{
|
||||
$this->row('合同快递', ['A' => '2024-01-01', 'B' => '2024-12-31']);
|
||||
$this->row('缺截止日期', ['A' => '2024-01-01', 'B' => '2024-12-31']);
|
||||
$this->row('仅导入日期', ['A' => '2024-01-01', 'B' => '2024-12-31']);
|
||||
$this->signature('合同快递', ['cooperation_start_date' => '2026-01-01', 'cooperation_end_date' => '2026-11-01'], ['archived_at' => '2026-01-02']);
|
||||
$latest = $this->signature('合同快递', ['cooperation_start_date' => '2026-11-02', 'cooperation_end_date' => '2027-11-01'], ['archived_at' => '2026-11-03']);
|
||||
$this->signature('合同快递', ['cooperation_end_date' => '2030-01-01'], ['archived_at' => '2026-01-03']);
|
||||
$this->signature('合同快递', ['partner_type' => 'supplier']);
|
||||
$this->signature('合同快递', [], ['company_id' => $this->company->id + 10]);
|
||||
$this->signature('合同快递', [], ['status' => 'completed']);
|
||||
$this->signature('合同快递', [], ['document_type' => 'account-proof']);
|
||||
$deleted = $this->signature('合同快递', ['cooperation_end_date' => '2035-01-01']);
|
||||
$deleted->delete();
|
||||
$this->signature('缺截止日期', ['cooperation_start_date' => '2026-02-01', 'cooperation_end_date' => '2026-02-30']);
|
||||
|
||||
$rows = collect(app(PayableSummary::class)->rows('2026-11'))->keyBy('cells.H');
|
||||
$this->assertSame('2026-11-02', $rows['合同快递']['cells']['A']);
|
||||
$this->assertSame('2027-11-01', $rows['合同快递']['cells']['B']);
|
||||
$this->assertSame('原签订公司', $rows['合同快递']['cells']['C']);
|
||||
$this->assertSame('原合同主体', $rows['合同快递']['cells']['G']);
|
||||
$this->assertFalse($rows['合同快递']['expired']);
|
||||
$this->assertSame('2026-02-01', $rows['缺截止日期']['cells']['A']);
|
||||
$this->assertSame('2024-12-31', $rows['缺截止日期']['cells']['B']);
|
||||
$this->assertSame('2024-01-01', $rows['仅导入日期']['cells']['A']);
|
||||
$this->assertSame('2024-12-31', $rows['仅导入日期']['cells']['B']);
|
||||
$this->assertTrue($rows['仅导入日期']['expired']);
|
||||
$latest->refresh();
|
||||
$this->assertSame('2026-11-02', $latest->payload['cooperation_start_date']);
|
||||
$file = tempnam(sys_get_temp_dir(), 'courier-contract-dates-');
|
||||
try {
|
||||
$handle = fopen($file, 'wb');
|
||||
app(PayableSummary::class)->export('2026-11', $handle);
|
||||
fclose($handle);
|
||||
$book = IOFactory::load($file);
|
||||
$sheet = $book->getSheetByName('汇总');
|
||||
$this->assertSame('2026-11-02', (string) $sheet->getCell('A4')->getValue());
|
||||
$this->assertSame('2027-11-01', (string) $sheet->getCell('B4')->getValue());
|
||||
$book->disconnectWorksheets();
|
||||
} finally {
|
||||
@unlink($file);
|
||||
}
|
||||
}
|
||||
|
||||
private function row(string $carrier, array $cells): int
|
||||
{
|
||||
$db = app(PayableSummary::class)->db();
|
||||
return (int) $db->table('courier_payable_summary_rows')->insertGetId([
|
||||
'month' => '2026-11', 'sort' => $db->table('courier_payable_summary_rows')->count() + 1,
|
||||
'carrier' => $carrier, 'cells' => json_encode($cells + ['H' => $carrier], JSON_UNESCAPED_UNICODE),
|
||||
'created_at' => now(), 'updated_at' => now(),
|
||||
]);
|
||||
}
|
||||
|
||||
private function signature(string $carrier, array $payload = [], array $attributes = []): CourierAgreementSignature
|
||||
{
|
||||
$key = 'summary-' . bin2hex(random_bytes(8));
|
||||
return CourierAgreementSignature::create($attributes + [
|
||||
'company_id' => $this->company->id, 'business_no' => $key, 'idempotency_key' => $key,
|
||||
'document_type' => 'cooperation-contract', 'template_code' => 'TPL-COOPERATION-CONTRACT-V1',
|
||||
'template_version' => '1', 'source_file_name' => 'contract.pdf', 'status' => 'archived',
|
||||
'courier_name' => $carrier, 'company_full_name' => '甲方', 'organization_name' => '乙方',
|
||||
'operator_name' => '经办人', 'payload' => $payload + ['partner_type' => 'courier', 'cooperation_start_date' => '2026-01-01', 'cooperation_end_date' => '2026-12-31'],
|
||||
'source_pdf_path' => $key . '/source.pdf', 'source_pdf_sha256' => '',
|
||||
'archived_at' => now(), 'created_by' => $this->user->id, 'updated_by' => $this->user->id,
|
||||
]);
|
||||
}
|
||||
}
|
||||
@ -25,6 +25,56 @@ class CourierSettlementRulesTest extends FeatureTestCase
|
||||
$this->assertEquals(8.01, CourierBillMatcher::selfAmount(Category::DIFF, 10, 8.006, null));
|
||||
}
|
||||
|
||||
public function test_actual_freight_exceptions_are_exact_names_and_preserve_manual_decisions(): void
|
||||
{
|
||||
foreach (['中铁物流', '武进安能'] as $name) {
|
||||
foreach ([Category::MATCH, Category::DIFF, Category::PRIOR] as $category) {
|
||||
foreach ([0, 8, 12, null] as $bill) $this->assertSame(10.0, CourierBillMatcher::selfAmount($category, 10, $bill, null, $name));
|
||||
}
|
||||
$this->assertNull(CourierBillMatcher::selfAmount(Category::UNCALCULATED, null, 8, null, $name));
|
||||
$this->assertSame(8.0, CourierBillMatcher::selfAmount(Category::DIFF, 10, 8, 'agree', $name));
|
||||
foreach (['exclude', 'defer'] as $resolution) $this->assertSame(0.0, CourierBillMatcher::selfAmount(Category::DIFF, 10, 8, $resolution, $name));
|
||||
$this->assertSame(0.0, CourierBillMatcher::selfAmount(Category::DUPLICATE, 10, 8, null, $name));
|
||||
}
|
||||
foreach (['中铁客退', '中铁物流其他', '武进安能其他'] as $name) $this->assertEquals(8, CourierBillMatcher::selfAmount(Category::DIFF, 10, 8, null, $name));
|
||||
}
|
||||
|
||||
public function test_actual_freight_rule_applies_to_matching_manual_reset_and_scoped_historical_refresh(): void
|
||||
{
|
||||
Storage::fake('local');$db=CourierBillMatcher::db();$store=app(CourierBillStore::class);
|
||||
$store->saveGroup(null,['name'=>'中铁物流','express_names'=>['中铁物流','武进安能','中铁客退']]);
|
||||
$shipping=app(\App\Support\CourierBills\ShippingLookup::class)->connection();
|
||||
foreach (['中铁物流','武进安能','中铁客退'] as $i=>$name) {
|
||||
$shipping->table('jst_oms_shipping')->insert(['source_id'=>$i+1,'express_no'=>'ACTUAL'.($i+1),'express_name1'=>$name,'ship_time'=>'2026-11-03 09:00:00']);
|
||||
$shipping->table('jst_oms_shipping_freight')->insert(['source_id'=>$i+1,'status'=>'OK','freight'=>10,'charge_weight'=>2]);
|
||||
}
|
||||
$path=tempnam(sys_get_temp_dir(),'actual').'.csv';file_put_contents($path,"单号,运费\nACTUAL1,8\nACTUAL2,8\nACTUAL3,8\n");
|
||||
try {$file=$store->upload([new \Illuminate\Http\UploadedFile($path,'中铁物流.csv',null,null,true)],'2026-11',[],'测试')[0];}
|
||||
finally {@unlink($path);}
|
||||
$id=(int)$db->table('courier_bill_files')->where('id',$file)->value('statement_id');
|
||||
$this->assertEquals([10,10,8],$db->table('courier_bill_lines')->where('statement_id',$id)->orderBy('row_no')->pluck('self_amount')->all());
|
||||
$line=(int)$db->table('courier_bill_lines')->where('waybill_no','ACTUAL1')->value('id');
|
||||
app(CourierBillMatcher::class)->resolve($id,[$line],'agree','测试');
|
||||
$this->assertEquals(8,$db->table('courier_bill_lines')->where('id',$line)->value('self_amount'));
|
||||
app(CourierBillMatcher::class)->resolve($id,[$line],null,'测试');
|
||||
$this->assertEquals(10,$db->table('courier_bill_lines')->where('id',$line)->value('self_amount'));
|
||||
$db->table('courier_bill_lines')->where('statement_id',$id)->update(['self_amount'=>8]);
|
||||
$db->table('bill_surcharge_matches')->insert(['scope'=>'courier','owner_id'=>$id,'file_id'=>$file,'sheet'=>'附加费','row_no'=>5,'bill_month'=>'2026-11','waybill_no'=>'ACTUAL1','item'=>'上楼费','summary_label'=>'附加费','bill_amount'=>5,'self_amount'=>9,'match_status'=>'已匹配','match_note'=>'保持核价']);
|
||||
$options=['--statement'=>[$id],'--express'=>['中铁物流','武进安能']];
|
||||
$this->artisan('courier-bills:refresh-settlement',$options)->assertSuccessful();
|
||||
$this->assertEquals(24,$db->table('courier_bill_lines')->sum('self_amount'));
|
||||
$this->artisan('courier-bills:refresh-settlement',$options+['--apply'=>true])->assertSuccessful();
|
||||
$this->assertEquals([10,10,8],$db->table('courier_bill_lines')->orderBy('row_no')->pluck('self_amount')->all());
|
||||
$this->assertEquals(9,$db->table('bill_surcharge_matches')->value('self_amount'));
|
||||
$out=tmpfile();app(StatementExporter::class)->export($id,$out);rewind($out);$path=tempnam(sys_get_temp_dir(),'actual-export');file_put_contents($path,stream_get_contents($out));fclose($out);
|
||||
try {
|
||||
$book=IOFactory::load($path);$grid=$book->getSheetByName('对账')->toArray(null,false,false);$headers=$grid[0];
|
||||
$calcCol=array_search('核算运费',$headers,true);$settleCol=array_search('结算运费',$headers,true);
|
||||
$this->assertSame($calcCol+1,$settleCol);$this->assertEquals(10,$grid[1][$settleCol]);
|
||||
$this->assertSame(1,count(array_filter($headers,fn($h)=>$h==='结算运费')));$book->disconnectWorksheets();
|
||||
} finally {@unlink($path);}
|
||||
}
|
||||
|
||||
public function test_wujin_subsidy_is_directional_summed_once_and_exported_separately(): void
|
||||
{
|
||||
Storage::fake('local');
|
||||
|
||||
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