报价变更支持新增省份 #1433

Open
limeng wants to merge 2 commits from feature/limeng-quote-add-province into main
9 changed files with 182 additions and 4 deletions

View File

@ -381,6 +381,12 @@ class CourierQuoteChanges extends Controller
'summary' => ['required', 'string', 'min:2', 'max:2000'],
'quote_notes' => ['sometimes', 'array', 'max:500'],
'quote_notes.*' => ['nullable', 'string', 'max:10000'],
'province_additions' => ['sometimes', 'array', 'max:34'],
'province_additions.*' => ['array:region,prices,note'],
'province_additions.*.region' => ['required', 'string', 'max:16', 'regex:/^[\p{Han}]+$/u'],
'province_additions.*.prices' => ['required', 'array'],
'province_additions.*.prices.*' => ['required', 'numeric', 'min:0', 'decimal:0,4'],
'province_additions.*.note' => ['nullable', 'string', 'max:10000'],
'items' => ['required', 'array', 'min:1', 'max:500'],
'items.*.source_cell' => ['required', 'regex:/^[A-Z]+[1-9][0-9]*$/'],
'items.*.source_row' => ['required', 'integer', 'min:0'],

View File

@ -72,7 +72,7 @@ class CourierQuoteChange extends Model
public function hasQuotePayload(): bool
{
return is_array($this->quote_payload) && array_diff_key($this->quote_payload, ['execution_periods' => true, 'quote_notes' => true]) !== [];
return is_array($this->quote_payload) && array_diff_key($this->quote_payload, ['execution_periods' => true, 'quote_notes' => true, 'province_additions' => true]) !== [];
}
public function isStockQuote(): bool

View File

@ -95,7 +95,10 @@ final class CourierQuoteChangeExport
$values[$item->source_row][$item->source_column] = $item->new_amount;
}
return [$values, $source['billing_rules'] ?? null];
$source['values'] = $values;
$source = CourierQuoteProvinceAdditions::apply($source, $change->quote_payload['province_additions'] ?? []);
return [$source['values'], $source['billing_rules'] ?? null];
}
private function text(Worksheet $sheet, string $address, mixed $value): void

View File

@ -29,6 +29,11 @@ final class CourierQuoteChangeService
$data = CourierQuotePeriods::normalize($data);
$data['quote_payload'] = CourierQuotePeriods::payload($data['quote_payload'] ?? null, $data['execution_periods']);
$data['quote_payload'] = CourierQuoteNotes::payload($data['quote_payload'], $data, $source);
unset($data['quote_payload']['province_additions']);
if (!empty($data['province_additions'])) {
CourierQuoteProvinceAdditions::apply($source, $data['province_additions']);
$data['quote_payload']['province_additions'] = $data['province_additions'];
}
}
return DB::transaction(function () use ($data, $userId, $source): CourierQuoteChange {
@ -72,6 +77,11 @@ final class CourierQuoteChangeService
$data = CourierQuotePeriods::normalize($data + ['end_date' => $change->end_date?->toDateString()]);
$data['quote_payload'] = CourierQuotePeriods::payload($change->quote_payload, $data['execution_periods']);
$data['quote_payload'] = CourierQuoteNotes::payload($data['quote_payload'], $data, $source);
unset($data['quote_payload']['province_additions']);
if (!empty($data['province_additions'])) {
CourierQuoteProvinceAdditions::apply($source, $data['province_additions']);
$data['quote_payload']['province_additions'] = $data['province_additions'];
}
}
return DB::transaction(function () use ($change, $data, $userId, $source): CourierQuoteChange {
@ -103,7 +113,7 @@ final class CourierQuoteChangeService
{
$this->ensureEditableBy($change, $userId);
if (! ($change->isStockQuote() && filled($change->proposed_values_json)) && $change->items()->count() === 0 && empty($change->quote_payload['quote_notes'])) {
if (! ($change->isStockQuote() && filled($change->proposed_values_json)) && $change->items()->count() === 0 && empty($change->quote_payload['quote_notes']) && empty($change->quote_payload['province_additions'])) {
throw ValidationException::withMessages(['items' => '至少需要一条发生变化的报价明细。']);
}
@ -231,6 +241,13 @@ final class CourierQuoteChangeService
$values[$item->source_row][$item->source_column] = $item->new_amount;
}
$expanded = CourierQuoteProvinceAdditions::apply(
['values' => $values, 'formulas' => $formulas],
$change->quote_payload['province_additions'] ?? []
);
$values = $expanded['values'];
$formulas = $expanded['formulas'];
$importedVersionCount = collect($this->snapshot->load()['quotes'] ?? [])
->whereNull('source_change_id')
->count();
@ -351,7 +368,7 @@ final class CourierQuoteChangeService
]);
}
if ($change->items()->count() === 0 && empty($change->quote_payload['quote_notes'])) {
if ($change->items()->count() === 0 && empty($change->quote_payload['quote_notes']) && empty($change->quote_payload['province_additions'])) {
throw ValidationException::withMessages(['items' => '至少需要一条原价格与新价格不同的变价明细。']);
}
}
@ -399,6 +416,7 @@ final class CourierQuoteChangeService
'end_date' => $change->end_date?->toDateString(),
'execution_periods' => $change->executionPeriods(),
'quote_notes' => $change->quote_payload['quote_notes'] ?? [],
'province_additions' => $change->quote_payload['province_additions'] ?? [],
'is_retrospective' => $change->isRetrospective(),
'recalculation_status' => $change->recalculation_status,
'recalculation_note' => $change->recalculation_note,

View File

@ -0,0 +1,64 @@
<?php
namespace App\Support;
use App\Http\Controllers\Business\CourierQuoteSignatures;
use Illuminate\Validation\ValidationException;
final class CourierQuoteProvinceAdditions
{
public static function fields(array $source): array
{
$layout = CourierQuoteSignatures::quoteLayout($source['values']);
$header = $layout['table'][0] ?? [];
$rows = array_slice($layout['table'], 1);
$columns = [];
$remarks = null;
foreach ($header as $column => $label) {
if ($column === 0 || blank($label)) continue;
if (preg_match('/^(报价备注|备注|说明)[::]?$/u', trim($label))) {
$remarks = $column;
} elseif (collect($rows)->contains(fn ($row) => is_numeric($row[$column] ?? null))) {
$columns[$column] = (string) $label;
}
}
return [$columns, $remarks, array_map(fn ($row) => (string) ($row[0] ?? ''), $rows), $layout['row_keys']];
}
public static function apply(array $source, array $additions): array
{
if ($additions === []) return $source;
[$columns, $remarks, $regions, $rowKeys] = self::fields($source);
$normalize = static fn ($name) => preg_replace('/(?:壮族自治区|回族自治区|维吾尔自治区|自治区|特别行政区|省|市)$/u', '', trim($name));
$existing = array_map($normalize, preg_split('/[、,,\/\s;;++]+/u', implode('、', $regions), -1, PREG_SPLIT_NO_EMPTY));
$rows = [];
foreach ($additions as $index => $addition) {
$region = $normalize($addition['region']);
if ($region === '' || in_array($region, $existing, true)) {
throw ValidationException::withMessages(["province_additions.$index.region" => '省份已存在,请直接编辑原报价行。']);
}
if ($columns === [] || array_keys($columns) !== array_keys(array_intersect_key($columns, $addition['prices'])) || array_diff_key($addition['prices'], $columns)) {
throw ValidationException::withMessages(["province_additions.$index.prices" => '请填写该省份的全部价格列。']);
}
$existing[] = $region;
$row = array_fill(0, max(array_keys($columns)) + 1, null);
$row[0] = $addition['region'];
foreach ($columns as $column => $label) {
$row[$column] = (float) $addition['prices'][$column];
}
if ($remarks !== null) $row[$remarks] = $addition['note'] ?? null;
ksort($row);
$rows[] = array_replace(array_fill(0, max(array_keys($row)) + 1, null), $row);
}
$offset = (int) end($rowKeys) + 1;
$formulas = array_replace(array_fill(0, count($source['values']), []), $source['formulas']);
array_splice($source['values'], $offset, 0, $rows);
array_splice($formulas, $offset, 0, array_fill(0, count($rows), []));
$source['formulas'] = $formulas;
return $source;
}
}

View File

@ -202,6 +202,21 @@
</tbody>
</table>
</div>
@php([$provinceColumns, $provinceRemarks] = \App\Support\CourierQuoteProvinceAdditions::fields($source))
@if($provinceColumns)
<div data-province-editor>
<p class="quote-change-panel__hint">仅新增原报价没有的省份。新增报价随本次变价审核生效。</p>
<div data-province-rows>
@foreach(old('province_additions', $change?->quote_payload['province_additions'] ?? []) as $provinceIndex => $province)
@include('business.pages.courier-payables.quote-change-province-fields')
@endforeach
</div>
<template data-province-template>
@include('business.pages.courier-payables.quote-change-province-fields', ['provinceIndex' => '__INDEX__', 'province' => []])
</template>
<button type="button" class="quote-change-button" data-add-province>+ 新增省份</button>
</div>
@endif
</div>
</section>
@ -227,6 +242,25 @@
var count = root.querySelector('[data-changed-count]');
var effectiveDate = root.querySelector('[data-effective-date]');
var retrospectiveAlert = root.querySelector('[data-retrospective-alert]');
const provinceEditor = root.querySelector('[data-province-editor]');
if (provinceEditor) {
const provinceRows = provinceEditor.querySelector('[data-province-rows]');
const provinceTemplate = provinceEditor.querySelector('[data-province-template]');
let nextProvinceIndex = Math.max(-1, ...Array.from(provinceRows.children, row => Number(row.dataset.provinceIndex))) + 1;
provinceEditor.querySelector('[data-add-province]').addEventListener('click', function () {
provinceRows.insertAdjacentHTML('beforeend', provinceTemplate.innerHTML.replaceAll('__INDEX__', String(nextProvinceIndex++)));
const newRow = provinceRows.lastElementChild;
newRow.querySelectorAll('[data-field-name]').forEach(field => {
field.name = field.dataset.fieldName;
});
newRow.querySelector('input').focus();
});
provinceRows.addEventListener('click', function (event) {
const removeButton = event.target.closest('[data-remove-province]');
if (removeButton) removeButton.closest('fieldset').remove();
});
}
function refreshRetrospective() {
if (!effectiveDate || !retrospectiveAlert) return;
var isRetrospective = effectiveDate.value !== '' && effectiveDate.value < root.dataset.today;

View File

@ -0,0 +1,17 @@
<fieldset data-province-index="{{ $provinceIndex }}" class="quote-change-panel__body">
<legend>新增省份 · 原报价无</legend>
<label>省份
<input class="quote-change-control" @if($provinceIndex === '__INDEX__') data-field-name @else name @endif="province_additions[{{ $provinceIndex }}][region]" value="{{ $province['region'] ?? '' }}" maxlength="16" required>
</label>
@foreach($provinceColumns as $column => $label)
<label>{{ $label }}
<input class="quote-change-price-input" type="number" min="0" step="0.0001" @if($provinceIndex === '__INDEX__') data-field-name @else name @endif="province_additions[{{ $provinceIndex }}][prices][{{ $column }}]" value="{{ $province['prices'][$column] ?? '' }}" required>
</label>
@endforeach
@if($provinceRemarks !== null)
<label>报价备注
<textarea class="quote-change-control" @if($provinceIndex === '__INDEX__') data-field-name @else name @endif="province_additions[{{ $provinceIndex }}][note]" maxlength="10000">{{ $province['note'] ?? '' }}</textarea>
</label>
@endif
<button type="button" class="quote-change-button" data-remove-province>移除</button>
</fieldset>

View File

@ -106,6 +106,16 @@
<div><dt>签署状态</dt><dd>{{ $change->version?->signatureLabel() ?? '未进入签署' }}</dd></div>
</dl>
<div class="quote-review__summary"><strong>变更依据与说明</strong><br>{{ $change->summary }}</div>
@if($change->quote_payload['province_additions'] ?? [])
<div>
<strong>新增省份</strong>
<ul>
@foreach($change->quote_payload['province_additions'] as $province)
<li>{{ $province['region'] }} · {{ implode(' / ', $province['prices']) }} {{ $province['note'] ?? '' }}</li>
@endforeach
</ul>
</div>
@endif
@if($change->quote_payload['quote_notes'] ?? [])
<div class="quote-review__summary"><strong>报价备注修改</strong>
@foreach($change->quote_payload['quote_notes'] as $note)

View File

@ -255,6 +255,32 @@ class CourierQuoteChangeWorkflowTest extends FeatureTestCase
$this->assertSame('QB-002', app(QuoteManagementSnapshot::class)->load()['quotes'][1]['id']);
}
public function test_a_province_can_be_added_without_changing_existing_prices(): void
{
$payload = $this->validPayload();
$payload['items'][0]['new_amount'] = $payload['items'][0]['original_amount'];
$payload['province_additions'] = [['region' => '浙江', 'prices' => [1 => '0', 2 => '1.2'], 'note' => '新增线路']];
$duplicate = $payload;
$duplicate['province_additions'][0]['region'] = '江苏';
$this->withExceptionHandling()->loginAs()->post(route('business.courier-quote-changes.store'), $duplicate)
->assertSessionHasErrors('province_additions.0.region');
$this->withoutExceptionHandling();
$this->post(route('business.courier-quote-changes.store'), $payload)->assertSessionHasNoErrors();
$change = CourierQuoteChange::firstOrFail();
$this->assertCount(0, $change->items);
$this->get(route('business.courier-quote-changes.edit', $change))->assertOk()->assertSee('浙江');
$this->post(route('business.courier-quote-changes.submit', $change))->assertSessionHasNoErrors();
$this->loginAs($this->createReviewer(), $this->company)
->post(route('business.courier-quote-changes.approve', $change))
->assertSessionHasNoErrors();
$values = json_decode(CourierQuoteVersion::firstOrFail()->values_json, true, 512, JSON_THROW_ON_ERROR);
$this->assertEquals(['浙江', 0, 1.2, '新增线路'], $values[3]);
$this->assertCount(3, app(QuoteManagementSnapshot::class)->load()['quotes'][0]['values']);
}
public function test_approving_historical_change_blocks_automatic_compensation_and_records_reason(): void
{
$payload = $this->validPayload();