First step of registration process

master
Rafael 2024-05-17 23:08:26 +02:00
parent bf20cbbd1f
commit 1cb7970982
6 changed files with 398 additions and 263 deletions

View File

@ -104,7 +104,7 @@ class MyDrawer extends StatelessWidget {
Navigator.push( Navigator.push(
context, context,
MaterialPageRoute( MaterialPageRoute(
builder: (context) => const UserDataPage(), builder: (context) => const UserDataPage(isRegProcess: false,),
)); ));
}, },
), ),

View File

@ -1,3 +1,10 @@
enum Gender {
none,
male,
female,
divers,
}
enum SkillOption { enum SkillOption {
product, product,
finance, finance,

View File

@ -3,6 +3,7 @@ import '../../helper.dart';
class ProfileCategoryForm<T> extends StatefulWidget { class ProfileCategoryForm<T> extends StatefulWidget {
final String title; final String title;
final String header;
final String description; final String description;
final List<T> options; // T to make it work with our different Enums final List<T> options; // T to make it work with our different Enums
final int minSelections; final int minSelections;
@ -15,6 +16,7 @@ class ProfileCategoryForm<T> extends StatefulWidget {
const ProfileCategoryForm({ const ProfileCategoryForm({
super.key, super.key,
required this.title, required this.title,
required this.header,
required this.description, required this.description,
required this.options, required this.options,
required this.minSelections, required this.minSelections,
@ -51,17 +53,15 @@ class ProfileCategoryFormState<T> extends State<ProfileCategoryForm<T>> {
crossAxisAlignment: CrossAxisAlignment.stretch, crossAxisAlignment: CrossAxisAlignment.stretch,
children: [ children: [
Text( Text(
'${widget.title}', widget.header,
style: const TextStyle( style: const TextStyle(
fontSize: 18.0, fontSize: 18.0,
fontWeight: FontWeight.bold, fontWeight: FontWeight.bold,
), ),
), ),
const SizedBox(height: 16,), const SizedBox(height: 16),
Text( Text(widget.description),
'${widget.description}', const SizedBox(height: 16),
),
const SizedBox(height: 16,),
Wrap( Wrap(
spacing: 8.0, spacing: 8.0,
children: List.generate(widget.options.length, (index) { children: List.generate(widget.options.length, (index) {

View File

@ -6,12 +6,17 @@ import '../../services/auth/auth_service.dart';
import 'profile_category_form.dart'; import 'profile_category_form.dart';
class SkillsForm extends StatelessWidget { class SkillsForm extends StatelessWidget {
SkillsForm({super.key, required this.skillsSought}); SkillsForm({
super.key,
required this.isRegProcess,
required this.skillsSought,
});
// get instance of firestore and auth // get instance of firestore and auth
final FirebaseFirestore _firestore = FirebaseFirestore.instance; final FirebaseFirestore _firestore = FirebaseFirestore.instance;
final AuthService _authService = AuthService(); final AuthService _authService = AuthService();
final bool isRegProcess;
final bool skillsSought; // flag to toggle offered and sought skills final bool skillsSought; // flag to toggle offered and sought skills
@override @override
@ -28,18 +33,42 @@ class SkillsForm extends StatelessWidget {
List<SkillOption>? userSkills = snapshot.data; List<SkillOption>? userSkills = snapshot.data;
return ProfileCategoryForm( return ProfileCategoryForm(
title: 'Skills', title: 'Skills',
header:
skillsSought ? 'Skills you are looking for' : 'Your own skills',
description: skillsSought description: skillsSought
? 'Choose up to 3 areas you are looking for in a cofounder' ? 'Choose up to 3 areas you are looking for in a co-founder'
: 'Select up to 3 areas in which you are skilled', : 'Select up to 3 areas in which you are skilled',
saveButtonText: isRegProcess ? 'Save and continue' : 'Save',
options: SkillOption.values.toList(), // Convert enum values to list options: SkillOption.values.toList(), // Convert enum values to list
minSelections: 1, minSelections: 1,
maxSelections: 3, maxSelections: 3,
preSelectedOptions: preSelectedOptions:
userSkills ?? [], // Pass pre-selected skills to the form userSkills ?? [], // Pass pre-selected skills to the form
onSave: (selectedOptions) { onSave: (selectedOptions) async {
// Handle saving selected options // Handle saving selected options
saveSkillsToFirebase(selectedOptions.cast<SkillOption>()); bool success = await saveSkillsToFirebase(
selectedOptions.cast<SkillOption>());
// Then navigate to another screen or perform any other action??? // Then navigate to another screen or perform any other action???
if (context.mounted) {
if (success) {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => SkillsForm(
isRegProcess: isRegProcess,
skillsSought: true,
),
),
);
} else {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Failed to save user skills.'),
),
);
}
}
}, },
); );
} }
@ -80,7 +109,8 @@ class SkillsForm extends StatelessWidget {
return []; return [];
} }
void saveSkillsToFirebase(List<SkillOption> selectedOptions) { Future<bool> saveSkillsToFirebase(List<SkillOption> selectedOptions) async {
try {
String currentUserId = _authService.getCurrentUser()!.uid; String currentUserId = _authService.getCurrentUser()!.uid;
// Convert enum values to strings, removing leading EnumType with split // Convert enum values to strings, removing leading EnumType with split
@ -103,5 +133,10 @@ class SkillsForm extends StatelessWidget {
}).catchError((error) { }).catchError((error) {
print('Failed to save $keyToUpdate: $error'); print('Failed to save $keyToUpdate: $error');
}); });
return true;
} catch (e) {
return false;
}
} }
} }

View File

@ -1,25 +1,28 @@
import 'dart:convert'; import 'dart:convert';
import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:cloud_firestore/cloud_firestore.dart';
import '../components/my_button.dart';
import '../constants.dart';
import '../models/language.dart';
import '../models/language_setting.dart';
import '../components/location_dialog.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter/services.dart'; import 'package:flutter/services.dart';
import 'package:flutter_svg/flutter_svg.dart'; import 'package:flutter_svg/flutter_svg.dart';
import '../services/auth/auth_service.dart'; import '../components/location_dialog.dart';
import '../components/my_button.dart';
import '../components/my_drawer.dart';
import '../constants.dart';
import '../enumerations.dart';
import '../forms/skills_form.dart';
import '../models/language.dart';
import '../models/language_setting.dart';
import '../models/location.dart'; import '../models/location.dart';
import '../services/auth/auth_service.dart';
class UserDataPage extends StatefulWidget { class UserDataPage extends StatefulWidget {
const UserDataPage({super.key}); final bool isRegProcess;
const UserDataPage({super.key, required this.isRegProcess});
@override @override
State<UserDataPage> createState() => _UserDataPageState(); State<UserDataPage> createState() => _UserDataPageState();
} }
enum Gender { none, male, female, divers }
class _UserDataPageState extends State<UserDataPage> { class _UserDataPageState extends State<UserDataPage> {
MyLocation? _mainLocation; MyLocation? _mainLocation;
MyLocation? _secondaryLocation; MyLocation? _secondaryLocation;
@ -129,7 +132,7 @@ class _UserDataPageState extends State<UserDataPage> {
// Load data from JSON file when the widget initializes // Load data from JSON file when the widget initializes
loadLanguagesFromJson(); loadLanguagesFromJson();
} catch (error) { } catch (error) {
print("Error fetching settings: $error"); _showSnackBar("Error fetching settings: $error");
} }
} }
@ -164,7 +167,8 @@ class _UserDataPageState extends State<UserDataPage> {
}); });
} }
void saveUserData(BuildContext context) async { Future<bool> saveUserData(BuildContext context) async {
try {
// Get userID from auth service // Get userID from auth service
String currentUserID = _authService.getCurrentUser()!.uid; String currentUserID = _authService.getCurrentUser()!.uid;
@ -182,8 +186,6 @@ class _UserDataPageState extends State<UserDataPage> {
); );
// update local value // update local value
_yearFromDb = _selectedYear; _yearFromDb = _selectedYear;
} else {
print("birth year did NOT change");
} }
// Update Gender in database - only if value has changed // Update Gender in database - only if value has changed
@ -193,8 +195,6 @@ class _UserDataPageState extends State<UserDataPage> {
); );
// update local value // update local value
_genderFromDb = genderView.index; _genderFromDb = genderView.index;
} else {
print("gender did NOT change");
} }
// Save locations // Save locations
@ -205,8 +205,6 @@ class _UserDataPageState extends State<UserDataPage> {
.doc(Constants.dbDocMainLocation) .doc(Constants.dbDocMainLocation)
.set(_mainLocation!.toMap()); .set(_mainLocation!.toMap());
} }
} else {
print("main location did NOT change");
} }
if (_secondaryLocation != _secondaryLocationFromDb) { if (_secondaryLocation != _secondaryLocationFromDb) {
@ -215,7 +213,6 @@ class _UserDataPageState extends State<UserDataPage> {
.doc(Constants.dbDocSecondLocation) .doc(Constants.dbDocSecondLocation)
.set(_secondaryLocation!.toMap()) .set(_secondaryLocation!.toMap())
.then((value) => { .then((value) => {
print("Document secondary location updated"),
// update local values // update local values
_secondaryLocationFromDb = _secondaryLocation, _secondaryLocationFromDb = _secondaryLocation,
_secondLocationExists = true _secondLocationExists = true
@ -224,21 +221,19 @@ class _UserDataPageState extends State<UserDataPage> {
// secondLocationExists but is null here -> delete secondary in DB // secondLocationExists but is null here -> delete secondary in DB
await locationsRef.doc(Constants.dbDocSecondLocation).delete().then( await locationsRef.doc(Constants.dbDocSecondLocation).delete().then(
(doc) => { (doc) => {
print("Document secondary location deleted"),
// update local values // update local values
_secondaryLocationFromDb = null, _secondaryLocationFromDb = null,
_secondLocationExists = false _secondLocationExists = false
}, },
onError: (e) => print("Error updating document $e"), onError: (e) => _showSnackBar("Error updating document: $e"),
); );
} }
} else {
print("secondary location did NOT change");
} }
// Save Languages - only if selected values changed // Save Languages - only if selected values changed
if (_selectedLanguages.isEmpty) { if (_selectedLanguages.isEmpty) {
print("no language selected"); _showSnackBar("No language selected");
return false;
} else if (_languagesFromDb.length != _selectedLanguages.length || } else if (_languagesFromDb.length != _selectedLanguages.length ||
_selectedLanguages _selectedLanguages
.any((element) => !_languagesFromDb.contains(element))) { .any((element) => !_languagesFromDb.contains(element))) {
@ -259,8 +254,12 @@ class _UserDataPageState extends State<UserDataPage> {
_selectedLanguages.map((language) => language.code).toList(); _selectedLanguages.map((language) => language.code).toList();
// Clean up languages that were not part of the provided list // Clean up languages that were not part of the provided list
await deleteUnusedDocuments(languagesRef, languageCodes); await deleteUnusedDocuments(languagesRef, languageCodes);
} else { }
print("languages did NOT change");
return true;
} catch (e) {
_showSnackBar(e.toString());
return false;
} }
} }
@ -326,8 +325,21 @@ class _UserDataPageState extends State<UserDataPage> {
title: const Text("User Data"), title: const Text("User Data"),
centerTitle: true, centerTitle: true,
), ),
body: ListView( drawer: const MyDrawer(),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: ListView(
children: [ children: [
if (widget.isRegProcess) ...[
const SizedBox(height: 10),
const Text(
'Please fill in the following fields to proceed with the registration process.',
style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
),
const SizedBox(height: 20),
const Divider(),
],
const SizedBox(height: 10),
const Text( const Text(
'Location', 'Location',
style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold), style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
@ -368,7 +380,8 @@ class _UserDataPageState extends State<UserDataPage> {
], ],
if (_mainLocation != null) ...[ if (_mainLocation != null) ...[
// Button to set secondary location // Button to set secondary location
ElevatedButton( Center(
child: ElevatedButton(
onPressed: () { onPressed: () {
_showLocationDialog(false); _showLocationDialog(false);
}, },
@ -376,13 +389,16 @@ class _UserDataPageState extends State<UserDataPage> {
? 'Change Secondary Location' ? 'Change Secondary Location'
: 'Add Secondary Location'), : 'Add Secondary Location'),
), ),
),
], ],
// Display selected secondary location or remove button // Display selected secondary location or remove button
if (_secondaryLocation != null) ...[ if (_secondaryLocation != null) ...[
ElevatedButton( Center(
child: ElevatedButton(
onPressed: _removeSecondaryLocation, onPressed: _removeSecondaryLocation,
child: const Text('Remove Secondary Location'), child: const Text('Remove Secondary Location'),
), ),
),
], ],
const SizedBox(height: 20), const SizedBox(height: 20),
const Text( const Text(
@ -394,7 +410,7 @@ class _UserDataPageState extends State<UserDataPage> {
const Padding(padding: EdgeInsets.symmetric(horizontal: 8)), const Padding(padding: EdgeInsets.symmetric(horizontal: 8)),
Text(_selectedYear != null Text(_selectedYear != null
? '${DateTime.now().year - (_selectedYear ?? 0)} years old' ? '${DateTime.now().year - (_selectedYear ?? 0)} years old'
: 'undefined'), : 'undefined age'),
const SizedBox(width: 20), const SizedBox(width: 20),
DropdownMenu( DropdownMenu(
initialSelection: _selectedYear, initialSelection: _selectedYear,
@ -416,7 +432,8 @@ class _UserDataPageState extends State<UserDataPage> {
const SizedBox(height: 20), const SizedBox(height: 20),
Text( Text(
'Gender (${genderView.name} selected)', 'Gender (${genderView.name} selected)',
style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold), style:
const TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
), ),
Center( Center(
child: SegmentedButton<Gender>( child: SegmentedButton<Gender>(
@ -452,16 +469,42 @@ class _UserDataPageState extends State<UserDataPage> {
const Divider(), const Divider(),
Text( Text(
'Language: (${_selectedLanguages.length} selected)', 'Language: (${_selectedLanguages.length} selected)',
style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold), style:
const TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
), ),
...languagesList.map(buildSingleCheckbox), // ... spread operator ...languagesList.map(buildSingleCheckbox), // ... spread operator
const Divider(), const Divider(),
Padding( Padding(
padding: const EdgeInsets.all(8.0), padding: const EdgeInsets.all(8.0),
child: MyButton(text: "Save", onTap: () => saveUserData(context)), child: MyButton(
) text: widget.isRegProcess ? 'Save and continue' : "Save",
onTap: () async {
bool success = await saveUserData(context);
if (context.mounted) {
if (success) {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => SkillsForm(
isRegProcess: widget.isRegProcess,
skillsSought: false,
),
),
);
} else {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Failed to save user data.'),
),
);
}
}
},
),
),
], ],
), ),
),
); );
} }
} }
@ -508,4 +551,19 @@ class _UserDataPageState extends State<UserDataPage> {
onChanged: (value) => onClicked(), onChanged: (value) => onClicked(),
), ),
); );
void _showSnackBar(String message) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(message),
backgroundColor: Colors.red,
action: SnackBarAction(
label: 'Dismiss',
onPressed: () {
ScaffoldMessenger.of(context).hideCurrentSnackBar();
},
),
),
);
}
} }

View File

@ -1,9 +1,13 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart'; import 'package:firebase_auth/firebase_auth.dart';
import 'package:cofounderella/services/auth/login_or_register.dart'; import 'auth_service.dart';
import 'package:cofounderella/pages/home_page.dart'; import 'login_or_register.dart';
import '../../constants.dart';
import '../../pages/home_page.dart';
import '../../pages/user_data_page.dart';
class AuthGate extends StatelessWidget{ class AuthGate extends StatelessWidget {
const AuthGate({super.key}); const AuthGate({super.key});
@override @override
@ -11,17 +15,48 @@ class AuthGate extends StatelessWidget{
return Scaffold( return Scaffold(
body: StreamBuilder( body: StreamBuilder(
stream: FirebaseAuth.instance.authStateChanges(), stream: FirebaseAuth.instance.authStateChanges(),
builder: (context, snapshot){ builder: (context, snapshot) {
// check if user is logged in or not // check if user is logged in or not
if(snapshot.hasData){ if (snapshot.hasData) {
return FutureBuilder(
// check database entries, if data is missing
// then complete registration process
// else go to HomePage
future: _checkCollectionsExist(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return const CircularProgressIndicator();
} else if (snapshot.hasData && snapshot.data == true) {
return HomePage(); return HomePage();
} else {
// also in case (snapshot.hasError)
return const UserDataPage(isRegProcess: true);
} }
else { },
);
} else {
return const LoginOrRegister(); return const LoginOrRegister();
} }
}, },
), ),
); );
} }
Future<bool> _checkCollectionsExist() async {
bool languagesExist =
await _checkUsersCollectionExists(Constants.dbCollectionLanguages);
bool locationsExist =
await _checkUsersCollectionExists(Constants.dbCollectionLocations);
return languagesExist && locationsExist;
}
Future<bool> _checkUsersCollectionExists(String collectionName) async {
String currentUserId = AuthService().getCurrentUser()!.uid;
final collection = FirebaseFirestore.instance
.collection(Constants.dbCollectionUsers)
.doc(currentUserId)
.collection(collectionName);
final snapshot = await collection.limit(1).get();
return snapshot.docs.isNotEmpty;
}
} }