0

Create an attendance period.

by
Published Oct 17, 2025

Create an attendance period and return newly created attendance period ID.

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
 * Create an attendance period.
8
 * Create an attendance period and return newly created attendance period ID.
9
 */
10
export async function main(
11
	auth: Personio,
12
	skip_approval: string | undefined,
13
	Beta: string,
14
	body: {
15
		person: { id: string }
16
		type: 'WORK' | 'BREAK'
17
		start: { date_time: string }
18
		end?: { date_time: string }
19
		comment?: string
20
		project?: { id: string }
21
	}
22
) {
23
	const url = new URL(`https://api.personio.de/v2/attendance-periods`)
24
	for (const [k, v] of [['skip_approval', skip_approval]]) {
25
		if (v !== undefined && v !== '' && k !== undefined) {
26
			url.searchParams.append(k, v)
27
		}
28
	}
29
	const response = await fetch(url, {
30
		method: 'POST',
31
		headers: {
32
			Beta: Beta,
33
			'Content-Type': 'application/json',
34
			Authorization: 'Bearer ' + (await getOAuthToken(auth, 'https://api.personio.de/oauth2/token'))
35
		},
36
		body: JSON.stringify(body)
37
	})
38
	if (!response.ok) {
39
		const text = await response.text()
40
		throw new Error(`${response.status} ${text}`)
41
	}
42
	return await response.json()
43
}
44

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

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

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

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