forked from johancoppens/smartschool-client
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
920 lines (871 loc) · 29.2 KB
/
index.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
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
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
/**
* De module smartschool-client voorziet een aantal functies die een subset van de
* Smartschool SOAP API implementeren, met de focus op gebruikers en groepen/klassen.
* Het biedt een zeer flexibele en vereenvoudigde manier om data uit Smartschool op
* te halen met nodeJS.
* @module smartschool-client
*/
const soap = require("soap");
const xmlParse = require("xml2js").parseStringPromise;
// const util = require('util')
module.exports = (function () {
"use strict";
let initialized = false;
let errorCodes = {};
const config = {
apiWSDL: null,
accessCode: null,
};
let soapClient = null;
/**
* Initialiseren van de smartschool-client API module
* @memberof module:smartschool-client
* @param {object} options
* @param {string} options.apiWSDL 'https://jouwschool.smartschool.be/Webservices/V3?wsdl'
* @param {string} options.accessCode Code geconfigureerd in je SmartSchool platform in Algemene Configuratie > Webservices
* @returns {Promise}
*/
const init = async ({ apiWSDL = r(), accessCode = r() } = {}) => {
config.apiWSDL = apiWSDL;
config.accessCode = accessCode;
try {
soapClient = await soap.createClientAsync(config.apiWSDL);
// console.log(util.inspect(soapClient.describe(), true, null))
} catch (err) {
throw new SOAPError("createClientAsync");
}
initialized = true;
errorCodes = await getErrorCodes();
};
/**
* Met deze methode kan je alle velden (behalve wachtwoorden en profielfoto)
* en de groepslidmaatschappen van een specifieke gebruiker ophalen.
* @memberof module:smartschool-client
* @param {object} options
* @param {string|number} options.userId Gebruikersnaam of intern nummer gebruiker
* @param {object} [options.transformation]
* @returns {Promise<Object>}
* @see {@link ./examples/00_get_user.js}
* @see {@link ./examples/01_get_user_transform.js}
*/
const getUser = async ({ userId = r(), transformation } = {}) => {
if (!initialized)
e("Module smartschool-client niet geïnitialiseerd met init()");
const params = {
accesscode: config.accessCode,
};
let res;
// Gebruikersnaam of intern nummer?
if (isNaN(userId)) {
params.username = userId;
res = await soapClient.getUserDetailsByUsernameAsync(params);
} else {
params.number = userId;
res = await soapClient.getUserDetailsByNumberAsync(params);
}
return handleJSONDataResponse(res, transformation);
};
/**
* Voegt een nieuwe gebruiker toe.
*
* Note: Niet alle mogelijke velden van
* Smartschool zijn geïmplementeerd in deze functie.
*
* Note2: De gebruiker wordt standaard toegevoegd aan de groep geconfigureerd
* in de Webservices pagina van Smartschool in het veld doelgroep. Als je een
* gebruiker aan een andere groep wilt toekennen, gebruik dan removeUserFromGroup
* en vervolgens addUserToGroup om de gebruiker te verplaatsen.
* @memberof module:smartschool-client
* @param {object} options
* @param {string} options.userName Gebruikersnaam
* @param {string} options.password Paswoord
* @param {string} options.firstName Voornaam
* @param {string} options.lastName Achternaam
* @param {string} [options.registrationNumber] stamboeknummer
* @param {string} [options.internalNumber] Intern nummer
* @param {string} [options.gender = m] Geslacht
* @param {string} [options.role = andere] Basisrol
* @param {string} [options.birthDate] Geboortedatum. Formaat YYYY-MM-DD of DD-MM-YYYY
* @param {string} [options.email] E-mail adres
* @param {string} [options.roosterCode] Roostercode (untis)
* @param {string} [options.mobilePhone] Mobiel nummer
* @returns {Promise}
* @see {@link ./examples/02_create_user.js}
*/
// Om verwarring te voorkomen maken we een verschil tussen create en update
const createUser = async ({
userName = r(),
password = r(),
firstName = r(),
lastName = r(),
registrationNumber, // stamboeknummer
internalNumber, // intern nummer
gender = "m",
role = "andere",
birthDate,
email,
roosterCode,
mobilePhone,
} = {}) => {
// Eerst controleren of gebruiker al bestaat
const user = await getUser({ userId: userName });
if (user === null) {
// Niet gevonden
const params = {
accesscode: config.accessCode,
username: userName,
passwd1: password,
name: firstName,
surname: lastName,
stamboeknummer: registrationNumber,
internnumber: internalNumber,
sex: gender,
basisrol: role,
birthday: birthDate,
email: email,
untis: roosterCode,
mobilephone: mobilePhone,
};
const res = await soapClient.saveUserAsync(params);
handleResultCodeResponse(res);
} else {
e(`Error createUser, gebruiker ${userName} bestaat reeds`);
}
};
/**
* Update een bestaande gebruiker.
*
* Note 1: Niet alle mogelijke velden van
* Smartschool zijn geïmplementeerd in deze functie.
*
* Note 2: Voor update gebruikersnaam, zie updateUserName
*
* Note 3: Voor update paswoord, zie updateUserPassword
* @memberof module:smartschool-client
* @param {object} options
* @param {string} options.userName Gebruikersnaam
* @param {string} [options.firstName] Voornaam
* @param {string} [options.lastName] Achternaam
* @param {string} [options.internalNumber] Intern nummer
* @param {string} [options.gender] Geslacht
* @param {string} [options.role] Basisrol
* @param {string} [options.birthDate] Geboortedatum. Formaat YYYY-MM-DD of DD-MM-YYYY
* @param {string} [options.email] E-mail adres
* @returns {Promise}
* @see {@link ./examples/03_update_user.js}
*/
// Om verwarring te voorkomen maken we een verschil tussen create en update
const updateUser = async ({
userName = r(),
firstName,
lastName,
gender,
role,
birthDate,
email,
} = {}) => {
// Eerst controleren of gebruiker bestaat
const user = await getUser({ userId: userName });
if (user) {
const params = {
accesscode: config.accessCode,
username: userName,
name: firstName,
surname: lastName,
sex: gender,
basisrol: role,
birthday: birthDate,
email: email,
};
const res = await soapClient.saveUserAsync(params);
return handleJSONDataResponse(res);
} else {
e(`Error updateUser, gebruiker ${userName} bestaat niet`);
}
};
/**
* Update gebruikersnaam. Kan alleen als er een intern nummer is ingevuld in Smartschool.
* @memberof module:smartschool-client
* @param {object} options
* @param {string} options.internalNumber Intern nummer
* @param {string} options.newUserName Nieuwe gebruikersnaam
* @returns {Promise}
* @see {@link ./examples/04_update_user_name.js}
*/
const updateUserName = async ({
internalNumber = r(),
newUserName = r(),
} = {}) => {
const params = {
accesscode: config.accessCode,
internNumber: internalNumber,
newUsername: newUserName,
};
const res = await soapClient.changeUsernameAsync(params);
return handleJSONDataResponse(res);
};
/**
* Update paswoorden Hoofd- en co-accounts gebruiker.
* @memberof module:smartschool-client
* @param {object} options
* @param {string} options.userName Gebruikersnaam
* @param {string} options.password Nieuw paswoord
* @param {number} [options.accountType = 0] Accounttype:'0' = hoofdaccount, '1' = co-account 1 of '2' = co-account 2 ...)
* @returns {Promise}
* @see {@link ./examples/05_update_user_password.js}
*/
const updateUserPassword = async ({
userName = r(),
password = r(),
accountType = 0,
} = {}) => {
const params = {
accesscode: config.accessCode,
userIdentifier: userName,
password: password,
accountType: accountType,
};
const res = await soapClient.savePasswordAsync(params);
handleResultCodeResponse(res);
};
/**
* Zet de status van een gebruiker op actief
* @memberof module:smartschool-client
* @param {object} options
* @param {string} options.userName Gebruikersnaam
* @returns {Promise}
* @see {@link ./examples/06_set_user_state.js}
*/
const setUserStateActive = async ({ userName = r() } = {}) => {
await setUserState({ userName: userName, state: "active" });
};
/**
* Zet de status van een gebruiker op inactief
* @memberof module:smartschool-client
* @param {object} options
* @param {string} options.userName Gebruikersnaam
* @returns {Promise}
* @see {@link ./examples/06_set_user_state.js}
*/
const setUserStateInactive = async ({ userName = r() } = {}) => {
await setUserState({ userName: userName, state: "inactive" });
};
/**
* Zet de status van een gebruiker op administratief
* @memberof module:smartschool-client
* @param {object} options
* @param {string} options.userName Gebruikersnaam
* @returns {Promise}
* @see {@link ./examples/06_set_user_state.js}
*/
const setUserStateAdministrative = async ({ userName = r() } = {}) => {
await setUserState({ userName: userName, state: "administrative" });
};
/**
* Voegt een gebruiker toe aan een groep of klas.
* @memberof module:smartschool-client
* @param {object} options
* @param {string} options.userName Gebruikersnaam
* @param {string} options.groupOrClassId Groep of klas code
* @returns {Promise}
* @see {@link ./examples/07_user_group.js}
*/
const addUserToGroup = async ({
userName = r(),
groupOrClassId = r(),
} = {}) => {
const params = {
accesscode: config.accessCode,
userIdentifier: userName,
class: groupOrClassId,
};
const res = await soapClient.saveUserToClassAsync(params);
handleResultCodeResponse(res);
};
/**
* Verwijdert een gebruiker uit een groep of klas.
* @memberof module:smartschool-client
* @param {object} options
* @param {string} options.userName Gebruikersnaam
* @param {string} options.groupOrClassId Groep of klas code
* @returns {Promise}
* @see {@link ./examples/07_user_group.js}
*/
const removeUserFromGroup = async ({
userName = r(),
groupOrClassId = r(),
} = {}) => {
const params = {
accesscode: config.accessCode,
userIdentifier: userName,
class: groupOrClassId,
};
const res = await soapClient.removeUserFromGroupAsync(params);
handleResultCodeResponse(res);
};
/**
* Haalt alle unieke gebruikers van het platform op met alle beschikbare velden.
* Als de groepCode is opgegegeven, worden enkel de gebruikers van deze groep opgehaald.
* De groepen waartoe de gebruiker behoort kan je vinden in het veld groups als een Array van strings
* @memberof module:smartschool-client
* @param {object} [options = {}]
* @param {string} [options.groupId] Unieke klas- of groepscode van de op te halen groep
* @param {bool} [options.recursive = true] Subgroepen ophalen?
* @param {object} [options.transformation]
* @returns {Promise<Array<Object>>}
* @see {@link ./examples/08_get_users.js}
* @see {@link ./examples/09_get_users_in_group.js}
* @see {@link ./examples/10_get_users_in_group_transform.js}
*/
const getUsers = async ({
groupId,
recursive = true,
transformation,
} = {}) => {
if (!initialized)
e("Module smartschool-client niet geïnitialiseerd met init()");
const params = {
accesscode: config.accessCode,
code: groupId || "", // '' voor alle gebruikers
recursive: recursive ? 1 : 0,
};
const res = await soapClient.getAllAccountsExtendedAsync(params);
return handleJSONDataResponse(res, transformation);
};
/**
* Haalt een lijst met alle klassen op.
* @memberof module:smartschool-client
* @param {object} [options = {}]
* @param {object} [options.transformation]
* @returns {Promise<Array<Object>>}
* @see {@link ./examples/11_get_classes.js}
*/
const getClasses = async ({ transformation } = {}) => {
if (!initialized)
e("Module smartschool-client niet geïnitialiseerd met init()");
const params = {
accesscode: config.accessCode,
};
const res = await soapClient.getClassListJsonAsync(params);
return handleJSONDataResponse(res, transformation);
};
/**
* Haalt een groep of klas op uit het Smartschoolplatform.
* @memberof module:smartschool-client
* @param {object} [options = {}]
* @param {string} options.groupOrClassId // group/class code
* @param {object} [options.transformation]
* @returns {Promise<Object>}
* @see {@link ./examples/12_get_group.js}
*/
const getGroup = async ({ groupOrClassId = r(), transformation } = {}) => {
if (!initialized)
e("Module smartschool-client niet geïnitialiseerd met init()");
let res = await getGroups();
res = res.find((obj) => {
if (obj.code === groupOrClassId) return obj;
});
if (!res) return null;
return transformation ? transformObject(res, transformation) : res;
};
/**
* Haalt alle groepen en klassen van het Smartschoolplatform.
* Als options.flat=false wordt er een object als boomstructuur geretourneerd.
* options.transformation is niet ondersteund in dit geval.
* @memberof module:smartschool-client
* @param {object} [options = {}]
* @param {boolean} [options.flat = true]
* @param {string} [options.groupId] Als opgegeven: deze groep en alle children
* @param {object} [options.transformation]
* @returns {Promise<Array<Object>>|Promise<Object>} null als niet gevonden
* @see {@link ./examples/13_getGroups_flat.js}
* @see {@link ./examples/14_getGroups_tree.js}
*/
const getGroups = async ({ flat = true, groupId, transformation } = {}) => {
if (transformation && flat === false)
e("options.transformation is niet toegestaan als flat=false");
if (!initialized)
e("Module smartschool-client niet geïnitialiseerd met init()");
const params = {
accesscode: config.accessCode,
};
const res = await soapClient.getAllGroupsAndClassesAsync(params);
// res[0].return.$value is data als base64 encoded xml string. Parse into a js object
let data = await xmlParse(
Buffer.from(res[0].return.$value, "base64").toString("utf-8")
);
if (typeof data === "object") {
data = cleanTree(data.groups.group[0]); // Groep "Iedereen"
if (groupId) {
data = findGroupSubTree(data, groupId);
}
if (flat) {
if (transformation) {
return transformArrayOfObjects(flattenTree(data), transformation);
} else {
return flattenTree(data);
}
} else {
return data;
}
}
// Kan niet anders dan een Smartschool Service returncode
const code = parseInt(data); // String en int door elkaar gebruikt in api
if (code === 12) return null; // Niet gevonden. Geen echte error, return null
if (code !== 0) throw new SmartSchoolServiceError(errorCodes[code], code);
};
/**
* Voegt een nieuwe groep toe.
* @memberof module:smartschool-client
* @param {object} options
* @param {string} options.groupId Groepsnaam of code
* @param {string} [options.description] Omschrijving
* @param {string} [options.parent] Unieke klas-of groepscode van parent groep. Op hoogste niveau als weggelaten.
* @param {string} [options.untis] Koppelingsvelds schoolagenda
* @returns {Promise}
* @see {@link ./examples/15_create_group.js}
*/
// Om verwarring te voorkomen maken we een verschil tussen create en update.
// In smartschool-client worden de smartschool-velden
// code en name vervangen door één veld groupId.
const createGroup = async ({
groupId = r(),
description,
parent,
untis,
} = {}) => {
// Eerst controleren of groep al bestaat
const group = await getGroup({ groupOrClassId: groupId });
if (group === null) {
// Niet gevonden
const params = {
accesscode: config.accessCode,
name: groupId,
desc: description,
code: groupId,
parent: parent,
untis: untis,
};
const res = await soapClient.saveGroupAsync(params);
handleResultCodeResponse(res);
} else {
e(`Error createGroup, groep ${groupId} bestaat reeds`);
}
};
/**
* Wijzigt een groep.
*
* Note: Hiermee kan je geen groepen in de groepenstructuur verplaatsen!
* Het wijzigen van de parent heeft geen effect. > vraag aan Smartschool team
* @memberof module:smartschool-client
* @param {object} options
* @param {string} options.groupId Groepsnaam of code
* @param {string} [options.description] Omschrijving
* @param {string} [options.parent] Unieke klas-of groepscode van parent groep. Op hoogste niveau als weggelaten.
* @param {string} [options.untis] Koppelingsveld schoolagenda
* @returns {Promise}
* @see {@link ./examples/16_update_group.js}
*/
// Om verwarring te voorkomen maken we een verschil tussen create en update.
// In smartschool-client worden de smartschool-velden
// code en name vervangen door één veld groupId.
const updateGroup = async ({
groupId = r(),
description,
parent,
untis,
} = {}) => {
// Eerst controleren of groep bestaat
const group = await getGroup({ groupOrClassId: groupId });
if (group !== null) {
// Gevonden
const params = {
accesscode: config.accessCode,
name: groupId,
desc: description,
code: groupId,
parent: parent,
untis: untis,
};
const res = await soapClient.saveGroupAsync(params);
handleResultCodeResponse(res);
} else {
e(`Error updateGroup, groep ${groupId} niet gevonden`);
}
};
/**
* Met deze methode kan je de foto van een gebruiker ophalen als base64
* encoded string in jpeg formaat
* @memberof module:smartschool-client
* @param {string} userName Gebruikersnaam
* @returns {Promise<string>}
* @see {@link ./examples/17_get_user_photo.js}
*/
const getUserPhoto = async ({ userName = r() } = {}) => {
if (!initialized)
e("Module smartschool-client niet geïnitialiseerd met init()");
const params = {
accesscode: config.accessCode,
userIdentifier: userName,
};
const res = await soapClient.getAccountPhotoAsync(params);
// We veronderstellen hier dat als res niet langer is dan 10 tekens,
// de smartschool api een errorcode doorgeeft.
if (res[0].return.$value.length < 10) {
const code = res[0].return.$value;
throw new SmartSchoolServiceError(errorCodes[code], code);
}
return res[0].return.$value;
};
/**
* Met deze methode kan je de foto van een gebruiker uploaden naar Smartschool als base64
* encoded string in jpeg formaat
* @memberof module:smartschool-client
* @param {string} userName Gebruikersnaam
* @param {string} photo Base64 encode string jpeg
* @returns {Promise}
*/
const setUserPhoto = async ({ userName = r(), photo = r() } = {}) => {
if (!initialized)
e("Module smartschool-client niet geïnitialiseerd met init()");
const params = {
accesscode: config.accessCode,
userIdentifier: userName,
photo: photo,
};
const res = await soapClient.setAccountPhotoAsync(params);
handleResultCodeResponse(res);
};
/**
* Via deze methode kan je een bericht naar de hoofdaccount of een co-account van een bepaalde gebruiker sturen. Het opgeven van de bijlage is optioneel.
* CopyToLVS niet geïmplementeerd
* Attachements toevoegen
* [
* { “filename”: “test1.docx”, “filedata”: “base64encoded string” },
* { “filename”: “test2.docx”, “filedata”: “base64encoded string” }
* ]
* @memberof module:smartschool-client
* @param {object} options
* @param {string} options.userName Gebruikersnaam
* @param {string} options.title Titel van het bericht
* @param {string} options.body Tekst van het bericht
* @param {string} [options.fromUser = 'Null'] Uniek veld gebruiker van de verzender. Geef 'Null' mee om geen verzender in te stellen
* @param {number} [options.accountType = 0] Accounttype:'0' = hoofdaccount, '1' = co-account 1 of '2' = co-account 2 ...)
* @param {Object[]} [options.attachments = []] Bijlagen (1 of meer) in base64 encoding (optioneel)
* @returns {Promise}
* @see {@link ./examples/19_send_message.js}
* @see {@link ./examples/20_send_message_attachments.js}
*/
const sendMessage = async ({
userName = r(),
title = r(),
body = r(),
fromUser = "Null",
accountType = 0,
attachments = [],
} = {}) => {
const params = {
accesscode: config.accessCode,
userIdentifier: userName,
title: title,
body: body,
senderIdentifier: fromUser,
coaccount: accountType,
attachments: attachments,
};
// Workaround error senderIdentifier = 'Null' not accepted. Simply delete it
if (params.senderIdentifier === "Null") delete params.senderIdentifier;
if (params.attachments.length === 0) {
delete params.attachments;
} else {
params.attachments = JSON.stringify(params.attachments);
}
const res = await soapClient.sendMsgAsync(params);
handleResultCodeResponse(res);
};
// PRIVATE API FUNCTIONS
// Non public exposed Smartschool api functions. Only privately used in this module
/**
* Deze methode haalt alle errorcodes op.
* @returns {Promise<object>}
*/
const getErrorCodes = async () => {
const res = await soapClient.returnJsonErrorCodesAsync(null);
return handleJSONDataResponse(res);
};
/**
* Met deze methode kan de status van een gebruiker gewijzigd worden.
* @param {object} options
* @param {string} options.userName Gebruikersnaam
* @param {string} options.state actief, inactief of administratief
* @returns {Promise}
*/
const setUserState = async ({ userName = r(), state = r() } = {}) => {
const params = {
accesscode: config.accessCode,
userIdentifier: userName,
accountStatus: state,
};
const res = await soapClient.setAccountStatusAsync(params);
handleResultCodeResponse(res);
};
const getSoapClient = async () => {
return soapClient;
};
// CUSTOM ERROR CLASSES
/**
* Custom Error class die een error van de Smartschool service representeert
* @class
* @memberof module:smartschool-client
*/
class SmartSchoolServiceError extends Error {
/**
* Constructor
* @param {string} message
* @param {string|number} code
*/
constructor(message, code) {
super(message);
this.name = "SmartSchoolServiceError";
this.code = code;
}
}
/**
* Custom Error class die een SOAP error representeert
* @class
* @memberof module:smartschool-client
*/
class SOAPError extends Error {
/**
* Constructor
* @param {string} message
*/
constructor(message) {
super(message);
this.name = "SOAPError";
}
}
/**
* Smartschool-client error
* @class
* @memberof module:smartschool-client
*/
class SmartSchoolClientError extends Error {
/**
* Constructor
* @param {string} message
*/
constructor(message) {
super(message);
this.name = "SmartSchoolClientError";
}
}
// PRIVATE DATA HANDLING FUNCTIONS
// Handles a JSON SOAP response that returns data
const handleJSONDataResponse = (resp, transformation) => {
const data = JSON.parse(resp[0].return.$value);
if (typeof data === "object") {
if (Array.isArray(data)) {
return cleanArrayOfObjects(
transformation ? transformArrayOfObjects(data, transformation) : data
);
} else {
return cleanObject(
transformation ? transformObject(data, transformation) : data
);
}
}
// Kan niet anders dan een Smartschool Service returncode
const code = parseInt(data); // String en int door elkaar gebruikt in api
if (code === 12) return null; // Niet gevonden. Geen echte error, return null
if (code !== 0) throw new SmartSchoolServiceError(errorCodes[code], code);
};
// Handles responses that perform an action
const handleResultCodeResponse = (resp) => {
const code = parseInt(JSON.parse(resp[0].return.$value)); // String en int door elkaar gebruikt in api
if (code !== 0) throw new SmartSchoolServiceError(errorCodes[code], code);
};
const cleanArrayOfObjects = (src) => {
return src.map((obj) => {
return cleanObject(obj);
});
};
// Clean values
// Empty strings to null
// ISO date strings to real Date objects
const cleanObject = (obj) => {
Object.keys(obj).forEach((fld) => {
const val = obj[fld];
// Dates like 2018-02-01
if (
RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9])-([0-9][0-9])$").test(val)
) {
// Geen datum is 0000-00-00. Vervangen door null
if (val === "0000-00-00") {
obj[fld] = null;
} else {
obj[fld] = new Date(val);
}
}
// Login tijden volgens pattern 2018-02-03 20:24:47;2018-02-03 20:24:47
// Bestaat in 2 delen gescheiden door ;
// Tweede deel is laatste inlogtijd en is de tijd die wordt weergegeven in Smartschool
// Eerste deel: voorlaatste keer ingelogd, of met mobiele app?
// We nemen tweede deel
// Als er nog nooit is ingelogd staat er enkel een ;. Dit vervangen we door null value
if (
RegExp(
";([0-9][0-9][0-9][0-9])-([0-9][0-9])-([0-9][0-9]) ([0-9][0-9]):([0-9][0-9]):([0-9][0-9])$"
).test(val)
) {
// extract last part after ;
const dat = RegExp(
"([0-9][0-9][0-9][0-9])-([0-9][0-9])-([0-9][0-9]) ([0-9][0-9]):([0-9][0-9]):([0-9][0-9])$"
)
.exec(val)[0]
.replace(" ", "T");
obj[fld] = new Date(dat);
}
// Nooit ingelogd
if (val === ";") {
obj[fld] = null;
}
// Replace '' values with null
if (val === "") {
obj[fld] = null;
}
});
return obj;
};
// Returns a new transformed array of transformed objects
const transformArrayOfObjects = (src, transformation) => {
return src.map((el) => {
return transformObject(el, transformation);
});
};
// Select and rename fields, and apply functions for calculated fields
const transformObject = (obj, transformation) => {
const newObj = {};
Object.keys(transformation).forEach((tKey) => {
if (typeof transformation[tKey] === "function") {
// apply the function on object
newObj[tKey] = transformation[tKey](obj);
} else {
if (obj[transformation[tKey]] !== undefined) {
newObj[tKey] = obj[transformation[tKey]];
} else {
newObj[tKey] = null;
}
}
});
return newObj;
};
const findGroupSubTree = (group, code) => {
let result = null;
if (group.code === code) {
return group;
}
if (group.children) {
group.children.some((child) => {
result = findGroupSubTree(child, code);
return result;
});
}
return result;
};
const cleanTree = (obj = {}) => {
Object.entries(obj).map((entry) => {
switch (entry[0]) {
case "children":
obj[entry[0]] = entry[1][0].group.map((el) => {
return cleanTree(el);
});
break;
case "titu":
obj[entry[0]] = entry[1][0].user.map((el) => {
return cleanTree(el);
});
break;
default:
switch (entry[1][0]) {
case "":
obj[entry[0]] = null;
break;
case "0":
obj[entry[0]] = false;
break;
case "1":
obj[entry[0]] = true;
break;
default:
obj[entry[0]] = entry[1][0];
}
}
});
return obj;
};
const flattenTree = (src) => {
const flat = [];
flattenTreeObj(src, flat);
return flat;
};
const flattenTreeObj = (obj, flat) => {
const newObj = {};
Object.entries(obj).forEach((entry) => {
const childrenAsStrings = [];
switch (entry[0]) {
case "children":
obj[entry[0]].forEach((child) => {
childrenAsStrings.push({ code: child.code, name: child.name });
flattenTreeObj(child, flat);
});
newObj[entry[0]] = childrenAsStrings;
break;
default:
newObj[entry[0]] = entry[1];
}
});
flat.push(newObj);
};
// Utility shortcut functions
// Parameter error func used if parameter is required
const r = () => {
e("Vereiste parameter is niet opgegeven");
};
// Shortcut for throwing an error
const e = (message) => {
throw new SmartSchoolClientError(message);
};
// Shortcut for console.log
// const l = (v) => {
// console.log(util.inspect(v, { color: true, depth: null }))
// }
// Expose public API
return {
SmartSchoolServiceError,
SOAPError,
SmartSchoolClientError,
init,
getUser,
getUsers,
createUser,
updateUser,
updateUserName,
updateUserPassword,
setUserStateActive,
setUserStateInactive,
setUserStateAdministrative,
addUserToGroup,
removeUserFromGroup,
getClasses,
getGroup,
getGroups,
createGroup,
updateGroup,
getUserPhoto,
setUserPhoto,
sendMessage,
transformArrayOfObjects,
getSoapClient,
};
})();