package handlers import ( "fmt" "html/template" "log" "net/http" "strconv" "shop/internal/auth" "shop/internal/compare" "shop/internal/heleket" "shop/internal/models" "shop/internal/repository" "shop/internal/version" ) type CustomerHandler struct { products *repository.ProductRepository categories *repository.CategoryRepository users *repository.UserRepository cart *repository.CartRepository orders *repository.OrderRepository priceHistory *repository.PriceHistoryRepository reservations *repository.ReservationRepository stats *repository.StatsRepository userSession *auth.Session cartSession *auth.Session compareSession *auth.Session heleket *heleket.Client heleketAPIKey string publicBaseURL string heleketCurrency string templates *template.Template } type shopPage struct { Title string User *models.User CartCount int CompareCount int Version string Products interface{} Categories interface{} Error string Success string } type cartPage struct { shopPage Items []models.CartItem Total float64 } type checkoutPage struct { shopPage Items []models.CartItem Total float64 Name string Email string Phone string Address string HeleketEnabled bool } type accountPage struct { shopPage Orders []models.Order Name string Phone string Address string } type productPage struct { shopPage Product models.Product PriceHistory []models.PriceHistoryEntry MaxHistoryPrice float64 Reservation *models.Reservation ReservedByOther bool CompareProducts []models.Product CompareCount int Success string Error string } type comparePage struct { shopPage Products []models.Product } type categoryPage struct { shopPage Category models.Category Products []models.Product } func NewCustomerHandler( products *repository.ProductRepository, categories *repository.CategoryRepository, users *repository.UserRepository, cart *repository.CartRepository, orders *repository.OrderRepository, priceHistory *repository.PriceHistoryRepository, reservations *repository.ReservationRepository, stats *repository.StatsRepository, userSession, cartSession, compareSession *auth.Session, heleketClient *heleket.Client, heleketAPIKey, publicBaseURL, heleketCurrency string, templates *template.Template, ) *CustomerHandler { return &CustomerHandler{ products: products, categories: categories, users: users, cart: cart, orders: orders, priceHistory: priceHistory, reservations: reservations, stats: stats, userSession: userSession, cartSession: cartSession, compareSession: compareSession, heleket: heleketClient, heleketAPIKey: heleketAPIKey, publicBaseURL: publicBaseURL, heleketCurrency: heleketCurrency, templates: templates, } } func (h *CustomerHandler) render(w http.ResponseWriter, name string, data any) { w.Header().Set("Content-Type", "text/html; charset=utf-8") w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate") if err := h.templates.ExecuteTemplate(w, name, data); err != nil { log.Printf("render %s: %v", name, err) } } func (h *CustomerHandler) basePage(r *http.Request, w http.ResponseWriter, title string) shopPage { p := shopPage{Title: title, Version: version.Version} if uid, ok := auth.UserIDFromSession(h.userSession, r); ok { if u, err := h.users.GetByID(r.Context(), uid); err == nil { p.User = &u } } cartID, _ := h.resolveCart(r, w) if cartID > 0 { if n, err := h.cart.ItemCount(r.Context(), cartID); err == nil { p.CartCount = n } } p.CompareCount = h.compareCount(r) return p } func (h *CustomerHandler) resolveCart(r *http.Request, w http.ResponseWriter) (int, error) { ctx := r.Context() sessionKey := h.cartSession.EnsureKey(w, r) var userID *int if uid, ok := auth.UserIDFromSession(h.userSession, r); ok { userID = &uid } return h.cart.GetOrCreate(ctx, sessionKey, userID) } func (h *CustomerHandler) Home(w http.ResponseWriter, r *http.Request) { ctx := r.Context() _ = h.stats.IncrementHomeVisit(ctx) products, _ := h.products.Featured(ctx, 8) categories, _ := h.products.Categories(ctx) p := h.basePage(r, w, "Shop — Интернет-магазин") p.Products = products p.Categories = categories h.render(w, "home.html", p) } func (h *CustomerHandler) ProductPage(w http.ResponseWriter, r *http.Request) { id, err := strconv.Atoi(r.PathValue("id")) if err != nil { http.NotFound(w, r) return } ctx := r.Context() product, err := h.products.GetActiveByID(ctx, id) if err != nil { http.NotFound(w, r) return } p := productPage{ shopPage: h.basePage(r, w, product.Name), Product: product, } p.PriceHistory, _ = h.priceHistory.ByProduct(ctx, id, 12) for _, e := range p.PriceHistory { if e.Price > p.MaxHistoryPrice { p.MaxHistoryPrice = e.Price } } sessionKey := h.cartSession.EnsureKey(w, r) if res, err := h.reservations.ActiveByProduct(ctx, id); err == nil { p.Reservation = res if res.SessionKey != sessionKey { var uid int if u, ok := auth.UserIDFromSession(h.userSession, r); ok { uid = u } if res.UserID == nil || uid == 0 || *res.UserID != uid { p.ReservedByOther = true } } } compareRaw, _ := h.compareSession.FromRequest(r) compareIDs := compare.Parse(compareRaw) p.CompareCount = len(compareIDs) var others []models.Product if product.CategoryID != nil { others, _ = h.products.ByCategoryID(ctx, *product.CategoryID) } else { others, _ = h.products.Featured(ctx, 50) } for _, o := range others { if o.ID != id { p.CompareProducts = append(p.CompareProducts, o) } } switch r.URL.Query().Get("ok") { case "reserve": p.Success = "Товар забронирован на 24 часа" case "compare": p.Success = "Товар добавлен к сравнению" } if r.URL.Query().Get("err") == "reserved" { p.Error = "Товар уже забронирован другим покупателем" } h.render(w, "product.html", p) } func (h *CustomerHandler) CategoryPage(w http.ResponseWriter, r *http.Request) { slug := r.PathValue("slug") cat, err := h.categories.GetBySlug(r.Context(), slug) if err != nil { http.NotFound(w, r) return } products, _ := h.products.ByCategoryID(r.Context(), cat.ID) p := categoryPage{ shopPage: h.basePage(r, w, cat.Name), Category: cat, Products: products, } h.render(w, "category.html", p) } func (h *CustomerHandler) RegisterPage(w http.ResponseWriter, r *http.Request) { if _, ok := auth.UserIDFromSession(h.userSession, r); ok { http.Redirect(w, r, "/account", http.StatusSeeOther) return } h.render(w, "register.html", h.basePage(r, w, "Регистрация")) } func (h *CustomerHandler) Register(w http.ResponseWriter, r *http.Request) { if err := r.ParseForm(); err != nil { http.Error(w, "Bad Request", http.StatusBadRequest) return } ctx := r.Context() email := r.FormValue("email") password := r.FormValue("password") name := r.FormValue("name") p := h.basePage(r, w, "Регистрация") if email == "" || password == "" || name == "" { p.Error = "Заполните все поля" h.render(w, "register.html", p) return } if len(password) < 6 { p.Error = "Пароль минимум 6 символов" h.render(w, "register.html", p) return } exists, _ := h.users.EmailExists(ctx, email) if exists { p.Error = "Email уже зарегистрирован" h.render(w, "register.html", p) return } u, err := h.users.Create(ctx, email, password, name) if err != nil { log.Printf("register: %v", err) p.Error = "Ошибка регистрации" h.render(w, "register.html", p) return } sessionKey := h.cartSession.EnsureKey(w, r) _ = h.cart.MergeToUser(ctx, sessionKey, u.ID) _ = auth.SetUserSession(h.userSession, w, r, u.ID) http.Redirect(w, r, "/account", http.StatusSeeOther) } func (h *CustomerHandler) LoginPage(w http.ResponseWriter, r *http.Request) { if _, ok := auth.UserIDFromSession(h.userSession, r); ok { http.Redirect(w, r, "/account", http.StatusSeeOther) return } h.render(w, "login.html", h.basePage(r, w, "Вход")) } func (h *CustomerHandler) Login(w http.ResponseWriter, r *http.Request) { if err := r.ParseForm(); err != nil { http.Error(w, "Bad Request", http.StatusBadRequest) return } ctx := r.Context() u, err := h.users.Authenticate(ctx, r.FormValue("email"), r.FormValue("password")) p := h.basePage(r, w, "Вход") if err != nil { p.Error = "Неверный email или пароль" h.render(w, "login.html", p) return } sessionKey := h.cartSession.EnsureKey(w, r) _ = h.cart.MergeToUser(ctx, sessionKey, u.ID) _ = auth.SetUserSession(h.userSession, w, r, u.ID) http.Redirect(w, r, "/account", http.StatusSeeOther) } func (h *CustomerHandler) Logout(w http.ResponseWriter, r *http.Request) { h.userSession.ClearCookie(w, r) http.Redirect(w, r, "/", http.StatusSeeOther) } func (h *CustomerHandler) CartAdd(w http.ResponseWriter, r *http.Request) { if err := r.ParseForm(); err != nil { http.Error(w, "Bad Request", http.StatusBadRequest) return } productID, _ := strconv.Atoi(r.FormValue("product_id")) qty, _ := strconv.Atoi(r.FormValue("quantity")) if qty < 1 { qty = 1 } if productID <= 0 { http.Redirect(w, r, "/", http.StatusSeeOther) return } cartID, err := h.resolveCart(r, w) if err == nil { _ = h.cart.AddItem(r.Context(), cartID, productID, qty) } http.Redirect(w, r, "/cart", http.StatusSeeOther) } func (h *CustomerHandler) CartPage(w http.ResponseWriter, r *http.Request) { cartID, err := h.resolveCart(r, w) p := cartPage{shopPage: h.basePage(r, w, "Корзина")} if err != nil || cartID == 0 { h.render(w, "cart.html", p) return } ctx := r.Context() p.Items, _ = h.cart.Items(ctx, cartID) p.Total, _ = h.cart.Total(ctx, cartID) h.render(w, "cart.html", p) } func (h *CustomerHandler) CartUpdate(w http.ResponseWriter, r *http.Request) { if err := r.ParseForm(); err != nil { http.Error(w, "Bad Request", http.StatusBadRequest) return } productID, _ := strconv.Atoi(r.FormValue("product_id")) qty, _ := strconv.Atoi(r.FormValue("quantity")) cartID, _ := h.resolveCart(r, w) if cartID > 0 { _ = h.cart.UpdateItem(r.Context(), cartID, productID, qty) } http.Redirect(w, r, "/cart", http.StatusSeeOther) } func (h *CustomerHandler) CartRemove(w http.ResponseWriter, r *http.Request) { if err := r.ParseForm(); err != nil { http.Error(w, "Bad Request", http.StatusBadRequest) return } productID, _ := strconv.Atoi(r.FormValue("product_id")) cartID, _ := h.resolveCart(r, w) if cartID > 0 { _ = h.cart.RemoveItem(r.Context(), cartID, productID) } http.Redirect(w, r, "/cart", http.StatusSeeOther) } func (h *CustomerHandler) CheckoutPage(w http.ResponseWriter, r *http.Request) { cartID, _ := h.resolveCart(r, w) ctx := r.Context() items, _ := h.cart.Items(ctx, cartID) if len(items) == 0 { http.Redirect(w, r, "/cart", http.StatusSeeOther) return } total, _ := h.cart.Total(ctx, cartID) p := checkoutPage{ shopPage: h.basePage(r, w, "Оформление заказа"), Items: items, Total: total, HeleketEnabled: h.heleket.Enabled(), } if p.User != nil { p.Name = p.User.Name p.Email = p.User.Email p.Phone = p.User.Phone p.Address = p.User.Address } h.render(w, "checkout.html", p) } func (h *CustomerHandler) Checkout(w http.ResponseWriter, r *http.Request) { if err := r.ParseForm(); err != nil { http.Error(w, "Bad Request", http.StatusBadRequest) return } ctx := r.Context() cartID, _ := h.resolveCart(r, w) items, _ := h.cart.Items(ctx, cartID) if len(items) == 0 { http.Redirect(w, r, "/cart", http.StatusSeeOther) return } total, _ := h.cart.Total(ctx, cartID) name := r.FormValue("name") email := r.FormValue("email") phone := r.FormValue("phone") address := r.FormValue("address") p := checkoutPage{ shopPage: h.basePage(r, w, "Оформление заказа"), Items: items, Total: total, Name: name, Email: email, Phone: phone, Address: address, HeleketEnabled: h.heleket.Enabled(), } if name == "" || email == "" || phone == "" || address == "" { p.Error = "Заполните все поля доставки" h.render(w, "checkout.html", p) return } paymentMethod := r.FormValue("payment_method") if paymentMethod != "heleket" { paymentMethod = "cod" } if paymentMethod == "heleket" && !h.heleket.Enabled() { p.Error = "Онлайн-оплата временно недоступна" h.render(w, "checkout.html", p) return } order := models.Order{ GuestName: name, GuestEmail: email, GuestPhone: phone, Address: address, Total: total, PaymentMethod: paymentMethod, } if paymentMethod == "heleket" { order.Status = "unpaid" } if uid, ok := auth.UserIDFromSession(h.userSession, r); ok { order.UserID = &uid _ = h.users.UpdateProfile(ctx, &models.User{ID: uid, Name: name, Phone: phone, Address: address}) } if err := h.orders.Create(ctx, &order, items); err != nil { log.Printf("checkout: %v", err) p.Error = "Ошибка оформления заказа" h.render(w, "checkout.html", p) return } if paymentMethod == "heleket" { externalID := heleket.OrderExternalID(order.ID) base := h.publicBaseURL if base == "" { base = "http://" + r.Host } invoice, err := h.heleket.CreateInvoice(ctx, heleket.InvoiceRequest{ Amount: heleket.FormatAmount(total), Currency: h.heleketCurrency, OrderID: externalID, URLReturn: base + "/cart", URLSuccess: base + "/order/" + strconv.Itoa(order.ID) + "/success", URLCallback: base + "/webhooks/heleket", PayerEmail: email, Lifetime: 3600, AdditionalData: "order:" + strconv.Itoa(order.ID), }) if err != nil { log.Printf("heleket invoice: %v", err) p.Error = "Заказ #" + strconv.Itoa(order.ID) + " создан, но счёт не выдан. Попробуйте оплатить из личного кабинета." h.render(w, "checkout.html", p) return } _ = h.orders.UpdateHeleketPayment(ctx, order.ID, invoice.UUID, externalID, invoice.URL, invoice.PaymentStatus) _ = h.cart.Clear(ctx, cartID) http.Redirect(w, r, invoice.URL, http.StatusSeeOther) return } _ = h.cart.Clear(ctx, cartID) success := h.basePage(r, w, "Заказ оформлен") success.Success = "Заказ #" + strconv.Itoa(order.ID) + " успешно создан!" h.render(w, "order_success.html", success) } func (h *CustomerHandler) Account(w http.ResponseWriter, r *http.Request) { uid, ok := auth.UserIDFromSession(h.userSession, r) if !ok { http.Redirect(w, r, "/login", http.StatusSeeOther) return } ctx := r.Context() u, err := h.users.GetByID(ctx, uid) if err != nil { http.Redirect(w, r, "/login", http.StatusSeeOther) return } if r.Method == http.MethodPost { _ = r.ParseForm() u.Name = r.FormValue("name") u.Phone = r.FormValue("phone") u.Address = r.FormValue("address") _ = h.users.UpdateProfile(ctx, &u) } orders, _ := h.orders.ByUser(ctx, uid) p := accountPage{ shopPage: h.basePage(r, w, "Личный кабинет"), Orders: orders, Name: u.Name, Phone: u.Phone, Address: u.Address, } p.User = &u if r.Method == http.MethodPost { p.Success = "Профиль сохранён" } h.render(w, "account.html", p) } func (h *CustomerHandler) Health(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") w.Header().Set("Cache-Control", "no-store") fmt.Fprintf(w, `{"status":"ok","version":%q}`, version.Version) }