generated from liutk/owl-admin-base
89 lines
2.6 KiB
PHP
89 lines
2.6 KiB
PHP
<?php
|
|
|
|
namespace App\Admin\Services;
|
|
|
|
use App\Admin\Filters\StoreFilter;
|
|
use App\Models\Store;
|
|
use App\Enums\StoreRole;
|
|
use Illuminate\Support\Facades\Validator;
|
|
use Illuminate\Validation\Rule;
|
|
|
|
class StoreService extends BaseService
|
|
{
|
|
protected array $withRelationships = ['category', 'level', 'business', 'master'];
|
|
|
|
protected string $modelName = Store::class;
|
|
|
|
protected string $modelFilterName = StoreFilter::class;
|
|
|
|
public function store($data): bool
|
|
{
|
|
$data = $this->resloveData($data);
|
|
|
|
$validate = $this->validate($data);
|
|
if ($validate !== true) {
|
|
$this->setError($validate);
|
|
return false;
|
|
}
|
|
|
|
$model = $this->modelName::create($data);
|
|
|
|
// 设置店长
|
|
$model->employees()->attach([$data['master_id'] => ['role' => StoreRole::Master]]);
|
|
|
|
return true;
|
|
}
|
|
|
|
public function update($primaryKey, $data): bool
|
|
{
|
|
$model = $this->query()->whereKey($primaryKey)->firstOrFail();
|
|
$data = $this->resloveData($data, $model);
|
|
$validate = $this->validate($data, $model);
|
|
if ($validate !== true) {
|
|
$this->setError($validate);
|
|
return false;
|
|
}
|
|
|
|
// 修改店长
|
|
if (isset($data['master_id']) && $data['master_id'] != $model->master_id) {
|
|
$store->employees()->detach($model->master_id);
|
|
$store->employees()->attach([$data['master_id'] => ['role' => StoreRole::Master]]);
|
|
}
|
|
|
|
return $model->update($data);
|
|
}
|
|
|
|
public function resloveData($data, $model = null)
|
|
{
|
|
if (isset($data['location'])) {
|
|
$data['lon'] = data_get($data['location'], 'lng');
|
|
$data['lat'] = data_get($data['location'], 'lat');
|
|
}
|
|
return $data;
|
|
}
|
|
|
|
public function validate($data, $model = null)
|
|
{
|
|
$createRules = [
|
|
'title' => ['required'],
|
|
'master_id' => ['required', Rule::unique('stores', 'master_id')],
|
|
'category_id' => ['required'],
|
|
'business_id' => ['required'],
|
|
'level_id' => ['required'],
|
|
'region' => ['required'],
|
|
'lon' => ['required'],
|
|
'lat' => ['required'],
|
|
];
|
|
$updateRules = [
|
|
'master_id' => [Rule::unique($model, 'master_id')]
|
|
];
|
|
$validator = Validator::make($data, $model ? $updateRules : $createRules, [
|
|
'master_id.unique' => '已经是店长了',
|
|
]);
|
|
if ($validator->fails()) {
|
|
return $validator->errors()->first();
|
|
}
|
|
return true;
|
|
}
|
|
}
|