feat(chat): add consultation progress and personal diet status

related to #1115
This commit is contained in:
2026-11-03 14:45:44 +03:00
parent 53ce73b41e
commit bd1155233f
35 changed files with 1999 additions and 265 deletions

View File

@@ -78,6 +78,66 @@ void main() {
meta: const ChatMetaModel(lastPage: 1),
);
const planForChosenPlanUpdates = PlanModel(
id: 1,
slug: 'test-plan',
name: 'Test Plan',
image: 'https://example.com/image.jpg',
duration: 7,
state: 'active',
type: PlanType(
fit: true,
slim: false,
behavior: false,
wellness: false,
),
details: 'Test details',
packetsCount: 3,
author: Author(
authorSlug: 'author',
authorName: 'Author Name',
authorProfileIcon: 'https://example.com/icon.jpg',
authorIsMe: false,
),
totalLikes: 10,
totalViews: 100,
totalComments: 5,
isFavorite: false,
minPriceOfOptions: 1000,
maxPriceOfOptions: 2000,
wasLikedByMe: false,
);
ChosenPlanModel buildChosenPlan(
int id,
ChosenPlanStateEnum chosenPlanState,
) {
return ChosenPlanModel(
id: id,
optionType: 'options1',
startDate: DateTime.now(),
chosenPlanState: chosenPlanState,
chatId: 'chat-id',
consultantId: 1,
plan: planForChosenPlanUpdates,
);
}
void stubChatChannel({
required Stream<ChannelReadEvent> chosenPlanStream,
}) {
when(mockWsManager.client).thenReturn(MockPusherChannelsClient());
when(
mockWsManager.directChatStream,
).thenAnswer((_) => const Stream<ChannelReadEvent>.empty());
when(
mockWsManager.clientTypingStream,
).thenAnswer((_) => const Stream<ChannelReadEvent>.empty());
when(
mockWsManager.chosenPlanStateChangedStream,
).thenAnswer((_) => chosenPlanStream);
}
setUp(() {
mockChatRepository = MockChatRepository();
mockCardsRepository = MockCardsRepository();
@@ -721,6 +781,160 @@ void main() {
},
);
test(
'chosenPlanStateChangedStream - перезапрашивает план и обновляет state',
() async {
const uuid = 'room-uuid';
const planId = 321;
final chosenPlan = buildChosenPlan(
planId,
ChosenPlanStateEnum.stateStarted,
);
final updatedPlan = chosenPlan.copyWith(
chosenPlanState: ChosenPlanStateEnum.statePaid,
);
final controller = StreamController<ChannelReadEvent>.broadcast();
when(
mockChatRepository.getChatRoom(uuid),
).thenAnswer((_) async => testChatRoom.copyWith(chosenPlanId: planId));
when(
mockChatRepository.getChatMessages(uuid, 1),
).thenAnswer((_) async => testChatMessages);
when(
mockChatRepository.getChosenPlan(id: planId),
).thenAnswer((_) async => chosenPlan);
stubChatChannel(chosenPlanStream: controller.stream);
await chatRoomCubit.initChat(uuid);
expect(chatRoomCubit.state, isA<ChatRoomStateLoaded>());
when(
mockChatRepository.getChosenPlan(id: planId),
).thenAnswer((_) async => updatedPlan);
clearInteractions(mockChatRepository);
controller.add(_FakeChannelReadEvent());
await Future<void>.delayed(const Duration(milliseconds: 350));
verify(mockChatRepository.getChosenPlan(id: planId)).called(1);
final state = chatRoomCubit.state as ChatRoomStateLoaded;
expect(
state.chatRoom.chosenPlan?.chosenPlanState,
ChosenPlanStateEnum.statePaid,
);
await controller.close();
},
);
test(
'chosenPlanStateChangedStream - использует chosenPlan.id если chosenPlanId null',
() async {
const orderId = 'alfa_c29_k15138_t1712345678_r1234';
const conversationUuid = 'fbd81429-8019-499a-80e8-e3933cc4d872';
const planId = 654;
final chosenPlan = buildChosenPlan(
planId,
ChosenPlanStateEnum.stateStarted,
);
final updatedPlan = chosenPlan.copyWith(
chosenPlanState: ChosenPlanStateEnum.statePaid,
);
final controller = StreamController<ChannelReadEvent>.broadcast();
when(
mockChatRepository.resolveOrderIdToConversation(orderId: orderId),
).thenAnswer(
(_) async => OrderIdToConversationModel(
chosenPlanId: planId,
conversationUuid: conversationUuid,
),
);
when(
mockChatRepository.getChatRoom(conversationUuid),
).thenAnswer((_) async => testChatRoom);
when(
mockChatRepository.getChatMessages(conversationUuid, 1),
).thenAnswer((_) async => testChatMessages);
when(
mockChatRepository.getChosenPlan(id: planId),
).thenAnswer((_) async => chosenPlan);
stubChatChannel(chosenPlanStream: controller.stream);
await chatRoomCubit.initChat(null, orderId: orderId);
final loaded = chatRoomCubit.state as ChatRoomStateLoaded;
expect(loaded.chatRoom.chosenPlanId, isNull);
expect(loaded.chatRoom.chosenPlan?.id, planId);
when(
mockChatRepository.getChosenPlan(id: planId),
).thenAnswer((_) async => updatedPlan);
clearInteractions(mockChatRepository);
controller.add(_FakeChannelReadEvent());
await Future<void>.delayed(const Duration(milliseconds: 350));
verify(mockChatRepository.getChosenPlan(id: planId)).called(1);
final state = chatRoomCubit.state as ChatRoomStateLoaded;
expect(
state.chatRoom.chosenPlan?.chosenPlanState,
ChosenPlanStateEnum.statePaid,
);
await controller.close();
},
);
test(
'chosenPlanStateChangedStream - дебаунсит повторные события',
() async {
const uuid = 'room-uuid';
const planId = 987;
final chosenPlan = buildChosenPlan(
planId,
ChosenPlanStateEnum.stateStarted,
);
final updatedPlan = chosenPlan.copyWith(
chosenPlanState: ChosenPlanStateEnum.statePaid,
);
final controller = StreamController<ChannelReadEvent>.broadcast();
when(
mockChatRepository.getChatRoom(uuid),
).thenAnswer((_) async => testChatRoom.copyWith(chosenPlanId: planId));
when(
mockChatRepository.getChatMessages(uuid, 1),
).thenAnswer((_) async => testChatMessages);
when(
mockChatRepository.getChosenPlan(id: planId),
).thenAnswer((_) async => chosenPlan);
stubChatChannel(chosenPlanStream: controller.stream);
await chatRoomCubit.initChat(uuid);
expect(chatRoomCubit.state, isA<ChatRoomStateLoaded>());
when(
mockChatRepository.getChosenPlan(id: planId),
).thenAnswer((_) async => updatedPlan);
clearInteractions(mockChatRepository);
controller
..add(_FakeChannelReadEvent())
..add(_FakeChannelReadEvent());
await Future<void>.delayed(const Duration(milliseconds: 350));
verify(mockChatRepository.getChosenPlan(id: planId)).called(1);
final state = chatRoomCubit.state as ChatRoomStateLoaded;
expect(
state.chatRoom.chosenPlan?.chosenPlanState,
ChosenPlanStateEnum.statePaid,
);
await controller.close();
},
);
test('choseStartPlanDate - устанавливает дату начала плана', () async {
const uuid = 'room-uuid';
const planId = 123;
@@ -2578,3 +2792,8 @@ void main() {
);
});
}
class _FakeChannelReadEvent extends Fake implements ChannelReadEvent {
@override
dynamic get data => null;
}

View File

@@ -0,0 +1,232 @@
import 'package:eatvio_app/features/chat/presentation/utils/chat_banner_resolver.dart';
import 'package:eatvio_app/features/chat/presentation/widgets/notification_banner.dart';
import 'package:eatvio_app/features/consultations/models/consultation_progress.dart';
import 'package:eatvio_app/features/consultations/utils/consultation_progress_mapper.dart';
import 'package:eatvio_app/features/plans/enums/chosen_plan_state_enum.dart';
import 'package:flutter_test/flutter_test.dart';
ConsultationProgress _progress(
ChosenPlanStateEnum state, {
bool hasPersonalDiet = false,
}) {
return mapConsultationProgress(
state: state,
hasPersonalDiet: hasPersonalDiet,
);
}
void main() {
group('resolveChatBanner — карта консультанта', () {
test('in_coordination без карты просит добавить карту', () {
final banner = resolveChatBanner(
progress: _progress(ChosenPlanStateEnum.stateInCoordination),
amIConsultant: true,
hasCard: false,
state: ChosenPlanStateEnum.stateInCoordination,
);
expect(banner, BannerType.card);
});
test('in_coordination с картой просит выбрать дату', () {
final banner = resolveChatBanner(
progress: _progress(ChosenPlanStateEnum.stateInCoordination),
amIConsultant: true,
hasCard: true,
state: ChosenPlanStateEnum.stateInCoordination,
);
expect(banner, BannerType.date);
});
test('paid + notProposed + диета просит предложить диету', () {
final banner = resolveChatBanner(
progress: _progress(
ChosenPlanStateEnum.statePaid,
hasPersonalDiet: true,
),
amIConsultant: true,
hasCard: true,
state: ChosenPlanStateEnum.statePaid,
);
expect(banner, BannerType.setPersonalDiet);
});
test(
'personal_diet_setted/started/in_progress + proposed просят сменить диету',
() {
const states = [
ChosenPlanStateEnum.personalDietSet,
ChosenPlanStateEnum.stateStarted,
ChosenPlanStateEnum.stateInProgress,
];
for (final state in states) {
final banner = resolveChatBanner(
progress: _progress(state, hasPersonalDiet: true),
amIConsultant: true,
hasCard: true,
state: state,
);
expect(
banner,
BannerType.changePersonalDiet,
reason: 'state=${state.name}',
);
}
},
);
test('last_day_finished не просит менять диету (нет баннера)', () {
final banner = resolveChatBanner(
progress: _progress(
ChosenPlanStateEnum.stateLastDayFinished,
hasPersonalDiet: true,
),
amIConsultant: true,
hasCard: true,
state: ChosenPlanStateEnum.stateLastDayFinished,
);
expect(banner, isNot(BannerType.changePersonalDiet));
expect(banner, isNull);
});
test('done не просит менять диету (collectCharge)', () {
final banner = resolveChatBanner(
progress: _progress(
ChosenPlanStateEnum.stateDone,
hasPersonalDiet: true,
),
amIConsultant: true,
hasCard: true,
state: ChosenPlanStateEnum.stateDone,
);
expect(banner, isNot(BannerType.changePersonalDiet));
expect(banner, BannerType.collectCharge);
});
});
group('resolveChatBanner — карта клиента', () {
test('start_date_has_been_set просит оплатить', () {
final banner = resolveChatBanner(
progress: _progress(ChosenPlanStateEnum.stateStartDateHasBeenSet),
amIConsultant: false,
hasCard: true,
state: ChosenPlanStateEnum.stateStartDateHasBeenSet,
);
expect(banner, BannerType.payment);
});
test('pending_payment просит оплатить', () {
final banner = resolveChatBanner(
progress: _progress(ChosenPlanStateEnum.statePendingPayment),
amIConsultant: false,
hasCard: true,
state: ChosenPlanStateEnum.statePendingPayment,
);
expect(banner, BannerType.payment);
});
test('paid + notProposed не показывает diet-баннер клиенту', () {
final banner = resolveChatBanner(
progress: _progress(
ChosenPlanStateEnum.statePaid,
hasPersonalDiet: true,
),
amIConsultant: false,
hasCard: true,
state: ChosenPlanStateEnum.statePaid,
);
expect(banner, isNull);
});
test(
'personal_diet_setted + proposed не показывает diet-баннер клиенту',
() {
final banner = resolveChatBanner(
progress: _progress(
ChosenPlanStateEnum.personalDietSet,
hasPersonalDiet: true,
),
amIConsultant: false,
hasCard: true,
state: ChosenPlanStateEnum.personalDietSet,
);
expect(banner, isNull);
},
);
});
group('resolveChatBanner — терминальные фазы', () {
test('canceled не показывает баннер', () {
expect(
resolveChatBanner(
progress: _progress(ChosenPlanStateEnum.stateCanceledByTheInitiator),
amIConsultant: true,
hasCard: true,
state: ChosenPlanStateEnum.stateCanceledByTheInitiator,
),
isNull,
);
expect(
resolveChatBanner(
progress: _progress(ChosenPlanStateEnum.stateCanceledByTheInitiator),
amIConsultant: false,
hasCard: true,
state: ChosenPlanStateEnum.stateCanceledByTheInitiator,
),
isNull,
);
});
test('payment_failed не показывает баннер', () {
expect(
resolveChatBanner(
progress: _progress(ChosenPlanStateEnum.statePaymentFailed),
amIConsultant: true,
hasCard: true,
state: ChosenPlanStateEnum.statePaymentFailed,
),
isNull,
);
expect(
resolveChatBanner(
progress: _progress(ChosenPlanStateEnum.statePaymentFailed),
amIConsultant: false,
hasCard: true,
state: ChosenPlanStateEnum.statePaymentFailed,
),
isNull,
);
});
test('нет progress или state — нет баннера', () {
expect(
resolveChatBanner(
progress: null,
amIConsultant: true,
hasCard: true,
state: ChosenPlanStateEnum.statePaid,
),
isNull,
);
expect(
resolveChatBanner(
progress: _progress(ChosenPlanStateEnum.statePaid),
amIConsultant: true,
hasCard: true,
state: null,
),
isNull,
);
});
});
}

View File

@@ -0,0 +1,82 @@
import 'package:eatvio_app/core/theme/theme_helper.dart';
import 'package:eatvio_app/features/chat/presentation/widgets/chat_consultation_header.dart';
import 'package:eatvio_app/features/consultations/presentation/widgets/consultation_progress_plank.dart';
import 'package:eatvio_app/features/consultations/models/consultation_progress.dart';
import 'package:eatvio_app/features/consultations/presentation/widgets/personal_diet_status_chip.dart';
import 'package:eatvio_app/features/consultations/utils/consultation_progress_mapper.dart';
import 'package:eatvio_app/features/plans/enums/chosen_plan_state_enum.dart';
import 'package:eatvio_app/generated/l10n.dart';
import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_test/flutter_test.dart';
Widget _wrap(Widget child) {
return MaterialApp(
theme: ThemeHelper().themeData(),
localizationsDelegates: const [
S.delegate,
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
],
supportedLocales: const [Locale('ru')],
home: Scaffold(body: Center(child: child)),
);
}
void main() {
group('ChatConsultationHeader', () {
testWidgets('вызывает onInfoTap по тапу на info', (tester) async {
var tapped = 0;
final progress = mapConsultationProgress(
state: ChosenPlanStateEnum.stateInited,
hasPersonalDiet: false,
);
await tester.pumpWidget(
_wrap(
ChatConsultationHeader(
progress: progress,
showInfoButton: true,
onInfoTap: () => tapped++,
),
),
);
await tester.tap(find.byIcon(Icons.info_outline_rounded));
await tester.pump();
expect(tapped, 1);
});
testWidgets(
'при showProgressPlank=false и proposed видны заголовок и чип, плашки нет',
(tester) async {
final progress = mapConsultationProgress(
state: ChosenPlanStateEnum.personalDietSet,
hasPersonalDiet: true,
);
expect(progress.showProgressPlank, isFalse);
expect(progress.dietStatus, PersonalDietStatus.proposed);
await tester.pumpWidget(
_wrap(
ChatConsultationHeader(
progress: progress,
showInfoButton: false,
onInfoTap: () {},
),
),
);
final s = S.of(tester.element(find.byType(ChatConsultationHeader)));
expect(find.text(s.more_about_order), findsOneWidget);
expect(find.byType(PersonalDietStatusChip), findsOneWidget);
expect(find.text(s.personal_diet_proposed), findsOneWidget);
expect(find.byType(ConsultationProgressPlank), findsNothing);
expect(find.byIcon(Icons.check), findsNothing);
},
);
});
}

View File

@@ -0,0 +1,71 @@
import 'package:eatvio_app/core/theme/theme_helper.dart';
import 'package:eatvio_app/features/consultations/presentation/widgets/consultation_progress_plank.dart';
import 'package:eatvio_app/features/consultations/utils/consultation_progress_mapper.dart';
import 'package:eatvio_app/features/plans/enums/chosen_plan_state_enum.dart';
import 'package:eatvio_app/generated/l10n.dart';
import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_test/flutter_test.dart';
Widget _wrap(Widget child) {
return MaterialApp(
theme: ThemeHelper().themeData(),
localizationsDelegates: const [
S.delegate,
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
],
supportedLocales: const [Locale('ru')],
home: Scaffold(body: Center(child: child)),
);
}
void main() {
group('ConsultationProgressPlank', () {
testWidgets('не строит шаги при showProgressPlank=false', (tester) async {
final progress = mapConsultationProgress(
state: ChosenPlanStateEnum.personalDietSet,
hasPersonalDiet: true,
);
expect(progress.showProgressPlank, isFalse);
await tester.pumpWidget(
_wrap(ConsultationProgressPlank(progress: progress)),
);
expect(
find.descendant(
of: find.byType(ConsultationProgressPlank),
matching: find.byType(SizedBox),
),
findsOneWidget,
);
expect(find.byIcon(Icons.check), findsNothing);
expect(find.byType(Text), findsNothing);
});
testWidgets(
'рисует 4 шага с иконками и подписями при showProgressPlank=true',
(tester) async {
final progress = mapConsultationProgress(
state: ChosenPlanStateEnum.stateDone,
hasPersonalDiet: false,
);
expect(progress.showProgressPlank, isTrue);
await tester.pumpWidget(
_wrap(ConsultationProgressPlank(progress: progress)),
);
final s = S.of(tester.element(find.byType(ConsultationProgressPlank)));
expect(find.byIcon(Icons.check), findsNWidgets(4));
expect(find.text(s.startDateHasBeenSet), findsOneWidget);
expect(find.text(s.order_paid), findsOneWidget);
expect(find.text(s.order_in_progress), findsOneWidget);
expect(find.text(s.done), findsOneWidget);
},
);
});
}

View File

@@ -0,0 +1,88 @@
import 'package:eatvio_app/core/theme/theme_helper.dart';
import 'package:eatvio_app/features/consultations/presentation/widgets/personal_diet_status_chip.dart';
import 'package:eatvio_app/features/consultations/utils/consultation_progress_mapper.dart';
import 'package:eatvio_app/features/plans/enums/chosen_plan_state_enum.dart';
import 'package:eatvio_app/generated/l10n.dart';
import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_test/flutter_test.dart';
Widget _wrap(Widget child) {
return MaterialApp(
theme: ThemeHelper().themeData(),
localizationsDelegates: const [
S.delegate,
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
],
supportedLocales: const [Locale('ru')],
home: Scaffold(body: Center(child: child)),
);
}
Widget _chip(ChosenPlanStateEnum state, {bool hasPersonalDiet = true}) {
return PersonalDietStatusChip(
progress: mapConsultationProgress(
state: state,
hasPersonalDiet: hasPersonalDiet,
),
);
}
void main() {
group('PersonalDietStatusChip', () {
testWidgets('notRequired + active ничего не показывает', (tester) async {
await tester.pumpWidget(
_wrap(_chip(ChosenPlanStateEnum.stateInited, hasPersonalDiet: false)),
);
expect(
find.descendant(
of: find.byType(PersonalDietStatusChip),
matching: find.byType(SizedBox),
),
findsOneWidget,
);
expect(find.byType(Text), findsNothing);
});
testWidgets('proposed показывает personal_diet_proposed', (tester) async {
await tester.pumpWidget(_wrap(_chip(ChosenPlanStateEnum.stateStarted)));
final s = S.of(tester.element(find.byType(PersonalDietStatusChip)));
expect(find.text(s.personal_diet_proposed), findsOneWidget);
});
testWidgets('notProposed показывает personal_diet_not_proposed', (
tester,
) async {
await tester.pumpWidget(_wrap(_chip(ChosenPlanStateEnum.statePaid)));
final s = S.of(tester.element(find.byType(PersonalDietStatusChip)));
expect(find.text(s.personal_diet_not_proposed), findsOneWidget);
});
testWidgets('canceled показывает orderCanceled', (tester) async {
await tester.pumpWidget(
_wrap(_chip(ChosenPlanStateEnum.stateCanceledByTheInitiator)),
);
final s = S.of(tester.element(find.byType(PersonalDietStatusChip)));
expect(find.text(s.orderCanceled), findsOneWidget);
});
testWidgets('paymentFailed показывает payment_failed', (tester) async {
await tester.pumpWidget(
_wrap(_chip(ChosenPlanStateEnum.statePaymentFailed)),
);
final s = S.of(tester.element(find.byType(PersonalDietStatusChip)));
expect(find.text(s.payment_failed), findsOneWidget);
});
});
}

View File

@@ -0,0 +1,279 @@
import 'package:eatvio_app/features/consultations/models/consultation_progress.dart';
import 'package:eatvio_app/features/consultations/utils/consultation_progress_mapper.dart';
import 'package:eatvio_app/features/plans/enums/chosen_plan_state_enum.dart';
import 'package:flutter_test/flutter_test.dart';
typedef _Expected = ({
Set<ConsultationStep> steps,
bool plank,
PersonalDietStatus diet,
ConsultationPhase phase,
});
const _startDate = ConsultationStep.startDate;
const _paid = ConsultationStep.paid;
const _inProgress = ConsultationStep.inProgress;
const _finished = ConsultationStep.finished;
final Map<ChosenPlanStateEnum, _Expected> _expectations = {
ChosenPlanStateEnum.stateInited: (
steps: {},
plank: false,
diet: PersonalDietStatus.notProposed,
phase: ConsultationPhase.active,
),
ChosenPlanStateEnum.stateStartDateHasBeenSet: (
steps: {_startDate},
plank: true,
diet: PersonalDietStatus.notProposed,
phase: ConsultationPhase.active,
),
ChosenPlanStateEnum.stateInCoordination: (
steps: {},
plank: true,
diet: PersonalDietStatus.notProposed,
phase: ConsultationPhase.active,
),
ChosenPlanStateEnum.stateStarted: (
steps: {_startDate, _paid, _inProgress},
plank: true,
diet: PersonalDietStatus.proposed,
phase: ConsultationPhase.active,
),
ChosenPlanStateEnum.stateInProgress: (
steps: {_startDate, _paid, _inProgress},
plank: true,
diet: PersonalDietStatus.proposed,
phase: ConsultationPhase.active,
),
ChosenPlanStateEnum.statePendingPayment: (
steps: {_startDate},
plank: true,
diet: PersonalDietStatus.notProposed,
phase: ConsultationPhase.active,
),
ChosenPlanStateEnum.stateConfirmedByConsultant: (
steps: {},
plank: false,
diet: PersonalDietStatus.notProposed,
phase: ConsultationPhase.active,
),
ChosenPlanStateEnum.statePaid: (
steps: {_startDate, _paid},
plank: true,
diet: PersonalDietStatus.notProposed,
phase: ConsultationPhase.active,
),
ChosenPlanStateEnum.stateCanceledByTheInitiator: (
steps: {},
plank: false,
diet: PersonalDietStatus.notRequired,
phase: ConsultationPhase.canceled,
),
ChosenPlanStateEnum.stateLastDayStarted: (
steps: {_startDate, _paid, _inProgress},
plank: true,
diet: PersonalDietStatus.proposed,
phase: ConsultationPhase.active,
),
ChosenPlanStateEnum.stateLastDayFinished: (
steps: {_startDate, _paid, _inProgress},
plank: true,
diet: PersonalDietStatus.proposed,
phase: ConsultationPhase.active,
),
ChosenPlanStateEnum.stateComplained: (
steps: {_startDate, _paid, _inProgress},
plank: true,
diet: PersonalDietStatus.proposed,
phase: ConsultationPhase.active,
),
ChosenPlanStateEnum.stateDone: (
steps: {_startDate, _paid, _inProgress, _finished},
plank: true,
diet: PersonalDietStatus.proposed,
phase: ConsultationPhase.active,
),
ChosenPlanStateEnum.personalDietSet: (
steps: {_startDate, _paid},
plank: false,
diet: PersonalDietStatus.proposed,
phase: ConsultationPhase.active,
),
ChosenPlanStateEnum.stateChargeWasCollected: (
steps: {_startDate, _paid, _inProgress, _finished},
plank: false,
diet: PersonalDietStatus.proposed,
phase: ConsultationPhase.active,
),
ChosenPlanStateEnum.statePaymentFailed: (
steps: {_startDate},
plank: false,
diet: PersonalDietStatus.notRequired,
phase: ConsultationPhase.paymentFailed,
),
};
void main() {
group('mapConsultationProgress — все состояния', () {
test('таблица покрывает ровно все 16 состояний', () {
expect(_expectations.length, 16);
expect(_expectations.keys.toSet(), ChosenPlanStateEnum.values.toSet());
});
for (final entry in _expectations.entries) {
test('${entry.key.name} маппится во все поля ConsultationProgress', () {
final progress = mapConsultationProgress(
state: entry.key,
hasPersonalDiet: true,
);
expect(progress.completedSteps, unorderedEquals(entry.value.steps));
expect(progress.showProgressPlank, entry.value.plank);
expect(progress.dietStatus, entry.value.diet);
expect(progress.phase, entry.value.phase);
});
}
});
group('mapConsultationProgress — ключевые сценарии', () {
test('in_coordination показывает плашку без завершённых шагов', () {
final progress = mapConsultationProgress(
state: ChosenPlanStateEnum.stateInCoordination,
hasPersonalDiet: true,
);
expect(progress.showProgressPlank, isTrue);
expect(progress.completedSteps, isEmpty);
});
test(
'personal_diet_setted не показывает плашку и завершает startDate+paid',
() {
final progress = mapConsultationProgress(
state: ChosenPlanStateEnum.personalDietSet,
hasPersonalDiet: true,
);
expect(progress.showProgressPlank, isFalse);
expect(progress.completedSteps, unorderedEquals([_startDate, _paid]));
},
);
test(
'started/in_progress/last_day_started/last_day_finished/complained — 3 шага',
() {
const states = [
ChosenPlanStateEnum.stateStarted,
ChosenPlanStateEnum.stateInProgress,
ChosenPlanStateEnum.stateLastDayStarted,
ChosenPlanStateEnum.stateLastDayFinished,
ChosenPlanStateEnum.stateComplained,
];
for (final state in states) {
final progress = mapConsultationProgress(
state: state,
hasPersonalDiet: true,
);
expect(
progress.completedSteps,
unorderedEquals([_startDate, _paid, _inProgress]),
reason: 'state=${state.name}',
);
}
},
);
test('done/charge_was_collected — 4 шага', () {
const states = [
ChosenPlanStateEnum.stateDone,
ChosenPlanStateEnum.stateChargeWasCollected,
];
for (final state in states) {
final progress = mapConsultationProgress(
state: state,
hasPersonalDiet: true,
);
expect(
progress.completedSteps,
unorderedEquals([_startDate, _paid, _inProgress, _finished]),
reason: 'state=${state.name}',
);
}
});
test(
'canceled — фаза canceled и dietStatus notRequired даже при диете',
() {
final progress = mapConsultationProgress(
state: ChosenPlanStateEnum.stateCanceledByTheInitiator,
hasPersonalDiet: true,
);
expect(progress.phase, ConsultationPhase.canceled);
expect(progress.isCanceled, isTrue);
expect(progress.dietStatus, PersonalDietStatus.notRequired);
},
);
test('payment_failed — фаза paymentFailed и только startDate', () {
final progress = mapConsultationProgress(
state: ChosenPlanStateEnum.statePaymentFailed,
hasPersonalDiet: true,
);
expect(progress.phase, ConsultationPhase.paymentFailed);
expect(progress.isPaymentFailed, isTrue);
expect(progress.completedSteps, unorderedEquals([_startDate]));
});
test('hasPersonalDiet=false даёт notRequired для любого состояния', () {
for (final state in ChosenPlanStateEnum.values) {
final progress = mapConsultationProgress(
state: state,
hasPersonalDiet: false,
);
expect(
progress.dietStatus,
PersonalDietStatus.notRequired,
reason: 'state=${state.name}',
);
expect(progress.hasDietChip, isFalse, reason: 'state=${state.name}');
}
});
test('paid с диетой даёт notProposed', () {
final progress = mapConsultationProgress(
state: ChosenPlanStateEnum.statePaid,
hasPersonalDiet: true,
);
expect(progress.dietStatus, PersonalDietStatus.notProposed);
});
test('personal_diet_setted/started/proposed дают proposed', () {
const states = [
ChosenPlanStateEnum.personalDietSet,
ChosenPlanStateEnum.stateStarted,
];
for (final state in states) {
final progress = mapConsultationProgress(
state: state,
hasPersonalDiet: true,
);
expect(
progress.dietStatus,
PersonalDietStatus.proposed,
reason: 'state=${state.name}',
);
}
});
});
}

View File

@@ -216,6 +216,8 @@ void main() {
consultationId: consultationId,
dietId: dietId,
)).called(1);
verify(mockPersonalDietSuggestionRepository.getConsultationWithPersonalDiets()).called(2);
verify(mockDietRepository.getDiet(dietId)).called(2);
});
test('reattachDietToConsultation - успешное переприкрепление диеты', () async {
@@ -265,6 +267,8 @@ void main() {
consultationId: consultationId,
dietId: dietId,
)).called(1);
verify(mockPersonalDietSuggestionRepository.getConsultationWithPersonalDiets()).called(2);
verify(mockDietRepository.getDiet(dietId)).called(2);
});
});
}

View File

@@ -231,6 +231,54 @@ void main() {
});
});
testWidgets('shows success bottom sheet after successful diet reattachment', (tester) async {
await mockNetworkImagesFor(() async {
final cubit = MockPersonalDietSuggestionCubit();
final consultationWithDiet = ConsultationModel(
id: 1,
chosenPlanState: ChosenPlanStateEnum.stateInProgress,
planTitle: 'Test Plan',
userName: 'Test User',
userSlug: 'test-user',
consultantPayment: 1000.0,
duration: 7,
currentDiaryDay: 3,
userProfilePhotoUrl: '/avatar.jpg',
consultationOptionPrice: 500,
startDate: DateTime(2025, 1, 1),
endDate: DateTime(2025, 1, 8),
consultantId: 1,
diaries: [],
personalDietId: 1,
);
when(cubit.state).thenReturn(PersonalDietSuggestionState());
when(cubit.stream).thenAnswer((_) => const Stream.empty());
when(cubit.close()).thenAnswer((_) async => Future<void>.value());
when(cubit.reattachDietToConsultation(consultationId: 1)).thenAnswer((_) async => true);
await tester.pumpWidget(
BlocProvider<PersonalDietSuggestionCubit>.value(
value: cubit,
child: wrap(ConsultationWidget(consultationModel: consultationWithDiet, dietName: 'Test Diet')),
),
);
await tester.pumpAndSettle();
final changeButton = find.text(S.of(tester.element(find.byType(ConsultationWidget))).changeDiet);
await tester.tap(changeButton);
await tester.pumpAndSettle();
final offerButton = find.text(S.of(tester.element(find.byType(ConsultationWidget))).toOffer);
await tester.tap(offerButton);
await tester.pumpAndSettle();
expect(find.text('«Test Diet» предложена пользователю Test User'), findsOneWidget);
verify(cubit.reattachDietToConsultation(consultationId: 1)).called(1);
verifyNever(cubit.attachDietToConsultation(consultationId: 1));
});
});
testWidgets('shows failure bottom sheet after failed diet attachment', (tester) async {
await mockNetworkImagesFor(() async {
final cubit = MockPersonalDietSuggestionCubit();
@@ -279,7 +327,7 @@ void main() {
expect(find.text('Test User'), findsOneWidget);
expect(find.text('Test Plan'), findsOneWidget);
expect(find.text('Старт: Test User'), findsOneWidget);
expect(find.text('Старт: 01.01.2025'), findsOneWidget);
});
});
@@ -318,7 +366,7 @@ void main() {
expect(find.text('Test User'), findsOneWidget);
expect(find.text('Test Plan'), findsOneWidget);
expect(find.text('Старт: Test User'), findsNothing);
expect(find.text('Старт: 01.01.2025'), findsNothing);
});
});
});

View File

@@ -68,41 +68,33 @@ void main() {
test('attachPersonalDiet - успешное прикрепление диеты', () async {
const consultationId = 1;
const dietId = 2;
final body = {'diet_id': dietId};
when(mockService.attachPersonalDiet(
consultationId: consultationId,
dietId: dietId,
)).thenAnswer((_) async => {});
when(mockService.attachPersonalDiet(consultationId, body))
.thenAnswer((_) async => {});
await repository.attachPersonalDiet(
consultationId: consultationId,
dietId: dietId,
);
verify(mockService.attachPersonalDiet(
consultationId: consultationId,
dietId: dietId,
)).called(1);
verify(mockService.attachPersonalDiet(consultationId, body)).called(1);
});
test('reattachPersonalDiet - успешное переприкрепление диеты', () async {
const consultationId = 1;
const dietId = 2;
final body = {'diet_id': dietId};
when(mockService.reattachPersonalDiet(
consultationId: consultationId,
dietId: dietId,
)).thenAnswer((_) async => {});
when(mockService.reattachPersonalDiet(consultationId, body))
.thenAnswer((_) async => {});
await repository.reattachPersonalDiet(
consultationId: consultationId,
dietId: dietId,
);
verify(mockService.reattachPersonalDiet(
consultationId: consultationId,
dietId: dietId,
)).called(1);
verify(mockService.reattachPersonalDiet(consultationId, body)).called(1);
});
});
}

View File

@@ -15,55 +15,48 @@ void main() {
setUp(() {
mockDio = MockDio();
when(mockDio.options).thenReturn(BaseOptions(baseUrl: 'http://localhost'));
service = PersonalDietSuggestionService(mockDio);
});
test('getConsultationWithPersonalDiets - успешное получение консультаций', () async {
final mockData = {
'data': [],
'links': {},
'meta': {
'current_page': 1,
'last_page': 1,
'total': 0,
'per_page': 10,
},
};
late RequestOptions capturedRequest;
when(mockDio.get(
'/api/consultations',
queryParameters: anyNamed('queryParameters'),
)).thenAnswer((_) async => Response(
requestOptions: RequestOptions(path: '/api/consultations'),
statusCode: 200,
data: mockData,
));
when(mockDio.fetch<Map<String, dynamic>>(any)).thenAnswer((invocation) async {
capturedRequest = invocation.positionalArguments.first as RequestOptions;
return Response<Map<String, dynamic>>(
requestOptions: capturedRequest,
statusCode: 200,
data: mockData,
);
});
final result = await service.getConsultationWithPersonalDiets();
expect(result, isA<ConsultationPaginationModel>());
verify(mockDio.get(
'/api/consultations',
queryParameters: {
'filters[plan][has_personal_diet][\$personal_diet]': '1',
'filters[last_state][\$notIn][]': [
'done',
'charge_was_collected',
'complained',
'last_day_finished',
'canceled_by_the_initiator',
'inited'
],
'sort[]': 'start_date:desc',
},
)).called(1);
expect(capturedRequest.path, '/api/consultations');
expect(capturedRequest.method, 'GET');
expect(capturedRequest.queryParameters, {
r'filters[plan][has_personal_diet][$personal_diet]': '1',
r'filters[last_state][$notIn][]': [
'done',
'charge_was_collected',
'complained',
'last_day_finished',
'last_day_started',
'canceled_by_the_initiator',
'inited',
],
r'sort[]': ['start_date:desc'],
});
verify(mockDio.fetch<Map<String, dynamic>>(any)).called(1);
});
test('getConsultationWithPersonalDiets - пробрасывает ошибку', () async {
when(mockDio.get(
any,
queryParameters: anyNamed('queryParameters'),
)).thenThrow(DioException(
when(mockDio.fetch<Map<String, dynamic>>(any)).thenThrow(DioException(
requestOptions: RequestOptions(path: '/api/consultations'),
));
@@ -75,74 +68,70 @@ void main() {
test('attachPersonalDiet - успешное прикрепление диеты', () async {
const consultationId = 1;
const dietId = 2;
final body = {'diet_id': 2};
late RequestOptions capturedRequest;
when(mockDio.post(
'/api/chosen_plans/$consultationId/attach_diet',
data: anyNamed('data'),
)).thenAnswer((_) async => Response(
requestOptions: RequestOptions(path: '/api/chosen_plans/$consultationId/attach_diet'),
statusCode: 200,
));
when(mockDio.fetch<void>(any)).thenAnswer((invocation) async {
capturedRequest = invocation.positionalArguments.first as RequestOptions;
return Response<void>(
requestOptions: capturedRequest,
statusCode: 200,
);
});
await service.attachPersonalDiet(consultationId: consultationId, dietId: dietId);
await service.attachPersonalDiet(consultationId, body);
verify(mockDio.post(
'/api/chosen_plans/$consultationId/attach_diet',
data: {'diet_id': dietId},
)).called(1);
expect(capturedRequest.path, '/api/chosen_plans/$consultationId/attach_diet');
expect(capturedRequest.method, 'POST');
expect(capturedRequest.data, body);
verify(mockDio.fetch<void>(any)).called(1);
});
test('attachPersonalDiet - пробрасывает ошибку', () async {
const consultationId = 1;
const dietId = 2;
final body = {'diet_id': 2};
when(mockDio.post(
any,
data: anyNamed('data'),
)).thenThrow(DioException(
when(mockDio.fetch<void>(any)).thenThrow(DioException(
requestOptions: RequestOptions(path: '/api/chosen_plans/$consultationId/attach_diet'),
));
expect(
() => service.attachPersonalDiet(consultationId: consultationId, dietId: dietId),
() => service.attachPersonalDiet(consultationId, body),
throwsA(isA<DioException>()),
);
});
test('reattachPersonalDiet - успешное повторное прикрепление диеты', () async {
const consultationId = 1;
const dietId = 3;
final body = {'diet_id': 3};
late RequestOptions capturedRequest;
when(mockDio.post(
'/api/chosen_plans/$consultationId/re_attach_diet',
data: anyNamed('data'),
)).thenAnswer((_) async => Response(
requestOptions: RequestOptions(path: '/api/chosen_plans/$consultationId/re_attach_diet'),
statusCode: 200,
));
when(mockDio.fetch<void>(any)).thenAnswer((invocation) async {
capturedRequest = invocation.positionalArguments.first as RequestOptions;
return Response<void>(
requestOptions: capturedRequest,
statusCode: 200,
);
});
await service.reattachPersonalDiet(consultationId: consultationId, dietId: dietId);
await service.reattachPersonalDiet(consultationId, body);
verify(mockDio.post(
'/api/chosen_plans/$consultationId/re_attach_diet',
data: {'diet_id': dietId},
)).called(1);
expect(capturedRequest.path, '/api/chosen_plans/$consultationId/re_attach_diet');
expect(capturedRequest.method, 'POST');
expect(capturedRequest.data, body);
verify(mockDio.fetch<void>(any)).called(1);
});
test('reattachPersonalDiet - пробрасывает ошибку', () async {
const consultationId = 1;
const dietId = 3;
final body = {'diet_id': 3};
when(mockDio.post(
any,
data: anyNamed('data'),
)).thenThrow(DioException(
when(mockDio.fetch<void>(any)).thenThrow(DioException(
requestOptions: RequestOptions(path: '/api/chosen_plans/$consultationId/re_attach_diet'),
));
expect(
() => service.reattachPersonalDiet(consultationId: consultationId, dietId: dietId),
() => service.reattachPersonalDiet(consultationId, body),
throwsA(isA<DioException>()),
);
});