All files / src/routes/onboarding +page.server.ts

100% Statements 26/26
100% Branches 14/14
100% Functions 3/3
100% Lines 25/25

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73      1x                 1x   1x 4x   4x 1x     3x       2x       1x   9x 9x 1x     8x     8x 8x       2x       6x 6x 36x   31x     6x                 6x 1x 1x     5x      
import { redirect, fail } from '@sveltejs/kit';
import type { PageServerLoad, Actions } from './$types';
 
const PARQ_FIELDS = [
	'has_heart_condition',
	'has_chest_pain',
	'has_dizziness',
	'has_bone_joint_problem',
	'has_blood_pressure_medication',
	'other_physical_reason',
] as const;
 
const VALID_EXPERIENCE_LEVELS = ['beginner', 'intermediate', 'advanced'] as const;
 
export const load: PageServerLoad = async ({ parent }) => {
	const { athlete } = await parent();
 
	if (athlete?.onboarding_status === 'parq_complete') {
		redirect(303, '/onboarding/assessment');
	}
 
	if (
		athlete?.onboarding_status === 'assessed' ||
		athlete?.onboarding_status === 'full'
	) {
		redirect(303, '/dashboard');
	}
};
 
export const actions: Actions = {
	default: async ({ request, locals: { supabase, safeGetSession } }) => {
		const { user } = await safeGetSession();
		if (!user) {
			redirect(303, '/login');
		}
 
		const formData = await request.formData();
 
		// Parse experience level
		const experienceLevel = formData.get('experience_level');
		if (
			typeof experienceLevel !== 'string' ||
			!VALID_EXPERIENCE_LEVELS.includes(experienceLevel as (typeof VALID_EXPERIENCE_LEVELS)[number])
		) {
			return fail(400, { error: 'Please select an experience level.' });
		}
 
		// Parse PARQ responses
		const parq: Record<string, boolean> = {};
		for (const field of PARQ_FIELDS) {
			parq[field] = formData.get(field) === 'true';
		}
		parq.physician_clearance_needed = PARQ_FIELDS.some((f) => parq[f]);
 
		// Update athlete with PARQ data and transition onboarding status
		const { error } = await supabase
			.from('athletes')
			.update({
				parq,
				experience_level: experienceLevel as (typeof VALID_EXPERIENCE_LEVELS)[number],
				onboarding_status: 'parq_complete',
			})
			.eq('id', user.id);
 
		if (error) {
			console.error({ event: 'parq_submission_failed', message: error.message, code: error.code, details: error.details });
			return fail(500, { error: 'Failed to save. Please try again.' });
		}
 
		redirect(303, '/onboarding/assessment');
	},
};