82 lines
2.3 KiB
PHP
82 lines
2.3 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
|
|
{
|
|
/**
|
|
* 变更积分
|
|
*
|
|
* @param User $user 用户
|
|
* @param int $points 积分
|
|
* @param PointLogAction $action 操作
|
|
* @param $options {remark: 备注, loggable: 来源, administrator: 操作人, store_id: 所属门店}
|
|
* @throws \App\Exceptions\BizException
|
|
*/
|
|
public function change(
|
|
User $user,
|
|
int $points,
|
|
PointLogAction $action,
|
|
// ?string $remark = null,
|
|
// ?Model $loggable = null,
|
|
// ?Administrator $administrator = null,
|
|
$options = []
|
|
) {
|
|
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,
|
|
]);
|
|
$remark = data_get($options, 'remark');
|
|
$loggable = data_get($options, 'loggable');
|
|
$administrator = data_get($options, 'administrator');
|
|
|
|
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,
|
|
'store_id' => data_get($options, 'store_id'),
|
|
]);
|
|
}
|
|
}
|