Compare commits

...

16 Commits

Author SHA1 Message Date
b273b2866f feat: add status filter to purchase index query for enhanced data retrieval 2026-07-08 11:32:56 -03:00
05a92b7ec3 feat: update purchase query in TelepagosWebhookService to handle multiple statuses and normalize DNI format 2026-07-08 10:05:49 -03:00
f23029e785 feat: enhance integration setup process with error handling and validation 2026-07-08 09:00:42 -03:00
f18fbc8147 feat: rename finalize methods to complete for consistency in purchase processing 2026-07-07 15:36:07 -03:00
c276ccd311 feat: refactor purchase status handling and add finalize endpoint for purchases 2026-07-07 15:33:29 -03:00
786b4eb6a9 feat: add MergeGuestCartMiddleware to tenant route for enhanced cart handling 2026-07-07 12:55:07 -03:00
eca3b01083 feat: update Telepagos webhook and payment intent logic for improved data handling 2026-07-07 11:11:21 -03:00
7b2a741884 feat: add total field to purchases and update related logic for payment processing 2026-07-07 10:16:28 -03:00
362e888e46 feat: update .gitignore to include .env.testing and enhance phpunit.xml with additional environment variables 2026-07-07 09:25:39 -03:00
92458e217e feat: enhance Telepagos webhook handling for transferencia and QR operations with improved purchase matching logic 2026-07-07 08:57:27 -03:00
4edda0bfd8 feat: add default entity value for payment account information in paymentIntent method 2026-07-06 16:53:58 -03:00
2c2cf45f78 feat: remove BankAccount domain and related functionality, including controller, model, requests, routes, and tests 2026-07-06 16:53:45 -03:00
1fcb3129ea feat: enhance Telepagos integration with token refresh handling and refactor CheckoutService to use updateOrCreate for purchases 2026-07-06 16:24:00 -03:00
3703ae9bcf feat: add getTotalAmount method to Cart and refactor Purchase model to utilize it 2026-07-06 15:26:41 -03:00
c19e00987e feat: implement MergeGuestCartMiddleware to merge guest cart with user cart upon authentication 2026-07-06 14:57:19 -03:00
7be2221bb8 feat: update MeController to return user data as UserResource 2026-07-06 14:30:15 -03:00
34 changed files with 930 additions and 675 deletions

1
.gitignore vendored
View File

@@ -1,6 +1,7 @@
*.log
.DS_Store
.env
.env.testing
.env.backup
.env.production
.phpactor.json

View File

@@ -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",

View File

@@ -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());
}
}

View File

@@ -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();
}
}

View File

@@ -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');
}
}

View File

@@ -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.',
];
}
}

View File

@@ -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.',
];
}
}

View File

@@ -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,
];
}
}

View File

@@ -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']);
});
});

View 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;
}
}

View File

@@ -59,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) {

View File

@@ -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 [

View File

@@ -3,7 +3,9 @@
use App\Domains\Cart\Controllers\CartController;
use Illuminate\Support\Facades\Route;
Route::prefix('tenants/{tenant:codigo}')->group(function (): void {
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']);

View File

@@ -36,6 +36,7 @@ class TenantIntegrationController extends Controller
{
$integration = Integration::where('integration_code', $integrationCode)->firstOrFail();
try {
$tenantIntegration = $this->tenantIntegrationService->updateOrCreateIntegration(
$tenantCode,
$integration,
@@ -43,5 +44,10 @@ class TenantIntegrationController extends Controller
);
return response()->json($tenantIntegration);
} catch (\Exception $e) {
return response()->json([
'message' => 'Error validando la configuración: ' . $e->getMessage()
], 400);
}
}
}

View File

@@ -152,4 +152,16 @@ abstract class BaseIntegrationService
* @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
}
}

View File

@@ -106,6 +106,29 @@ class TelepagosIntegrationService extends BaseIntegrationService
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.
*
@@ -117,17 +140,15 @@ class TelepagosIntegrationService extends BaseIntegrationService
*/
public function generateQr(float $amount, string $concept, string $description): array
{
$response = $this->client()->post('/v2/payment/cashin/qr/generate', [
$payload = [
'amount' => $amount,
'concept' => $concept,
'description' => $description,
]);
];
return $this->handleResponse($response, 'QR generation', [
'amount' => $amount,
'concept' => $concept,
'description' => $description,
]);
$response = $this->sendRequest('post', '/v2/payment/cashin/qr/generate', $payload);
return $this->handleResponse($response, 'QR generation', $payload);
}
/**
@@ -137,15 +158,27 @@ class TelepagosIntegrationService extends BaseIntegrationService
* @return array
* @throws Exception
*/
public function getCashinDetails(int $cashinId): array
public function getCashinDetails(string $cashinId): array
{
$response = $this->client()->get("/v2/payment/cashin/{$cashinId}");
$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.
*
@@ -180,4 +213,16 @@ class TelepagosIntegrationService extends BaseIntegrationService
$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();
}
}

View File

@@ -2,9 +2,10 @@
namespace App\Domains\Integration\Services;
use App\Domains\Purchase\Services\CheckoutService;
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;
@@ -28,19 +29,45 @@ class TelepagosWebhookService
$tenant = Tenant::where('codigo', $tenantCodigo)->firstOrFail();
$telepagosService = new TelepagosIntegrationService();
$telepagosService->forTenant($tenant);
$telepagosService->forTenant($tenant->codigo);
try {
$details = $telepagosService->getCashinDetails($cashinId);
// Extract the qr_order_id from the response
// The exact path depends on Telepagos response structure, assuming it's inside 'data'
// Need to handle potential nested structures based on actual API
$qrOrderId = $details['data']['qr_order_id'] ?? $details['qr_order_id'] ?? null;
$amount = $details['data']['amount'] ?? $details['amount'] ?? 0;
$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 cashin {$cashinId}");
Log::warning("Telepagos webhook: qr_order_id not found for QR cashin {$cashinId}");
return;
}
@@ -58,21 +85,26 @@ class TelepagosWebhookService
return;
}
$totalAmount = $compra->getTotalAmount();
// Depending on precision, we might need a looser comparison, but == should work for floats here
if ($amount != $totalAmount) {
Log::warning("Telepagos webhook: Amount mismatch. Cashin amount: {$amount}, Purchase amount: {$totalAmount}");
// In a real scenario, you might want to record a partial payment or flag it,
// but the instructions say to finalize ONLY if the amount is correct.
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;
}
// Create the TelepagosPayment and finalize the purchase in a transaction
$paymentData = [
'compra_id' => $compra->id,
'cuit_buyer' => $details['data']['cuit_buyer'] ?? $details['cuit_buyer'] ?? null,
'cvu_buyer' => $details['data']['cvu_buyer'] ?? $details['cvu_buyer'] ?? null,
'cuit_buyer' => $details['data']['buyer']['cuit'] ?? $details['buyer']['cuit'] ?? null,
'cvu_buyer' => $details['data']['buyer']['cvu'] ?? $details['buyer']['cvu'] ?? null,
'amount' => $amount,
'concept' => $details['data']['concept'] ?? $details['concept'] ?? null,
'operation' => $details['data']['operation'] ?? $details['operation'] ?? null,
@@ -85,14 +117,18 @@ class TelepagosWebhookService
\Illuminate\Support\Facades\DB::transaction(function () use ($compra, $paymentData) {
TelepagosPayment::create($paymentData);
$this->checkoutService->confirmPurchase($compra);
$compra->finalize();
$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, '.', '');
}
}

View File

@@ -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,7 +24,8 @@ class TenantIntegrationService
public function updateOrCreateIntegration(string $tenantCode, Integration $integration, array $data): TenantIntegration
{
return TenantIntegration::updateOrCreate(
return DB::transaction(function () use ($tenantCode, $integration, $data) {
$tenantIntegration = TenantIntegration::updateOrCreate(
[
'tenant_code' => $tenantCode,
'integration_code' => $integration->integration_code,
@@ -32,5 +34,24 @@ class TenantIntegrationService
'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;
}
}
}

View File

@@ -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();
@@ -54,49 +56,58 @@ class PurchaseController extends Controller
{
$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') {
$bankAccount = $tenant->selectedBankAccount;
return response()->json([
'payment_method' => 'transfer',
'transfer_data' => $bankAccount ? [
'titular' => $bankAccount->titular,
'entidad' => $bankAccount->entidad,
'alias' => $bankAccount->alias,
'cvu' => $bankAccount->cvu,
] : null,
]);
}
if ($method === 'qr') {
$telepagosQr = $compra->telepagosQr;
if (!$telepagosQr) {
$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(
$compra->getTotalAmount(),
$totalAmount,
'Compra',
"Compra #{$compra->id}"
);
$telepagosQr = $compra->telepagosQr()->create([
'qr_order_id' => (string) ($qrResponse['id'] ?? $qrResponse['order_id'] ?? $qrResponse['cashin_id'] ?? ''),
'qr_code' => $qrResponse['qr'] ?? $qrResponse['qr_code'] ?? $qrResponse['qr_data'] ?? '',
'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',
@@ -112,6 +123,15 @@ class PurchaseController extends Controller
], 400);
}
public function complete(Request $request, Tenant $tenant, Purchase $compra, CheckoutService $checkoutService): PurchaseResource
{
$compra = $this->resolveScopedPurchase($tenant, $request->user()->id, $compra);
return PurchaseResource::make(
$checkoutService->completePurchase($compra)
);
}
protected function resolveScopedPurchase(Tenant $tenant, int $userId, Purchase $purchase): Purchase
{
if ($purchase->tenant_codigo !== $tenant->codigo || $purchase->user_id !== $userId) {

View File

@@ -10,15 +10,14 @@ 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\Support\Collection;
#[Fillable([
'cart_id',
'tenant_codigo',
'user_id',
'status',
'payment_status',
'payment_method',
'total',
'dni',
'telefono',
'nombre_apellido',
@@ -28,6 +27,12 @@ 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
@@ -35,6 +40,7 @@ class Purchase extends Model
return [
'cart_id' => 'integer',
'user_id' => 'integer',
'total' => 'decimal:2',
];
}
@@ -59,7 +65,7 @@ class Purchase extends Model
*/
public function cart(): BelongsTo
{
return $this->belongsTo(Cart::class, 'cart_id')->withTrashed();
return $this->belongsTo(Cart::class, 'cart_id');
}
/**
@@ -88,32 +94,45 @@ class Purchase extends Model
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;
$cart = $this->relationLoaded('cart')
? $this->getRelation('cart')
: $this->cart()->with('items.variant.product')->first();
if ($cart === null) {
if (! $cart) {
return 0.0;
}
/** @var Collection<int, mixed> $items */
$items = $cart->relationLoaded('items')
? $cart->getRelation('items')
: $cart->items()->with('variant.product')->get();
return $items->reduce(
static fn (float $carry, $item): float => $carry + ((float) ($item->variant?->product?->precio ?? 0) * (int) $item->cantidad),
0.0,
);
return $cart->getTotalAmount();
}
public function finalize(): void
public function markAsPendingPayment(): void
{
$this->update([
'status' => 'pagado', // Or the equivalent final status in your system
'payment_status' => 'paid',
'status' => self::STATUS_PENDING_PAYMENT,
]);
}
public function markAsPaid(): void
{
$this->update([
'status' => self::STATUS_PAID,
]);
}
}

View File

@@ -3,7 +3,6 @@
namespace App\Domains\Purchase\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
class StorePurchaseRequest extends FormRequest
{
@@ -18,7 +17,6 @@ class StorePurchaseRequest extends FormRequest
public function rules(): array
{
return [
'status' => ['sometimes', 'string', Rule::in(['pending', 'paid', 'cancelled'])],
'cart_id' => ['required', 'integer', 'exists:carritos,id'],
'dni' => ['required', 'string'],
'telefono' => ['required', 'string'],

View File

@@ -19,15 +19,19 @@ class PurchaseResource extends JsonResource
? $this->resource->getRelation('items')
: collect();
$subtotal = $items->reduce(
$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(
$total = $items->isNotEmpty()
? $items->reduce(
fn (float $carry, $item): float => $carry + (float) $item->total,
0.0,
);
)
: (float) ($this->total ?? 0);
return [
'id' => $this->id,
@@ -35,7 +39,6 @@ class PurchaseResource extends JsonResource
'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,

View File

@@ -29,15 +29,65 @@ class CheckoutService
]);
}
$cartItems->load('variant.product');
$cart->setRelation('items', $cartItems);
$totalAmount = $cart->getTotalAmount();
/** @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 ($purchase === null) {
/** @var Purchase $purchase */
$purchase = Purchase::query()->create([
...$purchaseData,
'cart_id' => $cart->getKey(),
'tenant_codigo' => $tenant->codigo,
'user_id' => $userId,
'status' => 'pending',
'payment_status' => 'pending',
'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']);
});
}
public function completePurchase(Purchase $purchase): Purchase
{
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']);

View File

@@ -3,7 +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']);
});

View File

@@ -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');
}
}

View File

@@ -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');
});
}
};

View File

@@ -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');
});
}
};

View File

@@ -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();
});
}
};

View File

@@ -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();
}
}

View File

@@ -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"/>

View File

@@ -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';

View 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,
]);
}
}

View File

@@ -6,6 +6,7 @@ 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;
@@ -74,8 +75,10 @@ class StorePurchaseTest extends TestCase
$response->assertJsonPath('data.nombre_apellido', 'Juan Perez');
$response->assertJsonPath('data.email', 'juan.perez@example.com');
$response->assertJsonPath('data.tenant_codigo', 'sonder');
$response->assertJsonPath('data.status', Purchase::STATUS_CREATED);
$response->assertJsonPath('data.items', []);
$response->assertJsonPath('data.total', '0.00');
$response->assertJsonPath('data.subtotal', '100.00');
$response->assertJsonPath('data.total', '100.00');
$purchaseId = $response->json('data.id');
@@ -88,6 +91,8 @@ class StorePurchaseTest extends TestCase
'telefono' => '+54 9 341 555-4321',
'nombre_apellido' => 'Juan Perez',
'email' => 'juan.perez@example.com',
'status' => Purchase::STATUS_CREATED,
'total' => 100,
]);
$this->assertDatabaseMissing('compra_items', [
'compra_id' => $purchaseId,
@@ -97,10 +102,6 @@ class StorePurchaseTest extends TestCase
'status' => 'active',
'user_id' => $user->id,
]);
$this->assertDatabaseMissing('carritos', [
'id' => $cartId,
'deleted_at' => null,
]);
$this->assertDatabaseHas('carrito_items', [
'cart_id' => $cartId,
'producto_variante_id' => $variant->id,
@@ -113,6 +114,51 @@ class StorePurchaseTest extends TestCase
]);
}
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');

View File

@@ -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);
}
}