13 Commits

Author SHA1 Message Date
Priec
29854a972b save discount profile is now working perfectly well
Some checks failed
CI / Check Style (push) Has been cancelled
CI / Run Clippy (push) Has been cancelled
CI / Run Tests (push) Has been cancelled
2026-06-22 13:51:40 +02:00
Priec
88074c1871 indicator if applied discount profile
Some checks failed
CI / Check Style (push) Has been cancelled
CI / Run Clippy (push) Has been cancelled
CI / Run Tests (push) Has been cancelled
2026-06-22 13:22:46 +02:00
Priec
68f3472760 moved products menu up to save width 2026-06-22 13:15:29 +02:00
Priec
85f1657c67 dynamic width of the products to fit on the screen 2026-06-22 13:07:17 +02:00
Priec
4a736a8c85 collapsible admin sidebar 2026-06-22 12:59:05 +02:00
Priec
77d5c0fc25 sidebar in the admin 2026-06-22 12:49:08 +02:00
Priec
09634e1cd8 added missing remove button in the admin business
Some checks failed
CI / Check Style (push) Has been cancelled
CI / Run Clippy (push) Has been cancelled
CI / Run Tests (push) Has been cancelled
2026-06-22 11:33:07 +02:00
Priec
088fcb60a1 effective price is only highlighted if changed 2026-06-22 11:10:12 +02:00
Priec
bf8f8e54c9 discounts page removed, all migrated to the products page in admin 2026-06-22 09:19:38 +02:00
Priec
534ba9e8ec confirm dialogs 2026-06-22 09:11:16 +02:00
Priec
262ec1bfdb dynamic prices with dicounts 2026-06-22 08:47:22 +02:00
Priec
e98c70aa63 global discount price 2026-06-22 00:18:39 +02:00
Priec
d2b463135b discount for business and personall in discount page 2026-06-22 00:04:01 +02:00
29 changed files with 1404 additions and 517 deletions

View File

@@ -211,11 +211,17 @@ price = Price
sale-price = Sale price
admin-discounts = Discounts
admin-discounts-desc = Set discounted product prices. A discount shows up as a sale in the shop.
business-discount-desc = A baseline discount for all business accounts (off the regular price). Profiles and negotiated prices apply on top (lowest price wins).
audience-personal = Personal
audience-business = Business
apply-profiles-personal-hint = These profiles lower the public price for all customers.
apply-profiles-business-hint = These profiles lower the price for all business accounts. Businesses always get the lower of the personal and business price.
on-sale = On sale
no-discount = No discount
discount = Discount
set-discount = Set discount
remove-discount = Remove discount
remove = Remove
discount-mode-fixed = Fixed price
discount-mode-percent = Percentage
discount-percent = Discount (%)
@@ -226,6 +232,13 @@ discount-invalid = Invalid price.
discount-must-be-positive = The sale price must be greater than zero.
discount-below-regular = The sale price must be below the regular price.
discount-percent-range = The percentage must be between 0 and 100.
discount-apply-confirm = Apply these discounts to the shop?
discount-remove-confirm = Remove this discount?
profile-applied = Applied
profile-will-apply = Will apply
profile-will-remove = Will remove
profiles-unsaved = Unsaved changes — Save to apply
profiles-no-changes = No changes
admin-customers = Business accounts
admin-customers-desc = Manage negotiated prices for business (B2B) accounts.
admin-no-customers = No business accounts yet.
@@ -235,7 +248,11 @@ negotiated-prices = Negotiated prices
negotiated-prices-hint = Set a price for a specific product for this business account. The customer always pays the lower of the public and negotiated price.
manage-prices = Manage prices
public-price = Public price
business-price = Business price
negotiated-price = Negotiated price
set-negotiated-price = Set price
negotiated-price-hint = Set a negotiated price for this product for this business account. The customer always pays the lowest of the public, business and negotiated price.
negotiated-remove-confirm = Remove this negotiated price?
effective-price = Effective price
admin-discount-profiles = Discount profiles
admin-discount-profiles-desc = Create reusable discount layers (a % over chosen products) and assign them to business accounts.
@@ -280,6 +297,7 @@ shop-subtitle = browse our products.
shop-empty = There are no products here yet.
categories = Categories
all-products = All products
uncategorized = Uncategorized
cart-title = Cart
cart-empty = Your cart is empty.
cart-total = Total

View File

@@ -211,11 +211,17 @@ price = Cena
sale-price = Zľavnená cena
admin-discounts = Zľavy
admin-discounts-desc = Nastavte zľavnené ceny produktov. Zľava sa v obchode zobrazí ako akcia.
business-discount-desc = Základná zľava pre všetky firemné účty (z bežnej ceny). Profily a dohodnuté ceny sa uplatnia navyše (platí najnižšia cena).
audience-personal = Osobné
audience-business = Firemné
apply-profiles-personal-hint = Tieto profily znížia verejnú cenu pre všetkých zákazníkov.
apply-profiles-business-hint = Tieto profily znížia cenu pre všetky firemné účty. Firmy vždy dostanú nižšiu z osobnej a firemnej ceny.
on-sale = V akcii
no-discount = Bez zľavy
discount = Zľava
set-discount = Nastaviť zľavu
remove-discount = Zrušiť zľavu
remove = Odstrániť
discount-mode-fixed = Pevná cena
discount-mode-percent = Percentá
discount-percent = Zľava (%)
@@ -226,6 +232,13 @@ discount-invalid = Neplatná cena.
discount-must-be-positive = Zľavnená cena musí byť väčšia ako nula.
discount-below-regular = Zľavnená cena musí byť nižšia ako bežná cena.
discount-percent-range = Percento musí byť medzi 0 a 100.
discount-apply-confirm = Uplatniť tieto zľavy v obchode?
discount-remove-confirm = Zrušiť túto zľavu?
profile-applied = Uplatnené
profile-will-apply = Bude uplatnené
profile-will-remove = Bude zrušené
profiles-unsaved = Neuložené zmeny — uložte na uplatnenie
profiles-no-changes = Žiadne zmeny
admin-customers = Firemné účty
admin-customers-desc = Spravujte dohodnuté ceny pre firemné (B2B) účty.
admin-no-customers = Zatiaľ žiadne firemné účty.
@@ -235,7 +248,11 @@ negotiated-prices = Dohodnuté ceny
negotiated-prices-hint = Nastavte cenu pre konkrétny produkt pre tento firemný účet. Zákazník vždy zaplatí najnižšiu z verejnej a dohodnutej ceny.
manage-prices = Spravovať ceny
public-price = Verejná cena
business-price = Firemná cena
negotiated-price = Dohodnutá cena
set-negotiated-price = Nastaviť cenu
negotiated-price-hint = Nastavte dohodnutú cenu tohto produktu pre tento firemný účet. Zákazník vždy zaplatí najnižšiu z verejnej, firemnej a dohodnutej ceny.
negotiated-remove-confirm = Zrušiť túto dohodnutú cenu?
effective-price = Výsledná cena
admin-discount-profiles = Zľavové profily
admin-discount-profiles-desc = Vytvorte opakovane použiteľné zľavové vrstvy (% na vybrané produkty) a priraďte ich firemným účtom.
@@ -280,6 +297,7 @@ shop-subtitle = prezrite si našu ponuku produktov.
shop-empty = Zatiaľ tu nie sú žiadne produkty.
categories = Kategórie
all-products = Všetky produkty
uncategorized = Bez kategórie
cart-title = Košík
cart-empty = Váš košík je prázdny.
cart-total = Spolu

File diff suppressed because one or more lines are too long

View File

@@ -46,7 +46,14 @@
</head>
<body
hx-headers='{"X-CSRF-Token": "{{ csrf_token() }}"}'
x-data="{ showSidebar: false }"
x-data="{
showSidebar: false,
collapsed: localStorage.getItem('adminSidebarCollapsed') === '1',
toggleCollapsed() {
this.collapsed = !this.collapsed;
localStorage.setItem('adminSidebarCollapsed', this.collapsed ? '1' : '0');
}
}"
class="min-h-screen bg-surface text-on-surface antialiased dark:bg-surface-dark dark:text-on-surface-dark">
<!-- dark overlay for the open sidebar on small screens -->
@@ -56,8 +63,8 @@
<!-- sidebar -->
<nav aria-label="{{ t(key='menu', lang=lang | default(value='sk')) }}"
x-bind:class="showSidebar ? 'translate-x-0' : '-translate-x-60'"
class="fixed inset-y-0 left-0 z-40 flex w-60 flex-col border-r border-outline bg-surface-alt transition-transform duration-300 md:translate-x-0 dark:border-outline-dark dark:bg-surface-dark-alt">
x-bind:class="(showSidebar ? 'translate-x-0' : '-translate-x-60') + ' ' + (collapsed ? 'md:-translate-x-60' : 'md:translate-x-0')"
class="fixed inset-y-0 left-0 z-40 flex w-60 flex-col border-r border-outline bg-surface-alt transition-transform duration-300 dark:border-outline-dark dark:bg-surface-dark-alt">
{# Sidebar nav links — adapted from the vendored Penguin UI component
penguinui-components/sidebar/simple-sidebar.html: Penguin's link
@@ -78,10 +85,6 @@
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-products", lang=lang | default(value='sk')) }}
</a>
<a href="/admin/catalog/discounts" data-nav="/admin/catalog/discounts"
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-discounts", lang=lang | default(value='sk')) }}
</a>
<a href="/admin/catalog/discount-profiles" data-nav="/admin/catalog/discount-profiles"
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-discount-profiles", lang=lang | default(value='sk')) }}
@@ -118,7 +121,8 @@
</nav>
<!-- content column -->
<div class="flex min-h-screen flex-col md:ml-60">
<div :class="collapsed ? 'md:ml-0' : 'md:ml-60'"
class="flex min-h-screen flex-col transition-[margin] duration-300">
<header class="sticky top-0 z-20 flex h-16 items-center gap-4 border-b border-outline bg-surface/95 px-4 backdrop-blur dark:border-outline-dark dark:bg-surface-dark/95">
<!-- Penguin animated hamburger (bars ↔ X) in our ghost-square shell -->
<button type="button" @click="showSidebar = !showSidebar" :aria-expanded="showSidebar" aria-label="{{ t(key='menu', lang=lang | default(value='sk')) }}"
@@ -127,6 +131,12 @@
{{ ui::icon(name="close", size="size-6", attrs='x-cloak x-show="showSidebar"') }}
</button>
<!-- desktop sidebar collapse toggle (chevron flips when collapsed) -->
<button type="button" @click="toggleCollapsed()" :aria-expanded="(!collapsed).toString()" aria-label="{{ t(key='menu', lang=lang | default(value='sk')) }}"
class="hidden size-9 shrink-0 items-center justify-center rounded-radius bg-transparent text-secondary transition hover:opacity-75 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-secondary active:opacity-100 active:outline-offset-0 md:inline-flex dark:text-secondary-dark dark:focus-visible:outline-secondary-dark">
{{ ui::icon(name="chevron-double-left", size="size-6", extra="transition-transform duration-300", attrs=`x-bind:class="collapsed ? 'rotate-180' : ''"`) }}
</button>
<span class="text-sm font-semibold text-on-surface-strong dark:text-on-surface-dark-strong">
{% block crumb %}{{ t(key="admin-title", lang=lang | default(value='sk')) }}{% endblock crumb %}
</span>
@@ -137,7 +147,7 @@
</div>
</header>
<main class="mx-auto w-full max-w-5xl flex-1 px-4 py-8">
<main class="mx-auto w-full flex-1 px-4 py-8 {% block main_class %}max-w-5xl{% endblock main_class %}">
{% block content %}{% endblock content %}
</main>
</div>

View File

@@ -0,0 +1,8 @@
{# OOB fragment: effective-price cells recomputed from the unsaved profile
selection on the products page. Each span replaces the matching #eff-<id>
span in the table via htmx out-of-band swap. Rendered by
admin_products::profiles_preview. #}
{% import "macros/ui.html" as ui %}
{% for product in products %}
<span id="eff-{{ product.id }}" hx-swap-oob="true">{{ ui::eff_price(p=product, preview=true) }}</span>
{% endfor %}

View File

@@ -6,11 +6,16 @@
{% block content %}
<div class="flex items-center justify-between gap-3">
<h1 class="text-2xl font-bold text-on-surface-strong dark:text-on-surface-dark-strong">{{ product.name }}</h1>
{{ ui::button(variant="outline-secondary", label=t(key="cancel", lang=lang | default(value='sk')), href="/admin/catalog/discounts", size="px-3 py-2 text-sm") }}
<div>
<h1 class="text-2xl font-bold text-on-surface-strong dark:text-on-surface-dark-strong">{{ product.name }}</h1>
<p class="text-sm text-on-surface/70 dark:text-on-surface-dark/70">
{% if audience == "business" %}{{ t(key="audience-business", lang=lang | default(value='sk')) }}{% else %}{{ t(key="audience-personal", lang=lang | default(value='sk')) }}{% endif %}
</p>
</div>
{{ ui::button(variant="outline-secondary", label=t(key="cancel", lang=lang | default(value='sk')), href="/admin/catalog/products?audience=" ~ audience, size="px-3 py-2 text-sm") }}
</div>
<form method="post" action="/admin/catalog/discounts/{{ product.id }}"
<form method="post" action="/admin/catalog/products/{{ product.id }}/discount?audience={{ audience }}"
x-data="{
mode: '{{ mode }}',
fixed: '{{ fixed }}',
@@ -88,9 +93,9 @@
</div>
<div class="flex flex-wrap gap-3 pt-2">
{{ ui::button(label=t(key="save", lang=lang | default(value='sk')), type="submit") }}
{% if product.on_sale %}
{{ ui::button(variant="outline-danger", label=t(key="remove-discount", lang=lang | default(value='sk')), type="submit", attrs='formaction="/admin/catalog/discounts/' ~ product.id ~ '/remove"') }}
{{ ui::button(label=t(key="save", lang=lang | default(value='sk')), type="submit", attrs=`onclick="return confirm('` ~ t(key="discount-apply-confirm", lang=lang | default(value='sk')) ~ `')"`) }}
{% if has_discount %}
{{ ui::button(variant="outline-danger", label=t(key="remove-discount", lang=lang | default(value='sk')), type="submit", attrs=`formaction="/admin/catalog/products/` ~ product.id ~ `/discount/remove?audience=` ~ audience ~ `" onclick="return confirm('` ~ t(key="discount-remove-confirm", lang=lang | default(value='sk')) ~ `')"`) }}
{% endif %}
</div>
</form>

View File

@@ -1,70 +0,0 @@
{% extends "admin/base.html" %}
{% import "macros/ui.html" as ui %}
{% block title %}{{ t(key="admin-discounts", lang=lang | default(value='sk')) }}{% endblock title %}
{% block crumb %}{{ t(key="admin-discounts", lang=lang | default(value='sk')) }}{% endblock crumb %}
{% block content %}
<div class="flex flex-wrap items-end justify-between gap-3">
<div>
<h1 class="text-2xl font-bold text-on-surface-strong dark:text-on-surface-dark-strong">{{ t(key="admin-discounts", lang=lang | default(value='sk')) }}</h1>
<p class="text-sm text-on-surface/70 dark:text-on-surface-dark/70">{{ t(key="admin-discounts-desc", lang=lang | default(value='sk')) }}</p>
</div>
</div>
<div class="mt-6 {{ ui::table_wrap_cls() }}">
{% if products | length > 0 %}
<table class="{{ ui::table_cls() }}">
<thead class="{{ ui::thead_cls() }}">
<tr>
{{ ui::th(label=t(key="product", lang=lang | default(value='sk'))) }}
{{ ui::th(label=t(key="price", lang=lang | default(value='sk'))) }}
{{ ui::th(label=t(key="sale-price", lang=lang | default(value='sk'))) }}
{{ ui::th(label=t(key="status", lang=lang | default(value='sk'))) }}
{{ ui::th(label=t(key="actions", lang=lang | default(value='sk')), align="text-right") }}
</tr>
</thead>
<tbody class="{{ ui::tbody_cls() }}">
{% for product in products %}
<tr class="{{ ui::row_cls() }}">
<td class="px-4 py-3">
<div class="font-medium text-on-surface-strong dark:text-on-surface-dark-strong">{{ product.name }}</div>
</td>
<td class="px-4 py-3 tabular-nums">{{ product.regular_price }} {{ product.currency }}</td>
<td class="px-4 py-3 tabular-nums">
{% if product.on_sale %}
<span class="font-medium text-danger">{{ product.sale_price }} {{ product.currency }}</span>
<span class="ml-1 text-xs text-on-surface/60 dark:text-on-surface-dark/60">({{ product.percent_off }}%)</span>
{% else %}
<span class="text-on-surface/40 dark:text-on-surface-dark/40"></span>
{% endif %}
</td>
<td class="px-4 py-3">
{% if product.on_sale %}
{{ ui::badge(label=t(key="on-sale", lang=lang | default(value='sk')), variant="danger") }}
{% else %}
{{ ui::badge(label=t(key="no-discount", lang=lang | default(value='sk')), variant="neutral") }}
{% endif %}
</td>
<td class="px-4 py-3">
<div class="flex flex-wrap justify-end gap-2">
{{ ui::button(variant="outline-secondary", label=t(key="set-discount", lang=lang | default(value='sk')), href="/admin/catalog/discounts/" ~ product.id ~ "/edit", size="px-3 py-1.5 text-xs") }}
{% if product.on_sale %}
<form method="post" action="/admin/catalog/discounts/{{ product.id }}/remove">
{{ ui::csrf_field() }}
{{ ui::button(variant="outline-danger", label=t(key="remove-discount", lang=lang | default(value='sk')), type="submit", size="px-3 py-1.5 text-xs") }}
</form>
{% endif %}
</div>
</td>
</tr>
{% endfor %}
</tbody>
</table>
{% else %}
<div class="flex flex-col items-center gap-3 px-4 py-16 text-center">
<p class="text-on-surface/70 dark:text-on-surface-dark/70">{{ t(key="admin-no-products", lang=lang | default(value='sk')) }}</p>
</div>
{% endif %}
</div>
{% endblock content %}

View File

@@ -3,8 +3,10 @@
{% block title %}{{ t(key="admin-products", lang=lang | default(value='sk')) }}{% endblock title %}
{% block crumb %}{{ t(key="admin-products", lang=lang | default(value='sk')) }}{% endblock crumb %}
{% block main_class %}max-w-none{% endblock main_class %}
{% block content %}
{% set business = audience == "business" %}
<div class="flex flex-wrap items-end justify-between gap-3">
<div>
<h1 class="text-2xl font-bold text-on-surface-strong dark:text-on-surface-dark-strong">{{ t(key="admin-products", lang=lang | default(value='sk')) }}</h1>
@@ -13,13 +15,76 @@
{{ ui::button(label=t(key="new-product", lang=lang | default(value='sk')), href="/admin/catalog/products/new") }}
</div>
<div class="mt-6 {{ ui::table_wrap_cls() }}">
<!-- audience tabs -->
<div class="mt-4 inline-flex rounded-radius border border-outline p-1 dark:border-outline-dark">
<a href="/admin/catalog/products?audience=personal"
class="rounded-radius px-4 py-1.5 text-sm font-medium {% if not business %}bg-primary/10 text-on-surface-strong dark:bg-primary-dark/10 dark:text-on-surface-dark-strong{% else %}text-on-surface/70 dark:text-on-surface-dark/70{% endif %}">
{{ t(key="audience-personal", lang=lang | default(value='sk')) }}
</a>
<a href="/admin/catalog/products?audience=business"
class="rounded-radius px-4 py-1.5 text-sm font-medium {% if business %}bg-primary/10 text-on-surface-strong dark:bg-primary-dark/10 dark:text-on-surface-dark-strong{% else %}text-on-surface/70 dark:text-on-surface-dark/70{% endif %}">
{{ t(key="audience-business", lang=lang | default(value='sk')) }}
</a>
</div>
{% set category_base = "/admin/catalog/products" %}
{% set category_suffix = "&audience=" ~ audience %}
<div class="mt-4 flex flex-col gap-6 md:flex-row md:items-start">
{% include "admin/partials/category_filter.html" %}
<!-- discount profiles applied to this audience -->
<section class="min-w-0 flex-1 rounded-radius border border-outline bg-surface p-6 dark:border-outline-dark dark:bg-surface-dark-alt">
<h2 class="text-lg font-semibold text-on-surface-strong dark:text-on-surface-dark-strong">{{ t(key="discount-profiles", lang=lang | default(value='sk')) }}</h2>
<p class="mt-1 text-sm text-on-surface/70 dark:text-on-surface-dark/70">
{% if business %}{{ t(key="apply-profiles-business-hint", lang=lang | default(value='sk')) }}{% else %}{{ t(key="apply-profiles-personal-hint", lang=lang | default(value='sk')) }}{% endif %}
</p>
{% if profiles | length > 0 %}
<form method="post" action="/admin/catalog/products/profiles?audience={{ audience }}" class="mt-3 space-y-3"
hx-post="/admin/catalog/products/profiles/preview?audience={{ audience }}&category={{ selected_category }}"
hx-trigger="change"
hx-swap="none"
x-data="{
orig: { {% for p in profiles %}'{{ p.id }}': {% if p.assigned %}true{% else %}false{% endif %}{% if not loop.last %}, {% endif %}{% endfor %} },
sel: { {% for p in profiles %}'{{ p.id }}': {% if p.assigned %}true{% else %}false{% endif %}{% if not loop.last %}, {% endif %}{% endfor %} },
get changed() { return Object.keys(this.orig).some(k => this.orig[k] !== this.sel[k]) }
}"
onsubmit="return confirm('{{ t(key="discount-apply-confirm", lang=lang | default(value='sk')) }}')">
{{ ui::csrf_field() }}
<div class="grid gap-2 sm:grid-cols-2">
{% for profile in profiles %}
<label class="flex items-center gap-2 text-sm text-on-surface dark:text-on-surface-dark">
<input type="checkbox" name="profile_ids" value="{{ profile.id }}" x-model="sel['{{ profile.id }}']" {% if profile.assigned %}checked{% endif %}>
<span>{{ profile.name }} <span class="text-on-surface/60 dark:text-on-surface-dark/60">({{ profile.percent }}%, {% if profile.scope_type == "all_except" %}{{ t(key="scope-all-except", lang=lang | default(value='sk')) }}{% else %}{{ t(key="scope-include", lang=lang | default(value='sk')) }}{% endif %})</span></span>
<span x-cloak x-show="sel['{{ profile.id }}'] && orig['{{ profile.id }}']" class="inline-flex items-center rounded-radius border border-success px-1.5 py-0.5 text-xs font-medium text-success">{{ t(key="profile-applied", lang=lang | default(value='sk')) }}</span>
<span x-cloak x-show="sel['{{ profile.id }}'] && !orig['{{ profile.id }}']" class="inline-flex items-center rounded-radius border border-primary px-1.5 py-0.5 text-xs font-medium text-primary dark:border-primary-dark dark:text-primary-dark">{{ t(key="profile-will-apply", lang=lang | default(value='sk')) }}</span>
<span x-cloak x-show="!sel['{{ profile.id }}'] && orig['{{ profile.id }}']" class="inline-flex items-center rounded-radius border border-warning px-1.5 py-0.5 text-xs font-medium text-warning">{{ t(key="profile-will-remove", lang=lang | default(value='sk')) }}</span>
</label>
{% endfor %}
</div>
<div class="flex items-center gap-3">
{{ ui::button(label=t(key="save", lang=lang | default(value='sk')), type="submit", size="px-4 py-2 text-sm", attrs='x-bind:disabled="!changed"') }}
<span x-cloak x-show="changed" class="text-xs font-medium text-warning">{{ t(key="profiles-unsaved", lang=lang | default(value='sk')) }}</span>
<span x-cloak x-show="!changed" class="text-xs text-on-surface/50 dark:text-on-surface-dark/50">{{ t(key="profiles-no-changes", lang=lang | default(value='sk')) }}</span>
</div>
</form>
{% else %}
<p class="mt-2 text-sm text-on-surface/70 dark:text-on-surface-dark/70">
{{ t(key="admin-no-profiles", lang=lang | default(value='sk')) }}
<a href="/admin/catalog/discount-profiles/new" class="text-primary dark:text-primary-dark">{{ t(key="new-profile", lang=lang | default(value='sk')) }}</a>
</p>
{% endif %}
</section>
</div>
<div class="mt-4 {{ ui::table_wrap_cls() }}">
{% if products | length > 0 %}
<table class="{{ ui::table_cls() }}">
<thead class="{{ ui::thead_cls() }}">
<tr>
{{ ui::th(label=t(key="product", lang=lang | default(value='sk'))) }}
{{ ui::th(label=t(key="price", lang=lang | default(value='sk'))) }}
{{ ui::th(label=t(key="sale-price", lang=lang | default(value='sk'))) }}
{{ ui::th(label=t(key="effective-price", lang=lang | default(value='sk'))) }}
{{ ui::th(label=t(key="stock", lang=lang | default(value='sk'))) }}
{{ ui::th(label=t(key="status", lang=lang | default(value='sk'))) }}
{{ ui::th(label=t(key="actions", lang=lang | default(value='sk')), align="text-right") }}
@@ -41,14 +106,18 @@
</div>
</div>
</td>
<td class="px-4 py-3 tabular-nums">{{ product.regular_price }} {{ product.currency }}</td>
<td class="px-4 py-3 tabular-nums">
{% if product.on_sale %}
<span class="font-medium text-danger">{{ product.price }} {{ product.currency }}</span>
<span class="text-xs text-on-surface/50 line-through dark:text-on-surface-dark/50">{{ product.regular_price }}</span>
<span class="font-medium text-danger">{{ product.sale_price }} {{ product.currency }}</span>
<span class="ml-1 text-xs text-on-surface/60 dark:text-on-surface-dark/60">({{ product.percent_off }}%)</span>
{% else %}
{{ product.price }} {{ product.currency }}
<span class="text-on-surface/40 dark:text-on-surface-dark/40"></span>
{% endif %}
</td>
<td class="px-4 py-3 tabular-nums">
<span id="eff-{{ product.id }}">{{ ui::eff_price(p=product) }}</span>
</td>
<td class="px-4 py-3 tabular-nums">{{ product.stock }}</td>
<td class="px-4 py-3">
{% if product.published %}
@@ -60,11 +129,18 @@
<td class="px-4 py-3">
<div class="flex flex-wrap justify-end gap-2">
{{ ui::button(variant="outline-secondary", label=t(key="edit", lang=lang | default(value='sk')), href="/admin/catalog/products/" ~ product.id ~ "/edit", size="px-3 py-1.5 text-xs") }}
{{ ui::button(variant="outline-secondary", label=t(key="discount", lang=lang | default(value='sk')), href="/admin/catalog/discounts/" ~ product.id ~ "/edit", size="px-3 py-1.5 text-xs") }}
{{ ui::button(variant="outline-secondary", label=t(key="set-discount", lang=lang | default(value='sk')), href="/admin/catalog/products/" ~ product.id ~ "/discount/edit?audience=" ~ audience, size="px-3 py-1.5 text-xs") }}
{% if product.on_sale %}
<form method="post" action="/admin/catalog/products/{{ product.id }}/discount/remove?audience={{ audience }}"
onsubmit="return confirm('{{ t(key="discount-remove-confirm", lang=lang | default(value='sk')) }}')">
{{ ui::csrf_field() }}
{{ ui::button(variant="outline-danger", label=t(key="remove-discount", lang=lang | default(value='sk')), type="submit", size="px-3 py-1.5 text-xs") }}
</form>
{% endif %}
{{ ui::button(variant="outline-secondary", label=t(key="view", lang=lang | default(value='sk')), href="/shop/" ~ product.slug, size="px-3 py-1.5 text-xs") }}
<form method="post" action="/admin/catalog/products/{{ product.id }}/delete"
onsubmit="return confirm('{{ t(key="confirm-delete", lang=lang | default(value='sk')) }}')">
{{ ui::csrf_field() }}
{{ ui::csrf_field() }}
{{ ui::button(variant="outline-danger", label=t(key="delete", lang=lang | default(value='sk')), type="submit", size="px-3 py-1.5 text-xs") }}
</form>
</div>

View File

@@ -0,0 +1,97 @@
{% extends "admin/base.html" %}
{% import "macros/ui.html" as ui %}
{% block title %}{{ t(key="set-negotiated-price", lang=lang | default(value='sk')) }}{% endblock title %}
{% block crumb %}{{ t(key="admin-customers", lang=lang | default(value='sk')) }}{% endblock crumb %}
{% block content %}
<div class="flex items-center justify-between gap-3">
<div>
<div class="flex items-center gap-2">
<h1 class="text-2xl font-bold text-on-surface-strong dark:text-on-surface-dark-strong">{{ product.name }}</h1>
{{ ui::badge(label=t(key="negotiated-price", lang=lang | default(value='sk')), variant="info") }}
</div>
<p class="text-sm text-on-surface/70 dark:text-on-surface-dark/70">{{ customer.name }}</p>
</div>
{{ ui::button(variant="outline-secondary", label=t(key="back", lang=lang | default(value='sk')), href="/admin/customers/" ~ customer.id, size="px-3 py-2 text-sm") }}
</div>
{% if error %}
<div class="mt-4 max-w-md">{{ ui::alert_danger(message=t(key=error, lang=lang | default(value='sk'))) }}</div>
{% endif %}
<form method="post" action="/admin/customers/{{ customer.id }}/prices/{{ product.id }}"
x-data="{
price: '{{ negotiated }}',
regular: {{ product.regular_cents }},
num(v) { let n = parseFloat(String(v).replace(',', '.')); return isFinite(n) ? n : null; },
get afterCents() { let f = this.num(this.price); return f === null ? null : Math.round(f * 100); },
money(c) { return (c / 100).toFixed(2); },
get valid() { let a = this.afterCents; return a !== null && a > 0; }
}"
class="mt-6 max-w-md space-y-5 rounded-radius border-2 border-secondary/60 bg-surface p-6 dark:border-secondary-dark/60 dark:bg-surface-dark-alt">
{{ ui::csrf_field() }}
<p class="text-sm text-on-surface/70 dark:text-on-surface-dark/70">{{ t(key="negotiated-price-hint", lang=lang | default(value='sk')) }}</p>
<!-- reference prices -->
<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>
</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>
</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>
</div>
</div>
<!-- negotiated price input -->
<div class="space-y-1.5">
<label for="price" class="text-sm font-medium text-on-surface-strong dark:text-on-surface-dark-strong">{{ t(key="negotiated-price", lang=lang | default(value='sk')) }}</label>
{{ ui::input(name="price", id="price", value=negotiated, placeholder="0.00", attrs='inputmode="decimal" x-model="price"') }}
</div>
<!-- live preview -->
<div x-show="afterCents !== null" x-cloak
class="space-y-2 rounded-radius border border-outline bg-surface-alt px-4 py-3 dark:border-outline-dark dark:bg-surface-dark/40">
<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>
</div>
<p x-show="!valid" class="text-xs text-danger">{{ t(key="discount-must-be-positive", lang=lang | default(value='sk')) }}</p>
</div>
<div class="flex flex-wrap gap-3 pt-2">
{{ ui::button(variant="secondary", label=t(key="save", lang=lang | default(value='sk')), type="submit") }}
{% if has_negotiated %}
{{ ui::button(variant="outline-danger", label=t(key="remove", lang=lang | default(value='sk')), type="submit", attrs=`formaction="/admin/customers/` ~ customer.id ~ `/prices/` ~ product.id ~ `/remove" onclick="return confirm('` ~ t(key="negotiated-remove-confirm", lang=lang | default(value='sk')) ~ `')"`) }}
{% endif %}
</div>
</form>
{% if collision %}
<!-- collision resolution: two assigned profiles cover this product -->
<section class="mt-4 max-w-md rounded-radius border border-warning/60 bg-surface p-6 dark:bg-surface-dark-alt">
<div class="flex items-center gap-2">
<h2 class="text-lg font-semibold text-on-surface-strong dark:text-on-surface-dark-strong">{{ t(key="automated-price", lang=lang | default(value='sk')) }}</h2>
{{ ui::badge(label=t(key="collision", lang=lang | default(value='sk')), variant="warning") }}
</div>
<form method="post" action="/admin/customers/{{ customer.id }}/resolutions/{{ product.id }}" class="mt-3 flex items-center gap-2">
{{ ui::csrf_field() }}
<select name="profile_id" class="rounded-radius border border-outline bg-surface-alt px-2 py-1.5 text-sm dark:border-outline-dark dark:bg-surface-dark-alt/50 dark:text-on-surface-dark">
{% for c in covering %}
<option value="{{ c.id }}" {% if c.id == auto_profile_id %}selected{% endif %}>{{ c.name }}</option>
{% endfor %}
</select>
{{ ui::button(label=t(key="resolve", lang=lang | default(value='sk')), type="submit", size="px-3 py-1.5 text-sm") }}
</form>
</section>
{% endif %}
{% endblock content %}

View File

@@ -43,16 +43,19 @@
<p class="mt-6 text-sm text-on-surface/70 dark:text-on-surface-dark/70">{{ t(key="negotiated-prices-hint", lang=lang | default(value='sk')) }}</p>
<div class="mt-3 {{ ui::table_wrap_cls() }}">
{% set category_base = "/admin/customers/" ~ customer.id %}
{% set category_suffix = "" %}
<div class="mt-3 flex flex-col gap-6 md:flex-row md:items-start">
{% include "admin/partials/category_filter.html" %}
<div class="min-w-0 flex-1 {{ ui::table_wrap_cls() }}">
{% if products | length > 0 %}
<table class="{{ ui::table_cls() }}">
<thead class="{{ ui::thead_cls() }}">
<tr>
{{ ui::th(label=t(key="product", lang=lang | default(value='sk'))) }}
{{ ui::th(label=t(key="public-price", lang=lang | default(value='sk'))) }}
{{ ui::th(label=t(key="automated-price", lang=lang | default(value='sk'))) }}
{{ ui::th(label=t(key="negotiated-price", lang=lang | default(value='sk'))) }}
{{ ui::th(label=t(key="effective-price", lang=lang | default(value='sk')), align="text-right") }}
{{ ui::th(label=t(key="business-price", lang=lang | default(value='sk'))) }}
{{ ui::th(label=t(key="effective-price", lang=lang | default(value='sk'))) }}
{{ ui::th(label=t(key="actions", lang=lang | default(value='sk')), align="text-right") }}
</tr>
</thead>
<tbody class="{{ ui::tbody_cls() }}">
@@ -60,46 +63,28 @@
<tr class="{{ ui::row_cls() }}">
<td class="px-4 py-3 font-medium text-on-surface-strong dark:text-on-surface-dark-strong">{{ product.name }}</td>
<td class="px-4 py-3 tabular-nums">
{% if product.on_public_sale %}
<span class="font-medium text-danger">{{ product.public_price }} {{ product.currency }}</span>
{% if product.business_reduced %}
<span class="font-medium text-danger">{{ product.business_price }} {{ product.currency }}</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.public_price }} {{ product.currency }}
{{ product.business_price }} {{ product.currency }}
{% endif %}
</td>
<td class="px-4 py-3 tabular-nums">
{% if product.auto_price %}
<div>{{ product.auto_price }} {{ product.currency }}</div>
{% if product.collision %}
<div class="mt-1">{{ ui::badge(label=t(key="collision", lang=lang | default(value='sk')), variant="warning") }}</div>
<form method="post" action="/admin/customers/{{ customer.id }}/resolutions/{{ product.product_id }}" class="mt-1 flex items-center gap-1">
{{ ui::csrf_field() }}
<select name="profile_id" class="rounded-radius border border-outline bg-surface-alt px-2 py-1 text-xs dark:border-outline-dark dark:bg-surface-dark-alt/50 dark:text-on-surface-dark">
{% for c in product.covering %}
<option value="{{ c.id }}" {% if c.id == product.auto_profile_id %}selected{% endif %}>{{ c.name }}</option>
{% endfor %}
</select>
{{ ui::button(label=t(key="resolve", lang=lang | default(value='sk')), type="submit", size="px-2 py-1 text-xs") }}
</form>
{% elif product.auto_profile_name %}
<div class="text-xs text-on-surface/60 dark:text-on-surface-dark/60">{{ product.auto_profile_name }}</div>
{% endif %}
{% else %}
<span class="text-on-surface/40 dark:text-on-surface-dark/40"></span>
{% endif %}
<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>
{% 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">
<form method="post" action="/admin/customers/{{ customer.id }}/prices/{{ product.product_id }}" class="flex items-center gap-2">
{{ ui::csrf_field() }}
{{ ui::input(name="price", value=product.manual_price | default(value=""), placeholder="0.00", width="w-28", attrs='inputmode="decimal"') }}
{{ ui::button(label=t(key="save", lang=lang | default(value='sk')), type="submit", size="px-3 py-1.5 text-xs") }}
{% if product.manual_price %}
{{ ui::button(variant="outline-danger", label=t(key="remove", lang=lang | default(value='sk')), type="submit", size="px-3 py-1.5 text-xs", attrs='formaction="/admin/customers/' ~ customer.id ~ '/prices/' ~ product.product_id ~ '/remove"') }}
<div class="flex flex-wrap justify-end gap-2">
{{ ui::button(variant="outline-secondary", label=t(key="set-negotiated-price", lang=lang | default(value='sk')), href="/admin/customers/" ~ customer.id ~ "/prices/" ~ product.product_id ~ "/edit", size="px-3 py-1.5 text-xs") }}
{% if product.has_negotiated %}
<form method="post" action="/admin/customers/{{ customer.id }}/prices/{{ product.product_id }}/remove"
onsubmit="return confirm('{{ t(key="negotiated-remove-confirm", lang=lang | default(value='sk')) }}')">
{{ ui::csrf_field() }}
{{ ui::button(variant="outline-danger", label=t(key="remove", lang=lang | default(value='sk')), type="submit", size="px-3 py-1.5 text-xs") }}
</form>
{% endif %}
</form>
</td>
<td class="px-4 py-3 text-right tabular-nums">
<span class="font-medium {% if product.is_business %}text-primary dark:text-primary-dark{% else %}text-on-surface-strong dark:text-on-surface-dark-strong{% endif %}">{{ product.effective_price }} {{ product.currency }}</span>
</div>
</td>
</tr>
{% endfor %}
@@ -110,5 +95,6 @@
<p class="text-on-surface/70 dark:text-on-surface-dark/70">{{ t(key="admin-no-products", lang=lang | default(value='sk')) }}</p>
</div>
{% endif %}
</div>
</div>
{% endblock content %}

View File

@@ -0,0 +1,75 @@
{# Category-filter sidebar for admin product listings. Clicking a category
reloads the page with `?category=<id>` so the table server-side filters to
that category and its descendants. Expects in context:
- category_groups: [{ id, name, count, children: [{ id, name, count }] }]
(from views::shop::admin_category_groups)
- selected_category: "all" | "none" | "<id>" — the active filter
- total_count, uncategorized_count: ints
- category_base: page path, e.g. "/admin/catalog/products"
- category_suffix: extra query appended after the category param, e.g.
"&audience=business", or "" — set by the including template.
The link treatment mirrors shop/_sidebar.html (Penguin UI), but active state
is server-driven via aria-current (these links share a path, differing only
by query, so markActiveNav() can't pick the active one — hence no data-nav).
Numeric compare uses `| int(default=0)` because Tera string==number is false. #}
{% set sel = selected_category | int(default=0) %}
{% set link_cls = "flex flex-1 items-center gap-2 truncate 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" %}
<aside class="w-full shrink-0 md:w-56">
<p class="px-2 pb-2 text-xs font-semibold uppercase tracking-wide text-on-surface/60 dark:text-on-surface-dark/60">
{{ t(key="categories", lang=lang | default(value='sk')) }}
</p>
<div class="flex flex-col gap-1">
<a href="{{ category_base }}?category=all{{ category_suffix }}"
{% if selected_category == "all" %}aria-current="page"{% endif %} class="{{ link_cls }}">
<span class="flex-1 truncate">{{ t(key="all-products", lang=lang | default(value='sk')) }}</span>
<span class="text-xs text-on-surface/50 dark:text-on-surface-dark/50">{{ total_count }}</span>
</a>
{% for group in category_groups %}
{% set open_group = sel == group.id %}
{% for child in group.children %}{% if sel == child.id %}{% set_global open_group = true %}{% endif %}{% endfor %}
{% if group.children | length > 0 %}
<div x-data="{ open: {% if open_group %}true{% else %}false{% endif %} }" class="flex flex-col">
<div class="flex items-stretch">
<a href="{{ category_base }}?category={{ group.id }}{{ category_suffix }}"
{% if sel == group.id %}aria-current="page"{% endif %} class="{{ link_cls }} rounded-l-radius">
<span class="flex-1 truncate">{{ group.name }}</span>
<span class="text-xs text-on-surface/50 dark:text-on-surface-dark/50">{{ group.count }}</span>
</a>
<button type="button" x-on:click="open = ! open" x-bind:aria-expanded="open ? 'true' : 'false'"
aria-label="{{ group.name }}"
class="inline-flex w-8 shrink-0 items-center justify-center rounded-r-radius text-on-surface/60 transition hover:bg-primary/5 hover:text-on-surface-strong focus:outline-hidden focus-visible:underline dark:text-on-surface-dark/60 dark:hover:bg-primary-dark/5 dark:hover:text-on-surface-dark-strong">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor"
class="size-5 shrink-0 transition-transform rotate-0" x-bind:class="open ? 'rotate-180' : 'rotate-0'" aria-hidden="true">
<path fill-rule="evenodd" d="M5.22 8.22a.75.75 0 0 1 1.06 0L10 11.94l3.72-3.72a.75.75 0 1 1 1.06 1.06l-4.25 4.25a.75.75 0 0 1-1.06 0L5.22 9.28a.75.75 0 0 1 0-1.06Z" clip-rule="evenodd" />
</svg>
</button>
</div>
<ul x-show="open" x-cloak x-transition class="ml-3 mt-0.5 flex flex-col gap-0.5 border-l border-outline pl-1 dark:border-outline-dark">
{% for child in group.children %}
<li class="flex">
<a href="{{ category_base }}?category={{ child.id }}{{ category_suffix }}"
{% if sel == child.id %}aria-current="page"{% endif %}
class="flex flex-1 items-center gap-2 truncate rounded-radius px-2 py-1.5 text-sm 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">
<span class="flex-1 truncate">{{ child.name }}</span>
<span class="text-xs text-on-surface/50 dark:text-on-surface-dark/50">{{ child.count }}</span>
</a>
</li>
{% endfor %}
</ul>
</div>
{% else %}
<a href="{{ category_base }}?category={{ group.id }}{{ category_suffix }}"
{% if sel == group.id %}aria-current="page"{% endif %} class="{{ link_cls }}">
<span class="flex-1 truncate">{{ group.name }}</span>
<span class="text-xs text-on-surface/50 dark:text-on-surface-dark/50">{{ group.count }}</span>
</a>
{% endif %}
{% endfor %}
<a href="{{ category_base }}?category=none{{ category_suffix }}"
{% if selected_category == "none" %}aria-current="page"{% endif %} class="{{ link_cls }}">
<span class="flex-1 truncate">{{ t(key="uncategorized", lang=lang | default(value='sk')) }}</span>
<span class="text-xs text-on-surface/50 dark:text-on-surface-dark/50">{{ uncategorized_count }}</span>
</a>
</div>
</aside>

View File

@@ -81,6 +81,8 @@
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="{{ size }}{% if extra %} {{ extra }}{% endif %}" aria-hidden="true" {{ attrs | safe }}><path stroke-linecap="round" stroke-linejoin="round" d="M2.25 3h1.386c.51 0 .955.343 1.087.835l.383 1.437M7.5 14.25a3 3 0 0 0-3 3h15.75m-12.75-3h11.218c1.121-2.3 2.1-4.684 2.924-7.138a60.114 60.114 0 0 0-16.536-1.84M7.5 14.25 5.106 5.272M6 20.25a.75.75 0 1 1-1.5 0 .75.75 0 0 1 1.5 0Zm12.75 0a.75.75 0 1 1-1.5 0 .75.75 0 0 1 1.5 0Z" /></svg>
{%- elif name == "close" -%}
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="{{ size }}{% if extra %} {{ extra }}{% endif %}" aria-hidden="true" {{ attrs | safe }}><path stroke-linecap="round" stroke-linejoin="round" d="M6 18 18 6M6 6l12 12" /></svg>
{%- elif name == "chevron-double-left" -%}
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="{{ size }}{% if extra %} {{ extra }}{% endif %}" aria-hidden="true" {{ attrs | safe }}><path stroke-linecap="round" stroke-linejoin="round" d="m18.75 4.5-7.5 7.5 7.5 7.5m-6-15L5.25 12l7.5 7.5" /></svg>
{%- else -%}
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="{{ size }}{% if extra %} {{ extra }}{% endif %}" aria-hidden="true" {{ attrs | safe }}><path stroke-linecap="round" stroke-linejoin="round" d="M3.75 6.75h16.5M3.75 12h16.5m-16.5 5.25h16.5" /></svg>
{%- endif -%}
@@ -120,6 +122,21 @@
{%- endif %}
{%- endmacro badge %}
{# Effective-price cell content for the admin products table. The value is
colored only when it differs from the regular price (effective_reduced);
when equal it renders in the plain text color, unified with the Price column.
`preview=true` uses the info color (an unsaved profile-toggle preview) instead
of the saved primary color. No t() calls, so it is safe inside a macro. #}
{% 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="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 }}
{% endif %}
{%- endmacro eff_price %}
{# ---- Form controls. Verbatim Penguin classes from
penguinui/{text-input,text-area,select,checkbox,file-input}/default-*.html.
These macros emit only the control (callers keep their own <label>/layout), so

View File

@@ -38,6 +38,8 @@ mod m20260620_000001_add_totp_to_users;
mod m20260621_000001_add_sale_price_to_products;
mod m20260621_000002_account_product_prices;
mod m20260621_000003_discount_profiles;
mod m20260621_000004_add_business_sale_price_to_products;
mod m20260622_000001_audience_discount_profiles;
pub struct Migrator;
#[async_trait::async_trait]
@@ -80,6 +82,8 @@ impl MigratorTrait for Migrator {
Box::new(m20260621_000001_add_sale_price_to_products::Migration),
Box::new(m20260621_000002_account_product_prices::Migration),
Box::new(m20260621_000003_discount_profiles::Migration),
Box::new(m20260621_000004_add_business_sale_price_to_products::Migration),
Box::new(m20260622_000001_audience_discount_profiles::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> {
// Optional per-product discounted price (minor units) shown to ALL
// business (company) accounts as a baseline, computed off the regular
// price like the personal sale. Per-company profiles/negotiated prices
// still layer on top (lowest price wins).
add_column(m, "products", "business_sale_price_cents", ColType::BigIntegerNull).await
}
async fn down(&self, m: &SchemaManager) -> Result<(), DbErr> {
remove_column(m, "products", "business_sale_price_cents").await
}
}

View File

@@ -0,0 +1,40 @@
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> {
// Discount profiles applied globally to a whole audience, set on the
// discounts page: "personal" lowers the public price for everyone,
// "business" lowers the price for all company accounts. Per-company
// assignments (account_discount_profiles) still layer on top.
create_table(
m,
"audience_discount_profiles",
&[
("id", ColType::PkAuto),
("audience", ColType::String),
],
&[("discount_profile", "")],
)
.await?;
m.create_index(
Index::create()
.name("idx_audience_discount_profiles_unique")
.table(Alias::new("audience_discount_profiles"))
.col(Alias::new("audience"))
.col(Alias::new("discount_profile_id"))
.unique()
.to_owned(),
)
.await
}
async fn down(&self, m: &SchemaManager) -> Result<(), DbErr> {
drop_table(m, "audience_discount_profiles").await
}
}

View File

@@ -18,7 +18,7 @@ use std::{path::Path, sync::Arc};
use crate::{
controllers::{
account, admin_categories, admin_customers, admin_dashboard, admin_discount_profiles,
admin_discounts, admin_form, admin_orders, admin_products, admin_shipping, auth, auth_pages,
admin_form, admin_orders, admin_products, admin_shipping, auth, auth_pages,
cart, checkout, home, i18n, media, oauth2,
shop,
},
@@ -105,7 +105,6 @@ impl Hooks for App {
// admin
.add_route(admin_dashboard::routes())
.add_route(admin_products::routes())
.add_route(admin_discounts::routes())
.add_route(admin_discount_profiles::routes())
.add_route(admin_categories::routes())
.add_route(admin_orders::routes())

View File

@@ -21,16 +21,18 @@ use crate::{
controllers::i18n::current_lang,
models::{
account_discount_profiles, account_product_prices, account_product_resolutions,
discount_profiles, products, _entities::users,
categories, discount_profiles, products, _entities::users,
},
shared::{
guard,
money::{format_bp, format_price, parse_price_to_cents},
pricing,
},
views::shop as view,
};
const COMPANY: &str = "company";
const BUSINESS_AUDIENCE: &str = "business";
#[derive(Debug, Deserialize)]
struct PriceForm {
@@ -117,8 +119,6 @@ async fn show(
.all(&ctx.db)
.await?;
let assigned = assigned_profile_ids(&ctx, company.id).await?;
let profile_name: HashMap<i32, String> =
all_profiles.iter().map(|p| (p.id, p.name.clone())).collect();
let profiles_json: Vec<serde_json::Value> = all_profiles
.iter()
.map(|p| {
@@ -132,36 +132,52 @@ async fn show(
})
.collect();
let all_categories = categories::Entity::find()
.order_by_asc(categories::Column::Position)
.order_by_asc(categories::Column::Name)
.all(&ctx.db)
.await?;
let list = products::Entity::find()
.order_by_asc(products::Column::Name)
.all(&ctx.db)
.await?;
// Two prices per product:
// - the generic business price a freshly-registered company sees (business
// baseline + business-audience profiles, no per-company deals), and
// - this company's effective price (its negotiated price + assigned profiles).
// The effective price is highlighted only when it differs from the generic one.
let business = pricing::audience_price_many(&ctx, &list, BUSINESS_AUDIENCE).await?;
let details = pricing::detail_many(&ctx, &list, Some(&company)).await?;
// Category sidebar tree (counts over the full, unfiltered list) plus the
// active `?category=` filter applied to the rows.
let category_ids: Vec<Option<i32>> = list.iter().map(|p| p.category_id).collect();
let category_groups = view::admin_category_groups(&all_categories, &category_ids);
let selected_category = params
.get("category")
.map(String::as_str)
.unwrap_or("all")
.to_string();
let filter = view::category_filter_ids(&all_categories, &selected_category);
let rows: Vec<serde_json::Value> = list
.iter()
.zip(business.iter())
.zip(details.iter())
.map(|(product, d)| {
let covering: Vec<serde_json::Value> = d
.covering_profile_ids
.iter()
.map(|pid| json!({ "id": pid, "name": profile_name.get(pid) }))
.collect();
.filter(|((product, _), _)| view::category_filter_keep(&filter, product.category_id))
.map(|((product, b), d)| {
json!({
"product_id": product.id,
"name": product.name,
"currency": product.currency,
"regular_price": format_price(d.regular_cents),
"public_price": format_price(d.public_cents),
"on_public_sale": product.on_sale(),
"manual_price": d.manual_cents.map(format_price),
"auto_price": d.auto_cents.map(format_price),
"auto_profile_name": d.auto_profile_id.and_then(|pid| profile_name.get(&pid)),
"auto_profile_id": d.auto_profile_id,
"business_price": format_price(b.price_cents),
"business_reduced": b.price_cents < d.regular_cents,
"has_negotiated": d.manual_cents.is_some(),
"collision": d.collision,
"covering": covering,
"effective_price": format_price(d.price_cents),
"is_business": d.is_business,
"effective_differs": d.price_cents != b.price_cents,
})
})
.collect();
@@ -173,6 +189,79 @@ async fn show(
"customer": { "id": company.id, "name": company.name, "email": company.email },
"profiles": profiles_json,
"products": rows,
"category_groups": category_groups,
"selected_category": selected_category,
"total_count": list.len(),
"uncategorized_count": category_ids.iter().filter(|c| c.is_none()).count(),
"error": params.get("error"),
"lang": current_lang(&jar),
}),
)
}
/// Dedicated per-product page for the negotiated price (and, when two assigned
/// profiles collide, the resolution selector). Mirrors the catalog "Set discount"
/// page but for a single company.
#[debug_handler]
async fn price_edit(
auth: auth::JWT,
jar: CookieJar,
ViewEngine(v): ViewEngine<TeraView>,
Path((id, product_id)): Path<(i32, i32)>,
Query(params): Query<HashMap<String, String>>,
State(ctx): State<AppContext>,
) -> Result<Response> {
guard::current_admin(auth, &ctx).await?;
let company = company_by_id(&ctx, id).await?;
let product = products::Entity::find_by_id(product_id)
.one(&ctx.db)
.await?
.ok_or_else(|| Error::NotFound)?;
let business =
pricing::audience_price_many(&ctx, std::slice::from_ref(&product), BUSINESS_AUDIENCE)
.await?;
let business_cents = business[0].price_cents;
let detail = pricing::detail_many(&ctx, std::slice::from_ref(&product), Some(&company)).await?;
let d = &detail[0];
// Names for the covering profiles, used by the collision resolution selector.
let covering: Vec<serde_json::Value> = if d.covering_profile_ids.is_empty() {
Vec::new()
} else {
let profiles = discount_profiles::Entity::find()
.filter(discount_profiles::Column::Id.is_in(d.covering_profile_ids.clone()))
.all(&ctx.db)
.await?;
let name: HashMap<i32, String> =
profiles.iter().map(|p| (p.id, p.name.clone())).collect();
d.covering_profile_ids
.iter()
.map(|pid| json!({ "id": pid, "name": name.get(pid) }))
.collect()
};
format::view(
&v,
"admin/customers/price_form.html",
json!({
"customer": { "id": company.id, "name": company.name },
"product": {
"id": product.id,
"name": product.name,
"currency": product.currency,
"regular_price": format_price(d.regular_cents),
"regular_cents": d.regular_cents,
"business_price": format_price(business_cents),
"business_reduced": business_cents < d.regular_cents,
"effective_price": format_price(d.price_cents),
"effective_differs": d.price_cents != business_cents,
},
"negotiated": d.manual_cents.map(format_price).unwrap_or_default(),
"has_negotiated": d.manual_cents.is_some(),
"collision": d.collision,
"covering": covering,
"auto_profile_id": d.auto_profile_id,
"error": params.get("error"),
"lang": current_lang(&jar),
}),
@@ -199,7 +288,7 @@ async fn set_price(
Ok(cents) if cents > 0 => cents,
_ => {
return format::redirect(&format!(
"/admin/customers/{id}?error=discount-must-be-positive"
"/admin/customers/{id}/prices/{product_id}/edit?error=discount-must-be-positive"
))
}
};
@@ -288,6 +377,10 @@ pub fn routes() -> Routes {
.add("/admin/customers", get(index))
.add("/admin/customers/{id}", get(show))
.add("/admin/customers/{id}/profiles", post(sync_profiles))
.add(
"/admin/customers/{id}/prices/{product_id}/edit",
get(price_edit),
)
.add("/admin/customers/{id}/prices/{product_id}", post(set_price))
.add(
"/admin/customers/{id}/prices/{product_id}/remove",

View File

@@ -1,240 +0,0 @@
//! Admin management of per-product discounts.
//!
//! Discounts live on the product (`sale_price_cents`) but are set here, in a
//! place of their own, rather than on the product editor: an admin picks a
//! product, enters a discounted price, and the storefront then shows it on sale.
//! Editing a product never touches its discount, and vice versa.
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::products,
shared::{
guard,
money::{format_price, parse_percent, parse_price_to_cents},
},
};
#[derive(Debug, Deserialize)]
struct DiscountForm {
/// "fixed" (enter the new price) or "percent" (enter % off). Defaults to
/// fixed for older/JSON callers.
mode: Option<String>,
sale_price: Option<String>,
percent: Option<String>,
}
/// Resolve a percentage off the regular price into a fixed sale price in cents.
/// Rounds the discount amount to the nearest cent.
fn percent_to_sale_cents(regular_cents: i64, percent: f64) -> i64 {
let off = (regular_cents as f64 * percent / 100.0).round() as i64;
regular_cents - off
}
async fn product_by_id(ctx: &AppContext, id: i32) -> Result<products::Model> {
products::Entity::find_by_id(id)
.one(&ctx.db)
.await?
.ok_or_else(|| Error::NotFound)
}
/// Percent off the regular price, rounded to a whole number. `0` when there is
/// no positive regular price to discount from.
fn percent_off(regular_cents: i64, sale_cents: i64) -> i64 {
if regular_cents <= 0 {
return 0;
}
let off = (regular_cents - sale_cents) as f64 / regular_cents as f64 * 100.0;
off.round() as i64
}
/// Row shape for the discounts list.
fn list_row(product: &products::Model) -> serde_json::Value {
json!({
"id": product.id,
"name": product.name,
"slug": product.slug,
"currency": product.currency,
"regular_price": format_price(product.price_cents),
"on_sale": product.on_sale(),
"sale_price": product.sale_price_cents.map(format_price),
"percent_off": product.sale_price_cents.map(|sale| percent_off(product.price_cents, sale)),
})
}
#[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 list = products::Entity::find()
.order_by_asc(products::Column::Name)
.all(&ctx.db)
.await?;
let rows: Vec<serde_json::Value> = list.iter().map(list_row).collect();
format::view(
&v,
"admin/catalog/discounts.html",
json!({ "products": rows, "lang": current_lang(&jar) }),
)
}
/// What to pre-fill the form with: the chosen input mode and the raw values for
/// each field, so a rejected submit (or a re-edit) shows what the admin had.
#[derive(Default)]
struct FormPrefill {
mode: String,
fixed: String,
percent: String,
}
/// Render the single-product discount form, optionally with a validation error.
fn render_form(
v: &TeraView,
jar: &CookieJar,
product: &products::Model,
prefill: &FormPrefill,
error: Option<&str>,
) -> Result<Response> {
let mode = if prefill.mode == "percent" { "percent" } else { "fixed" };
format::view(
v,
"admin/catalog/discount_form.html",
json!({
"product": {
"id": product.id,
"name": product.name,
"currency": product.currency,
"regular_price": format_price(product.price_cents),
"regular_cents": product.price_cents,
"on_sale": product.on_sale(),
"sale_price": product.sale_price_cents.map(format_price),
},
"mode": mode,
"fixed": prefill.fixed,
"percent": prefill.percent,
"error": error,
"lang": current_lang(jar),
}),
)
}
#[debug_handler]
async fn edit(
auth: auth::JWT,
jar: CookieJar,
ViewEngine(v): ViewEngine<TeraView>,
Path(id): Path<i32>,
State(ctx): State<AppContext>,
) -> Result<Response> {
guard::current_admin(auth, &ctx).await?;
let product = product_by_id(&ctx, id).await?;
// Re-editing always opens in fixed mode showing the current sale price.
let prefill = FormPrefill {
mode: "fixed".to_string(),
fixed: product.sale_price_cents.map(format_price).unwrap_or_default(),
percent: String::new(),
};
render_form(&v, &jar, &product, &prefill, None)
}
#[debug_handler]
async fn update(
auth: auth::JWT,
jar: CookieJar,
ViewEngine(v): ViewEngine<TeraView>,
Path(id): Path<i32>,
State(ctx): State<AppContext>,
Form(form): Form<DiscountForm>,
) -> Result<Response> {
guard::current_admin(auth, &ctx).await?;
let product = product_by_id(&ctx, id).await?;
let mode = match form.mode.as_deref() {
Some("percent") => "percent",
_ => "fixed",
};
let fixed = form.sale_price.unwrap_or_default().trim().to_string();
let percent = form.percent.unwrap_or_default().trim().to_string();
// Whatever the mode, both raw inputs are echoed back on error so neither tab
// loses what was typed.
let prefill = FormPrefill {
mode: mode.to_string(),
fixed: fixed.clone(),
percent: percent.clone(),
};
let render_err = |key: &str| render_form(&v, &jar, &product, &prefill, Some(key));
// Resolve the entered discount into a fixed sale price in cents. An empty
// input in the active mode clears the discount (same as the Remove action).
let sale_cents = if mode == "percent" {
if percent.is_empty() {
return clear_discount(&ctx, product).await;
}
let pct = match parse_percent(&percent) {
Some(pct) => pct,
None => return render_err("discount-invalid"),
};
if pct <= 0.0 || pct >= 100.0 {
return render_err("discount-percent-range");
}
percent_to_sale_cents(product.price_cents, pct)
} else {
if fixed.is_empty() {
return clear_discount(&ctx, product).await;
}
match parse_price_to_cents(&fixed) {
Ok(cents) => cents,
Err(_) => return render_err("discount-invalid"),
}
};
// A discount must be a positive price strictly below the regular price —
// otherwise it isn't a discount.
if sale_cents <= 0 {
return render_err("discount-must-be-positive");
}
if sale_cents >= product.price_cents {
return render_err("discount-below-regular");
}
let mut active = product.into_active_model();
active.sale_price_cents = Set(Some(sale_cents));
active.update(&ctx.db).await?;
format::redirect("/admin/catalog/discounts")
}
async fn clear_discount(ctx: &AppContext, product: products::Model) -> Result<Response> {
let mut active = product.into_active_model();
active.sale_price_cents = Set(None);
active.update(&ctx.db).await?;
format::redirect("/admin/catalog/discounts")
}
#[debug_handler]
async fn remove(
auth: auth::JWT,
Path(id): Path<i32>,
State(ctx): State<AppContext>,
) -> Result<Response> {
guard::current_admin(auth, &ctx).await?;
let product = product_by_id(&ctx, id).await?;
clear_discount(&ctx, product).await
}
pub fn routes() -> Routes {
Routes::new()
.add("/admin/catalog/discounts", get(index))
.add("/admin/catalog/discounts/{id}/edit", get(edit))
.add("/admin/catalog/discounts/{id}", post(update))
.add("/admin/catalog/discounts/{id}/remove", post(remove))
}

View File

@@ -1,12 +1,15 @@
//! Admin product CRUD.
use std::collections::{HashMap, HashSet};
use axum::extract::{DefaultBodyLimit, Multipart};
use axum_extra::extract::cookie::CookieJar;
use loco_rs::prelude::*;
use sea_orm::{
ActiveModelTrait, ColumnTrait, EntityTrait, ModelTrait, PaginatorTrait, QueryFilter,
QueryOrder, Set,
QueryOrder, Set, TransactionTrait,
};
use serde::Deserialize;
use serde_json::json;
use crate::{
@@ -17,14 +20,19 @@ use crate::{
},
shared::{
guard,
money::parse_price_to_cents,
money::{format_bp, format_price, parse_percent, parse_price_to_cents},
pricing,
slug::{slugify, unique_slug},
},
models::{categories, product_images, products},
models::{
audience_discount_profiles, categories, discount_profiles, product_images, products,
},
views::shop as view,
};
/// Which discount column an audience tab operates on.
const BUSINESS: &str = "business";
async fn product_by_id(ctx: &AppContext, id: i32) -> Result<products::Model> {
products::Entity::find_by_id(id)
.one(&ctx.db)
@@ -113,33 +121,127 @@ async fn index(
auth: auth::JWT,
jar: CookieJar,
ViewEngine(v): ViewEngine<TeraView>,
Query(params): Query<HashMap<String, String>>,
State(ctx): State<AppContext>,
) -> Result<Response> {
guard::current_admin(auth, &ctx).await?;
let audience = read_audience(&params);
let all_categories = categories::Entity::find()
.order_by_asc(categories::Column::Position)
.order_by_asc(categories::Column::Name)
.all(&ctx.db)
.await?;
let category_name: HashMap<i32, String> = all_categories
.iter()
.map(|c| (c.id, c.name.clone()))
.collect();
let list = products::Entity::find()
.order_by_desc(products::Column::CreatedAt)
.all(&ctx.db)
.await?;
// Effective price each product carries for the active audience, after the
// global per-product discount and any profiles assigned to that audience.
let effective = pricing::audience_price_many(&ctx, &list, audience).await?;
// Category sidebar tree (counts over the full, unfiltered list) plus the
// active `?category=` filter applied to the rows.
let category_ids: Vec<Option<i32>> = list.iter().map(|p| p.category_id).collect();
let category_groups = view::admin_category_groups(&all_categories, &category_ids);
let selected_category = params
.get("category")
.map(String::as_str)
.unwrap_or("all")
.to_string();
let filter = view::category_filter_ids(&all_categories, &selected_category);
let mut rows = Vec::new();
for product in list {
for (product, priced) in list.iter().zip(effective.iter()) {
if !view::category_filter_keep(&filter, product.category_id) {
continue;
}
let image = product_images::first_for(&ctx, product.id).await?;
let category_name = match product.category_id {
Some(id) => categories::Entity::find_by_id(id)
.one(&ctx.db)
.await?
.map(|c| c.name),
None => None,
};
let priced = pricing::price_for(&ctx, &product, None).await?;
rows.push(view::product_card(&product, &priced, image, category_name));
let category_name = product
.category_id
.and_then(|id| category_name.get(&id).cloned());
rows.push(product_row(product, priced, image, category_name, audience));
}
format::view(
&v,
"admin/catalog/products.html",
json!({ "products": rows, "lang": current_lang(&jar) }),
json!({
"products": rows,
"profiles": load_audience_profiles(&ctx, audience).await?,
"audience": audience,
"category_groups": category_groups,
"selected_category": selected_category,
"total_count": list.len(),
"uncategorized_count": category_ids.iter().filter(|c| c.is_none()).count(),
"lang": current_lang(&jar),
}),
)
}
/// List-row shape: the product card fields plus the active audience's per-product
/// discount and its resolved effective price (after profiles).
fn product_row(
product: &products::Model,
effective: &pricing::PricedProduct,
image: Option<String>,
category_name: Option<String>,
audience: &str,
) -> serde_json::Value {
let sale = current_value(product, audience);
json!({
"id": product.id,
"name": product.name,
"slug": product.slug,
"currency": product.currency,
"stock": product.stock,
"published": product.published,
"image": image,
"category_name": category_name,
"regular_price": format_price(product.price_cents),
"on_sale": sale.is_some(),
"sale_price": sale.map(format_price),
"percent_off": sale.map(|s| percent_off(product.price_cents, s)),
"effective_price": format_price(effective.price_cents),
"effective_reduced": effective.is_reduced(),
"effective_percent_off": percent_off(product.price_cents, effective.price_cents),
})
}
/// All discount profiles, flagged with whether they are assigned to `audience`.
async fn load_audience_profiles(
ctx: &AppContext,
audience: &str,
) -> Result<Vec<serde_json::Value>> {
let assigned: HashSet<i32> = audience_discount_profiles::Entity::find()
.filter(audience_discount_profiles::Column::Audience.eq(audience))
.all(&ctx.db)
.await?
.into_iter()
.map(|a| a.discount_profile_id)
.collect();
let all_profiles = discount_profiles::Entity::find()
.order_by_asc(discount_profiles::Column::Name)
.all(&ctx.db)
.await?;
Ok(all_profiles
.iter()
.map(|p| {
json!({
"id": p.id,
"name": p.name,
"percent": format_bp(p.percent_bp),
"scope_type": p.scope_type,
"assigned": assigned.contains(&p.id),
})
})
.collect())
}
#[debug_handler]
async fn new(
auth: auth::JWT,
@@ -270,6 +372,311 @@ async fn delete(
format::redirect("/admin/catalog/products")
}
// --- Discounts -------------------------------------------------------------
//
// Two audiences, switched by an `?audience=` tab on the products page:
// - **personal** (default): the public sale price (`products.sale_price_cents`)
// everyone sees.
// - **business**: a baseline discount for all company accounts
// (`products.business_sale_price_cents`). Per-company profiles/negotiated
// prices still layer on top (lowest price wins). Both are off the regular price.
#[derive(Debug, Deserialize)]
struct DiscountForm {
/// "fixed" (enter the new price) or "percent" (enter % off). Defaults to
/// fixed for older/JSON callers.
mode: Option<String>,
sale_price: Option<String>,
percent: Option<String>,
}
fn read_audience(params: &HashMap<String, String>) -> &'static str {
match params.get("audience").map(String::as_str) {
Some(BUSINESS) => BUSINESS,
_ => "personal",
}
}
fn current_value(product: &products::Model, audience: &str) -> Option<i64> {
if audience == BUSINESS {
product.business_sale_price_cents
} else {
product.sale_price_cents
}
}
fn set_value(active: &mut products::ActiveModel, audience: &str, value: Option<i64>) {
if audience == BUSINESS {
active.business_sale_price_cents = Set(value);
} else {
active.sale_price_cents = Set(value);
}
}
fn list_redirect(audience: &str) -> Result<Response> {
format::redirect(&format!("/admin/catalog/products?audience={audience}"))
}
/// Resolve a percentage off the regular price into a fixed sale price in cents.
fn percent_to_sale_cents(regular_cents: i64, percent: f64) -> i64 {
let off = (regular_cents as f64 * percent / 100.0).round() as i64;
regular_cents - off
}
/// Percent off the regular price, rounded to a whole number.
fn percent_off(regular_cents: i64, sale_cents: i64) -> i64 {
if regular_cents <= 0 {
return 0;
}
let off = (regular_cents - sale_cents) as f64 / regular_cents as f64 * 100.0;
off.round() as i64
}
/// Preview the effective prices that the submitted (unsaved) checkbox set would
/// produce, without persisting anything. Returns OOB `<span>`s that htmx swaps
/// into the effective-price column so the admin sees the effect before Save.
#[debug_handler]
async fn profiles_preview(
auth: auth::JWT,
jar: CookieJar,
ViewEngine(v): ViewEngine<TeraView>,
Query(params): Query<HashMap<String, String>>,
State(ctx): State<AppContext>,
body: String,
) -> Result<Response> {
guard::current_admin(auth, &ctx).await?;
let audience = read_audience(&params);
let profile_ids: Vec<i32> = form_urlencoded::parse(body.as_bytes())
.filter(|(k, _)| k == "profile_ids")
.filter_map(|(_, value)| value.parse::<i32>().ok())
.collect();
let all_categories = categories::Entity::find()
.order_by_asc(categories::Column::Position)
.order_by_asc(categories::Column::Name)
.all(&ctx.db)
.await?;
let list = products::Entity::find()
.order_by_desc(products::Column::CreatedAt)
.all(&ctx.db)
.await?;
let effective =
pricing::audience_price_many_preview(&ctx, &list, audience, profile_ids).await?;
let selected_category = params.get("category").map(String::as_str).unwrap_or("all");
let filter = view::category_filter_ids(&all_categories, selected_category);
let mut rows = Vec::new();
for (product, priced) in list.iter().zip(effective.iter()) {
if !view::category_filter_keep(&filter, product.category_id) {
continue;
}
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(product.price_cents, priced.price_cents),
}));
}
format::view(
&v,
"admin/catalog/_price_preview.html",
json!({ "products": rows, "lang": current_lang(&jar) }),
)
}
/// Replace the profiles applied to this audience with the submitted checkbox set
/// (`profile_ids`, a repeated field parsed directly from the body).
#[debug_handler]
async fn sync_profiles(
auth: auth::JWT,
Query(params): Query<HashMap<String, String>>,
State(ctx): State<AppContext>,
body: String,
) -> Result<Response> {
guard::current_admin(auth, &ctx).await?;
let audience = read_audience(&params);
let profile_ids: Vec<i32> = form_urlencoded::parse(body.as_bytes())
.filter(|(k, _)| k == "profile_ids")
.filter_map(|(_, value)| value.parse::<i32>().ok())
.collect();
let txn = ctx.db.begin().await?;
audience_discount_profiles::Entity::delete_many()
.filter(audience_discount_profiles::Column::Audience.eq(audience))
.exec(&txn)
.await?;
for profile_id in profile_ids {
audience_discount_profiles::ActiveModel {
audience: Set(audience.to_string()),
discount_profile_id: Set(profile_id),
..Default::default()
}
.insert(&txn)
.await?;
}
txn.commit().await?;
list_redirect(audience)
}
/// What to pre-fill the discount form with: the chosen input mode and the raw
/// values for each field, so a rejected submit (or a re-edit) shows what the
/// admin had.
#[derive(Default)]
struct FormPrefill {
mode: String,
fixed: String,
percent: String,
}
fn render_discount_form(
v: &TeraView,
jar: &CookieJar,
product: &products::Model,
audience: &str,
prefill: &FormPrefill,
error: Option<&str>,
) -> Result<Response> {
let mode = if prefill.mode == "percent" { "percent" } else { "fixed" };
format::view(
v,
"admin/catalog/discount_form.html",
json!({
"product": {
"id": product.id,
"name": product.name,
"currency": product.currency,
"regular_price": format_price(product.price_cents),
"regular_cents": product.price_cents,
},
"audience": audience,
"has_discount": current_value(product, audience).is_some(),
"mode": mode,
"fixed": prefill.fixed,
"percent": prefill.percent,
"error": error,
"lang": current_lang(jar),
}),
)
}
#[debug_handler]
async fn discount_edit(
auth: auth::JWT,
jar: CookieJar,
ViewEngine(v): ViewEngine<TeraView>,
Path(id): Path<i32>,
Query(params): Query<HashMap<String, String>>,
State(ctx): State<AppContext>,
) -> Result<Response> {
guard::current_admin(auth, &ctx).await?;
let audience = read_audience(&params);
let product = product_by_id(&ctx, id).await?;
// Re-editing always opens in fixed mode showing the current price.
let prefill = FormPrefill {
mode: "fixed".to_string(),
fixed: current_value(&product, audience)
.map(format_price)
.unwrap_or_default(),
percent: String::new(),
};
render_discount_form(&v, &jar, &product, audience, &prefill, None)
}
#[debug_handler]
async fn discount_update(
auth: auth::JWT,
jar: CookieJar,
ViewEngine(v): ViewEngine<TeraView>,
Path(id): Path<i32>,
Query(params): Query<HashMap<String, String>>,
State(ctx): State<AppContext>,
Form(form): Form<DiscountForm>,
) -> Result<Response> {
guard::current_admin(auth, &ctx).await?;
let audience = read_audience(&params);
let product = product_by_id(&ctx, id).await?;
let mode = match form.mode.as_deref() {
Some("percent") => "percent",
_ => "fixed",
};
let fixed = form.sale_price.unwrap_or_default().trim().to_string();
let percent = form.percent.unwrap_or_default().trim().to_string();
let prefill = FormPrefill {
mode: mode.to_string(),
fixed: fixed.clone(),
percent: percent.clone(),
};
let render_err =
|key: &str| render_discount_form(&v, &jar, &product, audience, &prefill, Some(key));
// Resolve the entered discount into a fixed sale price in cents. An empty
// input in the active mode clears the discount (same as the Remove action).
let sale_cents = if mode == "percent" {
if percent.is_empty() {
return clear_discount(&ctx, product, audience).await;
}
let pct = match parse_percent(&percent) {
Some(pct) => pct,
None => return render_err("discount-invalid"),
};
if pct <= 0.0 || pct >= 100.0 {
return render_err("discount-percent-range");
}
percent_to_sale_cents(product.price_cents, pct)
} else {
if fixed.is_empty() {
return clear_discount(&ctx, product, audience).await;
}
match parse_price_to_cents(&fixed) {
Ok(cents) => cents,
Err(_) => return render_err("discount-invalid"),
}
};
if sale_cents <= 0 {
return render_err("discount-must-be-positive");
}
if sale_cents >= product.price_cents {
return render_err("discount-below-regular");
}
let mut active = product.into_active_model();
set_value(&mut active, audience, Some(sale_cents));
active.update(&ctx.db).await?;
list_redirect(audience)
}
async fn clear_discount(
ctx: &AppContext,
product: products::Model,
audience: &str,
) -> Result<Response> {
let mut active = product.into_active_model();
set_value(&mut active, audience, None);
active.update(&ctx.db).await?;
list_redirect(audience)
}
#[debug_handler]
async fn discount_remove(
auth: auth::JWT,
Path(id): Path<i32>,
Query(params): Query<HashMap<String, String>>,
State(ctx): State<AppContext>,
) -> Result<Response> {
guard::current_admin(auth, &ctx).await?;
let audience = read_audience(&params);
let product = product_by_id(&ctx, id).await?;
clear_discount(&ctx, product, audience).await
}
pub fn routes() -> Routes {
let image_limit = DefaultBodyLimit::max(IMAGE_MAX_BYTES + 1024 * 1024);
Routes::new()
@@ -279,10 +686,27 @@ pub fn routes() -> Routes {
"/admin/catalog/products",
post(create).layer(image_limit.clone()),
)
.add("/admin/catalog/products/profiles", post(sync_profiles))
.add(
"/admin/catalog/products/profiles/preview",
post(profiles_preview),
)
.add("/admin/catalog/products/{id}/edit", get(edit))
.add(
"/admin/catalog/products/{id}",
post(update).layer(image_limit),
)
.add("/admin/catalog/products/{id}/delete", post(delete))
.add(
"/admin/catalog/products/{id}/discount/edit",
get(discount_edit),
)
.add(
"/admin/catalog/products/{id}/discount",
post(discount_update),
)
.add(
"/admin/catalog/products/{id}/discount/remove",
post(discount_remove),
)
}

View File

@@ -6,7 +6,6 @@ pub mod admin_categories;
pub mod admin_customers;
pub mod admin_dashboard;
pub mod admin_discount_profiles;
pub mod admin_discounts;
pub mod admin_form;
pub mod admin_orders;
pub mod admin_products;

View File

@@ -0,0 +1,36 @@
//! `SeaORM` Entity assigning a discount profile to a whole audience (all
//! personal viewers or all company accounts). Hand-written to match the
//! `audience_discount_profiles` migration.
use sea_orm::entity::prelude::*;
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq, Serialize, Deserialize)]
#[sea_orm(table_name = "audience_discount_profiles")]
pub struct Model {
pub created_at: DateTimeWithTimeZone,
pub updated_at: DateTimeWithTimeZone,
#[sea_orm(primary_key)]
pub id: i32,
/// "personal" or "business".
pub audience: String,
pub discount_profile_id: i32,
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {
#[sea_orm(
belongs_to = "super::discount_profiles::Entity",
from = "Column::DiscountProfileId",
to = "super::discount_profiles::Column::Id",
on_update = "Cascade",
on_delete = "Cascade"
)]
DiscountProfiles,
}
impl Related<super::discount_profiles::Entity> for Entity {
fn to() -> RelationDef {
Relation::DiscountProfiles.def()
}
}

View File

@@ -4,6 +4,7 @@ pub mod prelude;
pub mod account_discount_profiles;
pub mod account_product_prices;
pub mod audience_discount_profiles;
pub mod account_product_resolutions;
pub mod audit_logs;
pub mod categories;

View File

@@ -3,6 +3,7 @@
pub use super::account_discount_profiles::Entity as AccountDiscountProfiles;
pub use super::account_product_prices::Entity as AccountProductPrices;
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::customer_profiles::Entity as CustomerProfiles;

View File

@@ -17,6 +17,7 @@ pub struct Model {
pub description: Option<String>,
pub price_cents: i64,
pub sale_price_cents: Option<i64>,
pub business_sale_price_cents: Option<i64>,
pub currency: String,
pub sku: Option<String>,
pub stock: i32,

View File

@@ -0,0 +1,18 @@
//! Discount profiles applied globally to an audience ("personal" or "business").
pub use crate::models::_entities::audience_discount_profiles::{
ActiveModel, Column, Entity, Model,
};
use sea_orm::entity::prelude::*;
pub type AudienceDiscountProfiles = 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,
{
Ok(self)
}
}

View File

@@ -9,6 +9,7 @@ pub mod _entities;
pub mod account_discount_profiles;
pub mod account_product_prices;
pub mod account_product_resolutions;
pub mod audience_discount_profiles;
pub mod audit_logs;
pub mod categories;
pub mod discount_profile_products;

View File

@@ -37,6 +37,13 @@ impl Model {
self.price_cents
}
}
/// Whether a baseline business discount (for all company accounts) is set and
/// actually below the regular price.
#[must_use]
pub fn business_on_sale(&self) -> bool {
matches!(self.business_sale_price_cents, Some(sale) if sale < self.price_cents)
}
}
// implement your write-oriented logic here

View File

@@ -1,11 +1,16 @@
//! Single source of truth for the price a given viewer pays for a product, so
//! the storefront, cart, and placed orders always agree.
//!
//! Everyone sees the public price — the lower of the regular price and any
//! public sale ([`products::Model::effective_price_cents`]). A logged-in
//! **company** account additionally gets their business price: the lowest of the
//! public price, any admin-set negotiated price, and the price from their
//! assigned automated discount profiles. **Lowest wins.**
//! Layers, all combined by "lowest wins":
//! - **Personal price** (everyone, incl. anonymous): the lower of the regular
//! price, the public sale (`products.sale_price_cents`), and any discount
//! profiles assigned to the *personal* audience on the discounts page.
//! - **Business price** (company accounts): the lower of the personal price, the
//! global business baseline (`products.business_sale_price_cents`), discount
//! profiles assigned to the *business* audience, the company's own assigned
//! profiles, and the company's manually negotiated price.
//!
//! A company therefore always pays the lowest of personal vs business.
use std::collections::{HashMap, HashSet};
@@ -14,48 +19,42 @@ use sea_orm::{ColumnTrait, EntityTrait, QueryFilter};
use crate::models::{
account_discount_profiles, account_product_prices, account_product_resolutions,
discount_profile_products, discount_profiles, products, users,
audience_discount_profiles, discount_profile_products, discount_profiles, products, users,
};
use crate::shared::money::apply_discount_bp;
/// `account_type` value that unlocks business pricing.
const COMPANY: &str = "company";
const AUDIENCE_PERSONAL: &str = "personal";
const AUDIENCE_BUSINESS: &str = "business";
/// The resolved price for one product and one viewer (the slim shape templates
/// and the cart use).
#[derive(Debug, Clone, Copy)]
pub struct PricedProduct {
/// What the viewer pays, in minor units.
pub price_cents: i64,
/// The regular list price, used as the struck-through reference.
pub regular_cents: i64,
/// True when a business-specific deal (not just a public sale) set the price.
/// True when a business-specific deal (not just the personal price) won.
pub is_business: bool,
}
impl PricedProduct {
/// Whether the final price is below the regular price (render it reduced).
#[must_use]
pub fn is_reduced(&self) -> bool {
self.price_cents < self.regular_cents
}
}
/// Full breakdown for one product and one viewer, used by the admin company page
/// (which needs to show each layer and any collision). The storefront only needs
/// [`PriceDetail::priced`].
/// Full breakdown for one product and one viewer, used by the admin company page.
#[derive(Debug, Clone)]
pub struct PriceDetail {
pub regular_cents: i64,
/// The personal price (what non-business viewers pay).
pub public_cents: i64,
pub manual_cents: Option<i64>,
pub auto_cents: Option<i64>,
/// The profile that produced `auto_cents` (the resolved/only/biggest one).
pub auto_profile_id: Option<i32>,
/// Every assigned profile that covers this product.
pub covering_profile_ids: Vec<i32>,
/// True when more than one profile covers the product and the admin has not
/// resolved which wins (a fallback was used).
pub collision: bool,
pub price_cents: i64,
pub is_business: bool,
@@ -86,66 +85,134 @@ impl PriceDetail {
}
}
/// The "lowest wins" decision: pick the business price only when it is at or
/// below the public price. Pure, so it is unit-tested directly.
fn decide(regular_cents: i64, public_cents: i64, business: Option<i64>) -> PricedProduct {
/// The "lowest wins" decision: take the business price only when it is at or
/// below the personal price. Pure, so it is unit-tested directly.
fn decide(regular_cents: i64, personal_cents: i64, business: Option<i64>) -> PricedProduct {
match business {
Some(b) if b <= public_cents => PricedProduct {
Some(b) if b <= personal_cents => PricedProduct {
price_cents: b,
regular_cents,
is_business: true,
},
_ => PricedProduct {
price_cents: public_cents,
price_cents: personal_cents,
regular_cents,
is_business: false,
},
}
}
/// Is this viewer a business (company) account?
fn is_company(user: Option<&users::Model>) -> bool {
matches!(user, Some(u) if u.account_type == COMPANY)
}
/// Everything needed to resolve every product's business price for one account,
/// loaded once so listing pages and the cart avoid N+1 queries.
struct B2bContext {
manual: HashMap<i32, i64>,
/// `min` of `Option`s, ignoring `None`s.
fn lowest(values: [Option<i64>; 4]) -> Option<i64> {
values.into_iter().flatten().min()
}
/// A set of discount profiles plus their product membership, with the logic to
/// price a product against them.
struct LoadedProfiles {
profiles: Vec<discount_profiles::Model>,
membership: HashMap<i32, HashSet<i32>>,
}
impl LoadedProfiles {
fn empty() -> Self {
Self {
profiles: Vec::new(),
membership: HashMap::new(),
}
}
/// The best (lowest) price any covering profile produces off the regular
/// price, or `None` when no profile covers the product.
fn best_price(&self, regular_cents: i64, product_id: i32) -> Option<i64> {
let empty = HashSet::new();
self.profiles
.iter()
.filter(|p| p.covers(product_id, self.membership.get(&p.id).unwrap_or(&empty)))
.map(|p| apply_discount_bp(regular_cents, p.percent_bp))
.min()
}
/// Every profile that covers a product (for the per-company collision UI).
fn covering(&self, product_id: i32) -> Vec<&discount_profiles::Model> {
let empty = HashSet::new();
self.profiles
.iter()
.filter(|p| p.covers(product_id, self.membership.get(&p.id).unwrap_or(&empty)))
.collect()
}
}
async fn load_membership(
ctx: &AppContext,
profile_ids: &[i32],
) -> Result<HashMap<i32, HashSet<i32>>> {
let mut membership: HashMap<i32, HashSet<i32>> = HashMap::new();
if profile_ids.is_empty() {
return Ok(membership);
}
let rows = discount_profile_products::Entity::find()
.filter(discount_profile_products::Column::DiscountProfileId.is_in(profile_ids.to_vec()))
.all(&ctx.db)
.await?;
for row in rows {
membership
.entry(row.discount_profile_id)
.or_default()
.insert(row.product_id);
}
Ok(membership)
}
async fn load_profiles_by_ids(ctx: &AppContext, ids: Vec<i32>) -> Result<LoadedProfiles> {
if ids.is_empty() {
return Ok(LoadedProfiles::empty());
}
let profiles = discount_profiles::Entity::find()
.filter(discount_profiles::Column::Id.is_in(ids.clone()))
.all(&ctx.db)
.await?;
let membership = load_membership(ctx, &ids).await?;
Ok(LoadedProfiles {
profiles,
membership,
})
}
/// Profiles assigned globally to an audience on the discounts page.
async fn load_audience(ctx: &AppContext, audience: &str) -> Result<LoadedProfiles> {
let ids: Vec<i32> = audience_discount_profiles::Entity::find()
.filter(audience_discount_profiles::Column::Audience.eq(audience))
.all(&ctx.db)
.await?
.into_iter()
.map(|a| a.discount_profile_id)
.collect();
load_profiles_by_ids(ctx, ids).await
}
/// Per-company pricing inputs (manual prices, assigned profiles, resolutions).
struct B2bContext {
manual: HashMap<i32, i64>,
profiles: LoadedProfiles,
resolutions: HashMap<i32, i32>,
}
async fn load_b2b(ctx: &AppContext, user_id: i32) -> Result<B2bContext> {
let manual = account_product_prices::Model::map_for_user(&ctx.db, user_id).await?;
let assigns = account_discount_profiles::Entity::find()
let ids: Vec<i32> = account_discount_profiles::Entity::find()
.filter(account_discount_profiles::Column::UserId.eq(user_id))
.all(&ctx.db)
.await?;
let profile_ids: Vec<i32> = assigns.iter().map(|a| a.discount_profile_id).collect();
let (profiles, membership) = if profile_ids.is_empty() {
(Vec::new(), HashMap::new())
} else {
let profiles = discount_profiles::Entity::find()
.filter(discount_profiles::Column::Id.is_in(profile_ids.clone()))
.all(&ctx.db)
.await?;
let rows = discount_profile_products::Entity::find()
.filter(discount_profile_products::Column::DiscountProfileId.is_in(profile_ids))
.all(&ctx.db)
.await?;
let mut membership: HashMap<i32, HashSet<i32>> = HashMap::new();
for row in rows {
membership
.entry(row.discount_profile_id)
.or_default()
.insert(row.product_id);
}
(profiles, membership)
};
.await?
.into_iter()
.map(|a| a.discount_profile_id)
.collect();
let profiles = load_profiles_by_ids(ctx, ids).await?;
let resolutions = account_product_resolutions::Entity::find()
.filter(account_product_resolutions::Column::UserId.eq(user_id))
@@ -158,86 +225,183 @@ async fn load_b2b(ctx: &AppContext, user_id: i32) -> Result<B2bContext> {
Ok(B2bContext {
manual,
profiles,
membership,
resolutions,
})
}
/// Resolve one product's full price breakdown for `b2b` (None = public viewer).
fn detail_for(product: &products::Model, b2b: Option<&B2bContext>) -> PriceDetail {
/// Everything loaded once per request to price any product for the viewer.
struct PricingCtx {
personal: LoadedProfiles,
business: LoadedProfiles,
b2b: Option<B2bContext>,
}
/// Resolve the per-company automated price for a product: the single covering
/// profile, the admin-resolved winner on a collision, or (unresolved) the
/// biggest discount, flagged.
fn company_auto(
b2b: &B2bContext,
regular_cents: i64,
product_id: i32,
) -> (Option<i64>, Option<i32>, bool, Vec<i32>) {
let covering = b2b.profiles.covering(product_id);
let ids: Vec<i32> = covering.iter().map(|p| p.id).collect();
if covering.is_empty() {
return (None, None, false, ids);
}
let (chosen, collision) = if covering.len() == 1 {
(covering[0], false)
} else {
match b2b
.resolutions
.get(&product_id)
.and_then(|rid| covering.iter().find(|p| p.id == *rid).copied())
{
Some(resolved) => (resolved, false),
None => (
covering
.iter()
.max_by_key(|p| p.percent_bp)
.copied()
.expect("covering is non-empty"),
true,
),
}
};
(
Some(apply_discount_bp(regular_cents, chosen.percent_bp)),
Some(chosen.id),
collision,
ids,
)
}
fn detail_for(product: &products::Model, pc: &PricingCtx) -> PriceDetail {
let regular = product.price_cents;
let public = product.effective_price_cents();
let Some(b2b) = b2b else {
return PriceDetail::public_only(regular, public);
// Personal price: public sale + personal-audience profiles, lowest wins.
let personal_sale = product.effective_price_cents();
let personal_profile = pc.personal.best_price(regular, product.id);
let personal_effective = personal_profile
.map_or(personal_sale, |p| personal_sale.min(p));
let Some(b2b) = &pc.b2b else {
return PriceDetail::public_only(regular, personal_effective);
};
// Business candidates (company accounts only).
let manual = b2b.manual.get(&product.id).copied();
let (auto_cents, auto_profile_id, collision, covering_ids) =
company_auto(b2b, regular, product.id);
let business_global = product.business_sale_price_cents;
let business_profile = pc.business.best_price(regular, product.id);
let business_best = lowest([manual, auto_cents, business_global, business_profile]);
// Which assigned profiles cover this product.
let empty = HashSet::new();
let covering: Vec<&discount_profiles::Model> = b2b
.profiles
.iter()
.filter(|p| p.covers(product.id, b2b.membership.get(&p.id).unwrap_or(&empty)))
.collect();
let mut auto_cents = None;
let mut auto_profile_id = None;
let mut collision = false;
if !covering.is_empty() {
let chosen = if covering.len() == 1 {
covering[0]
} else {
// Two+ profiles collide: honour the admin's resolution, else fall
// back to the biggest discount and flag it for resolving.
match b2b
.resolutions
.get(&product.id)
.and_then(|rid| covering.iter().find(|p| p.id == *rid).copied())
{
Some(resolved) => resolved,
None => {
collision = true;
covering
.iter()
.max_by_key(|p| p.percent_bp)
.copied()
.expect("covering is non-empty")
}
}
};
auto_profile_id = Some(chosen.id);
auto_cents = Some(apply_discount_bp(regular, chosen.percent_bp));
}
let business = [manual, auto_cents].into_iter().flatten().min();
let priced = decide(regular, public, business);
let priced = decide(regular, personal_effective, business_best);
PriceDetail {
regular_cents: regular,
public_cents: public,
public_cents: personal_effective,
manual_cents: manual,
auto_cents,
auto_profile_id,
covering_profile_ids: covering.iter().map(|p| p.id).collect(),
covering_profile_ids: covering_ids,
collision,
price_cents: priced.price_cents,
is_business: priced.is_business,
}
}
/// Full breakdowns for many products for `user`, batching per-account lookups.
async fn load_pricing_ctx(ctx: &AppContext, user: Option<&users::Model>) -> Result<PricingCtx> {
let personal = load_audience(ctx, AUDIENCE_PERSONAL).await?;
let (business, b2b) = if is_company(user) {
(
load_audience(ctx, AUDIENCE_BUSINESS).await?,
Some(load_b2b(ctx, user.expect("is_company implies Some").id).await?),
)
} else {
(LoadedProfiles::empty(), None)
};
Ok(PricingCtx {
personal,
business,
b2b,
})
}
/// Full breakdowns for many products for `user`, batching per-request lookups.
pub async fn detail_many(
ctx: &AppContext,
list: &[products::Model],
user: Option<&users::Model>,
) -> Result<Vec<PriceDetail>> {
let b2b = if is_company(user) {
Some(load_b2b(ctx, user.expect("is_company implies Some").id).await?)
let pc = load_pricing_ctx(ctx, user).await?;
Ok(list.iter().map(|p| detail_for(p, &pc)).collect())
}
/// Effective prices for a whole audience using only the global layers (the
/// per-product sale + audience-assigned profiles + the business baseline), with
/// no specific company's per-company deals. Used by the discounts admin page to
/// preview what each tab's discounts produce. `audience` is "personal" or
/// "business".
pub async fn audience_price_many(
ctx: &AppContext,
list: &[products::Model],
audience: &str,
) -> Result<Vec<PricedProduct>> {
let personal = load_audience(ctx, AUDIENCE_PERSONAL).await?;
let (business, b2b) = if audience == AUDIENCE_BUSINESS {
(
load_audience(ctx, AUDIENCE_BUSINESS).await?,
// A generic company with no per-company profiles/negotiated prices.
Some(B2bContext {
manual: HashMap::new(),
profiles: LoadedProfiles::empty(),
resolutions: HashMap::new(),
}),
)
} else {
None
(LoadedProfiles::empty(), None)
};
Ok(list.iter().map(|p| detail_for(p, b2b.as_ref())).collect())
let pc = PricingCtx {
personal,
business,
b2b,
};
Ok(list.iter().map(|p| detail_for(p, &pc).priced()).collect())
}
/// Like [`audience_price_many`], but prices against an *unsaved* set of profile
/// ids for the active audience instead of the persisted assignment. Used by the
/// products page to preview effective prices as the admin toggles profile
/// checkboxes, before they hit Save. For the business tab the personal layer
/// stays the persisted one (businesses get the lower of personal/business), and
/// only the business layer is replaced by the previewed selection.
pub async fn audience_price_many_preview(
ctx: &AppContext,
list: &[products::Model],
audience: &str,
selected_profile_ids: Vec<i32>,
) -> Result<Vec<PricedProduct>> {
let preview = load_profiles_by_ids(ctx, selected_profile_ids).await?;
let (personal, business, b2b) = if audience == AUDIENCE_BUSINESS {
(
load_audience(ctx, AUDIENCE_PERSONAL).await?,
preview,
Some(B2bContext {
manual: HashMap::new(),
profiles: LoadedProfiles::empty(),
resolutions: HashMap::new(),
}),
)
} else {
(preview, LoadedProfiles::empty(), None)
};
let pc = PricingCtx {
personal,
business,
b2b,
};
Ok(list.iter().map(|p| detail_for(p, &pc).priced()).collect())
}
/// Price one product for `user` (`None` = anonymous/public).
@@ -250,8 +414,7 @@ pub async fn price_for(
Ok(detail[0].priced())
}
/// Price many products for `user`, batching the per-account lookups to avoid
/// N+1 queries on listing pages and the cart.
/// Price many products for `user`, batching the per-request lookups.
pub async fn price_many(
ctx: &AppContext,
list: &[products::Model],
@@ -270,10 +433,9 @@ mod tests {
use crate::shared::money::apply_discount_bp;
#[test]
fn public_only() {
fn personal_only() {
let p = decide(10000, 10000, None);
assert_eq!(p.price_cents, 10000);
assert!(!p.is_reduced());
assert!(!p.is_business);
}
@@ -285,8 +447,8 @@ mod tests {
}
#[test]
fn public_sale_beats_business() {
// regular 100, public sale 80, business best 90 -> pay 80, not business.
fn personal_beats_business() {
// personal already 80 (e.g. personal profile), business best 90 -> 80.
let p = decide(10000, 8000, Some(9000));
assert_eq!(p.price_cents, 8000);
assert!(!p.is_business);
@@ -301,9 +463,8 @@ mod tests {
#[test]
fn discount_bp_rounds_half_up() {
assert_eq!(apply_discount_bp(10000, 500), 9500); // 5%
assert_eq!(apply_discount_bp(10000, 1500), 8500); // 15%
assert_eq!(apply_discount_bp(999, 500), 949); // 49.95 -> 50 off
assert_eq!(apply_discount_bp(10000, 500), 9500);
assert_eq!(apply_discount_bp(10000, 1500), 8500);
assert_eq!(apply_discount_bp(10000, 0), 10000);
}
}

View File

@@ -74,3 +74,85 @@ pub fn sidebar_groups(categories: &[categories::Model]) -> Vec<Value> {
})
.collect()
}
/// Admin category-filter tree for product listings: like [`sidebar_groups`] but
/// each node carries its `id` (links filter by `?category=<id>`) and a `count`
/// of matching products — the node's own products plus every descendant's, so a
/// parent's count covers its whole subtree. `category_ids` is each product's
/// `category_id` (`None` = uncategorized), taken over the full unfiltered list.
pub fn admin_category_groups(
categories: &[categories::Model],
category_ids: &[Option<i32>],
) -> Vec<Value> {
use std::collections::HashMap;
let mut direct: HashMap<i32, usize> = HashMap::new();
for id in category_ids.iter().flatten() {
*direct.entry(*id).or_default() += 1;
}
let subtree_count = |id: i32| -> usize {
let mut n = direct.get(&id).copied().unwrap_or(0);
for d in crate::models::categories::descendant_ids(categories, id) {
n += direct.get(&d).copied().unwrap_or(0);
}
n
};
let mut top: Vec<&categories::Model> = categories
.iter()
.filter(|c| c.parent_id.is_none())
.collect();
top.sort_by(|a, b| a.position.cmp(&b.position).then_with(|| a.name.cmp(&b.name)));
top.into_iter()
.map(|category| {
let children: Vec<Value> = crate::models::categories::children_of(categories, category.id)
.into_iter()
.map(|child| {
json!({ "id": child.id, "name": child.name, "count": subtree_count(child.id) })
})
.collect();
json!({
"id": category.id,
"name": category.name,
"count": subtree_count(category.id),
"children": children,
})
})
.collect()
}
/// Resolve the `?category=` filter param against the category forest into the
/// set of `category_id`s a product may have to be shown. Returns:
/// - `None` for "all" (no filtering) or an unknown value,
/// - `Some(empty set)` for "none" (uncategorized — match products with no
/// category; callers treat an empty set as "uncategorized only"),
/// - `Some({id} descendants)` for a numeric category id.
pub fn category_filter_ids(
categories: &[categories::Model],
selected: &str,
) -> Option<std::collections::HashSet<i32>> {
match selected {
"all" => None,
"none" => Some(std::collections::HashSet::new()),
s => s.parse::<i32>().ok().map(|id| {
let mut set = crate::models::categories::descendant_ids(categories, id);
set.insert(id);
set
}),
}
}
/// Whether a product with `category_id` passes the filter from
/// [`category_filter_ids`]: `None` keeps everything, an empty set keeps only
/// uncategorized products, a non-empty set keeps products in those categories.
pub fn category_filter_keep(
filter: &Option<std::collections::HashSet<i32>>,
category_id: Option<i32>,
) -> bool {
match filter {
None => true,
Some(set) if set.is_empty() => category_id.is_none(),
Some(set) => category_id.is_some_and(|id| set.contains(&id)),
}
}