Compare commits

...

3 Commits

17 changed files with 341 additions and 18 deletions

View File

@@ -7,6 +7,14 @@ use App\Domains\Event\Models\EventDate;
class EffectiveEventDateResolver
{
public function resolve(EventDate $eventDate): ?EventDate
{
$date = $this->resolveLatest($eventDate);
return $date !== null && $date->suspended_at === null ? $date : null;
}
/** Sigue las reprogramaciones para presentación, incluso si el destino está suspendido. */
public function resolveLatest(EventDate $eventDate): ?EventDate
{
$current = $eventDate;
$visited = [];
@@ -23,7 +31,7 @@ class EffectiveEventDateResolver
$visited[$identity] = true;
if ($current->rescheduled_to_event_date_id === null) {
return $current->suspended_at === null ? $current : null;
return $current;
}
$current->loadMissing('rescheduledTo');

View File

@@ -6,6 +6,7 @@ use App\Domains\Attachable\Models\Attachment;
use App\Domains\Catalog\Models\CatalogItem;
use App\Domains\Catalog\Models\Variant;
use App\Domains\Ticket\Models\Ticket;
use App\Domains\Ticket\Models\TicketRefund;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
@@ -66,6 +67,12 @@ class PurchaseItem extends Model
return $this->hasMany(Ticket::class, 'source_purchase_item_id');
}
/** @return HasMany<TicketRefund, $this> */
public function ticketRefunds(): HasMany
{
return $this->hasMany(TicketRefund::class);
}
/** @return BelongsTo<Attachment, $this> */
public function imageAttachment(): BelongsTo
{

View File

@@ -67,7 +67,7 @@ class AdminAppSaleService
{
return $this->findForTenant($tenant, $saleId)
->tickets()
->with([...TicketValidityResolver::RELATIONS, ...TicketPresentationResolver::RELATIONS])
->with([...TicketValidityResolver::RELATIONS, ...TicketPresentationResolver::RELATIONS, 'refund'])
->orderBy('id')
->get();
}

View File

@@ -54,7 +54,12 @@ class TicketController extends Controller
$tenant = $request->user()->tenant()->firstOrFail();
return new AdminAppTicketResource(
$this->ticketService->refund($tenant, $ticket, $request->validated('refund_type'))
$this->ticketService->refund(
$tenant,
$ticket,
$request->validated('refund_type'),
$request->user(),
)
);
}

View File

@@ -18,6 +18,7 @@ use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Support\Collection;
use Illuminate\Validation\ValidationException;
@@ -219,6 +220,12 @@ class Ticket extends Model
return $this->belongsTo(PurchaseItem::class, 'source_purchase_item_id');
}
/** @return HasOne<TicketRefund, $this> */
public function refund(): HasOne
{
return $this->hasOne(TicketRefund::class);
}
/** @return BelongsTo<CatalogItem, $this> */
public function sourceCatalogItem(): BelongsTo
{
@@ -284,6 +291,14 @@ class Ticket extends Model
public function getStatusLabelAttribute(): string
{
if ($this->status === self::STATUS_REFUNDED && $this->relationLoaded('refund')) {
$refund = $this->getRelation('refund');
if ($refund instanceof TicketRefund) {
return $refund->typeLabel();
}
}
return self::statusLabel($this->status);
}

View File

@@ -0,0 +1,66 @@
<?php
namespace App\Domains\Ticket\Models;
use App\Domains\Auth\Models\User;
use App\Domains\Purchase\Models\PurchaseItem;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
#[Fillable([
'ticket_id',
'purchase_item_id',
'created_by_user_id',
'type',
'amount',
])]
class TicketRefund extends Model
{
public const TYPE_PARTIAL = 'partial';
public const TYPE_TOTAL = 'total';
protected function casts(): array
{
return [
'ticket_id' => 'integer',
'purchase_item_id' => 'integer',
'created_by_user_id' => 'integer',
'amount' => 'decimal:2',
];
}
/** @return list<string> */
public static function types(): array
{
return [self::TYPE_PARTIAL, self::TYPE_TOTAL];
}
public function typeLabel(): string
{
return match ($this->type) {
self::TYPE_PARTIAL => 'Reembolso parcial',
self::TYPE_TOTAL => 'Reembolso total',
default => 'Reembolsado',
};
}
/** @return BelongsTo<Ticket, $this> */
public function ticket(): BelongsTo
{
return $this->belongsTo(Ticket::class);
}
/** @return BelongsTo<PurchaseItem, $this> */
public function purchaseItem(): BelongsTo
{
return $this->belongsTo(PurchaseItem::class);
}
/** @return BelongsTo<User, $this> */
public function createdBy(): BelongsTo
{
return $this->belongsTo(User::class, 'created_by_user_id')->withTrashed();
}
}

View File

@@ -2,6 +2,7 @@
namespace App\Domains\Ticket\Requests;
use App\Domains\Ticket\Models\TicketRefund;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
@@ -16,7 +17,7 @@ class AdminAppTicketRefundRequest extends FormRequest
public function rules(): array
{
return [
'refund_type' => ['required', 'string', Rule::in(['partial', 'total'])],
'refund_type' => ['required', 'string', Rule::in(TicketRefund::types())],
];
}
}

View File

@@ -23,6 +23,13 @@ class AdminAppTicketResource extends TicketResource
'is_active' => $this->resource->is_active(),
'can_cancel' => $this->resource->can_cancel(),
'can_refund' => $this->resource->can_refund(),
'refund' => $this->resource->refund === null ? null : [
'type' => $this->resource->refund->type,
'type_label' => $this->resource->refund->typeLabel(),
'amount' => $this->resource->refund->amount,
'created_at' => $this->resource->refund->created_at,
'created_by' => $this->resource->refund->createdBy?->nombre_apellido,
],
'values' => $rowService->values($this->resource, $details),
];
}

View File

@@ -18,6 +18,12 @@ class TicketResource extends JsonResource
'ticket' => $this->ticket,
'status' => $this->status,
'status_label' => $this->status_label,
'refund' => $this->whenLoaded('refund', fn (): ?array => $this->refund === null ? null : [
'type' => $this->refund->type,
'type_label' => $this->refund->typeLabel(),
'amount' => $this->refund->amount,
'created_at' => $this->refund->created_at,
]),
'name' => $this->name,
'description' => $this->description,
'client' => $this->user?->nombre_apellido,

View File

@@ -41,7 +41,9 @@ class AdminAppTicketExcelService
$row = $index + 2;
foreach ($columns as $columnIndex => $column) {
$coordinate = Coordinate::stringFromColumnIndex($columnIndex + 1).$row;
$value = $ticket[$column['key']] ?? null;
$value = $column['type'] === 'status'
? ($ticket['status_label'] ?? $ticket[$column['key']] ?? null)
: ($ticket[$column['key']] ?? null);
if ($column['type'] === 'currency' && $value !== null) {
$sheet->setCellValue($coordinate, (float) $value);

View File

@@ -23,6 +23,7 @@ class AdminAppTicketRowService
public function details(Ticket $ticket): array
{
$purchaseItem = $ticket->sourcePurchaseItem;
$refund = $ticket->refund;
return [
'source_purchase_item_id' => $ticket->source_purchase_item_id,
@@ -31,7 +32,9 @@ class AdminAppTicketRowService
?? $ticket->sourceCatalogItem?->nombre
?? $ticket->name,
'amount' => $purchaseItem?->precio_unitario,
'refunded_amount' => $purchaseItem?->refunded_amount,
'refunded_amount' => $refund?->amount ?? $purchaseItem?->refunded_amount,
'refund_type' => $refund?->type,
'refund_type_label' => $refund?->typeLabel(),
'client' => $purchaseItem?->purchase?->nombre_apellido ?? $ticket->user?->nombre_apellido,
'status' => $ticket->status,
'scanned_by' => $ticket->scannerUser?->nombre_apellido,
@@ -57,6 +60,7 @@ class AdminAppTicketRowService
'client' => $details['client'] ?? 'Sin nombre',
'id' => $ticket->id,
'status' => $details['status'],
'status_label' => $ticket->status_label,
'scanned_by' => $details['scanned_by'] ?? '-',
];
}
@@ -80,7 +84,9 @@ class AdminAppTicketRowService
return $rows->map(fn (array $row): array => collect($columns)
->mapWithKeys(fn (array $column): array => [
$column['key'] => $this->displayValue(
$row[$column['key']] ?? null,
$column['type'] === 'status'
? ($row['status_label'] ?? $row[$column['key']] ?? null)
: ($row[$column['key']] ?? null),
$column['type'],
$timeZone,
),

View File

@@ -7,6 +7,7 @@ use App\Domains\Purchase\Models\PurchaseItem;
use App\Domains\Purchase\Services\PurchaseRefundSummaryService;
use App\Domains\Tenant\Models\Tenant;
use App\Domains\Ticket\Models\Ticket;
use App\Domains\Ticket\Models\TicketRefund;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Collection;
@@ -23,6 +24,7 @@ class AdminAppTicketService
'scannerUser',
'sourceCatalogItem.category',
'sourcePurchaseItem.purchase',
'refund.createdBy',
];
public function __construct(
@@ -162,11 +164,15 @@ class AdminAppTicketService
];
}
public function refund(Tenant $tenant, int $ticketId, string $refundType): Ticket
{
public function refund(
Tenant $tenant,
int $ticketId,
string $refundType,
?User $createdBy = null,
): Ticket {
$this->ensureRefundIsAllowed($tenant, $refundType);
return DB::transaction(function () use ($tenant, $ticketId, $refundType): Ticket {
return DB::transaction(function () use ($tenant, $ticketId, $refundType, $createdBy): Ticket {
$ticket = Ticket::query()
->where('tenant_code', $tenant->codigo)
->lockForUpdate()
@@ -206,6 +212,14 @@ class AdminAppTicketService
$ticket->markAsRefunded();
$ticket->save();
TicketRefund::query()->create([
'ticket_id' => $ticket->id,
'purchase_item_id' => $purchaseItem->id,
'created_by_user_id' => $createdBy?->id,
'type' => $refundType,
'amount' => number_format($refundAmount, 2, '.', ''),
]);
$purchaseItem->update([
'refunded_amount' => number_format($refundedAmount, 2, '.', ''),
]);
@@ -217,8 +231,8 @@ class AdminAppTicketService
private function ensureRefundIsAllowed(Tenant $tenant, string $refundType): void
{
$isAllowed = match ($refundType) {
'partial' => $tenant->allow_refund() && $tenant->allow_partial_refund(),
'total' => $tenant->allow_refund() && (bool) $tenant->allow_ticket_total_refund,
TicketRefund::TYPE_PARTIAL => $tenant->allow_refund() && $tenant->allow_partial_refund(),
TicketRefund::TYPE_TOTAL => $tenant->allow_refund() && (bool) $tenant->allow_ticket_total_refund,
};
if (! $isAllowed) {
@@ -233,8 +247,8 @@ class AdminAppTicketService
$ticketAmount = (float) $purchaseItem->precio_unitario;
return match ($refundType) {
'partial' => round($ticketAmount * (float) $tenant->ticket_partial_refund_percentage / 100, 2),
'total' => $ticketAmount,
TicketRefund::TYPE_PARTIAL => round($ticketAmount * (float) $tenant->ticket_partial_refund_percentage / 100, 2),
TicketRefund::TYPE_TOTAL => $ticketAmount,
};
}

View File

@@ -2,10 +2,14 @@
namespace App\Domains\Ticket\Services;
use App\Domains\Event\Models\EventDate;
use App\Domains\Event\Services\EffectiveEventDateResolver;
use App\Domains\Ticket\Models\Ticket;
class TicketPresentationResolver
{
public function __construct(private readonly EffectiveEventDateResolver $effectiveEventDateResolver) {}
/** Relaciones necesarias para calcular nombre y descripción sin consultas N+1. */
public const RELATIONS = [
'sourceCatalogItem',
@@ -30,9 +34,15 @@ class TicketPresentationResolver
}
$itemAttributes = $variant->catalogItem->itemAttributes;
$eventDateLabels = $variant->selectedEventDates()
->map(fn (EventDate $date): EventDate => $this->effectiveEventDateResolver->resolveLatest($date) ?? $date)
->unique(fn (EventDate $date): int => $date->getKey())
->map(fn (EventDate $date): string => $date->date->format('d/m/Y'))
->implode(', ');
$properties = $variant->selectionOptions($itemAttributes)
->map(function (array $option, string $attributeCode) use ($itemAttributes): ?string {
$labels = collect(array_is_list($option) ? $option : [$option])
->map(function (array $option, string $attributeCode) use ($itemAttributes, $eventDateLabels): ?string {
$labels = $attributeCode === 'event_date' ? $eventDateLabels : collect(array_is_list($option) ? $option : [$option])
->pluck('label')
->filter(fn ($label): bool => is_string($label) && $label !== '')
->implode(', ');

View File

@@ -0,0 +1,28 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('ticket_refunds', function (Blueprint $table): void {
$table->id();
$table->foreignId('ticket_id')->unique()->constrained('tickets')->cascadeOnDelete();
$table->foreignId('purchase_item_id')->constrained('compra_items')->restrictOnDelete();
$table->foreignId('created_by_user_id')->nullable()->constrained('users')->nullOnDelete();
$table->string('type', 16);
$table->decimal('amount', 10, 2);
$table->timestamps();
$table->index(['purchase_item_id', 'type']);
});
}
public function down(): void
{
Schema::dropIfExists('ticket_refunds');
}
};

View File

@@ -17,6 +17,7 @@ use App\Domains\Shared\Enums\FieldType;
use App\Domains\Tenant\Models\Tenant;
use App\Domains\Tenant\Models\WebsiteType;
use App\Domains\Ticket\Models\Ticket;
use App\Domains\Ticket\Models\TicketRefund;
use Barryvdh\DomPDF\ServiceProvider as DomPdfServiceProvider;
use Database\Seeders\AttributeSeeder;
use Database\Seeders\AuthorizationSeeder;
@@ -192,10 +193,22 @@ class AdminAppTicketControllerTest extends TestCase
->assertOk()
->assertJsonPath('data.id', $ticket->id)
->assertJsonPath('data.status', Ticket::STATUS_REFUNDED)
->assertJsonPath('data.refunded_amount', '100.00');
->assertJsonPath('data.status_label', 'Reembolso total')
->assertJsonPath('data.refunded_amount', '100.00')
->assertJsonPath('data.refund.type', TicketRefund::TYPE_TOTAL)
->assertJsonPath('data.refund.type_label', 'Reembolso total')
->assertJsonPath('data.refund.amount', '100.00')
->assertJsonPath('data.refund.created_by', $admin->nombre_apellido);
$this->assertNotNull($ticket->fresh()->refunded_at);
$this->assertSame('100.00', $purchaseItem->fresh()->refunded_amount);
$this->assertDatabaseHas('ticket_refunds', [
'ticket_id' => $ticket->id,
'purchase_item_id' => $purchaseItem->id,
'created_by_user_id' => $admin->id,
'type' => TicketRefund::TYPE_TOTAL,
'amount' => '100.00',
]);
}
public function test_it_partially_refunds_a_ticket_using_the_tenant_percentage(): void
@@ -216,9 +229,58 @@ class AdminAppTicketControllerTest extends TestCase
])
->assertOk()
->assertJsonPath('data.status', Ticket::STATUS_REFUNDED)
->assertJsonPath('data.refunded_amount', '25.50');
->assertJsonPath('data.status_label', 'Reembolso parcial')
->assertJsonPath('data.refunded_amount', '25.50')
->assertJsonPath('data.refund.type', TicketRefund::TYPE_PARTIAL)
->assertJsonPath('data.refund.amount', '25.50');
$this->assertSame('25.50', $purchaseItem->fresh()->refunded_amount);
$this->assertDatabaseHas('ticket_refunds', [
'ticket_id' => $ticket->id,
'type' => TicketRefund::TYPE_PARTIAL,
'amount' => '25.50',
]);
}
public function test_it_records_different_refund_types_for_tickets_from_the_same_purchase_item(): void
{
$tenant = $this->createTenant('ticket-mixed-refunds');
$tenant->update([
'allow_ticket_refund' => true,
'allow_ticket_total_refund' => true,
'allow_ticket_partial_refund' => true,
'ticket_partial_refund_percentage' => 25.00,
]);
$admin = $this->createAdminAppUser($tenant);
$this->grantTicketsMenu($tenant);
Sanctum::actingAs($admin);
[$partialTicket, $purchaseItem] = $this->createRefundableTicket($tenant, $admin, '100.00');
$purchaseItem->update(['cantidad' => 2, 'total' => '200.00']);
$purchaseItem->purchase->update(['total' => '200.00']);
$totalTicket = $this->createTicket($tenant, $admin, [
'source_purchase_item_id' => $purchaseItem->id,
'source_catalog_item_id' => $partialTicket->source_catalog_item_id,
]);
$this->postJson("/api/v1/adminapp/tenant/tickets/{$partialTicket->id}/refund", [
'refund_type' => TicketRefund::TYPE_PARTIAL,
])->assertOk()->assertJsonPath('data.status_label', 'Reembolso parcial');
$this->postJson("/api/v1/adminapp/tenant/tickets/{$totalTicket->id}/refund", [
'refund_type' => TicketRefund::TYPE_TOTAL,
])->assertOk()->assertJsonPath('data.status_label', 'Reembolso total');
$this->assertSame('125.00', $purchaseItem->fresh()->refunded_amount);
$this->assertDatabaseHas('ticket_refunds', [
'ticket_id' => $partialTicket->id,
'type' => TicketRefund::TYPE_PARTIAL,
'amount' => '25.00',
]);
$this->assertDatabaseHas('ticket_refunds', [
'ticket_id' => $totalTicket->id,
'type' => TicketRefund::TYPE_TOTAL,
'amount' => '100.00',
]);
}
public function test_it_does_not_refund_a_ticket_when_the_requested_refund_type_is_disabled(): void

View File

@@ -5,12 +5,17 @@ namespace Tests\Feature\Ticket;
use App\Domains\Attachable\Enums\AttachmentType;
use App\Domains\Attachable\Models\Attachment;
use App\Domains\Auth\Models\User;
use App\Domains\Catalog\Models\Attribute;
use App\Domains\Catalog\Models\CatalogItem;
use App\Domains\Catalog\Models\Inventory;
use App\Domains\Event\Events\EventDateRescheduled;
use App\Domains\Event\Events\EventDateSuspended;
use App\Domains\Event\Models\EventDate;
use App\Domains\Event\Services\EventService;
use App\Domains\Tenant\Models\Tenant;
use App\Domains\Ticket\Models\Ticket;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Str;
use Tests\TestCase;
@@ -18,6 +23,72 @@ class TicketControllerTest extends TestCase
{
use RefreshDatabase;
public function test_ticket_names_follow_reschedules_without_changing_variant_selections(): void
{
Event::fake([EventDateRescheduled::class, EventDateSuspended::class]);
$tenant = $this->createTenant('rescheduled');
$user = User::factory()->create();
$ticket = $this->createTicket($tenant, $user, 'COMIDA');
$item = $ticket->sourceCatalogItem;
$attribute = Attribute::query()->create([
'tenant_codigo' => $tenant->codigo,
'codigo' => 'service',
'nombre' => 'Servicio',
'type' => 'string',
]);
$itemAttribute = $item->itemAttributes()->create([
'attribute_id' => $attribute->id,
'ticket_label' => 'Servicio',
]);
$source = $tenant->eventDates()->create([
'date' => '2026-10-29',
'time_start' => '08:00:00',
'time_end' => '10:00:00',
]);
$variant = $item->variants()->create([
'event_date_id' => $source->id,
'inventory_id' => Inventory::query()->create()->id,
]);
$variant->definitions()->create([
'item_attribute_id' => $itemAttribute->id,
'value' => 'COMEDOR',
]);
$ticket->update(['source_variant_id' => $variant->id]);
foreach (['29/10/2026', '02/11/2026', '05/11/2026'] as $step => $expectedDate) {
if ($step > 0) {
$previous = $step === 1 ? $source : $tenant->eventDates()->whereDate('date', '2026-11-02')->firstOrFail();
app(EventService::class)->rescheduleDateForTenant($tenant, $previous, [
'date' => $step === 1 ? '2026-11-02' : '2026-11-05',
]);
}
$this->actingAs($user, 'sanctum')
->getJson("/api/tenants/{$tenant->codigo}/tickets")
->assertOk()
->assertJsonPath('data.0.name', "COMIDA ({$expectedDate}, Servicio COMEDOR)")
->assertJsonPath('data.0.ticket', $ticket->ticket);
}
$destination = $tenant->eventDates()->whereDate('date', '2026-11-05')->firstOrFail();
$variant->eventDates()->sync([$source->id, $destination->id]);
$this->assertSame('COMIDA (05/11/2026, Servicio COMEDOR)', $ticket->fresh()->name);
$this->assertSame('29/10/2026', $variant->fresh()->selectionOptions()->get('event_date')[0]['label']);
$this->assertSame($source->id, $variant->fresh()->event_date_id);
app(EventService::class)->suspendDateForTenant($tenant, $destination);
$this->actingAs($user, 'sanctum')
->getJson("/api/tenants/{$tenant->codigo}/tickets")
->assertOk()
->assertJsonPath('data.0.name', 'COMIDA (05/11/2026, Servicio COMEDOR)')
->assertJsonPath('data.0.status', 'disabled')
->assertJsonPath('data.0.is_valid', false)
->assertJsonPath('data.0.starts_at', null)
->assertJsonPath('data.0.expires_at', null)
->assertJsonPath('data.0.ticket', $ticket->ticket);
}
public function test_an_authenticated_user_can_list_their_tickets_for_the_tenant(): void
{
$tenant = $this->createTenant('current');

View File

@@ -98,6 +98,21 @@ class AdminAppTicketExportServiceTest extends TestCase
$this->assertStringContainsString('Vianda', $html);
}
public function test_it_uses_the_refund_type_label_when_displaying_a_refunded_status(): void
{
$row = $this->row();
$row['status'] = 'refunded';
$row['status_label'] = 'Reembolso parcial';
$displayRow = (new AdminAppTicketRowService)->displayRows(
collect([$row]),
$this->columnService()->columns($this->tenant()),
'America/La_Paz',
)->first();
$this->assertSame('Reembolso parcial', $displayRow['status']);
}
private function reportService(): AdminAppTicketReportService
{
$rowService = Mockery::mock(AdminAppTicketRowService::class)->makePartial();