Refactor ShiftForm to streamline field definitions and implement unique code generation for shifts based on their names. Update ShiftFactory to utilize the new code generation method.
This commit is contained in:
@@ -14,28 +14,25 @@ class ShiftForm
|
||||
{
|
||||
return $schema
|
||||
->components([
|
||||
TimePicker::make('starts_at')
|
||||
->label(__('hr.fields.starts_at'))
|
||||
->required()
|
||||
->seconds(false),
|
||||
TimePicker::make('ends_at')
|
||||
->label(__('hr.fields.ends_at'))
|
||||
->required()
|
||||
->seconds(false),
|
||||
|
||||
TextInput::make('name')
|
||||
->label(__('hr.fields.name'))
|
||||
->required()
|
||||
->maxLength(255),
|
||||
TextInput::make('code')
|
||||
->label(__('hr.fields.code'))
|
||||
->required()
|
||||
->maxLength(50)
|
||||
->unique(ignoreRecord: true),
|
||||
TimePicker::make('starts_at')
|
||||
->label(__('hr.fields.starts_at'))
|
||||
->required()
|
||||
->seconds(false),
|
||||
TimePicker::make('ends_at')
|
||||
->label(__('hr.fields.ends_at'))
|
||||
->required()
|
||||
->seconds(false),
|
||||
|
||||
Textarea::make('description')
|
||||
->label(__('hr.fields.description'))
|
||||
->rows(3)
|
||||
->columnSpanFull(),
|
||||
Toggle::make('is_active')
|
||||
->rows(3),
|
||||
|
||||
Toggle::make('is_active')
|
||||
->label(__('hr.fields.active'))
|
||||
->default(true)
|
||||
->required(),
|
||||
|
||||
@@ -9,6 +9,7 @@ use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
use Illuminate\Database\Eloquent\SoftDeletes;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
class Shift extends Model
|
||||
{
|
||||
@@ -34,6 +35,38 @@ class Shift extends Model
|
||||
];
|
||||
}
|
||||
|
||||
protected static function booted(): void
|
||||
{
|
||||
static::saving(function (Shift $shift): void {
|
||||
if (blank($shift->code) && filled($shift->name)) {
|
||||
$shift->code = static::generateUniqueCodeFromName(
|
||||
$shift->name,
|
||||
$shift->id,
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public static function generateUniqueCodeFromName(string $name, ?int $ignoreId = null): string
|
||||
{
|
||||
$base = Str::upper(Str::slug($name));
|
||||
|
||||
$query = static::query()
|
||||
->when($ignoreId, fn ($query) => $query->where('id', '!=', $ignoreId));
|
||||
|
||||
if (! $query->clone()->where('code', $base)->exists()) {
|
||||
return $base;
|
||||
}
|
||||
|
||||
$maxSuffix = $query->clone()
|
||||
->where('code', 'like', "{$base}-%")
|
||||
->pluck('code')
|
||||
->map(fn (string $code): int => (int) Str::after($code, "{$base}-"))
|
||||
->max();
|
||||
|
||||
return "{$base}-".(($maxSuffix ?? 0) + 1);
|
||||
}
|
||||
|
||||
public function employees(): HasMany
|
||||
{
|
||||
return $this->hasMany(Employee::class);
|
||||
|
||||
Reference in New Issue
Block a user