From 29c6692a799e0f8cd9f192bdf68840fbf450bf8f Mon Sep 17 00:00:00 2001 From: Felix Thape Date: Thu, 12 Sep 2024 13:41:01 +0200 Subject: [PATCH 1/9] chore: move service APIs to the service package --- .../tasks/lib/components/assignee_select.dart | 4 +- .../lib/components/patient_bottom_sheet.dart | 379 +++++++++--------- apps/tasks/lib/components/patient_card.dart | 2 +- .../patient_status_chip_select.dart | 2 +- apps/tasks/lib/components/subtask_list.dart | 18 +- .../lib/components/task_bottom_sheet.dart | 9 +- apps/tasks/lib/components/task_card.dart | 2 +- .../lib/components/task_expansion_tile.dart | 3 +- .../lib/components/user_bottom_sheet.dart | 9 +- apps/tasks/lib/components/user_header.dart | 6 +- .../lib/components/visibility_select.dart | 1 - apps/tasks/lib/config/config.dart | 2 +- apps/tasks/lib/dataclasses/subtask.dart | 14 - apps/tasks/lib/debug/theme_visualizer.dart | 4 +- apps/tasks/lib/main.dart | 9 +- apps/tasks/lib/screens/landing_screen.dart | 6 +- apps/tasks/lib/screens/login_screen.dart | 2 +- apps/tasks/lib/screens/main_screen.dart | 6 +- .../my_tasks_screen.dart | 3 +- .../patient_screen.dart | 4 +- apps/tasks/lib/screens/settings_screen.dart | 3 +- .../tasks/lib/screens/ward_select_screen.dart | 10 +- apps/tasks/lib/services/grpc_client_svc.dart | 76 ---- apps/tasks/lib/services/task_svc.dart | 197 --------- apps/tasks/lib/util/task_status_mapping.dart | 16 - apps/tasks/pubspec.lock | 60 +-- apps/tasks/pubspec.yaml | 4 +- packages/helpwave_service/lib/auth.dart | 5 +- .../assignee_select_controller.dart | 10 +- .../lib/src/api/tasks/controllers/index.dart | 6 + .../controllers/my_tasks_controller.dart | 11 +- .../controllers/patient_controller.dart | 7 +- .../controllers/subtask_list_controller.dart | 48 +-- .../tasks}/controllers/task_controller.dart | 6 +- .../controllers/ward_patients_controller.dart | 11 +- .../lib/src/api/tasks/data_types}/bed.dart | 2 +- .../lib/src/api/tasks/data_types/index.dart | 8 + .../src/api/tasks/data_types}/patient.dart | 4 +- .../lib/src/api/tasks/data_types}/room.dart | 2 +- .../lib/src/api/tasks/data_types/subtask.dart | 27 ++ .../lib/src/api/tasks/data_types}/task.dart | 6 +- .../api/tasks/data_types}/task_template.dart | 2 +- .../data_types}/task_template_subtask.dart | 0 .../lib/src/api/tasks/data_types}/ward.dart | 0 .../lib/src/api/tasks/index.dart | 4 + .../lib/src/api/tasks/services/bed_svc.dart | 0 .../lib/src/api/tasks/services/index.dart | 5 + .../src/api/tasks}/services/patient_svc.dart | 63 +-- .../lib/src/api/tasks}/services/room_svc.dart | 14 +- .../lib/src/api/tasks/services/task_svc.dart | 163 ++++++++ .../src/api/tasks}/services/ward_service.dart | 23 +- .../lib/src/api/tasks/tasks_api_services.dart | 42 ++ .../api/tasks/util/task_status_mapping.dart | 30 ++ .../lib/src/api/user/controllers/index.dart | 1 + .../user}/controllers/user_controller.dart | 5 +- .../lib/src/api/user/data_types/index.dart | 2 + .../api/user/data_types}/organization.dart | 0 .../lib/src/api/user/data_types}/user.dart | 0 .../lib/src/api/user/index.dart | 4 + .../lib/src/api/user/services/index.dart | 2 + .../api/user}/services/organization_svc.dart | 20 +- .../src/api/user}/services/user_service.dart | 15 +- .../lib/src/api/user/user_api_services.dart | 36 ++ .../lib/src/auth/authentication_utility.dart | 18 + .../lib/src/auth}/current_ward_svc.dart | 12 +- .../helpwave_service/lib/src/auth/index.dart | 6 + .../src/auth}/user_session_controller.dart | 2 +- .../lib/src/auth}/user_session_service.dart | 10 +- packages/helpwave_service/lib/tasks.dart | 1 + packages/helpwave_service/lib/user.dart | 1 + packages/helpwave_service/pubspec.yaml | 7 +- .../lib/src/{ => theme}/dark_theme.dart | 4 +- .../lib/src/{ => theme}/light_theme.dart | 4 +- .../lib/src/{ => theme}/theme.dart | 2 +- .../lib/src/util/context_extension.dart | 5 + .../helpwave_theme/lib/src/util/index.dart | 2 + .../material_state_color_resolver.dart | 0 packages/helpwave_theme/lib/theme.dart | 4 +- packages/helpwave_theme/lib/util.dart | 2 +- packages/helpwave_util/lib/loading_state.dart | 1 + packages/helpwave_util/lib/search.dart | 1 + .../lib/src/loading_state/type.dart | 16 + .../lib/src/search}/search_helpers.dart | 0 .../src/loading/loading_and_error_widget.dart | 18 +- .../src/loading/loading_future_builder.dart | 1 + packages/helpwave_widget/pubspec.yaml | 1 + 86 files changed, 764 insertions(+), 789 deletions(-) delete mode 100644 apps/tasks/lib/dataclasses/subtask.dart delete mode 100644 apps/tasks/lib/services/grpc_client_svc.dart delete mode 100644 apps/tasks/lib/services/task_svc.dart delete mode 100644 apps/tasks/lib/util/task_status_mapping.dart rename {apps/tasks/lib => packages/helpwave_service/lib/src/api/tasks}/controllers/assignee_select_controller.dart (86%) create mode 100644 packages/helpwave_service/lib/src/api/tasks/controllers/index.dart rename {apps/tasks/lib => packages/helpwave_service/lib/src/api/tasks}/controllers/my_tasks_controller.dart (81%) rename {apps/tasks/lib => packages/helpwave_service/lib/src/api/tasks}/controllers/patient_controller.dart (95%) rename {apps/tasks/lib => packages/helpwave_service/lib/src/api/tasks}/controllers/subtask_list_controller.dart (66%) rename {apps/tasks/lib => packages/helpwave_service/lib/src/api/tasks}/controllers/task_controller.dart (96%) rename {apps/tasks/lib => packages/helpwave_service/lib/src/api/tasks}/controllers/ward_patients_controller.dart (86%) rename {apps/tasks/lib/dataclasses => packages/helpwave_service/lib/src/api/tasks/data_types}/bed.dart (84%) create mode 100644 packages/helpwave_service/lib/src/api/tasks/data_types/index.dart rename {apps/tasks/lib/dataclasses => packages/helpwave_service/lib/src/api/tasks/data_types}/patient.dart (94%) rename {apps/tasks/lib/dataclasses => packages/helpwave_service/lib/src/api/tasks/data_types}/room.dart (94%) create mode 100644 packages/helpwave_service/lib/src/api/tasks/data_types/subtask.dart rename {apps/tasks/lib/dataclasses => packages/helpwave_service/lib/src/api/tasks/data_types}/task.dart (93%) rename {apps/tasks/lib/dataclasses => packages/helpwave_service/lib/src/api/tasks/data_types}/task_template.dart (86%) rename {apps/tasks/lib/dataclasses => packages/helpwave_service/lib/src/api/tasks/data_types}/task_template_subtask.dart (100%) rename {apps/tasks/lib/dataclasses => packages/helpwave_service/lib/src/api/tasks/data_types}/ward.dart (100%) create mode 100644 packages/helpwave_service/lib/src/api/tasks/index.dart create mode 100644 packages/helpwave_service/lib/src/api/tasks/services/bed_svc.dart create mode 100644 packages/helpwave_service/lib/src/api/tasks/services/index.dart rename {apps/tasks/lib => packages/helpwave_service/lib/src/api/tasks}/services/patient_svc.dart (77%) rename {apps/tasks/lib => packages/helpwave_service/lib/src/api/tasks}/services/room_svc.dart (72%) create mode 100644 packages/helpwave_service/lib/src/api/tasks/services/task_svc.dart rename {apps/tasks/lib => packages/helpwave_service/lib/src/api/tasks}/services/ward_service.dart (59%) create mode 100644 packages/helpwave_service/lib/src/api/tasks/tasks_api_services.dart create mode 100644 packages/helpwave_service/lib/src/api/tasks/util/task_status_mapping.dart create mode 100644 packages/helpwave_service/lib/src/api/user/controllers/index.dart rename {apps/tasks/lib => packages/helpwave_service/lib/src/api/user}/controllers/user_controller.dart (91%) create mode 100644 packages/helpwave_service/lib/src/api/user/data_types/index.dart rename {apps/tasks/lib/dataclasses => packages/helpwave_service/lib/src/api/user/data_types}/organization.dart (100%) rename {apps/tasks/lib/dataclasses => packages/helpwave_service/lib/src/api/user/data_types}/user.dart (100%) create mode 100644 packages/helpwave_service/lib/src/api/user/index.dart create mode 100644 packages/helpwave_service/lib/src/api/user/services/index.dart rename {apps/tasks/lib => packages/helpwave_service/lib/src/api/user}/services/organization_svc.dart (74%) rename {apps/tasks/lib => packages/helpwave_service/lib/src/api/user}/services/user_service.dart (59%) create mode 100644 packages/helpwave_service/lib/src/api/user/user_api_services.dart create mode 100644 packages/helpwave_service/lib/src/auth/authentication_utility.dart rename {apps/tasks/lib/services => packages/helpwave_service/lib/src/auth}/current_ward_svc.dart (95%) create mode 100644 packages/helpwave_service/lib/src/auth/index.dart rename {apps/tasks/lib/controllers => packages/helpwave_service/lib/src/auth}/user_session_controller.dart (94%) rename {apps/tasks/lib/services => packages/helpwave_service/lib/src/auth}/user_session_service.dart (87%) create mode 100644 packages/helpwave_service/lib/tasks.dart create mode 100644 packages/helpwave_service/lib/user.dart rename packages/helpwave_theme/lib/src/{ => theme}/dark_theme.dart (97%) rename packages/helpwave_theme/lib/src/{ => theme}/light_theme.dart (97%) rename packages/helpwave_theme/lib/src/{ => theme}/theme.dart (99%) create mode 100644 packages/helpwave_theme/lib/src/util/context_extension.dart create mode 100644 packages/helpwave_theme/lib/src/util/index.dart rename packages/helpwave_theme/lib/src/{ => util}/material_state_color_resolver.dart (100%) create mode 100644 packages/helpwave_util/lib/loading_state.dart create mode 100644 packages/helpwave_util/lib/search.dart create mode 100644 packages/helpwave_util/lib/src/loading_state/type.dart rename {apps/tasks/lib/util => packages/helpwave_util/lib/src/search}/search_helpers.dart (100%) diff --git a/apps/tasks/lib/components/assignee_select.dart b/apps/tasks/lib/components/assignee_select.dart index d04bd06f..311999fb 100644 --- a/apps/tasks/lib/components/assignee_select.dart +++ b/apps/tasks/lib/components/assignee_select.dart @@ -1,11 +1,11 @@ import 'package:flutter/material.dart'; import 'package:helpwave_localization/localization.dart'; +import 'package:helpwave_service/tasks.dart'; +import 'package:helpwave_service/user.dart'; import 'package:helpwave_theme/constants.dart'; import 'package:helpwave_widget/bottom_sheets.dart'; import 'package:helpwave_widget/loading.dart'; import 'package:provider/provider.dart'; -import 'package:tasks/controllers/assignee_select_controller.dart'; -import 'package:tasks/dataclasses/user.dart'; /// A [BottomSheet] for selecting a assignee class AssigneeSelect extends StatelessWidget { diff --git a/apps/tasks/lib/components/patient_bottom_sheet.dart b/apps/tasks/lib/components/patient_bottom_sheet.dart index a15015e0..12b6e91e 100644 --- a/apps/tasks/lib/components/patient_bottom_sheet.dart +++ b/apps/tasks/lib/components/patient_bottom_sheet.dart @@ -1,5 +1,6 @@ import 'package:flutter/material.dart'; import 'package:helpwave_localization/localization.dart'; +import 'package:helpwave_service/auth.dart'; import 'package:helpwave_theme/constants.dart'; import 'package:helpwave_theme/util.dart'; import 'package:helpwave_widget/bottom_sheets.dart'; @@ -10,13 +11,8 @@ import 'package:helpwave_widget/text_input.dart'; import 'package:provider/provider.dart'; import 'package:tasks/components/task_bottom_sheet.dart'; import 'package:tasks/components/task_expansion_tile.dart'; -import 'package:tasks/controllers/patient_controller.dart'; -import 'package:tasks/dataclasses/bed.dart'; -import 'package:tasks/dataclasses/patient.dart'; -import 'package:tasks/dataclasses/room.dart'; -import 'package:tasks/dataclasses/task.dart'; -import 'package:tasks/services/current_ward_svc.dart'; -import 'package:tasks/services/room_svc.dart'; +import 'package:helpwave_service/tasks.dart'; +import 'package:helpwave_util/loading_state.dart'; /// A [BottomSheet] for showing [Patient] information and [Task]s for that [Patient] class PatientBottomSheet extends StatefulWidget { @@ -83,194 +79,199 @@ class _PatientBottomSheetState extends State { return LoadingAndErrorWidget( state: patientController.state, child: Row( - mainAxisAlignment: patientController.isCreating ? MainAxisAlignment.end : MainAxisAlignment.spaceBetween, - children: patientController.isCreating - ? [ - TextButton( - style: buttonStyleBig, - onPressed: patientController.create, - child: Text(context.localization!.create), - ) - ] - : [ - SizedBox( - width: width * 0.4, - // TODO make this state checking easier and more readable - child: TextButton( - onPressed: patientController.patient.isUnassigned - ? null - : () { - patientController.unassign(); - }, - style: buttonStyleMedium.copyWith( - backgroundColor: resolveByStatesAndContextBackground( - context: context, - defaultValue: inProgressColor, - ), - foregroundColor: resolveByStatesAndContextForeground( - context: context, - ), - ), - child: Text(context.localization!.unassigne), - ), - ), - SizedBox( - width: width * 0.4, - child: TextButton( - // TODO check whether the patient is active - onPressed: patientController.patient.isDischarged ? null : () { - showDialog( - context: context, - builder: (context) => AcceptDialog(titleText: context.localization!.dischargePatient), - ).then((value) { - if (value) { - patientController.discharge(); - Navigator.of(context).pop(); - } - }); - }, - style: buttonStyleMedium.copyWith( - backgroundColor: resolveByStatesAndContextBackground( - context: context, - defaultValue: negativeColor, - ), - foregroundColor: resolveByStatesAndContextForeground( - context: context, - ), - ), - child: Text(context.localization!.discharge), - ), - ), - ], - )); - } ), - ), builder: (BuildContext context) => Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Center( - child: Consumer(builder: (context, patientController, _) { - return LoadingFutureBuilder( - future: loadRoomsWithBeds(patientController.patient.id), - // TODO use a better loading widget - loadingWidget: const SizedBox(), - thenWidgetBuilder: (context, beds) { - if (beds.isEmpty) { - return Text( - context.localization!.noFreeBeds, - style: TextStyle(color: Theme.of(context).disabledColor, fontWeight: FontWeight.bold), - ); - } - return DropdownButtonHideUnderline( - child: DropdownButton( - iconEnabledColor: Theme.of(context).colorScheme.secondary.withOpacity(0.6), - padding: EdgeInsets.zero, - isDense: true, - hint: Text( - context.localization!.assignBed, - style: TextStyle(color: Theme.of(context).colorScheme.secondary.withOpacity(0.6)), - ), - value: !patientController.patient.isUnassigned - ? RoomWithBedFlat( - room: patientController.patient.room!, bed: patientController.patient.bed!) - : null, - items: beds - .map((roomWithBed) => DropdownMenuItem( - value: roomWithBed, - child: Text( - "${roomWithBed.room.name} - ${roomWithBed.bed.name}", - style: TextStyle(color: Theme.of(context).colorScheme.primary.withOpacity(0.6)), + mainAxisAlignment: + patientController.isCreating ? MainAxisAlignment.end : MainAxisAlignment.spaceBetween, + children: patientController.isCreating + ? [ + TextButton( + style: buttonStyleBig, + onPressed: patientController.create, + child: Text(context.localization!.create), + ) + ] + : [ + SizedBox( + width: width * 0.4, + // TODO make this state checking easier and more readable + child: TextButton( + onPressed: patientController.patient.isUnassigned + ? null + : () { + patientController.unassign(); + }, + style: buttonStyleMedium.copyWith( + backgroundColor: resolveByStatesAndContextBackground( + context: context, + defaultValue: inProgressColor, + ), + foregroundColor: resolveByStatesAndContextForeground( + context: context, + ), + ), + child: Text(context.localization!.unassigne), + ), + ), + SizedBox( + width: width * 0.4, + child: TextButton( + // TODO check whether the patient is active + onPressed: patientController.patient.isDischarged + ? null + : () { + showDialog( + context: context, + builder: (context) => + AcceptDialog(titleText: context.localization!.dischargePatient), + ).then((value) { + if (value) { + patientController.discharge(); + Navigator.of(context).pop(); + } + }); + }, + style: buttonStyleMedium.copyWith( + backgroundColor: resolveByStatesAndContextBackground( + context: context, + defaultValue: negativeColor, + ), + foregroundColor: resolveByStatesAndContextForeground( + context: context, + ), + ), + child: Text(context.localization!.discharge), + ), + ), + ], + )); + }), + ), + builder: (BuildContext context) => Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Center( + child: Consumer(builder: (context, patientController, _) { + return LoadingFutureBuilder( + future: loadRoomsWithBeds(patientController.patient.id), + // TODO use a better loading widget + loadingWidget: const SizedBox(), + thenWidgetBuilder: (context, beds) { + if (beds.isEmpty) { + return Text( + context.localization!.noFreeBeds, + style: TextStyle(color: Theme.of(context).disabledColor, fontWeight: FontWeight.bold), + ); + } + return DropdownButtonHideUnderline( + child: DropdownButton( + iconEnabledColor: Theme.of(context).colorScheme.secondary.withOpacity(0.6), + padding: EdgeInsets.zero, + isDense: true, + hint: Text( + context.localization!.assignBed, + style: TextStyle(color: Theme.of(context).colorScheme.secondary.withOpacity(0.6)), ), - )) - .toList(), - onChanged: (RoomWithBedFlat? value) { - // TODO later unassign here - if (value == null) { - return; - } - patientController.changeBed(value.room, value.bed); - }, - ), - ); - }, - ); - }), - ), - Text( - context.localization!.notes, - style: const TextStyle(fontSize: fontSizeBig, fontWeight: FontWeight.bold), - ), - const SizedBox(height: distanceSmall), - Consumer( - builder: (context, patientController, _) => - patientController.state == LoadingState.loaded || patientController.isCreating - ? TextFormFieldWithTimer( - initialValue: patientController.patient.notes, - maxLines: 6, - onUpdate: patientController.changeNotes, - ) - : TextFormField(maxLines: 6), - ), - Padding( - padding: const EdgeInsets.symmetric(vertical: paddingMedium), - child: Consumer(builder: (context, patientController, _) { - Patient patient = patientController.patient; - return AddList( - maxHeight: width * 0.5, - items: [ - ...patient.unscheduledTasks, - ...patient.inProgressTasks, - ...patient.doneTasks, - ], - itemBuilder: (_, index, taskList) { - if (index == 0) { - return TaskExpansionTile( - tasks: patient.unscheduledTasks - .map((task) => TaskWithPatient.fromTaskAndPatient( - task: task, - patient: patient, - )) - .toList(), - title: context.localization!.upcoming, - color: upcomingColor, + value: !patientController.patient.isUnassigned + ? RoomWithBedFlat( + room: patientController.patient.room!, bed: patientController.patient.bed!) + : null, + items: beds + .map((roomWithBed) => DropdownMenuItem( + value: roomWithBed, + child: Text( + "${roomWithBed.room.name} - ${roomWithBed.bed.name}", + style: TextStyle(color: Theme.of(context).colorScheme.primary.withOpacity(0.6)), + ), + )) + .toList(), + onChanged: (RoomWithBedFlat? value) { + // TODO later unassign here + if (value == null) { + return; + } + patientController.changeBed(value.room, value.bed); + }, + ), ); - } - if (index == 2) { + }, + ); + }), + ), + Text( + context.localization!.notes, + style: const TextStyle(fontSize: fontSizeBig, fontWeight: FontWeight.bold), + ), + const SizedBox(height: distanceSmall), + Consumer( + builder: (context, patientController, _) => + patientController.state == LoadingState.loaded || patientController.isCreating + ? TextFormFieldWithTimer( + initialValue: patientController.patient.notes, + maxLines: 6, + onUpdate: patientController.changeNotes, + ) + : TextFormField(maxLines: 6), + ), + Padding( + padding: const EdgeInsets.symmetric(vertical: paddingMedium), + child: Consumer(builder: (context, patientController, _) { + Patient patient = patientController.patient; + return AddList( + maxHeight: width * 0.5, + items: [ + ...patient.unscheduledTasks, + ...patient.inProgressTasks, + ...patient.doneTasks, + ], + itemBuilder: (_, index, taskList) { + if (index == 0) { + return TaskExpansionTile( + tasks: patient.unscheduledTasks + .map((task) => TaskWithPatient.fromTaskAndPatient( + task: task, + patient: patient, + )) + .toList(), + title: context.localization!.upcoming, + color: upcomingColor, + ); + } + if (index == 2) { + return TaskExpansionTile( + tasks: patient.doneTasks + .map((task) => TaskWithPatient.fromTaskAndPatient( + task: task, + patient: patient, + )) + .toList(), + title: context.localization!.inProgress, + color: inProgressColor, + ); + } return TaskExpansionTile( - tasks: patient.doneTasks + tasks: patient.inProgressTasks .map((task) => TaskWithPatient.fromTaskAndPatient( - task: task, - patient: patient, - )) + task: task, + patient: patient, + )) .toList(), - title: context.localization!.inProgress, - color: inProgressColor, + title: context.localization!.done, + color: doneColor, ); - } - return TaskExpansionTile( - tasks: patient.inProgressTasks - .map((task) => TaskWithPatient.fromTaskAndPatient( - task: task, - patient: patient, - )) - .toList(), - title: context.localization!.done, - color: doneColor, - ); - }, - title: Text( - context.localization!.tasks, - style: const TextStyle(fontSize: fontSizeBig, fontWeight: FontWeight.bold), - ), - // TODO use return value to add it to task list or force a refetch - onAdd: () => context.pushModal( - context: context, - builder: (context) => TaskBottomSheet(task: Task.empty, patient: patient), - ), - ); - }), - ), - ], - ), + }, + title: Text( + context.localization!.tasks, + style: const TextStyle(fontSize: fontSizeBig, fontWeight: FontWeight.bold), + ), + // TODO use return value to add it to task list or force a refetch + onAdd: () => context.pushModal( + context: context, + builder: (context) => TaskBottomSheet(task: Task.empty, patient: patient), + ), + ); + }), + ), + ], + ), ), ); } diff --git a/apps/tasks/lib/components/patient_card.dart b/apps/tasks/lib/components/patient_card.dart index cffd161e..d26c63a3 100644 --- a/apps/tasks/lib/components/patient_card.dart +++ b/apps/tasks/lib/components/patient_card.dart @@ -1,8 +1,8 @@ import 'package:flutter/material.dart'; +import 'package:helpwave_service/tasks.dart'; import 'package:tasks/components/task_status_pill_box.dart'; import 'package:helpwave_localization/localization.dart'; import 'package:helpwave_theme/constants.dart'; -import 'package:tasks/dataclasses/patient.dart'; /// A [Widget] for displaying a card containing [Patient] information class PatientCard extends StatelessWidget { diff --git a/apps/tasks/lib/components/patient_status_chip_select.dart b/apps/tasks/lib/components/patient_status_chip_select.dart index c352d9f2..093c5c2f 100644 --- a/apps/tasks/lib/components/patient_status_chip_select.dart +++ b/apps/tasks/lib/components/patient_status_chip_select.dart @@ -1,7 +1,7 @@ import 'package:flutter/cupertino.dart'; import 'package:helpwave_localization/localization.dart'; +import 'package:helpwave_service/tasks.dart'; import 'package:helpwave_widget/content_selection.dart'; -import 'package:tasks/dataclasses/patient.dart'; enum PatientStatusChipSelectOptions { all, active, unassigned, discharged } diff --git a/apps/tasks/lib/components/subtask_list.dart b/apps/tasks/lib/components/subtask_list.dart index 5f78657b..11433f36 100644 --- a/apps/tasks/lib/components/subtask_list.dart +++ b/apps/tasks/lib/components/subtask_list.dart @@ -1,25 +1,23 @@ import 'package:flutter/material.dart'; import 'package:helpwave_localization/localization.dart'; +import 'package:helpwave_service/tasks.dart'; import 'package:helpwave_theme/constants.dart'; import 'package:helpwave_theme/util.dart'; import 'package:helpwave_widget/lists.dart'; import 'package:provider/provider.dart'; -import 'package:tasks/controllers/subtask_list_controller.dart'; -import 'package:tasks/dataclasses/subtask.dart'; -import 'package:tasks/dataclasses/task.dart'; -/// A [Widget] for displaying an updating a [List] of [SubTask]s +/// A [Widget] for displaying an updating a [List] of [Subtask]s class SubtaskList extends StatelessWidget { - /// The identifier of the [Task] to which all of these [SubTask]s belong + /// The identifier of the [Task] to which all of these [Subtask]s belong final String taskId; /// The [List] of initial subtasks - final List subtasks; + final List subtasks; /// The callback when the [subtasks] are changed /// /// Should **only** be used when [taskId == ""] - final void Function(List subtasks) onChange; + final void Function(List subtasks) onChange; const SubtaskList({ super.key, @@ -43,7 +41,7 @@ class SubtaskList extends StatelessWidget { style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 16), ), onAdd: () => subtasksController - .add(SubTask(id: "", name: "Subtask ${subtasksController.subtasks.length + 1}")) + .add(Subtask(id: "", name: "Subtask ${subtasksController.subtasks.length + 1}")) .then((_) => onChange(subtasksController.subtasks)), itemBuilder: (context, _, subtask) => ListTile( contentPadding: EdgeInsets.zero, @@ -71,8 +69,8 @@ class SubtaskList extends StatelessWidget { shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(iconSizeSmall), ), - onChanged: (value) => subtasksController - .changeStatus(subTask: subtask, value: value ?? false) + onChanged: (isDone) => subtasksController + .updateSubtask(subTask: subtask.copyWith(isDone: isDone)) .then((value) => onChange(subtasksController.subtasks)), ), trailing: GestureDetector( diff --git a/apps/tasks/lib/components/task_bottom_sheet.dart b/apps/tasks/lib/components/task_bottom_sheet.dart index 84f33257..d01138eb 100644 --- a/apps/tasks/lib/components/task_bottom_sheet.dart +++ b/apps/tasks/lib/components/task_bottom_sheet.dart @@ -1,5 +1,6 @@ import 'package:flutter/material.dart'; import 'package:helpwave_localization/localization.dart'; +import 'package:helpwave_service/user.dart'; import 'package:helpwave_theme/constants.dart'; import 'package:helpwave_widget/bottom_sheets.dart'; import 'package:helpwave_widget/loading.dart'; @@ -8,13 +9,7 @@ import 'package:provider/provider.dart'; import 'package:tasks/components/assignee_select.dart'; import 'package:tasks/components/subtask_list.dart'; import 'package:tasks/components/visibility_select.dart'; -import 'package:tasks/controllers/task_controller.dart'; -import 'package:tasks/controllers/user_controller.dart'; -import 'package:tasks/dataclasses/patient.dart'; -import 'package:tasks/dataclasses/user.dart'; -import 'package:tasks/services/patient_svc.dart'; -import '../controllers/assignee_select_controller.dart'; -import '../dataclasses/task.dart'; +import 'package:helpwave_service/tasks.dart'; /// A private [Widget] similar to a [ListTile] that has an icon and then to text /// diff --git a/apps/tasks/lib/components/task_card.dart b/apps/tasks/lib/components/task_card.dart index 0ec86450..3eade9a4 100644 --- a/apps/tasks/lib/components/task_card.dart +++ b/apps/tasks/lib/components/task_card.dart @@ -1,8 +1,8 @@ import 'package:flutter/material.dart'; import 'package:helpwave_localization/localization.dart'; +import 'package:helpwave_service/tasks.dart'; import 'package:helpwave_theme/constants.dart'; import 'package:helpwave_widget/static_progress_indicator.dart'; -import 'package:tasks/dataclasses/task.dart'; /// A [Card] showing a [Task]'s information class TaskCard extends StatelessWidget { diff --git a/apps/tasks/lib/components/task_expansion_tile.dart b/apps/tasks/lib/components/task_expansion_tile.dart index ed768d44..dd03b854 100644 --- a/apps/tasks/lib/components/task_expansion_tile.dart +++ b/apps/tasks/lib/components/task_expansion_tile.dart @@ -5,8 +5,7 @@ import 'package:helpwave_widget/shapes.dart'; import 'package:provider/provider.dart'; import 'package:tasks/components/task_bottom_sheet.dart'; import 'package:tasks/components/task_card.dart'; -import '../controllers/my_tasks_controller.dart'; -import '../dataclasses/task.dart'; +import 'package:helpwave_service/tasks.dart'; /// A [ExpansionTile] for showing a [List] of [Task]s /// diff --git a/apps/tasks/lib/components/user_bottom_sheet.dart b/apps/tasks/lib/components/user_bottom_sheet.dart index a574454d..41d94aa1 100644 --- a/apps/tasks/lib/components/user_bottom_sheet.dart +++ b/apps/tasks/lib/components/user_bottom_sheet.dart @@ -5,12 +5,9 @@ import 'package:helpwave_theme/constants.dart'; import 'package:helpwave_widget/bottom_sheets.dart'; import 'package:helpwave_widget/loading.dart'; import 'package:provider/provider.dart'; -import 'package:tasks/controllers/user_session_controller.dart'; -import 'package:tasks/services/current_ward_svc.dart'; -import '../dataclasses/ward.dart'; -import '../screens/login_screen.dart'; -import '../services/user_session_service.dart'; -import '../services/ward_service.dart'; +import 'package:helpwave_service/tasks.dart'; +import 'package:helpwave_service/auth.dart'; +import 'package:tasks/screens/login_screen.dart'; /// A [BottomSheet] for showing the [User]s information class UserBottomSheet extends StatefulWidget { diff --git a/apps/tasks/lib/components/user_header.dart b/apps/tasks/lib/components/user_header.dart index 4506c38b..b66cac3a 100644 --- a/apps/tasks/lib/components/user_header.dart +++ b/apps/tasks/lib/components/user_header.dart @@ -1,13 +1,11 @@ import 'package:flutter/material.dart'; +import 'package:helpwave_service/auth.dart'; +import 'package:helpwave_service/tasks.dart'; import 'package:helpwave_theme/constants.dart'; import 'package:helpwave_widget/bottom_sheets.dart'; import 'package:provider/provider.dart'; import 'package:tasks/components/user_bottom_sheet.dart'; -import 'package:tasks/controllers/user_session_controller.dart'; -import 'package:tasks/dataclasses/organization.dart'; -import 'package:tasks/dataclasses/ward.dart'; import 'package:tasks/screens/settings_screen.dart'; -import 'package:tasks/services/current_ward_svc.dart'; /// A [AppBar] for displaying the current [User], [Organization] and [Ward] class UserHeader extends StatelessWidget implements PreferredSizeWidget { diff --git a/apps/tasks/lib/components/visibility_select.dart b/apps/tasks/lib/components/visibility_select.dart index 677e93ed..2c458b20 100644 --- a/apps/tasks/lib/components/visibility_select.dart +++ b/apps/tasks/lib/components/visibility_select.dart @@ -3,7 +3,6 @@ import 'package:helpwave_localization/localization.dart'; import 'package:helpwave_theme/constants.dart'; import 'package:helpwave_widget/bottom_sheets.dart'; import 'package:helpwave_widget/dialog.dart'; -import 'package:tasks/dataclasses/task.dart'; /// A [BottomSheet] to change the visibility class _VisibilityBottomSheet extends StatelessWidget { diff --git a/apps/tasks/lib/config/config.dart b/apps/tasks/lib/config/config.dart index 207fcd97..a0f1e628 100644 --- a/apps/tasks/lib/config/config.dart +++ b/apps/tasks/lib/config/config.dart @@ -4,7 +4,7 @@ const minimumPasswordCharacters = 6; /// Whether the development mode should be enabled /// /// Shortens the login -const bool devMode = false; +const bool devMode = true; /// The API for testing const String stagingAPIURL = "staging.api.helpwave.de"; diff --git a/apps/tasks/lib/dataclasses/subtask.dart b/apps/tasks/lib/dataclasses/subtask.dart deleted file mode 100644 index b48c6d32..00000000 --- a/apps/tasks/lib/dataclasses/subtask.dart +++ /dev/null @@ -1,14 +0,0 @@ -/// data class for [SubTask] -class SubTask { - String id; - String name; - bool isDone; - - bool get isCreating => id == ""; - - SubTask({ - required this.id, - required this.name, - this.isDone = false - }); -} diff --git a/apps/tasks/lib/debug/theme_visualizer.dart b/apps/tasks/lib/debug/theme_visualizer.dart index fe0b59bf..d042da5b 100644 --- a/apps/tasks/lib/debug/theme_visualizer.dart +++ b/apps/tasks/lib/debug/theme_visualizer.dart @@ -5,9 +5,7 @@ import 'package:helpwave_widget/loading.dart'; import 'package:provider/provider.dart'; import 'package:tasks/components/subtask_list.dart'; import 'package:tasks/components/task_card.dart'; -import 'package:tasks/dataclasses/patient.dart'; - -import '../dataclasses/task.dart'; +import 'package:helpwave_service/tasks.dart'; class ThemeVisualizer extends StatelessWidget { const ThemeVisualizer({super.key}); diff --git a/apps/tasks/lib/main.dart b/apps/tasks/lib/main.dart index f6e1808b..e5b4ad0f 100644 --- a/apps/tasks/lib/main.dart +++ b/apps/tasks/lib/main.dart @@ -1,14 +1,17 @@ import 'package:flutter/material.dart'; +import 'package:helpwave_service/auth.dart'; import 'package:provider/provider.dart'; import 'package:helpwave_localization/l10n/app_localizations.dart'; import 'package:helpwave_localization/localization.dart'; import 'package:helpwave_localization/localization_model.dart'; import 'package:helpwave_theme/theme.dart'; +import 'package:tasks/config/config.dart'; +import 'package:helpwave_service/tasks.dart'; import 'package:tasks/screens/login_screen.dart'; -import 'package:tasks/services/current_ward_svc.dart'; -import 'controllers/user_session_controller.dart'; void main() { + UserSessionService().changeMode(devMode); + TasksAPIServices.apiUrl = usedAPIURL; runApp(const MyApp()); } @@ -26,7 +29,7 @@ class MyApp extends StatelessWidget { create: (_) => LanguageModel(), ), ChangeNotifierProvider( - create: (_) => CurrentWardController(), + create: (_) => CurrentWardController(devMode: devMode), ), ChangeNotifierProvider( create: (_) => UserSessionController(), diff --git a/apps/tasks/lib/screens/landing_screen.dart b/apps/tasks/lib/screens/landing_screen.dart index ba487dd1..052622a1 100644 --- a/apps/tasks/lib/screens/landing_screen.dart +++ b/apps/tasks/lib/screens/landing_screen.dart @@ -1,10 +1,11 @@ import 'package:flutter/material.dart'; import 'package:helpwave_localization/localization.dart'; +import 'package:helpwave_service/auth.dart'; import 'package:helpwave_theme/constants.dart'; import 'package:helpwave_theme/theme.dart'; +import 'package:helpwave_theme/util.dart'; import 'package:helpwave_widget/loading.dart'; import 'package:provider/provider.dart'; -import 'package:tasks/controllers/user_session_controller.dart'; /// The Landing Screen of the Application class LandingScreen extends StatelessWidget { @@ -24,7 +25,8 @@ class LandingScreen extends StatelessWidget { } return OutlinedButton( - style: buttonStyleBig.copyWith(side: const MaterialStatePropertyAll(buttonBorderSideBig)), + style: buttonStyleBig.copyWith(side: MaterialStatePropertyAll(buttonBorderSideBig.copyWith(color: context + .theme.colorScheme.onBackground))), child: Text( context.localization!.loginSlogan, style: Theme.of(context).textTheme.labelLarge, diff --git a/apps/tasks/lib/screens/login_screen.dart b/apps/tasks/lib/screens/login_screen.dart index 8d963cb4..89ac9a6d 100644 --- a/apps/tasks/lib/screens/login_screen.dart +++ b/apps/tasks/lib/screens/login_screen.dart @@ -1,8 +1,8 @@ import 'package:flutter/cupertino.dart'; +import 'package:helpwave_service/auth.dart'; import 'package:provider/provider.dart'; import 'package:tasks/screens/landing_screen.dart'; import 'package:tasks/screens/main_screen.dart'; -import '../controllers/user_session_controller.dart'; /// A Screen for forcing the User to login or be logged in /// diff --git a/apps/tasks/lib/screens/main_screen.dart b/apps/tasks/lib/screens/main_screen.dart index 690e5d2b..1235b056 100644 --- a/apps/tasks/lib/screens/main_screen.dart +++ b/apps/tasks/lib/screens/main_screen.dart @@ -1,19 +1,19 @@ import 'dart:async'; import 'package:flutter/material.dart'; import 'package:helpwave_localization/localization.dart'; +import 'package:helpwave_service/auth.dart'; +import 'package:helpwave_service/tasks.dart'; import 'package:helpwave_theme/constants.dart'; import 'package:helpwave_theme/theme.dart'; import 'package:helpwave_widget/bottom_sheets.dart'; import 'package:helpwave_widget/animation.dart'; import 'package:provider/provider.dart'; import 'package:tasks/components/patient_bottom_sheet.dart'; +import 'package:tasks/components/task_bottom_sheet.dart'; import 'package:tasks/components/user_header.dart'; import 'package:tasks/screens/main_screen_subscreens/my_tasks_screen.dart'; import 'package:tasks/screens/main_screen_subscreens/patient_screen.dart'; import 'package:tasks/screens/ward_select_screen.dart'; -import 'package:tasks/services/current_ward_svc.dart'; -import '../components/task_bottom_sheet.dart'; -import '../dataclasses/task.dart'; /// The main screen of the app /// diff --git a/apps/tasks/lib/screens/main_screen_subscreens/my_tasks_screen.dart b/apps/tasks/lib/screens/main_screen_subscreens/my_tasks_screen.dart index 47a93010..43572a93 100644 --- a/apps/tasks/lib/screens/main_screen_subscreens/my_tasks_screen.dart +++ b/apps/tasks/lib/screens/main_screen_subscreens/my_tasks_screen.dart @@ -1,11 +1,10 @@ import 'package:flutter/material.dart'; +import 'package:helpwave_service/tasks.dart'; import 'package:helpwave_theme/constants.dart'; import 'package:provider/provider.dart'; import 'package:helpwave_localization/localization.dart'; import 'package:tasks/components/task_expansion_tile.dart'; import 'package:helpwave_widget/loading.dart'; -import '../../controllers/my_tasks_controller.dart'; -import '../../dataclasses/task.dart'; /// The Screen for showing all [Task]'s the [User] has assigned to them class MyTasksScreen extends StatefulWidget { diff --git a/apps/tasks/lib/screens/main_screen_subscreens/patient_screen.dart b/apps/tasks/lib/screens/main_screen_subscreens/patient_screen.dart index 511028a9..80ce9f6f 100644 --- a/apps/tasks/lib/screens/main_screen_subscreens/patient_screen.dart +++ b/apps/tasks/lib/screens/main_screen_subscreens/patient_screen.dart @@ -8,9 +8,7 @@ import 'package:tasks/components/patient_bottom_sheet.dart'; import 'package:tasks/components/patient_card.dart'; import 'package:tasks/components/patient_status_chip_select.dart'; import 'package:tasks/components/task_bottom_sheet.dart'; -import 'package:tasks/controllers/ward_patients_controller.dart'; -import 'package:tasks/dataclasses/patient.dart'; -import 'package:tasks/dataclasses/task.dart'; +import 'package:helpwave_service/tasks.dart'; /// A screen for showing a all [Patient]s by certain user-selectable filter properties /// diff --git a/apps/tasks/lib/screens/settings_screen.dart b/apps/tasks/lib/screens/settings_screen.dart index 6258c1e7..e943d53b 100644 --- a/apps/tasks/lib/screens/settings_screen.dart +++ b/apps/tasks/lib/screens/settings_screen.dart @@ -1,12 +1,11 @@ import 'package:flutter/material.dart'; import 'package:helpwave_localization/localization.dart'; import 'package:helpwave_localization/localization_model.dart'; +import 'package:helpwave_service/auth.dart'; import 'package:helpwave_theme/constants.dart'; import 'package:helpwave_theme/theme.dart'; import 'package:provider/provider.dart'; import 'package:tasks/screens/login_screen.dart'; -import 'package:tasks/services/user_session_service.dart'; -import 'package:tasks/services/current_ward_svc.dart'; /// Screen for settings and other app options class SettingsScreen extends StatefulWidget { diff --git a/apps/tasks/lib/screens/ward_select_screen.dart b/apps/tasks/lib/screens/ward_select_screen.dart index f0bda449..7e7248c7 100644 --- a/apps/tasks/lib/screens/ward_select_screen.dart +++ b/apps/tasks/lib/screens/ward_select_screen.dart @@ -1,16 +1,14 @@ import 'package:flutter/material.dart'; import 'package:helpwave_localization/localization.dart'; +import 'package:helpwave_service/auth.dart'; +import 'package:helpwave_service/tasks.dart'; +import 'package:helpwave_service/user.dart'; import 'package:helpwave_theme/constants.dart'; import 'package:helpwave_widget/content_selection.dart'; import 'package:provider/provider.dart'; -import 'package:tasks/dataclasses/organization.dart'; import 'package:tasks/screens/settings_screen.dart'; -import 'package:tasks/services/current_ward_svc.dart'; -import 'package:tasks/services/organization_svc.dart'; -import 'package:tasks/services/ward_service.dart'; -import '../dataclasses/ward.dart'; -/// A Screen to select the current [Organization] and [Ward] +/// A Screen to select the current [OrganizationService] and [Ward] class WardSelectScreen extends StatefulWidget { const WardSelectScreen({super.key}); diff --git a/apps/tasks/lib/services/grpc_client_svc.dart b/apps/tasks/lib/services/grpc_client_svc.dart deleted file mode 100644 index 30278c22..00000000 --- a/apps/tasks/lib/services/grpc_client_svc.dart +++ /dev/null @@ -1,76 +0,0 @@ -import 'package:grpc/grpc.dart'; -import 'package:helpwave_proto_dart/proto/services/task_svc/v1/patient_svc.pbgrpc.dart'; -import 'package:helpwave_proto_dart/proto/services/task_svc/v1/room_svc.pbgrpc.dart'; -import 'package:helpwave_proto_dart/proto/services/task_svc/v1/task_svc.pbgrpc.dart'; -import 'package:helpwave_proto_dart/proto/services/task_svc/v1/ward_svc.pbgrpc.dart'; -import 'package:helpwave_proto_dart/proto/services/user_svc/v1/organization_svc.pbgrpc.dart'; -import 'package:helpwave_proto_dart/proto/services/user_svc/v1/user_svc.pbgrpc.dart'; -import 'package:tasks/config/config.dart'; -import 'package:tasks/services/current_ward_svc.dart'; -import 'user_session_service.dart'; - -/// The Underlying GrpcService it provides other clients and the correct metadata for the requests -class GRPCClientService { - static final taskServiceChannel = ClientChannel( - usedAPIURL, - ); - static final userServiceChannel = ClientChannel( - usedAPIURL, - ); - - final UserSessionService authService = UserSessionService(); - - Map get authMetaData { - if (authService.isLoggedIn) { - return { - "Authorization": "Bearer ${UserSessionService().identity?.idToken}", - }; - } - // Maybe throw a error instead - return {}; - } - - String? get fallbackOrganizationId => - // Maybe throw a error instead for the last case - CurrentWardService().currentWard?.organizationId ?? authService.identity?.firstOrganization; - - Map getTaskServiceMetaData({String? organizationId}) { - var metaData = { - ...authMetaData, - "dapr-app-id": "task-svc", - }; - - if (organizationId != null) { - metaData["X-Organization"] = organizationId; - } else { - metaData["X-Organization"] = fallbackOrganizationId!; - } - - return metaData; - } - - Map getUserServiceMetaData({String? organizationId}) { - var metaData = { - ...authMetaData, - "dapr-app-id": "user-svc", - }; - - if (organizationId != null) { - metaData["X-Organization"] = organizationId; - } - - return metaData; - } - - static PatientServiceClient get getPatientServiceClient => PatientServiceClient(taskServiceChannel); - - static WardServiceClient get getWardServiceClient => WardServiceClient(taskServiceChannel); - - static RoomServiceClient get getRoomServiceClient => RoomServiceClient(taskServiceChannel); - - static TaskServiceClient get getTaskServiceClient => TaskServiceClient(taskServiceChannel); - - static UserServiceClient get getUserServiceClient => UserServiceClient(userServiceChannel); - - static OrganizationServiceClient get getOrganizationServiceClient => OrganizationServiceClient(userServiceChannel); -} diff --git a/apps/tasks/lib/services/task_svc.dart b/apps/tasks/lib/services/task_svc.dart deleted file mode 100644 index 642e45f4..00000000 --- a/apps/tasks/lib/services/task_svc.dart +++ /dev/null @@ -1,197 +0,0 @@ -import 'package:grpc/grpc.dart'; -import 'package:helpwave_proto_dart/google/protobuf/timestamp.pb.dart'; -import 'package:helpwave_proto_dart/proto/services/task_svc/v1/task_svc.pbgrpc.dart'; -import 'package:tasks/dataclasses/patient.dart'; -import 'package:tasks/dataclasses/subtask.dart'; -import 'package:tasks/services/grpc_client_svc.dart'; -import 'package:tasks/util/task_status_mapping.dart'; -import '../dataclasses/task.dart'; - -/// The GRPC Service for [Task]s -/// -/// Provides queries and requests that load or alter [Task] objects on the server -/// The server is defined in the underlying [GRPCClientService] -class TaskService { - /// The GRPC ServiceClient which handles GRPC - TaskServiceClient taskService = GRPCClientService.getTaskServiceClient; - - /// Loads the [Task]s by a [Patient] identifier - Future> getTasksByPatient({String? patientId}) async { - GetTasksByPatientRequest request = GetTasksByPatientRequest(patientId: patientId); - GetTasksByPatientResponse response = await taskService.getTasksByPatient( - request, - options: CallOptions(metadata: GRPCClientService().getTaskServiceMetaData()), - ); - - return response.tasks - .map((task) => Task( - id: task.id, - name: task.name, - notes: task.description, - isPublicVisible: task.public, - status: taskStatusMappingFromProto[task.status]!, - assignee: task.assignedUserId, - dueDate: task.dueAt.toDateTime(), - subtasks: task.subtasks - .map((subtask) => SubTask( - id: subtask.id, - name: subtask.name, - isDone: subtask.done, - )) - .toList(), - )) - .toList(); - } - - /// Loads the [Task]s by it's identifier - Future getTask({String? id}) async { - GetTaskRequest request = GetTaskRequest(id: id); - GetTaskResponse response = await taskService.getTask( - request, - options: CallOptions(metadata: GRPCClientService().getTaskServiceMetaData()), - ); - - return TaskWithPatient( - id: response.id, - name: response.name, - notes: response.description, - isPublicVisible: response.public, - status: taskStatusMappingFromProto[response.status]!, - assignee: response.assignedUserId, - dueDate: response.dueAt.toDateTime(), - patient: PatientMinimal(id: response.patient.id, name: response.patient.name), - subtasks: response.subtasks - .map((subtask) => SubTask( - id: subtask.id, - name: subtask.name, - isDone: subtask.done, - )) - .toList(), - ); - } - - Future createTask(TaskWithPatient task) async { - CreateTaskRequest request = CreateTaskRequest( - name: task.name, - description: task.notes, - initialStatus: taskStatusMappingToProto[task.status], - dueAt: task.dueDate != null ? Timestamp.fromDateTime(task.dueDate!) : null, - patientId: !task.patient.isCreating ? task.patient.id : null, - public: task.isPublicVisible, - ); - CreateTaskResponse response = await taskService.createTask( - request, - options: CallOptions(metadata: GRPCClientService().getTaskServiceMetaData()), - ); - - return response.id; - } - - /// Assign a [Task] to a [User] - Future assignToUser({required String taskId, required String userId}) async { - AssignTaskToUserRequest request = AssignTaskToUserRequest(id: taskId, userId: userId); - AssignTaskToUserResponse response = await taskService.assignTaskToUser( - request, - options: CallOptions(metadata: GRPCClientService().getTaskServiceMetaData()), - ); - - if (!response.isInitialized()) { - // Handle error - } - } - - /// Add a [SubTask] to a [Task] - Future addSubTask({required String taskId, required SubTask subTask}) async { - AddSubTaskRequest request = AddSubTaskRequest( - taskId: taskId, - name: subTask.name, - done: subTask.isDone, - ); - AddSubTaskResponse response = await taskService.addSubTask( - request, - options: CallOptions(metadata: GRPCClientService().getTaskServiceMetaData()), - ); - - return SubTask( - id: response.id, - name: subTask.name, - isDone: subTask.isDone, - ); - } - - /// Delete a [SubTask] by its identifier - Future deleteSubTask({required String id}) async { - RemoveSubTaskRequest request = RemoveSubTaskRequest(id: id); - RemoveSubTaskResponse response = await taskService.removeSubTask( - request, - options: CallOptions(metadata: GRPCClientService().getTaskServiceMetaData()), - ); - - return response.isInitialized(); - } - - /// Change a [SubTask]'s status to done by its identifier - Future subtaskToDone({required String id}) async { - SubTaskToDoneRequest request = SubTaskToDoneRequest(id: id); - SubTaskToDoneResponse response = await taskService.subTaskToDone( - request, - options: CallOptions(metadata: GRPCClientService().getTaskServiceMetaData()), - ); - - return response.isInitialized(); - } - - /// Change a [SubTask]'s status to todo by its identifier - Future subtaskToToDo({required String id}) async { - SubTaskToToDoRequest request = SubTaskToToDoRequest(id: id); - SubTaskToToDoResponse response = await taskService.subTaskToToDo( - request, - options: CallOptions(metadata: GRPCClientService().getTaskServiceMetaData()), - ); - - return response.isInitialized(); - } - - /// Change a [SubTask]'s status by its identifier - Future changeSubtaskStatus({ - required String id, - required isDone, - }) async { - if (isDone) { - return subtaskToDone(id: id); - } else { - return subtaskToToDo(id: id); - } - } - - /// Update a [SubTask]'s - Future updateSubTask({required SubTask subTask}) async { - UpdateSubTaskRequest request = UpdateSubTaskRequest( - id: subTask.id, - name: subTask.name, - ); - UpdateSubTaskResponse response = await taskService.updateSubTask( - request, - options: CallOptions(metadata: GRPCClientService().getTaskServiceMetaData()), - ); - - return response.isInitialized(); - } - - Future updateTask(Task task) async { - UpdateTaskRequest request = UpdateTaskRequest( - id: task.id, - name: task.name, - description: task.notes, - dueAt: task.dueDate != null ? Timestamp.fromDateTime(task.dueDate!) : null, - public: task.isPublicVisible, - ); - - UpdateTaskResponse response = await taskService.updateTask( - request, - options: CallOptions(metadata: GRPCClientService().getTaskServiceMetaData()), - ); - - return response.isInitialized(); - } -} diff --git a/apps/tasks/lib/util/task_status_mapping.dart b/apps/tasks/lib/util/task_status_mapping.dart deleted file mode 100644 index 6ee32cdf..00000000 --- a/apps/tasks/lib/util/task_status_mapping.dart +++ /dev/null @@ -1,16 +0,0 @@ -import 'package:tasks/dataclasses/task.dart' as task_lib; -import 'package:helpwave_proto_dart/proto/services/task_svc/v1/task_svc.pbenum.dart' as proto; - -Map taskStatusMappingFromProto = { - proto.TaskStatus.TASK_STATUS_TODO: task_lib.TaskStatus.todo, - proto.TaskStatus.TASK_STATUS_IN_PROGRESS: task_lib.TaskStatus.inProgress, - proto.TaskStatus.TASK_STATUS_DONE: task_lib.TaskStatus.done, - proto.TaskStatus.TASK_STATUS_UNSPECIFIED: task_lib.TaskStatus.unspecified, -}; - -Map taskStatusMappingToProto = { - task_lib.TaskStatus.todo: proto.TaskStatus.TASK_STATUS_TODO, - task_lib.TaskStatus.inProgress: proto.TaskStatus.TASK_STATUS_IN_PROGRESS, - task_lib.TaskStatus.done: proto.TaskStatus.TASK_STATUS_DONE, - task_lib.TaskStatus.unspecified: proto.TaskStatus.TASK_STATUS_UNSPECIFIED, -}; diff --git a/apps/tasks/pubspec.lock b/apps/tasks/pubspec.lock index fa0366a5..bbc15e5d 100644 --- a/apps/tasks/pubspec.lock +++ b/apps/tasks/pubspec.lock @@ -254,7 +254,7 @@ packages: source: hosted version: "1.4.1" grpc: - dependency: "direct main" + dependency: transitive description: name: grpc sha256: e93ee3bce45c134bf44e9728119102358c7cd69de7832d9a874e2e74eb8cab40 @@ -269,13 +269,13 @@ packages: source: path version: "0.0.1" helpwave_proto_dart: - dependency: "direct main" + dependency: transitive description: name: helpwave_proto_dart - sha256: "60e912fcb781e16b9b5bd6b5c27585d9481ae554be2bfc2e58c76dcfa4735d60" + sha256: "4d4b2b6d0129c7c1b678164688e2bd0a99029cc178794fd655e7c4e7aa505d58" url: "https://pub.dev" source: hosted - version: "0.39.0-aa8fd45" + version: "0.46.0-336429a" helpwave_service: dependency: "direct main" description: @@ -291,7 +291,7 @@ packages: source: path version: "0.0.1" helpwave_util: - dependency: "direct overridden" + dependency: "direct main" description: path: "../../packages/helpwave_util" relative: true @@ -376,30 +376,6 @@ packages: url: "https://pub.dev" source: hosted version: "4.8.1" - leak_tracker: - dependency: transitive - description: - name: leak_tracker - sha256: "78eb209deea09858f5269f5a5b02be4049535f568c07b275096836f01ea323fa" - url: "https://pub.dev" - source: hosted - version: "10.0.0" - leak_tracker_flutter_testing: - dependency: transitive - description: - name: leak_tracker_flutter_testing - sha256: b46c5e37c19120a8a01918cfaf293547f47269f7cb4b0058f21531c2465d6ef0 - url: "https://pub.dev" - source: hosted - version: "2.0.1" - leak_tracker_testing: - dependency: transitive - description: - name: leak_tracker_testing - sha256: a597f72a664dbd293f3bfc51f9ba69816f84dcd403cdac7066cb3f6003f3ab47 - url: "https://pub.dev" - source: hosted - version: "2.0.1" lints: dependency: transitive description: @@ -428,26 +404,26 @@ packages: dependency: transitive description: name: matcher - sha256: d2323aa2060500f906aa31a895b4030b6da3ebdcc5619d14ce1aada65cd161cb + sha256: "1803e76e6653768d64ed8ff2e1e67bea3ad4b923eb5c56a295c3e634bad5960e" url: "https://pub.dev" source: hosted - version: "0.12.16+1" + version: "0.12.16" material_color_utilities: dependency: transitive description: name: material_color_utilities - sha256: "0e0a020085b65b6083975e499759762399b4475f766c21668c4ecca34ea74e5a" + sha256: "9528f2f296073ff54cb9fee677df673ace1218163c3bc7628093e7eed5203d41" url: "https://pub.dev" source: hosted - version: "0.8.0" + version: "0.5.0" meta: dependency: transitive description: name: meta - sha256: d584fa6707a52763a52446f02cc621b077888fb63b93bbcb1143a7be5a0c0c04 + sha256: a6e590c838b18133bb482a2745ad77c5bb7715fb0451209e1a7567d416678b8e url: "https://pub.dev" source: hosted - version: "1.11.0" + version: "1.10.0" nested: dependency: transitive description: @@ -468,10 +444,10 @@ packages: dependency: transitive description: name: path - sha256: "087ce49c3f0dc39180befefc60fdb4acd8f8620e5682fe2476afd0b3688bb4af" + sha256: "8829d8a55c13fc0e37127c29fedf290c102f4e40ae94ada574091fe0ff96c917" url: "https://pub.dev" source: hosted - version: "1.9.0" + version: "1.8.3" path_provider: dependency: transitive description: @@ -773,14 +749,14 @@ packages: url: "https://pub.dev" source: hosted version: "2.1.4" - vm_service: + web: dependency: transitive description: - name: vm_service - sha256: b3d56ff4341b8f182b96aceb2fa20e3dcb336b9f867bc0eafc0de10f1048e957 + name: web + sha256: afe077240a270dcfd2aafe77602b4113645af95d0ad31128cc02bce5ac5d5152 url: "https://pub.dev" source: hosted - version: "13.0.0" + version: "0.3.0" win32: dependency: transitive description: @@ -822,5 +798,5 @@ packages: source: hosted version: "3.1.2" sdks: - dart: ">=3.2.0-0 <4.0.0" + dart: ">=3.2.0-194.0.dev <4.0.0" flutter: ">=3.16.0" diff --git a/apps/tasks/pubspec.yaml b/apps/tasks/pubspec.yaml index 068c883b..032d9e18 100644 --- a/apps/tasks/pubspec.yaml +++ b/apps/tasks/pubspec.yaml @@ -45,8 +45,8 @@ dependencies: path: "../../packages/helpwave_widget" helpwave_service: path: "../../packages/helpwave_service" - helpwave_proto_dart: ^0.39.0-aa8fd45 - grpc: ^3.2.4 + helpwave_util: + path: "../../packages/helpwave_util" shared_preferences: ^2.0.15 logger: ^2.0.2+1 diff --git a/packages/helpwave_service/lib/auth.dart b/packages/helpwave_service/lib/auth.dart index cba87fbb..497562fd 100644 --- a/packages/helpwave_service/lib/auth.dart +++ b/packages/helpwave_service/lib/auth.dart @@ -1,4 +1 @@ -export 'package:helpwave_service/src/auth/authentication_service.dart' - show AuthenticationService; - -export 'package:helpwave_service/src/auth/identity.dart'; +export 'package:helpwave_service/src/auth/index.dart'; diff --git a/apps/tasks/lib/controllers/assignee_select_controller.dart b/packages/helpwave_service/lib/src/api/tasks/controllers/assignee_select_controller.dart similarity index 86% rename from apps/tasks/lib/controllers/assignee_select_controller.dart rename to packages/helpwave_service/lib/src/api/tasks/controllers/assignee_select_controller.dart index 19d3c5d5..a8fd4fed 100644 --- a/apps/tasks/lib/controllers/assignee_select_controller.dart +++ b/packages/helpwave_service/lib/src/api/tasks/controllers/assignee_select_controller.dart @@ -1,11 +1,9 @@ import 'package:flutter/foundation.dart'; -import 'package:helpwave_widget/loading.dart'; +import 'package:helpwave_service/auth.dart'; +import 'package:helpwave_service/src/api/user/index.dart'; +import 'package:helpwave_util/loading_state.dart'; import 'package:logger/logger.dart'; -import 'package:tasks/dataclasses/task.dart'; -import 'package:tasks/services/current_ward_svc.dart'; -import 'package:tasks/services/organization_svc.dart'; -import 'package:tasks/services/task_svc.dart'; -import '../dataclasses/user.dart'; +import 'package:helpwave_service/tasks.dart'; /// The Controller for selecting a [User] as the assignee of a [Task] class AssigneeSelectController extends ChangeNotifier { diff --git a/packages/helpwave_service/lib/src/api/tasks/controllers/index.dart b/packages/helpwave_service/lib/src/api/tasks/controllers/index.dart new file mode 100644 index 00000000..a987ab71 --- /dev/null +++ b/packages/helpwave_service/lib/src/api/tasks/controllers/index.dart @@ -0,0 +1,6 @@ +export 'patient_controller.dart'; +export 'subtask_list_controller.dart'; +export 'task_controller.dart'; +export 'assignee_select_controller.dart'; +export 'my_tasks_controller.dart'; +export 'ward_patients_controller.dart'; diff --git a/apps/tasks/lib/controllers/my_tasks_controller.dart b/packages/helpwave_service/lib/src/api/tasks/controllers/my_tasks_controller.dart similarity index 81% rename from apps/tasks/lib/controllers/my_tasks_controller.dart rename to packages/helpwave_service/lib/src/api/tasks/controllers/my_tasks_controller.dart index 1513c18a..c353476a 100644 --- a/apps/tasks/lib/controllers/my_tasks_controller.dart +++ b/packages/helpwave_service/lib/src/api/tasks/controllers/my_tasks_controller.dart @@ -1,11 +1,6 @@ import 'package:flutter/cupertino.dart'; -import 'package:helpwave_widget/loading.dart'; -import 'package:tasks/dataclasses/task.dart'; -import 'package:tasks/services/current_ward_svc.dart'; -import 'package:tasks/services/patient_svc.dart'; -import 'package:tasks/services/task_svc.dart'; - -import '../dataclasses/patient.dart'; +import 'package:helpwave_service/tasks.dart'; +import 'package:helpwave_util/loading_state.dart'; /// The Controller for [Task]s of the current [User] class MyTasksController extends ChangeNotifier { @@ -38,7 +33,7 @@ class MyTasksController extends ChangeNotifier { notifyListeners(); } - var patients = await PatientService().getPatientList(wardId: CurrentWardService().currentWard?.wardId); + var patients = await PatientService().getPatientList(); ListallPatients = patients.all; _tasks = []; diff --git a/apps/tasks/lib/controllers/patient_controller.dart b/packages/helpwave_service/lib/src/api/tasks/controllers/patient_controller.dart similarity index 95% rename from apps/tasks/lib/controllers/patient_controller.dart rename to packages/helpwave_service/lib/src/api/tasks/controllers/patient_controller.dart index bf47e763..95daca37 100644 --- a/apps/tasks/lib/controllers/patient_controller.dart +++ b/packages/helpwave_service/lib/src/api/tasks/controllers/patient_controller.dart @@ -1,9 +1,6 @@ import 'package:flutter/material.dart'; -import 'package:helpwave_widget/loading.dart'; -import 'package:tasks/services/patient_svc.dart'; -import '../dataclasses/bed.dart'; -import '../dataclasses/patient.dart'; -import '../dataclasses/room.dart'; +import 'package:helpwave_util/loading_state.dart'; +import 'package:helpwave_service/src/api/tasks/index.dart'; /// The Controller for managing [Patient]s in a Ward class PatientController extends ChangeNotifier { diff --git a/apps/tasks/lib/controllers/subtask_list_controller.dart b/packages/helpwave_service/lib/src/api/tasks/controllers/subtask_list_controller.dart similarity index 66% rename from apps/tasks/lib/controllers/subtask_list_controller.dart rename to packages/helpwave_service/lib/src/api/tasks/controllers/subtask_list_controller.dart index 66620456..f11402f2 100644 --- a/apps/tasks/lib/controllers/subtask_list_controller.dart +++ b/packages/helpwave_service/lib/src/api/tasks/controllers/subtask_list_controller.dart @@ -1,12 +1,11 @@ import 'dart:async'; import 'package:flutter/cupertino.dart'; -import 'package:helpwave_widget/loading.dart'; -import 'package:tasks/dataclasses/subtask.dart'; -import 'package:tasks/services/task_svc.dart'; +import 'package:helpwave_service/src/api/tasks/index.dart'; +import 'package:helpwave_util/loading_state.dart'; /// The Controller for managing [Subtask]s in a [Task] /// -/// Providing a [taskId] means loading and synchronising the [SubTask]s with +/// Providing a [taskId] means loading and synchronising the [Subtask]s with /// the backend while no [taskId] or a empty [String] means that the subtasks /// only used locally class SubtasksController extends ChangeNotifier { @@ -21,11 +20,11 @@ class SubtasksController extends ChangeNotifier { } /// The [Subtask]s - List _subtasks = []; + List _subtasks = []; - List get subtasks => [..._subtasks]; + List get subtasks => [..._subtasks]; - set subtasks(List value) { + set subtasks(List value) { _subtasks = value; notifyListeners(); } @@ -39,7 +38,7 @@ class SubtasksController extends ChangeNotifier { /// Only valid in case [state] == [LoadingState.error] String errorMessage = ""; - SubtasksController({this.taskId = "", List? subtasks}) { + SubtasksController({this.taskId = "", List? subtasks}) { _isCreating = taskId == ""; if (!isCreating) { load(); @@ -64,7 +63,7 @@ class SubtasksController extends ChangeNotifier { state = LoadingState.loaded; } - /// Delete the subtask by the index + /// Delete the subtask by the index.dart Future deleteByIndex(int index) async { if (index < 0 || index >= subtasks.length) { return; @@ -75,7 +74,7 @@ class SubtasksController extends ChangeNotifier { return; } state = LoadingState.loading; - await TaskService().deleteSubTask(id: subtasks[index].id).then((value) { + await TaskService().deleteSubTask(subtaskId: subtasks[index].id, taskId: taskId).then((value) { if (value) { _subtasks.removeAt(index); state = LoadingState.loaded; @@ -87,7 +86,7 @@ class SubtasksController extends ChangeNotifier { }); } - /// Delete the [SubTask] by the id + /// Delete the [Subtask] by the id Future delete(String id) async { assert(!isCreating, "delete should not be used when creating a completely new SubTask list"); int index = _subtasks.indexWhere((element) => element.id == id); @@ -96,14 +95,14 @@ class SubtasksController extends ChangeNotifier { } } - /// Add the [SubTask] - Future add(SubTask subTask) async { + /// Add the [Subtask] + Future add(Subtask subTask) async { if (isCreating) { _subtasks.add(subTask); notifyListeners(); return; } - await TaskService().addSubTask(taskId: taskId, subTask: subTask).then((value) { + await TaskService().createSubTask(taskId: taskId, subTask: subTask).then((value) { _subtasks.add(value); state = LoadingState.loaded; }).catchError((error, stackTrace) { @@ -113,27 +112,10 @@ class SubtasksController extends ChangeNotifier { }); } - Future changeStatus({required SubTask subTask, required bool value}) async { - if (subTask.isCreating) { - subTask.isDone = value; - } else { - state = LoadingState.loading; - await TaskService().changeSubtaskStatus(id: subTask.id, isDone: value).then((value) { - subTask.isDone = value; - state = LoadingState.loaded; - }).catchError((error, stackTrace) { - errorMessage = error.toString(); - state = LoadingState.error; - return null; - }); - } - notifyListeners(); - } - - Future updateSubtask({required SubTask subTask}) async { + Future updateSubtask({required Subtask subTask}) async { if (!subTask.isCreating) { state = LoadingState.loading; - await TaskService().updateSubTask(subTask: subTask).then((value) { + await TaskService().updateSubtask(subtask: subTask, taskId: taskId).then((value) { state = LoadingState.loaded; }).catchError((error, stackTrace) { // Just reload in case of an error diff --git a/apps/tasks/lib/controllers/task_controller.dart b/packages/helpwave_service/lib/src/api/tasks/controllers/task_controller.dart similarity index 96% rename from apps/tasks/lib/controllers/task_controller.dart rename to packages/helpwave_service/lib/src/api/tasks/controllers/task_controller.dart index 917961fe..f12f77f9 100644 --- a/apps/tasks/lib/controllers/task_controller.dart +++ b/packages/helpwave_service/lib/src/api/tasks/controllers/task_controller.dart @@ -1,8 +1,6 @@ import 'package:flutter/material.dart'; -import 'package:helpwave_widget/loading.dart'; -import '../dataclasses/patient.dart'; -import '../dataclasses/task.dart'; -import '../services/task_svc.dart'; +import 'package:helpwave_util/loading_state.dart'; +import 'package:helpwave_service/src/api/tasks/index.dart'; /// The Controller for managing a [TaskWithPatient] class TaskController extends ChangeNotifier { diff --git a/apps/tasks/lib/controllers/ward_patients_controller.dart b/packages/helpwave_service/lib/src/api/tasks/controllers/ward_patients_controller.dart similarity index 86% rename from apps/tasks/lib/controllers/ward_patients_controller.dart rename to packages/helpwave_service/lib/src/api/tasks/controllers/ward_patients_controller.dart index e0edea42..e18d4d01 100644 --- a/apps/tasks/lib/controllers/ward_patients_controller.dart +++ b/packages/helpwave_service/lib/src/api/tasks/controllers/ward_patients_controller.dart @@ -1,9 +1,7 @@ import 'package:flutter/cupertino.dart'; -import 'package:helpwave_widget/loading.dart'; -import 'package:tasks/dataclasses/patient.dart'; -import 'package:tasks/services/current_ward_svc.dart'; -import 'package:tasks/services/patient_svc.dart'; -import 'package:tasks/util/search_helpers.dart'; +import 'package:helpwave_service/src/api/tasks/index.dart'; +import 'package:helpwave_util/loading_state.dart'; +import 'package:helpwave_util/search.dart'; /// The Controller for managing [Patient]s in a Ward class WardPatientsController extends ChangeNotifier { @@ -77,8 +75,7 @@ class WardPatientsController extends ChangeNotifier { state = LoadingState.loading; notifyListeners(); - _patientsByAssignmentStatus = - await PatientService().getPatientList(wardId: CurrentWardService().currentWard?.wardId); + _patientsByAssignmentStatus = await PatientService().getPatientList(); state = LoadingState.loaded; notifyListeners(); } diff --git a/apps/tasks/lib/dataclasses/bed.dart b/packages/helpwave_service/lib/src/api/tasks/data_types/bed.dart similarity index 84% rename from apps/tasks/lib/dataclasses/bed.dart rename to packages/helpwave_service/lib/src/api/tasks/data_types/bed.dart index df7d3a89..a988a270 100644 --- a/apps/tasks/lib/dataclasses/bed.dart +++ b/packages/helpwave_service/lib/src/api/tasks/data_types/bed.dart @@ -1,4 +1,4 @@ -import 'package:tasks/dataclasses/patient.dart'; +import 'package:helpwave_service/src/api/tasks/index.dart'; /// data class for [Bed] class BedMinimal { diff --git a/packages/helpwave_service/lib/src/api/tasks/data_types/index.dart b/packages/helpwave_service/lib/src/api/tasks/data_types/index.dart new file mode 100644 index 00000000..7b1fe9cc --- /dev/null +++ b/packages/helpwave_service/lib/src/api/tasks/data_types/index.dart @@ -0,0 +1,8 @@ +export 'ward.dart'; +export 'room.dart'; +export 'bed.dart'; +export 'patient.dart'; +export 'task.dart'; +export 'subtask.dart'; +export 'task_template.dart'; +export 'task_template_subtask.dart'; diff --git a/apps/tasks/lib/dataclasses/patient.dart b/packages/helpwave_service/lib/src/api/tasks/data_types/patient.dart similarity index 94% rename from apps/tasks/lib/dataclasses/patient.dart rename to packages/helpwave_service/lib/src/api/tasks/data_types/patient.dart index 31baa719..0942256b 100644 --- a/apps/tasks/lib/dataclasses/patient.dart +++ b/packages/helpwave_service/lib/src/api/tasks/data_types/patient.dart @@ -1,6 +1,4 @@ -import 'package:tasks/dataclasses/bed.dart'; -import 'package:tasks/dataclasses/room.dart'; -import 'package:tasks/dataclasses/task.dart'; +import 'package:helpwave_service/src/api/tasks/index.dart'; enum PatientAssignmentStatus { active, unassigned, discharged, all } diff --git a/apps/tasks/lib/dataclasses/room.dart b/packages/helpwave_service/lib/src/api/tasks/data_types/room.dart similarity index 94% rename from apps/tasks/lib/dataclasses/room.dart rename to packages/helpwave_service/lib/src/api/tasks/data_types/room.dart index 06775428..632ca7a1 100644 --- a/apps/tasks/lib/dataclasses/room.dart +++ b/packages/helpwave_service/lib/src/api/tasks/data_types/room.dart @@ -1,4 +1,4 @@ -import 'package:tasks/dataclasses/bed.dart'; +import 'package:helpwave_service/src/api/tasks/data_types/bed.dart'; /// data class for [Room] class RoomMinimal { diff --git a/packages/helpwave_service/lib/src/api/tasks/data_types/subtask.dart b/packages/helpwave_service/lib/src/api/tasks/data_types/subtask.dart new file mode 100644 index 00000000..f81a31dd --- /dev/null +++ b/packages/helpwave_service/lib/src/api/tasks/data_types/subtask.dart @@ -0,0 +1,27 @@ +/// Data class for a [Subtask] +class Subtask { + String id; + String name; + bool isDone; + + bool get isCreating => id == ""; + + Subtask({ + required this.id, + required this.name, + this.isDone = false + }); + + /// Create a copy of the [Subtask] + Subtask copyWith({ + String? id, + String? name, + bool? isDone, + }) { + return Subtask( + id: id ?? this.id, + name: name ?? this.name, + isDone: isDone ?? this.isDone, + ); + } +} diff --git a/apps/tasks/lib/dataclasses/task.dart b/packages/helpwave_service/lib/src/api/tasks/data_types/task.dart similarity index 93% rename from apps/tasks/lib/dataclasses/task.dart rename to packages/helpwave_service/lib/src/api/tasks/data_types/task.dart index b1633960..370ff4b2 100644 --- a/apps/tasks/lib/dataclasses/task.dart +++ b/packages/helpwave_service/lib/src/api/tasks/data_types/task.dart @@ -1,6 +1,6 @@ // TODO delete later and import from protobufs -import 'package:tasks/dataclasses/patient.dart'; -import 'package:tasks/dataclasses/subtask.dart'; +import 'package:helpwave_service/src/api/tasks/data_types/patient.dart'; +import 'package:helpwave_service/src/api/tasks/data_types/subtask.dart'; enum TaskStatus { unspecified, @@ -16,7 +16,7 @@ class Task { String? assignee; String notes; TaskStatus status; - List subtasks; + List subtasks; DateTime? dueDate; DateTime? creationDate; bool isPublicVisible; diff --git a/apps/tasks/lib/dataclasses/task_template.dart b/packages/helpwave_service/lib/src/api/tasks/data_types/task_template.dart similarity index 86% rename from apps/tasks/lib/dataclasses/task_template.dart rename to packages/helpwave_service/lib/src/api/tasks/data_types/task_template.dart index 35309363..8c61a31c 100644 --- a/apps/tasks/lib/dataclasses/task_template.dart +++ b/packages/helpwave_service/lib/src/api/tasks/data_types/task_template.dart @@ -1,4 +1,4 @@ -import 'package:tasks/dataclasses/task_template_subtask.dart'; +import '../index.dart'; /// data class for [TaskTemplate] class TaskTemplate { diff --git a/apps/tasks/lib/dataclasses/task_template_subtask.dart b/packages/helpwave_service/lib/src/api/tasks/data_types/task_template_subtask.dart similarity index 100% rename from apps/tasks/lib/dataclasses/task_template_subtask.dart rename to packages/helpwave_service/lib/src/api/tasks/data_types/task_template_subtask.dart diff --git a/apps/tasks/lib/dataclasses/ward.dart b/packages/helpwave_service/lib/src/api/tasks/data_types/ward.dart similarity index 100% rename from apps/tasks/lib/dataclasses/ward.dart rename to packages/helpwave_service/lib/src/api/tasks/data_types/ward.dart diff --git a/packages/helpwave_service/lib/src/api/tasks/index.dart b/packages/helpwave_service/lib/src/api/tasks/index.dart new file mode 100644 index 00000000..bebaf463 --- /dev/null +++ b/packages/helpwave_service/lib/src/api/tasks/index.dart @@ -0,0 +1,4 @@ +export 'data_types/index.dart'; +export 'services/index.dart'; +export 'controllers/index.dart'; +export 'tasks_api_services.dart'; diff --git a/packages/helpwave_service/lib/src/api/tasks/services/bed_svc.dart b/packages/helpwave_service/lib/src/api/tasks/services/bed_svc.dart new file mode 100644 index 00000000..e69de29b diff --git a/packages/helpwave_service/lib/src/api/tasks/services/index.dart b/packages/helpwave_service/lib/src/api/tasks/services/index.dart new file mode 100644 index 00000000..78922c72 --- /dev/null +++ b/packages/helpwave_service/lib/src/api/tasks/services/index.dart @@ -0,0 +1,5 @@ +export 'ward_service.dart'; +export 'room_svc.dart'; +export 'bed_svc.dart'; +export 'patient_svc.dart'; +export 'task_svc.dart'; diff --git a/apps/tasks/lib/services/patient_svc.dart b/packages/helpwave_service/lib/src/api/tasks/services/patient_svc.dart similarity index 77% rename from apps/tasks/lib/services/patient_svc.dart rename to packages/helpwave_service/lib/src/api/tasks/services/patient_svc.dart index c0c9ede6..c0c60d94 100644 --- a/apps/tasks/lib/services/patient_svc.dart +++ b/packages/helpwave_service/lib/src/api/tasks/services/patient_svc.dart @@ -1,21 +1,16 @@ import 'package:grpc/grpc.dart'; -import 'package:helpwave_proto_dart/proto/services/task_svc/v1/patient_svc.pbgrpc.dart'; -import 'package:tasks/dataclasses/bed.dart'; -import 'package:tasks/dataclasses/patient.dart'; -import 'package:tasks/dataclasses/room.dart'; -import 'package:tasks/dataclasses/subtask.dart'; -import 'package:tasks/dataclasses/ward.dart'; -import 'package:tasks/services/grpc_client_svc.dart'; +import 'package:helpwave_proto_dart/services/tasks_svc/v1/patient_svc.pbgrpc.dart'; +import 'package:helpwave_service/src/api/tasks/index.dart'; +import 'package:helpwave_service/src/api/tasks/util/task_status_mapping.dart'; -import '../dataclasses/task.dart'; /// The GRPC Service for [Patient]s /// /// Provides queries and requests that load or alter [Patient] objects on the server -/// The server is defined in the underlying [GRPCClientService] +/// The server is defined in the underlying [TasksAPIServices] class PatientService { /// The GRPC ServiceClient which handles GRPC - PatientServiceClient patientService = GRPCClientService.getPatientServiceClient; + PatientServiceClient patientService = TasksAPIServices.patientServiceClient; // TODO consider an enum instead of an string /// Loads the [Patient]s by [Ward] and sorts them by their assignment status @@ -24,17 +19,10 @@ class PatientService { GetPatientListResponse response = await patientService.getPatientList( request, options: CallOptions( - metadata: GRPCClientService().getTaskServiceMetaData(), + metadata: TasksAPIServices().getMetaData(), ), ); - Map taskStatusMapping = { - GetPatientListResponse_TaskStatus.TASK_STATUS_TODO: TaskStatus.todo, - GetPatientListResponse_TaskStatus.TASK_STATUS_IN_PROGRESS: TaskStatus.inProgress, - GetPatientListResponse_TaskStatus.TASK_STATUS_DONE: TaskStatus.done, - GetPatientListResponse_TaskStatus.TASK_STATUS_UNSPECIFIED: TaskStatus.unspecified, - }; - List active = response.active .map( (patient) => Patient( @@ -46,11 +34,11 @@ class PatientService { id: task.id, name: task.name, notes: task.description, - status: taskStatusMapping[task.status]!, + status: GRPCTypeConverter.taskStatusFromGRPC(task.status), isPublicVisible: task.public, assignee: task.assignedUserId, subtasks: task.subtasks - .map((subtask) => SubTask( + .map((subtask) => Subtask( id: subtask.id, name: subtask.name, isDone: subtask.done, @@ -77,11 +65,11 @@ class PatientService { id: task.id, name: task.name, notes: task.description, - status: taskStatusMapping[task.status]!, + status: GRPCTypeConverter.taskStatusFromGRPC(task.status), isPublicVisible: task.public, assignee: task.assignedUserId, subtasks: task.subtasks - .map((subtask) => SubTask( + .map((subtask) => Subtask( id: subtask.id, name: subtask.name, isDone: subtask.done, @@ -106,11 +94,11 @@ class PatientService { id: task.id, name: task.name, notes: task.description, - status: taskStatusMapping[task.status]!, + status: GRPCTypeConverter.taskStatusFromGRPC(task.status), isPublicVisible: task.public, assignee: task.assignedUserId, subtasks: task.subtasks - .map((subtask) => SubTask( + .map((subtask) => Subtask( id: subtask.id, name: subtask.name, isDone: subtask.done, @@ -138,7 +126,7 @@ class PatientService { GetPatientResponse response = await patientService.getPatient( request, options: CallOptions( - metadata: GRPCClientService().getTaskServiceMetaData(), + metadata: TasksAPIServices().getMetaData(), ), ); @@ -155,17 +143,10 @@ class PatientService { GetPatientDetailsResponse response = await patientService.getPatientDetails( request, options: CallOptions( - metadata: GRPCClientService().getTaskServiceMetaData(), + metadata: TasksAPIServices().getMetaData(), ), ); - Map statusMap = { - GetPatientDetailsResponse_TaskStatus.TASK_STATUS_TODO: TaskStatus.todo, - GetPatientDetailsResponse_TaskStatus.TASK_STATUS_IN_PROGRESS: TaskStatus.inProgress, - GetPatientDetailsResponse_TaskStatus.TASK_STATUS_DONE: TaskStatus.done, - GetPatientDetailsResponse_TaskStatus.TASK_STATUS_UNSPECIFIED: TaskStatus.unspecified, - }; - return Patient( id: response.id, name: response.humanReadableIdentifier, @@ -177,10 +158,10 @@ class PatientService { name: task.name, notes: task.description, assignee: task.assignedUserId, - status: statusMap[task.status]!, + status: GRPCTypeConverter.taskStatusFromGRPC(task.status), isPublicVisible: task.public, subtasks: task.subtasks - .map((subtask) => SubTask( + .map((subtask) => Subtask( id: subtask.id, name: subtask.name, )) @@ -198,7 +179,7 @@ class PatientService { GetPatientAssignmentByWardResponse response = await patientService.getPatientAssignmentByWard( request, options: CallOptions( - metadata: GRPCClientService().getTaskServiceMetaData(), + metadata: TasksAPIServices().getMetaData(), ), ); @@ -226,7 +207,7 @@ class PatientService { ); CreatePatientResponse response = await patientService.createPatient( request, - options: CallOptions(metadata: GRPCClientService().getTaskServiceMetaData()), + options: CallOptions(metadata: TasksAPIServices().getMetaData()), ); return response.id; @@ -241,7 +222,7 @@ class PatientService { ); UpdatePatientResponse response = await patientService.updatePatient( request, - options: CallOptions(metadata: GRPCClientService().getTaskServiceMetaData()), + options: CallOptions(metadata: TasksAPIServices().getMetaData()), ); if (response.isInitialized()) { @@ -256,7 +237,7 @@ class PatientService { DischargePatientRequest request = DischargePatientRequest(id: patientId); DischargePatientResponse response = await patientService.dischargePatient( request, - options: CallOptions(metadata: GRPCClientService().getTaskServiceMetaData()), + options: CallOptions(metadata: TasksAPIServices().getMetaData()), ); if (response.isInitialized()) { @@ -270,7 +251,7 @@ class PatientService { UnassignBedRequest request = UnassignBedRequest(id: patientId); UnassignBedResponse response = await patientService.unassignBed( request, - options: CallOptions(metadata: GRPCClientService().getTaskServiceMetaData()), + options: CallOptions(metadata: TasksAPIServices().getMetaData()), ); if (response.isInitialized()) { @@ -284,7 +265,7 @@ class PatientService { AssignBedRequest request = AssignBedRequest(id: patientId, bedId: bedId); AssignBedResponse response = await patientService.assignBed( request, - options: CallOptions(metadata: GRPCClientService().getTaskServiceMetaData()), + options: CallOptions(metadata: TasksAPIServices().getMetaData()), ); if (response.isInitialized()) { diff --git a/apps/tasks/lib/services/room_svc.dart b/packages/helpwave_service/lib/src/api/tasks/services/room_svc.dart similarity index 72% rename from apps/tasks/lib/services/room_svc.dart rename to packages/helpwave_service/lib/src/api/tasks/services/room_svc.dart index 48400564..ca4f3d3b 100644 --- a/apps/tasks/lib/services/room_svc.dart +++ b/packages/helpwave_service/lib/src/api/tasks/services/room_svc.dart @@ -1,23 +1,21 @@ import 'package:grpc/grpc.dart'; -import 'package:helpwave_proto_dart/proto/services/task_svc/v1/room_svc.pbgrpc.dart'; -import 'package:tasks/dataclasses/bed.dart'; -import 'package:tasks/dataclasses/patient.dart'; -import 'package:tasks/dataclasses/room.dart'; -import 'package:tasks/services/grpc_client_svc.dart'; +import 'package:helpwave_proto_dart/services/tasks_svc/v1/room_svc.pbgrpc.dart'; +import 'package:helpwave_service/src/api/tasks/data_types/index.dart'; +import 'package:helpwave_service/src/api/tasks/tasks_api_services.dart'; /// The GRPC Service for [Room]s /// /// Provides queries and requests that load or alter [Room] objects on the server -/// The server is defined in the underlying [GRPCClientService] +/// The server is defined in the underlying [TasksAPIServices] class RoomService { /// The GRPC ServiceClient which handles GRPC - RoomServiceClient roomService = GRPCClientService.getRoomServiceClient; + RoomServiceClient roomService = TasksAPIServices.roomServiceClient; Future> getRoomOverviews({required String wardId}) async { GetRoomOverviewsByWardRequest request = GetRoomOverviewsByWardRequest(id: wardId); GetRoomOverviewsByWardResponse response = await roomService.getRoomOverviewsByWard( request, - options: CallOptions(metadata: GRPCClientService().getTaskServiceMetaData()), + options: CallOptions(metadata: TasksAPIServices().getMetaData()), ); List rooms = response.rooms diff --git a/packages/helpwave_service/lib/src/api/tasks/services/task_svc.dart b/packages/helpwave_service/lib/src/api/tasks/services/task_svc.dart new file mode 100644 index 00000000..3d2cf292 --- /dev/null +++ b/packages/helpwave_service/lib/src/api/tasks/services/task_svc.dart @@ -0,0 +1,163 @@ +import 'package:grpc/grpc.dart'; +import 'package:helpwave_proto_dart/google/protobuf/timestamp.pb.dart'; +import 'package:helpwave_service/src/api/tasks/index.dart'; +import 'package:helpwave_proto_dart/services/tasks_svc/v1/task_svc.pbgrpc.dart'; +import '../util/task_status_mapping.dart'; + +/// The GRPC Service for [Task]s +/// +/// Provides queries and requests that load or alter [Task] objects on the server +/// The server is defined in the underlying [TasksAPIServices] +class TaskService { + /// The GRPC ServiceClient which handles GRPC + TaskServiceClient taskService = TasksAPIServices.taskServiceClient; + + /// Loads the [Task]s by a [Patient] identifier + Future> getTasksByPatient({String? patientId}) async { + GetTasksByPatientRequest request = GetTasksByPatientRequest(patientId: patientId); + GetTasksByPatientResponse response = await taskService.getTasksByPatient( + request, + options: CallOptions(metadata: TasksAPIServices().getMetaData()), + ); + + return response.tasks + .map((task) => Task( + id: task.id, + name: task.name, + notes: task.description, + isPublicVisible: task.public, + status: GRPCTypeConverter.taskStatusFromGRPC(task.status), + assignee: task.assignedUserId, + dueDate: task.dueAt.toDateTime(), + subtasks: task.subtasks + .map((subtask) => Subtask( + id: subtask.id, + name: subtask.name, + isDone: subtask.done, + )) + .toList(), + )) + .toList(); + } + + /// Loads the [Task]s by it's identifier + Future getTask({String? id}) async { + GetTaskRequest request = GetTaskRequest(id: id); + GetTaskResponse response = await taskService.getTask( + request, + options: CallOptions(metadata: TasksAPIServices().getMetaData()), + ); + + return TaskWithPatient( + id: response.id, + name: response.name, + notes: response.description, + isPublicVisible: response.public, + status: GRPCTypeConverter.taskStatusFromGRPC(response.status), + assignee: response.assignedUserId, + dueDate: response.dueAt.toDateTime(), + patient: PatientMinimal(id: response.patient.id, name: response.patient.humanReadableIdentifier), + subtasks: response.subtasks + .map((subtask) => Subtask( + id: subtask.id, + name: subtask.name, + isDone: subtask.done, + )) + .toList(), + ); + } + + Future createTask(TaskWithPatient task) async { + CreateTaskRequest request = CreateTaskRequest( + name: task.name, + description: task.notes, + initialStatus: GRPCTypeConverter.taskStatusToGRPC(task.status), + dueAt: task.dueDate != null ? Timestamp.fromDateTime(task.dueDate!) : null, + patientId: !task.patient.isCreating ? task.patient.id : null, + public: task.isPublicVisible, + ); + CreateTaskResponse response = await taskService.createTask( + request, + options: CallOptions(metadata: TasksAPIServices().getMetaData()), + ); + + return response.id; + } + + /// Assign a [Task] to a [User] + Future assignToUser({required String taskId, required String userId}) async { + AssignTaskRequest request = AssignTaskRequest(taskId: taskId, userId: userId); + AssignTaskResponse response = await taskService.assignTask( + request, + options: CallOptions(metadata: TasksAPIServices().getMetaData()), + ); + + if (!response.isInitialized()) { + // Handle error + } + } + + /// Add a [Subtask] to a [Task] + Future createSubTask({required String taskId, required Subtask subTask}) async { + CreateSubtaskRequest request = CreateSubtaskRequest( + taskId: taskId, + subtask: CreateSubtaskRequest_Subtask( + name: subTask.name, + done: subTask.isDone, + )); + CreateSubtaskResponse response = await taskService.createSubtask( + request, + options: CallOptions(metadata: TasksAPIServices().getMetaData()), + ); + + return Subtask( + id: response.subtaskId, + name: subTask.name, + isDone: subTask.isDone, + ); + } + + /// Delete a [Subtask] by its identifier + Future deleteSubTask({required String subtaskId, required String taskId}) async { + DeleteSubtaskRequest request = DeleteSubtaskRequest(subtaskId: subtaskId, taskId: taskId); + DeleteSubtaskResponse response = await taskService.deleteSubtask( + request, + options: CallOptions(metadata: TasksAPIServices().getMetaData()), + ); + + return response.isInitialized(); + } + + /// Update a [Subtask]'s + Future updateSubtask({required Subtask subtask, required taskId}) async { + UpdateSubtaskRequest request = UpdateSubtaskRequest( + taskId: taskId, + subtaskId: subtask.id, + subtask: UpdateSubtaskRequest_Subtask(done: subtask.isDone, name: subtask.name), + ); + UpdateSubtaskResponse response = await taskService.updateSubtask( + request, + options: CallOptions(metadata: TasksAPIServices().getMetaData()), + ); + + return response.isInitialized(); + } + + Future updateTask(Task task) async { + UpdateTaskRequest request = UpdateTaskRequest( + id: task.id, + name: task.name, + description: task.notes, + dueAt: task.dueDate != null ? Timestamp.fromDateTime(task.dueDate!) : null, + public: task.isPublicVisible, + status: GRPCTypeConverter.taskStatusToGRPC(task.status), + ); + + UpdateTaskResponse response = await taskService.updateTask( + request, + options: CallOptions(metadata: TasksAPIServices().getMetaData()), + ); + + return response.isInitialized(); + } +} diff --git a/apps/tasks/lib/services/ward_service.dart b/packages/helpwave_service/lib/src/api/tasks/services/ward_service.dart similarity index 59% rename from apps/tasks/lib/services/ward_service.dart rename to packages/helpwave_service/lib/src/api/tasks/services/ward_service.dart index 73ddcc9c..d34ebb15 100644 --- a/apps/tasks/lib/services/ward_service.dart +++ b/packages/helpwave_service/lib/src/api/tasks/services/ward_service.dart @@ -1,28 +1,27 @@ import 'package:grpc/grpc.dart'; -import 'package:helpwave_proto_dart/proto/services/task_svc/v1/ward_svc.pbgrpc.dart'; -import 'package:tasks/dataclasses/ward.dart'; -import 'package:tasks/services/grpc_client_svc.dart'; +import 'package:helpwave_proto_dart/services/tasks_svc/v1/ward_svc.pbgrpc.dart'; +import 'package:helpwave_service/src/api/tasks/data_types/index.dart'; +import 'package:helpwave_service/src/api/tasks/tasks_api_services.dart'; -/// The GRPC Service for [Ward]s +/// The Service for [Ward]s /// /// Provides queries and requests that load or alter [Ward] objects on the server -/// The server is defined in the underlying [GRPCClientService] +/// The server is defined in the underlying [TasksAPIServices] class WardService { /// The GRPC ServiceClient which handles GRPC - WardServiceClient wardService = GRPCClientService.getWardServiceClient; + WardServiceClient wardService = TasksAPIServices.wardServiceClient; - /// Loads a [Ward] by its identifier - Future getWard({required String id}) async { + /// Loads a [WardMinimal] by its identifier + Future getWard({required String id}) async { GetWardRequest request = GetWardRequest(id: id); GetWardResponse response = await wardService.getWard( request, - options: CallOptions(metadata: GRPCClientService().getTaskServiceMetaData()), + options: CallOptions(metadata: TasksAPIServices().getMetaData()), ); - return Ward( + return WardMinimal( id: response.id, name: response.name, - organizationId: response.organizationId, ); } @@ -31,7 +30,7 @@ class WardService { GetWardOverviewsRequest request = GetWardOverviewsRequest(); GetWardOverviewsResponse response = await wardService.getWardOverviews( request, - options: CallOptions(metadata: GRPCClientService().getTaskServiceMetaData(organizationId: organizationId)), + options: CallOptions(metadata: TasksAPIServices().getMetaData(organizationId: organizationId)), ); return response.wards diff --git a/packages/helpwave_service/lib/src/api/tasks/tasks_api_services.dart b/packages/helpwave_service/lib/src/api/tasks/tasks_api_services.dart new file mode 100644 index 00000000..1c09d123 --- /dev/null +++ b/packages/helpwave_service/lib/src/api/tasks/tasks_api_services.dart @@ -0,0 +1,42 @@ +import 'package:grpc/grpc.dart'; +import 'package:helpwave_proto_dart/services/tasks_svc/v1/ward_svc.pbgrpc.dart'; +import 'package:helpwave_proto_dart/services/tasks_svc/v1/patient_svc.pbgrpc.dart'; +import 'package:helpwave_proto_dart/services/tasks_svc/v1/room_svc.pbgrpc.dart'; +import 'package:helpwave_proto_dart/services/tasks_svc/v1/task_svc.pbgrpc.dart'; +import 'package:helpwave_service/src/auth/index.dart'; + +/// The Underlying GrpcService it provides other clients and the correct metadata for the requests +class TasksAPIServices { + /// The api URL used + static String? apiUrl; + + static ClientChannel get serviceChannel { + assert(TasksAPIServices.apiUrl != null); + return ClientChannel( + TasksAPIServices.apiUrl!, + ); + } + + Map getMetaData({String? organizationId}) { + var metaData = { + ...AuthenticationUtility.authMetaData, + "dapr-app-id": "task-svc", + }; + + if (organizationId != null) { + metaData["X-Organization"] = organizationId; + } else { + metaData["X-Organization"] = AuthenticationUtility.fallbackOrganizationId!; + } + + return metaData; + } + + static PatientServiceClient get patientServiceClient => PatientServiceClient(serviceChannel); + + static WardServiceClient get wardServiceClient => WardServiceClient(serviceChannel); + + static RoomServiceClient get roomServiceClient => RoomServiceClient(serviceChannel); + + static TaskServiceClient get taskServiceClient => TaskServiceClient(serviceChannel); +} diff --git a/packages/helpwave_service/lib/src/api/tasks/util/task_status_mapping.dart b/packages/helpwave_service/lib/src/api/tasks/util/task_status_mapping.dart new file mode 100644 index 00000000..97b65819 --- /dev/null +++ b/packages/helpwave_service/lib/src/api/tasks/util/task_status_mapping.dart @@ -0,0 +1,30 @@ +import 'package:helpwave_service/src/api/tasks/data_types/task.dart' as task_lib; +import 'package:helpwave_proto_dart/services/tasks_svc/v1/types.pbenum.dart' as proto; + +class GRPCTypeConverter { + static proto.TaskStatus taskStatusToGRPC(task_lib.TaskStatus status) { + switch (status) { + case task_lib.TaskStatus.todo: + return proto.TaskStatus.TASK_STATUS_TODO; + case task_lib.TaskStatus.inProgress: + return proto.TaskStatus.TASK_STATUS_IN_PROGRESS; + case task_lib.TaskStatus.done: + return proto.TaskStatus.TASK_STATUS_DONE; + case task_lib.TaskStatus.unspecified: + return proto.TaskStatus.TASK_STATUS_UNSPECIFIED; + } + } + + static task_lib.TaskStatus taskStatusFromGRPC(proto.TaskStatus status) { + switch (status) { + case proto.TaskStatus.TASK_STATUS_TODO: + return task_lib.TaskStatus.todo; + case proto.TaskStatus.TASK_STATUS_IN_PROGRESS: + return task_lib.TaskStatus.inProgress; + case proto.TaskStatus.TASK_STATUS_DONE: + return task_lib.TaskStatus.done; + default: + return task_lib.TaskStatus.unspecified; + } + } +} diff --git a/packages/helpwave_service/lib/src/api/user/controllers/index.dart b/packages/helpwave_service/lib/src/api/user/controllers/index.dart new file mode 100644 index 00000000..dcd72ff4 --- /dev/null +++ b/packages/helpwave_service/lib/src/api/user/controllers/index.dart @@ -0,0 +1 @@ +export 'user_controller.dart'; diff --git a/apps/tasks/lib/controllers/user_controller.dart b/packages/helpwave_service/lib/src/api/user/controllers/user_controller.dart similarity index 91% rename from apps/tasks/lib/controllers/user_controller.dart rename to packages/helpwave_service/lib/src/api/user/controllers/user_controller.dart index 518ef281..dce15479 100644 --- a/apps/tasks/lib/controllers/user_controller.dart +++ b/packages/helpwave_service/lib/src/api/user/controllers/user_controller.dart @@ -1,7 +1,6 @@ import 'package:flutter/material.dart'; -import 'package:helpwave_widget/loading.dart'; -import 'package:tasks/services/user_service.dart'; -import '../dataclasses/user.dart'; +import 'package:helpwave_util/loading_state.dart'; +import '../index.dart'; /// The Controller for managing a [User] class UserController extends ChangeNotifier { diff --git a/packages/helpwave_service/lib/src/api/user/data_types/index.dart b/packages/helpwave_service/lib/src/api/user/data_types/index.dart new file mode 100644 index 00000000..7d071f5a --- /dev/null +++ b/packages/helpwave_service/lib/src/api/user/data_types/index.dart @@ -0,0 +1,2 @@ +export 'user.dart'; +export 'organization.dart'; diff --git a/apps/tasks/lib/dataclasses/organization.dart b/packages/helpwave_service/lib/src/api/user/data_types/organization.dart similarity index 100% rename from apps/tasks/lib/dataclasses/organization.dart rename to packages/helpwave_service/lib/src/api/user/data_types/organization.dart diff --git a/apps/tasks/lib/dataclasses/user.dart b/packages/helpwave_service/lib/src/api/user/data_types/user.dart similarity index 100% rename from apps/tasks/lib/dataclasses/user.dart rename to packages/helpwave_service/lib/src/api/user/data_types/user.dart diff --git a/packages/helpwave_service/lib/src/api/user/index.dart b/packages/helpwave_service/lib/src/api/user/index.dart new file mode 100644 index 00000000..243eabf0 --- /dev/null +++ b/packages/helpwave_service/lib/src/api/user/index.dart @@ -0,0 +1,4 @@ +export 'data_types/index.dart'; +export 'services/index.dart'; +export 'controllers/index.dart'; +export 'user_api_services.dart'; diff --git a/packages/helpwave_service/lib/src/api/user/services/index.dart b/packages/helpwave_service/lib/src/api/user/services/index.dart new file mode 100644 index 00000000..01052c51 --- /dev/null +++ b/packages/helpwave_service/lib/src/api/user/services/index.dart @@ -0,0 +1,2 @@ +export 'organization_svc.dart'; +export 'user_service.dart'; diff --git a/apps/tasks/lib/services/organization_svc.dart b/packages/helpwave_service/lib/src/api/user/services/organization_svc.dart similarity index 74% rename from apps/tasks/lib/services/organization_svc.dart rename to packages/helpwave_service/lib/src/api/user/services/organization_svc.dart index 9db077c9..0b4283f8 100644 --- a/apps/tasks/lib/services/organization_svc.dart +++ b/packages/helpwave_service/lib/src/api/user/services/organization_svc.dart @@ -1,23 +1,23 @@ import 'package:grpc/grpc.dart'; -import 'package:helpwave_proto_dart/proto/services/user_svc/v1/organization_svc.pbgrpc.dart'; -import 'package:tasks/dataclasses/organization.dart'; -import 'package:tasks/dataclasses/user.dart'; -import 'package:tasks/services/grpc_client_svc.dart'; +import 'package:helpwave_proto_dart/services/user_svc/v1/organization_svc.pbgrpc.dart'; +import 'package:helpwave_service/auth.dart'; +import 'package:helpwave_service/src/api/user/user_api_services.dart'; +import '../data_types/index.dart'; /// The GRPC Service for [Organization]s /// /// Provides queries and requests that load or alter [Organization] objects on the server -/// The server is defined in the underlying [GRPCClientService] +/// The server is defined in the underlying [UserAPIServices] class OrganizationService { /// The GRPC ServiceClient which handles GRPC - OrganizationServiceClient organizationService = GRPCClientService.getOrganizationServiceClient; + OrganizationServiceClient organizationService = UserAPIServices.organizationServiceClient; /// Load a Organization by its identifier Future getOrganization({required String id}) async { GetOrganizationRequest request = GetOrganizationRequest(id: id); GetOrganizationResponse response = await organizationService.getOrganization( request, - options: CallOptions(metadata: GRPCClientService().getUserServiceMetaData(organizationId: id)), + options: CallOptions(metadata: UserAPIServices.getMetaData(organizationId: id)), ); // TODO use full information of request @@ -35,8 +35,8 @@ class OrganizationService { GetOrganizationsForUserResponse response = await organizationService.getOrganizationsForUser( request, options: CallOptions( - metadata: GRPCClientService().getUserServiceMetaData( - organizationId: GRPCClientService().fallbackOrganizationId, + metadata: UserAPIServices.getMetaData( + organizationId: AuthenticationUtility.fallbackOrganizationId, ), ), ); @@ -58,7 +58,7 @@ class OrganizationService { GetMembersByOrganizationResponse response = await organizationService.getMembersByOrganization( request, options: CallOptions( - metadata: GRPCClientService().getUserServiceMetaData(organizationId: organizationId), + metadata: UserAPIServices.getMetaData(organizationId: organizationId), ), ); diff --git a/apps/tasks/lib/services/user_service.dart b/packages/helpwave_service/lib/src/api/user/services/user_service.dart similarity index 59% rename from apps/tasks/lib/services/user_service.dart rename to packages/helpwave_service/lib/src/api/user/services/user_service.dart index fedb8899..a667b4cb 100644 --- a/apps/tasks/lib/services/user_service.dart +++ b/packages/helpwave_service/lib/src/api/user/services/user_service.dart @@ -1,15 +1,16 @@ import 'package:grpc/grpc.dart'; -import 'package:helpwave_proto_dart/proto/services/user_svc/v1/user_svc.pbgrpc.dart'; -import 'package:tasks/services/grpc_client_svc.dart'; -import '../dataclasses/user.dart'; +import 'package:helpwave_proto_dart/services/user_svc/v1/user_svc.pbgrpc.dart'; +import 'package:helpwave_service/auth.dart'; +import 'package:helpwave_service/src/api/user/user_api_services.dart'; +import '../data_types/index.dart'; /// The GRPC Service for [User]s /// /// Provides queries and requests that load or alter [User] objects on the server -/// The server is defined in the underlying [GRPCClientService] +/// The server is defined in the underlying [UserAPIServices] class UserService { /// The GRPC ServiceClient which handles GRPC - UserServiceClient userService = GRPCClientService.getUserServiceClient; + UserServiceClient userService = UserAPIServices.userServiceClient; /// Loads the [User]s by it's identifier Future getUser({String? id}) async { @@ -17,8 +18,8 @@ class UserService { ReadPublicProfileResponse response = await userService.readPublicProfile( request, options: CallOptions( - metadata: GRPCClientService().getUserServiceMetaData( - organizationId: GRPCClientService().fallbackOrganizationId, + metadata: UserAPIServices.getMetaData( + organizationId: AuthenticationUtility.fallbackOrganizationId, ), ), ); diff --git a/packages/helpwave_service/lib/src/api/user/user_api_services.dart b/packages/helpwave_service/lib/src/api/user/user_api_services.dart new file mode 100644 index 00000000..695cb5f9 --- /dev/null +++ b/packages/helpwave_service/lib/src/api/user/user_api_services.dart @@ -0,0 +1,36 @@ +import 'package:grpc/grpc.dart'; +import 'package:helpwave_proto_dart/services/user_svc/v1/user_svc.pbgrpc.dart'; +import 'package:helpwave_proto_dart/services/user_svc/v1/organization_svc.pbgrpc.dart'; +import 'package:helpwave_service/src/auth/index.dart'; + +/// A bundling of all User API services which can be used and are configured +/// +/// Make sure to set the [apiURL] to use the services +class UserAPIServices { + /// The api URL used + static String? apiUrl; + + static ClientChannel get serviceChannel { + assert(UserAPIServices.apiUrl != null); + return ClientChannel( + UserAPIServices.apiUrl!, + ); + } + + static Map getMetaData({String? organizationId}) { + var metaData = { + ...AuthenticationUtility.authMetaData, + "dapr-app-id": "user-svc", + }; + + if (organizationId != null) { + metaData["X-Organization"] = organizationId; + } + + return metaData; + } + + static UserServiceClient get userServiceClient => UserServiceClient(serviceChannel); + + static OrganizationServiceClient get organizationServiceClient => OrganizationServiceClient(serviceChannel); +} diff --git a/packages/helpwave_service/lib/src/auth/authentication_utility.dart b/packages/helpwave_service/lib/src/auth/authentication_utility.dart new file mode 100644 index 00000000..488e4558 --- /dev/null +++ b/packages/helpwave_service/lib/src/auth/authentication_utility.dart @@ -0,0 +1,18 @@ +import 'package:helpwave_service/auth.dart'; + +class AuthenticationUtility { + static Map get authMetaData { + UserSessionService sessionService = UserSessionService(); + if (sessionService.isLoggedIn) { + return { + "Authorization": "Bearer ${sessionService.identity?.idToken}", + }; + } + // Maybe throw a error instead + return {}; + } + + static String? get fallbackOrganizationId => + // Maybe throw a error instead for the last case + CurrentWardService().currentWard?.organizationId ?? UserSessionService().identity?.firstOrganization; +} diff --git a/apps/tasks/lib/services/current_ward_svc.dart b/packages/helpwave_service/lib/src/auth/current_ward_svc.dart similarity index 95% rename from apps/tasks/lib/services/current_ward_svc.dart rename to packages/helpwave_service/lib/src/auth/current_ward_svc.dart index 8711d471..8413e807 100644 --- a/apps/tasks/lib/services/current_ward_svc.dart +++ b/packages/helpwave_service/lib/src/auth/current_ward_svc.dart @@ -1,10 +1,7 @@ import 'package:flutter/foundation.dart'; import 'package:shared_preferences/shared_preferences.dart'; -import 'package:tasks/config/config.dart'; -import 'package:tasks/dataclasses/organization.dart'; -import 'package:tasks/dataclasses/ward.dart'; -import 'package:tasks/services/organization_svc.dart'; -import 'package:tasks/services/ward_service.dart'; +import 'package:helpwave_service/src/api/tasks/index.dart'; +import 'package:helpwave_service/src/api/user/index.dart'; /// A readonly class for getting the CurrentWard information class CurrentWardInformation { @@ -76,6 +73,8 @@ class _CurrentWardPreferences { /// /// Changes the [CurrentWardInformation] globally class CurrentWardService extends Listenable { + bool devMode = false; // TODO remove + /// A storage for the current ward final _CurrentWardPreferences _preferences = _CurrentWardPreferences(); @@ -169,7 +168,8 @@ class CurrentWardController extends ChangeNotifier { /// Whether this Controller has been initialized bool get isInitialized => service.isInitialized; - CurrentWardController() { + CurrentWardController({bool devMode = false}) { + service.devMode = devMode; service.addListener(notifyListeners); if (!service.isInitialized) { load(); diff --git a/packages/helpwave_service/lib/src/auth/index.dart b/packages/helpwave_service/lib/src/auth/index.dart new file mode 100644 index 00000000..27d7f07d --- /dev/null +++ b/packages/helpwave_service/lib/src/auth/index.dart @@ -0,0 +1,6 @@ +export 'authentication_service.dart' show AuthenticationService; +export 'identity.dart'; +export 'user_session_controller.dart'; +export 'user_session_service.dart'; +export 'authentication_utility.dart'; +export 'current_ward_svc.dart'; diff --git a/apps/tasks/lib/controllers/user_session_controller.dart b/packages/helpwave_service/lib/src/auth/user_session_controller.dart similarity index 94% rename from apps/tasks/lib/controllers/user_session_controller.dart rename to packages/helpwave_service/lib/src/auth/user_session_controller.dart index 1d44ddf0..f7238230 100644 --- a/apps/tasks/lib/controllers/user_session_controller.dart +++ b/packages/helpwave_service/lib/src/auth/user_session_controller.dart @@ -1,5 +1,5 @@ import 'package:flutter/foundation.dart'; -import 'package:tasks/services/user_session_service.dart'; +import 'package:helpwave_service/src/auth/user_session_service.dart'; /// A Controller for providing and updating the current user session class UserSessionController extends ChangeNotifier { diff --git a/apps/tasks/lib/services/user_session_service.dart b/packages/helpwave_service/lib/src/auth/user_session_service.dart similarity index 87% rename from apps/tasks/lib/services/user_session_service.dart rename to packages/helpwave_service/lib/src/auth/user_session_service.dart index 6df1ee87..1e4a40a7 100644 --- a/apps/tasks/lib/services/user_session_service.dart +++ b/packages/helpwave_service/lib/src/auth/user_session_service.dart @@ -1,6 +1,4 @@ import 'package:helpwave_service/auth.dart'; -import 'package:tasks/config/config.dart'; -import 'package:tasks/services/current_ward_svc.dart'; /// The class for storing an managing the user session class UserSessionService { @@ -10,6 +8,9 @@ class UserSessionService { /// Whether the stored tokens have already been used for authentication bool _hasTriedTokens = false; + /// Whether this service should run in development mode + bool _devMode = false; + final AuthenticationService _authService = AuthenticationService(); static final UserSessionService _userSessionService = UserSessionService._ensureInitialized(); @@ -24,6 +25,11 @@ class UserSessionService { bool get hasTriedTokens => _hasTriedTokens; + bool get devMode => _devMode; + + /// **Only use this** once before using the service + changeMode(bool isDevMode) => _devMode = isDevMode; + /// Logs a User in by using the stored tokens /// /// Sets the [hasTriedTokens] to true diff --git a/packages/helpwave_service/lib/tasks.dart b/packages/helpwave_service/lib/tasks.dart new file mode 100644 index 00000000..fabf21ad --- /dev/null +++ b/packages/helpwave_service/lib/tasks.dart @@ -0,0 +1 @@ +export 'package:helpwave_service/src/api/tasks/index.dart'; diff --git a/packages/helpwave_service/lib/user.dart b/packages/helpwave_service/lib/user.dart new file mode 100644 index 00000000..24d6abf3 --- /dev/null +++ b/packages/helpwave_service/lib/user.dart @@ -0,0 +1 @@ +export 'package:helpwave_service/src/api/user/index.dart'; diff --git a/packages/helpwave_service/pubspec.yaml b/packages/helpwave_service/pubspec.yaml index 1639ab95..cce05101 100644 --- a/packages/helpwave_service/pubspec.yaml +++ b/packages/helpwave_service/pubspec.yaml @@ -2,6 +2,7 @@ name: helpwave_service description: A package for the helpwave services version: 0.0.1 homepage: https://github.com/helpwave/mobile-app +publish_to: none environment: sdk: '>=3.1.0' @@ -16,6 +17,10 @@ dependencies: flutter_secure_storage: 9.0.0 jose: ^0.3.4 logger: ^2.0.2+1 + helpwave_proto_dart: ^0.46.0-336429a + grpc: ^3.2.4 + helpwave_util: + path: "../helpwave_util" dev_dependencies: flutter_test: @@ -24,4 +29,4 @@ dev_dependencies: flutter: - + # flutter config diff --git a/packages/helpwave_theme/lib/src/dark_theme.dart b/packages/helpwave_theme/lib/src/theme/dark_theme.dart similarity index 97% rename from packages/helpwave_theme/lib/src/dark_theme.dart rename to packages/helpwave_theme/lib/src/theme/dark_theme.dart index 423474e1..5002ff66 100644 --- a/packages/helpwave_theme/lib/src/dark_theme.dart +++ b/packages/helpwave_theme/lib/src/theme/dark_theme.dart @@ -1,6 +1,6 @@ import 'package:flutter/material.dart'; -import 'package:helpwave_theme/src/theme.dart'; -import 'constants.dart'; +import 'package:helpwave_theme/src/theme/theme.dart'; +import '../constants.dart'; const primaryColor = Color.fromARGB(255, 255, 255, 255); const onPrimaryColor = Color.fromARGB(255, 0, 0, 0); diff --git a/packages/helpwave_theme/lib/src/light_theme.dart b/packages/helpwave_theme/lib/src/theme/light_theme.dart similarity index 97% rename from packages/helpwave_theme/lib/src/light_theme.dart rename to packages/helpwave_theme/lib/src/theme/light_theme.dart index fc57e12d..72e708cf 100644 --- a/packages/helpwave_theme/lib/src/light_theme.dart +++ b/packages/helpwave_theme/lib/src/theme/light_theme.dart @@ -1,6 +1,6 @@ import 'package:flutter/material.dart'; -import 'package:helpwave_theme/src/theme.dart'; -import 'constants.dart'; +import 'package:helpwave_theme/src/theme/theme.dart'; +import '../constants.dart'; const primaryColor = Color.fromARGB(255, 0, 0, 0); const onPrimaryColor = Color.fromARGB(255, 255, 255, 255); diff --git a/packages/helpwave_theme/lib/src/theme.dart b/packages/helpwave_theme/lib/src/theme/theme.dart similarity index 99% rename from packages/helpwave_theme/lib/src/theme.dart rename to packages/helpwave_theme/lib/src/theme/theme.dart index bb97803f..a9a27fd7 100644 --- a/packages/helpwave_theme/lib/src/theme.dart +++ b/packages/helpwave_theme/lib/src/theme/theme.dart @@ -1,6 +1,6 @@ import 'package:flutter/material.dart'; import 'package:helpwave_util/material_state.dart'; -import '../constants.dart'; +import '../../constants.dart'; // A function to map incoming colors to a theme ThemeData makeTheme({ diff --git a/packages/helpwave_theme/lib/src/util/context_extension.dart b/packages/helpwave_theme/lib/src/util/context_extension.dart new file mode 100644 index 00000000..c5841c77 --- /dev/null +++ b/packages/helpwave_theme/lib/src/util/context_extension.dart @@ -0,0 +1,5 @@ +import 'package:flutter/material.dart'; + +extension BuildContextThemeExtension on BuildContext { + ThemeData get theme => Theme.of(this); +} diff --git a/packages/helpwave_theme/lib/src/util/index.dart b/packages/helpwave_theme/lib/src/util/index.dart new file mode 100644 index 00000000..a4351565 --- /dev/null +++ b/packages/helpwave_theme/lib/src/util/index.dart @@ -0,0 +1,2 @@ +export 'context_extension.dart'; +export 'material_state_color_resolver.dart'; diff --git a/packages/helpwave_theme/lib/src/material_state_color_resolver.dart b/packages/helpwave_theme/lib/src/util/material_state_color_resolver.dart similarity index 100% rename from packages/helpwave_theme/lib/src/material_state_color_resolver.dart rename to packages/helpwave_theme/lib/src/util/material_state_color_resolver.dart diff --git a/packages/helpwave_theme/lib/theme.dart b/packages/helpwave_theme/lib/theme.dart index af2d8684..65327fb0 100644 --- a/packages/helpwave_theme/lib/theme.dart +++ b/packages/helpwave_theme/lib/theme.dart @@ -1,3 +1,3 @@ -export "package:helpwave_theme/src/light_theme.dart" show lightTheme; -export "package:helpwave_theme/src/dark_theme.dart" show darkTheme; +export 'package:helpwave_theme/src/theme/light_theme.dart' show lightTheme; +export 'package:helpwave_theme/src/theme/dark_theme.dart' show darkTheme; export "package:helpwave_theme/src/theme_model.dart"; diff --git a/packages/helpwave_theme/lib/util.dart b/packages/helpwave_theme/lib/util.dart index 38c23504..4ef38e09 100644 --- a/packages/helpwave_theme/lib/util.dart +++ b/packages/helpwave_theme/lib/util.dart @@ -1 +1 @@ -export "package:helpwave_theme/src/material_state_color_resolver.dart"; +export 'package:helpwave_theme/src/util/index.dart'; diff --git a/packages/helpwave_util/lib/loading_state.dart b/packages/helpwave_util/lib/loading_state.dart new file mode 100644 index 00000000..b47bbe00 --- /dev/null +++ b/packages/helpwave_util/lib/loading_state.dart @@ -0,0 +1 @@ +export 'package:helpwave_util/src/loading_state/type.dart'; diff --git a/packages/helpwave_util/lib/search.dart b/packages/helpwave_util/lib/search.dart new file mode 100644 index 00000000..dc90568d --- /dev/null +++ b/packages/helpwave_util/lib/search.dart @@ -0,0 +1 @@ +export 'package:helpwave_util/src/search/search_helpers.dart'; diff --git a/packages/helpwave_util/lib/src/loading_state/type.dart b/packages/helpwave_util/lib/src/loading_state/type.dart new file mode 100644 index 00000000..137a5f9b --- /dev/null +++ b/packages/helpwave_util/lib/src/loading_state/type.dart @@ -0,0 +1,16 @@ +enum LoadingState { + /// The data is initializing + initializing, + + /// The data is loaded + loaded, + + /// The data is currently loading + loading, + + /// Loading the data produced an error + error, + + /// There is no loading state, meaning ignore the LoadingState + unspecified, +} diff --git a/apps/tasks/lib/util/search_helpers.dart b/packages/helpwave_util/lib/src/search/search_helpers.dart similarity index 100% rename from apps/tasks/lib/util/search_helpers.dart rename to packages/helpwave_util/lib/src/search/search_helpers.dart diff --git a/packages/helpwave_widget/lib/src/loading/loading_and_error_widget.dart b/packages/helpwave_widget/lib/src/loading/loading_and_error_widget.dart index 51281eb2..d9b26fc7 100644 --- a/packages/helpwave_widget/lib/src/loading/loading_and_error_widget.dart +++ b/packages/helpwave_widget/lib/src/loading/loading_and_error_widget.dart @@ -1,24 +1,8 @@ import 'package:flutter/cupertino.dart'; import 'package:helpwave_theme/constants.dart'; +import 'package:helpwave_util/loading_state.dart'; import 'package:helpwave_widget/loading.dart'; -enum LoadingState { - /// The date is initializing - initializing, - - /// The date is loaded - loaded, - - /// The date is currently loading - loading, - - /// The loading produced an error - error, - - /// There is no loading state, meaning ignore the LoadingState - unspecified, -} - /// A [Widget] to show different [Widget]s depending on the [LoadingState] class LoadingAndErrorWidget extends StatelessWidget { /// The [LoadingState] is used to determine the shown [Widget] diff --git a/packages/helpwave_widget/lib/src/loading/loading_future_builder.dart b/packages/helpwave_widget/lib/src/loading/loading_future_builder.dart index 7b5f7704..ccfb938e 100644 --- a/packages/helpwave_widget/lib/src/loading/loading_future_builder.dart +++ b/packages/helpwave_widget/lib/src/loading/loading_future_builder.dart @@ -1,4 +1,5 @@ import 'package:flutter/cupertino.dart'; +import 'package:helpwave_util/loading_state.dart'; import 'package:helpwave_widget/loading.dart'; /// A Wrapper for the standard [FutureBuilder] to easily distinguish the three diff --git a/packages/helpwave_widget/pubspec.yaml b/packages/helpwave_widget/pubspec.yaml index c0e91e36..bf60e6d9 100644 --- a/packages/helpwave_widget/pubspec.yaml +++ b/packages/helpwave_widget/pubspec.yaml @@ -25,3 +25,4 @@ dev_dependencies: flutter_lints: ^2.0.0 flutter: + # flutter config From ae7722af9d4d6300e69e78d068c7973968995106 Mon Sep 17 00:00:00 2001 From: Felix Thape Date: Sun, 15 Sep 2024 18:33:00 +0200 Subject: [PATCH 2/9] feat: draft for offline mode --- .../tasks/lib/components/assignee_select.dart | 2 +- .../lib/components/task_bottom_sheet.dart | 4 +- apps/tasks/lib/main.dart | 2 +- .../tasks/lib/screens/ward_select_screen.dart | 4 +- .../src/api/offline/offline_client_store.dart | 93 ++++ .../lib/src/api/offline/util.dart | 48 ++ .../controllers/my_tasks_controller.dart | 2 +- .../tasks/controllers/task_controller.dart | 6 +- .../lib/src/api/tasks/data_types/bed.dart | 6 + .../lib/src/api/tasks/data_types/patient.dart | 37 +- .../lib/src/api/tasks/data_types/room.dart | 6 + .../lib/src/api/tasks/data_types/subtask.dart | 11 +- .../lib/src/api/tasks/data_types/task.dart | 70 ++- .../api/tasks/data_types/task_template.dart | 28 +- .../lib/src/api/tasks/index.dart | 2 +- .../offline_clients/bed_offline_client.dart | 178 +++++++ .../patient_offline_client.dart | 366 ++++++++++++++ .../offline_clients/room_offline_client.dart | 161 +++++++ .../offline_clients/task_offline_client.dart | 445 ++++++++++++++++++ .../template_offline_client.dart | 241 ++++++++++ .../offline_clients/ward_offline_client.dart | 162 +++++++ .../src/api/tasks/services/patient_svc.dart | 32 +- .../lib/src/api/tasks/services/room_svc.dart | 8 +- .../lib/src/api/tasks/services/task_svc.dart | 22 +- .../src/api/tasks/services/ward_service.dart | 10 +- ...es.dart => tasks_api_service_clients.dart} | 6 +- .../src/api/user/data_types/organization.dart | 49 +- .../lib/src/api/user/data_types/user.dart | 18 +- .../lib/src/api/user/index.dart | 2 +- .../organization_offline_client.dart | 271 +++++++++++ .../offline_clients/user_offline_client.dart | 119 +++++ .../api/user/services/organization_svc.dart | 39 +- .../src/api/user/services/user_service.dart | 11 +- ...ces.dart => user_api_service_clients.dart} | 6 +- .../lib/src/auth/current_ward_svc.dart | 8 +- packages/helpwave_util/lib/lists.dart | 1 + .../helpwave_util/lib/src/lists/range.dart | 11 + 37 files changed, 2368 insertions(+), 119 deletions(-) create mode 100644 packages/helpwave_service/lib/src/api/offline/offline_client_store.dart create mode 100644 packages/helpwave_service/lib/src/api/offline/util.dart create mode 100644 packages/helpwave_service/lib/src/api/tasks/offline_clients/bed_offline_client.dart create mode 100644 packages/helpwave_service/lib/src/api/tasks/offline_clients/patient_offline_client.dart create mode 100644 packages/helpwave_service/lib/src/api/tasks/offline_clients/room_offline_client.dart create mode 100644 packages/helpwave_service/lib/src/api/tasks/offline_clients/task_offline_client.dart create mode 100644 packages/helpwave_service/lib/src/api/tasks/offline_clients/template_offline_client.dart create mode 100644 packages/helpwave_service/lib/src/api/tasks/offline_clients/ward_offline_client.dart rename packages/helpwave_service/lib/src/api/tasks/{tasks_api_services.dart => tasks_api_service_clients.dart} (92%) create mode 100644 packages/helpwave_service/lib/src/api/user/offline_clients/organization_offline_client.dart create mode 100644 packages/helpwave_service/lib/src/api/user/offline_clients/user_offline_client.dart rename packages/helpwave_service/lib/src/api/user/{user_api_services.dart => user_api_service_clients.dart} (89%) create mode 100644 packages/helpwave_util/lib/lists.dart create mode 100644 packages/helpwave_util/lib/src/lists/range.dart diff --git a/apps/tasks/lib/components/assignee_select.dart b/apps/tasks/lib/components/assignee_select.dart index 311999fb..08de7ad8 100644 --- a/apps/tasks/lib/components/assignee_select.dart +++ b/apps/tasks/lib/components/assignee_select.dart @@ -36,7 +36,7 @@ class AssigneeSelect extends StatelessWidget { }); }, leading: CircleAvatar( - foregroundColor: Colors.blue, backgroundImage: NetworkImage(user.profile.toString())), + foregroundColor: Colors.blue, backgroundImage: NetworkImage(user.profileUrl.toString())), title: Text(user.nickName), ); }, diff --git a/apps/tasks/lib/components/task_bottom_sheet.dart b/apps/tasks/lib/components/task_bottom_sheet.dart index d01138eb..44e62720 100644 --- a/apps/tasks/lib/components/task_bottom_sheet.dart +++ b/apps/tasks/lib/components/task_bottom_sheet.dart @@ -211,7 +211,7 @@ class _TaskBottomSheetState extends State { state: taskController.state, child: ChangeNotifierProvider( create: (BuildContext context) => AssigneeSelectController( - selected: taskController.task.assignee, + selected: taskController.task.assigneeId, taskId: taskController.task.id, ), child: AssigneeSelect( @@ -228,7 +228,7 @@ class _TaskBottomSheetState extends State { state: taskController.state, child: taskController.task.hasAssignee ? ChangeNotifierProvider( - create: (context) => UserController(User.empty(id: taskController.task.assignee!)), + create: (context) => UserController(User.empty(id: taskController.task.assigneeId!)), child: Consumer( builder: (context, userController, __) => LoadingAndErrorWidget.pulsing( state: userController.state, diff --git a/apps/tasks/lib/main.dart b/apps/tasks/lib/main.dart index e5b4ad0f..5a4da007 100644 --- a/apps/tasks/lib/main.dart +++ b/apps/tasks/lib/main.dart @@ -11,7 +11,7 @@ import 'package:tasks/screens/login_screen.dart'; void main() { UserSessionService().changeMode(devMode); - TasksAPIServices.apiUrl = usedAPIURL; + TasksAPIServiceClients.apiUrl = usedAPIURL; runApp(const MyApp()); } diff --git a/apps/tasks/lib/screens/ward_select_screen.dart b/apps/tasks/lib/screens/ward_select_screen.dart index 7e7248c7..73d0018c 100644 --- a/apps/tasks/lib/screens/ward_select_screen.dart +++ b/apps/tasks/lib/screens/ward_select_screen.dart @@ -43,7 +43,7 @@ class _WardSelectScreen extends State { children: [ ListTile( // TODO change to organization name - title: Text(organization?.name ?? context.localization!.none), + title: Text(organization?.longName ?? context.localization!.none), subtitle: Text(context.localization!.organization), trailing: const Icon(Icons.arrow_forward), onTap: () => Navigator.push( @@ -55,7 +55,7 @@ class _WardSelectScreen extends State { List organizations = await OrganizationService().getOrganizationsForUser(); return organizations; }, - elementToString: (Organization t) => t.name, + elementToString: (Organization t) => t.longName, ), ), ).then((value) { diff --git a/packages/helpwave_service/lib/src/api/offline/offline_client_store.dart b/packages/helpwave_service/lib/src/api/offline/offline_client_store.dart new file mode 100644 index 00000000..3fe8d420 --- /dev/null +++ b/packages/helpwave_service/lib/src/api/offline/offline_client_store.dart @@ -0,0 +1,93 @@ +import 'package:helpwave_service/src/api/tasks/offline_clients/bed_offline_client.dart'; +import 'package:helpwave_service/src/api/tasks/offline_clients/patient_offline_client.dart'; +import 'package:helpwave_service/src/api/tasks/offline_clients/room_offline_client.dart'; +import 'package:helpwave_service/src/api/tasks/offline_clients/task_offline_client.dart'; +import 'package:helpwave_service/src/api/tasks/offline_clients/template_offline_client.dart'; +import 'package:helpwave_service/src/api/tasks/offline_clients/ward_offline_client.dart'; +import 'package:helpwave_service/src/api/user/offline_clients/organization_offline_client.dart'; +import 'package:helpwave_service/src/api/user/offline_clients/user_offline_client.dart'; +import '../../../user.dart'; + +const String profileUrl = "https://helpwave.de/favicon.ico"; + +final List initialOrganizations = [ + Organization( + id: "organization1", + shortName: "Test", + longName: "Test Organization", + avatarURL: profileUrl, + email: "test@helpwave.de", + isPersonal: false, + isVerified: true), + Organization( + id: "organization2", + shortName: "MK", + longName: "Musterklinikum", + avatarURL: profileUrl, + email: "test@helpwave.de", + isPersonal: false, + isVerified: true), +]; +final List initialUsers = [ + User( + id: "user1", + name: "Testine Test", + nickName: "Testine", + email: "test@helpwave.de", + profileUrl: Uri.parse(profileUrl), + ), + User( + id: "user2", + name: "Peter Pete", + nickName: "Peter", + email: "test@helpwave.de", + profileUrl: Uri.parse(profileUrl), + ), + User( + id: "user3", + name: "John Doe", + nickName: "John", + email: "test@helpwave.de", + profileUrl: Uri.parse(profileUrl), + ), + User( + id: "user4", + name: "Walter White", + nickName: "Walter", + email: "test@helpwave.de", + profileUrl: Uri.parse(profileUrl), + ), + User( + id: "user5", + name: "Peter Parker", + nickName: "Parker", + email: "test@helpwave.de", + profileUrl: Uri.parse(profileUrl), + ), +]; + +class OfflineClientStore { + static final OfflineClientStore _instance = OfflineClientStore._internal(); + + OfflineClientStore._internal(); + + factory OfflineClientStore() => _instance; + + final OrganizationOfflineClientStore organizationStore = OrganizationOfflineClientStore(); + final UserOfflineService userStore = UserOfflineService(); + + final WardOfflineService wardStore = WardOfflineService(); + final RoomOfflineService roomStore = RoomOfflineService(); + final BedOfflineService bedStore = BedOfflineService(); + final PatientOfflineService patientStore = PatientOfflineService(); + final TaskOfflineService taskStore = TaskOfflineService(); + final SubtaskOfflineService subtaskStore = SubtaskOfflineService(); + final TaskTemplateOfflineService taskTemplateStore = TaskTemplateOfflineService(); + final TaskTemplateSubtaskOfflineService taskTemplateSubtaskStore = TaskTemplateSubtaskOfflineService(); + + void reset() { + organizationStore.organizations = initialOrganizations; + userStore.users = initialUsers; + + } +} diff --git a/packages/helpwave_service/lib/src/api/offline/util.dart b/packages/helpwave_service/lib/src/api/offline/util.dart new file mode 100644 index 00000000..c518556c --- /dev/null +++ b/packages/helpwave_service/lib/src/api/offline/util.dart @@ -0,0 +1,48 @@ +import 'dart:async'; +import 'package:grpc/grpc.dart'; + +class MockResponseFuture implements ResponseFuture { + final Future future; + + MockResponseFuture.value(T value) : future = Future.value(value); + + MockResponseFuture.error(Object error) : future = Future.error(error); + + MockResponseFuture.future(this.future); + + @override + Stream asStream() { + return future.asStream(); + } + + @override + Future cancel() async { + // Mock Futures cannot be canceled + } + + @override + Future catchError(Function onError, {bool Function(Object error)? test}) { + return future.catchError(onError, test: test); + } + + @override + Future> get headers => Future.value({}); + + @override + Future timeout(Duration timeLimit, {FutureOr Function()? onTimeout}) { + return future.timeout(timeLimit, onTimeout: onTimeout); + } + + @override + Future> get trailers => Future.value({}); + + @override + Future whenComplete(FutureOr Function() action) { + return future.whenComplete(action); + } + + @override + Future then(FutureOr Function(T p1) onValue, {Function? onError}) { + return future.then(onValue, onError: onError); + } +} diff --git a/packages/helpwave_service/lib/src/api/tasks/controllers/my_tasks_controller.dart b/packages/helpwave_service/lib/src/api/tasks/controllers/my_tasks_controller.dart index c353476a..98de67d5 100644 --- a/packages/helpwave_service/lib/src/api/tasks/controllers/my_tasks_controller.dart +++ b/packages/helpwave_service/lib/src/api/tasks/controllers/my_tasks_controller.dart @@ -44,7 +44,7 @@ class MyTasksController extends ChangeNotifier { _tasks.add(TaskWithPatient( id: task.id, name: task.name, - assignee: task.assignee, + assignee: task.assigneeId, notes: task.notes, dueDate: task.dueDate, status: task.status, diff --git a/packages/helpwave_service/lib/src/api/tasks/controllers/task_controller.dart b/packages/helpwave_service/lib/src/api/tasks/controllers/task_controller.dart index f12f77f9..a797f9e3 100644 --- a/packages/helpwave_service/lib/src/api/tasks/controllers/task_controller.dart +++ b/packages/helpwave_service/lib/src/api/tasks/controllers/task_controller.dart @@ -79,13 +79,13 @@ class TaskController extends ChangeNotifier { /// /// Without a backend request as we expect this to be done in the [AssigneeSelectController] Future changeAssignee(String assigneeId) async { - String? old = task.assignee; + String? old = task.assigneeId; updateTask( (task) { - task.assignee = assigneeId; + task.assigneeId = assigneeId; }, (task) { - task.assignee = old; + task.assigneeId = old; }, ); } diff --git a/packages/helpwave_service/lib/src/api/tasks/data_types/bed.dart b/packages/helpwave_service/lib/src/api/tasks/data_types/bed.dart index a988a270..2bf7f84e 100644 --- a/packages/helpwave_service/lib/src/api/tasks/data_types/bed.dart +++ b/packages/helpwave_service/lib/src/api/tasks/data_types/bed.dart @@ -11,6 +11,12 @@ class BedMinimal { }); } +class BedWithRoomId extends BedMinimal { + String roomId; + + BedWithRoomId({required super.id, required super.name, required this.roomId}); +} + class BedWithMinimalPatient extends BedMinimal{ PatientMinimal? patient; diff --git a/packages/helpwave_service/lib/src/api/tasks/data_types/patient.dart b/packages/helpwave_service/lib/src/api/tasks/data_types/patient.dart index 0942256b..26b0ce61 100644 --- a/packages/helpwave_service/lib/src/api/tasks/data_types/patient.dart +++ b/packages/helpwave_service/lib/src/api/tasks/data_types/patient.dart @@ -33,13 +33,45 @@ class PatientMinimal { @override String toString() { - if(isCreating){ + if (isCreating) { return "PatientMinimal"; } return "PatientMinimal<$id, $name>"; } } +class PatientWithBedId extends PatientMinimal { + String? bedId; + bool isDischarged; + String notes; + + PatientWithBedId({ + required super.id, + required super.name, + required this.isDischarged, + required this.notes, + this.bedId, + }); + + PatientWithBedId copyWith({ + String? id, + String? name, + String? bedId, + bool? isDischarged, + String? notes, + }) { + return PatientWithBedId( + id: id ?? this.id, + name: name ?? this.name, + isDischarged: isDischarged ?? this.isDischarged, + notes: notes ?? this.notes, + bedId: bedId ?? this.bedId, + ); + } + + bool get hasBed => bedId != null; +} + /// data class for [Patient] with TaskCount class Patient extends PatientMinimal { RoomMinimal? room; @@ -54,8 +86,7 @@ class Patient extends PatientMinimal { List get unscheduledTasks => tasks.where((task) => task.status == TaskStatus.todo).toList(); - List get inProgressTasks => - tasks.where((task) => task.status == TaskStatus.inProgress).toList(); + List get inProgressTasks => tasks.where((task) => task.status == TaskStatus.inProgress).toList(); List get doneTasks => tasks.where((task) => task.status == TaskStatus.done).toList(); diff --git a/packages/helpwave_service/lib/src/api/tasks/data_types/room.dart b/packages/helpwave_service/lib/src/api/tasks/data_types/room.dart index 632ca7a1..8e943ea0 100644 --- a/packages/helpwave_service/lib/src/api/tasks/data_types/room.dart +++ b/packages/helpwave_service/lib/src/api/tasks/data_types/room.dart @@ -11,6 +11,12 @@ class RoomMinimal { }); } +class RoomWithWardId extends RoomMinimal { + String wardId; + + RoomWithWardId({required super.id, required super.name, required this.wardId}); +} + class RoomWithBeds { String id; String name; diff --git a/packages/helpwave_service/lib/src/api/tasks/data_types/subtask.dart b/packages/helpwave_service/lib/src/api/tasks/data_types/subtask.dart index f81a31dd..956d235c 100644 --- a/packages/helpwave_service/lib/src/api/tasks/data_types/subtask.dart +++ b/packages/helpwave_service/lib/src/api/tasks/data_types/subtask.dart @@ -1,25 +1,24 @@ /// Data class for a [Subtask] class Subtask { - String id; + final String id; + final String taskId; String name; bool isDone; bool get isCreating => id == ""; - Subtask({ - required this.id, - required this.name, - this.isDone = false - }); + Subtask({required this.id, required this.taskId, required this.name, this.isDone = false}); /// Create a copy of the [Subtask] Subtask copyWith({ String? id, + String? taskId, String? name, bool? isDone, }) { return Subtask( id: id ?? this.id, + taskId: taskId ?? this.taskId, name: name ?? this.name, isDone: isDone ?? this.isDone, ); diff --git a/packages/helpwave_service/lib/src/api/tasks/data_types/task.dart b/packages/helpwave_service/lib/src/api/tasks/data_types/task.dart index 370ff4b2..9b13a237 100644 --- a/packages/helpwave_service/lib/src/api/tasks/data_types/task.dart +++ b/packages/helpwave_service/lib/src/api/tasks/data_types/task.dart @@ -1,4 +1,3 @@ -// TODO delete later and import from protobufs import 'package:helpwave_service/src/api/tasks/data_types/patient.dart'; import 'package:helpwave_service/src/api/tasks/data_types/subtask.dart'; @@ -11,29 +10,28 @@ enum TaskStatus { /// data class for [Task] class Task { - String id; + final String id; String name; - String? assignee; + String? assigneeId; String notes; TaskStatus status; List subtasks; DateTime? dueDate; - DateTime? creationDate; + final DateTime? creationDate; + final String? createdBy; bool isPublicVisible; + final String patientId; - static get empty => Task(id: "", name: "name", notes: ""); + factory Task.empty(String patientId) => Task(id: "", name: "name", notes: "", patientId: patientId); final _nullID = "00000000-0000-0000-0000-000000000000"; - double get progress => subtasks.isNotEmpty - ? subtasks.where((element) => element.isDone).length / subtasks.length - : 1; + double get progress => subtasks.isNotEmpty ? subtasks.where((element) => element.isDone).length / subtasks.length : 1; /// the remaining time until a task is due /// /// **NOTE**: returns [Duration.zero] if [dueDate] is null - Duration get remainingTime => - dueDate != null ? dueDate!.difference(DateTime.now()) : Duration.zero; + Duration get remainingTime => dueDate != null ? dueDate!.difference(DateTime.now()) : Duration.zero; bool get isOverdue => remainingTime.isNegative; @@ -43,29 +41,65 @@ class Task { bool get isCreating => id == ""; - bool get hasAssignee => assignee != null && assignee != "" && assignee != _nullID; + bool get hasAssignee => assigneeId != null && assigneeId != "" && assigneeId != _nullID; Task({ required this.id, required this.name, required this.notes, - this.assignee, + this.assigneeId, this.status = TaskStatus.todo, this.subtasks = const [], this.dueDate, this.creationDate, + this.createdBy, this.isPublicVisible = false, + required this.patientId, }); + + Task copyWith({ + String? id, + String? name, + String? assigneeId, + String? notes, + TaskStatus? status, + List? subtasks, + DateTime? dueDate, + DateTime? creationDate, + String? createdBy, + bool? isPublicVisible, + String? patientId, + }) { + return Task( + id: id ?? this.id, + name: name ?? this.name, + assigneeId: assigneeId ?? this.assigneeId, + notes: notes ?? this.notes, + status: status ?? this.status, + subtasks: subtasks ?? this.subtasks, + dueDate: dueDate ?? this.dueDate, + creationDate: creationDate ?? this.creationDate, + createdBy: createdBy ?? this.createdBy, + isPublicVisible: isPublicVisible ?? this.isPublicVisible, + patientId: patientId ?? this.patientId, + ); + } } class TaskWithPatient extends Task { - PatientMinimal patient; + final PatientMinimal patient; factory TaskWithPatient.empty({ String taskId = "", PatientMinimal? patient, }) { - return TaskWithPatient(id: taskId, name: "task name", notes: "", patient: patient ?? PatientMinimal.empty()); + return TaskWithPatient( + id: taskId, + name: "task name", + notes: "", + patient: patient ?? PatientMinimal.empty(), + patientId: patient?.id ?? "", + ); } factory TaskWithPatient.fromTaskAndPatient({ @@ -82,8 +116,9 @@ class TaskWithPatient extends Task { status: task.status, dueDate: task.dueDate, creationDate: task.creationDate, - assignee: task.assignee, + assigneeId: task.assigneeId, patient: patient ?? PatientMinimal.empty(), + patientId: patient?.id ?? "", ); } @@ -91,12 +126,13 @@ class TaskWithPatient extends Task { required super.id, required super.name, required super.notes, - super.assignee, + super.assigneeId, super.status, super.subtasks, super.dueDate, super.creationDate, super.isPublicVisible, + required super.patientId, required this.patient, - }); + }) : assert(patientId == patient.id); } diff --git a/packages/helpwave_service/lib/src/api/tasks/data_types/task_template.dart b/packages/helpwave_service/lib/src/api/tasks/data_types/task_template.dart index 8c61a31c..735c1993 100644 --- a/packages/helpwave_service/lib/src/api/tasks/data_types/task_template.dart +++ b/packages/helpwave_service/lib/src/api/tasks/data_types/task_template.dart @@ -3,20 +3,42 @@ import '../index.dart'; /// data class for [TaskTemplate] class TaskTemplate { String id; - String? wardID; + String? wardId; String name; String notes; List subtasks; bool isPublicVisible; + String? createdBy; - get isWardTemplate => wardID != null; + get isWardTemplate => wardId != null; TaskTemplate({ required this.id, - this.wardID, + this.wardId, required this.name, required this.notes, this.subtasks = const [], this.isPublicVisible = false, + this.createdBy }); + + TaskTemplate copyWith({ + String? id, + String? wardId, + String? name, + String? notes, + List? subtasks, + bool? isPublicVisible, + String? createdBy, + }) { + return TaskTemplate( + id: id ?? this.id, + wardId: wardId ?? this.wardId, + name: name ?? this.name, + notes: notes ?? this.notes, + subtasks: subtasks ?? this.subtasks, + isPublicVisible: isPublicVisible ?? this.isPublicVisible, + createdBy: createdBy ?? this.createdBy, + ); + } } diff --git a/packages/helpwave_service/lib/src/api/tasks/index.dart b/packages/helpwave_service/lib/src/api/tasks/index.dart index bebaf463..44b25815 100644 --- a/packages/helpwave_service/lib/src/api/tasks/index.dart +++ b/packages/helpwave_service/lib/src/api/tasks/index.dart @@ -1,4 +1,4 @@ export 'data_types/index.dart'; export 'services/index.dart'; export 'controllers/index.dart'; -export 'tasks_api_services.dart'; +export 'tasks_api_service_clients.dart'; diff --git a/packages/helpwave_service/lib/src/api/tasks/offline_clients/bed_offline_client.dart b/packages/helpwave_service/lib/src/api/tasks/offline_clients/bed_offline_client.dart new file mode 100644 index 00000000..11f565e9 --- /dev/null +++ b/packages/helpwave_service/lib/src/api/tasks/offline_clients/bed_offline_client.dart @@ -0,0 +1,178 @@ +import 'package:grpc/grpc.dart'; +import 'package:helpwave_proto_dart/services/tasks_svc/v1/bed_svc.pbgrpc.dart'; +import 'package:helpwave_service/src/api/offline/offline_client_store.dart'; +import 'package:helpwave_service/src/api/offline/util.dart'; +import 'package:helpwave_service/src/api/tasks/data_types/bed.dart'; +import 'package:helpwave_util/lists.dart'; + +class BedUpdate { + String id; + String? name; + + BedUpdate({required this.id, required this.name}); +} + +class BedOfflineService { + List beds = []; + + BedWithRoomId? findBed(String id) { + int index = OfflineClientStore().bedStore.beds.indexWhere((value) => value.id == id); + if (index == -1) { + return null; + } + return beds[index]; + } + + List findBeds([String? roomId]) { + final valueStore = OfflineClientStore().bedStore; + if (roomId == null) { + return valueStore.beds; + } + return valueStore.beds.where((value) => value.roomId == roomId).toList(); + } + + void create(BedWithRoomId bed) { + OfflineClientStore().bedStore.beds.add(bed); + } + + void update(BedUpdate bed) { + final valueStore = OfflineClientStore().bedStore; + bool found = false; + + valueStore.beds = valueStore.beds.map((value) { + if (value.id == bed.id) { + found = true; + return BedWithRoomId(id: bed.id, name: bed.name ?? value.name, roomId: value.roomId); + } + return value; + }).toList(); + + if (!found) { + throw Exception('UpdateBed: Could not find bed with id ${bed.id}'); + } + } + + void delete(String bedId) { + final valueStore = OfflineClientStore().bedStore; + valueStore.beds = valueStore.beds.where((value) => value.id != bedId).toList(); + // TODO: Cascade delete to bed-bound templates + } +} + +class BedServicePromiseClient extends BedServiceClient { + BedServicePromiseClient(super.channel); + + @override + ResponseFuture getBed(GetBedRequest request, {CallOptions? options}) { + final bed = OfflineClientStore().bedStore.findBed(request.id); + + if (bed == null) { + throw "Bed with bed id ${request.id} not found"; + } + + final response = GetBedResponse() + ..id = bed.id + ..name = bed.name + ..roomId = bed.roomId; + + return MockResponseFuture.value(response); + } + + @override + ResponseFuture getBeds(GetBedsRequest request, {CallOptions? options}) { + final beds = OfflineClientStore().bedStore.findBeds(); + final bedsList = beds.map((bed) => GetBedsResponse_Bed(id: bed.id, name: bed.name, roomId: bed.roomId)).toList(); + + final response = GetBedsResponse(beds: bedsList); + + return MockResponseFuture.value(response); + } + + @override + ResponseFuture getBedByPatient(GetBedByPatientRequest request, {CallOptions? options}) { + final patient = OfflineClientStore().patientStore.findPatient(request.patientId); + if (patient == null) { + throw "Patient with id ${request.patientId} not found"; + } + if (!patient.hasBed) { + throw "Patient with id ${request.patientId} has no bed"; + } + final bed = OfflineClientStore().bedStore.findBed(patient.bedId!); + if (bed == null) { + throw "Inconsistent Data: Bed with id ${patient.bedId} not found"; + } + final room = OfflineClientStore().roomStore.findRoom(bed.roomId); + if (room == null) { + throw "Inconsistent Data: Room with id ${bed.roomId} not found"; + } + final response = GetBedByPatientResponse( + bed: GetBedByPatientResponse_Bed(id: bed.id, name: bed.name), + room: GetBedByPatientResponse_Room(id: room.id, name: room.name, wardId: room.wardId), + ); + return MockResponseFuture.value(response); + } + + @override + ResponseFuture getBedsByRoom(GetBedsByRoomRequest request, {CallOptions? options}) { + final beds = OfflineClientStore().bedStore.findBeds(request.roomId); + final response = + GetBedsByRoomResponse(beds: beds.map((bed) => GetBedsByRoomResponse_Bed(id: bed.id, name: bed.name))); + return MockResponseFuture.value(response); + } + + @override + ResponseFuture createBed(CreateBedRequest request, {CallOptions? options}) { + final newBed = BedWithRoomId( + id: DateTime.now().millisecondsSinceEpoch.toString(), + name: request.name, + roomId: request.roomId, + ); + + OfflineClientStore().bedStore.create(newBed); + + final response = CreateBedResponse()..id = newBed.id; + + return MockResponseFuture.value(response); + } + + @override + ResponseFuture bulkCreateBeds(BulkCreateBedsRequest request, {CallOptions? options}) { + final beds = range(0, request.amountOfBeds) + .map((index) => BedWithRoomId( + id: DateTime.now().millisecondsSinceEpoch.toString(), + name: "New Bed ${index + 1}", + roomId: request.roomId, + )) + .toList(); + + for (var bed in beds) { + OfflineClientStore().bedStore.create(bed); + } + + final response = + BulkCreateBedsResponse(beds: beds.map((bed) => BulkCreateBedsResponse_Bed(id: bed.id, name: bed.name))); + + return MockResponseFuture.value(response); + } + + @override + ResponseFuture updateBed(UpdateBedRequest request, {CallOptions? options}) { + final update = BedUpdate( + id: request.id, + name: request.name, + ); + + OfflineClientStore().bedStore.update(update); + + final response = UpdateBedResponse(); + return MockResponseFuture.value(response); + } + + @override + ResponseFuture deleteBed(DeleteBedRequest request, {CallOptions? options}) { + OfflineClientStore().bedStore.delete(request.id); + + final response = DeleteBedResponse(); + return MockResponseFuture.value(response); + } +} diff --git a/packages/helpwave_service/lib/src/api/tasks/offline_clients/patient_offline_client.dart b/packages/helpwave_service/lib/src/api/tasks/offline_clients/patient_offline_client.dart new file mode 100644 index 00000000..22a46384 --- /dev/null +++ b/packages/helpwave_service/lib/src/api/tasks/offline_clients/patient_offline_client.dart @@ -0,0 +1,366 @@ +import 'package:grpc/grpc.dart'; +import 'package:helpwave_proto_dart/services/tasks_svc/v1/patient_svc.pbgrpc.dart'; +import 'package:helpwave_service/src/api/offline/offline_client_store.dart'; +import 'package:helpwave_service/src/api/offline/util.dart'; +import 'package:helpwave_service/src/api/tasks/data_types/patient.dart'; + +class PatientUpdate { + String id; + String? name; + String? notes; + bool? isDischarged; + + PatientUpdate({required this.id, this.name, this.notes, this.isDischarged}); +} + +class PatientOfflineService { + List patients = []; + + PatientWithBedId? findPatient(String id) { + int index = OfflineClientStore().patientStore.patients.indexWhere((value) => value.id == id); + if (index == -1) { + return null; + } + return patients[index]; + } + + PatientWithBedId? findPatientByBed(String bedId) { + final valueStore = OfflineClientStore().patientStore; + return valueStore.patients.where((value) => value.bedId == bedId).firstOrNull; + } + + void create(PatientWithBedId patient) { + OfflineClientStore().patientStore.patients.add(patient); + } + + void update(PatientUpdate patientUpdate) { + final valueStore = OfflineClientStore().patientStore; + bool found = false; + + valueStore.patients = valueStore.patients.map((value) { + if (value.id == patientUpdate.id) { + found = true; + return value.copyWith( + notes: patientUpdate.notes, + name: patientUpdate.name, + isDischarged: patientUpdate.isDischarged, + ); + } + return value; + }).toList(); + + if (!found) { + throw Exception('UpdatePatient: Could not find patient with id ${patientUpdate.id}'); + } + } + + void assignBed(String patientId, String bedId) { + final valueStore = OfflineClientStore().patientStore; + final bed = OfflineClientStore().bedStore.findBed(bedId); + if (bed != null) { + throw Exception('Could not find bed with id $bedId'); + } + bool found = false; + + valueStore.patients = valueStore.patients.map((value) { + if (value.id == patientId) { + found = true; + return value.copyWith(bedId: bedId); + } + return value; + }).toList(); + + if (!found) { + throw Exception('Could not find patient with id $patientId'); + } + } + + void unassignBed(String patientId) { + final valueStore = OfflineClientStore().patientStore; + bool found = false; + + valueStore.patients = valueStore.patients.map((value) { + if (value.id == patientId) { + found = true; + final copy = value.copyWith(); + copy.bedId = null; + return copy; + } + return value; + }).toList(); + + if (!found) { + throw Exception('Could not find patient with id $patientId'); + } + } + + void delete(String patientId) { + final valueStore = OfflineClientStore().patientStore; + valueStore.patients = valueStore.patients.where((value) => value.id != patientId).toList(); + // TODO: Cascade delete to tasks + } +} + +class PatientServicePromiseClient extends PatientServiceClient { + PatientServicePromiseClient(super.channel); + + @override + ResponseFuture getPatient(GetPatientRequest request, {CallOptions? options}) { + final patient = OfflineClientStore().patientStore.findPatient(request.id); + + if (patient == null) { + throw "Patient with patient id ${request.id} not found"; + } + + final response = GetPatientResponse(id: patient.id, humanReadableIdentifier: patient.name, notes: patient.notes); + + if (patient.bedId == null) { + return MockResponseFuture.value(response); + } + final bed = OfflineClientStore().bedStore.findBed(patient.bedId!); + if (bed == null) { + return MockResponseFuture.value(response); + } + final room = OfflineClientStore().roomStore.findRoom(bed.roomId); + if (room == null) { + return MockResponseFuture.value(response); + } + response.bedId = patient.bedId!; + response.bed = GetPatientResponse_Bed(id: bed.id, name: bed.name); + response.room = GetPatientResponse_Room(id: room.id, name: room.name); + return MockResponseFuture.value(response); + } + + @override + ResponseFuture getPatientDetails(GetPatientDetailsRequest request, + {CallOptions? options}) { + final patient = OfflineClientStore().patientStore.findPatient(request.id); + + if (patient == null) { + throw "Patient with patient id ${request.id} not found"; + } + + final response = GetPatientDetailsResponse( + id: patient.id, + humanReadableIdentifier: patient.name, + notes: patient.notes, + isDischarged: patient.isDischarged, + tasks: [], // TODO tasks + ); + + if (patient.bedId == null) { + return MockResponseFuture.value(response); + } + final bed = OfflineClientStore().bedStore.findBed(patient.bedId!); + if (bed == null) { + return MockResponseFuture.value(response); + } + final room = OfflineClientStore().roomStore.findRoom(bed.roomId); + if (room == null) { + return MockResponseFuture.value(response); + } + response.bed = GetPatientDetailsResponse_Bed(id: bed.id, name: bed.name); + response.room = GetPatientDetailsResponse_Room(id: room.id, name: room.name); + return MockResponseFuture.value(response); + } + + @override + ResponseFuture getPatientByBed(GetPatientByBedRequest request, {CallOptions? options}) { + final patient = OfflineClientStore().patientStore.findPatientByBed(request.bedId); + + if (patient == null) { + throw "Patient with bed id ${request.bedId} not found"; + } + + final response = GetPatientByBedResponse( + id: patient.id, + humanReadableIdentifier: patient.name, + notes: patient.notes, + bedId: patient.bedId, + ); + return MockResponseFuture.value(response); + } + + @override + ResponseFuture getPatientList(GetPatientListRequest request, {CallOptions? options}) { + mapping(patient) { + final res = GetPatientListResponse_Patient( + id: patient.id, + notes: patient.notes, + humanReadableIdentifier: patient.name, + tasks: [], // TODO get tasks + ); + if (patient.bedId == null) { + return res; + } + final bed = OfflineClientStore().bedStore.findBed(patient.bedId!); + if (bed == null) { + return res; + } + final room = OfflineClientStore().roomStore.findRoom(bed.roomId); + if (room == null) { + return res; + } + res.bed = GetPatientListResponse_Bed(id: bed.id, name: bed.name); + res.room = GetPatientListResponse_Room(id: room.id, name: room.name); + return res; + } + + final patients = OfflineClientStore().patientStore.patients; + final active = patients.where((element) => element.hasBed).map(mapping); + final discharged = patients.where((element) => element.isDischarged).map(mapping); + final unassigned = patients.where((element) => !element.isDischarged && element.bedId == null).map(mapping); + final response = GetPatientListResponse( + active: active, + dischargedPatients: discharged, + unassignedPatients: unassigned, + ); + + return MockResponseFuture.value(response); + } + + @override + ResponseFuture getRecentPatients(GetRecentPatientsRequest request, + {CallOptions? options}) { + final patients = OfflineClientStore().patientStore.patients.where((element) => element.hasBed).map((patient) { + final res = GetRecentPatientsResponse_PatientWithRoomAndBed( + id: patient.id, + humanReadableIdentifier: patient.name, + ); + if (patient.bedId == null) { + return res; + } + final bed = OfflineClientStore().bedStore.findBed(patient.bedId!); + if (bed == null) { + return res; + } + final room = OfflineClientStore().roomStore.findRoom(bed.roomId); + if (room == null) { + return res; + } + res.bed = GetRecentPatientsResponse_Bed(id: bed.id, name: bed.name); + res.room = GetRecentPatientsResponse_Room(id: room.id, name: room.name); + return res; + }); + final response = GetRecentPatientsResponse(recentPatients: patients); + + return MockResponseFuture.value(response); + } + + @override + ResponseFuture getPatientsByWard(GetPatientsByWardRequest request, + {CallOptions? options}) { + final rooms = OfflineClientStore().roomStore.findRooms(request.wardId); + final beds = rooms.map((room) => OfflineClientStore().bedStore.findBeds(room.id)).expand((element) => element); + List patients = []; + + for (final bed in beds) { + final patient = OfflineClientStore().patientStore.findPatientByBed(bed.id); + if (patient != null) { + patients.add(GetPatientsByWardResponse_Patient( + id: patient.id, notes: patient.notes, humanReadableIdentifier: patient.name, bedId: patient.bedId)); + } + } + final response = GetPatientsByWardResponse(patients: patients); + + return MockResponseFuture.value(response); + } + + @override + ResponseFuture getPatientAssignmentByWard( + GetPatientAssignmentByWardRequest request, + {CallOptions? options}) { + final rooms = + OfflineClientStore().roomStore.findRooms(request.wardId).map((room) => GetPatientAssignmentByWardResponse_Room( + id: room.id, + name: room.name, + beds: OfflineClientStore().bedStore.findBeds(room.id).map((bed) { + final res = GetPatientAssignmentByWardResponse_Room_Bed(id: bed.id, name: bed.name); + final patient = OfflineClientStore().patientStore.findPatientByBed(bed.id); + if (patient != null) { + res.patient = GetPatientAssignmentByWardResponse_Room_Bed_Patient( + id: patient.id, + name: patient.name, + ); + } + return res; + }), + )); + final response = GetPatientAssignmentByWardResponse(rooms: rooms); + + return MockResponseFuture.value(response); + } + + @override + ResponseFuture createPatient(CreatePatientRequest request, {CallOptions? options}) { + final newPatient = PatientWithBedId( + id: DateTime.now().millisecondsSinceEpoch.toString(), + name: request.humanReadableIdentifier, + notes: request.notes, + isDischarged: false, + ); + + OfflineClientStore().patientStore.create(newPatient); + + final response = CreatePatientResponse()..id = newPatient.id; + + return MockResponseFuture.value(response); + } + + @override + ResponseFuture updatePatient(UpdatePatientRequest request, {CallOptions? options}) { + final update = PatientUpdate( + id: request.id, + name: request.hasHumanReadableIdentifier() ? request.humanReadableIdentifier : null, + notes: request.hasNotes() ? request.notes : null, + ); + + OfflineClientStore().patientStore.update(update); + + final response = UpdatePatientResponse(); + return MockResponseFuture.value(response); + } + + @override + ResponseFuture assignBed(AssignBedRequest request, {CallOptions? options}) { + OfflineClientStore().patientStore.assignBed(request.id, request.bedId); + final response = AssignBedResponse(); + return MockResponseFuture.value(response); + } + + @override + ResponseFuture unassignBed(UnassignBedRequest request, {CallOptions? options}) { + OfflineClientStore().patientStore.unassignBed(request.id); + final response = UnassignBedResponse(); + return MockResponseFuture.value(response); + } + + @override + ResponseFuture dischargePatient(DischargePatientRequest request, {CallOptions? options}) { + final update = PatientUpdate(id: request.id, isDischarged: true); + + OfflineClientStore().patientStore.update(update); + OfflineClientStore().patientStore.unassignBed(request.id); + + final response = DischargePatientResponse(); + return MockResponseFuture.value(response); + } + + @override + ResponseFuture readmitPatient(ReadmitPatientRequest request, {CallOptions? options}) { + final update = PatientUpdate(id: request.patientId, isDischarged: false); + + OfflineClientStore().patientStore.update(update); + + final response = ReadmitPatientResponse(); + return MockResponseFuture.value(response); + } + + @override + ResponseFuture deletePatient(DeletePatientRequest request, {CallOptions? options}) { + OfflineClientStore().patientStore.delete(request.id); + + final response = DeletePatientResponse(); + return MockResponseFuture.value(response); + } +} diff --git a/packages/helpwave_service/lib/src/api/tasks/offline_clients/room_offline_client.dart b/packages/helpwave_service/lib/src/api/tasks/offline_clients/room_offline_client.dart new file mode 100644 index 00000000..34405d0e --- /dev/null +++ b/packages/helpwave_service/lib/src/api/tasks/offline_clients/room_offline_client.dart @@ -0,0 +1,161 @@ +import 'package:grpc/grpc.dart'; +import 'package:helpwave_proto_dart/services/tasks_svc/v1/room_svc.pbgrpc.dart'; +import 'package:helpwave_service/src/api/offline/offline_client_store.dart'; +import 'package:helpwave_service/src/api/offline/util.dart'; +import 'package:helpwave_service/src/api/tasks/data_types/index.dart'; + +class RoomUpdate { + String id; + String? name; + + RoomUpdate({required this.id, required this.name}); +} + +class RoomOfflineService { + List rooms = []; + + RoomWithWardId? findRoom(String id) { + int index = OfflineClientStore().roomStore.rooms.indexWhere((value) => value.id == id); + if (index == -1) { + return null; + } + return rooms[index]; + } + + List findRooms([String? wardId]) { + final valueStore = OfflineClientStore().roomStore; + if (wardId == null) { + return valueStore.rooms; + } + return valueStore.rooms.where((value) => value.wardId == wardId).toList(); + } + + void create(RoomWithWardId room) { + OfflineClientStore().roomStore.rooms.add(room); + } + + void update(RoomUpdate room) { + final valueStore = OfflineClientStore().roomStore; + bool found = false; + + valueStore.rooms = valueStore.rooms.map((value) { + if (value.id == room.id) { + found = true; + return RoomWithWardId(id: room.id, name: room.name ?? value.name, wardId: value.wardId); + } + return value; + }).toList(); + + if (!found) { + throw Exception('UpdateRoom: Could not find room with id ${room.id}'); + } + } + + void delete(String roomId) { + final valueStore = OfflineClientStore().roomStore; + valueStore.rooms = valueStore.rooms.where((value) => value.id != roomId).toList(); + OfflineClientStore().bedStore.findBeds(roomId).forEach((element) { + OfflineClientStore().bedStore.delete(element.id); + }); + } +} + +class RoomServicePromiseClient extends RoomServiceClient { + RoomServicePromiseClient(super.channel); + + @override + ResponseFuture getRoom(GetRoomRequest request, {CallOptions? options}) { + final room = OfflineClientStore().roomStore.findRoom(request.id); + + if (room == null) { + throw "Room with room id ${request.id} not found"; + } + + final response = GetRoomResponse() + ..id = room.id + ..name = room.name + ..wardId = room.wardId; + + return MockResponseFuture.value(response); + } + + @override + ResponseFuture getRooms(GetRoomsRequest request, {CallOptions? options}) { + final rooms = OfflineClientStore().roomStore.findRooms(); + final roomsList = rooms.map((room) => GetRoomsResponse_Room( + id: room.id, + name: room.name, + wardId: room.wardId, + beds: OfflineClientStore().bedStore.findBeds(room.id).map((bed) => GetRoomsResponse_Room_Bed( + id: bed.id, + name: bed.name, + )), + )); + + final response = GetRoomsResponse(rooms: roomsList); + return MockResponseFuture.value(response); + } + + @override + ResponseFuture getRoomOverviewsByWard(GetRoomOverviewsByWardRequest request, + {CallOptions? options}) { + final rooms = OfflineClientStore().roomStore.findRooms(request.id); + + final response = GetRoomOverviewsByWardResponse() + ..rooms.addAll(rooms.map((room) => GetRoomOverviewsByWardResponse_Room() + ..id = room.id + ..name = room.name + ..beds.addAll(OfflineClientStore().bedStore.findBeds(room.id).map((bed) { + final response = GetRoomOverviewsByWardResponse_Room_Bed(id: bed.id, name: bed.name); + final patient = OfflineClientStore().patientStore.findPatientByBed(bed.id); + if (patient != null) { + final tasks = OfflineClientStore().taskStore.findTasks(patient.id); + response.patient = GetRoomOverviewsByWardResponse_Room_Bed_Patient( + id: patient.id, + humanReadableIdentifier: patient.name, + tasksDone: tasks.where((element) => element.status == TaskStatus.done).length, + tasksInProgress: tasks.where((element) => element.status == TaskStatus.inProgress).length, + tasksUnscheduled: tasks.where((element) => element.status == TaskStatus.todo).length, + ); + } + return response; + })))); + return MockResponseFuture.value(response); + } + + @override + ResponseFuture createRoom(CreateRoomRequest request, {CallOptions? options}) { + final newRoom = RoomWithWardId( + id: DateTime.now().millisecondsSinceEpoch.toString(), + name: request.name, + wardId: request.wardId, + ); + + OfflineClientStore().roomStore.create(newRoom); + + final response = CreateRoomResponse()..id = newRoom.id; + + return MockResponseFuture.value(response); + } + + @override + ResponseFuture updateRoom(UpdateRoomRequest request, {CallOptions? options}) { + final update = RoomUpdate( + id: request.id, + name: request.name, + ); + + OfflineClientStore().roomStore.update(update); + + final response = UpdateRoomResponse(); + return MockResponseFuture.value(response); + } + + @override + ResponseFuture deleteRoom(DeleteRoomRequest request, {CallOptions? options}) { + OfflineClientStore().roomStore.delete(request.id); + + final response = DeleteRoomResponse(); + return MockResponseFuture.value(response); + } +} diff --git a/packages/helpwave_service/lib/src/api/tasks/offline_clients/task_offline_client.dart b/packages/helpwave_service/lib/src/api/tasks/offline_clients/task_offline_client.dart new file mode 100644 index 00000000..86fb98ef --- /dev/null +++ b/packages/helpwave_service/lib/src/api/tasks/offline_clients/task_offline_client.dart @@ -0,0 +1,445 @@ +import 'package:grpc/grpc.dart'; +import 'package:helpwave_proto_dart/google/protobuf/timestamp.pb.dart'; +import 'package:helpwave_proto_dart/services/tasks_svc/v1/task_svc.pbgrpc.dart'; +import 'package:helpwave_service/src/api/offline/offline_client_store.dart'; +import 'package:helpwave_service/src/api/offline/util.dart'; +import 'package:helpwave_service/src/api/tasks/index.dart'; +import 'package:helpwave_service/src/api/tasks/util/task_status_mapping.dart'; + +class TaskUpdate { + String id; + String? name; + String? notes; + TaskStatus? status; + bool? isPublicVisible; + DateTime? dueDate; + + TaskUpdate({required this.id, this.name, this.notes, this.status, this.isPublicVisible, this.dueDate}); +} + +class SubtaskUpdate { + String id; + bool? isDone; + String? name; + + SubtaskUpdate({required this.id, this.name, this.isDone}); +} + +class TaskOfflineService { + List tasks = []; + + Task? findTask(String id) { + int index = OfflineClientStore().taskStore.tasks.indexWhere((value) => value.id == id); + if (index == -1) { + return null; + } + return tasks[index]; + } + + List findTasks([String? patientId]) { + final valueStore = OfflineClientStore().taskStore; + if (patientId == null) { + return valueStore.tasks; + } + return valueStore.tasks.where((value) => value.patientId == patientId).toList(); + } + + void create(Task task) { + OfflineClientStore().taskStore.tasks.add(task); + } + + void update(TaskUpdate taskUpdate) { + final valueStore = OfflineClientStore().taskStore; + bool found = false; + + valueStore.tasks = valueStore.tasks.map((value) { + if (value.id == taskUpdate.id) { + found = true; + return value.copyWith( + name: taskUpdate.name, + notes: taskUpdate.notes, + status: taskUpdate.status, + isPublicVisible: taskUpdate.isPublicVisible, + dueDate: taskUpdate.dueDate, + ); + } + return value; + }).toList(); + + if (!found) { + throw Exception('UpdateTask: Could not find task with id ${taskUpdate.id}'); + } + } + + void removeDueDate(String taskId) { + final valueStore = OfflineClientStore().taskStore; + bool found = false; + + valueStore.tasks = valueStore.tasks.map((value) { + if (value.id == taskId) { + found = true; + final copy = value.copyWith(); + copy.dueDate = null; + return copy; + } + return value; + }).toList(); + + if (!found) { + throw Exception('Could not find task with id $taskId'); + } + } + + assignUser(String taskId, String assigneeId) { + final user = OfflineClientStore().userStore.find(assigneeId); + if (user == null) { + throw "Could not find user with id $assigneeId"; + } + final valueStore = OfflineClientStore().taskStore; + bool found = false; + + valueStore.tasks = valueStore.tasks.map((value) { + if (value.id == taskId) { + found = true; + return value.copyWith(assigneeId: assigneeId); + } + return value; + }).toList(); + + if (!found) { + throw Exception('Could not find task with id $taskId'); + } + } + + unassignUser(String taskId, String assigneeId) { + final valueStore = OfflineClientStore().taskStore; + bool found = false; + + valueStore.tasks = valueStore.tasks.map((value) { + if (value.id == taskId) { + found = true; + final copy = value.copyWith(); + copy.assigneeId = null; + return copy; + } + return value; + }).toList(); + + if (!found) { + throw Exception('Could not find task with id $taskId'); + } + } + + void delete(String taskId) { + final valueStore = OfflineClientStore().taskStore; + valueStore.tasks = valueStore.tasks.where((value) => value.id != taskId).toList(); + OfflineClientStore().subtaskStore.findSubtasks(taskId).forEach((subtask) { + OfflineClientStore().subtaskStore.delete(subtask.id); + }); + } +} + +class SubtaskOfflineService { + List subtasks = []; + + Subtask? findSubtask(String id) { + int index = OfflineClientStore().subtaskStore.subtasks.indexWhere((value) => value.id == id); + if (index == -1) { + return null; + } + return subtasks[index]; + } + + List findSubtasks([String? taskId]) { + final valueStore = OfflineClientStore().subtaskStore; + if (taskId == null) { + return valueStore.subtasks; + } + return valueStore.subtasks.where((value) => value.taskId == taskId).toList(); + } + + void create(Subtask subtask) { + OfflineClientStore().subtaskStore.subtasks.add(subtask); + } + + void update(SubtaskUpdate subtaskUpdate) { + final valueStore = OfflineClientStore().subtaskStore; + bool found = false; + + valueStore.subtasks = valueStore.subtasks.map((value) { + if (value.id == subtaskUpdate.id) { + found = true; + return value.copyWith(name: subtaskUpdate.name, isDone: subtaskUpdate.isDone); + } + return value; + }).toList(); + + if (!found) { + throw Exception('UpdateSubtask: Could not find subtask with id ${subtaskUpdate.id}'); + } + } + + void delete(String subtaskId) { + final valueStore = OfflineClientStore().subtaskStore; + valueStore.subtasks = valueStore.subtasks.where((value) => value.id != subtaskId).toList(); + } +} + +class TaskServicePromiseClient extends TaskServiceClient { + TaskServicePromiseClient(super.channel); + + @override + ResponseFuture getTask(GetTaskRequest request, {CallOptions? options}) { + final task = OfflineClientStore().taskStore.findTask(request.id); + + if (task == null) { + throw "Task with task id ${request.id} not found"; + } + + final patient = OfflineClientStore().patientStore.findPatient(task.patientId); + if (patient == null) { + throw "Inconsistency error: Patient with patient id ${task.patientId} not found"; + } + + final subtasks = OfflineClientStore() + .subtaskStore + .findSubtasks(task.id) + .map((subtask) => GetTaskResponse_SubTask(id: subtask.id, name: subtask.name, done: subtask.isDone)); + + final response = GetTaskResponse( + id: task.id, + name: task.name, + description: task.notes, + status: GRPCTypeConverter.taskStatusToGRPC(task.status), + dueAt: task.dueDate == null ? null : Timestamp.fromDateTime(task.dueDate!), + createdBy: task.createdBy, + createdAt: task.creationDate == null ? null : Timestamp.fromDateTime(task.creationDate!), + public: task.isPublicVisible, + assignedUserId: task.assigneeId, + patient: GetTaskResponse_Patient(id: patient.id, humanReadableIdentifier: patient.name), + subtasks: subtasks); + + return MockResponseFuture.value(response); + } + + @override + ResponseFuture getTasksByPatient(GetTasksByPatientRequest request, + {CallOptions? options}) { + final tasks = + OfflineClientStore().taskStore.findTasks(request.patientId).map((task) => GetTasksByPatientResponse_Task( + id: task.id, + name: task.name, + description: task.notes, + status: GRPCTypeConverter.taskStatusToGRPC(task.status), + dueAt: task.dueDate == null ? null : Timestamp.fromDateTime(task.dueDate!), + createdBy: task.createdBy, + createdAt: task.creationDate == null ? null : Timestamp.fromDateTime(task.creationDate!), + public: task.isPublicVisible, + assignedUserId: task.assigneeId, + patientId: request.patientId, + subtasks: OfflineClientStore() + .subtaskStore + .findSubtasks(task.id) + .map((subtask) => GetTasksByPatientResponse_Task_SubTask( + id: subtask.id, + name: subtask.name, + done: subtask.isDone, + )), + )); + + final response = GetTasksByPatientResponse(tasks: tasks); + + return MockResponseFuture.value(response); + } + + @override + ResponseFuture getAssignedTasks(GetAssignedTasksRequest request, {CallOptions? options}) { + final user = OfflineClientStore().userStore.users[0]; + final tasks = OfflineClientStore().taskStore.findTasks().where((task) => task.assigneeId == user.id).map((task) { + final res = GetAssignedTasksResponse_Task( + id: task.id, + name: task.name, + description: task.notes, + status: GRPCTypeConverter.taskStatusToGRPC(task.status), + dueAt: task.dueDate == null ? null : Timestamp.fromDateTime(task.dueDate!), + createdBy: task.createdBy, + createdAt: task.creationDate == null ? null : Timestamp.fromDateTime(task.creationDate!), + public: task.isPublicVisible, + assignedUserId: task.assigneeId, + subtasks: OfflineClientStore() + .subtaskStore + .findSubtasks(task.id) + .map((subtask) => GetAssignedTasksResponse_Task_SubTask( + id: subtask.id, + name: subtask.name, + done: subtask.isDone, + )), + ); + final patient = OfflineClientStore().patientStore.findPatient(task.patientId); + if (patient == null) { + throw "Inconsistency error: patient with id ${task.patientId} not found"; + } + res.patient = GetAssignedTasksResponse_Task_Patient(id: patient.id, humanReadableIdentifier: patient.name); + return res; + }); + + final response = GetAssignedTasksResponse(tasks: tasks); + + return MockResponseFuture.value(response); + } + + @override + ResponseFuture getTasksByPatientSortedByStatus( + GetTasksByPatientSortedByStatusRequest request, + {CallOptions? options}) { + mapping(task) => GetTasksByPatientSortedByStatusResponse_Task( + id: task.id, + name: task.name, + description: task.notes, + dueAt: task.dueDate == null ? null : Timestamp.fromDateTime(task.dueDate!), + createdBy: task.createdBy, + createdAt: task.creationDate == null ? null : Timestamp.fromDateTime(task.creationDate!), + public: task.isPublicVisible, + assignedUserId: task.assigneeId, + patientId: request.patientId, + subtasks: OfflineClientStore() + .subtaskStore + .findSubtasks(task.id) + .map((subtask) => GetTasksByPatientSortedByStatusResponse_Task_SubTask( + id: subtask.id, + name: subtask.name, + done: subtask.isDone, + )), + ); + + final tasks = OfflineClientStore().taskStore.findTasks(request.patientId); + + final response = GetTasksByPatientSortedByStatusResponse( + done: tasks.where((element) => element.status == TaskStatus.done).map(mapping), + inProgress: tasks.where((element) => element.status == TaskStatus.inProgress).map(mapping), + todo: tasks.where((element) => element.status == TaskStatus.todo).map(mapping), + ); + + return MockResponseFuture.value(response); + } + + @override + ResponseFuture createTask(CreateTaskRequest request, {CallOptions? options}) { + final patient = OfflineClientStore().patientStore.findPatient(request.patientId); + if (patient == null) { + throw "Patient with id ${request.patientId} not found"; + } + final newTask = Task( + id: DateTime.now().millisecondsSinceEpoch.toString(), + name: request.name, + notes: request.description, + patientId: request.patientId, + creationDate: DateTime.now(), + createdBy: OfflineClientStore().userStore.users[0].id, + dueDate: request.hasDueAt() ? request.dueAt.toDateTime() : null, + status: GRPCTypeConverter.taskStatusFromGRPC(request.initialStatus), + isPublicVisible: request.public, + assigneeId: request.assignedUserId, + ); + + OfflineClientStore().taskStore.create(newTask); + for (var subtask in request.subtasks) { + OfflineClientStore().subtaskStore.create(Subtask( + id: DateTime.now().millisecondsSinceEpoch.toString(), + taskId: newTask.id, + name: subtask.name, + isDone: subtask.done, + )); + } + + final response = CreateTaskResponse()..id = newTask.id; + + return MockResponseFuture.value(response); + } + + @override + ResponseFuture updateTask(UpdateTaskRequest request, {CallOptions? options}) { + final update = TaskUpdate( + id: request.id, + name: request.name, + status: GRPCTypeConverter.taskStatusFromGRPC(request.status), + isPublicVisible: request.public, + notes: request.description, + dueDate: request.hasDueAt() ? request.dueAt.toDateTime() : null, + ); + + OfflineClientStore().taskStore.update(update); + + final response = UpdateTaskResponse(); + return MockResponseFuture.value(response); + } + + @override + ResponseFuture assignTask(AssignTaskRequest request, {CallOptions? options}) { + OfflineClientStore().taskStore.assignUser(request.taskId, request.userId); + final response = AssignTaskResponse(); + return MockResponseFuture.value(response); + } + + @override + ResponseFuture unassignTask(UnassignTaskRequest request, {CallOptions? options}) { + OfflineClientStore().taskStore.unassignUser(request.taskId, request.userId); + final response = UnassignTaskResponse(); + return MockResponseFuture.value(response); + } + + @override + ResponseFuture removeTaskDueDate(RemoveTaskDueDateRequest request, + {CallOptions? options}) { + OfflineClientStore().taskStore.removeDueDate(request.taskId); + final response = RemoveTaskDueDateResponse(); + return MockResponseFuture.value(response); + } + + @override + ResponseFuture deleteTask(DeleteTaskRequest request, {CallOptions? options}) { + OfflineClientStore().taskStore.delete(request.id); + + final response = DeleteTaskResponse(); + return MockResponseFuture.value(response); + } + + @override + ResponseFuture createSubtask(CreateSubtaskRequest request, {CallOptions? options}) { + final task = OfflineClientStore().taskStore.findTask(request.taskId); + if (task == null) { + throw "Task with id ${request.taskId} not found"; + } + final subtask = Subtask( + id: DateTime.now().millisecondsSinceEpoch.toString(), + taskId: request.taskId, + name: request.subtask.name, + isDone: request.subtask.done); + + OfflineClientStore().subtaskStore.create(subtask); + final response = CreateSubtaskResponse()..subtaskId = subtask.id; + return MockResponseFuture.value(response); + } + + @override + ResponseFuture updateSubtask(UpdateSubtaskRequest request, {CallOptions? options}) { + final requestSubtask = request.subtask; + final update = SubtaskUpdate( + id: request.subtaskId, + isDone: requestSubtask.hasDone() ? requestSubtask.done : null, + name: requestSubtask.hasName() ? requestSubtask.name : null, + ); + OfflineClientStore().subtaskStore.update(update); + + final response = UpdateSubtaskResponse(); + return MockResponseFuture.value(response); + } + + @override + ResponseFuture deleteSubtask(DeleteSubtaskRequest request, {CallOptions? options}) { + OfflineClientStore().subtaskStore.delete(request.subtaskId); + + final response = DeleteSubtaskResponse(); + return MockResponseFuture.value(response); + } +} diff --git a/packages/helpwave_service/lib/src/api/tasks/offline_clients/template_offline_client.dart b/packages/helpwave_service/lib/src/api/tasks/offline_clients/template_offline_client.dart new file mode 100644 index 00000000..3479128a --- /dev/null +++ b/packages/helpwave_service/lib/src/api/tasks/offline_clients/template_offline_client.dart @@ -0,0 +1,241 @@ +import 'package:grpc/grpc.dart'; +import 'package:helpwave_proto_dart/services/tasks_svc/v1/task_template_svc.pbgrpc.dart'; +import 'package:helpwave_service/src/api/offline/offline_client_store.dart'; +import 'package:helpwave_service/src/api/offline/util.dart'; +import 'package:helpwave_service/src/api/tasks/data_types/index.dart'; + +class TaskTemplateUpdate { + String id; + String? name; + String? notes; + + TaskTemplateUpdate({required this.id, this.name, this.notes}); +} + +class TaskSubtaskTemplateUpdate { + String id; + String? name; + + TaskSubtaskTemplateUpdate({required this.id, this.name}); +} + +class TaskTemplateOfflineService { + List taskTemplates = []; + + TaskTemplate? findTaskTemplate(String id) { + int index = taskTemplates.indexWhere((value) => value.id == id); + if (index == -1) { + return null; + } + return taskTemplates[index]; + } + + List findTaskTemplates([String? wardId]) { + if (wardId == null) { + return taskTemplates; + } + return taskTemplates.where((value) => value.wardId == wardId).toList(); + } + + void create(TaskTemplate taskTemplate) { + taskTemplates.add(taskTemplate); + } + + void update(TaskTemplateUpdate taskTemplateUpdate) { + bool found = false; + + taskTemplates = taskTemplates.map((value) { + if (value.id == taskTemplateUpdate.id) { + found = true; + return value.copyWith( + name: taskTemplateUpdate.name, + notes: taskTemplateUpdate.notes, + ); + } + return value; + }).toList(); + + if (!found) { + throw Exception('UpdateTaskTemplate: Could not find task with id ${taskTemplateUpdate.id}'); + } + } + + void delete(String taskId) { + taskTemplates = taskTemplates.where((value) => value.id != taskId).toList(); + OfflineClientStore().taskTemplateSubtaskStore.findTemplateSubtasks(taskId).forEach((templateSubtask) { + OfflineClientStore().taskTemplateSubtaskStore.delete(templateSubtask.id); + }); + } +} + +class TaskTemplateSubtaskOfflineService { + List taskTemplateSubtasks = []; + + Subtask? findTemplateSubtask(String id) { + int index = taskTemplateSubtasks.indexWhere((value) => value.id == id); + if (index == -1) { + return null; + } + return taskTemplateSubtasks[index]; + } + + List findTemplateSubtasks([String? taskTemplateId]) { + if (taskTemplateId == null) { + return taskTemplateSubtasks; + } + return taskTemplateSubtasks.where((value) => value.taskId == taskTemplateId).toList(); + } + + void create(Subtask templateSubtask) { + taskTemplateSubtasks.add(templateSubtask); + } + + void update(TaskSubtaskTemplateUpdate templateSubtaskUpdate) { + bool found = false; + + taskTemplateSubtasks = taskTemplateSubtasks.map((value) { + if (value.id == templateSubtaskUpdate.id) { + found = true; + return value.copyWith(name: templateSubtaskUpdate.name); + } + return value; + }).toList(); + + if (!found) { + throw Exception('UpdateTemplateSubtask: Could not find templateSubtask with id ${templateSubtaskUpdate.id}'); + } + } + + void delete(String templateSubtaskId) { + taskTemplateSubtasks = taskTemplateSubtasks.where((value) => value.id != templateSubtaskId).toList(); + } +} + +class TaskTemplateServicePromiseClient extends TaskTemplateServiceClient { + TaskTemplateServicePromiseClient(super.channel); + + @override + ResponseFuture getAllTaskTemplates(GetAllTaskTemplatesRequest request, + {CallOptions? options}) { + final user = OfflineClientStore().userStore.users[0]; + final templates = OfflineClientStore().taskTemplateStore.taskTemplates.where((template) { + if (request.hasWardId() && template.wardId != request.wardId) { + return false; + } + if (request.hasCreatedBy() && template.createdBy != request.createdBy) { + return false; + } + if (request.privateOnly && template.createdBy != user.id) { + return false; + } + return true; + }); + + final response = GetAllTaskTemplatesResponse( + templates: templates.map( + (template) => GetAllTaskTemplatesResponse_TaskTemplate( + id: template.id, + name: template.name, + createdBy: template.createdBy, + description: template.notes, + isPublic: template.isPublicVisible, + subtasks: OfflineClientStore() + .taskTemplateSubtaskStore + .findTemplateSubtasks(template.id) + .map((taskTemplateSubtask) => GetAllTaskTemplatesResponse_TaskTemplate_SubTask( + id: taskTemplateSubtask.id, + name: taskTemplateSubtask.name, + taskTemplateId: taskTemplateSubtask.taskId, + ))), + )); + return MockResponseFuture.value(response); + } + + @override + ResponseFuture createTaskTemplate(CreateTaskTemplateRequest request, + {CallOptions? options}) { + final newTaskTemplate = TaskTemplate( + id: DateTime.now().millisecondsSinceEpoch.toString(), + name: request.name, + notes: request.description, + wardId: request.hasWardId() ? request.wardId : null, + createdBy: OfflineClientStore().userStore.users[0].id, + ); + + OfflineClientStore().taskTemplateStore.create(newTaskTemplate); + for (var templateSubtask in request.subtasks) { + OfflineClientStore().taskTemplateSubtaskStore.create(Subtask( + id: DateTime.now().millisecondsSinceEpoch.toString(), + taskId: newTaskTemplate.id, + name: templateSubtask.name, + isDone: false, + )); + } + + final response = CreateTaskTemplateResponse()..id = newTaskTemplate.id; + + return MockResponseFuture.value(response); + } + + @override + ResponseFuture updateTaskTemplate(UpdateTaskTemplateRequest request, + {CallOptions? options}) { + final update = TaskTemplateUpdate( + id: request.id, + name: request.hasName() ? request.name : null, + ); + + OfflineClientStore().taskTemplateStore.update(update); + + final response = UpdateTaskTemplateResponse(); + return MockResponseFuture.value(response); + } + + @override + ResponseFuture deleteTaskTemplate(DeleteTaskTemplateRequest request, + {CallOptions? options}) { + OfflineClientStore().taskStore.delete(request.id); + + final response = DeleteTaskTemplateResponse(); + return MockResponseFuture.value(response); + } + + @override + ResponseFuture createTaskTemplateSubTask(CreateTaskTemplateSubTaskRequest request, + {CallOptions? options}) { + final task = OfflineClientStore().taskTemplateStore.findTaskTemplate(request.taskTemplateId); + if (task == null) { + throw "TaskTemplate with id ${request.taskTemplateId} not found"; + } + final templateSubtask = Subtask( + id: DateTime.now().millisecondsSinceEpoch.toString(), + taskId: request.taskTemplateId, + name: request.name, + isDone: false, + ); + + OfflineClientStore().taskTemplateSubtaskStore.create(templateSubtask); + final response = CreateTaskTemplateSubTaskResponse()..id = templateSubtask.id; + return MockResponseFuture.value(response); + } + + @override + ResponseFuture updateTaskTemplateSubTask(UpdateTaskTemplateSubTaskRequest request, {CallOptions? options}) { + final update = TaskSubtaskTemplateUpdate( + id: request.subtaskId, + name: request.hasName() ? request.name : null, + ); + OfflineClientStore().taskTemplateSubtaskStore.update(update); + + final response = UpdateTaskTemplateSubTaskResponse(); + return MockResponseFuture.value(response); + } + + @override + ResponseFuture deleteTaskTemplateSubTask(DeleteTaskTemplateSubTaskRequest request, {CallOptions? options}) { + OfflineClientStore().taskTemplateSubtaskStore.delete(request.id); + + final response = DeleteTaskTemplateSubTaskResponse(); + return MockResponseFuture.value(response); + } +} diff --git a/packages/helpwave_service/lib/src/api/tasks/offline_clients/ward_offline_client.dart b/packages/helpwave_service/lib/src/api/tasks/offline_clients/ward_offline_client.dart new file mode 100644 index 00000000..b2d5648d --- /dev/null +++ b/packages/helpwave_service/lib/src/api/tasks/offline_clients/ward_offline_client.dart @@ -0,0 +1,162 @@ +import 'package:grpc/grpc.dart'; +import 'package:helpwave_proto_dart/services/tasks_svc/v1/ward_svc.pbgrpc.dart'; +import 'package:helpwave_service/src/api/offline/offline_client_store.dart'; +import 'package:helpwave_service/src/api/offline/util.dart'; +import 'package:helpwave_service/src/api/tasks/index.dart'; + +class WardUpdate { + String id; + String? name; + + WardUpdate({required this.id, required this.name}); +} + +class WardOfflineService { + List wards = []; + + Ward? findWard(String id) { + int index = OfflineClientStore().wardStore.wards.indexWhere((value) => value.id == id); + if (index == -1) { + return null; + } + return wards[index]; + } + + List findWards([String? organizationId]) { + final valueStore = OfflineClientStore().wardStore; + if (organizationId == null) { + return valueStore.wards; + } + return valueStore.wards.where((value) => value.organizationId == organizationId).toList(); + } + + void create(Ward ward) { + OfflineClientStore().wardStore.wards.add(ward); + } + + void update(WardUpdate ward) { + final valueStore = OfflineClientStore().wardStore; + bool found = false; + + valueStore.wards = valueStore.wards.map((value) { + if (value.id == ward.id) { + found = true; + return Ward(id: ward.id, name: ward.name ?? value.name, organizationId: value.organizationId); + } + return value; + }).toList(); + + if (!found) { + throw Exception('UpdateWard: Could not find ward with id ${ward.id}'); + } + } + + void delete(String wardId) { + final valueStore = OfflineClientStore().wardStore; + valueStore.wards = valueStore.wards.where((value) => value.id != wardId).toList(); + OfflineClientStore().roomStore.findRooms(wardId).forEach((element) { + OfflineClientStore().roomStore.delete(element.id); + }); + // TODO delete ward templates + } +} + +class WardServicePromiseClient extends WardServiceClient { + WardServicePromiseClient(super.channel); + + @override + ResponseFuture getWard(GetWardRequest request, {CallOptions? options}) { + final ward = OfflineClientStore().wardStore.findWard(request.id); + + if (ward == null) { + throw "Ward with ward id ${request.id} not found"; + } + + final response = GetWardResponse() + ..id = ward.id + ..name = ward.name; + + return MockResponseFuture.value(response); + } + + @override + ResponseFuture getWardDetails(GetWardDetailsRequest request, {CallOptions? options}) { + final ward = OfflineClientStore().wardStore.findWard(request.id); + + if (ward == null) { + throw "Ward with ward id ${request.id} not found"; + } + + final rooms = OfflineClientStore().roomStore.findRooms(ward.id).map((room) { + final beds = OfflineClientStore() + .bedStore + .findBeds(room.id) + .map((bed) => GetWardDetailsResponse_Bed(id: bed.id, name: bed.name)) + .toList(); + + return GetWardDetailsResponse_Room() + ..id = room.id + ..name = room.name + ..beds.addAll(beds); + }).toList(); + + final response = GetWardDetailsResponse( + id: ward.id, + name: ward.name, + rooms: rooms, + // TODO taskTemplates: + ); + + return MockResponseFuture.value(response); + } + + @override + ResponseFuture getWards(GetWardsRequest request, {CallOptions? options}) { + final wards = OfflineClientStore().wardStore.findWards(); + final wardsList = wards + .map((ward) => GetWardsResponse_Ward() + ..id = ward.id + ..name = ward.name) + .toList(); + + final response = GetWardsResponse()..wards.addAll(wardsList); + + return MockResponseFuture.value(response); + } + + @override + ResponseFuture createWard(CreateWardRequest request, {CallOptions? options}) { + final newWard = Ward( + id: DateTime.now().millisecondsSinceEpoch.toString(), + name: request.name, + organizationId: 'organization', // TODO: Check organization + ); + + OfflineClientStore().wardStore.create(newWard); + + final response = CreateWardResponse()..id = newWard.id; + + return MockResponseFuture.value(response); + } + + @override + ResponseFuture updateWard(UpdateWardRequest request, {CallOptions? options}) { + final update = WardUpdate( + id: request.id, + name: request.name, + ); + + OfflineClientStore().wardStore.update(update); + + final response = UpdateWardResponse(); + return MockResponseFuture.value(response); + } + + @override + ResponseFuture deleteWard(DeleteWardRequest request, {CallOptions? options}) { + OfflineClientStore().wardStore.delete(request.id); + + final response = DeleteWardResponse(); + return MockResponseFuture.value(response); + } +} diff --git a/packages/helpwave_service/lib/src/api/tasks/services/patient_svc.dart b/packages/helpwave_service/lib/src/api/tasks/services/patient_svc.dart index c0c60d94..acfc6674 100644 --- a/packages/helpwave_service/lib/src/api/tasks/services/patient_svc.dart +++ b/packages/helpwave_service/lib/src/api/tasks/services/patient_svc.dart @@ -7,10 +7,10 @@ import 'package:helpwave_service/src/api/tasks/util/task_status_mapping.dart'; /// The GRPC Service for [Patient]s /// /// Provides queries and requests that load or alter [Patient] objects on the server -/// The server is defined in the underlying [TasksAPIServices] +/// The server is defined in the underlying [TasksAPIServiceClients] class PatientService { /// The GRPC ServiceClient which handles GRPC - PatientServiceClient patientService = TasksAPIServices.patientServiceClient; + PatientServiceClient patientService = TasksAPIServiceClients.patientServiceClient; // TODO consider an enum instead of an string /// Loads the [Patient]s by [Ward] and sorts them by their assignment status @@ -19,7 +19,7 @@ class PatientService { GetPatientListResponse response = await patientService.getPatientList( request, options: CallOptions( - metadata: TasksAPIServices().getMetaData(), + metadata: TasksAPIServiceClients().getMetaData(), ), ); @@ -36,14 +36,16 @@ class PatientService { notes: task.description, status: GRPCTypeConverter.taskStatusFromGRPC(task.status), isPublicVisible: task.public, - assignee: task.assignedUserId, + assigneeId: task.assignedUserId, subtasks: task.subtasks .map((subtask) => Subtask( id: subtask.id, name: subtask.name, isDone: subtask.done, + taskId: task.id )) .toList(), + patientId: patient.id, // TODO due and creation date )) .toList(), @@ -67,7 +69,7 @@ class PatientService { notes: task.description, status: GRPCTypeConverter.taskStatusFromGRPC(task.status), isPublicVisible: task.public, - assignee: task.assignedUserId, + assigneeId: task.assignedUserId, subtasks: task.subtasks .map((subtask) => Subtask( id: subtask.id, @@ -96,7 +98,7 @@ class PatientService { notes: task.description, status: GRPCTypeConverter.taskStatusFromGRPC(task.status), isPublicVisible: task.public, - assignee: task.assignedUserId, + assigneeId: task.assignedUserId, subtasks: task.subtasks .map((subtask) => Subtask( id: subtask.id, @@ -126,7 +128,7 @@ class PatientService { GetPatientResponse response = await patientService.getPatient( request, options: CallOptions( - metadata: TasksAPIServices().getMetaData(), + metadata: TasksAPIServiceClients().getMetaData(), ), ); @@ -143,7 +145,7 @@ class PatientService { GetPatientDetailsResponse response = await patientService.getPatientDetails( request, options: CallOptions( - metadata: TasksAPIServices().getMetaData(), + metadata: TasksAPIServiceClients().getMetaData(), ), ); @@ -157,7 +159,7 @@ class PatientService { id: task.id, name: task.name, notes: task.description, - assignee: task.assignedUserId, + assigneeId: task.assignedUserId, status: GRPCTypeConverter.taskStatusFromGRPC(task.status), isPublicVisible: task.public, subtasks: task.subtasks @@ -179,7 +181,7 @@ class PatientService { GetPatientAssignmentByWardResponse response = await patientService.getPatientAssignmentByWard( request, options: CallOptions( - metadata: TasksAPIServices().getMetaData(), + metadata: TasksAPIServiceClients().getMetaData(), ), ); @@ -207,7 +209,7 @@ class PatientService { ); CreatePatientResponse response = await patientService.createPatient( request, - options: CallOptions(metadata: TasksAPIServices().getMetaData()), + options: CallOptions(metadata: TasksAPIServiceClients().getMetaData()), ); return response.id; @@ -222,7 +224,7 @@ class PatientService { ); UpdatePatientResponse response = await patientService.updatePatient( request, - options: CallOptions(metadata: TasksAPIServices().getMetaData()), + options: CallOptions(metadata: TasksAPIServiceClients().getMetaData()), ); if (response.isInitialized()) { @@ -237,7 +239,7 @@ class PatientService { DischargePatientRequest request = DischargePatientRequest(id: patientId); DischargePatientResponse response = await patientService.dischargePatient( request, - options: CallOptions(metadata: TasksAPIServices().getMetaData()), + options: CallOptions(metadata: TasksAPIServiceClients().getMetaData()), ); if (response.isInitialized()) { @@ -251,7 +253,7 @@ class PatientService { UnassignBedRequest request = UnassignBedRequest(id: patientId); UnassignBedResponse response = await patientService.unassignBed( request, - options: CallOptions(metadata: TasksAPIServices().getMetaData()), + options: CallOptions(metadata: TasksAPIServiceClients().getMetaData()), ); if (response.isInitialized()) { @@ -265,7 +267,7 @@ class PatientService { AssignBedRequest request = AssignBedRequest(id: patientId, bedId: bedId); AssignBedResponse response = await patientService.assignBed( request, - options: CallOptions(metadata: TasksAPIServices().getMetaData()), + options: CallOptions(metadata: TasksAPIServiceClients().getMetaData()), ); if (response.isInitialized()) { diff --git a/packages/helpwave_service/lib/src/api/tasks/services/room_svc.dart b/packages/helpwave_service/lib/src/api/tasks/services/room_svc.dart index ca4f3d3b..859a9d97 100644 --- a/packages/helpwave_service/lib/src/api/tasks/services/room_svc.dart +++ b/packages/helpwave_service/lib/src/api/tasks/services/room_svc.dart @@ -1,21 +1,21 @@ import 'package:grpc/grpc.dart'; import 'package:helpwave_proto_dart/services/tasks_svc/v1/room_svc.pbgrpc.dart'; import 'package:helpwave_service/src/api/tasks/data_types/index.dart'; -import 'package:helpwave_service/src/api/tasks/tasks_api_services.dart'; +import 'package:helpwave_service/src/api/tasks/tasks_api_service_clients.dart'; /// The GRPC Service for [Room]s /// /// Provides queries and requests that load or alter [Room] objects on the server -/// The server is defined in the underlying [TasksAPIServices] +/// The server is defined in the underlying [TasksAPIServiceClients] class RoomService { /// The GRPC ServiceClient which handles GRPC - RoomServiceClient roomService = TasksAPIServices.roomServiceClient; + RoomServiceClient roomService = TasksAPIServiceClients.roomServiceClient; Future> getRoomOverviews({required String wardId}) async { GetRoomOverviewsByWardRequest request = GetRoomOverviewsByWardRequest(id: wardId); GetRoomOverviewsByWardResponse response = await roomService.getRoomOverviewsByWard( request, - options: CallOptions(metadata: TasksAPIServices().getMetaData()), + options: CallOptions(metadata: TasksAPIServiceClients().getMetaData()), ); List rooms = response.rooms diff --git a/packages/helpwave_service/lib/src/api/tasks/services/task_svc.dart b/packages/helpwave_service/lib/src/api/tasks/services/task_svc.dart index 3d2cf292..3c9969ae 100644 --- a/packages/helpwave_service/lib/src/api/tasks/services/task_svc.dart +++ b/packages/helpwave_service/lib/src/api/tasks/services/task_svc.dart @@ -7,17 +7,17 @@ import '../util/task_status_mapping.dart'; /// The GRPC Service for [Task]s /// /// Provides queries and requests that load or alter [Task] objects on the server -/// The server is defined in the underlying [TasksAPIServices] +/// The server is defined in the underlying [TasksAPIServiceClients] class TaskService { /// The GRPC ServiceClient which handles GRPC - TaskServiceClient taskService = TasksAPIServices.taskServiceClient; + TaskServiceClient taskService = TasksAPIServiceClients.taskServiceClient; /// Loads the [Task]s by a [Patient] identifier Future> getTasksByPatient({String? patientId}) async { GetTasksByPatientRequest request = GetTasksByPatientRequest(patientId: patientId); GetTasksByPatientResponse response = await taskService.getTasksByPatient( request, - options: CallOptions(metadata: TasksAPIServices().getMetaData()), + options: CallOptions(metadata: TasksAPIServiceClients().getMetaData()), ); return response.tasks @@ -27,7 +27,7 @@ class TaskService { notes: task.description, isPublicVisible: task.public, status: GRPCTypeConverter.taskStatusFromGRPC(task.status), - assignee: task.assignedUserId, + assigneeId: task.assignedUserId, dueDate: task.dueAt.toDateTime(), subtasks: task.subtasks .map((subtask) => Subtask( @@ -45,7 +45,7 @@ class TaskService { GetTaskRequest request = GetTaskRequest(id: id); GetTaskResponse response = await taskService.getTask( request, - options: CallOptions(metadata: TasksAPIServices().getMetaData()), + options: CallOptions(metadata: TasksAPIServiceClients().getMetaData()), ); return TaskWithPatient( @@ -78,7 +78,7 @@ class TaskService { ); CreateTaskResponse response = await taskService.createTask( request, - options: CallOptions(metadata: TasksAPIServices().getMetaData()), + options: CallOptions(metadata: TasksAPIServiceClients().getMetaData()), ); return response.id; @@ -89,7 +89,7 @@ class TaskService { AssignTaskRequest request = AssignTaskRequest(taskId: taskId, userId: userId); AssignTaskResponse response = await taskService.assignTask( request, - options: CallOptions(metadata: TasksAPIServices().getMetaData()), + options: CallOptions(metadata: TasksAPIServiceClients().getMetaData()), ); if (!response.isInitialized()) { @@ -107,7 +107,7 @@ class TaskService { )); CreateSubtaskResponse response = await taskService.createSubtask( request, - options: CallOptions(metadata: TasksAPIServices().getMetaData()), + options: CallOptions(metadata: TasksAPIServiceClients().getMetaData()), ); return Subtask( @@ -122,7 +122,7 @@ class TaskService { DeleteSubtaskRequest request = DeleteSubtaskRequest(subtaskId: subtaskId, taskId: taskId); DeleteSubtaskResponse response = await taskService.deleteSubtask( request, - options: CallOptions(metadata: TasksAPIServices().getMetaData()), + options: CallOptions(metadata: TasksAPIServiceClients().getMetaData()), ); return response.isInitialized(); @@ -137,7 +137,7 @@ class TaskService { ); UpdateSubtaskResponse response = await taskService.updateSubtask( request, - options: CallOptions(metadata: TasksAPIServices().getMetaData()), + options: CallOptions(metadata: TasksAPIServiceClients().getMetaData()), ); return response.isInitialized(); @@ -155,7 +155,7 @@ class TaskService { UpdateTaskResponse response = await taskService.updateTask( request, - options: CallOptions(metadata: TasksAPIServices().getMetaData()), + options: CallOptions(metadata: TasksAPIServiceClients().getMetaData()), ); return response.isInitialized(); diff --git a/packages/helpwave_service/lib/src/api/tasks/services/ward_service.dart b/packages/helpwave_service/lib/src/api/tasks/services/ward_service.dart index d34ebb15..60156291 100644 --- a/packages/helpwave_service/lib/src/api/tasks/services/ward_service.dart +++ b/packages/helpwave_service/lib/src/api/tasks/services/ward_service.dart @@ -1,22 +1,22 @@ import 'package:grpc/grpc.dart'; import 'package:helpwave_proto_dart/services/tasks_svc/v1/ward_svc.pbgrpc.dart'; import 'package:helpwave_service/src/api/tasks/data_types/index.dart'; -import 'package:helpwave_service/src/api/tasks/tasks_api_services.dart'; +import 'package:helpwave_service/src/api/tasks/tasks_api_service_clients.dart'; /// The Service for [Ward]s /// /// Provides queries and requests that load or alter [Ward] objects on the server -/// The server is defined in the underlying [TasksAPIServices] +/// The server is defined in the underlying [TasksAPIServiceClients] class WardService { /// The GRPC ServiceClient which handles GRPC - WardServiceClient wardService = TasksAPIServices.wardServiceClient; + WardServiceClient wardService = TasksAPIServiceClients.wardServiceClient; /// Loads a [WardMinimal] by its identifier Future getWard({required String id}) async { GetWardRequest request = GetWardRequest(id: id); GetWardResponse response = await wardService.getWard( request, - options: CallOptions(metadata: TasksAPIServices().getMetaData()), + options: CallOptions(metadata: TasksAPIServiceClients().getMetaData()), ); return WardMinimal( @@ -30,7 +30,7 @@ class WardService { GetWardOverviewsRequest request = GetWardOverviewsRequest(); GetWardOverviewsResponse response = await wardService.getWardOverviews( request, - options: CallOptions(metadata: TasksAPIServices().getMetaData(organizationId: organizationId)), + options: CallOptions(metadata: TasksAPIServiceClients().getMetaData(organizationId: organizationId)), ); return response.wards diff --git a/packages/helpwave_service/lib/src/api/tasks/tasks_api_services.dart b/packages/helpwave_service/lib/src/api/tasks/tasks_api_service_clients.dart similarity index 92% rename from packages/helpwave_service/lib/src/api/tasks/tasks_api_services.dart rename to packages/helpwave_service/lib/src/api/tasks/tasks_api_service_clients.dart index 1c09d123..8a578a29 100644 --- a/packages/helpwave_service/lib/src/api/tasks/tasks_api_services.dart +++ b/packages/helpwave_service/lib/src/api/tasks/tasks_api_service_clients.dart @@ -6,14 +6,14 @@ import 'package:helpwave_proto_dart/services/tasks_svc/v1/task_svc.pbgrpc.dart'; import 'package:helpwave_service/src/auth/index.dart'; /// The Underlying GrpcService it provides other clients and the correct metadata for the requests -class TasksAPIServices { +class TasksAPIServiceClients { /// The api URL used static String? apiUrl; static ClientChannel get serviceChannel { - assert(TasksAPIServices.apiUrl != null); + assert(TasksAPIServiceClients.apiUrl != null); return ClientChannel( - TasksAPIServices.apiUrl!, + TasksAPIServiceClients.apiUrl!, ); } diff --git a/packages/helpwave_service/lib/src/api/user/data_types/organization.dart b/packages/helpwave_service/lib/src/api/user/data_types/organization.dart index 0d3a6e96..ca0caf6c 100644 --- a/packages/helpwave_service/lib/src/api/user/data_types/organization.dart +++ b/packages/helpwave_service/lib/src/api/user/data_types/organization.dart @@ -1,17 +1,54 @@ -/// data class for [Organization] -class Organization { +class OrganizationMinimal { String id; - String name; String shortName; + String longName; - Organization({ + OrganizationMinimal({ required this.id, - required this.name, required this.shortName, + required this.longName, + }); +} + +/// data class for [Organization] +class Organization extends OrganizationMinimal { + String avatarURL; + String email; + bool isPersonal; + bool isVerified; + + Organization({ + required super.id, + required super.shortName, + required super.longName, + required this.avatarURL, + required this.email, + required this.isPersonal, + required this.isVerified, }); + Organization copyWith({ + String? shortName, + String? longName, + String? avatarURL, + String? email, + bool? isPersonal, + bool? isVerified, + }) { + return Organization( + id: id, + // `id` is not changeable + shortName: shortName ?? this.shortName, + longName: longName ?? this.longName, + avatarURL: avatarURL ?? this.avatarURL, + email: email ?? this.email, + isPersonal: isPersonal ?? this.isPersonal, + isVerified: isVerified ?? this.isVerified, + ); + } + @override String toString() { - return "{id: $id, name: $name, shortName: $shortName}"; + return "{id: $id, name: $longName, shortName: $shortName}"; } } diff --git a/packages/helpwave_service/lib/src/api/user/data_types/user.dart b/packages/helpwave_service/lib/src/api/user/data_types/user.dart index 54733fc5..0abd1c09 100644 --- a/packages/helpwave_service/lib/src/api/user/data_types/user.dart +++ b/packages/helpwave_service/lib/src/api/user/data_types/user.dart @@ -3,21 +3,29 @@ class User { String id; String name; String nickName; - Uri profile; - - // TODO add email + String email; + Uri profileUrl; User({ required this.id, required this.name, required this.nickName, - required this.profile, + required this.email, + required this.profileUrl, }); - factory User.empty({String id = ""}) => User(id: id, name: "", nickName: "", profile: Uri.base); + factory User.empty({String id = ""}) => User(id: id, name: "", nickName: "", email: "", profileUrl: Uri.base); bool get isCreating => id == ""; + User copyWith({String? name, String? nickName, Uri? profileUrl, String? email}) => User( + id: id, + name: name ?? this.name, + nickName: nickName ?? this.nickName, + profileUrl: profileUrl ?? this.profileUrl, + email: email ?? this.email, + ); + @override bool operator ==(Object other) { if (identical(this, other)) return true; diff --git a/packages/helpwave_service/lib/src/api/user/index.dart b/packages/helpwave_service/lib/src/api/user/index.dart index 243eabf0..8bfb7f1d 100644 --- a/packages/helpwave_service/lib/src/api/user/index.dart +++ b/packages/helpwave_service/lib/src/api/user/index.dart @@ -1,4 +1,4 @@ export 'data_types/index.dart'; export 'services/index.dart'; export 'controllers/index.dart'; -export 'user_api_services.dart'; +export 'user_api_service_clients.dart'; diff --git a/packages/helpwave_service/lib/src/api/user/offline_clients/organization_offline_client.dart b/packages/helpwave_service/lib/src/api/user/offline_clients/organization_offline_client.dart new file mode 100644 index 00000000..f5173556 --- /dev/null +++ b/packages/helpwave_service/lib/src/api/user/offline_clients/organization_offline_client.dart @@ -0,0 +1,271 @@ +import 'package:grpc/grpc.dart'; +import 'package:helpwave_proto_dart/services/user_svc/v1/organization_svc.pbgrpc.dart'; +import 'package:helpwave_service/src/api/offline/offline_client_store.dart'; +import 'package:helpwave_service/src/api/offline/util.dart'; +import 'package:helpwave_service/user.dart'; + +class OrganizationUpdate { + String id; + String shortName; + String longName; + String email; + bool isPersonal; + String avatarURL; + + OrganizationUpdate({ + required this.id, + required this.shortName, + required this.longName, + required this.email, + required this.isPersonal, + required this.avatarURL, + }); +} + +class OrganizationOfflineClientStore { + List organizations = []; + + Organization? find(String id) { + int index = organizations.indexWhere((org) => org.id == id); + if (index == -1) { + return null; + } + return organizations[index]; + } + + List findOrganizations() { + return organizations; + } + + void create(Organization organization) { + organizations.add(organization); + } + + void update(OrganizationUpdate organizationUpdate) { + bool found = false; + organizations = organizations.map((org) { + if (org.id == organizationUpdate.id) { + found = true; + return org.copyWith( + shortName: organizationUpdate.shortName, + longName: organizationUpdate.longName, + avatarURL: organizationUpdate.avatarURL, + email: organizationUpdate.email, + isPersonal: organizationUpdate.isPersonal); + } + return org; + }).toList(); + + if (!found) { + throw Exception("UpdateOrganization: Could not find organization with id ${organizationUpdate.id}"); + } + } + + void delete(String organizationId) { + organizations.removeWhere((org) => org.id == organizationId); + // Assuming WardOfflineService handles related deletions (Wards, etc.) + // WardOfflineService.deleteByOrganization(organizationId); + } +} + +class OrganizationOfflineClient extends OrganizationServiceClient { + OrganizationOfflineClient(super.channel); + + @override + ResponseFuture createOrganization(CreateOrganizationRequest request, + {CallOptions? options}) { + final newOrganization = Organization( + id: DateTime.now().millisecondsSinceEpoch.toString(), + shortName: request.shortName, + longName: request.longName, + avatarURL: 'https://helpwave.de/favicon.ico', + email: request.contactEmail, + isPersonal: request.isPersonal, + isVerified: true, + ); + + OfflineClientStore().organizationStore.create(newOrganization); + + return MockResponseFuture.value(CreateOrganizationResponse()..id = newOrganization.id); + } + + @override + ResponseFuture createOrganizationForUser(CreateOrganizationForUserRequest request, + {CallOptions? options}) { + final newOrganization = Organization( + id: DateTime.now().millisecondsSinceEpoch.toString(), + shortName: request.shortName, + longName: request.longName, + avatarURL: 'https://helpwave.de/favicon.ico', + email: request.contactEmail, + isPersonal: request.isPersonal, + isVerified: true, + ); + + OfflineClientStore().organizationStore.create(newOrganization); + + return MockResponseFuture.value(CreateOrganizationForUserResponse()..id = newOrganization.id); + } + + @override + ResponseFuture getOrganization(GetOrganizationRequest request, {CallOptions? options}) { + final organization = OfflineClientStore().organizationStore.find(request.id); + + if (organization == null) { + throw Exception("GetOrganization: Could not find organization with id ${request.id}"); + } + + final members = + OfflineClientStore().userStore.findUsers().map((user) => GetOrganizationMember()..userId = user.id).toList(); + + return MockResponseFuture.value(GetOrganizationResponse() + ..id = organization.id + ..shortName = organization.shortName + ..longName = organization.longName + ..avatarUrl = organization.avatarURL + ..contactEmail = organization.email + ..isPersonal = organization.isPersonal + ..members.addAll(members)); + } + + @override + ResponseFuture getOrganizationsByUser(GetOrganizationsByUserRequest request, + {CallOptions? options}) { + final organizations = OfflineClientStore().organizationStore.findOrganizations().map((org) { + final members = OfflineClientStore() + .userStore + .findUsers() + .map((user) => GetOrganizationsByUserResponse_Organization_Member()..userId = user.id) + .toList(); + + return GetOrganizationsByUserResponse_Organization() + ..id = org.id + ..shortName = org.shortName + ..longName = org.longName + ..contactEmail = org.email + ..avatarUrl = org.avatarURL + ..members.addAll(members) + ..isPersonal = org.isPersonal; + }).toList(); + + return MockResponseFuture.value(GetOrganizationsByUserResponse()..organizations.addAll(organizations)); + } + + @override + ResponseFuture getOrganizationsForUser(GetOrganizationsForUserRequest request, {CallOptions? options}) { + final organizations = OfflineClientStore().organizationStore.findOrganizations().map((org) { + final members = OfflineClientStore() + .userStore + .findUsers() + .map((user) => GetOrganizationsForUserResponse_Organization_Member()..userId = user.id) + .toList(); + + return GetOrganizationsForUserResponse_Organization() + ..id = org.id + ..shortName = org.shortName + ..longName = org.longName + ..contactEmail = org.email + ..avatarUrl = org.avatarURL + ..members.addAll(members) + ..isPersonal = org.isPersonal; + }).toList(); + + return MockResponseFuture.value(GetOrganizationsForUserResponse()..organizations.addAll(organizations)); + + } + + @override + ResponseFuture updateOrganization(UpdateOrganizationRequest request, + {CallOptions? options}) { + final update = OrganizationUpdate( + id: request.id, + shortName: request.shortName, + longName: request.longName, + email: request.contactEmail, + avatarURL: request.avatarUrl, + isPersonal: request.isPersonal, + ); + + try { + OfflineClientStore().organizationStore.update(update); + return MockResponseFuture.value(UpdateOrganizationResponse()); + } catch (e) { + return MockResponseFuture.error(e); + } + } + + @override + ResponseFuture deleteOrganization(DeleteOrganizationRequest request, + {CallOptions? options}) { + try { + OfflineClientStore().organizationStore.delete(request.id); + return MockResponseFuture.value(DeleteOrganizationResponse()); + } catch (e) { + return MockResponseFuture.error(e); + } + } + + // Other missing methods + + @override + ResponseFuture getMembersByOrganization(GetMembersByOrganizationRequest request, + {CallOptions? options}) { + final organization = OfflineClientStore().organizationStore.find(request.id); + + if (organization == null) { + throw Exception("GetMembersByOrganization: Could not find organization with id ${request.id}"); + } + + final members = OfflineClientStore() + .userStore + .findUsers() + .map((user) => GetMembersByOrganizationResponse_Member() + ..userId = user.id + ..email = user.email + ..nickname = user.nickName + ..avatarUrl = user.profileUrl.toString()) + .toList(); + + return MockResponseFuture.value(GetMembersByOrganizationResponse()..members.addAll(members)); + } + + @override + ResponseFuture getInvitationsByOrganization(GetInvitationsByOrganizationRequest request, {CallOptions? options}) { + return MockResponseFuture.value(GetInvitationsByOrganizationResponse()); + } + + @override + ResponseFuture getInvitationsByUser(GetInvitationsByUserRequest request, {CallOptions? options}) { + return MockResponseFuture.value(GetInvitationsByUserResponse()); + } + + @override + ResponseFuture inviteMember(InviteMemberRequest request, {CallOptions? options}) { + throw UnimplementedError('Not implemented yet'); + } + + @override + ResponseFuture revokeInvitation(RevokeInvitationRequest request, {CallOptions? options}) { + throw UnimplementedError('Not implemented yet'); + } + + @override + ResponseFuture acceptInvitation(AcceptInvitationRequest request, {CallOptions? options}) { + throw UnimplementedError('Not implemented yet'); + } + + @override + ResponseFuture declineInvitation(DeclineInvitationRequest request, {CallOptions? options}) { + throw UnimplementedError('Not implemented yet'); + } + + @override + ResponseFuture addMember(AddMemberRequest request, {CallOptions? options}) { + throw UnimplementedError('Not implemented yet'); + } + + @override + ResponseFuture removeMember(RemoveMemberRequest request, {CallOptions? options}) { + throw UnimplementedError('Not implemented yet'); + } +} diff --git a/packages/helpwave_service/lib/src/api/user/offline_clients/user_offline_client.dart b/packages/helpwave_service/lib/src/api/user/offline_clients/user_offline_client.dart new file mode 100644 index 00000000..10839d27 --- /dev/null +++ b/packages/helpwave_service/lib/src/api/user/offline_clients/user_offline_client.dart @@ -0,0 +1,119 @@ +import 'package:grpc/grpc_web.dart'; +import 'package:helpwave_service/src/api/offline/offline_client_store.dart'; +import 'package:helpwave_service/src/api/offline/util.dart'; +import 'package:helpwave_service/src/api/user/index.dart'; +import 'package:helpwave_proto_dart/services/user_svc/v1/user_svc.pbgrpc.dart'; + +class UserUpdate { + final String id; + + UserUpdate({required this.id}); +} + +class UserOfflineService { + List users = []; + + User? find(String id) { + int index = users.indexWhere((user) => user.id == id); + if (index == -1) { + return null; + } + return users[index]; + } + + List findUsers() { + return users; + } + + void create(User user) { + users.add(user); + } + + void update(UserUpdate user) { + bool found = false; + + users = users.map((u) { + if (u.id == user.id) { + found = true; + return u.copyWith(); + } + return u; + }).toList(); + + if (!found) { + throw Exception('UpdateUser: Could not find user with id ${user.id}'); + } + } + + void delete(String userId) { + users.removeWhere((u) => u.id == userId); + } +} + +class UserOfflineClient extends UserServiceClient { + UserOfflineClient(super.channel); + + @override + ResponseFuture readPublicProfile(ReadPublicProfileRequest request, + {CallOptions? options}) { + final user = OfflineClientStore().userStore.find(request.id); + if (user == null) { + return MockResponseFuture.error(Exception('ReadPublicProfile: Could not find user with id ${request.id}')); + } + final response = ReadPublicProfileResponse() + ..id = user.id + ..name = user.name + ..nickname = user.nickName + ..avatarUrl = user.profileUrl.toString(); + return MockResponseFuture.value(response); + } + + @override + ResponseFuture readSelf(ReadSelfRequest request, {CallOptions? options}) { + final user = OfflineClientStore().userStore.users[0]; + + final organizations = OfflineClientStore() + .organizationStore + .findOrganizations() + .map((org) => ReadSelfOrganization()..id = org.id) + .toList(); + + final response = ReadSelfResponse() + ..id = user.id + ..name = user.name + ..nickname = user.nickName + ..avatarUrl = user.profileUrl.toString() + ..organizations.addAll(organizations); + + return MockResponseFuture.value(response); + } + + @override + ResponseFuture createUser(CreateUserRequest request, {CallOptions? options}) { + final newUser = User( + id: DateTime.now().millisecondsSinceEpoch.toString(), + name: request.name, + nickName: request.nickname, + email: request.email, + profileUrl: Uri.parse('https://helpwave.de/favicon.ico'), + ); + + OfflineClientStore().userStore.create(newUser); + + final response = CreateUserResponse()..id = newUser.id; + return MockResponseFuture.value(response); + } + + @override + ResponseFuture updateUser(UpdateUserRequest request, {CallOptions? options}) { + final update = UserUpdate(id: request.id); + + try { + OfflineClientStore().userStore.update(update); + final response = UpdateUserResponse(); + return MockResponseFuture.value(response); + } catch (e) { + return MockResponseFuture.error(e); + } + } +} diff --git a/packages/helpwave_service/lib/src/api/user/services/organization_svc.dart b/packages/helpwave_service/lib/src/api/user/services/organization_svc.dart index 0b4283f8..0775410f 100644 --- a/packages/helpwave_service/lib/src/api/user/services/organization_svc.dart +++ b/packages/helpwave_service/lib/src/api/user/services/organization_svc.dart @@ -1,31 +1,33 @@ import 'package:grpc/grpc.dart'; import 'package:helpwave_proto_dart/services/user_svc/v1/organization_svc.pbgrpc.dart'; import 'package:helpwave_service/auth.dart'; -import 'package:helpwave_service/src/api/user/user_api_services.dart'; +import 'package:helpwave_service/src/api/user/user_api_service_clients.dart'; import '../data_types/index.dart'; /// The GRPC Service for [Organization]s /// /// Provides queries and requests that load or alter [Organization] objects on the server -/// The server is defined in the underlying [UserAPIServices] +/// The server is defined in the underlying [UserAPIServiceClients] class OrganizationService { /// The GRPC ServiceClient which handles GRPC - OrganizationServiceClient organizationService = UserAPIServices.organizationServiceClient; + OrganizationServiceClient organizationService = UserAPIServiceClients.organizationServiceClient; /// Load a Organization by its identifier Future getOrganization({required String id}) async { GetOrganizationRequest request = GetOrganizationRequest(id: id); GetOrganizationResponse response = await organizationService.getOrganization( request, - options: CallOptions(metadata: UserAPIServices.getMetaData(organizationId: id)), + options: CallOptions(metadata: UserAPIServiceClients.getMetaData(organizationId: id)), ); - // TODO use full information of request Organization organization = Organization( - id: response.id, - name: response.longName, - shortName: response.shortName, - ); + id: response.id, + longName: response.longName, + shortName: response.shortName, + avatarURL: response.avatarUrl, + email: response.contactEmail, + isVerified: true, + isPersonal: response.isPersonal); return organization; } @@ -35,19 +37,21 @@ class OrganizationService { GetOrganizationsForUserResponse response = await organizationService.getOrganizationsForUser( request, options: CallOptions( - metadata: UserAPIServices.getMetaData( + metadata: UserAPIServiceClients.getMetaData( organizationId: AuthenticationUtility.fallbackOrganizationId, ), ), ); List organizations = response.organizations - // TODO use full information of request .map((organization) => Organization( - id: organization.id, - name: organization.longName, - shortName: organization.shortName, - )) + id: organization.id, + longName: organization.id, + shortName: organization.shortName, + avatarURL: organization.avatarUrl, + email: organization.contactEmail, + isVerified: true, + isPersonal: organization.isPersonal)) .toList(); return organizations; } @@ -58,7 +62,7 @@ class OrganizationService { GetMembersByOrganizationResponse response = await organizationService.getMembersByOrganization( request, options: CallOptions( - metadata: UserAPIServices.getMetaData(organizationId: organizationId), + metadata: UserAPIServiceClients.getMetaData(organizationId: organizationId), ), ); @@ -67,7 +71,8 @@ class OrganizationService { id: member.userId, name: member.nickname, // TODO replace this nickName: member.nickname, - profile: Uri.parse(member.avatarUrl), + email: member.email, + profileUrl: Uri.parse(member.avatarUrl), )) .toList(); return users; diff --git a/packages/helpwave_service/lib/src/api/user/services/user_service.dart b/packages/helpwave_service/lib/src/api/user/services/user_service.dart index a667b4cb..52468816 100644 --- a/packages/helpwave_service/lib/src/api/user/services/user_service.dart +++ b/packages/helpwave_service/lib/src/api/user/services/user_service.dart @@ -1,16 +1,16 @@ import 'package:grpc/grpc.dart'; import 'package:helpwave_proto_dart/services/user_svc/v1/user_svc.pbgrpc.dart'; import 'package:helpwave_service/auth.dart'; -import 'package:helpwave_service/src/api/user/user_api_services.dart'; +import 'package:helpwave_service/src/api/user/user_api_service_clients.dart'; import '../data_types/index.dart'; /// The GRPC Service for [User]s /// /// Provides queries and requests that load or alter [User] objects on the server -/// The server is defined in the underlying [UserAPIServices] +/// The server is defined in the underlying [UserAPIServiceClients] class UserService { /// The GRPC ServiceClient which handles GRPC - UserServiceClient userService = UserAPIServices.userServiceClient; + UserServiceClient userService = UserAPIServiceClients.userServiceClient; /// Loads the [User]s by it's identifier Future getUser({String? id}) async { @@ -18,7 +18,7 @@ class UserService { ReadPublicProfileResponse response = await userService.readPublicProfile( request, options: CallOptions( - metadata: UserAPIServices.getMetaData( + metadata: UserAPIServiceClients.getMetaData( organizationId: AuthenticationUtility.fallbackOrganizationId, ), ), @@ -28,7 +28,8 @@ class UserService { id: response.id, name: response.name, nickName: response.nickname, - profile: Uri.parse(response.avatarUrl), + email: "no-email", // TODO replace this + profileUrl: Uri.parse(response.avatarUrl), ); } } diff --git a/packages/helpwave_service/lib/src/api/user/user_api_services.dart b/packages/helpwave_service/lib/src/api/user/user_api_service_clients.dart similarity index 89% rename from packages/helpwave_service/lib/src/api/user/user_api_services.dart rename to packages/helpwave_service/lib/src/api/user/user_api_service_clients.dart index 695cb5f9..5e1f8954 100644 --- a/packages/helpwave_service/lib/src/api/user/user_api_services.dart +++ b/packages/helpwave_service/lib/src/api/user/user_api_service_clients.dart @@ -6,14 +6,14 @@ import 'package:helpwave_service/src/auth/index.dart'; /// A bundling of all User API services which can be used and are configured /// /// Make sure to set the [apiURL] to use the services -class UserAPIServices { +class UserAPIServiceClients { /// The api URL used static String? apiUrl; static ClientChannel get serviceChannel { - assert(UserAPIServices.apiUrl != null); + assert(UserAPIServiceClients.apiUrl != null); return ClientChannel( - UserAPIServices.apiUrl!, + UserAPIServiceClients.apiUrl!, ); } diff --git a/packages/helpwave_service/lib/src/auth/current_ward_svc.dart b/packages/helpwave_service/lib/src/auth/current_ward_svc.dart index 8413e807..bca9ab3f 100644 --- a/packages/helpwave_service/lib/src/auth/current_ward_svc.dart +++ b/packages/helpwave_service/lib/src/auth/current_ward_svc.dart @@ -9,7 +9,7 @@ class CurrentWardInformation { final WardMinimal ward; /// The identifier of the organization - final Organization organization; + final OrganizationMinimal organization; String get wardId => ward.id; @@ -17,11 +17,11 @@ class CurrentWardInformation { String get organizationId => organization.id; - String get organizationName => "${organization.name} (${organization.shortName})"; + String get organizationName => "${organization.longName} (${organization.shortName})"; bool get isEmpty => wardId == "" || organizationId == ""; - bool get hasFullInformation => ward.name != "" && organization.name != ""; + bool get hasFullInformation => ward.name != "" && organization.longName != ""; CurrentWardInformation(this.ward, this.organization); @@ -62,7 +62,7 @@ class _CurrentWardPreferences { if (wardId != null && organizationId != null) { return CurrentWardInformation( WardMinimal(id: wardId, name: ""), - Organization(id: organizationId, name: "", shortName: ""), + OrganizationMinimal(id: organizationId, longName: "", shortName: ""), ); } return null; diff --git a/packages/helpwave_util/lib/lists.dart b/packages/helpwave_util/lib/lists.dart new file mode 100644 index 00000000..da052351 --- /dev/null +++ b/packages/helpwave_util/lib/lists.dart @@ -0,0 +1 @@ +export 'package:helpwave_util/src/lists/range.dart'; diff --git a/packages/helpwave_util/lib/src/lists/range.dart b/packages/helpwave_util/lib/src/lists/range.dart new file mode 100644 index 00000000..4119bb3a --- /dev/null +++ b/packages/helpwave_util/lib/src/lists/range.dart @@ -0,0 +1,11 @@ +List range(int start, int end, [int step = 1]) { + if (step == 0) { + throw ArgumentError('Step cannot be zero.'); + } + + List result = []; + for (int i = start; (step > 0 ? i < end : i > end); i += step) { + result.add(i); + } + return result; +} From f97d8c6b41e511062c2c0444dc95056843fdcbf4 Mon Sep 17 00:00:00 2001 From: Felix Thape Date: Sun, 15 Sep 2024 20:10:27 +0200 Subject: [PATCH 3/9] fix: fix some errors --- .../controllers/my_tasks_controller.dart | 3 +- .../tasks/controllers/task_controller.dart | 2 +- .../lib/src/api/tasks/data_types/task.dart | 1 + .../src/api/tasks/services/patient_svc.dart | 151 ++++++------------ .../lib/src/api/tasks/services/task_svc.dart | 44 ++--- 5 files changed, 78 insertions(+), 123 deletions(-) diff --git a/packages/helpwave_service/lib/src/api/tasks/controllers/my_tasks_controller.dart b/packages/helpwave_service/lib/src/api/tasks/controllers/my_tasks_controller.dart index 98de67d5..05c0b4e5 100644 --- a/packages/helpwave_service/lib/src/api/tasks/controllers/my_tasks_controller.dart +++ b/packages/helpwave_service/lib/src/api/tasks/controllers/my_tasks_controller.dart @@ -44,11 +44,12 @@ class MyTasksController extends ChangeNotifier { _tasks.add(TaskWithPatient( id: task.id, name: task.name, - assignee: task.assigneeId, + assigneeId: task.assigneeId, notes: task.notes, dueDate: task.dueDate, status: task.status, subtasks: task.subtasks, + patientId: patient.id, patient: patient, )); } diff --git a/packages/helpwave_service/lib/src/api/tasks/controllers/task_controller.dart b/packages/helpwave_service/lib/src/api/tasks/controllers/task_controller.dart index a797f9e3..c52081d0 100644 --- a/packages/helpwave_service/lib/src/api/tasks/controllers/task_controller.dart +++ b/packages/helpwave_service/lib/src/api/tasks/controllers/task_controller.dart @@ -141,7 +141,7 @@ class TaskController extends ChangeNotifier { /// Only usable when creating Future changePatient(PatientMinimal patient) async { assert(task.isCreating, "Only use TaskController.changePatient, when you create a new task."); - task.patient = patient; + task = task.copyWith(patient); notifyListeners(); } diff --git a/packages/helpwave_service/lib/src/api/tasks/data_types/task.dart b/packages/helpwave_service/lib/src/api/tasks/data_types/task.dart index 9b13a237..a8b09b82 100644 --- a/packages/helpwave_service/lib/src/api/tasks/data_types/task.dart +++ b/packages/helpwave_service/lib/src/api/tasks/data_types/task.dart @@ -131,6 +131,7 @@ class TaskWithPatient extends Task { super.subtasks, super.dueDate, super.creationDate, + super.createdBy, super.isPublicVisible, required super.patientId, required this.patient, diff --git a/packages/helpwave_service/lib/src/api/tasks/services/patient_svc.dart b/packages/helpwave_service/lib/src/api/tasks/services/patient_svc.dart index acfc6674..39237b04 100644 --- a/packages/helpwave_service/lib/src/api/tasks/services/patient_svc.dart +++ b/packages/helpwave_service/lib/src/api/tasks/services/patient_svc.dart @@ -3,7 +3,6 @@ import 'package:helpwave_proto_dart/services/tasks_svc/v1/patient_svc.pbgrpc.dar import 'package:helpwave_service/src/api/tasks/index.dart'; import 'package:helpwave_service/src/api/tasks/util/task_status_mapping.dart'; - /// The GRPC Service for [Patient]s /// /// Provides queries and requests that load or alter [Patient] objects on the server @@ -23,96 +22,41 @@ class PatientService { ), ); - List active = response.active - .map( - (patient) => Patient( - id: patient.id, - name: patient.humanReadableIdentifier, - isDischarged: response.dischargedPatients.contains(patient), - tasks: patient.tasks - .map((task) => Task( - id: task.id, - name: task.name, - notes: task.description, - status: GRPCTypeConverter.taskStatusFromGRPC(task.status), - isPublicVisible: task.public, - assigneeId: task.assignedUserId, - subtasks: task.subtasks - .map((subtask) => Subtask( - id: subtask.id, - name: subtask.name, - isDone: subtask.done, - taskId: task.id - )) - .toList(), - patientId: patient.id, - // TODO due and creation date - )) - .toList(), - notes: patient.notes, - bed: BedMinimal(id: patient.bed.id, name: patient.bed.name), - room: RoomMinimal(id: patient.room.id, name: patient.room.name), - ), - ) - .toList(); - - List unassigned = response.unassignedPatients - .map( - (patient) => Patient( - id: patient.id, - name: patient.humanReadableIdentifier, - isDischarged: response.dischargedPatients.contains(patient), - tasks: patient.tasks - .map((task) => Task( - id: task.id, - name: task.name, - notes: task.description, - status: GRPCTypeConverter.taskStatusFromGRPC(task.status), - isPublicVisible: task.public, - assigneeId: task.assignedUserId, - subtasks: task.subtasks - .map((subtask) => Subtask( - id: subtask.id, - name: subtask.name, - isDone: subtask.done, - )) - .toList(), - // TODO due and creation date - )) - .toList(), - notes: patient.notes, - ), - ) - .toList(); + mapping(GetPatientListResponse_Patient patient) { + final res = Patient( + id: patient.id, + name: patient.humanReadableIdentifier, + isDischarged: response.dischargedPatients.contains(patient), + tasks: patient.tasks + .map((task) => Task( + id: task.id, + name: task.name, + notes: task.description, + status: GRPCTypeConverter.taskStatusFromGRPC(task.status), + isPublicVisible: task.public, + assigneeId: task.assignedUserId, + subtasks: task.subtasks + .map((subtask) => + Subtask(id: subtask.id, name: subtask.name, isDone: subtask.done, taskId: task.id)) + .toList(), + patientId: patient.id, + // TODO due and creation date + )) + .toList(), + notes: patient.notes, + bed: BedMinimal(id: patient.bed.id, name: patient.bed.name), + room: RoomMinimal(id: patient.room.id, name: patient.room.name), + ); + if (patient.hasBed() && patient.hasRoom()) { + res.bed = BedMinimal(id: patient.bed.id, name: patient.bed.name); + res.room = RoomMinimal(id: patient.room.id, name: patient.room.name); + } + return res; + } - List discharged = response.dischargedPatients - .map( - (patient) => Patient( - id: patient.id, - name: patient.humanReadableIdentifier, - isDischarged: true, - tasks: patient.tasks - .map((task) => Task( - id: task.id, - name: task.name, - notes: task.description, - status: GRPCTypeConverter.taskStatusFromGRPC(task.status), - isPublicVisible: task.public, - assigneeId: task.assignedUserId, - subtasks: task.subtasks - .map((subtask) => Subtask( - id: subtask.id, - name: subtask.name, - isDone: subtask.done, - )) - .toList(), - // TODO due and creation date - )) - .toList(), - notes: patient.notes, - ), - ) - .toList(); + final active = response.active.map(mapping).toList(); + final unassigned = response.unassignedPatients.map(mapping).toList(); + final discharged = response.dischargedPatients.map(mapping).toList(); return PatientsByAssignmentStatus( all: active + unassigned + discharged, @@ -156,19 +100,20 @@ class PatientService { isDischarged: response.isDischarged, tasks: response.tasks .map((task) => Task( - id: task.id, - name: task.name, - notes: task.description, - assigneeId: task.assignedUserId, - status: GRPCTypeConverter.taskStatusFromGRPC(task.status), - isPublicVisible: task.public, - subtasks: task.subtasks - .map((subtask) => Subtask( - id: subtask.id, - name: subtask.name, - )) - .toList(), - )) + id: task.id, + name: task.name, + notes: task.description, + assigneeId: task.assignedUserId, + status: GRPCTypeConverter.taskStatusFromGRPC(task.status), + isPublicVisible: task.public, + subtasks: task.subtasks + .map((subtask) => Subtask( + id: subtask.id, + taskId: task.id, + name: subtask.name, + )) + .toList(), + patientId: response.id)) .toList(), bed: response.hasBed() ? BedMinimal(id: response.bed.id, name: response.bed.name) : null, room: response.hasRoom() ? RoomMinimal(id: response.room.id, name: response.room.name) : null, diff --git a/packages/helpwave_service/lib/src/api/tasks/services/task_svc.dart b/packages/helpwave_service/lib/src/api/tasks/services/task_svc.dart index 3c9969ae..9a4a0e1a 100644 --- a/packages/helpwave_service/lib/src/api/tasks/services/task_svc.dart +++ b/packages/helpwave_service/lib/src/api/tasks/services/task_svc.dart @@ -22,21 +22,24 @@ class TaskService { return response.tasks .map((task) => Task( - id: task.id, - name: task.name, - notes: task.description, - isPublicVisible: task.public, - status: GRPCTypeConverter.taskStatusFromGRPC(task.status), - assigneeId: task.assignedUserId, - dueDate: task.dueAt.toDateTime(), - subtasks: task.subtasks - .map((subtask) => Subtask( - id: subtask.id, - name: subtask.name, - isDone: subtask.done, - )) - .toList(), - )) + id: task.id, + name: task.name, + notes: task.description, + isPublicVisible: task.public, + status: GRPCTypeConverter.taskStatusFromGRPC(task.status), + assigneeId: task.assignedUserId, + dueDate: task.dueAt.toDateTime(), + subtasks: task.subtasks + .map((subtask) => Subtask( + id: subtask.id, + taskId: task.id, + name: subtask.name, + isDone: subtask.done, + )) + .toList(), + patientId: task.patientId, + createdBy: task.createdBy, + creationDate: task.createdAt.toDateTime())) .toList(); } @@ -53,17 +56,21 @@ class TaskService { name: response.name, notes: response.description, isPublicVisible: response.public, - status: GRPCTypeConverter.taskStatusFromGRPC(response.status), - assignee: response.assignedUserId, + status: GRPCTypeConverter.taskStatusFromGRPC(response.status), + assigneeId: response.assignedUserId, dueDate: response.dueAt.toDateTime(), patient: PatientMinimal(id: response.patient.id, name: response.patient.humanReadableIdentifier), subtasks: response.subtasks .map((subtask) => Subtask( id: subtask.id, + taskId: response.id, name: subtask.name, isDone: subtask.done, )) .toList(), + patientId: response.patient.id, + createdBy: response.createdBy, + creationDate: response.createdAt.toDateTime(), ); } @@ -71,7 +78,7 @@ class TaskService { CreateTaskRequest request = CreateTaskRequest( name: task.name, description: task.notes, - initialStatus: GRPCTypeConverter.taskStatusToGRPC(task.status), + initialStatus: GRPCTypeConverter.taskStatusToGRPC(task.status), dueAt: task.dueDate != null ? Timestamp.fromDateTime(task.dueDate!) : null, patientId: !task.patient.isCreating ? task.patient.id : null, public: task.isPublicVisible, @@ -112,6 +119,7 @@ class TaskService { return Subtask( id: response.subtaskId, + taskId: taskId, name: subTask.name, isDone: subTask.isDone, ); From 5a5b2d922be0210f9d1cecb8f12a223cb6258c12 Mon Sep 17 00:00:00 2001 From: Felix Thape Date: Mon, 16 Sep 2024 00:54:38 +0200 Subject: [PATCH 4/9] feat: use offline mode api --- .../tasks/lib/components/assignee_select.dart | 45 +++++----- .../lib/components/patient_bottom_sheet.dart | 7 +- apps/tasks/lib/components/subtask_list.dart | 2 +- apps/tasks/lib/debug/theme_visualizer.dart | 1 + apps/tasks/lib/main.dart | 8 +- apps/tasks/lib/screens/main_screen.dart | 2 +- .../patient_screen.dart | 2 +- .../tasks/lib/screens/ward_select_screen.dart | 2 - .../src/api/offline/offline_client_store.dart | 77 ++++++++++++++++- .../tasks/controllers/task_controller.dart | 4 +- .../offline_clients/bed_offline_client.dart | 5 +- .../patient_offline_client.dart | 46 ++++++++-- .../offline_clients/room_offline_client.dart | 4 +- .../offline_clients/task_offline_client.dart | 4 +- .../offline_clients/ward_offline_client.dart | 84 ++++++++++++++++++- .../src/api/tasks/services/patient_svc.dart | 2 +- .../lib/src/api/tasks/services/room_svc.dart | 2 +- .../lib/src/api/tasks/services/task_svc.dart | 2 +- .../src/api/tasks/services/ward_service.dart | 2 +- .../api/tasks/tasks_api_service_clients.dart | 35 +++++--- .../src/api/user/data_types/organization.dart | 4 +- .../offline_clients/user_offline_client.dart | 2 +- .../api/user/services/organization_svc.dart | 10 +-- .../src/api/user/services/user_service.dart | 4 +- .../api/user/user_api_service_clients.dart | 28 +++++-- 25 files changed, 297 insertions(+), 87 deletions(-) diff --git a/apps/tasks/lib/components/assignee_select.dart b/apps/tasks/lib/components/assignee_select.dart index 08de7ad8..746dc1d0 100644 --- a/apps/tasks/lib/components/assignee_select.dart +++ b/apps/tasks/lib/components/assignee_select.dart @@ -19,31 +19,26 @@ class AssigneeSelect extends StatelessWidget { return BottomSheetBase( titleText: context.localization!.assignee, onClosing: () => {}, - builder: (context) => Flexible( - child: Padding( - padding: const EdgeInsets.symmetric(vertical: paddingMedium), - child: Consumer(builder: (context, assigneeSelectController, __) { - return LoadingAndErrorWidget( - state: assigneeSelectController.state, - child: ListView.builder( - itemCount: assigneeSelectController.users.length, - itemBuilder: (context, index) { - User user = assigneeSelectController.users[index]; - return ListTile( - onTap: () { - assigneeSelectController.changeAssignee(user.id).then((value) { - onChanged(user); - }); - }, - leading: CircleAvatar( - foregroundColor: Colors.blue, backgroundImage: NetworkImage(user.profileUrl.toString())), - title: Text(user.nickName), - ); - }, - ), - ); - }), - ), + builder: (context) => Padding( + padding: const EdgeInsets.symmetric(vertical: paddingMedium), + child: Consumer(builder: (context, assigneeSelectController, __) { + return LoadingAndErrorWidget( + state: assigneeSelectController.state, + child: Column( + children: assigneeSelectController.users.map((user) => + ListTile( + onTap: () { + assigneeSelectController.changeAssignee(user.id).then((value) { + onChanged(user); + }); + }, + leading: CircleAvatar( + foregroundColor: Colors.blue, backgroundImage: NetworkImage(user.profileUrl.toString())), + title: Text(user.nickName), + )).toList(), + ), + ); + }), ), ); } diff --git a/apps/tasks/lib/components/patient_bottom_sheet.dart b/apps/tasks/lib/components/patient_bottom_sheet.dart index 12b6e91e..a987645c 100644 --- a/apps/tasks/lib/components/patient_bottom_sheet.dart +++ b/apps/tasks/lib/components/patient_bottom_sheet.dart @@ -170,10 +170,7 @@ class _PatientBottomSheetState extends State { context.localization!.assignBed, style: TextStyle(color: Theme.of(context).colorScheme.secondary.withOpacity(0.6)), ), - value: !patientController.patient.isUnassigned - ? RoomWithBedFlat( - room: patientController.patient.room!, bed: patientController.patient.bed!) - : null, + value: beds.where((beds) => beds.bed.id == patientController.patient.bed?.id).firstOrNull, items: beds .map((roomWithBed) => DropdownMenuItem( value: roomWithBed, @@ -265,7 +262,7 @@ class _PatientBottomSheetState extends State { // TODO use return value to add it to task list or force a refetch onAdd: () => context.pushModal( context: context, - builder: (context) => TaskBottomSheet(task: Task.empty, patient: patient), + builder: (context) => TaskBottomSheet(task: Task.empty(patient.id), patient: patient), ), ); }), diff --git a/apps/tasks/lib/components/subtask_list.dart b/apps/tasks/lib/components/subtask_list.dart index 11433f36..01c5d314 100644 --- a/apps/tasks/lib/components/subtask_list.dart +++ b/apps/tasks/lib/components/subtask_list.dart @@ -41,7 +41,7 @@ class SubtaskList extends StatelessWidget { style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 16), ), onAdd: () => subtasksController - .add(Subtask(id: "", name: "Subtask ${subtasksController.subtasks.length + 1}")) + .add(Subtask(id: "", name: "Subtask ${subtasksController.subtasks.length + 1}", taskId: taskId)) .then((_) => onChange(subtasksController.subtasks)), itemBuilder: (context, _, subtask) => ListTile( contentPadding: EdgeInsets.zero, diff --git a/apps/tasks/lib/debug/theme_visualizer.dart b/apps/tasks/lib/debug/theme_visualizer.dart index d042da5b..be3cee9f 100644 --- a/apps/tasks/lib/debug/theme_visualizer.dart +++ b/apps/tasks/lib/debug/theme_visualizer.dart @@ -44,6 +44,7 @@ class ThemeVisualizer extends StatelessWidget { name: "Task", notes: "Some Notes", status: TaskStatus.inProgress, + patientId: "patient", dueDate: DateTime.now().add(const Duration(hours: 2)), patient: PatientMinimal( id: "patient", diff --git a/apps/tasks/lib/main.dart b/apps/tasks/lib/main.dart index 5a4da007..65b37680 100644 --- a/apps/tasks/lib/main.dart +++ b/apps/tasks/lib/main.dart @@ -1,5 +1,6 @@ import 'package:flutter/material.dart'; import 'package:helpwave_service/auth.dart'; +import 'package:helpwave_service/user.dart'; import 'package:provider/provider.dart'; import 'package:helpwave_localization/l10n/app_localizations.dart'; import 'package:helpwave_localization/localization.dart'; @@ -11,7 +12,12 @@ import 'package:tasks/screens/login_screen.dart'; void main() { UserSessionService().changeMode(devMode); - TasksAPIServiceClients.apiUrl = usedAPIURL; + TasksAPIServiceClients() + ..apiUrl = usedAPIURL + ..offlineMode = true; + UserAPIServiceClients() + ..apiUrl = usedAPIURL + ..offlineMode = true; runApp(const MyApp()); } diff --git a/apps/tasks/lib/screens/main_screen.dart b/apps/tasks/lib/screens/main_screen.dart index 1235b056..60797a42 100644 --- a/apps/tasks/lib/screens/main_screen.dart +++ b/apps/tasks/lib/screens/main_screen.dart @@ -142,7 +142,7 @@ class _TaskPatientFloatingActionButton extends StatelessWidget { onPressed: () { context.pushModal( context: context, - builder: (context) => TaskBottomSheet(task: Task.empty), + builder: (context) => TaskBottomSheet(task: Task.empty("")), ); }, ), diff --git a/apps/tasks/lib/screens/main_screen_subscreens/patient_screen.dart b/apps/tasks/lib/screens/main_screen_subscreens/patient_screen.dart index 80ce9f6f..2278a361 100644 --- a/apps/tasks/lib/screens/main_screen_subscreens/patient_screen.dart +++ b/apps/tasks/lib/screens/main_screen_subscreens/patient_screen.dart @@ -118,7 +118,7 @@ class _PatientScreenState extends State { context.pushModal( context: context, builder: (context) => TaskBottomSheet( - task: Task.empty, + task: Task.empty(patient.id), patient: patient, ), ).then((value) => patientController.load()); diff --git a/apps/tasks/lib/screens/ward_select_screen.dart b/apps/tasks/lib/screens/ward_select_screen.dart index 73d0018c..41c06071 100644 --- a/apps/tasks/lib/screens/ward_select_screen.dart +++ b/apps/tasks/lib/screens/ward_select_screen.dart @@ -42,7 +42,6 @@ class _WardSelectScreen extends State { body: Column( children: [ ListTile( - // TODO change to organization name title: Text(organization?.longName ?? context.localization!.none), subtitle: Text(context.localization!.organization), trailing: const Icon(Icons.arrow_forward), @@ -71,7 +70,6 @@ class _WardSelectScreen extends State { }), ), ListTile( - // TODO change to organization name title: Text(ward?.name ?? context.localization!.none), subtitle: Text(context.localization!.ward), trailing: const Icon(Icons.arrow_forward), diff --git a/packages/helpwave_service/lib/src/api/offline/offline_client_store.dart b/packages/helpwave_service/lib/src/api/offline/offline_client_store.dart index 3fe8d420..d61296a2 100644 --- a/packages/helpwave_service/lib/src/api/offline/offline_client_store.dart +++ b/packages/helpwave_service/lib/src/api/offline/offline_client_store.dart @@ -1,3 +1,4 @@ +import 'package:helpwave_service/src/api/tasks/index.dart'; import 'package:helpwave_service/src/api/tasks/offline_clients/bed_offline_client.dart'; import 'package:helpwave_service/src/api/tasks/offline_clients/patient_offline_client.dart'; import 'package:helpwave_service/src/api/tasks/offline_clients/room_offline_client.dart'; @@ -6,6 +7,7 @@ import 'package:helpwave_service/src/api/tasks/offline_clients/template_offline_ import 'package:helpwave_service/src/api/tasks/offline_clients/ward_offline_client.dart'; import 'package:helpwave_service/src/api/user/offline_clients/organization_offline_client.dart'; import 'package:helpwave_service/src/api/user/offline_clients/user_offline_client.dart'; +import 'package:helpwave_util/lists.dart'; import '../../../user.dart'; const String profileUrl = "https://helpwave.de/favicon.ico"; @@ -65,9 +67,73 @@ final List initialUsers = [ profileUrl: Uri.parse(profileUrl), ), ]; +final List initialWards = initialOrganizations + .map((organization) => range(0, 3).map((index) => + Ward(id: "${organization.id}${index + 1}", name: "Ward ${index + 1}", organizationId: organization.id))) + .expand((element) => element) + .toList(); +final List initialRooms = initialWards + .map((ward) => range(0, 2) + .map((index) => RoomWithWardId(id: "${ward.id}${index + 1}", name: "Room ${index + 1}", wardId: ward.id))) + .expand((element) => element) + .toList(); +final List initialBeds = initialRooms + .map((room) => range(0, 4) + .map((index) => BedWithRoomId(id: "${room.id}${index + 1}", name: "Bed ${index + 1}", roomId: room.id))) + .expand((element) => element) + .toList(); +final List initialPatients = initialBeds.indexed + .map((e) => PatientWithBedId( + id: "patient${e.$1}", + name: "Patient ${e.$1 + 1}", + notes: "", + isDischarged: e.$1 % 6 == 0, + bedId: e.$1 % 2 == 0 ? e.$2.id : null, + )) + .toList(); +final List initialTasks = initialPatients + .map((patient) => range(0, 3).map((index) => Task( + id: "${patient.id}${index + 1}", + name: "Task ${index + 1}", + patientId: patient.id, + notes: '', + ))) + .expand((element) => element) + .toList(); +final List initialTaskSubtasks = initialTasks + .map((task) => range(0, 2).map((index) => Subtask( + id: "${task.id}${index + 1}", + name: "Subtask ${index + 1}", + taskId: task.id, + ))) + .expand((element) => element) + .toList(); +final List initialTaskTemplates = range(0, 5) + .map((index) => TaskTemplate( + id: "template$index", + name: "template${index + 1}", + notes: "", + )) + .toList() + + initialWards + .map((ward) => TaskTemplate( + id: "wardTemplate${ward.id}", + name: "Ward ${ward.name} Template", + notes: "", + wardId: ward.id, + )) + .toList(); +final List initialTaskTemplateSubtasks = initialTasks + .map((task) => range(0, 3).map((index) => Subtask( + id: "${task.id}${index + 1}", + name: "Template Subtask ${index + 1}", + taskId: task.id, + ))) + .expand((element) => element) + .toList(); class OfflineClientStore { - static final OfflineClientStore _instance = OfflineClientStore._internal(); + static final OfflineClientStore _instance = OfflineClientStore._internal()..reset(); OfflineClientStore._internal(); @@ -88,6 +154,13 @@ class OfflineClientStore { void reset() { organizationStore.organizations = initialOrganizations; userStore.users = initialUsers; - + wardStore.wards = initialWards; + roomStore.rooms = initialRooms; + bedStore.beds = initialBeds; + patientStore.patients = initialPatients; + taskStore.tasks = initialTasks; + subtaskStore.subtasks = initialTaskSubtasks; + taskTemplateStore.taskTemplates = initialTaskTemplates; + taskTemplateSubtaskStore.taskTemplateSubtasks = initialTaskTemplateSubtasks; } } diff --git a/packages/helpwave_service/lib/src/api/tasks/controllers/task_controller.dart b/packages/helpwave_service/lib/src/api/tasks/controllers/task_controller.dart index c52081d0..4e26f1e7 100644 --- a/packages/helpwave_service/lib/src/api/tasks/controllers/task_controller.dart +++ b/packages/helpwave_service/lib/src/api/tasks/controllers/task_controller.dart @@ -141,7 +141,7 @@ class TaskController extends ChangeNotifier { /// Only usable when creating Future changePatient(PatientMinimal patient) async { assert(task.isCreating, "Only use TaskController.changePatient, when you create a new task."); - task = task.copyWith(patient); + task = TaskWithPatient.fromTaskAndPatient(task: task.copyWith(patientId: patient.id), patient: patient); notifyListeners(); } @@ -150,7 +150,7 @@ class TaskController extends ChangeNotifier { assert(!task.patient.isCreating, "A the patient must be set to create a task"); state = LoadingState.loading; return await TaskService().createTask(task).then((value) { - task.id = value; + task.copyWith(id: value); state = LoadingState.loaded; return true; }).catchError((error, stackTrace) { diff --git a/packages/helpwave_service/lib/src/api/tasks/offline_clients/bed_offline_client.dart b/packages/helpwave_service/lib/src/api/tasks/offline_clients/bed_offline_client.dart index 11f565e9..cadcb891 100644 --- a/packages/helpwave_service/lib/src/api/tasks/offline_clients/bed_offline_client.dart +++ b/packages/helpwave_service/lib/src/api/tasks/offline_clients/bed_offline_client.dart @@ -55,7 +55,10 @@ class BedOfflineService { void delete(String bedId) { final valueStore = OfflineClientStore().bedStore; valueStore.beds = valueStore.beds.where((value) => value.id != bedId).toList(); - // TODO: Cascade delete to bed-bound templates + final patient = OfflineClientStore().patientStore.findPatientByBed(bedId); + if(patient != null){ + OfflineClientStore().patientStore.unassignBed(patient.id); + } } } diff --git a/packages/helpwave_service/lib/src/api/tasks/offline_clients/patient_offline_client.dart b/packages/helpwave_service/lib/src/api/tasks/offline_clients/patient_offline_client.dart index 22a46384..97e62b46 100644 --- a/packages/helpwave_service/lib/src/api/tasks/offline_clients/patient_offline_client.dart +++ b/packages/helpwave_service/lib/src/api/tasks/offline_clients/patient_offline_client.dart @@ -3,6 +3,7 @@ import 'package:helpwave_proto_dart/services/tasks_svc/v1/patient_svc.pbgrpc.dar import 'package:helpwave_service/src/api/offline/offline_client_store.dart'; import 'package:helpwave_service/src/api/offline/util.dart'; import 'package:helpwave_service/src/api/tasks/data_types/patient.dart'; +import 'package:helpwave_service/src/api/tasks/util/task_status_mapping.dart'; class PatientUpdate { String id; @@ -97,12 +98,15 @@ class PatientOfflineService { void delete(String patientId) { final valueStore = OfflineClientStore().patientStore; valueStore.patients = valueStore.patients.where((value) => value.id != patientId).toList(); - // TODO: Cascade delete to tasks + final tasks = OfflineClientStore().taskStore.findTasks(patientId); + for (var task in tasks) { + OfflineClientStore().taskStore.delete(task.id); + } } } -class PatientServicePromiseClient extends PatientServiceClient { - PatientServicePromiseClient(super.channel); +class PatientOfflineClient extends PatientServiceClient { + PatientOfflineClient(super.channel); @override ResponseFuture getPatient(GetPatientRequest request, {CallOptions? options}) { @@ -145,7 +149,23 @@ class PatientServicePromiseClient extends PatientServiceClient { humanReadableIdentifier: patient.name, notes: patient.notes, isDischarged: patient.isDischarged, - tasks: [], // TODO tasks + tasks: OfflineClientStore().taskStore.findTasks(patient.id).map((task) => GetPatientDetailsResponse_Task( + id: task.id, + name: task.name, + patientId: patient.id, + assignedUserId: task.assigneeId, + description: task.notes, + public: task.isPublicVisible, + status: GRPCTypeConverter.taskStatusToGRPC(task.status), + subtasks: OfflineClientStore() + .subtaskStore + .findSubtasks(task.id) + .map((subtask) => GetPatientDetailsResponse_Task_SubTask( + id: subtask.id, + name: subtask.name, + done: subtask.isDone, + )), + )), ); if (patient.bedId == null) { @@ -188,7 +208,23 @@ class PatientServicePromiseClient extends PatientServiceClient { id: patient.id, notes: patient.notes, humanReadableIdentifier: patient.name, - tasks: [], // TODO get tasks + tasks: OfflineClientStore().taskStore.findTasks(patient.id).map((task) => GetPatientListResponse_Task( + id: task.id, + name: task.name, + patientId: patient.id, + assignedUserId: task.assigneeId, + description: task.notes, + public: task.isPublicVisible, + status: GRPCTypeConverter.taskStatusToGRPC(task.status), + subtasks: OfflineClientStore() + .subtaskStore + .findSubtasks(task.id) + .map((subtask) => GetPatientListResponse_Task_SubTask( + id: subtask.id, + name: subtask.name, + done: subtask.isDone, + )), + )), ); if (patient.bedId == null) { return res; diff --git a/packages/helpwave_service/lib/src/api/tasks/offline_clients/room_offline_client.dart b/packages/helpwave_service/lib/src/api/tasks/offline_clients/room_offline_client.dart index 34405d0e..57ed4799 100644 --- a/packages/helpwave_service/lib/src/api/tasks/offline_clients/room_offline_client.dart +++ b/packages/helpwave_service/lib/src/api/tasks/offline_clients/room_offline_client.dart @@ -60,8 +60,8 @@ class RoomOfflineService { } } -class RoomServicePromiseClient extends RoomServiceClient { - RoomServicePromiseClient(super.channel); +class RoomOfflineClient extends RoomServiceClient { + RoomOfflineClient(super.channel); @override ResponseFuture getRoom(GetRoomRequest request, {CallOptions? options}) { diff --git a/packages/helpwave_service/lib/src/api/tasks/offline_clients/task_offline_client.dart b/packages/helpwave_service/lib/src/api/tasks/offline_clients/task_offline_client.dart index 86fb98ef..27b1fae0 100644 --- a/packages/helpwave_service/lib/src/api/tasks/offline_clients/task_offline_client.dart +++ b/packages/helpwave_service/lib/src/api/tasks/offline_clients/task_offline_client.dart @@ -185,8 +185,8 @@ class SubtaskOfflineService { } } -class TaskServicePromiseClient extends TaskServiceClient { - TaskServicePromiseClient(super.channel); +class TaskOfflineClient extends TaskServiceClient { + TaskOfflineClient(super.channel); @override ResponseFuture getTask(GetTaskRequest request, {CallOptions? options}) { diff --git a/packages/helpwave_service/lib/src/api/tasks/offline_clients/ward_offline_client.dart b/packages/helpwave_service/lib/src/api/tasks/offline_clients/ward_offline_client.dart index b2d5648d..aacb28a3 100644 --- a/packages/helpwave_service/lib/src/api/tasks/offline_clients/ward_offline_client.dart +++ b/packages/helpwave_service/lib/src/api/tasks/offline_clients/ward_offline_client.dart @@ -57,12 +57,15 @@ class WardOfflineService { OfflineClientStore().roomStore.findRooms(wardId).forEach((element) { OfflineClientStore().roomStore.delete(element.id); }); - // TODO delete ward templates + final taskTemplates = OfflineClientStore().taskTemplateStore.findTaskTemplates(wardId); + for (var element in taskTemplates) { + OfflineClientStore().taskTemplateStore.delete(element.id); + } } } -class WardServicePromiseClient extends WardServiceClient { - WardServicePromiseClient(super.channel); +class WardOfflineClient extends WardServiceClient { + WardOfflineClient(super.channel); @override ResponseFuture getWard(GetWardRequest request, {CallOptions? options}) { @@ -104,7 +107,16 @@ class WardServicePromiseClient extends WardServiceClient { id: ward.id, name: ward.name, rooms: rooms, - // TODO taskTemplates: + taskTemplates: OfflineClientStore() + .taskTemplateStore + .findTaskTemplates(ward.id) + .map((template) => GetWardDetailsResponse_TaskTemplate( + id: template.id, + name: template.name, + subtasks: OfflineClientStore().taskTemplateSubtaskStore.findTemplateSubtasks(template.id).map( + (subtask) => GetWardDetailsResponse_Subtask(id: subtask.id, name: subtask.name), + ), + )), ); return MockResponseFuture.value(response); @@ -124,6 +136,70 @@ class WardServicePromiseClient extends WardServiceClient { return MockResponseFuture.value(response); } + @override + ResponseFuture getRecentWards(GetRecentWardsRequest request, {CallOptions? options}) { + final wards = OfflineClientStore().wardStore.findWards(); + final wardsList = wards.map((ward) { + final rooms = OfflineClientStore().roomStore.findRooms(ward.id); + final beds = + rooms.map((room) => OfflineClientStore().bedStore.findBeds(room.id)).expand((element) => element).toList(); + List patients = []; + for (var bed in beds) { + final patient = OfflineClientStore().patientStore.findPatient(bed.id); + if (patient != null) { + patients.add(patient); + } + } + List tasks = patients + .map((patient) => OfflineClientStore().taskStore.findTasks(patient.id)) + .expand((element) => element) + .toList(); + return GetRecentWardsResponse_Ward( + id: ward.id, + name: ward.name, + bedCount: beds.length, + tasksDone: tasks.where((element) => element.status == TaskStatus.done).length, + tasksInProgress: tasks.where((element) => element.status == TaskStatus.inProgress).length, + tasksTodo: tasks.where((element) => element.status == TaskStatus.todo).length, + ); + }); + final response = GetRecentWardsResponse()..wards.addAll(wardsList); + + return MockResponseFuture.value(response); + } + + @override + ResponseFuture getWardOverviews(GetWardOverviewsRequest request, {CallOptions? options}) { + final wards = OfflineClientStore().wardStore.findWards(); + final wardsList = wards.map((ward) { + final rooms = OfflineClientStore().roomStore.findRooms(ward.id); + final beds = + rooms.map((room) => OfflineClientStore().bedStore.findBeds(room.id)).expand((element) => element).toList(); + List patients = []; + for (var bed in beds) { + final patient = OfflineClientStore().patientStore.findPatient(bed.id); + if (patient != null) { + patients.add(patient); + } + } + List tasks = patients + .map((patient) => OfflineClientStore().taskStore.findTasks(patient.id)) + .expand((element) => element) + .toList(); + return GetWardOverviewsResponse_Ward( + id: ward.id, + name: ward.name, + bedCount: beds.length, + tasksDone: tasks.where((element) => element.status == TaskStatus.done).length, + tasksInProgress: tasks.where((element) => element.status == TaskStatus.inProgress).length, + tasksTodo: tasks.where((element) => element.status == TaskStatus.todo).length, + ); + }); + final response = GetWardOverviewsResponse(wards: wardsList); + + return MockResponseFuture.value(response); + } + @override ResponseFuture createWard(CreateWardRequest request, {CallOptions? options}) { final newWard = Ward( diff --git a/packages/helpwave_service/lib/src/api/tasks/services/patient_svc.dart b/packages/helpwave_service/lib/src/api/tasks/services/patient_svc.dart index 39237b04..32856a47 100644 --- a/packages/helpwave_service/lib/src/api/tasks/services/patient_svc.dart +++ b/packages/helpwave_service/lib/src/api/tasks/services/patient_svc.dart @@ -9,7 +9,7 @@ import 'package:helpwave_service/src/api/tasks/util/task_status_mapping.dart'; /// The server is defined in the underlying [TasksAPIServiceClients] class PatientService { /// The GRPC ServiceClient which handles GRPC - PatientServiceClient patientService = TasksAPIServiceClients.patientServiceClient; + PatientServiceClient patientService = TasksAPIServiceClients().patientServiceClient; // TODO consider an enum instead of an string /// Loads the [Patient]s by [Ward] and sorts them by their assignment status diff --git a/packages/helpwave_service/lib/src/api/tasks/services/room_svc.dart b/packages/helpwave_service/lib/src/api/tasks/services/room_svc.dart index 859a9d97..59ae4381 100644 --- a/packages/helpwave_service/lib/src/api/tasks/services/room_svc.dart +++ b/packages/helpwave_service/lib/src/api/tasks/services/room_svc.dart @@ -9,7 +9,7 @@ import 'package:helpwave_service/src/api/tasks/tasks_api_service_clients.dart'; /// The server is defined in the underlying [TasksAPIServiceClients] class RoomService { /// The GRPC ServiceClient which handles GRPC - RoomServiceClient roomService = TasksAPIServiceClients.roomServiceClient; + RoomServiceClient roomService = TasksAPIServiceClients().roomServiceClient; Future> getRoomOverviews({required String wardId}) async { GetRoomOverviewsByWardRequest request = GetRoomOverviewsByWardRequest(id: wardId); diff --git a/packages/helpwave_service/lib/src/api/tasks/services/task_svc.dart b/packages/helpwave_service/lib/src/api/tasks/services/task_svc.dart index 9a4a0e1a..c4f393dd 100644 --- a/packages/helpwave_service/lib/src/api/tasks/services/task_svc.dart +++ b/packages/helpwave_service/lib/src/api/tasks/services/task_svc.dart @@ -10,7 +10,7 @@ import '../util/task_status_mapping.dart'; /// The server is defined in the underlying [TasksAPIServiceClients] class TaskService { /// The GRPC ServiceClient which handles GRPC - TaskServiceClient taskService = TasksAPIServiceClients.taskServiceClient; + TaskServiceClient taskService = TasksAPIServiceClients().taskServiceClient; /// Loads the [Task]s by a [Patient] identifier Future> getTasksByPatient({String? patientId}) async { diff --git a/packages/helpwave_service/lib/src/api/tasks/services/ward_service.dart b/packages/helpwave_service/lib/src/api/tasks/services/ward_service.dart index 60156291..3d28ca97 100644 --- a/packages/helpwave_service/lib/src/api/tasks/services/ward_service.dart +++ b/packages/helpwave_service/lib/src/api/tasks/services/ward_service.dart @@ -9,7 +9,7 @@ import 'package:helpwave_service/src/api/tasks/tasks_api_service_clients.dart'; /// The server is defined in the underlying [TasksAPIServiceClients] class WardService { /// The GRPC ServiceClient which handles GRPC - WardServiceClient wardService = TasksAPIServiceClients.wardServiceClient; + WardServiceClient wardService = TasksAPIServiceClients().wardServiceClient; /// Loads a [WardMinimal] by its identifier Future getWard({required String id}) async { diff --git a/packages/helpwave_service/lib/src/api/tasks/tasks_api_service_clients.dart b/packages/helpwave_service/lib/src/api/tasks/tasks_api_service_clients.dart index 8a578a29..b2e06333 100644 --- a/packages/helpwave_service/lib/src/api/tasks/tasks_api_service_clients.dart +++ b/packages/helpwave_service/lib/src/api/tasks/tasks_api_service_clients.dart @@ -3,18 +3,29 @@ import 'package:helpwave_proto_dart/services/tasks_svc/v1/ward_svc.pbgrpc.dart'; import 'package:helpwave_proto_dart/services/tasks_svc/v1/patient_svc.pbgrpc.dart'; import 'package:helpwave_proto_dart/services/tasks_svc/v1/room_svc.pbgrpc.dart'; import 'package:helpwave_proto_dart/services/tasks_svc/v1/task_svc.pbgrpc.dart'; +import 'package:helpwave_service/src/api/tasks/offline_clients/patient_offline_client.dart'; +import 'package:helpwave_service/src/api/tasks/offline_clients/ward_offline_client.dart'; import 'package:helpwave_service/src/auth/index.dart'; +import 'offline_clients/room_offline_client.dart'; +import 'offline_clients/task_offline_client.dart'; + /// The Underlying GrpcService it provides other clients and the correct metadata for the requests class TasksAPIServiceClients { + TasksAPIServiceClients._privateConstructor(); + + static final TasksAPIServiceClients _instance = TasksAPIServiceClients._privateConstructor(); + + factory TasksAPIServiceClients() => _instance; + /// The api URL used - static String? apiUrl; + String? apiUrl; + + bool offlineMode = false; - static ClientChannel get serviceChannel { - assert(TasksAPIServiceClients.apiUrl != null); - return ClientChannel( - TasksAPIServiceClients.apiUrl!, - ); + ClientChannel get serviceChannel { + assert(apiUrl != null); + return ClientChannel(apiUrl!); } Map getMetaData({String? organizationId}) { @@ -32,11 +43,15 @@ class TasksAPIServiceClients { return metaData; } - static PatientServiceClient get patientServiceClient => PatientServiceClient(serviceChannel); + PatientServiceClient get patientServiceClient => + offlineMode ? PatientOfflineClient(serviceChannel) : PatientServiceClient(serviceChannel); - static WardServiceClient get wardServiceClient => WardServiceClient(serviceChannel); + WardServiceClient get wardServiceClient => + offlineMode ? WardOfflineClient(serviceChannel) : WardServiceClient(serviceChannel); - static RoomServiceClient get roomServiceClient => RoomServiceClient(serviceChannel); + RoomServiceClient get roomServiceClient => + offlineMode ? RoomOfflineClient(serviceChannel) : RoomServiceClient(serviceChannel); - static TaskServiceClient get taskServiceClient => TaskServiceClient(serviceChannel); + TaskServiceClient get taskServiceClient => + offlineMode ? TaskOfflineClient(serviceChannel) : TaskServiceClient(serviceChannel); } diff --git a/packages/helpwave_service/lib/src/api/user/data_types/organization.dart b/packages/helpwave_service/lib/src/api/user/data_types/organization.dart index ca0caf6c..9bc349a6 100644 --- a/packages/helpwave_service/lib/src/api/user/data_types/organization.dart +++ b/packages/helpwave_service/lib/src/api/user/data_types/organization.dart @@ -28,6 +28,7 @@ class Organization extends OrganizationMinimal { }); Organization copyWith({ + String? id, String? shortName, String? longName, String? avatarURL, @@ -36,8 +37,7 @@ class Organization extends OrganizationMinimal { bool? isVerified, }) { return Organization( - id: id, - // `id` is not changeable + id: id ?? this.id, shortName: shortName ?? this.shortName, longName: longName ?? this.longName, avatarURL: avatarURL ?? this.avatarURL, diff --git a/packages/helpwave_service/lib/src/api/user/offline_clients/user_offline_client.dart b/packages/helpwave_service/lib/src/api/user/offline_clients/user_offline_client.dart index 10839d27..d39c57c6 100644 --- a/packages/helpwave_service/lib/src/api/user/offline_clients/user_offline_client.dart +++ b/packages/helpwave_service/lib/src/api/user/offline_clients/user_offline_client.dart @@ -1,4 +1,4 @@ -import 'package:grpc/grpc_web.dart'; +import 'package:grpc/grpc.dart'; import 'package:helpwave_service/src/api/offline/offline_client_store.dart'; import 'package:helpwave_service/src/api/offline/util.dart'; import 'package:helpwave_service/src/api/user/index.dart'; diff --git a/packages/helpwave_service/lib/src/api/user/services/organization_svc.dart b/packages/helpwave_service/lib/src/api/user/services/organization_svc.dart index 0775410f..39c23315 100644 --- a/packages/helpwave_service/lib/src/api/user/services/organization_svc.dart +++ b/packages/helpwave_service/lib/src/api/user/services/organization_svc.dart @@ -10,14 +10,14 @@ import '../data_types/index.dart'; /// The server is defined in the underlying [UserAPIServiceClients] class OrganizationService { /// The GRPC ServiceClient which handles GRPC - OrganizationServiceClient organizationService = UserAPIServiceClients.organizationServiceClient; + OrganizationServiceClient organizationService = UserAPIServiceClients().organizationServiceClient; /// Load a Organization by its identifier Future getOrganization({required String id}) async { GetOrganizationRequest request = GetOrganizationRequest(id: id); GetOrganizationResponse response = await organizationService.getOrganization( request, - options: CallOptions(metadata: UserAPIServiceClients.getMetaData(organizationId: id)), + options: CallOptions(metadata: UserAPIServiceClients().getMetaData(organizationId: id)), ); Organization organization = Organization( @@ -37,7 +37,7 @@ class OrganizationService { GetOrganizationsForUserResponse response = await organizationService.getOrganizationsForUser( request, options: CallOptions( - metadata: UserAPIServiceClients.getMetaData( + metadata: UserAPIServiceClients().getMetaData( organizationId: AuthenticationUtility.fallbackOrganizationId, ), ), @@ -46,7 +46,7 @@ class OrganizationService { List organizations = response.organizations .map((organization) => Organization( id: organization.id, - longName: organization.id, + longName: organization.longName, shortName: organization.shortName, avatarURL: organization.avatarUrl, email: organization.contactEmail, @@ -62,7 +62,7 @@ class OrganizationService { GetMembersByOrganizationResponse response = await organizationService.getMembersByOrganization( request, options: CallOptions( - metadata: UserAPIServiceClients.getMetaData(organizationId: organizationId), + metadata: UserAPIServiceClients().getMetaData(organizationId: organizationId), ), ); diff --git a/packages/helpwave_service/lib/src/api/user/services/user_service.dart b/packages/helpwave_service/lib/src/api/user/services/user_service.dart index 52468816..943bba4a 100644 --- a/packages/helpwave_service/lib/src/api/user/services/user_service.dart +++ b/packages/helpwave_service/lib/src/api/user/services/user_service.dart @@ -10,7 +10,7 @@ import '../data_types/index.dart'; /// The server is defined in the underlying [UserAPIServiceClients] class UserService { /// The GRPC ServiceClient which handles GRPC - UserServiceClient userService = UserAPIServiceClients.userServiceClient; + UserServiceClient userService = UserAPIServiceClients().userServiceClient; /// Loads the [User]s by it's identifier Future getUser({String? id}) async { @@ -18,7 +18,7 @@ class UserService { ReadPublicProfileResponse response = await userService.readPublicProfile( request, options: CallOptions( - metadata: UserAPIServiceClients.getMetaData( + metadata: UserAPIServiceClients().getMetaData( organizationId: AuthenticationUtility.fallbackOrganizationId, ), ), diff --git a/packages/helpwave_service/lib/src/api/user/user_api_service_clients.dart b/packages/helpwave_service/lib/src/api/user/user_api_service_clients.dart index 5e1f8954..e41b01f6 100644 --- a/packages/helpwave_service/lib/src/api/user/user_api_service_clients.dart +++ b/packages/helpwave_service/lib/src/api/user/user_api_service_clients.dart @@ -1,23 +1,31 @@ import 'package:grpc/grpc.dart'; import 'package:helpwave_proto_dart/services/user_svc/v1/user_svc.pbgrpc.dart'; import 'package:helpwave_proto_dart/services/user_svc/v1/organization_svc.pbgrpc.dart'; +import 'package:helpwave_service/src/api/user/offline_clients/organization_offline_client.dart'; +import 'package:helpwave_service/src/api/user/offline_clients/user_offline_client.dart'; import 'package:helpwave_service/src/auth/index.dart'; /// A bundling of all User API services which can be used and are configured /// /// Make sure to set the [apiURL] to use the services class UserAPIServiceClients { + UserAPIServiceClients._privateConstructor(); + + static final UserAPIServiceClients _instance = UserAPIServiceClients._privateConstructor(); + + factory UserAPIServiceClients() => _instance; + /// The api URL used - static String? apiUrl; + String? apiUrl; + + bool offlineMode = false; - static ClientChannel get serviceChannel { - assert(UserAPIServiceClients.apiUrl != null); - return ClientChannel( - UserAPIServiceClients.apiUrl!, - ); + ClientChannel get serviceChannel { + assert(apiUrl != null); + return ClientChannel(apiUrl!); } - static Map getMetaData({String? organizationId}) { + Map getMetaData({String? organizationId}) { var metaData = { ...AuthenticationUtility.authMetaData, "dapr-app-id": "user-svc", @@ -30,7 +38,9 @@ class UserAPIServiceClients { return metaData; } - static UserServiceClient get userServiceClient => UserServiceClient(serviceChannel); + UserServiceClient get userServiceClient => + offlineMode ? UserOfflineClient(serviceChannel) : UserServiceClient(serviceChannel); - static OrganizationServiceClient get organizationServiceClient => OrganizationServiceClient(serviceChannel); + OrganizationServiceClient get organizationServiceClient => + offlineMode ? OrganizationOfflineClient(serviceChannel) : OrganizationServiceClient(serviceChannel); } From 777e8588417fb7780d3345e527e044e03df53f56 Mon Sep 17 00:00:00 2001 From: Felix Thape Date: Mon, 16 Sep 2024 17:44:25 +0200 Subject: [PATCH 5/9] feat: draft for loading change notifier --- .../lib/components/patient_bottom_sheet.dart | 6 +- apps/tasks/lib/components/subtask_list.dart | 6 +- .../lib/components/task_expansion_tile.dart | 4 +- .../my_tasks_screen.dart | 6 +- .../assignee_select_controller.dart | 55 +++-- .../controllers/my_tasks_controller.dart | 56 ++--- .../tasks/controllers/patient_controller.dart | 192 ++++++++---------- .../controllers/subtask_list_controller.dart | 123 +++++------ .../tasks/controllers/task_controller.dart | 70 ++----- .../controllers/ward_patients_controller.dart | 2 +- .../lib/src/api/tasks/data_types/patient.dart | 22 +- .../src/api/tasks/services/patient_svc.dart | 8 +- .../lib/src/api/tasks/services/task_svc.dart | 33 +++ .../api/user/controllers/user_controller.dart | 2 +- packages/helpwave_util/lib/loading.dart | 1 + packages/helpwave_util/lib/loading_state.dart | 1 - .../helpwave_util/lib/src/loading/index.dart | 2 + .../src/loading/loading_change_notifier.dart | 48 +++++ .../src/{loading_state => loading}/type.dart | 0 .../src/loading/loading_and_error_widget.dart | 2 +- .../src/loading/loading_future_builder.dart | 2 +- 21 files changed, 316 insertions(+), 325 deletions(-) create mode 100644 packages/helpwave_util/lib/loading.dart delete mode 100644 packages/helpwave_util/lib/loading_state.dart create mode 100644 packages/helpwave_util/lib/src/loading/index.dart create mode 100644 packages/helpwave_util/lib/src/loading/loading_change_notifier.dart rename packages/helpwave_util/lib/src/{loading_state => loading}/type.dart (100%) diff --git a/apps/tasks/lib/components/patient_bottom_sheet.dart b/apps/tasks/lib/components/patient_bottom_sheet.dart index a987645c..cb119c5c 100644 --- a/apps/tasks/lib/components/patient_bottom_sheet.dart +++ b/apps/tasks/lib/components/patient_bottom_sheet.dart @@ -12,7 +12,7 @@ import 'package:provider/provider.dart'; import 'package:tasks/components/task_bottom_sheet.dart'; import 'package:tasks/components/task_expansion_tile.dart'; import 'package:helpwave_service/tasks.dart'; -import 'package:helpwave_util/loading_state.dart'; +import 'package:helpwave_util/loading.dart'; /// A [BottomSheet] for showing [Patient] information and [Task]s for that [Patient] class PatientBottomSheet extends StatefulWidget { @@ -94,7 +94,7 @@ class _PatientBottomSheetState extends State { width: width * 0.4, // TODO make this state checking easier and more readable child: TextButton( - onPressed: patientController.patient.isUnassigned + onPressed: patientController.patient.isNotAssignedToBed ? null : () { patientController.unassign(); @@ -185,7 +185,7 @@ class _PatientBottomSheetState extends State { if (value == null) { return; } - patientController.changeBed(value.room, value.bed); + patientController.assignToBed(value.room, value.bed); }, ), ); diff --git a/apps/tasks/lib/components/subtask_list.dart b/apps/tasks/lib/components/subtask_list.dart index 01c5d314..f1db6772 100644 --- a/apps/tasks/lib/components/subtask_list.dart +++ b/apps/tasks/lib/components/subtask_list.dart @@ -41,7 +41,7 @@ class SubtaskList extends StatelessWidget { style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 16), ), onAdd: () => subtasksController - .add(Subtask(id: "", name: "Subtask ${subtasksController.subtasks.length + 1}", taskId: taskId)) + .create(Subtask(id: "", name: "Subtask ${subtasksController.subtasks.length + 1}", taskId: taskId)) .then((_) => onChange(subtasksController.subtasks)), itemBuilder: (context, _, subtask) => ListTile( contentPadding: EdgeInsets.zero, @@ -52,7 +52,7 @@ class SubtaskList extends StatelessWidget { ).then((value) { if (value != null) { subtask.name = value; - subtasksController.updateSubtask(subTask: subtask); + subtasksController.update(subtask: subtask); } }), title: Row( @@ -70,7 +70,7 @@ class SubtaskList extends StatelessWidget { borderRadius: BorderRadius.circular(iconSizeSmall), ), onChanged: (isDone) => subtasksController - .updateSubtask(subTask: subtask.copyWith(isDone: isDone)) + .update(subtask: subtask.copyWith(isDone: isDone)) .then((value) => onChange(subtasksController.subtasks)), ), trailing: GestureDetector( diff --git a/apps/tasks/lib/components/task_expansion_tile.dart b/apps/tasks/lib/components/task_expansion_tile.dart index dd03b854..a5c31a61 100644 --- a/apps/tasks/lib/components/task_expansion_tile.dart +++ b/apps/tasks/lib/components/task_expansion_tile.dart @@ -57,8 +57,8 @@ class TaskExpansionTile extends StatelessWidget { context: context, builder: (context) => TaskBottomSheet(task: task, patient: task.patient), ).then((_) { - MyTasksController controller = Provider.of(context, listen: false); - controller.load(); + AssignedTasksController controller = Provider.of(context, listen: false); + controller.loadHandler(); }); }, child: TaskCard( diff --git a/apps/tasks/lib/screens/main_screen_subscreens/my_tasks_screen.dart b/apps/tasks/lib/screens/main_screen_subscreens/my_tasks_screen.dart index 43572a93..54b2ca37 100644 --- a/apps/tasks/lib/screens/main_screen_subscreens/my_tasks_screen.dart +++ b/apps/tasks/lib/screens/main_screen_subscreens/my_tasks_screen.dart @@ -18,9 +18,9 @@ class _MyTasksScreenState extends State { @override Widget build(BuildContext context) { return ChangeNotifierProvider( - create: (_) => MyTasksController(), - child: Consumer( - builder: (BuildContext context, MyTasksController tasksController, Widget? child) { + create: (_) => AssignedTasksController(), + child: Consumer( + builder: (BuildContext context, AssignedTasksController tasksController, Widget? child) { return LoadingAndErrorWidget( state: tasksController.state, child: ListView(children: [ diff --git a/packages/helpwave_service/lib/src/api/tasks/controllers/assignee_select_controller.dart b/packages/helpwave_service/lib/src/api/tasks/controllers/assignee_select_controller.dart index a8fd4fed..99f6886c 100644 --- a/packages/helpwave_service/lib/src/api/tasks/controllers/assignee_select_controller.dart +++ b/packages/helpwave_service/lib/src/api/tasks/controllers/assignee_select_controller.dart @@ -1,22 +1,10 @@ -import 'package:flutter/foundation.dart'; import 'package:helpwave_service/auth.dart'; import 'package:helpwave_service/src/api/user/index.dart'; -import 'package:helpwave_util/loading_state.dart'; -import 'package:logger/logger.dart'; +import 'package:helpwave_util/loading.dart'; import 'package:helpwave_service/tasks.dart'; /// The Controller for selecting a [User] as the assignee of a [Task] -class AssigneeSelectController extends ChangeNotifier { - /// The [LoadingState] of the Controller - LoadingState _state = LoadingState.initializing; - - LoadingState get state => _state; - - set state(LoadingState value) { - _state = value; - notifyListeners(); - } - +class AssigneeSelectController extends LoadingChangeNotifier { /// The selected [User] identifier String? _selected; @@ -27,43 +15,46 @@ class AssigneeSelectController extends ChangeNotifier { /// The currently loaded user List _users = []; - /// The currently loaded tasks + /// The currently loaded users List get users => _users; /// The identifier of the current [Task] it determines whether /// changes are pushed to the server String? _taskId; + /// Whether the object is + bool get isCreating => _taskId == null && _taskId!.isNotEmpty; // TODO remove .isNotEmpty when semantic is changed + AssigneeSelectController({String? selected, String? taskId}) { _selected = selected; _taskId = taskId; load(); } - /// Loads the tasks + /// Loads the users Future load() async { - state = LoadingState.loading; - String? currentOrganization = CurrentWardService().currentWard?.organizationId; - if(currentOrganization == null){ - if(kDebugMode){ - Logger().w("Organization Id not set in CurrentWardService" - " while trying to load in AssigneeSelectController"); + loadUsersFuture() async { + String? currentOrganization = CurrentWardService().currentWard?.organizationId; + if (currentOrganization == null) { + // TODO throw a better error here + throw "Organization Id not set in CurrentWardService while trying to load in AssigneeSelectController"; } - state = LoadingState.error; - return; + _users = await OrganizationService().getMembersByOrganization(currentOrganization); } - _users = await OrganizationService().getMembersByOrganization(currentOrganization); - state = LoadingState.loaded; + await loadHandler(future: loadUsersFuture()); } /// Change the assignee - Future changeAssignee(String id) async{ - if(_taskId != null && _taskId!.isNotEmpty){ - state = LoadingState.loading; - await TaskService().assignToUser(taskId: _taskId!, userId: id); + Future changeAssignee(String id) async { + changeAssigneeFuture() async { + if (!isCreating) { + await TaskService().assignToUser(taskId: _taskId!, userId: id).then((value) => _selected = id); + } else { + _selected = id; + } } - _selected = id; - state = LoadingState.loaded; + + await loadHandler(future: changeAssigneeFuture()); } } diff --git a/packages/helpwave_service/lib/src/api/tasks/controllers/my_tasks_controller.dart b/packages/helpwave_service/lib/src/api/tasks/controllers/my_tasks_controller.dart index 05c0b4e5..3953085f 100644 --- a/packages/helpwave_service/lib/src/api/tasks/controllers/my_tasks_controller.dart +++ b/packages/helpwave_service/lib/src/api/tasks/controllers/my_tasks_controller.dart @@ -1,61 +1,33 @@ -import 'package:flutter/cupertino.dart'; import 'package:helpwave_service/tasks.dart'; -import 'package:helpwave_util/loading_state.dart'; +import 'package:helpwave_util/loading.dart'; /// The Controller for [Task]s of the current [User] -class MyTasksController extends ChangeNotifier { - /// The [LoadingState] of the Controller - LoadingState state = LoadingState.initializing; - - /// The currently loaded tasks +class AssignedTasksController extends LoadingChangeNotifier { + /// The currently loaded [Task]s List _tasks = []; - /// The currently loaded tasks + /// The currently loaded [Task]s List get tasks => _tasks; - /// The loaded tasks which have [TaskStatus.todo] + /// The loaded [Task]s which have [TaskStatus.todo] List get todo => _tasks.where((element) => element.status == TaskStatus.todo).toList(); - /// The loaded tasks which have [TaskStatus.inProgress] + /// The loaded [Task]s which have [TaskStatus.inProgress] List get inProgress => _tasks.where((element) => element.status == TaskStatus.inProgress).toList(); - /// The loaded tasks which have [TaskStatus.done] + /// The loaded [Task]s which have [TaskStatus.done] List get done => _tasks.where((element) => element.status == TaskStatus.done).toList(); - MyTasksController() { - load(); + AssignedTasksController() { + loadTasks(); } - /// Loads the tasks - Future load() async { - if (state == LoadingState.initializing) { - state = LoadingState.loading; - notifyListeners(); - } - - var patients = await PatientService().getPatientList(); - ListallPatients = patients.all; - - _tasks = []; - // TODO use the already given information by the later updated getPatientList - for(Patient patient in allPatients) { - List tasks = await TaskService().getTasksByPatient(patientId: patient.id); - for(var task in tasks) { - _tasks.add(TaskWithPatient( - id: task.id, - name: task.name, - assigneeId: task.assigneeId, - notes: task.notes, - dueDate: task.dueDate, - status: task.status, - subtasks: task.subtasks, - patientId: patient.id, - patient: patient, - )); - } + /// Loads the [Task]s + Future loadTasks() async { + loadTasksFuture() async { + _tasks = await TaskService().getAssignedTasks(); } - state = LoadingState.loaded; - notifyListeners(); + loadHandler(future: loadTasksFuture()); } } diff --git a/packages/helpwave_service/lib/src/api/tasks/controllers/patient_controller.dart b/packages/helpwave_service/lib/src/api/tasks/controllers/patient_controller.dart index 95daca37..9bfa732e 100644 --- a/packages/helpwave_service/lib/src/api/tasks/controllers/patient_controller.dart +++ b/packages/helpwave_service/lib/src/api/tasks/controllers/patient_controller.dart @@ -1,151 +1,129 @@ -import 'package:flutter/material.dart'; -import 'package:helpwave_util/loading_state.dart'; +import 'package:helpwave_util/loading.dart'; import 'package:helpwave_service/src/api/tasks/index.dart'; +import 'package:logger/logger.dart'; /// The Controller for managing [Patient]s in a Ward -class PatientController extends ChangeNotifier { - /// The [LoadingState] of the Controller - LoadingState _state = LoadingState.initializing; - - /// The current [Patient], may or may not be loaded depending on the [_state] +class PatientController extends LoadingChangeNotifier { + /// The current [Patient] Patient _patient; - /// The error message to show should only be used when [state] == [LoadingState.error] - String errorMessage = ""; - - PatientController(this._patient) { - if (!_patient.isCreating) { - load(); - } - } - - LoadingState get state => _state; - - set state(LoadingState value) { - _state = value; - notifyListeners(); - } - + /// The current [Patient] Patient get patient => _patient; set patient(Patient value) { _patient = value; - _state = LoadingState.loaded; - notifyListeners(); + changeState(LoadingState.loaded); } - /// Saves whether we are currently creating of a patient or already have them + /// Is the current [Patient] already saved on the server or are we creating? get isCreating => _patient.isCreating; - // Used to trigger the notify call without having to copy or save the patient locally - updatePatient(void Function(Patient patient) updateTransform, void Function(Patient patient) revertTransform) { - updateTransform(patient); - if (!isCreating) { - PatientService().updatePatient(patient).then((value) { - if (value) { - state = LoadingState.loaded; - } else { - throw Error(); - } - }).catchError((error, stackTrace) { - revertTransform(patient); - errorMessage = error.toString(); - state = LoadingState.error; - }); - } else { - state = LoadingState.loaded; + PatientController(this._patient) { + if (!_patient.isCreating) { + load(); } } /// A function to load the [Patient] Future load() async { - state = LoadingState.loading; - await PatientService().getPatientDetails(patientId: patient.id).then((value) { - patient = value; - state = LoadingState.loaded; - }).catchError((error, stackTrace) { - errorMessage = error.toString(); - state = LoadingState.error; - }); + if (isCreating) { + Logger().w("PatientController.load should not be called when the patient has not been created"); + return; + } + loadPatient() async { + patient = await PatientService().getPatientDetails(patientId: patient.id); + } + + loadHandler( + future: loadPatient(), + ); } - /// Unassigns the patient the [patients] + /// Unassigns the [Patient] from their [Bed] Future unassign() async { - state = LoadingState.loading; - notifyListeners(); - await PatientService().unassignPatient(patientId: patient.id); - // Here we can maybe use optimistic updates - load(); + unassignPatient() async { + await PatientService().unassignPatient(patientId: patient.id).then((value) { + final patientCopy = patient.copyWith(); + patientCopy.bed = null; + patientCopy.room = null; + patient = patientCopy; + }); + } + + loadHandler(future: unassignPatient()); } - /// Discharges the patient the [patients] + /// Discharges the [Patient] Future discharge() async { - state = LoadingState.loading; - notifyListeners(); - await PatientService().dischargePatient(patientId: patient.id); - // Here we can maybe use optimistic updates - load(); + dischargePatient() async { + await PatientService().dischargePatient(patientId: patient.id).then((value) { + final patientCopy = patient.copyWith(isDischarged: true); + patientCopy.bed = null; + patientCopy.room = null; + patient = patientCopy; + }); + } + + loadHandler(future: dischargePatient()); } - /// Assigns the patient to a bed - Future changeBed(RoomMinimal room, BedMinimal bed) async { + /// Assigns the [Patient] to a [Bed] and [Room] + Future assignToBed(RoomMinimal room, BedMinimal bed) async { if (isCreating) { patient.room = room; patient.bed = bed; - state = LoadingState.loaded; return; } - state = LoadingState.loading; - await PatientService().assignBed(patientId: patient.id, bedId: bed.id).then((value) { - patient.room = room; - patient.bed = bed; - state = LoadingState.loaded; - }).catchError((error, stackTrace) { - errorMessage = error.toString(); - state = LoadingState.error; - }); + assignPatientToBed() async { + await PatientService().assignBed(patientId: patient.id, bedId: bed.id).then((value) { + patient = patient.copyWith(bed: bed, room: room); + }); + } + + loadHandler(future: assignPatientToBed()); } - /// Change the name of the [patient] + /// Change the name of the [Patient] Future changeName(String name) async { - String oldName = name; - updatePatient( - (patient) { + if(isCreating){ + patient.name = name; + return; + } + updateName() async { + await PatientService().updatePatient(id: patient.id, name: name).then((_) { patient.name = name; - }, - (patient) { - patient.name = oldName; - }, - ); + }); + } + + loadHandler(future: updateName()); } - /// Change the notes of the [patient] + /// Change the notes of the [Patient] Future changeNotes(String notes) async { - String oldNotes = notes; - updatePatient( - (patient) { + if(isCreating){ + patient.notes = notes; + return; + } + updateNotes() async { + await PatientService().updatePatient(id: patient.id, notes: notes).then((_) { patient.notes = notes; - }, - (patient) { - patient.notes = oldNotes; - }, - ); + }); + } + + loadHandler(future: updateNotes()); } - /// Creates the patient and returns - Future create() async { - state = LoadingState.loading; - return await PatientService().createPatient(patient).then((value) async { - patient.id = value; - if (!patient.isUnassigned) { - await PatientService().assignBed(patientId: patient.id, bedId: patient.bed!.id); + /// Creates the [Patient] + Future create() async { + createPatient() async { + await PatientService().createPatient(patient).then((id) { + patient = patient.copyWith(id: id); + }); + if (!patient.isNotAssignedToBed) { + await assignToBed(patient.room!, patient.bed!); } - state = LoadingState.loaded; - return true; - }).catchError((error, stackTrace) { - errorMessage = error.toString(); - state = LoadingState.error; - return false; - }); + } + + loadHandler(future: createPatient()); } } diff --git a/packages/helpwave_service/lib/src/api/tasks/controllers/subtask_list_controller.dart b/packages/helpwave_service/lib/src/api/tasks/controllers/subtask_list_controller.dart index f11402f2..a0b8e98c 100644 --- a/packages/helpwave_service/lib/src/api/tasks/controllers/subtask_list_controller.dart +++ b/packages/helpwave_service/lib/src/api/tasks/controllers/subtask_list_controller.dart @@ -1,24 +1,13 @@ import 'dart:async'; -import 'package:flutter/cupertino.dart'; import 'package:helpwave_service/src/api/tasks/index.dart'; -import 'package:helpwave_util/loading_state.dart'; +import 'package:helpwave_util/loading.dart'; /// The Controller for managing [Subtask]s in a [Task] /// /// Providing a [taskId] means loading and synchronising the [Subtask]s with /// the backend while no [taskId] or a empty [String] means that the subtasks /// only used locally -class SubtasksController extends ChangeNotifier { - /// The [LoadingState] of the Controller - LoadingState _state = LoadingState.initializing; - - LoadingState get state => _state; - - set state(LoadingState value) { - _state = state; - notifyListeners(); - } - +class SubtasksController extends LoadingChangeNotifier { /// The [Subtask]s List _subtasks = []; @@ -29,41 +18,30 @@ class SubtasksController extends ChangeNotifier { notifyListeners(); } - bool _isCreating = false; - - bool get isCreating => _isCreating; - - String taskId; + bool get isCreating => taskId == null || taskId!.isEmpty; - /// Only valid in case [state] == [LoadingState.error] - String errorMessage = ""; + String? taskId; SubtasksController({this.taskId = "", List? subtasks}) { - _isCreating = taskId == ""; if (!isCreating) { load(); - } else { - state = LoadingState.unspecified; } } + /// Loads a [Task] Future load() async { - state = LoadingState.loading; - if (!isCreating) { - await TaskService().getTask(id: taskId).then((task) { - subtasks = task.subtasks; - state = LoadingState.loaded; - }).onError( - (error, stackTrace) { - state = LoadingState.error; - }, - ); + if (isCreating) { return; } - state = LoadingState.loaded; + loadTask() async { + final task = await TaskService().getTask(id: taskId); + subtasks = task.subtasks; + } + + loadHandler(future: loadTask()); } - /// Delete the subtask by the index.dart + /// Delete the [Subtask] by its index int the list Future deleteByIndex(int index) async { if (index < 0 || index >= subtasks.length) { return; @@ -73,55 +51,60 @@ class SubtasksController extends ChangeNotifier { notifyListeners(); return; } - state = LoadingState.loading; - await TaskService().deleteSubTask(subtaskId: subtasks[index].id, taskId: taskId).then((value) { - if (value) { - _subtasks.removeAt(index); - state = LoadingState.loaded; - } - }).catchError((error, stackTrace) { - errorMessage = error.toString(); - state = LoadingState.error; - return null; - }); + await deleteById(subtasks[index].id); } /// Delete the [Subtask] by the id - Future delete(String id) async { - assert(!isCreating, "delete should not be used when creating a completely new SubTask list"); - int index = _subtasks.indexWhere((element) => element.id == id); - if (index != -1) { - deleteByIndex(index); + Future deleteById(String id) async { + assert(!isCreating, "deleteById should not be used when creating a completely new Subtask list"); + deleteSubtask() async { + await TaskService().deleteSubTask(subtaskId: id, taskId: taskId!).then((value) { + if (value) { + int index = _subtasks.indexWhere((element) => element.id == id); + if (index != -1) { + _subtasks.removeAt(index); + } + } + }); } + + loadHandler(future: deleteSubtask()); } /// Add the [Subtask] - Future add(Subtask subTask) async { + Future create(Subtask subTask) async { if (isCreating) { _subtasks.add(subTask); notifyListeners(); return; } - await TaskService().createSubTask(taskId: taskId, subTask: subTask).then((value) { - _subtasks.add(value); - state = LoadingState.loaded; - }).catchError((error, stackTrace) { - errorMessage = error.toString(); - state = LoadingState.error; - return null; - }); + createSubtask() async { + await TaskService().createSubTask(taskId: taskId!, subTask: subTask).then((value) { + _subtasks.add(value); + }); + } + + loadHandler(future: createSubtask()); } - Future updateSubtask({required Subtask subTask}) async { - if (!subTask.isCreating) { - state = LoadingState.loading; - await TaskService().updateSubtask(subtask: subTask, taskId: taskId).then((value) { - state = LoadingState.loaded; - }).catchError((error, stackTrace) { - // Just reload in case of an error - load(); - }); + Future update({required Subtask subtask, int? index}) async { + if (isCreating) { + assert( + index != null && index >= 0 && index < subtasks.length, + "When creating a subtask list and updating a subtask, a index for the subtask must be provided", + ); + subtasks[index!] = subtask; + return; } - notifyListeners(); + updateSubtask() async { + assert(!subtask.isCreating, "To update a subtask on the server the subtask must have an id"); + await TaskService().updateSubtask(subtask: subtask, taskId: taskId!); + int index = subtasks.indexWhere((element) => element.id == subtask.id); + if (index != -1) { + subtasks[index] = subtask; + } + } + + loadHandler(future: updateSubtask()); } } diff --git a/packages/helpwave_service/lib/src/api/tasks/controllers/task_controller.dart b/packages/helpwave_service/lib/src/api/tasks/controllers/task_controller.dart index 4e26f1e7..80061bb8 100644 --- a/packages/helpwave_service/lib/src/api/tasks/controllers/task_controller.dart +++ b/packages/helpwave_service/lib/src/api/tasks/controllers/task_controller.dart @@ -1,81 +1,45 @@ -import 'package:flutter/material.dart'; -import 'package:helpwave_util/loading_state.dart'; +import 'package:helpwave_util/loading.dart'; import 'package:helpwave_service/src/api/tasks/index.dart'; /// The Controller for managing a [TaskWithPatient] -class TaskController extends ChangeNotifier { - /// The [LoadingState] of the Controller - LoadingState _state = LoadingState.initializing; - - /// The current [Task], may or may not be loaded depending on the [_state] +class TaskController extends LoadingChangeNotifier { + /// The current [Task] TaskWithPatient _task; - /// The error message to show should only be used when [state] == [LoadingState.error] - String errorMessage = ""; - TaskController(this._task) { if (!_task.isCreating) { load(); - } else { - state = LoadingState.unspecified; } } - LoadingState get state => _state; - - set state(LoadingState value) { - _state = value; - notifyListeners(); - } - TaskWithPatient get task => _task; + set task(TaskWithPatient value) { _task = value; - _state = LoadingState.loaded; notifyListeners(); } - /// Used to trigger the notify call without having to copy or save the Task locally - updateTask(void Function(TaskWithPatient task) updateTransform, void Function(TaskWithPatient task) revertTransform) { - updateTransform(task); - if (!isCreating) { - TaskService().updateTask(task).then((value) { - if (value) { - state = LoadingState.loaded; - } else { - throw Error(); - } - }).catchError((error, stackTrace) { - revertTransform(task); - errorMessage = error.toString(); - state = LoadingState.error; - }); - } else { - state = LoadingState.loaded; - } - } + PatientMinimal get patient => task.patient; bool get isCreating => _task.isCreating; - // only create when a patient is assigned + /// Whether the [Task] object can be used to create a [Task] + /// + /// Create is only possible when a [Patient] is assigned to the [Task] bool get isReadyForCreate => !task.patient.isCreating; - PatientMinimal get patient => task.patient; - /// A function to load the [Task] load() async { - state = LoadingState.loading; - await TaskService().getTask(id: task.id).then((value) { - task = value; - state = LoadingState.loaded; - }).catchError((error, stackTrace) { - errorMessage = error.toString(); - state = LoadingState.error; - }); + loadTask() async { + await TaskService().getTask(id: task.id).then((value) { + task = value; + }); + } + loadHandler(future: loadTask()); } - /// Changes the Assignee + /// Changes the assigned [User] /// /// Without a backend request as we expect this to be done in the [AssigneeSelectController] Future changeAssignee(String assigneeId) async { @@ -140,14 +104,14 @@ class TaskController extends ChangeNotifier { /// Only usable when creating Future changePatient(PatientMinimal patient) async { - assert(task.isCreating, "Only use TaskController.changePatient, when you create a new task."); + assert(isCreating, "Only use TaskController.changePatient, when you create a new task."); task = TaskWithPatient.fromTaskAndPatient(task: task.copyWith(patientId: patient.id), patient: patient); notifyListeners(); } /// Creates the Task and returns Future create() async { - assert(!task.patient.isCreating, "A the patient must be set to create a task"); + assert(!isReadyForCreate, "A the patient must be set to create a task"); state = LoadingState.loading; return await TaskService().createTask(task).then((value) { task.copyWith(id: value); diff --git a/packages/helpwave_service/lib/src/api/tasks/controllers/ward_patients_controller.dart b/packages/helpwave_service/lib/src/api/tasks/controllers/ward_patients_controller.dart index e18d4d01..c93817d7 100644 --- a/packages/helpwave_service/lib/src/api/tasks/controllers/ward_patients_controller.dart +++ b/packages/helpwave_service/lib/src/api/tasks/controllers/ward_patients_controller.dart @@ -1,6 +1,6 @@ import 'package:flutter/cupertino.dart'; import 'package:helpwave_service/src/api/tasks/index.dart'; -import 'package:helpwave_util/loading_state.dart'; +import 'package:helpwave_util/loading.dart'; import 'package:helpwave_util/search.dart'; /// The Controller for managing [Patient]s in a Ward diff --git a/packages/helpwave_service/lib/src/api/tasks/data_types/patient.dart b/packages/helpwave_service/lib/src/api/tasks/data_types/patient.dart index 26b0ce61..db56424f 100644 --- a/packages/helpwave_service/lib/src/api/tasks/data_types/patient.dart +++ b/packages/helpwave_service/lib/src/api/tasks/data_types/patient.dart @@ -80,7 +80,7 @@ class Patient extends PatientMinimal { List tasks; bool isDischarged; - get isUnassigned => bed == null && room == null; + get isNotAssignedToBed => bed == null && room == null; get isActive => bed != null && room != null; @@ -109,6 +109,26 @@ class Patient extends PatientMinimal { this.room, this.bed, }); + + Patient copyWith({ + String? id, + String? name, + List? tasks, + String? notes, + bool? isDischarged, + RoomMinimal? room, + BedMinimal? bed, + }) { + return Patient( + id: id ?? this.id, + name: name ?? this.name, + tasks: tasks ?? this.tasks, + notes: notes ?? this.notes, + isDischarged: isDischarged ?? this.isDischarged, + room: room ?? this.room, + bed: bed ?? this.bed, + ); + } } /// A data class which maps all [PatientAssignmentStatus]es to a [List] of [Patient]s diff --git a/packages/helpwave_service/lib/src/api/tasks/services/patient_svc.dart b/packages/helpwave_service/lib/src/api/tasks/services/patient_svc.dart index 32856a47..a6898183 100644 --- a/packages/helpwave_service/lib/src/api/tasks/services/patient_svc.dart +++ b/packages/helpwave_service/lib/src/api/tasks/services/patient_svc.dart @@ -161,11 +161,11 @@ class PatientService { } /// Update a [Patient] - Future updatePatient(Patient patient) async { + Future updatePatient({required String id, String? notes, String? name}) async { UpdatePatientRequest request = UpdatePatientRequest( - id: patient.id, - notes: patient.notes, - humanReadableIdentifier: patient.name, + id: id, + notes: notes, + humanReadableIdentifier: name, ); UpdatePatientResponse response = await patientService.updatePatient( request, diff --git a/packages/helpwave_service/lib/src/api/tasks/services/task_svc.dart b/packages/helpwave_service/lib/src/api/tasks/services/task_svc.dart index c4f393dd..2de819e2 100644 --- a/packages/helpwave_service/lib/src/api/tasks/services/task_svc.dart +++ b/packages/helpwave_service/lib/src/api/tasks/services/task_svc.dart @@ -74,6 +74,39 @@ class TaskService { ); } + /// Loads the [Task]s assigned to the current [User] + Future> getAssignedTasks({String? id}) async { + GetAssignedTasksRequest request = GetAssignedTasksRequest(); + GetAssignedTasksResponse response = await taskService.getAssignedTasks( + request, + options: CallOptions(metadata: TasksAPIServiceClients().getMetaData()), + ); + + return response.tasks + .map((task) => TaskWithPatient( + id: task.id, + name: task.name, + notes: task.description, + isPublicVisible: task.public, + status: GRPCTypeConverter.taskStatusFromGRPC(task.status), + assigneeId: task.assignedUserId, + dueDate: task.dueAt.toDateTime(), + patient: PatientMinimal(id: task.patient.id, name: task.patient.humanReadableIdentifier), + subtasks: task.subtasks + .map((subtask) => Subtask( + id: subtask.id, + taskId: task.id, + name: subtask.name, + isDone: subtask.done, + )) + .toList(), + patientId: task.patient.id, + createdBy: task.createdBy, + creationDate: task.createdAt.toDateTime(), + )) + .toList(); + } + Future createTask(TaskWithPatient task) async { CreateTaskRequest request = CreateTaskRequest( name: task.name, diff --git a/packages/helpwave_service/lib/src/api/user/controllers/user_controller.dart b/packages/helpwave_service/lib/src/api/user/controllers/user_controller.dart index dce15479..6d975aa2 100644 --- a/packages/helpwave_service/lib/src/api/user/controllers/user_controller.dart +++ b/packages/helpwave_service/lib/src/api/user/controllers/user_controller.dart @@ -1,5 +1,5 @@ import 'package:flutter/material.dart'; -import 'package:helpwave_util/loading_state.dart'; +import 'package:helpwave_util/loading.dart'; import '../index.dart'; /// The Controller for managing a [User] diff --git a/packages/helpwave_util/lib/loading.dart b/packages/helpwave_util/lib/loading.dart new file mode 100644 index 00000000..938db0bd --- /dev/null +++ b/packages/helpwave_util/lib/loading.dart @@ -0,0 +1 @@ +export 'package:helpwave_util/src/loading/index.dart'; diff --git a/packages/helpwave_util/lib/loading_state.dart b/packages/helpwave_util/lib/loading_state.dart deleted file mode 100644 index b47bbe00..00000000 --- a/packages/helpwave_util/lib/loading_state.dart +++ /dev/null @@ -1 +0,0 @@ -export 'package:helpwave_util/src/loading_state/type.dart'; diff --git a/packages/helpwave_util/lib/src/loading/index.dart b/packages/helpwave_util/lib/src/loading/index.dart new file mode 100644 index 00000000..e47463c6 --- /dev/null +++ b/packages/helpwave_util/lib/src/loading/index.dart @@ -0,0 +1,2 @@ +export 'type.dart'; +export 'loading_change_notifier.dart'; diff --git a/packages/helpwave_util/lib/src/loading/loading_change_notifier.dart b/packages/helpwave_util/lib/src/loading/loading_change_notifier.dart new file mode 100644 index 00000000..53dfa8c3 --- /dev/null +++ b/packages/helpwave_util/lib/src/loading/loading_change_notifier.dart @@ -0,0 +1,48 @@ +import 'package:flutter/cupertino.dart'; +import '../../loading.dart'; + +/// A [ChangeNotifier] that manages a [LoadingState] to indicate to components what state they should show +class LoadingChangeNotifier extends ChangeNotifier { + /// The [LoadingState] of the Controller + LoadingState _state = LoadingState.initializing; + + /// The [LoadingState] of the Controller + LoadingState get state => _state; + + /// The Error, when the Controller is [LoadingState.error] + Object? error; + + /// Function + changeState(LoadingState value) { + _state = value; + notifyListeners(); + } + + LoadingChangeNotifier(); + + Future loadHandler({ + required Future future, + Future Function(Object? error, StackTrace stackTrace)? errorHandler, + }) async { + defaultErrorHandler(errorObj, _) async { + error = errorObj.toString(); + return false; + } + + changeState(LoadingState.loading); + await future.then((_) => changeState(LoadingState.loaded)).onError((error, stackTrace) async { + if (errorHandler != null) { + try { + bool isHandled = await errorHandler(error, stackTrace); + if (isHandled) { + return; + } + } catch (_) {} + } else { + defaultErrorHandler(error, stackTrace); + } + + changeState(LoadingState.error); + }); + } +} diff --git a/packages/helpwave_util/lib/src/loading_state/type.dart b/packages/helpwave_util/lib/src/loading/type.dart similarity index 100% rename from packages/helpwave_util/lib/src/loading_state/type.dart rename to packages/helpwave_util/lib/src/loading/type.dart diff --git a/packages/helpwave_widget/lib/src/loading/loading_and_error_widget.dart b/packages/helpwave_widget/lib/src/loading/loading_and_error_widget.dart index d9b26fc7..1f64ddf1 100644 --- a/packages/helpwave_widget/lib/src/loading/loading_and_error_widget.dart +++ b/packages/helpwave_widget/lib/src/loading/loading_and_error_widget.dart @@ -1,6 +1,6 @@ import 'package:flutter/cupertino.dart'; import 'package:helpwave_theme/constants.dart'; -import 'package:helpwave_util/loading_state.dart'; +import 'package:helpwave_util/loading.dart'; import 'package:helpwave_widget/loading.dart'; /// A [Widget] to show different [Widget]s depending on the [LoadingState] diff --git a/packages/helpwave_widget/lib/src/loading/loading_future_builder.dart b/packages/helpwave_widget/lib/src/loading/loading_future_builder.dart index ccfb938e..08b1625b 100644 --- a/packages/helpwave_widget/lib/src/loading/loading_future_builder.dart +++ b/packages/helpwave_widget/lib/src/loading/loading_future_builder.dart @@ -1,5 +1,5 @@ import 'package:flutter/cupertino.dart'; -import 'package:helpwave_util/loading_state.dart'; +import 'package:helpwave_util/loading.dart'; import 'package:helpwave_widget/loading.dart'; /// A Wrapper for the standard [FutureBuilder] to easily distinguish the three From a0759182caac9b1b32ef697a107bf804f7a80a76 Mon Sep 17 00:00:00 2001 From: Felix Thape Date: Tue, 17 Sep 2024 14:40:18 +0200 Subject: [PATCH 6/9] feat: update all controllers --- .../tasks/lib/components/assignee_select.dart | 53 ++++--- .../lib/components/patient_bottom_sheet.dart | 2 +- .../lib/components/task_bottom_sheet.dart | 138 ++++++++--------- .../lib/components/task_expansion_tile.dart | 2 +- .../lib/components/user_bottom_sheet.dart | 2 +- .../helpwave_localization/lib/l10n/app_de.arb | 3 +- .../helpwave_localization/lib/l10n/app_en.arb | 3 +- .../src/api/offline/offline_client_store.dart | 9 +- .../assignee_select_controller.dart | 60 -------- .../lib/src/api/tasks/controllers/index.dart | 1 - .../controllers/my_tasks_controller.dart | 4 +- .../tasks/controllers/task_controller.dart | 145 ++++++++++-------- .../controllers/ward_patients_controller.dart | 30 ++-- .../lib/src/api/tasks/data_types/patient.dart | 3 +- .../src/api/tasks/services/patient_svc.dart | 1 - .../lib/src/api/tasks/services/task_svc.dart | 55 +++++-- .../src/loading/loading_change_notifier.dart | 9 +- .../lib/content_selection.dart | 4 +- .../lib/src/content_selection/index.dart | 4 + .../src/content_selection/list_select.dart | 28 ++++ .../src/loading/loading_future_builder.dart | 54 ++++--- 21 files changed, 308 insertions(+), 302 deletions(-) delete mode 100644 packages/helpwave_service/lib/src/api/tasks/controllers/assignee_select_controller.dart create mode 100644 packages/helpwave_widget/lib/src/content_selection/index.dart create mode 100644 packages/helpwave_widget/lib/src/content_selection/list_select.dart diff --git a/apps/tasks/lib/components/assignee_select.dart b/apps/tasks/lib/components/assignee_select.dart index 746dc1d0..02e4794f 100644 --- a/apps/tasks/lib/components/assignee_select.dart +++ b/apps/tasks/lib/components/assignee_select.dart @@ -1,18 +1,23 @@ +import 'dart:async'; import 'package:flutter/material.dart'; import 'package:helpwave_localization/localization.dart'; -import 'package:helpwave_service/tasks.dart'; import 'package:helpwave_service/user.dart'; import 'package:helpwave_theme/constants.dart'; import 'package:helpwave_widget/bottom_sheets.dart'; -import 'package:helpwave_widget/loading.dart'; -import 'package:provider/provider.dart'; +import 'package:helpwave_widget/content_selection.dart'; /// A [BottomSheet] for selecting a assignee -class AssigneeSelect extends StatelessWidget { +class AssigneeSelectBottomSheet extends StatelessWidget { /// The callback when the assignee should be changed - final Function(User assignee) onChanged; + /// + /// Null if the assignee should be removed + final Function(User? assignee) onChanged; - const AssigneeSelect({super.key, required this.onChanged}); + final FutureOr> users; + + final String? selectedId; + + const AssigneeSelectBottomSheet({super.key, required this.onChanged, required this.users, this.selectedId}); @override Widget build(BuildContext context) { @@ -21,24 +26,26 @@ class AssigneeSelect extends StatelessWidget { onClosing: () => {}, builder: (context) => Padding( padding: const EdgeInsets.symmetric(vertical: paddingMedium), - child: Consumer(builder: (context, assigneeSelectController, __) { - return LoadingAndErrorWidget( - state: assigneeSelectController.state, - child: Column( - children: assigneeSelectController.users.map((user) => - ListTile( - onTap: () { - assigneeSelectController.changeAssignee(user.id).then((value) { - onChanged(user); - }); - }, - leading: CircleAvatar( - foregroundColor: Colors.blue, backgroundImage: NetworkImage(user.profileUrl.toString())), - title: Text(user.nickName), - )).toList(), + child: Column( + children: [ + TextButton( + child: Text(context.localization!.remove), + onPressed: () => onChanged(null), + ), + const SizedBox(height: 10), + ListSelect( + items: users, + onSelect: onChanged, + builder: (context, user, select) => ListTile( + onTap: select, + leading: CircleAvatar( + foregroundColor: Colors.blue, backgroundImage: NetworkImage(user.profileUrl.toString())), + title: Text(user.nickName, + style: TextStyle(decoration: user.id == selectedId ? TextDecoration.underline : null)), + ), ), - ); - }), + ], + ), ), ); } diff --git a/apps/tasks/lib/components/patient_bottom_sheet.dart b/apps/tasks/lib/components/patient_bottom_sheet.dart index cb119c5c..431773a4 100644 --- a/apps/tasks/lib/components/patient_bottom_sheet.dart +++ b/apps/tasks/lib/components/patient_bottom_sheet.dart @@ -151,7 +151,7 @@ class _PatientBottomSheetState extends State { Center( child: Consumer(builder: (context, patientController, _) { return LoadingFutureBuilder( - future: loadRoomsWithBeds(patientController.patient.id), + data: loadRoomsWithBeds(patientController.patient.id), // TODO use a better loading widget loadingWidget: const SizedBox(), thenWidgetBuilder: (context, beds) { diff --git a/apps/tasks/lib/components/task_bottom_sheet.dart b/apps/tasks/lib/components/task_bottom_sheet.dart index 44e62720..7f2590d4 100644 --- a/apps/tasks/lib/components/task_bottom_sheet.dart +++ b/apps/tasks/lib/components/task_bottom_sheet.dart @@ -1,7 +1,9 @@ import 'package:flutter/material.dart'; import 'package:helpwave_localization/localization.dart'; +import 'package:helpwave_service/auth.dart'; import 'package:helpwave_service/user.dart'; import 'package:helpwave_theme/constants.dart'; +import 'package:helpwave_util/loading.dart'; import 'package:helpwave_widget/bottom_sheets.dart'; import 'package:helpwave_widget/loading.dart'; import 'package:helpwave_widget/text_input.dart'; @@ -137,24 +139,24 @@ class _TaskBottomSheetState extends State { child: Consumer( builder: (context, taskController, child) => taskController.isCreating ? Padding( - padding: const EdgeInsets.only(top: paddingSmall), - child: Align( - alignment: Alignment.topRight, - child: TextButton( - style: buttonStyleBig, - onPressed: taskController.isReadyForCreate - ? () { - taskController.create().then((value) { - if (value) { - Navigator.pop(context); - } - }); - } - : null, - child: Text(context.localization!.create), - ), - ), - ) + padding: const EdgeInsets.only(top: paddingSmall), + child: Align( + alignment: Alignment.topRight, + child: TextButton( + style: buttonStyleBig, + onPressed: taskController.isReadyForCreate + ? () { + taskController.create().then((value) { + if (value) { + Navigator.pop(context); + } + }); + } + : null, + child: Text(context.localization!.create), + ), + ), + ) : const SizedBox(), ), ), @@ -166,34 +168,35 @@ class _TaskBottomSheetState extends State { children: [ Center( child: Consumer(builder: - // TODO move this to its own component + // TODO move this to its own component (context, taskController, __) { return LoadingAndErrorWidget.pulsing( state: taskController.state, child: !taskController.isCreating ? Text(taskController.patient.name) : LoadingFutureBuilder( - future: PatientService().getPatientList(), - loadingWidget: const PulsingContainer(), - thenWidgetBuilder: (context, patientList) { - List patients = patientList.active + patientList.unassigned; - return DropdownButton( - underline: const SizedBox(), - iconEnabledColor: Theme.of(context).colorScheme.secondary.withOpacity(0.6), - // removes the default underline - padding: EdgeInsets.zero, - hint: Text( - context.localization!.selectPatient, - style: TextStyle(color: Theme.of(context).colorScheme.secondary.withOpacity(0.6)), - ), - isDense: true, - items: patients - .map((patient) => DropdownMenuItem(value: patient, child: Text(patient.name))) - .toList(), - value: taskController.patient.isCreating ? null : taskController.patient, - onChanged: (patient) => taskController.changePatient(patient ?? PatientMinimal.empty()), - ); - }), + data: PatientService().getPatientList(), + loadingWidget: const PulsingContainer(), + thenWidgetBuilder: (context, patientList) { + List patients = patientList.active + patientList.unassigned; + return DropdownButton( + underline: const SizedBox(), + iconEnabledColor: Theme.of(context).colorScheme.secondary.withOpacity(0.6), + // removes the default underline + padding: EdgeInsets.zero, + hint: Text( + context.localization!.selectPatient, + style: TextStyle(color: Theme.of(context).colorScheme.secondary.withOpacity(0.6)), + ), + isDense: true, + items: patients + .map((patient) => DropdownMenuItem(value: patient, child: Text(patient.name))) + .toList(), + value: taskController.patient.isCreating ? null : taskController.patient, + onChanged: (patient) => + taskController.changePatient(patient ?? PatientMinimal.empty()), + ); + }), ); }), ), @@ -207,43 +210,30 @@ class _TaskBottomSheetState extends State { label: context.localization!.assignedTo, onTap: () => context.pushModal( context: context, - builder: (BuildContext context) => LoadingAndErrorWidget( - state: taskController.state, - child: ChangeNotifierProvider( - create: (BuildContext context) => AssigneeSelectController( - selected: taskController.task.assigneeId, - taskId: taskController.task.id, - ), - child: AssigneeSelect( - onChanged: (assignee) { - taskController.changeAssignee(assignee.id).then((value) => Navigator.of(context).pop()); - }, - ), - ), + builder: (BuildContext context) => AssigneeSelectBottomSheet( + users: OrganizationService() + .getMembersByOrganization(CurrentWardService().currentWard!.organizationId), + onChanged: (User? assignee) { + taskController.changeAssignee(assignee); + Navigator.pop(context); + }, + selectedId: taskController.task.assigneeId, ), ), - // TODO maybe do some optimisations here - // TODO update the error and loading widgets - valueWidget: LoadingAndErrorWidget.pulsing( - state: taskController.state, - child: taskController.task.hasAssignee - ? ChangeNotifierProvider( - create: (context) => UserController(User.empty(id: taskController.task.assigneeId!)), - child: Consumer( - builder: (context, userController, __) => LoadingAndErrorWidget.pulsing( - state: userController.state, + valueWidget: taskController.task.hasAssignee + ? LoadingAndErrorWidget.pulsing( + state: taskController.assignee != null ? LoadingState.loaded : LoadingState.loading, child: Text( - userController.user.name, + // Never the case that we display the empty String, but the text is computed + // before being displayed + taskController.assignee?.name ?? "", style: editableValueTextStyle(context), ), + ) + : Text( + context.localization!.unassigned, + style: editableValueTextStyle(context), ), - ), - ) - : Text( - context.localization!.unassigned, - style: editableValueTextStyle(context), - ), - ), ); }), Consumer( @@ -278,7 +268,8 @@ class _TaskBottomSheetState extends State { lastDate: DateTime.now().add(const Duration(days: 365 * 5)), builder: (context, child) { // Overwrite the Theme - ThemeData pickerTheme = Theme.of(context).copyWith(textButtonTheme: const TextButtonThemeData()); + ThemeData pickerTheme = + Theme.of(context).copyWith(textButtonTheme: const TextButtonThemeData()); return Theme(data: pickerTheme, child: child ?? const SizedBox()); }, ).then((date) async { @@ -389,8 +380,7 @@ class _TaskBottomSheetState extends State { ), ), ], - ) - ), + )), ), ), ); diff --git a/apps/tasks/lib/components/task_expansion_tile.dart b/apps/tasks/lib/components/task_expansion_tile.dart index a5c31a61..de316ace 100644 --- a/apps/tasks/lib/components/task_expansion_tile.dart +++ b/apps/tasks/lib/components/task_expansion_tile.dart @@ -58,7 +58,7 @@ class TaskExpansionTile extends StatelessWidget { builder: (context) => TaskBottomSheet(task: task, patient: task.patient), ).then((_) { AssignedTasksController controller = Provider.of(context, listen: false); - controller.loadHandler(); + controller.load(); }); }, child: TaskCard( diff --git a/apps/tasks/lib/components/user_bottom_sheet.dart b/apps/tasks/lib/components/user_bottom_sheet.dart index 41d94aa1..4b18600a 100644 --- a/apps/tasks/lib/components/user_bottom_sheet.dart +++ b/apps/tasks/lib/components/user_bottom_sheet.dart @@ -77,7 +77,7 @@ class _UserBottomSheetState extends State { child: Consumer(builder: (context, currentWardController, __) { return LoadingFutureBuilder( loadingWidget: const SizedBox(), - future: + data: WardService().getWardOverviews(organizationId: currentWardController.currentWard!.organizationId), thenWidgetBuilder: (BuildContext context, List data) { double menuWidth = min(250, width * 0.7); diff --git a/packages/helpwave_localization/lib/l10n/app_de.arb b/packages/helpwave_localization/lib/l10n/app_de.arb index 4490bc54..18a2eeef 100644 --- a/packages/helpwave_localization/lib/l10n/app_de.arb +++ b/packages/helpwave_localization/lib/l10n/app_de.arb @@ -168,5 +168,6 @@ "darkMode": "Dunkel", "lightMode": "Hell", "system": "System", - "newTaskOrPatient": "Neu" + "newTaskOrPatient": "Neu", + "remove": "Entfernen" } diff --git a/packages/helpwave_localization/lib/l10n/app_en.arb b/packages/helpwave_localization/lib/l10n/app_en.arb index c516a9ab..0321789b 100644 --- a/packages/helpwave_localization/lib/l10n/app_en.arb +++ b/packages/helpwave_localization/lib/l10n/app_en.arb @@ -168,5 +168,6 @@ "darkMode": "Dark", "lightMode": "Light", "system": "System", - "newTaskOrPatient": "New" + "newTaskOrPatient": "New", + "remove": "Remove" } diff --git a/packages/helpwave_service/lib/src/api/offline/offline_client_store.dart b/packages/helpwave_service/lib/src/api/offline/offline_client_store.dart index d61296a2..5f62cd5a 100644 --- a/packages/helpwave_service/lib/src/api/offline/offline_client_store.dart +++ b/packages/helpwave_service/lib/src/api/offline/offline_client_store.dart @@ -15,14 +15,6 @@ const String profileUrl = "https://helpwave.de/favicon.ico"; final List initialOrganizations = [ Organization( id: "organization1", - shortName: "Test", - longName: "Test Organization", - avatarURL: profileUrl, - email: "test@helpwave.de", - isPersonal: false, - isVerified: true), - Organization( - id: "organization2", shortName: "MK", longName: "Musterklinikum", avatarURL: profileUrl, @@ -97,6 +89,7 @@ final List initialTasks = initialPatients name: "Task ${index + 1}", patientId: patient.id, notes: '', + assigneeId: [initialUsers[0].id, null, initialUsers[2].id][index], ))) .expand((element) => element) .toList(); diff --git a/packages/helpwave_service/lib/src/api/tasks/controllers/assignee_select_controller.dart b/packages/helpwave_service/lib/src/api/tasks/controllers/assignee_select_controller.dart deleted file mode 100644 index 99f6886c..00000000 --- a/packages/helpwave_service/lib/src/api/tasks/controllers/assignee_select_controller.dart +++ /dev/null @@ -1,60 +0,0 @@ -import 'package:helpwave_service/auth.dart'; -import 'package:helpwave_service/src/api/user/index.dart'; -import 'package:helpwave_util/loading.dart'; -import 'package:helpwave_service/tasks.dart'; - -/// The Controller for selecting a [User] as the assignee of a [Task] -class AssigneeSelectController extends LoadingChangeNotifier { - /// The selected [User] identifier - String? _selected; - - String? get selected => _selected; - - User? get selectedUser => _users.firstWhere((user) => user.id == selected); - - /// The currently loaded user - List _users = []; - - /// The currently loaded users - List get users => _users; - - /// The identifier of the current [Task] it determines whether - /// changes are pushed to the server - String? _taskId; - - /// Whether the object is - bool get isCreating => _taskId == null && _taskId!.isNotEmpty; // TODO remove .isNotEmpty when semantic is changed - - AssigneeSelectController({String? selected, String? taskId}) { - _selected = selected; - _taskId = taskId; - load(); - } - - /// Loads the users - Future load() async { - loadUsersFuture() async { - String? currentOrganization = CurrentWardService().currentWard?.organizationId; - if (currentOrganization == null) { - // TODO throw a better error here - throw "Organization Id not set in CurrentWardService while trying to load in AssigneeSelectController"; - } - _users = await OrganizationService().getMembersByOrganization(currentOrganization); - } - - await loadHandler(future: loadUsersFuture()); - } - - /// Change the assignee - Future changeAssignee(String id) async { - changeAssigneeFuture() async { - if (!isCreating) { - await TaskService().assignToUser(taskId: _taskId!, userId: id).then((value) => _selected = id); - } else { - _selected = id; - } - } - - await loadHandler(future: changeAssigneeFuture()); - } -} diff --git a/packages/helpwave_service/lib/src/api/tasks/controllers/index.dart b/packages/helpwave_service/lib/src/api/tasks/controllers/index.dart index a987ab71..2940b0c6 100644 --- a/packages/helpwave_service/lib/src/api/tasks/controllers/index.dart +++ b/packages/helpwave_service/lib/src/api/tasks/controllers/index.dart @@ -1,6 +1,5 @@ export 'patient_controller.dart'; export 'subtask_list_controller.dart'; export 'task_controller.dart'; -export 'assignee_select_controller.dart'; export 'my_tasks_controller.dart'; export 'ward_patients_controller.dart'; diff --git a/packages/helpwave_service/lib/src/api/tasks/controllers/my_tasks_controller.dart b/packages/helpwave_service/lib/src/api/tasks/controllers/my_tasks_controller.dart index 3953085f..70b89070 100644 --- a/packages/helpwave_service/lib/src/api/tasks/controllers/my_tasks_controller.dart +++ b/packages/helpwave_service/lib/src/api/tasks/controllers/my_tasks_controller.dart @@ -19,11 +19,11 @@ class AssignedTasksController extends LoadingChangeNotifier { List get done => _tasks.where((element) => element.status == TaskStatus.done).toList(); AssignedTasksController() { - loadTasks(); + load(); } /// Loads the [Task]s - Future loadTasks() async { + Future load() async { loadTasksFuture() async { _tasks = await TaskService().getAssignedTasks(); } diff --git a/packages/helpwave_service/lib/src/api/tasks/controllers/task_controller.dart b/packages/helpwave_service/lib/src/api/tasks/controllers/task_controller.dart index 80061bb8..2eae7924 100644 --- a/packages/helpwave_service/lib/src/api/tasks/controllers/task_controller.dart +++ b/packages/helpwave_service/lib/src/api/tasks/controllers/task_controller.dart @@ -1,6 +1,8 @@ import 'package:helpwave_util/loading.dart'; import 'package:helpwave_service/src/api/tasks/index.dart'; +import '../../../../user.dart'; + /// The Controller for managing a [TaskWithPatient] class TaskController extends LoadingChangeNotifier { /// The current [Task] @@ -14,7 +16,6 @@ class TaskController extends LoadingChangeNotifier { TaskWithPatient get task => _task; - set task(TaskWithPatient value) { _task = value; notifyListeners(); @@ -22,6 +23,10 @@ class TaskController extends LoadingChangeNotifier { PatientMinimal get patient => task.patient; + User? _assignee; + + User? get assignee => _assignee; + bool get isCreating => _task.isCreating; /// Whether the [Task] object can be used to create a [Task] @@ -32,79 +37,100 @@ class TaskController extends LoadingChangeNotifier { /// A function to load the [Task] load() async { loadTask() async { - await TaskService().getTask(id: task.id).then((value) { + await TaskService().getTask(id: task.id).then((value) async { task = value; + if (task.hasAssignee) { + UserService().getUser(id: task.assigneeId!).then((value) => _assignee = value); + } }); } + loadHandler(future: loadTask()); } /// Changes the assigned [User] - /// - /// Without a backend request as we expect this to be done in the [AssigneeSelectController] - Future changeAssignee(String assigneeId) async { - String? old = task.assigneeId; - updateTask( - (task) { - task.assigneeId = assigneeId; - }, - (task) { - task.assigneeId = old; - }, - ); + Future changeAssignee(User? user) async { + if (isCreating) { + task.assigneeId = user?.id; + _assignee = user; + notifyListeners(); + return; + } + changeAssigneeFuture() async { + await TaskService().changeAssignee(taskId: task.id, userId: user?.id).then((value) { + task.assigneeId = user?.id; + _assignee = user; + }); + } + + await loadHandler(future: changeAssigneeFuture()); } Future changeName(String name) async { - String oldName = task.name; - updateTask( - (task) { - task.name = name; - }, - (task) { - task.name = oldName; - }, - ); + if (isCreating) { + task = TaskWithPatient.fromTaskAndPatient(task: task.copyWith(name: name), patient: task.patient); + notifyListeners(); + return; + } + updateName() async { + await TaskService().updateTask(taskId: task.id, name: name).then( + (_) => task = TaskWithPatient.fromTaskAndPatient(task: task.copyWith(name: name), patient: task.patient)); + } + + loadHandler(future: updateName()); } Future changeIsPublic(bool isPublic) async { - bool old = task.isPublicVisible; - updateTask( - (task) { - task.isPublicVisible = isPublic; - }, - (task) { - task.isPublicVisible = old; - }, - ); + if (isCreating) { + task = TaskWithPatient.fromTaskAndPatient(task: task.copyWith(isPublicVisible: isPublic), patient: task.patient); + notifyListeners(); + return; + } + updateIsPublic() async { + await TaskService().updateTask(taskId: task.id, isPublic: isPublic).then((_) => task = + TaskWithPatient.fromTaskAndPatient(task: task.copyWith(isPublicVisible: isPublic), patient: task.patient)); + } + + loadHandler(future: updateIsPublic()); } Future changeNotes(String notes) async { - String oldNotes = notes; - updateTask( - (task) { - task.notes = notes; - }, - (task) { - task.notes = oldNotes; - }, - ); + if (isCreating) { + task = TaskWithPatient.fromTaskAndPatient(task: task.copyWith(notes: notes), patient: task.patient); + notifyListeners(); + return; + } + updateNotes() async { + await TaskService().updateTask(taskId: task.id, notes: notes).then( + (_) => task = TaskWithPatient.fromTaskAndPatient(task: task.copyWith(notes: notes), patient: task.patient)); + } + + loadHandler(future: updateNotes()); } Future changeDueDate(DateTime? dueDate) async { - DateTime? old = task.dueDate; - updateTask( - (task) { - task.dueDate = dueDate; - }, - (task) { - task.dueDate = old; - }, - ); + if (isCreating) { + task = TaskWithPatient.fromTaskAndPatient(task: task.copyWith(dueDate: dueDate), patient: task.patient); + notifyListeners(); + return; + } + updateDueDate() async { + await TaskService().updateTask(taskId: task.id, dueDate: dueDate).then((_) => + task = TaskWithPatient.fromTaskAndPatient(task: task.copyWith(dueDate: dueDate), patient: task.patient)); + } + + removeDueDate() async { + await TaskService().removeDueDate(taskId: task.id).then((_) => + task = TaskWithPatient.fromTaskAndPatient(task: task.copyWith(dueDate: dueDate), patient: task.patient)); + } + + loadHandler(future: dueDate == null ? removeDueDate() : updateDueDate()); } - /// Only usable when creating + /// Only usable when creating a [Task] Future changePatient(PatientMinimal patient) async { assert(isCreating, "Only use TaskController.changePatient, when you create a new task."); + assert(!patient.isCreating, "The patient you are trying to attach the Task to must exist"); task = TaskWithPatient.fromTaskAndPatient(task: task.copyWith(patientId: patient.id), patient: patient); notifyListeners(); } @@ -112,15 +138,12 @@ class TaskController extends LoadingChangeNotifier { /// Creates the Task and returns Future create() async { assert(!isReadyForCreate, "A the patient must be set to create a task"); - state = LoadingState.loading; - return await TaskService().createTask(task).then((value) { - task.copyWith(id: value); - state = LoadingState.loaded; - return true; - }).catchError((error, stackTrace) { - errorMessage = error.toString(); - state = LoadingState.error; - return false; - }); + createTask() async { + await TaskService().createTask(task).then((value) { + task.copyWith(id: value); + }); + } + + return loadHandler(future: createTask()); } } diff --git a/packages/helpwave_service/lib/src/api/tasks/controllers/ward_patients_controller.dart b/packages/helpwave_service/lib/src/api/tasks/controllers/ward_patients_controller.dart index c93817d7..c1a29d76 100644 --- a/packages/helpwave_service/lib/src/api/tasks/controllers/ward_patients_controller.dart +++ b/packages/helpwave_service/lib/src/api/tasks/controllers/ward_patients_controller.dart @@ -1,13 +1,9 @@ -import 'package:flutter/cupertino.dart'; import 'package:helpwave_service/src/api/tasks/index.dart'; import 'package:helpwave_util/loading.dart'; import 'package:helpwave_util/search.dart'; -/// The Controller for managing [Patient]s in a Ward -class WardPatientsController extends ChangeNotifier { - /// The [LoadingState] of the Controller - LoadingState state = LoadingState.initializing; - +/// The Controller for managing [Patient]s in a [Ward] +class WardPatientsController extends LoadingChangeNotifier { /// The [Patient]s mapped by the [PatientsByAssignmentStatus] PatientsByAssignmentStatus _patientsByAssignmentStatus = PatientsByAssignmentStatus(); @@ -70,22 +66,20 @@ class WardPatientsController extends ChangeNotifier { return results; } - /// Loads the [patients] + /// Loads the [Patient]s Future load() async { - state = LoadingState.loading; - notifyListeners(); - - _patientsByAssignmentStatus = await PatientService().getPatientList(); - state = LoadingState.loaded; - notifyListeners(); + loadPatients() async { + _patientsByAssignmentStatus = await PatientService().getPatientList(); + } + loadHandler(future: loadPatients()); } /// Discharges the patient the [patients] Future discharge(String patientId) async { - state = LoadingState.loading; - notifyListeners(); - await PatientService().dischargePatient(patientId: patientId); - // Here we can maybe use optimistic updates - load(); + dischargePatient() async { + await PatientService().dischargePatient(patientId: patientId); + await load(); + } + loadHandler(future: dischargePatient()); } } diff --git a/packages/helpwave_service/lib/src/api/tasks/data_types/patient.dart b/packages/helpwave_service/lib/src/api/tasks/data_types/patient.dart index db56424f..9a4adc94 100644 --- a/packages/helpwave_service/lib/src/api/tasks/data_types/patient.dart +++ b/packages/helpwave_service/lib/src/api/tasks/data_types/patient.dart @@ -136,13 +136,12 @@ class PatientsByAssignmentStatus { List active; List unassigned; List discharged; - List all; + List get all => active + unassigned + discharged; PatientsByAssignmentStatus({ this.active = const [], this.unassigned = const [], this.discharged = const [], - this.all = const [], }); byAssignmentStatus(PatientAssignmentStatus status) { diff --git a/packages/helpwave_service/lib/src/api/tasks/services/patient_svc.dart b/packages/helpwave_service/lib/src/api/tasks/services/patient_svc.dart index a6898183..5695ddbe 100644 --- a/packages/helpwave_service/lib/src/api/tasks/services/patient_svc.dart +++ b/packages/helpwave_service/lib/src/api/tasks/services/patient_svc.dart @@ -59,7 +59,6 @@ class PatientService { final discharged = response.dischargedPatients.map(mapping).toList(); return PatientsByAssignmentStatus( - all: active + unassigned + discharged, active: active, unassigned: unassigned, discharged: discharged, diff --git a/packages/helpwave_service/lib/src/api/tasks/services/task_svc.dart b/packages/helpwave_service/lib/src/api/tasks/services/task_svc.dart index 2de819e2..f32e175f 100644 --- a/packages/helpwave_service/lib/src/api/tasks/services/task_svc.dart +++ b/packages/helpwave_service/lib/src/api/tasks/services/task_svc.dart @@ -124,16 +124,20 @@ class TaskService { return response.id; } - /// Assign a [Task] to a [User] - Future assignToUser({required String taskId, required String userId}) async { - AssignTaskRequest request = AssignTaskRequest(taskId: taskId, userId: userId); - AssignTaskResponse response = await taskService.assignTask( - request, - options: CallOptions(metadata: TasksAPIServiceClients().getMetaData()), - ); - - if (!response.isInitialized()) { - // Handle error + /// Assign a [Task] to a [User] or unassign the [User] + Future changeAssignee({required String taskId, required String? userId}) async { + if(userId != null){ + AssignTaskRequest request = AssignTaskRequest(taskId: taskId, userId: userId); + await taskService.assignTask( + request, + options: CallOptions(metadata: TasksAPIServiceClients().getMetaData()), + ); + } else { + UnassignTaskRequest request = UnassignTaskRequest(taskId: taskId, userId: userId); + await taskService.unassignTask( + request, + options: CallOptions(metadata: TasksAPIServiceClients().getMetaData()), + ); } } @@ -184,14 +188,21 @@ class TaskService { return response.isInitialized(); } - Future updateTask(Task task) async { + Future updateTask({ + required String taskId, + String? name, + String? notes, + DateTime? dueDate, + bool? isPublic, + TaskStatus? status, + }) async { UpdateTaskRequest request = UpdateTaskRequest( - id: task.id, - name: task.name, - description: task.notes, - dueAt: task.dueDate != null ? Timestamp.fromDateTime(task.dueDate!) : null, - public: task.isPublicVisible, - status: GRPCTypeConverter.taskStatusToGRPC(task.status), + id: taskId, + name: name, + description: notes, + dueAt: dueDate != null ? Timestamp.fromDateTime(dueDate) : null, + public: isPublic, + status: status != null ? GRPCTypeConverter.taskStatusToGRPC(status) : null, ); UpdateTaskResponse response = await taskService.updateTask( @@ -201,4 +212,14 @@ class TaskService { return response.isInitialized(); } + + Future removeDueDate({ + required String taskId, + }) async { + RemoveTaskDueDateRequest request = RemoveTaskDueDateRequest(taskId: taskId); + await taskService.removeTaskDueDate( + request, + options: CallOptions(metadata: TasksAPIServiceClients().getMetaData()), + ); + } } diff --git a/packages/helpwave_util/lib/src/loading/loading_change_notifier.dart b/packages/helpwave_util/lib/src/loading/loading_change_notifier.dart index 53dfa8c3..a3fa3782 100644 --- a/packages/helpwave_util/lib/src/loading/loading_change_notifier.dart +++ b/packages/helpwave_util/lib/src/loading/loading_change_notifier.dart @@ -20,17 +20,21 @@ class LoadingChangeNotifier extends ChangeNotifier { LoadingChangeNotifier(); - Future loadHandler({ + Future loadHandler({ required Future future, Future Function(Object? error, StackTrace stackTrace)? errorHandler, }) async { + bool success = false; defaultErrorHandler(errorObj, _) async { error = errorObj.toString(); return false; } changeState(LoadingState.loading); - await future.then((_) => changeState(LoadingState.loaded)).onError((error, stackTrace) async { + await future.then((_) { + changeState(LoadingState.loaded); + success = true; + }).onError((error, stackTrace) async { if (errorHandler != null) { try { bool isHandled = await errorHandler(error, stackTrace); @@ -44,5 +48,6 @@ class LoadingChangeNotifier extends ChangeNotifier { changeState(LoadingState.error); }); + return success; } } diff --git a/packages/helpwave_widget/lib/content_selection.dart b/packages/helpwave_widget/lib/content_selection.dart index dab610d1..ad24aa53 100644 --- a/packages/helpwave_widget/lib/content_selection.dart +++ b/packages/helpwave_widget/lib/content_selection.dart @@ -1,3 +1 @@ -export 'package:helpwave_widget/src/content_selection/list_search.dart' show ListSearch; -export 'package:helpwave_widget/src/content_selection/content_selector.dart' show ContentSelector; -export 'package:helpwave_widget/src/content_selection/chip_select.dart'; +export 'package:helpwave_widget/src/content_selection/index.dart'; diff --git a/packages/helpwave_widget/lib/src/content_selection/index.dart b/packages/helpwave_widget/lib/src/content_selection/index.dart new file mode 100644 index 00000000..6c033924 --- /dev/null +++ b/packages/helpwave_widget/lib/src/content_selection/index.dart @@ -0,0 +1,4 @@ +export 'chip_select.dart'; +export 'content_selector.dart' show ContentSelector; +export 'list_search.dart'; +export 'list_select.dart'; diff --git a/packages/helpwave_widget/lib/src/content_selection/list_select.dart b/packages/helpwave_widget/lib/src/content_selection/list_select.dart new file mode 100644 index 00000000..1f7e9383 --- /dev/null +++ b/packages/helpwave_widget/lib/src/content_selection/list_select.dart @@ -0,0 +1,28 @@ +import 'dart:async'; +import 'package:flutter/cupertino.dart'; +import 'package:helpwave_widget/loading.dart'; + +class ListSelect extends StatelessWidget { + final FutureOr> items; + + final void Function(T item) onSelect; + + final Widget Function(BuildContext context, T item, Function() select) builder; + + const ListSelect({ + super.key, + required this.items, + required this.onSelect, + required this.builder, + }); + + @override + Widget build(BuildContext context) { + return LoadingFutureBuilder( + data: items, + thenWidgetBuilder: (context, data) => Column( + children: data.map((item) => builder(context, item, () => onSelect(item))).toList(), + ), + ); + } +} diff --git a/packages/helpwave_widget/lib/src/loading/loading_future_builder.dart b/packages/helpwave_widget/lib/src/loading/loading_future_builder.dart index 08b1625b..fb7439c0 100644 --- a/packages/helpwave_widget/lib/src/loading/loading_future_builder.dart +++ b/packages/helpwave_widget/lib/src/loading/loading_future_builder.dart @@ -1,3 +1,4 @@ +import 'dart:async'; import 'package:flutter/cupertino.dart'; import 'package:helpwave_util/loading.dart'; import 'package:helpwave_widget/loading.dart'; @@ -5,21 +6,21 @@ import 'package:helpwave_widget/loading.dart'; /// A Wrapper for the standard [FutureBuilder] to easily distinguish the three /// cases error, loading, then class LoadingFutureBuilder extends StatelessWidget { - /// The [Future] to load - final Future future; + /// The [FutureOr] to load + final FutureOr data; - /// The Builder for the [Widget] upon an successful [Future] + /// The Builder for the [Widget] upon an successful [FutureOr] final Widget Function(BuildContext context, T data) thenWidgetBuilder; - /// The Builder for the [Widget] when loading the [Future] + /// The Builder for the [Widget] when loading the [FutureOr] final Widget loadingWidget; - /// The [Widget] for an error containing [Future] + /// The [Widget] for an error containing [FutureOr] final Widget errorWidget; const LoadingFutureBuilder({ super.key, - required this.future, + required this.data, required this.thenWidgetBuilder, this.loadingWidget = const LoadingSpinner(), this.errorWidget = const LoadErrorWidget(), @@ -27,24 +28,27 @@ class LoadingFutureBuilder extends StatelessWidget { @override Widget build(BuildContext context) { - return FutureBuilder( - future: future, - builder: (context, snapshot) { - LoadingState state = LoadingState.loaded; - if (snapshot.hasError) { - state = LoadingState.error; - } - if (!snapshot.hasData || snapshot.data == null) { - state = LoadingState.loading; - } - return LoadingAndErrorWidget( - state: state, - errorWidget: Center(child: errorWidget), - loadingWidget: Center(child: loadingWidget), - // Safety check because typecast may fail otherwise - child: snapshot.data != null ? thenWidgetBuilder(context, snapshot.data as T) : const SizedBox(), - ); - }, - ); + if(data is Future){ + return FutureBuilder( + future: data as Future, + builder: (context, snapshot) { + LoadingState state = LoadingState.loaded; + if (snapshot.hasError) { + state = LoadingState.error; + } + if (!snapshot.hasData || snapshot.data == null) { + state = LoadingState.loading; + } + return LoadingAndErrorWidget( + state: state, + errorWidget: Center(child: errorWidget), + loadingWidget: Center(child: loadingWidget), + // Safety check because typecast may fail otherwise + child: snapshot.data != null ? thenWidgetBuilder(context, snapshot.data as T) : const SizedBox(), + ); + }, + ); + } + return thenWidgetBuilder(context, data as T); } } From fe095c1b41ecb93b7890f13b5a1dce3258f254af Mon Sep 17 00:00:00 2001 From: Felix Thape Date: Wed, 18 Sep 2024 18:21:09 +0200 Subject: [PATCH 7/9] feat: update bottom sheets to handle nested navigation --- .../tasks/lib/components/assignee_select.dart | 30 +- .../lib/components/patient_bottom_sheet.dart | 270 +++++----- .../lib/components/task_bottom_sheet.dart | 461 +++++++++--------- .../lib/components/user_bottom_sheet.dart | 61 +-- apps/tasks/lib/components/user_header.dart | 152 ++---- .../lib/components/visibility_select.dart | 6 +- apps/tasks/lib/main.dart | 4 +- apps/tasks/lib/screens/main_screen.dart | 2 +- apps/tasks/lib/screens/settings_screen.dart | 134 ++++- .../src/api/user/services/user_service.dart | 20 + .../helpwave_theme/lib/src/constants.dart | 2 + .../lib/src/theme/dark_theme.dart | 6 + .../lib/src/theme/light_theme.dart | 8 +- .../helpwave_theme/lib/src/theme/theme.dart | 10 +- .../helpwave_widget/lib/bottom_sheets.dart | 2 +- .../src/bottom_sheets/bottom_sheet_base.dart | 253 ++++++---- .../lib/src/bottom_sheets/index.dart | 2 + .../nested_bottom_sheet_navigation.dart | 102 ++++ .../lib/src/widgets/fallback_avatar.dart | 40 ++ .../lib/src/widgets/index.dart | 2 + .../{widgets.dart => list_tile_card.dart} | 0 packages/helpwave_widget/lib/widgets.dart | 2 +- packages/helpwave_widget/pubspec.yaml | 1 + 23 files changed, 946 insertions(+), 624 deletions(-) create mode 100644 packages/helpwave_widget/lib/src/bottom_sheets/index.dart create mode 100644 packages/helpwave_widget/lib/src/bottom_sheets/nested_bottom_sheet_navigation.dart create mode 100644 packages/helpwave_widget/lib/src/widgets/fallback_avatar.dart create mode 100644 packages/helpwave_widget/lib/src/widgets/index.dart rename packages/helpwave_widget/lib/src/widgets/{widgets.dart => list_tile_card.dart} (100%) diff --git a/apps/tasks/lib/components/assignee_select.dart b/apps/tasks/lib/components/assignee_select.dart index 02e4794f..3e314f90 100644 --- a/apps/tasks/lib/components/assignee_select.dart +++ b/apps/tasks/lib/components/assignee_select.dart @@ -2,7 +2,6 @@ import 'dart:async'; import 'package:flutter/material.dart'; import 'package:helpwave_localization/localization.dart'; import 'package:helpwave_service/user.dart'; -import 'package:helpwave_theme/constants.dart'; import 'package:helpwave_widget/bottom_sheets.dart'; import 'package:helpwave_widget/content_selection.dart'; @@ -22,31 +21,32 @@ class AssigneeSelectBottomSheet extends StatelessWidget { @override Widget build(BuildContext context) { return BottomSheetBase( - titleText: context.localization!.assignee, + header: BottomSheetHeader( + titleText: context.localization!.assignee, + ), onClosing: () => {}, - builder: (context) => Padding( - padding: const EdgeInsets.symmetric(vertical: paddingMedium), - child: Column( + builder: (context) => Column( children: [ TextButton( child: Text(context.localization!.remove), onPressed: () => onChanged(null), ), const SizedBox(height: 10), - ListSelect( - items: users, - onSelect: onChanged, - builder: (context, user, select) => ListTile( - onTap: select, - leading: CircleAvatar( - foregroundColor: Colors.blue, backgroundImage: NetworkImage(user.profileUrl.toString())), - title: Text(user.nickName, - style: TextStyle(decoration: user.id == selectedId ? TextDecoration.underline : null)), + SingleChildScrollView( + child: ListSelect( + items: users, + onSelect: onChanged, + builder: (context, user, select) => ListTile( + onTap: select, + leading: CircleAvatar( + foregroundColor: Colors.blue, backgroundImage: NetworkImage(user.profileUrl.toString())), + title: Text(user.nickName, + style: TextStyle(decoration: user.id == selectedId ? TextDecoration.underline : null)), + ), ), ), ], ), - ), ); } } diff --git a/apps/tasks/lib/components/patient_bottom_sheet.dart b/apps/tasks/lib/components/patient_bottom_sheet.dart index 431773a4..446882d2 100644 --- a/apps/tasks/lib/components/patient_bottom_sheet.dart +++ b/apps/tasks/lib/components/patient_bottom_sheet.dart @@ -52,29 +52,31 @@ class _PatientBottomSheetState extends State { ), ], child: BottomSheetBase( - title: Consumer(builder: (context, patientController, _) { - if (patientController.state == LoadingState.loaded || patientController.isCreating) { - return ClickableTextEdit( - initialValue: patientController.patient.name, - onUpdated: patientController.changeName, - textAlign: TextAlign.center, - textStyle: TextStyle( - color: Theme.of(context).colorScheme.secondary, - fontWeight: FontWeight.bold, - fontSize: iconSizeTiny, - fontFamily: "SpaceGrotesk", - overflow: TextOverflow.ellipsis, - ), - ); - } else { - return const PulsingContainer(width: 30); - } - }), + header: BottomSheetHeader( + title: Consumer(builder: (context, patientController, _) { + if (patientController.state == LoadingState.loaded || patientController.isCreating) { + return ClickableTextEdit( + initialValue: patientController.patient.name, + onUpdated: patientController.changeName, + textAlign: TextAlign.center, + textStyle: TextStyle( + color: Theme.of(context).colorScheme.secondary, + fontWeight: FontWeight.bold, + fontSize: iconSizeTiny, + fontFamily: "SpaceGrotesk", + overflow: TextOverflow.ellipsis, + ), + ); + } else { + return const PulsingContainer(width: 30); + } + }), + ), onClosing: () { // TODO handle this }, bottomWidget: Padding( - padding: const EdgeInsets.only(top: paddingMedium), + padding: const EdgeInsets.only(top: paddingSmall), child: Consumer(builder: (context, patientController, _) { return LoadingAndErrorWidget( state: patientController.state, @@ -145,129 +147,131 @@ class _PatientBottomSheetState extends State { )); }), ), - builder: (BuildContext context) => Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Center( - child: Consumer(builder: (context, patientController, _) { - return LoadingFutureBuilder( - data: loadRoomsWithBeds(patientController.patient.id), - // TODO use a better loading widget - loadingWidget: const SizedBox(), - thenWidgetBuilder: (context, beds) { - if (beds.isEmpty) { - return Text( - context.localization!.noFreeBeds, - style: TextStyle(color: Theme.of(context).disabledColor, fontWeight: FontWeight.bold), - ); - } - return DropdownButtonHideUnderline( - child: DropdownButton( - iconEnabledColor: Theme.of(context).colorScheme.secondary.withOpacity(0.6), - padding: EdgeInsets.zero, - isDense: true, - hint: Text( - context.localization!.assignBed, - style: TextStyle(color: Theme.of(context).colorScheme.secondary.withOpacity(0.6)), + builder: (BuildContext context) => SingleChildScrollView( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Center( + child: Consumer(builder: (context, patientController, _) { + return LoadingFutureBuilder( + data: loadRoomsWithBeds(patientController.patient.id), + // TODO use a better loading widget + loadingWidget: const SizedBox(), + thenWidgetBuilder: (context, beds) { + if (beds.isEmpty) { + return Text( + context.localization!.noFreeBeds, + style: TextStyle(color: Theme.of(context).disabledColor, fontWeight: FontWeight.bold), + ); + } + return DropdownButtonHideUnderline( + child: DropdownButton( + iconEnabledColor: Theme.of(context).colorScheme.secondary.withOpacity(0.6), + padding: EdgeInsets.zero, + isDense: true, + hint: Text( + context.localization!.assignBed, + style: TextStyle(color: Theme.of(context).colorScheme.secondary.withOpacity(0.6)), + ), + value: beds.where((beds) => beds.bed.id == patientController.patient.bed?.id).firstOrNull, + items: beds + .map((roomWithBed) => DropdownMenuItem( + value: roomWithBed, + child: Text( + "${roomWithBed.room.name} - ${roomWithBed.bed.name}", + style: TextStyle(color: Theme.of(context).colorScheme.primary.withOpacity(0.6)), + ), + )) + .toList(), + onChanged: (RoomWithBedFlat? value) { + // TODO later unassign here + if (value == null) { + return; + } + patientController.assignToBed(value.room, value.bed); + }, ), - value: beds.where((beds) => beds.bed.id == patientController.patient.bed?.id).firstOrNull, - items: beds - .map((roomWithBed) => DropdownMenuItem( - value: roomWithBed, - child: Text( - "${roomWithBed.room.name} - ${roomWithBed.bed.name}", - style: TextStyle(color: Theme.of(context).colorScheme.primary.withOpacity(0.6)), - ), - )) - .toList(), - onChanged: (RoomWithBedFlat? value) { - // TODO later unassign here - if (value == null) { - return; - } - patientController.assignToBed(value.room, value.bed); - }, - ), - ); - }, - ); - }), - ), - Text( - context.localization!.notes, - style: const TextStyle(fontSize: fontSizeBig, fontWeight: FontWeight.bold), - ), - const SizedBox(height: distanceSmall), - Consumer( - builder: (context, patientController, _) => - patientController.state == LoadingState.loaded || patientController.isCreating - ? TextFormFieldWithTimer( - initialValue: patientController.patient.notes, - maxLines: 6, - onUpdate: patientController.changeNotes, - ) - : TextFormField(maxLines: 6), - ), - Padding( - padding: const EdgeInsets.symmetric(vertical: paddingMedium), - child: Consumer(builder: (context, patientController, _) { - Patient patient = patientController.patient; - return AddList( - maxHeight: width * 0.5, - items: [ - ...patient.unscheduledTasks, - ...patient.inProgressTasks, - ...patient.doneTasks, - ], - itemBuilder: (_, index, taskList) { - if (index == 0) { - return TaskExpansionTile( - tasks: patient.unscheduledTasks - .map((task) => TaskWithPatient.fromTaskAndPatient( - task: task, - patient: patient, - )) - .toList(), - title: context.localization!.upcoming, - color: upcomingColor, ); - } - if (index == 2) { + }, + ); + }), + ), + Text( + context.localization!.notes, + style: const TextStyle(fontSize: fontSizeBig, fontWeight: FontWeight.bold), + ), + const SizedBox(height: distanceSmall), + Consumer( + builder: (context, patientController, _) => + patientController.state == LoadingState.loaded || patientController.isCreating + ? TextFormFieldWithTimer( + initialValue: patientController.patient.notes, + maxLines: 6, + onUpdate: patientController.changeNotes, + ) + : TextFormField(maxLines: 6), + ), + Padding( + padding: const EdgeInsets.symmetric(vertical: paddingMedium), + child: Consumer(builder: (context, patientController, _) { + Patient patient = patientController.patient; + return AddList( + maxHeight: width * 0.5, + items: [ + ...patient.unscheduledTasks, + ...patient.inProgressTasks, + ...patient.doneTasks, + ], + itemBuilder: (_, index, taskList) { + if (index == 0) { + return TaskExpansionTile( + tasks: patient.unscheduledTasks + .map((task) => TaskWithPatient.fromTaskAndPatient( + task: task, + patient: patient, + )) + .toList(), + title: context.localization!.upcoming, + color: upcomingColor, + ); + } + if (index == 2) { + return TaskExpansionTile( + tasks: patient.doneTasks + .map((task) => TaskWithPatient.fromTaskAndPatient( + task: task, + patient: patient, + )) + .toList(), + title: context.localization!.inProgress, + color: inProgressColor, + ); + } return TaskExpansionTile( - tasks: patient.doneTasks + tasks: patient.inProgressTasks .map((task) => TaskWithPatient.fromTaskAndPatient( task: task, patient: patient, )) .toList(), - title: context.localization!.inProgress, - color: inProgressColor, + title: context.localization!.done, + color: doneColor, ); - } - return TaskExpansionTile( - tasks: patient.inProgressTasks - .map((task) => TaskWithPatient.fromTaskAndPatient( - task: task, - patient: patient, - )) - .toList(), - title: context.localization!.done, - color: doneColor, - ); - }, - title: Text( - context.localization!.tasks, - style: const TextStyle(fontSize: fontSizeBig, fontWeight: FontWeight.bold), - ), - // TODO use return value to add it to task list or force a refetch - onAdd: () => context.pushModal( - context: context, - builder: (context) => TaskBottomSheet(task: Task.empty(patient.id), patient: patient), - ), - ); - }), - ), - ], + }, + title: Text( + context.localization!.tasks, + style: const TextStyle(fontSize: fontSizeBig, fontWeight: FontWeight.bold), + ), + // TODO use return value to add it to task list or force a refetch + onAdd: () => context.pushModal( + context: context, + builder: (context) => TaskBottomSheet(task: Task.empty(patient.id), patient: patient), + ), + ); + }), + ), + ], + ), ), ), ); diff --git a/apps/tasks/lib/components/task_bottom_sheet.dart b/apps/tasks/lib/components/task_bottom_sheet.dart index 7f2590d4..271facb8 100644 --- a/apps/tasks/lib/components/task_bottom_sheet.dart +++ b/apps/tasks/lib/components/task_bottom_sheet.dart @@ -116,11 +116,11 @@ class _TaskBottomSheetState extends State { return ChangeNotifierProvider( create: (context) => TaskController(TaskWithPatient.fromTaskAndPatient(task: widget.task, patient: widget.patient)), - child: SingleChildScrollView( - child: BottomSheetBase( - onClosing: () async { - // TODO do saving or something when the dialog is closed - }, + child: BottomSheetBase( + onClosing: () async { + // TODO do saving or something when the dialog is closed + }, + header: BottomSheetHeader( title: Consumer( builder: (context, taskController, child) => ClickableTextEdit( initialValue: taskController.task.name, @@ -135,252 +135,247 @@ class _TaskBottomSheetState extends State { ), ), ), - bottomWidget: Flexible( - child: Consumer( - builder: (context, taskController, child) => taskController.isCreating - ? Padding( - padding: const EdgeInsets.only(top: paddingSmall), - child: Align( - alignment: Alignment.topRight, - child: TextButton( - style: buttonStyleBig, - onPressed: taskController.isReadyForCreate - ? () { - taskController.create().then((value) { - if (value) { - Navigator.pop(context); - } - }); + ), + bottomWidget: Consumer( + builder: (context, taskController, child) => taskController.isCreating + ? Padding( + padding: const EdgeInsets.only(top: paddingSmall), + child: Align( + alignment: Alignment.topRight, + child: TextButton( + style: buttonStyleBig, + onPressed: taskController.isReadyForCreate + ? () { + taskController.create().then((value) { + if (value) { + Navigator.pop(context); } - : null, - child: Text(context.localization!.create), - ), - ), - ) - : const SizedBox(), - ), - ), - builder: (context) => Container( - constraints: BoxConstraints(maxHeight: MediaQuery.of(context).size.height * 0.8), - child: Column( - mainAxisSize: MainAxisSize.min, - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Center( - child: Consumer(builder: - // TODO move this to its own component - (context, taskController, __) { - return LoadingAndErrorWidget.pulsing( - state: taskController.state, - child: !taskController.isCreating - ? Text(taskController.patient.name) - : LoadingFutureBuilder( - data: PatientService().getPatientList(), - loadingWidget: const PulsingContainer(), - thenWidgetBuilder: (context, patientList) { - List patients = patientList.active + patientList.unassigned; - return DropdownButton( - underline: const SizedBox(), - iconEnabledColor: Theme.of(context).colorScheme.secondary.withOpacity(0.6), - // removes the default underline - padding: EdgeInsets.zero, - hint: Text( - context.localization!.selectPatient, - style: TextStyle(color: Theme.of(context).colorScheme.secondary.withOpacity(0.6)), - ), - isDense: true, - items: patients - .map((patient) => DropdownMenuItem(value: patient, child: Text(patient.name))) - .toList(), - value: taskController.patient.isCreating ? null : taskController.patient, - onChanged: (patient) => - taskController.changePatient(patient ?? PatientMinimal.empty()), - ); - }), - ); - }), + }); + } + : null, + child: Text(context.localization!.create), + ), ), - const SizedBox(height: distanceMedium), - Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: [ - Consumer(builder: (context, taskController, __) { - return _SheetListTile( - icon: Icons.person, - label: context.localization!.assignedTo, - onTap: () => context.pushModal( - context: context, - builder: (BuildContext context) => AssigneeSelectBottomSheet( - users: OrganizationService() - .getMembersByOrganization(CurrentWardService().currentWard!.organizationId), - onChanged: (User? assignee) { - taskController.changeAssignee(assignee); - Navigator.pop(context); - }, - selectedId: taskController.task.assigneeId, - ), - ), - valueWidget: taskController.task.hasAssignee - ? LoadingAndErrorWidget.pulsing( - state: taskController.assignee != null ? LoadingState.loaded : LoadingState.loading, - child: Text( - // Never the case that we display the empty String, but the text is computed - // before being displayed - taskController.assignee?.name ?? "", - style: editableValueTextStyle(context), - ), - ) - : Text( - context.localization!.unassigned, - style: editableValueTextStyle(context), + ) + : const SizedBox(), + ), + builder: (context) => Flexible( + child: ListView( + children: [ + Center( + child: Consumer(builder: + // TODO move this to its own component + (context, taskController, __) { + return LoadingAndErrorWidget.pulsing( + state: taskController.state, + child: !taskController.isCreating + ? Text(taskController.patient.name) + : LoadingFutureBuilder( + data: PatientService().getPatientList(), + loadingWidget: const PulsingContainer(), + thenWidgetBuilder: (context, patientList) { + List patients = patientList.active + patientList.unassigned; + return DropdownButton( + underline: const SizedBox(), + iconEnabledColor: Theme.of(context).colorScheme.secondary.withOpacity(0.6), + // removes the default underline + padding: EdgeInsets.zero, + hint: Text( + context.localization!.selectPatient, + style: TextStyle(color: Theme.of(context).colorScheme.secondary.withOpacity(0.6)), ), - ); - }), - Consumer( - builder: (context, taskController, __) => LoadingAndErrorWidget.pulsing( - state: taskController.state, - child: _SheetListTile( - icon: Icons.access_time, - label: context.localization!.due, - // TODO localization and date formatting here - valueWidget: Builder(builder: (context) { - DateTime? dueDate = taskController.task.dueDate; - if (dueDate != null) { - String date = - "${dueDate.day.toString().padLeft(2, "0")}.${dueDate.month.toString().padLeft(2, "0")}.${dueDate.year.toString().padLeft(4, "0")}"; - String time = - "${dueDate.hour.toString().padLeft(2, "0")}:${dueDate.minute.toString().padLeft(2, "0")}"; - return Column( - mainAxisSize: MainAxisSize.min, - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text(time, style: editableValueTextStyle(context)), - Text(date), - ], - ); - } - return Text(context.localization!.none); + isDense: true, + items: patients + .map((patient) => DropdownMenuItem(value: patient, child: Text(patient.name))) + .toList(), + value: taskController.patient.isCreating ? null : taskController.patient, + onChanged: (patient) => taskController.changePatient(patient ?? PatientMinimal.empty()), + ); }), - onTap: () => showDatePicker( - context: context, - initialDate: taskController.task.dueDate ?? DateTime.now(), - firstDate: DateTime(1960), - lastDate: DateTime.now().add(const Duration(days: 365 * 5)), - builder: (context, child) { - // Overwrite the Theme - ThemeData pickerTheme = - Theme.of(context).copyWith(textButtonTheme: const TextButtonThemeData()); - return Theme(data: pickerTheme, child: child ?? const SizedBox()); - }, - ).then((date) async { - await showTimePicker( - context: context, - initialTime: TimeOfDay.fromDateTime(taskController.task.dueDate ?? DateTime.now()), - builder: (context, child) { - ThemeData originalTheme = Theme.of(context); - - // Temporarily set a default theme for the picker - ThemeData pickerTheme = ThemeData.fallback().copyWith( - colorScheme: originalTheme.colorScheme, - ); - return Theme(data: pickerTheme, child: child ?? const SizedBox()); - }, - ).then((time) { - if (date == null && time == null) { - return; - } - date ??= taskController.task.dueDate; - if (date == null) { - return; - } - if (time != null) { - date = DateTime( - date!.year, - date!.month, - date!.day, - time.hour, - time.minute, - ); - } - taskController.changeDueDate(date); - }); - }), - ), + ); + }), + ), + const SizedBox(height: distanceMedium), + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Consumer(builder: (context, taskController, __) { + return _SheetListTile( + icon: Icons.person, + label: context.localization!.assignedTo, + onTap: () => context.pushModal( + context: context, + builder: (BuildContext context) => AssigneeSelectBottomSheet( + users: OrganizationService() + .getMembersByOrganization(CurrentWardService().currentWard!.organizationId), + onChanged: (User? assignee) { + taskController.changeAssignee(assignee); + Navigator.pop(context); + }, + selectedId: taskController.task.assigneeId, ), ), - ], - ), - const SizedBox(height: distanceSmall), + valueWidget: taskController.task.hasAssignee + ? LoadingAndErrorWidget.pulsing( + state: taskController.assignee != null ? LoadingState.loaded : LoadingState.loading, + child: Text( + // Never the case that we display the empty String, but the text is computed + // before being displayed + taskController.assignee?.name ?? "", + style: editableValueTextStyle(context), + ), + ) + : Text( + context.localization!.unassigned, + style: editableValueTextStyle(context), + ), + ); + }), Consumer( - builder: (_, taskController, __) => LoadingAndErrorWidget.pulsing( + builder: (context, taskController, __) => LoadingAndErrorWidget.pulsing( state: taskController.state, child: _SheetListTile( - icon: Icons.lock, - label: context.localization!.visibility, - valueWidget: VisibilitySelect( - isPublicVisible: taskController.task.isPublicVisible, - onChanged: taskController.changeIsPublic, - isCreating: taskController.isCreating, - textStyle: editableValueTextStyle(context), - ), + icon: Icons.access_time, + label: context.localization!.due, + // TODO localization and date formatting here + valueWidget: Builder(builder: (context) { + DateTime? dueDate = taskController.task.dueDate; + if (dueDate != null) { + String date = + "${dueDate.day.toString().padLeft(2, "0")}.${dueDate.month.toString().padLeft(2, "0")}.${dueDate.year.toString().padLeft(4, "0")}"; + String time = + "${dueDate.hour.toString().padLeft(2, "0")}:${dueDate.minute.toString().padLeft(2, "0")}"; + return Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(time, style: editableValueTextStyle(context)), + Text(date), + ], + ); + } + return Text(context.localization!.none); + }), + onTap: () => showDatePicker( + context: context, + initialDate: taskController.task.dueDate ?? DateTime.now(), + firstDate: DateTime(1960), + lastDate: DateTime.now().add(const Duration(days: 365 * 5)), + builder: (context, child) { + // Overwrite the Theme + ThemeData pickerTheme = + Theme.of(context).copyWith(textButtonTheme: const TextButtonThemeData()); + return Theme(data: pickerTheme, child: child ?? const SizedBox()); + }, + ).then((date) async { + await showTimePicker( + context: context, + initialTime: TimeOfDay.fromDateTime(taskController.task.dueDate ?? DateTime.now()), + builder: (context, child) { + ThemeData originalTheme = Theme.of(context); + + // Temporarily set a default theme for the picker + ThemeData pickerTheme = ThemeData.fallback().copyWith( + colorScheme: originalTheme.colorScheme, + ); + return Theme(data: pickerTheme, child: child ?? const SizedBox()); + }, + ).then((time) { + if (date == null && time == null) { + return; + } + date ??= taskController.task.dueDate; + if (date == null) { + return; + } + if (time != null) { + date = DateTime( + date!.year, + date!.month, + date!.day, + time.hour, + time.minute, + ); + } + taskController.changeDueDate(date); + }); + }), ), ), ), - const SizedBox(height: distanceMedium), - Text( - context.localization!.notes, - style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 16), + ], + ), + const SizedBox(height: distanceSmall), + Consumer( + builder: (_, taskController, __) => LoadingAndErrorWidget.pulsing( + state: taskController.state, + child: _SheetListTile( + icon: Icons.lock, + label: context.localization!.visibility, + valueWidget: VisibilitySelect( + isPublicVisible: taskController.task.isPublicVisible, + onChanged: taskController.changeIsPublic, + isCreating: taskController.isCreating, + textStyle: editableValueTextStyle(context), + ), ), - const SizedBox(height: distanceTiny), - Consumer( - builder: (_, taskController, __) => LoadingAndErrorWidget( - state: taskController.state, - loadingWidget: PulsingContainer( - width: MediaQuery.of(context).size.width, - height: 25 * 6, // 25px per line - ), - errorWidget: PulsingContainer( - width: MediaQuery.of(context).size.width, - height: 25 * 6, - // 25px per line - maxOpacity: 1, - minOpacity: 1, - color: negativeColor, - ), - child: TextFormFieldWithTimer( - initialValue: taskController.task.notes, - onUpdate: taskController.changeNotes, - maxLines: 6, - decoration: InputDecoration( - contentPadding: const EdgeInsets.all(paddingMedium), - border: const OutlineInputBorder( - borderSide: BorderSide( - width: 1.0, - ), - ), - hintText: context.localization!.yourNotes, + ), + ), + const SizedBox(height: distanceMedium), + Text( + context.localization!.notes, + style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 16), + ), + const SizedBox(height: distanceTiny), + Consumer( + builder: (_, taskController, __) => LoadingAndErrorWidget( + state: taskController.state, + loadingWidget: PulsingContainer( + width: MediaQuery.of(context).size.width, + height: 25 * 6, // 25px per line + ), + errorWidget: PulsingContainer( + width: MediaQuery.of(context).size.width, + height: 25 * 6, + // 25px per line + maxOpacity: 1, + minOpacity: 1, + color: negativeColor, + ), + child: TextFormFieldWithTimer( + initialValue: taskController.task.notes, + onUpdate: taskController.changeNotes, + maxLines: 6, + decoration: InputDecoration( + contentPadding: const EdgeInsets.all(paddingMedium), + border: const OutlineInputBorder( + borderSide: BorderSide( + width: 1.0, ), ), + hintText: context.localization!.yourNotes, ), ), - const SizedBox(height: distanceBig), - // TODO add callback here for task creation to update the Task accordingly - Consumer( - builder: (_, taskController, __) => LoadingAndErrorWidget.pulsing( - state: taskController.state, - child: SubtaskList( - taskId: taskController.task.id, - subtasks: taskController.task.subtasks, - onChange: (subtasks) { - if (taskController.task.isCreating) { - taskController.task.subtasks = subtasks; - } - }, - ), - ), + ), + ), + const SizedBox(height: distanceBig), + // TODO add callback here for task creation to update the Task accordingly + Consumer( + builder: (_, taskController, __) => LoadingAndErrorWidget.pulsing( + state: taskController.state, + child: SubtaskList( + taskId: taskController.task.id, + subtasks: taskController.task.subtasks, + onChange: (subtasks) { + if (taskController.task.isCreating) { + taskController.task.subtasks = subtasks; + } + }, ), - ], - )), + ), + ), + ], + ), ), ), ); diff --git a/apps/tasks/lib/components/user_bottom_sheet.dart b/apps/tasks/lib/components/user_bottom_sheet.dart index 4b18600a..4823ac6f 100644 --- a/apps/tasks/lib/components/user_bottom_sheet.dart +++ b/apps/tasks/lib/components/user_bottom_sheet.dart @@ -1,6 +1,7 @@ import 'dart:math'; import 'package:flutter/material.dart'; import 'package:helpwave_localization/localization.dart'; +import 'package:helpwave_service/user.dart'; import 'package:helpwave_theme/constants.dart'; import 'package:helpwave_widget/bottom_sheets.dart'; import 'package:helpwave_widget/loading.dart'; @@ -8,50 +9,42 @@ import 'package:provider/provider.dart'; import 'package:helpwave_service/tasks.dart'; import 'package:helpwave_service/auth.dart'; import 'package:tasks/screens/login_screen.dart'; +import 'package:helpwave_widget/widgets.dart'; +import 'package:tasks/screens/settings_screen.dart'; -/// A [BottomSheet] for showing the [User]s information -class UserBottomSheet extends StatefulWidget { - const UserBottomSheet({super.key}); +class UserBottomSheetPageBuilder with BottomSheetPageBuilder { @override - State createState() => _UserBottomSheetState(); -} + BottomSheetHeader? headerBuilder(BuildContext context, NestedBottomSheetNavigationController controller) { + return BottomSheetHeader( + trailing: BottomSheetAction( + icon: Icons.settings, + onPressed: () => controller.push(SettingsBottomSheetPageBuilder()), + ), + ); + } -class _UserBottomSheetState extends State { @override - Widget build(BuildContext context) { + Widget build(BuildContext context, NestedBottomSheetNavigationController controller) { final double width = MediaQuery.of(context).size.width; - return BottomSheetBase( - onClosing: () {}, - titleText: context.localization!.profile, - builder: (BuildContext ctx) => Column( + return Flexible( + child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Padding( padding: const EdgeInsets.all(paddingSmall).copyWith(top: paddingMedium), - child: CircleAvatar( - radius: iconSizeMedium, - child: Container( - decoration: const BoxDecoration( - shape: BoxShape.circle, - gradient: LinearGradient( - begin: Alignment.topLeft, - end: Alignment(0.8, 1), - colors: [ - Color(0xff1f005c), - Color(0xff5b0060), - Color(0xff870160), - Color(0xffac255e), - Color(0xffca485c), - Color(0xffe16b5c), - Color(0xfff39060), - Color(0xffffb56b), - ], - tileMode: TileMode.mirror, - ), - ), - ), + child: LoadingFutureBuilder( + data: UserService().getSelf(), + thenWidgetBuilder: (context, data) { + return CircleAvatar( + backgroundColor: Colors.transparent, + radius: iconSizeMedium, + foregroundImage: NetworkImage(data.profileUrl.toString()), + ); + }, + loadingWidget: const FallbackAvatar(size: iconSizeMedium), + errorWidget: const FallbackAvatar(size: iconSizeMedium), ), ), Consumer(builder: (context, userSessionController, _) { @@ -60,7 +53,6 @@ class _UserBottomSheetState extends State { style: const TextStyle(fontSize: fontSizeBig), ); }), - // TODO consider a loading widget here Consumer( builder: (context, currentWardController, __) => Text( currentWardController.currentWard?.organizationName ?? context.localization!.loading, @@ -147,6 +139,7 @@ class _UserBottomSheetState extends State { }); }), ), + const Spacer(), Padding( padding: const EdgeInsets.only(bottom: distanceMedium), child: Consumer(builder: (context, currentWardService, _) { diff --git a/apps/tasks/lib/components/user_header.dart b/apps/tasks/lib/components/user_header.dart index b66cac3a..5ea59d78 100644 --- a/apps/tasks/lib/components/user_header.dart +++ b/apps/tasks/lib/components/user_header.dart @@ -1,126 +1,78 @@ import 'package:flutter/material.dart'; import 'package:helpwave_service/auth.dart'; import 'package:helpwave_service/tasks.dart'; +import 'package:helpwave_service/user.dart'; import 'package:helpwave_theme/constants.dart'; +import 'package:helpwave_theme/util.dart'; import 'package:helpwave_widget/bottom_sheets.dart'; +import 'package:helpwave_widget/loading.dart'; +import 'package:helpwave_widget/widgets.dart'; import 'package:provider/provider.dart'; import 'package:tasks/components/user_bottom_sheet.dart'; -import 'package:tasks/screens/settings_screen.dart'; /// A [AppBar] for displaying the current [User], [Organization] and [Ward] class UserHeader extends StatelessWidget implements PreferredSizeWidget { - // TODO fetch users by with grpc const UserHeader({Key? key}) : super(key: key); @override Widget build(BuildContext context) { - return Padding( - padding: const EdgeInsets.all(paddingSmall), - child: AppBar( - centerTitle: false, - titleSpacing: paddingSmall, - leadingWidth: iconSizeSmall, - leading: GestureDetector( - onTap: () { - context.pushModal( - context: context, - builder: (context) => const UserBottomSheet(), - ); - }, - child: CircleAvatar( - backgroundColor: Colors.transparent, - radius: iconSizeSmall / 2, - child: Container( + return Container( + color: context.theme.appBarTheme.backgroundColor, + child: Consumer(builder: (context, userSession, __) { + return SafeArea( + child: ListTile( + leading: SizedBox( width: iconSizeSmall, height: iconSizeSmall, - decoration: const BoxDecoration( - shape: BoxShape.circle, - gradient: LinearGradient( - begin: Alignment.topLeft, - end: Alignment(0.8, 1), - colors: [ - Color(0xff1f005c), - Color(0xff5b0060), - Color(0xff870160), - Color(0xffac255e), - Color(0xffca485c), - Color(0xffe16b5c), - Color(0xfff39060), - Color(0xffffb56b), - ], - tileMode: TileMode.mirror, - ), - ), - ), - ), - ), - title: GestureDetector( - onTap: () { - context.pushModal( - context: context, - builder: (context) => const UserBottomSheet(), - ); - }, - child: Column( - mainAxisSize: MainAxisSize.min, - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - // TODO get information somewhere - Consumer( - builder: (context, userSession, __) { - return Text( - userSession.identity!.name, - style: const TextStyle(fontSize: 16), + child: LoadingFutureBuilder( + data: UserService().getSelf(), + thenWidgetBuilder: (context, data) { + return CircleAvatar( + backgroundColor: Colors.transparent, + radius: iconSizeSmall / 2, + foregroundImage: NetworkImage(data.profileUrl.toString()), ); - } + }, + loadingWidget: const FallbackAvatar(), + errorWidget: const FallbackAvatar(), ), - - // TODO maybe show something for loading - Consumer( - builder: (context, currentWardController, __) => Row( - children: [ - Text( - "${currentWardController.currentWard?.organization.shortName ?? ""} - ", - style: const TextStyle( - color: Colors.grey, - fontSize: 14, - ), + ), + onTap: () { + context.pushModal( + context: context, + builder: (context) => NestedBottomSheetNavigator(initialPageBuilder: UserBottomSheetPageBuilder()), + ); + }, + title: Text( + userSession.identity!.name, + style: const TextStyle(fontSize: 16), + ), + subtitle: Consumer( + builder: (context, currentWardController, __) => Row( + children: [ + Text( + "${currentWardController.currentWard?.organization.shortName ?? ""} - ", + style: TextStyle( + color: Theme.of(context).colorScheme.onBackground.withOpacity(0.7), + fontSize: 14, ), - Text( - currentWardController.currentWard?.wardName ?? "", - overflow: TextOverflow.fade, - style: const TextStyle( - fontWeight: FontWeight.bold, - fontSize: 14, - ), + ), + Text( + currentWardController.currentWard?.wardName ?? "", + overflow: TextOverflow.fade, + style: const TextStyle( + fontWeight: FontWeight.bold, + fontSize: 14, ), - ], - ), + ), + ], ), - ], + ), + trailing: const Icon(Icons.expand_more), ), - ), - actions: [ - IconButton( - padding: EdgeInsets.zero, - splashRadius: iconSizeSmall / 2, - constraints: const BoxConstraints(maxWidth: iconSizeSmall, maxHeight: iconSizeSmall), - iconSize: iconSizeSmall, - onPressed: () { - Navigator.push( - context, - MaterialPageRoute( - builder: (context) => const SettingsScreen(), - ), - ); - }, - icon: const Icon(Icons.settings), - ) - ], - ), + ); + }), ); - - } @override diff --git a/apps/tasks/lib/components/visibility_select.dart b/apps/tasks/lib/components/visibility_select.dart index 2c458b20..2ae8ca04 100644 --- a/apps/tasks/lib/components/visibility_select.dart +++ b/apps/tasks/lib/components/visibility_select.dart @@ -25,9 +25,11 @@ class _VisibilityBottomSheet extends StatelessWidget { top: paddingMedium, bottom: paddingBig, ), - titleText: context.localization!.visibility, + header: BottomSheetHeader( + titleText: context.localization!.visibility, + ), builder: (context) { - return Column( + return ListView( children: [ const SizedBox(height: distanceSmall), GestureDetector( diff --git a/apps/tasks/lib/main.dart b/apps/tasks/lib/main.dart index 65b37680..0350f9c2 100644 --- a/apps/tasks/lib/main.dart +++ b/apps/tasks/lib/main.dart @@ -57,9 +57,7 @@ class MyApp extends StatelessWidget { ], supportedLocales: getSupportedLocals(), locale: Locale(languageNotifier.language), - home: const Scaffold( - body: SafeArea(child: LoginScreen()), - ), + home: const LoginScreen(), ); }), ); diff --git a/apps/tasks/lib/screens/main_screen.dart b/apps/tasks/lib/screens/main_screen.dart index 60797a42..d39b2564 100644 --- a/apps/tasks/lib/screens/main_screen.dart +++ b/apps/tasks/lib/screens/main_screen.dart @@ -45,7 +45,7 @@ class _MainScreenState extends State { } return Scaffold( appBar: const UserHeader(), - body: [const MyTasksScreen(), const SizedBox(), const PatientScreen()][index], + body: SafeArea(child: [const MyTasksScreen(), const SizedBox(), const PatientScreen()][index]), floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat, floatingActionButton: PopInAndOutAnimator( visible: isShowingActionButton, diff --git a/apps/tasks/lib/screens/settings_screen.dart b/apps/tasks/lib/screens/settings_screen.dart index e943d53b..9f31e582 100644 --- a/apps/tasks/lib/screens/settings_screen.dart +++ b/apps/tasks/lib/screens/settings_screen.dart @@ -4,18 +4,14 @@ import 'package:helpwave_localization/localization_model.dart'; import 'package:helpwave_service/auth.dart'; import 'package:helpwave_theme/constants.dart'; import 'package:helpwave_theme/theme.dart'; +import 'package:helpwave_widget/bottom_sheets.dart'; import 'package:provider/provider.dart'; import 'package:tasks/screens/login_screen.dart'; /// Screen for settings and other app options -class SettingsScreen extends StatefulWidget { +class SettingsScreen extends StatelessWidget { const SettingsScreen({super.key}); - @override - State createState() => _SettingsScreenState(); -} - -class _SettingsScreenState extends State { @override Widget build(BuildContext context) { return Scaffold( @@ -147,3 +143,129 @@ class _SettingsScreenState extends State { ); } } + +class SettingsBottomSheetPageBuilder with BottomSheetPageBuilder { + @override + Widget build(BuildContext context, NestedBottomSheetNavigationController controller) { + return Flexible( + child: ListView( + children: ListTile.divideTiles( + context: context, + tiles: [ + ListTile( + leading: const Icon(Icons.brightness_medium), + title: Text(context.localization!.darkMode), + trailing: Consumer( + builder: (_, ThemeModel themeNotifier, __) { + return PopupMenuButton( + initialValue: themeNotifier.themeMode, + position: PopupMenuPosition.under, + itemBuilder: (context) => [ + PopupMenuItem(value: ThemeMode.dark, child: Text(context.localization!.darkMode)), + PopupMenuItem(value: ThemeMode.light, child: Text(context.localization!.lightMode)), + PopupMenuItem(value: ThemeMode.system, child: Text(context.localization!.system)), + ], + onSelected: (value) { + if (value == ThemeMode.system) { + themeNotifier.isDark = null; + } else { + themeNotifier.isDark = value == ThemeMode.dark; + } + }, + child: Material( + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Text( + { + ThemeMode.dark: context.localization!.darkMode, + ThemeMode.light: context.localization!.lightMode, + ThemeMode.system: context.localization!.system, + }[themeNotifier.themeMode]!, + style: const TextStyle( + fontSize: 14, + fontWeight: FontWeight.w800, + )), + const SizedBox( + width: distanceTiny, + ), + const Icon( + Icons.expand_more_rounded, + size: iconSizeTiny, + ), + ], + ), + ), + ); + }, + ), + ), + Consumer( + builder: (context, languageModel, child) { + return ListTile( + leading: const Icon(Icons.language), + title: Text(context.localization!.language), + trailing: PopupMenuButton( + position: PopupMenuPosition.under, + initialValue: languageModel.local, + onSelected: (value) { + languageModel.setLanguage(value); + }, + itemBuilder: (BuildContext context) => getSupportedLocalsWithName() + .map((local) => PopupMenuItem( + value: local.local, + child: Text( + local.name, + ), + )) + .toList(), + child: Material( + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Text(languageModel.name, + style: const TextStyle( + fontSize: 14, + fontWeight: FontWeight.w800, + )), + const SizedBox( + width: distanceTiny, + ), + const Icon( + Icons.expand_more_rounded, + size: iconSizeTiny, + ), + ], + ), + ), + ), + ); + }, + ), + ListTile( + leading: const Icon(Icons.info_outline), + title: Text(context.localization!.licenses), + trailing: const Icon(Icons.arrow_forward), + onTap: () => {showLicensePage(context: context)}, + ), + Consumer( + builder: (context, currentWardService, _) { + return ListTile( + leading: const Icon(Icons.logout), + title: Text(context.localization!.logout), + onTap: () { + UserSessionService().logout(); + currentWardService.clear(); + Navigator.of(context).pushReplacement( + MaterialPageRoute(builder: (_) => const LoginScreen()), + ); + }, + ); + }, + ), + ], + ).toList(), + ), + ); + } +} diff --git a/packages/helpwave_service/lib/src/api/user/services/user_service.dart b/packages/helpwave_service/lib/src/api/user/services/user_service.dart index 943bba4a..16680bdd 100644 --- a/packages/helpwave_service/lib/src/api/user/services/user_service.dart +++ b/packages/helpwave_service/lib/src/api/user/services/user_service.dart @@ -32,4 +32,24 @@ class UserService { profileUrl: Uri.parse(response.avatarUrl), ); } + + Future getSelf() async { + ReadSelfRequest request = ReadSelfRequest(); + ReadSelfResponse response = await userService.readSelf( + request, + options: CallOptions( + metadata: UserAPIServiceClients().getMetaData( + organizationId: AuthenticationUtility.fallbackOrganizationId, + ), + ), + ); + + return User( + id: response.id, + name: response.name, + nickName: response.nickname, + email: "no-email", // TODO replace this + profileUrl: Uri.parse(response.avatarUrl), + ); + } } diff --git a/packages/helpwave_theme/lib/src/constants.dart b/packages/helpwave_theme/lib/src/constants.dart index 6d0e95c0..291df3aa 100644 --- a/packages/helpwave_theme/lib/src/constants.dart +++ b/packages/helpwave_theme/lib/src/constants.dart @@ -130,6 +130,8 @@ const chipTheme = ChipThemeData( pressElevation: 4, ); +const AppBarTheme sharedAppBarTheme = AppBarTheme(centerTitle: true); + /// TextStyles TextStyle editableValueTextStyle(BuildContext context) => TextStyle(color: Theme.of(context).colorScheme.secondary, fontSize: 16, fontWeight: FontWeight.bold); diff --git a/packages/helpwave_theme/lib/src/theme/dark_theme.dart b/packages/helpwave_theme/lib/src/theme/dark_theme.dart index 5002ff66..8953e56f 100644 --- a/packages/helpwave_theme/lib/src/theme/dark_theme.dart +++ b/packages/helpwave_theme/lib/src/theme/dark_theme.dart @@ -81,4 +81,10 @@ ThemeData darkTheme = makeTheme( // additional brightness: Brightness.dark, + + // flutter themes + appBarTheme: sharedAppBarTheme.copyWith( + backgroundColor: const Color.fromARGB(255, 15, 15, 15), + foregroundColor: Colors.white, + ) ); diff --git a/packages/helpwave_theme/lib/src/theme/light_theme.dart b/packages/helpwave_theme/lib/src/theme/light_theme.dart index 72e708cf..881e600d 100644 --- a/packages/helpwave_theme/lib/src/theme/light_theme.dart +++ b/packages/helpwave_theme/lib/src/theme/light_theme.dart @@ -10,7 +10,7 @@ const onSecondaryColor = Color.fromARGB(255, 255, 255, 255); const tertiary = Color.fromARGB(255, 180, 180, 180); const onTertiary = Color.fromARGB(255, 0, 0, 0); -const backgroundColor = Color.fromARGB(255, 230, 230, 230); +const backgroundColor = Color.fromARGB(255, 242, 242, 242); const onBackgroundColor = Color.fromARGB(255, 0, 0, 0); const surface = Color.fromARGB(255, 220, 220, 220); @@ -81,4 +81,10 @@ ThemeData lightTheme = makeTheme( // additional brightness: Brightness.dark, + + // flutter themes + appBarTheme: sharedAppBarTheme.copyWith( + backgroundColor: Colors.white, + foregroundColor: Colors.black, + ) ); diff --git a/packages/helpwave_theme/lib/src/theme/theme.dart b/packages/helpwave_theme/lib/src/theme/theme.dart index a9a27fd7..6c559af3 100644 --- a/packages/helpwave_theme/lib/src/theme/theme.dart +++ b/packages/helpwave_theme/lib/src/theme/theme.dart @@ -48,6 +48,9 @@ ThemeData makeTheme({ // additional parameters required Brightness brightness, + + // Flutter Themes + AppBarTheme appBarTheme = sharedAppBarTheme, }) { return ThemeData( useMaterial3: true, @@ -104,12 +107,7 @@ ThemeData makeTheme({ listTileTheme: ListTileThemeData( iconColor: focusedColor, ), - appBarTheme: AppBarTheme( - centerTitle: true, - foregroundColor: primaryColor, - backgroundColor: Colors.transparent, - shadowColor: Colors.transparent, - ), + appBarTheme: appBarTheme, elevatedButtonTheme: ElevatedButtonThemeData( style: buttonStyleSmall.copyWith( backgroundColor: resolveByStates( diff --git a/packages/helpwave_widget/lib/bottom_sheets.dart b/packages/helpwave_widget/lib/bottom_sheets.dart index bd339f47..4625700e 100644 --- a/packages/helpwave_widget/lib/bottom_sheets.dart +++ b/packages/helpwave_widget/lib/bottom_sheets.dart @@ -1 +1 @@ -export 'package:helpwave_widget/src/bottom_sheets/bottom_sheet_base.dart'; +export 'package:helpwave_widget/src/bottom_sheets/index.dart'; diff --git a/packages/helpwave_widget/lib/src/bottom_sheets/bottom_sheet_base.dart b/packages/helpwave_widget/lib/src/bottom_sheets/bottom_sheet_base.dart index 67e6e62d..451e5735 100644 --- a/packages/helpwave_widget/lib/src/bottom_sheets/bottom_sheet_base.dart +++ b/packages/helpwave_widget/lib/src/bottom_sheets/bottom_sheet_base.dart @@ -6,13 +6,14 @@ extension PushModalContextExtension on BuildContext { required BuildContext context, required Widget Function(BuildContext context) builder, Duration animationDuration = const Duration(milliseconds: 500), + Duration reverseDuration = const Duration(milliseconds: 250), }) async { T? value = await Navigator.of(context).push( PageRouteBuilder( - barrierColor: Colors.black.withOpacity(0.3), + barrierColor: Colors.black.withOpacity(0.4), barrierDismissible: true, transitionDuration: animationDuration, - reverseTransitionDuration: animationDuration, + reverseTransitionDuration: reverseDuration, opaque: false, // Set to false to make the route semi-transparent pageBuilder: (BuildContext context, _, __) { @@ -92,7 +93,7 @@ class _ModalWrapperState extends State<_ModalWrapper> with TickerProviderStateMi if (newOffset < 0) { newOffset = 0; } - + offset.value = newOffset; touchPositionY = details.globalPosition.dy; @@ -111,18 +112,142 @@ class _ModalWrapperState extends State<_ModalWrapper> with TickerProviderStateMi child: Align( alignment: Alignment.bottomCenter, child: ValueListenableBuilder( - valueListenable: offset, - child: Material( - color: Colors.transparent, - child: widget.builder(context), - ), - builder: (context, offsetValue, child) { - return Transform.translate( + valueListenable: offset, + child: Material( + color: Colors.transparent, + child: widget.builder(context), + ), + builder: (context, offsetValue, child) { + return Transform.translate( offset: Offset(0, offsetValue), - child: child, - ); - }, + child: child, + ); + }, + ), + ), + ); + } +} + +class BottomSheetAction { + final IconData icon; + final Function() onPressed; + + BottomSheetAction({required this.icon, required this.onPressed}); +} + +class BottomSheetHeader extends StatelessWidget { + /// A [BottomSheetAction] leading before the [title] + /// + /// Defaults to a closing button + final BottomSheetAction? leading; + + /// A [BottomSheetAction] trailing after the [title] + final BottomSheetAction? trailing; + + /// The title of the [BottomSheetHeader] displayed in the center + /// + /// Overwrites [titleText] + final Widget? title; + + /// The title text of the [BottomSheetHeader] displayed in the center + /// + /// Overwritten by [title] + final String? titleText; + + /// Whether the drag handler widget should be shown + final bool isShowingDragHandler; + + /// An additional padding for the [BottomSheetHeader] + /// + /// Be aware that the [BottomSheetBase] **already provides a padding** to all sides. + /// + /// You most likely want to change the bottom padding to create spacing between [BottomSheetHeader] and content of + /// the [BottomSheetBase]. + final EdgeInsets padding; + + const BottomSheetHeader({ + super.key, + this.leading, + this.trailing, + this.title, + this.titleText, + this.isShowingDragHandler = false, + this.padding = const EdgeInsets.only(bottom: paddingSmall), + }); + + @override + Widget build(BuildContext context) { + BottomSheetAction usedLeading = + leading ?? BottomSheetAction(icon: Icons.close_rounded, onPressed: () => Navigator.maybePop(context)); + + const double iconSize = iconSizeSmall; + + return Padding( + padding: padding, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Visibility( + visible: isShowingDragHandler, + child: Padding( + padding: const EdgeInsets.only(bottom: paddingSmall), + child: Center( + child: Container( + height: 5, + width: 30, + decoration: BoxDecoration( + color: Theme.of(context).colorScheme.onBackground.withOpacity(0.8), + borderRadius: BorderRadius.circular(5), + ), + ), + ), + ), ), + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + SizedBox( + width: iconSize, + height: iconSize, + child: IconButton( + padding: EdgeInsets.zero, + iconSize: iconSize, + onPressed: usedLeading.onPressed, + icon: Icon(usedLeading.icon), + ), + ), + Flexible( + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: paddingSmall), + child: title ?? + Text( + titleText ?? "", + style: const TextStyle( + fontWeight: FontWeight.bold, + fontSize: iconSizeTiny, + fontFamily: "SpaceGrotesk", + overflow: TextOverflow.ellipsis, + ), + ), + ), + ), + SizedBox( + width: iconSize, + height: iconSize, + child: trailing != null + ? IconButton( + padding: EdgeInsets.zero, + iconSize: iconSize, + onPressed: trailing!.onPressed, + icon: Icon(trailing!.icon), + ) + : null, + ), + ], + ), + ], ), ); } @@ -136,32 +261,27 @@ class BottomSheetBase extends StatefulWidget { /// The builder function call to build the content of the [BottomSheetBase] final Widget Function(BuildContext context) builder; - /// The title of the titlebar - /// - /// Overwrites [titleText] - final Widget? title; - - /// The title text of the titlebar + /// A header [Widget] above the builder content /// - /// Overwritten by [title] - final String titleText; + /// Defaults to the [BottomSheetHeader] + final Widget header; /// The bottom [Widget] below the [builder] - /// - /// Overwrites [titleText] final Widget? bottomWidget; /// The [Padding] of the builder [Widget] final EdgeInsetsGeometry padding; + final MainAxisSize mainAxisSize; + const BottomSheetBase({ super.key, required this.onClosing, required this.builder, - this.title, - this.titleText = "", this.padding = const EdgeInsets.all(paddingMedium), this.bottomWidget, + this.header = const BottomSheetHeader(), + this.mainAxisSize = MainAxisSize.min, }); @override @@ -171,69 +291,26 @@ class BottomSheetBase extends StatefulWidget { class _BottomSheetBase extends State with TickerProviderStateMixin { @override Widget build(BuildContext context) { - return BottomSheet( - animationController: BottomSheet.createAnimationController(this), - enableDrag: false, - onClosing: widget.onClosing, - builder: (context) { - return Padding( - padding: widget.padding, - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - Padding( - padding: const EdgeInsets.only(bottom: paddingSmall), - child: Center( - child: Container( - height: 5, - width: 30, - decoration: BoxDecoration( - color: Theme.of(context).colorScheme.onBackground.withOpacity(0.8), - borderRadius: BorderRadius.circular(5), - ), - ), - ), - ), - Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - crossAxisAlignment: CrossAxisAlignment.center, - children: [ - SizedBox( - width: iconSizeTiny, - height: iconSizeTiny, - child: IconButton( - padding: EdgeInsets.zero, - iconSize: iconSizeTiny, - onPressed: () => Navigator.maybePop(context), - icon: const Icon(Icons.close_rounded), - ), - ), - Flexible( - child: Padding( - padding: const EdgeInsets.symmetric(horizontal: paddingSmall), - child: widget.title ?? - Text( - widget.titleText, - style: const TextStyle( - fontWeight: FontWeight.bold, - fontSize: iconSizeTiny, - fontFamily: "SpaceGrotesk", - overflow: TextOverflow.ellipsis, - ), - ), - ), - ), - const SizedBox(width: iconSizeTiny), - ], - ), - SingleChildScrollView( - child: widget.builder(context), - ), - widget.bottomWidget ?? const SizedBox(), - ], - ), - ); - }, + return SafeArea( + child: BottomSheet( + constraints: BoxConstraints(maxHeight: MediaQuery.of(context).size.height * 0.85), + animationController: BottomSheet.createAnimationController(this), + enableDrag: false, + onClosing: widget.onClosing, + builder: (context) { + return Padding( + padding: widget.padding, + child: Column( + mainAxisSize: widget.mainAxisSize, + children: [ + widget.header, + widget.builder(context), + widget.bottomWidget ?? const SizedBox(), + ], + ), + ); + }, + ), ); } } diff --git a/packages/helpwave_widget/lib/src/bottom_sheets/index.dart b/packages/helpwave_widget/lib/src/bottom_sheets/index.dart new file mode 100644 index 00000000..e1423f66 --- /dev/null +++ b/packages/helpwave_widget/lib/src/bottom_sheets/index.dart @@ -0,0 +1,2 @@ +export 'bottom_sheet_base.dart'; +export 'nested_bottom_sheet_navigation.dart'; diff --git a/packages/helpwave_widget/lib/src/bottom_sheets/nested_bottom_sheet_navigation.dart b/packages/helpwave_widget/lib/src/bottom_sheets/nested_bottom_sheet_navigation.dart new file mode 100644 index 00000000..af15be7e --- /dev/null +++ b/packages/helpwave_widget/lib/src/bottom_sheets/nested_bottom_sheet_navigation.dart @@ -0,0 +1,102 @@ +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; +import 'package:helpwave_widget/src/bottom_sheets/bottom_sheet_base.dart'; + +mixin BottomSheetPageBuilder { + /// The [BottomSheetHeader] of the [BottomSheetPageBuilder] + /// + /// The leading icon will always be ignored to + BottomSheetHeader? headerBuilder(BuildContext context, NestedBottomSheetNavigationController controller) { + return null; + } + + /// The [BottomSheetBase] bottom widget to display for the [BottomSheetPageBuilder] + Widget? bottomWidgetBuilder(BuildContext context, NestedBottomSheetNavigationController controller) { + return null; + } + + /// The builder function call to build the content of the [BottomSheetBase] + Widget build(BuildContext context, NestedBottomSheetNavigationController controller); +} + +class NestedBottomSheetNavigationController extends ChangeNotifier { + List stack = []; + + BottomSheetPageBuilder get currentPage => stack.last; + + bool get canPop => stack.length > 1; + + bool get isInitialPage => stack.length == 1; + + NestedBottomSheetNavigationController({ + required BottomSheetPageBuilder initialPageBuilder, + }) { + stack.add(initialPageBuilder); + } + + void push(BottomSheetPageBuilder page) { + stack.add(page); + notifyListeners(); + } + + void pop() { + stack.removeLast(); + notifyListeners(); + } +} + +class NestedBottomSheetNavigator extends StatelessWidget { + final BottomSheetPageBuilder initialPageBuilder; + + const NestedBottomSheetNavigator({super.key, required this.initialPageBuilder}); + + @override + Widget build(BuildContext context) { + return ChangeNotifierProvider( + create: (context) => NestedBottomSheetNavigationController( + initialPageBuilder: initialPageBuilder, + ), + child: Consumer( + builder: (context, navigationController, child) { + BottomSheetPageBuilder page = navigationController.currentPage; + + BottomSheetHeader? computedHeader = page.headerBuilder(context, navigationController); + + BottomSheetHeader header = BottomSheetHeader( + title: computedHeader?.title, + titleText: computedHeader?.titleText, + isShowingDragHandler: computedHeader?.isShowingDragHandler ?? false, + trailing: computedHeader?.trailing, + leading: BottomSheetAction( + icon: navigationController.isInitialPage ? Icons.close : Icons.chevron_left_rounded, + onPressed: () { + if (navigationController.canPop) { + navigationController.pop(); + } else { + Navigator.pop(context); + } + }, + ), + ); + + return PopScope( + // If the navigation controller cannot pop to another bottom sheet, a normal pop is correct + canPop: !navigationController.canPop, + onPopInvoked: (didPop) { + if(navigationController.canPop){ + navigationController.pop(); + } + }, + child: BottomSheetBase( + onClosing: () {}, + builder: (context) => page.build(context, navigationController), + header: header, + bottomWidget: page.bottomWidgetBuilder(context, navigationController), + mainAxisSize: MainAxisSize.max, + ), + ); + }, + ), + ); + } +} diff --git a/packages/helpwave_widget/lib/src/widgets/fallback_avatar.dart b/packages/helpwave_widget/lib/src/widgets/fallback_avatar.dart new file mode 100644 index 00000000..678fcd1e --- /dev/null +++ b/packages/helpwave_widget/lib/src/widgets/fallback_avatar.dart @@ -0,0 +1,40 @@ +import 'package:flutter/material.dart'; +import 'package:helpwave_theme/constants.dart'; + +/// A [CircleAvatar] with a dummy image that can be sized as needed +class FallbackAvatar extends StatelessWidget{ + /// The size of the [CircleAvatar] + final double size; + + const FallbackAvatar({super.key, this.size = iconSizeSmall}); + + @override + Widget build(BuildContext context) { + return CircleAvatar( + backgroundColor: Colors.transparent, + radius: iconSizeSmall / 2, + child: Container( + width: iconSizeSmall, + height: iconSizeSmall, + decoration: const BoxDecoration( + shape: BoxShape.circle, + gradient: LinearGradient( + begin: Alignment.topLeft, + end: Alignment(0.8, 1), + colors: [ + Color(0xff1f005c), + Color(0xff5b0060), + Color(0xff870160), + Color(0xffac255e), + Color(0xffca485c), + Color(0xffe16b5c), + Color(0xfff39060), + Color(0xffffb56b), + ], + tileMode: TileMode.mirror, + ), + ), + ), + ); + } +} diff --git a/packages/helpwave_widget/lib/src/widgets/index.dart b/packages/helpwave_widget/lib/src/widgets/index.dart new file mode 100644 index 00000000..5cbf43ab --- /dev/null +++ b/packages/helpwave_widget/lib/src/widgets/index.dart @@ -0,0 +1,2 @@ +export 'fallback_avatar.dart'; +export 'list_tile_card.dart'; diff --git a/packages/helpwave_widget/lib/src/widgets/widgets.dart b/packages/helpwave_widget/lib/src/widgets/list_tile_card.dart similarity index 100% rename from packages/helpwave_widget/lib/src/widgets/widgets.dart rename to packages/helpwave_widget/lib/src/widgets/list_tile_card.dart diff --git a/packages/helpwave_widget/lib/widgets.dart b/packages/helpwave_widget/lib/widgets.dart index df63dd05..8dfcb136 100644 --- a/packages/helpwave_widget/lib/widgets.dart +++ b/packages/helpwave_widget/lib/widgets.dart @@ -1 +1 @@ -export 'package:helpwave_widget/src/widgets/widgets.dart'; +export 'package:helpwave_widget/src/widgets/index.dart'; diff --git a/packages/helpwave_widget/pubspec.yaml b/packages/helpwave_widget/pubspec.yaml index bf60e6d9..22e6edf3 100644 --- a/packages/helpwave_widget/pubspec.yaml +++ b/packages/helpwave_widget/pubspec.yaml @@ -18,6 +18,7 @@ dependencies: path: "../helpwave_localization" helpwave_util: path: "../helpwave_util" + provider: ^6.0.3 dev_dependencies: flutter_test: From a1d8dc975024a68b9ec1c940b60be33fdc0675fd Mon Sep 17 00:00:00 2001 From: Felix Thape Date: Wed, 18 Sep 2024 18:46:48 +0200 Subject: [PATCH 8/9] feat: make navigator generic --- .../lib/components/user_bottom_sheet.dart | 5 +- apps/tasks/lib/components/user_header.dart | 2 +- .../patient_screen.dart | 2 +- apps/tasks/lib/screens/settings_screen.dart | 13 +-- packages/helpwave_widget/lib/navigation.dart | 1 + .../bottom_sheets/bottom_sheet_navigator.dart | 46 ++++++++ .../bottom_sheet_page_builder.dart | 20 ++++ .../lib/src/bottom_sheets/index.dart | 3 +- .../nested_bottom_sheet_navigation.dart | 102 ------------------ .../lib/src/navigation/index.dart | 2 + .../src/navigation/navigation_controller.dart | 27 +++++ .../lib/src/navigation/simple_navigator.dart | 35 ++++++ 12 files changed, 145 insertions(+), 113 deletions(-) create mode 100644 packages/helpwave_widget/lib/navigation.dart create mode 100644 packages/helpwave_widget/lib/src/bottom_sheets/bottom_sheet_navigator.dart create mode 100644 packages/helpwave_widget/lib/src/bottom_sheets/bottom_sheet_page_builder.dart delete mode 100644 packages/helpwave_widget/lib/src/bottom_sheets/nested_bottom_sheet_navigation.dart create mode 100644 packages/helpwave_widget/lib/src/navigation/index.dart create mode 100644 packages/helpwave_widget/lib/src/navigation/navigation_controller.dart create mode 100644 packages/helpwave_widget/lib/src/navigation/simple_navigator.dart diff --git a/apps/tasks/lib/components/user_bottom_sheet.dart b/apps/tasks/lib/components/user_bottom_sheet.dart index 4823ac6f..74a7dfbd 100644 --- a/apps/tasks/lib/components/user_bottom_sheet.dart +++ b/apps/tasks/lib/components/user_bottom_sheet.dart @@ -5,6 +5,7 @@ import 'package:helpwave_service/user.dart'; import 'package:helpwave_theme/constants.dart'; import 'package:helpwave_widget/bottom_sheets.dart'; import 'package:helpwave_widget/loading.dart'; +import 'package:helpwave_widget/navigation.dart'; import 'package:provider/provider.dart'; import 'package:helpwave_service/tasks.dart'; import 'package:helpwave_service/auth.dart'; @@ -15,7 +16,7 @@ import 'package:tasks/screens/settings_screen.dart'; class UserBottomSheetPageBuilder with BottomSheetPageBuilder { @override - BottomSheetHeader? headerBuilder(BuildContext context, NestedBottomSheetNavigationController controller) { + BottomSheetHeader? headerBuilder(BuildContext context, NavigationController controller) { return BottomSheetHeader( trailing: BottomSheetAction( icon: Icons.settings, @@ -25,7 +26,7 @@ class UserBottomSheetPageBuilder with BottomSheetPageBuilder { } @override - Widget build(BuildContext context, NestedBottomSheetNavigationController controller) { + Widget build(BuildContext context, NavigationController controller) { final double width = MediaQuery.of(context).size.width; return Flexible( diff --git a/apps/tasks/lib/components/user_header.dart b/apps/tasks/lib/components/user_header.dart index 5ea59d78..15a9ece6 100644 --- a/apps/tasks/lib/components/user_header.dart +++ b/apps/tasks/lib/components/user_header.dart @@ -40,7 +40,7 @@ class UserHeader extends StatelessWidget implements PreferredSizeWidget { onTap: () { context.pushModal( context: context, - builder: (context) => NestedBottomSheetNavigator(initialPageBuilder: UserBottomSheetPageBuilder()), + builder: (context) => BottomSheetNavigator(initialPageBuilder: UserBottomSheetPageBuilder()), ); }, title: Text( diff --git a/apps/tasks/lib/screens/main_screen_subscreens/patient_screen.dart b/apps/tasks/lib/screens/main_screen_subscreens/patient_screen.dart index 2278a361..77a4dd12 100644 --- a/apps/tasks/lib/screens/main_screen_subscreens/patient_screen.dart +++ b/apps/tasks/lib/screens/main_screen_subscreens/patient_screen.dart @@ -28,7 +28,7 @@ class _PatientScreenState extends State { child: Column( children: [ Padding( - padding: const EdgeInsets.only(left: paddingSmall, right: paddingSmall, bottom: paddingMedium), + padding: const EdgeInsets.only(left: paddingSmall, right: paddingSmall, bottom: paddingMedium, top: paddingSmall), child: Consumer(builder: (_, patientController, __) { return SearchBar( hintText: context.localization!.searchPatient, diff --git a/apps/tasks/lib/screens/settings_screen.dart b/apps/tasks/lib/screens/settings_screen.dart index 9f31e582..02bc5588 100644 --- a/apps/tasks/lib/screens/settings_screen.dart +++ b/apps/tasks/lib/screens/settings_screen.dart @@ -5,6 +5,7 @@ import 'package:helpwave_service/auth.dart'; import 'package:helpwave_theme/constants.dart'; import 'package:helpwave_theme/theme.dart'; import 'package:helpwave_widget/bottom_sheets.dart'; +import 'package:helpwave_widget/navigation.dart'; import 'package:provider/provider.dart'; import 'package:tasks/screens/login_screen.dart'; @@ -146,7 +147,7 @@ class SettingsScreen extends StatelessWidget { class SettingsBottomSheetPageBuilder with BottomSheetPageBuilder { @override - Widget build(BuildContext context, NestedBottomSheetNavigationController controller) { + Widget build(BuildContext context, NavigationController controller) { return Flexible( child: ListView( children: ListTile.divideTiles( @@ -213,11 +214,11 @@ class SettingsBottomSheetPageBuilder with BottomSheetPageBuilder { }, itemBuilder: (BuildContext context) => getSupportedLocalsWithName() .map((local) => PopupMenuItem( - value: local.local, - child: Text( - local.name, - ), - )) + value: local.local, + child: Text( + local.name, + ), + )) .toList(), child: Material( child: Row( diff --git a/packages/helpwave_widget/lib/navigation.dart b/packages/helpwave_widget/lib/navigation.dart new file mode 100644 index 00000000..073a7465 --- /dev/null +++ b/packages/helpwave_widget/lib/navigation.dart @@ -0,0 +1 @@ +export 'package:helpwave_widget/src/navigation/index.dart'; diff --git a/packages/helpwave_widget/lib/src/bottom_sheets/bottom_sheet_navigator.dart b/packages/helpwave_widget/lib/src/bottom_sheets/bottom_sheet_navigator.dart new file mode 100644 index 00000000..50544009 --- /dev/null +++ b/packages/helpwave_widget/lib/src/bottom_sheets/bottom_sheet_navigator.dart @@ -0,0 +1,46 @@ +import 'package:flutter/material.dart'; +import 'package:helpwave_widget/navigation.dart'; +import '../../bottom_sheets.dart'; + +class BottomSheetNavigator extends StatelessWidget { + final BottomSheetPageBuilder initialPageBuilder; + + const BottomSheetNavigator({super.key, required this.initialPageBuilder}); + + @override + Widget build(BuildContext context) { + return SimpleNavigator( + initialPage: initialPageBuilder, + builder: (context, navigationController) { + BottomSheetPageBuilder page = navigationController.currentPage; + + BottomSheetHeader? computedHeader = page.headerBuilder(context, navigationController); + + BottomSheetHeader header = BottomSheetHeader( + title: computedHeader?.title, + titleText: computedHeader?.titleText, + isShowingDragHandler: computedHeader?.isShowingDragHandler ?? false, + trailing: computedHeader?.trailing, + leading: BottomSheetAction( + icon: navigationController.isInitialPage ? Icons.close : Icons.chevron_left_rounded, + onPressed: () { + if (navigationController.canPop) { + navigationController.pop(); + } else { + Navigator.pop(context); + } + }, + ), + ); + + return BottomSheetBase( + onClosing: () {}, + builder: (context) => page.build(context, navigationController), + header: header, + bottomWidget: page.bottomWidgetBuilder(context, navigationController), + mainAxisSize: MainAxisSize.max, + ); + }, + ); + } +} diff --git a/packages/helpwave_widget/lib/src/bottom_sheets/bottom_sheet_page_builder.dart b/packages/helpwave_widget/lib/src/bottom_sheets/bottom_sheet_page_builder.dart new file mode 100644 index 00000000..0af34f0c --- /dev/null +++ b/packages/helpwave_widget/lib/src/bottom_sheets/bottom_sheet_page_builder.dart @@ -0,0 +1,20 @@ +import 'package:flutter/cupertino.dart'; +import 'package:helpwave_widget/navigation.dart'; +import '../../bottom_sheets.dart'; + +mixin BottomSheetPageBuilder { + /// The [BottomSheetHeader] of the [BottomSheetPageBuilder] + /// + /// The leading icon will always be ignored to + BottomSheetHeader? headerBuilder(BuildContext context, NavigationController controller) { + return null; + } + + /// The [BottomSheetBase] bottom widget to display for the [BottomSheetPageBuilder] + Widget? bottomWidgetBuilder(BuildContext context, NavigationController controller) { + return null; + } + + /// The builder function call to build the content of the [BottomSheetBase] + Widget build(BuildContext context, NavigationController controller); +} diff --git a/packages/helpwave_widget/lib/src/bottom_sheets/index.dart b/packages/helpwave_widget/lib/src/bottom_sheets/index.dart index e1423f66..5277adaf 100644 --- a/packages/helpwave_widget/lib/src/bottom_sheets/index.dart +++ b/packages/helpwave_widget/lib/src/bottom_sheets/index.dart @@ -1,2 +1,3 @@ export 'bottom_sheet_base.dart'; -export 'nested_bottom_sheet_navigation.dart'; +export 'bottom_sheet_navigator.dart'; +export 'bottom_sheet_page_builder.dart'; diff --git a/packages/helpwave_widget/lib/src/bottom_sheets/nested_bottom_sheet_navigation.dart b/packages/helpwave_widget/lib/src/bottom_sheets/nested_bottom_sheet_navigation.dart deleted file mode 100644 index af15be7e..00000000 --- a/packages/helpwave_widget/lib/src/bottom_sheets/nested_bottom_sheet_navigation.dart +++ /dev/null @@ -1,102 +0,0 @@ -import 'package:flutter/material.dart'; -import 'package:provider/provider.dart'; -import 'package:helpwave_widget/src/bottom_sheets/bottom_sheet_base.dart'; - -mixin BottomSheetPageBuilder { - /// The [BottomSheetHeader] of the [BottomSheetPageBuilder] - /// - /// The leading icon will always be ignored to - BottomSheetHeader? headerBuilder(BuildContext context, NestedBottomSheetNavigationController controller) { - return null; - } - - /// The [BottomSheetBase] bottom widget to display for the [BottomSheetPageBuilder] - Widget? bottomWidgetBuilder(BuildContext context, NestedBottomSheetNavigationController controller) { - return null; - } - - /// The builder function call to build the content of the [BottomSheetBase] - Widget build(BuildContext context, NestedBottomSheetNavigationController controller); -} - -class NestedBottomSheetNavigationController extends ChangeNotifier { - List stack = []; - - BottomSheetPageBuilder get currentPage => stack.last; - - bool get canPop => stack.length > 1; - - bool get isInitialPage => stack.length == 1; - - NestedBottomSheetNavigationController({ - required BottomSheetPageBuilder initialPageBuilder, - }) { - stack.add(initialPageBuilder); - } - - void push(BottomSheetPageBuilder page) { - stack.add(page); - notifyListeners(); - } - - void pop() { - stack.removeLast(); - notifyListeners(); - } -} - -class NestedBottomSheetNavigator extends StatelessWidget { - final BottomSheetPageBuilder initialPageBuilder; - - const NestedBottomSheetNavigator({super.key, required this.initialPageBuilder}); - - @override - Widget build(BuildContext context) { - return ChangeNotifierProvider( - create: (context) => NestedBottomSheetNavigationController( - initialPageBuilder: initialPageBuilder, - ), - child: Consumer( - builder: (context, navigationController, child) { - BottomSheetPageBuilder page = navigationController.currentPage; - - BottomSheetHeader? computedHeader = page.headerBuilder(context, navigationController); - - BottomSheetHeader header = BottomSheetHeader( - title: computedHeader?.title, - titleText: computedHeader?.titleText, - isShowingDragHandler: computedHeader?.isShowingDragHandler ?? false, - trailing: computedHeader?.trailing, - leading: BottomSheetAction( - icon: navigationController.isInitialPage ? Icons.close : Icons.chevron_left_rounded, - onPressed: () { - if (navigationController.canPop) { - navigationController.pop(); - } else { - Navigator.pop(context); - } - }, - ), - ); - - return PopScope( - // If the navigation controller cannot pop to another bottom sheet, a normal pop is correct - canPop: !navigationController.canPop, - onPopInvoked: (didPop) { - if(navigationController.canPop){ - navigationController.pop(); - } - }, - child: BottomSheetBase( - onClosing: () {}, - builder: (context) => page.build(context, navigationController), - header: header, - bottomWidget: page.bottomWidgetBuilder(context, navigationController), - mainAxisSize: MainAxisSize.max, - ), - ); - }, - ), - ); - } -} diff --git a/packages/helpwave_widget/lib/src/navigation/index.dart b/packages/helpwave_widget/lib/src/navigation/index.dart new file mode 100644 index 00000000..42ae72d6 --- /dev/null +++ b/packages/helpwave_widget/lib/src/navigation/index.dart @@ -0,0 +1,2 @@ +export 'navigation_controller.dart'; +export 'simple_navigator.dart'; diff --git a/packages/helpwave_widget/lib/src/navigation/navigation_controller.dart b/packages/helpwave_widget/lib/src/navigation/navigation_controller.dart new file mode 100644 index 00000000..8d540f8f --- /dev/null +++ b/packages/helpwave_widget/lib/src/navigation/navigation_controller.dart @@ -0,0 +1,27 @@ +import 'package:flutter/cupertino.dart'; + +class NavigationController extends ChangeNotifier { + List stack = []; + + T get currentPage => stack.last; + + bool get canPop => stack.length > 1; + + bool get isInitialPage => stack.length == 1; + + NavigationController({ + required T initialPage, + }) { + stack.add(initialPage); + } + + void push(T page) { + stack.add(page); + notifyListeners(); + } + + void pop() { + stack.removeLast(); + notifyListeners(); + } +} diff --git a/packages/helpwave_widget/lib/src/navigation/simple_navigator.dart b/packages/helpwave_widget/lib/src/navigation/simple_navigator.dart new file mode 100644 index 00000000..de114744 --- /dev/null +++ b/packages/helpwave_widget/lib/src/navigation/simple_navigator.dart @@ -0,0 +1,35 @@ +import 'package:flutter/material.dart'; +import 'package:helpwave_widget/src/navigation/index.dart'; +import 'package:provider/provider.dart'; + +/// A navigation widget which can be used withing the flutter [Navigator] +class SimpleNavigator extends StatelessWidget { + final T initialPage; + + final Widget Function(BuildContext context, NavigationController navigationController) builder; + + const SimpleNavigator({super.key, required this.initialPage, required this.builder}); + + @override + Widget build(BuildContext context) { + return ChangeNotifierProvider( + create: (context) => NavigationController( + initialPage: initialPage, + ), + child: Consumer>( + builder: (context, navigationController, _) { + return PopScope( + // If the navigation controller cannot pop to another bottom sheet, a normal pop is correct + canPop: !navigationController.canPop, + onPopInvoked: (didPop) { + if (navigationController.canPop) { + navigationController.pop(); + } + }, + child: builder(context, navigationController), + ); + }, + ), + ); + } +} From 91c536101729994b4a704f74099bae817e4121dc Mon Sep 17 00:00:00 2001 From: Felix Thape Date: Thu, 19 Sep 2024 03:40:43 +0200 Subject: [PATCH 9/9] feat: update user bottom sheet and setting bottom sheet --- .../lib/components/patient_bottom_sheet.dart | 10 +- .../lib/components/task_bottom_sheet.dart | 11 +- apps/tasks/lib/components/task_card.dart | 13 +- .../lib/components/task_expansion_tile.dart | 9 +- .../lib/components/user_bottom_sheet.dart | 122 +++----- apps/tasks/lib/components/user_header.dart | 9 +- .../components/ward_select_bottom_sheet.dart | 53 ++++ apps/tasks/lib/screens/landing_screen.dart | 2 +- apps/tasks/lib/screens/main_screen.dart | 28 +- .../my_tasks_screen.dart | 3 +- .../patient_screen.dart | 5 +- apps/tasks/lib/screens/settings_screen.dart | 260 +++++++++++++----- apps/tasks/pubspec.yaml | 4 + .../helpwave_localization/lib/l10n/app_de.arb | 8 +- .../helpwave_localization/lib/l10n/app_en.arb | 8 +- .../src/api/tasks/services/ward_service.dart | 15 + .../fonts/Space_Grotesk/OFL.txt | 0 .../fonts/Space_Grotesk/README.txt | 0 .../SpaceGrotesk-VariableFont_wght.ttf | Bin .../static/SpaceGrotesk-Bold.ttf | Bin .../static/SpaceGrotesk-Light.ttf | Bin .../static/SpaceGrotesk-Medium.ttf | Bin .../static/SpaceGrotesk-Regular.ttf | Bin .../static/SpaceGrotesk-SemiBold.ttf | Bin .../helpwave_theme/lib/src/constants.dart | 3 +- .../lib/src/theme/dark_theme.dart | 51 ++-- .../lib/src/theme/light_theme.dart | 47 ++-- .../helpwave_theme/lib/src/theme/theme.dart | 39 +-- .../helpwave_theme/lib/src/theme_model.dart | 3 +- .../util/material_state_color_resolver.dart | 5 +- packages/helpwave_theme/pubspec.yaml | 2 +- packages/helpwave_widget/lib/lists.dart | 2 +- .../src/bottom_sheets/bottom_sheet_base.dart | 3 +- .../lib/src/content_selection/list_entry.dart | 3 +- .../src/content_selection/list_search.dart | 5 +- .../lib/src/lists/add_list.dart | 5 +- .../helpwave_widget/lib/src/lists/index.dart | 2 + .../lib/src/lists/rounded_list_tiles.dart | 56 ++++ .../lib/src/loading/loading_spinner.dart | 3 +- .../src/text_input/clickable_text_edit.dart | 11 +- 40 files changed, 516 insertions(+), 284 deletions(-) create mode 100644 apps/tasks/lib/components/ward_select_bottom_sheet.dart rename packages/helpwave_theme/{assets => lib}/fonts/Space_Grotesk/OFL.txt (100%) rename packages/helpwave_theme/{assets => lib}/fonts/Space_Grotesk/README.txt (100%) rename packages/helpwave_theme/{assets => lib}/fonts/Space_Grotesk/SpaceGrotesk-VariableFont_wght.ttf (100%) rename packages/helpwave_theme/{assets => lib}/fonts/Space_Grotesk/static/SpaceGrotesk-Bold.ttf (100%) rename packages/helpwave_theme/{assets => lib}/fonts/Space_Grotesk/static/SpaceGrotesk-Light.ttf (100%) rename packages/helpwave_theme/{assets => lib}/fonts/Space_Grotesk/static/SpaceGrotesk-Medium.ttf (100%) rename packages/helpwave_theme/{assets => lib}/fonts/Space_Grotesk/static/SpaceGrotesk-Regular.ttf (100%) rename packages/helpwave_theme/{assets => lib}/fonts/Space_Grotesk/static/SpaceGrotesk-SemiBold.ttf (100%) create mode 100644 packages/helpwave_widget/lib/src/lists/index.dart create mode 100644 packages/helpwave_widget/lib/src/lists/rounded_list_tiles.dart diff --git a/apps/tasks/lib/components/patient_bottom_sheet.dart b/apps/tasks/lib/components/patient_bottom_sheet.dart index 446882d2..f5a0cca3 100644 --- a/apps/tasks/lib/components/patient_bottom_sheet.dart +++ b/apps/tasks/lib/components/patient_bottom_sheet.dart @@ -60,7 +60,7 @@ class _PatientBottomSheetState extends State { onUpdated: patientController.changeName, textAlign: TextAlign.center, textStyle: TextStyle( - color: Theme.of(context).colorScheme.secondary, + color: context.theme.colorScheme.primary, fontWeight: FontWeight.bold, fontSize: iconSizeTiny, fontFamily: "SpaceGrotesk", @@ -161,17 +161,17 @@ class _PatientBottomSheetState extends State { if (beds.isEmpty) { return Text( context.localization!.noFreeBeds, - style: TextStyle(color: Theme.of(context).disabledColor, fontWeight: FontWeight.bold), + style: TextStyle(color: context.theme.disabledColor, fontWeight: FontWeight.bold), ); } return DropdownButtonHideUnderline( child: DropdownButton( - iconEnabledColor: Theme.of(context).colorScheme.secondary.withOpacity(0.6), + iconEnabledColor: context.theme.colorScheme.primary.withOpacity(0.6), padding: EdgeInsets.zero, isDense: true, hint: Text( context.localization!.assignBed, - style: TextStyle(color: Theme.of(context).colorScheme.secondary.withOpacity(0.6)), + style: TextStyle(color: context.theme.colorScheme.primary.withOpacity(0.6)), ), value: beds.where((beds) => beds.bed.id == patientController.patient.bed?.id).firstOrNull, items: beds @@ -179,7 +179,7 @@ class _PatientBottomSheetState extends State { value: roomWithBed, child: Text( "${roomWithBed.room.name} - ${roomWithBed.bed.name}", - style: TextStyle(color: Theme.of(context).colorScheme.primary.withOpacity(0.6)), + style: TextStyle(color: context.theme.colorScheme.primary.withOpacity(0.6)), ), )) .toList(), diff --git a/apps/tasks/lib/components/task_bottom_sheet.dart b/apps/tasks/lib/components/task_bottom_sheet.dart index 271facb8..212311e5 100644 --- a/apps/tasks/lib/components/task_bottom_sheet.dart +++ b/apps/tasks/lib/components/task_bottom_sheet.dart @@ -3,6 +3,7 @@ import 'package:helpwave_localization/localization.dart'; import 'package:helpwave_service/auth.dart'; import 'package:helpwave_service/user.dart'; import 'package:helpwave_theme/constants.dart'; +import 'package:helpwave_theme/util.dart'; import 'package:helpwave_util/loading.dart'; import 'package:helpwave_widget/bottom_sheets.dart'; import 'package:helpwave_widget/loading.dart'; @@ -127,7 +128,7 @@ class _TaskBottomSheetState extends State { onUpdated: taskController.changeName, textAlign: TextAlign.center, textStyle: TextStyle( - color: Theme.of(context).colorScheme.secondary, + color: context.theme.colorScheme.primary, fontWeight: FontWeight.bold, fontSize: iconSizeTiny, fontFamily: "SpaceGrotesk", @@ -177,12 +178,12 @@ class _TaskBottomSheetState extends State { List patients = patientList.active + patientList.unassigned; return DropdownButton( underline: const SizedBox(), - iconEnabledColor: Theme.of(context).colorScheme.secondary.withOpacity(0.6), + iconEnabledColor: context.theme.colorScheme.primary.withOpacity(0.6), // removes the default underline padding: EdgeInsets.zero, hint: Text( context.localization!.selectPatient, - style: TextStyle(color: Theme.of(context).colorScheme.secondary.withOpacity(0.6)), + style: TextStyle(color: context.theme.colorScheme.primary.withOpacity(0.6)), ), isDense: true, items: patients @@ -264,7 +265,7 @@ class _TaskBottomSheetState extends State { builder: (context, child) { // Overwrite the Theme ThemeData pickerTheme = - Theme.of(context).copyWith(textButtonTheme: const TextButtonThemeData()); + context.theme.copyWith(textButtonTheme: const TextButtonThemeData()); return Theme(data: pickerTheme, child: child ?? const SizedBox()); }, ).then((date) async { @@ -272,7 +273,7 @@ class _TaskBottomSheetState extends State { context: context, initialTime: TimeOfDay.fromDateTime(taskController.task.dueDate ?? DateTime.now()), builder: (context, child) { - ThemeData originalTheme = Theme.of(context); + ThemeData originalTheme = context.theme; // Temporarily set a default theme for the picker ThemeData pickerTheme = ThemeData.fallback().copyWith( diff --git a/apps/tasks/lib/components/task_card.dart b/apps/tasks/lib/components/task_card.dart index 3eade9a4..d88d195a 100644 --- a/apps/tasks/lib/components/task_card.dart +++ b/apps/tasks/lib/components/task_card.dart @@ -2,6 +2,7 @@ import 'package:flutter/material.dart'; import 'package:helpwave_localization/localization.dart'; import 'package:helpwave_service/tasks.dart'; import 'package:helpwave_theme/constants.dart'; +import 'package:helpwave_theme/util.dart'; import 'package:helpwave_widget/static_progress_indicator.dart'; /// A [Card] showing a [Task]'s information @@ -82,8 +83,8 @@ class TaskCard extends StatelessWidget { children: [ StaticProgressIndicator( progress: task.progress, - color: Theme.of(context).colorScheme.secondary, - backgroundColor: Theme.of(context).colorScheme.onSecondary.withOpacity(0.5), + color: context.theme.colorScheme.primary, + backgroundColor: context.theme.colorScheme.onSurface.withOpacity(0.3), isClockwise: true, angle: 0, ), @@ -110,7 +111,7 @@ class TaskCard extends StatelessWidget { children: [ Text( task.patient.name, - style: TextStyle(color: Theme.of(context).colorScheme.secondary), + style: TextStyle(color: context.theme.colorScheme.primary), ), Text( task.name, @@ -126,7 +127,7 @@ class TaskCard extends StatelessWidget { fontSize: 14, fontFamily: "SpaceGrotesk", overflow: TextOverflow.ellipsis, - color: Theme.of(context).colorScheme.onSurface.withOpacity(0.6), + color: context.theme.colorScheme.onSurface.withOpacity(0.6), ), ) : const SizedBox(), ], @@ -143,7 +144,9 @@ class TaskCard extends StatelessWidget { size: iconSizeTiny, Icons.check_circle_outline_rounded, // TODO change colors later - color: task.status == TaskStatus.done ? Colors.grey : Theme.of(context).colorScheme.secondary, + color: task.status == TaskStatus.done ? context.theme.colorScheme.onSurface.withOpacity(0.4) : context.theme + .colorScheme + .primary, ), ), ], diff --git a/apps/tasks/lib/components/task_expansion_tile.dart b/apps/tasks/lib/components/task_expansion_tile.dart index de316ace..5b9e5725 100644 --- a/apps/tasks/lib/components/task_expansion_tile.dart +++ b/apps/tasks/lib/components/task_expansion_tile.dart @@ -1,5 +1,6 @@ import 'package:flutter/material.dart'; import 'package:helpwave_theme/constants.dart'; +import 'package:helpwave_theme/util.dart'; import 'package:helpwave_widget/bottom_sheets.dart'; import 'package:helpwave_widget/shapes.dart'; import 'package:provider/provider.dart'; @@ -29,13 +30,13 @@ class TaskExpansionTile extends StatelessWidget { @override Widget build(BuildContext context) { return Theme( - data: Theme.of(context).copyWith( + data: context.theme.copyWith( dividerColor: Colors.transparent, - listTileTheme: Theme.of(context).listTileTheme.copyWith(minLeadingWidth: 0, horizontalTitleGap: paddingSmall), + listTileTheme: context.theme.listTileTheme.copyWith(minLeadingWidth: 0, horizontalTitleGap: paddingSmall), ), child: ExpansionTile( - iconColor: Theme.of(context).colorScheme.primary.withOpacity(0.8), - collapsedIconColor: Theme.of(context).colorScheme.primary.withOpacity(0.8), + iconColor: context.theme.colorScheme.primary.withOpacity(0.8), + collapsedIconColor: context.theme.colorScheme.primary.withOpacity(0.8), textColor: color, collapsedTextColor: color, initiallyExpanded: true, diff --git a/apps/tasks/lib/components/user_bottom_sheet.dart b/apps/tasks/lib/components/user_bottom_sheet.dart index 74a7dfbd..f3f649e2 100644 --- a/apps/tasks/lib/components/user_bottom_sheet.dart +++ b/apps/tasks/lib/components/user_bottom_sheet.dart @@ -1,19 +1,20 @@ -import 'dart:math'; import 'package:flutter/material.dart'; import 'package:helpwave_localization/localization.dart'; import 'package:helpwave_service/user.dart'; import 'package:helpwave_theme/constants.dart'; +import 'package:helpwave_theme/util.dart'; import 'package:helpwave_widget/bottom_sheets.dart'; +import 'package:helpwave_widget/lists.dart'; import 'package:helpwave_widget/loading.dart'; import 'package:helpwave_widget/navigation.dart'; import 'package:provider/provider.dart'; import 'package:helpwave_service/tasks.dart'; import 'package:helpwave_service/auth.dart'; +import 'package:tasks/components/ward_select_bottom_sheet.dart'; import 'package:tasks/screens/login_screen.dart'; import 'package:helpwave_widget/widgets.dart'; import 'package:tasks/screens/settings_screen.dart'; - class UserBottomSheetPageBuilder with BottomSheetPageBuilder { @override BottomSheetHeader? headerBuilder(BuildContext context, NavigationController controller) { @@ -27,8 +28,6 @@ class UserBottomSheetPageBuilder with BottomSheetPageBuilder { @override Widget build(BuildContext context, NavigationController controller) { - final double width = MediaQuery.of(context).size.width; - return Flexible( child: Column( mainAxisAlignment: MainAxisAlignment.center, @@ -59,87 +58,48 @@ class UserBottomSheetPageBuilder with BottomSheetPageBuilder { currentWardController.currentWard?.organizationName ?? context.localization!.loading, style: TextStyle( fontSize: fontSizeSmall, - color: Theme.of(context).colorScheme.primary.withOpacity(0.6), + color: context.theme.hintColor, ), ), ), - Padding( - padding: const EdgeInsets.symmetric( - vertical: paddingBig, - ), - child: Consumer(builder: (context, currentWardController, __) { - return LoadingFutureBuilder( - loadingWidget: const SizedBox(), - data: - WardService().getWardOverviews(organizationId: currentWardController.currentWard!.organizationId), - thenWidgetBuilder: (BuildContext context, List data) { - double menuWidth = min(250, width * 0.7); - return PopupMenuButton( - initialValue: currentWardController.currentWard?.wardId, - shadowColor: Colors.transparent, - position: PopupMenuPosition.under, - itemBuilder: (context) { - return data - .map( - (WardOverview ward) => PopupMenuItem( - value: ward.id, - child: SizedBox( - child: Text(ward.name), - ), - ), - ) - .toList(); - }, - onSelected: (wardId) { - currentWardController.currentWard = CurrentWardInformation( - data.firstWhere((ward) => ward.id == wardId), - currentWardController.currentWard!.organization); - }, - // Material used to hide splash effects of the PopupMenu's Inkwell - child: Material( - child: Container( - width: menuWidth, - constraints: BoxConstraints(maxWidth: menuWidth, minWidth: menuWidth), - decoration: BoxDecoration( - borderRadius: BorderRadius.circular(borderRadiusMedium), - color: Theme.of(context).popupMenuTheme.color, - ), - child: Padding( - padding: const EdgeInsets.symmetric(horizontal: paddingMedium, vertical: paddingSmall), - child: Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: [ - Text( - context.localization!.ward, - style: TextStyle( - color: Theme.of(context).popupMenuTheme.textStyle?.color?.withOpacity(0.6), - ), - ), - Row( - mainAxisSize: MainAxisSize.min, - children: [ - Text( - currentWardController.currentWard?.wardName ?? context.localization!.none, - style: const TextStyle(fontWeight: FontWeight.bold), - ), - const SizedBox( - width: distanceTiny, - ), - const Icon( - Icons.expand_more_rounded, - size: iconSizeTiny, - ), - ], - ), - ], - ), - ), - ), - ), + const SizedBox(height: distanceBig), + RoundedListTiles(items: [ + ListTile( + leading: Icon( + Icons.house_rounded, + color: context.theme.colorScheme.primary, + ), + title: Text(context.localization!.currentWard, style: const TextStyle(fontWeight: FontWeight.bold)), + trailing: Row( + mainAxisSize: MainAxisSize.min, + mainAxisAlignment: MainAxisAlignment.end, + children: [ + Consumer(builder: (context, currentWardController, __) { + return Text( + currentWardController.currentWard!.wardName, + style: context.theme.textTheme.labelLarge, ); - }); - }), - ), + }), + const Icon(Icons.chevron_right_rounded), + ], + ), + onTap: () => { + context.pushModal( + context: context, + builder: (context) => WardSelectBottomSheet( + selectedWardId: CurrentWardService().currentWard!.wardId, + onChange: (WardMinimal ward) { + CurrentWardService().currentWard = CurrentWardInformation( + ward, + CurrentWardService().currentWard!.organization, + ); + Navigator.pop(context); + }, + ), + ) + }, + ), + ]), const Spacer(), Padding( padding: const EdgeInsets.only(bottom: distanceMedium), diff --git a/apps/tasks/lib/components/user_header.dart b/apps/tasks/lib/components/user_header.dart index 15a9ece6..1e942115 100644 --- a/apps/tasks/lib/components/user_header.dart +++ b/apps/tasks/lib/components/user_header.dart @@ -17,7 +17,12 @@ class UserHeader extends StatelessWidget implements PreferredSizeWidget { @override Widget build(BuildContext context) { return Container( - color: context.theme.appBarTheme.backgroundColor, + decoration: BoxDecoration( + color: context.theme.appBarTheme.backgroundColor, + boxShadow: [ + BoxShadow(spreadRadius: 0, blurRadius: 2, offset: const Offset(0, -1), color: Colors.black.withOpacity(0.1)), + ] + ), child: Consumer(builder: (context, userSession, __) { return SafeArea( child: ListTile( @@ -53,7 +58,7 @@ class UserHeader extends StatelessWidget implements PreferredSizeWidget { Text( "${currentWardController.currentWard?.organization.shortName ?? ""} - ", style: TextStyle( - color: Theme.of(context).colorScheme.onBackground.withOpacity(0.7), + color: context.theme.colorScheme.onBackground.withOpacity(0.7), fontSize: 14, ), ), diff --git a/apps/tasks/lib/components/ward_select_bottom_sheet.dart b/apps/tasks/lib/components/ward_select_bottom_sheet.dart new file mode 100644 index 00000000..e84d083d --- /dev/null +++ b/apps/tasks/lib/components/ward_select_bottom_sheet.dart @@ -0,0 +1,53 @@ +import 'package:flutter/material.dart'; +import 'package:helpwave_localization/localization.dart'; +import 'package:helpwave_service/auth.dart'; +import 'package:helpwave_service/tasks.dart'; +import 'package:helpwave_widget/bottom_sheets.dart'; +import 'package:helpwave_widget/loading.dart'; + +class WardSelectBottomSheet extends StatelessWidget { + /// The currently selected [WardMinimal] + /// + /// This is used to highlight the [WardMinimal] in the [List] + final String? selectedWardId; + + /// The [Organization] identifier for which all [WardMinimal]s are loaded + /// + /// If unspecified the organizationId of the [CurrentWardService] is taken + final String? organizationId; + + final void Function(WardMinimal ward) onChange; + + const WardSelectBottomSheet({super.key, this.selectedWardId, this.organizationId, required this.onChange}); + + @override + Widget build(BuildContext context) { + return BottomSheetBase( + onClosing: () {}, + header: BottomSheetHeader(titleText: context.localization!.selectWard), + mainAxisSize: MainAxisSize.min, + builder: (context) { + return LoadingFutureBuilder( + loadingWidget: const SizedBox(), + data: WardService().getWards(organizationId: organizationId), + thenWidgetBuilder: (context, wards) { + return Flexible( + child: ListView( + shrinkWrap: true, + children: wards + .map((ward) => ListTile( + onTap: () => onChange(ward), + title: Text( + ward.name, + style:TextStyle(decoration: ward.id == selectedWardId ? TextDecoration.underline : null), + ), + )) + .toList(), + ), + ); + }, + ); + }, + ); + } +} diff --git a/apps/tasks/lib/screens/landing_screen.dart b/apps/tasks/lib/screens/landing_screen.dart index 052622a1..b6d4a1ee 100644 --- a/apps/tasks/lib/screens/landing_screen.dart +++ b/apps/tasks/lib/screens/landing_screen.dart @@ -29,7 +29,7 @@ class LandingScreen extends StatelessWidget { .theme.colorScheme.onBackground))), child: Text( context.localization!.loginSlogan, - style: Theme.of(context).textTheme.labelLarge, + style: context.theme.textTheme.labelLarge, ), onPressed: () { userSessionController.login(); diff --git a/apps/tasks/lib/screens/main_screen.dart b/apps/tasks/lib/screens/main_screen.dart index d39b2564..c2ec10fb 100644 --- a/apps/tasks/lib/screens/main_screen.dart +++ b/apps/tasks/lib/screens/main_screen.dart @@ -5,6 +5,7 @@ import 'package:helpwave_service/auth.dart'; import 'package:helpwave_service/tasks.dart'; import 'package:helpwave_theme/constants.dart'; import 'package:helpwave_theme/theme.dart'; +import 'package:helpwave_theme/util.dart'; import 'package:helpwave_widget/bottom_sheets.dart'; import 'package:helpwave_widget/animation.dart'; import 'package:provider/provider.dart'; @@ -52,30 +53,19 @@ class _MainScreenState extends State { child: _TaskPatientFloatingActionButton(), ), bottomNavigationBar: NavigationBar( - indicatorColor: Theme.of(context).colorScheme.secondary, - backgroundColor: themeNotifier.getIsDarkNullSafe(context) ? Colors.white10 : Colors.white, + indicatorColor: context.theme.colorScheme.primary, + surfaceTintColor: Colors.transparent, + shadowColor: context.theme.colorScheme.shadow, destinations: [ NavigationDestination( - selectedIcon: Icon( - Icons.check_circle_outline, - color: Theme.of(context).colorScheme.onSecondary, - ), icon: const Icon(Icons.check_circle_outline), label: context.localization!.myTasks, ), NavigationDestination( - selectedIcon: Icon( - Icons.add_circle_outline, - color: Theme.of(context).colorScheme.onSecondary, - ), icon: const Icon(Icons.add_circle_outline), label: context.localization!.newTaskOrPatient, ), NavigationDestination( - selectedIcon: Icon( - Icons.person, - color: Theme.of(context).colorScheme.onSecondary, - ), icon: const Icon(Icons.person), label: context.localization!.patients, ), @@ -117,7 +107,7 @@ class _TaskPatientFloatingActionButton extends StatelessWidget { return Container( decoration: BoxDecoration( borderRadius: BorderRadius.circular(componentHeight), - color: Color.alphaBlend(Theme.of(context).colorScheme.secondary.withOpacity(0.7), Colors.black), + color: Color.alphaBlend(context.theme.colorScheme.primary.withOpacity(0.7), Colors.black), ), child: Padding( padding: const EdgeInsets.all(paddingSmall), @@ -128,8 +118,8 @@ class _TaskPatientFloatingActionButton extends StatelessWidget { ActionChip( labelPadding: EdgeInsets.zero, visualDensity: VisualDensity.compact, - backgroundColor: Theme.of(context).colorScheme.secondary, - labelStyle: TextStyle(color: Theme.of(context).colorScheme.onSecondary), + backgroundColor: context.theme.colorScheme.primary, + labelStyle: TextStyle(color: context.theme.colorScheme.onPrimary), side: BorderSide.none, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(chipHeight), // Adjust the radius as needed @@ -152,8 +142,8 @@ class _TaskPatientFloatingActionButton extends StatelessWidget { ActionChip( labelPadding: EdgeInsets.zero, visualDensity: VisualDensity.compact, - backgroundColor: Theme.of(context).colorScheme.secondary, - labelStyle: TextStyle(color: Theme.of(context).colorScheme.onSecondary), + backgroundColor: context.theme.colorScheme.primary, + labelStyle: TextStyle(color: context.theme.colorScheme.onPrimary), side: BorderSide.none, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(chipHeight), // Adjust the radius as needed diff --git a/apps/tasks/lib/screens/main_screen_subscreens/my_tasks_screen.dart b/apps/tasks/lib/screens/main_screen_subscreens/my_tasks_screen.dart index 54b2ca37..7db67b62 100644 --- a/apps/tasks/lib/screens/main_screen_subscreens/my_tasks_screen.dart +++ b/apps/tasks/lib/screens/main_screen_subscreens/my_tasks_screen.dart @@ -1,6 +1,7 @@ import 'package:flutter/material.dart'; import 'package:helpwave_service/tasks.dart'; import 'package:helpwave_theme/constants.dart'; +import 'package:helpwave_theme/util.dart'; import 'package:provider/provider.dart'; import 'package:helpwave_localization/localization.dart'; import 'package:tasks/components/task_expansion_tile.dart'; @@ -25,7 +26,7 @@ class _MyTasksScreenState extends State { state: tasksController.state, child: ListView(children: [ Theme( - data: Theme.of(context).copyWith( + data: context.theme.copyWith( dividerColor: Colors.transparent, listTileTheme: const ListTileThemeData(minLeadingWidth: 0, horizontalTitleGap: distanceSmall), ), diff --git a/apps/tasks/lib/screens/main_screen_subscreens/patient_screen.dart b/apps/tasks/lib/screens/main_screen_subscreens/patient_screen.dart index 77a4dd12..fdef6aa0 100644 --- a/apps/tasks/lib/screens/main_screen_subscreens/patient_screen.dart +++ b/apps/tasks/lib/screens/main_screen_subscreens/patient_screen.dart @@ -1,6 +1,7 @@ import 'package:flutter/material.dart'; import 'package:helpwave_localization/localization.dart'; import 'package:helpwave_theme/constants.dart'; +import 'package:helpwave_theme/util.dart'; import 'package:helpwave_widget/bottom_sheets.dart'; import 'package:helpwave_widget/loading.dart'; import 'package:provider/provider.dart'; @@ -40,7 +41,7 @@ class _PatientScreenState extends State { icon: Icon( Icons.search, size: iconSizeTiny, - color: Theme.of(context).searchBarTheme.textStyle!.resolve({MaterialState.selected})!.color, + color: context.theme.searchBarTheme.textStyle!.resolve({MaterialState.selected})!.color, ), ), ], @@ -84,7 +85,7 @@ class _PatientScreenState extends State { padding: const EdgeInsets.all(paddingTiny), child: Container( decoration: BoxDecoration( - color: Theme.of(context).colorScheme.secondary, + color: context.theme.colorScheme.primary, borderRadius: BorderRadius.circular(borderRadiusMedium), ), padding: const EdgeInsets.symmetric(horizontal: paddingMedium), diff --git a/apps/tasks/lib/screens/settings_screen.dart b/apps/tasks/lib/screens/settings_screen.dart index 02bc5588..e21ac3ae 100644 --- a/apps/tasks/lib/screens/settings_screen.dart +++ b/apps/tasks/lib/screens/settings_screen.dart @@ -2,9 +2,13 @@ import 'package:flutter/material.dart'; import 'package:helpwave_localization/localization.dart'; import 'package:helpwave_localization/localization_model.dart'; import 'package:helpwave_service/auth.dart'; +import 'package:helpwave_service/user.dart'; import 'package:helpwave_theme/constants.dart'; import 'package:helpwave_theme/theme.dart'; +import 'package:helpwave_theme/util.dart'; import 'package:helpwave_widget/bottom_sheets.dart'; +import 'package:helpwave_widget/lists.dart'; +import 'package:helpwave_widget/loading.dart'; import 'package:helpwave_widget/navigation.dart'; import 'package:provider/provider.dart'; import 'package:tasks/screens/login_screen.dart'; @@ -145,35 +149,133 @@ class SettingsScreen extends StatelessWidget { } } +class NavigationListTile extends StatelessWidget { + final IconData icon; + final Color? color; + final String title; + final void Function() onTap; + final String? trailingText; + + const NavigationListTile({ + super.key, + required this.icon, + this.color, + required this.title, + required this.onTap, + this.trailingText, + }); + + @override + Widget build(BuildContext context) { + return ListTile( + leading: Icon( + icon, + color: color ?? context.theme.colorScheme.primary, + ), + title: Text(title, style: TextStyle(fontWeight: FontWeight.bold, color: color)), + trailing: Row( + mainAxisSize: MainAxisSize.min, + mainAxisAlignment: MainAxisAlignment.end, + children: [ + trailingText != null + ? Text( + trailingText!, + style: context.theme.textTheme.labelLarge, + ) + : const SizedBox(), + Icon( + Icons.chevron_right_rounded, + color: context.theme.colorScheme.onBackground.withOpacity(0.7), + ), + ], + ), + ); + } +} + class SettingsBottomSheetPageBuilder with BottomSheetPageBuilder { + @override + BottomSheetHeader? headerBuilder(BuildContext context, NavigationController controller) { + return BottomSheetHeader( + titleText: context.localization!.settings, + ); + } + @override Widget build(BuildContext context, NavigationController controller) { + titleBuilder(String title) { + return Padding( + padding: const EdgeInsets.only(bottom: paddingSmall), + child: Text( + title, + style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold, fontFamily: "SpaceGrotesk"), + ), + ); + } + return Flexible( child: ListView( - children: ListTile.divideTiles( - context: context, - tiles: [ - ListTile( - leading: const Icon(Icons.brightness_medium), - title: Text(context.localization!.darkMode), - trailing: Consumer( - builder: (_, ThemeModel themeNotifier, __) { - return PopupMenuButton( - initialValue: themeNotifier.themeMode, - position: PopupMenuPosition.under, - itemBuilder: (context) => [ - PopupMenuItem(value: ThemeMode.dark, child: Text(context.localization!.darkMode)), - PopupMenuItem(value: ThemeMode.light, child: Text(context.localization!.lightMode)), - PopupMenuItem(value: ThemeMode.system, child: Text(context.localization!.system)), - ], - onSelected: (value) { - if (value == ThemeMode.system) { - themeNotifier.isDark = null; - } else { - themeNotifier.isDark = value == ThemeMode.dark; - } - }, - child: Material( + children: [ + titleBuilder(context.localization!.personalSettings), + RoundedListTiles( + items: [ + NavigationListTile( + icon: Icons.person, + title: context.localization!.personalData, + onTap: () {}, + ), + NavigationListTile( + icon: Icons.security_rounded, + title: context.localization!.passwordAndSecurity, + onTap: () {}, + ), + NavigationListTile( + icon: Icons.checklist_rounded, + title: context.localization!.myTaskTemplates, + onTap: () {}, + ), + ], + ), + const SizedBox(height: distanceMedium), + titleBuilder(context.localization!.myOrganizations), + LoadingFutureBuilder( + data: OrganizationService().getOrganizationsForUser(), + thenWidgetBuilder: (context, data) { + return RoundedListTiles( + items: data + .map((organization) => NavigationListTile( + icon: Icons.apartment_rounded, + title: organization.longName, + onTap: () {}, + )) + .toList(), + ); + }, + ), + const SizedBox(height: distanceMedium), + titleBuilder(context.localization!.appearance), + RoundedListTiles( + items: [ + ListTile( + leading: Icon(Icons.brightness_medium, color: context.theme.colorScheme.primary), + title: Text(context.localization!.darkMode, style: const TextStyle(fontWeight: FontWeight.bold)), + trailing: Consumer( + builder: (_, ThemeModel themeNotifier, __) { + return PopupMenuButton( + initialValue: themeNotifier.themeMode, + position: PopupMenuPosition.under, + itemBuilder: (context) => [ + PopupMenuItem(value: ThemeMode.dark, child: Text(context.localization!.darkMode)), + PopupMenuItem(value: ThemeMode.light, child: Text(context.localization!.lightMode)), + PopupMenuItem(value: ThemeMode.system, child: Text(context.localization!.system)), + ], + onSelected: (value) { + if (value == ThemeMode.system) { + themeNotifier.isDark = null; + } else { + themeNotifier.isDark = value == ThemeMode.dark; + } + }, child: Row( mainAxisSize: MainAxisSize.min, children: [ @@ -196,31 +298,32 @@ class SettingsBottomSheetPageBuilder with BottomSheetPageBuilder { ), ], ), - ), - ); - }, + ); + }, + ), ), - ), - Consumer( - builder: (context, languageModel, child) { - return ListTile( - leading: const Icon(Icons.language), - title: Text(context.localization!.language), - trailing: PopupMenuButton( - position: PopupMenuPosition.under, - initialValue: languageModel.local, - onSelected: (value) { - languageModel.setLanguage(value); - }, - itemBuilder: (BuildContext context) => getSupportedLocalsWithName() - .map((local) => PopupMenuItem( - value: local.local, - child: Text( - local.name, - ), - )) - .toList(), - child: Material( + Consumer( + builder: (context, languageModel, child) { + return ListTile( + leading: Icon(Icons.language, color: context.theme.colorScheme.primary), + title: Text( + context.localization!.language, + style: const TextStyle(fontWeight: FontWeight.bold), + ), + trailing: PopupMenuButton( + position: PopupMenuPosition.under, + initialValue: languageModel.local, + onSelected: (value) { + languageModel.setLanguage(value); + }, + itemBuilder: (BuildContext context) => getSupportedLocalsWithName() + .map((local) => PopupMenuItem( + value: local.local, + child: Text( + local.name, + ), + )) + .toList(), child: Row( mainAxisSize: MainAxisSize.min, children: [ @@ -239,33 +342,40 @@ class SettingsBottomSheetPageBuilder with BottomSheetPageBuilder { ], ), ), - ), - ); - }, - ), - ListTile( - leading: const Icon(Icons.info_outline), - title: Text(context.localization!.licenses), - trailing: const Icon(Icons.arrow_forward), - onTap: () => {showLicensePage(context: context)}, - ), - Consumer( - builder: (context, currentWardService, _) { - return ListTile( - leading: const Icon(Icons.logout), - title: Text(context.localization!.logout), - onTap: () { - UserSessionService().logout(); - currentWardService.clear(); - Navigator.of(context).pushReplacement( - MaterialPageRoute(builder: (_) => const LoginScreen()), - ); - }, - ); - }, - ), - ], - ).toList(), + ); + }, + ), + ], + ), + const SizedBox(height: distanceMedium), + titleBuilder(context.localization!.other), + RoundedListTiles( + items: [ + NavigationListTile( + icon: Icons.info_outline, + title: context.localization!.licenses, + onTap: () => {showLicensePage(context: context)}, + ), + Consumer( + builder: (context, currentWardService, _) { + return NavigationListTile( + icon: Icons.logout, + title: context.localization!.logout, + color: Colors.red.withOpacity(0.7), // TODO get this from theme + onTap: () { + // TODO add confirm dialog + UserSessionService().logout(); + currentWardService.clear(); + Navigator.of(context).pushReplacement( + MaterialPageRoute(builder: (_) => const LoginScreen()), + ); + }, + ); + }, + ), + ], + ), + ], ), ); } diff --git a/apps/tasks/pubspec.yaml b/apps/tasks/pubspec.yaml index 032d9e18..bc5ede94 100644 --- a/apps/tasks/pubspec.yaml +++ b/apps/tasks/pubspec.yaml @@ -69,6 +69,10 @@ flutter: uses-material-design: true assets: - assets/ + fonts: + - family: SpaceGrotesk + fonts: + - asset: packages/helpwave_theme/fonts/Space_Grotesk/SpaceGrotesk-VariableFont_wght.ttf flutter_native_splash: # see https://pub.dev/packages/flutter_native_splash diff --git a/packages/helpwave_localization/lib/l10n/app_de.arb b/packages/helpwave_localization/lib/l10n/app_de.arb index 18a2eeef..fc852afb 100644 --- a/packages/helpwave_localization/lib/l10n/app_de.arb +++ b/packages/helpwave_localization/lib/l10n/app_de.arb @@ -169,5 +169,11 @@ "lightMode": "Hell", "system": "System", "newTaskOrPatient": "Neu", - "remove": "Entfernen" + "remove": "Entfernen", + "appearance": "Aussehen", + "personalSettings": "Persönliche Einstellungen", + "personalData": "Persönliche Daten", + "passwordAndSecurity": "Passwort & Sicherheit", + "other": "Weiteres", + "myTaskTemplates": "Meine Task Templates" } diff --git a/packages/helpwave_localization/lib/l10n/app_en.arb b/packages/helpwave_localization/lib/l10n/app_en.arb index 0321789b..4d370c2c 100644 --- a/packages/helpwave_localization/lib/l10n/app_en.arb +++ b/packages/helpwave_localization/lib/l10n/app_en.arb @@ -169,5 +169,11 @@ "lightMode": "Light", "system": "System", "newTaskOrPatient": "New", - "remove": "Remove" + "remove": "Remove", + "appearance": "Appearance", + "personalSettings": "Personal Settings", + "personalData": "Personal Data", + "passwordAndSecurity": "Password & Security", + "other": "Other", + "myTaskTemplates": "My Task Templates" } diff --git a/packages/helpwave_service/lib/src/api/tasks/services/ward_service.dart b/packages/helpwave_service/lib/src/api/tasks/services/ward_service.dart index 3d28ca97..5dcf8e79 100644 --- a/packages/helpwave_service/lib/src/api/tasks/services/ward_service.dart +++ b/packages/helpwave_service/lib/src/api/tasks/services/ward_service.dart @@ -45,5 +45,20 @@ class WardService { .toList(); } + Future> getWards({String? organizationId}) async { + GetWardsRequest request = GetWardsRequest(); + GetWardsResponse response = await wardService.getWards( + request, + options: CallOptions(metadata: TasksAPIServiceClients().getMetaData(organizationId: organizationId)), + ); + + return response.wards + .map((ward) => WardMinimal( + id: ward.id, + name: ward.name, + )) + .toList(); + } + // TODO ward requests } diff --git a/packages/helpwave_theme/assets/fonts/Space_Grotesk/OFL.txt b/packages/helpwave_theme/lib/fonts/Space_Grotesk/OFL.txt similarity index 100% rename from packages/helpwave_theme/assets/fonts/Space_Grotesk/OFL.txt rename to packages/helpwave_theme/lib/fonts/Space_Grotesk/OFL.txt diff --git a/packages/helpwave_theme/assets/fonts/Space_Grotesk/README.txt b/packages/helpwave_theme/lib/fonts/Space_Grotesk/README.txt similarity index 100% rename from packages/helpwave_theme/assets/fonts/Space_Grotesk/README.txt rename to packages/helpwave_theme/lib/fonts/Space_Grotesk/README.txt diff --git a/packages/helpwave_theme/assets/fonts/Space_Grotesk/SpaceGrotesk-VariableFont_wght.ttf b/packages/helpwave_theme/lib/fonts/Space_Grotesk/SpaceGrotesk-VariableFont_wght.ttf similarity index 100% rename from packages/helpwave_theme/assets/fonts/Space_Grotesk/SpaceGrotesk-VariableFont_wght.ttf rename to packages/helpwave_theme/lib/fonts/Space_Grotesk/SpaceGrotesk-VariableFont_wght.ttf diff --git a/packages/helpwave_theme/assets/fonts/Space_Grotesk/static/SpaceGrotesk-Bold.ttf b/packages/helpwave_theme/lib/fonts/Space_Grotesk/static/SpaceGrotesk-Bold.ttf similarity index 100% rename from packages/helpwave_theme/assets/fonts/Space_Grotesk/static/SpaceGrotesk-Bold.ttf rename to packages/helpwave_theme/lib/fonts/Space_Grotesk/static/SpaceGrotesk-Bold.ttf diff --git a/packages/helpwave_theme/assets/fonts/Space_Grotesk/static/SpaceGrotesk-Light.ttf b/packages/helpwave_theme/lib/fonts/Space_Grotesk/static/SpaceGrotesk-Light.ttf similarity index 100% rename from packages/helpwave_theme/assets/fonts/Space_Grotesk/static/SpaceGrotesk-Light.ttf rename to packages/helpwave_theme/lib/fonts/Space_Grotesk/static/SpaceGrotesk-Light.ttf diff --git a/packages/helpwave_theme/assets/fonts/Space_Grotesk/static/SpaceGrotesk-Medium.ttf b/packages/helpwave_theme/lib/fonts/Space_Grotesk/static/SpaceGrotesk-Medium.ttf similarity index 100% rename from packages/helpwave_theme/assets/fonts/Space_Grotesk/static/SpaceGrotesk-Medium.ttf rename to packages/helpwave_theme/lib/fonts/Space_Grotesk/static/SpaceGrotesk-Medium.ttf diff --git a/packages/helpwave_theme/assets/fonts/Space_Grotesk/static/SpaceGrotesk-Regular.ttf b/packages/helpwave_theme/lib/fonts/Space_Grotesk/static/SpaceGrotesk-Regular.ttf similarity index 100% rename from packages/helpwave_theme/assets/fonts/Space_Grotesk/static/SpaceGrotesk-Regular.ttf rename to packages/helpwave_theme/lib/fonts/Space_Grotesk/static/SpaceGrotesk-Regular.ttf diff --git a/packages/helpwave_theme/assets/fonts/Space_Grotesk/static/SpaceGrotesk-SemiBold.ttf b/packages/helpwave_theme/lib/fonts/Space_Grotesk/static/SpaceGrotesk-SemiBold.ttf similarity index 100% rename from packages/helpwave_theme/assets/fonts/Space_Grotesk/static/SpaceGrotesk-SemiBold.ttf rename to packages/helpwave_theme/lib/fonts/Space_Grotesk/static/SpaceGrotesk-SemiBold.ttf diff --git a/packages/helpwave_theme/lib/src/constants.dart b/packages/helpwave_theme/lib/src/constants.dart index 291df3aa..214faf3b 100644 --- a/packages/helpwave_theme/lib/src/constants.dart +++ b/packages/helpwave_theme/lib/src/constants.dart @@ -1,4 +1,5 @@ import 'package:flutter/material.dart'; +import 'package:helpwave_theme/src/util/context_extension.dart'; /// Button attributes and @@ -134,4 +135,4 @@ const AppBarTheme sharedAppBarTheme = AppBarTheme(centerTitle: true); /// TextStyles TextStyle editableValueTextStyle(BuildContext context) => - TextStyle(color: Theme.of(context).colorScheme.secondary, fontSize: 16, fontWeight: FontWeight.bold); + TextStyle(color: context.theme.colorScheme.primary, fontSize: 16, fontWeight: FontWeight.bold); diff --git a/packages/helpwave_theme/lib/src/theme/dark_theme.dart b/packages/helpwave_theme/lib/src/theme/dark_theme.dart index 8953e56f..319d15c6 100644 --- a/packages/helpwave_theme/lib/src/theme/dark_theme.dart +++ b/packages/helpwave_theme/lib/src/theme/dark_theme.dart @@ -2,32 +2,31 @@ import 'package:flutter/material.dart'; import 'package:helpwave_theme/src/theme/theme.dart'; import '../constants.dart'; -const primaryColor = Color.fromARGB(255, 255, 255, 255); -const onPrimaryColor = Color.fromARGB(255, 0, 0, 0); -const inversePrimaryColor = Color.fromARGB(255, 30, 30, 30); -const secondaryColor = Color.fromARGB(255, 150, 129, 205); -const onSecondaryColor = Color.fromARGB(255, 255, 255, 255); -const tertiary = Color.fromARGB(255, 180, 180, 180); -const onTertiary = Color.fromARGB(255, 0, 0, 0); +const primaryColor = Color.fromARGB(255, 105, 75, 180); +const onPrimaryColor = Colors.white; +const inversePrimaryColor = Color.fromARGB(255, 150, 130, 200); +const secondaryColor = Color.fromARGB(255, 75, 160, 240); +const onSecondaryColor = Colors.white; +const tertiary = Color.fromARGB(255, 90, 90, 90); +const onTertiary = Colors.white; -const backgroundColor = Color.fromARGB(255, 27, 27, 27); +const backgroundColor = Color.fromARGB(255, 20, 20, 20); const onBackgroundColor = Color.fromARGB(255, 255, 255, 255); -const surface = Color.fromARGB(255, 50, 50, 50); -const onSurface = Color.fromARGB(255, 255, 255, 255); +const surface = Color.fromARGB(255, 40, 40, 40); +const onSurface = Colors.white; const surfaceVariant = Color.fromARGB(255, 80, 80, 80); -const onSurfaceVariant = Color.fromARGB(255, 255, 255, 255); +const onSurfaceVariant = Colors.white; const inverseSurface = Color.fromARGB(255, 180, 180, 180); -const onInverseSurface = Color.fromARGB(255, 0, 0, 0); +const onInverseSurface = Colors.black; -const primaryContainer = Color.fromARGB(255, 180, 180, 180); -const onPrimaryContainer = Color.fromARGB(255, 0, 0, 0); -const secondaryContainer = Color.fromARGB(255, 140, 140, 140); -const onSecondaryContainer = Color.fromARGB(255, 0, 0, 0); -const tertiaryContainer = Color.fromARGB(255, 80, 80, 80); -const onTertiaryContainer = Color.fromARGB(255, 255, 255, 255); +const primaryContainer = Color.fromARGB(255, 105, 75, 180); +const onPrimaryContainer = Colors.white; +const secondaryContainer = Color.fromARGB(255, 75, 160, 240); +const onSecondaryContainer = Colors.white; +const tertiaryContainer = Color.fromARGB(255, 0, 0, 0); +const onTertiaryContainer = Colors.white; -const surfaceTint = Colors.transparent; const shadow = Color.fromARGB(255, 60, 60, 60); const outline = Color.fromARGB(255, 255, 255, 255); const disabledColor = Color.fromARGB(255, 100, 100, 100); @@ -71,7 +70,6 @@ ThemeData darkTheme = makeTheme( onErrorContainer: onErrorColor, // other - surfaceTint: surfaceTint, shadow: shadow, outline: outline, disabledColor: disabledColor, @@ -82,9 +80,12 @@ ThemeData darkTheme = makeTheme( // additional brightness: Brightness.dark, - // flutter themes - appBarTheme: sharedAppBarTheme.copyWith( - backgroundColor: const Color.fromARGB(255, 15, 15, 15), - foregroundColor: Colors.white, - ) + // flutter themes + appBarTheme: sharedAppBarTheme.copyWith( + backgroundColor: const Color.fromARGB(255, 15, 15, 15), + foregroundColor: Colors.white, + ), + + // text + primaryTextColor: Colors.white, ); diff --git a/packages/helpwave_theme/lib/src/theme/light_theme.dart b/packages/helpwave_theme/lib/src/theme/light_theme.dart index 881e600d..50eba584 100644 --- a/packages/helpwave_theme/lib/src/theme/light_theme.dart +++ b/packages/helpwave_theme/lib/src/theme/light_theme.dart @@ -2,32 +2,31 @@ import 'package:flutter/material.dart'; import 'package:helpwave_theme/src/theme/theme.dart'; import '../constants.dart'; -const primaryColor = Color.fromARGB(255, 0, 0, 0); -const onPrimaryColor = Color.fromARGB(255, 255, 255, 255); -const inversePrimaryColor = Color.fromARGB(255, 210, 210, 210); -const secondaryColor = Color.fromARGB(255, 105, 75, 180); -const onSecondaryColor = Color.fromARGB(255, 255, 255, 255); -const tertiary = Color.fromARGB(255, 180, 180, 180); -const onTertiary = Color.fromARGB(255, 0, 0, 0); +const primaryColor = Color.fromARGB(255, 105, 75, 180); +const onPrimaryColor = Colors.white; +const inversePrimaryColor = Color.fromARGB(255, 150, 130, 200); +const secondaryColor = Color.fromARGB(255, 75, 160, 240); +const onSecondaryColor = Colors.white; +const tertiary = Color.fromARGB(255, 90, 90, 90); +const onTertiary = Colors.white; -const backgroundColor = Color.fromARGB(255, 242, 242, 242); -const onBackgroundColor = Color.fromARGB(255, 0, 0, 0); +const backgroundColor = Color.fromARGB(255, 237, 237, 237); +const onBackgroundColor = Colors.black; -const surface = Color.fromARGB(255, 220, 220, 220); -const onSurface = Color.fromARGB(255, 0, 0, 0); +const surface = Color.fromARGB(255, 255, 255, 255); +const onSurface = Colors.black; const surfaceVariant = Color.fromARGB(255, 170, 170, 170); -const onSurfaceVariant = Color.fromARGB(255, 0, 0, 0); -const inverseSurface = Color.fromARGB(255, 120, 120, 120); -const onInverseSurface = Color.fromARGB(255, 255, 255, 255); +const onSurfaceVariant = Colors.black; +const inverseSurface = Color.fromARGB(255, 90, 90, 90); +const onInverseSurface = Colors.white; -const primaryContainer = Color.fromARGB(255, 200, 200, 200); -const onPrimaryContainer = Color.fromARGB(255, 0, 0, 0); -const secondaryContainer = Color.fromARGB(255, 160, 160, 160); -const onSecondaryContainer = Color.fromARGB(255, 0, 0, 0); -const tertiaryContainer = Color.fromARGB(255, 120, 120, 120); -const onTertiaryContainer = Color.fromARGB(255, 255, 255, 255); +const primaryContainer = Color.fromARGB(255, 105, 75, 180); +const onPrimaryContainer = Colors.white; +const secondaryContainer = Color.fromARGB(255, 75, 160, 240); +const onSecondaryContainer = Colors.white; +const tertiaryContainer = Color.fromARGB(255, 255, 255, 255); +const onTertiaryContainer = Color.fromARGB(255, 0, 0, 0); -const surfaceTint = Colors.transparent; const shadow = Color.fromARGB(255, 60, 60, 60); const outline = Color.fromARGB(255, 30, 30, 30); const disabledColor = Color.fromARGB(255, 100, 100, 100); @@ -71,7 +70,6 @@ ThemeData lightTheme = makeTheme( onErrorContainer: onErrorColor, // other - surfaceTint: surfaceTint, shadow: shadow, outline: outline, disabledColor: disabledColor, @@ -86,5 +84,8 @@ ThemeData lightTheme = makeTheme( appBarTheme: sharedAppBarTheme.copyWith( backgroundColor: Colors.white, foregroundColor: Colors.black, - ) + ), + + // text + primaryTextColor: Colors.black, ); diff --git a/packages/helpwave_theme/lib/src/theme/theme.dart b/packages/helpwave_theme/lib/src/theme/theme.dart index 6c559af3..3454388d 100644 --- a/packages/helpwave_theme/lib/src/theme/theme.dart +++ b/packages/helpwave_theme/lib/src/theme/theme.dart @@ -38,7 +38,6 @@ ThemeData makeTheme({ required Color onErrorContainer, // other - required Color surfaceTint, required Color shadow, required Color outline, required Color disabledColor, @@ -49,15 +48,18 @@ ThemeData makeTheme({ // additional parameters required Brightness brightness, - // Flutter Themes + // flutter themes AppBarTheme appBarTheme = sharedAppBarTheme, + + // text + required Color primaryTextColor }) { return ThemeData( useMaterial3: true, disabledColor: disabledColor, - textSelectionTheme: const TextSelectionThemeData( - cursorColor: Colors.blue, - selectionHandleColor: Colors.blueAccent, + textSelectionTheme: TextSelectionThemeData( + cursorColor: secondaryColor, + selectionHandleColor: secondaryColor, ), scaffoldBackgroundColor: backgroundColor, bottomSheetTheme: BottomSheetThemeData( @@ -102,20 +104,20 @@ ThemeData makeTheme({ }), ), bottomNavigationBarTheme: BottomNavigationBarThemeData( - backgroundColor: backgroundColor, + backgroundColor: surface, ), listTileTheme: ListTileThemeData( - iconColor: focusedColor, + iconColor: primaryTextColor, ), appBarTheme: appBarTheme, elevatedButtonTheme: ElevatedButtonThemeData( style: buttonStyleSmall.copyWith( backgroundColor: resolveByStates( - defaultValue: secondaryColor, + defaultValue: primaryColor, disabled: disabledColor, ), foregroundColor: resolveByStates( - defaultValue: onSecondaryColor, + defaultValue: onPrimaryColor, disabled: onDisabledColor, ), ), @@ -139,24 +141,24 @@ ThemeData makeTheme({ textButtonTheme: TextButtonThemeData( style: buttonStyleSmall.copyWith( backgroundColor: resolveByStates( - defaultValue: secondaryColor, + defaultValue: primaryColor, disabled: disabledColor, ), foregroundColor: resolveByStates( - defaultValue: onSecondaryColor, + defaultValue: onPrimaryColor, disabled: onDisabledColor, ), ), ), iconTheme: IconThemeData( size: iconSizeSmall, - color: primaryColor, + color: primaryTextColor, ), chipTheme: chipTheme.copyWith( - selectedColor: secondaryColor, - secondaryLabelStyle: TextStyle(color: onSecondaryColor), + selectedColor: primaryColor, + secondaryLabelStyle: TextStyle(color: onPrimaryColor), // The TextStyle for selection - labelStyle: TextStyle(color: primaryColor), + labelStyle: TextStyle(color: primaryTextColor), ), cardTheme: CardTheme( elevation: 0, @@ -173,9 +175,11 @@ ThemeData makeTheme({ ), searchBarTheme: searchBarTheme, expansionTileTheme: ExpansionTileThemeData( - textColor: primaryColor, - iconColor: primaryColor, + textColor: primaryTextColor, + iconColor: primaryTextColor, ), + dividerTheme: DividerThemeData(color: primaryTextColor.withOpacity(0.4), space: 1, thickness: 1), + hintColor: primaryTextColor.withOpacity(0.7), colorScheme: ColorScheme( // General brightness: brightness, @@ -194,7 +198,6 @@ ThemeData makeTheme({ error: errorColor, onError: onErrorColor, // Surface - surfaceTint: surfaceTint, surface: surface, onSurface: onSurface, surfaceVariant: surfaceVariant, diff --git a/packages/helpwave_theme/lib/src/theme_model.dart b/packages/helpwave_theme/lib/src/theme_model.dart index 7360b8df..92363861 100644 --- a/packages/helpwave_theme/lib/src/theme_model.dart +++ b/packages/helpwave_theme/lib/src/theme_model.dart @@ -1,5 +1,6 @@ import 'package:flutter/material.dart'; import 'package:helpwave_theme/src/theme_preferences.dart'; +import 'package:helpwave_theme/src/util/context_extension.dart'; /// Model for the Color Theme /// @@ -40,7 +41,7 @@ class ThemeModel extends ChangeNotifier { /// Uses the [BuildContext] to determine the [Theme]'s brightness, which /// corresponds to the System setting bool getIsDarkNullSafe(BuildContext context) => - isDark ?? Theme.of(context).brightness == Brightness.dark; + isDark ?? context.theme.brightness == Brightness.dark; /// Load the preferences with the [ThemePreferences] getPreferences() async { diff --git a/packages/helpwave_theme/lib/src/util/material_state_color_resolver.dart b/packages/helpwave_theme/lib/src/util/material_state_color_resolver.dart index af44f6c2..f866a4d4 100644 --- a/packages/helpwave_theme/lib/src/util/material_state_color_resolver.dart +++ b/packages/helpwave_theme/lib/src/util/material_state_color_resolver.dart @@ -1,4 +1,5 @@ import 'package:flutter/material.dart'; +import 'package:helpwave_theme/src/util/context_extension.dart'; import 'package:helpwave_util/material_state.dart'; /// Resolves the background [Color] based on the [MaterialState] and the [ThemeData] @@ -14,7 +15,7 @@ MaterialStateProperty resolveByStatesAndContextBackground({ Color? hovered, Color? scrolledUnder, }) { - ThemeData theme = Theme.of(context); + ThemeData theme = context.theme; ColorScheme colorScheme = theme.colorScheme; return resolveByStates( defaultValue: defaultValue ?? colorScheme.primary, @@ -42,7 +43,7 @@ MaterialStateProperty resolveByStatesAndContextForeground({ Color? hovered, Color? scrolledUnder, }) { - ThemeData theme = Theme.of(context); + ThemeData theme = context.theme; ColorScheme colorScheme = theme.colorScheme; return resolveByStates( defaultValue: defaultValue ?? colorScheme.onPrimary, diff --git a/packages/helpwave_theme/pubspec.yaml b/packages/helpwave_theme/pubspec.yaml index 8f0e6bff..fdb63398 100644 --- a/packages/helpwave_theme/pubspec.yaml +++ b/packages/helpwave_theme/pubspec.yaml @@ -25,4 +25,4 @@ flutter: fonts: - family: SpaceGrotesk fonts: - - asset: assets/fonts/Space_Grotesk/SpaceGrotesk-VariableFont_wght.ttf + - asset: lib/fonts/Space_Grotesk/SpaceGrotesk-VariableFont_wght.ttf diff --git a/packages/helpwave_widget/lib/lists.dart b/packages/helpwave_widget/lib/lists.dart index 1a309ca1..6e351e70 100644 --- a/packages/helpwave_widget/lib/lists.dart +++ b/packages/helpwave_widget/lib/lists.dart @@ -1 +1 @@ -export 'package:helpwave_widget/src/lists/add_list.dart'; +export 'package:helpwave_widget/src/lists/index.dart'; diff --git a/packages/helpwave_widget/lib/src/bottom_sheets/bottom_sheet_base.dart b/packages/helpwave_widget/lib/src/bottom_sheets/bottom_sheet_base.dart index 451e5735..0e578d9a 100644 --- a/packages/helpwave_widget/lib/src/bottom_sheets/bottom_sheet_base.dart +++ b/packages/helpwave_widget/lib/src/bottom_sheets/bottom_sheet_base.dart @@ -1,5 +1,6 @@ import 'package:flutter/material.dart'; import 'package:helpwave_theme/constants.dart'; +import 'package:helpwave_theme/util.dart'; extension PushModalContextExtension on BuildContext { Future pushModal({ @@ -197,7 +198,7 @@ class BottomSheetHeader extends StatelessWidget { height: 5, width: 30, decoration: BoxDecoration( - color: Theme.of(context).colorScheme.onBackground.withOpacity(0.8), + color: context.theme.colorScheme.onBackground.withOpacity(0.8), borderRadius: BorderRadius.circular(5), ), ), diff --git a/packages/helpwave_widget/lib/src/content_selection/list_entry.dart b/packages/helpwave_widget/lib/src/content_selection/list_entry.dart index 60419f4f..4a6eb2e2 100644 --- a/packages/helpwave_widget/lib/src/content_selection/list_entry.dart +++ b/packages/helpwave_widget/lib/src/content_selection/list_entry.dart @@ -1,5 +1,6 @@ import 'package:flutter/material.dart'; import 'package:helpwave_theme/constants.dart'; +import 'package:helpwave_theme/util.dart'; import 'package:helpwave_widget/src/content_selection/content_selector.dart'; /// The ListEntry used by [ContentSelector] @@ -65,7 +66,7 @@ class ListEntry extends StatelessWidget { Expanded( child: Text( "- $name", - style: Theme.of(context).textTheme.bodyLarge, + style: context.theme.textTheme.bodyLarge, ), ), Row( diff --git a/packages/helpwave_widget/lib/src/content_selection/list_search.dart b/packages/helpwave_widget/lib/src/content_selection/list_search.dart index e57968bc..1961d444 100644 --- a/packages/helpwave_widget/lib/src/content_selection/list_search.dart +++ b/packages/helpwave_widget/lib/src/content_selection/list_search.dart @@ -1,6 +1,7 @@ import 'package:flutter/material.dart'; import 'package:helpwave_localization/localization.dart'; import 'package:helpwave_theme/constants.dart'; +import 'package:helpwave_theme/util.dart'; /// A customizable Search within a List /// @@ -203,7 +204,7 @@ class _ListSearchState extends State> { widget.elementNotFoundText != null ? widget.elementNotFoundText!(_searchController.text) : "${context.localization!.noItem} ${_searchController.text} ${context.localization!.found}", - style: Theme.of(context).textTheme.titleLarge, + style: context.theme.textTheme.titleLarge, ), const SizedBox(height: distanceDefault), widget.allowSelectAnyway @@ -220,7 +221,7 @@ class _ListSearchState extends State> { children = [ Icon( Icons.error_outline, - color: Theme.of(context).colorScheme.error, + color: context.theme.colorScheme.error, size: iconSizeBig, ), const SizedBox(height: distanceBig), diff --git a/packages/helpwave_widget/lib/src/lists/add_list.dart b/packages/helpwave_widget/lib/src/lists/add_list.dart index ea2bbf75..59251908 100644 --- a/packages/helpwave_widget/lib/src/lists/add_list.dart +++ b/packages/helpwave_widget/lib/src/lists/add_list.dart @@ -1,5 +1,6 @@ import 'package:flutter/material.dart'; import 'package:helpwave_theme/constants.dart'; +import 'package:helpwave_theme/util.dart'; import 'package:helpwave_widget/shapes.dart'; /// The default add icon for the [AddList] @@ -12,7 +13,7 @@ class _DefaultAddButton extends StatelessWidget { Widget build(BuildContext context) { const double subtaskAddIconSize = 21; return Circle( - color: Theme.of(context).colorScheme.secondary, + color: context.theme.colorScheme.primary, diameter: subtaskAddIconSize, child: IconButton( padding: EdgeInsets.zero, @@ -20,7 +21,7 @@ class _DefaultAddButton extends StatelessWidget { onPressed: onClick, icon: Icon( Icons.add_rounded, - color: Theme.of(context).colorScheme.onSecondary, + color: context.theme.colorScheme.onPrimary, ), ), ); diff --git a/packages/helpwave_widget/lib/src/lists/index.dart b/packages/helpwave_widget/lib/src/lists/index.dart new file mode 100644 index 00000000..d1f7fa13 --- /dev/null +++ b/packages/helpwave_widget/lib/src/lists/index.dart @@ -0,0 +1,2 @@ +export 'add_list.dart'; +export 'rounded_list_tiles.dart'; diff --git a/packages/helpwave_widget/lib/src/lists/rounded_list_tiles.dart b/packages/helpwave_widget/lib/src/lists/rounded_list_tiles.dart new file mode 100644 index 00000000..a87c0284 --- /dev/null +++ b/packages/helpwave_widget/lib/src/lists/rounded_list_tiles.dart @@ -0,0 +1,56 @@ +import 'package:flutter/material.dart'; +import 'package:helpwave_theme/constants.dart'; +import 'package:helpwave_theme/util.dart'; + +class RoundedListTiles extends StatelessWidget { + final List items; + + const RoundedListTiles({super.key, required this.items}); + + @override + Widget build(BuildContext context) { + const double borderRadius = borderRadiusMedium; + + return Container( + decoration: BoxDecoration( + color: context.theme.colorScheme.surface, + borderRadius: BorderRadius.circular(borderRadius), + boxShadow: [ + BoxShadow( + color: Colors.black.withOpacity(0.1), + blurRadius: 4, + spreadRadius: 1, + ) + ], + ), + child: Column( + mainAxisSize: MainAxisSize.min, + children: List.generate(items.length * 2 - 1, (index) { + if(index.isOdd){ + return const Divider(); + } + Widget item = items[index ~/ 2]; + if (index == 0 && items.length == 1) { + return ClipRRect( + borderRadius: BorderRadius.circular(borderRadius), + child: item, + ); + } + if (index == 0) { + return ClipRRect( + borderRadius: const BorderRadius.vertical(top: Radius.circular(borderRadius)), + child: item, + ); + } + if (index == items.length - 1) { + return ClipRRect( + borderRadius: const BorderRadius.vertical(bottom: Radius.circular(borderRadius)), + child: item, + ); + } + return item; + }), + ), + ); + } +} diff --git a/packages/helpwave_widget/lib/src/loading/loading_spinner.dart b/packages/helpwave_widget/lib/src/loading/loading_spinner.dart index b4e91925..6b6f05e3 100644 --- a/packages/helpwave_widget/lib/src/loading/loading_spinner.dart +++ b/packages/helpwave_widget/lib/src/loading/loading_spinner.dart @@ -1,6 +1,7 @@ import 'package:flutter/material.dart'; import 'package:helpwave_localization/localization.dart'; import 'package:helpwave_theme/constants.dart'; +import 'package:helpwave_theme/util.dart'; /// The Spinner to show when Loading data class LoadingSpinner extends StatelessWidget { @@ -36,7 +37,7 @@ class LoadingSpinner extends StatelessWidget { child: CircularProgressIndicator( strokeWidth: width, semanticsLabel: text ?? context.localization!.loading, - color: color ?? Theme.of(context).colorScheme.secondary, + color: color ?? context.theme.colorScheme.primary, ), ), const SizedBox(height: distanceBig), diff --git a/packages/helpwave_widget/lib/src/text_input/clickable_text_edit.dart b/packages/helpwave_widget/lib/src/text_input/clickable_text_edit.dart index 78fe47db..c3742ab7 100644 --- a/packages/helpwave_widget/lib/src/text_input/clickable_text_edit.dart +++ b/packages/helpwave_widget/lib/src/text_input/clickable_text_edit.dart @@ -1,5 +1,6 @@ import 'package:flutter/material.dart'; import 'package:helpwave_theme/constants.dart'; +import 'package:helpwave_theme/util.dart'; import 'package:helpwave_widget/src/text_input/text_form_field_with_timer.dart'; /// A Widget that is a normal [TextFormField], but has no border @@ -21,7 +22,7 @@ class ClickableTextEdit extends StatefulWidget { /// The default uses: /// /// ```dart - /// color: Theme.of(context).colorScheme.secondary, + /// color: context.theme.colorScheme.primary, /// fontSize: 20, /// fontWeight: FontWeight.w700 /// ``` @@ -75,10 +76,14 @@ class _ClickableTextEditState extends State { ); TextStyle usedTextStyle = widget.textStyle ?? - TextStyle(color: Theme.of(context).colorScheme.secondary, fontSize: 20, fontWeight: FontWeight.w700); + TextStyle( + color: context.theme.colorScheme.primary, + fontSize: 20, + fontWeight: FontWeight.w700, + ); return Theme( - data: Theme.of(context).copyWith( + data: context.theme.copyWith( inputDecorationTheme: const InputDecorationTheme( contentPadding: EdgeInsets.zero, border: borderTheme,