Compare commits

..

8 Commits

61 changed files with 834 additions and 1205 deletions

View File

@@ -34,8 +34,3 @@ Bajo `/v1/adminapp/tenant/featured-groups`, con `auth:sanctum` y `adminapp.tenan
## Dependencias y reglas
Usa `Attachable` para imágenes/archivos, `Tenant` para aislamiento y `Ticket`/`Event` para vigencia y fechas. `Cart` y `Purchase` consumen sus precios, variantes e inventario. Los cambios de stock deben pasar por `CatalogInventoryService` para conservar reservas y disponibilidad.
## Menús deprecados
Los menús `adminapp.combos` y `adminapp.categories` están retirados; las
categorías del catálogo y sus datos comerciales no se eliminan.

View File

@@ -13,8 +13,9 @@ class PurchaseRefundSummaryService
$total = TicketRefund::query()
->whereHas(
'purchaseItem.purchase',
fn (Builder $query): Builder => $query->where('tenant_codigo', $tenant->codigo)
->when($eventId !== null, fn (Builder $purchase) => $purchase->where('event_id', $eventId))
fn (Builder $query): Builder => $query
->where('tenant_codigo', $tenant->codigo)
->when($eventId !== null, fn (Builder $query): Builder => $query->where('event_id', $eventId))
)
->sum('amount');

View File

@@ -13,7 +13,6 @@ use App\Domains\Commerce\Sale\Resources\AdminApp\SaleTicketResource;
use App\Domains\Commerce\Sale\Services\AdminAppSaleExcelService;
use App\Domains\Commerce\Sale\Services\AdminAppSalePdfService;
use App\Domains\Commerce\Sale\Services\AdminAppSaleService;
use App\Domains\Core\Auth\Services\EventScopeService;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
@@ -28,20 +27,15 @@ class SaleController extends Controller
protected AdminAppSaleExcelService $saleExcelService,
) {}
private function eventId(Request $request): ?int
{
return app(EventScopeService::class)->eventId($request->user());
}
public function index(AdminAppSaleIndexRequest $request): AnonymousResourceCollection
{
$tenant = $request->user()->tenant()->firstOrFail();
return SaleResource::collection(
$this->saleService->sales($tenant, $request->validated(), $this->eventId($request))
$this->saleService->sales($tenant, $request->validated(), $request->user()->event_id)
)->additional([
'confirmed_sales_total' => $this->saleService->confirmedSalesTotal($tenant, $this->eventId($request)),
'refunded_total' => $this->saleService->refundedTotal($tenant, $this->eventId($request)),
'confirmed_sales_total' => $this->saleService->confirmedSalesTotal($tenant, $request->user()->event_id),
'refunded_total' => $this->saleService->refundedTotal($tenant, $request->user()->event_id),
]);
}
@@ -49,7 +43,7 @@ class SaleController extends Controller
{
$tenant = $request->user()->tenant()->firstOrFail();
return new SaleDetailResource($this->saleService->detail($tenant, $sale, $this->eventId($request)));
return new SaleDetailResource($this->saleService->detail($tenant, $sale, $request->user()->event_id));
}
public function tickets(Request $request, int $sale): AnonymousResourceCollection
@@ -57,7 +51,7 @@ class SaleController extends Controller
$tenant = $request->user()->tenant()->firstOrFail();
return SaleTicketResource::collection(
$this->saleService->tickets($tenant, $sale, $this->eventId($request))
$this->saleService->tickets($tenant, $sale, $request->user()->event_id)
);
}
@@ -65,14 +59,14 @@ class SaleController extends Controller
{
$tenant = $request->user()->tenant()->firstOrFail();
return new SaleResource($this->saleService->confirm($tenant, $sale, $this->eventId($request)));
return new SaleResource($this->saleService->confirm($tenant, $sale, $request->user()->event_id));
}
public function cancel(Request $request, int $sale): SaleResource
{
$tenant = $request->user()->tenant()->firstOrFail();
return new SaleResource($this->saleService->cancel($tenant, $sale, $this->eventId($request)));
return new SaleResource($this->saleService->cancel($tenant, $sale, $request->user()->event_id));
}
public function modifications(
@@ -82,7 +76,7 @@ class SaleController extends Controller
$this->saleService->modifications(
$request->user()->tenant()->firstOrFail(),
$request->validated(),
$this->eventId($request),
$request->user()->event_id,
)
);
}
@@ -93,7 +87,7 @@ class SaleController extends Controller
return $this->salePdfService->downloadSales(
$tenant,
$this->saleService->salesForExport($tenant, $request->validated(), $this->eventId($request)),
$this->saleService->salesForExport($tenant, $request->validated(), $request->user()->event_id),
$request->validated('timezone'),
);
}
@@ -104,7 +98,7 @@ class SaleController extends Controller
return $this->salePdfService->downloadModifications(
$tenant,
$this->saleService->modificationsForExport($tenant, $request->validated(), $this->eventId($request)),
$this->saleService->modificationsForExport($tenant, $request->validated(), $request->user()->event_id),
$request->validated('timezone'),
);
}
@@ -115,7 +109,7 @@ class SaleController extends Controller
return $this->saleExcelService->downloadSales(
$tenant,
$this->saleService->salesForExport($tenant, $request->validated(), $this->eventId($request)),
$this->saleService->salesForExport($tenant, $request->validated(), $request->user()->event_id),
$request->validated('timezone'),
);
}
@@ -127,7 +121,7 @@ class SaleController extends Controller
return $this->saleExcelService->downloadModifications(
$tenant,
$this->saleService->modificationsForExport($tenant, $request->validated(), $this->eventId($request)),
$this->saleService->modificationsForExport($tenant, $request->validated(), $request->user()->event_id),
$request->validated('timezone'),
);
}

View File

@@ -23,9 +23,7 @@ class AdminAppSaleService
public function confirmedSalesTotal(Tenant $tenant, ?int $eventId = null): string
{
$total = Purchase::query()
->where('tenant_codigo', $tenant->codigo)
->when($eventId !== null, fn (Builder $query) => $query->where('event_id', $eventId))
$total = $this->purchasesQuery($tenant, $eventId)
->where('status', Purchase::STATUS_PAID)
->sum('total');
@@ -57,9 +55,7 @@ class AdminAppSaleService
public function detail(Tenant $tenant, int $saleId, ?int $eventId = null): Purchase
{
return Purchase::query()
->where('tenant_codigo', $tenant->codigo)
->when($eventId !== null, fn (Builder $query) => $query->where('event_id', $eventId))
return $this->purchasesQuery($tenant, $eventId)
->with('items')
->findOrFail($saleId);
}
@@ -139,9 +135,7 @@ class AdminAppSaleService
? $requestedDirection
: 'desc';
return Purchase::query()
->where('tenant_codigo', $tenant->codigo)
->when($eventId !== null, fn (Builder $query) => $query->where('event_id', $eventId))
return $this->purchasesQuery($tenant, $eventId)
->when($filters['q'] ?? null, function (Builder $query, string $search): void {
$term = trim($search);
@@ -184,9 +178,13 @@ class AdminAppSaleService
return ValueChange::query()
->where('tenant_code', $tenant->codigo)
->where('trackable_type', (new Purchase)->getMorphClass())
->when($eventId !== null, fn (Builder $query) => $query->whereHasMorph(
'trackable', [Purchase::class],
fn (Builder $sales) => $sales->where('event_id', $eventId)))
->when($eventId !== null, fn (Builder $query): Builder => $query->whereHasMorph(
'trackable',
[Purchase::class],
fn (Builder $sales): Builder => $sales
->where('tenant_codigo', $tenant->codigo)
->where('event_id', $eventId),
))
->when($filters['q'] ?? null, function (Builder $query, string $search): void {
$term = trim($search);
@@ -228,11 +226,17 @@ class AdminAppSaleService
}
protected function findForTenant(Tenant $tenant, int $saleId, ?int $eventId = null): Purchase
{
return $this->purchasesQuery($tenant, $eventId)
->findOrFail($saleId);
}
/** @return Builder<Purchase> */
protected function purchasesQuery(Tenant $tenant, ?int $eventId): Builder
{
return Purchase::query()
->where('tenant_codigo', $tenant->codigo)
->when($eventId !== null, fn (Builder $query) => $query->where('event_id', $eventId))
->findOrFail($saleId);
->when($eventId !== null, fn (Builder $query): Builder => $query->where('event_id', $eventId));
}
protected function saleForResponse(Purchase $sale): Purchase

View File

@@ -29,11 +29,8 @@ Consume compras de `Purchase`, datos del tenant y entradas de `Logging`. No es d
La consulta paginada y la colección de exportación deben aplicar los mismos filtros para evitar diferencias entre pantalla, PDF y Excel.
Cuando el usuario autenticado tiene `event_id`, el controlador lo pasa al servicio como alcance obligatorio para ventas, totales, historial y exportaciones. El alcance se combina con el tenant y no se obtiene de los filtros enviados por el cliente. Los administradores sin `event_id` conservan el alcance del tenant.
El detalle, los tickets de una venta, la confirmación y la cancelación buscan la compra dentro del mismo alcance. Una venta de otro evento o sin evento devuelve 404 para un administrador con `event_id`, antes de ejecutar cualquier acción en `CheckoutService`.
El historial comparte con ventas los filtros de búsqueda, ID, fecha de venta y estado. En el historial, el estado se evalúa sobre `ValueChange.new_value`: representa el resultado de esa modificación y no el estado actual de la venta.
## Alcance por evento
Las rutas usan `adminapp.tenant:event`. Para admins de evento, listados, totales,
detalles, tickets de compras, confirmación, cancelación, historial y exportaciones
se filtran por `user.event_id` además del tenant. Las compras pertenecen a un
único evento. Un admin de tenant conserva acceso a sus compras de todos los eventos.

View File

@@ -4,7 +4,7 @@ use App\Domains\Commerce\Sale\Controllers\AdminApp\SaleController;
use Illuminate\Support\Facades\Route;
Route::prefix('v1/adminapp/tenant')
->middleware(['auth:sanctum', 'adminapp.tenant:event'])
->middleware(['auth:sanctum', 'adminapp.tenant'])
->group(function (): void {
Route::get('sales', [SaleController::class, 'index']);
Route::get('sales/pdf', [SaleController::class, 'downloadPdf']);

View File

@@ -20,6 +20,7 @@ class AdminAppAdministratorController extends Controller
return AdministratorResource::collection($this->administratorService->list(
$request->user()->tenant()->firstOrFail(),
$request->string('search')->trim()->toString() ?: null,
$request->user()->event_id,
));
}
@@ -28,6 +29,7 @@ class AdminAppAdministratorController extends Controller
return AdministratorResource::make($this->administratorService->create(
$request->user()->tenant()->firstOrFail(),
$request->validated(),
$request->user()->event_id,
));
}
@@ -37,6 +39,7 @@ class AdminAppAdministratorController extends Controller
$request->user()->tenant()->firstOrFail(),
$administrator,
$request->validated(),
$request->user()->event_id,
));
}

View File

@@ -18,6 +18,7 @@ class AdministratorResource extends JsonResource
'dni' => $this->dni,
'email' => $this->email,
'rol_codigo' => $this->rol_codigo,
'event_id' => $this->event_id,
'role' => $this->whenLoaded('role', fn () => [
'codigo' => $this->role?->codigo,
'nombre' => $this->role?->nombre,

View File

@@ -19,9 +19,9 @@ class AdministratorService
public function __construct(private readonly ResetPasswordAttemptService $resetPasswordAttemptService) {}
/** @return Collection<int, User> */
public function list(Tenant $tenant, ?string $search = null): Collection
public function list(Tenant $tenant, ?string $search = null, ?int $eventId = null): Collection
{
return $this->query($tenant)->with('role')
return $this->query($tenant, $eventId)->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}%")
@@ -31,14 +31,15 @@ class AdministratorService
}
/** @param array<string, mixed> $data */
public function create(Tenant $tenant, array $data): User
public function create(Tenant $tenant, array $data, ?int $eventId = null): User
{
return DB::transaction(function () use ($tenant, $data): User {
return DB::transaction(function () use ($tenant, $data, $eventId): User {
$administrator = User::query()->create([
...$this->attributes($data),
'password' => Str::random(64),
'rol_codigo' => RoleCode::AdminApp->value,
'tenant_codigo' => $tenant->codigo,
'event_id' => $eventId,
]);
$this->resetPasswordAttemptService->createForAdminAppEmail(
$administrator->email,
@@ -50,10 +51,10 @@ class AdministratorService
}
/** @param array<string, mixed> $data */
public function update(Tenant $tenant, int $administratorId, array $data): User
public function update(Tenant $tenant, int $administratorId, array $data, ?int $eventId = null): User
{
return DB::transaction(function () use ($tenant, $administratorId, $data): User {
$administrator = $this->query($tenant)->lockForUpdate()->findOrFail($administratorId);
return DB::transaction(function () use ($tenant, $administratorId, $data, $eventId): User {
$administrator = $this->query($tenant, $eventId)->lockForUpdate()->findOrFail($administratorId);
$administrator->update($this->attributes($data));
return $administrator->load('role');
@@ -66,11 +67,11 @@ class AdministratorService
// 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);
$administrator = $this->query($tenant, $actor->event_id)->lockForUpdate()->findOrFail($administratorId);
if ($administrator->is($actor)) {
throw ValidationException::withMessages(['administrator' => 'No podés eliminar tu propio usuario.']);
}
$activeAdministrators = $this->query($tenant)->lockForUpdate()->get();
$activeAdministrators = $this->query($tenant, $actor->event_id)->lockForUpdate()->get();
if ($activeAdministrators->count() <= 1) {
throw ValidationException::withMessages(['administrator' => 'El tenant debe conservar al menos un administrador.']);
}
@@ -80,10 +81,11 @@ class AdministratorService
});
}
private function query(Tenant $tenant): Builder
private function query(Tenant $tenant, ?int $eventId = null): Builder
{
return User::query()->where('tenant_codigo', $tenant->codigo)
->where('rol_codigo', RoleCode::AdminApp->value);
->where('rol_codigo', RoleCode::AdminApp->value)
->when($eventId !== null, fn (Builder $query): Builder => $query->where('event_id', $eventId));
}
/** @param array<string, mixed> $data

View File

@@ -55,6 +55,8 @@ No agrega tablas ni migraciones. No modifica el CRUD de escáneres ni el fronten
## Verificación
Cuando el actor tiene `event_id`, los nuevos administradores heredan su evento y el listado, la búsqueda, la edición y la baja se limitan a ese evento dentro del tenant. La comprobación de administradores activos también usa ese alcance. El evento se toma del usuario autenticado, no del cuerpo de la solicitud; sin `event_id` se conserva el comportamiento por tenant.
`php artisan test tests/Feature/Administrator/AdministratorControllerTest.php`
Las pruebas cubren CRUD, normalización y unicidad del email, establecimiento de

View File

@@ -1,9 +0,0 @@
<?php
namespace App\Domains\Core\Auth\Enums;
enum AdminScope: string
{
case Tenant = 'tenant';
case Event = 'event';
}

View File

@@ -3,7 +3,6 @@
namespace App\Domains\Core\Auth\Models;
use App\Domains\Commerce\Catalog\Models\Category;
use App\Domains\Core\Auth\Enums\AdminScope;
use App\Domains\Core\Authorization\Enums\RoleCode;
use App\Domains\Core\Authorization\Models\Role;
use App\Domains\Core\Tenant\Models\Tenant;
@@ -22,7 +21,7 @@ use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
#[Fillable(['nombre_apellido', 'email', 'password', 'dni', 'telefono', 'google_id', 'rol_codigo', 'tenant_codigo', 'admin_scope', 'event_id'])]
#[Fillable(['nombre_apellido', 'email', 'password', 'dni', 'telefono', 'google_id', 'rol_codigo', 'tenant_codigo', 'event_id'])]
#[Hidden(['password', 'remember_token', 'active_email', 'active_google_id'])]
class User extends Authenticatable
{
@@ -31,7 +30,6 @@ class User extends Authenticatable
protected $attributes = [
'rol_codigo' => RoleCode::User->value,
'admin_scope' => AdminScope::Tenant->value,
];
protected static function newFactory(): UserFactory
@@ -95,13 +93,6 @@ class User extends Authenticatable
return $this->belongsTo(Event::class);
}
public function isTenantAdministrator(): bool
{
return $this->rol_codigo === RoleCode::AdminApp->value
&& $this->admin_scope === AdminScope::Tenant->value
&& $this->event_id === null;
}
/** @return BelongsToMany<Category, $this> */
public function scanCategories(): BelongsToMany
{

View File

@@ -20,11 +20,6 @@ class AdminAppMeResource extends JsonResource
return [
'user' => UserResource::make($this->resource),
'tenant' => TenantResource::make($this->tenant),
'event' => $this->whenLoaded('event', fn () => $this->event === null ? null : [
'id' => $this->event->id,
'title' => $this->event->title,
'tenant_code' => $this->event->tenant_code,
]),
];
}
}

View File

@@ -16,9 +16,6 @@ class ScannerMeResource extends JsonResource
return [
'user' => UserResource::make($this->resource),
'tenant' => TenantResource::make($this->tenant),
'event' => $this->whenLoaded('event', fn () => $this->event === null ? null : [
'id' => $this->event->id, 'title' => $this->event->title,
]),
];
}
}

View File

@@ -3,7 +3,6 @@
namespace App\Domains\Core\Auth\Resources;
use App\Domains\Core\Auth\Models\User;
use App\Domains\Core\Authorization\Enums\RoleCode;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
@@ -25,8 +24,7 @@ class UserResource extends JsonResource
'telefono' => $this->telefono,
'rol_codigo' => $this->rol_codigo,
'tenant_codigo' => $this->tenant_codigo,
'admin_scope' => $this->when($this->rol_codigo === RoleCode::AdminApp->value, $this->admin_scope),
'event_id' => $this->when(in_array($this->rol_codigo, [RoleCode::AdminApp->value, RoleCode::Scanner->value], true), $this->event_id),
'event_id' => $this->event_id,
'categories' => $this->whenLoaded('scanCategories', fn () => $this->scanCategories
->map(fn ($category) => [
'id' => $category->id,

View File

@@ -1,27 +0,0 @@
<?php
namespace App\Domains\Core\Auth\Services;
use App\Domains\Core\Auth\Enums\AdminScope;
use App\Domains\Core\Auth\Models\User;
use App\Domains\Core\Authorization\Enums\RoleCode;
class AdminAppAccessService
{
public function hasValidScope(User $user): bool
{
if ($user->rol_codigo !== RoleCode::AdminApp->value
|| ! $user->tenant_codigo
|| ! $user->tenant()->exists()) {
return false;
}
if ($user->isTenantAdministrator()) {
return true;
}
return $user->admin_scope === AdminScope::Event->value
&& $user->event_id !== null
&& $user->event()->where('tenant_code', $user->tenant_codigo)->exists();
}
}

View File

@@ -20,7 +20,6 @@ class AdminAppContextService
->firstOrFail();
$user->setRelation('tenant', $tenant);
$user->load('event');
return $user;
}

View File

@@ -1,24 +0,0 @@
<?php
namespace App\Domains\Core\Auth\Services;
use App\Domains\Core\Auth\Enums\AdminScope;
use App\Domains\Core\Auth\Models\User;
use Illuminate\Auth\Access\AuthorizationException;
class EventScopeService
{
public function eventId(User $user): ?int
{
if ($user->admin_scope === AdminScope::Event->value || $user->event_id !== null) {
if ($user->event_id === null
|| ! $user->event()->where('tenant_code', $user->tenant_codigo)->exists()) {
throw new AuthorizationException;
}
return $user->event_id;
}
return null;
}
}

View File

@@ -10,7 +10,6 @@ use App\Domains\Core\Authorization\Enums\PermissionCode;
use App\Domains\Core\Authorization\Enums\RoleCode;
use App\Shared\Notification\Events\PasswordResetRequested;
use Carbon\CarbonImmutable;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Log;
@@ -20,7 +19,6 @@ class PasswordLoginService
{
public function __construct(
private readonly ResetPasswordAttemptService $resetPasswordAttemptService,
private readonly AdminAppAccessService $adminAppAccessService,
) {}
/**
@@ -198,26 +196,6 @@ class PasswordLoginService
];
}
if ($requiredRole === RoleCode::AdminApp && ! $this->adminAppAccessService->hasValidScope($user)) {
$this->recordAttempt(
$user, $normalizedEmail, $attemptTenantCode,
LoginAttempt::OUTCOME_INVALID_CREDENTIALS, $ipAddress, $userAgent,
);
return ['outcome' => LoginAttempt::OUTCOME_INVALID_CREDENTIALS, 'user' => $user, 'locked_until' => null];
}
if ($requiredRole === RoleCode::Scanner) {
try {
app(EventScopeService::class)->eventId($user);
} catch (AuthorizationException) {
$this->recordAttempt($user, $normalizedEmail, $attemptTenantCode,
LoginAttempt::OUTCOME_INVALID_CREDENTIALS, $ipAddress, $userAgent);
return ['outcome' => LoginAttempt::OUTCOME_INVALID_CREDENTIALS, 'user' => $user, 'locked_until' => null];
}
}
$user->forceFill([
'failed_login_attempts' => 0,
'last_failed_login_at' => null,

View File

@@ -18,7 +18,6 @@ class ScannerContextService
->firstOrFail();
$user->setRelation('tenant', $tenant);
$user->load('event');
if ($tenant->requiresScannerCategoryValidation()) {
$categories = $user->scanCategories()

View File

@@ -17,6 +17,6 @@ Route::prefix('v1/adminapp')->group(function (): void {
Route::post('password/reset', ResetPasswordController::class)
->defaults('reset_role', 'adminapp')
->middleware('throttle:5,1');
Route::middleware(['auth:sanctum', 'adminapp.tenant:context'])
Route::middleware(['auth:sanctum', 'adminapp.tenant'])
->get('me', AdminAppMeController::class);
});

View File

@@ -2,7 +2,6 @@
namespace App\Domains\Core\Staff\Controllers;
use App\Domains\Core\Auth\Services\EventScopeService;
use App\Domains\Core\Staff\Requests\StoreStaffRequest;
use App\Domains\Core\Staff\Requests\UpdateStaffRequest;
use App\Domains\Core\Staff\Resources\StaffResource;
@@ -22,17 +21,12 @@ class AdminAppStaffController extends Controller
private readonly ScannerTicketService $scannerTicketService,
) {}
private function eventId(Request $request): ?int
{
return app(EventScopeService::class)->eventId($request->user());
}
public function index(Request $request): AnonymousResourceCollection
{
return StaffResource::collection($this->staffService->list(
$request->user()->tenant()->firstOrFail(),
$request->string('search')->trim()->toString() ?: null,
$this->eventId($request),
$request->user()->event_id,
));
}
@@ -41,7 +35,7 @@ class AdminAppStaffController extends Controller
return StaffResource::make($this->staffService->create(
$request->user()->tenant()->firstOrFail(),
$request->validated(),
$this->eventId($request),
$request->user()->event_id,
));
}
@@ -51,13 +45,13 @@ class AdminAppStaffController extends Controller
$request->user()->tenant()->firstOrFail(),
$staff,
$request->validated(),
$this->eventId($request),
$request->user()->event_id,
));
}
public function destroy(Request $request, int $staff): Response
{
$this->staffService->delete($request->user()->tenant()->firstOrFail(), $staff, $this->eventId($request));
$this->staffService->delete($request->user()->tenant()->firstOrFail(), $staff, $request->user()->event_id);
return response()->noContent();
}
@@ -69,7 +63,7 @@ class AdminAppStaffController extends Controller
$scanner = $this->staffService->find(
$request->user()->tenant()->firstOrFail(),
$staff,
$this->eventId($request),
$request->user()->event_id,
);
return ScanAttemptResource::collection(

View File

@@ -14,11 +14,11 @@ class StaffResource extends JsonResource
{
return [
'id' => $this->id,
'event_id' => $this->event_id,
'nombre_apellido' => $this->nombre_apellido,
'dni' => $this->dni,
'email' => $this->email,
'rol_codigo' => $this->rol_codigo,
'event_id' => $this->event_id,
'role' => $this->whenLoaded('role', fn () => [
'codigo' => $this->role?->codigo,
'nombre' => $this->role?->nombre,

View File

@@ -8,7 +8,6 @@ use App\Domains\Core\Auth\Models\User;
use App\Domains\Core\Auth\Services\ResetPasswordAttemptService;
use App\Domains\Core\Authorization\Enums\RoleCode;
use App\Domains\Core\Tenant\Models\Tenant;
use App\Domains\Ticketing\Event\Models\Event;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Arr;
@@ -39,7 +38,7 @@ class StaffService
}
/** @return Collection<int, Category> */
private function assignableCategories(Tenant $tenant, ?int $eventId = null): Collection
private function assignableCategories(Tenant $tenant): Collection
{
return Category::query()
->whereNull('categoria_id')
@@ -48,8 +47,6 @@ class StaffService
->orWhereHas('catalogItems', fn (Builder $items) => $items
->where('tenant_code', $tenant->codigo));
})
->when($eventId !== null, fn (Builder $query) => $query->whereHas(
'catalogItems', fn (Builder $items) => $items->where('tenant_code', $tenant->codigo)->where('event_id', $eventId)))
->orderBy('nombre')
->get();
}
@@ -57,11 +54,8 @@ class StaffService
/** @param array<string, mixed> $data */
public function create(Tenant $tenant, array $data, ?int $eventId = null): User
{
$eventId ??= $tenant->active_event_id;
Event::query()
->where('tenant_code', $tenant->codigo)->findOrFail($eventId);
$categoryIds = $this->categoryIdsFor($tenant, $data);
$this->assertCategoriesBelongToTenant($tenant, $categoryIds, $eventId);
$this->assertCategoriesBelongToTenant($tenant, $categoryIds);
return DB::transaction(function () use ($tenant, $data, $categoryIds, $eventId): User {
$staff = User::query()->create([
@@ -71,7 +65,6 @@ class StaffService
'rol_codigo' => RoleCode::Scanner->value,
'tenant_codigo' => $tenant->codigo,
'event_id' => $eventId,
'admin_scope' => $eventId === null ? 'tenant' : 'event',
]);
$staff->scanCategories()->sync($categoryIds);
$this->resetPasswordAttemptService->createForScannerEmail(
@@ -88,7 +81,7 @@ class StaffService
{
$staff = $this->find($tenant, $staffId, $eventId);
$categoryIds = $this->categoryIdsFor($tenant, $data);
$this->assertCategoriesBelongToTenant($tenant, $categoryIds, $eventId);
$this->assertCategoriesBelongToTenant($tenant, $categoryIds);
return DB::transaction(function () use ($staff, $data, $categoryIds): User {
$attributes = Arr::only($data, ['nombre_apellido', 'dni', 'email']);
@@ -120,14 +113,14 @@ class StaffService
return User::query()
->where('tenant_codigo', $tenant->codigo)
->where('rol_codigo', RoleCode::Scanner->value)
->when($eventId !== null, fn (Builder $query) => $query->where('event_id', $eventId));
->when($eventId !== null, fn (Builder $query): Builder => $query->where('event_id', $eventId));
}
/**
* @param array<string, mixed> $data
* @return array<int, int>
*/
private function categoryIdsFor(Tenant $tenant, array $data, ?int $eventId = null): array
private function categoryIdsFor(Tenant $tenant, array $data): array
{
if (! $tenant->requiresScannerCategoryValidation()) {
return [];
@@ -137,9 +130,9 @@ class StaffService
}
/** @param array<int, int> $categoryIds */
private function assertCategoriesBelongToTenant(Tenant $tenant, array $categoryIds, ?int $eventId = null): void
private function assertCategoriesBelongToTenant(Tenant $tenant, array $categoryIds): void
{
$validIds = $this->assignableCategories($tenant, $eventId)
$validIds = $this->assignableCategories($tenant)
->whereIn('id', $categoryIds)
->pluck('id');

View File

@@ -19,12 +19,4 @@ Recurso REST `/v1/adminapp/tenant/staff`, excepto detalle individual, protegido
Usa `Auth/User` como entidad de personal, `Authorization` para su rol, `Catalog/Category` para asignaciones y `Tenant` para aislamiento. Toda búsqueda, edición o borrado debe comprobar que el usuario pertenece al tenant autenticado.
## Alcance por evento
Los endpoints de Staff y su formulario aceptan `adminapp.tenant:event`. Un admin
de evento lista, edita, elimina y consulta el historial solo de scanners de su
evento. El backend asigna el evento al crear un scanner y no acepta cambios de
asignación desde el formulario. Las categorías autorizables se limitan a las
usadas por productos del evento. Los scanners aplican además su evento en
lectura de tickets, escaneo e historial. Los intentos registran `event_id` para
conservar el aislamiento aunque cambie la asignación del scanner.
Si el administrador autenticado tiene `event_id`, el alta de scanners hereda ese valor y las búsquedas, ediciones, bajas y consultas de intentos de escaneo se limitan a personal del mismo evento. El cliente no puede elegir ni cambiar el evento. Sin `event_id`, se mantiene el alcance por tenant.

View File

@@ -4,7 +4,7 @@ use App\Domains\Core\Staff\Controllers\AdminAppStaffController;
use Illuminate\Support\Facades\Route;
Route::prefix('v1/adminapp/tenant')
->middleware(['auth:sanctum', 'adminapp.tenant:event'])
->middleware(['auth:sanctum', 'adminapp.tenant'])
->group(function (): void {
Route::get('staff/{staff}/scan-attempts', [AdminAppStaffController::class, 'scanAttempts']);
Route::apiResource('staff', AdminAppStaffController::class)->except('show');

View File

@@ -2,7 +2,6 @@
namespace App\Domains\Ticketing\Event\Controllers\AdminApp;
use App\Domains\Core\Auth\Services\EventScopeService;
use App\Domains\Ticketing\Event\Models\EventDate;
use App\Domains\Ticketing\Event\Requests\RescheduleEventDateRequest;
use App\Domains\Ticketing\Event\Requests\StoreEventDateRequest;
@@ -20,8 +19,7 @@ class EventController extends Controller
public function show(Request $request): EventResource
{
return EventResource::make(
$this->eventService->forTenant($request->user()->tenant()->firstOrFail(),
app(EventScopeService::class)->eventId($request->user()))
$this->eventService->forTenant($request->user()->tenant()->firstOrFail())
);
}
@@ -30,8 +28,7 @@ class EventController extends Controller
return EventResource::make(
$this->eventService->updateForTenant(
$request->user()->tenant()->firstOrFail(),
$request->validated(),
app(EventScopeService::class)->eventId($request->user())
$request->validated()
)
);
}
@@ -42,7 +39,6 @@ class EventController extends Controller
$this->eventService->createDateForTenant(
$request->user()->tenant()->firstOrFail(),
$request->validated(),
app(EventScopeService::class)->eventId($request->user()),
)
);
}

View File

@@ -15,27 +15,14 @@ use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
#[Fillable(['client_id', 'tenant_code', 'slug', 'event_category_id', 'title', 'subtitle', 'description', 'location', 'exact_location', 'date_text', 'published_at', 'attachment_id', 'allow_ticket_refund', 'allow_ticket_total_refund', 'allow_ticket_partial_refund', 'ticket_partial_refund_percentage'])]
#[Fillable(['client_id', 'tenant_code', 'slug', 'event_category_id', 'title', 'subtitle', 'description', 'location', 'exact_location', 'date_text', 'published_at', 'attachment_id'])]
class Event extends Model
{
use HasFactory;
protected function casts(): array
{
return ['allow_ticket_refund' => 'boolean', 'allow_ticket_total_refund' => 'boolean',
'allow_ticket_partial_refund' => 'boolean', 'ticket_partial_refund_percentage' => 'decimal:2', 'client_id' => 'integer', 'published_at' => 'datetime', 'exact_location' => 'array'];
}
public function allow_refund(): bool
{
return (bool) $this->allow_ticket_refund
&& ((bool) $this->allow_ticket_total_refund || $this->allow_partial_refund());
}
public function allow_partial_refund(): bool
{
return (bool) $this->allow_ticket_refund && (bool) $this->allow_ticket_partial_refund
&& (float) $this->ticket_partial_refund_percentage > 0;
return ['client_id' => 'integer', 'published_at' => 'datetime', 'exact_location' => 'array'];
}
/** @return BelongsTo<Tenant, $this> */

View File

@@ -26,10 +26,10 @@ class EventResource extends JsonResource
'date_text' => $this->date_text,
'published_at' => $this->published_at?->toIso8601String(),
'attachment_id' => $this->attachment_id,
'allow_ticket_refund' => $this->allow_ticket_refund,
'allow_ticket_total_refund' => $this->allow_ticket_total_refund,
'allow_ticket_partial_refund' => $this->allow_ticket_partial_refund,
'ticket_partial_refund_percentage' => $this->ticket_partial_refund_percentage,
'allow_ticket_refund' => $this->tenant->allow_ticket_refund,
'allow_ticket_total_refund' => $this->tenant->allow_ticket_total_refund,
'allow_ticket_partial_refund' => $this->tenant->allow_ticket_partial_refund,
'ticket_partial_refund_percentage' => $this->tenant->ticket_partial_refund_percentage,
'dates' => EventDateResource::collection(
app(EventDateGroupingService::class)->group($this->dates)
),

View File

@@ -2,19 +2,18 @@
namespace App\Domains\Ticketing\Event\Services;
use App\Domains\Core\Auth\Models\User;
use App\Domains\Commerce\Cart\Services\InvalidateEventDateCartsService;
use App\Domains\Commerce\Catalog\Models\Variant;
use App\Domains\Commerce\Catalog\Services\StockReservationService;
use App\Domains\Commerce\Catalog\Services\VariantReplacementService;
use App\Domains\Core\Auth\Models\User;
use App\Domains\Core\Auth\Services\EventScopeService;
use App\Domains\Core\Tenant\Models\Tenant;
use App\Domains\Ticketing\Event\Enums\EventDateChangeType;
use App\Domains\Ticketing\Event\Events\EventDateRescheduled;
use App\Domains\Ticketing\Event\Events\EventDateSuspended;
use App\Domains\Ticketing\Event\Models\Event;
use App\Domains\Ticketing\Event\Models\EventDate;
use App\Domains\Ticketing\Event\Models\EventDateChange;
use App\Domains\Ticketing\Event\Models\Event;
use App\Domains\Core\Tenant\Models\Tenant;
use App\Domains\Ticketing\Ticket\Models\Ticket;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
@@ -35,22 +34,22 @@ class EventService
private readonly InvalidateEventDateCartsService $invalidateEventDateCarts,
) {}
public function forTenant(Tenant $tenant, ?int $eventId = null): Event
public function forTenant(Tenant $tenant): Event
{
return $this->resolveEvent($tenant, $eventId)->load(['dates.validityTime', 'socialMedia']);
return $tenant->activeEvent->load(['dates.validityTime', 'socialMedia']);
}
/** @param array<string, mixed> $data */
public function updateForTenant(Tenant $tenant, array $data, ?int $eventId = null): Event
public function updateForTenant(Tenant $tenant, array $data): Event
{
return DB::transaction(function () use ($tenant, $data, $eventId): Event {
$event = $this->resolveEvent($tenant, $eventId);
return DB::transaction(function () use ($tenant, $data): Event {
$event = $tenant->activeEvent;
$event->update([
'title' => $data['title'],
'location' => $data['location'],
...array_intersect_key($data, ['attachment_id' => true, 'exact_location' => true]),
]);
$event->update([
$tenant->update([
...array_intersect_key($data, array_flip([
'allow_ticket_refund',
'allow_ticket_total_refund',
@@ -70,10 +69,10 @@ class EventService
}
/** @param array{date: string, start_time: string, end_time: string} $data */
public function createDateForTenant(Tenant $tenant, array $data, ?int $eventId = null): EventDate
public function createDateForTenant(Tenant $tenant, array $data): EventDate
{
return DB::transaction(function () use ($tenant, $data, $eventId): EventDate {
$event = $this->resolveEvent($tenant, $eventId);
return DB::transaction(function () use ($tenant, $data): EventDate {
$event = $tenant->activeEvent;
$attributes = $this->dateAttributes($data);
if ($event->dates()->where($attributes)->exists()) {
@@ -94,7 +93,7 @@ class EventService
?User $createdBy = null,
): EventDate {
return DB::transaction(function () use ($tenant, $eventDate, $data, $createdBy): EventDate {
$source = $this->lockedDateForTenant($tenant, $eventDate, $createdBy);
$source = $this->lockedDateForTenant($tenant, $eventDate);
if ($source->suspended_at !== null) {
throw ValidationException::withMessages([
@@ -173,7 +172,7 @@ class EventService
?User $createdBy = null,
): EventDate {
return DB::transaction(function () use ($tenant, $eventDate, $createdBy): EventDate {
$date = $this->lockedDateForTenant($tenant, $eventDate, $createdBy);
$date = $this->lockedDateForTenant($tenant, $eventDate);
if ($date->rescheduled_to_event_date_id !== null) {
throw ValidationException::withMessages([
@@ -217,18 +216,10 @@ class EventService
});
}
private function resolveEvent(Tenant $tenant, ?int $eventId): Event
{
return Event::query()->where('tenant_code', $tenant->codigo)
->findOrFail($eventId ?? $tenant->active_event_id);
}
private function lockedDateForTenant(Tenant $tenant, EventDate $eventDate, ?User $actor = null): EventDate
private function lockedDateForTenant(Tenant $tenant, EventDate $eventDate): EventDate
{
return $tenant->eventDates()
->whereKey($eventDate->getKey())
->when($actor !== null && ! $actor->isTenantAdministrator(),
fn ($query) => $query->where('event_id', app(EventScopeService::class)->eventId($actor)))
->lockForUpdate()
->firstOrFail();
}

View File

@@ -37,10 +37,10 @@ se guardan en el evento. Sin evento activo se conservan las redes propias del te
## API
Los endpoints de AdminApp usan `auth:sanctum` y `adminapp.tenant:event`:
Los endpoints de AdminApp usan `auth:sanctum` y `adminapp.tenant`:
- `GET/PUT /v1/adminapp/tenant/event`: acceso al evento asociado al usuario con scope de evento;
para admins de tenant se conserva el evento activo.
- `GET/PUT /v1/adminapp/tenant/event`: acceso al evento seleccionado para el
storefront de evento único.
- `POST /v1/adminapp/tenant/event-dates`: crea una fecha para ese evento.
- `POST /v1/adminapp/tenant/event-dates/{eventDate}/reschedule` y
`POST /v1/adminapp/tenant/event-dates/{eventDate}/suspend`: cambios de fecha.
@@ -53,8 +53,3 @@ una lista de eventos ni existe todavía una pantalla para gestionarlos.
Las fechas se vinculan con variantes de `Catalog`, que a su vez pueden generar
tickets. Los avisos por suspensión y reprogramación se construyen dinámicamente
después de excluir los cambios que el usuario ya vio tres veces.
La configuración de devoluciones se persiste en `events`, se entrega en
`EventResource` y se aplica al evento de cada ticket. La migración inicial copia
los valores anteriores del tenant a sus eventos. Las fechas se autorizan por
tenant y por evento antes de cualquier suspensión o reprogramación.

View File

@@ -4,7 +4,7 @@ use App\Domains\Ticketing\Event\Controllers\AdminApp\EventController;
use Illuminate\Support\Facades\Route;
Route::prefix('v1/adminapp/tenant')
->middleware(['auth:sanctum', 'adminapp.tenant:event'])
->middleware(['auth:sanctum', 'adminapp.tenant'])
->group(function (): void {
Route::get('event', [EventController::class, 'show']);
Route::put('event', [EventController::class, 'update']);

View File

@@ -29,7 +29,7 @@ class TicketController extends Controller
$tenant = $request->user()->tenant()->firstOrFail();
return new AdminAppTicketCollection(
$this->ticketService->search($tenant, $request->validated())
$this->ticketService->search($tenant, $request->validated(), $request->user()->event_id)
);
}
@@ -37,7 +37,7 @@ class TicketController extends Controller
{
$tenant = $request->user()->tenant()->firstOrFail();
return new AdminAppTicketResource($this->ticketService->cancel($tenant, $ticket));
return new AdminAppTicketResource($this->ticketService->cancel($tenant, $ticket, $request->user()->event_id));
}
public function calculateRefund(Request $request, int $ticket): AdminAppTicketRefundCalculationResource
@@ -45,7 +45,7 @@ class TicketController extends Controller
$tenant = $request->user()->tenant()->firstOrFail();
return new AdminAppTicketRefundCalculationResource(
$this->ticketService->calculateRefund($tenant, $ticket)
$this->ticketService->calculateRefund($tenant, $ticket, $request->user()->event_id)
);
}
@@ -69,7 +69,7 @@ class TicketController extends Controller
return $this->ticketPdfService->download(
$tenant,
$this->ticketService->ticketsForExport($tenant, $request->validated()),
$this->ticketService->ticketsForExport($tenant, $request->validated(), $request->user()->event_id),
$request->validated('timezone'),
);
}
@@ -80,7 +80,7 @@ class TicketController extends Controller
return $this->ticketExcelService->download(
$tenant,
$this->ticketService->ticketsForExport($tenant, $request->validated()),
$this->ticketService->ticketsForExport($tenant, $request->validated(), $request->user()->event_id),
$request->validated('timezone'),
);
}

View File

@@ -11,7 +11,6 @@ use Illuminate\Database\Eloquent\Relations\BelongsTo;
#[Fillable([
'tenant_code',
'event_id',
'scanner_user_id',
'ticket_id',
'data',
@@ -44,7 +43,6 @@ class ScanAttempt extends Model
{
return [
'scanner_user_id' => 'integer',
'event_id' => 'integer',
'ticket_id' => 'integer',
'result' => ScanAttemptResult::class,
'created_at' => 'datetime',

View File

@@ -148,9 +148,7 @@ class Ticket extends Model
public function allow_refund(): bool
{
return $this->event_id === null
? ($this->tenant?->allow_refund() ?? false)
: ($this->event?->allow_refund() ?? false);
return $this->tenant?->allow_refund() ?? false;
}
public function allowRefund(): bool

View File

@@ -32,7 +32,7 @@ class ScanAttemptResource extends JsonResource
ScanAttemptResult::Processing => 'Error',
ScanAttemptResult::Accepted => 'Verificado',
ScanAttemptResult::InvalidQr => 'QR no pertenece al evento',
ScanAttemptResult::TicketNotFound => 'QR no pertenece al evento',
ScanAttemptResult::TicketNotFound => 'Error',
ScanAttemptResult::CategoryForbidden => 'Error',
ScanAttemptResult::AlreadyScanned => 'Usado',
ScanAttemptResult::Expired => 'Vencido',

View File

@@ -9,7 +9,6 @@ use App\Domains\Commerce\Purchase\Models\PurchaseItem;
use App\Domains\Commerce\Purchase\Services\PurchaseRefundSummaryService;
use App\Domains\Core\Auth\Models\User;
use App\Domains\Core\Tenant\Models\Tenant;
use App\Domains\Ticketing\Event\Models\Event;
use App\Domains\Ticketing\Ticket\Models\Ticket;
use App\Domains\Ticketing\Ticket\Models\TicketRefund;
use Illuminate\Database\Eloquent\Builder;
@@ -24,7 +23,6 @@ class AdminAppTicketService
...TicketValidityResolver::RELATIONS,
...TicketPresentationResolver::RELATIONS,
'tenant',
'event',
'user',
'scannerUser',
'sourceCatalogItem.category',
@@ -43,9 +41,9 @@ class AdminAppTicketService
/**
* @param array{q?: string|null, category?: string|null, product?: string|null, type?: string|null, date?: string|null, size?: string|null, status?: string|null, page?: int, per_page?: int, sort_by?: string|null, sort_direction?: string|null} $filters
*/
public function search(Tenant $tenant, array $filters = []): AdminAppTicketResult
public function search(Tenant $tenant, array $filters = [], ?int $eventId = null): AdminAppTicketResult
{
$query = $this->baseQuery($tenant, $filters);
$query = $this->baseQuery($tenant, $filters, $eventId);
$countQuery = clone $query;
$databaseSorted = $this->applyDatabaseSort($query, $tenant, $filters);
@@ -79,7 +77,7 @@ class AdminAppTicketService
tickets: $tickets,
scannedTickets: $scannedTickets,
totalTickets: $totalTickets,
refundedTotal: $this->refundSummaryService->totalForTenant($tenant),
refundedTotal: $this->refundSummaryService->totalForTenant($tenant, $eventId),
);
}
@@ -87,9 +85,9 @@ class AdminAppTicketService
* @param array{q?: string|null, category?: string|null, product?: string|null, type?: string|null, date?: string|null, size?: string|null, status?: string|null, sort_by?: string|null, sort_direction?: string|null} $filters
* @return Collection<int, Ticket>
*/
public function ticketsForExport(Tenant $tenant, array $filters = []): Collection
public function ticketsForExport(Tenant $tenant, array $filters = [], ?int $eventId = null): Collection
{
$query = $this->baseQuery($tenant, $filters);
$query = $this->baseQuery($tenant, $filters, $eventId);
$databaseSorted = $this->applyDatabaseSort($query, $tenant, $filters);
$tickets = $query
->with(self::RELATIONS)
@@ -99,11 +97,10 @@ class AdminAppTicketService
return $databaseSorted ? $tickets : $this->sortTickets($tickets, $tenant, $filters);
}
public function cancel(Tenant $tenant, int $ticketId): Ticket
public function cancel(Tenant $tenant, int $ticketId, ?int $eventId = null): Ticket
{
return DB::transaction(function () use ($tenant, $ticketId): Ticket {
$ticket = Ticket::query()
->where('tenant_code', $tenant->codigo)
return DB::transaction(function () use ($tenant, $ticketId, $eventId): Ticket {
$ticket = $this->ticketsQuery($tenant, $eventId)
->lockForUpdate()
->findOrFail($ticketId);
@@ -126,10 +123,9 @@ class AdminAppTicketService
* partial: string|null,
* }
*/
public function calculateRefund(Tenant $tenant, int $ticketId): array
public function calculateRefund(Tenant $tenant, int $ticketId, ?int $eventId = null): array
{
$ticket = Ticket::query()
->where('tenant_code', $tenant->codigo)
$ticket = $this->ticketsQuery($tenant, $eventId)
->findOrFail($ticketId);
if (! $ticket->can_refund()) {
@@ -147,20 +143,19 @@ class AdminAppTicketService
]);
}
$configuration = $ticket->event_id === null ? $tenant : $ticket->event;
$unitPrice = (float) $purchaseItem->precio_unitario;
$itemTotal = (float) $purchaseItem->total;
$itemRefundedAmount = $this->refundedAmountForPurchaseItem($purchaseItem);
$remainingItemAmount = max(0.0, round($itemTotal - $itemRefundedAmount, 2));
$total = null;
if ($configuration->allow_refund() && $configuration->allow_ticket_total_refund && $unitPrice <= $remainingItemAmount) {
if ($tenant->allow_refund() && $tenant->allow_ticket_total_refund && $unitPrice <= $remainingItemAmount) {
$total = number_format($unitPrice, 2, '.', '');
}
$partial = null;
if ($configuration->allow_refund() && $configuration->allow_partial_refund()) {
$partialAmount = $this->refundAmount($purchaseItem, $configuration, 'partial');
if ($tenant->allow_refund() && $tenant->allow_partial_refund()) {
$partialAmount = $this->refundAmount($purchaseItem, $tenant, 'partial');
if ($partialAmount <= $remainingItemAmount) {
$partial = number_format($partialAmount, 2, '.', '');
}
@@ -179,13 +174,11 @@ class AdminAppTicketService
?User $createdBy = null,
): Ticket {
return DB::transaction(function () use ($tenant, $ticketId, $refundType, $createdBy): Ticket {
$ticket = Ticket::query()
->where('tenant_code', $tenant->codigo)
$ticket = $this->ticketsQuery($tenant, $createdBy?->event_id)
->lockForUpdate()
->findOrFail($ticketId);
$configuration = $ticket->event_id === null ? $tenant : $ticket->event;
$this->ensureRefundIsAllowed($configuration, $refundType);
$this->ensureRefundIsAllowed($tenant, $refundType);
if (! $ticket->can_refund()) {
if ($ticket->status !== Ticket::STATUS_ACTIVE) {
@@ -209,7 +202,7 @@ class AdminAppTicketService
]);
}
$refundAmount = $this->refundAmount($purchaseItem, $configuration, $refundType);
$refundAmount = $this->refundAmount($purchaseItem, $tenant, $refundType);
$refundedAmount = round(
$this->refundedAmountForPurchaseItem($purchaseItem) + $refundAmount,
2,
@@ -290,7 +283,7 @@ class AdminAppTicketService
->sum('amount'), 2);
}
private function ensureRefundIsAllowed(Tenant|Event $tenant, string $refundType): void
private function ensureRefundIsAllowed(Tenant $tenant, string $refundType): void
{
$isAllowed = match ($refundType) {
TicketRefund::TYPE_PARTIAL => $tenant->allow_refund() && $tenant->allow_partial_refund(),
@@ -304,7 +297,7 @@ class AdminAppTicketService
}
}
private function refundAmount(PurchaseItem $purchaseItem, Tenant|Event $tenant, string $refundType): float
private function refundAmount(PurchaseItem $purchaseItem, Tenant $tenant, string $refundType): float
{
$ticketAmount = (float) $purchaseItem->precio_unitario;
@@ -318,12 +311,11 @@ class AdminAppTicketService
* @param array{q?: string|null, category?: string|null, product?: string|null, type?: string|null, date?: string|null, size?: string|null, status?: string|null, page?: int, per_page?: int} $filters
* @return Builder<Ticket>
*/
private function baseQuery(Tenant $tenant, array $filters): Builder
private function baseQuery(Tenant $tenant, array $filters, ?int $eventId = null): Builder
{
$search = trim((string) ($filters['q'] ?? ''));
$query = Ticket::query()
->where('tenant_code', $tenant->codigo)
$query = $this->ticketsQuery($tenant, $eventId)
->when($search !== '', function (Builder $query) use ($search): void {
$this->applySearchFilter($query, $search);
})
@@ -363,6 +355,14 @@ class AdminAppTicketService
return $query;
}
/** @return Builder<Ticket> */
private function ticketsQuery(Tenant $tenant, ?int $eventId): Builder
{
return Ticket::query()
->where('tenant_code', $tenant->codigo)
->when($eventId !== null, fn (Builder $query): Builder => $query->where('tickets.event_id', $eventId));
}
/** @param Builder<Ticket> $query */
private function applySearchFilter(Builder $query, string $search): void
{

View File

@@ -3,7 +3,6 @@
namespace App\Domains\Ticketing\Ticket\Services;
use App\Domains\Core\Auth\Models\User;
use App\Domains\Core\Auth\Services\EventScopeService;
use App\Domains\Ticketing\Ticket\Enums\ScanAttemptResult;
use App\Domains\Ticketing\Ticket\Models\ScanAttempt;
use App\Domains\Ticketing\Ticket\Models\Ticket;
@@ -28,7 +27,6 @@ class ScannerTicketService
->with('ticket.sourceCatalogItem.category')
->where('tenant_code', $scanner->tenant_codigo)
->where('scanner_user_id', $scanner->getKey())
->when($this->eventId($scanner) !== null, fn (Builder $query) => $query->where('event_id', $this->eventId($scanner)))
->when($search !== '', function (Builder $query) use ($search): void {
$attemptedAtDate = $this->parseSearchDate($search);
@@ -62,7 +60,6 @@ class ScannerTicketService
->with('ticket.sourceCatalogItem.category')
->where('tenant_code', $scanner->tenant_codigo)
->where('scanner_user_id', $scanner->getKey())
->when($this->eventId($scanner) !== null, fn (Builder $query) => $query->where('event_id', $this->eventId($scanner)))
->when($search !== '', function (Builder $query) use ($search): void {
$attemptedAtDate = $this->parseSearchDate($search);
$attemptedAtDayMonth = $this->parseSearchDayMonth($search);
@@ -109,7 +106,6 @@ class ScannerTicketService
->with('ticket')
->where('tenant_code', $scanner->tenant_codigo)
->where('scanner_user_id', $scanner->getKey())
->when($this->eventId($scanner) !== null, fn (Builder $query) => $query->where('event_id', $this->eventId($scanner)))
->findOrFail($scanAttemptId);
$scanAttempt->ticket?->loadMissing($this->relations());
@@ -117,11 +113,6 @@ class ScannerTicketService
return $scanAttempt;
}
private function eventId(User $scanner): ?int
{
return app(EventScopeService::class)->eventId($scanner);
}
private function parseSearchDate(string $search): ?string
{
if (preg_match('/^(\d{4})-(\d{2})-(\d{2})$/', $search, $matches) === 1) {
@@ -163,8 +154,7 @@ class ScannerTicketService
{
$query = $this->baseQuery()
->where('tenant_code', $scanner->tenant_codigo)
->where('ticket', $ticketUuid)
->when($this->eventId($scanner) !== null, fn (Builder $query) => $query->where('event_id', $this->eventId($scanner)));
->where('ticket', $ticketUuid);
if ($this->requiresCategoryValidation($scanner)) {
$categoryIds = $this->scannerCategoryIds($scanner);
@@ -188,7 +178,6 @@ class ScannerTicketService
$scanAttempt = ScanAttempt::query()->create([
'tenant_code' => $scanner->tenant_codigo,
'scanner_user_id' => $scanner->getKey(),
'event_id' => $this->eventId($scanner),
'data' => $this->serializeScannedData($scannedData),
'result' => ScanAttemptResult::Processing,
]);
@@ -211,7 +200,6 @@ class ScannerTicketService
$ticket = $this->baseQuery()
->where('tenant_code', $scanner->tenant_codigo)
->where('ticket', $scannedData)
->when($this->eventId($scanner) !== null, fn (Builder $query) => $query->where('event_id', $this->eventId($scanner)))
->lockForUpdate()
->firstOrFail();
$ticketId = (int) $ticket->getKey();

View File

@@ -89,6 +89,10 @@ Bajo `/v1/adminapp/tenant`, protegido por `auth:sanctum`, `adminapp.tenant` y el
`TicketPdfService` genera la descarga y `TicketResource`/`ValidityTimeResource` definen las respuestas.
Si el administrador autenticado tiene `event_id`, las consultas de Tickets y sus exportaciones se limitan a `tickets.event_id` dentro del tenant. Los contadores usan el mismo alcance y el total reembolsado se limita a las compras del evento. Sin `event_id`, se conserva el alcance por tenant.
La cancelación, el cálculo de reembolso y el reembolso buscan el ticket dentro de ese alcance antes de validar o ejecutar la operación. Un ticket de otro evento o sin evento devuelve 404 para un administrador con evento asignado. El alcance se obtiene del usuario autenticado, no de los parámetros del cliente.
## Dependencias y reglas
Depende de `Purchase`, `Catalog`, `Tenant` y `Auth`. La generación debe ser idempotente ante reintentos del evento. `TicketNotAvailableException` y `TicketGenerationException` separan indisponibilidad de errores de generación.

View File

@@ -2,7 +2,6 @@
namespace App\Http\Middleware;
use App\Domains\Core\Auth\Services\AdminAppAccessService;
use App\Domains\Core\Authorization\Enums\RoleCode;
use Closure;
use Illuminate\Auth\Access\AuthorizationException;
@@ -11,12 +10,10 @@ use Symfony\Component\HttpFoundation\Response;
class EnsureAdminAppTenant
{
public function __construct(private readonly AdminAppAccessService $accessService) {}
/**
* Ensure the authenticated user is an AdminApp user bound to a tenant.
*/
public function handle(Request $request, Closure $next, string $access = 'tenant'): Response
public function handle(Request $request, Closure $next): Response
{
$user = $request->user();
@@ -24,9 +21,6 @@ class EnsureAdminAppTenant
! $user
|| $user->rol_codigo !== RoleCode::AdminApp->value
|| ! $user->tenant_codigo
|| ! $this->accessService->hasValidScope($user)
// Only routes implementing event authorization may accept event administrators.
|| (! in_array($access, ['context', 'event'], true) && ! $user->isTenantAdministrator())
) {
throw new AuthorizationException;
}

View File

@@ -2,7 +2,6 @@
namespace App\Http\Middleware;
use App\Domains\Core\Auth\Services\EventScopeService;
use App\Domains\Core\Authorization\Enums\PermissionCode;
use App\Domains\Core\Authorization\Enums\RoleCode;
use Closure;
@@ -28,8 +27,6 @@ class EnsureScannerTenant
throw new AuthorizationException;
}
app(EventScopeService::class)->eventId($user);
return $next($request);
}
}

View File

@@ -2,10 +2,9 @@
namespace App\Shared\Forms\Controllers\AdminApp;
use App\Domains\Core\Auth\Services\EventScopeService;
use App\Http\Controllers\Controller;
use App\Shared\Forms\Resources\EventFormResource;
use App\Shared\Forms\Services\EventFormService;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class EventFormController extends Controller
@@ -16,8 +15,7 @@ class EventFormController extends Controller
{
return EventFormResource::make(
$this->eventFormService->get(
$request->user('sanctum')->tenant()->firstOrFail(),
app(EventScopeService::class)->eventId($request->user())
$request->user('sanctum')->tenant()->firstOrFail()
)
);
}

View File

@@ -2,10 +2,9 @@
namespace App\Shared\Forms\Controllers\AdminApp;
use App\Domains\Core\Auth\Services\EventScopeService;
use App\Http\Controllers\Controller;
use App\Shared\Forms\Resources\StaffFormResource;
use App\Shared\Forms\Services\StaffFormService;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class StaffFormController extends Controller
@@ -16,8 +15,7 @@ class StaffFormController extends Controller
{
return StaffFormResource::make(
$this->staffFormService->get(
$request->user('sanctum')->tenant()->firstOrFail(),
app(EventScopeService::class)->eventId($request->user())
$request->user('sanctum')->tenant()->firstOrFail()
)
);
}

View File

@@ -4,17 +4,14 @@ namespace App\Shared\Forms\Services;
use App\Domains\Core\Tenant\Models\SocialMedia;
use App\Domains\Core\Tenant\Models\Tenant;
use App\Domains\Ticketing\Event\Models\Event;
use Illuminate\Database\Eloquent\Collection;
class EventFormService
{
/** @return array{social_media: Collection<int, SocialMedia>} */
public function get(Tenant $tenant, ?int $eventId = null): array
public function get(Tenant $tenant): array
{
$event = $eventId === null ? $tenant->activeEvent
: Event::query()
->where('tenant_code', $tenant->codigo)->findOrFail($eventId);
$event = $tenant->activeEvent;
$urls = $event?->socialMedia()
->pluck('event_social_media.url', 'social_media.code') ?? collect();

View File

@@ -10,7 +10,7 @@ use Illuminate\Database\Eloquent\Collection;
class StaffFormService
{
/** @return array{categories: Collection<int, Category>} */
public function get(Tenant $tenant, ?int $eventId = null): array
public function get(Tenant $tenant): array
{
return [
'categories' => Category::query()
@@ -20,8 +20,6 @@ class StaffFormService
->orWhereHas('catalogItems', fn (Builder $items) => $items
->where('tenant_code', $tenant->codigo));
})
->when($eventId !== null, fn (Builder $query) => $query->whereHas(
'catalogItems', fn (Builder $items) => $items->where('tenant_code', $tenant->codigo)->where('event_id', $eventId)))
->orderBy('nombre')
->get(),
];

View File

@@ -12,33 +12,33 @@ use App\Shared\Forms\Controllers\AdminApp\TicketFormController;
use Illuminate\Support\Facades\Route;
Route::prefix('v1/adminapp/forms')
->middleware(['auth:sanctum', 'adminapp.tenant:event'])
->middleware(['auth:sanctum', 'adminapp.tenant'])
->group(function (): void {
Route::get('event', EventFormController::class);
Route::get(
'desfile/entry-reservation',
DesfileEntryReservationFormController::class
)->middleware('adminapp.tenant')->middleware('tenant.menu:adminapp.desfile.reservas')
)->middleware('tenant.menu:adminapp.desfile.reservas')
->name('adminapp.forms.desfile.entry-reservation');
Route::get('sale', SaleFormController::class);
Route::get('staff', StaffFormController::class);
Route::get('tickets-filter', TicketFilterFormController::class)->middleware('adminapp.tenant')
Route::get('tickets-filter', TicketFilterFormController::class)
->middleware('tenant.menu:adminapp.tickets')
->name('adminapp.forms.tickets-filter');
Route::get(
'fiesta-futbol-infantil/ticket',
TicketFormController::class
)->middleware('adminapp.tenant');
);
Route::get(
'fiesta-futbol-infantil/entry',
EntryFormController::class
)->middleware('adminapp.tenant');
);
Route::get(
'fiesta-futbol-infantil/merchandise',
MerchandiseFormController::class
)->middleware('adminapp.tenant');
);
Route::get(
'fiesta-futbol-infantil/food',
FoodFormController::class
)->middleware('adminapp.tenant');
);
});

View File

@@ -1,44 +0,0 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;
return new class extends Migration
{
public function up(): void
{
DB::transaction(function (): void {
DB::table('tenants')
->join('events', 'events.id', '=', 'tenants.active_event_id')
->whereColumn('events.tenant_code', 'tenants.codigo')
->select('tenants.codigo', 'tenants.active_event_id')
->get()
->each(function (object $tenant): void {
DB::table('users')
->whereIn('rol_codigo', ['adminapp', 'scanner'])
->where('tenant_codigo', $tenant->codigo)
->where('admin_scope', 'tenant')
->whereNull('event_id')
->whereNull('deleted_at')
->update([
'admin_scope' => 'event',
'event_id' => $tenant->active_event_id,
'updated_at' => now(),
]);
});
// Missing or mismatched active events must not leave legacy staff with tenant-wide access.
DB::table('users')
->whereIn('rol_codigo', ['adminapp', 'scanner'])
->where('admin_scope', 'tenant')
->whereNull('event_id')
->whereNull('deleted_at')
->update(['admin_scope' => 'event', 'updated_at' => now()]);
});
}
public function down(): void
{
// Do not broaden permissions or overwrite subsequent assignments on rollback.
}
};

View File

@@ -1,38 +0,0 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::table('events', function (Blueprint $table): void {
$table->boolean('allow_ticket_refund')->default(false);
$table->boolean('allow_ticket_total_refund')->default(false);
$table->boolean('allow_ticket_partial_refund')->default(false);
$table->decimal('ticket_partial_refund_percentage', 5, 2)->default(0);
});
DB::table('tenants')->select([
'codigo', 'allow_ticket_refund', 'allow_ticket_total_refund',
'allow_ticket_partial_refund', 'ticket_partial_refund_percentage',
])->get()->each(function (object $tenant): void {
DB::table('events')->where('tenant_code', $tenant->codigo)->update([
'allow_ticket_refund' => $tenant->allow_ticket_refund,
'allow_ticket_total_refund' => $tenant->allow_ticket_total_refund,
'allow_ticket_partial_refund' => $tenant->allow_ticket_partial_refund,
'ticket_partial_refund_percentage' => $tenant->ticket_partial_refund_percentage ?? 0,
]);
});
}
public function down(): void
{
Schema::table('events', fn (Blueprint $table) => $table->dropColumn([
'allow_ticket_refund', 'allow_ticket_total_refund',
'allow_ticket_partial_refund', 'ticket_partial_refund_percentage',
]));
}
};

View File

@@ -1,22 +0,0 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;
return new class extends Migration
{
public function up(): void
{
DB::transaction(function (): void {
$codes = ['adminapp.combos', 'adminapp.categories'];
DB::table('roles_menues')->whereIn('menu_codigo', $codes)->delete();
DB::table('tenants_menues')->whereIn('menu_code', $codes)->delete();
DB::table('menues')->whereIn('code', $codes)->delete();
});
}
public function down(): void
{
// Deprecated menus must not be restored by rollback.
}
};

View File

@@ -1,28 +0,0 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::table('scan_attempts', function (Blueprint $table): void {
$table->foreignId('event_id')->nullable()->constrained('events')->nullOnDelete();
$table->index(['scanner_user_id', 'event_id']);
});
DB::table('scan_attempts')->update([
'event_id' => DB::raw('(SELECT tickets.event_id FROM tickets WHERE tickets.id = scan_attempts.ticket_id)'),
]);
}
public function down(): void
{
Schema::table('scan_attempts', function (Blueprint $table): void {
$table->dropIndex(['scanner_user_id', 'event_id']);
$table->dropConstrainedForeignId('event_id');
});
}
};

View File

@@ -9,17 +9,20 @@ return new class extends Migration
public function up(): void
{
Schema::table('users', function (Blueprint $table): void {
// Existing administrators keep their tenant-wide access.
$table->string('admin_scope', 20)->default('tenant');
$table->foreignId('event_id')->nullable()->constrained('events')->nullOnDelete();
$table->foreignId('event_id')
->nullable()
->after('tenant_codigo')
->constrained('events')
->cascadeOnUpdate()
->restrictOnDelete();
});
}
public function down(): void
{
Schema::table('users', function (Blueprint $table): void {
$table->dropConstrainedForeignId('event_id');
$table->dropColumn('admin_scope');
$table->dropForeign(['event_id']);
$table->dropColumn('event_id');
});
}
};

View File

@@ -70,6 +70,18 @@ class MenuSeeder extends Seeder
'parent_menu_code' => 'main.adminapp',
'route' => '/admin/catalog',
],
[
'code' => 'adminapp.combos',
'label' => 'Combos',
'parent_menu_code' => 'main.adminapp',
'route' => '/admin/combos',
],
[
'code' => 'adminapp.categories',
'label' => 'Categorías',
'parent_menu_code' => 'main.adminapp',
'route' => '/admin/categories',
],
[
'code' => 'adminapp.ventas',
'label' => 'Ventas',
@@ -230,8 +242,6 @@ class MenuSeeder extends Seeder
->whereIn('code', [
'admin.event',
'admin.catalog',
'adminapp.combos',
'adminapp.categories',
'admin.combos',
'admin.categories',
'admin.ventas',

View File

@@ -1,236 +0,0 @@
<?php
namespace Tests\Feature\Auth;
use App\Domains\Core\Auth\Models\User;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Schema;
use Illuminate\Testing\TestResponse;
use Tests\TestCase;
class AdminAppEventScopeTest extends TestCase
{
private User $user;
protected function setUp(): void
{
parent::setUp();
// Focused pre-migration schema: do not replay unrelated provisioning migrations.
// Tests\TestCase and tests/bootstrap.php enforce SQLite :memory:.
Schema::create('tenants', function (Blueprint $table): void {
$table->id();
$table->string('codigo')->unique();
$table->string('nombre');
$table->string('dominio');
$table->string('search_product_layout')->default('column_with_image');
$table->string('search_group_layout')->default('paginated');
});
Schema::create('events', function (Blueprint $table): void {
$table->id();
$table->string('tenant_code');
$table->string('title');
$table->timestamps();
});
Schema::create('users', function (Blueprint $table): void {
$table->id();
$table->string('nombre_apellido');
$table->string('email');
$table->string('active_email')->virtualAs('CASE WHEN deleted_at IS NULL THEN lower(email) ELSE NULL END');
$table->string('password');
$table->string('rol_codigo')->default('user');
$table->string('tenant_codigo')->nullable();
$table->softDeletes();
$table->timestamps();
$table->unique(['active_email', 'rol_codigo']);
});
Schema::create('menues', function (Blueprint $table): void {
$table->id();
$table->string('code')->unique();
$table->string('label');
$table->string('route');
$table->string('parent_menu_code')->nullable();
$table->string('content_type')->default('dynamic');
});
Schema::create('roles_menues', function (Blueprint $table): void {
$table->string('rol_codigo');
$table->string('menu_codigo');
});
Schema::create('tenants_menues', function (Blueprint $table): void {
$table->string('tenant_code');
$table->string('menu_code');
$table->json('static_content')->nullable();
$table->timestamps();
});
foreach ([
'2026_06_18_130006_create_personal_access_tokens_table.php',
'2026_07_28_000000_create_roles_and_permissions_tables.php',
'2026_07_29_000000_add_login_security_fields_to_users_table.php',
'2026_07_29_000100_create_login_attempts_table.php',
] as $file) {
(require database_path('migrations/'.$file))->up();
}
DB::table('roles')->insert(['codigo' => 'adminapp', 'nombre' => 'AdminApp']);
DB::table('tenants')->insert([
['codigo' => 'onticket', 'nombre' => 'OnTicket', 'dominio' => 'onticket.test'],
['codigo' => 'other', 'nombre' => 'Other', 'dominio' => 'other.test'],
]);
DB::table('events')->insert([
['id' => 1, 'tenant_code' => 'onticket', 'title' => 'Evento A'],
['id' => 2, 'tenant_code' => 'onticket', 'title' => 'Evento B'],
['id' => 3, 'tenant_code' => 'other', 'title' => 'Evento ajeno'],
]);
// An existing administrator must remain general after applying the new migration.
DB::table('users')->insert([
'id' => 1, 'nombre_apellido' => 'Admin', 'email' => 'admin@example.test',
'password' => Hash::make('secret123'), 'rol_codigo' => 'adminapp', 'tenant_codigo' => 'onticket',
]);
$this->scopeMigration()->up();
$this->user = User::query()->findOrFail(1);
DB::table('menues')->insert([
['code' => 'main.adminapp', 'label' => 'Administración', 'route' => '/', 'parent_menu_code' => null],
['code' => 'adminapp.ventas', 'label' => 'Ventas', 'route' => '/admin/ventas', 'parent_menu_code' => 'main.adminapp'],
]);
foreach (['main.adminapp', 'adminapp.ventas'] as $code) {
DB::table('roles_menues')->insert(['rol_codigo' => 'adminapp', 'menu_codigo' => $code]);
DB::table('tenants_menues')->insert(['tenant_code' => 'onticket', 'menu_code' => $code]);
}
}
private function scopeMigration(): Migration
{
return require database_path('migrations/2026_09_30_000000_add_admin_scope_to_users.php');
}
private function login(array $extra = []): TestResponse
{
return $this->postJson('/api/v1/adminapp/login', [
'email' => ' ADMIN@EXAMPLE.TEST ', 'password' => 'secret123', ...$extra,
]);
}
public function test_existing_admin_keeps_general_access_after_migration(): void
{
$this->assertTrue($this->user->isTenantAdministrator());
$token = $this->login()->assertOk()->assertJsonPath('user.admin_scope', 'tenant')
->assertJsonPath('user.event_id', null)->json('token');
$this->withToken($token)->getJson('/api/v1/adminapp/me')->assertOk()
->assertJsonPath('data.event', null)->assertJsonCount(1, 'data.tenant.menues.0.submenues');
}
public function test_event_admin_logs_in_and_restores_only_its_assigned_context(): void
{
$this->user->update(['admin_scope' => 'event', 'event_id' => 1]);
$this->assertSame(1, $this->user->event->id);
// Scope cannot be chosen by the caller during login.
$token = $this->login(['admin_scope' => 'tenant', 'event_id' => 2])->assertOk()
->assertJsonPath('user.admin_scope', 'event')->assertJsonPath('user.event_id', 1)->json('token');
$this->withToken($token)->getJson('/api/v1/adminapp/me')->assertOk()
->assertJsonPath('data.event.id', 1)->assertJsonPath('data.event.title', 'Evento A')
->assertJsonPath('data.tenant.codigo', 'onticket')
->assertJsonCount(1, 'data.tenant.menues.0.submenues');
$this->assertSame(['adminapp'], $this->user->tokens()->sole()->abilities);
}
public function test_event_admins_of_the_same_tenant_receive_the_same_assigned_menus(): void
{
DB::table('menues')->insert([
'code' => 'onticket.adminapp.event',
'label' => 'Eventos',
'route' => '/admin/event',
'parent_menu_code' => 'main.adminapp',
]);
DB::table('roles_menues')->insert([
'rol_codigo' => 'adminapp',
'menu_codigo' => 'onticket.adminapp.event',
]);
DB::table('tenants_menues')->insert([
'tenant_code' => 'onticket',
'menu_code' => 'onticket.adminapp.event',
]);
$this->user->update(['admin_scope' => 'event', 'event_id' => 1]);
$token = $this->login()->assertOk()->json('token');
$firstMenus = $this->withToken($token)->getJson('/api/v1/adminapp/me')
->assertOk()->json('data.tenant.menues');
$this->user->update(['event_id' => 2]);
$secondMenus = $this->withToken($token)->getJson('/api/v1/adminapp/me')
->assertOk()->json('data.tenant.menues');
$this->assertSame($firstMenus, $secondMenus);
$this->assertSame(
['adminapp.ventas', 'onticket.adminapp.event'],
collect($firstMenus[0]['submenues'])->pluck('code')->sort()->values()->all(),
);
}
public function test_invalid_scopes_never_issue_tokens_or_increment_password_failure_counts(): void
{
foreach ([
['admin_scope' => 'event', 'event_id' => null],
['admin_scope' => 'event', 'event_id' => 3],
['admin_scope' => 'tenant', 'event_id' => 1],
['admin_scope' => 'unknown', 'event_id' => null],
['admin_scope' => 'event', 'event_id' => 1, 'tenant_codigo' => null],
] as $attributes) {
$this->user->update($attributes);
$this->login()->assertUnprocessable()->assertJsonValidationErrors('email');
}
$this->assertDatabaseCount('personal_access_tokens', 0);
$this->assertSame(0, $this->user->refresh()->failed_login_attempts);
}
public function test_event_admin_cannot_access_tenant_operations_but_can_logout(): void
{
$this->user->update(['admin_scope' => 'event', 'event_id' => 1]);
$token = $this->login()->assertOk()->json('token');
foreach (['tenant/tickets', 'tenant/administrators', 'tenant/website-extras', 'forms/tickets-filter'] as $path) {
$this->withToken($token)->getJson('/api/v1/adminapp/'.$path)->assertForbidden();
}
$this->withToken($token)->postJson('/api/v1/adminapp/tenant/administrators', [])->assertForbidden();
$this->withToken($token)->postJson('/api/logout')->assertOk();
$this->assertDatabaseCount('personal_access_tokens', 0);
}
public function test_deleting_the_event_invalidates_an_existing_token_without_promoting_the_user(): void
{
$this->user->update(['admin_scope' => 'event', 'event_id' => 1]);
$token = $this->login()->assertOk()->json('token');
DB::table('events')->where('id', 1)->delete();
$this->assertNull($this->user->refresh()->event_id);
$this->assertSame('event', $this->user->admin_scope);
$this->withToken($token)->getJson('/api/v1/adminapp/me')->assertForbidden();
$this->withToken($token)->getJson('/api/v1/adminapp/tenant/administrators')->assertForbidden();
}
public function test_event_reassignment_and_tenant_changes_apply_to_existing_tokens(): void
{
$this->user->update(['admin_scope' => 'event', 'event_id' => 1]);
$token = $this->login()->assertOk()->json('token');
$this->user->update(['event_id' => 2]);
$this->withToken($token)->getJson('/api/v1/adminapp/me')->assertOk()->assertJsonPath('data.event.id', 2);
DB::table('events')->where('id', 2)->update(['tenant_code' => 'other']);
$this->withToken($token)->getJson('/api/v1/adminapp/me')->assertForbidden();
}
public function test_wrong_password_still_counts_as_a_failed_attempt(): void
{
$this->user->update(['admin_scope' => 'event', 'event_id' => 1]);
$this->login(['password' => 'wrong'])->assertUnprocessable()->assertJsonValidationErrors('email');
$this->assertSame(1, $this->user->refresh()->failed_login_attempts);
$this->assertDatabaseCount('personal_access_tokens', 0);
}
public function test_scope_migration_can_be_rolled_back_without_removing_users(): void
{
$this->scopeMigration()->down();
$this->assertFalse(Schema::hasColumn('users', 'admin_scope'));
$this->assertFalse(Schema::hasColumn('users', 'event_id'));
$this->assertDatabaseHas('users', ['id' => 1, 'email' => 'admin@example.test']);
}
}

View File

@@ -1,485 +0,0 @@
<?php
namespace Tests\Feature\Auth;
use App\Domains\Commerce\Purchase\Models\Purchase;
use App\Domains\Commerce\Sale\Services\AdminAppSaleService;
use App\Domains\Core\Auth\Models\User;
use App\Domains\Core\Auth\Services\ResetPasswordAttemptService;
use App\Domains\Ticketing\Ticket\Models\Ticket;
use App\Domains\Ticketing\Ticket\Services\AdminAppTicketService;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Schema;
use Illuminate\Testing\TestResponse;
use Laravel\Sanctum\Sanctum;
use Tests\TestCase;
class EventScopedOperationsTest extends TestCase
{
private User $user;
protected function setUp(): void
{
parent::setUp();
// Focused pre-migration schema: do not replay unrelated provisioning migrations.
// Tests\TestCase and tests/bootstrap.php enforce SQLite :memory:.
Schema::create('tenants', function (Blueprint $table): void {
$table->id();
$table->string('codigo')->unique();
$table->string('nombre');
$table->string('dominio');
$table->string('search_product_layout')->default('column_with_image');
$table->string('search_group_layout')->default('paginated');
});
Schema::create('events', function (Blueprint $table): void {
$table->id();
$table->string('tenant_code');
$table->string('title');
$table->timestamps();
});
Schema::create('users', function (Blueprint $table): void {
$table->id();
$table->string('nombre_apellido');
$table->string('email');
$table->string('active_email')->virtualAs('CASE WHEN deleted_at IS NULL THEN lower(email) ELSE NULL END');
$table->string('password');
$table->string('rol_codigo')->default('user');
$table->string('tenant_codigo')->nullable();
$table->softDeletes();
$table->timestamps();
$table->unique(['active_email', 'rol_codigo']);
});
Schema::create('menues', function (Blueprint $table): void {
$table->id();
$table->string('code')->unique();
$table->string('label');
$table->string('route');
$table->string('parent_menu_code')->nullable();
$table->string('content_type')->default('dynamic');
});
Schema::create('roles_menues', function (Blueprint $table): void {
$table->string('rol_codigo');
$table->string('menu_codigo');
});
Schema::create('tenants_menues', function (Blueprint $table): void {
$table->string('tenant_code');
$table->string('menu_code');
$table->json('static_content')->nullable();
$table->timestamps();
});
foreach ([
'2026_06_18_130006_create_personal_access_tokens_table.php',
'2026_07_28_000000_create_roles_and_permissions_tables.php',
'2026_07_29_000000_add_login_security_fields_to_users_table.php',
'2026_07_29_000100_create_login_attempts_table.php',
] as $file) {
(require database_path('migrations/'.$file))->up();
}
DB::table('roles')->insert(['codigo' => 'adminapp', 'nombre' => 'AdminApp']);
DB::table('tenants')->insert([
['codigo' => 'onticket', 'nombre' => 'OnTicket', 'dominio' => 'onticket.test'],
['codigo' => 'other', 'nombre' => 'Other', 'dominio' => 'other.test'],
]);
DB::table('events')->insert([
['id' => 1, 'tenant_code' => 'onticket', 'title' => 'Evento A'],
['id' => 2, 'tenant_code' => 'onticket', 'title' => 'Evento B'],
['id' => 3, 'tenant_code' => 'other', 'title' => 'Evento ajeno'],
]);
// An existing administrator must remain general after applying the new migration.
DB::table('users')->insert([
'id' => 1, 'nombre_apellido' => 'Admin', 'email' => 'admin@example.test',
'password' => Hash::make('secret123'), 'rol_codigo' => 'adminapp', 'tenant_codigo' => 'onticket',
]);
$this->scopeMigration()->up();
$this->user = User::query()->findOrFail(1);
$this->createOperationsSchema();
DB::table('menues')->insert([
['code' => 'main.adminapp', 'label' => 'Administración', 'route' => '/', 'parent_menu_code' => null],
['code' => 'adminapp.ventas', 'label' => 'Ventas', 'route' => '/admin/ventas', 'parent_menu_code' => 'main.adminapp'],
]);
foreach (['main.adminapp', 'adminapp.ventas'] as $code) {
DB::table('roles_menues')->insert(['rol_codigo' => 'adminapp', 'menu_codigo' => $code]);
DB::table('tenants_menues')->insert(['tenant_code' => 'onticket', 'menu_code' => $code]);
}
}
private function scopeMigration(): Migration
{
return require database_path('migrations/2026_09_30_000000_add_admin_scope_to_users.php');
}
private function login(array $extra = []): TestResponse
{
return $this->postJson('/api/v1/adminapp/login', [
'email' => ' ADMIN@EXAMPLE.TEST ', 'password' => 'secret123', ...$extra,
]);
}
private function createOperationsSchema(): void
{
Schema::table('tenants', function (Blueprint $table): void {
$table->unsignedBigInteger('active_event_id')->nullable();
$table->boolean('scanner_category_validation_enabled')->default(false);
$table->boolean('allow_ticket_refund')->default(true);
$table->boolean('allow_ticket_total_refund')->default(true);
$table->boolean('allow_ticket_partial_refund')->default(true);
$table->decimal('ticket_partial_refund_percentage')->default(25);
});
Schema::table('users', fn (Blueprint $table) => $table->string('dni')->nullable());
Schema::table('events', function (Blueprint $table): void {
$table->string('location')->nullable();
$table->string('date_text')->nullable();
});
(require database_path('migrations/2026_09_30_000200_add_refund_configuration_to_events.php'))->up();
DB::table('tenants')->where('codigo', 'onticket')->update(['active_event_id' => 2]);
Schema::create('social_media', function (Blueprint $table): void {
$table->id();
$table->string('code')->unique();
$table->string('nombre');
});
Schema::create('event_social_media', function (Blueprint $table): void {
$table->unsignedBigInteger('event_id');
$table->string('social_media_code');
$table->string('url');
$table->integer('orden');
$table->timestamps();
});
Schema::create('event_dates', function (Blueprint $table): void {
$table->id();
$table->string('tenant_code');
$table->unsignedBigInteger('event_id');
$table->date('date');
$table->time('time_start');
$table->time('time_end');
$table->unsignedBigInteger('validity_time_id')->nullable();
$table->unsignedBigInteger('rescheduled_to_event_date_id')->nullable();
$table->timestamp('suspended_at')->nullable();
});
Schema::create('validity_times', function (Blueprint $table): void {
$table->id();
$table->string('type');
$table->time('start_time')->nullable();
$table->time('end_time')->nullable();
$table->timestamp('fixed_starts_at')->nullable();
$table->timestamp('fixed_expires_at')->nullable();
$table->timestamps();
});
Schema::create('categorias', function (Blueprint $table): void {
$table->id();
$table->string('tenant_code')->nullable();
$table->unsignedBigInteger('categoria_id')->nullable();
$table->string('nombre');
});
Schema::create('category_scanners', function (Blueprint $table): void {
$table->unsignedBigInteger('user_id');
$table->unsignedBigInteger('categoria_id');
$table->timestamps();
});
Schema::create('catalog_items', function (Blueprint $table): void {
$table->id();
$table->string('tenant_code');
$table->unsignedBigInteger('event_id');
$table->unsignedBigInteger('category_id')->nullable();
$table->string('nombre');
$table->string('slug');
$table->text('descripcion')->nullable();
$table->decimal('precio')->default(0);
$table->string('type')->default('standard');
$table->string('inventory_policy')->default('tracked');
$table->string('inventory_subject')->default('product');
$table->integer('group_order')->default(0);
$table->boolean('has_tickets')->default(false);
$table->softDeletes();
});
Schema::create('compras', function (Blueprint $table): void {
$table->id();
$table->string('tenant_codigo');
$table->unsignedBigInteger('event_id');
$table->string('status');
$table->decimal('total');
$table->string('nombre_apellido');
$table->timestamps();
});
Schema::create('compra_items', function (Blueprint $table): void {
$table->id();
$table->unsignedBigInteger('compra_id');
$table->integer('cantidad');
$table->string('item_nombre')->nullable();
$table->decimal('precio_unitario')->default(10);
$table->decimal('total')->default(10);
});
Schema::create('tickets', function (Blueprint $table): void {
$table->id();
$table->string('tenant_code');
$table->unsignedBigInteger('event_id')->nullable();
$table->uuid('ticket');
foreach (['source_purchase_item_id', 'source_catalog_item_id', 'source_variant_id', 'scanner_user_id', 'user_id'] as $column) {
$table->unsignedBigInteger($column)->nullable();
}
foreach (['used_at', 'disabled_at', 'cancelled_at', 'refunded_at'] as $column) {
$table->timestamp($column)->nullable();
}
});
Schema::create('ticket_refunds', function (Blueprint $table): void {
$table->id();
$table->unsignedBigInteger('purchase_item_id');
$table->decimal('amount');
});
Schema::create('scan_attempts', function (Blueprint $table): void {
$table->id();
$table->string('tenant_code');
$table->unsignedBigInteger('scanner_user_id');
$table->unsignedBigInteger('ticket_id')->nullable();
$table->text('data')->nullable();
$table->string('result');
$table->timestamp('created_at')->nullable();
$table->timestamp('resolved_at')->nullable();
});
(require database_path('migrations/2026_09_30_000400_add_event_id_to_scan_attempts.php'))->up();
Schema::create('value_changes', function (Blueprint $table): void {
$table->id();
$table->string('tenant_code');
$table->string('trackable_type');
$table->unsignedBigInteger('trackable_id');
$table->string('attribute');
$table->string('old_value')->nullable();
$table->string('new_value')->nullable();
$table->string('actor_type')->default('user');
$table->unsignedBigInteger('user_id')->nullable();
$table->timestamp('changed_at')->nullable();
});
DB::table('roles')->insert(['codigo' => 'scanner', 'nombre' => 'Scanner']);
DB::table('permisos')->insert(['codigo' => 'tickets.escanear', 'nombre' => 'Escanear']);
DB::table('roles_permisos')->insert(['rol_codigo' => 'scanner', 'codigo_permiso' => 'tickets.escanear']);
foreach (['adminapp.catalog', 'adminapp.event', 'adminapp.staff', 'adminapp.inicio'] as $code) {
DB::table('menues')->insert(['code' => $code, 'label' => $code, 'route' => '/admin/test', 'parent_menu_code' => 'main.adminapp']);
DB::table('roles_menues')->insert(['rol_codigo' => 'adminapp', 'menu_codigo' => $code]);
DB::table('tenants_menues')->insert(['tenant_code' => 'onticket', 'menu_code' => $code]);
}
}
private function actingEventAdmin(): void
{
$this->user->update(['admin_scope' => 'event', 'event_id' => 1]);
Sanctum::actingAs($this->user);
}
public function test_event_and_refund_settings_use_user_event_even_when_tenant_active_event_changes(): void
{
$this->actingEventAdmin();
$this->getJson('/api/v1/adminapp/tenant/event')->assertOk()->assertJsonPath('data.id', 1)
->assertJsonPath('data.allow_ticket_refund', true);
$this->putJson('/api/v1/adminapp/tenant/event', [
'title' => 'Solo A', 'location' => 'Predio A', 'social_media' => [], 'allow_ticket_refund' => false,
'allow_ticket_total_refund' => true, 'allow_ticket_partial_refund' => true,
'ticket_partial_refund_percentage' => 30,
])->assertOk()->assertJsonPath('data.id', 1)->assertJsonPath('data.allow_ticket_refund', false);
$this->assertDatabaseHas('events', ['id' => 1, 'title' => 'Solo A', 'allow_ticket_refund' => false]);
$this->assertDatabaseHas('events', ['id' => 2, 'title' => 'Evento B', 'allow_ticket_refund' => true]);
$this->assertDatabaseHas('tenants', ['codigo' => 'onticket', 'allow_ticket_refund' => true]);
$this->getJson('/api/v1/adminapp/forms/event')->assertOk();
$this->getJson('/api/v1/adminapp/tenant/website-extras')->assertForbidden();
}
public function test_dates_are_created_on_user_event_and_other_event_dates_cannot_be_changed(): void
{
$this->actingEventAdmin();
$this->postJson('/api/v1/adminapp/tenant/event-dates', [
'date' => '2027-01-20', 'start_time' => '10:00', 'end_time' => '12:00',
])->assertSuccessful();
$this->assertDatabaseHas('event_dates', ['event_id' => 1, 'date' => '2027-01-20']);
DB::table('event_dates')->insert(['id' => 20, 'event_id' => 2, 'tenant_code' => 'onticket',
'date' => '2027-01-20', 'time_start' => '10:00', 'time_end' => '12:00']);
$this->postJson('/api/v1/adminapp/tenant/event-dates/20/suspend')->assertNotFound();
$this->postJson('/api/v1/adminapp/tenant/event-dates/20/reschedule', ['date' => '2027-01-21'])->assertNotFound();
$this->assertDatabaseHas('event_dates', ['id' => 20, 'suspended_at' => null]);
}
public function test_sales_totals_details_exports_and_history_are_scoped_to_user_event(): void
{
$this->actingEventAdmin();
foreach ([1, 2] as $id) {
DB::table('compras')->insert(['id' => $id, 'tenant_codigo' => 'onticket', 'event_id' => $id,
'status' => 'paid', 'total' => $id * 100, 'nombre_apellido' => 'Cliente', 'created_at' => now()]);
DB::table('compra_items')->insert(['id' => $id, 'compra_id' => $id, 'cantidad' => 1]);
DB::table('ticket_refunds')->insert(['purchase_item_id' => $id, 'amount' => $id * 10]);
DB::table('value_changes')->insert(['tenant_code' => 'onticket',
'trackable_type' => (new Purchase)->getMorphClass(),
'trackable_id' => $id, 'attribute' => 'status', 'new_value' => 'paid', 'changed_at' => now()]);
}
$this->getJson('/api/v1/adminapp/tenant/sales')->assertOk()->assertJsonCount(1, 'data')
->assertJsonPath('confirmed_sales_total', '100.00')->assertJsonPath('refunded_total', '10.00');
$this->getJson('/api/v1/adminapp/tenant/sales/1')->assertOk();
foreach (['', '/tickets'] as $suffix) {
$this->getJson('/api/v1/adminapp/tenant/sales/2'.$suffix)->assertNotFound();
}
foreach (['confirm', 'cancel'] as $action) {
$this->postJson('/api/v1/adminapp/tenant/sales/2/'.$action)->assertNotFound();
}
$this->getJson('/api/v1/adminapp/tenant/sales/modifications')->assertOk()->assertJsonCount(1, 'data');
$service = app(AdminAppSaleService::class);
$tenant = $this->user->tenant;
$this->assertSame([1], $service->salesForExport($tenant, [], 1)->pluck('id')->all());
$this->assertSame([1], $service->modificationsForExport($tenant, [], 1)->pluck('trackable_id')->all());
}
private function scanner(int $eventId, int $id = 10): User
{
return User::query()->create(['id' => $id, 'nombre_apellido' => 'Scanner',
'email' => "scanner{$id}@example.test", 'password' => 'password', 'dni' => '123',
'tenant_codigo' => 'onticket', 'rol_codigo' => 'scanner', 'admin_scope' => 'event', 'event_id' => $eventId]);
}
public function test_staff_is_created_on_admin_event_and_other_staff_cannot_be_managed(): void
{
$this->actingEventAdmin();
$scanner = $this->scanner(2);
$this->getJson('/api/v1/adminapp/tenant/staff')->assertOk()->assertJsonCount(0, 'data');
$payload = ['nombre_apellido' => 'Nuevo', 'email' => 'nuevo@example.test', 'dni' => '123'];
$this->putJson('/api/v1/adminapp/tenant/staff/'.$scanner->id, $payload)->assertNotFound();
$this->deleteJson('/api/v1/adminapp/tenant/staff/'.$scanner->id)->assertNotFound();
$this->getJson('/api/v1/adminapp/tenant/staff/'.$scanner->id.'/scan-attempts')->assertNotFound();
$this->mock(ResetPasswordAttemptService::class,
fn ($mock) => $mock->shouldReceive('createForScannerEmail')->once());
$this->postJson('/api/v1/adminapp/tenant/staff', [...$payload, 'event_id' => 2])
->assertSuccessful()->assertJsonPath('data.event_id', 1);
$this->assertDatabaseHas('users', ['email' => 'nuevo@example.test', 'event_id' => 1, 'admin_scope' => 'event']);
}
public function test_scanner_rejects_foreign_event_qr_without_consuming_or_disclosing_ticket(): void
{
$scanner = $this->scanner(1);
Sanctum::actingAs($scanner);
$uuid = '11111111-1111-4111-8111-111111111111';
DB::table('tickets')->insert(['id' => 20, 'tenant_code' => 'onticket', 'event_id' => 2, 'ticket' => $uuid]);
$this->getJson('/api/v1/scanner/tickets/'.$uuid)->assertNotFound();
$this->postJson('/api/v1/scanner/tickets/scan', ['data' => $uuid])->assertOk()
->assertJsonPath('data.scan_attempt.result', 'ticket_not_found')->assertJsonPath('data.ticket', null);
$this->assertDatabaseHas('tickets', ['id' => 20, 'used_at' => null, 'scanner_user_id' => null]);
$this->assertDatabaseHas('scan_attempts', ['scanner_user_id' => $scanner->id, 'event_id' => 1, 'ticket_id' => null]);
}
public function test_scanner_history_and_detail_follow_assignment_changes_and_invalid_event_is_denied(): void
{
$scanner = $this->scanner(1);
Sanctum::actingAs($scanner);
$response = $this->postJson('/api/v1/scanner/tickets/scan', ['data' => 'invalid'])->assertOk();
$id = $response->json('data.scan_attempt.id');
$this->getJson('/api/v1/scanner/attempts')->assertOk()->assertJsonCount(1, 'data');
$scanner->update(['event_id' => 2]);
$this->getJson('/api/v1/scanner/attempts')->assertOk()->assertJsonCount(0, 'data');
$this->getJson('/api/v1/scanner/attempts/'.$id)->assertNotFound();
$scanner->update(['event_id' => null]);
$this->getJson('/api/v1/scanner/attempts')->assertForbidden();
}
public function test_initial_assignment_migration_preserves_existing_scopes_and_ignores_missing_events(): void
{
$this->user->update(['admin_scope' => 'event', 'event_id' => 1]);
$scanner = $this->scanner(1);
$scanner->update(['event_id' => null, 'admin_scope' => 'tenant']);
$migration = require database_path('migrations/2026_09_30_000100_assign_active_event_to_staff_users.php');
$migration->up();
$migration->up();
$this->assertDatabaseHas('users', ['id' => 1, 'event_id' => 1]);
$this->assertDatabaseHas('users', ['id' => $scanner->id, 'event_id' => 2, 'admin_scope' => 'event']);
DB::table('tenants')->where('codigo', 'onticket')->update(['active_event_id' => 3]);
$scanner->refresh()->update(['event_id' => null, 'admin_scope' => 'tenant']);
$migration->up();
$this->assertDatabaseHas('users', ['id' => $scanner->id, 'event_id' => null, 'admin_scope' => 'event']);
}
public function test_deprecated_menus_are_removed_with_their_role_and_tenant_assignments(): void
{
foreach (['adminapp.categories', 'adminapp.combos'] as $code) {
DB::table('menues')->insert(['code' => $code, 'label' => $code, 'route' => '/admin/old']);
DB::table('roles_menues')->insert(['rol_codigo' => 'adminapp', 'menu_codigo' => $code]);
DB::table('tenants_menues')->insert(['tenant_code' => 'onticket', 'menu_code' => $code]);
}
(require database_path('migrations/2026_09_30_000300_remove_deprecated_admin_menus.php'))->up();
foreach (['adminapp.categories', 'adminapp.combos'] as $code) {
$this->assertDatabaseMissing('menues', ['code' => $code]);
$this->assertDatabaseMissing('roles_menues', ['menu_codigo' => $code]);
$this->assertDatabaseMissing('tenants_menues', ['menu_code' => $code]);
}
}
public function test_scanner_accepts_ticket_from_its_event_and_cannot_consume_it_twice(): void
{
$scanner = $this->scanner(1);
Sanctum::actingAs($scanner);
$uuid = '11111111-1111-4111-8111-111111111111';
DB::table('tickets')->insert(['id' => 20, 'tenant_code' => 'onticket', 'event_id' => 1, 'ticket' => $uuid]);
$this->postJson('/api/v1/scanner/tickets/scan', ['data' => $uuid])->assertOk()
->assertJsonPath('data.scan_attempt.result', 'accepted')->assertJsonPath('data.ticket.id', 20);
$this->assertNotNull(DB::table('tickets')->where('id', 20)->value('used_at'));
$this->postJson('/api/v1/scanner/tickets/scan', ['data' => $uuid])->assertOk()
->assertJsonPath('data.scan_attempt.result', 'already_scanned');
$this->getJson('/api/v1/scanner/tickets/'.$uuid)->assertOk();
}
public function test_refund_calculation_uses_ticket_event_configuration_instead_of_tenant_defaults(): void
{
Schema::create('desfile_entry_reservations', function (Blueprint $table): void {
$table->id();
$table->unsignedBigInteger('ticket_id');
$table->softDeletes();
});
DB::table('ticket_refunds')->delete();
DB::table('compra_items')->insert(['id' => 1, 'compra_id' => 1, 'cantidad' => 1,
'precio_unitario' => 100, 'total' => 100]);
DB::table('tickets')->insert(['id' => 20, 'tenant_code' => 'onticket', 'event_id' => 1,
'ticket' => '11111111-1111-4111-8111-111111111111', 'source_purchase_item_id' => 1]);
DB::table('events')->where('id', 1)->update(['ticket_partial_refund_percentage' => 75]);
$calculation = app(AdminAppTicketService::class)
->calculateRefund($this->user->tenant, 20);
$this->assertSame(['total' => '100.00', 'partial' => '75.00'], $calculation);
DB::table('events')->where('id', 1)->update(['allow_ticket_refund' => false]);
$this->assertFalse(Ticket::query()->findOrFail(20)->allow_refund());
}
public function test_staff_category_options_and_assignments_exclude_other_event_products(): void
{
$this->actingEventAdmin();
DB::table('tenants')->where('codigo', 'onticket')->update(['scanner_category_validation_enabled' => true]);
foreach ([1, 2] as $id) {
DB::table('categorias')->insert(['id' => $id, 'nombre' => "Categoria {$id}", 'tenant_code' => 'onticket']);
DB::table('catalog_items')->insert(['id' => $id, 'tenant_code' => 'onticket', 'event_id' => $id,
'nombre' => "Producto {$id}", 'slug' => "producto-{$id}", 'category_id' => $id]);
}
$this->getJson('/api/v1/adminapp/forms/staff')->assertOk()->assertJsonCount(1, 'data.categories')
->assertJsonPath('data.categories.0.id', 1);
$this->postJson('/api/v1/adminapp/tenant/staff', ['nombre_apellido' => 'Nuevo', 'dni' => '123',
'email' => 'nuevo@example.test', 'category_ids' => [2]])->assertUnprocessable()->assertJsonValidationErrors('category_ids');
$this->assertDatabaseMissing('users', ['email' => 'nuevo@example.test']);
}
public function test_initial_migration_assigns_existing_tenant_admin_and_blocks_staff_without_active_event(): void
{
$unassigned = $this->scanner(1);
$unassigned->update(['tenant_codigo' => 'other', 'admin_scope' => 'tenant', 'event_id' => null]);
(require database_path('migrations/2026_09_30_000100_assign_active_event_to_staff_users.php'))->up();
$this->assertDatabaseHas('users', ['id' => 1, 'admin_scope' => 'event', 'event_id' => 2]);
$this->assertDatabaseHas('users', ['id' => $unassigned->id, 'admin_scope' => 'event', 'event_id' => null]);
$this->user->refresh();
$this->assertFalse($this->user->isTenantAdministrator());
$this->login()->assertOk()->assertJsonPath('user.event_id', 2);
}
public function test_scanner_login_validates_event_before_issuing_a_token(): void
{
$scanner = $this->scanner(1);
$this->postJson('/api/v1/scanner/login', ['email' => $scanner->email, 'password' => 'password'])
->assertOk()->assertJsonPath('user.event_id', 1);
$scanner->update(['event_id' => null]);
$this->postJson('/api/v1/scanner/login', ['email' => $scanner->email, 'password' => 'password'])
->assertUnprocessable()->assertJsonValidationErrors('email');
$this->assertDatabaseCount('personal_access_tokens', 1);
$this->assertSame(0, $scanner->refresh()->failed_login_attempts);
}
}

View File

@@ -17,6 +17,7 @@ class UserAuthorizationRelationsTest extends TestCase
$this->assertTrue(Schema::hasColumns('users', [
'rol_codigo',
'tenant_codigo',
'event_id',
]));
}
@@ -28,5 +29,7 @@ class UserAuthorizationRelationsTest extends TestCase
$this->assertNull($user->tenant_codigo);
$this->assertSame(RoleCode::User->value, $user->role->codigo);
$this->assertNull($user->tenant);
$this->assertNull($user->event_id);
$this->assertNull($user->event);
}
}

View File

@@ -0,0 +1,76 @@
<?php
namespace Tests\Feature\Menu;
use App\Domains\Core\Auth\Models\User;
use App\Http\Middleware\EnsureTenantHasMenu;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Schema;
use PHPUnit\Framework\Attributes\DataProvider;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Tests\TestCase;
class TicketMenuAccessTest extends TestCase
{
public static function menuAssignments(): array
{
return [
'new code' => ['onticket.adminapp.tickets', 'current', false],
'old code' => ['adminapp.tickets', 'current', true],
'another tenant' => ['adminapp.tickets', 'other', false],
'unrelated menu' => ['adminapp.ventas', 'current', false],
];
}
#[DataProvider('menuAssignments')]
public function test_ticket_menu_requires_an_association_with_the_authenticated_tenant(string $menuCode, string $assignedTenant, bool $allowed): void
{
Schema::create('tenants', function (Blueprint $table): void {
$table->id();
$table->string('codigo');
});
Schema::create('menues', function (Blueprint $table): void {
$table->id();
$table->string('code');
});
Schema::create('tenants_menues', function (Blueprint $table): void {
$table->string('tenant_code');
$table->string('menu_code');
});
DB::table('tenants')->insert(['codigo' => 'current']);
DB::table('menues')->insert(['code' => $menuCode]);
DB::table('tenants_menues')->insert(['tenant_code' => $assignedTenant, 'menu_code' => $menuCode]);
$user = new User(['tenant_codigo' => 'current']);
$request = Request::create('/api/v1/adminapp/tenant/tickets');
$request->setUserResolver(fn () => $user);
if (! $allowed) {
$this->expectException(HttpException::class);
$this->expectExceptionCode(0);
}
try {
$response = (new EnsureTenantHasMenu)->handle($request, fn () => response('allowed'), 'adminapp.tickets');
$this->assertSame('allowed', $response->getContent());
} catch (HttpException $exception) {
$this->assertSame(404, $exception->getStatusCode());
throw $exception;
}
}
public function test_all_ticket_routes_and_filter_form_use_the_updated_menu_codes(): void
{
foreach ([
'adminapp.tickets.index', 'adminapp.tickets.cancel',
'adminapp.tickets.calculate-refund', 'adminapp.tickets.refund',
'adminapp.tickets.pdf', 'adminapp.tickets.excel', 'adminapp.forms.tickets-filter',
] as $name) {
$route = Route::getRoutes()->getByName($name);
$this->assertNotNull($route);
$this->assertContains('tenant.menu:adminapp.tickets', $route->gatherMiddleware());
}
}
}

View File

@@ -0,0 +1,57 @@
<?php
namespace Tests\Feature\Migrations;
use App\Domains\Core\Administrator\Resources\AdministratorResource;
use App\Domains\Core\Auth\Models\User;
use App\Domains\Core\Auth\Resources\UserResource;
use Illuminate\Database\QueryException;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Tests\TestCase;
class AddEventIdToUsersTest extends TestCase
{
public function test_event_assignment_preserves_existing_users_and_restricts_event_deletion(): void
{
Schema::create('events', function (Blueprint $table): void {
$table->id();
});
Schema::create('users', function (Blueprint $table): void {
$table->id();
$table->string('tenant_codigo')->nullable();
$table->softDeletes();
$table->timestamps();
});
DB::table('users')->insert(['id' => 1, 'tenant_codigo' => 'legacy']);
DB::table('events')->insert(['id' => 42]);
$migration = require database_path('migrations/2026_10_01_000000_add_event_id_to_users_table.php');
$migration->up();
$legacy = User::query()->findOrFail(1);
$this->assertNull($legacy->event_id);
$this->assertNull($legacy->event);
$this->assertSame('legacy', $legacy->tenant_codigo);
$legacy->update(['event_id' => '42']);
$user = $legacy->fresh();
$this->assertSame(42, $user->event_id);
$this->assertSame(42, $user->event->id);
$this->assertSame(42, UserResource::make($user)->resolve(new Request)['event_id']);
$this->assertSame(42, AdministratorResource::make($user)->resolve(new Request)['event_id']);
try {
DB::table('events')->where('id', 42)->delete();
$this->fail('An assigned event must not be deleted.');
} catch (QueryException $exception) {
$this->assertStringContainsString('FOREIGN KEY', $exception->getMessage());
}
$migration->down();
$this->assertFalse(Schema::hasColumn('users', 'event_id'));
$this->assertSame('legacy', DB::table('users')->where('id', 1)->value('tenant_codigo'));
}
}

View File

@@ -0,0 +1,183 @@
<?php
namespace Tests\Feature\Sale;
use App\Domains\Commerce\Purchase\Models\Purchase;
use App\Domains\Commerce\Purchase\Services\CheckoutService;
use App\Domains\Commerce\Sale\Services\AdminAppSaleExcelService;
use App\Domains\Commerce\Sale\Services\AdminAppSalePdfService;
use App\Domains\Core\Auth\Models\User;
use App\Domains\Core\Authorization\Enums\RoleCode;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Laravel\Sanctum\Sanctum;
use Mockery\MockInterface;
use Symfony\Component\HttpFoundation\StreamedResponse;
use Tests\TestCase;
class AdminAppSaleEventScopeTest extends TestCase
{
protected function setUp(): void
{
parent::setUp();
// Isolated schema: the full legacy migration chain cannot run on SQLite.
Schema::create('tenants', function (Blueprint $table): void {
$table->id();
$table->string('codigo');
});
Schema::create('users', function (Blueprint $table): void {
$table->id();
$table->softDeletes();
});
Schema::create('compras', function (Blueprint $table): void {
$table->id();
$table->string('tenant_codigo');
$table->unsignedBigInteger('event_id')->nullable();
$table->string('nombre_apellido');
$table->string('status');
$table->decimal('total', 12, 2);
$table->timestamps();
});
Schema::create('compra_items', function (Blueprint $table): void {
$table->id();
$table->unsignedBigInteger('compra_id');
$table->integer('cantidad');
});
Schema::create('tickets', function (Blueprint $table): void {
$table->id();
$table->unsignedBigInteger('source_purchase_item_id');
});
Schema::create('ticket_refunds', function (Blueprint $table): void {
$table->id();
$table->unsignedBigInteger('purchase_item_id');
$table->decimal('amount', 12, 2);
});
Schema::create('value_changes', function (Blueprint $table): void {
$table->id();
$table->string('tenant_code');
$table->string('trackable_type');
$table->unsignedBigInteger('trackable_id');
$table->string('attribute');
$table->string('old_value');
$table->string('new_value');
$table->timestamp('changed_at');
$table->string('actor_type');
$table->unsignedBigInteger('user_id')->nullable();
});
DB::table('tenants')->insert(['codigo' => 'onticket']);
foreach ([1 => ['onticket', 10], 2 => ['onticket', 20], 3 => ['onticket', null], 4 => ['other', 10]] as $id => [$tenant, $event]) {
DB::table('compras')->insert([
'id' => $id,
'tenant_codigo' => $tenant,
'event_id' => $event,
'nombre_apellido' => 'Cliente',
'status' => Purchase::STATUS_PAID,
'total' => $id * 100,
'created_at' => now(),
'updated_at' => now(),
]);
DB::table('compra_items')->insert(['id' => $id, 'compra_id' => $id, 'cantidad' => 1]);
DB::table('ticket_refunds')->insert(['purchase_item_id' => $id, 'amount' => $id * 10]);
DB::table('value_changes')->insert([
'id' => $id,
'tenant_code' => $tenant,
'trackable_type' => (new Purchase)->getMorphClass(),
'trackable_id' => $id,
'attribute' => 'status',
'old_value' => Purchase::STATUS_PENDING_PAYMENT,
'new_value' => Purchase::STATUS_PAID,
'changed_at' => now(),
'actor_type' => 'system',
]);
}
$this->actingAsAdministrator(10);
}
public function test_list_totals_and_filters_cannot_escape_the_authenticated_event(): void
{
$this->getJson('/api/v1/adminapp/tenant/sales?event_id=20&q=Cliente')
->assertOk()
->assertJsonCount(1, 'data')
->assertJsonPath('data.0.id', 1)
->assertJsonPath('confirmed_sales_total', '100.00')
->assertJsonPath('refunded_total', '10.00');
$this->getJson('/api/v1/adminapp/tenant/sales?id=2')->assertOk()->assertJsonCount(0, 'data');
$this->getJson('/api/v1/adminapp/tenant/sales/modifications?q=Cliente')
->assertOk()->assertJsonCount(1, 'data')->assertJsonPath('data.0.sale_id', 1);
}
public function test_unscoped_administrators_keep_access_to_all_sales_in_their_tenant(): void
{
$this->actingAsAdministrator(null);
$this->getJson('/api/v1/adminapp/tenant/sales')->assertOk()->assertJsonCount(3, 'data')
->assertJsonPath('confirmed_sales_total', '600.00')->assertJsonPath('refunded_total', '60.00');
$this->getJson('/api/v1/adminapp/tenant/sales/modifications')->assertOk()->assertJsonCount(3, 'data');
$this->getJson('/api/v1/adminapp/tenant/sales/2')->assertOk();
$this->getJson('/api/v1/adminapp/tenant/sales/3')->assertOk();
}
public function test_foreign_and_unassigned_sales_are_inaccessible_before_any_checkout_action(): void
{
$this->mock(CheckoutService::class, function (MockInterface $mock): void {
$mock->shouldNotReceive('confirmPaidPurchase');
$mock->shouldNotReceive('cancelPurchaseFromAdmin');
});
foreach ([2, 3, 4] as $id) {
$this->getJson("/api/v1/adminapp/tenant/sales/{$id}")->assertNotFound();
$this->getJson("/api/v1/adminapp/tenant/sales/{$id}/tickets")->assertNotFound();
$this->postJson("/api/v1/adminapp/tenant/sales/{$id}/confirm", ['event_id' => 20])->assertNotFound();
$this->postJson("/api/v1/adminapp/tenant/sales/{$id}/cancel", ['event_id' => 20])->assertNotFound();
}
$this->assertSame(Purchase::STATUS_PAID, DB::table('compras')->where('id', 2)->value('status'));
}
public function test_own_event_allows_detail_tickets_and_checkout_actions(): void
{
// Empty snapshots keep this fixture focused on authorization.
DB::table('compra_items')->where('compra_id', 1)->delete();
$this->mock(CheckoutService::class, function (MockInterface $mock): void {
foreach (['confirmPaidPurchase', 'cancelPurchaseFromAdmin'] as $method) {
$mock->shouldReceive($method)->once()->withArgs(fn (Purchase $sale): bool => $sale->id === 1)
->andReturnUsing(fn (Purchase $sale): Purchase => $sale);
}
});
$this->getJson('/api/v1/adminapp/tenant/sales/1')->assertOk()->assertJsonPath('data.id', 1);
$this->getJson('/api/v1/adminapp/tenant/sales/1/tickets')->assertOk();
$this->postJson('/api/v1/adminapp/tenant/sales/1/confirm')->assertOk()->assertJsonPath('data.id', 1);
$this->postJson('/api/v1/adminapp/tenant/sales/1/cancel')->assertOk()->assertJsonPath('data.id', 1);
}
public function test_pdf_and_excel_exports_only_receive_sales_and_history_for_the_own_event(): void
{
foreach ([AdminAppSalePdfService::class, AdminAppSaleExcelService::class] as $class) {
$this->mock($class, function (MockInterface $mock) use ($class): void {
foreach (['downloadSales', 'downloadModifications'] as $method) {
$mock->shouldReceive($method)->once()->withArgs(
fn ($tenant, Collection $rows, $timezone): bool => $tenant->codigo === 'onticket'
&& $rows->pluck('id')->all() === [1] && $timezone === 'UTC'
)->andReturn($class === AdminAppSalePdfService::class
? response('pdf') : new StreamedResponse(fn () => print ('excel')));
}
});
}
foreach (['pdf', 'excel', 'modifications/pdf', 'modifications/excel'] as $path) {
$this->getJson("/api/v1/adminapp/tenant/sales/{$path}?timezone=UTC&event_id=20")->assertOk();
}
}
private function actingAsAdministrator(?int $eventId): void
{
$user = new User;
$user->setRawAttributes([
'id' => 1,
'rol_codigo' => RoleCode::AdminApp->value,
'tenant_codigo' => 'onticket',
'event_id' => $eventId,
]);
Sanctum::actingAs($user);
}
}

View File

@@ -27,6 +27,8 @@ class MenuSeederTest extends TestCase
$expectedMenus = [
'adminapp.inicio' => ['Inicio', '/admin/inicio'],
'adminapp.catalog' => ['Catálogo', '/admin/catalog'],
'adminapp.categories' => ['Categorías', '/admin/categories'],
'adminapp.combos' => ['Combos', '/admin/combos'],
'adminapp.event' => ['Eventos', '/admin/event'],
'adminapp.staff' => ['Staff', '/admin/staff'],
'adminapp.ventas' => ['Ventas', '/admin/ventas'],
@@ -98,8 +100,6 @@ class MenuSeederTest extends TestCase
$this->assertFalse(
Menu::query()->whereIn('code', [
'adminapp.categories',
'adminapp.combos',
'admin.event',
'admin.catalog',
'admin.combos',

View File

@@ -0,0 +1,158 @@
<?php
namespace Tests\Feature\Staff;
use App\Domains\Core\Auth\Models\User;
use App\Domains\Core\Auth\Services\ResetPasswordAttemptService;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Laravel\Sanctum\Sanctum;
use Mockery\MockInterface;
use Tests\TestCase;
class StaffEventScopeTest extends TestCase
{
protected function setUp(): void
{
parent::setUp();
// Exercise HTTP authorization on SQLite without the incompatible legacy migrations.
Schema::create('tenants', function (Blueprint $table): void {
$table->id();
$table->string('codigo');
$table->boolean('scanner_category_validation_enabled')->default(false);
});
Schema::create('roles', function (Blueprint $table): void {
$table->id();
$table->string('codigo');
$table->string('nombre');
});
Schema::create('users', function (Blueprint $table): void {
$table->id();
$table->string('rol_codigo');
$table->string('tenant_codigo');
$table->unsignedBigInteger('event_id')->nullable();
$table->string('nombre_apellido');
$table->string('dni');
$table->string('email');
$table->string('active_email')->nullable();
$table->string('password')->nullable();
$table->timestamps();
$table->softDeletes();
});
Schema::create('categorias', function (Blueprint $table): void {
$table->id();
$table->string('nombre');
$table->string('tenant_code')->nullable();
$table->unsignedBigInteger('categoria_id')->nullable();
});
Schema::create('catalog_items', function (Blueprint $table): void {
$table->id();
$table->unsignedBigInteger('category_id');
$table->string('tenant_code');
$table->softDeletes();
});
Schema::create('category_scanners', function (Blueprint $table): void {
$table->unsignedBigInteger('user_id');
$table->unsignedBigInteger('categoria_id');
$table->timestamps();
});
Schema::create('personal_access_tokens', function (Blueprint $table): void {
$table->id();
$table->string('tokenable_type');
$table->unsignedBigInteger('tokenable_id');
});
DB::table('tenants')->insert(['codigo' => 'onticket']);
foreach (['adminapp', 'scanner'] as $role) {
DB::table('roles')->insert(['codigo' => $role, 'nombre' => $role]);
foreach ([10, 20, null] as $eventId) {
$this->insertUser($role, 'onticket', $eventId);
}
$this->insertUser($role, 'other', 10);
}
Sanctum::actingAs(User::query()->findOrFail(1));
}
public function test_lists_and_searches_are_restricted_to_the_authenticated_event(): void
{
foreach (['administrators' => 1, 'staff' => 5] as $path => $id) {
foreach (['', '?search=Persona&event_id=20'] as $query) {
$this->getJson("/api/v1/adminapp/tenant/{$path}{$query}")
->assertOk()->assertJsonCount(1, 'data')
->assertJsonPath('data.0.id', $id)->assertJsonPath('data.0.event_id', 10);
}
}
}
public function test_creation_inherits_the_actor_event_even_if_the_client_supplies_another(): void
{
$this->mock(ResetPasswordAttemptService::class, function (MockInterface $mock): void {
$mock->shouldReceive('createForAdminAppEmail')->once();
$mock->shouldReceive('createForScannerEmail')->once();
});
foreach (['administrators' => 'adminapp', 'staff' => 'scanner'] as $path => $role) {
$this->postJson("/api/v1/adminapp/tenant/{$path}", [
...$this->payload("new-{$role}@example.com"), 'event_id' => 20,
])->assertSuccessful()->assertJsonPath('data.event_id', 10);
$this->assertDatabaseHas('users', ['email' => "new-{$role}@example.com", 'event_id' => 10, 'rol_codigo' => $role]);
}
}
public function test_foreign_and_unassigned_staff_cannot_be_edited_deleted_or_inspected(): void
{
foreach (['administrators' => [2, 3, 4], 'staff' => [6, 7, 8]] as $path => $ids) {
foreach ($ids as $id) {
$this->putJson("/api/v1/adminapp/tenant/{$path}/{$id}", $this->payload("update-{$id}@example.com"))->assertNotFound();
$this->deleteJson("/api/v1/adminapp/tenant/{$path}/{$id}")->assertNotFound();
$this->assertDatabaseHas('users', ['id' => $id, 'deleted_at' => null, 'email' => "person-{$id}@example.com"]);
if ($path === 'staff') {
$this->getJson("/api/v1/adminapp/tenant/staff/{$id}/scan-attempts")->assertNotFound();
}
}
}
}
public function test_own_staff_can_be_edited_and_deleted_without_changing_its_event(): void
{
$adminId = $this->insertUser('adminapp', 'onticket', 10);
foreach (['administrators' => $adminId, 'staff' => 5] as $path => $id) {
$this->putJson("/api/v1/adminapp/tenant/{$path}/{$id}", [
...$this->payload("updated-{$id}@example.com"), 'event_id' => 20,
])->assertOk()->assertJsonPath('data.event_id', 10);
$this->deleteJson("/api/v1/adminapp/tenant/{$path}/{$id}")->assertNoContent();
$this->assertSoftDeleted('users', ['id' => $id]);
}
}
public function test_unscoped_actor_keeps_tenant_lists_and_creates_without_an_event(): void
{
Sanctum::actingAs(User::query()->findOrFail(3));
$this->mock(ResetPasswordAttemptService::class, function (MockInterface $mock): void {
$mock->shouldReceive('createForAdminAppEmail')->once();
$mock->shouldReceive('createForScannerEmail')->once();
});
foreach (['administrators', 'staff'] as $path) {
$this->getJson("/api/v1/adminapp/tenant/{$path}")->assertOk()->assertJsonCount(3, 'data');
$this->postJson("/api/v1/adminapp/tenant/{$path}", $this->payload("legacy-{$path}@example.com"))
->assertSuccessful()->assertJsonPath('data.event_id', null);
}
}
private function insertUser(string $role, string $tenant, ?int $eventId): int
{
$id = DB::table('users')->count() + 1;
return DB::table('users')->insertGetId([
'id' => $id, 'rol_codigo' => $role, 'tenant_codigo' => $tenant,
'event_id' => $eventId, 'nombre_apellido' => 'Persona', 'dni' => '12345678',
'email' => "person-{$id}@example.com", 'active_email' => "person-{$id}@example.com",
]);
}
private function payload(string $email): array
{
return ['nombre_apellido' => 'Persona editada', 'dni' => '87654321', 'email' => $email];
}
}

View File

@@ -0,0 +1,178 @@
<?php
namespace Tests\Feature\Ticket;
use App\Domains\Core\Auth\Models\User;
use App\Domains\Ticketing\Ticket\Services\AdminAppTicketExcelService;
use App\Domains\Ticketing\Ticket\Services\AdminAppTicketPdfService;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Laravel\Sanctum\Sanctum;
use Mockery\MockInterface;
use Symfony\Component\HttpFoundation\StreamedResponse;
use Tests\TestCase;
class AdminAppTicketEventScopeTest extends TestCase
{
protected function setUp(): void
{
parent::setUp();
// Keep HTTP tests isolated from legacy migrations incompatible with SQLite.
Schema::create('tenants', function (Blueprint $table): void {
$table->id();
$table->string('codigo');
$table->string('timezone')->default('UTC');
$table->boolean('allow_ticket_refund')->default(false);
$table->boolean('allow_ticket_total_refund')->default(false);
$table->boolean('allow_ticket_partial_refund')->default(false);
});
Schema::create('menues', function (Blueprint $table): void {
$table->id();
$table->string('code');
});
Schema::create('tenants_menues', function (Blueprint $table): void {
$table->string('tenant_code');
$table->string('menu_code');
});
Schema::create('users', function (Blueprint $table): void {
$table->id();
$table->string('nombre_apellido');
$table->softDeletes();
});
Schema::create('tickets', function (Blueprint $table): void {
$table->id();
$table->string('tenant_code');
$table->unsignedBigInteger('event_id')->nullable();
$table->string('ticket');
foreach (['source_variant_id', 'source_catalog_item_id', 'source_purchase_item_id', 'scanner_user_id', 'user_id'] as $column) {
$table->unsignedBigInteger($column)->nullable();
}
foreach (['used_at', 'disabled_at', 'cancelled_at', 'refunded_at'] as $column) {
$table->timestamp($column)->nullable();
}
$table->timestamps();
});
Schema::create('compras', function (Blueprint $table): void {
$table->id();
$table->string('tenant_codigo');
$table->unsignedBigInteger('event_id')->nullable();
$table->string('nombre_apellido');
});
Schema::create('compra_items', function (Blueprint $table): void {
$table->id();
$table->unsignedBigInteger('compra_id');
$table->decimal('precio_unitario', 12, 2);
});
Schema::create('ticket_refunds', function (Blueprint $table): void {
$table->id();
$table->unsignedBigInteger('ticket_id')->nullable();
$table->unsignedBigInteger('purchase_item_id');
$table->decimal('amount', 12, 2);
});
Schema::create('desfile_entry_reservations', function (Blueprint $table): void {
$table->id();
$table->unsignedBigInteger('ticket_id');
$table->softDeletes();
});
Schema::create('value_changes', function (Blueprint $table): void {
$table->id();
$table->string('tenant_code');
$table->string('trackable_type');
$table->unsignedBigInteger('trackable_id');
$table->string('attribute');
$table->string('old_value')->nullable();
$table->string('new_value')->nullable();
$table->timestamp('changed_at');
$table->string('actor_type');
$table->unsignedBigInteger('user_id')->nullable();
});
DB::table('tenants')->insert(['codigo' => 'onticket']);
DB::table('menues')->insert(['code' => 'adminapp.tickets']);
DB::table('tenants_menues')->insert(['tenant_code' => 'onticket', 'menu_code' => 'adminapp.tickets']);
foreach ([1 => ['onticket', 10], 2 => ['onticket', 20], 3 => ['onticket', null], 4 => ['other', 10]] as $id => [$tenant, $event]) {
DB::table('tickets')->insert([
'id' => $id, 'tenant_code' => $tenant, 'event_id' => $event,
'ticket' => "ticket-{$id}", 'used_at' => now(),
]);
DB::table('compras')->insert(['id' => $id, 'tenant_codigo' => $tenant, 'event_id' => $event, 'nombre_apellido' => 'Cliente']);
DB::table('compra_items')->insert(['id' => $id, 'compra_id' => $id, 'precio_unitario' => 100]);
DB::table('ticket_refunds')->insert(['purchase_item_id' => $id, 'amount' => $id * 10]);
}
$this->actingAsAdmin(10);
}
public function test_list_counts_refunded_total_and_search_cannot_escape_the_user_event(): void
{
$this->getJson('/api/v1/adminapp/tenant/tickets?sort_by=id&event_id=20')
->assertOk()->assertJsonCount(1, 'data')->assertJsonPath('data.0.id', 1)
->assertJsonPath('scanned_tickets', 1)->assertJsonPath('total_tickets', 1)
->assertJsonPath('refunded_total', '10.00');
$this->getJson('/api/v1/adminapp/tenant/tickets?q=2')->assertOk()->assertJsonCount(0, 'data');
// Status uses sorting in memory rather than the database.
$this->getJson('/api/v1/adminapp/tenant/tickets?sort_by=status')
->assertOk()->assertJsonCount(1, 'data')->assertJsonPath('data.0.id', 1);
DB::table('tickets')->where('id', 1)->update(['used_at' => null]);
$this->getJson('/api/v1/adminapp/tenant/tickets?status=active')
->assertOk()->assertJsonCount(1, 'data')
->assertJsonPath('scanned_tickets', 0)->assertJsonPath('total_tickets', 1);
}
public function test_foreign_unassigned_and_other_tenant_tickets_cannot_be_modified_or_refunded(): void
{
foreach ([2, 3, 4] as $id) {
$this->postJson("/api/v1/adminapp/tenant/tickets/{$id}/cancel", ['event_id' => 20])->assertNotFound();
$this->getJson("/api/v1/adminapp/tenant/tickets/{$id}/refund")->assertNotFound();
$this->postJson("/api/v1/adminapp/tenant/tickets/{$id}/refund", ['refund_type' => 'total', 'event_id' => 20])->assertNotFound();
$this->assertDatabaseHas('tickets', ['id' => $id, 'cancelled_at' => null, 'refunded_at' => null]);
}
$this->assertDatabaseCount('value_changes', 0);
$this->assertDatabaseCount('ticket_refunds', 4);
}
public function test_own_ticket_can_be_cancelled_and_refund_requests_reach_business_validation(): void
{
DB::table('tickets')->where('id', 1)->update(['used_at' => null]);
$this->getJson('/api/v1/adminapp/tenant/tickets/1/refund')->assertUnprocessable();
$this->postJson('/api/v1/adminapp/tenant/tickets/1/refund', ['refund_type' => 'total'])->assertUnprocessable();
$this->postJson('/api/v1/adminapp/tenant/tickets/1/cancel')->assertOk();
$this->assertNotNull(DB::table('tickets')->where('id', 1)->value('cancelled_at'));
}
public function test_unscoped_admin_keeps_the_tenant_scope(): void
{
$this->actingAsAdmin(null);
$this->getJson('/api/v1/adminapp/tenant/tickets?sort_by=id')
->assertOk()->assertJsonCount(3, 'data')->assertJsonPath('total_tickets', 3)
->assertJsonPath('refunded_total', '60.00');
DB::table('tickets')->where('id', 3)->update(['used_at' => null]);
$this->postJson('/api/v1/adminapp/tenant/tickets/3/cancel')->assertOk();
$this->postJson('/api/v1/adminapp/tenant/tickets/4/cancel')->assertNotFound();
}
public function test_pdf_and_excel_receive_only_the_tickets_of_the_user_event(): void
{
foreach ([AdminAppTicketPdfService::class, AdminAppTicketExcelService::class] as $class) {
$this->mock($class, function (MockInterface $mock) use ($class): void {
$mock->shouldReceive('download')->once()->withArgs(
fn ($tenant, Collection $tickets, $timezone): bool => $tenant->codigo === 'onticket'
&& $tickets->pluck('id')->all() === [1] && $timezone === 'UTC'
)->andReturn($class === AdminAppTicketPdfService::class
? response('pdf') : new StreamedResponse(fn () => print ('excel')));
});
}
foreach (['pdf', 'excel'] as $format) {
$this->getJson("/api/v1/adminapp/tenant/tickets/{$format}?timezone=UTC&event_id=20")->assertOk();
}
}
private function actingAsAdmin(?int $eventId): void
{
$user = new User;
$user->setRawAttributes(['id' => 1, 'rol_codigo' => 'adminapp', 'tenant_codigo' => 'onticket', 'event_id' => $eventId]);
Sanctum::actingAs($user);
}
}