1 | |
2 | type Personio = { |
3 | clientId: string |
4 | clientSecret: string |
5 | } |
6 | |
7 | * List Time-Offs |
8 | * Fetches absence periods for absences with **time unit** set to **days**. The result can be `paginated` and `filtered` by period and/or specific employee/employees. The result contains a list of absence periods. |
9 | */ |
10 | export async function main( |
11 | auth: Personio, |
12 | start_date: string | undefined, |
13 | end_date: string | undefined, |
14 | updated_from: string | undefined, |
15 | updated_to: string | undefined, |
16 | employees__: string | undefined, |
17 | limit: string | undefined, |
18 | offset: string | undefined, |
19 | X_Personio_Partner_ID?: string, |
20 | X_Personio_App_ID?: string |
21 | ) { |
22 | const url = new URL(`https://api.personio.de/v1/company/time-offs`) |
23 | for (const [k, v] of [ |
24 | ['start_date', start_date], |
25 | ['end_date', end_date], |
26 | ['updated_from', updated_from], |
27 | ['updated_to', updated_to], |
28 | ['employees[]', employees__], |
29 | ['limit', limit], |
30 | ['offset', offset] |
31 | ]) { |
32 | if (v !== undefined && v !== '' && k !== undefined) { |
33 | url.searchParams.append(k, v) |
34 | } |
35 | } |
36 | const response = await fetch(url, { |
37 | method: 'GET', |
38 | headers: { |
39 | ...(X_Personio_Partner_ID ? { 'X-Personio-Partner-ID': X_Personio_Partner_ID } : {}), |
40 | ...(X_Personio_App_ID ? { 'X-Personio-App-ID': X_Personio_App_ID } : {}), |
41 | Authorization: 'Bearer ' + (await getOAuthToken(auth, 'https://api.personio.de/oauth2/token')) |
42 | }, |
43 | body: undefined |
44 | }) |
45 | if (!response.ok) { |
46 | const text = await response.text() |
47 | throw new Error(`${response.status} ${text}`) |
48 | } |
49 | return await response.json() |
50 | } |
51 |
|
52 | async function getOAuthToken(auth: Personio, tokenUrl: string): Promise<string> { |
53 | const params = new URLSearchParams({ |
54 | grant_type: 'client_credentials', |
55 | client_id: auth.clientId, |
56 | client_secret: auth.clientSecret |
57 | }) |
58 |
|
59 | const response = await fetch(tokenUrl, { |
60 | method: 'POST', |
61 | headers: { |
62 | Authorization: 'Basic ' + btoa(`${auth.clientId}:${auth.clientSecret}`), |
63 | 'Content-Type': 'application/x-www-form-urlencoded' |
64 | }, |
65 | body: params.toString() |
66 | }) |
67 |
|
68 | if (!response.ok) { |
69 | const text = await response.text() |
70 | throw new Error(`OAuth token request failed: ${response.status} ${text}`) |
71 | } |
72 |
|
73 | const data = await response.json() |
74 | return data.access_token |
75 | } |
76 |
|