This commit is contained in:
Ondur
2026-10-30 16:31:03 +01:00
2 changed files with 98 additions and 3 deletions

View File

@@ -4,6 +4,9 @@
@using Web_Jarmark.Data.Models @using Web_Jarmark.Data.Models
@using Web_Jarmark.Components.Pages.Shared @using Web_Jarmark.Components.Pages.Shared
@inject ApplicationDbContext DbContext @inject ApplicationDbContext DbContext
@inject IHttpContextAccessor HttpContextAccessor
@inject PersistentComponentState ApplicationState
@implements IDisposable
<PageTitle>Školní jarmark | Katalog</PageTitle> <PageTitle>Školní jarmark | Katalog</PageTitle>
@@ -49,6 +52,9 @@
@code { @code {
private List<Product> products = new(); private List<Product> products = new();
private bool isLoading = true; private bool isLoading = true;
private string? cartToken;
private PersistingComponentStateSubscription? subscription;
protected override async Task OnInitializedAsync() protected override async Task OnInitializedAsync()
{ {
@@ -65,9 +71,76 @@
{ {
isLoading = false; isLoading = false;
} }
} if (!ApplicationState.TryTakeFromJson<string>(
private void HandleAddToCart(Product product) "CartToken", out cartToken))
{ {
Console.WriteLine($"Přidán produkt: {product.Name}"); cartToken = HttpContextAccessor.HttpContext?
.Items["CartToken"] as string;
} }
subscription = ApplicationState.RegisterOnPersisting(() =>
{
ApplicationState.PersistAsJson("CartToken", cartToken);
return Task.CompletedTask;
});
}
private async Task HandleAddToCart(Product product)
{
if (string.IsNullOrWhiteSpace(cartToken))
return;
// Najdeme košík podle cookie
var cart = await DbContext.Carts
.FirstOrDefaultAsync(c => c.Token == cartToken);
// Pokud košík neexistuje, vytvoříme ho
if (cart == null)
{
cart = new Cart
{
Token = cartToken,
CreatedAt = DateTime.UtcNow,
UpdatedAt = DateTime.UtcNow
};
DbContext.Carts.Add(cart);
await DbContext.SaveChangesAsync();
}
// Zjistíme, jestli už produkt v košíku je
var cartItem = await DbContext.CartItems
.FirstOrDefaultAsync(ci =>
ci.CartId == cart.Id &&
ci.ProductId == product.Id);
if (cartItem != null)
{
// Produkt už existuje – zvýšíme množství
cartItem.Quantity++;
}
else
{
// Produkt ještě v košíku není
cartItem = new CartItem
{
CartId = cart.Id,
ProductId = product.Id,
Quantity = 1
};
DbContext.CartItems.Add(cartItem);
}
cart.UpdatedAt = DateTime.UtcNow;
await DbContext.SaveChangesAsync();
}
public void Dispose()
{
subscription?.Dispose();
}
} }

View File

@@ -37,7 +37,7 @@ builder.Services.AddIdentityCore<ApplicationUser>(options =>
.AddDefaultTokenProviders(); .AddDefaultTokenProviders();
builder.Services.AddSingleton<IEmailSender<ApplicationUser>, IdentityNoOpEmailSender>(); builder.Services.AddSingleton<IEmailSender<ApplicationUser>, IdentityNoOpEmailSender>();
builder.Services.AddHttpContextAccessor();
var app = builder.Build(); var app = builder.Build();
// Configure the HTTP request pipeline. // Configure the HTTP request pipeline.
@@ -54,6 +54,28 @@ else
app.UseStatusCodePagesWithReExecute("/not-found", createScopeForStatusCodePages: true); app.UseStatusCodePagesWithReExecute("/not-found", createScopeForStatusCodePages: true);
app.UseHttpsRedirection(); app.UseHttpsRedirection();
app.Use(async (context, next) =>
{
const string cookieName = "CartToken";
if (!context.Request.Cookies.TryGetValue(cookieName, out var token)
|| !Guid.TryParse(token, out _))
{
token = Guid.NewGuid().ToString();
context.Response.Cookies.Append(cookieName, token, new CookieOptions
{
HttpOnly = true,
Secure = true,
SameSite = SameSiteMode.Lax,
Expires = DateTimeOffset.UtcNow.AddDays(30),
IsEssential = true
});
}
await next();
});
app.UseAntiforgery(); app.UseAntiforgery();
app.MapStaticAssets(); app.MapStaticAssets();