Repository navigation
Expand file tree
/
Copy pathorder.go
More file actions
480 lines (393 loc) · 14.5 KB
/
Copy pathorder.go
File metadata and controls
480 lines (393 loc) · 14.5 KB
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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
package main
import (
"context"
"errors"
"fmt"
"sync"
"time"
"github.com/luno/workflow"
"github.com/luno/workflow/adapters/memrecordstore"
"github.com/luno/workflow/adapters/memrolescheduler"
"github.com/luno/workflow/adapters/memstreamer"
"github.com/luno/workflow/adapters/memtimeoutstore"
)
// OrderStatus represents all possible states in our order workflow
type OrderStatus int
const (
OrderStatusUnknown OrderStatus = 0
OrderStatusCreated OrderStatus = 1
OrderStatusValidated OrderStatus = 2
OrderStatusPaymentProcessing OrderStatus = 3
OrderStatusPaymentProcessed OrderStatus = 4
OrderStatusPaymentFailed OrderStatus = 5
OrderStatusInventoryReserved OrderStatus = 6
OrderStatusInventoryFailed OrderStatus = 7
OrderStatusFulfilled OrderStatus = 8
OrderStatusCancelled OrderStatus = 9
OrderStatusRefunded OrderStatus = 10
)
func (s OrderStatus) String() string {
switch s {
case OrderStatusCreated:
return "Created"
case OrderStatusValidated:
return "Validated"
case OrderStatusPaymentProcessing:
return "PaymentProcessing"
case OrderStatusPaymentProcessed:
return "PaymentProcessed"
case OrderStatusPaymentFailed:
return "PaymentFailed"
case OrderStatusInventoryReserved:
return "InventoryReserved"
case OrderStatusInventoryFailed:
return "InventoryFailed"
case OrderStatusFulfilled:
return "Fulfilled"
case OrderStatusCancelled:
return "Cancelled"
case OrderStatusRefunded:
return "Refunded"
default:
return "Unknown"
}
}
// Order represents our business entity flowing through the workflow
type Order struct {
ID string `json:"id"`
CustomerID string `json:"customer_id"`
Items []OrderItem `json:"items"`
Total float64 `json:"total"`
PaymentMethod string `json:"payment_method"`
ShippingAddress Address `json:"shipping_address"`
// Workflow state
ValidationErrors []string `json:"validation_errors,omitempty"`
PaymentID string `json:"payment_id,omitempty"`
ReservationID string `json:"reservation_id,omitempty"`
TrackingNumber string `json:"tracking_number,omitempty"`
PaymentAttempts int `json:"payment_attempts"`
// Timestamps
CreatedAt time.Time `json:"created_at"`
ValidatedAt *time.Time `json:"validated_at,omitempty"`
PaidAt *time.Time `json:"paid_at,omitempty"`
FulfilledAt *time.Time `json:"fulfilled_at,omitempty"`
CancelledAt *time.Time `json:"cancelled_at,omitempty"`
}
type OrderItem struct {
ProductID string `json:"product_id"`
Quantity int `json:"quantity"`
Price float64 `json:"price"`
}
type Address struct {
Street string `json:"street"`
City string `json:"city"`
State string `json:"state"`
ZipCode string `json:"zip_code"`
Country string `json:"country"`
}
func NewOrderWorkflow(
paymentService *MockPaymentService,
inventoryService *MockInventoryService,
shippingService *MockShippingService,
) *workflow.Workflow[Order, OrderStatus] {
b := workflow.NewBuilder[Order, OrderStatus]("order-processing")
// Step 1: Validate order
b.AddStep(OrderStatusCreated, validateOrder, OrderStatusValidated, OrderStatusCancelled)
// Step 2: Process payment (with retries)
b.AddStep(OrderStatusValidated, processPayment(paymentService), OrderStatusPaymentProcessing, OrderStatusPaymentFailed, OrderStatusCancelled)
// Step 3: Complete payment processing
b.AddStep(OrderStatusPaymentProcessing, completePayment(paymentService), OrderStatusPaymentProcessed, OrderStatusPaymentFailed)
// Step 4: Reserve inventory
b.AddStep(OrderStatusPaymentProcessed, reserveInventory(inventoryService), OrderStatusInventoryReserved, OrderStatusInventoryFailed)
// Step 5: Fulfill order
b.AddStep(OrderStatusInventoryReserved, fulfillOrder(shippingService), OrderStatusFulfilled)
// Error handling flows
b.AddStep(OrderStatusPaymentFailed, handlePaymentFailure(paymentService), OrderStatusCancelled, OrderStatusPaymentProcessing)
b.AddStep(OrderStatusInventoryFailed, handleInventoryFailure(inventoryService, paymentService), OrderStatusRefunded, OrderStatusInventoryReserved)
// Cancellation flow
b.AddStep(OrderStatusCancelled, processCancellation(inventoryService, paymentService), OrderStatusRefunded)
// Add timeouts
b.AddTimeout(
OrderStatusPaymentProcessing,
workflow.DurationTimerFunc[Order, OrderStatus](5*time.Minute),
func(ctx context.Context, r *workflow.Run[Order, OrderStatus], now time.Time) (OrderStatus, error) {
return OrderStatusPaymentFailed, nil
},
OrderStatusPaymentFailed,
)
// Add hooks for monitoring
b.OnComplete(func(ctx context.Context, record *workflow.TypedRecord[Order, OrderStatus]) error {
fmt.Printf("📊 [%s] Order completed in %v\n", record.Object.ID, time.Since(record.CreatedAt))
return nil
})
b.OnPause(func(ctx context.Context, record *workflow.TypedRecord[Order, OrderStatus]) error {
fmt.Printf("⚠️ [%s] Order paused due to errors - requires investigation\n", record.Object.ID)
// In real implementation, send alert to operations team
return nil
})
return b.Build(
memstreamer.New(),
memrecordstore.New(),
memrolescheduler.New(),
workflow.WithTimeoutStore(memtimeoutstore.New()),
)
}
// Step implementations
func validateOrder(ctx context.Context, r *workflow.Run[Order, OrderStatus]) (OrderStatus, error) {
fmt.Printf("🔍 [%s] Validating order\n", r.Object.ID)
var validationErrors []string
// Validate items
if len(r.Object.Items) == 0 {
validationErrors = append(validationErrors, "Order must have at least one item")
}
// Validate total
calculatedTotal := 0.0
for _, item := range r.Object.Items {
if item.Quantity <= 0 {
validationErrors = append(validationErrors, fmt.Sprintf("Invalid quantity for product %s", item.ProductID))
}
if item.Price < 0 {
validationErrors = append(validationErrors, fmt.Sprintf("Invalid price for product %s", item.ProductID))
}
calculatedTotal += item.Price * float64(item.Quantity)
}
if abs(r.Object.Total-calculatedTotal) > 0.01 {
validationErrors = append(validationErrors, "Order total does not match item prices")
}
// Validate payment method
if r.Object.PaymentMethod == "" {
validationErrors = append(validationErrors, "Payment method is required")
}
// Validate shipping address
if r.Object.ShippingAddress.Street == "" || r.Object.ShippingAddress.City == "" {
validationErrors = append(validationErrors, "Complete shipping address is required")
}
if len(validationErrors) > 0 {
r.Object.ValidationErrors = validationErrors
return OrderStatusCancelled, nil
}
now := time.Now()
r.Object.ValidatedAt = &now
fmt.Printf("✅ [%s] Order validated successfully\n", r.Object.ID)
return OrderStatusValidated, nil
}
func processPayment(ps *MockPaymentService) func(ctx context.Context, r *workflow.Run[Order, OrderStatus]) (OrderStatus, error) {
return func(ctx context.Context, r *workflow.Run[Order, OrderStatus]) (OrderStatus, error) {
fmt.Printf("💳 [%s] Processing payment (attempt %d)\n", r.Object.ID, r.Object.PaymentAttempts+1)
r.Object.PaymentAttempts++
// Simulate payment processing
paymentID, err := ps.ProcessPayment(PaymentRequest{
Amount: r.Object.Total,
PaymentMethod: r.Object.PaymentMethod,
CustomerID: r.Object.CustomerID,
OrderID: r.Object.ID,
})
if err != nil {
if isRetryablePaymentError(err) && r.Object.PaymentAttempts < 3 {
// Try again until no longer tryable or max attempts reached
return r.SaveAndRepeat()
}
fmt.Printf("❌ [%s] Payment processing failed: %v\n", r.Object.ID, err)
return OrderStatusPaymentFailed, nil
}
r.Object.PaymentID = paymentID
return OrderStatusPaymentProcessing, nil
}
}
func completePayment(ps *MockPaymentService) func(ctx context.Context, r *workflow.Run[Order, OrderStatus]) (OrderStatus, error) {
return func(ctx context.Context, r *workflow.Run[Order, OrderStatus]) (OrderStatus, error) {
fmt.Printf("✅ [%s] Confirming payment %s\n", r.Object.ID, r.Object.PaymentID)
// Check payment status
status, err := ps.GetPaymentStatus(r.Object.PaymentID)
if err != nil {
return 0, err
}
switch status {
case "completed":
now := time.Now()
r.Object.PaidAt = &now
return OrderStatusPaymentProcessed, nil
case "failed":
return OrderStatusPaymentFailed, nil
case "processing":
// Still processing, check again later
return OrderStatusPaymentProcessing, nil
default:
return OrderStatusPaymentFailed, nil
}
}
}
func reserveInventory(is *MockInventoryService) func(ctx context.Context, r *workflow.Run[Order, OrderStatus]) (OrderStatus, error) {
return func(ctx context.Context, r *workflow.Run[Order, OrderStatus]) (OrderStatus, error) {
fmt.Printf("📦 [%s] Reserving inventory\n", r.Object.ID)
reservationID, err := is.ReserveItems(r.Object.Items)
if err != nil {
if errors.Is(err, ErrInsufficientInventory) {
return OrderStatusInventoryFailed, nil
}
return 0, err // Retryable error
}
r.Object.ReservationID = reservationID
fmt.Printf("✅ [%s] Inventory reserved with ID %s\n", r.Object.ID, reservationID)
return OrderStatusInventoryReserved, nil
}
}
func fulfillOrder(ss *MockShippingService) func(ctx context.Context, r *workflow.Run[Order, OrderStatus]) (OrderStatus, error) {
return func(ctx context.Context, r *workflow.Run[Order, OrderStatus]) (OrderStatus, error) {
fmt.Printf("🚚 [%s] Fulfilling order\n", r.Object.ID)
// Create shipment
trackingNumber, err := ss.CreateShipment(ShipmentRequest{
OrderID: r.Object.ID,
Items: r.Object.Items,
ShippingAddress: r.Object.ShippingAddress,
ReservationID: r.Object.ReservationID,
})
if err != nil {
return 0, err
}
r.Object.TrackingNumber = trackingNumber
now := time.Now()
r.Object.FulfilledAt = &now
fmt.Printf("🎉 [%s] Order fulfilled! Tracking number: %s\n", r.Object.ID, trackingNumber)
return OrderStatusFulfilled, nil
}
}
// Error handlers
func handlePaymentFailure(ps *MockPaymentService) func(ctx context.Context, r *workflow.Run[Order, OrderStatus]) (OrderStatus, error) {
return func(ctx context.Context, r *workflow.Run[Order, OrderStatus]) (OrderStatus, error) {
fmt.Printf("❌ [%s] Handling payment failure\n", r.Object.ID)
if hasAlternativePaymentMethod(r.Object.CustomerID) {
fmt.Printf("🔄 [%s] Retrying payment with alternative method\n", r.Object.ID)
r.Object.PaymentMethod = getAlternativePaymentMethod(r.Object.CustomerID)
return OrderStatusPaymentProcessing, nil
}
return OrderStatusCancelled, nil
}
}
func handleInventoryFailure(is *MockInventoryService, ps *MockPaymentService) func(ctx context.Context, r *workflow.Run[Order, OrderStatus]) (OrderStatus, error) {
return func(ctx context.Context, r *workflow.Run[Order, OrderStatus]) (OrderStatus, error) {
fmt.Printf("📦 [%s] Handling inventory failure\n", r.Object.ID)
// Check if we have partial inventory
availableItems, err := is.CheckPartialAvailability(r.Object.Items)
if err != nil {
return 0, err
}
if len(availableItems) > 0 && len(availableItems) < len(r.Object.Items) {
// Offer partial fulfillment (simplified - in real app, would need customer consent)
r.Object.Items = availableItems
return OrderStatusInventoryReserved, nil
}
// No inventory available - refund payment
err = ps.RefundPayment(r.Object.PaymentID)
if err != nil {
return 0, err
}
return OrderStatusRefunded, nil
}
}
func processCancellation(is *MockInventoryService, ps *MockPaymentService) func(ctx context.Context, r *workflow.Run[Order, OrderStatus]) (OrderStatus, error) {
return func(ctx context.Context, r *workflow.Run[Order, OrderStatus]) (OrderStatus, error) {
fmt.Printf("🚫 [%s] Processing cancellation\n", r.Object.ID)
if r.Object.PaymentID == "" && r.Object.ReservationID == "" {
return r.Cancel(ctx, "No payment to refund")
}
// Release inventory reservation if exists
if r.Object.ReservationID != "" {
if err := is.ReleaseReservation(r.Object.ReservationID); err != nil {
return 0, err
}
}
// Refund payment if exists
if r.Object.PaymentID != "" {
if err := ps.RefundPayment(r.Object.PaymentID); err != nil {
return 0, err
}
}
now := time.Now()
r.Object.CancelledAt = &now
return OrderStatusRefunded, nil
}
}
// Mock service implementations
type MockPaymentService struct{}
type PaymentRequest struct {
Amount float64
PaymentMethod string
CustomerID string
OrderID string
}
func (s *MockPaymentService) ProcessPayment(req PaymentRequest) (string, error) {
// Simulate payment processing
if req.PaymentMethod == "invalid_card" {
return "", errors.New("invalid payment method")
}
if req.Amount > 1000 && req.PaymentMethod == "credit_card" {
return "", errors.New("payment declined by bank")
}
return fmt.Sprintf("pay_%s", req.OrderID), nil
}
func (s *MockPaymentService) GetPaymentStatus(paymentID string) (string, error) {
// Simulate async payment processing
return "completed", nil
}
func (s *MockPaymentService) RefundPayment(paymentID string) error {
fmt.Printf("💰 Refunding payment %s\n", paymentID)
return nil
}
type MockInventoryService struct {
mu sync.Mutex
counter int
}
var ErrInsufficientInventory = errors.New("insufficient inventory")
func (s *MockInventoryService) ReserveItems(items []OrderItem) (string, error) {
// Simulate inventory check
for _, item := range items {
if item.ProductID == "out_of_stock" {
return "", ErrInsufficientInventory
}
}
s.mu.Lock()
defer s.mu.Unlock()
s.counter++
return fmt.Sprintf("res_%d", s.counter), nil
}
func (s *MockInventoryService) CheckPartialAvailability(items []OrderItem) ([]OrderItem, error) {
var available []OrderItem
for _, item := range items {
if item.ProductID != "out_of_stock" {
available = append(available, item)
}
}
return available, nil
}
func (s *MockInventoryService) ReleaseReservation(reservationID string) error {
fmt.Printf("📦 Releasing reservation %s\n", reservationID)
return nil
}
type MockShippingService struct{}
type ShipmentRequest struct {
OrderID string
Items []OrderItem
ShippingAddress Address
ReservationID string
}
func (s *MockShippingService) CreateShipment(req ShipmentRequest) (string, error) {
return fmt.Sprintf("TRACK_%s", req.OrderID), nil
}
// Helper functions
func isRetryablePaymentError(err error) bool {
return err.Error() == "payment declined by bank" ||
err.Error() == "network timeout"
}
func hasAlternativePaymentMethod(customerID string) bool {
return customerID == "premium_customer"
}
func getAlternativePaymentMethod(customerID string) string {
return "debit_card"
}
func abs(x float64) float64 {
if x < 0 {
return -x
}
return x
}