-
Notifications
You must be signed in to change notification settings - Fork 0
PR #613: Currency system (UAH/USD/EUR) + NBU daily sync + user preferences #623
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
51f5729
feat(currency): add ExchangeRate and UserPreferences entities + migra…
barach6662001-bit 302f175
feat(currency): NBU service, daily sync job, and currency API endpoints
barach6662001-bit b6704f0
feat(currency): frontend store, useFormatCurrency hook, Profile curre…
barach6662001-bit 3618aec
test(currency): unit + integration tests for NBU service and currency…
barach6662001-bit 71a8a2d
Merge branch 'main' into pr613-currency-system
barach6662001-bit 4d69d9b
Merge branch 'main' into pr613-currency-system
barach6662001-bit File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,23 @@ | ||
| import apiClient from './axios'; | ||
| import type { SupportedCurrency } from './me'; | ||
|
|
||
| export interface ExchangeRateDto { | ||
| code: 'USD' | 'EUR'; | ||
| date: string; // ISO date | ||
| rateToUah: number; | ||
| } | ||
|
|
||
| export interface CurrencyPreferences { | ||
| preferredCurrency: SupportedCurrency; | ||
| } | ||
|
|
||
| export const getLatestRates = () => | ||
| apiClient.get<ExchangeRateDto[]>('/api/currency/rates/latest').then((r) => r.data); | ||
|
|
||
| export const getPreferences = () => | ||
| apiClient.get<CurrencyPreferences>('/api/currency/preferences').then((r) => r.data); | ||
|
|
||
| export const updatePreferences = (preferredCurrency: SupportedCurrency) => | ||
| apiClient | ||
| .put<CurrencyPreferences>('/api/currency/preferences', { preferredCurrency }) | ||
| .then((r) => r.data); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,57 @@ | ||
| import { useCallback } from 'react'; | ||
| import { useCurrencyStore } from '../stores/currencyStore'; | ||
| import type { SupportedCurrency } from '../api/me'; | ||
|
|
||
| export interface FormatCurrencyOptions { | ||
| /** Override target currency; defaults to user's preferred. */ | ||
| target?: SupportedCurrency; | ||
| /** Fraction digits for the output amount; defaults 2. */ | ||
| fractionDigits?: number; | ||
| } | ||
|
|
||
| /** | ||
| * Returns a memoised formatter that converts a UAH amount into the user's | ||
| * preferred display currency using the last-known NBU rate. | ||
| * | ||
| * Invariants per ROADMAP "Decisions locked / Currency": | ||
| * - All stored amounts in the DB are UAH. | ||
| * - Conversion happens at presentation only. | ||
| * - Fallback: if the target currency's rate is not loaded yet (or failed), | ||
| * we return the UAH value labelled as UAH (graceful degrade). | ||
| */ | ||
| export function useFormatCurrency() { | ||
| const preferredCurrency = useCurrencyStore((s) => s.preferredCurrency); | ||
| const rates = useCurrencyStore((s) => s.rates); | ||
|
|
||
| return useCallback( | ||
| (amountUah: number | null | undefined, opts?: FormatCurrencyOptions): string => { | ||
| const value = typeof amountUah === 'number' && Number.isFinite(amountUah) ? amountUah : 0; | ||
| const target: SupportedCurrency = opts?.target ?? preferredCurrency; | ||
| const fractionDigits = opts?.fractionDigits ?? 2; | ||
|
|
||
| let displayValue = value; | ||
| let displayCode: SupportedCurrency = target; | ||
|
|
||
| if (target === 'UAH') { | ||
| displayValue = value; | ||
| } else { | ||
| const rate = rates[target]; | ||
| if (rate && rate > 0) { | ||
| displayValue = value / rate; | ||
| } else { | ||
| // Rate unknown → degrade to UAH. Keeps product usable offline / before load. | ||
| displayCode = 'UAH'; | ||
| displayValue = value; | ||
| } | ||
| } | ||
|
|
||
| return new Intl.NumberFormat('uk-UA', { | ||
| style: 'currency', | ||
| currency: displayCode, | ||
| minimumFractionDigits: fractionDigits, | ||
| maximumFractionDigits: fractionDigits, | ||
| }).format(displayValue); | ||
| }, | ||
| [preferredCurrency, rates] | ||
| ); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,67 @@ | ||
| import { create } from 'zustand'; | ||
| import { getLatestRates, getPreferences, updatePreferences, type ExchangeRateDto } from '../api/currency'; | ||
| import type { SupportedCurrency } from '../api/me'; | ||
| import { useAuthStore } from './authStore'; | ||
|
|
||
| interface CurrencyState { | ||
| preferredCurrency: SupportedCurrency; | ||
| rates: Record<'USD' | 'EUR', number | null>; | ||
| loaded: boolean; | ||
| loading: boolean; | ||
| loadedForTenantId: string | null; | ||
|
|
||
| load: () => Promise<void>; | ||
| setPreferredCurrency: (c: SupportedCurrency) => Promise<void>; | ||
| reset: () => void; | ||
| } | ||
|
|
||
| const emptyRates = (): Record<'USD' | 'EUR', number | null> => ({ USD: null, EUR: null }); | ||
|
|
||
| export const useCurrencyStore = create<CurrencyState>((set, get) => ({ | ||
| preferredCurrency: 'UAH', | ||
| rates: emptyRates(), | ||
| loaded: false, | ||
| loading: false, | ||
| loadedForTenantId: null, | ||
|
|
||
| load: async () => { | ||
| const { token, tenantId } = useAuthStore.getState(); | ||
| if (!token || !tenantId) { | ||
| set({ preferredCurrency: 'UAH', rates: emptyRates(), loaded: false, loading: false, loadedForTenantId: null }); | ||
| return; | ||
| } | ||
| if (get().loading) return; | ||
| if (get().loaded && get().loadedForTenantId === tenantId) return; | ||
|
|
||
| set({ loading: true }); | ||
| try { | ||
| const [prefs, rates] = await Promise.all([getPreferences(), getLatestRates()]); | ||
| const next = emptyRates(); | ||
| for (const r of rates as ExchangeRateDto[]) { | ||
| if (r.code === 'USD' || r.code === 'EUR') next[r.code] = r.rateToUah; | ||
| } | ||
| set({ | ||
| preferredCurrency: prefs.preferredCurrency, | ||
| rates: next, | ||
| loaded: true, | ||
| loading: false, | ||
| loadedForTenantId: tenantId, | ||
| }); | ||
| } catch { | ||
| set({ loading: false }); | ||
| } | ||
| }, | ||
|
|
||
| setPreferredCurrency: async (c) => { | ||
| const prev = get().preferredCurrency; | ||
| set({ preferredCurrency: c }); | ||
| try { | ||
| await updatePreferences(c); | ||
| } catch (e) { | ||
| set({ preferredCurrency: prev }); | ||
| throw e; | ||
| } | ||
| }, | ||
|
|
||
| reset: () => set({ preferredCurrency: 'UAH', rates: emptyRates(), loaded: false, loading: false, loadedForTenantId: null }), | ||
| })); | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,109 @@ | ||
| using System.Security.Claims; | ||
| using AgroPlatform.Application.Common.Interfaces; | ||
| using AgroPlatform.Domain.Users; | ||
| using Microsoft.AspNetCore.Authorization; | ||
| using Microsoft.AspNetCore.Mvc; | ||
| using Microsoft.EntityFrameworkCore; | ||
|
|
||
| namespace AgroPlatform.Api.Controllers; | ||
|
|
||
| /// <summary> | ||
| /// Currency preferences and exchange rates. Base currency in DB is always UAH; | ||
| /// this controller exposes stored NBU rates and the signed-in user's display preference. | ||
| /// See ROADMAP.md "Decisions locked / Currency". | ||
| /// </summary> | ||
| [ApiController] | ||
| [Authorize] | ||
| [Route("api/currency")] | ||
| [Produces("application/json")] | ||
| public sealed class CurrencyController : ControllerBase | ||
| { | ||
| private static readonly string[] AllowedCodes = { "UAH", "USD", "EUR" }; | ||
| private static readonly string[] TrackedCodes = { "USD", "EUR" }; | ||
|
|
||
| private readonly IAppDbContext _db; | ||
| private readonly INbuCurrencyService _nbu; | ||
|
|
||
| public CurrencyController(IAppDbContext db, INbuCurrencyService nbu) | ||
| { | ||
| _db = db; | ||
| _nbu = nbu; | ||
| } | ||
|
|
||
| public record RateDto(string Code, DateOnly Date, decimal RateToUah); | ||
| public record PreferencesDto(string PreferredCurrency); | ||
| public record UpdatePreferencesRequest(string PreferredCurrency); | ||
|
|
||
| /// <summary>Latest stored rates for tracked currencies (USD, EUR).</summary> | ||
| [HttpGet("rates/latest")] | ||
| public async Task<IActionResult> GetLatestRates(CancellationToken ct) | ||
| { | ||
| var rows = new List<RateDto>(); | ||
| foreach (var code in TrackedCodes) | ||
| { | ||
| var r = await _db.ExchangeRates | ||
| .Where(x => x.Code == code) | ||
| .OrderByDescending(x => x.Date) | ||
| .Select(x => new RateDto(x.Code, x.Date, x.RateToUah)) | ||
| .FirstOrDefaultAsync(ct); | ||
| if (r is not null) rows.Add(r); | ||
| } | ||
| return Ok(rows); | ||
| } | ||
|
|
||
| /// <summary>Rate for <paramref name="code"/> on <paramref name="date"/> (fallback to previous business day).</summary> | ||
| [HttpGet("rates")] | ||
| public async Task<IActionResult> GetRate([FromQuery] string code, [FromQuery] DateOnly date, CancellationToken ct) | ||
| { | ||
| if (string.IsNullOrWhiteSpace(code)) return BadRequest(new { error = "code required" }); | ||
| code = code.ToUpperInvariant(); | ||
| if (code == "UAH") return Ok(new RateDto("UAH", date, 1m)); | ||
| var rate = await _nbu.GetRateAsync(code, date, ct); | ||
| if (rate is null) return NotFound(new { error = "no rate for given currency" }); | ||
| // Look up the actual row date (could be earlier than requested). | ||
| var row = await _db.ExchangeRates | ||
| .Where(r => r.Code == code && r.Date <= date) | ||
| .OrderByDescending(r => r.Date) | ||
| .Select(r => new RateDto(r.Code, r.Date, r.RateToUah)) | ||
| .FirstOrDefaultAsync(ct); | ||
| return Ok(row); | ||
| } | ||
|
|
||
| /// <summary>Current user's display preferences (creates defaults if missing).</summary> | ||
| [HttpGet("preferences")] | ||
| public async Task<IActionResult> GetPreferences(CancellationToken ct) | ||
| { | ||
| var userId = User.FindFirstValue(ClaimTypes.NameIdentifier); | ||
| if (string.IsNullOrEmpty(userId)) return Unauthorized(); | ||
| var row = await _db.UserPreferences.FirstOrDefaultAsync(p => p.UserId == userId, ct); | ||
| return Ok(new PreferencesDto(row?.PreferredCurrency ?? "UAH")); | ||
| } | ||
|
|
||
| [HttpPut("preferences")] | ||
| public async Task<IActionResult> UpdatePreferences([FromBody] UpdatePreferencesRequest req, CancellationToken ct) | ||
| { | ||
| var userId = User.FindFirstValue(ClaimTypes.NameIdentifier); | ||
| if (string.IsNullOrEmpty(userId)) return Unauthorized(); | ||
| var code = (req.PreferredCurrency ?? string.Empty).ToUpperInvariant(); | ||
| if (!AllowedCodes.Contains(code)) | ||
| return BadRequest(new { error = "PreferredCurrency must be one of UAH, USD, EUR" }); | ||
|
|
||
| var existing = await _db.UserPreferences.FirstOrDefaultAsync(p => p.UserId == userId, ct); | ||
| if (existing is null) | ||
| { | ||
| _db.UserPreferences.Add(new UserPreferences | ||
| { | ||
| UserId = userId, | ||
| PreferredCurrency = code, | ||
| UpdatedAtUtc = DateTime.UtcNow, | ||
| }); | ||
| } | ||
| else | ||
| { | ||
| existing.PreferredCurrency = code; | ||
| existing.UpdatedAtUtc = DateTime.UtcNow; | ||
| } | ||
| await _db.SaveChangesAsync(ct); | ||
| return Ok(new PreferencesDto(code)); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The
loadguard caches currency data at tenant scope, butpreferredCurrencyis user-specific. When user A logs out and user B (same tenant) logs in within the same SPA session,load()returns early and keeps user A’s preference, so profile/settings and any formatting based on this store can show the wrong currency for user B. Include user identity in the cache key (or force reset/refetch on auth user change) instead of onlytenantId.Useful? React with 👍 / 👎.