This repository has been archived by the owner on Feb 8, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
286 lines (267 loc) · 7.55 KB
/
main.js
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
279
280
281
282
283
284
285
286
var date = (new Date().getFullYear() - 2010) * 12 + new Date().getMonth();
var usdfilter = /\$ ([\d\.-]+)/;
var data = {
start: monthSerial(date - 12),
end: monthSerial(date - 1),
startRaw: () => unmonthSerial(data.start),
endRaw: () => Math.max(data.startRaw(), unmonthSerial(data.end)),
dateRange: Array(date + 1).fill().map((_, i) => monthSerial(i)).reverse(),
pubId: localStorage['uas-priv-pubid'] || 0,
pubIdHint: 'https://i.imgur.com/uBFYQMA.png',
operation: 'downloads',
operationChoices: ['downloads', 'sales'],
property: 'qty',
propertyChoices: ['qty', 'gross'],
range: [],
raw: [],
parsed: [],
parsedCumulative: {},
idx: 0,
showCodePanel: false,
theJS: '',
theData: '',
theDataError: '',
loadTheDataFromDisk: function () {
data.theData = localStorage['uas-priv-data-' + data.operation] || '[]';
setTimeout(() => data.goStep2(), 0);
},
// Generate the JS
goStep1: () => {
var range = new Array(data.endRaw() - data.startRaw() + 1).fill().map((_, i) => monthSerial(i + data.startRaw()));
data.theJS = makeTheJS(data.operation, data.pubId, data.range = range);
},
// Parse the data
goStep2: () => {
try {
var sales = data.operation === 'sales';
localStorage['uas-priv-pubid'] = data.pubId;
localStorage['uas-priv-dates'] = JSON.stringify({
start: data.start,
end: data.end
});
data.raw = JSON.parse(localStorage['uas-priv-data-' + data.operation] = data.theData);
var parsed = [];
var iter = 0;
data.raw.forEach(el => {
if (typeof el === 'object') {
var aaData = el.aaData;
var result = el.result;
var snapst = el.snapshot;
for (let i = 0; i < aaData.length; i++) {
var name = aaData[i][0];
var qty = parseFloat(sales ? aaData[i][2] : aaData[i][1]);
var gross = sales ? parseFloat(aaData[i][5].match(usdfilter)[1]) : 0;
var short = result[i]['short_url'];
var obj = parsed.find((v, i, a) => v.short === short);
if (!obj) parsed.push(obj = {
name: name,
short: short,
stat: new Array(data.raw.length).fill(),
total: {
qty: 0,
gross: 0
}
});
var st = {
qty: qty,
gross: gross,
};
obj.stat[iter] = combineStat(obj.stat[iter], st);
obj.stat[iter].snapshot = snapst;
obj.total = combineStat(obj.total, st);
}
}
iter++;
});
data.theDataError = '';
data.parsed = parsed; {
var cum = data.parsedCumulative = {
name: "Total",
short: {},
stat: new Array(data.raw.length).fill(),
total: {
qty: 0,
gross: 0
}
};
var stat = cum.stat;
parsed.forEach(el => {
for (let i = 0; i < el.stat.length; i++) {
if (stat[i] = combineStat(stat[i], el.stat[i]))
stat[i].snapshot = stat[i].snapshot || (el.stat[i] && el.stat[i].snapshot);
}
})
stat.forEach(el => cum.total = combineStat(cum.total, el));
}
data.goStep3();
} catch (e) {
console.log(e);
data.theDataError = e && e.message;
}
},
// Graph the whole thing
goStep3: () => {
var buffer = [];
data.parsed.forEach(el => {
var stat2 = [];
data.range.forEach(r => stat2.push(el.stat.find(v => v && v.snapshot === r) || null));
buffer.push({
label: el.name,
backgroundColor: 'transparent',
borderColor: serialColor(el.name),
data: stat2.map(v => (v && v[data.property]) || 0),
})
})
if (data.parsed.length > 1) {
var stat2 = [];
data.range.forEach(r => stat2.push(data.parsedCumulative.stat.find(v => v && v.snapshot === r) || null));
buffer.push({
label: "Total",
backgroundColor: 'transparent',
borderColor: 'rgba(0, 0, 0, 0.3)',
borderWidth: 2,
data: stat2.map(v => (v && v[data.property]) || 0),
});
}
if (window.graphCanvas) window.graphCanvas.destroy();
if (window.cumulativeCanvas) window.cumulativeCanvas.destroy();
window.graphCanvas = new Chart(graph.getContext("2d"), {
type: 'line',
data: {
labels: data.range,
datasets: buffer
},
options: {
tooltips: {
mode: 'index',
axis: 'xy'
},
maintainAspectRatio: false
}
})
var dataSets = data.parsed.map((x) => data.range.map(y => {
var w = x.stat.find(z => z && z.snapshot == y);
return w ? w[data.property] : 0;
}).reduce((a, b) => a + b, 0));
var sumOfAll = dataSets.reduce((a, b) => a + b, 0);
// entirely different graph
window.cumulativeCanvas = new Chart(cumulative.getContext("2d"), {
type: 'pie',
data: {
labels: data.parsed.map((x) => x.name),
datasets: [{
backgroundColor: data.parsed.map((x) => serialColor(x.name)),
data: dataSets,
}]
},
options: {
tooltips: {
callbacks: {
// Include a dollar sign in the ticks
label: function (value, data) {
var i = value.index;
return `${data.labels[i]} : ${dataSets[i]} of ${sumOfAll} (${(dataSets[i]/sumOfAll*100).toFixed(1)}%)`;
}
}
}
}
})
},
copyTheJS: function () {
var area = document.getElementById('theJS');
area.select();
area.focus();
var ok = document.execCommand('copy');
var btn = document.getElementById('copyTheJS-btn');
btn.textContent = ok ? 'Copied!' : 'Press Ctrl + C';
setTimeout(() => btn.textContent = 'Copy', 3000);
}
}
new Vue({
el: '#app',
data: data,
mounted: () => {
var dates = localStorage['uas-priv-dates'];
if (dates) {
dates = JSON.parse(dates);
data.start = dates.start;
data.end = dates.end;
if (data.pubId > 0) {
data.goStep1();
}
}
data.loadTheDataFromDisk();
}
})
function makeTheJS(operation, pubid, requests) {
if (pubid==0) return `please set Publisher ID first`;
return `
(function () {
var uri = '/api/publisher-info/${operation}/${pubid}/';
var data = [];
var requests = ${JSON.stringify(requests)};
var finalmsg = "Requests done. Scroll down the page and hit Ctrl + C to copy the data";
function DoRequest(i) {
var req = requests[i];
console.log("Requesting data at " + req);
var xhr = new XMLHttpRequest();
var url = uri + req + ".json";
xhr.onreadystatechange = function () {
if (this.readyState == 4) {
if (this.status == 200)
data.push(Object.assign(JSON.parse(this.responseText), {snapshot:req}));
else
data.push("⛔ " + this.status);
if (i + 1 < requests.length)
DoRequest(i + 1);
else {
var area = document.createElement("textarea");
document.body.appendChild(area);
area.value = JSON.stringify(data);
area.style.width = '100%';
area.style.height = '20%';
area.select();
area.focus();
console.log(finalmsg);
}
}
};
xhr.open("GET", url, true);
xhr.timeout = 60000;
xhr.setRequestHeader("accept", "application/json")
xhr.send();
}
setTimeout(() => DoRequest(0), 0);
return "Wait a minute while we doing " + requests.length + " requests";
})();
`.trim().replace(/\t/g, " ");
}
function monthSerial(number) {
// number is month counting from from Jan 2010 (zero)
return (2010 + Math.trunc(number / 12)) + (number % 12 + 1).toString().padStart(2, "0");
}
function unmonthSerial(str) {
str = str || "201701";
return (parseInt(str.substring(0, 4)) - 2010) * 12 + parseInt(str.substring(4, 6)) - 1;
}
function serialColor(str) {
// https://stackoverflow.com/a/16348977/3908409
var hash = 0;
for (var i = 0; i < str.length; i++) {
hash = str.charCodeAt(i) + ((hash << 5) - hash);
}
var colour = '#';
for (var i = 0; i < 3; i++) {
var value = (hash >> (i * 8)) & 0xFF;
colour += ('00' + value.toString(16)).substr(-2);
}
return colour;
}
function combineStat(a, b) {
if (!a) return b;
if (!b) return a;
return {
qty: a.qty + b.qty,
gross: a.gross + b.gross,
}
}