-
Notifications
You must be signed in to change notification settings - Fork 0
/
freee_functions.gs
175 lines (153 loc) · 6.17 KB
/
freee_functions.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
////// freeeから情報の取得用メソッド
function getCompanies() {
try{
const accessToken = getOAuthService().getAccessToken();
const requestUrl = 'https://api.freee.co.jp/hr/api/v1/users/me';
const params = {
method : 'get',
headers : {'Authorization':'Bearer ' + accessToken},
};
const response = UrlFetchApp.fetch(requestUrl,params);
const companies = JSON.parse(response.getContentText()).companies;
console.log(companies);
}
catch (e) {
throw new Error('at getCompanies() in freee_functions.gs: ' + e.message);
}
}
function getUsers() {
try{
const accessToken = getOAuthService().getAccessToken();
const requestUrl = 'https://api.freee.co.jp/hr/api/v1/users/me';
const params = {
method : 'get',
headers : {'Authorization':'Bearer ' + accessToken},
};
const response = UrlFetchApp.fetch(requestUrl,params);
const companies = JSON.parse(response.getContentText()).companies;
console.log(companies);
}
catch (e) {
throw new Error('at getUsers() in freee_functions.gs: ' + e.message);
}
}
function getUserNameAndId(accessToken) {
try{
const requestUrl = 'https://api.freee.co.jp/hr/api/v1/users/me';
const params = {
method : 'get',
headers : {'Authorization':'Bearer ' + accessToken},
};
const response = UrlFetchApp.fetch(requestUrl, params);
const parsedResponse = JSON.parse(response.getContentText());
const companies = parsedResponse.companies;
const foundCompany = companies.find(function(company) {
return company.id == PropertiesService.getScriptProperties().getProperty("freeeCompanyId").toString();
});
if (!foundCompany) {
throw new Error('at function getUserNameAndId(accessToken) in freee_functions.gs. foundCompany is null. companies: ' + JSON.stringify(companies));
}
return {id: foundCompany.employee_id, name: foundCompany.display_name.split(' ')[0]};
}
catch (e) {
throw new Error('at getUserNameAndId() in freee_functions.gs: ' + e.message);
}
}
function getStampsForDateRange(from_date, to_date, userId, accessToken) {
try{
var timeZone = Session.getScriptTimeZone(); // スクリプトのタイムゾーンを取得
var urlParams = {
company_id: PropertiesService.getScriptProperties().getProperty("freeeCompanyId").toString(),
from_date: Utilities.formatDate(from_date, timeZone, 'yyyy-MM-dd',),
to_date: Utilities.formatDate(to_date, timeZone, 'yyyy-MM-dd'),
limit: 100,
offset: 0
};
const requestUrl = generateRequestUrl('https://api.freee.co.jp/hr/api/v1/employees/' + userId + '/time_clocks', urlParams);
const params = {
method : 'get',
headers : {'Authorization':'Bearer ' + accessToken},
};
const response = UrlFetchApp.fetch(requestUrl, params);
const parsedResponse = JSON.parse(response.getContentText());
const minutesToAdd = 3;
var stamps = [];
if (parsedResponse.length == 0) {
return stamps;
}
for (e of parsedResponse) {
switch (e.type) {
case 'clock_in':
stamps.push({startTime: new Date(e.datetime), endTime: null});
if (stamps.length > 1) {
if (stamps.slice(-2)[0].endTime === null) {
stamps.slice(-2)[0].endTime = new Date(stamps.slice(-1)[0].startTime.getTime() + (minutesToAdd * 60 * 1000));
}
}
break;
case 'break_begin':
if (stamps.length > 0 && stamps.slice(-1)[0].endTime === null) {
stamps.slice(-1)[0].endTime = new Date(e.datetime);
}
break;
case 'break_end':
stamps.push({startTime: new Date(e.datetime), endTime: null});
if (stamps.length > 1) {
if (stamps.slice(-2)[0].endTime === null) {
stamps.slice(-2)[0].endTime = new Date(stamps.slice(-1)[0].startTime.getTime() + (minutesToAdd * 60 * 1000));
}
}
break;
case 'clock_out':
if (stamps.length > 0 && stamps.slice(-1)[0].endTime === null) {
stamps.slice(-1)[0].endTime = new Date(e.datetime);
}
break;
}
}
if (stamps.slice(-1)[0].endTime === null) {
stamps.slice(-1)[0].endTime = new Date(stamps.slice(-1)[0].startTime.getTime() + (minutesToAdd * 60 * 1000));
}
return stamps;
}
catch (e) {
throw new Error('at getStampsForDateRange() in freee_functions.gs: ' + e.message);
}
}
function generateRequestUrl(baseUrl, params) {
return baseUrl + '?' + Object.keys(params).map(function(key) {
return encodeURIComponent(key) + '=' + encodeURIComponent(params[key]);
}).join('&');
}
////// OAuth認証用メソッド
// 認証機能の参考URL
// https://moripro.net/freee-gas-api/
//freeeAPIのサービスを取得
function getOAuthService() {
return OAuth2.createService('freee')
.setAuthorizationBaseUrl('https://accounts.secure.freee.co.jp/public_api/authorize')
.setTokenUrl('https://accounts.secure.freee.co.jp/public_api/token')
.setClientId(PropertiesService.getScriptProperties().getProperty("freeeClientId"))
.setClientSecret(PropertiesService.getScriptProperties().getProperty("freeeClientSecret"))
.setCallbackFunction('authCallback')
.setPropertyStore(PropertiesService.getUserProperties())
}
//認証コールバック関数
function authCallback(request) {
var service = getOAuthService();
var isAuthorized = service.handleCallback(request);
var html = HtmlService.createHtmlOutput();
html.append(htmlTemplate);
html.append('<script>');
html.append('document.getElementById("currentUser").innerText = "' + Session.getEffectiveUser().getEmail() + '";');
html.append('</script>');
if (isAuthorized) {
html.append('<h1 class="mt-4">認証が完了しました</h1>');
html.append('<p>freeeとの連携が完了しました。元のタブに戻ってページをリロードしてください。このタブは閉じてかまいません。</p>');
return html;
} else {
html.append('<h1 class="mt-4">認証に失敗しました</h1>');
html.append('<p>freeeとの連携に失敗しました。管理者に問い合わせてください。</p>');
return html;
}
}