'{month}月{factory}', 'headers' => ['原始', '简尚核对', '差异'], 'labels' => ['运费', '记账', '代发', '退货'], 'total' => '合计']; /** * 从手工做好的代发账单里找汇总块:标题格以「X月」开头,右边三格里有「简尚…」和「差异/差额」。优先看名字带「汇总」的表。 * * @param iterable>> $sheets 表名 => 行 * @return array{title:string,headers:list,labels:list,total:string}|null */ public static function find(iterable $sheets): ?array { $ordered = []; foreach ($sheets as $name => $rows) { $rows = self::firstRows($rows, 60); str_contains((string) $name, '汇总') ? array_unshift($ordered, $rows) : $ordered[] = $rows; } foreach ($ordered as $rows) { if (($template = self::parse($rows)) !== null) { return $template; } } return null; } /** @param list> $rows */ public static function parse(array $rows): ?array { foreach ($rows as $i => $row) { $row = array_values($row); foreach ($row as $c => $value) { if (! is_string($value) || ! preg_match('/^\s*(\d{4}[.年])?\d{1,2}月/u', $value)) { continue; } $headers = array_map(static fn ($v): string => trim((string) $v), array_slice($row, $c + 1, 3)); if (count($headers) < 3 || ! array_filter($headers, static fn (string $h): bool => str_contains($h, '简尚')) || ! array_filter($headers, static fn (string $h): bool => str_contains($h, '差'))) { continue; } $labels = []; $total = '合计'; foreach (array_slice($rows, $i + 1, 30) as $next) { $next = array_values($next); $label = trim((string) ($next[$c] ?? '')); if ($label === '') { if ($labels !== []) { break; } continue; } if (preg_match('/^[\d.\-\s]+$/u', $label)) { continue; } if (in_array($label, self::TOTALS, true)) { $total = $label; break; } $labels[] = $label; } if ($labels === []) { continue; } return ['title' => trim($value), 'headers' => $headers, 'labels' => $labels, 'total' => $total]; } } return null; } /** 模板月份顺延 $delta 个月(标题和类目名里的「X月」)。 */ public static function roll(array $template, int $delta): array { $template['title'] = SummaryTemplate::roll((string) $template['title'], $delta); $template['labels'] = array_map(static fn (string $l): string => SummaryTemplate::roll($l, $delta), array_values($template['labels'])); return $template; } public static function fallback(string $month, string $factory): array { $template = self::DEFAULT; $template['title'] = str_replace(['{month}', '{factory}'], [(string) (int) substr($month, 5, 2), $factory], $template['title']); return $template; } /** 「运费」「10月运费」「运费10月」算运费行(系统填)。 */ public static function isFreight(string $label): bool { return (bool) preg_match('/^((\d{1,2}月)?运费|运费(\d{1,2}月)?)$/u', trim($label)); } /** 标题去掉月份,剩下的是厂家名(可能为空,如「10月」)。 */ public static function titleName(string $title): string { return trim(preg_replace('/^\s*(\d{4}[.年])?\d{1,2}月(份)?/u', '', $title) ?? ''); } /** @return list> */ private static function firstRows(iterable $rows, int $limit): array { $result = []; foreach ($rows as $row) { $result[] = (array) $row; if (count($result) >= $limit) { break; } } return $result; } }