Repository navigation
Expand file tree
/
Copy pathanalyticsController.js
More file actions
278 lines (256 loc) · 8.77 KB
/
Copy pathanalyticsController.js
File metadata and controls
278 lines (256 loc) · 8.77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
/**
* src/controllers/analyticsController.js
* Handles analytics endpoints for transaction volume insights.
*/
"use strict";
const analyticsService = require("../services/analyticsService");
const stellarService = require("../services/stellarService");
/**
* @typedef {object} AnalyticsSummary
* @property {string} publicKey
* @property {string} totalSentXLM
* @property {string} totalReceivedXLM
* @property {number} uniqueCounterparties
* @property {string} averageTransactionSize
* @property {number} totalTransactions
* @property {object} comparison
* @property {number} comparison.thisWeekCount
* @property {number} comparison.lastWeekCount
* @property {number} comparison.countChangePercent
* @property {string} comparison.thisWeekVolume
* @property {string} comparison.lastWeekVolume
* @property {number} comparison.volumeChangePercent
*/
/**
* @typedef {object} TopRecipientsResponse
* @property {string} publicKey
* @property {Array<{address: string, totalXLMSent: string}>} topRecipients
* @property {number} count
*/
/**
* @typedef {object} ActivityByDayResponse
* @property {string} publicKey
* @property {Array<{day: string, dayIndex: number, transactionCount: number}>} activityByDay
*/
/**
* @typedef {object} CohortBreakdownResponse
* @property {string} publicKey
* @property {"week"|"month"} period
* @property {number} periods
* @property {{start: string|null, end: string|null}} range
* @property {Array<object>} cohorts
*/
/**
* GET /api/analytics/:publicKey/summary
* Returns: total sent, received, unique counterparties, avg transaction size.
*
* @param {object} req - Express request
* @param {object} req.params
* @param {string} req.params.publicKey - Stellar public key (G...)
* @param {object} res - Express response
* @param {function} next - Express error-handling callback
* @returns {Promise<void>} JSON: `{ success: true, data: AnalyticsSummary }`
*/
async function getSummary(req, res, next) {
try {
const { publicKey } = req.params;
const data = await analyticsService.getSummary(publicKey);
res.json({ success: true, data });
} catch (err) {
next(err);
}
}
/**
* GET /api/analytics/:publicKey/top-recipients
* Returns: top 5 addresses by total XLM sent.
*
* @param {object} req - Express request
* @param {object} req.params
* @param {string} req.params.publicKey - Stellar public key (G...)
* @param {object} res - Express response
* @param {function} next - Express error-handling callback
* @returns {Promise<void>} JSON: `{ success: true, data: TopRecipientsResponse }`
*/
async function getTopRecipients(req, res, next) {
try {
const { publicKey } = req.params;
const data = await analyticsService.getTopRecipients(publicKey);
res.json({ success: true, data });
} catch (err) {
next(err);
}
}
/**
* GET /api/analytics/:publicKey/activity
* Returns: payment count by day of week (all 7 days).
*
* @param {object} req - Express request
* @param {object} req.params
* @param {string} req.params.publicKey - Stellar public key (G...)
* @param {object} res - Express response
* @param {function} next - Express error-handling callback
* @returns {Promise<void>} JSON: `{ success: true, data: ActivityByDayResponse }`
*/
async function getActivityByDay(req, res, next) {
try {
const { publicKey } = req.params;
const data = await analyticsService.getActivityByDay(publicKey);
res.json({ success: true, data });
} catch (err) {
next(err);
}
}
/**
* GET /api/analytics/:publicKey/cohorts
* Returns repeat vs one-time counterparties grouped by period.
*
* @param {object} req - Express request
* @param {object} req.params
* @param {string} req.params.publicKey - Stellar public key (G...)
* @param {object} req.query
* @param {"week"|"month"} [req.query.period] - Cohort bucket size, defaults to "month"
* @param {string} [req.query.periods] - Number of buckets to return (max 12, default 6)
* @param {object} res - Express response
* @param {function} next - Express error-handling callback
* @returns {Promise<void>} JSON: `{ success: true, data: CohortBreakdownResponse }`
*/
async function getCohortBreakdown(req, res, next) {
try {
const { publicKey } = req.params;
const { period, periods } = req.query;
const data = await analyticsService.getCohortBreakdown(publicKey, { period, periods });
res.json({ success: true, data });
} catch (err) {
next(err);
}
}
/**
* GET /api/analytics/:publicKey/stream
* Server-sent events stream for new payment operations.
*
* @param {object} req - Express request
* @param {object} req.params
* @param {string} req.params.publicKey - Stellar public key (G...)
* @param {object} res - Express response (kept open as a `text/event-stream`)
* @param {function} next - Express error-handling callback
* @returns {Promise<void>} SSE stream emitting `event: payment` with a JSON-encoded
* PaymentRecord-like payload, `event: error` with `{ message: string }`, and periodic
* `: heartbeat` comments
*/
async function streamPayments(req, res, next) {
try {
const { publicKey } = req.params;
res.status(200);
res.setHeader("Content-Type", "text/event-stream; charset=utf-8");
res.setHeader("Cache-Control", "no-cache, no-transform");
res.setHeader("Connection", "keep-alive");
res.setHeader("X-Accel-Buffering", "no");
if (typeof res.flushHeaders === "function") {
res.flushHeaders();
}
res.write("retry: 5000\n\n");
const heartbeat = setInterval(() => {
res.write(": heartbeat\n\n");
}, 25000);
const stopStream = stellarService.streamPaymentEvents(publicKey, {
onPayment: (payment) => {
res.write(`event: payment\ndata: ${JSON.stringify(payment)}\n\n`);
},
onError: (error) => {
res.write(
`event: error\ndata: ${JSON.stringify({
message: error instanceof Error ? error.message : "Payment stream error",
})}\n\n`
);
},
});
const cleanup = () => {
clearInterval(heartbeat);
stopStream();
if (!res.writableEnded) {
res.end();
}
};
req.on("close", cleanup);
req.on("aborted", cleanup);
} catch (err) {
next(err);
}
}
/**
* POST /api/analytics/:publicKey/export-schedule
* Set up recurring email export.
*
* @param {object} req - Express request
* @param {object} req.params
* @param {string} req.params.publicKey - Stellar public key (G...)
* @param {object} req.body
* @param {string} req.body.email - Destination email address
* @param {"daily"|"weekly"} req.body.frequency - Export cadence
* @param {object} res - Express response
* @param {function} next - Express error-handling callback
* @returns {Promise<void>} 201 JSON: `{ success: true, data: { publicKey: string, email: string,
* frequency: string, nextRunAt: string }, message: string }`
*/
async function scheduleExport(req, res, next) {
try {
const { publicKey } = req.params;
const { email, frequency } = req.body;
const data = analyticsService.scheduleExport(publicKey, email, frequency);
res.status(201).json({ success: true, data, message: "Recurring export scheduled successfully" });
} catch (err) {
next(err);
}
}
/**
* GET /api/analytics/:publicKey/export-schedule
* Get scheduled export configuration.
*
* @param {object} req - Express request
* @param {object} req.params
* @param {string} req.params.publicKey - Stellar public key (G...)
* @param {object} res - Express response
* @param {function} next - Express error-handling callback
* @returns {Promise<void>} JSON: `{ success: true, data: { publicKey: string, email: string,
* frequency: string, nextRunAt: string } | null }`
*/
async function getExportSchedule(req, res, next) {
try {
const { publicKey } = req.params;
const data = analyticsService.getExportSchedule(publicKey);
res.json({ success: true, data });
} catch (err) {
next(err);
}
}
/**
* POST /api/analytics/:publicKey/export-trigger
* Manually trigger sending export email.
*
* @param {object} req - Express request
* @param {object} req.params
* @param {string} req.params.publicKey - Stellar public key (G...)
* @param {object} res - Express response
* @param {function} next - Express error-handling callback
* @returns {Promise<void>} JSON: `{ success: true, data: { success: true }, message: string }`,
* or 404 (via next) when no export schedule exists for this public key
*/
async function triggerExport(req, res, next) {
try {
const { publicKey } = req.params;
const data = await analyticsService.triggerEmailExport(publicKey);
res.json({ success: true, data, message: "Export email sent" });
} catch (err) {
next(err);
}
}
module.exports = {
getSummary,
getTopRecipients,
getActivityByDay,
getCohortBreakdown,
streamPayments,
scheduleExport,
getExportSchedule,
triggerExport,
};