helpers.mjs 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /* eslint-disable @overleaf/require-script-runner */
  2. // This file contains helper functions used by other scripts.
  3. // The scripts that import these helpers should use Script Runner.
  4. /**
  5. * @import Stripe from 'stripe'
  6. * @import { getRegionClient } from '../../modules/subscriptions/app/src/StripeClient.mjs'
  7. */
  8. /**
  9. * @export
  10. * @typedef {Object} CSVSubscriptionChange
  11. * @property {string} subscription_id
  12. * @property {string} current_lookup_key
  13. * @property {string} new_lookup_key
  14. * @property {string} current_add_on_lookup_key
  15. * @property {string} new_add_on_lookup_key
  16. */
  17. /**
  18. * @export
  19. * @typedef {'renewal' | 'now'} Timeframe
  20. */
  21. /**
  22. * @export
  23. * @typedef {ReturnType<typeof getRegionClient>} StripeClient
  24. */
  25. /**
  26. * Custom error class for reportable errors that should be written to CSV output
  27. */
  28. export class ReportError extends Error {
  29. /**
  30. * @param {string} status - The error status code for CSV output
  31. * @param {string} message - The error message
  32. */
  33. constructor(status, message) {
  34. super(message)
  35. this.status = status
  36. }
  37. }
  38. /**
  39. * Gets the product ID from a Stripe Subscription Item
  40. *
  41. * @param {Stripe.SubscriptionItem | Stripe.SubscriptionSchedule.Phase.Item} item
  42. * @returns {string}
  43. */
  44. export function getProductIdFromItem(item) {
  45. const product =
  46. typeof item.price === 'string'
  47. ? null
  48. : 'product' in item.price
  49. ? item.price.product
  50. : null
  51. return typeof product === 'string' ? product : (product?.id ?? '')
  52. }
  53. /**
  54. * Gets the price ID from a Stripe Subscription Item
  55. *
  56. * @param {Stripe.SubscriptionItem | Stripe.SubscriptionSchedule.Phase.Item} item
  57. * @returns {string}
  58. */
  59. export function getPriceIdFromItem(item) {
  60. return typeof item.price === 'string' ? item.price : (item.price?.id ?? '')
  61. }
  62. /**
  63. * Gets the product ID from a Stripe Price object
  64. *
  65. * @param {Stripe.Price} price
  66. * @returns {string}
  67. */
  68. export function getProductIdFromPrice(price) {
  69. return typeof price.product === 'string'
  70. ? price.product
  71. : (price.product?.id ?? '')
  72. }