102 lines
2.7 KiB
PHP
102 lines
2.7 KiB
PHP
<?php
|
|
|
|
namespace App\Admin\Forms;
|
|
|
|
use App\Models\DealerProduct;
|
|
use App\Models\DealerProductSaleRule as DealerProductSaleRuleModel;
|
|
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 DealerProductSaleRule extends Form implements LazyRenderable
|
|
{
|
|
use LazyWidget;
|
|
|
|
/**
|
|
* 权限判断,如不需要可以删除此方法
|
|
*
|
|
* @param Model|Authenticatable|HasPermissions|null $user
|
|
*
|
|
* @return bool
|
|
*/
|
|
protected function authorize($user): bool
|
|
{
|
|
return $user->can('dcat.admin.dealer_products.sale_rules');
|
|
}
|
|
|
|
/**
|
|
* Handle the form request.
|
|
*
|
|
* @param array $input
|
|
*
|
|
* @return mixed
|
|
*/
|
|
public function handle(array $input)
|
|
{
|
|
$productId = $this->payload['id'] ?? 0;
|
|
|
|
$product = DealerProduct::findOrFail($productId);
|
|
$saleRules = [];
|
|
$delRules = [];
|
|
foreach ($input['saleRules'] as $rule) {
|
|
if ($rule['_remove_'] == 1) {
|
|
$delRules[] = $rule['id'];
|
|
} else {
|
|
if (is_null($rule['id'])) {
|
|
$saleRules[] = new DealerProductSaleRuleModel($rule);
|
|
} else {
|
|
$_rule = DealerProductSaleRuleModel::find($rule['id']);
|
|
$_rule['qty'] = $rule['qty'];
|
|
$_rule['price'] = $rule['price'];
|
|
$saleRules[] = $_rule;
|
|
}
|
|
}
|
|
}
|
|
|
|
try {
|
|
DB::beginTransaction();
|
|
$product->saleRules()->saveMany($saleRules);
|
|
|
|
DealerProductSaleRuleModel::whereIn('id', $delRules)->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()
|
|
{
|
|
$this->hasMany('saleRules', '销售规则', function (NestedForm $form) {
|
|
$form->number('qty', '达到数量')->min(0);
|
|
$form->currency('price', '进货单价')->symbol('¥');
|
|
});
|
|
}
|
|
|
|
/**
|
|
* The data of the form.
|
|
*
|
|
* @return array
|
|
*/
|
|
public function default()
|
|
{
|
|
$productId = $this->payload['id'] ?? 0;
|
|
|
|
$product = DealerProduct::findOrFail($productId);
|
|
return [
|
|
'saleRules' => $product->saleRules,
|
|
];
|
|
}
|
|
}
|