1 | |
2 | type Personio = { |
3 | clientId: string |
4 | clientSecret: string |
5 | } |
6 | |
7 | * Create an Attendance |
8 | * This endpoint is responsible for adding attendance data for the company employees. It is possible to add attendances for one or many employees at the same time. The payload sent on the request should be a list of attendance periods, in the form of an array containing attendance period objects. |
9 | */ |
10 | export async function main( |
11 | auth: Personio, |
12 | body: { |
13 | attendances?: { |
14 | employee: number |
15 | date: string |
16 | start_time: string |
17 | end_time?: string |
18 | break: number |
19 | comment?: string |
20 | project_id?: number |
21 | }[] |
22 | skip_approval?: false | true |
23 | }, |
24 | X_Personio_Partner_ID?: string, |
25 | X_Personio_App_ID?: string |
26 | ) { |
27 | const url = new URL(`https://api.personio.de/v1/company/attendances`) |
28 |
|
29 | const response = await fetch(url, { |
30 | method: 'POST', |
31 | headers: { |
32 | ...(X_Personio_Partner_ID ? { 'X-Personio-Partner-ID': X_Personio_Partner_ID } : {}), |
33 | ...(X_Personio_App_ID ? { 'X-Personio-App-ID': X_Personio_App_ID } : {}), |
34 | 'Content-Type': 'application/json', |
35 | Authorization: 'Bearer ' + (await getOAuthToken(auth, 'https://api.personio.de/oauth2/token')) |
36 | }, |
37 | body: JSON.stringify(body) |
38 | }) |
39 | if (!response.ok) { |
40 | const text = await response.text() |
41 | throw new Error(`${response.status} ${text}`) |
42 | } |
43 | return await response.json() |
44 | } |
45 |
|
46 | async function getOAuthToken(auth: Personio, tokenUrl: string): Promise<string> { |
47 | const params = new URLSearchParams({ |
48 | grant_type: 'client_credentials', |
49 | client_id: auth.clientId, |
50 | client_secret: auth.clientSecret |
51 | }) |
52 |
|
53 | const response = await fetch(tokenUrl, { |
54 | method: 'POST', |
55 | headers: { |
56 | Authorization: 'Basic ' + btoa(`${auth.clientId}:${auth.clientSecret}`), |
57 | 'Content-Type': 'application/x-www-form-urlencoded' |
58 | }, |
59 | body: params.toString() |
60 | }) |
61 |
|
62 | if (!response.ok) { |
63 | const text = await response.text() |
64 | throw new Error(`OAuth token request failed: ${response.status} ${text}`) |
65 | } |
66 |
|
67 | const data = await response.json() |
68 | return data.access_token |
69 | } |
70 |
|