func GetOrdersWithOrderItemStatusOrderPending(w http.ResponseWriter, r *http.Request) {
// Parse URL parameters
params := mux.Vars(r)
clientIDStr := params["clientID"]
// Parse the client ID from the URL parameter
clientID, err := strconv.Atoi(clientIDStr)
if err != nil {
http.Error(w, "Invalid clientID", http.StatusBadRequest)
return
}
// Get distinct orders with the specified client ID and status "OrderPending"
connection := GetDatabase()
defer CloseDatabase(connection)
var orders []Order
result := connection.Joins("JOIN order_items ON orders.id = order_items.order_id").
Where("orders.client_id = ? AND order_items.order_item_status = ?", clientID, "OrderPending").
Select("DISTINCT orders.*").
Find(&orders)
if result.Error != nil {
http.Error(w, "No orders with OrderPending status found", http.StatusNotFound)
return
}
// Create the response structure
var responseOrders []struct {
ID uint `json:"id"`
Status string `json:"status"`
TableNoID uint `json:"tableNoID"`
TotalPrice float64 `json:"totalPrice"`
TableName string `json:"tableNoTableName"`
OrderTime int `json:"orderTime"`
OrderItems []OrderItem `json:"orderItems"`
}
for _, order := range orders {
var orderItems []OrderItem
result := connection.Model(&order).Where("order_items.order_item_status = ?", "OrderPending").Related(&orderItems)
if result.Error != nil {
http.Error(w, result.Error.Error(), http.StatusInternalServerError)
return
}
// Only include orders that have at least one "OrderPending" item
if len(orderItems) > 0 {
responseOrder := struct {
ID uint `json:"id"`
Status string `json:"status"`
TableNoID uint `json:"tableNoID"`
TotalPrice float64 `json:"totalPrice"`
TableName string `json:"tableNoTableName"`
OrderTime int `json:"orderTime"`
OrderItems []OrderItem `json:"orderItems"`
}{
ID: order.ID,
Status: order.Status,
TableNoID: order.TableNoID,
TotalPrice: order.TotalPrice,
TableName: order.TableNoTableName,
OrderTime: order.OrderTime,
OrderItems: orderItems,
}
responseOrders = append(responseOrders, responseOrder)
}
}
// Send the response with distinct orders and their filtered order items
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(responseOrders)
}