From 29c6692a799e0f8cd9f192bdf68840fbf450bf8f Mon Sep 17 00:00:00 2001 From: Felix Thape Date: Thu, 12 Sep 2024 13:41:01 +0200 Subject: [PATCH 1/4] 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/4] 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/4] 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/4] 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); }