73 lines
1.8 KiB
PHP
73 lines
1.8 KiB
PHP
<?php
|
|
|
|
namespace App\Services;
|
|
|
|
use App\Enums\PointLogAction;
|
|
use App\Exceptions\BizException;
|
|
use App\Models\Admin\Administrator;
|
|
use App\Models\PointLog;
|
|
use App\Models\User;
|
|
use App\Models\UserInfo;
|
|
use Illuminate\Database\Eloquent\Model;
|
|
|
|
class PointService
|
|
{
|
|
/**
|
|
* 变更积分
|
|
*
|
|
* @throws \App\Exceptions\BizException
|
|
*/
|
|
public function change(
|
|
User $user,
|
|
int $points,
|
|
PointLogAction $action,
|
|
?string $remark = null,
|
|
?Model $loggable = null,
|
|
?Administrator $administrator = null,
|
|
) {
|
|
if ($points === 0) {
|
|
return;
|
|
}
|
|
|
|
$userinfo = UserInfo::lockForUpdate()->where('user_id', $user->id)->firstOrFail();
|
|
|
|
switch ($action) {
|
|
case PointLogAction::Recharge:
|
|
if ($points < 0) {
|
|
throw new BizException('积分不能小于 0');
|
|
}
|
|
break;
|
|
|
|
case PointLogAction::Deduction:
|
|
case PointLogAction::Consumption:
|
|
if ($points > 0) {
|
|
throw new BizException('积分不能大于 0');
|
|
}
|
|
break;
|
|
}
|
|
|
|
$before = $userinfo->points;
|
|
$after = $before + $points;
|
|
|
|
if ($after < 0) {
|
|
throw new BizException('积分不足');
|
|
}
|
|
|
|
$userinfo->update([
|
|
'points' => $after,
|
|
]);
|
|
|
|
PointLog::create([
|
|
'loggable_id' => $loggable?->id,
|
|
'loggable_type' => $loggable?->getMorphClass(),
|
|
'user_id' => $user->id,
|
|
'action' => $action,
|
|
'change_points' => $points,
|
|
'before_points' => $before,
|
|
'after_points' => $after,
|
|
'remark' => $remark,
|
|
'administrator_id' => $administrator?->id,
|
|
]);
|
|
}
|
|
}
|