Return all active subscriptions with category and normalize timer payloads.
GET /subscriptions/me now returns every active subscription with plan category. PREP_TIME and ANSWER_TIMER dynamic slots are normalized to { seconds: N } on save.
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
parent
d02f21b276
commit
ff5cb64758
|
|
@ -62,6 +62,7 @@ RETURNING *;
|
|||
SELECT
|
||||
us.*,
|
||||
sp.name AS plan_name,
|
||||
sp.category AS plan_category,
|
||||
sp.duration_value,
|
||||
sp.duration_unit,
|
||||
sp.price,
|
||||
|
|
@ -104,16 +105,17 @@ SELECT COALESCE(
|
|||
)::text AS subscription_status;
|
||||
|
||||
-- name: GetActiveSubscriptionByUserID :one
|
||||
SELECT
|
||||
SELECT
|
||||
us.*,
|
||||
sp.name AS plan_name,
|
||||
sp.category AS plan_category,
|
||||
sp.duration_value,
|
||||
sp.duration_unit,
|
||||
sp.price,
|
||||
sp.currency
|
||||
FROM user_subscriptions us
|
||||
JOIN subscription_plans sp ON sp.id = us.plan_id
|
||||
WHERE us.user_id = $1
|
||||
WHERE us.user_id = $1
|
||||
AND us.status = 'ACTIVE'
|
||||
AND us.expires_at > CURRENT_TIMESTAMP
|
||||
ORDER BY us.expires_at DESC
|
||||
|
|
|
|||
|
|
@ -253,16 +253,17 @@ func (q *Queries) ExtendSubscription(ctx context.Context, arg ExtendSubscription
|
|||
}
|
||||
|
||||
const GetActiveSubscriptionByUserID = `-- name: GetActiveSubscriptionByUserID :one
|
||||
SELECT
|
||||
SELECT
|
||||
us.id, us.user_id, us.plan_id, us.starts_at, us.expires_at, us.status, us.payment_reference, us.payment_method, us.auto_renew, us.cancelled_at, us.created_at, us.updated_at,
|
||||
sp.name AS plan_name,
|
||||
sp.category AS plan_category,
|
||||
sp.duration_value,
|
||||
sp.duration_unit,
|
||||
sp.price,
|
||||
sp.currency
|
||||
FROM user_subscriptions us
|
||||
JOIN subscription_plans sp ON sp.id = us.plan_id
|
||||
WHERE us.user_id = $1
|
||||
WHERE us.user_id = $1
|
||||
AND us.status = 'ACTIVE'
|
||||
AND us.expires_at > CURRENT_TIMESTAMP
|
||||
ORDER BY us.expires_at DESC
|
||||
|
|
@ -283,6 +284,7 @@ type GetActiveSubscriptionByUserIDRow struct {
|
|||
CreatedAt pgtype.Timestamptz `json:"created_at"`
|
||||
UpdatedAt pgtype.Timestamptz `json:"updated_at"`
|
||||
PlanName string `json:"plan_name"`
|
||||
PlanCategory string `json:"plan_category"`
|
||||
DurationValue int32 `json:"duration_value"`
|
||||
DurationUnit string `json:"duration_unit"`
|
||||
Price pgtype.Numeric `json:"price"`
|
||||
|
|
@ -306,6 +308,7 @@ func (q *Queries) GetActiveSubscriptionByUserID(ctx context.Context, userID int6
|
|||
&i.CreatedAt,
|
||||
&i.UpdatedAt,
|
||||
&i.PlanName,
|
||||
&i.PlanCategory,
|
||||
&i.DurationValue,
|
||||
&i.DurationUnit,
|
||||
&i.Price,
|
||||
|
|
@ -490,6 +493,7 @@ const GetUserSubscriptionByID = `-- name: GetUserSubscriptionByID :one
|
|||
SELECT
|
||||
us.id, us.user_id, us.plan_id, us.starts_at, us.expires_at, us.status, us.payment_reference, us.payment_method, us.auto_renew, us.cancelled_at, us.created_at, us.updated_at,
|
||||
sp.name AS plan_name,
|
||||
sp.category AS plan_category,
|
||||
sp.duration_value,
|
||||
sp.duration_unit,
|
||||
sp.price,
|
||||
|
|
@ -513,6 +517,7 @@ type GetUserSubscriptionByIDRow struct {
|
|||
CreatedAt pgtype.Timestamptz `json:"created_at"`
|
||||
UpdatedAt pgtype.Timestamptz `json:"updated_at"`
|
||||
PlanName string `json:"plan_name"`
|
||||
PlanCategory string `json:"plan_category"`
|
||||
DurationValue int32 `json:"duration_value"`
|
||||
DurationUnit string `json:"duration_unit"`
|
||||
Price pgtype.Numeric `json:"price"`
|
||||
|
|
@ -536,6 +541,7 @@ func (q *Queries) GetUserSubscriptionByID(ctx context.Context, id int64) (GetUse
|
|||
&i.CreatedAt,
|
||||
&i.UpdatedAt,
|
||||
&i.PlanName,
|
||||
&i.PlanCategory,
|
||||
&i.DurationValue,
|
||||
&i.DurationUnit,
|
||||
&i.Price,
|
||||
|
|
|
|||
|
|
@ -566,6 +566,86 @@ func ValidateDynamicPayloadAgainstDefinition(payload DynamicQuestionPayload, def
|
|||
return fmt.Errorf("%s", strings.Join(errs, "; "))
|
||||
}
|
||||
|
||||
func isTimerComponentKind(kind string) bool {
|
||||
switch strings.TrimSpace(kind) {
|
||||
case string(StimulusPrepTime), string(ResponseAnswerTimer):
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func parseNonNegativeIntValue(raw interface{}) (int, bool) {
|
||||
switch v := raw.(type) {
|
||||
case float64:
|
||||
if v >= 0 && v == float64(int(v)) {
|
||||
return int(v), true
|
||||
}
|
||||
case int:
|
||||
if v >= 0 {
|
||||
return v, true
|
||||
}
|
||||
case int32:
|
||||
if v >= 0 {
|
||||
return int(v), true
|
||||
}
|
||||
case int64:
|
||||
if v >= 0 {
|
||||
return int(v), true
|
||||
}
|
||||
case string:
|
||||
t := strings.TrimSpace(v)
|
||||
if t == "" {
|
||||
return 0, false
|
||||
}
|
||||
var n int
|
||||
if _, err := fmt.Sscanf(t, "%d", &n); err == nil && n >= 0 {
|
||||
return n, true
|
||||
}
|
||||
}
|
||||
return 0, false
|
||||
}
|
||||
|
||||
// normalizeTimerElementValue coerces PREP_TIME / ANSWER_TIMER values to { "seconds": N }.
|
||||
func normalizeTimerElementValue(value interface{}) interface{} {
|
||||
if value == nil {
|
||||
return map[string]interface{}{"seconds": 0}
|
||||
}
|
||||
if m, ok := value.(map[string]interface{}); ok {
|
||||
if seconds, ok := parseNonNegativeIntValue(m["seconds"]); ok {
|
||||
return map[string]interface{}{"seconds": seconds}
|
||||
}
|
||||
}
|
||||
if seconds, ok := parseNonNegativeIntValue(value); ok {
|
||||
return map[string]interface{}{"seconds": seconds}
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
// NormalizeDynamicQuestionPayload canonicalizes known structured slot values before persistence.
|
||||
func NormalizeDynamicQuestionPayload(payload *DynamicQuestionPayload) *DynamicQuestionPayload {
|
||||
if payload == nil {
|
||||
return nil
|
||||
}
|
||||
normalizeSide := func(slots []DynamicElementInstance) []DynamicElementInstance {
|
||||
if len(slots) == 0 {
|
||||
return slots
|
||||
}
|
||||
out := make([]DynamicElementInstance, len(slots))
|
||||
for i, el := range slots {
|
||||
out[i] = el
|
||||
if isTimerComponentKind(el.Kind) {
|
||||
out[i].Value = normalizeTimerElementValue(el.Value)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
return &DynamicQuestionPayload{
|
||||
Stimulus: normalizeSide(payload.Stimulus),
|
||||
Response: normalizeSide(payload.Response),
|
||||
}
|
||||
}
|
||||
|
||||
func isMultipleChoiceComponentKind(kind string) bool {
|
||||
switch strings.TrimSpace(kind) {
|
||||
case string(ResponseMultipleChoice), string(ResponseOption):
|
||||
|
|
|
|||
|
|
@ -317,6 +317,41 @@ func TestValidateDynamicPayloadAgainstDefinition_optionDuplicateOptionID(t *test
|
|||
}
|
||||
}
|
||||
|
||||
func TestNormalizeDynamicQuestionPayload_timerStringValue(t *testing.T) {
|
||||
payload := &DynamicQuestionPayload{
|
||||
Response: []DynamicElementInstance{
|
||||
{ID: "answer_timer_1", Kind: "ANSWER_TIMER", Value: "30"},
|
||||
},
|
||||
}
|
||||
got := NormalizeDynamicQuestionPayload(payload)
|
||||
if got == nil || len(got.Response) != 1 {
|
||||
t.Fatalf("expected normalized payload, got %#v", got)
|
||||
}
|
||||
m, ok := got.Response[0].Value.(map[string]interface{})
|
||||
if !ok {
|
||||
t.Fatalf("expected object value, got %#v", got.Response[0].Value)
|
||||
}
|
||||
if m["seconds"] != 30 && m["seconds"] != float64(30) && m["seconds"] != int(30) {
|
||||
t.Fatalf("expected seconds 30, got %#v", m["seconds"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeDynamicQuestionPayload_timerObjectValue(t *testing.T) {
|
||||
payload := &DynamicQuestionPayload{
|
||||
Stimulus: []DynamicElementInstance{
|
||||
{ID: "prep_time_1", Kind: "PREP_TIME", Value: map[string]interface{}{"seconds": 15}},
|
||||
},
|
||||
}
|
||||
got := NormalizeDynamicQuestionPayload(payload)
|
||||
m, ok := got.Stimulus[0].Value.(map[string]interface{})
|
||||
if !ok {
|
||||
t.Fatalf("expected object value, got %#v", got.Stimulus[0].Value)
|
||||
}
|
||||
if m["seconds"] != 15 && m["seconds"] != float64(15) && m["seconds"] != int(15) {
|
||||
t.Fatalf("expected seconds 15, got %#v", m["seconds"])
|
||||
}
|
||||
}
|
||||
|
||||
func testQuestionTypeCatalog() []QuestionTypeDefinition {
|
||||
return []QuestionTypeDefinition{
|
||||
{ID: 1, Key: "multiple_choice", DisplayName: "Multiple Choice", IsSystem: true},
|
||||
|
|
|
|||
|
|
@ -134,25 +134,13 @@ func (s *Store) GetActiveSubscriptionByUserID(ctx context.Context, userID int64)
|
|||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &domain.UserSubscription{
|
||||
ID: sub.ID,
|
||||
UserID: sub.UserID,
|
||||
PlanID: sub.PlanID,
|
||||
StartsAt: sub.StartsAt.Time,
|
||||
ExpiresAt: sub.ExpiresAt.Time,
|
||||
Status: sub.Status,
|
||||
PaymentReference: fromPgText(sub.PaymentReference),
|
||||
PaymentMethod: fromPgText(sub.PaymentMethod),
|
||||
AutoRenew: sub.AutoRenew,
|
||||
CancelledAt: timePtr(sub.CancelledAt),
|
||||
CreatedAt: sub.CreatedAt.Time,
|
||||
UpdatedAt: timePtr(sub.UpdatedAt),
|
||||
PlanName: &sub.PlanName,
|
||||
DurationValue: &sub.DurationValue,
|
||||
DurationUnit: &sub.DurationUnit,
|
||||
Price: float64Ptr(fromPgNumeric(sub.Price)),
|
||||
Currency: &sub.Currency,
|
||||
}, nil
|
||||
out := mapUserSubscriptionPlanJoinRow(
|
||||
sub.ID, sub.UserID, sub.PlanID, sub.StartsAt, sub.ExpiresAt, sub.Status,
|
||||
sub.PaymentReference, sub.PaymentMethod, sub.AutoRenew, sub.CancelledAt,
|
||||
sub.CreatedAt, sub.UpdatedAt, sub.PlanName, sub.PlanCategory,
|
||||
sub.DurationValue, sub.DurationUnit, sub.Price, sub.Currency,
|
||||
)
|
||||
return &out, nil
|
||||
}
|
||||
|
||||
func (s *Store) ListSubscriptionDisplayStatusesByUserIDs(ctx context.Context, userIDs []int64) (map[int64]string, error) {
|
||||
|
|
@ -385,7 +373,7 @@ func userSubscriptionWithPlanToDomain(s dbgen.GetUserSubscriptionByIDRow) *domai
|
|||
out := mapUserSubscriptionPlanJoinRow(
|
||||
s.ID, s.UserID, s.PlanID, s.StartsAt, s.ExpiresAt, s.Status,
|
||||
s.PaymentReference, s.PaymentMethod, s.AutoRenew, s.CancelledAt,
|
||||
s.CreatedAt, s.UpdatedAt, s.PlanName, "",
|
||||
s.CreatedAt, s.UpdatedAt, s.PlanName, s.PlanCategory,
|
||||
s.DurationValue, s.DurationUnit, s.Price, s.Currency,
|
||||
)
|
||||
return &out
|
||||
|
|
|
|||
|
|
@ -65,7 +65,7 @@ func buildQuestionInput(
|
|||
effectiveDynamicPayload = existing.DynamicPayload
|
||||
}
|
||||
if item.DynamicPayload != nil {
|
||||
effectiveDynamicPayload = item.DynamicPayload
|
||||
effectiveDynamicPayload = domain.NormalizeDynamicQuestionPayload(item.DynamicPayload)
|
||||
}
|
||||
|
||||
payloadForChecks := effectiveDynamicPayload
|
||||
|
|
|
|||
|
|
@ -222,6 +222,11 @@ func (s *Service) GetActiveSubscription(ctx context.Context, userID int64) (*dom
|
|||
return s.store.GetActiveSubscriptionByUserID(ctx, userID)
|
||||
}
|
||||
|
||||
// GetActiveSubscriptions returns all ACTIVE, non-expired subscriptions for the user (one per category).
|
||||
func (s *Service) GetActiveSubscriptions(ctx context.Context, userID int64) ([]domain.UserSubscription, error) {
|
||||
return s.store.ListActiveSubscriptionsByUserID(ctx, userID)
|
||||
}
|
||||
|
||||
// ListSubscriptionDisplayStatusesForUserIDs returns ACTIVE, PENDING, or Unsubscribed per user_id (admin list).
|
||||
func (s *Service) ListSubscriptionDisplayStatusesForUserIDs(ctx context.Context, userIDs []int64) (map[int64]string, error) {
|
||||
return s.store.ListSubscriptionDisplayStatusesByUserIDs(ctx, userIDs)
|
||||
|
|
|
|||
|
|
@ -74,6 +74,7 @@ type subscriptionRes struct {
|
|||
UserID int64 `json:"user_id"`
|
||||
PlanID int64 `json:"plan_id"`
|
||||
PlanName *string `json:"plan_name,omitempty"`
|
||||
Category *string `json:"category,omitempty"`
|
||||
StartsAt string `json:"starts_at"`
|
||||
ExpiresAt string `json:"expires_at"`
|
||||
Status string `json:"status"`
|
||||
|
|
@ -458,12 +459,11 @@ func (h *Handler) SubscribeWithPayment(c *fiber.Ctx) error {
|
|||
}
|
||||
|
||||
// GetMySubscription godoc
|
||||
// @Summary Get current subscription
|
||||
// @Description Returns the authenticated user's active subscription
|
||||
// @Summary Get active subscriptions
|
||||
// @Description Returns all active subscriptions for the authenticated user (one per plan category)
|
||||
// @Tags subscriptions
|
||||
// @Produce json
|
||||
// @Success 200 {object} domain.Response
|
||||
// @Failure 404 {object} domain.ErrorResponse
|
||||
// @Router /api/v1/subscriptions/me [get]
|
||||
func (h *Handler) GetMySubscription(c *fiber.Ctx) error {
|
||||
userID, ok := c.Locals("user_id").(int64)
|
||||
|
|
@ -473,16 +473,22 @@ func (h *Handler) GetMySubscription(c *fiber.Ctx) error {
|
|||
})
|
||||
}
|
||||
|
||||
sub, err := h.subscriptionsSvc.GetActiveSubscription(c.Context(), userID)
|
||||
subs, err := h.subscriptionsSvc.GetActiveSubscriptions(c.Context(), userID)
|
||||
if err != nil {
|
||||
return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{
|
||||
Message: "No active subscription found",
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
|
||||
Message: "Failed to get subscriptions",
|
||||
Error: err.Error(),
|
||||
})
|
||||
}
|
||||
|
||||
result := make([]subscriptionRes, len(subs))
|
||||
for i, s := range subs {
|
||||
result[i] = *subscriptionToRes(&s)
|
||||
}
|
||||
|
||||
return c.JSON(domain.Response{
|
||||
Message: "Subscription retrieved successfully",
|
||||
Data: subscriptionToRes(sub),
|
||||
Message: "Subscriptions retrieved successfully",
|
||||
Data: result,
|
||||
})
|
||||
}
|
||||
|
||||
|
|
@ -692,6 +698,7 @@ func subscriptionToRes(s *domain.UserSubscription) *subscriptionRes {
|
|||
UserID: s.UserID,
|
||||
PlanID: s.PlanID,
|
||||
PlanName: s.PlanName,
|
||||
Category: s.PlanCategory,
|
||||
StartsAt: s.StartsAt.Format("2006-01-02T15:04:05Z07:00"),
|
||||
ExpiresAt: s.ExpiresAt.Format("2006-01-02T15:04:05Z07:00"),
|
||||
Status: s.Status,
|
||||
|
|
|
|||
Loading…
Reference in New Issue
Block a user