streamDownload(static function (): void { $book = new StreamingWorkbook(); $book->row('账单', self::HEADERS, true); $book->writeTo(fopen('php://output', 'wb')); }, $fileName); } /** * 校验上传的文件是不是按模板填的,不对就把前几处错误一起报出来。 * * @return array{rows:int,waybills:int,amount:float} */ public function validate(string $path, string $extension): array { try { $sheets = $this->reader->sheets($path, $extension); $rows = $sheets->current(); } catch (Throwable $error) { throw new RuntimeException('读不了这个文件:' . $error->getMessage()); } if ($rows === null) { throw new RuntimeException('文件是空的。'); } if (\App\Support\DropshipFreight\FactoryBillParser::skipWord((string) $sheets->key()) !== null) { throw new RuntimeException('请保留模板的「账单」工作表名称,不要改成汇总、对账或报价等名称。'); } $errors = []; $header = null; $count = 0; $amount = 0.0; $waybills = []; foreach ($rows as $index => $row) { $cells = array_map(static fn ($v): string => trim((string) $v), $row); if ($header === null) { $cells[0] = preg_replace('/^\x{FEFF}/u', '', $cells[0] ?? ''); $header = array_values(self::trimTail($cells)); if ($header !== self::HEADERS) { throw new RuntimeException('请用上传模板:第一行必须依次是「' . implode('、', self::HEADERS) . '」,现在是「' . implode('、', array_filter($header, static fn (string $h): bool => $h !== '')) . '」。'); } continue; } if (implode('', $cells) === '') { continue; } $line = (int) $index; $waybill = $cells[0] ?? ''; if (in_array($waybill, self::TOTAL_WORDS, true)) { continue; } if ($waybill === '') { $errors[] = '第 ' . $line . ' 行没有单号'; } elseif (Waybill::normalize($waybill) === null) { $errors[] = '第 ' . $line . ' 行单号格式不对,请使用完整单号文本'; } $freight = BillParser::number($cells[3] ?? null); if ($freight === null || ! is_finite($freight)) { $errors[] = '第 ' . $line . ' 行运费' . (($cells[3] ?? '') === '' ? '没填' : '「' . $cells[3] . '」不是数字'); } foreach ([2 => '重量', 5 => '面单', 6 => '费率'] as $col => $name) { $value = BillParser::number($cells[$col] ?? null); if (($cells[$col] ?? '') !== '' && ($value === null || ! is_finite($value))) { $errors[] = '第 ' . $line . ' 行' . $name . '「' . $cells[$col] . '」不是数字'; } } if (count($errors) >= self::MAX_ERRORS) { break; } $count++; if ($count > 100000) throw new RuntimeException('每份账单最多100,000行,请分批上传。'); $amount += (float) $freight; $waybills[$waybill] = true; } if ($header === null) { throw new RuntimeException('文件是空的。'); } if ($errors !== []) { throw new RuntimeException('账单有 ' . (count($errors) >= self::MAX_ERRORS ? '多处' : count($errors) . ' 处') . '要改:' . implode(';', array_slice($errors, 0, self::MAX_ERRORS)) . '。'); } if ($count === 0) { throw new RuntimeException('模板里还没有填账单明细。'); } $sheets->next(); if ($sheets->valid()) throw new RuntimeException('请只保留模板的一张账单工作表,不要附带其他工作表。'); return ['rows' => $count, 'waybills' => count($waybills), 'amount' => round($amount, 2)]; } /** @param list $cells */ private static function trimTail(array $cells): array { while ($cells !== [] && end($cells) === '') { array_pop($cells); } return $cells; } }