CaiWuXiTong/app/Support/DropshipFreight/DropshipFreightStore.php
Claude 4c038e47b1 快递批量推送上传链接跳过已推/已有账单;代发小汇总附加费补读老文件(重做补丁 35、36,基于 main 75cba0dde938)
- 批量「推送上传链接到快递群」:这个月已推过、已有账单的分组跳过;对账分组里单独点照发。
  推送记录按月存 supplier_payable_overrides(courier-upload-link-pushed:YYYY-MM),无迁移。
- 代发:之前入库的厂家账单 sheets 里没记附加费,导出小汇总和各厂家汇总时现读原文件补记一次;表名带「附加费」都认。

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UNTa9mVziToe5w52mmrrar
2026-12-03 14:30:44 +08:00

516 lines
25 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 App\Support\DropshipFreight;
use App\Support\CourierBills\BillWorkbookReader;
use App\Support\CourierBills\CourierBillStore;
use App\Support\CourierBills\FreightBillTemplate;
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,
) {}
/**
* 这份账单「附加费」表按类型的金额(类型 => 金额)。入库时记在 sheets 里;之前入库的老文件现读原文件补记一次。
*
* @return array<string,float>
*/
public function feesFor(object $file): array
{
$sheets = (array) json_decode((string) ($file->sheets ?? ''), true);
$surcharge = array_filter($sheets, static fn ($sheet): bool => is_array($sheet)
&& str_contains((string) ($sheet['sheet'] ?? ''), FreightBillTemplate::SURCHARGE_SHEET));
if ($surcharge === []) {
return []; // sheets 里列着原文件每张表,没有附加费表就不用读文件
}
$fees = [];
if (array_filter($surcharge, static fn (array $sheet): bool => array_key_exists('fees', $sheet)) !== []) {
foreach ($surcharge as $sheet) {
foreach ((array) ($sheet['fees'] ?? []) as $type => $amount) {
$fees[(string) $type] = round(($fees[(string) $type] ?? 0) + (float) $amount, 2);
}
}
return $fees;
}
if (empty($file->stored_path) || ! Storage::disk(self::DISK)->exists((string) $file->stored_path)) {
return [];
}
$fees = (new FreightBillTemplate(new BillWorkbookReader()))->surchargesByType(Storage::disk(self::DISK)->path((string) $file->stored_path),
pathinfo((string) $file->stored_path, PATHINFO_EXTENSION));
if (! empty($file->id)) {
$this->db()->table('dropship_bill_files')->where('id', $file->id)
->update(['sheets' => json_encode(self::withFees($sheets, $fees), JSON_UNESCAPED_UNICODE)]);
}
return $fees;
}
/** 把附加费金额记到 sheets 里「附加费」那张表的记录上(没有附加费也记个空的,下次不用再读文件);不新增记录,导出按记录数给原表起名。 */
private static function withFees(array $sheets, array $fees): array
{
$note = $fees === [] ? '没有附加费' : '附加费按类型记入各厂家汇总和小汇总';
$done = false;
foreach ($sheets as $i => $sheet) {
if (! $done && is_array($sheet) && str_contains((string) ($sheet['sheet'] ?? ''), FreightBillTemplate::SURCHARGE_SHEET)) {
$sheets[$i]['fees'] = $fees;
$sheets[$i]['note'] = $note;
$done = true;
}
}
return $sheets;
}
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 uploadFor(string $name, string $path, string $month, int $factoryId, string $user): int
{
$factory = collect($this->factories())->firstWhere('id', $factoryId);
if ($factory === null) {
throw new RuntimeException('厂家不存在。');
}
return $this->register($name, $path, $month, [$factory], $user, $factory);
}
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);
}
/**
* 这家这个月导出用的汇总样子:这个月或之前最近一个月的手工汇总,月份顺延到这个月;一份都没有就用默认样子。
*
* @return array{title:string,headers:list<string>,labels:list<string>,total:string,from:?string}
*/
public function summaryTemplate(object $factory, string $month): array
{
$row = $this->db()->table('dropship_summary_templates')->where('factory_id', $factory->id)->where('bill_month', '<=', $month)
->orderByDesc('bill_month')->first();
if ($row === null) {
return DropshipSummaryTemplate::withoutDropped(DropshipSummaryTemplate::fallback($month, (string) $factory->name)) + ['from' => null];
}
$delta = ((int) substr($month, 0, 4) - (int) substr((string) $row->bill_month, 0, 4)) * 12
+ (int) substr($month, 5, 2) - (int) substr((string) $row->bill_month, 5, 2);
$template = DropshipSummaryTemplate::roll(['title' => (string) $row->title, 'headers' => array_values((array) json_decode((string) $row->headers, true)),
'labels' => array_values((array) json_decode((string) $row->labels, true)), 'total' => (string) $row->total_label], $delta);
return DropshipSummaryTemplate::withoutDropped($template) + ['from' => (string) $row->bill_month];
}
/**
* 从手工做好的代发账单(带「汇总」表)里读汇总的样子。
*
* @param list<array{0:string,1:string}> $files [原文件名, 路径]
* @return array{blocks:int,saved:list<string>,unknown:list<string>}
*/
public function importSummaryTemplates(array $files, string $month): array
{
$reader = new BillWorkbookReader();
$blocks = [];
$unknown = [];
foreach ($files as [$name, $path]) {
$template = DropshipSummaryTemplate::find($reader->sheets($path, strtolower(pathinfo($name, PATHINFO_EXTENSION))));
if ($template === null) {
$unknown[] = $name . '(没找到汇总)';
continue;
}
$blocks[] = $template + ['source' => $name, 'fallback' => $name];
}
$result = $this->saveSummaryTemplates($blocks, $month);
$result['unknown'] = [...$unknown, ...$result['unknown']];
return $result;
}
/**
* @param list<array{title:string,headers:list<string>,labels:list<string>,total?:string,factory?:?string,source?:?string,fallback?:?string}> $blocks
* factory = 厂家名(有就按它认),否则按标题里的厂家名认,再不行按文件名认
* @return array{blocks:int,saved:list<string>,unknown:list<string>}
*/
public function saveSummaryTemplates(array $blocks, string $month): array
{
$factories = $this->factories();
$saved = [];
$unknown = [];
foreach ($blocks as $block) {
$factory = null;
foreach ([$block['factory'] ?? null, DropshipSummaryTemplate::titleName((string) $block['title']), $block['fallback'] ?? null] as $hint) {
$hint = trim((string) $hint);
if ($hint === '') {
continue;
}
$factory = collect($factories)->first(static fn ($f): bool => (string) $f->name === $hint) ?? self::identify($hint, $factories);
if ($factory !== null) {
break;
}
}
if ($factory === null) {
$unknown[] = ($block['factory'] ?? null) ?: (($block['source'] ?? null) ?: $block['title']);
continue;
}
$headers = array_values(array_map('strval', (array) $block['headers']));
$this->db()->table('dropship_summary_templates')->updateOrInsert(
['factory_id' => $factory->id, 'bill_month' => $month],
['title' => mb_substr((string) $block['title'], 0, 255),
'headers' => json_encode(array_slice(array_pad($headers, 3, ''), 0, 3), JSON_UNESCAPED_UNICODE),
'labels' => json_encode(array_values(array_map('strval', (array) $block['labels'])), JSON_UNESCAPED_UNICODE),
'total_label' => mb_substr((string) (($block['total'] ?? '') ?: '合计'), 0, 32),
'source' => isset($block['source']) ? mb_substr((string) $block['source'], 0, 255) : null,
'created_at' => now(), 'updated_at' => now()],
);
$saved[(int) $factory->id] = (string) $factory->name;
}
return ['blocks' => count($blocks), 'saved' => array_values($saved), 'unknown' => array_values(array_unique($unknown))];
}
/** @param list<object> $factories */
private function register(string $name, string $path, string $month, array $factories, string $user, ?object $known = null): int
{
$extension = strtolower(pathinfo($name, PATHINFO_EXTENSION));
$stored = 'dropship-bills/' . $month . '/' . Str::uuid() . '.' . $extension;
Storage::disk(self::DISK)->put($stored, fopen($path, 'rb'));
$factory = $known ?? 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'];
// 按上传模板填的「附加费」表:按类型记下金额,各厂家汇总里自动带入退回费、拦截费等列
$fees = (new FreightBillTemplate(new BillWorkbookReader()))->surchargesByType(Storage::disk(self::DISK)->path($file->stored_path),
pathinfo($file->stored_path, PATHINFO_EXTENSION));
$result['sheets'] = self::withFees($result['sheets'], $fees);
$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);
}
}