diff --git a/packages/commonwealth/server/routes/communityStats.ts b/packages/commonwealth/server/routes/communityStats.ts index e6f26c1d09e..7c210f4b05e 100644 --- a/packages/commonwealth/server/routes/communityStats.ts +++ b/packages/commonwealth/server/routes/communityStats.ts @@ -36,13 +36,16 @@ const communityStats = async ( // get new objects created over the last ${numberOfPrevDays} days const newObjectsQuery = async (table: string) => { + const isComments = table === '"Comments"'; + return models.sequelize.query( ` - SELECT seq.date, COUNT(${table}.*) AS new_items + SELECT seq.date, COUNT(tbl.*) AS new_items FROM ( SELECT CURRENT_DATE - seq.date AS date FROM generate_series(0, ${numberOfPrevDays}) AS seq(date) ) seq - LEFT JOIN ${table} ON ${table}.created_at::date = seq.date - WHERE ${table}.community_id = :communityId - GROUP BY seq.date + LEFT JOIN ${table} tbl ON tbl.created_at::date = seq.date + ${isComments ? 'LEFT JOIN "Threads" t on t.id = tbl.thread_id' : ''} + WHERE ${isComments ? 't' : 'tbl'}.community_id = :communityId + GROUP BY seq.date ${isComments ? ', t.community_id' : ''} ORDER BY seq.date DESC;`, { type: QueryTypes.SELECT, @@ -57,8 +60,13 @@ const communityStats = async ( // get total number of roles, threads, and comments const totalObjectsQuery = async (table: string) => { + const isComments = table === '"Comments"'; + return models.sequelize.query( - `SELECT COUNT(id) AS new_items FROM ${table} WHERE community_id = :communityId;`, + `SELECT COUNT(tbl.id) AS new_items + FROM ${table} tbl + ${isComments ? 'LEFT JOIN "Threads" t on t.id = tbl.thread_id' : ''} + WHERE ${isComments ? 't' : 'tbl'}.community_id = :communityId;`, { type: QueryTypes.SELECT, // @ts-expect-error StrictNullChecks @@ -79,10 +87,16 @@ LEFT JOIN ( SELECT address_id, created_at FROM "Threads" WHERE created_at > CURRENT_DATE - ${numberOfPrevDays} AND community_id = :communityId UNION - SELECT address_id, created_at FROM "Comments" WHERE created_at > CURRENT_DATE - ${numberOfPrevDays} - AND community_id = :communityId + SELECT + c.address_id, c.created_at + FROM "Comments" c + LEFT JOIN "Threads" t on t.id = c.thread_id WHERE c.created_at > CURRENT_DATE - ${numberOfPrevDays} + AND t.community_id = :communityId UNION - SELECT address_id, created_at FROM "Reactions" WHERE created_at > CURRENT_DATE - ${numberOfPrevDays} + SELECT + r.address_id, r.created_at + FROM "Reactions" r + LEFT JOIN "Threads" t on t.id = r.thread_id WHERE r.created_at > CURRENT_DATE - ${numberOfPrevDays} AND community_id = :communityId ) objs ON objs.created_at::date = seq.date