format('Y'); $prefix = 'HD-'.$year.'-'; $this->lockReferenceSeries($prefix); /** @var list $existingReferences */ $existingReferences = Ticket::query() ->withoutGlobalScopes() ->withTrashed() ->where('reference', 'like', $prefix.'%') ->pluck('reference') ->filter(static fn (mixed $reference): bool => is_string($reference) && preg_match('/^'.preg_quote($prefix, '/').'\d+$/', $reference) === 1) ->values() ->all(); $highestSuffix = 0; foreach ($existingReferences as $existingReference) { $highestSuffix = max($highestSuffix, (int) substr($existingReference, strlen($prefix))); } return $prefix.str_pad((string) ($highestSuffix + 1), 5, '0', STR_PAD_LEFT); } /** * Lock the current ticket reference series for the active transaction. */ private function lockReferenceSeries(string $prefix): void { if (DB::connection()->getDriverName() !== 'pgsql') { return; } DB::select('select pg_advisory_xact_lock(hashtext(?))', [ 'helpdesk-ticket-reference:'.$prefix, ]); } }