Compare commits
15 Commits
e0f0fb1a72
...
a12b3dd0c8
| Author | SHA1 | Date | |
|---|---|---|---|
| a12b3dd0c8 | |||
| 1b22989252 | |||
| 8e94cf7856 | |||
| 5b089e71b2 | |||
| 45d74e166f | |||
| f50d3d0587 | |||
| 36c1c185ee | |||
| 0fae1ca1d7 | |||
| 1d7c484510 | |||
| cb98652e2f | |||
| 622a3eef86 | |||
| 498b4d9eac | |||
| 7d9489169d | |||
| 3eaa3f8202 | |||
| 254faedf2c |
42
app/Domains/Auth/Controllers/ScannerLoginController.php
Normal file
@@ -0,0 +1,42 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Auth\Controllers;
|
||||||
|
|
||||||
|
use App\Domains\Auth\Requests\ScannerLoginRequest;
|
||||||
|
use App\Domains\Auth\Resources\UserResource;
|
||||||
|
use App\Domains\Auth\Services\PasswordLoginService;
|
||||||
|
use App\Http\Controllers\Controller;
|
||||||
|
use Illuminate\Http\JsonResponse;
|
||||||
|
|
||||||
|
class ScannerLoginController extends Controller
|
||||||
|
{
|
||||||
|
public function __construct(
|
||||||
|
private readonly PasswordLoginService $passwordLoginService,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
public function __invoke(ScannerLoginRequest $request): JsonResponse
|
||||||
|
{
|
||||||
|
$credentials = $request->validated();
|
||||||
|
$user = $this->passwordLoginService->authenticateScanner(
|
||||||
|
$credentials['email'],
|
||||||
|
$credentials['password'],
|
||||||
|
$request->ip(),
|
||||||
|
$request->userAgent(),
|
||||||
|
);
|
||||||
|
|
||||||
|
$expirationMinutes = (int) config('sanctum.expiration');
|
||||||
|
$token = $user->createToken(
|
||||||
|
'scanner-token',
|
||||||
|
['scanner'],
|
||||||
|
now()->addMinutes($expirationMinutes),
|
||||||
|
)->plainTextToken;
|
||||||
|
|
||||||
|
return response()->json([
|
||||||
|
'code' => 'auth.login_success',
|
||||||
|
'message' => __('api.auth.login_success'),
|
||||||
|
'token' => $token,
|
||||||
|
'token_type' => 'Bearer',
|
||||||
|
'user' => UserResource::make($user),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
}
|
||||||
24
app/Domains/Auth/Controllers/ScannerMeController.php
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Auth\Controllers;
|
||||||
|
|
||||||
|
use App\Domains\Auth\Models\User;
|
||||||
|
use App\Domains\Auth\Resources\ScannerMeResource;
|
||||||
|
use App\Domains\Auth\Services\ScannerContextService;
|
||||||
|
use App\Http\Controllers\Controller;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
|
||||||
|
class ScannerMeController extends Controller
|
||||||
|
{
|
||||||
|
public function __construct(
|
||||||
|
private readonly ScannerContextService $scannerContextService,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
public function __invoke(Request $request): ScannerMeResource
|
||||||
|
{
|
||||||
|
/** @var User $user */
|
||||||
|
$user = $request->user();
|
||||||
|
|
||||||
|
return ScannerMeResource::make($this->scannerContextService->load($user));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -53,6 +53,16 @@ class User extends Authenticatable
|
|||||||
return $this->belongsTo(Role::class, 'rol_codigo', 'codigo');
|
return $this->belongsTo(Role::class, 'rol_codigo', 'codigo');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function hasPermission(string $permissionCode): bool
|
||||||
|
{
|
||||||
|
return $this->role()
|
||||||
|
->whereHas(
|
||||||
|
'permissions',
|
||||||
|
fn ($query) => $query->where('permisos.codigo', $permissionCode)
|
||||||
|
)
|
||||||
|
->exists();
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @return BelongsTo<Tenant, $this>
|
* @return BelongsTo<Tenant, $this>
|
||||||
*/
|
*/
|
||||||
|
|||||||
5
app/Domains/Auth/Requests/ScannerLoginRequest.php
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Auth\Requests;
|
||||||
|
|
||||||
|
class ScannerLoginRequest extends AdminAppLoginRequest {}
|
||||||
21
app/Domains/Auth/Resources/ScannerMeResource.php
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Auth\Resources;
|
||||||
|
|
||||||
|
use App\Domains\Auth\Models\User;
|
||||||
|
use App\Domains\Tenant\Resources\TenantResource;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Illuminate\Http\Resources\Json\JsonResource;
|
||||||
|
|
||||||
|
/** @mixin User */
|
||||||
|
class ScannerMeResource extends JsonResource
|
||||||
|
{
|
||||||
|
/** @return array<string, mixed> */
|
||||||
|
public function toArray(Request $request): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'user' => UserResource::make($this->resource),
|
||||||
|
'tenant' => TenantResource::make($this->tenant),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -5,6 +5,7 @@ namespace App\Domains\Auth\Services;
|
|||||||
use App\Domains\Auth\Exceptions\AccountLockedException;
|
use App\Domains\Auth\Exceptions\AccountLockedException;
|
||||||
use App\Domains\Auth\Models\LoginAttempt;
|
use App\Domains\Auth\Models\LoginAttempt;
|
||||||
use App\Domains\Auth\Models\User;
|
use App\Domains\Auth\Models\User;
|
||||||
|
use App\Domains\Authorization\Enums\PermissionCode;
|
||||||
use App\Domains\Authorization\Enums\RoleCode;
|
use App\Domains\Authorization\Enums\RoleCode;
|
||||||
use Carbon\CarbonImmutable;
|
use Carbon\CarbonImmutable;
|
||||||
use Illuminate\Support\Facades\DB;
|
use Illuminate\Support\Facades\DB;
|
||||||
@@ -62,14 +63,39 @@ class PasswordLoginService
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Authenticate a tenant-bound user authorized to scan tickets.
|
||||||
|
*
|
||||||
|
* @throws AccountLockedException
|
||||||
|
* @throws ValidationException
|
||||||
|
*/
|
||||||
|
public function authenticateScanner(
|
||||||
|
string $email,
|
||||||
|
string $password,
|
||||||
|
?string $ipAddress,
|
||||||
|
?string $userAgent,
|
||||||
|
): User {
|
||||||
|
return $this->authenticateUser(
|
||||||
|
$email,
|
||||||
|
$password,
|
||||||
|
null,
|
||||||
|
$ipAddress,
|
||||||
|
$userAgent,
|
||||||
|
null,
|
||||||
|
true,
|
||||||
|
PermissionCode::ScanTickets->value,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
private function authenticateUser(
|
private function authenticateUser(
|
||||||
string $email,
|
string $email,
|
||||||
string $password,
|
string $password,
|
||||||
?string $tenantCode,
|
?string $tenantCode,
|
||||||
?string $ipAddress,
|
?string $ipAddress,
|
||||||
?string $userAgent,
|
?string $userAgent,
|
||||||
RoleCode $requiredRole = RoleCode::User,
|
?RoleCode $requiredRole = RoleCode::User,
|
||||||
bool $requiresTenant = false,
|
bool $requiresTenant = false,
|
||||||
|
?string $requiredPermission = null,
|
||||||
): User {
|
): User {
|
||||||
$normalizedEmail = mb_strtolower(trim($email));
|
$normalizedEmail = mb_strtolower(trim($email));
|
||||||
$now = CarbonImmutable::now();
|
$now = CarbonImmutable::now();
|
||||||
@@ -84,10 +110,21 @@ class PasswordLoginService
|
|||||||
$now,
|
$now,
|
||||||
$requiredRole,
|
$requiredRole,
|
||||||
$requiresTenant,
|
$requiresTenant,
|
||||||
|
$requiredPermission,
|
||||||
): array {
|
): array {
|
||||||
$user = User::query()
|
$user = User::query()
|
||||||
->where('email', $normalizedEmail)
|
->where('email', $normalizedEmail)
|
||||||
->where('rol_codigo', $requiredRole->value)
|
->when(
|
||||||
|
$requiredRole !== null,
|
||||||
|
fn ($query) => $query->where('rol_codigo', $requiredRole->value),
|
||||||
|
)
|
||||||
|
->when(
|
||||||
|
$requiredPermission !== null,
|
||||||
|
fn ($query) => $query->whereHas(
|
||||||
|
'role.permissions',
|
||||||
|
fn ($query) => $query->where('permisos.codigo', $requiredPermission)
|
||||||
|
),
|
||||||
|
)
|
||||||
->when(
|
->when(
|
||||||
$requiresTenant,
|
$requiresTenant,
|
||||||
fn ($query) => $query->whereNotNull('tenant_codigo'),
|
fn ($query) => $query->whereNotNull('tenant_codigo'),
|
||||||
@@ -122,8 +159,8 @@ class PasswordLoginService
|
|||||||
}
|
}
|
||||||
|
|
||||||
if ($user === null || ! Hash::check($password, $user->password)) {
|
if ($user === null || ! Hash::check($password, $user->password)) {
|
||||||
if ($user !== null) {
|
if ($user !== null && $attemptTenantCode !== null) {
|
||||||
$this->registerFailure($user, $now, $tenantCode);
|
$this->registerFailure($user, $now, $attemptTenantCode);
|
||||||
}
|
}
|
||||||
|
|
||||||
$outcome = $user?->locked_until?->isFuture()
|
$outcome = $user?->locked_until?->isFuture()
|
||||||
@@ -210,7 +247,7 @@ class PasswordLoginService
|
|||||||
} catch (\Throwable $e) {
|
} catch (\Throwable $e) {
|
||||||
Log::error('Failed to trigger reset password on account lock', [
|
Log::error('Failed to trigger reset password on account lock', [
|
||||||
'user_id' => $user->id,
|
'user_id' => $user->id,
|
||||||
'exception' => $e
|
'exception' => $e,
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
24
app/Domains/Auth/Services/ScannerContextService.php
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Auth\Services;
|
||||||
|
|
||||||
|
use App\Domains\Auth\Models\User;
|
||||||
|
|
||||||
|
class ScannerContextService
|
||||||
|
{
|
||||||
|
public function load(User $user): User
|
||||||
|
{
|
||||||
|
$tenant = $user->tenant()
|
||||||
|
->with([
|
||||||
|
'menues' => fn ($query) => $query->whereHas(
|
||||||
|
'roles',
|
||||||
|
fn ($query) => $query->where('codigo', $user->rol_codigo)
|
||||||
|
),
|
||||||
|
])
|
||||||
|
->firstOrFail();
|
||||||
|
|
||||||
|
$user->setRelation('tenant', $tenant);
|
||||||
|
|
||||||
|
return $user;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -25,3 +25,4 @@ Route::middleware('auth:sanctum')->get('/me', MeController::class);
|
|||||||
Route::middleware('auth:sanctum')->put('/me', UpdateProfileController::class);
|
Route::middleware('auth:sanctum')->put('/me', UpdateProfileController::class);
|
||||||
|
|
||||||
require __DIR__.'/adminapp.php';
|
require __DIR__.'/adminapp.php';
|
||||||
|
require __DIR__.'/scanner.php';
|
||||||
|
|||||||
11
app/Domains/Auth/routes/scanner.php
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use App\Domains\Auth\Controllers\ScannerLoginController;
|
||||||
|
use App\Domains\Auth\Controllers\ScannerMeController;
|
||||||
|
use Illuminate\Support\Facades\Route;
|
||||||
|
|
||||||
|
Route::prefix('v1/scanner')->group(function (): void {
|
||||||
|
Route::post('login', ScannerLoginController::class)->middleware('throttle:login');
|
||||||
|
Route::middleware(['auth:sanctum', 'scanner.tenant'])
|
||||||
|
->get('me', ScannerMeController::class);
|
||||||
|
});
|
||||||
8
app/Domains/Authorization/Enums/PermissionCode.php
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Authorization\Enums;
|
||||||
|
|
||||||
|
enum PermissionCode: string
|
||||||
|
{
|
||||||
|
case ScanTickets = 'tickets.escanear';
|
||||||
|
}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Bootstrap\Controllers;
|
||||||
|
|
||||||
|
use App\Domains\Bootstrap\Requests\ScannerBootstrapRequest;
|
||||||
|
use App\Domains\Bootstrap\Resources\ScannerBootstrapResource;
|
||||||
|
use App\Domains\Bootstrap\Services\ScannerBootstrapService;
|
||||||
|
use App\Http\Controllers\Controller;
|
||||||
|
|
||||||
|
class ScannerBootstrapController extends Controller
|
||||||
|
{
|
||||||
|
public function __construct(protected ScannerBootstrapService $bootstrapService) {}
|
||||||
|
|
||||||
|
public function __invoke(ScannerBootstrapRequest $request): ScannerBootstrapResource
|
||||||
|
{
|
||||||
|
return ScannerBootstrapResource::make(
|
||||||
|
$this->bootstrapService->get((string) $request->validated('dominio'))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Bootstrap\Requests;
|
||||||
|
|
||||||
|
class ScannerBootstrapRequest extends TenantBootstrapRequest {}
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Bootstrap\Resources;
|
||||||
|
|
||||||
|
class ScannerBootstrapResource extends AdminAppBootstrapResource {}
|
||||||
19
app/Domains/Bootstrap/Services/ScannerBootstrapService.php
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Bootstrap\Services;
|
||||||
|
|
||||||
|
use App\Domains\Tenant\Models\WebsiteType;
|
||||||
|
|
||||||
|
class ScannerBootstrapService
|
||||||
|
{
|
||||||
|
/** @return array{website_type: WebsiteType} */
|
||||||
|
public function get(string $domain): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'website_type' => WebsiteType::query()
|
||||||
|
->with(['siteLogo', 'footerLogo'])
|
||||||
|
->where('scanner_domain', $domain)
|
||||||
|
->firstOrFail(),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -7,3 +7,4 @@ Route::get('tenants/bootstrap/{dominio}', TenantBootstrapController::class)
|
|||||||
->where('dominio', '.*');
|
->where('dominio', '.*');
|
||||||
|
|
||||||
require __DIR__.'/adminapp.php';
|
require __DIR__.'/adminapp.php';
|
||||||
|
require __DIR__.'/scanner.php';
|
||||||
|
|||||||
9
app/Domains/Bootstrap/routes/scanner.php
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use App\Domains\Bootstrap\Controllers\ScannerBootstrapController;
|
||||||
|
use Illuminate\Support\Facades\Route;
|
||||||
|
|
||||||
|
Route::get(
|
||||||
|
'v1/scanner/bootstrap/{dominio}',
|
||||||
|
ScannerBootstrapController::class
|
||||||
|
);
|
||||||
@@ -8,6 +8,7 @@ enum GroupLayout: string
|
|||||||
case Simple = 'simple';
|
case Simple = 'simple';
|
||||||
case SimpleVertical = 'simple_vertical';
|
case SimpleVertical = 'simple_vertical';
|
||||||
case Carousel = 'carousel';
|
case Carousel = 'carousel';
|
||||||
|
case Single = 'single';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @return list<string>
|
* @return list<string>
|
||||||
|
|||||||
16
app/Domains/Catalog/Enums/InventorySubject.php
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Catalog\Enums;
|
||||||
|
|
||||||
|
enum InventorySubject: string
|
||||||
|
{
|
||||||
|
case Product = 'product';
|
||||||
|
case Seat = 'seat';
|
||||||
|
case Ticket = 'ticket';
|
||||||
|
|
||||||
|
/** @return array<int, string> */
|
||||||
|
public static function values(): array
|
||||||
|
{
|
||||||
|
return array_column(self::cases(), 'value');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -7,6 +7,7 @@ enum ProductLayout: string
|
|||||||
case Row = 'row';
|
case Row = 'row';
|
||||||
case ColumnWithImage = 'column_with_image';
|
case ColumnWithImage = 'column_with_image';
|
||||||
case ColumnWithCart = 'column_with_cart';
|
case ColumnWithCart = 'column_with_cart';
|
||||||
|
case TicketSelector = 'ticket_selector';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @return list<string>
|
* @return list<string>
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ namespace App\Domains\Catalog\Models;
|
|||||||
use App\Domains\Attachable\Models\Attachment;
|
use App\Domains\Attachable\Models\Attachment;
|
||||||
use App\Domains\Catalog\Enums\CatalogItemType;
|
use App\Domains\Catalog\Enums\CatalogItemType;
|
||||||
use App\Domains\Catalog\Enums\InventoryPolicy;
|
use App\Domains\Catalog\Enums\InventoryPolicy;
|
||||||
|
use App\Domains\Catalog\Enums\InventorySubject;
|
||||||
use App\Domains\Catalog\Services\CatalogInventoryService;
|
use App\Domains\Catalog\Services\CatalogInventoryService;
|
||||||
use App\Domains\Tenant\Models\Tenant;
|
use App\Domains\Tenant\Models\Tenant;
|
||||||
use App\Domains\Ticket\Enums\TicketGenerationPolicy;
|
use App\Domains\Ticket\Enums\TicketGenerationPolicy;
|
||||||
@@ -30,6 +31,7 @@ use Illuminate\Support\Collection;
|
|||||||
'descripcion',
|
'descripcion',
|
||||||
'precio',
|
'precio',
|
||||||
'inventory_policy',
|
'inventory_policy',
|
||||||
|
'inventory_subject',
|
||||||
'max_units_per_user',
|
'max_units_per_user',
|
||||||
'has_tickets',
|
'has_tickets',
|
||||||
'ticket_generation_policy',
|
'ticket_generation_policy',
|
||||||
@@ -46,6 +48,7 @@ class CatalogItem extends Model
|
|||||||
protected $attributes = [
|
protected $attributes = [
|
||||||
'type' => CatalogItemType::Standard->value,
|
'type' => CatalogItemType::Standard->value,
|
||||||
'inventory_policy' => InventoryPolicy::Tracked->value,
|
'inventory_policy' => InventoryPolicy::Tracked->value,
|
||||||
|
'inventory_subject' => InventorySubject::Product->value,
|
||||||
'has_tickets' => false,
|
'has_tickets' => false,
|
||||||
'ticket_generation_policy' => TicketGenerationPolicy::PerEventDate->value,
|
'ticket_generation_policy' => TicketGenerationPolicy::PerEventDate->value,
|
||||||
];
|
];
|
||||||
@@ -59,6 +62,7 @@ class CatalogItem extends Model
|
|||||||
'type' => CatalogItemType::class,
|
'type' => CatalogItemType::class,
|
||||||
'precio' => 'decimal:2',
|
'precio' => 'decimal:2',
|
||||||
'inventory_policy' => InventoryPolicy::class,
|
'inventory_policy' => InventoryPolicy::class,
|
||||||
|
'inventory_subject' => InventorySubject::class,
|
||||||
'max_units_per_user' => 'integer',
|
'max_units_per_user' => 'integer',
|
||||||
'has_tickets' => 'boolean',
|
'has_tickets' => 'boolean',
|
||||||
'ticket_generation_policy' => TicketGenerationPolicy::class,
|
'ticket_generation_policy' => TicketGenerationPolicy::class,
|
||||||
@@ -208,6 +212,11 @@ class CatalogItem extends Model
|
|||||||
return $this->nombre;
|
return $this->nombre;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function getSelectionLabel(): string
|
||||||
|
{
|
||||||
|
return $this->getName();
|
||||||
|
}
|
||||||
|
|
||||||
public function getDescription(): ?string
|
public function getDescription(): ?string
|
||||||
{
|
{
|
||||||
return $this->descripcion;
|
return $this->descripcion;
|
||||||
|
|||||||
@@ -12,6 +12,8 @@ use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
|||||||
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
|
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
|
||||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||||
use Illuminate\Support\Collection;
|
use Illuminate\Support\Collection;
|
||||||
|
use Illuminate\Support\Facades\Lang;
|
||||||
|
use Illuminate\Support\Str;
|
||||||
|
|
||||||
#[Fillable([
|
#[Fillable([
|
||||||
'catalog_item_id',
|
'catalog_item_id',
|
||||||
@@ -113,6 +115,42 @@ class Variant extends Model
|
|||||||
return $this->catalogItem->nombre;
|
return $this->catalogItem->nombre;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function getSelectionLabel(): string
|
||||||
|
{
|
||||||
|
$this->loadMissing([
|
||||||
|
'catalogItem.itemAttributes.attribute.options',
|
||||||
|
'definitions.itemAttribute.attribute.options',
|
||||||
|
'eventDates',
|
||||||
|
'eventDate',
|
||||||
|
]);
|
||||||
|
|
||||||
|
$itemAttributes = $this->catalogItem->itemAttributes;
|
||||||
|
|
||||||
|
$label = $this->selectionOptions($itemAttributes)
|
||||||
|
->map(function (array $option, string $attributeCode) use ($itemAttributes): ?string {
|
||||||
|
$itemAttribute = $itemAttributes->first(
|
||||||
|
fn (ItemAttribute $candidate): bool => $candidate->attribute?->codigo === $attributeCode,
|
||||||
|
);
|
||||||
|
$translationKey = "api.catalog.attribute_labels.{$attributeCode}";
|
||||||
|
$attributeName = Lang::has($translationKey)
|
||||||
|
? __($translationKey)
|
||||||
|
: ($itemAttribute?->attribute?->nombre ?? Str::headline($attributeCode));
|
||||||
|
$selectedOptions = array_is_list($option) ? $option : [$option];
|
||||||
|
$selectedLabels = collect($selectedOptions)
|
||||||
|
->pluck('label')
|
||||||
|
->filter()
|
||||||
|
->implode(', ');
|
||||||
|
|
||||||
|
return $selectedLabels === ''
|
||||||
|
? null
|
||||||
|
: "{$attributeName} {$selectedLabels}";
|
||||||
|
})
|
||||||
|
->filter()
|
||||||
|
->implode(' · ');
|
||||||
|
|
||||||
|
return $label !== '' ? $label : $this->getName();
|
||||||
|
}
|
||||||
|
|
||||||
/** @return Collection<string, string|array<int, string>> */
|
/** @return Collection<string, string|array<int, string>> */
|
||||||
public function selectionValues(): Collection
|
public function selectionValues(): Collection
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ namespace App\Domains\Catalog\Requests;
|
|||||||
|
|
||||||
use App\Domains\Catalog\Enums\CatalogItemType;
|
use App\Domains\Catalog\Enums\CatalogItemType;
|
||||||
use App\Domains\Catalog\Enums\InventoryPolicy;
|
use App\Domains\Catalog\Enums\InventoryPolicy;
|
||||||
|
use App\Domains\Catalog\Enums\InventorySubject;
|
||||||
use App\Domains\Shared\Rules\ImageOrBase64Rule;
|
use App\Domains\Shared\Rules\ImageOrBase64Rule;
|
||||||
use App\Domains\Ticket\Enums\TicketGenerationPolicy;
|
use App\Domains\Ticket\Enums\TicketGenerationPolicy;
|
||||||
use Illuminate\Foundation\Http\FormRequest;
|
use Illuminate\Foundation\Http\FormRequest;
|
||||||
@@ -54,6 +55,7 @@ class StoreCatalogItemRequest extends FormRequest
|
|||||||
'descripcion' => ['sometimes', 'nullable', 'string'],
|
'descripcion' => ['sometimes', 'nullable', 'string'],
|
||||||
'precio' => ['required', 'numeric', 'min:0'],
|
'precio' => ['required', 'numeric', 'min:0'],
|
||||||
'inventory_policy' => [Rule::prohibitedIf($isBundle), 'sometimes', Rule::enum(InventoryPolicy::class)],
|
'inventory_policy' => [Rule::prohibitedIf($isBundle), 'sometimes', Rule::enum(InventoryPolicy::class)],
|
||||||
|
'inventory_subject' => ['sometimes', Rule::enum(InventorySubject::class)],
|
||||||
'max_units_per_user' => ['sometimes', 'nullable', 'integer', 'min:1'],
|
'max_units_per_user' => ['sometimes', 'nullable', 'integer', 'min:1'],
|
||||||
'has_tickets' => [Rule::prohibitedIf($isBundle), 'sometimes', 'boolean'],
|
'has_tickets' => [Rule::prohibitedIf($isBundle), 'sometimes', 'boolean'],
|
||||||
'ticket_generation_policy' => [Rule::prohibitedIf($isBundle), 'sometimes', Rule::enum(TicketGenerationPolicy::class)],
|
'ticket_generation_policy' => [Rule::prohibitedIf($isBundle), 'sometimes', Rule::enum(TicketGenerationPolicy::class)],
|
||||||
|
|||||||
@@ -25,7 +25,7 @@ class CatalogFeaturedItemResource extends JsonResource
|
|||||||
return $this->columnWithImageData($catalogItem);
|
return $this->columnWithImageData($catalogItem);
|
||||||
}
|
}
|
||||||
|
|
||||||
return [
|
$data = [
|
||||||
'id' => $catalogItem->id,
|
'id' => $catalogItem->id,
|
||||||
'type' => $catalogItem->type->value,
|
'type' => $catalogItem->type->value,
|
||||||
'nombre' => $catalogItem->nombre,
|
'nombre' => $catalogItem->nombre,
|
||||||
@@ -51,16 +51,17 @@ class CatalogFeaturedItemResource extends JsonResource
|
|||||||
])
|
])
|
||||||
->values(),
|
->values(),
|
||||||
];
|
];
|
||||||
|
|
||||||
|
if ($featuredGroup->product_layout === ProductLayout::TicketSelector) {
|
||||||
|
$data['image'] = $this->firstImageUrl($catalogItem);
|
||||||
|
}
|
||||||
|
|
||||||
|
return $data;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @return array<string, mixed> */
|
/** @return array<string, mixed> */
|
||||||
private function columnWithImageData(CatalogItem $catalogItem): array
|
private function columnWithImageData(CatalogItem $catalogItem): array
|
||||||
{
|
{
|
||||||
$attachment = $catalogItem->attachments->first()
|
|
||||||
?? $catalogItem->variants
|
|
||||||
->flatMap(fn (Variant $variant) => $variant->attachments)
|
|
||||||
->first();
|
|
||||||
|
|
||||||
return [
|
return [
|
||||||
'id' => $catalogItem->id,
|
'id' => $catalogItem->id,
|
||||||
'type' => $catalogItem->type->value,
|
'type' => $catalogItem->type->value,
|
||||||
@@ -69,7 +70,17 @@ class CatalogFeaturedItemResource extends JsonResource
|
|||||||
'ticket_generation_policy' => $catalogItem->ticket_generation_policy->value,
|
'ticket_generation_policy' => $catalogItem->ticket_generation_policy->value,
|
||||||
'validity_time_id' => $catalogItem->validity_time_id,
|
'validity_time_id' => $catalogItem->validity_time_id,
|
||||||
'validity_time' => ValidityTimeResource::make($catalogItem->validityTime),
|
'validity_time' => ValidityTimeResource::make($catalogItem->validityTime),
|
||||||
'image' => $attachment?->getTemporaryUrl(1440),
|
'image' => $this->firstImageUrl($catalogItem),
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private function firstImageUrl(CatalogItem $catalogItem): ?string
|
||||||
|
{
|
||||||
|
$attachment = $catalogItem->attachments->first()
|
||||||
|
?? $catalogItem->variants
|
||||||
|
->flatMap(fn (Variant $variant) => $variant->attachments)
|
||||||
|
->first();
|
||||||
|
|
||||||
|
return $attachment?->getTemporaryUrl(1440);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -33,6 +33,7 @@ class CatalogItemDetailResource extends JsonResource
|
|||||||
'category' => $this->category?->nombre,
|
'category' => $this->category?->nombre,
|
||||||
'brand' => $this->brand?->nombre,
|
'brand' => $this->brand?->nombre,
|
||||||
'inventory_policy' => $this->inventory_policy?->value,
|
'inventory_policy' => $this->inventory_policy?->value,
|
||||||
|
'inventory_subject' => $this->inventory_subject->value,
|
||||||
'max_units_per_user' => $this->max_units_per_user,
|
'max_units_per_user' => $this->max_units_per_user,
|
||||||
'has_tickets' => $this->has_tickets,
|
'has_tickets' => $this->has_tickets,
|
||||||
'ticket_generation_policy' => $this->ticket_generation_policy->value,
|
'ticket_generation_policy' => $this->ticket_generation_policy->value,
|
||||||
|
|||||||
@@ -23,6 +23,7 @@ class CatalogItemResource extends JsonResource
|
|||||||
'descripcion' => $this->descripcion,
|
'descripcion' => $this->descripcion,
|
||||||
'precio' => $this->precio,
|
'precio' => $this->precio,
|
||||||
'inventory_policy' => $this->inventory_policy?->value,
|
'inventory_policy' => $this->inventory_policy?->value,
|
||||||
|
'inventory_subject' => $this->inventory_subject->value,
|
||||||
'max_units_per_user' => $this->max_units_per_user,
|
'max_units_per_user' => $this->max_units_per_user,
|
||||||
'has_tickets' => $this->has_tickets,
|
'has_tickets' => $this->has_tickets,
|
||||||
'ticket_generation_policy' => $this->ticket_generation_policy->value,
|
'ticket_generation_policy' => $this->ticket_generation_policy->value,
|
||||||
|
|||||||
@@ -18,7 +18,13 @@ class FeaturedGroupService
|
|||||||
public function itemsResponse(FeaturedGroup $featuredGroup, int $page): array
|
public function itemsResponse(FeaturedGroup $featuredGroup, int $page): array
|
||||||
{
|
{
|
||||||
if ($featuredGroup->group_layout !== GroupLayout::Paginated) {
|
if ($featuredGroup->group_layout !== GroupLayout::Paginated) {
|
||||||
$items = $this->itemsQuery($featuredGroup)->get();
|
$query = $this->itemsQuery($featuredGroup);
|
||||||
|
|
||||||
|
if ($featuredGroup->group_layout === GroupLayout::Single) {
|
||||||
|
$query->limit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
$items = $query->get();
|
||||||
$this->attachGroup($items, $featuredGroup);
|
$this->attachGroup($items, $featuredGroup);
|
||||||
|
|
||||||
return CatalogFeaturedItemResource::collection($items)->resolve();
|
return CatalogFeaturedItemResource::collection($items)->resolve();
|
||||||
|
|||||||
@@ -0,0 +1,36 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Purchase\Exceptions;
|
||||||
|
|
||||||
|
use RuntimeException;
|
||||||
|
|
||||||
|
class InsufficientStockException extends RuntimeException
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* @param array<int, array{
|
||||||
|
* index: int,
|
||||||
|
* catalog_item_id: int,
|
||||||
|
* variant_id: int|null,
|
||||||
|
* requested_quantity: int,
|
||||||
|
* available_quantity: int,
|
||||||
|
* message: string
|
||||||
|
* }> $unavailableItems
|
||||||
|
*/
|
||||||
|
public function __construct(
|
||||||
|
public readonly array $unavailableItems,
|
||||||
|
) {
|
||||||
|
parent::__construct(
|
||||||
|
collect($unavailableItems)->pluck('message')->unique()->implode(' '),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @return array<string, array<int, string>> */
|
||||||
|
public function errors(): array
|
||||||
|
{
|
||||||
|
return collect($this->unavailableItems)
|
||||||
|
->mapWithKeys(fn (array $item): array => [
|
||||||
|
"direct_items.{$item['index']}.cantidad" => [$item['message']],
|
||||||
|
])
|
||||||
|
->all();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -19,29 +19,21 @@ class StartCheckoutRequest extends FormRequest
|
|||||||
{
|
{
|
||||||
return [
|
return [
|
||||||
'cart_id' => [
|
'cart_id' => [
|
||||||
'required_without:direct_item',
|
'required_without:direct_items',
|
||||||
Rule::prohibitedIf(fn (): bool => $this->has('direct_item')),
|
Rule::prohibitedIf(fn (): bool => $this->has('direct_items')),
|
||||||
'integer',
|
'integer',
|
||||||
'exists:carritos,id',
|
'exists:carritos,id',
|
||||||
],
|
],
|
||||||
'direct_item' => [
|
'direct_items' => [
|
||||||
'required_without:cart_id',
|
'required_without:cart_id',
|
||||||
Rule::prohibitedIf(fn (): bool => $this->has('cart_id')),
|
Rule::prohibitedIf(fn (): bool => $this->has('cart_id')),
|
||||||
'array',
|
'array',
|
||||||
],
|
|
||||||
'direct_item.catalog_item_id' => [
|
|
||||||
'required_with:direct_item',
|
|
||||||
'integer',
|
|
||||||
],
|
|
||||||
'direct_item.variant_id' => [
|
|
||||||
'nullable',
|
|
||||||
'integer',
|
|
||||||
],
|
|
||||||
'direct_item.cantidad' => [
|
|
||||||
'required_with:direct_item',
|
|
||||||
'integer',
|
|
||||||
'min:1',
|
'min:1',
|
||||||
],
|
],
|
||||||
|
'direct_items.*' => ['required', 'array'],
|
||||||
|
'direct_items.*.catalog_item_id' => ['required', 'integer'],
|
||||||
|
'direct_items.*.variant_id' => ['nullable', 'integer'],
|
||||||
|
'direct_items.*.cantidad' => ['required', 'integer', 'min:1'],
|
||||||
'dni' => ['prohibited'],
|
'dni' => ['prohibited'],
|
||||||
'telefono' => ['prohibited'],
|
'telefono' => ['prohibited'],
|
||||||
'nombre_apellido' => ['prohibited'],
|
'nombre_apellido' => ['prohibited'],
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ class CatalogSelectionResolver
|
|||||||
Tenant $tenant,
|
Tenant $tenant,
|
||||||
int $catalogItemId,
|
int $catalogItemId,
|
||||||
?int $variantId,
|
?int $variantId,
|
||||||
|
string $fieldPrefix = 'direct_items',
|
||||||
): CatalogItem|Variant {
|
): CatalogItem|Variant {
|
||||||
/** @var CatalogItem|null $catalogItem */
|
/** @var CatalogItem|null $catalogItem */
|
||||||
$catalogItem = CatalogItem::query()
|
$catalogItem = CatalogItem::query()
|
||||||
@@ -31,13 +32,13 @@ class CatalogSelectionResolver
|
|||||||
if ($catalogItem->isBundle()) {
|
if ($catalogItem->isBundle()) {
|
||||||
if ($variantId !== null) {
|
if ($variantId !== null) {
|
||||||
throw ValidationException::withMessages([
|
throw ValidationException::withMessages([
|
||||||
'direct_item.variant_id' => __('api.cart.bundle_variant_forbidden'),
|
"{$fieldPrefix}.variant_id" => __('api.cart.bundle_variant_forbidden'),
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (! $catalogItem->bundleComponents()->exists()) {
|
if (! $catalogItem->bundleComponents()->exists()) {
|
||||||
throw ValidationException::withMessages([
|
throw ValidationException::withMessages([
|
||||||
'direct_item.catalog_item_id' => __('api.cart.empty_bundle'),
|
"{$fieldPrefix}.catalog_item_id" => __('api.cart.empty_bundle'),
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -47,7 +48,7 @@ class CatalogSelectionResolver
|
|||||||
if ($variantId === null) {
|
if ($variantId === null) {
|
||||||
if ($catalogItem->inventory_id === null) {
|
if ($catalogItem->inventory_id === null) {
|
||||||
throw ValidationException::withMessages([
|
throw ValidationException::withMessages([
|
||||||
'direct_item.variant_id' => __('api.cart.variant_required'),
|
"{$fieldPrefix}.variant_id" => __('api.cart.variant_required'),
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,43 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Purchase\Services\Checkout;
|
||||||
|
|
||||||
|
use App\Domains\Catalog\Enums\InventorySubject;
|
||||||
|
use App\Domains\Catalog\Models\CatalogItem;
|
||||||
|
use App\Domains\Catalog\Models\Variant;
|
||||||
|
|
||||||
|
class InsufficientStockMessageBuilder
|
||||||
|
{
|
||||||
|
public function build(
|
||||||
|
CatalogItem $catalogItem,
|
||||||
|
CatalogItem|Variant $selection,
|
||||||
|
int $availableQuantity,
|
||||||
|
): string {
|
||||||
|
return match ($catalogItem->inventory_subject) {
|
||||||
|
InventorySubject::Seat => __('api.purchase.stock.seat_unavailable', [
|
||||||
|
'selection' => $selection->getSelectionLabel(),
|
||||||
|
]),
|
||||||
|
InventorySubject::Ticket => __('api.purchase.stock.ticket_unavailable', [
|
||||||
|
'selection' => $selection->getSelectionLabel(),
|
||||||
|
]),
|
||||||
|
InventorySubject::Product => __('api.purchase.stock.product_unavailable', [
|
||||||
|
'selection' => $this->productSelectionLabel($catalogItem, $selection),
|
||||||
|
'max' => $availableQuantity,
|
||||||
|
]),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private function productSelectionLabel(
|
||||||
|
CatalogItem $catalogItem,
|
||||||
|
CatalogItem|Variant $selection,
|
||||||
|
): string {
|
||||||
|
if ($selection instanceof CatalogItem) {
|
||||||
|
return $selection->getSelectionLabel();
|
||||||
|
}
|
||||||
|
|
||||||
|
return __('api.purchase.stock.product_selection', [
|
||||||
|
'product' => $catalogItem->getName(),
|
||||||
|
'selection' => $selection->getSelectionLabel(),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -7,6 +7,7 @@ use App\Domains\Cart\Models\CartItem;
|
|||||||
use App\Domains\Catalog\Models\CatalogItem;
|
use App\Domains\Catalog\Models\CatalogItem;
|
||||||
use App\Domains\Catalog\Models\Variant;
|
use App\Domains\Catalog\Models\Variant;
|
||||||
use App\Domains\Catalog\Services\CatalogInventoryService;
|
use App\Domains\Catalog\Services\CatalogInventoryService;
|
||||||
|
use App\Domains\Purchase\Exceptions\InsufficientStockException;
|
||||||
use App\Domains\Purchase\Models\Purchase;
|
use App\Domains\Purchase\Models\Purchase;
|
||||||
use App\Domains\Purchase\Services\UserPurchaseLimitService;
|
use App\Domains\Purchase\Services\UserPurchaseLimitService;
|
||||||
use App\Domains\Tenant\Models\Tenant;
|
use App\Domains\Tenant\Models\Tenant;
|
||||||
@@ -22,6 +23,7 @@ class StartCheckoutService
|
|||||||
private readonly UserPurchaseLimitService $purchaseLimits,
|
private readonly UserPurchaseLimitService $purchaseLimits,
|
||||||
private readonly CatalogSelectionResolver $selections,
|
private readonly CatalogSelectionResolver $selections,
|
||||||
private readonly PurchaseItemSnapshotFactory $snapshots,
|
private readonly PurchaseItemSnapshotFactory $snapshots,
|
||||||
|
private readonly InsufficientStockMessageBuilder $stockMessages,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
/** @param array<string, mixed> $purchaseData */
|
/** @param array<string, mixed> $purchaseData */
|
||||||
@@ -33,12 +35,17 @@ class StartCheckoutService
|
|||||||
->lockForUpdate()
|
->lockForUpdate()
|
||||||
->findOrFail($tenant->getKey());
|
->findOrFail($tenant->getKey());
|
||||||
|
|
||||||
$directItem = $purchaseData['direct_item'] ?? null;
|
$directItems = $purchaseData['direct_items'] ?? null;
|
||||||
$cartId = isset($purchaseData['cart_id']) ? (int) $purchaseData['cart_id'] : null;
|
$cartId = isset($purchaseData['cart_id']) ? (int) $purchaseData['cart_id'] : null;
|
||||||
unset($purchaseData['direct_item'], $purchaseData['cart_id']);
|
unset($purchaseData['direct_items'], $purchaseData['cart_id']);
|
||||||
|
|
||||||
if (is_array($directItem)) {
|
if (is_array($directItems)) {
|
||||||
return $this->startDirect($tenant, $userId, $purchaseData, $directItem);
|
return $this->startDirectItems(
|
||||||
|
$tenant,
|
||||||
|
$userId,
|
||||||
|
$purchaseData,
|
||||||
|
$directItems,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
if ($cartId === null) {
|
if ($cartId === null) {
|
||||||
@@ -53,63 +60,153 @@ class StartCheckoutService
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* @param array<string, mixed> $purchaseData
|
* @param array<string, mixed> $purchaseData
|
||||||
* @param array<string, mixed> $directItem
|
* @param array<int, array<string, mixed>> $directItems
|
||||||
*/
|
*/
|
||||||
private function startDirect(
|
private function startDirectItems(
|
||||||
Tenant $tenant,
|
Tenant $tenant,
|
||||||
int $userId,
|
int $userId,
|
||||||
array $purchaseData,
|
array $purchaseData,
|
||||||
array $directItem,
|
array $directItems,
|
||||||
): Purchase {
|
): Purchase {
|
||||||
$catalogItemId = (int) $directItem['catalog_item_id'];
|
$lines = collect(array_values($directItems))
|
||||||
$variantId = isset($directItem['variant_id']) ? (int) $directItem['variant_id'] : null;
|
->map(function (array $item, int $index): array {
|
||||||
$quantity = (int) $directItem['cantidad'];
|
return [
|
||||||
$selection = $this->selections->resolve($tenant, $catalogItemId, $variantId);
|
'index' => $index,
|
||||||
$catalogItem = $selection instanceof Variant ? $selection->catalogItem : $selection;
|
'catalog_item_id' => (int) $item['catalog_item_id'],
|
||||||
|
'variant_id' => isset($item['variant_id']) ? (int) $item['variant_id'] : null,
|
||||||
|
'quantity' => (int) $item['cantidad'],
|
||||||
|
'field' => "direct_items.{$index}",
|
||||||
|
];
|
||||||
|
})
|
||||||
|
->groupBy(fn (array $line): string => sprintf(
|
||||||
|
'%d:%s',
|
||||||
|
$line['catalog_item_id'],
|
||||||
|
$line['variant_id'] === null ? 'none' : (string) $line['variant_id'],
|
||||||
|
))
|
||||||
|
->map(function (Collection $duplicateLines): array {
|
||||||
|
$line = $duplicateLines->first();
|
||||||
|
$line['quantity'] = (int) $duplicateLines->sum('quantity');
|
||||||
|
|
||||||
$this->purchaseLimits->assertCanPurchase(
|
return $line;
|
||||||
$catalogItem,
|
})
|
||||||
$userId,
|
->sortBy(fn (array $line): string => sprintf(
|
||||||
$quantity,
|
'%020d:%020d',
|
||||||
field: 'direct_item.cantidad',
|
$line['catalog_item_id'],
|
||||||
);
|
$line['variant_id'] ?? 0,
|
||||||
|
))
|
||||||
|
->values();
|
||||||
|
|
||||||
$availableQuantity = $this->inventory->availableQuantity($selection);
|
$resolvedLines = $lines->map(function (array $line) use ($tenant): array {
|
||||||
|
$selection = $this->selections->resolve(
|
||||||
|
$tenant,
|
||||||
|
$line['catalog_item_id'],
|
||||||
|
$line['variant_id'],
|
||||||
|
$line['field'],
|
||||||
|
);
|
||||||
|
|
||||||
if ($availableQuantity !== null && $availableQuantity < $quantity) {
|
return [
|
||||||
throw ValidationException::withMessages([
|
...$line,
|
||||||
'direct_item.cantidad' => __('api.purchase.direct_item_max_stock', ['max' => $availableQuantity]),
|
'selection' => $selection,
|
||||||
]);
|
'catalog_item' => $selection instanceof Variant
|
||||||
|
? $selection->catalogItem
|
||||||
|
: $selection,
|
||||||
|
];
|
||||||
|
});
|
||||||
|
|
||||||
|
$resolvedLines
|
||||||
|
->groupBy(fn (array $line): int => $line['catalog_item']->getKey())
|
||||||
|
->each(function (Collection $catalogLines) use ($userId): void {
|
||||||
|
/** @var CatalogItem $catalogItem */
|
||||||
|
$catalogItem = $catalogLines->first()['catalog_item'];
|
||||||
|
$this->purchaseLimits->assertCanPurchase(
|
||||||
|
$catalogItem,
|
||||||
|
$userId,
|
||||||
|
(int) $catalogLines->sum('quantity'),
|
||||||
|
field: 'direct_items',
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
$unavailableItems = $resolvedLines
|
||||||
|
->map(function (array $line): ?array {
|
||||||
|
$availableQuantity = $this->inventory->availableQuantity($line['selection']);
|
||||||
|
|
||||||
|
if ($availableQuantity === null || $availableQuantity >= $line['quantity']) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return $this->unavailableItem($line, $availableQuantity);
|
||||||
|
})
|
||||||
|
->filter()
|
||||||
|
->values()
|
||||||
|
->all();
|
||||||
|
|
||||||
|
if ($unavailableItems !== []) {
|
||||||
|
throw new InsufficientStockException($unavailableItems);
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
foreach ($resolvedLines as $line) {
|
||||||
$this->inventory->reserve($selection, $quantity);
|
try {
|
||||||
} catch (\InvalidArgumentException) {
|
$this->inventory->reserve($line['selection'], $line['quantity']);
|
||||||
throw ValidationException::withMessages([
|
} catch (\InvalidArgumentException) {
|
||||||
'direct_item.cantidad' => __('api.purchase.insufficient_stock'),
|
$availableQuantity = $this->inventory->availableQuantity($line['selection']) ?? 0;
|
||||||
]);
|
|
||||||
|
throw new InsufficientStockException([
|
||||||
|
$this->unavailableItem($line, $availableQuantity),
|
||||||
|
]);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
$purchase = $this->createPurchase(
|
$purchase = $this->createPurchase(
|
||||||
$tenant,
|
$tenant,
|
||||||
$userId,
|
$userId,
|
||||||
$purchaseData,
|
$purchaseData,
|
||||||
$selection->getPrice() * $quantity,
|
(float) $resolvedLines->sum(
|
||||||
|
fn (array $line): float => $line['selection']->getPrice() * $line['quantity'],
|
||||||
|
),
|
||||||
null,
|
null,
|
||||||
);
|
);
|
||||||
$directCartItem = $this->makeDirectCartItem(
|
|
||||||
$selection,
|
$directCartItems = $resolvedLines->map(fn (array $line): CartItem => $this->makeDirectCartItem(
|
||||||
$catalogItemId,
|
$line['selection'],
|
||||||
$variantId,
|
$line['catalog_item_id'],
|
||||||
$quantity,
|
$line['variant_id'],
|
||||||
);
|
$line['quantity'],
|
||||||
|
));
|
||||||
|
|
||||||
$purchase->items()->createMany(
|
$purchase->items()->createMany(
|
||||||
$this->snapshots->fromCartItems(collect([$directCartItem])),
|
$this->snapshots->fromCartItems($directCartItems),
|
||||||
);
|
);
|
||||||
|
|
||||||
return $this->loadPurchase($purchase);
|
return $this->loadPurchase($purchase);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<string, mixed> $line
|
||||||
|
* @return array{
|
||||||
|
* index: int,
|
||||||
|
* catalog_item_id: int,
|
||||||
|
* variant_id: int|null,
|
||||||
|
* requested_quantity: int,
|
||||||
|
* available_quantity: int,
|
||||||
|
* message: string
|
||||||
|
* }
|
||||||
|
*/
|
||||||
|
private function unavailableItem(array $line, int $availableQuantity): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'index' => $line['index'],
|
||||||
|
'catalog_item_id' => $line['catalog_item_id'],
|
||||||
|
'variant_id' => $line['variant_id'],
|
||||||
|
'requested_quantity' => $line['quantity'],
|
||||||
|
'available_quantity' => $availableQuantity,
|
||||||
|
'message' => $this->stockMessages->build(
|
||||||
|
$line['catalog_item'],
|
||||||
|
$line['selection'],
|
||||||
|
$availableQuantity,
|
||||||
|
),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
/** @param array<string, mixed> $purchaseData */
|
/** @param array<string, mixed> $purchaseData */
|
||||||
private function startFromCart(
|
private function startFromCart(
|
||||||
Tenant $tenant,
|
Tenant $tenant,
|
||||||
|
|||||||
@@ -29,12 +29,15 @@ use Illuminate\Database\Eloquent\Relations\HasMany;
|
|||||||
'footer_bg_color',
|
'footer_bg_color',
|
||||||
'header_logo_id',
|
'header_logo_id',
|
||||||
'footer_logo_id',
|
'footer_logo_id',
|
||||||
|
'header_bg_image_id',
|
||||||
|
'footer_bg_image_id',
|
||||||
'website_type_code',
|
'website_type_code',
|
||||||
'search_product_layout',
|
'search_product_layout',
|
||||||
'search_group_layout',
|
'search_group_layout',
|
||||||
'search_items_per_page',
|
'search_items_per_page',
|
||||||
'display_categories',
|
'display_categories',
|
||||||
'display_seach_bar',
|
'display_seach_bar',
|
||||||
|
'display_cart',
|
||||||
'event_title',
|
'event_title',
|
||||||
'event_location',
|
'event_location',
|
||||||
'event_date_text',
|
'event_date_text',
|
||||||
@@ -49,6 +52,7 @@ class Tenant extends Model
|
|||||||
'search_items_per_page' => 12,
|
'search_items_per_page' => 12,
|
||||||
'display_categories' => true,
|
'display_categories' => true,
|
||||||
'display_seach_bar' => true,
|
'display_seach_bar' => true,
|
||||||
|
'display_cart' => true,
|
||||||
];
|
];
|
||||||
|
|
||||||
public function getRouteKeyName(): string
|
public function getRouteKeyName(): string
|
||||||
@@ -69,6 +73,7 @@ class Tenant extends Model
|
|||||||
'search_items_per_page' => 'integer',
|
'search_items_per_page' => 'integer',
|
||||||
'display_categories' => 'boolean',
|
'display_categories' => 'boolean',
|
||||||
'display_seach_bar' => 'boolean',
|
'display_seach_bar' => 'boolean',
|
||||||
|
'display_cart' => 'boolean',
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -88,6 +93,22 @@ class Tenant extends Model
|
|||||||
return $this->belongsTo(Attachment::class, 'footer_logo_id');
|
return $this->belongsTo(Attachment::class, 'footer_logo_id');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return BelongsTo<Attachment, $this>
|
||||||
|
*/
|
||||||
|
public function headerBackgroundImage(): BelongsTo
|
||||||
|
{
|
||||||
|
return $this->belongsTo(Attachment::class, 'header_bg_image_id');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return BelongsTo<Attachment, $this>
|
||||||
|
*/
|
||||||
|
public function footerBackgroundImage(): BelongsTo
|
||||||
|
{
|
||||||
|
return $this->belongsTo(Attachment::class, 'footer_bg_image_id');
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @return BelongsTo<WebsiteType, $this>
|
* @return BelongsTo<WebsiteType, $this>
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ use Illuminate\Database\Eloquent\Relations\HasMany;
|
|||||||
'codigo',
|
'codigo',
|
||||||
'nombre',
|
'nombre',
|
||||||
'dominio',
|
'dominio',
|
||||||
|
'scanner_domain',
|
||||||
'primary_color',
|
'primary_color',
|
||||||
'secondary_color',
|
'secondary_color',
|
||||||
'danger_color',
|
'danger_color',
|
||||||
|
|||||||
@@ -63,6 +63,8 @@ class StoreTenantRequest extends FormRequest
|
|||||||
'footer_bg_color' => ['required', 'string', 'regex:/^#([a-fA-F0-9]{3,4}|[a-fA-F0-9]{6}|[a-fA-F0-9]{8})$/'],
|
'footer_bg_color' => ['required', 'string', 'regex:/^#([a-fA-F0-9]{3,4}|[a-fA-F0-9]{6}|[a-fA-F0-9]{8})$/'],
|
||||||
'header_logo' => $logoRule,
|
'header_logo' => $logoRule,
|
||||||
'footer_logo' => $logoRule,
|
'footer_logo' => $logoRule,
|
||||||
|
'header_bg_image' => ['sometimes', 'nullable', new ImageOrBase64Rule],
|
||||||
|
'footer_bg_image' => ['sometimes', 'nullable', new ImageOrBase64Rule],
|
||||||
'social_media' => ['sometimes', 'array'],
|
'social_media' => ['sometimes', 'array'],
|
||||||
'social_media.*.code' => [
|
'social_media.*.code' => [
|
||||||
'required',
|
'required',
|
||||||
@@ -77,6 +79,7 @@ class StoreTenantRequest extends FormRequest
|
|||||||
'search_items_per_page' => ['sometimes', 'integer', 'min:4', 'max:48'],
|
'search_items_per_page' => ['sometimes', 'integer', 'min:4', 'max:48'],
|
||||||
'display_categories' => ['sometimes', 'boolean'],
|
'display_categories' => ['sometimes', 'boolean'],
|
||||||
'display_seach_bar' => ['sometimes', 'boolean'],
|
'display_seach_bar' => ['sometimes', 'boolean'],
|
||||||
|
'display_cart' => ['sometimes', 'boolean'],
|
||||||
'website_type_code' => [
|
'website_type_code' => [
|
||||||
'required_with:extras',
|
'required_with:extras',
|
||||||
'sometimes',
|
'sometimes',
|
||||||
|
|||||||
@@ -73,6 +73,8 @@ class UpdateTenantRequest extends FormRequest
|
|||||||
'footer_bg_color' => ['nullable', 'string', 'regex:/^#([a-fA-F0-9]{3,4}|[a-fA-F0-9]{6}|[a-fA-F0-9]{8})$/'],
|
'footer_bg_color' => ['nullable', 'string', 'regex:/^#([a-fA-F0-9]{3,4}|[a-fA-F0-9]{6}|[a-fA-F0-9]{8})$/'],
|
||||||
'header_logo' => $logoRule,
|
'header_logo' => $logoRule,
|
||||||
'footer_logo' => $logoRule,
|
'footer_logo' => $logoRule,
|
||||||
|
'header_bg_image' => ['sometimes', 'nullable', new ImageOrBase64Rule],
|
||||||
|
'footer_bg_image' => ['sometimes', 'nullable', new ImageOrBase64Rule],
|
||||||
'social_media' => ['sometimes', 'array'],
|
'social_media' => ['sometimes', 'array'],
|
||||||
'social_media.*.code' => [
|
'social_media.*.code' => [
|
||||||
'required',
|
'required',
|
||||||
@@ -87,6 +89,7 @@ class UpdateTenantRequest extends FormRequest
|
|||||||
'search_items_per_page' => ['sometimes', 'integer', 'min:4', 'max:48'],
|
'search_items_per_page' => ['sometimes', 'integer', 'min:4', 'max:48'],
|
||||||
'display_categories' => ['sometimes', 'boolean'],
|
'display_categories' => ['sometimes', 'boolean'],
|
||||||
'display_seach_bar' => ['sometimes', 'boolean'],
|
'display_seach_bar' => ['sometimes', 'boolean'],
|
||||||
|
'display_cart' => ['sometimes', 'boolean'],
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -59,11 +59,14 @@ class TenantResource extends JsonResource
|
|||||||
// 1 day
|
// 1 day
|
||||||
'header_logo' => $this->headerLogo?->getTemporaryUrl(1440),
|
'header_logo' => $this->headerLogo?->getTemporaryUrl(1440),
|
||||||
'footer_logo' => $this->footerLogo?->getTemporaryUrl(1440),
|
'footer_logo' => $this->footerLogo?->getTemporaryUrl(1440),
|
||||||
|
'header_bg_image' => $this->headerBackgroundImage?->getTemporaryUrl(1440),
|
||||||
|
'footer_bg_image' => $this->footerBackgroundImage?->getTemporaryUrl(1440),
|
||||||
'search_product_layout' => $this->search_product_layout->value,
|
'search_product_layout' => $this->search_product_layout->value,
|
||||||
'search_group_layout' => $this->search_group_layout->value,
|
'search_group_layout' => $this->search_group_layout->value,
|
||||||
'search_items_per_page' => $this->search_items_per_page,
|
'search_items_per_page' => $this->search_items_per_page,
|
||||||
'display_categories' => $this->display_categories,
|
'display_categories' => $this->display_categories,
|
||||||
'display_seach_bar' => $this->display_seach_bar,
|
'display_seach_bar' => $this->display_seach_bar,
|
||||||
|
'display_cart' => $this->display_cart,
|
||||||
'social_media' => $this->whenLoaded(
|
'social_media' => $this->whenLoaded(
|
||||||
'socialMedia',
|
'socialMedia',
|
||||||
fn () => $this->socialMedia
|
fn () => $this->socialMedia
|
||||||
|
|||||||
@@ -13,6 +13,8 @@ class TenantInformationService
|
|||||||
private const DEFAULT_RELATIONS = [
|
private const DEFAULT_RELATIONS = [
|
||||||
'headerLogo',
|
'headerLogo',
|
||||||
'footerLogo',
|
'footerLogo',
|
||||||
|
'headerBackgroundImage',
|
||||||
|
'footerBackgroundImage',
|
||||||
'socialMedia',
|
'socialMedia',
|
||||||
'websiteExtras.websiteTypeExtra',
|
'websiteExtras.websiteTypeExtra',
|
||||||
'eventDates',
|
'eventDates',
|
||||||
|
|||||||
@@ -25,12 +25,16 @@ class TenantService
|
|||||||
return DB::transaction(function () use ($data): Tenant {
|
return DB::transaction(function () use ($data): Tenant {
|
||||||
$headerLogo = $data['header_logo'] ?? null;
|
$headerLogo = $data['header_logo'] ?? null;
|
||||||
$footerLogo = $data['footer_logo'] ?? null;
|
$footerLogo = $data['footer_logo'] ?? null;
|
||||||
|
$headerBackgroundImage = $data['header_bg_image'] ?? null;
|
||||||
|
$footerBackgroundImage = $data['footer_bg_image'] ?? null;
|
||||||
$socialMedia = $data['social_media'] ?? [];
|
$socialMedia = $data['social_media'] ?? [];
|
||||||
$extras = $data['extras'] ?? [];
|
$extras = $data['extras'] ?? [];
|
||||||
|
|
||||||
unset(
|
unset(
|
||||||
$data['header_logo'],
|
$data['header_logo'],
|
||||||
$data['footer_logo'],
|
$data['footer_logo'],
|
||||||
|
$data['header_bg_image'],
|
||||||
|
$data['footer_bg_image'],
|
||||||
$data['social_media'],
|
$data['social_media'],
|
||||||
$data['extras'],
|
$data['extras'],
|
||||||
);
|
);
|
||||||
@@ -59,6 +63,8 @@ class TenantService
|
|||||||
|
|
||||||
$data['header_logo_id'] = $headerAttachmentId;
|
$data['header_logo_id'] = $headerAttachmentId;
|
||||||
$data['footer_logo_id'] = $footerAttachmentId;
|
$data['footer_logo_id'] = $footerAttachmentId;
|
||||||
|
$data['header_bg_image_id'] = $this->storeTenantImage($headerBackgroundImage);
|
||||||
|
$data['footer_bg_image_id'] = $this->storeTenantImage($footerBackgroundImage);
|
||||||
|
|
||||||
/** @var Tenant $tenant */
|
/** @var Tenant $tenant */
|
||||||
$tenant = Tenant::query()->create($data);
|
$tenant = Tenant::query()->create($data);
|
||||||
@@ -79,14 +85,20 @@ class TenantService
|
|||||||
return DB::transaction(function () use ($tenant, $data): Tenant {
|
return DB::transaction(function () use ($tenant, $data): Tenant {
|
||||||
$hasHeaderLogoKey = array_key_exists('header_logo', $data);
|
$hasHeaderLogoKey = array_key_exists('header_logo', $data);
|
||||||
$hasFooterLogoKey = array_key_exists('footer_logo', $data);
|
$hasFooterLogoKey = array_key_exists('footer_logo', $data);
|
||||||
|
$hasHeaderBackgroundImageKey = array_key_exists('header_bg_image', $data);
|
||||||
|
$hasFooterBackgroundImageKey = array_key_exists('footer_bg_image', $data);
|
||||||
$hasSocialMediaKey = array_key_exists('social_media', $data);
|
$hasSocialMediaKey = array_key_exists('social_media', $data);
|
||||||
$headerLogo = $data['header_logo'] ?? null;
|
$headerLogo = $data['header_logo'] ?? null;
|
||||||
$footerLogo = $data['footer_logo'] ?? null;
|
$footerLogo = $data['footer_logo'] ?? null;
|
||||||
|
$headerBackgroundImage = $data['header_bg_image'] ?? null;
|
||||||
|
$footerBackgroundImage = $data['footer_bg_image'] ?? null;
|
||||||
$socialMedia = $data['social_media'] ?? [];
|
$socialMedia = $data['social_media'] ?? [];
|
||||||
|
|
||||||
unset(
|
unset(
|
||||||
$data['header_logo'],
|
$data['header_logo'],
|
||||||
$data['footer_logo'],
|
$data['footer_logo'],
|
||||||
|
$data['header_bg_image'],
|
||||||
|
$data['footer_bg_image'],
|
||||||
$data['social_media']
|
$data['social_media']
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -124,6 +136,14 @@ class TenantService
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if ($hasHeaderBackgroundImageKey) {
|
||||||
|
$tenant->header_bg_image_id = $this->storeTenantImage($headerBackgroundImage);
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($hasFooterBackgroundImageKey) {
|
||||||
|
$tenant->footer_bg_image_id = $this->storeTenantImage($footerBackgroundImage);
|
||||||
|
}
|
||||||
|
|
||||||
$tenant->save();
|
$tenant->save();
|
||||||
|
|
||||||
if ($hasSocialMediaKey) {
|
if ($hasSocialMediaKey) {
|
||||||
@@ -151,4 +171,17 @@ class TenantService
|
|||||||
$tenant->socialMedia()->sync($associations);
|
$tenant->socialMedia()->sync($associations);
|
||||||
$tenant->unsetRelation('socialMedia');
|
$tenant->unsetRelation('socialMedia');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private function storeTenantImage(mixed $image): ?int
|
||||||
|
{
|
||||||
|
if (! $image) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
$attachment = is_string($image) && Str::isUuid($image)
|
||||||
|
? Attachment::query()->where('key', $image)->first()
|
||||||
|
: $this->attachmentService->store($image, 'tenants');
|
||||||
|
|
||||||
|
return $attachment?->id;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
47
app/Domains/Ticket/Controllers/Scanner/TicketController.php
Normal file
@@ -0,0 +1,47 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Ticket\Controllers\Scanner;
|
||||||
|
|
||||||
|
use App\Domains\Auth\Models\User;
|
||||||
|
use App\Domains\Ticket\Requests\ScannerTicketIndexRequest;
|
||||||
|
use App\Domains\Ticket\Resources\Scanner\ScannedTicketResource;
|
||||||
|
use App\Domains\Ticket\Resources\TicketResource;
|
||||||
|
use App\Domains\Ticket\Services\ScannerTicketService;
|
||||||
|
use App\Http\Controllers\Controller;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
|
||||||
|
|
||||||
|
class TicketController extends Controller
|
||||||
|
{
|
||||||
|
public function __construct(private readonly ScannerTicketService $ticketService) {}
|
||||||
|
|
||||||
|
public function index(ScannerTicketIndexRequest $request): AnonymousResourceCollection
|
||||||
|
{
|
||||||
|
/** @var User $scanner */
|
||||||
|
$scanner = $request->user();
|
||||||
|
|
||||||
|
return ScannedTicketResource::collection(
|
||||||
|
$this->ticketService->scannedBy($scanner, $request->validated())
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function show(Request $request, string $ticketUuid): TicketResource
|
||||||
|
{
|
||||||
|
/** @var User $scanner */
|
||||||
|
$scanner = $request->user();
|
||||||
|
|
||||||
|
return TicketResource::make(
|
||||||
|
$this->ticketService->detail($scanner, $ticketUuid)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function scan(Request $request, string $ticketUuid): TicketResource
|
||||||
|
{
|
||||||
|
/** @var User $scanner */
|
||||||
|
$scanner = $request->user();
|
||||||
|
|
||||||
|
return TicketResource::make(
|
||||||
|
$this->ticketService->scan($scanner, $ticketUuid)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
23
app/Domains/Ticket/Requests/ScannerTicketIndexRequest.php
Normal file
@@ -0,0 +1,23 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Ticket\Requests;
|
||||||
|
|
||||||
|
use Illuminate\Foundation\Http\FormRequest;
|
||||||
|
|
||||||
|
class ScannerTicketIndexRequest extends FormRequest
|
||||||
|
{
|
||||||
|
public function authorize(): bool
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @return array<string, list<string>> */
|
||||||
|
public function rules(): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'q' => ['sometimes', 'nullable', 'string', 'max:255'],
|
||||||
|
'page' => ['sometimes', 'integer', 'min:1'],
|
||||||
|
'per_page' => ['sometimes', 'integer', 'min:1', 'max:100'],
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Ticket\Resources\Scanner;
|
||||||
|
|
||||||
|
use App\Domains\Ticket\Models\Ticket;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Illuminate\Http\Resources\Json\JsonResource;
|
||||||
|
|
||||||
|
/** @mixin Ticket */
|
||||||
|
class ScannedTicketResource extends JsonResource
|
||||||
|
{
|
||||||
|
/** @return array<string, mixed> */
|
||||||
|
public function toArray(Request $request): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'product' => $this->name,
|
||||||
|
'id' => $this->id,
|
||||||
|
'ticket' => $this->ticket,
|
||||||
|
'used_at' => $this->used_at,
|
||||||
|
'expires_at' => $this->getEffectiveExpiresAt(),
|
||||||
|
'status' => $this->status,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -18,6 +18,8 @@ class TicketResource extends JsonResource
|
|||||||
'ticket' => $this->ticket,
|
'ticket' => $this->ticket,
|
||||||
'name' => $this->name,
|
'name' => $this->name,
|
||||||
'description' => $this->description,
|
'description' => $this->description,
|
||||||
|
'client' => $this->user?->nombre_apellido,
|
||||||
|
'category' => $this->sourceCatalogItem?->category?->nombre,
|
||||||
'source_catalog_item_id' => $this->source_catalog_item_id,
|
'source_catalog_item_id' => $this->source_catalog_item_id,
|
||||||
'source_variant_id' => $this->source_variant_id,
|
'source_variant_id' => $this->source_variant_id,
|
||||||
'validity_times' => ValidityTimeResource::collection($this->allValidityTimes()),
|
'validity_times' => ValidityTimeResource::collection($this->allValidityTimes()),
|
||||||
|
|||||||
163
app/Domains/Ticket/Services/ScannerTicketService.php
Normal file
@@ -0,0 +1,163 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Ticket\Services;
|
||||||
|
|
||||||
|
use App\Domains\Auth\Models\User;
|
||||||
|
use App\Domains\Ticket\Models\Ticket;
|
||||||
|
use Illuminate\Database\Eloquent\Builder;
|
||||||
|
use Illuminate\Pagination\LengthAwarePaginator;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Illuminate\Validation\ValidationException;
|
||||||
|
|
||||||
|
class ScannerTicketService
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* @param array{q?: string|null, page?: int, per_page?: int} $filters
|
||||||
|
* @return LengthAwarePaginator<Ticket>
|
||||||
|
*/
|
||||||
|
public function scannedBy(User $scanner, array $filters = []): LengthAwarePaginator
|
||||||
|
{
|
||||||
|
$search = trim((string) ($filters['q'] ?? ''));
|
||||||
|
|
||||||
|
return $this->baseQuery()
|
||||||
|
->where('tenant_code', $scanner->tenant_codigo)
|
||||||
|
->where('scanner_user_id', $scanner->getKey())
|
||||||
|
->when($search !== '', function (Builder $query) use ($search): void {
|
||||||
|
$usedAtDate = $this->parseSearchDate($search);
|
||||||
|
|
||||||
|
$query->where(function (Builder $searchQuery) use ($search, $usedAtDate): void {
|
||||||
|
$searchQuery->where('ticket', 'like', "%{$search}%");
|
||||||
|
|
||||||
|
if (ctype_digit($search)) {
|
||||||
|
$searchQuery->orWhere('id', (int) $search);
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($usedAtDate !== null) {
|
||||||
|
$searchQuery->orWhereDate('used_at', $usedAtDate);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
})
|
||||||
|
->orderByDesc('used_at')
|
||||||
|
->orderByDesc('id')
|
||||||
|
->paginateFromRequest()
|
||||||
|
->withQueryString();
|
||||||
|
}
|
||||||
|
|
||||||
|
private function parseSearchDate(string $search): ?string
|
||||||
|
{
|
||||||
|
if (preg_match('/^(\d{4})-(\d{2})-(\d{2})$/', $search, $matches) === 1) {
|
||||||
|
[$year, $month, $day] = array_map('intval', array_slice($matches, 1));
|
||||||
|
|
||||||
|
if (checkdate($month, $day, $year)) {
|
||||||
|
return sprintf('%04d-%02d-%02d', $year, $month, $day);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (preg_match('/^(\d{2})\/(\d{2})\/(\d{2}|\d{4})$/', $search, $matches) === 1) {
|
||||||
|
$day = (int) $matches[1];
|
||||||
|
$month = (int) $matches[2];
|
||||||
|
$year = (int) $matches[3];
|
||||||
|
$year = strlen($matches[3]) === 2 ? 2000 + $year : $year;
|
||||||
|
|
||||||
|
if (checkdate($month, $day, $year)) {
|
||||||
|
return sprintf('%04d-%02d-%02d', $year, $month, $day);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function detail(User $scanner, string $ticketUuid): Ticket
|
||||||
|
{
|
||||||
|
$categoryIds = $this->scannerCategoryIds($scanner);
|
||||||
|
|
||||||
|
return $this->baseQuery()
|
||||||
|
->where('tenant_code', $scanner->tenant_codigo)
|
||||||
|
->where('ticket', $ticketUuid)
|
||||||
|
->where(function (Builder $query) use ($scanner, $categoryIds): void {
|
||||||
|
$query
|
||||||
|
->where('scanner_user_id', $scanner->getKey())
|
||||||
|
->orWhereHas(
|
||||||
|
'sourceCatalogItem',
|
||||||
|
fn (Builder $catalogItemQuery): Builder => $catalogItemQuery
|
||||||
|
->whereIn('category_id', $categoryIds)
|
||||||
|
);
|
||||||
|
})
|
||||||
|
->firstOrFail();
|
||||||
|
}
|
||||||
|
|
||||||
|
public function scan(User $scanner, string $ticketUuid): Ticket
|
||||||
|
{
|
||||||
|
return DB::transaction(function () use ($scanner, $ticketUuid): Ticket {
|
||||||
|
$ticket = $this->baseQuery()
|
||||||
|
->where('tenant_code', $scanner->tenant_codigo)
|
||||||
|
->where('ticket', $ticketUuid)
|
||||||
|
->lockForUpdate()
|
||||||
|
->firstOrFail();
|
||||||
|
|
||||||
|
if (! $this->scannerCanScan($scanner, $ticket)) {
|
||||||
|
throw ValidationException::withMessages([
|
||||||
|
'ticket' => __('api.ticket.scanner_category_forbidden'),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($ticket->is_used) {
|
||||||
|
throw ValidationException::withMessages([
|
||||||
|
'ticket' => __('api.ticket.already_scanned'),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (! $ticket->is_valid) {
|
||||||
|
throw ValidationException::withMessages([
|
||||||
|
'ticket' => $ticket->is_expired
|
||||||
|
? __('api.ticket.expired_for_scan')
|
||||||
|
: __('api.ticket.not_valid_for_scan'),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
$ticket->forceFill([
|
||||||
|
'used_at' => now(),
|
||||||
|
'scanner_user_id' => $scanner->getKey(),
|
||||||
|
])->save();
|
||||||
|
|
||||||
|
return $ticket->refresh()->load($this->relations());
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @return Builder<Ticket> */
|
||||||
|
private function baseQuery(): Builder
|
||||||
|
{
|
||||||
|
return Ticket::query()->with($this->relations());
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @return array<int, string> */
|
||||||
|
private function relations(): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'validityGroups.validityTimes',
|
||||||
|
'sourceCatalogItem.category',
|
||||||
|
'sourceVariant.eventDate',
|
||||||
|
'sourceVariant.catalogItem',
|
||||||
|
'user',
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @return array<int, int> */
|
||||||
|
private function scannerCategoryIds(User $scanner): array
|
||||||
|
{
|
||||||
|
return $scanner->scanCategories()
|
||||||
|
->pluck('categorias.id')
|
||||||
|
->map(fn (mixed $id): int => (int) $id)
|
||||||
|
->all();
|
||||||
|
}
|
||||||
|
|
||||||
|
private function scannerCanScan(User $scanner, Ticket $ticket): bool
|
||||||
|
{
|
||||||
|
$categoryId = $ticket->sourceCatalogItem?->category_id;
|
||||||
|
|
||||||
|
return $categoryId !== null
|
||||||
|
&& $scanner->scanCategories()
|
||||||
|
->where('categorias.id', $categoryId)
|
||||||
|
->exists();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -9,3 +9,5 @@ Route::prefix('tenants/{tenant:codigo}')
|
|||||||
Route::get('tickets', [TicketController::class, 'index']);
|
Route::get('tickets', [TicketController::class, 'index']);
|
||||||
Route::post('tickets/pdf', [TicketController::class, 'downloadPdf']);
|
Route::post('tickets/pdf', [TicketController::class, 'downloadPdf']);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
require __DIR__.'/scanner.php';
|
||||||
|
|||||||
14
app/Domains/Ticket/routes/scanner.php
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use App\Domains\Ticket\Controllers\Scanner\TicketController;
|
||||||
|
use Illuminate\Support\Facades\Route;
|
||||||
|
|
||||||
|
Route::prefix('v1/scanner/tickets')
|
||||||
|
->middleware(['auth:sanctum', 'scanner.tenant'])
|
||||||
|
->group(function (): void {
|
||||||
|
Route::get('/', [TicketController::class, 'index']);
|
||||||
|
Route::get('{ticketUuid}', [TicketController::class, 'show'])
|
||||||
|
->whereUuid('ticketUuid');
|
||||||
|
Route::post('{ticketUuid}/scan', [TicketController::class, 'scan'])
|
||||||
|
->whereUuid('ticketUuid');
|
||||||
|
});
|
||||||
30
app/Http/Middleware/EnsureScannerTenant.php
Normal file
@@ -0,0 +1,30 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Middleware;
|
||||||
|
|
||||||
|
use App\Domains\Authorization\Enums\PermissionCode;
|
||||||
|
use Closure;
|
||||||
|
use Illuminate\Auth\Access\AuthorizationException;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Symfony\Component\HttpFoundation\Response;
|
||||||
|
|
||||||
|
class EnsureScannerTenant
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Ensure the authenticated user can scan tickets for a tenant.
|
||||||
|
*/
|
||||||
|
public function handle(Request $request, Closure $next): Response
|
||||||
|
{
|
||||||
|
$user = $request->user();
|
||||||
|
|
||||||
|
if (
|
||||||
|
! $user
|
||||||
|
|| ! $user->tenant_codigo
|
||||||
|
|| ! $user->hasPermission(PermissionCode::ScanTickets->value)
|
||||||
|
) {
|
||||||
|
throw new AuthorizationException;
|
||||||
|
}
|
||||||
|
|
||||||
|
return $next($request);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,8 +1,10 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
use App\Domains\Auth\Exceptions\AccountLockedException;
|
use App\Domains\Auth\Exceptions\AccountLockedException;
|
||||||
|
use App\Domains\Purchase\Exceptions\InsufficientStockException;
|
||||||
use App\Domains\Ticket\Exceptions\TicketNotAvailableException;
|
use App\Domains\Ticket\Exceptions\TicketNotAvailableException;
|
||||||
use App\Http\Middleware\EnsureAdminAppTenant;
|
use App\Http\Middleware\EnsureAdminAppTenant;
|
||||||
|
use App\Http\Middleware\EnsureScannerTenant;
|
||||||
use App\Http\Middleware\EnsureTenantHasMenu;
|
use App\Http\Middleware\EnsureTenantHasMenu;
|
||||||
use App\Http\Middleware\SetApiLocale;
|
use App\Http\Middleware\SetApiLocale;
|
||||||
use Illuminate\Auth\Access\AuthorizationException;
|
use Illuminate\Auth\Access\AuthorizationException;
|
||||||
@@ -25,6 +27,7 @@ return Application::configure(basePath: dirname(__DIR__))
|
|||||||
->withMiddleware(function (Middleware $middleware): void {
|
->withMiddleware(function (Middleware $middleware): void {
|
||||||
$middleware->alias([
|
$middleware->alias([
|
||||||
'adminapp.tenant' => EnsureAdminAppTenant::class,
|
'adminapp.tenant' => EnsureAdminAppTenant::class,
|
||||||
|
'scanner.tenant' => EnsureScannerTenant::class,
|
||||||
'tenant.menu' => EnsureTenantHasMenu::class,
|
'tenant.menu' => EnsureTenantHasMenu::class,
|
||||||
]);
|
]);
|
||||||
$middleware->encryptCookies(except: [
|
$middleware->encryptCookies(except: [
|
||||||
@@ -72,6 +75,18 @@ return Application::configure(basePath: dirname(__DIR__))
|
|||||||
'message' => __('api.errors.forbidden'),
|
'message' => __('api.errors.forbidden'),
|
||||||
], 403);
|
], 403);
|
||||||
});
|
});
|
||||||
|
$exceptions->render(function (InsufficientStockException $exception, Request $request) {
|
||||||
|
if (! $request->is('api/*')) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return response()->json([
|
||||||
|
'code' => 'purchase.insufficient_stock',
|
||||||
|
'message' => $exception->getMessage(),
|
||||||
|
'errors' => $exception->errors(),
|
||||||
|
'unavailable_items' => $exception->unavailableItems,
|
||||||
|
], 422);
|
||||||
|
});
|
||||||
$exceptions->render(function (ModelNotFoundException $exception, Request $request) {
|
$exceptions->render(function (ModelNotFoundException $exception, Request $request) {
|
||||||
if (! $request->is('api/*')) {
|
if (! $request->is('api/*')) {
|
||||||
return null;
|
return null;
|
||||||
|
|||||||
@@ -0,0 +1,23 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use Illuminate\Database\Migrations\Migration;
|
||||||
|
use Illuminate\Database\Schema\Blueprint;
|
||||||
|
use Illuminate\Support\Facades\Schema;
|
||||||
|
|
||||||
|
return new class extends Migration
|
||||||
|
{
|
||||||
|
public function up(): void
|
||||||
|
{
|
||||||
|
Schema::table('website_type', function (Blueprint $table): void {
|
||||||
|
$table->string('scanner_domain')->nullable()->unique()->after('dominio');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public function down(): void
|
||||||
|
{
|
||||||
|
Schema::table('website_type', function (Blueprint $table): void {
|
||||||
|
$table->dropUnique(['scanner_domain']);
|
||||||
|
$table->dropColumn('scanner_domain');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use App\Domains\Catalog\Enums\GroupLayout;
|
||||||
|
use App\Domains\Catalog\Enums\ProductLayout;
|
||||||
|
use Illuminate\Database\Migrations\Migration;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
|
||||||
|
return new class extends Migration
|
||||||
|
{
|
||||||
|
public function up(): void
|
||||||
|
{
|
||||||
|
if (! in_array(DB::getDriverName(), ['mysql', 'mariadb'], true)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->alterEnums(ProductLayout::values(), GroupLayout::values());
|
||||||
|
}
|
||||||
|
|
||||||
|
public function down(): void
|
||||||
|
{
|
||||||
|
if (! in_array(DB::getDriverName(), ['mysql', 'mariadb'], true)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->alterEnums(
|
||||||
|
['row', 'column_with_image', 'column_with_cart'],
|
||||||
|
['paginated', 'simple', 'simple_vertical', 'carousel'],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param list<string> $productLayouts
|
||||||
|
* @param list<string> $groupLayouts
|
||||||
|
*/
|
||||||
|
private function alterEnums(array $productLayouts, array $groupLayouts): void
|
||||||
|
{
|
||||||
|
$products = $this->enumValues($productLayouts);
|
||||||
|
$groups = $this->enumValues($groupLayouts);
|
||||||
|
|
||||||
|
DB::statement("ALTER TABLE featured_groups MODIFY product_layout ENUM({$products}) NOT NULL");
|
||||||
|
DB::statement("ALTER TABLE featured_groups MODIFY group_layout ENUM({$groups}) NOT NULL DEFAULT 'paginated'");
|
||||||
|
DB::statement("ALTER TABLE tenants MODIFY search_product_layout ENUM({$products}) NOT NULL DEFAULT 'column_with_image'");
|
||||||
|
DB::statement("ALTER TABLE tenants MODIFY search_group_layout ENUM({$groups}) NOT NULL DEFAULT 'paginated'");
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @param list<string> $values */
|
||||||
|
private function enumValues(array $values): string
|
||||||
|
{
|
||||||
|
return collect($values)
|
||||||
|
->map(fn (string $value): string => DB::getPdo()->quote($value))
|
||||||
|
->implode(',');
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -0,0 +1,329 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use Illuminate\Database\Migrations\Migration;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Illuminate\Support\Facades\Storage;
|
||||||
|
use Illuminate\Support\Str;
|
||||||
|
|
||||||
|
return new class extends Migration
|
||||||
|
{
|
||||||
|
private const TENANT_CODE = 'desfile_pura_tendencia';
|
||||||
|
|
||||||
|
private const SOURCE_TENANT_CODE = 'fiesta_futbol_infantil';
|
||||||
|
|
||||||
|
/** @var list<string> */
|
||||||
|
private array $storedPaths = [];
|
||||||
|
|
||||||
|
public function up(): void
|
||||||
|
{
|
||||||
|
if (DB::table('tenants')->where('codigo', self::TENANT_CODE)->exists()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$heroExtraId = DB::table('website_type_extras')
|
||||||
|
->where('website_type_code', 'onticket')
|
||||||
|
->where('codigo', 'heroConfig')
|
||||||
|
->value('id');
|
||||||
|
|
||||||
|
if (
|
||||||
|
$heroExtraId === null
|
||||||
|
|| ! DB::table('website_type')->where('codigo', 'onticket')->exists()
|
||||||
|
|| ! DB::table('tenants')->where('codigo', self::SOURCE_TENANT_CODE)->exists()
|
||||||
|
) {
|
||||||
|
// This data migration targets installations whose reference data was
|
||||||
|
// already provisioned. Fresh test databases do not contain seed data.
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
DB::transaction(function () use ($heroExtraId): void {
|
||||||
|
$headerLogoId = $this->storeImage(
|
||||||
|
'images/tennants/desfile_pura_tendencia/desfile_pura_tendencia_header.png',
|
||||||
|
'desfile_pura_tendencia_header.png',
|
||||||
|
'tenants/'.self::TENANT_CODE,
|
||||||
|
);
|
||||||
|
$footerLogoId = $this->storeImage(
|
||||||
|
'images/tennants/desfile_pura_tendencia/desfile_pura_tendencia_footer.png',
|
||||||
|
'desfile_pura_tendencia_footer.png',
|
||||||
|
'tenants/'.self::TENANT_CODE,
|
||||||
|
);
|
||||||
|
$heroImageId = $this->storeImage(
|
||||||
|
'images/tennants/desfile_pura_tendencia/desfile_pura_tendencia_hero.png',
|
||||||
|
'desfile_pura_tendencia_hero.png',
|
||||||
|
'tenants/'.self::TENANT_CODE.'/extras/heroConfig',
|
||||||
|
);
|
||||||
|
|
||||||
|
$now = now();
|
||||||
|
|
||||||
|
DB::table('tenants')->insert([
|
||||||
|
'codigo' => self::TENANT_CODE,
|
||||||
|
'nombre' => 'Desfile Pura Tendencia',
|
||||||
|
'dominio' => 'desfile-pura-tendencia.localhost',
|
||||||
|
'event_title' => 'Desfile Pura Tendencia',
|
||||||
|
'event_location' => 'Salón Centro Recreativo Luz y Fuerza',
|
||||||
|
'event_date_text' => '16 de Octubre 2026',
|
||||||
|
'primary_color' => '#BA69A9',
|
||||||
|
'secondary_color' => '#A0A0A0',
|
||||||
|
'danger_color' => '#FF8888',
|
||||||
|
'success_color' => '#198754',
|
||||||
|
'header_bg_color' => '#ffffff',
|
||||||
|
'footer_bg_color' => '#D4441C',
|
||||||
|
'header_logo_id' => $headerLogoId,
|
||||||
|
'footer_logo_id' => $footerLogoId,
|
||||||
|
'website_type_code' => 'onticket',
|
||||||
|
'display_categories' => false,
|
||||||
|
'display_seach_bar' => false,
|
||||||
|
'created_at' => $now,
|
||||||
|
'updated_at' => $now,
|
||||||
|
]);
|
||||||
|
|
||||||
|
$validityTimeId = DB::table('validity_times')->insertGetId([
|
||||||
|
'type' => 'fixed_window',
|
||||||
|
'start_time' => null,
|
||||||
|
'end_time' => null,
|
||||||
|
'fixed_starts_at' => '2026-10-16 20:30:00',
|
||||||
|
'fixed_expires_at' => '2026-10-16 23:59:00',
|
||||||
|
'created_at' => $now,
|
||||||
|
'updated_at' => $now,
|
||||||
|
]);
|
||||||
|
|
||||||
|
DB::table('event_dates')->insert([
|
||||||
|
'tenant_code' => self::TENANT_CODE,
|
||||||
|
'validity_time_id' => $validityTimeId,
|
||||||
|
'date' => '2026-10-16',
|
||||||
|
'time_start' => '20:30:00',
|
||||||
|
'time_end' => '23:59:00',
|
||||||
|
]);
|
||||||
|
|
||||||
|
$this->createEntryCatalog($validityTimeId, $now);
|
||||||
|
|
||||||
|
DB::table('websites_extras')->insert([
|
||||||
|
'website_code' => self::TENANT_CODE,
|
||||||
|
'website_type_extra_id' => $heroExtraId,
|
||||||
|
'config' => json_encode([
|
||||||
|
'title_html' => '<h1>LA NOCHE DE LA MODA</h1>',
|
||||||
|
'description_html' => 'Viví una experiencia de <b>Alta Costura con conducción exclusiva de Pampita</b> y las colecciones de Pucheta-Paz.',
|
||||||
|
'background_image_id' => $heroImageId,
|
||||||
|
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
|
||||||
|
'is_enabled' => true,
|
||||||
|
'created_at' => $now,
|
||||||
|
'updated_at' => $now,
|
||||||
|
]);
|
||||||
|
|
||||||
|
$menuAssignments = DB::table('tenants_menues')
|
||||||
|
->where('tenant_code', self::SOURCE_TENANT_CODE)
|
||||||
|
->where('menu_code', 'not like', 'adminapp.fiesta-futbol-infantil.%')
|
||||||
|
->orderBy('id')
|
||||||
|
->get(['menu_code', 'static_content']);
|
||||||
|
|
||||||
|
foreach ($menuAssignments as $assignment) {
|
||||||
|
DB::table('tenants_menues')->insert([
|
||||||
|
'tenant_code' => self::TENANT_CODE,
|
||||||
|
'menu_code' => $assignment->menu_code,
|
||||||
|
'static_content' => $assignment->static_content,
|
||||||
|
'created_at' => $now,
|
||||||
|
'updated_at' => $now,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} catch (Throwable $throwable) {
|
||||||
|
Storage::disk('s3')->delete($this->storedPaths);
|
||||||
|
|
||||||
|
throw $throwable;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public function down(): void
|
||||||
|
{
|
||||||
|
// Intentionally irreversible: once active, this tenant can own users,
|
||||||
|
// purchases, tickets and catalog data that a rollback must not delete.
|
||||||
|
}
|
||||||
|
|
||||||
|
private function storeImage(string $relativePath, string $filename, string $directory): int
|
||||||
|
{
|
||||||
|
$sourcePath = public_path($relativePath);
|
||||||
|
|
||||||
|
if (! is_file($sourcePath)) {
|
||||||
|
throw new RuntimeException("Image not found at path: {$sourcePath}");
|
||||||
|
}
|
||||||
|
|
||||||
|
$contents = file_get_contents($sourcePath);
|
||||||
|
|
||||||
|
if ($contents === false) {
|
||||||
|
throw new RuntimeException("Could not read image at path: {$sourcePath}");
|
||||||
|
}
|
||||||
|
|
||||||
|
$key = (string) Str::uuid();
|
||||||
|
$storedPath = trim($directory, '/').'/'.$key.'.png';
|
||||||
|
|
||||||
|
if (! Storage::disk('s3')->put($storedPath, $contents)) {
|
||||||
|
throw new RuntimeException("Could not store image at path: {$storedPath}");
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->storedPaths[] = $storedPath;
|
||||||
|
|
||||||
|
return DB::table('attachments')->insertGetId([
|
||||||
|
'key' => $key,
|
||||||
|
'path' => $storedPath,
|
||||||
|
'filename' => $filename,
|
||||||
|
'type' => 'image',
|
||||||
|
'mime_type' => 'image/png',
|
||||||
|
'extension' => 'png',
|
||||||
|
'size' => strlen($contents),
|
||||||
|
'created_at' => now(),
|
||||||
|
'updated_at' => now(),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
private function createEntryCatalog(int $validityTimeId, DateTimeInterface $now): void
|
||||||
|
{
|
||||||
|
$attributes = [
|
||||||
|
'tipo' => [
|
||||||
|
'name' => 'Tipo',
|
||||||
|
'options' => ['VIP + LUNCH', 'NORMAL'],
|
||||||
|
],
|
||||||
|
'sector' => [
|
||||||
|
'name' => 'Sector',
|
||||||
|
'options' => ['A', 'B', 'C', 'D'],
|
||||||
|
],
|
||||||
|
'fila' => [
|
||||||
|
'name' => 'Fila',
|
||||||
|
'options' => array_map('strval', range(1, 17)),
|
||||||
|
],
|
||||||
|
'asiento' => [
|
||||||
|
'name' => 'Asiento',
|
||||||
|
'options' => array_map('strval', range(1, 5)),
|
||||||
|
],
|
||||||
|
];
|
||||||
|
$attributeIds = [];
|
||||||
|
|
||||||
|
foreach ($attributes as $code => $definition) {
|
||||||
|
$attributeId = DB::table('attribute')->insertGetId([
|
||||||
|
'tenant_codigo' => self::TENANT_CODE,
|
||||||
|
'codigo' => $code,
|
||||||
|
'nombre' => $definition['name'],
|
||||||
|
'is_required' => true,
|
||||||
|
'metadata_schema' => null,
|
||||||
|
'type' => 'select',
|
||||||
|
'created_at' => $now,
|
||||||
|
'updated_at' => $now,
|
||||||
|
]);
|
||||||
|
$attributeIds[$code] = $attributeId;
|
||||||
|
|
||||||
|
foreach ($definition['options'] as $index => $option) {
|
||||||
|
DB::table('attribute_options')->insert([
|
||||||
|
'attribute_id' => $attributeId,
|
||||||
|
'validity_time_id' => null,
|
||||||
|
'value' => $option,
|
||||||
|
'label' => $option,
|
||||||
|
'sort_order' => $index + 1,
|
||||||
|
'metadata' => null,
|
||||||
|
'created_at' => $now,
|
||||||
|
'updated_at' => $now,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$catalogItemId = DB::table('catalog_items')->insertGetId([
|
||||||
|
'tenant_code' => self::TENANT_CODE,
|
||||||
|
'category_id' => null,
|
||||||
|
'brand_id' => null,
|
||||||
|
'inventory_id' => null,
|
||||||
|
'type' => 'standard',
|
||||||
|
'slug' => 'entrada',
|
||||||
|
'nombre' => 'Entrada',
|
||||||
|
'descripcion' => 'Entrada para Desfile Pura Tendencia',
|
||||||
|
'precio' => 40000,
|
||||||
|
'inventory_policy' => 'tracked',
|
||||||
|
'has_tickets' => true,
|
||||||
|
'ticket_generation_policy' => 'one_per_unit',
|
||||||
|
'validity_time_id' => $validityTimeId,
|
||||||
|
'max_units_per_user' => null,
|
||||||
|
]);
|
||||||
|
$itemAttributeIds = [];
|
||||||
|
|
||||||
|
foreach (array_keys($attributes) as $index => $code) {
|
||||||
|
$itemAttributeIds[$code] = DB::table('item_attributes')->insertGetId([
|
||||||
|
'catalog_item_id' => $catalogItemId,
|
||||||
|
'attribute_id' => $attributeIds[$code],
|
||||||
|
'allow_multi_select' => false,
|
||||||
|
'sort_order' => $index + 1,
|
||||||
|
'created_at' => $now,
|
||||||
|
'updated_at' => $now,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach (['A', 'B', 'C', 'D'] as $sector) {
|
||||||
|
$lastRow = in_array($sector, ['B', 'D'], true) ? 16 : 17;
|
||||||
|
|
||||||
|
foreach (range(1, $lastRow) as $row) {
|
||||||
|
foreach (range(1, 5) as $seat) {
|
||||||
|
[$type, $price] = $this->entryTypeAndPrice($sector, $seat);
|
||||||
|
$inventoryId = DB::table('inventories')->insertGetId([
|
||||||
|
'sold_units' => 0,
|
||||||
|
'reserved_stock' => 0,
|
||||||
|
'real_stock' => 1,
|
||||||
|
]);
|
||||||
|
$variantId = DB::table('variantes')->insertGetId([
|
||||||
|
'catalog_item_id' => $catalogItemId,
|
||||||
|
'event_date_id' => null,
|
||||||
|
'inventory_id' => $inventoryId,
|
||||||
|
'descripcion' => "Sector {$sector} - Fila {$row} - Asiento {$seat} - {$type}",
|
||||||
|
'precio' => $price,
|
||||||
|
]);
|
||||||
|
|
||||||
|
foreach ([
|
||||||
|
'tipo' => $type,
|
||||||
|
'sector' => $sector,
|
||||||
|
'fila' => (string) $row,
|
||||||
|
'asiento' => (string) $seat,
|
||||||
|
] as $code => $value) {
|
||||||
|
DB::table('variant_values')->insert([
|
||||||
|
'variant_id' => $variantId,
|
||||||
|
'item_attribute_id' => $itemAttributeIds[$code],
|
||||||
|
'value' => $value,
|
||||||
|
'created_at' => $now,
|
||||||
|
'updated_at' => $now,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$entryImageId = $this->storeImage(
|
||||||
|
'images/tennants/desfile_pura_tendencia/catalog/entrada_pasarela.png',
|
||||||
|
'entrada_pasarela.png',
|
||||||
|
'catalog-items',
|
||||||
|
);
|
||||||
|
|
||||||
|
DB::table('catalog_items_attachments')->insert([
|
||||||
|
'variant_id' => null,
|
||||||
|
'catalog_item_id' => $catalogItemId,
|
||||||
|
'attachment_id' => $entryImageId,
|
||||||
|
'orden' => 0,
|
||||||
|
]);
|
||||||
|
|
||||||
|
DB::table('featured_groups')->insert([
|
||||||
|
'tenant_code' => self::TENANT_CODE,
|
||||||
|
'source_type' => 'all',
|
||||||
|
'category_id' => null,
|
||||||
|
'product_layout' => 'ticket_selector',
|
||||||
|
'group_layout' => 'single',
|
||||||
|
'group_name' => 'Entradas',
|
||||||
|
'group_order' => 0,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @return array{string, int} */
|
||||||
|
private function entryTypeAndPrice(string $sector, int $seat): array
|
||||||
|
{
|
||||||
|
$prices = in_array($sector, ['A', 'C'], true)
|
||||||
|
? [1 => 250000, 2 => 200000, 3 => 100000, 4 => 75000, 5 => 50000]
|
||||||
|
: [1 => 240000, 2 => 190000, 3 => 90000, 4 => 65000, 5 => 40000];
|
||||||
|
|
||||||
|
return [
|
||||||
|
$seat <= 2 ? 'VIP + LUNCH' : 'NORMAL',
|
||||||
|
$prices[$seat],
|
||||||
|
];
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use Illuminate\Database\Migrations\Migration;
|
||||||
|
use Illuminate\Support\Collection;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
|
||||||
|
return new class extends Migration
|
||||||
|
{
|
||||||
|
private const TENANT_CODE = 'desfile_pura_tendencia';
|
||||||
|
|
||||||
|
private const CATALOG_SLUG = 'entrada';
|
||||||
|
|
||||||
|
public function up(): void
|
||||||
|
{
|
||||||
|
$variantIds = $this->variantIds();
|
||||||
|
|
||||||
|
if ($variantIds->isEmpty()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
DB::transaction(function () use ($variantIds): void {
|
||||||
|
DB::table('variant_event_dates')
|
||||||
|
->whereIn('variant_id', $variantIds)
|
||||||
|
->delete();
|
||||||
|
|
||||||
|
DB::table('variantes')
|
||||||
|
->whereIn('id', $variantIds)
|
||||||
|
->update(['event_date_id' => null]);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public function down(): void
|
||||||
|
{
|
||||||
|
$eventDateId = DB::table('event_dates')
|
||||||
|
->where('tenant_code', self::TENANT_CODE)
|
||||||
|
->where('date', '2026-10-16')
|
||||||
|
->value('id');
|
||||||
|
$variantIds = $this->variantIds();
|
||||||
|
|
||||||
|
if ($eventDateId === null || $variantIds->isEmpty()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
DB::transaction(function () use ($eventDateId, $variantIds): void {
|
||||||
|
DB::table('variantes')
|
||||||
|
->whereIn('id', $variantIds)
|
||||||
|
->update(['event_date_id' => $eventDateId]);
|
||||||
|
|
||||||
|
foreach ($variantIds as $variantId) {
|
||||||
|
DB::table('variant_event_dates')->insertOrIgnore([
|
||||||
|
'variant_id' => $variantId,
|
||||||
|
'event_date_id' => $eventDateId,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private function variantIds(): Collection
|
||||||
|
{
|
||||||
|
return DB::table('variantes')
|
||||||
|
->join('catalog_items', 'catalog_items.id', '=', 'variantes.catalog_item_id')
|
||||||
|
->where('catalog_items.tenant_code', self::TENANT_CODE)
|
||||||
|
->where('catalog_items.slug', self::CATALOG_SLUG)
|
||||||
|
->pluck('variantes.id');
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
<?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('tenants', function (Blueprint $table): void {
|
||||||
|
$table->boolean('display_cart')->default(true)->after('display_seach_bar');
|
||||||
|
});
|
||||||
|
|
||||||
|
DB::table('tenants')->update(['display_cart' => true]);
|
||||||
|
DB::table('tenants')
|
||||||
|
->where('codigo', 'desfile_pura_tendencia')
|
||||||
|
->update(['display_cart' => false]);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function down(): void
|
||||||
|
{
|
||||||
|
Schema::table('tenants', function (Blueprint $table): void {
|
||||||
|
$table->dropColumn('display_cart');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use Illuminate\Database\Migrations\Migration;
|
||||||
|
use Illuminate\Database\Schema\Blueprint;
|
||||||
|
use Illuminate\Support\Facades\Schema;
|
||||||
|
|
||||||
|
return new class extends Migration
|
||||||
|
{
|
||||||
|
public function up(): void
|
||||||
|
{
|
||||||
|
Schema::table('tenants', function (Blueprint $table): void {
|
||||||
|
$table->foreignId('header_bg_image_id')
|
||||||
|
->nullable()
|
||||||
|
->after('footer_logo_id')
|
||||||
|
->constrained('attachments')
|
||||||
|
->nullOnDelete();
|
||||||
|
$table->foreignId('footer_bg_image_id')
|
||||||
|
->nullable()
|
||||||
|
->after('header_bg_image_id')
|
||||||
|
->constrained('attachments')
|
||||||
|
->nullOnDelete();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public function down(): void
|
||||||
|
{
|
||||||
|
Schema::table('tenants', function (Blueprint $table): void {
|
||||||
|
$table->dropConstrainedForeignId('footer_bg_image_id');
|
||||||
|
$table->dropConstrainedForeignId('header_bg_image_id');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use Illuminate\Database\Migrations\Migration;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Illuminate\Support\Facades\Storage;
|
||||||
|
use Illuminate\Support\Str;
|
||||||
|
|
||||||
|
return new class extends Migration
|
||||||
|
{
|
||||||
|
private const TENANT_CODE = 'desfile_pura_tendencia';
|
||||||
|
|
||||||
|
private const FILENAME = 'desfile_pura_tendencia_footer_background.png';
|
||||||
|
|
||||||
|
public function up(): void
|
||||||
|
{
|
||||||
|
$tenant = DB::table('tenants')
|
||||||
|
->where('codigo', self::TENANT_CODE)
|
||||||
|
->first(['id', 'footer_bg_image_id']);
|
||||||
|
|
||||||
|
if ($tenant === null || $tenant->footer_bg_image_id !== null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$sourcePath = public_path(
|
||||||
|
'images/tennants/desfile_pura_tendencia/'.self::FILENAME
|
||||||
|
);
|
||||||
|
|
||||||
|
if (! is_file($sourcePath)) {
|
||||||
|
throw new RuntimeException("Image not found at path: {$sourcePath}");
|
||||||
|
}
|
||||||
|
|
||||||
|
$contents = file_get_contents($sourcePath);
|
||||||
|
|
||||||
|
if ($contents === false) {
|
||||||
|
throw new RuntimeException("Could not read image at path: {$sourcePath}");
|
||||||
|
}
|
||||||
|
|
||||||
|
$key = (string) Str::uuid();
|
||||||
|
$storedPath = 'tenants/'.self::TENANT_CODE.'/'.$key.'.png';
|
||||||
|
|
||||||
|
if (! Storage::disk('s3')->put($storedPath, $contents)) {
|
||||||
|
throw new RuntimeException("Could not store image at path: {$storedPath}");
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
DB::transaction(function () use ($contents, $key, $storedPath): void {
|
||||||
|
$attachmentId = DB::table('attachments')->insertGetId([
|
||||||
|
'key' => $key,
|
||||||
|
'path' => $storedPath,
|
||||||
|
'filename' => self::FILENAME,
|
||||||
|
'type' => 'image',
|
||||||
|
'mime_type' => 'image/png',
|
||||||
|
'extension' => 'png',
|
||||||
|
'size' => strlen($contents),
|
||||||
|
'created_at' => now(),
|
||||||
|
'updated_at' => now(),
|
||||||
|
]);
|
||||||
|
|
||||||
|
DB::table('tenants')
|
||||||
|
->where('codigo', self::TENANT_CODE)
|
||||||
|
->update([
|
||||||
|
'footer_bg_image_id' => $attachmentId,
|
||||||
|
'updated_at' => now(),
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
} catch (Throwable $throwable) {
|
||||||
|
Storage::disk('s3')->delete($storedPath);
|
||||||
|
|
||||||
|
throw $throwable;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public function down(): void
|
||||||
|
{
|
||||||
|
// The attachment may already be referenced externally; keep this data
|
||||||
|
// migration irreversible instead of deleting a potentially active asset.
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use App\Domains\Catalog\Enums\InventorySubject;
|
||||||
|
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('catalog_items', function (Blueprint $table): void {
|
||||||
|
$table->enum('inventory_subject', InventorySubject::values())
|
||||||
|
->default(InventorySubject::Product->value)
|
||||||
|
->after('inventory_policy');
|
||||||
|
});
|
||||||
|
|
||||||
|
DB::table('catalog_items')
|
||||||
|
->where('tenant_code', 'desfile_pura_tendencia')
|
||||||
|
->where('slug', 'entrada')
|
||||||
|
->update(['inventory_subject' => InventorySubject::Seat->value]);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function down(): void
|
||||||
|
{
|
||||||
|
Schema::table('catalog_items', function (Blueprint $table): void {
|
||||||
|
$table->dropColumn('inventory_subject');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -2,6 +2,7 @@
|
|||||||
|
|
||||||
namespace Database\Seeders;
|
namespace Database\Seeders;
|
||||||
|
|
||||||
|
use App\Domains\Authorization\Enums\PermissionCode;
|
||||||
use App\Domains\Authorization\Enums\RoleCode;
|
use App\Domains\Authorization\Enums\RoleCode;
|
||||||
use App\Domains\Authorization\Models\Permission;
|
use App\Domains\Authorization\Models\Permission;
|
||||||
use App\Domains\Authorization\Models\Role;
|
use App\Domains\Authorization\Models\Role;
|
||||||
@@ -81,7 +82,7 @@ class AuthorizationSeeder extends Seeder
|
|||||||
'nombre' => 'Gestionar tickets',
|
'nombre' => 'Gestionar tickets',
|
||||||
'descripcion' => 'Permite emitir, invalidar o regenerar tickets.',
|
'descripcion' => 'Permite emitir, invalidar o regenerar tickets.',
|
||||||
],
|
],
|
||||||
'tickets.escanear' => [
|
PermissionCode::ScanTickets->value => [
|
||||||
'nombre' => 'Escanear tickets',
|
'nombre' => 'Escanear tickets',
|
||||||
'descripcion' => 'Permite validar y consumir tickets de las categorías asignadas al usuario.',
|
'descripcion' => 'Permite validar y consumir tickets de las categorías asignadas al usuario.',
|
||||||
],
|
],
|
||||||
@@ -119,12 +120,12 @@ class AuthorizationSeeder extends Seeder
|
|||||||
RoleCode::AdminApp->value => [
|
RoleCode::AdminApp->value => [
|
||||||
'nombre' => 'Administrador de la aplicación',
|
'nombre' => 'Administrador de la aplicación',
|
||||||
'descripcion' => 'Accede a los menús administrativos de la aplicación.',
|
'descripcion' => 'Accede a los menús administrativos de la aplicación.',
|
||||||
'permisos' => [],
|
'permisos' => [PermissionCode::ScanTickets->value],
|
||||||
],
|
],
|
||||||
RoleCode::Scanner->value => [
|
RoleCode::Scanner->value => [
|
||||||
'nombre' => 'Scanner',
|
'nombre' => 'Scanner',
|
||||||
'descripcion' => 'Valida y consume tickets de las categorías que tiene asignadas.',
|
'descripcion' => 'Valida y consume tickets de las categorías que tiene asignadas.',
|
||||||
'permisos' => ['tickets.escanear'],
|
'permisos' => [PermissionCode::ScanTickets->value],
|
||||||
],
|
],
|
||||||
RoleCode::User->value => [
|
RoleCode::User->value => [
|
||||||
'nombre' => 'Usuario',
|
'nombre' => 'Usuario',
|
||||||
|
|||||||
@@ -29,6 +29,13 @@ class MenuSeeder extends Seeder
|
|||||||
'content_type' => Menu::CONTENT_TYPE_DYNAMIC,
|
'content_type' => Menu::CONTENT_TYPE_DYNAMIC,
|
||||||
'route' => '/',
|
'route' => '/',
|
||||||
],
|
],
|
||||||
|
['code' => 'scanner.inicio', 'label' => 'Inicio', 'route' => '/scanner/inicio'],
|
||||||
|
['code' => 'scanner.scan', 'label' => 'Escanear', 'route' => '/scanner/scan'],
|
||||||
|
[
|
||||||
|
'code' => 'scanner.detail',
|
||||||
|
'label' => 'Detalle',
|
||||||
|
'route' => '/scanner/detail/:id',
|
||||||
|
],
|
||||||
[
|
[
|
||||||
'code' => 'adminapp.event',
|
'code' => 'adminapp.event',
|
||||||
'label' => 'Eventos',
|
'label' => 'Eventos',
|
||||||
@@ -219,8 +226,11 @@ class MenuSeeder extends Seeder
|
|||||||
->where('code', 'main.adminapp')
|
->where('code', 'main.adminapp')
|
||||||
->orWhere('parent_menu_code', 'main.adminapp')
|
->orWhere('parent_menu_code', 'main.adminapp')
|
||||||
->pluck('code');
|
->pluck('code');
|
||||||
|
$scannerMenuCodes = Menu::query()
|
||||||
|
->where('code', 'like', 'scanner.%')
|
||||||
|
->pluck('code');
|
||||||
$userMenuCodes = Menu::query()
|
$userMenuCodes = Menu::query()
|
||||||
->whereNotIn('code', $adminAppMenuCodes)
|
->whereNotIn('code', $adminAppMenuCodes->merge($scannerMenuCodes))
|
||||||
->pluck('code');
|
->pluck('code');
|
||||||
|
|
||||||
Role::query()
|
Role::query()
|
||||||
@@ -231,6 +241,10 @@ class MenuSeeder extends Seeder
|
|||||||
->where('codigo', RoleCode::User->value)
|
->where('codigo', RoleCode::User->value)
|
||||||
->each(fn (Role $role) => $role->menus()->sync($userMenuCodes));
|
->each(fn (Role $role) => $role->menus()->sync($userMenuCodes));
|
||||||
|
|
||||||
|
Role::query()
|
||||||
|
->where('codigo', RoleCode::Scanner->value)
|
||||||
|
->each(fn (Role $role) => $role->menus()->sync($scannerMenuCodes));
|
||||||
|
|
||||||
$tenants = Tenant::all();
|
$tenants = Tenant::all();
|
||||||
|
|
||||||
$allMenus = Menu::pluck('code')->toArray();
|
$allMenus = Menu::pluck('code')->toArray();
|
||||||
|
|||||||
@@ -58,6 +58,7 @@ class TenantSeeder extends Seeder
|
|||||||
'footer_bg_color' => '#313131',
|
'footer_bg_color' => '#313131',
|
||||||
'display_categories' => true,
|
'display_categories' => true,
|
||||||
'display_seach_bar' => true,
|
'display_seach_bar' => true,
|
||||||
|
'display_cart' => true,
|
||||||
'header_logo' => $this->uploadedImage('images/tennants/sonder/sonder_header.png', 'sonder_header.png'),
|
'header_logo' => $this->uploadedImage('images/tennants/sonder/sonder_header.png', 'sonder_header.png'),
|
||||||
'footer_logo' => $this->uploadedImage('images/tennants/sonder/sonder_footer.png', 'sonder_footer.png'),
|
'footer_logo' => $this->uploadedImage('images/tennants/sonder/sonder_footer.png', 'sonder_footer.png'),
|
||||||
'social_media' => self::SOCIAL_MEDIA,
|
'social_media' => self::SOCIAL_MEDIA,
|
||||||
@@ -111,6 +112,7 @@ class TenantSeeder extends Seeder
|
|||||||
'footer_bg_color' => '#015327',
|
'footer_bg_color' => '#015327',
|
||||||
'display_categories' => false,
|
'display_categories' => false,
|
||||||
'display_seach_bar' => false,
|
'display_seach_bar' => false,
|
||||||
|
'display_cart' => true,
|
||||||
'header_logo' => $this->uploadedImage(
|
'header_logo' => $this->uploadedImage(
|
||||||
'images/tennants/fiesta_futbol_infantil/futbol_infantil_header.png',
|
'images/tennants/fiesta_futbol_infantil/futbol_infantil_header.png',
|
||||||
'futbol_infantil_header.png',
|
'futbol_infantil_header.png',
|
||||||
|
|||||||
@@ -31,6 +31,7 @@ class WebsiteTypeSeeder extends Seeder
|
|||||||
[
|
[
|
||||||
'nombre' => 'ShopIt',
|
'nombre' => 'ShopIt',
|
||||||
'dominio' => 'localhost',
|
'dominio' => 'localhost',
|
||||||
|
'scanner_domain' => 'scanner.localhost',
|
||||||
...self::PRESENTATION,
|
...self::PRESENTATION,
|
||||||
'site_logo' => $this->onTicketLogo(),
|
'site_logo' => $this->onTicketLogo(),
|
||||||
'footer_logo' => $this->onTicketFooterLogo(),
|
'footer_logo' => $this->onTicketFooterLogo(),
|
||||||
@@ -63,6 +64,7 @@ class WebsiteTypeSeeder extends Seeder
|
|||||||
[
|
[
|
||||||
'nombre' => 'OnTicket',
|
'nombre' => 'OnTicket',
|
||||||
'dominio' => 'onticket.localhost',
|
'dominio' => 'onticket.localhost',
|
||||||
|
'scanner_domain' => 'scanner.onticket.localhost',
|
||||||
...self::PRESENTATION,
|
...self::PRESENTATION,
|
||||||
'site_logo' => $this->onTicketLogo(),
|
'site_logo' => $this->onTicketLogo(),
|
||||||
'footer_logo' => $this->onTicketFooterLogo(),
|
'footer_logo' => $this->onTicketFooterLogo(),
|
||||||
|
|||||||
@@ -42,7 +42,12 @@ return [
|
|||||||
'cannot_confirm' => 'A cancelled, rejected, or expired purchase cannot be confirmed.',
|
'cannot_confirm' => 'A cancelled, rejected, or expired purchase cannot be confirmed.',
|
||||||
'inconsistent_reservation' => 'The purchase has an inconsistent stock reservation.',
|
'inconsistent_reservation' => 'The purchase has an inconsistent stock reservation.',
|
||||||
'paid_cannot_cancel' => 'A paid purchase cannot be cancelled.',
|
'paid_cannot_cancel' => 'A paid purchase cannot be cancelled.',
|
||||||
'direct_item_max_stock' => 'There is not enough stock. Maximum available: :max.',
|
'stock' => [
|
||||||
|
'seat_unavailable' => 'Seat :selection is no longer available.',
|
||||||
|
'ticket_unavailable' => 'Ticket :selection is no longer available.',
|
||||||
|
'product_unavailable' => 'There is not enough stock for :selection. Maximum available: :max.',
|
||||||
|
'product_selection' => ':product (:selection)',
|
||||||
|
],
|
||||||
'empty_cart' => 'The selected cart does not contain items.',
|
'empty_cart' => 'The selected cart does not contain items.',
|
||||||
'catalog_item_missing' => 'One or more catalog items could not be loaded.',
|
'catalog_item_missing' => 'One or more catalog items could not be loaded.',
|
||||||
'catalog_item_wrong_tenant' => 'One or more catalog items do not belong to the tenant.',
|
'catalog_item_wrong_tenant' => 'One or more catalog items do not belong to the tenant.',
|
||||||
@@ -62,6 +67,10 @@ return [
|
|||||||
'invalid_variant' => 'Variant :variant does not belong to product :product.',
|
'invalid_variant' => 'Variant :variant does not belong to product :product.',
|
||||||
'purchase_without_user' => 'Purchase :purchase does not have an associated user.',
|
'purchase_without_user' => 'Purchase :purchase does not have an associated user.',
|
||||||
'product_not_found' => 'The product for purchase item :purchase_item was not found.',
|
'product_not_found' => 'The product for purchase item :purchase_item was not found.',
|
||||||
|
'already_scanned' => 'The ticket has already been scanned.',
|
||||||
|
'expired_for_scan' => 'The ticket has expired.',
|
||||||
|
'not_valid_for_scan' => 'The ticket is not currently valid.',
|
||||||
|
'scanner_category_forbidden' => 'The scanner is not assigned to the ticket category.',
|
||||||
],
|
],
|
||||||
'integration' => [
|
'integration' => [
|
||||||
'not_configured' => 'The integration is not configured for this tenant.',
|
'not_configured' => 'The integration is not configured for this tenant.',
|
||||||
@@ -76,6 +85,13 @@ return [
|
|||||||
'test_sent' => 'Test email sent successfully.',
|
'test_sent' => 'Test email sent successfully.',
|
||||||
],
|
],
|
||||||
'catalog' => [
|
'catalog' => [
|
||||||
|
'attribute_labels' => [
|
||||||
|
'tipo' => 'Type',
|
||||||
|
'sector' => 'Sector',
|
||||||
|
'fila' => 'Row',
|
||||||
|
'asiento' => 'Seat',
|
||||||
|
'event_date' => 'Date',
|
||||||
|
],
|
||||||
'standard_with_components' => 'A standard item cannot have components.',
|
'standard_with_components' => 'A standard item cannot have components.',
|
||||||
'duplicate_component' => 'The component is duplicated.',
|
'duplicate_component' => 'The component is duplicated.',
|
||||||
'component_wrong_tenant' => 'The item does not belong to the bundle tenant.',
|
'component_wrong_tenant' => 'The item does not belong to the bundle tenant.',
|
||||||
|
|||||||
@@ -42,7 +42,12 @@ return [
|
|||||||
'cannot_confirm' => 'Una compra cancelada, rechazada o vencida no se puede confirmar.',
|
'cannot_confirm' => 'Una compra cancelada, rechazada o vencida no se puede confirmar.',
|
||||||
'inconsistent_reservation' => 'La compra tiene una reserva de stock inconsistente.',
|
'inconsistent_reservation' => 'La compra tiene una reserva de stock inconsistente.',
|
||||||
'paid_cannot_cancel' => 'Una compra pagada no se puede cancelar.',
|
'paid_cannot_cancel' => 'Una compra pagada no se puede cancelar.',
|
||||||
'direct_item_max_stock' => 'Stock insuficiente. Máximo disponible: :max.',
|
'stock' => [
|
||||||
|
'seat_unavailable' => 'El asiento :selection ya no está disponible.',
|
||||||
|
'ticket_unavailable' => 'La entrada :selection ya no está disponible.',
|
||||||
|
'product_unavailable' => 'No hay stock suficiente de :selection. Máximo disponible: :max.',
|
||||||
|
'product_selection' => ':product (:selection)',
|
||||||
|
],
|
||||||
'empty_cart' => 'El carrito seleccionado no contiene productos.',
|
'empty_cart' => 'El carrito seleccionado no contiene productos.',
|
||||||
'catalog_item_missing' => 'No se pudieron cargar uno o más productos del catálogo.',
|
'catalog_item_missing' => 'No se pudieron cargar uno o más productos del catálogo.',
|
||||||
'catalog_item_wrong_tenant' => 'Uno o más productos no pertenecen al tenant.',
|
'catalog_item_wrong_tenant' => 'Uno o más productos no pertenecen al tenant.',
|
||||||
@@ -62,6 +67,10 @@ return [
|
|||||||
'invalid_variant' => 'La variante :variant no pertenece al producto :product.',
|
'invalid_variant' => 'La variante :variant no pertenece al producto :product.',
|
||||||
'purchase_without_user' => 'La compra :purchase no tiene un usuario asociado.',
|
'purchase_without_user' => 'La compra :purchase no tiene un usuario asociado.',
|
||||||
'product_not_found' => 'No se encontró el producto de la línea de compra :purchase_item.',
|
'product_not_found' => 'No se encontró el producto de la línea de compra :purchase_item.',
|
||||||
|
'already_scanned' => 'El ticket ya fue escaneado.',
|
||||||
|
'expired_for_scan' => 'El ticket está vencido.',
|
||||||
|
'not_valid_for_scan' => 'El ticket no es válido en este momento.',
|
||||||
|
'scanner_category_forbidden' => 'El scanner no está asignado a la categoría del ticket.',
|
||||||
],
|
],
|
||||||
'integration' => [
|
'integration' => [
|
||||||
'not_configured' => 'La integración no está configurada para este tenant.',
|
'not_configured' => 'La integración no está configurada para este tenant.',
|
||||||
@@ -76,6 +85,13 @@ return [
|
|||||||
'test_sent' => 'Correo de prueba enviado correctamente.',
|
'test_sent' => 'Correo de prueba enviado correctamente.',
|
||||||
],
|
],
|
||||||
'catalog' => [
|
'catalog' => [
|
||||||
|
'attribute_labels' => [
|
||||||
|
'tipo' => 'Tipo',
|
||||||
|
'sector' => 'Sector',
|
||||||
|
'fila' => 'Fila',
|
||||||
|
'asiento' => 'Asiento',
|
||||||
|
'event_date' => 'Fecha',
|
||||||
|
],
|
||||||
'standard_with_components' => 'Un ítem standard no puede tener componentes.',
|
'standard_with_components' => 'Un ítem standard no puede tener componentes.',
|
||||||
'duplicate_component' => 'El componente está duplicado.',
|
'duplicate_component' => 'El componente está duplicado.',
|
||||||
'component_wrong_tenant' => 'El ítem no pertenece al tenant del bundle.',
|
'component_wrong_tenant' => 'El ítem no pertenece al tenant del bundle.',
|
||||||
|
|||||||
|
After Width: | Height: | Size: 333 KiB |
|
After Width: | Height: | Size: 1.8 KiB |
|
After Width: | Height: | Size: 53 KiB |
|
After Width: | Height: | Size: 6.2 KiB |
|
After Width: | Height: | Size: 1.2 MiB |
|
Before Width: | Height: | Size: 45 KiB After Width: | Height: | Size: 45 KiB |
|
Before Width: | Height: | Size: 54 KiB After Width: | Height: | Size: 54 KiB |
|
Before Width: | Height: | Size: 91 KiB After Width: | Height: | Size: 91 KiB |
|
Before Width: | Height: | Size: 92 KiB After Width: | Height: | Size: 92 KiB |
|
Before Width: | Height: | Size: 49 KiB After Width: | Height: | Size: 49 KiB |
|
Before Width: | Height: | Size: 1.0 MiB After Width: | Height: | Size: 1.0 MiB |
|
Before Width: | Height: | Size: 61 KiB After Width: | Height: | Size: 61 KiB |
|
Before Width: | Height: | Size: 73 KiB After Width: | Height: | Size: 73 KiB |
|
Before Width: | Height: | Size: 50 KiB After Width: | Height: | Size: 50 KiB |
|
Before Width: | Height: | Size: 458 KiB After Width: | Height: | Size: 458 KiB |
|
Before Width: | Height: | Size: 128 KiB After Width: | Height: | Size: 128 KiB |
|
Before Width: | Height: | Size: 103 KiB After Width: | Height: | Size: 103 KiB |
|
Before Width: | Height: | Size: 3.2 KiB After Width: | Height: | Size: 3.2 KiB |
|
Before Width: | Height: | Size: 94 KiB After Width: | Height: | Size: 94 KiB |
|
Before Width: | Height: | Size: 33 KiB After Width: | Height: | Size: 33 KiB |
|
Before Width: | Height: | Size: 208 KiB After Width: | Height: | Size: 208 KiB |
|
Before Width: | Height: | Size: 40 KiB After Width: | Height: | Size: 40 KiB |
|
Before Width: | Height: | Size: 76 KiB After Width: | Height: | Size: 76 KiB |
|
Before Width: | Height: | Size: 165 KiB After Width: | Height: | Size: 165 KiB |
|
Before Width: | Height: | Size: 15 KiB After Width: | Height: | Size: 15 KiB |
|
Before Width: | Height: | Size: 16 KiB After Width: | Height: | Size: 16 KiB |
|
Before Width: | Height: | Size: 96 KiB After Width: | Height: | Size: 96 KiB |
|
Before Width: | Height: | Size: 386 KiB After Width: | Height: | Size: 386 KiB |
116
tests/Feature/Auth/ScannerLoginControllerTest.php
Normal file
@@ -0,0 +1,116 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Tests\Feature\Auth;
|
||||||
|
|
||||||
|
use App\Domains\Auth\Models\LoginAttempt;
|
||||||
|
use App\Domains\Auth\Models\User;
|
||||||
|
use App\Domains\Authorization\Enums\PermissionCode;
|
||||||
|
use App\Domains\Authorization\Enums\RoleCode;
|
||||||
|
use App\Domains\Authorization\Models\Permission;
|
||||||
|
use App\Domains\Authorization\Models\Role;
|
||||||
|
use App\Domains\Tenant\Models\Tenant;
|
||||||
|
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||||
|
use Illuminate\Support\Facades\Hash;
|
||||||
|
use Tests\TestCase;
|
||||||
|
|
||||||
|
class ScannerLoginControllerTest extends TestCase
|
||||||
|
{
|
||||||
|
use RefreshDatabase;
|
||||||
|
|
||||||
|
public function test_it_logs_in_a_tenant_bound_user_with_scan_permission(): void
|
||||||
|
{
|
||||||
|
$role = Role::query()->create([
|
||||||
|
'codigo' => RoleCode::AdminApp->value,
|
||||||
|
'nombre' => 'Operador',
|
||||||
|
]);
|
||||||
|
$permission = Permission::query()->create([
|
||||||
|
'codigo' => PermissionCode::ScanTickets->value,
|
||||||
|
'nombre' => 'Escanear tickets',
|
||||||
|
]);
|
||||||
|
$role->permissions()->attach($permission->codigo);
|
||||||
|
$tenant = Tenant::query()->create([
|
||||||
|
'codigo' => 'acme',
|
||||||
|
'nombre' => 'Acme',
|
||||||
|
'dominio' => 'acme.test',
|
||||||
|
]);
|
||||||
|
$user = User::factory()->create([
|
||||||
|
'email' => 'scanner@example.com',
|
||||||
|
'password' => Hash::make('secret123'),
|
||||||
|
'rol_codigo' => $role->codigo,
|
||||||
|
'tenant_codigo' => $tenant->codigo,
|
||||||
|
]);
|
||||||
|
|
||||||
|
$response = $this->postJson('/api/v1/scanner/login', [
|
||||||
|
'email' => ' SCANNER@EXAMPLE.COM ',
|
||||||
|
'password' => 'secret123',
|
||||||
|
]);
|
||||||
|
|
||||||
|
$response
|
||||||
|
->assertOk()
|
||||||
|
->assertJsonPath('user.id', $user->id)
|
||||||
|
->assertJsonPath('user.rol_codigo', RoleCode::AdminApp->value)
|
||||||
|
->assertJsonPath('token_type', 'Bearer');
|
||||||
|
|
||||||
|
$this->assertSame(['scanner'], $user->tokens()->sole()->abilities);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_it_rejects_a_user_without_scan_permission(): void
|
||||||
|
{
|
||||||
|
$role = Role::query()->create([
|
||||||
|
'codigo' => RoleCode::Scanner->value,
|
||||||
|
'nombre' => 'Scanner sin permiso',
|
||||||
|
]);
|
||||||
|
$tenant = Tenant::query()->create([
|
||||||
|
'codigo' => 'acme',
|
||||||
|
'nombre' => 'Acme',
|
||||||
|
'dominio' => 'acme.test',
|
||||||
|
]);
|
||||||
|
$user = User::factory()->create([
|
||||||
|
'email' => 'customer@example.com',
|
||||||
|
'password' => Hash::make('secret123'),
|
||||||
|
'rol_codigo' => $role->codigo,
|
||||||
|
'tenant_codigo' => $tenant->codigo,
|
||||||
|
]);
|
||||||
|
|
||||||
|
$this->postJson('/api/v1/scanner/login', [
|
||||||
|
'email' => $user->email,
|
||||||
|
'password' => 'secret123',
|
||||||
|
])->assertUnprocessable()->assertJsonValidationErrors(['email']);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_an_invalid_password_is_recorded_with_the_users_tenant(): void
|
||||||
|
{
|
||||||
|
$role = Role::query()->create([
|
||||||
|
'codigo' => RoleCode::Scanner->value,
|
||||||
|
'nombre' => 'Scanner',
|
||||||
|
]);
|
||||||
|
$permission = Permission::query()->create([
|
||||||
|
'codigo' => PermissionCode::ScanTickets->value,
|
||||||
|
'nombre' => 'Escanear tickets',
|
||||||
|
]);
|
||||||
|
$role->permissions()->attach($permission->codigo);
|
||||||
|
$tenant = Tenant::query()->create([
|
||||||
|
'codigo' => 'acme',
|
||||||
|
'nombre' => 'Acme',
|
||||||
|
'dominio' => 'acme.test',
|
||||||
|
]);
|
||||||
|
$user = User::factory()->create([
|
||||||
|
'email' => 'scanner@example.com',
|
||||||
|
'password' => Hash::make('correct-password'),
|
||||||
|
'rol_codigo' => $role->codigo,
|
||||||
|
'tenant_codigo' => $tenant->codigo,
|
||||||
|
]);
|
||||||
|
|
||||||
|
$this->postJson('/api/v1/scanner/login', [
|
||||||
|
'email' => $user->email,
|
||||||
|
'password' => 'wrong-password',
|
||||||
|
])->assertUnprocessable()->assertJsonValidationErrors(['email']);
|
||||||
|
|
||||||
|
$this->assertSame(1, $user->refresh()->failed_login_attempts);
|
||||||
|
$this->assertDatabaseHas('login_attempts', [
|
||||||
|
'user_id' => $user->id,
|
||||||
|
'tenant_codigo' => $tenant->codigo,
|
||||||
|
'outcome' => LoginAttempt::OUTCOME_INVALID_CREDENTIALS,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
}
|
||||||
68
tests/Feature/Auth/ScannerMeControllerTest.php
Normal file
@@ -0,0 +1,68 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Tests\Feature\Auth;
|
||||||
|
|
||||||
|
use App\Domains\Auth\Models\User;
|
||||||
|
use App\Domains\Authorization\Enums\PermissionCode;
|
||||||
|
use App\Domains\Authorization\Enums\RoleCode;
|
||||||
|
use App\Domains\Authorization\Models\Permission;
|
||||||
|
use App\Domains\Authorization\Models\Role;
|
||||||
|
use App\Domains\Menu\Models\Menu;
|
||||||
|
use App\Domains\Tenant\Models\Tenant;
|
||||||
|
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||||
|
use Laravel\Sanctum\Sanctum;
|
||||||
|
use Tests\TestCase;
|
||||||
|
|
||||||
|
class ScannerMeControllerTest extends TestCase
|
||||||
|
{
|
||||||
|
use RefreshDatabase;
|
||||||
|
|
||||||
|
public function test_it_returns_only_scanner_menus_assigned_to_the_tenant(): void
|
||||||
|
{
|
||||||
|
$scannerRole = Role::query()->create([
|
||||||
|
'codigo' => RoleCode::Scanner->value,
|
||||||
|
'nombre' => 'Scanner',
|
||||||
|
]);
|
||||||
|
$permission = Permission::query()->create([
|
||||||
|
'codigo' => PermissionCode::ScanTickets->value,
|
||||||
|
'nombre' => 'Escanear tickets',
|
||||||
|
]);
|
||||||
|
$scannerRole->permissions()->attach($permission->codigo);
|
||||||
|
$tenant = Tenant::query()->create([
|
||||||
|
'codigo' => 'acme',
|
||||||
|
'nombre' => 'Acme',
|
||||||
|
'dominio' => 'acme.test',
|
||||||
|
]);
|
||||||
|
$home = Menu::query()->create([
|
||||||
|
'code' => 'scanner.inicio',
|
||||||
|
'label' => 'Inicio',
|
||||||
|
'route' => '/scanner/inicio',
|
||||||
|
]);
|
||||||
|
$scan = Menu::query()->create([
|
||||||
|
'code' => 'scanner.scan',
|
||||||
|
'label' => 'Escanear',
|
||||||
|
'route' => '/scanner/scan',
|
||||||
|
]);
|
||||||
|
$foreign = Menu::query()->create([
|
||||||
|
'code' => 'adminapp.inicio',
|
||||||
|
'label' => 'Administración',
|
||||||
|
'route' => '/admin/inicio',
|
||||||
|
]);
|
||||||
|
|
||||||
|
$scannerRole->menus()->sync([$home->code, $scan->code]);
|
||||||
|
$tenant->menues()->sync([$home->code, $scan->code, $foreign->code]);
|
||||||
|
|
||||||
|
$user = User::factory()->create([
|
||||||
|
'rol_codigo' => $scannerRole->codigo,
|
||||||
|
'tenant_codigo' => $tenant->codigo,
|
||||||
|
]);
|
||||||
|
Sanctum::actingAs($user);
|
||||||
|
|
||||||
|
$this->getJson('/api/v1/scanner/me')
|
||||||
|
->assertOk()
|
||||||
|
->assertJsonPath('data.user.id', $user->id)
|
||||||
|
->assertJsonPath('data.tenant.codigo', $tenant->codigo)
|
||||||
|
->assertJsonCount(2, 'data.tenant.menues')
|
||||||
|
->assertJsonMissing(['code' => $foreign->code]);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -241,6 +241,32 @@ class CatalogControllerTest extends TestCase
|
|||||||
->assertJsonPath('0.nombre', 'carousel Item 1');
|
->assertJsonPath('0.nombre', 'carousel Item 1');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function test_single_group_layout_returns_only_its_first_available_item(): void
|
||||||
|
{
|
||||||
|
$tenant = $this->createTenant('catalog-single-layout');
|
||||||
|
$group = $this->createGroup(
|
||||||
|
$tenant,
|
||||||
|
ProductLayout::TicketSelector,
|
||||||
|
'Entradas',
|
||||||
|
groupLayout: GroupLayout::Single,
|
||||||
|
);
|
||||||
|
|
||||||
|
foreach (['Primera entrada', 'Segunda entrada'] as $order => $name) {
|
||||||
|
$item = $this->createItem($tenant, $name);
|
||||||
|
$group->featuredItems()->create([
|
||||||
|
'catalog_item_id' => $item->id,
|
||||||
|
'order' => $order,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->getJson("/api/tenants/{$tenant->codigo}/catalog")
|
||||||
|
->assertOk()
|
||||||
|
->assertJsonPath('0.layout', ProductLayout::TicketSelector->value)
|
||||||
|
->assertJsonPath('0.group_layout', GroupLayout::Single->value)
|
||||||
|
->assertJsonCount(1, '0.items')
|
||||||
|
->assertJsonPath('0.items.0.nombre', 'Primera entrada');
|
||||||
|
}
|
||||||
|
|
||||||
public function test_groups_can_source_items_from_a_category_or_the_entire_catalog(): void
|
public function test_groups_can_source_items_from_a_category_or_the_entire_catalog(): void
|
||||||
{
|
{
|
||||||
$tenant = $this->createTenant('catalog-sources');
|
$tenant = $this->createTenant('catalog-sources');
|
||||||
|
|||||||
@@ -0,0 +1,242 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Tests\Feature\Migrations;
|
||||||
|
|
||||||
|
use Database\Seeders\MenuSeeder;
|
||||||
|
use Database\Seeders\SocialMediaSeeder;
|
||||||
|
use Database\Seeders\TenantSeeder;
|
||||||
|
use Database\Seeders\WebsiteTypeSeeder;
|
||||||
|
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Illuminate\Support\Facades\Storage;
|
||||||
|
use Tests\TestCase;
|
||||||
|
|
||||||
|
class CreateDesfilePuraTendenciaTenantTest extends TestCase
|
||||||
|
{
|
||||||
|
use RefreshDatabase;
|
||||||
|
|
||||||
|
public function test_it_provisions_the_desfile_tenant_configuration(): void
|
||||||
|
{
|
||||||
|
Storage::fake('s3');
|
||||||
|
|
||||||
|
$this->seed([
|
||||||
|
WebsiteTypeSeeder::class,
|
||||||
|
SocialMediaSeeder::class,
|
||||||
|
TenantSeeder::class,
|
||||||
|
MenuSeeder::class,
|
||||||
|
]);
|
||||||
|
|
||||||
|
$migration = require database_path(
|
||||||
|
'migrations/2026_08_12_020000_create_desfile_pura_tendencia_tenant.php'
|
||||||
|
);
|
||||||
|
$migration->up();
|
||||||
|
|
||||||
|
$footerBackgroundMigration = require database_path(
|
||||||
|
'migrations/2026_08_12_060000_set_desfile_footer_background_image.php'
|
||||||
|
);
|
||||||
|
$footerBackgroundMigration->up();
|
||||||
|
|
||||||
|
$this->assertDatabaseHas('tenants', [
|
||||||
|
'codigo' => 'desfile_pura_tendencia',
|
||||||
|
'nombre' => 'Desfile Pura Tendencia',
|
||||||
|
'dominio' => 'desfile-pura-tendencia.localhost',
|
||||||
|
'website_type_code' => 'onticket',
|
||||||
|
'event_title' => 'Desfile Pura Tendencia',
|
||||||
|
'event_location' => 'Salón Centro Recreativo Luz y Fuerza',
|
||||||
|
'event_date_text' => '16 de Octubre 2026',
|
||||||
|
'primary_color' => '#BA69A9',
|
||||||
|
'secondary_color' => '#A0A0A0',
|
||||||
|
'danger_color' => '#FF8888',
|
||||||
|
'success_color' => '#198754',
|
||||||
|
'header_bg_color' => '#ffffff',
|
||||||
|
'footer_bg_color' => '#D4441C',
|
||||||
|
'display_categories' => false,
|
||||||
|
'display_seach_bar' => false,
|
||||||
|
]);
|
||||||
|
|
||||||
|
$eventDate = DB::table('event_dates')
|
||||||
|
->where('tenant_code', 'desfile_pura_tendencia')
|
||||||
|
->sole();
|
||||||
|
|
||||||
|
$this->assertSame('2026-10-16', $eventDate->date);
|
||||||
|
$this->assertSame('20:30:00', $eventDate->time_start);
|
||||||
|
$this->assertSame('23:59:00', $eventDate->time_end);
|
||||||
|
$this->assertDatabaseHas('validity_times', [
|
||||||
|
'id' => $eventDate->validity_time_id,
|
||||||
|
'type' => 'fixed_window',
|
||||||
|
'fixed_starts_at' => '2026-10-16 20:30:00',
|
||||||
|
'fixed_expires_at' => '2026-10-16 23:59:00',
|
||||||
|
]);
|
||||||
|
|
||||||
|
$hero = DB::table('websites_extras')
|
||||||
|
->join(
|
||||||
|
'website_type_extras',
|
||||||
|
'website_type_extras.id',
|
||||||
|
'=',
|
||||||
|
'websites_extras.website_type_extra_id',
|
||||||
|
)
|
||||||
|
->where('websites_extras.website_code', 'desfile_pura_tendencia')
|
||||||
|
->where('website_type_extras.codigo', 'heroConfig')
|
||||||
|
->value('websites_extras.config');
|
||||||
|
$hero = json_decode($hero, true, flags: JSON_THROW_ON_ERROR);
|
||||||
|
|
||||||
|
$this->assertSame('<h1>LA NOCHE DE LA MODA</h1>', $hero['title_html']);
|
||||||
|
$this->assertSame(
|
||||||
|
'Viví una experiencia de <b>Alta Costura con conducción exclusiva de Pampita</b> y las colecciones de Pucheta-Paz.',
|
||||||
|
$hero['description_html'],
|
||||||
|
);
|
||||||
|
$this->assertDatabaseHas('attachments', [
|
||||||
|
'id' => $hero['background_image_id'],
|
||||||
|
'filename' => 'desfile_pura_tendencia_hero.png',
|
||||||
|
'type' => 'image',
|
||||||
|
]);
|
||||||
|
$footerBackgroundImageId = DB::table('tenants')
|
||||||
|
->where('codigo', 'desfile_pura_tendencia')
|
||||||
|
->value('footer_bg_image_id');
|
||||||
|
$this->assertDatabaseHas('attachments', [
|
||||||
|
'id' => $footerBackgroundImageId,
|
||||||
|
'filename' => 'desfile_pura_tendencia_footer_background.png',
|
||||||
|
'type' => 'image',
|
||||||
|
]);
|
||||||
|
|
||||||
|
foreach ([
|
||||||
|
'desfile_pura_tendencia_header.png',
|
||||||
|
'desfile_pura_tendencia_footer.png',
|
||||||
|
'desfile_pura_tendencia_hero.png',
|
||||||
|
'desfile_pura_tendencia_footer_background.png',
|
||||||
|
'entrada_pasarela.png',
|
||||||
|
] as $filename) {
|
||||||
|
$path = DB::table('attachments')->where('filename', $filename)->value('path');
|
||||||
|
|
||||||
|
$this->assertNotNull($path);
|
||||||
|
Storage::disk('s3')->assertExists($path);
|
||||||
|
}
|
||||||
|
|
||||||
|
$expectedMenus = DB::table('tenants_menues')
|
||||||
|
->where('tenant_code', 'fiesta_futbol_infantil')
|
||||||
|
->where('menu_code', 'not like', 'adminapp.fiesta-futbol-infantil.%')
|
||||||
|
->orderBy('menu_code')
|
||||||
|
->pluck('menu_code')
|
||||||
|
->all();
|
||||||
|
$actualMenus = DB::table('tenants_menues')
|
||||||
|
->where('tenant_code', 'desfile_pura_tendencia')
|
||||||
|
->orderBy('menu_code')
|
||||||
|
->pluck('menu_code')
|
||||||
|
->all();
|
||||||
|
|
||||||
|
$this->assertSame($expectedMenus, $actualMenus);
|
||||||
|
$this->assertContains('main.adminapp', $actualMenus);
|
||||||
|
$this->assertContains('adminapp.event', $actualMenus);
|
||||||
|
$this->assertContains('scanner.scan', $actualMenus);
|
||||||
|
$this->assertNotContains('adminapp.fiesta-futbol-infantil.entradas', $actualMenus);
|
||||||
|
|
||||||
|
$catalogItem = DB::table('catalog_items')
|
||||||
|
->where('tenant_code', 'desfile_pura_tendencia')
|
||||||
|
->where('slug', 'entrada')
|
||||||
|
->sole();
|
||||||
|
|
||||||
|
$this->assertSame('Entrada', $catalogItem->nombre);
|
||||||
|
$this->assertSame('tracked', $catalogItem->inventory_policy);
|
||||||
|
$this->assertSame(1, $catalogItem->has_tickets);
|
||||||
|
$this->assertSame('one_per_unit', $catalogItem->ticket_generation_policy);
|
||||||
|
$this->assertSame($eventDate->validity_time_id, $catalogItem->validity_time_id);
|
||||||
|
$this->assertDatabaseHas('catalog_items_attachments', [
|
||||||
|
'catalog_item_id' => $catalogItem->id,
|
||||||
|
'variant_id' => null,
|
||||||
|
'orden' => 0,
|
||||||
|
]);
|
||||||
|
$this->assertDatabaseHas('featured_groups', [
|
||||||
|
'tenant_code' => 'desfile_pura_tendencia',
|
||||||
|
'source_type' => 'all',
|
||||||
|
'product_layout' => 'ticket_selector',
|
||||||
|
'group_layout' => 'single',
|
||||||
|
]);
|
||||||
|
|
||||||
|
$attributes = DB::table('attribute')
|
||||||
|
->where('tenant_codigo', 'desfile_pura_tendencia')
|
||||||
|
->orderBy('id')
|
||||||
|
->get()
|
||||||
|
->keyBy('codigo');
|
||||||
|
|
||||||
|
$this->assertSame(['tipo', 'sector', 'fila', 'asiento'], $attributes->keys()->all());
|
||||||
|
$this->assertSame([
|
||||||
|
'tipo' => ['VIP + LUNCH', 'NORMAL'],
|
||||||
|
'sector' => ['A', 'B', 'C', 'D'],
|
||||||
|
'fila' => array_map('strval', range(1, 17)),
|
||||||
|
'asiento' => array_map('strval', range(1, 5)),
|
||||||
|
], $attributes->map(fn (object $attribute): array => DB::table('attribute_options')
|
||||||
|
->where('attribute_id', $attribute->id)
|
||||||
|
->orderBy('sort_order')
|
||||||
|
->pluck('value')
|
||||||
|
->all())->all());
|
||||||
|
|
||||||
|
$variants = DB::table('variantes')->where('catalog_item_id', $catalogItem->id);
|
||||||
|
|
||||||
|
$this->assertSame(330, (clone $variants)->count());
|
||||||
|
$this->assertSame(1320, DB::table('variant_values')
|
||||||
|
->whereIn('variant_id', (clone $variants)->pluck('id'))
|
||||||
|
->count());
|
||||||
|
$this->assertSame(0, DB::table('variant_event_dates')
|
||||||
|
->whereIn('variant_id', (clone $variants)->pluck('id'))
|
||||||
|
->count());
|
||||||
|
$this->assertSame(330, (clone $variants)->whereNull('event_date_id')->count());
|
||||||
|
$this->assertSame(330, DB::table('inventories')
|
||||||
|
->whereIn('id', (clone $variants)->pluck('inventory_id'))
|
||||||
|
->where('real_stock', 1)
|
||||||
|
->where('reserved_stock', 0)
|
||||||
|
->where('sold_units', 0)
|
||||||
|
->count());
|
||||||
|
|
||||||
|
foreach ([
|
||||||
|
250000 => 34,
|
||||||
|
200000 => 34,
|
||||||
|
100000 => 34,
|
||||||
|
75000 => 34,
|
||||||
|
50000 => 34,
|
||||||
|
240000 => 32,
|
||||||
|
190000 => 32,
|
||||||
|
90000 => 32,
|
||||||
|
65000 => 32,
|
||||||
|
40000 => 32,
|
||||||
|
] as $price => $expectedCount) {
|
||||||
|
$this->assertSame($expectedCount, (clone $variants)->where('precio', $price)->count());
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->assertSame(0, $this->variantCountForSelection($catalogItem->id, [
|
||||||
|
'sector' => ['B', 'D'],
|
||||||
|
'fila' => ['17'],
|
||||||
|
]));
|
||||||
|
$this->assertSame(66, $this->variantCountForSelection($catalogItem->id, [
|
||||||
|
'tipo' => ['VIP + LUNCH'],
|
||||||
|
'asiento' => ['1'],
|
||||||
|
]));
|
||||||
|
$this->assertSame(66, $this->variantCountForSelection($catalogItem->id, [
|
||||||
|
'tipo' => ['NORMAL'],
|
||||||
|
'asiento' => ['5'],
|
||||||
|
]));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @param array<string, list<string>> $selection */
|
||||||
|
private function variantCountForSelection(int $catalogItemId, array $selection): int
|
||||||
|
{
|
||||||
|
$query = DB::table('variantes')->where('catalog_item_id', $catalogItemId);
|
||||||
|
|
||||||
|
foreach ($selection as $attributeCode => $values) {
|
||||||
|
$query->whereExists(fn ($subquery) => $subquery
|
||||||
|
->selectRaw('1')
|
||||||
|
->from('variant_values')
|
||||||
|
->join(
|
||||||
|
'item_attributes',
|
||||||
|
'item_attributes.id',
|
||||||
|
'=',
|
||||||
|
'variant_values.item_attribute_id',
|
||||||
|
)
|
||||||
|
->join('attribute', 'attribute.id', '=', 'item_attributes.attribute_id')
|
||||||
|
->whereColumn('variant_values.variant_id', 'variantes.id')
|
||||||
|
->where('attribute.codigo', $attributeCode)
|
||||||
|
->whereIn('variant_values.value', $values));
|
||||||
|
}
|
||||||
|
|
||||||
|
return $query->count();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -143,10 +143,12 @@ class StorePurchaseTest extends TestCase
|
|||||||
|
|
||||||
$response = $this->actingAs($user, 'sanctum')
|
$response = $this->actingAs($user, 'sanctum')
|
||||||
->postJson('/api/tenants/sonder/compras/start-checkout', [
|
->postJson('/api/tenants/sonder/compras/start-checkout', [
|
||||||
'direct_item' => [
|
'direct_items' => [
|
||||||
'catalog_item_id' => $variant->catalog_item_id,
|
[
|
||||||
'variant_id' => $variant->id,
|
'catalog_item_id' => $variant->catalog_item_id,
|
||||||
'cantidad' => 3,
|
'variant_id' => $variant->id,
|
||||||
|
'cantidad' => 3,
|
||||||
|
],
|
||||||
],
|
],
|
||||||
])
|
])
|
||||||
->assertCreated()
|
->assertCreated()
|
||||||
@@ -185,6 +187,105 @@ class StorePurchaseTest extends TestCase
|
|||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function test_it_creates_one_direct_purchase_with_multiple_variant_items(): void
|
||||||
|
{
|
||||||
|
$this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
|
||||||
|
$user = User::factory()->create();
|
||||||
|
$firstVariant = $this->createVariantForTenant('sonder', 1, '50.00');
|
||||||
|
$secondInventory = Inventory::query()->create(['real_stock' => 1]);
|
||||||
|
$secondVariant = Variant::query()->create([
|
||||||
|
'catalog_item_id' => $firstVariant->catalog_item_id,
|
||||||
|
'inventory_id' => $secondInventory->id,
|
||||||
|
'precio' => '75.00',
|
||||||
|
]);
|
||||||
|
|
||||||
|
$response = $this->actingAs($user, 'sanctum')
|
||||||
|
->postJson('/api/tenants/sonder/compras/start-checkout', [
|
||||||
|
'direct_items' => [
|
||||||
|
[
|
||||||
|
'catalog_item_id' => $firstVariant->catalog_item_id,
|
||||||
|
'variant_id' => $firstVariant->id,
|
||||||
|
'cantidad' => 1,
|
||||||
|
],
|
||||||
|
[
|
||||||
|
'catalog_item_id' => $secondVariant->catalog_item_id,
|
||||||
|
'variant_id' => $secondVariant->id,
|
||||||
|
'cantidad' => 1,
|
||||||
|
],
|
||||||
|
],
|
||||||
|
])
|
||||||
|
->assertCreated()
|
||||||
|
->assertJsonPath('data.cart_id', null)
|
||||||
|
->assertJsonCount(2, 'data.items')
|
||||||
|
->assertJsonPath('data.items.0.source_variant_id', $firstVariant->id)
|
||||||
|
->assertJsonPath('data.items.1.source_variant_id', $secondVariant->id)
|
||||||
|
->assertJsonPath('data.total', '125.00');
|
||||||
|
|
||||||
|
$purchaseId = $response->json('data.id');
|
||||||
|
|
||||||
|
$this->assertDatabaseCount('carritos', 0);
|
||||||
|
$this->assertDatabaseHas('compra_items', [
|
||||||
|
'compra_id' => $purchaseId,
|
||||||
|
'source_variant_id' => $firstVariant->id,
|
||||||
|
'cantidad' => 1,
|
||||||
|
'reservation_status' => 'active',
|
||||||
|
]);
|
||||||
|
$this->assertDatabaseHas('compra_items', [
|
||||||
|
'compra_id' => $purchaseId,
|
||||||
|
'source_variant_id' => $secondVariant->id,
|
||||||
|
'cantidad' => 1,
|
||||||
|
'reservation_status' => 'active',
|
||||||
|
]);
|
||||||
|
$this->assertDatabaseHas('inventories', [
|
||||||
|
'id' => $firstVariant->inventory_id,
|
||||||
|
'reserved_stock' => 1,
|
||||||
|
]);
|
||||||
|
$this->assertDatabaseHas('inventories', [
|
||||||
|
'id' => $secondInventory->id,
|
||||||
|
'reserved_stock' => 1,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_multi_item_direct_purchase_rolls_back_every_reservation_when_one_item_is_unavailable(): void
|
||||||
|
{
|
||||||
|
$this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
|
||||||
|
$user = User::factory()->create();
|
||||||
|
$availableVariant = $this->createVariantForTenant('sonder', 1, '50.00');
|
||||||
|
$unavailableInventory = Inventory::query()->create(['real_stock' => 0]);
|
||||||
|
$unavailableVariant = Variant::query()->create([
|
||||||
|
'catalog_item_id' => $availableVariant->catalog_item_id,
|
||||||
|
'inventory_id' => $unavailableInventory->id,
|
||||||
|
]);
|
||||||
|
|
||||||
|
$this->actingAs($user, 'sanctum')
|
||||||
|
->postJson('/api/tenants/sonder/compras/start-checkout', [
|
||||||
|
'direct_items' => [
|
||||||
|
[
|
||||||
|
'catalog_item_id' => $availableVariant->catalog_item_id,
|
||||||
|
'variant_id' => $availableVariant->id,
|
||||||
|
'cantidad' => 1,
|
||||||
|
],
|
||||||
|
[
|
||||||
|
'catalog_item_id' => $unavailableVariant->catalog_item_id,
|
||||||
|
'variant_id' => $unavailableVariant->id,
|
||||||
|
'cantidad' => 1,
|
||||||
|
],
|
||||||
|
],
|
||||||
|
])
|
||||||
|
->assertUnprocessable()
|
||||||
|
->assertJsonValidationErrors('direct_items.1.cantidad');
|
||||||
|
|
||||||
|
$this->assertDatabaseCount('compras', 0);
|
||||||
|
$this->assertDatabaseHas('inventories', [
|
||||||
|
'id' => $availableVariant->inventory_id,
|
||||||
|
'reserved_stock' => 0,
|
||||||
|
]);
|
||||||
|
$this->assertDatabaseHas('inventories', [
|
||||||
|
'id' => $unavailableInventory->id,
|
||||||
|
'reserved_stock' => 0,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
public function test_it_enforces_the_user_purchase_limit_and_releases_it_after_cancellation(): void
|
public function test_it_enforces_the_user_purchase_limit_and_releases_it_after_cancellation(): void
|
||||||
{
|
{
|
||||||
$this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
|
$this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
|
||||||
@@ -195,10 +296,12 @@ class StorePurchaseTest extends TestCase
|
|||||||
|
|
||||||
$firstPurchaseId = $this->actingAs($user, 'sanctum')
|
$firstPurchaseId = $this->actingAs($user, 'sanctum')
|
||||||
->postJson('/api/tenants/sonder/compras/start-checkout', [
|
->postJson('/api/tenants/sonder/compras/start-checkout', [
|
||||||
'direct_item' => [
|
'direct_items' => [
|
||||||
'catalog_item_id' => $variant->catalog_item_id,
|
[
|
||||||
'variant_id' => $variant->id,
|
'catalog_item_id' => $variant->catalog_item_id,
|
||||||
'cantidad' => 2,
|
'variant_id' => $variant->id,
|
||||||
|
'cantidad' => 2,
|
||||||
|
],
|
||||||
],
|
],
|
||||||
])
|
])
|
||||||
->assertCreated()
|
->assertCreated()
|
||||||
@@ -206,21 +309,25 @@ class StorePurchaseTest extends TestCase
|
|||||||
|
|
||||||
$this->actingAs($user, 'sanctum')
|
$this->actingAs($user, 'sanctum')
|
||||||
->postJson('/api/tenants/sonder/compras/start-checkout', [
|
->postJson('/api/tenants/sonder/compras/start-checkout', [
|
||||||
'direct_item' => [
|
'direct_items' => [
|
||||||
'catalog_item_id' => $variant->catalog_item_id,
|
[
|
||||||
'variant_id' => $variant->id,
|
'catalog_item_id' => $variant->catalog_item_id,
|
||||||
'cantidad' => 2,
|
'variant_id' => $variant->id,
|
||||||
|
'cantidad' => 2,
|
||||||
|
],
|
||||||
],
|
],
|
||||||
])
|
])
|
||||||
->assertUnprocessable()
|
->assertUnprocessable()
|
||||||
->assertJsonValidationErrors('direct_item.cantidad');
|
->assertJsonValidationErrors('direct_items');
|
||||||
|
|
||||||
$this->actingAs($otherUser, 'sanctum')
|
$this->actingAs($otherUser, 'sanctum')
|
||||||
->postJson('/api/tenants/sonder/compras/start-checkout', [
|
->postJson('/api/tenants/sonder/compras/start-checkout', [
|
||||||
'direct_item' => [
|
'direct_items' => [
|
||||||
'catalog_item_id' => $variant->catalog_item_id,
|
[
|
||||||
'variant_id' => $variant->id,
|
'catalog_item_id' => $variant->catalog_item_id,
|
||||||
'cantidad' => 3,
|
'variant_id' => $variant->id,
|
||||||
|
'cantidad' => 3,
|
||||||
|
],
|
||||||
],
|
],
|
||||||
])
|
])
|
||||||
->assertCreated();
|
->assertCreated();
|
||||||
@@ -231,10 +338,12 @@ class StorePurchaseTest extends TestCase
|
|||||||
|
|
||||||
$this->actingAs($user, 'sanctum')
|
$this->actingAs($user, 'sanctum')
|
||||||
->postJson('/api/tenants/sonder/compras/start-checkout', [
|
->postJson('/api/tenants/sonder/compras/start-checkout', [
|
||||||
'direct_item' => [
|
'direct_items' => [
|
||||||
'catalog_item_id' => $variant->catalog_item_id,
|
[
|
||||||
'variant_id' => $variant->id,
|
'catalog_item_id' => $variant->catalog_item_id,
|
||||||
'cantidad' => 3,
|
'variant_id' => $variant->id,
|
||||||
|
'cantidad' => 3,
|
||||||
|
],
|
||||||
],
|
],
|
||||||
])
|
])
|
||||||
->assertCreated();
|
->assertCreated();
|
||||||
@@ -361,10 +470,12 @@ class StorePurchaseTest extends TestCase
|
|||||||
|
|
||||||
$purchaseResponse = $this->actingAs($user, 'sanctum')
|
$purchaseResponse = $this->actingAs($user, 'sanctum')
|
||||||
->postJson('/api/tenants/sonder/compras/start-checkout', [
|
->postJson('/api/tenants/sonder/compras/start-checkout', [
|
||||||
'direct_item' => [
|
'direct_items' => [
|
||||||
'catalog_item_id' => $variant->catalog_item_id,
|
[
|
||||||
'variant_id' => $variant->id,
|
'catalog_item_id' => $variant->catalog_item_id,
|
||||||
'cantidad' => 2,
|
'variant_id' => $variant->id,
|
||||||
|
'cantidad' => 2,
|
||||||
|
],
|
||||||
],
|
],
|
||||||
])
|
])
|
||||||
->assertCreated()
|
->assertCreated()
|
||||||
@@ -535,10 +646,12 @@ class StorePurchaseTest extends TestCase
|
|||||||
|
|
||||||
$this->actingAs($user, 'sanctum')
|
$this->actingAs($user, 'sanctum')
|
||||||
->postJson('/api/tenants/sonder/compras/start-checkout', [
|
->postJson('/api/tenants/sonder/compras/start-checkout', [
|
||||||
'direct_item' => [
|
'direct_items' => [
|
||||||
'catalog_item_id' => $variant->catalog_item_id,
|
[
|
||||||
'variant_id' => $variant->id,
|
'catalog_item_id' => $variant->catalog_item_id,
|
||||||
'cantidad' => 1,
|
'variant_id' => $variant->id,
|
||||||
|
'cantidad' => 1,
|
||||||
|
],
|
||||||
],
|
],
|
||||||
'dni' => '987654321',
|
'dni' => '987654321',
|
||||||
'telefono' => '+54 9 341 555-4321',
|
'telefono' => '+54 9 341 555-4321',
|
||||||
|
|||||||
@@ -2,6 +2,7 @@
|
|||||||
|
|
||||||
namespace Tests\Feature\Seeders;
|
namespace Tests\Feature\Seeders;
|
||||||
|
|
||||||
|
use App\Domains\Authorization\Enums\PermissionCode;
|
||||||
use App\Domains\Authorization\Enums\RoleCode;
|
use App\Domains\Authorization\Enums\RoleCode;
|
||||||
use App\Domains\Authorization\Models\Permission;
|
use App\Domains\Authorization\Models\Permission;
|
||||||
use App\Domains\Authorization\Models\Role;
|
use App\Domains\Authorization\Models\Role;
|
||||||
@@ -21,6 +22,7 @@ class AuthorizationSeederTest extends TestCase
|
|||||||
[
|
[
|
||||||
RoleCode::Admin->value,
|
RoleCode::Admin->value,
|
||||||
RoleCode::AdminApp->value,
|
RoleCode::AdminApp->value,
|
||||||
|
RoleCode::Scanner->value,
|
||||||
RoleCode::User->value,
|
RoleCode::User->value,
|
||||||
],
|
],
|
||||||
Role::query()->orderBy('codigo')->pluck('codigo')->all()
|
Role::query()->orderBy('codigo')->pluck('codigo')->all()
|
||||||
@@ -34,10 +36,15 @@ class AuthorizationSeederTest extends TestCase
|
|||||||
|
|
||||||
$admin = Role::query()->where('codigo', RoleCode::Admin->value)->firstOrFail();
|
$admin = Role::query()->where('codigo', RoleCode::Admin->value)->firstOrFail();
|
||||||
$appAdmin = Role::query()->where('codigo', RoleCode::AdminApp->value)->firstOrFail();
|
$appAdmin = Role::query()->where('codigo', RoleCode::AdminApp->value)->firstOrFail();
|
||||||
|
$scanner = Role::query()->where('codigo', RoleCode::Scanner->value)->firstOrFail();
|
||||||
$user = Role::query()->where('codigo', RoleCode::User->value)->firstOrFail();
|
$user = Role::query()->where('codigo', RoleCode::User->value)->firstOrFail();
|
||||||
|
|
||||||
$this->assertCount(22, $admin->permissions);
|
$this->assertCount(22, $admin->permissions);
|
||||||
$this->assertCount(0, $appAdmin->permissions);
|
$this->assertCount(0, $appAdmin->permissions);
|
||||||
|
$this->assertSame(
|
||||||
|
[PermissionCode::ScanTickets->value],
|
||||||
|
$scanner->permissions->pluck('codigo')->all()
|
||||||
|
);
|
||||||
$this->assertCount(0, $user->permissions);
|
$this->assertCount(0, $user->permissions);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -46,8 +53,8 @@ class AuthorizationSeederTest extends TestCase
|
|||||||
$this->seed(AuthorizationSeeder::class);
|
$this->seed(AuthorizationSeeder::class);
|
||||||
$this->seed(AuthorizationSeeder::class);
|
$this->seed(AuthorizationSeeder::class);
|
||||||
|
|
||||||
$this->assertCount(3, Role::query()->get());
|
$this->assertCount(4, Role::query()->get());
|
||||||
$this->assertCount(22, Permission::query()->get());
|
$this->assertCount(22, Permission::query()->get());
|
||||||
$this->assertDatabaseCount('roles_permisos', 22);
|
$this->assertDatabaseCount('roles_permisos', 23);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -124,8 +124,13 @@ class MenuSeederTest extends TestCase
|
|||||||
->where('code', 'main.adminapp')
|
->where('code', 'main.adminapp')
|
||||||
->orWhere('parent_menu_code', 'main.adminapp')
|
->orWhere('parent_menu_code', 'main.adminapp')
|
||||||
->pluck('code');
|
->pluck('code');
|
||||||
|
$scannerMenuCodes = Menu::query()
|
||||||
|
->where('code', 'like', 'scanner.%')
|
||||||
|
->orderBy('code')
|
||||||
|
->pluck('code')
|
||||||
|
->all();
|
||||||
$userMenuCodes = Menu::query()
|
$userMenuCodes = Menu::query()
|
||||||
->whereNotIn('code', $adminAppMenuCodes)
|
->whereNotIn('code', [...$adminAppMenuCodes, ...$scannerMenuCodes])
|
||||||
->orderBy('code')
|
->orderBy('code')
|
||||||
->pluck('code')
|
->pluck('code')
|
||||||
->all();
|
->all();
|
||||||
@@ -153,9 +158,23 @@ class MenuSeederTest extends TestCase
|
|||||||
$this->assertSame($userMenuCodes, $userRoleMenuCodes);
|
$this->assertSame($userMenuCodes, $userRoleMenuCodes);
|
||||||
$this->assertNotContains('main.adminapp', $userRoleMenuCodes);
|
$this->assertNotContains('main.adminapp', $userRoleMenuCodes);
|
||||||
$this->assertNotContains('adminapp.catalog', $userRoleMenuCodes);
|
$this->assertNotContains('adminapp.catalog', $userRoleMenuCodes);
|
||||||
|
|
||||||
|
$scannerRoleMenuCodes = Role::query()
|
||||||
|
->where('codigo', RoleCode::Scanner->value)
|
||||||
|
->firstOrFail()
|
||||||
|
->menus()
|
||||||
|
->orderBy('menues.code')
|
||||||
|
->pluck('menues.code')
|
||||||
|
->all();
|
||||||
|
|
||||||
|
$this->assertSame([
|
||||||
|
'scanner.detail',
|
||||||
|
'scanner.inicio',
|
||||||
|
'scanner.scan',
|
||||||
|
], $scannerRoleMenuCodes);
|
||||||
$this->assertDatabaseCount(
|
$this->assertDatabaseCount(
|
||||||
'roles_menues',
|
'roles_menues',
|
||||||
(count($allMenuCodes) * 2) + count($userMenuCodes)
|
(count($allMenuCodes) * 2) + count($userMenuCodes) + count($scannerMenuCodes)
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -43,6 +43,7 @@ class WebsiteTypeSeederTest extends TestCase
|
|||||||
|
|
||||||
$this->assertSame('ShopIt', $shopIt->nombre);
|
$this->assertSame('ShopIt', $shopIt->nombre);
|
||||||
$this->assertSame('localhost', $shopIt->dominio);
|
$this->assertSame('localhost', $shopIt->dominio);
|
||||||
|
$this->assertSame('scanner.localhost', $shopIt->scanner_domain);
|
||||||
$this->assertSame($expectedPresentation, $shopIt->only(array_keys($expectedPresentation)));
|
$this->assertSame($expectedPresentation, $shopIt->only(array_keys($expectedPresentation)));
|
||||||
$this->assertSame('onticket_logo.png', $shopIt->siteLogo->filename);
|
$this->assertSame('onticket_logo.png', $shopIt->siteLogo->filename);
|
||||||
Storage::disk('s3')->assertExists($shopIt->siteLogo->path);
|
Storage::disk('s3')->assertExists($shopIt->siteLogo->path);
|
||||||
@@ -70,6 +71,7 @@ class WebsiteTypeSeederTest extends TestCase
|
|||||||
|
|
||||||
$this->assertSame('OnTicket', $onTicket->nombre);
|
$this->assertSame('OnTicket', $onTicket->nombre);
|
||||||
$this->assertSame('onticket.localhost', $onTicket->dominio);
|
$this->assertSame('onticket.localhost', $onTicket->dominio);
|
||||||
|
$this->assertSame('scanner.onticket.localhost', $onTicket->scanner_domain);
|
||||||
$this->assertSame($expectedPresentation, $onTicket->only(array_keys($expectedPresentation)));
|
$this->assertSame($expectedPresentation, $onTicket->only(array_keys($expectedPresentation)));
|
||||||
$this->assertSame('onticket_logo.png', $onTicket->siteLogo->filename);
|
$this->assertSame('onticket_logo.png', $onTicket->siteLogo->filename);
|
||||||
Storage::disk('s3')->assertExists($onTicket->siteLogo->path);
|
Storage::disk('s3')->assertExists($onTicket->siteLogo->path);
|
||||||
|
|||||||
76
tests/Feature/Tenant/BootstrapScannerControllerTest.php
Normal file
@@ -0,0 +1,76 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Tests\Feature\Tenant;
|
||||||
|
|
||||||
|
use App\Domains\Attachable\Models\Attachment;
|
||||||
|
use App\Domains\Tenant\Models\WebsiteType;
|
||||||
|
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||||
|
use Tests\TestCase;
|
||||||
|
|
||||||
|
class BootstrapScannerControllerTest extends TestCase
|
||||||
|
{
|
||||||
|
use RefreshDatabase;
|
||||||
|
|
||||||
|
public function test_it_publicly_bootstraps_the_scanner_by_scanner_domain(): void
|
||||||
|
{
|
||||||
|
$siteLogo = Attachment::factory()->create();
|
||||||
|
|
||||||
|
WebsiteType::query()->create([
|
||||||
|
'codigo' => 'shopit',
|
||||||
|
'nombre' => 'ShopIt',
|
||||||
|
'dominio' => 'admin.shopit.test',
|
||||||
|
'scanner_domain' => 'scanner.shopit.test',
|
||||||
|
'primary_color' => '#112233',
|
||||||
|
'secondary_color' => '#445566',
|
||||||
|
'danger_color' => '#aa0000',
|
||||||
|
'success_color' => '#00aa00',
|
||||||
|
'warning_color' => '#ffaa00',
|
||||||
|
'body_color' => '#666666',
|
||||||
|
'darker_body_color' => '#333333',
|
||||||
|
'surface_color' => '#ffffff',
|
||||||
|
'background_color' => '#f8f8f8',
|
||||||
|
'border_color' => '#eaeaea',
|
||||||
|
'login_header_footer_color' => '#313131',
|
||||||
|
'site_logo' => $siteLogo->id,
|
||||||
|
]);
|
||||||
|
|
||||||
|
$this->getJson('/api/v1/scanner/bootstrap/SCANNER.SHOPIT.TEST')
|
||||||
|
->assertOk()
|
||||||
|
->assertJsonPath('data.website_type_code', 'shopit')
|
||||||
|
->assertJsonPath('data.primary_color', '#112233')
|
||||||
|
->assertJsonPath('data.site_logo', $siteLogo->getTemporaryUrl(1440))
|
||||||
|
->assertJsonPath('data.footer_logo', null)
|
||||||
|
->assertJsonMissingPath('data.codigo')
|
||||||
|
->assertJsonMissingPath('data.nombre')
|
||||||
|
->assertJsonMissingPath('data.dominio')
|
||||||
|
->assertJsonMissingPath('data.scanner_domain');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_it_does_not_match_the_admin_app_domain(): void
|
||||||
|
{
|
||||||
|
WebsiteType::query()->create([
|
||||||
|
'codigo' => 'shopit',
|
||||||
|
'nombre' => 'ShopIt',
|
||||||
|
'dominio' => 'admin.shopit.test',
|
||||||
|
'scanner_domain' => 'scanner.shopit.test',
|
||||||
|
]);
|
||||||
|
|
||||||
|
$this->getJson('/api/v1/scanner/bootstrap/admin.shopit.test')
|
||||||
|
->assertNotFound();
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_it_returns_not_found_for_an_unknown_scanner_domain(): void
|
||||||
|
{
|
||||||
|
$this->getJson('/api/v1/scanner/bootstrap/unknown.test')
|
||||||
|
->assertNotFound();
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_it_rejects_an_invalid_domain(): void
|
||||||
|
{
|
||||||
|
$invalidDomain = str_repeat('a', 256);
|
||||||
|
|
||||||
|
$this->getJson("/api/v1/scanner/bootstrap/{$invalidDomain}")
|
||||||
|
->assertUnprocessable()
|
||||||
|
->assertJsonValidationErrors(['dominio']);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -39,6 +39,20 @@ class BootstrapTenantControllerTest extends TestCase
|
|||||||
'type' => AttachmentType::Image,
|
'type' => AttachmentType::Image,
|
||||||
'mime_type' => 'image/png',
|
'mime_type' => 'image/png',
|
||||||
]);
|
]);
|
||||||
|
$headerBackgroundAttachment = Attachment::create([
|
||||||
|
'key' => (string) Str::uuid(),
|
||||||
|
'path' => 'tenants/header-background.png',
|
||||||
|
'filename' => 'header-background.png',
|
||||||
|
'type' => AttachmentType::Image,
|
||||||
|
'mime_type' => 'image/png',
|
||||||
|
]);
|
||||||
|
$footerBackgroundAttachment = Attachment::create([
|
||||||
|
'key' => (string) Str::uuid(),
|
||||||
|
'path' => 'tenants/footer-background.png',
|
||||||
|
'filename' => 'footer-background.png',
|
||||||
|
'type' => AttachmentType::Image,
|
||||||
|
'mime_type' => 'image/png',
|
||||||
|
]);
|
||||||
|
|
||||||
$tenant = Tenant::create([
|
$tenant = Tenant::create([
|
||||||
'codigo' => 'acme',
|
'codigo' => 'acme',
|
||||||
@@ -52,9 +66,12 @@ class BootstrapTenantControllerTest extends TestCase
|
|||||||
'footer_bg_color' => '#ffffff',
|
'footer_bg_color' => '#ffffff',
|
||||||
'header_logo_id' => $headerAttachment->id,
|
'header_logo_id' => $headerAttachment->id,
|
||||||
'footer_logo_id' => $footerAttachment->id,
|
'footer_logo_id' => $footerAttachment->id,
|
||||||
|
'header_bg_image_id' => $headerBackgroundAttachment->id,
|
||||||
|
'footer_bg_image_id' => $footerBackgroundAttachment->id,
|
||||||
'event_date_text' => '9, 10, 11 y 12 de Octubre 2026',
|
'event_date_text' => '9, 10, 11 y 12 de Octubre 2026',
|
||||||
'display_categories' => false,
|
'display_categories' => false,
|
||||||
'display_seach_bar' => false,
|
'display_seach_bar' => false,
|
||||||
|
'display_cart' => false,
|
||||||
]);
|
]);
|
||||||
|
|
||||||
$response = $this->getJson('/api/tenants/bootstrap/acme.com');
|
$response = $this->getJson('/api/tenants/bootstrap/acme.com');
|
||||||
@@ -70,13 +87,18 @@ class BootstrapTenantControllerTest extends TestCase
|
|||||||
->assertJsonPath('data.event_date_text', '9, 10, 11 y 12 de Octubre 2026')
|
->assertJsonPath('data.event_date_text', '9, 10, 11 y 12 de Octubre 2026')
|
||||||
->assertJsonPath('data.display_categories', false)
|
->assertJsonPath('data.display_categories', false)
|
||||||
->assertJsonPath('data.display_seach_bar', false)
|
->assertJsonPath('data.display_seach_bar', false)
|
||||||
|
->assertJsonPath('data.display_cart', false)
|
||||||
->assertJsonPath('data.header_bg_color', '#ffffff')->assertJsonPath('data.footer_bg_color', '#ffffff');
|
->assertJsonPath('data.header_bg_color', '#ffffff')->assertJsonPath('data.footer_bg_color', '#ffffff');
|
||||||
|
|
||||||
$headerUrl = $response->json('data.header_logo');
|
$headerUrl = $response->json('data.header_logo');
|
||||||
$footerUrl = $response->json('data.footer_logo');
|
$footerUrl = $response->json('data.footer_logo');
|
||||||
|
$headerBackgroundUrl = $response->json('data.header_bg_image');
|
||||||
|
$footerBackgroundUrl = $response->json('data.footer_bg_image');
|
||||||
|
|
||||||
$this->assertStringContainsString($headerAttachment->key, $headerUrl);
|
$this->assertStringContainsString($headerAttachment->key, $headerUrl);
|
||||||
$this->assertStringContainsString($footerAttachment->key, $footerUrl);
|
$this->assertStringContainsString($footerAttachment->key, $footerUrl);
|
||||||
|
$this->assertStringContainsString($headerBackgroundAttachment->key, $headerBackgroundUrl);
|
||||||
|
$this->assertStringContainsString($footerBackgroundAttachment->key, $footerBackgroundUrl);
|
||||||
$this->assertTrue(
|
$this->assertTrue(
|
||||||
str_contains($headerUrl, 'Expires=') || str_contains($headerUrl, 'expiration=') || str_contains($headerUrl, 'X-Amz-Expires=')
|
str_contains($headerUrl, 'Expires=') || str_contains($headerUrl, 'expiration=') || str_contains($headerUrl, 'X-Amz-Expires=')
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -20,6 +20,7 @@ class WebsiteTypeServiceTest extends TestCase
|
|||||||
'codigo' => 'marketplace',
|
'codigo' => 'marketplace',
|
||||||
'nombre' => 'Marketplace',
|
'nombre' => 'Marketplace',
|
||||||
'dominio' => 'marketplace.test',
|
'dominio' => 'marketplace.test',
|
||||||
|
'scanner_domain' => 'scanner.marketplace.test',
|
||||||
'primary_color' => '#111111',
|
'primary_color' => '#111111',
|
||||||
'secondary_color' => '#222222',
|
'secondary_color' => '#222222',
|
||||||
'danger_color' => '#ff0000',
|
'danger_color' => '#ff0000',
|
||||||
@@ -48,6 +49,7 @@ class WebsiteTypeServiceTest extends TestCase
|
|||||||
$this->assertDatabaseHas('website_type', [
|
$this->assertDatabaseHas('website_type', [
|
||||||
'codigo' => 'marketplace',
|
'codigo' => 'marketplace',
|
||||||
'dominio' => 'marketplace.test',
|
'dominio' => 'marketplace.test',
|
||||||
|
'scanner_domain' => 'scanner.marketplace.test',
|
||||||
'warning_color' => '#ffaa00',
|
'warning_color' => '#ffaa00',
|
||||||
'body_color' => '#666666',
|
'body_color' => '#666666',
|
||||||
'darker_body_color' => '#333333',
|
'darker_body_color' => '#333333',
|
||||||
|
|||||||