CaiWuXiTong/app/Support/CourierQuoteConfirmation.php

92 lines
3.4 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
namespace App\Support;
use App\Models\Business\CourierQuoteVersion;
final class CourierQuoteConfirmation
{
public function data(CourierQuoteVersion $version): array
{
$version->loadMissing(['change.items']);
$values = $this->decodeMatrix($version->values_json);
$nextVersion = CourierQuoteVersion::query()
->where('carrier_name', $version->carrier_name)
->where('quote_type', $version->quote_type)
->where('effective_date', '>', $version->effective_date)
->orderBy('effective_date')
->first();
return [
'version_id' => $version->id,
'version_code' => $version->version_code,
'party_a' => company((int) $version->company_id)?->name ?: '当前公司',
'party_b' => $version->carrier_name,
'carrier_name' => $version->carrier_name,
'quote_type' => $version->quote_type,
'effective_date' => $version->effective_date?->toDateString(),
'expiry_date' => $nextVersion?->effective_date?->copy()->subDay()->toDateString() ?: '长期',
'face_fee' => $this->matrixMetric($values, ['面单费', '面单费用', '面单']),
'bubble_coefficient' => $this->matrixMetric($values, ['计泡系数', '泡系数', '计泡']),
'values' => $values,
'formulas' => $this->decodeMatrix($version->formulas_json),
];
}
private function decodeMatrix(?string $json): array
{
if (blank($json)) {
return [];
}
$decoded = json_decode($json, true);
return is_array($decoded) ? $decoded : [];
}
private function matrixMetric(array $values, array $labels): string
{
foreach ($values as $rowIndex => $row) {
if (! is_array($row)) {
continue;
}
foreach (array_values($row) as $columnIndex => $cell) {
$text = trim((string) $cell);
foreach ($labels as $label) {
if ($text !== $label && ! str_contains($text, $label)) {
continue;
}
$inline = trim((string) preg_replace('/^.*?' . preg_quote($label, '/') . '\\s*[::=]?\\s*/u', '', $text));
if ($inline !== '' && $inline !== $text && $inline !== $label) {
return $inline;
}
$columnValues = [];
foreach (array_slice($values, $rowIndex + 1) as $nextRow) {
$value = is_array($nextRow) ? ($nextRow[$columnIndex] ?? null) : null;
if ($value !== null && trim((string) $value) !== '') {
$columnValues[] = trim((string) $value);
}
}
$columnValues = array_values(array_unique($columnValues));
if (count($columnValues) === 1) {
return $columnValues[0];
}
if (count($columnValues) > 1) {
return '详见报价明细';
}
$adjacent = $row[$columnIndex + 1] ?? null;
if ($adjacent !== null && trim((string) $adjacent) !== '') {
return trim((string) $adjacent);
}
}
}
}
return '按报价明细';
}
}