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(
context,
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 {
product,
finance,

View File

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

View File

@ -6,12 +6,17 @@ import '../../services/auth/auth_service.dart';
import 'profile_category_form.dart';
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
final FirebaseFirestore _firestore = FirebaseFirestore.instance;
final AuthService _authService = AuthService();
final bool isRegProcess;
final bool skillsSought; // flag to toggle offered and sought skills
@override
@ -28,18 +33,42 @@ class SkillsForm extends StatelessWidget {
List<SkillOption>? userSkills = snapshot.data;
return ProfileCategoryForm(
title: 'Skills',
header:
skillsSought ? 'Skills you are looking for' : 'Your own skills',
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',
saveButtonText: isRegProcess ? 'Save and continue' : 'Save',
options: SkillOption.values.toList(), // Convert enum values to list
minSelections: 1,
maxSelections: 3,
preSelectedOptions:
userSkills ?? [], // Pass pre-selected skills to the form
onSave: (selectedOptions) {
onSave: (selectedOptions) async {
// 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???
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 [];
}
void saveSkillsToFirebase(List<SkillOption> selectedOptions) {
Future<bool> saveSkillsToFirebase(List<SkillOption> selectedOptions) async {
try {
String currentUserId = _authService.getCurrentUser()!.uid;
// Convert enum values to strings, removing leading EnumType with split
@ -103,5 +133,10 @@ class SkillsForm extends StatelessWidget {
}).catchError((error) {
print('Failed to save $keyToUpdate: $error');
});
return true;
} catch (e) {
return false;
}
}
}

View File

@ -1,25 +1,28 @@
import 'dart:convert';
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/services.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 '../services/auth/auth_service.dart';
class UserDataPage extends StatefulWidget {
const UserDataPage({super.key});
final bool isRegProcess;
const UserDataPage({super.key, required this.isRegProcess});
@override
State<UserDataPage> createState() => _UserDataPageState();
}
enum Gender { none, male, female, divers }
class _UserDataPageState extends State<UserDataPage> {
MyLocation? _mainLocation;
MyLocation? _secondaryLocation;
@ -129,7 +132,7 @@ class _UserDataPageState extends State<UserDataPage> {
// Load data from JSON file when the widget initializes
loadLanguagesFromJson();
} 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
String currentUserID = _authService.getCurrentUser()!.uid;
@ -182,8 +186,6 @@ class _UserDataPageState extends State<UserDataPage> {
);
// update local value
_yearFromDb = _selectedYear;
} else {
print("birth year did NOT change");
}
// Update Gender in database - only if value has changed
@ -193,8 +195,6 @@ class _UserDataPageState extends State<UserDataPage> {
);
// update local value
_genderFromDb = genderView.index;
} else {
print("gender did NOT change");
}
// Save locations
@ -205,8 +205,6 @@ class _UserDataPageState extends State<UserDataPage> {
.doc(Constants.dbDocMainLocation)
.set(_mainLocation!.toMap());
}
} else {
print("main location did NOT change");
}
if (_secondaryLocation != _secondaryLocationFromDb) {
@ -215,7 +213,6 @@ class _UserDataPageState extends State<UserDataPage> {
.doc(Constants.dbDocSecondLocation)
.set(_secondaryLocation!.toMap())
.then((value) => {
print("Document secondary location updated"),
// update local values
_secondaryLocationFromDb = _secondaryLocation,
_secondLocationExists = true
@ -224,21 +221,19 @@ class _UserDataPageState extends State<UserDataPage> {
// secondLocationExists but is null here -> delete secondary in DB
await locationsRef.doc(Constants.dbDocSecondLocation).delete().then(
(doc) => {
print("Document secondary location deleted"),
// update local values
_secondaryLocationFromDb = null,
_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
if (_selectedLanguages.isEmpty) {
print("no language selected");
_showSnackBar("No language selected");
return false;
} else if (_languagesFromDb.length != _selectedLanguages.length ||
_selectedLanguages
.any((element) => !_languagesFromDb.contains(element))) {
@ -259,8 +254,12 @@ class _UserDataPageState extends State<UserDataPage> {
_selectedLanguages.map((language) => language.code).toList();
// Clean up languages that were not part of the provided list
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"),
centerTitle: true,
),
body: ListView(
drawer: const MyDrawer(),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: ListView(
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(
'Location',
style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
@ -368,7 +380,8 @@ class _UserDataPageState extends State<UserDataPage> {
],
if (_mainLocation != null) ...[
// Button to set secondary location
ElevatedButton(
Center(
child: ElevatedButton(
onPressed: () {
_showLocationDialog(false);
},
@ -376,13 +389,16 @@ class _UserDataPageState extends State<UserDataPage> {
? 'Change Secondary Location'
: 'Add Secondary Location'),
),
),
],
// Display selected secondary location or remove button
if (_secondaryLocation != null) ...[
ElevatedButton(
Center(
child: ElevatedButton(
onPressed: _removeSecondaryLocation,
child: const Text('Remove Secondary Location'),
),
),
],
const SizedBox(height: 20),
const Text(
@ -394,7 +410,7 @@ class _UserDataPageState extends State<UserDataPage> {
const Padding(padding: EdgeInsets.symmetric(horizontal: 8)),
Text(_selectedYear != null
? '${DateTime.now().year - (_selectedYear ?? 0)} years old'
: 'undefined'),
: 'undefined age'),
const SizedBox(width: 20),
DropdownMenu(
initialSelection: _selectedYear,
@ -416,7 +432,8 @@ class _UserDataPageState extends State<UserDataPage> {
const SizedBox(height: 20),
Text(
'Gender (${genderView.name} selected)',
style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
style:
const TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
),
Center(
child: SegmentedButton<Gender>(
@ -452,16 +469,42 @@ class _UserDataPageState extends State<UserDataPage> {
const Divider(),
Text(
'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
const Divider(),
Padding(
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(),
),
);
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,7 +1,11 @@
import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:cofounderella/services/auth/login_or_register.dart';
import 'package:cofounderella/pages/home_page.dart';
import 'auth_service.dart';
import 'login_or_register.dart';
import '../../constants.dart';
import '../../pages/home_page.dart';
import '../../pages/user_data_page.dart';
class AuthGate extends StatelessWidget {
const AuthGate({super.key});
@ -12,16 +16,47 @@ class AuthGate extends StatelessWidget{
body: StreamBuilder(
stream: FirebaseAuth.instance.authStateChanges(),
builder: (context, snapshot) {
// check if user is logged in or not
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();
} else {
// also in case (snapshot.hasError)
return const UserDataPage(isRegProcess: true);
}
else {
},
);
} else {
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;
}
}