CaiWuXiTong/modules/EcommerceFinance/Services/SupplierFreeShippingStore.php
chenxi 257fd65496 商品成本新增商品与供应商属性列 (#576)
商品成本新增商品与供应商属性列 (#576)
2026-10-26 09:53:30 +08:00

117 lines
3.4 KiB
PHP

<?php
namespace Modules\EcommerceFinance\Services;
/**
* 供应商是否包邮厂家的本地补充资料。
*
* 供应商主档来自只读共享镜像,包邮标记保存在现有供应商维护表中,
* 以供应商镜像的稳定 ID 关联,不写回上游。
*/
class SupplierFreeShippingStore
{
public const DATASET = 'supplier-management.free-shipping-manufacturer';
public const FIELD = 'free_shipping_manufacturer';
/** @var array<int,array<string,array<string,mixed>>> */
private array $cache = [];
public function __construct(private readonly SupplierPayableOverrideStore $overrides)
{
}
/** @param list<object> $rows
* @return list<object>
*/
public function decorateRows(array $rows, int $companyId): array
{
foreach ($rows as $row) {
$this->decorateRow($row, $companyId);
}
return $rows;
}
public function decorateRow(object $row, int $companyId): object
{
$id = (int) ($row->Id ?? 0);
$values = $this->values($companyId);
$row->{self::FIELD} = $id > 0 && (bool) ($values[$this->key($id)][self::FIELD] ?? false);
return $row;
}
/**
* @param list<int> $supplierIds
* @return array<int,bool>
*/
public function flagsBySupplierIds(array $supplierIds, int $companyId): array
{
$values = $this->values($companyId);
$flags = [];
foreach (array_unique(array_filter($supplierIds, static fn (int $id): bool => $id > 0)) as $supplierId) {
$flags[$supplierId] = (bool) ($values[$this->key($supplierId)][self::FIELD] ?? false);
}
return $flags;
}
/** @return array{created:int,updated:int} */
public function save(int $supplierId, bool $isFreeShipping, int $companyId, ?int $userId, string $source = 'manual'): array
{
$result = $this->overrides->save(
self::DATASET,
$this->key($supplierId),
[self::FIELD => $isFreeShipping],
$companyId,
$userId,
$source,
);
unset($this->cache[$companyId]);
return $result;
}
/**
* @param array<int,bool> $values 供应商 ID => 是否包邮厂家
* @return array{created:int,updated:int}
*/
public function saveMany(array $values, int $companyId, ?int $userId, string $source = 'import'): array
{
$records = [];
foreach ($values as $supplierId => $isFreeShipping) {
if ((int) $supplierId <= 0) {
continue;
}
$records[$this->key((int) $supplierId)] = [self::FIELD => (bool) $isFreeShipping];
}
$result = $this->overrides->saveBatch(self::DATASET, $records, $companyId, $userId, $source);
unset($this->cache[$companyId]);
return $result;
}
/** @return array<string,array<string,mixed>> */
private function values(int $companyId): array
{
if (! isset($this->cache[$companyId])) {
$this->cache[$companyId] = [];
foreach ($this->overrides->listRows(self::DATASET, $companyId) as $row) {
$key = (string) ($row['_action_key'] ?? '');
if ($key !== '') {
$this->cache[$companyId][$key] = $row;
}
}
}
return $this->cache[$companyId];
}
private function key(int $supplierId): string
{
return 'supplier:' . $supplierId;
}
}