98 lines
2.7 KiB
PHP
98 lines
2.7 KiB
PHP
<?php
|
|
|
|
namespace App\Admin\Forms;
|
|
|
|
use App\Models\Coupon;
|
|
use App\Models\ProductPart;
|
|
use App\Models\ProductPartCoupon;
|
|
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 PartCoupon 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_parts.coupons');
|
|
}
|
|
|
|
/**
|
|
* Handle the form request.
|
|
*
|
|
* @param array $input
|
|
*
|
|
* @return mixed
|
|
*/
|
|
public function handle(array $input)
|
|
{
|
|
$couponIds = [];
|
|
$coupons = [];
|
|
$delCouponIds = [];
|
|
foreach ($input['coupons'] as $coupon) {
|
|
if ($coupon['_remove_'] == 1) {
|
|
$delCouponIds[] = $coupon['id'];
|
|
} else {
|
|
if (is_null($coupon['id'])) {
|
|
$coupons[] = new ProductPartCoupon($coupon);
|
|
} else {
|
|
$_coupon = ProductPartCoupon::find($coupon['id']);
|
|
$_coupon->coupon_id = $coupon['coupon_id'];
|
|
$_coupon->num = $coupon['num'];
|
|
|
|
$coupons[] = $_coupon;
|
|
}
|
|
}
|
|
}
|
|
$partId = $input['part_id'];
|
|
$part = ProductPart::findOrFail($partId);
|
|
|
|
try {
|
|
DB::beginTransaction();
|
|
$part->coupons()->saveMany($coupons);
|
|
|
|
ProductPartCoupon::whereIn('id', $delCouponIds)->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;
|
|
$part = ProductPart::with('coupons')->findOrFail($id);
|
|
|
|
$this->hasMany('coupons', function (NestedForm $form) {
|
|
$form->select('coupon_id')->options(function ($id) {
|
|
$coupon = Coupon::find($id);
|
|
if ($coupon) {
|
|
return [$coupon->id => $coupon->name];
|
|
}
|
|
})->ajax(admin_route('api.coupons'))->required();
|
|
$form->number('num')->min(1)->default(1);
|
|
})->customFormat(function () use ($part) {
|
|
return $part->coupons;
|
|
});
|
|
$this->hidden('part_id')->value($id);
|
|
}
|
|
}
|