287 lines
12 KiB
PHP
287 lines
12 KiB
PHP
<?php
|
||
|
||
namespace Modules\EcommerceFinance\Services;
|
||
|
||
use Illuminate\Support\Facades\Storage;
|
||
use InvalidArgumentException;
|
||
use RuntimeException;
|
||
|
||
/**
|
||
* 种菜额度规则(ID负责人 / 店铺+职级 / 店铺 / 平台+职级),财务在种菜报销工作台维护。
|
||
*
|
||
* 初始数据 = 「脉象」导出的 309 条(resources/data/planting_quota_rules_2026-11-27.csv);第一次保存后存为
|
||
* storage/app/planting-reimbursement-references/<公司>/quota-rules.json(持久卷),不建表。
|
||
* 业务唯一键:规则类型 + 平台 + 店铺 + 渠道 + 职级 + ID负责人;金额留空 = 该维度不判定。
|
||
*/
|
||
class PlantingQuotaRules
|
||
{
|
||
public const SEED = 'planting_quota_rules_2026-11-27.csv';
|
||
|
||
public const FIELDS = ['rule_type', 'platform', 'shop_name', 'channel', 'position_level', 'ider', 'month_limit', 'day_limit', 'single_limit', 'is_enabled', 'remark'];
|
||
|
||
public const LIMIT_FIELDS = ['month_limit', 'day_limit', 'single_limit'];
|
||
|
||
/** 各规则类型必填的字段。 */
|
||
public const REQUIRED = [
|
||
'ider' => ['ider'],
|
||
'shop_level' => ['shop_name', 'position_level'],
|
||
'shop' => ['shop_name'],
|
||
'platform' => ['platform', 'position_level'],
|
||
];
|
||
|
||
public const FIELD_LABELS = [
|
||
'rule_type' => '规则类型', 'platform' => '平台', 'shop_name' => '店铺', 'channel' => '渠道', 'position_level' => '职级',
|
||
'ider' => 'ID负责人', 'month_limit' => '月限额', 'day_limit' => '日限额', 'single_limit' => '单笔限额', 'is_enabled' => '启用', 'remark' => '备注',
|
||
];
|
||
|
||
/** @var array<int,array<string,mixed>> */
|
||
private array $loaded = [];
|
||
|
||
/** @return array{rules:list<array<string,mixed>>,source:string,updated_at:?string,updated_by:?int} */
|
||
public function document(int $companyId): array
|
||
{
|
||
if (isset($this->loaded[$companyId])) {
|
||
return $this->loaded[$companyId];
|
||
}
|
||
$disk = Storage::disk('local');
|
||
$path = $this->path($companyId);
|
||
$document = $disk->exists($path) ? json_decode((string) $disk->get($path), true) : null;
|
||
if (! is_array($document) || ! is_array($document['rules'] ?? null)) {
|
||
$document = [
|
||
'rules' => $this->withIds($this->parseCsv((string) file_get_contents(resource_path('data/' . self::SEED)))),
|
||
'source' => 'seed',
|
||
'updated_at' => null,
|
||
'updated_by' => null,
|
||
];
|
||
}
|
||
|
||
return $this->loaded[$companyId] = $document;
|
||
}
|
||
|
||
/** @return list<array<string,mixed>> */
|
||
public function all(int $companyId): array
|
||
{
|
||
return $this->document($companyId)['rules'];
|
||
}
|
||
|
||
/**
|
||
* 新增或修改一条规则。
|
||
*
|
||
* @param array<string,mixed> $input
|
||
*/
|
||
public function save(int $companyId, ?int $id, array $input, ?int $userId): array
|
||
{
|
||
$rule = $this->normalize($input);
|
||
$rules = $this->all($companyId);
|
||
$key = self::uniqueKey($rule);
|
||
foreach ($rules as $existing) {
|
||
if (self::uniqueKey($existing) === $key && (int) $existing['id'] !== (int) $id) {
|
||
throw new InvalidArgumentException('已有相同的规则(' . PlantingQuotaCalculator::ruleLabel($existing + ['channel' => '']) . '),请直接修改那一条。');
|
||
}
|
||
}
|
||
|
||
if ($id === null) {
|
||
$rule['id'] = $rules === [] ? 1 : max(array_column($rules, 'id')) + 1;
|
||
$rules[] = $rule;
|
||
} else {
|
||
$found = false;
|
||
foreach ($rules as &$existing) {
|
||
if ((int) $existing['id'] === $id) {
|
||
$existing = ['id' => $id] + $rule;
|
||
$found = true;
|
||
}
|
||
}
|
||
unset($existing);
|
||
if (! $found) {
|
||
throw new InvalidArgumentException('要修改的规则不存在,请刷新页面后重试。');
|
||
}
|
||
$rule['id'] = $id;
|
||
}
|
||
$this->store($companyId, $rules, 'edited', $userId);
|
||
|
||
return $rule;
|
||
}
|
||
|
||
public function delete(int $companyId, int $id, ?int $userId): void
|
||
{
|
||
$rules = array_values(array_filter($this->all($companyId), static fn (array $rule): bool => (int) $rule['id'] !== $id));
|
||
if (count($rules) === count($this->all($companyId))) {
|
||
throw new InvalidArgumentException('要删除的规则不存在,请刷新页面后重试。');
|
||
}
|
||
$this->store($companyId, $rules, 'edited', $userId);
|
||
}
|
||
|
||
/** 用 CSV(脉象导出格式,表头即字段名)整体替换。 */
|
||
public function import(int $companyId, string $content, ?int $userId): int
|
||
{
|
||
$rules = $this->parseCsv($content);
|
||
if ($rules === []) {
|
||
throw new InvalidArgumentException('文件里没有读到规则。');
|
||
}
|
||
$this->store($companyId, $this->withIds($rules), 'import', $userId);
|
||
|
||
return count($rules);
|
||
}
|
||
|
||
public function exportCsv(int $companyId): string
|
||
{
|
||
$stream = fopen('php://temp', 'r+');
|
||
fwrite($stream, "\xEF\xBB\xBF");
|
||
fputcsv($stream, self::FIELDS, ',', '"', '');
|
||
foreach ($this->all($companyId) as $rule) {
|
||
fputcsv($stream, array_map(static fn (string $field): string => $field === 'is_enabled' ? ($rule[$field] ? '1' : '0') : (string) ($rule[$field] ?? ''), self::FIELDS), ',', '"', '');
|
||
}
|
||
rewind($stream);
|
||
$csv = (string) stream_get_contents($stream);
|
||
fclose($stream);
|
||
|
||
return $csv;
|
||
}
|
||
|
||
/**
|
||
* @return list<array<string,mixed>>
|
||
*/
|
||
public function parseCsv(string $content): array
|
||
{
|
||
if (str_starts_with($content, "\xEF\xBB\xBF")) {
|
||
$content = substr($content, 3);
|
||
} elseif (! mb_check_encoding($content, 'UTF-8')) {
|
||
$content = (string) mb_convert_encoding($content, 'UTF-8', 'GB18030');
|
||
}
|
||
$stream = fopen('php://temp', 'r+');
|
||
fwrite($stream, $content);
|
||
rewind($stream);
|
||
$header = fgetcsv($stream, 0, ',', '"', '');
|
||
$header = is_array($header) ? array_map(static fn ($v): string => trim((string) $v), $header) : [];
|
||
$labels = array_flip(self::FIELD_LABELS);
|
||
$header = array_map(static fn (string $name): string => $labels[$name] ?? $name, $header);
|
||
if (array_diff(['rule_type', 'month_limit', 'day_limit', 'single_limit'], $header) !== []) {
|
||
fclose($stream);
|
||
throw new InvalidArgumentException('规则文件表头不对,请用「导出规则」或脉象导出的 CSV(rule_type, platform, shop_name, channel, position_level, ider, month_limit, day_limit, single_limit, is_enabled, remark)。');
|
||
}
|
||
|
||
$rules = [];
|
||
$keys = [];
|
||
$line = 1;
|
||
while (($row = fgetcsv($stream, 0, ',', '"', '')) !== false) {
|
||
$line++;
|
||
if ($row === [null] || implode('', array_map('trim', array_map('strval', $row))) === '') {
|
||
continue;
|
||
}
|
||
$values = [];
|
||
foreach ($header as $index => $name) {
|
||
$values[$name] = $row[$index] ?? '';
|
||
}
|
||
try {
|
||
$rule = $this->normalize($values);
|
||
} catch (InvalidArgumentException $exception) {
|
||
fclose($stream);
|
||
throw new InvalidArgumentException('第 ' . $line . ' 行:' . $exception->getMessage());
|
||
}
|
||
$key = self::uniqueKey($rule);
|
||
if (isset($keys[$key])) {
|
||
fclose($stream);
|
||
throw new InvalidArgumentException('第 ' . $line . ' 行与第 ' . $keys[$key] . ' 行是同一条规则。');
|
||
}
|
||
$keys[$key] = $line;
|
||
$rules[] = $rule;
|
||
}
|
||
fclose($stream);
|
||
|
||
return $rules;
|
||
}
|
||
|
||
/**
|
||
* @param array<string,mixed> $input
|
||
* @return array<string,mixed>
|
||
*/
|
||
public function normalize(array $input): array
|
||
{
|
||
$type = trim((string) ($input['rule_type'] ?? ''));
|
||
$type = array_flip(PlantingQuotaCalculator::RULE_TYPES)[$type] ?? $type;
|
||
if (! isset(self::REQUIRED[$type])) {
|
||
throw new InvalidArgumentException('规则类型只能是 ID负责人 / 店铺+职级 / 店铺 / 平台+职级。');
|
||
}
|
||
$rule = ['rule_type' => $type];
|
||
foreach (['platform', 'shop_name', 'channel', 'position_level', 'ider'] as $field) {
|
||
$rule[$field] = mb_substr(trim((string) ($input[$field] ?? '')), 0, 191);
|
||
}
|
||
$rule['position_level'] = strtoupper($rule['position_level']);
|
||
foreach (self::REQUIRED[$type] as $field) {
|
||
if ($rule[$field] === '') {
|
||
throw new InvalidArgumentException(PlantingQuotaCalculator::RULE_TYPES[$type] . '规则必须填写' . self::FIELD_LABELS[$field] . '。');
|
||
}
|
||
}
|
||
// 只保留该类型用得到的维度,避免多填的字段影响匹配。
|
||
foreach (['platform', 'shop_name', 'channel', 'position_level', 'ider'] as $field) {
|
||
$used = match ($type) {
|
||
'ider' => ['ider'],
|
||
'shop_level' => ['shop_name', 'position_level'],
|
||
'shop' => ['shop_name'],
|
||
default => ['platform', 'position_level', 'channel'],
|
||
};
|
||
if (! in_array($field, $used, true)) {
|
||
$rule[$field] = '';
|
||
}
|
||
}
|
||
if ($rule['position_level'] !== '' && PlantingQuotaCalculator::band($rule['position_level']) !== $rule['position_level']) {
|
||
throw new InvalidArgumentException('职级须为 P0~P7 或 M1~M5。');
|
||
}
|
||
if ($type === 'platform' && PlantingQuotaCalculator::platform($rule['platform']) !== $rule['platform']) {
|
||
throw new InvalidArgumentException('平台须为 京喜 / 京东 / 天猫 / 拼多多 / 抖音 / 淘宝 / 阿里巴巴。');
|
||
}
|
||
foreach (self::LIMIT_FIELDS as $field) {
|
||
$value = str_replace([',', ',', ' '], '', trim((string) ($input[$field] ?? '')));
|
||
if ($value === '') {
|
||
$rule[$field] = null;
|
||
continue;
|
||
}
|
||
if (! is_numeric($value) || (float) $value < 0) {
|
||
throw new InvalidArgumentException(self::FIELD_LABELS[$field] . '须为不小于 0 的金额,留空表示不判定。');
|
||
}
|
||
$rule[$field] = number_format((float) $value, 2, '.', '');
|
||
}
|
||
if ($rule['month_limit'] === null && $rule['day_limit'] === null && $rule['single_limit'] === null) {
|
||
throw new InvalidArgumentException('月限额、日限额、单笔限额至少填一项。');
|
||
}
|
||
$enabled = $input['is_enabled'] ?? '1';
|
||
$rule['is_enabled'] = ! in_array(strtolower(trim((string) $enabled)), ['0', 'false', '停用', 'off', ''], true) || $enabled === true;
|
||
$rule['remark'] = mb_substr(trim((string) ($input['remark'] ?? '')), 0, 500);
|
||
|
||
return $rule;
|
||
}
|
||
|
||
public static function uniqueKey(array $rule): string
|
||
{
|
||
return implode("\x1f", array_map(static fn (string $field): string => mb_strtoupper(trim((string) ($rule[$field] ?? ''))), ['rule_type', 'platform', 'shop_name', 'channel', 'position_level', 'ider']));
|
||
}
|
||
|
||
/** @param list<array<string,mixed>> $rules */
|
||
private function store(int $companyId, array $rules, string $source, ?int $userId): void
|
||
{
|
||
$document = ['rules' => array_values($rules), 'source' => $source, 'updated_at' => now()->format('Y-m-d H:i:s'), 'updated_by' => $userId];
|
||
if (! Storage::disk('local')->put($this->path($companyId), json_encode($document, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR))) {
|
||
throw new RuntimeException('规则保存失败。');
|
||
}
|
||
$this->loaded[$companyId] = $document;
|
||
}
|
||
|
||
/**
|
||
* @param list<array<string,mixed>> $rules
|
||
* @return list<array<string,mixed>>
|
||
*/
|
||
private function withIds(array $rules): array
|
||
{
|
||
$id = 0;
|
||
|
||
return array_map(static function (array $rule) use (&$id): array {
|
||
return ['id' => ++$id] + $rule;
|
||
}, $rules);
|
||
}
|
||
|
||
private function path(int $companyId): string
|
||
{
|
||
return PlantingReimbursementReferences::DIRECTORY . '/' . $companyId . '/quota-rules.json';
|
||
}
|
||
}
|