From 760169d7667070d44bf84cf002a9f8c61fa73903 Mon Sep 17 00:00:00 2001 From: ParkSuMin Date: Fri, 21 Feb 2025 22:52:41 +0300 Subject: [PATCH] Almost ready backend of cart --- frontend/style/app/{pay => payment}/pay.go | 135 ++++++++++++++++++ .../urls_pay.db => payment/pay_orders.db} | Bin frontend/style/lib/cartStorage.ts | 24 +++- 3 files changed, 152 insertions(+), 7 deletions(-) rename frontend/style/app/{pay => payment}/pay.go (63%) rename frontend/style/app/{pay/urls_pay.db => payment/pay_orders.db} (100%) diff --git a/frontend/style/app/pay/pay.go b/frontend/style/app/payment/pay.go similarity index 63% rename from frontend/style/app/pay/pay.go rename to frontend/style/app/payment/pay.go index 7f269698..fc62da51 100644 --- a/frontend/style/app/pay/pay.go +++ b/frontend/style/app/payment/pay.go @@ -192,6 +192,83 @@ func checkPayHandler(w http.ResponseWriter, r *http.Request) { w.Write([]byte(response)) } +type CartItem struct { + ID int `json:"id"` + Title string `json:"title"` + Price float64 `json:"price"` + Quantity int `json:"quantity"` +} + +type Cart struct { + CartItems []CartItem `json:"cart_items"` +} + +func add_to_cart(w http.ResponseWriter, r *http.Request) { + + cartCookie, err := r.Cookie("cart") + if err != nil { + http.Error(w, "Cart cookie not found", http.StatusBadRequest) + return + } + fmt.Print("cartCookie.Value: ", cartCookie.Value) + var cart Cart + + // Разбираем JSON + err = json.Unmarshal([]byte(cartCookie.Value), &cart) + if err != nil { + fmt.Println("Ошибка при разборе JSON:", err) + return + } + + del_cookie, err := r.Cookie("uuid") + if err != nil { + http.Error(w, "Не найден cookie с uuid", http.StatusBadRequest) + return + } + total_cookie, err := r.Cookie("total_price") + if err != nil { + http.Error(w, "Не найден cookie с total_price", http.StatusBadRequest) + return + } + + total_price := total_cookie.Value + order_id := del_cookie.Value + + insertSql := `INSERT INTO order_list VALUES (?, ?, ?)` + _, err = db.Exec(insertSql, order_id, total_price, time.Now().Format("2006-01-02 15:04:05")) + if err != nil { + http.Error(w, "Ошибка при сохранении данных в базу данных", http.StatusInternalServerError) + return + } + + for _, item := range cart.CartItems { + + insertSQL := `INSERT INTO order_lines VALUES (?, ?, ?, ?, ?)` + _, err = db.Exec(insertSQL, order_id, item.ID, item.Title, item.Price, item.Quantity) + if err != nil { + http.Error(w, "Ошибка при сохранении данных в базу данных", http.StatusInternalServerError) + return + } + } + + // insertSQL := `DELETE FROM url_pays WHERE uuid = ?` + // _, err = db.Exec(insertSQL, del_cookie.Value) + // if err != nil { + // http.Error(w, "Ошибка при сохранении данных в базу данных", http.StatusInternalServerError) + // return + // } + // // Clear uuid cookie + // del_cookie = &http.Cookie{ + // Name: "uuid", + // Value: "", + // MaxAge: -1, + // } + // http.SetCookie(w, del_cookie) + + // Send success response + w.WriteHeader(http.StatusOK) + w.Write([]byte("OK")) +} func main() { initDB() @@ -206,6 +283,7 @@ func main() { // Register handlers http.HandleFunc("/api/pay", payHandler) http.HandleFunc("/api/check_pay", checkPayHandler) + http.HandleFunc("/api/add_to_cart", add_to_cart) // Start server with CORS middleware port := os.Getenv("PORT") @@ -216,3 +294,60 @@ func main() { fmt.Println("Go-сервер запущен на порту", port) log.Fatal(http.ListenAndServe(":"+port, cors(http.DefaultServeMux))) } + +// package main + +// import ( +// "encoding/json" +// "fmt" +// ) + +// // Subscriber представляет структуру одного подписчика +// type Subscriber struct { +// Email string `json:"email"` +// Name string `json:"name"` +// Phone string `json:"phone"` +// } + +// // Subscribers представляет структуру всего JSON-объекта +// type Subscribers struct { +// Subscribers []Subscriber `json:"subscribers"` +// } + +// func main() { +// // Пример JSON-данных +// jsonData := `{ +// "subscribers" : [ +// { +// "email" : "somemail@gmail.com", +// "name" : "Maksim", +// "phone" : "80-77-524-2432" +// }, +// { +// "email" : "someAnotherMail@gmail.com", +// "name" : "Sasha", +// "phone" : "" +// }, +// { +// "email" : "someAnotherMail_1@gmail.com", +// "name" : "NoName", +// "phone" : "" +// } +// ] +// }` + +// // Создаем переменную для хранения разобранных данных +// var subscribers Subscribers + +// // Разбираем JSON +// err := json.Unmarshal([]byte(jsonData), &subscribers) +// if err != nil { +// fmt.Println("Ошибка при разборе JSON:", err) +// return +// } + +// // Выводим данные +// for _, subscriber := range subscribers.Subscribers { +// fmt.Printf("Email: %s, Name: %s, Phone: %s\n", subscriber.Email, subscriber.Name, subscriber.Phone) +// } +// } diff --git a/frontend/style/app/pay/urls_pay.db b/frontend/style/app/payment/pay_orders.db similarity index 100% rename from frontend/style/app/pay/urls_pay.db rename to frontend/style/app/payment/pay_orders.db diff --git a/frontend/style/lib/cartStorage.ts b/frontend/style/lib/cartStorage.ts index dacdc475..08df0fb7 100644 --- a/frontend/style/lib/cartStorage.ts +++ b/frontend/style/lib/cartStorage.ts @@ -7,21 +7,31 @@ export interface CartItem { quantity: number; } -// Сохранить корзину в cookies +interface Cart { + cart_items: CartItem[]; +} + +// Save cart to cookies export const saveCart = (cartItems: CartItem[]): void => { - const cartData = JSON.stringify(cartItems); - Cookies.set('cart', cartData, { expires: 7 }); // Срок хранения cookies 7 дней + const cart: Cart = { + cart_items: cartItems + }; + const cartData = JSON.stringify(cart); + Cookies.set('cart', cartData, { expires: 7 }); }; -// Получить корзину из cookies +// Get cart from cookies export const getCart = (): CartItem[] => { const cartData = Cookies.get('cart'); - return cartData ? JSON.parse(cartData) : []; // Возвращаем пустой массив, если корзина не найдена + if (!cartData) return []; + + const cart: Cart = JSON.parse(cartData); + return cart.cart_items; }; -// Очистить корзину в cookies +// Clear cart in cookies export const clearCart = (): void => { - Cookies.remove('cart'); // Удаляем cookies с данными корзины + Cookies.remove('cart'); };