1+ import prisma from '$lib/prisma' ;
2+ import { fail , redirect } from '@sveltejs/kit' ;
3+
4+ /** @type {import('./$types').PageServerLoad } */
5+ export async function load ( { locals } ) {
6+ if ( ! locals . user ) {
7+ throw redirect ( 307 , '/login' ) ;
8+ }
9+
10+ // Get user with their organization memberships
11+ const user = await prisma . user . findUnique ( {
12+ where : {
13+ id : locals . user . id
14+ } ,
15+ include : {
16+ organizations : {
17+ include : {
18+ organization : true
19+ }
20+ }
21+ }
22+ } ) ;
23+
24+ if ( ! user ) {
25+ throw redirect ( 307 , '/login' ) ;
26+ }
27+
28+ return {
29+ user : {
30+ id : user . id ,
31+ user_id : user . user_id ,
32+ email : user . email ,
33+ name : user . name ,
34+ profilePhoto : user . profilePhoto ,
35+ phone : user . phone ,
36+ isActive : user . isActive ,
37+ lastLogin : user . lastLogin ,
38+ createdAt : user . createdAt ,
39+ organizations : user . organizations
40+ }
41+ } ;
42+ }
43+
44+ /** @type {import('./$types').Actions } */
45+ export const actions = {
46+ updateProfile : async ( { request, locals } ) => {
47+ if ( ! locals . user ) {
48+ throw redirect ( 307 , '/login' ) ;
49+ }
50+
51+ const formData = await request . formData ( ) ;
52+ const name = formData . get ( 'name' ) ?. toString ( ) ;
53+ const phone = formData . get ( 'phone' ) ?. toString ( ) ;
54+
55+ // Validate required fields
56+ if ( ! name || name . trim ( ) . length === 0 ) {
57+ return fail ( 400 , {
58+ error : 'Name is required' ,
59+ data : { name, phone }
60+ } ) ;
61+ }
62+
63+ if ( name . trim ( ) . length < 2 ) {
64+ return fail ( 400 , {
65+ error : 'Name must be at least 2 characters long' ,
66+ data : { name, phone }
67+ } ) ;
68+ }
69+
70+ // Validate phone if provided
71+ if ( phone && phone . trim ( ) . length > 0 ) {
72+ const phoneRegex = / ^ [ \+ ] ? [ 1 - 9 ] [ \d ] { 0 , 15 } $ / ;
73+ if ( ! phoneRegex . test ( phone . replace ( / [ \s \- \( \) ] / g, '' ) ) ) {
74+ return fail ( 400 , {
75+ error : 'Please enter a valid phone number' ,
76+ data : { name, phone }
77+ } ) ;
78+ }
79+ }
80+
81+ try {
82+ await prisma . user . update ( {
83+ where : {
84+ id : locals . user . id
85+ } ,
86+ data : {
87+ name : name . trim ( ) ,
88+ phone : phone ?. trim ( ) || null ,
89+ updatedAt : new Date ( )
90+ }
91+ } ) ;
92+
93+ return {
94+ success : true ,
95+ message : 'Profile updated successfully'
96+ } ;
97+ } catch ( error ) {
98+ console . error ( 'Error updating profile:' , error ) ;
99+ return fail ( 500 , {
100+ error : 'Failed to update profile. Please try again.' ,
101+ data : { name, phone }
102+ } ) ;
103+ }
104+ }
105+ } ;
0 commit comments