Skip to content

Commit

Permalink
feat: Massive overhaul to errors API
Browse files Browse the repository at this point in the history
  • Loading branch information
noahpistilli committed Nov 25, 2024
1 parent 5e4aa2f commit 3d2480d
Show file tree
Hide file tree
Showing 13 changed files with 238 additions and 88 deletions.
3 changes: 1 addition & 2 deletions areas.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import (
"context"
"encoding/xml"
"math/rand"
"net/http"
"strconv"
)

Expand Down Expand Up @@ -258,7 +257,7 @@ func areaList(r *Response) {
newAreaCode := GenerateAreaCode(areaCode)
_, err := pool.Exec(context.Background(), InsertUser, newAreaCode, r.request.Header.Get("X-WiiID"))
if err != nil {
r.ReportError(err, http.StatusInternalServerError)
r.ReportError(err)
return
}

Expand Down
84 changes: 44 additions & 40 deletions basket.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import (
"fmt"
"github.com/gofrs/uuid"
"github.com/mitchellh/go-wordwrap"
"net/http"
"strconv"
"strings"
"time"
Expand All @@ -20,12 +19,14 @@ const (
QueryUserForOrder = `SELECT "user".basket, "user".price, "user".order_id FROM "user" WHERE "user".wii_id = $1 LIMIT 1`
InsertAuthkey = `UPDATE "user" SET auth_key = $1 WHERE wii_id = $2`
ClearBasket = `UPDATE "user" SET order_id = $1, price = $2, basket = $3 WHERE wii_id = $4`
UpdateUserBasket = `UPDATE "user" SET basket = $1 WHERE wii_id = $2`
UpdateOrderId = `UPDATE "user" SET order_id = $1, price = $2 WHERE wii_id = $3`
)

func authKey(r *Response) {
authKeyValue, err := uuid.DefaultGenerator.NewV1()
if err != nil {
r.ReportError(err, http.StatusInternalServerError)
r.ReportError(err)
return
}

Expand All @@ -34,21 +35,21 @@ func authKey(r *Response) {
row := pool.QueryRow(context.Background(), DoesAuthKeyExist, r.request.Header.Get("X-WiiID"))
err = row.Scan(&authExists)
if err != nil {
r.ReportError(err, http.StatusInternalServerError)
r.ReportError(err)
return
}

if authExists {
_, err = pool.Exec(context.Background(), ClearBasket, "", "", "[]", r.request.Header.Get("X-WiiID"))
if err != nil {
r.ReportError(err, http.StatusInternalServerError)
r.ReportError(err)
return
}
}

_, err = pool.Exec(context.Background(), InsertAuthkey, authKeyValue.String(), r.request.Header.Get("X-WiiID"))
if err != nil {
r.ReportError(err, http.StatusInternalServerError)
r.ReportError(err)
return
}

Expand All @@ -61,47 +62,48 @@ func authKey(r *Response) {
}

func basketReset(r *Response) {
_, err := pool.Exec(context.Background(), `UPDATE "user" SET order_id = $1, price = $2, basket = $3 WHERE wii_id = $4`, "", "", "[]", r.request.Header.Get("X-WiiID"))
_, err := pool.Exec(context.Background(), ClearBasket, "", "", "[]", r.request.Header.Get("X-WiiID"))
if err != nil {
r.ReportError(err, http.StatusInternalServerError)
r.ReportError(err)
return
}
}

func basketDelete(r *Response) {
basketNumber, err := strconv.ParseInt(r.request.URL.Query().Get("basketNo"), 10, 64)
basketNumber, err := strconv.Atoi(r.request.URL.Query().Get("basketNo"))
if err != nil {
r.ReportError(err, http.StatusInternalServerError)
r.ReportError(err)
return
}

var lastBasket string
row := pool.QueryRow(context.Background(), QueryUserBasket, r.request.Header.Get("X-WiiID"))
err = row.Scan(&lastBasket, nil)
if err != nil {
r.ReportError(err, http.StatusInternalServerError)
r.ReportError(err)
return
}

var actualBasket []map[string]any
err = json.Unmarshal([]byte(lastBasket), &actualBasket)
if err != nil {
r.ReportError(err, http.StatusInternalServerError)
r.ReportError(err)
return
}

// Pop last element
actualBasket = append(actualBasket[:basketNumber-1], actualBasket[basketNumber:]...)

// Convert basket to JSON then insert to database
jsonStr, err := json.Marshal(actualBasket)
if err != nil {
r.ReportError(err, http.StatusInternalServerError)
r.ReportError(err)
return
}

_, err = pool.Exec(context.Background(), `UPDATE "user" SET basket = $1 WHERE wii_id = $2`, jsonStr, r.request.Header.Get("X-WiiID"))
_, err = pool.Exec(context.Background(), UpdateUserBasket, jsonStr, r.request.Header.Get("X-WiiID"))
if err != nil {
r.ReportError(err, http.StatusInternalServerError)
r.ReportError(err)
return
}
}
Expand All @@ -115,7 +117,7 @@ func basketAdd(r *Response) {
var err error
r.dominos, err = dominos.NewDominos(r.request)
if err != nil {
r.ReportError(err, http.StatusInternalServerError)
r.ReportError(err)
return
}

Expand Down Expand Up @@ -148,22 +150,22 @@ func basketAdd(r *Response) {
// Create our basket
basket, err := r.dominos.AddItem(shopCode, itemCode, quantity, toppings)
if err != nil {
r.ReportError(err, http.StatusInternalServerError)
r.ReportError(err)
return
}

var _authKey string
row := pool.QueryRow(context.Background(), QueryUserBasket, r.GetHollywoodId())
err = row.Scan(&lastBasket, &_authKey)
if err != nil {
r.ReportError(err, http.StatusInternalServerError)
r.ReportError(err)
return
}

var actualBasket []map[string]any
err = json.Unmarshal([]byte(lastBasket), &actualBasket)
if err != nil {
r.ReportError(err, http.StatusInternalServerError)
r.ReportError(err)
return
}

Expand All @@ -172,13 +174,13 @@ func basketAdd(r *Response) {
// Convert basket to JSON then insert to database
jsonStr, err := json.Marshal(actualBasket)
if err != nil {
r.ReportError(err, http.StatusInternalServerError)
r.ReportError(err)
return
}

_, err = pool.Exec(context.Background(), `UPDATE "user" SET basket = $1 WHERE wii_id = $2`, jsonStr, r.GetHollywoodId())
_, err = pool.Exec(context.Background(), UpdateUserBasket, jsonStr, r.GetHollywoodId())
if err != nil {
r.ReportError(err, http.StatusInternalServerError)
r.ReportError(err)
return
}
}
Expand All @@ -191,26 +193,26 @@ func basketList(r *Response) {
row := pool.QueryRow(context.Background(), QueryUserBasket, r.GetHollywoodId())
err := row.Scan(&basketStr, nil)
if err != nil {
r.ReportError(err, http.StatusInternalServerError)
r.ReportError(err)
return
}

var basket []map[string]any
err = json.Unmarshal([]byte(basketStr), &basket)
if err != nil {
r.ReportError(err, http.StatusInternalServerError)
r.ReportError(err)
return
}

r.dominos, err = dominos.NewDominos(r.request)
if err != nil {
r.ReportError(err, http.StatusInternalServerError)
r.ReportError(err)
return
}

user, err := r.dominos.AddressLookup(postalCode, address)
if err != nil {
r.ReportError(err, http.StatusInternalServerError)
r.ReportError(err)
return
}

Expand All @@ -219,30 +221,30 @@ func basketList(r *Response) {

items, err := r.dominos.GetPrice(user)
if err != nil {
r.ReportError(err, http.StatusInternalServerError)
r.ReportError(err)
return
}

// Add order ID and price to database
_, err = pool.Exec(context.Background(), `UPDATE "user" SET order_id = $1, price = $2 WHERE wii_id = $3`, items.OrderId, fmt.Sprintf("%.2f", items.TotalPrice), r.GetHollywoodId())
_, err = pool.Exec(context.Background(), UpdateOrderId, items.OrderId, fmt.Sprintf("%.2f", items.TotalPrice), r.GetHollywoodId())
if err != nil {
r.ReportError(err, http.StatusInternalServerError)
r.ReportError(err)
return
}

basketPrice := KVField{
XMLName: xml.Name{Local: "basketPrice"},
Value: items.BasketPrice,
Value: fmt.Sprintf("$%.2f", items.BasketPrice),
}

chargePrice := KVField{
XMLName: xml.Name{Local: "chargePrice"},
Value: items.ChargePrice,
Value: fmt.Sprintf("$%.2f", items.ChargePrice),
}

totalPrice := KVField{
XMLName: xml.Name{Local: "totalPrice"},
Value: items.TotalPrice,
Value: fmt.Sprintf("$%.2f", items.TotalPrice),
}

status := KVFieldWChildren{
Expand Down Expand Up @@ -284,7 +286,7 @@ func basketList(r *Response) {
IsSoldout: CDATA{BoolToInt(false)},
})
}
name := wordwrap.WrapString(*item.Name, 29)
name := wordwrap.WrapString(item.Name, 29)
for i, s := range strings.Split(name, "\n") {
switch i {
case 0:
Expand All @@ -301,17 +303,19 @@ func basketList(r *Response) {
}
}

priceStr := fmt.Sprintf("$%.2f", item.Price)
amountStr := fmt.Sprintf("$%.2f", item.Amount)
basketItems = append(basketItems, BasketItem{
XMLName: xml.Name{Local: fmt.Sprintf("container%d", i)},
BasketNo: CDATA{i + 1},
MenuCode: CDATA{1},
ItemCode: CDATA{item.Code},
Name: CDATA{name},
Price: CDATA{item.Price},
Price: CDATA{priceStr},
Size: CDATA{""},
IsSoldout: CDATA{BoolToInt(false)},
Quantity: CDATA{item.Quantity},
SubTotalPrice: CDATA{item.Amount},
SubTotalPrice: CDATA{amountStr},
Menu: KVFieldWChildren{
XMLName: xml.Name{Local: "Menu"},
Value: []any{
Expand Down Expand Up @@ -365,26 +369,26 @@ func orderDone(r *Response) {
row := pool.QueryRow(context.Background(), QueryUserForOrder, r.GetHollywoodId())
err := row.Scan(&basketStr, &price, &orderId)
if err != nil {
r.ReportError(err, http.StatusInternalServerError)
r.ReportError(err)
return
}

var basket []map[string]any
err = json.Unmarshal([]byte(basketStr), &basket)
if err != nil {
r.ReportError(err, http.StatusInternalServerError)
r.ReportError(err)
return
}

r.dominos, err = dominos.NewDominos(r.request)
if err != nil {
r.ReportError(err, http.StatusInternalServerError)
r.ReportError(err)
return
}

user, err := r.dominos.AddressLookup(r.request.PostForm.Get("member[PostNo]"), r.request.PostForm.Get("member[Address5]"))
if err != nil {
r.ReportError(err, http.StatusInternalServerError)
r.ReportError(err)
return
}

Expand Down Expand Up @@ -421,9 +425,9 @@ func orderDone(r *Response) {
r.AddKVNode("hour", currentTime)

// Remove the order data from the database
_, err = pool.Exec(context.Background(), `UPDATE "user" SET order_id = $1, price = $2, basket = $3 WHERE wii_id = $4`, "", "", "[]", r.GetHollywoodId())
_, err = pool.Exec(context.Background(), ClearBasket, "", "", "[]", r.GetHollywoodId())
if err != nil || didError {
r.ReportError(err, http.StatusInternalServerError)
r.ReportError(err)
return
}

Expand Down
13 changes: 7 additions & 6 deletions dominos/dominos.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ func (d *Dominos) AddressLookup(zipCode, address string) (*User, error) {
}

if jsonData["Status"].(float64) != 0 && jsonData["Status"].(float64) != 1 {
return nil, fmt.Errorf("domino's returned a status code of %.0f", jsonData["Status"].(float64))
return nil, MakeError(jsonData)
}

locationType := "House"
Expand Down Expand Up @@ -634,7 +634,8 @@ func (d *Dominos) GetPrice(user *User) (*Basket, error) {
}

if jsonData["Status"].(float64) != 0 && jsonData["Status"].(float64) != 1 {
return nil, fmt.Errorf("domino's returned a status code of %.0f\nError: %s", jsonData["Status"].(float64), jsonData["StatusItems"].([]any)[0].(map[string]any)["Code"].(string))
// 0 is success, 1 is a warning that is non-fatal
return nil, MakeError(jsonData)
}

var items []BasketItem
Expand All @@ -651,9 +652,9 @@ func (d *Dominos) GetPrice(user *User) (*Basket, error) {

items = append(items, BasketItem{
Code: itemData["Code"].(string),
Name: &name,
Price: &price,
Amount: &amount,
Name: name,
Price: price,
Amount: amount,
Quantity: int(itemData["Qty"].(float64)),
Options: options,
})
Expand Down Expand Up @@ -758,7 +759,7 @@ func (d *Dominos) PlaceOrder(info *User) error {
}

if jsonData["Status"].(float64) != 0 && jsonData["Status"].(float64) != 1 {
return fmt.Errorf("domino's returned a status code of %.0f", jsonData["Status"].(float64))
return MakeError(jsonData)
}

return nil
Expand Down
32 changes: 31 additions & 1 deletion dominos/errors.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,37 @@
package dominos

import "errors"
import (
"errors"
"fmt"
)

var (
InvalidCountry = errors.New("invalid country code")
GenericError = errors.New("An unknown error has occurred. Please contact WiiLink support\nError Code: ")
)

func MakeError(err map[string]any) error {
// Dominos error system is quite confusing, the more people that encounter errors the more we will learn.
statuses := err["Order"].(map[string]any)["StatusItems"].([]any)

for _, status := range statuses {
// Our implementation should always have the first dictionary be "AutoAddedOrderId".
// To be safe we will skip if encountered.
code := status.(map[string]any)["Code"].(string)
if code == "AutoAddedOrderId" {
continue
}

// This is not guaranteed to exist. If it does, it is much more verbose than the code.
pulseText := status.(map[string]any)["PulseText"]
if pulseText != nil {
return errors.New(fmt.Sprintf("An error has occured: %s\nError Code: ", pulseText))
}

// Default to the error code
return errors.New(fmt.Sprintf("An error has occured: %s\nError Code: ", code))
}

// If somehow nothing existed, give generic error.
return GenericError
}
Loading

0 comments on commit 3d2480d

Please sign in to comment.