mirror of
https://github.com/marcusDenslow/terminalShop.git
synced 2026-10-26 18:28:47 +01:00
Adds POST /api/v1/orders/{id}/label (admin-only) that buys a shipping
label through Shippo and writes carrier + tracking + label fields back
onto the order, transitioning paid -> shipped.
262 lines
8.2 KiB
Go
262 lines
8.2 KiB
Go
package handlers
|
|
|
|
import (
|
|
"encoding/json"
|
|
"net/http"
|
|
"os"
|
|
"strconv"
|
|
"terminalShop/pkg/shippo"
|
|
"time"
|
|
|
|
"terminalShop/api/middleware"
|
|
"terminalShop/pkg/audit"
|
|
"terminalShop/pkg/database"
|
|
"terminalShop/pkg/models"
|
|
"terminalShop/pkg/utils"
|
|
|
|
"github.com/go-chi/chi/v5"
|
|
"github.com/stripe/stripe-go/v78"
|
|
"github.com/stripe/stripe-go/v78/refund"
|
|
)
|
|
|
|
type OrderHandler struct {
|
|
stripeKey string
|
|
}
|
|
|
|
func NewOrderHandler(stripeSecretKey string) *OrderHandler {
|
|
return &OrderHandler{stripeKey: stripeSecretKey}
|
|
}
|
|
|
|
func (h *OrderHandler) GetOrders(w http.ResponseWriter, r *http.Request) {
|
|
db := database.GetDB().WithContext(r.Context())
|
|
userID := middleware.UserIDFromContext(r.Context())
|
|
|
|
var orders []models.Order
|
|
db.Where("user_id = ?", userID).Preload("Items").Order("created_at desc").Find(&orders)
|
|
|
|
utils.RespondSuccess(w, http.StatusOK, map[string]interface{}{
|
|
"orders": orders,
|
|
})
|
|
}
|
|
|
|
// RefundOrder issues a full refund for an order via Stripe and marks it as
|
|
// refunded. Only orders in paid or shipped status can be refunded.
|
|
func (h *OrderHandler) RefundOrder(w http.ResponseWriter, r *http.Request) {
|
|
db := database.GetDB().WithContext(r.Context())
|
|
userID := middleware.UserIDFromContext(r.Context())
|
|
|
|
idStr := chi.URLParam(r, "id")
|
|
id, err := strconv.ParseUint(idStr, 10, 32)
|
|
if err != nil {
|
|
utils.RespondError(w, http.StatusBadRequest, "INVALID_ID", "invalid order id", nil)
|
|
return
|
|
}
|
|
|
|
var order models.Order
|
|
if err := db.Where("id = ? AND user_id = ?", id, userID).First(&order).Error; err != nil {
|
|
utils.RespondError(w, http.StatusNotFound, "ORDER_NOT_FOUND", "order not found", nil)
|
|
return
|
|
}
|
|
|
|
// Only paid or shipped orders can be refunded.
|
|
if order.Status != models.OrderStatusPaid && order.Status != models.OrderStatusShipped {
|
|
utils.RespondError(w, http.StatusBadRequest, "INVALID_STATE",
|
|
"only paid or shipped orders can be refunded", nil)
|
|
return
|
|
}
|
|
|
|
if order.StripePaymentID == "" {
|
|
utils.RespondError(w, http.StatusBadRequest, "MISSING_PAYMENT_ID",
|
|
"order has no stripe payment id — contact support", nil)
|
|
return
|
|
}
|
|
|
|
stripe.Key = h.stripeKey
|
|
|
|
rf, err := refund.New(&stripe.RefundParams{
|
|
PaymentIntent: stripe.String(order.StripePaymentID),
|
|
})
|
|
if err != nil {
|
|
if stripeErr, ok := err.(*stripe.Error); ok {
|
|
utils.RespondError(w, http.StatusBadRequest, "STRIPE_ERROR", stripeErr.Msg, nil)
|
|
return
|
|
}
|
|
utils.RespondError(w, http.StatusInternalServerError, "REFUND_FAILED", "refund failed", nil)
|
|
return
|
|
}
|
|
|
|
if err := db.Model(&order).Update("status", models.OrderStatusRefunded).Error; err != nil {
|
|
utils.RespondError(w, http.StatusInternalServerError, "DATABASE_ERROR", "refund issued but failed to update order status", nil)
|
|
return
|
|
}
|
|
|
|
audit.OrderRefunded(userID, order.ID, order.Total, rf.ID)
|
|
|
|
utils.RespondSuccess(w, http.StatusOK, map[string]interface{}{
|
|
"refund_id": rf.ID,
|
|
"status": "refunded",
|
|
})
|
|
}
|
|
|
|
// updateTrackingRequest is the JSON body accepted by UpdateTracking.
|
|
// shipped_at defaults to now if not otherwise specified
|
|
type updateTrackingRequest struct {
|
|
Carrier string `json:"carrier"`
|
|
TrackingNumber string `json:"tracking_number"`
|
|
TrackingURL string `json:"tracking_url"`
|
|
ShippedAt *time.Time `json:"shipped_at"`
|
|
}
|
|
|
|
// UpdateTracking sets carrier metadata on the order. Transitions paid orders
|
|
// to shipped automatically. Admin only, gated by RequireAdmin in routes.go,
|
|
// not RequireAuth, so no user JWT is needed.
|
|
func (h *OrderHandler) UpdateTracking(w http.ResponseWriter, r *http.Request) {
|
|
db := database.GetDB().WithContext(r.Context())
|
|
|
|
idStr := chi.URLParam(r, "id")
|
|
id, err := strconv.ParseUint(idStr, 10, 32)
|
|
if err != nil {
|
|
utils.RespondError(w, http.StatusBadRequest, "INVALID_ID", "invalid order id", nil)
|
|
return
|
|
}
|
|
|
|
var req updateTrackingRequest
|
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
|
utils.RespondError(w, http.StatusBadRequest, "INVALID_BODY", "invalid request body", nil)
|
|
return
|
|
}
|
|
if req.Carrier == "" || req.TrackingNumber == "" {
|
|
utils.RespondError(w, http.StatusBadRequest, "MISSING_FIELDS", "carrier and or tracking_number fields are required", nil)
|
|
return
|
|
}
|
|
|
|
var order models.Order
|
|
if err := db.Where("id = ?", id).First(&order).Error; err != nil {
|
|
utils.RespondError(w, http.StatusNotFound, "ORDER_NOT_FOUND", "order not found", nil)
|
|
return
|
|
}
|
|
|
|
shippedAt := req.ShippedAt
|
|
if shippedAt == nil {
|
|
now := time.Now()
|
|
shippedAt = &now
|
|
}
|
|
|
|
updates := map[string]any{
|
|
"carrier": req.Carrier,
|
|
"tracking_number": req.TrackingNumber,
|
|
"tracking_url": req.TrackingURL,
|
|
"shipped_at": shippedAt,
|
|
}
|
|
if order.Status == models.OrderStatusPaid {
|
|
updates["status"] = models.OrderStatusShipped
|
|
}
|
|
if err := db.Model(&order).Updates(updates).Error; err != nil {
|
|
utils.RespondError(w, http.StatusInternalServerError, "DATABASE_ERROR", "failed to record shipment", nil)
|
|
return
|
|
}
|
|
|
|
audit.OrderShipped(order.UserID, order.ID, req.Carrier, req.TrackingNumber)
|
|
|
|
utils.RespondSuccess(w, http.StatusOK, map[string]interface{}{
|
|
"order_id": order.ID,
|
|
"carrier": req.Carrier,
|
|
"tracking_number": req.TrackingNumber,
|
|
"status": order.Status,
|
|
})
|
|
}
|
|
|
|
// PurchaseLabel buys a shipping label from shippo for the order, writes
|
|
// the carrier, tracking, and label fields onto the order, and changes the status
|
|
// from paid to shipped
|
|
func (h *OrderHandler) PurchaseLabel(w http.ResponseWriter, r *http.Request) {
|
|
db := database.GetDB().WithContext(r.Context())
|
|
|
|
idStr := chi.URLParam(r, "id")
|
|
id, err := strconv.ParseUint(idStr, 10, 32)
|
|
if err != nil {
|
|
utils.RespondError(w, http.StatusBadRequest, "INVALID_ID", "invalid order id", nil)
|
|
return
|
|
}
|
|
|
|
var order models.Order
|
|
if err := db.Preload("Items.Coffee").Preload("User").Where("id = ?", id).First(&order).Error; err != nil {
|
|
utils.RespondError(w, http.StatusNotFound, "ORDER_NOT_FOUND", "order not found", nil)
|
|
return
|
|
}
|
|
|
|
if order.Status != models.OrderStatusPaid {
|
|
utils.RespondError(w, http.StatusConflict, "INVALID_STATE", "only paid orders can be labeled", nil)
|
|
return
|
|
}
|
|
if order.TrackingNumber != "" {
|
|
utils.RespondError(w, http.StatusConflict, "ALREADY_LABELED", "order already has a tracking number", nil)
|
|
return
|
|
}
|
|
|
|
// Coffee.Ounces in ounces; shippo client expects kg
|
|
const ozToKg = 0.0283495
|
|
const defaultOunces = 12.0
|
|
|
|
lineItems := make([]shippo.LineItem, 0, len(order.Items))
|
|
for _, it := range order.Items {
|
|
oz := float64(it.Coffee.Ounces)
|
|
if oz <= 0 {
|
|
oz = defaultOunces
|
|
}
|
|
lineItems = append(lineItems, shippo.LineItem{
|
|
Title: it.Name,
|
|
Quantity: it.Quantity,
|
|
WeightKg: oz * ozToKg,
|
|
})
|
|
}
|
|
|
|
to := shippo.Address{
|
|
Name: order.ShippingName,
|
|
Street1: order.ShippingStreet,
|
|
Street2: order.ShippingStreet2,
|
|
City: order.ShippingCity,
|
|
State: order.ShippingState,
|
|
Country: order.ShippingCountry,
|
|
Zip: order.ShippingZip,
|
|
Phone: order.ShippingPhone,
|
|
}
|
|
|
|
client := shippo.NewClient(os.Getenv("SHIPPO_API_KEY"))
|
|
result, err := client.CreateLabel(r.Context(), to, order.User.Email, lineItems)
|
|
if err != nil {
|
|
utils.RespondError(w, http.StatusBadGateway, "SHIPPO_ERROR", err.Error(), nil)
|
|
return
|
|
}
|
|
|
|
now := time.Now()
|
|
updates := map[string]any{
|
|
"carrier": result.Carrier,
|
|
"tracking_number": result.TrackingNumber,
|
|
"tracking_url": result.TrackingURL,
|
|
"shipped_at": &now,
|
|
"status": models.OrderStatusShipped,
|
|
"shippo_transaction_id": result.TransactionID,
|
|
"label_url": result.LabelURL,
|
|
"label_cost_cents": result.CostCents,
|
|
}
|
|
if err := db.Model(&order).Updates(updates).Error; err != nil {
|
|
audit.LabelOrphaned(order.ID, result.TransactionID, result.TrackingNumber, err)
|
|
utils.RespondError(w, http.StatusInternalServerError, "DATABASE_ERROR", "label purchased but failed to record on order; ops will reconcile", nil)
|
|
return
|
|
}
|
|
|
|
audit.LabelPurchased(order.ID, result.Carrier, result.TrackingNumber, result.TransactionID, result.CostCents)
|
|
|
|
utils.RespondSuccess(w, http.StatusOK, map[string]any{
|
|
"order_id": order.ID,
|
|
"carrier": result.Carrier,
|
|
"service": result.ServiceLevel,
|
|
"tracking_number": result.TrackingNumber,
|
|
"tracking_url": result.TrackingURL,
|
|
"label_url": result.LabelURL,
|
|
"cost_cents": result.CostCents,
|
|
"status": models.OrderStatusShipped,
|
|
})
|
|
}
|