Skip to content

Commit

Permalink
Fix community analytics query
Browse files Browse the repository at this point in the history
  • Loading branch information
mzparacha committed Aug 30, 2024
1 parent c136976 commit 9765552
Showing 1 changed file with 22 additions and 8 deletions.
30 changes: 22 additions & 8 deletions packages/commonwealth/server/routes/communityStats.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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
Expand All @@ -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
Expand Down

0 comments on commit 9765552

Please sign in to comment.