CaiWuXiTong/modules/EcommerceFinance/Services/ShippingMeasuredWeightImporter.php

113 lines
4.9 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;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;
use RuntimeException;
class ShippingMeasuredWeightImporter
{
private const HEADERS = ['条形码', '称重重量', '适用快递名称'];
private const MAX_KEYS = 50000;
/** @return array{source_rows:int, keys:int} */
public function import(string $path, int $companyId, int $userId): array
{
$rows = $this->read($path);
$now = now();
DB::transaction(static function () use ($rows, $companyId, $userId, $now): void {
foreach (array_chunk($rows['weights'], 500) as $chunk) {
DB::table('shipping_measured_weights')->upsert(
array_map(static fn (array $weight): array => $weight + [
'company_id' => $companyId,
'updated_by' => $userId,
'created_at' => $now,
'updated_at' => $now,
], $chunk),
['company_id', 'carrier_name', 'barcode'],
['weight_kg', 'updated_by', 'updated_at'],
);
}
}, 3);
// 核算运费用称重重量:导入后这些快递的核算结果从核算起始日起重算
\Modules\EcommerceFinance\Services\Freight\ShippingFreightService::queueMeasuredCarriers(array_column($rows['weights'], 'carrier_name'));
return ['source_rows' => $rows['source_rows'], 'keys' => count($rows['weights'])];
}
/** @return array{source_rows:int, weights:array<string,array{carrier_name:string,barcode:string,weight_kg:float}>} */
private function read(string $path): array
{
$reader = PayablesWorkbookStreamReader::forFile($path, 'xlsx');
$weights = [];
$sourceRows = 0;
$hasHeader = false;
try {
foreach ($reader->rows(0, null, 10002) as $number => $cells) {
$row = array_map(static fn ($value): string => trim((string) $value), $cells);
$nonBlank = array_filter($row, static fn (string $value): bool => $value !== '');
if ($number === 1) {
if (array_values($nonBlank) !== self::HEADERS || array_keys($nonBlank) !== [0, 1, 2]) {
$this->invalid('第一行表头须依次为「条形码」「称重重量」「适用快递名称」。');
}
$hasHeader = true;
continue;
}
if (! $hasHeader) {
$this->invalid('第一行缺少导入表头。');
}
if ($number > 10001) {
$this->invalid('一次最多导入 10,000 行称重数据。');
}
if ($nonBlank === []) {
continue;
}
$barcode = mb_strtoupper($row[0] ?? '');
$weight = $row[1] ?? '';
$carriers = preg_split('/[、,,;;\r\n]+/u', $row[2] ?? '');
$carriers = array_unique(array_filter(array_map('trim', $carriers ?: []), static fn (string $name): bool => $name !== ''));
if ($barcode === '' || mb_strlen($barcode) > 128 || str_contains($barcode, "\0")) {
$this->invalid("第 {$number} 行条形码为空或无效。");
}
$kg = is_numeric($weight) ? round((float) $weight, 4) : 0;
if (! is_finite((float) $kg) || $kg <= 0 || $kg >= 100000000) {
$this->invalid("第 {$number} 行称重重量须为大于 0 的公斤数。");
}
if ($carriers === [] || array_diff_key($nonBlank, [0 => true, 1 => true, 2 => true]) !== []) {
$this->invalid("第 {$number} 行请填写适用快递名称,并只使用模板的三列。");
}
foreach ($carriers as $carrier) {
if (mb_strlen($carrier) > 128 || str_contains($carrier, "\0")) {
$this->invalid("第 {$number} 行适用快递名称无效。");
}
$weights[$carrier . "\0" . $barcode] = ['carrier_name' => $carrier, 'barcode' => $barcode, 'weight_kg' => $kg];
}
if (count($weights) > self::MAX_KEYS) {
$this->invalid('拆分多家快递后最多保存 50,000 条称重记录。');
}
$sourceRows++;
}
} catch (RuntimeException $exception) {
$this->invalid('无法读取此 XLSX 文件,请确认文件完整后重试。');
}
if ($weights === []) {
$this->invalid('文件中没有可导入的称重数据。');
}
return ['source_rows' => $sourceRows, 'weights' => $weights];
}
private function invalid(string $message): never
{
throw ValidationException::withMessages(['measured_weight_file' => $message]);
}
}