-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtransform.js
More file actions
476 lines (413 loc) · 14.3 KB
/
Copy pathtransform.js
File metadata and controls
476 lines (413 loc) · 14.3 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
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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
var CJCD;
CJCD = (function () {
var ids = {};
var people = {};
//
// Generic stuff
// You can change this, but don't need to
//
// format phone numbers as (801) 555-1234
function formatTel(t) {
t = (t || "").replace(/\D/g, "").trim();
if (!t) {
return "";
}
if (t.length > 10) {
if ("1" !== t[0] || t.length > 11) {
console.warn("phone too long:", t);
}
t = t.slice(-10);
//return "";
}
if (t.length < 10) {
console.warn("phone too short:", t);
t = t.padStart(10, "_");
//return "";
}
// (801) 555-1234
//return `(${t.slice(0, 3)}) ${t.slice(3, 6)}-${t.slice(6, 10)}`;
// +18015551234
return `+1${t.slice(0, 10)}`;
}
// formats the email
function formatEmail(name, email) {
if (!email || !/@/.test(email)) {
return "";
}
email = email.toLowerCase().trim();
// "Harry Potter <harry.j.potter@email.com>"
//return `<pre>"${name}" <${email}>,</pre>`;
return email;
}
// formats a card as a row
function formatMember(c) {
return {
id: c.id,
district: c.district,
name: c.name,
nickname: c.spokenName,
age: c.age,
gender: "FEMALE" === c.gender ? "F" : "M",
phone: CJCD._formatTel(c.individualPhone || c.phone),
email: CJCD._formatEmail(c.spokenName, c.email),
address: c._address || [],
imageDataUrl: CJCD._images[c.id] || "",
};
}
function getPerson(cmisId) {
if (!people[cmisId]) {
ids[cmisId] = true;
people[cmisId] = {
cmisId: cmisId,
companions: {},
assignments: {},
ministers: {},
};
}
return people[cmisId];
}
function organize() {
CJCD._data.props.pageProps.initialState.ministeringData.elders.forEach(
function (district) {
district.companionships.forEach(function (ship, i) {
//console.log("companionship", i);
// this is a little imperfect for people in multiple companionships, but should work generally
ship.ministers.forEach(function (m, j) {
//console.log("minister", j);
ids[m.legacyCmisId] = true;
var p = getPerson(m.legacyCmisId);
p.district = district.districtName;
if (ship.ministers) {
ship.ministers.forEach(function (n) {
if (m === n) {
return;
}
p.companions[n.legacyCmisId] = true;
});
}
if (ship.assignments) {
ship.assignments.forEach(function (a) {
var q = getPerson(a.legacyCmisId);
q.ministers[m.legacyCmisId] = true;
p.assignments[a.legacyCmisId] = true;
ids[a.legacyCmisId] = true;
});
}
});
});
}
);
}
async function getCards() {
for (id in ids) {
await getCard(id);
}
}
function getCachedCard(id) {
return CJCD._cards[id];
}
async function getProfile(id) {
if (CJCD._profiles[id]) {
return await CJCD._profiles[id];
}
//console.log(Object.keys(profiles).length, id);
// misnomer, this is the whole family, formatted 10 different ways
var profileUrl = `https://lcr.churchofjesuschrist.org/records/member-profile/service/${id}?lang=eng`;
CJCD._profiles[id] = fetch(profileUrl, {
credentials: "same-origin",
}).then(async function (resp) {
CJCD._profiles[id] = await resp.json();
// data.individual?.residentialAddress?.formattedLines
return CJCD._profiles[id];
});
return await CJCD._profiles[id];
}
async function getImageDataUrl(id) {
if (CJCD._p_images[id]) {
return CJCD._p_images[id];
}
var profileImageUrl = `https://lcr.churchofjesuschrist.org/services/photos/manage-photos/approved-image-individual/${id}?lang=eng&addable=false`;
//var profileImageUrl = `https://lcr.churchofjesuschrist.org/services/photos/manage-photos/approved-image-household/${id}?lang=eng&type=HOUSEHOLD`;
CJCD._p_images[id] = fetch(profileImageUrl, {
credentials: "same-origin",
}).then(async function (resp) {
let data = await resp.json();
let tokenUrl = data.image?.tokenUrl || "";
if (!tokenUrl || 'images/nohousehold.svg' === tokenUrl || 'images/nophoto.svg' === tokenUrl) {
return "";
}
var imgUrl = `${tokenUrl}/MEDIUM`;
var opts = { credentials: "same-origin" };
return await fetch(imgUrl, opts)
.then(async function (resp) {
let blob = await resp.blob();
CJCD._images[id] = await blobToDataURL(blob);
//return CJCD._images[id];
});
}).catch(function (err) {
console.error("Image Error: Could not fetch image for", id);
console.error(err);
CJCD._images[id] = "";
// return CJCD._images[id];
});
return CJCD._p_images[id];
//**blob to dataURL**
function blobToDataURL(blob) {
return new Promise(function (resolve, reject) {
var a = new FileReader();
a.onload = function (e) {
resolve(e.target.result);
};
a.onerror = function (e) {
reject(e);
};
a.readAsDataURL(blob);
});
}
}
async function getCard(id) {
if (CJCD._cards[id]) {
return await CJCD._cards[id];
}
//console.log(Object.keys(cards).length, id);
var cardUrl =
`https://lcr.churchofjesuschrist.org/services/member-card` +
`?id=${id}&includePriesthood=true&lang=eng&type=INDIVIDUAL`;
CJCD._cards[id] = fetch(cardUrl, {
credentials: "same-origin",
}).then(async function (resp) {
CJCD._cards[id] = await resp.json();
CJCD._cards[id]._address = await getProfile(id)
.then(function (data) {
return (
data.individual?.residentialAddress?.formattedLines || []
);
})
.catch(function () {
return [];
});
await getImageDataUrl(id);
return CJCD._cards[id];
});
return await CJCD._cards[id];
}
async function getAssignment(id) {
var p = CJCD.getPerson(id);
var c = await CJCD.getCard(id);
if (!c) {
throw new Error(`Error: invalid id '${id}'`);
}
var assignment = {
member: CJCD._formatMember(c),
assignments: [],
ministers: [],
companions: [],
};
if (Object.keys(p.assignments).length) {
assignment.assignments = await Promise.all(Object.keys(p.assignments).map(
async function (id) {
var family = await CJCD.getCard(id);
return CJCD._formatMember(family);
}
));
}
if (Object.keys(p.companions).length > 0) {
assignment.companions = await Promise.all(Object.keys(p.companions).map(
async function (id) {
var companion = await CJCD.getCard(id);
return CJCD._formatMember(companion);
}
));
}
if (Object.keys(p.ministers).length > 0) {
assignment.ministers = await Promise.all(Object.keys(p.ministers).map(
async function (id) {
var minister = await CJCD.getCard(id);
return CJCD._formatMember(minister);
}
));
}
return assignment;
}
function toCSV() {
var exported = {};
var csv = [
[ "District", "Companions", "Families" ]
];
var ships = [];
var members = CJCD.toJSON();
members.forEach(function (m) {
var p = m.member
if (exported[p.id]) {
return;
}
exported[p.id] = true;
m.companions.forEach(function (c) {
if (exported[c.id]) {
return;
}
exported[c.id] = true;
ships.push(m);
});
});
ships.sort(function (a, b) {
if (a.district < b.district) {
return -1;
}
if (a.district > b.district) {
return 1;
}
return 0;
});
ships.forEach(function (m) {
var p = m.member
//console.log(m);
var mName = p.nickname || p.name;
var mPhone = p.phone || p.email;
var companions = [
[mName, mPhone].join(' ')
];
m.companions.forEach(function (c) {
var name = c.nickname || c.name;
var phone = c.phone || c.email || '';
companions.push(
[name, phone].join(' ')
);
});
if (!m.assignments?.length) {
//console.log('skip');
return;
}
csv.push([
'"' + m.district + '"',
'"' + companions.join('\n') + '"',
'"' + m.assignments.map(function (a) {
return a.nickname || a.name;
}).join('\n') + '"',
]);
});
return csv.map(function (row) {
return row.join('\t');
}).join('\n');
}
function idToMember(id) {
var p = CJCD.getPerson(id);
var c = CJCD.getCachedCard(id);
if (!c) {
throw new Error(`Error: invalid id '${id}'`);
}
var assignment = {
district: p.district,
member: CJCD._formatMember(c),
assignments: [],
ministers: [],
companions: [],
};
if (Object.keys(p.assignments).length) {
assignment.assignments = Object.keys(p.assignments).map(
function (m) {
var family = CJCD.getCachedCard(m);
return CJCD._formatMember(family);
}
);
}
if (Object.keys(p.companions).length > 0) {
assignment.companions = Object.keys(p.companions).map(function (
id
) {
var companion = CJCD.getCachedCard(id);
return CJCD._formatMember(companion);
});
}
if (Object.keys(p.ministers).length > 0) {
assignment.ministers = Object.keys(p.ministers).map(function (
id
) {
var minister = CJCD.getCachedCard(id);
return CJCD._formatMember(minister);
});
}
return assignment;
}
function toJSON() {
// assignments
return Object.keys(CJCD.ids).map(idToMember);
}
function $(sel, el) {
return (el || document.body).querySelector(sel);
}
function createDownloadAnchor(text, name) {
// TODO https://stackoverflow.com/a/41553494/151312
//var contentType = "text/json;charset=utf-8";
var contentType = "application/octet-stream";
var dataStr = "data:" + contentType + "," + encodeURIComponent(text);
var a = document.createElement('a');
a.setAttribute("href", dataStr);
a.setAttribute("download", name);
return a;
}
function download(json, name, replacer, indent) {
var text;
if ('string' === typeof json) {
text = json;
} else {
text = JSON.stringify(json, replacer, indent);
}
var a = createDownloadAnchor(text, name);
document.body.appendChild(a); // required for firefox
a.click();
a.remove();
}
return {
_data: null,
_cards: null,
_p_images: null,
_images: null,
_people: people,
_formatTel: formatTel,
_formatEmail: formatEmail,
_formatMember: formatMember,
ids: ids,
init: async function (_data, _cards, _profiles, _images) {
if (!_data) {
_data = JSON.parse(
$('script[type="application/json"]').innerText
);
}
CJCD._data = _data;
CJCD.organize();
CJCD._cards = _cards || CJCD._cards || {};
CJCD._images = _images || CJCD._images || {};
CJCD._p_images = {};
CJCD._profiles = _profiles || CJCD._profiles || {};
},
organize: organize,
getPerson: getPerson,
getAssignment: getAssignment,
getAssignments: async function () {
let assignments = [];
await Object.keys(CJCD.ids).reduce(function (promise, id) {
return promise.then(async function () {
let assignment = await CJCD.getAssignment(id);
assignments.push(assignment);
});
}, Promise.resolve());
return assignments;
},
getCard: getCard,
getCards: getCards,
getCachedCard: getCachedCard,
toJSON: toJSON,
toCSV: toCSV,
download: function (name = 'ministering-assignments.json', replacer, indent) {
if (name.endsWith('.csv')) {
download(toCSV(), name, replacer, indent);
} else {
download(toJSON(), name, replacer, indent);
}
},
};
})();
if ("undefined" != typeof module) {
module.exports = CJCD;
}