Compare commits
25 Commits
0cb1c37566
...
feature/ch
| Author | SHA1 | Date | |
|---|---|---|---|
| b273b2866f | |||
| 05a92b7ec3 | |||
| f23029e785 | |||
| f18fbc8147 | |||
| c276ccd311 | |||
| 786b4eb6a9 | |||
| eca3b01083 | |||
| 7b2a741884 | |||
| 362e888e46 | |||
| 92458e217e | |||
| 4edda0bfd8 | |||
| 2c2cf45f78 | |||
| 1fcb3129ea | |||
| 3703ae9bcf | |||
| c19e00987e | |||
| 7be2221bb8 | |||
| dc32eb9bee | |||
| 6bda3bf013 | |||
| 3731cd67fe | |||
| 403caf77f5 | |||
| 04b2bb0b2a | |||
| 1af5b1d7ed | |||
| 387e136707 | |||
| 9a1e36337d | |||
| 0c28302f84 |
@@ -1,7 +1,7 @@
|
||||
APP_NAME=Laravel
|
||||
APP_ENV=local
|
||||
APP_ENV=production
|
||||
APP_KEY=
|
||||
APP_DEBUG=true
|
||||
APP_DEBUG=false
|
||||
APP_URL=http://localhost
|
||||
FRONTEND_URL=http://localhost:4200
|
||||
INTEGRATION_SECRET=
|
||||
|
||||
1
.gitignore
vendored
1
.gitignore
vendored
@@ -1,6 +1,7 @@
|
||||
*.log
|
||||
.DS_Store
|
||||
.env
|
||||
.env.testing
|
||||
.env.backup
|
||||
.env.production
|
||||
.phpactor.json
|
||||
|
||||
@@ -1367,7 +1367,7 @@
|
||||
],
|
||||
"body": {
|
||||
"mode": "raw",
|
||||
"raw": "{\n \"status\": \"pending\",\n \"payment_status\": \"pending\",\n \"payment_method\": \"cash\",\n \"items\": [\n {\n \"producto_variante_id\": {{product_variant_id}},\n \"cantidad\": 1\n }\n ]\n}"
|
||||
"raw": "{\n \"cart_id\": {{cart_id}},\n \"dni\": \"12345678\",\n \"telefono\": \"+54 9 341 555-4321\",\n \"nombre_apellido\": \"Juan Perez\",\n \"email\": \"juan.perez@example.com\"\n}"
|
||||
},
|
||||
"url": {
|
||||
"raw": "{{base_url}}/api/tenants/{{tenant_codigo}}/compras",
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace App\Domains\Auth\Controllers;
|
||||
|
||||
use App\Domains\Auth\Resources\UserResource;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
@@ -9,6 +10,6 @@ class MeController
|
||||
{
|
||||
public function __invoke(Request $request): JsonResponse
|
||||
{
|
||||
return response()->json($request->user());
|
||||
return response()->json(UserResource::make($request->user())->resolve());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,76 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\BankAccount\Controllers;
|
||||
|
||||
use App\Domains\BankAccount\Models\BankAccount;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use App\Domains\BankAccount\Requests\StoreBankAccountRequest;
|
||||
use App\Domains\BankAccount\Requests\UpdateBankAccountRequest;
|
||||
use App\Domains\BankAccount\Resources\BankAccountResource;
|
||||
use App\Domains\Tenant\Resources\TenantResource;
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Response;
|
||||
|
||||
class BankAccountController extends Controller
|
||||
{
|
||||
public function index(Tenant $tenant): JsonResponse
|
||||
{
|
||||
$accounts = $tenant->bankAccounts()->latest()->get();
|
||||
return BankAccountResource::collection($accounts)->response();
|
||||
}
|
||||
|
||||
public function store(StoreBankAccountRequest $request, Tenant $tenant): JsonResponse
|
||||
{
|
||||
$data = $request->validated();
|
||||
$data['tenant_code'] = $tenant->codigo;
|
||||
|
||||
$account = BankAccount::query()->create($data);
|
||||
|
||||
return BankAccountResource::make($account)->response()->setStatusCode(201);
|
||||
}
|
||||
|
||||
public function show(Tenant $tenant, BankAccount $bankAccount): BankAccountResource
|
||||
{
|
||||
abort_if($bankAccount->tenant_code !== $tenant->codigo, 404);
|
||||
|
||||
return BankAccountResource::make($bankAccount);
|
||||
}
|
||||
|
||||
public function update(UpdateBankAccountRequest $request, Tenant $tenant, BankAccount $bankAccount): BankAccountResource
|
||||
{
|
||||
abort_if($bankAccount->tenant_code !== $tenant->codigo, 404);
|
||||
|
||||
$bankAccount->update($request->validated());
|
||||
|
||||
return BankAccountResource::make($bankAccount);
|
||||
}
|
||||
|
||||
public function destroy(Tenant $tenant, BankAccount $bankAccount): Response
|
||||
{
|
||||
abort_if($bankAccount->tenant_code !== $tenant->codigo, 404);
|
||||
|
||||
$bankAccount->delete();
|
||||
|
||||
return response()->noContent();
|
||||
}
|
||||
|
||||
public function select(Tenant $tenant, BankAccount $bankAccount): TenantResource
|
||||
{
|
||||
abort_if($bankAccount->tenant_code !== $tenant->codigo, 400, 'La cuenta bancaria no pertenece a este tenant.');
|
||||
|
||||
$tenant->selected_bank_account_id = $bankAccount->id;
|
||||
$tenant->save();
|
||||
|
||||
return TenantResource::make($tenant->loadMissing(['headerLogo', 'footerLogo']));
|
||||
}
|
||||
|
||||
public function selected(Tenant $tenant): JsonResponse
|
||||
{
|
||||
$account = $tenant->selectedBankAccount;
|
||||
|
||||
abort_if(!$account, 404, 'No hay ninguna cuenta bancaria seleccionada para este tenant.');
|
||||
|
||||
return BankAccountResource::make($account)->response();
|
||||
}
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\BankAccount\Models;
|
||||
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
class BankAccount extends Model
|
||||
{
|
||||
use HasFactory;
|
||||
|
||||
protected $fillable = [
|
||||
'tenant_code',
|
||||
'titular',
|
||||
'entidad',
|
||||
'alias',
|
||||
'cvu',
|
||||
];
|
||||
|
||||
/**
|
||||
* @return BelongsTo<Tenant, $this>
|
||||
*/
|
||||
public function tenant(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Tenant::class, 'tenant_code', 'codigo');
|
||||
}
|
||||
}
|
||||
@@ -1,47 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\BankAccount\Requests;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
|
||||
class StoreBankAccountRequest extends FormRequest
|
||||
{
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'titular' => ['required', 'string', 'max:255'],
|
||||
'entidad' => ['required', 'string', 'max:255'],
|
||||
'alias' => ['required', 'string', 'max:255'],
|
||||
'cvu' => ['required', 'string', 'max:255'],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, string>
|
||||
*/
|
||||
public function messages(): array
|
||||
{
|
||||
return [
|
||||
'titular.required' => 'El campo titular es obligatorio.',
|
||||
'titular.string' => 'El campo titular debe ser una cadena de texto.',
|
||||
'titular.max' => 'El campo titular no debe superar los 255 caracteres.',
|
||||
'entidad.required' => 'El campo entidad es obligatorio.',
|
||||
'entidad.string' => 'El campo entidad debe ser una cadena de texto.',
|
||||
'entidad.max' => 'El campo entidad no debe superar los 255 caracteres.',
|
||||
'alias.required' => 'El campo alias es obligatorio.',
|
||||
'alias.string' => 'El campo alias debe ser una cadena de texto.',
|
||||
'alias.max' => 'El campo alias no debe superar los 255 caracteres.',
|
||||
'cvu.required' => 'El campo cvu es obligatorio.',
|
||||
'cvu.string' => 'El campo cvu debe ser una cadena de texto.',
|
||||
'cvu.max' => 'El campo cvu no debe superar los 255 caracteres.',
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -1,43 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\BankAccount\Requests;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
|
||||
class UpdateBankAccountRequest extends FormRequest
|
||||
{
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'titular' => ['sometimes', 'string', 'max:255'],
|
||||
'entidad' => ['sometimes', 'string', 'max:255'],
|
||||
'alias' => ['sometimes', 'string', 'max:255'],
|
||||
'cvu' => ['sometimes', 'string', 'max:255'],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, string>
|
||||
*/
|
||||
public function messages(): array
|
||||
{
|
||||
return [
|
||||
'titular.string' => 'El campo titular debe ser una cadena de texto.',
|
||||
'titular.max' => 'El campo titular no debe superar los 255 caracteres.',
|
||||
'entidad.string' => 'El campo entidad debe ser una cadena de texto.',
|
||||
'entidad.max' => 'El campo entidad no debe superar los 255 caracteres.',
|
||||
'alias.string' => 'El campo alias debe ser una cadena de texto.',
|
||||
'alias.max' => 'El campo alias no debe superar los 255 caracteres.',
|
||||
'cvu.string' => 'El campo cvu debe ser una cadena de texto.',
|
||||
'cvu.max' => 'El campo cvu no debe superar los 255 caracteres.',
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\BankAccount\Resources;
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
/**
|
||||
* @mixin \App\Domains\BankAccount\Models\BankAccount
|
||||
*/
|
||||
class BankAccountResource extends JsonResource
|
||||
{
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'tenant_code' => $this->tenant_code,
|
||||
'titular' => $this->titular,
|
||||
'entidad' => $this->entidad,
|
||||
'alias' => $this->alias,
|
||||
'cvu' => $this->cvu,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
<?php
|
||||
|
||||
use App\Domains\BankAccount\Controllers\BankAccountController;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
|
||||
Route::prefix('tenants/{tenant:codigo}')->group(function (): void {
|
||||
Route::middleware('auth:sanctum')->group(function (): void {
|
||||
Route::get('bank-accounts/selected', [BankAccountController::class, 'selected']);
|
||||
Route::post('bank-accounts/{bank_account}/select', [BankAccountController::class, 'select']);
|
||||
Route::apiResource('bank-accounts', BankAccountController::class)
|
||||
->parameters(['bank-accounts' => 'bank_account']);
|
||||
});
|
||||
});
|
||||
73
app/Domains/Cart/Middleware/MergeGuestCartMiddleware.php
Normal file
73
app/Domains/Cart/Middleware/MergeGuestCartMiddleware.php
Normal file
@@ -0,0 +1,73 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Cart\Middleware;
|
||||
|
||||
use App\Domains\Cart\Models\Cart;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use Closure;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Facades\Cookie;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
class MergeGuestCartMiddleware
|
||||
{
|
||||
public function handle(Request $request, Closure $next): Response
|
||||
{
|
||||
$guestToken = $request->cookie('guest_token');
|
||||
|
||||
// Resolve authenticated user optionally (from default guard or sanctum guard)
|
||||
$user = $request->user() ?? Auth::guard('sanctum')->user();
|
||||
$userId = $user?->getKey();
|
||||
|
||||
\Illuminate\Support\Facades\Log::info('MergeGuestCartMiddleware processed', [
|
||||
'user_id' => $userId,
|
||||
'guest_token' => $guestToken,
|
||||
]);
|
||||
|
||||
if ($user !== null && is_string($guestToken) && $guestToken !== '') {
|
||||
$tenantParam = $request->route('tenant');
|
||||
$tenantCodigo = null;
|
||||
|
||||
if ($tenantParam instanceof Tenant) {
|
||||
$tenantCodigo = $tenantParam->codigo;
|
||||
} elseif (is_string($tenantParam)) {
|
||||
$tenantCodigo = $tenantParam;
|
||||
}
|
||||
|
||||
if ($tenantCodigo !== null) {
|
||||
$guestCart = Cart::query()
|
||||
->where('tenant_codigo', $tenantCodigo)
|
||||
->where('guest_token', $guestToken)
|
||||
->first();
|
||||
|
||||
if ($guestCart !== null && $guestCart->items()->exists()) {
|
||||
$userCart = Cart::query()
|
||||
->where('tenant_codigo', $tenantCodigo)
|
||||
->where('user_id', $userId)
|
||||
->first();
|
||||
|
||||
if ($userCart !== null) {
|
||||
$userCart->delete();
|
||||
}
|
||||
|
||||
$guestCart->update([
|
||||
'user_id' => $userId,
|
||||
'guest_token' => null,
|
||||
]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$response = $next($request);
|
||||
|
||||
if ($user !== null && is_string($guestToken) && $guestToken !== '') {
|
||||
// Remove the cookie from the response since the user is authenticated.
|
||||
if (method_exists($response, 'withCookie')) {
|
||||
$response->withCookie(Cookie::forget('guest_token'));
|
||||
}
|
||||
}
|
||||
|
||||
return $response;
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,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\SoftDeletes;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
|
||||
@@ -23,6 +24,7 @@ use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
|
||||
class Cart extends Model
|
||||
{
|
||||
use HasFactory;
|
||||
use SoftDeletes;
|
||||
|
||||
protected $table = 'carritos';
|
||||
|
||||
@@ -57,6 +59,18 @@ class Cart extends Model
|
||||
return $this->hasMany(CartItem::class, 'cart_id');
|
||||
}
|
||||
|
||||
public function getTotalAmount(): float
|
||||
{
|
||||
$items = $this->relationLoaded('items')
|
||||
? $this->getRelation('items')
|
||||
: $this->items()->with('variant.product')->get();
|
||||
|
||||
return (float) $items->reduce(
|
||||
fn (float $carry, $item): float => $carry + ((float) ($item->variant?->product?->precio ?? 0) * $item->cantidad),
|
||||
0.0,
|
||||
);
|
||||
}
|
||||
|
||||
public function addItem(int $productVariantId, int $quantity): CartItem
|
||||
{
|
||||
if ($quantity <= 0) {
|
||||
|
||||
@@ -104,7 +104,7 @@ class CartService
|
||||
*/
|
||||
protected function resolveIdentity(Request $request, bool $generateGuestToken = false): ?array
|
||||
{
|
||||
$user = $request->user();
|
||||
$user = $request->user() ?? \Illuminate\Support\Facades\Auth::guard('sanctum')->user();
|
||||
|
||||
if ($user instanceof User) {
|
||||
return [
|
||||
|
||||
@@ -3,9 +3,11 @@
|
||||
use App\Domains\Cart\Controllers\CartController;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
|
||||
Route::prefix('tenants/{tenant:codigo}')->group(function (): void {
|
||||
Route::get('cart', [CartController::class, 'show']);
|
||||
Route::post('cart/items', [CartController::class, 'addItem']);
|
||||
Route::patch('cart/items/{productVariant}', [CartController::class, 'updateItemQuantity']);
|
||||
Route::delete('cart/items/{productVariant}', [CartController::class, 'removeItem']);
|
||||
});
|
||||
Route::prefix('tenants/{tenant:codigo}')
|
||||
->middleware(\App\Domains\Cart\Middleware\MergeGuestCartMiddleware::class)
|
||||
->group(function (): void {
|
||||
Route::get('cart', [CartController::class, 'show']);
|
||||
Route::post('cart/items', [CartController::class, 'addItem']);
|
||||
Route::patch('cart/items/{productVariant}', [CartController::class, 'updateItemQuantity']);
|
||||
Route::delete('cart/items/{productVariant}', [CartController::class, 'removeItem']);
|
||||
});
|
||||
|
||||
@@ -85,6 +85,25 @@ class ProductVariant extends Model
|
||||
$this->save();
|
||||
}
|
||||
|
||||
public function confirmReservedStock(int $amount): void
|
||||
{
|
||||
if ($amount < 0) {
|
||||
throw new \InvalidArgumentException('El monto a confirmar debe ser positivo.');
|
||||
}
|
||||
|
||||
if ($this->stock_real < $amount) {
|
||||
throw new \InvalidArgumentException('No hay suficiente stock real para confirmar la reserva.');
|
||||
}
|
||||
|
||||
if ($this->stock_reservado < $amount) {
|
||||
throw new \InvalidArgumentException('No hay suficiente stock reservado para confirmar la reserva.');
|
||||
}
|
||||
|
||||
$this->stock_real -= $amount;
|
||||
$this->stock_reservado -= $amount;
|
||||
$this->save();
|
||||
}
|
||||
|
||||
protected function stockTecnico(): Attribute
|
||||
{
|
||||
return Attribute::get(fn () => $this->stock_real - $this->stock_reservado);
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Integration\Controllers;
|
||||
|
||||
use App\Domains\Integration\Requests\TelepagosWebhookRequest;
|
||||
use App\Domains\Integration\Services\TelepagosWebhookService;
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
class TelepagosWebhookController extends Controller
|
||||
{
|
||||
/**
|
||||
* Handle the incoming Telepagos webhook.
|
||||
*
|
||||
* @param TelepagosWebhookRequest $request
|
||||
* @param string $tenantCodigo
|
||||
* @param TelepagosWebhookService $service
|
||||
* @return JsonResponse
|
||||
*/
|
||||
public function handle(TelepagosWebhookRequest $request, string $tenantCodigo, TelepagosWebhookService $service): JsonResponse
|
||||
{
|
||||
try {
|
||||
$cashinId = $request->validated('id');
|
||||
|
||||
$service->handleWebhook($tenantCodigo, $cashinId);
|
||||
|
||||
return response()->json(['status' => 'success']);
|
||||
} catch (\Exception $e) {
|
||||
return response()->json(['status' => 'error', 'message' => $e->getMessage()], 500);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -36,12 +36,18 @@ class TenantIntegrationController extends Controller
|
||||
{
|
||||
$integration = Integration::where('integration_code', $integrationCode)->firstOrFail();
|
||||
|
||||
$tenantIntegration = $this->tenantIntegrationService->updateOrCreateIntegration(
|
||||
$tenantCode,
|
||||
$integration,
|
||||
$request->input('integration_data', [])
|
||||
);
|
||||
try {
|
||||
$tenantIntegration = $this->tenantIntegrationService->updateOrCreateIntegration(
|
||||
$tenantCode,
|
||||
$integration,
|
||||
$request->input('integration_data', [])
|
||||
);
|
||||
|
||||
return response()->json($tenantIntegration);
|
||||
return response()->json($tenantIntegration);
|
||||
} catch (\Exception $e) {
|
||||
return response()->json([
|
||||
'message' => 'Error validando la configuración: ' . $e->getMessage()
|
||||
], 400);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
28
app/Domains/Integration/Requests/TelepagosWebhookRequest.php
Normal file
28
app/Domains/Integration/Requests/TelepagosWebhookRequest.php
Normal file
@@ -0,0 +1,28 @@
|
||||
<?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'],
|
||||
];
|
||||
}
|
||||
}
|
||||
167
app/Domains/Integration/Services/BaseIntegrationService.php
Normal file
167
app/Domains/Integration/Services/BaseIntegrationService.php
Normal file
@@ -0,0 +1,167 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Integration\Services;
|
||||
|
||||
use App\Domains\Integration\Models\Integration;
|
||||
use App\Domains\Integration\Models\TenantIntegration;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Http\Client\PendingRequest;
|
||||
use Exception;
|
||||
|
||||
abstract class BaseIntegrationService
|
||||
{
|
||||
/**
|
||||
* The unique code of the integration.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected string $integrationCode;
|
||||
|
||||
/**
|
||||
* The current tenant code.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected string $tenantCode;
|
||||
|
||||
/**
|
||||
* The integration model instance.
|
||||
*
|
||||
* @var Integration|null
|
||||
*/
|
||||
protected ?Integration $integration = null;
|
||||
|
||||
/**
|
||||
* The tenant-specific integration model instance.
|
||||
*
|
||||
* @var TenantIntegration|null
|
||||
*/
|
||||
protected ?TenantIntegration $tenantIntegration = null;
|
||||
|
||||
/**
|
||||
* Set the integration code.
|
||||
*
|
||||
* @param string $integrationCode
|
||||
* @return $this
|
||||
*/
|
||||
public function setIntegrationCode(string $integrationCode): self
|
||||
{
|
||||
$this->integrationCode = $integrationCode;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the integration code.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getIntegrationCode(): string
|
||||
{
|
||||
return $this->integrationCode;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the tenant code and load the integration models.
|
||||
*
|
||||
* @param string $tenantCode
|
||||
* @return $this
|
||||
* @throws Exception
|
||||
*/
|
||||
public function forTenant(string $tenantCode): self
|
||||
{
|
||||
$this->tenantCode = $tenantCode;
|
||||
$this->loadIntegration();
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Load the Integration and TenantIntegration models.
|
||||
*
|
||||
* @throws Exception
|
||||
*/
|
||||
protected function loadIntegration(): void
|
||||
{
|
||||
if (empty($this->integrationCode)) {
|
||||
throw new Exception("Integration code is not set.");
|
||||
}
|
||||
|
||||
$this->integration = Integration::where('integration_code', $this->integrationCode)->first();
|
||||
if (!$this->integration) {
|
||||
throw new Exception("Integration with code '{$this->integrationCode}' not found.");
|
||||
}
|
||||
|
||||
$this->tenantIntegration = TenantIntegration::where('tenant_code', $this->tenantCode)
|
||||
->where('integration_code', $this->integrationCode)
|
||||
->first();
|
||||
|
||||
if (!$this->tenantIntegration) {
|
||||
throw new Exception("Tenant '{$this->tenantCode}' does not have integration '{$this->integrationCode}' configured.");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the request URL.
|
||||
*
|
||||
* @param string $path
|
||||
* @return string
|
||||
* @throws Exception
|
||||
*/
|
||||
public function getUrl(string $path = ''): string
|
||||
{
|
||||
if (!$this->integration) {
|
||||
throw new Exception("Integration is not loaded. Call forTenant() first.");
|
||||
}
|
||||
|
||||
$baseUrl = rtrim($this->integration->url, '/');
|
||||
$path = ltrim($path, '/');
|
||||
|
||||
return $path !== '' ? "{$baseUrl}/{$path}" : $baseUrl;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get integration setting by key from tenant's integration data.
|
||||
*
|
||||
* @param string $key
|
||||
* @param mixed $default
|
||||
* @return mixed
|
||||
*/
|
||||
protected function getIntegrationSetting(string $key, mixed $default = null): mixed
|
||||
{
|
||||
if (!$this->tenantIntegration || !$this->tenantIntegration->integration_data) {
|
||||
return $default;
|
||||
}
|
||||
|
||||
return $this->tenantIntegration->integration_data[$key] ?? $default;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a pre-configured HTTP client builder.
|
||||
*
|
||||
* @return PendingRequest
|
||||
* @throws Exception
|
||||
*/
|
||||
public function client(): PendingRequest
|
||||
{
|
||||
return Http::baseUrl($this->getUrl())
|
||||
->withHeaders($this->getHeaders());
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the headers for the integration.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
abstract public function getHeaders(): array;
|
||||
|
||||
/**
|
||||
* Hook called after the integration is configured for the tenant.
|
||||
* Can be used to validate credentials or perform initial setups.
|
||||
* Throw an Exception on failure.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function onSetup(): void
|
||||
{
|
||||
// Override in child classes if needed
|
||||
}
|
||||
}
|
||||
228
app/Domains/Integration/Services/TelepagosIntegrationService.php
Normal file
228
app/Domains/Integration/Services/TelepagosIntegrationService.php
Normal file
@@ -0,0 +1,228 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Integration\Services;
|
||||
|
||||
use Exception;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Carbon\Carbon;
|
||||
|
||||
class TelepagosIntegrationService extends BaseIntegrationService
|
||||
{
|
||||
/**
|
||||
* TelepagosIntegrationService constructor.
|
||||
*
|
||||
* @param string $integrationCode
|
||||
*/
|
||||
public function __construct(string $integrationCode = 'telepagos')
|
||||
{
|
||||
// Force homologation code if not in production and using default
|
||||
if ($integrationCode === 'telepagos' && !app()->environment('production')) {
|
||||
$integrationCode = 'telepagos_homo';
|
||||
}
|
||||
|
||||
$this->integrationCode = $integrationCode;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the headers for Telepagos integration.
|
||||
*
|
||||
* @return array
|
||||
* @throws Exception
|
||||
*/
|
||||
public function getHeaders(): array
|
||||
{
|
||||
return [
|
||||
'Authorization' => 'Bearer ' . $this->getToken(),
|
||||
'Content-Type' => 'application/json',
|
||||
'Accept' => 'application/json',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a valid token, either from cache or by performing a login.
|
||||
*
|
||||
* @return string
|
||||
* @throws Exception
|
||||
*/
|
||||
public function getToken(): string
|
||||
{
|
||||
if (!$this->tenantIntegration) {
|
||||
throw new Exception("Tenant integration is not loaded. Call forTenant() first.");
|
||||
}
|
||||
|
||||
$cacheKey = "integration_token:{$this->tenantCode}:{$this->integrationCode}";
|
||||
|
||||
$token = Cache::get($cacheKey);
|
||||
|
||||
if ($token) {
|
||||
return $token;
|
||||
}
|
||||
|
||||
return $this->login();
|
||||
}
|
||||
|
||||
/**
|
||||
* Authenticate with Telepagos and cache the returned token.
|
||||
*
|
||||
* @return string
|
||||
* @throws Exception
|
||||
*/
|
||||
public function login(): string
|
||||
{
|
||||
$username = $this->getIntegrationSetting('username');
|
||||
$password = $this->getIntegrationSetting('password');
|
||||
|
||||
if (empty($username) || empty($password)) {
|
||||
throw new Exception("Missing username or password in Telepagos integration settings.");
|
||||
}
|
||||
|
||||
$url = $this->getUrl('/v2/auth/token');
|
||||
|
||||
$response = Http::post($url, [
|
||||
'username' => $username,
|
||||
'password' => $password,
|
||||
]);
|
||||
|
||||
$data = $this->handleResponse($response, 'authentication', [
|
||||
'username' => $username,
|
||||
]);
|
||||
|
||||
$token = $data['token'] ?? null;
|
||||
$expiresAtStr = $data['expires_at'] ?? null;
|
||||
|
||||
if (!$token || !$expiresAtStr) {
|
||||
throw new Exception("Telepagos authentication response is missing token or expires_at.");
|
||||
}
|
||||
|
||||
$expiresAt = Carbon::parse($expiresAtStr);
|
||||
// Calculate TTL and subtract a buffer of 60 seconds
|
||||
$ttlSeconds = max(1, $expiresAt->diffInSeconds(now()) - 60);
|
||||
|
||||
$cacheKey = "integration_token:{$this->tenantCode}:{$this->integrationCode}";
|
||||
Cache::put($cacheKey, $token, $ttlSeconds);
|
||||
|
||||
return $token;
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a request to Telepagos, handling 401 Unauthorized for token refresh.
|
||||
*
|
||||
* @param string $method
|
||||
* @param string $endpoint
|
||||
* @param array $data
|
||||
* @return \Illuminate\Http\Client\Response
|
||||
*/
|
||||
protected function sendRequest(string $method, string $endpoint, array $data = []): \Illuminate\Http\Client\Response
|
||||
{
|
||||
$response = $this->client()->$method($endpoint, $data);
|
||||
|
||||
if ($response->status() === 401) {
|
||||
Log::info("Telepagos 401 Unauthorized. Refreshing token and retrying...");
|
||||
|
||||
$this->clearToken();
|
||||
|
||||
$response = $this->client()->$method($endpoint, $data);
|
||||
}
|
||||
|
||||
return $response;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a QR code for cash-in.
|
||||
*
|
||||
* @param float $amount
|
||||
* @param string $concept
|
||||
* @param string $description
|
||||
* @return array
|
||||
* @throws Exception
|
||||
*/
|
||||
public function generateQr(float $amount, string $concept, string $description): array
|
||||
{
|
||||
$payload = [
|
||||
'amount' => $amount,
|
||||
'concept' => $concept,
|
||||
'description' => $description,
|
||||
];
|
||||
|
||||
$response = $this->sendRequest('post', '/v2/payment/cashin/qr/generate', $payload);
|
||||
|
||||
return $this->handleResponse($response, 'QR generation', $payload);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the details of a cash-in payment.
|
||||
*
|
||||
* @param int $cashinId
|
||||
* @return array
|
||||
* @throws Exception
|
||||
*/
|
||||
public function getCashinDetails(string $cashinId): array
|
||||
{
|
||||
$response = $this->sendRequest('get', "/v2/payment/cashin/{$cashinId}");
|
||||
|
||||
return $this->handleResponse($response, 'get cash-in details', [
|
||||
'cashin_id' => $cashinId,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the account info.
|
||||
*
|
||||
* @return array
|
||||
* @throws Exception
|
||||
*/
|
||||
public function getAccountInfo(): array
|
||||
{
|
||||
$response = $this->sendRequest('get', '/v2/account/info');
|
||||
return $this->handleResponse($response, 'get account info');
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle the Telepagos API response, logging any failures and throwing Exceptions.
|
||||
*
|
||||
* @param \Illuminate\Http\Client\Response $response
|
||||
* @param string $actionDescription
|
||||
* @param array $context
|
||||
* @return array
|
||||
* @throws Exception
|
||||
*/
|
||||
protected function handleResponse(\Illuminate\Http\Client\Response $response, string $actionDescription, array $context = []): array
|
||||
{
|
||||
if ($response->failed() || $response->json('status') !== 'ok') {
|
||||
$errorMessage = $response->json('message') ?? $response->body();
|
||||
Log::error("Telepagos {$actionDescription} failed: {$errorMessage}", array_merge([
|
||||
'response_status' => $response->status(),
|
||||
'response_body' => $response->json() ?? $response->body(),
|
||||
], $context));
|
||||
|
||||
throw new Exception("Telepagos {$actionDescription} failed: {$errorMessage}");
|
||||
}
|
||||
|
||||
return $response->json() ?? [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear the cached token.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function clearToken(): void
|
||||
{
|
||||
$cacheKey = "integration_token:{$this->tenantCode}:{$this->integrationCode}";
|
||||
Cache::forget($cacheKey);
|
||||
}
|
||||
|
||||
/**
|
||||
* Perform initial setup validation for Telepagos.
|
||||
*
|
||||
* @return void
|
||||
* @throws Exception
|
||||
*/
|
||||
public function onSetup(): void
|
||||
{
|
||||
// Realiza un login de prueba para validar que las credenciales son correctas.
|
||||
$this->login();
|
||||
}
|
||||
}
|
||||
134
app/Domains/Integration/Services/TelepagosWebhookService.php
Normal file
134
app/Domains/Integration/Services/TelepagosWebhookService.php
Normal file
@@ -0,0 +1,134 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Integration\Services;
|
||||
|
||||
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\Tenant\Models\Tenant;
|
||||
use Exception;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
class TelepagosWebhookService
|
||||
{
|
||||
public function __construct(
|
||||
private readonly CheckoutService $checkoutService,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* 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->forTenant($tenant->codigo);
|
||||
|
||||
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;
|
||||
|
||||
$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::warning("Telepagos webhook: CUIT not found for Transferencia cashin {$cashinId}");
|
||||
return;
|
||||
}
|
||||
|
||||
$dni = substr($cuit, 2, -1);
|
||||
|
||||
$compra = Purchase::where('tenant_codigo', $tenantCodigo)
|
||||
->whereRaw("REPLACE(dni, '.', '') = ?", [$dni])
|
||||
->whereIn('status', [Purchase::STATUS_CREATED, Purchase::STATUS_PENDING_PAYMENT])
|
||||
->where('payment_method', 'transfer')
|
||||
->where('total', $amount)
|
||||
->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;
|
||||
}
|
||||
|
||||
$telepagosQr = TelepagosQr::where('qr_order_id', $qrOrderId)->first();
|
||||
|
||||
if (! $telepagosQr) {
|
||||
Log::warning("Telepagos webhook: QR {$qrOrderId} not found in database for cashin {$cashinId}");
|
||||
return;
|
||||
}
|
||||
|
||||
$compra = $telepagosQr->compra;
|
||||
|
||||
if (! $compra) {
|
||||
Log::warning("Telepagos webhook: Purchase not found for QR {$qrOrderId}");
|
||||
return;
|
||||
}
|
||||
|
||||
if ($compra->status !== Purchase::STATUS_PENDING_PAYMENT) {
|
||||
Log::warning("Telepagos webhook: Purchase {$compra->id} is not awaiting payment confirmation");
|
||||
return;
|
||||
}
|
||||
|
||||
$totalAmount = $this->normalizeAmount($compra->getTotalAmount());
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
$paymentData = [
|
||||
'compra_id' => $compra->id,
|
||||
'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,
|
||||
];
|
||||
|
||||
\Illuminate\Support\Facades\DB::transaction(function () use ($compra, $paymentData) {
|
||||
TelepagosPayment::create($paymentData);
|
||||
$this->checkoutService->confirmPurchase($compra);
|
||||
$compra->markAsPaid();
|
||||
});
|
||||
|
||||
Log::info("Telepagos webhook: Successfully processed cashin {$cashinId} for purchase {$compra->id}");
|
||||
} catch (Exception $e) {
|
||||
Log::error("Telepagos webhook error: " . $e->getMessage());
|
||||
throw $e;
|
||||
}
|
||||
}
|
||||
|
||||
protected function normalizeAmount(mixed $amount): string
|
||||
{
|
||||
return number_format((float) $amount, 2, '.', '');
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ namespace App\Domains\Integration\Services;
|
||||
|
||||
use App\Domains\Integration\Models\Integration;
|
||||
use App\Domains\Integration\Models\TenantIntegration;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
class TenantIntegrationService
|
||||
{
|
||||
@@ -23,14 +24,34 @@ class TenantIntegrationService
|
||||
|
||||
public function updateOrCreateIntegration(string $tenantCode, Integration $integration, array $data): TenantIntegration
|
||||
{
|
||||
return TenantIntegration::updateOrCreate(
|
||||
[
|
||||
'tenant_code' => $tenantCode,
|
||||
'integration_code' => $integration->integration_code,
|
||||
],
|
||||
[
|
||||
'integration_data' => $data,
|
||||
]
|
||||
);
|
||||
return DB::transaction(function () use ($tenantCode, $integration, $data) {
|
||||
$tenantIntegration = TenantIntegration::updateOrCreate(
|
||||
[
|
||||
'tenant_code' => $tenantCode,
|
||||
'integration_code' => $integration->integration_code,
|
||||
],
|
||||
[
|
||||
'integration_data' => $data,
|
||||
]
|
||||
);
|
||||
|
||||
$service = $this->resolveService($integration->integration_code);
|
||||
if ($service) {
|
||||
$service->forTenant($tenantCode)->onSetup();
|
||||
}
|
||||
|
||||
return $tenantIntegration;
|
||||
});
|
||||
}
|
||||
|
||||
protected function resolveService(string $integrationCode): ?BaseIntegrationService
|
||||
{
|
||||
switch ($integrationCode) {
|
||||
case 'telepagos':
|
||||
case 'telepagos_homo':
|
||||
return new TelepagosIntegrationService($integrationCode);
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,3 +17,5 @@ Route::group(['prefix' => '{tenant_code}/integrations'], function () {
|
||||
Route::get('/{integration_code}', [TenantIntegrationController::class, 'show']);
|
||||
Route::post('/{integration_code}', [TenantIntegrationController::class, 'store']);
|
||||
});
|
||||
|
||||
Route::post('webhooks/telepagos/{tenant_codigo}', [\App\Domains\Integration\Controllers\TelepagosWebhookController::class, 'handle']);
|
||||
|
||||
@@ -2,16 +2,15 @@
|
||||
|
||||
namespace App\Domains\Purchase\Controllers;
|
||||
|
||||
use App\Domains\Catalog\Models\ProductVariant;
|
||||
use App\Domains\Purchase\Models\Purchase;
|
||||
use App\Domains\Purchase\Requests\StorePurchaseRequest;
|
||||
use App\Domains\Purchase\Resources\PurchaseResource;
|
||||
use App\Domains\Purchase\Services\CheckoutService;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use App\Domains\Purchase\Services\CheckoutService;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
|
||||
|
||||
class PurchaseController extends Controller
|
||||
@@ -23,6 +22,9 @@ class PurchaseController extends Controller
|
||||
->with(['items.variant.product', 'items.variant.definitions.productAttribute.attribute'])
|
||||
->where('tenant_codigo', $tenant->codigo)
|
||||
->where('user_id', $request->user()->id)
|
||||
->when($request->query('status'), function ($query, $status) {
|
||||
$query->where('status', $status);
|
||||
})
|
||||
->latest()
|
||||
->paginateFromRequest()
|
||||
)->response();
|
||||
@@ -32,7 +34,7 @@ class PurchaseController extends Controller
|
||||
{
|
||||
$data = $request->validated();
|
||||
|
||||
$purchase = $checkoutService->processCheckout(
|
||||
$purchase = $checkoutService->startCheckout(
|
||||
$tenant,
|
||||
$request->user()->id,
|
||||
$data
|
||||
@@ -50,7 +52,85 @@ class PurchaseController extends Controller
|
||||
);
|
||||
}
|
||||
|
||||
public function paymentIntent(\App\Domains\Purchase\Requests\PaymentIntentRequest $request, Tenant $tenant, Purchase $compra): JsonResponse
|
||||
{
|
||||
$compra = $this->resolveScopedPurchase($tenant, $request->user()->id, $compra);
|
||||
$method = $request->validated('method');
|
||||
$totalAmount = $compra->calculateCurrentTotalAmount();
|
||||
|
||||
$compra->update([
|
||||
'payment_method' => $method,
|
||||
'total' => $totalAmount,
|
||||
]);
|
||||
|
||||
if ($method === 'transfer') {
|
||||
$telepagosService = new \App\Domains\Integration\Services\TelepagosIntegrationService();
|
||||
$telepagosService->forTenant($tenant->codigo);
|
||||
|
||||
try {
|
||||
$accountInfo = $telepagosService->getAccountInfo();
|
||||
|
||||
return response()->json([
|
||||
'payment_method' => 'transfer',
|
||||
'transfer_data' => [
|
||||
'titular' => $accountInfo['holder'] ?? null,
|
||||
'cvu' => $accountInfo['cvu'] ?? null,
|
||||
'alias' => $accountInfo['alias'] ?? null,
|
||||
'cuit' => $accountInfo['cuit'] ?? null,
|
||||
'entidad' => $accountInfo['entity'] ?? 'Telepagos S.A.',
|
||||
],
|
||||
]);
|
||||
} catch (\Exception $e) {
|
||||
return response()->json([
|
||||
'message' => 'Error getting account info: ' . $e->getMessage()
|
||||
], 500);
|
||||
}
|
||||
}
|
||||
|
||||
if ($method === 'qr') {
|
||||
$telepagosService = new \App\Domains\Integration\Services\TelepagosIntegrationService();
|
||||
$telepagosService->forTenant($tenant->codigo);
|
||||
|
||||
try {
|
||||
Log::info("Generating QR for purchase ID: {$compra->id}, amount: {$totalAmount}");
|
||||
$qrResponse = $telepagosService->generateQr(
|
||||
$totalAmount,
|
||||
'Compra',
|
||||
"Compra #{$compra->id}"
|
||||
);
|
||||
|
||||
$telepagosQr = $compra->telepagosQr()->create([
|
||||
'qr_order_id' => (string) ($qrResponse['qr_order_id'] ?? ''),
|
||||
'qr_code' => $qrResponse['qr_code'] ?? '',
|
||||
]);
|
||||
} catch (\Exception $e) {
|
||||
return response()->json([
|
||||
'message' => 'Error generating QR: ' . $e->getMessage()
|
||||
], 500);
|
||||
}
|
||||
|
||||
return response()->json([
|
||||
'payment_method' => 'qr',
|
||||
'qr_data' => [
|
||||
'qr_code' => $telepagosQr->qr_code,
|
||||
'qr_order_id' => $telepagosQr->qr_order_id,
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
return response()->json([
|
||||
'message' => 'Invalid payment method.',
|
||||
], 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)
|
||||
);
|
||||
}
|
||||
|
||||
protected function resolveScopedPurchase(Tenant $tenant, int $userId, Purchase $purchase): Purchase
|
||||
{
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
namespace App\Domains\Purchase\Models;
|
||||
|
||||
use App\Domains\Auth\Models\User;
|
||||
use App\Domains\Cart\Models\Cart;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
@@ -11,11 +12,12 @@ use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
|
||||
#[Fillable([
|
||||
'cart_id',
|
||||
'tenant_codigo',
|
||||
'user_id',
|
||||
'status',
|
||||
'payment_status',
|
||||
'payment_method',
|
||||
'total',
|
||||
'dni',
|
||||
'telefono',
|
||||
'nombre_apellido',
|
||||
@@ -25,12 +27,20 @@ class Purchase extends Model
|
||||
{
|
||||
use HasFactory;
|
||||
|
||||
public const STATUS_CREATED = 'created';
|
||||
public const STATUS_PENDING_PAYMENT = 'pending_payment';
|
||||
public const STATUS_PAID = 'paid';
|
||||
public const STATUS_CANCELLED = 'cancelled';
|
||||
public const STATUS_REJECTED = 'rejected';
|
||||
|
||||
protected $table = 'compras';
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'cart_id' => 'integer',
|
||||
'user_id' => 'integer',
|
||||
'total' => 'decimal:2',
|
||||
];
|
||||
}
|
||||
|
||||
@@ -50,6 +60,14 @@ class Purchase extends Model
|
||||
return $this->belongsTo(User::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return BelongsTo<Cart, $this>
|
||||
*/
|
||||
public function cart(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Cart::class, 'cart_id');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return HasMany<PurchaseItem, $this>
|
||||
*/
|
||||
@@ -57,4 +75,64 @@ class Purchase extends Model
|
||||
{
|
||||
return $this->hasMany(PurchaseItem::class, 'compra_id');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return \Illuminate\Database\Eloquent\Relations\HasOne<TelepagosQr, $this>
|
||||
*/
|
||||
public function telepagosQr()
|
||||
{
|
||||
return $this->hasOne(TelepagosQr::class, 'compra_id');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return HasMany<TelepagosPayment, $this>
|
||||
*/
|
||||
public function telepagosPayments(): HasMany
|
||||
{
|
||||
return $this->hasMany(TelepagosPayment::class, 'compra_id');
|
||||
}
|
||||
|
||||
public function getTotalAmount(): float
|
||||
{
|
||||
if ($this->total !== null) {
|
||||
return (float) $this->total;
|
||||
}
|
||||
|
||||
return $this->calculateCurrentTotalAmount();
|
||||
}
|
||||
|
||||
public function calculateCurrentTotalAmount(): float
|
||||
{
|
||||
if ($this->relationLoaded('items') && $this->getRelation('items')->isNotEmpty()) {
|
||||
return (float) $this->getRelation('items')->sum('total');
|
||||
}
|
||||
|
||||
if ($this->items()->exists()) {
|
||||
return (float) $this->items()->sum('total');
|
||||
}
|
||||
|
||||
$cart = $this->relationLoaded('cart')
|
||||
? $this->getRelation('cart')
|
||||
: $this->cart()->with('items.variant.product')->first();
|
||||
|
||||
if (! $cart) {
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
return $cart->getTotalAmount();
|
||||
}
|
||||
|
||||
public function markAsPendingPayment(): void
|
||||
{
|
||||
$this->update([
|
||||
'status' => self::STATUS_PENDING_PAYMENT,
|
||||
]);
|
||||
}
|
||||
|
||||
public function markAsPaid(): void
|
||||
{
|
||||
$this->update([
|
||||
'status' => self::STATUS_PAID,
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
43
app/Domains/Purchase/Models/TelepagosPayment.php
Normal file
43
app/Domains/Purchase/Models/TelepagosPayment.php
Normal file
@@ -0,0 +1,43 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Purchase\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
#[Fillable([
|
||||
'compra_id',
|
||||
'cuit_buyer',
|
||||
'cvu_buyer',
|
||||
'amount',
|
||||
'concept',
|
||||
'operation',
|
||||
'operation_id',
|
||||
'transaction_id',
|
||||
'qr_order_id',
|
||||
'link_id',
|
||||
])]
|
||||
class TelepagosPayment extends Model
|
||||
{
|
||||
use HasFactory;
|
||||
|
||||
protected $table = 'telepagos_payments';
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'compra_id' => 'integer',
|
||||
'amount' => 'decimal:2',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return BelongsTo<Purchase, $this>
|
||||
*/
|
||||
public function compra(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Purchase::class, 'compra_id');
|
||||
}
|
||||
}
|
||||
35
app/Domains/Purchase/Models/TelepagosQr.php
Normal file
35
app/Domains/Purchase/Models/TelepagosQr.php
Normal file
@@ -0,0 +1,35 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Purchase\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
#[Fillable([
|
||||
'compra_id',
|
||||
'qr_order_id',
|
||||
'qr_code',
|
||||
])]
|
||||
class TelepagosQr extends Model
|
||||
{
|
||||
use HasFactory;
|
||||
|
||||
protected $table = 'telepagos_qr';
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'compra_id' => 'integer',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return BelongsTo<Purchase, $this>
|
||||
*/
|
||||
public function compra(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Purchase::class, 'compra_id');
|
||||
}
|
||||
}
|
||||
24
app/Domains/Purchase/Requests/PaymentIntentRequest.php
Normal file
24
app/Domains/Purchase/Requests/PaymentIntentRequest.php
Normal file
@@ -0,0 +1,24 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Purchase\Requests;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Validation\Rule;
|
||||
|
||||
class PaymentIntentRequest extends FormRequest
|
||||
{
|
||||
public function authorize(): bool
|
||||
{
|
||||
return $this->user() !== null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'method' => ['required', 'string', Rule::in(['qr', 'transfer'])],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,6 @@
|
||||
namespace App\Domains\Purchase\Requests;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Validation\Rule;
|
||||
|
||||
class StorePurchaseRequest extends FormRequest
|
||||
{
|
||||
@@ -18,16 +17,11 @@ class StorePurchaseRequest extends FormRequest
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'status' => ['sometimes', 'string', Rule::in(['pending', 'paid', 'cancelled'])],
|
||||
'payment_status' => ['sometimes', 'string', Rule::in(['pending', 'approved', 'rejected'])],
|
||||
'payment_method' => ['required', 'string'],
|
||||
'cart_id' => ['required', 'integer', 'exists:carritos,id'],
|
||||
'dni' => ['required', 'string'],
|
||||
'telefono' => ['required', 'string'],
|
||||
'nombre_apellido' => ['required', 'string'],
|
||||
'email' => ['required', 'string', 'email'],
|
||||
'items' => ['required', 'array', 'min:1'],
|
||||
'items.*.producto_variante_id' => ['required', 'integer', 'exists:productos_variantes,id'],
|
||||
'items.*.cantidad' => ['required', 'integer', 'min:1'],
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,22 +19,26 @@ class PurchaseResource extends JsonResource
|
||||
? $this->resource->getRelation('items')
|
||||
: collect();
|
||||
|
||||
$subtotal = $items->reduce(
|
||||
fn (float $carry, $item): float => $carry + ((float) $item->precio_unitario * $item->cantidad),
|
||||
0.0,
|
||||
);
|
||||
$subtotal = $items->isNotEmpty()
|
||||
? $items->reduce(
|
||||
fn (float $carry, $item): float => $carry + ((float) $item->precio_unitario * $item->cantidad),
|
||||
0.0,
|
||||
)
|
||||
: (float) ($this->total ?? 0);
|
||||
|
||||
$total = $items->reduce(
|
||||
fn (float $carry, $item): float => $carry + (float) $item->total,
|
||||
0.0,
|
||||
);
|
||||
$total = $items->isNotEmpty()
|
||||
? $items->reduce(
|
||||
fn (float $carry, $item): float => $carry + (float) $item->total,
|
||||
0.0,
|
||||
)
|
||||
: (float) ($this->total ?? 0);
|
||||
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'cart_id' => $this->cart_id,
|
||||
'tenant_codigo' => $this->tenant_codigo,
|
||||
'user_id' => $this->user_id,
|
||||
'status' => $this->status,
|
||||
'payment_status' => $this->payment_status,
|
||||
'payment_method' => $this->payment_method,
|
||||
'dni' => $this->dni,
|
||||
'telefono' => $this->telefono,
|
||||
|
||||
@@ -2,71 +2,154 @@
|
||||
|
||||
namespace App\Domains\Purchase\Services;
|
||||
|
||||
use App\Domains\Cart\Models\Cart;
|
||||
use App\Domains\Cart\Models\CartItem;
|
||||
use App\Domains\Catalog\Models\ProductVariant;
|
||||
use App\Domains\Purchase\Models\Purchase;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use Illuminate\Support\Collection;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
|
||||
|
||||
class CheckoutService
|
||||
{
|
||||
public function processCheckout(Tenant $tenant, int $userId, array $purchaseData): Purchase
|
||||
public function startCheckout(Tenant $tenant, int $userId, array $purchaseData): Purchase
|
||||
{
|
||||
// 1. Preparar items de la compra
|
||||
$items = $purchaseData['items'];
|
||||
unset($purchaseData['items']);
|
||||
$cartId = (int) $purchaseData['cart_id'];
|
||||
unset($purchaseData['cart_id']);
|
||||
|
||||
$variants = $this->resolveTenantVariants($tenant, $items);
|
||||
$purchaseItemsPayload = $this->buildPurchaseItemsPayload($items, $variants);
|
||||
return DB::transaction(function () use ($tenant, $userId, $purchaseData, $cartId): Purchase {
|
||||
$cart = $this->resolveCheckoutCart($tenant, $userId, $cartId);
|
||||
$cartItems = $cart->items()->lockForUpdate()->get();
|
||||
|
||||
// 2. Crear la orden de compra y vaciar carrito
|
||||
return DB::transaction(function () use ($tenant, $userId, $purchaseData, $purchaseItemsPayload): Purchase {
|
||||
/** @var Purchase $purchase */
|
||||
$purchase = Purchase::query()->create([
|
||||
...$purchaseData,
|
||||
'tenant_codigo' => $tenant->codigo,
|
||||
'user_id' => $userId,
|
||||
]);
|
||||
if ($cartItems->isEmpty()) {
|
||||
throw ValidationException::withMessages([
|
||||
'cart_id' => 'The selected cart does not contain items.',
|
||||
]);
|
||||
}
|
||||
|
||||
$purchase->items()->createMany($purchaseItemsPayload);
|
||||
$cartItems->load('variant.product');
|
||||
$cart->setRelation('items', $cartItems);
|
||||
$totalAmount = $cart->getTotalAmount();
|
||||
|
||||
// Vaciar y eliminar el carrito activo del usuario
|
||||
$cart = \App\Domains\Cart\Models\Cart::query()
|
||||
/** @var Purchase|null $purchase */
|
||||
$purchase = Purchase::query()
|
||||
->where('cart_id', $cart->getKey())
|
||||
->where('tenant_codigo', $tenant->codigo)
|
||||
->where('user_id', $userId)
|
||||
->whereIn('status', [Purchase::STATUS_CREATED, Purchase::STATUS_PENDING_PAYMENT])
|
||||
->latest('id')
|
||||
->first();
|
||||
if ($cart) {
|
||||
$cart->items()->delete();
|
||||
$cart->delete();
|
||||
|
||||
if ($purchase === null) {
|
||||
/** @var Purchase $purchase */
|
||||
$purchase = Purchase::query()->create([
|
||||
...$purchaseData,
|
||||
'cart_id' => $cart->getKey(),
|
||||
'tenant_codigo' => $tenant->codigo,
|
||||
'user_id' => $userId,
|
||||
'status' => Purchase::STATUS_CREATED,
|
||||
'payment_method' => null,
|
||||
'total' => $totalAmount,
|
||||
]);
|
||||
} else {
|
||||
$purchase->fill([
|
||||
...$purchaseData,
|
||||
'status' => Purchase::STATUS_CREATED,
|
||||
'payment_method' => null,
|
||||
'total' => $totalAmount,
|
||||
]);
|
||||
$purchase->save();
|
||||
}
|
||||
|
||||
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)
|
||||
public function completePurchase(Purchase $purchase): Purchase
|
||||
{
|
||||
$variantIds = collect($items)
|
||||
return DB::transaction(function () use ($purchase): Purchase {
|
||||
/** @var Purchase $purchase */
|
||||
$purchase = Purchase::query()
|
||||
->lockForUpdate()
|
||||
->findOrFail($purchase->getKey());
|
||||
|
||||
if ($purchase->payment_method === null) {
|
||||
throw ValidationException::withMessages([
|
||||
'payment_method' => 'The purchase payment method must be selected before finalizing.',
|
||||
]);
|
||||
}
|
||||
|
||||
if (in_array($purchase->status, [Purchase::STATUS_PAID, Purchase::STATUS_CANCELLED, Purchase::STATUS_REJECTED], true)) {
|
||||
return $purchase->load(['items.variant.product', 'items.variant.definitions.productAttribute.attribute']);
|
||||
}
|
||||
|
||||
$purchase->update([
|
||||
'status' => Purchase::STATUS_PENDING_PAYMENT,
|
||||
'total' => $purchase->calculateCurrentTotalAmount(),
|
||||
]);
|
||||
|
||||
return $purchase->load(['items.variant.product', 'items.variant.definitions.productAttribute.attribute']);
|
||||
});
|
||||
}
|
||||
|
||||
public function confirmPurchase(Purchase $purchase): void
|
||||
{
|
||||
DB::transaction(function () use ($purchase): void {
|
||||
/** @var Cart|null $cart */
|
||||
$cart = $purchase->cart()->lockForUpdate()->first();
|
||||
|
||||
if ($cart === null) {
|
||||
throw ValidationException::withMessages([
|
||||
'cart_id' => 'The purchase cart is no longer available.',
|
||||
]);
|
||||
}
|
||||
|
||||
$cartItems = $cart->items()->lockForUpdate()->get();
|
||||
|
||||
if ($cartItems->isEmpty()) {
|
||||
throw ValidationException::withMessages([
|
||||
'cart_id' => 'The purchase cart does not contain items.',
|
||||
]);
|
||||
}
|
||||
|
||||
if ($purchase->items()->exists()) {
|
||||
return;
|
||||
}
|
||||
|
||||
$cartItems->load('variant.product');
|
||||
$variants = $this->resolveTenantVariants($purchase->tenant, $cartItems);
|
||||
$purchaseItemsPayload = $this->buildPurchaseItemsPayload($cartItems, $variants);
|
||||
|
||||
$purchase->items()->createMany($purchaseItemsPayload);
|
||||
$this->completeCartConversion($cart, $cartItems, $variants);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Collection<int, ProductVariant>
|
||||
*/
|
||||
protected function resolveTenantVariants(Tenant $tenant, Collection $cartItems): Collection
|
||||
{
|
||||
$variantIds = $cartItems
|
||||
->pluck('producto_variante_id')
|
||||
->filter()
|
||||
->map(static fn (mixed $id): int => (int) $id)
|
||||
->unique()
|
||||
->values();
|
||||
|
||||
/** @var Collection<int, ProductVariant> $variants */
|
||||
$variants = ProductVariant::query()
|
||||
->with('product')
|
||||
->whereIn('id', $variantIds)
|
||||
->whereHas('product', fn ($query) => $query->where('tenant_codigo', $tenant->codigo))
|
||||
->lockForUpdate()
|
||||
->get()
|
||||
->keyBy('id');
|
||||
|
||||
if ($variants->count() !== $variantIds->count()) {
|
||||
throw ValidationException::withMessages([
|
||||
'items' => 'One or more product variants do not belong to the tenant.',
|
||||
'cart_id' => 'One or more product variants do not belong to the tenant.',
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -74,14 +157,38 @@ class CheckoutService
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, array<string, mixed>> $items
|
||||
* @param \Illuminate\Support\Collection<int, ProductVariant> $variants
|
||||
* @param Collection<int, CartItem> $cartItems
|
||||
* @return \Illuminate\Support\Collection<int, ProductVariant>
|
||||
*/
|
||||
protected function resolveCheckoutCart(Tenant $tenant, int $userId, int $cartId): Cart
|
||||
{
|
||||
/** @var Cart|null $cart */
|
||||
$cart = Cart::query()
|
||||
->lockForUpdate()
|
||||
->find($cartId);
|
||||
|
||||
if ($cart === null || $cart->tenant_codigo !== $tenant->codigo || $cart->user_id !== $userId) {
|
||||
throw new NotFoundHttpException('Cart not found for tenant.');
|
||||
}
|
||||
|
||||
if ($cart->status !== 'active') {
|
||||
throw ValidationException::withMessages([
|
||||
'cart_id' => 'The selected cart is no longer active.',
|
||||
]);
|
||||
}
|
||||
|
||||
return $cart;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Collection<int, CartItem> $cartItems
|
||||
* @param Collection<int, ProductVariant> $variants
|
||||
* @return array<int, array<string, mixed>>
|
||||
*/
|
||||
protected function buildPurchaseItemsPayload(array $items, $variants): array
|
||||
protected function buildPurchaseItemsPayload(Collection $cartItems, Collection $variants): array
|
||||
{
|
||||
return collect($items)
|
||||
->map(function (array $item) use ($variants): array {
|
||||
return $cartItems
|
||||
->map(function (CartItem $item) use ($variants): array {
|
||||
/** @var ProductVariant $variant */
|
||||
$variant = $variants->get((int) $item['producto_variante_id']);
|
||||
$quantity = (int) $item['cantidad'];
|
||||
@@ -98,4 +205,31 @@ class CheckoutService
|
||||
})
|
||||
->all();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Collection<int, CartItem> $cartItems
|
||||
* @param Collection<int, ProductVariant> $variants
|
||||
*/
|
||||
protected function completeCartConversion(Cart $cart, Collection $cartItems, Collection $variants): void
|
||||
{
|
||||
foreach ($cartItems as $item) {
|
||||
/** @var ProductVariant $variant */
|
||||
$variant = $variants->get((int) $item->producto_variante_id);
|
||||
$quantity = (int) $item->cantidad;
|
||||
|
||||
try {
|
||||
$variant->confirmReservedStock($quantity);
|
||||
} catch (\InvalidArgumentException $exception) {
|
||||
throw ValidationException::withMessages([
|
||||
'cart_id' => 'The selected cart has inconsistent stock state.',
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
$cart->status = 'converted';
|
||||
$cart->user_id = null;
|
||||
$cart->guest_token = null;
|
||||
$cart->save();
|
||||
$cart->delete();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,6 +3,8 @@
|
||||
use App\Domains\Purchase\Controllers\PurchaseController;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
|
||||
Route::prefix('tenants/{tenant:codigo}')->middleware('auth:sanctum')->group(function (): void {
|
||||
Route::prefix('tenants/{tenant:codigo}')->middleware(['auth:sanctum', \App\Domains\Cart\Middleware\MergeGuestCartMiddleware::class])->group(function (): void {
|
||||
Route::apiResource('compras', PurchaseController::class)->only(['index', 'store', 'show']);
|
||||
Route::post('compras/{compra}/payment-intent', [PurchaseController::class, 'paymentIntent']);
|
||||
Route::post('compras/{compra}/complete', [PurchaseController::class, 'complete']);
|
||||
});
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
namespace App\Domains\Tenant\Models;
|
||||
|
||||
use App\Domains\Attachable\Models\Attachment;
|
||||
use App\Domains\BankAccount\Models\BankAccount;
|
||||
use App\Domains\Catalog\Models\Product;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
@@ -49,28 +48,9 @@ class Tenant extends Model
|
||||
return $this->belongsTo(Attachment::class, 'footer_logo_id');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return HasMany<Product, $this>
|
||||
*/
|
||||
public function productos(): HasMany
|
||||
{
|
||||
return $this->hasMany(Product::class, 'tenant_codigo', 'codigo');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return HasMany<BankAccount, $this>
|
||||
*/
|
||||
public function bankAccounts(): HasMany
|
||||
{
|
||||
return $this->hasMany(BankAccount::class, 'tenant_code', 'codigo');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return BelongsTo<BankAccount, $this>
|
||||
*/
|
||||
public function selectedBankAccount(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(BankAccount::class, 'selected_bank_account_id');
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
/**
|
||||
* Run the migrations.
|
||||
*/
|
||||
public function up(): void
|
||||
{
|
||||
Schema::create('telepagos_payments', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->foreignId('compra_id')->constrained('compras')->onDelete('cascade');
|
||||
$table->string('cuit_buyer')->nullable();
|
||||
$table->string('cvu_buyer')->nullable();
|
||||
$table->decimal('amount', 10, 2);
|
||||
$table->string('concept')->nullable();
|
||||
$table->string('operation')->nullable();
|
||||
$table->string('operation_id')->nullable();
|
||||
$table->string('transaction_id')->nullable();
|
||||
$table->string('qr_order_id')->nullable();
|
||||
$table->string('link_id')->nullable();
|
||||
$table->timestamps();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Reverse the migrations.
|
||||
*/
|
||||
public function down(): void
|
||||
{
|
||||
Schema::dropIfExists('telepagos_payments');
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,30 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
/**
|
||||
* Run the migrations.
|
||||
*/
|
||||
public function up(): void
|
||||
{
|
||||
Schema::create('telepagos_qr', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->foreignId('compra_id')->constrained('compras')->onDelete('cascade');
|
||||
$table->string('qr_order_id');
|
||||
$table->text('qr_code');
|
||||
$table->timestamps();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Reverse the migrations.
|
||||
*/
|
||||
public function down(): void
|
||||
{
|
||||
Schema::dropIfExists('telepagos_qr');
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,33 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
/**
|
||||
* Run the migrations.
|
||||
*/
|
||||
public function up(): void
|
||||
{
|
||||
Schema::table('compras', function (Blueprint $table) {
|
||||
$table->foreignId('cart_id')
|
||||
->nullable()
|
||||
->after('user_id')
|
||||
->constrained('carritos')
|
||||
->cascadeOnUpdate()
|
||||
->nullOnDelete();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Reverse the migrations.
|
||||
*/
|
||||
public function down(): void
|
||||
{
|
||||
Schema::table('compras', function (Blueprint $table) {
|
||||
$table->dropConstrainedForeignId('cart_id');
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -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
|
||||
{
|
||||
/**
|
||||
* Run the migrations.
|
||||
*/
|
||||
public function up(): void
|
||||
{
|
||||
Schema::table('carritos', function (Blueprint $table) {
|
||||
$table->softDeletes();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Reverse the migrations.
|
||||
*/
|
||||
public function down(): void
|
||||
{
|
||||
Schema::table('carritos', function (Blueprint $table) {
|
||||
$table->dropSoftDeletes();
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,44 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
/**
|
||||
* Run the migrations.
|
||||
*/
|
||||
public function up(): void
|
||||
{
|
||||
Schema::table('tenants', function (Blueprint $table) {
|
||||
$table->dropForeign(['selected_bank_account_id']);
|
||||
$table->dropColumn('selected_bank_account_id');
|
||||
});
|
||||
|
||||
Schema::dropIfExists('bank_accounts');
|
||||
}
|
||||
|
||||
/**
|
||||
* Reverse the migrations.
|
||||
*/
|
||||
public function down(): void
|
||||
{
|
||||
Schema::create('bank_accounts', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->string('tenant_code');
|
||||
$table->string('titular');
|
||||
$table->string('entidad');
|
||||
$table->string('alias');
|
||||
$table->string('cvu');
|
||||
$table->timestamps();
|
||||
|
||||
$table->foreign('tenant_code')->references('codigo')->on('tenants')->onDelete('cascade');
|
||||
});
|
||||
|
||||
Schema::table('tenants', function (Blueprint $table) {
|
||||
$table->unsignedBigInteger('selected_bank_account_id')->nullable();
|
||||
$table->foreign('selected_bank_account_id')->references('id')->on('bank_accounts')->onDelete('set null');
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,59 @@
|
||||
<?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
|
||||
{
|
||||
/**
|
||||
* Run the migrations.
|
||||
*/
|
||||
public function up(): void
|
||||
{
|
||||
Schema::table('compras', function (Blueprint $table) {
|
||||
$table->decimal('total', 10, 2)->default(0)->after('payment_method');
|
||||
});
|
||||
|
||||
DB::table('compras')
|
||||
->orderBy('id')
|
||||
->chunkById(100, function ($compras): void {
|
||||
foreach ($compras as $compra) {
|
||||
$itemsQuery = DB::table('compra_items')
|
||||
->where('compra_id', $compra->id);
|
||||
$hasItems = $itemsQuery->exists();
|
||||
$itemsTotal = $itemsQuery->sum('total');
|
||||
|
||||
$total = (float) $itemsTotal;
|
||||
|
||||
if (! $hasItems && $compra->cart_id !== null) {
|
||||
$cartTotal = DB::table('carrito_items as carrito_item')
|
||||
->join('productos_variantes as variante', 'variante.id', '=', 'carrito_item.producto_variante_id')
|
||||
->join('productos as producto', 'producto.id', '=', 'variante.producto_id')
|
||||
->where('carrito_item.cart_id', $compra->cart_id)
|
||||
->selectRaw('COALESCE(SUM(producto.precio * carrito_item.cantidad), 0) as total')
|
||||
->value('total');
|
||||
|
||||
$total = (float) ($cartTotal ?? 0);
|
||||
}
|
||||
|
||||
DB::table('compras')
|
||||
->where('id', $compra->id)
|
||||
->update([
|
||||
'total' => number_format($total, 2, '.', ''),
|
||||
]);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Reverse the migrations.
|
||||
*/
|
||||
public function down(): void
|
||||
{
|
||||
Schema::table('compras', function (Blueprint $table) {
|
||||
$table->dropColumn('total');
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,83 @@
|
||||
<?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
|
||||
{
|
||||
/**
|
||||
* Run the migrations.
|
||||
*/
|
||||
public function up(): void
|
||||
{
|
||||
Schema::table('compras', function (Blueprint $table) {
|
||||
$table->string('status')->default('created')->change();
|
||||
});
|
||||
|
||||
if (Schema::hasColumn('compras', 'payment_status')) {
|
||||
DB::table('compras')
|
||||
->where('payment_status', 'approved')
|
||||
->update(['status' => 'paid']);
|
||||
|
||||
DB::table('compras')
|
||||
->where('payment_status', 'rejected')
|
||||
->where('status', '!=', 'cancelled')
|
||||
->update(['status' => 'rejected']);
|
||||
}
|
||||
|
||||
DB::table('compras')
|
||||
->where('status', 'pending')
|
||||
->whereNull('payment_method')
|
||||
->update(['status' => 'created']);
|
||||
|
||||
DB::table('compras')
|
||||
->where('status', 'pending')
|
||||
->whereNotNull('payment_method')
|
||||
->update(['status' => 'pending_payment']);
|
||||
|
||||
if (Schema::hasColumn('compras', 'payment_status')) {
|
||||
Schema::table('compras', function (Blueprint $table) {
|
||||
$table->dropColumn('payment_status');
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Reverse the migrations.
|
||||
*/
|
||||
public function down(): void
|
||||
{
|
||||
if (! Schema::hasColumn('compras', 'payment_status')) {
|
||||
Schema::table('compras', function (Blueprint $table) {
|
||||
$table->string('payment_status')->default('pending')->after('status');
|
||||
});
|
||||
}
|
||||
|
||||
DB::table('compras')
|
||||
->where('status', 'paid')
|
||||
->update([
|
||||
'status' => 'paid',
|
||||
'payment_status' => 'approved',
|
||||
]);
|
||||
|
||||
DB::table('compras')
|
||||
->where('status', 'rejected')
|
||||
->update([
|
||||
'status' => 'pending',
|
||||
'payment_status' => 'rejected',
|
||||
]);
|
||||
|
||||
DB::table('compras')
|
||||
->whereIn('status', ['created', 'pending_payment'])
|
||||
->update([
|
||||
'status' => 'pending',
|
||||
'payment_status' => 'pending',
|
||||
]);
|
||||
|
||||
Schema::table('compras', function (Blueprint $table) {
|
||||
$table->string('status')->default('pending')->change();
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -85,32 +85,5 @@ class TenantSeeder extends Seeder
|
||||
'header_logo' => $headerLogo,
|
||||
'footer_logo' => $footerLogo,
|
||||
]);
|
||||
|
||||
$bankAccount1 = \App\Domains\BankAccount\Models\BankAccount::query()->create([
|
||||
'tenant_code' => $tenant->codigo,
|
||||
'titular' => 'Sonder S.A. (Principal)',
|
||||
'entidad' => 'Banco de la Nación Argentina',
|
||||
'alias' => 'sonder.indumentaria',
|
||||
'cvu' => '0110065420006540987654',
|
||||
]);
|
||||
|
||||
\App\Domains\BankAccount\Models\BankAccount::query()->create([
|
||||
'tenant_code' => $tenant->codigo,
|
||||
'titular' => 'Sonder S.A. (Secundaria)',
|
||||
'entidad' => 'Banco de Galicia y Buenos Aires',
|
||||
'alias' => 'sonder.indumentaria.galicia',
|
||||
'cvu' => '0070012345678901234567',
|
||||
]);
|
||||
|
||||
\App\Domains\BankAccount\Models\BankAccount::query()->create([
|
||||
'tenant_code' => $tenant->codigo,
|
||||
'titular' => 'Sonder S.A. (Mercado Pago)',
|
||||
'entidad' => 'Mercado Pago',
|
||||
'alias' => 'sonder.indumentaria.mp',
|
||||
'cvu' => '0000003100012345678901',
|
||||
]);
|
||||
|
||||
$tenant->selected_bank_account_id = $bankAccount1->id;
|
||||
$tenant->save();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,12 +20,14 @@
|
||||
<php>
|
||||
<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"/>
|
||||
<env name="APP_PACKAGES_CACHE" value="bootstrap/cache/phpunit-packages.php"/>
|
||||
<env name="APP_ROUTES_CACHE" value="bootstrap/cache/phpunit-routes.php"/>
|
||||
<env name="APP_SERVICES_CACHE" value="bootstrap/cache/phpunit-services.php"/>
|
||||
<env name="BCRYPT_ROUNDS" value="4"/>
|
||||
<env name="BROADCAST_CONNECTION" value="null"/>
|
||||
<env name="CACHE_STORE" value="array"/>
|
||||
<env name="DB_CONNECTION" value="sqlite"/>
|
||||
<env name="DB_DATABASE" value=":memory:"/>
|
||||
<env name="DB_URL" value=""/>
|
||||
<env name="MAIL_MAILER" value="array"/>
|
||||
<env name="QUEUE_CONNECTION" value="sync"/>
|
||||
<env name="SESSION_DRIVER" value="array"/>
|
||||
|
||||
@@ -9,5 +9,4 @@ require __DIR__.'/../app/Domains/Cart/routes/api.php';
|
||||
require __DIR__.'/../app/Domains/StorageTest/routes/api.php';
|
||||
require __DIR__.'/../app/Domains/Purchase/routes/api.php';
|
||||
require __DIR__.'/../app/Domains/Tenant/routes/api.php';
|
||||
require __DIR__.'/../app/Domains/BankAccount/routes/api.php';
|
||||
require __DIR__.'/../app/Domains/Integration/routes/api.php';
|
||||
|
||||
525
tests/Feature/Integration/IntegrationServiceTest.php
Normal file
525
tests/Feature/Integration/IntegrationServiceTest.php
Normal file
@@ -0,0 +1,525 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Integration;
|
||||
|
||||
use App\Domains\Integration\Models\Integration;
|
||||
use App\Domains\Integration\Models\TenantIntegration;
|
||||
use App\Domains\Integration\Services\TelepagosIntegrationService;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Tests\TestCase;
|
||||
use Exception;
|
||||
|
||||
class IntegrationServiceTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private Tenant $tenant;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
// Set the integrations secret for tests
|
||||
config(['services.integrations.secret' => 'base64:' . base64_encode(random_bytes(32))]);
|
||||
|
||||
// Clear cache to prevent test pollution
|
||||
Cache::flush();
|
||||
|
||||
$hdrKey = (string) \Illuminate\Support\Str::uuid();
|
||||
$ftrKey = (string) \Illuminate\Support\Str::uuid();
|
||||
|
||||
$headerAttachment = \App\Domains\Attachable\Models\Attachment::create([
|
||||
'key' => $hdrKey,
|
||||
'path' => 'tenants/' . $hdrKey . '.png',
|
||||
'filename' => 'logo_header.png',
|
||||
'type' => \App\Domains\Attachable\Enums\AttachmentType::Image,
|
||||
'mime_type' => 'image/png',
|
||||
]);
|
||||
$footerAttachment = \App\Domains\Attachable\Models\Attachment::create([
|
||||
'key' => $ftrKey,
|
||||
'path' => 'tenants/' . $ftrKey . '.png',
|
||||
'filename' => 'logo_footer.png',
|
||||
'type' => \App\Domains\Attachable\Enums\AttachmentType::Image,
|
||||
'mime_type' => 'image/png',
|
||||
]);
|
||||
|
||||
// Create a test tenant
|
||||
$this->tenant = Tenant::create([
|
||||
'codigo' => 'test-tenant',
|
||||
'nombre' => 'Test Tenant',
|
||||
'dominio' => 'test.com',
|
||||
'primary_color' => '#ffffff',
|
||||
'secondary_color' => '#ffffff',
|
||||
'danger_color' => '#ffffff',
|
||||
'success_color' => '#ffffff',
|
||||
'header_bg_color' => '#ffffff',
|
||||
'footer_bg_color' => '#ffffff',
|
||||
'header_logo_id' => $headerAttachment->id,
|
||||
'footer_logo_id' => $footerAttachment->id,
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_it_throws_exception_if_integration_code_is_invalid(): void
|
||||
{
|
||||
$service = new TelepagosIntegrationService('invalid_code');
|
||||
|
||||
$this->expectException(Exception::class);
|
||||
$this->expectExceptionMessage("Integration with code 'invalid_code' not found.");
|
||||
|
||||
$service->forTenant($this->tenant->codigo);
|
||||
}
|
||||
|
||||
public function test_it_throws_exception_if_tenant_integration_is_not_configured(): void
|
||||
{
|
||||
// Seed integration but don't configure for tenant
|
||||
Integration::create([
|
||||
'integration_code' => 'telepagos_homo',
|
||||
'name' => 'Telepagos',
|
||||
'url' => 'https://api.telepagos.com.ar',
|
||||
'integration_data_schema' => [
|
||||
'username' => 'required|string',
|
||||
'password' => 'required|string',
|
||||
]
|
||||
]);
|
||||
|
||||
$service = new TelepagosIntegrationService('telepagos');
|
||||
|
||||
$this->expectException(Exception::class);
|
||||
$this->expectExceptionMessage("Tenant 'test-tenant' does not have integration 'telepagos_homo' configured.");
|
||||
|
||||
$service->forTenant($this->tenant->codigo);
|
||||
}
|
||||
|
||||
public function test_it_resolves_base_url_and_paths(): void
|
||||
{
|
||||
Integration::create([
|
||||
'integration_code' => 'telepagos_homo',
|
||||
'name' => 'Telepagos',
|
||||
'url' => 'https://api.telepagos.com.ar/', // Trailing slash to test trimming
|
||||
'integration_data_schema' => [
|
||||
'username' => 'required|string',
|
||||
'password' => 'required|string',
|
||||
]
|
||||
]);
|
||||
|
||||
TenantIntegration::create([
|
||||
'tenant_code' => $this->tenant->codigo,
|
||||
'integration_code' => 'telepagos_homo',
|
||||
'integration_data' => [
|
||||
'username' => 'user123',
|
||||
'password' => 'pass123',
|
||||
]
|
||||
]);
|
||||
|
||||
$service = new TelepagosIntegrationService('telepagos');
|
||||
$service->forTenant($this->tenant->codigo);
|
||||
|
||||
$this->assertEquals('https://api.telepagos.com.ar', $service->getUrl());
|
||||
$this->assertEquals('https://api.telepagos.com.ar/v1/payments', $service->getUrl('v1/payments'));
|
||||
$this->assertEquals('https://api.telepagos.com.ar/v1/payments', $service->getUrl('/v1/payments'));
|
||||
}
|
||||
|
||||
public function test_it_generates_correct_headers_for_telepagos_using_cached_token(): void
|
||||
{
|
||||
Integration::create([
|
||||
'integration_code' => 'telepagos_homo',
|
||||
'name' => 'Telepagos',
|
||||
'url' => 'https://api.telepagos.com.ar',
|
||||
'integration_data_schema' => [
|
||||
'username' => 'required|string',
|
||||
'password' => 'required|string',
|
||||
]
|
||||
]);
|
||||
|
||||
TenantIntegration::create([
|
||||
'tenant_code' => $this->tenant->codigo,
|
||||
'integration_code' => 'telepagos_homo',
|
||||
'integration_data' => [
|
||||
'username' => 'tele_user',
|
||||
'password' => 'tele_pass',
|
||||
]
|
||||
]);
|
||||
|
||||
// Mock HTTP response sequence for authentication
|
||||
Http::fake([
|
||||
'https://api.telepagos.com.ar/v2/auth/token' => Http::sequence()
|
||||
->push([
|
||||
'status' => 'ok',
|
||||
'token' => 'mock-jwt-token-123',
|
||||
'expires_at' => now()->addHour()->toDateTimeString()
|
||||
], 200)
|
||||
->push([
|
||||
'status' => 'ok',
|
||||
'token' => 'new-mock-jwt-token',
|
||||
'expires_at' => now()->addHour()->toDateTimeString()
|
||||
], 200)
|
||||
]);
|
||||
|
||||
$service = new TelepagosIntegrationService('telepagos');
|
||||
$service->forTenant($this->tenant->codigo);
|
||||
|
||||
// Fetch headers first time (triggers API login)
|
||||
$headers = $service->getHeaders();
|
||||
|
||||
$this->assertEquals('Bearer mock-jwt-token-123', $headers['Authorization']);
|
||||
$this->assertEquals('application/json', $headers['Content-Type']);
|
||||
$this->assertEquals('application/json', $headers['Accept']);
|
||||
|
||||
// Assert HTTP call was made once
|
||||
Http::assertSentCount(1);
|
||||
|
||||
// Retrieve token again, should be same (cached)
|
||||
$this->assertEquals('mock-jwt-token-123', $service->getToken());
|
||||
Http::assertSentCount(1); // Still 1 since it's cached!
|
||||
|
||||
// Clear token, should trigger another API login (sequence returns second token)
|
||||
$service->clearToken();
|
||||
$this->assertEquals('new-mock-jwt-token', $service->getToken());
|
||||
Http::assertSentCount(2);
|
||||
}
|
||||
|
||||
public function test_it_throws_exception_if_credentials_are_missing(): void
|
||||
{
|
||||
Integration::create([
|
||||
'integration_code' => 'telepagos_homo',
|
||||
'name' => 'Telepagos',
|
||||
'url' => 'https://api.telepagos.com.ar',
|
||||
'integration_data_schema' => [
|
||||
'username' => 'required|string',
|
||||
'password' => 'required|string',
|
||||
]
|
||||
]);
|
||||
|
||||
TenantIntegration::create([
|
||||
'tenant_code' => $this->tenant->codigo,
|
||||
'integration_code' => 'telepagos_homo',
|
||||
'integration_data' => [
|
||||
'username' => '',
|
||||
'password' => 'tele_pass',
|
||||
]
|
||||
]);
|
||||
|
||||
$service = new TelepagosIntegrationService('telepagos');
|
||||
$service->forTenant($this->tenant->codigo);
|
||||
|
||||
$this->expectException(Exception::class);
|
||||
$this->expectExceptionMessage("Missing username or password in Telepagos integration settings.");
|
||||
|
||||
$service->getToken();
|
||||
}
|
||||
|
||||
public function test_it_throws_exception_if_api_fails(): void
|
||||
{
|
||||
Integration::create([
|
||||
'integration_code' => 'telepagos_homo',
|
||||
'name' => 'Telepagos',
|
||||
'url' => 'https://api.telepagos.com.ar',
|
||||
'integration_data_schema' => [
|
||||
'username' => 'required|string',
|
||||
'password' => 'required|string',
|
||||
]
|
||||
]);
|
||||
|
||||
TenantIntegration::create([
|
||||
'tenant_code' => $this->tenant->codigo,
|
||||
'integration_code' => 'telepagos_homo',
|
||||
'integration_data' => [
|
||||
'username' => 'tele_user',
|
||||
'password' => 'tele_pass',
|
||||
]
|
||||
]);
|
||||
|
||||
Http::fake([
|
||||
'https://api.telepagos.com.ar/v2/auth/token' => Http::response([
|
||||
'status' => 'error',
|
||||
'message' => 'Invalid credentials'
|
||||
], 401)
|
||||
]);
|
||||
|
||||
\Illuminate\Support\Facades\Log::shouldReceive('error')
|
||||
->once()
|
||||
->with('Telepagos authentication failed: Invalid credentials', \Mockery::on(function ($context) {
|
||||
return $context['username'] === 'tele_user'
|
||||
&& $context['response_status'] === 401
|
||||
&& $context['response_body'] === ['status' => 'error', 'message' => 'Invalid credentials'];
|
||||
}));
|
||||
|
||||
$service = new TelepagosIntegrationService('telepagos');
|
||||
$service->forTenant($this->tenant->codigo);
|
||||
|
||||
$this->expectException(Exception::class);
|
||||
$this->expectExceptionMessage("Telepagos authentication failed: Invalid credentials");
|
||||
|
||||
$service->getToken();
|
||||
}
|
||||
|
||||
public function test_it_returns_preconfigured_client(): void
|
||||
{
|
||||
Integration::create([
|
||||
'integration_code' => 'telepagos_homo',
|
||||
'name' => 'Telepagos',
|
||||
'url' => 'https://api.telepagos.com.ar',
|
||||
'integration_data_schema' => [
|
||||
'username' => 'required|string',
|
||||
'password' => 'required|string',
|
||||
]
|
||||
]);
|
||||
|
||||
TenantIntegration::create([
|
||||
'tenant_code' => $this->tenant->codigo,
|
||||
'integration_code' => 'telepagos_homo',
|
||||
'integration_data' => [
|
||||
'username' => 'tele_user',
|
||||
'password' => 'tele_pass',
|
||||
]
|
||||
]);
|
||||
|
||||
Http::fake([
|
||||
'https://api.telepagos.com.ar/v2/auth/token' => Http::response([
|
||||
'status' => 'ok',
|
||||
'token' => 'mock-jwt-token-123',
|
||||
'expires_at' => now()->addHour()->toDateTimeString()
|
||||
], 200),
|
||||
'https://api.telepagos.com.ar/v1/payments' => Http::response([
|
||||
'status' => 'success',
|
||||
'payment_id' => 999
|
||||
], 200)
|
||||
]);
|
||||
|
||||
$service = new TelepagosIntegrationService('telepagos');
|
||||
$service->forTenant($this->tenant->codigo);
|
||||
|
||||
// Get configured client and perform GET request
|
||||
$client = $service->client();
|
||||
$this->assertInstanceOf(\Illuminate\Http\Client\PendingRequest::class, $client);
|
||||
|
||||
$response = $client->get('/v1/payments');
|
||||
|
||||
$this->assertTrue($response->successful());
|
||||
$this->assertEquals(999, $response->json('payment_id'));
|
||||
|
||||
// Assert the authorization header was correctly set during request
|
||||
Http::assertSent(function ($request) {
|
||||
return $request->hasHeader('Authorization', 'Bearer mock-jwt-token-123')
|
||||
&& $request->url() === 'https://api.telepagos.com.ar/v1/payments';
|
||||
});
|
||||
}
|
||||
|
||||
public function test_it_generates_qr_code(): void
|
||||
{
|
||||
Integration::create([
|
||||
'integration_code' => 'telepagos_homo',
|
||||
'name' => 'Telepagos',
|
||||
'url' => 'https://api.telepagos.com.ar',
|
||||
'integration_data_schema' => [
|
||||
'username' => 'required|string',
|
||||
'password' => 'required|string',
|
||||
]
|
||||
]);
|
||||
|
||||
TenantIntegration::create([
|
||||
'tenant_code' => $this->tenant->codigo,
|
||||
'integration_code' => 'telepagos_homo',
|
||||
'integration_data' => [
|
||||
'username' => 'tele_user',
|
||||
'password' => 'tele_pass',
|
||||
]
|
||||
]);
|
||||
|
||||
Http::fake([
|
||||
'https://api.telepagos.com.ar/v2/auth/token' => Http::response([
|
||||
'status' => 'ok',
|
||||
'token' => 'mock-jwt-token-123',
|
||||
'expires_at' => now()->addHour()->toDateTimeString()
|
||||
], 200),
|
||||
'https://api.telepagos.com.ar/v2/payment/cashin/qr/generate' => Http::response([
|
||||
'status' => 'ok',
|
||||
'qr_code' => 'mock-qr-code-data',
|
||||
'qr_order_id' => 6353
|
||||
], 200)
|
||||
]);
|
||||
|
||||
$service = new TelepagosIntegrationService('telepagos');
|
||||
$service->forTenant($this->tenant->codigo);
|
||||
|
||||
$result = $service->generateQr(1200.00, 'Test Concept', 'Test Description');
|
||||
|
||||
$this->assertEquals('ok', $result['status']);
|
||||
$this->assertEquals('mock-qr-code-data', $result['qr_code']);
|
||||
$this->assertEquals(6353, $result['qr_order_id']);
|
||||
|
||||
Http::assertSent(function ($request) {
|
||||
return $request->hasHeader('Authorization', 'Bearer mock-jwt-token-123')
|
||||
&& $request->url() === 'https://api.telepagos.com.ar/v2/payment/cashin/qr/generate'
|
||||
&& $request['amount'] === 1200.00
|
||||
&& $request['concept'] === 'Test Concept'
|
||||
&& $request['description'] === 'Test Description';
|
||||
});
|
||||
}
|
||||
|
||||
public function test_it_logs_and_throws_exception_on_generate_qr_error(): void
|
||||
{
|
||||
Integration::create([
|
||||
'integration_code' => 'telepagos_homo',
|
||||
'name' => 'Telepagos',
|
||||
'url' => 'https://api.telepagos.com.ar',
|
||||
'integration_data_schema' => [
|
||||
'username' => 'required|string',
|
||||
'password' => 'required|string',
|
||||
]
|
||||
]);
|
||||
|
||||
TenantIntegration::create([
|
||||
'tenant_code' => $this->tenant->codigo,
|
||||
'integration_code' => 'telepagos_homo',
|
||||
'integration_data' => [
|
||||
'username' => 'tele_user',
|
||||
'password' => 'tele_pass',
|
||||
]
|
||||
]);
|
||||
|
||||
Http::fake([
|
||||
'https://api.telepagos.com.ar/v2/auth/token' => Http::response([
|
||||
'status' => 'ok',
|
||||
'token' => 'mock-jwt-token-123',
|
||||
'expires_at' => now()->addHour()->toDateTimeString()
|
||||
], 200),
|
||||
'https://api.telepagos.com.ar/v2/payment/cashin/qr/generate' => Http::response([
|
||||
'status' => 'error',
|
||||
'message' => 'Importe inválido'
|
||||
], 422)
|
||||
]);
|
||||
|
||||
\Illuminate\Support\Facades\Log::shouldReceive('error')
|
||||
->once()
|
||||
->with('Telepagos QR generation failed: Importe inválido', \Mockery::on(function ($context) {
|
||||
return $context['amount'] === 1200.00
|
||||
&& $context['concept'] === 'Test Concept'
|
||||
&& $context['description'] === 'Test Description'
|
||||
&& $context['response_status'] === 422
|
||||
&& $context['response_body'] === ['status' => 'error', 'message' => 'Importe inválido'];
|
||||
}));
|
||||
|
||||
$service = new TelepagosIntegrationService('telepagos');
|
||||
$service->forTenant($this->tenant->codigo);
|
||||
|
||||
$this->expectException(Exception::class);
|
||||
$this->expectExceptionMessage("Telepagos QR generation failed: Importe inválido");
|
||||
|
||||
$service->generateQr(1200.00, 'Test Concept', 'Test Description');
|
||||
}
|
||||
|
||||
public function test_it_gets_cashin_details(): void
|
||||
{
|
||||
Integration::create([
|
||||
'integration_code' => 'telepagos_homo',
|
||||
'name' => 'Telepagos',
|
||||
'url' => 'https://api.telepagos.com.ar',
|
||||
'integration_data_schema' => [
|
||||
'username' => 'required|string',
|
||||
'password' => 'required|string',
|
||||
]
|
||||
]);
|
||||
|
||||
TenantIntegration::create([
|
||||
'tenant_code' => $this->tenant->codigo,
|
||||
'integration_code' => 'telepagos_homo',
|
||||
'integration_data' => [
|
||||
'username' => 'tele_user',
|
||||
'password' => 'tele_pass',
|
||||
]
|
||||
]);
|
||||
|
||||
Http::fake([
|
||||
'https://api.telepagos.com.ar/v2/auth/token' => Http::response([
|
||||
'status' => 'ok',
|
||||
'token' => 'mock-jwt-token-123',
|
||||
'expires_at' => now()->addHour()->toDateTimeString()
|
||||
], 200),
|
||||
'https://api.telepagos.com.ar/v2/payment/cashin/6351' => Http::response([
|
||||
'status' => 'ok',
|
||||
'buyer' => [
|
||||
'cuit' => '20416561398',
|
||||
'cvu' => '0000124900000000011974'
|
||||
],
|
||||
'amount' => 1200,
|
||||
'concept' => 'VAR',
|
||||
'operation' => 'QR Telepagos',
|
||||
'operation_id' => 37,
|
||||
'description' => 'Pago prueba',
|
||||
'transaction_id' => '2026070364',
|
||||
'qr_order_id' => 6351,
|
||||
'link_id' => null
|
||||
], 200)
|
||||
]);
|
||||
|
||||
$service = new TelepagosIntegrationService('telepagos');
|
||||
$service->forTenant($this->tenant->codigo);
|
||||
|
||||
$result = $service->getCashinDetails(6351);
|
||||
|
||||
$this->assertEquals('ok', $result['status']);
|
||||
$this->assertEquals(1200, $result['amount']);
|
||||
$this->assertEquals('VAR', $result['concept']);
|
||||
$this->assertEquals(6351, $result['qr_order_id']);
|
||||
|
||||
Http::assertSent(function ($request) {
|
||||
return $request->hasHeader('Authorization', 'Bearer mock-jwt-token-123')
|
||||
&& $request->url() === 'https://api.telepagos.com.ar/v2/payment/cashin/6351'
|
||||
&& $request->method() === 'GET';
|
||||
});
|
||||
}
|
||||
|
||||
public function test_it_logs_and_throws_exception_on_get_cashin_details_error(): void
|
||||
{
|
||||
Integration::create([
|
||||
'integration_code' => 'telepagos_homo',
|
||||
'name' => 'Telepagos',
|
||||
'url' => 'https://api.telepagos.com.ar',
|
||||
'integration_data_schema' => [
|
||||
'username' => 'required|string',
|
||||
'password' => 'required|string',
|
||||
]
|
||||
]);
|
||||
|
||||
TenantIntegration::create([
|
||||
'tenant_code' => $this->tenant->codigo,
|
||||
'integration_code' => 'telepagos_homo',
|
||||
'integration_data' => [
|
||||
'username' => 'tele_user',
|
||||
'password' => 'tele_pass',
|
||||
]
|
||||
]);
|
||||
|
||||
Http::fake([
|
||||
'https://api.telepagos.com.ar/v2/auth/token' => Http::response([
|
||||
'status' => 'ok',
|
||||
'token' => 'mock-jwt-token-123',
|
||||
'expires_at' => now()->addHour()->toDateTimeString()
|
||||
], 200),
|
||||
'https://api.telepagos.com.ar/v2/payment/cashin/6351' => Http::response([
|
||||
'status' => 'error',
|
||||
'message' => 'Cashin no encontrado'
|
||||
], 404)
|
||||
]);
|
||||
|
||||
\Illuminate\Support\Facades\Log::shouldReceive('error')
|
||||
->once()
|
||||
->with('Telepagos get cash-in details failed: Cashin no encontrado', \Mockery::on(function ($context) {
|
||||
return $context['cashin_id'] === 6351
|
||||
&& $context['response_status'] === 404
|
||||
&& $context['response_body'] === ['status' => 'error', 'message' => 'Cashin no encontrado'];
|
||||
}));
|
||||
|
||||
$service = new TelepagosIntegrationService('telepagos');
|
||||
$service->forTenant($this->tenant->codigo);
|
||||
|
||||
$this->expectException(Exception::class);
|
||||
$this->expectExceptionMessage("Telepagos get cash-in details failed: Cashin no encontrado");
|
||||
|
||||
$service->getCashinDetails(6351);
|
||||
}
|
||||
}
|
||||
246
tests/Feature/Integration/TelepagosWebhookTest.php
Normal file
246
tests/Feature/Integration/TelepagosWebhookTest.php
Normal file
@@ -0,0 +1,246 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Integration;
|
||||
|
||||
use App\Domains\Auth\Models\User;
|
||||
use App\Domains\Cart\Models\Cart;
|
||||
use App\Domains\Catalog\Models\Product;
|
||||
use App\Domains\Catalog\Models\ProductVariant;
|
||||
use App\Domains\Integration\Models\Integration;
|
||||
use App\Domains\Integration\Models\TenantIntegration;
|
||||
use App\Domains\Purchase\Models\Purchase;
|
||||
use App\Domains\Purchase\Services\CheckoutService;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Tests\TestCase;
|
||||
|
||||
class TelepagosWebhookTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
config(['services.integrations.secret' => 'base64:' . base64_encode(random_bytes(32))]);
|
||||
Cache::flush();
|
||||
}
|
||||
|
||||
public function test_transfer_webhook_matches_pending_purchase_by_dni_and_total_amount(): void
|
||||
{
|
||||
$tenant = $this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
|
||||
$this->configureTelepagosIntegration($tenant);
|
||||
|
||||
$matchingUser = User::factory()->create([
|
||||
'email' => 'buyer@example.com',
|
||||
]);
|
||||
$newerUser = User::factory()->create([
|
||||
'email' => 'buyer-2@example.com',
|
||||
]);
|
||||
|
||||
$variant = $this->createVariantForTenant('sonder', 10, '50.00');
|
||||
|
||||
$matchingPurchase = $this->createPendingTransferPurchase(
|
||||
$tenant,
|
||||
$matchingUser->id,
|
||||
$variant->id,
|
||||
1,
|
||||
'12345678'
|
||||
);
|
||||
|
||||
$newerPurchase = $this->createPendingTransferPurchase(
|
||||
$tenant,
|
||||
$newerUser->id,
|
||||
$variant->id,
|
||||
2,
|
||||
'12345678'
|
||||
);
|
||||
|
||||
Http::fake([
|
||||
'https://api.telepagos.com.ar/v2/auth/token' => Http::response([
|
||||
'status' => 'ok',
|
||||
'token' => 'test-token',
|
||||
'expires_at' => now()->addHour()->toIso8601String(),
|
||||
]),
|
||||
'https://api.telepagos.com.ar/v2/payment/cashin/6351' => Http::response([
|
||||
'status' => 'ok',
|
||||
'data' => [
|
||||
'amount' => 50,
|
||||
'operation_id' => 1,
|
||||
'transaction_id' => 'tx-123',
|
||||
'buyer' => [
|
||||
'cuit' => '20123456789',
|
||||
],
|
||||
],
|
||||
]),
|
||||
]);
|
||||
|
||||
$this->postJson('/api/webhooks/telepagos/sonder', [
|
||||
'id' => '6351',
|
||||
])->assertOk()->assertJsonPath('status', 'success');
|
||||
|
||||
$this->assertDatabaseHas('compras', [
|
||||
'id' => $matchingPurchase->id,
|
||||
'status' => Purchase::STATUS_PAID,
|
||||
'payment_method' => 'transfer',
|
||||
'total' => 50,
|
||||
]);
|
||||
|
||||
$this->assertDatabaseHas('compras', [
|
||||
'id' => $newerPurchase->id,
|
||||
'status' => Purchase::STATUS_PENDING_PAYMENT,
|
||||
'payment_method' => 'transfer',
|
||||
'total' => 100,
|
||||
]);
|
||||
|
||||
$this->assertDatabaseHas('telepagos_payments', [
|
||||
'compra_id' => $matchingPurchase->id,
|
||||
'amount' => 50,
|
||||
'operation_id' => 1,
|
||||
'transaction_id' => 'tx-123',
|
||||
]);
|
||||
|
||||
$this->assertDatabaseMissing('telepagos_payments', [
|
||||
'compra_id' => $newerPurchase->id,
|
||||
]);
|
||||
|
||||
$this->assertDatabaseHas('compra_items', [
|
||||
'compra_id' => $matchingPurchase->id,
|
||||
'producto_variante_id' => $variant->id,
|
||||
'cantidad' => 1,
|
||||
'total' => 50,
|
||||
]);
|
||||
|
||||
$this->assertDatabaseMissing('compra_items', [
|
||||
'compra_id' => $newerPurchase->id,
|
||||
]);
|
||||
|
||||
$this->assertSoftDeleted('carritos', [
|
||||
'id' => $matchingPurchase->cart_id,
|
||||
]);
|
||||
}
|
||||
|
||||
private function createPendingTransferPurchase(
|
||||
Tenant $tenant,
|
||||
int $userId,
|
||||
int $variantId,
|
||||
int $quantity,
|
||||
string $dni,
|
||||
): Purchase {
|
||||
$cart = Cart::query()->create([
|
||||
'tenant_codigo' => $tenant->codigo,
|
||||
'user_id' => $userId,
|
||||
'status' => 'active',
|
||||
]);
|
||||
|
||||
$cart->addItem($variantId, $quantity);
|
||||
|
||||
/** @var CheckoutService $checkoutService */
|
||||
$checkoutService = app(CheckoutService::class);
|
||||
|
||||
$purchase = $checkoutService->startCheckout($tenant, $userId, [
|
||||
'cart_id' => $cart->id,
|
||||
'dni' => $dni,
|
||||
'telefono' => '+54 9 341 555-4321',
|
||||
'nombre_apellido' => 'Juan Perez',
|
||||
'email' => 'juan.perez@example.com',
|
||||
]);
|
||||
|
||||
$purchase->update([
|
||||
'payment_method' => 'transfer',
|
||||
]);
|
||||
|
||||
$checkoutService->completePurchase($purchase);
|
||||
|
||||
return $purchase->fresh();
|
||||
}
|
||||
|
||||
private function configureTelepagosIntegration(Tenant $tenant): void
|
||||
{
|
||||
Integration::create([
|
||||
'integration_code' => 'telepagos_homo',
|
||||
'name' => 'Telepagos',
|
||||
'url' => 'https://api.telepagos.com.ar',
|
||||
'integration_data_schema' => [
|
||||
'username' => 'required|string',
|
||||
'password' => 'required|string',
|
||||
],
|
||||
]);
|
||||
|
||||
TenantIntegration::create([
|
||||
'tenant_code' => $tenant->codigo,
|
||||
'integration_code' => 'telepagos_homo',
|
||||
'integration_data' => [
|
||||
'username' => 'user123',
|
||||
'password' => 'pass123',
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
private function createVariantForTenant(
|
||||
string $tenantCode,
|
||||
int $stock,
|
||||
string $price,
|
||||
string $slugPrefix = 'shirt',
|
||||
): ProductVariant {
|
||||
$category = \App\Domains\Catalog\Models\Category::query()->create([
|
||||
'tenant_code' => $tenantCode,
|
||||
'nombre' => "{$slugPrefix} category {$tenantCode}",
|
||||
]);
|
||||
|
||||
$product = Product::query()->create([
|
||||
'tenant_codigo' => $tenantCode,
|
||||
'categoria_id' => $category->id,
|
||||
'slug' => "{$slugPrefix}-{$tenantCode}-".Product::query()->count(),
|
||||
'nombre' => ucfirst($slugPrefix)." {$tenantCode}",
|
||||
'descripcion' => 'Test product',
|
||||
'precio' => $price,
|
||||
]);
|
||||
|
||||
return ProductVariant::query()->create([
|
||||
'producto_id' => $product->id,
|
||||
'slug' => "{$slugPrefix}-variant-".ProductVariant::query()->count(),
|
||||
'nombre' => ucfirst($slugPrefix).' Variant',
|
||||
'stock' => $stock,
|
||||
'descripcion' => 'Test variant',
|
||||
'precio' => $price,
|
||||
])->load('product');
|
||||
}
|
||||
|
||||
private function createTenant(string $codigo, string $nombre, string $dominio): Tenant
|
||||
{
|
||||
$hdrKey = (string) \Illuminate\Support\Str::uuid();
|
||||
$ftrKey = (string) \Illuminate\Support\Str::uuid();
|
||||
|
||||
$headerAttachment = \App\Domains\Attachable\Models\Attachment::create([
|
||||
'key' => $hdrKey,
|
||||
'path' => 'tenants/' . $hdrKey . '.png',
|
||||
'filename' => 'logo_header.png',
|
||||
'type' => \App\Domains\Attachable\Enums\AttachmentType::Image,
|
||||
'mime_type' => 'image/png',
|
||||
]);
|
||||
$footerAttachment = \App\Domains\Attachable\Models\Attachment::create([
|
||||
'key' => $ftrKey,
|
||||
'path' => 'tenants/' . $ftrKey . '.png',
|
||||
'filename' => 'logo_footer.png',
|
||||
'type' => \App\Domains\Attachable\Enums\AttachmentType::Image,
|
||||
'mime_type' => 'image/png',
|
||||
]);
|
||||
|
||||
return Tenant::create([
|
||||
'codigo' => $codigo,
|
||||
'nombre' => $nombre,
|
||||
'dominio' => $dominio,
|
||||
'primary_color' => '#111111',
|
||||
'secondary_color' => '#222222',
|
||||
'danger_color' => '#333333',
|
||||
'success_color' => '#28a745',
|
||||
'header_bg_color' => '#444444',
|
||||
'footer_bg_color' => '#444444',
|
||||
'header_logo_id' => $headerAttachment->id,
|
||||
'footer_logo_id' => $footerAttachment->id,
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -3,8 +3,10 @@
|
||||
namespace Tests\Feature\Purchase;
|
||||
|
||||
use App\Domains\Auth\Models\User;
|
||||
use App\Domains\Cart\Models\Cart;
|
||||
use App\Domains\Catalog\Models\Product;
|
||||
use App\Domains\Catalog\Models\ProductVariant;
|
||||
use App\Domains\Purchase\Models\Purchase;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Tests\TestCase;
|
||||
@@ -13,17 +15,12 @@ class StorePurchaseTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
public function test_it_creates_a_purchase_with_customer_details_and_clears_the_cart(): void
|
||||
public function test_it_creates_a_purchase_from_cart_id_without_persisting_items_yet(): void
|
||||
{
|
||||
// 1. Setup Tenant
|
||||
$tenant = $this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
|
||||
|
||||
// 2. Setup User
|
||||
$user = User::factory()->create([
|
||||
'email' => 'buyer@example.com'
|
||||
'email' => 'buyer@example.com',
|
||||
]);
|
||||
|
||||
// 3. Setup Product & Variant
|
||||
$category = \App\Domains\Catalog\Models\Category::query()->create([
|
||||
'tenant_code' => 'sonder',
|
||||
'nombre' => 'Test Category',
|
||||
@@ -46,61 +43,251 @@ class StorePurchaseTest extends TestCase
|
||||
'precio' => '50.00',
|
||||
]);
|
||||
|
||||
// 4. Add item to user's cart
|
||||
$this->actingAs($user, 'sanctum')
|
||||
$cartResponse = $this->actingAs($user, 'sanctum')
|
||||
->postJson('/api/tenants/sonder/cart/items', [
|
||||
'product_variant_id' => $variant->id,
|
||||
'cantidad' => 2,
|
||||
])
|
||||
->assertOk();
|
||||
|
||||
// Check cart exists in DB
|
||||
$cartId = $cartResponse->json('data.id');
|
||||
|
||||
$this->assertDatabaseHas('carritos', [
|
||||
'id' => $cartId,
|
||||
'tenant_codigo' => 'sonder',
|
||||
'user_id' => $user->id,
|
||||
'status' => 'active',
|
||||
]);
|
||||
|
||||
// 5. Submit Purchase with payment_method at root
|
||||
$response = $this->actingAs($user, 'sanctum')
|
||||
->postJson('/api/tenants/sonder/compras', [
|
||||
'cart_id' => $cartId,
|
||||
'dni' => '987654321',
|
||||
'telefono' => '+54 9 341 555-4321',
|
||||
'nombre_apellido' => 'Juan Perez',
|
||||
'email' => 'juan.perez@example.com',
|
||||
'payment_method' => 'transferencia',
|
||||
'items' => [
|
||||
[
|
||||
'producto_variante_id' => $variant->id,
|
||||
'cantidad' => 2,
|
||||
]
|
||||
]
|
||||
]);
|
||||
|
||||
// 6. Assertions
|
||||
$response->assertCreated();
|
||||
$response->assertJsonPath('data.cart_id', $cartId);
|
||||
$response->assertJsonPath('data.dni', '987654321');
|
||||
$response->assertJsonPath('data.telefono', '+54 9 341 555-4321');
|
||||
$response->assertJsonPath('data.nombre_apellido', 'Juan Perez');
|
||||
$response->assertJsonPath('data.email', 'juan.perez@example.com');
|
||||
$response->assertJsonPath('data.payment_method', 'transferencia');
|
||||
$response->assertJsonPath('data.tenant_codigo', 'sonder');
|
||||
$response->assertJsonPath('data.status', Purchase::STATUS_CREATED);
|
||||
$response->assertJsonPath('data.items', []);
|
||||
$response->assertJsonPath('data.subtotal', '100.00');
|
||||
$response->assertJsonPath('data.total', '100.00');
|
||||
|
||||
$purchaseId = $response->json('data.id');
|
||||
|
||||
// Assert Purchase saved in DB
|
||||
$this->assertDatabaseHas('compras', [
|
||||
'id' => $purchaseId,
|
||||
'cart_id' => $cartId,
|
||||
'tenant_codigo' => 'sonder',
|
||||
'user_id' => $user->id,
|
||||
'dni' => '987654321',
|
||||
'telefono' => '+54 9 341 555-4321',
|
||||
'nombre_apellido' => 'Juan Perez',
|
||||
'email' => 'juan.perez@example.com',
|
||||
'payment_method' => 'transferencia',
|
||||
'status' => Purchase::STATUS_CREATED,
|
||||
'total' => 100,
|
||||
]);
|
||||
|
||||
// Assert Cart was cleared (deleted)
|
||||
$this->assertDatabaseMissing('carritos', [
|
||||
'tenant_codigo' => 'sonder',
|
||||
$this->assertDatabaseMissing('compra_items', [
|
||||
'compra_id' => $purchaseId,
|
||||
]);
|
||||
$this->assertDatabaseHas('carritos', [
|
||||
'id' => $cartId,
|
||||
'status' => 'active',
|
||||
'user_id' => $user->id,
|
||||
]);
|
||||
$this->assertDatabaseHas('carrito_items', [
|
||||
'cart_id' => $cartId,
|
||||
'producto_variante_id' => $variant->id,
|
||||
'cantidad' => 2,
|
||||
]);
|
||||
$this->assertDatabaseHas('productos_variantes', [
|
||||
'id' => $variant->id,
|
||||
'stock_real' => 10,
|
||||
'stock_reservado' => 2,
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_it_moves_a_created_purchase_to_pending_payment_when_finalized(): void
|
||||
{
|
||||
$tenant = $this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
|
||||
$user = User::factory()->create([
|
||||
'email' => 'buyer@example.com',
|
||||
]);
|
||||
$variant = $this->createVariantForTenant('sonder', 10, '50.00');
|
||||
|
||||
$cartId = $this->actingAs($user, 'sanctum')
|
||||
->postJson('/api/tenants/sonder/cart/items', [
|
||||
'product_variant_id' => $variant->id,
|
||||
'cantidad' => 2,
|
||||
])
|
||||
->assertOk()
|
||||
->json('data.id');
|
||||
|
||||
$purchaseId = $this->actingAs($user, 'sanctum')
|
||||
->postJson('/api/tenants/sonder/compras', [
|
||||
'cart_id' => $cartId,
|
||||
'dni' => '987654321',
|
||||
'telefono' => '+54 9 341 555-4321',
|
||||
'nombre_apellido' => 'Juan Perez',
|
||||
'email' => 'juan.perez@example.com',
|
||||
])
|
||||
->assertCreated()
|
||||
->json('data.id');
|
||||
|
||||
Purchase::query()
|
||||
->whereKey($purchaseId)
|
||||
->update([
|
||||
'payment_method' => 'transfer',
|
||||
]);
|
||||
|
||||
$this->actingAs($user, 'sanctum')
|
||||
->postJson("/api/tenants/sonder/compras/{$purchaseId}/complete")
|
||||
->assertOk()
|
||||
->assertJsonPath('data.status', Purchase::STATUS_PENDING_PAYMENT);
|
||||
|
||||
$this->assertDatabaseHas('compras', [
|
||||
'id' => $purchaseId,
|
||||
'status' => Purchase::STATUS_PENDING_PAYMENT,
|
||||
'payment_method' => 'transfer',
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_it_rejects_a_cart_from_another_user(): void
|
||||
{
|
||||
$this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
|
||||
$owner = User::factory()->create();
|
||||
$attacker = User::factory()->create();
|
||||
$variant = $this->createVariantForTenant('sonder', 10, '50.00');
|
||||
|
||||
$cartId = $this->actingAs($owner, 'sanctum')
|
||||
->postJson('/api/tenants/sonder/cart/items', [
|
||||
'product_variant_id' => $variant->id,
|
||||
'cantidad' => 1,
|
||||
])
|
||||
->assertOk()
|
||||
->json('data.id');
|
||||
|
||||
$this->actingAs($attacker, 'sanctum')
|
||||
->postJson('/api/tenants/sonder/compras', [
|
||||
'cart_id' => $cartId,
|
||||
'dni' => '12345678',
|
||||
'telefono' => '+54 9 341 555-1111',
|
||||
'nombre_apellido' => 'Intruso',
|
||||
'email' => 'intruso@example.com',
|
||||
])
|
||||
->assertNotFound();
|
||||
}
|
||||
|
||||
public function test_it_rejects_a_cart_from_another_tenant(): void
|
||||
{
|
||||
$this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
|
||||
$this->createTenant('globex', 'Globex', 'globex.com.ar');
|
||||
$user = User::factory()->create();
|
||||
$variant = $this->createVariantForTenant('globex', 10, '50.00');
|
||||
|
||||
$cartId = $this->actingAs($user, 'sanctum')
|
||||
->postJson('/api/tenants/globex/cart/items', [
|
||||
'product_variant_id' => $variant->id,
|
||||
'cantidad' => 1,
|
||||
])
|
||||
->assertOk()
|
||||
->json('data.id');
|
||||
|
||||
$this->actingAs($user, 'sanctum')
|
||||
->postJson('/api/tenants/sonder/compras', [
|
||||
'cart_id' => $cartId,
|
||||
'dni' => '12345678',
|
||||
'telefono' => '+54 9 341 555-1111',
|
||||
'nombre_apellido' => 'Juan Perez',
|
||||
'email' => 'juan.perez@example.com',
|
||||
])
|
||||
->assertNotFound();
|
||||
}
|
||||
|
||||
public function test_it_rejects_an_empty_cart(): void
|
||||
{
|
||||
$this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
|
||||
$user = User::factory()->create();
|
||||
$cart = Cart::query()->create([
|
||||
'tenant_codigo' => 'sonder',
|
||||
'user_id' => $user->id,
|
||||
'status' => 'active',
|
||||
]);
|
||||
|
||||
$this->actingAs($user, 'sanctum')
|
||||
->postJson('/api/tenants/sonder/compras', [
|
||||
'cart_id' => $cart->id,
|
||||
'dni' => '12345678',
|
||||
'telefono' => '+54 9 341 555-1111',
|
||||
'nombre_apellido' => 'Juan Perez',
|
||||
'email' => 'juan.perez@example.com',
|
||||
])
|
||||
->assertUnprocessable()
|
||||
->assertJsonValidationErrors(['cart_id']);
|
||||
}
|
||||
|
||||
public function test_it_rejects_a_converted_cart(): void
|
||||
{
|
||||
$this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
|
||||
$user = User::factory()->create();
|
||||
$cart = Cart::query()->create([
|
||||
'tenant_codigo' => 'sonder',
|
||||
'user_id' => $user->id,
|
||||
'status' => 'converted',
|
||||
]);
|
||||
|
||||
$this->actingAs($user, 'sanctum')
|
||||
->postJson('/api/tenants/sonder/compras', [
|
||||
'cart_id' => $cart->id,
|
||||
'dni' => '12345678',
|
||||
'telefono' => '+54 9 341 555-1111',
|
||||
'nombre_apellido' => 'Juan Perez',
|
||||
'email' => 'juan.perez@example.com',
|
||||
])
|
||||
->assertUnprocessable()
|
||||
->assertJsonValidationErrors(['cart_id']);
|
||||
}
|
||||
|
||||
protected function createVariantForTenant(
|
||||
string $tenantCode,
|
||||
int $stock,
|
||||
string $price,
|
||||
string $slugPrefix = 'shirt',
|
||||
): ProductVariant {
|
||||
$tenant = Tenant::query()->where('codigo', $tenantCode)->first();
|
||||
if (! $tenant) {
|
||||
$this->createTenant($tenantCode, ucfirst($tenantCode), "{$tenantCode}.com");
|
||||
}
|
||||
|
||||
$category = \App\Domains\Catalog\Models\Category::query()->create([
|
||||
'tenant_code' => $tenantCode,
|
||||
'nombre' => "{$slugPrefix} category {$tenantCode}",
|
||||
]);
|
||||
|
||||
$product = Product::query()->create([
|
||||
'tenant_codigo' => $tenantCode,
|
||||
'categoria_id' => $category->id,
|
||||
'slug' => "{$slugPrefix}-{$tenantCode}-".Product::query()->count(),
|
||||
'nombre' => ucfirst($slugPrefix)." {$tenantCode}",
|
||||
'descripcion' => 'Test product',
|
||||
'precio' => $price,
|
||||
]);
|
||||
|
||||
return ProductVariant::query()->create([
|
||||
'producto_id' => $product->id,
|
||||
'slug' => "{$slugPrefix}-variant-".ProductVariant::query()->count(),
|
||||
'nombre' => ucfirst($slugPrefix).' Variant',
|
||||
'stock' => $stock,
|
||||
'descripcion' => 'Test variant',
|
||||
'precio' => $price,
|
||||
])->load('product');
|
||||
}
|
||||
|
||||
protected function createTenant(string $codigo, string $nombre, string $dominio): Tenant
|
||||
|
||||
@@ -1,242 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Tenant;
|
||||
|
||||
use App\Domains\BankAccount\Models\BankAccount;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use App\Domains\Auth\Models\User;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Tests\TestCase;
|
||||
|
||||
class BankAccountControllerTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private Tenant $tenant;
|
||||
private User $user;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
$hdrKey = (string) \Illuminate\Support\Str::uuid();
|
||||
$ftrKey = (string) \Illuminate\Support\Str::uuid();
|
||||
|
||||
$headerAttachment = \App\Domains\Attachable\Models\Attachment::create([
|
||||
'key' => $hdrKey,
|
||||
'path' => 'tenants/' . $hdrKey . '.png',
|
||||
'filename' => 'logo_header.png',
|
||||
'type' => \App\Domains\Attachable\Enums\AttachmentType::Image,
|
||||
'mime_type' => 'image/png',
|
||||
]);
|
||||
$footerAttachment = \App\Domains\Attachable\Models\Attachment::create([
|
||||
'key' => $ftrKey,
|
||||
'path' => 'tenants/' . $ftrKey . '.png',
|
||||
'filename' => 'logo_footer.png',
|
||||
'type' => \App\Domains\Attachable\Enums\AttachmentType::Image,
|
||||
'mime_type' => 'image/png',
|
||||
]);
|
||||
|
||||
$this->tenant = Tenant::create([
|
||||
'codigo' => 'acme',
|
||||
'nombre' => 'Acme',
|
||||
'dominio' => 'acme.com',
|
||||
'primary_color' => '#ff0000',
|
||||
'secondary_color' => '#00ff00',
|
||||
'danger_color' => '#0000ff',
|
||||
'success_color' => '#00ff00',
|
||||
'header_bg_color' => '#ffffff',
|
||||
'footer_bg_color' => '#ffffff',
|
||||
'header_logo_id' => $headerAttachment->id,
|
||||
'footer_logo_id' => $footerAttachment->id,
|
||||
]);
|
||||
|
||||
$this->user = User::factory()->create();
|
||||
$this->actingAs($this->user, 'sanctum');
|
||||
}
|
||||
|
||||
public function test_it_lists_bank_accounts_for_a_tenant(): void
|
||||
{
|
||||
BankAccount::query()->create([
|
||||
'tenant_code' => 'acme',
|
||||
'titular' => 'John Doe',
|
||||
'entidad' => 'Banco Galicia',
|
||||
'alias' => 'john.doe.galicia',
|
||||
'cvu' => '1234567890123456789012',
|
||||
]);
|
||||
|
||||
$response = $this->getJson("/api/tenants/acme/bank-accounts");
|
||||
|
||||
$response->assertOk()
|
||||
->assertJsonCount(1, 'data')
|
||||
->assertJsonPath('data.0.titular', 'John Doe');
|
||||
}
|
||||
|
||||
public function test_it_creates_a_bank_account_for_a_tenant(): void
|
||||
{
|
||||
$response = $this->postJson("/api/tenants/acme/bank-accounts", [
|
||||
'titular' => 'Jane Doe',
|
||||
'entidad' => 'Banco Nación',
|
||||
'alias' => 'jane.doe.nacion',
|
||||
'cvu' => '9876543210987654321098',
|
||||
]);
|
||||
|
||||
$response->assertCreated()
|
||||
->assertJsonPath('data.titular', 'Jane Doe');
|
||||
|
||||
$this->assertDatabaseHas('bank_accounts', [
|
||||
'tenant_code' => 'acme',
|
||||
'titular' => 'Jane Doe',
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_it_shows_a_bank_account(): void
|
||||
{
|
||||
$account = BankAccount::query()->create([
|
||||
'tenant_code' => 'acme',
|
||||
'titular' => 'John Doe',
|
||||
'entidad' => 'Banco Galicia',
|
||||
'alias' => 'john.doe.galicia',
|
||||
'cvu' => '1234567890123456789012',
|
||||
]);
|
||||
|
||||
$response = $this->getJson("/api/tenants/acme/bank-accounts/{$account->id}");
|
||||
|
||||
$response->assertOk()
|
||||
->assertJsonPath('data.titular', 'John Doe');
|
||||
}
|
||||
|
||||
public function test_it_updates_a_bank_account(): void
|
||||
{
|
||||
$account = BankAccount::query()->create([
|
||||
'tenant_code' => 'acme',
|
||||
'titular' => 'John Doe',
|
||||
'entidad' => 'Banco Galicia',
|
||||
'alias' => 'john.doe.galicia',
|
||||
'cvu' => '1234567890123456789012',
|
||||
]);
|
||||
|
||||
$response = $this->putJson("/api/tenants/acme/bank-accounts/{$account->id}", [
|
||||
'titular' => 'John Doe Updated',
|
||||
]);
|
||||
|
||||
$response->assertOk()
|
||||
->assertJsonPath('data.titular', 'John Doe Updated');
|
||||
|
||||
$this->assertDatabaseHas('bank_accounts', [
|
||||
'id' => $account->id,
|
||||
'titular' => 'John Doe Updated',
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_it_deletes_a_bank_account(): void
|
||||
{
|
||||
$account = BankAccount::query()->create([
|
||||
'tenant_code' => 'acme',
|
||||
'titular' => 'John Doe',
|
||||
'entidad' => 'Banco Galicia',
|
||||
'alias' => 'john.doe.galicia',
|
||||
'cvu' => '1234567890123456789012',
|
||||
]);
|
||||
|
||||
$response = $this->deleteJson("/api/tenants/acme/bank-accounts/{$account->id}");
|
||||
|
||||
$response->assertNoContent();
|
||||
|
||||
$this->assertDatabaseMissing('bank_accounts', ['id' => $account->id]);
|
||||
}
|
||||
|
||||
public function test_it_selects_a_bank_account_for_a_tenant(): void
|
||||
{
|
||||
$account = BankAccount::query()->create([
|
||||
'tenant_code' => 'acme',
|
||||
'titular' => 'John Doe',
|
||||
'entidad' => 'Banco Galicia',
|
||||
'alias' => 'john.doe.galicia',
|
||||
'cvu' => '1234567890123456789012',
|
||||
]);
|
||||
|
||||
$response = $this->postJson("/api/tenants/acme/bank-accounts/{$account->id}/select");
|
||||
|
||||
$response->assertOk()
|
||||
->assertJsonPath('data.selected_bank_account_id', $account->id);
|
||||
|
||||
$this->tenant->refresh();
|
||||
$this->assertEquals($account->id, $this->tenant->selected_bank_account_id);
|
||||
}
|
||||
|
||||
public function test_it_deletes_related_bank_accounts_when_tenant_is_deleted(): void
|
||||
{
|
||||
$account = BankAccount::query()->create([
|
||||
'tenant_code' => 'acme',
|
||||
'titular' => 'John Doe',
|
||||
'entidad' => 'Banco Galicia',
|
||||
'alias' => 'john.doe.galicia',
|
||||
'cvu' => '1234567890123456789012',
|
||||
]);
|
||||
|
||||
$this->assertDatabaseHas('bank_accounts', ['id' => $account->id]);
|
||||
|
||||
$this->tenant->delete();
|
||||
|
||||
$this->assertDatabaseMissing('bank_accounts', ['id' => $account->id]);
|
||||
}
|
||||
|
||||
public function test_it_sets_selected_bank_account_id_to_null_when_selected_bank_account_is_deleted(): void
|
||||
{
|
||||
$account = BankAccount::query()->create([
|
||||
'tenant_code' => 'acme',
|
||||
'titular' => 'John Doe',
|
||||
'entidad' => 'Banco Galicia',
|
||||
'alias' => 'john.doe.galicia',
|
||||
'cvu' => '1234567890123456789012',
|
||||
]);
|
||||
|
||||
$this->tenant->selected_bank_account_id = $account->id;
|
||||
$this->tenant->save();
|
||||
|
||||
$account->delete();
|
||||
|
||||
$this->tenant->refresh();
|
||||
$this->assertNull($this->tenant->selected_bank_account_id);
|
||||
}
|
||||
|
||||
public function test_it_gets_the_selected_bank_account_for_a_tenant(): void
|
||||
{
|
||||
$account = BankAccount::query()->create([
|
||||
'tenant_code' => 'acme',
|
||||
'titular' => 'John Doe',
|
||||
'entidad' => 'Banco Galicia',
|
||||
'alias' => 'john.doe.galicia',
|
||||
'cvu' => '1234567890123456789012',
|
||||
]);
|
||||
|
||||
// When no bank account is selected
|
||||
$response = $this->getJson("/api/tenants/acme/bank-accounts/selected");
|
||||
$response->assertNotFound();
|
||||
|
||||
// Select the bank account
|
||||
$this->tenant->selected_bank_account_id = $account->id;
|
||||
$this->tenant->save();
|
||||
|
||||
// Get selected bank account
|
||||
$response = $this->getJson("/api/tenants/acme/bank-accounts/selected");
|
||||
$response->assertOk()
|
||||
->assertJsonPath('data.id', $account->id)
|
||||
->assertJsonPath('data.titular', 'John Doe');
|
||||
}
|
||||
|
||||
public function test_it_rejects_unauthenticated_requests(): void
|
||||
{
|
||||
$this->app['auth']->forgetGuards();
|
||||
|
||||
$response = $this->getJson("/api/tenants/acme/bank-accounts/selected");
|
||||
$response->assertStatus(401);
|
||||
|
||||
$response2 = $this->getJson("/api/tenants/acme/bank-accounts");
|
||||
$response2->assertStatus(401);
|
||||
|
||||
$response3 = $this->postJson("/api/tenants/acme/bank-accounts", []);
|
||||
$response3->assertStatus(401);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user