120 lines
3.4 KiB
PHP
120 lines
3.4 KiB
PHP
<?php
|
||
|
||
namespace App\Admin\Forms;
|
||
|
||
use App\Exceptions\BizException;
|
||
use App\Models\DrawActivityPrize;
|
||
use Dcat\Admin\Contracts\LazyRenderable;
|
||
use Dcat\Admin\Traits\LazyWidget;
|
||
use Dcat\Admin\Widgets\Form;
|
||
use Illuminate\Database\QueryException;
|
||
|
||
class DrawActivityPrizeStockChange extends Form implements LazyRenderable
|
||
{
|
||
use LazyWidget;
|
||
|
||
public const TYPE_ADD = 1;
|
||
public const TYPE_SUB = 2;
|
||
|
||
/**
|
||
* @param Model|Authenticatable|HasPermissions|null $user
|
||
*
|
||
* @return bool
|
||
*/
|
||
protected function authorize($user): bool
|
||
{
|
||
return $user->can('dcat.admin.draw_activities.prize_stock');
|
||
}
|
||
|
||
/**
|
||
* Handle the form request.
|
||
*
|
||
* @param array $input
|
||
*
|
||
* @return mixed
|
||
*/
|
||
public function handle(array $input)
|
||
{
|
||
$drawActivityPrize = DrawActivityPrize::findOrFail($this->payload['id']);
|
||
|
||
if ($drawActivityPrize->activity->isClosed()) {
|
||
throw new BizException('活动已结束');
|
||
}
|
||
|
||
$limited = (bool) $input['limited'];
|
||
|
||
try {
|
||
if ($limited) {
|
||
$stock = (int) $input['stock'];
|
||
|
||
// 如果限量
|
||
if ($drawActivityPrize->limited) {
|
||
if ($stock === 0) {
|
||
throw new BizException('库存不能为0');
|
||
}
|
||
|
||
$drawActivityPrize->increment('stock', $stock);
|
||
} else {
|
||
$drawActivityPrize->update([
|
||
'limited' => $limited,
|
||
'stock' => $stock,
|
||
]);
|
||
}
|
||
} else {
|
||
$drawActivityPrize->update([
|
||
'limited' => $limited,
|
||
'stock' => 0,
|
||
]);
|
||
}
|
||
} catch (QueryException $e) {
|
||
if (strpos($e->getMessage(), 'Numeric value out of range') !== false) {
|
||
$e = new BizException('奖品库存不足');
|
||
}
|
||
|
||
throw $e;
|
||
}
|
||
|
||
return $this->response()
|
||
->success(__('admin.update_succeeded'))
|
||
->refresh();
|
||
}
|
||
|
||
/**
|
||
* Build a form here.
|
||
*/
|
||
public function form()
|
||
{
|
||
$drawActivityPrize = DrawActivityPrize::findOrFail($this->payload['id']);
|
||
|
||
$this->radio('limited', '是否限量')
|
||
->options([
|
||
0 => '否',
|
||
1 => '是',
|
||
])
|
||
->when(1, function () use ($drawActivityPrize) {
|
||
if ($drawActivityPrize->limited) {
|
||
$this->number('stock', '库存')
|
||
->rules(['required_if:limited,1', 'int'], ['required_if' => '不能为空'])
|
||
->help('库存大于0时,增加库存;小于0,减少库存')
|
||
->setLabelClass(['asterisk']);
|
||
} else {
|
||
$this->number('stock', '初始库存')
|
||
->min(0)
|
||
->rules(['required_if:limited,1', 'int', 'min:0'], ['required_if' => '不能为空'])
|
||
->setLabelClass(['asterisk']);
|
||
}
|
||
})
|
||
->value($drawActivityPrize->limited)
|
||
->customFormat(function ($v) {
|
||
return $v ? 1 : 0;
|
||
})
|
||
->setLabelClass(['asterisk']);
|
||
}
|
||
|
||
public function default()
|
||
{
|
||
return [
|
||
];
|
||
}
|
||
}
|