65 lines
3.0 KiB
PHP
65 lines
3.0 KiB
PHP
<?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;
|
||
}
|
||
}
|