@vrplatform/hyperline-client 1.0.25 → 1.0.26

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (94) hide show
  1. package/build/main/client.d.ts +2 -2
  2. package/build/main/client.js.map +1 -1
  3. package/build/main/const.d.ts +0 -7
  4. package/build/main/const.js +0 -7
  5. package/build/main/const.js.map +1 -1
  6. package/build/main/src/_types.generated.d.ts +22310 -0
  7. package/build/main/src/_types.generated.js +6 -0
  8. package/build/main/src/_types.generated.js.map +1 -0
  9. package/build/main/src/client.d.ts +1706 -0
  10. package/build/main/src/client.js +294 -0
  11. package/build/main/src/client.js.map +1 -0
  12. package/build/main/src/const.d.ts +73 -0
  13. package/build/main/src/const.js +257 -0
  14. package/build/main/src/const.js.map +1 -0
  15. package/build/main/src/hooks.d.ts +10 -0
  16. package/build/main/src/hooks.js +13 -0
  17. package/build/main/src/hooks.js.map +1 -0
  18. package/build/main/src/index.d.ts +5 -0
  19. package/build/main/src/index.js +6 -0
  20. package/build/main/src/index.js.map +1 -0
  21. package/build/main/src/types.d.ts +35 -0
  22. package/build/main/src/types.js +2 -0
  23. package/build/main/src/types.js.map +1 -0
  24. package/build/main/src/utils/arrayBufferToBase64.d.ts +1 -0
  25. package/build/main/src/utils/arrayBufferToBase64.js +9 -0
  26. package/build/main/src/utils/arrayBufferToBase64.js.map +1 -0
  27. package/build/main/src/utils/calculateMrr.d.ts +45 -0
  28. package/build/main/src/utils/calculateMrr.js +107 -0
  29. package/build/main/src/utils/calculateMrr.js.map +1 -0
  30. package/build/main/src/utils/getMrrDiffReasons.d.ts +15 -0
  31. package/build/main/src/utils/getMrrDiffReasons.js +217 -0
  32. package/build/main/src/utils/getMrrDiffReasons.js.map +1 -0
  33. package/build/main/src/utils/index.d.ts +3 -0
  34. package/build/main/src/utils/index.js +4 -0
  35. package/build/main/src/utils/index.js.map +1 -0
  36. package/build/main/tsconfig.main.tsbuildinfo +1 -0
  37. package/build/main/types.d.ts +0 -43
  38. package/build/main/types.js.map +1 -1
  39. package/build/main/utils/calculateMrr.d.ts +45 -0
  40. package/build/main/utils/calculateMrr.js +107 -0
  41. package/build/main/utils/calculateMrr.js.map +1 -0
  42. package/build/main/utils/index.d.ts +1 -0
  43. package/build/main/utils/index.js +1 -0
  44. package/build/main/utils/index.js.map +1 -1
  45. package/build/module/client.d.ts +2 -2
  46. package/build/module/client.js.map +1 -1
  47. package/build/module/const.d.ts +0 -7
  48. package/build/module/const.js +0 -7
  49. package/build/module/const.js.map +1 -1
  50. package/build/module/src/_types.generated.d.ts +22310 -0
  51. package/build/module/src/_types.generated.js +6 -0
  52. package/build/module/src/_types.generated.js.map +1 -0
  53. package/build/module/src/client.d.ts +1706 -0
  54. package/build/module/src/client.js +296 -0
  55. package/build/module/src/client.js.map +1 -0
  56. package/build/module/src/const.d.ts +73 -0
  57. package/build/module/src/const.js +257 -0
  58. package/build/module/src/const.js.map +1 -0
  59. package/build/module/src/hooks.d.ts +10 -0
  60. package/build/module/src/hooks.js +13 -0
  61. package/build/module/src/hooks.js.map +1 -0
  62. package/build/module/src/index.d.ts +5 -0
  63. package/build/module/src/index.js +6 -0
  64. package/build/module/src/index.js.map +1 -0
  65. package/build/module/src/types.d.ts +35 -0
  66. package/build/module/src/types.js +2 -0
  67. package/build/module/src/types.js.map +1 -0
  68. package/build/module/src/utils/arrayBufferToBase64.d.ts +1 -0
  69. package/build/module/src/utils/arrayBufferToBase64.js +9 -0
  70. package/build/module/src/utils/arrayBufferToBase64.js.map +1 -0
  71. package/build/module/src/utils/calculateMrr.d.ts +45 -0
  72. package/build/module/src/utils/calculateMrr.js +107 -0
  73. package/build/module/src/utils/calculateMrr.js.map +1 -0
  74. package/build/module/src/utils/getMrrDiffReasons.d.ts +15 -0
  75. package/build/module/src/utils/getMrrDiffReasons.js +217 -0
  76. package/build/module/src/utils/getMrrDiffReasons.js.map +1 -0
  77. package/build/module/src/utils/index.d.ts +3 -0
  78. package/build/module/src/utils/index.js +4 -0
  79. package/build/module/src/utils/index.js.map +1 -0
  80. package/build/module/tsconfig.esm.tsbuildinfo +1 -0
  81. package/build/module/types.d.ts +0 -43
  82. package/build/module/types.js.map +1 -1
  83. package/build/module/utils/calculateMrr.d.ts +45 -0
  84. package/build/module/utils/calculateMrr.js +107 -0
  85. package/build/module/utils/calculateMrr.js.map +1 -0
  86. package/build/module/utils/index.d.ts +1 -0
  87. package/build/module/utils/index.js +1 -0
  88. package/build/module/utils/index.js.map +1 -1
  89. package/package.json +2 -4
  90. package/src/client.ts +6 -6
  91. package/src/const.ts +0 -14
  92. package/src/types.ts +0 -55
  93. package/src/utils/calculateMrr.ts +206 -0
  94. package/src/utils/index.ts +1 -0
@@ -0,0 +1,217 @@
1
+ import { groupBy, utc } from '@vrplatform/utils';
2
+ import { VRP_TENANT_ID, XIMPLIFI_TENANT_ID } from '../const';
3
+ function printFinancialNumber(number, showPlusMinus = true) {
4
+ return `${showPlusMinus ? (number >= 0 ? '+' : '-') : ''}$${Math.abs(number)
5
+ .toFixed(2)
6
+ .toString()
7
+ .replace(/\B(?=(\d{3})+(?!\d))/g, ',')}`;
8
+ }
9
+ function printPlusMinus(number) {
10
+ return `${number >= 0 ? '+' : '-'}${Math.abs(number)}`;
11
+ }
12
+ export async function getMrrDiffReasons(firstDate, lastDate, client) {
13
+ const messages = [];
14
+ messages.push(`MRR Diff Reasons from ${utc(firstDate).yyyymmdd()} to ${utc(lastDate).yyyymmdd()}`);
15
+ messages.push('--------------------------------');
16
+ const { mrrEvents, listingsEvents } = await client.query((q) => ({
17
+ mrrEvents: q
18
+ .tracking_event({
19
+ where: {
20
+ name: { _eq: 'mrr_reported' },
21
+ _or: [
22
+ {
23
+ createdAt: {
24
+ _gte: utc(firstDate).yyyymmdd(),
25
+ _lte: utc(firstDate).add(1, 'day').yyyymmdd(),
26
+ },
27
+ },
28
+ {
29
+ createdAt: {
30
+ _gte: utc(lastDate).yyyymmdd(),
31
+ _lte: utc(lastDate).add(1, 'day').yyyymmdd(),
32
+ },
33
+ },
34
+ ],
35
+ },
36
+ })
37
+ .map((e) => ({
38
+ tenantId: e.tenant?.id,
39
+ tenantName: e.tenant?.name,
40
+ tenantCreatedAt: e.tenant?.createdAt,
41
+ tenantPlan: e.tenant?.billingPlan,
42
+ partnerTeamsCreatedFirstDate: e.tenant
43
+ ?.clients({
44
+ where: {
45
+ createdAt: {
46
+ _lte: utc(firstDate).yyyymmdd(),
47
+ },
48
+ },
49
+ })
50
+ .map((c) => c.id).length,
51
+ partnerTeamsCreatedLastDate: e.tenant
52
+ ?.clients({
53
+ where: {
54
+ createdAt: {
55
+ _lte: utc(lastDate).yyyymmdd(),
56
+ },
57
+ },
58
+ })
59
+ .map((c) => c.id).length,
60
+ partnerTeamsCancelledFirstDate: e.tenant
61
+ ?.clients({
62
+ where: {
63
+ cancelledAt: {
64
+ _lte: utc(firstDate).yyyymmdd(),
65
+ },
66
+ },
67
+ })
68
+ .map((c) => c.id).length,
69
+ partnerTeamsCancelledLastDate: e.tenant
70
+ ?.clients({
71
+ where: {
72
+ cancelledAt: {
73
+ _lte: utc(lastDate).yyyymmdd(),
74
+ },
75
+ },
76
+ })
77
+ .map((c) => c.id).length,
78
+ mrr: e.props()?.mrr,
79
+ createdAt: utc(e.createdAt).yyyymmdd(),
80
+ })),
81
+ listingsEvents: q
82
+ .tracking_event({
83
+ where: {
84
+ name: { _eq: 'listings_reported' },
85
+ _or: [
86
+ {
87
+ createdAt: {
88
+ _gte: utc(firstDate).yyyymmdd(),
89
+ _lte: utc(firstDate).add(1, 'day').yyyymmdd(),
90
+ },
91
+ },
92
+ {
93
+ createdAt: {
94
+ _gte: utc(lastDate).yyyymmdd(),
95
+ _lte: utc(lastDate).add(1, 'day').yyyymmdd(),
96
+ },
97
+ },
98
+ ],
99
+ },
100
+ })
101
+ .map((e) => ({
102
+ tenantId: e.tenant?.id,
103
+ billingPartnerId: e.tenant?.calculatedBillingPartnerId,
104
+ listings: e.props()?.activeListings,
105
+ createdAt: utc(e.createdAt).yyyymmdd(),
106
+ })),
107
+ }));
108
+ messages.push(`Found ${mrrEvents.length} mrr events`);
109
+ // join mrr and listings events
110
+ const trackingEvents = mrrEvents
111
+ .filter((e) => e.tenantId)
112
+ .map((e) => {
113
+ const filteredEvents = listingsEvents.filter((l) => {
114
+ if (!l.billingPartnerId || !l.tenantId)
115
+ return false;
116
+ const tenantId = [VRP_TENANT_ID, XIMPLIFI_TENANT_ID].includes(l.billingPartnerId)
117
+ ? l.tenantId
118
+ : l.billingPartnerId;
119
+ return tenantId === e.tenantId && l.createdAt === e.createdAt;
120
+ });
121
+ return {
122
+ ...e,
123
+ listings: filteredEvents.reduce((acc, l) => acc + (l.listings ?? 0), 0),
124
+ };
125
+ });
126
+ // get list of tenants
127
+ const tenants = {};
128
+ for (const event of trackingEvents) {
129
+ if (!event.tenantId)
130
+ continue;
131
+ if (!tenants[event.tenantId]) {
132
+ const partnerTeamsCreatedDiff = (event.partnerTeamsCreatedLastDate || 0) -
133
+ (event.partnerTeamsCreatedFirstDate || 0);
134
+ const partnerTeamsCancelledDiff = (event.partnerTeamsCancelledLastDate || 0) -
135
+ (event.partnerTeamsCancelledFirstDate || 0);
136
+ tenants[event.tenantId] = {
137
+ id: event.tenantId,
138
+ name: event.tenantName,
139
+ plan: event.tenantPlan,
140
+ activePartnerTeamsDiff: partnerTeamsCreatedDiff - partnerTeamsCancelledDiff,
141
+ mrrFirstDate: undefined,
142
+ mrrLastDate: undefined,
143
+ mrrDiff: 0,
144
+ listingsFirstDate: undefined,
145
+ listingsLastDate: undefined,
146
+ listingsDiff: 0,
147
+ createdAt: utc(event.tenantCreatedAt).yyyymmdd(),
148
+ isNew: utc(event.tenantCreatedAt).isBetween(utc(firstDate), utc(lastDate)),
149
+ };
150
+ }
151
+ if (event.createdAt === firstDate) {
152
+ tenants[event.tenantId].mrrFirstDate = event.mrr;
153
+ tenants[event.tenantId].listingsFirstDate = event.listings;
154
+ }
155
+ if (event.createdAt === lastDate) {
156
+ tenants[event.tenantId].mrrLastDate = event.mrr;
157
+ tenants[event.tenantId].listingsLastDate = event.listings;
158
+ }
159
+ }
160
+ const result = Object.values(tenants)
161
+ .map(({ mrrFirstDate, mrrLastDate, listingsFirstDate, listingsLastDate, ...t }) => ({
162
+ ...t,
163
+ mrrDiff: (mrrLastDate ?? 0) - (mrrFirstDate ?? 0),
164
+ listingsDiff: (listingsLastDate ?? 0) - (listingsFirstDate ?? 0),
165
+ hasCancelled: mrrFirstDate !== undefined && mrrLastDate === undefined,
166
+ }))
167
+ .filter((t) => t.mrrDiff)
168
+ .sort((a, b) => b.mrrDiff - a.mrrDiff)
169
+ .reverse();
170
+ // calculate summ of mrr per day
171
+ const groupedEvents = groupBy(trackingEvents, (e) => e.createdAt);
172
+ const summedMrrPerDay = Object.entries(groupedEvents)
173
+ .map(([date, events]) => {
174
+ const typedEvents = events;
175
+ const mrr = typedEvents.reduce((acc, e) => acc + (e.mrr ?? 0), 0);
176
+ const listings = typedEvents.reduce((acc, e) => acc + (e.listings ?? 0), 0);
177
+ return {
178
+ date,
179
+ mrr,
180
+ count: typedEvents.length,
181
+ listings,
182
+ };
183
+ })
184
+ .sort((a, b) => utc(b.date).diff(utc(a.date)));
185
+ messages.push(`MRR sum changed from ${printFinancialNumber(summedMrrPerDay[1].mrr, false)} to ${printFinancialNumber(summedMrrPerDay[0].mrr, false)} (${printFinancialNumber(summedMrrPerDay[0].mrr - summedMrrPerDay[1].mrr)})`);
186
+ messages.push(`MRR Reports changed from ${summedMrrPerDay[1].count.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',')} to ${summedMrrPerDay[0].count.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',')} (${printPlusMinus(summedMrrPerDay[0].count - summedMrrPerDay[1].count)})`);
187
+ messages.push(`Active Listings changed from ${summedMrrPerDay[1].listings.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',')} to ${summedMrrPerDay[0].listings.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',')} (${printPlusMinus(summedMrrPerDay[0].listings - summedMrrPerDay[1].listings)})`);
188
+ messages.push(`Active Partner Teams changed by ${printPlusMinus(result.reduce((acc, t) => acc + t.activePartnerTeamsDiff, 0))}`);
189
+ messages.push();
190
+ const cancelledTenants = result.filter((t) => t.hasCancelled);
191
+ const legacyTenants = result.filter((t) => t.plan?.includes('Legacy') &&
192
+ !cancelledTenants.map((t) => t.id).includes(t.id));
193
+ const newTenants = result.filter((t) => t.isNew &&
194
+ !cancelledTenants.map((t) => t.id).includes(t.id) &&
195
+ !legacyTenants.map((t) => t.id).includes(t.id));
196
+ const activeListings = result.filter((t) => t.listingsDiff &&
197
+ !newTenants.map((t) => t.id).includes(t.id) &&
198
+ !cancelledTenants.map((t) => t.id).includes(t.id) &&
199
+ !legacyTenants.map((t) => t.id).includes(t.id));
200
+ const otherTenants = result.filter((t) => !newTenants.map((t) => t.id).includes(t.id) &&
201
+ !cancelledTenants.map((t) => t.id).includes(t.id) &&
202
+ !legacyTenants.map((t) => t.id).includes(t.id) &&
203
+ !activeListings.map((t) => t.id).includes(t.id));
204
+ const total = newTenants.reduce((acc, t) => acc + t.mrrDiff, 0) +
205
+ cancelledTenants.reduce((acc, t) => acc + t.mrrDiff, 0) +
206
+ legacyTenants.reduce((acc, t) => acc + t.mrrDiff, 0) +
207
+ activeListings.reduce((acc, t) => acc + t.mrrDiff, 0) +
208
+ otherTenants.reduce((acc, t) => acc + t.mrrDiff, 0);
209
+ messages.push(`MRR from ${newTenants.length} new tenants: ${printFinancialNumber(newTenants.reduce((acc, t) => acc + t.mrrDiff, 0))}`);
210
+ messages.push(`MRR from ${cancelledTenants.length} cancelled tenants: ${printFinancialNumber(cancelledTenants.reduce((acc, t) => acc + t.mrrDiff, 0))}`);
211
+ messages.push(`MRR from ${legacyTenants.length} tenants with Legacy plans: ${printFinancialNumber(legacyTenants.reduce((acc, t) => acc + t.mrrDiff, 0))}`);
212
+ messages.push(`MRR from ${activeListings.length} tenants with active listings changes: ${printFinancialNumber(activeListings.reduce((acc, t) => acc + t.mrrDiff, 0))}`);
213
+ messages.push(`MRR from ${otherTenants.length} other tenants: ${printFinancialNumber(otherTenants.reduce((acc, t) => acc + t.mrrDiff, 0))} (${otherTenants.map((t) => `${t.name} (${printFinancialNumber(t.mrrDiff)})`).join(', ')})`);
214
+ messages.push(`= ${printFinancialNumber(total)}`);
215
+ return { messages, result };
216
+ }
217
+ //# sourceMappingURL=getMrrDiffReasons.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"getMrrDiffReasons.js","sourceRoot":"src/","sources":["src/utils/getMrrDiffReasons.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,OAAO,EAAE,GAAG,EAAE,MAAM,mBAAmB,CAAC;AACjD,OAAO,EAAE,aAAa,EAAE,kBAAkB,EAAE,MAAM,UAAU,CAAC;AAE7D,SAAS,oBAAoB,CAAC,MAAc,EAAE,aAAa,GAAG,IAAI;IAChE,OAAO,GAAG,aAAa,CAAC,CAAC,CAAC,CAAC,MAAM,IAAI,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,IAAI,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC;SACzE,OAAO,CAAC,CAAC,CAAC;SACV,QAAQ,EAAE;SACV,OAAO,CAAC,uBAAuB,EAAE,GAAG,CAAC,EAAE,CAAC;AAC7C,CAAC;AACD,SAAS,cAAc,CAAC,MAAc;IACpC,OAAO,GAAG,MAAM,IAAI,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,GAAG,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,EAAE,CAAC;AACzD,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,iBAAiB,CACrC,SAAiB,EACjB,QAAgB,EAChB,MAAoB;IAEpB,MAAM,QAAQ,GAAa,EAAE,CAAC;IAC9B,QAAQ,CAAC,IAAI,CACX,yBAAyB,GAAG,CAAC,SA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AC,KAAK,oBAAoB,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;IAElD,OAAO,EAAE,QAAQ,EAAE,MAAM,EAAE,CAAC;AAC9B,CAAC","sourcesContent":["import { HasuraClient } from '@vrplatform/graphql';\nimport { groupBy, utc } from '@vrplatform/utils';\nimport { VRP_TENANT_ID, XIMPLIFI_TENANT_ID } from '../const';\n\nfunction printFinancialNumber(number: number, showPlusMinus = true) {\n return `${showPlusMinus ? (number >= 0 ? '+' : '-') : ''}$${Math.abs(number)\n .toFixed(2)\n .toString()\n .replace(/\\B(?=(\\d{3})+(?!\\d))/g, ',')}`;\n}\nfunction printPlusMinus(number: number) {\n return `${number >= 0 ? '+' : '-'}${Math.abs(number)}`;\n}\n\nexport async function getMrrDiffReasons(\n firstDate: string,\n lastDate: string,\n client: HasuraClient\n) {\n const messages: string[] = [];\n messages.push(\n `MRR Diff Reasons from ${utc(firstDate).yyyymmdd()} to ${utc(lastDate).yyyymmdd()}`\n );\n messages.push('--------------------------------');\n\n const { mrrEvents, listingsEvents } = await client.query((q) => ({\n mrrEvents: q\n .tracking_event({\n where: {\n name: { _eq: 'mrr_reported' },\n _or: [\n {\n createdAt: {\n _gte: utc(firstDate).yyyymmdd(),\n _lte: utc(firstDate).add(1, 'day').yyyymmdd(),\n },\n },\n {\n createdAt: {\n _gte: utc(lastDate).yyyymmdd(),\n _lte: utc(lastDate).add(1, 'day').yyyymmdd(),\n },\n },\n ],\n },\n })\n .map((e) => ({\n tenantId: e.tenant?.id,\n tenantName: e.tenant?.name,\n tenantCreatedAt: e.tenant?.createdAt,\n tenantPlan: e.tenant?.billingPlan,\n partnerTeamsCreatedFirstDate: e.tenant\n ?.clients({\n where: {\n createdAt: {\n _lte: utc(firstDate).yyyymmdd(),\n },\n },\n })\n .map((c) => c.id).length,\n partnerTeamsCreatedLastDate: e.tenant\n ?.clients({\n where: {\n createdAt: {\n _lte: utc(lastDate).yyyymmdd(),\n },\n },\n })\n .map((c) => c.id).length,\n partnerTeamsCancelledFirstDate: e.tenant\n ?.clients({\n where: {\n cancelledAt: {\n _lte: utc(firstDate).yyyymmdd(),\n },\n },\n })\n .map((c) => c.id).length,\n partnerTeamsCancelledLastDate: e.tenant\n ?.clients({\n where: {\n cancelledAt: {\n _lte: utc(lastDate).yyyymmdd(),\n },\n },\n })\n .map((c) => c.id).length,\n mrr: e.props()?.mrr,\n createdAt: utc(e.createdAt).yyyymmdd(),\n })),\n listingsEvents: q\n .tracking_event({\n where: {\n name: { _eq: 'listings_reported' },\n _or: [\n {\n createdAt: {\n _gte: utc(firstDate).yyyymmdd(),\n _lte: utc(firstDate).add(1, 'day').yyyymmdd(),\n },\n },\n {\n createdAt: {\n _gte: utc(lastDate).yyyymmdd(),\n _lte: utc(lastDate).add(1, 'day').yyyymmdd(),\n },\n },\n ],\n },\n })\n .map((e) => ({\n tenantId: e.tenant?.id,\n billingPartnerId: e.tenant?.calculatedBillingPartnerId,\n listings: e.props()?.activeListings,\n createdAt: utc(e.createdAt).yyyymmdd(),\n })),\n }));\n messages.push(`Found ${mrrEvents.length} mrr events`);\n\n // join mrr and listings events\n const trackingEvents = mrrEvents\n .filter((e) => e.tenantId)\n .map((e) => {\n const filteredEvents = listingsEvents.filter((l) => {\n if (!l.billingPartnerId || !l.tenantId) return false;\n const tenantId = [VRP_TENANT_ID, XIMPLIFI_TENANT_ID].includes(\n l.billingPartnerId\n )\n ? l.tenantId\n : l.billingPartnerId;\n\n return tenantId === e.tenantId && l.createdAt === e.createdAt;\n });\n\n return {\n ...e,\n listings: filteredEvents.reduce((acc, l) => acc + (l.listings ?? 0), 0),\n };\n });\n\n // get list of tenants\n const tenants: Record<\n string,\n {\n id: string;\n name?: string;\n plan?: string;\n activePartnerTeamsDiff: number;\n mrrFirstDate?: number;\n mrrLastDate?: number;\n mrrDiff: number;\n listingsFirstDate?: number;\n listingsLastDate?: number;\n listingsDiff: number;\n createdAt: string;\n isNew: boolean;\n hasCancelled?: boolean;\n }\n > = {};\n for (const event of trackingEvents) {\n if (!event.tenantId) continue;\n if (!tenants[event.tenantId]) {\n const partnerTeamsCreatedDiff =\n (event.partnerTeamsCreatedLastDate || 0) -\n (event.partnerTeamsCreatedFirstDate || 0);\n const partnerTeamsCancelledDiff =\n (event.partnerTeamsCancelledLastDate || 0) -\n (event.partnerTeamsCancelledFirstDate || 0);\n\n tenants[event.tenantId] = {\n id: event.tenantId,\n name: event.tenantName,\n plan: event.tenantPlan,\n activePartnerTeamsDiff:\n partnerTeamsCreatedDiff - partnerTeamsCancelledDiff,\n mrrFirstDate: undefined,\n mrrLastDate: undefined,\n mrrDiff: 0,\n listingsFirstDate: undefined,\n listingsLastDate: undefined,\n listingsDiff: 0,\n createdAt: utc(event.tenantCreatedAt).yyyymmdd(),\n isNew: utc(event.tenantCreatedAt).isBetween(\n utc(firstDate),\n utc(lastDate)\n ),\n };\n }\n\n if (event.createdAt === firstDate) {\n tenants[event.tenantId].mrrFirstDate = event.mrr;\n tenants[event.tenantId].listingsFirstDate = event.listings;\n }\n if (event.createdAt === lastDate) {\n tenants[event.tenantId].mrrLastDate = event.mrr;\n tenants[event.tenantId].listingsLastDate = event.listings;\n }\n }\n\n const result = Object.values(tenants)\n .map(\n ({\n mrrFirstDate,\n mrrLastDate,\n listingsFirstDate,\n listingsLastDate,\n ...t\n }) => ({\n ...t,\n mrrDiff: (mrrLastDate ?? 0) - (mrrFirstDate ?? 0),\n listingsDiff: (listingsLastDate ?? 0) - (listingsFirstDate ?? 0),\n hasCancelled: mrrFirstDate !== undefined && mrrLastDate === undefined,\n })\n )\n .filter((t) => t.mrrDiff)\n .sort((a, b) => b.mrrDiff - a.mrrDiff)\n .reverse();\n\n // calculate summ of mrr per day\n const groupedEvents = groupBy(trackingEvents, (e) => e.createdAt);\n const summedMrrPerDay = Object.entries(groupedEvents)\n .map(([date, events]) => {\n const typedEvents = events as typeof trackingEvents;\n const mrr = typedEvents.reduce((acc, e) => acc + (e.mrr ?? 0), 0);\n const listings = typedEvents.reduce(\n (acc, e) => acc + (e.listings ?? 0),\n 0\n );\n\n return {\n date,\n mrr,\n count: typedEvents.length,\n listings,\n };\n })\n .sort((a, b) => utc(b.date).diff(utc(a.date)));\n messages.push(\n `MRR sum changed from ${printFinancialNumber(summedMrrPerDay[1].mrr, false)} to ${printFinancialNumber(summedMrrPerDay[0].mrr, false)} (${printFinancialNumber(summedMrrPerDay[0].mrr - summedMrrPerDay[1].mrr)})`\n );\n messages.push(\n `MRR Reports changed from ${summedMrrPerDay[1].count.toString().replace(/\\B(?=(\\d{3})+(?!\\d))/g, ',')} to ${summedMrrPerDay[0].count.toString().replace(/\\B(?=(\\d{3})+(?!\\d))/g, ',')} (${printPlusMinus(summedMrrPerDay[0].count - summedMrrPerDay[1].count)})`\n );\n messages.push(\n `Active Listings changed from ${summedMrrPerDay[1].listings.toString().replace(/\\B(?=(\\d{3})+(?!\\d))/g, ',')} to ${summedMrrPerDay[0].listings.toString().replace(/\\B(?=(\\d{3})+(?!\\d))/g, ',')} (${printPlusMinus(summedMrrPerDay[0].listings - summedMrrPerDay[1].listings)})`\n );\n messages.push(\n `Active Partner Teams changed by ${printPlusMinus(\n result.reduce((acc, t) => acc + t.activePartnerTeamsDiff, 0)\n )}`\n );\n messages.push();\n\n const cancelledTenants = result.filter((t) => t.hasCancelled);\n const legacyTenants = result.filter(\n (t) =>\n t.plan?.includes('Legacy') &&\n !cancelledTenants.map((t) => t.id).includes(t.id)\n );\n const newTenants = result.filter(\n (t) =>\n t.isNew &&\n !cancelledTenants.map((t) => t.id).includes(t.id) &&\n !legacyTenants.map((t) => t.id).includes(t.id)\n );\n const activeListings = result.filter(\n (t) =>\n t.listingsDiff &&\n !newTenants.map((t) => t.id).includes(t.id) &&\n !cancelledTenants.map((t) => t.id).includes(t.id) &&\n !legacyTenants.map((t) => t.id).includes(t.id)\n );\n const otherTenants = result.filter(\n (t) =>\n !newTenants.map((t) => t.id).includes(t.id) &&\n !cancelledTenants.map((t) => t.id).includes(t.id) &&\n !legacyTenants.map((t) => t.id).includes(t.id) &&\n !activeListings.map((t) => t.id).includes(t.id)\n );\n const total =\n newTenants.reduce((acc, t) => acc + t.mrrDiff, 0) +\n cancelledTenants.reduce((acc, t) => acc + t.mrrDiff, 0) +\n legacyTenants.reduce((acc, t) => acc + t.mrrDiff, 0) +\n activeListings.reduce((acc, t) => acc + t.mrrDiff, 0) +\n otherTenants.reduce((acc, t) => acc + t.mrrDiff, 0);\n messages.push(\n `MRR from ${newTenants.length} new tenants: ${printFinancialNumber(newTenants.reduce((acc, t) => acc + t.mrrDiff, 0))}`\n );\n messages.push(\n `MRR from ${cancelledTenants.length} cancelled tenants: ${printFinancialNumber(cancelledTenants.reduce((acc, t) => acc + t.mrrDiff, 0))}`\n );\n messages.push(\n `MRR from ${legacyTenants.length} tenants with Legacy plans: ${printFinancialNumber(legacyTenants.reduce((acc, t) => acc + t.mrrDiff, 0))}`\n );\n messages.push(\n `MRR from ${activeListings.length} tenants with active listings changes: ${printFinancialNumber(activeListings.reduce((acc, t) => acc + t.mrrDiff, 0))}`\n );\n messages.push(\n `MRR from ${otherTenants.length} other tenants: ${printFinancialNumber(\n otherTenants.reduce((acc, t) => acc + t.mrrDiff, 0)\n )} (${otherTenants.map((t) => `${t.name} (${printFinancialNumber(t.mrrDiff)})`).join(', ')})`\n );\n messages.push(`= ${printFinancialNumber(total)}`);\n\n return { messages, result };\n}\n"]}
@@ -0,0 +1,3 @@
1
+ export * from './arrayBufferToBase64';
2
+ export * from './calculateMrr';
3
+ export * from './getMrrDiffReasons';
@@ -0,0 +1,4 @@
1
+ export * from './arrayBufferToBase64';
2
+ export * from './calculateMrr';
3
+ export * from './getMrrDiffReasons';
4
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"src/","sources":["src/utils/index.ts"],"names":[],"mappings":"AAAA,cAAc,uBAAuB,CAAC;AACtC,cAAc,gBAAgB,CAAC;AAC/B,cAAc,qBAAqB,CAAC","sourcesContent":["export * from './arrayBufferToBase64';\nexport * from './calculateMrr';\nexport * from './getMrrDiffReasons';\n"]}
@@ -0,0 +1 @@
1
+ {"root":["../../src/_types.generated.ts","../../src/client.ts","../../src/const.ts","../../src/hooks.ts","../../src/index.ts","../../src/types.ts","../../src/utils/arraybuffertobase64.ts","../../src/utils/calculatemrr.ts","../../src/utils/getmrrdiffreasons.ts","../../src/utils/index.ts"],"errors":true,"version":"6.0.3"}
@@ -8,49 +8,6 @@ export type HyperlinePayload<T extends HyperlineWebhook> = {
8
8
  event_type: T;
9
9
  data: Record<string, any>;
10
10
  };
11
- export type HyperlineCreateSubscriptionPayload = {
12
- customer_id: string;
13
- invoicing_entity_id?: string | null;
14
- activation_strategy?: 'start_date' | 'manually' | 'checkout';
15
- starts_at?: string;
16
- plan_id?: string;
17
- template_id?: string;
18
- template_configuration_id?: string;
19
- trial?: {
20
- end_strategy: 'manual' | 'end_date' | 'duration';
21
- starts_at?: string;
22
- ends_at?: string;
23
- duration?: {
24
- period: 'days' | 'weeks' | 'months' | 'years';
25
- count: number;
26
- };
27
- };
28
- cancellation_strategy?: 'refund_prorata' | 'refund_custom' | 'charge_prorata' | 'charge_custom' | 'end_of_period' | 'do_nothing';
29
- generate_draft_invoices?: boolean;
30
- renew_automatically?: boolean;
31
- contract_terms?: {
32
- activation_strategy: 'start_date' | 'immediately' | 'manual' | 'quote_signature' | 'checkout';
33
- end_strategy: 'end_date' | 'duration' | 'manual';
34
- starts_at?: string;
35
- duration?: {
36
- period: 'days' | 'weeks' | 'months' | 'years';
37
- count: number;
38
- };
39
- renew_automatically?: boolean;
40
- renew_for_duration?: {
41
- period: 'days' | 'weeks' | 'months' | 'years';
42
- count: number;
43
- };
44
- };
45
- billing_cycle_alignment?: 'calendar_period' | 'anniversary';
46
- coupons?: {
47
- id: string;
48
- repeat: 'once' | 'forever' | 'custom';
49
- expires_at?: string;
50
- apply_at?: string;
51
- product_ids?: string[];
52
- }[];
53
- };
54
11
  export type BillableEvent = {
55
12
  record: {
56
13
  id: '202408_cus_w_Q7M9bXcHMKB6';
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"src/","sources":["types.ts"],"names":[],"mappings":"","sourcesContent":["import type { components, paths } from './_types.generated';\nimport { WEBHOOKS } from './const';\n\nexport type HyperlineEntities = components['schemas'];\n\nexport type HyperlineEndpoints = paths;\n\nexport type HyperlineWebhook = keyof typeof WEBHOOKS;\n\nexport type HyperlineEvent<T extends HyperlineWebhook> = (typeof WEBHOOKS)[T];\n\nexport type HyperlinePayload<T extends HyperlineWebhook> = {\n event_type: T;\n data: Record<string, any>;\n};\n\nexport type HyperlineCreateSubscriptionPayload = {\n customer_id: string;\n invoicing_entity_id?: string | null;\n activation_strategy?: 'start_date' | 'manually' | 'checkout';\n starts_at?: string;\n plan_id?: string;\n template_id?: string;\n template_configuration_id?: string;\n trial?: {\n end_strategy: 'manual' | 'end_date' | 'duration';\n starts_at?: string;\n ends_at?: string;\n duration?: {\n period: 'days' | 'weeks' | 'months' | 'years';\n count: number;\n };\n };\n cancellation_strategy?:\n | 'refund_prorata'\n | 'refund_custom'\n | 'charge_prorata'\n | 'charge_custom'\n | 'end_of_period'\n | 'do_nothing';\n generate_draft_invoices?: boolean;\n renew_automatically?: boolean;\n contract_terms?: {\n activation_strategy:\n | 'start_date'\n | 'immediately'\n | 'manual'\n | 'quote_signature'\n | 'checkout';\n end_strategy: 'end_date' | 'duration' | 'manual';\n starts_at?: string;\n duration?: {\n period: 'days' | 'weeks' | 'months' | 'years';\n count: number;\n };\n renew_automatically?: boolean;\n renew_for_duration?: {\n period: 'days' | 'weeks' | 'months' | 'years';\n count: number;\n };\n };\n billing_cycle_alignment?: 'calendar_period' | 'anniversary';\n coupons?: {\n id: string;\n repeat: 'once' | 'forever' | 'custom';\n expires_at?: string;\n apply_at?: string;\n product_ids?: string[];\n }[];\n};\n\nexport type BillableEvent = {\n record: {\n id: '202408_cus_w_Q7M9bXcHMKB6';\n amount: 26;\n };\n timestamp: '2024-08-07T07:35:20.307Z';\n event_type: 'api_call';\n customer_id: 'cus_w_Q7M9bXcHMKB6';\n};\n\nexport type BillableEvents = {\n events_created: BillableEvent[];\n};\n\nexport type CreateBillableEvent = {\n customer_id: string;\n event_type: 'api_call';\n timestamp: string;\n record: {\n id?: string;\n durationInMs?: number;\n isVerified?: true;\n amount?: number;\n amountGl?: number;\n amountNonGl?: number;\n };\n};\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"src/","sources":["types.ts"],"names":[],"mappings":"","sourcesContent":["import type { components, paths } from './_types.generated';\nimport { WEBHOOKS } from './const';\n\nexport type HyperlineEntities = components['schemas'];\n\nexport type HyperlineEndpoints = paths;\n\nexport type HyperlineWebhook = keyof typeof WEBHOOKS;\n\nexport type HyperlineEvent<T extends HyperlineWebhook> = (typeof WEBHOOKS)[T];\n\nexport type HyperlinePayload<T extends HyperlineWebhook> = {\n event_type: T;\n data: Record<string, any>;\n};\n\nexport type BillableEvent = {\n record: {\n id: '202408_cus_w_Q7M9bXcHMKB6';\n amount: 26;\n };\n timestamp: '2024-08-07T07:35:20.307Z';\n event_type: 'api_call';\n customer_id: 'cus_w_Q7M9bXcHMKB6';\n};\n\nexport type BillableEvents = {\n events_created: BillableEvent[];\n};\n\nexport type CreateBillableEvent = {\n customer_id: string;\n event_type: 'api_call';\n timestamp: string;\n record: {\n id?: string;\n durationInMs?: number;\n isVerified?: true;\n amount?: number;\n amountGl?: number;\n amountNonGl?: number;\n };\n};\n"]}
@@ -0,0 +1,45 @@
1
+ export declare function calculateMrr(subscriptionId: string, estimated?: boolean, _activeListings?: number, hyperline?: {
2
+ getSubscription(id: string, liveBilling?: boolean): Promise<{
3
+ customer_id: string;
4
+ plan_id: string | null;
5
+ products?: unknown[];
6
+ coupons?: ({
7
+ type: 'amount';
8
+ repeat: 'once' | 'forever' | 'custom';
9
+ discount_amount: number;
10
+ } | {
11
+ type: 'percent';
12
+ repeat: 'once' | 'forever' | 'custom';
13
+ discount_percent: number;
14
+ })[];
15
+ phases?: {
16
+ type: 'setup' | 'trial' | 'standard';
17
+ status: 'pending' | 'active' | 'finished';
18
+ products: {
19
+ min_amount?: number | null;
20
+ max_amount?: number | null;
21
+ prices: ({
22
+ type: 'volume';
23
+ amount: number;
24
+ from: number;
25
+ to: number | null;
26
+ unit_count: number;
27
+ } | {
28
+ type: 'bps' | 'bulk' | 'bundle' | 'fee' | 'flat_fee' | 'packaged';
29
+ })[];
30
+ }[];
31
+ }[];
32
+ live_billing?: {
33
+ total_amount: number;
34
+ };
35
+ } | null>;
36
+ getInvoicesByCustomerId(id: string): Promise<{
37
+ data: {
38
+ emitted_at: string;
39
+ total_amount: number;
40
+ }[];
41
+ } | null>;
42
+ }, includeLiveBilling?: boolean): Promise<{
43
+ mrr: number;
44
+ mrrAlt: number | null;
45
+ }>;
@@ -0,0 +1,107 @@
1
+ import { GL_HYPERLINE_DEFAULT_DEV_PLAN_ID, GL_HYPERLINE_DEFAULT_MIN_AMOUNT, GL_HYPERLINE_DEFAULT_PLAN_ID, HYPERLINE_DEFAULT_DEV_PLAN_ID, HYPERLINE_DEFAULT_MIN_AMOUNT, HYPERLINE_DEFAULT_PLAN_ID, } from '../const';
2
+ import { useHyperlineByToken } from '../hooks';
3
+ export async function calculateMrr(subscriptionId, estimated = false, _activeListings, hyperline = useHyperlineByToken(process.env.HYPERLINE_TOKEN), includeLiveBilling = false) {
4
+ const _subscription = await hyperline.getSubscription(subscriptionId, includeLiveBilling);
5
+ if (!_subscription)
6
+ throw new Error('Subscription not found');
7
+ const { products, phases, ...subscription } = _subscription;
8
+ let mrr = 0;
9
+ const activeListings = _activeListings || 0;
10
+ const phase = phases?.filter((x) => estimated
11
+ ? x.type === 'standard'
12
+ : (x.type === 'trial' && x.status === 'active') || x.type === 'standard')?.[0];
13
+ const product = phase?.products?.[0];
14
+ const type = product?.prices?.[0].type;
15
+ if (type === 'volume') {
16
+ const volumePrices = [];
17
+ product?.prices?.forEach((price) => {
18
+ if (price.type !== 'volume' ||
19
+ !('amount' in price) ||
20
+ !('from' in price) ||
21
+ !('to' in price) ||
22
+ !('unit_count' in price))
23
+ return;
24
+ volumePrices.push({
25
+ amount: price.amount,
26
+ from: price.from,
27
+ to: price.to,
28
+ unit_count: price.unit_count,
29
+ });
30
+ });
31
+ volumePrices.sort((a, b) => a.from - b.from);
32
+ mrr =
33
+ volumePrices.reduce((acc, price) => {
34
+ const listings = price.to && activeListings >= price.to
35
+ ? price.to - price.from
36
+ : activeListings >= price.from
37
+ ? activeListings - price.from
38
+ : 0;
39
+ acc += (price.amount / 100) * (listings / price.unit_count);
40
+ return acc;
41
+ }, 0) || 0;
42
+ const firstTier = volumePrices[0];
43
+ const secondTier = volumePrices[1];
44
+ const product_min_amount = product &&
45
+ 'min_amount' in product &&
46
+ typeof product.min_amount === 'number'
47
+ ? product.min_amount
48
+ : null;
49
+ const product_max_amount = product &&
50
+ 'max_amount' in product &&
51
+ typeof product.max_amount === 'number'
52
+ ? product.max_amount
53
+ : null;
54
+ const inferred_min_amount = firstTier &&
55
+ secondTier &&
56
+ firstTier.from === 0 &&
57
+ firstTier.to != null &&
58
+ secondTier.from === firstTier.to &&
59
+ firstTier.amount === secondTier.amount &&
60
+ firstTier.unit_count === secondTier.unit_count
61
+ ? firstTier.amount *
62
+ ((firstTier.to - firstTier.from) / firstTier.unit_count)
63
+ : 0;
64
+ const plan_min_amount = [
65
+ GL_HYPERLINE_DEFAULT_PLAN_ID,
66
+ GL_HYPERLINE_DEFAULT_DEV_PLAN_ID,
67
+ ].includes(subscription.plan_id)
68
+ ? GL_HYPERLINE_DEFAULT_MIN_AMOUNT
69
+ : [HYPERLINE_DEFAULT_PLAN_ID, HYPERLINE_DEFAULT_DEV_PLAN_ID].includes(subscription.plan_id)
70
+ ? HYPERLINE_DEFAULT_MIN_AMOUNT
71
+ : 0;
72
+ const min_amount = ((product_min_amount || plan_min_amount || inferred_min_amount) ?? 0) /
73
+ 100;
74
+ mrr = Math.max(mrr, min_amount);
75
+ const max_amount = ((product_max_amount || 0) ?? 0) / 100;
76
+ mrr = max_amount > 0 ? Math.min(mrr, max_amount) : mrr;
77
+ // apply discounts (only these who repeat forever if estimated is true)
78
+ (subscription.coupons || [])
79
+ .filter((coupon) => (estimated ? coupon.repeat === 'forever' : true))
80
+ .forEach((x) => {
81
+ if ('discount_amount' in x && x.discount_amount)
82
+ mrr -= x.discount_amount / 100;
83
+ else if ('discount_percent' in x && x.discount_percent)
84
+ mrr -= (x.discount_percent / 100) * mrr;
85
+ });
86
+ }
87
+ else if (type === 'bps') {
88
+ const { data } = subscription?.customer_id
89
+ ? (await hyperline.getInvoicesByCustomerId(subscription.customer_id)) || {
90
+ data: [],
91
+ }
92
+ : { data: [] };
93
+ // sort invoices by date
94
+ const invoices = data
95
+ ?.sort((a, b) => a.emitted_at.localeCompare(b.emitted_at))
96
+ .reverse();
97
+ // get the last invoice
98
+ mrr = (invoices[0]?.total_amount || 0) / 100;
99
+ }
100
+ return {
101
+ mrr,
102
+ mrrAlt: subscription.live_billing?.total_amount == null
103
+ ? null
104
+ : subscription.live_billing.total_amount / 100,
105
+ };
106
+ }
107
+ //# sourceMappingURL=calculateMrr.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"calculateMrr.js","sourceRoot":"src/","sources":["utils/calculateMrr.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,gCAAgC,EAChC,+BAA+B,EAC/B,4BAA4B,EAC5B,6BAA6B,EAC7B,4BAA4B,EAC5B,yBAAyB,GAC1B,MAAM,UAAU,CAAC;AAClB,OAAO,EAAE,mBAAmB,EAAE,MAAM,UAAU,CAAC;AAE/C,MAAM,CAAC,KAAK,UAAU,YAAY,CAChC,cAAsB,EACtB,SAAS,GAAG,KAAK,EACjB,eAAwB,EACxB,YAsDI,mBAAmB,CAAC,OAAO,CAAC,GAAG,CAAC,eAAgB,CAAC,EACrD,kBAAkB,GAAG,KAAK;IAE1B,MAAM,aAAa,GAAG,MAAM,SAAS,CAAC,eAAe,CACnD,cAA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AN_ID,\n GL_HYPERLINE_DEFAULT_MIN_AMOUNT,\n GL_HYPERLINE_DEFAULT_PLAN_ID,\n HYPERLINE_DEFAULT_DEV_PLAN_ID,\n HYPERLINE_DEFAULT_MIN_AMOUNT,\n HYPERLINE_DEFAULT_PLAN_ID,\n} from '../const';\nimport { useHyperlineByToken } from '../hooks';\n\nexport async function calculateMrr(\n subscriptionId: string,\n estimated = false,\n _activeListings?: number,\n hyperline: {\n getSubscription(\n id: string,\n liveBilling?: boolean\n ): Promise<{\n customer_id: string;\n plan_id: string | null;\n products?: unknown[];\n coupons?: (\n | {\n type: 'amount';\n repeat: 'once' | 'forever' | 'custom';\n discount_amount: number;\n }\n | {\n type: 'percent';\n repeat: 'once' | 'forever' | 'custom';\n discount_percent: number;\n }\n )[];\n phases?: {\n type: 'setup' | 'trial' | 'standard';\n status: 'pending' | 'active' | 'finished';\n products: {\n min_amount?: number | null;\n max_amount?: number | null;\n prices: (\n | {\n type: 'volume';\n amount: number;\n from: number;\n to: number | null;\n unit_count: number;\n }\n | {\n type:\n | 'bps'\n | 'bulk'\n | 'bundle'\n | 'fee'\n | 'flat_fee'\n | 'packaged';\n }\n )[];\n }[];\n }[];\n live_billing?: { total_amount: number };\n } | null>;\n getInvoicesByCustomerId(id: string): Promise<{\n data: {\n emitted_at: string;\n total_amount: number;\n }[];\n } | null>;\n } = useHyperlineByToken(process.env.HYPERLINE_TOKEN!),\n includeLiveBilling = false\n) {\n const _subscription = await hyperline.getSubscription(\n subscriptionId,\n includeLiveBilling\n );\n if (!_subscription) throw new Error('Subscription not found');\n\n const { products, phases, ...subscription } = _subscription;\n\n let mrr = 0;\n const activeListings = _activeListings || 0;\n const phase = phases?.filter((x) =>\n estimated\n ? x.type === 'standard'\n : (x.type === 'trial' && x.status === 'active') || x.type === 'standard'\n )?.[0];\n const product = phase?.products?.[0];\n const type = product?.prices?.[0].type;\n if (type === 'volume') {\n const volumePrices: Array<{\n amount: number;\n from: number;\n to: number | null;\n unit_count: number;\n }> = [];\n\n product?.prices?.forEach((price) => {\n if (\n price.type !== 'volume' ||\n !('amount' in price) ||\n !('from' in price) ||\n !('to' in price) ||\n !('unit_count' in price)\n )\n return;\n\n volumePrices.push({\n amount: price.amount,\n from: price.from,\n to: price.to,\n unit_count: price.unit_count,\n });\n });\n volumePrices.sort((a, b) => a.from - b.from);\n\n mrr =\n volumePrices.reduce((acc, price) => {\n const listings =\n price.to && activeListings >= price.to\n ? price.to - price.from\n : activeListings >= price.from\n ? activeListings - price.from\n : 0;\n\n acc += (price.amount / 100) * (listings / price.unit_count);\n\n return acc;\n }, 0) || 0;\n\n const firstTier = volumePrices[0];\n const secondTier = volumePrices[1];\n const product_min_amount =\n product &&\n 'min_amount' in product &&\n typeof product.min_amount === 'number'\n ? product.min_amount\n : null;\n const product_max_amount =\n product &&\n 'max_amount' in product &&\n typeof product.max_amount === 'number'\n ? product.max_amount\n : null;\n const inferred_min_amount =\n firstTier &&\n secondTier &&\n firstTier.from === 0 &&\n firstTier.to != null &&\n secondTier.from === firstTier.to &&\n firstTier.amount === secondTier.amount &&\n firstTier.unit_count === secondTier.unit_count\n ? firstTier.amount *\n ((firstTier.to - firstTier.from) / firstTier.unit_count)\n : 0;\n const plan_min_amount = [\n GL_HYPERLINE_DEFAULT_PLAN_ID,\n GL_HYPERLINE_DEFAULT_DEV_PLAN_ID,\n ].includes(subscription.plan_id!)\n ? GL_HYPERLINE_DEFAULT_MIN_AMOUNT\n : [HYPERLINE_DEFAULT_PLAN_ID, HYPERLINE_DEFAULT_DEV_PLAN_ID].includes(\n subscription.plan_id!\n )\n ? HYPERLINE_DEFAULT_MIN_AMOUNT\n : 0;\n\n const min_amount =\n ((product_min_amount || plan_min_amount || inferred_min_amount) ?? 0) /\n 100;\n mrr = Math.max(mrr, min_amount);\n\n const max_amount = ((product_max_amount || 0) ?? 0) / 100;\n mrr = max_amount > 0 ? Math.min(mrr, max_amount) : mrr;\n\n // apply discounts (only these who repeat forever if estimated is true)\n (subscription.coupons || [])\n .filter((coupon) => (estimated ? coupon.repeat === 'forever' : true))\n .forEach((x) => {\n if ('discount_amount' in x && x.discount_amount)\n mrr -= x.discount_amount / 100;\n else if ('discount_percent' in x && x.discount_percent)\n mrr -= (x.discount_percent / 100) * mrr;\n });\n } else if (type === 'bps') {\n const { data } = subscription?.customer_id\n ? (await hyperline.getInvoicesByCustomerId(subscription.customer_id)) || {\n data: [],\n }\n : { data: [] };\n\n // sort invoices by date\n const invoices = data\n ?.sort((a, b) => a.emitted_at.localeCompare(b.emitted_at))\n .reverse();\n\n // get the last invoice\n mrr = (invoices[0]?.total_amount || 0) / 100;\n }\n\n return {\n mrr,\n mrrAlt:\n subscription.live_billing?.total_amount == null\n ? null\n : subscription.live_billing.total_amount / 100,\n };\n}\n"]}
@@ -1,2 +1,3 @@
1
1
  export * from './arrayBufferToBase64';
2
+ export * from './calculateMrr';
2
3
  export * from './getMrrDiffReasons';
@@ -1,3 +1,4 @@
1
1
  export * from './arrayBufferToBase64';
2
+ export * from './calculateMrr';
2
3
  export * from './getMrrDiffReasons';
3
4
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"src/","sources":["utils/index.ts"],"names":[],"mappings":"AAAA,cAAc,uBAAuB,CAAC;AACtC,cAAc,qBAAqB,CAAC","sourcesContent":["export * from './arrayBufferToBase64';\nexport * from './getMrrDiffReasons';\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"src/","sources":["utils/index.ts"],"names":[],"mappings":"AAAA,cAAc,uBAAuB,CAAC;AACtC,cAAc,gBAAgB,CAAC;AAC/B,cAAc,qBAAqB,CAAC","sourcesContent":["export * from './arrayBufferToBase64';\nexport * from './calculateMrr';\nexport * from './getMrrDiffReasons';\n"]}
@@ -1,5 +1,5 @@
1
1
  import type { operations, paths } from './_types.generated';
2
- import { BillableEvents, CreateBillableEvent, HyperlineCreateSubscriptionPayload } from './types';
2
+ import { BillableEvents, CreateBillableEvent } from './types';
3
3
  export type Logger = {
4
4
  error(message?: any, ...optionalParams: any[]): void;
5
5
  };
@@ -666,7 +666,7 @@ export declare class HyperlineAPI {
666
666
  data: import("./_types.generated").components["schemas"]["Subscription"][];
667
667
  } | null>;
668
668
  getAllSubscriptions(items?: paths['/v2/subscriptions']['get']['responses'][200]['content']['application/json']['data'], query?: operations['getSubscriptions']['parameters']['query']): Promise<paths['/v2/subscriptions']['get']['responses'][200]['content']['application/json']['data']>;
669
- createSubscription(data: HyperlineCreateSubscriptionPayload): Promise<({
669
+ createSubscription(data: NonNullable<paths['/v2/subscriptions']['post']['requestBody']>['content']['application/json']): Promise<({
670
670
  id: string;
671
671
  name: string | null;
672
672
  currency: "EUR" | "AED" | "AFN" | "XCD" | "ALL" | "AMD" | "AOA" | "ARS" | "USD" | "AUD" | "AWG" | "AZN" | "BAM" | "BBD" | "BDT" | "XOF" | "BGN" | "BHD" | "BIF" | "BMD" | "BND" | "BOB" | "BRL" | "BSD" | "BTN" | "NOK" | "BWP" | "BYR" | "BZD" | "CAD" | "CDF" | "XAF" | "CHF" | "NZD" | "CLP" | "CNY" | "COP" | "CRC" | "CUP" | "CVE" | "ANG" | "CZK" | "DJF" | "DKK" | "DOP" | "DZD" | "EGP" | "MAD" | "ERN" | "ETB" | "FJD" | "FKP" | "GBP" | "GEL" | "GHS" | "GIP" | "GMD" | "GNF" | "GTQ" | "GYD" | "HKD" | "HNL" | "HRK" | "HTG" | "HUF" | "IDR" | "ILS" | "INR" | "IQD" | "IRR" | "ISK" | "JMD" | "JOD" | "JPY" | "KES" | "KGS" | "KHR" | "KMF" | "KPW" | "KRW" | "KWD" | "KYD" | "KZT" | "LAK" | "LBP" | "LKR" | "LRD" | "LSL" | "LYD" | "MDL" | "MGA" | "MKD" | "MMK" | "MNT" | "MOP" | "MRO" | "MUR" | "MVR" | "MWK" | "MXN" | "MYR" | "MZN" | "NAD" | "XPF" | "NGN" | "NIO" | "NPR" | "OMR" | "PAB" | "PEN" | "PGK" | "PHP" | "PKR" | "PLN" | "PYG" | "QAR" | "RON" | "RSD" | "RUB" | "RWF" | "SAR" | "SBD" | "SCR" | "SDG" | "SEK" | "SGD" | "SHP" | "SLL" | "SOS" | "SRD" | "SSP" | "STD" | "SYP" | "SZL" | "THB" | "TJS" | "TMT" | "TND" | "TOP" | "TRY" | "TTD" | "TWD" | "TZS" | "UAH" | "UGX" | "UYU" | "UZS" | "VEF" | "VND" | "VUV" | "WST" | "YER" | "ZAR" | "ZMW" | "ZWL";