store-manage/app/Admin/Services/AgreementService.php

88 lines
2.5 KiB
PHP

<?php
namespace App\Admin\Services;
use App\Admin\Filters\AgreementFilter;
use App\Models\{Agreement, WorkflowCheck};
use Illuminate\Support\Facades\{Validator, Storage};
use Illuminate\Support\Str;
class AgreementService extends BaseService
{
protected array $withRelationships = ['employee', 'workflow'];
protected string $modelName = Agreement::class;
protected string $modelFilterName = AgreementFilter::class;
public function resloveData($data, $model = null)
{
if (isset($data['images']) && $data['images']) {
$images = [];
foreach ($data['images'] as $value) {
if (is_array($value)) {
$image = data_get($value, 'value');
$url = Str::startsWith($image, ['http://', 'https://']) ? $image : Storage::url($image);
array_push($images, [
'value' => $image,
'preview' => $url,
]);
} else {
array_push($images, [
'value' => $value,
'preview' => $value,
]);
}
}
$data['images'] = $images;
}
return $data;
}
public function validate($data, $model = null)
{
$createRules = [
'employee_id' => ['required'],
'name' => ['required'],
];
$updateRules = [];
$validator = Validator::make($data, $model ? $updateRules : $createRules);
if ($validator->fails()) {
return $validator->errors()->first();
}
return true;
}
public function update($primaryKey, $data): bool
{
$model = $this->query()->whereKey($primaryKey)->firstOrFail();
if (!$model->canUpdate()) {
return $this->setError('审核中, 无法修改');
}
$data = $this->resloveData($data, $model);
$validate = $this->validate($data, $model);
if ($validate !== true) {
$this->setError($validate);
return false;
}
$model->update($data);
$this->currentModel = $model;
return true;
}
public function delete(string $ids): mixed
{
$list = $this->query()->with(['workflow'])->whereIn('id', explode(',', $ids))->get();
foreach ($list as $item) {
if (!$item->canUpdate()) {
return $this->setError('审核中, 无法删除');
}
$item->delete();
}
return true;
}
}