repo_id
stringlengths
21
168
file_path
stringlengths
36
210
content
stringlengths
1
9.98M
__index_level_0__
int64
0
0
mirrored_repositories/barbershop/lib/src/features/employee
mirrored_repositories/barbershop/lib/src/features/employee/schedule/employee_schedule_vm.dart
import 'package:barbershop/src/core/exceptions/repository_exception.dart'; import 'package:barbershop/src/core/fp/either.dart'; import 'package:barbershop/src/core/providers/application_providers.dart'; import 'package:barbershop/src/models/schedule_model.dart'; import 'package:riverpod_annotation/riverpod_annotation.dart'; part 'employee_schedule_vm.g.dart'; @riverpod class EmployeeScheduleVM extends _$EmployeeScheduleVM { @override Future<List<ScheduleModel>> build(int userId, DateTime date) async => switch (await _getSchedules(userId, date)) { Success(value: final schedules) => schedules, Failure(:final exception) => throw Exception(exception), }; Future<void> changeDate(int userId, DateTime date) async => state = switch (await _getSchedules(userId, date)) { Success(value: final schedules) => AsyncData(schedules), Failure(:final exception) => AsyncError(Exception(exception), StackTrace.current), }; Future<Either<RepositoryException, List<ScheduleModel>>> _getSchedules( int userId, DateTime date, ) => ref .read(scheduleRepositoryProvider) .findScheduleByDate((userId: userId, date: date)); }
0
mirrored_repositories/barbershop/lib/src/features/employee
mirrored_repositories/barbershop/lib/src/features/employee/schedule/employee_schedule_vm.g.dart
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'employee_schedule_vm.dart'; // ************************************************************************** // RiverpodGenerator // ************************************************************************** String _$employeeScheduleVMHash() => r'fcd4fb19f0b66eb54b6763dd5acac6418cf1a08a'; /// Copied from Dart SDK class _SystemHash { _SystemHash._(); static int combine(int hash, int value) { // ignore: parameter_assignments hash = 0x1fffffff & (hash + value); // ignore: parameter_assignments hash = 0x1fffffff & (hash + ((0x0007ffff & hash) << 10)); return hash ^ (hash >> 6); } static int finish(int hash) { // ignore: parameter_assignments hash = 0x1fffffff & (hash + ((0x03ffffff & hash) << 3)); // ignore: parameter_assignments hash = hash ^ (hash >> 11); return 0x1fffffff & (hash + ((0x00003fff & hash) << 15)); } } abstract class _$EmployeeScheduleVM extends BuildlessAutoDisposeAsyncNotifier<List<ScheduleModel>> { late final int userId; late final DateTime date; Future<List<ScheduleModel>> build( int userId, DateTime date, ); } /// See also [EmployeeScheduleVM]. @ProviderFor(EmployeeScheduleVM) const employeeScheduleVMProvider = EmployeeScheduleVMFamily(); /// See also [EmployeeScheduleVM]. class EmployeeScheduleVMFamily extends Family<AsyncValue<List<ScheduleModel>>> { /// See also [EmployeeScheduleVM]. const EmployeeScheduleVMFamily(); /// See also [EmployeeScheduleVM]. EmployeeScheduleVMProvider call( int userId, DateTime date, ) { return EmployeeScheduleVMProvider( userId, date, ); } @override EmployeeScheduleVMProvider getProviderOverride( covariant EmployeeScheduleVMProvider provider, ) { return call( provider.userId, provider.date, ); } static const Iterable<ProviderOrFamily>? _dependencies = null; @override Iterable<ProviderOrFamily>? get dependencies => _dependencies; static const Iterable<ProviderOrFamily>? _allTransitiveDependencies = null; @override Iterable<ProviderOrFamily>? get allTransitiveDependencies => _allTransitiveDependencies; @override String? get name => r'employeeScheduleVMProvider'; } /// See also [EmployeeScheduleVM]. class EmployeeScheduleVMProvider extends AutoDisposeAsyncNotifierProviderImpl< EmployeeScheduleVM, List<ScheduleModel>> { /// See also [EmployeeScheduleVM]. EmployeeScheduleVMProvider( this.userId, this.date, ) : super.internal( () => EmployeeScheduleVM() ..userId = userId ..date = date, from: employeeScheduleVMProvider, name: r'employeeScheduleVMProvider', debugGetCreateSourceHash: const bool.fromEnvironment('dart.vm.product') ? null : _$employeeScheduleVMHash, dependencies: EmployeeScheduleVMFamily._dependencies, allTransitiveDependencies: EmployeeScheduleVMFamily._allTransitiveDependencies, ); final int userId; final DateTime date; @override bool operator ==(Object other) { return other is EmployeeScheduleVMProvider && other.userId == userId && other.date == date; } @override int get hashCode { var hash = _SystemHash.combine(0, runtimeType.hashCode); hash = _SystemHash.combine(hash, userId.hashCode); hash = _SystemHash.combine(hash, date.hashCode); return _SystemHash.finish(hash); } @override Future<List<ScheduleModel>> runNotifierBuild( covariant EmployeeScheduleVM notifier, ) { return notifier.build( userId, date, ); } } // ignore_for_file: type=lint // ignore_for_file: subtype_of_sealed_class, invalid_use_of_internal_member
0
mirrored_repositories/barbershop/lib/src/features/employee
mirrored_repositories/barbershop/lib/src/features/employee/register/employee_register_page.dart
import 'dart:developer'; import 'package:barbershop/src/core/providers/application_providers.dart'; import 'package:barbershop/src/core/ui/helpers/form_helper.dart'; import 'package:barbershop/src/core/ui/helpers/messages.dart'; import 'package:barbershop/src/core/ui/widgets/avatar_widget.dart'; import 'package:barbershop/src/core/ui/widgets/barbershop_loader.dart'; import 'package:barbershop/src/core/ui/widgets/hours_panel.dart'; import 'package:barbershop/src/core/ui/widgets/weekdays_panel.dart'; import 'package:barbershop/src/features/employee/register/employee_register_state.dart'; import 'package:barbershop/src/features/employee/register/employee_register_vm.dart'; import 'package:barbershop/src/models/barbershop_model.dart'; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:validatorless/validatorless.dart'; class EmployeeRegisterPage extends ConsumerStatefulWidget { const EmployeeRegisterPage({super.key}); @override ConsumerState<EmployeeRegisterPage> createState() => _EmployeeRegisterPageState(); } class _EmployeeRegisterPageState extends ConsumerState<EmployeeRegisterPage> { var registerADM = false; final formKey = GlobalKey<FormState>(); final nameController = TextEditingController(); final emailController = TextEditingController(); final passwordController = TextEditingController(); @override void dispose() { super.dispose(); nameController.dispose(); emailController.dispose(); passwordController.dispose(); } @override Widget build(BuildContext context) { final employeeRegisterVM = ref.watch(employeeRegisterVMProvider.notifier); final barbershopAsyncValue = ref.watch(getMyBarbershopProvider); ref.listen( employeeRegisterVMProvider.select((state) => state.status), (_, status) { switch (status) { case EmployeeRegisterStateStatus.initial: break; case EmployeeRegisterStateStatus.success: context.showSuccess('Colaborador registrado com sucesso'); Navigator.of(context).pop(); case EmployeeRegisterStateStatus.error: context.showError('Erro ao registar colaborador'); } }, ); return Scaffold( appBar: AppBar( title: const Text('Cadastrar Colaborador'), ), body: barbershopAsyncValue.when( loading: () => const BarbershopLoader(), error: (e, s) { log('Erro ao carregar a página', error: e, stackTrace: s); return const Center( child: Text('Erro ao carregar a página'), ); }, data: (barbershop) { final BarbershopModel(:openDays, :openHours) = barbershop; return SingleChildScrollView( child: Padding( padding: const EdgeInsets.all(12), child: Form( key: formKey, child: Center( child: Column( children: [ const AvatarWidget(), const SizedBox(height: 32), Row( children: [ Checkbox.adaptive( value: registerADM, onChanged: (_) { setState(() { registerADM = !registerADM; }); employeeRegisterVM.setRegisterADM(registerADM); }, ), const Expanded( child: Text( 'Sou administrador e quero me cadastrar como colaborador', style: TextStyle(fontSize: 14), ), ), ], ), Offstage( offstage: registerADM, child: Column( children: [ const SizedBox(height: 24), TextFormField( onTapOutside: (_) => context.unfocus(), controller: nameController, decoration: const InputDecoration( label: Text('Nome'), ), validator: registerADM ? null : Validatorless.required( 'Nome é obrigatório', ), ), const SizedBox(height: 24), TextFormField( onTapOutside: (_) => context.unfocus(), controller: emailController, keyboardType: TextInputType.emailAddress, decoration: const InputDecoration( label: Text('Email'), ), validator: registerADM ? null : Validatorless.multiple([ Validatorless.required( 'E-mail é obrigatório', ), Validatorless.email( 'Digite um e-mail válido', ), ]), ), const SizedBox(height: 24), TextFormField( onTapOutside: (_) => context.unfocus(), obscureText: true, controller: passwordController, decoration: const InputDecoration( label: Text('Senha'), ), validator: registerADM ? null : Validatorless.multiple([ Validatorless.required( 'Senha é obrigatória', ), Validatorless.min( 6, 'Senha deve conter no mínimo 6 caracteres', ), ]), ), ], ), ), const SizedBox(height: 24), WeekdaysPanel( enabledDays: openDays, onDayPressed: employeeRegisterVM.addOrRemoveWeekDays, ), const SizedBox(height: 24), HoursPanel( startTime: 6, endTime: 23, enabledTimes: openHours, onTimePressed: employeeRegisterVM.addOrRemoveWorkHours, ), const SizedBox(height: 24), ElevatedButton( style: ElevatedButton.styleFrom( minimumSize: const Size.fromHeight(56), ), onPressed: () { switch (formKey.currentState?.validate()) { case false || null: context.showError('Existem campos inválidos'); case true: final EmployeeRegisterState( workDays: List(isEmpty: hasWorkDays), workHours: List(isEmpty: hasWorkHours), ) = ref.watch(employeeRegisterVMProvider); if (hasWorkDays || hasWorkHours) { context.showError( 'Selecione os dias da semana e horário de atendimento', ); return; } employeeRegisterVM.register( name: nameController.text, email: emailController.text, password: passwordController.text, ); } }, child: const Text('CADASTRAR COLABORADOR'), ), ], ), ), ), ), ); }, ), ); } }
0
mirrored_repositories/barbershop/lib/src/features/employee
mirrored_repositories/barbershop/lib/src/features/employee/register/employee_register_vm.g.dart
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'employee_register_vm.dart'; // ************************************************************************** // RiverpodGenerator // ************************************************************************** String _$employeeRegisterVMHash() => r'e8096a13e4ad01a629119f9240b386708fc1e7d9'; /// See also [EmployeeRegisterVM]. @ProviderFor(EmployeeRegisterVM) final employeeRegisterVMProvider = AutoDisposeNotifierProvider< EmployeeRegisterVM, EmployeeRegisterState>.internal( EmployeeRegisterVM.new, name: r'employeeRegisterVMProvider', debugGetCreateSourceHash: const bool.fromEnvironment('dart.vm.product') ? null : _$employeeRegisterVMHash, dependencies: null, allTransitiveDependencies: null, ); typedef _$EmployeeRegisterVM = AutoDisposeNotifier<EmployeeRegisterState>; // ignore_for_file: type=lint // ignore_for_file: subtype_of_sealed_class, invalid_use_of_internal_member
0
mirrored_repositories/barbershop/lib/src/features/employee
mirrored_repositories/barbershop/lib/src/features/employee/register/employee_register_vm.dart
import 'package:asyncstate/asyncstate.dart'; import 'package:barbershop/src/core/exceptions/repository_exception.dart'; import 'package:barbershop/src/core/fp/either.dart'; import 'package:barbershop/src/core/fp/nil.dart'; import 'package:barbershop/src/core/providers/application_providers.dart'; import 'package:barbershop/src/features/employee/register/employee_register_state.dart'; import 'package:barbershop/src/models/barbershop_model.dart'; import 'package:barbershop/src/repositories/user/user_repository.dart'; import 'package:riverpod_annotation/riverpod_annotation.dart'; part 'employee_register_vm.g.dart'; @riverpod class EmployeeRegisterVM extends _$EmployeeRegisterVM { @override EmployeeRegisterState build() => EmployeeRegisterState.initial(); void setRegisterADM(bool isRegisterADM) { state = state.copyWith(registerADM: isRegisterADM); } void addOrRemoveWeekDays(String weekDay) { final EmployeeRegisterState(:workDays) = state; if (workDays.contains(weekDay)) { workDays.remove(weekDay); } else { workDays.add(weekDay); } state = state.copyWith(workDays: workDays); } void addOrRemoveWorkHours(int workHour) { final EmployeeRegisterState(:workHours) = state; if (workHours.contains(workHour)) { workHours.remove(workHour); } else { workHours.add(workHour); } state = state.copyWith(workHours: workHours); } Future<void> register({ String? name, String? email, String? password, }) async { final EmployeeRegisterState(:registerADM, :workDays, :workHours) = state; final asyncLoaderHandler = AsyncLoaderHandler()..start(); final UserRepository(:registerADMAsEmployee, :registerEmployee) = ref.read(userRepositoryProvider); final Either<RepositoryException, Nil> resultRegister; if (registerADM) { final dto = ( workDays: workDays, workHours: workHours, ); resultRegister = await registerADMAsEmployee(dto); } else { final BarbershopModel(:id) = await ref.watch(getMyBarbershopProvider.future); final dto = ( barbershopId: id, name: name!, email: email!, password: password!, workDays: workDays, workHours: workHours, ); resultRegister = await registerEmployee(dto); } state = state.copyWith( status: switch (resultRegister) { Success() => EmployeeRegisterStateStatus.success, Failure() => EmployeeRegisterStateStatus.error, }, ); asyncLoaderHandler.close(); } }
0
mirrored_repositories/barbershop/lib/src/features/employee
mirrored_repositories/barbershop/lib/src/features/employee/register/employee_register_state.dart
enum EmployeeRegisterStateStatus { initial, success, error, } class EmployeeRegisterState { EmployeeRegisterState.initial() : this( status: EmployeeRegisterStateStatus.initial, registerADM: false, workDays: <String>[], workHours: <int>[], ); EmployeeRegisterState({ required this.status, required this.registerADM, required this.workDays, required this.workHours, }); final EmployeeRegisterStateStatus status; final bool registerADM; final List<String> workDays; final List<int> workHours; EmployeeRegisterState copyWith({ EmployeeRegisterStateStatus? status, bool? registerADM, List<String>? workDays, List<int>? workHours, }) => EmployeeRegisterState( status: status ?? this.status, registerADM: registerADM ?? this.registerADM, workDays: workDays ?? this.workDays, workHours: workHours ?? this.workHours, ); }
0
mirrored_repositories/barbershop/lib/src/features/auth
mirrored_repositories/barbershop/lib/src/features/auth/login/login_vm.dart
import 'package:asyncstate/asyncstate.dart'; import 'package:barbershop/src/core/exceptions/service_exception.dart'; import 'package:barbershop/src/core/fp/either.dart'; import 'package:barbershop/src/core/providers/application_providers.dart'; import 'package:barbershop/src/features/auth/login/login_state.dart'; import 'package:barbershop/src/models/user_model.dart'; import 'package:riverpod_annotation/riverpod_annotation.dart'; part 'login_vm.g.dart'; @riverpod class LoginVM extends _$LoginVM { @override LoginState build() => const LoginState.initial(); Future<void> login(String email, String password) async { final loaderHandler = AsyncLoaderHandler()..start(); final loginService = ref.watch(userLoginServiceProvider); final result = await loginService.execute( email: email, password: password, ); switch (result) { case Success(): ref ..invalidate(getMeProvider) ..invalidate(getMyBarbershopProvider); final userModel = await ref.read(getMeProvider.future); state.copyWith( status: switch (userModel) { UserModelADM() => LoginStateStatus.admLogin, UserModelEmployee() => LoginStateStatus.employeeLogin, }, ); case Failure(exception: ServiceException(:final message)): state = state.copyWith( status: LoginStateStatus.error, errorMessage: () => message, ); } loaderHandler.close(); } }
0
mirrored_repositories/barbershop/lib/src/features/auth
mirrored_repositories/barbershop/lib/src/features/auth/login/login_vm.g.dart
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'login_vm.dart'; // ************************************************************************** // RiverpodGenerator // ************************************************************************** String _$loginVMHash() => r'2e103372a528f52d2e11d9b26d5e4241a153a7ba'; /// See also [LoginVM]. @ProviderFor(LoginVM) final loginVMProvider = AutoDisposeNotifierProvider<LoginVM, LoginState>.internal( LoginVM.new, name: r'loginVMProvider', debugGetCreateSourceHash: const bool.fromEnvironment('dart.vm.product') ? null : _$loginVMHash, dependencies: null, allTransitiveDependencies: null, ); typedef _$LoginVM = AutoDisposeNotifier<LoginState>; // ignore_for_file: type=lint // ignore_for_file: subtype_of_sealed_class, invalid_use_of_internal_member
0
mirrored_repositories/barbershop/lib/src/features/auth
mirrored_repositories/barbershop/lib/src/features/auth/login/login_page.dart
import 'package:barbershop/src/core/constants/constants.dart'; import 'package:barbershop/src/core/ui/helpers/form_helper.dart'; import 'package:barbershop/src/core/ui/helpers/messages.dart'; import 'package:barbershop/src/features/auth/login/login_state.dart'; import 'package:barbershop/src/features/auth/login/login_vm.dart'; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:validatorless/validatorless.dart'; final class LoginPage extends ConsumerStatefulWidget { const LoginPage({super.key}); @override ConsumerState<LoginPage> createState() => _LoginPageState(); } final class _LoginPageState extends ConsumerState<LoginPage> { final formKey = GlobalKey<FormState>(); final emailController = TextEditingController(); final passwordController = TextEditingController(); @override void dispose() { emailController.dispose(); passwordController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { final LoginVM(:login) = ref.watch(loginVMProvider.notifier); ref.listen( loginVMProvider, (_, state) { debugPrint('state: ${state.status}'); switch (state) { case LoginState(status: LoginStateStatus.initial): break; case LoginState(status: LoginStateStatus.error, :final errorMessage?): context.showError(errorMessage); case LoginState(status: LoginStateStatus.error): context.showError('Erro ao realizar login'); case LoginState(status: LoginStateStatus.admLogin): Navigator.of(context) .pushNamedAndRemoveUntil('/home/adm', (_) => false); case LoginState(status: LoginStateStatus.employeeLogin): Navigator.of(context) .pushNamedAndRemoveUntil('/home/employee', (_) => false); } }, ); return Scaffold( backgroundColor: Colors.black, resizeToAvoidBottomInset: false, body: DecoratedBox( decoration: const BoxDecoration( image: DecorationImage( image: AssetImage(AppImages.backgroundChair), fit: BoxFit.cover, opacity: 0.2, ), ), child: Padding( padding: const EdgeInsets.all(30), child: Form( key: formKey, child: CustomScrollView( slivers: [ SliverFillRemaining( hasScrollBody: false, child: Stack( alignment: Alignment.center, children: [ Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Image.asset( AppImages.imgLogo, width: 150, height: 170, ), const SizedBox(height: 24), TextFormField( controller: emailController, onTapOutside: (_) => context.unfocus(), keyboardType: TextInputType.emailAddress, validator: Validatorless.multiple([ Validatorless.required('E-mail obrigatório'), Validatorless.email('E-mail inválido'), ]), decoration: const InputDecoration( label: Text('E-mail'), labelStyle: TextStyle(color: Colors.black), hintText: 'E-mail', hintStyle: TextStyle(color: Colors.black), floatingLabelBehavior: FloatingLabelBehavior.never, ), ), const SizedBox(height: 24), TextFormField( controller: passwordController, onTapOutside: (_) => context.unfocus(), validator: Validatorless.multiple([ Validatorless.required('Senha obrigatória'), Validatorless.min(6, 'Senha inválida'), ]), obscureText: true, decoration: const InputDecoration( label: Text('Senha'), labelStyle: TextStyle(color: Colors.black), hintText: 'Senha', hintStyle: TextStyle(color: Colors.black), floatingLabelBehavior: FloatingLabelBehavior.never, ), ), const SizedBox(height: 16), const Align( alignment: Alignment.centerLeft, child: Text( 'Esqueceu a senha?', style: TextStyle( color: AppColors.brown, fontSize: 12, ), ), ), const SizedBox(height: 24), ElevatedButton( onPressed: () => switch (formKey.currentState?.validate()) { (false || null) => context.showError('Campos inválidos'), true => login( emailController.text, passwordController.text, ), }, style: ElevatedButton.styleFrom( minimumSize: const Size.fromHeight(56), ), child: const Text('ACESSAR'), ), ], ), Align( alignment: Alignment.bottomCenter, child: InkWell( onTap: () => Navigator.of(context).pushNamed( '/auth/register/user', ), child: const Text( 'Criar conta', style: TextStyle( color: Colors.white, fontSize: 16, fontWeight: FontWeight.w500, ), ), ), ), ], ), ), ], ), ), ), ), ); } }
0
mirrored_repositories/barbershop/lib/src/features/auth
mirrored_repositories/barbershop/lib/src/features/auth/login/login_state.dart
import 'package:flutter/material.dart'; enum LoginStateStatus { initial, error, admLogin, employeeLogin, } class LoginState { const LoginState({ required this.status, this.errorMessage, }); const LoginState.initial() : this(status: LoginStateStatus.initial); final LoginStateStatus status; final String? errorMessage; LoginState copyWith({ LoginStateStatus? status, ValueGetter<String?>? errorMessage, }) { return LoginState( status: status ?? this.status, errorMessage: errorMessage != null ? errorMessage() : this.errorMessage, ); } }
0
mirrored_repositories/barbershop/lib/src/features/auth/register
mirrored_repositories/barbershop/lib/src/features/auth/register/user/user_register_providers.dart
import 'package:barbershop/src/core/providers/application_providers.dart'; import 'package:barbershop/src/services/user_register_adm/user_service_adm.dart'; import 'package:barbershop/src/services/user_register_adm/user_service_adm_impl.dart'; import 'package:riverpod_annotation/riverpod_annotation.dart'; part 'user_register_providers.g.dart'; @riverpod UserRegisterServiceADM userRegisterServiceADM(UserRegisterServiceADMRef ref) => UserRegisterServiceADMImpl( userRepository: ref.watch(userRepositoryProvider), userService: ref.watch(userLoginServiceProvider), );
0
mirrored_repositories/barbershop/lib/src/features/auth/register
mirrored_repositories/barbershop/lib/src/features/auth/register/user/user_register_providers.g.dart
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'user_register_providers.dart'; // ************************************************************************** // RiverpodGenerator // ************************************************************************** String _$userRegisterServiceADMHash() => r'a2a276c226f68e3d2c5318bc5f6cf8fd4d5372a6'; /// See also [userRegisterServiceADM]. @ProviderFor(userRegisterServiceADM) final userRegisterServiceADMProvider = AutoDisposeProvider<UserRegisterServiceADM>.internal( userRegisterServiceADM, name: r'userRegisterServiceADMProvider', debugGetCreateSourceHash: const bool.fromEnvironment('dart.vm.product') ? null : _$userRegisterServiceADMHash, dependencies: null, allTransitiveDependencies: null, ); typedef UserRegisterServiceADMRef = AutoDisposeProviderRef<UserRegisterServiceADM>; // ignore_for_file: type=lint // ignore_for_file: subtype_of_sealed_class, invalid_use_of_internal_member
0
mirrored_repositories/barbershop/lib/src/features/auth/register
mirrored_repositories/barbershop/lib/src/features/auth/register/user/user_register_vm.dart
import 'package:barbershop/src/core/fp/either.dart'; import 'package:barbershop/src/core/providers/application_providers.dart'; import 'package:barbershop/src/features/auth/register/user/user_register_providers.dart'; import 'package:riverpod_annotation/riverpod_annotation.dart'; part 'user_register_vm.g.dart'; enum UserRegisterStateStatus { initial, success, error } @riverpod class UserRegisterVM extends _$UserRegisterVM { @override UserRegisterStateStatus build() => UserRegisterStateStatus.initial; Future<void> register({ required String name, required String email, required String password, }) async { final userRegisterService = ref.watch(userRegisterServiceADMProvider); final userData = ( name: name, email: email, password: password, ); final result = await userRegisterService.execute(userData); switch (result) { case Success(): ref.invalidate(getMeProvider); state = UserRegisterStateStatus.success; case Failure(): state = UserRegisterStateStatus.error; } } }
0
mirrored_repositories/barbershop/lib/src/features/auth/register
mirrored_repositories/barbershop/lib/src/features/auth/register/user/user_register_page.dart
import 'package:barbershop/src/core/fp/nil.dart'; import 'package:barbershop/src/core/ui/helpers/form_helper.dart'; import 'package:barbershop/src/core/ui/helpers/messages.dart'; import 'package:barbershop/src/features/auth/register/user/user_register_vm.dart'; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:validatorless/validatorless.dart'; class UserRegisterPage extends ConsumerStatefulWidget { const UserRegisterPage({super.key}); @override ConsumerState<UserRegisterPage> createState() => _UserRegisterPageState(); } final class _UserRegisterPageState extends ConsumerState<UserRegisterPage> { final formKey = GlobalKey<FormState>(); final nameController = TextEditingController(); final emailController = TextEditingController(); final passwordController = TextEditingController(); @override void dispose() { nameController.dispose(); emailController.dispose(); passwordController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { final userRegisterVM = ref.watch(userRegisterVMProvider.notifier); ref.listen( userRegisterVMProvider, (_, state) => switch (state) { UserRegisterStateStatus.initial => nil, UserRegisterStateStatus.success => Navigator.of(context).pushNamed('/auth/register/barbershop'), UserRegisterStateStatus.error => context.showError('Erro ao registrar usuário Administrador'), }, ); return Scaffold( appBar: AppBar( title: const Text('Criar conta'), ), body: Form( key: formKey, child: ListView( padding: const EdgeInsets.all(30), children: [ const SizedBox(height: 20), TextFormField( controller: nameController, decoration: const InputDecoration(label: Text('Nome')), onTapOutside: (_) => context.unfocus(), validator: Validatorless.required('Nome obrigatório'), ), const SizedBox(height: 24), TextFormField( controller: emailController, keyboardType: TextInputType.emailAddress, decoration: const InputDecoration(label: Text('E-mail')), onTapOutside: (_) => context.unfocus(), validator: Validatorless.multiple([ Validatorless.required('E-mail obrigatório'), Validatorless.email('E-mail inválido'), ]), ), const SizedBox(height: 24), TextFormField( controller: passwordController, decoration: const InputDecoration(label: Text('Senha')), obscureText: true, onTapOutside: (_) => context.unfocus(), validator: Validatorless.multiple([ Validatorless.required('Senha obrigatória'), Validatorless.min(6, 'Senha deve ter no mínimo 6 caracteres'), ]), ), const SizedBox(height: 24), TextFormField( decoration: const InputDecoration(label: Text('Confirmar senha')), obscureText: true, onTapOutside: (_) => context.unfocus(), validator: Validatorless.multiple([ Validatorless.required('Senha obrigatória'), Validatorless.compare( passwordController, 'Senhas não conferem', ), ]), ), const SizedBox(height: 24), ElevatedButton( onPressed: () => switch (formKey.currentState?.validate()) { null || false => context.showError('Formulário inválido'), true => userRegisterVM.register( name: nameController.text, email: emailController.text, password: passwordController.text, ), }, style: ElevatedButton.styleFrom( minimumSize: const Size.fromHeight(56), ), child: const Text('CRIAR CONTA'), ), ], ), ), ); } }
0
mirrored_repositories/barbershop/lib/src/features/auth/register
mirrored_repositories/barbershop/lib/src/features/auth/register/user/user_register_vm.g.dart
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'user_register_vm.dart'; // ************************************************************************** // RiverpodGenerator // ************************************************************************** String _$userRegisterVMHash() => r'7bcd4f23c5668eff8678e81a961183735f68a823'; /// See also [UserRegisterVM]. @ProviderFor(UserRegisterVM) final userRegisterVMProvider = AutoDisposeNotifierProvider<UserRegisterVM, UserRegisterStateStatus>.internal( UserRegisterVM.new, name: r'userRegisterVMProvider', debugGetCreateSourceHash: const bool.fromEnvironment('dart.vm.product') ? null : _$userRegisterVMHash, dependencies: null, allTransitiveDependencies: null, ); typedef _$UserRegisterVM = AutoDisposeNotifier<UserRegisterStateStatus>; // ignore_for_file: type=lint // ignore_for_file: subtype_of_sealed_class, invalid_use_of_internal_member
0
mirrored_repositories/barbershop/lib/src/features/auth/register
mirrored_repositories/barbershop/lib/src/features/auth/register/barbershop/barbershop_register_vm.g.dart
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'barbershop_register_vm.dart'; // ************************************************************************** // RiverpodGenerator // ************************************************************************** String _$barbershopRegisterVMHash() => r'1b87e3d0ce260f8ac1ec0e3361409d4e38971958'; /// See also [BarbershopRegisterVM]. @ProviderFor(BarbershopRegisterVM) final barbershopRegisterVMProvider = AutoDisposeNotifierProvider< BarbershopRegisterVM, BarbershopRegisterState>.internal( BarbershopRegisterVM.new, name: r'barbershopRegisterVMProvider', debugGetCreateSourceHash: const bool.fromEnvironment('dart.vm.product') ? null : _$barbershopRegisterVMHash, dependencies: null, allTransitiveDependencies: null, ); typedef _$BarbershopRegisterVM = AutoDisposeNotifier<BarbershopRegisterState>; // ignore_for_file: type=lint // ignore_for_file: subtype_of_sealed_class, invalid_use_of_internal_member
0
mirrored_repositories/barbershop/lib/src/features/auth/register
mirrored_repositories/barbershop/lib/src/features/auth/register/barbershop/barbershop_register_page.dart
import 'package:barbershop/src/core/fp/nil.dart'; import 'package:barbershop/src/core/ui/helpers/form_helper.dart'; import 'package:barbershop/src/core/ui/helpers/messages.dart'; import 'package:barbershop/src/core/ui/widgets/hours_panel.dart'; import 'package:barbershop/src/core/ui/widgets/weekdays_panel.dart'; import 'package:barbershop/src/features/auth/register/barbershop/barbershop_register_status.dart'; import 'package:barbershop/src/features/auth/register/barbershop/barbershop_register_vm.dart'; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:validatorless/validatorless.dart'; final class BarbershopRegisterPage extends ConsumerStatefulWidget { const BarbershopRegisterPage({super.key}); @override ConsumerState<BarbershopRegisterPage> createState() => _BarbershopRegisterPageState(); } final class _BarbershopRegisterPageState extends ConsumerState<BarbershopRegisterPage> { final formKey = GlobalKey<FormState>(); final nameController = TextEditingController(); final emailController = TextEditingController(); @override void dispose() { nameController.dispose(); emailController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { final BarbershopRegisterVM( :addOrRemoveOpeningDays, :addOrRemoveOpeningHours, :register, ) = ref.watch(barbershopRegisterVMProvider.notifier); ref.listen( barbershopRegisterVMProvider, (_, state) => switch (state.status) { BarbershopRegisterStateStatus.initial => nil, BarbershopRegisterStateStatus.error => context.showError('Erro ao cadastrar estabelecimento'), BarbershopRegisterStateStatus.success => Navigator.of(context) .pushNamedAndRemoveUntil('/home/adm', (_) => false), }, ); return Scaffold( appBar: AppBar(title: const Text('Cadastrar estabelecimento')), body: Form( key: formKey, child: ListView( padding: const EdgeInsets.all(20), children: [ const SizedBox(height: 5), TextFormField( controller: nameController, decoration: const InputDecoration(label: Text('Nome')), onTapOutside: (_) => context.unfocus(), validator: Validatorless.required('Nome obrigatório'), ), const SizedBox(height: 24), TextFormField( controller: emailController, decoration: const InputDecoration(label: Text('E-mail')), onTapOutside: (_) => context.unfocus(), keyboardType: TextInputType.emailAddress, validator: Validatorless.multiple([ Validatorless.required('E-mail obrigatório'), Validatorless.email('E-mail inválido'), ]), ), const SizedBox(height: 24), WeekdaysPanel( onDayPressed: addOrRemoveOpeningDays, ), const SizedBox(height: 24), HoursPanel( startTime: 6, endTime: 23, onTimePressed: addOrRemoveOpeningHours, ), const SizedBox(height: 24), ElevatedButton( onPressed: () => switch (formKey.currentState?.validate()) { false || null => context.showError('Formulário inválido'), true => register( name: nameController.text, email: emailController.text, ), }, style: ElevatedButton.styleFrom( minimumSize: const Size.fromHeight(56), ), child: const Text('Cadastrar estabelecimento'), ), ], ), ), ); } }
0
mirrored_repositories/barbershop/lib/src/features/auth/register
mirrored_repositories/barbershop/lib/src/features/auth/register/barbershop/barbershop_register_status.dart
enum BarbershopRegisterStateStatus { initial, success, error, } final class BarbershopRegisterState { const BarbershopRegisterState({ required this.status, required this.openingDays, required this.openingHours, }); BarbershopRegisterState.initial() : status = BarbershopRegisterStateStatus.initial, openingDays = [], openingHours = []; final BarbershopRegisterStateStatus status; final List<String> openingDays; final List<int> openingHours; BarbershopRegisterState copyWith({ BarbershopRegisterStateStatus? status, List<String>? openingDays, List<int>? openingHours, }) => BarbershopRegisterState( status: status ?? this.status, openingDays: openingDays ?? this.openingDays, openingHours: openingHours ?? this.openingHours, ); }
0
mirrored_repositories/barbershop/lib/src/features/auth/register
mirrored_repositories/barbershop/lib/src/features/auth/register/barbershop/barbershop_register_vm.dart
import 'package:barbershop/src/core/fp/either.dart'; import 'package:barbershop/src/core/providers/application_providers.dart'; import 'package:barbershop/src/features/auth/register/barbershop/barbershop_register_status.dart'; import 'package:riverpod_annotation/riverpod_annotation.dart'; part 'barbershop_register_vm.g.dart'; @riverpod class BarbershopRegisterVM extends _$BarbershopRegisterVM { @override BarbershopRegisterState build() => BarbershopRegisterState.initial(); void addOrRemoveOpeningDays(String weekDay) { final openingDays = state.openingDays; if (openingDays.contains(weekDay)) { openingDays.remove(weekDay); } else { openingDays.add(weekDay); } state = state.copyWith(openingDays: openingDays); } void addOrRemoveOpeningHours(int hour) { final openingHours = state.openingHours; if (openingHours.contains(hour)) { openingHours.remove(hour); } else { openingHours.add(hour); } state = state.copyWith(openingHours: openingHours); } Future<void> register({ required String name, required String email, }) async { final repository = ref.watch(barbershopRepositoryProvider); final BarbershopRegisterState(:openingDays, :openingHours) = state; final dto = ( name: name, email: email, openingDays: openingDays, openingHours: openingHours, ); final registerResult = await repository.save(dto); switch (registerResult) { case Success(): ref.invalidate(getMyBarbershopProvider); state = state.copyWith(status: BarbershopRegisterStateStatus.success); case Failure(): state = state.copyWith(status: BarbershopRegisterStateStatus.error); } } }
0
mirrored_repositories/barbershop/lib/src/features/home
mirrored_repositories/barbershop/lib/src/features/home/widgets/home_header.dart
import 'package:barbershop/src/core/constants/constants.dart'; import 'package:barbershop/src/core/providers/application_providers.dart'; import 'package:barbershop/src/core/ui/barbershop_icons.dart'; import 'package:barbershop/src/core/ui/widgets/barbershop_loader.dart'; import 'package:barbershop/src/features/home/adm/home_adm_vm.dart'; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; class HomeHeader extends ConsumerWidget { const HomeHeader({super.key}) : hideFilter = true; const HomeHeader.withoutFilter({super.key}) : hideFilter = false; final bool hideFilter; @override Widget build(BuildContext context, WidgetRef ref) { final barberShop = ref.watch(getMyBarbershopProvider); return Container( width: MediaQuery.sizeOf(context).width, padding: const EdgeInsets.all(16), decoration: const BoxDecoration( color: Colors.black, borderRadius: BorderRadius.only( bottomLeft: Radius.circular(32), bottomRight: Radius.circular(32), ), image: DecorationImage( fit: BoxFit.cover, opacity: 0.5, image: AssetImage( AppImages.backgroundChair, ), ), ), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ SizedBox(height: MediaQuery.maybeViewPaddingOf(context)?.top), barberShop.maybeWhen( orElse: () => const Center( child: BarbershopLoader(), ), data: (barbershop) => Row( children: [ const CircleAvatar( backgroundColor: Color(0xffbdbdbd), child: SizedBox.shrink(), ), const SizedBox(width: 16), Expanded( child: Text( barbershop.name, overflow: TextOverflow.ellipsis, maxLines: 1, style: const TextStyle( color: Colors.white, fontSize: 14, fontWeight: FontWeight.bold, ), ), ), const Spacer(), const Text( 'Editar', style: TextStyle( color: AppColors.brown, fontSize: 12, fontWeight: FontWeight.w700, ), ), IconButton( alignment: Alignment.centerRight, onPressed: () { ref.read(homeADMVMProvider.notifier).logout(); }, icon: const Icon( BarbershopIcons.exit, color: AppColors.brown, size: 32, ), ), ], ), ), const SizedBox(height: 24), const Text( 'Bem-vindo', style: TextStyle( color: Colors.white, fontWeight: FontWeight.w500, fontSize: 18, ), ), const SizedBox(height: 24), const Text( 'Agende um Cliente', style: TextStyle( color: Colors.white, fontWeight: FontWeight.w600, fontSize: 40, ), ), Offstage( offstage: hideFilter, child: const SizedBox(height: 24), ), Offstage( offstage: hideFilter, child: TextFormField( decoration: const InputDecoration( hintText: 'Buscar colaborador', suffixIcon: Padding( padding: EdgeInsets.only(right: 24), child: Icon( BarbershopIcons.search, color: AppColors.brown, ), ), ), ), ), ], ), ); } }
0
mirrored_repositories/barbershop/lib/src/features/home
mirrored_repositories/barbershop/lib/src/features/home/adm/home_adm_vm.dart
import 'package:asyncstate/asyncstate.dart'; import 'package:barbershop/src/core/fp/either.dart'; import 'package:barbershop/src/core/providers/application_providers.dart'; import 'package:barbershop/src/features/home/adm/home_adm_state.dart'; import 'package:barbershop/src/models/barbershop_model.dart'; import 'package:barbershop/src/models/user_model.dart'; import 'package:riverpod_annotation/riverpod_annotation.dart'; part 'home_adm_vm.g.dart'; @riverpod class HomeADMVM extends _$HomeADMVM { @override Future<HomeADMState> build() async { final repository = ref.read(userRepositoryProvider); final BarbershopModel(id: barbershopId) = await ref.read(getMyBarbershopProvider.future); final me = await ref.watch(getMeProvider.future); final employeesResult = await repository.getEmployees(barbershopId); switch (employeesResult) { case Success(value: final employeesData): final employees = <UserModel>[]; if (me case UserModelADM(workDays: _?, workHours: _?)) { employees.add(me); } employees.addAll(employeesData); return HomeADMState( status: HomeADMStateStatus.loaded, employees: employees, ); case Failure(): return HomeADMState( status: HomeADMStateStatus.error, employees: [], ); } } Future<void> logout() async => ref.watch(logoutProvider.future).asyncLoader(); }
0
mirrored_repositories/barbershop/lib/src/features/home
mirrored_repositories/barbershop/lib/src/features/home/adm/home_adm_page.dart
import 'dart:developer'; import 'package:barbershop/src/core/constants/constants.dart'; import 'package:barbershop/src/core/providers/application_providers.dart'; import 'package:barbershop/src/core/ui/barbershop_icons.dart'; import 'package:barbershop/src/core/ui/widgets/barbershop_loader.dart'; import 'package:barbershop/src/features/home/adm/home_adm_state.dart'; import 'package:barbershop/src/features/home/adm/home_adm_vm.dart'; import 'package:barbershop/src/features/home/adm/widgets/home_employee_tile.dart'; import 'package:barbershop/src/features/home/widgets/home_header.dart'; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; class HomeADMPage extends ConsumerWidget { const HomeADMPage({super.key}); @override Widget build(BuildContext context, WidgetRef ref) { final homeState = ref.watch(homeADMVMProvider); return Scaffold( floatingActionButton: FloatingActionButton( onPressed: () async { await Navigator.of(context).pushNamed('/employee/register'); ref.invalidate(getMeProvider); ref.invalidate(homeADMVMProvider); }, shape: const CircleBorder(), backgroundColor: AppColors.brown, child: const CircleAvatar( backgroundColor: Colors.white, maxRadius: 12, child: Icon( BarbershopIcons.addEmployee, color: AppColors.brown, ), ), ), body: homeState.when( loading: () => const BarbershopLoader(), error: (e, s) { log('UI Erro ao buscar colaboradores', error: e, stackTrace: s); return Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ const Text( 'Erro ao carregar página.', style: TextStyle(color: Colors.black), ), TextButton( onPressed: () { ref.read(homeADMVMProvider.notifier).logout(); }, child: const Text('Deslogar'), ), ], ), ); }, data: (HomeADMState data) => CustomScrollView( slivers: [ const SliverToBoxAdapter( child: HomeHeader(), ), SliverList( delegate: SliverChildBuilderDelegate( childCount: data.employees.length, (context, index) => HomeEmployeeTile( employee: data.employees[index], ), ), ), ], ), ), ); } }
0
mirrored_repositories/barbershop/lib/src/features/home
mirrored_repositories/barbershop/lib/src/features/home/adm/home_adm_vm.g.dart
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'home_adm_vm.dart'; // ************************************************************************** // RiverpodGenerator // ************************************************************************** String _$homeADMVMHash() => r'19872c31fb8946de05cfe416e4300e854b8f4c4c'; /// See also [HomeADMVM]. @ProviderFor(HomeADMVM) final homeADMVMProvider = AutoDisposeAsyncNotifierProvider<HomeADMVM, HomeADMState>.internal( HomeADMVM.new, name: r'homeADMVMProvider', debugGetCreateSourceHash: const bool.fromEnvironment('dart.vm.product') ? null : _$homeADMVMHash, dependencies: null, allTransitiveDependencies: null, ); typedef _$HomeADMVM = AutoDisposeAsyncNotifier<HomeADMState>; // ignore_for_file: type=lint // ignore_for_file: subtype_of_sealed_class, invalid_use_of_internal_member
0
mirrored_repositories/barbershop/lib/src/features/home
mirrored_repositories/barbershop/lib/src/features/home/adm/home_adm_state.dart
import 'package:barbershop/src/models/user_model.dart'; enum HomeADMStateStatus { loaded, error } class HomeADMState { HomeADMState({ required this.status, required this.employees, }); final HomeADMStateStatus status; final List<UserModel> employees; HomeADMState copyWith({ HomeADMStateStatus? status, List<UserModel>? employees, }) => HomeADMState( status: status ?? this.status, employees: employees ?? this.employees, ); }
0
mirrored_repositories/barbershop/lib/src/features/home/adm
mirrored_repositories/barbershop/lib/src/features/home/adm/widgets/home_employee_tile.dart
import 'package:barbershop/src/core/constants/constants.dart'; import 'package:barbershop/src/core/ui/barbershop_icons.dart'; import 'package:barbershop/src/models/user_model.dart'; import 'package:flutter/material.dart'; class HomeEmployeeTile extends StatelessWidget { const HomeEmployeeTile({ super.key, required this.employee, }); final UserModel employee; @override Widget build(BuildContext context) { return Container( width: MediaQuery.sizeOf(context).width, margin: const EdgeInsets.symmetric(horizontal: 12, vertical: 8), padding: const EdgeInsets.all(8), decoration: BoxDecoration( borderRadius: BorderRadius.circular(8), border: Border.all(color: AppColors.grey), ), child: Row( children: [ Container( width: 56, height: 56, decoration: BoxDecoration( color: AppColors.grey, borderRadius: BorderRadius.circular(8), image: DecorationImage( fit: BoxFit.cover, image: switch (employee.avatar) { final avatar? => NetworkImage(avatar), _ => const AssetImage(AppImages.avatar), } as ImageProvider<Object>, ), ), ), const SizedBox(width: 12), Expanded( child: Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( employee.name, style: const TextStyle( fontWeight: FontWeight.w500, fontSize: 16, ), ), const SizedBox(height: 8), Row( mainAxisAlignment: MainAxisAlignment.spaceAround, children: [ ElevatedButton( onPressed: () { Navigator.of(context).pushNamed( '/schedule', arguments: employee, ); }, style: ElevatedButton.styleFrom( maximumSize: const Size(double.infinity, 56), padding: const EdgeInsets.symmetric(horizontal: 12), ), child: const Text('AGENDAR'), ), OutlinedButton( onPressed: () { Navigator.of(context).pushNamed( '/employee/schedule', arguments: employee, ); }, style: OutlinedButton.styleFrom( padding: const EdgeInsets.symmetric(horizontal: 8), ), child: const Text('VER AGENDA'), ), const Icon( BarbershopIcons.penEdit, color: AppColors.brown, size: 16, ), const Icon( BarbershopIcons.trash, color: AppColors.red, size: 16, ), ], ), ], ), ), ], ), ); } }
0
mirrored_repositories/barbershop/lib/src/features/home
mirrored_repositories/barbershop/lib/src/features/home/employee/home_employee_provider.g.dart
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'home_employee_provider.dart'; // ************************************************************************** // RiverpodGenerator // ************************************************************************** String _$getTotalSchedulesTodayHash() => r'ec991558c2daf303a25cafc26b1006c9065cae31'; /// Copied from Dart SDK class _SystemHash { _SystemHash._(); static int combine(int hash, int value) { // ignore: parameter_assignments hash = 0x1fffffff & (hash + value); // ignore: parameter_assignments hash = 0x1fffffff & (hash + ((0x0007ffff & hash) << 10)); return hash ^ (hash >> 6); } static int finish(int hash) { // ignore: parameter_assignments hash = 0x1fffffff & (hash + ((0x03ffffff & hash) << 3)); // ignore: parameter_assignments hash = hash ^ (hash >> 11); return 0x1fffffff & (hash + ((0x00003fff & hash) << 15)); } } typedef GetTotalSchedulesTodayRef = AutoDisposeFutureProviderRef<int>; /// See also [getTotalSchedulesToday]. @ProviderFor(getTotalSchedulesToday) const getTotalSchedulesTodayProvider = GetTotalSchedulesTodayFamily(); /// See also [getTotalSchedulesToday]. class GetTotalSchedulesTodayFamily extends Family<AsyncValue<int>> { /// See also [getTotalSchedulesToday]. const GetTotalSchedulesTodayFamily(); /// See also [getTotalSchedulesToday]. GetTotalSchedulesTodayProvider call( int userId, ) { return GetTotalSchedulesTodayProvider( userId, ); } @override GetTotalSchedulesTodayProvider getProviderOverride( covariant GetTotalSchedulesTodayProvider provider, ) { return call( provider.userId, ); } static const Iterable<ProviderOrFamily>? _dependencies = null; @override Iterable<ProviderOrFamily>? get dependencies => _dependencies; static const Iterable<ProviderOrFamily>? _allTransitiveDependencies = null; @override Iterable<ProviderOrFamily>? get allTransitiveDependencies => _allTransitiveDependencies; @override String? get name => r'getTotalSchedulesTodayProvider'; } /// See also [getTotalSchedulesToday]. class GetTotalSchedulesTodayProvider extends AutoDisposeFutureProvider<int> { /// See also [getTotalSchedulesToday]. GetTotalSchedulesTodayProvider( this.userId, ) : super.internal( (ref) => getTotalSchedulesToday( ref, userId, ), from: getTotalSchedulesTodayProvider, name: r'getTotalSchedulesTodayProvider', debugGetCreateSourceHash: const bool.fromEnvironment('dart.vm.product') ? null : _$getTotalSchedulesTodayHash, dependencies: GetTotalSchedulesTodayFamily._dependencies, allTransitiveDependencies: GetTotalSchedulesTodayFamily._allTransitiveDependencies, ); final int userId; @override bool operator ==(Object other) { return other is GetTotalSchedulesTodayProvider && other.userId == userId; } @override int get hashCode { var hash = _SystemHash.combine(0, runtimeType.hashCode); hash = _SystemHash.combine(hash, userId.hashCode); return _SystemHash.finish(hash); } } // ignore_for_file: type=lint // ignore_for_file: subtype_of_sealed_class, invalid_use_of_internal_member
0
mirrored_repositories/barbershop/lib/src/features/home
mirrored_repositories/barbershop/lib/src/features/home/employee/home_employee_provider.dart
import 'package:barbershop/src/core/fp/either.dart'; import 'package:barbershop/src/core/providers/application_providers.dart'; import 'package:riverpod_annotation/riverpod_annotation.dart'; part 'home_employee_provider.g.dart'; @riverpod Future<int> getTotalSchedulesToday( GetTotalSchedulesTodayRef ref, int userId, ) async { final DateTime(:year, :month, :day) = DateTime.now(); final filter = (date: DateTime(year, month, day, 0, 0, 0), userId: userId); final scheduleResult = await ref.read(scheduleRepositoryProvider).findScheduleByDate(filter); return switch (scheduleResult) { Success(value: List(length: final totalSchedules)) => totalSchedules, Failure(:final exception) => throw exception, }; }
0
mirrored_repositories/barbershop/lib/src/features/home
mirrored_repositories/barbershop/lib/src/features/home/employee/home_employee_page.dart
import 'dart:developer'; import 'package:barbershop/src/core/constants/constants.dart'; import 'package:barbershop/src/core/providers/application_providers.dart'; import 'package:barbershop/src/core/ui/widgets/avatar_widget.dart'; import 'package:barbershop/src/core/ui/widgets/barbershop_loader.dart'; import 'package:barbershop/src/features/home/employee/home_employee_provider.dart'; import 'package:barbershop/src/features/home/widgets/home_header.dart'; import 'package:barbershop/src/models/user_model.dart'; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; class HomeEmployeePage extends ConsumerWidget { const HomeEmployeePage({super.key}); @override Widget build(BuildContext context, WidgetRef ref) { final userModelAsync = ref.watch(getMeProvider); return Scaffold( body: userModelAsync.when( error: (e, s) { const errorMessage = 'Erro ao carregar página'; log(errorMessage, error: e, stackTrace: s); return const Center( child: Text(errorMessage), ); }, loading: () => const BarbershopLoader(), data: (user) { final UserModel(:id, :name) = user; return CustomScrollView( slivers: [ const SliverToBoxAdapter( child: HomeHeader(), ), SliverFillRemaining( hasScrollBody: false, child: Padding( padding: const EdgeInsets.all(24), child: Column( children: [ const AvatarWidget.withoutButton(), const SizedBox(height: 24), Text( name, style: const TextStyle( fontSize: 20, fontWeight: FontWeight.w500, ), ), const SizedBox(height: 20), Container( width: MediaQuery.of(context).size.width * .7, height: 108, decoration: BoxDecoration( border: Border.all(color: AppColors.grey), borderRadius: BorderRadius.circular(8), ), child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Consumer( builder: (context, ref, child) { final totalAsync = ref.watch( getTotalSchedulesTodayProvider(id), ); return totalAsync.when( error: (e, s) { const errorMessage = 'Erro ao carregar total de agendamentos'; return const Text(errorMessage); }, loading: () => const BarbershopLoader(), skipLoadingOnRefresh: false, data: (totalScheduule) { return Text( '$totalScheduule', style: const TextStyle( fontSize: 40, color: AppColors.brown, fontWeight: FontWeight.w600, ), ); }, ); }, ), const Text( 'Hoje', style: TextStyle( fontSize: 16, color: AppColors.brown, fontWeight: FontWeight.w600, ), ), ], ), ), const SizedBox(height: 24), ElevatedButton( onPressed: () async { await Navigator.of(context).pushNamed( '/schedule', arguments: user, ); ref.invalidate(getTotalSchedulesTodayProvider(id)); }, style: ElevatedButton.styleFrom( minimumSize: const Size.fromHeight(56), ), child: const Text('AGENDAR CLIENTE'), ), const SizedBox(height: 24), OutlinedButton( style: ElevatedButton.styleFrom( minimumSize: const Size.fromHeight(56), ), onPressed: () { Navigator.of(context).pushNamed( '/employee/schedule', arguments: user, ); }, child: const Text('VER AGENDA'), ), ], ), ), ), ], ); }, ), ); } }
0
mirrored_repositories/barbershop/lib/src/features
mirrored_repositories/barbershop/lib/src/features/splash/splash_vm.dart
import 'package:barbershop/src/core/constants/constants.dart'; import 'package:barbershop/src/core/providers/application_providers.dart'; import 'package:barbershop/src/models/user_model.dart'; import 'package:riverpod_annotation/riverpod_annotation.dart'; import 'package:shared_preferences/shared_preferences.dart'; part 'splash_vm.g.dart'; enum SplashState { initial, login, loggedADM, loggedEmployee, } @riverpod class SplashVM extends _$SplashVM { @override Future<SplashState> build() async { final sharedPreferences = await SharedPreferences.getInstance(); if (sharedPreferences.containsKey(LocalStorageKeys.accessToken)) { ref.invalidate(getMeProvider); ref.invalidate(getMyBarbershopProvider); try { final userModel = await ref.watch(getMeProvider.future); return switch (userModel) { UserModelADM() => SplashState.loggedADM, UserModelEmployee() => SplashState.loggedEmployee, }; } catch (e) { return SplashState.login; } } return SplashState.login; } }
0
mirrored_repositories/barbershop/lib/src/features
mirrored_repositories/barbershop/lib/src/features/splash/splash_vm.g.dart
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'splash_vm.dart'; // ************************************************************************** // RiverpodGenerator // ************************************************************************** String _$splashVMHash() => r'6931c5d24c20266edcd793e0975ca247895c710d'; /// See also [SplashVM]. @ProviderFor(SplashVM) final splashVMProvider = AutoDisposeAsyncNotifierProvider<SplashVM, SplashState>.internal( SplashVM.new, name: r'splashVMProvider', debugGetCreateSourceHash: const bool.fromEnvironment('dart.vm.product') ? null : _$splashVMHash, dependencies: null, allTransitiveDependencies: null, ); typedef _$SplashVM = AutoDisposeAsyncNotifier<SplashState>; // ignore_for_file: type=lint // ignore_for_file: subtype_of_sealed_class, invalid_use_of_internal_member
0
mirrored_repositories/barbershop/lib/src/features
mirrored_repositories/barbershop/lib/src/features/splash/splash_page.dart
import 'dart:developer'; import 'package:barbershop/src/core/constants/constants.dart'; import 'package:barbershop/src/core/ui/helpers/messages.dart'; import 'package:barbershop/src/features/auth/login/login_page.dart'; import 'package:barbershop/src/features/splash/splash_vm.dart'; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; final class SplashPage extends ConsumerStatefulWidget { const SplashPage({super.key}); @override ConsumerState<SplashPage> createState() => _SplashPageState(); } final class _SplashPageState extends ConsumerState<SplashPage> { var _scale = 10.0; var _animationOpacityLogo = 0.0; double get _logoAnimationWidth => 150 * _scale; double get _logoAnimationHeight => 170 * _scale; @override void initState() { super.initState(); WidgetsBinding.instance.addPostFrameCallback((_) { setState(() { _animationOpacityLogo = 1.0; _scale = 1.0; }); }); } @override Widget build(BuildContext context) { ref.listen(splashVMProvider, (_, state) { state.whenOrNull( error: (e, s) { log('Erro ao validar login', error: e, stackTrace: s); context.showError('Erro ao validar login'); Navigator.of(context) .pushNamedAndRemoveUntil('/auth/login', (_) => false); }, data: (data) => switch (data) { SplashState.loggedADM => Navigator.of(context) .pushNamedAndRemoveUntil('/home/adm', (_) => false), SplashState.loggedEmployee => Navigator.of(context) .pushNamedAndRemoveUntil('/home/employee', (_) => false), _ => Navigator.of(context) .pushNamedAndRemoveUntil('/auth/login', (_) => false), }, ); }); return Scaffold( backgroundColor: Colors.black, body: DecoratedBox( decoration: const BoxDecoration( image: DecorationImage( image: AssetImage(AppImages.backgroundChair), fit: BoxFit.cover, opacity: 0.2, ), ), child: Center( child: AnimatedOpacity( opacity: _animationOpacityLogo, curve: Curves.easeIn, duration: const Duration(seconds: 3), onEnd: () => Navigator.of(context).pushAndRemoveUntil<void>( PageRouteBuilder( pageBuilder: (_, __, ___) => const LoginPage(), transitionsBuilder: (_, animation, __, child) => FadeTransition(opacity: animation, child: child), ), (_) => false, ), child: AnimatedContainer( width: _logoAnimationWidth, height: _logoAnimationHeight, curve: Curves.linearToEaseOut, duration: const Duration(seconds: 3), child: Image.asset( AppImages.imgLogo, fit: BoxFit.cover, ), ), ), ), ), ); } }
0
mirrored_repositories/barbershop/lib/src
mirrored_repositories/barbershop/lib/src/models/schedule_model.dart
class ScheduleModel { ScheduleModel({ required this.id, required this.barbershopId, required this.userId, required this.clientName, required this.date, required this.hour, }); factory ScheduleModel.fromMap(Map<String, dynamic> json) { switch (json) { case { 'id': int id, 'barbershop_id': int barbershopId, 'user_id': int userId, 'client_name': String clientName, 'date': String scheduleDate, 'time': int hour, }: return ScheduleModel( id: id, barbershopId: barbershopId, userId: userId, clientName: clientName, date: DateTime.parse(scheduleDate), hour: hour, ); case _: throw ArgumentError('Invalid JSON: $json'); } } final int id, barbershopId, userId, hour; final String clientName; final DateTime date; }
0
mirrored_repositories/barbershop/lib/src
mirrored_repositories/barbershop/lib/src/models/barbershop_model.dart
final class BarbershopModel { const BarbershopModel({ required this.id, required this.name, required this.email, required this.openDays, required this.openHours, }); factory BarbershopModel.fromMap(Map<String, dynamic> json) { return switch (json) { { 'id': int id, 'name': String name, 'email': String email, 'opening_days': final List openDays, 'opening_hours': final List openHours, } => BarbershopModel( id: id, name: name, email: email, openDays: openDays.cast<String>(), openHours: openHours.cast<int>(), ), _ => throw ArgumentError('Invalid BarbershopModel JSON: $json'), }; } final int id; final String name; final String email; final List<String> openDays; final List<int> openHours; }
0
mirrored_repositories/barbershop/lib/src
mirrored_repositories/barbershop/lib/src/models/user_model.dart
sealed class UserModel { UserModel({ required this.id, required this.name, required this.email, this.avatar, }); factory UserModel.fromMap(Map<String, dynamic> json) { return switch (json['profile']) { 'ADM' => UserModelADM.fromMap(json), 'EMPLOYEE' => UserModelEmployee.fromMap(json), _ => throw ArgumentError('User profile not found'), }; } final int id; final String name, email; final String? avatar; } class UserModelADM extends UserModel { UserModelADM({ required super.id, required super.name, required super.email, super.avatar, this.workDays, this.workHours, }); factory UserModelADM.fromMap(Map<String, dynamic> json) { return switch (json) { { 'id': final int id, 'name': final String name, 'email': final String email, } => UserModelADM( id: id, name: name, email: email, avatar: json['avatar'], // ignore: avoid_dynamic_calls workDays: json['work_days']?.cast<String>(), // ignore: avoid_dynamic_calls workHours: json['work_hours']?.cast<int>(), ), _ => throw ArgumentError('Invalid Json'), }; } final List<String>? workDays; final List<int>? workHours; } class UserModelEmployee extends UserModel { UserModelEmployee({ required super.id, required super.name, required super.email, required this.barbershopId, super.avatar, required this.workDays, required this.workHours, }); factory UserModelEmployee.fromMap(Map<String, dynamic> json) { return switch (json) { { 'id': final int id, 'name': final String name, 'email': final String email, 'barbershop_id': final int barbershopId, 'work_days': final List workDays, 'work_hours': final List workHours, } => UserModelEmployee( id: id, name: name, email: email, workDays: workDays.cast<String>(), workHours: workHours.cast<int>(), avatar: json['avatar'], barbershopId: barbershopId, ), _ => throw ArgumentError('Invalid UserModelEmployee JSON: $json'), }; } final List<String> workDays; final List<int> workHours; final int barbershopId; }
0
mirrored_repositories/barbershop/lib/src/core
mirrored_repositories/barbershop/lib/src/core/constants/app_colors.dart
import 'package:flutter/material.dart'; sealed class AppColors { static const brown = Color(0xFFB07B01); static const grey = Color(0xFF999999); static const lightGrey = Color(0xFFE6E2E9); static const red = Color(0xFFEB1212); }
0
mirrored_repositories/barbershop/lib/src/core
mirrored_repositories/barbershop/lib/src/core/constants/app_fonts.dart
sealed class AppFonts { static const String fontFamily = 'Poppins'; }
0
mirrored_repositories/barbershop/lib/src/core
mirrored_repositories/barbershop/lib/src/core/constants/constants.dart
export 'app_colors.dart'; export 'app_fonts.dart'; export 'app_images.dart'; export 'local_storage_keys.dart';
0
mirrored_repositories/barbershop/lib/src/core
mirrored_repositories/barbershop/lib/src/core/constants/app_images.dart
sealed class AppImages { static const backgroundChair = 'assets/images/background_image_chair.jpg'; static const imgLogo = 'assets/images/imgLogo.png'; static const avatar = 'assets/images/avatar.png'; }
0
mirrored_repositories/barbershop/lib/src/core
mirrored_repositories/barbershop/lib/src/core/constants/local_storage_keys.dart
sealed class LocalStorageKeys { static const accessToken = 'ACCESS_TOKEN_KEY'; }
0
mirrored_repositories/barbershop/lib/src/core
mirrored_repositories/barbershop/lib/src/core/rest_client/rest_client.dart
import 'package:barbershop/src/core/rest_client/interceptors/auth_interceptor.dart'; import 'package:dio/dio.dart'; import 'package:dio/io.dart'; import 'package:pretty_dio_logger/pretty_dio_logger.dart'; final class RestClient extends DioForNative { RestClient() : super( BaseOptions( connectTimeout: const Duration(seconds: 10), receiveTimeout: const Duration(seconds: 60), baseUrl: 'http://192.168.1.14:8080', ), ) { interceptors.addAll([ AuthInterceptor(), PrettyDioLogger(), ]); } RestClient get auth => this..options.extra['DIO_AUTH_KEY'] = true; RestClient get unAuth => this..options.extra['DIO_AUTH_KEY'] = false; }
0
mirrored_repositories/barbershop/lib/src/core/rest_client
mirrored_repositories/barbershop/lib/src/core/rest_client/interceptors/auth_interceptor.dart
import 'dart:io'; import 'package:barbershop/src/core/constants/local_storage_keys.dart'; import 'package:barbershop/src/core/ui/barbershop_nav_global_key.dart'; import 'package:dio/dio.dart'; import 'package:flutter/material.dart'; import 'package:shared_preferences/shared_preferences.dart'; final class AuthInterceptor extends Interceptor { @override Future<void> onRequest( RequestOptions options, RequestInterceptorHandler handler, ) async { final RequestOptions(:headers, :extra) = options; headers.remove(HttpHeaders.authorizationHeader); if (extra case {'DIO_AUTH_KEY': true}) { final sharedPreferences = await SharedPreferences.getInstance(); headers.addAll({ HttpHeaders.authorizationHeader: 'Bearer ${sharedPreferences.getString(LocalStorageKeys.accessToken)}', }); } return handler.next(options); } @override Future<void> onError( DioException err, ErrorInterceptorHandler handler, ) async { super.onError(err, handler); final DioException(requestOptions: RequestOptions(:extra), :response) = err; if (extra case {'DIO_AUTH_KEY': true}) { if (response != null && response.statusCode == HttpStatus.forbidden) { Navigator.of( BarbershopNavGlobalKey.instance.navKey.currentContext!, ).pushNamedAndRemoveUntil('/auth/login', ((route) => false)); } } return handler.reject(err); } }
0
mirrored_repositories/barbershop/lib/src/core
mirrored_repositories/barbershop/lib/src/core/exceptions/repository_exception.dart
final class RepositoryException implements Exception { const RepositoryException({required this.message}); final String message; }
0
mirrored_repositories/barbershop/lib/src/core
mirrored_repositories/barbershop/lib/src/core/exceptions/auth_exception.dart
sealed class AuthException implements Exception { const AuthException({required this.message}); final String message; } final class AuthError extends AuthException { const AuthError({required super.message}); } final class AuthUnauthorizedException extends AuthException { const AuthUnauthorizedException({super.message = ''}); }
0
mirrored_repositories/barbershop/lib/src/core
mirrored_repositories/barbershop/lib/src/core/exceptions/service_exception.dart
final class ServiceException implements Exception { const ServiceException({required this.message}); final String message; }
0
mirrored_repositories/barbershop/lib/src/core
mirrored_repositories/barbershop/lib/src/core/ui/barbershop_nav_global_key.dart
import 'package:flutter/widgets.dart'; final class BarbershopNavGlobalKey { BarbershopNavGlobalKey._(); final navKey = GlobalKey<NavigatorState>(); static BarbershopNavGlobalKey? _instance; static BarbershopNavGlobalKey get instance => _instance ??= BarbershopNavGlobalKey._(); }
0
mirrored_repositories/barbershop/lib/src/core
mirrored_repositories/barbershop/lib/src/core/ui/barbershop_theme.dart
import 'package:barbershop/src/core/constants/constants.dart'; import 'package:flutter/material.dart'; const _defaultInputBorder = OutlineInputBorder( borderSide: BorderSide(color: AppColors.grey), borderRadius: BorderRadius.all(Radius.circular(8)), ); sealed class BarbershopTheme { static ThemeData themeData = ThemeData( useMaterial3: true, fontFamily: AppFonts.fontFamily, inputDecorationTheme: InputDecorationTheme( filled: true, fillColor: Colors.white, border: _defaultInputBorder, labelStyle: const TextStyle(color: AppColors.grey), focusedBorder: _defaultInputBorder, errorBorder: _defaultInputBorder.copyWith( borderSide: const BorderSide(color: AppColors.red), ), ), appBarTheme: const AppBarTheme( iconTheme: IconThemeData(color: AppColors.brown), centerTitle: true, backgroundColor: Colors.white, titleTextStyle: TextStyle( color: Colors.black, fontSize: 18, fontWeight: FontWeight.w500, fontFamily: AppFonts.fontFamily, ), ), elevatedButtonTheme: ElevatedButtonThemeData( style: ElevatedButton.styleFrom( backgroundColor: AppColors.brown, foregroundColor: Colors.white, shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)), ), ), outlinedButtonTheme: OutlinedButtonThemeData( style: ElevatedButton.styleFrom( foregroundColor: AppColors.brown, side: const BorderSide(color: AppColors.brown, width: 1), shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)), ), ), ); }
0
mirrored_repositories/barbershop/lib/src/core
mirrored_repositories/barbershop/lib/src/core/ui/barbershop_icons.dart
import 'package:flutter/material.dart'; class BarbershopIcons { static const String _fontFamily = 'barbershop_icons'; static const IconData addEmployee = IconData(0xe900, fontFamily: _fontFamily); static const changeAvatar = IconData(0xe901, fontFamily: _fontFamily); static const exit = IconData(0xe902, fontFamily: _fontFamily); static const calendar = IconData(0xe909, fontFamily: _fontFamily); static const search = IconData(0xe943, fontFamily: _fontFamily); static const penEdit = IconData(0xe944, fontFamily: _fontFamily); static const trash = IconData(0xe945, fontFamily: _fontFamily); }
0
mirrored_repositories/barbershop/lib/src/core/ui
mirrored_repositories/barbershop/lib/src/core/ui/widgets/hours_panel.dart
import 'package:barbershop/src/core/constants/constants.dart'; import 'package:flutter/material.dart'; class HoursPanel extends StatefulWidget { const HoursPanel({ super.key, this.enabledTimes, required this.startTime, required this.endTime, required this.onTimePressed, }) : singleSelection = false; const HoursPanel.singleSelection({ super.key, this.enabledTimes, required this.startTime, required this.endTime, required this.onTimePressed, }) : singleSelection = true; final List<int>? enabledTimes; final int startTime, endTime; final ValueChanged<int> onTimePressed; final bool singleSelection; @override State<HoursPanel> createState() => _HoursPanelState(); } class _HoursPanelState extends State<HoursPanel> { int? lastSelection; @override Widget build(BuildContext context) { final HoursPanel(:singleSelection) = widget; return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ const Text( 'Selecione os horários de atendimento', style: TextStyle( fontSize: 14, fontWeight: FontWeight.w500, ), ), const SizedBox(height: 16), Wrap( spacing: 8, runSpacing: 16, children: [ for (int i = widget.startTime; i <= widget.endTime; i++) TimeButton( enabledTimes: widget.enabledTimes, label: '${i.toString().padLeft(2, '0')}:00', value: i, timeSelected: lastSelection, singleSelection: singleSelection, onPressed: (timeSelected) { setState(() { if (singleSelection) { if (lastSelection == timeSelected) { lastSelection = null; } else { lastSelection = timeSelected; } } }); widget.onTimePressed(timeSelected); }, ), ], ), ], ); } } class TimeButton extends StatefulWidget { const TimeButton({ super.key, this.enabledTimes, required this.label, required this.value, required this.onPressed, required this.singleSelection, required this.timeSelected, }); final List<int>? enabledTimes; final String label; final int value; final ValueChanged<int> onPressed; final bool singleSelection; final int? timeSelected; @override State<TimeButton> createState() => _TimeButtonState(); } class _TimeButtonState extends State<TimeButton> { var selected = false; @override Widget build(BuildContext context) { final TimeButton( :singleSelection, :timeSelected, :value, :label, :enabledTimes, :onPressed, ) = widget; if (singleSelection && timeSelected != null) { selected = timeSelected == value; } final textColor = selected ? Colors.white : AppColors.grey; var buttonColor = selected ? AppColors.brown : Colors.white; final buttonBorderColor = selected ? AppColors.brown : AppColors.grey; final disableTime = enabledTimes != null && !enabledTimes.contains(value); if (disableTime) { buttonColor = Colors.grey[400]!; } return InkWell( borderRadius: BorderRadius.circular(8), onTap: disableTime ? null : () { setState(() { selected = !selected; onPressed(value); }); }, child: Container( width: 64, height: 36, decoration: BoxDecoration( borderRadius: BorderRadius.circular(8), color: buttonColor, border: Border.all(color: buttonBorderColor), ), child: Center( child: Text( label, style: TextStyle( color: textColor, fontSize: 12, fontWeight: FontWeight.w500, ), ), ), ), ); } }
0
mirrored_repositories/barbershop/lib/src/core/ui
mirrored_repositories/barbershop/lib/src/core/ui/widgets/weekdays_panel.dart
import 'package:barbershop/src/core/constants/constants.dart'; import 'package:flutter/material.dart'; class WeekdaysPanel extends StatelessWidget { const WeekdaysPanel({ super.key, required this.onDayPressed, this.enabledDays, }); final ValueChanged<String> onDayPressed; final List<String>? enabledDays; @override Widget build(BuildContext context) { return SizedBox( width: double.infinity, child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ const Text( 'Selecione os dias da semana', style: TextStyle(fontSize: 14, fontWeight: FontWeight.w500), ), const SizedBox(height: 16), SingleChildScrollView( scrollDirection: Axis.horizontal, child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ ButtonDay( label: 'Seg', enabledDays: enabledDays, onDayPressed: onDayPressed, ), ButtonDay( label: 'Ter', enabledDays: enabledDays, onDayPressed: onDayPressed, ), ButtonDay( label: 'Qua', enabledDays: enabledDays, onDayPressed: onDayPressed, ), ButtonDay( label: 'Qui', enabledDays: enabledDays, onDayPressed: onDayPressed, ), ButtonDay( label: 'Sex', enabledDays: enabledDays, onDayPressed: onDayPressed, ), ButtonDay( label: 'Sab', enabledDays: enabledDays, onDayPressed: onDayPressed, ), ButtonDay( label: 'Dom', enabledDays: enabledDays, onDayPressed: onDayPressed, ), ], ), ), ], ), ); } } class ButtonDay extends StatefulWidget { const ButtonDay({ super.key, required this.label, required this.onDayPressed, this.enabledDays, }); final String label; final ValueChanged<String> onDayPressed; final List<String>? enabledDays; @override State<ButtonDay> createState() => ButtonDayState(); } class ButtonDayState extends State<ButtonDay> { var selected = false; @override Widget build(BuildContext context) { final textColor = selected ? Colors.white : AppColors.grey; var buttonColor = selected ? AppColors.brown : Colors.white; final buttonBorderColor = selected ? AppColors.brown : AppColors.grey; final ButtonDay(:enabledDays, :label) = widget; final disableDay = enabledDays != null && !enabledDays.contains(label); if (disableDay) { buttonColor = Colors.grey[400]!; } return Padding( padding: const EdgeInsets.all(5), child: InkWell( onTap: disableDay ? null : () { widget.onDayPressed(label); setState(() { selected = !selected; }); }, borderRadius: const BorderRadius.all(Radius.circular(8)), child: Container( width: 40, height: 56, decoration: BoxDecoration( color: buttonColor, border: Border.fromBorderSide(BorderSide(color: buttonBorderColor)), borderRadius: const BorderRadius.all(Radius.circular(8)), ), child: Center( child: Text( label, style: TextStyle( color: textColor, fontSize: 12, fontWeight: FontWeight.w500, ), ), ), ), ), ); } }
0
mirrored_repositories/barbershop/lib/src/core/ui
mirrored_repositories/barbershop/lib/src/core/ui/widgets/avatar_widget.dart
import 'package:barbershop/src/core/constants/constants.dart'; import 'package:barbershop/src/core/ui/barbershop_icons.dart'; import 'package:flutter/material.dart'; class AvatarWidget extends StatelessWidget { const AvatarWidget({super.key}) : hideUploadButton = false; const AvatarWidget.withoutButton({super.key}) : hideUploadButton = true; final bool hideUploadButton; @override Widget build(BuildContext context) { return SizedBox.square( dimension: 102, child: Stack( clipBehavior: Clip.none, children: [ Container( width: 92, height: 92, decoration: const BoxDecoration( image: DecorationImage( image: AssetImage(AppImages.avatar), ), ), ), Positioned( right: -4, bottom: -4, child: Offstage( offstage: hideUploadButton, child: Container( decoration: BoxDecoration( shape: BoxShape.circle, color: Colors.white, border: Border.all( color: AppColors.brown, width: 4, ), ), child: const Icon( BarbershopIcons.addEmployee, color: AppColors.brown, size: 20, ), ), ), ), ], ), ); } }
0
mirrored_repositories/barbershop/lib/src/core/ui
mirrored_repositories/barbershop/lib/src/core/ui/widgets/barbershop_loader.dart
import 'package:flutter/material.dart'; import 'package:loading_animation_widget/loading_animation_widget.dart'; class BarbershopLoader extends StatelessWidget { const BarbershopLoader({super.key}); @override Widget build(BuildContext context) { return Center( child: LoadingAnimationWidget.threeArchedCircle( color: Colors.brown, size: 60, ), ); } }
0
mirrored_repositories/barbershop/lib/src/core/ui
mirrored_repositories/barbershop/lib/src/core/ui/helpers/messages.dart
import 'package:flutter/material.dart'; import 'package:top_snackbar_flutter/custom_snack_bar.dart'; import 'package:top_snackbar_flutter/top_snack_bar.dart'; extension Messages on BuildContext { void showError(String message) => _showCommonSnackBar(CustomSnackBar.error(message: message)); void showSuccess(String message) => _showCommonSnackBar(CustomSnackBar.success(message: message)); void showInfo(String message) => _showCommonSnackBar(CustomSnackBar.info(message: message)); void _showCommonSnackBar(Widget child) => showTopSnackBar(Overlay.of(this), child); }
0
mirrored_repositories/barbershop/lib/src/core/ui
mirrored_repositories/barbershop/lib/src/core/ui/helpers/form_helper.dart
import 'package:flutter/material.dart'; extension FormExtension on BuildContext { void unfocus() => FocusScope.of(this).unfocus(); }
0
mirrored_repositories/barbershop/lib/src/core
mirrored_repositories/barbershop/lib/src/core/providers/application_providers.g.dart
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'application_providers.dart'; // ************************************************************************** // RiverpodGenerator // ************************************************************************** String _$restClientHash() => r'0ee58f1fd102b2016ed621885f1e8d52ed00da66'; /// See also [restClient]. @ProviderFor(restClient) final restClientProvider = Provider<RestClient>.internal( restClient, name: r'restClientProvider', debugGetCreateSourceHash: const bool.fromEnvironment('dart.vm.product') ? null : _$restClientHash, dependencies: null, allTransitiveDependencies: null, ); typedef RestClientRef = ProviderRef<RestClient>; String _$userRepositoryHash() => r'4a324f69804b6738f220b7c48b19aad627021894'; /// See also [userRepository]. @ProviderFor(userRepository) final userRepositoryProvider = Provider<UserRepository>.internal( userRepository, name: r'userRepositoryProvider', debugGetCreateSourceHash: const bool.fromEnvironment('dart.vm.product') ? null : _$userRepositoryHash, dependencies: null, allTransitiveDependencies: null, ); typedef UserRepositoryRef = ProviderRef<UserRepository>; String _$userLoginServiceHash() => r'62431221aac8e45888e74928ecf0b5836e72b999'; /// See also [userLoginService]. @ProviderFor(userLoginService) final userLoginServiceProvider = Provider<UserLoginService>.internal( userLoginService, name: r'userLoginServiceProvider', debugGetCreateSourceHash: const bool.fromEnvironment('dart.vm.product') ? null : _$userLoginServiceHash, dependencies: null, allTransitiveDependencies: null, ); typedef UserLoginServiceRef = ProviderRef<UserLoginService>; String _$getMeHash() => r'835de91f459d1216fe7813de1ce4ffa8c28975d4'; /// See also [getMe]. @ProviderFor(getMe) final getMeProvider = FutureProvider<UserModel>.internal( getMe, name: r'getMeProvider', debugGetCreateSourceHash: const bool.fromEnvironment('dart.vm.product') ? null : _$getMeHash, dependencies: null, allTransitiveDependencies: null, ); typedef GetMeRef = FutureProviderRef<UserModel>; String _$barbershopRepositoryHash() => r'a64ad01ae6b70f8192c02a09abc33ea968315cb9'; /// See also [barbershopRepository]. @ProviderFor(barbershopRepository) final barbershopRepositoryProvider = Provider<BarbershopRepository>.internal( barbershopRepository, name: r'barbershopRepositoryProvider', debugGetCreateSourceHash: const bool.fromEnvironment('dart.vm.product') ? null : _$barbershopRepositoryHash, dependencies: null, allTransitiveDependencies: null, ); typedef BarbershopRepositoryRef = ProviderRef<BarbershopRepository>; String _$getMyBarbershopHash() => r'e1c72495b6a8e9b1b3af23c7ef1c9144fb45e841'; /// See also [getMyBarbershop]. @ProviderFor(getMyBarbershop) final getMyBarbershopProvider = FutureProvider<BarbershopModel>.internal( getMyBarbershop, name: r'getMyBarbershopProvider', debugGetCreateSourceHash: const bool.fromEnvironment('dart.vm.product') ? null : _$getMyBarbershopHash, dependencies: null, allTransitiveDependencies: null, ); typedef GetMyBarbershopRef = FutureProviderRef<BarbershopModel>; String _$logoutHash() => r'd1382ccaba4d095ba11e122b71da66151bc6fbd6'; /// See also [logout]. @ProviderFor(logout) final logoutProvider = AutoDisposeFutureProvider<void>.internal( logout, name: r'logoutProvider', debugGetCreateSourceHash: const bool.fromEnvironment('dart.vm.product') ? null : _$logoutHash, dependencies: null, allTransitiveDependencies: null, ); typedef LogoutRef = AutoDisposeFutureProviderRef<void>; String _$scheduleRepositoryHash() => r'd8bb90e09ddffd4926259e9e2ec796a76739a37d'; /// See also [scheduleRepository]. @ProviderFor(scheduleRepository) final scheduleRepositoryProvider = AutoDisposeProvider<ScheduleRepository>.internal( scheduleRepository, name: r'scheduleRepositoryProvider', debugGetCreateSourceHash: const bool.fromEnvironment('dart.vm.product') ? null : _$scheduleRepositoryHash, dependencies: null, allTransitiveDependencies: null, ); typedef ScheduleRepositoryRef = AutoDisposeProviderRef<ScheduleRepository>; // ignore_for_file: type=lint // ignore_for_file: subtype_of_sealed_class, invalid_use_of_internal_member
0
mirrored_repositories/barbershop/lib/src/core
mirrored_repositories/barbershop/lib/src/core/providers/application_providers.dart
import 'package:barbershop/src/core/fp/either.dart'; import 'package:barbershop/src/core/rest_client/rest_client.dart'; import 'package:barbershop/src/core/ui/barbershop_nav_global_key.dart'; import 'package:barbershop/src/models/barbershop_model.dart'; import 'package:barbershop/src/models/user_model.dart'; import 'package:barbershop/src/repositories/barbershop/barbershop_repository.dart'; import 'package:barbershop/src/repositories/barbershop/barbershop_repository_impl.dart'; import 'package:barbershop/src/repositories/schedule/schedule_repository.dart'; import 'package:barbershop/src/repositories/schedule/schedule_repository_impl.dart'; import 'package:barbershop/src/repositories/user/user_repository.dart'; import 'package:barbershop/src/repositories/user/user_repository_impl.dart'; import 'package:barbershop/src/services/user_login/user_login_service.dart'; import 'package:barbershop/src/services/user_login/user_login_service_impl.dart'; import 'package:flutter/material.dart'; import 'package:riverpod_annotation/riverpod_annotation.dart'; import 'package:shared_preferences/shared_preferences.dart'; part 'application_providers.g.dart'; @Riverpod(keepAlive: true) RestClient restClient(RestClientRef ref) => RestClient(); @Riverpod(keepAlive: true) UserRepository userRepository(UserRepositoryRef ref) => UserRepositoryImpl(restClient: ref.read(restClientProvider)); @Riverpod(keepAlive: true) UserLoginService userLoginService(UserLoginServiceRef ref) => UserLoginServiceImpl(userRepository: ref.read(userRepositoryProvider)); @Riverpod(keepAlive: true) Future<UserModel> getMe(GetMeRef ref) async { final result = await ref.watch(userRepositoryProvider).me(); return switch (result) { Success(value: final userModel) => userModel, Failure(:final exception) => throw exception, }; } @Riverpod(keepAlive: true) BarbershopRepository barbershopRepository(BarbershopRepositoryRef ref) => BarbershopRepositoryImpl(restClient: ref.watch(restClientProvider)); @Riverpod(keepAlive: true) Future<BarbershopModel> getMyBarbershop(GetMyBarbershopRef ref) async { final userModel = await ref.watch(getMeProvider.future); final barbershopRepository = ref.watch(barbershopRepositoryProvider); final result = await barbershopRepository.getMyBarbershop(userModel); return switch (result) { Success(value: final barbershop) => barbershop, Failure(:final exception) => throw exception, }; } @riverpod Future<void> logout(LogoutRef ref) async { final sharedPreferences = await SharedPreferences.getInstance(); sharedPreferences.clear(); ref.invalidate(getMeProvider); ref.invalidate(getMyBarbershopProvider); Navigator.of(BarbershopNavGlobalKey.instance.navKey.currentContext!) .pushNamedAndRemoveUntil('/auth/login', (route) => false); } @riverpod ScheduleRepository scheduleRepository(ScheduleRepositoryRef ref) => ScheduleRepositoryImpl(restClient: ref.read(restClientProvider));
0
mirrored_repositories/barbershop/lib/src/core
mirrored_repositories/barbershop/lib/src/core/fp/either.dart
sealed class Either<E extends Exception, S> {} class Failure<E extends Exception, S> extends Either<E, S> { Failure(this.exception); final E exception; } class Success<E extends Exception, S> extends Either<E, S> { Success(this.value); final S value; }
0
mirrored_repositories/barbershop/lib/src/core
mirrored_repositories/barbershop/lib/src/core/fp/nil.dart
final class Nil { const Nil(); @override String toString() => 'Nil'; } const nil = Nil();
0
mirrored_repositories/barbershop/lib/src/repositories
mirrored_repositories/barbershop/lib/src/repositories/schedule/schedule_repository.dart
import 'package:barbershop/src/core/exceptions/repository_exception.dart'; import 'package:barbershop/src/core/fp/either.dart'; import 'package:barbershop/src/core/fp/nil.dart'; import 'package:barbershop/src/models/schedule_model.dart'; abstract interface class ScheduleRepository { Future<Either<RepositoryException, Nil>> scheduleClient( ({ int barbershopId, int userId, String clientName, DateTime date, int time, }) scheduleData, ); Future<Either<RepositoryException, List<ScheduleModel>>> findScheduleByDate( ({DateTime date, int userId}) filter, ); }
0
mirrored_repositories/barbershop/lib/src/repositories
mirrored_repositories/barbershop/lib/src/repositories/schedule/schedule_repository_impl.dart
import 'dart:developer'; import 'package:barbershop/src/core/exceptions/repository_exception.dart'; import 'package:barbershop/src/core/fp/either.dart'; import 'package:barbershop/src/core/fp/nil.dart'; import 'package:barbershop/src/core/rest_client/rest_client.dart'; import 'package:barbershop/src/models/schedule_model.dart'; import 'package:barbershop/src/repositories/schedule/schedule_repository.dart'; import 'package:dio/dio.dart'; class ScheduleRepositoryImpl implements ScheduleRepository { ScheduleRepositoryImpl({ required RestClient restClient, }) : _restClient = restClient; final RestClient _restClient; @override Future<Either<RepositoryException, Nil>> scheduleClient( ({ int barbershopId, String clientName, DateTime date, int time, int userId }) scheduleData, ) async { try { await _restClient.auth.post( '/schedules', data: { 'barbershop_id': scheduleData.barbershopId, 'user_id': scheduleData.userId, 'client_name': scheduleData.clientName, 'date': scheduleData.date.toIso8601String(), 'time': scheduleData.time, }, ); return Success(nil); } on DioException catch (e, s) { const errorMessage = 'Erro ao registrar agendamento'; log(errorMessage, error: e, stackTrace: s); return Failure( const RepositoryException(message: errorMessage), ); } } @override Future<Either<RepositoryException, List<ScheduleModel>>> findScheduleByDate( ({DateTime date, int userId}) filter, ) async { try { final Response(:List data) = await _restClient.auth.get( '/schedules', queryParameters: { 'user_id': filter.userId, 'date': filter.date.toIso8601String(), }, ); return Success(data.map((s) => ScheduleModel.fromMap(s)).toList()); } on DioException catch (e, s) { const errorMessage = 'Erro ao buscar agendamento de uma data'; log(errorMessage, error: e, stackTrace: s); return Failure( const RepositoryException(message: errorMessage), ); } on ArgumentError catch (e, s) { const errorMessage = 'Json inválido'; log(errorMessage, error: e, stackTrace: s); return Failure( const RepositoryException(message: errorMessage), ); } } }
0
mirrored_repositories/barbershop/lib/src/repositories
mirrored_repositories/barbershop/lib/src/repositories/user/user_repository_impl.dart
import 'dart:developer'; import 'dart:io'; import 'package:barbershop/src/core/exceptions/auth_exception.dart'; import 'package:barbershop/src/core/exceptions/repository_exception.dart'; import 'package:barbershop/src/core/fp/either.dart'; import 'package:barbershop/src/core/fp/nil.dart'; import 'package:barbershop/src/core/rest_client/rest_client.dart'; import 'package:barbershop/src/models/user_model.dart'; import 'package:barbershop/src/repositories/user/user_repository.dart'; import 'package:dio/dio.dart'; class UserRepositoryImpl implements UserRepository { const UserRepositoryImpl({ required RestClient restClient, }) : _restClient = restClient; final RestClient _restClient; @override Future<Either<AuthException, String>> login({ required String email, required String password, }) async { try { final Response(:data) = await _restClient.unAuth.post( '/auth', data: {'email': email, 'password': password}, ); // ignore: avoid_dynamic_calls return Success(data['access_token']); } on DioException catch (e, s) { if (e.response != null) { final Response(:statusCode) = e.response!; if (statusCode == HttpStatus.forbidden) { log('Login ou senha inválido login', error: e, stackTrace: s); return Failure(const AuthUnauthorizedException()); } } log('Erro ao realizar login', error: e, stackTrace: s); return Failure(const AuthError(message: 'Erro ao realizar login')); } } @override Future<Either<RepositoryException, UserModel>> me() async { try { final Response(:data) = await _restClient.auth.get('/me'); return Success(UserModel.fromMap(data)); } on DioException catch (e, s) { log('Erro ao buscar usuário logado', error: e, stackTrace: s); return Failure( const RepositoryException(message: 'Erro ao buscar usuário logado'), ); } on ArgumentError catch (e, s) { log('Invalid JSON', error: e, stackTrace: s); return Failure( const RepositoryException(message: 'Invalid JSON'), ); } } @override Future<Either<RepositoryException, Nil>> registerAdmin( ({String email, String name, String password}) userData, ) async { try { await _restClient.unAuth.post( '/users', data: { 'name': userData.name, 'email': userData.email, 'password': userData.password, 'profile': 'ADM', }, ); return Success(nil); } on DioException catch (e, s) { log('Erro ao registrar usuário', error: e, stackTrace: s); return Failure( const RepositoryException( message: 'Erro ao registrar usuário adminstrador', ), ); } } @override Future<Either<RepositoryException, List<UserModel>>> getEmployees( int barbershopId, ) async { try { final Response(:List data) = await _restClient.auth.get( '/users', queryParameters: { 'barbershop_id': barbershopId, }, ); final employees = data.map((e) => UserModelEmployee.fromMap(e)).toList(); return Success(employees); } on DioException catch (e, s) { const errorMessage = 'Erro ao buscar colaboradores'; log(errorMessage, error: e, stackTrace: s); return Failure(const RepositoryException(message: errorMessage)); } on ArgumentError catch (e, s) { const errorMessage = 'Erro ao buscar colaboradores (Invalid JSON)'; log(errorMessage, error: e, stackTrace: s); return Failure(const RepositoryException(message: errorMessage)); } } @override Future<Either<RepositoryException, Nil>> registerADMAsEmployee( ({List<int> workHours, List<String> workDays}) userModel, ) async { try { final userModelResult = await me(); final int userId; switch (userModelResult) { case Success(value: UserModel(:var id)): userId = id; case Failure(:var exception): return Failure(exception); } await _restClient.auth.put( '/users/$userId', data: { 'work_days': userModel.workDays, 'work_hours': userModel.workHours, }, ); return Success(nil); } on DioException catch (e, s) { const errorMessage = 'Erro ao inserir administrador como colaborador'; log(errorMessage, error: e, stackTrace: s); return Failure( const RepositoryException(message: errorMessage), ); } } @override Future<Either<RepositoryException, Nil>> registerEmployee( ({ int barbershopId, String email, String name, String password, List<String> workDays, List<int> workHours }) userModel, ) async { try { await _restClient.auth.post( '/users/', data: { 'name': userModel.name, 'email': userModel.email, 'password': userModel.password, 'work_days': userModel.workDays, 'work_hours': userModel.workHours, 'barbershop_id': userModel.barbershopId, 'profile': 'EMPLOYEE', }, ); return Success(nil); } on DioException catch (e, s) { const errorMessage = 'Erro ao inserir colaborador'; log(errorMessage, error: e, stackTrace: s); return Failure( const RepositoryException(message: errorMessage), ); } } }
0
mirrored_repositories/barbershop/lib/src/repositories
mirrored_repositories/barbershop/lib/src/repositories/user/user_repository.dart
import 'package:barbershop/src/core/exceptions/auth_exception.dart'; import 'package:barbershop/src/core/exceptions/repository_exception.dart'; import 'package:barbershop/src/core/fp/either.dart'; import 'package:barbershop/src/core/fp/nil.dart'; import 'package:barbershop/src/models/user_model.dart'; abstract interface class UserRepository { Future<Either<AuthException, String>> login({ required String email, required String password, }); Future<Either<RepositoryException, UserModel>> me(); Future<Either<RepositoryException, Nil>> registerAdmin( ({String name, String email, String password}) userData, ); Future<Either<RepositoryException, List<UserModel>>> getEmployees( int barbershopId, ); Future<Either<RepositoryException, Nil>> registerADMAsEmployee( ({List<String> workDays, List<int> workHours}) userModel, ); Future<Either<RepositoryException, Nil>> registerEmployee( ({ int barbershopId, String name, String email, String password, List<String> workDays, List<int> workHours, }) userModel, ); }
0
mirrored_repositories/barbershop/lib/src/repositories
mirrored_repositories/barbershop/lib/src/repositories/barbershop/barbershop_repository.dart
import 'package:barbershop/src/core/exceptions/repository_exception.dart'; import 'package:barbershop/src/core/fp/either.dart'; import 'package:barbershop/src/core/fp/nil.dart'; import 'package:barbershop/src/models/barbershop_model.dart'; import 'package:barbershop/src/models/user_model.dart'; abstract interface class BarbershopRepository { Future<Either<RepositoryException, BarbershopModel>> getMyBarbershop( UserModel userModel, ); Future<Either<RepositoryException, Nil>> save( ({ String name, String email, List<String> openingDays, List<int> openingHours, }) data, ); }
0
mirrored_repositories/barbershop/lib/src/repositories
mirrored_repositories/barbershop/lib/src/repositories/barbershop/barbershop_repository_impl.dart
import 'dart:developer'; import 'package:barbershop/src/core/exceptions/repository_exception.dart'; import 'package:barbershop/src/core/fp/either.dart'; import 'package:barbershop/src/core/fp/nil.dart'; import 'package:barbershop/src/core/rest_client/rest_client.dart'; import 'package:barbershop/src/models/barbershop_model.dart'; import 'package:barbershop/src/models/user_model.dart'; import 'package:barbershop/src/repositories/barbershop/barbershop_repository.dart'; import 'package:dio/dio.dart'; class BarbershopRepositoryImpl implements BarbershopRepository { BarbershopRepositoryImpl({ required RestClient restClient, }) : _restClient = restClient; final RestClient _restClient; @override Future<Either<RepositoryException, BarbershopModel>> getMyBarbershop( UserModel userModel, ) async { switch (userModel) { case UserModelADM(): final Response(data: List(first: data)) = await _restClient.auth.get( '/barbershop', queryParameters: {'user_id': '#userAuthRef'}, ); return Success(BarbershopModel.fromMap(data)); case UserModelEmployee(): final Response(:data) = await _restClient.auth.get( '/barbershop/${userModel.barbershopId}', ); return Success(BarbershopModel.fromMap(data)); } } @override Future<Either<RepositoryException, Nil>> save( ({ String email, String name, List<String> openingDays, List<int> openingHours, }) data, ) async { try { await _restClient.auth.post( '/barbershop', data: { 'user_id': '#userAuthRef', 'name': data.name, 'email': data.email, 'opening_days': data.openingDays, 'opening_hours': data.openingHours, }, ); return Success(nil); } on DioException catch (e, s) { const errorMessage = 'Erro ao salvar barbearia'; log(errorMessage, error: e, stackTrace: s); return Failure(const RepositoryException(message: errorMessage)); } } }
0
mirrored_repositories/barbershop/lib/src/services
mirrored_repositories/barbershop/lib/src/services/user_register_adm/user_service_adm.dart
import 'package:barbershop/src/core/exceptions/service_exception.dart'; import 'package:barbershop/src/core/fp/either.dart'; import 'package:barbershop/src/core/fp/nil.dart'; abstract interface class UserRegisterServiceADM { Future<Either<ServiceException, Nil>> execute( ({String name, String email, String password}) userData, ); }
0
mirrored_repositories/barbershop/lib/src/services
mirrored_repositories/barbershop/lib/src/services/user_register_adm/user_service_adm_impl.dart
import 'package:barbershop/src/core/exceptions/service_exception.dart'; import 'package:barbershop/src/core/fp/either.dart'; import 'package:barbershop/src/core/fp/nil.dart'; import 'package:barbershop/src/repositories/user/user_repository.dart'; import 'package:barbershop/src/services/user_login/user_login_service.dart'; import 'package:barbershop/src/services/user_register_adm/user_service_adm.dart'; final class UserRegisterServiceADMImpl implements UserRegisterServiceADM { UserRegisterServiceADMImpl({ required UserRepository userRepository, required UserLoginService userService, }) : _userRepository = userRepository, _userService = userService; final UserRepository _userRepository; final UserLoginService _userService; @override Future<Either<ServiceException, Nil>> execute( ({String name, String email, String password}) userData, ) async { final result = await _userRepository.registerAdmin(userData); switch (result) { case Success(): return _userService.execute( email: userData.email, password: userData.password, ); case Failure(:final exception): return Failure(ServiceException(message: exception.message)); } } }
0
mirrored_repositories/barbershop/lib/src/services
mirrored_repositories/barbershop/lib/src/services/user_login/user_login_service.dart
import 'package:barbershop/src/core/exceptions/service_exception.dart'; import 'package:barbershop/src/core/fp/either.dart'; import 'package:barbershop/src/core/fp/nil.dart'; abstract interface class UserLoginService { Future<Either<ServiceException, Nil>> execute({ required String email, required String password, }); }
0
mirrored_repositories/barbershop/lib/src/services
mirrored_repositories/barbershop/lib/src/services/user_login/user_login_service_impl.dart
import 'package:barbershop/src/core/constants/local_storage_keys.dart'; import 'package:barbershop/src/core/exceptions/auth_exception.dart'; import 'package:barbershop/src/core/exceptions/service_exception.dart'; import 'package:barbershop/src/core/fp/either.dart'; import 'package:barbershop/src/core/fp/nil.dart'; import 'package:barbershop/src/repositories/user/user_repository.dart'; import 'package:barbershop/src/services/user_login/user_login_service.dart'; import 'package:shared_preferences/shared_preferences.dart'; final class UserLoginServiceImpl implements UserLoginService { UserLoginServiceImpl({ required UserRepository userRepository, }) : _userRepository = userRepository; final UserRepository _userRepository; @override Future<Either<ServiceException, Nil>> execute({ required String email, required String password, }) async { final result = await _userRepository.login( email: email, password: password, ); switch (result) { case Success(:final value): final sharedPreferences = await SharedPreferences.getInstance(); sharedPreferences.setString(LocalStorageKeys.accessToken, value); return Success(nil); case Failure(:final exception): return switch (exception) { AuthError() => Failure(const ServiceException(message: 'Erro ao realizar login')), AuthUnauthorizedException() => Failure( const ServiceException(message: 'Login ou senha inválidos'), ), }; } } }
0
mirrored_repositories/Power-Up
mirrored_repositories/Power-Up/lib/main.dart
import 'package:flutter/material.dart'; import 'package:powerup/pages/LoginPage.dart'; void main() => runApp(MaterialApp( debugShowCheckedModeBanner: false, home: LoginPage(), ));
0
mirrored_repositories/Power-Up
mirrored_repositories/Power-Up/lib/DBHelper.dart
import 'dart:async'; import 'dart:io'; import 'dart:typed_data'; import 'package:flutter/services.dart'; import 'package:path/path.dart'; import 'package:sqflite/sqflite.dart'; import 'package:powerup/entities/Course.dart'; import 'package:powerup/entities/User.dart'; import 'package:powerup/entities/Vendor.dart'; import 'package:powerup/entities/Session.dart'; import 'package:mailer/mailer.dart'; import 'package:mailer/smtp_server.dart'; class DBHelper { /// Singleton static DBHelper single_instance = null; static DBHelper getInstance() { if (single_instance == null) single_instance = new DBHelper(); return single_instance; } static Database _db; static const String DB_NAME = 'MainDB.db'; //User Table static const String UserTABLE = 'User'; static const String name = 'name'; static const String dob = 'DOB'; static const String emailAddress = 'emailAddress'; static const String contactNum = 'contactNum'; static const String passU = 'passwordU'; static const String NOKname = 'NOKname'; static const String NOKNum = 'NOKcontactNum'; //Vendor Table static const String VendorTABLE = 'Vendor'; static const String nameOfPOC = 'nameOfPOC'; static const String contactNumOfPOC = 'contactNumOfPOC'; static const String passV = 'passwordV'; static const String busRegNum = 'busRegNum'; static const String compName = 'companyName'; //Course Table static const String CourseTABLE = 'Course'; static const String courseID = 'courseID'; static const String courseTitle = 'courseTitle'; static const String courseDesc = 'courseDesc'; static const String rating = 'rating'; static const String price = 'price'; static const String url = 'url'; static const String location = 'location'; static const String ageGroup = 'ageGroup'; static const String startDate = 'startDate'; static const String regDeadline = 'regDeadline'; //Fav Table static const String FavTABLE = 'Favourite'; //Session Table static const String SessionTABLE = 'Session'; static const String sessionID = 'sessionID'; static const String startDateOfSession = 'startDate'; static const String dateTime = 'dateTime'; static const String vacancy = 'vacancy'; static const String classSize = 'classSize'; //Register static const String RegisterTABLE = 'Register'; /// This function initializes a new database when the current database is null, /// and returns the current database when it is not null Future<Database> get db async { if (_db != null) { return _db; } _db = await initDb(); return _db; } /// This function enables foreign key support static Future _onConfigure(Database db) async { await db.execute('PRAGMA foreign_keys = ON'); } /// If the current database is not null, this function executes to retrieve the /// current database initDb() async { var databasesPath = await getDatabasesPath(); var path = join(databasesPath, "MainDB.db"); // Check if the database exists var exists = await databaseExists(path); if (!exists) { // Should happen only the first time you launch your application print("Creating new copy from asset"); // Make sure the parent directory exists try { await Directory(dirname(path)).create(recursive: true); } catch (_) {} // Copy from asset ByteData data = await rootBundle.load(join("assets", "MainDB.db")); List<int> bytes = data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes); // Write and flush the bytes written await File(path).writeAsBytes(bytes, flush: true); } else { print("Opening existing database"); } // open the database var db = await openDatabase(path, readOnly: false); return db; } /// This function creates all the tables for the database _onCreate(Database db, int version) async { await db.execute("CREATE TABLE $UserTABLE ($name TEXT," "$dob TEXT,$emailAddress TEXT PRIMARY KEY,$contactNum INTEGER, $passU TEXT," "$NOKname TEXT,$NOKNum INTEGER)"); await db.execute( "CREATE TABLE $VendorTABLE ($emailAddress TEXT PRIMARY KEY, $nameOfPOC TEXT, $contactNumOfPOC INTEGER, $passV TEXT, $busRegNum TEXT, $compName TEXT)"); await db.execute( "CREATE TABLE $CourseTABLE ($courseID INTEGER NOT NULL, $courseTitle TEXT NOT NULL, $courseDesc TEXT, $compName TEXT, $rating REAL, $price REAL, $url TEXT, $location TEXT, $ageGroup TEXT, $nameOfPOC TEXT, $contactNumOfPOC INTEGER, $startDate TEXT, $regDeadline TEXT, PRIMARY KEY(\"courseID\" AUTOINCREMENT))"); await db.execute( "CREATE TABLE $FavTABLE ($emailAddress TEXT NOT NULL, $courseID INTEGER NOT NULL, PRIMARY KEY(\"emailAddress\", \"courseID\"),FOREIGN KEY(\"emailAddress\") REFERENCES \"User\"(\"emailAddress\") ON DELETE CASCADE)"); await db //Session .execute("CREATE TABLE $SessionTABLE ($sessionID INTEGER NOT NULL, " "$courseID INTEGER NOT NULL, $startDateOfSession TEXT NOT NULL, $dateTime TEXT NOT NULL, " "$vacancy INTEGER NOT NULL, $classSize INTEGER NOT NULL, " "PRIMARY KEY($sessionID AUTOINCREMENT)," "FOREIGN KEY($courseID) REFERENCES $CourseTABLE($courseID)" "ON DELETE CASCADE)"); await db //Register .execute( "CREATE TABLE $RegisterTABLE ($emailAddress TEXT NOT NULL, $sessionID INTEGER NOT NULL, $courseID INTEGER NOT NULL," "PRIMARY KEY($emailAddress, $sessionID, $courseID)," "FOREIGN KEY($emailAddress) REFERENCES $UserTABLE($emailAddress)" "ON DELETE CASCADE," "FOREIGN KEY($sessionID) REFERENCES $SessionTABLE($sessionID)" "ON DELETE CASCADE," "FOREIGN KEY($courseID) REFERENCES $CourseTABLE($courseID)" "ON DELETE CASCADE)"); } /// This function saves a new course into the Course table Future<Course> saveCourse(Course course) async { var dbClient = await db; await dbClient.insert(CourseTABLE, course.toMap()); return course; } /// This function saves a new user into the User table Future<User> saveUser(User user) async { var dbClient = await db; await dbClient.insert(UserTABLE, user.toMap()); return user; } /// This function saves a new vendor into the Vendor table Future<Vendor> saveVendor(Vendor vendor) async { var dbClient = await db; await dbClient.insert(VendorTABLE, vendor.toMap()); return vendor; } /// This function saves a user's favourite course into the Favourite Table Future<bool> saveFavourite(String email, int courseID) async { var dbClient = await db; await dbClient.rawInsert( "INSERT INTO $FavTABLE(emailAddress,courseID) VALUES (?,?)", [email, courseID]); return true; } /// This function saves a new session into the Session table Future<Session> saveSession(Session session, int courseID) async { var dbClient = await db; await dbClient.rawInsert( "INSERT INTO $SessionTABLE(courseID,startDate,dateTime,vacancy,classSize) VALUES (?, ?, ?, ?, ?)", [courseID, session.startDate, session.dateTime, session.vacancy, session.classSize]); return session; } /// This function saves a new registered course and session for a user into the Register table Future<bool> saveRegister( int courseID, int sessionID, String userEmail) async { var dbClient = await db; await dbClient.rawInsert( "INSERT INTO Register(emailAddress, sessionID, courseID) VALUES(?,?,?)", [userEmail, sessionID, courseID]); return true; } /// This function returns a list of all courses from the Course table Future<List<Course>> getAllCourses() async { var dbClient = await db; List<Map> maps = await dbClient.rawQuery("SELECT * FROM $CourseTABLE"); List<Course> courses = []; if (maps.length > 0) { for (int i = 0; i < maps.length; i++) { courses.add(Course.forHomePage(maps[i])); } } return courses; } /// This function returns a course object given a courseID from the Course table Future<Course> getCourseById(int courseID) async { var dbClient = await db; List<Map> maps = await dbClient .rawQuery("SELECT * FROM $CourseTABLE WHERE courseID = ?", [courseID]); List<Course> courses = []; if (maps.length > 0) { for (int i = 0; i < maps.length; i++) { courses.add(Course.forHomePage(maps[i])); } } return courses[0]; } /// This function returns a list of all users from the User table Future<List<User>> getAllUsers() async { var dbClient = await db; List<Map> maps = await dbClient.query(UserTABLE, columns: [name, dob, emailAddress, contactNum, passU, NOKname, NOKNum]); List<User> users = []; if (maps.length > 0) { for (int i = 0; i < maps.length; i++) { users.add(User.fromMap(maps[i])); } } return users; } /// This function returns a list of all vendors from the Vendor table Future<List<Vendor>> getAllVendors() async { var dbClient = await db; List<Map> maps = await dbClient.query(VendorTABLE, columns: [emailAddress, nameOfPOC, contactNumOfPOC, passV, busRegNum, compName]); List<Vendor> vendors = []; if (maps.length > 0) { for (int i = 0; i < maps.length; i++) { vendors.add(Vendor.fromMap(maps[i])); } } return vendors; } /// This function returns a list of favourited courses by a user from the Favourite table Future<List<Course>> getFavForUser(String email) async { var dbClient = await db; List<Map> maps = await dbClient.rawQuery( "SELECT courseID from Favourite WHERE emailAddress = ?", [email]); List<Course> courseList = []; if (maps.length > 0) { for (int i = 0; i < maps.length; i++) { Course course = await getCourseById(maps[i]['courseID']); courseList.add(course); } } return courseList; } /// This function returns a list of sessions from the Session table Future<List<Session>> getAllSessions() async { var dbClient = await db; List<Map> maps = await dbClient.query(SessionTABLE, columns: [sessionID, courseID, startDate, dateTime, vacancy, classSize]); List<Session> sessions = []; if (maps.length > 0) { for (int i = 0; i < maps.length; i++) { sessions.add(Session.fromMap(maps[i])); } } return sessions; } /// This function returns a list of sessions given a courseID from the /// Session table Future<List<Session>> getSessionsByCourse(int courseID) async { var dbClient = await db; List<Map> maps = await dbClient .rawQuery("SELECT * FROM $SessionTABLE WHERE courseID = ?", [courseID]); List<Session> sessions = []; if (maps.length > 0) { for (int i = 0; i < maps.length; i++) { sessions.add(Session.fromMap(maps[i])); } } return sessions; } /// This function returns a list of email addresses of users registered in a /// session from the Register table Future<List<String>> getRegisterBySession(int sessionID) async { var dbClient = await db; List<Map> maps = await dbClient.rawQuery( "SELECT emailAddress FROM Register WHERE sessionID = ?", [sessionID]); List<String> register = []; if (maps.length > 0) { for (int i = 0; i < maps.length; i++) { register.add(maps[i]['emailAddress']); } } return register; } /// This function returns a list of names of users registered for each session for /// the particular course that the vendor wants to see Future<List<String>> getUserByEmail(List<String> emailAddress) async { var dbClient = await db; List<Map> maps = []; List<String> usernameList = []; print(emailAddress.length); for (int i = 0; i < emailAddress.length; i++) { maps = await dbClient.rawQuery( "SELECT name FROM User WHERE emailAddress = ?", [emailAddress[i]]); usernameList.add(maps[0]['name']); } List<String> protectUserEmailAddress = []; if (usernameList.length > 0) { for (int i = 0; i < usernameList.length; i++) { protectUserEmailAddress.add(usernameList[i]); } } return protectUserEmailAddress; } /// This function returns a list of courses that a user has registered from /// the Register table Future<List<Course>> getRegisterByUser(String userEmail) async { var dbClient = await db; List<Map> maps = await dbClient.rawQuery( "SELECT courseID from Register WHERE emailAddress = ?", [userEmail]); List<Course> courseList = []; if (maps.length > 0) { for (int i = 0; i < maps.length; i++) { Course course = await getCourseById(maps[i]['courseID']); courseList.add(course); } } return courseList; } /// This function returns a list of courses that a vendor has created from the /// Course table Future<List<Course>> getVendorCourse(int contactNumberPoc) async { var dbClient = await db; List<Map> maps = await dbClient.rawQuery( "SELECT * FROM Course WHERE contactNumOfPOC = ?", [contactNumberPoc]); List<Course> courses = []; if (maps.length > 0) { for (int i = 0; i < maps.length; i++) { courses.add(Course.fromMap(maps[i])); } } return courses; } /// This function deletes a course from the Course table Future<bool> deleteCourse(int courseID) async { var dbClient = await db; await dbClient .delete(CourseTABLE, where: 'courseID = ?', whereArgs: [courseID]); return true; } /// This function deletes a user from the User table Future<bool> deleteUser(String emailAddress) async { var dbClient = await db; await dbClient.delete(UserTABLE, where: 'emailAddress = ?', whereArgs: [emailAddress]); return true; } /// This function deletes a vendor from the Vendor table Future<bool> deleteVendor(String emailAddress) async { var dbClient = await db; await dbClient.delete(VendorTABLE, where: 'emailAddress = ?', whereArgs: [emailAddress]); return true; } /// This function deletes a course from a user's list of favourited courses from /// the Favourite table Future<bool> deleteFavCourseByUser(String emailAddress, int courseID) async { var dbClient = await db; await dbClient.rawDelete( "DELETE FROM Favourite WHERE emailAddress = ? AND courseID = ?", [emailAddress, courseID]); return true; } /// This function deletes a session from the Session table Future<bool> deleteSession(int sessionID, int courseID) async { var dbClient = await db; await dbClient.rawDelete( 'DELETE FROM Session WHERE sessionID = ? AND courseID = ?', [sessionID, courseID]); return true; } /// This function deletes all the courseID from the Register table when the /// course is removed Future<bool> deleteRegisterByCourse(int courseID) async { var dbClient = await db; await dbClient .delete(RegisterTABLE, where: 'courseID = ?', whereArgs: [courseID]); return true; } /// This function deletes a user from the Register table when he withdraws /// from a course Future<bool> deleteRegisterByUser(String userEmail, int courseID) async { var dbClient = await db; await dbClient.rawDelete( "DELETE FROM Register WHERE emailAddress = ? AND courseID = ?", [userEmail, courseID]); return true; } /// This function deletes all the sessionID from the Register table when the /// session is removed Future<bool> deleteRegisterBySession(int sessionID) async { var dbClient = await db; await dbClient .rawDelete("DELETE FROM Register WHERE sessionID = ?", [sessionID]); return true; } /// This function updates an existing course in the Course table Future<bool> updateCourse(Course course) async { var dbClient = await db; await dbClient.update(CourseTABLE, course.toMap(), where: 'courseID = ?', whereArgs: [course.courseID]); return true; } /// This function updates an existing user in the User table Future<bool> updateUser(User user) async { var dbClient = await db; await dbClient.update(UserTABLE, user.toMap(), where: 'emailAddress = ?', whereArgs: [user.emailAddress]); return true; } /// This function updates an existing vendor in the Vendor table Future<bool> updateVendor(Vendor vendor) async { var dbClient = await db; await dbClient.update(VendorTABLE, vendor.toMap(), where: 'emailAddress = ?', whereArgs: [vendor.emailAddress]); return true; } /// This function updates an existing session in the Session table Future<bool> updateSession(Session session) async { var dbClient = await db; await dbClient.update(SessionTABLE, session.toMap(), where: 'sessionID = ?', whereArgs: [session.sessionID]); return true; } /// This function updates the Register table when a new user registers for a /// course/session Future<bool> updateRegister( int courseID, int sessionID, String userEmail) async { var dbClient = await db; await dbClient.rawUpdate( 'UPDATE Register SET email = ? ' 'WHERE sessionID = ? AND courseID = ?', [sessionID, courseID]); return true; } /// This function adds sessions into the Session table and adds a new course /// into the Course table Future<bool> addCourse(Course course, List<Session> sessions) async { await saveCourse(course); int courseID = await getLatestCourseID(); for (int i = 0; i < sessions.length; i++) { await saveSession(sessions[i], courseID); } return true; } /// This function returns the latest, largest courseID Future<int> getLatestCourseID() async { var dbClient = await db; var maps = await dbClient .rawQuery("SELECT MAX(courseID) as latest_id FROM Course;"); int courseID = maps.first['latest_id']; return courseID; } /// This function gets the email addresses of the participants of a course and sends them a notification /// before removing the relevant data from respective tables Future<bool> removeCourse(int courseID) async { String username = 'studentemailtester2020@gmail.com'; String password = 'studentemailpassword2020'; final smtpServer = gmail(username, password); List<Session> sessions = await getSessionsByCourse(courseID); for (int j = 0; j < sessions.length; j++) { List<String> emails = await getRegisterBySession(sessions[j].sessionID); for (int k = 0; k < emails.length; k++) { // Create message final message = Message() ..from = Address(username, 'PowerUp!') ..recipients.add(emails[k]) ..subject = 'PowerUp! Course Removal Notification :: ${DateTime.now()}' ..text = 'Apologies. We regret to inform you that the course you have registered for has been removed.\n'; /// Send email to notify participants try { final sendReport = await send(message, smtpServer); print('Message sent: ' + sendReport.toString()); } on MailerException catch (e) { print('Message not sent.'); for (var p in e.problems) { print('Problem: ${p.code}: ${p.msg}'); } } } } for (int i = 0; i < sessions.length; i++) { deleteSession(sessions[i].sessionID, courseID); } await deleteRegisterByCourse(courseID); await deleteCourse(courseID); return true; } /// This function returns a list of courses ordered by their popularity Future<List<Course>> getPopularityByCourse(List<Course> list) async { var dbClient = await db; List<Course> courseList = []; List<Map> maps = await dbClient.rawQuery( "SELECT courseID FROM Register GROUP BY courseID ORDER BY COUNT(courseID) DESC"); for (int i = 0; i < maps.length; i++) { int i1 = maps[i][courseID]; for (int j = 0; j < list.length; j++) { int i2 = list[j].courseID; if (i1 == i2) { courseList.add(await getCourseById(i1)); } } } List<Course> courses = list; bool exist = false; for (int i = 0; i < courses.length; i++) { exist = false; for (int j = 0; j < courseList.length; j++) { if (courseList[j].courseID == courses[i].courseID) { exist = true; break; } } if (exist == false) { courseList.add(courses[i]); } } return courseList; } /// This function closes the database Future close() async { var dbClient = await db; dbClient.close(); } }
0
mirrored_repositories/Power-Up/lib
mirrored_repositories/Power-Up/lib/controllers/UserController.dart
import 'package:powerup/entities/User.dart'; import 'package:powerup/entities/Course.dart'; import 'dart:async'; import 'package:powerup/DBHelper.dart'; import 'package:powerup/entities/Session.dart'; class UserController { static User user; /// Singleton static UserController single_instance = null; static UserController getInstance() { if (single_instance == null) single_instance = new UserController(); return single_instance; } DBHelper dbHelper = DBHelper.getInstance(); /// This function returns a list of courses that a User has registered Future<List<Course>> getUserRegisteredCourse(String emailAddress) async { return dbHelper.getRegisterByUser(emailAddress); } /// This function adds a new course and session into a User's list of registered courses void addCourseToList(int courseID, int sessionID, String emailAddress) { dbHelper.saveRegister(courseID, sessionID, emailAddress); } /// This function removes an existing course and session from a User's list of registered courses void withdrawCourseFromList(String emailAddress, int courseID) { dbHelper.deleteRegisterByUser(emailAddress, courseID); } /// This function checks if the course is registered by a User Future<bool> containsRegisteredCourse(int courseID, String emailAddress) async { var dbClient = await dbHelper.db; List<Map> maps = await dbClient.rawQuery( "SELECT * from RegisterTABLE WHERE courseID = ? AND email = ?", [courseID, emailAddress]); if (maps.isEmpty) { return false; } return true; } /// This function returns a list of courses that a User has favourited Future<List<Course>> getUserFavoriteCourses(String emailAddress) async { return dbHelper.getFavForUser(emailAddress); } /// This function adds a new course into a User's list of favourited courses void addFavoriteCourseToList(String emailAddress, int courseID) { dbHelper.saveFavourite(emailAddress, courseID); } /// This function removes an existing course from a User's list of favourited courses void removeFavoriteCourseFromList(String emailAddress, int courseID) async { dbHelper.deleteFavCourseByUser(emailAddress, courseID); } /// This function checks if the course is favourited by a User Future<bool> containsFavoriteCourse(String emailAddress, int courseID) async { var dbClient = await dbHelper.db; List<Map> maps = await dbClient.rawQuery( "SELECT * from Favourite WHERE emailAddress = ? AND courseID = ?", [emailAddress, courseID]); if (maps.isEmpty) { return false; } return true; } /// This function returns a list of sessions for a course Future<List<Session>> getAllSessionByCourse(int courseID) async { return await dbHelper.getSessionsByCourse(courseID); } /// This function returns a list of sessions with vacancy > 0 for a course Future<List<Session>> getAvailSessionByCourse(int courseID) async { List<Session> sessionList = await dbHelper.getSessionsByCourse(courseID); List<Session> vacancyList = []; for (int i = 0; i < sessionList.length; i++) { if (sessionList[i].vacancy > 0) { vacancyList.add(sessionList[i]); } } return vacancyList; } /// This function checks if a User is registered for a course Future<bool> checkUserRegisteredForCourse(String emailAddress, int courseID) async { List<Course> courseList = await dbHelper.getRegisterByUser(emailAddress); for (int i = 0; i < courseList.length; i++) { if (courseList[i].courseID == courseID) { return true; } } return false; } }
0
mirrored_repositories/Power-Up/lib
mirrored_repositories/Power-Up/lib/controllers/VendorController.dart
import 'dart:core'; import 'package:powerup/entities/Session.dart'; import 'package:powerup/entities/Vendor.dart'; import 'package:powerup/entities/Course.dart'; import 'dart:async'; import 'package:powerup/DBHelper.dart'; import '../entities/Vendor.dart'; class VendorController { /// Singleton static VendorController single_instance = null; static VendorController getInstance() { if (single_instance == null) single_instance = new VendorController(); return single_instance; } static Vendor vendor; DBHelper dbHelper = DBHelper.getInstance(); ///This function adds a course created by the vendor to the database Future<bool> addCourseToDB(Course course, List<Session> sessions) async { return dbHelper.addCourse(course, sessions); } ///This function removes an existing course from the vendor in the database Future<bool> removeCourseFromDB(int courseToRemoveID) async { return dbHelper.removeCourse(courseToRemoveID); } ///This function retrieves from the database and returns the list of participants lists ///for all sessions of that course Future<List<List<String>>> viewParticipants(int courseID) async { List<List<String>> listOfParticipantsList = []; List<Session> sessionList = await dbHelper.getSessionsByCourse(courseID); for(int i =0;i<sessionList.length;i++){ List<String> participantsList = []; List<String> iterateList = await dbHelper.getRegisterBySession(sessionList[i].sessionID); for (int j = 0; j<iterateList.length; j++){ participantsList.add(iterateList[j]); } List<String> nameList = await dbHelper.getUserByEmail(participantsList); listOfParticipantsList.add(nameList); } return listOfParticipantsList; } /// This function retrieves from the database and returns the list of sessions of that course Future<List<Session>> getCourseSessions(int courseID) async{ List<Session> sessions = await dbHelper.getSessionsByCourse(courseID); return sessions; } ///This function retrieves from the database and returns the vacancy of a session of that course Future<int> getVacancyOfSession(int courseID, int sessionID) async{ int vacancy; List<Session> sessions = await dbHelper.getSessionsByCourse(courseID); for (int i = 0; i < sessions.length; i++) { if (sessionID == sessions[i].sessionID) { vacancy=sessions[i].vacancy; } } return vacancy; } /// This functions retrieves from database and returns the list of courses that the vendor has created Future<List<Course>> getVendorCreatedCourses(int contactNumberPoc){ return dbHelper.getVendorCourse(contactNumberPoc); } }
0
mirrored_repositories/Power-Up/lib
mirrored_repositories/Power-Up/lib/controllers/LoginRegisterController.dart
import 'dart:convert'; import 'package:crypto/crypto.dart'; import 'package:email_auth/email_auth.dart'; import 'package:email_validator/email_validator.dart'; import 'package:powerup/DBHelper.dart'; import 'package:powerup/entities/User.dart'; import 'package:powerup/entities/Vendor.dart'; import '../DBHelper.dart'; class LoginRegisterController{ /// Singleton static LoginRegisterController single_instance = null; static LoginRegisterController getInstance() { if (single_instance == null) single_instance = new LoginRegisterController(); return single_instance; } DBHelper dbHelper = DBHelper.getInstance(); /// This function gets the list of User Objects in the database and checks if the user's email address matches /// any of the existing email address in the database and returns that user object, else nothings is returned Future<User> getUserObj(String emailAddress) async { /// Get list of User objects var users = await dbHelper.getAllUsers(); /// check if the id attribute matches for (int i = 0; i < users.length; i++) { if (users[i].emailAddress == emailAddress) /// returns the user object that matches the user's email address return users[i]; } /// returns no user object if the user's email address does not match any in the database return null; } /// This function gets the list of Vendor Objects in the database and checks if the vendor's email address matches /// any of the existing email address in the database and returns that vendor object, else nothings is returned Future<Vendor> getVendorObj(String emailAddress) async { /// Get list of Vendor objects var vendors = await dbHelper.getAllVendors(); /// check if the id attribute matches for (int i = 0; i < vendors.length; i++) { if (vendors[i].emailAddress == emailAddress) /// returns the vendor object that matches the vendor's email address return vendors[i]; } /// returns no vendor object if the vendor's email address does not match any in the database return null; } /// This function sends the OTP to the valid email void sendOtp(String email) async { EmailAuth.sessionName = "Power Up"; await EmailAuth.sendOtp(receiverMail: email); } /// This function verifies if the input One Time Password (OTP) matches the OTP sent to the email address bool verify(String email, String otpController) { bool validate; validate = EmailAuth.validate( receiverMail:email, userOTP: otpController); return validate; } /// This function checks if input email address is valid first, then it will check if the email address already exists in the database /// If any of the conditions fail, the function will return false, else the function will return true Future<bool> isValidEmail(String email) async { /// Check if input email address format is valid try { final bool isValid = EmailValidator.validate(email); if (isValid == true) { /// If format is okay, check database if any existing email address match /// by first getting the list of User objects var users = await dbHelper.getAllUsers(); /// check if the id attribute matches for (int i = 0; i < users.length; i++) { if (users[i].emailAddress == email) /// return false if email address matches in database (match --> email already in use) return false; } /// return true if email address does not exist in database return true; } } catch(e) { print(e); } /// If control flow reaches here ==> caught error return false; } /// This function checks if the user has input the password accordingly to how it should be /// If the password matches the pattern, the function will return true, else false will be returned bool isValidPassword(String value){ String pattern = r'^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9]).{8,}$'; RegExp regExp = new RegExp(pattern); return regExp.hasMatch(value); } /// This function checks if the input contact number is in a valid Singapore contact number format /// If it is valid, true will be returned, else false will be returned bool isValidContactNum(int contactNum) { String contactNumStr = contactNum.toString(); RegExp regExp = new RegExp(r"^[6|8|9]\d{7}$"); if (!regExp.hasMatch(contactNumStr)) { return false; } else { return true; } } /// This function hashes the input password so as to allow for data protection and return the hashed password /// If there is an error in the hashing, "Hashing Failed" will be displayed on the screen String generateHash(String passwordU) { /// return hashed password for storage try { var bytes = utf8.encode(passwordU); var digest = sha256.convert(bytes); String output = digest.toString(); return output; } catch(e) { print(e); } /// If control flow reaches here ==> caught error return "Hashing Failed."; } /// This function processes login for users/vendors with accounts in database /// return true if user/vendor found AND passwords match /// return false if username not found OR username found but password does not match. Future<String> login(String username, String password) async { /// Perform hashing for comparison with stored password later String hashedPassword = generateHash(password); try { var userAccounts = await dbHelper.getAllUsers(); var vendorAccounts = await dbHelper.getAllVendors(); /// Check for users for (int i = 0; i < userAccounts.length; i++) { if (userAccounts[i].emailAddress == username){ if (userAccounts[i].passwordU == hashedPassword) { return "user"; } if (!(userAccounts[i].passwordU == hashedPassword)) { /// User found but passwordU does not match return "Login Failed"; } } } /// Check for vendors for (int i = 0; i < vendorAccounts.length; i++) { if (vendorAccounts[i].emailAddress == username){ if (vendorAccounts[i].passwordV == hashedPassword) { return "vendor"; } if (!(vendorAccounts[i].passwordV == hashedPassword)) { /// Vendor found but passwordV does not match return "Login Failed"; } } } } catch (e) { print(e); } /// If control flow reaches here ==> either: /// account does not exist (through try block) /// caught error (through catch block) return "Login Failed"; } /// This function creates a new user to be stored in the database upon successfully registering a user account /// If there is an error in the processing of creating the user, null will be returned /// Else if the user is successfully created and saved in the database, the user object is returned Future<User> createUser(String name, String dob, String email, int contactNum, String passwordU, String nokName, int nokContactNum) async { String hashedPassword = ""; /// Hash password for storage try { hashedPassword = generateHash(passwordU); } catch (e) { print(e); return null; } User user; User saveResult; /// Format data in User object to pass to DB class so that DBHelper can write to DB under one single user try { user = new User(name, dob, email, contactNum, hashedPassword, nokName, nokContactNum); saveResult = await dbHelper.saveUser(user); } catch (e) { print(e); return null; } if (!(user.emailAddress == saveResult.emailAddress)) { return null; } else { return user; } } /// This function creates a new vendor to be stored in the database upon successfully registering a vendor account /// If there is an error in the processing of creating the vendor, null will be returned /// Else if the vendor is successfully created and saved in the database, the vendor object is returned Future<Vendor> createVendor(String emailAddress, String nameOfPOC, int contactNumOfPOC, String passwordV, String busRegNum, String companyName) async { String hashedPassword = ""; /// Hash password for storage try { hashedPassword = generateHash(passwordV); } catch (e) { print(e); return null; } Vendor vendor; Vendor saveResult; /// Format data in Vendor object to pass to DB class so that DBHelper can write to DB under one single vendor try { vendor = new Vendor(emailAddress, nameOfPOC, contactNumOfPOC, hashedPassword, busRegNum, companyName); saveResult = await dbHelper.saveVendor(vendor); } catch (e) { print(e); return null; } if (!(vendor == saveResult)) return null; else return vendor; } }
0
mirrored_repositories/Power-Up/lib
mirrored_repositories/Power-Up/lib/controllers/SearchController.dart
import 'dart:core'; import 'package:powerup/entities/Course.dart'; import 'package:powerup/DBHelper.dart'; class SearchController { /// Singleton static SearchController single_instance = null; static SearchController getInstance() { if (single_instance == null) single_instance = new SearchController(); return single_instance; } DBHelper dbHelper = DBHelper.getInstance(); /// This maps the 12 months from String to int Map<String, int> monthMap = { "January": 1, "February": 2, "March": 3, "April": 4, "May": 5, "June": 6, "July": 7, "August": 8, "September": 9, "October": 10, "November": 11, "December": 12 }; /// This function maps the first 2 digits of a postal code to a zone String getLocation (String address) { /// Lists of postal code prefixes for different zones List<int> northZone = [53, 54, 55, 82, 56, 57, 72, 73, 77, 78, 75, 76, 79, 80]; List<int> southZone = [09, 10, 14,15, 16]; List<int> eastZone = [34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 81, 51, 52]; List<int> westZone = [11, 12, 13, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71]; List<int> centralZone = [01, 02, 03, 04, 05, 06, 07, 08, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33]; /// Extract first 2 digits of postal code from address String postalCode = address.substring(address.length - 6); int sector = int.parse(postalCode.substring(0,2)); String zone = ""; /// Map the first 2 digits to values in the lists of zones if (northZone.contains(sector)) zone = "North"; else if (southZone.contains(sector)) zone = "South"; else if (eastZone.contains(sector)) zone = "East"; else if (westZone.contains(sector)) zone = "West"; else if (centralZone.contains(sector)) zone = "Central"; else zone = "Error in getLocation(). Zone could not be found."; return zone; } /// This function searches through the entire list of courses using the general use search function, /// to return a list of courses related to the search term Future<List<Course>> searchAllCourses(String searchTerm) async { List<Course> searchResults = []; dbHelper.getAllCourses().then((List<Course> courses) { searchResults = search(searchTerm, courses); }); return searchResults; } /// This function is a general use search function which searches through the list of courses /// passed to it as an argument (either full list of courses or filtered list) /// to return a list of courses which contains the search term either within their /// course title, description or company name List<Course> search(String searchTerm, List<Course> listofCourses) { List<Course> searchResults = []; for (Course course in listofCourses) { if (course.courseTitle.toLowerCase().contains( searchTerm.toLowerCase()) || course.courseDesc.toLowerCase().contains(searchTerm.toLowerCase()) || course.company.toLowerCase().contains(searchTerm.toLowerCase())) searchResults.add(course); } return searchResults; } /// This function filters through the list of courses/search results to return a list of courses which /// meet any filter value defined for each criteria (e.g. West OR North) and /// multiple filter criteria (e.g. Location = 'West' OR 'North' AND Start Month = 'January') List<Course> sFilterLocationAgeGroupStartMonth(List<String> filters, List<Course> listOfCourses) { List<Course> courseList = listOfCourses; List<String> locations = []; List<String> ageGroups = []; List<String> startMonth = []; List<String> startYear = []; for (int i = 0; i < filters.length; i++) { if (filters[i] == 'North' || filters[i] == 'South' || filters[i] == 'East' || filters[i] == 'West' || filters[i] == 'Central') { locations.add(filters[i]); } if (filters[i] == '7-12' || filters[i] == '13-18' || filters[i] == '19-35' || filters[i] == '36-55' || filters[i] == '56-67') { ageGroups.add(filters[i]); } if (monthMap.containsKey(filters[i])) { startMonth.add(filters[i]); } if (filters[i] == "2021" || filters[i] == "2022") { startYear.add(filters[i]); } } if (locations.isNotEmpty) { List<Course> filterOne = filterLocation(locations, courseList); courseList = filterOne; } if (ageGroups.isNotEmpty) { List<Course> filterTwo = filterAgeGroup(ageGroups, courseList); courseList = filterTwo; } if (startMonth.length > 0) { List<Course> filterThree = filterMonth(startMonth, courseList); courseList = filterThree; } if (startYear.isNotEmpty) { List<Course> filterFour = filterYear(startYear, courseList); courseList = filterFour; } return courseList; } /// This function filters through the list of courses/search results to return a list of courses which /// meet any filter value defined for location criteria (e.g. West OR North) List<Course> filterLocation(List<String> locations, List<Course> listOfCourses) { List<String> zones = []; List<Course> filteredCourseList = []; for (int i = 0; i < listOfCourses.length; i++) { zones.add(getLocation(listOfCourses[i].location)); } for (var i = 0; i < zones.length; i++) { for (var j = 0; j < locations.length; j++) { if (zones[i].toLowerCase().contains( locations[j].toLowerCase())) { filteredCourseList.add(listOfCourses[i]); break; } else { continue; } } } return filteredCourseList; } /// This function filters through the list of courses/search results to return a list of courses which /// meet any filter value defined for age group criteria (e.g. '13-18' OR '19-35') /// Filters through list of courses/search results to return list of courses which /// meet any filter value defined for age group criteria (e.g. '13-18' OR '19-35') List<Course> filterAgeGroup(List<String> ageGroups, List<Course> listOfCourses) { List<Course> filteredCourseList = []; //return variable for (int i = 0; i < listOfCourses.length; i++) { for (int j = 0; j < ageGroups.length; j++) { if (listOfCourses[i].ageGroup == ageGroups[j]) { filteredCourseList.add(listOfCourses[i]); } } } return filteredCourseList; } /// This function Filters through the list of courses/search results to return a list of courses which /// meet any filter value defined for start month criteria (e.g. 'January' OR 'February') List<Course> filterMonth(List<String> startMonth, List<Course> listOfCourses) { List<int> month = []; List<Course> filteredCourseList = []; for (int i = 0; i < startMonth.length; i++) { month.add(monthMap[startMonth[i]]); } for (int i = 0; i < listOfCourses.length; i++) { for (int j = 0; j < month.length; j++) { if (int.parse(listOfCourses[i].startDate.split('/')[1]) == month[j]) { filteredCourseList.add(listOfCourses[i]); } } } return filteredCourseList; } /// This function Filters through the list of courses/search results to return a list of courses which /// meet any filter value defined for year criteria (e.g. '2021' OR '2022') List<Course> filterYear(List<String> startYear, List<Course> listOfCourses) { List<int> year = []; List<Course> filteredCourseList = []; for (int i = 0; i < startYear.length; i++) { year.add(int.parse(startYear[i])); } for (int i = 0; i < listOfCourses.length; i++) { for (int j = 0; j < startYear.length; j++) { if (int.parse(listOfCourses[i].startDate.split('/')[2]) == year[j]) { filteredCourseList.add(listOfCourses[i]); } } } return filteredCourseList; } /// This function orders the list of courses by orderChoice = /// 1: price, ascending 2: price, descending 4: popularity List<Course> orderBy(int orderChoice, List<Course> listOfCourses) { if (orderChoice == 1) { listOfCourses.sort((b, a) => a.price.compareTo(b.price)); return listOfCourses; } else if (orderChoice == 2) { listOfCourses.sort((a, b) => a.price.compareTo(b.price)); return listOfCourses; } else if (orderChoice == 4) { listOfCourses.sort((b, a) => a.rating.compareTo(b.rating)); return listOfCourses; } else { return listOfCourses; } } /// This function returns all courses in the database ordered by ratings Future<List<Course>> allCourses() async { List<Course> topCourses = []; topCourses = await dbHelper.getAllCourses(); topCourses = orderBy(4, topCourses); return topCourses; } /// This function returns a list of courses ordered by popularity (number of /// Users who registered for the course) Future<List<Course>> getPopularityForHomePage(List<Course> list) async{ return await dbHelper.getPopularityByCourse(list); } }
0
mirrored_repositories/Power-Up/lib
mirrored_repositories/Power-Up/lib/pages/VerificationPage.dart
import 'dart:async'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:powerup/controllers/LoginRegisterController.dart'; import 'package:powerup/entities/User.dart'; import 'package:powerup/entities/Vendor.dart'; import 'package:powerup/pages/VendorProfile.dart'; import 'HomePage.dart'; class VerificationPage extends StatefulWidget { TextEditingController otpcontroller = TextEditingController(); String name; String dob; String userEmail; int contactNumber; String password; String nokName; int nokContact; String nameOfPoc; int contactNumOfPOC; String brn; String companyName; String companyEmail; String companyPassword; VerificationPage.fromUser(this.otpcontroller, this.name, this.dob, this.userEmail, this.contactNumber, this.password, this.nokName, this.nokContact); VerificationPage.fromVendor(this.otpcontroller, this.nameOfPoc, this.contactNumOfPOC, this.brn, this.companyName, this.companyEmail, this.companyPassword); @override /// This function displays the Verification Page _VerificationPageState createState() => _VerificationPageState(); } class _VerificationPageState extends State<VerificationPage> with TickerProviderStateMixin { User user; Vendor vendor; bool countdownEnd = false; TextEditingController _otpcontroller = TextEditingController(); LoginRegisterController loginRegController = LoginRegisterController.single_instance; String email; String name; String dob; String userEmail; int contactNumber; String password; String nokName; int nokContact; String nameOfPoc; String brn; String companyName; String companyEmail; String companyPassword; AnimationController _controller; int levelClock = 1800; int _counter; Timer _timer; @override void initState() { super.initState(); if (widget.companyEmail == null) { assignEmail(widget.userEmail); } else if (widget.userEmail == null) { assignEmail(widget.companyEmail); } _startTimer(levelClock); _controller = AnimationController( vsync: this, duration: Duration( seconds: levelClock) ); _controller.forward(); } @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( title: const Text('Verification Page'), ), body: Builder(builder:(context){ return Center( child: Center( child: Column( children: <Widget>[ SizedBox(height: 10), Text('Countdown until verification code expires'), Container( margin: EdgeInsets.only(top: 5), height: 50, width: 200, color: Colors.grey, child: Center( child : Countdown( animation: StepTween( begin: levelClock, end: 0, ).animate(_controller), ),), ), //Verification Functions SizedBox(height: 30), Center( child: Text( 'A verification code has been sent to ' + email, textAlign: TextAlign.center, ) ), Text('Please enter the corresponding verification OTP'), fieldBox(widget.otpcontroller, null, false), Container( margin: EdgeInsets.only(top: 20), height: 50, width: 200, color: Colors.green[400], child: MaterialButton( onPressed:() async { print(email); print(widget.otpcontroller.value.text); if(loginRegController.verify(email, widget.otpcontroller.value.text)) { _timer.cancel(); _controller.dispose(); if (widget.companyEmail == null) { /// user creation User user = await loginRegController.createUser(widget.name, widget.dob, widget.userEmail, widget.contactNumber, widget.password, widget.nokName, widget.nokContact); Navigator.of(context).push( MaterialPageRoute( builder: (context) => HomePage( /// user object user )) ); } else if (widget.userEmail == null) { /// vendor creation Vendor vendor = await loginRegController.createVendor( widget.companyEmail, widget.nameOfPoc, widget.contactNumOfPOC, widget.companyPassword, widget.brn, widget.companyName); Navigator.of(context).push( MaterialPageRoute( builder: (context) => VendorProfile( /// vendor object vendor )) ); } } else { ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: const Text( 'The input Verification Code is invalid', style: TextStyle( fontSize: 16, ), ), backgroundColor: Colors.redAccent, duration: const Duration(seconds: 5), )); } }, child: Center( child: Text( "Verify", style: TextStyle( fontWeight: FontWeight.bold, color: Colors.white, fontSize: 20, ), ), ), ), ), /// Resent OTP function (_counter == 0) ? Card( margin: EdgeInsets.only(top: 20), elevation: 6, child: Container( height: 50, width: 200, color: Colors.green[400], child: ElevatedButton ( onPressed:() async { ///resend OTP loginRegController.sendOtp(email); setState(() { }); ///Snackbar to notify user that it has been resent ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: Text( 'OTP code has been resent to ' + email, style: TextStyle( fontSize: 16, ), ), backgroundColor: Colors.blue, duration: const Duration(seconds: 5), )); ///restart timer ///verification code update if (widget.companyEmail == null) { /// passing user object Navigator.of(context).push( MaterialPageRoute( builder: (context) => VerificationPage.fromUser( _otpcontroller, widget.name, widget.dob, widget.userEmail, widget.contactNumber, widget.password, widget.nokName, widget.nokContact )) ); } else if (widget.userEmail == null) { /// passing vendor object Navigator.of(context).push( MaterialPageRoute( builder: (context) => VerificationPage.fromVendor( _otpcontroller, widget.nameOfPoc, widget.contactNumOfPOC, widget.brn, widget.companyName, widget.companyEmail, widget.companyPassword )) ); } }, child: Center( child: Text( "Resend OTP", style: TextStyle( fontWeight: FontWeight.bold, color: Colors.black, fontSize: 20, ), ), ), ), ), ) :SizedBox(height: 1) ], ), )); }) ), ); } /// This is a widget that creates a field box for the user/vendor to input their information /// and informs the user/vendor that the field is to be filled should it be left blank Widget fieldBox(TextEditingController controller, String hintText, bool obscureText) { return Container( child: TextFormField( obscureText: obscureText, controller: controller, validator: (string){ if(string.isEmpty){ return 'Compulsory field cannot be empty'; } return null; }, decoration: InputDecoration( hintText: hintText, border: OutlineInputBorder(borderRadius: BorderRadius.circular(16)), contentPadding: EdgeInsets.fromLTRB(10, 0, 0, 20)), ) ); } void assignEmail(String emailAss){ email = emailAss; } void _startTimer(levelClock) { _counter = levelClock - 1; if (_timer != null) { _timer.cancel(); } _timer = Timer.periodic(Duration(seconds: 1), (timer) { setState(() { if (_counter > 0) { _counter--; } else { _timer.cancel(); } }); }); } } /// Countdown animation for the countdown timer class Countdown extends AnimatedWidget { Countdown({Key key, this.animation}) : super(key: key, listenable: animation); Animation<int> animation; @override build(BuildContext context) { Duration clockTimer = Duration(seconds: animation.value); String timerText = '${clockTimer.inMinutes.remainder(60).toString()}:${clockTimer.inSeconds.remainder(60).toString().padLeft(2, '0')}'; return Text( "$timerText", style: TextStyle( fontSize: 40, color: Theme.of(context).bottomAppBarColor, ), ); } Widget fieldBox(TextEditingController controller, String hintText, bool obscureText) { return Container( child: TextFormField( obscureText: obscureText, controller: controller, validator: (string){ if(string.isEmpty){ return 'Compulsory field cannot be empty'; } return null; }, decoration: InputDecoration( hintText: hintText, border: OutlineInputBorder(borderRadius: BorderRadius.circular(16)), contentPadding: EdgeInsets.fromLTRB(10, 0, 0, 20)), ) ); } }
0
mirrored_repositories/Power-Up/lib
mirrored_repositories/Power-Up/lib/pages/LoginPage.dart
import 'dart:ui'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:powerup/pages/HomePage.dart'; import 'package:powerup/controllers/LoginRegisterController.dart'; import 'package:powerup/pages/RegisterPage.dart'; import 'package:powerup/entities/User.dart'; import 'package:powerup/pages/VendorProfile.dart'; import '../controllers/LoginRegisterController.dart'; class LoginPage extends StatefulWidget { @override /// This function displays the Login Page _LoginPageState createState() => _LoginPageState(); } class _LoginPageState extends State<LoginPage> { TextStyle style = TextStyle(fontFamily: 'Montserrat', fontSize: 20); TextEditingController email = TextEditingController(); TextEditingController password = TextEditingController(); var _formKey = GlobalKey<FormState>(); LoginRegisterController loginRegController = LoginRegisterController.getInstance(); User user; @override Widget build(BuildContext context) { return Scaffold( resizeToAvoidBottomInset: true, body: Stack( children: [ Container( decoration: BoxDecoration( image: DecorationImage( image: AssetImage('assets/background.png'), fit: BoxFit.cover, ) ) ), Builder(builder: (context){ return SingleChildScrollView( child: Form( autovalidateMode: AutovalidateMode.onUserInteraction, key: _formKey, child: Padding( padding: EdgeInsets.fromLTRB(30, 30, 30, 0), child: Column( children: [ Image.asset( 'assets/powerup.png', scale: 2 ), SizedBox(height: 20), TextFormField( controller: email, obscureText: false, style: style, validator: (String email){ if(email.isEmpty) { return 'Email cannot be empty'; } return null; }, decoration: InputDecoration( prefixIcon: Icon( Icons.email, color: Colors.grey[450] ), contentPadding: EdgeInsets.fromLTRB(20, 15, 20, 15), hintText: "Email address", border: OutlineInputBorder(borderRadius: BorderRadius.circular(32)), ) ), SizedBox(height: 10), TextFormField( controller: password, obscureText: true, style: style, validator: (String password){ if(password.isEmpty){ return 'Password cannot be empty'; } return null; }, decoration: InputDecoration( prefixIcon: Icon( Icons.lock, color: Colors.grey[450] ), contentPadding: EdgeInsets.fromLTRB(20, 15, 20, 15), hintText: "Password", border: OutlineInputBorder(borderRadius: BorderRadius.circular(32.0)), ) ), SizedBox(height: 20), Material( elevation: 5.0, borderRadius: BorderRadius.circular(30), color: Colors.white, child: MaterialButton( minWidth: MediaQuery.of(context).size.width, padding: EdgeInsets.fromLTRB(20, 15, 20, 15), onPressed: (){ FocusScope.of(context).requestFocus(FocusNode()); if(_formKey.currentState.validate()){ loginRegController.login(email.text, password.text).then((loginCheck){ if(loginCheck == "user"){ loginRegController.getUserObj(email.text).then((user){ Navigator.of(context).push( MaterialPageRoute( builder: (context) => HomePage( user )) ); }); } else if (loginCheck == "vendor"){ loginRegController.getVendorObj(email.text).then((vendor){ Navigator.of(context).push( MaterialPageRoute( builder: (context) => VendorProfile( vendor )) ); }); } else{ SnackBar sb = SnackBar( content: Text( 'The email or password is invalid or the account does not exist', style: TextStyle( fontSize: 16, ), ), backgroundColor: Colors.redAccent, duration: Duration(seconds: 5), ); Scaffold.of(context) ..hideCurrentSnackBar() ..showSnackBar(sb); } /// else } /// inside then ); /// then } /// if (_formkey) }, /// on pressed child: Text( "Login", textAlign: TextAlign.center, style: style.copyWith( color: Colors.black, fontWeight: FontWeight.bold, ) ) ) ), SizedBox(height: 10), Text( "Don't have an account?", style: style.copyWith( color: Colors.black, ) ), FlatButton( onPressed: (){ Navigator.of(context).push( MaterialPageRoute( builder: (context) => RegisterPage()) ); }, child: Text( "Create a new one", style: TextStyle( color: Colors.white, decoration: TextDecoration.underline, )), ) ], ) ), ), ); }) ], ) ); } }
0
mirrored_repositories/Power-Up/lib
mirrored_repositories/Power-Up/lib/pages/CoursePage.dart
import 'dart:ui'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:powerup/entities/Course.dart'; import 'package:powerup/entities/User.dart'; import 'package:powerup/entities/Session.dart'; import 'package:powerup/controllers/UserController.dart'; import 'package:flutter_rating_bar/flutter_rating_bar.dart'; import 'package:powerup/pages/HomePage.dart'; class CoursePage extends StatefulWidget { @override User user; Course course; bool registered; CoursePage(this.registered, this.course, this.user); /// This function displays the Course Page _CoursePageState createState() => _CoursePageState(); } class _CoursePageState extends State<CoursePage> { String allSessions = ""; final _formKey = GlobalKey<FormState>(); bool _autovalidate = false; UserController userController = UserController.getInstance(); List<Session> sessions = []; Session selectedSession; bool favourite = false; @override void initState() { super.initState(); userController.getAvailSessionByCourse(widget.course.courseID).then((list){ if(list.isNotEmpty){ selectedSession = list[0]; } }); } @override Widget build(BuildContext context) { userController.getAllSessionByCourse(widget.course.courseID).then((sessionList){ String string = ""; for(int i = 0; i < sessionList.length; i++){ string += "Session " + (i+1).toString() + ": " + sessionList[i].startDate + ", " + sessionList[i].dateTime + "\n"; } allSessions = string; setState(() {}); }); userController.containsFavoriteCourse(widget.user.emailAddress, widget.course.courseID).then((value){ favourite = value; setState(() { }); }); setState(() { }); return Scaffold( resizeToAvoidBottomInset: false, body: Stack( children: [ Container( decoration: BoxDecoration( image: DecorationImage( image: AssetImage('assets/background.png'), fit: BoxFit.cover, ) ) ), SingleChildScrollView( child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ Image.network( widget.course.url, fit: BoxFit.fitWidth, ), SizedBox(height: 10), Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ IconButton( icon: Icon(Icons.arrow_back), color: Colors.black, iconSize: 40, onPressed:(){ Navigator.of(context).pushAndRemoveUntil(MaterialPageRoute(builder: (context) => HomePage( widget.user )), (Route<dynamic> route) => false); } ), IconButton( icon: Icon(Icons.favorite), color: favourite?Colors.red[700]:Colors.grey[350], iconSize: 40, onPressed: (){ setState(() { if(favourite){ favourite = false; userController.removeFavoriteCourseFromList(widget.user.emailAddress, widget.course.courseID); } else{ favourite = true; userController.addFavoriteCourseToList(widget.user.emailAddress, widget.course.courseID); } }); }, ), ], ), Padding( padding: EdgeInsets.fromLTRB(20, 0, 20, 0), child: Column( children: [ Text( widget.course.courseTitle, textAlign: TextAlign.center, style: TextStyle( fontSize: 24, fontWeight: FontWeight.bold, ) ), SizedBox(height: 10), Text( widget.course.company, style: TextStyle( fontSize: 16 ), ), SizedBox(height: 20), Row( mainAxisAlignment: MainAxisAlignment.center, children: [ RatingBarIndicator( rating: widget.course.rating, itemBuilder: (_, __){ return Icon( Icons.star, color: Colors.amber, ); }, itemSize: 30, ), SizedBox(width: 20), Text( widget.course.rating.toString(), style: TextStyle( fontSize: 30 ), ), ] ), SizedBox(height: 20), Text( widget.course.courseDesc, style: TextStyle( fontSize: 16, ) ), SizedBox(height: 20), ListTile( leading: Icon( Icons.monetization_on_rounded, color: Colors.red[700], ), title: Text("Course fees: \$" + widget.course.price.toString(),), ), ListTile( leading: Icon( Icons.location_on, color: Colors.red[700], ), title: Text(widget.course.location), ), ListTile( leading: Icon( Icons.phone, color: Colors.red[700], ), title: Text(widget.course.contactNumOfPOC.toString()) ), ListTile( leading: Icon( Icons.face, color: Colors.red[700], ), title: Text("Age Group: " + widget.course.ageGroup), ), ListTile( leading: Icon( Icons.calendar_today, color: Colors.red[700], ), title: Text( allSessions, ), ), (!widget.registered) ? Container( width: double.infinity, child: RaisedButton( color: Colors.red, elevation: 0, onPressed: (){ showModalBottomSheet( shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(10), ), context: context, builder: (context){ return Padding( padding: const EdgeInsets.all(32), child: Container( height: 250, child: StatefulBuilder( builder: (context, setState){ userController.getAvailSessionByCourse(widget.course.courseID).then((list) { sessions = list; if(this.mounted){ setState((){ }); } else{ return; } }); return (selectedSession != null)?Column( children: [ SizedBox(height: 20), Text( "Preferred session:", style: TextStyle( fontSize: 20 ), ), SizedBox(height: 20), Form( key: _formKey, autovalidate: _autovalidate, child: DropdownButtonFormField( hint: Text("Select session"), value: selectedSession.sessionID, validator: (value) => value == null ? 'Please select a session': null, onChanged: (newSession){ setState(() { for(int i = 0; i < sessions.length; i++){ if(sessions[i].sessionID == newSession){ selectedSession = sessions[i]; } } }); }, items: sessions.map((session){ return DropdownMenuItem( value: session.sessionID, child: Text( session.startDate + ", " + session.dateTime + "\n", ), ); }).toList(), ), ), SizedBox(height: 50), RaisedButton( color: Colors.red, child: Text( 'Confirm Registration', style: TextStyle( fontSize: 20, color: Colors.white, ) ), onPressed: (){ if(_formKey.currentState.validate()){ userController.addCourseToList(widget.course.courseID, selectedSession.sessionID, widget.user.emailAddress); widget.registered = true; _formKey.currentState.save(); Navigator.of(context).pop(); showDialog( barrierDismissible: false, context: context, builder: (context) { return Dialog( shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(4.0) ), child: Stack( overflow: Overflow.visible, alignment: Alignment.topCenter, children: [ Container( height: 450, child: Padding( padding: const EdgeInsets.fromLTRB(10, 70, 10, 10), child: Column( children: [ Text( "You have successfully been registered for the course - ", style: TextStyle(fontSize: 20), textAlign: TextAlign.center, ), SizedBox(height: 20), Text( widget.course.courseTitle, style: TextStyle(fontSize: 30, fontWeight: FontWeight.bold), textAlign: TextAlign.center, ), SizedBox(height: 10), ListTile( leading: Icon( Icons.monetization_on_rounded, color: Colors.red[700], ), title: Text( "Course fees: \$" + widget.course.price.toString(), style: TextStyle(fontSize: 15), ), ), ListTile( leading: Icon( Icons.location_on, color: Colors.red[700], ), title: Text( widget.course.location, style: TextStyle(fontSize: 15), ), ), ListTile( leading: Icon( Icons.calendar_today, color: Colors.red[700], ), title: Text( selectedSession.startDate + ", " + selectedSession.dateTime, style: TextStyle(fontSize: 15), ), ), SizedBox(height: 20), RaisedButton(onPressed: () { Navigator.of(context).pop(); }, color: Colors.red, child: Text('Okay', style: TextStyle(color: Colors.white, fontSize: 20),), ) ], ), ), ), Positioned( top: -40, child: CircleAvatar( backgroundColor: Colors.green, radius: 40, child: Icon(Icons.check, color: Colors.white, size: 50), ) ), ], ) ); } ); } else{ setState((){ _autovalidate = true; }); } } ) ], ): Align( alignment: Alignment.center, child: Text( 'There is no more vacancy for this course', style: TextStyle( fontSize: 16, color: Colors.red, fontWeight: FontWeight.bold, ), ), ); } ), ), ); }); }, child: Text( "Register", style: TextStyle( fontSize: 16, color: Colors.white, fontWeight: FontWeight.bold, ), ) ), ) : Column( children: [ Container( width: double.infinity, child: RaisedButton( child: Text("Withdraw"), onPressed: (){ userController.withdrawCourseFromList(widget.user.emailAddress, widget.course.courseID); showDialog( barrierDismissible: false, context: context, builder: (builder) { return AlertDialog( backgroundColor: Colors.redAccent, title: Text( 'Do you want to withdraw from this course?', textAlign: TextAlign.center, ), content: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ FlatButton( child: Text("Confirm"), onPressed: () { widget.registered = false; Navigator.of(context, rootNavigator: true).pop(); }, ), FlatButton( child: Text("Cancel"), onPressed: () { Navigator.of(context, rootNavigator: true).pop(); }, ), ] ) ); } ); }, ), ), ] ) ], ), ) ], ), ) ], ) ); } }
0
mirrored_repositories/Power-Up/lib
mirrored_repositories/Power-Up/lib/pages/RegisterPage.dart
import 'dart:ui'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:powerup/controllers/LoginRegisterController.dart'; import 'package:powerup/entities/Vendor.dart'; import 'package:intl/intl.dart'; import 'package:powerup/pages/VerificationPage.dart'; class RegisterPage extends StatefulWidget { @override /// This function displays the Registration Page _RegisterPageState createState() => _RegisterPageState(); } class _RegisterPageState extends State<RegisterPage> { String emailValidator; String companyValidator; TextEditingController lastName = TextEditingController(); TextEditingController firstName = TextEditingController(); TextEditingController dob = TextEditingController(); TextEditingController contactNumber = TextEditingController(); TextEditingController email = TextEditingController(); TextEditingController password = TextEditingController(); TextEditingController confirmPassword = TextEditingController(); TextEditingController nokName = TextEditingController(); TextEditingController nokContact = TextEditingController(); TextEditingController nameOfPOC = TextEditingController(); TextEditingController contactNumOfPOC = TextEditingController(); TextEditingController brn = TextEditingController(); TextEditingController companyName = TextEditingController(); TextEditingController companyEmail = TextEditingController(); TextEditingController companyPassword = TextEditingController(); TextEditingController companyConfirmPassword = TextEditingController(); final TextEditingController _otpcontroller = TextEditingController(); DateTime dobDT; int yearOfUser; bool dobFormat; int yearNow = int.parse(DateFormat('yyyy').format(DateTime.now())); final GlobalKey<FormState> _formKey1 = GlobalKey<FormState>(); final GlobalKey<FormState> _formKey2 = GlobalKey<FormState>(); LoginRegisterController registerControl = LoginRegisterController.single_instance; Vendor vendor; @override void initState(){ super.initState(); } @override Widget build(BuildContext context) { return MaterialApp( home: DefaultTabController( length: 2, child: Scaffold( resizeToAvoidBottomInset: true, backgroundColor: Colors.grey[300], appBar: AppBar( centerTitle: true, title: Text('Register As', style: TextStyle(fontSize: 24, color: Colors.black)), backgroundColor: Colors.lightBlueAccent, elevation: 0, bottom: TabBar( unselectedLabelColor: Colors.white, labelColor: Colors.black, indicatorSize: TabBarIndicatorSize.label, indicator: BoxDecoration( borderRadius: BorderRadius.only(topLeft: Radius.circular(10), topRight: Radius.circular(10)), color: Colors.grey[300], ), tabs: [ Tab(child: Align( child: Text('User', style: TextStyle(fontSize: 16)), )), Tab(child: Align( child: Text('Vendor', style: TextStyle(fontSize: 16)), )), ] ) ), body: TabBarView( children: [ Form( key: _formKey1, child: Padding( padding: EdgeInsets.all(30), child: SingleChildScrollView( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text('*Last name'), fieldBox(lastName, null, false), SizedBox(height: 10), Text('*First name'), fieldBox(firstName, null, false), SizedBox(height: 10), Text('*Date of birth'), Container( child: TextFormField( controller: dob, validator: (string){ dobFormat = false; if(string.isEmpty){ return 'Compulsory field cannot be empty'; } try{ dobDT = DateFormat('dd/MM/yyyy').parseStrict(string); yearOfUser = int.parse(DateFormat('yyyy').format(dobDT)); if(yearOfUser >= 1900 && yearOfUser < yearNow){ dobFormat = true; return null; } return 'Wrong date format'; } catch(e){ return 'Wrong date format'; } }, decoration: InputDecoration( hintText: "DD/MM/YYYY", border: OutlineInputBorder(borderRadius: BorderRadius.circular(16)), contentPadding: EdgeInsets.fromLTRB(10, 0, 0, 20)), ) ), SizedBox(height: 10), Text('*Contact number'), Container( child: TextFormField( keyboardType: TextInputType.number, maxLength: 8, controller: contactNumber, validator: (string){ if(string.isEmpty){ /// error message return 'Compulsory field cannot be empty'; } if(!registerControl.isValidContactNum(int.parse(contactNumber.text))) { /// error message return "Contact number is invalid. Please try again."; } return null; }, decoration: InputDecoration( border: OutlineInputBorder(borderRadius: BorderRadius.circular(16)), contentPadding: EdgeInsets.fromLTRB(10, 0, 0, 20)), ) ), SizedBox(height: 10), Text('*Email address'), Container( child: TextFormField( controller: email, validator: (string){ if(string.isEmpty){ /// error message return 'Compulsory field cannot be empty'; } return emailValidator; }, decoration: InputDecoration( border: OutlineInputBorder(borderRadius: BorderRadius.circular(16)), contentPadding: EdgeInsets.fromLTRB(10, 0, 0, 20)), ) ), SizedBox(height: 10), Text('*Password'), Container( child: TextFormField( obscureText: true, controller: password, validator: (string){ if(string.isEmpty){ /// error message return 'Compulsory field cannot be empty'; } if(!registerControl.isValidPassword(password.text)) { /// error message return "Password should contain at least 8 characters with: \n\tAt least 1 Uppercase\n\tAt least 1 Lowercase\n\tAt least 1 digit"; } return null; }, decoration: InputDecoration( border: OutlineInputBorder(borderRadius: BorderRadius.circular(16)), contentPadding: EdgeInsets.fromLTRB(10, 0, 0, 20)), ) ), SizedBox(height: 10), Text('*Confirm password'), Container( child: TextFormField( obscureText: true, controller: confirmPassword, validator: (string){ if(string.isEmpty){ /// error message return 'Compulsory field cannot be empty'; } if(password.text != string){ /// error message return 'Passwords do not match'; } return null; }, decoration: InputDecoration( border: OutlineInputBorder(borderRadius: BorderRadius.circular(16)), contentPadding: EdgeInsets.fromLTRB(10, 0, 0, 20)), ) ), SizedBox(height: 10), Text('Name of next-of-kin'), Container( child: TextFormField( controller: nokName, validator: (string){ if(dobFormat && yearNow - yearOfUser <= 12){ /// error message return 'Compulsory field cannot be empty'; } return null; }, decoration: InputDecoration( hintText: 'For children <12 years old', border: OutlineInputBorder(borderRadius: BorderRadius.circular(16)), contentPadding: EdgeInsets.fromLTRB(10, 0, 0, 20)), ) ), SizedBox(height: 10), Text('Contact number of next-of-kin'), Container( child: TextFormField( keyboardType: TextInputType.number, maxLength: 8, controller: nokContact, validator: (string){ if (yearOfUser != null) { if(yearNow - yearOfUser <= 12){ if(nokContact.text == "") /// error message return 'Compulsory field cannot be empty'; if(!registerControl.isValidContactNum(int.parse(nokContact.text))) /// error message return "NOK contact number is invalid. Please try again."; } } return null; }, decoration: InputDecoration( hintText: 'For children <12 years old', border: OutlineInputBorder(borderRadius: BorderRadius.circular(16)), contentPadding: EdgeInsets.fromLTRB(10, 0, 0, 20)), ) ), SizedBox(height: 10), Text( 'By signing up, you agree to PowerUp\'s Terms of Service and Privacy Policy', style: TextStyle(fontSize: 10) ), SizedBox(height: 20), Align( alignment: Alignment.center, child: RaisedButton( color: Colors.red, child: Text( 'Sign Up', style: TextStyle( fontSize: 24, color: Colors.white, ) ), onPressed:() async { bool valid = await registerControl.isValidEmail(email.text); setState(() { if(valid){ emailValidator = null; } else{ /// error message emailValidator = "Email Address is invalid or used. Please try again."; } }); if(_formKey1.currentState.validate()){ registerControl.sendOtp(email.value.text) ; setState(() { }); //if email not in db String name = firstName.text + " " + lastName.text; if((yearNow - yearOfUser <= 12) || ((yearNow - yearOfUser > 12) && (nokContact.text != "") && (nokName.text != ""))){ Navigator.of(context).push( MaterialPageRoute( /// user details, age <=12 builder: (context) => VerificationPage.fromUser( _otpcontroller, name, dob.text, email.text, int.parse(contactNumber.text), password.text, nokName.text, int.parse(nokContact.text) )) ); } if (yearNow - yearOfUser > 12) { Navigator.of(context).push( MaterialPageRoute( /// user details, age <=12 builder: (context) => VerificationPage.fromUser( _otpcontroller, name, dob.text, email.text, int.parse(contactNumber.text), password.text, nokName.text, int.parse("-1") )) ); } } }), ) ], ), ) ) ), Form( key: _formKey2, child: Padding( padding: EdgeInsets.all(30), child: SingleChildScrollView( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text('*Name of Point of Contact'), fieldBox(nameOfPOC, null, false), SizedBox(height: 10), Text('*Contact Number of Point of Contact'), Container( child: TextFormField( keyboardType: TextInputType.number, maxLength: 8, controller: contactNumOfPOC, validator: (string){ if(string.isEmpty) { /// error message return 'Compulsory field cannot be empty'; } if(!registerControl.isValidContactNum(int.parse(contactNumOfPOC.text))) { /// error message return "Contact number is invalid. Please try again."; } return null; }, decoration: InputDecoration( border: OutlineInputBorder(borderRadius: BorderRadius.circular(16)), contentPadding: EdgeInsets.fromLTRB(10, 0, 0, 20)), ) ), SizedBox(height: 10), Text('Business Registration Number'), Container( child: TextFormField( controller: brn, decoration: InputDecoration( border: OutlineInputBorder(borderRadius: BorderRadius.circular(16)), contentPadding: EdgeInsets.fromLTRB(10, 0, 0, 20)), ) ), SizedBox(height: 10), Text('Company Name'), Container( child: TextFormField( controller: companyName, decoration: InputDecoration( border: OutlineInputBorder(borderRadius: BorderRadius.circular(16)), contentPadding: EdgeInsets.fromLTRB(10, 0, 0, 20)), ) ), SizedBox(height: 10), Text('*Company Email'), Container( child: TextFormField( controller: companyEmail, validator: (string){ if(string.isEmpty){ /// error message return 'Compulsory field cannot be empty'; } return companyValidator; }, decoration: InputDecoration( border: OutlineInputBorder(borderRadius: BorderRadius.circular(16)), contentPadding: EdgeInsets.fromLTRB(10, 0, 0, 20)), ) ), SizedBox(height: 10), Text('*Password'), Container( child: TextFormField( obscureText: true, controller: companyPassword, validator: (string){ if(string.isEmpty){ /// error message return 'Compulsory field cannot be empty'; } if(!registerControl.isValidPassword(companyPassword.text)) { /// error message return "Password should contain at least 8 characters with: \n\tAt least 1 Uppercase\n\tAt least 1 Lowercase\n\tAt least 1 digit"; } return null; }, decoration: InputDecoration( border: OutlineInputBorder(borderRadius: BorderRadius.circular(16)), contentPadding: EdgeInsets.fromLTRB(10, 0, 0, 20)), ) ), SizedBox(height: 10), Text('*Confirm password'), Container( child: TextFormField( obscureText: true, controller: companyConfirmPassword, validator: (string){ if(string.isEmpty){ /// error message return 'Compulsory field cannot be empty'; } if(companyPassword.text != string){ /// error message return 'Passwords do not match'; } return null; }, decoration: InputDecoration( border: OutlineInputBorder(borderRadius: BorderRadius.circular(16)), contentPadding: EdgeInsets.fromLTRB(10, 0, 0, 20)), ) ), SizedBox(height: 10), Text( 'By signing up, you agree to PowerUp\'s Terms of Service and Privacy Policy', style: TextStyle(fontSize: 10) ), SizedBox(height: 20), Align( alignment: Alignment.center, child: RaisedButton( color: Colors.red, child: Text( 'Sign Up', style: TextStyle( fontSize: 24, color: Colors.white, ) ), onPressed:() async { bool valid = await registerControl.isValidEmail(companyEmail.text); setState(() { if(valid){ companyValidator = null; } else{ /// error message companyValidator = "Email Address is invalid or used. Please try again."; } }); if(_formKey2.currentState.validate()){ registerControl.sendOtp(companyEmail.value.text) ; setState(() { }); //if email not in db Navigator.of(context).push( MaterialPageRoute( /// vendor details builder: (context) => VerificationPage.fromVendor( _otpcontroller, nameOfPOC.text, int.parse(contactNumOfPOC.text), brn.text, companyName.text, companyEmail.text, companyPassword.text )) ); } return; }), ) ] ) ) ) ) ], ) ) ), ); } /// This is a widget that creates a field box for the user/vendor to input their information /// and informs the user/vendor that the field is to be filled should it be left blank Widget fieldBox(TextEditingController controller, String hintText, bool obscureText) { return Container( child: TextFormField( obscureText: obscureText, controller: controller, validator: (string){ if(string.isEmpty){ return 'Compulsory field cannot be empty'; } return null; }, decoration: InputDecoration( hintText: hintText, border: OutlineInputBorder(borderRadius: BorderRadius.circular(16)), contentPadding: EdgeInsets.fromLTRB(10, 0, 0, 20)), ) ); } }
0
mirrored_repositories/Power-Up/lib
mirrored_repositories/Power-Up/lib/pages/UserProfile.dart
import 'dart:ui'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:powerup/controllers/UserController.dart'; import 'package:powerup/entities/User.dart'; import 'package:powerup/entities/Course.dart'; import 'package:powerup/pages/CoursePage.dart'; import 'HomePage.dart'; import 'LoginPage.dart'; class UserProfile extends StatefulWidget { User user; UserProfile(this.user); @override /// This function displays the User Profile Page _UserProfileState createState() => _UserProfileState(); } class _UserProfileState extends State<UserProfile> with TickerProviderStateMixin { List<Course> courseList = []; List<Course> favouriteList = []; UserController userController = UserController.getInstance(); User user; TabController _controller; int length = 0; @override void initState(){ super.initState(); _controller = TabController(length: 2, vsync: this); userController.getUserRegisteredCourse(widget.user.emailAddress).then((value) { courseList = value; setState(() { }); }); userController.getUserFavoriteCourses(widget.user.emailAddress).then((value) { favouriteList = value; setState(() { }); }); } @override void dispose() { _controller.dispose(); super.dispose(); } Widget build(BuildContext context) { String name = widget.user.name; String email = widget.user.emailAddress; int contactNo = widget.user.contactNum; return DefaultTabController( length: 2, child: Scaffold( appBar: AppBar( title: Text( 'Power Up!', style: TextStyle(color: Colors.black, fontSize: 28), ), centerTitle: true, backgroundColor: Colors.white, elevation: 0, ), body: Stack( children: [ Container( decoration: BoxDecoration( image: DecorationImage( image: AssetImage('assets/background.png'), fit: BoxFit.cover, ) ) ), Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ IconButton( icon: Icon(Icons.arrow_back), color: Colors.black, iconSize: 40, onPressed:(){ _controller.removeListener(() { }); Navigator.push(context, MaterialPageRoute( builder: (context) => HomePage( widget.user ))); } ), Padding( padding: EdgeInsets.fromLTRB(0, 0, 10, 0), child: ElevatedButton( child: Text('Log Out'), onPressed: (){ Navigator.of(context).pushAndRemoveUntil(MaterialPageRoute(builder: (context) => LoginPage()), (Route<dynamic> route) => false); }, ), ), ], ), Column( children: <Widget>[ SizedBox(height: 30), Icon(Icons.account_circle, size: 100,), SizedBox(height: 10), Text("Name: " + name, style: TextStyle(fontSize: 20)), SizedBox(height: 10), Text("Email: " + email, style: TextStyle(fontSize: 20)), SizedBox(height: 10), Text("Contact Number: " + contactNo.toString(), style: TextStyle(fontSize: 20),), SizedBox(height: 40), SizedBox( height: 50, child: AppBar( backgroundColor: Colors.grey[400], bottom: TabBar( controller: _controller, onTap: (value){ if(value == 0){ userController.getUserRegisteredCourse(widget.user.emailAddress).then((value) { courseList = value; setState(() { }); }); } else if(value == 1){ userController.getUserFavoriteCourses(widget.user.emailAddress).then((value) { favouriteList = value; setState(() { }); }); } }, tabs: [ Tab( icon: Icon(Icons.check, color: Colors.greenAccent[700]), ), Tab(icon: Icon(Icons.favorite, color: Colors.red), ), ], ), ), ), Expanded( child: TabBarView( controller: _controller, children:[ Container( child: Column( children:[ Padding( padding: EdgeInsets.fromLTRB(0, 20, 0, 10), child: Text( "Registered Courses", textAlign: TextAlign.center, style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold), ), ), Expanded( child: Padding( padding: EdgeInsets.fromLTRB(10, 0, 10, 20), child: Scrollbar( child: ListView.builder( itemCount: courseList.length, itemBuilder: (context, index){ return CourseInProfile(courseList[index]); } ), ), ), ) ] ), color: Colors.grey[350], ), Container( child: Column( children:[ Padding( padding: EdgeInsets.fromLTRB(0, 20, 0, 10), child: Text( "Favourited Courses", textAlign: TextAlign.center, style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold), ), ), Expanded( child: Padding( padding: EdgeInsets.fromLTRB(10, 0, 10, 20), child: Scrollbar( child: ListView.builder( itemCount: favouriteList.length, itemBuilder: (context, index){ return CourseInProfile(favouriteList[index]); } ), ), ), ) ] ), color: Colors.grey[350], ), ], ), ), ], ),] ), ), ); } /// This widget is to retrieve the courses that the user has registered/favorite to be displayed Widget CourseInProfile(Course course){ return GestureDetector( onTap:(){ userController.checkUserRegisteredForCourse(widget.user.emailAddress, course.courseID).then((registered){ Navigator.push(context, MaterialPageRoute( builder: (context) => CoursePage( registered, course, widget.user ))); }); }, child: Card( margin: EdgeInsets.fromLTRB(16, 5, 16, 0), child: Column( children: [ Text( course.courseTitle, style: TextStyle( fontSize: 18, ) ), SizedBox(height: 6), Text( course.company, style: TextStyle( fontSize: 14, color: Colors.grey[600] ), ) ], ), ) ); } }
0
mirrored_repositories/Power-Up/lib
mirrored_repositories/Power-Up/lib/pages/VendorCoursePage.dart
import 'dart:ui'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:rflutter_alert/rflutter_alert.dart'; import '../entities/Course.dart'; import '../controllers/VendorController.dart'; import '../pages/VendorProfile.dart'; import '../entities/Vendor.dart'; class VendorCoursePage extends StatefulWidget { Course course; Vendor vendor; VendorCoursePage(this.course, this.vendor); @override /// This function displays the Course Page _VendorCoursePageState createState() => _VendorCoursePageState(); } class _VendorCoursePageState extends State<VendorCoursePage> { VendorController vcontroller = VendorController.getInstance(); List<Widget> participantsData = []; String allSessions = ''; String allParticipants = ''; @override void initState() { super.initState(); List <Widget> listItems = []; /// generate participants list vcontroller.viewParticipants(widget.course.courseID).then((allSessionsParticipantList){ allSessionsParticipantList.forEach((session){ session.forEach((participant) { listItems.add(Text(participant)); }); }); setState(() { participantsData = listItems; }); }); /// generate sessions list vcontroller.getCourseSessions(widget.course.courseID).then((sessionList) { String string = ""; for(int i = 0; i < sessionList.length; i++){ string += "Session " + (i+1).toString() + ": " + sessionList[i].startDate + ", " + sessionList[i].dateTime + "\n"; } allSessions = string; setState(() {}); }); /// generate participants list vcontroller.viewParticipants(widget.course.courseID).then((participantList) { String string = ""; for(int i = 0; i < participantList.length; i++){ string += "Session " + (i+1).toString() + '\n'; for(int j = 0; j<participantList[i].length; j++){ string += participantList[i][j] + '\n'; } string += '\n'; } allParticipants = string; setState(() { }); }); } /// This widget is to display course details with vendor's options Widget build(BuildContext context) { return Scaffold( resizeToAvoidBottomInset: false, body: Stack( children: [ Container( decoration: BoxDecoration( image: DecorationImage( image: AssetImage('assets/background.png'), fit: BoxFit.cover, ) ) ), SingleChildScrollView( child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ Image.network( widget.course.url, fit: BoxFit.fitWidth, ), SizedBox(height: 10), Padding( padding: EdgeInsets.fromLTRB(20, 10, 20, 0), child: Column( children: [ Text( widget.course.courseTitle, textAlign: TextAlign.center, style: TextStyle( fontSize: 24, fontWeight: FontWeight.bold, ) ), SizedBox(height: 30), Text( widget.course.courseDesc, style: TextStyle( fontSize: 16, ) ), SizedBox(height: 10), ListTile( leading: Icon( Icons.monetization_on_rounded, color: Colors.red[700], ), title: Text("Course fees: \$"+ widget.course.price.toString()), ), ListTile( leading: Icon( Icons.location_on, color: Colors.red[700], ), title: Text(widget.course.location), ), ListTile( leading: Icon( Icons.calendar_today, color: Colors.red[700], ), title: Text(allSessions), ), SizedBox(height: 10), Text('Registration Deadline: ${widget.course.regDeadline}', style: TextStyle(color: Colors.redAccent), ), SizedBox(height: 20), Container( height: 45, width: 500, child: RaisedButton( shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(30), ), child: Text("View Participants"), color: Colors.blue, hoverColor: Colors.lightBlueAccent, onPressed: (){ _openPopup(context); }, ) ), SizedBox(height: 10), Container( height: 45, width: 500, child: RaisedButton( shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(30), ), color: Colors.red, hoverColor: Colors.redAccent, child: Text("Remove Course"), onPressed: (){ showDialog( barrierDismissible: false, context: context, builder: (builder) { return AlertDialog( backgroundColor: Colors.redAccent, title: Text( 'Are you sure you want to remove this course?', textAlign: TextAlign.center, ), content: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ FlatButton( child: Text("Confirm"), onPressed: () { /// remove course from database vcontroller.removeCourseFromDB(widget.course.courseID).then((value) { if (value == true){} Navigator.of(context).pop(); Navigator.of(context).pop(); /// return to vendor profile page after removing course Navigator.push(context, MaterialPageRoute( builder: (context) => VendorProfile( widget.vendor ))); setState(() { }); }); }, ), FlatButton( child: Text("Cancel"), onPressed: () { Navigator.of(context).pop(); }, ), ] ) ); } ); }, ), ), ], ), ) ], ), ) ], ) ); } /// opens popup containing participant list for course _openPopup(context) { Alert( context: context, title: "Participant List", content: Column( children: <Widget>[ Container( child: Text(allParticipants) ), ], ), buttons: [ DialogButton( height: 35, width: 230, onPressed: () => Navigator.pop(context), child: Text( "Back to Course", style: TextStyle(color: Colors.white, fontSize: 20), ), ) ]).show(); } }
0
mirrored_repositories/Power-Up/lib
mirrored_repositories/Power-Up/lib/pages/CourseFormPage.dart
import 'dart:ui'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:intl/intl.dart'; import '../entities/Session.dart'; import '../controllers/VendorController.dart'; import '../entities/Course.dart'; import '../pages/VendorProfile.dart'; import '../entities/Vendor.dart'; class CourseFormPage extends StatefulWidget { @override String companyName; String nameOfPoc; int contactNumberOfPoc; Vendor vendor; CourseFormPage( this.companyName, this.nameOfPoc, this.contactNumberOfPoc, this.vendor); /// This function displays the CourseForm Page _CourseFormPageState createState() => _CourseFormPageState(); } class _CourseFormPageState extends State<CourseFormPage> { VendorController vcontroller = VendorController.getInstance(); String ageGroupDropDown = '7-12 Years'; int dateOfDT; int dateNow = int.parse(DateFormat('yyyy').format(DateTime.now())); int sd; int j; int i; bool dobFormat; bool sdFormat; bool tFormat; DateTime dobDT; DateTime sdDT; final GlobalKey<FormState> _formKey = GlobalKey<FormState>(); List<Widget> sessionWidget = []; List<Session> sessionEntryData = []; TextEditingController title = TextEditingController(); TextEditingController description = TextEditingController(); TextEditingController location = TextEditingController(); TextEditingController urlImage = TextEditingController(); TextEditingController pocName = TextEditingController(); TextEditingController pocContact = TextEditingController(); TextEditingController fees = TextEditingController(); TextEditingController regDeadline = TextEditingController(); TextEditingController courseStartDate = TextEditingController(); TextEditingController sessionCount = TextEditingController(); TextEditingController classSize = TextEditingController(); TextEditingController startDate = TextEditingController(); TextEditingController dateTime = TextEditingController(); @override void initState() { super.initState(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( elevation: 0, backgroundColor: Colors.blue, title: Text("New Course"), ), body: SingleChildScrollView( child: Container( margin: EdgeInsets.all(24), child: Form( autovalidateMode: AutovalidateMode.onUserInteraction, key: _formKey, child: Column( children: <Widget>[ TextFormField( controller: title, validator: (title) { if (title.isEmpty) { return 'Compulsory field cannot be empty'; } return null; }, decoration: InputDecoration( labelText: 'Course Title', ), ), TextFormField( controller: description, validator: (description) { if (description.isEmpty) { /// error message return 'Compulsory field cannot be empty'; } return null; }, decoration: InputDecoration( labelText: 'Description', ), ), TextFormField( controller: location, validator: (location) { if (location.isEmpty) { /// error message return 'Compulsory field cannot be empty'; } return null; }, decoration: InputDecoration( labelText: 'Location', ), ), Row( children: [ Text( 'Select Age Group: ', style: TextStyle(fontSize: 17), ), SizedBox( width: 10, ), DropdownButton<String>( focusColor: Colors.blue, value: ageGroupDropDown, onChanged: (newValue) { setState(() { ageGroupDropDown = newValue; }); }, /// Age groups displayed items: <String>[ '7-12 Years', '13-18 Years', '19-25 Years', '25-35 Years' ].map<DropdownMenuItem<String>>((String value) { return DropdownMenuItem<String>( value: value, child: Text(value), ); }).toList(), ), ], ), TextFormField( keyboardType: TextInputType.number, controller: fees, validator: (fees) { tFormat= false; if (fees.isEmpty) { /// error message return 'Compulsory field cannot be empty'; } try { /// checking for correct denomination representations if (int.parse(fees) is int || (int.parse(fees)*100) is int) { tFormat = true; return null; } /// error message return 'Please only input numbers.'; } catch (e) { /// error message return 'Please only input numbers.'; } }, decoration: InputDecoration( labelText: 'Course fees:', ), ), TextFormField( controller: urlImage, toolbarOptions: ToolbarOptions( cut: true, copy: true, selectAll: true, paste: true, ), validator: (urlImage) { tFormat = false; if (urlImage.isEmpty) { /// error message return 'Compulsory field cannot be empty'; } try { if (Uri.parse(urlImage).isAbsolute) { tFormat = true; return null; } /// error message return 'Input is not a URL.'; } catch (e) { /// error message return 'Input is not a URL.'; } }, decoration: InputDecoration( labelText: 'Course Image(in url):', ), ), SizedBox( height: 10, ), Container( child: TextFormField( controller: regDeadline, validator: (string) { dobFormat = false; if (string.isEmpty) { /// error message return 'Compulsory field cannot be empty'; } try { dobDT = DateFormat('dd/MM/yyyy').parseStrict(string); dateOfDT = int.parse(DateFormat('yyyy').format(dobDT)); if (dateOfDT >= dateNow) { dobFormat = true; return null; } /// error message return 'Wrong date format'; } catch (e) { /// error message return 'Wrong date format'; } }, decoration: InputDecoration( hintText: "Registration Deadline(DD/MM/YYYY)", border: OutlineInputBorder( borderRadius: BorderRadius.circular(16)), contentPadding: EdgeInsets.fromLTRB(10, 0, 0, 20)), )), SizedBox( height: 10, ), Container( child: TextFormField( controller: courseStartDate, validator: (string) { dobFormat = false; if (string.isEmpty) { /// error message return 'Compulsory field cannot be empty'; } try { dobDT = DateFormat('dd/MM/yyyy').parseStrict(string); dateOfDT = int.parse(DateFormat('yyyy').format(dobDT)); if (dateOfDT >= dateNow) { dobFormat = true; return null; } /// error message return 'Wrong date format'; } catch (e) { /// error message return 'Wrong date format'; } }, decoration: InputDecoration( hintText: "Start Date(DD/MM/YYYY)", border: OutlineInputBorder( borderRadius: BorderRadius.circular(16)), contentPadding: EdgeInsets.fromLTRB(10, 0, 0, 20)), )), SizedBox( height: 10, ), Container( height: 30, width: 160, child: RaisedButton( shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(30), ), color: Colors.orange, hoverColor: Colors.orangeAccent, onPressed: () { setState(() { sessionWidget.add(Padding( padding: EdgeInsets.all(15.0), child: Column( children: [ TextFormField( keyboardType: TextInputType.number, controller: classSize, validator: (count) { tFormat = false; if (count.isEmpty) { /// error message return 'Compulsory field cannot be empty'; } try { if (int.parse(count) is int) { tFormat = true; return null; } /// error message return 'Please only input whole numbers.'; } catch (e) { /// error message return 'Please only input whole numbers.'; } }, decoration: InputDecoration( labelText: 'Session Class Size(e.g. 20)', ), ), SizedBox( height: 10, ), Container( child: TextFormField( controller: startDate, validator: (string) { sdFormat = false; if (string.isEmpty) { /// error message return 'Compulsory field cannot be empty'; } try { sdDT = DateFormat('dd/MM/yyyy') .parseStrict(string); dateOfDT = int.parse( DateFormat('yyyy').format(sdDT)); if (dateOfDT >= dateNow) { sdFormat = true; return null; } /// error message return 'Wrong date format'; } catch (e) { /// error message return 'Wrong date format'; } }, decoration: InputDecoration( hintText: "Session Start Date(DD/MM/YYYY)", border: OutlineInputBorder( borderRadius: BorderRadius.circular(16)), contentPadding: EdgeInsets.fromLTRB(10, 0, 0, 20)), )), TextFormField( controller: dateTime, validator: (count) { tFormat = false; if (count.isEmpty) { /// error message return 'Compulsory field cannot be empty'; } try { i = int.parse(count.split(':')[0]); j = int.parse(count.split(':')[1]); if (i <= 23 && j <= 59) { tFormat = true; return null; } /// error message return 'Wrong time format'; } catch (e) { /// error message return 'Wrong time format'; } }, decoration: InputDecoration( labelText: 'Session time(HH:MM)', ), ), RaisedButton( color: Colors.green, hoverColor: Colors.lightGreenAccent, child: Text('Save Session', style: TextStyle( fontSize: 17, color: Colors.white, )), onPressed: () { Session session = Session( startDate.text, dateTime.text, int.parse(classSize.text), int.parse(classSize.text)); setState(() { sessionEntryData.add(session); }); showDialog( barrierDismissible: false, context: context, builder: (builder) { return AlertDialog( backgroundColor: Colors.green, title: Text( 'Session Saved! To create another session, re-enter new session details', textAlign: TextAlign.center, ), content: Row( mainAxisAlignment: MainAxisAlignment .spaceBetween, children: [ FlatButton( child: Text("OK"), onPressed: () { Navigator.of(context, rootNavigator: true).pop(); }, ), ])); }); }) ], ))); }); }, child: Text('Add Session', style: TextStyle(fontSize: 20, color: Colors.white)))), Padding( padding: EdgeInsets.symmetric(horizontal: 25, vertical: 30), child: Column( children: List.generate(sessionWidget.length, (i) { return sessionWidget[i]; }), )), Container( height: 40, width: 250, child: RaisedButton( shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(30), ), color: Colors.blue, hoverColor: Colors.lightGreenAccent, child: Text('Submit', style: TextStyle( fontSize: 23, color: Colors.white, )), onPressed: () { if (_formKey.currentState.validate()) { Course course = Course( title.text, description.text, widget.companyName, 0, double.parse(fees.text), urlImage.text, location.text, ageGroupDropDown, widget.nameOfPoc, widget.contactNumberOfPoc, courseStartDate.text, regDeadline.text); String string = 'Course Title: '+ /// course details processing course.courseTitle.toString() + '\n' + 'Course Description: ' + course.courseDesc.toString() + '\n' + 'Location: ' + course.location.toString() + '\n' + 'Age Group: ' + course.ageGroup.toString() + '\n' + 'Course Fees: \$' + course.price.toString() + '\n' + 'Start Date: ' + course.startDate.toString() + '\n' + 'Registration Deadline: ' + course.regDeadline.toString() + '\n' + '\n'; for (int i = 0; i < sessionEntryData.length; i++) { string += 'Session ' + (i + 1).toString() + ": " + sessionEntryData[i].startDate + ", " + sessionEntryData[i].dateTime + ", " + 'class size: ' + sessionEntryData[i].classSize.toString() + "\n"; } showDialog( context: context, builder: (context) { return AlertDialog( title: Text("Course Details"), content: Text("$string"), //add question details actions: <Widget>[ FlatButton( child: Text("Confirm"), onPressed: () { _formKey.currentState.save(); vcontroller.addCourseToDB( course, sessionEntryData); Navigator.of(context, rootNavigator: true).pop(); showDialog( barrierDismissible: false, context: context, builder: (context) { return Dialog( shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular( 4.0)), child: Stack( overflow: Overflow.visible, alignment: Alignment.topCenter, children: [ Container( height: 450, child: Padding( padding: const EdgeInsets .fromLTRB( 10, 70, 10, 10), child: Column( children: [ Text( /// confirmation message "The following course has been successfully created - ", style: TextStyle( fontSize: 20), textAlign: TextAlign .center, ), SizedBox( height: 20), Text( title.text, style: TextStyle( fontSize: 30, fontWeight: FontWeight .bold), textAlign: TextAlign .center, ), SizedBox( height: 20), RaisedButton( onPressed: () { Navigator.of( context) .pop(); Navigator.of( context) .pop(); Navigator.push( context, MaterialPageRoute( builder: (context) => VendorProfile(widget.vendor))); }, color: Colors.red, child: Text( 'Back to Profile', style: TextStyle( color: Colors .white, fontSize: 20), ), ) ], ), ), ), Positioned( top: -40, child: CircleAvatar( backgroundColor: Colors.green, radius: 30, child: Icon( Icons.check, color: Colors .white, size: 40), )), ], )); }); }), FlatButton( child: Text("Edit"), onPressed: () => Navigator.pop(context, false), ) ], ); }); } }), ) ], ), ), )), ); } } /// This function creates a widget which allows the Vendor to input details about /// a session Widget sessionCreate() { DateTime sdDT; int sd; bool sdFormat; int yearNow = int.parse(DateFormat('yyyy').format(DateTime.now())); final GlobalKey<FormState> _formKey2 = GlobalKey<FormState>(); TextEditingController vacancies = TextEditingController(); TextEditingController startDate = TextEditingController(); TextEditingController dateTime = TextEditingController(); return Padding( padding: EdgeInsets.all(15.0), child: Column( children: [ TextFormField( keyboardType: TextInputType.number, controller: vacancies, validator: (count) { if (count.isEmpty) { /// error message return 'Compulsory field cannot be empty'; } return null; }, decoration: InputDecoration( labelText: 'Session Class Vacancies(e.g. 20)', ), ), SizedBox( height: 10, ), Container( child: TextFormField( controller: startDate, validator: (string) { sdFormat = false; if (string.isEmpty) { /// error message return 'Compulsory field cannot be empty'; } try { sdDT = DateFormat('dd/MM/yyyy').parseStrict(string); sd = int.parse(DateFormat('yyyy').format(sdDT)); if (sd >= 1900 && sd < yearNow) { sdFormat = true; return null; } /// error message return 'Wrong date format'; } catch (e) { /// error message return 'Wrong date format'; } }, decoration: InputDecoration( hintText: "Session Start Date(DD/MM/YYYY)", border: OutlineInputBorder(borderRadius: BorderRadius.circular(16)), contentPadding: EdgeInsets.fromLTRB(10, 0, 0, 20)), )), TextFormField( controller: dateTime, validator: (count) { if (count.isEmpty) { /// error message return 'Compulsory field cannot be empty'; } return null; }, decoration: InputDecoration( labelText: 'Session time(HH:MM)', ), ), RaisedButton( color: Colors.green, hoverColor: Colors.lightGreenAccent, child: Text('Save Session', style: TextStyle( fontSize: 17, color: Colors.white, )), onPressed: () { if (_formKey2.currentState.validate()) {} }) ], )); }
0
mirrored_repositories/Power-Up/lib
mirrored_repositories/Power-Up/lib/pages/HomePage.dart
import 'dart:ui'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:powerup/controllers/UserController.dart'; import 'package:powerup/entities/User.dart'; import 'package:powerup/pages/CoursePage.dart'; import 'package:flutter_rating_bar/flutter_rating_bar.dart'; import 'package:powerup/entities/Course.dart'; import 'package:powerup/pages/UserProfile.dart'; import 'package:powerup/controllers/SearchController.dart'; class HomePage extends StatefulWidget { @override /// This function displays the Home Page User user; HomePage(this.user); _HomePageState createState() => _HomePageState(); } class _HomePageState extends State<HomePage> { TextEditingController search = TextEditingController(); bool showOrderBy = false; List<Course> courseList = []; List<Course> fullList = []; List<Course> popularList = []; List<bool> selectedOrderBy; List<String> orderByCategories; SearchController searchController = SearchController.getInstance(); UserController userController = UserController.getInstance(); @override void initState(){ super.initState(); selectedOrderBy = [false, false, false, false]; orderByCategories = ['PriceUp', 'PriceDown', 'Popularity', 'Ratings']; searchController.allCourses().then((value){ courseList = value; fullList = courseList; setState(() { }); }); search.addListener(() { if(search.text.length == 0 && FilterChipWidgetState.selectedFilters.isEmpty){ setState(() { searchController.allCourses().then((value){ courseList = value; fullList = courseList; setState(() { }); }); }); } else if(search.text.length > 0){ setState(() { courseList = searchController.search(search.text, fullList); courseList = searchController.sFilterLocationAgeGroupStartMonth( FilterChipWidgetState.selectedFilters, courseList); showOrderBy = true; }); } }); } @override Widget build(BuildContext context) { return Scaffold( resizeToAvoidBottomInset: true, appBar: AppBar( backgroundColor: Colors.white, elevation: 0, title: Text('Power Up!', style: TextStyle( fontSize: 28, fontWeight: FontWeight.bold, color: Colors.black, )), centerTitle: true, leading: IconButton( icon: Icon(Icons.account_circle), onPressed: (){ Navigator.push(context, MaterialPageRoute( builder: (context) => UserProfile( widget.user ))); }, color: Colors.black, iconSize: 30, ), ), body: Stack( children: [ Container( decoration: BoxDecoration( image: DecorationImage( image: AssetImage('assets/background.png'), fit: BoxFit.cover, ) ) ), Column( children: [Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [Container( height: 40, width: 250, margin: EdgeInsets.fromLTRB(20, 20, 0, 10), child: TextField( controller: search, textAlignVertical: TextAlignVertical.bottom, enableInteractiveSelection: true, obscureText: false, decoration: InputDecoration( contentPadding: EdgeInsets.fromLTRB(20, 15, 20, 15), hintText: "Search course", hintStyle: TextStyle(color: Colors.black), border: OutlineInputBorder( borderRadius: BorderRadius.circular(25.0), ), ) ), ), IconButton(icon: Icon(Icons.search), onPressed: (){ setState(() { if(search.text.isNotEmpty) { showOrderBy = true; courseList = searchController.search( search.text, fullList); courseList = searchController.sFilterLocationAgeGroupStartMonth( FilterChipWidgetState.selectedFilters, courseList); } else { showOrderBy = false; courseList = searchController.sFilterLocationAgeGroupStartMonth( FilterChipWidgetState.selectedFilters, fullList); } setState(() { }); }); FocusManager.instance.primaryFocus.unfocus(); }), IconButton(icon: Icon(Icons.filter_list), onPressed: () { showDialog( context: context, builder: (BuildContext context) { return AlertDialog( content: Stack( overflow: Overflow.visible, children: <Widget>[ Positioned( right: -40.0, top: -40.0, child: InkResponse( onTap: () { Navigator.of(context).pop(); }, child: CircleAvatar( child: Icon(Icons.close), backgroundColor: Colors.red, ), ), ), filterWindow(context), ], ), ); }); },), ] ), SizedBox(height: 5), showOrderBy == true ? Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ ToggleButtons( borderRadius: BorderRadius.circular(6), borderColor: Colors.grey, color: Colors.black, fillColor: Colors.orangeAccent, selectedColor: Colors.black, children:[ Text('Price ⬆'), Text('Price ⬇'), Text('Popularity'), Text('Ratings'), ], constraints: BoxConstraints(minWidth: 90, maxWidth: 90, minHeight: kMinInteractiveDimension), onPressed: (index){ setState(() { courseList = searchController.search(search.text, fullList); courseList = searchController.sFilterLocationAgeGroupStartMonth( FilterChipWidgetState.selectedFilters, courseList); for (int i = 0; i < selectedOrderBy.length; i++) { selectedOrderBy[i] = i == index; if(selectedOrderBy[i] == true) index = i; } if(index == 0){ courseList = searchController.orderBy(1, courseList); } if(index == 1){ courseList = searchController.orderBy(2, courseList); } if(index == 2){ searchController.getPopularityForHomePage(courseList).then((value){ setState(() { courseList = value; }); }); courseList = []; } if(index == 3){ courseList = searchController.orderBy(4, courseList); } }); }, isSelected: selectedOrderBy, ) ] ) : Text(''), Expanded( child: Scrollbar( child: ListView.builder( itemCount: courseList.length, itemBuilder: (context, index){ return courseTemplate(courseList[index]); } ), ), ) ]), ], ) ); } /// This function creates a widget which displays the courses that are being offered by their course title, /// company name, course image and ratings, sorted from highest rating to lowest Widget courseTemplate(Course course){ return GestureDetector( onTap:(){ userController.checkUserRegisteredForCourse(widget.user.emailAddress, course.courseID).then((registered){ Navigator.push(context, MaterialPageRoute( builder: (context) => CoursePage( registered, course, widget.user ))); }); }, child: Padding( padding: EdgeInsets.fromLTRB(16, 0, 16, 0), child: Card( clipBehavior: Clip.antiAlias, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(5), ), color: Colors.grey[300], child: Row( children:[ Ink( height: 100, width: 100, decoration: BoxDecoration( color: Colors.blueGrey, image: DecorationImage( fit: BoxFit.cover, image: NetworkImage(course.url), ) ), ), Flexible( child: Padding( padding: EdgeInsets.all(15), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text(course.courseTitle, overflow: TextOverflow.ellipsis ,style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold)), SizedBox(height: 7), Text(course.company), SizedBox(height: 5), RatingBarIndicator( rating: course.rating, itemBuilder: (_, __){ return Icon( Icons.star, color: Colors.amber, ); }, itemSize: 20, ) ], ), ), ) ] ) ), ) ); } /// This widget displays the filter window that has the filter features for location, /// age group, start month and start year Widget filterWindow(BuildContext context) { return SingleChildScrollView( child: Column( children: [ Align( alignment: Alignment.centerLeft, child: Padding( padding: EdgeInsets.all(1), child: _titleContainer("Location"), ), ), Padding( padding: EdgeInsets.only(left: 8), child: Align( alignment: Alignment.centerLeft, child: Wrap( spacing: 5, runSpacing: -10, children: [ FilterChipWidget(chipName: 'North',), FilterChipWidget(chipName: 'South',), FilterChipWidget(chipName: 'East',), FilterChipWidget(chipName: 'West',), FilterChipWidget(chipName: 'Central',), ] ) ), ), Align( alignment: Alignment.centerLeft, child: Padding( padding: EdgeInsets.all(1), child: _titleContainer("Age"), ), ), Padding( padding: EdgeInsets.only(left: 8), child: Align( alignment: Alignment.centerLeft, child: Wrap( spacing: 5, runSpacing: -10, children: [ FilterChipWidget(chipName: '7-12',), FilterChipWidget(chipName: '13-18',), FilterChipWidget(chipName: '19-35',), FilterChipWidget(chipName: '36-55',), FilterChipWidget(chipName: '56-67',), ] ) ) ), Align( alignment: Alignment.centerLeft, child: Padding( padding: EdgeInsets.all(1), child: _titleContainer("Month"), ), ), Padding( padding: EdgeInsets.only(left: 8), child: Align( alignment: Alignment.centerLeft, child: Wrap( spacing: 5, runSpacing: -10, children: [ FilterChipWidget(chipName: 'January',), FilterChipWidget(chipName: 'February',), FilterChipWidget(chipName: 'March',), FilterChipWidget(chipName: 'April',), FilterChipWidget(chipName: 'May',), FilterChipWidget(chipName: 'June',), FilterChipWidget(chipName: 'July',), FilterChipWidget(chipName: 'August',), FilterChipWidget(chipName: 'September',), FilterChipWidget(chipName: 'October',), FilterChipWidget(chipName: 'November',), FilterChipWidget(chipName: 'December',), ] ) ) ), Align( alignment: Alignment.centerLeft, child: Padding( padding: EdgeInsets.all(1), child: _titleContainer("Year"), ), ), Padding( padding: EdgeInsets.only(left: 8), child: Align( alignment: Alignment.centerLeft, child: Wrap( spacing: 5, runSpacing: -10, children: [ FilterChipWidget(chipName: '2021',), FilterChipWidget(chipName: '2022',), ] ) ) ), SizedBox(height: 30), RaisedButton( color: Colors.grey[350], elevation: 0, onPressed: () { if (mounted) { setState(() { if(FilterChipWidgetState.selectedFilters.isNotEmpty) { showOrderBy = true; courseList = searchController.search(search.text, fullList); courseList = searchController.sFilterLocationAgeGroupStartMonth( FilterChipWidgetState.selectedFilters, courseList); } else { showOrderBy = false; courseList = searchController.search(search.text, fullList); } Navigator.of(context).pop(); }); } }, child: Text( "Filter", style: TextStyle( fontSize: 16, fontWeight: FontWeight.bold, ), ) ) ] ), ); } } /// This widget is to act as the code for title containers that will display myTitle in this format Widget _titleContainer(String myTitle){ return Text( myTitle, style: TextStyle( color: Colors.black, fontSize: 20, fontWeight: FontWeight.bold), ); } class FilterChipWidget extends StatefulWidget { final String chipName; FilterChipWidget({Key key, this.chipName}) : super(key: key); @override FilterChipWidgetState createState() => FilterChipWidgetState(); } class FilterChipWidgetState extends State<FilterChipWidget> { var _isSelected = false; static List<String> selectedFilters = new List(); @override Widget build(BuildContext context) { return FilterChip( label: Text(widget.chipName), selected: selectedFilters.contains(widget.chipName), onSelected: (isSelected){ setState(() { _isSelected = isSelected; if(_isSelected){ selectedFilters.add(widget.chipName); } else{ selectedFilters.remove(widget.chipName); } }); }, selectedColor: Colors.lightBlue, ); } }
0
mirrored_repositories/Power-Up/lib
mirrored_repositories/Power-Up/lib/pages/VendorProfile.dart
import 'dart:ui'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:powerup/pages/CourseFormPage.dart'; import '../pages/VendorCoursePage.dart'; import '../entities/Vendor.dart'; import '../controllers/VendorController.dart'; import '../pages/CourseFormPage.dart'; import '../pages/LoginPage.dart'; class VendorProfile extends StatefulWidget { Vendor vendor; VendorProfile(this.vendor); @override /// This function displays the Vendor Profile Page _VendorProfileState createState() => _VendorProfileState(); } class _VendorProfileState extends State<VendorProfile> { ScrollController scrollController = ScrollController(); VendorController vcontroller = VendorController.getInstance(); List<Widget> itemsData = []; @override void initState() { super.initState(); List<Widget> listItems = []; vcontroller .getVendorCreatedCourses(widget.vendor.contactNumOfPOC) .then((courseList) { courseList.forEach((course) { listItems.add(Container( padding: EdgeInsets.fromLTRB(10,10,10,0), height: 60, width: double.maxFinite, child: GestureDetector( onTap: () { Navigator.of(context).push( MaterialPageRoute( builder: (context) => VendorCoursePage(course, widget.vendor)) ); }, child: Card( elevation: 4, margin: EdgeInsets.fromLTRB(16, 5, 16, 5), child: Column( children: [ SizedBox(height:5 ), Text(course.courseTitle, style: TextStyle( fontSize: 22,), textAlign: TextAlign.center,), ], ), )), )); }); setState(() { itemsData = listItems; }); }); } /// This widget is to display vendor's details and courses Widget build(BuildContext context) { return DefaultTabController( length: 2, child: Scaffold( appBar: AppBar( title: Text( 'Power Up!', style: TextStyle(color: Colors.black, fontSize: 28), ), centerTitle: true, backgroundColor: Colors.white, elevation: 0, ), body: Stack(children: [ Container( decoration: BoxDecoration( image: DecorationImage( image: AssetImage('assets/background.png'), fit: BoxFit.cover, ))), Column( children: <Widget>[ Row( children: [ SizedBox(height: 30), Container( height: 30, width: 140, child: RaisedButton( shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(30), ), color: Colors.blue, hoverColor: Colors.lightBlueAccent, onPressed: () { /// navigates back to login page Navigator.of(context).pushAndRemoveUntil(MaterialPageRoute(builder: (context) => LoginPage()), (Route<dynamic> route) => false); }, child: Text('Log Out', style: TextStyle( fontSize: 20, color: Colors.white)))) ], ), Icon( Icons.account_circle, size: 100, ), /// vendor's details displayed on profile page SizedBox(height: 10), Text("Company Name: ${widget.vendor.companyName}", style: TextStyle(fontSize: 20)), SizedBox(height: 10), Text("Name of POC: ${widget.vendor.nameOfPOC}", style: TextStyle(fontSize: 20)), SizedBox(height: 10), Text("Email: ${widget.vendor.emailAddress}", style: TextStyle(fontSize: 20)), SizedBox(height: 10), Text( "Contact Number: ${widget.vendor.contactNumOfPOC}", style: TextStyle(fontSize: 20), ), SizedBox(height: 20), Expanded( child: Container( child: Column(children: [ SizedBox(height: 10), Row( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Padding( padding: EdgeInsets.fromLTRB(20, 10, 0, 10), child: Text( "My Courses", textAlign: TextAlign.center, style: TextStyle( fontSize: 23, fontWeight: FontWeight.bold), ), ), SizedBox(width: 50), Container( height: 30, width: 140, child: RaisedButton( shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(30), ), color: Colors.blue, hoverColor: Colors.lightBlueAccent, onPressed: () { /// navigates to course form page for vendor to add course Navigator.of(context).push( MaterialPageRoute( builder: (context) => CourseFormPage( widget.vendor.companyName, widget.vendor.nameOfPOC, widget.vendor.contactNumOfPOC, widget.vendor )) ); }, /// add course button child: Text('Add Course', style: TextStyle( fontSize: 20, color: Colors.white)))) ], ), Expanded( child: ListView.builder( controller: scrollController, itemCount: itemsData.length, physics: BouncingScrollPhysics(), itemBuilder: (context, index) { return itemsData[index]; })), ]), color: Colors.grey[350], ), ), ], ), ]), ), ); } }
0
mirrored_repositories/Power-Up/lib
mirrored_repositories/Power-Up/lib/entities/User.dart
class User { String _name; String _DOB; String _emailAddress; int _contactNum; String _passwordU; String _NOKname; int _NOKcontactNum; /// Singleton static final User _inst = new User._internal(); User._internal(); factory User( String _name, String _DOB, String _emailAddress, int _contactNum, String _passwordU, String _NOKname, int _NOKcontactNum ) { _inst._name = _name; _inst._DOB = _DOB; _inst._emailAddress = _emailAddress; _inst._contactNum = _contactNum; _inst._passwordU = _passwordU; _inst._NOKname = _NOKname; _inst._NOKcontactNum = _NOKcontactNum; return _inst; } User.fromMap(Map<String,dynamic> map){ _name = map['name']; _DOB = map['DOB']; _emailAddress = map['emailAddress']; _contactNum= map['contactNum']; _passwordU= map['passwordU']; _NOKname= map['NOKname']; _NOKcontactNum= map['NOKcontactNum']; } /// This function maps the local variables of a User instance and returns a map Map<String,dynamic> toMap() { var map = <String,dynamic>{ 'name':_name, 'DOB': _DOB, 'emailAddress': _emailAddress, 'contactNum': _contactNum, 'passwordU': _passwordU, 'NOKname': _NOKname, 'NOKcontactNum': _NOKcontactNum, }; return map; } /// This function is a getter for the local variable name String get name => _name; /// This function is a setter for the local variable name set name(String value) { _name = value; } /// This function is a getter for the local variable DOB String get DOB => _DOB; /// This function is a setter for the local variable DOB set DOB(String value) { _DOB = value; } /// This function is a getter for the local variable emailAddress String get emailAddress => _emailAddress; /// This function is a setter for the local variable emailAddress set emailAddress(String value) { _emailAddress = value; } /// This function is a getter for the local variable contactNum int get contactNum => _contactNum; /// This function is a setter for the local variable contactNum set contactNum(int value) { _contactNum = value; } /// This function is a getter for the local variable passwordU String get passwordU => _passwordU; /// This function is a setter for the local variable passwordU set passwordU(String value) { _passwordU = value; } /// This function is a getter for the local variable NOKname String get NOKname => _NOKname; /// This function is a setter for the local variable NOKname set NOKname(String value) { _NOKname = value; } /// This function is a getter for the local variable NOKcontactNum int get NOKcontactNum => _NOKcontactNum; /// This function is a setter for the local variable NOKcontactNum set NOKcontactNum(int value) { _NOKcontactNum = value; } }
0
mirrored_repositories/Power-Up/lib
mirrored_repositories/Power-Up/lib/entities/Course.dart
class Course{ int _courseID; String _courseTitle; String _courseDesc; String _company; double _rating; double _price; String _url; String _location; String _ageGroup; String _nameOfPOC; int _contactNumOfPOC; String _startDate; String _regDeadline; /// Singleton static final Course _inst = new Course._internal(); Course._internal(); factory Course( String _courseTitle, String _courseDesc, String _company, double _rating, double _price, String _url, String _location, String _ageGroup, String _nameOfPOC, int _contactNumOfPOC, String _startDate, String _regDeadline, ) { _inst._courseTitle = _courseTitle; _inst._courseDesc = _courseDesc; _inst._company = _company; _inst._rating = _rating; _inst._price = _price; _inst._url = _url; _inst._location = _location; _inst._ageGroup = _ageGroup; _inst._nameOfPOC = _nameOfPOC; _inst._contactNumOfPOC = _contactNumOfPOC; _inst._startDate = _startDate; _inst._regDeadline = _regDeadline; return _inst; } Course.fromMap(Map<String,dynamic> map){ _courseID = map['courseID']; _courseTitle = map['courseTitle']; _courseDesc = map['courseDesc']; _company = map['companyName']; _rating = map['rating']; _price = map['price']; _url = map['url']; _location = map['location']; _ageGroup = map['ageGroup']; _nameOfPOC = map['nameOfPOC']; _regDeadline = map['regDeadline']; } Course.forHomePage(Map<String,dynamic> map){ _courseID = map['courseID']; _courseTitle = map['courseTitle']; _courseDesc = map['courseDesc']; _company = map['companyName']; _rating = map['rating']; _price = map['price']; _url = map['url']; _location = map['location']; _ageGroup = map['ageGroup']; _nameOfPOC = map['nameOfPOC']; _contactNumOfPOC = map['contactNumOfPOC']; _startDate = map['startDate']; _regDeadline = map['regDeadline']; } /// This function maps the local variables of a Course instance and returns a map Map<String, dynamic> toMap(){ var map = <String, dynamic>{ 'courseID' : _courseID, 'courseTitle' : _courseTitle, 'courseDesc' : _courseDesc, 'companyName' : _company, 'rating' : _rating, 'price' : _price, 'url' : _url, 'location' : _location, 'ageGroup' : _ageGroup, 'nameOfPOC' : _nameOfPOC, 'contactNumOfPOC' : _contactNumOfPOC, 'startDate' : _startDate, 'regDeadline' : _regDeadline, }; return map; } /// This function is a getter for the local variable courseID int get courseID => _courseID; /// This function is a setter for the local variable courseID set courseID(int value) { _courseID = value; } /// This function is a getter for the local variable courseTitle String get courseTitle => _courseTitle; /// This function is a setter for the local variable courseTitle set courseTitle(String value) { _courseTitle = value; } /// This function is a getter for the local variable courseDesc String get courseDesc => _courseDesc; /// This function is a setter for the local variable courseDesc set courseDesc(String value) { _courseDesc = value; } /// This function is a getter for the local variable company String get company => _company; /// This function is a setter for the local variable company set company(String value) { _company = value; } /// This function is a getter for the local variable rating double get rating => _rating; /// This function is a setter for the local variable rating set rating(double value) { _rating = value; } /// This function is a getter for the local variable price double get price => _price; /// This function is a setter for the local variable price set price(double value) { _price = value; } /// This function is a getter for the local variable url String get url => _url; /// This function is a setter for the local variable url set url(String value) { _url = value; } /// This function is a getter for the local variable location String get location => _location; /// This function is a setter for the local variable location set location(String value) { _location = value; } /// This function is a getter for the local variable ageGroup String get ageGroup => _ageGroup; /// This function is a setter for the local variable ageGroup set ageGroup(String value) { _ageGroup = value; } /// This function is a getter for the local variable nameOfPOC String get nameOfPOC => _nameOfPOC; /// This function is a setter for the local variable nameOfPOC set nameOfPOC(String value) { _nameOfPOC = value; } /// This function is a getter for the local variable contactNumOfPOC int get contactNumOfPOC => _contactNumOfPOC; /// This function is a setter for the local variable contactNumOfPOC set contactNumOfPOC(int value) { _contactNumOfPOC = value; } /// This function is a getter for the local variable startDate String get startDate => _startDate; /// This function is a setter for the local variable startDate set startDate(String value) { _startDate = value; } /// This function is a getter for the local variable regDeadline String get regDeadline => _regDeadline; /// This function is a setter for the local variable regDeadline set regDeadline(String value) { _regDeadline = value; } }
0
mirrored_repositories/Power-Up/lib
mirrored_repositories/Power-Up/lib/entities/Session.dart
class Session{ int _sessionID; String _startDate; String _dateTime; int _vacancy; int _classSize; List<String> participantList; /// Singleton static final Session _inst = new Session._internal(); Session._internal(); factory Session( String _startDate, String _dateTime, int _vacancy, int _classSize, ) { _inst._startDate = _startDate; _inst._dateTime = _dateTime; _inst._vacancy = _vacancy; _inst._classSize = _classSize; return _inst; } factory Session.empty(){return _inst;} Session.fromMap(Map<String, dynamic> map) { _sessionID = map['sessionID']; _startDate = map['startDate']; _dateTime = map['dateTime']; _vacancy = map['vacancy']; _classSize = map['classSize']; } /// This function maps the local variables of a Session instance and returns a map Map<String, dynamic> toMap() { var map = <String, dynamic> { "sessionID":_sessionID, "startDate":_startDate, "dateTime": _dateTime, "vacancy":_vacancy, "classSize": _classSize, }; return map; } /// This function is a getter for the local variable sessionID int get sessionID => _sessionID; /// This function is a setter for the local variable sessionID set sessionID(int value) { _sessionID = value; } /// This function is a getter for the local variable startDate String get startDate => _startDate; /// This function is a setter for the local variable startDate set startDate(String value) { _startDate = value; } /// This function is a getter for the local variable dateTime String get dateTime => _dateTime; /// This function is a setter for the local variable dateTime set dateTime(String value) { _dateTime = value; } /// This function is a getter for the local variable vacancy int get vacancy => _vacancy; /// This function is a setter for the local variable vacancy set vacancy(int value) { _vacancy = value; } /// This function is a getter for the local variable classSize int get classSize => this._classSize; /// This function is a setter for the local variable classSize set classSize(int value) { _classSize = value; } /// This function is a getter for the local variable participantList List<String> get participantListTotal => this.participantList; /// This function is a setter for the local variable participantList set participantListTotal(List<String> participantEmail) { participantList = participantEmail; } /// This function adds a new User to a Session's participant list and decreases /// the Session's vacancy void addToParticipantList(String participantEmail){ participantList.add(participantEmail); _vacancy--; } /// This function removes an existing User from a Session's participant list and increases /// the Session's vacancy void removeFromParticipantList(String participantEmail){ participantList.remove(participantEmail); _vacancy++; } }
0
mirrored_repositories/Power-Up/lib
mirrored_repositories/Power-Up/lib/entities/Vendor.dart
class Vendor{ String _emailAddress; String _nameOfPOC; int _contactNumOfPOC; String _passwordV; String _busRegNum; String _companyName; /// Singleton static final Vendor _inst = new Vendor._internal(); Vendor._internal(); factory Vendor( String _emailAddress, String _nameOfPOC, int _contactNumOfPOC, String _passwordV, String _busRegNum, String _companyName ) { _inst._emailAddress = _emailAddress; _inst._nameOfPOC = _nameOfPOC; _inst._contactNumOfPOC = _contactNumOfPOC; _inst._passwordV = _passwordV; _inst._busRegNum = _busRegNum; _inst._companyName = _companyName; return _inst; } Vendor.fromMap(Map<String,dynamic> map){ _emailAddress=map['emailAddress']; _nameOfPOC= map['nameOfPOC']; _contactNumOfPOC=map['contactNumOfPOC']; _passwordV=map['passwordV']; _busRegNum=map['busRegNum']; _companyName=map['companyName']; } /// This function maps the local variables of a Vendor instance and returns a map Map<String,dynamic> toMap() { return { 'emailAddress':_emailAddress, 'nameOfPOC':_nameOfPOC, 'contactNumOfPOC':_contactNumOfPOC, 'passwordV':_passwordV, 'busRegNum':_busRegNum, 'companyName':_companyName, }; } /// This function is a getter for the local variable emailAddress String get emailAddress => _emailAddress; /// This function is a setter for the local variable emailAddress set emailAddress(String value) { _emailAddress = value; } /// This function is a getter for the local variable nameOfPOC String get nameOfPOC => _nameOfPOC; /// This function is a setter for the local variable nameOfPOC set nameOfPOC(String value) { _nameOfPOC = value; } /// This function is a getter for the local variable contactNumOfPOC int get contactNumOfPOC => _contactNumOfPOC; /// This function is a setter for the local variable contactNumOfPOC set contactNumOfPOC(int value) { _contactNumOfPOC = value; } /// This function is a getter for the local variable passwordV String get passwordV => _passwordV; /// This function is a setter for the local variable passwordV set passwordV(String value) { _passwordV = value; } /// This function is a getter for the local variable busRegNum String get busRegNum => _busRegNum; /// This function is a setter for the local variable busRegNum set busRegNum(String value) { _busRegNum = value; } /// This function is a getter for the local variable companyName String get companyName => _companyName; /// This function is a setter for the local variable companyName set companyName(String value) { _companyName = value; } }
0
mirrored_repositories/Power-Up
mirrored_repositories/Power-Up/test/widget_test.dart
// This is a basic Flutter widget test. // // To perform an interaction with a widget in your test, use the WidgetTester // utility that Flutter provides. For example, you can send tap and scroll // gestures. You can also use WidgetTester to find child widgets in the widget // tree, read text, and verify that the values of widget properties are correct. import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('Counter increments smoke test', (WidgetTester tester) async { // Build our app and trigger a frame. await tester.pumpWidget(MyApp()); // Verify that our counter starts at 0. expect(find.text('0'), findsOneWidget); expect(find.text('1'), findsNothing); // Tap the '+' icon and trigger a frame. await tester.tap(find.byIcon(Icons.add)); await tester.pump(); // Verify that our counter has incremented. expect(find.text('0'), findsNothing); expect(find.text('1'), findsOneWidget); }); }
0
mirrored_repositories/TokTik-App
mirrored_repositories/TokTik-App/lib/main.dart
import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import 'package:toktik/config/theme/app_theme.dart'; import 'package:toktik/domain/datasources/video_posts_datasource.dart'; import 'package:toktik/domain/repositories/video_posts_repository.dart'; import 'package:toktik/infraestructure/datasources/local_video_datasource_impl.dart'; import 'package:toktik/infraestructure/repositories/video_posts_repository_impl.dart'; import 'package:toktik/presentation/providers/discover_provider.dart'; import 'package:toktik/presentation/screens/discover/discover_screen.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { final VideoPostRepository videoPostRepository = VideoPostsRepositoryImpl( videoPostsDatasource: LocalVideoDatasourceImpl()); return MultiProvider( providers: [ ChangeNotifierProvider( lazy: false, create: (_) => DiscoverProvider( videoPostRepository: videoPostRepository)..loadNextPage()), ], child: MaterialApp( debugShowCheckedModeBanner: false, title: 'Tok Tik', theme: AppTheme().getTheme(), home: const DiscoverScreen() ), ); } }
0
mirrored_repositories/TokTik-App/lib/shared
mirrored_repositories/TokTik-App/lib/shared/data/local_video_posts.dart
List<Map<String, dynamic>> videoPosts = [ { 'name': 'Subiendo escaleras automáticas', 'videoUrl': 'assets/videos/1.mp4', 'likes': 23230, 'views': 1523, }, { 'name': 'Planta apreciada por peatones', 'videoUrl': 'assets/videos/2.mp4', 'likes': 24230, 'views': 1343, }, { 'name': 'Que borroso veo todo!', 'videoUrl': 'assets/videos/3.mp4', 'likes': 21564320, 'views': 123563, }, { 'name': '¿Esto es trigo? que interesante', 'videoUrl': 'assets/videos/4.mp4', 'likes': 320, 'views': 2300, }, { 'name': 'El COVID no me afecta', 'videoUrl': 'assets/videos/5.mp4', 'likes': 3230, 'views': 31030, }, { 'name': 'No quiero ir a trabajar hoy señor Stark', 'videoUrl': 'assets/videos/6.mp4', 'likes': 10, 'views': 330, }, { 'name': 'Limpiar nunca fue tan divertido', 'videoUrl': 'assets/videos/7.mp4', 'likes': 1320, 'views': 33032, }, { 'name': '¿Ya llegamos a la India?... umm si', 'videoUrl': 'assets/videos/8.mp4', 'likes': 342, 'views': 3332, }, ];
0
mirrored_repositories/TokTik-App/lib/config
mirrored_repositories/TokTik-App/lib/config/theme/app_theme.dart
import 'package:flutter/material.dart'; class AppTheme { ThemeData getTheme() => ThemeData( useMaterial3: true, brightness: Brightness.dark ); }
0
mirrored_repositories/TokTik-App/lib/config
mirrored_repositories/TokTik-App/lib/config/helpers/human_formats.dart
import 'package:intl/intl.dart'; class HumanFormats { static String humanReadbleNumber( double number ){ final formatterNumber = NumberFormat.compactCurrency( decimalDigits: 0, symbol: '' ).format(number); return formatterNumber; } }
0
mirrored_repositories/TokTik-App/lib/presentation/widgets
mirrored_repositories/TokTik-App/lib/presentation/widgets/shared/video_scrollable_view.dart
import 'package:flutter/material.dart'; import 'package:toktik/domain/entities/video_post.dart'; import 'package:toktik/presentation/widgets/shared/video_buttons.dart'; import 'package:toktik/presentation/widgets/videos/full_screen_player.dart'; class VideoScrollableView extends StatelessWidget { final List<VideoPost> videos; const VideoScrollableView({ super.key, required this.videos }); @override Widget build(BuildContext context) { return PageView.builder( scrollDirection: Axis.vertical, physics: const BouncingScrollPhysics(), itemCount: videos.length, itemBuilder: (context, index) { final videoPost = videos[index]; return Stack( children: [ FullScreenPlayer(caption: videoPost.caption , urlVideo: videoPost.videoUrl), // const Placeholder(), Positioned( bottom: 40, right: 40, child: VideoButtons(video: videoPost) ), ], ); }, ); } }
0
mirrored_repositories/TokTik-App/lib/presentation/widgets
mirrored_repositories/TokTik-App/lib/presentation/widgets/shared/video_buttons.dart
import 'package:flutter/material.dart'; import 'package:toktik/config/helpers/human_formats.dart'; import 'package:toktik/domain/entities/video_post.dart'; import 'package:animate_do/animate_do.dart'; class VideoButtons extends StatelessWidget { final VideoPost video; const VideoButtons({ super.key, required this.video }); @override Widget build(BuildContext context) { return Column( children: [ _CustomIconButton( value: video.likes, iconColor: Colors.red, iconData: Icons.favorite ), const SizedBox(height: 16,), _CustomIconButton( value: video.views, iconData: Icons.remove_red_eye_outlined ), const SizedBox(height: 16,), Spin( infinite: true, duration: const Duration(seconds: 5), child: const _CustomIconButton( value: 0, iconData: Icons.play_circle_outline ) ), ], ); } } class _CustomIconButton extends StatelessWidget { final int value; final IconData iconData; final Color? color; const _CustomIconButton({ required this.value, required this.iconData, iconColor, }): color = iconColor ?? Colors.white; @override Widget build(BuildContext context) { return Column( children: [ IconButton( onPressed: () {}, icon: Icon(iconData, color: color, size: 40,) ), if(value > 0) Text(HumanFormats.humanReadbleNumber(value.toDouble())) ], ); } }
0
mirrored_repositories/TokTik-App/lib/presentation/widgets
mirrored_repositories/TokTik-App/lib/presentation/widgets/videos/video_background.dart
import 'package:flutter/material.dart'; class VideoBackground extends StatelessWidget { final List<Color> colors; final List<double> stops; const VideoBackground({ super.key, this.colors = const [ Colors.transparent, Colors.black87 ], this.stops = const [ 0.5, 1.0 ] }):assert(colors.length == stops.length, "Stops and Colors must be same length"); @override Widget build(BuildContext context) { return Positioned.fill( child: DecoratedBox( decoration: BoxDecoration( gradient: LinearGradient( colors: colors, stops: stops, begin: Alignment.topCenter, end: Alignment.bottomCenter ), ) ) ); } }
0
mirrored_repositories/TokTik-App/lib/presentation/widgets
mirrored_repositories/TokTik-App/lib/presentation/widgets/videos/full_screen_player.dart
import 'package:flutter/material.dart'; import 'package:toktik/presentation/widgets/videos/video_background.dart'; import 'package:video_player/video_player.dart'; class FullScreenPlayer extends StatefulWidget { final String caption; final String urlVideo; const FullScreenPlayer({ super.key, required this.caption, required this.urlVideo, }); @override State<FullScreenPlayer> createState() => _FullScreenPlayerState(); } class _FullScreenPlayerState extends State<FullScreenPlayer> { late VideoPlayerController controller; @override void initState() { super.initState(); controller = VideoPlayerController.asset( widget.urlVideo ) ..setVolume(0) ..setLooping(true) ..play(); } @override void dispose() { controller.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return FutureBuilder( future: controller.initialize(), builder: (context, snapshot) { if( snapshot.connectionState != ConnectionState.done) { return const Center(child: CircularProgressIndicator( strokeWidth: 2,)); } return GestureDetector( onTap: () { if ( controller.value.isPlaying ) { controller.pause(); return; } controller.play(); }, // child: AspectRatio( // aspectRatio: controller.value.aspectRatio, // child: Placeholder()), child: AspectRatio( // TODO: AspectRatio genera errores inesperados, suerte con resolverlo aspectRatio: controller.value.aspectRatio, child: Stack( children: [ VideoPlayer(controller), // const Placeholder(), // Gradiente VideoBackground(stops: const [0.8,1.0],), // Texto Positioned( bottom: 50, left: 20, child: _CaptionVideo(caption: widget.caption), ) ]), ), ); }, ); } } class _CaptionVideo extends StatelessWidget { final String caption; const _CaptionVideo({ required this.caption }); @override Widget build(BuildContext context) { final size = MediaQuery.of(context).size; final styleTheme = Theme.of(context).textTheme.titleLarge; return SizedBox( width: size.width * 0.6, child: Text( caption, maxLines: 2, style: styleTheme),); } }
0
mirrored_repositories/TokTik-App/lib/presentation/screens
mirrored_repositories/TokTik-App/lib/presentation/screens/discover/discover_screen.dart
import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import 'package:toktik/presentation/providers/discover_provider.dart'; import 'package:toktik/presentation/widgets/shared/video_scrollable_view.dart'; class DiscoverScreen extends StatelessWidget { const DiscoverScreen({super.key}); @override Widget build(BuildContext context) { final discoverProvider = context.watch<DiscoverProvider>(); // final otroDiscoverProvider = Provider.of<DiscoverProvider>(context); return Scaffold( body: Center( child: (discoverProvider.initialLoading) ? const Center(child: CircularProgressIndicator( strokeWidth: 2,)) : VideoScrollableView(videos: discoverProvider.videos ) ), ); } }
0
mirrored_repositories/TokTik-App/lib/presentation
mirrored_repositories/TokTik-App/lib/presentation/providers/discover_provider.dart
import 'package:flutter/material.dart'; import 'package:toktik/domain/entities/video_post.dart'; import 'package:toktik/domain/repositories/video_posts_repository.dart'; import 'package:toktik/infraestructure/models/local_video_model.dart'; import 'package:toktik/shared/data/local_video_posts.dart'; class DiscoverProvider extends ChangeNotifier{ final VideoPostRepository videoPostRepository; bool initialLoading = true; List<VideoPost> videos = []; DiscoverProvider({ required this.videoPostRepository }); Future<void> loadNextPage() async { await Future.delayed(const Duration(seconds: 5)); final newVideos = videoPosts.map((json) => LocalVideoModel.fromJsonMap(json).toVideoPostEntity()).toList(); videos.addAll(newVideos); initialLoading = false; notifyListeners(); } }
0
mirrored_repositories/TokTik-App/lib/domain
mirrored_repositories/TokTik-App/lib/domain/entities/video_post.dart
class VideoPost { String caption; String videoUrl; int likes; int views; VideoPost({ required this.caption, required this.videoUrl, this.likes = 0, this.views = 0 }); }
0
mirrored_repositories/TokTik-App/lib/domain
mirrored_repositories/TokTik-App/lib/domain/datasources/video_posts_datasource.dart
import 'package:toktik/domain/entities/video_post.dart'; abstract class VideoPostsDatasource{ Future<List<VideoPost>> getFavoriteVideosByUser( String userID ); Future<List<VideoPost>> getTrendingVideosByPage( int page ); }
0
mirrored_repositories/TokTik-App/lib/domain
mirrored_repositories/TokTik-App/lib/domain/repositories/video_posts_repository.dart
import 'package:toktik/domain/entities/video_post.dart'; abstract class VideoPostRepository{ Future<List<VideoPost>> getFavoriteVideosByUser( String userID ); Future<List<VideoPost>> getTrendingVideosByPage( int page ); }
0