Garoon スケジュールと Outlook 予定表を使って予定を調整する

目次

caution
警告

Moment.js はメンテナンスモードになり、 日付処理できる代替ライブラリへの移行 (External link) が推奨されています。
代替ライブラリのひとつ Luxon (External link) については、 kintone カスタマイズでの導入方法の紹介記事 があります。

はじめに

営業は Outlook の予定表をメインに使っているけど、他の部署は Garoon スケジュールを使っている。
違う部署のメンバーとの打ち合わせをするときは、Garoon と Outlook それぞれにログインしてにらめっこ…。

そんな問題を Garoon カスタマイズで解決しませんか?
この記事で紹介するカスタマイズでは、Garoon 上で次のことを行えます。

  • Garoon と Outlook の両方の予定を参照して予定を登録する。
  • Garoon 上で予定を登録・変更・削除したときに、Outlook 予定表へ自動で同期する。
    このカスタマイズでは、Outlook に登録された予定の Garoon への同期はできません。

必要なもの

  • Garoon クラウド版
  • Microsoft Office365 アカウント

完成イメージ

予定の登録・変更

  • Garoon の「予定の登録」「予定の変更」画面に[空き時間照会]ボタンが追加されます。

  • [空き時間照会]ボタンをクリックすると、参加者の Garoon に登録された予定と、Outlook 予定表に登録された予定を同時に確認できます。

  • Garoon 予定を登録すると、Outlook 予定表にも予定が登録されます。
    予定のタイトルのほか、「メモ」の内容も予定に反映されます。

予定の削除

「予定の詳細」画面で、[Outlook スケジュールの削除]ボタンをクリックすると、Outlook の予定表から予定が削除されます。
Garoon のスケジュールから予定を削除する場合は、[削除する]リンクで予定を削除する必要があります。
Outlook 予定表の設定で、共有先の編集を許可している場合のみ可能です。

システム構成

このカスタマイズのシステム構成としくみは次のとおりです。

  1. Garoon から OAuth 認証を用いて Entra ID V2 Endpoint へサインインします。
    Microsoft Authentication Library for JavaScript (MSAL.js) (External link) を利用することで、OAuth を使った認可フローを実現します。
  2. Azure からアクセストークンを取得します。
  3. ユーザーを取得する API を実行します。
  4. cybozu.com のユーザー情報から、参加者の Office365 のログイン ID を取得します。
  5. アクセストークンを使って、Microsoft Graph API を実行します。
    Microsoft Graph API(以降、Graph API)は、Microsoft 365 サービスの情報を利用する API です。
  6. Outlook 予定表を取得します。
  7. Garoon REST API を実行して、参加者の予定を取得します。
  8. アクセストークンを使って、ユーザーの操作(予定の登録・変更・削除)に応じた Graph API を実行します。

注意事項

Microsoft Entra ID の設定

アプリケーションの作成

Garoon から Graph API (External link) を利用するため、Microsoft Entra ID にアプリケーションを登録します。
この設定は、管理者のみ行う作業です。利用者が個々に設定する必要はありません。

Azure ポータル (External link) で、Microsoft Entra ID にアプリケーションを登録します。
手順は次のページを参照してください。
Garoon ポータルで Outlook の未読メール数をチェックしよう:アプリケーションの作成

  • この記事では、作成するアプリケーション名を「garoon-outlook-schedule」としています。
  • アプリケーション作成後、作成したアプリケーションの詳細画面が表示されます。
    「Application (client) ID (アプリケーション(クライアント)ID)」の値をメモしてください。
    Garoon カスタマイズファイルで利用します。
    詳細画面は、Azure ポータル >[Microsoft Entra ID]>[App registrations]の手順でも開くことができます。

アプリケーションの設定

手順1. リダイレクト URL の設定
  1. 作成したアプリケーションの詳細画面の左サイドメニューから、[Authentication]([認証])を選択します。

  2. [Add a Platform](プラットフォームを追加)ボタンをクリックします。

  3. [Single-page application](シングルページアプリケーション)を選択します。

  4. 次の内容を入力します。入力後、[Configure](構成)ボタンをクリックします。

    項目 備考
    Redirect URIs
    (リダイレクトURL)
    次の URL を入力します。
    https://{subdomain}.cybozu.com/g/schedule/add.csp
    Type(種類)は、「Web」を選択します。
    {subdomain} の部分は、利用環境に合わせてください
  5. 「Add URL」(URL の追加)をクリックし、「Redirect URIs」(リダイレクト URL)に次の内容を入力します。入力後、[Save](保存)ボタンをクリックします。

    • https://{subdomain}.cybozu.com/g/schedule/modify.csp
    • https://{subdomain}.cybozu.com/g/schedule/view.csp

    {subdomain} の部分は、利用環境に合わせてください

手順2. OAuth 認証スコープの設定
  1. 作成したアプリケーションの詳細画面の左サイドメニューから、[API permissions]([API のアクセス許可])を選択します。

  2. [Add a permission]([アクセス許可の追加])ボタンをクリックします。

  3. Microsoft Graph API を利用可能に設定します。[Add permission]([追加])ボタンをクリックし、[Microsoft Graph]を選択します。

  4. [Delegated permissions]([委任されたアクセス許可])を選択します。

    • Calendars.ReadWrite
    • Calendars.ReadWrite.Shared
    • User.Read.All
      デフォルトで設定されている User.Read はチェックを外してください。

  5. 次の権限が、Configured permissions(構成されたアクセス許可)画面の一覧に表示されていれば OK です。

    • Microsoft Graph
      • Calendars.ReadWrite
      • Calendars.ReadWrite.Shared
      • User.Read.All
  6. Configured permissions(構成されたアクセス許可)画面で、[Grant admin consent for xxx]([xxx に管理者の同意を与えます])をクリックし、処理を実行します。
    xxx は Entra ID のディレクトリー名です。

Outlook の設定

  1. Outlook (External link) にログインします。

  2. カレンダーアイコンをクリックして、予定表を開きます。

  3. 「個人用の予定表」「予定表」の[…]をクリックし、[共有とアクセス許可]をクリックします。

  4. 組織内の連絡先、または共有したいユーザを入力し、以下のいずれかの権限に設定します。

    • すべての詳細を表示可能:
    • 編集が可能:他の人の Outlook スケジュールを予定を登録する場合は、「編集が可能」を選択してください。

  5. ユーザーに共有した場合は、共有先に設定したメールアドレス宛へ「予定表へのアクセス権が追加されました」というメールが届きます。[承諾]ボタンをクリックして、相手の Outlook 予定表から予定が見えるようにします。

Garoon の設定

Garoon では、以下を設定します。

  1. Graph API を利用するためのプロキシ API 設定を追加
  2. cybozu.com 共通管理でユーザーのカスタマイズ項目を追加
  3. スケジュールアプリにカスタマイズファイルを適用

なお、このカスタマイズでは、次の外部ライブラリを利用しています。

手順1.プロキシ API 設定

手順の詳細は「 プロキシAPIの設定を追加する (External link) 」を参照してください。

  1. 「Garoon システム管理」画面を開きます。

  2. 「基本システムの管理」タブをクリックし、[API]を選択します。

  3. [プロキシ API の設定]をクリックします。

  4. [追加する]をクリックします。

  5. 以下の内容を入力します。入力が終わったら、[追加する]ボタンをクリックして、設定を追加します。

    項目
    ステータス 「有効」を選択します。
    プロキシコード GET_GAROON_OUTLOOK
    メソッド 「GET」を選択します。
    URL https://graph.microsoft.com/
  6. 4.〜の手順と同様に、POST 用および DELETE 用のプロキシ API を設定します。

    • POST

      項目
      ステータス 「有効」を選択します。
      プロキシコード POST_GAROON_OUTLOOK
      メソッド 「POST」を選択します。
      URL https://graph.microsoft.com/
    • DELETE

      項目
      ステータス 「有効」を選択します。
      プロキシコード DELETE_GAROON_OUTLOOK
      メソッド 「DELETE」を選択します。
      URL https://graph.microsoft.com/
    • PATCH

      項目
      ステータス 「有効」を選択します。
      プロキシコード PATCH_GAROON_OUTLOOK
      メソッド 「PATCH」を選択します。
      URL https://graph.microsoft.com/

手順2. ユーザーのカスタマイズ項目

cybozu.com 共通管理で、Office365 ログイン ID を設定するユーザのカスタマイズ項目を作成します。
手順の詳細は「 ユーザー情報の項目を追加する(カスタマイズ項目) (External link) 」を参照してください。

  1. 「cybozu.com 共通管理」画面を開きます。

  2. 「ユーザー管理」の[組織/ユーザー]を選択します。

  3. [プロフィール項目の設定]ボタンをクリックします。

  4. 「カスタマイズ項目の設定」の[追加]ボタンをクリックします。

  5. 次の内容を入力します。入力が終わったら[保存]ボタンをクリックし、保存します。

    項目
    項目名 Office365ログインID
    項目コード office365_loginId
    タイプ 「文字列(1行)」を選択します。
    公開/非公開 「公開する」を選択します。
    ユーザーによる変更 任意でチェックを入れてください。
  6. 設定が完了したら、「cybozu.com 共通管理」からユーザー情報を編集します。
    Outlook 予定表を利用しているユーザーアカウントの「Office365 ログイン ID」を設定してください(参考: ユーザー情報を編集する (External link)

手順3.カスタマイズファイルの適用

カスタマイズグループを作成し、スケジュールのカスタマイズファイルを適用します。
手順の詳細は スケジュールのカスタマイズ設定 (External link) を参照してください。

  1. Garoon メニュー右の歯車アイコンをクリックし、[Garoon システム管理]を選択します。
  2. [各アプリケーションの管理]タブを選択し、[スケジュール]を選択します。
  3. [JavaScript/CSS によるカスタマイズ]を選択します。
  4. [カスタマイズグループを追加する]をクリックします。
  5. 次の内容を入力します。入力が終わったら、[追加する]ボタンをクリックします。

    項目名 設定値
    カスタマイズ 「適用する」を選択します。
    カスタマイズグループ名 任意の値を入力します。
    今回は「Outlook予定表連携」とします。
    適用対象 カスタマイズを適用するユーザー・グループを選択します。
    JavaScript カスタマイズ 以下の順で、URL およびファイルを指定します。
    「fullcalendar」で始まるファイルの入手方法は FullCalendar ライブラリの入手方法 を参照してください。
    1. https://alcdn.msauth.net/browser/2.12.1/js/msal-browser.min.js
    2. https://js.cybozu.com/jquery/3.3.1/jquery.min.js
    3. https://js.cybozu.com/momentjs/2.24.0/moment-with-locales.min.js
    4. https://js.cybozu.com/sweetalert2/v8.2.1/sweetalert2.min.js
    5. fullcalendar-core-main.min.js
    6. fullcalendar-daygrid-main.min.js
    7. fullcalendar-timegrid-main.min.js
    8. fullcalendar-core-locales_all.min.js
    9. https://js.cybozu.com/es6-promise/v4.2.5/es6-promise.auto.min.js
    10. カスタマイズファイル(scheduleGaroonoutlook.js)
      詳細は、後述の サンプルコード(scheduleGaroonoutlook.js) を参照してください。
    CSS カスタマイズ 以下の順で、URLおよびファイルを指定します。
    「fullcalendar」で始まるファイルの入手方法は FullCalendar ライブラリの入手方法 を参照してください。
    1. https://js.cybozu.com/sweetalert2/v8.2.1/sweetalert2.min.css
    2. fullcalendar-core-main.min.css
    3. fullcalendar-daygrid-main.min.css
    4. fullcalendar-timegrid-main.min.css
    5. カスタマイズファイル(scheduleGaroonoutlook.css)
      詳細は、後述の サンプルコード(scheduleGaroonoutlook.css) を参照してください。
FullCalendar ライブラリの入手方法
  1. lib_fullcalendar-4.0.1.zip からファイルをダウンロードします。
  2. ダウンロードした zip ファイルを解凍します。
  3. 解凍したファイルの「js」「css」フォルダー以下にあるファイルを利用します。

動作確認

予定の登録

事前に Outlook 予定表へ予定を登録しておいてください。

  1. Garoon で、スケジュールの「予定の登録」画面を開きます。

  2. Microsoft アカウントのログイン画面が表示されます。Microsoft アカウントでログインします。

  3. 登録したい予定の日付を入力し、「参加者」にユーザーを追加します。

  4. [空き時間照会]ボタンをクリックします。

  5. モーダルが表示されます。
    入力した日付の「参加者」に追加しているユーザーの Garoon および Outlook の予定タイトルが同時に表示されます。

    予定タイトル冒頭の [Gr][OI] は、次の意味です。
    [Gr]:Garoon スケジュールに登録された予定
    [OI]:Outlook 予定表に登録された予定

  6. 任意の時間を入力し、予定を登録します。

  7. Garoon に予定が登録されます。
    Outlook の設定 で、共有先の権限に「編集が可能」を設定しているユーザーの場合、Outlook 予定表に予定が追加されます。

予定の変更

変更時も同様に、[空き時間照会]ボタンから、「参加者」に追加しているユーザーの Garoon と Outlook の予定を同時に確認できます。

共有先の権限に「編集が可能」を設定しているユーザーの場合、変更した内容が Outlook の予定表にも反映されます。

予定の削除

  1. 削除したい予定の詳細画面を開きます。
  2. [Outlook スケジュールの登録]ボタンをクリックします。

  3. 「Outlook スケジュールを削除します」ダイアログが表示されます。[はい]ボタンをクリックすると、Outlook 予定表から予定が削除されます。

  4. [OK]ボタンをクリックし、ダイアログを閉じます。

  5. Garoon のスケジュールから予定を削除したい場合は、[削除する]リンクをクリックします。

サンプルコード

scheduleGaroonoutlook.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
/*
 * 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));

scheduleGaroonoutlook.css

 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
/*
 * Garoon Schedule x Outlook Schedule sample program
 * Copyright (c) 2020 Cybozu
 *
 * Licensed under the MIT License
*/

#sample-modal {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  width: 100vw;
  background-color: rgba(0, 0, 0, 0.8);
  position: fixed;
  top: 0;
  left: 0;
  z-index: 9999;
}

#sample-modal-contents {
  height: 90%;
  width: 55%;
  background-color: white;
  position: relative;
}

#sample-modal-schedule-content {
  height: 80%;
}

#sample-modal-footer {
  display: flex;
  justify-content: center;
  position: absolute;
  bottom: 0;
  margin: 10px;
  width: 100%;
}

#sample-modal-close {
  cursor: pointer;
  width: 10em;
  height: 3em;
}

#sample-names {
  margin-top: 10px;
  white-space: nowrap;
  overflow: hidden;
}

.sample-name {
  color: #2d2d2d;
  padding: 3px 10px;
  margin: 10px;
  display: inline-block;
}

#schedule-window {
  width: 10em;
  height: 2em;
}

/* sweet alert のボタンデザイン修正 */
.swal2-confirm.swal2-styled,
.swal2-cancel.swal2-styled {
  padding: 0;
  width: 90px;
  height: 35px;
}

おわりに

この記事では、Garoon スケジュール上で、予定の参加者の Outlook 予定表に登録された予定を確認したり、登録・変更・削除した予定を同期するカスタマイズを紹介しました。
他にも、 Garoon と Office365 などの外部サービスと連携したカスタマイズ があるので、ぜひご参考ください。

サンプルコードで使用している API

このカスタマイズでは、次の API を利用しています。
お使いの Garoon で使用できる API かどうかは、各 API のドキュメントを参照してください。

このカスタマイズは、サイボウズ オフィシャル SI パートナー クロス・ヘッド株式会社による有償サポートの対象カスタマイズです。
詳細は サイボウズ製品 API 開発サポート (External link) を参照してください。

変更履歴

  • 2021 年 8 月 19 日 v1.1
    • スケジュールの付加情報の保存先を、カスタム項目(additionalItems)からカスタム項目(Schedule datastore)に変更しました。