1 | |
2 | type Personio = { |
3 | clientId: string |
4 | clientSecret: string |
5 | } |
6 | |
7 | * Update Employee by ID |
8 | * Updates an existing employee. Note: Only the fields that are listed in the body example are updatable. Attributes that are not part of the sample request body but are present inside the request are ignored. It's not possible to update the Email field. |
9 |
|
10 | */ |
11 | export async function main( |
12 | auth: Personio, |
13 | employee_id: string, |
14 | body: { |
15 | employee?: { |
16 | first_name?: string |
17 | last_name?: string |
18 | preferred_name?: string |
19 | gender?: string |
20 | position?: string |
21 | subcompany?: string |
22 | department?: string |
23 | office?: string |
24 | hire_date?: string |
25 | weekly_working_hours?: number |
26 | status?: string |
27 | supervisor_id?: number |
28 | custom_attributes?: { 'dynamic_{{ field uid }}'?: string } |
29 | } |
30 | }, |
31 | X_Personio_Partner_ID?: string, |
32 | X_Personio_App_ID?: string |
33 | ) { |
34 | const url = new URL(`https://api.personio.de/v1/company/employees/${employee_id}`) |
35 |
|
36 | const response = await fetch(url, { |
37 | method: 'PATCH', |
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 | 'Content-Type': 'application/json', |
42 | Authorization: 'Bearer ' + (await getOAuthToken(auth, 'https://api.personio.de/oauth2/token')) |
43 | }, |
44 | body: JSON.stringify(body) |
45 | }) |
46 | if (!response.ok) { |
47 | const text = await response.text() |
48 | throw new Error(`${response.status} ${text}`) |
49 | } |
50 | return await response.json() |
51 | } |
52 |
|
53 | async function getOAuthToken(auth: Personio, tokenUrl: string): Promise<string> { |
54 | const params = new URLSearchParams({ |
55 | grant_type: 'client_credentials', |
56 | client_id: auth.clientId, |
57 | client_secret: auth.clientSecret |
58 | }) |
59 |
|
60 | const response = await fetch(tokenUrl, { |
61 | method: 'POST', |
62 | headers: { |
63 | Authorization: 'Basic ' + btoa(`${auth.clientId}:${auth.clientSecret}`), |
64 | 'Content-Type': 'application/x-www-form-urlencoded' |
65 | }, |
66 | body: params.toString() |
67 | }) |
68 |
|
69 | if (!response.ok) { |
70 | const text = await response.text() |
71 | throw new Error(`OAuth token request failed: ${response.status} ${text}`) |
72 | } |
73 |
|
74 | const data = await response.json() |
75 | return data.access_token |
76 | } |
77 |
|