StudentRegistrationDraftService.php 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. <?php
  2. namespace App\Services;
  3. use App\Models\User;
  4. use Closure;
  5. use Illuminate\Support\Facades\Cache;
  6. use Illuminate\Support\Facades\Validator;
  7. use Illuminate\Support\Str;
  8. use Illuminate\Validation\ValidationException;
  9. class StudentRegistrationDraftService
  10. {
  11. private const CACHE_PREFIX = 'student-registration-draft:';
  12. private const LOCK_KEY = 'student-registration-drafts:lock';
  13. private const LOCK_SECONDS = 60;
  14. private const UNIQUE_FIELDS = [
  15. 'email',
  16. ];
  17. public function store(User $user, array $data): array
  18. {
  19. $unitId = $this->resolveUnitId($user);
  20. $requestedToken = $data['registration_draft_token'] ?? null;
  21. unset($data['registration_draft_token']);
  22. return Cache::lock(self::LOCK_KEY, self::LOCK_SECONDS)->block(5, function () use (
  23. $user,
  24. $unitId,
  25. $requestedToken,
  26. $data,
  27. ): array {
  28. $existingDraft = null;
  29. if ($requestedToken !== null) {
  30. $existingDraft = $this->findOwnedDraft($user, $requestedToken, $unitId);
  31. if ($existingDraft === null) {
  32. $this->invalidToken();
  33. }
  34. }
  35. $token = $requestedToken ?? (string) Str::uuid();
  36. $expiresAt = now()->addMinutes(config('students.registration_draft_ttl_minutes', 15));
  37. $oldReservations = $existingDraft['reservations'] ?? [];
  38. $newReservations = $this->reservationKeys($data);
  39. $acquiredReservations = [];
  40. $this->validateDatabaseUniques($data);
  41. try {
  42. foreach ($newReservations as $field => $key) {
  43. if (($oldReservations[$field] ?? null) === $key) {
  44. if (Cache::get($key) !== $token) {
  45. $this->invalidToken();
  46. }
  47. continue;
  48. }
  49. if (! Cache::add($key, $token, $expiresAt) && Cache::get($key) !== $token) {
  50. $this->uniqueReservationConflict($field);
  51. }
  52. $acquiredReservations[$field] = $key;
  53. }
  54. } catch (ValidationException $exception) {
  55. $this->releaseReservations($acquiredReservations, $token);
  56. throw $exception;
  57. }
  58. $removedReservations = array_diff($oldReservations, $newReservations);
  59. $this->releaseReservations($removedReservations, $token);
  60. foreach ($newReservations as $key) {
  61. Cache::put($key, $token, $expiresAt);
  62. }
  63. $draft = [
  64. 'user_id' => $user->id,
  65. 'unit_id' => $unitId,
  66. 'data' => $data,
  67. 'reservations' => $newReservations,
  68. 'expires_at' => $expiresAt->toIso8601String(),
  69. ];
  70. Cache::put($this->draftKey($token), $draft, $expiresAt);
  71. return [
  72. 'registration_draft_token' => $token,
  73. 'expires_at' => $draft['expires_at'],
  74. ];
  75. });
  76. }
  77. public function findOwnedDraft(User $user, string $token, ?int $unitId = null): ?array
  78. {
  79. $draft = Cache::get($this->draftKey($token));
  80. if (! is_array($draft)) {
  81. return null;
  82. }
  83. $unitId ??= $this->resolveUnitId($user);
  84. if ($draft['user_id'] !== $user->id || $draft['unit_id'] !== $unitId) {
  85. return null;
  86. }
  87. return $draft;
  88. }
  89. public function consume(User $user, string $token, Closure $callback): mixed
  90. {
  91. $unitId = $this->resolveUnitId($user);
  92. return Cache::lock(self::LOCK_KEY, self::LOCK_SECONDS)->block(5, function () use (
  93. $user,
  94. $token,
  95. $unitId,
  96. $callback,
  97. ): mixed {
  98. $draft = $this->findOwnedDraft($user, $token, $unitId);
  99. if ($draft === null || ! $this->ownsAllReservations($draft['reservations'], $token)) {
  100. $this->invalidToken();
  101. }
  102. $this->validateDatabaseUniques($draft['data']);
  103. $result = $callback($draft['data'], $unitId);
  104. $this->releaseReservations($draft['reservations'], $token);
  105. Cache::forget($this->draftKey($token));
  106. return $result;
  107. });
  108. }
  109. private function resolveUnitId(User $user): int
  110. {
  111. $activeUnitId = request()->input('active_unit_id');
  112. if ($activeUnitId) {
  113. $unit = $user->units()->where('units.id', $activeUnitId)->first();
  114. abort_if(! $unit, 403, 'Unidade não autorizada para este usuário.');
  115. return $unit->id;
  116. }
  117. $unit = $user->units()->first();
  118. abort_if(! $unit, 403, 'Usuário sem unidade associada.');
  119. return $unit->id;
  120. }
  121. private function reservationKeys(array $data): array
  122. {
  123. $keys = [];
  124. foreach (self::UNIQUE_FIELDS as $field) {
  125. $value = $data[$field] ?? null;
  126. if (! is_string($value) || $value === '') {
  127. continue;
  128. }
  129. $normalizedValue = Str::lower(trim($value));
  130. $keys[$field] = self::CACHE_PREFIX."reservation:{$field}:".hash('sha256', $normalizedValue);
  131. }
  132. return $keys;
  133. }
  134. private function ownsAllReservations(array $reservations, string $token): bool
  135. {
  136. foreach ($reservations as $key) {
  137. if (Cache::get($key) !== $token) {
  138. return false;
  139. }
  140. }
  141. return true;
  142. }
  143. private function releaseReservations(array $reservations, string $token): void
  144. {
  145. foreach ($reservations as $key) {
  146. if (Cache::get($key) === $token) {
  147. Cache::forget($key);
  148. }
  149. }
  150. }
  151. private function validateDatabaseUniques(array $data): void
  152. {
  153. Validator::make($data, [
  154. 'email' => 'sometimes|nullable|unique:students,email',
  155. ])->validate();
  156. }
  157. private function uniqueReservationConflict(string $field): never
  158. {
  159. throw ValidationException::withMessages([
  160. $field => __('validation.unique', [
  161. 'attribute' => __("validation.attributes.{$field}"),
  162. ]),
  163. ]);
  164. }
  165. private function invalidToken(): never
  166. {
  167. throw ValidationException::withMessages([
  168. 'registration_draft_token' => __('validation.registration_draft_invalid'),
  169. ]);
  170. }
  171. private function draftKey(string $token): string
  172. {
  173. return self::CACHE_PREFIX.$token;
  174. }
  175. }