* Aggregate raw pooled stats for all members of an organization in a single * query. Used by org-scoped summary and overage calculations so we don't * call `getUserUsageData` per-member — that helper now returns the entire * pool for org-scoped subs, which would N-times-count the usage. * * The
( organizationId: string, executor: DbClient = db )
| 117 | * current-period billing math. |
| 118 | */ |
| 119 | async function aggregateOrgMemberStats( |
| 120 | organizationId: string, |
| 121 | executor: DbClient = db |
| 122 | ): Promise<{ |
| 123 | memberIds: string[] |
| 124 | currentPeriodCost: number |
| 125 | currentPeriodCopilotCost: number |
| 126 | lastPeriodCopilotCost: number |
| 127 | }> { |
| 128 | const rows = await executor |
| 129 | .select({ |
| 130 | userId: member.userId, |
| 131 | currentPeriodCost: userStats.currentPeriodCost, |
| 132 | currentPeriodCopilotCost: userStats.currentPeriodCopilotCost, |
| 133 | lastPeriodCopilotCost: userStats.lastPeriodCopilotCost, |
| 134 | }) |
| 135 | .from(member) |
| 136 | .leftJoin(userStats, eq(member.userId, userStats.userId)) |
| 137 | .where(eq(member.organizationId, organizationId)) |
| 138 | |
| 139 | let currentPeriodCost = new Decimal(0) |
| 140 | // Copilot baseline (copilot source). All copilot-family usage (incl. MCP) lives |
| 141 | // in usage_log and is added via the copilot ledger by callers — not a baseline. |
| 142 | let currentPeriodCopilotCost = new Decimal(0) |
| 143 | let lastPeriodCopilotCost = new Decimal(0) |
| 144 | const memberIds: string[] = [] |
| 145 | |
| 146 | for (const row of rows) { |
| 147 | memberIds.push(row.userId) |
| 148 | currentPeriodCost = currentPeriodCost.plus(toDecimal(row.currentPeriodCost)) |
| 149 | currentPeriodCopilotCost = currentPeriodCopilotCost.plus( |
| 150 | toDecimal(row.currentPeriodCopilotCost) |
| 151 | ) |
| 152 | lastPeriodCopilotCost = lastPeriodCopilotCost.plus(toDecimal(row.lastPeriodCopilotCost)) |
| 153 | } |
| 154 | |
| 155 | return { |
| 156 | memberIds, |
| 157 | currentPeriodCost: toNumber(currentPeriodCost), |
| 158 | currentPeriodCopilotCost: toNumber(currentPeriodCopilotCost), |
| 159 | lastPeriodCopilotCost: toNumber(lastPeriodCopilotCost), |
| 160 | } |
| 161 | } |
| 162 | |
| 163 | /** |
| 164 | * Compute an org's overage amount from already-fetched pool/departed |
no test coverage detected