rentease/internal/server/handle_stripe_sync.go

63 lines
1.5 KiB
Go

package server
import (
"context"
"encoding/json"
"errors"
"io"
"net/http"
"time"
"github.com/labstack/echo/v4"
"github.com/rjNemo/rentease/internal/service/booking"
)
type stripeSyncRequest struct {
From string `json:"from"`
To string `json:"to"`
}
type stripeSyncer interface {
SyncStripePayments(ctx context.Context, from, to time.Time) error
}
func handleStripeSync(bs stripeSyncer) echo.HandlerFunc {
return func(c echo.Context) error {
req := new(stripeSyncRequest)
if err := json.NewDecoder(c.Request().Body).Decode(req); err != nil {
if !errors.Is(err, io.EOF) {
return echo.NewHTTPError(http.StatusBadRequest, "invalid request payload")
}
}
now := time.Now().UTC()
from := now.Add(-24 * time.Hour)
to := now
if req.From != "" {
parsed, err := time.Parse(time.RFC3339, req.From)
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, "invalid 'from' timestamp, expected RFC3339")
}
from = parsed
}
if req.To != "" {
parsed, err := time.Parse(time.RFC3339, req.To)
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, "invalid 'to' timestamp, expected RFC3339")
}
to = parsed
}
if err := bs.SyncStripePayments(c.Request().Context(), from, to); err != nil {
if errors.Is(err, booking.ErrStripeClientNotConfigured) {
return echo.NewHTTPError(http.StatusServiceUnavailable, "stripe client not configured")
}
return echo.NewHTTPError(http.StatusInternalServerError, err.Error())
}
return c.JSON(http.StatusOK, map[string]string{"status": "ok"})
}
}