feat: implement checkout service and payment processing integration
This commit is contained in:
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Integration\Services\Contracts;
|
||||
|
||||
interface PaymentProviderInterface
|
||||
{
|
||||
/**
|
||||
* Procesa un pago con las credenciales específicas del Tenant.
|
||||
*
|
||||
* @param array $paymentData Datos del pago, incluyendo el método (ej. qr, transferencia).
|
||||
* @param array $credentials Credenciales encriptadas previamente configuradas por el Tenant.
|
||||
* @return array
|
||||
*/
|
||||
public function process(array $paymentData, array $credentials): array;
|
||||
}
|
||||
18
app/Domains/Integration/Services/PaymentProviderFactory.php
Normal file
18
app/Domains/Integration/Services/PaymentProviderFactory.php
Normal file
@@ -0,0 +1,18 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Integration\Services;
|
||||
|
||||
use App\Domains\Integration\Services\Contracts\PaymentProviderInterface;
|
||||
use App\Domains\Integration\Services\Providers\TelepagosProvider;
|
||||
use InvalidArgumentException;
|
||||
|
||||
class PaymentProviderFactory
|
||||
{
|
||||
public function make(string $integrationCode): PaymentProviderInterface
|
||||
{
|
||||
return match ($integrationCode) {
|
||||
'telepagos' => new TelepagosProvider(),
|
||||
default => throw new InvalidArgumentException("Integración de pago no soportada: {$integrationCode}"),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Integration\Services\Providers;
|
||||
|
||||
use App\Domains\Integration\Services\Contracts\PaymentProviderInterface;
|
||||
use BadMethodCallException;
|
||||
|
||||
class TelepagosProvider implements PaymentProviderInterface
|
||||
{
|
||||
public function process(array $paymentData, array $credentials): array
|
||||
{
|
||||
// TODO: Implementar lógica de comunicación con Telepagos (usando $paymentData['payment_method'])
|
||||
throw new BadMethodCallException('Método de pago no implementado para Telepagos.');
|
||||
}
|
||||
}
|
||||
@@ -10,7 +10,7 @@ use App\Domains\Tenant\Models\Tenant;
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use App\Domains\Purchase\Services\CheckoutService;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
|
||||
|
||||
@@ -28,28 +28,22 @@ class PurchaseController extends Controller
|
||||
)->response();
|
||||
}
|
||||
|
||||
public function store(StorePurchaseRequest $request, Tenant $tenant): JsonResponse
|
||||
public function store(StorePurchaseRequest $request, Tenant $tenant, CheckoutService $checkoutService): JsonResponse
|
||||
{
|
||||
$data = $request->validated();
|
||||
$items = $data['items'];
|
||||
|
||||
$integrationCode = $data['integration_code'];
|
||||
$paymentData = $data['payment_data'];
|
||||
|
||||
unset($data['integration_code'], $data['payment_data']);
|
||||
|
||||
unset($data['items']);
|
||||
|
||||
$variants = $this->resolveTenantVariants($tenant, $items);
|
||||
$purchaseItems = $this->buildPurchaseItemsPayload($items, $variants);
|
||||
|
||||
$purchase = DB::transaction(function () use ($request, $tenant, $data, $purchaseItems): Purchase {
|
||||
/** @var Purchase $purchase */
|
||||
$purchase = Purchase::query()->create([
|
||||
...$data,
|
||||
'tenant_codigo' => $tenant->codigo,
|
||||
'user_id' => $request->user()->id,
|
||||
]);
|
||||
|
||||
$purchase->items()->createMany($purchaseItems);
|
||||
|
||||
return $purchase->load(['items.variant.product', 'items.variant.definitions.productAttribute.attribute']);
|
||||
});
|
||||
$purchase = $checkoutService->processCheckout(
|
||||
$tenant,
|
||||
$request->user()->id,
|
||||
$data,
|
||||
$integrationCode,
|
||||
$paymentData
|
||||
);
|
||||
|
||||
return PurchaseResource::make($purchase)->response()->setStatusCode(201);
|
||||
}
|
||||
@@ -63,60 +57,7 @@ class PurchaseController extends Controller
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, array<string, mixed>> $items
|
||||
* @return \Illuminate\Support\Collection<int, ProductVariant>
|
||||
*/
|
||||
protected function resolveTenantVariants(Tenant $tenant, array $items)
|
||||
{
|
||||
$variantIds = collect($items)
|
||||
->pluck('producto_variante_id')
|
||||
->filter()
|
||||
->map(static fn (mixed $id): int => (int) $id)
|
||||
->unique()
|
||||
->values();
|
||||
|
||||
$variants = ProductVariant::query()
|
||||
->with('product')
|
||||
->whereIn('id', $variantIds)
|
||||
->whereHas('product', fn ($query) => $query->where('tenant_codigo', $tenant->codigo))
|
||||
->get()
|
||||
->keyBy('id');
|
||||
|
||||
if ($variants->count() !== $variantIds->count()) {
|
||||
throw ValidationException::withMessages([
|
||||
'items' => 'One or more product variants do not belong to the tenant.',
|
||||
]);
|
||||
}
|
||||
|
||||
return $variants;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, array<string, mixed>> $items
|
||||
* @param \Illuminate\Support\Collection<int, ProductVariant> $variants
|
||||
* @return array<int, array<string, mixed>>
|
||||
*/
|
||||
protected function buildPurchaseItemsPayload(array $items, $variants): array
|
||||
{
|
||||
return collect($items)
|
||||
->map(function (array $item) use ($variants): array {
|
||||
/** @var ProductVariant $variant */
|
||||
$variant = $variants->get((int) $item['producto_variante_id']);
|
||||
$quantity = (int) $item['cantidad'];
|
||||
$unitPrice = (float) ($variant->product?->precio ?? 0);
|
||||
|
||||
return [
|
||||
'producto_variante_id' => $variant->getKey(),
|
||||
'cantidad' => $quantity,
|
||||
'precio_unitario' => $unitPrice,
|
||||
'discount_total' => null,
|
||||
'tax_total' => null,
|
||||
'total' => $unitPrice * $quantity,
|
||||
];
|
||||
})
|
||||
->all();
|
||||
}
|
||||
|
||||
protected function resolveScopedPurchase(Tenant $tenant, int $userId, Purchase $purchase): Purchase
|
||||
{
|
||||
|
||||
@@ -20,7 +20,9 @@ class StorePurchaseRequest extends FormRequest
|
||||
return [
|
||||
'status' => ['sometimes', 'string', Rule::in(['pending', 'paid', 'cancelled'])],
|
||||
'payment_status' => ['sometimes', 'string', Rule::in(['pending', 'approved', 'rejected'])],
|
||||
'payment_method' => ['nullable', 'string', 'max:255'],
|
||||
'integration_code' => ['required', 'string'],
|
||||
'payment_data' => ['required', 'array'],
|
||||
'payment_data.payment_method' => ['required', 'string'],
|
||||
'items' => ['required', 'array', 'min:1'],
|
||||
'items.*.producto_variante_id' => ['required', 'integer', 'exists:productos_variantes,id'],
|
||||
'items.*.cantidad' => ['required', 'integer', 'min:1'],
|
||||
|
||||
121
app/Domains/Purchase/Services/CheckoutService.php
Normal file
121
app/Domains/Purchase/Services/CheckoutService.php
Normal file
@@ -0,0 +1,121 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Purchase\Services;
|
||||
|
||||
use App\Domains\Catalog\Models\ProductVariant;
|
||||
use App\Domains\Integration\Services\PaymentProviderFactory;
|
||||
use App\Domains\Integration\Services\TenantIntegrationService;
|
||||
use App\Domains\Purchase\Models\Purchase;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Exception;
|
||||
|
||||
class CheckoutService
|
||||
{
|
||||
protected TenantIntegrationService $tenantIntegrationService;
|
||||
protected PaymentProviderFactory $paymentProviderFactory;
|
||||
|
||||
public function __construct(
|
||||
TenantIntegrationService $tenantIntegrationService,
|
||||
PaymentProviderFactory $paymentProviderFactory
|
||||
) {
|
||||
$this->tenantIntegrationService = $tenantIntegrationService;
|
||||
$this->paymentProviderFactory = $paymentProviderFactory;
|
||||
}
|
||||
|
||||
public function processCheckout(Tenant $tenant, int $userId, array $purchaseData, string $integrationCode, array $paymentData): Purchase
|
||||
{
|
||||
// 1. Obtener configuración del tenant
|
||||
$tenantIntegration = $this->tenantIntegrationService->getTenantIntegration($tenant->codigo, $integrationCode);
|
||||
|
||||
if (!$tenantIntegration) {
|
||||
throw ValidationException::withMessages([
|
||||
'integration_code' => "El tenant no tiene configurada la integración: {$integrationCode}",
|
||||
]);
|
||||
}
|
||||
|
||||
// 2. Instanciar el proveedor de pago
|
||||
$provider = $this->paymentProviderFactory->make($integrationCode);
|
||||
|
||||
// 3. Procesar el pago con las credenciales desencriptadas
|
||||
$paymentResult = $provider->process($paymentData, $tenantIntegration->integration_data);
|
||||
|
||||
// 4. Preparar items de la compra
|
||||
$items = $purchaseData['items'];
|
||||
unset($purchaseData['items']);
|
||||
|
||||
$variants = $this->resolveTenantVariants($tenant, $items);
|
||||
$purchaseItemsPayload = $this->buildPurchaseItemsPayload($items, $variants);
|
||||
|
||||
// 5. Crear la orden de compra
|
||||
return DB::transaction(function () use ($tenant, $userId, $purchaseData, $purchaseItemsPayload, $paymentResult): Purchase {
|
||||
/** @var Purchase $purchase */
|
||||
$purchase = Purchase::query()->create([
|
||||
...$purchaseData,
|
||||
'tenant_codigo' => $tenant->codigo,
|
||||
'user_id' => $userId,
|
||||
// TODO: En un futuro se puede guardar info de $paymentResult en la base de datos (ej: payment_id, status)
|
||||
]);
|
||||
|
||||
$purchase->items()->createMany($purchaseItemsPayload);
|
||||
|
||||
return $purchase->load(['items.variant.product', 'items.variant.definitions.productAttribute.attribute']);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, array<string, mixed>> $items
|
||||
* @return \Illuminate\Support\Collection<int, ProductVariant>
|
||||
*/
|
||||
protected function resolveTenantVariants(Tenant $tenant, array $items)
|
||||
{
|
||||
$variantIds = collect($items)
|
||||
->pluck('producto_variante_id')
|
||||
->filter()
|
||||
->map(static fn (mixed $id): int => (int) $id)
|
||||
->unique()
|
||||
->values();
|
||||
|
||||
$variants = ProductVariant::query()
|
||||
->with('product')
|
||||
->whereIn('id', $variantIds)
|
||||
->whereHas('product', fn ($query) => $query->where('tenant_codigo', $tenant->codigo))
|
||||
->get()
|
||||
->keyBy('id');
|
||||
|
||||
if ($variants->count() !== $variantIds->count()) {
|
||||
throw ValidationException::withMessages([
|
||||
'items' => 'One or more product variants do not belong to the tenant.',
|
||||
]);
|
||||
}
|
||||
|
||||
return $variants;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, array<string, mixed>> $items
|
||||
* @param \Illuminate\Support\Collection<int, ProductVariant> $variants
|
||||
* @return array<int, array<string, mixed>>
|
||||
*/
|
||||
protected function buildPurchaseItemsPayload(array $items, $variants): array
|
||||
{
|
||||
return collect($items)
|
||||
->map(function (array $item) use ($variants): array {
|
||||
/** @var ProductVariant $variant */
|
||||
$variant = $variants->get((int) $item['producto_variante_id']);
|
||||
$quantity = (int) $item['cantidad'];
|
||||
$unitPrice = (float) ($variant->product?->precio ?? 0);
|
||||
|
||||
return [
|
||||
'producto_variante_id' => $variant->getKey(),
|
||||
'cantidad' => $quantity,
|
||||
'precio_unitario' => $unitPrice,
|
||||
'discount_total' => null,
|
||||
'tax_total' => null,
|
||||
'total' => $unitPrice * $quantity,
|
||||
];
|
||||
})
|
||||
->all();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user