refactor(services): Documents→Document + ExchangeRate→Integrations/ExchangeRate

Two follow-ups to the Services reorg that landed in 6d1816bd.

**Documents → Document** (singular). Documents/ was the only plural subdir in app/Services/ — every other bucket (Company, Mail, Module, Pdf, Storage, Update, ExchangeRate) was singular. Renaming to Document/ normalizes the whole tree.

**ExchangeRate → Integrations/ExchangeRate**. Introduces Integrations/ as an umbrella for external-service adapter subsystems. Exchange rate providers move in first; AI providers, payment gateways, and any other driver-pattern integrations land as sibling subdirs (Integrations/Ai/, Integrations/Payment/) without another reorg. Integrations/ was chosen over Providers/ to avoid conceptual collision with Laravel's app/Providers/ — 'check the providers' shouldn't be ambiguous.

17 files moved, 21 consumer files rewritten to point at the new namespaces via literal-string replacement (same approach as the previous reorg). 350 tests pass, Pint clean.
This commit is contained in:
Darko Gjorgjijoski
2026-04-11 11:30:00 +02:00
parent 6d1816bd1b
commit 947d00a9f1
37 changed files with 47 additions and 47 deletions

View File

@@ -0,0 +1,57 @@
<?php
namespace App\Services\Integrations\ExchangeRate;
use Illuminate\Support\Facades\Http;
class CurrencyConverterDriver extends ExchangeRateDriver
{
public function getExchangeRate(string $baseCurrency, string $targetCurrency): array
{
$baseUrl = $this->getBaseUrl();
$query = "{$baseCurrency}_{$targetCurrency}";
$url = "{$baseUrl}/api/v7/convert?apiKey={$this->apiKey}&q={$query}&compact=y";
$response = Http::get($url)->json();
return array_values($response[$query]);
}
public function getSupportedCurrencies(): array
{
$baseUrl = $this->getBaseUrl();
$url = "{$baseUrl}/api/v7/currencies?apiKey={$this->apiKey}";
$response = Http::get($url)->json();
if ($response == null) {
throw new ExchangeRateException('Server not responding', 'server_error');
}
if (array_key_exists('results', $response)) {
return array_keys($response['results']);
}
throw new ExchangeRateException('Please Enter Valid Provider Key.', 'invalid_key');
}
public function validateConnection(): array
{
$baseUrl = $this->getBaseUrl();
$query = 'INR_USD';
$url = "{$baseUrl}/api/v7/convert?apiKey={$this->apiKey}&q={$query}&compact=y";
$response = Http::get($url)->json();
return array_values($response[$query]);
}
private function getBaseUrl(): string
{
$type = $this->config['type'] ?? 'FREE';
return match ($type) {
'PREMIUM' => 'https://api.currconv.com',
'PREPAID' => 'https://prepaid.currconv.com',
'FREE' => 'https://free.currconv.com',
'DEDICATED' => $this->config['url'] ?? 'https://free.currconv.com',
};
}
}

View File

@@ -0,0 +1,54 @@
<?php
namespace App\Services\Integrations\ExchangeRate;
use Illuminate\Support\Facades\Http;
class CurrencyFreakDriver extends ExchangeRateDriver
{
private string $baseUrl = 'https://api.currencyfreaks.com';
public function getExchangeRate(string $baseCurrency, string $targetCurrency): array
{
$url = "{$this->baseUrl}/latest?apikey={$this->apiKey}&symbols={$targetCurrency}&base={$baseCurrency}";
$response = Http::get($url)->json();
if (array_key_exists('success', $response) && $response['success'] == false) {
throw new ExchangeRateException($response['error']['message'], 'provider_error');
}
return array_values($response['rates']);
}
public function getSupportedCurrencies(): array
{
$url = "{$this->baseUrl}/currency-symbols";
$response = Http::get($url)->json();
if ($response == null) {
throw new ExchangeRateException('Server not responding', 'server_error');
}
$checkKey = $this->validateConnection();
return array_keys($response);
}
public function validateConnection(): array
{
$url = "{$this->baseUrl}/latest?apikey={$this->apiKey}&symbols=INR&base=USD";
$response = Http::get($url)->json();
if ($response == null) {
throw new ExchangeRateException('Server not responding', 'server_error');
}
if (array_key_exists('success', $response) && array_key_exists('error', $response)) {
if ($response['error']['status'] == 404) {
throw new ExchangeRateException('Please Enter Valid Provider Key.', 'invalid_key');
}
}
return array_values($response['rates']);
}
}

View File

@@ -0,0 +1,50 @@
<?php
namespace App\Services\Integrations\ExchangeRate;
use Illuminate\Support\Facades\Http;
class CurrencyLayerDriver extends ExchangeRateDriver
{
private string $baseUrl = 'http://api.currencylayer.com';
public function getExchangeRate(string $baseCurrency, string $targetCurrency): array
{
$url = "{$this->baseUrl}/live?access_key={$this->apiKey}&source={$baseCurrency}&currencies={$targetCurrency}";
$response = Http::get($url)->json();
if (array_key_exists('success', $response) && $response['success'] == false) {
throw new ExchangeRateException($response['error']['info'], 'provider_error');
}
return array_values($response['quotes']);
}
public function getSupportedCurrencies(): array
{
$url = "{$this->baseUrl}/list?access_key={$this->apiKey}";
$response = Http::get($url)->json();
if ($response == null) {
throw new ExchangeRateException('Server not responding', 'server_error');
}
if (array_key_exists('currencies', $response)) {
return array_keys($response['currencies']);
}
throw new ExchangeRateException('Please Enter Valid Provider Key.', 'invalid_key');
}
public function validateConnection(): array
{
$url = "{$this->baseUrl}/live?access_key={$this->apiKey}&source=INR&currencies=USD";
$response = Http::get($url)->json();
if (array_key_exists('success', $response) && $response['success'] == false) {
throw new ExchangeRateException($response['error']['info'], 'provider_error');
}
return array_values($response['quotes']);
}
}

View File

@@ -0,0 +1,34 @@
<?php
namespace App\Services\Integrations\ExchangeRate;
abstract class ExchangeRateDriver
{
public function __construct(
protected string $apiKey,
protected array $config = [],
) {}
/**
* Fetch exchange rate between two currencies.
*
* @return array Exchange rate values
*/
abstract public function getExchangeRate(string $baseCurrency, string $targetCurrency): array;
/**
* Get list of currencies supported by this provider.
*
* @return array Currency codes
*/
abstract public function getSupportedCurrencies(): array;
/**
* Validate that the API key and connection work.
*
* @return array Exchange rate values (proof of working connection)
*
* @throws ExchangeRateException
*/
abstract public function validateConnection(): array;
}

View File

@@ -0,0 +1,79 @@
<?php
namespace App\Services\Integrations\ExchangeRate;
use InvalidArgumentException;
use InvoiceShelf\Modules\Registry;
class ExchangeRateDriverFactory
{
/**
* Built-in driver fallback map.
*
* Kept as a backstop so that direct calls to register() (without going through
* the module Registry) continue to work. Built-in drivers are also registered
* via the Registry by DriverRegistryProvider — that registration is the
* canonical source for driver metadata (label, website, config_fields).
*
* @var array<string, class-string<ExchangeRateDriver>>
*/
protected static array $drivers = [
'currency_freak' => CurrencyFreakDriver::class,
'currency_layer' => CurrencyLayerDriver::class,
'open_exchange_rate' => OpenExchangeRateDriver::class,
'currency_converter' => CurrencyConverterDriver::class,
];
/**
* Register a custom exchange rate driver directly with the factory.
*
* Modules should prefer Registry::registerExchangeRateDriver() instead, which
* carries metadata (label, website, config_fields) the frontend needs to render
* a configuration form for the driver.
*/
public static function register(string $name, string $driverClass): void
{
static::$drivers[$name] = $driverClass;
}
public static function make(string $driver, string $apiKey, array $config = []): ExchangeRateDriver
{
$class = static::resolveDriverClass($driver);
if (! $class) {
throw new InvalidArgumentException("Unknown exchange rate driver: {$driver}");
}
return new $class($apiKey, $config);
}
/**
* Get all known driver names — both built-in/factory-registered and Registry-registered.
*
* @return array<int, string>
*/
public static function availableDrivers(): array
{
$local = array_keys(static::$drivers);
$registry = array_keys(Registry::allDrivers('exchange_rate'));
return array_values(array_unique(array_merge($local, $registry)));
}
/**
* Resolve a driver name to its concrete class.
*
* Checks the local $drivers map first (built-ins and factory::register() calls),
* then falls back to the module Registry.
*/
protected static function resolveDriverClass(string $driver): ?string
{
if (isset(static::$drivers[$driver])) {
return static::$drivers[$driver];
}
$meta = Registry::driverMeta('exchange_rate', $driver);
return $meta['class'] ?? null;
}
}

View File

@@ -0,0 +1,11 @@
<?php
namespace App\Services\Integrations\ExchangeRate;
class ExchangeRateException extends \RuntimeException
{
public function __construct(string $message, public readonly string $errorKey = 'exchange_rate_error')
{
parent::__construct($message);
}
}

View File

@@ -0,0 +1,120 @@
<?php
namespace App\Services\Integrations\ExchangeRate;
use App\Http\Requests\ExchangeRateProviderRequest;
use App\Models\CompanySetting;
use App\Models\ExchangeRateLog;
use App\Models\ExchangeRateProvider;
use App\Services\Integrations\ExchangeRate\ExchangeRateDriverFactory;
use App\Services\Integrations\ExchangeRate\ExchangeRateException;
class ExchangeRateProviderService
{
public function create(ExchangeRateProviderRequest $request): ExchangeRateProvider
{
return ExchangeRateProvider::create($request->getExchangeRateProviderPayload());
}
public function update(ExchangeRateProvider $provider, ExchangeRateProviderRequest $request): ExchangeRateProvider
{
$provider->update($request->getExchangeRateProviderPayload());
return $provider;
}
public function checkActiveCurrencies($request)
{
$currencies = $request->currencies;
if (empty($currencies)) {
return collect();
}
$query = ExchangeRateProvider::where('active', true);
foreach ($currencies as $currency) {
$query->orWhere(function ($q) use ($currency) {
$q->where('active', true)
->whereJsonContains('currencies', $currency);
});
}
return $query->get();
}
public function checkUpdateActiveCurrencies(ExchangeRateProvider $provider, $request)
{
$currencies = $request->currencies;
if (empty($currencies)) {
return collect();
}
$query = ExchangeRateProvider::where('id', '<>', $provider->id)
->where('active', true);
$query->where(function ($q) use ($currencies) {
foreach ($currencies as $currency) {
$q->orWhereJsonContains('currencies', $currency);
}
});
return $query->get();
}
public function checkProviderStatus($request)
{
try {
$driver = ExchangeRateDriverFactory::make(
$request['driver'],
$request['key'],
$request['driver_config'] ?? []
);
$rates = $driver->validateConnection();
return response()->json([
'exchangeRate' => $rates,
], 200);
} catch (ExchangeRateException $e) {
return respondJson($e->errorKey, $e->getMessage());
}
}
public function getExchangeRate(string $driver, string $apiKey, array $driverConfig, string $baseCurrency, string $targetCurrency)
{
try {
$driverInstance = ExchangeRateDriverFactory::make($driver, $apiKey, $driverConfig);
return response()->json([
'exchangeRate' => $driverInstance->getExchangeRate($baseCurrency, $targetCurrency),
], 200);
} catch (ExchangeRateException $e) {
return respondJson($e->errorKey, $e->getMessage());
}
}
public function getSupportedCurrencies(string $driver, string $apiKey, array $driverConfig = [])
{
try {
$driverInstance = ExchangeRateDriverFactory::make($driver, $apiKey, $driverConfig);
return response()->json([
'supportedCurrencies' => $driverInstance->getSupportedCurrencies(),
]);
} catch (ExchangeRateException $e) {
return respondJson($e->errorKey, $e->getMessage());
}
}
public function addExchangeRateLog($model): ExchangeRateLog
{
return ExchangeRateLog::create([
'exchange_rate' => $model->exchange_rate,
'company_id' => $model->company_id,
'base_currency_id' => $model->currency_id,
'currency_id' => CompanySetting::getSetting('currency', $model->company_id),
]);
}
}

View File

@@ -0,0 +1,52 @@
<?php
namespace App\Services\Integrations\ExchangeRate;
use Illuminate\Support\Facades\Http;
class OpenExchangeRateDriver extends ExchangeRateDriver
{
private string $baseUrl = 'https://openexchangerates.org/api';
public function getExchangeRate(string $baseCurrency, string $targetCurrency): array
{
$url = "{$this->baseUrl}/latest.json?app_id={$this->apiKey}&base={$baseCurrency}&symbols={$targetCurrency}";
$response = Http::get($url)->json();
if (array_key_exists('error', $response)) {
throw new ExchangeRateException($response['description'], $response['message']);
}
return array_values($response['rates']);
}
public function getSupportedCurrencies(): array
{
$url = "{$this->baseUrl}/currencies.json";
$response = Http::get($url)->json();
if ($response == null) {
throw new ExchangeRateException('Server not responding', 'server_error');
}
$checkKey = $this->validateConnection();
return array_keys($response);
}
public function validateConnection(): array
{
$url = "{$this->baseUrl}/latest.json?app_id={$this->apiKey}&base=USD&symbols=EUR";
$response = Http::get($url)->json();
if (array_key_exists('error', $response)) {
if ($response['status'] == 401) {
throw new ExchangeRateException('Please Enter Valid Provider Key.', 'invalid_key');
}
throw new ExchangeRateException($response['description'], $response['message']);
}
return array_values($response['rates']);
}
}