(
billingEntity: BillingEntity,
billingPeriod: { start: Date; end: Date },
source?: UsageLogSource | UsageLogSource[],
executor: DbClient = db
)
| 209 | } |
| 210 | |
| 211 | export async function getBillingPeriodUsageCostByUser( |
| 212 | billingEntity: BillingEntity, |
| 213 | billingPeriod: { start: Date; end: Date }, |
| 214 | source?: UsageLogSource | UsageLogSource[], |
| 215 | executor: DbClient = db |
| 216 | ): Promise<Map<string, number>> { |
| 217 | const conditions = [ |
| 218 | eq(usageLog.billingEntityType, billingEntity.type), |
| 219 | eq(usageLog.billingEntityId, billingEntity.id), |
| 220 | eq(usageLog.billingPeriodStart, billingPeriod.start), |
| 221 | eq(usageLog.billingPeriodEnd, billingPeriod.end), |
| 222 | ] |
| 223 | if (source) { |
| 224 | conditions.push( |
| 225 | Array.isArray(source) ? inArray(usageLog.source, source) : eq(usageLog.source, source) |
| 226 | ) |
| 227 | } |
| 228 | |
| 229 | const rows = await executor |
| 230 | .select({ |
| 231 | userId: usageLog.userId, |
| 232 | cost: sql<string>`COALESCE(SUM(${usageLog.cost}), 0)`, |
| 233 | }) |
| 234 | .from(usageLog) |
| 235 | .where(and(...conditions)) |
| 236 | .groupBy(usageLog.userId) |
| 237 | |
| 238 | return new Map(rows.map((row) => [row.userId, Number.parseFloat(row.cost ?? '0')])) |
| 239 | } |
| 240 | |
| 241 | /** |
| 242 | * A single user's usage_log cost inside an organization's own workspaces within |
no test coverage detected