Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -63,3 +63,13 @@ AWS_BUCKET=
AWS_USE_PATH_STYLE_ENDPOINT=false

VITE_APP_NAME="${APP_NAME}"

CURRENCY_PROVIDER=nbu
CURRENCY_NBU_API_URL=https://bank.gov.ua/NBUStatService/v1/statdirectory/exchange
CURRENCY_FALLBACK_PROVIDER=open_er_api
CURRENCY_OPEN_ER_API_URL=https://open.er-api.com/v6/latest/UAH

CURRENCY_CACHE_TTL_MINUTES=10
CURRENCY_TIMEOUT_SECONDS=5

DUMMYJSON_BASE_URL=https://dummyjson.com
52 changes: 32 additions & 20 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
# Smartphone Catalog API

A Laravel 12 backend application that serves a smartphone product catalog with real-time currency conversion (USD to UAH) using the National Bank of Ukraine (NBU) exchange rates.
A Laravel 12 backend application that serves a smartphone product catalog with real-time currency conversion (USD, UAH, EUR) using exchange-rate providers (NBU as primary, Open ER API as fallback) with caching.

## Features

- Browse smartphone catalog sourced from [DummyJSON](https://dummyjson.com/)
- View prices in USD (original) or UAH (converted via NBU rates)
- Retrieve the current USD/UAH exchange rate from the NBU API
- Modular domain-driven architecture for the Currency module
- View prices in USD (original) or UAH/EUR (converted via exchange-rate providers)
- Retrieve the current USD/UAH and EUR/UAH exchange rates
- Modular domain-driven architecture for the Currency module with pluggable providers

## Tech Stack

Expand All @@ -24,7 +24,7 @@ Returns a list of smartphones with prices in the requested currency.

| Parameter | Type | Allowed Values | Description |
|------------|--------|----------------|--------------------------------------|
| `currency` | string | `usd`, `uah` | Currency for product prices |
| `currency` | string | `usd`, `uah`, `eur` | Currency for product prices |

**Response (200):**

Expand All @@ -44,9 +44,9 @@ Returns a list of smartphones with prices in the requested currency.

Unsupported currencies return **404**.

### `GET /api/exchangeRate/USD`
### `GET /api/exchangeRate/{currency}`

Returns the current USD to UAH exchange rate from the NBU.
Returns the current exchange rate of the given currency to UAH (currently supports `USD` and `EUR`).

**Response (200):**

Expand All @@ -66,29 +66,39 @@ Returns the current USD to UAH exchange rate from the NBU.
app/
├── Http/
│ ├── Controllers/
│ │ └── CatalogController.php # Smartphone catalog endpoint
│ │ └── CatalogController.php # Smartphone catalog endpoint
│ └── Requests/
│ └── CatalogRequest.php # Validates currency parameter
│ └── CatalogRequest.php # Validates currency parameter
├── Jobs/
│ └── TrackCatalogCurrencyUsage.php # Tracks catalog usage in background
├── Models/
│ └── User.php
│ └── CatalogCurrencyUsage.php # Catalog currency usage entries
└── Modules/
└── Currency/
├── Application/
│ ├── Facades/
│ │ └── CurrencyExchangeFacade.php # Entry point for currency operations
│ │ └── CurrencyExchangeFacade.php # Entry point for currency operations
│ └── Http/
│ ├── Controllers/
│ │ └── ExchangeRateController.php
│ └── Requests/
│ └── ExchangeRateRequest.php
├── Domain/
│ ├── ConvertedPrice.php # DTO for converted price data
│ ├── CurrencyExchangeService.php # Core exchange logic
│ └── CurrencyRate.php # DTO for rate data
│ ├── Contracts/
│ │ └── ExchangeRateProviderInterface.php # Abstraction for rate providers
│ ├── Enums/
│ │ └── CurrencyCode.php # Supported currency codes
│ ├── ConvertedPrice.php # DTO for converted price data
│ ├── CurrencyExchangeService.php # Core exchange logic
│ └── CurrencyRate.php # DTO for rate data
├── Infrastructure/
│ └── NbuApiCurrencyRepository.php # NBU API integration
│ └── Providers/
│ ├── NbuExchangeRateProvider.php # NBU API integration (primary)
│ ├── OpenErApiExchangeRateProvider.php # Open ER API integration (fallback)
│ ├── FailoverExchangeRateProvider.php # Primary + fallback composition
│ └── CachedExchangeRateProvider.php # Caching decorator
└── Providers/
└── CurrencyServiceProvider.php # DI bindings
└── CurrencyServiceProvider.php # DI bindings
```

## Getting Started
Expand Down Expand Up @@ -145,13 +155,15 @@ Tests use `Http::fake()` to mock external API calls (DummyJSON and NBU), so no n

### Test Coverage

- **Catalog endpoint** — USD/UAH responses, price conversion, currency validation, HTTP method restrictions
- **Exchange rate endpoint** — JSON structure, rate values, HTTP method restrictions
- Both endpoints verified to not require authentication
- **Catalog endpoint** — USD/UAH/EUR responses, price conversion, currency validation, HTTP method restrictions
- **Exchange rate endpoint** — USD/EUR JSON structure, rate values, HTTP method restrictions
- **Currency providers** — conversion logic, failover and caching behavior
- **Catalog usage tracking** — job execution and database records

## External APIs

| API | Purpose | URL |
|-----|---------|-----|
| DummyJSON | Smartphone product data | `https://dummyjson.com/products/category/smartphones` |
| NBU | USD/UAH exchange rate | `https://bank.gov.ua/NBUStatService/v1/statdirectory/exchange` |
| NBU | Exchange rates (primary) | `https://bank.gov.ua/NBUStatService/v1/statdirectory/exchange` |
| Open ER API | Exchange rates (fallback) | `https://open.er-api.com/v6/latest/UAH` |
43 changes: 43 additions & 0 deletions app/Actions/GetCatalogAction.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
<?php

namespace App\Actions;

use App\Jobs\TrackCatalogCurrencyUsage;
use App\Services\Catalog\SmartphoneCatalogClient;
use Modules\Currency\Application\Facades\CurrencyExchangeFacade;
use Modules\Currency\Domain\Enums\CurrencyCode;

class GetCatalogAction
{
private const DEFAULT_LIMIT = 5;

public function __construct(
private readonly CurrencyExchangeFacade $currencyExchange,
private readonly SmartphoneCatalogClient $catalogClient,
) {}

public function handle(CurrencyCode $currencyCode): array
{
TrackCatalogCurrencyUsage::dispatch($currencyCode->value, now()->toIso8601String());

$products = $this->catalogClient->getSmartphones(self::DEFAULT_LIMIT);

return collect($products)
->map(function (array $product) use ($currencyCode) {
$convertedPrice = $this->currencyExchange->convertFromUsdTo(
$currencyCode,
(float) $product['price'],
);

return [
'id' => $product['id'],
'title' => $product['title'],
'price' => $convertedPrice->convertedPrice,
'rating' => $product['rating'],
'thumbnail' => $product['thumbnail'],
];
})
->values()
->all();
}
}
32 changes: 8 additions & 24 deletions app/Http/Controllers/CatalogController.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,41 +2,25 @@

namespace App\Http\Controllers;

use App\Actions\GetCatalogAction;
use App\Http\Requests\CatalogRequest;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Http;
use Modules\Currency\Application\Facades\CurrencyExchangeFacade;
use Modules\Currency\Domain\Enums\CurrencyCode;

class CatalogController extends Controller
{
public function __construct(
private readonly CurrencyExchangeFacade $currencyExchange,
private readonly GetCatalogAction $getCatalogAction,
) {}

public function __invoke(CatalogRequest $request): JsonResponse
{
$currency = $request->route('currency');
$response = Http::get('https://dummyjson.com/products/category/smartphones', [
'limit' => 5,
]);

$products = collect($response->json('products'))->map(function (array $product) use ($currency) {
$price = $product['price'];
$currencyCode = CurrencyCode::from(strtoupper($request->route('currency')));

if (strtoupper($currency) === 'UAH') {
$converted = $this->currencyExchange->convertFromUsdToUah((int) $price);
$price = $converted->convertedPrice;
}
$products = $this->getCatalogAction->handle($currencyCode);

return [
'id' => $product['id'],
'title' => $product['title'],
'price' => $price,
'rating' => $product['rating'],
'thumbnail' => $product['thumbnail'],
];
});

return response()->json(['data' => $products]);
return response()->json([
'data' => $products,
]);
}
}
3 changes: 2 additions & 1 deletion app/Http/Requests/CatalogRequest.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,15 @@
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
use Modules\Currency\Domain\Enums\CurrencyCode;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

class CatalogRequest extends FormRequest
{
public function rules(): array
{
return [
'currency' => ['required', 'string', Rule::in(['uah', 'usd'])],
'currency' => ['required', 'string', Rule::in(CurrencyCode::catalogSupported())],
];
}

Expand Down
29 changes: 29 additions & 0 deletions app/Jobs/TrackCatalogCurrencyUsage.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<?php

namespace App\Jobs;

use App\Models\CatalogCurrencyUsage;
use Carbon\CarbonImmutable;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class TrackCatalogCurrencyUsage implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

public function __construct(
public readonly string $currency,
public readonly string $requestedAt,
) {}

public function handle(): void
{
CatalogCurrencyUsage::create([
'currency' => $this->currency,
'requested_at' => CarbonImmutable::parse($this->requestedAt),
]);
}
}
22 changes: 22 additions & 0 deletions app/Models/CatalogCurrencyUsage.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class CatalogCurrencyUsage extends Model
{
use HasFactory;

protected $table = 'catalog_currency_usages';

protected $fillable = [
'currency',
'requested_at',
];

protected $casts = [
'requested_at' => 'datetime',
];
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,33 +5,21 @@
use Modules\Currency\Domain\ConvertedPrice;
use Modules\Currency\Domain\CurrencyExchangeService;
use Modules\Currency\Domain\CurrencyRate;
use Modules\Currency\Domain\Enums\CurrencyCode;

class CurrencyExchangeFacade
{
private const string USD_CODE = 'USD';
private const string UAH_CODE = 'UAH';

public function __construct(
private readonly CurrencyExchangeService $service,
) {}

public function getUsdRate(): CurrencyRate
public function getRate(CurrencyCode $currency): CurrencyRate
{
return $this->service->findUsdRate();
return $this->service->getRate($currency);
}

public function convertFromUsdToUah(int $price): ConvertedPrice
public function convertFromUsdTo(CurrencyCode $currency, float $price): ConvertedPrice
{
$usdRate = $this->service->findUsdRate();

$convertedPrice = $price * $usdRate->rate;

return new ConvertedPrice(
originalPrice: $price,
convertedPrice: round($convertedPrice, 2),
fromCurrency: self::USD_CODE,
toCurrency: self::UAH_CODE,
rate: $usdRate->rate,
);
return $this->service->convertUsdTo($currency, $price);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
use Illuminate\Http\JsonResponse;
use Modules\Currency\Application\Facades\CurrencyExchangeFacade;
use Modules\Currency\Application\Http\Requests\ExchangeRateRequest;
use Modules\Currency\Domain\Enums\CurrencyCode;

class ExchangeRateController extends Controller
{
Expand All @@ -15,7 +16,9 @@ public function __construct(

public function __invoke(ExchangeRateRequest $request): JsonResponse
{
$rate = $this->currencyExchange->getUsdRate();
$currencyCode = CurrencyCode::from(strtoupper($request->route('currency')));

$rate = $this->currencyExchange->getRate($currencyCode);

return response()->json([
'data' => [
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,22 @@
namespace Modules\Currency\Application\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
use Modules\Currency\Domain\Enums\CurrencyCode;

class ExchangeRateRequest extends FormRequest
{
public function rules(): array
{
return [];
return [
'currency' => ['required', 'string', Rule::in(CurrencyCode::exchangeRateSupported())],
];
}

public function validationData(): array
{
return array_merge(parent::validationData(), [
'currency' => strtolower($this->route('currency')),
]);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<?php

namespace Modules\Currency\Domain\Contracts;

use Modules\Currency\Domain\CurrencyRate;

interface ExchangeRateProviderInterface
{
/**
* @return CurrencyRate[]
*/
public function getAll(): array;

public function getRate(string $currencyCode): CurrencyRate;
}
2 changes: 1 addition & 1 deletion app/Modules/Currency/Domain/ConvertedPrice.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
readonly class ConvertedPrice
{
public function __construct(
public int $originalPrice,
public float $originalPrice,
public float $convertedPrice,
public string $fromCurrency,
public string $toCurrency,
Expand Down
Loading