sync-subscriptions.ts 1.1 KB

123456789101112131415161718192021222324252627282930
  1. import { CronJob } from 'cron'
  2. import { isCloudMode } from '@/lib/features'
  3. import { billingRequest, isTorqvoiceComBillingConfigured } from '@/lib/torqvoice-com'
  4. import { createLogger } from '@/lib/logger'
  5. /**
  6. * Cloud mode: once a day, asks torqvoice.com to compare every Stripe-backed
  7. * subscription with Stripe and correct the rows here. Webhooks do the real
  8. * work; this catches the one that was missed.
  9. */
  10. export function syncSubscriptions() {
  11. if (!isCloudMode()) return
  12. const job = new CronJob('0 1 * * *', async () => {
  13. if (!isTorqvoiceComBillingConfigured()) return
  14. try {
  15. const result = await billingRequest<{ checked: number; synced: number; errors: number }>(
  16. 'sync',
  17. {}
  18. )
  19. const fields = { checked: result.checked, synced: result.synced, errors: result.errors }
  20. if (result.errors > 0) createLogger('cron').error('Subscription sync had errors', fields)
  21. else if (result.synced > 0) createLogger('cron').info('Subscription sync', fields)
  22. } catch (error) {
  23. createLogger('cron').error('Subscription sync failed', { err: error })
  24. }
  25. })
  26. job.start()
  27. }