395 lines
17 KiB
PHP
395 lines
17 KiB
PHP
<?php
|
||
|
||
namespace Modules\EcommerceFinance\Services;
|
||
|
||
/**
|
||
* 种菜额度风险计算:按《种菜明细报表 · 生成逻辑》(业务交付包 2026-11-27)复刻「脉象」每日种菜监控看板的判定。
|
||
*
|
||
* ① 工单:种菜报销工单,排除审核驳回 / 作废,业务日期 = 支付时间(payDateField);
|
||
* ② 金额:种菜报销金额 = 实付金额字段(actualPaidAmountField),为空才取最终报销金额字段(2026-11-27 财务确认与看板一致);
|
||
* ③ 维度:店铺 → 平台 + 店长(工作平台店铺信息);商品ID → ID负责人 + 部门负责人(按商品行顺序取第一个有负责人的,
|
||
* 都没有用店长兜底);负责人 → 职级 → 档位(P0~P7、M1~M5);
|
||
* ④ 规则:只取启用规则,优先级 ID负责人 > 店铺+职级 > 店铺 > 平台+职级(平台规则优先渠道为空的);
|
||
* ⑤ 额度域内按支付日 / 支付月累计(含已完成报销的单;月累计含当月至今所有单),判单笔 / 每日 / 月度超额及缺配置类风险。
|
||
*
|
||
* 2026-11-27 用看板 11 月 1–27 日全部 13,941 单对照:规则来源、日累计、月累计、风险类型逐单一致。
|
||
*
|
||
* 纯计算类:不读数据库。
|
||
*/
|
||
final class PlantingQuotaCalculator
|
||
{
|
||
public const TYPE_OWNER_MISSING = '未匹配负责人';
|
||
|
||
public const TYPE_RANK_MISSING = '职级为空';
|
||
|
||
public const TYPE_RANK_UNCONFIGURED = '职级未配置';
|
||
|
||
public const TYPE_RULE_MISSING = '额度规则未配置';
|
||
|
||
public const TYPE_SINGLE = '单笔超额';
|
||
|
||
public const TYPE_DAY = '每日超额';
|
||
|
||
public const TYPE_MONTH = '月度超额';
|
||
|
||
public const OVER_TYPES = [self::TYPE_SINGLE, self::TYPE_DAY, self::TYPE_MONTH];
|
||
|
||
public const LEVEL_OK = 'ok';
|
||
|
||
public const LEVEL_WARNING = 'warning';
|
||
|
||
public const LEVEL_DANGER = 'danger';
|
||
|
||
/** 计入累计的工单排除这些状态(审核驳回、作废)。 */
|
||
public const EXCLUDED_STATUSES = ['REJECT_AUDIT', 'DISABLED'];
|
||
|
||
public const RULE_TYPES = [
|
||
'ider' => 'ID负责人',
|
||
'shop_level' => '店铺+职级',
|
||
'shop' => '店铺',
|
||
'platform' => '平台+职级',
|
||
];
|
||
|
||
private const RULE_ORDER = ['ider' => 0, 'shop_level' => 1, 'shop' => 2, 'platform' => 3];
|
||
|
||
private const BANDS = ['P0', 'P1', 'P2', 'P3', 'P4', 'P5', 'P6', 'P7', 'M1', 'M2', 'M3', 'M4', 'M5'];
|
||
|
||
/**
|
||
* @param list<array<string,mixed>> $rows 工单行(PlantingReimbursementRepository::decorate 的字段,含 status_code)
|
||
* @param array<string,array{platform?:?string,shop_head?:?string}> $shops ERP店铺名称 → 平台 / 店长
|
||
* @param array<string,array{ider?:?string,curr_cater?:?string}> $owners 商品ID → ID负责人 / 部门负责人
|
||
* @param array<string,string> $levels 负责人姓名 → 职级原文
|
||
* @param list<array<string,mixed>> $rules 额度规则(PlantingQuotaRules 的字段)
|
||
* @return array<string,array<string,mixed>> 工单号 → 计算结果
|
||
*/
|
||
public function calculate(array $rows, array $shops, array $owners, array $levels, array $rules): array
|
||
{
|
||
$rules = $this->prepareRules($rules);
|
||
$shopIndex = [];
|
||
foreach ($shops as $name => $shop) {
|
||
$shopIndex[self::key((string) $name)] ??= $shop;
|
||
}
|
||
|
||
$items = [];
|
||
foreach ($rows as $row) {
|
||
if (in_array((string) ($row['status_code'] ?? ''), self::EXCLUDED_STATUSES, true)) {
|
||
continue;
|
||
}
|
||
$paidAt = self::time((string) ($row['paid_at'] ?? ''));
|
||
if ($paidAt === '') {
|
||
continue;
|
||
}
|
||
$shopName = trim((string) ($row['shop_name'] ?? ''));
|
||
$shop = $shopIndex[self::key($shopName)] ?? [];
|
||
$productIds = self::productIds($row);
|
||
|
||
$owner = null;
|
||
$matchedProduct = null;
|
||
foreach ($productIds as $productId) {
|
||
$candidate = trim((string) ($owners[$productId]['ider'] ?? ''));
|
||
if ($candidate !== '') {
|
||
$owner = $owners[$productId];
|
||
$matchedProduct = $productId;
|
||
break;
|
||
}
|
||
}
|
||
$ider = $owner !== null ? trim((string) $owner['ider']) : trim((string) ($shop['shop_head'] ?? ''));
|
||
$ider = $ider === '' ? null : $ider;
|
||
$level = $ider !== null ? trim((string) ($levels[$ider] ?? '')) : '';
|
||
$platform = self::platform(trim((string) ($shop['platform'] ?? '')) !== '' ? (string) $shop['platform'] : (string) ($row['platform'] ?? ''));
|
||
$band = self::band($level);
|
||
$rule = $this->match($rules, $ider, $shopName, $platform, $band);
|
||
|
||
$items[] = [
|
||
'work_order_no' => (string) ($row['work_order_no'] ?? ''),
|
||
'paid_at' => $paidAt,
|
||
'amount' => self::amount($row),
|
||
'shop_name' => $shopName,
|
||
'platform' => $platform,
|
||
'ider' => $ider,
|
||
'curr_cater' => $owner !== null ? (trim((string) ($owner['curr_cater'] ?? '')) ?: null) : null,
|
||
'product_id' => $matchedProduct ?? ($productIds[0] ?? null),
|
||
'position_level' => $level === '' ? null : $level,
|
||
'level_band' => $band,
|
||
'rule' => $rule,
|
||
'scope_key' => self::scopeKey($ider, $rule, $shopName, $platform, $band),
|
||
];
|
||
}
|
||
|
||
$dayTotals = [];
|
||
$monthTotals = [];
|
||
foreach ($items as $item) {
|
||
$dayTotals[$item['scope_key'] . '#' . substr($item['paid_at'], 0, 10)] = ($dayTotals[$item['scope_key'] . '#' . substr($item['paid_at'], 0, 10)] ?? 0) + $item['amount'];
|
||
$monthTotals[$item['scope_key'] . '#' . substr($item['paid_at'], 0, 7)] = ($monthTotals[$item['scope_key'] . '#' . substr($item['paid_at'], 0, 7)] ?? 0) + $item['amount'];
|
||
}
|
||
|
||
$results = [];
|
||
foreach ($items as $item) {
|
||
$day = $dayTotals[$item['scope_key'] . '#' . substr($item['paid_at'], 0, 10)];
|
||
$month = $monthTotals[$item['scope_key'] . '#' . substr($item['paid_at'], 0, 7)];
|
||
$results[$item['work_order_no']] = $this->judge($item, $day, $month);
|
||
}
|
||
|
||
return $results;
|
||
}
|
||
|
||
/** @return array<string,mixed> */
|
||
private function judge(array $item, int $day, int $month): array
|
||
{
|
||
$rule = $item['rule'];
|
||
$single = $rule['single_limit'] ?? null;
|
||
$dayLimit = $rule['day_limit'] ?? null;
|
||
$monthLimit = $rule['month_limit'] ?? null;
|
||
$amount = $item['amount'];
|
||
|
||
$types = [];
|
||
if ($item['ider'] === null) {
|
||
$types[] = self::TYPE_OWNER_MISSING;
|
||
}
|
||
if (($rule === null || in_array($rule['rule_type'], ['platform', 'shop_level'], true)) && $item['ider'] !== null) {
|
||
if ($item['position_level'] === null) {
|
||
$types[] = self::TYPE_RANK_MISSING;
|
||
} elseif ($item['level_band'] === null) {
|
||
$types[] = self::TYPE_RANK_UNCONFIGURED;
|
||
}
|
||
}
|
||
// 实测看板(2026-11 全月 13,941 单):职级为空 / 未配置时不再叠加「额度规则未配置」。
|
||
if ($item['ider'] !== null && $rule === null && array_intersect([self::TYPE_RANK_MISSING, self::TYPE_RANK_UNCONFIGURED], $types) === []) {
|
||
$types[] = self::TYPE_RULE_MISSING;
|
||
}
|
||
if ($single !== null && $amount > $single) {
|
||
$types[] = self::TYPE_SINGLE;
|
||
}
|
||
if ($dayLimit !== null && $day > $dayLimit) {
|
||
$types[] = self::TYPE_DAY;
|
||
}
|
||
if ($monthLimit !== null && $month > $monthLimit) {
|
||
$types[] = self::TYPE_MONTH;
|
||
}
|
||
|
||
$over = array_values(array_intersect($types, self::OVER_TYPES));
|
||
$level = $over !== [] ? self::LEVEL_DANGER : ($types !== [] ? self::LEVEL_WARNING : self::LEVEL_OK);
|
||
$overAmount = max(
|
||
0,
|
||
$single !== null ? $amount - $single : 0,
|
||
$dayLimit !== null ? $day - $dayLimit : 0,
|
||
$monthLimit !== null ? $month - $monthLimit : 0,
|
||
);
|
||
|
||
return [
|
||
'work_order_no' => $item['work_order_no'],
|
||
'paid_at' => $item['paid_at'],
|
||
'platform' => $item['platform'],
|
||
'shop_name' => $item['shop_name'],
|
||
'product_id' => $item['product_id'],
|
||
'ider' => $item['ider'],
|
||
'curr_cater' => $item['curr_cater'],
|
||
'position_level' => $item['position_level'],
|
||
'level_band' => $item['level_band'],
|
||
'amount' => self::money($amount),
|
||
'single_limit' => $single === null ? null : self::money($single),
|
||
'day_total' => self::money($day),
|
||
'day_limit' => $dayLimit === null ? null : self::money($dayLimit),
|
||
'month_total' => self::money($month),
|
||
'month_limit' => $monthLimit === null ? null : self::money($monthLimit),
|
||
'over_amount' => self::money($overAmount),
|
||
'rule_id' => $rule['id'] ?? null,
|
||
'rule_type' => $rule['rule_type'] ?? null,
|
||
'rule_label' => $rule === null ? '' : self::ruleLabel($rule),
|
||
'scope_key' => $item['scope_key'],
|
||
'risk_level' => $level,
|
||
'risk_types' => $types,
|
||
'risk_message' => $this->message($types, $item, $amount, $single, $day, $dayLimit, $month, $monthLimit),
|
||
];
|
||
}
|
||
|
||
private function message(array $types, array $item, int $amount, ?int $single, int $day, ?int $dayLimit, int $month, ?int $monthLimit): string
|
||
{
|
||
if ($types === []) {
|
||
return '未超额';
|
||
}
|
||
if (in_array(self::TYPE_OWNER_MISSING, $types, true)) {
|
||
return '商品ID未匹配负责人,暂不判断额度';
|
||
}
|
||
$totals = '当日累计 ' . self::money($day) . ',本月累计 ' . self::money($month);
|
||
if (in_array(self::TYPE_RANK_MISSING, $types, true)) {
|
||
return '职级为空,暂不判断平台规则;' . $totals;
|
||
}
|
||
if (in_array(self::TYPE_RANK_UNCONFIGURED, $types, true)) {
|
||
return '职级 ' . $item['position_level'] . ' 未配置额度规则;' . $totals;
|
||
}
|
||
if (in_array(self::TYPE_RULE_MISSING, $types, true)) {
|
||
return '未命中ID负责人、店铺或平台规则;平台 ' . $item['platform'] . ',职级 ' . ($item['level_band'] ?? '-');
|
||
}
|
||
|
||
$parts = [];
|
||
if (in_array(self::TYPE_SINGLE, $types, true)) {
|
||
$parts[] = '单笔 ' . self::money($amount) . ' 超过上限 ' . self::money((int) $single);
|
||
}
|
||
if (in_array(self::TYPE_DAY, $types, true)) {
|
||
$parts[] = '当日累计 ' . self::money($day) . ' 超过上限 ' . self::money((int) $dayLimit);
|
||
}
|
||
if (in_array(self::TYPE_MONTH, $types, true)) {
|
||
$parts[] = '本月累计 ' . self::money($month) . ' 超过上限 ' . self::money((int) $monthLimit);
|
||
}
|
||
|
||
return implode(';', $parts);
|
||
}
|
||
|
||
/**
|
||
* @param list<array<string,mixed>> $rules
|
||
* @return list<array<string,mixed>> 启用规则,按匹配优先级排序,金额转分
|
||
*/
|
||
private function prepareRules(array $rules): array
|
||
{
|
||
$prepared = [];
|
||
foreach ($rules as $index => $rule) {
|
||
if (! self::enabled($rule['is_enabled'] ?? true) || ! isset(self::RULE_ORDER[(string) ($rule['rule_type'] ?? '')])) {
|
||
continue;
|
||
}
|
||
$prepared[] = [
|
||
'id' => $rule['id'] ?? null,
|
||
'rule_type' => (string) $rule['rule_type'],
|
||
'platform' => trim((string) ($rule['platform'] ?? '')),
|
||
'shop_name' => trim((string) ($rule['shop_name'] ?? '')),
|
||
'channel' => trim((string) ($rule['channel'] ?? '')),
|
||
'position_level' => trim((string) ($rule['position_level'] ?? '')),
|
||
'ider' => trim((string) ($rule['ider'] ?? '')),
|
||
'month_limit' => self::limit($rule['month_limit'] ?? null),
|
||
'day_limit' => self::limit($rule['day_limit'] ?? null),
|
||
'single_limit' => self::limit($rule['single_limit'] ?? null),
|
||
'order' => [self::RULE_ORDER[(string) $rule['rule_type']], (string) ($rule['channel'] ?? '') === '' ? 0 : 1, $index],
|
||
];
|
||
}
|
||
usort($prepared, static fn (array $a, array $b): int => $a['order'] <=> $b['order']);
|
||
|
||
return $prepared;
|
||
}
|
||
|
||
/** @param list<array<string,mixed>> $rules */
|
||
private function match(array $rules, ?string $ider, string $shop, string $platform, ?string $band): ?array
|
||
{
|
||
foreach ($rules as $rule) {
|
||
$hit = match ($rule['rule_type']) {
|
||
'ider' => $ider !== null && $rule['ider'] === $ider,
|
||
'shop_level' => $band !== null && self::key($rule['shop_name']) === self::key($shop) && strtoupper($rule['position_level']) === $band,
|
||
'shop' => self::key($rule['shop_name']) === self::key($shop),
|
||
'platform' => $band !== null && $rule['platform'] === $platform && strtoupper($rule['position_level']) === $band,
|
||
default => false,
|
||
};
|
||
if ($hit) {
|
||
return $rule;
|
||
}
|
||
}
|
||
|
||
return null;
|
||
}
|
||
|
||
private static function scopeKey(?string $ider, ?array $rule, string $shop, string $platform, ?string $band): string
|
||
{
|
||
$owner = mb_strtoupper($ider ?? '未匹配');
|
||
$type = $rule['rule_type'] ?? null;
|
||
if ($type === 'ider') {
|
||
return $owner . '|ider';
|
||
}
|
||
if ($type === 'shop' || $type === 'shop_level') {
|
||
return $owner . '|' . strtoupper($type) . '|' . mb_strtoupper($shop !== '' ? $shop : '-') . '|' . ($band ?? '-');
|
||
}
|
||
|
||
return $owner . '|platform|' . mb_strtoupper($platform !== '' ? $platform : '-') . '|' . ($band ?? '-');
|
||
}
|
||
|
||
public static function ruleLabel(array $rule): string
|
||
{
|
||
return match ($rule['rule_type']) {
|
||
'ider' => 'ID负责人:' . $rule['ider'],
|
||
'shop_level' => '店铺+职级:' . $rule['shop_name'] . '/' . $rule['position_level'],
|
||
'shop' => '店铺:' . $rule['shop_name'],
|
||
default => '平台+职级:' . $rule['platform'] . '/' . $rule['position_level'] . ($rule['channel'] !== '' ? '/' . $rule['channel'] : ''),
|
||
};
|
||
}
|
||
|
||
/** 平台归一(顺序不能乱:京喜在京东前、天猫在淘宝前)。 */
|
||
public static function platform(string $raw): string
|
||
{
|
||
foreach ([['京喜', '京喜'], ['京东', '京东'], ['天猫', '天猫'], ['拼多多', '拼多多'], ['PDD', '拼多多'], ['抖音', '抖音'], ['淘宝', '淘宝'], ['阿里', '阿里巴巴'], ['1688', '阿里巴巴'], ['ALIBABA', '阿里巴巴']] as [$needle, $platform]) {
|
||
if (str_contains(mb_strtoupper($raw), $needle)) {
|
||
return $platform;
|
||
}
|
||
}
|
||
|
||
return '未归属';
|
||
}
|
||
|
||
/** 职级档位:取第一个「P/M+数字」,须在 P0~P7、M1~M5 内。 */
|
||
public static function band(string $level): ?string
|
||
{
|
||
if (preg_match('/[PM][0-9]/', strtoupper($level), $match) !== 1) {
|
||
return null;
|
||
}
|
||
|
||
return in_array($match[0], self::BANDS, true) ? $match[0] : null;
|
||
}
|
||
|
||
/** 种菜报销金额(分):实付金额字段,为空才取最终报销金额字段,再空记 0。 */
|
||
public static function amount(array $row): int
|
||
{
|
||
foreach (['actual_paid_amount', 'reimbursement_amount'] as $field) {
|
||
$value = $row[$field] ?? null;
|
||
if ($value !== null && trim((string) $value) !== '' && is_numeric(str_replace(',', '', (string) $value))) {
|
||
return PlantingReimbursementAuditor::cents($value);
|
||
}
|
||
}
|
||
|
||
return 0;
|
||
}
|
||
|
||
/** @return list<string> 商品ID(按商品行顺序,去空去重) */
|
||
private static function productIds(array $row): array
|
||
{
|
||
$ids = [];
|
||
foreach (preg_split('/[\r\n,]+/', (string) ($row['platform_product_id'] ?? '')) ?: [] as $id) {
|
||
$id = trim($id);
|
||
if ($id !== '' && ! in_array($id, $ids, true)) {
|
||
$ids[] = $id;
|
||
}
|
||
}
|
||
|
||
return $ids;
|
||
}
|
||
|
||
private static function time(string $value): string
|
||
{
|
||
$value = str_replace(['/', 'T'], ['-', ' '], trim($value));
|
||
if (preg_match('/^(\d{4})-(\d{1,2})-(\d{1,2})(?:\s+(\d{1,2}):(\d{2})(?::(\d{2}))?)?/', $value, $m) !== 1) {
|
||
return '';
|
||
}
|
||
|
||
return sprintf('%04d-%02d-%02d %02d:%02d:%02d', $m[1], $m[2], $m[3], $m[4] ?? 0, $m[5] ?? 0, $m[6] ?? 0);
|
||
}
|
||
|
||
private static function limit(mixed $value): ?int
|
||
{
|
||
if ($value === null || trim((string) $value) === '') {
|
||
return null;
|
||
}
|
||
|
||
return PlantingReimbursementAuditor::cents($value);
|
||
}
|
||
|
||
private static function enabled(mixed $value): bool
|
||
{
|
||
return ! in_array(strtolower(trim((string) $value)), ['0', 'false', '停用', ''], true) || $value === true;
|
||
}
|
||
|
||
private static function key(string $value): string
|
||
{
|
||
return mb_strtoupper(trim($value));
|
||
}
|
||
|
||
private static function money(int $cents): string
|
||
{
|
||
return PlantingReimbursementAuditor::money($cents);
|
||
}
|
||
}
|