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