Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion apps/stats/src/hooks/useGrowthStats.ts
Original file line number Diff line number Diff line change
Expand Up @@ -204,7 +204,11 @@ export const useGrowthStats = (range: number) => {
}
});

const {data: mrrHistoryResponse, isLoading: isMrrLoading} = useMrrHistory();
const {data: mrrHistoryResponse, isLoading: isMrrLoading} = useMrrHistory({
searchParams: {
date_from: memberDataStartDate
}
});

// Fetch subscription stats for real subscription events
const {data: subscriptionStatsResponse, isLoading: isSubscriptionLoading} = useSubscriptionStats();
Expand Down
14 changes: 10 additions & 4 deletions ghost/core/core/server/api/endpoints/stats.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,14 +35,20 @@ const controller = {
docName: 'members',
method: 'browse'
},
options: [
'date_from'
],
cache: statsService.cache,
generateCacheKeyData() {
generateCacheKeyData(frame) {
return {
method: 'mrr'
method: 'mrr',
options: frame.options
};
},
async query() {
return await statsService.api.getMRRHistory();
async query(frame) {
return await statsService.api.getMRRHistory({
dateFrom: frame?.options?.date_from
});
}
},
subscriptions: {
Expand Down
15 changes: 10 additions & 5 deletions ghost/core/core/server/services/stats/MrrStatsService.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,32 +34,37 @@ class MrrStatsService {

/**
* Get the MRR deltas for all days (from old to new), grouped by currency (ascending alphabetically)
* @param {string} [dateFrom] - Start date to fetch deltas from
* @returns {Promise<MrrDelta[]>} The deltas sorted from new to old
*/
async fetchAllDeltas() {
async fetchAllDeltas(dateFrom) {
const knex = this.knex;
const ninetyDaysAgo = moment.utc().subtract(90, 'days').startOf('day').utc().format('YYYY-MM-DD HH:mm:ss');
const startDate = dateFrom
? moment.utc(dateFrom).startOf('day').utc().format('YYYY-MM-DD HH:mm:ss')
: moment.utc().subtract(90, 'days').startOf('day').utc().format('YYYY-MM-DD HH:mm:ss');
const rows = await knex('members_paid_subscription_events')
Comment on lines +42 to 45
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Validate and normalize dateFrom; fall back if invalid.

An invalid dateFrom produces 'Invalid date' and an unexpected WHERE bound.

Apply:

-        const startDate = dateFrom
-            ? moment.utc(dateFrom).startOf('day').utc().format('YYYY-MM-DD HH:mm:ss')
-            : moment.utc().subtract(90, 'days').startOf('day').utc().format('YYYY-MM-DD HH:mm:ss');
+        const parsed = dateFrom ? moment.utc(dateFrom, ['YYYY-MM-DD', moment.ISO_8601], true) : null;
+        const startDate = parsed?.isValid()
+            ? parsed.startOf('day').format('YYYY-MM-DD HH:mm:ss')
+            : moment.utc().subtract(90, 'days').startOf('day').format('YYYY-MM-DD HH:mm:ss');
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const startDate = dateFrom
? moment.utc(dateFrom).startOf('day').utc().format('YYYY-MM-DD HH:mm:ss')
: moment.utc().subtract(90, 'days').startOf('day').utc().format('YYYY-MM-DD HH:mm:ss');
const rows = await knex('members_paid_subscription_events')
const parsed = dateFrom ? moment.utc(dateFrom, ['YYYY-MM-DD', moment.ISO_8601], true) : null;
const startDate = parsed?.isValid()
? parsed.startOf('day').format('YYYY-MM-DD HH:mm:ss')
: moment.utc().subtract(90, 'days').startOf('day').format('YYYY-MM-DD HH:mm:ss');
const rows = await knex('members_paid_subscription_events')
🤖 Prompt for AI Agents
In ghost/core/core/server/services/stats/MrrStatsService.js around lines 42 to
45, the current ternary uses moment.utc(dateFrom) without validating it so an
invalid dateFrom yields "Invalid date" and bad query bindings; change this to
explicitly parse and validate dateFrom (e.g. const parsed =
moment.utc(dateFrom); if (dateFrom && parsed.isValid()) use
parsed.startOf('day').utc().format('YYYY-MM-DD HH:mm:ss') else fall back to
moment.utc().subtract(90, 'days').startOf('day').utc().format(...)); ensure you
handle non-string/undefined inputs, use the validated/normalized string in the
WHERE binding, and remove the original ternary.

.select('currency')
// In SQLite, DATE(created_at) would map to a string value, while DATE(created_at) would map to a JSDate object in MySQL
// That is why we need the cast here (to have some consistency)
.select(knex.raw('CAST(DATE(created_at) as CHAR) as date'))
.select(knex.raw(`SUM(mrr_delta) as delta`))
.where('created_at', '>=', ninetyDaysAgo)
.where('created_at', '>=', startDate)
.groupByRaw('CAST(DATE(created_at) as CHAR), currency');
return rows;
}

/**
* Returns a list of the MRR history for each day and currency, including the current MRR per currency as meta data.
* The respons is in ascending date order, and currencies for the same date are always in ascending order.
* @param {Object} [options]
* @param {string} [options.dateFrom] - Start date to fetch history from
* @returns {Promise<MrrHistory>}
*/
async getHistory() {
async getHistory(options = {}) {
// Fetch current total amounts and start counting from there
const totals = await this.getCurrentMrr();

const rows = await this.fetchAllDeltas();
const rows = await this.fetchAllDeltas(options.dateFrom);

rows.sort((rowA, rowB) => {
const dateA = new Date(rowA.date);
Expand Down
4 changes: 2 additions & 2 deletions ghost/core/core/server/services/stats/StatsService.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,8 @@ class StatsService {
this.content = deps.content;
}

async getMRRHistory() {
return this.mrr.getHistory();
async getMRRHistory(options = {}) {
return this.mrr.getHistory(options);
}

/**
Expand Down
Loading