CaiWuXiTong/modules/EcommerceFinance/Repositories/SupplierAccessoryFreightRepository.php

53 lines
3.4 KiB
PHP

<?php
namespace Modules\EcommerceFinance\Repositories;
use Modules\EcommerceFinance\Services\AccessoryReshipMatcher;
use Modules\EcommerceFinance\Services\BusinessMirrorDatasetRegistry;
use Modules\EcommerceFinance\Services\SupplierAccessoryFreightMatcher;
use RuntimeException;
/** 只读现有共享镜像,不使用发货行的历史供应商字段代替商品资料。 */
class SupplierAccessoryFreightRepository
{
public function __construct(
private readonly ShippingOrderRepository $shipping,
private readonly BusinessMirrorDatasetRegistry $datasets,
private readonly GenericBusinessMirrorRepository $mirror,
private readonly SupplierAccessoryFreightMatcher $matcher,
) {}
public function rows(string $month): \Generator
{
$productDataset = $this->datasets->get(ProductCatalogMirrorRepository::DATASET_KEY);
$supplierDataset = $this->datasets->get(SupplierManagementMirrorRepository::DATASET);
$courierDataset = $this->datasets->get(CourierInformationMirrorRepository::DATASET_KEY);
if (!$this->mirror->ready($productDataset) || !$this->mirror->ready($supplierDataset) || !$this->mirror->ready($courierDataset)) {
throw new RuntimeException('商品、供应商或快递资料尚未完成首次同步');
}
$db = $this->mirror->connection();
// 供应商档案数量较小,一次读取,批量商品查询避免逐单访问数据库。
$suppliers = $db->table($supplierDataset->targetTable())->get(['scmname', 'linkerprovience'])
->groupBy(static fn ($row) => trim((string) $row->scmname))
->map(static fn ($group) => $group->map(static fn ($row) => (array) $row)->all());
// 快递资料约 1,900 条,仅读取名称和原始属性;同名候选保留供规则核实,不逐单查询。
$couriers = $db->table($courierDataset->targetTable())->get(['expname', 'exp_properties'])
->groupBy(static fn ($row) => trim((string) $row->expname))
->map(static fn ($group) => $group->map(static fn ($row) => (array) $row)->all());
$start = \Carbon\Carbon::createFromFormat('!Y-m', $month);
foreach ($this->shipping->accessoryFreightBatches($start->format('Y-m-d'), $start->copy()->addMonth()->format('Y-m-d')) as $batch) {
$barcodes = array_values(array_unique(array_filter(array_map(static fn ($row) => AccessoryReshipMatcher::barcode((string) ($row['barcode'] ?? '')), $batch), static fn ($value) => $value !== '')));
$products = $db->table($productDataset->targetTable())->where('sku_type', 'normal')->whereIn('sku_id', $barcodes)
->get(['sku_id', 'name', 'supplier_name'])->groupBy(static fn ($row) => trim((string) $row->sku_id))
->map(static fn ($group) => $group->map(static fn ($row) => (array) $row)->all());
foreach ($batch as $row) {
$barcode = AccessoryReshipMatcher::barcode((string) ($row['barcode'] ?? ''));
$candidates = $products->get($barcode, []);
$supplierName = trim((string) ($candidates[0]['supplier_name'] ?? ''));
$courierName = trim((string) ($row['express_name1'] ?? '')) ?: trim((string) ($row['express_name2'] ?? ''));
yield $this->matcher->match($row, $candidates, $suppliers->get($supplierName, []), $couriers->get($courierName, []));
}
}
}
}