325 lines
12 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 Modules\EcommerceFinance\Services\Freight;
/**
* 报价表(报价管理 values_json 单元格)解析:找表头、按省份取行、识别重量段表头、条码报价表。
* 与离线核算脚本(10 月核对过的口径)一一对应,单元格里的数字/文字按原样参与判断。
*/
final class QuoteSheet
{
public const CITY_KEYS = ['深圳', '舟山', '拉萨', '广州'];
public const PROVINCES = ['北京', '天津', '上海', '重庆', '河北', '山西', '辽宁', '吉林', '黑龙', '江苏', '浙江', '安徽', '福建', '江西', '山东', '河南', '湖北', '湖南', '广东', '海南', '四川', '贵州', '云南', '陕西', '甘肃', '青海', '台湾', '内蒙', '广西', '西藏', '宁夏', '新疆'];
private const HEADER_FIRST_CELLS = ['省份', '目的地', '地区', '公斤段', '条形码'];
private const BARCODE_RE = '/[A-Za-z]{2,}\d[A-Za-z0-9\-]{5,}/u';
/** 单元格转文字(对齐 Python str:整数值的小数写成 3.0,空/0 视为空)。 */
public static function text(mixed $cell): string
{
if ($cell === null || $cell === false || $cell === '' || $cell === 0 || $cell === 0.0) {
return '';
}
if (is_float($cell)) {
return floor($cell) == $cell && abs($cell) < 1e15 ? sprintf('%.1f', $cell) : (string) $cell;
}
return (string) $cell;
}
/** 数字单元格转 float;文字原样(去空白)返回;空返回 null。 */
public static function num(mixed $cell): float|string|null
{
if ($cell === null) {
return null;
}
if (is_int($cell) || is_float($cell)) {
return (float) $cell;
}
$t = trim((string) $cell);
if ($t !== '' && is_numeric($t)) {
return (float) $t;
}
return $t === '' ? null : $t;
}
/** 省份名归一到两字(黑龙/内蒙/广西/宁夏/新疆/西藏 前缀)。 */
public static function province(mixed $name): string
{
$s = (string) preg_replace('/\s/u', '', (string) ($name ?? ''));
foreach (['黑龙', '内蒙', '广西', '宁夏', '新疆', '西藏'] as $p) {
if (str_starts_with($s, $p)) {
return $p;
}
}
$s = (string) preg_replace('/((维吾尔|壮族|回族)?自治区|省|市)$/u', '', $s);
return mb_substr($s, 0, 2);
}
/**
* @param list<list<mixed>> $vals
* @return array{head:list<string>,rows:array<string,list<mixed>>,top:string}|null
*/
public static function parse(array $vals): ?array
{
$h = null;
foreach ($vals as $i => $r) {
if (is_array($r) && $r !== [] && in_array(str_replace(' ', '', trim(self::text($r[0] ?? null))), self::HEADER_FIRST_CELLS, true)) {
$h = $i;
break;
}
}
if ($h === null) {
return null;
}
$ncol = 0;
foreach ($vals as $r) {
$ncol = max($ncol, is_array($r) ? count($r) : 0);
}
$head = [];
for ($i = 0; $i < $ncol; $i++) {
$head[] = str_replace("\n", ' ', self::text($vals[$h][$i] ?? null));
}
$start = $h + 1;
$next = $vals[$h + 1] ?? [];
$c0 = is_array($next) && $next !== [] ? trim(self::text($next[0] ?? null)) : '';
if (is_array($next) && $next !== [] && in_array($c0, ['', '省份'], true) && self::anyTruthy(array_slice($next, 1))) {
for ($i = 0; $i < $ncol; $i++) {
$head[$i] = $head[$i] . ' ' . self::text($next[$i] ?? null);
}
$start = $h + 2;
}
$rows = [];
foreach (array_slice($vals, $start) as $r) {
if (! is_array($r) || $r === [] || ($r[0] ?? null) === null) {
continue;
}
$name = (string) preg_replace('/\s/u', '', self::rawText($r[0]));
if ($name === '' || mb_strlen($name) > 8) {
continue;
}
$key = in_array($name, ['深圳', '舟山', '拉萨'], true) ? $name : self::province($name);
$row = [];
for ($i = 0; $i < $ncol; $i++) {
$row[] = self::num($r[$i] ?? null);
}
$keys = [$key];
foreach (self::CITY_KEYS as $ck) { // 城市单独报价行(如 深圳市 / 深圳广州)
if (str_contains($name, $ck) && $ck !== $key) {
$keys[] = $ck;
}
}
foreach ($keys as $region) {
if (! array_key_exists($region, $rows) || self::replacesUnavailableRow($rows[$region], $row, $head)) {
$rows[$region] = $row;
}
}
}
$top = implode(' ', array_map(static fn ($c) => self::text($c), is_array($vals[0] ?? null) ? $vals[0] : []));
return ['head' => $head, 'rows' => $rows, 'top' => $top];
}
/** 被 Excel 存成日期序列号的公斤段表头还原为「月-日」。 */
public static function undate(string $text): string
{
if (! preg_match('/^4\d{4}(\.0+)?$/', trim($text))) {
return $text;
}
$date = (new \DateTimeImmutable('1899-12-30'))->modify('+' . (int) $text . ' days');
return $date->format('n') . '-' . $date->format('j');
}
/** 第一个匹配任一正则、且不匹配排除正则的表头列号(从 $start 起)。 */
public static function col(array $head, array $patterns, int $start = 1, array $exclude = []): ?int
{
for ($i = $start, $n = count($head); $i < $n; $i++) {
$t = $head[$i];
$hit = false;
foreach ($patterns as $p) {
if (preg_match('/' . $p . '/u', $t)) {
$hit = true;
break;
}
}
if (! $hit) {
continue;
}
foreach ($exclude as $e) {
if (preg_match('/' . $e . '/u', $t)) {
continue 2;
}
}
return $i;
}
return null;
}
/**
* 表头里的重量段:[下限, 上限, 列号]。识别 0-1kg、500g-1kg、300g、3kg、一口价 等写法。
*
* @param iterable<int> $cols
* @return list<array{0:float,1:float,2:int}>
*/
public static function bands(array $head, iterable $cols): array
{
$out = [];
foreach ($cols as $i) {
$t = str_replace([' ', '~', '~'], ['', '-', '-'], (string) ($head[$i] ?? ''));
$t = self::undate($t);
if (preg_match('/(\d+)g-([\d.]+)kg/iu', $t, $m)) {
$out[] = [(float) $m[1] / 1000, (float) $m[2], $i];
} elseif (preg_match('/^(\d+)g(一口价)?$/iu', $t, $m)) {
$out[] = [0.0, (float) $m[1] / 1000, $i];
} elseif (preg_match('/([\d.]+)\s*[-~]\s*([\d.]+)/u', $t, $m) && is_numeric($m[1]) && is_numeric($m[2])) {
$out[] = [(float) $m[1], (float) $m[2], $i];
} elseif (preg_match('/([\d.]+)\s*(kg|公斤|KG)/u', $t, $m) && is_numeric($m[1])) {
$out[] = [0.0, (float) $m[1], $i];
} elseif (str_contains($t, '一口价')) {
$out[] = [0.0, 1e9, $i];
}
}
return $out;
}
/** 文字里出现的省份(两字简称)。 */
public static function provincesIn(mixed $text): array
{
$t = (string) preg_replace('/\s/u', '', self::text($text));
$out = [];
foreach (self::PROVINCES as $p) {
if (str_contains($t, $p)) {
$out[$p] = true;
}
}
return $out;
}
/**
* 按条码报价的表:{条码: [[省份集合|null(其余), 价格]]}、不发省份、布局。
*
* @return array{0:array<string,list<array{0:?array,1:mixed}>>,1:array<string,bool>,2:string}
*/
public static function barcodeTable(array $vals): array
{
$table = [];
$nogo = [];
foreach ($vals as $r) {
foreach ((array) $r as $c) {
$s = self::text($c);
if ($s !== '' && str_contains($s, '不发') && ! preg_match(self::BARCODE_RE, $s)) {
$nogo += self::provincesIn($c);
}
}
}
$isBarcode = static fn ($c): bool => (bool) preg_match('/^' . trim(self::BARCODE_RE, '/u') . '$/u', trim(self::text($c)));
$rowsBc = array_values(array_filter($vals, static fn ($r) => is_array($r) && ($r[0] ?? null) && $isBarcode($r[0])));
if ($rowsBc !== []) {
$hdr = null;
foreach ($vals as $r) {
foreach ((array) $r as $c) {
$s = self::text($c);
if ($s !== '' && (str_contains($s, '剩余') || str_contains($s, '其余') || str_contains($s, '其他'))) {
$hdr = $r;
break 2;
}
}
}
$regions = [];
if ($hdr !== null) {
foreach ($hdr as $i => $c) {
$s = self::text($c);
if ($i === 0 || $s === '') {
continue;
}
$regions[] = [$i, (str_contains($s, '剩余') || str_contains($s, '其余') || str_contains($s, '其他')) ? null : self::provincesIn($c)];
}
} else {
$regions = [[1, null]];
}
foreach ($rowsBc as $r) {
$bc = mb_strtoupper(trim(self::text($r[0])));
$table[$bc] = array_map(static fn ($reg) => [$reg[1], self::num($r[$reg[0]] ?? null)], $regions);
}
return [$table, $nogo, 'rows'];
}
foreach ($vals as $hi => $r) {
$groups = [];
foreach ((array) $r as $i => $c) {
$s = self::text($c);
if ($s !== '' && preg_match_all(self::BARCODE_RE, $s, $mm)) {
$groups[] = [$i, array_map('mb_strtoupper', $mm[0])];
}
}
if ($groups === []) {
continue;
}
$provRows = [];
foreach (array_slice($vals, $hi + 1) as $rr) {
if (is_array($rr) && ($rr[0] ?? null)) {
$k = self::province($rr[0]);
if (in_array($k, self::PROVINCES, true)) {
$provRows[$k] = $rr;
}
}
}
foreach ($groups as [$i, $bcs]) {
foreach ($bcs as $bc) {
$list = [];
foreach ($provRows as $p => $rr) {
$list[] = [[$p => true], self::num($rr[$i] ?? null)];
}
$table[$bc] = $list;
}
}
return [$table, $nogo, 'cols'];
}
return [[], $nogo, 'none'];
}
private static function rawText(mixed $cell): string
{
return is_float($cell) ? self::text($cell) : (string) $cell;
}
/** 新增省份可能追加在表尾:仅用数值报价替换原来的全空/不发行,保留已有有效价格。 */
private static function replacesUnavailableRow(array $current, array $candidate, array $head): bool
{
$hasPrice = false;
foreach ($head as $i => $label) {
if ($i === 0 || preg_match('/备注|说明/u', $label)) {
continue;
}
if (($current[$i] ?? null) !== null && ! in_array(trim((string) $current[$i]), ['不发', '不发货'], true)) {
return false;
}
$hasPrice = $hasPrice || is_float($candidate[$i] ?? null);
}
return $hasPrice;
}
private static function anyTruthy(array $cells): bool
{
foreach ($cells as $c) {
if ($c !== null && $c !== '' && $c !== 0 && $c !== 0.0 && $c !== false) {
return true;
}
}
return false;
}
}