invoices.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package billing
  2. import (
  3. "fmt"
  4. "net/http"
  5. "github.com/porter-dev/porter/api/server/handlers"
  6. "github.com/porter-dev/porter/api/server/shared"
  7. "github.com/porter-dev/porter/api/server/shared/apierrors"
  8. "github.com/porter-dev/porter/api/server/shared/config"
  9. "github.com/porter-dev/porter/api/types"
  10. "github.com/porter-dev/porter/internal/models"
  11. "github.com/porter-dev/porter/internal/telemetry"
  12. )
  13. // ListCustomerInvoicesHandler is a handler for listing payment methods
  14. type ListCustomerInvoicesHandler struct {
  15. handlers.PorterHandlerReadWriter
  16. }
  17. // NewListCustomerInvoicesHandler will create a new ListCustomerInvoicesHandler
  18. func NewListCustomerInvoicesHandler(
  19. config *config.Config,
  20. decoderValidator shared.RequestDecoderValidator,
  21. writer shared.ResultWriter,
  22. ) *ListCustomerInvoicesHandler {
  23. return &ListCustomerInvoicesHandler{
  24. PorterHandlerReadWriter: handlers.NewDefaultPorterHandler(config, decoderValidator, writer),
  25. }
  26. }
  27. func (c *ListCustomerInvoicesHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  28. ctx, span := telemetry.NewSpan(r.Context(), "serve-list-payment-methods")
  29. defer span.End()
  30. proj, _ := ctx.Value(types.ProjectScope).(*models.Project)
  31. telemetry.WithAttributes(span,
  32. telemetry.AttributeKV{Key: "billing-config-exists", Value: c.Config().BillingManager.StripeConfigLoaded},
  33. telemetry.AttributeKV{Key: "billing-enabled", Value: proj.GetFeatureFlag(models.BillingEnabled, c.Config().LaunchDarklyClient)},
  34. telemetry.AttributeKV{Key: "porter-cloud-enabled", Value: proj.EnableSandbox},
  35. )
  36. if !c.Config().BillingManager.StripeConfigLoaded || !proj.GetFeatureFlag(models.BillingEnabled, c.Config().LaunchDarklyClient) {
  37. c.WriteResult(w, r, "")
  38. return
  39. }
  40. req := &types.ListCustomerInvoicesRequest{}
  41. if ok := c.DecodeAndValidate(w, r, req); !ok {
  42. err := telemetry.Error(ctx, span, nil, "error decoding list customer usage request")
  43. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusBadRequest))
  44. return
  45. }
  46. invoices, err := c.Config().BillingManager.StripeClient.ListCustomerInvoices(ctx, proj.BillingID, req.Status)
  47. if err != nil {
  48. err = telemetry.Error(ctx, span, err, fmt.Sprintf("error listing invoices for customer %s", proj.BillingID))
  49. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusBadRequest))
  50. return
  51. }
  52. // Write the response to the frontend
  53. c.WriteResult(w, r, invoices)
  54. }