File size: 7,519 Bytes
2489a52
 
 
49b9550
b0af541
b71f990
c854a4a
2489a52
 
 
 
 
 
 
49b9550
2489a52
 
71d6ca6
2489a52
 
 
 
 
 
 
 
 
 
 
 
7000831
 
4f88458
7000831
 
 
 
c118131
7000831
 
b71f990
7000831
b71f990
 
2489a52
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3f1ce87
49b9550
2489a52
 
 
 
 
 
 
 
49b9550
2489a52
 
 
 
 
18d64e4
2489a52
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3f1ce87
 
 
 
 
 
 
 
 
 
 
 
 
 
18d64e4
3f1ce87
ca52144
b0af541
374ea48
3f1ce87
f5fc317
3f1ce87
 
b0af541
58d7f81
304a735
1937883
2489a52
49b9550
c854a4a
 
 
 
f398a45
c854a4a
49b9550
c854a4a
 
 
49b9550
 
 
 
 
 
18d64e4
49b9550
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18d64e4
49b9550
 
 
18d64e4
49b9550
2489a52
 
 
9fc64fd
 
 
 
 
 
 
 
 
 
2489a52
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c118131
2489a52
 
 
 
 
c118131
2489a52
 
 
 
c118131
2489a52
 
 
 
c118131
 
2489a52
 
 
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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
package cmd

import (
	"api/internal/chatbot"
	"api/internal/dashboard"
	"api/migrations"
	"os"
	"strings"

	"github.com/pocketbase/dbx"
	"github.com/pocketbase/pocketbase"
	"github.com/pocketbase/pocketbase/apis"
	"github.com/pocketbase/pocketbase/core"
	"github.com/pocketbase/pocketbase/tools/hook"
	"github.com/redis/go-redis/v9"
)

var app *pocketbase.PocketBase

func Start() error {
	app = pocketbase.New()
	if _, err := Execute(app); err != nil {
		return err
	}
	return nil
}

func Execute(app *pocketbase.PocketBase) (*pocketbase.PocketBase, error) {
	app.RootCmd.Root()

	// Use a flag to ensure migration runs only once
	var migrationRun bool

	// Run migration on serve when DB is definitely ready
	app.OnServe().BindFunc(func(se *core.ServeEvent) error {
		if !migrationRun {
			if err := migrations.FixVerifiedFieldRequired(se.App); err != nil {
				se.App.Logger().Error("Migration failed", "error", err)
			}
			migrationRun = true
		}
		return se.Next()
	})

	app.OnServe().BindFunc(func(se *core.ServeEvent) error {
		// attach global middleware
		se.Router.BindFunc(func(e *core.RequestEvent) error {
			println(0)
			return e.Next()
		}).Bind(apis.SkipSuccessActivityLog())

		sub := se.Router.Group("/sub")

		// attach group middleware
		sub.BindFunc(func(e *core.RequestEvent) error {
			println(1)
			return e.Next()
		})

		// attach group middleware with an id and custom priority
		sub.Bind(&hook.Handler[*core.RequestEvent]{
			Id: "something",
			Func: func(e *core.RequestEvent) error {
				println(2)
				return e.Next()
			},
			Priority: -1,
		})

		// attach middleware to a single route
		//
		// "GET /sub/hello" should print the sequence: 2,0,1,3,4
		sub.GET("/hello", func(e *core.RequestEvent) error {
			println(4)
			return e.String(200, "Hello!")
		}).BindFunc(func(e *core.RequestEvent) error {
			println(3)
			return e.Next()
		}).Unbind("something")

		se.Router.POST("/cust/auth/phone-login", func(e *core.RequestEvent) error {
			println("=> start this")
			data := struct {
				Phone    string `json:"phone" form:"phone"`
				Password string `json:"password" form:"password"`
			}{}
			if err := e.BindBody(&data); err != nil {
				return e.BadRequestError("Failed to read request data", err)
			}

			println("=> pass")
			record, err := e.App.FindFirstRecordByData("customers", "phone_number", data.Phone)
			if err != nil || !record.ValidatePassword(data.Password) {
				return e.BadRequestError("Invalid credentials", err)
			}

			return apis.RecordAuthResponse(e, record, "phone", map[string]any{"token_duration": 315360000})
		})

		se.Router.PUT("/order-status", func(e *core.RequestEvent) error {
			data := struct {
				OrderID string      `json:"orderId"`
				Status  OrderStatus `json:"status"`
			}{}

			if err := e.BindBody(&data); err != nil {
				return e.BadRequestError("Failed to read request data", err)
			}

			_, err := app.DB().
				Update(
					"orders",
					dbx.Params{"status": data.Status},
					dbx.NewExp("LOWER([[id]])={:id}", dbx.Params{"id": strings.ToLower(data.OrderID)}),
				).
				Execute()
			if err != nil {
				return apis.NewInternalServerError("Failed to retrieve order data", err) // More specific error message
			}

			return e.JSON(200, map[string]string{"status": "success"})
		})

		se.Router.POST("/auth/phone-login", func(e *core.RequestEvent) error {
			data := struct {
				Phone    string `json:"phone" form:"phone"`
				Password string `json:"password" form:"password"`
			}{}
			if err := e.BindBody(&data); err != nil {
				return e.BadRequestError("Failed to read request data", err)
			}

			record, err := e.App.FindFirstRecordByData("users", "phone_number", data.Phone)
			if err != nil || !record.ValidatePassword(data.Password) {
				return e.BadRequestError("Invalid credentials", err)
			}

			return apis.RecordAuthResponse(e, record, "phone", map[string]any{"token_duration": 315360000})
		})
		customer := se.Router.Group("/cust").Bind(apis.RequireAuth("customers"))
		customer.POST("/checkout", Checkout)
		customer.GET("/order-list", ListOrdersByCustID)

		bo := se.Router.Group("").Bind(apis.RequireAuth("users"))
		bo.GET("/order-list", ListOrders)

		dashboard := dashboard.NewDashboardService(app)

		bo.GET("/dashboard/status-count", dashboard.StatusCount)
		bo.GET("/dashboard/sell-revenue", dashboard.SellRevenue)

		// Initialize Redis client for chatbot
		redisAddr := os.Getenv("REDIS_ADDR")
		if redisAddr == "" {
			redisAddr = "localhost:6379"
		}

		redisPassword := os.Getenv("REDIS_PASSWORD")
		redisClient := redis.NewClient(&redis.Options{
			Addr:     redisAddr,
			Password: redisPassword,
			DB:       0,
		})

		// Initialize chatbot service
		chatbotService := chatbot.NewChatbotService(app, redisClient)

		// Chatbot endpoints
		chatbotGroup := se.Router.Group("/chatbot")
		chatbotGroup.POST("/message", func(e *core.RequestEvent) error {
			data := struct {
				Message string `json:"message"`
			}{}

			if err := e.BindBody(&data); err != nil {
				return e.BadRequestError("Failed to read request data", err)
			}

			user := e.Auth
			response, err := chatbotService.ProcessMessage(e.Request.Context(), user.Id, data.Message)
			if err != nil {
				return e.InternalServerError("Failed to process message", err)
			}

			return e.JSON(200, response)
		})

		// WebSocket endpoint for real-time chat
		se.Router.GET("/chatbot/ws", func(e *core.RequestEvent) error {
			// Set user in request context for WebSocket handler
			ctx := e.Request.Context()
			// ctx = context.WithValue(ctx, "user", e.Auth)
			e.Request = e.Request.WithContext(ctx)

			return chatbotService.HandleWebSocket(e.Response, e.Request)
		})

		return se.Next()
	})

	app.OnRecordCreateRequest("customers").BindFunc(func(e *core.RecordRequestEvent) error {
		// Always set verified to false for new customers
		e.Record.Set("verified", false)
		return e.Next()
	})

	app.OnRecordCreateRequest("users").BindFunc(func(e *core.RecordRequestEvent) error {
		e.Record.Set("verified", false)
		return e.Next()
	})

	app.OnSettingsReload().BindFunc(func(e *core.SettingsReloadEvent) error {
		println("on setting reload")
		if err := e.Next(); err != nil {
			return err
		}

		e.App.Settings()

		return nil
	})

	app.OnTerminate().BindFunc(func(e *core.TerminateEvent) error {
		println("app is terminated")
		return e.Next()
	})

	app.OnMailerSend().BindFunc(func(e *core.MailerEvent) error {
		return e.Next()
	})

	app.OnMailerRecordVerificationSend().BindFunc(func(e *core.MailerRecordEvent) error {
		e.Message.Subject = "hook verify email"
		return e.Next()
	})

	app.OnMailerRecordOTPSend().BindFunc(func(e *core.MailerRecordEvent) error {
		e.Message.Subject = "OnMailerRecordOTPSend"
		return e.Next()
	})

	// use for sse
	app.OnRealtimeConnectRequest().BindFunc(func(e *core.RealtimeConnectRequestEvent) error {
		println("sse connecting")
		e.App.Logger().Info("SSE connection established", "client", e.Client, "timeout", e.IdleTimeout)
		return e.Next()
	})

	app.OnRealtimeMessageSend().BindFunc(func(e *core.RealtimeMessageEvent) error {
		println("send sse message")
		e.App.Logger().Info("SSE message sent", "client", e.Client, "message", e.Message)
		return e.Next()
	})

	app.OnCollectionsListRequest().BindFunc(func(e *core.CollectionsListRequestEvent) error {
		e.App.Logger().Info("Collections list requested")
		return e.Next()
	})

	if err := app.Start(); err != nil {
		app.Logger().Error("Failed to start application", "error", err)
		return nil, err
	}
	return app, nil
}