Add user auth, cart, checkout and personal account for guests and registered users
This commit is contained in:
@@ -0,0 +1,377 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"html/template"
|
||||
"log"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"shop/internal/auth"
|
||||
"shop/internal/models"
|
||||
"shop/internal/repository"
|
||||
)
|
||||
|
||||
type CustomerHandler struct {
|
||||
products *repository.ProductRepository
|
||||
users *repository.UserRepository
|
||||
cart *repository.CartRepository
|
||||
orders *repository.OrderRepository
|
||||
stats *repository.StatsRepository
|
||||
userSession *auth.Session
|
||||
cartSession *auth.Session
|
||||
templates *template.Template
|
||||
}
|
||||
|
||||
type shopPage struct {
|
||||
Title string
|
||||
User *models.User
|
||||
CartCount int
|
||||
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
|
||||
}
|
||||
|
||||
type accountPage struct {
|
||||
shopPage
|
||||
Orders []models.Order
|
||||
Name string
|
||||
Phone string
|
||||
Address string
|
||||
}
|
||||
|
||||
func NewCustomerHandler(
|
||||
products *repository.ProductRepository,
|
||||
users *repository.UserRepository,
|
||||
cart *repository.CartRepository,
|
||||
orders *repository.OrderRepository,
|
||||
stats *repository.StatsRepository,
|
||||
userSession, cartSession *auth.Session,
|
||||
templates *template.Template,
|
||||
) *CustomerHandler {
|
||||
return &CustomerHandler{
|
||||
products: products, users: users, cart: cart, orders: orders, stats: stats,
|
||||
userSession: userSession, cartSession: cartSession, templates: templates,
|
||||
}
|
||||
}
|
||||
|
||||
func (h *CustomerHandler) render(w http.ResponseWriter, name string, data any) {
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
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}
|
||||
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
|
||||
}
|
||||
}
|
||||
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) 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,
|
||||
}
|
||||
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,
|
||||
}
|
||||
if name == "" || email == "" || phone == "" || address == "" {
|
||||
p.Error = "Заполните все поля доставки"
|
||||
h.render(w, "checkout.html", p)
|
||||
return
|
||||
}
|
||||
|
||||
order := models.Order{
|
||||
GuestName: name, GuestEmail: email, GuestPhone: phone,
|
||||
Address: address, Total: total,
|
||||
}
|
||||
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
|
||||
}
|
||||
_ = 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.Write([]byte(`{"status":"ok"}`))
|
||||
}
|
||||
Reference in New Issue
Block a user