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}"
@layout Web_Jarmark.Components.Layout.Admin.AdminLayout
@rendermode InteractiveServer
@using Microsoft.EntityFrameworkCore
@using Microsoft.AspNetCore.Authorization
@using Web_Jarmark.Data
@using Web_Jarmark.Data.Models
@inject ApplicationDbContext Db
@inject NavigationManager Nav
@@ -41,7 +44,7 @@
<section class="ao-panel" style="max-width:560px;margin:0 auto">
<div class="ap-field">
<label>Název</label>
<input class="ao-input" @bind="name" />
<input class="ao-input" maxlength="150" @bind="name" />
</div>
<div class="ap-field">
@@ -57,22 +60,35 @@
<div class="ap-field">
<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 class="ap-field">
<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 class="ap-field">
<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 class="ap-field">
<label>URL obrázku</label>
<input class="ao-input" @bind="imageUrl" />
<input class="ao-input"
maxlength="2048"
@bind="imageUrl" />
</div>
<label class="ap-switch">
@@ -81,9 +97,13 @@
</label>
<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")
</button>
<a class="ap-btn" href="/admin/zbozi">Zrušit</a>
</div>
</section>
@@ -136,7 +156,10 @@
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)
{
notFound = true;
@@ -151,29 +174,75 @@
stockQuantity = entity.StockQuantity;
imageUrl = entity.ImageUrl ?? "";
isVisible = entity.IsVisible;
loading = false;
}
private async Task SaveAsync()
{
if (saving)
return;
saving = true;
error = null;
try
{
name = name?.Trim() ?? "";
description = description?.Trim() ?? "";
imageUrl = imageUrl?.Trim() ?? "";
if (string.IsNullOrWhiteSpace(name))
{
error = "Zadejte název produktu.";
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;
}
Product entity;
if (IsNew)
{
entity = new Product();
@@ -181,24 +250,37 @@
}
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.Description = description?.Trim() ?? "";
entity.Name = name;
entity.Description = description;
entity.CategoryId = categoryId;
entity.Price = price;
entity.StockQuantity = stockQuantity;
entity.ImageUrl = imageUrl?.Trim() ?? "";
entity.ImageUrl = imageUrl;
entity.IsVisible = isVisible;
entity.UpdatedAt = DateTime.UtcNow;
await Db.SaveChangesAsync();
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
{
@@ -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);
}
```

View File

@@ -1326,7 +1326,27 @@
private async Task HandleAddToCart(Product product)
{
if (string.IsNullOrWhiteSpace(cartToken))
{
await ShowCartNotification("Košík se nepodařilo načíst. Obnovte stránku a zkuste to znovu.");
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
.FirstOrDefaultAsync(c => c.Token == cartToken);
@@ -1347,10 +1367,18 @@
var cartItem = await DbContext.CartItems
.FirstOrDefaultAsync(ci =>
ci.CartId == cart.Id &&
ci.ProductId == product.Id);
ci.ProductId == currentProduct.Id);
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++;
}
else
@@ -1358,7 +1386,7 @@
cartItem = new CartItem
{
CartId = cart.Id,
ProductId = product.Id,
ProductId = currentProduct.Id,
Quantity = 1
};
@@ -1369,18 +1397,18 @@
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();
var currentCts = new CancellationTokenSource();
notificationCts = currentCts;
notificationMessage = $"{productName} byl přidán do košíku.";
notificationMessage = message;
showNotification = true;
await InvokeAsync(StateHasChanged);
@@ -1397,7 +1425,7 @@
}
catch (OperationCanceledException)
{
// Nové přidání produktu restartovalo čas notifikace.
// Nová notifikace restartovala čas zobrazení.
}
finally
{

View File

@@ -486,6 +486,10 @@
try
{
// Začneme databázovou transakci.
await using var transaction =
await DbContext.Database.BeginTransactionAsync();
var cart = await DbContext.Carts
.Include(c => c.CartItems)
.ThenInclude(ci => ci.Product)
@@ -497,14 +501,42 @@
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 accessToken = Convert.ToBase64String(tokenBytes)
.Replace("+", "-")
.Replace("/", "_")
.TrimEnd('=');
// Uložíme pouze hash tokenu
// Uložíme pouze hash tokenu.
var tokenHash = Convert.ToHexString(
SHA256.HashData(
Encoding.UTF8.GetBytes(accessToken)));
@@ -521,6 +553,10 @@
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
{
ProductId = item.ProductId,
@@ -535,8 +571,12 @@
DbContext.Orders.Add(order);
DbContext.CartItems.RemoveRange(cart.CartItems);
// Uložíme objednávku i změny skladu.
await DbContext.SaveChangesAsync();
// Potvrdíme transakci.
await transaction.CommitAsync();
var orderUrl =
$"/objednavka/{order.Code}?token={Uri.EscapeDataString(accessToken)}";
@@ -544,7 +584,9 @@
}
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
{