(params: {
organizationId: string
userId: string
logger: Logger
})
| 518 | } |
| 519 | |
| 520 | export async function checkAndTriggerOrgAutoTopup(params: { |
| 521 | organizationId: string |
| 522 | userId: string |
| 523 | logger: Logger |
| 524 | }): Promise<void> { |
| 525 | const { organizationId, userId, logger } = params |
| 526 | const logContext: any = { organizationId, userId } |
| 527 | |
| 528 | try { |
| 529 | const org = await getOrganizationSettings(organizationId) |
| 530 | |
| 531 | if (!org.auto_topup_enabled || !org.stripe_customer_id) { |
| 532 | return |
| 533 | } |
| 534 | |
| 535 | const { balance } = await calculateOrganizationUsageAndBalance({ |
| 536 | ...params, |
| 537 | quotaResetDate: getNextQuotaReset(null), |
| 538 | }) |
| 539 | |
| 540 | if (balance.netBalance > (org.auto_topup_threshold || 0)) { |
| 541 | logger.info( |
| 542 | { |
| 543 | ...logContext, |
| 544 | currentBalance: balance.netBalance, |
| 545 | threshold: org.auto_topup_threshold, |
| 546 | }, |
| 547 | `Organization auto top-up not needed. Balance ${balance.netBalance} is above threshold ${org.auto_topup_threshold}.`, |
| 548 | ) |
| 549 | return |
| 550 | } |
| 551 | |
| 552 | const amountToTopUp = org.auto_topup_amount || 0 |
| 553 | |
| 554 | if (amountToTopUp < MINIMUM_PURCHASE_CREDITS) { |
| 555 | logger.warn( |
| 556 | logContext, |
| 557 | `Organization auto-top-up triggered but amount ${amountToTopUp} is less than minimum ${MINIMUM_PURCHASE_CREDITS}. Skipping top-up. Check organization settings.`, |
| 558 | ) |
| 559 | return |
| 560 | } |
| 561 | |
| 562 | logger.info( |
| 563 | { |
| 564 | ...logContext, |
| 565 | currentBalance: balance.netBalance, |
| 566 | threshold: org.auto_topup_threshold, |
| 567 | amountToTopUp, |
| 568 | }, |
| 569 | `Organization auto-top-up needed. Will attempt to purchase ${amountToTopUp} credits.`, |
| 570 | ) |
| 571 | |
| 572 | try { |
| 573 | await processOrgAutoTopupPayment({ |
| 574 | ...params, |
| 575 | amountToTopUp, |
| 576 | stripeCustomerId: org.stripe_customer_id, |
| 577 | }) |
nothing calls this directly
no test coverage detected