File size: 7,277 Bytes
2489a52
e2e7b3b
 
 
faf67a3
e2e7b3b
faf67a3
 
e2e7b3b
 
 
 
 
 
 
faf67a3
 
 
 
 
 
 
e2e7b3b
faf67a3
 
 
ca52144
 
e2e7b3b
 
 
 
ca52144
e2e7b3b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e09fbc7
 
e2e7b3b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c118131
e2e7b3b
 
 
 
 
 
 
 
e09fbc7
 
 
 
 
 
 
 
 
e2e7b3b
 
 
 
 
 
 
 
 
 
 
374ea48
 
ca52144
374ea48
faf67a3
374ea48
 
faf67a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
374ea48
faf67a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
374ea48
faf67a3
374ea48
 
 
 
 
 
 
 
 
 
 
faf67a3
 
 
 
374ea48
 
 
 
faf67a3
 
374ea48
 
 
 
 
 
faf67a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
374ea48
 
faf67a3
 
ca52144
 
faf67a3
 
374ea48
faf67a3
 
 
374ea48
faf67a3
374ea48
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
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
}