Compare commits
17 Commits
dev
...
refactor/s
| Author | SHA1 | Date |
|---|---|---|
|
|
6d123cd403 | |
|
|
3164a00e6c | |
|
|
36cbc8da29 | |
|
|
58e027cad5 | |
|
|
971c5f6cd9 | |
|
|
2524f00dfd | |
|
|
045fcfab72 | |
|
|
cfe29b41a9 | |
|
|
bd600649b6 | |
|
|
7685089540 | |
|
|
889e188deb | |
|
|
4a166e3cbf | |
|
|
d8b3a354d9 | |
|
|
44f75185a1 | |
|
|
3adef9341e | |
|
|
3b1698ffd1 | |
|
|
c436302d7a |
|
|
@ -5,10 +5,6 @@ APP_DEBUG=false
|
|||
APP_URL=http://localhost
|
||||
|
||||
PURCHASE_CHECKOUT_EXPIRATION_MINUTES=30
|
||||
PURCHASE_QR_EXPIRATION_MINUTES=15
|
||||
PURCHASE_TELEPAGOS_EXPIRATION_MINUTES=30
|
||||
PURCHASE_TRANSFER_EXPIRATION_MINUTES=1440
|
||||
PURCHASE_TRANSFER_CANDIDATE_AMOUNT_TOLERANCE_PERCENTAGE=5
|
||||
STOCK_RESERVATION_EXPIRATION_MINUTES=30
|
||||
FRONTEND_URLS=http://localhost:4200
|
||||
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load Diff
|
|
@ -1,65 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Domains\Catalog\Controllers\AdminApp;
|
||||
|
||||
use App\Domains\Catalog\Models\FeaturedGroup;
|
||||
use App\Domains\Catalog\Requests\AdminApp\UpsertOnTicketFeaturedGroupRequest;
|
||||
use App\Domains\Catalog\Resources\AdminApp\OnTicketFeaturedGroupResource;
|
||||
use App\Domains\Catalog\Services\OnTicketFeaturedGroupService;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
|
||||
|
||||
class OnTicketFeaturedGroupController extends Controller
|
||||
{
|
||||
public function __construct(
|
||||
private readonly OnTicketFeaturedGroupService $featuredGroupService,
|
||||
) {}
|
||||
|
||||
public function index(Request $request): AnonymousResourceCollection
|
||||
{
|
||||
return OnTicketFeaturedGroupResource::collection(
|
||||
$this->featuredGroupService->forTenant($this->onTicketTenant($request))
|
||||
);
|
||||
}
|
||||
|
||||
public function store(UpsertOnTicketFeaturedGroupRequest $request): JsonResponse
|
||||
{
|
||||
$featuredGroup = $this->featuredGroupService->create(
|
||||
$this->onTicketTenant($request),
|
||||
$request->validated(),
|
||||
);
|
||||
|
||||
return OnTicketFeaturedGroupResource::make($featuredGroup)
|
||||
->response()
|
||||
->setStatusCode(201);
|
||||
}
|
||||
|
||||
public function update(
|
||||
UpsertOnTicketFeaturedGroupRequest $request,
|
||||
FeaturedGroup $featuredGroup,
|
||||
): OnTicketFeaturedGroupResource {
|
||||
$tenant = $this->onTicketTenant($request);
|
||||
|
||||
abort_unless($featuredGroup->tenant_code === $tenant->codigo, 404);
|
||||
|
||||
return OnTicketFeaturedGroupResource::make(
|
||||
$this->featuredGroupService->update(
|
||||
$tenant,
|
||||
$featuredGroup,
|
||||
$request->validated(),
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
private function onTicketTenant(Request $request): Tenant
|
||||
{
|
||||
$tenant = $request->user()->tenant()->firstOrFail();
|
||||
|
||||
abort_unless($tenant->website_type_code === 'onticket', 404);
|
||||
|
||||
return $tenant;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,22 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Domains\Catalog\Requests\AdminApp;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
|
||||
class UpsertOnTicketFeaturedGroupRequest extends FormRequest
|
||||
{
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/** @return array<string, mixed> */
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'category_name' => ['required', 'string', 'max:255'],
|
||||
'is_featured' => ['required', 'boolean'],
|
||||
];
|
||||
}
|
||||
}
|
||||
|
|
@ -1,29 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Domains\Catalog\Resources\AdminApp;
|
||||
|
||||
use App\Domains\Catalog\Enums\ProductLayout;
|
||||
use App\Domains\Catalog\Models\FeaturedGroup;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
/** @mixin FeaturedGroup */
|
||||
class OnTicketFeaturedGroupResource extends JsonResource
|
||||
{
|
||||
/** @return array<string, mixed> */
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'code' => $this->code,
|
||||
'category_id' => $this->category_id,
|
||||
'category_name' => $this->category->nombre,
|
||||
'group_name' => $this->group_name,
|
||||
'is_featured' => $this->product_layout === ProductLayout::Row,
|
||||
'type' => $this->source_type->value,
|
||||
'product_layout' => $this->product_layout->value,
|
||||
'group_layout' => $this->group_layout->value,
|
||||
'order' => $this->group_order,
|
||||
];
|
||||
}
|
||||
}
|
||||
|
|
@ -1,95 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Domains\Catalog\Services;
|
||||
|
||||
use App\Domains\Catalog\Enums\FeaturedGroupSource;
|
||||
use App\Domains\Catalog\Enums\GroupLayout;
|
||||
use App\Domains\Catalog\Enums\ProductLayout;
|
||||
use App\Domains\Catalog\Models\Category;
|
||||
use App\Domains\Catalog\Models\FeaturedGroup;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use Illuminate\Database\Eloquent\Collection;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
class OnTicketFeaturedGroupService
|
||||
{
|
||||
/** @return Collection<int, FeaturedGroup> */
|
||||
public function forTenant(Tenant $tenant): Collection
|
||||
{
|
||||
return FeaturedGroup::query()
|
||||
->where('tenant_code', $tenant->codigo)
|
||||
->where('source_type', FeaturedGroupSource::Category)
|
||||
->whereHas('category', fn ($query) => $query->where('tenant_code', $tenant->codigo))
|
||||
->with('category')
|
||||
->orderBy('group_order')
|
||||
->orderBy('id')
|
||||
->get();
|
||||
}
|
||||
|
||||
/** @param array{category_name: string, is_featured: bool} $data */
|
||||
public function create(Tenant $tenant, array $data): FeaturedGroup
|
||||
{
|
||||
return DB::transaction(function () use ($tenant, $data): FeaturedGroup {
|
||||
$category = $tenant->categories()->create([
|
||||
'nombre' => $data['category_name'],
|
||||
]);
|
||||
|
||||
$featuredGroup = FeaturedGroup::query()->create([
|
||||
'tenant_code' => $tenant->codigo,
|
||||
'source_type' => FeaturedGroupSource::Category,
|
||||
'category_id' => $category->id,
|
||||
'product_layout' => $this->productLayout($data['is_featured']),
|
||||
'group_layout' => GroupLayout::Paginated,
|
||||
'group_name' => $data['category_name'],
|
||||
'group_order' => $this->nextOrder($tenant),
|
||||
]);
|
||||
|
||||
return $featuredGroup->setRelation('category', $category);
|
||||
});
|
||||
}
|
||||
|
||||
/** @param array{category_name: string, is_featured: bool} $data */
|
||||
public function update(
|
||||
Tenant $tenant,
|
||||
FeaturedGroup $featuredGroup,
|
||||
array $data,
|
||||
): FeaturedGroup {
|
||||
return DB::transaction(function () use ($tenant, $featuredGroup, $data): FeaturedGroup {
|
||||
$featuredGroup = FeaturedGroup::query()
|
||||
->whereKey($featuredGroup->getKey())
|
||||
->where('tenant_code', $tenant->codigo)
|
||||
->where('source_type', FeaturedGroupSource::Category)
|
||||
->lockForUpdate()
|
||||
->firstOrFail();
|
||||
|
||||
$category = Category::query()
|
||||
->whereKey($featuredGroup->category_id)
|
||||
->where('tenant_code', $tenant->codigo)
|
||||
->lockForUpdate()
|
||||
->firstOrFail();
|
||||
|
||||
$category->update(['nombre' => $data['category_name']]);
|
||||
$featuredGroup->update([
|
||||
'group_name' => $data['category_name'],
|
||||
'product_layout' => $this->productLayout($data['is_featured']),
|
||||
'group_layout' => GroupLayout::Paginated,
|
||||
]);
|
||||
|
||||
return $featuredGroup->setRelation('category', $category);
|
||||
});
|
||||
}
|
||||
|
||||
private function productLayout(bool $isFeatured): ProductLayout
|
||||
{
|
||||
return $isFeatured ? ProductLayout::Row : ProductLayout::ColumnWithCart;
|
||||
}
|
||||
|
||||
private function nextOrder(Tenant $tenant): int
|
||||
{
|
||||
$maximumOrder = FeaturedGroup::query()
|
||||
->where('tenant_code', $tenant->codigo)
|
||||
->max('group_order');
|
||||
|
||||
return $maximumOrder === null ? 0 : ((int) $maximumOrder) + 1;
|
||||
}
|
||||
}
|
||||
|
|
@ -21,16 +21,11 @@ Modela y publica la oferta comercial del tenant: productos, variantes, categorí
|
|||
- `StockReservationService`: sincroniza el carrito como conjunto, bloquea todos sus inventarios en orden estable y mantiene el ledger agregado consistente con `Inventory.reserved_stock`.
|
||||
- `ExpireStockReservationsService`: detecta en un único recorrido reservas vencidas de compras, carritos y huérfanas, y delega los efectos comerciales sin mezclar esas reglas con la liberación física del inventario.
|
||||
- `FeaturedGroupService`: pagina los ítems destacados para la tienda.
|
||||
- `OnTicketFeaturedGroupService`: administra grupos destacados del panel para sitios de tickets.
|
||||
|
||||
## Endpoints de tienda
|
||||
|
||||
Bajo `/tenants/{tenant:codigo}` se publican catálogo, búsqueda, categoría, detalle, alta de ítems y paginación de grupos destacados.
|
||||
|
||||
## Endpoints administrativos
|
||||
|
||||
Bajo `/v1/adminapp/tenant/featured-groups`, con `auth:sanctum` y `adminapp.tenant`, se listan, crean y actualizan grupos destacados.
|
||||
|
||||
## Dependencias y reglas
|
||||
|
||||
Usa `Attachable` para imágenes/archivos, `Tenant` para aislamiento y `Ticket`/`Event` para vigencia y fechas. `Cart` y `Purchase` consumen sus precios, variantes e inventario. Los cambios de stock deben pasar por `CatalogInventoryService` para conservar reservas y disponibilidad.
|
||||
|
|
|
|||
|
|
@ -1,15 +0,0 @@
|
|||
<?php
|
||||
|
||||
use App\Domains\Catalog\Controllers\AdminApp\OnTicketFeaturedGroupController;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
|
||||
Route::prefix('v1/adminapp/tenant')
|
||||
->middleware(['auth:sanctum', 'adminapp.tenant'])
|
||||
->group(function (): void {
|
||||
Route::get('featured-groups', [OnTicketFeaturedGroupController::class, 'index'])
|
||||
->name('adminapp.featured-groups.index');
|
||||
Route::post('featured-groups', [OnTicketFeaturedGroupController::class, 'store'])
|
||||
->name('adminapp.featured-groups.store');
|
||||
Route::put('featured-groups/{featuredGroup}', [OnTicketFeaturedGroupController::class, 'update'])
|
||||
->name('adminapp.featured-groups.update');
|
||||
});
|
||||
|
|
@ -15,5 +15,3 @@ Route::prefix('tenants/{tenant:codigo}')->group(function (): void {
|
|||
Route::post('catalog-items/{catalogItem}/variant-options', [CatalogController::class, 'variantOptions']);
|
||||
Route::post('catalog-items', [CatalogController::class, 'store']);
|
||||
});
|
||||
|
||||
require __DIR__.'/adminapp.php';
|
||||
|
|
|
|||
|
|
@ -1,47 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Domains\Client\Controllers;
|
||||
|
||||
use App\Domains\Client\Models\Client;
|
||||
use App\Domains\Client\Requests\StoreClientRequest;
|
||||
use App\Domains\Client\Requests\UpdateClientRequest;
|
||||
use App\Domains\Client\Resources\ClientResource;
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Response;
|
||||
|
||||
class ClientController extends Controller
|
||||
{
|
||||
public function index(): JsonResponse
|
||||
{
|
||||
return ClientResource::collection(
|
||||
Client::query()->with('tenants')->latest()->paginateFromRequest()
|
||||
)->response();
|
||||
}
|
||||
|
||||
public function store(StoreClientRequest $request): JsonResponse
|
||||
{
|
||||
return ClientResource::make(
|
||||
Client::query()->create($request->validated())->load('tenants')
|
||||
)->response()->setStatusCode(201);
|
||||
}
|
||||
|
||||
public function show(Client $client): ClientResource
|
||||
{
|
||||
return ClientResource::make($client->load('tenants'));
|
||||
}
|
||||
|
||||
public function update(UpdateClientRequest $request, Client $client): ClientResource
|
||||
{
|
||||
$client->update($request->validated());
|
||||
|
||||
return ClientResource::make($client->fresh()->load('tenants'));
|
||||
}
|
||||
|
||||
public function destroy(Client $client): Response
|
||||
{
|
||||
$client->delete();
|
||||
|
||||
return response()->noContent();
|
||||
}
|
||||
}
|
||||
|
|
@ -1,22 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Domains\Client\Requests;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Validation\Rule;
|
||||
|
||||
class StoreClientRequest extends FormRequest
|
||||
{
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'code' => ['required', 'string', 'max:255', Rule::unique('clients', 'code')],
|
||||
'name' => ['required', 'string', 'max:255'],
|
||||
];
|
||||
}
|
||||
}
|
||||
|
|
@ -1,26 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Domains\Client\Requests;
|
||||
|
||||
use App\Domains\Client\Models\Client;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Validation\Rule;
|
||||
|
||||
class UpdateClientRequest extends FormRequest
|
||||
{
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
public function rules(): array
|
||||
{
|
||||
/** @var Client|null $client */
|
||||
$client = $this->route('client');
|
||||
|
||||
return [
|
||||
'code' => ['sometimes', 'string', 'max:255', Rule::unique('clients', 'code')->ignore($client?->id)],
|
||||
'name' => ['sometimes', 'string', 'max:255'],
|
||||
];
|
||||
}
|
||||
}
|
||||
|
|
@ -1,26 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Domains\Client\Resources;
|
||||
|
||||
use App\Domains\Client\Models\Client;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
/** @mixin Client */
|
||||
class ClientResource extends JsonResource
|
||||
{
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'code' => $this->code,
|
||||
'name' => $this->name,
|
||||
'tenants' => $this->whenLoaded('tenants', fn () => $this->tenants->map(fn ($tenant): array => [
|
||||
'id' => $tenant->id,
|
||||
'codigo' => $tenant->codigo,
|
||||
'nombre' => $tenant->nombre,
|
||||
'dominio' => $tenant->dominio,
|
||||
])),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
|
@ -1,6 +0,0 @@
|
|||
<?php
|
||||
|
||||
use App\Domains\Client\Controllers\ClientController;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
|
||||
Route::apiResource('clients', ClientController::class);
|
||||
|
|
@ -10,7 +10,6 @@ use App\Domains\Desfile\Services\EntryService;
|
|||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Response;
|
||||
|
||||
class EntryController extends Controller
|
||||
{
|
||||
|
|
@ -48,10 +47,4 @@ class EntryController extends Controller
|
|||
));
|
||||
}
|
||||
|
||||
public function destroyImage(Request $request): Response
|
||||
{
|
||||
$this->entryService->deleteImage($request->user()->tenant()->firstOrFail());
|
||||
|
||||
return response()->noContent();
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -166,19 +166,6 @@ class EntryService
|
|||
return $this->current($tenant);
|
||||
}
|
||||
|
||||
public function deleteImage(Tenant $tenant): void
|
||||
{
|
||||
$attachment = DB::transaction(function () use ($tenant): Attachment {
|
||||
$entry = $this->entryQuery($tenant)->lockForUpdate()->firstOrFail();
|
||||
$attachment = $entry->allAttachments()->lockForUpdate()->firstOrFail();
|
||||
$entry->allAttachments()->detach($attachment->id);
|
||||
|
||||
return $attachment;
|
||||
});
|
||||
|
||||
$this->deleteIfUnused($attachment);
|
||||
}
|
||||
|
||||
/** @return Collection<string, ItemAttribute> */
|
||||
private function itemAttributes(CatalogItem $entry): Collection
|
||||
{
|
||||
|
|
|
|||
|
|
@ -22,7 +22,7 @@ class InvitationPurchaseProvisioner
|
|||
private const ALLOCATIONS = [
|
||||
['sector' => 'A', 'row' => 1, 'first_seat' => 1, 'last_seat' => 16, 'type' => 'NORMAL'],
|
||||
['sector' => 'A', 'row' => 3, 'first_seat' => 1, 'last_seat' => 14, 'type' => 'NORMAL'],
|
||||
['sector' => 'C', 'row' => 1, 'first_seat' => 1, 'last_seat' => 17, 'type' => 'VIP + LUNCH'],
|
||||
['sector' => 'C', 'row' => 1, 'first_seat' => 1, 'last_seat' => 16, 'type' => 'VIP + LUNCH'],
|
||||
['sector' => 'C', 'row' => 3, 'first_seat' => 6, 'last_seat' => 7, 'type' => 'NORMAL'],
|
||||
];
|
||||
|
||||
|
|
|
|||
|
|
@ -14,6 +14,4 @@ Route::prefix('v1/adminapp/tenant/desfile')
|
|||
->name('adminapp.desfile.entries.image.replace');
|
||||
Route::patch('entries/image', [EntryController::class, 'updateImage'])
|
||||
->name('adminapp.desfile.entries.image.update');
|
||||
Route::delete('entries/image', [EntryController::class, 'destroyImage'])
|
||||
->name('adminapp.desfile.entries.image.destroy');
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,20 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Domains\Forms\Controllers\AdminApp;
|
||||
|
||||
use App\Domains\Forms\Resources\TicketFilterFormResource;
|
||||
use App\Domains\Forms\Services\TicketFilterFormService;
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
class TicketFilterFormController extends Controller
|
||||
{
|
||||
public function __construct(private readonly TicketFilterFormService $formService) {}
|
||||
|
||||
public function __invoke(Request $request): TicketFilterFormResource
|
||||
{
|
||||
$tenant = $request->user('sanctum')->tenant()->firstOrFail();
|
||||
|
||||
return TicketFilterFormResource::make($this->formService->get($tenant));
|
||||
}
|
||||
}
|
||||
|
|
@ -1,22 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Domains\Forms\Controllers\AdminApp;
|
||||
|
||||
use App\Domains\Forms\Resources\TicketFormResource;
|
||||
use App\Domains\Forms\Services\TicketFormService;
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
class TicketFormController extends Controller
|
||||
{
|
||||
public function __construct(protected TicketFormService $ticketFormService) {}
|
||||
|
||||
public function __invoke(Request $request): TicketFormResource
|
||||
{
|
||||
return TicketFormResource::make(
|
||||
$this->ticketFormService->get(
|
||||
$request->user('sanctum')->tenant()->firstOrFail()
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,21 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Domains\Forms\Resources;
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
class TicketFilterFormResource extends JsonResource
|
||||
{
|
||||
/** @return array<string, mixed> */
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
'code' => $this->resource['code'],
|
||||
'action' => $this->resource['action'],
|
||||
'method' => $this->resource['method'],
|
||||
'fields' => $this->resource['fields'],
|
||||
'columns' => $this->resource['columns'],
|
||||
];
|
||||
}
|
||||
}
|
||||
|
|
@ -1,18 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Domains\Forms\Resources;
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
class TicketFormResource extends JsonResource
|
||||
{
|
||||
/** @return array<string, mixed> */
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
'statuses' => $this->resource['statuses'],
|
||||
'categories' => $this->resource['categories'],
|
||||
];
|
||||
}
|
||||
}
|
||||
|
|
@ -1,127 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Domains\Forms\Services;
|
||||
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use App\Domains\Ticket\Models\Ticket;
|
||||
use App\Domains\Ticket\Services\AdminAppTicketColumnService;
|
||||
|
||||
class TicketFilterFormService
|
||||
{
|
||||
private const FIESTA_FUTBOL_INFANTIL = 'fiesta_futbol_infantil';
|
||||
|
||||
public function __construct(
|
||||
private readonly TicketFormService $ticketFormService,
|
||||
private readonly AdminAppTicketColumnService $columnService,
|
||||
) {}
|
||||
|
||||
/** @return array<string, mixed> */
|
||||
public function get(Tenant $tenant): array
|
||||
{
|
||||
$fields = $this->commonFields();
|
||||
|
||||
if ($tenant->codigo === self::FIESTA_FUTBOL_INFANTIL) {
|
||||
$fields = [
|
||||
...$this->fiestaFutbolInfantilFields($tenant),
|
||||
...$fields,
|
||||
];
|
||||
}
|
||||
|
||||
return [
|
||||
'code' => 'tickets_filter',
|
||||
'action' => '/api/v1/adminapp/tenant/tickets',
|
||||
'method' => 'GET',
|
||||
'fields' => $fields,
|
||||
'columns' => $this->columnService->publicColumns($tenant),
|
||||
];
|
||||
}
|
||||
|
||||
/** @return list<array<string, mixed>> */
|
||||
private function fiestaFutbolInfantilFields(Tenant $tenant): array
|
||||
{
|
||||
$form = $this->ticketFormService->getForFilters($tenant);
|
||||
|
||||
return [
|
||||
[
|
||||
'name' => 'category',
|
||||
'query_param' => 'category',
|
||||
'label' => 'Categoría',
|
||||
'type' => 'select',
|
||||
'required' => false,
|
||||
'default' => null,
|
||||
'placeholder' => 'Categoría',
|
||||
'options' => array_map(
|
||||
fn (array $category): array => [
|
||||
'value' => $category['value'],
|
||||
'label' => $category['label'],
|
||||
'children' => [
|
||||
'field' => 'product',
|
||||
'disabled' => $category['products'] === [],
|
||||
'options' => array_map(
|
||||
fn (array $product): array => [
|
||||
'value' => $product['value'],
|
||||
'label' => $product['label'],
|
||||
'children' => [
|
||||
'field' => 'type',
|
||||
'disabled' => $product['types'] === [],
|
||||
'options' => $product['types'],
|
||||
],
|
||||
],
|
||||
$category['products'],
|
||||
),
|
||||
],
|
||||
],
|
||||
$form['categories'],
|
||||
),
|
||||
],
|
||||
$this->dependentSelect('product', 'Producto', 'category'),
|
||||
$this->dependentSelect('type', 'Tipo', 'product'),
|
||||
];
|
||||
}
|
||||
|
||||
/** @return list<array<string, mixed>> */
|
||||
private function commonFields(): array
|
||||
{
|
||||
return [
|
||||
[
|
||||
'name' => 'date',
|
||||
'query_param' => 'date',
|
||||
'label' => 'Fecha',
|
||||
'type' => 'date',
|
||||
'required' => false,
|
||||
'default' => null,
|
||||
],
|
||||
[
|
||||
'name' => 'status',
|
||||
'query_param' => 'status',
|
||||
'label' => 'Estado',
|
||||
'type' => 'select',
|
||||
'required' => false,
|
||||
'default' => null,
|
||||
'placeholder' => 'Estado',
|
||||
'options' => [
|
||||
['value' => Ticket::STATUS_ACTIVE, 'label' => 'Activo'],
|
||||
['value' => Ticket::STATUS_USED, 'label' => 'Usado'],
|
||||
['value' => Ticket::STATUS_EXPIRED, 'label' => 'Vencido'],
|
||||
],
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
/** @return array<string, mixed> */
|
||||
private function dependentSelect(string $name, string $label, string $dependency): array
|
||||
{
|
||||
return [
|
||||
'name' => $name,
|
||||
'query_param' => $name,
|
||||
'label' => $label,
|
||||
'type' => 'select',
|
||||
'required' => false,
|
||||
'default' => null,
|
||||
'placeholder' => $label,
|
||||
'depends_on' => $dependency,
|
||||
'disabled' => true,
|
||||
'options' => [],
|
||||
];
|
||||
}
|
||||
}
|
||||
|
|
@ -1,336 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Domains\Forms\Services;
|
||||
|
||||
use App\Domains\Catalog\Models\CatalogItem;
|
||||
use App\Domains\Catalog\Models\Variant;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use App\Domains\Ticket\Models\Ticket;
|
||||
use Illuminate\Database\Eloquent\Collection;
|
||||
|
||||
class TicketFormService
|
||||
{
|
||||
private const PRODUCT = 'product';
|
||||
|
||||
/**
|
||||
* @var array<string, array{label: string|null, product: string, type: string|null, order: int}>
|
||||
*/
|
||||
private const CATEGORY_PRESENTATIONS = [
|
||||
'entradas' => [
|
||||
'label' => null,
|
||||
'product' => self::PRODUCT,
|
||||
'type' => null,
|
||||
'order' => 1,
|
||||
],
|
||||
'alojamientos' => [
|
||||
'label' => 'Camping',
|
||||
'product' => 'tipo_alojamiento',
|
||||
'type' => null,
|
||||
'order' => 2,
|
||||
],
|
||||
'camping' => [
|
||||
'label' => null,
|
||||
'product' => 'tipo_alojamiento',
|
||||
'type' => null,
|
||||
'order' => 2,
|
||||
],
|
||||
'comidas' => [
|
||||
'label' => 'Comida',
|
||||
'product' => 'event_date',
|
||||
'type' => 'horario',
|
||||
'order' => 3,
|
||||
],
|
||||
'comida' => [
|
||||
'label' => null,
|
||||
'product' => 'event_date',
|
||||
'type' => 'horario',
|
||||
'order' => 3,
|
||||
],
|
||||
'merchandising' => [
|
||||
'label' => null,
|
||||
'product' => self::PRODUCT,
|
||||
'type' => 'color',
|
||||
'order' => 4,
|
||||
],
|
||||
];
|
||||
|
||||
/**
|
||||
* @return array{
|
||||
* statuses: list<array{value: string, label: string}>,
|
||||
* categories: list<array{
|
||||
* value: string,
|
||||
* label: string,
|
||||
* products: list<array{
|
||||
* value: string,
|
||||
* label: string,
|
||||
* types: list<array{value: string, label: string}>
|
||||
* }>
|
||||
* }>
|
||||
* }
|
||||
*/
|
||||
public function get(Tenant $tenant): array
|
||||
{
|
||||
$items = CatalogItem::query()
|
||||
->where('tenant_code', $tenant->codigo)
|
||||
->where('has_tickets', true)
|
||||
->whereHas('category')
|
||||
->with($this->relations())
|
||||
->orderBy('group_order')
|
||||
->orderBy('nombre')
|
||||
->get();
|
||||
|
||||
return $this->build($items);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return active catalog options plus soft-deleted sources still referenced by
|
||||
* tickets, so historical tickets never become impossible to filter.
|
||||
*
|
||||
* @return array{
|
||||
* statuses: list<array{value: string, label: string}>,
|
||||
* categories: list<array{
|
||||
* value: string,
|
||||
* label: string,
|
||||
* products: list<array{
|
||||
* value: string,
|
||||
* label: string,
|
||||
* types: list<array{value: string, label: string}>
|
||||
* }>
|
||||
* }>
|
||||
* }
|
||||
*/
|
||||
public function getForFilters(Tenant $tenant): array
|
||||
{
|
||||
$historicalVariantIds = Ticket::query()
|
||||
->where('tenant_code', $tenant->codigo)
|
||||
->whereNotNull('source_variant_id')
|
||||
->distinct()
|
||||
->pluck('source_variant_id')
|
||||
->map(fn ($id): int => (int) $id)
|
||||
->all();
|
||||
$historicalCatalogItemIds = Ticket::query()
|
||||
->where('tenant_code', $tenant->codigo)
|
||||
->whereNotNull('source_catalog_item_id')
|
||||
->distinct()
|
||||
->pluck('source_catalog_item_id')
|
||||
->map(fn ($id): int => (int) $id)
|
||||
->merge(
|
||||
Variant::withTrashed()
|
||||
->whereKey($historicalVariantIds)
|
||||
->pluck('catalog_item_id')
|
||||
->map(fn ($id): int => (int) $id),
|
||||
)
|
||||
->unique()
|
||||
->values()
|
||||
->all();
|
||||
|
||||
$items = CatalogItem::withTrashed()
|
||||
->where('tenant_code', $tenant->codigo)
|
||||
->whereHas('category')
|
||||
->where(function ($query) use ($historicalCatalogItemIds): void {
|
||||
$query
|
||||
->where(function ($activeQuery): void {
|
||||
$activeQuery
|
||||
->whereNull('catalog_items.deleted_at')
|
||||
->where('has_tickets', true);
|
||||
})
|
||||
->orWhereIn('catalog_items.id', $historicalCatalogItemIds);
|
||||
})
|
||||
->with([
|
||||
'category',
|
||||
'itemAttributes.attribute.options',
|
||||
'variants' => fn ($query) => $query
|
||||
->withTrashed()
|
||||
->where(function ($variantQuery) use ($historicalVariantIds): void {
|
||||
$variantQuery
|
||||
->whereNull('variantes.deleted_at')
|
||||
->orWhereIn('variantes.id', $historicalVariantIds);
|
||||
}),
|
||||
'variants.definitions.itemAttribute.attribute.options',
|
||||
'variants.eventDates',
|
||||
'variants.eventDate',
|
||||
])
|
||||
->orderBy('group_order')
|
||||
->orderBy('nombre')
|
||||
->get();
|
||||
|
||||
return $this->build($items);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Collection<int, CatalogItem> $items
|
||||
* @return array{
|
||||
* statuses: list<array{value: string, label: string}>,
|
||||
* categories: list<array{
|
||||
* value: string,
|
||||
* label: string,
|
||||
* products: list<array{
|
||||
* value: string,
|
||||
* label: string,
|
||||
* types: list<array{value: string, label: string}>
|
||||
* }>
|
||||
* }>
|
||||
* }
|
||||
*/
|
||||
private function build(Collection $items): array
|
||||
{
|
||||
$categories = [];
|
||||
|
||||
foreach ($items as $item) {
|
||||
$sourceCategory = trim((string) $item->category?->nombre);
|
||||
$categoryValue = mb_strtolower($sourceCategory);
|
||||
$presentation = self::CATEGORY_PRESENTATIONS[$categoryValue] ?? [
|
||||
'label' => null,
|
||||
'product' => self::PRODUCT,
|
||||
'type' => null,
|
||||
'order' => PHP_INT_MAX,
|
||||
];
|
||||
|
||||
$categories[$categoryValue] ??= [
|
||||
'value' => $categoryValue,
|
||||
'label' => $presentation['label'] ?? $sourceCategory,
|
||||
'order' => $presentation['order'],
|
||||
'products' => [],
|
||||
];
|
||||
|
||||
foreach ($this->products($item, $presentation['product'], $presentation['type']) as $product) {
|
||||
$productValue = $product['value'];
|
||||
$existingProduct = $categories[$categoryValue]['products'][$productValue] ?? [
|
||||
'value' => $productValue,
|
||||
'label' => $product['label'],
|
||||
'types' => [],
|
||||
];
|
||||
|
||||
foreach ($product['types'] as $type) {
|
||||
$existingProduct['types'][$type['value']] = $type;
|
||||
}
|
||||
|
||||
$categories[$categoryValue]['products'][$productValue] = $existingProduct;
|
||||
}
|
||||
}
|
||||
|
||||
uasort($categories, fn (array $left, array $right): int => $left['order'] <=> $right['order']
|
||||
?: $left['label'] <=> $right['label']);
|
||||
|
||||
return [
|
||||
'statuses' => [
|
||||
['value' => Ticket::STATUS_ACTIVE, 'label' => 'Activo'],
|
||||
['value' => Ticket::STATUS_USED, 'label' => 'Usado'],
|
||||
['value' => Ticket::STATUS_EXPIRED, 'label' => 'Vencido'],
|
||||
],
|
||||
'categories' => array_values(array_map(
|
||||
fn (array $category): array => [
|
||||
'value' => $category['value'],
|
||||
'label' => $category['label'],
|
||||
'products' => array_values(array_map(
|
||||
fn (array $product): array => [
|
||||
'value' => $product['value'],
|
||||
'label' => $product['label'],
|
||||
'types' => array_values($product['types']),
|
||||
],
|
||||
$category['products'],
|
||||
)),
|
||||
],
|
||||
$categories,
|
||||
)),
|
||||
];
|
||||
}
|
||||
|
||||
/** @return list<string> */
|
||||
private function relations(): array
|
||||
{
|
||||
return [
|
||||
'category',
|
||||
'itemAttributes.attribute.options',
|
||||
'variants.definitions.itemAttribute.attribute.options',
|
||||
'variants.eventDates',
|
||||
'variants.eventDate',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<array{
|
||||
* value: string,
|
||||
* label: string,
|
||||
* types: list<array{value: string, label: string}>
|
||||
* }>
|
||||
*/
|
||||
private function products(CatalogItem $item, string $productCode, ?string $typeCode): array
|
||||
{
|
||||
if ($productCode === self::PRODUCT) {
|
||||
return [[
|
||||
'value' => $item->slug,
|
||||
'label' => $item->nombre,
|
||||
'types' => $this->types($item, $typeCode),
|
||||
]];
|
||||
}
|
||||
|
||||
$products = [];
|
||||
|
||||
foreach ($item->variants as $variant) {
|
||||
foreach ($this->variantOptions($variant, $productCode) as $productOption) {
|
||||
$productValue = $productOption['value'];
|
||||
$products[$productValue] ??= [
|
||||
'value' => $productValue,
|
||||
'label' => $this->optionLabel($productOption['label'], $productCode),
|
||||
'types' => [],
|
||||
];
|
||||
|
||||
foreach ($this->variantOptions($variant, $typeCode) as $typeOption) {
|
||||
$products[$productValue]['types'][$typeOption['value']] = $typeOption;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return array_values(array_map(
|
||||
fn (array $product): array => [
|
||||
'value' => $product['value'],
|
||||
'label' => $product['label'],
|
||||
'types' => array_values($product['types']),
|
||||
],
|
||||
$products,
|
||||
));
|
||||
}
|
||||
|
||||
/** @return list<array{value: string, label: string}> */
|
||||
private function types(CatalogItem $item, ?string $typeCode): array
|
||||
{
|
||||
$types = [];
|
||||
|
||||
foreach ($item->variants as $variant) {
|
||||
foreach ($this->variantOptions($variant, $typeCode) as $typeOption) {
|
||||
$types[$typeOption['value']] = $typeOption;
|
||||
}
|
||||
}
|
||||
|
||||
return array_values($types);
|
||||
}
|
||||
|
||||
/** @return list<array{value: string, label: string}> */
|
||||
private function variantOptions(Variant $variant, ?string $attributeCode): array
|
||||
{
|
||||
if ($attributeCode === null) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$selection = $variant->selectionOptions($variant->catalogItem->itemAttributes)
|
||||
->get($attributeCode);
|
||||
|
||||
if ($selection === null) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return array_is_list($selection) ? $selection : [$selection];
|
||||
}
|
||||
|
||||
private function optionLabel(string $label, string $attributeCode): string
|
||||
{
|
||||
if ($attributeCode !== 'event_date') {
|
||||
return $label;
|
||||
}
|
||||
|
||||
[$day, $month] = array_pad(explode('/', $label), 2, null);
|
||||
|
||||
return $day !== null && $month !== null ? "{$day}/{$month}" : $label;
|
||||
}
|
||||
}
|
||||
|
|
@ -9,7 +9,6 @@ Provee catálogos y opciones auxiliares para construir formularios del panel adm
|
|||
- `EventFormService`: devuelve redes sociales disponibles y las URL configuradas para el tenant.
|
||||
- `SaleFormService`: expone los estados admitidos para compras con sus etiquetas de presentación.
|
||||
- `StaffFormService`: lista categorías raíz que pueden asignarse al personal del tenant.
|
||||
- `TicketFormService`: expone estados y opciones anidadas de categoría, producto y tipo para los tickets de Fiesta Fútbol Infantil.
|
||||
|
||||
Cada servicio tiene un controlador invocable y un `JsonResource` específico. `SocialMediaOptionResource` representa las opciones de redes sociales.
|
||||
|
||||
|
|
@ -20,7 +19,6 @@ Bajo `/v1/adminapp/forms`, con `auth:sanctum` y `adminapp.tenant`:
|
|||
- `GET /event`.
|
||||
- `GET /sale`.
|
||||
- `GET /staff`.
|
||||
- `GET /fiesta-futbol-infantil/ticket`: estados y jerarquía categoría → producto → tipo para filtros de tickets.
|
||||
- `GET /fiesta-futbol-infantil/merchandise`: opciones de color y talle del tenant para merchandising.
|
||||
|
||||
## Dependencias
|
||||
|
|
|
|||
|
|
@ -5,8 +5,6 @@ use App\Domains\Forms\Controllers\AdminApp\FoodFormController;
|
|||
use App\Domains\Forms\Controllers\AdminApp\MerchandiseFormController;
|
||||
use App\Domains\Forms\Controllers\AdminApp\SaleFormController;
|
||||
use App\Domains\Forms\Controllers\AdminApp\StaffFormController;
|
||||
use App\Domains\Forms\Controllers\AdminApp\TicketFilterFormController;
|
||||
use App\Domains\Forms\Controllers\AdminApp\TicketFormController;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
|
||||
Route::prefix('v1/adminapp/forms')
|
||||
|
|
@ -15,13 +13,6 @@ Route::prefix('v1/adminapp/forms')
|
|||
Route::get('event', EventFormController::class);
|
||||
Route::get('sale', SaleFormController::class);
|
||||
Route::get('staff', StaffFormController::class);
|
||||
Route::get('tickets-filter', TicketFilterFormController::class)
|
||||
->middleware('tenant.menu:adminapp.tickets')
|
||||
->name('adminapp.forms.tickets-filter');
|
||||
Route::get(
|
||||
'fiesta-futbol-infantil/ticket',
|
||||
TicketFormController::class
|
||||
);
|
||||
Route::get(
|
||||
'fiesta-futbol-infantil/merchandise',
|
||||
MerchandiseFormController::class
|
||||
|
|
|
|||
|
|
@ -1,42 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Domains\Integration\Controllers;
|
||||
|
||||
use App\Domains\Integration\Models\Integration;
|
||||
use App\Domains\Integration\Requests\StoreIntegrationRequest;
|
||||
use App\Domains\Integration\Requests\UpdateIntegrationRequest;
|
||||
use Illuminate\Routing\Controller;
|
||||
|
||||
class IntegrationController extends Controller
|
||||
{
|
||||
public function index()
|
||||
{
|
||||
return response()->json(Integration::all());
|
||||
}
|
||||
|
||||
public function store(StoreIntegrationRequest $request)
|
||||
{
|
||||
$integration = Integration::create($request->validated());
|
||||
|
||||
return response()->json($integration, 201);
|
||||
}
|
||||
|
||||
public function show(Integration $integration)
|
||||
{
|
||||
return response()->json($integration);
|
||||
}
|
||||
|
||||
public function update(UpdateIntegrationRequest $request, Integration $integration)
|
||||
{
|
||||
$integration->update($request->validated());
|
||||
|
||||
return response()->json($integration->fresh());
|
||||
}
|
||||
|
||||
public function destroy(Integration $integration)
|
||||
{
|
||||
$integration->delete();
|
||||
|
||||
return response()->noContent();
|
||||
}
|
||||
}
|
||||
|
|
@ -1,32 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Domains\Integration\Controllers;
|
||||
|
||||
use App\Domains\Client\Models\Client;
|
||||
use App\Domains\Integration\Requests\TelepagosWebhookRequest;
|
||||
use App\Domains\Integration\Services\TelepagosWebhookService;
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
|
||||
class TelepagosWebhookController extends Controller
|
||||
{
|
||||
/**
|
||||
* Handle the incoming Telepagos webhook.
|
||||
*/
|
||||
public function handle(TelepagosWebhookRequest $request, Client $client, TelepagosWebhookService $service): JsonResponse
|
||||
{
|
||||
try {
|
||||
$cashinId = $request->validated('id');
|
||||
|
||||
$service->handleWebhook($client, $cashinId);
|
||||
|
||||
return response()->json(['status' => 'success']);
|
||||
} catch (\Exception $e) {
|
||||
return response()->json([
|
||||
'status' => 'error',
|
||||
'code' => 'integration.webhook_failed',
|
||||
'message' => __('api.integration.webhook_failed'),
|
||||
], 500);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,24 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Domains\Integration\Requests;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
|
||||
class StoreIntegrationRequest extends FormRequest
|
||||
{
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'integration_code' => ['required', 'string', 'unique:integrations,integration_code'],
|
||||
'name' => ['required', 'string', 'max:255'],
|
||||
'url' => ['nullable', 'url', 'max:255'],
|
||||
'integration_data_schema' => ['nullable', 'array'],
|
||||
'requires_client_configuration' => ['sometimes', 'boolean'],
|
||||
];
|
||||
}
|
||||
}
|
||||
|
|
@ -1,28 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Domains\Integration\Requests;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
|
||||
class TelepagosWebhookRequest extends FormRequest
|
||||
{
|
||||
/**
|
||||
* Determine if the user is authorized to make this request.
|
||||
*/
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the validation rules that apply to the request.
|
||||
*
|
||||
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array|string>
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'id' => ['required', 'string'],
|
||||
];
|
||||
}
|
||||
}
|
||||
|
|
@ -1,27 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Domains\Integration\Requests;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
|
||||
class UpdateIntegrationRequest extends FormRequest
|
||||
{
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
public function rules(): array
|
||||
{
|
||||
$integration = $this->route('integration');
|
||||
|
||||
return [
|
||||
'name' => ['sometimes', 'required', 'string', 'max:255'],
|
||||
'url' => ['nullable', 'url', 'max:255'],
|
||||
'integration_data_schema' => ['nullable', 'array'],
|
||||
'requires_client_configuration' => ['sometimes', 'boolean'],
|
||||
// the code shouldn't ideally be updatable, but if it is:
|
||||
'integration_code' => ['sometimes', 'required', 'string', 'unique:integrations,integration_code,'.($integration->id ?? '')],
|
||||
];
|
||||
}
|
||||
}
|
||||
|
|
@ -1,333 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Domains\Integration\Services;
|
||||
|
||||
use App\Domains\Client\Models\Client;
|
||||
use App\Domains\Purchase\Models\Purchase;
|
||||
use App\Domains\Purchase\Models\TelepagosPayment;
|
||||
use App\Domains\Purchase\Models\TelepagosQr;
|
||||
use App\Domains\Purchase\Services\CheckoutService;
|
||||
use App\Domains\Purchase\Services\DniDistanceService;
|
||||
use Exception;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\Collection;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
class TelepagosWebhookService
|
||||
{
|
||||
public function __construct(
|
||||
private readonly CheckoutService $checkoutService,
|
||||
private readonly DniDistanceService $dniDistance,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Handle the Telepagos webhook notification.
|
||||
*
|
||||
* @throws Exception
|
||||
*/
|
||||
public function handleWebhook(Client $client, string $cashinId): void
|
||||
{
|
||||
Log::channel('telepagos')->info('Telepagos webhook received.', [
|
||||
'client_code' => $client->code,
|
||||
'cashin_id' => $cashinId,
|
||||
]);
|
||||
|
||||
$telepagosService = new TelepagosIntegrationService;
|
||||
$telepagosService->forClient($client);
|
||||
|
||||
try {
|
||||
$details = $telepagosService->getCashinDetails($cashinId);
|
||||
|
||||
$qrOrderId = $details['data']['qr_order_id'] ?? $details['qr_order_id'] ?? null;
|
||||
$amount = $this->normalizeAmount($details['data']['amount'] ?? $details['amount'] ?? 0);
|
||||
$operationId = $details['data']['operation_id'] ?? $details['operation_id'] ?? null;
|
||||
|
||||
$paymentData = [
|
||||
'compra_id' => null,
|
||||
'cuit_buyer' => $details['data']['buyer']['cuit'] ?? $details['buyer']['cuit'] ?? null,
|
||||
'cvu_buyer' => $details['data']['buyer']['cvu'] ?? $details['buyer']['cvu'] ?? null,
|
||||
'amount' => $amount,
|
||||
'concept' => $details['data']['concept'] ?? $details['concept'] ?? null,
|
||||
'operation' => $details['data']['operation'] ?? $details['operation'] ?? null,
|
||||
'operation_id' => $details['data']['operation_id'] ?? $details['operation_id'] ?? null,
|
||||
'transaction_id' => $details['data']['transaction_id'] ?? $details['transaction_id'] ?? null,
|
||||
'qr_order_id' => $qrOrderId,
|
||||
'link_id' => $details['data']['link_id'] ?? $details['link_id'] ?? null,
|
||||
];
|
||||
|
||||
$transferenciaOperationIds = [1, 3, 11];
|
||||
$qrOperationIds = [31, 37, 47];
|
||||
|
||||
$compra = null;
|
||||
|
||||
if (in_array((int) $operationId, $transferenciaOperationIds, true)) {
|
||||
$cuit = $details['data']['buyer']['cuit'] ?? $details['buyer']['cuit'] ?? null;
|
||||
|
||||
if (! $cuit) {
|
||||
Log::channel('telepagos')->warning('Telepagos webhook: CUIT not found for transfer.', [
|
||||
'client_code' => $client->code,
|
||||
'cashin_id' => $cashinId,
|
||||
]);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$dni = substr($cuit, 2, -1);
|
||||
|
||||
$tenantCodes = $client->tenants()->pluck('codigo');
|
||||
$eligiblePurchases = Purchase::query()
|
||||
->whereIn('tenant_codigo', $tenantCodes)
|
||||
->whereIn('status', [
|
||||
Purchase::STATUS_CREATED,
|
||||
Purchase::STATUS_PENDING_PAYMENT,
|
||||
Purchase::STATUS_IN_REVIEW,
|
||||
])
|
||||
->where('payment_method', 'transfer');
|
||||
|
||||
$purchases = (clone $eligiblePurchases)
|
||||
->where('total', $amount)
|
||||
->latest()
|
||||
->get()
|
||||
->filter(fn (Purchase $purchase): bool => $purchase->transfer_payer_dni !== null
|
||||
&& $this->dniDistance->distance($dni, $purchase->transfer_payer_dni) === 0)
|
||||
->values();
|
||||
|
||||
$compra = $purchases->count() === 1 ? $purchases->first() : null;
|
||||
|
||||
if (! $compra) {
|
||||
$candidatePurchases = $this->findTransferCandidates(
|
||||
$eligiblePurchases,
|
||||
$dni,
|
||||
$amount,
|
||||
);
|
||||
if ($candidatePurchases->isNotEmpty()) {
|
||||
$payment = $this->storeTransferCandidates(
|
||||
$paymentData,
|
||||
$candidatePurchases,
|
||||
$dni,
|
||||
$amount,
|
||||
);
|
||||
|
||||
Log::channel('telepagos')->info('Telepagos webhook: Transfer payment candidates found.', [
|
||||
'client_code' => $client->code,
|
||||
'cashin_id' => $cashinId,
|
||||
'telepagos_payment_id' => $payment->id,
|
||||
'amount' => $amount,
|
||||
'candidate_count' => $payment->candidates->count(),
|
||||
'candidates' => $payment->candidates
|
||||
->map(fn ($candidate): array => [
|
||||
'purchase_id' => $candidate->compra_id,
|
||||
'match_reason' => $candidate->match_reason,
|
||||
'dni_distance' => $candidate->dni_distance,
|
||||
'amount_difference' => $candidate->amount_difference,
|
||||
'confidence' => $candidate->confidence,
|
||||
])
|
||||
->all(),
|
||||
]);
|
||||
}
|
||||
|
||||
Log::channel('telepagos')->warning('Telepagos webhook: Expected exactly one matching purchase.', [
|
||||
'client_code' => $client->code,
|
||||
'cashin_id' => $cashinId,
|
||||
'amount' => $amount,
|
||||
'matches' => $purchases->count(),
|
||||
]);
|
||||
|
||||
return;
|
||||
}
|
||||
} elseif (in_array((int) $operationId, $qrOperationIds, true)) {
|
||||
if (! $qrOrderId) {
|
||||
Log::channel('telepagos')->warning('Telepagos webhook: qr_order_id not present in provider response.', [
|
||||
'client_code' => $client->code,
|
||||
'cashin_id' => $cashinId,
|
||||
]);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$telepagosQr = TelepagosQr::where('qr_order_id', $qrOrderId)->first();
|
||||
|
||||
if (! $telepagosQr) {
|
||||
Log::channel('telepagos')->warning('Telepagos webhook: QR not found in database.', [
|
||||
'client_code' => $client->code,
|
||||
'cashin_id' => $cashinId,
|
||||
'qr_order_id' => $qrOrderId,
|
||||
]);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$compra = $telepagosQr->compra;
|
||||
|
||||
if (! $compra) {
|
||||
Log::channel('telepagos')->warning('Telepagos webhook: Purchase not found for QR.', [
|
||||
'client_code' => $client->code,
|
||||
'cashin_id' => $cashinId,
|
||||
'qr_order_id' => $qrOrderId,
|
||||
]);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (! $client->tenants()->where('codigo', $compra->tenant_codigo)->exists()) {
|
||||
Log::channel('telepagos')->warning('Telepagos webhook: Purchase does not belong to client.', [
|
||||
'client_code' => $client->code,
|
||||
'cashin_id' => $cashinId,
|
||||
'purchase_id' => $compra->id,
|
||||
]);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (! in_array($compra->status, [
|
||||
Purchase::STATUS_PENDING_PAYMENT,
|
||||
], true)) {
|
||||
Log::channel('telepagos')->warning('Telepagos webhook: Purchase is not awaiting payment confirmation.', [
|
||||
'client_code' => $client->code,
|
||||
'cashin_id' => $cashinId,
|
||||
'purchase_id' => $compra->id,
|
||||
'purchase_status' => $compra->status,
|
||||
]);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$totalAmount = $this->normalizeAmount($compra->getTotalAmount());
|
||||
|
||||
if ($amount !== $totalAmount) {
|
||||
Log::channel('telepagos')->warning('Telepagos webhook: Amount mismatch.', [
|
||||
'client_code' => $client->code,
|
||||
'cashin_id' => $cashinId,
|
||||
'purchase_id' => $compra->id,
|
||||
'cashin_amount' => $amount,
|
||||
'purchase_amount' => $totalAmount,
|
||||
]);
|
||||
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
Log::channel('telepagos')->warning('Telepagos webhook: Unknown operation_id.', [
|
||||
'client_code' => $client->code,
|
||||
'cashin_id' => $cashinId,
|
||||
'operation_id' => $operationId,
|
||||
]);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$paymentData['compra_id'] = $compra->id;
|
||||
|
||||
DB::transaction(function () use ($compra, $paymentData) {
|
||||
TelepagosPayment::create($paymentData);
|
||||
$this->checkoutService->confirmPaidPurchase($compra);
|
||||
});
|
||||
|
||||
Log::channel('telepagos')->info('Telepagos webhook processed successfully.', [
|
||||
'client_code' => $client->code,
|
||||
'cashin_id' => $cashinId,
|
||||
'purchase_id' => $compra->id,
|
||||
'transaction_id' => $paymentData['transaction_id'],
|
||||
]);
|
||||
} catch (Exception $e) {
|
||||
Log::channel('telepagos')->error('Telepagos webhook processing failed.', [
|
||||
'client_code' => $client->code,
|
||||
'cashin_id' => $cashinId,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
throw $e;
|
||||
}
|
||||
}
|
||||
|
||||
protected function normalizeAmount(mixed $amount): string
|
||||
{
|
||||
return number_format((float) $amount, 2, '.', '');
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Builder<Purchase> $eligiblePurchases
|
||||
* @return Collection<int, Purchase>
|
||||
*/
|
||||
private function findTransferCandidates(Builder $eligiblePurchases, string $dni, string $amount): Collection
|
||||
{
|
||||
$tolerancePercentage = max(
|
||||
0,
|
||||
(float) config('purchase.transfer_candidate_amount_tolerance_percentage', 5),
|
||||
);
|
||||
$numericAmount = (float) $amount;
|
||||
$tolerance = $numericAmount * ($tolerancePercentage / 100);
|
||||
$minimumAmount = $this->normalizeAmount(max(0, $numericAmount - $tolerance));
|
||||
$maximumAmount = $this->normalizeAmount($numericAmount + $tolerance);
|
||||
|
||||
return (clone $eligiblePurchases)
|
||||
->whereBetween('total', [$minimumAmount, $maximumAmount])
|
||||
->latest()
|
||||
->get()
|
||||
->filter(function (Purchase $purchase) use ($dni, $amount): bool {
|
||||
if ($purchase->transfer_payer_dni === null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$purchaseAmount = $this->normalizeAmount($purchase->total);
|
||||
$distance = $this->dniDistance->distance(
|
||||
$dni,
|
||||
(string) $purchase->transfer_payer_dni,
|
||||
);
|
||||
|
||||
return $distance === 0
|
||||
|| ($purchaseAmount === $amount && $distance <= 2);
|
||||
})
|
||||
->values();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $paymentData
|
||||
* @param Collection<int, Purchase> $candidatePurchases
|
||||
*/
|
||||
private function storeTransferCandidates(
|
||||
array $paymentData,
|
||||
Collection $candidatePurchases,
|
||||
string $dni,
|
||||
string $amount,
|
||||
): TelepagosPayment {
|
||||
return DB::transaction(function () use ($paymentData, $candidatePurchases, $dni, $amount): TelepagosPayment {
|
||||
$payment = TelepagosPayment::create($paymentData);
|
||||
|
||||
$payment->candidates()->createMany(
|
||||
$candidatePurchases
|
||||
->map(function (Purchase $purchase) use ($dni, $amount): array {
|
||||
$purchaseAmount = $this->normalizeAmount($purchase->total);
|
||||
$dniDistance = $this->dniDistance->distance(
|
||||
$dni,
|
||||
(string) $purchase->transfer_payer_dni,
|
||||
);
|
||||
$dniMatches = $dniDistance === 0;
|
||||
$amountMatches = $purchaseAmount === $amount;
|
||||
|
||||
return [
|
||||
'compra_id' => $purchase->id,
|
||||
'dni_matches' => $dniMatches,
|
||||
'dni_distance' => $dniDistance,
|
||||
'payment_dni' => $dni,
|
||||
'purchase_dni' => $purchase->transfer_payer_dni,
|
||||
'amount_matches' => $amountMatches,
|
||||
'payment_amount' => $amount,
|
||||
'purchase_amount' => $purchaseAmount,
|
||||
'amount_difference' => $this->normalizeAmount(
|
||||
abs((float) $purchaseAmount - (float) $amount),
|
||||
),
|
||||
'match_reason' => $amountMatches
|
||||
? ($dniMatches ? 'ambiguous_exact_match' : 'exact_amount_near_dni')
|
||||
: 'exact_dni_near_amount',
|
||||
'confidence' => $amountMatches
|
||||
? ($dniMatches ? 'exact' : 'medium')
|
||||
: 'high',
|
||||
];
|
||||
})
|
||||
->all(),
|
||||
);
|
||||
|
||||
return $payment->load('candidates');
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
@ -16,18 +16,15 @@ Gestiona integraciones externas disponibles y su configuración por cliente. Un
|
|||
- `BaseIntegrationService`: resuelve el cliente desde el tenant operativo y carga exclusivamente la configuración del cliente.
|
||||
- `MailService`: envío de correo usando la integración configurada.
|
||||
- `TelepagosIntegrationService`: autenticación, caché de token, generación de QR y consulta de cobros.
|
||||
- `TelepagosWebhookService`: procesa notificaciones recibidas desde Telepagos.
|
||||
|
||||
## Endpoints
|
||||
|
||||
- CRUD global bajo `/integrations`.
|
||||
- Consulta y configuración por cliente bajo `/clients/{client}/integrations`.
|
||||
- `POST /webhooks/telepagos/{client}` para notificaciones del proveedor.
|
||||
|
||||
## Logging de Telepagos
|
||||
|
||||
Los eventos de autenticación, QR, consultas de cuenta y procesamiento de webhooks se escriben en el canal diario `telepagos`, separado del log general. Los archivos se generan en `storage/logs/telepagos/telepagos-YYYY-MM-DD.log`; el nivel y la retención se configuran con `TELEPAGOS_LOG_LEVEL` y `TELEPAGOS_LOG_DAYS`. Tokens y credenciales se eliminan del contexto antes de registrar respuestas del proveedor.
|
||||
Los eventos de autenticación, QR y consultas de cuenta se escriben en el canal diario `telepagos`, separado del log general. Los archivos se generan en `storage/logs/telepagos/telepagos-YYYY-MM-DD.log`; el nivel y la retención se configuran con `TELEPAGOS_LOG_LEVEL` y `TELEPAGOS_LOG_DAYS`. Tokens y credenciales se eliminan del contexto antes de registrar respuestas del proveedor.
|
||||
|
||||
## Dependencias y reglas
|
||||
|
||||
Se integra con `Client`, `Tenant` y con el checkout de `Purchase`. `Notification` utiliza `MailService`. El tenant conserva el contexto operativo y de branding, pero nunca es dueño de credenciales. Las credenciales no se exponen en respuestas ni logs; los webhooks deben validar su contrato antes de alterar una compra.
|
||||
Se integra con `Client`, `Tenant` y con el checkout de `Purchase`. `Notification` utiliza `MailService`. El tenant conserva el contexto operativo y de branding, pero nunca es dueño de credenciales. Las credenciales no se exponen en respuestas ni logs.
|
||||
|
|
|
|||
|
|
@ -1,22 +1,10 @@
|
|||
<?php
|
||||
|
||||
use App\Domains\Integration\Controllers\ClientIntegrationController;
|
||||
use App\Domains\Integration\Controllers\IntegrationController;
|
||||
use App\Domains\Integration\Controllers\TelepagosWebhookController;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
|
||||
Route::group(['prefix' => 'integrations'], function () {
|
||||
Route::get('/', [IntegrationController::class, 'index']);
|
||||
Route::post('/', [IntegrationController::class, 'store']);
|
||||
Route::get('/{integration}', [IntegrationController::class, 'show']);
|
||||
Route::put('/{integration}', [IntegrationController::class, 'update']);
|
||||
Route::delete('/{integration}', [IntegrationController::class, 'destroy']);
|
||||
});
|
||||
|
||||
Route::group(['prefix' => 'clients/{client}/integrations'], function () {
|
||||
Route::get('/', [ClientIntegrationController::class, 'index']);
|
||||
Route::get('/{integration_code}', [ClientIntegrationController::class, 'show']);
|
||||
Route::put('/{integration_code}', [ClientIntegrationController::class, 'store']);
|
||||
});
|
||||
|
||||
Route::post('webhooks/telepagos/{client}', [TelepagosWebhookController::class, 'handle']);
|
||||
|
|
|
|||
|
|
@ -1,32 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Domains\MailTest\Controllers;
|
||||
|
||||
use App\Domains\MailTest\Requests\SendTestMailRequest;
|
||||
use App\Domains\MailTest\Services\MailTestService;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
|
||||
class MailTestController extends Controller
|
||||
{
|
||||
public function __construct(
|
||||
protected MailTestService $mailTestService,
|
||||
) {}
|
||||
|
||||
public function __invoke(SendTestMailRequest $request, string $tenantCode): JsonResponse
|
||||
{
|
||||
$tenant = Tenant::query()
|
||||
->where('codigo', $tenantCode)
|
||||
->firstOrFail();
|
||||
|
||||
return response()->json(
|
||||
$this->mailTestService->send(
|
||||
$tenant,
|
||||
$request->validated('to'),
|
||||
$request->validated('subject'),
|
||||
$request->validated('message'),
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,51 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Domains\MailTest\Mailables;
|
||||
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use Illuminate\Bus\Queueable;
|
||||
use Illuminate\Mail\Mailable;
|
||||
use Illuminate\Mail\Mailables\Content;
|
||||
use Illuminate\Mail\Mailables\Envelope;
|
||||
use Illuminate\Queue\SerializesModels;
|
||||
|
||||
class TestMail extends Mailable
|
||||
{
|
||||
use Queueable, SerializesModels;
|
||||
|
||||
public function __construct(
|
||||
public readonly string $mailSubject,
|
||||
public readonly string $mailMessage,
|
||||
public readonly Tenant $tenant,
|
||||
) {}
|
||||
|
||||
public function envelope(): Envelope
|
||||
{
|
||||
return new Envelope(subject: $this->mailSubject);
|
||||
}
|
||||
|
||||
public function content(): Content
|
||||
{
|
||||
$this->tenant->loadMissing(['headerLogo', 'footerLogo']);
|
||||
|
||||
$branding = [
|
||||
'name' => $this->tenant->nombre,
|
||||
'primary_color' => $this->tenant->primary_color ?? '#6376f3',
|
||||
'body_color' => '#334155',
|
||||
'background_color' => '#f1f5f9',
|
||||
'surface_color' => '#ffffff',
|
||||
'header_bg_color' => $this->tenant->header_bg_color ?? '#ffffff',
|
||||
'footer_bg_color' => $this->tenant->footer_bg_color ?? '#334155',
|
||||
];
|
||||
|
||||
return new Content(
|
||||
view: 'mail.test',
|
||||
with: [
|
||||
'tenant' => $this->tenant,
|
||||
'branding' => $branding,
|
||||
'headerLogoUrl' => $this->tenant->headerLogo?->getTemporaryUrl(1440),
|
||||
'footerLogoUrl' => $this->tenant->footerLogo?->getTemporaryUrl(1440),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,25 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Domains\MailTest\Requests;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
|
||||
class SendTestMailRequest extends FormRequest
|
||||
{
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, array<int, string>>
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'to' => ['required', 'string', 'email', 'max:255'],
|
||||
'subject' => ['nullable', 'string', 'max:255'],
|
||||
'message' => ['nullable', 'string', 'max:5000'],
|
||||
];
|
||||
}
|
||||
}
|
||||
|
|
@ -1,35 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Domains\MailTest\Services;
|
||||
|
||||
use App\Domains\Integration\Services\MailService;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
|
||||
class MailTestService
|
||||
{
|
||||
/**
|
||||
* @return array<string, string>
|
||||
*/
|
||||
public function send(Tenant $tenant, string $recipient, ?string $subject = null, ?string $message = null): array
|
||||
{
|
||||
$subject ??= 'Prueba de correo de Shopit';
|
||||
$message ??= 'Este es un correo de prueba enviado desde Shopit.';
|
||||
|
||||
$mailService = (new MailService)->forTenant($tenant->codigo);
|
||||
$mailService->send(
|
||||
$recipient,
|
||||
$subject,
|
||||
'<h1 style="margin: 0 0 20px;">'.e($subject).'</h1>'
|
||||
.'<p>'.nl2br(e($message)).'</p>',
|
||||
);
|
||||
|
||||
return [
|
||||
'code' => 'mail.test_sent',
|
||||
'message' => __('api.mail.test_sent'),
|
||||
'recipient' => $recipient,
|
||||
'tenant_code' => $tenant->codigo,
|
||||
'mailer' => $mailService->mailerName(),
|
||||
'sent_at' => now()->toIso8601String(),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
|
@ -1,24 +0,0 @@
|
|||
# Dominio MailTest
|
||||
|
||||
## Propósito
|
||||
|
||||
Ofrece una operación técnica para verificar la configuración de correo de un tenant sin ejecutar un flujo funcional real.
|
||||
|
||||
## Componentes
|
||||
|
||||
- `MailTestController`: endpoint invocable de envío.
|
||||
- `SendTestMailRequest`: valida destinatario y contenido requerido.
|
||||
- `MailTestService`: coordina el envío de prueba.
|
||||
- `TestMail`: mailable utilizado para construir el mensaje.
|
||||
|
||||
## Endpoint
|
||||
|
||||
- `POST /{tenant_code}/mail-test/send`.
|
||||
|
||||
## Dependencias
|
||||
|
||||
Usa la configuración de correo del dominio `Integration` y resuelve el tenant indicado.
|
||||
|
||||
## Consideraciones
|
||||
|
||||
Es una herramienta de diagnóstico. Debe restringirse o deshabilitarse en entornos donde no corresponda exponer envíos de prueba, y nunca debe registrar credenciales.
|
||||
|
|
@ -1,6 +0,0 @@
|
|||
<?php
|
||||
|
||||
use App\Domains\MailTest\Controllers\MailTestController;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
|
||||
Route::post('{tenant_code}/mail-test/send', MailTestController::class);
|
||||
|
|
@ -1,79 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Domains\Menu\Controllers;
|
||||
|
||||
use App\Domains\Menu\Models\Menu;
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Validation\Rule;
|
||||
|
||||
class MenuController extends Controller
|
||||
{
|
||||
public function index(): JsonResponse
|
||||
{
|
||||
$menues = Menu::all();
|
||||
|
||||
return response()->json($menues);
|
||||
}
|
||||
|
||||
public function store(Request $request): JsonResponse
|
||||
{
|
||||
$validated = $request->validate([
|
||||
'code' => 'required|string|unique:menues,code',
|
||||
'label' => 'required|string|max:255',
|
||||
'parent_menu_code' => [
|
||||
'nullable',
|
||||
'string',
|
||||
Rule::exists('menues', 'code'),
|
||||
'different:code',
|
||||
],
|
||||
'content_type' => [
|
||||
'sometimes',
|
||||
Rule::in([Menu::CONTENT_TYPE_STATIC, Menu::CONTENT_TYPE_DYNAMIC]),
|
||||
],
|
||||
'static_content_schema' => 'required_if:content_type,static|nullable|array',
|
||||
'route' => 'required|string',
|
||||
]);
|
||||
|
||||
$menu = Menu::create($validated);
|
||||
|
||||
return response()->json($menu, 201);
|
||||
}
|
||||
|
||||
public function show(Menu $menu): JsonResponse
|
||||
{
|
||||
return response()->json($menu);
|
||||
}
|
||||
|
||||
public function update(Request $request, Menu $menu): JsonResponse
|
||||
{
|
||||
$validated = $request->validate([
|
||||
'code' => 'sometimes|required|string|unique:menues,code,'.$menu->id,
|
||||
'label' => 'sometimes|required|string|max:255',
|
||||
'parent_menu_code' => [
|
||||
'nullable',
|
||||
'string',
|
||||
Rule::exists('menues', 'code'),
|
||||
Rule::notIn([$menu->code]),
|
||||
],
|
||||
'content_type' => [
|
||||
'sometimes',
|
||||
Rule::in([Menu::CONTENT_TYPE_STATIC, Menu::CONTENT_TYPE_DYNAMIC]),
|
||||
],
|
||||
'static_content_schema' => 'required_if:content_type,static|nullable|array',
|
||||
'route' => 'sometimes|required|string',
|
||||
]);
|
||||
|
||||
$menu->update($validated);
|
||||
|
||||
return response()->json($menu);
|
||||
}
|
||||
|
||||
public function destroy(Menu $menu): JsonResponse
|
||||
{
|
||||
$menu->delete();
|
||||
|
||||
return response()->json(null, 204);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,32 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Domains\Menu\Controllers;
|
||||
|
||||
use App\Domains\Menu\Models\Menu;
|
||||
use App\Domains\Menu\Requests\StoreTenantMenuRequest;
|
||||
use App\Domains\Menu\Services\TenantMenuService;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
|
||||
class TenantMenuController extends Controller
|
||||
{
|
||||
public function __construct(private readonly TenantMenuService $tenantMenuService) {}
|
||||
|
||||
public function store(
|
||||
StoreTenantMenuRequest $request,
|
||||
string $tenantCode,
|
||||
string $menuCode,
|
||||
): JsonResponse {
|
||||
$tenant = Tenant::query()->where('codigo', $tenantCode)->firstOrFail();
|
||||
$menu = Menu::query()->where('code', $menuCode)->firstOrFail();
|
||||
|
||||
$tenantMenu = $this->tenantMenuService->configure(
|
||||
$tenant,
|
||||
$menu,
|
||||
$request->validated('static_content'),
|
||||
);
|
||||
|
||||
return response()->json($tenantMenu);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,49 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Domains\Menu\Requests;
|
||||
|
||||
use App\Domains\Menu\Models\Menu;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
class StoreTenantMenuRequest extends FormRequest
|
||||
{
|
||||
private ?Menu $menuModel = null;
|
||||
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
protected function prepareForValidation(): void
|
||||
{
|
||||
$this->menuModel = Menu::query()
|
||||
->where('code', $this->route('menu_code'))
|
||||
->first();
|
||||
|
||||
if (! $this->menuModel) {
|
||||
throw ValidationException::withMessages([
|
||||
'menu_code' => __('api.menu.not_found'),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
public function rules(): array
|
||||
{
|
||||
if ($this->menuModel?->content_type !== Menu::CONTENT_TYPE_STATIC) {
|
||||
return [
|
||||
'static_content' => ['nullable', 'array'],
|
||||
];
|
||||
}
|
||||
|
||||
$rules = [
|
||||
'static_content' => ['required', 'array'],
|
||||
];
|
||||
|
||||
foreach ($this->menuModel->static_content_schema as $field => $rule) {
|
||||
$rules["static_content.{$field}"] = $rule;
|
||||
}
|
||||
|
||||
return $rules;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,26 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Domains\Menu\Services;
|
||||
|
||||
use App\Domains\Menu\Models\Menu;
|
||||
use App\Domains\Menu\Models\TenantMenu;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
class TenantMenuService
|
||||
{
|
||||
public function configure(Tenant $tenant, Menu $menu, ?array $staticContent): TenantMenu
|
||||
{
|
||||
return DB::transaction(fn () => TenantMenu::query()->updateOrCreate(
|
||||
[
|
||||
'tenant_code' => $tenant->codigo,
|
||||
'menu_code' => $menu->code,
|
||||
],
|
||||
[
|
||||
'static_content' => $menu->content_type === Menu::CONTENT_TYPE_STATIC
|
||||
? $staticContent
|
||||
: null,
|
||||
],
|
||||
));
|
||||
}
|
||||
}
|
||||
|
|
@ -10,15 +10,6 @@ Define menús disponibles y permite configurar su contenido para cada tenant y r
|
|||
- `TenantMenu`: configuración específica por tenant, incluyendo contenido estático cuando corresponde.
|
||||
- `MenuRole`: asociación entre menú y rol autorizado.
|
||||
|
||||
## Servicios
|
||||
|
||||
`TenantMenuService::configure()` crea o actualiza atómicamente la configuración de un menú para un tenant. Solo conserva `static_content` cuando el menú fue definido como contenido estático.
|
||||
|
||||
## Endpoints
|
||||
|
||||
- Recurso REST `/menues` mediante `MenuController`.
|
||||
- `POST /{tenant_code}/menues/{menu_code}` para configurar un menú del tenant.
|
||||
|
||||
## Dependencias y reglas
|
||||
|
||||
Depende de `Tenant` y `Authorization`. Los códigos de menú y tenant forman la identidad lógica de la configuración; el contenido enviado debe respetar el tipo definido por `Menu`.
|
||||
Depende de `Tenant` y `Authorization`. Los menús se configuran mediante seeders y relaciones internas; no se exponen endpoints públicos de administración.
|
||||
|
|
|
|||
|
|
@ -1,12 +0,0 @@
|
|||
<?php
|
||||
|
||||
use App\Domains\Menu\Controllers\MenuController;
|
||||
use App\Domains\Menu\Controllers\TenantMenuController;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
|
||||
Route::apiResource('menues', MenuController::class);
|
||||
|
||||
Route::post(
|
||||
'{tenant_code}/menues/{menu_code}',
|
||||
[TenantMenuController::class, 'store']
|
||||
);
|
||||
|
|
@ -243,15 +243,6 @@ class PurchaseController extends Controller
|
|||
], 400);
|
||||
}
|
||||
|
||||
public function complete(Request $request, Tenant $tenant, Purchase $compra, CheckoutService $checkoutService): PurchaseResource
|
||||
{
|
||||
$compra = $this->resolveScopedPurchase($tenant, $request->user()->id, $compra);
|
||||
|
||||
return PurchaseResource::make(
|
||||
$checkoutService->completePurchase($compra)
|
||||
);
|
||||
}
|
||||
|
||||
public function submitForReview(
|
||||
Request $request,
|
||||
Tenant $tenant,
|
||||
|
|
|
|||
|
|
@ -145,12 +145,6 @@ class Purchase extends Model
|
|||
return $this->hasMany(TelepagosPayment::class, 'compra_id');
|
||||
}
|
||||
|
||||
/** @return HasMany<TelepagosPaymentCandidate, $this> */
|
||||
public function telepagosPaymentCandidates(): HasMany
|
||||
{
|
||||
return $this->hasMany(TelepagosPaymentCandidate::class, 'compra_id');
|
||||
}
|
||||
|
||||
public function getTotalAmount(): float
|
||||
{
|
||||
if ($this->total !== null) {
|
||||
|
|
|
|||
|
|
@ -6,10 +6,10 @@ use Illuminate\Database\Eloquent\Attributes\Fillable;
|
|||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
|
||||
#[Fillable([
|
||||
'compra_id',
|
||||
'matched_purchase_ids',
|
||||
'cuit_buyer',
|
||||
'cvu_buyer',
|
||||
'amount',
|
||||
|
|
@ -30,6 +30,7 @@ class TelepagosPayment extends Model
|
|||
{
|
||||
return [
|
||||
'compra_id' => 'integer',
|
||||
'matched_purchase_ids' => 'array',
|
||||
'amount' => 'decimal:2',
|
||||
];
|
||||
}
|
||||
|
|
@ -41,10 +42,4 @@ class TelepagosPayment extends Model
|
|||
{
|
||||
return $this->belongsTo(Purchase::class, 'compra_id');
|
||||
}
|
||||
|
||||
/** @return HasMany<TelepagosPaymentCandidate, $this> */
|
||||
public function candidates(): HasMany
|
||||
{
|
||||
return $this->hasMany(TelepagosPaymentCandidate::class, 'telepagos_payment_id');
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,50 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Domains\Purchase\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
#[Fillable([
|
||||
'telepagos_payment_id',
|
||||
'compra_id',
|
||||
'dni_matches',
|
||||
'dni_distance',
|
||||
'payment_dni',
|
||||
'purchase_dni',
|
||||
'amount_matches',
|
||||
'payment_amount',
|
||||
'purchase_amount',
|
||||
'amount_difference',
|
||||
'match_reason',
|
||||
'confidence',
|
||||
])]
|
||||
class TelepagosPaymentCandidate extends Model
|
||||
{
|
||||
protected $table = 'telepagos_payment_candidates';
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'telepagos_payment_id' => 'integer',
|
||||
'compra_id' => 'integer',
|
||||
'dni_matches' => 'boolean',
|
||||
'dni_distance' => 'integer',
|
||||
'amount_matches' => 'boolean',
|
||||
'payment_amount' => 'decimal:2',
|
||||
'purchase_amount' => 'decimal:2',
|
||||
'amount_difference' => 'decimal:2',
|
||||
];
|
||||
}
|
||||
|
||||
public function payment(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(TelepagosPayment::class, 'telepagos_payment_id');
|
||||
}
|
||||
|
||||
public function purchase(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Purchase::class, 'compra_id');
|
||||
}
|
||||
}
|
||||
|
|
@ -4,7 +4,6 @@ namespace App\Domains\Purchase\Resources;
|
|||
|
||||
use App\Domains\Purchase\Models\Purchase;
|
||||
use App\Domains\Purchase\Models\PurchaseItem;
|
||||
use App\Domains\Purchase\Models\TelepagosPaymentCandidate;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
|
|
@ -26,7 +25,6 @@ class PurchaseResource extends JsonResource
|
|||
$ticketsCount = array_key_exists('tickets_count', $this->resource->getAttributes())
|
||||
? (int) $this->resource->getAttribute('tickets_count')
|
||||
: null;
|
||||
$paymentVerification = $this->resolvePaymentVerification();
|
||||
|
||||
$subtotal = $items->isNotEmpty()
|
||||
? $items->reduce(
|
||||
|
|
@ -66,7 +64,6 @@ class PurchaseResource extends JsonResource
|
|||
'items' => PurchaseItemResource::collection($items),
|
||||
'tickets_count' => $this->when($ticketsCount !== null, $ticketsCount),
|
||||
'has_generated_tickets' => $this->when($ticketsCount !== null, $ticketsCount > 0),
|
||||
'payment_verification' => $this->when($paymentVerification !== null, $paymentVerification),
|
||||
'subtotal' => $this->formatMoney($subtotal),
|
||||
'total' => $this->formatMoney($total),
|
||||
];
|
||||
|
|
@ -86,75 +83,4 @@ class PurchaseResource extends JsonResource
|
|||
{
|
||||
return number_format((float) ($amount ?? 0), 2, '.', '');
|
||||
}
|
||||
|
||||
/** @return array<string, mixed>|null */
|
||||
private function resolvePaymentVerification(): ?array
|
||||
{
|
||||
if (
|
||||
$this->status !== Purchase::STATUS_IN_REVIEW
|
||||
|| $this->payment_method !== 'transfer'
|
||||
|| ! $this->resource->relationLoaded('telepagosPaymentCandidates')
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$candidates = $this->resource
|
||||
->getRelation('telepagosPaymentCandidates')
|
||||
->sort(fn (TelepagosPaymentCandidate $left, TelepagosPaymentCandidate $right): int => $this->comparePaymentCandidates($left, $right))
|
||||
->values();
|
||||
/** @var TelepagosPaymentCandidate|null $primary */
|
||||
$primary = $candidates->first();
|
||||
|
||||
return [
|
||||
'status' => $primary === null ? 'pending' : 'candidate',
|
||||
'candidate_count' => $candidates->count(),
|
||||
'primary' => $primary === null ? null : [
|
||||
'reason' => $primary->match_reason,
|
||||
'dni_distance' => $primary->dni_distance,
|
||||
'payment_amount' => $this->formatMoney($primary->payment_amount),
|
||||
'purchase_amount' => $this->formatMoney($primary->purchase_amount),
|
||||
'amount_difference' => $this->formatMoney($primary->amount_difference),
|
||||
'confidence' => $primary->confidence,
|
||||
'detected_at' => $primary->payment?->created_at?->toIso8601String(),
|
||||
],
|
||||
'reasons' => $candidates
|
||||
->pluck('match_reason')
|
||||
->unique()
|
||||
->values()
|
||||
->all(),
|
||||
];
|
||||
}
|
||||
|
||||
private function comparePaymentCandidates(
|
||||
TelepagosPaymentCandidate $left,
|
||||
TelepagosPaymentCandidate $right,
|
||||
): int {
|
||||
$reasonComparison = $this->paymentCandidateRank($left->match_reason)
|
||||
<=> $this->paymentCandidateRank($right->match_reason);
|
||||
|
||||
if ($reasonComparison !== 0) {
|
||||
return $reasonComparison;
|
||||
}
|
||||
|
||||
$differenceComparison = (float) $left->amount_difference <=> (float) $right->amount_difference;
|
||||
|
||||
if ($differenceComparison !== 0) {
|
||||
return $differenceComparison;
|
||||
}
|
||||
|
||||
$leftTimestamp = $left->payment?->created_at?->getTimestamp() ?? 0;
|
||||
$rightTimestamp = $right->payment?->created_at?->getTimestamp() ?? 0;
|
||||
|
||||
return ($rightTimestamp <=> $leftTimestamp) ?: ($right->id <=> $left->id);
|
||||
}
|
||||
|
||||
private function paymentCandidateRank(string $reason): int
|
||||
{
|
||||
return match ($reason) {
|
||||
'ambiguous_exact_match' => 0,
|
||||
'exact_dni_near_amount' => 1,
|
||||
'exact_amount_near_dni' => 2,
|
||||
default => 3,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -18,33 +18,6 @@ class CompleteCheckoutService
|
|||
private readonly PurchaseStateGuard $purchaseState,
|
||||
) {}
|
||||
|
||||
public function complete(Purchase $purchase): Purchase
|
||||
{
|
||||
return DB::transaction(function () use ($purchase): Purchase {
|
||||
$purchase = $this->lockPurchase($purchase);
|
||||
$this->purchaseState->assertNotExpired($purchase);
|
||||
|
||||
if ($purchase->payment_method === null) {
|
||||
throw ValidationException::withMessages([
|
||||
'payment_method' => __('api.purchase.payment_method_required'),
|
||||
]);
|
||||
}
|
||||
|
||||
if ($this->isTerminal($purchase)) {
|
||||
return $this->loadPurchase($purchase);
|
||||
}
|
||||
|
||||
$this->purchaseState->lockCurrentCart($purchase);
|
||||
|
||||
$purchase->update([
|
||||
'status' => Purchase::STATUS_PENDING_PAYMENT,
|
||||
'total' => $purchase->calculateCurrentTotalAmount(),
|
||||
]);
|
||||
|
||||
return $this->loadPurchase($purchase);
|
||||
});
|
||||
}
|
||||
|
||||
public function submitForReview(Purchase $purchase): Purchase
|
||||
{
|
||||
return DB::transaction(function () use ($purchase): Purchase {
|
||||
|
|
@ -171,18 +144,6 @@ class CompleteCheckoutService
|
|||
});
|
||||
}
|
||||
|
||||
private function isTerminal(Purchase $purchase): bool
|
||||
{
|
||||
return in_array($purchase->status, [
|
||||
Purchase::STATUS_PAID,
|
||||
Purchase::STATUS_IN_REVIEW,
|
||||
Purchase::STATUS_CANCELLED,
|
||||
Purchase::STATUS_REJECTED,
|
||||
Purchase::STATUS_EXPIRED,
|
||||
Purchase::STATUS_SUPERSEDED,
|
||||
], true);
|
||||
}
|
||||
|
||||
private function lockPurchase(Purchase $purchase): Purchase
|
||||
{
|
||||
/** @var Purchase */
|
||||
|
|
|
|||
|
|
@ -8,15 +8,6 @@ class PurchaseResponseLoader
|
|||
{
|
||||
public function load(Purchase $purchase): Purchase
|
||||
{
|
||||
$relations = ['tenant', 'items.imageAttachment', 'stockReservation'];
|
||||
|
||||
if (
|
||||
$purchase->status === Purchase::STATUS_IN_REVIEW
|
||||
&& $purchase->payment_method === 'transfer'
|
||||
) {
|
||||
$relations[] = 'telepagosPaymentCandidates.payment';
|
||||
}
|
||||
|
||||
return $purchase->load($relations);
|
||||
return $purchase->load(['tenant', 'items.imageAttachment', 'stockReservation']);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -30,11 +30,6 @@ class CheckoutService
|
|||
return $this->starter->start($tenant, $userId, $purchaseData);
|
||||
}
|
||||
|
||||
public function completePurchase(Purchase $purchase): Purchase
|
||||
{
|
||||
return $this->completer->complete($purchase);
|
||||
}
|
||||
|
||||
public function submitForReview(Purchase $purchase): Purchase
|
||||
{
|
||||
return $this->completer->submitForReview($purchase);
|
||||
|
|
|
|||
|
|
@ -1,82 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Domains\Purchase\Services;
|
||||
|
||||
/**
|
||||
* Measures likely DNI typing errors using the optimal-string-alignment
|
||||
* variant of the Damerau-Levenshtein distance.
|
||||
*
|
||||
* The returned value is the minimum number of single-character edits needed
|
||||
* to transform one DNI into the other. Supported edits are insertion,
|
||||
* deletion, substitution and transposition of two adjacent digits.
|
||||
*/
|
||||
class DniDistanceService
|
||||
{
|
||||
/**
|
||||
* Calculate the edit distance between two normalized DNI strings.
|
||||
*
|
||||
* Each matrix cell [row][column] stores the minimum edits required to
|
||||
* transform the first $row digits of $left into the first $column digits
|
||||
* of $right. The bottom-right cell therefore contains the final distance.
|
||||
*/
|
||||
public function distance(string $left, string $right): int
|
||||
{
|
||||
$left = $this->normalize($left);
|
||||
$right = $this->normalize($right);
|
||||
$leftLength = strlen($left);
|
||||
$rightLength = strlen($right);
|
||||
$matrix = [];
|
||||
|
||||
// Transforming a prefix into an empty string requires deleting every digit.
|
||||
for ($row = 0; $row <= $leftLength; $row++) {
|
||||
$matrix[$row] = [$row];
|
||||
}
|
||||
|
||||
// Transforming an empty string into a prefix requires inserting every digit.
|
||||
for ($column = 0; $column <= $rightLength; $column++) {
|
||||
$matrix[0][$column] = $column;
|
||||
}
|
||||
|
||||
for ($row = 1; $row <= $leftLength; $row++) {
|
||||
for ($column = 1; $column <= $rightLength; $column++) {
|
||||
$substitutionCost = $left[$row - 1] === $right[$column - 1] ? 0 : 1;
|
||||
$deletionDistance = $matrix[$row - 1][$column] + 1;
|
||||
$insertionDistance = $matrix[$row][$column - 1] + 1;
|
||||
$substitutionDistance = $matrix[$row - 1][$column - 1] + $substitutionCost;
|
||||
|
||||
// Keep the cheapest way to align the two prefixes at this position.
|
||||
$matrix[$row][$column] = min(
|
||||
$deletionDistance,
|
||||
$insertionDistance,
|
||||
$substitutionDistance,
|
||||
);
|
||||
|
||||
// Count two adjacent inverted digits as one edit instead of two substitutions.
|
||||
if (
|
||||
$row > 1
|
||||
&& $column > 1
|
||||
&& $left[$row - 1] === $right[$column - 2]
|
||||
&& $left[$row - 2] === $right[$column - 1]
|
||||
) {
|
||||
$matrix[$row][$column] = min(
|
||||
$matrix[$row][$column],
|
||||
$matrix[$row - 2][$column - 2] + 1,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $matrix[$leftLength][$rightLength];
|
||||
}
|
||||
|
||||
/**
|
||||
* Keep only digits and left-pad seven-digit DNIs so comparisons preserve
|
||||
* the leading zero that is present when the DNI is extracted from a CUIT.
|
||||
*/
|
||||
public function normalize(string $dni): string
|
||||
{
|
||||
$digits = preg_replace('/\D+/', '', $dni) ?? '';
|
||||
|
||||
return str_pad($digits, 8, '0', STR_PAD_LEFT);
|
||||
}
|
||||
}
|
||||
|
|
@ -9,7 +9,6 @@ Route::prefix('tenants/{tenant:codigo}')->middleware('auth:sanctum')->group(func
|
|||
Route::get('compras/{compra}', [PurchaseController::class, 'show']);
|
||||
Route::patch('compras/{compra}/customer-data', [PurchaseController::class, 'updateCustomerData']);
|
||||
Route::post('compras/{compra}/payment-intent', [PurchaseController::class, 'paymentIntent']);
|
||||
Route::post('compras/{compra}/complete', [PurchaseController::class, 'complete']);
|
||||
Route::post('compras/{compra}/review', [PurchaseController::class, 'submitForReview']);
|
||||
Route::post('compras/{compra}/cancel', [PurchaseController::class, 'cancel']);
|
||||
});
|
||||
|
|
|
|||
|
|
@ -6,5 +6,8 @@ use Illuminate\Support\Facades\Route;
|
|||
Route::prefix('v1/adminapp/tenant')
|
||||
->middleware(['auth:sanctum', 'adminapp.tenant'])
|
||||
->group(function (): void {
|
||||
Route::apiResource('staff', AdminAppStaffController::class)->except('show');
|
||||
Route::get('staff', [AdminAppStaffController::class, 'index']);
|
||||
Route::post('staff', [AdminAppStaffController::class, 'store']);
|
||||
Route::put('staff/{staff}', [AdminAppStaffController::class, 'update']);
|
||||
Route::delete('staff/{staff}', [AdminAppStaffController::class, 'destroy']);
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,58 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Domains\StorageTest\Controllers;
|
||||
|
||||
use App\Domains\Attachable\Services\AttachmentService;
|
||||
use App\Domains\StorageTest\Requests\GenerateS3TemporaryUrlRequest;
|
||||
use App\Domains\StorageTest\Requests\StoreS3TestFileRequest;
|
||||
use App\Domains\StorageTest\Services\S3TestService;
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
|
||||
class S3TestController extends Controller
|
||||
{
|
||||
public function __construct(
|
||||
protected AttachmentService $attachmentService,
|
||||
protected S3TestService $s3TestService,
|
||||
) {
|
||||
}
|
||||
|
||||
public function store(StoreS3TestFileRequest $request): JsonResponse
|
||||
{
|
||||
$attachment = $this->attachmentService->store(
|
||||
$request->file('file') ?? (string) $request->validated('file_base64'),
|
||||
$request->validated('path'),
|
||||
);
|
||||
|
||||
$temporaryUrl = $this->s3TestService->generateTemporaryUrl(
|
||||
$attachment->path,
|
||||
(int) $request->validated('expires_in_minutes', 10),
|
||||
);
|
||||
|
||||
return response()->json(
|
||||
[
|
||||
'id' => $attachment->id,
|
||||
'key' => $attachment->key,
|
||||
'path' => $attachment->path,
|
||||
'filename' => $attachment->filename,
|
||||
'type' => $attachment->type->value,
|
||||
'mime_type' => $attachment->mime_type,
|
||||
'extension' => $attachment->extension,
|
||||
'size' => $attachment->size,
|
||||
'temporary_url' => $temporaryUrl['temporary_url'],
|
||||
'temporary_url_expires_at' => $temporaryUrl['temporary_url_expires_at'],
|
||||
],
|
||||
201,
|
||||
);
|
||||
}
|
||||
|
||||
public function temporaryUrl(GenerateS3TemporaryUrlRequest $request): JsonResponse
|
||||
{
|
||||
return response()->json(
|
||||
$this->s3TestService->generateTemporaryUrl(
|
||||
$request->validated('path'),
|
||||
(int) $request->validated('expires_in_minutes', 10),
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,24 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Domains\StorageTest\Requests;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
|
||||
class GenerateS3TemporaryUrlRequest extends FormRequest
|
||||
{
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, array<int, string>>
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'path' => ['required', 'string', 'max:2048'],
|
||||
'expires_in_minutes' => ['nullable', 'integer', 'min:1', 'max:1440'],
|
||||
];
|
||||
}
|
||||
}
|
||||
|
|
@ -1,26 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Domains\StorageTest\Requests;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
|
||||
class StoreS3TestFileRequest extends FormRequest
|
||||
{
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, array<int, string>>
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'file' => ['nullable', 'file', 'max:10240', 'required_without:file_base64'],
|
||||
'file_base64' => ['nullable', 'string', 'required_without:file'],
|
||||
'path' => ['required', 'string', 'max:2048'],
|
||||
'expires_in_minutes' => ['nullable', 'integer', 'min:1', 'max:1440'],
|
||||
];
|
||||
}
|
||||
}
|
||||
|
|
@ -1,81 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Domains\StorageTest\Services;
|
||||
|
||||
use Illuminate\Http\UploadedFile;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Illuminate\Support\Str;
|
||||
use RuntimeException;
|
||||
|
||||
class S3TestService
|
||||
{
|
||||
/**
|
||||
* @return array<string, int|string|null>
|
||||
*/
|
||||
public function storeTestFile(
|
||||
UploadedFile $file,
|
||||
?string $directory = null,
|
||||
int $expiresInMinutes = 10,
|
||||
): array {
|
||||
$directory = $this->normalizeDirectory($directory);
|
||||
$disk = Storage::disk('s3');
|
||||
$path = $disk->putFile($directory, $file);
|
||||
|
||||
if (! is_string($path) || $path === '') {
|
||||
Log::error('S3 upload returned an empty path.', [
|
||||
'disk' => 's3',
|
||||
'directory' => $directory,
|
||||
'original_name' => $file->getClientOriginalName(),
|
||||
'mime_type' => $file->getClientMimeType(),
|
||||
'size' => $file->getSize(),
|
||||
]);
|
||||
|
||||
throw new RuntimeException('No se pudo subir el archivo al disco s3.');
|
||||
}
|
||||
|
||||
return [
|
||||
'disk' => 's3',
|
||||
'directory' => $directory,
|
||||
'key' => $path,
|
||||
'path' => $path,
|
||||
'filename' => basename($path),
|
||||
'original_name' => $file->getClientOriginalName(),
|
||||
'mime_type' => $file->getClientMimeType(),
|
||||
'extension' => $file->extension(),
|
||||
'size' => $file->getSize(),
|
||||
'temporary_url' => $disk->temporaryUrl($path, now()->addMinutes($expiresInMinutes)),
|
||||
'temporary_url_expires_at' => now()->addMinutes($expiresInMinutes)->toIso8601String(),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, string>
|
||||
*/
|
||||
public function generateTemporaryUrl(string $path, int $expiresInMinutes = 10): array
|
||||
{
|
||||
return [
|
||||
'disk' => 's3',
|
||||
'key' => $path,
|
||||
'path' => $path,
|
||||
'temporary_url' => $this->temporaryUrlForPath($path, $expiresInMinutes),
|
||||
'temporary_url_expires_at' => now()->addMinutes($expiresInMinutes)->toIso8601String(),
|
||||
];
|
||||
}
|
||||
|
||||
protected function temporaryUrlForPath(string $path, int $expiresInMinutes): string
|
||||
{
|
||||
return Storage::disk('s3')->temporaryUrl($path, now()->addMinutes($expiresInMinutes));
|
||||
}
|
||||
|
||||
protected function normalizeDirectory(?string $directory): string
|
||||
{
|
||||
$directory = trim((string) $directory, '/');
|
||||
|
||||
if ($directory !== '') {
|
||||
return $directory;
|
||||
}
|
||||
|
||||
return 'testing/attachments/'.now()->format('Y/m/d').'/'.Str::uuid();
|
||||
}
|
||||
}
|
||||
|
|
@ -1,23 +0,0 @@
|
|||
# Dominio StorageTest
|
||||
|
||||
## Propósito
|
||||
|
||||
Expone operaciones técnicas para comprobar la escritura en S3 y la generación de URL temporales.
|
||||
|
||||
## Componentes
|
||||
|
||||
- `S3TestController`: recibe solicitudes de carga y URL temporal.
|
||||
- `S3TestService`: almacena un archivo de prueba y genera el enlace firmado.
|
||||
- `StoreS3TestFileRequest`: valida la carga.
|
||||
- `GenerateS3TemporaryUrlRequest`: valida ruta y tiempo de expiración.
|
||||
|
||||
## Endpoints
|
||||
|
||||
Bajo `/storage-test/s3`:
|
||||
|
||||
- `POST /upload`.
|
||||
- `GET /temporary-url`.
|
||||
|
||||
## Consideraciones
|
||||
|
||||
Es infraestructura de diagnóstico, no una API funcional de archivos. Debe restringirse por entorno o autorización. Para adjuntos de negocio se debe usar el dominio `Attachable`.
|
||||
|
|
@ -1,9 +0,0 @@
|
|||
<?php
|
||||
|
||||
use App\Domains\StorageTest\Controllers\S3TestController;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
|
||||
Route::prefix('storage-test/s3')->group(function (): void {
|
||||
Route::post('upload', [S3TestController::class, 'store']);
|
||||
Route::get('temporary-url', [S3TestController::class, 'temporaryUrl']);
|
||||
});
|
||||
|
|
@ -5,7 +5,6 @@ namespace App\Domains\Tenant\Controllers\AdminApp;
|
|||
use App\Domains\Auth\Models\User;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use App\Domains\Tenant\Requests\AdminApp\UpdateWebsiteExtraRequest;
|
||||
use App\Domains\Tenant\Resources\AdminApp\WebsiteExtraResource;
|
||||
use App\Domains\Tenant\Resources\AdminApp\WebsiteExtrasResource;
|
||||
use App\Domains\Tenant\Services\TenantInformationService;
|
||||
use App\Domains\Tenant\Services\WebsiteExtraService;
|
||||
|
|
@ -26,20 +25,6 @@ class WebsiteExtraController extends Controller
|
|||
);
|
||||
}
|
||||
|
||||
public function showExtra(Request $request, string $websiteExtraCode): WebsiteExtraResource
|
||||
{
|
||||
$tenant = $this->loadTenant($request->user());
|
||||
$definition = $this->websiteExtraService->definitionForTenant($tenant, $websiteExtraCode);
|
||||
$websiteExtra = $tenant->websiteExtras
|
||||
->firstWhere('website_type_extra_id', $definition->id);
|
||||
|
||||
if (! $websiteExtra) {
|
||||
abort(404);
|
||||
}
|
||||
|
||||
return WebsiteExtraResource::make($websiteExtra);
|
||||
}
|
||||
|
||||
public function update(
|
||||
UpdateWebsiteExtraRequest $request,
|
||||
string $websiteExtraCode
|
||||
|
|
|
|||
|
|
@ -1,64 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Domains\Tenant\Controllers;
|
||||
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use App\Domains\Tenant\Requests\StoreTenantRequest;
|
||||
use App\Domains\Tenant\Requests\UpdateTenantRequest;
|
||||
use App\Domains\Tenant\Resources\TenantResource;
|
||||
use App\Domains\Tenant\Services\TenantInformationService;
|
||||
use App\Domains\Tenant\Services\TenantService;
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Response;
|
||||
|
||||
class TenantController extends Controller
|
||||
{
|
||||
public function __construct(
|
||||
protected TenantService $tenantService,
|
||||
protected TenantInformationService $tenantInformationService,
|
||||
) {}
|
||||
|
||||
public function index(): JsonResponse
|
||||
{
|
||||
$tenants = Tenant::query()
|
||||
->latest()
|
||||
->paginateFromRequest();
|
||||
|
||||
$this->tenantInformationService->loadMany($tenants->getCollection());
|
||||
|
||||
return TenantResource::collection($tenants)->response();
|
||||
}
|
||||
|
||||
public function store(StoreTenantRequest $request): JsonResponse
|
||||
{
|
||||
$tenant = $this->tenantService->create($request->validated());
|
||||
|
||||
return TenantResource::make(
|
||||
$this->tenantInformationService->load($tenant)
|
||||
)->response()->setStatusCode(201);
|
||||
}
|
||||
|
||||
public function show(Tenant $tenant): TenantResource
|
||||
{
|
||||
return TenantResource::make(
|
||||
$this->tenantInformationService->load($tenant)
|
||||
);
|
||||
}
|
||||
|
||||
public function update(UpdateTenantRequest $request, Tenant $tenant): TenantResource
|
||||
{
|
||||
$tenant = $this->tenantService->update($tenant, $request->validated());
|
||||
|
||||
return TenantResource::make(
|
||||
$this->tenantInformationService->load($tenant)
|
||||
);
|
||||
}
|
||||
|
||||
public function destroy(Tenant $tenant): Response
|
||||
{
|
||||
$tenant->delete();
|
||||
|
||||
return response()->noContent();
|
||||
}
|
||||
}
|
||||
|
|
@ -1,128 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Domains\Tenant\Requests;
|
||||
|
||||
use App\Domains\Catalog\Enums\GroupLayout;
|
||||
use App\Domains\Catalog\Enums\ProductLayout;
|
||||
use App\Domains\Shared\Rules\ImageOrBase64Rule;
|
||||
use App\Domains\Tenant\Enums\CartEditingPolicy;
|
||||
use App\Domains\Tenant\Services\WebsiteExtraService;
|
||||
use App\Domains\Tenant\Support\TenantDomainNormalizer;
|
||||
use Closure;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Validation\Rule;
|
||||
|
||||
class StoreTenantRequest extends FormRequest
|
||||
{
|
||||
protected bool $hasInvalidDomain = false;
|
||||
|
||||
protected bool $hasInvalidBasePath = false;
|
||||
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
protected function prepareForValidation(): void
|
||||
{
|
||||
$rawDomain = $this->input('dominio');
|
||||
$hasExplicitBasePath = $this->has('base_path');
|
||||
$rawBasePath = $hasExplicitBasePath
|
||||
? $this->input('base_path')
|
||||
: TenantDomainNormalizer::pathFromDomain($rawDomain);
|
||||
$normalizedDomain = TenantDomainNormalizer::normalize($rawDomain);
|
||||
$normalizedBasePath = TenantDomainNormalizer::normalizePath($rawBasePath);
|
||||
|
||||
$this->hasInvalidDomain = TenantDomainNormalizer::hasValue($rawDomain)
|
||||
&& $normalizedDomain === null;
|
||||
$this->hasInvalidBasePath = ($hasExplicitBasePath && ! is_string($rawBasePath))
|
||||
|| $normalizedBasePath === null;
|
||||
|
||||
$this->merge([
|
||||
'dominio' => $normalizedDomain,
|
||||
'base_path' => $normalizedBasePath,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
$logoRule = ['required', new ImageOrBase64Rule];
|
||||
|
||||
return array_merge([
|
||||
'client_id' => ['sometimes', 'integer', Rule::exists('clients', 'id')],
|
||||
'codigo' => ['required', 'string', 'max:255', Rule::unique('tenants', 'codigo')],
|
||||
'nombre' => ['required', 'string', 'max:255'],
|
||||
'dominio' => [
|
||||
'bail',
|
||||
function (string $attribute, mixed $value, Closure $fail): void {
|
||||
if ($this->hasInvalidDomain) {
|
||||
$fail("The {$attribute} field must contain a valid domain or URL.");
|
||||
}
|
||||
},
|
||||
'required',
|
||||
'string',
|
||||
'max:255',
|
||||
Rule::unique('tenants', 'dominio')
|
||||
->where('base_path', $this->input('base_path')),
|
||||
],
|
||||
'base_path' => [
|
||||
'bail',
|
||||
function (string $attribute, mixed $value, Closure $fail): void {
|
||||
if ($this->hasInvalidBasePath) {
|
||||
$fail("The {$attribute} field must contain a valid URL path.");
|
||||
}
|
||||
},
|
||||
'required',
|
||||
'string',
|
||||
'max:255',
|
||||
Rule::unique('tenants', 'base_path')
|
||||
->where('dominio', $this->input('dominio')),
|
||||
],
|
||||
'site_title' => ['sometimes', 'nullable', 'string', 'max:255'],
|
||||
'address' => ['sometimes', 'nullable', 'string', 'max:255'],
|
||||
'phone' => ['sometimes', 'nullable', 'string', 'max:255'],
|
||||
'primary_color' => ['required', 'string', 'regex:/^#([a-fA-F0-9]{3,4}|[a-fA-F0-9]{6}|[a-fA-F0-9]{8})$/'],
|
||||
'secondary_color' => ['required', 'string', 'regex:/^#([a-fA-F0-9]{3,4}|[a-fA-F0-9]{6}|[a-fA-F0-9]{8})$/'],
|
||||
'danger_color' => ['required', 'string', 'regex:/^#([a-fA-F0-9]{3,4}|[a-fA-F0-9]{6}|[a-fA-F0-9]{8})$/'],
|
||||
'success_color' => ['required', 'string', 'regex:/^#([a-fA-F0-9]{3,4}|[a-fA-F0-9]{6}|[a-fA-F0-9]{8})$/'],
|
||||
'header_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,
|
||||
'footer_logo' => $logoRule,
|
||||
'favicon' => ['sometimes', 'nullable', new ImageOrBase64Rule],
|
||||
'header_bg_image' => ['sometimes', 'nullable', new ImageOrBase64Rule],
|
||||
'footer_bg_image' => ['sometimes', 'nullable', new ImageOrBase64Rule],
|
||||
'social_media' => ['sometimes', 'array'],
|
||||
'social_media.*.code' => [
|
||||
'required',
|
||||
'string',
|
||||
'distinct',
|
||||
Rule::exists('social_media', 'code'),
|
||||
],
|
||||
'social_media.*.url' => ['required', 'url', 'max:2048'],
|
||||
'social_media.*.orden' => ['sometimes', 'integer', 'min:0', 'distinct'],
|
||||
'search_product_layout' => ['sometimes', Rule::enum(ProductLayout::class)],
|
||||
'search_group_layout' => ['sometimes', Rule::enum(GroupLayout::class)],
|
||||
'search_items_per_page' => ['sometimes', 'integer', 'min:4', 'max:48'],
|
||||
'display_categories' => ['sometimes', 'boolean'],
|
||||
'display_seach_bar' => ['sometimes', 'boolean'],
|
||||
'display_cart' => ['sometimes', 'boolean'],
|
||||
'cart_editing_policy' => ['sometimes', Rule::enum(CartEditingPolicy::class)],
|
||||
'checkout_editing_policy' => [
|
||||
'sometimes',
|
||||
Rule::in([CartEditingPolicy::Disabled->value]),
|
||||
],
|
||||
'display_cart_item_images' => ['sometimes', 'boolean'],
|
||||
'scanner_category_validation_enabled' => ['sometimes', 'boolean'],
|
||||
'website_type_code' => [
|
||||
'required_with:extras',
|
||||
'sometimes',
|
||||
'string',
|
||||
Rule::exists('website_type', 'codigo'),
|
||||
],
|
||||
], app(WebsiteExtraService::class)->requestRules($this->input('website_type_code')));
|
||||
}
|
||||
}
|
||||
|
|
@ -1,143 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Domains\Tenant\Requests;
|
||||
|
||||
use App\Domains\Catalog\Enums\GroupLayout;
|
||||
use App\Domains\Catalog\Enums\ProductLayout;
|
||||
use App\Domains\Shared\Rules\ImageOrBase64Rule;
|
||||
use App\Domains\Tenant\Enums\CartEditingPolicy;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use App\Domains\Tenant\Support\TenantDomainNormalizer;
|
||||
use Closure;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Validation\Rule;
|
||||
|
||||
class UpdateTenantRequest extends FormRequest
|
||||
{
|
||||
protected bool $hasInvalidDomain = false;
|
||||
|
||||
protected bool $hasInvalidBasePath = false;
|
||||
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
protected function prepareForValidation(): void
|
||||
{
|
||||
if ($this->has('dominio')) {
|
||||
$rawDomain = $this->input('dominio');
|
||||
$normalizedDomain = TenantDomainNormalizer::normalize($rawDomain);
|
||||
$embeddedBasePath = TenantDomainNormalizer::pathFromDomain($rawDomain);
|
||||
|
||||
$this->hasInvalidDomain = TenantDomainNormalizer::hasValue($rawDomain)
|
||||
&& ($normalizedDomain === null || $embeddedBasePath === null);
|
||||
|
||||
$this->merge([
|
||||
'dominio' => $normalizedDomain,
|
||||
]);
|
||||
|
||||
if (! $this->has('base_path') && $embeddedBasePath !== null && $embeddedBasePath !== '/') {
|
||||
$this->merge(['base_path' => $embeddedBasePath]);
|
||||
}
|
||||
}
|
||||
|
||||
if ($this->has('base_path')) {
|
||||
$rawBasePath = $this->input('base_path');
|
||||
$normalizedBasePath = TenantDomainNormalizer::normalizePath($rawBasePath);
|
||||
|
||||
$this->hasInvalidBasePath = ! is_string($rawBasePath)
|
||||
|| $normalizedBasePath === null;
|
||||
|
||||
$this->merge(['base_path' => $normalizedBasePath]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
/** @var Tenant|null $tenant */
|
||||
$tenant = $this->route('tenant');
|
||||
$domain = $this->input('dominio', $tenant?->dominio);
|
||||
$basePath = $this->input('base_path', $tenant?->base_path ?? '/');
|
||||
|
||||
$logoRule = ['nullable', new ImageOrBase64Rule];
|
||||
|
||||
return [
|
||||
'client_id' => ['sometimes', 'integer', Rule::exists('clients', 'id')],
|
||||
'codigo' => [
|
||||
'nullable',
|
||||
'string',
|
||||
'max:255',
|
||||
Rule::unique('tenants', 'codigo')->ignore($tenant?->id),
|
||||
],
|
||||
'nombre' => ['nullable', 'string', 'max:255'],
|
||||
'dominio' => [
|
||||
'bail',
|
||||
function (string $attribute, mixed $value, Closure $fail): void {
|
||||
if ($this->hasInvalidDomain) {
|
||||
$fail("The {$attribute} field must contain a valid domain or URL.");
|
||||
}
|
||||
},
|
||||
'nullable',
|
||||
'string',
|
||||
'max:255',
|
||||
Rule::unique('tenants', 'dominio')
|
||||
->where('base_path', $basePath)
|
||||
->ignore($tenant?->id),
|
||||
],
|
||||
'base_path' => [
|
||||
'bail',
|
||||
function (string $attribute, mixed $value, Closure $fail): void {
|
||||
if ($this->hasInvalidBasePath) {
|
||||
$fail("The {$attribute} field must contain a valid URL path.");
|
||||
}
|
||||
},
|
||||
'nullable',
|
||||
'string',
|
||||
'max:255',
|
||||
Rule::unique('tenants', 'base_path')
|
||||
->where('dominio', $domain)
|
||||
->ignore($tenant?->id),
|
||||
],
|
||||
'site_title' => ['sometimes', 'nullable', 'string', 'max:255'],
|
||||
'address' => ['sometimes', 'nullable', 'string', 'max:255'],
|
||||
'phone' => ['sometimes', 'nullable', 'string', 'max:255'],
|
||||
'primary_color' => ['nullable', 'string', 'regex:/^#([a-fA-F0-9]{3,4}|[a-fA-F0-9]{6}|[a-fA-F0-9]{8})$/'],
|
||||
'secondary_color' => ['nullable', 'string', 'regex:/^#([a-fA-F0-9]{3,4}|[a-fA-F0-9]{6}|[a-fA-F0-9]{8})$/'],
|
||||
'danger_color' => ['nullable', 'string', 'regex:/^#([a-fA-F0-9]{3,4}|[a-fA-F0-9]{6}|[a-fA-F0-9]{8})$/'],
|
||||
'success_color' => ['nullable', 'string', 'regex:/^#([a-fA-F0-9]{3,4}|[a-fA-F0-9]{6}|[a-fA-F0-9]{8})$/'],
|
||||
'header_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,
|
||||
'footer_logo' => $logoRule,
|
||||
'favicon' => ['sometimes', 'nullable', new ImageOrBase64Rule],
|
||||
'header_bg_image' => ['sometimes', 'nullable', new ImageOrBase64Rule],
|
||||
'footer_bg_image' => ['sometimes', 'nullable', new ImageOrBase64Rule],
|
||||
'social_media' => ['sometimes', 'array'],
|
||||
'social_media.*.code' => [
|
||||
'required',
|
||||
'string',
|
||||
'distinct',
|
||||
Rule::exists('social_media', 'code'),
|
||||
],
|
||||
'social_media.*.url' => ['required', 'url', 'max:2048'],
|
||||
'social_media.*.orden' => ['sometimes', 'integer', 'min:0', 'distinct'],
|
||||
'search_product_layout' => ['sometimes', Rule::enum(ProductLayout::class)],
|
||||
'search_group_layout' => ['sometimes', Rule::enum(GroupLayout::class)],
|
||||
'search_items_per_page' => ['sometimes', 'integer', 'min:4', 'max:48'],
|
||||
'display_categories' => ['sometimes', 'boolean'],
|
||||
'display_seach_bar' => ['sometimes', 'boolean'],
|
||||
'display_cart' => ['sometimes', 'boolean'],
|
||||
'cart_editing_policy' => ['sometimes', Rule::enum(CartEditingPolicy::class)],
|
||||
'checkout_editing_policy' => [
|
||||
'sometimes',
|
||||
Rule::in([CartEditingPolicy::Disabled->value]),
|
||||
],
|
||||
'display_cart_item_images' => ['sometimes', 'boolean'],
|
||||
'scanner_category_validation_enabled' => ['sometimes', 'boolean'],
|
||||
];
|
||||
}
|
||||
}
|
||||
|
|
@ -1,86 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Domains\Tenant\Resources\AdminApp;
|
||||
|
||||
use App\Domains\Attachable\Models\Attachment;
|
||||
use App\Domains\Attachable\Models\AttachmentCrop;
|
||||
use App\Domains\Tenant\Models\WebsiteExtra;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
/**
|
||||
* @mixin WebsiteExtra
|
||||
*/
|
||||
class WebsiteExtraResource extends JsonResource
|
||||
{
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
'codigo' => $this->websiteTypeExtra->codigo,
|
||||
'nombre' => $this->websiteTypeExtra->nombre,
|
||||
'descripcion' => $this->websiteTypeExtra->descripcion,
|
||||
'is_required' => $this->websiteTypeExtra->is_required,
|
||||
'is_enabled' => $this->is_enabled,
|
||||
'request_rules' => $this->websiteTypeExtra->config_schema['request_rules'] ?? [],
|
||||
'config' => $this->formatConfig(
|
||||
$this->resolvedConfig(),
|
||||
fn (Attachment $attachment): string => $attachment->key
|
||||
),
|
||||
'resolved_config' => $this->formatConfig(
|
||||
$this->resolvedAdminConfig(),
|
||||
fn (Attachment $attachment): string => $attachment->getTemporaryUrl(1440)
|
||||
),
|
||||
];
|
||||
}
|
||||
|
||||
private function resolvedAdminConfig(): mixed
|
||||
{
|
||||
$config = $this->resolvedConfig();
|
||||
|
||||
if (
|
||||
$this->websiteTypeExtra->codigo !== 'heroConfig'
|
||||
|| ! is_array($config)
|
||||
|| ! ($config['background_image_id'] ?? null) instanceof Attachment
|
||||
) {
|
||||
return $config;
|
||||
}
|
||||
|
||||
$attachment = $config['background_image_id'];
|
||||
$fullRange = ['start_percentage' => 0.0, 'end_percentage' => 100.0];
|
||||
$crops = $attachment->cropVariants->keyBy('variant');
|
||||
$config['background_image_id'] = [
|
||||
'url' => $attachment->getTemporaryUrl(1440),
|
||||
'crops' => collect(AttachmentCrop::VARIANTS)->mapWithKeys(
|
||||
function (string $variant) use ($crops, $fullRange): array {
|
||||
$crop = $crops->get($variant);
|
||||
|
||||
return [$variant => [
|
||||
'crop_horizontal' => $crop?->crop_horizontal ?? $fullRange,
|
||||
'crop_vertical' => $crop?->crop_vertical ?? $fullRange,
|
||||
]];
|
||||
}
|
||||
)->all(),
|
||||
];
|
||||
|
||||
return $config;
|
||||
}
|
||||
|
||||
private function formatConfig(mixed $value, callable $formatAttachment): mixed
|
||||
{
|
||||
if ($value instanceof Attachment) {
|
||||
return $formatAttachment($value);
|
||||
}
|
||||
|
||||
if (! is_array($value)) {
|
||||
return $value;
|
||||
}
|
||||
|
||||
return array_map(
|
||||
fn (mixed $item): mixed => $this->formatConfig($item, $formatAttachment),
|
||||
$value
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
@ -7,7 +7,6 @@ Route::prefix('v1/adminapp/tenant')
|
|||
->middleware(['auth:sanctum', 'adminapp.tenant'])
|
||||
->group(function (): void {
|
||||
Route::get('website-extras', [WebsiteExtraController::class, 'show']);
|
||||
Route::get('website-extras/{websiteExtraCode}', [WebsiteExtraController::class, 'showExtra']);
|
||||
Route::put('website-extras/{websiteExtraCode}', [WebsiteExtraController::class, 'update']);
|
||||
Route::patch('website-extras/{websiteExtraCode}/toggle', [WebsiteExtraController::class, 'toggle']);
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,8 +1,3 @@
|
|||
<?php
|
||||
|
||||
use App\Domains\Tenant\Controllers\TenantController;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
|
||||
Route::apiResource('tenants', TenantController::class);
|
||||
|
||||
require __DIR__.'/adminapp.php';
|
||||
|
|
|
|||
|
|
@ -1,53 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Domains\Ticket\Controllers\AdminApp;
|
||||
|
||||
use App\Domains\Ticket\Requests\AdminAppTicketExportRequest;
|
||||
use App\Domains\Ticket\Requests\AdminAppTicketIndexRequest;
|
||||
use App\Domains\Ticket\Resources\AdminApp\AdminAppTicketCollection;
|
||||
use App\Domains\Ticket\Services\AdminAppTicketExcelService;
|
||||
use App\Domains\Ticket\Services\AdminAppTicketPdfService;
|
||||
use App\Domains\Ticket\Services\AdminAppTicketService;
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\Response;
|
||||
use Symfony\Component\HttpFoundation\StreamedResponse;
|
||||
|
||||
class TicketController extends Controller
|
||||
{
|
||||
public function __construct(
|
||||
private readonly AdminAppTicketService $ticketService,
|
||||
private readonly AdminAppTicketPdfService $ticketPdfService,
|
||||
private readonly AdminAppTicketExcelService $ticketExcelService,
|
||||
) {}
|
||||
|
||||
public function index(AdminAppTicketIndexRequest $request): AdminAppTicketCollection
|
||||
{
|
||||
$tenant = $request->user()->tenant()->firstOrFail();
|
||||
|
||||
return new AdminAppTicketCollection(
|
||||
$this->ticketService->search($tenant, $request->validated())
|
||||
);
|
||||
}
|
||||
|
||||
public function downloadPdf(AdminAppTicketExportRequest $request): Response
|
||||
{
|
||||
$tenant = $request->user()->tenant()->firstOrFail();
|
||||
|
||||
return $this->ticketPdfService->download(
|
||||
$tenant,
|
||||
$this->ticketService->ticketsForExport($tenant, $request->validated()),
|
||||
$request->validated('timezone'),
|
||||
);
|
||||
}
|
||||
|
||||
public function downloadExcel(AdminAppTicketExportRequest $request): StreamedResponse
|
||||
{
|
||||
$tenant = $request->user()->tenant()->firstOrFail();
|
||||
|
||||
return $this->ticketExcelService->download(
|
||||
$tenant,
|
||||
$this->ticketService->ticketsForExport($tenant, $request->validated()),
|
||||
$request->validated('timezone'),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,17 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Domains\Ticket\Requests;
|
||||
|
||||
use App\Domains\Shared\Rules\ValidTimezone;
|
||||
|
||||
class AdminAppTicketExportRequest extends AdminAppTicketIndexRequest
|
||||
{
|
||||
/** @return array<string, mixed> */
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
...parent::rules(),
|
||||
'timezone' => ['required', 'string', new ValidTimezone],
|
||||
];
|
||||
}
|
||||
}
|
||||
|
|
@ -1,46 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Domains\Ticket\Requests;
|
||||
|
||||
use App\Domains\Ticket\Models\Ticket;
|
||||
use App\Domains\Ticket\Services\AdminAppTicketColumnService;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Validation\Rule;
|
||||
|
||||
class AdminAppTicketIndexRequest extends FormRequest
|
||||
{
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/** @return array<string, list<string>> */
|
||||
public function rules(): array
|
||||
{
|
||||
$tenant = $this->user()?->tenant()->first();
|
||||
$sortableKeys = $tenant === null
|
||||
? []
|
||||
: app(AdminAppTicketColumnService::class)->sortableKeys($tenant);
|
||||
|
||||
return [
|
||||
'q' => ['sometimes', 'nullable', 'string', 'max:255'],
|
||||
'category' => ['sometimes', 'nullable', 'string', 'max:255'],
|
||||
'product' => ['sometimes', 'nullable', 'string', 'max:255'],
|
||||
'type' => ['sometimes', 'nullable', 'string', 'max:255'],
|
||||
'date' => ['sometimes', 'nullable', 'date_format:Y-m-d'],
|
||||
'status' => [
|
||||
'sometimes',
|
||||
'nullable',
|
||||
Rule::in([
|
||||
Ticket::STATUS_ACTIVE,
|
||||
Ticket::STATUS_USED,
|
||||
Ticket::STATUS_EXPIRED,
|
||||
]),
|
||||
],
|
||||
'page' => ['sometimes', 'integer', 'min:1'],
|
||||
'per_page' => ['sometimes', 'integer', 'min:1', 'max:100'],
|
||||
'sort_by' => ['sometimes', 'nullable', 'string', Rule::in($sortableKeys)],
|
||||
'sort_direction' => ['sometimes', 'nullable', 'string', Rule::in(['asc', 'desc'])],
|
||||
];
|
||||
}
|
||||
}
|
||||
|
|
@ -1,34 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Domains\Ticket\Resources\AdminApp;
|
||||
|
||||
use App\Domains\Ticket\Services\AdminAppTicketResult;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\ResourceCollection;
|
||||
|
||||
class AdminAppTicketCollection extends ResourceCollection
|
||||
{
|
||||
/** @var class-string<AdminAppTicketResource> */
|
||||
public $collects = AdminAppTicketResource::class;
|
||||
|
||||
private readonly int $scannedTickets;
|
||||
|
||||
private readonly int $totalTickets;
|
||||
|
||||
public function __construct(AdminAppTicketResult $result)
|
||||
{
|
||||
parent::__construct($result->tickets);
|
||||
|
||||
$this->scannedTickets = $result->scannedTickets;
|
||||
$this->totalTickets = $result->totalTickets;
|
||||
}
|
||||
|
||||
/** @return array{scanned_tickets: int, total_tickets: int} */
|
||||
public function with(Request $request): array
|
||||
{
|
||||
return [
|
||||
'scanned_tickets' => $this->scannedTickets,
|
||||
'total_tickets' => $this->totalTickets,
|
||||
];
|
||||
}
|
||||
}
|
||||
|
|
@ -1,25 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Domains\Ticket\Resources\AdminApp;
|
||||
|
||||
use App\Domains\Ticket\Models\Ticket;
|
||||
use App\Domains\Ticket\Resources\TicketResource;
|
||||
use App\Domains\Ticket\Services\AdminAppTicketRowService;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
/** @mixin Ticket */
|
||||
class AdminAppTicketResource extends TicketResource
|
||||
{
|
||||
/** @return array<string, mixed> */
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
$rowService = app(AdminAppTicketRowService::class);
|
||||
$details = $rowService->details($this->resource);
|
||||
|
||||
return [
|
||||
...parent::toArray($request),
|
||||
...$details,
|
||||
'values' => $rowService->values($this->resource, $details),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
|
@ -1,103 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Domains\Ticket\Services;
|
||||
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
|
||||
class AdminAppTicketColumnService
|
||||
{
|
||||
private const FIESTA_FUTBOL_INFANTIL = 'fiesta_futbol_infantil';
|
||||
|
||||
/** @return list<array{key: string, label: string, type: string, sortable: bool, sort_param: string, width: string, excel_width: int}> */
|
||||
public function columns(Tenant $tenant): array
|
||||
{
|
||||
$keys = $tenant->codigo === self::FIESTA_FUTBOL_INFANTIL
|
||||
? ['order_number', 'category', 'product', 'type', 'amount', 'client', 'ticket', 'date', 'status', 'scanned_by']
|
||||
: ['order_number', 'product', 'amount', 'client', 'ticket', 'date', 'status', 'scanned_by'];
|
||||
|
||||
$columns = array_map(fn (string $key): array => $this->definitions()[$key], $keys);
|
||||
|
||||
if ($tenant->codigo === self::FIESTA_FUTBOL_INFANTIL) {
|
||||
$columns = array_map(function (array $column): array {
|
||||
if (in_array($column['key'], ['product', 'type'], true)) {
|
||||
$column['sortable'] = false;
|
||||
}
|
||||
|
||||
return $column;
|
||||
}, $columns);
|
||||
} else {
|
||||
$widths = [
|
||||
'order_number' => '11%',
|
||||
'product' => '15%',
|
||||
'amount' => '10%',
|
||||
'client' => '15%',
|
||||
'ticket' => '19%',
|
||||
'date' => '11%',
|
||||
'status' => '8%',
|
||||
'scanned_by' => '11%',
|
||||
];
|
||||
$columns = array_map(function (array $column) use ($widths): array {
|
||||
$column['width'] = $widths[$column['key']];
|
||||
|
||||
return $column;
|
||||
}, $columns);
|
||||
}
|
||||
|
||||
return $columns;
|
||||
}
|
||||
|
||||
/** @return list<array{key: string, label: string, type: string, sortable: bool, sort_param: string, width: string}> */
|
||||
public function publicColumns(Tenant $tenant): array
|
||||
{
|
||||
return array_map(function (array $column): array {
|
||||
unset($column['excel_width']);
|
||||
|
||||
return $column;
|
||||
}, $this->columns($tenant));
|
||||
}
|
||||
|
||||
/** @return list<string> */
|
||||
public function sortableKeys(Tenant $tenant): array
|
||||
{
|
||||
return array_values(array_map(
|
||||
fn (array $column): string => $column['sort_param'],
|
||||
array_filter($this->columns($tenant), fn (array $column): bool => $column['sortable']),
|
||||
));
|
||||
}
|
||||
|
||||
/** @return array<string, array{key: string, label: string, type: string, sortable: bool, sort_param: string, width: string, excel_width: int}> */
|
||||
private function definitions(): array
|
||||
{
|
||||
return [
|
||||
'order_number' => $this->column('order_number', 'N° de orden', 'order_number', '10.5%', 14),
|
||||
'category' => $this->column('category', 'Categoría', 'text', '11%', 18),
|
||||
'product' => $this->column('product', 'Producto', 'text', '11%', 22),
|
||||
'type' => $this->column('type', 'Tipo', 'text', '8%', 18),
|
||||
'amount' => $this->column('amount', 'Importe', 'currency', '9%', 15),
|
||||
'client' => $this->column('client', 'Cliente', 'text', '13%', 30),
|
||||
'ticket' => $this->column('ticket', 'ID', 'text', '14.5%', 39),
|
||||
'date' => $this->column('date', 'Fecha', 'date', '9.5%', 20),
|
||||
'status' => $this->column('status', 'Estado', 'status', '7%', 13),
|
||||
'scanned_by' => $this->column('scanned_by', 'Escaneado por', 'text', '9%', 28),
|
||||
];
|
||||
}
|
||||
|
||||
/** @return array{key: string, label: string, type: string, sortable: bool, sort_param: string, width: string, excel_width: int} */
|
||||
private function column(
|
||||
string $key,
|
||||
string $label,
|
||||
string $type,
|
||||
string $width,
|
||||
int $excelWidth,
|
||||
): array {
|
||||
return [
|
||||
'key' => $key,
|
||||
'label' => $label,
|
||||
'type' => $type,
|
||||
'sortable' => true,
|
||||
'sort_param' => $key,
|
||||
'width' => $width,
|
||||
'excel_width' => $excelWidth,
|
||||
];
|
||||
}
|
||||
}
|
||||
|
|
@ -1,105 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Domains\Ticket\Services;
|
||||
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use App\Domains\Ticket\Models\Ticket;
|
||||
use Carbon\CarbonInterface;
|
||||
use Illuminate\Support\Collection;
|
||||
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
|
||||
use PhpOffice\PhpSpreadsheet\Cell\DataType;
|
||||
use PhpOffice\PhpSpreadsheet\Shared\Date;
|
||||
use PhpOffice\PhpSpreadsheet\Spreadsheet;
|
||||
use PhpOffice\PhpSpreadsheet\Style\Alignment;
|
||||
use PhpOffice\PhpSpreadsheet\Style\Fill;
|
||||
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
|
||||
use Symfony\Component\HttpFoundation\StreamedResponse;
|
||||
|
||||
class AdminAppTicketExcelService
|
||||
{
|
||||
public function __construct(
|
||||
private readonly AdminAppTicketReportService $reportService,
|
||||
private readonly AdminAppTicketColumnService $columnService,
|
||||
) {}
|
||||
|
||||
/** @param Collection<int, Ticket> $tickets */
|
||||
public function download(Tenant $tenant, Collection $tickets, string $timeZone): StreamedResponse
|
||||
{
|
||||
$generatedAt = now();
|
||||
$rows = $this->reportService->rows($tickets);
|
||||
$columns = $this->columnService->columns($tenant);
|
||||
$spreadsheet = new Spreadsheet;
|
||||
$spreadsheet->getProperties()
|
||||
->setCreator('Shopit')
|
||||
->setTitle('Listado de tickets')
|
||||
->setSubject($tenant->nombre);
|
||||
$sheet = $spreadsheet->getActiveSheet();
|
||||
$sheet->setTitle('Tickets');
|
||||
$sheet->fromArray([array_column($columns, 'label')], null, 'A1');
|
||||
|
||||
foreach ($rows as $index => $ticket) {
|
||||
$row = $index + 2;
|
||||
foreach ($columns as $columnIndex => $column) {
|
||||
$coordinate = Coordinate::stringFromColumnIndex($columnIndex + 1).$row;
|
||||
$value = $ticket[$column['key']] ?? null;
|
||||
|
||||
if ($column['type'] === 'currency' && $value !== null) {
|
||||
$sheet->setCellValue($coordinate, (float) $value);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($column['type'] === 'date' && $value instanceof CarbonInterface) {
|
||||
$sheet->setCellValue(
|
||||
$coordinate,
|
||||
Date::dateTimeToExcel($value->copy()->timezone($timeZone)),
|
||||
);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$sheet->setCellValueExplicit(
|
||||
$coordinate,
|
||||
$this->reportService->displayValue($value, $column['type'], $timeZone),
|
||||
DataType::TYPE_STRING,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
$lastRow = max(2, $rows->count() + 1);
|
||||
$lastColumn = Coordinate::stringFromColumnIndex(count($columns));
|
||||
foreach ($columns as $columnIndex => $column) {
|
||||
$letter = Coordinate::stringFromColumnIndex($columnIndex + 1);
|
||||
if ($column['type'] === 'currency') {
|
||||
$sheet->getStyle("{$letter}2:{$letter}{$lastRow}")
|
||||
->getNumberFormat()->setFormatCode('$ #,##0.00');
|
||||
}
|
||||
if ($column['type'] === 'date') {
|
||||
$sheet->getStyle("{$letter}2:{$letter}{$lastRow}")
|
||||
->getNumberFormat()->setFormatCode('dd/mm/yyyy hh:mm');
|
||||
}
|
||||
$sheet->getColumnDimension($letter)->setWidth($column['excel_width']);
|
||||
}
|
||||
$sheet->getStyle("A1:{$lastColumn}1")->applyFromArray([
|
||||
'font' => ['bold' => true, 'color' => ['rgb' => 'FFFFFF']],
|
||||
'fill' => [
|
||||
'fillType' => Fill::FILL_SOLID,
|
||||
'startColor' => ['rgb' => '26382E'],
|
||||
],
|
||||
'alignment' => ['vertical' => Alignment::VERTICAL_CENTER],
|
||||
]);
|
||||
$sheet->getRowDimension(1)->setRowHeight(24);
|
||||
$sheet->freezePane('A2');
|
||||
$sheet->setAutoFilter("A1:{$lastColumn}{$lastRow}");
|
||||
|
||||
$filename = 'tickets_'.$tenant->codigo.'_'
|
||||
.$generatedAt->copy()->timezone($timeZone)->format('Ymd_His').'.xlsx';
|
||||
|
||||
return response()->streamDownload(function () use ($spreadsheet): void {
|
||||
(new Xlsx($spreadsheet))->save('php://output');
|
||||
$spreadsheet->disconnectWorksheets();
|
||||
}, $filename, [
|
||||
'Content-Type' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,56 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Domains\Ticket\Services;
|
||||
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use App\Domains\Ticket\Models\Ticket;
|
||||
use Barryvdh\DomPDF\Facade\Pdf;
|
||||
use Barryvdh\DomPDF\PDF as DomPdf;
|
||||
use Illuminate\Http\Response;
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
class AdminAppTicketPdfService
|
||||
{
|
||||
public function __construct(
|
||||
private readonly AdminAppTicketReportService $reportService,
|
||||
private readonly AdminAppTicketColumnService $columnService,
|
||||
) {}
|
||||
|
||||
/** @param Collection<int, Ticket> $tickets */
|
||||
public function download(Tenant $tenant, Collection $tickets, string $timeZone): Response
|
||||
{
|
||||
$generatedAt = now();
|
||||
$columns = $this->columnService->columns($tenant);
|
||||
$rows = $this->reportService->rows($tickets);
|
||||
$pdf = Pdf::loadView('pdf.adminapp.tickets', [
|
||||
'tenant' => $tenant,
|
||||
'columns' => $columns,
|
||||
'tickets' => $this->reportService->displayRows($rows, $columns, $timeZone),
|
||||
'generatedAt' => $generatedAt,
|
||||
'timeZone' => $timeZone,
|
||||
])->setPaper('a3', 'landscape');
|
||||
|
||||
$this->addPageNumbers($pdf);
|
||||
|
||||
return $pdf->download(
|
||||
'tickets_'.$tenant->codigo.'_'
|
||||
.$generatedAt->copy()->timezone($timeZone)->format('Ymd_His').'.pdf'
|
||||
);
|
||||
}
|
||||
|
||||
private function addPageNumbers(DomPdf $pdf): void
|
||||
{
|
||||
$pdf->render();
|
||||
$domPdf = $pdf->getDomPDF();
|
||||
$font = $domPdf->getFontMetrics()->getFont('DejaVu Sans');
|
||||
|
||||
$domPdf->getCanvas()->page_text(
|
||||
565,
|
||||
805,
|
||||
'Página {PAGE_NUM} de {PAGE_COUNT}',
|
||||
$font,
|
||||
7,
|
||||
[0.48, 0.52, 0.49],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,35 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Domains\Ticket\Services;
|
||||
|
||||
use App\Domains\Ticket\Models\Ticket;
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
class AdminAppTicketReportService
|
||||
{
|
||||
public function __construct(private readonly AdminAppTicketRowService $rowService) {}
|
||||
|
||||
/**
|
||||
* @param Collection<int, Ticket> $tickets
|
||||
* @return Collection<int, array<string, mixed>>
|
||||
*/
|
||||
public function rows(Collection $tickets): Collection
|
||||
{
|
||||
return $this->rowService->rows($tickets);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Collection<int, array<string, mixed>> $rows
|
||||
* @param list<array<string, mixed>> $columns
|
||||
* @return Collection<int, array<string, string>>
|
||||
*/
|
||||
public function displayRows(Collection $rows, array $columns, string $timeZone): Collection
|
||||
{
|
||||
return $this->rowService->displayRows($rows, $columns, $timeZone);
|
||||
}
|
||||
|
||||
public function displayValue(mixed $value, string $type, string $timeZone): string
|
||||
{
|
||||
return $this->rowService->displayValue($value, $type, $timeZone);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,16 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Domains\Ticket\Services;
|
||||
|
||||
use App\Domains\Ticket\Models\Ticket;
|
||||
use Illuminate\Pagination\LengthAwarePaginator;
|
||||
|
||||
final readonly class AdminAppTicketResult
|
||||
{
|
||||
/** @param LengthAwarePaginator<Ticket> $tickets */
|
||||
public function __construct(
|
||||
public LengthAwarePaginator $tickets,
|
||||
public int $scannedTickets,
|
||||
public int $totalTickets,
|
||||
) {}
|
||||
}
|
||||
|
|
@ -1,217 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Domains\Ticket\Services;
|
||||
|
||||
use App\Domains\Catalog\Models\ItemAttribute;
|
||||
use App\Domains\Purchase\Models\PurchaseItem;
|
||||
use App\Domains\Ticket\Models\Ticket;
|
||||
use Carbon\Carbon;
|
||||
use Carbon\CarbonInterface;
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
class AdminAppTicketRowService
|
||||
{
|
||||
private const FIESTA_FUTBOL_INFANTIL = 'fiesta_futbol_infantil';
|
||||
|
||||
private const CATEGORY_PRESENTATIONS = [
|
||||
'alojamientos' => ['category' => 'Camping', 'product' => 'tipo_alojamiento', 'type' => null],
|
||||
'camping' => ['category' => null, 'product' => 'tipo_alojamiento', 'type' => null],
|
||||
'entradas' => ['category' => null, 'product' => 'product', 'type' => null],
|
||||
'comidas' => ['category' => 'Comida', 'product' => 'event_date', 'type' => 'horario'],
|
||||
'comida' => ['category' => null, 'product' => 'event_date', 'type' => 'horario'],
|
||||
'merchandising' => ['category' => null, 'product' => 'product', 'type' => 'color'],
|
||||
];
|
||||
|
||||
/** @return array<string, mixed> */
|
||||
public function details(Ticket $ticket): array
|
||||
{
|
||||
$purchaseItem = $this->sourcePurchaseItem($ticket);
|
||||
|
||||
return [
|
||||
'source_purchase_id' => $ticket->source_purchase_id,
|
||||
'order_number' => $ticket->source_purchase_id,
|
||||
'product' => $purchaseItem?->item_nombre
|
||||
?? $ticket->sourceCatalogItem?->nombre
|
||||
?? $ticket->name,
|
||||
'amount' => $purchaseItem?->precio_unitario,
|
||||
'client' => $ticket->sourcePurchase?->nombre_apellido ?? $ticket->user?->nombre_apellido,
|
||||
'date' => $ticket->sourcePurchase?->created_at,
|
||||
'status' => $ticket->status,
|
||||
'scanned_by' => $ticket->scannerUser?->nombre_apellido,
|
||||
'variant_properties' => $this->variantProperties($ticket),
|
||||
];
|
||||
}
|
||||
|
||||
/** @param array<string, mixed>|null $details */
|
||||
public function values(Ticket $ticket, ?array $details = null): array
|
||||
{
|
||||
$details ??= $this->details($ticket);
|
||||
$presentation = $this->presentation($ticket, $details);
|
||||
|
||||
return [
|
||||
'order_number' => $details['order_number'],
|
||||
'category' => $presentation['category'],
|
||||
'product' => $presentation['product'],
|
||||
'type' => $presentation['type'],
|
||||
'amount' => $details['amount'] === null ? null : (float) $details['amount'],
|
||||
'client' => $details['client'] ?? 'Sin nombre',
|
||||
'ticket' => $ticket->ticket,
|
||||
'date' => $details['date'],
|
||||
'status' => $details['status'],
|
||||
'scanned_by' => $details['scanned_by'] ?? '-',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Collection<int, Ticket> $tickets
|
||||
* @return Collection<int, array<string, mixed>>
|
||||
*/
|
||||
public function rows(Collection $tickets): Collection
|
||||
{
|
||||
return $tickets->values()->map(fn (Ticket $ticket): array => $this->values($ticket));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Collection<int, array<string, mixed>> $rows
|
||||
* @param list<array<string, mixed>> $columns
|
||||
* @return Collection<int, array<string, string>>
|
||||
*/
|
||||
public function displayRows(Collection $rows, array $columns, string $timeZone): Collection
|
||||
{
|
||||
return $rows->map(fn (array $row): array => collect($columns)
|
||||
->mapWithKeys(fn (array $column): array => [
|
||||
$column['key'] => $this->displayValue(
|
||||
$row[$column['key']] ?? null,
|
||||
$column['type'],
|
||||
$timeZone,
|
||||
),
|
||||
])
|
||||
->all());
|
||||
}
|
||||
|
||||
public function displayValue(mixed $value, string $type, string $timeZone): string
|
||||
{
|
||||
if ($value === null || $value === '') {
|
||||
return '-';
|
||||
}
|
||||
|
||||
return match ($type) {
|
||||
'order_number' => '#'.$value,
|
||||
'currency' => '$'.number_format((float) $value, 2, ',', '.'),
|
||||
'date' => ($value instanceof CarbonInterface ? $value : Carbon::parse((string) $value))
|
||||
->copy()->timezone($timeZone)->format('d/m/Y H:i'),
|
||||
'status' => match ((string) $value) {
|
||||
Ticket::STATUS_USED => 'Usado',
|
||||
Ticket::STATUS_EXPIRED => 'Vencido',
|
||||
default => 'Activo',
|
||||
},
|
||||
default => (string) $value,
|
||||
};
|
||||
}
|
||||
|
||||
/** @param array<string, mixed> $details */
|
||||
private function presentation(Ticket $ticket, array $details): array
|
||||
{
|
||||
$sourceCategory = trim((string) ($ticket->sourceCatalogItem?->category?->nombre ?? '')) ?: '-';
|
||||
|
||||
if ($ticket->tenant_code !== self::FIESTA_FUTBOL_INFANTIL) {
|
||||
return [
|
||||
'category' => $sourceCategory,
|
||||
'product' => (string) ($details['product'] ?: $ticket->name ?: '-'),
|
||||
'type' => $this->allPropertyLabels($details) ?: '-',
|
||||
];
|
||||
}
|
||||
|
||||
$configuration = self::CATEGORY_PRESENTATIONS[mb_strtolower($sourceCategory)] ?? null;
|
||||
if ($configuration === null) {
|
||||
return [
|
||||
'category' => $sourceCategory,
|
||||
'product' => (string) ($details['product'] ?: $ticket->name ?: '-'),
|
||||
'type' => $this->allPropertyLabels($details) ?: '-',
|
||||
];
|
||||
}
|
||||
|
||||
return [
|
||||
'category' => $configuration['category'] ?? $sourceCategory,
|
||||
'product' => $configuration['product'] === 'product'
|
||||
? (string) ($details['product'] ?: $ticket->name ?: '-')
|
||||
: ($this->propertyLabels($details, $configuration['product']) ?: '-'),
|
||||
'type' => $configuration['type'] === null
|
||||
? '-'
|
||||
: ($this->propertyLabels($details, $configuration['type']) ?: '-'),
|
||||
];
|
||||
}
|
||||
|
||||
/** @param array<string, mixed> $details */
|
||||
private function propertyLabels(array $details, string $code): string
|
||||
{
|
||||
$property = collect($details['variant_properties'] ?? [])->firstWhere('code', $code);
|
||||
$labels = collect($property['values'] ?? [])->pluck('label')->filter();
|
||||
|
||||
if ($code === 'event_date') {
|
||||
$labels = $labels->map(function (string $label): string {
|
||||
[$day, $month] = array_pad(explode('/', $label), 2, null);
|
||||
|
||||
return $day !== null && $month !== null ? "{$day}/{$month}" : $label;
|
||||
});
|
||||
}
|
||||
|
||||
return $labels->implode(', ');
|
||||
}
|
||||
|
||||
/** @param array<string, mixed> $details */
|
||||
private function allPropertyLabels(array $details): string
|
||||
{
|
||||
return collect($details['variant_properties'] ?? [])
|
||||
->flatMap(fn (array $property): array => $property['values'] ?? [])
|
||||
->pluck('label')
|
||||
->filter()
|
||||
->implode(', ');
|
||||
}
|
||||
|
||||
private function sourcePurchaseItem(Ticket $ticket): ?PurchaseItem
|
||||
{
|
||||
return $ticket->sourcePurchase?->items->first(function (PurchaseItem $item) use ($ticket): bool {
|
||||
if ($ticket->source_variant_id !== null) {
|
||||
return $item->source_variant_id === $ticket->source_variant_id;
|
||||
}
|
||||
|
||||
return $item->source_catalog_item_id === $ticket->source_catalog_item_id
|
||||
&& $item->source_variant_id === null;
|
||||
});
|
||||
}
|
||||
|
||||
/** @return list<array{code: string, label: string, values: list<array{value: string, label: string}>}> */
|
||||
private function variantProperties(Ticket $ticket): array
|
||||
{
|
||||
$variant = $ticket->sourceVariant;
|
||||
if ($variant === null) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$itemAttributes = $variant->definitions
|
||||
->map(fn ($definition) => $definition->itemAttribute)
|
||||
->filter()
|
||||
->merge($variant->catalogItem?->itemAttributes ?? collect())
|
||||
->unique('id')
|
||||
->values();
|
||||
|
||||
return $variant->selectionOptions($itemAttributes)
|
||||
->map(function (array $selection, string $attributeCode) use ($itemAttributes): array {
|
||||
$itemAttribute = $itemAttributes->first(
|
||||
fn (ItemAttribute $itemAttribute): bool => $itemAttribute->attribute?->codigo
|
||||
=== $attributeCode,
|
||||
);
|
||||
$values = array_is_list($selection) ? $selection : [$selection];
|
||||
|
||||
return [
|
||||
'code' => $attributeCode,
|
||||
'label' => $itemAttribute?->attribute?->nombre
|
||||
?? ($attributeCode === 'event_date' ? 'Fecha' : $attributeCode),
|
||||
'values' => array_values($values),
|
||||
];
|
||||
})
|
||||
->values()
|
||||
->all();
|
||||
}
|
||||
}
|
||||
|
|
@ -1,338 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Domains\Ticket\Services;
|
||||
|
||||
use App\Domains\Auth\Models\User;
|
||||
use App\Domains\Purchase\Models\Purchase;
|
||||
use App\Domains\Purchase\Models\PurchaseItem;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use App\Domains\Ticket\Models\Ticket;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Pagination\LengthAwarePaginator;
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
class AdminAppTicketService
|
||||
{
|
||||
private const RELATIONS = [
|
||||
...TicketValidityResolver::RELATIONS,
|
||||
...TicketPresentationResolver::RELATIONS,
|
||||
'user',
|
||||
'scannerUser',
|
||||
'sourceCatalogItem.category',
|
||||
'sourcePurchase.items',
|
||||
];
|
||||
|
||||
public function __construct(
|
||||
private readonly AdminAppTicketColumnService $columnService,
|
||||
private readonly AdminAppTicketRowService $rowService,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @param array{q?: string|null, category?: string|null, product?: string|null, type?: string|null, date?: string|null, status?: string|null, page?: int, per_page?: int, sort_by?: string|null, sort_direction?: string|null} $filters
|
||||
*/
|
||||
public function search(Tenant $tenant, array $filters = []): AdminAppTicketResult
|
||||
{
|
||||
$query = $this->baseQuery($tenant, $filters);
|
||||
$countQuery = clone $query;
|
||||
|
||||
$databaseSorted = $this->applyDatabaseSort($query, $tenant, $filters);
|
||||
|
||||
if (($filters['sort_by'] ?? null) && ! $databaseSorted) {
|
||||
$matchingTickets = (clone $query)
|
||||
->with(self::RELATIONS)
|
||||
->get();
|
||||
$matchingTickets = $this->sortTickets($matchingTickets, $tenant, $filters);
|
||||
$tickets = $this->paginate($matchingTickets, $filters);
|
||||
$scannedTickets = $matchingTickets->whereNotNull('used_at')->count();
|
||||
} else {
|
||||
$tickets = (clone $query)
|
||||
->with(self::RELATIONS)
|
||||
->when(! $databaseSorted, fn (Builder $query): Builder => $query->orderByDesc('id'))
|
||||
->paginateFromRequest()
|
||||
->withQueryString();
|
||||
$scannedTickets = $countQuery->whereNotNull('used_at')->count();
|
||||
}
|
||||
|
||||
return new AdminAppTicketResult(
|
||||
tickets: $tickets,
|
||||
scannedTickets: $scannedTickets,
|
||||
totalTickets: $tickets->total(),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array{q?: string|null, category?: string|null, product?: string|null, type?: string|null, date?: string|null, status?: string|null, sort_by?: string|null, sort_direction?: string|null} $filters
|
||||
* @return Collection<int, Ticket>
|
||||
*/
|
||||
public function ticketsForExport(Tenant $tenant, array $filters = []): Collection
|
||||
{
|
||||
$query = $this->baseQuery($tenant, $filters);
|
||||
$databaseSorted = $this->applyDatabaseSort($query, $tenant, $filters);
|
||||
$tickets = $query
|
||||
->with(self::RELATIONS)
|
||||
->when(! $databaseSorted, fn (Builder $query): Builder => $query->orderByDesc('id'))
|
||||
->get();
|
||||
|
||||
return $databaseSorted ? $tickets : $this->sortTickets($tickets, $tenant, $filters);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array{q?: string|null, category?: string|null, product?: string|null, type?: string|null, date?: string|null, status?: string|null, page?: int, per_page?: int} $filters
|
||||
* @return Builder<Ticket>
|
||||
*/
|
||||
private function baseQuery(Tenant $tenant, array $filters): Builder
|
||||
{
|
||||
$search = trim((string) ($filters['q'] ?? ''));
|
||||
|
||||
$query = Ticket::query()
|
||||
->where('tenant_code', $tenant->codigo)
|
||||
->when($search !== '', function (Builder $query) use ($search): void {
|
||||
$query->when(
|
||||
ctype_digit($search),
|
||||
fn (Builder $searchQuery): Builder => $searchQuery
|
||||
->where('tickets.id', (int) $search),
|
||||
fn (Builder $searchQuery): Builder => $searchQuery
|
||||
->where('ticket', 'like', "%{$search}%"),
|
||||
);
|
||||
})
|
||||
->when($filters['category'] ?? null, function (Builder $query, string $category): void {
|
||||
$query->whereHas('sourceCatalogItem.category', fn (Builder $categoryQuery): Builder => $categoryQuery
|
||||
->whereRaw('LOWER(nombre) = ?', [mb_strtolower(trim($category))]));
|
||||
})
|
||||
->when($filters['product'] ?? null, function (Builder $query, string $product) use ($filters): void {
|
||||
$this->applyProductFilter($query, (string) ($filters['category'] ?? ''), $product);
|
||||
})
|
||||
->when($filters['type'] ?? null, function (Builder $query, string $type) use ($filters): void {
|
||||
$this->applyTypeFilter($query, (string) ($filters['category'] ?? ''), $type);
|
||||
})
|
||||
->when($filters['date'] ?? null, fn (Builder $query, string $date): Builder => $query
|
||||
->whereHas('sourcePurchase', fn (Builder $purchaseQuery): Builder => $purchaseQuery
|
||||
->whereDate('created_at', $date)));
|
||||
|
||||
$this->applyStatusFilter($query, $filters['status'] ?? null);
|
||||
|
||||
return $query;
|
||||
}
|
||||
|
||||
/** @param Builder<Ticket> $query */
|
||||
private function applyProductFilter(Builder $query, string $category, string $product): void
|
||||
{
|
||||
$category = $this->normalizedCategory($category);
|
||||
|
||||
if (in_array($category, ['alojamientos', 'camping'], true)) {
|
||||
$this->whereVariantDefinition($query, 'tipo_alojamiento', $product);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (in_array($category, ['comidas', 'comida'], true)) {
|
||||
$query->whereHas('sourceVariant', function (Builder $variantQuery) use ($product): void {
|
||||
$variantQuery->where(function (Builder $dateQuery) use ($product): void {
|
||||
$dateQuery
|
||||
->where('event_date_id', $product)
|
||||
->orWhereHas('eventDates', fn (Builder $eventDateQuery): Builder => $eventDateQuery
|
||||
->whereKey($product));
|
||||
});
|
||||
});
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$query->whereHas('sourceCatalogItem', fn (Builder $itemQuery): Builder => $itemQuery
|
||||
->where('slug', $product));
|
||||
}
|
||||
|
||||
/** @param Builder<Ticket> $query */
|
||||
private function applyTypeFilter(Builder $query, string $category, string $type): void
|
||||
{
|
||||
$attribute = match ($this->normalizedCategory($category)) {
|
||||
'comidas', 'comida' => 'horario',
|
||||
'merchandising' => 'color',
|
||||
default => null,
|
||||
};
|
||||
|
||||
if ($attribute !== null) {
|
||||
$this->whereVariantDefinition($query, $attribute, $type);
|
||||
}
|
||||
}
|
||||
|
||||
/** @param Builder<Ticket> $query */
|
||||
private function whereVariantDefinition(Builder $query, string $attribute, string $value): void
|
||||
{
|
||||
$query->whereHas('sourceVariant.definitions', fn (Builder $definitionQuery): Builder => $definitionQuery
|
||||
->where('value', $value)
|
||||
->whereHas('itemAttribute.attribute', fn (Builder $attributeQuery): Builder => $attributeQuery
|
||||
->where('codigo', $attribute)));
|
||||
}
|
||||
|
||||
/** @param Builder<Ticket> $query */
|
||||
private function applyStatusFilter(Builder $query, ?string $status): void
|
||||
{
|
||||
if ($status === null || $status === '') {
|
||||
return;
|
||||
}
|
||||
|
||||
if ($status === Ticket::STATUS_USED) {
|
||||
$query->whereNotNull('used_at');
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$matchingIds = (clone $query)
|
||||
->whereNull('used_at')
|
||||
->with(TicketValidityResolver::RELATIONS)
|
||||
->get()
|
||||
->filter(fn (Ticket $ticket): bool => $ticket->status === $status)
|
||||
->pluck('id');
|
||||
|
||||
$query->whereIn('tickets.id', $matchingIds);
|
||||
}
|
||||
|
||||
private function normalizedCategory(string $category): string
|
||||
{
|
||||
return mb_strtolower(trim($category));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Builder<Ticket> $query
|
||||
* @param array{sort_by?: string|null, sort_direction?: string|null} $filters
|
||||
*/
|
||||
private function applyDatabaseSort(Builder $query, Tenant $tenant, array $filters): bool
|
||||
{
|
||||
$sortBy = (string) ($filters['sort_by'] ?? '');
|
||||
if ($sortBy === '') {
|
||||
return false;
|
||||
}
|
||||
|
||||
$direction = ($filters['sort_direction'] ?? 'asc') === 'desc' ? 'desc' : 'asc';
|
||||
|
||||
$sortExpression = match ($sortBy) {
|
||||
'order_number' => 'tickets.source_purchase_id',
|
||||
'ticket' => 'tickets.ticket',
|
||||
'date' => Purchase::query()
|
||||
->select('created_at')
|
||||
->whereColumn('compras.id', 'tickets.source_purchase_id'),
|
||||
'amount' => $this->purchaseItemSortQuery('precio_unitario'),
|
||||
'scanned_by' => User::query()
|
||||
->select('nombre_apellido')
|
||||
->whereColumn('users.id', 'tickets.scanner_user_id'),
|
||||
'product' => $tenant->codigo === 'fiesta_futbol_infantil'
|
||||
? null
|
||||
: $this->purchaseItemSortQuery('item_nombre'),
|
||||
default => null,
|
||||
};
|
||||
|
||||
if ($sortExpression === null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$query->orderBy($sortExpression, $direction)->orderByDesc('tickets.id');
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/** @return Builder<PurchaseItem> */
|
||||
private function purchaseItemSortQuery(string $column): Builder
|
||||
{
|
||||
return PurchaseItem::query()
|
||||
->select($column)
|
||||
->whereColumn('compra_items.compra_id', 'tickets.source_purchase_id')
|
||||
->where(function (Builder $query): void {
|
||||
$query
|
||||
->where(function (Builder $variantQuery): void {
|
||||
$variantQuery
|
||||
->whereNotNull('tickets.source_variant_id')
|
||||
->whereColumn('compra_items.source_variant_id', 'tickets.source_variant_id');
|
||||
})
|
||||
->orWhere(function (Builder $itemQuery): void {
|
||||
$itemQuery
|
||||
->whereNull('tickets.source_variant_id')
|
||||
->whereNull('compra_items.source_variant_id')
|
||||
->whereColumn('compra_items.source_catalog_item_id', 'tickets.source_catalog_item_id');
|
||||
});
|
||||
})
|
||||
->limit(1);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Collection<int, Ticket> $tickets
|
||||
* @param array{sort_by?: string|null, sort_direction?: string|null} $filters
|
||||
* @return Collection<int, Ticket>
|
||||
*/
|
||||
private function sortTickets(Collection $tickets, Tenant $tenant, array $filters): Collection
|
||||
{
|
||||
$sortBy = (string) ($filters['sort_by'] ?? '');
|
||||
if ($sortBy === '') {
|
||||
return $tickets;
|
||||
}
|
||||
|
||||
$column = collect($this->columnService->columns($tenant))
|
||||
->firstWhere('sort_param', $sortBy);
|
||||
if ($column === null) {
|
||||
return $tickets;
|
||||
}
|
||||
|
||||
$direction = ($filters['sort_direction'] ?? 'asc') === 'desc' ? -1 : 1;
|
||||
$values = $tickets->mapWithKeys(fn (Ticket $ticket): array => [
|
||||
$ticket->getKey() => $this->rowService->values($ticket)[$column['key']] ?? null,
|
||||
]);
|
||||
|
||||
return $tickets->sort(function (Ticket $left, Ticket $right) use ($column, $direction, $values): int {
|
||||
$leftValue = $values->get($left->getKey());
|
||||
$rightValue = $values->get($right->getKey());
|
||||
|
||||
if ($leftValue === null || $leftValue === '') {
|
||||
return $rightValue === null || $rightValue === '' ? $right->id <=> $left->id : 1;
|
||||
}
|
||||
if ($rightValue === null || $rightValue === '') {
|
||||
return -1;
|
||||
}
|
||||
|
||||
$comparison = $this->compareValues($leftValue, $rightValue, $column['type']);
|
||||
|
||||
return $comparison === 0
|
||||
? $right->id <=> $left->id
|
||||
: $comparison * $direction;
|
||||
})->values();
|
||||
}
|
||||
|
||||
private function compareValues(mixed $left, mixed $right, string $type): int
|
||||
{
|
||||
if (in_array($type, ['currency', 'order_number'], true)) {
|
||||
return (float) $left <=> (float) $right;
|
||||
}
|
||||
|
||||
if ($type === 'date') {
|
||||
$leftTimestamp = $left instanceof \DateTimeInterface ? $left->getTimestamp() : strtotime((string) $left);
|
||||
$rightTimestamp = $right instanceof \DateTimeInterface ? $right->getTimestamp() : strtotime((string) $right);
|
||||
|
||||
return $leftTimestamp <=> $rightTimestamp;
|
||||
}
|
||||
|
||||
if ($type === 'status') {
|
||||
$left = $this->rowService->displayValue($left, $type, 'UTC');
|
||||
$right = $this->rowService->displayValue($right, $type, 'UTC');
|
||||
}
|
||||
|
||||
return strnatcasecmp((string) $left, (string) $right);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Collection<int, Ticket> $tickets
|
||||
* @param array{page?: int, per_page?: int} $filters
|
||||
* @return LengthAwarePaginator<Ticket>
|
||||
*/
|
||||
private function paginate(Collection $tickets, array $filters): LengthAwarePaginator
|
||||
{
|
||||
$page = (int) ($filters['page'] ?? 1);
|
||||
$perPage = (int) ($filters['per_page'] ?? 15);
|
||||
|
||||
return (new LengthAwarePaginator(
|
||||
$tickets->forPage($page, $perPage)->values(),
|
||||
$tickets->count(),
|
||||
$perPage,
|
||||
$page,
|
||||
['path' => request()->url()],
|
||||
))->withQueryString();
|
||||
}
|
||||
}
|
||||
|
|
@ -30,12 +30,6 @@ Bajo `/tenants/{tenant:codigo}`, protegidos por `auth:sanctum`:
|
|||
- `GET /tickets`.
|
||||
- `POST /tickets/pdf`.
|
||||
|
||||
Bajo `/v1/adminapp/tenant`, protegido por `auth:sanctum`, `adminapp.tenant` y el menú
|
||||
`adminapp.tickets`:
|
||||
|
||||
- `GET /tickets`, paginado y con búsqueda opcional mediante `q`. La respuesta incluye
|
||||
`scanned_tickets` y `total_tickets` para el tenant autenticado.
|
||||
|
||||
`TicketPdfService` genera la descarga y `TicketResource`/`ValidityTimeResource` definen las respuestas.
|
||||
|
||||
## Dependencias y reglas
|
||||
|
|
|
|||
|
|
@ -1,18 +0,0 @@
|
|||
<?php
|
||||
|
||||
use App\Domains\Ticket\Controllers\AdminApp\TicketController;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
|
||||
Route::prefix('v1/adminapp/tenant')
|
||||
->middleware(['auth:sanctum', 'adminapp.tenant'])
|
||||
->group(function (): void {
|
||||
Route::get('tickets', [TicketController::class, 'index'])
|
||||
->middleware('tenant.menu:adminapp.tickets')
|
||||
->name('adminapp.tickets.index');
|
||||
Route::get('tickets/pdf', [TicketController::class, 'downloadPdf'])
|
||||
->middleware('tenant.menu:adminapp.tickets')
|
||||
->name('adminapp.tickets.pdf');
|
||||
Route::get('tickets/excel', [TicketController::class, 'downloadExcel'])
|
||||
->middleware('tenant.menu:adminapp.tickets')
|
||||
->name('adminapp.tickets.excel');
|
||||
});
|
||||
|
|
@ -11,4 +11,3 @@ Route::prefix('tenants/{tenant:codigo}')
|
|||
});
|
||||
|
||||
require __DIR__.'/scanner.php';
|
||||
require __DIR__.'/adminapp.php';
|
||||
|
|
|
|||
|
|
@ -2,15 +2,4 @@
|
|||
|
||||
return [
|
||||
'checkout_expiration_minutes' => (int) env('PURCHASE_CHECKOUT_EXPIRATION_MINUTES', 30),
|
||||
|
||||
'payment_expiration_minutes' => [
|
||||
'qr' => (int) env('PURCHASE_QR_EXPIRATION_MINUTES', 15),
|
||||
'telepagos' => (int) env('PURCHASE_TELEPAGOS_EXPIRATION_MINUTES', 30),
|
||||
'transfer' => (int) env('PURCHASE_TRANSFER_EXPIRATION_MINUTES', 1440),
|
||||
],
|
||||
|
||||
'transfer_candidate_amount_tolerance_percentage' => (float) env(
|
||||
'PURCHASE_TRANSFER_CANDIDATE_AMOUNT_TOLERANCE_PERCENTAGE',
|
||||
5,
|
||||
),
|
||||
];
|
||||
|
|
|
|||
|
|
@ -1,141 +0,0 @@
|
|||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
Schema::create('telepagos_payment_candidates', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->foreignId('telepagos_payment_id')
|
||||
->constrained('telepagos_payments')
|
||||
->cascadeOnDelete();
|
||||
$table->foreignId('compra_id')->constrained('compras')->cascadeOnDelete();
|
||||
$table->boolean('dni_matches');
|
||||
$table->boolean('amount_matches');
|
||||
$table->decimal('payment_amount', 10, 2);
|
||||
$table->decimal('purchase_amount', 10, 2);
|
||||
$table->decimal('amount_difference', 10, 2);
|
||||
$table->string('match_reason');
|
||||
$table->string('confidence');
|
||||
$table->timestamps();
|
||||
|
||||
$table->unique(
|
||||
['telepagos_payment_id', 'compra_id'],
|
||||
'telepagos_payment_candidate_unique',
|
||||
);
|
||||
});
|
||||
|
||||
$this->migrateExistingCandidates();
|
||||
|
||||
Schema::table('telepagos_payments', function (Blueprint $table) {
|
||||
$table->dropColumn('matched_purchase_ids');
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::table('telepagos_payments', function (Blueprint $table) {
|
||||
$table->json('matched_purchase_ids')->nullable()->after('compra_id');
|
||||
});
|
||||
|
||||
DB::table('telepagos_payments')
|
||||
->whereNull('compra_id')
|
||||
->orderBy('id')
|
||||
->each(function (object $payment): void {
|
||||
$candidateIds = DB::table('telepagos_payment_candidates')
|
||||
->where('telepagos_payment_id', $payment->id)
|
||||
->pluck('compra_id')
|
||||
->all();
|
||||
|
||||
if ($candidateIds !== []) {
|
||||
DB::table('telepagos_payments')
|
||||
->where('id', $payment->id)
|
||||
->update(['matched_purchase_ids' => json_encode($candidateIds)]);
|
||||
}
|
||||
});
|
||||
|
||||
Schema::dropIfExists('telepagos_payment_candidates');
|
||||
}
|
||||
|
||||
private function migrateExistingCandidates(): void
|
||||
{
|
||||
DB::table('telepagos_payments')
|
||||
->whereNull('compra_id')
|
||||
->whereNotNull('matched_purchase_ids')
|
||||
->orderBy('id')
|
||||
->each(function (object $payment): void {
|
||||
$candidateIds = json_decode((string) $payment->matched_purchase_ids, true);
|
||||
|
||||
if (! is_array($candidateIds)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$paymentAmount = number_format((float) $payment->amount, 2, '.', '');
|
||||
$payerDni = $payment->cuit_buyer
|
||||
? substr((string) $payment->cuit_buyer, 2, -1)
|
||||
: null;
|
||||
|
||||
foreach ($candidateIds as $candidateId) {
|
||||
$purchase = DB::table('compras')->find($candidateId);
|
||||
|
||||
if ($purchase === null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$purchaseAmount = number_format((float) $purchase->total, 2, '.', '');
|
||||
$dniMatches = $payerDni !== null && $purchase->transfer_payer_dni === $payerDni;
|
||||
$amountMatches = $purchaseAmount === $paymentAmount;
|
||||
|
||||
DB::table('telepagos_payment_candidates')->insertOrIgnore([
|
||||
'telepagos_payment_id' => $payment->id,
|
||||
'compra_id' => $purchase->id,
|
||||
'dni_matches' => $dniMatches,
|
||||
'amount_matches' => $amountMatches,
|
||||
'payment_amount' => $paymentAmount,
|
||||
'purchase_amount' => $purchaseAmount,
|
||||
'amount_difference' => number_format(
|
||||
abs((float) $purchaseAmount - (float) $paymentAmount),
|
||||
2,
|
||||
'.',
|
||||
'',
|
||||
),
|
||||
'match_reason' => $this->matchReason($dniMatches, $amountMatches),
|
||||
'confidence' => $this->confidence($dniMatches, $amountMatches),
|
||||
'created_at' => $payment->created_at,
|
||||
'updated_at' => $payment->updated_at,
|
||||
]);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private function matchReason(bool $dniMatches, bool $amountMatches): string
|
||||
{
|
||||
if ($dniMatches && $amountMatches) {
|
||||
return 'ambiguous_exact_match';
|
||||
}
|
||||
|
||||
if ($dniMatches) {
|
||||
return 'exact_dni_near_amount';
|
||||
}
|
||||
|
||||
if ($amountMatches) {
|
||||
return 'exact_amount_different_dni';
|
||||
}
|
||||
|
||||
return 'legacy_candidate';
|
||||
}
|
||||
|
||||
private function confidence(bool $dniMatches, bool $amountMatches): string
|
||||
{
|
||||
if ($dniMatches && $amountMatches) {
|
||||
return 'exact';
|
||||
}
|
||||
|
||||
return $dniMatches ? 'high' : 'medium';
|
||||
}
|
||||
};
|
||||
|
|
@ -1,61 +0,0 @@
|
|||
<?php
|
||||
|
||||
use App\Domains\Purchase\Services\DniDistanceService;
|
||||
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('telepagos_payment_candidates', function (Blueprint $table) {
|
||||
$table->unsignedTinyInteger('dni_distance')->nullable()->after('dni_matches');
|
||||
$table->string('payment_dni', 8)->nullable()->after('dni_distance');
|
||||
$table->string('purchase_dni', 8)->nullable()->after('payment_dni');
|
||||
});
|
||||
|
||||
$dniDistance = new DniDistanceService;
|
||||
|
||||
DB::table('telepagos_payment_candidates as candidate')
|
||||
->join('telepagos_payments as payment', 'payment.id', '=', 'candidate.telepagos_payment_id')
|
||||
->join('compras as purchase', 'purchase.id', '=', 'candidate.compra_id')
|
||||
->select([
|
||||
'candidate.id',
|
||||
'candidate.match_reason',
|
||||
'payment.cuit_buyer',
|
||||
'purchase.transfer_payer_dni',
|
||||
])
|
||||
->orderBy('candidate.id')
|
||||
->each(function (object $candidate) use ($dniDistance): void {
|
||||
if ($candidate->cuit_buyer === null || $candidate->transfer_payer_dni === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
$payerDni = substr((string) $candidate->cuit_buyer, 2, -1);
|
||||
$distance = $dniDistance->distance($payerDni, (string) $candidate->transfer_payer_dni);
|
||||
|
||||
if ($candidate->match_reason === 'exact_amount_different_dni' && $distance > 2) {
|
||||
DB::table('telepagos_payment_candidates')->where('id', $candidate->id)->delete();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
DB::table('telepagos_payment_candidates')
|
||||
->where('id', $candidate->id)
|
||||
->update([
|
||||
'dni_distance' => $distance,
|
||||
'payment_dni' => $payerDni,
|
||||
'purchase_dni' => $candidate->transfer_payer_dni,
|
||||
]);
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::table('telepagos_payment_candidates', function (Blueprint $table) {
|
||||
$table->dropColumn(['dni_distance', 'payment_dni', 'purchase_dni']);
|
||||
});
|
||||
}
|
||||
};
|
||||
|
|
@ -1,21 +0,0 @@
|
|||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
DB::table('telepagos_payment_candidates')
|
||||
->where('match_reason', 'exact_amount_different_dni')
|
||||
->update(['match_reason' => 'exact_amount_near_dni']);
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
DB::table('telepagos_payment_candidates')
|
||||
->where('match_reason', 'exact_amount_near_dni')
|
||||
->update(['match_reason' => 'exact_amount_different_dni']);
|
||||
}
|
||||
};
|
||||
|
|
@ -1,82 +0,0 @@
|
|||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
private const MENU_CODE = 'adminapp.tickets';
|
||||
|
||||
private const TENANT_CODE = 'fiesta_futbol_infantil';
|
||||
|
||||
public function up(): void
|
||||
{
|
||||
if (! DB::table('menues')->where('code', 'main.adminapp')->exists()) {
|
||||
// Reference data is added by seeders on fresh installations.
|
||||
return;
|
||||
}
|
||||
|
||||
$now = now();
|
||||
|
||||
DB::transaction(function () use ($now): void {
|
||||
DB::table('menues')->updateOrInsert(
|
||||
['code' => self::MENU_CODE],
|
||||
[
|
||||
'label' => 'Tickets',
|
||||
'parent_menu_code' => 'main.adminapp',
|
||||
'content_type' => 'dynamic',
|
||||
'static_content_schema' => null,
|
||||
'route' => '/admin/tickets',
|
||||
'created_at' => $now,
|
||||
'updated_at' => $now,
|
||||
],
|
||||
);
|
||||
|
||||
DB::table('tenants_menues')
|
||||
->where('menu_code', self::MENU_CODE)
|
||||
->where('tenant_code', '!=', self::TENANT_CODE)
|
||||
->delete();
|
||||
|
||||
if (DB::table('tenants')->where('codigo', self::TENANT_CODE)->exists()) {
|
||||
DB::table('tenants_menues')->updateOrInsert(
|
||||
[
|
||||
'tenant_code' => self::TENANT_CODE,
|
||||
'menu_code' => self::MENU_CODE,
|
||||
],
|
||||
[
|
||||
'static_content' => null,
|
||||
'created_at' => $now,
|
||||
'updated_at' => $now,
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
DB::table('roles')
|
||||
->whereIn('codigo', ['admin', 'adminapp'])
|
||||
->pluck('codigo')
|
||||
->each(function (string $roleCode): void {
|
||||
DB::table('roles_menues')->updateOrInsert([
|
||||
'rol_codigo' => $roleCode,
|
||||
'menu_codigo' => self::MENU_CODE,
|
||||
]);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
DB::transaction(function (): void {
|
||||
DB::table('tenants_menues')
|
||||
->where('menu_code', self::MENU_CODE)
|
||||
->delete();
|
||||
|
||||
DB::table('roles_menues')
|
||||
->where('menu_codigo', self::MENU_CODE)
|
||||
->delete();
|
||||
|
||||
DB::table('menues')
|
||||
->where('code', self::MENU_CODE)
|
||||
->delete();
|
||||
});
|
||||
}
|
||||
};
|
||||
|
|
@ -78,12 +78,6 @@ class MenuSeeder extends Seeder
|
|||
'parent_menu_code' => 'main.adminapp',
|
||||
'route' => '/admin/staff',
|
||||
],
|
||||
[
|
||||
'code' => 'adminapp.tickets',
|
||||
'label' => 'Tickets',
|
||||
'parent_menu_code' => 'main.adminapp',
|
||||
'route' => '/admin/tickets',
|
||||
],
|
||||
[
|
||||
'code' => 'adminapp.fiesta-futbol-infantil.entradas',
|
||||
'label' => 'Entradas',
|
||||
|
|
@ -276,7 +270,6 @@ class MenuSeeder extends Seeder
|
|||
'fiesta_futbol_infantil',
|
||||
];
|
||||
$fiestaCategoryMenuCodes = [
|
||||
'adminapp.tickets',
|
||||
'adminapp.fiesta-futbol-infantil.entradas',
|
||||
'adminapp.fiesta-futbol-infantil.alojamientos',
|
||||
'adminapp.fiesta-futbol-infantil.merchandising',
|
||||
|
|
|
|||
|
|
@ -18,8 +18,7 @@
|
|||
</include>
|
||||
</source>
|
||||
<php>
|
||||
<env name="APP_ENV" value="testing" force="true"/>
|
||||
<env name="DB_DATABASE" value="shopit_test" force="true"/>
|
||||
<env name="APP_ENV" value="testing"/>
|
||||
<env name="APP_MAINTENANCE_DRIVER" value="file"/>
|
||||
<env name="APP_CONFIG_CACHE" value="bootstrap/cache/phpunit-config.php"/>
|
||||
<env name="APP_EVENTS_CACHE" value="bootstrap/cache/phpunit-events.php"/>
|
||||
|
|
|
|||
|
|
@ -1,95 +0,0 @@
|
|||
{
|
||||
"info": {
|
||||
"_postman_id": "8faefdb8-734a-4262-a3b6-4d49e56ea901",
|
||||
"name": "Storage Test S3",
|
||||
"schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json"
|
||||
},
|
||||
"variable": [
|
||||
{
|
||||
"key": "base_url",
|
||||
"value": "http://127.0.0.1:8000"
|
||||
},
|
||||
{
|
||||
"key": "expires_in_minutes",
|
||||
"value": "10"
|
||||
},
|
||||
{
|
||||
"key": "path",
|
||||
"value": ""
|
||||
}
|
||||
],
|
||||
"item": [
|
||||
{
|
||||
"name": "Upload Test File",
|
||||
"request": {
|
||||
"method": "POST",
|
||||
"header": [],
|
||||
"body": {
|
||||
"mode": "formdata",
|
||||
"formdata": [
|
||||
{
|
||||
"key": "file",
|
||||
"type": "file",
|
||||
"src": []
|
||||
},
|
||||
{
|
||||
"key": "directory",
|
||||
"value": "testing/manual",
|
||||
"type": "text"
|
||||
},
|
||||
{
|
||||
"key": "expires_in_minutes",
|
||||
"value": "{{expires_in_minutes}}",
|
||||
"type": "text"
|
||||
}
|
||||
]
|
||||
},
|
||||
"url": {
|
||||
"raw": "{{base_url}}/api/storage-test/s3/upload",
|
||||
"host": [
|
||||
"{{base_url}}"
|
||||
],
|
||||
"path": [
|
||||
"api",
|
||||
"storage-test",
|
||||
"s3",
|
||||
"upload"
|
||||
]
|
||||
},
|
||||
"description": "Sube un archivo al disco s3 y devuelve el path junto con una temporary_url."
|
||||
},
|
||||
"response": []
|
||||
},
|
||||
{
|
||||
"name": "Generate Temporary URL",
|
||||
"request": {
|
||||
"method": "GET",
|
||||
"header": [],
|
||||
"url": {
|
||||
"raw": "{{base_url}}/api/storage-test/s3/temporary-url?path={{path}}&expires_in_minutes={{expires_in_minutes}}",
|
||||
"host": [
|
||||
"{{base_url}}"
|
||||
],
|
||||
"path": [
|
||||
"api",
|
||||
"storage-test",
|
||||
"s3",
|
||||
"temporary-url"
|
||||
],
|
||||
"query": [
|
||||
{
|
||||
"key": "path",
|
||||
"value": "{{path}}"
|
||||
},
|
||||
{
|
||||
"key": "expires_in_minutes",
|
||||
"value": "{{expires_in_minutes}}"
|
||||
}
|
||||
]
|
||||
},
|
||||
"description": "Genera una URL temporal para un path ya existente en S3."
|
||||
},
|
||||
"response": []
|
||||
}
|
||||
]
|
||||
}
|
||||
|
|
@ -67,18 +67,7 @@ function bodyFor(string $method, string $uri): ?array
|
|||
'POST api/password/reset-attempts' => ['tenant_codigo' => '{{tenant_code}}', 'email' => '{{user_email}}'],
|
||||
'POST api/password/reset-attempts/validate' => ['email' => '{{user_email}}', 'codigo' => '{{reset_code}}'],
|
||||
'POST api/password/reset' => ['email' => '{{user_email}}', 'codigo' => '{{reset_code}}', 'password' => '{{user_password}}', 'password_confirmation' => '{{user_password}}'],
|
||||
'POST api/clients' => ['code' => 'cliente-demo', 'name' => 'Cliente Demo'],
|
||||
'PUT api/clients/{client}' => ['code' => 'cliente-demo', 'name' => 'Cliente Demo Actualizado'],
|
||||
'PATCH api/clients/{client}' => ['name' => 'Cliente Demo Actualizado'],
|
||||
'POST api/integrations' => ['integration_code' => 'telepagos', 'name' => 'Telepagos', 'url' => 'https://api.example.com', 'integration_data_schema' => ['api_key' => ['required', 'string']], 'requires_client_configuration' => true],
|
||||
'PUT api/integrations/{integration}' => ['name' => 'Telepagos', 'url' => 'https://api.example.com', 'requires_client_configuration' => true],
|
||||
'PUT api/clients/{client}/integrations/{integration_code}' => ['integration_data' => ['api_key' => 'replace-me']],
|
||||
'POST api/menues' => ['code' => 'demo', 'label' => 'Demo', 'parent_menu_code' => null, 'content_type' => 'static', 'static_content_schema' => ['title' => ['required', 'string']], 'route' => '/demo'],
|
||||
'PUT api/menues/{menue}' => ['label' => 'Demo actualizado', 'route' => '/demo'],
|
||||
'PATCH api/menues/{menue}' => ['label' => 'Demo actualizado'],
|
||||
'POST api/{tenant_code}/menues/{menu_code}' => ['static_content' => ['title' => 'Contenido demo']],
|
||||
'POST api/webhooks/telepagos/{client}' => ['id' => 'payment-id-demo'],
|
||||
'POST api/{tenant_code}/mail-test/send' => ['to' => 'destinatario@example.com', 'subject' => 'Prueba ShopIt', 'message' => 'Correo de prueba enviado desde Postman.'],
|
||||
'POST api/tenants/{tenant:codigo}/cart/items' => ['catalog_item_id' => '{{catalog_item_id}}', 'variant_id' => '{{variant_id}}', 'cantidad' => 1],
|
||||
'PATCH api/tenants/{tenant:codigo}/cart/items/{cartItem}' => ['cantidad' => 2, 'variant_id' => '{{variant_id}}'],
|
||||
'POST api/tenants/{tenant:codigo}/catalog-items/{catalogItem}/variant-options' => ['selected_values' => ['color' => 'azul'], 'cart_item_id' => '{{cart_item_id}}'],
|
||||
|
|
@ -92,11 +81,8 @@ function bodyFor(string $method, string $uri): ?array
|
|||
'POST api/v1/adminapp/password/reset-attempts/validate' => ['email' => '{{admin_email}}', 'codigo' => '{{reset_code}}'],
|
||||
'POST api/v1/adminapp/password/reset' => ['email' => '{{admin_email}}', 'codigo' => '{{reset_code}}', 'password' => '{{admin_password}}', 'password_confirmation' => '{{admin_password}}'],
|
||||
'PUT api/v1/adminapp/tenant/event' => ['title' => 'Evento Demo', 'location' => 'Buenos Aires', 'dates' => [['date' => '2026-12-01', 'start_time' => '18:00', 'end_time' => '23:00']], 'social_media' => [['code' => 'instagram', 'url' => 'https://instagram.com/example', 'orden' => 0]]],
|
||||
'POST api/v1/adminapp/tenant/featured-groups' => ['category_name' => 'Destacados', 'is_featured' => true],
|
||||
'PUT api/v1/adminapp/tenant/featured-groups/{featuredGroup}' => ['category_name' => 'Destacados', 'is_featured' => true],
|
||||
'POST api/v1/adminapp/tenant/staff' => ['nombre_apellido' => 'Operador Demo', 'dni' => '30123456', 'email' => 'operador@example.com', 'category_ids' => [1]],
|
||||
'PUT api/v1/adminapp/tenant/staff/{staff}' => ['nombre_apellido' => 'Operador Demo', 'dni' => '30123456', 'email' => 'operador@example.com', 'category_ids' => [1]],
|
||||
'PATCH api/v1/adminapp/tenant/staff/{staff}' => ['nombre_apellido' => 'Operador Demo', 'dni' => '30123456', 'email' => 'operador@example.com', 'category_ids' => [1]],
|
||||
'PUT api/v1/adminapp/tenant/website-extras/{websiteExtraCode}' => ['enabled' => true, 'content' => ['title' => 'Contenido demo']],
|
||||
'PATCH api/v1/adminapp/tenant/website-extras/{websiteExtraCode}/toggle' => ['enabled' => true],
|
||||
'POST api/v1/adminapp/tenant/accommodations' => ['variants' => [['title' => 'Habitación doble', 'description' => 'Dos personas', 'stock' => 10, 'price' => 100000]]],
|
||||
|
|
@ -162,10 +148,6 @@ function bodyFor(string $method, string $uri): ?array
|
|||
]);
|
||||
}
|
||||
|
||||
if ($key === 'POST api/storage-test/s3/upload') {
|
||||
return formDataBody(['path' => 'postman/test-file.png', 'expires_in_minutes' => '60'], ['file']);
|
||||
}
|
||||
|
||||
if ($key === 'POST api/v1/adminapp/tenant/desfile/entries/image') {
|
||||
return formDataBody(['is_enabled' => '1'], ['image']);
|
||||
}
|
||||
|
|
@ -194,7 +176,6 @@ function queryFor(string $uri): array
|
|||
['key' => 'per_page', 'value' => '20'],
|
||||
],
|
||||
'api/v1/scanner/tickets' => [['key' => 'q', 'value' => '', 'disabled' => true], ['key' => 'page', 'value' => '1'], ['key' => 'per_page', 'value' => '20']],
|
||||
'api/storage-test/s3/temporary-url' => [['key' => 'path', 'value' => '{{s3_path}}'], ['key' => 'expires_in_minutes', 'value' => '60']],
|
||||
default => [],
|
||||
};
|
||||
}
|
||||
|
|
@ -213,14 +194,6 @@ function folderFor(string $uri, string $action): array
|
|||
return ['Scanner API', $domain];
|
||||
}
|
||||
|
||||
if (str_starts_with($uri, 'api/webhooks/')) {
|
||||
return ['Webhooks', $domain];
|
||||
}
|
||||
|
||||
if (in_array($domain, ['StorageTest', 'MailTest'], true)) {
|
||||
return ['Developer Utilities', $domain];
|
||||
}
|
||||
|
||||
if (in_array($domain, ['Client', 'Integration', 'Menu', 'Tenant'], true) && ! str_contains($uri, '{tenant:codigo}')) {
|
||||
return ['Platform Management', $domain];
|
||||
}
|
||||
|
|
@ -268,8 +241,7 @@ function pathFor(string $uri): string
|
|||
{
|
||||
$variables = [
|
||||
'tenant:codigo' => 'tenant_code', 'tenant' => 'tenant_id', 'client' => 'client_id',
|
||||
'integration_code' => 'integration_code', 'integration' => 'integration_id', 'menue' => 'menu_id',
|
||||
'menu_code' => 'menu_code', 'tenant_code' => 'tenant_code', 'catalogItem' => 'catalog_item_id',
|
||||
'integration_code' => 'integration_code', 'tenant_code' => 'tenant_code', 'catalogItem' => 'catalog_item_id',
|
||||
'featuredGroup' => 'featured_group_id', 'category' => 'category_id', 'cartItem' => 'cart_item_id',
|
||||
'compra' => 'purchase_id', 'item' => 'purchase_item_id', 'dominio' => 'tenant_domain',
|
||||
'sale' => 'sale_id', 'staff' => 'staff_id', 'websiteExtraCode' => 'website_extra_code',
|
||||
|
|
@ -420,14 +392,13 @@ $variables = [
|
|||
'admin_email' => 'admin@example.com', 'admin_password' => 'Password!123',
|
||||
'scanner_email' => 'scanner@example.com', 'scanner_password' => 'Password!123',
|
||||
'tenant_code' => 'demo', 'tenant_id' => '1', 'tenant_domain' => 'demo.test',
|
||||
'client_id' => '1', 'integration_id' => '1', 'integration_code' => 'telepagos',
|
||||
'menu_id' => '1', 'menu_code' => 'demo', 'catalog_item_id' => '1', 'variant_id' => '1',
|
||||
'client_id' => '1', 'integration_code' => 'telepagos',
|
||||
'catalog_item_id' => '1', 'variant_id' => '1',
|
||||
'category_id' => '1', 'featured_group_id' => '1', 'cart_id' => '1', 'cart_item_id' => '1',
|
||||
'purchase_id' => '1', 'purchase_item_id' => '1', 'sale_id' => '1', 'staff_id' => '1',
|
||||
'website_extra_code' => 'hero', 'accommodation_id' => '1', 'entry_id' => '1', 'food_id' => '1',
|
||||
'merchandise_id' => '1', 'ticket_uuid' => '00000000-0000-0000-0000-000000000000',
|
||||
'oauth_code' => '00000000-0000-0000-0000-000000000000', 'reset_code' => '1234',
|
||||
's3_path' => 'postman/test-file.png',
|
||||
];
|
||||
|
||||
$collection = [
|
||||
|
|
|
|||
|
|
@ -1,60 +0,0 @@
|
|||
<!doctype html>
|
||||
<html lang="es">
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
|
||||
<style>
|
||||
@page { margin: 28px 34px 58px; }
|
||||
body { color: #17211b; font-family: DejaVu Sans, sans-serif; font-size: 8px; margin: 0; }
|
||||
h1 { font-size: 21px; margin: 0 0 3px; }
|
||||
.subtitle { color: #66736b; margin: 0 0 15px; }
|
||||
.summary { background: #eef5f1; border-left: 4px solid #198754; margin-bottom: 14px; padding: 8px 11px; }
|
||||
.summary strong { font-size: 12px; }
|
||||
table { border-collapse: collapse; table-layout: fixed; width: 100%; }
|
||||
thead { display: table-header-group; }
|
||||
tr { page-break-inside: avoid; }
|
||||
th { background: #26382e; color: #fff; font-size: 7px; letter-spacing: .25px; padding: 6px 5px; text-align: left; text-transform: uppercase; }
|
||||
td { border-bottom: 1px solid #dfe7e2; overflow-wrap: break-word; padding: 6px 5px; vertical-align: top; }
|
||||
tbody tr:nth-child(even) { background: #f7f9f8; }
|
||||
.number { text-align: right; }
|
||||
.ticket-id { font-size: 6.8px; word-break: break-all; }
|
||||
.empty { color: #66736b; padding: 24px; text-align: center; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<h1>Listado de tickets</h1>
|
||||
<p class="subtitle">{{ $tenant->nombre }} · Generado el {{ $generatedAt->copy()->timezone($timeZone)->format('d/m/Y H:i') }}</p>
|
||||
|
||||
<div class="summary">
|
||||
Tickets incluidos: <strong>{{ $tickets->count() }}</strong>
|
||||
·
|
||||
Escaneados: <strong>{{ $tickets->where('status', 'Usado')->count() }}</strong>
|
||||
</div>
|
||||
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
@foreach ($columns as $column)
|
||||
<th
|
||||
style="width: {{ $column['width'] }}"
|
||||
@class(['number' => $column['type'] === 'currency'])
|
||||
>{{ $column['label'] }}</th>
|
||||
@endforeach
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@forelse ($tickets as $ticket)
|
||||
<tr>
|
||||
@foreach ($columns as $column)
|
||||
<td @class([
|
||||
'number' => $column['type'] === 'currency',
|
||||
'ticket-id' => $column['key'] === 'ticket',
|
||||
])>{{ $ticket[$column['key']] }}</td>
|
||||
@endforeach
|
||||
</tr>
|
||||
@empty
|
||||
<tr><td class="empty" colspan="{{ count($columns) }}">No hay tickets para los criterios seleccionados.</td></tr>
|
||||
@endforelse
|
||||
</tbody>
|
||||
</table>
|
||||
</body>
|
||||
</html>
|
||||
|
|
@ -3,15 +3,11 @@
|
|||
require __DIR__.'/../app/Domains/Auth/routes/api.php';
|
||||
require __DIR__.'/../app/Domains/Catalog/routes/api.php';
|
||||
require __DIR__.'/../app/Domains/Cart/routes/api.php';
|
||||
require __DIR__.'/../app/Domains/StorageTest/routes/api.php';
|
||||
require __DIR__.'/../app/Domains/MailTest/routes/api.php';
|
||||
require __DIR__.'/../app/Domains/Purchase/routes/api.php';
|
||||
require __DIR__.'/../app/Domains/Sale/routes/api.php';
|
||||
require __DIR__.'/../app/Domains/Bootstrap/routes/api.php';
|
||||
require __DIR__.'/../app/Domains/Tenant/routes/api.php';
|
||||
require __DIR__.'/../app/Domains/Client/routes/api.php';
|
||||
require __DIR__.'/../app/Domains/Integration/routes/api.php';
|
||||
require __DIR__.'/../app/Domains/Menu/routes/api.php';
|
||||
require __DIR__.'/../app/Domains/Ticket/routes/api.php';
|
||||
require __DIR__.'/../app/Domains/Event/routes/api.php';
|
||||
require __DIR__.'/../app/Domains/Forms/routes/api.php';
|
||||
|
|
|
|||
|
|
@ -199,7 +199,7 @@ class BundleCatalogItemTest extends TestCase
|
|||
'email' => 'bundle@example.com',
|
||||
]);
|
||||
$purchase->update(['payment_method' => 'transfer']);
|
||||
$checkoutService->confirmPurchase($checkoutService->completePurchase($purchase));
|
||||
$checkoutService->confirmPurchase($purchase);
|
||||
|
||||
$this->assertDatabaseCount('compra_items', 1);
|
||||
$this->assertDatabaseHas('compra_items', [
|
||||
|
|
|
|||
|
|
@ -1,266 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace Tests\Feature\Catalog;
|
||||
|
||||
use App\Domains\Auth\Models\User;
|
||||
use App\Domains\Authorization\Enums\RoleCode;
|
||||
use App\Domains\Catalog\Enums\FeaturedGroupSource;
|
||||
use App\Domains\Catalog\Enums\GroupLayout;
|
||||
use App\Domains\Catalog\Enums\ProductLayout;
|
||||
use App\Domains\Catalog\Models\Category;
|
||||
use App\Domains\Catalog\Models\FeaturedGroup;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use App\Domains\Tenant\Models\WebsiteType;
|
||||
use Database\Seeders\AuthorizationSeeder;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Laravel\Sanctum\Sanctum;
|
||||
use Tests\TestCase;
|
||||
|
||||
class OnTicketFeaturedGroupControllerTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
$this->seed(AuthorizationSeeder::class);
|
||||
WebsiteType::query()->create([
|
||||
'codigo' => 'onticket',
|
||||
'nombre' => 'OnTicket',
|
||||
]);
|
||||
WebsiteType::query()->create([
|
||||
'codigo' => 'shopit',
|
||||
'nombre' => 'Shopit',
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_authentication_is_required(): void
|
||||
{
|
||||
$this->getJson('/api/v1/adminapp/tenant/featured-groups')->assertUnauthorized();
|
||||
$this->postJson('/api/v1/adminapp/tenant/featured-groups', $this->payload())
|
||||
->assertUnauthorized();
|
||||
$this->putJson('/api/v1/adminapp/tenant/featured-groups/1', $this->payload())
|
||||
->assertUnauthorized();
|
||||
}
|
||||
|
||||
public function test_index_returns_only_category_groups_for_the_onticket_tenant(): void
|
||||
{
|
||||
$tenant = $this->createTenant('acme');
|
||||
$otherTenant = $this->createTenant('other');
|
||||
$first = $this->createCategoryGroup($tenant, 'Food', order: 2);
|
||||
$second = $this->createCategoryGroup($tenant, 'Tickets', order: 1);
|
||||
$this->createCategoryGroup($otherTenant, 'Other tenant');
|
||||
FeaturedGroup::query()->create([
|
||||
'tenant_code' => $tenant->codigo,
|
||||
'source_type' => FeaturedGroupSource::All,
|
||||
'product_layout' => ProductLayout::Row,
|
||||
'group_layout' => GroupLayout::Paginated,
|
||||
'group_name' => 'All products',
|
||||
'group_order' => 0,
|
||||
]);
|
||||
Sanctum::actingAs($this->createAdminAppUser($tenant));
|
||||
|
||||
$this->getJson('/api/v1/adminapp/tenant/featured-groups')
|
||||
->assertOk()
|
||||
->assertJsonCount(2, 'data')
|
||||
->assertJsonPath('data.0.id', $second->id)
|
||||
->assertJsonPath('data.0.category_name', 'Tickets')
|
||||
->assertJsonPath('data.1.id', $first->id)
|
||||
->assertJsonMissing(['category_name' => 'Other tenant'])
|
||||
->assertJsonMissing(['group_name' => 'All products']);
|
||||
}
|
||||
|
||||
public function test_store_creates_a_category_and_a_featured_horizontal_group(): void
|
||||
{
|
||||
$tenant = $this->createTenant('acme');
|
||||
Sanctum::actingAs($this->createAdminAppUser($tenant));
|
||||
|
||||
$response = $this->postJson('/api/v1/adminapp/tenant/featured-groups', [
|
||||
'category_name' => 'Food',
|
||||
'is_featured' => true,
|
||||
])
|
||||
->assertCreated()
|
||||
->assertJsonPath('data.code', 'food')
|
||||
->assertJsonPath('data.category_name', 'Food')
|
||||
->assertJsonPath('data.group_name', 'Food')
|
||||
->assertJsonPath('data.is_featured', true)
|
||||
->assertJsonPath('data.type', 'category')
|
||||
->assertJsonPath('data.product_layout', 'row')
|
||||
->assertJsonPath('data.group_layout', 'paginated');
|
||||
|
||||
$categoryId = $response->json('data.category_id');
|
||||
$this->assertDatabaseHas('categorias', [
|
||||
'id' => $categoryId,
|
||||
'tenant_code' => $tenant->codigo,
|
||||
'nombre' => 'Food',
|
||||
]);
|
||||
$this->assertDatabaseHas('featured_groups', [
|
||||
'tenant_code' => $tenant->codigo,
|
||||
'code' => 'food',
|
||||
'source_type' => 'category',
|
||||
'category_id' => $categoryId,
|
||||
'product_layout' => 'row',
|
||||
'group_layout' => 'paginated',
|
||||
'group_name' => 'Food',
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_store_uses_column_with_cart_when_the_category_is_not_featured(): void
|
||||
{
|
||||
$tenant = $this->createTenant('acme');
|
||||
Sanctum::actingAs($this->createAdminAppUser($tenant));
|
||||
|
||||
$this->postJson('/api/v1/adminapp/tenant/featured-groups', [
|
||||
'category_name' => 'Parking',
|
||||
'is_featured' => false,
|
||||
])
|
||||
->assertCreated()
|
||||
->assertJsonPath('data.is_featured', false)
|
||||
->assertJsonPath('data.product_layout', 'column_with_cart')
|
||||
->assertJsonPath('data.group_layout', 'paginated');
|
||||
}
|
||||
|
||||
public function test_update_changes_the_category_and_group_together(): void
|
||||
{
|
||||
$tenant = $this->createTenant('acme');
|
||||
$group = $this->createCategoryGroup($tenant, 'Old name', ProductLayout::ColumnWithCart);
|
||||
Sanctum::actingAs($this->createAdminAppUser($tenant));
|
||||
|
||||
$this->putJson("/api/v1/adminapp/tenant/featured-groups/{$group->id}", [
|
||||
'category_name' => 'New name',
|
||||
'is_featured' => true,
|
||||
])
|
||||
->assertOk()
|
||||
->assertJsonPath('data.code', 'old-name')
|
||||
->assertJsonPath('data.category_name', 'New name')
|
||||
->assertJsonPath('data.group_name', 'New name')
|
||||
->assertJsonPath('data.is_featured', true)
|
||||
->assertJsonPath('data.product_layout', 'row')
|
||||
->assertJsonPath('data.group_layout', 'paginated');
|
||||
|
||||
$this->assertDatabaseHas('categorias', [
|
||||
'id' => $group->category_id,
|
||||
'nombre' => 'New name',
|
||||
]);
|
||||
$this->assertDatabaseHas('featured_groups', [
|
||||
'id' => $group->id,
|
||||
'code' => 'old-name',
|
||||
'group_name' => 'New name',
|
||||
'product_layout' => 'row',
|
||||
'group_layout' => 'paginated',
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_update_rejects_groups_from_another_tenant_or_source(): void
|
||||
{
|
||||
$tenant = $this->createTenant('acme');
|
||||
$otherTenant = $this->createTenant('other');
|
||||
$otherGroup = $this->createCategoryGroup($otherTenant, 'Other');
|
||||
$allGroup = FeaturedGroup::query()->create([
|
||||
'tenant_code' => $tenant->codigo,
|
||||
'source_type' => FeaturedGroupSource::All,
|
||||
'product_layout' => ProductLayout::Row,
|
||||
'group_layout' => GroupLayout::Paginated,
|
||||
'group_name' => 'All products',
|
||||
'group_order' => 0,
|
||||
]);
|
||||
Sanctum::actingAs($this->createAdminAppUser($tenant));
|
||||
|
||||
$this->putJson(
|
||||
"/api/v1/adminapp/tenant/featured-groups/{$otherGroup->id}",
|
||||
$this->payload(),
|
||||
)->assertNotFound();
|
||||
$this->putJson(
|
||||
"/api/v1/adminapp/tenant/featured-groups/{$allGroup->id}",
|
||||
$this->payload(),
|
||||
)->assertNotFound();
|
||||
}
|
||||
|
||||
public function test_name_and_featured_flag_are_required(): void
|
||||
{
|
||||
$tenant = $this->createTenant('acme');
|
||||
Sanctum::actingAs($this->createAdminAppUser($tenant));
|
||||
|
||||
$this->postJson('/api/v1/adminapp/tenant/featured-groups', [
|
||||
'category_name' => '',
|
||||
'is_featured' => 'yes',
|
||||
])
|
||||
->assertUnprocessable()
|
||||
->assertJsonValidationErrors(['category_name', 'is_featured']);
|
||||
|
||||
$this->assertDatabaseCount('categorias', 0);
|
||||
$this->assertDatabaseCount('featured_groups', 0);
|
||||
}
|
||||
|
||||
public function test_the_controller_is_not_available_for_non_onticket_tenants(): void
|
||||
{
|
||||
$tenant = $this->createTenant('store', 'shopit');
|
||||
Sanctum::actingAs($this->createAdminAppUser($tenant));
|
||||
|
||||
$this->getJson('/api/v1/adminapp/tenant/featured-groups')->assertNotFound();
|
||||
$this->postJson('/api/v1/adminapp/tenant/featured-groups', $this->payload())
|
||||
->assertNotFound();
|
||||
}
|
||||
|
||||
public function test_a_customer_cannot_manage_onticket_featured_groups(): void
|
||||
{
|
||||
Sanctum::actingAs(User::factory()->create([
|
||||
'rol_codigo' => RoleCode::User->value,
|
||||
'tenant_codigo' => null,
|
||||
]));
|
||||
|
||||
$this->getJson('/api/v1/adminapp/tenant/featured-groups')->assertForbidden();
|
||||
$this->postJson('/api/v1/adminapp/tenant/featured-groups', $this->payload())
|
||||
->assertForbidden();
|
||||
}
|
||||
|
||||
/** @return array{category_name: string, is_featured: bool} */
|
||||
private function payload(): array
|
||||
{
|
||||
return [
|
||||
'category_name' => 'Food',
|
||||
'is_featured' => true,
|
||||
];
|
||||
}
|
||||
|
||||
private function createTenant(string $code, string $websiteType = 'onticket'): Tenant
|
||||
{
|
||||
return Tenant::query()->create([
|
||||
'codigo' => $code,
|
||||
'nombre' => ucfirst($code),
|
||||
'dominio' => "{$code}.test",
|
||||
'website_type_code' => $websiteType,
|
||||
]);
|
||||
}
|
||||
|
||||
private function createAdminAppUser(Tenant $tenant): User
|
||||
{
|
||||
return User::factory()->create([
|
||||
'rol_codigo' => RoleCode::AdminApp->value,
|
||||
'tenant_codigo' => $tenant->codigo,
|
||||
]);
|
||||
}
|
||||
|
||||
private function createCategoryGroup(
|
||||
Tenant $tenant,
|
||||
string $name,
|
||||
ProductLayout $productLayout = ProductLayout::Row,
|
||||
int $order = 0,
|
||||
): FeaturedGroup {
|
||||
$category = Category::query()->create([
|
||||
'tenant_code' => $tenant->codigo,
|
||||
'nombre' => $name,
|
||||
]);
|
||||
|
||||
return FeaturedGroup::query()->create([
|
||||
'tenant_code' => $tenant->codigo,
|
||||
'source_type' => FeaturedGroupSource::Category,
|
||||
'category_id' => $category->id,
|
||||
'product_layout' => $productLayout,
|
||||
'group_layout' => GroupLayout::Paginated,
|
||||
'group_name' => $name,
|
||||
'group_order' => $order,
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,309 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace Tests\Feature\Forms;
|
||||
|
||||
use App\Domains\Attachable\Enums\AttachmentType;
|
||||
use App\Domains\Attachable\Models\Attachment;
|
||||
use App\Domains\Auth\Models\User;
|
||||
use App\Domains\Authorization\Enums\RoleCode;
|
||||
use App\Domains\Catalog\Models\CatalogItem;
|
||||
use App\Domains\Catalog\Services\CatalogService;
|
||||
use App\Domains\Menu\Models\Menu;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use App\Domains\Ticket\Models\Ticket;
|
||||
use Database\Seeders\AttributeSeeder;
|
||||
use Database\Seeders\AuthorizationSeeder;
|
||||
use Database\Seeders\FiestaFutbolInfantilProductSeeder;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Str;
|
||||
use Laravel\Sanctum\Sanctum;
|
||||
use Tests\TestCase;
|
||||
|
||||
class AdminAppTicketFilterFormControllerTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
$this->seed(AuthorizationSeeder::class);
|
||||
}
|
||||
|
||||
public function test_authentication_is_required(): void
|
||||
{
|
||||
$this->getJson('/api/v1/adminapp/forms/tickets-filter')->assertUnauthorized();
|
||||
}
|
||||
|
||||
public function test_the_tenant_must_have_the_tickets_menu(): void
|
||||
{
|
||||
$tenant = $this->createTenant('tenant_without_tickets');
|
||||
Sanctum::actingAs($this->createAdminAppUser($tenant));
|
||||
|
||||
$this->getJson('/api/v1/adminapp/forms/tickets-filter')->assertNotFound();
|
||||
}
|
||||
|
||||
public function test_it_returns_the_common_ticket_filter_fields_for_other_tenants(): void
|
||||
{
|
||||
$tenant = $this->createTenant('another_tenant');
|
||||
$this->grantTicketsMenu($tenant);
|
||||
Sanctum::actingAs($this->createAdminAppUser($tenant));
|
||||
|
||||
$this->getJson('/api/v1/adminapp/forms/tickets-filter')
|
||||
->assertOk()
|
||||
->assertExactJson([
|
||||
'data' => [
|
||||
'code' => 'tickets_filter',
|
||||
'action' => '/api/v1/adminapp/tenant/tickets',
|
||||
'method' => 'GET',
|
||||
'columns' => $this->commonColumns(),
|
||||
'fields' => [
|
||||
[
|
||||
'name' => 'date',
|
||||
'query_param' => 'date',
|
||||
'label' => 'Fecha',
|
||||
'type' => 'date',
|
||||
'required' => false,
|
||||
'default' => null,
|
||||
],
|
||||
[
|
||||
'name' => 'status',
|
||||
'query_param' => 'status',
|
||||
'label' => 'Estado',
|
||||
'type' => 'select',
|
||||
'required' => false,
|
||||
'default' => null,
|
||||
'placeholder' => 'Estado',
|
||||
'options' => [
|
||||
['value' => 'active', 'label' => 'Activo'],
|
||||
['value' => 'used', 'label' => 'Usado'],
|
||||
['value' => 'expired', 'label' => 'Vencido'],
|
||||
],
|
||||
],
|
||||
],
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_it_returns_the_complete_nested_form_for_fiesta_futbol_infantil(): void
|
||||
{
|
||||
$tenant = $this->createFiestaFutbolInfantilTenant();
|
||||
$this->grantTicketsMenu($tenant);
|
||||
$admin = $this->createAdminAppUser($tenant);
|
||||
Sanctum::actingAs($admin);
|
||||
|
||||
$response = $this->getJson('/api/v1/adminapp/forms/tickets-filter')
|
||||
->assertOk()
|
||||
->assertJsonPath('data.fields.0.name', 'category')
|
||||
->assertJsonPath('data.fields.0.query_param', 'category')
|
||||
->assertJsonPath('data.fields.1.name', 'product')
|
||||
->assertJsonPath('data.fields.1.query_param', 'product')
|
||||
->assertJsonPath('data.fields.1.depends_on', 'category')
|
||||
->assertJsonPath('data.fields.2.name', 'type')
|
||||
->assertJsonPath('data.fields.2.query_param', 'type')
|
||||
->assertJsonPath('data.fields.2.depends_on', 'product')
|
||||
->assertJsonPath('data.fields.3.name', 'date')
|
||||
->assertJsonPath('data.fields.3.query_param', 'date')
|
||||
->assertJsonPath('data.fields.4.name', 'status')
|
||||
->assertJsonPath('data.fields.4.query_param', 'status')
|
||||
->assertJsonPath('data.columns.0.key', 'order_number')
|
||||
->assertJsonPath('data.columns.0.sort_param', 'order_number')
|
||||
->assertJsonPath('data.columns.1.key', 'category')
|
||||
->assertJsonPath('data.columns.2.key', 'product')
|
||||
->assertJsonPath('data.columns.2.sortable', false)
|
||||
->assertJsonPath('data.columns.3.key', 'type')
|
||||
->assertJsonPath('data.columns.3.sortable', false);
|
||||
|
||||
$categories = collect($response->json('data.fields.0.options'));
|
||||
$this->assertSame(
|
||||
['Entradas', 'Camping', 'Comida', 'Merchandising'],
|
||||
$categories->pluck('label')->all(),
|
||||
);
|
||||
|
||||
$entries = $categories->firstWhere('value', 'entradas');
|
||||
$this->assertSame('Abono', $entries['children']['options'][0]['label']);
|
||||
$this->assertTrue($entries['children']['options'][0]['children']['disabled']);
|
||||
|
||||
$camping = $categories->firstWhere('value', 'alojamientos');
|
||||
$this->assertSame(
|
||||
['Carpa', 'Motorhome'],
|
||||
collect($camping['children']['options'])->pluck('label')->all(),
|
||||
);
|
||||
$this->assertTrue($camping['children']['options'][0]['children']['disabled']);
|
||||
|
||||
$merchandise = $categories->firstWhere('value', 'merchandising');
|
||||
$this->assertSame('Camiseta', $merchandise['children']['options'][0]['label']);
|
||||
$this->assertSame(
|
||||
['Verde', 'Blanco'],
|
||||
collect($merchandise['children']['options'][0]['children']['options'])->pluck('label')->all(),
|
||||
);
|
||||
}
|
||||
|
||||
public function test_a_food_schedule_is_only_returned_when_a_variant_exists_for_the_date(): void
|
||||
{
|
||||
$tenant = $this->createFiestaFutbolInfantilTenant();
|
||||
$this->grantTicketsMenu($tenant);
|
||||
Sanctum::actingAs($this->createAdminAppUser($tenant));
|
||||
|
||||
$date = $tenant->eventDates()->orderByDesc('date')->firstOrFail();
|
||||
$food = CatalogItem::query()
|
||||
->where('tenant_code', $tenant->codigo)
|
||||
->where('slug', 'comida')
|
||||
->with([
|
||||
'itemAttributes.attribute.options',
|
||||
'variants.definitions.itemAttribute.attribute.options',
|
||||
'variants.eventDates',
|
||||
'variants.eventDate',
|
||||
])
|
||||
->firstOrFail();
|
||||
|
||||
$food->variants
|
||||
->filter(fn ($variant): bool => $variant->selectedEventDates()->contains('id', $date->id)
|
||||
&& $variant->selectionValues()->get('horario') === 'Almuerzo')
|
||||
->each->delete();
|
||||
|
||||
$response = $this->getJson('/api/v1/adminapp/forms/tickets-filter')->assertOk();
|
||||
$foodCategory = collect($response->json('data.fields.0.options'))->firstWhere('value', 'comidas');
|
||||
$dateProduct = collect($foodCategory['children']['options'])
|
||||
->firstWhere('value', (string) $date->id);
|
||||
$schedules = collect($dateProduct['children']['options'])->pluck('value');
|
||||
|
||||
$this->assertNotContains('Almuerzo', $schedules);
|
||||
$this->assertContains('Desayuno', $schedules);
|
||||
$this->assertContains('Cena', $schedules);
|
||||
}
|
||||
|
||||
public function test_a_deleted_food_variant_remains_in_the_filter_when_a_ticket_references_it(): void
|
||||
{
|
||||
$tenant = $this->createFiestaFutbolInfantilTenant();
|
||||
$this->grantTicketsMenu($tenant);
|
||||
$admin = $this->createAdminAppUser($tenant);
|
||||
Sanctum::actingAs($admin);
|
||||
|
||||
$food = CatalogItem::query()
|
||||
->where('tenant_code', $tenant->codigo)
|
||||
->where('slug', 'comida')
|
||||
->with([
|
||||
'itemAttributes.attribute.options',
|
||||
'variants.definitions.itemAttribute.attribute.options',
|
||||
'variants.eventDates',
|
||||
'variants.eventDate',
|
||||
])
|
||||
->firstOrFail();
|
||||
$historicalVariant = $food->variants->first(function ($variant): bool {
|
||||
return $variant->selectedEventDates()->first()?->date->format('d/m') === '12/10'
|
||||
&& $variant->selectionValues()->get('horario') === 'Cena';
|
||||
});
|
||||
$this->assertNotNull($historicalVariant);
|
||||
|
||||
$ticket = Ticket::query()->create([
|
||||
'tenant_code' => $tenant->codigo,
|
||||
'ticket' => (string) Str::uuid(),
|
||||
'user_id' => $admin->id,
|
||||
'source_catalog_item_id' => $food->id,
|
||||
'source_variant_id' => $historicalVariant->id,
|
||||
]);
|
||||
|
||||
$catalogService = app(CatalogService::class);
|
||||
foreach ($food->variants as $variant) {
|
||||
$catalogService->deleteVariant($variant);
|
||||
}
|
||||
|
||||
$this->assertTrue(CatalogItem::withTrashed()->findOrFail($food->id)->trashed());
|
||||
|
||||
$response = $this->getJson('/api/v1/adminapp/forms/tickets-filter')->assertOk();
|
||||
$foodCategory = collect($response->json('data.fields.0.options'))->firstWhere('value', 'comidas');
|
||||
$products = collect($foodCategory['children']['options']);
|
||||
|
||||
$this->assertCount(1, $products);
|
||||
$this->assertSame('12/10', $products->first()['label']);
|
||||
$this->assertSame(
|
||||
['Cena'],
|
||||
collect($products->first()['children']['options'])->pluck('label')->all(),
|
||||
);
|
||||
|
||||
$this->getJson('/api/v1/adminapp/tenant/tickets?'.http_build_query([
|
||||
'category' => 'comidas',
|
||||
'product' => $products->first()['value'],
|
||||
'type' => 'Cena',
|
||||
]))
|
||||
->assertOk()
|
||||
->assertJsonCount(1, 'data')
|
||||
->assertJsonPath('data.0.id', $ticket->id)
|
||||
->assertJsonPath('data.0.values.category', 'Comida')
|
||||
->assertJsonPath('data.0.values.product', '12/10')
|
||||
->assertJsonPath('data.0.values.type', 'Cena');
|
||||
}
|
||||
|
||||
private function createFiestaFutbolInfantilTenant(): Tenant
|
||||
{
|
||||
$tenant = $this->createTenant('fiesta_futbol_infantil');
|
||||
$this->seed([AttributeSeeder::class, FiestaFutbolInfantilProductSeeder::class]);
|
||||
|
||||
return $tenant->refresh();
|
||||
}
|
||||
|
||||
/** @return list<array<string, mixed>> */
|
||||
private function commonColumns(): array
|
||||
{
|
||||
return [
|
||||
['key' => 'order_number', 'label' => 'N° de orden', 'type' => 'order_number', 'sortable' => true, 'sort_param' => 'order_number', 'width' => '11%'],
|
||||
['key' => 'product', 'label' => 'Producto', 'type' => 'text', 'sortable' => true, 'sort_param' => 'product', 'width' => '15%'],
|
||||
['key' => 'amount', 'label' => 'Importe', 'type' => 'currency', 'sortable' => true, 'sort_param' => 'amount', 'width' => '10%'],
|
||||
['key' => 'client', 'label' => 'Cliente', 'type' => 'text', 'sortable' => true, 'sort_param' => 'client', 'width' => '15%'],
|
||||
['key' => 'ticket', 'label' => 'ID', 'type' => 'text', 'sortable' => true, 'sort_param' => 'ticket', 'width' => '19%'],
|
||||
['key' => 'date', 'label' => 'Fecha', 'type' => 'date', 'sortable' => true, 'sort_param' => 'date', 'width' => '11%'],
|
||||
['key' => 'status', 'label' => 'Estado', 'type' => 'status', 'sortable' => true, 'sort_param' => 'status', 'width' => '8%'],
|
||||
['key' => 'scanned_by', 'label' => 'Escaneado por', 'type' => 'text', 'sortable' => true, 'sort_param' => 'scanned_by', 'width' => '11%'],
|
||||
];
|
||||
}
|
||||
|
||||
private function createTenant(string $code): Tenant
|
||||
{
|
||||
$headerLogo = $this->createAttachment("{$code}-header.png");
|
||||
$footerLogo = $this->createAttachment("{$code}-footer.png");
|
||||
|
||||
return Tenant::query()->create([
|
||||
'codigo' => $code,
|
||||
'nombre' => ucfirst($code),
|
||||
'dominio' => "{$code}.test",
|
||||
'primary_color' => '#111111',
|
||||
'secondary_color' => '#222222',
|
||||
'danger_color' => '#333333',
|
||||
'success_color' => '#444444',
|
||||
'header_bg_color' => '#ffffff',
|
||||
'footer_bg_color' => '#ffffff',
|
||||
'header_logo_id' => $headerLogo->id,
|
||||
'footer_logo_id' => $footerLogo->id,
|
||||
]);
|
||||
}
|
||||
|
||||
private function createAttachment(string $filename): Attachment
|
||||
{
|
||||
return Attachment::query()->create([
|
||||
'path' => "tests/{$filename}",
|
||||
'filename' => $filename,
|
||||
'type' => AttachmentType::Image,
|
||||
'mime_type' => 'image/png',
|
||||
]);
|
||||
}
|
||||
|
||||
private function createAdminAppUser(Tenant $tenant): User
|
||||
{
|
||||
return User::factory()->create([
|
||||
'rol_codigo' => RoleCode::AdminApp->value,
|
||||
'tenant_codigo' => $tenant->codigo,
|
||||
]);
|
||||
}
|
||||
|
||||
private function grantTicketsMenu(Tenant $tenant): void
|
||||
{
|
||||
$menu = Menu::query()->create([
|
||||
'code' => 'adminapp.tickets',
|
||||
'label' => 'Tickets',
|
||||
'route' => '/admin/tickets',
|
||||
]);
|
||||
|
||||
$tenant->menues()->attach($menu->code);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,155 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace Tests\Feature\Forms;
|
||||
|
||||
use App\Domains\Attachable\Enums\AttachmentType;
|
||||
use App\Domains\Attachable\Models\Attachment;
|
||||
use App\Domains\Auth\Models\User;
|
||||
use App\Domains\Authorization\Enums\RoleCode;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use Database\Seeders\AttributeSeeder;
|
||||
use Database\Seeders\AuthorizationSeeder;
|
||||
use Database\Seeders\FiestaFutbolInfantilProductSeeder;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Laravel\Sanctum\Sanctum;
|
||||
use Tests\TestCase;
|
||||
|
||||
class AdminAppTicketFormControllerTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
$this->seed(AuthorizationSeeder::class);
|
||||
}
|
||||
|
||||
public function test_authentication_is_required(): void
|
||||
{
|
||||
$this->getJson('/api/v1/adminapp/forms/fiesta-futbol-infantil/ticket')
|
||||
->assertUnauthorized();
|
||||
}
|
||||
|
||||
public function test_it_returns_nested_ticket_options_using_the_frontend_presentation_mapping(): void
|
||||
{
|
||||
$headerLogo = $this->createAttachment('header.png');
|
||||
$footerLogo = $this->createAttachment('footer.png');
|
||||
$tenant = Tenant::query()->create([
|
||||
'codigo' => 'fiesta_futbol_infantil',
|
||||
'nombre' => 'Fiesta Fútbol Infantil',
|
||||
'dominio' => 'fiesta-futbol-infantil.test',
|
||||
'primary_color' => '#00973F',
|
||||
'secondary_color' => '#A0A0A0',
|
||||
'danger_color' => '#FF8888',
|
||||
'success_color' => '#198754',
|
||||
'header_bg_color' => '#ffffff',
|
||||
'footer_bg_color' => '#015327',
|
||||
'header_logo_id' => $headerLogo->id,
|
||||
'footer_logo_id' => $footerLogo->id,
|
||||
]);
|
||||
$this->seed([AttributeSeeder::class, FiestaFutbolInfantilProductSeeder::class]);
|
||||
|
||||
Sanctum::actingAs(User::factory()->create([
|
||||
'rol_codigo' => RoleCode::AdminApp->value,
|
||||
'tenant_codigo' => $tenant->codigo,
|
||||
]));
|
||||
|
||||
$response = $this->getJson('/api/v1/adminapp/forms/fiesta-futbol-infantil/ticket')
|
||||
->assertOk()
|
||||
->assertExactJson([
|
||||
'data' => [
|
||||
'statuses' => [
|
||||
['value' => 'active', 'label' => 'Activo'],
|
||||
['value' => 'used', 'label' => 'Usado'],
|
||||
['value' => 'expired', 'label' => 'Vencido'],
|
||||
],
|
||||
'categories' => [
|
||||
[
|
||||
'value' => 'entradas',
|
||||
'label' => 'Entradas',
|
||||
'products' => [[
|
||||
'value' => 'abono',
|
||||
'label' => 'Abono',
|
||||
'types' => [],
|
||||
]],
|
||||
],
|
||||
[
|
||||
'value' => 'alojamientos',
|
||||
'label' => 'Camping',
|
||||
'products' => [
|
||||
['value' => 'Carpa', 'label' => 'Carpa', 'types' => []],
|
||||
['value' => 'Motorhome', 'label' => 'Motorhome', 'types' => []],
|
||||
],
|
||||
],
|
||||
[
|
||||
'value' => 'comidas',
|
||||
'label' => 'Comida',
|
||||
'products' => [
|
||||
[
|
||||
'value' => (string) $tenant->eventDates[0]->id,
|
||||
'label' => '09/10',
|
||||
'types' => [
|
||||
['value' => 'Desayuno', 'label' => 'Desayuno'],
|
||||
['value' => 'Almuerzo', 'label' => 'Almuerzo'],
|
||||
['value' => 'Cena', 'label' => 'Cena'],
|
||||
],
|
||||
],
|
||||
[
|
||||
'value' => (string) $tenant->eventDates[1]->id,
|
||||
'label' => '10/10',
|
||||
'types' => [
|
||||
['value' => 'Desayuno', 'label' => 'Desayuno'],
|
||||
['value' => 'Almuerzo', 'label' => 'Almuerzo'],
|
||||
['value' => 'Cena', 'label' => 'Cena'],
|
||||
],
|
||||
],
|
||||
[
|
||||
'value' => (string) $tenant->eventDates[2]->id,
|
||||
'label' => '11/10',
|
||||
'types' => [
|
||||
['value' => 'Desayuno', 'label' => 'Desayuno'],
|
||||
['value' => 'Almuerzo', 'label' => 'Almuerzo'],
|
||||
['value' => 'Cena', 'label' => 'Cena'],
|
||||
],
|
||||
],
|
||||
[
|
||||
'value' => (string) $tenant->eventDates[3]->id,
|
||||
'label' => '12/10',
|
||||
'types' => [
|
||||
['value' => 'Desayuno', 'label' => 'Desayuno'],
|
||||
['value' => 'Almuerzo', 'label' => 'Almuerzo'],
|
||||
['value' => 'Cena', 'label' => 'Cena'],
|
||||
],
|
||||
],
|
||||
],
|
||||
],
|
||||
[
|
||||
'value' => 'merchandising',
|
||||
'label' => 'Merchandising',
|
||||
'products' => [[
|
||||
'value' => 'camiseta',
|
||||
'label' => 'Camiseta',
|
||||
'types' => [
|
||||
['value' => 'Verde', 'label' => 'Verde'],
|
||||
['value' => 'Blanco', 'label' => 'Blanco'],
|
||||
],
|
||||
]],
|
||||
],
|
||||
],
|
||||
],
|
||||
]);
|
||||
|
||||
$response->assertJsonMissingPath('data.categories.0.products.0.category');
|
||||
}
|
||||
|
||||
private function createAttachment(string $filename): Attachment
|
||||
{
|
||||
return Attachment::query()->create([
|
||||
'path' => "tests/{$filename}",
|
||||
'filename' => $filename,
|
||||
'type' => AttachmentType::Image,
|
||||
'mime_type' => 'image/png',
|
||||
]);
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue