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

@@ -31,7 +31,9 @@ class ChatRoomCubit extends Cubit<ChatRoomState> {
StreamSubscription<ChannelReadEvent>? typingSubscription;
StreamSubscription<ChannelReadEvent>? messagesSubscription;
StreamSubscription<ChannelReadEvent>? _chosenPlanStateSubscription;
StreamSubscription<void>? _reconnectSubscription;
bool _isUpdatingChosenPlan = false;
int currentPage = 1;
late int lastPage;
bool isLoading = false;
@@ -171,6 +173,7 @@ class ChatRoomCubit extends Cubit<ChatRoomState> {
log(e.toString());
typingSubscription?.cancel();
messagesSubscription?.cancel();
_chosenPlanStateSubscription?.cancel();
_reconnectSubscription?.cancel();
_reconnectSubscription = null;
wsManager.unsubscribeDirectChatChannel();
@@ -260,19 +263,30 @@ class ChatRoomCubit extends Cubit<ChatRoomState> {
}
Future<void> updateChosenPlanState() async {
if (_isUpdatingChosenPlan) return;
try {
_isUpdatingChosenPlan = true;
final currentState = state;
if (currentState is! ChatRoomStateLoaded) {
return;
}
final chosenPlanId = currentState.chatRoom.chosenPlanId;
final chosenPlanId =
currentState.chatRoom.chosenPlanId ??
currentState.chatRoom.chosenPlan?.id;
if (chosenPlanId == null) {
return;
}
final chosenPlan = await chatRepository.getChosenPlan(id: chosenPlanId);
_emitLoaded((latest) => latest.copyWith.chatRoom(chosenPlan: chosenPlan));
if (isClosed) return;
_emitLoaded(
(latest) => latest.copyWith(
chatRoom: latest.chatRoom.copyWith(chosenPlan: chosenPlan),
),
);
} catch (e, st) {
await reportFrom(e, st, this);
} finally {
_isUpdatingChosenPlan = false;
}
}
@@ -338,8 +352,10 @@ class ChatRoomCubit extends Cubit<ChatRoomState> {
if (client == null) return;
await messagesSubscription?.cancel();
await typingSubscription?.cancel();
await _chosenPlanStateSubscription?.cancel();
messagesSubscription = null;
typingSubscription = null;
_chosenPlanStateSubscription = null;
await wsManager.initPrivateDirectChatChannel(chatId);
wsManager.subscribeDirectChatChannel();
messagesSubscription = wsManager.directChatStream?.listen(
@@ -361,6 +377,20 @@ class ChatRoomCubit extends Cubit<ChatRoomState> {
),
);
});
_chosenPlanStateSubscription = wsManager
.chosenPlanStateChangedStream
?.listen(
(_) {
EasyDebounce.debounce(
'chosen-plan-state-changed',
const Duration(milliseconds: 250),
() => unawaited(updateChosenPlanState()),
);
},
onError: (Object e, StackTrace st) {
unawaited(reportFrom(e, st, this));
},
);
}
void _onDirectChatEvent(ChannelReadEvent event) {
@@ -731,6 +761,7 @@ class ChatRoomCubit extends Cubit<ChatRoomState> {
Future<void> close() async {
EasyDebounce.cancel('client-typing');
EasyDebounce.cancel('searchChatRoom');
EasyDebounce.cancel('chosen-plan-state-changed');
if (_presenceOnlineListener != null) {
wsManager.removePresenceDirectChatListener(_presenceOnlineListener!);
_presenceOnlineListener = null;
@@ -739,6 +770,7 @@ class ChatRoomCubit extends Cubit<ChatRoomState> {
_timer?.cancel();
await messagesSubscription?.cancel();
await typingSubscription?.cancel();
await _chosenPlanStateSubscription?.cancel();
await _reconnectSubscription?.cancel();
super.close();
}

View File

@@ -11,7 +11,6 @@ import 'package:eatvio_app/features/chat/presentation/bloc/chat_room_cubit/chat_
import 'package:eatvio_app/features/chat/presentation/bloc/chat_room_cubit/chat_room_state.dart';
import 'package:eatvio_app/features/chat/presentation/bloc/chats_cubit/chats_cubit.dart';
import 'package:eatvio_app/features/chat/presentation/pages/photo_view_screen.dart';
import 'package:eatvio_app/features/chat/presentation/widgets/about_order_button.dart';
import 'package:eatvio_app/features/chat/presentation/widgets/chat_bubble_widget.dart';
import 'package:eatvio_app/features/chat/models/chat_message_model.dart';
import 'package:eatvio_app/features/chat/models/chat_user_model.dart';
@@ -24,11 +23,14 @@ import 'package:eatvio_app/features/menu/presentation/blocked_user_cubit/blocked
import 'package:eatvio_app/core/theme/custom_text_style.dart';
import 'package:eatvio_app/core/theme/theme_helper.dart';
import 'package:eatvio_app/features/chat/presentation/widgets/chat_user_online_status_line.dart';
import 'package:eatvio_app/features/chat/presentation/utils/chat_banner_resolver.dart';
import 'package:eatvio_app/features/chat/presentation/widgets/chat_consultation_header.dart';
import 'package:eatvio_app/features/chat/presentation/widgets/notification_banner.dart';
import 'package:eatvio_app/features/chat/utils/chat_counterpart_utils.dart';
import 'package:eatvio_app/features/feed/models/plan_pagination_model.dart';
import 'package:eatvio_app/features/consultations/utils/consultation_progress_mapper.dart';
import 'package:eatvio_app/features/order_info/presentation/info_by_order_screen.dart';
import 'package:eatvio_app/features/plans/enums/chosen_plan_state_enum.dart';
import 'package:eatvio_app/features/plans/models/chosen_plan_model.dart';
import 'package:eatvio_app/features/user_details/presentation/user_details_screen.dart';
import 'package:eatvio_app/features/video_calls/managers/video_call_manager.dart';
import 'package:eatvio_app/features/video_calls/presentation/pages/video_call_screen.dart';
@@ -63,8 +65,6 @@ class _ChatScreenState extends State<ChatScreen> {
final TextEditingController textEditingController = TextEditingController();
final ChatRoomCubit chatRoomCubit = sl<ChatRoomCubit>();
final List<int> unreadMessageIds = [];
final showableChatBadgeStates =
ChosenPlanStateEnum.getShowableChatBadgeStates();
late AppLifecycleListener _listener;
List<File> pickedFiles = [];
@@ -188,49 +188,23 @@ class _ChatScreenState extends State<ChatScreen> {
ChosenPlanStateEnum.statePendingPayment,
ChosenPlanStateEnum.stateInCoordination,
].contains(chosenPlan?.chosenPlanState);
PacketOptions? chosenOption;
if (chosenPlan?.optionType == 'options1') {
chosenOption = chosenPlan?.plan.packet1Options;
} else if (chosenPlan?.optionType == 'options2') {
chosenOption = chosenPlan?.plan.packet2Options;
} else if (chosenPlan?.optionType == 'options3') {
chosenOption = chosenPlan?.plan.packet3Options;
}
final showAboutOrderButton =
state.chatRoom.chosenPlan != null &&
state.chatRoom.chosenPlan!.chosenPlanState !=
final chosenOption = chosenPlan?.chosenOption;
final progress = chosenPlan == null
? null
: mapConsultationProgress(
state: chosenPlan.chosenPlanState,
hasPersonalDiet: chosenOption?.hasPersonalDiet ?? false,
);
final bannerType = resolveChatBanner(
progress: progress,
amIConsultant: amIConsultant,
hasCard: state.hasCard,
state: chosenPlan?.chosenPlanState,
);
final showInfoButton =
chosenPlan != null &&
chosenPlan.chosenPlanState !=
ChosenPlanStateEnum.stateCanceledByTheInitiator;
BannerType? bannerType;
if (chosenPlan == null ||
chosenPlan.chosenPlanState ==
ChosenPlanStateEnum.stateCanceledByTheInitiator) {
bannerType = null;
} else if (amIConsultant &&
!state.hasCard &&
chosenPlan.chosenPlanState == ChosenPlanStateEnum.stateInCoordination) {
bannerType = BannerType.card;
} else if (amIConsultant &&
chosenPlan.chosenPlanState == ChosenPlanStateEnum.stateInCoordination) {
bannerType = BannerType.date;
} else if (!amIConsultant &&
(chosenPlan.chosenPlanState ==
ChosenPlanStateEnum.stateStartDateHasBeenSet ||
chosenPlan.chosenPlanState ==
ChosenPlanStateEnum.statePendingPayment)) {
bannerType = BannerType.payment;
} else if (chosenPlan.chosenPlanState == ChosenPlanStateEnum.stateDone &&
amIConsultant) {
bannerType = BannerType.collectCharge;
} else if (chosenPlan.chosenPlanState ==
ChosenPlanStateEnum.stateLastDayFinished &&
!amIConsultant) {
bannerType = BannerType.finishPlan;
} else if (chosenOption?.hasPersonalDiet == true &&
amIConsultant &&
chosenPlan.chosenPlanState != ChosenPlanStateEnum.stateDone) {
bannerType = BannerType.setPersonalDiet;
}
return Scaffold(
resizeToAvoidBottomInset: true,
@@ -340,6 +314,28 @@ class _ChatScreenState extends State<ChatScreen> {
Column(
mainAxisSize: MainAxisSize.min,
children: [
if (progress != null)
ChatConsultationHeader(
progress: progress,
showInfoButton: showInfoButton,
onInfoTap: () {
if (amIConsultant) {
GoRouter.of(context).push(
InfoByOrderScreen.path,
extra: {
'planId': chosenPlan?.id,
'customerSlug':
state.chatRoom.users.receiver.slug,
},
);
return;
}
GoRouter.of(context).push(
InfoByOrderScreen.path,
extra: {'planId': chosenPlan?.id},
);
},
),
Expanded(
child: Container(
color: appTheme.whiteA700,
@@ -384,22 +380,9 @@ class _ChatScreenState extends State<ChatScreen> {
final isPlanOrderMessage =
message.type == ChatMessageType.planOrder;
PacketOptions? messageOption;
if (isPlanOrderMessage &&
chosenPlan != null) {
if (chosenPlan.optionType == 'options1') {
messageOption =
chosenPlan.plan.packet1Options;
} else if (chosenPlan.optionType ==
'options2') {
messageOption =
chosenPlan.plan.packet2Options;
} else if (chosenPlan.optionType ==
'options3') {
messageOption =
chosenPlan.plan.packet3Options;
}
}
final messageOption = isPlanOrderMessage
? chosenPlan?.chosenOption
: null;
return Column(
children: [
@@ -450,21 +433,9 @@ class _ChatScreenState extends State<ChatScreen> {
final isPlanOrderMessage =
message.type == ChatMessageType.planOrder;
PacketOptions? messageOption;
if (isPlanOrderMessage && chosenPlan != null) {
if (chosenPlan.optionType == 'options1') {
messageOption =
chosenPlan.plan.packet1Options;
} else if (chosenPlan.optionType ==
'options2') {
messageOption =
chosenPlan.plan.packet2Options;
} else if (chosenPlan.optionType ==
'options3') {
messageOption =
chosenPlan.plan.packet3Options;
}
}
final messageOption = isPlanOrderMessage
? chosenPlan?.chosenOption
: null;
return Column(
children: [
@@ -804,30 +775,6 @@ class _ChatScreenState extends State<ChatScreen> {
),
],
),
if (showAboutOrderButton)
Positioned(
top: 8,
right: 15,
left: 16,
child: AboutOrderButton(
onTap: () async {
if (amIConsultant) {
GoRouter.of(context).push(
InfoByOrderScreen.path,
extra: {
'planId': state.chatRoom.chosenPlan?.id,
'customerSlug': state.chatRoom.users.receiver.slug,
},
);
return;
}
GoRouter.of(context).push(
InfoByOrderScreen.path,
extra: {'planId': state.chatRoom.chosenPlan?.id},
);
},
),
),
],
),
),

View File

@@ -0,0 +1,52 @@
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/plans/enums/chosen_plan_state_enum.dart';
BannerType? resolveChatBanner({
required ConsultationProgress? progress,
required bool amIConsultant,
required bool hasCard,
required ChosenPlanStateEnum? state,
}) {
if (progress == null ||
state == null ||
progress.phase != ConsultationPhase.active) {
return null;
}
if (amIConsultant &&
!hasCard &&
state == ChosenPlanStateEnum.stateInCoordination) {
return BannerType.card;
}
if (amIConsultant && state == ChosenPlanStateEnum.stateInCoordination) {
return BannerType.date;
}
if (!amIConsultant &&
(state == ChosenPlanStateEnum.stateStartDateHasBeenSet ||
state == ChosenPlanStateEnum.statePendingPayment)) {
return BannerType.payment;
}
if (state == ChosenPlanStateEnum.stateDone && amIConsultant) {
return BannerType.collectCharge;
}
if (state == ChosenPlanStateEnum.stateLastDayFinished && !amIConsultant) {
return BannerType.finishPlan;
}
if (!amIConsultant) {
return null;
}
if (state == ChosenPlanStateEnum.statePaid &&
progress.dietStatus == PersonalDietStatus.notProposed) {
return BannerType.setPersonalDiet;
}
if ((state == ChosenPlanStateEnum.personalDietSet ||
state == ChosenPlanStateEnum.stateStarted ||
state == ChosenPlanStateEnum.stateInProgress) &&
progress.dietStatus == PersonalDietStatus.proposed) {
return BannerType.changePersonalDiet;
}
return null;
}

View File

@@ -0,0 +1,112 @@
import 'package:eatvio_app/core/theme/custom_text_style.dart';
import 'package:eatvio_app/core/theme/theme_helper.dart';
import 'package:eatvio_app/features/consultations/models/consultation_progress.dart';
import 'package:eatvio_app/features/consultations/presentation/widgets/consultation_progress_plank.dart';
import 'package:eatvio_app/features/consultations/presentation/widgets/personal_diet_status_chip.dart';
import 'package:eatvio_app/generated/l10n.dart';
import 'package:flutter/material.dart';
class ChatConsultationHeader extends StatelessWidget {
const ChatConsultationHeader({
super.key,
required this.progress,
required this.showInfoButton,
required this.onInfoTap,
});
final ConsultationProgress progress;
final bool showInfoButton;
final VoidCallback onInfoTap;
@override
Widget build(BuildContext context) {
final showPlank = progress.showProgressPlank;
final showChip = progress.hasChip;
if (!showPlank && !showChip && !showInfoButton) {
return const SizedBox.shrink();
}
final s = S.of(context);
return Container(
margin: const EdgeInsets.fromLTRB(16, 8, 16, 0),
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: appTheme.commentBg,
borderRadius: BorderRadius.circular(20),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
if (progress.phase == ConsultationPhase.active || showPlank)
Row(
children: [
Expanded(
child: Text(
_title(s),
style: TextStyles.textMMedium.copyWith(
color: appTheme.black,
),
),
),
if (showInfoButton)
_InfoButton(
onTap: onInfoTap,
),
],
)
else if (showInfoButton)
Align(
alignment: Alignment.centerRight,
child: _InfoButton(
onTap: onInfoTap,
),
),
if (showPlank) ...[
const SizedBox(height: 8),
ConsultationProgressPlank(progress: progress),
],
if (showChip) ...[
const SizedBox(height: 8),
PersonalDietStatusChip(progress: progress),
],
],
),
);
}
String _title(S s) {
if (progress.isCanceled) return s.orderCanceled;
if (progress.isPaymentFailed) return s.payment_failed;
if (progress.isStepCompleted(ConsultationStep.finished)) return s.done;
if (progress.showProgressPlank) return s.order_in_progress;
return s.more_about_order;
}
}
class _InfoButton extends StatelessWidget {
const _InfoButton({required this.onTap});
final VoidCallback onTap;
@override
Widget build(BuildContext context) {
return InkWell(
onTap: onTap,
customBorder: const CircleBorder(),
child: Container(
width: 32,
height: 32,
decoration: BoxDecoration(
color: appTheme.whiteA700,
shape: BoxShape.circle,
),
child: Icon(
Icons.info_outline_rounded,
size: 18,
color: appTheme.blueA400,
),
),
);
}
}

View File

@@ -142,12 +142,37 @@ class _NotificationBannerState extends State<NotificationBanner> {
BannerType.setPersonalDiet => [
SizedBox(
width: size.width * 0.6,
child: Text(s.createPersonalDiet, style: TextStyles.textMMedium.copyWith(color: appTheme.black)),
child: Text(s.suggestDiet, style: TextStyles.textMMedium.copyWith(color: appTheme.black)),
),
const SizedBox(height: 12),
GestureDetector(
onTap: () {
GoRouter.of(context).pushNamed(MyDietsScreen.name);
GoRouter.of(context).pushNamed(
MyDietsScreen.name,
queryParameters: {'initialTabIndex': '2'},
);
},
child: Text(s.goToMyDiets, style: TextStyles.textLSemibold.copyWith(color: appTheme.blueA400)),
),
const SizedBox(height: 16),
],
BannerType.changePersonalDiet => [
SizedBox(
width: size.width * 0.6,
child: Text(s.change_personal_diet, style: TextStyles.textMMedium.copyWith(color: appTheme.black)),
),
const SizedBox(height: 8),
SizedBox(
width: size.width * 0.6,
child: Text(s.personal_diet_replaces_tomorrow, style: TextStyles.textSMedium.copyWith(color: appTheme.black)),
),
const SizedBox(height: 12),
GestureDetector(
onTap: () {
GoRouter.of(context).pushNamed(
MyDietsScreen.name,
queryParameters: {'initialTabIndex': '2'},
);
},
child: Text(s.goToMyDiets, style: TextStyles.textLSemibold.copyWith(color: appTheme.blueA400)),
),
@@ -240,4 +265,4 @@ class _StarIcon extends StatelessWidget {
}
}
enum BannerType { date, card, payment, collectCharge, finishPlan, setPersonalDiet }
enum BannerType { date, card, payment, collectCharge, finishPlan, setPersonalDiet, changePersonalDiet }

View File

@@ -20,7 +20,7 @@ abstract class ConsultationModel with _$ConsultationModel {
@JsonKey(name: 'user_profile_photo_url') required String userProfilePhotoUrl,
@JsonKey(name: 'consultation_option_price') required int consultationOptionPrice,
@JsonKey(name: 'start_date', fromJson: parseDate) required DateTime startDate,
@JsonKey(name: 'end_date', fromJson: parseDate) required DateTime endDate,
@JsonKey(name: 'end_date', fromJson: parseDateOrNull) DateTime? endDate,
@JsonKey(name: 'consultant_id') required int consultantId,
required List<DiaryModel> diaries,
@JsonKey(name: 'personal_diet_id') required int? personalDietId,
@@ -40,6 +40,11 @@ abstract class DiaryModel with _$DiaryModel {
factory DiaryModel.fromJson(Map<String, dynamic> json) => _$DiaryModelFromJson(json);
}
DateTime? parseDateOrNull(dynamic date) {
if (date == null) return null;
return parseDate(date as String);
}
DateTime parseUnformattedDate(String date) {
final dateChunks = date.split('-').map(int.parse).toList();

View File

@@ -0,0 +1,31 @@
enum ConsultationStep { startDate, paid, inProgress, finished }
enum PersonalDietStatus { notRequired, notProposed, proposed }
enum ConsultationPhase { active, canceled, paymentFailed }
class ConsultationProgress {
const ConsultationProgress({
required this.completedSteps,
required this.showProgressPlank,
required this.dietStatus,
required this.phase,
});
final Set<ConsultationStep> completedSteps;
final bool showProgressPlank;
final PersonalDietStatus dietStatus;
final ConsultationPhase phase;
bool isStepCompleted(ConsultationStep step) => completedSteps.contains(step);
bool get hasDietChip => dietStatus != PersonalDietStatus.notRequired;
bool get hasStatusChip => phase != ConsultationPhase.active;
bool get hasChip => hasDietChip || hasStatusChip;
bool get isCanceled => phase == ConsultationPhase.canceled;
bool get isPaymentFailed => phase == ConsultationPhase.paymentFailed;
}

View File

@@ -85,6 +85,25 @@ class _ConsultationCardWidgetState extends State<ConsultationCardWidget> {
widget.consultationsModel.planTitle,
style: const TextStyle(height: 1, color: Color(0xFF88949F), fontSize: 14, fontWeight: FontWeight.w500),
),
if (widget.consultationsModel.personalDietId != null) ...[
const SizedBox(height: 4),
Container(
padding: const EdgeInsets.symmetric(
horizontal: 8,
vertical: 4,
),
decoration: BoxDecoration(
color: appTheme.transparentGreen,
borderRadius: BorderRadius.circular(100),
),
child: Text(
s.personal_diet_proposed,
style: TextStyles.textXSSemibold.copyWith(
color: appTheme.greenA700,
),
),
),
],
],
),
],

View File

@@ -0,0 +1,111 @@
import 'package:eatvio_app/core/theme/custom_text_style.dart';
import 'package:eatvio_app/core/theme/theme_helper.dart';
import 'package:eatvio_app/features/consultations/models/consultation_progress.dart';
import 'package:eatvio_app/generated/l10n.dart';
import 'package:flutter/material.dart';
class ConsultationProgressPlank extends StatelessWidget {
const ConsultationProgressPlank({super.key, required this.progress});
final ConsultationProgress progress;
static const _steps = [
ConsultationStep.startDate,
ConsultationStep.paid,
ConsultationStep.inProgress,
ConsultationStep.finished,
];
@override
Widget build(BuildContext context) {
if (!progress.showProgressPlank) {
return const SizedBox.shrink();
}
return Column(
children: [
Row(
children: [
for (var index = 0; index < _steps.length; index++) ...[
_ProgressStepCircle(
index: index,
isCompleted: progress.isStepCompleted(_steps[index]),
),
if (index != _steps.length - 1)
Expanded(
child: Container(
height: 2,
color: progress.isStepCompleted(_steps[index])
? appTheme.greenA700
: appTheme.lightGray00,
),
),
],
],
),
const SizedBox(height: 6),
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
for (final step in _steps)
Expanded(
child: Text(
_stepLabel(S.of(context), step),
textAlign: TextAlign.center,
maxLines: 2,
overflow: TextOverflow.ellipsis,
style: TextStyles.textFS10FW500.copyWith(
color: progress.isStepCompleted(step)
? appTheme.black
: appTheme.gray,
),
),
),
],
),
],
);
}
String _stepLabel(S s, ConsultationStep step) {
switch (step) {
case ConsultationStep.startDate:
return s.startDateHasBeenSet;
case ConsultationStep.paid:
return s.order_paid;
case ConsultationStep.inProgress:
return s.order_in_progress;
case ConsultationStep.finished:
return s.done;
}
}
}
class _ProgressStepCircle extends StatelessWidget {
const _ProgressStepCircle({
required this.index,
required this.isCompleted,
});
final int index;
final bool isCompleted;
@override
Widget build(BuildContext context) {
return Container(
width: 24,
height: 24,
alignment: Alignment.center,
decoration: BoxDecoration(
shape: BoxShape.circle,
color: isCompleted ? appTheme.greenA700 : appTheme.lightGray00,
),
child: isCompleted
? Icon(Icons.check, size: 14, color: appTheme.whiteA700)
: Text(
'${index + 1}',
style: TextStyles.textFS10FW500.copyWith(color: appTheme.gray),
),
);
}
}

View File

@@ -0,0 +1,57 @@
import 'package:eatvio_app/core/theme/custom_text_style.dart';
import 'package:eatvio_app/core/theme/theme_helper.dart';
import 'package:eatvio_app/features/consultations/models/consultation_progress.dart';
import 'package:eatvio_app/generated/l10n.dart';
import 'package:flutter/material.dart';
class PersonalDietStatusChip extends StatelessWidget {
const PersonalDietStatusChip({super.key, required this.progress});
final ConsultationProgress progress;
@override
Widget build(BuildContext context) {
if (!progress.hasChip) {
return const SizedBox.shrink();
}
final s = S.of(context);
final (label, background, foreground) = _chipStyle(s);
return Align(
alignment: Alignment.centerLeft,
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6),
decoration: BoxDecoration(
color: background,
borderRadius: BorderRadius.circular(100),
),
child: Text(
label,
style: TextStyles.textXSSemibold.copyWith(color: foreground),
),
),
);
}
(String, Color, Color) _chipStyle(S s) {
if (progress.isCanceled) {
return (s.orderCanceled, appTheme.lightRed, appTheme.red);
}
if (progress.isPaymentFailed) {
return (s.payment_failed, appTheme.lightRed, appTheme.red);
}
if (progress.dietStatus == PersonalDietStatus.proposed) {
return (
s.personal_diet_proposed,
appTheme.transparentGreen,
appTheme.greenA700,
);
}
return (
s.personal_diet_not_proposed,
appTheme.gray100,
appTheme.gray,
);
}
}

View File

@@ -0,0 +1,114 @@
import 'package:eatvio_app/features/consultations/models/consultation_progress.dart';
import 'package:eatvio_app/features/plans/enums/chosen_plan_state_enum.dart';
ConsultationProgress mapConsultationProgress({
required ChosenPlanStateEnum state,
required bool hasPersonalDiet,
}) {
return ConsultationProgress(
completedSteps: _completedSteps(state),
showProgressPlank: _showProgressPlank(state),
dietStatus: _dietStatus(state, hasPersonalDiet),
phase: _phase(state),
);
}
Set<ConsultationStep> _completedSteps(ChosenPlanStateEnum state) {
switch (state) {
case ChosenPlanStateEnum.stateInited:
case ChosenPlanStateEnum.stateConfirmedByConsultant:
case ChosenPlanStateEnum.stateInCoordination:
case ChosenPlanStateEnum.stateCanceledByTheInitiator:
return const {};
case ChosenPlanStateEnum.stateStartDateHasBeenSet:
case ChosenPlanStateEnum.statePendingPayment:
case ChosenPlanStateEnum.statePaymentFailed:
return const {ConsultationStep.startDate};
case ChosenPlanStateEnum.statePaid:
case ChosenPlanStateEnum.personalDietSet:
return const {ConsultationStep.startDate, ConsultationStep.paid};
case ChosenPlanStateEnum.stateStarted:
case ChosenPlanStateEnum.stateInProgress:
case ChosenPlanStateEnum.stateLastDayStarted:
case ChosenPlanStateEnum.stateLastDayFinished:
case ChosenPlanStateEnum.stateComplained:
return const {
ConsultationStep.startDate,
ConsultationStep.paid,
ConsultationStep.inProgress,
};
case ChosenPlanStateEnum.stateDone:
case ChosenPlanStateEnum.stateChargeWasCollected:
return const {
ConsultationStep.startDate,
ConsultationStep.paid,
ConsultationStep.inProgress,
ConsultationStep.finished,
};
}
}
bool _showProgressPlank(ChosenPlanStateEnum state) {
switch (state) {
case ChosenPlanStateEnum.stateInited:
case ChosenPlanStateEnum.stateConfirmedByConsultant:
case ChosenPlanStateEnum.personalDietSet:
case ChosenPlanStateEnum.stateChargeWasCollected:
case ChosenPlanStateEnum.stateCanceledByTheInitiator:
case ChosenPlanStateEnum.statePaymentFailed:
return false;
case ChosenPlanStateEnum.stateInCoordination:
case ChosenPlanStateEnum.stateStartDateHasBeenSet:
case ChosenPlanStateEnum.statePendingPayment:
case ChosenPlanStateEnum.statePaid:
case ChosenPlanStateEnum.stateStarted:
case ChosenPlanStateEnum.stateInProgress:
case ChosenPlanStateEnum.stateLastDayStarted:
case ChosenPlanStateEnum.stateLastDayFinished:
case ChosenPlanStateEnum.stateComplained:
case ChosenPlanStateEnum.stateDone:
return true;
}
}
PersonalDietStatus _dietStatus(
ChosenPlanStateEnum state,
bool hasPersonalDiet,
) {
if (!hasPersonalDiet) {
return PersonalDietStatus.notRequired;
}
switch (state) {
case ChosenPlanStateEnum.personalDietSet:
case ChosenPlanStateEnum.stateStarted:
case ChosenPlanStateEnum.stateInProgress:
case ChosenPlanStateEnum.stateLastDayStarted:
case ChosenPlanStateEnum.stateLastDayFinished:
case ChosenPlanStateEnum.stateComplained:
case ChosenPlanStateEnum.stateDone:
case ChosenPlanStateEnum.stateChargeWasCollected:
return PersonalDietStatus.proposed;
case ChosenPlanStateEnum.stateInited:
case ChosenPlanStateEnum.stateInCoordination:
case ChosenPlanStateEnum.stateConfirmedByConsultant:
case ChosenPlanStateEnum.stateStartDateHasBeenSet:
case ChosenPlanStateEnum.statePendingPayment:
case ChosenPlanStateEnum.statePaid:
return PersonalDietStatus.notProposed;
case ChosenPlanStateEnum.stateCanceledByTheInitiator:
case ChosenPlanStateEnum.statePaymentFailed:
return PersonalDietStatus.notRequired;
}
}
ConsultationPhase _phase(ChosenPlanStateEnum state) {
switch (state) {
case ChosenPlanStateEnum.stateCanceledByTheInitiator:
return ConsultationPhase.canceled;
case ChosenPlanStateEnum.statePaymentFailed:
return ConsultationPhase.paymentFailed;
default:
return ConsultationPhase.active;
}
}

View File

@@ -136,6 +136,11 @@ class MyDietsCubit extends Cubit<MyDietsState> {
}
}
void selectInitialTab(int index) {
if (index < 0 || index > 2) return;
emit(state.copyWith(selectedStateIndex: index));
}
void changeSelectedStateIndex(int index) {
emit(state.copyWith(selectedStateIndex: index));
if (state.activeDiets.isEmpty) {

View File

@@ -19,12 +19,19 @@ import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:go_router/go_router.dart';
class MyDietsScreen extends StatelessWidget {
const MyDietsScreen({super.key});
const MyDietsScreen({super.key, this.initialTabIndex = 0});
static const name = 'myDietsScreen';
static const path = '/my-diets-screen';
final int initialTabIndex;
@override
Widget build(BuildContext context) {
return BlocProvider(create: (context) => sl<MyDietsCubit>()..loadAllDiets(), child: MyDietsScreenContent());
return BlocProvider(
create: (context) =>
sl<MyDietsCubit>()
..selectInitialTab(initialTabIndex)
..loadAllDiets(),
child: MyDietsScreenContent(),
);
}
}

View File

@@ -9,38 +9,50 @@ import 'package:eatvio_app/core/error_reporting/report_from.dart';
class PersonalDietSuggestionCubit extends Cubit<PersonalDietSuggestionState> {
final DietRepository dietRepository;
final PersonalDietSuggestionRepository personalDietSuggestionService;
late final int dietId;
late int dietId;
PersonalDietSuggestionCubit({required this.dietRepository, required this.personalDietSuggestionService}) : super(PersonalDietSuggestionState());
Future<void> setDietName(int dietId) async {
try {
emit(state.copyWith(isLoading: true, error: null));
if (!isClosed) {
emit(state.copyWith(isLoading: true, error: null));
}
final diet = await dietRepository.getDiet(dietId);
emit(state.copyWith(isLoading: false, dietName: diet.name));
if (!isClosed) {
emit(state.copyWith(isLoading: false, dietName: diet.name));
}
} catch (e, st) {
await reportFrom(e, st, this);
log(e.toString(), stackTrace: st);
emit(state.copyWith(isLoading: false, error: e.toString()));
if (!isClosed) {
emit(state.copyWith(isLoading: false, error: e.toString()));
}
}
}
Future<void> getConsultationWithPersonalDiets(int dietId) async {
try {
this.dietId = dietId;
emit(state.copyWith(isLoading: true, error: null));
setDietName(dietId);
if (!isClosed) {
emit(state.copyWith(isLoading: true, error: null));
}
await setDietName(dietId);
final consultations = await personalDietSuggestionService.getConsultationWithPersonalDiets();
final consultationWithDiet = consultations.where((consultation) => consultation.personalDietId != null).toList();
final consultationWithoutDiet = consultations.where((consultation) => consultation.personalDietId == null).toList();
emit(state.copyWith(
isLoading: false,
consultationsWithDiet: consultationWithDiet,
consultationsWithoutDiet: consultationWithoutDiet,
));
if (!isClosed) {
emit(state.copyWith(
isLoading: false,
consultationsWithDiet: consultationWithDiet,
consultationsWithoutDiet: consultationWithoutDiet,
));
}
} catch (e, st) {
await reportFrom(e, st, this);
log(e.toString(), stackTrace: st);
emit(state.copyWith(isLoading: false, error: e.toString()));
if (!isClosed) {
emit(state.copyWith(isLoading: false, error: e.toString()));
}
}
}
@@ -49,6 +61,7 @@ class PersonalDietSuggestionCubit extends Cubit<PersonalDietSuggestionState> {
}) async {
try {
await personalDietSuggestionService.attachPersonalDiet(consultationId: consultationId, dietId: dietId);
await getConsultationWithPersonalDiets(dietId);
return true;
} catch (e, st) {
await reportFrom(e, st, this);
@@ -62,6 +75,7 @@ class PersonalDietSuggestionCubit extends Cubit<PersonalDietSuggestionState> {
}) async {
try {
await personalDietSuggestionService.reattachPersonalDiet(consultationId: consultationId, dietId: dietId);
await getConsultationWithPersonalDiets(dietId);
return true;
} catch (e, st) {
await reportFrom(e, st, this);

View File

@@ -11,6 +11,7 @@ import 'package:eatvio_app/features/consultations/models/consultation_model.dart
import 'package:eatvio_app/features/personal_diet_suggestion/cubit/personal_diet_suggestion_cubit.dart';
import 'package:eatvio_app/generated/l10n.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:go_router/go_router.dart';
@@ -64,7 +65,11 @@ class ConsultationWidget extends StatelessWidget {
),
),
Text(
'Старт: ${consultationModel.userName}',
s.start_date_label(
DateFormat('dd.MM.yyyy').format(
consultationModel.startDate,
),
),
style: TextStyles.textMMedium.copyWith(
color: const Color(0xFF88949F),
),
@@ -130,7 +135,7 @@ class ConsultationWidget extends StatelessWidget {
onTap: () async {
final result = await context
.read<PersonalDietSuggestionCubit>()
.attachDietToConsultation(
.reattachDietToConsultation(
consultationId: consultationModel.id,
);
AppRouter.navigatorKey.currentContext?.pop();

View File

@@ -11,13 +11,23 @@ class PersonalDietSuggestionRepository {
}
Future<void> attachPersonalDiet({required int consultationId, required int dietId}) async {
return personalDietSuggestionService.attachPersonalDiet(consultationId: consultationId, dietId: dietId);
Future<void> attachPersonalDiet({
required int consultationId,
required int dietId,
}) async {
await personalDietSuggestionService.attachPersonalDiet(
consultationId,
{'diet_id': dietId},
);
}
Future<void> reattachPersonalDiet({required int consultationId, required int dietId}) async {
return await personalDietSuggestionService.reattachPersonalDiet(consultationId: consultationId, dietId: dietId);
Future<void> reattachPersonalDiet({
required int consultationId,
required int dietId,
}) async {
await personalDietSuggestionService.reattachPersonalDiet(
consultationId,
{'diet_id': dietId},
);
}
}

View File

@@ -1,36 +1,40 @@
import 'package:dio/dio.dart';
import 'package:eatvio_app/features/consultations/models/consultation_model.dart';
import 'package:retrofit/retrofit.dart';
class PersonalDietSuggestionService {
final Dio dio;
PersonalDietSuggestionService(this.dio);
part 'personal_diet_suggestion_service.g.dart';
Future<ConsultationPaginationModel> getConsultationWithPersonalDiets() async {
try {
final response = await dio.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',
});
return ConsultationPaginationModel.fromJson(response.data);
} catch (e) {
rethrow;
}
}
@RestApi()
abstract class PersonalDietSuggestionService {
factory PersonalDietSuggestionService(Dio dio, {String? baseUrl}) =
_PersonalDietSuggestionService;
Future<void> attachPersonalDiet({required int consultationId, required int dietId}) async {
try {
await dio.post('/api/chosen_plans/$consultationId/attach_diet', data: {'diet_id': dietId});
} catch (e) {
rethrow;
}
}
@GET('/api/consultations')
Future<ConsultationPaginationModel> getConsultationWithPersonalDiets({
@Query('filters[plan][has_personal_diet][\$personal_diet]')
String hasPersonalDiet = '1',
@Query('filters[last_state][\$notIn][]')
List<String> notIn = const [
'done',
'charge_was_collected',
'complained',
'last_day_finished',
'last_day_started',
'canceled_by_the_initiator',
'inited',
],
@Query('sort[]') List<String> sort = const ['start_date:desc'],
});
Future<void> reattachPersonalDiet({required int consultationId, required int dietId}) async {
try {
await dio.post('/api/chosen_plans/$consultationId/re_attach_diet', data: {'diet_id': dietId});
} catch (e) {
rethrow;
}
}
@POST('/api/chosen_plans/{id}/attach_diet')
Future<void> attachPersonalDiet(
@Path('id') int consultationId,
@Body() Map<String, dynamic> body,
);
@POST('/api/chosen_plans/{id}/re_attach_diet')
Future<void> reattachPersonalDiet(
@Path('id') int consultationId,
@Body() Map<String, dynamic> body,
);
}

View File

@@ -21,6 +21,21 @@ abstract class ChosenPlanModel with _$ChosenPlanModel {
factory ChosenPlanModel.fromJson(Map<String, dynamic> json) => _$ChosenPlanModelFromJson(json);
}
extension ChosenPlanModelX on ChosenPlanModel {
PacketOptions? get chosenOption {
switch (optionType) {
case 'options1':
return plan.packet1Options;
case 'options2':
return plan.packet2Options;
case 'options3':
return plan.packet3Options;
default:
return null;
}
}
}
ChosenPlanModel? parseChosenPlan(dynamic json) {
if (json is Map<String, dynamic>) {
return ChosenPlanModel.fromJson(json);