You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
virt/web/app/Services/ReferralConfig.php

199 lines
6.7 KiB
PHP

<?php
namespace App\Services;
use App\Models\Configurations;
/**
* Runtime settings for referral rewards.
*
* The values are kept in the administrator configuration table and cached in
* Redis. The configured flag is intentionally retained so installations
* upgraded from the old per-referrer `user.aff_rate` model keep their current
* behaviour until an administrator explicitly saves the new global rate.
*/
class ReferralConfig
{
public const RATE_KEY = 'referral_reward_rate';
public const VALID_DAYS_KEY = 'referral_reward_days';
public const ENABLED_KEY = 'referral_reward_enabled';
public const CACHE_KEY = 'referral:config';
public const CACHE_TTL_MINUTES = 5;
public const DEFAULT_RATE = '20';
public const DEFAULT_VALID_DAYS = '730';
public const DEFAULT_ENABLED = 'true';
private const DEFAULTS = [
self::RATE_KEY => self::DEFAULT_RATE,
self::VALID_DAYS_KEY => self::DEFAULT_VALID_DAYS,
self::ENABLED_KEY => self::DEFAULT_ENABLED,
];
/**
* @return array{referral_reward_rate: string, referral_reward_days: int,
* referral_reward_enabled: bool, rate_configured: bool,
* days_configured: bool, enabled_configured: bool}
*/
public static function values(): array
{
$raw = null;
try {
$redis = new RedisClient();
$cached = $redis->get(self::CACHE_KEY, self::CACHE_TTL_MINUTES, static function () {
return json_encode(self::loadRaw(), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
});
if (is_string($cached) && $cached !== '') {
$decoded = json_decode($cached, true);
if (is_array($decoded)) {
$raw = $decoded;
}
}
} catch (\Throwable $exception) {
// Redis is an optional acceleration layer. Database settings are
// still authoritative when it is unavailable during a request.
}
if (!is_array($raw)) {
$raw = self::loadRaw();
}
$rate = self::normalizeRate($raw[self::RATE_KEY] ?? self::DEFAULT_RATE);
$days = self::normalizeDays($raw[self::VALID_DAYS_KEY] ?? self::DEFAULT_VALID_DAYS);
$enabled = self::normalizeBoolean($raw[self::ENABLED_KEY] ?? self::DEFAULT_ENABLED);
return [
self::RATE_KEY => $rate,
self::VALID_DAYS_KEY => $days,
self::ENABLED_KEY => $enabled,
'rate_configured' => (bool) ($raw[self::RATE_KEY . '_configured'] ?? false),
'days_configured' => (bool) ($raw[self::VALID_DAYS_KEY . '_configured'] ?? false),
'enabled_configured' => (bool) ($raw[self::ENABLED_KEY . '_configured'] ?? false),
];
}
public static function clearCache(?RedisClient $redis = null): void
{
try {
($redis ?? new RedisClient())->del(self::CACHE_KEY);
} catch (\Throwable $exception) {
// A stale Redis cache must never prevent an administrator from
// saving a valid database configuration.
}
}
public static function normalizeRate($value): string
{
$value = trim((string) $value);
if (!preg_match('/^(?:\d{1,3})(?:\.\d{1,2})?$/D', $value)) {
return self::DEFAULT_RATE;
}
$number = (float) $value;
if (!is_finite($number) || $number < 0 || $number > 100) {
return self::DEFAULT_RATE;
}
return number_format($number, 2, '.', '');
}
public static function validateRate($value): string
{
$value = trim((string) $value);
if (!preg_match('/^(?:\d{1,3})(?:\.\d{1,2})?$/D', $value)
|| (float) $value < 0 || (float) $value > 100) {
throw new \InvalidArgumentException('推广返利比例必须是 0 至 100 之间的数字,最多两位小数');
}
return number_format((float) $value, 2, '.', '');
}
public static function normalizeDays($value): int
{
$value = trim((string) $value);
if (!preg_match('/^\d+$/D', $value)) {
return (int) self::DEFAULT_VALID_DAYS;
}
return max(1, min(3650, (int) $value));
}
public static function validateDays($value): int
{
$value = trim((string) $value);
if (!preg_match('/^\d+$/D', $value) || (int) $value < 1 || (int) $value > 3650) {
throw new \InvalidArgumentException('推广返利有效期必须是 1 至 3650 天');
}
return (int) $value;
}
public static function normalizeBoolean($value): bool
{
return in_array(strtolower(trim((string) $value)), ['1', 'true', 'yes', 'on'], true);
}
public static function validateBoolean($value): string
{
$value = strtolower(trim((string) $value));
if (!in_array($value, ['0', '1', 'true', 'false', 'yes', 'no', 'on', 'off'], true)) {
throw new \InvalidArgumentException('推广返利开关值无效');
}
return self::normalizeBoolean($value) ? 'true' : 'false';
}
public static function isEligible($user, ?int $now = null): bool
{
$values = self::values();
if (!$values[self::ENABLED_KEY] || (int) ($user->ref_by ?? 0) <= 0) {
return false;
}
$registeredAt = strtotime((string) ($user->reg_date ?? ''));
if ($registeredAt === false) {
return false;
}
$now = $now ?? time();
$age = $now - $registeredAt;
return $age >= 0 && $age <= $values[self::VALID_DAYS_KEY] * 86400;
}
public static function rateFor($referrer): float
{
$values = self::values();
if ($values['rate_configured']) {
return (float) $values[self::RATE_KEY];
}
// Existing installations may still rely on a per-referrer rate. The
// administrator can switch to the global rule by saving the setting.
$legacy = (float) ($referrer->aff_rate ?? 0);
return max(0.0, min(100.0, $legacy));
}
private static function loadRaw(): array
{
$raw = self::DEFAULTS;
foreach (array_keys(self::DEFAULTS) as $key) {
$raw[$key . '_configured'] = false;
}
try {
$rows = Configurations::whereIn('name', array_keys(self::DEFAULTS))->get()->keyBy('name');
foreach (array_keys(self::DEFAULTS) as $key) {
if (isset($rows[$key])) {
$raw[$key] = (string) $rows[$key]->value;
$raw[$key . '_configured'] = true;
}
}
} catch (\Throwable $exception) {
// Fresh bootstrap/tests may not have created the settings table.
}
return $raw;
}
}