0

Creates a new absence period.

by
Published Oct 17, 2025

Creates a new absence period.

Script personio Verified

The script

Submitted by hugo697 Bun
Verified 235 days ago
1
//native
2
type Personio = {
3
	clientId: string
4
	clientSecret: string
5
}
6
/**
7
 * Creates a new absence period.
8
 * Creates a new absence period.
9
 */
10
export async function main(
11
	auth: Personio,
12
	skip_approval: string | undefined,
13
	Beta: string,
14
	body: {
15
		person: { id: string }
16
		starts_from: { date_time: string; type?: 'FIRST_HALF' | 'SECOND_HALF' }
17
		ends_at?: { date_time: string; type?: 'FIRST_HALF' | 'SECOND_HALF' }
18
		comment?: string
19
		absence_type: { id: string }
20
	}
21
) {
22
	const url = new URL(`https://api.personio.de/v2/absence-periods`)
23
	for (const [k, v] of [['skip_approval', skip_approval]]) {
24
		if (v !== undefined && v !== '' && k !== undefined) {
25
			url.searchParams.append(k, v)
26
		}
27
	}
28
	const response = await fetch(url, {
29
		method: 'POST',
30
		headers: {
31
			Beta: Beta,
32
			'Content-Type': 'application/json',
33
			Authorization: 'Bearer ' + (await getOAuthToken(auth, 'https://api.personio.de/oauth2/token'))
34
		},
35
		body: JSON.stringify(body)
36
	})
37
	if (!response.ok) {
38
		const text = await response.text()
39
		throw new Error(`${response.status} ${text}`)
40
	}
41
	return await response.json()
42
}
43

44
async function getOAuthToken(auth: Personio, tokenUrl: string): Promise<string> {
45
	const params = new URLSearchParams({
46
		grant_type: 'client_credentials',
47
		client_id: auth.clientId,
48
		client_secret: auth.clientSecret
49
	})
50

51
	const response = await fetch(tokenUrl, {
52
		method: 'POST',
53
		headers: {
54
			Authorization: 'Basic ' + btoa(`${auth.clientId}:${auth.clientSecret}`),
55
			'Content-Type': 'application/x-www-form-urlencoded'
56
		},
57
		body: params.toString()
58
	})
59

60
	if (!response.ok) {
61
		const text = await response.text()
62
		throw new Error(`OAuth token request failed: ${response.status} ${text}`)
63
	}
64

65
	const data = await response.json()
66
	return data.access_token
67
}
68