-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.js
337 lines (265 loc) · 7.83 KB
/
utils.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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
import {apiSettings} from './settings';
import Big from 'big.js';
import moment from 'moment';
import {parseCookies} from "nookies";
import fetch from 'isomorphic-unfetch'
import locale_es from "moment/locale/es";
import {fetchApiResource, filterApiResourceObjectsByType} from "./ApiResource";
export const getAuthToken = ctx => {
return parseCookies(ctx)['authToken'];
};
// REF: https://stackoverflow.com/questions/6660977/convert-hyphens-to-camel-case-camelcase
export function camelize(str) {
return str.replace(/_([a-z])/g, function (g) {
return g[1].toUpperCase();
});
}
export function fetchJson(input, init = {}) {
return fetchAuth(null, input, init);
}
export function fetchAuth(authToken, input, init = {}) {
if (!input.includes(apiSettings.endpoint)) {
input = apiSettings.endpoint + input
}
if (!init.headers) {
init.headers = {}
}
if (authToken) {
init.headers.Authorization = `Token ${authToken}`;
}
if (init.headers['Content-Type'] === null) {
delete init.headers['Content-Type']
} else if (typeof(init.headers['Content-Type'] === 'undefined')) {
init.headers['Content-Type'] = 'application/json';
}
init.headers['Accept'] = 'application/json';
return fetch(input, init).then(res => {
if (!res.ok) {
throw res
}
if (res.status === 204) {
return res
} else {
return res.json()
}
})
}
export function navigatorLanguage() {
// Define user's language. Different browsers have the user locale defined
// on different fields on the `navigator` object, so we make sure to account
// for these different by checking all of them
const language = (navigator.languages && navigator.languages[0]) ||
navigator.language ||
navigator.userLanguage;
return language.toLowerCase().split(/[_-]+/)[0];
}
export function formatDateStr(timestampStr) {
const dateObj = moment(timestampStr);
return dateObj.format('llll')
}
export function formatCurrency(value, valueCurrency, conversionCurrency, thousandsSeparator, decimalSeparator) {
if (typeof value === 'undefined' || value === null || Number.isNaN(value)) {
return ''
}
let formattingCurrency = valueCurrency;
if (conversionCurrency && (valueCurrency.url !== conversionCurrency.url)) {
value *= new Big(conversionCurrency.exchangeRate) / new Big(valueCurrency.exchangeRate);
formattingCurrency = conversionCurrency
}
const decimalPlaces = formattingCurrency.decimalPlaces;
const prefix = formattingCurrency.prefix;
const decimalValue = new Big(value);
return prefix + ' ' + _formatCurrency(decimalValue, decimalPlaces, 3, thousandsSeparator, decimalSeparator);
}
export function convertToDecimal(value) {
if (typeof value === 'undefined') {
return undefined
}
if (value === null) {
return null
}
return new Big(value)
}
export function setLocale(locale) {
const localesDict = {
'es': locale_es,
'en': null
};
if (typeof localesDict[locale] === 'undefined') {
console.warn('Using unsupported locale: ' + locale);
}
moment.locale(locale)
}
/**
* @param value: Value to format
* @param n: length of decimal
* @param x: length of whole part
* @param s: sections delimiter
* @param c: decimal delimiter
*/
export function _formatCurrency(value, n, x, s, c) {
const re = '\\d(?=(\\d{' + (x || 3) + '})+' + (n > 0 ? '\\D' : '$') + ')',
num = value.toFixed(Math.max(0, ~~n));
return (c ? num.replace('.', c) : num).replace(new RegExp(re, 'g'), '$&' + (s || ','));
}
export function listToObject(list, key = 'id') {
const result = {};
for (const item of list) {
result[item[key]] = item
}
return result
}
export function parseBig(value) {
if (value === null) {
return null
}
return new Big(value)
}
export function fillTimeLapse(dataset, startDate, endDate, dateField, valueField, emptyValue) {
const valuesDict = {};
for (const dataPoint of dataset) {
valuesDict[dataPoint[dateField]] = dataPoint[valueField]
}
const result = [];
const iterDate = moment(startDate);
while (iterDate <= endDate) {
let entryValue = valuesDict[iterDate];
if (typeof(entryValue) === 'undefined') {
entryValue = emptyValue
}
result.push({
date: moment(iterDate),
[valueField]: entryValue
});
iterDate.add(1, 'days')
}
return result;
}
const offset = moment().utcOffset();
export function parseDateToCurrentTz(dateStr) {
/* Handle all the dates using the CURRENT timezone of the browser
* This is different than just calling moment(dateStr) because moment()
* handles DST, so if two dates are in different DST then they have a 1 hour
* offset */
return moment(dateStr).utcOffset(offset, true);
}
export function loadResources(requiredResources, store, callback) {
const apiResourceObjects = {};
for (let resource of requiredResources) {
fetchApiResource(resource, store.dispatch)
.then((apiResourceObjectList) => {
const state = store.getState();
for (const apiResourceObject of apiResourceObjectList) {
apiResourceObjects[apiResourceObject.url] = apiResourceObject
}
if (requiredResources.every(resource => filterApiResourceObjectsByType(apiResourceObjects, resource).length)) {
callback(
state.authToken,
store.dispatch,
apiResourceObjects
)
}
})
}
}
export function areObjectsEqual(objA, objB, valueField='url') {
const objAValue = objA ? objA[valueField] : null;
const objBValue = objB ? objB[valueField] : null;
return objAValue === objBValue;
}
export function areObjectListsEqual(listA, listB, valueField='url') {
if (listA === null && listB === null) {
return true;
}
if (typeof(listA) === 'undefined' && typeof(listB) === 'undefined') {
return true;
}
if (typeof(listA) !== typeof(listB)) {
return false
}
if (listA === null && listB !== null) {
return false
}
if (listA !== null && listB === null) {
return false
}
if (listA.length !== listB.length) {
return false
}
for (let i = 0; i < listA.length; i++) {
if (listA[i][valueField] !== listB[i][valueField]) {
return false;
}
}
return true;
}
export function areValuesEqual(valueA, valueB, valueField='url') {
if (typeof(valueA) !== typeof(valueB)) {
return false;
} else if (Array.isArray(valueA)) {
return areObjectListsEqual(valueA, valueB, valueField)
} else {
return areObjectsEqual(valueA, valueB, valueField)
}
}
export function registerLead(authToken, websiteId, entity, uuid) {
const requestBody = {
website: websiteId
};
if (uuid) {
requestBody['uuid'] = uuid
}
return fetchAuth(
authToken,
`entities/${entity.id}/register_lead/`,
{
method: 'POST',
body: JSON.stringify(requestBody)
});
}
export function areListsEqual(listA, listB) {
if (listA === null && listB === null) {
return true;
}
if ((listA === null && listB !== null) || (listA !== null && listB === null)) {
return false
}
if (typeof(listA) !== typeof(listB)) {
return false
}
if (listA.length !== listB.length) {
return false
}
for (let i = 0; i < listA.length; i++) {
if (listA[i] !== listB[i]) {
return false;
}
}
return true;
}
export function areValueListsEqual(listA, listB) {
if (listA === null && listB === null) {
return true;
}
if (typeof(listA) !== typeof(listB)) {
return false
}
if (listA.length !== listB.length) {
return false
}
for (let i = 0; i < listA.length; i++) {
if (listA[i].id !== listB[i].id) {
return false;
}
}
return true;
}
// A nice helper to tell us if we're on the server
export const isServer = !(
typeof window !== 'undefined' &&
window.document &&
window.document.createElement
);
export const convertIdToUrl = (id, resource) => {
return `${apiSettings.apiResourceEndpoints[resource]}${id}/`
};