( userId: string, executor: DbClient = db )
| 686 | * all org members; personally-scoped subs return this user's own cost. |
| 687 | */ |
| 688 | export async function getEffectiveCurrentPeriodCost( |
| 689 | userId: string, |
| 690 | executor: DbClient = db |
| 691 | ): Promise<number> { |
| 692 | const subscription = await getHighestPrioritySubscription(userId, { executor }) |
| 693 | const orgScoped = isOrgScopedSubscription(subscription, userId) |
| 694 | |
| 695 | let rawCost: number |
| 696 | let refreshUserIds: string[] = [userId] |
| 697 | |
| 698 | if (orgScoped && subscription) { |
| 699 | const pooled = await getPooledOrgCurrentPeriodCost(subscription.referenceId, executor) |
| 700 | if (pooled.memberIds.length === 0) return 0 |
| 701 | refreshUserIds = pooled.memberIds |
| 702 | const billingPeriod = |
| 703 | subscription.periodStart && subscription.periodEnd |
| 704 | ? { start: subscription.periodStart, end: subscription.periodEnd } |
| 705 | : defaultBillingPeriod() |
| 706 | rawCost = |
| 707 | pooled.currentPeriodCost + |
| 708 | (await getBillingPeriodUsageCost( |
| 709 | { type: 'organization', id: subscription.referenceId }, |
| 710 | billingPeriod, |
| 711 | undefined, |
| 712 | executor |
| 713 | )) |
| 714 | } else { |
| 715 | const rows = await executor |
| 716 | .select({ current: userStats.currentPeriodCost }) |
| 717 | .from(userStats) |
| 718 | .where(eq(userStats.userId, userId)) |
| 719 | .limit(1) |
| 720 | |
| 721 | if (rows.length === 0) return 0 |
| 722 | const billingPeriod = |
| 723 | subscription?.periodStart && subscription.periodEnd |
| 724 | ? { start: subscription.periodStart, end: subscription.periodEnd } |
| 725 | : defaultBillingPeriod() |
| 726 | rawCost = |
| 727 | toNumber(toDecimal(rows[0].current)) + |
| 728 | (await getBillingPeriodUsageCost( |
| 729 | { type: 'user', id: userId }, |
| 730 | billingPeriod, |
| 731 | undefined, |
| 732 | executor |
| 733 | )) |
| 734 | } |
| 735 | |
| 736 | if (!subscription || !isPaid(subscription.plan) || !subscription.periodStart) { |
| 737 | return rawCost |
| 738 | } |
| 739 | |
| 740 | const planDollars = getPlanTierDollars(subscription.plan) |
| 741 | if (planDollars <= 0) return rawCost |
| 742 | |
| 743 | const userBounds = |
| 744 | orgScoped && subscription.periodStart |
| 745 | ? await getOrgMemberRefreshBounds( |
no test coverage detected