Listing all sales database function

This commit is contained in:
vinchent 2024-08-21 22:39:30 +02:00
parent 2dce6e02ab
commit 21273c22cb

View File

@ -43,15 +43,18 @@ type Widget struct {
// Order is the type for all orders // Order is the type for all orders
type Order struct { type Order struct {
ID int `json:"id"` ID int `json:"id"`
WidgetID int `json:"widget_id"` WidgetID int `json:"widget_id"`
TransactionID int `json:"transaction_id"` TransactionID int `json:"transaction_id"`
CustomerID int `json:"customer_id"` CustomerID int `json:"customer_id"`
StatusID int `json:"status_id"` StatusID int `json:"status_id"`
Quantity int `json:"quantity"` Quantity int `json:"quantity"`
Amount int `json:"amount"` Amount int `json:"amount"`
CreatedAt time.Time `json:"-"` CreatedAt time.Time `json:"-"`
UpdatedAt time.Time `json:"-"` UpdatedAt time.Time `json:"-"`
Widget Widget `json:"widget"`
Transaction Transaction `json:"transaction"`
Customer Customer `json:"customer"`
} }
// Status is the type for orders statuses // Status is the type for orders statuses
@ -293,3 +296,67 @@ func (m *DBModel) UpdatePasswordForUser(u User, hash string) error {
} }
return nil return nil
} }
func (m *DBModel) GetAllOrders() ([]*Order, error) {
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
orders := []*Order{}
query := `
SELECT
o.id, o.widget_id, o.transaction_id, o.customer_id,
o.status_id, o.quantity, o.amount, o.created_at, o.updated_at,
w.id, w.name, t.id, t.amount, t.currency, t.last_four,
t.expiry_month, t.expiry_year, t.payment_intent, t.bank_return_code,
c.id, c.first_name, c.last_name, c.email
FROM orders o
LEFT JOIN widgets w on (o.widget_id = w.id)
LEFT JOIN transactions t on (o.transaction_id = t.id)
LEFT JOIN customers c on (o.customer_id = c.id)
WHERE
w.is_recurring = 0
ORDER BY
o.created_at DESC
`
rows, err := m.DB.QueryContext(ctx, query)
if err != nil {
return nil, err
}
defer rows.Close()
for rows.Next() {
var o Order
err = rows.Scan(
&o.ID,
&o.WidgetID,
&o.TransactionID,
&o.CustomerID,
&o.StatusID,
&o.Quantity,
&o.Amount,
&o.CreatedAt,
&o.UpdatedAt,
&o.Widget.ID,
&o.Widget.Name,
&o.Transaction.ID,
&o.Transaction.Amount,
&o.Transaction.Currency,
&o.Transaction.LastFour,
&o.Transaction.ExpiryMonth,
&o.Transaction.ExpiryYear,
&o.Transaction.PaymentIntent,
&o.Transaction.BankReturnCode,
&o.Customer.ID,
&o.Customer.FirstName,
&o.Customer.LastName,
&o.Customer.Email,
)
if err != nil {
return nil, err
}
orders = append(orders, &o)
}
return orders, nil
}