Spaces:
Running
Running
Download cmd/orders.go from miss-clean-spa/api: direct link, hf CLI and curl.
- Browser
- Download file 7.28 kB
-
https://huggingface.co/spaces/miss-clean-spa/api/resolve/main/cmd/orders.go
- Command line
-
hf download hf://spaces/miss-clean-spa/api/cmd/orders.go
-
curl -L -o orders.go https://huggingface.co/spaces/miss-clean-spa/api/resolve/main/cmd/orders.go
7.28 kB
| package cmd | |
| import ( | |
| "fmt" | |
| "math" | |
| "net/http" | |
| "strconv" | |
| "time" | |
| "github.com/pocketbase/dbx" | |
| "github.com/pocketbase/pocketbase/core" | |
| ) | |
| type OrderStatus string | |
| const ( | |
| MaxOrderLimit = 100 | |
| DefaultOrderLimit = 10 | |
| DateFormat = "2006-01-02" | |
| DateTimeFormat = "2006-01-02 15:04:05.000Z" | |
| ) | |
| var ( | |
| OrderStatusPending OrderStatus = "pending" | |
| OrderStatusPurchased OrderStatus = "purchased" | |
| OrderStatusCancel OrderStatus = "cancel" | |
| OrderStatusDelivering OrderStatus = "delivering" | |
| OrderStatusCompleted OrderStatus = "completed" | |
| ) | |
| func (s *OrderStatus) UnmarshalText(text []byte) error { | |
| switch status := string(text); status { | |
| case string(OrderStatusPending), string(OrderStatusPurchased), string(OrderStatusCancel), string(OrderStatusDelivering), string(OrderStatusCompleted): | |
| *s = OrderStatus(status) | |
| return nil | |
| default: | |
| return fmt.Errorf("invalid order status: %s", status) | |
| } | |
| } | |
| type Order struct { | |
| Id string `db:"id" json:"id"` | |
| ReferenceID string `db:"reference_id" json:"referenceID"` | |
| CustomerID string `db:"customer_id" json:"customerID"` | |
| CustomerName string `db:"customer_name" json:"customerName"` | |
| PhoneNumber string `db:"phone_number" json:"phoneNumber"` | |
| Address string `db:"address" json:"address"` | |
| Status string `db:"status" json:"status"` | |
| Qty *int `db:"quantity" json:"quantity"` | |
| PriceLAK *string `db:"price_lak" json:"amountLAK"` | |
| PriceTHB *string `db:"price_thb" json:"amountTHB"` | |
| PriceUSD *string `db:"price_usd" json:"amountUSD"` | |
| Created string `db:"created" json:"created"` | |
| Updated string `db:"updated" json:"updated"` | |
| } | |
| func ListOrders(e *core.RequestEvent) error { | |
| statusParam := e.Request.URL.Query().Get("status") | |
| query := app.DB(). | |
| Select( | |
| "o.id AS id", | |
| "o.reference_id", | |
| "o.customer_id", | |
| "o.customer_name", | |
| "o.phone_number", | |
| "o.address", | |
| "o.status", | |
| "o.created", | |
| "o.updated", | |
| "SUM(item.quantity) AS quantity", | |
| "SUM(item.price_lak) AS price_lak", | |
| "SUM(item.price_thb) AS price_thb", | |
| "SUM(item.price_usd) AS price_usd", | |
| ). | |
| From("orders o"). | |
| LeftJoin("order_items item", dbx.NewExp("item.order_id = o.id")). | |
| OrderBy("o.created DESC"). | |
| GroupBy("o.id") | |
| subquery := app.DB(). | |
| Select( | |
| "count(*)", | |
| ). | |
| From("orders") | |
| if statusParam != "" { | |
| var status OrderStatus | |
| if err := status.UnmarshalText([]byte(statusParam)); err != nil { | |
| return e.BadRequestError("Invalid status parameter", err) | |
| } | |
| query = query.Where(dbx.NewExp("o.status = {:status}", dbx.Params{"status": string(status)})) | |
| subquery = subquery.Where(dbx.NewExp("status = {:status}", dbx.Params{"status": string(status)})) | |
| } | |
| searchProvider := NewProvider().Query(query).SubQuery(subquery) | |
| records := make([]Order, 0) | |
| result, err := searchProvider.ParseAndExec(e.Request.URL.Query().Encode(), records) | |
| if err != nil { | |
| return fmt.Errorf("ParseAndExec failed: %w", err) | |
| } | |
| return e.JSON(http.StatusOK, result) | |
| } | |
| func ListOrdersByCustID(e *core.RequestEvent) error { | |
| custId := e.Auth.Id | |
| if custId == "" { | |
| return e.JSON(http.StatusUnauthorized, "unauthorized") | |
| } | |
| filters, err := parseOrderFilters(e) | |
| if err != nil { | |
| return e.BadRequestError("Invalid request parameters", err) | |
| } | |
| query, subquery := buildOrderQuery(custId, filters) | |
| searchProvider := NewProvider().Query(query).SubQuery(subquery) | |
| records := make([]Order, 0) | |
| result, err := searchProvider.ParseAndExec(e.Request.URL.Query().Encode(), records) | |
| if err != nil { | |
| return fmt.Errorf("failed to fetch orders: %w", err) | |
| } | |
| return e.JSON(http.StatusOK, result) | |
| } | |
| type OrderFilters struct { | |
| Status OrderStatus | |
| CreatedAt time.Time | |
| Limit int | |
| } | |
| func parseOrderFilters(e *core.RequestEvent) (*OrderFilters, error) { | |
| filters := &OrderFilters{} | |
| statusParam := e.Request.URL.Query().Get("status") | |
| if statusParam != "" { | |
| if err := filters.Status.UnmarshalText([]byte(statusParam)); err != nil { | |
| return nil, fmt.Errorf("invalid status parameter: %w", err) | |
| } | |
| } | |
| createdParamStr := e.Request.URL.Query().Get("createdAt") | |
| if createdParamStr != "" { | |
| createdParam, err := time.Parse(DateFormat, createdParamStr) | |
| if err != nil { | |
| createdParam, err = time.Parse(DateTimeFormat, createdParamStr) | |
| if err != nil { | |
| return nil, fmt.Errorf("invalid createdAt parameter format. Expected YYYY-MM-DD or YYYY-MM-DD HH:MM:SS.sssZ: %w", err) | |
| } | |
| } | |
| filters.CreatedAt = createdParam | |
| } | |
| limitParam := e.Request.URL.Query().Get("limit") | |
| if limitParam != "" { | |
| filters.Limit = parseIntOrDefault(limitParam, DefaultOrderLimit) | |
| if filters.Limit > MaxOrderLimit { | |
| filters.Limit = MaxOrderLimit | |
| } | |
| } | |
| return filters, nil | |
| } | |
| func buildOrderQuery(custId string, filters *OrderFilters) (*dbx.SelectQuery, *dbx.SelectQuery) { | |
| query := app.DB(). | |
| Select( | |
| "o.id AS id", | |
| "o.reference_id", | |
| "o.customer_id", | |
| "o.customer_name", | |
| "o.phone_number", | |
| "o.address", | |
| "o.status", | |
| "o.created", | |
| "o.updated", | |
| "COALESCE(SUM(item.quantity), 0) AS quantity", | |
| "COALESCE(SUM(item.quantity * item.price_lak), 0) AS price_lak", | |
| "COALESCE(SUM(item.quantity * item.price_thb), 0) AS price_thb", | |
| "COALESCE(SUM(item.quantity * item.price_usd), 0) AS price_usd", | |
| ). | |
| From("orders o"). | |
| LeftJoin("order_items item", dbx.NewExp("item.order_id = o.id")). | |
| Where(dbx.NewExp("o.customer_id = {:custId}", dbx.Params{"custId": custId})). | |
| GroupBy("o.id", "o.reference_id", "o.customer_id", "o.customer_name", "o.phone_number", "o.address", "o.status", "o.created", "o.updated"). | |
| OrderBy("o.created DESC") | |
| subquery := app.DB(). | |
| Select("count(*)"). | |
| From("orders"). | |
| Where(dbx.NewExp("customer_id = {:custId}", dbx.Params{"custId": custId})) | |
| hasStatus := filters.Status != "" | |
| hasCreated := !filters.CreatedAt.IsZero() | |
| createdParam := filters.CreatedAt.Format(DateFormat) | |
| if hasStatus && hasCreated { | |
| query = query.Where(dbx.NewExp("DATE(o.created) = {:created} AND o.status = {:status} AND customer_id = {:custId}", | |
| dbx.Params{"created": createdParam, "status": string(filters.Status), "custId": custId})) | |
| subquery = subquery.Where(dbx.NewExp("DATE(created) = {:created} AND status = {:status} AND customer_id = {:custId}", | |
| dbx.Params{"created": createdParam, "status": string(filters.Status), "custId": custId})) | |
| } else if hasStatus { | |
| query = query.Where(dbx.NewExp("o.status = {:status} AND customer_id = {:custId}", | |
| dbx.Params{"status": string(filters.Status), "custId": custId})) | |
| subquery = subquery.Where(dbx.NewExp("status = {:status} AND customer_id = {:custId}", | |
| dbx.Params{"status": string(filters.Status), "custId": custId})) | |
| } else if hasCreated { | |
| query = query.Where(dbx.NewExp("DATE(o.created) = {:created} AND customer_id = {:custId}", | |
| dbx.Params{"created": createdParam, "custId": custId})) | |
| subquery = subquery.Where(dbx.NewExp("DATE(created) = {:created} AND customer_id = {:custId}", | |
| dbx.Params{"created": createdParam, "custId": custId})) | |
| } | |
| if filters.Limit > 0 { | |
| query = query.Limit(int64(math.Min(float64(filters.Limit), MaxOrderLimit))) | |
| } | |
| return query, subquery | |
| } | |
| func parseIntOrDefault(s string, defaultValue int) int { | |
| if val, err := strconv.Atoi(s); err == nil { | |
| return val | |
| } | |
| return defaultValue | |
| } | |