109 lines
3.0 KiB
PHP
109 lines
3.0 KiB
PHP
<?php
|
|
|
|
namespace App\Admin\Forms;
|
|
|
|
use App\Models\ProductSku;
|
|
use App\Models\ProductSpu;
|
|
use App\Models\ProductSpuSpec;
|
|
use Dcat\Admin\Contracts\LazyRenderable;
|
|
use Dcat\Admin\Traits\LazyWidget;
|
|
use Dcat\Admin\Widgets\Form;
|
|
use Illuminate\Support\Facades\DB;
|
|
use Throwable;
|
|
|
|
class AddSku 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_spus.add_sku');
|
|
}
|
|
|
|
/**
|
|
* Handle the form request.
|
|
*
|
|
* @param array $input
|
|
*
|
|
* @return mixed
|
|
*/
|
|
public function handle(array $input)
|
|
{
|
|
if ($input) {
|
|
$spuId = $this->payload['spu_id'] ?? 0;
|
|
$_skuSpecs = [];
|
|
$_price = 0;
|
|
foreach ($input as $id => $value) {
|
|
$spuSpec = ProductSpuSpec::where('id', $id)->first();
|
|
foreach ($spuSpec->items as $item) {
|
|
if ($item['name'] == $value) {
|
|
$_skuSpecs[$id] = $item['name'];
|
|
$_price += $item['value'];
|
|
}
|
|
}
|
|
}
|
|
//如果存在该规格组合
|
|
$skuQuery = ProductSku::where('spu_id', $spuId);
|
|
foreach ($_skuSpecs as $id=> $spec) {
|
|
$skuQuery->where('specs->'.$id, $spec);
|
|
}
|
|
if ($skuQuery->first()) {
|
|
return $this->response()->error(__('admin_message.forms.add_sku.errors.has_specs'));
|
|
} else {
|
|
$spu = ProductSpu::findOrFail($spuId);
|
|
try {
|
|
DB::beginTransaction();
|
|
ProductSku::createBySpec([
|
|
'specs'=>$_skuSpecs,
|
|
'price'=>$_price,
|
|
], $spu);
|
|
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()
|
|
{
|
|
$spuId = $this->payload['spu_id'] ?? 0;
|
|
|
|
$spu = ProductSpu::findOrFail($spuId);
|
|
foreach ($spu->specs as $spec) {
|
|
$this->select($spec->id, $spec->name)->options(function () use ($spec) {
|
|
return collect($spec->items)->pluck('name', 'name');
|
|
})->required();
|
|
}
|
|
$this->disableResetButton();
|
|
}
|
|
|
|
/**
|
|
* The data of the form.
|
|
*
|
|
* @return array
|
|
*/
|
|
public function default()
|
|
{
|
|
return [
|
|
// 'name' => 'John Doe',
|
|
// 'email' => 'John.Doe@gmail.com',
|
|
];
|
|
}
|
|
}
|