105 lines
3.3 KiB
PHP
105 lines
3.3 KiB
PHP
<?php
|
|
|
|
namespace App\Admin\Forms;
|
|
|
|
use App\Models\ProductGift;
|
|
use App\Models\ProductSku;
|
|
use Dcat\Admin\Contracts\LazyRenderable;
|
|
use Dcat\Admin\Form\NestedForm;
|
|
use Dcat\Admin\Traits\LazyWidget;
|
|
use Dcat\Admin\Widgets\Form;
|
|
use Illuminate\Support\Facades\DB;
|
|
use Throwable;
|
|
|
|
class SkuGift extends Form implements LazyRenderable
|
|
{
|
|
use LazyWidget;
|
|
|
|
/**
|
|
* @param Model|Authenticatable|HasPermissions|null $user
|
|
*
|
|
* @return bool
|
|
*/
|
|
protected function authorize($user): bool
|
|
{
|
|
return $user->can('dcat.admin.product_skus.sku_gift');
|
|
}
|
|
|
|
/**
|
|
* Handle the form request.
|
|
*
|
|
* @param array $input
|
|
*
|
|
* @return mixed
|
|
*/
|
|
public function handle(array $input)
|
|
{
|
|
$giftSkuIds = [];
|
|
$giftSku = [];
|
|
$delGiftIds = [];
|
|
foreach ($input['gifts'] as $gift) {
|
|
if ($gift['_remove_'] == 1) {
|
|
$delGiftIds[] = $gift['id'];
|
|
} else {
|
|
if (is_null($gift['id'])) {
|
|
$gift['remaining'] = $gift['limit'];//剩余数量;
|
|
$giftSku[] = new ProductGift($gift);
|
|
} else {
|
|
$_gift = ProductGift::find($gift['id']);
|
|
$_gift->gift_sku_id = $gift['gift_sku_id'];
|
|
$_gift->num = $gift['num'];
|
|
$_gift->limit = $gift['limit'];
|
|
$_gift->remaining = $gift['limit'] > 0 ? ($gift['limit'] - $_gift->sent) : $gift['limit'];
|
|
if ($_gift->remaining < 0) {
|
|
return $this->response()->error('无法设置限制数量小于已发数量');
|
|
}
|
|
$giftSku[] = $_gift;
|
|
}
|
|
}
|
|
}
|
|
$skuId = $input['sku_id'];
|
|
$sku = ProductSku::findOrFail($skuId);
|
|
if ($sku->verify_state == 1 || !is_null($sku->release_at)) {//如果是审核中,或者上架中,则无法修改。
|
|
return $this->response()->error('当前商品目前无法修改赠品');
|
|
}
|
|
try {
|
|
DB::beginTransaction();
|
|
$sku->gifts()->saveMany($giftSku);
|
|
|
|
ProductGift::whereIn('id', $delGiftIds)->delete();
|
|
DB::commit();
|
|
} catch (Throwable $th) {
|
|
DB::rollBack();
|
|
report($th);
|
|
return $this->response()->error('操作失败:'.$th->getMessage())->refresh();
|
|
}
|
|
|
|
return $this->response()
|
|
->success(__('admin.update_succeeded'))
|
|
->refresh();
|
|
}
|
|
|
|
/**
|
|
* Build a form here.
|
|
*/
|
|
public function form()
|
|
{
|
|
$id = $this->payload['id'] ?? 0;
|
|
$sku = ProductSku::with('gifts')->findOrFail($id);
|
|
|
|
$this->hasMany('gifts', function (NestedForm $form) {
|
|
$form->select('gift_sku_id')->options(function ($id) {
|
|
$sku = ProductSku::find($id);
|
|
if ($sku) {
|
|
return [$sku->id => $sku->name];
|
|
}
|
|
})->ajax(admin_route('api.product_skus'))->required();
|
|
$form->number('num')->min(1)->default(1);
|
|
$form->number('limit')->min(0)->default(0);
|
|
})->customFormat(function () use ($sku) {
|
|
return $sku->gifts;
|
|
});
|
|
$this->hidden('sku_id')->value($id);
|
|
}
|
|
}
|