feat: create PENDING subscription when payment is initiated
Link checkout payments to a pending subscription row and activate it on success, or cancel it when payment fails, is cancelled, or expires. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
parent
0e0203ab37
commit
4f6c356b6c
|
|
@ -137,6 +137,19 @@ WHERE status = 'PENDING'
|
|||
AND expires_at IS NOT NULL
|
||||
AND expires_at <= CURRENT_TIMESTAMP;
|
||||
|
||||
-- Cancel PENDING subscriptions whose linked payment ended without success.
|
||||
-- name: CancelPendingSubscriptionsForTerminalPayments :execrows
|
||||
UPDATE user_subscriptions us
|
||||
SET
|
||||
status = 'CANCELLED',
|
||||
cancelled_at = CURRENT_TIMESTAMP,
|
||||
auto_renew = false,
|
||||
updated_at = CURRENT_TIMESTAMP
|
||||
FROM payments p
|
||||
WHERE p.subscription_id = us.id
|
||||
AND us.status = 'PENDING'
|
||||
AND p.status IN ('EXPIRED', 'FAILED', 'CANCELLED');
|
||||
|
||||
-- name: CountUserPayments :one
|
||||
SELECT COUNT(*) FROM payments WHERE user_id = $1;
|
||||
|
||||
|
|
|
|||
|
|
@ -167,6 +167,21 @@ SET
|
|||
updated_at = CURRENT_TIMESTAMP
|
||||
WHERE id = $2;
|
||||
|
||||
-- Activate a checkout PENDING subscription after successful payment.
|
||||
-- name: ActivatePendingUserSubscription :one
|
||||
UPDATE user_subscriptions
|
||||
SET
|
||||
status = 'ACTIVE',
|
||||
starts_at = $2,
|
||||
expires_at = $3,
|
||||
payment_reference = COALESCE($4, payment_reference),
|
||||
payment_method = COALESCE($5, payment_method),
|
||||
cancelled_at = NULL,
|
||||
updated_at = CURRENT_TIMESTAMP
|
||||
WHERE id = $1
|
||||
AND status = 'PENDING'
|
||||
RETURNING *;
|
||||
|
||||
-- name: CancelUserSubscription :exec
|
||||
UPDATE user_subscriptions
|
||||
SET
|
||||
|
|
|
|||
|
|
@ -169,7 +169,7 @@ Inactive plans may be selected (`active_only=false` on the plans list).
|
|||
|
||||
| Status | Meaning |
|
||||
|--------|---------|
|
||||
| `PENDING` | Checkout not completed |
|
||||
| `PENDING` | Checkout started; payment not completed yet |
|
||||
| `ACTIVE` | Active (access also requires `expires_at` in the future for "currently active") |
|
||||
| `EXPIRED` | Past expiry |
|
||||
| `CANCELLED` | Admin or learner cancelled |
|
||||
|
|
|
|||
|
|
@ -30,6 +30,28 @@ func (q *Queries) CancelPaymentsBySubscriptionID(ctx context.Context, subscripti
|
|||
return result.RowsAffected(), nil
|
||||
}
|
||||
|
||||
const CancelPendingSubscriptionsForTerminalPayments = `-- name: CancelPendingSubscriptionsForTerminalPayments :execrows
|
||||
UPDATE user_subscriptions us
|
||||
SET
|
||||
status = 'CANCELLED',
|
||||
cancelled_at = CURRENT_TIMESTAMP,
|
||||
auto_renew = false,
|
||||
updated_at = CURRENT_TIMESTAMP
|
||||
FROM payments p
|
||||
WHERE p.subscription_id = us.id
|
||||
AND us.status = 'PENDING'
|
||||
AND p.status IN ('EXPIRED', 'FAILED', 'CANCELLED')
|
||||
`
|
||||
|
||||
// Cancel PENDING subscriptions whose linked payment ended without success.
|
||||
func (q *Queries) CancelPendingSubscriptionsForTerminalPayments(ctx context.Context) (int64, error) {
|
||||
result, err := q.db.Exec(ctx, CancelPendingSubscriptionsForTerminalPayments)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return result.RowsAffected(), nil
|
||||
}
|
||||
|
||||
const CountPaymentsAdmin = `-- name: CountPaymentsAdmin :one
|
||||
SELECT COUNT(*)::bigint AS total
|
||||
FROM payments p
|
||||
|
|
|
|||
|
|
@ -11,6 +11,56 @@ import (
|
|||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
const ActivatePendingUserSubscription = `-- name: ActivatePendingUserSubscription :one
|
||||
UPDATE user_subscriptions
|
||||
SET
|
||||
status = 'ACTIVE',
|
||||
starts_at = $2,
|
||||
expires_at = $3,
|
||||
payment_reference = COALESCE($4, payment_reference),
|
||||
payment_method = COALESCE($5, payment_method),
|
||||
cancelled_at = NULL,
|
||||
updated_at = CURRENT_TIMESTAMP
|
||||
WHERE id = $1
|
||||
AND status = 'PENDING'
|
||||
RETURNING id, user_id, plan_id, starts_at, expires_at, status, payment_reference, payment_method, auto_renew, cancelled_at, created_at, updated_at
|
||||
`
|
||||
|
||||
type ActivatePendingUserSubscriptionParams struct {
|
||||
ID int64 `json:"id"`
|
||||
StartsAt pgtype.Timestamptz `json:"starts_at"`
|
||||
ExpiresAt pgtype.Timestamptz `json:"expires_at"`
|
||||
PaymentReference pgtype.Text `json:"payment_reference"`
|
||||
PaymentMethod pgtype.Text `json:"payment_method"`
|
||||
}
|
||||
|
||||
// Activate a checkout PENDING subscription after successful payment.
|
||||
func (q *Queries) ActivatePendingUserSubscription(ctx context.Context, arg ActivatePendingUserSubscriptionParams) (UserSubscription, error) {
|
||||
row := q.db.QueryRow(ctx, ActivatePendingUserSubscription,
|
||||
arg.ID,
|
||||
arg.StartsAt,
|
||||
arg.ExpiresAt,
|
||||
arg.PaymentReference,
|
||||
arg.PaymentMethod,
|
||||
)
|
||||
var i UserSubscription
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.UserID,
|
||||
&i.PlanID,
|
||||
&i.StartsAt,
|
||||
&i.ExpiresAt,
|
||||
&i.Status,
|
||||
&i.PaymentReference,
|
||||
&i.PaymentMethod,
|
||||
&i.AutoRenew,
|
||||
&i.CancelledAt,
|
||||
&i.CreatedAt,
|
||||
&i.UpdatedAt,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const AdminExtendUserSubscription = `-- name: AdminExtendUserSubscription :exec
|
||||
UPDATE user_subscriptions
|
||||
SET
|
||||
|
|
|
|||
|
|
@ -72,13 +72,14 @@ type PaymentListPage struct {
|
|||
}
|
||||
|
||||
type CreatePaymentInput struct {
|
||||
UserID int64
|
||||
PlanID *int64
|
||||
Amount float64
|
||||
Currency string
|
||||
PaymentMethod *string
|
||||
Nonce string
|
||||
ExpiresAt *time.Time
|
||||
UserID int64
|
||||
PlanID *int64
|
||||
SubscriptionID *int64
|
||||
Amount float64
|
||||
Currency string
|
||||
PaymentMethod *string
|
||||
Nonce string
|
||||
ExpiresAt *time.Time
|
||||
}
|
||||
|
||||
// CreateAdminPaymentInput records an admin-panel payment as SUCCESS at the plan price
|
||||
|
|
|
|||
|
|
@ -26,10 +26,12 @@ type SubscriptionStore interface {
|
|||
HasActiveSubscription(ctx context.Context, userID int64) (bool, error)
|
||||
HasActiveSubscriptionByCategory(ctx context.Context, userID int64, category string) (bool, error)
|
||||
CancelUserSubscription(ctx context.Context, id int64) error
|
||||
ActivatePendingUserSubscription(ctx context.Context, id int64, startsAt, expiresAt time.Time, paymentReference, paymentMethod string) (*domain.UserSubscription, error)
|
||||
UpdateSubscriptionStatus(ctx context.Context, id int64, status string) error
|
||||
UpdateAutoRenew(ctx context.Context, id int64, autoRenew bool) error
|
||||
ExtendSubscription(ctx context.Context, id int64, newExpiresAt time.Time) error
|
||||
AdminExtendUserSubscription(ctx context.Context, id, planID int64, newExpiresAt time.Time) error
|
||||
ListUserSubscriptionsAdmin(ctx context.Context, filter domain.UserSubscriptionAdminFilter) (domain.UserSubscriptionAdminPage, error)
|
||||
ListLearnEnglishSubscriptionsExpiringInSevenDays(ctx context.Context) ([]domain.SubscriptionExpiryReminder, error)
|
||||
CancelPendingSubscriptionsForTerminalPayments(ctx context.Context) (int64, error)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -12,7 +12,7 @@ func (s *Store) CreatePayment(ctx context.Context, input domain.CreatePaymentInp
|
|||
payment, err := s.queries.CreatePayment(ctx, dbgen.CreatePaymentParams{
|
||||
UserID: input.UserID,
|
||||
PlanID: int64PtrToPgInt8(input.PlanID),
|
||||
SubscriptionID: pgtype.Int8{Valid: false},
|
||||
SubscriptionID: int64PtrToPgInt8(input.SubscriptionID),
|
||||
SessionID: pgtype.Text{Valid: false},
|
||||
TransactionID: pgtype.Text{Valid: false},
|
||||
Nonce: input.Nonce,
|
||||
|
|
|
|||
|
|
@ -249,6 +249,29 @@ func (s *Store) CancelUserSubscription(ctx context.Context, id int64) error {
|
|||
return s.queries.CancelUserSubscription(ctx, id)
|
||||
}
|
||||
|
||||
func (s *Store) ActivatePendingUserSubscription(
|
||||
ctx context.Context,
|
||||
id int64,
|
||||
startsAt, expiresAt time.Time,
|
||||
paymentReference, paymentMethod string,
|
||||
) (*domain.UserSubscription, error) {
|
||||
sub, err := s.queries.ActivatePendingUserSubscription(ctx, dbgen.ActivatePendingUserSubscriptionParams{
|
||||
ID: id,
|
||||
StartsAt: toPgTimestamptz(startsAt),
|
||||
ExpiresAt: toPgTimestamptz(expiresAt),
|
||||
PaymentReference: toPgText(&paymentReference),
|
||||
PaymentMethod: toPgText(&paymentMethod),
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return userSubscriptionToDomain(sub), nil
|
||||
}
|
||||
|
||||
func (s *Store) CancelPendingSubscriptionsForTerminalPayments(ctx context.Context) (int64, error) {
|
||||
return s.queries.CancelPendingSubscriptionsForTerminalPayments(ctx)
|
||||
}
|
||||
|
||||
func (s *Store) UpdateSubscriptionStatus(ctx context.Context, id int64, status string) error {
|
||||
return s.queries.UpdateUserSubscriptionStatus(ctx, dbgen.UpdateUserSubscriptionStatusParams{
|
||||
Status: status,
|
||||
|
|
|
|||
|
|
@ -16,6 +16,7 @@ import (
|
|||
"Yimaru-Backend/internal/config"
|
||||
"Yimaru-Backend/internal/domain"
|
||||
"Yimaru-Backend/internal/ports"
|
||||
"Yimaru-Backend/internal/services/checkoutsubscription"
|
||||
learnernotifications "Yimaru-Backend/internal/services/learnernotifications"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
|
@ -84,21 +85,34 @@ func (s *ArifpayService) InitiateSubscriptionPayment(ctx context.Context, userID
|
|||
// Generate unique nonce
|
||||
nonce := uuid.NewString()
|
||||
expiresAt := time.Now().Add(3 * time.Hour)
|
||||
paymentMethod := string(domain.PaymentProviderArifPay)
|
||||
|
||||
pendingSub, err := checkoutsubscription.CreatePending(
|
||||
ctx,
|
||||
s.subscriptionStore,
|
||||
userID,
|
||||
plan,
|
||||
nonce,
|
||||
paymentMethod,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
pendingSubID := pendingSub.ID
|
||||
|
||||
// Create payment record
|
||||
payment, err := s.paymentStore.CreatePayment(ctx, domain.CreatePaymentInput{
|
||||
UserID: userID,
|
||||
PlanID: &req.PlanID,
|
||||
Amount: plan.Price,
|
||||
Currency: plan.Currency,
|
||||
PaymentMethod: func() *string {
|
||||
v := string(domain.PaymentProviderArifPay)
|
||||
return &v
|
||||
}(),
|
||||
Nonce: nonce,
|
||||
ExpiresAt: &expiresAt,
|
||||
UserID: userID,
|
||||
PlanID: &req.PlanID,
|
||||
SubscriptionID: &pendingSubID,
|
||||
Amount: plan.Price,
|
||||
Currency: plan.Currency,
|
||||
PaymentMethod: &paymentMethod,
|
||||
Nonce: nonce,
|
||||
ExpiresAt: &expiresAt,
|
||||
})
|
||||
if err != nil {
|
||||
checkoutsubscription.AbandonPending(ctx, s.subscriptionStore, &pendingSubID)
|
||||
return nil, fmt.Errorf("failed to create payment record: %w", err)
|
||||
}
|
||||
|
||||
|
|
@ -143,6 +157,8 @@ func (s *ArifpayService) InitiateSubscriptionPayment(ctx context.Context, userID
|
|||
// Marshal to JSON
|
||||
payload, err := json.Marshal(checkoutReq)
|
||||
if err != nil {
|
||||
_ = s.paymentStore.UpdatePaymentStatus(ctx, payment.ID, string(domain.PaymentStatusFailed))
|
||||
checkoutsubscription.AbandonPending(ctx, s.subscriptionStore, &pendingSubID)
|
||||
return nil, fmt.Errorf("failed to marshal checkout request: %w", err)
|
||||
}
|
||||
|
||||
|
|
@ -150,6 +166,8 @@ func (s *ArifpayService) InitiateSubscriptionPayment(ctx context.Context, userID
|
|||
url := fmt.Sprintf("%s/api/checkout/session", s.cfg.ARIFPAY.BaseURL)
|
||||
httpReq, err := http.NewRequestWithContext(ctx, "POST", url, bytes.NewBuffer(payload))
|
||||
if err != nil {
|
||||
_ = s.paymentStore.UpdatePaymentStatus(ctx, payment.ID, string(domain.PaymentStatusFailed))
|
||||
checkoutsubscription.AbandonPending(ctx, s.subscriptionStore, &pendingSubID)
|
||||
return nil, err
|
||||
}
|
||||
httpReq.Header.Set("Content-Type", "application/json")
|
||||
|
|
@ -157,26 +175,36 @@ func (s *ArifpayService) InitiateSubscriptionPayment(ctx context.Context, userID
|
|||
|
||||
resp, err := s.httpClient.Do(httpReq)
|
||||
if err != nil {
|
||||
_ = s.paymentStore.UpdatePaymentStatus(ctx, payment.ID, string(domain.PaymentStatusFailed))
|
||||
checkoutsubscription.AbandonPending(ctx, s.subscriptionStore, &pendingSubID)
|
||||
return nil, fmt.Errorf("failed to call ArifPay API: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
_ = s.paymentStore.UpdatePaymentStatus(ctx, payment.ID, string(domain.PaymentStatusFailed))
|
||||
checkoutsubscription.AbandonPending(ctx, s.subscriptionStore, &pendingSubID)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
_ = s.paymentStore.UpdatePaymentStatus(ctx, payment.ID, string(domain.PaymentStatusFailed))
|
||||
checkoutsubscription.AbandonPending(ctx, s.subscriptionStore, &pendingSubID)
|
||||
return nil, fmt.Errorf("ArifPay API error: %s", string(body))
|
||||
}
|
||||
|
||||
var result map[string]interface{}
|
||||
if err := json.Unmarshal(body, &result); err != nil {
|
||||
_ = s.paymentStore.UpdatePaymentStatus(ctx, payment.ID, string(domain.PaymentStatusFailed))
|
||||
checkoutsubscription.AbandonPending(ctx, s.subscriptionStore, &pendingSubID)
|
||||
return nil, fmt.Errorf("invalid response from ArifPay: %w", err)
|
||||
}
|
||||
|
||||
data, ok := result["data"].(map[string]interface{})
|
||||
if !ok {
|
||||
_ = s.paymentStore.UpdatePaymentStatus(ctx, payment.ID, string(domain.PaymentStatusFailed))
|
||||
checkoutsubscription.AbandonPending(ctx, s.subscriptionStore, &pendingSubID)
|
||||
return nil, errors.New("invalid response structure from ArifPay")
|
||||
}
|
||||
|
||||
|
|
@ -261,38 +289,27 @@ func (s *ArifpayService) ProcessPaymentWebhook(ctx context.Context, req domain.W
|
|||
return fmt.Errorf("failed to update payment status: %w", err)
|
||||
}
|
||||
|
||||
// If payment succeeded, create the subscription
|
||||
// If payment succeeded, activate the pending subscription (or create for legacy payments).
|
||||
if newStatus == string(domain.PaymentStatusSuccess) && payment.PlanID != nil {
|
||||
plan, err := s.subscriptionStore.GetSubscriptionPlanByID(ctx, *payment.PlanID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to get subscription plan: %w", err)
|
||||
}
|
||||
|
||||
startsAt := time.Now()
|
||||
expiresAt := domain.CalculateSubscriptionExpiresAt(startsAt, plan.Category, plan.DurationValue, plan.DurationUnit)
|
||||
activeStatus := string(domain.SubscriptionStatusActive)
|
||||
autoRenew := false
|
||||
paymentRef := nonce
|
||||
|
||||
subscription, err := s.subscriptionStore.CreateUserSubscription(ctx, domain.CreateUserSubscriptionInput{
|
||||
UserID: payment.UserID,
|
||||
PlanID: *payment.PlanID,
|
||||
StartsAt: &startsAt,
|
||||
ExpiresAt: expiresAt,
|
||||
Status: &activeStatus,
|
||||
PaymentReference: &paymentRef,
|
||||
PaymentMethod: &paymentMethod,
|
||||
AutoRenew: &autoRenew,
|
||||
})
|
||||
subscription, err := checkoutsubscription.Fulfill(ctx, s.subscriptionStore, payment, plan, paymentMethod)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create subscription: %w", err)
|
||||
return err
|
||||
}
|
||||
|
||||
// Link payment to subscription
|
||||
if err := s.paymentStore.LinkPaymentToSubscription(ctx, payment.ID, subscription.ID); err != nil {
|
||||
return fmt.Errorf("failed to link payment to subscription: %w", err)
|
||||
if payment.SubscriptionID == nil || *payment.SubscriptionID != subscription.ID {
|
||||
if err := s.paymentStore.LinkPaymentToSubscription(ctx, payment.ID, subscription.ID); err != nil {
|
||||
return fmt.Errorf("failed to link payment to subscription: %w", err)
|
||||
}
|
||||
}
|
||||
s.notifyLearnPackageSubscribed(payment.UserID, plan, expiresAt)
|
||||
s.notifyLearnPackageSubscribed(payment.UserID, plan, subscription.ExpiresAt)
|
||||
} else if newStatus == string(domain.PaymentStatusFailed) ||
|
||||
newStatus == string(domain.PaymentStatusCancelled) {
|
||||
checkoutsubscription.AbandonPending(ctx, s.subscriptionStore, payment.SubscriptionID)
|
||||
}
|
||||
|
||||
return nil
|
||||
|
|
@ -395,7 +412,11 @@ func (s *ArifpayService) CancelPayment(ctx context.Context, paymentID int64, use
|
|||
return ErrInvalidPaymentState
|
||||
}
|
||||
|
||||
return s.paymentStore.UpdatePaymentStatus(ctx, paymentID, string(domain.PaymentStatusCancelled))
|
||||
if err := s.paymentStore.UpdatePaymentStatus(ctx, paymentID, string(domain.PaymentStatusCancelled)); err != nil {
|
||||
return err
|
||||
}
|
||||
checkoutsubscription.AbandonPending(ctx, s.subscriptionStore, payment.SubscriptionID)
|
||||
return nil
|
||||
}
|
||||
|
||||
// CreateCheckoutSession creates a generic checkout session (for non-subscription payments)
|
||||
|
|
@ -643,16 +664,31 @@ func (s *ArifpayService) InitiateDirectPayment(ctx context.Context, userID int64
|
|||
|
||||
// Create payment record
|
||||
paymentMethod := string(req.PaymentMethod)
|
||||
pendingSub, err := checkoutsubscription.CreatePending(
|
||||
ctx,
|
||||
s.subscriptionStore,
|
||||
userID,
|
||||
plan,
|
||||
nonce,
|
||||
paymentMethod,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
pendingSubID := pendingSub.ID
|
||||
|
||||
payment, err := s.paymentStore.CreatePayment(ctx, domain.CreatePaymentInput{
|
||||
UserID: userID,
|
||||
PlanID: &req.PlanID,
|
||||
Amount: plan.Price,
|
||||
Currency: plan.Currency,
|
||||
Nonce: nonce,
|
||||
PaymentMethod: &paymentMethod,
|
||||
ExpiresAt: &expiresAt,
|
||||
UserID: userID,
|
||||
PlanID: &req.PlanID,
|
||||
SubscriptionID: &pendingSubID,
|
||||
Amount: plan.Price,
|
||||
Currency: plan.Currency,
|
||||
Nonce: nonce,
|
||||
PaymentMethod: &paymentMethod,
|
||||
ExpiresAt: &expiresAt,
|
||||
})
|
||||
if err != nil {
|
||||
checkoutsubscription.AbandonPending(ctx, s.subscriptionStore, &pendingSubID)
|
||||
return nil, fmt.Errorf("failed to create payment record: %w", err)
|
||||
}
|
||||
|
||||
|
|
@ -676,6 +712,7 @@ func (s *ArifpayService) InitiateDirectPayment(ctx context.Context, userID int64
|
|||
if err != nil {
|
||||
// Update payment status to failed
|
||||
s.paymentStore.UpdatePaymentStatus(ctx, payment.ID, string(domain.PaymentStatusFailed))
|
||||
checkoutsubscription.AbandonPending(ctx, s.subscriptionStore, &pendingSubID)
|
||||
return nil, fmt.Errorf("failed to initiate direct transfer: %w", err)
|
||||
}
|
||||
|
||||
|
|
@ -1026,29 +1063,16 @@ func (s *ArifpayService) VerifyDirectPaymentOTP(ctx context.Context, userID int6
|
|||
return nil, fmt.Errorf("failed to update payment status: %w", err)
|
||||
}
|
||||
|
||||
// Create subscription
|
||||
// Activate pending subscription (or create for legacy payments).
|
||||
if payment.PlanID != nil {
|
||||
plan, err := s.subscriptionStore.GetSubscriptionPlanByID(ctx, *payment.PlanID)
|
||||
if err == nil {
|
||||
startsAt := time.Now()
|
||||
expiresAt := domain.CalculateSubscriptionExpiresAt(startsAt, plan.Category, plan.DurationValue, plan.DurationUnit)
|
||||
activeStatus := string(domain.SubscriptionStatusActive)
|
||||
autoRenew := false
|
||||
paymentRef := payment.Nonce
|
||||
|
||||
subscription, err := s.subscriptionStore.CreateUserSubscription(ctx, domain.CreateUserSubscriptionInput{
|
||||
UserID: payment.UserID,
|
||||
PlanID: *payment.PlanID,
|
||||
StartsAt: &startsAt,
|
||||
ExpiresAt: expiresAt,
|
||||
Status: &activeStatus,
|
||||
PaymentReference: &paymentRef,
|
||||
PaymentMethod: &paymentMethod,
|
||||
AutoRenew: &autoRenew,
|
||||
})
|
||||
if err == nil {
|
||||
s.paymentStore.LinkPaymentToSubscription(ctx, payment.ID, subscription.ID)
|
||||
s.notifyLearnPackageSubscribed(payment.UserID, plan, expiresAt)
|
||||
subscription, fulfillErr := checkoutsubscription.Fulfill(ctx, s.subscriptionStore, payment, plan, paymentMethod)
|
||||
if fulfillErr == nil {
|
||||
if payment.SubscriptionID == nil || *payment.SubscriptionID != subscription.ID {
|
||||
s.paymentStore.LinkPaymentToSubscription(ctx, payment.ID, subscription.ID)
|
||||
}
|
||||
s.notifyLearnPackageSubscribed(payment.UserID, plan, subscription.ExpiresAt)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ package chapa
|
|||
|
||||
import (
|
||||
"Yimaru-Backend/internal/domain"
|
||||
"Yimaru-Backend/internal/services/checkoutsubscription"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
|
|
@ -91,16 +92,31 @@ func (s *Service) InitiateDirectChargeSubscription(ctx context.Context, userID i
|
|||
}
|
||||
|
||||
method := domain.ChapaDirectChargePaymentMethod(chargeType)
|
||||
pendingSub, err := checkoutsubscription.CreatePending(
|
||||
ctx,
|
||||
s.subscriptionStore,
|
||||
userID,
|
||||
prep.Plan,
|
||||
prep.TxRef,
|
||||
method,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
pendingSubID := pendingSub.ID
|
||||
|
||||
payment, err := s.paymentStore.CreatePayment(ctx, domain.CreatePaymentInput{
|
||||
UserID: userID,
|
||||
PlanID: &req.PlanID,
|
||||
Amount: prep.Plan.Price,
|
||||
Currency: prep.Plan.Currency,
|
||||
PaymentMethod: &method,
|
||||
Nonce: prep.TxRef,
|
||||
ExpiresAt: &prep.ExpiresAt,
|
||||
UserID: userID,
|
||||
PlanID: &req.PlanID,
|
||||
SubscriptionID: &pendingSubID,
|
||||
Amount: prep.Plan.Price,
|
||||
Currency: prep.Plan.Currency,
|
||||
PaymentMethod: &method,
|
||||
Nonce: prep.TxRef,
|
||||
ExpiresAt: &prep.ExpiresAt,
|
||||
})
|
||||
if err != nil {
|
||||
checkoutsubscription.AbandonPending(ctx, s.subscriptionStore, &pendingSubID)
|
||||
return nil, fmt.Errorf("failed to create payment record: %w", err)
|
||||
}
|
||||
|
||||
|
|
@ -113,6 +129,7 @@ func (s *Service) InitiateDirectChargeSubscription(ctx context.Context, userID i
|
|||
})
|
||||
if err != nil {
|
||||
_ = s.paymentStore.UpdatePaymentStatus(ctx, payment.ID, string(domain.PaymentStatusFailed))
|
||||
checkoutsubscription.AbandonPending(ctx, s.subscriptionStore, &pendingSubID)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -19,6 +19,7 @@ import (
|
|||
"Yimaru-Backend/internal/config"
|
||||
"Yimaru-Backend/internal/domain"
|
||||
"Yimaru-Backend/internal/ports"
|
||||
"Yimaru-Backend/internal/services/checkoutsubscription"
|
||||
learnernotifications "Yimaru-Backend/internal/services/learnernotifications"
|
||||
)
|
||||
|
||||
|
|
@ -97,20 +98,33 @@ func (s *Service) InitiateSubscriptionPayment(ctx context.Context, userID int64,
|
|||
}
|
||||
|
||||
expiresAt := time.Now().Add(3 * time.Hour)
|
||||
paymentMethod := string(domain.PaymentProviderChapa)
|
||||
|
||||
pendingSub, err := checkoutsubscription.CreatePending(
|
||||
ctx,
|
||||
s.subscriptionStore,
|
||||
userID,
|
||||
prep.Plan,
|
||||
prep.TxRef,
|
||||
paymentMethod,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
pendingSubID := pendingSub.ID
|
||||
|
||||
payment, err := s.paymentStore.CreatePayment(ctx, domain.CreatePaymentInput{
|
||||
UserID: userID,
|
||||
PlanID: &req.PlanID,
|
||||
Amount: prep.Plan.Price,
|
||||
Currency: prep.Plan.Currency,
|
||||
PaymentMethod: func() *string {
|
||||
v := string(domain.PaymentProviderChapa)
|
||||
return &v
|
||||
}(),
|
||||
Nonce: prep.TxRef,
|
||||
ExpiresAt: &expiresAt,
|
||||
UserID: userID,
|
||||
PlanID: &req.PlanID,
|
||||
SubscriptionID: &pendingSubID,
|
||||
Amount: prep.Plan.Price,
|
||||
Currency: prep.Plan.Currency,
|
||||
PaymentMethod: &paymentMethod,
|
||||
Nonce: prep.TxRef,
|
||||
ExpiresAt: &expiresAt,
|
||||
})
|
||||
if err != nil {
|
||||
checkoutsubscription.AbandonPending(ctx, s.subscriptionStore, &pendingSubID)
|
||||
return nil, fmt.Errorf("failed to create payment record: %w", err)
|
||||
}
|
||||
|
||||
|
|
@ -130,6 +144,8 @@ func (s *Service) InitiateSubscriptionPayment(ctx context.Context, userID int64,
|
|||
|
||||
checkoutURL, err := s.initializeTransaction(ctx, initReq)
|
||||
if err != nil {
|
||||
_ = s.paymentStore.UpdatePaymentStatus(ctx, payment.ID, string(domain.PaymentStatusFailed))
|
||||
checkoutsubscription.AbandonPending(ctx, s.subscriptionStore, &pendingSubID)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
|
|
@ -335,6 +351,13 @@ func (s *Service) applyVerifiedTransaction(ctx context.Context, data domain.Chap
|
|||
return fmt.Errorf("failed to update payment status: %w", err)
|
||||
}
|
||||
|
||||
if newStatus == string(domain.PaymentStatusFailed) ||
|
||||
newStatus == string(domain.PaymentStatusCancelled) ||
|
||||
newStatus == string(domain.PaymentStatusExpired) {
|
||||
checkoutsubscription.AbandonPending(ctx, s.subscriptionStore, payment.SubscriptionID)
|
||||
return nil
|
||||
}
|
||||
|
||||
if newStatus != string(domain.PaymentStatusSuccess) || payment.PlanID == nil {
|
||||
return nil
|
||||
}
|
||||
|
|
@ -348,32 +371,19 @@ func (s *Service) activateSubscription(ctx context.Context, payment *domain.Paym
|
|||
return fmt.Errorf("failed to get subscription plan: %w", err)
|
||||
}
|
||||
|
||||
startsAt := time.Now()
|
||||
expiresAt := domain.CalculateSubscriptionExpiresAt(startsAt, plan.Category, plan.DurationValue, plan.DurationUnit)
|
||||
activeStatus := string(domain.SubscriptionStatusActive)
|
||||
autoRenew := false
|
||||
paymentRef := payment.Nonce
|
||||
|
||||
subscription, err := s.subscriptionStore.CreateUserSubscription(ctx, domain.CreateUserSubscriptionInput{
|
||||
UserID: payment.UserID,
|
||||
PlanID: *payment.PlanID,
|
||||
StartsAt: &startsAt,
|
||||
ExpiresAt: expiresAt,
|
||||
Status: &activeStatus,
|
||||
PaymentReference: &paymentRef,
|
||||
PaymentMethod: &paymentMethod,
|
||||
AutoRenew: &autoRenew,
|
||||
})
|
||||
subscription, err := checkoutsubscription.Fulfill(ctx, s.subscriptionStore, payment, plan, paymentMethod)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create subscription: %w", err)
|
||||
return err
|
||||
}
|
||||
|
||||
if err := s.paymentStore.LinkPaymentToSubscription(ctx, payment.ID, subscription.ID); err != nil {
|
||||
return fmt.Errorf("failed to link payment to subscription: %w", err)
|
||||
if payment.SubscriptionID == nil || *payment.SubscriptionID != subscription.ID {
|
||||
if err := s.paymentStore.LinkPaymentToSubscription(ctx, payment.ID, subscription.ID); err != nil {
|
||||
return fmt.Errorf("failed to link payment to subscription: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
if s.learnerNotifier != nil {
|
||||
s.learnerNotifier.MaybeNotifyLearnPackageSubscribed(payment.UserID, plan.Category, plan.Name, expiresAt)
|
||||
s.learnerNotifier.MaybeNotifyLearnPackageSubscribed(payment.UserID, plan.Category, plan.Name, subscription.ExpiresAt)
|
||||
}
|
||||
|
||||
return nil
|
||||
|
|
@ -414,9 +424,17 @@ func (s *Service) GetPaymentByID(ctx context.Context, id int64) (*domain.Payment
|
|||
return s.paymentStore.GetPaymentByID(ctx, id)
|
||||
}
|
||||
|
||||
// ExpireStalePendingPayments marks PENDING payments past expires_at as EXPIRED.
|
||||
// ExpireStalePendingPayments marks PENDING payments past expires_at as EXPIRED
|
||||
// and cancels any linked PENDING subscriptions.
|
||||
func (s *Service) ExpireStalePendingPayments(ctx context.Context) (int64, error) {
|
||||
return s.paymentStore.ExpireStalePendingPayments(ctx)
|
||||
expired, err := s.paymentStore.ExpireStalePendingPayments(ctx)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if _, cancelErr := s.subscriptionStore.CancelPendingSubscriptionsForTerminalPayments(ctx); cancelErr != nil {
|
||||
return expired, cancelErr
|
||||
}
|
||||
return expired, nil
|
||||
}
|
||||
|
||||
func (s *Service) CancelPayment(ctx context.Context, paymentID int64, userID int64) error {
|
||||
|
|
@ -430,7 +448,11 @@ func (s *Service) CancelPayment(ctx context.Context, paymentID int64, userID int
|
|||
if payment.Status != string(domain.PaymentStatusPending) {
|
||||
return ErrInvalidPaymentState
|
||||
}
|
||||
return s.paymentStore.UpdatePaymentStatus(ctx, paymentID, string(domain.PaymentStatusCancelled))
|
||||
if err := s.paymentStore.UpdatePaymentStatus(ctx, paymentID, string(domain.PaymentStatusCancelled)); err != nil {
|
||||
return err
|
||||
}
|
||||
checkoutsubscription.AbandonPending(ctx, s.subscriptionStore, payment.SubscriptionID)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Service) GetPaymentMethods() []domain.ChapaPaymentMethod {
|
||||
|
|
|
|||
112
internal/services/checkoutsubscription/checkoutsubscription.go
Normal file
112
internal/services/checkoutsubscription/checkoutsubscription.go
Normal file
|
|
@ -0,0 +1,112 @@
|
|||
package checkoutsubscription
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"Yimaru-Backend/internal/domain"
|
||||
"Yimaru-Backend/internal/ports"
|
||||
)
|
||||
|
||||
// CreatePending creates a PENDING subscription when checkout/payment is initiated.
|
||||
func CreatePending(
|
||||
ctx context.Context,
|
||||
store ports.SubscriptionStore,
|
||||
userID int64,
|
||||
plan *domain.SubscriptionPlan,
|
||||
paymentRef string,
|
||||
paymentMethod string,
|
||||
) (*domain.UserSubscription, error) {
|
||||
now := time.Now()
|
||||
expiresAt := domain.CalculateSubscriptionExpiresAt(now, plan.Category, plan.DurationValue, plan.DurationUnit)
|
||||
status := string(domain.SubscriptionStatusPending)
|
||||
autoRenew := false
|
||||
ref := paymentRef
|
||||
method := paymentMethod
|
||||
|
||||
sub, err := store.CreateUserSubscription(ctx, domain.CreateUserSubscriptionInput{
|
||||
UserID: userID,
|
||||
PlanID: plan.ID,
|
||||
StartsAt: &now,
|
||||
ExpiresAt: expiresAt,
|
||||
Status: &status,
|
||||
PaymentReference: &ref,
|
||||
PaymentMethod: &method,
|
||||
AutoRenew: &autoRenew,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to create pending subscription: %w", err)
|
||||
}
|
||||
return sub, nil
|
||||
}
|
||||
|
||||
// AbandonPending cancels a PENDING subscription when checkout fails or is cancelled.
|
||||
func AbandonPending(ctx context.Context, store ports.SubscriptionStore, subscriptionID *int64) {
|
||||
if subscriptionID == nil || *subscriptionID < 1 {
|
||||
return
|
||||
}
|
||||
sub, err := store.GetUserSubscriptionByID(ctx, *subscriptionID)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if sub.Status != string(domain.SubscriptionStatusPending) {
|
||||
return
|
||||
}
|
||||
_ = store.CancelUserSubscription(ctx, *subscriptionID)
|
||||
}
|
||||
|
||||
// Fulfill activates the payment's PENDING subscription, or creates an ACTIVE one
|
||||
// for legacy payments that were not linked at initiate time.
|
||||
func Fulfill(
|
||||
ctx context.Context,
|
||||
store ports.SubscriptionStore,
|
||||
payment *domain.Payment,
|
||||
plan *domain.SubscriptionPlan,
|
||||
paymentMethod string,
|
||||
) (*domain.UserSubscription, error) {
|
||||
startsAt := time.Now()
|
||||
expiresAt := domain.CalculateSubscriptionExpiresAt(startsAt, plan.Category, plan.DurationValue, plan.DurationUnit)
|
||||
paymentRef := payment.Nonce
|
||||
activeStatus := string(domain.SubscriptionStatusActive)
|
||||
autoRenew := false
|
||||
method := paymentMethod
|
||||
|
||||
if payment.SubscriptionID != nil {
|
||||
sub, err := store.GetUserSubscriptionByID(ctx, *payment.SubscriptionID)
|
||||
if err == nil {
|
||||
switch sub.Status {
|
||||
case string(domain.SubscriptionStatusActive):
|
||||
return sub, nil
|
||||
case string(domain.SubscriptionStatusPending):
|
||||
activated, actErr := store.ActivatePendingUserSubscription(
|
||||
ctx,
|
||||
*payment.SubscriptionID,
|
||||
startsAt,
|
||||
expiresAt,
|
||||
paymentRef,
|
||||
method,
|
||||
)
|
||||
if actErr != nil {
|
||||
return nil, fmt.Errorf("failed to activate pending subscription: %w", actErr)
|
||||
}
|
||||
return activated, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
created, err := store.CreateUserSubscription(ctx, domain.CreateUserSubscriptionInput{
|
||||
UserID: payment.UserID,
|
||||
PlanID: plan.ID,
|
||||
StartsAt: &startsAt,
|
||||
ExpiresAt: expiresAt,
|
||||
Status: &activeStatus,
|
||||
PaymentReference: &paymentRef,
|
||||
PaymentMethod: &method,
|
||||
AutoRenew: &autoRenew,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to create subscription: %w", err)
|
||||
}
|
||||
return created, nil
|
||||
}
|
||||
Loading…
Reference in New Issue
Block a user