forked from masuidrive/miyamoto
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmain.gs
1384 lines (1236 loc) · 59.9 KB
/
main.gs
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
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Miyamoto-san https://github.com/masuidrive/miyamoto/ */
/* (c) masuidrive 2014- License: MIT */
/* ------------------- */
// 日付関係の関数
// DateUtils = loadDateUtils();
loadDateUtils = function () {
var DateUtils = {};
// 今を返す
var _now = new Date();
var now = function(datetime) {
if(typeof datetime != 'undefined') {
_now = datetime;
}
return _now;
};
DateUtils.now = now;
// テキストから時間を抽出
DateUtils.parseTime = function(str) {
str = String(str || "").toLowerCase().replace(/[A-Za-z0-9]/g, function(s) {
return String.fromCharCode(s.charCodeAt(0) - 0xFEE0);
});
var reg = /((\d{1,2})\s*[:時]{1}\s*(\d{1,2})\s*(pm|)|(am|pm|午前|午後)\s*(\d{1,2})(\s*[:時]\s*(\d{1,2})|)|(\d{1,2})(\s*[:時]{1}\s*(\d{1,2})|)(am|pm)|(\d{1,2})\s*時)/;
var matches = str.match(reg);
if(matches) {
var hour, min;
// 1時20, 2:30, 3:00pm
if(matches[2] != null) {
hour = parseInt(matches[2], 10);
min = parseInt((matches[3] ? matches[3] : '0'), 10);
if(_.contains(['pm'], matches[4])) {
hour += 12;
}
}
// 午後1 午後2時30 pm3
if(matches[5] != null) {
hour = parseInt(matches[6], 10);
min = parseInt((matches[8] ? matches[8] : '0'), 10);
if(_.contains(['pm', '午後'], matches[5])) {
hour += 12;
}
}
// 1am 2:30pm
if(matches[9] != null) {
hour = parseInt(matches[9], 10);
min = parseInt((matches[11] ? matches[11] : '0'), 10);
if(_.contains(['pm'], matches[12])) {
hour += 12;
}
}
// 14時
if(matches[13] != null) {
hour = parseInt(matches[13], 10);
min = 0;
}
return [hour, min];
}
return null;
};
// テキストから休憩時間を抽出
DateUtils.parseMinutes = function(str) {
str = String(str || "").toLowerCase().replace(/[A-Za-z0-9]/g, function(s) {
return String.fromCharCode(s.charCodeAt(0) - 0xFEE0);
});
var reg = /(\d*.\d*\s*(分|minutes?|mins|時間|hour|hours))(\d*(分|minutes?|mins))?/;
var matches = str.match(reg);
if(matches) {
var hour = 0;
var min = 0;
// 最初のマッチ
if(matches[1] != null) {
if (['時間','hour','hours'].includes(matches[2])) {
// 1.5 時間
hour = parseFloat(matches[1], 10);
// 2回めのマッチ
if(matches[3] != null) {
min = parseInt(matches[3], 10);
}
} else {
// 60 分
min = parseInt(matches[1], 10);
}
}
return [hour * 60 + min];
}
return null;
};
// テキストから日付を抽出
DateUtils.parseDate = function(str) {
str = String(str || "").toLowerCase().replace(/[A-Za-z0-9]/g, function(s) {
return String.fromCharCode(s.charCodeAt(0) - 0xFEE0);
});
if(str.match(/(明日|tomorrow)/)) {
var tomorrow = new Date(now().getFullYear(), now().getMonth(), now().getDate()+1);
return [tomorrow.getFullYear(), tomorrow.getMonth()+1, tomorrow.getDate()]
}
if(str.match(/(今日|today)/)) {
return [now().getFullYear(), now().getMonth()+1, now().getDate()]
}
if(str.match(/(昨日|yesterday)/)) {
var yesterday = new Date(now().getFullYear(), now().getMonth(), now().getDate()-1);
return [yesterday.getFullYear(), yesterday.getMonth()+1, yesterday.getDate()]
}
var reg = /((\d{4})[-\/年]{1}|)(\d{1,2})[-\/月]{1}(\d{1,2})/;
var matches = str.match(reg);
if(matches) {
var year = parseInt(matches[2], 10);
var month = parseInt(matches[3], 10);
var day = parseInt(matches[4], 10);
if(_.isNaN(year) || year < 1970) {
//
if((now().getMonth() + 1) >= 11 && month <= 2) {
year = now().getFullYear() + 1;
}
else if((now().getMonth() + 1) <= 2 && month >= 11) {
year = now().getFullYear() - 1;
}
else {
year = now().getFullYear();
}
}
return [year, month, day];
}
return null;
};
// 日付と時間の配列から、Dateオブジェクトを生成
DateUtils.normalizeDateTime = function(date, time) {
// 時間だけの場合は日付を補完する
if(date) {
if(!time) date = null;
}
else {
date = [now().getFullYear(), now().getMonth()+1, now().getDate()];
if(!time) {
time = [now().getHours(), now().getMinutes()];
}
}
// 日付を指定したけど、時間を書いてない場合は扱わない
if(date && time) {
return(new Date(date[0], date[1]-1, date[2], time[0], time[1], 0));
}
else {
return null;
}
};
// 日時をいれてparseする
DateUtils.parseDateTime = function(str) {
var date = DateUtils.parseDate(str);
var time = DateUtils.parseTime(str);
if(!date) return null;
if(time) {
return(new Date(date[0], date[1]-1, date[2], time[0], time[1], 0));
}
else {
return(new Date(date[0], date[1]-1, date[2], 0, 0, 0));
}
};
// Dateから日付部分だけを取り出す
DateUtils.toDate = function(date) {
return(new Date(date.getFullYear(), date.getMonth(), date.getDate(), 0, 0, 0));
};
// 曜日を解析
DateUtils.parseWday = function(str) {
str = String(str).replace(/曜日/g, '');
var result = [];
var wdays = [/(sun|日)/i, /(mon|月)/i, /(tue|火)/i, /(wed|水)/i, /(thu|木)/i, /(fri|金)/i, /(sat|土)/i];
for(var i=0; i<wdays.length; ++i) {
if(str.match(wdays[i])) result.push(i);
}
return result;
}
var replaceChars = {
Y: function() { return this.getFullYear(); },
y: function() { return String(this.getFullYear()).substr(-2, 2); },
m: function() { return ("0"+(this.getMonth()+1)).substr(-2, 2); },
d: function() { return ("0"+(this.getDate())).substr(-2, 2); },
H: function() { return ("0"+(this.getHours())).substr(-2, 2); },
M: function() { return ("0"+(this.getMinutes())).substr(-2, 2); },
s: function() { return ("0"+(this.getSeconds())).substr(-2, 2); },
};
DateUtils.format = function(format, date) {
var result = '';
for (var i = 0; i < format.length; i++) {
var curChar = format.charAt(i);
if (replaceChars[curChar]) {
result += replaceChars[curChar].call(date);
}
else {
result += curChar;
}
}
return result;
};
return DateUtils;
};
if(typeof exports !== 'undefined') {
exports.DateUtils = loadDateUtils();
}
// 日付関係の関数
// EventListener = loadEventListener();
loadEventListener = function () {
var EventListener = function() {
this._events = {};
}
// イベントを捕捉
EventListener.prototype.on = function(eventName, func) {
if(this._events[eventName]) {
this._events[eventName].push(func);
}
else {
this._events[eventName] = [func];
}
};
// イベント発行
EventListener.prototype.fireEvent = function(eventName) {
var funcs = this._events[eventName];
if(funcs) {
for(var i = 0; i < funcs.length; ++i) {
funcs[i].apply(this, Array.prototype.slice.call(arguments, 1));
}
}
};
return EventListener;
};
if(typeof exports !== 'undefined') {
exports.EventListener = loadEventListener();
}
// KVS
// でも今回は使ってないです
loadGASProperties = function (exports) {
var GASProperties = function() {
this.properties = PropertiesService.getScriptProperties();
};
GASProperties.prototype.get = function(key) {
return this.properties.getProperty(key);
};
GASProperties.prototype.set = function(key, val) {
this.properties.setProperty(key, val);
return val;
};
return GASProperties;
};
if(typeof exports !== 'undefined') {
exports.GASProperties = loadGASProperties();
}
// Google Apps Script専用ユーティリティ
// GASのログ出力をブラウザ互換にする
if(typeof(console) == 'undefined' && typeof(Logger) != 'undefined') {
console = {};
console.log = function() {
Logger.log(Array.prototype.slice.call(arguments).join(', '));
}
}
// サーバに新しいバージョンが無いかチェックする
checkUpdate = function(responder) {
if(typeof GASProperties === 'undefined') GASProperties = loadGASProperties();
var current_version = parseFloat(new GASProperties().get('version')) || 0;
var response = UrlFetchApp.fetch("https://raw.githubusercontent.com/georepublic/miyamoto/master/VERSION", {muteHttpExceptions: true});
if(response.getResponseCode() == 200) {
var latest_version = parseFloat(response.getContentText());
if(latest_version > 0 && latest_version > current_version) {
responder.send("Timesheet Script was updated. \nhttps://github.com/georepublic/miyamoto/blob/master/UPDATE.md を読んでください。");
var response = UrlFetchApp.fetch("https://raw.githubusercontent.com/georepublic/miyamoto/master/HISTORY.md", {muteHttpExceptions: true});
if(response.getResponseCode() == 200) {
var text = String(response.getContentText()).replace(new RegExp("## "+current_version+"[\\s\\S]*", "m"), '');
responder.send(text);
}
}
}
};
// KVS
loadGSBigQuery = function (exports) {
var GSBigQuery = function (spreadsheet, prop) {
// initialize
this.spreadsheet = spreadsheet;
this.projectID = prop.projectID;
this.datasetID = prop.datasetID;
};
/**
* push timesheet data to bigqurey table
*/
GSBigQuery.prototype.pushTables = function () {
console.log('push to bigquery ');
_this = this;
// push all sheets
_.map(this.spreadsheet.getSheets(), function (s) {
var name = s.getName();
if (String(name).substr(0, 1) != '_') {
_this.pushTable(s);
}
})
};
/**
*
* @param sheet a sheet of Spreadsheet
*/
GSBigQuery.prototype.pushTable = function (sheet) {
var tableID = sheet.getName().replace(".", "_");
// table schema
var table = {
tableReference: {
projectId: this.projectID,
datasetId: this.datasetID,
tableId: tableID
},
schema: {
fields: [{
name: 'work_date',
type: 'date'
},
{
name: 'start_working',
type: 'datetime'
},
{
name: 'end_working',
type: 'datetime'
},
{
name: 'break_time',
type: 'integer'
},
{
name: 'note',
type: 'string'
},
{
name: 'work_minutes',
type: 'integer'
},
{
name: 'holiday',
type: 'boolean'
},
]
}
};
// remove table first
try {
BigQuery.Tables.remove(this.projectID, this.datasetID, tableID);
} catch (e) {}
table = BigQuery.Tables.insert(table, this.projectID, this.datasetID);
// load data as CSV format
var range = sheet.getDataRange();
var blob = Utilities.newBlob(this.convCsv(range)).setContentType('application/octet-stream');
// create job
var job = {
configuration: {
load: {
destinationTable: {
projectId: this.projectID,
datasetId: this.datasetID,
tableId: tableID
}
}
}
};
console.log('load data');
// insert data
job = BigQuery.Jobs.insert(job, this.projectID, blob);
};
GSBigQuery.prototype.convCsv = function (range) {
try {
var data = range.getValues();
var csv = "";
// read every rows
for (var i = 0; i < data.length; i++) {
for (var j = 0; j < data[i].length; j++) {
if (data[i][j].toString().indexOf(",") != -1) {
data[i][j] = "\"" + data[i][j] + "\"";
}
}
// if both of start and end time is set, load data
if (Object.prototype.toString.call(data[i][0]) == "[object Date]" &&
Object.prototype.toString.call(data[i][1]) == "[object Date]" &&
Object.prototype.toString.call(data[i][2]) == "[object Date]"
) {
var daycheck = data[i][0];
// format work_date and start/end time
data[i][0] = Utilities.formatDate(data[i][0], "JST", "yyyy-MM-dd");
// start/end time. use same date as working time for fixing data
data[i][1] = data[i][0] + Utilities.formatDate(data[i][1], "JST", " HH:mm:ss");
daycheck.setDate(daycheck.getDate() + 1);
// if the end_date is the next day of the working day, it will be an overnight work.
if (Utilities.formatDate(daycheck, "JST", "yyyy-MM-dd") ==
Utilities.formatDate(data[i][2], "JST", "yyyy-MM-dd")) {
data[i][2] = Utilities.formatDate(data[i][2], "JST", "yyyy-MM-dd HH:mm:ss");
} else {
data[i][2] = data[i][0] + Utilities.formatDate(data[i][2], "JST", " HH:mm:ss");
}
// if no breaks, it makes 0 mins
if (!data[i][3]) {
data[i][3] = 0;
}
// calculate working minutes
data[i][5] = ((new Date(data[i][2]) - new Date(data[i][1])) / (60 * 1000)) - data[i][3];
// not holiday
data[i][6] = false;
while (data[i].length > 7) {
data[i].pop();
}
csv += data[i].join(",") + "\r\n";
} else if (Object.prototype.toString.call(data[i][0]) == "[object Date]" &&
data[i][1] == '-' &&
data[i][2] == '-') {
// log holidays
// format work_date
data[i][0] = Utilities.formatDate(data[i][0], "JST", "yyyy-MM-dd");
data[i][1] = null;
data[i][2] = null;
data[i][3] = 0;
data[i][5] = 0;
// holiday
data[i][6] = true;
while (data[i].length > 7) {
data[i].pop();
}
csv += data[i].join(",") + "\r\n";
}
}
return csv;
} catch (e) {
Logger.log(e);
}
};
/**
*
* @param sheet a sheet of Spreadsheet
*/
GSBigQuery.prototype.pushWorkDays = function () {
var tableID = "workdays";
// table schema
var table = {
tableReference: {
projectId: this.projectID,
datasetId: this.datasetID,
tableId: tableID
},
schema: {
fields: [{
name: 'work_month',
type: 'string'
},
{
name: 'work_days',
type: 'integer'
}
]
}
};
// remove table first
try {
BigQuery.Tables.remove(this.projectID, this.datasetID, tableID);
} catch (e) {}
table = BigQuery.Tables.insert(table, this.projectID, this.datasetID);
// load data as CSV format
var sheet = this.spreadsheet.getSheetByName('_勤務日数');
var range = sheet.getDataRange();
var blob = Utilities.newBlob(this.convWorkDayCsv(range)).setContentType('application/octet-stream');
// create job
var job = {
configuration: {
load: {
destinationTable: {
projectId: this.projectID,
datasetId: this.datasetID,
tableId: tableID
}
}
}
};
console.log('load data');
// insert data
job = BigQuery.Jobs.insert(job, this.projectID, blob);
};
GSBigQuery.prototype.convWorkDayCsv = function (range) {
try {
var data = range.getValues();
var csv = "";
// read every rows
for (var i = 0; i < data.length; i++) {
data[i][0] = Utilities.formatDate(data[i][0], "JST", "yyyy-MM");
csv += data[i].join(",") + "\r\n";
}
return csv;
} catch (e) {
Logger.log(e);
}
};
return GSBigQuery;
};
if (typeof exports !== 'undefined') {
exports.GSBigQuery = loadGSBigQuery();
}// カレンダーテンプレート
// GSCalendar = loadGSCalendar();
loadGSCalendar = function () {
var GSCalendar = function (spreadsheet, settings) {
this.spreadsheet = spreadsheet;
this.settings = settings;
// メッセージテンプレート設定
this.sheet = this.spreadsheet.getSheetByName('_勤務日数');
if (!this.sheet) {
this.sheet = this.spreadsheet.insertSheet('_勤務日数');
if (!this.sheet) {
throw "エラー: メッセージシートを作れませんでした";
}
}
};
GSCalendar.prototype.setupCalendar = function () {
var settings = this.settings;
var startDate = this.getStartDate();
// 休日を設定 (iCal)
var calendarId = 'ja.japanese#[email protected]';
var calendar = CalendarApp.getCalendarById(calendarId);
var endDate = new Date(startDate.getFullYear() + 1, startDate.getMonth());
var holidays = _.map(calendar.getEvents(startDate, endDate), function (ev) {
return DateUtils.format("Y-m-d", ev.getAllDayStartDate());
});
settings.set('休日', holidays.join(', '));
settings.setNote('休日', '日付を,区切りで。来年までは自動設定されているので、以後は再度 updateCalendar() を実行してください。');
endDate.setDate(endDate.getDate() - 1);
settings.set('最終日', DateUtils.format("Y-m-d", endDate))
settings.setNote('最終日', '年度の最終日。この日以降はエラーが出ます。');
if (!settings.get('追加休日')) {
settings.set('追加休日', [
startDate.getFullYear() + '-12-29',
startDate.getFullYear() + '-12-30',
startDate.getFullYear() + '-12-31',
(startDate.getFullYear() + 1) + '-01-01',
(startDate.getFullYear() + 1) + '-01-02',
(startDate.getFullYear() + 1) + '-01-03'
].join(', '))
}
settings.setNote('追加休日', '追加の休日です。年末年始などをカンマ区切りで入力してください。変更したら、再度 updateCalendar() を実行してください。');
this.updateWorkdays();
};
/** setup Calendars */
GSCalendar.prototype.updateWorkdays = function () {
this.spreadsheet.deleteSheet(this.sheet);
this.sheet = this.spreadsheet.insertSheet('_勤務日数');
var startDate = this.getStartDate();
var endDate = new Date(startDate.getFullYear() + 1, startDate.getMonth());
var holidays = this.settings.get('休日') + "," + this.settings.get('追加休日');
var workDays = 0;
var values = [];
while (startDate < endDate) {
if (startDate.getDay() == 0 || startDate.getDay() == 6 || holidays.indexOf(DateUtils.format("Y-m-d", startDate)) > -1) {
// holiday
} else {
workDays += 1;
}
var currentMonth = startDate.getMonth();
var ym = DateUtils.format("Y-m", startDate)
startDate.setDate(startDate.getDate() + 1);
if (startDate.getMonth() != currentMonth) {
values.push([ym, workDays]);
workDays = 0;
}
}
this.sheet.getRange(1, 1, values.length, 2).setValues(values);
};
/** getStartDate */
GSCalendar.prototype.getStartDate = function () {
var startMonth = Number(this.settings.get('開始月'));
if (!startMonth) {
startMonth = 4;
}
var startDate = new Date(DateUtils.now().getFullYear(), (startMonth - 1));
// use last year if the referencing date is future date
if (startDate > new Date()) {
startDate = new Date(DateUtils.now().getFullYear() - 1, (startMonth - 1));
}
return startDate;
}
return GSCalendar;
};
if (typeof exports !== 'undefined') {
exports.GSCalendar = loadGSCalendar();
}// KVS
loadGSProperties = function (exports) {
var GSProperties = function(spreadsheet) {
// 初期設定
this.sheet = spreadsheet.getSheetByName('_設定');
if(!this.sheet) {
this.sheet = spreadsheet.insertSheet('_設定');
}
};
GSProperties.prototype.get = function(key) {
if(this.sheet.getLastRow() < 1) return defaultValue;
var vals = _.find(this.sheet.getRange("A1:B"+this.sheet.getLastRow()).getValues(), function(v) {
return(v[0] == key);
});
if(vals) {
if(_.isDate(vals[1])) {
return DateUtils.format("Y-m-d H:M:s", vals[1]);
}
else {
return String(vals[1]);
}
}
else {
return null;
}
};
GSProperties.prototype.set = function(key, val) {
if(this.sheet.getLastRow() > 0) {
var vals = this.sheet.getRange("A1:A"+this.sheet.getLastRow()).getValues();
for(var i = 0; i < this.sheet.getLastRow(); ++i) {
if(vals[i][0] == key) {
this.sheet.getRange("B"+(i+1)).setValue(String(val));
return val;
}
}
}
this.sheet.getRange("A"+(this.sheet.getLastRow()+1)+":B"+(this.sheet.getLastRow()+1)).setValues([[key, val]]);
return val;
};
GSProperties.prototype.setNote = function(key, note) {
if(this.sheet.getLastRow() > 0) {
var vals = this.sheet.getRange("A1:A"+this.sheet.getLastRow()).getValues();
for(var i = 0; i < this.sheet.getLastRow(); ++i) {
if(vals[i][0] == key) {
this.sheet.getRange("D"+(i+1)).setValue(note);
return;
}
}
}
this.sheet.getRange("A"+(this.sheet.getLastRow()+1)+":D"+(this.sheet.getLastRow()+1)).setValues([[key, '', note]]);
return;
};
return GSProperties;
};
if(typeof exports !== 'undefined') {
exports.GSProperties = loadGSProperties();
}
// メッセージテンプレート
// GSTemplate = loadGSTemplate();
loadGSTemplate = function () {
var GSTemplate = function (spreadsheet) {
this.spreadsheet = spreadsheet;
// メッセージテンプレート設定
this.sheet = this.spreadsheet.getSheetByName('_メッセージ');
if (!this.sheet) {
this.sheet = this.spreadsheet.insertSheet('_メッセージ');
if (!this.sheet) {
throw "エラー: メッセージシートを作れませんでした";
} else {
var now = DateUtils.now();
this.sheet.getRange("A1:P2").setValues([
[
"出勤", "出勤更新", "退勤", "退勤更新", "休憩", "休暇", "休暇取消",
"出勤中", "出勤なし", "休暇中", "休暇なし", "出勤確認", "退勤確認",
"休憩エラー", "退勤と休憩", "退勤更新と休憩"
],
[
"<@#1> Good morning (#2)!", "<@#1> I changed starting time to #2",
"<@#1> Great work! (#2)", "<@#1> I changed leaving time to #2",
"<@#1> I changed break time to #2",
"<@#1> I registered a holiday for #2", "<@#1> I canceled holiday #2",
"#1 is working", "All staffs are working",
"#2 is having a holiday at #1", "No one is having a holiday at #1",
"Is today holiday? #1", "Did you finish working today? #1",
"[Error] You have not started working today!",
"<@#1> Great work! I added 60 mins break for you (#2)",
"<@#1> I changed leaving time to #2 and added 6 mins break for you"
]
]);
}
}
};
// テンプレートからメッセージを生成
GSTemplate.prototype.template = function (label) {
var labels = this.sheet.getRange("A1:Z1").getValues()[0];
for (var i = 0; i < labels.length; ++i) {
if (labels[i] == label) {
var template = _.sample(
_.filter(
_.map(this.sheet.getRange(String.fromCharCode(i + 65) + '2:' + (String.fromCharCode(i + 65))).getValues(), function (v) {
return v[0];
}),
function (v) {
return !!v;
}
)
);
var message = template;
for (var i = 1; i < arguments.length; i++) {
var arg = arguments[i]
if (_.isArray(arg)) {
arg = _.map(arg, function (u) {
return "<@" + u + ">";
}).join(', ');
}
message = message.replace("#" + i, arg);
}
return message;
}
}
return arguments.join(', ');
}
return GSTemplate;
};
if (typeof exports !== 'undefined') {
exports.GSTemplate = loadGSTemplate();
}// 入力内容を解析して、メソッドを呼び出す
// Timesheets = loadTimesheets();
loadGSTimesheets = function () {
var GSTimesheets = function(spreadsheet, settings) {
this.spreadsheet = spreadsheet;
this.settings = settings;
this._sheets = {};
this.scheme = {
columns: [
{ name: '日付' },
{ name: '出勤' },
{ name: '退勤' },
{ name: '休憩(分)' },
{ name: 'ノート' },
],
properties: [
{ name: 'DayOff', value: '土,日', comment: '← 月,火,水みたいに入力してください。アカウント停止のためには「全部」と入れてください。'},
]
};
};
GSTimesheets.prototype._getSheet = function(username) {
if(this._sheets[username]) return this._sheets[username];
var sheet = this.spreadsheet.getSheetByName(username);
if(!sheet) {
sheet = this.spreadsheet.insertSheet(username);
if(!sheet) {
throw "エラー: "+sheetName+"のシートが作れませんでした";
}
else {
// 中身が無い場合は新規作成
if(sheet.getLastRow() == 0) {
// 設定部の書き出し
var properties = [["Properties count", this.scheme.properties.length, null]];
this.scheme.properties.forEach(function(s) {
properties.push([s.name, s.value, s.comment]);
});
sheet.getRange("A1:C"+(properties.length)).setValues(properties);
// ヘッダの書き出し
var rowNo = properties.length + 2;
var cols = this.scheme.columns.map(function(c) { return c.name; });
sheet.getRange("A"+rowNo+":"+String.fromCharCode(65 + cols.length - 1)+rowNo).setValues([cols]);
}
//this.on("newUser", username);
}
}
this._sheets[username] = sheet;
return sheet;
};
GSTimesheets.prototype._getRowNo = function(username, date) {
if(!date) date = DateUtils.now();
var rowNo = this.scheme.properties.length + 4;
var startAt = DateUtils.parseDate(this.settings.get("開始日"));
var s = new Date(startAt[0], startAt[1]-1, startAt[2], 0, 0, 0);
rowNo += parseInt((date.getTime()-date.getTimezoneOffset()*60*1000)/(1000*24*60*60), 10) - parseInt((s.getTime()-s.getTimezoneOffset()*60*1000)/(1000*24*60*60), 10);
return rowNo;
};
GSTimesheets.prototype.get = function(username, date) {
var sheet = this._getSheet(username);
var rowNo = this._getRowNo(username, date);
var row = sheet.getRange("A"+rowNo+":"+String.fromCharCode(65 + this.scheme.columns.length - 1)+rowNo).getValues()[0].map(function(v) {
return v === '' ? undefined : v;
});
return({ user: username, date: row[0], signIn: row[1], signOut: row[2], break: row[3], note: row[4] });
};
GSTimesheets.prototype.set = function(username, date, params) {
var row = this.get(username, date);
_.extend(row, _.pick(params, 'signIn', 'signOut', 'break', 'note'));
var sheet = this._getSheet(username);
var rowNo = this._getRowNo(username, date);
var data = [DateUtils.toDate(date), row.signIn, row.signOut, row.break, row.note].map(function(v) {
return v == null ? '' : v;
});
sheet.getRange("A"+rowNo+":"+String.fromCharCode(65 + this.scheme.columns.length - 1)+rowNo).setValues([data]);
sheet.getRange("B"+rowNo+":C"+rowNo).setNumberFormat('hh:mm')
return row;
};
GSTimesheets.prototype.getUsers = function() {
return _.compact(_.map(this.spreadsheet.getSheets(), function(s) {
var name = s.getName();
return String(name).substr(0, 1) == '_' ? undefined : name;
}));
};
GSTimesheets.prototype.getByDate = function(date) {
var self = this;
return _.map(this.getUsers(), function(username) {
return self.get(username, date);
});
};
// 休みの曜日を数字で返す
GSTimesheets.prototype.getDayOff = function(username) {
var sheet = this._getSheet(username);
return DateUtils.parseWday(sheet.getRange("B2").getValue());
};
return GSTimesheets;
};
if(typeof exports !== 'undefined') {
exports.GSTimesheets = loadGSTimesheets();
}
// 各モジュールの読み込み
var initLibraries = function () {
if (typeof EventListener === 'undefined') EventListener = loadEventListener();
if (typeof DateUtils === 'undefined') DateUtils = loadDateUtils();
if (typeof GASProperties === 'undefined') GASProperties = loadGASProperties();
if (typeof GSProperties === 'undefined') GSProperties = loadGSProperties();
if (typeof GSTemplate === 'undefined') GSTemplate = loadGSTemplate();
if (typeof GSTimesheets === 'undefined') GSTimesheets = loadGSTimesheets();
if (typeof Timesheets === 'undefined') Timesheets = loadTimesheets();
if (typeof Slack === 'undefined') Slack = loadSlack();
if (typeof GSBigQuery === 'undefined') GSBigQuery = loadGSBigQuery();
if (typeof GSCalendar === 'undefined') GSCalendar = loadGSCalendar();
};
var init = function () {
initLibraries();
var global_settings = new GASProperties();
var spreadsheetId = global_settings.get('spreadsheet');
if (spreadsheetId) {
var spreadsheet = SpreadsheetApp.openById(spreadsheetId);
var settings = new GSProperties(spreadsheet);
var template = new GSTemplate(spreadsheet);
var slack = new Slack(settings.get('Slack Incoming URL'), template, settings);
var storage = new GSTimesheets(spreadsheet, settings);
var timesheets = new Timesheets(storage, settings, slack);
var bigquery = null;
if (global_settings.get('bigQueryProjectID') && global_settings.get('bigQueryDatasetID')) {
bigquery = new GSBigQuery(spreadsheet, {
projectID: global_settings.get('bigQueryProjectID'),
datasetID: global_settings.get('bigQueryDatasetID')
});
}
return ({
receiver: slack,
timesheets: timesheets,
storage: storage,
bigquery: bigquery
});
}
return null;
}
// SlackのOutgoingから来るメッセージ
function doPost(e) {
if (e.parameters.user_name == undefined) { // data is undefined (Slack Event)
var postJSON = JSON.parse(e.postData.getDataAsString());
// verification Slack Event
if (postJSON.type == 'url_verification'){
var out = ContentService.createTextOutput();
//Mime TypeをJSONに設定
out.setMimeType(ContentService.MimeType.TEXT);
//JSONテキストをセットする
out.setContent(postJSON.challenge);
return out;
}else if (postJSON.event.subtype != 'bot_message') {
var miyamoto = init();
var userid = String(postJSON.event.user);
var body = String(postJSON.event.text);
var token = new GASProperties().get('SLACK_OAUTH_TOKEN');
var ret = UrlFetchApp.fetch('https://slack.com/api/users.info?token=' + token + '&user=' + userid);
var userdata = JSON.parse(ret);
miyamoto.receiver.receiveMessage(userdata.user.name, body);
}
}else{ // data is defined (Outgoing web hook)
var miyamoto = init();
var username = String(e.parameters.user_name);
var body = String(e.parameters['text']);
miyamoto.receiver.receiveMessage(username, body);
}
}
// Time-based triggerで実行
function confirmSignIn() {
var miyamoto = init();
miyamoto.timesheets.confirmSignIn();
}
// Time-based triggerで実行
function confirmSignOut() {
var miyamoto = init();
miyamoto.timesheets.confirmSignOut();
}
function pushToBigQuery() {
var miyamoto = init();
if (miyamoto.bigquery) {
miyamoto.bigquery.pushTables();
}
}
// 初期化する
function setUp() {
initLibraries();
// spreadsheetが無かったら初期化
var global_settings = new GASProperties();
if (!global_settings.get('spreadsheet')) {
// タイムシートを作る
var spreadsheet = SpreadsheetApp.create("Slack Timesheets");
var sheets = spreadsheet.getSheets();
if (sheets.length == 1 && sheets[0].getLastRow() == 0) {
sheets[0].setName('_設定');
}
global_settings.set('spreadsheet', spreadsheet.getId());
var settings = new GSProperties(spreadsheet);
settings.set('Slack Incoming URL', '');