Compare commits
5 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| e4db36e650 | |||
| ffa3f10b18 | |||
| 7acef66ee7 | |||
| 18f1217daa | |||
| ac44e82454 |
@@ -0,0 +1,49 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Administrator\Controllers;
|
||||
|
||||
use App\Domains\Administrator\Requests\StoreAdministratorRequest;
|
||||
use App\Domains\Administrator\Requests\UpdateAdministratorRequest;
|
||||
use App\Domains\Administrator\Resources\AdministratorResource;
|
||||
use App\Domains\Administrator\Services\AdministratorService;
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
class AdminAppAdministratorController extends Controller
|
||||
{
|
||||
public function __construct(private readonly AdministratorService $administratorService) {}
|
||||
|
||||
public function index(Request $request): AnonymousResourceCollection
|
||||
{
|
||||
return AdministratorResource::collection($this->administratorService->list(
|
||||
$request->user()->tenant()->firstOrFail(),
|
||||
$request->string('search')->trim()->toString() ?: null,
|
||||
));
|
||||
}
|
||||
|
||||
public function store(StoreAdministratorRequest $request): AdministratorResource
|
||||
{
|
||||
return AdministratorResource::make($this->administratorService->create(
|
||||
$request->user()->tenant()->firstOrFail(),
|
||||
$request->validated(),
|
||||
));
|
||||
}
|
||||
|
||||
public function update(UpdateAdministratorRequest $request, int $administrator): AdministratorResource
|
||||
{
|
||||
return AdministratorResource::make($this->administratorService->update(
|
||||
$request->user()->tenant()->firstOrFail(),
|
||||
$administrator,
|
||||
$request->validated(),
|
||||
));
|
||||
}
|
||||
|
||||
public function destroy(Request $request, int $administrator): Response
|
||||
{
|
||||
$this->administratorService->delete($request->user()->tenant()->firstOrFail(), $administrator, $request->user());
|
||||
|
||||
return response()->noContent();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Administrator\Requests;
|
||||
|
||||
use App\Domains\Authorization\Enums\RoleCode;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Validation\Rule;
|
||||
|
||||
class StoreAdministratorRequest extends FormRequest
|
||||
{
|
||||
public function authorize(): bool
|
||||
{
|
||||
return $this->user()?->rol_codigo === RoleCode::AdminApp->value;
|
||||
}
|
||||
|
||||
protected function prepareForValidation(): void
|
||||
{
|
||||
if (is_string($this->input('email'))) {
|
||||
$this->merge(['email' => mb_strtolower(trim($this->input('email')))]);
|
||||
}
|
||||
}
|
||||
|
||||
/** @return array<string, mixed> */
|
||||
public function rules(): array
|
||||
{
|
||||
|
||||
return [
|
||||
'nombre_apellido' => ['required', 'string', 'max:255'],
|
||||
'dni' => ['required', 'string', 'max:50'],
|
||||
'email' => [
|
||||
'required',
|
||||
'email',
|
||||
'max:255',
|
||||
Rule::unique('users', 'email')->whereNull('deleted_at'),
|
||||
],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Administrator\Requests;
|
||||
|
||||
use App\Domains\Authorization\Enums\RoleCode;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Validation\Rule;
|
||||
|
||||
class UpdateAdministratorRequest extends FormRequest
|
||||
{
|
||||
public function authorize(): bool
|
||||
{
|
||||
return $this->user()?->rol_codigo === RoleCode::AdminApp->value;
|
||||
}
|
||||
|
||||
protected function prepareForValidation(): void
|
||||
{
|
||||
if (is_string($this->input('email'))) {
|
||||
$this->merge(['email' => mb_strtolower(trim($this->input('email')))]);
|
||||
}
|
||||
}
|
||||
|
||||
/** @return array<string, mixed> */
|
||||
public function rules(): array
|
||||
{
|
||||
$administratorId = (int) $this->route('administrator');
|
||||
|
||||
return [
|
||||
'nombre_apellido' => ['required', 'string', 'max:255'],
|
||||
'dni' => ['required', 'string', 'max:50'],
|
||||
'email' => [
|
||||
'required',
|
||||
'email',
|
||||
'max:255',
|
||||
Rule::unique('users', 'email')
|
||||
->whereNull('deleted_at')
|
||||
->ignore($administratorId),
|
||||
],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Administrator\Resources;
|
||||
|
||||
use App\Domains\Auth\Models\User;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
/** @mixin User */
|
||||
class AdministratorResource extends JsonResource
|
||||
{
|
||||
/** @return array<string, mixed> */
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'nombre_apellido' => $this->nombre_apellido,
|
||||
'dni' => $this->dni,
|
||||
'email' => $this->email,
|
||||
'rol_codigo' => $this->rol_codigo,
|
||||
'role' => $this->whenLoaded('role', fn () => [
|
||||
'codigo' => $this->role?->codigo,
|
||||
'nombre' => $this->role?->nombre,
|
||||
]),
|
||||
];
|
||||
}
|
||||
}
|
||||
99
app/Domains/Administrator/Services/AdministratorService.php
Normal file
99
app/Domains/Administrator/Services/AdministratorService.php
Normal file
@@ -0,0 +1,99 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Administrator\Services;
|
||||
|
||||
use App\Domains\Auth\Models\ResetPasswordAttempt;
|
||||
use App\Domains\Auth\Models\User;
|
||||
use App\Domains\Auth\Services\ResetPasswordAttemptService;
|
||||
use App\Domains\Authorization\Enums\RoleCode;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\Collection;
|
||||
use Illuminate\Support\Arr;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
class AdministratorService
|
||||
{
|
||||
public function __construct(private readonly ResetPasswordAttemptService $resetPasswordAttemptService) {}
|
||||
|
||||
/** @return Collection<int, User> */
|
||||
public function list(Tenant $tenant, ?string $search = null): Collection
|
||||
{
|
||||
return $this->query($tenant)->with('role')
|
||||
->when($search, fn (Builder $query, string $search) => $query->where(function (Builder $query) use ($search): void {
|
||||
$query->where('nombre_apellido', 'like', "%{$search}%")
|
||||
->orWhere('dni', 'like', "%{$search}%")
|
||||
->orWhere('email', 'like', "%{$search}%");
|
||||
}))
|
||||
->orderBy('nombre_apellido')->get();
|
||||
}
|
||||
|
||||
/** @param array<string, mixed> $data */
|
||||
public function create(Tenant $tenant, array $data): User
|
||||
{
|
||||
return DB::transaction(function () use ($tenant, $data): User {
|
||||
$administrator = User::query()->create([
|
||||
...$this->attributes($data),
|
||||
'password' => Str::random(64),
|
||||
'rol_codigo' => RoleCode::AdminApp->value,
|
||||
'tenant_codigo' => $tenant->codigo,
|
||||
]);
|
||||
$this->resetPasswordAttemptService->createForAdminAppEmail(
|
||||
$administrator->email,
|
||||
ResetPasswordAttempt::REASON_ADMINISTRATOR_CREATED,
|
||||
);
|
||||
|
||||
return $administrator->load('role');
|
||||
});
|
||||
}
|
||||
|
||||
/** @param array<string, mixed> $data */
|
||||
public function update(Tenant $tenant, int $administratorId, array $data): User
|
||||
{
|
||||
return DB::transaction(function () use ($tenant, $administratorId, $data): User {
|
||||
$administrator = $this->query($tenant)->lockForUpdate()->findOrFail($administratorId);
|
||||
$administrator->update($this->attributes($data));
|
||||
|
||||
return $administrator->load('role');
|
||||
});
|
||||
}
|
||||
|
||||
public function delete(Tenant $tenant, int $administratorId, User $actor): void
|
||||
{
|
||||
DB::transaction(function () use ($tenant, $administratorId, $actor): void {
|
||||
// Serialize deletions for this tenant, including requests already authenticated
|
||||
// when another administrator removes their account.
|
||||
Tenant::query()->whereKey($tenant->getKey())->lockForUpdate()->firstOrFail();
|
||||
$administrator = $this->query($tenant)->lockForUpdate()->findOrFail($administratorId);
|
||||
if ($administrator->is($actor)) {
|
||||
throw ValidationException::withMessages(['administrator' => 'No podés eliminar tu propio usuario.']);
|
||||
}
|
||||
$activeAdministrators = $this->query($tenant)->lockForUpdate()->get();
|
||||
if ($activeAdministrators->count() <= 1) {
|
||||
throw ValidationException::withMessages(['administrator' => 'El tenant debe conservar al menos un administrador.']);
|
||||
}
|
||||
abort_unless($activeAdministrators->contains('id', $actor->id), 403);
|
||||
$administrator->tokens()->delete();
|
||||
$administrator->delete();
|
||||
});
|
||||
}
|
||||
|
||||
private function query(Tenant $tenant): Builder
|
||||
{
|
||||
return User::query()->where('tenant_codigo', $tenant->codigo)
|
||||
->where('rol_codigo', RoleCode::AdminApp->value);
|
||||
}
|
||||
|
||||
/** @param array<string, mixed> $data
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function attributes(array $data): array
|
||||
{
|
||||
return [
|
||||
...Arr::only($data, ['nombre_apellido', 'dni']),
|
||||
'email' => mb_strtolower(trim((string) $data['email'])),
|
||||
];
|
||||
}
|
||||
}
|
||||
63
app/Domains/Administrator/documentacion/README.md
Normal file
63
app/Domains/Administrator/documentacion/README.md
Normal file
@@ -0,0 +1,63 @@
|
||||
# Administradores de AdminApp
|
||||
|
||||
CRUD de usuarios con rol `adminapp`, limitado al tenant del usuario autenticado.
|
||||
Todos los administradores del tenant pueden gestionar esta sección.
|
||||
|
||||
## Endpoints
|
||||
|
||||
Base: `/api/v1/adminapp/tenant/administrators`.
|
||||
Requieren `auth:sanctum` y `adminapp.tenant`.
|
||||
|
||||
- `GET /`: listado ordenado por nombre; acepta `search` por nombre, DNI o email.
|
||||
- `POST /`: alta; responde `201` con `data`.
|
||||
- `PUT /{administrator}`: actualización de los tres campos; responde `200` con `data`.
|
||||
- `DELETE /{administrator}`: baja lógica; responde `204`.
|
||||
|
||||
Alta y actualización reciben:
|
||||
|
||||
```json
|
||||
{
|
||||
"nombre_apellido": "Ada Lovelace",
|
||||
"dni": "12345678",
|
||||
"email": "ada@example.test"
|
||||
}
|
||||
```
|
||||
|
||||
Nombre (hasta 255 caracteres), DNI (hasta 50) y email (hasta 255) son obligatorios.
|
||||
El email se normaliza a minúsculas antes de validar y debe ser único entre
|
||||
usuarios activos, sin importar su tenant o rol. Se permite reutilizar el email
|
||||
de un usuario eliminado. Rol y tenant no son editables desde esta API.
|
||||
|
||||
Las respuestas incluyen `id`, `nombre_apellido`, `dni`, `email`, `rol_codigo`
|
||||
y `role` (`codigo`, `nombre`). Nunca incluyen contraseña ni datos de escaneo.
|
||||
|
||||
## Alta y acceso
|
||||
|
||||
Se genera una contraseña aleatoria y un intento de establecimiento de contraseña
|
||||
con motivo `administrator_created`, reutilizando `createForAdminAppEmail`.
|
||||
El evento usa el canal `adminapp`; el listener existente envía el email después
|
||||
del commit mediante la cola `emails`. Requiere la configuración de correo,
|
||||
dominio AdminApp y worker existentes. No se envían contraseñas en texto plano.
|
||||
|
||||
## Eliminación y aislamiento
|
||||
|
||||
Las consultas de usuarios se limitan por tenant y rol `adminapp`. IDs ajenos,
|
||||
usuarios eliminados y usuarios de otros roles devuelven `404`.
|
||||
La validación de campos devuelve `422`; falta de autenticación, `401`, y rol
|
||||
no autorizado, `403`.
|
||||
|
||||
No se permite eliminar al propio usuario ni dejar al tenant sin administradores
|
||||
(`422`, error `administrator`). La eliminación bloquea la fila del tenant dentro
|
||||
de una transacción para serializar bajas concurrentes. También verifica que el
|
||||
actor siga activo, revoca tokens y aplica el borrado lógico existente en `users`.
|
||||
|
||||
No agrega tablas ni migraciones. No modifica el CRUD de escáneres ni el frontend.
|
||||
|
||||
## Verificación
|
||||
|
||||
`php artisan test tests/Feature/Administrator/AdministratorControllerTest.php`
|
||||
|
||||
Las pruebas cubren CRUD, normalización y unicidad del email, establecimiento de
|
||||
contraseña, restricciones de rol y tenant, baja lógica, tokens y protecciones de
|
||||
eliminación. El caso de petición autenticada antes de la baja del actor se simula;
|
||||
no es una prueba con conexiones concurrentes reales.
|
||||
10
app/Domains/Administrator/routes/api.php
Normal file
10
app/Domains/Administrator/routes/api.php
Normal file
@@ -0,0 +1,10 @@
|
||||
<?php
|
||||
|
||||
use App\Domains\Administrator\Controllers\AdminAppAdministratorController;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
|
||||
Route::prefix('v1/adminapp/tenant')
|
||||
->middleware(['auth:sanctum', 'adminapp.tenant'])
|
||||
->group(function (): void {
|
||||
Route::apiResource('administrators', AdminAppAdministratorController::class)->except('show');
|
||||
});
|
||||
@@ -17,6 +17,8 @@ class ResetPasswordAttempt extends Model
|
||||
|
||||
public const REASON_STAFF_CREATED = 'staff_created';
|
||||
|
||||
public const REASON_ADMINISTRATOR_CREATED = 'administrator_created';
|
||||
|
||||
public const STATUS_PENDING = 'pending';
|
||||
|
||||
public const STATUS_VALIDATED = 'validated';
|
||||
|
||||
@@ -32,13 +32,14 @@ class NotificationMailService
|
||||
$tenant = Tenant::query()->with('websiteType')->where('codigo', $tenantCode)->firstOrFail();
|
||||
$user = User::query()->findOrFail($userId);
|
||||
$brand = $tenant->websiteType ?? $tenant;
|
||||
$tenantUrl = 'https://'.$tenant->dominio.$tenant->base_path;
|
||||
|
||||
$this->mailService
|
||||
->forTenant($tenantCode)
|
||||
->send(
|
||||
$user->email,
|
||||
"Bienvenido a {$brand->nombre}",
|
||||
view('mail.notifications.welcome', compact('brand', 'user'))->render(),
|
||||
view('mail.notifications.welcome', compact('brand', 'user', 'tenantUrl'))->render(),
|
||||
$brand,
|
||||
);
|
||||
|
||||
@@ -99,12 +100,25 @@ class NotificationMailService
|
||||
: 'https://'.$recoveryDomain.$recoveryBasePath.'/recuperar-contrasena/codigo?'.http_build_query($recoveryQuery);
|
||||
$brand = $tenant->websiteType ?? $tenant;
|
||||
|
||||
[$subject, $template] = match ($attempt->reason) {
|
||||
ResetPasswordAttempt::REASON_STAFF_CREATED => [
|
||||
'Tu cuenta de escáner está lista', 'scanner-created',
|
||||
],
|
||||
ResetPasswordAttempt::REASON_ADMINISTRATOR_CREATED => [
|
||||
'Tu cuenta de administrador está lista', 'administrator-created',
|
||||
],
|
||||
ResetPasswordAttempt::REASON_ACCOUNT_LOCKED => [
|
||||
'Desbloqueá tu cuenta', 'account-locked',
|
||||
],
|
||||
default => ['Código para recuperar tu contraseña', 'password-reset'],
|
||||
};
|
||||
|
||||
$this->mailService
|
||||
->forTenant($tenantCode)
|
||||
->send(
|
||||
$attempt->user->email,
|
||||
"Código para recuperar tu contraseña - {$brand->nombre}",
|
||||
view('mail.notifications.password-reset', [
|
||||
"{$subject} - {$brand->nombre}",
|
||||
view("mail.notifications.{$template}", [
|
||||
'attempt' => $attempt,
|
||||
'recoveryUrl' => $recoveryUrl,
|
||||
'brand' => $brand,
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
namespace App\Domains\Ticket\Services;
|
||||
|
||||
use App\Domains\Auth\Models\User;
|
||||
use App\Domains\Authorization\Enums\RoleCode;
|
||||
use App\Domains\Ticket\Models\Ticket;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Pagination\LengthAwarePaginator;
|
||||
@@ -73,7 +74,7 @@ class ScannerTicketService
|
||||
->where('tenant_code', $scanner->tenant_codigo)
|
||||
->where('ticket', $ticketUuid);
|
||||
|
||||
if ($scanner->tenant()->firstOrFail()->requiresScannerCategoryValidation()) {
|
||||
if ($this->requiresCategoryValidation($scanner)) {
|
||||
$categoryIds = $this->scannerCategoryIds($scanner);
|
||||
|
||||
$query->where(function (Builder $query) use ($scanner, $categoryIds): void {
|
||||
@@ -158,7 +159,7 @@ class ScannerTicketService
|
||||
|
||||
private function scannerCanScan(User $scanner, Ticket $ticket): bool
|
||||
{
|
||||
if (! $scanner->tenant()->firstOrFail()->requiresScannerCategoryValidation()) {
|
||||
if (! $this->requiresCategoryValidation($scanner)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -169,4 +170,10 @@ class ScannerTicketService
|
||||
->where('categorias.id', $categoryId)
|
||||
->exists();
|
||||
}
|
||||
|
||||
private function requiresCategoryValidation(User $scanner): bool
|
||||
{
|
||||
return $scanner->rol_codigo !== RoleCode::AdminApp->value
|
||||
&& $scanner->tenant()->firstOrFail()->requiresScannerCategoryValidation();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
private const MENU_CODE = 'adminapp.staff';
|
||||
|
||||
public function up(): void
|
||||
{
|
||||
DB::table('menues')
|
||||
->where('code', self::MENU_CODE)
|
||||
->update([
|
||||
'label' => 'Usuarios',
|
||||
'updated_at' => now(),
|
||||
]);
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
DB::table('menues')
|
||||
->where('code', self::MENU_CODE)
|
||||
->update([
|
||||
'label' => 'Staff',
|
||||
'updated_at' => now(),
|
||||
]);
|
||||
}
|
||||
};
|
||||
@@ -74,7 +74,7 @@ class MenuSeeder extends Seeder
|
||||
],
|
||||
[
|
||||
'code' => 'adminapp.staff',
|
||||
'label' => 'Staff',
|
||||
'label' => 'Usuarios',
|
||||
'parent_menu_code' => 'main.adminapp',
|
||||
'route' => '/admin/staff',
|
||||
],
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
@include('mail.notifications.partials.password-action', [
|
||||
'title' => 'Desbloqueá tu cuenta',
|
||||
'description' => 'registramos varios intentos fallidos de inicio de sesión en tu cuenta. Por seguridad, bloqueamos el acceso temporalmente. Utilizá este código para cambiar tu contraseña y desbloquearla.',
|
||||
'buttonLabel' => 'Ingresar código ahora',
|
||||
'footer' => 'Si no fuiste vos, por favor desestimá y borrá este correo. Tu cuenta seguirá protegida.',
|
||||
])
|
||||
@@ -0,0 +1,6 @@
|
||||
@include('mail.notifications.partials.password-action', [
|
||||
'title' => 'Tu cuenta de administrador está lista',
|
||||
'description' => 'creamos tu cuenta de administrador en '.$brand->nombre.'. Creá tu contraseña con este código para ingresar al panel de administración.',
|
||||
'buttonLabel' => 'Crear mi contraseña',
|
||||
'footer' => 'Si no esperabas recibir una cuenta de administrador, podés ignorar este mensaje.',
|
||||
])
|
||||
@@ -0,0 +1,24 @@
|
||||
<h1 style="margin: 0 0 20px; color: {{ $brand->primary_color }};">
|
||||
{{ $title }}
|
||||
</h1>
|
||||
|
||||
<p>Hola {{ $attempt->user->nombre_apellido }}, {{ $description }}</p>
|
||||
|
||||
<p>Ingresá este código en {{ $brand->nombre }}:</p>
|
||||
|
||||
<div style="margin: 28px 0; padding: 20px; border: 2px solid {{ $brand->primary_color }}; border-radius: 8px; text-align: center;">
|
||||
<span style="color: {{ $brand->primary_color }}; font-size: 36px; font-weight: 700; letter-spacing: 12px;">
|
||||
{{ $attempt->codigo }}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
@if($recoveryUrl)
|
||||
<div style="text-align: center; margin-bottom: 28px;">
|
||||
<a href="{{ $recoveryUrl }}"
|
||||
style="display: inline-block; padding: 12px 24px; background-color: {{ $brand->primary_color }}; color: #ffffff; text-decoration: none; border-radius: 6px; font-weight: bold;">
|
||||
{{ $buttonLabel }}
|
||||
</a>
|
||||
</div>
|
||||
@endif
|
||||
|
||||
<p style="color: #64748b; font-size: 14px;">{{ $footer }}</p>
|
||||
@@ -1,45 +1,6 @@
|
||||
<h1 style="margin: 0 0 20px; color: {{ $brand->primary_color }};">
|
||||
Recuperá tu contraseña
|
||||
</h1>
|
||||
|
||||
@if($attempt->reason === \App\Domains\Auth\Models\ResetPasswordAttempt::REASON_STAFF_CREATED)
|
||||
<p>
|
||||
Hola {{ $attempt->user->nombre_apellido }}, creamos tu cuenta de scanner en {{ $brand->nombre }}. Utilizá este código para crear tu contraseña y comenzar a usarla.
|
||||
</p>
|
||||
@elseif($attempt->reason === \App\Domains\Auth\Models\ResetPasswordAttempt::REASON_ACCOUNT_LOCKED)
|
||||
<p>
|
||||
Hola {{ $attempt->user->nombre_apellido }}, registramos varios intentos fallidos de inicio de sesión en tu cuenta. Por seguridad, hemos bloqueado el acceso temporalmente. Puedes utilizar este código para cambiar tu contraseña y desbloquearla inmediatamente.
|
||||
</p>
|
||||
@else
|
||||
<p>
|
||||
Hola {{ $attempt->user->nombre_apellido }}, recibimos una solicitud para restablecer
|
||||
la contraseña de tu cuenta.
|
||||
</p>
|
||||
@endif
|
||||
|
||||
<p>Ingresá este código en {{ $brand->nombre }}:</p>
|
||||
|
||||
<div style="margin: 28px 0; padding: 20px; border: 2px solid {{ $brand->primary_color }}; border-radius: 8px; text-align: center;">
|
||||
<span style="color: {{ $brand->primary_color }}; font-size: 36px; font-weight: 700; letter-spacing: 12px;">
|
||||
{{ $attempt->codigo }}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
@if($recoveryUrl)
|
||||
<div style="text-align: center; margin-bottom: 28px;">
|
||||
<a href="{{ $recoveryUrl }}"
|
||||
style="display: inline-block; padding: 12px 24px; background-color: {{ $brand->primary_color }}; color: #ffffff; text-decoration: none; border-radius: 6px; font-weight: bold;">
|
||||
{{ $attempt->reason === \App\Domains\Auth\Models\ResetPasswordAttempt::REASON_STAFF_CREATED ? 'Crear mi contraseña' : 'Ingresar código ahora' }}
|
||||
</a>
|
||||
</div>
|
||||
@endif
|
||||
|
||||
<p style="color: #64748b; font-size: 14px;">
|
||||
@if($attempt->reason === \App\Domains\Auth\Models\ResetPasswordAttempt::REASON_ACCOUNT_LOCKED)
|
||||
Si no fuiste vos, por favor desestimá y borrá este correo. Tu cuenta seguirá protegida.
|
||||
@elseif($attempt->reason === \App\Domains\Auth\Models\ResetPasswordAttempt::REASON_STAFF_CREATED)
|
||||
Si no esperabas recibir una cuenta de scanner, podés ignorar este mensaje.
|
||||
@else
|
||||
Si no solicitaste recuperar tu contraseña, podés ignorar este mensaje.
|
||||
@endif
|
||||
</p>
|
||||
@include('mail.notifications.partials.password-action', [
|
||||
'title' => 'Recuperá tu contraseña',
|
||||
'description' => 'recibimos una solicitud para restablecer la contraseña de tu cuenta.',
|
||||
'buttonLabel' => 'Ingresar código ahora',
|
||||
'footer' => 'Si no solicitaste recuperar tu contraseña, podés ignorar este mensaje.',
|
||||
])
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
@include('mail.notifications.partials.password-action', [
|
||||
'title' => 'Tu cuenta de escáner está lista',
|
||||
'description' => 'creamos tu cuenta de escáner en '.$brand->nombre.'. Creá tu contraseña con este código para ingresar y comenzar a escanear entradas.',
|
||||
'buttonLabel' => 'Crear mi contraseña',
|
||||
'footer' => 'Si no esperabas recibir una cuenta de escáner, podés ignorar este mensaje.',
|
||||
])
|
||||
@@ -1,3 +1,8 @@
|
||||
<h1 style="margin: 0 0 20px;">¡Bienvenido a {{ $brand->nombre }}!</h1>
|
||||
<p>Hola {{ $user->nombre_apellido }}, tu cuenta fue creada correctamente.</p>
|
||||
<p>Ya podés ingresar y comenzar a comprar.</p>
|
||||
<div style="text-align: center; margin-bottom: 28px;">
|
||||
<a href="{{ $tenantUrl }}"
|
||||
style="display: inline-block; padding: 12px 24px; background-color: {{ $brand->primary_color }}; color: #ffffff; text-decoration: none; border-radius: 6px; font-weight: bold;">
|
||||
Encendé tu experiencia
|
||||
</a>
|
||||
</div>
|
||||
|
||||
@@ -16,5 +16,6 @@ require __DIR__.'/../app/Domains/Ticket/routes/api.php';
|
||||
require __DIR__.'/../app/Domains/Event/routes/api.php';
|
||||
require __DIR__.'/../app/Domains/Forms/routes/api.php';
|
||||
require __DIR__.'/../app/Domains/Staff/routes/api.php';
|
||||
require __DIR__.'/../app/Domains/Administrator/routes/api.php';
|
||||
require __DIR__.'/../app/Domains/FiestaFutbolInfantil/routes/api.php';
|
||||
require __DIR__.'/../app/Domains/Desfile/routes/api.php';
|
||||
|
||||
148
tests/Feature/Administrator/AdministratorControllerTest.php
Normal file
148
tests/Feature/Administrator/AdministratorControllerTest.php
Normal file
@@ -0,0 +1,148 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Administrator;
|
||||
|
||||
use App\Domains\Attachable\Enums\AttachmentType;
|
||||
use App\Domains\Attachable\Models\Attachment;
|
||||
use App\Domains\Auth\Models\ResetPasswordAttempt;
|
||||
use App\Domains\Auth\Models\User;
|
||||
use App\Domains\Authorization\Enums\RoleCode;
|
||||
use App\Domains\Notification\Events\PasswordResetRequested;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use App\Domains\Tenant\Models\WebsiteType;
|
||||
use Database\Seeders\AuthorizationSeeder;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\Event;
|
||||
use Laravel\Sanctum\Sanctum;
|
||||
use Tests\TestCase;
|
||||
|
||||
class AdministratorControllerTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private Tenant $tenant;
|
||||
|
||||
private User $admin;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
Event::fake([PasswordResetRequested::class]);
|
||||
$this->seed(AuthorizationSeeder::class);
|
||||
WebsiteType::query()->create(['codigo' => 'onticket', 'nombre' => 'OnTicket']);
|
||||
$headerLogo = $this->createAttachment('header.png');
|
||||
$footerLogo = $this->createAttachment('footer.png');
|
||||
$this->tenant = Tenant::query()->create([
|
||||
'codigo' => 'acme',
|
||||
'nombre' => 'Acme',
|
||||
'dominio' => 'acme.test',
|
||||
'website_type_code' => 'onticket',
|
||||
'primary_color' => '#111111',
|
||||
'secondary_color' => '#222222',
|
||||
'danger_color' => '#cc0000',
|
||||
'success_color' => '#008800',
|
||||
'header_bg_color' => '#ffffff',
|
||||
'footer_bg_color' => '#ffffff',
|
||||
'header_logo_id' => $headerLogo->id,
|
||||
'footer_logo_id' => $footerLogo->id,
|
||||
]);
|
||||
$this->admin = User::factory()->create([
|
||||
'rol_codigo' => RoleCode::AdminApp->value,
|
||||
'tenant_codigo' => $this->tenant->codigo,
|
||||
]);
|
||||
}
|
||||
|
||||
private const URL = '/api/v1/adminapp/tenant/administrators';
|
||||
|
||||
private function payload(): array
|
||||
{
|
||||
return ['nombre_apellido' => 'Ada Lovelace', 'dni' => '12345678', 'email' => 'ada@example.test'];
|
||||
}
|
||||
|
||||
public function test_crud_and_password_setup_and_token_revocation(): void
|
||||
{
|
||||
Sanctum::actingAs($this->admin);
|
||||
$response = $this->postJson(self::URL, [...$this->payload(), 'email' => ' ADA@example.test ', 'rol_codigo' => 'admin', 'tenant_codigo' => 'other'])
|
||||
->assertCreated()->assertJsonPath('data.email', 'ada@example.test')
|
||||
->assertJsonPath('data.rol_codigo', 'adminapp')->assertJsonMissingPath('data.password');
|
||||
$id = $response->json('data.id');
|
||||
$this->assertDatabaseHas('users', ['id' => $id, 'tenant_codigo' => $this->tenant->codigo, 'rol_codigo' => 'adminapp']);
|
||||
$this->assertDatabaseHas('reset_password_attempts', ['user_id' => $id, 'reason' => ResetPasswordAttempt::REASON_ADMINISTRATOR_CREATED, 'status' => ResetPasswordAttempt::STATUS_PENDING]);
|
||||
Event::assertDispatched(PasswordResetRequested::class, fn ($event) => $event->channel === PasswordResetRequested::CHANNEL_ADMINAPP && $event->tenantCode === $this->tenant->codigo);
|
||||
$this->getJson(self::URL.'?search=Ada')->assertOk()->assertJsonCount(1, 'data');
|
||||
$this->putJson(self::URL."/{$id}", [...$this->payload(), 'nombre_apellido' => 'Ada Byron', 'rol_codigo' => 'scanner'])
|
||||
->assertOk()->assertJsonPath('data.nombre_apellido', 'Ada Byron')->assertJsonPath('data.rol_codigo', 'adminapp');
|
||||
$token = User::findOrFail($id)->createToken('adminapp')->accessToken;
|
||||
$this->deleteJson(self::URL."/{$id}")->assertNoContent();
|
||||
$this->assertSoftDeleted('users', ['id' => $id]);
|
||||
$this->assertDatabaseMissing('personal_access_tokens', ['id' => $token->id]);
|
||||
$this->getJson(self::URL.'?search=Ada')->assertOk()->assertJsonCount(0, 'data');
|
||||
$this->postJson(self::URL, $this->payload())->assertCreated();
|
||||
}
|
||||
|
||||
public function test_validation_and_case_insensitive_active_email_uniqueness(): void
|
||||
{
|
||||
Sanctum::actingAs($this->admin);
|
||||
$this->postJson(self::URL, [])->assertUnprocessable()->assertJsonValidationErrors(['nombre_apellido', 'dni', 'email']);
|
||||
$this->postJson(self::URL, [...$this->payload(), 'email' => 'invalid'])->assertUnprocessable()->assertJsonValidationErrors('email');
|
||||
$this->postJson(self::URL, [...$this->payload(), 'email' => strtoupper($this->admin->email)])->assertUnprocessable()->assertJsonValidationErrors('email');
|
||||
$target = User::factory()->create(['rol_codigo' => 'adminapp', 'tenant_codigo' => $this->tenant->codigo]);
|
||||
$this->putJson(self::URL."/{$target->id}", [...$this->payload(), 'email' => strtoupper($this->admin->email)])->assertUnprocessable()->assertJsonValidationErrors('email');
|
||||
}
|
||||
|
||||
public function test_other_tenants_and_roles_are_excluded(): void
|
||||
{
|
||||
Sanctum::actingAs($this->admin);
|
||||
$otherTenant = $this->tenant->replicate();
|
||||
$otherTenant->codigo = 'other';
|
||||
$otherTenant->dominio = 'other.test';
|
||||
$otherTenant->save();
|
||||
$targets = [
|
||||
User::factory()->create(['rol_codigo' => 'adminapp', 'tenant_codigo' => $otherTenant->codigo]),
|
||||
User::factory()->create(['rol_codigo' => 'scanner', 'tenant_codigo' => $this->tenant->codigo]),
|
||||
User::factory()->create(['rol_codigo' => 'admin', 'tenant_codigo' => $this->tenant->codigo]),
|
||||
];
|
||||
$this->getJson(self::URL)->assertOk()->assertJsonCount(1, 'data')->assertJsonPath('data.0.id', $this->admin->id);
|
||||
foreach ($targets as $target) {
|
||||
$this->putJson(self::URL."/{$target->id}", $this->payload())->assertNotFound();
|
||||
$this->deleteJson(self::URL."/{$target->id}")->assertNotFound();
|
||||
$this->assertNotSoftDeleted($target);
|
||||
}
|
||||
}
|
||||
|
||||
public function test_cannot_delete_self_even_with_another_administrator(): void
|
||||
{
|
||||
Sanctum::actingAs($this->admin);
|
||||
$this->deleteJson(self::URL."/{$this->admin->id}")->assertUnprocessable()->assertJsonValidationErrors('administrator');
|
||||
User::factory()->create(['rol_codigo' => 'adminapp', 'tenant_codigo' => $this->tenant->codigo]);
|
||||
$this->deleteJson(self::URL."/{$this->admin->id}")->assertUnprocessable();
|
||||
$this->assertNotSoftDeleted($this->admin);
|
||||
}
|
||||
|
||||
public function test_in_flight_request_from_deleted_actor_cannot_remove_last_administrator(): void
|
||||
{
|
||||
$remaining = User::factory()->create(['rol_codigo' => 'adminapp', 'tenant_codigo' => $this->tenant->codigo]);
|
||||
$this->admin->delete();
|
||||
Sanctum::actingAs($this->admin);
|
||||
$this->deleteJson(self::URL."/{$remaining->id}")->assertUnprocessable()->assertJsonValidationErrors('administrator');
|
||||
$this->assertNotSoftDeleted($remaining);
|
||||
}
|
||||
|
||||
public function test_authentication_and_role_are_required_for_all_operations(): void
|
||||
{
|
||||
$this->getJson(self::URL)->assertUnauthorized();
|
||||
foreach (['user', 'scanner', 'admin'] as $role) {
|
||||
Sanctum::actingAs(User::factory()->create(['rol_codigo' => $role, 'tenant_codigo' => $this->tenant->codigo]));
|
||||
$this->getJson(self::URL)->assertForbidden();
|
||||
$this->postJson(self::URL, $this->payload())->assertForbidden();
|
||||
$this->putJson(self::URL."/{$this->admin->id}", $this->payload())->assertForbidden();
|
||||
$this->deleteJson(self::URL."/{$this->admin->id}")->assertForbidden();
|
||||
}
|
||||
}
|
||||
|
||||
private function createAttachment(string $filename): Attachment
|
||||
{
|
||||
return Attachment::query()->create(['path' => "test/{$filename}", 'filename' => $filename, 'type' => AttachmentType::Image, 'mime_type' => 'image/png']);
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ namespace Tests\Feature\Notification;
|
||||
|
||||
use App\Domains\Attachable\Enums\AttachmentType;
|
||||
use App\Domains\Attachable\Models\Attachment;
|
||||
use App\Domains\Auth\Models\ResetPasswordAttempt;
|
||||
use App\Domains\Auth\Models\User;
|
||||
use App\Domains\Catalog\Models\CatalogItem;
|
||||
use App\Domains\Integration\Models\Integration;
|
||||
@@ -133,15 +134,64 @@ class NotificationMailServiceTest extends TestCase
|
||||
);
|
||||
|
||||
Mail::assertSent(Mailable::class, function (Mailable $mail): bool {
|
||||
$mail->assertHasSubject('Tu cuenta de escáner está lista - Scanner Mail');
|
||||
$rendered = $mail->render();
|
||||
|
||||
return str_contains($rendered, 'https://scanner.mail.local/recuperar-contrasena/codigo')
|
||||
&& str_contains($rendered, 'Tu cuenta de escáner está lista')
|
||||
&& str_contains($rendered, 'comenzar a escanear entradas')
|
||||
&& ! str_contains($rendered, 'Recuperá tu contraseña')
|
||||
&& str_contains($rendered, 'email=ada%40example.com')
|
||||
&& str_contains($rendered, 'code=0123')
|
||||
&& str_contains($rendered, 'Crear mi');
|
||||
});
|
||||
}
|
||||
|
||||
public function test_administrator_creation_has_custom_copy_and_the_existing_code_and_link(): void
|
||||
{
|
||||
$websiteType = WebsiteType::query()->create([
|
||||
'codigo' => 'admin-mail', 'nombre' => 'Admin Mail',
|
||||
'dominio' => 'admin.mail.local', 'scanner_domain' => 'scanner.mail.local',
|
||||
]);
|
||||
$this->tenant->update(['website_type_code' => $websiteType->codigo]);
|
||||
$attempt = $this->user->resetPasswordAttempts()->create([
|
||||
'codigo' => '0456', 'reason' => ResetPasswordAttempt::REASON_ADMINISTRATOR_CREATED,
|
||||
]);
|
||||
app(NotificationMailService::class)->sendPasswordResetCode($attempt->id, $this->tenant->codigo, PasswordResetRequested::CHANNEL_ADMINAPP);
|
||||
Mail::assertSent(Mailable::class, function (Mailable $mail): bool {
|
||||
$mail->assertHasSubject('Tu cuenta de administrador está lista - Admin Mail');
|
||||
$html = $mail->render();
|
||||
|
||||
return str_contains($html, 'Tu cuenta de administrador está lista')
|
||||
&& str_contains($html, 'ingresar al panel de administración')
|
||||
&& str_contains($html, '0456')
|
||||
&& str_contains($html, 'Crear mi contraseña')
|
||||
&& str_contains($html, 'https://admin.mail.local/recuperar-contrasena/codigo?email=ada%40example.com')
|
||||
&& ! str_contains($html, 'scanner.mail.local')
|
||||
&& ! str_contains($html, 'administrator_created')
|
||||
&& ! str_contains($html, 'Recuperá tu contraseña');
|
||||
});
|
||||
}
|
||||
|
||||
public function test_locked_account_has_its_own_copy_and_the_shared_code_action(): void
|
||||
{
|
||||
$attempt = $this->user->resetPasswordAttempts()->create([
|
||||
'codigo' => '0789', 'reason' => ResetPasswordAttempt::REASON_ACCOUNT_LOCKED,
|
||||
]);
|
||||
app(NotificationMailService::class)->sendPasswordResetCode($attempt->id, $this->tenant->codigo);
|
||||
Mail::assertSent(Mailable::class, function (Mailable $mail): bool {
|
||||
$mail->assertHasSubject('Desbloqueá tu cuenta - Mail Tenant');
|
||||
$html = $mail->render();
|
||||
|
||||
return str_contains($html, 'Desbloqueá tu cuenta')
|
||||
&& str_contains($html, 'bloqueamos el acceso temporalmente')
|
||||
&& str_contains($html, '0789')
|
||||
&& str_contains($html, 'Ingresar código ahora')
|
||||
&& str_contains($html, 'https://mail.local/recuperar-contrasena/codigo')
|
||||
&& ! str_contains($html, 'account_locked');
|
||||
});
|
||||
}
|
||||
|
||||
public function test_it_sends_one_purchase_confirmation_with_generated_tickets_attached(): void
|
||||
{
|
||||
$this->useWebsiteTypeBranding();
|
||||
|
||||
@@ -52,7 +52,7 @@ class ScannerTicketControllerTest extends TestCase
|
||||
$this->getJson('/api/v1/scanner/tickets')->assertUnauthorized();
|
||||
|
||||
Sanctum::actingAs(User::factory()->create([
|
||||
'rol_codigo' => RoleCode::AdminApp->value,
|
||||
'rol_codigo' => RoleCode::User->value,
|
||||
'tenant_codigo' => $this->tenant->codigo,
|
||||
]));
|
||||
|
||||
@@ -300,6 +300,45 @@ class ScannerTicketControllerTest extends TestCase
|
||||
->assertNotFound();
|
||||
}
|
||||
|
||||
public function test_adminapp_can_read_and_scan_all_tenant_categories_without_assignments(): void
|
||||
{
|
||||
$this->tenant->update(['scanner_category_validation_enabled' => true]);
|
||||
$admin = User::factory()->create([
|
||||
'rol_codigo' => RoleCode::AdminApp->value,
|
||||
'tenant_codigo' => $this->tenant->codigo,
|
||||
]);
|
||||
$this->assertCount(0, $admin->scanCategories);
|
||||
$otherCategory = Category::query()->create([
|
||||
'tenant_code' => $this->tenant->codigo, 'nombre' => 'Comidas',
|
||||
]);
|
||||
Sanctum::actingAs($admin);
|
||||
foreach ([$this->category, $otherCategory] as $category) {
|
||||
$ticket = $this->createTicket((string) Str::uuid(), [], $category);
|
||||
$this->getJson("/api/v1/scanner/tickets/{$ticket->ticket}")->assertOk();
|
||||
$this->postJson("/api/v1/scanner/tickets/{$ticket->ticket}/scan")
|
||||
->assertOk()->assertJsonPath('data.scanner_user_id', $admin->id);
|
||||
$this->postJson("/api/v1/scanner/tickets/{$ticket->ticket}/scan")
|
||||
->assertUnprocessable()->assertJsonValidationErrors('ticket');
|
||||
}
|
||||
}
|
||||
|
||||
public function test_adminapp_cannot_read_or_scan_another_tenants_ticket(): void
|
||||
{
|
||||
$admin = User::factory()->create([
|
||||
'rol_codigo' => RoleCode::AdminApp->value,
|
||||
'tenant_codigo' => $this->tenant->codigo,
|
||||
]);
|
||||
$foreignTenant = $this->createTenant('foreign');
|
||||
$foreignCategory = Category::query()->create([
|
||||
'tenant_code' => $foreignTenant->codigo, 'nombre' => 'Externas',
|
||||
]);
|
||||
$ticket = $this->createTicket((string) Str::uuid(), [], $foreignCategory, $foreignTenant);
|
||||
Sanctum::actingAs($admin);
|
||||
$this->getJson("/api/v1/scanner/tickets/{$ticket->ticket}")->assertNotFound();
|
||||
$this->postJson("/api/v1/scanner/tickets/{$ticket->ticket}/scan")->assertNotFound();
|
||||
$this->assertNull($ticket->fresh()->used_at);
|
||||
}
|
||||
|
||||
/** @param array<string, mixed> $attributes */
|
||||
private function createTicket(
|
||||
string $uuid,
|
||||
|
||||
Reference in New Issue
Block a user