api / cmd /checkout.go
souliyappps's picture
refactor: remove auth requirements and update customer ID handling in orders and checkout
18d64e4
Raw History Blame Contribute Delete
11.7 kB
package cmd
import (
"api/tools"
"errors"
"fmt"
"net/http"
"strings"
"time"
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/core"
"github.com/shopspring/decimal"
)
// Data Models
type CartInfo struct {
CustomerID string `db:"customer_id" json:"customerId"`
CustomerName string `db:"customer_name" json:"customerName"`
PhoneNumber string `db:"phone_number" json:"phoneNumber"`
AddressID string `db:"address_id" json:"addressID"`
Village string `db:"village" json:"village"`
ShippingName string `db:"shipping_name" json:"shippingName"`
Province string `db:"province" json:"province"`
District string `db:"district" json:"district"`
// International address fields
CountryCode string `db:"country_code" json:"countryCode"`
CountryName string `db:"country_name" json:"countryName"`
AddressLine1 string `db:"address_line_1" json:"addressLine1"`
AddressLine2 string `db:"address_line_2" json:"addressLine2"`
City string `db:"city" json:"city"`
StateRegion string `db:"state_region" json:"stateRegion"`
PostalCode string `db:"postal_code" json:"postalCode"`
IsInternational bool `db:"is_international" json:"isInternational"`
ProductID string `db:"product_id" json:"productId"`
ProductName string `db:"product_name" json:"productName"`
PriceLAK decimal.Decimal `db:"price" json:"priceLAK"`
PriceUSD decimal.Decimal `json:"priceUSD"`
PriceTHB decimal.Decimal `json:"priceTHB"`
Quantity int `db:"quantity" json:"quantity"`
}
type CheckoutReq struct {
CartItems []any `json:"cartItems"`
Remark string `json:"remark"`
CustomerID string `json:"customerID"`
}
// Checkout handles the conversion of cart items to an order
func Checkout(e *core.RequestEvent) error {
var req CheckoutReq
if err := e.BindBody(&req); err != nil {
app.Logger().Error("failed to bind request body", "error", err)
return e.JSON(http.StatusBadRequest, "Invalid request format")
}
// Log checkout request details
userID := req.CustomerID
if userID == "" {
userID = "anonymous"
}
clientIP := e.RealIP()
app.Logger().Info("Checkout request initiated",
"user_id", userID,
"client_ip", clientIP,
"cart_items", req.CartItems,
"remark", req.Remark,
)
var orderID string // ⬅ declare outside to capture it
err := app.RunInTransaction(func(txApp core.App) error {
// 1️⃣ Update cart status
if err := updateCartStatus(txApp, req.CartItems); err != nil {
return e.JSON(http.StatusInternalServerError, err.Error())
}
// 2️⃣ Fetch cart details
cartsInfo, err := fetchCartDetails(txApp, req.CartItems)
if err != nil {
return e.JSON(http.StatusInternalServerError, err.Error())
}
if len(cartsInfo) == 0 {
return errors.New("no carts found for the given items")
}
// 2.5️⃣ Validate address information
if err := validateAddress(cartsInfo[0]); err != nil {
return e.JSON(http.StatusBadRequest, "Address validation failed: "+err.Error())
}
// 3️⃣ Create order
orderID, _, err = createOrder(txApp, cartsInfo[0], req.Remark)
if err != nil {
return e.JSON(http.StatusInternalServerError, err.Error())
}
// 4️⃣ Fetch currency rates
currencies, err := fetchCurrencies(txApp)
if err != nil {
return e.JSON(http.StatusInternalServerError, err.Error())
}
// 5️⃣ Insert order items
if err := insertOrderItems(txApp, orderID, cartsInfo, currencies); err != nil {
return e.JSON(http.StatusInternalServerError, err.Error())
}
return nil
})
if err != nil {
app.Logger().Error("Transaction failed", "error", err)
return e.JSON(http.StatusInternalServerError, "Checkout failed")
}
// ✅ Return order_id on success
return e.JSON(http.StatusOK, map[string]any{
"message": "Checkout successful",
"order_id": orderID,
})
}
// updateCartStatus updates the cart status to 'purchased'
func updateCartStatus(txApp core.App, cartIDs []any) error {
result, err := txApp.DB().
Update("carts",
dbx.Params{"status": "purchased"},
dbx.HashExp{"id": cartIDs}).
Execute()
if err != nil {
app.Logger().Error("Failed to update cart status", "error", err)
return fmt.Errorf("failed to update cart status")
}
rows, _ := result.RowsAffected()
if rows == 0 {
return errors.New("no rows affected when creating order")
}
return nil
}
// fetchCartDetails retrieves detailed cart data needed for order creation
func fetchCartDetails(txApp core.App, cartIDs []any) ([]CartInfo, error) {
var carts []CartInfo
err := txApp.DB().
Select(
"c.customer_id", "cust.name as customer_name", "cust.phone_number", "cust.address_id",
"a.village", "a.shipping_name", "pro.name as province", "d.name as district",
"a.country_code", "a.country_name", "a.address_line_1", "a.address_line_2",
"a.city", "a.state_region", "a.postal_code",
"a.is_international",
"c.product_id", "c.quantity", "p.name as product_name", "p.price").
From("carts c").
InnerJoin("products p", dbx.NewExp("p.id = c.product_id")).
InnerJoin("customers cust", dbx.NewExp("cust.id = c.customer_id")).
InnerJoin("addresses a", dbx.NewExp("a.id = cust.address_id")).
LeftJoin("provinces pro", dbx.NewExp("pro.id = a.province_id")).
LeftJoin("districts d", dbx.NewExp("d.id = a.district_id")).
Where(dbx.HashExp{"c.id": cartIDs}).
OrderBy("c.created ASC").
All(&carts)
if err != nil {
app.Logger().Error("Failed to fetch cart info", "error", err)
return nil, fmt.Errorf("failed to fetch cart info")
}
return carts, nil
}
// formatInternationalAddress formats address for international shipping (DHL-compatible)
func formatInternationalAddress(info CartInfo) string {
var parts []string
// Recipient name
if info.ShippingName != "" {
parts = append(parts, info.ShippingName)
}
// Address lines
if info.AddressLine1 != "" {
parts = append(parts, info.AddressLine1)
}
if info.AddressLine2 != "" {
parts = append(parts, info.AddressLine2)
}
// City, State/Region, Postal Code
var locationParts []string
if info.City != "" {
locationParts = append(locationParts, info.City)
}
if info.StateRegion != "" {
locationParts = append(locationParts, info.StateRegion)
}
if info.PostalCode != "" {
locationParts = append(locationParts, info.PostalCode)
}
if len(locationParts) > 0 {
joinedLocation := strings.TrimSpace(strings.Join(locationParts, " "))
if joinedLocation != "" {
parts = append(parts, joinedLocation)
}
}
// Country
if info.CountryName != "" {
parts = append(parts, info.CountryName)
}
return strings.Join(parts, ", ")
}
// validateAddress validates address based on whether it's domestic or international
func validateAddress(info CartInfo) error {
if info.IsInternational {
return validateInternationalAddress(info)
}
return validateDomesticAddress(info)
}
// validateDomesticAddress validates domestic (Laos) address format
func validateDomesticAddress(info CartInfo) error {
if info.Province == "" {
return errors.New("province is required for domestic addresses")
}
if info.District == "" {
return errors.New("district is required for domestic addresses")
}
if info.Village == "" {
return errors.New("village is required for domestic addresses")
}
if info.ShippingName == "" {
return errors.New("shipping name is required")
}
return nil
}
// validateInternationalAddress validates international address format (DHL-compatible)
func validateInternationalAddress(info CartInfo) error {
if info.ShippingName == "" {
return errors.New("recipient name is required for international addresses")
}
if info.AddressLine1 == "" {
return errors.New("address line 1 is required for international addresses")
}
if info.City == "" {
return errors.New("city is required for international addresses")
}
if info.CountryCode == "" {
return errors.New("country code is required for international addresses")
}
if info.CountryName == "" {
return errors.New("country name is required for international addresses")
}
if info.PostalCode == "" {
return errors.New("postal code is required for international addresses")
}
// Validate country code format (ISO 3166-1 alpha-2)
if len(info.CountryCode) != 2 {
return errors.New("country code must be 2 characters (ISO 3166-1 alpha-2)")
}
return nil
}
// createOrder inserts a new order based on cart info and returns the order ID and reference ID
func createOrder(txApp core.App, info CartInfo, remark string) (orderID, referenceID string, err error) {
orderID = tools.GenerateRandomString(10)
referenceID = tools.GenerateRandomString(6)
var addressStr string
if info.IsInternational {
// Format international address (DHL-compatible)
addressStr = formatInternationalAddress(info)
} else {
// Format domestic address (existing format)
addressStr = fmt.Sprintf("%s,%s,%s,%s", info.Province, info.District, info.Village, info.ShippingName)
}
result, err := txApp.DB().
Insert("orders", map[string]any{
"id": orderID,
"customer_id": info.CustomerID,
"customer_name": info.CustomerName,
"phone_number": info.PhoneNumber,
"address_id": info.AddressID,
"address": addressStr,
"status": "pending",
"reference_id": referenceID,
"remark": remark,
"created": time.Now().UTC().Format("2006-01-02 15:04:05"),
"updated": dbx.NewExp("DATETIME('now')"),
}).
Execute()
if err != nil {
app.Logger().Error("Failed to insert order", "error", err)
return "", "", fmt.Errorf("failed to create order")
}
rows, _ := result.RowsAffected()
if rows == 0 {
return "", "", errors.New("no rows affected when creating order")
}
return orderID, referenceID, nil
}
// CurrencyRate holds valuation for conversion
type CurrencyRate struct {
Ccy string `db:"ccy" json:"ccy"`
Type string `db:"type" json:"type"`
Rate decimal.Decimal `db:"rate" json:"rate"`
}
// fetchCurrencies retrieves current SELL currency exchange rates
func fetchCurrencies(txApp core.App) ([]CurrencyRate, error) {
var curr []CurrencyRate
err := txApp.DB().
Select("ccy", "type", "rate").
From("currency").
Where(dbx.HashExp{"type": "SELL"}).
OrderBy("created ASC").
All(&curr)
if err != nil {
app.Logger().Error("Failed to fetch currency rates", "error", err)
return nil, fmt.Errorf("failed to load currency rates")
}
return curr, nil
}
// insertOrderItems inserts all products in carts into the `order_items`
func insertOrderItems(txApp core.App, orderID string, cartsInfo []CartInfo, currencies []CurrencyRate) error {
for _, cart := range cartsInfo {
for _, rate := range currencies {
switch rate.Ccy {
case "USD":
cart.PriceUSD = cart.PriceLAK.Div(rate.Rate).Round(2)
case "THB":
cart.PriceTHB = cart.PriceLAK.Div(rate.Rate).Round(2)
}
}
result, err := txApp.DB().
Insert("order_items", map[string]any{
"order_id": orderID,
"product_id": cart.ProductID,
"quantity": cart.Quantity,
"price_lak": cart.PriceLAK,
"price_usd": cart.PriceUSD,
"price_thb": cart.PriceTHB,
"product_name": cart.ProductName,
"created": time.Now().UTC().Format("2006-01-02 15:04:05"),
"updated": dbx.NewExp("DATETIME('now')"),
}).
Execute()
if err != nil {
app.Logger().Error("Failed to insert order item", "error", err)
return fmt.Errorf("insert order item failed")
}
rows, _ := result.RowsAffected()
if rows == 0 {
return errors.New("no order item row inserted")
}
}
return nil
}