diff --git a/prisma/migrations/20241101151907_fix_territory_revenue/migration.sql b/prisma/migrations/20241101151907_fix_territory_revenue/migration.sql new file mode 100644 index 00000000..0a92b67f --- /dev/null +++ b/prisma/migrations/20241101151907_fix_territory_revenue/migration.sql @@ -0,0 +1,28 @@ +-- fix revenue for users who have multiple revenue entries for the same day +WITH revenue_days AS ( + SELECT coalesce(sum(msats), 0) as revenue_msats, "userId", created_at + FROM "SubAct" + WHERE type = 'REVENUE' + GROUP BY "userId", created_at + HAVING COUNT(*) > 1 +), +revenue_total AS ( + SELECT coalesce(sum(revenue_msats), 0) as revenue_msats, "userId" + FROM revenue_days + GROUP BY "userId" +) +UPDATE users SET msats = users.msats + revenue_total.revenue_msats +FROM revenue_total +WHERE users.id = revenue_total."userId"; + +-- fix stacked msats for users who have territory revenue +-- prior to this, we were not updating stacked msats for territory revenue +WITH territory_revenue AS ( + SELECT coalesce(sum(msats), 0) as revenue_msats, "userId" + FROM "SubAct" + WHERE type = 'REVENUE' + GROUP BY "userId" +) +UPDATE users SET "stackedMsats" = users."stackedMsats" + territory_revenue.revenue_msats +FROM territory_revenue +WHERE users.id = territory_revenue."userId"; diff --git a/worker/territory.js b/worker/territory.js index 21bb87b7..d7a7f479 100644 --- a/worker/territory.js +++ b/worker/territory.js @@ -72,10 +72,17 @@ export async function territoryRevenue ({ models }) { FROM revenue WHERE revenue > 1000 RETURNING * + ), + "SubActResultTotal" AS ( + SELECT coalesce(sum(msats), 0) as total_msats, "userId" + FROM "SubActResult" + GROUP BY "userId" ) - UPDATE users SET msats = users.msats + "SubActResult".msats - FROM "SubActResult" - WHERE users.id = "SubActResult"."userId"`, + UPDATE users + SET msats = users.msats + "SubActResultTotal".total_msats, + "stackedMsats" = users."stackedMsats" + "SubActResultTotal".total_msats + FROM "SubActResultTotal" + WHERE users.id = "SubActResultTotal"."userId"`, { models } ) }