103 lines
3.2 KiB
PHP
103 lines
3.2 KiB
PHP
<?php
|
|
|
|
namespace App\Admin\Forms;
|
|
|
|
use App\Exceptions\BizException;
|
|
use App\Models\DealerProduct;
|
|
use App\Models\DealerUserProduct;
|
|
use App\Models\DealerUserProductLog;
|
|
use Dcat\Admin\Contracts\LazyRenderable;
|
|
use Dcat\Admin\Traits\LazyWidget;
|
|
use Dcat\Admin\Widgets\Form;
|
|
use Illuminate\Database\QueryException;
|
|
use Illuminate\Support\Facades\DB;
|
|
use Throwable;
|
|
|
|
class DealerEditProduct extends Form implements LazyRenderable
|
|
{
|
|
use LazyWidget;
|
|
|
|
/**
|
|
* @param Model|Authenticatable|HasPermissions|null $user
|
|
*
|
|
* @return bool
|
|
*/
|
|
protected function authorize($user): bool
|
|
{
|
|
return $user->can('dcat.admin.dealers.edit_product');
|
|
}
|
|
|
|
/**
|
|
* Handle the form request.
|
|
*
|
|
* @param array $input
|
|
*
|
|
* @return mixed
|
|
*/
|
|
public function handle(array $input)
|
|
{
|
|
$id = $this->payload['id'] ?? 0;
|
|
try {
|
|
DB::beginTransaction();
|
|
$product = DealerUserProduct::where([
|
|
'user_id' => $id,
|
|
'product_id'=>$input['product_id'],
|
|
])->first();
|
|
switch ($input['type']) {
|
|
case DealerUserProductLog::TYPE_ADMIN_IN:
|
|
if (!$product) {
|
|
$product = DealerUserProduct::create([
|
|
'user_id' => $id,
|
|
'product_id'=>$input['product_id'],
|
|
]);
|
|
}
|
|
$product->increment('stock', $input['qty']);
|
|
break;
|
|
case DealerUserProductLog::TYPE_ADMIN_OUT:
|
|
if (!$product) {
|
|
throw new BizException('库存不足');
|
|
}
|
|
$product->decrement('stock', $input['qty']);
|
|
break;
|
|
}
|
|
DealerUserProductLog::create([
|
|
'user_id'=> $id,
|
|
'product_id'=> $input['product_id'],
|
|
'type' => $input['type'],
|
|
'qty'=>$input['qty'],
|
|
'remark'=>'后台改动:'.$input['remark'] ?? null,
|
|
]);
|
|
DB::commit();
|
|
} catch (QueryException $e) {
|
|
DB::rollBack();
|
|
if (strpos($e->getMessage(), 'Numeric value out of range') !== false) {
|
|
$e = new BizException('库存不足');
|
|
}
|
|
throw $e;
|
|
} catch (Throwable $th) {
|
|
DB::rollBack();
|
|
report($th);
|
|
return $this->response()->error('操作失败:'.$th->getMessage());
|
|
}
|
|
|
|
return $this->response()
|
|
->success(__('admin.update_succeeded'))
|
|
->refresh();
|
|
}
|
|
|
|
/**
|
|
* Build a form here.
|
|
*/
|
|
public function form()
|
|
{
|
|
$this->radio('type', '操作')->options([
|
|
DealerUserProductLog::TYPE_ADMIN_IN =>'添加',
|
|
DealerUserProductLog::TYPE_ADMIN_OUT=>'扣减',
|
|
])->required();
|
|
$this->select('product_id', '商品')->options(DealerProduct::all()->pluck('name', 'id'))
|
|
->required();
|
|
$this->number('qty', '数量')->default(1)->min(1);
|
|
$this->text('remark', '备注')->default('调整库存');
|
|
}
|
|
}
|