Port the Fuc 0.12.0 frontend and default-off VIP plugin. Include the previously approved password-reset token revocation. Deploy only to an independent FUC-XB test instance; no production cutover.
115 lines
8.5 KiB
PHP
115 lines
8.5 KiB
PHP
<?php
|
|
namespace Plugin\VipLoyalty;
|
|
use App\Models\{User,Order,Plan};
|
|
use Illuminate\Support\Facades\DB;
|
|
use Illuminate\Validation\ValidationException;
|
|
final class Service {
|
|
public function __construct(private Settings $settings) {}
|
|
public function enabled(): bool { return $this->settings->values()['enabled']; }
|
|
private function account(User $user): object {
|
|
DB::table('fuc_vip_accounts')->insertOrIgnore(['user_id'=>$user->id,'opening_cents'=>0,'cumulative_cents'=>0,'manual_discount'=>$user->discount,
|
|
'created_at'=>time(),'updated_at'=>time()]);
|
|
return DB::table('fuc_vip_accounts')->where('user_id',$user->id)->lockForUpdate()->first();
|
|
}
|
|
private function apply(User $user,object $account): object {
|
|
$manual=$account->manual_discount;
|
|
// Respect a native admin discount edit since our last write.
|
|
if($account->applied_discount!==null && (int)$user->discount!==(int)$account->applied_discount)$manual=$user->discount;
|
|
$vip=0;foreach($this->settings->levels() as $tier)if($account->cumulative_cents >= $tier['threshold_cents'])$vip=$tier['discount'];
|
|
$effective=max((int)$manual,$vip);
|
|
$user->discount=$effective;$user->save();
|
|
DB::table('fuc_vip_accounts')->where('user_id',$user->id)->update(['manual_discount'=>$manual,'applied_discount'=>$effective,'updated_at'=>time()]);
|
|
$account->manual_discount=$manual;$account->applied_discount=$effective;
|
|
return $account;
|
|
}
|
|
public function sync(int $userId): ?object {
|
|
if(!$this->enabled())return null;
|
|
return DB::transaction(function()use($userId){
|
|
$user=User::whereKey($userId)->lockForUpdate()->firstOrFail();
|
|
return $this->apply($user,$this->account($user));
|
|
});
|
|
}
|
|
public function opening(int $userId,string $uuid,int $cents,string $reference): void {
|
|
if(!$this->enabled())throw new \RuntimeException('VIP未在当前实例启用');
|
|
if($cents<0 || !preg_match('/^[a-f0-9]{64}$/D',$reference))throw new \InvalidArgumentException('Invalid opening');
|
|
DB::transaction(function()use($userId,$uuid,$cents,$reference){
|
|
$user=User::whereKey($userId)->lockForUpdate()->firstOrFail();
|
|
if(!hash_equals($user->uuid,$uuid))throw new \RuntimeException('迁移用户UUID不一致');
|
|
$account=$this->account($user);
|
|
if($account->opening_reference!==null) {
|
|
if($account->opening_reference!==$reference || (int)$account->opening_cents!==$cents)throw new \RuntimeException('期初已存在且不同,禁止覆盖');
|
|
return;
|
|
}
|
|
if(DB::table('fuc_vip_entries')->where('user_id',$userId)->where('kind','!=','opening')->exists())throw new \RuntimeException('用户已有新消费,禁止补写期初');
|
|
DB::table('fuc_vip_entries')->insert(['user_id'=>$userId,'entry_key'=>'opening:'.$userId,'kind'=>'opening','amount_cents'=>$cents,'created_at'=>time()]);
|
|
// Migrated discount is old VIP, not an unrelated native manual discount.
|
|
DB::table('fuc_vip_accounts')->where('user_id',$userId)->update(['opening_cents'=>$cents,'cumulative_cents'=>$cents,'manual_discount'=>null,'applied_discount'=>$user->discount,'opening_reference'=>$reference]);
|
|
$account=DB::table('fuc_vip_accounts')->where('user_id',$userId)->first();$this->apply($user,$account);
|
|
});
|
|
}
|
|
public function openingOrder(Order $order): void {
|
|
if(!$this->enabled())return;
|
|
if(DB::transactionLevel()<1)throw new \RuntimeException('VIP累计必须与开通同事务');
|
|
if((int)$order->status!==Order::STATUS_PROCESSING || !in_array($order->period,[Plan::PERIOD_MONTHLY,Plan::PERIOD_QUARTERLY,Plan::PERIOD_HALF_YEARLY,Plan::PERIOD_YEARLY,Plan::PERIOD_TWO_YEARLY,Plan::PERIOD_THREE_YEARLY,Plan::PERIOD_ONETIME],true))return;
|
|
$user=User::whereKey($order->user_id)->lockForUpdate()->firstOrFail();$account=$this->account($user);
|
|
$key='purchase:'.$order->id;
|
|
if(DB::table('fuc_vip_entries')->where('entry_key',$key)->exists())return;
|
|
$amount=(int)$order->total_amount+(int)$order->balance_amount;
|
|
if($amount<0)throw new \RuntimeException('套餐消费金额不能为负');
|
|
DB::table('fuc_vip_entries')->insert(['user_id'=>$user->id,'order_id'=>$order->id,'entry_key'=>$key,'kind'=>'purchase','amount_cents'=>$amount,'created_at'=>time()]);
|
|
$account->cumulative_cents+=(int)$amount;
|
|
DB::table('fuc_vip_accounts')->where('user_id',$user->id)->update(['cumulative_cents'=>$account->cumulative_cents]);
|
|
$this->apply($user,$account);
|
|
}
|
|
public function reverse(int $orderId,int $cents,string $reference): void {
|
|
if(!$this->enabled())throw new \RuntimeException('VIP未启用');
|
|
if($cents<=0 || !preg_match('/^[A-Za-z0-9_-]{1,80}$/D',$reference))throw new \InvalidArgumentException('Invalid reversal');
|
|
DB::transaction(function()use($orderId,$cents,$reference){
|
|
$order=Order::whereKey($orderId)->lockForUpdate()->firstOrFail();
|
|
$user=User::whereKey($order->user_id)->lockForUpdate()->firstOrFail();$account=$this->account($user);
|
|
$key='refund:'.$reference;
|
|
$existing=DB::table('fuc_vip_entries')->where('entry_key',$key)->first();
|
|
if($existing) {
|
|
if((int)$existing->order_id!==$orderId || -(int)$existing->amount_cents!==$cents)throw new \RuntimeException('退款凭证已用于其他金额或订单');
|
|
return;
|
|
}
|
|
$paid=DB::table('fuc_vip_entries')->where('entry_key','purchase:'.$orderId)->value('amount_cents');
|
|
$reversed=-(int)DB::table('fuc_vip_entries')->where('order_id',$orderId)->where('kind','refund')->sum('amount_cents');
|
|
if($paid===null || $cents>(int)$paid-$reversed)throw ValidationException::withMessages(['amount'=>'VIP冲回超过已计入且未冲回的消费']);
|
|
DB::table('fuc_vip_entries')->insert(['user_id'=>$user->id,'order_id'=>$orderId,'entry_key'=>$key,'kind'=>'refund','amount_cents'=>-$cents,'created_at'=>time()]);
|
|
$account->cumulative_cents=max(0,(int)$account->cumulative_cents-$cents);
|
|
DB::table('fuc_vip_accounts')->where('user_id',$user->id)->update(['cumulative_cents'=>$account->cumulative_cents]);
|
|
$this->apply($user,$account);
|
|
});
|
|
}
|
|
public function suspend(): void {
|
|
// Disable changes discounts only; keep the independent consumption audit intact.
|
|
DB::table('fuc_vip_accounts')->whereNotNull('applied_discount')->orderBy('user_id')->chunkById(200,function($rows){
|
|
foreach($rows as $row)DB::transaction(function()use($row){
|
|
$user=User::whereKey($row->user_id)->lockForUpdate()->first();
|
|
$account=DB::table('fuc_vip_accounts')->where('user_id',$row->user_id)->lockForUpdate()->first();
|
|
if(!$user || $account->applied_discount===null)return;
|
|
if((int)$user->discount===(int)$account->applied_discount){$user->discount=$account->manual_discount;$user->save();}
|
|
DB::table('fuc_vip_accounts')->where('user_id',$row->user_id)->update(['applied_discount'=>null]);
|
|
});
|
|
},'user_id');
|
|
}
|
|
public function manualChanged(array $payload): void {
|
|
if(!$this->enabled() || !array_key_exists('discount',$payload['params']??[]))return;
|
|
$id=$payload['user']->id;
|
|
DB::transaction(function()use($id,$payload){
|
|
$user=User::whereKey($id)->lockForUpdate()->firstOrFail();$account=$this->account($user);
|
|
DB::table('fuc_vip_accounts')->where('user_id',$id)->update(['manual_discount'=>$payload['params']['discount'],'applied_discount'=>$user->discount]);
|
|
$account->manual_discount=$payload['params']['discount'];$account->applied_discount=$user->discount;
|
|
$this->apply($user,$account);
|
|
});
|
|
}
|
|
public function summary(int $userId): array {
|
|
if(!$this->enabled())return ['enabled'=>false];
|
|
$a=$this->sync($userId);$levels=$this->settings->levels();$current=0;$next=null;
|
|
foreach($levels as $tier) {if($a->cumulative_cents >= $tier['threshold_cents'])$current=$tier['level'];elseif($next===null)$next=$tier;}
|
|
return ['enabled'=>true,'cumulative_cents'=>(int)$a->cumulative_cents,'level'=>$current,'name'=>$current?$levels[$current-1]['name']:'普通用户','discount_percent'=>(int)$a->applied_discount,
|
|
'next_level'=>$next,'remaining_cents'=>$next?max(0,$next['threshold_cents']-(int)$a->cumulative_cents):0,'levels'=>$levels];
|
|
}
|
|
}
|