Edits history of script submission #17717 for ' Create a Time-Off (personio)'

  • bun
    One script reply has been approved by the moderators
    Ap­pro­ved
    //native
    type Personio = {
    	clientId: string
    	clientSecret: string
    }
    /**
     * Create a Time-Off
     * Adds absence data for absence types with **time unit** set to **days**.
     */
    export async function main(
    	auth: Personio,
    	body: {
    		employee_id: number
    		time_off_type_id: number
    		start_date: string
    		end_date: string
    		half_day_start: false | true
    		half_day_end: false | true
    		comment?: string
    		skip_approval?: false | true
    	},
    	X_Personio_Partner_ID?: string,
    	X_Personio_App_ID?: string
    ) {
    	const url = new URL(`https://api.personio.de/v1/company/time-offs`)
    
    	const response = await fetch(url, {
    		method: 'POST',
    		headers: {
    			...(X_Personio_Partner_ID ? { 'X-Personio-Partner-ID': X_Personio_Partner_ID } : {}),
    			...(X_Personio_App_ID ? { 'X-Personio-App-ID': X_Personio_App_ID } : {}),
    			'Content-Type': 'application/x-www-form-urlencoded',
    			Authorization: 'Bearer ' + (await getOAuthToken(auth, 'https://api.personio.de/oauth2/token'))
    		},
    		body: new URLSearchParams(
    			Object.entries(body).reduce((acc, [key, value]) => {
    				acc[key] = String(value)
    				return acc
    			}, {} as Record<string, string>)
    		)
    	})
    	if (!response.ok) {
    		const text = await response.text()
    		throw new Error(`${response.status} ${text}`)
    	}
    	return await response.json()
    }
    
    async function getOAuthToken(auth: Personio, tokenUrl: string): Promise<string> {
    	const params = new URLSearchParams({
    		grant_type: 'client_credentials',
    		client_id: auth.clientId,
    		client_secret: auth.clientSecret
    	})
    
    	const response = await fetch(tokenUrl, {
    		method: 'POST',
    		headers: {
    			Authorization: 'Basic ' + btoa(`${auth.clientId}:${auth.clientSecret}`),
    			'Content-Type': 'application/x-www-form-urlencoded'
    		},
    		body: params.toString()
    	})
    
    	if (!response.ok) {
    		const text = await response.text()
    		throw new Error(`OAuth token request failed: ${response.status} ${text}`)
    	}
    
    	const data = await response.json()
    	return data.access_token
    }
    

    Submitted by hugo697 235 days ago