76 lines
2.2 KiB
Go
76 lines
2.2 KiB
Go
package httpapi
|
|||
|
|
|
||
|
|
import (
|
||
|
|
"net/http"
|
||
|
|
"strings"
|
||
|
|
|
||
|
|
"github.com/descrybe/descrybe-v2/apps/api/internal/billing"
|
||
|
|
)
|
||
|
|
|
||
|
|
// POST /api/admin/settings/stripe/sync-credit-packs
|
||
|
|
// Creates/updates Stripe Products + one-time Prices for DefaultCreditPacks using
|
||
|
|
// the configured secret key (sk_test_* or sk_live_*), then writes Price IDs into
|
||
|
|
// platform settings (stripe.price.pack.*).
|
||
|
|
func (s *Server) handleAdminSyncStripeCreditPacks(w http.ResponseWriter, r *http.Request) {
|
||
|
|
if s.PlatformSettings == nil {
|
||
|
|
Error(w, http.StatusServiceUnavailable, "platform settings unavailable")
|
||
|
|
return
|
||
|
|
}
|
||
|
|
if s.Stripe == nil {
|
||
|
|
Error(w, http.StatusServiceUnavailable, "stripe unavailable")
|
||
|
|
return
|
||
|
|
}
|
||
|
|
|
||
|
|
cfg, err := s.PlatformSettings.ResolveStripe(r.Context(), s.Stripe.Cfg)
|
||
|
|
if err != nil {
|
||
|
|
Error(w, http.StatusInternalServerError, "failed to resolve stripe settings")
|
||
|
|
return
|
||
|
|
}
|
||
|
|
secret := strings.TrimSpace(cfg.SecretKey)
|
||
|
|
if secret == "" || cfg.ForceMock {
|
||
|
|
Error(w, http.StatusBadRequest, "configure a Stripe secret key (test or live) and turn mock off before syncing")
|
||
|
|
return
|
||
|
|
}
|
||
|
|
|
||
|
|
mode := "live"
|
||
|
|
if strings.HasPrefix(secret, "sk_test_") {
|
||
|
|
mode = "test"
|
||
|
|
} else if !strings.HasPrefix(secret, "sk_live_") {
|
||
|
|
mode = "unknown"
|
||
|
|
}
|
||
|
|
|
||
|
|
svc := &billing.StripeService{
|
||
|
|
Pool: s.Stripe.Pool,
|
||
|
|
Cfg: billing.StripeConfig{SecretKey: secret},
|
||
|
|
}
|
||
|
|
results, err := svc.SyncCreditPackProducts(r.Context())
|
||
|
|
if err != nil {
|
||
|
|
ClientOrLog(w, http.StatusBadRequest, "could not sync credit packs to Stripe", err, billing.ClientError)
|
||
|
|
return
|
||
|
|
}
|
||
|
|
|
||
|
|
written := make([]map[string]any, 0, len(results))
|
||
|
|
for _, row := range results {
|
||
|
|
key := billing.CreditPackSettingsKey(row.PackID)
|
||
|
|
if err := s.PlatformSettings.SetKV(r.Context(), key, row.PriceID); err != nil {
|
||
|
|
ClientOrLog(w, http.StatusBadRequest, "synced Stripe but failed to save price id", err, billing.ClientError)
|
||
|
|
return
|
||
|
|
}
|
||
|
|
written = append(written, map[string]any{
|
||
|
|
"pack_id": row.PackID,
|
||
|
|
"product_id": row.ProductID,
|
||
|
|
"price_id": row.PriceID,
|
||
|
|
"credits": row.Credits,
|
||
|
|
"price_usd": row.PriceUSD,
|
||
|
|
"created": row.Created,
|
||
|
|
"settings_key": key,
|
||
|
|
})
|
||
|
|
}
|
||
|
|
|
||
|
|
JSON(w, http.StatusOK, map[string]any{
|
||
|
|
"mode": mode,
|
||
|
|
"packs": written,
|
||
|
|
"message": "Credit pack Products/Prices synced; Price IDs saved to settings.",
|
||
|
|
})
|
||
|
|
}
|