diff --git a/app/Models/Tenant/LaborCategory.php b/app/Models/Tenant/LaborCategory.php index ddc9b6b..175d3f7 100644 --- a/app/Models/Tenant/LaborCategory.php +++ b/app/Models/Tenant/LaborCategory.php @@ -5,6 +5,7 @@ namespace App\Models\Tenant; use App\Models\Concerns\BelongsToTenant; use App\Models\Scopes\TenantScope; use Illuminate\Database\Eloquent\Model; +use Illuminate\Support\Facades\DB; class LaborCategory extends Model { @@ -16,26 +17,31 @@ class LaborCategory extends Model { parent::boot(); - // When sort_order is changed to a value already occupied by another record, - // shift all records at that position and above up by 1 to make room. static::saving(function (self $cat) { $new = (int) $cat->sort_order; $old = (int) ($cat->getOriginal('sort_order') ?? PHP_INT_MAX); - if ($new === $old) return; - $conflict = static::withoutGlobalScope(TenantScope::class) + // Make room: shift all records at >= new position up by 1. + static::withoutGlobalScope(TenantScope::class) ->where('company_id', $cat->company_id) - ->where('sort_order', $new) + ->where('sort_order', '>=', $new) ->where('id', '!=', $cat->id ?? 0) - ->exists(); + ->increment('sort_order'); + }); - if ($conflict) { - static::withoutGlobalScope(TenantScope::class) - ->where('company_id', $cat->company_id) - ->where('sort_order', '>=', $new) - ->where('id', '!=', $cat->id ?? 0) - ->increment('sort_order', 10); + static::saved(function (self $cat) { + // Renormalize to 1, 2, 3, … to close any gaps left after the move. + $ids = static::withoutGlobalScope(TenantScope::class) + ->where('company_id', $cat->company_id) + ->orderBy('sort_order') + ->orderBy('id') + ->pluck('id'); + + foreach ($ids as $i => $id) { + DB::table('labor_categories') + ->where('id', $id) + ->update(['sort_order' => $i + 1]); } }); } diff --git a/database/migrations/2026_09_08_110000_normalize_labor_category_sort_order.php b/database/migrations/2026_09_08_110000_normalize_labor_category_sort_order.php index 03b4b23..bab9511 100644 --- a/database/migrations/2026_09_08_110000_normalize_labor_category_sort_order.php +++ b/database/migrations/2026_09_08_110000_normalize_labor_category_sort_order.php @@ -19,7 +19,7 @@ return new class extends Migration foreach ($rows as $i => $id) { DB::table('labor_categories') ->where('id', $id) - ->update(['sort_order' => ($i + 1) * 10]); + ->update(['sort_order' => $i + 1]); } } }