Merge pull request 'BUILD 92' (#842) from main into test-flight

Reviewed-on: eatvio/eatvio_app#842
This commit is contained in:
mso7nueh
2025-12-26 11:17:03 +00:00
37 changed files with 1111 additions and 1030 deletions

View File

@@ -31,3 +31,6 @@ abstract class OAuthVerificationConfirmResponse with _$OAuthVerificationConfirmR

View File

@@ -25,3 +25,6 @@ abstract class OAuthVerificationRequestResponse with _$OAuthVerificationRequestR

View File

@@ -1,166 +1,124 @@
import 'package:eatvio_app/core/locator_service.dart'; import 'package:eatvio_app/core/locator_service.dart';
import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart';
import 'package:eatvio_app/core/utils/toasts.dart'; import 'package:eatvio_app/core/utils/toasts.dart';
import 'package:eatvio_app/core/widgets/custom_text_form_field.dart'; import 'package:eatvio_app/core/widgets/custom_text_form_field.dart';
import 'package:eatvio_app/features/auth/presentation/bloc/reset_password_cubit/reset_password_cubit.dart'; import 'package:eatvio_app/features/auth/presentation/bloc/reset_password_cubit/reset_password_cubit.dart';
import 'package:eatvio_app/features/auth/presentation/bloc/reset_password_cubit/reset_password_state.dart'; import 'package:eatvio_app/features/auth/presentation/bloc/reset_password_cubit/reset_password_state.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter/services.dart';
import 'package:go_router/go_router.dart'; import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:go_router/go_router.dart';
class ForgetPasswordScreen extends StatefulWidget {
final bool isAuth; class ForgetPasswordScreen extends StatefulWidget {
const ForgetPasswordScreen({super.key, required this.isAuth}); final bool isAuth;
const ForgetPasswordScreen({super.key, required this.isAuth});
@override
State<ForgetPasswordScreen> createState() => _ForgetPasswordScreenState(); @override
} State<ForgetPasswordScreen> createState() => _ForgetPasswordScreenState();
}
class _ForgetPasswordScreenState extends State<ForgetPasswordScreen> {
final emailController = TextEditingController(); class _ForgetPasswordScreenState extends State<ForgetPasswordScreen> {
final codeController = TextEditingController(); final emailController = TextEditingController();
final passwordController = TextEditingController(); final codeController = TextEditingController();
final passwordConfirmController = TextEditingController(); final passwordController = TextEditingController();
final passwordConfirmController = TextEditingController();
@override
Widget build(BuildContext context) { @override
return BlocProvider<ResetPasswordCubit>( Widget build(BuildContext context) {
create: (BuildContext context) => sl<ResetPasswordCubit>(), return BlocProvider<ResetPasswordCubit>(
child: BlocConsumer<ResetPasswordCubit, ResetPasswordState>( create: (BuildContext context) => sl<ResetPasswordCubit>(),
builder: (BuildContext context, ResetPasswordState state) { child: BlocConsumer<ResetPasswordCubit, ResetPasswordState>(
return Scaffold( builder: (BuildContext context, ResetPasswordState state) {
appBar: AppBar( return Scaffold(
title: widget.isAuth ? const Text('Смена пароля') : const Text('Восстановление пароля'), appBar: AppBar(title: widget.isAuth ? const Text('Смена пароля') : const Text('Восстановление пароля'), centerTitle: false),
centerTitle: false, body: state is ResetPasswordStateLoadingResetPassword || state is ResetPasswordStateLoadingSendEmailCode
), ? const Center(child: CircularProgressIndicator())
body: state is ResetPasswordStateLoadingResetPassword || state is ResetPasswordStateLoadingSendEmailCode : Padding(
? const Center( padding: const EdgeInsets.all(16),
child: CircularProgressIndicator(), child: Column(
) crossAxisAlignment: CrossAxisAlignment.start,
: Padding( children: [
padding: const EdgeInsets.all(16), if (state is ResetPasswordStateCodeSendError || state is ResetPasswordStateEmpty) ...[
child: Column( Text(
crossAxisAlignment: CrossAxisAlignment.start, '${widget.isAuth ? '' : 'Забыли пароль? '}Укажите свой email,\nи мы пришлём код для сброса.',
children: [ style: const TextStyle(fontSize: 16, fontWeight: FontWeight.w500),
if (state is ResetPasswordStateCodeSendError || state is ResetPasswordStateEmpty) ...[ ),
Text( const SizedBox(height: 24),
'${widget.isAuth ? '' : 'Забыли пароль? '}Укажите свой email,\nи мы пришлём код для сброса.', const Text('E-mail', style: TextStyle(fontSize: 14, fontWeight: FontWeight.w500)),
style: const TextStyle( const SizedBox(height: 4),
fontSize: 16, CustomTextFormField(controller: emailController, hintText: 'Введите e-mail'),
fontWeight: FontWeight.w500, ],
), if (state is ResetPasswordStateCodeSendSuccess || state is ResetPasswordStateResetPasswordError) ...[
), const Text('Код', style: TextStyle(fontSize: 14, fontWeight: FontWeight.w500)),
const SizedBox(height: 24), const SizedBox(height: 4),
const Text( CustomTextFormField(controller: codeController, hintText: 'Введите код'),
'E-mail', const SizedBox(height: 12),
style: TextStyle( const Text('Пароль', style: TextStyle(fontSize: 14, fontWeight: FontWeight.w500)),
fontSize: 14, const SizedBox(height: 4),
fontWeight: FontWeight.w500, CustomTextFormField(
), controller: passwordController,
), hintText: 'Введите новый пароль',
const SizedBox(height: 4), inputFormatters: [FilteringTextInputFormatter.deny(RegExp(r'\s'))],
CustomTextFormField( ),
controller: emailController, const SizedBox(height: 12),
hintText: 'Введите e-mail', const Text('Подтвердите пароль', style: TextStyle(fontSize: 14, fontWeight: FontWeight.w500)),
), const SizedBox(height: 4),
], CustomTextFormField(
if (state is ResetPasswordStateCodeSendSuccess || state is ResetPasswordStateResetPasswordError) ...[ controller: passwordConfirmController,
const Text( hintText: 'Введите новый пароль',
'Код', inputFormatters: [FilteringTextInputFormatter.deny(RegExp(r'\s'))],
style: TextStyle( ),
fontSize: 14, ],
fontWeight: FontWeight.w500, const Spacer(),
), InkWell(
), onTap: () {
const SizedBox(height: 4), if (state is ResetPasswordStateCodeSendSuccess || state is ResetPasswordStateResetPasswordError) {
CustomTextFormField( context.read<ResetPasswordCubit>().tryResetPassword(
controller: codeController, emailController.text,
hintText: 'Введите код', codeController.text,
), passwordController.text,
const SizedBox(height: 12), passwordConfirmController.text,
const Text( );
'Пароль', } else {
style: TextStyle( context.read<ResetPasswordCubit>().trySendEmailCode(emailController.text);
fontSize: 14, }
fontWeight: FontWeight.w500, },
), borderRadius: BorderRadius.circular(20),
), child: Ink(
const SizedBox(height: 4), width: MediaQuery.of(context).size.width - 32,
CustomTextFormField( padding: const EdgeInsets.all(16),
controller: passwordController, decoration: BoxDecoration(borderRadius: BorderRadius.circular(20), color: appTheme.blueA400),
hintText: 'Введите новый пароль', child: Center(
), child: Text(
const SizedBox(height: 12), state is ResetPasswordStateCodeSendSuccess || state is ResetPasswordStateResetPasswordError
const Text( ? 'Сменить пароль'
'Подтвердите пароль', : 'Сбросить пароль',
style: TextStyle( style: const TextStyle(fontSize: 18, fontWeight: FontWeight.w600, color: Colors.white),
fontSize: 14, ),
fontWeight: FontWeight.w500, ),
), ),
), ),
const SizedBox(height: 4), ],
CustomTextFormField( ),
controller: passwordConfirmController, ),
hintText: 'Введите новый пароль', );
), },
], listener: (BuildContext context, ResetPasswordState state) {
const Spacer(), if (state is ResetPasswordStateCodeSendSuccess) {
InkWell( showSuccessToast('Код на почту успешно отправлен');
onTap: () { }
if (state is ResetPasswordStateCodeSendSuccess || state is ResetPasswordStateResetPasswordError) { if (state is ResetPasswordStateCodeSendError) {
context.read<ResetPasswordCubit>().tryResetPassword( showErrorToast('Ошибка отправки кода. Проверьте правильность ввёдной почты');
emailController.text, }
codeController.text, if (state is ResetPasswordStateResetPasswordError) {
passwordController.text, showErrorToast('Ошибка смены пароля. Проверьте правильность ввёднного кода и совпадение пароля');
passwordConfirmController.text, }
); if (state is ResetPasswordStateResetPassowrdSuccess) {
} else { GoRouter.of(context).pop();
context.read<ResetPasswordCubit>().trySendEmailCode(emailController.text); showSuccessToast('Пароль успешно сменён. ${widget.isAuth ? '' : 'Войдите в аккаунт'}');
} }
}, },
borderRadius: BorderRadius.circular(20), ),
child: Ink( );
width: MediaQuery.of(context).size.width - 32, }
padding: const EdgeInsets.all(16), }
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
color: appTheme.blueA400,
),
child: Center(
child: Text(
state is ResetPasswordStateCodeSendSuccess || state is ResetPasswordStateResetPasswordError
? 'Сменить пароль'
: 'Сбросить пароль',
style: const TextStyle(
fontSize: 18,
fontWeight: FontWeight.w600,
color: Colors.white,
),
),
),
),
),
],
),
),
);
},
listener: (BuildContext context, ResetPasswordState state) {
if (state is ResetPasswordStateCodeSendSuccess) {
showSuccessToast('Код на почту успешно отправлен');
}
if (state is ResetPasswordStateCodeSendError) {
showErrorToast('Ошибка отправки кода. Проверьте правильность ввёдной почты');
}
if (state is ResetPasswordStateResetPasswordError) {
showErrorToast('Ошибка смены пароля. Проверьте правильность ввёднного кода и совпадение пароля');
}
if (state is ResetPasswordStateResetPassowrdSuccess) {
GoRouter.of(context).pop();
showSuccessToast('Пароль успешно сменён. ${widget.isAuth ? '' : 'Войдите в аккаунт'}');
}
},
),
);
}
}

View File

@@ -19,3 +19,6 @@ abstract class BarcodeService {

View File

@@ -1,378 +1,388 @@
import 'package:eatvio_app/core/utils/image_constant.dart'; import 'package:eatvio_app/core/utils/image_constant.dart';
import 'package:eatvio_app/core/widgets/loader.dart'; import 'package:eatvio_app/core/widgets/loader.dart';
import 'package:eatvio_app/features/registration/presentation/bloc/registration_cubit/registration_cubit.dart'; import 'package:eatvio_app/features/registration/presentation/bloc/registration_cubit/registration_cubit.dart';
import 'package:eatvio_app/features/registration/presentation/bloc/registration_cubit/registration_state.dart'; import 'package:eatvio_app/features/registration/presentation/bloc/registration_cubit/registration_state.dart';
import 'package:eatvio_app/features/registration/presentation/pages/additional_information_screen.dart'; import 'package:eatvio_app/features/registration/presentation/pages/additional_information_screen.dart';
import 'package:eatvio_app/features/registration/presentation/pages/allergies_screen.dart'; import 'package:eatvio_app/features/registration/presentation/pages/allergies_screen.dart';
import 'package:eatvio_app/features/registration/presentation/pages/blood_pressure_screen.dart'; import 'package:eatvio_app/features/registration/presentation/pages/blood_pressure_screen.dart';
import 'package:eatvio_app/features/registration/presentation/pages/body_circumferences_screen.dart'; import 'package:eatvio_app/features/registration/presentation/pages/body_circumferences_screen.dart';
import 'package:eatvio_app/features/registration/presentation/pages/city_of_living_screen.dart'; import 'package:eatvio_app/features/registration/presentation/pages/city_of_living_screen.dart';
import 'package:eatvio_app/features/registration/presentation/pages/credentials_screen.dart'; import 'package:eatvio_app/features/registration/presentation/pages/credentials_screen.dart';
import 'package:eatvio_app/features/registration/presentation/pages/date_of_birth_screen.dart'; import 'package:eatvio_app/features/registration/presentation/pages/date_of_birth_screen.dart';
import 'package:eatvio_app/features/registration/presentation/pages/favorite_foods_screen.dart'; import 'package:eatvio_app/features/registration/presentation/pages/favorite_foods_screen.dart';
import 'package:eatvio_app/features/registration/presentation/pages/favorite_sports_screen.dart'; import 'package:eatvio_app/features/registration/presentation/pages/favorite_sports_screen.dart';
import 'package:eatvio_app/features/registration/presentation/pages/gender_screen.dart'; import 'package:eatvio_app/features/registration/presentation/pages/gender_screen.dart';
import 'package:eatvio_app/features/registration/presentation/pages/height_screen.dart'; import 'package:eatvio_app/features/registration/presentation/pages/height_screen.dart';
import 'package:eatvio_app/features/registration/presentation/pages/medicine_intake_screen.dart'; import 'package:eatvio_app/features/registration/presentation/pages/medicine_intake_screen.dart';
import 'package:eatvio_app/features/registration/presentation/pages/name_screen.dart'; import 'package:eatvio_app/features/registration/presentation/pages/name_screen.dart';
import 'package:eatvio_app/features/registration/presentation/pages/phone_screen.dart'; import 'package:eatvio_app/features/registration/presentation/pages/phone_screen.dart';
import 'package:eatvio_app/features/registration/presentation/pages/weight_screen.dart'; import 'package:eatvio_app/features/registration/presentation/pages/weight_screen.dart';
import 'package:eatvio_app/features/registration/services/registration_analytics_service.dart'; import 'package:eatvio_app/features/registration/services/registration_analytics_service.dart';
import 'package:eatvio_app/generated/l10n.dart'; import 'package:eatvio_app/generated/l10n.dart';
import 'package:eatvio_app/core/locator_service.dart'; import 'package:eatvio_app/core/locator_service.dart';
import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_svg/flutter_svg.dart'; import 'package:flutter_svg/flutter_svg.dart';
import 'package:go_router/go_router.dart'; import 'package:go_router/go_router.dart';
import 'package:validators/validators.dart'; import 'package:validators/validators.dart';
class RegistrationScreen extends StatefulWidget { class RegistrationScreen extends StatefulWidget {
const RegistrationScreen({super.key}); const RegistrationScreen({super.key});
@override @override
State<RegistrationScreen> createState() => _RegistrationScreenState(); State<RegistrationScreen> createState() => _RegistrationScreenState();
} }
class _RegistrationScreenState extends State<RegistrationScreen> { class _RegistrationScreenState extends State<RegistrationScreen> {
double progressValue = 1 / 15; double progressValue = 1 / 15;
int step = 1; int step = 1;
final pageController = PageController(); final pageController = PageController();
final RegistrationCubit registrationCubit = sl<RegistrationCubit>(); final RegistrationCubit registrationCubit = sl<RegistrationCubit>();
@override @override
void initState() { void initState() {
super.initState(); super.initState();
RegistrationAnalyticsService.reportRegistrationStep(step); RegistrationAnalyticsService.reportRegistrationStep(step);
} }
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return BlocProvider<RegistrationCubit>( return BlocProvider<RegistrationCubit>(
create: (BuildContext context) => registrationCubit, create: (BuildContext context) => registrationCubit,
child: BlocListener<RegistrationCubit, RegistrationState>( child: BlocListener<RegistrationCubit, RegistrationState>(
listener: (context, state) { listener: (context, state) {
if (state.error != null && state.error!.isNotEmpty) { if (state.error != null && state.error!.isNotEmpty) {
showDialog( showDialog(
context: context, context: context,
builder: (context) => AlertDialog( builder: (context) => AlertDialog(
title: const Text('Ошибка при регистрации'), title: const Text('Ошибка при регистрации'),
content: Text(state.error!), content: Text(state.error!),
actions: [TextButton(onPressed: () => Navigator.pop(context), child: const Text('OK'))], actions: [TextButton(onPressed: () => Navigator.pop(context), child: const Text('OK'))],
), ),
); );
} }
}, },
child: BlocBuilder<RegistrationCubit, RegistrationState>( child: BlocBuilder<RegistrationCubit, RegistrationState>(
builder: (BuildContext context, RegistrationState state) { builder: (BuildContext context, RegistrationState state) {
return Scaffold( return Scaffold(
floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat, floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
floatingActionButton: Row( floatingActionButton: Row(
children: [ children: [
Container( Container(
height: 48, height: 48,
width: MediaQuery.of(context).size.width * 0.2, width: MediaQuery.of(context).size.width * 0.2,
padding: const EdgeInsets.only(left: 16, right: 4), padding: const EdgeInsets.only(left: 16, right: 4),
child: FloatingActionButton.extended( child: FloatingActionButton.extended(
heroTag: 'backButtonRegistration', heroTag: 'backButtonRegistration',
highlightElevation: 0, highlightElevation: 0,
focusElevation: 0, focusElevation: 0,
elevation: 0, elevation: 0,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)), shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
backgroundColor: const Color(0xFFEAF2FD), backgroundColor: const Color(0xFFEAF2FD),
onPressed: () async { onPressed: () async {
setState(() { setState(() {
pageController.previousPage(duration: const Duration(milliseconds: 350), curve: Curves.easeInOut); pageController.previousPage(duration: const Duration(milliseconds: 350), curve: Curves.easeInOut);
}); });
}, },
label: Icon(Icons.arrow_back_ios_new_rounded, color: appTheme.blueA400), label: Icon(Icons.arrow_back_ios_new_rounded, color: appTheme.blueA400),
), ),
), ),
Container( Container(
height: 48, height: 48,
width: MediaQuery.of(context).size.width * 0.8, width: MediaQuery.of(context).size.width * 0.8,
padding: const EdgeInsets.only(left: 4, right: 16), padding: const EdgeInsets.only(left: 4, right: 16),
child: FloatingActionButton.extended( child: FloatingActionButton.extended(
heroTag: 'nextButtonRegistration', heroTag: 'nextButtonRegistration',
highlightElevation: 0, highlightElevation: 0,
elevation: 0, elevation: 0,
focusElevation: 0, focusElevation: 0,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)), shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
backgroundColor: appTheme.blueA400, backgroundColor: appTheme.blueA400,
onPressed: () async { onPressed: () async {
if (await canGoNext(state, context)) { if (await canGoNext(state, context)) {
setState(() { setState(() {
pageController.nextPage(duration: const Duration(milliseconds: 350), curve: Curves.easeInOut); pageController.nextPage(duration: const Duration(milliseconds: 350), curve: Curves.easeInOut);
}); });
} }
}, },
label: Text('Продолжить', style: theme.textTheme.titleSmall!.copyWith(color: Colors.white)), label: Text('Продолжить', style: theme.textTheme.titleSmall!.copyWith(color: Colors.white)),
), ),
), ),
], ],
), ),
appBar: AppBar( appBar: AppBar(
automaticallyImplyLeading: false, automaticallyImplyLeading: false,
leading: Builder( leading: Builder(
builder: (context) => IconButton(icon: const Icon(Icons.close_rounded), onPressed: () => GoRouter.of(context).pop()), builder: (context) => IconButton(icon: const Icon(Icons.close_rounded), onPressed: () => GoRouter.of(context).pop()),
), ),
centerTitle: true, centerTitle: true,
title: SvgPicture.asset(ImageConstant.imgLogoEatvio, height: 48, fit: BoxFit.contain), title: SvgPicture.asset(ImageConstant.imgLogoEatvio, height: 48, fit: BoxFit.contain),
actions: [Padding(padding: const EdgeInsets.only(right: 16), child: Text('шаг $step из 15'))], actions: [Padding(padding: const EdgeInsets.only(right: 16), child: Text('шаг $step из 15'))],
bottom: PreferredSize( bottom: PreferredSize(
preferredSize: Size(MediaQuery.of(context).size.width, 32), preferredSize: Size(MediaQuery.of(context).size.width, 32),
child: Padding( child: Padding(
padding: const EdgeInsets.all(16), padding: const EdgeInsets.all(16),
child: TweenAnimationBuilder<double>( child: TweenAnimationBuilder<double>(
duration: const Duration(milliseconds: 350), duration: const Duration(milliseconds: 350),
curve: Curves.easeInOut, curve: Curves.easeInOut,
tween: Tween<double>(begin: 1 / 15, end: progressValue), tween: Tween<double>(begin: 1 / 15, end: progressValue),
builder: (context, value, _) => LinearProgressIndicator( builder: (context, value, _) => LinearProgressIndicator(
value: value, value: value,
borderRadius: BorderRadius.circular(16), borderRadius: BorderRadius.circular(16),
minHeight: 8, minHeight: 8,
backgroundColor: Colors.grey.shade100, backgroundColor: Colors.grey.shade100,
valueColor: AlwaysStoppedAnimation<Color>(appTheme.blueA400), valueColor: AlwaysStoppedAnimation<Color>(appTheme.blueA400),
), ),
), ),
), ),
), ),
), ),
body: PageView( body: PageView(
physics: const NeverScrollableScrollPhysics(), physics: const NeverScrollableScrollPhysics(),
controller: pageController, controller: pageController,
onPageChanged: (index) { onPageChanged: (index) {
setState(() { setState(() {
step = index + 1; step = index + 1;
progressValue = step / 15; progressValue = step / 15;
}); });
// Report analytics for step completion // Report analytics for step completion
RegistrationAnalyticsService.reportRegistrationStep(step); RegistrationAnalyticsService.reportRegistrationStep(step);
}, },
children: [ children: [
// LanguageSelectScreen(sheet: state.sheet), // LanguageSelectScreen(sheet: state.sheet),
PhoneScreen(sheet: state.sheet), PhoneScreen(sheet: state.sheet),
CredentialsScreen(sheet: state.sheet), CredentialsScreen(sheet: state.sheet),
NameScreen(sheet: state.sheet), NameScreen(sheet: state.sheet),
GenderScreen(sheet: state.sheet), GenderScreen(sheet: state.sheet),
DateOfBirthScreen(sheet: state.sheet), DateOfBirthScreen(sheet: state.sheet),
CityOfLivingScreen(sheet: state.sheet), CityOfLivingScreen(sheet: state.sheet),
BodyCircumferencesScreen(sheet: state.sheet), BodyCircumferencesScreen(sheet: state.sheet),
WeightScreen(sheet: state.sheet), WeightScreen(sheet: state.sheet),
HeightScreen(sheet: state.sheet), HeightScreen(sheet: state.sheet),
BloodPressureScreen(sheet: state.sheet), BloodPressureScreen(sheet: state.sheet),
AllergiesScreen(sheet: state.sheet), AllergiesScreen(sheet: state.sheet),
MedicineIntakeScreen(sheet: state.sheet), MedicineIntakeScreen(sheet: state.sheet),
FavoriteSportsScreen(sheet: state.sheet), FavoriteSportsScreen(sheet: state.sheet),
FavoriteFoodsScreen(sheet: state.sheet), FavoriteFoodsScreen(sheet: state.sheet),
AdditionalInformationScreen(sheet: state.sheet), AdditionalInformationScreen(sheet: state.sheet),
], ],
), ),
); );
}, },
), ),
), ),
); );
} }
Future<bool> canGoNext(RegistrationState state, BuildContext context) async { Future<bool> canGoNext(RegistrationState state, BuildContext context) async {
switch (step) { switch (step) {
case 1: case 1:
if (state.sheet.phone.length != 18) { if (state.sheet.phone.length != 18) {
showDialog( showDialog(
context: context, context: context,
builder: (context) => AlertDialog( builder: (context) => AlertDialog(
title: const Text('Ошибка'), title: const Text('Ошибка'),
content: const Text('Введите корректный номер телефона'), content: const Text('Введите корректный номер телефона'),
actions: [TextButton(onPressed: () => Navigator.pop(context), child: const Text('OK'))], actions: [TextButton(onPressed: () => Navigator.pop(context), child: const Text('OK'))],
), ),
); );
return false; return false;
} else { } else {
return true; return true;
} }
case 2: case 2:
List<String> errors = validateCredentialsFields(state.sheet.email, state.sheet.password, state.sheet.passwordConfirmation, context); List<String> errors = validateCredentialsFields(state.sheet.email, state.sheet.password, state.sheet.passwordConfirmation, context);
if (errors.isEmpty) { if (errors.isEmpty) {
return true; return true;
} else { } else {
String errorMessage = ''; String errorMessage = '';
for (var error in errors) { for (var error in errors) {
errorMessage += '$error\n\n'; errorMessage += '$error\n\n';
} }
showDialog( showDialog(
context: context, context: context,
builder: (context) => AlertDialog( builder: (context) => AlertDialog(
title: const Text('Ошибка'), title: const Text('Ошибка'),
content: Text(errorMessage), content: Text(errorMessage),
actions: [TextButton(onPressed: () => Navigator.pop(context), child: const Text('OK'))], actions: [TextButton(onPressed: () => Navigator.pop(context), child: const Text('OK'))],
), ),
); );
return false; return false;
} }
case 3: case 3:
List<String> errors = validateNameFields(state.sheet.firstName.toString(), state.sheet.lastName.toString(), context); List<String> errors = validateNameFields(state.sheet.firstName.toString(), state.sheet.lastName.toString(), context);
if (errors.isEmpty) { if (errors.isEmpty) {
return true; return true;
} else { } else {
String errorMessage = ''; String errorMessage = '';
for (var error in errors) { for (var error in errors) {
errorMessage += '$error\n\n'; errorMessage += '$error\n\n';
} }
showDialog( showDialog(
context: context, context: context,
builder: (context) => AlertDialog( builder: (context) => AlertDialog(
title: const Text('Ошибка'), title: const Text('Ошибка'),
content: Text(errorMessage), content: Text(errorMessage),
actions: [TextButton(onPressed: () => Navigator.pop(context), child: const Text('OK'))], actions: [TextButton(onPressed: () => Navigator.pop(context), child: const Text('OK'))],
), ),
); );
return false; return false;
} }
case 4: case 4:
if (state.sheet.gender.isNotEmpty) { if (state.sheet.gender.isNotEmpty) {
return true; return true;
} else { } else {
showDialog( showDialog(
context: context, context: context,
builder: (context) => AlertDialog( builder: (context) => AlertDialog(
title: const Text('Ошибка'), title: const Text('Ошибка'),
content: const Text('Выберете пол'), content: const Text('Выберете пол'),
actions: [TextButton(onPressed: () => Navigator.pop(context), child: const Text('OK'))], actions: [TextButton(onPressed: () => Navigator.pop(context), child: const Text('OK'))],
), ),
); );
return false; return false;
} }
case 6: case 6:
if (state.sheet.location.isNotEmpty) { if (state.sheet.location.isNotEmpty) {
return true; return true;
} else { } else {
showDialog( showDialog(
context: context, context: context,
builder: (context) => AlertDialog( builder: (context) => AlertDialog(
title: const Text('Ошибка'), title: const Text('Ошибка'),
content: const Text('Заполните все поля'), content: const Text('Заполните все поля'),
actions: [TextButton(onPressed: () => Navigator.pop(context), child: const Text('OK'))], actions: [TextButton(onPressed: () => Navigator.pop(context), child: const Text('OK'))],
), ),
); );
return false; return false;
} }
case 7: case 7:
List<String> errors = validateCircumferencesFields( List<String> errors = validateCircumferencesFields(
state.sheet.chestCircumference.toString(), state.sheet.chestCircumference.toString(),
state.sheet.waistCircumference.toString(), state.sheet.waistCircumference.toString(),
state.sheet.hipCircumference.toString(), state.sheet.hipCircumference.toString(),
context, context,
); );
if (errors.isEmpty) { if (errors.isEmpty) {
return true; return true;
} else { } else {
String errorMessage = ''; String errorMessage = '';
for (var error in errors) { for (var error in errors) {
errorMessage += '$error\n\n'; errorMessage += '$error\n\n';
} }
showDialog( showDialog(
context: context, context: context,
builder: (context) => AlertDialog( builder: (context) => AlertDialog(
title: const Text('Ошибка'), title: const Text('Ошибка'),
content: Text(errorMessage), content: Text(errorMessage),
actions: [TextButton(onPressed: () => Navigator.pop(context), child: const Text('OK'))], actions: [TextButton(onPressed: () => Navigator.pop(context), child: const Text('OK'))],
), ),
); );
return false; return false;
} }
case 15: case 15:
try { try {
showDialog( showDialog(
barrierDismissible: false, barrierDismissible: false,
useSafeArea: false, useSafeArea: false,
context: context, context: context,
builder: (context) => const PopScope(canPop: false, child: Loader()), builder: (context) => const PopScope(canPop: false, child: Loader()),
); );
await registrationCubit.tryRegistration(); await registrationCubit.tryRegistration();
if (context.mounted) { if (context.mounted) {
Navigator.pop(context); Navigator.pop(context);
} }
} catch (e) { } catch (e) {
if (context.mounted) { if (context.mounted) {
Navigator.pop(context); Navigator.pop(context);
showDialog( String errorMessage = '';
context: context, if (e is String) {
builder: (context) => const AlertDialog(title: Text('Ошибка при попытке регистрации')), errorMessage = e;
); } else {
} errorMessage = e.toString().replaceFirst('Exception: ', '').replaceFirst('Error: ', '');
} }
return false; showDialog(
default: context: context,
return true; builder: (context) => AlertDialog(
} title: const Text('Ошибка при регистрации'),
} content: Text(errorMessage.isNotEmpty ? errorMessage : 'Регистрация не удалась'),
actions: [TextButton(onPressed: () => Navigator.pop(context), child: const Text('OK'))],
List<String> validateCircumferencesFields(String chestCircumference, String waistCircumference, String hipCircumference, BuildContext context) { ),
final s = S.of(context); );
}
List<String> errors = []; }
return false;
if (chestCircumference.isEmpty | waistCircumference.isEmpty | hipCircumference.isEmpty) { default:
errors.add(s.circumference_empty); return true;
} }
}
if (![chestCircumference, waistCircumference, hipCircumference].every((circumference) => int.tryParse(circumference) != null)) {
errors.add(s.circumference_is_not_a_number); List<String> validateCircumferencesFields(String chestCircumference, String waistCircumference, String hipCircumference, BuildContext context) {
} final s = S.of(context);
return errors; List<String> errors = [];
}
if (chestCircumference.isEmpty | waistCircumference.isEmpty | hipCircumference.isEmpty) {
List<String> validateCredentialsFields(String email, String password, String passwordConfirmation, BuildContext context) { errors.add(s.circumference_empty);
final s = S.of(context); }
List<String> errors = []; if (![chestCircumference, waistCircumference, hipCircumference].every((circumference) => int.tryParse(circumference) != null)) {
errors.add(s.circumference_is_not_a_number);
if (!isEmail(email)) { }
errors.add(s.email_invalid);
} return errors;
}
if (email.isEmpty) {
errors.add(s.email_empty); List<String> validateCredentialsFields(String email, String password, String passwordConfirmation, BuildContext context) {
} final s = S.of(context);
if (password.length < 6) { List<String> errors = [];
errors.add(s.password_short);
} if (!isEmail(email)) {
errors.add(s.email_invalid);
if (password != passwordConfirmation) { }
errors.add(s.password_confirmation_mismatch);
} if (email.isEmpty) {
errors.add(s.email_empty);
return errors; }
}
if (password.length < 6) {
List<String> validateNameFields(String firstName, String lastName, BuildContext context) { errors.add(s.password_short);
List<String> errors = []; }
if (firstName.isEmpty) { if (password != passwordConfirmation) {
errors.add('First name cannot be empty'); errors.add(s.password_confirmation_mismatch);
} }
if (firstName.isEmpty) { return errors;
errors.add('First name is too short'); }
}
List<String> validateNameFields(String firstName, String lastName, BuildContext context) {
if (lastName.isEmpty) { List<String> errors = [];
errors.add('Last name cannot be empty');
} if (firstName.isEmpty) {
errors.add('First name cannot be empty');
if (lastName.isEmpty) { }
errors.add('Last name is too short');
} if (firstName.isEmpty) {
errors.add('First name is too short');
return errors; }
}
} if (lastName.isEmpty) {
errors.add('Last name cannot be empty');
}
if (lastName.isEmpty) {
errors.add('Last name is too short');
}
return errors;
}
}

View File

@@ -1,238 +1,266 @@
import 'dart:developer'; import 'dart:developer';
import 'package:dio/dio.dart'; import 'package:dio/dio.dart';
import 'package:eatvio_app/core/token_storage.dart'; import 'package:eatvio_app/core/token_storage.dart';
import 'package:eatvio_app/core/utils/date_time_utils.dart'; import 'package:eatvio_app/core/utils/date_time_utils.dart';
import 'package:eatvio_app/features/registration_v2/cubit/registration_state.dart'; import 'package:eatvio_app/features/registration_v2/cubit/registration_state.dart';
import 'package:eatvio_app/features/registration_v2/models/registration_model.dart'; import 'package:eatvio_app/features/registration_v2/models/registration_model.dart';
import 'package:eatvio_app/features/registration_v2/repositories/registration_repository_v2.dart'; import 'package:eatvio_app/features/registration_v2/repositories/registration_repository_v2.dart';
import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:gpassword/gpassword.dart'; import 'package:gpassword/gpassword.dart';
class RegistrationCubitV2 extends Cubit<RegistrationStateV2> { class RegistrationCubitV2 extends Cubit<RegistrationStateV2> {
final RegistrationRepositoryV2 registrationRepository; final RegistrationRepositoryV2 registrationRepository;
RegistrationCubitV2({required this.registrationRepository}) : super(RegistrationStateV2()); RegistrationCubitV2({required this.registrationRepository}) : super(const RegistrationStateV2());
void setFirstName(String firstName) { void setFirstName(String firstName) {
emit(state.copyWith(firstName: firstName)); emit(state.copyWith(firstName: firstName));
validateFirstName(); validateFirstName();
} }
void setLastName(String lastName) { void setLastName(String lastName) {
emit(state.copyWith(lastName: lastName)); emit(state.copyWith(lastName: lastName));
validateLastName(); validateLastName();
} }
void setEmail(String email) { void setEmail(String email) {
emit(state.copyWith(email: email)); emit(state.copyWith(email: email));
validateEmail(); validateEmail();
} }
void setPhone(String phone) { void setPhone(String phone) {
emit(state.copyWith(phone: phone)); emit(state.copyWith(phone: phone));
validatePhone(); validatePhone();
} }
void setBirthday(DateTime birthday) { void setBirthday(DateTime birthday) {
emit(state.copyWith(birthday: birthday)); emit(state.copyWith(birthday: birthday));
validateBirthday(); validateBirthday();
} }
void setGender(String gender) { void setGender(String gender) {
emit(state.copyWith(gender: gender)); emit(state.copyWith(gender: gender));
validateGender(); validateGender();
} }
void setWeight(int weight) { void setWeight(int weight) {
emit(state.copyWith(weight: weight)); emit(state.copyWith(weight: weight));
validateWeight(); validateWeight();
} }
void setHeight(int height) { void setHeight(int height) {
emit(state.copyWith(height: height)); emit(state.copyWith(height: height));
validateHeight(); validateHeight();
} }
void setActivityCoefficient(double activityCoefficient) { void setActivityCoefficient(double activityCoefficient) {
emit(state.copyWith(activityCoefficient: activityCoefficient)); emit(state.copyWith(activityCoefficient: activityCoefficient));
validateActivityCoefficient(); validateActivityCoefficient();
} }
void setPassword(String password) { void setPassword(String password) {
emit(state.copyWith(password: password)); emit(state.copyWith(password: password));
} }
bool validateFirstName() { bool validateFirstName() {
if (state.firstName.isEmpty) { if (state.firstName.isEmpty) {
emit(state.copyWith(isFirstNameValid: false)); emit(state.copyWith(isFirstNameValid: false));
return false; return false;
} }
emit(state.copyWith(isFirstNameValid: true)); emit(state.copyWith(isFirstNameValid: true));
return true; return true;
} }
bool validateLastName() { bool validateLastName() {
if (state.lastName.isEmpty) { if (state.lastName.isEmpty) {
emit(state.copyWith(isLastNameValid: false)); emit(state.copyWith(isLastNameValid: false));
return false; return false;
} }
emit(state.copyWith(isLastNameValid: true)); emit(state.copyWith(isLastNameValid: true));
return true; return true;
} }
bool validateEmail() { bool validateEmail() {
if (state.email.isEmpty) { if (state.email.isEmpty) {
emit(state.copyWith(isEmailValid: false)); emit(state.copyWith(isEmailValid: false));
return false; return false;
} }
emit(state.copyWith(isEmailValid: true)); emit(state.copyWith(isEmailValid: true));
return true; return true;
} }
bool validatePhone() { bool validatePhone() {
if (state.phone.isEmpty) { if (state.phone.isEmpty) {
emit(state.copyWith(isPhoneValid: false)); emit(state.copyWith(isPhoneValid: false));
return false; return false;
} }
emit(state.copyWith(isPhoneValid: true)); emit(state.copyWith(isPhoneValid: true));
return true; return true;
} }
bool validateGender() { bool validateGender() {
if (state.gender.isEmpty) { if (state.gender.isEmpty) {
emit(state.copyWith(isGenderValid: false)); emit(state.copyWith(isGenderValid: false));
return false; return false;
} }
emit(state.copyWith(isGenderValid: true)); emit(state.copyWith(isGenderValid: true));
return true; return true;
} }
bool validateWeight() { bool validateWeight() {
if (state.weight == 0) { if (state.weight == 0) {
emit(state.copyWith(isWeightValid: false)); emit(state.copyWith(isWeightValid: false));
return false; return false;
} }
emit(state.copyWith(isWeightValid: true)); emit(state.copyWith(isWeightValid: true));
return true; return true;
} }
bool validateHeight() { bool validateHeight() {
if (state.height == 0) { if (state.height == 0) {
emit(state.copyWith(isHeightValid: false)); emit(state.copyWith(isHeightValid: false));
return false; return false;
} }
emit(state.copyWith(isHeightValid: true)); emit(state.copyWith(isHeightValid: true));
return true; return true;
} }
bool validateActivityCoefficient() { bool validateActivityCoefficient() {
if (state.activityCoefficient == 0) { if (state.activityCoefficient == 0) {
emit(state.copyWith(isActivityCoefficientValid: false)); emit(state.copyWith(isActivityCoefficientValid: false));
return false; return false;
} }
emit(state.copyWith(isActivityCoefficientValid: true)); emit(state.copyWith(isActivityCoefficientValid: true));
return true; return true;
} }
bool validateBirthday() { bool validateBirthday() {
if (state.birthday == null) { if (state.birthday == null) {
emit(state.copyWith(isBirthdayValid: false)); emit(state.copyWith(isBirthdayValid: false));
return false; return false;
} }
emit(state.copyWith(isBirthdayValid: true)); emit(state.copyWith(isBirthdayValid: true));
return true; return true;
} }
void nextStep() { void nextStep() {
emit(state.copyWith(step: 1)); emit(state.copyWith(step: 1));
} }
void prevStep() { void prevStep() {
emit(state.copyWith(step: 0)); emit(state.copyWith(step: 0));
} }
bool validateAllFields() { bool validateAllFields() {
if (!validateFirstName() || if (!validateFirstName() ||
!validateLastName() || !validateLastName() ||
!validateEmail() || !validateEmail() ||
!validatePhone() || !validatePhone() ||
!validateGender() || !validateGender() ||
!validateWeight() || !validateWeight() ||
!validateHeight() || !validateHeight() ||
!validateActivityCoefficient() || !validateActivityCoefficient() ||
!validateBirthday()) { !validateBirthday()) {
return false; return false;
} }
return true; return true;
} }
Future<(bool, bool)> register() async { Future<(bool, bool)> register() async {
if (!validateAllFields()) { if (!validateAllFields()) {
return (false, true); return (false, true);
} }
final birthday = state.birthday?.format('yyyy-MM-dd'); final birthday = state.birthday?.format('yyyy-MM-dd');
if (birthday == null) { if (birthday == null) {
validateBirthday(); validateBirthday();
return (false, true); return (false, true);
} }
final password = await _generatePassword(); final password = await _generatePassword();
final registrationModel = RegistrationModel( final registrationModel = RegistrationModel(
firstName: state.firstName, firstName: state.firstName,
lastName: state.lastName, lastName: state.lastName,
email: state.email, email: state.email,
phone: state.phone, phone: state.phone,
gender: state.gender, gender: state.gender,
password: password, password: password,
confirmPassword: password, confirmPassword: password,
weight: state.weight, weight: state.weight,
height: state.height, height: state.height,
activityCoefficient: state.activityCoefficient, activityCoefficient: state.activityCoefficient,
birthday: birthday, birthday: birthday,
); );
bool didApiComplainOnValidation = false; bool didApiComplainOnValidation = false;
try { String errorMessage = '';
final token = await registrationRepository.register(registrationModel: registrationModel); try {
if (token != null) { final token = await registrationRepository.register(registrationModel: registrationModel);
TokenStorage.saveTokenInStorage(token); if (token != null) {
return (true, false); TokenStorage.saveTokenInStorage(token);
} emit(state.copyWith(registrationError: null));
} on DioException catch (e) { return (true, false);
final errors = e.response?.data['errors'] as Map<String, dynamic>?; }
final emailErrors = errors?['email'] as List<dynamic>?; } on DioException catch (e) {
final phoneErrors = errors?['phone'] as List<dynamic>?; final errors = e.response?.data['errors'] as Map<String, dynamic>?;
final dateOfBirth = errors?['date_of_birth'] as List<dynamic>?; final emailErrors = errors?['email'] as List<dynamic>?;
if (emailErrors != null && emailErrors.isNotEmpty) { final phoneErrors = errors?['phone'] as List<dynamic>?;
if (emailErrors.contains('Некорректный формат email')) { final dateOfBirth = errors?['date_of_birth'] as List<dynamic>?;
emit(state.copyWith(isEmailValid: false, emailDisplayError: 'Некорректный формат email'));
didApiComplainOnValidation = true; // Собираем все ошибки для отображения в диалоге
} List<String> allErrors = [];
if (emailErrors.contains('Такой Эл. почта уже существует.')) {
emit(state.copyWith(isEmailValid: false, emailDisplayError: 'Такая Эл. почта уже существует.')); if (emailErrors != null && emailErrors.isNotEmpty) {
didApiComplainOnValidation = true; for (var error in emailErrors) {
} allErrors.add(error.toString());
} if (error.toString() == 'Некорректный формат email') {
if (phoneErrors != null && phoneErrors.isNotEmpty) { emit(state.copyWith(isEmailValid: false, emailDisplayError: 'Некорректный формат email'));
if (phoneErrors.contains('Такой phone уже существует.')) { didApiComplainOnValidation = true;
emit(state.copyWith(isPhoneValid: false, phoneDisplayError: 'Такой номер телефона уже существует.')); }
didApiComplainOnValidation = true; if (error.toString() == 'Такой Эл. почта уже существует.') {
} emit(state.copyWith(isEmailValid: false, emailDisplayError: 'Такая Эл. почта уже существует.'));
} didApiComplainOnValidation = true;
if (dateOfBirth != null && dateOfBirth.isNotEmpty) { }
if (dateOfBirth.contains('Некорректный формат даты рождения')) { }
emit(state.copyWith(isBirthdayValid: false, emailDisplayError: 'Некорректный формат даты рождения')); }
didApiComplainOnValidation = true; if (phoneErrors != null && phoneErrors.isNotEmpty) {
} for (var error in phoneErrors) {
} allErrors.add(error.toString());
} catch (e) { if (error.toString() == 'Такой phone уже существует.') {
log(e.toString()); emit(state.copyWith(isPhoneValid: false, phoneDisplayError: 'Такой номер телефона уже существует.'));
} didApiComplainOnValidation = true;
return (false, didApiComplainOnValidation); }
} }
}
Future<String> _generatePassword() async { if (dateOfBirth != null && dateOfBirth.isNotEmpty) {
final generator = GPassword(); for (var error in dateOfBirth) {
final password = generator.generate(passwordLength: 10); allErrors.add(error.toString());
emit(state.copyWith(password: password)); if (error.toString() == 'Некорректный формат даты рождения') {
return password; emit(state.copyWith(isBirthdayValid: false, dateOfBirthDisplayError: 'Некорректный формат даты рождения'));
} didApiComplainOnValidation = true;
} }
}
}
// Сохраняем все ошибки для отображения в диалоге
if (allErrors.isNotEmpty) {
errorMessage = allErrors.join('\n');
emit(state.copyWith(registrationError: errorMessage));
} else {
// Если нет конкретных ошибок, берем общее сообщение
final message = e.response?.data['message'] as String?;
errorMessage = message ?? 'Ошибка при регистрации';
emit(state.copyWith(registrationError: errorMessage));
}
} catch (e) {
log(e.toString());
errorMessage = e.toString();
emit(state.copyWith(registrationError: errorMessage));
}
return (false, didApiComplainOnValidation);
}
Future<String> _generatePassword() async {
final generator = GPassword();
final password = generator.generate(passwordLength: 10);
emit(state.copyWith(password: password));
return password;
}
}

View File

@@ -1,32 +1,33 @@
import 'package:freezed_annotation/freezed_annotation.dart'; import 'package:freezed_annotation/freezed_annotation.dart';
part 'registration_state.freezed.dart'; part 'registration_state.freezed.dart';
@freezed @freezed
abstract class RegistrationStateV2 with _$RegistrationStateV2 { abstract class RegistrationStateV2 with _$RegistrationStateV2 {
factory RegistrationStateV2({ const factory RegistrationStateV2({
@Default('') String firstName, @Default('') String firstName,
@Default('') String lastName, @Default('') String lastName,
@Default('') String email, @Default('') String email,
@Default('') String phone, @Default('') String phone,
@Default('') String gender, @Default('') String gender,
@Default('') String password, @Default('') String password,
@Default(0) int weight, @Default(0) int weight,
@Default(0) int height, @Default(0) int height,
@Default(1.2) double activityCoefficient, @Default(1.2) double activityCoefficient,
DateTime? birthday, DateTime? birthday,
@Default(true) bool isFirstNameValid, @Default(true) bool isFirstNameValid,
@Default(true) bool isLastNameValid, @Default(true) bool isLastNameValid,
@Default(true) bool isEmailValid, @Default(true) bool isEmailValid,
@Default(true) bool isPhoneValid, @Default(true) bool isPhoneValid,
@Default(true) bool isGenderValid, @Default(true) bool isGenderValid,
@Default(true) bool isWeightValid, @Default(true) bool isWeightValid,
@Default(true) bool isHeightValid, @Default(true) bool isHeightValid,
@Default(true) bool isActivityCoefficientValid, @Default(true) bool isActivityCoefficientValid,
@Default(true) bool isBirthdayValid, @Default(true) bool isBirthdayValid,
@Default(0) int step, @Default(0) int step,
@Default('') String emailDisplayError, @Default('') String emailDisplayError,
@Default('') String phoneDisplayError, @Default('') String phoneDisplayError,
@Default('') String dateOfBirthDisplayError, @Default('') String dateOfBirthDisplayError,
}) = _RegistrationStateV2; String? registrationError,
} }) = _RegistrationStateV2;
}

View File

@@ -137,7 +137,8 @@ class _SecondStepContentState extends State<SecondStepContent> {
setState(() { setState(() {
isLoading = false; isLoading = false;
}); });
if (context.mounted && !hasValidationError) { if (context.mounted) {
// Показываем bottom sheet всегда: при успехе или ошибке
showRegistrationBottomSheet(context, cubit, commonResult); showRegistrationBottomSheet(context, cubit, commonResult);
} }
}, },
@@ -157,7 +158,7 @@ class _SecondStepContentState extends State<SecondStepContent> {
child: RichText( child: RichText(
textAlign: TextAlign.center, textAlign: TextAlign.center,
text: TextSpan( text: TextSpan(
text: 'Нажимая “Зарегистрироваться”, Вы соглашаетесь \n', text: 'Нажимая "Зарегистрироваться", Вы соглашаетесь \n',
style: const TextStyle(fontSize: 12, color: Colors.black), style: const TextStyle(fontSize: 12, color: Colors.black),
children: [ children: [
const TextSpan(text: 'c '), const TextSpan(text: 'c '),

View File

@@ -76,7 +76,7 @@ class _RegistrationBottomSheetState extends State<RegistrationBottomSheet> {
buttonTextStyle: TextStyles.textMSemibold.copyWith(color: appTheme.whiteA700), buttonTextStyle: TextStyles.textMSemibold.copyWith(color: appTheme.whiteA700),
buttonStyle: ButtonStyle(side: const WidgetStatePropertyAll(BorderSide.none), backgroundColor: WidgetStatePropertyAll(appTheme.blueA400)), buttonStyle: ButtonStyle(side: const WidgetStatePropertyAll(BorderSide.none), backgroundColor: WidgetStatePropertyAll(appTheme.blueA400)),
onPressed: () async { onPressed: () async {
AppRouter.navigatorKey.currentContext?.go(RouteConstants.verifyEmailScreen); AppRouter.navigatorKey.currentContext?.go(RouteConstants.feedScreen);
}, },
), ),
const SizedBox(width: 20), const SizedBox(width: 20),
@@ -96,7 +96,12 @@ class _RegistrationBottomSheetState extends State<RegistrationBottomSheet> {
Padding( Padding(
padding: const EdgeInsets.only(bottom: 16.0), padding: const EdgeInsets.only(bottom: 16.0),
child: Text(s.error_desc, style: TextStyles.textMMediumAuto.copyWith(color: appTheme.darkGrey)), child: Text(
widget.cubit.state.registrationError?.isNotEmpty == true
? widget.cubit.state.registrationError!
: s.error_desc,
style: TextStyles.textMMediumAuto.copyWith(color: appTheme.darkGrey),
),
), ),
const SizedBox(width: 20), const SizedBox(width: 20),
], ],

View File

@@ -1,6 +1,6 @@
name: eatvio_app name: eatvio_app
description: A new Flutter project. description: A new Flutter project.
version: 1.3.10+90 version: 1.3.11+91
publish_to: 'none' publish_to: 'none'
environment: environment:

View File

@@ -151,6 +151,9 @@ void main() {

View File

@@ -86,6 +86,9 @@ void main() {

View File

@@ -100,6 +100,9 @@ void main() {

View File

@@ -49,6 +49,9 @@ void main() {

View File

@@ -45,6 +45,9 @@ void main() {

View File

@@ -42,6 +42,9 @@ void main() {

View File

@@ -125,6 +125,9 @@ void main() {

View File

@@ -49,6 +49,9 @@ void main() {

View File

@@ -43,6 +43,9 @@ void main() {

View File

@@ -68,6 +68,9 @@ void main() {

View File

@@ -150,6 +150,9 @@ void main() {

View File

@@ -154,6 +154,9 @@ void main() {

View File

@@ -91,6 +91,9 @@ void main() {

View File

@@ -80,6 +80,9 @@ void main() {

View File

@@ -73,6 +73,9 @@ void main() {

View File

@@ -105,6 +105,9 @@ void main() {

View File

@@ -66,6 +66,9 @@ void main() {

View File

@@ -77,5 +77,8 @@ void main() {

View File

@@ -1,83 +1,83 @@
import 'package:eatvio_app/core/app_config.dart'; import 'package:eatvio_app/core/app_config.dart';
import 'package:eatvio_app/core/app_initializer.dart'; import 'package:eatvio_app/core/app_initializer.dart';
import 'package:eatvio_app/core/locator_service.dart'; import 'package:eatvio_app/core/locator_service.dart';
import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart';
import 'package:eatvio_app/features/registration_v2/cubit/registration_cubit.dart'; import 'package:eatvio_app/features/registration_v2/cubit/registration_cubit.dart';
import 'package:eatvio_app/features/registration_v2/cubit/registration_state.dart'; import 'package:eatvio_app/features/registration_v2/cubit/registration_state.dart';
import 'package:eatvio_app/features/registration_v2/presentation/widgets/password_field.dart'; import 'package:eatvio_app/features/registration_v2/presentation/widgets/password_field.dart';
import 'package:eatvio_app/generated/l10n.dart'; import 'package:eatvio_app/generated/l10n.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_portal/flutter_portal.dart'; import 'package:flutter_portal/flutter_portal.dart';
import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_test/flutter_test.dart';
import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart';
import 'package:mockito/annotations.dart'; import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart'; import 'package:mockito/mockito.dart';
import 'password_field_test.mocks.dart'; import 'password_field_test.mocks.dart';
@GenerateNiceMocks([MockSpec<RegistrationCubitV2>()]) @GenerateNiceMocks([MockSpec<RegistrationCubitV2>()])
void main() { void main() {
group('PasswordField', () { group('PasswordField', () {
setUp(() async { setUp(() async {
await sl.reset(); await sl.reset();
dotenv.loadFromString(envString: 'DEV_BASE_URL=http://localhost\nBASE_URL=http://localhost'); dotenv.loadFromString(envString: 'DEV_BASE_URL=http://localhost\nBASE_URL=http://localhost');
sl.registerLazySingleton<AppConfig>(() => AppConfig(buildType: AppBuildType.tests)..setBaseUrl('http://localhost')); sl.registerLazySingleton<AppConfig>(() => AppConfig(buildType: AppBuildType.tests)..setBaseUrl('http://localhost'));
}); });
Widget createTestWidget(Widget child, RegistrationCubitV2 cubit) { Widget createTestWidget(Widget child, RegistrationCubitV2 cubit) {
return MaterialApp( return MaterialApp(
theme: ThemeHelper().themeData(), theme: ThemeHelper().themeData(),
localizationsDelegates: const [ localizationsDelegates: const [
S.delegate, S.delegate,
GlobalMaterialLocalizations.delegate, GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate, GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate, GlobalCupertinoLocalizations.delegate,
], ],
supportedLocales: const [Locale('ru')], supportedLocales: const [Locale('ru')],
home: Portal( home: Portal(
child: BlocProvider<RegistrationCubitV2>( child: BlocProvider<RegistrationCubitV2>(
create: (_) => cubit, create: (_) => cubit,
child: Scaffold(body: child), child: Scaffold(body: child),
), ),
), ),
); );
} }
testWidgets('should display password field with password from state', (WidgetTester tester) async { testWidgets('should display password field with password from state', (WidgetTester tester) async {
// Arrange // Arrange
final mockCubit = MockRegistrationCubitV2(); final mockCubit = MockRegistrationCubitV2();
const testPassword = 'testPassword123'; const testPassword = 'testPassword123';
when(mockCubit.state).thenReturn( when(mockCubit.state).thenReturn(
RegistrationStateV2(password: testPassword), const RegistrationStateV2(password: testPassword),
); );
final widget = PasswordField(cubit: mockCubit); final widget = PasswordField(cubit: mockCubit);
// Act // Act
await tester.pumpWidget(createTestWidget(widget, mockCubit)); await tester.pumpWidget(createTestWidget(widget, mockCubit));
await tester.pump(); await tester.pump();
// Assert // Assert
expect(find.byType(PasswordField), findsOneWidget); expect(find.byType(PasswordField), findsOneWidget);
expect(find.text(testPassword), findsOneWidget); expect(find.text(testPassword), findsOneWidget);
}); });
testWidgets('should show copy icon initially', (WidgetTester tester) async { testWidgets('should show copy icon initially', (WidgetTester tester) async {
// Arrange // Arrange
final mockCubit = MockRegistrationCubitV2(); final mockCubit = MockRegistrationCubitV2();
when(mockCubit.state).thenReturn( when(mockCubit.state).thenReturn(
RegistrationStateV2(password: 'test'), const RegistrationStateV2(password: 'test'),
); );
final widget = PasswordField(cubit: mockCubit); final widget = PasswordField(cubit: mockCubit);
// Act // Act
await tester.pumpWidget(createTestWidget(widget, mockCubit)); await tester.pumpWidget(createTestWidget(widget, mockCubit));
await tester.pump(); await tester.pump();
// Assert // Assert
expect(find.byType(PasswordField), findsOneWidget); expect(find.byType(PasswordField), findsOneWidget);
}); });
}); });
} }

View File

@@ -42,14 +42,14 @@ void main() {
testWidgets('displays sex widget', (tester) async { testWidgets('displays sex widget', (tester) async {
when(mockCubit.state).thenReturn( when(mockCubit.state).thenReturn(
RegistrationStateV2( const RegistrationStateV2(
step: 0, step: 0,
gender: '', gender: '',
isGenderValid: true, isGenderValid: true,
), ),
); );
when(mockCubit.stream).thenAnswer((_) => Stream.value( when(mockCubit.stream).thenAnswer((_) => Stream.value(
RegistrationStateV2( const RegistrationStateV2(
step: 0, step: 0,
gender: '', gender: '',
isGenderValid: true, isGenderValid: true,
@@ -64,14 +64,14 @@ void main() {
testWidgets('calls setGender when male is tapped', (tester) async { testWidgets('calls setGender when male is tapped', (tester) async {
when(mockCubit.state).thenReturn( when(mockCubit.state).thenReturn(
RegistrationStateV2( const RegistrationStateV2(
step: 0, step: 0,
gender: '', gender: '',
isGenderValid: true, isGenderValid: true,
), ),
); );
when(mockCubit.stream).thenAnswer((_) => Stream.value( when(mockCubit.stream).thenAnswer((_) => Stream.value(
RegistrationStateV2( const RegistrationStateV2(
step: 0, step: 0,
gender: '', gender: '',
isGenderValid: true, isGenderValid: true,
@@ -94,14 +94,14 @@ void main() {
testWidgets('shows error when gender is invalid', (tester) async { testWidgets('shows error when gender is invalid', (tester) async {
when(mockCubit.state).thenReturn( when(mockCubit.state).thenReturn(
RegistrationStateV2( const RegistrationStateV2(
step: 0, step: 0,
gender: '', gender: '',
isGenderValid: false, isGenderValid: false,
), ),
); );
when(mockCubit.stream).thenAnswer((_) => Stream.value( when(mockCubit.stream).thenAnswer((_) => Stream.value(
RegistrationStateV2( const RegistrationStateV2(
step: 0, step: 0,
gender: '', gender: '',
isGenderValid: false, isGenderValid: false,

View File

@@ -1,118 +1,118 @@
import 'package:eatvio_app/core/app_config.dart'; import 'package:eatvio_app/core/app_config.dart';
import 'package:eatvio_app/core/app_initializer.dart'; import 'package:eatvio_app/core/app_initializer.dart';
import 'package:eatvio_app/core/locator_service.dart'; import 'package:eatvio_app/core/locator_service.dart';
import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart';
import 'package:eatvio_app/features/registration_v2/cubit/registration_cubit.dart'; import 'package:eatvio_app/features/registration_v2/cubit/registration_cubit.dart';
import 'package:eatvio_app/features/registration_v2/cubit/registration_state.dart'; import 'package:eatvio_app/features/registration_v2/cubit/registration_state.dart';
import 'package:eatvio_app/features/registration_v2/presentation/widgets/show_successful_registration_bottom_sheet.dart'; import 'package:eatvio_app/features/registration_v2/presentation/widgets/show_successful_registration_bottom_sheet.dart';
import 'package:eatvio_app/generated/l10n.dart'; import 'package:eatvio_app/generated/l10n.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_portal/flutter_portal.dart'; import 'package:flutter_portal/flutter_portal.dart';
import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_test/flutter_test.dart';
import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart';
import 'package:mockito/annotations.dart'; import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart'; import 'package:mockito/mockito.dart';
import 'show_successful_registration_bottom_sheet_test.mocks.dart'; import 'show_successful_registration_bottom_sheet_test.mocks.dart';
@GenerateNiceMocks([MockSpec<RegistrationCubitV2>()]) @GenerateNiceMocks([MockSpec<RegistrationCubitV2>()])
void main() { void main() {
group('ShowSuccessfulRegistrationBottomSheet', () { group('ShowSuccessfulRegistrationBottomSheet', () {
setUp(() async { setUp(() async {
await sl.reset(); await sl.reset();
dotenv.loadFromString(envString: 'DEV_BASE_URL=http://localhost\nBASE_URL=http://localhost'); dotenv.loadFromString(envString: 'DEV_BASE_URL=http://localhost\nBASE_URL=http://localhost');
sl.registerLazySingleton<AppConfig>(() => AppConfig(buildType: AppBuildType.tests)..setBaseUrl('http://localhost')); sl.registerLazySingleton<AppConfig>(() => AppConfig(buildType: AppBuildType.tests)..setBaseUrl('http://localhost'));
}); });
Widget createTestWidget(Widget child, RegistrationCubitV2 cubit) { Widget createTestWidget(Widget child, RegistrationCubitV2 cubit) {
return MaterialApp( return MaterialApp(
theme: ThemeHelper().themeData(), theme: ThemeHelper().themeData(),
localizationsDelegates: const [ localizationsDelegates: const [
S.delegate, S.delegate,
GlobalMaterialLocalizations.delegate, GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate, GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate, GlobalCupertinoLocalizations.delegate,
], ],
supportedLocales: const [Locale('ru')], supportedLocales: const [Locale('ru')],
home: Portal( home: Portal(
child: BlocProvider<RegistrationCubitV2>( child: BlocProvider<RegistrationCubitV2>(
create: (_) => cubit, create: (_) => cubit,
child: Scaffold( child: Scaffold(
body: Builder( body: Builder(
builder: (context) => ElevatedButton( builder: (context) => ElevatedButton(
onPressed: () { onPressed: () {
showRegistrationBottomSheet(context, cubit, true); showRegistrationBottomSheet(context, cubit, true);
}, },
child: const Text('Show Bottom Sheet'), child: const Text('Show Bottom Sheet'),
), ),
), ),
), ),
), ),
), ),
); );
} }
testWidgets('should display success bottom sheet when isSuccess is true', (WidgetTester tester) async { testWidgets('should display success bottom sheet when isSuccess is true', (WidgetTester tester) async {
// Arrange // Arrange
final mockCubit = MockRegistrationCubitV2(); final mockCubit = MockRegistrationCubitV2();
when(mockCubit.state).thenReturn( when(mockCubit.state).thenReturn(
RegistrationStateV2(password: 'testPassword'), const RegistrationStateV2(password: 'testPassword'),
); );
// Act // Act
await tester.pumpWidget(createTestWidget(const SizedBox(), mockCubit)); await tester.pumpWidget(createTestWidget(const SizedBox(), mockCubit));
await tester.tap(find.text('Show Bottom Sheet')); await tester.tap(find.text('Show Bottom Sheet'));
await tester.pumpAndSettle(); await tester.pumpAndSettle();
// Assert // Assert
expect(find.byType(RegistrationBottomSheet), findsOneWidget); expect(find.byType(RegistrationBottomSheet), findsOneWidget);
}); });
testWidgets('should display error bottom sheet when isSuccess is false', (WidgetTester tester) async { testWidgets('should display error bottom sheet when isSuccess is false', (WidgetTester tester) async {
// Arrange // Arrange
final mockCubit = MockRegistrationCubitV2(); final mockCubit = MockRegistrationCubitV2();
when(mockCubit.state).thenReturn( when(mockCubit.state).thenReturn(
RegistrationStateV2(), const RegistrationStateV2(),
); );
Widget createTestWidgetError(Widget child, RegistrationCubitV2 cubit) { Widget createTestWidgetError(Widget child, RegistrationCubitV2 cubit) {
return MaterialApp( return MaterialApp(
theme: ThemeHelper().themeData(), theme: ThemeHelper().themeData(),
localizationsDelegates: const [ localizationsDelegates: const [
S.delegate, S.delegate,
GlobalMaterialLocalizations.delegate, GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate, GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate, GlobalCupertinoLocalizations.delegate,
], ],
supportedLocales: const [Locale('ru')], supportedLocales: const [Locale('ru')],
home: Portal( home: Portal(
child: BlocProvider<RegistrationCubitV2>( child: BlocProvider<RegistrationCubitV2>(
create: (_) => cubit, create: (_) => cubit,
child: Scaffold( child: Scaffold(
body: Builder( body: Builder(
builder: (context) => ElevatedButton( builder: (context) => ElevatedButton(
onPressed: () { onPressed: () {
showRegistrationBottomSheet(context, cubit, false); showRegistrationBottomSheet(context, cubit, false);
}, },
child: const Text('Show Bottom Sheet'), child: const Text('Show Bottom Sheet'),
), ),
), ),
), ),
), ),
), ),
); );
} }
// Act // Act
await tester.pumpWidget(createTestWidgetError(const SizedBox(), mockCubit)); await tester.pumpWidget(createTestWidgetError(const SizedBox(), mockCubit));
await tester.tap(find.text('Show Bottom Sheet')); await tester.tap(find.text('Show Bottom Sheet'));
await tester.pumpAndSettle(); await tester.pumpAndSettle();
// Assert // Assert
expect(find.byType(RegistrationBottomSheet), findsOneWidget); expect(find.byType(RegistrationBottomSheet), findsOneWidget);
}); });
}); });
} }

View File

@@ -43,9 +43,9 @@ void main() {
testWidgets('displays step widget', (tester) async { testWidgets('displays step widget', (tester) async {
when(mockCubit.state).thenReturn( when(mockCubit.state).thenReturn(
RegistrationStateV2(step: 0), const RegistrationStateV2(step: 0),
); );
when(mockCubit.stream).thenAnswer((_) => Stream.value(RegistrationStateV2(step: 0))); when(mockCubit.stream).thenAnswer((_) => Stream.value(const RegistrationStateV2(step: 0)));
await tester.pumpWidget(createTestWidget()); await tester.pumpWidget(createTestWidget());
await tester.pumpAndSettle(); await tester.pumpAndSettle();
@@ -55,9 +55,9 @@ void main() {
testWidgets('displays correct step number', (tester) async { testWidgets('displays correct step number', (tester) async {
when(mockCubit.state).thenReturn( when(mockCubit.state).thenReturn(
RegistrationStateV2(step: 2), const RegistrationStateV2(step: 2),
); );
when(mockCubit.stream).thenAnswer((_) => Stream.value(RegistrationStateV2(step: 2))); when(mockCubit.stream).thenAnswer((_) => Stream.value(const RegistrationStateV2(step: 2)));
await tester.pumpWidget(createTestWidget()); await tester.pumpWidget(createTestWidget());
await tester.pumpAndSettle(); await tester.pumpAndSettle();