Add free subscription plans and enforce unique billing periods.
Introduce is_free plans with gateway-free checkout enrollment, require positive pricing for paid plans, and block duplicate category plus period combinations including free versus paid. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
parent
e68814c2c5
commit
1eb03b7e03
|
|
@ -0,0 +1 @@
|
||||||
|
DROP INDEX IF EXISTS idx_subscription_plans_category_period;
|
||||||
|
|
@ -0,0 +1,3 @@
|
||||||
|
-- One catalog row per category + billing period (free vs paid is not part of the key).
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS idx_subscription_plans_category_period
|
||||||
|
ON subscription_plans (category, is_lifetime, duration_value, duration_unit);
|
||||||
5
db/migrations/000111_subscription_plan_is_free.down.sql
Normal file
5
db/migrations/000111_subscription_plan_is_free.down.sql
Normal file
|
|
@ -0,0 +1,5 @@
|
||||||
|
ALTER TABLE subscription_plans
|
||||||
|
DROP CONSTRAINT IF EXISTS chk_subscription_plans_free_price;
|
||||||
|
|
||||||
|
ALTER TABLE subscription_plans
|
||||||
|
DROP COLUMN IF EXISTS is_free;
|
||||||
15
db/migrations/000111_subscription_plan_is_free.up.sql
Normal file
15
db/migrations/000111_subscription_plan_is_free.up.sql
Normal file
|
|
@ -0,0 +1,15 @@
|
||||||
|
ALTER TABLE subscription_plans
|
||||||
|
ADD COLUMN IF NOT EXISTS is_free BOOLEAN NOT NULL DEFAULT FALSE;
|
||||||
|
|
||||||
|
-- Legacy zero-price rows become explicitly free before the price constraint is enforced.
|
||||||
|
UPDATE subscription_plans
|
||||||
|
SET is_free = TRUE
|
||||||
|
WHERE price = 0
|
||||||
|
AND is_free = FALSE;
|
||||||
|
|
||||||
|
ALTER TABLE subscription_plans
|
||||||
|
ADD CONSTRAINT chk_subscription_plans_free_price
|
||||||
|
CHECK (
|
||||||
|
(is_free = TRUE AND price = 0)
|
||||||
|
OR (is_free = FALSE AND price > 0)
|
||||||
|
);
|
||||||
|
|
@ -4,14 +4,28 @@
|
||||||
|
|
||||||
-- name: CreateSubscriptionPlan :one
|
-- name: CreateSubscriptionPlan :one
|
||||||
INSERT INTO subscription_plans (
|
INSERT INTO subscription_plans (
|
||||||
name, description, category, duration_value, duration_unit, price, currency, is_lifetime, is_active
|
name, description, category, duration_value, duration_unit, price, currency, is_lifetime, is_free, is_active
|
||||||
)
|
)
|
||||||
VALUES ($1, $2, $3, $4, $5, $6, $7, COALESCE($8, false), COALESCE($9, true))
|
VALUES ($1, $2, $3, $4, $5, $6, $7, COALESCE($8, false), COALESCE($9, false), COALESCE($10, true))
|
||||||
RETURNING *;
|
RETURNING *;
|
||||||
|
|
||||||
-- name: GetSubscriptionPlanByID :one
|
-- name: GetSubscriptionPlanByID :one
|
||||||
SELECT * FROM subscription_plans WHERE id = $1;
|
SELECT * FROM subscription_plans WHERE id = $1;
|
||||||
|
|
||||||
|
-- name: SubscriptionPlanExistsWithCategoryPeriod :one
|
||||||
|
SELECT EXISTS(
|
||||||
|
SELECT 1
|
||||||
|
FROM subscription_plans
|
||||||
|
WHERE category = $1
|
||||||
|
AND is_lifetime = $2
|
||||||
|
AND duration_value = $3
|
||||||
|
AND duration_unit = $4
|
||||||
|
AND (
|
||||||
|
sqlc.narg('exclude_plan_id')::bigint IS NULL
|
||||||
|
OR id <> sqlc.narg('exclude_plan_id')::bigint
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
-- name: ListSubscriptionPlans :many
|
-- name: ListSubscriptionPlans :many
|
||||||
SELECT * FROM subscription_plans
|
SELECT * FROM subscription_plans
|
||||||
WHERE (
|
WHERE (
|
||||||
|
|
@ -41,6 +55,7 @@ SET
|
||||||
price = COALESCE(sqlc.narg('price')::numeric, price),
|
price = COALESCE(sqlc.narg('price')::numeric, price),
|
||||||
currency = COALESCE(sqlc.narg('currency')::varchar, currency),
|
currency = COALESCE(sqlc.narg('currency')::varchar, currency),
|
||||||
is_lifetime = COALESCE(sqlc.narg('is_lifetime')::boolean, is_lifetime),
|
is_lifetime = COALESCE(sqlc.narg('is_lifetime')::boolean, is_lifetime),
|
||||||
|
is_free = COALESCE(sqlc.narg('is_free')::boolean, is_free),
|
||||||
is_active = COALESCE(sqlc.narg('is_active')::boolean, is_active),
|
is_active = COALESCE(sqlc.narg('is_active')::boolean, is_active),
|
||||||
updated_at = CURRENT_TIMESTAMP
|
updated_at = CURRENT_TIMESTAMP
|
||||||
WHERE id = sqlc.arg('id');
|
WHERE id = sqlc.arg('id');
|
||||||
|
|
|
||||||
|
|
@ -553,6 +553,7 @@ type SubscriptionPlan struct {
|
||||||
UpdatedAt pgtype.Timestamptz `json:"updated_at"`
|
UpdatedAt pgtype.Timestamptz `json:"updated_at"`
|
||||||
Category string `json:"category"`
|
Category string `json:"category"`
|
||||||
IsLifetime bool `json:"is_lifetime"`
|
IsLifetime bool `json:"is_lifetime"`
|
||||||
|
IsFree bool `json:"is_free"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type TeamInvitation struct {
|
type TeamInvitation struct {
|
||||||
|
|
|
||||||
|
|
@ -123,10 +123,10 @@ func (q *Queries) CountUserSubscriptionsByPlanID(ctx context.Context, planID int
|
||||||
const CreateSubscriptionPlan = `-- name: CreateSubscriptionPlan :one
|
const CreateSubscriptionPlan = `-- name: CreateSubscriptionPlan :one
|
||||||
|
|
||||||
INSERT INTO subscription_plans (
|
INSERT INTO subscription_plans (
|
||||||
name, description, category, duration_value, duration_unit, price, currency, is_lifetime, is_active
|
name, description, category, duration_value, duration_unit, price, currency, is_lifetime, is_free, is_active
|
||||||
)
|
)
|
||||||
VALUES ($1, $2, $3, $4, $5, $6, $7, COALESCE($8, false), COALESCE($9, true))
|
VALUES ($1, $2, $3, $4, $5, $6, $7, COALESCE($8, false), COALESCE($9, false), COALESCE($10, true))
|
||||||
RETURNING id, name, description, duration_value, duration_unit, price, currency, is_active, created_at, updated_at, category, is_lifetime
|
RETURNING id, name, description, duration_value, duration_unit, price, currency, is_active, created_at, updated_at, category, is_lifetime, is_free
|
||||||
`
|
`
|
||||||
|
|
||||||
type CreateSubscriptionPlanParams struct {
|
type CreateSubscriptionPlanParams struct {
|
||||||
|
|
@ -139,6 +139,7 @@ type CreateSubscriptionPlanParams struct {
|
||||||
Currency string `json:"currency"`
|
Currency string `json:"currency"`
|
||||||
Column8 interface{} `json:"column_8"`
|
Column8 interface{} `json:"column_8"`
|
||||||
Column9 interface{} `json:"column_9"`
|
Column9 interface{} `json:"column_9"`
|
||||||
|
Column10 interface{} `json:"column_10"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// =====================
|
// =====================
|
||||||
|
|
@ -155,6 +156,7 @@ func (q *Queries) CreateSubscriptionPlan(ctx context.Context, arg CreateSubscrip
|
||||||
arg.Currency,
|
arg.Currency,
|
||||||
arg.Column8,
|
arg.Column8,
|
||||||
arg.Column9,
|
arg.Column9,
|
||||||
|
arg.Column10,
|
||||||
)
|
)
|
||||||
var i SubscriptionPlan
|
var i SubscriptionPlan
|
||||||
err := row.Scan(
|
err := row.Scan(
|
||||||
|
|
@ -170,6 +172,7 @@ func (q *Queries) CreateSubscriptionPlan(ctx context.Context, arg CreateSubscrip
|
||||||
&i.UpdatedAt,
|
&i.UpdatedAt,
|
||||||
&i.Category,
|
&i.Category,
|
||||||
&i.IsLifetime,
|
&i.IsLifetime,
|
||||||
|
&i.IsFree,
|
||||||
)
|
)
|
||||||
return i, err
|
return i, err
|
||||||
}
|
}
|
||||||
|
|
@ -484,7 +487,7 @@ func (q *Queries) GetSubscriptionDisplayStatusByUserID(ctx context.Context, user
|
||||||
}
|
}
|
||||||
|
|
||||||
const GetSubscriptionPlanByID = `-- name: GetSubscriptionPlanByID :one
|
const GetSubscriptionPlanByID = `-- name: GetSubscriptionPlanByID :one
|
||||||
SELECT id, name, description, duration_value, duration_unit, price, currency, is_active, created_at, updated_at, category, is_lifetime FROM subscription_plans WHERE id = $1
|
SELECT id, name, description, duration_value, duration_unit, price, currency, is_active, created_at, updated_at, category, is_lifetime, is_free FROM subscription_plans WHERE id = $1
|
||||||
`
|
`
|
||||||
|
|
||||||
func (q *Queries) GetSubscriptionPlanByID(ctx context.Context, id int64) (SubscriptionPlan, error) {
|
func (q *Queries) GetSubscriptionPlanByID(ctx context.Context, id int64) (SubscriptionPlan, error) {
|
||||||
|
|
@ -503,6 +506,7 @@ func (q *Queries) GetSubscriptionPlanByID(ctx context.Context, id int64) (Subscr
|
||||||
&i.UpdatedAt,
|
&i.UpdatedAt,
|
||||||
&i.Category,
|
&i.Category,
|
||||||
&i.IsLifetime,
|
&i.IsLifetime,
|
||||||
|
&i.IsFree,
|
||||||
)
|
)
|
||||||
return i, err
|
return i, err
|
||||||
}
|
}
|
||||||
|
|
@ -698,7 +702,7 @@ func (q *Queries) HasActiveSubscriptionByCategory(ctx context.Context, arg HasAc
|
||||||
}
|
}
|
||||||
|
|
||||||
const ListActiveSubscriptionPlans = `-- name: ListActiveSubscriptionPlans :many
|
const ListActiveSubscriptionPlans = `-- name: ListActiveSubscriptionPlans :many
|
||||||
SELECT id, name, description, duration_value, duration_unit, price, currency, is_active, created_at, updated_at, category, is_lifetime FROM subscription_plans
|
SELECT id, name, description, duration_value, duration_unit, price, currency, is_active, created_at, updated_at, category, is_lifetime, is_free FROM subscription_plans
|
||||||
WHERE is_active = true
|
WHERE is_active = true
|
||||||
ORDER BY price ASC
|
ORDER BY price ASC
|
||||||
`
|
`
|
||||||
|
|
@ -725,6 +729,7 @@ func (q *Queries) ListActiveSubscriptionPlans(ctx context.Context) ([]Subscripti
|
||||||
&i.UpdatedAt,
|
&i.UpdatedAt,
|
||||||
&i.Category,
|
&i.Category,
|
||||||
&i.IsLifetime,
|
&i.IsLifetime,
|
||||||
|
&i.IsFree,
|
||||||
); err != nil {
|
); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
@ -993,7 +998,7 @@ func (q *Queries) ListSubscriptionDisplayStatusesByUserIDs(ctx context.Context,
|
||||||
}
|
}
|
||||||
|
|
||||||
const ListSubscriptionPlans = `-- name: ListSubscriptionPlans :many
|
const ListSubscriptionPlans = `-- name: ListSubscriptionPlans :many
|
||||||
SELECT id, name, description, duration_value, duration_unit, price, currency, is_active, created_at, updated_at, category, is_lifetime FROM subscription_plans
|
SELECT id, name, description, duration_value, duration_unit, price, currency, is_active, created_at, updated_at, category, is_lifetime, is_free FROM subscription_plans
|
||||||
WHERE (
|
WHERE (
|
||||||
$1::boolean IS NULL
|
$1::boolean IS NULL
|
||||||
OR $1::boolean = false
|
OR $1::boolean = false
|
||||||
|
|
@ -1033,6 +1038,7 @@ func (q *Queries) ListSubscriptionPlans(ctx context.Context, arg ListSubscriptio
|
||||||
&i.UpdatedAt,
|
&i.UpdatedAt,
|
||||||
&i.Category,
|
&i.Category,
|
||||||
&i.IsLifetime,
|
&i.IsLifetime,
|
||||||
|
&i.IsFree,
|
||||||
); err != nil {
|
); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
@ -1193,6 +1199,42 @@ func (q *Queries) SetLifetimeExpiresForActiveSubscriptionsByPlanID(ctx context.C
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const SubscriptionPlanExistsWithCategoryPeriod = `-- name: SubscriptionPlanExistsWithCategoryPeriod :one
|
||||||
|
SELECT EXISTS(
|
||||||
|
SELECT 1
|
||||||
|
FROM subscription_plans
|
||||||
|
WHERE category = $1
|
||||||
|
AND is_lifetime = $2
|
||||||
|
AND duration_value = $3
|
||||||
|
AND duration_unit = $4
|
||||||
|
AND (
|
||||||
|
$5::bigint IS NULL
|
||||||
|
OR id <> $5::bigint
|
||||||
|
)
|
||||||
|
)
|
||||||
|
`
|
||||||
|
|
||||||
|
type SubscriptionPlanExistsWithCategoryPeriodParams struct {
|
||||||
|
Category string `json:"category"`
|
||||||
|
IsLifetime bool `json:"is_lifetime"`
|
||||||
|
DurationValue int32 `json:"duration_value"`
|
||||||
|
DurationUnit string `json:"duration_unit"`
|
||||||
|
ExcludePlanID pgtype.Int8 `json:"exclude_plan_id"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (q *Queries) SubscriptionPlanExistsWithCategoryPeriod(ctx context.Context, arg SubscriptionPlanExistsWithCategoryPeriodParams) (bool, error) {
|
||||||
|
row := q.db.QueryRow(ctx, SubscriptionPlanExistsWithCategoryPeriod,
|
||||||
|
arg.Category,
|
||||||
|
arg.IsLifetime,
|
||||||
|
arg.DurationValue,
|
||||||
|
arg.DurationUnit,
|
||||||
|
arg.ExcludePlanID,
|
||||||
|
)
|
||||||
|
var exists bool
|
||||||
|
err := row.Scan(&exists)
|
||||||
|
return exists, err
|
||||||
|
}
|
||||||
|
|
||||||
const UpdateAutoRenew = `-- name: UpdateAutoRenew :exec
|
const UpdateAutoRenew = `-- name: UpdateAutoRenew :exec
|
||||||
UPDATE user_subscriptions
|
UPDATE user_subscriptions
|
||||||
SET
|
SET
|
||||||
|
|
@ -1222,9 +1264,10 @@ SET
|
||||||
price = COALESCE($6::numeric, price),
|
price = COALESCE($6::numeric, price),
|
||||||
currency = COALESCE($7::varchar, currency),
|
currency = COALESCE($7::varchar, currency),
|
||||||
is_lifetime = COALESCE($8::boolean, is_lifetime),
|
is_lifetime = COALESCE($8::boolean, is_lifetime),
|
||||||
is_active = COALESCE($9::boolean, is_active),
|
is_free = COALESCE($9::boolean, is_free),
|
||||||
|
is_active = COALESCE($10::boolean, is_active),
|
||||||
updated_at = CURRENT_TIMESTAMP
|
updated_at = CURRENT_TIMESTAMP
|
||||||
WHERE id = $10
|
WHERE id = $11
|
||||||
`
|
`
|
||||||
|
|
||||||
type UpdateSubscriptionPlanParams struct {
|
type UpdateSubscriptionPlanParams struct {
|
||||||
|
|
@ -1236,6 +1279,7 @@ type UpdateSubscriptionPlanParams struct {
|
||||||
Price pgtype.Numeric `json:"price"`
|
Price pgtype.Numeric `json:"price"`
|
||||||
Currency pgtype.Text `json:"currency"`
|
Currency pgtype.Text `json:"currency"`
|
||||||
IsLifetime pgtype.Bool `json:"is_lifetime"`
|
IsLifetime pgtype.Bool `json:"is_lifetime"`
|
||||||
|
IsFree pgtype.Bool `json:"is_free"`
|
||||||
IsActive pgtype.Bool `json:"is_active"`
|
IsActive pgtype.Bool `json:"is_active"`
|
||||||
ID int64 `json:"id"`
|
ID int64 `json:"id"`
|
||||||
}
|
}
|
||||||
|
|
@ -1250,6 +1294,7 @@ func (q *Queries) UpdateSubscriptionPlan(ctx context.Context, arg UpdateSubscrip
|
||||||
arg.Price,
|
arg.Price,
|
||||||
arg.Currency,
|
arg.Currency,
|
||||||
arg.IsLifetime,
|
arg.IsLifetime,
|
||||||
|
arg.IsFree,
|
||||||
arg.IsActive,
|
arg.IsActive,
|
||||||
arg.ID,
|
arg.ID,
|
||||||
)
|
)
|
||||||
|
|
|
||||||
|
|
@ -121,12 +121,14 @@ type InitiateSubscriptionPaymentRequest struct {
|
||||||
}
|
}
|
||||||
|
|
||||||
type InitiateSubscriptionPaymentResponse struct {
|
type InitiateSubscriptionPaymentResponse struct {
|
||||||
PaymentID int64 `json:"payment_id"`
|
PaymentID int64 `json:"payment_id,omitempty"`
|
||||||
SessionID string `json:"session_id"`
|
SessionID string `json:"session_id,omitempty"`
|
||||||
PaymentURL string `json:"payment_url"`
|
PaymentURL string `json:"payment_url,omitempty"`
|
||||||
Amount float64 `json:"amount"`
|
Amount float64 `json:"amount,omitempty"`
|
||||||
Currency string `json:"currency"`
|
Currency string `json:"currency,omitempty"`
|
||||||
ExpiresAt string `json:"expires_at"`
|
ExpiresAt string `json:"expires_at,omitempty"`
|
||||||
|
FreeEnrollment bool `json:"free_enrollment,omitempty"`
|
||||||
|
SubscriptionID int64 `json:"subscription_id,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type VerifyPaymentRequest struct {
|
type VerifyPaymentRequest struct {
|
||||||
|
|
|
||||||
|
|
@ -1,10 +1,18 @@
|
||||||
package domain
|
package domain
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"errors"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
ErrFreePlanMustHaveZeroPrice = errors.New("free plans must have price 0")
|
||||||
|
ErrPaidPlanMustHavePositivePrice = errors.New("paid plans must have price greater than 0")
|
||||||
|
// ErrDuplicateSubscriptionPlanPeriod: only one plan (free or paid) per category + billing period.
|
||||||
|
ErrDuplicateSubscriptionPlanPeriod = errors.New("a subscription plan already exists for this category and billing period")
|
||||||
|
)
|
||||||
|
|
||||||
type SubscriptionCategory string
|
type SubscriptionCategory string
|
||||||
|
|
||||||
const (
|
const (
|
||||||
|
|
@ -108,6 +116,7 @@ type SubscriptionPlan struct {
|
||||||
Price float64
|
Price float64
|
||||||
Currency string
|
Currency string
|
||||||
IsLifetime bool
|
IsLifetime bool
|
||||||
|
IsFree bool
|
||||||
IsActive bool
|
IsActive bool
|
||||||
CreatedAt time.Time
|
CreatedAt time.Time
|
||||||
UpdatedAt *time.Time
|
UpdatedAt *time.Time
|
||||||
|
|
@ -145,6 +154,7 @@ type CreateSubscriptionPlanInput struct {
|
||||||
Price float64
|
Price float64
|
||||||
Currency string
|
Currency string
|
||||||
IsLifetime bool
|
IsLifetime bool
|
||||||
|
IsFree bool
|
||||||
IsActive *bool
|
IsActive *bool
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -157,9 +167,24 @@ type UpdateSubscriptionPlanInput struct {
|
||||||
Price *float64
|
Price *float64
|
||||||
Currency *string
|
Currency *string
|
||||||
IsLifetime *bool
|
IsLifetime *bool
|
||||||
|
IsFree *bool
|
||||||
IsActive *bool
|
IsActive *bool
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// NormalizeSubscriptionPlanPricing enforces free vs paid pricing rules.
|
||||||
|
func NormalizeSubscriptionPlanPricing(isFree bool, price float64) (bool, float64, error) {
|
||||||
|
if isFree {
|
||||||
|
if price > 0 {
|
||||||
|
return false, 0, ErrFreePlanMustHaveZeroPrice
|
||||||
|
}
|
||||||
|
return true, 0, nil
|
||||||
|
}
|
||||||
|
if price <= 0 {
|
||||||
|
return false, 0, ErrPaidPlanMustHavePositivePrice
|
||||||
|
}
|
||||||
|
return false, price, nil
|
||||||
|
}
|
||||||
|
|
||||||
type CreateUserSubscriptionInput struct {
|
type CreateUserSubscriptionInput struct {
|
||||||
UserID int64
|
UserID int64
|
||||||
PlanID int64
|
PlanID int64
|
||||||
|
|
@ -215,7 +240,72 @@ func NormalizeLifetimePlanCreateDuration(isLifetime bool, durationValue int32, d
|
||||||
if isLifetime {
|
if isLifetime {
|
||||||
return LifetimeDurationValue, LifetimeDurationUnit
|
return LifetimeDurationValue, LifetimeDurationUnit
|
||||||
}
|
}
|
||||||
return durationValue, durationUnit
|
return durationValue, strings.ToUpper(strings.TrimSpace(durationUnit))
|
||||||
|
}
|
||||||
|
|
||||||
|
// SubscriptionPlanPeriod identifies a plan's category and billing period (price-independent).
|
||||||
|
type SubscriptionPlanPeriod struct {
|
||||||
|
Category string
|
||||||
|
IsLifetime bool
|
||||||
|
DurationValue int32
|
||||||
|
DurationUnit string
|
||||||
|
}
|
||||||
|
|
||||||
|
func SubscriptionPlanPeriodFromCreate(input CreateSubscriptionPlanInput) SubscriptionPlanPeriod {
|
||||||
|
return subscriptionPlanPeriod(
|
||||||
|
input.Category,
|
||||||
|
input.IsLifetime,
|
||||||
|
input.DurationValue,
|
||||||
|
input.DurationUnit,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
func SubscriptionPlanPeriodFromPlan(plan SubscriptionPlan) SubscriptionPlanPeriod {
|
||||||
|
return subscriptionPlanPeriod(
|
||||||
|
plan.Category,
|
||||||
|
plan.IsLifetime,
|
||||||
|
plan.DurationValue,
|
||||||
|
plan.DurationUnit,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
func SubscriptionPlanPeriodFromUpdate(existing SubscriptionPlan, input UpdateSubscriptionPlanInput) SubscriptionPlanPeriod {
|
||||||
|
category := existing.Category
|
||||||
|
if input.Category != nil {
|
||||||
|
category = *input.Category
|
||||||
|
}
|
||||||
|
isLifetime := existing.IsLifetime
|
||||||
|
if input.IsLifetime != nil {
|
||||||
|
isLifetime = *input.IsLifetime
|
||||||
|
}
|
||||||
|
durationValue := existing.DurationValue
|
||||||
|
if input.DurationValue != nil {
|
||||||
|
durationValue = *input.DurationValue
|
||||||
|
}
|
||||||
|
durationUnit := existing.DurationUnit
|
||||||
|
if input.DurationUnit != nil {
|
||||||
|
durationUnit = *input.DurationUnit
|
||||||
|
}
|
||||||
|
return subscriptionPlanPeriod(category, isLifetime, durationValue, durationUnit)
|
||||||
|
}
|
||||||
|
|
||||||
|
func subscriptionPlanPeriod(category string, isLifetime bool, durationValue int32, durationUnit string) SubscriptionPlanPeriod {
|
||||||
|
dv, du := NormalizeLifetimePlanCreateDuration(isLifetime, durationValue, durationUnit)
|
||||||
|
return SubscriptionPlanPeriod{
|
||||||
|
Category: normalizeSubscriptionCategory(category),
|
||||||
|
IsLifetime: isLifetime,
|
||||||
|
DurationValue: dv,
|
||||||
|
DurationUnit: du,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// SameSubscriptionPlanPeriod reports whether two plans share category and billing period
|
||||||
|
// (is_free and price are ignored — free and paid plans cannot coexist for the same period).
|
||||||
|
func SameSubscriptionPlanPeriod(a, b SubscriptionPlanPeriod) bool {
|
||||||
|
return a.Category == b.Category &&
|
||||||
|
a.IsLifetime == b.IsLifetime &&
|
||||||
|
a.DurationValue == b.DurationValue &&
|
||||||
|
a.DurationUnit == b.DurationUnit
|
||||||
}
|
}
|
||||||
|
|
||||||
// CalculateSubscriptionExpiresAt returns when a subscription ends.
|
// CalculateSubscriptionExpiresAt returns when a subscription ends.
|
||||||
|
|
|
||||||
|
|
@ -40,6 +40,66 @@ func TestNormalizeLifetimePlanCreateDuration(t *testing.T) {
|
||||||
if v != 3 || u != "MONTH" {
|
if v != 3 || u != "MONTH" {
|
||||||
t.Fatalf("got %d %s", v, u)
|
t.Fatalf("got %d %s", v, u)
|
||||||
}
|
}
|
||||||
|
v, u = NormalizeLifetimePlanCreateDuration(false, 3, "month")
|
||||||
|
if v != 3 || u != "MONTH" {
|
||||||
|
t.Fatalf("expected trimmed uppercase unit, got %d %s", v, u)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNormalizeSubscriptionPlanPricing(t *testing.T) {
|
||||||
|
_, price, err := NormalizeSubscriptionPlanPricing(true, 10)
|
||||||
|
if err != ErrFreePlanMustHaveZeroPrice || price != 0 {
|
||||||
|
t.Fatalf("expected free plan price error, got price=%v err=%v", price, err)
|
||||||
|
}
|
||||||
|
isFree, price, err := NormalizeSubscriptionPlanPricing(true, 0)
|
||||||
|
if err != nil || !isFree || price != 0 {
|
||||||
|
t.Fatalf("expected free zero price, got isFree=%v price=%v err=%v", isFree, price, err)
|
||||||
|
}
|
||||||
|
_, _, err = NormalizeSubscriptionPlanPricing(false, 0)
|
||||||
|
if err != ErrPaidPlanMustHavePositivePrice {
|
||||||
|
t.Fatalf("expected paid plan error, got %v", err)
|
||||||
|
}
|
||||||
|
isFree, price, err = NormalizeSubscriptionPlanPricing(false, 99)
|
||||||
|
if err != nil || isFree || price != 99 {
|
||||||
|
t.Fatalf("expected paid plan 99, got isFree=%v price=%v err=%v", isFree, price, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSameSubscriptionPlanPeriod_ignoresFreeVsPaid(t *testing.T) {
|
||||||
|
free := SubscriptionPlanPeriodFromCreate(CreateSubscriptionPlanInput{
|
||||||
|
Category: "LEARN_ENGLISH", IsLifetime: false, DurationValue: 1, DurationUnit: "MONTH", IsFree: true,
|
||||||
|
})
|
||||||
|
paid := SubscriptionPlanPeriodFromCreate(CreateSubscriptionPlanInput{
|
||||||
|
Category: "LEARN_ENGLISH", IsLifetime: false, DurationValue: 1, DurationUnit: "MONTH", IsFree: false, Price: 99,
|
||||||
|
})
|
||||||
|
if !SameSubscriptionPlanPeriod(free, paid) {
|
||||||
|
t.Fatal("free and paid plans with same category and period must conflict")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSubscriptionPlanPeriodFromCreate(t *testing.T) {
|
||||||
|
lifetime := SubscriptionPlanPeriodFromCreate(CreateSubscriptionPlanInput{
|
||||||
|
Category: "learn_english",
|
||||||
|
IsLifetime: true,
|
||||||
|
DurationValue: 6,
|
||||||
|
DurationUnit: "MONTH",
|
||||||
|
})
|
||||||
|
if lifetime.Category != "LEARN_ENGLISH" || !lifetime.IsLifetime {
|
||||||
|
t.Fatalf("unexpected lifetime period: %+v", lifetime)
|
||||||
|
}
|
||||||
|
if lifetime.DurationValue != LifetimeDurationValue || lifetime.DurationUnit != LifetimeDurationUnit {
|
||||||
|
t.Fatalf("lifetime duration not normalized: %+v", lifetime)
|
||||||
|
}
|
||||||
|
|
||||||
|
monthly := SubscriptionPlanPeriodFromCreate(CreateSubscriptionPlanInput{
|
||||||
|
Category: "IELTS",
|
||||||
|
IsLifetime: false,
|
||||||
|
DurationValue: 1,
|
||||||
|
DurationUnit: "MONTH",
|
||||||
|
})
|
||||||
|
if monthly.Category != "IELTS" || monthly.IsLifetime || monthly.DurationValue != 1 || monthly.DurationUnit != "MONTH" {
|
||||||
|
t.Fatalf("unexpected monthly period: %+v", monthly)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestSubscriptionGrantsContentAccess(t *testing.T) {
|
func TestSubscriptionGrantsContentAccess(t *testing.T) {
|
||||||
|
|
|
||||||
|
|
@ -10,6 +10,14 @@ type SubscriptionStore interface {
|
||||||
// Subscription Plans
|
// Subscription Plans
|
||||||
CreateSubscriptionPlan(ctx context.Context, input domain.CreateSubscriptionPlanInput) (*domain.SubscriptionPlan, error)
|
CreateSubscriptionPlan(ctx context.Context, input domain.CreateSubscriptionPlanInput) (*domain.SubscriptionPlan, error)
|
||||||
GetSubscriptionPlanByID(ctx context.Context, id int64) (*domain.SubscriptionPlan, error)
|
GetSubscriptionPlanByID(ctx context.Context, id int64) (*domain.SubscriptionPlan, error)
|
||||||
|
SubscriptionPlanExistsWithCategoryPeriod(
|
||||||
|
ctx context.Context,
|
||||||
|
category string,
|
||||||
|
isLifetime bool,
|
||||||
|
durationValue int32,
|
||||||
|
durationUnit string,
|
||||||
|
excludePlanID int64,
|
||||||
|
) (bool, error)
|
||||||
ListSubscriptionPlans(ctx context.Context, activeOnly bool, category *string) ([]domain.SubscriptionPlan, error)
|
ListSubscriptionPlans(ctx context.Context, activeOnly bool, category *string) ([]domain.SubscriptionPlan, error)
|
||||||
UpdateSubscriptionPlan(ctx context.Context, id int64, input domain.UpdateSubscriptionPlanInput) error
|
UpdateSubscriptionPlan(ctx context.Context, id int64, input domain.UpdateSubscriptionPlanInput) error
|
||||||
DeleteSubscriptionPlan(ctx context.Context, id int64) error
|
DeleteSubscriptionPlan(ctx context.Context, id int64) error
|
||||||
|
|
|
||||||
|
|
@ -51,7 +51,8 @@ func (s *Store) CreateSubscriptionPlan(ctx context.Context, input domain.CreateS
|
||||||
Price: toPgNumeric(input.Price),
|
Price: toPgNumeric(input.Price),
|
||||||
Currency: input.Currency,
|
Currency: input.Currency,
|
||||||
Column8: input.IsLifetime,
|
Column8: input.IsLifetime,
|
||||||
Column9: input.IsActive,
|
Column9: input.IsFree,
|
||||||
|
Column10: input.IsActive,
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
|
|
@ -67,6 +68,27 @@ func (s *Store) GetSubscriptionPlanByID(ctx context.Context, id int64) (*domain.
|
||||||
return subscriptionPlanToDomain(plan), nil
|
return subscriptionPlanToDomain(plan), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (s *Store) SubscriptionPlanExistsWithCategoryPeriod(
|
||||||
|
ctx context.Context,
|
||||||
|
category string,
|
||||||
|
isLifetime bool,
|
||||||
|
durationValue int32,
|
||||||
|
durationUnit string,
|
||||||
|
excludePlanID int64,
|
||||||
|
) (bool, error) {
|
||||||
|
var exclude pgtype.Int8
|
||||||
|
if excludePlanID > 0 {
|
||||||
|
exclude = pgtype.Int8{Int64: excludePlanID, Valid: true}
|
||||||
|
}
|
||||||
|
return s.queries.SubscriptionPlanExistsWithCategoryPeriod(ctx, dbgen.SubscriptionPlanExistsWithCategoryPeriodParams{
|
||||||
|
Category: category,
|
||||||
|
IsLifetime: isLifetime,
|
||||||
|
DurationValue: durationValue,
|
||||||
|
DurationUnit: durationUnit,
|
||||||
|
ExcludePlanID: exclude,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
func (s *Store) ListSubscriptionPlans(ctx context.Context, activeOnly bool, category *string) ([]domain.SubscriptionPlan, error) {
|
func (s *Store) ListSubscriptionPlans(ctx context.Context, activeOnly bool, category *string) ([]domain.SubscriptionPlan, error) {
|
||||||
plans, err := s.queries.ListSubscriptionPlans(ctx, dbgen.ListSubscriptionPlansParams{
|
plans, err := s.queries.ListSubscriptionPlans(ctx, dbgen.ListSubscriptionPlansParams{
|
||||||
ActiveOnly: pgtype.Bool{Bool: activeOnly, Valid: true},
|
ActiveOnly: pgtype.Bool{Bool: activeOnly, Valid: true},
|
||||||
|
|
@ -93,6 +115,7 @@ func (s *Store) UpdateSubscriptionPlan(ctx context.Context, id int64, input doma
|
||||||
Price: numericPtrToNumeric(input.Price),
|
Price: numericPtrToNumeric(input.Price),
|
||||||
Currency: optionalTextUpdate(input.Currency),
|
Currency: optionalTextUpdate(input.Currency),
|
||||||
IsLifetime: optionalBool(input.IsLifetime),
|
IsLifetime: optionalBool(input.IsLifetime),
|
||||||
|
IsFree: optionalBool(input.IsFree),
|
||||||
IsActive: optionalBool(input.IsActive),
|
IsActive: optionalBool(input.IsActive),
|
||||||
ID: id,
|
ID: id,
|
||||||
})
|
})
|
||||||
|
|
@ -357,6 +380,7 @@ func subscriptionPlanToDomain(p dbgen.SubscriptionPlan) *domain.SubscriptionPlan
|
||||||
Price: fromPgNumeric(p.Price),
|
Price: fromPgNumeric(p.Price),
|
||||||
Currency: p.Currency,
|
Currency: p.Currency,
|
||||||
IsLifetime: p.IsLifetime,
|
IsLifetime: p.IsLifetime,
|
||||||
|
IsFree: p.IsFree,
|
||||||
IsActive: p.IsActive,
|
IsActive: p.IsActive,
|
||||||
CreatedAt: p.CreatedAt.Time,
|
CreatedAt: p.CreatedAt.Time,
|
||||||
UpdatedAt: timePtr(p.UpdatedAt),
|
UpdatedAt: timePtr(p.UpdatedAt),
|
||||||
|
|
|
||||||
|
|
@ -72,6 +72,9 @@ func (s *ArifpayService) InitiateSubscriptionPayment(ctx context.Context, userID
|
||||||
if !plan.IsActive {
|
if !plan.IsActive {
|
||||||
return nil, errors.New("subscription plan is not active")
|
return nil, errors.New("subscription plan is not active")
|
||||||
}
|
}
|
||||||
|
if plan.IsFree {
|
||||||
|
return nil, errors.New("free subscription plans do not use the payment gateway")
|
||||||
|
}
|
||||||
|
|
||||||
// Check if user already has an active subscription
|
// Check if user already has an active subscription
|
||||||
hasActive, err := s.subscriptionStore.HasActiveSubscriptionByCategory(ctx, userID, plan.Category)
|
hasActive, err := s.subscriptionStore.HasActiveSubscriptionByCategory(ctx, userID, plan.Category)
|
||||||
|
|
|
||||||
|
|
@ -34,6 +34,9 @@ func (s *Service) prepareSubscriptionPayment(ctx context.Context, userID, planID
|
||||||
if !plan.IsActive {
|
if !plan.IsActive {
|
||||||
return nil, errors.New("subscription plan is not active")
|
return nil, errors.New("subscription plan is not active")
|
||||||
}
|
}
|
||||||
|
if plan.IsFree {
|
||||||
|
return nil, errors.New("free subscription plans do not use the payment gateway")
|
||||||
|
}
|
||||||
|
|
||||||
hasActive, err := s.subscriptionStore.HasActiveSubscriptionByCategory(ctx, userID, plan.Category)
|
hasActive, err := s.subscriptionStore.HasActiveSubscriptionByCategory(ctx, userID, plan.Category)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|
|
||||||
|
|
@ -11,6 +11,7 @@ import (
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/jackc/pgx/v5"
|
"github.com/jackc/pgx/v5"
|
||||||
|
"github.com/jackc/pgx/v5/pgconn"
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
|
|
@ -23,6 +24,9 @@ var (
|
||||||
ErrInvalidExtendInput = errors.New("provide exactly one of new_expires_at, duration_value+duration_unit, or renew_one_period")
|
ErrInvalidExtendInput = errors.New("provide exactly one of new_expires_at, duration_value+duration_unit, or renew_one_period")
|
||||||
ErrExtendExpiresInPast = errors.New("new expiry must be in the future")
|
ErrExtendExpiresInPast = errors.New("new expiry must be in the future")
|
||||||
ErrNotALearner = errors.New("target user is not a learner account")
|
ErrNotALearner = errors.New("target user is not a learner account")
|
||||||
|
ErrDuplicatePlanPeriod = domain.ErrDuplicateSubscriptionPlanPeriod
|
||||||
|
ErrPlanRequiresPayment = errors.New("subscription plan requires payment")
|
||||||
|
ErrFreePlanNoPayment = errors.New("free subscription plans do not use the payment gateway")
|
||||||
)
|
)
|
||||||
|
|
||||||
type Service struct {
|
type Service struct {
|
||||||
|
|
@ -58,10 +62,26 @@ func NewService(store ports.SubscriptionStore, payments ports.PaymentStore) *Ser
|
||||||
// =====================
|
// =====================
|
||||||
|
|
||||||
func (s *Service) CreatePlan(ctx context.Context, input domain.CreateSubscriptionPlanInput) (*domain.SubscriptionPlan, error) {
|
func (s *Service) CreatePlan(ctx context.Context, input domain.CreateSubscriptionPlanInput) (*domain.SubscriptionPlan, error) {
|
||||||
|
var err error
|
||||||
|
input.IsFree, input.Price, err = domain.NormalizeSubscriptionPlanPricing(input.IsFree, input.Price)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
input.DurationValue, input.DurationUnit = domain.NormalizeLifetimePlanCreateDuration(
|
input.DurationValue, input.DurationUnit = domain.NormalizeLifetimePlanCreateDuration(
|
||||||
input.IsLifetime, input.DurationValue, input.DurationUnit,
|
input.IsLifetime, input.DurationValue, input.DurationUnit,
|
||||||
)
|
)
|
||||||
return s.store.CreateSubscriptionPlan(ctx, input)
|
period := domain.SubscriptionPlanPeriodFromCreate(input)
|
||||||
|
if err := s.ensureUniquePlanPeriod(ctx, period, 0); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
plan, err := s.store.CreateSubscriptionPlan(ctx, input)
|
||||||
|
if err != nil {
|
||||||
|
if isDuplicateSubscriptionPlanPeriodErr(err) {
|
||||||
|
return nil, domain.ErrDuplicateSubscriptionPlanPeriod
|
||||||
|
}
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return plan, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Service) GetPlanByID(ctx context.Context, id int64) (*domain.SubscriptionPlan, error) {
|
func (s *Service) GetPlanByID(ctx context.Context, id int64) (*domain.SubscriptionPlan, error) {
|
||||||
|
|
@ -79,7 +99,36 @@ func (s *Service) UpdatePlan(ctx context.Context, id int64, input domain.UpdateS
|
||||||
input.DurationValue = &v
|
input.DurationValue = &v
|
||||||
input.DurationUnit = &u
|
input.DurationUnit = &u
|
||||||
}
|
}
|
||||||
|
existing, err := s.store.GetSubscriptionPlanByID(ctx, id)
|
||||||
|
if err != nil {
|
||||||
|
if errors.Is(err, pgx.ErrNoRows) {
|
||||||
|
return ErrPlanNotFound
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
isFree := existing.IsFree
|
||||||
|
if input.IsFree != nil {
|
||||||
|
isFree = *input.IsFree
|
||||||
|
}
|
||||||
|
price := existing.Price
|
||||||
|
if input.Price != nil {
|
||||||
|
price = *input.Price
|
||||||
|
}
|
||||||
|
normalizedFree, normalizedPrice, err := domain.NormalizeSubscriptionPlanPricing(isFree, price)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
input.IsFree = &normalizedFree
|
||||||
|
input.Price = &normalizedPrice
|
||||||
|
|
||||||
|
period := domain.SubscriptionPlanPeriodFromUpdate(*existing, input)
|
||||||
|
if err := s.ensureUniquePlanPeriod(ctx, period, id); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
if err := s.store.UpdateSubscriptionPlan(ctx, id, input); err != nil {
|
if err := s.store.UpdateSubscriptionPlan(ctx, id, input); err != nil {
|
||||||
|
if isDuplicateSubscriptionPlanPeriodErr(err) {
|
||||||
|
return domain.ErrDuplicateSubscriptionPlanPeriod
|
||||||
|
}
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
if input.IsLifetime != nil && *input.IsLifetime {
|
if input.IsLifetime != nil && *input.IsLifetime {
|
||||||
|
|
@ -90,6 +139,32 @@ func (s *Service) UpdatePlan(ctx context.Context, id int64, input domain.UpdateS
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (s *Service) ensureUniquePlanPeriod(ctx context.Context, period domain.SubscriptionPlanPeriod, excludePlanID int64) error {
|
||||||
|
exists, err := s.store.SubscriptionPlanExistsWithCategoryPeriod(
|
||||||
|
ctx,
|
||||||
|
period.Category,
|
||||||
|
period.IsLifetime,
|
||||||
|
period.DurationValue,
|
||||||
|
period.DurationUnit,
|
||||||
|
excludePlanID,
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if exists {
|
||||||
|
return domain.ErrDuplicateSubscriptionPlanPeriod
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func isDuplicateSubscriptionPlanPeriodErr(err error) bool {
|
||||||
|
var pgErr *pgconn.PgError
|
||||||
|
if !errors.As(err, &pgErr) || pgErr.Code != "23505" {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return pgErr.ConstraintName == "idx_subscription_plans_category_period"
|
||||||
|
}
|
||||||
|
|
||||||
func (s *Service) DeletePlan(ctx context.Context, id int64) error {
|
func (s *Service) DeletePlan(ctx context.Context, id int64) error {
|
||||||
if _, err := s.store.GetSubscriptionPlanByID(ctx, id); err != nil {
|
if _, err := s.store.GetSubscriptionPlanByID(ctx, id); err != nil {
|
||||||
if errors.Is(err, pgx.ErrNoRows) {
|
if errors.Is(err, pgx.ErrNoRows) {
|
||||||
|
|
@ -113,6 +188,25 @@ func (s *Service) DeletePlan(ctx context.Context, id int64) error {
|
||||||
// User Subscriptions
|
// User Subscriptions
|
||||||
// =====================
|
// =====================
|
||||||
|
|
||||||
|
// EnrollFreePlan activates a free subscription plan without a payment gateway.
|
||||||
|
func (s *Service) EnrollFreePlan(ctx context.Context, userID, planID int64) (*domain.UserSubscription, error) {
|
||||||
|
plan, err := s.store.GetSubscriptionPlanByID(ctx, planID)
|
||||||
|
if err != nil {
|
||||||
|
if errors.Is(err, pgx.ErrNoRows) {
|
||||||
|
return nil, ErrPlanNotFound
|
||||||
|
}
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if !plan.IsActive {
|
||||||
|
return nil, ErrInvalidPlan
|
||||||
|
}
|
||||||
|
if !plan.IsFree {
|
||||||
|
return nil, ErrPlanRequiresPayment
|
||||||
|
}
|
||||||
|
method := "FREE"
|
||||||
|
return s.Subscribe(ctx, userID, planID, nil, &method)
|
||||||
|
}
|
||||||
|
|
||||||
// Subscribe creates a new subscription for a user
|
// Subscribe creates a new subscription for a user
|
||||||
func (s *Service) Subscribe(ctx context.Context, userID, planID int64, paymentRef, paymentMethod *string) (*domain.UserSubscription, error) {
|
func (s *Service) Subscribe(ctx context.Context, userID, planID int64, paymentRef, paymentMethod *string) (*domain.UserSubscription, error) {
|
||||||
// Get the plan to calculate expiry
|
// Get the plan to calculate expiry
|
||||||
|
|
|
||||||
|
|
@ -17,6 +17,8 @@ import (
|
||||||
// Subscription Plan Types
|
// Subscription Plan Types
|
||||||
// =====================
|
// =====================
|
||||||
|
|
||||||
|
const duplicateSubscriptionPlanPeriodMessage = "Only one subscription plan is allowed per category and billing period. A free plan and a paid plan cannot coexist for the same period—edit the existing plan or change category or duration."
|
||||||
|
|
||||||
type createPlanReq struct {
|
type createPlanReq struct {
|
||||||
Name string `json:"name" validate:"required"`
|
Name string `json:"name" validate:"required"`
|
||||||
Description *string `json:"description"`
|
Description *string `json:"description"`
|
||||||
|
|
@ -26,6 +28,7 @@ type createPlanReq struct {
|
||||||
Price float64 `json:"price" validate:"gte=0"`
|
Price float64 `json:"price" validate:"gte=0"`
|
||||||
Currency string `json:"currency" validate:"required"`
|
Currency string `json:"currency" validate:"required"`
|
||||||
IsLifetime bool `json:"is_lifetime"`
|
IsLifetime bool `json:"is_lifetime"`
|
||||||
|
IsFree bool `json:"is_free"`
|
||||||
IsActive *bool `json:"is_active"`
|
IsActive *bool `json:"is_active"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -38,6 +41,7 @@ type updatePlanReq struct {
|
||||||
Price *float64 `json:"price"`
|
Price *float64 `json:"price"`
|
||||||
Currency *string `json:"currency"`
|
Currency *string `json:"currency"`
|
||||||
IsLifetime *bool `json:"is_lifetime"`
|
IsLifetime *bool `json:"is_lifetime"`
|
||||||
|
IsFree *bool `json:"is_free"`
|
||||||
IsActive *bool `json:"is_active"`
|
IsActive *bool `json:"is_active"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -51,10 +55,16 @@ type planRes struct {
|
||||||
Price float64 `json:"price"`
|
Price float64 `json:"price"`
|
||||||
Currency string `json:"currency"`
|
Currency string `json:"currency"`
|
||||||
IsLifetime bool `json:"is_lifetime"`
|
IsLifetime bool `json:"is_lifetime"`
|
||||||
|
IsFree bool `json:"is_free"`
|
||||||
IsActive bool `json:"is_active"`
|
IsActive bool `json:"is_active"`
|
||||||
CreatedAt string `json:"created_at"`
|
CreatedAt string `json:"created_at"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type subscriptionCheckoutRes struct {
|
||||||
|
domain.InitiateSubscriptionPaymentResponse
|
||||||
|
Subscription *subscriptionRes `json:"subscription,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
// =====================
|
// =====================
|
||||||
// User Subscription Types
|
// User Subscription Types
|
||||||
// =====================
|
// =====================
|
||||||
|
|
@ -151,9 +161,22 @@ func (h *Handler) CreateSubscriptionPlan(c *fiber.Ctx) error {
|
||||||
Price: req.Price,
|
Price: req.Price,
|
||||||
Currency: req.Currency,
|
Currency: req.Currency,
|
||||||
IsLifetime: req.IsLifetime,
|
IsLifetime: req.IsLifetime,
|
||||||
|
IsFree: req.IsFree,
|
||||||
IsActive: req.IsActive,
|
IsActive: req.IsActive,
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
if errors.Is(err, domain.ErrFreePlanMustHaveZeroPrice) || errors.Is(err, domain.ErrPaidPlanMustHavePositivePrice) {
|
||||||
|
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
|
||||||
|
Message: "Validation failed",
|
||||||
|
Error: err.Error(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
if errors.Is(err, domain.ErrDuplicateSubscriptionPlanPeriod) {
|
||||||
|
return c.Status(fiber.StatusConflict).JSON(domain.ErrorResponse{
|
||||||
|
Message: "Duplicate subscription plan",
|
||||||
|
Error: duplicateSubscriptionPlanPeriodMessage,
|
||||||
|
})
|
||||||
|
}
|
||||||
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
|
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
|
||||||
Message: "Failed to create subscription plan",
|
Message: "Failed to create subscription plan",
|
||||||
Error: err.Error(),
|
Error: err.Error(),
|
||||||
|
|
@ -313,9 +336,27 @@ func (h *Handler) UpdateSubscriptionPlan(c *fiber.Ctx) error {
|
||||||
Price: req.Price,
|
Price: req.Price,
|
||||||
Currency: req.Currency,
|
Currency: req.Currency,
|
||||||
IsLifetime: req.IsLifetime,
|
IsLifetime: req.IsLifetime,
|
||||||
|
IsFree: req.IsFree,
|
||||||
IsActive: req.IsActive,
|
IsActive: req.IsActive,
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
if errors.Is(err, domain.ErrFreePlanMustHaveZeroPrice) || errors.Is(err, domain.ErrPaidPlanMustHavePositivePrice) {
|
||||||
|
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
|
||||||
|
Message: "Validation failed",
|
||||||
|
Error: err.Error(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
if errors.Is(err, subscriptionsvc.ErrPlanNotFound) {
|
||||||
|
return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{
|
||||||
|
Message: "Subscription plan not found",
|
||||||
|
})
|
||||||
|
}
|
||||||
|
if errors.Is(err, domain.ErrDuplicateSubscriptionPlanPeriod) {
|
||||||
|
return c.Status(fiber.StatusConflict).JSON(domain.ErrorResponse{
|
||||||
|
Message: "Duplicate subscription plan",
|
||||||
|
Error: duplicateSubscriptionPlanPeriodMessage,
|
||||||
|
})
|
||||||
|
}
|
||||||
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
|
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
|
||||||
Message: "Failed to update subscription plan",
|
Message: "Failed to update subscription plan",
|
||||||
Error: err.Error(),
|
Error: err.Error(),
|
||||||
|
|
@ -483,6 +524,60 @@ func (h *Handler) SubscribeWithPayment(c *fiber.Ctx) error {
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
plan, err := h.subscriptionsSvc.GetPlanByID(c.Context(), req.PlanID)
|
||||||
|
if err != nil {
|
||||||
|
if errors.Is(err, subscriptionsvc.ErrPlanNotFound) {
|
||||||
|
return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{
|
||||||
|
Message: "Subscription plan not found",
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
|
||||||
|
Message: "Failed to load subscription plan",
|
||||||
|
Error: err.Error(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
if plan.IsFree {
|
||||||
|
sub, enrollErr := h.subscriptionsSvc.EnrollFreePlan(c.Context(), userID, req.PlanID)
|
||||||
|
if enrollErr != nil {
|
||||||
|
status := fiber.StatusInternalServerError
|
||||||
|
message := "Failed to activate free subscription"
|
||||||
|
switch {
|
||||||
|
case errors.Is(enrollErr, subscriptionsvc.ErrAlreadySubscribed):
|
||||||
|
status = fiber.StatusConflict
|
||||||
|
message = "User already has an active subscription for this category"
|
||||||
|
case errors.Is(enrollErr, subscriptionsvc.ErrInvalidPlan):
|
||||||
|
status = fiber.StatusBadRequest
|
||||||
|
message = "Subscription plan is not available"
|
||||||
|
case errors.Is(enrollErr, subscriptionsvc.ErrPlanNotFound):
|
||||||
|
status = fiber.StatusNotFound
|
||||||
|
message = "Subscription plan not found"
|
||||||
|
}
|
||||||
|
return c.Status(status).JSON(domain.ErrorResponse{
|
||||||
|
Message: message,
|
||||||
|
Error: enrollErr.Error(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
if h.learnerNotifSvc != nil {
|
||||||
|
h.learnerNotifSvc.MaybeNotifyLearnPackageSubscribed(userID, plan.Category, plan.Name, sub.ExpiresAt)
|
||||||
|
}
|
||||||
|
|
||||||
|
subID := sub.ID
|
||||||
|
h.recordActivity(c, domain.ActionSubscriptionCreated, domain.ResourceSubscription, &subID, fmt.Sprintf("Activated free subscription plan ID: %d", req.PlanID), nil)
|
||||||
|
|
||||||
|
return c.JSON(domain.Response{
|
||||||
|
Message: "Subscription activated successfully.",
|
||||||
|
Data: subscriptionCheckoutRes{
|
||||||
|
InitiateSubscriptionPaymentResponse: domain.InitiateSubscriptionPaymentResponse{
|
||||||
|
FreeEnrollment: true,
|
||||||
|
SubscriptionID: sub.ID,
|
||||||
|
},
|
||||||
|
Subscription: subscriptionToRes(sub),
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
provider, err := domain.ParsePaymentProvider(req.Provider)
|
provider, err := domain.ParsePaymentProvider(req.Provider)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
|
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
|
||||||
|
|
@ -744,6 +839,7 @@ func planToRes(p *domain.SubscriptionPlan) *planRes {
|
||||||
Price: p.Price,
|
Price: p.Price,
|
||||||
Currency: p.Currency,
|
Currency: p.Currency,
|
||||||
IsLifetime: p.IsLifetime,
|
IsLifetime: p.IsLifetime,
|
||||||
|
IsFree: p.IsFree,
|
||||||
IsActive: p.IsActive,
|
IsActive: p.IsActive,
|
||||||
CreatedAt: p.CreatedAt.Format("2006-01-02T15:04:05Z07:00"),
|
CreatedAt: p.CreatedAt.Format("2006-01-02T15:04:05Z07:00"),
|
||||||
}
|
}
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue
Block a user