Add subscription behaviour analytics and clean profile breakdowns.
Extend the analytics dashboard with live subscription snapshots, renewal/resubscribe metrics, and field-options normalization so Unknown and invalid profile values aggregate as Other. Also include exam_prep in the learner progress summary. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
parent
09fc1e80f7
commit
3b08a07c85
|
|
@ -203,6 +203,262 @@ LEFT JOIN user_subscriptions us ON us.created_at::date = d.date
|
|||
GROUP BY d.date
|
||||
ORDER BY d.date;
|
||||
|
||||
-- Point-in-time learner subscription behaviour (not filtered by created_at range).
|
||||
-- name: AnalyticsSubscriptionsSnapshot :one
|
||||
SELECT
|
||||
COUNT(*) FILTER (
|
||||
WHERE us.status = 'ACTIVE' AND us.expires_at > CURRENT_TIMESTAMP
|
||||
)::bigint AS active_now,
|
||||
COUNT(DISTINCT us.user_id) FILTER (
|
||||
WHERE us.status = 'ACTIVE' AND us.expires_at > CURRENT_TIMESTAMP
|
||||
)::bigint AS active_learners,
|
||||
COUNT(*) FILTER (WHERE us.status = 'PENDING')::bigint AS pending_now,
|
||||
COUNT(*) FILTER (
|
||||
WHERE us.status = 'EXPIRED'
|
||||
OR (us.status = 'ACTIVE' AND us.expires_at <= CURRENT_TIMESTAMP)
|
||||
)::bigint AS expired_now,
|
||||
COUNT(*) FILTER (WHERE us.status = 'CANCELLED')::bigint AS cancelled_now,
|
||||
COUNT(*) FILTER (
|
||||
WHERE us.status = 'ACTIVE'
|
||||
AND us.expires_at > CURRENT_TIMESTAMP
|
||||
AND sp.is_lifetime = FALSE
|
||||
AND us.expires_at <= CURRENT_TIMESTAMP + INTERVAL '7 days'
|
||||
)::bigint AS expiring_within_7_days,
|
||||
COUNT(*) FILTER (
|
||||
WHERE us.status = 'ACTIVE'
|
||||
AND us.expires_at > CURRENT_TIMESTAMP
|
||||
AND sp.is_lifetime = FALSE
|
||||
AND us.expires_at <= CURRENT_TIMESTAMP + INTERVAL '30 days'
|
||||
)::bigint AS expiring_within_30_days,
|
||||
COUNT(*) FILTER (
|
||||
WHERE us.status = 'ACTIVE'
|
||||
AND us.expires_at > CURRENT_TIMESTAMP
|
||||
AND us.auto_renew = TRUE
|
||||
)::bigint AS auto_renew_enabled,
|
||||
COUNT(*) FILTER (
|
||||
WHERE us.status = 'ACTIVE'
|
||||
AND us.expires_at > CURRENT_TIMESTAMP
|
||||
AND sp.is_lifetime = TRUE
|
||||
)::bigint AS lifetime_active,
|
||||
COUNT(*) FILTER (
|
||||
WHERE us.status = 'ACTIVE'
|
||||
AND us.expires_at > CURRENT_TIMESTAMP
|
||||
AND sp.is_lifetime = FALSE
|
||||
)::bigint AS term_active
|
||||
FROM user_subscriptions us
|
||||
JOIN subscription_plans sp ON sp.id = us.plan_id;
|
||||
|
||||
-- name: AnalyticsActiveSubscriptionsByCategory :many
|
||||
SELECT
|
||||
COALESCE(sp.category, 'unknown') AS label,
|
||||
COUNT(*)::bigint AS count
|
||||
FROM user_subscriptions us
|
||||
JOIN subscription_plans sp ON sp.id = us.plan_id
|
||||
WHERE us.status = 'ACTIVE'
|
||||
AND us.expires_at > CURRENT_TIMESTAMP
|
||||
GROUP BY sp.category
|
||||
ORDER BY count DESC;
|
||||
|
||||
-- name: AnalyticsActiveSubscriptionsByPlan :many
|
||||
SELECT
|
||||
sp.name AS label,
|
||||
COUNT(*)::bigint AS count
|
||||
FROM user_subscriptions us
|
||||
JOIN subscription_plans sp ON sp.id = us.plan_id
|
||||
WHERE us.status = 'ACTIVE'
|
||||
AND us.expires_at > CURRENT_TIMESTAMP
|
||||
GROUP BY sp.name
|
||||
ORDER BY count DESC;
|
||||
|
||||
-- name: AnalyticsActiveSubscriptionsByLifetime :many
|
||||
SELECT
|
||||
CASE WHEN sp.is_lifetime THEN 'lifetime' ELSE 'term' END AS label,
|
||||
COUNT(*)::bigint AS count
|
||||
FROM user_subscriptions us
|
||||
JOIN subscription_plans sp ON sp.id = us.plan_id
|
||||
WHERE us.status = 'ACTIVE'
|
||||
AND us.expires_at > CURRENT_TIMESTAMP
|
||||
GROUP BY CASE WHEN sp.is_lifetime THEN 'lifetime' ELSE 'term' END
|
||||
ORDER BY count DESC;
|
||||
|
||||
-- How new subscriptions were acquired (paid checkout vs admin grant/extend).
|
||||
-- name: AnalyticsSubscriptionAcquisitionBySource :many
|
||||
SELECT
|
||||
CASE
|
||||
WHEN UPPER(COALESCE(us.payment_method, '')) IN ('ADMIN_GRANT', 'ADMIN_EXTEND')
|
||||
THEN UPPER(us.payment_method)
|
||||
WHEN COALESCE(TRIM(us.payment_method), '') = '' THEN 'unknown'
|
||||
ELSE 'paid'
|
||||
END AS label,
|
||||
COUNT(*)::bigint AS count
|
||||
FROM user_subscriptions us
|
||||
WHERE (sqlc.narg('range_start')::timestamptz IS NULL OR us.created_at >= sqlc.narg('range_start')::timestamptz)
|
||||
AND (sqlc.narg('range_end')::timestamptz IS NULL OR us.created_at < sqlc.narg('range_end')::timestamptz)
|
||||
GROUP BY 1
|
||||
ORDER BY count DESC;
|
||||
|
||||
-- name: AnalyticsRevenueByPlanCategory :many
|
||||
SELECT
|
||||
COALESCE(sp.category, 'unknown') AS label,
|
||||
COUNT(p.id)::bigint AS count,
|
||||
COALESCE(SUM(p.amount), 0)::float8 AS amount
|
||||
FROM payments p
|
||||
JOIN subscription_plans sp ON sp.id = p.plan_id
|
||||
WHERE p.status = 'SUCCESS'
|
||||
AND (sqlc.narg('range_start')::timestamptz IS NULL OR COALESCE(p.paid_at, p.created_at) >= sqlc.narg('range_start')::timestamptz)
|
||||
AND (sqlc.narg('range_end')::timestamptz IS NULL OR COALESCE(p.paid_at, p.created_at) < sqlc.narg('range_end')::timestamptz)
|
||||
GROUP BY sp.category
|
||||
ORDER BY amount DESC;
|
||||
|
||||
-- name: AnalyticsSubscriptionCancellationsLast30Days :many
|
||||
SELECT
|
||||
d.date,
|
||||
COUNT(us.id)::bigint AS count
|
||||
FROM generate_series(
|
||||
sqlc.arg('series_start')::date,
|
||||
sqlc.arg('series_end')::date,
|
||||
INTERVAL '1 day'
|
||||
) AS d(date)
|
||||
LEFT JOIN user_subscriptions us ON us.cancelled_at::date = d.date
|
||||
AND (sqlc.narg('range_start')::timestamptz IS NULL OR us.cancelled_at >= sqlc.narg('range_start')::timestamptz)
|
||||
AND (sqlc.narg('range_end')::timestamptz IS NULL OR us.cancelled_at < sqlc.narg('range_end')::timestamptz)
|
||||
GROUP BY d.date
|
||||
ORDER BY d.date;
|
||||
|
||||
-- Term-plan expirations by expires_at date (lifetime plans excluded).
|
||||
-- name: AnalyticsSubscriptionExpirationsLast30Days :many
|
||||
SELECT
|
||||
d.date,
|
||||
COUNT(us.id)::bigint AS count
|
||||
FROM generate_series(
|
||||
sqlc.arg('series_start')::date,
|
||||
sqlc.arg('series_end')::date,
|
||||
INTERVAL '1 day'
|
||||
) AS d(date)
|
||||
LEFT JOIN user_subscriptions us ON us.expires_at::date = d.date
|
||||
AND (sqlc.narg('range_start')::timestamptz IS NULL OR us.expires_at >= sqlc.narg('range_start')::timestamptz)
|
||||
AND (sqlc.narg('range_end')::timestamptz IS NULL OR us.expires_at < sqlc.narg('range_end')::timestamptz)
|
||||
AND EXISTS (
|
||||
SELECT 1
|
||||
FROM subscription_plans sp
|
||||
WHERE sp.id = us.plan_id
|
||||
AND sp.is_lifetime = FALSE
|
||||
)
|
||||
GROUP BY d.date
|
||||
ORDER BY d.date;
|
||||
|
||||
-- First-time vs returning / resubscribe-after-expiry behaviour for the selected period.
|
||||
-- Returning = prior subscription in the same plan category for the same learner.
|
||||
-- Resubscribe after expiry = prior same-category sub whose expires_at <= new starts_at.
|
||||
-- Renewal rate = expired term subs in period that got a later same-category subscription.
|
||||
-- name: AnalyticsSubscriptionRenewalSummary :one
|
||||
WITH ranged_subs AS (
|
||||
SELECT
|
||||
us.id,
|
||||
us.user_id,
|
||||
us.created_at,
|
||||
us.starts_at,
|
||||
sp.category
|
||||
FROM user_subscriptions us
|
||||
JOIN subscription_plans sp ON sp.id = us.plan_id
|
||||
WHERE (sqlc.narg('range_start')::timestamptz IS NULL OR us.created_at >= sqlc.narg('range_start')::timestamptz)
|
||||
AND (sqlc.narg('range_end')::timestamptz IS NULL OR us.created_at < sqlc.narg('range_end')::timestamptz)
|
||||
),
|
||||
classified AS (
|
||||
SELECT
|
||||
rs.id,
|
||||
EXISTS (
|
||||
SELECT 1
|
||||
FROM user_subscriptions prev
|
||||
JOIN subscription_plans psp ON psp.id = prev.plan_id
|
||||
WHERE prev.user_id = rs.user_id
|
||||
AND psp.category = rs.category
|
||||
AND prev.id <> rs.id
|
||||
AND prev.created_at < rs.created_at
|
||||
) AS is_returning,
|
||||
EXISTS (
|
||||
SELECT 1
|
||||
FROM user_subscriptions prev
|
||||
JOIN subscription_plans psp ON psp.id = prev.plan_id
|
||||
WHERE prev.user_id = rs.user_id
|
||||
AND psp.category = rs.category
|
||||
AND prev.id <> rs.id
|
||||
AND prev.expires_at <= rs.starts_at
|
||||
) AS is_resubscribe_after_expiry
|
||||
FROM ranged_subs rs
|
||||
),
|
||||
expired_in_range AS (
|
||||
SELECT
|
||||
us.id AS sub_id,
|
||||
us.user_id,
|
||||
us.expires_at,
|
||||
sp.category
|
||||
FROM user_subscriptions us
|
||||
JOIN subscription_plans sp ON sp.id = us.plan_id
|
||||
WHERE sp.is_lifetime = FALSE
|
||||
AND (sqlc.narg('range_start')::timestamptz IS NULL OR us.expires_at >= sqlc.narg('range_start')::timestamptz)
|
||||
AND (sqlc.narg('range_end')::timestamptz IS NULL OR us.expires_at < sqlc.narg('range_end')::timestamptz)
|
||||
),
|
||||
renewals AS (
|
||||
SELECT
|
||||
e.sub_id,
|
||||
e.expires_at,
|
||||
MIN(n.created_at) AS resub_at
|
||||
FROM expired_in_range e
|
||||
JOIN user_subscriptions n ON n.user_id = e.user_id
|
||||
AND n.id <> e.sub_id
|
||||
AND n.created_at >= e.expires_at
|
||||
JOIN subscription_plans nsp ON nsp.id = n.plan_id
|
||||
AND nsp.category = e.category
|
||||
GROUP BY e.sub_id, e.expires_at
|
||||
)
|
||||
SELECT
|
||||
COUNT(*) FILTER (WHERE NOT c.is_returning)::bigint AS first_time_subscriptions,
|
||||
COUNT(*) FILTER (WHERE c.is_returning)::bigint AS returning_subscriptions,
|
||||
COUNT(*) FILTER (WHERE c.is_resubscribe_after_expiry)::bigint AS resubscribe_after_expiry,
|
||||
(SELECT COUNT(*)::bigint FROM expired_in_range) AS expired_in_period,
|
||||
(SELECT COUNT(*)::bigint FROM renewals) AS renewed_after_expiry,
|
||||
COALESCE(
|
||||
(SELECT AVG(EXTRACT(EPOCH FROM (r.resub_at - r.expires_at)) / 86400.0) FROM renewals r),
|
||||
0
|
||||
)::float8 AS avg_days_to_resubscribe,
|
||||
COALESCE(
|
||||
(
|
||||
SELECT PERCENTILE_CONT(0.5) WITHIN GROUP (
|
||||
ORDER BY EXTRACT(EPOCH FROM (r.resub_at - r.expires_at)) / 86400.0
|
||||
)
|
||||
FROM renewals r
|
||||
),
|
||||
0
|
||||
)::float8 AS median_days_to_resubscribe
|
||||
FROM classified c;
|
||||
|
||||
-- Daily count of resubscribes after expiry (same category, prior expires_at <= starts_at).
|
||||
-- name: AnalyticsResubscriptionsLast30Days :many
|
||||
SELECT
|
||||
d.date,
|
||||
COUNT(us.id)::bigint AS count
|
||||
FROM generate_series(
|
||||
sqlc.arg('series_start')::date,
|
||||
sqlc.arg('series_end')::date,
|
||||
INTERVAL '1 day'
|
||||
) AS d(date)
|
||||
LEFT JOIN user_subscriptions us ON us.created_at::date = d.date
|
||||
AND (sqlc.narg('range_start')::timestamptz IS NULL OR us.created_at >= sqlc.narg('range_start')::timestamptz)
|
||||
AND (sqlc.narg('range_end')::timestamptz IS NULL OR us.created_at < sqlc.narg('range_end')::timestamptz)
|
||||
AND EXISTS (
|
||||
SELECT 1
|
||||
FROM user_subscriptions prev
|
||||
JOIN subscription_plans psp ON psp.id = prev.plan_id
|
||||
JOIN subscription_plans usp ON usp.id = us.plan_id
|
||||
WHERE prev.user_id = us.user_id
|
||||
AND psp.category = usp.category
|
||||
AND prev.id <> us.id
|
||||
AND prev.expires_at <= us.starts_at
|
||||
)
|
||||
GROUP BY d.date
|
||||
ORDER BY d.date;
|
||||
|
||||
-- =====================
|
||||
-- Payment Analytics
|
||||
-- =====================
|
||||
|
|
|
|||
|
|
@ -11,6 +11,117 @@ import (
|
|||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
const AnalyticsActiveSubscriptionsByCategory = `-- name: AnalyticsActiveSubscriptionsByCategory :many
|
||||
SELECT
|
||||
COALESCE(sp.category, 'unknown') AS label,
|
||||
COUNT(*)::bigint AS count
|
||||
FROM user_subscriptions us
|
||||
JOIN subscription_plans sp ON sp.id = us.plan_id
|
||||
WHERE us.status = 'ACTIVE'
|
||||
AND us.expires_at > CURRENT_TIMESTAMP
|
||||
GROUP BY sp.category
|
||||
ORDER BY count DESC
|
||||
`
|
||||
|
||||
type AnalyticsActiveSubscriptionsByCategoryRow struct {
|
||||
Label string `json:"label"`
|
||||
Count int64 `json:"count"`
|
||||
}
|
||||
|
||||
func (q *Queries) AnalyticsActiveSubscriptionsByCategory(ctx context.Context) ([]AnalyticsActiveSubscriptionsByCategoryRow, error) {
|
||||
rows, err := q.db.Query(ctx, AnalyticsActiveSubscriptionsByCategory)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var items []AnalyticsActiveSubscriptionsByCategoryRow
|
||||
for rows.Next() {
|
||||
var i AnalyticsActiveSubscriptionsByCategoryRow
|
||||
if err := rows.Scan(&i.Label, &i.Count); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const AnalyticsActiveSubscriptionsByLifetime = `-- name: AnalyticsActiveSubscriptionsByLifetime :many
|
||||
SELECT
|
||||
CASE WHEN sp.is_lifetime THEN 'lifetime' ELSE 'term' END AS label,
|
||||
COUNT(*)::bigint AS count
|
||||
FROM user_subscriptions us
|
||||
JOIN subscription_plans sp ON sp.id = us.plan_id
|
||||
WHERE us.status = 'ACTIVE'
|
||||
AND us.expires_at > CURRENT_TIMESTAMP
|
||||
GROUP BY CASE WHEN sp.is_lifetime THEN 'lifetime' ELSE 'term' END
|
||||
ORDER BY count DESC
|
||||
`
|
||||
|
||||
type AnalyticsActiveSubscriptionsByLifetimeRow struct {
|
||||
Label string `json:"label"`
|
||||
Count int64 `json:"count"`
|
||||
}
|
||||
|
||||
func (q *Queries) AnalyticsActiveSubscriptionsByLifetime(ctx context.Context) ([]AnalyticsActiveSubscriptionsByLifetimeRow, error) {
|
||||
rows, err := q.db.Query(ctx, AnalyticsActiveSubscriptionsByLifetime)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var items []AnalyticsActiveSubscriptionsByLifetimeRow
|
||||
for rows.Next() {
|
||||
var i AnalyticsActiveSubscriptionsByLifetimeRow
|
||||
if err := rows.Scan(&i.Label, &i.Count); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const AnalyticsActiveSubscriptionsByPlan = `-- name: AnalyticsActiveSubscriptionsByPlan :many
|
||||
SELECT
|
||||
sp.name AS label,
|
||||
COUNT(*)::bigint AS count
|
||||
FROM user_subscriptions us
|
||||
JOIN subscription_plans sp ON sp.id = us.plan_id
|
||||
WHERE us.status = 'ACTIVE'
|
||||
AND us.expires_at > CURRENT_TIMESTAMP
|
||||
GROUP BY sp.name
|
||||
ORDER BY count DESC
|
||||
`
|
||||
|
||||
type AnalyticsActiveSubscriptionsByPlanRow struct {
|
||||
Label string `json:"label"`
|
||||
Count int64 `json:"count"`
|
||||
}
|
||||
|
||||
func (q *Queries) AnalyticsActiveSubscriptionsByPlan(ctx context.Context) ([]AnalyticsActiveSubscriptionsByPlanRow, error) {
|
||||
rows, err := q.db.Query(ctx, AnalyticsActiveSubscriptionsByPlan)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var items []AnalyticsActiveSubscriptionsByPlanRow
|
||||
for rows.Next() {
|
||||
var i AnalyticsActiveSubscriptionsByPlanRow
|
||||
if err := rows.Scan(&i.Label, &i.Count); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const AnalyticsCourseCounts = `-- name: AnalyticsCourseCounts :one
|
||||
|
||||
SELECT
|
||||
|
|
@ -622,6 +733,70 @@ func (q *Queries) AnalyticsQuestionsCounts(ctx context.Context, arg AnalyticsQue
|
|||
return i, err
|
||||
}
|
||||
|
||||
const AnalyticsResubscriptionsLast30Days = `-- name: AnalyticsResubscriptionsLast30Days :many
|
||||
SELECT
|
||||
d.date,
|
||||
COUNT(us.id)::bigint AS count
|
||||
FROM generate_series(
|
||||
$1::date,
|
||||
$2::date,
|
||||
INTERVAL '1 day'
|
||||
) AS d(date)
|
||||
LEFT JOIN user_subscriptions us ON us.created_at::date = d.date
|
||||
AND ($3::timestamptz IS NULL OR us.created_at >= $3::timestamptz)
|
||||
AND ($4::timestamptz IS NULL OR us.created_at < $4::timestamptz)
|
||||
AND EXISTS (
|
||||
SELECT 1
|
||||
FROM user_subscriptions prev
|
||||
JOIN subscription_plans psp ON psp.id = prev.plan_id
|
||||
JOIN subscription_plans usp ON usp.id = us.plan_id
|
||||
WHERE prev.user_id = us.user_id
|
||||
AND psp.category = usp.category
|
||||
AND prev.id <> us.id
|
||||
AND prev.expires_at <= us.starts_at
|
||||
)
|
||||
GROUP BY d.date
|
||||
ORDER BY d.date
|
||||
`
|
||||
|
||||
type AnalyticsResubscriptionsLast30DaysParams struct {
|
||||
SeriesStart pgtype.Date `json:"series_start"`
|
||||
SeriesEnd pgtype.Date `json:"series_end"`
|
||||
RangeStart pgtype.Timestamptz `json:"range_start"`
|
||||
RangeEnd pgtype.Timestamptz `json:"range_end"`
|
||||
}
|
||||
|
||||
type AnalyticsResubscriptionsLast30DaysRow struct {
|
||||
Date interface{} `json:"date"`
|
||||
Count int64 `json:"count"`
|
||||
}
|
||||
|
||||
// Daily count of resubscribes after expiry (same category, prior expires_at <= starts_at).
|
||||
func (q *Queries) AnalyticsResubscriptionsLast30Days(ctx context.Context, arg AnalyticsResubscriptionsLast30DaysParams) ([]AnalyticsResubscriptionsLast30DaysRow, error) {
|
||||
rows, err := q.db.Query(ctx, AnalyticsResubscriptionsLast30Days,
|
||||
arg.SeriesStart,
|
||||
arg.SeriesEnd,
|
||||
arg.RangeStart,
|
||||
arg.RangeEnd,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var items []AnalyticsResubscriptionsLast30DaysRow
|
||||
for rows.Next() {
|
||||
var i AnalyticsResubscriptionsLast30DaysRow
|
||||
if err := rows.Scan(&i.Date, &i.Count); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const AnalyticsRevenueByPlan = `-- name: AnalyticsRevenueByPlan :many
|
||||
SELECT
|
||||
sp.name AS plan_name,
|
||||
|
|
@ -674,6 +849,51 @@ func (q *Queries) AnalyticsRevenueByPlan(ctx context.Context, arg AnalyticsReven
|
|||
return items, nil
|
||||
}
|
||||
|
||||
const AnalyticsRevenueByPlanCategory = `-- name: AnalyticsRevenueByPlanCategory :many
|
||||
SELECT
|
||||
COALESCE(sp.category, 'unknown') AS label,
|
||||
COUNT(p.id)::bigint AS count,
|
||||
COALESCE(SUM(p.amount), 0)::float8 AS amount
|
||||
FROM payments p
|
||||
JOIN subscription_plans sp ON sp.id = p.plan_id
|
||||
WHERE p.status = 'SUCCESS'
|
||||
AND ($1::timestamptz IS NULL OR COALESCE(p.paid_at, p.created_at) >= $1::timestamptz)
|
||||
AND ($2::timestamptz IS NULL OR COALESCE(p.paid_at, p.created_at) < $2::timestamptz)
|
||||
GROUP BY sp.category
|
||||
ORDER BY amount DESC
|
||||
`
|
||||
|
||||
type AnalyticsRevenueByPlanCategoryParams struct {
|
||||
RangeStart pgtype.Timestamptz `json:"range_start"`
|
||||
RangeEnd pgtype.Timestamptz `json:"range_end"`
|
||||
}
|
||||
|
||||
type AnalyticsRevenueByPlanCategoryRow struct {
|
||||
Label string `json:"label"`
|
||||
Count int64 `json:"count"`
|
||||
Amount float64 `json:"amount"`
|
||||
}
|
||||
|
||||
func (q *Queries) AnalyticsRevenueByPlanCategory(ctx context.Context, arg AnalyticsRevenueByPlanCategoryParams) ([]AnalyticsRevenueByPlanCategoryRow, error) {
|
||||
rows, err := q.db.Query(ctx, AnalyticsRevenueByPlanCategory, arg.RangeStart, arg.RangeEnd)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var items []AnalyticsRevenueByPlanCategoryRow
|
||||
for rows.Next() {
|
||||
var i AnalyticsRevenueByPlanCategoryRow
|
||||
if err := rows.Scan(&i.Label, &i.Count, &i.Amount); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const AnalyticsRevenueLast30Days = `-- name: AnalyticsRevenueLast30Days :many
|
||||
SELECT
|
||||
d.date,
|
||||
|
|
@ -790,6 +1010,283 @@ func (q *Queries) AnalyticsRevenueMonthlyByYear(ctx context.Context, reportYear
|
|||
return items, nil
|
||||
}
|
||||
|
||||
const AnalyticsSubscriptionAcquisitionBySource = `-- name: AnalyticsSubscriptionAcquisitionBySource :many
|
||||
SELECT
|
||||
CASE
|
||||
WHEN UPPER(COALESCE(us.payment_method, '')) IN ('ADMIN_GRANT', 'ADMIN_EXTEND')
|
||||
THEN UPPER(us.payment_method)
|
||||
WHEN COALESCE(TRIM(us.payment_method), '') = '' THEN 'unknown'
|
||||
ELSE 'paid'
|
||||
END AS label,
|
||||
COUNT(*)::bigint AS count
|
||||
FROM user_subscriptions us
|
||||
WHERE ($1::timestamptz IS NULL OR us.created_at >= $1::timestamptz)
|
||||
AND ($2::timestamptz IS NULL OR us.created_at < $2::timestamptz)
|
||||
GROUP BY 1
|
||||
ORDER BY count DESC
|
||||
`
|
||||
|
||||
type AnalyticsSubscriptionAcquisitionBySourceParams struct {
|
||||
RangeStart pgtype.Timestamptz `json:"range_start"`
|
||||
RangeEnd pgtype.Timestamptz `json:"range_end"`
|
||||
}
|
||||
|
||||
type AnalyticsSubscriptionAcquisitionBySourceRow struct {
|
||||
Label string `json:"label"`
|
||||
Count int64 `json:"count"`
|
||||
}
|
||||
|
||||
// How new subscriptions were acquired (paid checkout vs admin grant/extend).
|
||||
func (q *Queries) AnalyticsSubscriptionAcquisitionBySource(ctx context.Context, arg AnalyticsSubscriptionAcquisitionBySourceParams) ([]AnalyticsSubscriptionAcquisitionBySourceRow, error) {
|
||||
rows, err := q.db.Query(ctx, AnalyticsSubscriptionAcquisitionBySource, arg.RangeStart, arg.RangeEnd)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var items []AnalyticsSubscriptionAcquisitionBySourceRow
|
||||
for rows.Next() {
|
||||
var i AnalyticsSubscriptionAcquisitionBySourceRow
|
||||
if err := rows.Scan(&i.Label, &i.Count); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const AnalyticsSubscriptionCancellationsLast30Days = `-- name: AnalyticsSubscriptionCancellationsLast30Days :many
|
||||
SELECT
|
||||
d.date,
|
||||
COUNT(us.id)::bigint AS count
|
||||
FROM generate_series(
|
||||
$1::date,
|
||||
$2::date,
|
||||
INTERVAL '1 day'
|
||||
) AS d(date)
|
||||
LEFT JOIN user_subscriptions us ON us.cancelled_at::date = d.date
|
||||
AND ($3::timestamptz IS NULL OR us.cancelled_at >= $3::timestamptz)
|
||||
AND ($4::timestamptz IS NULL OR us.cancelled_at < $4::timestamptz)
|
||||
GROUP BY d.date
|
||||
ORDER BY d.date
|
||||
`
|
||||
|
||||
type AnalyticsSubscriptionCancellationsLast30DaysParams struct {
|
||||
SeriesStart pgtype.Date `json:"series_start"`
|
||||
SeriesEnd pgtype.Date `json:"series_end"`
|
||||
RangeStart pgtype.Timestamptz `json:"range_start"`
|
||||
RangeEnd pgtype.Timestamptz `json:"range_end"`
|
||||
}
|
||||
|
||||
type AnalyticsSubscriptionCancellationsLast30DaysRow struct {
|
||||
Date interface{} `json:"date"`
|
||||
Count int64 `json:"count"`
|
||||
}
|
||||
|
||||
func (q *Queries) AnalyticsSubscriptionCancellationsLast30Days(ctx context.Context, arg AnalyticsSubscriptionCancellationsLast30DaysParams) ([]AnalyticsSubscriptionCancellationsLast30DaysRow, error) {
|
||||
rows, err := q.db.Query(ctx, AnalyticsSubscriptionCancellationsLast30Days,
|
||||
arg.SeriesStart,
|
||||
arg.SeriesEnd,
|
||||
arg.RangeStart,
|
||||
arg.RangeEnd,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var items []AnalyticsSubscriptionCancellationsLast30DaysRow
|
||||
for rows.Next() {
|
||||
var i AnalyticsSubscriptionCancellationsLast30DaysRow
|
||||
if err := rows.Scan(&i.Date, &i.Count); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const AnalyticsSubscriptionExpirationsLast30Days = `-- name: AnalyticsSubscriptionExpirationsLast30Days :many
|
||||
SELECT
|
||||
d.date,
|
||||
COUNT(us.id)::bigint AS count
|
||||
FROM generate_series(
|
||||
$1::date,
|
||||
$2::date,
|
||||
INTERVAL '1 day'
|
||||
) AS d(date)
|
||||
LEFT JOIN user_subscriptions us ON us.expires_at::date = d.date
|
||||
AND ($3::timestamptz IS NULL OR us.expires_at >= $3::timestamptz)
|
||||
AND ($4::timestamptz IS NULL OR us.expires_at < $4::timestamptz)
|
||||
AND EXISTS (
|
||||
SELECT 1
|
||||
FROM subscription_plans sp
|
||||
WHERE sp.id = us.plan_id
|
||||
AND sp.is_lifetime = FALSE
|
||||
)
|
||||
GROUP BY d.date
|
||||
ORDER BY d.date
|
||||
`
|
||||
|
||||
type AnalyticsSubscriptionExpirationsLast30DaysParams struct {
|
||||
SeriesStart pgtype.Date `json:"series_start"`
|
||||
SeriesEnd pgtype.Date `json:"series_end"`
|
||||
RangeStart pgtype.Timestamptz `json:"range_start"`
|
||||
RangeEnd pgtype.Timestamptz `json:"range_end"`
|
||||
}
|
||||
|
||||
type AnalyticsSubscriptionExpirationsLast30DaysRow struct {
|
||||
Date interface{} `json:"date"`
|
||||
Count int64 `json:"count"`
|
||||
}
|
||||
|
||||
// Term-plan expirations by expires_at date (lifetime plans excluded).
|
||||
func (q *Queries) AnalyticsSubscriptionExpirationsLast30Days(ctx context.Context, arg AnalyticsSubscriptionExpirationsLast30DaysParams) ([]AnalyticsSubscriptionExpirationsLast30DaysRow, error) {
|
||||
rows, err := q.db.Query(ctx, AnalyticsSubscriptionExpirationsLast30Days,
|
||||
arg.SeriesStart,
|
||||
arg.SeriesEnd,
|
||||
arg.RangeStart,
|
||||
arg.RangeEnd,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var items []AnalyticsSubscriptionExpirationsLast30DaysRow
|
||||
for rows.Next() {
|
||||
var i AnalyticsSubscriptionExpirationsLast30DaysRow
|
||||
if err := rows.Scan(&i.Date, &i.Count); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const AnalyticsSubscriptionRenewalSummary = `-- name: AnalyticsSubscriptionRenewalSummary :one
|
||||
WITH ranged_subs AS (
|
||||
SELECT
|
||||
us.id,
|
||||
us.user_id,
|
||||
us.created_at,
|
||||
us.starts_at,
|
||||
sp.category
|
||||
FROM user_subscriptions us
|
||||
JOIN subscription_plans sp ON sp.id = us.plan_id
|
||||
WHERE ($1::timestamptz IS NULL OR us.created_at >= $1::timestamptz)
|
||||
AND ($2::timestamptz IS NULL OR us.created_at < $2::timestamptz)
|
||||
),
|
||||
classified AS (
|
||||
SELECT
|
||||
rs.id,
|
||||
EXISTS (
|
||||
SELECT 1
|
||||
FROM user_subscriptions prev
|
||||
JOIN subscription_plans psp ON psp.id = prev.plan_id
|
||||
WHERE prev.user_id = rs.user_id
|
||||
AND psp.category = rs.category
|
||||
AND prev.id <> rs.id
|
||||
AND prev.created_at < rs.created_at
|
||||
) AS is_returning,
|
||||
EXISTS (
|
||||
SELECT 1
|
||||
FROM user_subscriptions prev
|
||||
JOIN subscription_plans psp ON psp.id = prev.plan_id
|
||||
WHERE prev.user_id = rs.user_id
|
||||
AND psp.category = rs.category
|
||||
AND prev.id <> rs.id
|
||||
AND prev.expires_at <= rs.starts_at
|
||||
) AS is_resubscribe_after_expiry
|
||||
FROM ranged_subs rs
|
||||
),
|
||||
expired_in_range AS (
|
||||
SELECT
|
||||
us.id AS sub_id,
|
||||
us.user_id,
|
||||
us.expires_at,
|
||||
sp.category
|
||||
FROM user_subscriptions us
|
||||
JOIN subscription_plans sp ON sp.id = us.plan_id
|
||||
WHERE sp.is_lifetime = FALSE
|
||||
AND ($1::timestamptz IS NULL OR us.expires_at >= $1::timestamptz)
|
||||
AND ($2::timestamptz IS NULL OR us.expires_at < $2::timestamptz)
|
||||
),
|
||||
renewals AS (
|
||||
SELECT
|
||||
e.sub_id,
|
||||
e.expires_at,
|
||||
MIN(n.created_at) AS resub_at
|
||||
FROM expired_in_range e
|
||||
JOIN user_subscriptions n ON n.user_id = e.user_id
|
||||
AND n.id <> e.sub_id
|
||||
AND n.created_at >= e.expires_at
|
||||
JOIN subscription_plans nsp ON nsp.id = n.plan_id
|
||||
AND nsp.category = e.category
|
||||
GROUP BY e.sub_id, e.expires_at
|
||||
)
|
||||
SELECT
|
||||
COUNT(*) FILTER (WHERE NOT c.is_returning)::bigint AS first_time_subscriptions,
|
||||
COUNT(*) FILTER (WHERE c.is_returning)::bigint AS returning_subscriptions,
|
||||
COUNT(*) FILTER (WHERE c.is_resubscribe_after_expiry)::bigint AS resubscribe_after_expiry,
|
||||
(SELECT COUNT(*)::bigint FROM expired_in_range) AS expired_in_period,
|
||||
(SELECT COUNT(*)::bigint FROM renewals) AS renewed_after_expiry,
|
||||
COALESCE(
|
||||
(SELECT AVG(EXTRACT(EPOCH FROM (r.resub_at - r.expires_at)) / 86400.0) FROM renewals r),
|
||||
0
|
||||
)::float8 AS avg_days_to_resubscribe,
|
||||
COALESCE(
|
||||
(
|
||||
SELECT PERCENTILE_CONT(0.5) WITHIN GROUP (
|
||||
ORDER BY EXTRACT(EPOCH FROM (r.resub_at - r.expires_at)) / 86400.0
|
||||
)
|
||||
FROM renewals r
|
||||
),
|
||||
0
|
||||
)::float8 AS median_days_to_resubscribe
|
||||
FROM classified c
|
||||
`
|
||||
|
||||
type AnalyticsSubscriptionRenewalSummaryParams struct {
|
||||
RangeStart pgtype.Timestamptz `json:"range_start"`
|
||||
RangeEnd pgtype.Timestamptz `json:"range_end"`
|
||||
}
|
||||
|
||||
type AnalyticsSubscriptionRenewalSummaryRow struct {
|
||||
FirstTimeSubscriptions int64 `json:"first_time_subscriptions"`
|
||||
ReturningSubscriptions int64 `json:"returning_subscriptions"`
|
||||
ResubscribeAfterExpiry int64 `json:"resubscribe_after_expiry"`
|
||||
ExpiredInPeriod int64 `json:"expired_in_period"`
|
||||
RenewedAfterExpiry int64 `json:"renewed_after_expiry"`
|
||||
AvgDaysToResubscribe float64 `json:"avg_days_to_resubscribe"`
|
||||
MedianDaysToResubscribe float64 `json:"median_days_to_resubscribe"`
|
||||
}
|
||||
|
||||
// First-time vs returning / resubscribe-after-expiry behaviour for the selected period.
|
||||
// Returning = prior subscription in the same plan category for the same learner.
|
||||
// Resubscribe after expiry = prior same-category sub whose expires_at <= new starts_at.
|
||||
// Renewal rate = expired term subs in period that got a later same-category subscription.
|
||||
func (q *Queries) AnalyticsSubscriptionRenewalSummary(ctx context.Context, arg AnalyticsSubscriptionRenewalSummaryParams) (AnalyticsSubscriptionRenewalSummaryRow, error) {
|
||||
row := q.db.QueryRow(ctx, AnalyticsSubscriptionRenewalSummary, arg.RangeStart, arg.RangeEnd)
|
||||
var i AnalyticsSubscriptionRenewalSummaryRow
|
||||
err := row.Scan(
|
||||
&i.FirstTimeSubscriptions,
|
||||
&i.ReturningSubscriptions,
|
||||
&i.ResubscribeAfterExpiry,
|
||||
&i.ExpiredInPeriod,
|
||||
&i.RenewedAfterExpiry,
|
||||
&i.AvgDaysToResubscribe,
|
||||
&i.MedianDaysToResubscribe,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const AnalyticsSubscriptionsByStatus = `-- name: AnalyticsSubscriptionsByStatus :many
|
||||
SELECT
|
||||
COALESCE(us.status, 'unknown') AS status,
|
||||
|
|
@ -831,6 +1328,83 @@ func (q *Queries) AnalyticsSubscriptionsByStatus(ctx context.Context, arg Analyt
|
|||
return items, nil
|
||||
}
|
||||
|
||||
const AnalyticsSubscriptionsSnapshot = `-- name: AnalyticsSubscriptionsSnapshot :one
|
||||
SELECT
|
||||
COUNT(*) FILTER (
|
||||
WHERE us.status = 'ACTIVE' AND us.expires_at > CURRENT_TIMESTAMP
|
||||
)::bigint AS active_now,
|
||||
COUNT(DISTINCT us.user_id) FILTER (
|
||||
WHERE us.status = 'ACTIVE' AND us.expires_at > CURRENT_TIMESTAMP
|
||||
)::bigint AS active_learners,
|
||||
COUNT(*) FILTER (WHERE us.status = 'PENDING')::bigint AS pending_now,
|
||||
COUNT(*) FILTER (
|
||||
WHERE us.status = 'EXPIRED'
|
||||
OR (us.status = 'ACTIVE' AND us.expires_at <= CURRENT_TIMESTAMP)
|
||||
)::bigint AS expired_now,
|
||||
COUNT(*) FILTER (WHERE us.status = 'CANCELLED')::bigint AS cancelled_now,
|
||||
COUNT(*) FILTER (
|
||||
WHERE us.status = 'ACTIVE'
|
||||
AND us.expires_at > CURRENT_TIMESTAMP
|
||||
AND sp.is_lifetime = FALSE
|
||||
AND us.expires_at <= CURRENT_TIMESTAMP + INTERVAL '7 days'
|
||||
)::bigint AS expiring_within_7_days,
|
||||
COUNT(*) FILTER (
|
||||
WHERE us.status = 'ACTIVE'
|
||||
AND us.expires_at > CURRENT_TIMESTAMP
|
||||
AND sp.is_lifetime = FALSE
|
||||
AND us.expires_at <= CURRENT_TIMESTAMP + INTERVAL '30 days'
|
||||
)::bigint AS expiring_within_30_days,
|
||||
COUNT(*) FILTER (
|
||||
WHERE us.status = 'ACTIVE'
|
||||
AND us.expires_at > CURRENT_TIMESTAMP
|
||||
AND us.auto_renew = TRUE
|
||||
)::bigint AS auto_renew_enabled,
|
||||
COUNT(*) FILTER (
|
||||
WHERE us.status = 'ACTIVE'
|
||||
AND us.expires_at > CURRENT_TIMESTAMP
|
||||
AND sp.is_lifetime = TRUE
|
||||
)::bigint AS lifetime_active,
|
||||
COUNT(*) FILTER (
|
||||
WHERE us.status = 'ACTIVE'
|
||||
AND us.expires_at > CURRENT_TIMESTAMP
|
||||
AND sp.is_lifetime = FALSE
|
||||
)::bigint AS term_active
|
||||
FROM user_subscriptions us
|
||||
JOIN subscription_plans sp ON sp.id = us.plan_id
|
||||
`
|
||||
|
||||
type AnalyticsSubscriptionsSnapshotRow struct {
|
||||
ActiveNow int64 `json:"active_now"`
|
||||
ActiveLearners int64 `json:"active_learners"`
|
||||
PendingNow int64 `json:"pending_now"`
|
||||
ExpiredNow int64 `json:"expired_now"`
|
||||
CancelledNow int64 `json:"cancelled_now"`
|
||||
ExpiringWithin7Days int64 `json:"expiring_within_7_days"`
|
||||
ExpiringWithin30Days int64 `json:"expiring_within_30_days"`
|
||||
AutoRenewEnabled int64 `json:"auto_renew_enabled"`
|
||||
LifetimeActive int64 `json:"lifetime_active"`
|
||||
TermActive int64 `json:"term_active"`
|
||||
}
|
||||
|
||||
// Point-in-time learner subscription behaviour (not filtered by created_at range).
|
||||
func (q *Queries) AnalyticsSubscriptionsSnapshot(ctx context.Context) (AnalyticsSubscriptionsSnapshotRow, error) {
|
||||
row := q.db.QueryRow(ctx, AnalyticsSubscriptionsSnapshot)
|
||||
var i AnalyticsSubscriptionsSnapshotRow
|
||||
err := row.Scan(
|
||||
&i.ActiveNow,
|
||||
&i.ActiveLearners,
|
||||
&i.PendingNow,
|
||||
&i.ExpiredNow,
|
||||
&i.CancelledNow,
|
||||
&i.ExpiringWithin7Days,
|
||||
&i.ExpiringWithin30Days,
|
||||
&i.AutoRenewEnabled,
|
||||
&i.LifetimeActive,
|
||||
&i.TermActive,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const AnalyticsSubscriptionsSummary = `-- name: AnalyticsSubscriptionsSummary :one
|
||||
|
||||
SELECT
|
||||
|
|
|
|||
|
|
@ -58,6 +58,21 @@ type AnalyticsUsersSection struct {
|
|||
RegistrationsLast30Days []AnalyticsTimePoint `json:"registrations_last_30_days"`
|
||||
}
|
||||
|
||||
// AnalyticsSubscriptionSnapshot is a point-in-time view of learner subscription state
|
||||
// (not filtered by the dashboard created_at date range).
|
||||
type AnalyticsSubscriptionSnapshot struct {
|
||||
ActiveNow int64 `json:"active_now"`
|
||||
ActiveLearners int64 `json:"active_learners"`
|
||||
PendingNow int64 `json:"pending_now"`
|
||||
ExpiredNow int64 `json:"expired_now"`
|
||||
CancelledNow int64 `json:"cancelled_now"`
|
||||
ExpiringWithin7Days int64 `json:"expiring_within_7_days"`
|
||||
ExpiringWithin30Days int64 `json:"expiring_within_30_days"`
|
||||
AutoRenewEnabled int64 `json:"auto_renew_enabled"`
|
||||
LifetimeActive int64 `json:"lifetime_active"`
|
||||
TermActive int64 `json:"term_active"`
|
||||
}
|
||||
|
||||
type AnalyticsSubscriptionsSection struct {
|
||||
TotalSubscriptions int64 `json:"total_subscriptions"`
|
||||
ActiveSubscriptions int64 `json:"active_subscriptions"`
|
||||
|
|
@ -69,6 +84,33 @@ type AnalyticsSubscriptionsSection struct {
|
|||
RevenueByPlan []AnalyticsRevenueByPlan `json:"revenue_by_plan"`
|
||||
|
||||
NewSubscriptionsLast30Days []AnalyticsTimePoint `json:"new_subscriptions_last_30_days"`
|
||||
|
||||
// Learner subscription behaviour
|
||||
Snapshot AnalyticsSubscriptionSnapshot `json:"snapshot"`
|
||||
ActiveByCategory []AnalyticsLabelCount `json:"active_by_category"`
|
||||
ActiveByPlan []AnalyticsLabelCount `json:"active_by_plan"`
|
||||
ActiveByLifetime []AnalyticsLabelCount `json:"active_by_lifetime"`
|
||||
AcquisitionBySource []AnalyticsLabelCount `json:"acquisition_by_source"`
|
||||
RevenueByCategory []AnalyticsLabelAmount `json:"revenue_by_category"`
|
||||
CancellationsLast30Days []AnalyticsTimePoint `json:"cancellations_last_30_days"`
|
||||
ExpirationsLast30Days []AnalyticsTimePoint `json:"expirations_last_30_days"`
|
||||
|
||||
// Resubscribe / renewal behaviour
|
||||
Renewal AnalyticsSubscriptionRenewal `json:"renewal"`
|
||||
NewByCohort []AnalyticsLabelCount `json:"new_by_cohort"`
|
||||
ResubscriptionsLast30Days []AnalyticsTimePoint `json:"resubscriptions_last_30_days"`
|
||||
}
|
||||
|
||||
// AnalyticsSubscriptionRenewal summarizes first-time vs returning buys and post-expiry renewals.
|
||||
type AnalyticsSubscriptionRenewal struct {
|
||||
FirstTimeSubscriptions int64 `json:"first_time_subscriptions"`
|
||||
ReturningSubscriptions int64 `json:"returning_subscriptions"`
|
||||
ResubscribeAfterExpiry int64 `json:"resubscribe_after_expiry"`
|
||||
ExpiredInPeriod int64 `json:"expired_in_period"`
|
||||
RenewedAfterExpiry int64 `json:"renewed_after_expiry"`
|
||||
RenewalRate float64 `json:"renewal_rate"` // 0–1; renewed_after_expiry / expired_in_period
|
||||
AvgDaysToResubscribe float64 `json:"avg_days_to_resubscribe"`
|
||||
MedianDaysToResubscribe float64 `json:"median_days_to_resubscribe"`
|
||||
}
|
||||
|
||||
type AnalyticsPaymentsSection struct {
|
||||
|
|
|
|||
|
|
@ -2,8 +2,10 @@ package domain
|
|||
|
||||
// LMSProgressSummary returns the learner's progress tree using the same access
|
||||
// contract exposed by the LMS hierarchy endpoints.
|
||||
// ExamPrep is optional: set on GET /lms/progress-summary for learners; omitted in admin LMS-only embeds.
|
||||
type LMSProgressSummary struct {
|
||||
Programs []LMSProgressSummaryProgram `json:"programs"`
|
||||
ExamPrep *ExamPrepProgressSummary `json:"exam_prep,omitempty"`
|
||||
}
|
||||
|
||||
type LMSProgressSummaryProgram struct {
|
||||
|
|
|
|||
|
|
@ -24,13 +24,15 @@ var (
|
|||
)
|
||||
|
||||
const (
|
||||
ProfileFieldEducationLevel = "education_level"
|
||||
ProfileFieldOccupation = "occupation"
|
||||
ProfileFieldAgeGroup = "age_group"
|
||||
ProfileFieldLearningGoal = "learning_goal"
|
||||
ProfileFieldEducationLevel = "education_level"
|
||||
ProfileFieldOccupation = "occupation"
|
||||
ProfileFieldAgeGroup = "age_group"
|
||||
ProfileFieldLearningGoal = "learning_goal"
|
||||
ProfileFieldLanguageChallange = "language_challange"
|
||||
ProfileFieldLanguageGoal = "language_goal"
|
||||
ProfileFieldFavouriteTopic = "favourite_topic"
|
||||
ProfileFieldLanguageGoal = "language_goal"
|
||||
ProfileFieldFavouriteTopic = "favourite_topic"
|
||||
ProfileFieldCountry = "country"
|
||||
ProfileFieldEthiopiaRegions = "ethiopia_regions"
|
||||
)
|
||||
|
||||
// User profile columns validated against field_options on PUT /user (when non-empty).
|
||||
|
|
|
|||
96
internal/web_server/handlers/analytics_field_normalize.go
Normal file
96
internal/web_server/handlers/analytics_field_normalize.go
Normal file
|
|
@ -0,0 +1,96 @@
|
|||
package handlers
|
||||
|
||||
import (
|
||||
"Yimaru-Backend/internal/domain"
|
||||
"context"
|
||||
"sort"
|
||||
"strings"
|
||||
)
|
||||
|
||||
const analyticsOtherLabel = "OTHER"
|
||||
|
||||
// analyticsProfileFieldKeys are user-profile breakdowns validated against field_options.
|
||||
var analyticsProfileFieldKeys = []string{
|
||||
domain.ProfileFieldAgeGroup,
|
||||
domain.ProfileFieldEducationLevel,
|
||||
domain.ProfileFieldOccupation,
|
||||
domain.ProfileFieldLearningGoal,
|
||||
domain.ProfileFieldLanguageChallange,
|
||||
domain.ProfileFieldCountry,
|
||||
domain.ProfileFieldEthiopiaRegions,
|
||||
}
|
||||
|
||||
func (h *Handler) loadAnalyticsFieldOptionSets(ctx context.Context) (map[string][]domain.ProfileFieldOption, error) {
|
||||
sets := make(map[string][]domain.ProfileFieldOption, len(analyticsProfileFieldKeys))
|
||||
if h.profileFieldOptionSvc == nil {
|
||||
return sets, nil
|
||||
}
|
||||
active := domain.ProfileFieldOptionStatusActive
|
||||
for _, key := range analyticsProfileFieldKeys {
|
||||
fieldKey := key
|
||||
options, _, err := h.profileFieldOptionSvc.ListProfileFieldOptions(ctx, &fieldKey, &active, 500, 0)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
sets[key] = options
|
||||
}
|
||||
return sets, nil
|
||||
}
|
||||
|
||||
func normalizeAnalyticsOptionKey(raw string) string {
|
||||
normalized := strings.ToUpper(strings.TrimSpace(raw))
|
||||
normalized = strings.ReplaceAll(normalized, " ", "_")
|
||||
normalized = strings.ReplaceAll(normalized, "-", "_")
|
||||
return normalized
|
||||
}
|
||||
|
||||
// resolveAnalyticsFieldLabel maps a stored user value to a static field_options code.
|
||||
// Empty / "unknown" / values not in the option list become OTHER.
|
||||
// When options is empty, only empty/unknown are remapped (other values kept as-is).
|
||||
func resolveAnalyticsFieldLabel(raw string, options []domain.ProfileFieldOption) string {
|
||||
trimmed := strings.TrimSpace(raw)
|
||||
if trimmed == "" || strings.EqualFold(trimmed, "unknown") {
|
||||
return analyticsOtherLabel
|
||||
}
|
||||
if len(options) == 0 {
|
||||
return trimmed
|
||||
}
|
||||
|
||||
key := normalizeAnalyticsOptionKey(trimmed)
|
||||
for _, opt := range options {
|
||||
if strings.EqualFold(opt.Code, trimmed) || normalizeAnalyticsOptionKey(opt.Code) == key {
|
||||
return opt.Code
|
||||
}
|
||||
if strings.EqualFold(strings.TrimSpace(opt.Label), trimmed) {
|
||||
return opt.Code
|
||||
}
|
||||
}
|
||||
return analyticsOtherLabel
|
||||
}
|
||||
|
||||
func collapseAnalyticsLabelCounts(rows []domain.AnalyticsLabelCount, options []domain.ProfileFieldOption) []domain.AnalyticsLabelCount {
|
||||
if len(rows) == 0 {
|
||||
return rows
|
||||
}
|
||||
sums := make(map[string]int64, len(rows))
|
||||
for _, row := range rows {
|
||||
label := resolveAnalyticsFieldLabel(row.Label, options)
|
||||
sums[label] += row.Count
|
||||
}
|
||||
out := make([]domain.AnalyticsLabelCount, 0, len(sums))
|
||||
for label, count := range sums {
|
||||
out = append(out, domain.AnalyticsLabelCount{Label: label, Count: count})
|
||||
}
|
||||
sort.Slice(out, func(i, j int) bool {
|
||||
if out[i].Count == out[j].Count {
|
||||
return out[i].Label < out[j].Label
|
||||
}
|
||||
return out[i].Count > out[j].Count
|
||||
})
|
||||
return out
|
||||
}
|
||||
|
||||
// collapseUnknownToOther remaps empty/unknown labels when no field_options catalog exists.
|
||||
func collapseUnknownToOther(rows []domain.AnalyticsLabelCount) []domain.AnalyticsLabelCount {
|
||||
return collapseAnalyticsLabelCounts(rows, nil)
|
||||
}
|
||||
|
|
@ -0,0 +1,89 @@
|
|||
package handlers
|
||||
|
||||
import (
|
||||
"Yimaru-Backend/internal/domain"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestResolveAnalyticsFieldLabel(t *testing.T) {
|
||||
options := []domain.ProfileFieldOption{
|
||||
{Code: "ET", Label: "Ethiopia"},
|
||||
{Code: "EVERYDAY_CONVERSATION", Label: "Everyday conversation"},
|
||||
{Code: "OTHER", Label: "Other"},
|
||||
{Code: "ADDIS_ABABA", Label: "Addis Ababa"},
|
||||
}
|
||||
|
||||
cases := []struct {
|
||||
raw string
|
||||
want string
|
||||
}{
|
||||
{"", "OTHER"},
|
||||
{"unknown", "OTHER"},
|
||||
{"Unknown", "OTHER"},
|
||||
{"ET", "ET"},
|
||||
{"et", "ET"},
|
||||
{"Ethiopia", "ET"},
|
||||
{"EVERYDAY_CONVERSATION", "EVERYDAY_CONVERSATION"},
|
||||
{"Everyday conversation", "EVERYDAY_CONVERSATION"},
|
||||
{"Learn to Speak English", "OTHER"},
|
||||
{"Nurse", "OTHER"},
|
||||
{"addis abeba", "OTHER"},
|
||||
{"Addis Ababa", "ADDIS_ABABA"},
|
||||
{"OTHER", "OTHER"},
|
||||
}
|
||||
|
||||
for _, tc := range cases {
|
||||
got := resolveAnalyticsFieldLabel(tc.raw, options)
|
||||
if got != tc.want {
|
||||
t.Fatalf("resolveAnalyticsFieldLabel(%q) = %q, want %q", tc.raw, got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCollapseAnalyticsLabelCounts(t *testing.T) {
|
||||
options := []domain.ProfileFieldOption{
|
||||
{Code: "ET", Label: "Ethiopia"},
|
||||
{Code: "PRONUNCIATION", Label: "Pronunciation"},
|
||||
{Code: "OTHER", Label: "Other"},
|
||||
}
|
||||
rows := []domain.AnalyticsLabelCount{
|
||||
{Label: "ET", Count: 10},
|
||||
{Label: "Ethiopia", Count: 2},
|
||||
{Label: "unknown", Count: 5},
|
||||
{Label: "Pronunciation", Count: 3},
|
||||
{Label: "Grammar", Count: 1},
|
||||
{Label: "OTHER", Count: 4},
|
||||
}
|
||||
|
||||
got := collapseAnalyticsLabelCounts(rows, options)
|
||||
want := map[string]int64{
|
||||
"ET": 12,
|
||||
"PRONUNCIATION": 3,
|
||||
"OTHER": 10, // 5 unknown + 1 Grammar + 4 OTHER
|
||||
}
|
||||
if len(got) != len(want) {
|
||||
t.Fatalf("got %d rows, want %d: %+v", len(got), len(want), got)
|
||||
}
|
||||
for _, row := range got {
|
||||
if want[row.Label] != row.Count {
|
||||
t.Fatalf("label %q count = %d, want %d", row.Label, row.Count, want[row.Label])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCollapseUnknownToOtherWithoutOptions(t *testing.T) {
|
||||
rows := []domain.AnalyticsLabelCount{
|
||||
{Label: "BEGINNER", Count: 3},
|
||||
{Label: "unknown", Count: 2},
|
||||
}
|
||||
got := collapseUnknownToOther(rows)
|
||||
want := map[string]int64{"BEGINNER": 3, "OTHER": 2}
|
||||
if len(got) != len(want) {
|
||||
t.Fatalf("got %+v", got)
|
||||
}
|
||||
for _, row := range got {
|
||||
if want[row.Label] != row.Count {
|
||||
t.Fatalf("label %q count = %d, want %d", row.Label, row.Count, want[row.Label])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -110,6 +110,46 @@ func (h *Handler) GetAnalyticsDashboard(c *fiber.Ctx) error {
|
|||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusInternalServerError, "Failed to fetch new subscriptions time series")
|
||||
}
|
||||
subsSnapshot, err := h.analyticsDB.AnalyticsSubscriptionsSnapshot(ctx)
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusInternalServerError, "Failed to fetch subscription snapshot")
|
||||
}
|
||||
activeByCategory, err := h.analyticsDB.AnalyticsActiveSubscriptionsByCategory(ctx)
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusInternalServerError, "Failed to fetch active subscriptions by category")
|
||||
}
|
||||
activeByPlan, err := h.analyticsDB.AnalyticsActiveSubscriptionsByPlan(ctx)
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusInternalServerError, "Failed to fetch active subscriptions by plan")
|
||||
}
|
||||
activeByLifetime, err := h.analyticsDB.AnalyticsActiveSubscriptionsByLifetime(ctx)
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusInternalServerError, "Failed to fetch active subscriptions by lifetime")
|
||||
}
|
||||
acquisitionBySource, err := h.analyticsDB.AnalyticsSubscriptionAcquisitionBySource(ctx, p.AcquisitionBySource)
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusInternalServerError, "Failed to fetch subscription acquisition by source")
|
||||
}
|
||||
revenueByCategory, err := h.analyticsDB.AnalyticsRevenueByPlanCategory(ctx, p.RevenueByCategory)
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusInternalServerError, "Failed to fetch revenue by plan category")
|
||||
}
|
||||
cancellations30, err := h.analyticsDB.AnalyticsSubscriptionCancellationsLast30Days(ctx, p.CancellationsSeries)
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusInternalServerError, "Failed to fetch subscription cancellations time series")
|
||||
}
|
||||
expirations30, err := h.analyticsDB.AnalyticsSubscriptionExpirationsLast30Days(ctx, p.ExpirationsSeries)
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusInternalServerError, "Failed to fetch subscription expirations time series")
|
||||
}
|
||||
renewalSummary, err := h.analyticsDB.AnalyticsSubscriptionRenewalSummary(ctx, p.RenewalSummary)
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusInternalServerError, "Failed to fetch subscription renewal analytics")
|
||||
}
|
||||
resubscriptions30, err := h.analyticsDB.AnalyticsResubscriptionsLast30Days(ctx, p.ResubscriptionsSeries)
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusInternalServerError, "Failed to fetch resubscriptions time series")
|
||||
}
|
||||
|
||||
paymentsSummary, err := h.analyticsDB.AnalyticsPaymentsSummary(ctx, p.PaymentsSummary)
|
||||
if err != nil {
|
||||
|
|
@ -205,6 +245,11 @@ func (h *Handler) GetAnalyticsDashboard(c *fiber.Ctx) error {
|
|||
return fiber.NewError(fiber.StatusInternalServerError, "Failed to fetch video drop-off analytics")
|
||||
}
|
||||
|
||||
fieldOptions, err := h.loadAnalyticsFieldOptionSets(ctx)
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusInternalServerError, "Failed to load profile field options for analytics")
|
||||
}
|
||||
|
||||
dashboard := domain.AnalyticsDashboard{
|
||||
GeneratedAt: time.Now().UTC(),
|
||||
DateFilter: filter,
|
||||
|
|
@ -212,8 +257,24 @@ func (h *Handler) GetAnalyticsDashboard(c *fiber.Ctx) error {
|
|||
usersSummary, usersByRole, usersByStatus, usersByAge,
|
||||
usersByEducation, usersByOccupation, usersByLearningGoal, usersByLanguageChallange,
|
||||
usersByKnowledge, usersByCountry, usersByRegion, userRegs,
|
||||
fieldOptions,
|
||||
),
|
||||
Subscriptions: mapSubscriptionsSection(
|
||||
subsSummary,
|
||||
subsByStatus,
|
||||
revenueByPlan,
|
||||
newSubs30,
|
||||
subsSnapshot,
|
||||
activeByCategory,
|
||||
activeByPlan,
|
||||
activeByLifetime,
|
||||
acquisitionBySource,
|
||||
revenueByCategory,
|
||||
cancellations30,
|
||||
expirations30,
|
||||
renewalSummary,
|
||||
resubscriptions30,
|
||||
),
|
||||
Subscriptions: mapSubscriptionsSection(subsSummary, subsByStatus, revenueByPlan, newSubs30),
|
||||
Payments: mapPaymentsSection(paymentsSummary, paymentsByStatus, paymentsByMethod, revenue30, revenueMonthlyRows, monthlyRevenueYear),
|
||||
Courses: mapCoursesSection(courseCounts),
|
||||
Videos: mapVideosSection(videoSummary, videoDropOff),
|
||||
|
|
@ -267,6 +328,7 @@ func mapUsersSection(
|
|||
byCountry []dbgen.AnalyticsUsersByCountryRow,
|
||||
byRegion []dbgen.AnalyticsUsersByRegionRow,
|
||||
regs []dbgen.AnalyticsUserRegistrationsLast30DaysRow,
|
||||
fieldOptions map[string][]domain.ProfileFieldOption,
|
||||
) domain.AnalyticsUsersSection {
|
||||
roles := make([]domain.AnalyticsLabelCount, len(byRole))
|
||||
for i, r := range byRole {
|
||||
|
|
@ -312,21 +374,29 @@ func mapUsersSection(
|
|||
for i, r := range regs {
|
||||
timePoints[i] = domain.AnalyticsTimePoint{Date: toTime(r.Date), Count: r.Count}
|
||||
}
|
||||
|
||||
if fieldOptions == nil {
|
||||
fieldOptions = map[string][]domain.ProfileFieldOption{}
|
||||
}
|
||||
|
||||
return domain.AnalyticsUsersSection{
|
||||
TotalUsers: summary.Total,
|
||||
NewToday: summary.NewToday,
|
||||
NewWeek: summary.NewThisWeek,
|
||||
NewMonth: summary.NewThisMonth,
|
||||
ByRole: roles,
|
||||
ByStatus: statuses,
|
||||
ByAgeGroup: ages,
|
||||
ByEducationLevel: education,
|
||||
ByOccupation: occupations,
|
||||
ByLearningGoal: learningGoals,
|
||||
ByLanguageChallange: languageChallanges,
|
||||
ByKnowledgeLevel: knowledge,
|
||||
ByCountry: countries,
|
||||
ByRegion: regions,
|
||||
TotalUsers: summary.Total,
|
||||
NewToday: summary.NewToday,
|
||||
NewWeek: summary.NewThisWeek,
|
||||
NewMonth: summary.NewThisMonth,
|
||||
ByRole: roles,
|
||||
ByStatus: statuses,
|
||||
ByAgeGroup: collapseAnalyticsLabelCounts(ages, fieldOptions[domain.ProfileFieldAgeGroup]),
|
||||
ByEducationLevel: collapseAnalyticsLabelCounts(education, fieldOptions[domain.ProfileFieldEducationLevel]),
|
||||
ByOccupation: collapseAnalyticsLabelCounts(occupations, fieldOptions[domain.ProfileFieldOccupation]),
|
||||
ByLearningGoal: collapseAnalyticsLabelCounts(learningGoals, fieldOptions[domain.ProfileFieldLearningGoal]),
|
||||
ByLanguageChallange: collapseAnalyticsLabelCounts(
|
||||
languageChallanges,
|
||||
fieldOptions[domain.ProfileFieldLanguageChallange],
|
||||
),
|
||||
ByKnowledgeLevel: collapseUnknownToOther(knowledge),
|
||||
ByCountry: collapseAnalyticsLabelCounts(countries, fieldOptions[domain.ProfileFieldCountry]),
|
||||
ByRegion: collapseAnalyticsLabelCounts(regions, fieldOptions[domain.ProfileFieldEthiopiaRegions]),
|
||||
RegistrationsLast30Days: timePoints,
|
||||
}
|
||||
}
|
||||
|
|
@ -336,6 +406,16 @@ func mapSubscriptionsSection(
|
|||
byStatus []dbgen.AnalyticsSubscriptionsByStatusRow,
|
||||
byPlan []dbgen.AnalyticsRevenueByPlanRow,
|
||||
newSubs []dbgen.AnalyticsNewSubscriptionsLast30DaysRow,
|
||||
snapshot dbgen.AnalyticsSubscriptionsSnapshotRow,
|
||||
activeByCategory []dbgen.AnalyticsActiveSubscriptionsByCategoryRow,
|
||||
activeByPlan []dbgen.AnalyticsActiveSubscriptionsByPlanRow,
|
||||
activeByLifetime []dbgen.AnalyticsActiveSubscriptionsByLifetimeRow,
|
||||
acquisitionBySource []dbgen.AnalyticsSubscriptionAcquisitionBySourceRow,
|
||||
revenueByCategory []dbgen.AnalyticsRevenueByPlanCategoryRow,
|
||||
cancellations []dbgen.AnalyticsSubscriptionCancellationsLast30DaysRow,
|
||||
expirations []dbgen.AnalyticsSubscriptionExpirationsLast30DaysRow,
|
||||
renewal dbgen.AnalyticsSubscriptionRenewalSummaryRow,
|
||||
resubscriptions []dbgen.AnalyticsResubscriptionsLast30DaysRow,
|
||||
) domain.AnalyticsSubscriptionsSection {
|
||||
statuses := make([]domain.AnalyticsLabelCount, len(byStatus))
|
||||
for i, r := range byStatus {
|
||||
|
|
@ -349,6 +429,44 @@ func mapSubscriptionsSection(
|
|||
for i, r := range newSubs {
|
||||
timePoints[i] = domain.AnalyticsTimePoint{Date: toTime(r.Date), Count: r.Count}
|
||||
}
|
||||
byCategory := make([]domain.AnalyticsLabelCount, len(activeByCategory))
|
||||
for i, r := range activeByCategory {
|
||||
byCategory[i] = domain.AnalyticsLabelCount{Label: r.Label, Count: r.Count}
|
||||
}
|
||||
byActivePlan := make([]domain.AnalyticsLabelCount, len(activeByPlan))
|
||||
for i, r := range activeByPlan {
|
||||
byActivePlan[i] = domain.AnalyticsLabelCount{Label: r.Label, Count: r.Count}
|
||||
}
|
||||
byLifetime := make([]domain.AnalyticsLabelCount, len(activeByLifetime))
|
||||
for i, r := range activeByLifetime {
|
||||
byLifetime[i] = domain.AnalyticsLabelCount{Label: r.Label, Count: r.Count}
|
||||
}
|
||||
bySource := make([]domain.AnalyticsLabelCount, len(acquisitionBySource))
|
||||
for i, r := range acquisitionBySource {
|
||||
bySource[i] = domain.AnalyticsLabelCount{Label: r.Label, Count: r.Count}
|
||||
}
|
||||
revByCategory := make([]domain.AnalyticsLabelAmount, len(revenueByCategory))
|
||||
for i, r := range revenueByCategory {
|
||||
revByCategory[i] = domain.AnalyticsLabelAmount{Label: r.Label, Count: r.Count, Amount: r.Amount}
|
||||
}
|
||||
cancelPoints := make([]domain.AnalyticsTimePoint, len(cancellations))
|
||||
for i, r := range cancellations {
|
||||
cancelPoints[i] = domain.AnalyticsTimePoint{Date: toTime(r.Date), Count: r.Count}
|
||||
}
|
||||
expirePoints := make([]domain.AnalyticsTimePoint, len(expirations))
|
||||
for i, r := range expirations {
|
||||
expirePoints[i] = domain.AnalyticsTimePoint{Date: toTime(r.Date), Count: r.Count}
|
||||
}
|
||||
resubPoints := make([]domain.AnalyticsTimePoint, len(resubscriptions))
|
||||
for i, r := range resubscriptions {
|
||||
resubPoints[i] = domain.AnalyticsTimePoint{Date: toTime(r.Date), Count: r.Count}
|
||||
}
|
||||
|
||||
var renewalRate float64
|
||||
if renewal.ExpiredInPeriod > 0 {
|
||||
renewalRate = float64(renewal.RenewedAfterExpiry) / float64(renewal.ExpiredInPeriod)
|
||||
}
|
||||
|
||||
return domain.AnalyticsSubscriptionsSection{
|
||||
TotalSubscriptions: summary.Total,
|
||||
ActiveSubscriptions: summary.Active,
|
||||
|
|
@ -358,6 +476,40 @@ func mapSubscriptionsSection(
|
|||
ByStatus: statuses,
|
||||
RevenueByPlan: plans,
|
||||
NewSubscriptionsLast30Days: timePoints,
|
||||
Snapshot: domain.AnalyticsSubscriptionSnapshot{
|
||||
ActiveNow: snapshot.ActiveNow,
|
||||
ActiveLearners: snapshot.ActiveLearners,
|
||||
PendingNow: snapshot.PendingNow,
|
||||
ExpiredNow: snapshot.ExpiredNow,
|
||||
CancelledNow: snapshot.CancelledNow,
|
||||
ExpiringWithin7Days: snapshot.ExpiringWithin7Days,
|
||||
ExpiringWithin30Days: snapshot.ExpiringWithin30Days,
|
||||
AutoRenewEnabled: snapshot.AutoRenewEnabled,
|
||||
LifetimeActive: snapshot.LifetimeActive,
|
||||
TermActive: snapshot.TermActive,
|
||||
},
|
||||
ActiveByCategory: byCategory,
|
||||
ActiveByPlan: byActivePlan,
|
||||
ActiveByLifetime: byLifetime,
|
||||
AcquisitionBySource: bySource,
|
||||
RevenueByCategory: revByCategory,
|
||||
CancellationsLast30Days: cancelPoints,
|
||||
ExpirationsLast30Days: expirePoints,
|
||||
Renewal: domain.AnalyticsSubscriptionRenewal{
|
||||
FirstTimeSubscriptions: renewal.FirstTimeSubscriptions,
|
||||
ReturningSubscriptions: renewal.ReturningSubscriptions,
|
||||
ResubscribeAfterExpiry: renewal.ResubscribeAfterExpiry,
|
||||
ExpiredInPeriod: renewal.ExpiredInPeriod,
|
||||
RenewedAfterExpiry: renewal.RenewedAfterExpiry,
|
||||
RenewalRate: renewalRate,
|
||||
AvgDaysToResubscribe: renewal.AvgDaysToResubscribe,
|
||||
MedianDaysToResubscribe: renewal.MedianDaysToResubscribe,
|
||||
},
|
||||
NewByCohort: []domain.AnalyticsLabelCount{
|
||||
{Label: "first_time", Count: renewal.FirstTimeSubscriptions},
|
||||
{Label: "returning", Count: renewal.ReturningSubscriptions},
|
||||
},
|
||||
ResubscriptionsLast30Days: resubPoints,
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -26,6 +26,12 @@ type analyticsQueryParams struct {
|
|||
SubscriptionsByStatus dbgen.AnalyticsSubscriptionsByStatusParams
|
||||
RevenueByPlan dbgen.AnalyticsRevenueByPlanParams
|
||||
NewSubscriptionsSeries dbgen.AnalyticsNewSubscriptionsLast30DaysParams
|
||||
AcquisitionBySource dbgen.AnalyticsSubscriptionAcquisitionBySourceParams
|
||||
RevenueByCategory dbgen.AnalyticsRevenueByPlanCategoryParams
|
||||
CancellationsSeries dbgen.AnalyticsSubscriptionCancellationsLast30DaysParams
|
||||
ExpirationsSeries dbgen.AnalyticsSubscriptionExpirationsLast30DaysParams
|
||||
RenewalSummary dbgen.AnalyticsSubscriptionRenewalSummaryParams
|
||||
ResubscriptionsSeries dbgen.AnalyticsResubscriptionsLast30DaysParams
|
||||
|
||||
PaymentsSummary dbgen.AnalyticsPaymentsSummaryParams
|
||||
PaymentsByStatus dbgen.AnalyticsPaymentsByStatusParams
|
||||
|
|
@ -85,6 +91,27 @@ func newAnalyticsQueryParams(f domain.AnalyticsDateFilter) analyticsQueryParams
|
|||
RangeStart: rs,
|
||||
RangeEnd: re,
|
||||
},
|
||||
AcquisitionBySource: dbgen.AnalyticsSubscriptionAcquisitionBySourceParams{RangeStart: rs, RangeEnd: re},
|
||||
RevenueByCategory: dbgen.AnalyticsRevenueByPlanCategoryParams{RangeStart: rs, RangeEnd: re},
|
||||
CancellationsSeries: dbgen.AnalyticsSubscriptionCancellationsLast30DaysParams{
|
||||
SeriesStart: series.SeriesStart,
|
||||
SeriesEnd: series.SeriesEnd,
|
||||
RangeStart: rs,
|
||||
RangeEnd: re,
|
||||
},
|
||||
ExpirationsSeries: dbgen.AnalyticsSubscriptionExpirationsLast30DaysParams{
|
||||
SeriesStart: series.SeriesStart,
|
||||
SeriesEnd: series.SeriesEnd,
|
||||
RangeStart: rs,
|
||||
RangeEnd: re,
|
||||
},
|
||||
RenewalSummary: dbgen.AnalyticsSubscriptionRenewalSummaryParams{RangeStart: rs, RangeEnd: re},
|
||||
ResubscriptionsSeries: dbgen.AnalyticsResubscriptionsLast30DaysParams{
|
||||
SeriesStart: series.SeriesStart,
|
||||
SeriesEnd: series.SeriesEnd,
|
||||
RangeStart: rs,
|
||||
RangeEnd: re,
|
||||
},
|
||||
|
||||
PaymentsSummary: dbgen.AnalyticsPaymentsSummaryParams{RangeStart: rs, RangeEnd: re},
|
||||
PaymentsByStatus: dbgen.AnalyticsPaymentsByStatusParams{RangeStart: rs, RangeEnd: re},
|
||||
|
|
|
|||
|
|
@ -38,8 +38,8 @@ func (h *Handler) GetMyLMSProgress(c *fiber.Ctx) error {
|
|||
}
|
||||
|
||||
// GetMyLMSProgressSummary godoc
|
||||
// @Summary Get my LMS progress summary
|
||||
// @Description Returns the learner's nested LMS hierarchy with the same access progress data exposed on the individual program, course, module, and lesson APIs.
|
||||
// @Summary Get my LMS and exam-prep progress summary
|
||||
// @Description Returns the learner's nested Learn English hierarchy (programs) and exam-prep hierarchy (exam_prep) with the same access progress data exposed on the individual content APIs.
|
||||
// @Tags lms
|
||||
// @Produce json
|
||||
// @Success 200 {object} domain.Response
|
||||
|
|
@ -55,6 +55,14 @@ func (h *Handler) GetMyLMSProgressSummary(c *fiber.Ctx) error {
|
|||
Error: err.Error(),
|
||||
})
|
||||
}
|
||||
examPrep, err := h.buildExamPrepProgressSummary(c.Context(), role, uid, !h.canManageExamPrepCatalogCourses(c))
|
||||
if err != nil {
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
|
||||
Message: "Failed to load exam prep progress summary",
|
||||
Error: err.Error(),
|
||||
})
|
||||
}
|
||||
summary.ExamPrep = &examPrep
|
||||
return c.JSON(domain.Response{
|
||||
Message: "LMS progress summary retrieved successfully",
|
||||
Data: summary,
|
||||
|
|
|
|||
Loading…
Reference in New Issue
Block a user