4 Commits

16 changed files with 236 additions and 14 deletions

View File

@@ -8,6 +8,7 @@ use App\Domains\Purchase\Models\TelepagosQr;
use App\Domains\Purchase\Services\CheckoutService;
use App\Domains\Tenant\Models\Tenant;
use Exception;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
class TelepagosWebhookService
@@ -19,16 +20,13 @@ class TelepagosWebhookService
/**
* Handle the Telepagos webhook notification.
*
* @param string $tenantCodigo
* @param string $cashinId
* @return void
* @throws Exception
*/
public function handleWebhook(string $tenantCodigo, string $cashinId): void
{
$tenant = Tenant::where('codigo', $tenantCodigo)->firstOrFail();
$telepagosService = new TelepagosIntegrationService();
$telepagosService = new TelepagosIntegrationService;
$telepagosService->forTenant($tenant->codigo);
try {
@@ -48,26 +46,36 @@ class TelepagosWebhookService
if (! $cuit) {
Log::warning("Telepagos webhook: CUIT not found for Transferencia cashin {$cashinId}");
return;
}
$dni = substr($cuit, 2, -1);
$compra = Purchase::where('tenant_codigo', $tenantCodigo)
->where('transfer_payer_dni', $dni)
->whereIn('status', [Purchase::STATUS_CREATED, Purchase::STATUS_PENDING_PAYMENT])
->where('transfer_payer_dni', $dni)
->whereIn('status', [
Purchase::STATUS_CREATED,
Purchase::STATUS_PENDING_PAYMENT,
Purchase::STATUS_IN_REVIEW,
])
->where('payment_method', 'transfer')
->where('total', $amount)
->orderByRaw('CASE WHEN status = ? THEN 0 ELSE 1 END', [
Purchase::STATUS_IN_REVIEW,
])
->latest()
->first();
if (! $compra) {
Log::warning("Telepagos webhook: No matching purchase found for DNI {$dni} and amount {$amount} for cashin {$cashinId}");
return;
}
} elseif (in_array((int) $operationId, $qrOperationIds, true)) {
if (! $qrOrderId) {
Log::warning("Telepagos webhook: qr_order_id not found for QR cashin {$cashinId}");
return;
}
@@ -75,6 +83,7 @@ class TelepagosWebhookService
if (! $telepagosQr) {
Log::warning("Telepagos webhook: QR {$qrOrderId} not found in database for cashin {$cashinId}");
return;
}
@@ -82,11 +91,16 @@ class TelepagosWebhookService
if (! $compra) {
Log::warning("Telepagos webhook: Purchase not found for QR {$qrOrderId}");
return;
}
if ($compra->status !== Purchase::STATUS_PENDING_PAYMENT) {
if (! in_array($compra->status, [
Purchase::STATUS_PENDING_PAYMENT,
Purchase::STATUS_IN_REVIEW,
], true)) {
Log::warning("Telepagos webhook: Purchase {$compra->id} is not awaiting payment confirmation");
return;
}
@@ -94,10 +108,12 @@ class TelepagosWebhookService
if ($amount !== $totalAmount) {
Log::warning("Telepagos webhook: Amount mismatch. Cashin amount: {$amount}, Purchase amount: {$totalAmount}");
return;
}
} else {
Log::warning("Telepagos webhook: Unknown operation_id {$operationId} for cashin {$cashinId}");
return;
}
@@ -114,7 +130,7 @@ class TelepagosWebhookService
'link_id' => $details['data']['link_id'] ?? $details['link_id'] ?? null,
];
\Illuminate\Support\Facades\DB::transaction(function () use ($compra, $paymentData) {
DB::transaction(function () use ($compra, $paymentData) {
TelepagosPayment::create($paymentData);
$this->checkoutService->confirmPurchase($compra);
$compra->markAsPaid();
@@ -122,7 +138,7 @@ class TelepagosWebhookService
Log::info("Telepagos webhook: Successfully processed cashin {$cashinId} for purchase {$compra->id}");
} catch (Exception $e) {
Log::error("Telepagos webhook error: " . $e->getMessage());
Log::error('Telepagos webhook error: '.$e->getMessage());
throw $e;
}
}

View File

@@ -55,7 +55,7 @@ class PurchaseController extends Controller
{
$compra = $this->resolveScopedPurchase($tenant, $request->user()->id, $compra);
$compra->loadMissing('items');
$compra->loadMissing('items')->loadCount('tickets');
$compra->items->load('imageAttachment');
return PurchaseResource::make($compra);
@@ -223,6 +223,19 @@ class PurchaseController extends Controller
);
}
public function submitForReview(
Request $request,
Tenant $tenant,
Purchase $compra,
CheckoutService $checkoutService,
): PurchaseResource {
$compra = $this->resolveScopedPurchase($tenant, $request->user()->id, $compra);
return PurchaseResource::make(
$checkoutService->submitForReview($compra),
);
}
public function cancel(Request $request, Tenant $tenant, Purchase $compra, CheckoutService $checkoutService): PurchaseResource
{
$compra = $this->resolveScopedPurchase($tenant, $request->user()->id, $compra);

View File

@@ -6,6 +6,7 @@ use App\Domains\Auth\Models\User;
use App\Domains\Cart\Models\Cart;
use App\Domains\Purchase\Events\PurchasePaid;
use App\Domains\Tenant\Models\Tenant;
use App\Domains\Ticket\Models\Ticket;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
@@ -36,6 +37,8 @@ class Purchase extends Model
public const STATUS_PENDING_PAYMENT = 'pending_payment';
public const STATUS_IN_REVIEW = 'in_review';
public const STATUS_PAID = 'paid';
public const STATUS_CANCELLED = 'cancelled';
@@ -88,6 +91,14 @@ class Purchase extends Model
return $this->hasMany(PurchaseItem::class, 'compra_id');
}
/**
* @return HasMany<Ticket, $this>
*/
public function tickets(): HasMany
{
return $this->hasMany(Ticket::class, 'source_purchase_id');
}
/**
* @return HasOne<TelepagosQr, $this>
*/

View File

@@ -20,6 +20,9 @@ class PurchaseResource extends JsonResource
$items = $this->resource->relationLoaded('items')
? $this->resource->getRelation('items')
: collect();
$ticketsCount = array_key_exists('tickets_count', $this->resource->getAttributes())
? (int) $this->resource->getAttribute('tickets_count')
: null;
$subtotal = $items->isNotEmpty()
? $items->reduce(
@@ -51,6 +54,8 @@ class PurchaseResource extends JsonResource
'email' => $this->email,
'items_source' => $items->isNotEmpty() ? 'purchase' : null,
'items' => PurchaseItemResource::collection($items),
'tickets_count' => $this->when($ticketsCount !== null, $ticketsCount),
'has_generated_tickets' => $this->when($ticketsCount !== null, $ticketsCount > 0),
'subtotal' => $this->formatMoney($subtotal),
'total' => $this->formatMoney($total),
];

View File

@@ -70,6 +70,7 @@ class CheckoutService
if (in_array($purchase->status, [
Purchase::STATUS_PAID,
Purchase::STATUS_IN_REVIEW,
Purchase::STATUS_CANCELLED,
Purchase::STATUS_REJECTED,
Purchase::STATUS_EXPIRED,
@@ -86,6 +87,39 @@ class CheckoutService
});
}
public function submitForReview(Purchase $purchase): Purchase
{
return DB::transaction(function () use ($purchase): Purchase {
/** @var Purchase $purchase */
$purchase = Purchase::query()
->lockForUpdate()
->findOrFail($purchase->getKey());
if (in_array($purchase->status, [
Purchase::STATUS_IN_REVIEW,
Purchase::STATUS_PAID,
], true)) {
return $this->loadPurchase($purchase);
}
if (
$purchase->status !== Purchase::STATUS_PENDING_PAYMENT
|| ($purchase->expires_at !== null && $purchase->expires_at->isPast())
) {
throw ValidationException::withMessages([
'purchase' => __('api.purchase.not_available_for_review'),
]);
}
$purchase->update([
'status' => Purchase::STATUS_IN_REVIEW,
'expires_at' => null,
]);
return $this->loadPurchase($purchase);
});
}
/**
* @param array<string, string> $customerData
*/
@@ -98,7 +132,10 @@ class CheckoutService
->findOrFail($purchase->getKey());
if (
$purchase->status !== Purchase::STATUS_CREATED
! in_array($purchase->status, [
Purchase::STATUS_CREATED,
Purchase::STATUS_PENDING_PAYMENT,
], true)
|| ($purchase->expires_at !== null && $purchase->expires_at->isPast())
) {
throw ValidationException::withMessages([

View File

@@ -12,5 +12,6 @@ Route::prefix('tenants/{tenant:codigo}')->middleware('auth:sanctum')->group(func
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']);
});

View File

@@ -45,6 +45,7 @@ class GenerateTicketsForPaidPurchase
$user,
$purchaseItem->cantidad,
$purchaseItem->source_variant_id,
$purchase->getKey(),
);
array_push($ticketIds, ...$generatedTickets->pluck('id')->all());

View File

@@ -3,6 +3,7 @@
namespace App\Domains\Ticket\Models;
use App\Domains\Auth\Models\User;
use App\Domains\Purchase\Models\Purchase;
use App\Domains\Tenant\Models\Tenant;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
@@ -14,6 +15,7 @@ use Illuminate\Database\Eloquent\Relations\BelongsTo;
'ticket',
'name',
'description',
'source_purchase_id',
'source_catalog_item_id',
'source_variant_id',
'starts_at',
@@ -38,6 +40,7 @@ class Ticket extends Model
return [
'source_catalog_item_id' => 'integer',
'source_variant_id' => 'integer',
'source_purchase_id' => 'integer',
'starts_at' => 'datetime',
'expires_at' => 'datetime',
'used_at' => 'datetime',
@@ -57,6 +60,12 @@ class Ticket extends Model
return $this->belongsTo(User::class);
}
/** @return BelongsTo<Purchase, $this> */
public function sourcePurchase(): BelongsTo
{
return $this->belongsTo(Purchase::class, 'source_purchase_id');
}
public function isValid(): bool
{
$now = now();

View File

@@ -21,12 +21,13 @@ class TicketGeneratorService
User $user,
int $quantity = 1,
?int $sourceVariantId = null,
?int $sourcePurchaseId = null,
): Collection {
if ($quantity < 1) {
throw TicketGenerationException::invalidQuantity();
}
return DB::transaction(function () use ($catalogItem, $user, $quantity, $sourceVariantId): Collection {
return DB::transaction(function () use ($catalogItem, $user, $quantity, $sourceVariantId, $sourcePurchaseId): Collection {
$targets = $this->resolveTargets(
$catalogItem,
$quantity,
@@ -36,6 +37,7 @@ class TicketGeneratorService
return $targets->map(function (array $target) use (
$catalogItem,
$sourceVariantId,
$sourcePurchaseId,
$user,
): Ticket {
$item = $target['catalog_item'];
@@ -46,6 +48,7 @@ class TicketGeneratorService
'ticket' => (string) Str::uuid(),
'name' => $item->nombre,
'description' => (string) ($item->descripcion ?? ''),
'source_purchase_id' => $sourcePurchaseId,
'source_catalog_item_id' => $catalogItem->getKey(),
'source_variant_id' => $sourceVariantId,
'starts_at' => $selectedItem->getMinimumUseDate(),

View File

@@ -0,0 +1,27 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::table('tickets', function (Blueprint $table): void {
$table->foreignId('source_purchase_id')
->nullable()
->after('description')
->constrained('compras')
->cascadeOnUpdate()
->nullOnDelete();
});
}
public function down(): void
{
Schema::table('tickets', function (Blueprint $table): void {
$table->dropConstrainedForeignId('source_purchase_id');
});
}
};

View File

@@ -46,6 +46,7 @@ return [
'catalog_item_wrong_tenant' => 'One or more catalog items do not belong to the tenant.',
'inactive_cart' => 'The selected cart is no longer active.',
'not_available_for_payment' => 'The purchase is no longer available for payment.',
'not_available_for_review' => 'The purchase is no longer available for review.',
],
'ticket' => [
'not_available' => 'One or more tickets are not available.',

View File

@@ -46,6 +46,7 @@ return [
'catalog_item_wrong_tenant' => 'Uno o más productos no pertenecen al tenant.',
'inactive_cart' => 'El carrito seleccionado ya no está activo.',
'not_available_for_payment' => 'La compra ya no está disponible para el pago.',
'not_available_for_review' => "La compra ya no est\u{00E1} disponible para revisi\u{00F3}n.",
],
'ticket' => [
'not_available' => 'Uno o más tickets no están disponibles.',

View File

@@ -37,7 +37,7 @@ return [
'required_with' => 'El campo :attribute es obligatorio cuando :values está presente.',
'required_without' => 'El campo :attribute es obligatorio cuando :values no está presente.',
'string' => ':Attribute debe ser texto.',
'unique' => 'El valor de :attribute ya está en uso.',
'unique' => 'El :attribute ya está en uso.',
'url' => ':Attribute debe ser una URL válida.',
'uuid' => ':Attribute debe ser un UUID válido.',
'attributes' => [

View File

@@ -100,7 +100,7 @@ class TelepagosWebhookTest extends TestCase
]);
}
public function test_transfer_webhook_matches_pending_purchase_by_dni_and_total_amount(): void
public function test_transfer_webhook_matches_purchase_in_review_by_dni_and_total_amount(): void
{
$tenant = $this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
$this->configureTelepagosIntegration($tenant);
@@ -122,6 +122,8 @@ class TelepagosWebhookTest extends TestCase
'12345678'
);
$matchingPurchase->update(['status' => Purchase::STATUS_IN_REVIEW]);
$newerPurchase = $this->createPendingTransferPurchase(
$tenant,
$newerUser->id,

View File

@@ -304,6 +304,32 @@ class StorePurchaseTest extends TestCase
]);
}
public function test_it_updates_customer_data_for_a_pending_payment_purchase(): void
{
$this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
$user = User::factory()->create();
$variant = $this->createVariantForTenant('sonder', 10, '50.00');
$purchase = $this->createCheckoutPurchase($user, 'sonder', $variant, 1);
$purchase->update(['status' => Purchase::STATUS_PENDING_PAYMENT]);
$this->actingAs($user, 'sanctum')
->patchJson("/api/tenants/sonder/compras/{$purchase->id}/customer-data", [
'dni' => '987654321',
'telefono' => '+54 9 341 555-4321',
'nombre_apellido' => 'Juan Perez',
'email' => 'juan.perez@example.com',
])
->assertOk()
->assertJsonPath('data.status', Purchase::STATUS_PENDING_PAYMENT)
->assertJsonPath('data.dni', '987654321');
$this->assertDatabaseHas('compras', [
'id' => $purchase->id,
'status' => Purchase::STATUS_PENDING_PAYMENT,
'dni' => '987654321',
]);
}
public function test_it_updates_a_created_purchase_item_quantity_and_its_stock_reservation(): void
{
$this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
@@ -448,6 +474,62 @@ class StorePurchaseTest extends TestCase
]);
}
public function test_it_submits_a_pending_purchase_for_review_idempotently(): void
{
$this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
$user = User::factory()->create();
$variant = $this->createVariantForTenant('sonder', 10, '50.00');
$purchase = $this->createCheckoutPurchase($user, 'sonder', $variant, 2);
$purchase->update([
'payment_method' => 'transfer',
'status' => Purchase::STATUS_PENDING_PAYMENT,
'expires_at' => now()->addMinutes(30),
]);
$url = "/api/tenants/sonder/compras/{$purchase->id}/review";
$this->actingAs($user, 'sanctum')
->postJson($url)
->assertOk()
->assertJsonPath('data.status', Purchase::STATUS_IN_REVIEW)
->assertJsonPath('data.expires_at', null);
$this->assertDatabaseHas('compras', [
'id' => $purchase->id,
'status' => Purchase::STATUS_IN_REVIEW,
'expires_at' => null,
]);
$this->actingAs($user, 'sanctum')
->postJson($url)
->assertOk()
->assertJsonPath('data.status', Purchase::STATUS_IN_REVIEW);
$this->actingAs($user, 'sanctum')
->postJson("/api/tenants/sonder/compras/{$purchase->id}/complete")
->assertOk()
->assertJsonPath('data.status', Purchase::STATUS_IN_REVIEW);
}
public function test_it_rejects_review_for_a_purchase_that_is_not_awaiting_payment(): void
{
$this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
$user = User::factory()->create();
$variant = $this->createVariantForTenant('sonder', 10, '50.00');
$purchase = $this->createCheckoutPurchase($user, 'sonder', $variant, 1);
$this->actingAs($user, 'sanctum')
->postJson("/api/tenants/sonder/compras/{$purchase->id}/review")
->assertUnprocessable()
->assertJsonValidationErrors(['purchase']);
$this->assertDatabaseHas('compras', [
'id' => $purchase->id,
'status' => Purchase::STATUS_CREATED,
]);
}
public function test_it_expires_an_abandoned_purchase_and_restores_its_cart(): void
{
$this->createTenant('sonder', 'Sonder', 'sonder.com.ar');

View File

@@ -193,6 +193,12 @@ class TicketGeneratorServiceTest extends TestCase
$this->assertDatabaseCount('tickets', 2);
Event::assertDispatchedTimes(TicketsAvailable::class, 1);
$this->actingAs($this->user, 'sanctum')
->getJson("/api/tenants/{$this->tenant->codigo}/compras/{$purchase->id}")
->assertOk()
->assertJsonPath('data.tickets_count', 2)
->assertJsonPath('data.has_generated_tickets', true);
$purchase->markAsPaid();
$this->assertDatabaseCount('tickets', 2);
@@ -209,6 +215,7 @@ class TicketGeneratorServiceTest extends TestCase
$purchase->markAsPaid();
$this->assertDatabaseHas('tickets', [
'source_purchase_id' => $purchase->id,
'source_catalog_item_id' => $item->id,
'source_variant_id' => $variant->id,
]);
@@ -226,6 +233,12 @@ class TicketGeneratorServiceTest extends TestCase
$this->assertSame(Purchase::STATUS_PAID, $purchase->status);
$this->assertDatabaseCount('tickets', 0);
Event::assertNotDispatched(TicketsAvailable::class);
$this->actingAs($this->user, 'sanctum')
->getJson("/api/tenants/{$this->tenant->codigo}/compras/{$purchase->id}")
->assertOk()
->assertJsonPath('data.tickets_count', 0)
->assertJsonPath('data.has_generated_tickets', false);
}
public function test_paid_status_is_confirmed_when_ticket_maximum_use_date_was_reached(): void