3 Commits

Author SHA1 Message Date
Priec
ac31cdfbf3 eur czk can be disabled from now on
Some checks are pending
CI / Check Style (push) Waiting to run
CI / Run Clippy (push) Waiting to run
CI / Run Tests (push) Waiting to run
2026-06-23 21:54:09 +02:00
Priec
c409e85995 CZK implemented 2026-06-23 12:54:11 +02:00
Priec
6b7422806f whole eshop is now in euro 2026-06-23 12:31:52 +02:00
57 changed files with 761 additions and 149 deletions

View File

@@ -20,6 +20,7 @@ admin-audio-desc = upload songs, then group them into albums.
logout = Log out
settings = Settings
settings-language = Language
settings-currency = Currency
settings-theme = Theme
language-en = English
language-sk = Slovak
@@ -475,6 +476,14 @@ bank-amount = Amount
admin-shipping = Shipping
admin-shipping-desc = set the price and availability of each delivery option.
shipping-enabled = Active
admin-currency = Exchange rate
admin-currency-desc = set the exchange rate for the currencies customers can switch between. You always enter prices in EUR.
currency-rate = Rate
exchange-rate = Exchange rate
exchange-rate-hint = { $code } prices are the { $base } price recalculated at this rate.
currency-enabled = Available to customers
currency-base = Base currency
currency-base-hint = the currency you enter prices in and settle payment in. Cannot be changed.
shipping-new = Add delivery option
shipping-add = Add
shipping-requires-pickup = Requires pickup point

View File

@@ -20,6 +20,7 @@ admin-audio-desc = nahrať skladby a potom ich zoskupiť do albumov.
logout = Odhlásiť sa
settings = Nastavenia
settings-language = Jazyk
settings-currency = Mena
settings-theme = Téma
language-en = Angličtina
language-sk = Slovenčina
@@ -475,6 +476,14 @@ bank-amount = Suma
admin-shipping = Doprava
admin-shipping-desc = nastaviť cenu a dostupnosť jednotlivých možností dopravy.
shipping-enabled = Aktívne
admin-currency = Kurz
admin-currency-desc = nastaviť výmenný kurz pre meny, medzi ktorými môžu zákazníci prepínať. Ceny zadávate vždy v EUR.
currency-rate = Kurz
exchange-rate = Výmenný kurz
exchange-rate-hint = ceny v { $code } sa prepočítajú z ceny v { $base } týmto kurzom.
currency-enabled = Dostupná pre zákazníkov
currency-base = Základná mena
currency-base-hint = mena, v ktorej zadávate ceny a prebieha platba. Nedá sa zmeniť.
shipping-new = Pridať možnosť dopravy
shipping-add = Pridať
shipping-requires-pickup = Vyžaduje výdajné miesto

View File

@@ -30,18 +30,18 @@
{% for item in items %}
<li class="flex justify-between gap-2">
<span class="text-on-surface/80 dark:text-on-surface-dark/80">{{ item.product_name }}{% if item.variant_label %} · {{ item.variant_label }}{% endif %} × {{ item.quantity }}</span>
<span class="tabular-nums">{{ item.line_total }} {{ order.currency }}</span>
<span class="tabular-nums">{{ item.line_total }} </span>
</li>
{% endfor %}
</ul>
<div class="space-y-1 border-t border-outline py-3 text-sm dark:border-outline-dark">
<div class="flex justify-between"><span class="text-on-surface/70 dark:text-on-surface-dark/70">{{ t(key="checkout-subtotal", lang=lang | default(value='sk')) }}</span><span class="tabular-nums">{{ order.subtotal }} {{ order.currency }}</span></div>
<div class="flex justify-between"><span class="text-on-surface/70 dark:text-on-surface-dark/70">{{ order.carrier_name }}</span><span class="tabular-nums">{{ order.shipping }} {{ order.currency }}</span></div>
<div class="flex justify-between"><span class="text-on-surface/70 dark:text-on-surface-dark/70">{{ t(key="checkout-subtotal", lang=lang | default(value='sk')) }}</span><span class="tabular-nums">{{ order.subtotal }} </span></div>
<div class="flex justify-between"><span class="text-on-surface/70 dark:text-on-surface-dark/70">{{ order.carrier_name }}</span><span class="tabular-nums">{{ order.shipping }} </span></div>
{% if order.pickup_point_name %}<div class="text-xs text-on-surface/60 dark:text-on-surface-dark/60">{{ order.pickup_point_name }}</div>{% endif %}
</div>
<div class="flex justify-between border-t border-outline pt-3 font-bold dark:border-outline-dark">
<span>{{ t(key="order-total", lang=lang | default(value='sk')) }}</span>
<span class="tabular-nums text-primary dark:text-primary-dark">{{ order.total }} {{ order.currency }}</span>
<span class="tabular-nums text-primary dark:text-primary-dark">{{ order.total }} </span>
</div>
</div>
@@ -68,7 +68,7 @@
<span class="text-on-surface/70 dark:text-on-surface-dark/70">{{ t(key="bank-account-name", lang=lang | default(value='sk')) }}</span><span class="font-medium">{{ order.bank_account_name }}</span>
<span class="text-on-surface/70 dark:text-on-surface-dark/70">IBAN</span><span class="font-mono font-medium">{{ order.bank_iban }}</span>
<span class="text-on-surface/70 dark:text-on-surface-dark/70">{{ t(key="bank-variable-symbol", lang=lang | default(value='sk')) }}</span><span class="font-mono font-medium">{{ order.variable_symbol }}</span>
<span class="text-on-surface/70 dark:text-on-surface-dark/70">{{ t(key="bank-amount", lang=lang | default(value='sk')) }}</span><span class="font-medium tabular-nums">{{ order.total }} {{ order.currency }}</span>
<span class="text-on-surface/70 dark:text-on-surface-dark/70">{{ t(key="bank-amount", lang=lang | default(value='sk')) }}</span><span class="font-medium tabular-nums">{{ order.total }} </span>
</div>
</div>
{% endif %}

View File

@@ -22,7 +22,7 @@
</div>
<div class="flex items-center gap-4">
{{ self::status_badge(status=order.status) }}
<span class="tabular-nums text-sm font-medium text-on-surface-strong dark:text-on-surface-dark-strong">{{ order.total }} {{ order.currency }}</span>
<span class="tabular-nums text-sm font-medium text-on-surface-strong dark:text-on-surface-dark-strong">{{ order.total }} </span>
</div>
</a>
{% endmacro order_row %}

View File

@@ -105,6 +105,10 @@
class="flex items-center gap-2 rounded-radius px-2 py-1.5 text-sm font-medium text-on-surface underline-offset-2 transition hover:bg-primary/5 hover:text-on-surface-strong focus:outline-hidden focus-visible:underline aria-[current=page]:bg-primary/10 aria-[current=page]:text-on-surface-strong dark:text-on-surface-dark dark:hover:bg-primary-dark/5 dark:hover:text-on-surface-dark-strong dark:aria-[current=page]:bg-primary-dark/10 dark:aria-[current=page]:text-on-surface-dark-strong">
{{ t(key="admin-shipping", lang=lang | default(value='sk')) }}
</a>
<a href="/admin/currencies" data-nav="/admin/currencies"
class="flex items-center gap-2 rounded-radius px-2 py-1.5 text-sm font-medium text-on-surface underline-offset-2 transition hover:bg-primary/5 hover:text-on-surface-strong focus:outline-hidden focus-visible:underline aria-[current=page]:bg-primary/10 aria-[current=page]:text-on-surface-strong dark:text-on-surface-dark dark:hover:bg-primary-dark/5 dark:hover:text-on-surface-dark-strong dark:aria-[current=page]:bg-primary-dark/10 dark:aria-[current=page]:text-on-surface-dark-strong">
{{ t(key="admin-currency", lang=lang | default(value='sk')) }}
</a>
</div>
<div class="border-t border-outline p-4 dark:border-outline-dark">

View File

@@ -38,7 +38,7 @@
x-text="row.label || ('#' + row.id)"></span>
<span class="text-sm tabular-nums text-on-surface/70 dark:text-on-surface-dark/70">
{{ t(key="price", lang=lang | default(value='sk')) }}:
<span x-text="row.regular_price"></span> <span x-text="row.currency"></span>
<span x-text="row.regular_price"></span>
</span>
</div>
@@ -80,9 +80,9 @@
class="flex flex-wrap items-center justify-between gap-3 rounded-radius border border-outline bg-surface-alt px-4 py-2.5 text-sm dark:border-outline-dark dark:bg-surface-dark/40">
<span class="text-on-surface/70 dark:text-on-surface-dark/70">{{ t(key="discount-preview-after", lang=lang | default(value='sk')) }}</span>
<span class="flex items-center gap-2">
<span class="tabular-nums text-on-surface/50 line-through dark:text-on-surface-dark/50" x-text="money(row.regular_cents) + ' ' + row.currency"></span>
<span class="tabular-nums text-on-surface/50 line-through dark:text-on-surface-dark/50" x-text="money(row.regular_cents) + ' '"></span>
<span class="text-base font-semibold tabular-nums" :class="valid(row) ? 'text-danger' : 'text-on-surface/40 dark:text-on-surface-dark/40'"
x-text="money(afterCents(row)) + ' ' + row.currency"></span>
x-text="money(afterCents(row)) + ' '"></span>
<span x-show="valid(row)" class="text-xs text-on-surface/60 dark:text-on-surface-dark/60" x-text="'(' + percentOff(row) + '%)'"></span>
</span>
</div>
@@ -106,7 +106,6 @@
label: r.label || '',
regular_cents: r.regular_cents,
regular_price: r.regular_price,
currency: r.currency,
mode: r.mode || 'fixed',
fixed: r.fixed || '',
percent: r.percent || '',

View File

@@ -21,9 +21,9 @@
{{ ui::csrf_field() }}
{% if product %}
{% set v_name = product.name %}{% set v_currency = product.currency %}{% set v_desc = product.description | default(value="") %}{% set v_short = product.short_description | default(value="") %}{% set v_pub = product.published %}
{% set v_name = product.name %}{% set v_desc = product.description | default(value="") %}{% set v_short = product.short_description | default(value="") %}{% set v_pub = product.published %}
{% else %}
{% set v_name = "" %}{% set v_currency = "EUR" %}{% set v_desc = "" %}{% set v_short = "" %}{% set v_pub = false %}
{% set v_name = "" %}{% set v_desc = "" %}{% set v_short = "" %}{% set v_pub = false %}
{% endif %}
{% set inp = "w-full rounded-radius border border-outline bg-surface-alt px-3 py-2 text-sm text-on-surface focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary dark:border-outline-dark dark:bg-surface-dark-alt/50 dark:text-on-surface-dark dark:focus-visible:outline-primary-dark" %}
{% set sublabel = "text-xs font-medium text-on-surface/70 dark:text-on-surface-dark/70" %}
@@ -33,11 +33,6 @@
{{ ui::input(name="name", id="name", required=true, value=v_name) }}
</div>
<div class="space-y-1.5 sm:max-w-[10rem]">
<label for="currency" class="text-sm font-medium text-on-surface-strong dark:text-on-surface-dark-strong">{{ t(key="currency", lang=lang | default(value='sk')) }}</label>
{{ ui::input(name="currency", id="currency", value=v_currency, attrs='maxlength="3"', extra="uppercase") }}
</div>
{# --- Variants / options editor ------------------------------------------- #}
{# Each product is sold as one or more variants (a free-text label such as #}
{# "10cm x 13cm" or "5ml" plus its own price). Price is required. Stock is #}
@@ -76,7 +71,7 @@
<input type="number" min="0" :name="`variants[${i}][stock]`" x-model="row.stock" class="{{ inp }}" placeholder="∞" title="{{ t(key='stock-untracked-hint', lang=lang | default(value='sk')) }}">
</div>
<div class="space-y-1 sm:col-span-2">
<label class="{{ sublabel }} block truncate">{{ t(key="price", lang=lang | default(value='sk')) }}</label>
<label class="{{ sublabel }} block truncate">{{ t(key="price", lang=lang | default(value='sk')) }} (€)</label>
<input :name="`variants[${i}][price]`" x-model="row.price" inputmode="decimal" required class="{{ inp }}" placeholder="0.00">
</div>
</div>

View File

@@ -122,7 +122,7 @@
</div>
</div>
</td>
<td class="px-4 py-3 tabular-nums">{% if product.has_options %}{{ t(key="from-price", price=product.regular_price, lang=lang | default(value='sk')) }}{% else %}{{ product.regular_price }}{% endif %} {{ product.currency }}</td>
<td class="px-4 py-3 tabular-nums">{% if product.has_options %}{{ t(key="from-price", price=product.regular_price, lang=lang | default(value='sk')) }}{% else %}{{ product.regular_price }}{% endif %} </td>
<td class="px-4 py-3 tabular-nums">{{ product.variant_count }}</td>
<td class="px-4 py-3 tabular-nums">
<span id="eff-{{ product.id }}">{{ ui::eff_price(p=product) }}</span>

View File

@@ -0,0 +1,44 @@
{% extends "admin/base.html" %}
{% import "macros/ui.html" as ui %}
{% block title %}{{ t(key="admin-currency", lang=lang | default(value='sk')) }}{% endblock title %}
{% block crumb %}{{ t(key="admin-currency", lang=lang | default(value='sk')) }}{% endblock crumb %}
{% block content %}
<header class="space-y-1">
<h1 class="text-2xl font-bold text-on-surface-strong dark:text-on-surface-dark-strong">{{ t(key="admin-currency", lang=lang | default(value='sk')) }}</h1>
<p class="text-sm text-on-surface/70 dark:text-on-surface-dark/70">{{ t(key="admin-currency-desc", lang=lang | default(value='sk')) }}</p>
</header>
<div class="mt-6 space-y-4">
<!-- base currency, read-only for context -->
<div class="flex flex-wrap items-center gap-4 rounded-radius border border-outline bg-surface-alt/40 p-5 dark:border-outline-dark dark:bg-surface-dark-alt/30">
<div class="min-w-40">
<p class="font-semibold text-on-surface-strong dark:text-on-surface-dark-strong">{{ base_code }} ({{ base_symbol }})</p>
<p class="text-xs text-on-surface/60 dark:text-on-surface-dark/60">{{ t(key="currency-base-hint", lang=lang | default(value='sk')) }}</p>
</div>
{{ ui::badge(label=t(key="currency-base", lang=lang | default(value='sk')), variant="neutral") }}
</div>
{% for c in currencies %}
<form method="post" action="/admin/currencies/{{ c.id }}"
class="flex flex-wrap items-end gap-4 rounded-radius border border-outline bg-surface p-5 dark:border-outline-dark dark:bg-surface-dark-alt">
{{ ui::csrf_field() }}
<div class="min-w-40">
<p class="font-semibold text-on-surface-strong dark:text-on-surface-dark-strong">{{ c.code }} ({{ c.symbol }})</p>
<p class="text-xs text-on-surface/60 dark:text-on-surface-dark/60">{{ t(key="exchange-rate-hint", code=c.code, base=base_code, lang=lang | default(value='sk')) }}</p>
</div>
<div class="space-y-1.5">
<label for="rate-{{ c.id }}" class="text-sm font-medium text-on-surface-strong dark:text-on-surface-dark-strong">{{ t(key="exchange-rate", lang=lang | default(value='sk')) }}</label>
<span class="flex items-center gap-2">
<span class="text-sm text-on-surface/60 dark:text-on-surface-dark/60">1 {{ base_code }} =</span>
{{ ui::input(name="rate", id="rate-" ~ c.id, value=c.rate, width="w-28", attrs='inputmode="decimal"') }}
<span class="text-sm text-on-surface/60 dark:text-on-surface-dark/60">{{ c.code }}</span>
</span>
</div>
<div class="pb-2">{{ ui::checkbox(name="enabled", label=t(key="currency-enabled", lang=lang | default(value='sk')), checked=c.enabled) }}</div>
{{ ui::button(label=t(key="save", lang=lang | default(value='sk')), type="submit", extra="ml-auto") }}
</form>
{% endfor %}
</div>
{% endblock content %}

View File

@@ -38,15 +38,15 @@
<div class="space-y-2 rounded-radius bg-surface-alt px-4 py-3 dark:bg-surface-dark/40">
<div class="flex items-center justify-between gap-3 text-sm">
<span class="text-on-surface/70 dark:text-on-surface-dark/70">{{ t(key="price", lang=lang | default(value='sk')) }}</span>
<span class="tabular-nums text-on-surface-strong dark:text-on-surface-dark-strong">{{ product.regular_price }} {{ product.currency }}</span>
<span class="tabular-nums text-on-surface-strong dark:text-on-surface-dark-strong">{{ product.regular_price }} </span>
</div>
<div class="flex items-center justify-between gap-3 text-sm">
<span class="text-on-surface/70 dark:text-on-surface-dark/70">{{ t(key="business-price", lang=lang | default(value='sk')) }}</span>
<span class="tabular-nums {% if product.business_reduced %}font-medium text-danger{% else %}text-on-surface-strong dark:text-on-surface-dark-strong{% endif %}">{{ product.business_price }} {{ product.currency }}</span>
<span class="tabular-nums {% if product.business_reduced %}font-medium text-danger{% else %}text-on-surface-strong dark:text-on-surface-dark-strong{% endif %}">{{ product.business_price }} </span>
</div>
<div class="flex items-center justify-between gap-3 text-sm">
<span class="text-on-surface/70 dark:text-on-surface-dark/70">{{ t(key="effective-price", lang=lang | default(value='sk')) }}</span>
<span class="tabular-nums font-medium {% if product.effective_differs %}text-primary dark:text-primary-dark{% else %}text-on-surface-strong dark:text-on-surface-dark-strong{% endif %}">{{ product.effective_price }} {{ product.currency }}</span>
<span class="tabular-nums font-medium {% if product.effective_differs %}text-primary dark:text-primary-dark{% else %}text-on-surface-strong dark:text-on-surface-dark-strong{% endif %}">{{ product.effective_price }} </span>
</div>
</div>
@@ -62,7 +62,7 @@
<div class="flex items-center justify-between gap-3">
<span class="text-sm text-on-surface/70 dark:text-on-surface-dark/70">{{ t(key="negotiated-price", lang=lang | default(value='sk')) }}</span>
<span class="text-lg font-semibold tabular-nums" :class="valid ? 'text-secondary dark:text-secondary-dark' : 'text-on-surface/40 dark:text-on-surface-dark/40'">
<span x-text="money(afterCents)"></span> {{ product.currency }}
<span x-text="money(afterCents)"></span>
</span>
</div>
<p x-show="!valid" class="text-xs text-danger">{{ t(key="discount-must-be-positive", lang=lang | default(value='sk')) }}</p>

View File

@@ -82,14 +82,14 @@
</td>
<td class="px-4 py-3 tabular-nums">
{% if product.business_reduced %}
<span class="font-medium text-danger">{{ product.business_price }} {{ product.currency }}</span>
<span class="font-medium text-danger">{{ product.business_price }} </span>
<span class="ml-1 text-xs text-on-surface/50 line-through dark:text-on-surface-dark/50">{{ product.regular_price }}</span>
{% else %}
{{ product.business_price }} {{ product.currency }}
{{ product.business_price }}
{% endif %}
</td>
<td class="px-4 py-3 tabular-nums">
<span class="font-medium {% if product.effective_differs %}text-primary dark:text-primary-dark{% else %}text-on-surface-strong dark:text-on-surface-dark-strong{% endif %}">{{ product.effective_price }} {{ product.currency }}</span>
<span class="font-medium {% if product.effective_differs %}text-primary dark:text-primary-dark{% else %}text-on-surface-strong dark:text-on-surface-dark-strong{% endif %}">{{ product.effective_price }} </span>
{% if product.collision %}<span class="ml-1">{{ ui::badge(label=t(key="collision", lang=lang | default(value='sk')), variant="warning") }}</span>{% endif %}
</td>
<td class="px-4 py-3">

View File

@@ -44,7 +44,7 @@
<td class="px-4 py-3">
{{ ui::badge(label=t(key="order-status-" ~ order.status, lang=lang | default(value='sk')), variant="neutral") }}
</td>
<td class="px-4 py-3 text-right tabular-nums">{{ order.total }} {{ order.currency }}</td>
<td class="px-4 py-3 text-right tabular-nums">{{ order.total }} </td>
<td class="px-4 py-3 text-right">
{{ ui::button(variant="outline-secondary", label=t(key="view", lang=lang | default(value='sk')), href="/admin/orders/" ~ order.id, size="px-3 py-1.5 text-xs") }}
</td>

View File

@@ -38,14 +38,14 @@
<tr>
<td class="px-4 py-3">{{ item.product_name }}{% if item.variant_label %} <span class="text-on-surface/60 dark:text-on-surface-dark/60">· {{ item.variant_label }}</span>{% endif %}</td>
<td class="px-4 py-3 tabular-nums">{{ item.quantity }}</td>
<td class="px-4 py-3 text-right tabular-nums">{{ item.line_total }} {{ order.currency }}</td>
<td class="px-4 py-3 text-right tabular-nums">{{ item.line_total }} </td>
</tr>
{% endfor %}
</tbody>
<tfoot class="{{ ui::tfoot_cls() }}">
<tr>
<td colspan="2" class="px-4 py-3 text-right font-semibold">{{ t(key="order-total", lang=lang | default(value='sk')) }}</td>
<td class="px-4 py-3 text-right font-bold tabular-nums text-primary dark:text-primary-dark">{{ order.total }} {{ order.currency }}</td>
<td class="px-4 py-3 text-right font-bold tabular-nums text-primary dark:text-primary-dark">{{ order.total }} </td>
</tr>
</tfoot>
</table>
@@ -75,7 +75,7 @@
</div>
<div>
<p class="text-xs uppercase tracking-wide text-on-surface/60 dark:text-on-surface-dark/60">{{ t(key="checkout-carrier", lang=lang | default(value='sk')) }}</p>
<p class="text-on-surface/80 dark:text-on-surface-dark/80">{{ order.carrier_name }} — {{ order.shipping }} {{ order.currency }}</p>
<p class="text-on-surface/80 dark:text-on-surface-dark/80">{{ order.carrier_name }} — {{ order.shipping }} </p>
{% if order.pickup_point_name %}<p class="text-on-surface/80 dark:text-on-surface-dark/80">{{ order.pickup_point_name }}</p>{% endif %}
</div>
<div>

View File

@@ -104,8 +104,19 @@
{% endif %}
</ul>
<!-- right side: cart + settings + mobile toggle -->
<!-- right side: kurz + cart + settings + mobile toggle -->
<div class="ml-auto flex items-center gap-3">
<!-- exchange-rate ("kurz") display: the admin-set EUR→alt rate(s).
Hidden when the store is EUR-only (no enabled alternatives). -->
{% set nav_cc = currencies() %}
{% if nav_cc.alts | length > 0 %}
<div class="hidden items-center gap-2 text-xs text-on-surface/70 dark:text-on-surface-dark/70 sm:flex">
<span class="font-semibold uppercase tracking-wide">{{ t(key="currency-rate", lang=lang | default(value='sk')) }}</span>
{% for a in nav_cc.alts %}
<span class="tabular-nums">1 {{ nav_cc.base.symbol }} = {{ a.rate }} {{ a.symbol }}</span>
{% endfor %}
</div>
{% endif %}
<!-- customer profile dropdown (avatar + name + account type) -->
{% if logged_in_customer %}
{% include "partials/profile_menu.html" %}

View File

@@ -132,10 +132,10 @@
{% macro eff_price(p, preview=false) -%}
{%- if preview -%}{% set strong = "text-info" %}{%- else -%}{% set strong = "text-primary dark:text-primary-dark" %}{%- endif -%}
{% if p.effective_reduced %}
<span class="font-medium {{ strong }}">{{ p.effective_price }} {{ p.currency }}</span>
<span class="font-medium {{ strong }}">{{ p.effective_price }} </span>
<span class="ml-1 text-xs text-on-surface/60 dark:text-on-surface-dark/60">({{ p.effective_percent_off }}%)</span>
{% else %}
{{ p.effective_price }} {{ p.currency }}
{{ p.effective_price }}
{% endif %}
{%- endmacro eff_price %}

View File

@@ -35,6 +35,32 @@
{% if lang | default(value='sk') == "sk" %}<span class="text-primary dark:text-primary-dark"></span>{% endif %}
</button>
</form>
{# Currency switcher. Only enabled (buyer-available) currencies are listed,
from the `currencies()` snapshot; the whole section is hidden when the store
is EUR-only (no enabled alternatives). The active code is read from the
`currency` cookie client-side (Alpine); posting to /currency sets it. #}
{% set cc = currencies() %}
{% if cc.alts | length > 0 %}
<p class="mt-1 px-4 py-1.5 text-xs font-semibold uppercase tracking-wide text-on-surface/60 dark:text-on-surface-dark/60">
{{ t(key="settings-currency", lang=lang | default(value='sk')) }}
</p>
<form method="post" action="/currency" hx-boost="false"
x-data="{ cur: ((document.cookie.split('; ').find(function (c) { return c.indexOf('currency=') === 0 }) || 'currency={{ cc.base.code }}').split('=')[1]) }">
<input type="hidden" name="_csrf" value="{{ csrf_token() }}">
<button type="submit" name="currency" value="{{ cc.base.code }}" role="menuitem"
class="flex w-full items-center justify-between px-4 py-2 text-sm text-on-surface transition hover:bg-primary/5 hover:text-on-surface-strong focus-visible:bg-primary/10 focus-visible:text-on-surface-strong focus-visible:outline-hidden dark:text-on-surface-dark dark:hover:bg-primary-dark/5 dark:hover:text-on-surface-dark-strong">
<span>{{ cc.base.code }} ({{ cc.base.symbol }})</span>
<span x-cloak x-show="cur === '{{ cc.base.code }}'" class="text-primary dark:text-primary-dark"></span>
</button>
{% for a in cc.alts %}
<button type="submit" name="currency" value="{{ a.code }}" role="menuitem"
class="flex w-full items-center justify-between px-4 py-2 text-sm text-on-surface transition hover:bg-primary/5 hover:text-on-surface-strong focus-visible:bg-primary/10 focus-visible:text-on-surface-strong focus-visible:outline-hidden dark:text-on-surface-dark dark:hover:bg-primary-dark/5 dark:hover:text-on-surface-dark-strong">
<span>{{ a.code }} ({{ a.symbol }})</span>
<span x-cloak x-show="cur === '{{ a.code }}'" class="text-primary dark:text-primary-dark"></span>
</button>
{% endfor %}
</form>
{% endif %}
<p class="mt-1 px-4 py-1.5 text-xs font-semibold uppercase tracking-wide text-on-surface/60 dark:text-on-surface-dark/60">
{{ t(key="settings-theme", lang=lang | default(value='sk')) }}
</p>

View File

@@ -38,11 +38,11 @@
{% endif %}
{% if product.on_sale %}
<div class="flex flex-wrap items-baseline gap-x-2 leading-tight">
<span class="text-xl font-semibold text-danger"><span class="sr-only">Price</span>{% if product.has_options %}{{ t(key="from-price", price=product.price, lang=lang | default(value='sk')) }}{% else %}{{ product.price }}{% endif %} {{ product.currency }}</span>
<span class="text-sm text-on-surface/50 line-through dark:text-on-surface-dark/50">{{ product.regular_price }} {{ product.currency }}</span>
<span class="text-xl font-semibold text-danger"><span class="sr-only">Price</span>{% if product.has_options %}{{ t(key="from-price", price=product.price, lang=lang | default(value='sk')) }}{% else %}{{ product.price }}{% endif %} {{ currency_symbol }}</span>
<span class="text-sm text-on-surface/50 line-through dark:text-on-surface-dark/50">{{ product.regular_price }} {{ currency_symbol }}</span>
</div>
{% else %}
<span class="break-words text-xl"><span class="sr-only">Price</span>{% if product.has_options %}{{ t(key="from-price", price=product.price, lang=lang | default(value='sk')) }}{% else %}{{ product.price }}{% endif %} {{ product.currency }}</span>
<span class="break-words text-xl"><span class="sr-only">Price</span>{% if product.has_options %}{{ t(key="from-price", price=product.price, lang=lang | default(value='sk')) }}{% else %}{{ product.price }}{% endif %} {{ currency_symbol }}</span>
{% endif %}
</div>
</a>

View File

@@ -23,10 +23,10 @@
</td>
<td class="px-4 py-3 tabular-nums">
{% if item.on_sale %}
<span class="font-medium text-danger">{{ item.price }} {{ item.currency }}</span>
<span class="font-medium text-danger">{{ item.price }} {{ currency_symbol }}</span>
<span class="ml-1 text-xs text-on-surface/50 line-through dark:text-on-surface-dark/50">{{ item.regular_price }}</span>
{% else %}
{{ item.price }} {{ item.currency }}
{{ item.price }} {{ currency_symbol }}
{% endif %}
</td>
<td class="px-4 py-3">
@@ -48,7 +48,7 @@
class="w-20 rounded-radius border border-outline bg-surface-alt px-2 py-1 text-sm text-on-surface focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary disabled:cursor-not-allowed disabled:opacity-75 dark:border-outline-dark dark:bg-surface-dark-alt/50 dark:text-on-surface-dark dark:focus-visible:outline-primary-dark">
</form>
</td>
<td class="px-4 py-3 text-right font-medium tabular-nums">{{ item.line_total }} {{ item.currency }}</td>
<td class="px-4 py-3 text-right font-medium tabular-nums">{{ item.line_total }} {{ currency_symbol }}</td>
<td class="px-4 py-3 text-right">
<form method="post" action="/cart/remove"
hx-post="/cart/remove" hx-target="#cart-body" hx-swap="innerHTML">
@@ -63,7 +63,7 @@
<tfoot class="{{ ui::tfoot_cls() }}">
<tr>
<td colspan="3" class="px-4 py-3 text-right font-semibold text-on-surface-strong dark:text-on-surface-dark-strong">{{ t(key="cart-total", lang=lang | default(value='sk')) }}</td>
<td class="px-4 py-3 text-right text-lg font-bold tabular-nums text-primary dark:text-primary-dark">{{ total }} {{ currency }}</td>
<td class="px-4 py-3 text-right text-lg font-bold tabular-nums text-primary dark:text-primary-dark">{{ total }} {{ currency_symbol }}</td>
<td></td>
</tr>
</tfoot>

View File

@@ -1,6 +1,6 @@
{# Mini-cart preview shown on hover over the navbar cart (Alza-style).
Lazy-loaded via htmx from /partials/cart into the hover dropdown panel in
base.html. Receives: items[], total, currency, lang. #}
base.html. Receives: items[], total, lang. #}
{% import "macros/ui.html" as ui %}
{% if items | length > 0 %}
<div class="max-h-80 divide-y divide-outline overflow-y-auto dark:divide-outline-dark">
@@ -9,16 +9,16 @@
<div class="min-w-0 flex-1">
<a href="/shop/{{ item.slug }}" class="block truncate text-sm font-medium text-on-surface-strong hover:text-primary dark:text-on-surface-dark-strong dark:hover:text-primary-dark">{{ item.name }}</a>
{% if item.variant_label %}<span class="block truncate text-xs text-on-surface/60 dark:text-on-surface-dark/60">{{ item.variant_label }}</span>{% endif %}
<p class="mt-0.5 text-xs tabular-nums text-on-surface dark:text-on-surface-dark">{{ item.quantity }} × {{ item.price }} {{ item.currency }}</p>
<p class="mt-0.5 text-xs tabular-nums text-on-surface dark:text-on-surface-dark">{{ item.quantity }} × {{ item.price }} {{ currency_symbol }}</p>
</div>
<span class="shrink-0 text-sm font-semibold tabular-nums text-on-surface-strong dark:text-on-surface-dark-strong">{{ item.line_total }} {{ item.currency }}</span>
<span class="shrink-0 text-sm font-semibold tabular-nums text-on-surface-strong dark:text-on-surface-dark-strong">{{ item.line_total }} {{ currency_symbol }}</span>
</div>
{% endfor %}
</div>
<div class="border-t border-outline px-4 py-3 dark:border-outline-dark">
<div class="mb-3 flex items-center justify-between">
<span class="text-sm text-on-surface dark:text-on-surface-dark">{{ t(key="cart-total", lang=lang | default(value='sk')) }}</span>
<span class="text-base font-bold tabular-nums text-primary dark:text-primary-dark">{{ total }} {{ currency }}</span>
<span class="text-base font-bold tabular-nums text-primary dark:text-primary-dark">{{ total }} {{ currency_symbol }}</span>
</div>
<div class="flex gap-2">
{{ ui::button(href="/cart", variant="outline-primary", label=t(key="cart-title", lang=lang | default(value='sk')), extra="flex-1", attrs='hx-boost="false"') }}

View File

@@ -65,7 +65,7 @@
<!-- price band -->
<label class="flex flex-col gap-1 text-xs font-medium text-on-surface/70 dark:text-on-surface-dark/70">
{{ t(key="filter-price", lang=L) }}
{{ t(key="filter-price", lang=L) }}{% if currency_symbol %} ({{ currency_symbol }}){% endif %}
<span class="flex items-center gap-1">
<input type="number" name="min_price" min="0" step="0.01" inputmode="decimal"
value="{{ min_price | default(value='') }}" placeholder="{{ price_floor }}"

View File

@@ -188,7 +188,7 @@
class="before:content[''] relative h-4 w-4 appearance-none rounded-full border border-outline bg-surface before:invisible before:absolute before:left-1/2 before:top-1/2 before:h-1.5 before:w-1.5 before:-translate-x-1/2 before:-translate-y-1/2 before:rounded-full before:bg-on-primary checked:border-primary checked:bg-primary checked:before:visible focus:outline-2 focus:outline-offset-2 focus:outline-outline-strong checked:focus:outline-primary disabled:cursor-not-allowed dark:border-outline-dark dark:bg-surface-dark dark:before:bg-on-primary-dark dark:checked:border-primary-dark dark:checked:bg-primary-dark dark:focus:outline-outline-dark-strong dark:checked:focus:outline-primary-dark">
<span class="font-medium text-on-surface-strong dark:text-on-surface-dark-strong">{{ m.name }}</span>
</span>
<span class="tabular-nums text-on-surface/80 dark:text-on-surface-dark/80">{{ m.price }} {{ currency }}</span>
<span class="tabular-nums text-on-surface/80 dark:text-on-surface-dark/80">{{ m.price }} </span>
</label>
{% endfor %}
@@ -252,23 +252,23 @@
{% for item in items %}
<li class="flex justify-between gap-2">
<span class="text-on-surface/80 dark:text-on-surface-dark/80">{{ item.name }} × {{ item.quantity }}</span>
<span class="tabular-nums">{{ item.line_total }} {{ item.currency }}</span>
<span class="tabular-nums">{{ item.line_total }} </span>
</li>
{% endfor %}
</ul>
<div class="space-y-1 border-t border-outline pt-3 text-sm dark:border-outline-dark">
<div class="flex justify-between">
<span class="text-on-surface/70 dark:text-on-surface-dark/70">{{ t(key="checkout-subtotal", lang=lang | default(value='sk')) }}</span>
<span class="tabular-nums">{{ subtotal }} {{ currency }}</span>
<span class="tabular-nums">{{ subtotal }} </span>
</div>
<div class="flex justify-between">
<span class="text-on-surface/70 dark:text-on-surface-dark/70">{{ t(key="checkout-shipping-cost", lang=lang | default(value='sk')) }}</span>
<span class="tabular-nums" x-text="fmt(carrierPrice) + ' {{ currency }}'"></span>
<span class="tabular-nums" x-text="fmt(carrierPrice) + ' '"></span>
</div>
</div>
<div class="flex justify-between border-t border-outline pt-3 text-base font-bold dark:border-outline-dark">
<span>{{ t(key="cart-total", lang=lang | default(value='sk')) }}</span>
<span class="tabular-nums text-primary dark:text-primary-dark" x-text="fmt(subtotal + carrierPrice) + ' {{ currency }}'"></span>
<span class="tabular-nums text-primary dark:text-primary-dark" x-text="fmt(subtotal + carrierPrice) + ' '"></span>
</div>
{{ ui::button(label=t(key="checkout-place-order", lang=lang | default(value='sk')), type="submit", attrs=':disabled="!canSubmit"', extra="w-full", size="px-6 py-2.5 text-sm") }}
</aside>

View File

@@ -30,18 +30,18 @@
{% for item in items %}
<li class="flex justify-between gap-2">
<span class="text-on-surface/80 dark:text-on-surface-dark/80">{{ item.product_name }}{% if item.variant_label %} · {{ item.variant_label }}{% endif %} × {{ item.quantity }}</span>
<span class="tabular-nums">{{ item.line_total }} {{ order.currency }}</span>
<span class="tabular-nums">{{ item.line_total }} </span>
</li>
{% endfor %}
</ul>
<div class="space-y-1 border-t border-outline py-3 text-sm dark:border-outline-dark">
<div class="flex justify-between"><span class="text-on-surface/70 dark:text-on-surface-dark/70">{{ t(key="checkout-subtotal", lang=lang | default(value='sk')) }}</span><span class="tabular-nums">{{ order.subtotal }} {{ order.currency }}</span></div>
<div class="flex justify-between"><span class="text-on-surface/70 dark:text-on-surface-dark/70">{{ order.carrier_name }}</span><span class="tabular-nums">{{ order.shipping }} {{ order.currency }}</span></div>
<div class="flex justify-between"><span class="text-on-surface/70 dark:text-on-surface-dark/70">{{ t(key="checkout-subtotal", lang=lang | default(value='sk')) }}</span><span class="tabular-nums">{{ order.subtotal }} </span></div>
<div class="flex justify-between"><span class="text-on-surface/70 dark:text-on-surface-dark/70">{{ order.carrier_name }}</span><span class="tabular-nums">{{ order.shipping }} </span></div>
{% if order.pickup_point_name %}<div class="text-xs text-on-surface/60 dark:text-on-surface-dark/60">{{ order.pickup_point_name }}</div>{% endif %}
</div>
<div class="flex justify-between border-t border-outline pt-3 font-bold dark:border-outline-dark">
<span>{{ t(key="order-total", lang=lang | default(value='sk')) }}</span>
<span class="tabular-nums text-primary dark:text-primary-dark">{{ order.total }} {{ order.currency }}</span>
<span class="tabular-nums text-primary dark:text-primary-dark">{{ order.total }} </span>
</div>
</div>
@@ -52,7 +52,7 @@
<span class="text-on-surface/70 dark:text-on-surface-dark/70">{{ t(key="bank-account-name", lang=lang | default(value='sk')) }}</span><span class="font-medium">{{ order.bank_account_name }}</span>
<span class="text-on-surface/70 dark:text-on-surface-dark/70">IBAN</span><span class="font-mono font-medium">{{ order.bank_iban }}</span>
<span class="text-on-surface/70 dark:text-on-surface-dark/70">{{ t(key="bank-variable-symbol", lang=lang | default(value='sk')) }}</span><span class="font-mono font-medium">{{ order.variable_symbol }}</span>
<span class="text-on-surface/70 dark:text-on-surface-dark/70">{{ t(key="bank-amount", lang=lang | default(value='sk')) }}</span><span class="font-medium tabular-nums">{{ order.total }} {{ order.currency }}</span>
<span class="text-on-surface/70 dark:text-on-surface-dark/70">{{ t(key="bank-amount", lang=lang | default(value='sk')) }}</span><span class="font-medium tabular-nums">{{ order.total }} </span>
</div>
</div>
{% else %}

View File

@@ -67,7 +67,7 @@
<label for="variant-select" class="text-sm font-medium text-on-surface-strong dark:text-on-surface-dark-strong">{{ t(key="choose-option", lang=lang | default(value='sk')) }}</label>
<select id="variant-select" x-model.number="sel" class="{{ fld }}">
<template x-for="(v, i) in variants" :key="v.id">
<option :value="i" x-text="(v.label || '—') + ' · ' + v.price + ' {{ product.currency }}' + (v.in_stock ? '' : ' ({{ t(key='out-of-stock', lang=lang | default(value='sk')) }})')"></option>
<option :value="i" x-text="(v.label || '—') + ' · ' + v.price + ' {{ currency_symbol }}' + (v.in_stock ? '' : ' ({{ t(key='out-of-stock', lang=lang | default(value='sk')) }})')"></option>
</template>
</select>
</div>
@@ -75,10 +75,10 @@
<div class="flex items-baseline gap-3">
<p class="text-2xl font-semibold" :class="current.on_sale ? 'text-danger' : 'text-primary dark:text-primary-dark'">
<span x-text="current.price"></span> {{ product.currency }}
<span x-text="current.price"></span> {{ currency_symbol }}
</p>
<template x-if="current.on_sale">
<p class="text-lg text-on-surface/50 line-through dark:text-on-surface-dark/50"><span x-text="current.regular_price"></span> {{ product.currency }}</p>
<p class="text-lg text-on-surface/50 line-through dark:text-on-surface-dark/50"><span x-text="current.regular_price"></span> {{ currency_symbol }}</p>
</template>
</div>

View File

@@ -47,6 +47,8 @@ mod m20260622_000005_product_search_aggregate;
mod m20260622_000006_order_search_indexes;
mod m20260623_000001_add_short_description_to_products;
mod m20260623_000002_strip_html_from_product_search;
mod m20260623_000003_drop_currency;
mod m20260623_000004_currencies;
pub struct Migrator;
#[async_trait::async_trait]
@@ -98,6 +100,8 @@ impl MigratorTrait for Migrator {
Box::new(m20260622_000006_order_search_indexes::Migration),
Box::new(m20260623_000001_add_short_description_to_products::Migration),
Box::new(m20260623_000002_strip_html_from_product_search::Migration),
Box::new(m20260623_000003_drop_currency::Migration),
Box::new(m20260623_000004_currencies::Migration),
// inject-above (do not remove this comment)
]
}

View File

@@ -0,0 +1,20 @@
use loco_rs::schema::*;
use sea_orm_migration::prelude::*;
#[derive(DeriveMigrationName)]
pub struct Migration;
#[async_trait::async_trait]
impl MigrationTrait for Migration {
async fn up(&self, m: &SchemaManager) -> Result<(), DbErr> {
// The store is EUR-only. Currency is no longer stored per product/order;
// the euro symbol is rendered everywhere in the UI.
remove_column(m, "products", "currency").await?;
remove_column(m, "orders", "currency").await
}
async fn down(&self, m: &SchemaManager) -> Result<(), DbErr> {
add_column(m, "products", "currency", ColType::StringWithDefault("EUR".to_string())).await?;
add_column(m, "orders", "currency", ColType::StringWithDefault("EUR".to_string())).await
}
}

View File

@@ -0,0 +1,31 @@
use loco_rs::schema::*;
use sea_orm_migration::prelude::*;
#[derive(DeriveMigrationName)]
pub struct Migration;
#[async_trait::async_trait]
impl MigrationTrait for Migration {
async fn up(&self, m: &SchemaManager) -> Result<(), DbErr> {
// Buyer-selectable display currencies. EUR is the base/transaction
// currency and is NOT stored here; each row is an alternative the buyer
// can switch to, whose prices are the EUR price recalculated at
// `rate_e4` (units of this currency per 1 EUR, scaled ×10000). For now
// the only row is CZK, seeded by `initializers::currency_seeder`.
create_table(m, "currencies",
&[
("id", ColType::PkAuto),
("code", ColType::StringUniq),
("symbol", ColType::String),
("rate_e4", ColType::BigIntegerWithDefault(10_000)),
("enabled", ColType::BooleanWithDefault(true)),
],
&[
]
).await
}
async fn down(&self, m: &SchemaManager) -> Result<(), DbErr> {
drop_table(m, "currencies").await
}
}

View File

@@ -17,9 +17,9 @@ use std::{path::Path, sync::Arc};
#[allow(unused_imports)]
use crate::{
controllers::{
account, admin_categories, admin_customers, admin_dashboard, admin_discount_profiles,
admin_form, admin_orders, admin_products, admin_shipping, auth, auth_pages,
cart, checkout, home, i18n, media, oauth2,
account, admin_categories, admin_currencies, admin_customers, admin_dashboard,
admin_discount_profiles, admin_form, admin_orders, admin_products, admin_shipping,
auth, auth_pages, cart, checkout, currency, home, i18n, media, oauth2,
shop,
},
initializers,
@@ -83,6 +83,7 @@ impl Hooks for App {
Box::new(initializers::view_engine::ViewEngineInitializer),
Box::new(initializers::admin_seeder::AdminSeeder),
Box::new(initializers::shipping_seeder::ShippingSeeder),
Box::new(initializers::currency_seeder::CurrencySeeder),
Box::new(initializers::oauth2::OAuth2StoreInitializer),
Box::new(initializers::oauth2_session::OAuth2SessionInitializer),
])
@@ -95,6 +96,7 @@ impl Hooks for App {
.add_route(shop::routes())
.add_route(cart::routes())
.add_route(checkout::routes())
.add_route(currency::routes())
// cross-cutting
.add_route(auth::routes())
.add_route(auth_pages::routes())
@@ -110,6 +112,7 @@ impl Hooks for App {
.add_route(admin_orders::routes())
.add_route(admin_customers::routes())
.add_route(admin_shipping::routes())
.add_route(admin_currencies::routes())
}
async fn after_context(ctx: AppContext) -> Result<AppContext> {

View File

@@ -0,0 +1,94 @@
//! Admin management of the alternative display currencies.
//!
//! EUR is the base/transaction currency and is shown read-only for context. The
//! admin sets each alternative currency's exchange rate (units per 1 EUR) and
//! toggles whether buyers may switch to it. The currencies themselves are fixed
//! and seeded by `initializers::currency_seeder`.
use axum_extra::extract::cookie::CookieJar;
use loco_rs::prelude::*;
use sea_orm::{ActiveModelTrait, EntityTrait, QueryOrder, Set};
use serde::Deserialize;
use serde_json::json;
use crate::{
controllers::i18n::current_lang,
models::currencies,
shared::{
currency::{self, BASE_CODE, BASE_SYMBOL},
guard,
},
};
#[derive(Debug, Deserialize)]
struct CurrencyForm {
rate: String,
enabled: Option<String>,
}
fn is_checked(value: &Option<String>) -> bool {
matches!(value.as_deref(), Some("on" | "true" | "1"))
}
#[debug_handler]
async fn index(
auth: auth::JWT,
jar: CookieJar,
ViewEngine(v): ViewEngine<TeraView>,
State(ctx): State<AppContext>,
) -> Result<Response> {
guard::current_admin(auth, &ctx).await?;
let rows = currencies::Entity::find()
.order_by_asc(currencies::Column::Code)
.all(&ctx.db)
.await?;
let currencies_json: Vec<serde_json::Value> = rows
.iter()
.map(|c| {
json!({
"id": c.id,
"code": c.code,
"symbol": c.symbol,
"rate": currency::format_rate(c.rate_e4),
"enabled": c.enabled,
})
})
.collect();
format::view(
&v,
"admin/currencies/index.html",
json!({
"base_code": BASE_CODE,
"base_symbol": BASE_SYMBOL,
"currencies": currencies_json,
"lang": current_lang(&jar),
}),
)
}
#[debug_handler]
async fn update(
auth: auth::JWT,
Path(id): Path<i32>,
State(ctx): State<AppContext>,
Form(form): Form<CurrencyForm>,
) -> Result<Response> {
guard::current_admin(auth, &ctx).await?;
let row = currencies::Entity::find_by_id(id)
.one(&ctx.db)
.await?
.ok_or_else(|| Error::NotFound)?;
let mut active = row.into_active_model();
active.rate_e4 = Set(currency::parse_rate(&form.rate)?);
active.enabled = Set(is_checked(&form.enabled));
active.update(&ctx.db).await?;
// Keep the navbar/settings chrome snapshot in sync with the new rate/state.
currency::refresh_snapshot(&ctx.db).await?;
format::redirect("/admin/currencies")
}
pub fn routes() -> Routes {
Routes::new()
.add("/admin/currencies", get(index))
.add("/admin/currencies/{id}", post(update))
}

View File

@@ -198,7 +198,6 @@ async fn show(
"variant_id": variant.id,
"name": product.name,
"variant_label": variant.label,
"currency": product.currency,
"regular_price": format_price(d.regular_cents),
"business_price": format_price(b.price_cents),
"business_reduced": b.price_cents < d.regular_cents,
@@ -285,7 +284,6 @@ async fn price_edit(
"variant_id": variant.id,
"name": product.name,
"variant_label": variant.label,
"currency": product.currency,
"regular_price": format_price(d.regular_cents),
"regular_cents": d.regular_cents,
"business_price": format_price(business_cents),

View File

@@ -202,7 +202,6 @@ async fn ship(
country: order.country.as_deref(),
pickup_point_id: order.pickup_point_id.as_deref(),
cod_cents,
currency: &order.currency,
value_cents: goods_value,
weight_grams: DEFAULT_PARCEL_WEIGHT_GRAMS,
};

View File

@@ -53,7 +53,6 @@ struct ProductFields {
slug: String,
description: Option<String>,
short_description: Option<String>,
currency: String,
category_id: Option<i32>,
published: bool,
}
@@ -66,7 +65,6 @@ async fn parse_product_fields(
let name = form
.text("name")
.ok_or_else(|| Error::BadRequest("product name is required".to_string()))?;
let currency = form.text("currency").unwrap_or_else(|| "EUR".to_string());
let description = form.text("description");
let short_description = form.text("short_description");
let category_id = form.text("category_id").and_then(|s| s.parse::<i32>().ok());
@@ -94,7 +92,6 @@ async fn parse_product_fields(
slug,
description,
short_description,
currency,
category_id,
published,
})
@@ -366,7 +363,6 @@ fn product_row(
"id": product.id,
"name": product.name,
"slug": product.slug,
"currency": product.currency,
"stock": stock_display,
"variant_count": variant_count,
"has_options": variant_count > 1,
@@ -442,7 +438,6 @@ async fn create(
slug: Set(fields.slug),
description: Set(fields.description),
short_description: Set(fields.short_description),
currency: Set(fields.currency),
view_count: Set(0),
published: Set(fields.published),
published_at: Set(fields.published.then(|| chrono::Utc::now().into())),
@@ -557,7 +552,6 @@ async fn update(
product.slug = Set(fields.slug);
product.description = Set(fields.description);
product.short_description = Set(fields.short_description);
product.currency = Set(fields.currency);
product.category_id = Set(fields.category_id);
product.published = Set(fields.published);
if fields.published && !was_published {
@@ -704,7 +698,6 @@ async fn profiles_preview(
}
rows.push(json!({
"id": product.id,
"currency": product.currency,
"effective_price": format_price(priced.price_cents),
"effective_reduced": priced.is_reduced(),
"effective_percent_off": percent_off(priced.regular_cents, priced.price_cents),
@@ -816,13 +809,12 @@ impl DiscountRow {
}
}
fn to_json(&self, currency: &str) -> serde_json::Value {
fn to_json(&self) -> serde_json::Value {
json!({
"id": self.id,
"label": self.label,
"regular_cents": self.regular_cents,
"regular_price": format_price(self.regular_cents),
"currency": currency,
"mode": self.mode,
"fixed": self.fixed,
"percent": self.percent,
@@ -871,7 +863,7 @@ async fn discount_view(
audience: &str,
error: Option<&str>,
) -> Result<Response> {
let rows_json: Vec<_> = rows.iter().map(|r| r.to_json(&product.currency)).collect();
let rows_json: Vec<_> = rows.iter().map(DiscountRow::to_json).collect();
let has_discount = rows.iter().any(|r| r.has_discount);
format::view(
v,
@@ -880,7 +872,6 @@ async fn discount_view(
"product": {
"id": product.id,
"name": product.name,
"currency": product.currency,
},
"rows": rows_json,
"audience": audience,

View File

@@ -1,4 +1,4 @@
use crate::{controllers::i18n::current_lang, shared::{guard, money::format_price, pricing}, models::{product_variants, products}};
use crate::{controllers::i18n::current_lang, shared::{currency::{self, Currency}, guard, pricing}, models::{product_variants, products}};
use axum::{
http::{HeaderMap, StatusCode},
response::Redirect,
@@ -65,7 +65,7 @@ fn cart_cookie(value: String) -> Cookie<'static> {
}
/// Look up a variant whose product is published, returning the variant together
/// with its parent product (for name/slug/currency).
/// with its parent product (for name/slug).
async fn published_variant(
ctx: &AppContext,
variant_id: i32,
@@ -173,12 +173,8 @@ async fn cart_response(
return Ok((jar, Redirect::to("/cart")).into_response());
}
let (lines, valid, total) = resolve_cart(ctx, &jar).await?;
let currency = lines
.first()
.and_then(|line| line["currency"].as_str())
.unwrap_or("EUR")
.to_string();
let cur = currency::resolve(ctx, &jar).await;
let (lines, valid, total) = resolve_cart(ctx, &jar, &cur).await?;
// Persist the re-validated cookie (drops now-invalid lines).
let jar = jar.add(cart_cookie(serialize_cart(&valid)));
let response = format::view(
@@ -186,8 +182,8 @@ async fn cart_response(
"shop/_cart_body.html",
json!({
"items": lines,
"total": format_price(total),
"currency": currency,
"total": cur.format(total),
"currency_symbol": cur.symbol,
"lang": current_lang(&jar),
}),
)?;
@@ -200,6 +196,7 @@ async fn cart_response(
pub(crate) async fn resolve_cart(
ctx: &AppContext,
jar: &CookieJar,
cur: &Currency,
) -> Result<(Vec<serde_json::Value>, Vec<(i32, i32)>, i64)> {
// Resolve the cart entries to in-stock products first, then price them all
// for the current viewer in one batch (the price depends on who's logged in).
@@ -232,13 +229,12 @@ pub(crate) async fn resolve_cart(
"name": product.name,
"variant_label": variant.label,
"slug": product.slug,
"price": format_price(unit_price),
"regular_price": format_price(priced.regular_cents),
"price": cur.format(unit_price),
"regular_price": cur.format(priced.regular_cents),
"on_sale": priced.is_reduced(),
"currency": product.currency,
"quantity": qty,
"stock": variant.stock,
"line_total": format_price(line_total),
"line_total": cur.format(line_total),
}));
}
@@ -251,12 +247,8 @@ async fn show(
ViewEngine(v): ViewEngine<TeraView>,
State(ctx): State<AppContext>,
) -> Result<Response> {
let (lines, valid, total) = resolve_cart(&ctx, &jar).await?;
let currency = lines
.first()
.and_then(|line| line["currency"].as_str())
.unwrap_or("EUR")
.to_string();
let cur = currency::resolve(&ctx, &jar).await;
let (lines, valid, total) = resolve_cart(&ctx, &jar, &cur).await?;
// Drop any now-invalid lines from the cookie so the badge stays accurate.
let rebuilt = serialize_cart(&valid);
@@ -266,8 +258,8 @@ async fn show(
"shop/cart.html",
json!({
"items": lines,
"total": format_price(total),
"currency": currency,
"total": cur.format(total),
"currency_symbol": cur.symbol,
"logged_in_admin": c.logged_in_admin,
"logged_in_customer": c.logged_in_customer,
"customer_name": c.customer_name,
@@ -287,20 +279,16 @@ async fn preview(
ViewEngine(v): ViewEngine<TeraView>,
State(ctx): State<AppContext>,
) -> Result<Response> {
let (lines, valid, total) = resolve_cart(&ctx, &jar).await?;
let currency = lines
.first()
.and_then(|line| line["currency"].as_str())
.unwrap_or("EUR")
.to_string();
let cur = currency::resolve(&ctx, &jar).await;
let (lines, valid, total) = resolve_cart(&ctx, &jar, &cur).await?;
let rebuilt = serialize_cart(&valid);
let response = format::view(
&v,
"shop/_cart_preview.html",
json!({
"items": lines,
"total": format_price(total),
"currency": currency,
"total": cur.format(total),
"currency_symbol": cur.symbol,
"lang": current_lang(&jar),
}),
)?;

View File

@@ -18,7 +18,7 @@ use crate::{
users::{self, normalize_account_type},
},
controllers::i18n::current_lang,
shared::{guard, money::format_price, settings},
shared::{currency::Currency, guard, money::format_price, settings},
views::checkout as view,
};
@@ -77,15 +77,12 @@ async fn checkout_page(
ViewEngine(v): ViewEngine<TeraView>,
State(ctx): State<AppContext>,
) -> Result<Response> {
let (lines, _valid, subtotal) = resolve_cart(&ctx, &jar).await?;
// Checkout and everything past it (orders, confirmation) stay in the EUR
// base — the settlement currency — even when the buyer browsed in another.
let (lines, _valid, subtotal) = resolve_cart(&ctx, &jar, &Currency::eur()).await?;
if lines.is_empty() {
return format::redirect("/cart");
}
let currency = lines
.first()
.and_then(|line| line["currency"].as_str())
.unwrap_or("EUR")
.to_string();
let methods: Vec<serde_json::Value> = enabled_shipping_methods(&ctx)
.await?
@@ -127,7 +124,6 @@ async fn checkout_page(
"items": lines,
"subtotal": format_price(subtotal),
"subtotal_cents": subtotal,
"currency": currency,
"shipping_methods": methods,
"packeta_api_key": settings::get(&ctx, "packeta_api_key").unwrap_or(""),
"logged_in_admin": is_admin,
@@ -165,7 +161,7 @@ async fn place_order(
State(ctx): State<AppContext>,
Form(form): Form<CheckoutForm>,
) -> Result<Response> {
let (_lines, valid, _total) = resolve_cart(&ctx, &jar).await?;
let (_lines, valid, _total) = resolve_cart(&ctx, &jar, &Currency::eur()).await?;
if valid.is_empty() {
return format::redirect("/cart");
}

View File

@@ -0,0 +1,39 @@
//! Storefront display-currency switcher.
//!
//! Sets the `currency` cookie to the buyer's chosen display currency, then sends
//! them back where they were. EUR is the base; any other code must name an
//! enabled row in `currencies` or it falls back to EUR on the next render.
use axum::{
http::{header, HeaderMap},
response::Redirect,
};
use loco_rs::prelude::*;
use serde::Deserialize;
use crate::controllers::i18n::back_path;
use crate::shared::currency::{BASE_CODE, COOKIE};
#[derive(Debug, Deserialize)]
pub struct CurrencyForm {
pub currency: String,
}
#[debug_handler]
async fn set_currency(headers: HeaderMap, Form(form): Form<CurrencyForm>) -> Result<Response> {
// Store the code uppercased; validation against the enabled set happens at
// render time (shared::currency::resolve), which falls back to EUR.
let code = form.currency.trim().to_uppercase();
let code = if code.is_empty() { BASE_CODE.to_string() } else { code };
let cookie = format!("{COOKIE}={code}; Path=/; Max-Age=31536000; SameSite=Lax");
Ok((
[(header::SET_COOKIE, cookie)],
Redirect::to(&back_path(&headers)),
)
.into_response())
}
pub fn routes() -> Routes {
Routes::new().add("/currency", post(set_currency))
}

View File

@@ -4,7 +4,9 @@ use axum_extra::extract::cookie::CookieJar;
use loco_rs::prelude::*;
use serde_json::json;
use crate::{controllers::i18n::current_lang, shared::guard, controllers::shop};
use crate::{
controllers::i18n::current_lang, controllers::shop, shared::currency, shared::guard,
};
#[debug_handler]
async fn index(
@@ -13,7 +15,8 @@ async fn index(
State(ctx): State<AppContext>,
) -> Result<Response> {
let user = guard::current_user(&ctx, &jar).await;
let products = shop::featured_products(&ctx, user.as_ref(), 8).await?;
let cur = currency::resolve(&ctx, &jar).await;
let products = shop::featured_products(&ctx, user.as_ref(), 8, &cur).await?;
let c = guard::chrome_from(&ctx, user.as_ref());
format::view(
@@ -25,6 +28,7 @@ async fn index(
"logged_in_customer": c.logged_in_customer,
"customer_name": c.customer_name,
"customer_account_type": c.customer_account_type,
"currency_symbol": cur.symbol,
"lang": current_lang(&jar),
}),
)

View File

@@ -34,7 +34,7 @@ async fn set_lang(headers: HeaderMap, Form(form): Form<LangForm>) -> Result<Resp
.into_response())
}
fn back_path(headers: &HeaderMap) -> String {
pub(crate) fn back_path(headers: &HeaderMap) -> String {
let raw = headers
.get(header::REFERER)
.and_then(|value| value.to_str().ok())

View File

@@ -3,6 +3,7 @@ pub mod auth;
pub mod auth_pages;
pub mod oauth2;
pub mod admin_categories;
pub mod admin_currencies;
pub mod admin_customers;
pub mod admin_dashboard;
pub mod admin_discount_profiles;
@@ -12,6 +13,7 @@ pub mod admin_products;
pub mod admin_shipping;
pub mod cart;
pub mod checkout;
pub mod currency;
pub mod home;
pub mod i18n;
pub mod media;

View File

@@ -13,8 +13,9 @@ use serde_json::json;
use crate::{
controllers::i18n::current_lang,
shared::{
currency::{self, Currency},
guard,
money::{format_price, parse_price_to_cents},
money::parse_price_to_cents,
pricing,
},
models::{categories, product_images, product_variants, products, users},
@@ -90,6 +91,7 @@ async fn run_search(
ctx: &AppContext,
user: Option<&users::Model>,
params: &SearchParams,
cur: &Currency,
) -> Result<serde_json::Value> {
let q = params.q.clone().unwrap_or_default();
let q_trim = q.trim().to_string();
@@ -136,9 +138,19 @@ async fn run_search(
let price_floor = items.iter().map(|i| i.priced.price_cents).min().unwrap_or(0);
let price_ceil = items.iter().map(|i| i.priced.price_cents).max().unwrap_or(0);
// 3. Non-category filters: price band + in-stock.
let min_c = params.min_price.as_deref().and_then(|s| parse_price_to_cents(s).ok());
let max_c = params.max_price.as_deref().and_then(|s| parse_price_to_cents(s).ok());
// 3. Non-category filters: price band + in-stock. The typed bounds are in
// the buyer's display currency; convert them back to EUR cents to compare
// against the (EUR) resolved prices.
let min_c = params
.min_price
.as_deref()
.and_then(|s| parse_price_to_cents(s).ok())
.map(|c| cur.to_eur_cents(c));
let max_c = params
.max_price
.as_deref()
.and_then(|s| parse_price_to_cents(s).ok())
.map(|c| cur.to_eur_cents(c));
let in_stock_only = is_on(&params.in_stock);
items.retain(|i| {
min_c.is_none_or(|m| i.priced.price_cents >= m)
@@ -203,6 +215,7 @@ async fn run_search(
item.count,
image,
cat_name,
cur,
));
}
@@ -219,8 +232,9 @@ async fn run_search(
"in_stock": in_stock_only,
"min_price": params.min_price.clone().unwrap_or_default(),
"max_price": params.max_price.clone().unwrap_or_default(),
"price_floor": format_price(price_floor),
"price_ceil": format_price(price_ceil),
"price_floor": cur.format(price_floor),
"price_ceil": cur.format(price_ceil),
"currency_symbol": cur.symbol,
"total": total,
"page": page,
"pages": pages,
@@ -240,6 +254,7 @@ async fn product_rows(
ctx: &AppContext,
user: Option<&users::Model>,
list: Vec<products::Model>,
cur: &Currency,
) -> Result<Vec<serde_json::Value>> {
let ids: Vec<i32> = list.iter().map(|p| p.id).collect();
let grouped = product_variants::Entity::grouped_for_products(&ctx.db, &ids).await?;
@@ -261,7 +276,7 @@ async fn product_rows(
let mut rows = Vec::with_capacity(entries.len());
for ((product, rep, count), priced) in entries.iter().zip(priced.iter()) {
let image = product_images::first_for(ctx, product.id).await?;
rows.push(view::product_card(product, rep, priced, *count, image, None));
rows.push(view::product_card(product, rep, priced, *count, image, None, cur));
}
Ok(rows)
}
@@ -272,6 +287,7 @@ pub(crate) async fn featured_products(
ctx: &AppContext,
user: Option<&users::Model>,
limit: u64,
cur: &Currency,
) -> Result<Vec<serde_json::Value>> {
let list = products::Entity::find()
.filter(products::Column::Published.eq(true))
@@ -279,7 +295,7 @@ pub(crate) async fn featured_products(
.limit(limit)
.all(&ctx.db)
.await?;
product_rows(ctx, user, list).await
product_rows(ctx, user, list, cur).await
}
/// The site-wide category sidebar, loaded lazily via htmx by the base layout so
@@ -320,7 +336,8 @@ async fn index(
State(ctx): State<AppContext>,
) -> Result<Response> {
let user = guard::current_user(&ctx, &jar).await;
let mut context = run_search(&ctx, user.as_ref(), &SearchParams::default()).await?;
let cur = currency::resolve(&ctx, &jar).await;
let mut context = run_search(&ctx, user.as_ref(), &SearchParams::default(), &cur).await?;
let c = guard::chrome_from(&ctx, user.as_ref());
add_chrome(&mut context, &c, &current_lang(&jar));
format::view(&v, "shop/index.html", context)
@@ -341,7 +358,8 @@ async fn search(
State(ctx): State<AppContext>,
) -> Result<Response> {
let user = guard::current_user(&ctx, &jar).await;
let mut context = run_search(&ctx, user.as_ref(), &params).await?;
let cur = currency::resolve(&ctx, &jar).await;
let mut context = run_search(&ctx, user.as_ref(), &params, &cur).await?;
let lang = current_lang(&jar);
if headers.contains_key("HX-Request") {
@@ -385,12 +403,13 @@ async fn show(
};
let user = guard::current_user(&ctx, &jar).await;
let cur = currency::resolve(&ctx, &jar).await;
let variants = product_variants::Entity::for_product(&ctx.db, product.id).await?;
let variant_prices = pricing::price_variants(&ctx, &variants, user.as_ref()).await?;
let options: Vec<serde_json::Value> = variants
.iter()
.zip(variant_prices.iter())
.map(|(variant, priced)| view::variant_option(variant, priced))
.map(|(variant, priced)| view::variant_option(variant, priced, &cur))
.collect();
// The card header uses the representative (first) variant for its headline
// price; the picker below lets the customer switch.
@@ -404,6 +423,7 @@ async fn show(
variants.len(),
None,
category.as_ref().map(|c| c.name.clone()),
&cur,
),
// A product with no variants isn't purchasable; show it without a price.
_ => serde_json::json!({
@@ -411,7 +431,6 @@ async fn show(
"name": product.name,
"slug": product.slug,
"description": product.description,
"currency": product.currency,
"variant_count": 0,
"has_options": false,
}),
@@ -429,6 +448,7 @@ async fn show(
"logged_in_customer": c.logged_in_customer,
"customer_name": c.customer_name,
"customer_account_type": c.customer_account_type,
"currency_symbol": cur.symbol,
"lang": current_lang(&jar),
}),
)
@@ -464,7 +484,8 @@ async fn category(
};
let user = guard::current_user(&ctx, &jar).await;
let mut context = run_search(&ctx, user.as_ref(), &params).await?;
let cur = currency::resolve(&ctx, &jar).await;
let mut context = run_search(&ctx, user.as_ref(), &params, &cur).await?;
if let Some(map) = context.as_object_mut() {
map.insert("category".into(), serde_json::to_value(&category)?);
map.insert("breadcrumbs".into(), serde_json::to_value(&breadcrumbs)?);

View File

@@ -0,0 +1,52 @@
//! Ensures the built-in alternative display currencies always exist.
//!
//! EUR is the base currency and is never stored. For now the only alternative is
//! the Czech koruna (CZK); the admin sets its exchange rate and can disable it.
//! We insert each one only when its `code` is missing, so an admin's rate/enabled
//! changes are never overwritten on the next boot.
use async_trait::async_trait;
use loco_rs::prelude::*;
use sea_orm::{ActiveModelTrait, ColumnTrait, EntityTrait, PaginatorTrait, QueryFilter, Set};
use crate::models::currencies;
use crate::shared::currency::{self, SCALE};
/// `(code, symbol, default_rate_e4)` — default rate is a placeholder the admin
/// is expected to update from the live FX rate.
const BUILTINS: [(&str, &str, i64); 1] = [("CZK", "", 25 * SCALE)];
pub struct CurrencySeeder;
#[async_trait]
impl Initializer for CurrencySeeder {
fn name(&self) -> String {
"currency-seeder".to_string()
}
async fn before_run(&self, ctx: &AppContext) -> Result<()> {
for (code, symbol, rate_e4) in BUILTINS {
let exists = currencies::Entity::find()
.filter(currencies::Column::Code.eq(code))
.count(&ctx.db)
.await?
> 0;
if exists {
continue;
}
currencies::ActiveModel {
code: Set(code.to_string()),
symbol: Set(symbol.to_string()),
rate_e4: Set(rate_e4),
enabled: Set(true),
..Default::default()
}
.insert(&ctx.db)
.await?;
tracing::info!(currency = code, "seeded display currency");
}
// Prime the process-wide snapshot used by the navbar/settings chrome.
currency::refresh_snapshot(&ctx.db).await?;
Ok(())
}
}

View File

@@ -1,4 +1,5 @@
pub mod admin_seeder;
pub mod currency_seeder;
pub mod oauth2;
pub mod oauth2_session;
pub mod shipping_seeder;

View File

@@ -54,6 +54,12 @@ impl Initializer for ViewEngineInitializer {
crate::shared::csrf::current_token().unwrap_or_default(),
))
});
// `currencies()`: the EUR base plus enabled alternative currencies
// (from the process-wide snapshot), used by the global chrome — the
// settings-menu switcher and the navbar exchange-rate display.
tera.register_function("currencies", |_args: &HashMap<String, serde_json::Value>| {
Ok(crate::shared::currency::selectable_json())
});
Ok(())
})?;

View File

@@ -28,7 +28,6 @@ pub struct ShipmentRequest<'a> {
pub pickup_point_id: Option<&'a str>,
/// Cash-on-delivery amount in cents; `0` when payment is not COD.
pub cod_cents: i64,
pub currency: &'a str,
/// Total order value in cents (for insurance / customs declarations).
pub value_cents: i64,
pub weight_grams: i32,

View File

@@ -77,7 +77,7 @@ pub async fn create_shipment(ctx: &AppContext, req: ShipmentRequest<'_>) -> Resu
xml_escape(address_id),
value,
cod,
xml_escape(req.currency),
"EUR",
weight_kg,
xml_escape(sender_label),
);

View File

@@ -0,0 +1,22 @@
//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.19
use sea_orm::entity::prelude::*;
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq, Serialize, Deserialize)]
#[sea_orm(table_name = "currencies")]
pub struct Model {
pub created_at: DateTimeWithTimeZone,
pub updated_at: DateTimeWithTimeZone,
#[sea_orm(primary_key)]
pub id: i32,
#[sea_orm(unique)]
pub code: String,
pub symbol: String,
/// Units of this currency per 1 EUR, scaled ×10000 (e.g. 25.30 → 253000).
pub rate_e4: i64,
pub enabled: bool,
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {}

View File

@@ -8,6 +8,7 @@ pub mod account_product_resolutions;
pub mod audience_discount_profiles;
pub mod audit_logs;
pub mod categories;
pub mod currencies;
pub mod customer_profiles;
pub mod discount_profile_products;
pub mod discount_profiles;

View File

@@ -16,7 +16,6 @@ pub struct Model {
pub customer_name: Option<String>,
pub status: String,
pub total_cents: i64,
pub currency: String,
pub address: Option<String>,
pub city: Option<String>,
pub zip: Option<String>,

View File

@@ -6,6 +6,7 @@ pub use super::account_product_resolutions::Entity as AccountProductResolutions;
pub use super::audience_discount_profiles::Entity as AudienceDiscountProfiles;
pub use super::audit_logs::Entity as AuditLogs;
pub use super::categories::Entity as Categories;
pub use super::currencies::Entity as Currencies;
pub use super::customer_profiles::Entity as CustomerProfiles;
pub use super::discount_profile_products::Entity as DiscountProfileProducts;
pub use super::discount_profiles::Entity as DiscountProfiles;

View File

@@ -17,7 +17,6 @@ pub struct Model {
pub description: Option<String>,
#[sea_orm(column_type = "Text", nullable)]
pub short_description: Option<String>,
pub currency: String,
pub view_count: i32,
pub published: bool,
pub published_at: Option<DateTimeWithTimeZone>,

40
src/models/currencies.rs Normal file
View File

@@ -0,0 +1,40 @@
use sea_orm::entity::prelude::*;
pub use crate::models::_entities::currencies::{ActiveModel, Column, Entity, Model};
pub type Currencies = Entity;
#[async_trait::async_trait]
impl ActiveModelBehavior for ActiveModel {
async fn before_save<C>(self, _db: &C, insert: bool) -> std::result::Result<Self, DbErr>
where
C: ConnectionTrait,
{
if !insert && self.updated_at.is_unchanged() {
let mut this = self;
this.updated_at = sea_orm::ActiveValue::Set(chrono::Utc::now().into());
Ok(this)
} else {
Ok(self)
}
}
}
// implement your read-oriented logic here
impl Model {}
// implement your write-oriented logic here
impl ActiveModel {}
// implement your custom finders, selectors oriented logic here
impl Entity {
/// An enabled currency by its ISO code (case-insensitive), or `None`.
pub async fn find_enabled_by_code<C: ConnectionTrait>(
db: &C,
code: &str,
) -> Result<Option<Model>, DbErr> {
Entity::find()
.filter(Column::Code.eq(code.to_uppercase()))
.filter(Column::Enabled.eq(true))
.one(db)
.await
}
}

View File

@@ -12,6 +12,7 @@ pub mod account_product_resolutions;
pub mod audience_discount_profiles;
pub mod audit_logs;
pub mod categories;
pub mod currencies;
pub mod discount_profile_products;
pub mod discount_profiles;
pub mod customer_profiles;

View File

@@ -53,7 +53,6 @@ pub async fn place(
let txn = ctx.db.begin().await?;
let mut subtotal: i64 = 0;
let mut currency = "EUR".to_string();
let mut snapshots = Vec::new();
for (variant_id, qty) in items {
let variant = product_variants::Entity::find_by_id(*variant_id)
@@ -75,7 +74,6 @@ pub async fn place(
)));
}
}
currency = product.currency.clone();
// Snapshot the price the buyer actually pays — public sale or, for a
// business account, their negotiated/lowest price (same resolver the
// cart and storefront use).
@@ -98,7 +96,6 @@ pub async fn place(
customer_name: Set(details.customer_name),
status: Set("pending".to_string()),
total_cents: Set(subtotal + details.method.price_cents),
currency: Set(currency),
user_id: Set(details.user_id),
account_type: Set(details.account_type),
company_name: Set(details.company_name),

View File

@@ -57,7 +57,7 @@ impl Entity {
let sql = format!(
r#"
SELECT p.created_at, p.updated_at, p.id, p.name, p.slug, p.description,
p.currency, p.view_count, p.published, p.published_at, p.category_id
p.short_description, p.view_count, p.published, p.published_at, p.category_id
FROM products p
WHERE {published_clause} (
p.search_vector @@ websearch_to_tsquery('sk_unaccent', $1)

View File

@@ -161,7 +161,6 @@ pub async fn seed_catalog(ctx: &AppContext) -> Result<()> {
name: Set(item.name.to_string()),
slug: Set(product_slug),
description: Set(Some(item.description.to_string())),
currency: Set("EUR".to_string()),
published: Set(true),
published_at: Set(Some(now.into())),
category_id: Set(category.map(|c| c.id)),

206
src/shared/currency.rs Normal file
View File

@@ -0,0 +1,206 @@
//! Buyer-selectable display currency.
//!
//! EUR is the base/transaction currency: every price is stored and reasoned
//! about in EUR minor units (cents). A buyer may switch their *display* currency
//! (cookie [`COOKIE`]); non-base currencies live in the `currencies` table with
//! an admin-set exchange `rate_e4` (units per 1 EUR, scaled ×10000). The
//! [`Currency`] resolved per request converts EUR cents into the chosen currency
//! for display only — the cart logic, orders and admin stay in EUR.
use std::sync::RwLock;
use axum_extra::extract::cookie::CookieJar;
use loco_rs::prelude::*;
use sea_orm::{ColumnTrait, EntityTrait, QueryFilter, QueryOrder};
use crate::models::currencies;
use crate::shared::money::format_price;
/// Cookie holding the buyer's chosen display-currency code.
pub const COOKIE: &str = "currency";
/// The base/transaction currency code.
pub const BASE_CODE: &str = "EUR";
/// The base currency symbol.
pub const BASE_SYMBOL: &str = "";
/// Fixed-point scale for exchange rates (`rate_e4` = rate × 10000).
pub const SCALE: i64 = 10_000;
/// A resolved display currency: how to label prices and how to convert them
/// from the EUR base.
#[derive(Debug, Clone)]
pub struct Currency {
pub code: String,
pub symbol: String,
/// Units of this currency per 1 EUR, scaled ×10000. `SCALE` for the base.
pub rate_e4: i64,
}
impl Currency {
/// The base currency (EUR), the identity conversion.
#[must_use]
pub fn eur() -> Self {
Self {
code: BASE_CODE.to_string(),
symbol: BASE_SYMBOL.to_string(),
rate_e4: SCALE,
}
}
#[must_use]
pub fn is_base(&self) -> bool {
self.code == BASE_CODE
}
/// Convert EUR minor units into this currency's minor units (half-up).
#[must_use]
pub fn convert_cents(&self, eur_cents: i64) -> i64 {
if self.is_base() {
return eur_cents;
}
let scale = i128::from(SCALE);
((i128::from(eur_cents) * i128::from(self.rate_e4) + scale / 2) / scale) as i64
}
/// Inverse of [`convert_cents`]: this currency's minor units back to EUR
/// minor units (half-up). Used to interpret price-filter bounds typed in the
/// display currency.
#[must_use]
pub fn to_eur_cents(&self, cents: i64) -> i64 {
if self.is_base() || self.rate_e4 == 0 {
return cents;
}
let rate = i128::from(self.rate_e4);
((i128::from(cents) * i128::from(SCALE) + rate / 2) / rate) as i64
}
/// Render EUR minor units as a plain decimal string in this currency (no
/// symbol). The symbol is appended by templates via `currency_symbol`.
#[must_use]
pub fn format(&self, eur_cents: i64) -> String {
format_price(self.convert_cents(eur_cents))
}
}
/// Resolve the buyer's display currency from the `currency` cookie, falling back
/// to EUR when the cookie is absent, names the base, or names a currency that is
/// missing or disabled.
pub async fn resolve(ctx: &AppContext, jar: &CookieJar) -> Currency {
let code = jar
.get(COOKIE)
.map(|c| c.value().to_string())
.unwrap_or_default();
if code.is_empty() || code.eq_ignore_ascii_case(BASE_CODE) {
return Currency::eur();
}
match currencies::Entity::find_enabled_by_code(&ctx.db, &code).await {
Ok(Some(m)) => Currency {
code: m.code,
symbol: m.symbol,
rate_e4: m.rate_e4,
},
_ => Currency::eur(),
}
}
/// One enabled, buyer-selectable alternative currency in the process-wide
/// snapshot below.
#[derive(Clone)]
struct Selectable {
code: String,
symbol: String,
rate_e4: i64,
}
/// Process-wide snapshot of the enabled alternative currencies, so the global
/// chrome (the settings-menu switcher and the navbar rate) can be rendered via a
/// Tera function without a per-request DB hit. Loaded at boot by
/// `initializers::currency_seeder` and refreshed by the admin on every edit (see
/// [`refresh_snapshot`]). EUR (the base) is implicit and never listed here.
static ENABLED: RwLock<Vec<Selectable>> = RwLock::new(Vec::new());
/// Reload the [`ENABLED`] snapshot from the database. Call at boot and after any
/// admin change to a currency's rate/enabled state.
pub async fn refresh_snapshot<C: sea_orm::ConnectionTrait>(db: &C) -> Result<()> {
let rows = currencies::Entity::find()
.filter(currencies::Column::Enabled.eq(true))
.order_by_asc(currencies::Column::Code)
.all(db)
.await?;
let list = rows
.into_iter()
.map(|m| Selectable {
code: m.code,
symbol: m.symbol,
rate_e4: m.rate_e4,
})
.collect();
*ENABLED.write().unwrap() = list;
Ok(())
}
/// The selectable currencies for templates (the Tera `currencies()` function):
/// the EUR base plus every enabled alternative, each with a human rate string.
/// `alts` is empty when the store is effectively EUR-only.
#[must_use]
pub fn selectable_json() -> serde_json::Value {
let alts: Vec<serde_json::Value> = ENABLED
.read()
.unwrap()
.iter()
.map(|s| {
serde_json::json!({
"code": s.code,
"symbol": s.symbol,
"rate": format_rate(s.rate_e4),
})
})
.collect();
serde_json::json!({
"base": { "code": BASE_CODE, "symbol": BASE_SYMBOL },
"alts": alts,
})
}
/// Parse an exchange rate typed in major units ("25", "25.3", "25,30",
/// "25.3045") into `rate_e4` (×10000). Rejects negatives and >4 decimals.
pub fn parse_rate(value: &str) -> Result<i64> {
let value = value.trim().replace(',', ".");
let invalid = || Error::BadRequest("invalid exchange rate".to_string());
let (whole, frac) = match value.split_once('.') {
Some((w, f)) => (w, f),
None => (value.as_str(), ""),
};
if frac.len() > 4 || whole.is_empty() || !whole.chars().all(|c| c.is_ascii_digit()) {
return Err(invalid());
}
if !frac.chars().all(|c| c.is_ascii_digit()) {
return Err(invalid());
}
let whole: i64 = whole.parse().map_err(|_| invalid())?;
// Right-pad the fractional part to exactly 4 digits.
let padded = format!("{frac:0<4}");
let frac: i64 = if padded.is_empty() {
0
} else {
padded.parse().map_err(|_| invalid())?
};
let rate = whole * SCALE + frac;
if rate <= 0 {
return Err(invalid());
}
Ok(rate)
}
/// Render `rate_e4` as a human string, trimming trailing zeros (253000 → "25.3",
/// 250000 → "25").
#[must_use]
pub fn format_rate(rate_e4: i64) -> String {
let whole = rate_e4 / SCALE;
let frac = (rate_e4 % SCALE).abs();
if frac == 0 {
return whole.to_string();
}
let frac = format!("{frac:04}");
let trimmed = frac.trim_end_matches('0');
format!("{whole}.{trimmed}")
}

View File

@@ -1,6 +1,7 @@
//! Cross-cutting helpers used across feature slices.
pub mod csrf;
pub mod currency;
pub mod guard;
pub mod money;
pub mod pricing;

View File

@@ -40,7 +40,6 @@ pub fn detail(order: &orders::Model, bank_iban: &str, bank_account_name: &str) -
"subtotal": format_price(order.total_cents - order.shipping_cents),
"shipping": format_price(order.shipping_cents),
"total": format_price(order.total_cents),
"currency": order.currency,
"address": order.address,
"city": order.city,
"zip": order.zip,
@@ -68,7 +67,6 @@ pub fn summary(order: &orders::Model) -> Value {
"email": order.email,
"status": order.status,
"total": format_price(order.total_cents),
"currency": order.currency,
"created_at": order.created_at.to_rfc3339(),
})
}

View File

@@ -3,7 +3,7 @@
use serde_json::{json, Value};
use crate::models::_entities::{categories, product_images, product_variants, products};
use crate::shared::money::format_price;
use crate::shared::currency::Currency;
use crate::shared::pricing::PricedProduct;
/// Card/list shape for a product: model fields plus the viewer's resolved price
@@ -20,6 +20,7 @@ pub fn product_card(
variant_count: usize,
image: Option<String>,
category_name: Option<String>,
cur: &Currency,
) -> Value {
json!({
"id": product.id,
@@ -28,11 +29,10 @@ pub fn product_card(
"slug": product.slug,
"description": product.description,
"short_description": product.short_description,
"price": format_price(priced.price_cents),
"price": cur.format(priced.price_cents),
"on_sale": priced.is_reduced(),
"is_business": priced.is_business,
"regular_price": format_price(priced.regular_cents),
"currency": product.currency,
"regular_price": cur.format(priced.regular_cents),
"sku": representative.sku,
"stock": representative.stock,
"tracked": representative.tracked(),
@@ -46,7 +46,11 @@ pub fn product_card(
}
/// One priced variant row for the product detail page's option picker.
pub fn variant_option(variant: &product_variants::Model, priced: &PricedProduct) -> Value {
pub fn variant_option(
variant: &product_variants::Model,
priced: &PricedProduct,
cur: &Currency,
) -> Value {
json!({
"id": variant.id,
"label": variant.label,
@@ -54,9 +58,9 @@ pub fn variant_option(variant: &product_variants::Model, priced: &PricedProduct)
"stock": variant.stock,
"tracked": variant.tracked(),
"in_stock": variant.in_stock(),
"price": format_price(priced.price_cents),
"price": cur.format(priced.price_cents),
"on_sale": priced.is_reduced(),
"regular_price": format_price(priced.regular_cents),
"regular_price": cur.format(priced.regular_cents),
"is_business": priced.is_business,
})
}
@@ -71,7 +75,6 @@ pub fn product_form(product: &products::Model, images: &[product_images::Model])
"slug": product.slug,
"description": product.description,
"short_description": product.short_description,
"currency": product.currency,
"published": product.published,
"category_id": product.category_id,
"images": images