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
|
/*
* Garoon Schedule x Outlook Schedule sample program
* Copyright (c) 2020 Cybozu
*
* Licensed under the MIT License
*/
(function($) {
'use strict';
// クライアントID
const CLIENT_ID = 'AZURE_APPLICATION_CLIENT_ID';
// cybozu.comのホスト名(xxx.cybozu.comのxxx部分)
const HOST_NAME = 'YOUR_CYBOZU_HOST_NAME';
// ユーザのカスタマイズ項目の項目コード
const CUSTOMIZE_ITEM_KEY = 'office365_loginId';
// Schedule Datastoreのカスタム項目名
const CUSTOMIZE_NAME = 'X.Y.Z.schedule.sample';
const GAROON_BASE_PROXY_GET = 'GET_GAROON_OUTLOOK';
const GAROON_BASE_PROXY_POST = 'POST_GAROON_OUTLOOK';
const GAROON_BASE_PROXY_DELETE = 'DELETE_GAROON_OUTLOOK';
const GAROON_TIMEZONE = '+09:00';
const API_SCOPES = ['user.read', 'calendars.readwrite'];
const GRAPH_URL = 'https://graph.microsoft.com/v1.0/me/events';
const GRAPH_USER_URL = 'https://graph.microsoft.com/v1.0/users/';
// SweetAlertのダイアログ設定
const swAlert = {
showAlert: function(config) {
return Swal.fire(config);
},
showLoading: function() {
Swal.fire({
title: '処理中です...',
type: 'info',
allowOutsideClick: false,
allowEscapeKey: false,
showConfirmButton: false
});
},
showSuccess: function(title) {
return Swal.fire({
title: title,
type: 'success',
confirmButtonText: 'OK'
});
},
showError: function(text) {
return Swal.fire({
title: 'エラーが発生しました',
type: 'error',
html: text || ''
});
},
closeAlert: function() {
Swal.close();
}
};
// Garoonの画面に表示するボタンの設定
const buttonDesign = {
button: {
scheduleDeleter: {
id: 'schedule-deleter',
text: 'Outlookスケジュールの削除',
style: {
cursor: 'pointer'
}
},
freeSchedule: {
id: 'schedule-free',
text: 'スケジュール確認画面表示',
style: {
cursor: 'pointer'
}
},
scheduleWindow: {
id: 'schedule-window',
text: '空き時間照会',
style: {
cursor: 'pointer'
}
}
},
createButton: function(param) {
const button = document.createElement('input');
button.type = 'button';
button.id = param.id;
button.value = param.text;
button.style.margin = '0px 0px 10px 5px';
button.style.cursor = param.style.cursor;
return button;
},
createButtonOnHeaderSpace: function(param) {
$(garoon.schedule.event.getHeaderSpaceElement()).append(this.createButton(param));
}
};
// Garoon API
const garoonApi = {
deleteGaroonScheduleCustomizeValue: function(scheduleId) {
return garoon.api(
'api/v1/schedule/events/' + scheduleId + '/datastore/' + CUSTOMIZE_NAME,
'DELETE',
{}
);
},
// Schedule DatastoreからOutlook予定表の情報を取得する
getScheduleInfoOfOutlook: function() {
let scheduleInfo = {};
const customizeDatastore = garoon.schedule.event.datastore.get(CUSTOMIZE_NAME);
if (typeof customizeDatastore !== 'undefined') {
const customizeValue = customizeDatastore.value;
if (customizeValue.scheduleId !== '') {
scheduleInfo = {
scheduleId: encodeURIComponent(customizeValue.scheduleId),
organizer: encodeURIComponent(customizeValue.organizer)
};
}
}
return scheduleInfo;
},
// 参加者の予定をGaroonスケジュールから取得する
getScheduleAllDay: function(customize, attende) {
const query =
'?rangeStart=' +
encodeURIComponent(customize.start + 'T00:00:00' + GAROON_TIMEZONE) +
'&rangeEnd=' +
encodeURIComponent(customize.start + 'T23:59:59' + GAROON_TIMEZONE) +
'&target=' +
encodeURIComponent(attende.garoonCode) +
'&targetType=' +
encodeURIComponent(attende.type.toLowerCase());
return garoon.api('/api/v1/schedule/events' + query, 'GET', {});
}
};
// User API
const userApi = {
// ユーザー情報からOffice365ログインIDを取得する
fetchUsersInfo: function(users) {
const codes = users.map((user, index) => {
return 'codes[' + index + ']=' + user.code;
});
return new Promise((resolve, reject) => {
$.ajax({
url: 'https://' + HOST_NAME + '.cybozu.com/v1/users.json?' + codes.join('&'),
type: 'GET',
}).done((res) => {
resolve(res.users);
}).fail((e) => {
reject(e);
});
});
}
};
// Microsoft Graph API
const graphApi = {
clientId: CLIENT_ID,
apiScopes: API_SCOPES,
graphUrl: GRAPH_URL,
msalInstance: null,
loginToken: null,
loginUser: null,
init: function() {
const config = {
auth: {
clientId: this.clientId
}
};
this.msalInstance = new msal.PublicClientApplication(config);
},
showLogionPopup: function() {
return this.msalInstance.loginPopup();
},
setLoginAccount: function() {
const user = this.msalInstance.getAllAccounts();
if (user.length === 1) {
this.loginUser = user[0];
}
},
// Outlook予定表に予定を登録する
postRequest: function(scheduleInfo, header, param) {
return new Promise((resolve, reject) => {
garoon.base.proxy.send(
GAROON_BASE_PROXY_POST,
GRAPH_USER_URL + scheduleInfo.organizer + '/events',
'POST',
header,
param
).then((response) => {
const responseJson = !response[0] ? {} : JSON.parse(response[0]);
if ('error' in responseJson) {
reject(responseJson.error.code + ': ' + responseJson.error.message);
} else {
const registeredInfo = {
scheduleId: responseJson.id,
organizer: responseJson.organizer.emailAddress.address
};
resolve(registeredInfo);
}
}).catch((e) => {
reject(e);
});
});
},
// Outlook予定表の予定を変更する
patchRequest: function(scheduleInfo, header, param) {
const url = GRAPH_USER_URL + scheduleInfo.organizer + '/events/' + scheduleInfo.scheduleId;
return new Promise((resolve, reject) => {
garoon.base.proxy.send(
'PATCH_GAROON_OUTLOOK',
url,
'PATCH',
header,
param
).then((response) => {
const data = JSON.parse(response[0]);
const status = response[1];
if (status === 200) {
resolve();
} else {
const errorObj = data.error;
let message = errorObj.code + ': ' + errorObj.message;
if (status === 404) {
message = 'Outlookのスケジュールの更新に失敗しました。\n既に削除されている可能性があります。status: 404.';
const value = {
value: {
scheduleId: '',
organizer: ''
}
};
garoon.schedule.event.datastore.set(CUSTOMIZE_NAME, value);
}
reject(message);
}
}).catch((error) => {
reject(error);
});
});
},
// Outlook予定表から予定を削除する
deleteRequest: function(schedule, scheduleInfo, headers) {
garoon.base.proxy.send(
GAROON_BASE_PROXY_DELETE,
GRAPH_USER_URL + scheduleInfo.organizer + '/events/' + scheduleInfo.scheduleId,
'DELETE',
headers,
{},
(response, statusCode) => {
const responseJson = !response ? {} : JSON.parse(response);
if ('error' in responseJson) {
if (statusCode === 404) {
swAlert.showError('Outlookのスケジュールの削除に失敗しました。<br>既に削除されている可能性があります。').then(() => {
return garoonApi.deleteGaroonScheduleCustomizeValue(schedule.id);
}).then(() => {
location.reload();
});
} else {
swAlert.showError(
'code: ' + responseJson.error.code + '<br>' +
'message: ' + responseJson.error.message
);
}
} else {
garoonApi.deleteGaroonScheduleCustomizeValue(schedule.id).then(() => {
return swAlert.showSuccess('Outlookのスケジュールの\n削除に成功しました.');
}).then(() => {
location.reload();
});
}
},
(error) => {
console.error(error);
swAlert.showError(error);
}
);
},
// 「参加者」に追加されているユーザーのOutlook予定表に登録・変更・削除する
modifyOutlookSchedule: function(method, scheduleInfo, param) {
const self = this;
const schedule = param.event;
const userOnlyAttendees = schedule.attendees.filter((attende) => {
return attende.type === 'USER';
});
let sendParam = {};
// eslint-disable-next-line consistent-return
return userApi.fetchUsersInfo(userOnlyAttendees).then((usersInfo) => {
const margeAttandees = customize.margeAttendeesArray(userOnlyAttendees, usersInfo);
const attendees = margeAttandees.map((attendee) => {
return {
emailAddress: {
address: customize.getOffice365LoginId(attendee.customItemValues)
}
};
});
const header = {
Authorization: 'Bearer ' + self.loginToken,
'Content-Type': 'application/json'
};
if (attendees.length > 0) {
const DATE_TIME_FORMAT = 'YYYY-MM-DDTHH:mm:SS';
const startDateTime = moment(schedule.start.dateTime);
let endDateTime = schedule.isStartOnly ? startDateTime : moment(schedule.end.dateTime);
if (startDateTime.format('HH:mm:SS') === endDateTime.format('HH:mm:SS') && schedule.isAllDay) {
endDateTime = endDateTime.add(1, 'd');
}
if (['POST', 'PATCH'].indexOf(method) >= 0) {
sendParam = {
subject: schedule.subject,
body: {
contentType: 'text',
content: schedule.notes
},
start: {
dateTime: startDateTime.format(DATE_TIME_FORMAT),
timeZone: schedule.start.timeZone
},
end: {
dateTime: endDateTime.format(DATE_TIME_FORMAT),
timeZone: schedule.end.timeZone
},
attendees: attendees,
isAllDay: schedule.isAllDay,
sensitivity: ['PRIVATE', 'SET_PRIVATE_WATCHERS'].indexOf(schedule.visibilityType) >= 0 ? 'private' : 'normal'
};
}
switch (method) {
case 'POST':
return self.postRequest(
scheduleInfo,
header,
sendParam
);
case 'PATCH':
return self.patchRequest(
scheduleInfo,
header,
sendParam
);
case 'DELETE':
self.deleteRequest(
schedule,
scheduleInfo,
header
);
break;
}
} else {
alert('参加者がいないためOutlookへ登録/更新は行いません。');
}
});
},
registerScheduleToOutlook: function(scheduleInfo, param) {
return this.modifyOutlookSchedule('POST', scheduleInfo, param);
},
updateScheduleToOutlook: function(scheduleInfo, param) {
return this.modifyOutlookSchedule('PATCH', scheduleInfo, param);
},
deleteScheduleToOutlook: function(scheduleInfo, param) {
const self = this;
swAlert.showAlert({
title: 'Outlookのスケジュールを\n削除します.',
type: 'warning',
confirmButtonText: 'はい',
cancelButtonText: 'いいえ',
showCancelButton: true
}).then((result) => {
if (result.value) {
swAlert.showLoading();
self.setLoginAccount();
if (self.loginUser) {
self.setLoginToken().then(() => {
self.modifyOutlookSchedule('DELETE', scheduleInfo, param);
}).catch((e) => {
console.error(e);
});
} else {
self.showLogionPopup().then(() => {
self.setLoginAccount();
return self.setLoginToken();
}).then(() => {
self.modifyOutlookSchedule('DELETE', scheduleInfo, param);
}).catch((e) => {
console.error(e);
swAlert.closeAlert();
});
}
}
});
},
// Outlook予定表からログインIDを指定して予定を取得する
getScheduleAllDay: function(loginId, customize, header) {
const url =
GRAPH_USER_URL +
encodeURIComponent(loginId) +
'/calendar/calendarView?' +
'startDateTime=' +
encodeURIComponent(customize.start + 'T00:00:00') +
'&endDateTime=' +
encodeURIComponent(customize.start + 'T23:59:59');
return garoon.base.proxy.send(
GAROON_BASE_PROXY_GET,
url,
'GET',
header,
{}
);
},
// Graph APIを実行できるアクセストークンを取得する
setLoginToken: function() {
const config = {
scopes: this.apiScopes,
account: this.loginUser
};
const self = this;
return new Promise((resolve, reject) => {
self.msalInstance.acquireTokenSilent(config).then((token) => {
self.loginToken = token.accessToken;
resolve();
}).catch((e) => {
console.error(e);
swAlert.showLoading();
self.msalInstance.acquireTokenPopup(config).then((token) => {
self.loginToken = token.accessToken;
resolve();
}).catch((e2) => {
console.error(e2);
reject(e2);
});
});
});
}
};
const customize = {
$modal: null,
$modalScheduler: null,
$calendar: null,
setConfigOfModal: function(isVisible, $modalCloseBtn) {
const event = garoon.schedule.event.get();
let startDate;
if (event.attendees.length > 0) {
startDate = event.start.dateTime.split('T')[0];
window.garoon_customize_sample = {
start: startDate,
attendees: event.attendees.filter((attende) => {
return attende.type === 'USER';
})
};
this.$modal.fadeIn();
this.createScheduleView();
$('#sample-names').remove();
$modalCloseBtn.fadeIn();
return !isVisible;
}
swAlert.showAlert({
title: '参加者を指定してください.',
type: 'warning'
});
return isVisible;
},
createModalOfScheduler: function() {
const self = this;
let isVisible = false;
this.$modal = $('<div></div>', {
id: 'sample-modal',
on: {
click: function() {
if (event.target.id === 'sample-modal') {
self.$modal.fadeOut();
isVisible = false;
self.$calendar.destroy();
$('#sample-names').remove();
}
}
}
});
const $modalContents = $('<div></div>', {
id: 'sample-modal-contents'
});
const $modalScheduleContent = $('<div></div>', {
id: 'sample-modal-schedule-content'
});
this.$modalScheduler = $('<div></div>', {
id: 'sample-modal-scheduler'
});
const $modalFooter = $('<div></div>', {
id: 'sample-modal-footer'
});
const $modalCloseBtn = $('<input></input>', {
type: 'button',
value: '閉じる',
id: 'sample-modal-close',
on: {
click: function() {
self.$modal.fadeOut();
isVisible = false;
self.$calendar.destroy();
$('#sample-names').remove();
}
}
});
$modalFooter.append($modalCloseBtn);
this.$modal.append(
$modalContents
.append($modalScheduleContent.append(this.$modalScheduler))
.append($modalFooter)
);
this.$modal.hide();
$(garoon.schedule.event.getHeaderSpaceElement()).append(this.$modal);
$('#schedule-window').on('click', () => {
isVisible = self.setConfigOfModal(isVisible, $modalCloseBtn);
});
},
createScheduler: function(garoonCustomize) {
const calendar = new FullCalendar.Calendar(this.$modalScheduler[0], {
plugins: ['timeGrid'],
defaultView: 'timeGridDay',
timezone: 'Asia/Tokyo',
locale: 'ja',
defaultDate: garoonCustomize.start,
header: {
left: false,
center: 'title',
right: false
},
height: 'parent',
scrollTime: '09:00:00'
});
calendar.render();
this.$calendar = calendar;
return calendar;
},
margeAttendeesArray: function(garoonAttendees, users) {
const attendees = garoonAttendees.map((grAttende) => {
let info;
$.each(users, (index, user) => {
if (grAttende.code === user.code) {
info = user;
info.garoonCode = grAttende.id;
info.type = grAttende.type;
}
});
return info;
});
return attendees;
},
getOffice365LoginId: function(items) {
let loginId = '';
$.each(items, (index, item) => {
if (item.code === CUSTOMIZE_ITEM_KEY) {
loginId = item.value;
}
});
return loginId;
},
createScheduleView: function() {
const self = this;
// 背景色
const bgColors = [
'#FFF295',
'#CFF3C1',
'#D4FFF1',
'#D5EAF2',
'#DCD6FF',
'#D2C8F6',
'#FFD4E6',
'#F5CAC4',
'#FFDFDB',
'#FFE3F9'
];
const garoonCustomize = window.garoon_customize_sample;
if (garoonCustomize.attendees.length > 0) {
userApi.fetchUsersInfo(garoonCustomize.attendees).then((usersInfo) => {
const attendees = self.margeAttendeesArray(garoonCustomize.attendees, usersInfo);
const calendar = self.createScheduler(garoonCustomize);
const config = {
scopes: graphApi.apiScopes,
account: graphApi.loginUser
};
graphApi.msalInstance.acquireTokenSilent(config).then((token) => {
const header = {
Authorization: 'Bearer ' + token.accessToken,
'Content-Type': 'application/json',
Prefer: 'outlook.timezone="Tokyo Standard Time"'
};
const $names = $('<div></div>', {id: 'sample-names'});
const bgColorOfUsers = {};
self.$modalScheduler.prepend($names);
attendees.forEach((attende, attendeNo) => {
const $name = $('<span>' + attende.name + '</span>');
$name.addClass('sample-name');
bgColorOfUsers[attende.code] = bgColors[attendeNo % bgColors.length];
$name.css({
'background-color': bgColorOfUsers[attende.code]
});
$('#sample-names').append($name);
const loginId = self.getOffice365LoginId(attende.customItemValues);
if (loginId !== '') {
graphApi.getScheduleAllDay(loginId, garoonCustomize, header).then((response) => {
const responseJson = !response ? {} : JSON.parse(response[0]);
try {
if (typeof responseJson.value !== 'undefined') {
responseJson.value.forEach((schedule) => {
calendar.addEvent({
title: '[Ol]' + schedule.subject,
start: schedule.start.dateTime,
end: schedule.end.dateTime,
color: bgColorOfUsers[attende.code],
allDay: schedule.isAllDay,
textColor: '#2d2d2d'
});
});
}
} catch (e) {
console.error(e);
}
}).catch((e) => {
console.error(e);
});
}
garoonApi.getScheduleAllDay(garoonCustomize, attende).then((response) => {
response.data.events.forEach((schedule) => {
calendar.addEvent({
title: '[Gr]' + schedule.subject,
start: schedule.start.dateTime,
end: schedule.end.dateTime,
color: bgColorOfUsers[attende.code],
allDay: schedule.isAllDay,
textColor: '#2d2d2d'
});
});
}).catch((e) => {
console.error(e);
});
});
});
}).catch((error) => {
console.error(error);
});
}
}
};
const customizeController = {
createFreeTimeScheduler: function() {
buttonDesign.createButtonOnHeaderSpace(
buttonDesign.button.scheduleWindow
);
customize.createModalOfScheduler();
},
createActionButtonOfOffice365: function(param) {
graphApi.init();
const customizeDatastore = garoon.schedule.event.datastore.get(CUSTOMIZE_NAME);
if (typeof customizeDatastore !== 'undefined') {
const customizeValue = customizeDatastore.value;
if (customizeValue.scheduleId !== '') {
buttonDesign.createButtonOnHeaderSpace(
buttonDesign.button.scheduleDeleter
);
$('#schedule-deleter').on('click', () => {
graphApi.deleteScheduleToOutlook(customizeValue, param);
});
}
}
},
loginToOutlook: function() {
graphApi.setLoginAccount();
return new Promise((resolve, reject) => {
if (graphApi.loginUser) {
return resolve();
}
swAlert.showLoading();
return graphApi.showLogionPopup().then((param) => {
graphApi.setLoginAccount();
resolve(param);
}).catch((e) => {
reject(e);
});
});
}
};
garoon.events.on('schedule.event.detail.show', (param) => {
customizeController.createActionButtonOfOffice365(param);
});
garoon.events.on(['schedule.event.create.show', 'schedule.event.edit.show'], (event) => {
if (['REPEATING', 'ALL_DAY'].indexOf(event.event.eventType) >= 0) {
return event;
}
graphApi.init();
customizeController.loginToOutlook().then(() => {
return graphApi.setLoginToken();
}).then(() => {
customizeController.createFreeTimeScheduler();
userApi.fetchUsersInfo([garoon.base.user.getLoginUser()]).then((res) => {
const o365LoginId = customize.getOffice365LoginId(res[0].customItemValues);
if (o365LoginId !== '') {
const scheduleInfo = {
organizer: encodeURIComponent(o365LoginId)
};
garoon.events.on('schedule.event.create.submit', (param) => {
return graphApi.registerScheduleToOutlook(scheduleInfo, param).then((response) => {
return garoon.schedule.event.datastore.set(CUSTOMIZE_NAME, {value: response});
}).then(() => {
return param;
}).catch((error) => {
console.error(error);
alert('Outlookへスケジュールを登録中にエラーが発生しました。\n' + error);
});
});
}
swAlert.closeAlert();
}).catch((error) => {
console.error(error);
swAlert.closeAlert();
});
garoon.events.on('schedule.event.edit.submit', (param) => {
const scheduleInfo = garoonApi.getScheduleInfoOfOutlook();
if (Object.keys(scheduleInfo).length > 0) {
return graphApi.updateScheduleToOutlook(scheduleInfo, param).then(() => {
return param;
}).catch((error) => {
console.error(error);
alert('Outlookのスケジュールを更新中にエラーが発生しました。\n' + error);
});
}
return param;
});
}).catch((e) => {
console.error(e);
swAlert.closeAlert();
});
return event;
});
})(jQuery.noConflict(true));
|