objednavky

This commit is contained in:
Ondur
2026-11-18 18:14:43 +01:00
parent b6f81a12ea
commit 69a8138226
5 changed files with 232 additions and 55 deletions

View File

@@ -1,11 +1,14 @@
@page "/admin/zbozi/edit" ```razor
@page "/admin/zbozi/edit"
@page "/admin/zbozi/edit/{Id:int}" @page "/admin/zbozi/edit/{Id:int}"
@layout Web_Jarmark.Components.Layout.Admin.AdminLayout @layout Web_Jarmark.Components.Layout.Admin.AdminLayout
@rendermode InteractiveServer @rendermode InteractiveServer
@using Microsoft.EntityFrameworkCore @using Microsoft.EntityFrameworkCore
@using Microsoft.AspNetCore.Authorization @using Microsoft.AspNetCore.Authorization
@using Web_Jarmark.Data @using Web_Jarmark.Data
@using Web_Jarmark.Data.Models @using Web_Jarmark.Data.Models
@inject ApplicationDbContext Db @inject ApplicationDbContext Db
@inject NavigationManager Nav @inject NavigationManager Nav
@@ -41,7 +44,7 @@
<section class="ao-panel" style="max-width:560px;margin:0 auto"> <section class="ao-panel" style="max-width:560px;margin:0 auto">
<div class="ap-field"> <div class="ap-field">
<label>Název</label> <label>Název</label>
<input class="ao-input" @bind="name" /> <input class="ao-input" maxlength="150" @bind="name" />
</div> </div>
<div class="ap-field"> <div class="ap-field">
@@ -57,22 +60,35 @@
<div class="ap-field"> <div class="ap-field">
<label>Popis</label> <label>Popis</label>
<textarea class="ao-input" style="min-height:110px;resize:vertical" @bind="description"></textarea> <textarea class="ao-input"
maxlength="5000"
style="min-height:110px;resize:vertical"
@bind="description"></textarea>
</div> </div>
<div class="ap-field"> <div class="ap-field">
<label>Cena (Kč)</label> <label>Cena (Kč)</label>
<input type="number" step="0.01" class="ao-input" @bind="price" /> <input type="number"
min="0"
step="0.01"
class="ao-input"
@bind="price" />
</div> </div>
<div class="ap-field"> <div class="ap-field">
<label>Sklad (ks)</label> <label>Sklad (ks)</label>
<input type="number" class="ao-input" @bind="stockQuantity" /> <input type="number"
min="0"
step="1"
class="ao-input"
@bind="stockQuantity" />
</div> </div>
<div class="ap-field"> <div class="ap-field">
<label>URL obrázku</label> <label>URL obrázku</label>
<input class="ao-input" @bind="imageUrl" /> <input class="ao-input"
maxlength="2048"
@bind="imageUrl" />
</div> </div>
<label class="ap-switch"> <label class="ap-switch">
@@ -81,9 +97,13 @@
</label> </label>
<div class="ap-form-actions"> <div class="ap-form-actions">
<button type="button" class="ap-btn ap-btn-primary" disabled="@saving" @onclick="SaveAsync"> <button type="button"
class="ap-btn ap-btn-primary"
disabled="@saving"
@onclick="SaveAsync">
@(saving ? "Ukládám…" : "Uložit") @(saving ? "Ukládám…" : "Uložit")
</button> </button>
<a class="ap-btn" href="/admin/zbozi">Zrušit</a> <a class="ap-btn" href="/admin/zbozi">Zrušit</a>
</div> </div>
</section> </section>
@@ -136,7 +156,10 @@
return; return;
} }
var entity = await Db.Products.AsNoTracking().FirstOrDefaultAsync(p => p.Id == Id!.Value); var entity = await Db.Products
.AsNoTracking()
.FirstOrDefaultAsync(p => p.Id == Id!.Value);
if (entity is null) if (entity is null)
{ {
notFound = true; notFound = true;
@@ -151,29 +174,75 @@
stockQuantity = entity.StockQuantity; stockQuantity = entity.StockQuantity;
imageUrl = entity.ImageUrl ?? ""; imageUrl = entity.ImageUrl ?? "";
isVisible = entity.IsVisible; isVisible = entity.IsVisible;
loading = false; loading = false;
} }
private async Task SaveAsync() private async Task SaveAsync()
{ {
if (saving)
return;
saving = true; saving = true;
error = null; error = null;
try try
{ {
name = name?.Trim() ?? "";
description = description?.Trim() ?? "";
imageUrl = imageUrl?.Trim() ?? "";
if (string.IsNullOrWhiteSpace(name)) if (string.IsNullOrWhiteSpace(name))
{ {
error = "Zadejte název produktu."; error = "Zadejte název produktu.";
return; return;
} }
if (categoryId <= 0) if (name.Length > 150)
{ {
error = "Vyberte kategorii."; error = "Název může mít maximálně 150 znaků.";
return;
}
if (description.Length > 5000)
{
error = "Popis může mít maximálně 5000 znaků.";
return;
}
if (price < 0 || price > 100000000)
{
error = "Cena musí být mezi 0 a 100 000 000 Kč.";
return;
}
if (decimal.Round(price, 2) != price)
{
error = "Cena může mít maximálně dvě desetinná místa.";
return;
}
if (stockQuantity < 0)
{
error = "Počet kusů na skladě nemůže být záporný.";
return;
}
if (categoryId <= 0 ||
!await Db.Categories.AnyAsync(c => c.Id == categoryId))
{
error = "Vyberte platnou kategorii.";
return;
}
if (!IsValidImageUrl(imageUrl))
{
error = "Obrázek musí mít platnou HTTPS adresu nebo bezpečnou relativní cestu.";
return; return;
} }
Product entity; Product entity;
if (IsNew) if (IsNew)
{ {
entity = new Product(); entity = new Product();
@@ -181,24 +250,37 @@
} }
else else
{ {
entity = await Db.Products.FirstAsync(p => p.Id == Id!.Value); entity = await Db.Products
.FirstOrDefaultAsync(p => p.Id == Id!.Value);
if (entity is null)
{
notFound = true;
error = "Produkt již neexistuje.";
return;
}
} }
entity.Name = name.Trim(); entity.Name = name;
entity.Description = description?.Trim() ?? ""; entity.Description = description;
entity.CategoryId = categoryId; entity.CategoryId = categoryId;
entity.Price = price; entity.Price = price;
entity.StockQuantity = stockQuantity; entity.StockQuantity = stockQuantity;
entity.ImageUrl = imageUrl?.Trim() ?? ""; entity.ImageUrl = imageUrl;
entity.IsVisible = isVisible; entity.IsVisible = isVisible;
entity.UpdatedAt = DateTime.UtcNow; entity.UpdatedAt = DateTime.UtcNow;
await Db.SaveChangesAsync(); await Db.SaveChangesAsync();
Nav.NavigateTo("/admin/zbozi"); Nav.NavigateTo("/admin/zbozi");
} }
catch (Exception ex) catch (DbUpdateException)
{ {
error = "Uložení se nezdařilo: " + ex.Message; error = "Produkt se nepodařilo uložit. Zkontrolujte zadané údaje.";
}
catch (Exception)
{
error = "Při ukládání nastala neočekávaná chyba.";
} }
finally finally
{ {
@@ -206,5 +288,30 @@
} }
} }
private static bool IsValidImageUrl(string value)
{
if (string.IsNullOrWhiteSpace(value))
return true;
if (value.Length > 2048)
return false;
if (value.StartsWith("//") ||
value.Contains('\\') ||
value.Any(char.IsControl))
return false;
if (Uri.TryCreate(value, UriKind.Absolute, out var uri))
{
return uri.Scheme == Uri.UriSchemeHttps &&
!string.IsNullOrWhiteSpace(uri.Host);
}
return value.StartsWith('/') &&
!value.StartsWith("//") &&
!value.Contains("..");
}
private sealed record CatOption(int Id, string Name); private sealed record CatOption(int Id, string Name);
} }
```

View File

@@ -259,8 +259,8 @@
<style> <style>
/* ========================================== /* ==========================================
ZÁKLADNÍ VZHLED ZÁKLADNÍ VZHLED
========================================== */ ========================================== */
.shop-page { .shop-page {
width: 100%; width: 100%;
@@ -278,8 +278,8 @@
/* ========================================== /* ==========================================
HERO SEKCE HERO SEKCE
========================================== */ ========================================== */
.market-hero { .market-hero {
position: relative; position: relative;
@@ -394,8 +394,8 @@
/* ========================================== /* ==========================================
DEKORACE HERO SEKCE DEKORACE HERO SEKCE
========================================== */ ========================================== */
.hero-decoration { .hero-decoration {
position: absolute; position: absolute;
@@ -556,8 +556,8 @@
/* ========================================== /* ==========================================
INFORMAČNÍ LIŠTA INFORMAČNÍ LIŠTA
========================================== */ ========================================== */
.benefits-section { .benefits-section {
display: grid; display: grid;
@@ -614,8 +614,8 @@
/* ========================================== /* ==========================================
KATALOG KATALOG
========================================== */ ========================================== */
.catalog-section { .catalog-section {
padding: 0 5px; padding: 0 5px;
@@ -695,8 +695,8 @@
/* ========================================== /* ==========================================
VYHLEDÁVÁNÍ VYHLEDÁVÁNÍ
========================================== */ ========================================== */
.catalog-search { .catalog-search {
display: flex; display: flex;
@@ -764,8 +764,8 @@
/* ========================================== /* ==========================================
PRODUKTOVÉ KARTY PRODUKTOVÉ KARTY
========================================== */ ========================================== */
.market-grid { .market-grid {
display: grid; display: grid;
@@ -843,8 +843,8 @@
/* ========================================== /* ==========================================
PRÁZDNÉ STAVY PRÁZDNÉ STAVY
========================================== */ ========================================== */
.market-empty { .market-empty {
display: flex; display: flex;
@@ -901,8 +901,8 @@
/* ========================================== /* ==========================================
PATIČKA PATIČKA
========================================== */ ========================================== */
.shop-footer { .shop-footer {
display: flex; display: flex;
@@ -941,8 +941,8 @@
/* ========================================== /* ==========================================
NOTIFIKACE KOŠÍKU NOTIFIKACE KOŠÍKU
========================================== */ ========================================== */
.cart-notification { .cart-notification {
position: fixed; position: fixed;
@@ -1003,8 +1003,8 @@
/* ========================================== /* ==========================================
TABLETY TABLETY
========================================== */ ========================================== */
@@media (max-width: 1100px) { @@media (max-width: 1100px) {
@@ -1028,8 +1028,8 @@
/* ========================================== /* ==========================================
MENŠÍ DISPLEJE MENŠÍ DISPLEJE
========================================== */ ========================================== */
@@media (max-width: 800px) { @@media (max-width: 800px) {
@@ -1070,8 +1070,8 @@
/* ========================================== /* ==========================================
MOBILY MOBILY
========================================== */ ========================================== */
@@media (max-width: 600px) { @@media (max-width: 600px) {
@@ -1230,8 +1230,8 @@
/* ========================================== /* ==========================================
REDUKCE ANIMACÍ REDUKCE ANIMACÍ
========================================== */ ========================================== */
@@media (prefers-reduced-motion: reduce) { @@media (prefers-reduced-motion: reduce) {
@@ -1326,7 +1326,27 @@
private async Task HandleAddToCart(Product product) private async Task HandleAddToCart(Product product)
{ {
if (string.IsNullOrWhiteSpace(cartToken)) if (string.IsNullOrWhiteSpace(cartToken))
{
await ShowCartNotification("Košík se nepodařilo načíst. Obnovte stránku a zkuste to znovu.");
return; return;
}
// Vždy načteme aktuální stav produktu z databáze.
// Údaje předané z produktové karty mohou být zastaralé.
var currentProduct = await DbContext.Products
.FirstOrDefaultAsync(p => p.Id == product.Id && p.IsVisible);
if (currentProduct == null)
{
await ShowCartNotification("Tento produkt už není dostupný.");
return;
}
if (currentProduct.StockQuantity <= 0)
{
await ShowCartNotification("Tento produkt už není skladem.");
return;
}
var cart = await DbContext.Carts var cart = await DbContext.Carts
.FirstOrDefaultAsync(c => c.Token == cartToken); .FirstOrDefaultAsync(c => c.Token == cartToken);
@@ -1347,10 +1367,18 @@
var cartItem = await DbContext.CartItems var cartItem = await DbContext.CartItems
.FirstOrDefaultAsync(ci => .FirstOrDefaultAsync(ci =>
ci.CartId == cart.Id && ci.CartId == cart.Id &&
ci.ProductId == product.Id); ci.ProductId == currentProduct.Id);
if (cartItem != null) if (cartItem != null)
{ {
// Nepovolíme zvýšit množství nad aktuální skladovou zásobu.
if (cartItem.Quantity >= currentProduct.StockQuantity)
{
await ShowCartNotification(
$"V košíku už máte maximální dostupné množství produktu {currentProduct.Name}.");
return;
}
cartItem.Quantity++; cartItem.Quantity++;
} }
else else
@@ -1358,7 +1386,7 @@
cartItem = new CartItem cartItem = new CartItem
{ {
CartId = cart.Id, CartId = cart.Id,
ProductId = product.Id, ProductId = currentProduct.Id,
Quantity = 1 Quantity = 1
}; };
@@ -1369,18 +1397,18 @@
await DbContext.SaveChangesAsync(); await DbContext.SaveChangesAsync();
await ShowCartNotification(product.Name); await ShowCartNotification($"{currentProduct.Name} byl přidán do košíku.");
} }
private async Task ShowCartNotification(string productName) private async Task ShowCartNotification(string message)
{ {
notificationCts?.Cancel(); notificationCts?.Cancel();
var currentCts = new CancellationTokenSource(); var currentCts = new CancellationTokenSource();
notificationCts = currentCts; notificationCts = currentCts;
notificationMessage = $"{productName} byl přidán do košíku."; notificationMessage = message;
showNotification = true; showNotification = true;
await InvokeAsync(StateHasChanged); await InvokeAsync(StateHasChanged);
@@ -1397,7 +1425,7 @@
} }
catch (OperationCanceledException) catch (OperationCanceledException)
{ {
// Nové přidání produktu restartovalo čas notifikace. // Nová notifikace restartovala čas zobrazení.
} }
finally finally
{ {
@@ -1417,4 +1445,4 @@
subscription?.Dispose(); subscription?.Dispose();
} }
} }

View File

@@ -486,6 +486,10 @@
try try
{ {
// Začneme databázovou transakci.
await using var transaction =
await DbContext.Database.BeginTransactionAsync();
var cart = await DbContext.Carts var cart = await DbContext.Carts
.Include(c => c.CartItems) .Include(c => c.CartItems)
.ThenInclude(ci => ci.Product) .ThenInclude(ci => ci.Product)
@@ -497,14 +501,42 @@
return; return;
} }
// Vygenerování náhodného přístupového tokenu // Znovu načteme aktuální skladové zásoby.
foreach (var item in cart.CartItems)
{
if (item.Quantity <= 0 || item.Product == null)
{
saveError = "Košík obsahuje neplatnou položku. Vrať se prosím do košíku.";
return;
}
await DbContext.Entry(item.Product).ReloadAsync();
if (DbContext.Entry(item.Product).State == EntityState.Detached
|| !item.Product.IsVisible)
{
saveError = $"Produkt „{item.Product.Name}“ už není dostupný.";
return;
}
if (item.Product.StockQuantity < item.Quantity)
{
saveError =
$"Produkt „{item.Product.Name}“ už nemá dostatečnou skladovou zásobu. " +
$"Aktuálně je skladem pouze {item.Product.StockQuantity} ks. " +
"Uprav množství v košíku.";
return;
}
}
// Vygenerování náhodného přístupového tokenu.
var tokenBytes = RandomNumberGenerator.GetBytes(32); var tokenBytes = RandomNumberGenerator.GetBytes(32);
var accessToken = Convert.ToBase64String(tokenBytes) var accessToken = Convert.ToBase64String(tokenBytes)
.Replace("+", "-") .Replace("+", "-")
.Replace("/", "_") .Replace("/", "_")
.TrimEnd('='); .TrimEnd('=');
// Uložíme pouze hash tokenu // Uložíme pouze hash tokenu.
var tokenHash = Convert.ToHexString( var tokenHash = Convert.ToHexString(
SHA256.HashData( SHA256.HashData(
Encoding.UTF8.GetBytes(accessToken))); Encoding.UTF8.GetBytes(accessToken)));
@@ -521,6 +553,10 @@
foreach (var item in cart.CartItems) foreach (var item in cart.CartItems)
{ {
// Odečteme objednané množství ze skladu.
item.Product.StockQuantity -= item.Quantity;
item.Product.UpdatedAt = DateTime.UtcNow;
order.OrderItems.Add(new OrderItem order.OrderItems.Add(new OrderItem
{ {
ProductId = item.ProductId, ProductId = item.ProductId,
@@ -535,8 +571,12 @@
DbContext.Orders.Add(order); DbContext.Orders.Add(order);
DbContext.CartItems.RemoveRange(cart.CartItems); DbContext.CartItems.RemoveRange(cart.CartItems);
// Uložíme objednávku i změny skladu.
await DbContext.SaveChangesAsync(); await DbContext.SaveChangesAsync();
// Potvrdíme transakci.
await transaction.CommitAsync();
var orderUrl = var orderUrl =
$"/objednavka/{order.Code}?token={Uri.EscapeDataString(accessToken)}"; $"/objednavka/{order.Code}?token={Uri.EscapeDataString(accessToken)}";
@@ -544,7 +584,9 @@
} }
catch catch
{ {
saveError = "Objednávku se nepodařilo uložit. Zkus to znovu."; saveError =
"Objednávku se nepodařilo uložit. Zkus to znovu. " +
"Pokud problém přetrvává, kontaktuj správce.";
} }
finally finally
{ {