360 lines
17 KiB
PHP
360 lines
17 KiB
PHP
<?php
|
||
|
||
namespace App\Support\DropshipFreight;
|
||
|
||
use App\Support\CourierBills\CourierBillStore;
|
||
use App\Support\CourierBills\ShippingLookup;
|
||
use Illuminate\Database\ConnectionInterface;
|
||
use Illuminate\Http\UploadedFile;
|
||
use Illuminate\Support\Facades\DB;
|
||
use Illuminate\Support\Facades\Storage;
|
||
use Illuminate\Support\Str;
|
||
use RuntimeException;
|
||
use Throwable;
|
||
|
||
/**
|
||
* 代发厂家清单、厂家账单上传入库。
|
||
*
|
||
* 代发运费 = 从厂家代发仓发出、快递名称1 含厂家关键字、且不是自有快递(快递账单对账分组里的快递名称1)的包裹运费。
|
||
*/
|
||
final class DropshipFreightStore
|
||
{
|
||
public const EXTENSIONS = ['xlsx', 'xls', 'csv', 'zip'];
|
||
private const DISK = 'local';
|
||
/** 在这么多个仓库都出现的快递名称1 当通用快递(京喜京东快递、线下快递、中铁物流……),不算哪家厂家的代发快递。 */
|
||
private const GENERIC_WAREHOUSES = 3;
|
||
|
||
public function __construct(
|
||
private readonly FactoryBillParser $parser,
|
||
private readonly ShippingLookup $shipping,
|
||
private readonly CourierBillStore $courierBills,
|
||
) {}
|
||
|
||
public function db(): ConnectionInterface
|
||
{
|
||
return DB::connection('business_mirror');
|
||
}
|
||
|
||
/** @return list<object> 厂家,keyword_list 已拆成数组 */
|
||
public function factories(): array
|
||
{
|
||
return $this->db()->table('dropship_factories')->orderBy('name')->get()->map(static function ($factory) {
|
||
$factory->keyword_list = self::splitKeywords((string) $factory->keywords);
|
||
|
||
return $factory;
|
||
})->all();
|
||
}
|
||
|
||
/** @param array{name:string,warehouse:string,keywords:string,note?:?string} $data */
|
||
public function saveFactory(?int $id, array $data): int
|
||
{
|
||
$keywords = self::splitKeywords($data['keywords']);
|
||
if ($keywords === []) {
|
||
throw new RuntimeException('至少填一个代发快递关键字。');
|
||
}
|
||
$values = ['name' => trim($data['name']), 'warehouse' => trim($data['warehouse']), 'keywords' => implode(',', $keywords),
|
||
'note' => self::blank($data['note'] ?? null), 'updated_at' => now()];
|
||
$same = $this->db()->table('dropship_factories')->where('name', $values['name'])->value('id');
|
||
if ($same !== null && (int) $same !== $id) {
|
||
throw new RuntimeException('厂家「' . $values['name'] . '」已经有了。');
|
||
}
|
||
if ($id === null) {
|
||
return (int) $this->db()->table('dropship_factories')->insertGetId($values + ['created_at' => now()]);
|
||
}
|
||
$this->db()->table('dropship_factories')->where('id', $id)->update($values);
|
||
|
||
return $id;
|
||
}
|
||
|
||
public function deleteFactory(int $id): void
|
||
{
|
||
if ($this->db()->table('dropship_bill_files')->where('factory_id', $id)->exists()) {
|
||
throw new RuntimeException('这家厂家已有上传的账单,先删掉账单文件再删厂家。');
|
||
}
|
||
$this->db()->table('dropship_factories')->where('id', $id)->delete();
|
||
}
|
||
|
||
/** 自有快递:快递账单对账分组里的全部快递名称1。自有快递不给代发仓结算运费。 */
|
||
public function ownExpressNames(): array
|
||
{
|
||
try {
|
||
return collect($this->courierBills->groups())->flatMap(static fn ($group): array => $group->express_names)
|
||
->map(static fn ($name): string => trim((string) $name))->filter()->unique()->values()->all();
|
||
} catch (Throwable) {
|
||
return [];
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 按某月发货数据生成厂家清单(只补还没有的代发仓):
|
||
* 「工厂-…代发仓」发出的快递名称1,去掉自有快递和通用快递后剩下的就是这家的代发快递,关键字取它们共同的部分。
|
||
*
|
||
* @return array{created:list<string>,skipped:list<string>}
|
||
*/
|
||
public function generate(string $month): array
|
||
{
|
||
[$from, $to] = self::monthRange($month);
|
||
$rows = $this->shipping->connection()->table('jst_oms_shipping')
|
||
->where('ship_time', '>=', $from)->where('ship_time', '<', $to)
|
||
->groupBy('warehouse_name', 'express_name1', 'supplier_name')
|
||
->selectRaw('warehouse_name, express_name1, supplier_name, COUNT(DISTINCT express_no) as n')->get();
|
||
$own = array_flip($this->ownExpressNames());
|
||
$warehousesOf = [];
|
||
$byWarehouse = [];
|
||
$suppliers = [];
|
||
foreach ($rows as $row) {
|
||
$warehouse = trim((string) $row->warehouse_name);
|
||
$express = trim((string) $row->express_name1);
|
||
if ($warehouse === '' || $express === '') {
|
||
continue;
|
||
}
|
||
$warehousesOf[$express][$warehouse] = true;
|
||
if (str_starts_with($warehouse, '工厂-') && str_ends_with($warehouse, '代发仓')) {
|
||
$byWarehouse[$warehouse][$express] = ($byWarehouse[$warehouse][$express] ?? 0) + (int) $row->n;
|
||
foreach (preg_split('/[,,、]/u', (string) $row->supplier_name) ?: [] as $supplier) {
|
||
if (($supplier = trim($supplier)) !== '') {
|
||
$suppliers[$warehouse][$supplier] = ($suppliers[$warehouse][$supplier] ?? 0) + (int) $row->n;
|
||
}
|
||
}
|
||
}
|
||
}
|
||
$existing = collect($this->factories());
|
||
$created = [];
|
||
$skipped = [];
|
||
ksort($byWarehouse);
|
||
foreach ($byWarehouse as $warehouse => $expresses) {
|
||
if ($existing->contains('warehouse', $warehouse)) {
|
||
continue;
|
||
}
|
||
$candidates = array_values(array_filter(array_keys($expresses),
|
||
static fn (string $e): bool => ! isset($own[$e]) && count($warehousesOf[$e] ?? []) < self::GENERIC_WAREHOUSES));
|
||
if ($candidates === []) {
|
||
$skipped[] = $warehouse . '(只有自有快递或通用快递)';
|
||
continue;
|
||
}
|
||
$core = self::warehouseCore($warehouse);
|
||
$named = array_values(array_filter($candidates, static fn (string $e): bool => self::commonPart([$e, $core]) !== ''));
|
||
// 关键字尽量取厂家名(代发仓核心名)里的字,口径同手工:「卿德客申通」「卿德客极兔」→「卿德客」
|
||
$shared = $named !== [] ? self::commonPart([...$named, $core]) : '';
|
||
$keywords = $shared !== '' ? [$shared] : self::keywordsFor($named !== [] ? $named : $candidates);
|
||
$names = $suppliers[$warehouse] ?? [];
|
||
arsort($names);
|
||
$name = (string) (array_key_first($names) ?? $core);
|
||
if ($existing->contains('name', $name)) {
|
||
$name .= '(' . $core . ')';
|
||
}
|
||
$this->saveFactory(null, ['name' => $name, 'warehouse' => $warehouse, 'keywords' => implode(',', $keywords),
|
||
'note' => '按 ' . $month . ' 发货数据生成:' . implode('、', $named !== [] ? $named : $candidates)]);
|
||
$existing->push((object) ['name' => $name, 'warehouse' => $warehouse]);
|
||
$created[] = $name;
|
||
}
|
||
|
||
return ['created' => $created, 'skipped' => $skipped];
|
||
}
|
||
|
||
/**
|
||
* @param list<UploadedFile> $files
|
||
* @return list<int> 文件 id
|
||
*/
|
||
public function upload(array $files, string $month, string $user): array
|
||
{
|
||
$factories = $this->factories();
|
||
$ids = [];
|
||
foreach ($files as $file) {
|
||
if (strtolower($file->getClientOriginalExtension()) === 'zip') {
|
||
foreach ($this->courierBills->unzip((string) $file->getRealPath()) as [$name, $path]) {
|
||
$ids[] = $this->register($name, $path, $month, $factories, $user);
|
||
}
|
||
continue;
|
||
}
|
||
$ids[] = $this->register($file->getClientOriginalName(), (string) $file->getRealPath(), $month, $factories, $user);
|
||
}
|
||
|
||
return $ids;
|
||
}
|
||
|
||
public function assign(int $fileId, int $factoryId): void
|
||
{
|
||
$file = $this->db()->table('dropship_bill_files')->find($fileId);
|
||
if ($file === null || $file->status !== 'pending_factory') {
|
||
throw new RuntimeException('这个文件不是待选厂家状态。');
|
||
}
|
||
if (! $this->db()->table('dropship_factories')->where('id', $factoryId)->exists()) {
|
||
throw new RuntimeException('厂家不存在。');
|
||
}
|
||
$this->ingest($fileId, $factoryId);
|
||
}
|
||
|
||
public function deleteFile(int $fileId): void
|
||
{
|
||
$file = $this->db()->table('dropship_bill_files')->find($fileId);
|
||
if ($file === null) {
|
||
return;
|
||
}
|
||
$this->db()->transaction(function () use ($file): void {
|
||
$this->db()->table('dropship_bill_lines')->where('file_id', $file->id)->delete();
|
||
$this->db()->table('dropship_bill_files')->where('id', $file->id)->delete();
|
||
});
|
||
Storage::disk(self::DISK)->delete($file->stored_path);
|
||
}
|
||
|
||
/** @param list<object> $factories */
|
||
private function register(string $name, string $path, string $month, array $factories, string $user): int
|
||
{
|
||
$extension = strtolower(pathinfo($name, PATHINFO_EXTENSION));
|
||
$stored = 'dropship-bills/' . $month . '/' . Str::uuid() . '.' . $extension;
|
||
Storage::disk(self::DISK)->put($stored, fopen($path, 'rb'));
|
||
$factory = self::identify($name, $factories);
|
||
$id = (int) $this->db()->table('dropship_bill_files')->insertGetId([
|
||
'bill_month' => $month, 'original_name' => mb_substr($name, 0, 255), 'stored_path' => $stored, 'status' => 'pending_factory',
|
||
'message' => $factory === null ? '文件名里没认出是哪家厂家,请选择厂家' : null,
|
||
'uploaded_by' => mb_substr($user, 0, 64), 'created_at' => now(), 'updated_at' => now(),
|
||
]);
|
||
if (! in_array($extension, ['xlsx', 'xls', 'csv'], true)) {
|
||
$this->db()->table('dropship_bill_files')->where('id', $id)->update(['status' => 'failed', 'message' => '不支持的文件类型']);
|
||
} elseif ($factory !== null) {
|
||
$this->ingest($id, (int) $factory->id);
|
||
}
|
||
|
||
return $id;
|
||
}
|
||
|
||
private function ingest(int $fileId, int $factoryId): void
|
||
{
|
||
$db = $this->db();
|
||
$file = $db->table('dropship_bill_files')->find($fileId);
|
||
try {
|
||
$result = $this->parser->parse(Storage::disk(self::DISK)->path($file->stored_path), pathinfo($file->stored_path, PATHINFO_EXTENSION));
|
||
} catch (Throwable $error) {
|
||
$db->table('dropship_bill_files')->where('id', $fileId)->update(['factory_id' => $factoryId, 'status' => 'failed',
|
||
'message' => mb_substr('读取失败:' . $error->getMessage(), 0, 500), 'updated_at' => now()]);
|
||
|
||
return;
|
||
}
|
||
$lines = $result['lines'];
|
||
$notes = [];
|
||
if ($lines === []) {
|
||
$notes[] = '没读到厂家运费:要有一张表同时有单号列(快递单号/运单号/单号…)和运费列(快递运费/运费/快递费…),且运费不为空';
|
||
}
|
||
$others = [];
|
||
foreach (array_chunk(array_map('strval', array_keys($lines)), 1000) as $chunk) {
|
||
array_push($others, ...$db->table('dropship_bill_lines')->where('factory_id', $factoryId)->where('bill_month', $file->bill_month)
|
||
->where('file_id', '!=', $fileId)->whereIn('waybill_no', $chunk)->distinct()->pluck('waybill_no')->map('strval')->all());
|
||
}
|
||
if ($others !== [] && count($others) * 2 >= count($lines)) {
|
||
$db->table('dropship_bill_files')->where('id', $fileId)->update(['factory_id' => $factoryId, 'status' => 'failed',
|
||
'message' => '重复导入:这家本月已上传的账单里已有 ' . count($others) . '/' . count($lines) . ' 个相同单号,这份没读入。要换新版本先删掉旧文件。',
|
||
'sheets' => json_encode($result['sheets'], JSON_UNESCAPED_UNICODE), 'updated_at' => now()]);
|
||
|
||
return;
|
||
}
|
||
if ($others !== []) {
|
||
$notes[] = count($others) . ' 个单号本月别的账单文件里也有,对账时只算一次';
|
||
$lines = array_diff_key($lines, array_flip($others));
|
||
}
|
||
$db->transaction(function () use ($db, $fileId, $factoryId, $file, $lines, $result, $notes): void {
|
||
$db->table('dropship_bill_lines')->where('file_id', $fileId)->delete();
|
||
foreach (array_chunk($lines, 500, true) as $chunk) {
|
||
$insert = [];
|
||
foreach ($chunk as $waybill => $line) {
|
||
$insert[] = ['file_id' => $fileId, 'factory_id' => $factoryId, 'bill_month' => $file->bill_month, 'waybill_no' => (string) $waybill,
|
||
'amount' => $line['amount'], 'sheet' => mb_substr($line['sheet'], 0, 64), 'row_no' => $line['row']];
|
||
}
|
||
$db->table('dropship_bill_lines')->insert($insert);
|
||
}
|
||
$read = array_values(array_filter($result['sheets'], static fn (array $s): bool => $s['read']));
|
||
$db->table('dropship_bill_files')->where('id', $fileId)->update([
|
||
'factory_id' => $factoryId, 'status' => 'parsed', 'waybill_count' => count($lines),
|
||
'amount' => round(array_sum(array_column($lines, 'amount')), 2),
|
||
'sheets' => json_encode($result['sheets'], JSON_UNESCAPED_UNICODE),
|
||
'message' => mb_substr(implode(';', [...array_map(static fn (array $s): string => '「' . $s['sheet'] . '」' . $s['note'], $read), ...$notes]), 0, 500),
|
||
'updated_at' => now(),
|
||
]);
|
||
});
|
||
}
|
||
|
||
/** 文件名里出现厂家名、关键字或代发仓核心名,取最长命中的那家。 */
|
||
public static function identify(string $fileName, array $factories): ?object
|
||
{
|
||
$best = null;
|
||
$bestLength = 0;
|
||
foreach ($factories as $factory) {
|
||
foreach ([$factory->name, ...$factory->keyword_list, self::warehouseCore((string) $factory->warehouse)] as $word) {
|
||
$word = trim((string) $word);
|
||
if (mb_strlen($word) >= 2 && mb_strlen($word) > $bestLength && str_contains($fileName, $word)) {
|
||
$best = $factory;
|
||
$bestLength = mb_strlen($word);
|
||
}
|
||
}
|
||
}
|
||
|
||
return $best;
|
||
}
|
||
|
||
/** 「工厂-山东卿德客代发仓」→「卿德客」 */
|
||
public static function warehouseCore(string $warehouse): string
|
||
{
|
||
$core = preg_replace('/^工厂-|代发仓$/u', '', trim($warehouse)) ?? '';
|
||
$core = preg_replace('/^(山东|河北|浙江|江苏|福建|河南|江西|安徽|广东|湖北|湖南|四川|天津|北京|上海)/u', '', $core) ?? $core;
|
||
|
||
return preg_replace('/^(菏泽|霸州|临沂|常州|徐州|曹县|郯城|洛阳)/u', '', $core) ?? $core;
|
||
}
|
||
|
||
/** @return list<string> */
|
||
public static function splitKeywords(string $value): array
|
||
{
|
||
return array_values(array_unique(array_filter(array_map('trim', preg_split('/[,,、\s]+/u', $value) ?: []),
|
||
static fn (string $k): bool => $k !== '')));
|
||
}
|
||
|
||
/**
|
||
* 代发快递的关键字:几个快递名称共同的部分(如「卿德客申通」「卿德客极兔」→「卿德客」);没有共同部分就各用全名。
|
||
*
|
||
* @param list<string> $expresses
|
||
* @return list<string>
|
||
*/
|
||
public static function keywordsFor(array $expresses): array
|
||
{
|
||
$common = self::commonPart($expresses);
|
||
|
||
return $common !== '' ? [$common] : array_values($expresses);
|
||
}
|
||
|
||
/** 几个字符串共同的最长子串(至少 2 个字)。 */
|
||
public static function commonPart(array $values): string
|
||
{
|
||
$values = array_values(array_filter(array_map('strval', $values), static fn (string $v): bool => $v !== ''));
|
||
if ($values === []) {
|
||
return '';
|
||
}
|
||
usort($values, static fn (string $a, string $b): int => mb_strlen($a) <=> mb_strlen($b));
|
||
$shortest = $values[0];
|
||
$length = mb_strlen($shortest);
|
||
for ($size = $length; $size >= 2; $size--) {
|
||
for ($start = 0; $start + $size <= $length; $start++) {
|
||
$part = mb_substr($shortest, $start, $size);
|
||
if (array_reduce($values, static fn (bool $ok, string $v): bool => $ok && str_contains($v, $part), true)) {
|
||
return $part;
|
||
}
|
||
}
|
||
}
|
||
|
||
return '';
|
||
}
|
||
|
||
/** @return array{0:string,1:string} */
|
||
public static function monthRange(string $month): array
|
||
{
|
||
$start = \Carbon\CarbonImmutable::createFromFormat('Y-m-d', $month . '-01')->startOfDay();
|
||
|
||
return [$start->format('Y-m-d H:i:s'), $start->addMonth()->format('Y-m-d H:i:s')];
|
||
}
|
||
|
||
private static function blank(?string $value): ?string
|
||
{
|
||
$value = trim((string) $value);
|
||
|
||
return $value === '' ? null : mb_substr($value, 0, 255);
|
||
}
|
||
}
|