feat: Introduce client management and integration updates
- Added client_id field to StoreTenantRequest and UpdateTenantRequest for tenant management. - Updated TenantResource to include client_id in the response. - Created migration to establish clients table and link tenants to clients. - Migrated existing tenant integrations to client_integrations table. - Grouped specific tenants under a shared client (OnTicket) in a new migration. - Updated seeders to reflect new client structure and relationships. - Adjusted integration configurations to require client instead of tenant. - Added tests for client integration functionality and ensured existing tests reflect the new client structure.
This commit is contained in:
47
app/Domains/Client/Controllers/ClientController.php
Normal file
47
app/Domains/Client/Controllers/ClientController.php
Normal file
@@ -0,0 +1,47 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Client\Controllers;
|
||||
|
||||
use App\Domains\Client\Models\Client;
|
||||
use App\Domains\Client\Requests\StoreClientRequest;
|
||||
use App\Domains\Client\Requests\UpdateClientRequest;
|
||||
use App\Domains\Client\Resources\ClientResource;
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Response;
|
||||
|
||||
class ClientController extends Controller
|
||||
{
|
||||
public function index(): JsonResponse
|
||||
{
|
||||
return ClientResource::collection(
|
||||
Client::query()->with('tenants')->latest()->paginateFromRequest()
|
||||
)->response();
|
||||
}
|
||||
|
||||
public function store(StoreClientRequest $request): JsonResponse
|
||||
{
|
||||
return ClientResource::make(
|
||||
Client::query()->create($request->validated())->load('tenants')
|
||||
)->response()->setStatusCode(201);
|
||||
}
|
||||
|
||||
public function show(Client $client): ClientResource
|
||||
{
|
||||
return ClientResource::make($client->load('tenants'));
|
||||
}
|
||||
|
||||
public function update(UpdateClientRequest $request, Client $client): ClientResource
|
||||
{
|
||||
$client->update($request->validated());
|
||||
|
||||
return ClientResource::make($client->fresh()->load('tenants'));
|
||||
}
|
||||
|
||||
public function destroy(Client $client): Response
|
||||
{
|
||||
$client->delete();
|
||||
|
||||
return response()->noContent();
|
||||
}
|
||||
}
|
||||
30
app/Domains/Client/Models/Client.php
Normal file
30
app/Domains/Client/Models/Client.php
Normal file
@@ -0,0 +1,30 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Client\Models;
|
||||
|
||||
use App\Domains\Integration\Models\ClientIntegration;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
|
||||
#[Fillable(['code', 'name'])]
|
||||
class Client extends Model
|
||||
{
|
||||
public function getRouteKeyName(): string
|
||||
{
|
||||
return 'code';
|
||||
}
|
||||
|
||||
/** @return HasMany<Tenant, $this> */
|
||||
public function tenants(): HasMany
|
||||
{
|
||||
return $this->hasMany(Tenant::class);
|
||||
}
|
||||
|
||||
/** @return HasMany<ClientIntegration, $this> */
|
||||
public function integrations(): HasMany
|
||||
{
|
||||
return $this->hasMany(ClientIntegration::class);
|
||||
}
|
||||
}
|
||||
22
app/Domains/Client/Requests/StoreClientRequest.php
Normal file
22
app/Domains/Client/Requests/StoreClientRequest.php
Normal file
@@ -0,0 +1,22 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Client\Requests;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Validation\Rule;
|
||||
|
||||
class StoreClientRequest extends FormRequest
|
||||
{
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'code' => ['required', 'string', 'max:255', Rule::unique('clients', 'code')],
|
||||
'name' => ['required', 'string', 'max:255'],
|
||||
];
|
||||
}
|
||||
}
|
||||
26
app/Domains/Client/Requests/UpdateClientRequest.php
Normal file
26
app/Domains/Client/Requests/UpdateClientRequest.php
Normal file
@@ -0,0 +1,26 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Client\Requests;
|
||||
|
||||
use App\Domains\Client\Models\Client;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Validation\Rule;
|
||||
|
||||
class UpdateClientRequest extends FormRequest
|
||||
{
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
public function rules(): array
|
||||
{
|
||||
/** @var Client|null $client */
|
||||
$client = $this->route('client');
|
||||
|
||||
return [
|
||||
'code' => ['sometimes', 'string', 'max:255', Rule::unique('clients', 'code')->ignore($client?->id)],
|
||||
'name' => ['sometimes', 'string', 'max:255'],
|
||||
];
|
||||
}
|
||||
}
|
||||
26
app/Domains/Client/Resources/ClientResource.php
Normal file
26
app/Domains/Client/Resources/ClientResource.php
Normal file
@@ -0,0 +1,26 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Client\Resources;
|
||||
|
||||
use App\Domains\Client\Models\Client;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
/** @mixin Client */
|
||||
class ClientResource extends JsonResource
|
||||
{
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'code' => $this->code,
|
||||
'name' => $this->name,
|
||||
'tenants' => $this->whenLoaded('tenants', fn () => $this->tenants->map(fn ($tenant): array => [
|
||||
'id' => $tenant->id,
|
||||
'codigo' => $tenant->codigo,
|
||||
'nombre' => $tenant->nombre,
|
||||
'dominio' => $tenant->dominio,
|
||||
])),
|
||||
];
|
||||
}
|
||||
}
|
||||
6
app/Domains/Client/routes/api.php
Normal file
6
app/Domains/Client/routes/api.php
Normal file
@@ -0,0 +1,6 @@
|
||||
<?php
|
||||
|
||||
use App\Domains\Client\Controllers\ClientController;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
|
||||
Route::apiResource('clients', ClientController::class);
|
||||
@@ -0,0 +1,64 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Integration\Controllers;
|
||||
|
||||
use App\Domains\Client\Models\Client;
|
||||
use App\Domains\Integration\Models\Integration;
|
||||
use App\Domains\Integration\Requests\StoreClientIntegrationRequest;
|
||||
use App\Domains\Integration\Services\ClientIntegrationService;
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
|
||||
class ClientIntegrationController extends Controller
|
||||
{
|
||||
public function __construct(
|
||||
private readonly ClientIntegrationService $clientIntegrationService,
|
||||
) {}
|
||||
|
||||
public function index(Client $client): JsonResponse
|
||||
{
|
||||
return response()->json($this->clientIntegrationService->getAllForClient($client));
|
||||
}
|
||||
|
||||
public function show(Client $client, string $integrationCode): JsonResponse
|
||||
{
|
||||
$integration = $this->clientIntegrationService->getClientIntegration($client, $integrationCode);
|
||||
|
||||
if (! $integration) {
|
||||
return response()->json([
|
||||
'code' => 'integration.not_configured',
|
||||
'message' => __('api.integration.not_configured'),
|
||||
], 404);
|
||||
}
|
||||
|
||||
return response()->json($integration);
|
||||
}
|
||||
|
||||
public function store(
|
||||
StoreClientIntegrationRequest $request,
|
||||
Client $client,
|
||||
string $integrationCode,
|
||||
): JsonResponse {
|
||||
$integration = Integration::query()
|
||||
->where('integration_code', $integrationCode)
|
||||
->firstOrFail();
|
||||
|
||||
try {
|
||||
$this->clientIntegrationService->updateOrCreateIntegration(
|
||||
$client,
|
||||
$integration,
|
||||
$request->input('integration_data', []),
|
||||
);
|
||||
|
||||
return response()->json([
|
||||
'code' => 'integration.configured',
|
||||
'message' => __('api.integration.configured'),
|
||||
]);
|
||||
} catch (\Exception $exception) {
|
||||
return response()->json([
|
||||
'code' => 'integration.validation_failed',
|
||||
'message' => __('api.integration.validation_failed', ['error' => $exception->getMessage()]),
|
||||
], 400);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace App\Domains\Integration\Controllers;
|
||||
|
||||
use App\Domains\Client\Models\Client;
|
||||
use App\Domains\Integration\Requests\TelepagosWebhookRequest;
|
||||
use App\Domains\Integration\Services\TelepagosWebhookService;
|
||||
use App\Http\Controllers\Controller;
|
||||
@@ -12,12 +13,12 @@ class TelepagosWebhookController extends Controller
|
||||
/**
|
||||
* Handle the incoming Telepagos webhook.
|
||||
*/
|
||||
public function handle(TelepagosWebhookRequest $request, string $tenantCodigo, TelepagosWebhookService $service): JsonResponse
|
||||
public function handle(TelepagosWebhookRequest $request, Client $client, TelepagosWebhookService $service): JsonResponse
|
||||
{
|
||||
try {
|
||||
$cashinId = $request->validated('id');
|
||||
|
||||
$service->handleWebhook($tenantCodigo, $cashinId);
|
||||
$service->handleWebhook($client, $cashinId);
|
||||
|
||||
return response()->json(['status' => 'success']);
|
||||
} catch (\Exception $e) {
|
||||
|
||||
@@ -1,60 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Integration\Controllers;
|
||||
|
||||
use App\Domains\Integration\Models\Integration;
|
||||
use App\Domains\Integration\Requests\StoreTenantIntegrationRequest;
|
||||
use App\Domains\Integration\Services\TenantIntegrationService;
|
||||
use Illuminate\Routing\Controller;
|
||||
|
||||
class TenantIntegrationController extends Controller
|
||||
{
|
||||
protected TenantIntegrationService $tenantIntegrationService;
|
||||
|
||||
public function __construct(TenantIntegrationService $tenantIntegrationService)
|
||||
{
|
||||
$this->tenantIntegrationService = $tenantIntegrationService;
|
||||
}
|
||||
|
||||
public function index(string $tenantCode)
|
||||
{
|
||||
return response()->json($this->tenantIntegrationService->getAllForTenant($tenantCode));
|
||||
}
|
||||
|
||||
public function show(string $tenantCode, string $integrationCode)
|
||||
{
|
||||
$integration = $this->tenantIntegrationService->getTenantIntegration($tenantCode, $integrationCode);
|
||||
|
||||
if (! $integration) {
|
||||
return response()->json([
|
||||
'code' => 'integration.not_configured',
|
||||
'message' => __('api.integration.not_configured'),
|
||||
], 404);
|
||||
}
|
||||
|
||||
return response()->json($integration);
|
||||
}
|
||||
|
||||
public function store(StoreTenantIntegrationRequest $request, string $tenantCode, string $integrationCode)
|
||||
{
|
||||
$integration = Integration::where('integration_code', $integrationCode)->firstOrFail();
|
||||
|
||||
try {
|
||||
$this->tenantIntegrationService->updateOrCreateIntegration(
|
||||
$tenantCode,
|
||||
$integration,
|
||||
$request->input('integration_data', [])
|
||||
);
|
||||
|
||||
return response()->json([
|
||||
'code' => 'integration.configured',
|
||||
'message' => __('api.integration.configured'),
|
||||
]);
|
||||
} catch (\Exception $e) {
|
||||
return response()->json([
|
||||
'code' => 'integration.validation_failed',
|
||||
'message' => __('api.integration.validation_failed', ['error' => $e->getMessage()]),
|
||||
], 400);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,16 +2,18 @@
|
||||
|
||||
namespace App\Domains\Integration\Models;
|
||||
|
||||
use App\Domains\Client\Models\Client;
|
||||
use App\Domains\Integration\Casts\EncryptedIntegrationData;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
class TenantIntegration extends Model
|
||||
class ClientIntegration extends Model
|
||||
{
|
||||
protected $table = 'tenant_integration';
|
||||
protected $hidden = ['integration_data'];
|
||||
|
||||
protected $fillable = [
|
||||
'client_id',
|
||||
'integration_code',
|
||||
'tenant_code',
|
||||
'integration_data',
|
||||
];
|
||||
|
||||
@@ -19,7 +21,14 @@ class TenantIntegration extends Model
|
||||
'integration_data' => EncryptedIntegrationData::class,
|
||||
];
|
||||
|
||||
public function integration()
|
||||
/** @return BelongsTo<Client, $this> */
|
||||
public function client(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Client::class);
|
||||
}
|
||||
|
||||
/** @return BelongsTo<Integration, $this> */
|
||||
public function integration(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Integration::class, 'integration_code', 'integration_code');
|
||||
}
|
||||
@@ -13,16 +13,16 @@ class Integration extends Model
|
||||
'name',
|
||||
'url',
|
||||
'integration_data_schema',
|
||||
'requires_tenant_configuration',
|
||||
'requires_client_configuration',
|
||||
];
|
||||
|
||||
protected $casts = [
|
||||
'integration_data_schema' => 'array',
|
||||
'requires_tenant_configuration' => 'boolean',
|
||||
'requires_client_configuration' => 'boolean',
|
||||
];
|
||||
|
||||
public function tenantIntegrations()
|
||||
|
||||
public function clientIntegrations()
|
||||
{
|
||||
return $this->hasMany(TenantIntegration::class, 'integration_code', 'integration_code');
|
||||
return $this->hasMany(ClientIntegration::class, 'integration_code', 'integration_code');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@ use App\Domains\Integration\Models\Integration;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
class StoreTenantIntegrationRequest extends FormRequest
|
||||
class StoreClientIntegrationRequest extends FormRequest
|
||||
{
|
||||
protected ?Integration $integrationModel = null;
|
||||
|
||||
@@ -15,10 +15,12 @@ class StoreTenantIntegrationRequest extends FormRequest
|
||||
return true;
|
||||
}
|
||||
|
||||
protected function prepareForValidation()
|
||||
protected function prepareForValidation(): void
|
||||
{
|
||||
$integrationCode = $this->route('integration_code');
|
||||
$this->integrationModel = Integration::where('integration_code', $integrationCode)->first();
|
||||
$this->integrationModel = Integration::query()
|
||||
->where('integration_code', $integrationCode)
|
||||
->first();
|
||||
|
||||
if (! $this->integrationModel) {
|
||||
throw ValidationException::withMessages([
|
||||
@@ -31,11 +33,8 @@ class StoreTenantIntegrationRequest extends FormRequest
|
||||
{
|
||||
$rules = [];
|
||||
|
||||
// Dynamic validation rules based on the integration data schema
|
||||
if ($this->integrationModel && $this->integrationModel->integration_data_schema) {
|
||||
foreach ($this->integrationModel->integration_data_schema as $field => $rule) {
|
||||
$rules['integration_data.'.$field] = $rule;
|
||||
}
|
||||
foreach ($this->integrationModel?->integration_data_schema ?? [] as $field => $rule) {
|
||||
$rules['integration_data.'.$field] = $rule;
|
||||
}
|
||||
|
||||
return $rules;
|
||||
@@ -18,7 +18,7 @@ class StoreIntegrationRequest extends FormRequest
|
||||
'name' => ['required', 'string', 'max:255'],
|
||||
'url' => ['nullable', 'url', 'max:255'],
|
||||
'integration_data_schema' => ['nullable', 'array'],
|
||||
'requires_tenant_configuration' => ['sometimes', 'boolean'],
|
||||
'requires_client_configuration' => ['sometimes', 'boolean'],
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,14 +14,14 @@ class UpdateIntegrationRequest extends FormRequest
|
||||
public function rules(): array
|
||||
{
|
||||
$integration = $this->route('integration');
|
||||
|
||||
|
||||
return [
|
||||
'name' => ['sometimes', 'required', 'string', 'max:255'],
|
||||
'url' => ['nullable', 'url', 'max:255'],
|
||||
'integration_data_schema' => ['nullable', 'array'],
|
||||
'requires_tenant_configuration' => ['sometimes', 'boolean'],
|
||||
'requires_client_configuration' => ['sometimes', 'boolean'],
|
||||
// the code shouldn't ideally be updatable, but if it is:
|
||||
'integration_code' => ['sometimes', 'required', 'string', 'unique:integrations,integration_code,' . ($integration->id ?? '')],
|
||||
'integration_code' => ['sometimes', 'required', 'string', 'unique:integrations,integration_code,'.($integration->id ?? '')],
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,58 +2,54 @@
|
||||
|
||||
namespace App\Domains\Integration\Services;
|
||||
|
||||
use App\Domains\Client\Models\Client;
|
||||
use App\Domains\Integration\Models\ClientIntegration;
|
||||
use App\Domains\Integration\Models\Integration;
|
||||
use App\Domains\Integration\Models\TenantIntegration;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Http\Client\PendingRequest;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use Exception;
|
||||
use Illuminate\Http\Client\PendingRequest;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
|
||||
abstract class BaseIntegrationService
|
||||
{
|
||||
/**
|
||||
* The unique code of the integration.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected string $integrationCode;
|
||||
|
||||
/**
|
||||
* The current tenant code.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected string $tenantCode;
|
||||
|
||||
protected ?Tenant $tenant = null;
|
||||
|
||||
protected ?Client $clientContext = null;
|
||||
|
||||
/**
|
||||
* The integration model instance.
|
||||
*
|
||||
* @var Integration|null
|
||||
*/
|
||||
protected ?Integration $integration = null;
|
||||
|
||||
/**
|
||||
* The tenant-specific integration model instance.
|
||||
*
|
||||
* @var TenantIntegration|null
|
||||
* The client-owned integration configuration.
|
||||
*/
|
||||
protected ?TenantIntegration $tenantIntegration = null;
|
||||
protected ?ClientIntegration $clientIntegration = 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
|
||||
{
|
||||
@@ -63,53 +59,69 @@ abstract class BaseIntegrationService
|
||||
/**
|
||||
* 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->tenant = Tenant::query()->with('client')->where('codigo', $tenantCode)->firstOrFail();
|
||||
$this->clientContext = $this->tenant->client;
|
||||
$this->loadIntegration();
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function forClient(Client|string $client): self
|
||||
{
|
||||
$this->clientContext = $client instanceof Client
|
||||
? $client
|
||||
: Client::query()->where('code', $client)->firstOrFail();
|
||||
$this->tenant = null;
|
||||
$this->loadIntegration();
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Load the Integration and TenantIntegration models.
|
||||
* Load the integration definition and its client-owned configuration.
|
||||
*
|
||||
* @throws Exception
|
||||
*/
|
||||
protected function loadIntegration(): void
|
||||
{
|
||||
if (empty($this->integrationCode)) {
|
||||
throw new Exception("Integration code is not set.");
|
||||
throw new Exception('Integration code is not set.');
|
||||
}
|
||||
|
||||
$this->integration = Integration::where('integration_code', $this->integrationCode)->first();
|
||||
if (!$this->integration) {
|
||||
if (! $this->integration) {
|
||||
throw new Exception("Integration with code '{$this->integrationCode}' not found.");
|
||||
}
|
||||
|
||||
$this->tenantIntegration = TenantIntegration::where('tenant_code', $this->tenantCode)
|
||||
if (! $this->clientContext) {
|
||||
throw new Exception('Client context is not set.');
|
||||
}
|
||||
|
||||
$this->clientIntegration = ClientIntegration::where('client_id', $this->clientContext->id)
|
||||
->where('integration_code', $this->integrationCode)
|
||||
->first();
|
||||
|
||||
if (!$this->tenantIntegration && $this->integration->requires_tenant_configuration) {
|
||||
throw new Exception("Tenant '{$this->tenantCode}' does not have integration '{$this->integrationCode}' configured.");
|
||||
if (! $this->clientIntegration && $this->integration->requires_client_configuration) {
|
||||
throw new Exception("Client '{$this->clientContext->code}' 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.");
|
||||
if (! $this->integration) {
|
||||
throw new Exception('Integration is not loaded. Call forTenant() or forClient() first.');
|
||||
}
|
||||
|
||||
$baseUrl = rtrim($this->integration->url, '/');
|
||||
@@ -119,25 +131,20 @@ abstract class BaseIntegrationService
|
||||
}
|
||||
|
||||
/**
|
||||
* Get integration setting by key from tenant's integration data.
|
||||
*
|
||||
* @param string $key
|
||||
* @param mixed $default
|
||||
* @return mixed
|
||||
* Get an integration setting from the client-owned configuration.
|
||||
*/
|
||||
protected function getIntegrationSetting(string $key, mixed $default = null): mixed
|
||||
{
|
||||
if (!$this->tenantIntegration || !$this->tenantIntegration->integration_data) {
|
||||
if (! $this->clientIntegration || ! $this->clientIntegration->integration_data) {
|
||||
return $default;
|
||||
}
|
||||
|
||||
return $this->tenantIntegration->integration_data[$key] ?? $default;
|
||||
return $this->clientIntegration->integration_data[$key] ?? $default;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a pre-configured HTTP client builder.
|
||||
*
|
||||
* @return PendingRequest
|
||||
* @throws Exception
|
||||
*/
|
||||
public function client(): PendingRequest
|
||||
@@ -148,17 +155,13 @@ abstract class BaseIntegrationService
|
||||
|
||||
/**
|
||||
* Get the headers for the integration.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
abstract public function getHeaders(): array;
|
||||
|
||||
/**
|
||||
* Hook called after the integration is configured for the tenant.
|
||||
* Hook called after the integration is configured for the client.
|
||||
* Can be used to validate credentials or perform initial setups.
|
||||
* Throw an Exception on failure.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function onSetup(): void
|
||||
{
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Integration\Services;
|
||||
|
||||
use App\Domains\Client\Models\Client;
|
||||
use App\Domains\Integration\Models\ClientIntegration;
|
||||
use App\Domains\Integration\Models\Integration;
|
||||
use Illuminate\Database\Eloquent\Collection;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
class ClientIntegrationService
|
||||
{
|
||||
public function getClientIntegration(Client $client, string $integrationCode): ?ClientIntegration
|
||||
{
|
||||
return $client->integrations()
|
||||
->where('integration_code', $integrationCode)
|
||||
->first();
|
||||
}
|
||||
|
||||
/** @return Collection<int, ClientIntegration> */
|
||||
public function getAllForClient(Client $client): Collection
|
||||
{
|
||||
return $client->integrations()->with('integration')->get();
|
||||
}
|
||||
|
||||
public function updateOrCreateIntegration(
|
||||
Client $client,
|
||||
Integration $integration,
|
||||
array $data,
|
||||
): ClientIntegration {
|
||||
return DB::transaction(function () use ($client, $integration, $data): ClientIntegration {
|
||||
$clientIntegration = ClientIntegration::query()->updateOrCreate(
|
||||
[
|
||||
'client_id' => $client->id,
|
||||
'integration_code' => $integration->integration_code,
|
||||
],
|
||||
['integration_data' => $data],
|
||||
);
|
||||
|
||||
$service = $this->resolveService($integration->integration_code);
|
||||
$service?->forClient($client)->onSetup();
|
||||
|
||||
return $clientIntegration;
|
||||
});
|
||||
}
|
||||
|
||||
protected function resolveService(string $integrationCode): ?BaseIntegrationService
|
||||
{
|
||||
return match ($integrationCode) {
|
||||
'email' => new MailService,
|
||||
'telepagos', 'telepagos_homo' => new TelepagosIntegrationService($integrationCode),
|
||||
default => null,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
namespace App\Domains\Integration\Services;
|
||||
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use App\Domains\Client\Models\Client;
|
||||
use Exception;
|
||||
use Illuminate\Contracts\Mail\Factory as MailFactory;
|
||||
use Illuminate\Contracts\Mail\Mailer;
|
||||
@@ -27,9 +27,7 @@ class MailService extends BaseIntegrationService
|
||||
|
||||
private ?Mailer $mailer = null;
|
||||
|
||||
private ?Tenant $tenant = null;
|
||||
|
||||
private bool $usesTenantMailer = false;
|
||||
private bool $usesClientMailer = false;
|
||||
|
||||
public function __construct(?MailFactory $mailFactory = null)
|
||||
{
|
||||
@@ -40,16 +38,28 @@ class MailService extends BaseIntegrationService
|
||||
{
|
||||
parent::forTenant($tenantCode);
|
||||
|
||||
$this->tenant = Tenant::query()
|
||||
->where('codigo', $tenantCode)
|
||||
->firstOrFail();
|
||||
|
||||
if ($this->tenantIntegration) {
|
||||
if ($this->clientIntegration) {
|
||||
$this->mailer = $this->resolveMailer();
|
||||
$this->usesTenantMailer = true;
|
||||
$this->usesClientMailer = true;
|
||||
} else {
|
||||
$this->mailer = $this->mailFactory->mailer();
|
||||
$this->usesTenantMailer = false;
|
||||
$this->usesClientMailer = false;
|
||||
}
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function forClient(Client|string $client): self
|
||||
{
|
||||
parent::forClient($client);
|
||||
$this->tenant = $this->clientContext?->tenants()->first();
|
||||
|
||||
if ($this->clientIntegration) {
|
||||
$this->mailer = $this->resolveMailer();
|
||||
$this->usesClientMailer = true;
|
||||
} else {
|
||||
$this->mailer = $this->mailFactory->mailer();
|
||||
$this->usesClientMailer = false;
|
||||
}
|
||||
|
||||
return $this;
|
||||
@@ -63,7 +73,7 @@ class MailService extends BaseIntegrationService
|
||||
public function send(string|array $recipient, string $subject, string $content): void
|
||||
{
|
||||
if (! $this->mailer || ! $this->tenant) {
|
||||
throw new Exception('MailService no está configurado. Llamá a forTenant() primero.');
|
||||
throw new Exception('MailService no está configurado. Llamá a forTenant() o forClient() primero.');
|
||||
}
|
||||
|
||||
$this->tenant->loadMissing(['headerLogo', 'footerLogo']);
|
||||
@@ -91,43 +101,50 @@ class MailService extends BaseIntegrationService
|
||||
|
||||
public function mailerName(): string
|
||||
{
|
||||
return $this->usesTenantMailer
|
||||
? 'tenant-smtp'
|
||||
return $this->usesClientMailer
|
||||
? 'client-smtp'
|
||||
: (string) config('mail.default');
|
||||
}
|
||||
|
||||
public function onSetup(): void
|
||||
{
|
||||
if (! $this->tenant) {
|
||||
throw new Exception('MailService no está configurado. Llamá a forTenant() primero.');
|
||||
if (! $this->mailer || ! $this->clientContext) {
|
||||
throw new Exception('MailService no está configurado. Llamá a forTenant() o forClient() primero.');
|
||||
}
|
||||
|
||||
$recipient = $this->getIntegrationSetting('MAIL_FROM_ADDRESS');
|
||||
|
||||
if (! is_string($recipient) || $recipient === '') {
|
||||
throw new InvalidArgumentException('Falta MAIL_FROM_ADDRESS en la configuración SMTP del tenant.');
|
||||
throw new InvalidArgumentException('Falta MAIL_FROM_ADDRESS en la configuración SMTP del cliente.');
|
||||
}
|
||||
|
||||
$this->send(
|
||||
$recipient,
|
||||
'Configuración de correo validada',
|
||||
'<h1 style="margin: 0 0 20px;">Configuración de correo validada</h1>'
|
||||
.'<p>La integración SMTP de '.e($this->tenant->nombre).' fue configurada correctamente.</p>'
|
||||
.'<p style="color: #64748b; font-size: 13px;">Este mensaje fue enviado automáticamente para validar las credenciales de correo.</p>',
|
||||
$subject = 'Configuración de correo validada';
|
||||
$content = '<h1 style="margin: 0 0 20px;">Configuración de correo validada</h1>'
|
||||
.'<p>La integración SMTP de '.e($this->clientContext->name).' fue configurada correctamente.</p>'
|
||||
.'<p style="color: #64748b; font-size: 13px;">Este mensaje fue enviado automáticamente para validar las credenciales de correo.</p>';
|
||||
|
||||
if ($this->tenant) {
|
||||
$this->send($recipient, $subject, $content);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$this->mailer->to($recipient)->send(
|
||||
(new Mailable)->subject($subject)->html($content)
|
||||
);
|
||||
}
|
||||
|
||||
private function resolveMailer(): Mailer
|
||||
{
|
||||
$data = $this->tenantIntegration?->integration_data;
|
||||
$data = $this->clientIntegration?->integration_data;
|
||||
|
||||
if (! is_array($data)) {
|
||||
throw new InvalidArgumentException('La configuración SMTP del tenant no es válida.');
|
||||
throw new InvalidArgumentException('La configuración SMTP del cliente no es válida.');
|
||||
}
|
||||
|
||||
foreach (self::REQUIRED_SMTP_FIELDS as $field) {
|
||||
if (! array_key_exists($field, $data) || $data[$field] === null || $data[$field] === '') {
|
||||
throw new InvalidArgumentException("Falta {$field} en la configuración SMTP del tenant.");
|
||||
throw new InvalidArgumentException("Falta {$field} en la configuración SMTP del cliente.");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -137,7 +154,7 @@ class MailService extends BaseIntegrationService
|
||||
}
|
||||
|
||||
$mailer = $this->mailFactory->build([
|
||||
'name' => "tenant-smtp-{$this->tenantCode}",
|
||||
'name' => 'client-smtp-'.$this->clientContext?->id,
|
||||
'transport' => 'smtp',
|
||||
'scheme' => $data['MAIL_SCHEME'] ?? null,
|
||||
'host' => $data['MAIL_HOST'],
|
||||
@@ -150,7 +167,7 @@ class MailService extends BaseIntegrationService
|
||||
|
||||
$mailer->alwaysFrom(
|
||||
$data['MAIL_FROM_ADDRESS'],
|
||||
$data['MAIL_FROM_NAME'] ?? $this->tenant?->nombre,
|
||||
$data['MAIL_FROM_NAME'] ?? $this->clientContext?->name,
|
||||
);
|
||||
|
||||
return $mailer;
|
||||
|
||||
@@ -2,39 +2,37 @@
|
||||
|
||||
namespace App\Domains\Integration\Services;
|
||||
|
||||
use Carbon\Carbon;
|
||||
use Exception;
|
||||
use Illuminate\Http\Client\Response;
|
||||
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')) {
|
||||
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(),
|
||||
'Authorization' => 'Bearer '.$this->getToken(),
|
||||
'Content-Type' => 'application/json',
|
||||
'Accept' => 'application/json',
|
||||
];
|
||||
@@ -43,16 +41,15 @@ class TelepagosIntegrationService extends BaseIntegrationService
|
||||
/**
|
||||
* 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.");
|
||||
if (! $this->clientIntegration || ! $this->clientContext) {
|
||||
throw new Exception('Client integration is not loaded. Call forTenant() or forClient() first.');
|
||||
}
|
||||
|
||||
$cacheKey = "integration_token:{$this->tenantCode}:{$this->integrationCode}";
|
||||
$cacheKey = "integration_token:{$this->clientContext->id}:{$this->integrationCode}";
|
||||
|
||||
$token = Cache::get($cacheKey);
|
||||
|
||||
@@ -66,7 +63,6 @@ class TelepagosIntegrationService extends BaseIntegrationService
|
||||
/**
|
||||
* Authenticate with Telepagos and cache the returned token.
|
||||
*
|
||||
* @return string
|
||||
* @throws Exception
|
||||
*/
|
||||
public function login(): string
|
||||
@@ -75,7 +71,7 @@ class TelepagosIntegrationService extends BaseIntegrationService
|
||||
$password = $this->getIntegrationSetting('password');
|
||||
|
||||
if (empty($username) || empty($password)) {
|
||||
throw new Exception("Missing username or password in Telepagos integration settings.");
|
||||
throw new Exception('Missing username or password in Telepagos integration settings.');
|
||||
}
|
||||
|
||||
$url = $this->getUrl('/v2/auth/token');
|
||||
@@ -92,15 +88,15 @@ class TelepagosIntegrationService extends BaseIntegrationService
|
||||
$token = $data['token'] ?? null;
|
||||
$expiresAtStr = $data['expires_at'] ?? null;
|
||||
|
||||
if (!$token || !$expiresAtStr) {
|
||||
throw new Exception("Telepagos authentication response is missing token or expires_at.");
|
||||
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}";
|
||||
$cacheKey = "integration_token:{$this->clientContext->id}:{$this->integrationCode}";
|
||||
Cache::put($cacheKey, $token, $ttlSeconds);
|
||||
|
||||
return $token;
|
||||
@@ -108,21 +104,16 @@ class TelepagosIntegrationService extends BaseIntegrationService
|
||||
|
||||
/**
|
||||
* 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
|
||||
protected function sendRequest(string $method, string $endpoint, array $data = []): Response
|
||||
{
|
||||
$response = $this->client()->$method($endpoint, $data);
|
||||
|
||||
if ($response->status() === 401) {
|
||||
Log::info("Telepagos 401 Unauthorized. Refreshing token and retrying...");
|
||||
|
||||
Log::info('Telepagos 401 Unauthorized. Refreshing token and retrying...');
|
||||
|
||||
$this->clearToken();
|
||||
|
||||
|
||||
$response = $this->client()->$method($endpoint, $data);
|
||||
}
|
||||
|
||||
@@ -132,10 +123,6 @@ class TelepagosIntegrationService extends BaseIntegrationService
|
||||
/**
|
||||
* 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
|
||||
@@ -154,8 +141,8 @@ class TelepagosIntegrationService extends BaseIntegrationService
|
||||
/**
|
||||
* Get the details of a cash-in payment.
|
||||
*
|
||||
* @param int $cashinId
|
||||
* @return array
|
||||
* @param int $cashinId
|
||||
*
|
||||
* @throws Exception
|
||||
*/
|
||||
public function getCashinDetails(string $cashinId): array
|
||||
@@ -170,25 +157,21 @@ class TelepagosIntegrationService extends BaseIntegrationService
|
||||
/**
|
||||
* 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
|
||||
protected function handleResponse(Response $response, string $actionDescription, array $context = []): array
|
||||
{
|
||||
if ($response->failed() || $response->json('status') !== 'ok') {
|
||||
$errorMessage = $response->json('message') ?? $response->body();
|
||||
@@ -205,19 +188,20 @@ class TelepagosIntegrationService extends BaseIntegrationService
|
||||
|
||||
/**
|
||||
* Clear the cached token.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function clearToken(): void
|
||||
{
|
||||
$cacheKey = "integration_token:{$this->tenantCode}:{$this->integrationCode}";
|
||||
if (! $this->clientContext) {
|
||||
return;
|
||||
}
|
||||
|
||||
$cacheKey = "integration_token:{$this->clientContext->id}:{$this->integrationCode}";
|
||||
Cache::forget($cacheKey);
|
||||
}
|
||||
|
||||
/**
|
||||
* Perform initial setup validation for Telepagos.
|
||||
*
|
||||
* @return void
|
||||
* @throws Exception
|
||||
*/
|
||||
public function onSetup(): void
|
||||
|
||||
@@ -2,11 +2,11 @@
|
||||
|
||||
namespace App\Domains\Integration\Services;
|
||||
|
||||
use App\Domains\Client\Models\Client;
|
||||
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\DB;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
@@ -22,12 +22,10 @@ class TelepagosWebhookService
|
||||
*
|
||||
* @throws Exception
|
||||
*/
|
||||
public function handleWebhook(string $tenantCodigo, string $cashinId): void
|
||||
public function handleWebhook(Client $client, string $cashinId): void
|
||||
{
|
||||
$tenant = Tenant::where('codigo', $tenantCodigo)->firstOrFail();
|
||||
|
||||
$telepagosService = new TelepagosIntegrationService;
|
||||
$telepagosService->forTenant($tenant->codigo);
|
||||
$telepagosService->forClient($client);
|
||||
|
||||
try {
|
||||
$details = $telepagosService->getCashinDetails($cashinId);
|
||||
@@ -52,7 +50,8 @@ class TelepagosWebhookService
|
||||
|
||||
$dni = substr($cuit, 2, -1);
|
||||
|
||||
$compra = Purchase::where('tenant_codigo', $tenantCodigo)
|
||||
$tenantCodes = $client->tenants()->pluck('codigo');
|
||||
$purchases = Purchase::whereIn('tenant_codigo', $tenantCodes)
|
||||
->where('transfer_payer_dni', $dni)
|
||||
->whereIn('status', [
|
||||
Purchase::STATUS_CREATED,
|
||||
@@ -61,10 +60,13 @@ class TelepagosWebhookService
|
||||
->where('payment_method', 'transfer')
|
||||
->where('total', $amount)
|
||||
->latest()
|
||||
->first();
|
||||
->limit(2)
|
||||
->get();
|
||||
|
||||
$compra = $purchases->count() === 1 ? $purchases->first() : null;
|
||||
|
||||
if (! $compra) {
|
||||
Log::warning("Telepagos webhook: No matching purchase found for DNI {$dni} and amount {$amount} for cashin {$cashinId}");
|
||||
Log::warning("Telepagos webhook: Expected one matching purchase for client {$client->code}, DNI {$dni}, amount {$amount} and cashin {$cashinId}; found {$purchases->count()}");
|
||||
|
||||
return;
|
||||
}
|
||||
@@ -91,6 +93,12 @@ class TelepagosWebhookService
|
||||
return;
|
||||
}
|
||||
|
||||
if (! $client->tenants()->where('codigo', $compra->tenant_codigo)->exists()) {
|
||||
Log::warning("Telepagos webhook: Purchase {$compra->id} does not belong to client {$client->code}");
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (! in_array($compra->status, [
|
||||
Purchase::STATUS_PENDING_PAYMENT,
|
||||
], true)) {
|
||||
|
||||
@@ -1,59 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Integration\Services;
|
||||
|
||||
use App\Domains\Integration\Models\Integration;
|
||||
use App\Domains\Integration\Models\TenantIntegration;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
class TenantIntegrationService
|
||||
{
|
||||
public function getTenantIntegration(string $tenantCode, string $integrationCode): ?TenantIntegration
|
||||
{
|
||||
return TenantIntegration::where('tenant_code', $tenantCode)
|
||||
->where('integration_code', $integrationCode)
|
||||
->first();
|
||||
}
|
||||
|
||||
public function getAllForTenant(string $tenantCode)
|
||||
{
|
||||
return TenantIntegration::with('integration')
|
||||
->where('tenant_code', $tenantCode)
|
||||
->get();
|
||||
}
|
||||
|
||||
public function updateOrCreateIntegration(string $tenantCode, Integration $integration, array $data): TenantIntegration
|
||||
{
|
||||
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 'email':
|
||||
return new MailService;
|
||||
case 'telepagos':
|
||||
case 'telepagos_homo':
|
||||
return new TelepagosIntegrationService($integrationCode);
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,18 +2,18 @@
|
||||
|
||||
## Propósito
|
||||
|
||||
Gestiona integraciones externas disponibles y su configuración por tenant. Incluye correo y pagos mediante Telepagos.
|
||||
Gestiona integraciones externas disponibles y su configuración por cliente. Un cliente puede agrupar múltiples tenants que comparten las mismas credenciales. Incluye correo y pagos mediante Telepagos.
|
||||
|
||||
## Modelo y seguridad
|
||||
|
||||
- `Integration`: definición global de una integración.
|
||||
- `TenantIntegration`: configuración y credenciales de una integración para un tenant.
|
||||
- `ClientIntegration`: configuración y credenciales de una integración para un cliente.
|
||||
- `EncryptedIntegrationData`: cast que protege los datos sensibles persistidos.
|
||||
- `TenantIntegrationService`: consulta y configura integraciones del tenant.
|
||||
- `ClientIntegrationService`: consulta y configura integraciones del cliente.
|
||||
|
||||
## Servicios externos
|
||||
|
||||
- `BaseIntegrationService`: base para resolver configuración, URL y cliente del tenant.
|
||||
- `BaseIntegrationService`: resuelve el cliente desde el tenant operativo y carga exclusivamente la configuración del cliente.
|
||||
- `MailService`: envío de correo usando la integración configurada.
|
||||
- `TelepagosIntegrationService`: autenticación, caché de token, generación de QR y consulta de cobros.
|
||||
- `TelepagosWebhookService`: procesa notificaciones recibidas desde Telepagos.
|
||||
@@ -21,9 +21,9 @@ Gestiona integraciones externas disponibles y su configuración por tenant. Incl
|
||||
## Endpoints
|
||||
|
||||
- CRUD global bajo `/integrations`.
|
||||
- Consulta y configuración por tenant bajo `/{tenant_code}/integrations`.
|
||||
- `POST /webhooks/telepagos/{tenant_codigo}` para notificaciones del proveedor.
|
||||
- Consulta y configuración por cliente bajo `/clients/{client}/integrations`.
|
||||
- `POST /webhooks/telepagos/{client}` para notificaciones del proveedor.
|
||||
|
||||
## Dependencias y reglas
|
||||
|
||||
Se integra con `Tenant` y con el checkout de `Purchase`. `Notification` utiliza `MailService`. Las credenciales no deben exponerse en respuestas ni logs; los webhooks deben validar su contrato antes de alterar una compra.
|
||||
Se integra con `Client`, `Tenant` y con el checkout de `Purchase`. `Notification` utiliza `MailService`. El tenant conserva el contexto operativo y de branding, pero nunca es dueño de credenciales. Las credenciales no se exponen en respuestas ni logs; los webhooks deben validar su contrato antes de alterar una compra.
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
<?php
|
||||
|
||||
use App\Domains\Integration\Controllers\ClientIntegrationController;
|
||||
use App\Domains\Integration\Controllers\IntegrationController;
|
||||
use App\Domains\Integration\Controllers\TenantIntegrationController;
|
||||
use App\Domains\Integration\Controllers\TelepagosWebhookController;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
|
||||
Route::group(['prefix' => 'integrations'], function () {
|
||||
@@ -12,10 +13,10 @@ Route::group(['prefix' => 'integrations'], function () {
|
||||
Route::delete('/{integration}', [IntegrationController::class, 'destroy']);
|
||||
});
|
||||
|
||||
Route::group(['prefix' => '{tenant_code}/integrations'], function () {
|
||||
Route::get('/', [TenantIntegrationController::class, 'index']);
|
||||
Route::get('/{integration_code}', [TenantIntegrationController::class, 'show']);
|
||||
Route::post('/{integration_code}', [TenantIntegrationController::class, 'store']);
|
||||
Route::group(['prefix' => 'clients/{client}/integrations'], function () {
|
||||
Route::get('/', [ClientIntegrationController::class, 'index']);
|
||||
Route::get('/{integration_code}', [ClientIntegrationController::class, 'show']);
|
||||
Route::put('/{integration_code}', [ClientIntegrationController::class, 'store']);
|
||||
});
|
||||
|
||||
Route::post('webhooks/telepagos/{tenant_codigo}', [\App\Domains\Integration\Controllers\TelepagosWebhookController::class, 'handle']);
|
||||
Route::post('webhooks/telepagos/{client}', [TelepagosWebhookController::class, 'handle']);
|
||||
|
||||
@@ -7,6 +7,7 @@ use App\Domains\Catalog\Enums\GroupLayout;
|
||||
use App\Domains\Catalog\Enums\ProductLayout;
|
||||
use App\Domains\Catalog\Models\CatalogItem;
|
||||
use App\Domains\Catalog\Models\Category;
|
||||
use App\Domains\Client\Models\Client;
|
||||
use App\Domains\Event\Models\EventDate;
|
||||
use App\Domains\Menu\Models\Menu;
|
||||
use App\Domains\Menu\Models\TenantMenu;
|
||||
@@ -16,8 +17,10 @@ use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
#[Fillable([
|
||||
'client_id',
|
||||
'codigo',
|
||||
'nombre',
|
||||
'dominio',
|
||||
@@ -64,6 +67,28 @@ class Tenant extends Model
|
||||
return 'codigo';
|
||||
}
|
||||
|
||||
protected static function booted(): void
|
||||
{
|
||||
static::creating(function (Tenant $tenant): void {
|
||||
if ($tenant->client_id !== null || ! Schema::hasTable('clients')) {
|
||||
return;
|
||||
}
|
||||
|
||||
$client = Client::query()->firstOrCreate(
|
||||
['code' => $tenant->codigo],
|
||||
['name' => $tenant->nombre],
|
||||
);
|
||||
|
||||
$tenant->client()->associate($client);
|
||||
});
|
||||
}
|
||||
|
||||
/** @return BelongsTo<Client, $this> */
|
||||
public function client(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Client::class);
|
||||
}
|
||||
|
||||
public function requiresScannerCategoryValidation(): bool
|
||||
{
|
||||
return $this->scanner_category_validation_enabled;
|
||||
|
||||
@@ -41,6 +41,7 @@ class StoreTenantRequest extends FormRequest
|
||||
$logoRule = ['required', new ImageOrBase64Rule];
|
||||
|
||||
return array_merge([
|
||||
'client_id' => ['sometimes', 'integer', Rule::exists('clients', 'id')],
|
||||
'codigo' => ['required', 'string', 'max:255', Rule::unique('tenants', 'codigo')],
|
||||
'nombre' => ['required', 'string', 'max:255'],
|
||||
'dominio' => [
|
||||
|
||||
@@ -46,6 +46,7 @@ class UpdateTenantRequest extends FormRequest
|
||||
$logoRule = ['nullable', new ImageOrBase64Rule];
|
||||
|
||||
return [
|
||||
'client_id' => ['sometimes', 'integer', Rule::exists('clients', 'id')],
|
||||
'codigo' => [
|
||||
'nullable',
|
||||
'string',
|
||||
|
||||
@@ -24,6 +24,7 @@ class TenantResource extends JsonResource
|
||||
{
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'client_id' => $this->client_id,
|
||||
'codigo' => $this->codigo,
|
||||
'nombre' => $this->nombre,
|
||||
'dominio' => $this->dominio,
|
||||
|
||||
Reference in New Issue
Block a user