From 4f24f8313a9ecd32222f02895eb8e04aa1a2629e Mon Sep 17 00:00:00 2001 From: Aman Date: Wed, 23 Aug 2023 21:54:31 +0530 Subject: [PATCH 01/21] feat: add retrofit Signed-off-by: Aman --- analysis_options.yaml | 8 ++ lib/data/constants/api_endpoints.dart | 8 ++ .../services/{ => local}/dialog_service.dart | 0 .../{ => local}/local_storage_service.dart | 0 .../{ => local}/package_info_service.dart | 0 lib/data/services/remote/api_service.dart | 17 ++++ .../push_notification_service.dart | 2 +- .../{ => remote}/remote_config_service.dart | 0 .../amenity}/analytics_service.dart | 0 lib/domain/models/appetizer_version.dart | 27 +++--- lib/locator.dart | 12 +-- pubspec.lock | 92 +++++++++++++++---- pubspec.yaml | 5 + 13 files changed, 130 insertions(+), 41 deletions(-) create mode 100644 lib/data/constants/api_endpoints.dart rename lib/data/services/{ => local}/dialog_service.dart (100%) rename lib/data/services/{ => local}/local_storage_service.dart (100%) rename lib/data/services/{ => local}/package_info_service.dart (100%) create mode 100644 lib/data/services/remote/api_service.dart rename lib/data/services/{ => remote}/push_notification_service.dart (95%) rename lib/data/services/{ => remote}/remote_config_service.dart (100%) rename lib/{data/services => domain/amenity}/analytics_service.dart (100%) diff --git a/analysis_options.yaml b/analysis_options.yaml index d0f4914e..7c7df1c5 100644 --- a/analysis_options.yaml +++ b/analysis_options.yaml @@ -9,6 +9,14 @@ # packages, and plugins designed to encourage good coding practices. include: package:flutter_lints/flutter.yaml +analyzer: + exclude: + - "**/*.g.dart" + - "**/*.freezed.dart" + - packages + errors: + invalid_annotation_target: ignore + linter: # The lint rules applied to this project can be customized in the # section below to disable rules from the `package:flutter_lints/flutter.yaml` diff --git a/lib/data/constants/api_endpoints.dart b/lib/data/constants/api_endpoints.dart new file mode 100644 index 00000000..191d2ad2 --- /dev/null +++ b/lib/data/constants/api_endpoints.dart @@ -0,0 +1,8 @@ +import 'package:appetizer/data/constants/env_config.dart'; + +class ApiEnpoints { + static const String baseUrl = EnvironmentConfig.BASE_URL; + + static const String checkVersion = + '/panel/version/expire/{platform}/{versionNumber}'; +} diff --git a/lib/data/services/dialog_service.dart b/lib/data/services/local/dialog_service.dart similarity index 100% rename from lib/data/services/dialog_service.dart rename to lib/data/services/local/dialog_service.dart diff --git a/lib/data/services/local_storage_service.dart b/lib/data/services/local/local_storage_service.dart similarity index 100% rename from lib/data/services/local_storage_service.dart rename to lib/data/services/local/local_storage_service.dart diff --git a/lib/data/services/package_info_service.dart b/lib/data/services/local/package_info_service.dart similarity index 100% rename from lib/data/services/package_info_service.dart rename to lib/data/services/local/package_info_service.dart diff --git a/lib/data/services/remote/api_service.dart b/lib/data/services/remote/api_service.dart new file mode 100644 index 00000000..56252895 --- /dev/null +++ b/lib/data/services/remote/api_service.dart @@ -0,0 +1,17 @@ +import 'package:appetizer/data/constants/api_endpoints.dart'; +import 'package:appetizer/domain/models/appetizer_version.dart'; +import 'package:dio/dio.dart'; +import 'package:retrofit/retrofit.dart'; + +part 'api_service.g.dart'; + +@RestApi(baseUrl: ApiEnpoints.baseUrl) +abstract class ApiService { + factory ApiService(Dio dio, {String baseUrl}) = _ApiService; + + @GET(ApiEnpoints.checkVersion) + Future checkVersion( + @Path("platform") String platform, + @Path("versionNumber") String versionNumber, + ); +} diff --git a/lib/data/services/push_notification_service.dart b/lib/data/services/remote/push_notification_service.dart similarity index 95% rename from lib/data/services/push_notification_service.dart rename to lib/data/services/remote/push_notification_service.dart index 255b4df0..4bee0730 100644 --- a/lib/data/services/push_notification_service.dart +++ b/lib/data/services/remote/push_notification_service.dart @@ -1,5 +1,5 @@ import 'package:appetizer/locator.dart'; -import 'package:appetizer/data/services/local_storage_service.dart'; +import 'package:appetizer/data/services/local/local_storage_service.dart'; import 'package:firebase_messaging/firebase_messaging.dart'; class PushNotificationService { diff --git a/lib/data/services/remote_config_service.dart b/lib/data/services/remote/remote_config_service.dart similarity index 100% rename from lib/data/services/remote_config_service.dart rename to lib/data/services/remote/remote_config_service.dart diff --git a/lib/data/services/analytics_service.dart b/lib/domain/amenity/analytics_service.dart similarity index 100% rename from lib/data/services/analytics_service.dart rename to lib/domain/amenity/analytics_service.dart diff --git a/lib/domain/models/appetizer_version.dart b/lib/domain/models/appetizer_version.dart index 45b9262d..f59307d9 100644 --- a/lib/domain/models/appetizer_version.dart +++ b/lib/domain/models/appetizer_version.dart @@ -1,9 +1,18 @@ +import 'package:json_annotation/json_annotation.dart'; + +part 'appetizer_version.g.dart'; + +@JsonSerializable() class AppetizerVersion { String number; String platform; + @JsonKey(name: "expiry_date") dynamic expiryDate; + @JsonKey(name: "is_expired") bool isExpired; + @JsonKey(name: "is_latest") bool isLatest; + @JsonKey(name: "date_created") int dateCreated; AppetizerVersion({ @@ -16,21 +25,7 @@ class AppetizerVersion { }); factory AppetizerVersion.fromJson(Map json) => - AppetizerVersion( - number: json['number'], - platform: json['platform'], - expiryDate: json['expiry_date'], - isExpired: json['is_expired'], - isLatest: json['is_latest'], - dateCreated: json['date_created'], - ); + _$AppetizerVersionFromJson(json); - Map toJson() => { - 'number': number, - 'platform': platform, - 'expiry_date': expiryDate, - 'is_expired': isExpired, - 'is_latest': isLatest, - 'date_created': dateCreated, - }; + Map toJson() => _$AppetizerVersionToJson(this); } diff --git a/lib/locator.dart b/lib/locator.dart index 3dcab395..29a79b98 100644 --- a/lib/locator.dart +++ b/lib/locator.dart @@ -1,4 +1,4 @@ -import 'package:appetizer/data/services/analytics_service.dart'; +import 'package:appetizer/domain/amenity/analytics_service.dart'; import 'package:appetizer/data/services/api/coupon_api.dart'; import 'package:appetizer/data/services/api/feedback_api.dart'; import 'package:appetizer/data/services/api/leave_api.dart'; @@ -7,11 +7,11 @@ import 'package:appetizer/data/services/api/multimessing_api.dart'; import 'package:appetizer/data/services/api/transaction_api.dart'; import 'package:appetizer/data/services/api/user_api.dart'; import 'package:appetizer/data/services/api/version_check_api.dart'; -import 'package:appetizer/data/services/dialog_service.dart'; -import 'package:appetizer/data/services/local_storage_service.dart'; -import 'package:appetizer/data/services/package_info_service.dart'; -import 'package:appetizer/data/services/push_notification_service.dart'; -import 'package:appetizer/data/services/remote_config_service.dart'; +import 'package:appetizer/data/services/local/dialog_service.dart'; +import 'package:appetizer/data/services/local/local_storage_service.dart'; +import 'package:appetizer/data/services/local/package_info_service.dart'; +import 'package:appetizer/data/services/remote/push_notification_service.dart'; +import 'package:appetizer/data/services/remote/remote_config_service.dart'; import 'package:get_it/get_it.dart'; GetIt locator = GetIt.instance; diff --git a/pubspec.lock b/pubspec.lock index 83b1bc03..174d32b8 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -5,10 +5,10 @@ packages: dependency: transitive description: name: _fe_analyzer_shared - sha256: eb376e9acf6938204f90eb3b1f00b578640d3188b4c8a8ec054f9f479af8d051 + sha256: ae92f5d747aee634b87f89d9946000c2de774be1d6ac3e58268224348cd0101a url: "https://pub.dev" source: hosted - version: "64.0.0" + version: "61.0.0" _flutterfire_internals: dependency: transitive description: @@ -21,10 +21,10 @@ packages: dependency: transitive description: name: analyzer - sha256: "69f54f967773f6c26c7dcb13e93d7ccee8b17a641689da39e878d5cf13b06893" + sha256: ea3d8652bda62982addfd92fdc2d0214e5f82e43325104990d4f4c4a2a313562 url: "https://pub.dev" source: hosted - version: "6.2.0" + version: "5.13.0" args: dependency: transitive description: @@ -173,10 +173,10 @@ packages: dependency: transitive description: name: collection - sha256: "4a07be6cb69c84d677a6c3096fcf960cc3285a8330b4603e0d463d15d9bd934c" + sha256: f092b211a4319e98e5ff58223576de6c2803db36221657b46c82574721240687 url: "https://pub.dev" source: hosted - version: "1.17.1" + version: "1.17.2" convert: dependency: transitive description: @@ -225,6 +225,14 @@ packages: url: "https://pub.dev" source: hosted version: "1.1.0" + dio: + dependency: "direct main" + description: + name: dio + sha256: ce75a1b40947fea0a0e16ce73337122a86762e38b982e1ccb909daa3b9bc4197 + url: "https://pub.dev" + source: hosted + version: "5.3.2" equatable: dependency: "direct main" description: @@ -521,10 +529,10 @@ packages: dependency: "direct main" description: name: intl - sha256: a3715e3bc90294e971cb7dc063fbf3cd9ee0ebf8604ffeafabd9e6f16abbdbe6 + sha256: "3bc132a9dbce73a7e4a21a17d06e1878839ffbf975568bc875c60537824b0c4d" url: "https://pub.dev" source: hosted - version: "0.18.0" + version: "0.18.1" io: dependency: transitive description: @@ -542,13 +550,21 @@ packages: source: hosted version: "0.6.7" json_annotation: - dependency: transitive + dependency: "direct main" description: name: json_annotation sha256: b10a7b2ff83d83c777edba3c6a0f97045ddadd56c944e1a23a3fdf43a1bf4467 url: "https://pub.dev" source: hosted version: "4.8.1" + json_serializable: + dependency: "direct dev" + description: + name: json_serializable + sha256: aa1f5a8912615733e0fdc7a02af03308933c93235bdc8d50d0b0c8a8ccb0b969 + url: "https://pub.dev" + source: hosted + version: "6.7.1" lints: dependency: transitive description: @@ -569,18 +585,18 @@ packages: dependency: transitive description: name: matcher - sha256: "6501fbd55da300384b768785b83e5ce66991266cec21af89ab9ae7f5ce1c4cbb" + sha256: "1803e76e6653768d64ed8ff2e1e67bea3ad4b923eb5c56a295c3e634bad5960e" url: "https://pub.dev" source: hosted - version: "0.12.15" + version: "0.12.16" material_color_utilities: dependency: transitive description: name: material_color_utilities - sha256: d92141dc6fe1dad30722f9aa826c7fbc896d021d792f80678280601aff8cf724 + sha256: "9528f2f296073ff54cb9fee677df673ace1218163c3bc7628093e7eed5203d41" url: "https://pub.dev" source: hosted - version: "0.2.0" + version: "0.5.0" meta: dependency: transitive description: @@ -757,6 +773,22 @@ packages: url: "https://pub.dev" source: hosted version: "1.2.3" + retrofit: + dependency: "direct main" + description: + name: retrofit + sha256: "5eedbd8f73697f190dabc88520e0bcf2d3b2d9b9ad5c837f1dbb3ee6172d7709" + url: "https://pub.dev" + source: hosted + version: "4.0.1" + retrofit_generator: + dependency: "direct dev" + description: + name: retrofit_generator + sha256: "9499eb46b3657a62192ddbc208ff7e6c6b768b19e83c1ee6f6b119c864b99690" + url: "https://pub.dev" + source: hosted + version: "7.0.8" sembast: dependency: "direct main" description: @@ -850,14 +882,22 @@ packages: url: "https://pub.dev" source: hosted version: "1.4.0" + source_helper: + dependency: transitive + description: + name: source_helper + sha256: "6adebc0006c37dd63fe05bca0a929b99f06402fc95aa35bf36d67f5c06de01fd" + url: "https://pub.dev" + source: hosted + version: "1.3.4" source_span: dependency: transitive description: name: source_span - sha256: dd904f795d4b4f3b870833847c461801f6750a9fa8e61ea5ac53f9422b31f250 + sha256: "53e943d4206a5e30df338fd4c6e7a077e02254531b138a15aec3bd143c1a8b3c" url: "https://pub.dev" source: hosted - version: "1.9.1" + version: "1.10.0" stack_trace: dependency: transitive description: @@ -910,10 +950,10 @@ packages: dependency: transitive description: name: test_api - sha256: eb6ac1540b26de412b3403a163d919ba86f6a973fe6cc50ae3541b80092fdcfb + sha256: "75760ffd7786fffdfb9597c35c5b27eaeec82be8edfb6d71d32651128ed7aab8" url: "https://pub.dev" source: hosted - version: "0.5.1" + version: "0.6.0" timing: dependency: transitive description: @@ -922,6 +962,14 @@ packages: url: "https://pub.dev" source: hosted version: "1.0.1" + tuple: + dependency: transitive + description: + name: tuple + sha256: a97ce2013f240b2f3807bcbaf218765b6f301c3eff91092bcfa23a039e7dd151 + url: "https://pub.dev" + source: hosted + version: "2.0.2" typed_data: dependency: transitive description: @@ -970,6 +1018,14 @@ packages: url: "https://pub.dev" source: hosted version: "1.1.0" + web: + dependency: transitive + description: + name: web + sha256: dc8ccd225a2005c1be616fe02951e2e342092edf968cf0844220383757ef8f10 + url: "https://pub.dev" + source: hosted + version: "0.1.4-beta" web_socket_channel: dependency: transitive description: @@ -1011,5 +1067,5 @@ packages: source: hosted version: "3.1.2" sdks: - dart: ">=3.0.0 <4.0.0" + dart: ">=3.1.0-185.0.dev <4.0.0" flutter: ">=3.10.0" diff --git a/pubspec.yaml b/pubspec.yaml index 93ceb63f..037a1bfc 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -37,10 +37,15 @@ dependencies: month_picker_dialog: ^2.0.2 hive: ^2.2.3 device_preview: ^1.1.0 + retrofit: ^4.0.1 + dio: ^5.3.2 + json_annotation: ^4.8.1 dev_dependencies: auto_route_generator: ^7.3.0 build_runner: ">2.3.0 <4.0.0" + json_serializable: ^6.7.1 + retrofit_generator: ^7.0.8 flutter_test: sdk: flutter From 2303252fd5c696faf19617f16462fb755f2942d8 Mon Sep 17 00:00:00 2001 From: NanoNish Date: Wed, 23 Aug 2023 23:19:07 +0530 Subject: [PATCH 02/21] chore: add freezed packages --- pubspec.lock | 52 ++++++++++++++++++++++++++-------------------------- pubspec.yaml | 2 ++ 2 files changed, 28 insertions(+), 26 deletions(-) diff --git a/pubspec.lock b/pubspec.lock index 174d32b8..7ca9c0d6 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -5,10 +5,10 @@ packages: dependency: transitive description: name: _fe_analyzer_shared - sha256: ae92f5d747aee634b87f89d9946000c2de774be1d6ac3e58268224348cd0101a + sha256: eb376e9acf6938204f90eb3b1f00b578640d3188b4c8a8ec054f9f479af8d051 url: "https://pub.dev" source: hosted - version: "61.0.0" + version: "64.0.0" _flutterfire_internals: dependency: transitive description: @@ -21,10 +21,10 @@ packages: dependency: transitive description: name: analyzer - sha256: ea3d8652bda62982addfd92fdc2d0214e5f82e43325104990d4f4c4a2a313562 + sha256: "69f54f967773f6c26c7dcb13e93d7ccee8b17a641689da39e878d5cf13b06893" url: "https://pub.dev" source: hosted - version: "5.13.0" + version: "6.2.0" args: dependency: transitive description: @@ -173,10 +173,10 @@ packages: dependency: transitive description: name: collection - sha256: f092b211a4319e98e5ff58223576de6c2803db36221657b46c82574721240687 + sha256: "4a07be6cb69c84d677a6c3096fcf960cc3285a8330b4603e0d463d15d9bd934c" url: "https://pub.dev" source: hosted - version: "1.17.2" + version: "1.17.1" convert: dependency: transitive description: @@ -429,8 +429,16 @@ packages: url: "https://pub.dev" source: hosted version: "8.2.2" + freezed: + dependency: "direct dev" + description: + name: freezed + sha256: "83462cfc33dc9680533a7f3a4a6ab60aa94f287db5f4ee6511248c22833c497f" + url: "https://pub.dev" + source: hosted + version: "2.4.2" freezed_annotation: - dependency: transitive + dependency: "direct main" description: name: freezed_annotation sha256: c3fd9336eb55a38cc1bbd79ab17573113a8deccd0ecbbf926cca3c62803b5c2d @@ -529,10 +537,10 @@ packages: dependency: "direct main" description: name: intl - sha256: "3bc132a9dbce73a7e4a21a17d06e1878839ffbf975568bc875c60537824b0c4d" + sha256: a3715e3bc90294e971cb7dc063fbf3cd9ee0ebf8604ffeafabd9e6f16abbdbe6 url: "https://pub.dev" source: hosted - version: "0.18.1" + version: "0.18.0" io: dependency: transitive description: @@ -585,18 +593,18 @@ packages: dependency: transitive description: name: matcher - sha256: "1803e76e6653768d64ed8ff2e1e67bea3ad4b923eb5c56a295c3e634bad5960e" + sha256: "6501fbd55da300384b768785b83e5ce66991266cec21af89ab9ae7f5ce1c4cbb" url: "https://pub.dev" source: hosted - version: "0.12.16" + version: "0.12.15" material_color_utilities: dependency: transitive description: name: material_color_utilities - sha256: "9528f2f296073ff54cb9fee677df673ace1218163c3bc7628093e7eed5203d41" + sha256: d92141dc6fe1dad30722f9aa826c7fbc896d021d792f80678280601aff8cf724 url: "https://pub.dev" source: hosted - version: "0.5.0" + version: "0.2.0" meta: dependency: transitive description: @@ -894,10 +902,10 @@ packages: dependency: transitive description: name: source_span - sha256: "53e943d4206a5e30df338fd4c6e7a077e02254531b138a15aec3bd143c1a8b3c" + sha256: dd904f795d4b4f3b870833847c461801f6750a9fa8e61ea5ac53f9422b31f250 url: "https://pub.dev" source: hosted - version: "1.10.0" + version: "1.9.1" stack_trace: dependency: transitive description: @@ -950,10 +958,10 @@ packages: dependency: transitive description: name: test_api - sha256: "75760ffd7786fffdfb9597c35c5b27eaeec82be8edfb6d71d32651128ed7aab8" + sha256: eb6ac1540b26de412b3403a163d919ba86f6a973fe6cc50ae3541b80092fdcfb url: "https://pub.dev" source: hosted - version: "0.6.0" + version: "0.5.1" timing: dependency: transitive description: @@ -1018,14 +1026,6 @@ packages: url: "https://pub.dev" source: hosted version: "1.1.0" - web: - dependency: transitive - description: - name: web - sha256: dc8ccd225a2005c1be616fe02951e2e342092edf968cf0844220383757ef8f10 - url: "https://pub.dev" - source: hosted - version: "0.1.4-beta" web_socket_channel: dependency: transitive description: @@ -1067,5 +1067,5 @@ packages: source: hosted version: "3.1.2" sdks: - dart: ">=3.1.0-185.0.dev <4.0.0" + dart: ">=3.0.0 <4.0.0" flutter: ">=3.10.0" diff --git a/pubspec.yaml b/pubspec.yaml index 037a1bfc..c0d515f9 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -40,10 +40,12 @@ dependencies: retrofit: ^4.0.1 dio: ^5.3.2 json_annotation: ^4.8.1 + freezed_annotation: ^2.4.1 dev_dependencies: auto_route_generator: ^7.3.0 build_runner: ">2.3.0 <4.0.0" + freezed: ^2.4.2 json_serializable: ^6.7.1 retrofit_generator: ^7.0.8 From a3b2f0922a99fbc4fd6a797df289938f2f166814 Mon Sep 17 00:00:00 2001 From: NanoNish Date: Wed, 23 Aug 2023 23:19:22 +0530 Subject: [PATCH 03/21] feat: add coupon model --- lib/domain/models/coupon/coupon.dart | 39 ++++++++++------------------ 1 file changed, 13 insertions(+), 26 deletions(-) diff --git a/lib/domain/models/coupon/coupon.dart b/lib/domain/models/coupon/coupon.dart index 8f8dfbed..4fcf63c6 100644 --- a/lib/domain/models/coupon/coupon.dart +++ b/lib/domain/models/coupon/coupon.dart @@ -1,29 +1,16 @@ -import 'dart:convert'; +import 'package:freezed_annotation/freezed_annotation.dart'; -Coupon notificationFromJson(String str) => Coupon.fromJson(json.decode(str)); +part 'coupon.freezed.dart'; +part 'coupon.g.dart'; -String notificationToJson(Coupon data) => json.encode(data.toJson()); +@freezed +class Coupon with _$Coupon { + @JsonSerializable(fieldRename: FieldRename.snake) + const factory Coupon({ + @JsonKey(name: 'id') required int id, + @JsonKey(name: 'meal') required String meal, + @JsonKey(name: 'is_active') bool? isActive, + }) = _Coupon; -class Coupon { - int id; - String meal; - String title; - - Coupon({ - required this.id, - required this.meal, - required this.title, - }); - - factory Coupon.fromJson(Map json) => Coupon( - id: json['id'], - meal: json['meal'], - title: json['title'], - ); - - Map toJson() => { - 'id': id, - 'meal': meal, - 'title': title, - }; -} + factory Coupon.fromJson(Map json) => _$CouponFromJson(json); +} \ No newline at end of file From a22444a4fe7c600ae96ca5b4a2aee72232c54187 Mon Sep 17 00:00:00 2001 From: Aman Date: Thu, 24 Aug 2023 01:10:49 +0530 Subject: [PATCH 04/21] feat: implement router and app bloc Signed-off-by: Aman --- lib/data/core/router/registry/paths.dart | 6 ++ lib/data/core/router/registry/routes.dart | 24 ++++++ lib/main.dart | 73 +------------------ lib/presentation/app/app.dart | 65 +++++++++++++++++ lib/presentation/app/bloc/app_bloc.dart | 26 +++++++ lib/presentation/app/bloc/app_event.dart | 24 ++++++ lib/presentation/app/bloc/app_state.dart | 21 ++++++ lib/presentation/coupons/coupons_view.dart | 6 +- .../leaves_and_rebate/leaves_and_rebate.dart | 20 +++-- lib/presentation/login/login_screen.dart | 2 + .../notifications/notification_view.dart | 6 +- lib/presentation/profile/profile_view.dart | 9 +-- .../week_menu/your_menu_view.dart | 6 +- lib/utils/interceptors/auth_interceptor.dart | 25 +++++++ lib/utils/interceptors/logging.dart | 27 +++++++ pubspec.lock | 40 +++++++++- pubspec.yaml | 6 +- 17 files changed, 290 insertions(+), 96 deletions(-) create mode 100644 lib/presentation/app/app.dart create mode 100644 lib/presentation/app/bloc/app_bloc.dart create mode 100644 lib/presentation/app/bloc/app_event.dart create mode 100644 lib/presentation/app/bloc/app_state.dart create mode 100644 lib/utils/interceptors/auth_interceptor.dart create mode 100644 lib/utils/interceptors/logging.dart diff --git a/lib/data/core/router/registry/paths.dart b/lib/data/core/router/registry/paths.dart index e42c732e..6b089bf2 100644 --- a/lib/data/core/router/registry/paths.dart +++ b/lib/data/core/router/registry/paths.dart @@ -3,5 +3,11 @@ part of '../router.dart'; class AppPathsRegistry { AppPathsRegistry._(); + static const String login = '/login'; static const String home = '/home'; + static const String notification = '/notifications'; + static const String profile = '/profile'; + static const String coupon = '/coupon'; + static const String weekMenu = '/weekMenu'; + static const String leavesAndRebate = '/leavesAndRebate'; } diff --git a/lib/data/core/router/registry/routes.dart b/lib/data/core/router/registry/routes.dart index ccc39bfa..5aa24e3c 100644 --- a/lib/data/core/router/registry/routes.dart +++ b/lib/data/core/router/registry/routes.dart @@ -4,9 +4,33 @@ class AppRoutesRegistry { AppRoutesRegistry._(); static List routes = [ + CustomRoute( + path: AppPathsRegistry.login, + page: LoginRoute.page, + ), CustomRoute( path: AppPathsRegistry.home, page: HomeRoute.page, ), + CustomRoute( + path: AppPathsRegistry.coupon, + page: CouponsRoute.page, + ), + CustomRoute( + path: AppPathsRegistry.notification, + page: NotificationRoute.page, + ), + CustomRoute( + path: AppPathsRegistry.leavesAndRebate, + page: LeavesAndRebateRoute.page, + ), + CustomRoute( + path: AppPathsRegistry.profile, + page: ProfileRoute.page, + ), + CustomRoute( + path: AppPathsRegistry.weekMenu, + page: YourWeekMenuRoute.page, + ), ]; } diff --git a/lib/main.dart b/lib/main.dart index f5c76058..f1e078dc 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -1,6 +1,4 @@ -import 'package:appetizer/domain/models/leaves/paginated_leaves.dart'; -import 'package:appetizer/domain/models/transaction/paginated_yearly_rebate.dart'; -import 'package:appetizer/presentation/leaves_and_rebate/leaves_and_rebate.dart'; +import 'package:appetizer/presentation/app/app.dart'; import 'package:appetizer/utils/local_storage.dart'; import 'package:device_preview/device_preview.dart'; import 'package:flutter/foundation.dart'; @@ -9,6 +7,7 @@ import 'package:flutter/material.dart'; Future main() async { WidgetsFlutterBinding.ensureInitialized(); await LocalStorage.init(); + runApp( DevicePreview( enabled: !kReleaseMode, @@ -16,71 +15,3 @@ Future main() async { ), ); } - -class AppetizerApp extends StatelessWidget { - const AppetizerApp({super.key}); - - @override - Widget build(BuildContext context) { - PaginatedLeaves dummyLeaves = PaginatedLeaves.fromJson({ - "count": 1, - "has_next": false, - "has_previous": false, - "results": [ - { - "id": 51, - "date_created": 1675078095318, - "start_meal_type": "Dinner", - "start_datetime": 1675260000000, - "status": "P", - "meal_count": 1, - "end_meal_type": "Dinner", - "end_datetime": 1675260000000 - } - ] - }); - PaginatedYearlyRebate dummyRebate = PaginatedYearlyRebate.fromJson({ - "count": 3, - "has_next": false, - "has_previous": false, - "results": [ - { - "month_id": 8, - "year": 2023, - "bill": null, - "expenses": 0, - "rebate": 0, - "start_date": 1690828200000 - }, - { - "month_id": 2, - "year": 2023, - "bill": null, - "expenses": 0, - "rebate": 0, - "start_date": 1675189800000 - }, - { - "month_id": 1, - "year": 2023, - "bill": null, - "expenses": 0, - "rebate": 0, - "start_date": 1672511400000 - } - ] - }); - int mealsSkipped = 1, remainingLeaves = 104; - return MaterialApp( - home: Scaffold( - body: LeavesAndRebate( - isCheckedOut: false, - initialYearlyRebates: dummyRebate, - mealsSkipped: mealsSkipped, - remainingLeaves: remainingLeaves, - currYearLeaves: dummyLeaves, - ), - ), - ); - } -} diff --git a/lib/presentation/app/app.dart b/lib/presentation/app/app.dart new file mode 100644 index 00000000..13ebc8d9 --- /dev/null +++ b/lib/presentation/app/app.dart @@ -0,0 +1,65 @@ +import 'package:appetizer/data/services/remote/api_service.dart'; +import 'package:appetizer/presentation/app/bloc/app_bloc.dart'; +import 'package:appetizer/utils/app_extensions/app_extensions.dart'; +import 'package:appetizer/utils/interceptors/auth_interceptor.dart'; +import 'package:appetizer/utils/interceptors/logging.dart'; +import 'package:auto_route/auto_route.dart'; +import 'package:device_preview/device_preview.dart'; +import 'package:dio/dio.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:sentry_dio/sentry_dio.dart'; + +class AppetizerApp extends StatefulWidget { + const AppetizerApp({super.key}); + + @override + State createState() => _AppetizerAppState(); +} + +class _AppetizerAppState extends State { + late final ApiService apiService; + + @override + void initState() { + apiService = _getApiService(); + super.initState(); + } + + @override + Widget build(BuildContext context) { + return MultiRepositoryProvider( + providers: [], + child: BlocBuilder( + builder: (context, state) { + return MaterialApp.router( + debugShowCheckedModeBanner: false, + title: "Appetizer", + locale: DevicePreview.locale(context), + builder: DevicePreview.appBuilder, + routerDelegate: AutoRouterDelegate(BaseApp.router), + routeInformationParser: BaseApp.router.defaultRouteParser(), + // TODO: add theme + ); + }, + ), + ); + } + + ApiService _getApiService() { + return ApiService( + Dio( + BaseOptions( + headers: {'Content-Type': 'application/json'}, + ), + ) + ..interceptors.addAll( + [ + AuthInterceptor(), // TODO: wirein get token method + Logging(), + ], + ) + ..addSentry(), + ); + } +} diff --git a/lib/presentation/app/bloc/app_bloc.dart b/lib/presentation/app/bloc/app_bloc.dart new file mode 100644 index 00000000..dfbfaccb --- /dev/null +++ b/lib/presentation/app/bloc/app_bloc.dart @@ -0,0 +1,26 @@ +import 'dart:async'; + +import 'package:equatable/equatable.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; + +part 'app_event.dart'; +part 'app_state.dart'; + +class AppBloc extends Bloc { + AppBloc() : super(AppState.initial()) { + on(_onInitialize); + on(_onGetUser); + on(_onNavigateToHome); + on(_onNavigateToLogin); + } + + FutureOr _onInitialize(Initialize event, Emitter emit) {} + + FutureOr _onGetUser(GetUser event, Emitter emit) {} + + FutureOr _onNavigateToHome( + NavigateToHomeScreen event, Emitter emit) {} + + FutureOr _onNavigateToLogin( + NavigateToLoginScreen event, Emitter emit) {} +} diff --git a/lib/presentation/app/bloc/app_event.dart b/lib/presentation/app/bloc/app_event.dart new file mode 100644 index 00000000..8a88f53b --- /dev/null +++ b/lib/presentation/app/bloc/app_event.dart @@ -0,0 +1,24 @@ +part of 'app_bloc.dart'; + +abstract class AppEvent extends Equatable { + const AppEvent(); + + @override + List get props => []; +} + +class Initialize extends AppEvent { + const Initialize(); +} + +class GetUser extends AppEvent { + const GetUser(); +} + +class NavigateToHomeScreen extends AppEvent { + const NavigateToHomeScreen(); +} + +class NavigateToLoginScreen extends AppEvent { + const NavigateToLoginScreen(); +} diff --git a/lib/presentation/app/bloc/app_state.dart b/lib/presentation/app/bloc/app_state.dart new file mode 100644 index 00000000..cd951ad6 --- /dev/null +++ b/lib/presentation/app/bloc/app_state.dart @@ -0,0 +1,21 @@ +part of 'app_bloc.dart'; + +enum NavigateTo { + inital, + showLoginScreen, + showHomeScreen, +} + +class AppState { + final NavigateTo navigateTo; + + AppState({required this.navigateTo}); + + AppState copyWith({ + NavigateTo? navigateTo, + }) { + return AppState(navigateTo: navigateTo ?? this.navigateTo); + } + + factory AppState.initial() => AppState(navigateTo: NavigateTo.inital); +} diff --git a/lib/presentation/coupons/coupons_view.dart b/lib/presentation/coupons/coupons_view.dart index 5e7dc4a6..017d94d7 100644 --- a/lib/presentation/coupons/coupons_view.dart +++ b/lib/presentation/coupons/coupons_view.dart @@ -1,11 +1,13 @@ import 'package:appetizer/presentation/components/no_data_found_container.dart'; import 'package:appetizer/presentation/coupons/bloc/coupons_page_bloc.dart'; import 'package:appetizer/presentation/coupons/components/coupon_card.dart'; +import 'package:auto_route/auto_route.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; -class CouponsPage extends StatelessWidget { - const CouponsPage({super.key}); +@RoutePage() +class CouponsScreen extends StatelessWidget { + const CouponsScreen({super.key}); @override Widget build(BuildContext context) { diff --git a/lib/presentation/leaves_and_rebate/leaves_and_rebate.dart b/lib/presentation/leaves_and_rebate/leaves_and_rebate.dart index 3794135a..8b2cf76d 100644 --- a/lib/presentation/leaves_and_rebate/leaves_and_rebate.dart +++ b/lib/presentation/leaves_and_rebate/leaves_and_rebate.dart @@ -7,17 +7,21 @@ import 'package:appetizer/presentation/leaves_and_rebate/components/leave_histor import 'package:appetizer/presentation/leaves_and_rebate/components/monthly_rebates.dart'; import 'package:appetizer/presentation/components/app_banner.dart'; import 'package:appetizer/presentation/components/round_edge_container.dart'; +import 'package:auto_route/auto_route.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; -class LeavesAndRebate extends StatelessWidget { - const LeavesAndRebate( - {super.key, - required this.isCheckedOut, - required this.initialYearlyRebates, - required this.currYearLeaves, - required this.mealsSkipped, - required this.remainingLeaves}); +@RoutePage() +class LeavesAndRebateScreen extends StatelessWidget { + const LeavesAndRebateScreen({ + required this.isCheckedOut, + required this.initialYearlyRebates, + required this.currYearLeaves, + required this.mealsSkipped, + required this.remainingLeaves, + super.key, + }); + final bool isCheckedOut; final PaginatedYearlyRebate initialYearlyRebates; final PaginatedLeaves currYearLeaves; diff --git a/lib/presentation/login/login_screen.dart b/lib/presentation/login/login_screen.dart index dce48cef..27a1e503 100644 --- a/lib/presentation/login/login_screen.dart +++ b/lib/presentation/login/login_screen.dart @@ -1,9 +1,11 @@ import 'package:appetizer/presentation/login/components/login_button.dart'; import 'package:appetizer/presentation/login/bloc/login_bloc.dart'; +import 'package:auto_route/auto_route.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:google_fonts/google_fonts.dart'; +@RoutePage() class LoginScreen extends StatefulWidget { const LoginScreen({super.key}); diff --git a/lib/presentation/notifications/notification_view.dart b/lib/presentation/notifications/notification_view.dart index 47191d9c..e757f0c9 100644 --- a/lib/presentation/notifications/notification_view.dart +++ b/lib/presentation/notifications/notification_view.dart @@ -2,11 +2,13 @@ import 'package:appetizer/presentation/notifications/bloc/notification_page_bloc import 'package:appetizer/presentation/notifications/components/no_notification_widget.dart'; import 'package:appetizer/presentation/notifications/components/notification_card.dart'; import 'package:appetizer/presentation/notifications/components/switch_bar.dart'; +import 'package:auto_route/auto_route.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; -class NotificationPage extends StatelessWidget { - const NotificationPage({super.key}); +@RoutePage() +class NotificationScreen extends StatelessWidget { + const NotificationScreen({super.key}); @override Widget build(BuildContext context) { diff --git a/lib/presentation/profile/profile_view.dart b/lib/presentation/profile/profile_view.dart index f2fc3bef..2cae8ff1 100644 --- a/lib/presentation/profile/profile_view.dart +++ b/lib/presentation/profile/profile_view.dart @@ -3,13 +3,12 @@ import 'package:appetizer/presentation/components/black_button.dart'; import 'package:appetizer/presentation/profile/components/profile_button.dart'; import 'package:appetizer/presentation/profile/components/profile_card.dart'; import 'package:appetizer/presentation/profile/components/profile_photo.dart'; +import 'package:auto_route/auto_route.dart'; import 'package:flutter/material.dart'; -class ProfilePage extends StatelessWidget { - const ProfilePage({ - required this.data, - Key? key, - }) : super(key: key); +@RoutePage() +class ProfileScreen extends StatelessWidget { + const ProfileScreen({required this.data, Key? key}) : super(key: key); final User data; diff --git a/lib/presentation/week_menu/your_menu_view.dart b/lib/presentation/week_menu/your_menu_view.dart index a84248f7..d011de33 100644 --- a/lib/presentation/week_menu/your_menu_view.dart +++ b/lib/presentation/week_menu/your_menu_view.dart @@ -8,6 +8,7 @@ import 'package:appetizer/presentation/week_menu/components/yourMealDailyCardsCo import 'package:appetizer/presentation/components/app_banner.dart'; import 'package:appetizer/presentation/components/loading_indicator.dart'; import 'package:appetizer/presentation/components/round_edge_container.dart'; +import 'package:auto_route/auto_route.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:intl/intl.dart'; @@ -37,8 +38,9 @@ class DayMenuFull { } } -class YourWeekMenu extends StatelessWidget { - const YourWeekMenu( +@RoutePage() +class YourWeekMenuScreen extends StatelessWidget { + const YourWeekMenuScreen( {super.key, required this.weekMenu, required this.isCheckedOut}); // final DateTime monthAndYear, startDateTime, endDateTime; final WeekMenu weekMenu; diff --git a/lib/utils/interceptors/auth_interceptor.dart b/lib/utils/interceptors/auth_interceptor.dart new file mode 100644 index 00000000..8df4423c --- /dev/null +++ b/lib/utils/interceptors/auth_interceptor.dart @@ -0,0 +1,25 @@ +import 'dart:async'; + +import 'package:dio/dio.dart'; +import 'package:flutter/foundation.dart'; + +class AuthInterceptor extends Interceptor { + ValueGetter>? getToken; + + AuthInterceptor({this.getToken}); + + @override + void onRequest( + RequestOptions options, RequestInterceptorHandler handler) async { + final token = await getToken?.call(); + if (token != null) { + final headerOptions = options.copyWith( + headers: {'Authorization': 'Token $token'}, + ); + + return super.onRequest(headerOptions, handler); + } + + return super.onRequest(options, handler); + } +} diff --git a/lib/utils/interceptors/logging.dart b/lib/utils/interceptors/logging.dart new file mode 100644 index 00000000..43d2f78d --- /dev/null +++ b/lib/utils/interceptors/logging.dart @@ -0,0 +1,27 @@ +import 'dart:developer'; + +import 'package:dio/dio.dart'; + +class Logging extends Interceptor { + @override + void onRequest(RequestOptions options, RequestInterceptorHandler handler) { + log('REQUEST[${options.headers} Body: ${options.data.toString()}] => PATH: ${options.uri}'); + return super.onRequest(options, handler); + } + + @override + void onResponse(Response response, ResponseInterceptorHandler handler) { + log( + 'RESPONSE[${response.statusCode}] Body: ${response.data.toString()} => PATH: ${response.requestOptions.uri}', + ); + return super.onResponse(response, handler); + } + + @override + void onError(DioException err, ErrorInterceptorHandler handler) { + log( + 'ERROR[${err.response?.statusCode}] => PATH: ${err.requestOptions.uri}', + ); + return super.onError(err, handler); + } +} diff --git a/pubspec.lock b/pubspec.lock index 174d32b8..c16afd26 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -45,18 +45,18 @@ packages: dependency: "direct main" description: name: auto_route - sha256: "35e5c7f8de56ec07c40fca4c953cb7d1d113e26d50bd876a4130a9b874923f27" + sha256: "02120972925a567c37921fa28ac7e90680c7095dd0e70711353737ec2727cdc6" url: "https://pub.dev" source: hosted - version: "7.8.1" + version: "7.4.0" auto_route_generator: dependency: "direct dev" description: name: auto_route_generator - sha256: e7aa9ab44b77cd31a4619d94db645ab5736e543fd0b4c6058c281249e479dfb8 + sha256: d0555913cc54153c38b1dd4f69e0d6a623818ca7195e7c1437901d52b2596eec url: "https://pub.dev" source: hosted - version: "7.3.1" + version: "7.1.1" bloc: dependency: "direct main" description: @@ -797,6 +797,30 @@ packages: url: "https://pub.dev" source: hosted version: "3.5.0+1" + sentry: + dependency: transitive + description: + name: sentry + sha256: "39c23342fc96105da449914f7774139a17a0ca8a4e70d9ad5200171f7e47d6ba" + url: "https://pub.dev" + source: hosted + version: "7.9.0" + sentry_dio: + dependency: "direct main" + description: + name: sentry_dio + sha256: df4c1eca92ab0a4b4e4ef67477a01d3fc898e9394c2675f9cf2b0a20285b1847 + url: "https://pub.dev" + source: hosted + version: "7.9.0" + sentry_flutter: + dependency: "direct main" + description: + name: sentry_flutter + sha256: ff68ab31918690da004a42e20204242a3ad9ad57da7e2712da8487060ac9767f + url: "https://pub.dev" + source: hosted + version: "7.9.0" shared_preferences: dependency: "direct main" description: @@ -978,6 +1002,14 @@ packages: url: "https://pub.dev" source: hosted version: "1.3.2" + uuid: + dependency: transitive + description: + name: uuid + sha256: "648e103079f7c64a36dc7d39369cabb358d377078a051d6ae2ad3aa539519313" + url: "https://pub.dev" + source: hosted + version: "3.0.7" vector_graphics: dependency: transitive description: diff --git a/pubspec.yaml b/pubspec.yaml index 037a1bfc..b12974af 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -14,7 +14,7 @@ dependencies: sdk: flutter cupertino_icons: ^1.0.2 - auto_route: ^7.8.0 + auto_route: 7.4.0 flutter_bloc: ^8.1.3 equatable: ^2.0.5 firebase_analytics: ^10.4.4 @@ -40,9 +40,11 @@ dependencies: retrofit: ^4.0.1 dio: ^5.3.2 json_annotation: ^4.8.1 + sentry_flutter: ^7.9.0 + sentry_dio: ^7.9.0 dev_dependencies: - auto_route_generator: ^7.3.0 + auto_route_generator: 7.1.1 build_runner: ">2.3.0 <4.0.0" json_serializable: ^6.7.1 retrofit_generator: ^7.0.8 From ffd6e262163be4d597e8a2af9452b50b39ea0772 Mon Sep 17 00:00:00 2001 From: NanoNish Date: Thu, 24 Aug 2023 01:21:01 +0530 Subject: [PATCH 05/21] feat: add feeback models --- .../models/feedback/appetizer_feedback.dart | 32 ++++++------------- .../models/feedback/feedback_response.dart | 19 ++++++----- .../models/feedback/paginated_feedbacks.dart | 29 ++++++++--------- pubspec.lock | 12 +++---- pubspec.yaml | 2 +- 5 files changed, 39 insertions(+), 55 deletions(-) diff --git a/lib/domain/models/feedback/appetizer_feedback.dart b/lib/domain/models/feedback/appetizer_feedback.dart index b0031330..2f2691d1 100644 --- a/lib/domain/models/feedback/appetizer_feedback.dart +++ b/lib/domain/models/feedback/appetizer_feedback.dart @@ -1,11 +1,19 @@ +import 'package:json_annotation/json_annotation.dart'; + +part 'appetizer_feedback.g.dart'; + +@JsonSerializable() class AppetizerFeedback { int id; String type; String title; String message; int timestamp; + @JsonKey(name: 'meal_id') dynamic mealId; + @JsonKey(name: 'image_url') dynamic imageUrl; + @JsonKey(name: 'date_issue') int dateIssue; dynamic response; @@ -22,27 +30,7 @@ class AppetizerFeedback { }); factory AppetizerFeedback.fromJson(Map json) => - AppetizerFeedback( - id: json['id'], - type: json['type'], - title: json['title'], - message: json['message'], - timestamp: json['timestamp'], - mealId: json['meal_id'], - imageUrl: json['image_url'], - dateIssue: json['date_issue'], - response: json['response'], - ); + _$AppetizerFeedbackFromJson(json); - Map toJson() => { - 'id': id, - 'type': type, - 'title': title, - 'message': message, - 'timestamp': timestamp, - 'meal_id': mealId, - 'image_url': imageUrl, - 'date_issue': dateIssue, - 'response': response, - }; + Map toJson() => _$AppetizerFeedbackToJson(this); } diff --git a/lib/domain/models/feedback/feedback_response.dart b/lib/domain/models/feedback/feedback_response.dart index a21237ba..a9864f0f 100644 --- a/lib/domain/models/feedback/feedback_response.dart +++ b/lib/domain/models/feedback/feedback_response.dart @@ -1,6 +1,13 @@ +import 'package:json_annotation/json_annotation.dart'; + +part 'feedback_response.g.dart'; + +@JsonSerializable() class FeedbackResponse { String message; + @JsonKey(name: 'is_read') bool isRead; + @JsonKey(name: 'date_created') int dateCreated; FeedbackResponse({ @@ -10,15 +17,7 @@ class FeedbackResponse { }); factory FeedbackResponse.fromJson(Map json) => - FeedbackResponse( - message: json['message'], - isRead: json['is_read'], - dateCreated: json['date_created'], - ); + _$FeedbackResponseFromJson(json); - Map toJson() => { - 'message': message, - 'is_read': isRead, - 'date_created': dateCreated, - }; + Map toJson() => _$FeedbackResponseToJson(this); } diff --git a/lib/domain/models/feedback/paginated_feedbacks.dart b/lib/domain/models/feedback/paginated_feedbacks.dart index 918a0b1a..109a16e5 100644 --- a/lib/domain/models/feedback/paginated_feedbacks.dart +++ b/lib/domain/models/feedback/paginated_feedbacks.dart @@ -1,31 +1,28 @@ import 'package:appetizer/domain/models/feedback/appetizer_feedback.dart'; +import 'package:json_annotation/json_annotation.dart'; -class PaginatedFeedbacks { +part 'paginated_feedbacks.g.dart'; + +@JsonSerializable() +class PaginatedFeedback { int count; + @JsonKey(name: 'has_next') bool hasNext; + @JsonKey(name: 'has_previous') bool hasPrevious; List feedbacks; - PaginatedFeedbacks({ + PaginatedFeedback({ required this.count, required this.hasNext, required this.hasPrevious, required this.feedbacks, }); - factory PaginatedFeedbacks.fromJson(Map json) => - PaginatedFeedbacks( - count: json['count'], - hasNext: json['has_next'], - hasPrevious: json['has_previous'], - feedbacks: List.from( - json['results'].map((x) => AppetizerFeedback.fromJson(x))), - ); + // TODO: check if feedbacks parse correctly into the map + + factory PaginatedFeedback.fromJson(Map json) => + _$PaginatedFeedbackFromJson(json); - Map toJson() => { - 'count': count, - 'has_next': hasNext, - 'has_previous': hasPrevious, - 'results': List.from(feedbacks.map((x) => x.toJson())), - }; + Map toJson() => _$PaginatedFeedbackToJson(this); } diff --git a/pubspec.lock b/pubspec.lock index 6eef3449..617d8e99 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -5,10 +5,10 @@ packages: dependency: transitive description: name: _fe_analyzer_shared - sha256: eb376e9acf6938204f90eb3b1f00b578640d3188b4c8a8ec054f9f479af8d051 + sha256: ae92f5d747aee634b87f89d9946000c2de774be1d6ac3e58268224348cd0101a url: "https://pub.dev" source: hosted - version: "64.0.0" + version: "61.0.0" _flutterfire_internals: dependency: transitive description: @@ -21,10 +21,10 @@ packages: dependency: transitive description: name: analyzer - sha256: "69f54f967773f6c26c7dcb13e93d7ccee8b17a641689da39e878d5cf13b06893" + sha256: ea3d8652bda62982addfd92fdc2d0214e5f82e43325104990d4f4c4a2a313562 url: "https://pub.dev" source: hosted - version: "6.2.0" + version: "5.13.0" args: dependency: transitive description: @@ -433,10 +433,10 @@ packages: dependency: "direct dev" description: name: freezed - sha256: "83462cfc33dc9680533a7f3a4a6ab60aa94f287db5f4ee6511248c22833c497f" + sha256: "2df89855fe181baae3b6d714dc3c4317acf4fccd495a6f36e5e00f24144c6c3b" url: "https://pub.dev" source: hosted - version: "2.4.2" + version: "2.4.1" freezed_annotation: dependency: "direct main" description: diff --git a/pubspec.yaml b/pubspec.yaml index 80ed4756..4478cb9d 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -47,8 +47,8 @@ dependencies: dev_dependencies: auto_route_generator: 7.1.1 build_runner: ">2.3.0 <4.0.0" - freezed: ^2.4.2 json_serializable: ^6.7.1 + freezed: ^2.4.1 retrofit_generator: ^7.0.8 flutter_test: From b6c3621f3946fb8d2e95743187edfcae74eeb81d Mon Sep 17 00:00:00 2001 From: NanoNish Date: Thu, 24 Aug 2023 01:32:32 +0530 Subject: [PATCH 06/21] feat: add leave models --- lib/domain/models/leaves/leave.dart | 72 +++++++------------ .../models/leaves/paginated_leaves.dart | 43 +++++------ 2 files changed, 41 insertions(+), 74 deletions(-) diff --git a/lib/domain/models/leaves/leave.dart b/lib/domain/models/leaves/leave.dart index 3cb8a8f2..6aa392a6 100644 --- a/lib/domain/models/leaves/leave.dart +++ b/lib/domain/models/leaves/leave.dart @@ -1,50 +1,26 @@ -import 'dart:convert'; +import 'package:freezed_annotation/freezed_annotation.dart'; +part 'leave.freezed.dart'; +part 'leave.g.dart'; -Leave leaveFromJson(String str) => Leave.fromJson(json.decode(str)); +@freezed +class Leave with _$Leave { + @JsonSerializable(fieldRename: FieldRename.snake) + const factory Leave({ + required int id, + @JsonKey(name: 'date_created') + required DateTime dateCreated, + @JsonKey(name: 'start_meal_type') + required String startMealType, + @JsonKey(name: 'end_meal_type') + required String endMealType, + @JsonKey(name: 'start_datetime') + required DateTime startDatetime, + @JsonKey(name: 'end_datetime') + required DateTime endDatetime, + @JsonKey(name: 'meal_count') + required int mealCount, + required String status, + }) = _Leave; -String leaveToJson(Leave data) => json.encode(data.toJson()); - -class Leave { - int id; - DateTime dateCreated; - String startMealType; - String endMealType; - DateTime startDatetime; - DateTime endDatetime; - int mealCount; - String status; - - Leave({ - required this.id, - required this.dateCreated, - required this.startMealType, - required this.endMealType, - required this.startDatetime, - required this.endDatetime, - required this.mealCount, - required this.status, - }); - - factory Leave.fromJson(Map json) => Leave( - id: json['id'], - dateCreated: DateTime.fromMillisecondsSinceEpoch(json['date_created']), - startMealType: json['start_meal_type'], - endMealType: json['end_meal_type'], - startDatetime: - DateTime.fromMillisecondsSinceEpoch(json['start_datetime']), - endDatetime: DateTime.fromMillisecondsSinceEpoch(json['end_datetime']), - mealCount: json['meal_count'], - status: json['status'], - ); - - Map toJson() => { - 'id': id, - 'date_created': dateCreated.millisecondsSinceEpoch, - 'start_meal_type': startMealType, - 'end_meal_type': endMealType, - 'start_datetime': startDatetime.millisecondsSinceEpoch, - 'end_datetime': endDatetime.millisecondsSinceEpoch, - 'meal_count': mealCount, - 'status': status, - }; -} + factory Leave.fromJson(Map json) => _$LeaveFromJson(json); +} \ No newline at end of file diff --git a/lib/domain/models/leaves/paginated_leaves.dart b/lib/domain/models/leaves/paginated_leaves.dart index 838532af..b9a3bd25 100644 --- a/lib/domain/models/leaves/paginated_leaves.dart +++ b/lib/domain/models/leaves/paginated_leaves.dart @@ -1,31 +1,22 @@ import 'package:appetizer/domain/models/leaves/leave.dart'; +import 'package:freezed_annotation/freezed_annotation.dart'; -class PaginatedLeaves { - int count; - bool hasNext; - bool hasPrevious; - List results; +part 'paginated_leaves.freezed.dart'; +part 'paginated_leaves.g.dart'; - PaginatedLeaves({ - required this.count, - required this.hasNext, - required this.hasPrevious, - required this.results, - }); +@freezed +class PaginatedLeaves with _$PaginatedLeaves { + @JsonSerializable(fieldRename: FieldRename.snake) + const factory PaginatedLeaves({ + required int count, + @JsonKey(name: 'has_next') + required bool hasNext, + @JsonKey(name: 'has_previous') + required bool hasPrevious, + required List results, + }) = _PaginatedLeaves; - factory PaginatedLeaves.fromJson(Map json) => - PaginatedLeaves( - count: json['count'], - hasNext: json['has_next'], - hasPrevious: json['has_previous'], - results: - List.from(json['results'].map((x) => Leave.fromJson(x))), - ); + // TODO: check if leaves parse correctly into the map - Map toJson() => { - 'count': count, - 'has_next': hasNext, - 'has_previous': hasPrevious, - 'results': List.from(results.map((x) => x.toJson())), - }; -} + factory PaginatedLeaves.fromJson(Map json) => _$PaginatedLeavesFromJson(json); +} \ No newline at end of file From 544e4a2b0483a499fa6f529166d976675cf2b50b Mon Sep 17 00:00:00 2001 From: NanoNish Date: Thu, 24 Aug 2023 01:46:13 +0530 Subject: [PATCH 07/21] patch: add snakecase to jsonserializer rules --- lib/domain/models/coupon/coupon.dart | 6 +++--- lib/domain/models/feedback/appetizer_feedback.dart | 5 +---- lib/domain/models/feedback/feedback_response.dart | 4 +--- lib/domain/models/feedback/paginated_feedbacks.dart | 2 +- lib/domain/models/leaves/leave.dart | 6 ------ lib/domain/models/leaves/paginated_leaves.dart | 2 -- 6 files changed, 6 insertions(+), 19 deletions(-) diff --git a/lib/domain/models/coupon/coupon.dart b/lib/domain/models/coupon/coupon.dart index 4fcf63c6..e91ad70c 100644 --- a/lib/domain/models/coupon/coupon.dart +++ b/lib/domain/models/coupon/coupon.dart @@ -7,9 +7,9 @@ part 'coupon.g.dart'; class Coupon with _$Coupon { @JsonSerializable(fieldRename: FieldRename.snake) const factory Coupon({ - @JsonKey(name: 'id') required int id, - @JsonKey(name: 'meal') required String meal, - @JsonKey(name: 'is_active') bool? isActive, + required int id, + required String meal, + bool? isActive, }) = _Coupon; factory Coupon.fromJson(Map json) => _$CouponFromJson(json); diff --git a/lib/domain/models/feedback/appetizer_feedback.dart b/lib/domain/models/feedback/appetizer_feedback.dart index 2f2691d1..4584f706 100644 --- a/lib/domain/models/feedback/appetizer_feedback.dart +++ b/lib/domain/models/feedback/appetizer_feedback.dart @@ -2,18 +2,15 @@ import 'package:json_annotation/json_annotation.dart'; part 'appetizer_feedback.g.dart'; -@JsonSerializable() +@JsonSerializable(fieldRename: FieldRename.snake) class AppetizerFeedback { int id; String type; String title; String message; int timestamp; - @JsonKey(name: 'meal_id') dynamic mealId; - @JsonKey(name: 'image_url') dynamic imageUrl; - @JsonKey(name: 'date_issue') int dateIssue; dynamic response; diff --git a/lib/domain/models/feedback/feedback_response.dart b/lib/domain/models/feedback/feedback_response.dart index a9864f0f..6614714b 100644 --- a/lib/domain/models/feedback/feedback_response.dart +++ b/lib/domain/models/feedback/feedback_response.dart @@ -2,12 +2,10 @@ import 'package:json_annotation/json_annotation.dart'; part 'feedback_response.g.dart'; -@JsonSerializable() +@JsonSerializable(fieldRename: FieldRename.snake) class FeedbackResponse { String message; - @JsonKey(name: 'is_read') bool isRead; - @JsonKey(name: 'date_created') int dateCreated; FeedbackResponse({ diff --git a/lib/domain/models/feedback/paginated_feedbacks.dart b/lib/domain/models/feedback/paginated_feedbacks.dart index 109a16e5..f89f8dc8 100644 --- a/lib/domain/models/feedback/paginated_feedbacks.dart +++ b/lib/domain/models/feedback/paginated_feedbacks.dart @@ -3,7 +3,7 @@ import 'package:json_annotation/json_annotation.dart'; part 'paginated_feedbacks.g.dart'; -@JsonSerializable() +@JsonSerializable(explicitToJson: true, fieldRename: FieldRename.snake) class PaginatedFeedback { int count; @JsonKey(name: 'has_next') diff --git a/lib/domain/models/leaves/leave.dart b/lib/domain/models/leaves/leave.dart index 6aa392a6..2a4fb9f5 100644 --- a/lib/domain/models/leaves/leave.dart +++ b/lib/domain/models/leaves/leave.dart @@ -7,17 +7,11 @@ class Leave with _$Leave { @JsonSerializable(fieldRename: FieldRename.snake) const factory Leave({ required int id, - @JsonKey(name: 'date_created') required DateTime dateCreated, - @JsonKey(name: 'start_meal_type') required String startMealType, - @JsonKey(name: 'end_meal_type') required String endMealType, - @JsonKey(name: 'start_datetime') required DateTime startDatetime, - @JsonKey(name: 'end_datetime') required DateTime endDatetime, - @JsonKey(name: 'meal_count') required int mealCount, required String status, }) = _Leave; diff --git a/lib/domain/models/leaves/paginated_leaves.dart b/lib/domain/models/leaves/paginated_leaves.dart index b9a3bd25..c1b42d8d 100644 --- a/lib/domain/models/leaves/paginated_leaves.dart +++ b/lib/domain/models/leaves/paginated_leaves.dart @@ -9,9 +9,7 @@ class PaginatedLeaves with _$PaginatedLeaves { @JsonSerializable(fieldRename: FieldRename.snake) const factory PaginatedLeaves({ required int count, - @JsonKey(name: 'has_next') required bool hasNext, - @JsonKey(name: 'has_previous') required bool hasPrevious, required List results, }) = _PaginatedLeaves; From f07f52b398c85913ceafb4ab204d7c8118ce0fab Mon Sep 17 00:00:00 2001 From: NanoNish Date: Thu, 24 Aug 2023 04:09:10 +0530 Subject: [PATCH 08/21] feat: add menu models --- lib/domain/models/menu/week_menu.dart | 439 +++++++------------------- 1 file changed, 114 insertions(+), 325 deletions(-) diff --git a/lib/domain/models/menu/week_menu.dart b/lib/domain/models/menu/week_menu.dart index 27d55f4c..c9bcd494 100644 --- a/lib/domain/models/menu/week_menu.dart +++ b/lib/domain/models/menu/week_menu.dart @@ -1,119 +1,55 @@ -import 'dart:convert'; - import 'package:appetizer/enums/enum_values.dart'; -import 'package:appetizer/globals.dart'; -import 'package:appetizer/utils/date_time_utils.dart'; -import 'package:intl/intl.dart'; - -class WeekMenu { - int weekId; - int year; - dynamic name; - String? hostelName; - DailyItems dailyItems; - List dayMenus; - bool isApproved; - - WeekMenu({ - required this.weekId, - required this.year, - required this.name, - this.hostelName, - required this.dailyItems, - required this.dayMenus, - required this.isApproved, - }); - - factory WeekMenu.fromJson(Map json) => WeekMenu( - weekId: json['week_id'], - year: json['year'], - name: json['name'], - hostelName: json['hostel_name'], - dailyItems: DailyItems.fromJson(json['daily_items']), - dayMenus: - List.from(json['days'].map((x) => DayMenu.fromJson(x))), - isApproved: json['is_approved'], - ); - - Map toJson() => { - 'week_id': weekId, - 'year': year, - 'name': name, - 'hostel_name': hostelName, - 'daily_items': dailyItems.toJson(), - 'days': List.from(dayMenus.map((x) => x.toJson())), - 'is_approved': isApproved, - }; +import 'package:flutter/foundation.dart'; +import 'package:freezed_annotation/freezed_annotation.dart'; + +part 'week_menu.freezed.dart'; +part 'week_menu.g.dart'; + +// TODO: remove enums from this file + +@freezed +class WeekMenu with _$WeekMenu { + @JsonSerializable(fieldRename: FieldRename.snake, explicitToJson: true) + const factory WeekMenu({ + required int weekId, + required int year, + required dynamic name, + String? hostelName, + required DailyItems dailyItems, + @JsonKey(name: 'days') required List dayMenus, + required bool isApproved, + }) = _WeekMenu; + + factory WeekMenu.fromJson(Map json) => + _$WeekMenuFromJson(json); } -class DailyItems { - int id; - List breakfast; - List lunch; - List dinner; - List snack; - - DailyItems({ - required this.id, - required this.breakfast, - required this.lunch, - required this.dinner, - required this.snack, - }); - - factory DailyItems.fromJson(Map json) => DailyItems( - id: json['id'], - breakfast: List.from( - json['breakfast'].map((x) => MealItem.fromJson(x)), - ), - lunch: List.from( - json['lunch'].map((x) => MealItem.fromJson(x)), - ), - dinner: List.from( - json['dinner'].map((x) => MealItem.fromJson(x)), - ), - snack: List.from( - json['snack'].map((x) => MealItem.fromJson(x)), - ), - ); - - Map toJson() => { - 'id': id, - 'breakfast': List.from(breakfast.map((x) => x.toJson())), - 'lunch': List.from(lunch.map((x) => x.toJson())), - 'dinner': List.from(dinner.map((x) => x.toJson())), - 'snack': List.from(snack.map((x) => x.toJson())), - }; +@freezed +class DailyItems with _$DailyItems { + @JsonSerializable(fieldRename: FieldRename.snake, explicitToJson: true) + const factory DailyItems({ + required int id, + required List breakfast, + required List lunch, + required List dinner, + List? snack, + }) = _DailyItems; + + factory DailyItems.fromJson(Map json) => + _$DailyItemsFromJson(json); } -List mealItemFromJson(String str) => - List.from(json.decode(str).map((x) => MealItem.fromJson(x))); - -String mealItemToJson(List data) => - json.encode(List.from(data.map((x) => x.toJson()))); - -class MealItem { - int id; - MealItemType type; - String name; - - MealItem({ - required this.id, - required this.type, - required this.name, - }); - - factory MealItem.fromJson(Map json) => MealItem( - id: json['id'], - type: breakfastTypeValues.map[json['type']]!, - name: json['name'], - ); - - Map toJson() => { - 'id': id, - 'type': breakfastTypeValues.reverse[type], - 'name': name, - }; +@freezed +class MealItem with _$MealItem { + @JsonSerializable() + const factory MealItem({ + required int id, + required MealItemType type, + required String name, + }) = _MealItem; + + factory MealItem.fromJson(Map json) => + _$MealItemFromJson(json); } enum MealItemType { MCL, SLD, EXT, MCD, STR, SNK, CPN } @@ -128,174 +64,56 @@ final breakfastTypeValues = EnumValues({ 'cpn': MealItemType.CPN, }); -class DayMenu { - int id; - int dayId; - DateTime date; - List meals; - late Map mealMap; - - DayMenu({ - required this.id, - required this.dayId, - required this.date, - required this.meals, - }) { - mealMap = {}; +@freezed +class DayMenu with _$DayMenu { + @JsonSerializable(fieldRename: FieldRename.snake, explicitToJson: true) + const DayMenu._(); + + factory DayMenu({ + required int id, + required int dayId, + required DateTime date, + required List meals, + }) = _DayMenu; + + // TODO: check if mealMap is parsed correctly + Map get mealMap { + Map mealMap = {}; for (var meal in meals) { mealMap[meal.type] = meal; } + return mealMap; } - factory DayMenu.fromJson(Map json) => DayMenu( - id: json['id'], - dayId: json['day_id'], - date: DateTime.parse(json['date']), - meals: List.from( - json['meals'].map( - (meal) => Meal.fromJson(meal, DateTime.parse(json['date'])), - ), - ), - ); - - Map toJson() => { - 'id': id, - 'day_id': dayId, - 'date': DateTimeUtils.getDashedDate(date), - 'meals': List.from(meals.map((x) => x.toJson())), - }; + factory DayMenu.fromJson(Map json) => + _$DayMenuFromJson(json); } -class Meal { - int id; - MealType type; - CostType? costType; - List items; - DateTime startTime; - DateTime endTime; - LeaveStatus leaveStatus; - CouponStatus couponStatus; - dynamic wastage; - bool isSwitchable; - SwitchStatus switchStatus; - String? hostelName; - String? secretCode; - bool isOutdated; - bool isLeaveToggleOutdated; - bool isCouponOutdated; - DateTime startDateTime; - DateTime endDateTime; - - Meal({ - required this.id, - required this.type, - this.costType, - required this.items, - required this.startTime, - required this.endTime, - required this.leaveStatus, - required this.wastage, - required this.isSwitchable, - required this.switchStatus, - this.hostelName, - this.secretCode, - required this.isOutdated, - required this.isLeaveToggleOutdated, - required this.isCouponOutdated, - required this.startDateTime, - required this.endDateTime, - required this.couponStatus, - }); - - factory Meal.fromJson(Map json, DateTime date) => Meal( - id: json['id'], - type: mealTypeValues.map[json['type']]!, - costType: costTypeValues.map[json['cost_type']], - items: - List.from(json['items'].map((x) => MealItem.fromJson(x))), - startTime: DateFormat('HH:mm:ss').parse(json['start_time']), - endTime: DateFormat('HH:mm:ss').parse(json['end_time']), - leaveStatus: LeaveStatus.fromJson(json['leave_status']), - couponStatus: CouponStatus.fromJson(json['coupon_status']), - wastage: json['wastage'], - isSwitchable: json['is_switchable'] ?? false, - switchStatus: SwitchStatus.fromJson(json['switch_status']), - hostelName: json['hostel_name'], - secretCode: json['secret_code'], - isOutdated: - !DateTimeUtils.getDateTimeFromDateAndTime(date, json['start_time']) - .isAfter(DateTime.now()), - isLeaveToggleOutdated: - !DateTimeUtils.getDateTimeFromDateAndTime(date, json['start_time']) - .subtract(outdatedTime) - .isAfter(DateTime.now()), - isCouponOutdated: - !DateTimeUtils.getDateTimeFromDateAndTime(date, json['start_time']) - .subtract(outdatedTime * 2) - .isAfter(DateTime.now()), - startDateTime: - DateTimeUtils.getDateTimeFromDateAndTime(date, json['start_time']), - endDateTime: - DateTimeUtils.getDateTimeFromDateAndTime(date, json['end_time']), - ); - - Map toJson() => { - 'id': id, - 'type': mealTypeValues.reverse[type], - 'cost_type': costTypeValues.reverse[costType], - 'items': List.from(items.map((x) => x.toJson())), - 'start_time': startTime, - 'end_time': endTime, - 'leave_status': leaveStatus.toJson(), - 'wastage': wastage, - 'is_switchable': isSwitchable, - 'switch_status': switchStatus.toJson(), - 'hostel_name': hostelName, - 'secret_code': secretCode, - }; - - Meal copyWith({ - int? id, - MealType? type, +@freezed +class Meal with _$Meal { + @JsonSerializable(fieldRename: FieldRename.snake, explicitToJson: true) + const Meal._(); + + const factory Meal({ + required int id, + required MealType type, CostType? costType, - List? items, - DateTime? startTime, - DateTime? endTime, - LeaveStatus? leaveStatus, - CouponStatus? couponStatus, - dynamic wastage, - bool? isSwitchable, - SwitchStatus? switchStatus, + required List items, + required DateTime startTime, + required DateTime endTime, + required LeaveStatus leaveStatus, + required CouponStatus couponStatus, + required dynamic wastage, + required bool isSwitchable, + required SwitchStatus switchStatus, String? hostelName, String? secretCode, - bool? isOutdated, - bool? isLeaveToggleOutdated, - bool? isCouponOutdated, - DateTime? startDateTime, - DateTime? endDateTime, - }) { - return Meal( - id: id ?? this.id, - type: type ?? this.type, - costType: costType ?? this.costType, - items: items ?? this.items, - startTime: startTime ?? this.startTime, - endTime: endTime ?? this.endTime, - leaveStatus: leaveStatus ?? this.leaveStatus, - couponStatus: couponStatus ?? this.couponStatus, - wastage: wastage ?? this.wastage, - isSwitchable: isSwitchable ?? this.isSwitchable, - switchStatus: switchStatus ?? this.switchStatus, - hostelName: hostelName ?? this.hostelName, - secretCode: secretCode ?? this.secretCode, - isLeaveToggleOutdated: - isLeaveToggleOutdated ?? this.isLeaveToggleOutdated, - isOutdated: isOutdated ?? this.isOutdated, - isCouponOutdated: isCouponOutdated ?? this.isCouponOutdated, - startDateTime: startDateTime ?? this.startDateTime, - endDateTime: endDateTime ?? this.endDateTime, - ); - } + required bool isOutdated, + required bool isLeaveToggleOutdated, + required bool isCouponOutdated, + required DateTime startDateTime, + required DateTime endDateTime, + }) = _Meal; String get title { switch (type) { @@ -311,70 +129,41 @@ class Meal { return 'Meal'; } } -} -class LeaveStatus { - int? id; - LeaveStatusEnum status; - - LeaveStatus({ - this.id, - required this.status, - }); - - factory LeaveStatus.fromJson(Map? json) => LeaveStatus( - id: json != null ? json['id'] : null, - status: json != null - ? leaveStatusValues.map[json['status'] ?? 'N']! - : LeaveStatusEnum.N, - ); - - Map toJson() => { - 'id': id, - 'status': leaveStatusValues.reverse[status], - }; + factory Meal.fromJson(Map json) => _$MealFromJson(json); } -class CouponStatus { - int? id; - CouponStatusEnum status; +@freezed +class LeaveStatus with _$LeaveStatus { + const factory LeaveStatus({ + int? id, + @Default(LeaveStatusEnum.N) LeaveStatusEnum status, + }) = _LeaveStatus; - CouponStatus({ - this.id, - required this.status, - }); + factory LeaveStatus.fromJson(Map json) => + _$LeaveStatusFromJson(json); +} - factory CouponStatus.fromJson(Map? json) => CouponStatus( - id: json?['id'], - status: couponStatusValues.map[json?['status'] ?? 'N']!, - ); +@freezed +class CouponStatus with _$CouponStatus { + const factory CouponStatus({ + int? id, + @Default(CouponStatusEnum.N) required CouponStatusEnum status, + }) = _CouponStatus; - Map toJson() => { - 'id': id, - 'status': couponStatusValues.reverse[status], - }; + factory CouponStatus.fromJson(Map json) => + _$CouponStatusFromJson(json); } -class SwitchStatus { - int id; - SwitchStatusEnum status; - - SwitchStatus({ - required this.id, - required this.status, - }); - - factory SwitchStatus.fromJson(Map? json) => SwitchStatus( - id: json != null ? (json['id'] ?? 0) : 0, - status: json != null - ? switchStatusValues.map[json['status'] ?? 'N']! - : SwitchStatusEnum.N, - ); - - Map toJson() => { - 'id': id, - 'status': switchStatusValues.reverse[status], - }; +@freezed +class SwitchStatus with _$SwitchStatus { + const factory SwitchStatus({ + int? id, + @Default(SwitchStatusEnum.N) required SwitchStatusEnum status, + }) = _SwitchStatus; + + factory SwitchStatus.fromJson(Map json) => + _$SwitchStatusFromJson(json); } enum LeaveStatusEnum { N, A, D, P, U } From 00a6eaacaa8f87a1a197e90c5642a6ec81f21fa3 Mon Sep 17 00:00:00 2001 From: NanoNish Date: Thu, 24 Aug 2023 04:13:29 +0530 Subject: [PATCH 09/21] feat: add multimessing models --- lib/domain/models/multimessing/switch.dart | 21 ++------ .../models/multimessing/switchable_meal.dart | 48 ++++--------------- 2 files changed, 15 insertions(+), 54 deletions(-) diff --git a/lib/domain/models/multimessing/switch.dart b/lib/domain/models/multimessing/switch.dart index d448693b..1a82c60a 100644 --- a/lib/domain/models/multimessing/switch.dart +++ b/lib/domain/models/multimessing/switch.dart @@ -1,9 +1,8 @@ -import 'dart:convert'; +import 'package:json_annotation/json_annotation.dart'; -Switch switchFromJson(String str) => Switch.fromJson(json.decode(str)); - -String switchToJson(Switch data) => json.encode(data.toJson()); +part 'switch.g.dart'; +@JsonSerializable(fieldRename: FieldRename.snake) class Switch { int id; int toMeal; @@ -17,17 +16,7 @@ class Switch { required this.status, }); - factory Switch.fromJson(Map json) => Switch( - id: json['id'], - toMeal: json['to_meal'], - secretCode: json['secret_code'], - status: json['status'], - ); + factory Switch.fromJson(Map json) => _$SwitchFromJson(json); - Map toJson() => { - 'id': id, - 'to_meal': toMeal, - 'secret_code': secretCode, - 'status': status, - }; + Map toJson() => _$SwitchToJson(this); } diff --git a/lib/domain/models/multimessing/switchable_meal.dart b/lib/domain/models/multimessing/switchable_meal.dart index 7cc0fdda..c86adf59 100644 --- a/lib/domain/models/multimessing/switchable_meal.dart +++ b/lib/domain/models/multimessing/switchable_meal.dart @@ -1,12 +1,8 @@ -import 'dart:convert'; +import 'package:json_annotation/json_annotation.dart'; -List switchableMealsFromJson(String str) => - List.from( - json.decode(str).map((x) => SwitchableMeal.fromJson(x))); - -String switchableMealsToJson(List data) => - json.encode(List.from(data.map((x) => x.toJson()))); +part 'switchable_meal.g.dart'; +@JsonSerializable(fieldRename: FieldRename.snake, explicitToJson: true) class SwitchableMeal { int id; String type; @@ -28,29 +24,13 @@ class SwitchableMeal { required this.hostelName, }); - factory SwitchableMeal.fromJson(Map json) => SwitchableMeal( - id: json['id'], - type: json['type'], - items: List.from(json['items'].map((x) => Item.fromJson(x))), - startTime: json['start_time'], - endTime: json['end_time'], - leaveStatus: json['leave_status'], - wastage: json['wastage'], - hostelName: json['hostel_name'], - ); - - Map toJson() => { - 'id': id, - 'type': type, - 'items': List.from(items.map((x) => x.toJson())), - 'start_time': startTime, - 'end_time': endTime, - 'leave_status': leaveStatus, - 'wastage': wastage, - 'hostel_name': hostelName, - }; + factory SwitchableMeal.fromJson(Map json) => + _$SwitchableMealFromJson(json); + + Map toJson() => _$SwitchableMealToJson(this); } +@JsonSerializable() class Item { int id; String type; @@ -62,15 +42,7 @@ class Item { required this.name, }); - factory Item.fromJson(Map json) => Item( - id: json['id'], - type: json['type'], - name: json['name'], - ); + factory Item.fromJson(Map json) => _$ItemFromJson(json); - Map toJson() => { - 'id': id, - 'type': type, - 'name': name, - }; + Map toJson() => _$ItemToJson(this); } From a91b8a8e246edcddd37d14911b6e93001e31e44d Mon Sep 17 00:00:00 2001 From: NanoNish Date: Thu, 24 Aug 2023 04:19:52 +0530 Subject: [PATCH 10/21] feat: add transaction models --- lib/domain/models/transaction/faq.dart | 21 +--- .../transaction/paginated_yearly_rebate.dart | 99 ++++++------------- 2 files changed, 36 insertions(+), 84 deletions(-) diff --git a/lib/domain/models/transaction/faq.dart b/lib/domain/models/transaction/faq.dart index 8fe85509..d57eb21a 100644 --- a/lib/domain/models/transaction/faq.dart +++ b/lib/domain/models/transaction/faq.dart @@ -1,11 +1,8 @@ -import 'dart:convert'; +import 'package:json_annotation/json_annotation.dart'; -List faqFromJson(String str) => - List.from(json.decode(str).map((x) => Faq.fromJson(x))); - -String faqToJson(List data) => - json.encode(List.from(data.map((x) => x.toJson()))); +part 'faq.g.dart'; +@JsonSerializable() class Faq { int id; String question; @@ -17,15 +14,7 @@ class Faq { required this.answer, }); - factory Faq.fromJson(Map json) => Faq( - id: json['id'], - question: json['question'], - answer: json['answer'], - ); + factory Faq.fromJson(Map json) => _$FaqFromJson(json); - Map toJson() => { - 'id': id, - 'question': question, - 'answer': answer, - }; + Map toJson() => _$FaqToJson(this); } diff --git a/lib/domain/models/transaction/paginated_yearly_rebate.dart b/lib/domain/models/transaction/paginated_yearly_rebate.dart index 86eaca21..9ed0df66 100644 --- a/lib/domain/models/transaction/paginated_yearly_rebate.dart +++ b/lib/domain/models/transaction/paginated_yearly_rebate.dart @@ -1,73 +1,36 @@ -import 'dart:convert'; - -PaginatedYearlyRebate paginatedYearlyRebateFromJson(String str) => - PaginatedYearlyRebate.fromJson(json.decode(str)); - -String paginatedYearlyRebateToJson(PaginatedYearlyRebate data) => - json.encode(data.toJson()); - -class PaginatedYearlyRebate { - int count; - bool hasNext; - bool hasPrevious; - List results; - - PaginatedYearlyRebate({ - required this.count, - required this.hasNext, - required this.hasPrevious, - required this.results, - }); +import 'package:freezed_annotation/freezed_annotation.dart'; + +part 'paginated_yearly_rebate.freezed.dart'; +part 'paginated_yearly_rebate.g.dart'; + +@freezed +class PaginatedYearlyRebate with _$PaginatedYearlyRebate { + @JsonSerializable(fieldRename: FieldRename.snake, explicitToJson: true) + + const factory PaginatedYearlyRebate({ + required int count, + required bool hasNext, + required bool hasPrevious, + required List results, + }) = _PaginatedYearlyRebate; factory PaginatedYearlyRebate.fromJson(Map json) => - PaginatedYearlyRebate( - count: json['count'], - hasNext: json['has_next'], - hasPrevious: json['has_previous'], - results: List.from( - json['results'].map((x) => YearlyRebate.fromJson(x))), - ); - - Map toJson() => { - 'count': count, - 'has_next': hasNext, - 'has_previous': hasPrevious, - 'results': List.from(results.map((x) => x.toJson())), - }; + _$PaginatedYearlyRebateFromJson(json); } -class YearlyRebate { - int monthId; - int year; - dynamic bill; - int expenses; - num rebate; - int startDate; - - YearlyRebate({ - required this.monthId, - required this.year, - required this.bill, - required this.expenses, - required this.rebate, - required this.startDate, - }); - - factory YearlyRebate.fromJson(Map json) => YearlyRebate( - monthId: json['month_id'], - year: json['year'], - bill: json['bill'], - expenses: json['expenses'], - rebate: json['rebate'], - startDate: json['start_date'], - ); - - Map toJson() => { - 'month_id': monthId, - 'year': year, - 'bill': bill, - 'expenses': expenses, - 'rebate': rebate, - 'start_date': startDate, - }; +@freezed +class YearlyRebate with _$YearlyRebate { + @JsonSerializable(fieldRename: FieldRename.snake) + + const factory YearlyRebate({ + required int monthId, + required int year, + required dynamic bill, + required int expenses, + required num rebate, + required int startDate, + }) = _YearlyRebate; + + factory YearlyRebate.fromJson(Map json) => + _$YearlyRebateFromJson(json); } From 30dc3dd7b65d4777bbb5b9595bf7d62dac84af52 Mon Sep 17 00:00:00 2001 From: NanoNish Date: Thu, 24 Aug 2023 04:51:17 +0530 Subject: [PATCH 11/21] feat: add user models --- lib/domain/models/user/notification.dart | 54 ++++---- lib/domain/models/user/oauth_user.dart | 21 ++-- .../models/user/paginated_notifications.dart | 31 ----- lib/domain/models/user/user.dart | 116 +++++------------- .../coupons/components/coupon_card.dart | 2 +- .../your_meal_daily_cards_combined.dart | 6 +- 6 files changed, 65 insertions(+), 165 deletions(-) delete mode 100644 lib/domain/models/user/paginated_notifications.dart diff --git a/lib/domain/models/user/notification.dart b/lib/domain/models/user/notification.dart index 8e25f0be..e5f2f77e 100644 --- a/lib/domain/models/user/notification.dart +++ b/lib/domain/models/user/notification.dart @@ -1,34 +1,32 @@ -import 'dart:convert'; +import 'package:freezed_annotation/freezed_annotation.dart'; -Notification notificationFromJson(String str) => - Notification.fromJson(json.decode(str)); +part 'notification.freezed.dart'; +part 'notification.g.dart'; -String notificationToJson(Notification data) => json.encode(data.toJson()); +@freezed +class Notification with _$Notification { + @JsonSerializable(fieldRename: FieldRename.snake) + const factory Notification({ + required int id, + required int dateCreated, + required String title, + required String message, + }) = _Notification; -class Notification { - int id; - int dateCreated; - String title; - String message; - - Notification({ - required this.id, - required this.dateCreated, - required this.title, - required this.message, - }); + factory Notification.fromJson(Map json) => + _$NotificationFromJson(json); +} - factory Notification.fromJson(Map json) => Notification( - id: json['id'], - dateCreated: json['date_created'], - title: json['title'], - message: json['message'], - ); +@freezed +class PaginatedNotifications with _$PaginatedNotifications { + @JsonSerializable(fieldRename: FieldRename.snake, explicitToJson: true) + const factory PaginatedNotifications({ + required int count, + required bool hasNext, + required bool hasPrevious, + required List results, + }) = _PaginatedNotifications; - Map toJson() => { - 'id': id, - 'date_created': dateCreated, - 'title': title, - 'message': message, - }; + factory PaginatedNotifications.fromJson(Map json) => + _$PaginatedNotificationsFromJson(json); } diff --git a/lib/domain/models/user/oauth_user.dart b/lib/domain/models/user/oauth_user.dart index ad5d47fc..0de69143 100644 --- a/lib/domain/models/user/oauth_user.dart +++ b/lib/domain/models/user/oauth_user.dart @@ -1,12 +1,13 @@ -import 'dart:convert'; - import 'package:appetizer/domain/models/user/user.dart'; +import 'package:json_annotation/json_annotation.dart'; -OAuthUser oauthUserFromJson(String str) => OAuthUser.fromJson(json.decode(str)); +import 'package:json_annotation/json_annotation.dart'; -String oauthuserToJson(OAuthUser data) => json.encode(data.toJson()); +part 'oauth_user.g.dart'; +@JsonSerializable(fieldRename: FieldRename.snake, explicitToJson: true) class OAuthUser { + String? token; User studentData; bool isNew; @@ -17,15 +18,7 @@ class OAuthUser { required this.isNew, }); - factory OAuthUser.fromJson(Map json) => OAuthUser( - token: json['token'], - studentData: User.fromJson(json['student_data']), - isNew: json['is_new'], - ); + factory OAuthUser.fromJson(Map json) => _$OAuthUserFromJson(json); - Map toJson() => { - 'token': token, - 'student_data': studentData.toJson(), - 'is_new': isNew, - }; + Map toJson() => _$OAuthUserToJson(this); } diff --git a/lib/domain/models/user/paginated_notifications.dart b/lib/domain/models/user/paginated_notifications.dart deleted file mode 100644 index c727c105..00000000 --- a/lib/domain/models/user/paginated_notifications.dart +++ /dev/null @@ -1,31 +0,0 @@ -import 'package:appetizer/domain/models/user/notification.dart'; - -class PaginatedNotifications { - int count; - bool hasNext; - bool hasPrevious; - List results; - - PaginatedNotifications({ - required this.count, - required this.hasNext, - required this.hasPrevious, - required this.results, - }); - - factory PaginatedNotifications.fromJson(Map json) => - PaginatedNotifications( - count: json['count'], - hasNext: json['has_next'], - hasPrevious: json['has_previous'], - results: List.from( - json['results'].map((x) => Notification.fromJson(x))), - ); - - Map toJson() => { - 'count': count, - 'has_next': hasNext, - 'has_previous': hasPrevious, - 'results': List.from(results.map((x) => x.toJson())), - }; -} diff --git a/lib/domain/models/user/user.dart b/lib/domain/models/user/user.dart index afbeb063..0de68b8a 100644 --- a/lib/domain/models/user/user.dart +++ b/lib/domain/models/user/user.dart @@ -1,93 +1,33 @@ -import 'dart:convert'; +import 'package:freezed_annotation/freezed_annotation.dart'; -User userFromJson(String str) => User.fromJson(json.decode(str)); +part 'user.freezed.dart'; +part 'user.g.dart'; -String userToJson(User data) => json.encode(data.toJson()); +@freezed +class User with _$User{ + @JsonSerializable(fieldRename: FieldRename.snake) -class User { - String email; - String hostelName; - String hostelCode; - String? roomNo; - int enrNo; - String name; - String contactNo; - String? branch; - dynamic imageUrl; - bool isCheckedOut; - int? lastUpdated; - int? leavesLeft; - dynamic dob; - String? gender; - dynamic degree; - dynamic admissionYear; - String? role; - String? token; - bool isNew; + const factory User({ + required String email, + required String hostelName, + required String hostelCode, + String? roomNo, + required int enrNo, + required String name, + required String contactNo, + String? branch, + required dynamic imageUrl, + required bool isCheckedOut, + int? lastUpdated, + int? leavesLeft, + required dynamic dob, + String? gender, + required dynamic degree, + required dynamic admissionYear, + String? role, + String? token, + required bool isNew, + }) = _User; - User({ - required this.email, - required this.hostelName, - required this.hostelCode, - this.roomNo, - required this.enrNo, - required this.name, - required this.contactNo, - required this.branch, - required this.imageUrl, - required this.isCheckedOut, - this.lastUpdated, - this.leavesLeft, - required this.dob, - this.gender, - required this.degree, - required this.admissionYear, - this.role, - this.token, - required this.isNew, - }); - - factory User.fromJson(Map json) => User( - email: json['email'], - hostelName: json['hostel_name'], - hostelCode: json['hostel_code'], - roomNo: json['room_no'], - enrNo: json['enr_no'], - name: json['name'], - contactNo: json['contact_no'], - branch: json['branch'], - imageUrl: json['image_url'], - isCheckedOut: json['is_checked_out'] ?? false, - lastUpdated: json['last_updated'], - leavesLeft: json['leaves_left'], - dob: json['dob'], - gender: json['gender'], - degree: json['degree'], - admissionYear: json['admission_year'], - role: json['role'], - token: json['token'], - isNew: json['is_new'] ?? true, - ); - - Map toJson() => { - 'email': email, - 'hostel_name': hostelName, - 'hostel_code': hostelCode, - 'room_no': roomNo, - 'enr_no': enrNo, - 'name': name, - 'contact_no': contactNo, - 'branch': branch, - 'image_url': imageUrl, - 'is_checked_out': isCheckedOut, - 'last_updated': lastUpdated, - 'leaves_left': leavesLeft, - 'dob': dob, - 'gender': gender, - 'degree': degree, - 'admission_year': admissionYear, - 'role': role, - 'token': token, - 'is_new': isNew, - }; + factory User.fromJson(Map json) => _$UserFromJson(json); } diff --git a/lib/presentation/coupons/components/coupon_card.dart b/lib/presentation/coupons/components/coupon_card.dart index 34780f31..3716b4e0 100644 --- a/lib/presentation/coupons/components/coupon_card.dart +++ b/lib/presentation/coupons/components/coupon_card.dart @@ -52,7 +52,7 @@ class CouponCard extends StatelessWidget { mainAxisSize: MainAxisSize.min, children: [ Text( - coupon.title, + coupon.id.toString(), textAlign: TextAlign.left, style: const TextStyle( color: Color(0xFF111111), diff --git a/lib/presentation/week_menu/components/yourMealDailyCardsCombined/your_meal_daily_cards_combined.dart b/lib/presentation/week_menu/components/yourMealDailyCardsCombined/your_meal_daily_cards_combined.dart index b7558b78..1a6aa40e 100644 --- a/lib/presentation/week_menu/components/yourMealDailyCardsCombined/your_meal_daily_cards_combined.dart +++ b/lib/presentation/week_menu/components/yourMealDailyCardsCombined/your_meal_daily_cards_combined.dart @@ -43,9 +43,9 @@ class YourMealDailyCardsCombined extends StatelessWidget { ? dailyItems.breakfast : (meal.type == MealType.L ? dailyItems.lunch - : (meal.type == MealType.S - ? dailyItems.snack - : dailyItems.dinner)), + : (meal.type == MealType.D + ? dailyItems.dinner + : dailyItems.snack!)), meal: meal, ); }, From a10fcf9a45901665952c14cc1ff9cf7b80946331 Mon Sep 17 00:00:00 2001 From: NanoNish Date: Thu, 24 Aug 2023 17:57:50 +0530 Subject: [PATCH 12/21] feat: add default values to models --- lib/domain/models/appetizer_version.dart | 6 +----- lib/domain/models/menu/week_menu.dart | 15 +++++++++------ lib/domain/models/user/user.dart | 4 ++-- 3 files changed, 12 insertions(+), 13 deletions(-) diff --git a/lib/domain/models/appetizer_version.dart b/lib/domain/models/appetizer_version.dart index f59307d9..cf65d0d7 100644 --- a/lib/domain/models/appetizer_version.dart +++ b/lib/domain/models/appetizer_version.dart @@ -2,17 +2,13 @@ import 'package:json_annotation/json_annotation.dart'; part 'appetizer_version.g.dart'; -@JsonSerializable() +@JsonSerializable(fieldRename: FieldRename.snake) class AppetizerVersion { String number; String platform; - @JsonKey(name: "expiry_date") dynamic expiryDate; - @JsonKey(name: "is_expired") bool isExpired; - @JsonKey(name: "is_latest") bool isLatest; - @JsonKey(name: "date_created") int dateCreated; AppetizerVersion({ diff --git a/lib/domain/models/menu/week_menu.dart b/lib/domain/models/menu/week_menu.dart index c9bcd494..4cac3cd2 100644 --- a/lib/domain/models/menu/week_menu.dart +++ b/lib/domain/models/menu/week_menu.dart @@ -6,6 +6,7 @@ part 'week_menu.freezed.dart'; part 'week_menu.g.dart'; // TODO: remove enums from this file +// TODO: check for DateTime parsing (different in different api) @freezed class WeekMenu with _$WeekMenu { @@ -99,18 +100,20 @@ class Meal with _$Meal { required MealType type, CostType? costType, required List items, - required DateTime startTime, - required DateTime endTime, + // TODO: write getters + // required DateTime startTime, + // required DateTime endTime, required LeaveStatus leaveStatus, required CouponStatus couponStatus, required dynamic wastage, - required bool isSwitchable, + @Default(false) bool isSwitchable, required SwitchStatus switchStatus, String? hostelName, String? secretCode, - required bool isOutdated, - required bool isLeaveToggleOutdated, - required bool isCouponOutdated, + // TODO: write getters + // required bool isOutdated, + // required bool isLeaveToggleOutdated, + // required bool isCouponOutdated, required DateTime startDateTime, required DateTime endDateTime, }) = _Meal; diff --git a/lib/domain/models/user/user.dart b/lib/domain/models/user/user.dart index 0de68b8a..f94e935b 100644 --- a/lib/domain/models/user/user.dart +++ b/lib/domain/models/user/user.dart @@ -17,7 +17,7 @@ class User with _$User{ required String contactNo, String? branch, required dynamic imageUrl, - required bool isCheckedOut, + @Default(false) bool isCheckedOut, int? lastUpdated, int? leavesLeft, required dynamic dob, @@ -26,7 +26,7 @@ class User with _$User{ required dynamic admissionYear, String? role, String? token, - required bool isNew, + @Default(true) bool isNew, }) = _User; factory User.fromJson(Map json) => _$UserFromJson(json); From 8a7032218ce0c5b93154f98ca031494d431bf8ba Mon Sep 17 00:00:00 2001 From: NanoNish Date: Thu, 24 Aug 2023 18:39:36 +0530 Subject: [PATCH 13/21] feat: add endpoints --- lib/data/constants/api_endpoints.dart | 33 +++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/lib/data/constants/api_endpoints.dart b/lib/data/constants/api_endpoints.dart index 191d2ad2..0ff29df4 100644 --- a/lib/data/constants/api_endpoints.dart +++ b/lib/data/constants/api_endpoints.dart @@ -5,4 +5,37 @@ class ApiEnpoints { static const String checkVersion = '/panel/version/expire/{platform}/{versionNumber}'; + + static const String coupon = '/api/coupon'; + static const String couponWithId = '/api/coupon/{couponId}'; + + static const String submittedFeedback = '/api/feedback/all/'; + static const String responseOfFeedback = '/api/feedback/response/list/'; + static const String newFeedback = '/api/feedback/'; + + static const String remainingLeaves = '/api/leave/count/remaining/'; + static const String getLeaves = '/api/leave/all/'; + static const String check = '/api/leave/check/'; + static const String leave = '/api/leave/'; + static const String cancelLeave = '/api/leave/meal/{id}'; + + static const String weekMenuMultimessing = '/api/menu/week/v2/'; + static const String weekMenuForYourMeals = '/api/menu/my_week/'; + static const String weekMenu = '/api/menu/week/'; + static const String dayMenu = '/api/menu/{week}/{dayOfWeek}'; + + // TODO: add multimessing endpoints + + static const String monthlyRebate = '/api/transaction/rebate/current/'; + static const String yearlyRebate = '/api/transaction/list/expenses/'; + static const String faqs = '/api/faqs/'; + + static const String login = '/api/user/login/'; + static const String logout = '/api/user/logout/'; + static const String user = '/api/user/me/'; + static const String password = '/api/user/me/password/'; + static const String resetpassword = '/api/user/me/password/reset/'; + static const String oAuthRedirect = '/api/user/oauth/omniport/redirect/'; + static const String oAuthComplete = '/api/user/oauth/complete/'; + static const String notifications = '/api/user/message/list/'; } From b4e9013be93bea1ee369eb7a4a80fa7a2994e05f Mon Sep 17 00:00:00 2001 From: NanoNish Date: Thu, 24 Aug 2023 18:49:09 +0530 Subject: [PATCH 14/21] feat: add coupon and feedback to api service --- lib/data/services/remote/api_service.dart | 37 ++++++++++++++++++++++- 1 file changed, 36 insertions(+), 1 deletion(-) diff --git a/lib/data/services/remote/api_service.dart b/lib/data/services/remote/api_service.dart index 56252895..3b5a67cf 100644 --- a/lib/data/services/remote/api_service.dart +++ b/lib/data/services/remote/api_service.dart @@ -1,6 +1,10 @@ import 'package:appetizer/data/constants/api_endpoints.dart'; import 'package:appetizer/domain/models/appetizer_version.dart'; -import 'package:dio/dio.dart'; +import 'package:appetizer/domain/models/coupon/coupon.dart'; +import 'package:appetizer/domain/models/feedback/appetizer_feedback.dart'; +import 'package:appetizer/domain/models/feedback/feedback_response.dart'; +import 'package:appetizer/domain/models/menu/week_menu.dart'; +import 'package:dio/dio.dart' hide Headers; import 'package:retrofit/retrofit.dart'; part 'api_service.g.dart'; @@ -14,4 +18,35 @@ abstract class ApiService { @Path("platform") String platform, @Path("versionNumber") String versionNumber, ); + + // TODO: add token to all headers + // TODO: find a way to remove maps + + // Coupon API + + @POST(ApiEnpoints.coupon) + Future applyForCoupon( + @Body() Map map, + ); + + @PATCH(ApiEnpoints.couponWithId) + Future cancelCoupon( + @Path("couponId") String couponId, + @Body() Map map, + ); + + // Feedback API + + @GET(ApiEnpoints.submittedFeedback) + Future> submittedFeedbacks(); + + @GET(ApiEnpoints.responseOfFeedback) + Future> responseOfFeedbacks(); + + @POST(ApiEnpoints.newFeedback) + Future newFeedback( + @Body() Map map, + ); + + } From f4d7ebcc15c1291015235739532366e24cf96e36 Mon Sep 17 00:00:00 2001 From: NanoNish Date: Thu, 24 Aug 2023 19:09:13 +0530 Subject: [PATCH 15/21] feat: add leave and menu to api service --- lib/data/constants/api_endpoints.dart | 2 +- lib/data/services/remote/api_service.dart | 75 ++++++++++++++++++++--- 2 files changed, 67 insertions(+), 10 deletions(-) diff --git a/lib/data/constants/api_endpoints.dart b/lib/data/constants/api_endpoints.dart index 0ff29df4..fb8d6a35 100644 --- a/lib/data/constants/api_endpoints.dart +++ b/lib/data/constants/api_endpoints.dart @@ -1,6 +1,6 @@ import 'package:appetizer/data/constants/env_config.dart'; -class ApiEnpoints { +class ApiEndpoints { static const String baseUrl = EnvironmentConfig.BASE_URL; static const String checkVersion = diff --git a/lib/data/services/remote/api_service.dart b/lib/data/services/remote/api_service.dart index 3b5a67cf..940aa272 100644 --- a/lib/data/services/remote/api_service.dart +++ b/lib/data/services/remote/api_service.dart @@ -1,19 +1,20 @@ import 'package:appetizer/data/constants/api_endpoints.dart'; import 'package:appetizer/domain/models/appetizer_version.dart'; -import 'package:appetizer/domain/models/coupon/coupon.dart'; import 'package:appetizer/domain/models/feedback/appetizer_feedback.dart'; import 'package:appetizer/domain/models/feedback/feedback_response.dart'; +import 'package:appetizer/domain/models/leaves/paginated_leaves.dart'; import 'package:appetizer/domain/models/menu/week_menu.dart'; import 'package:dio/dio.dart' hide Headers; import 'package:retrofit/retrofit.dart'; +import 'dart:async'; part 'api_service.g.dart'; -@RestApi(baseUrl: ApiEnpoints.baseUrl) +@RestApi(baseUrl: ApiEndpoints.baseUrl) abstract class ApiService { factory ApiService(Dio dio, {String baseUrl}) = _ApiService; - @GET(ApiEnpoints.checkVersion) + @GET(ApiEndpoints.checkVersion) Future checkVersion( @Path("platform") String platform, @Path("versionNumber") String versionNumber, @@ -24,12 +25,12 @@ abstract class ApiService { // Coupon API - @POST(ApiEnpoints.coupon) + @POST(ApiEndpoints.coupon) Future applyForCoupon( @Body() Map map, ); - @PATCH(ApiEnpoints.couponWithId) + @PATCH(ApiEndpoints.couponWithId) Future cancelCoupon( @Path("couponId") String couponId, @Body() Map map, @@ -37,16 +38,72 @@ abstract class ApiService { // Feedback API - @GET(ApiEnpoints.submittedFeedback) + @GET(ApiEndpoints.submittedFeedback) Future> submittedFeedbacks(); - @GET(ApiEnpoints.responseOfFeedback) + @GET(ApiEndpoints.responseOfFeedback) Future> responseOfFeedbacks(); - @POST(ApiEnpoints.newFeedback) + @POST(ApiEndpoints.newFeedback) Future newFeedback( @Body() Map map, ); - + // Leave API + + @GET(ApiEndpoints.remainingLeaves) + Future remainingLeaves(); + + @GET(ApiEndpoints.getLeaves) + Future getLeaves( + @Query("year") String year, + @Query("month") String? month, + ); + + @POST(ApiEndpoints.check) + Future checkout( + @Body() Map map, + ); + + @POST(ApiEndpoints.check) + Future checkin( + @Body() Map map, + ); + + @POST(ApiEndpoints.leave) + Future leave( + @Body() Map map, + ); + + @DELETE(ApiEndpoints.cancelLeave) + Future cancelLeave( + @Path("id") int id, + ); + + // Menu API + + @GET(ApiEndpoints.weekMenuMultimessing) + Future weekMenuMultimessing( + @Query("hostel") String hostelCode, + @Query("week_id") String week, + ); + + @GET(ApiEndpoints.weekMenuForYourMeals) + Future weekMenuForYourMeals( + @Query("week_id") String week, + ); + + @GET(ApiEndpoints.weekMenu) + Future weekMenuByWeekId( + @Query("week_id") String week, + ); + + @GET(ApiEndpoints.weekMenu) + Future currentWeekMenu(); + + @GET(ApiEndpoints.dayMenu) + Future dayMenu( + @Path("week") String week, + @Path("dayOfWeek") String dayOfWeek, + ); } From 948000d30d77b4850473e832ba3175f7fdf6c835 Mon Sep 17 00:00:00 2001 From: NanoNish Date: Thu, 24 Aug 2023 19:17:08 +0530 Subject: [PATCH 16/21] feat: add user and transaction to api service --- lib/data/services/remote/api_service.dart | 65 +++++++++++++++++++++++ 1 file changed, 65 insertions(+) diff --git a/lib/data/services/remote/api_service.dart b/lib/data/services/remote/api_service.dart index 940aa272..8d7fe602 100644 --- a/lib/data/services/remote/api_service.dart +++ b/lib/data/services/remote/api_service.dart @@ -4,6 +4,10 @@ import 'package:appetizer/domain/models/feedback/appetizer_feedback.dart'; import 'package:appetizer/domain/models/feedback/feedback_response.dart'; import 'package:appetizer/domain/models/leaves/paginated_leaves.dart'; import 'package:appetizer/domain/models/menu/week_menu.dart'; +import 'package:appetizer/domain/models/transaction/faq.dart'; +import 'package:appetizer/domain/models/user/notification.dart'; +import 'package:appetizer/domain/models/user/oauth_user.dart'; +import 'package:appetizer/domain/models/user/user.dart'; import 'package:dio/dio.dart' hide Headers; import 'package:retrofit/retrofit.dart'; import 'dart:async'; @@ -106,4 +110,65 @@ abstract class ApiService { @Path("week") String week, @Path("dayOfWeek") String dayOfWeek, ); + + // TODO: add Multimessing API + + // Transaction API + + @GET(ApiEndpoints.monthlyRebate) + Future getMonthlyRebate(); + + @GET(ApiEndpoints.yearlyRebate) + Future getYearlyRebate( + @Query("year") int year, + ); + + @GET(ApiEndpoints.faqs) + Future> getFAQs(); + + // User API + + @POST(ApiEndpoints.login) + Future login( + @Body() Map map, + ); + + @POST(ApiEndpoints.logout) + Future logout(); + + @GET(ApiEndpoints.user) + Future getCurrentUser(); + + @PATCH(ApiEndpoints.user) + Future updateUser( + @Body() Map map, + ); + + @PATCH(ApiEndpoints.user) + Future updateFcmTokenForUser( + @Body() Map map, + ); + + @PUT(ApiEndpoints.password) + Future changePassword( + @Body() Map map, + ); + + @POST(ApiEndpoints.resetpassword) + Future resetPassword( + @Body() Map map, + ); + + @GET(ApiEndpoints.oAuthRedirect) + Future oAuthRedirect( + @Query("code") String code, + ); + + @POST(ApiEndpoints.oAuthComplete) + Future oAuthComplete( + @Body() Map map, + ); + + @GET(ApiEndpoints.notifications) + Future> getNotifications(); } From a2037fb6945187f22370225d204e8df9a3c0a347 Mon Sep 17 00:00:00 2001 From: NanoNish Date: Thu, 24 Aug 2023 22:46:54 +0530 Subject: [PATCH 17/21] feat: add repositories --- lib/data/services/remote/api_service.dart | 31 ++--- .../repositories/coupon_repository.dart | 36 +++++ .../repositories/feedback_repository.dart | 44 ++++++ lib/domain/repositories/leave_repository.dart | 84 ++++++++++++ lib/domain/repositories/menu_repository.dart | 59 +++++++++ .../repositories/transaction_repositroy.dart | 40 ++++++ lib/domain/repositories/user_repository.dart | 125 ++++++++++++++++++ 7 files changed, 404 insertions(+), 15 deletions(-) create mode 100644 lib/domain/repositories/coupon_repository.dart create mode 100644 lib/domain/repositories/feedback_repository.dart create mode 100644 lib/domain/repositories/leave_repository.dart create mode 100644 lib/domain/repositories/menu_repository.dart create mode 100644 lib/domain/repositories/transaction_repositroy.dart create mode 100644 lib/domain/repositories/user_repository.dart diff --git a/lib/data/services/remote/api_service.dart b/lib/data/services/remote/api_service.dart index 8d7fe602..c31c69e1 100644 --- a/lib/data/services/remote/api_service.dart +++ b/lib/data/services/remote/api_service.dart @@ -5,6 +5,7 @@ import 'package:appetizer/domain/models/feedback/feedback_response.dart'; import 'package:appetizer/domain/models/leaves/paginated_leaves.dart'; import 'package:appetizer/domain/models/menu/week_menu.dart'; import 'package:appetizer/domain/models/transaction/faq.dart'; +import 'package:appetizer/domain/models/transaction/paginated_yearly_rebate.dart'; import 'package:appetizer/domain/models/user/notification.dart'; import 'package:appetizer/domain/models/user/oauth_user.dart'; import 'package:appetizer/domain/models/user/user.dart'; @@ -60,27 +61,27 @@ abstract class ApiService { @GET(ApiEndpoints.getLeaves) Future getLeaves( - @Query("year") String year, - @Query("month") String? month, + @Query("year") int year, + @Query("month") int month, ); - @POST(ApiEndpoints.check) - Future checkout( - @Body() Map map, + @GET(ApiEndpoints.getLeaves) + Future getLeavesForYear( + @Query("year") int year, ); @POST(ApiEndpoints.check) - Future checkin( + Future check( @Body() Map map, ); @POST(ApiEndpoints.leave) - Future leave( + Future leave( @Body() Map map, ); @DELETE(ApiEndpoints.cancelLeave) - Future cancelLeave( + Future cancelLeave( @Path("id") int id, ); @@ -89,17 +90,17 @@ abstract class ApiService { @GET(ApiEndpoints.weekMenuMultimessing) Future weekMenuMultimessing( @Query("hostel") String hostelCode, - @Query("week_id") String week, + @Query("week_id") int week, ); @GET(ApiEndpoints.weekMenuForYourMeals) Future weekMenuForYourMeals( - @Query("week_id") String week, + @Query("week_id") int week, ); @GET(ApiEndpoints.weekMenu) Future weekMenuByWeekId( - @Query("week_id") String week, + @Query("week_id") int week, ); @GET(ApiEndpoints.weekMenu) @@ -107,7 +108,7 @@ abstract class ApiService { @GET(ApiEndpoints.dayMenu) Future dayMenu( - @Path("week") String week, + @Path("week") int week, @Path("dayOfWeek") String dayOfWeek, ); @@ -116,10 +117,10 @@ abstract class ApiService { // Transaction API @GET(ApiEndpoints.monthlyRebate) - Future getMonthlyRebate(); + Future getMonthlyRebate(); @GET(ApiEndpoints.yearlyRebate) - Future getYearlyRebate( + Future getYearlyRebate( @Query("year") int year, ); @@ -141,7 +142,7 @@ abstract class ApiService { @PATCH(ApiEndpoints.user) Future updateUser( - @Body() Map map, + @Body() User user, ); @PATCH(ApiEndpoints.user) diff --git a/lib/domain/repositories/coupon_repository.dart b/lib/domain/repositories/coupon_repository.dart new file mode 100644 index 00000000..0b819026 --- /dev/null +++ b/lib/domain/repositories/coupon_repository.dart @@ -0,0 +1,36 @@ +import 'package:appetizer/data/constants/constants.dart'; +import 'package:appetizer/data/services/remote/api_service.dart'; +import 'package:appetizer/domain/models/coupon/coupon.dart'; +import 'package:appetizer/domain/models/failure_model.dart'; +import 'package:appetizer/domain/models/menu/week_menu.dart'; + +class CouponRepositroy { + final ApiService _apiService; + + CouponRepositroy(this._apiService); + + Future applyForCoupon(Coupon coupon) async { + Map map = { + 'meal': coupon.meal, + 'is_active': true, + }; + try { + return await _apiService.applyForCoupon(map); + } catch (e) { + print(e); + throw Failure(AppConstants.GENERIC_FAILURE); + } + } + + Future cancelCoupon(Coupon coupon) async { + Map map = { + 'is_active': false, + }; + try { + return await _apiService.cancelCoupon(coupon.meal, map); + } catch (e) { + print(e); + throw Failure(AppConstants.GENERIC_FAILURE); + } + } +} diff --git a/lib/domain/repositories/feedback_repository.dart b/lib/domain/repositories/feedback_repository.dart new file mode 100644 index 00000000..03b3eb44 --- /dev/null +++ b/lib/domain/repositories/feedback_repository.dart @@ -0,0 +1,44 @@ +import 'package:appetizer/data/constants/constants.dart'; +import 'package:appetizer/data/services/remote/api_service.dart'; +import 'package:appetizer/domain/models/failure_model.dart'; +import 'package:appetizer/domain/models/feedback/appetizer_feedback.dart'; +import 'package:appetizer/domain/models/feedback/feedback_response.dart'; + +class FeedbackRepository { + final ApiService _apiService; + + FeedbackRepository(this._apiService); + + Future> submittedFeedbacks() async { + try { + return await _apiService.submittedFeedbacks(); + } catch (e) { + print(e); + throw Failure(AppConstants.GENERIC_FAILURE); + } + } + + Future> responseOfFeedbacks() async { + try { + return await _apiService.responseOfFeedbacks(); + } catch (e) { + print(e); + throw Failure(AppConstants.GENERIC_FAILURE); + } + } + + Future newFeedback(AppetizerFeedback feedback) async { + Map map = { + 'type': feedback.type, + 'title': feedback.title, + 'message': feedback.message, + 'date_issue': feedback.dateIssue, + }; + try { + return await _apiService.newFeedback(map); + } catch (e) { + print(e); + throw Failure(AppConstants.GENERIC_FAILURE); + } + } +} diff --git a/lib/domain/repositories/leave_repository.dart b/lib/domain/repositories/leave_repository.dart new file mode 100644 index 00000000..bc6eb919 --- /dev/null +++ b/lib/domain/repositories/leave_repository.dart @@ -0,0 +1,84 @@ +import 'package:appetizer/data/constants/constants.dart'; +import 'package:appetizer/data/services/remote/api_service.dart'; +import 'package:appetizer/domain/models/failure_model.dart'; +import 'package:appetizer/domain/models/leaves/paginated_leaves.dart'; +import 'package:appetizer/domain/models/menu/week_menu.dart'; + +class LeaveRepository { + ApiService _apiService; + + LeaveRepository(this._apiService); + + Future remainingLeaves() async { + try { + return await _apiService.remainingLeaves(); + } catch (e) { + // TODO: Handle error + return 0; + } + } + + Future getLeaves(int year, int month) async { + try { + if (month == 0) return await _apiService.getLeavesForYear(year); + return await _apiService.getLeaves(year, month); + } catch (e) { + // TODO: Handle error + return const PaginatedLeaves( + count: 0, + hasNext: false, + hasPrevious: false, + results: [], + ); + } + } + + Future checkout() async { + Map map = { + 'is_checked_out': true, + }; + try { + return await _apiService.check(map); + } catch (e) { + print(e); + throw Failure(AppConstants.GENERIC_FAILURE); + } + } + + Future checkin() async { + Map map = { + 'is_checked_out': false, + }; + try { + return await _apiService.check(map); + } catch (e) { + print(e); + throw Failure(AppConstants.GENERIC_FAILURE); + } + } + + // TODO: check if Future or Future or something else + // TODO: confirm the input params + Future applyLeave(Meal meal) async { + Map map = { + 'meal': meal.id, + }; + try { + return await _apiService.leave(map); + } catch (e) { + print(e); + throw Failure(AppConstants.GENERIC_FAILURE); + } + } + + // TODO: check if Future or Future or something else + // TODO: confirm the input params + Future cancelLeave(Meal meal) async { + try { + return await _apiService.cancelLeave(meal.id); + } catch (e) { + print(e); + throw Failure(AppConstants.GENERIC_FAILURE); + } + } +} diff --git a/lib/domain/repositories/menu_repository.dart b/lib/domain/repositories/menu_repository.dart new file mode 100644 index 00000000..6be211f4 --- /dev/null +++ b/lib/domain/repositories/menu_repository.dart @@ -0,0 +1,59 @@ +import 'package:appetizer/data/constants/constants.dart'; +import 'package:appetizer/data/services/remote/api_service.dart'; +import 'package:appetizer/domain/models/failure_model.dart'; +import 'package:appetizer/domain/models/menu/week_menu.dart'; + +class MenuRepository { + ApiService _apiService; + + MenuRepository(this._apiService); + + // TODO: check correct input params for all functions + + Future weekMenuMultiMessing(String hostelCode, int id) async { + try { + return await _apiService.weekMenuMultimessing(hostelCode, id); + } catch (e) { + print(e); + throw Failure(AppConstants.GENERIC_FAILURE); + } + } + + Future weekMenuForYourMeals(int weekId) async { + try { + return await _apiService.weekMenuForYourMeals(weekId); + } catch (e) { + print(e); + throw Failure(AppConstants.GENERIC_FAILURE); + } + } + + // TODO: weekMenuFromDB() + + Future weekMenuByWeekId(int weekId) async { + try { + return await _apiService.weekMenuByWeekId(weekId); + } catch (e) { + print(e); + throw Failure(AppConstants.GENERIC_FAILURE); + } + } + + Future currentWeekMenu() async { + try { + return await _apiService.currentWeekMenu(); + } catch (e) { + print(e); + throw Failure(AppConstants.GENERIC_FAILURE); + } + } + + Future dayMenu(int week, String dayOfWeek) async { + try { + return await _apiService.dayMenu(week, dayOfWeek); + } catch (e) { + print(e); + throw Failure(AppConstants.GENERIC_FAILURE); + } + } +} diff --git a/lib/domain/repositories/transaction_repositroy.dart b/lib/domain/repositories/transaction_repositroy.dart new file mode 100644 index 00000000..cb74919a --- /dev/null +++ b/lib/domain/repositories/transaction_repositroy.dart @@ -0,0 +1,40 @@ +import 'package:appetizer/data/constants/constants.dart'; +import 'package:appetizer/data/services/remote/api_service.dart'; +import 'package:appetizer/domain/models/failure_model.dart'; +import 'package:appetizer/domain/models/transaction/faq.dart'; +import 'package:appetizer/domain/models/transaction/paginated_yearly_rebate.dart'; + +class TransactionRepository { + ApiService _apiService; + + TransactionRepository(this._apiService); + + // TODO: check correct input params for all functions + + Future getMonthlyRebates() async { + try { + return await _apiService.getMonthlyRebate(); + } catch (e) { + print(e); + throw Failure(AppConstants.GENERIC_FAILURE); + } + } + + Future getYearlyRebates(int year) async { + try { + return await _apiService.getYearlyRebate(year); + } catch (e) { + print(e); + throw Failure(AppConstants.GENERIC_FAILURE); + } + } + + Future> getFAQs() async { + try { + return await _apiService.getFAQs(); + } catch (e) { + print(e); + throw Failure(AppConstants.GENERIC_FAILURE); + } + } +} diff --git a/lib/domain/repositories/user_repository.dart b/lib/domain/repositories/user_repository.dart new file mode 100644 index 00000000..8d78d82f --- /dev/null +++ b/lib/domain/repositories/user_repository.dart @@ -0,0 +1,125 @@ +import 'package:appetizer/data/constants/constants.dart'; +import 'package:appetizer/data/services/remote/api_service.dart'; +import 'package:appetizer/domain/models/failure_model.dart'; +import 'package:appetizer/domain/models/user/notification.dart'; +import 'package:appetizer/domain/models/user/oauth_user.dart'; +import 'package:appetizer/domain/models/user/user.dart'; + +class UserRepository { + ApiService _apiService; + + UserRepository(this._apiService); + + // TODO: check correct input params for all functions + + Future userLogin(String username, String password) async { + Map map = { + 'username': username, + 'password': password, + }; + try { + return await _apiService.login(map); + } catch (e) { + print(e); + throw Failure(AppConstants.GENERIC_FAILURE); + } + } + + Future logout() async { + try { + return await _apiService.logout(); + } catch (e) { + print(e); + throw Failure(AppConstants.GENERIC_FAILURE); + } + } + + Future getCurrentUser() async { + try { + return await _apiService.getCurrentUser(); + } catch (e) { + print(e); + throw Failure(AppConstants.GENERIC_FAILURE); + } + } + + Future updateUser(User user) async { + try { + return await _apiService.updateUser(user); + } catch (e) { + print(e); + throw Failure(AppConstants.GENERIC_FAILURE); + } + } + + Future updateFcmTokenForUser(User user) async { + Map map = { + // TODO: check if fcmToken is token or not + 'fcm_token': user.token, + }; + try { + return await _apiService.updateFcmTokenForUser(map); + } catch (e) { + print(e); + throw Failure(AppConstants.GENERIC_FAILURE); + } + } + + Future changePassword(String oldPassword, String newPassword) async { + Map map = { + 'old_password': oldPassword, + 'new_password': newPassword, + }; + try { + return await _apiService.changePassword(map); + } catch (e) { + print(e); + throw Failure(AppConstants.GENERIC_FAILURE); + } + } + + Future sendResetPasswordLink(User user) async { + Map map = { + 'email': user.email, + }; + try { + return await _apiService.resetPassword(map); + } catch (e) { + print(e); + throw Failure(AppConstants.GENERIC_FAILURE); + } + } + + Future oAuthRedirect(String code) async { + try { + return await _apiService.oAuthRedirect(code); + } catch (e) { + print(e); + throw Failure(AppConstants.GENERIC_FAILURE); + } + } + + Future oAuthComplete(OAuthUser user, String password) async { + Map map = { + 'enr': user.studentData.enrNo, + 'password': password, + 'email': user.studentData.email, + 'contact_no': user.studentData.contactNo, + }; + try { + return await _apiService.oAuthComplete(map); + } catch (e) { + print(e); + throw Failure(AppConstants.GENERIC_FAILURE); + } + } + + Future> getNotifications() async { + try { + return await _apiService.getNotifications(); + } catch (e) { + print(e); + throw Failure(AppConstants.GENERIC_FAILURE); + } + } +} \ No newline at end of file From 2392536a1a54047ac04b5207a727882f00c20349 Mon Sep 17 00:00:00 2001 From: NanoNish Date: Thu, 24 Aug 2023 22:51:26 +0530 Subject: [PATCH 18/21] patch: remove old api --- lib/data/repositories/.gitkeep | 0 lib/data/services/api/coupon_api.dart | 46 ---- lib/data/services/api/feedback_api.dart | 77 ------- lib/data/services/api/leave_api.dart | 126 ----------- lib/data/services/api/menu_api.dart | 141 ------------ lib/data/services/api/multimessing_api.dart | 130 ----------- lib/data/services/api/transaction_api.dart | 69 ------ lib/data/services/api/user_api.dart | 221 ------------------- lib/data/services/api/version_check_api.dart | 32 --- 9 files changed, 842 deletions(-) delete mode 100644 lib/data/repositories/.gitkeep delete mode 100644 lib/data/services/api/coupon_api.dart delete mode 100644 lib/data/services/api/feedback_api.dart delete mode 100644 lib/data/services/api/leave_api.dart delete mode 100644 lib/data/services/api/menu_api.dart delete mode 100644 lib/data/services/api/multimessing_api.dart delete mode 100644 lib/data/services/api/transaction_api.dart delete mode 100644 lib/data/services/api/user_api.dart delete mode 100644 lib/data/services/api/version_check_api.dart diff --git a/lib/data/repositories/.gitkeep b/lib/data/repositories/.gitkeep deleted file mode 100644 index e69de29b..00000000 diff --git a/lib/data/services/api/coupon_api.dart b/lib/data/services/api/coupon_api.dart deleted file mode 100644 index 48b3194b..00000000 --- a/lib/data/services/api/coupon_api.dart +++ /dev/null @@ -1,46 +0,0 @@ -import 'package:appetizer/data/constants/constants.dart'; -import 'package:appetizer/data/constants/env_config.dart'; -import 'package:appetizer/domain/models/failure_model.dart'; -import 'package:appetizer/domain/models/menu/week_menu.dart'; -import 'package:appetizer/utils/api_utils.dart'; -import 'package:flutter/foundation.dart'; -import 'package:http/http.dart' as http; - -class CouponApi { - var headers = {'Content-Type': 'application/json'}; - http.Client client = http.Client(); - - Future applyForCoupon(int mealId) async { - var endpoint = '/api/coupon/'; - var uri = EnvironmentConfig.BASE_URL + endpoint; - - try { - await ApiUtils.addTokenToHeaders(headers); - var jsonResponse = await ApiUtils.post(uri, - headers: headers, body: {'meal': mealId, 'is_active': true}); - - return CouponStatus( - status: CouponStatusEnum.A, - id: jsonResponse['id'], - ); - } on Exception catch (e) { - debugPrint(e.toString()); - throw Failure(AppConstants.GENERIC_FAILURE); - } - } - - Future cancelCoupon(int couponId) async { - var endpoint = '/api/coupon/$couponId'; - var uri = EnvironmentConfig.BASE_URL + endpoint; - - try { - await ApiUtils.addTokenToHeaders(headers); - await ApiUtils.patch(uri, headers: headers, body: {'is_active': false}); - - return CouponStatus(status: CouponStatusEnum.N); - } on Exception catch (e) { - debugPrint(e.toString()); - throw Failure(AppConstants.GENERIC_FAILURE); - } - } -} diff --git a/lib/data/services/api/feedback_api.dart b/lib/data/services/api/feedback_api.dart deleted file mode 100644 index 2371709e..00000000 --- a/lib/data/services/api/feedback_api.dart +++ /dev/null @@ -1,77 +0,0 @@ -import 'package:appetizer/data/constants/constants.dart'; -import 'package:appetizer/data/constants/env_config.dart'; -import 'package:appetizer/domain/models/failure_model.dart'; -import 'package:appetizer/domain/models/feedback/appetizer_feedback.dart'; -import 'package:appetizer/domain/models/feedback/feedback_response.dart'; -import 'package:appetizer/domain/models/feedback/paginated_feedbacks.dart'; -import 'package:appetizer/utils/api_utils.dart'; -import 'package:flutter/foundation.dart'; -import 'package:http/http.dart' as http; - -class FeedbackApi { - var headers = {'Content-Type': 'application/json'}; - http.Client client = http.Client(); - - Future> submittedFeedBacks() async { - var endpoint = '/api/feedback/all/'; - var uri = EnvironmentConfig.BASE_URL + endpoint; - - try { - await ApiUtils.addTokenToHeaders(headers); - var jsonResponse = await ApiUtils.get(uri, headers: headers); - var paginatedFeedbacks = PaginatedFeedbacks.fromJson(jsonResponse); - return paginatedFeedbacks.feedbacks; - } on FormatException catch (e) { - debugPrint(e.message); - throw Failure(AppConstants.BAD_RESPONSE_FORMAT); - } on Exception catch (e) { - debugPrint(e.toString()); - throw Failure(AppConstants.GENERIC_FAILURE); - } - } - - Future> responseOfFeedBacks() async { - var endpoint = '/api/feedback/response/list/'; - var uri = EnvironmentConfig.BASE_URL + endpoint; - - try { - await ApiUtils.addTokenToHeaders(headers); - var jsonResponse = await ApiUtils.get(uri, headers: headers); - var feedbackResponses = List.from( - jsonResponse.map((x) => FeedbackResponse.fromJson(x)), - ); - return feedbackResponses; - } on FormatException catch (e) { - debugPrint(e.message); - throw Failure(AppConstants.BAD_RESPONSE_FORMAT); - } on Exception catch (e) { - debugPrint(e.toString()); - throw Failure(AppConstants.GENERIC_FAILURE); - } - } - - Future newFeedBack( - String type, String title, String message, DateTime dateIssue) async { - var endpoint = '/api/feedback/'; - var uri = EnvironmentConfig.BASE_URL + endpoint; - var json = { - 'type': type, - 'title': title, - 'message': message, - 'date_issue': dateIssue.millisecondsSinceEpoch.toString() - }; - - try { - await ApiUtils.addTokenToHeaders(headers); - var jsonResponse = await ApiUtils.post(uri, headers: headers, body: json); - var feedback = AppetizerFeedback.fromJson(jsonResponse); - return feedback; - } on FormatException catch (e) { - debugPrint(e.message); - throw Failure(AppConstants.BAD_RESPONSE_FORMAT); - } on Exception catch (e) { - debugPrint(e.toString()); - throw Failure(AppConstants.GENERIC_FAILURE); - } - } -} diff --git a/lib/data/services/api/leave_api.dart b/lib/data/services/api/leave_api.dart deleted file mode 100644 index 57bc7c28..00000000 --- a/lib/data/services/api/leave_api.dart +++ /dev/null @@ -1,126 +0,0 @@ -import 'package:appetizer/data/constants/constants.dart'; -import 'package:appetizer/data/constants/env_config.dart'; -import 'package:appetizer/domain/models/failure_model.dart'; -import 'package:appetizer/domain/models/leaves/paginated_leaves.dart'; -import 'package:appetizer/utils/api_utils.dart'; -import 'package:flutter/foundation.dart'; -import 'package:http/http.dart' as http; - -class LeaveApi { - var headers = {'Content-Type': 'application/json'}; - http.Client client = http.Client(); - - Future remainingLeaves() async { - var endPoint = '/api/leave/count/remaining/'; - var uri = EnvironmentConfig.BASE_URL + endPoint; - - try { - await ApiUtils.addTokenToHeaders(headers); - var jsonResponse = await ApiUtils.get(uri, headers: headers); - var count = jsonResponse['count']; - return count; - } on FormatException catch (e) { - debugPrint(e.message); - throw Failure(AppConstants.BAD_RESPONSE_FORMAT); - } on Exception catch (e) { - debugPrint(e.toString()); - throw Failure(AppConstants.GENERIC_FAILURE); - } - } - - Future getLeaves(int year, int month) async { - String endPoint; - if (month == 0) { - endPoint = '/api/leave/all/?year=$year'; - } else { - endPoint = '/api/leave/all/?year=$year&month=$month'; - } - var uri = EnvironmentConfig.BASE_URL + endPoint; - - try { - await ApiUtils.addTokenToHeaders(headers); - var jsonResponse = await ApiUtils.get(uri, headers: headers); - var leaveList = PaginatedLeaves.fromJson(jsonResponse); - return leaveList; - } on FormatException catch (e) { - debugPrint(e.message); - throw Failure(AppConstants.BAD_RESPONSE_FORMAT); - } on Exception catch (e) { - debugPrint(e.toString()); - throw Failure(AppConstants.GENERIC_FAILURE); - } - } - - Future checkout() async { - var endPoint = '/api/leave/check/'; - var uri = EnvironmentConfig.BASE_URL + endPoint; - var json = {'is_checked_out': true}; - - try { - await ApiUtils.addTokenToHeaders(headers); - var jsonResponse = await ApiUtils.post(uri, headers: headers, body: json); - var isCheckedOut = jsonResponse['is_checked_out']; - return isCheckedOut; - } on FormatException catch (e) { - debugPrint(e.message); - throw Failure(AppConstants.BAD_RESPONSE_FORMAT); - } on Exception catch (e) { - debugPrint(e.toString()); - throw Failure(AppConstants.GENERIC_FAILURE); - } - } - - Future checkin() async { - var endPoint = '/api/leave/check/'; - var uri = EnvironmentConfig.BASE_URL + endPoint; - var json = {'is_checked_out': false}; - - try { - await ApiUtils.addTokenToHeaders(headers); - var jsonResponse = await ApiUtils.post(uri, headers: headers, body: json); - var isCheckedOut = jsonResponse['is_checked_out']; - return isCheckedOut; - } on FormatException catch (e) { - debugPrint(e.message); - throw Failure(AppConstants.BAD_RESPONSE_FORMAT); - } on Exception catch (e) { - debugPrint(e.toString()); - throw Failure(AppConstants.GENERIC_FAILURE); - } - } - - Future leave(String id) async { - var endPoint = '/api/leave/'; - var uri = EnvironmentConfig.BASE_URL + endPoint; - var json = {'meal': id}; - - try { - await ApiUtils.addTokenToHeaders(headers); - await ApiUtils.post(uri, headers: headers, body: json); - return true; - } on FormatException catch (e) { - debugPrint(e.message); - throw Failure(AppConstants.BAD_RESPONSE_FORMAT); - } on Exception catch (e) { - debugPrint(e.toString()); - throw Failure(AppConstants.GENERIC_FAILURE); - } - } - - Future cancelLeave(int id) async { - var endPoint = '/api/leave/meal/$id'; - var uri = EnvironmentConfig.BASE_URL + endPoint; - - try { - await ApiUtils.addTokenToHeaders(headers); - final response = await ApiUtils.delete(uri, headers: headers); - return response == null; - } on FormatException catch (e) { - debugPrint(e.message); - throw Failure(AppConstants.BAD_RESPONSE_FORMAT); - } on Exception catch (e) { - debugPrint(e.toString()); - throw Failure(AppConstants.GENERIC_FAILURE); - } - } -} diff --git a/lib/data/services/api/menu_api.dart b/lib/data/services/api/menu_api.dart deleted file mode 100644 index a681e6d5..00000000 --- a/lib/data/services/api/menu_api.dart +++ /dev/null @@ -1,141 +0,0 @@ -import 'package:appetizer/data/constants/constants.dart'; -import 'package:appetizer/data/constants/env_config.dart'; -import 'package:appetizer/domain/models/failure_model.dart'; -import 'package:appetizer/domain/models/menu/week_menu.dart'; -import 'package:appetizer/utils/api_utils.dart'; -import 'package:appetizer/utils/app_exceptions.dart'; -import 'package:flutter/foundation.dart'; -import 'package:http/http.dart' as http; - -class MenuApi { - var headers = {'Content-Type': 'application/json'}; - http.Client client = http.Client(); - - Future weekMenuMultiMessing(int weekId, String hostelCode) async { - var endpoint = '/api/menu/week/v2?hostel=$hostelCode&week_id=$weekId'; - var uri = EnvironmentConfig.BASE_URL + endpoint; - - try { - await ApiUtils.addTokenToHeaders(headers); - var jsonResponse = await ApiUtils.get(uri, headers: headers); - var weekMenu = WeekMenu.fromJson(jsonResponse); - return weekMenu; - } on NotFoundException catch (e) { - debugPrint(e.message); - throw Failure(AppConstants.MENU_NOT_FOUND); - } on FormatException catch (e) { - debugPrint(e.message); - throw Failure(AppConstants.BAD_RESPONSE_FORMAT); - } on Exception catch (e) { - debugPrint(e.toString()); - throw Failure(AppConstants.GENERIC_FAILURE); - } - } - - Future weekMenuForYourMeals(int weekId) async { - var endpoint = '/api/menu/my_week/?week_id=$weekId'; - var uri = EnvironmentConfig.BASE_URL + endpoint; - - try { - await ApiUtils.addTokenToHeaders(headers); - var jsonResponse = await ApiUtils.get(uri, headers: headers); - var weekMenu = WeekMenu.fromJson(jsonResponse); - return weekMenu; - } on NotFoundException catch (e) { - debugPrint(e.message); - throw Failure(AppConstants.MENU_NOT_FOUND); - } on FormatException catch (e) { - debugPrint(e.message); - throw Failure(AppConstants.BAD_RESPONSE_FORMAT); - } on Exception catch (e) { - debugPrint(e.toString()); - throw Failure(AppConstants.GENERIC_FAILURE); - } - } - - Future weekMenuFromDb() async { - // const MEAL_STORE_NAME = 'meals'; - - // A Store with int keys and Map values. - // This Store acts like a persistent map, values of which are Week objects converted to Map - // final mealStore = intMapStoreFactory.store(MEAL_STORE_NAME); - - // Private getter to shorten the amount of code needed to get the - // singleton instance of an opened database. - // var db = await AppDatabase.instance.database; - - try { - // var prefs = await SharedPreferences.getInstance(); - // var record = await mealStore.record(prefs.getInt('mealKey')!).get(db); - // return WeekMenu.fromJson(record!); - // TODO: Implement using Hive - throw NotFoundException("not implemented yet"); - } on FormatException catch (e) { - debugPrint(e.message); - throw Failure(AppConstants.BAD_RESPONSE_FORMAT); - } on Exception catch (e) { - debugPrint(e.toString()); - throw Failure(AppConstants.GENERIC_FAILURE); - } - } - - Future weekMenuByWeekId(int weekId) async { - var endpoint = '/api/menu/week/?week_id=$weekId'; - var uri = EnvironmentConfig.BASE_URL + endpoint; - - try { - await ApiUtils.addTokenToHeaders(headers); - var jsonResponse = await ApiUtils.get(uri, headers: headers); - var weekMenu = WeekMenu.fromJson(jsonResponse); - return weekMenu; - } on NotFoundException catch (e) { - debugPrint(e.message); - throw Failure(AppConstants.MENU_NOT_FOUND); - } on FormatException catch (e) { - debugPrint(e.message); - throw Failure(AppConstants.BAD_RESPONSE_FORMAT); - } on Exception catch (e) { - debugPrint(e.toString()); - throw Failure(AppConstants.GENERIC_FAILURE); - } - } - - Future currentWeekMenu() async { - var endpoint = '/api/menu/week/'; - var uri = EnvironmentConfig.BASE_URL + endpoint; - - try { - await ApiUtils.addTokenToHeaders(headers); - var jsonResponse = await ApiUtils.get(uri, headers: headers); - var weekMenu = WeekMenu.fromJson(jsonResponse); - return weekMenu; - } on NotFoundException catch (e) { - debugPrint(e.message); - throw Failure(AppConstants.MENU_NOT_FOUND); - } on FormatException catch (e) { - debugPrint(e.message); - throw Failure(AppConstants.BAD_RESPONSE_FORMAT); - } on Exception catch (e) { - debugPrint(e.toString()); - throw Failure(AppConstants.GENERIC_FAILURE); - } - } - - Future dayMenu(int week, int dayOfWeek) async { - var endpoint = '/api/menu/$week/$dayOfWeek'; - var uri = EnvironmentConfig.BASE_URL + endpoint; - - try { - await ApiUtils.addTokenToHeaders(headers); - var jsonResponse = await ApiUtils.get(uri, headers: headers); - var dayMenu = DayMenu.fromJson(jsonResponse); - return dayMenu; - } on FormatException catch (e) { - debugPrint(e.message); - throw Failure(AppConstants.BAD_RESPONSE_FORMAT); - } on Exception catch (e) { - debugPrint(e.toString()); - throw Failure(AppConstants.GENERIC_FAILURE); - } - } -} diff --git a/lib/data/services/api/multimessing_api.dart b/lib/data/services/api/multimessing_api.dart deleted file mode 100644 index acb9657e..00000000 --- a/lib/data/services/api/multimessing_api.dart +++ /dev/null @@ -1,130 +0,0 @@ -import 'dart:convert'; - -import 'package:appetizer/data/constants/constants.dart'; -import 'package:appetizer/data/constants/env_config.dart'; -import 'package:appetizer/domain/models/failure_model.dart'; -import 'package:appetizer/domain/models/multimessing/switchable_meal.dart'; -import 'package:appetizer/domain/models/multimessing/switch.dart'; -import 'package:appetizer/utils/api_utils.dart'; -import 'package:flutter/foundation.dart'; -import 'package:http/http.dart' as http; - -class MultimessingApi { - var headers = {'Content-Type': 'application/json'}; - http.Client client = http.Client(); - - Future> getSwitchableMeals(int id) async { - var endpoint = '/api/menu/switch_meal/$id'; - var uri = EnvironmentConfig.BASE_URL + endpoint; - try { - await ApiUtils.addTokenToHeaders(headers); - var jsonResponse = await ApiUtils.get(uri, headers: headers); - var switchableMeals = switchableMealsFromJson(json.encode(jsonResponse)); - return switchableMeals; - } on FormatException catch (e) { - debugPrint(e.message); - throw Failure(AppConstants.BAD_RESPONSE_FORMAT); - } on Exception catch (e) { - debugPrint(e.toString()); - throw Failure(AppConstants.GENERIC_FAILURE); - } - } - - Future remainingSwitches() async { - var endPoint = '/api/leave/switch/count/remaining/'; - var uri = EnvironmentConfig.BASE_URL + endPoint; - - try { - await ApiUtils.addTokenToHeaders(headers); - var jsonResponse = await ApiUtils.get(uri, headers: headers); - var switchCount = jsonResponse['switches']; - return switchCount; - } on FormatException catch (e) { - debugPrint(e.message); - throw Failure(AppConstants.BAD_RESPONSE_FORMAT); - } on Exception catch (e) { - debugPrint(e.toString()); - throw Failure(AppConstants.GENERIC_FAILURE); - } - } - - Future switchMeals(int mealId, String toHostel) async { - var endPoint = '/api/leave/switch/'; - var uri = EnvironmentConfig.BASE_URL + endPoint; - var json = { - 'from_meal': mealId, - 'to_hostel': toHostel, - }; - - try { - await ApiUtils.addTokenToHeaders(headers); - var response = await client.post(Uri.parse(uri), - headers: headers, body: jsonEncode(json)); - if (response.statusCode == 201) { - return true; - } - return false; - } on FormatException catch (e) { - debugPrint(e.message); - throw Failure(AppConstants.BAD_RESPONSE_FORMAT); - } on Exception catch (e) { - debugPrint(e.toString()); - throw Failure(AppConstants.GENERIC_FAILURE); - } - } - - Future cancelSwitch(int id) async { - var endPoint = '/api/leave/switch/$id'; - var uri = EnvironmentConfig.BASE_URL + endPoint; - - try { - await ApiUtils.addTokenToHeaders(headers); - final response = await client.delete(Uri.parse(uri), headers: headers); - if (response.statusCode >= 200 && response.statusCode < 210) { - return true; - } - return false; - } on FormatException catch (e) { - debugPrint(e.message); - throw Failure(AppConstants.BAD_RESPONSE_FORMAT); - } on Exception catch (e) { - debugPrint(e.toString()); - throw Failure(AppConstants.GENERIC_FAILURE); - } - } - - Future getSwitchDetails(int id) async { - var endpoint = '/api/leave/switch/$id'; - var uri = EnvironmentConfig.BASE_URL + endpoint; - try { - await ApiUtils.addTokenToHeaders(headers); - final jsonResponse = await ApiUtils.get(uri, headers: headers); - var switchDetails = Switch.fromJson(jsonResponse); - return switchDetails; - } on FormatException catch (e) { - debugPrint(e.message); - throw Failure(AppConstants.BAD_RESPONSE_FORMAT); - } on Exception catch (e) { - debugPrint(e.toString()); - throw Failure(AppConstants.GENERIC_FAILURE); - } - } - - Future>> switchableHostels() async { - var endPoint = '/api/user/multimessing/hostels'; - var uri = EnvironmentConfig.BASE_URL + endPoint; - try { - await ApiUtils.addTokenToHeaders(headers); - var jsonResponse = await ApiUtils.get(uri, headers: headers); - var switchableHostels = List>.from( - jsonResponse.map((x) => List.from(x.map((x) => x)))); - return switchableHostels; - } on FormatException catch (e) { - debugPrint(e.message); - throw Failure(AppConstants.BAD_RESPONSE_FORMAT); - } on Exception catch (e) { - debugPrint(e.toString()); - throw Failure(AppConstants.GENERIC_FAILURE); - } - } -} diff --git a/lib/data/services/api/transaction_api.dart b/lib/data/services/api/transaction_api.dart deleted file mode 100644 index cabf94e9..00000000 --- a/lib/data/services/api/transaction_api.dart +++ /dev/null @@ -1,69 +0,0 @@ -import 'dart:convert'; - -import 'package:appetizer/data/constants/constants.dart'; -import 'package:appetizer/data/constants/env_config.dart'; -import 'package:appetizer/domain/models/failure_model.dart'; -import 'package:appetizer/domain/models/transaction/paginated_yearly_rebate.dart'; -import 'package:appetizer/domain/models/transaction/faq.dart'; -import 'package:appetizer/utils/api_utils.dart'; -import 'package:flutter/foundation.dart'; -import 'package:http/http.dart' as http; - -class TransactionApi { - var headers = {'Content-Type': 'application/json'}; - http.Client client = http.Client(); - - Future getMonthlyRebate() async { - var endPoint = '/api/transaction/rebate/current/'; - var uri = EnvironmentConfig.BASE_URL + endPoint; - - try { - await ApiUtils.addTokenToHeaders(headers); - var jsonResponse = await ApiUtils.get(uri, headers: headers); - var monthlyRebate = jsonResponse['rebate']; - return monthlyRebate; - } on FormatException catch (e) { - debugPrint(e.message); - throw Failure(AppConstants.BAD_RESPONSE_FORMAT); - } on Exception catch (e) { - debugPrint(e.toString()); - throw Failure(AppConstants.GENERIC_FAILURE); - } - } - - Future getYearlyRebate(int year) async { - var endPoint = '/api/transaction/list/expenses/?year=$year'; - var uri = EnvironmentConfig.BASE_URL + endPoint; - - try { - await ApiUtils.addTokenToHeaders(headers); - var jsonResponse = await ApiUtils.get(uri, headers: headers); - var paginatedYearlyRebate = PaginatedYearlyRebate.fromJson(jsonResponse); - return paginatedYearlyRebate; - } on FormatException catch (e) { - debugPrint(e.message); - throw Failure(AppConstants.BAD_RESPONSE_FORMAT); - } on Exception catch (e) { - debugPrint(e.toString()); - throw Failure(AppConstants.GENERIC_FAILURE); - } - } - - Future> getFAQ() async { - var endPoint = '/api/faqs/'; - var uri = EnvironmentConfig.BASE_URL + endPoint; - - try { - await ApiUtils.addTokenToHeaders(headers); - var jsonResponse = await ApiUtils.get(uri, headers: headers); - var faqList = faqFromJson(json.encode(jsonResponse)); - return faqList; - } on FormatException catch (e) { - debugPrint(e.message); - throw Failure(AppConstants.BAD_RESPONSE_FORMAT); - } on Exception catch (e) { - debugPrint(e.toString()); - throw Failure(AppConstants.GENERIC_FAILURE); - } - } -} diff --git a/lib/data/services/api/user_api.dart b/lib/data/services/api/user_api.dart deleted file mode 100644 index 239506a5..00000000 --- a/lib/data/services/api/user_api.dart +++ /dev/null @@ -1,221 +0,0 @@ -import 'package:appetizer/data/constants/constants.dart'; -import 'package:appetizer/data/constants/env_config.dart'; -import 'package:appetizer/domain/models/failure_model.dart'; -import 'package:appetizer/domain/models/user/oauth_user.dart'; -import 'package:appetizer/domain/models/user/paginated_notifications.dart'; -import 'package:appetizer/domain/models/user/user.dart'; -import 'package:appetizer/utils/api_utils.dart'; -import 'package:appetizer/utils/app_exceptions.dart'; -import 'package:flutter/foundation.dart'; -import 'package:http/http.dart' as http; -import 'package:appetizer/domain/models/user/notification.dart'; - -class UserApi { - var headers = {'Content-Type': 'application/json'}; - http.Client client = http.Client(); - - Future userLogin(String id, String pass) async { - var endpoint = '/api/user/login/'; - var uri = EnvironmentConfig.BASE_URL + endpoint; - var json = { - 'enr': id, - 'password': pass, - }; - - try { - var jsonResponse = await ApiUtils.post(uri, headers: headers, body: json); - var user = User.fromJson(jsonResponse); - return user; - } on ForbiddenException catch (e) { - debugPrint(e.message); - throw Failure(AppConstants.USER_AUTH_WRONG_CREDENTIALS); - } on FormatException catch (e) { - debugPrint(e.message); - throw Failure(AppConstants.BAD_RESPONSE_FORMAT); - } on Exception catch (e) { - debugPrint(e.toString()); - throw Failure(AppConstants.GENERIC_FAILURE); - } - } - - Future userLogout() async { - var endpoint = '/api/user/logout/'; - var uri = EnvironmentConfig.BASE_URL + endpoint; - - try { - await ApiUtils.addTokenToHeaders(headers); - await ApiUtils.post(uri, headers: headers); - } on FormatException catch (e) { - debugPrint(e.message); - throw Failure(AppConstants.BAD_RESPONSE_FORMAT); - } on Exception catch (e) { - debugPrint(e.toString()); - throw Failure(AppConstants.GENERIC_FAILURE); - } - } - - Future getCurrentUser() async { - var endpoint = '/api/user/me/'; - var uri = EnvironmentConfig.BASE_URL + endpoint; - - try { - await ApiUtils.addTokenToHeaders(headers); - var jsonResponse = await ApiUtils.get( - uri, - headers: headers, - ); - var user = User.fromJson(jsonResponse); - return user; - } on FormatException catch (e) { - debugPrint(e.message); - throw Failure(AppConstants.BAD_RESPONSE_FORMAT); - } on Exception catch (e) { - debugPrint(e.toString()); - throw Failure(AppConstants.GENERIC_FAILURE); - } - } - - Future updateUser(String email, String contactNo) async { - var endpoint = '/api/user/me/'; - var uri = EnvironmentConfig.BASE_URL + endpoint; - var json = { - 'email': email, - 'contact_no': contactNo, - }; - - try { - await ApiUtils.addTokenToHeaders(headers); - var jsonResponse = await ApiUtils.patch( - uri, - headers: headers, - body: json, - ); - var user = User.fromJson(jsonResponse); - return user; - } on FormatException catch (e) { - debugPrint(e.message); - throw Failure(AppConstants.BAD_RESPONSE_FORMAT); - } on Exception catch (e) { - debugPrint(e.toString()); - throw Failure(AppConstants.GENERIC_FAILURE); - } - } - - Future updateFcmTokenForUser(String fcmToken) async { - var endpoint = '/api/user/me/'; - var uri = EnvironmentConfig.BASE_URL + endpoint; - var json = {'fcm_token': fcmToken}; - - try { - await ApiUtils.addTokenToHeaders(headers); - var jsonResponse = await ApiUtils.patch( - uri, - headers: headers, - body: json, - ); - var user = User.fromJson(jsonResponse); - return user; - } on FormatException catch (e) { - debugPrint(e.message); - throw Failure(AppConstants.BAD_RESPONSE_FORMAT); - } on Exception catch (e) { - debugPrint(e.toString()); - throw Failure(AppConstants.GENERIC_FAILURE); - } - } - - Future resetUserPassword(String oldPassword, String newPassword) async { - var endpoint = '/api/user/me/password/'; - var uri = EnvironmentConfig.BASE_URL + endpoint; - var json = { - 'old_password': oldPassword, - 'new_password': newPassword, - }; - - try { - await ApiUtils.addTokenToHeaders(headers); - await ApiUtils.put(uri, headers: headers, body: json); - } on FormatException catch (e) { - debugPrint(e.message); - throw Failure(AppConstants.BAD_RESPONSE_FORMAT); - } on Exception catch (e) { - debugPrint(e.toString()); - throw Failure(AppConstants.GENERIC_FAILURE); - } - } - - Future sendResetPasswordLink(String email) async { - var endpoint = '/api/user/me/password/reset/'; - var uri = EnvironmentConfig.BASE_URL + endpoint; - var json = {'email': email}; - final headers = {'Content-Type': 'application/json'}; - - try { - await ApiUtils.post(uri, headers: headers, body: json); - } on FormatException catch (e) { - debugPrint(e.message); - throw Failure(AppConstants.BAD_RESPONSE_FORMAT); - } on Exception catch (e) { - debugPrint(e.toString()); - throw Failure(AppConstants.GENERIC_FAILURE); - } - } - - Future oAuthRedirect(String code) async { - var endpoint = '/api/user/oauth/omniport/redirect/?code=$code'; - var uri = EnvironmentConfig.BASE_URL + endpoint; - try { - var jsonResponse = await ApiUtils.get(uri); - var oauthUser = OAuthUser.fromJson(jsonResponse); - return oauthUser; - } on FormatException catch (e) { - debugPrint(e.message); - throw Failure(AppConstants.BAD_RESPONSE_FORMAT); - } on Exception catch (e) { - debugPrint(e.toString()); - throw Failure(AppConstants.GENERIC_FAILURE); - } - } - - Future oAuthComplete( - int enrNo, String password, String email, int contactNo) async { - var endpoint = '/api/user/oauth/complete/'; - var uri = EnvironmentConfig.BASE_URL + endpoint; - var json = { - 'enr': enrNo, - 'password': password, - 'email': email, - 'contact_no': contactNo, - }; - - try { - var jsonResponse = await ApiUtils.post(uri, headers: headers, body: json); - var oauthUser = OAuthUser.fromJson(jsonResponse); - return oauthUser; - } on FormatException catch (e) { - debugPrint(e.message); - throw Failure(AppConstants.BAD_RESPONSE_FORMAT); - } on Exception catch (e) { - debugPrint(e.toString()); - throw Failure(AppConstants.GENERIC_FAILURE); - } - } - - Future> getNotifications() async { - var endpoint = '/api/user/message/list/'; - var uri = EnvironmentConfig.BASE_URL + endpoint; - try { - await ApiUtils.addTokenToHeaders(headers); - var jsonResponse = await ApiUtils.get(uri, headers: headers); - var paginatedNotifications = - PaginatedNotifications.fromJson(jsonResponse); - return paginatedNotifications.results; - } on FormatException catch (e) { - debugPrint(e.message); - throw Failure(AppConstants.BAD_RESPONSE_FORMAT); - } on Exception catch (e) { - debugPrint(e.toString()); - throw Failure(AppConstants.GENERIC_FAILURE); - } - } -} diff --git a/lib/data/services/api/version_check_api.dart b/lib/data/services/api/version_check_api.dart deleted file mode 100644 index 33884c32..00000000 --- a/lib/data/services/api/version_check_api.dart +++ /dev/null @@ -1,32 +0,0 @@ -import 'dart:io' show Platform; - -import 'package:appetizer/data/constants/constants.dart'; -import 'package:appetizer/data/constants/env_config.dart'; -import 'package:appetizer/domain/models/failure_model.dart'; -import 'package:appetizer/domain/models/appetizer_version.dart'; -import 'package:appetizer/utils/api_utils.dart'; -import 'package:flutter/foundation.dart'; -import 'package:http/http.dart' as http; - -class VersionCheckApi { - var header = {'Content-Type': 'application/json'}; - http.Client client = http.Client(); - - Future checkVersion(String versionNumber) async { - var platform = Platform.isAndroid ? 'an' : 'io'; - var endPoint = '/panel/version/expire/$platform/$versionNumber'; - var uri = EnvironmentConfig.BASE_URL + endPoint; - - try { - var jsonResponse = await ApiUtils.get(uri, headers: header); - var appiVersion = AppetizerVersion.fromJson(jsonResponse); - return appiVersion; - } on FormatException catch (e) { - debugPrint(e.message); - throw Failure(AppConstants.BAD_RESPONSE_FORMAT); - } on Exception catch (e) { - debugPrint(e.toString()); - throw Failure(AppConstants.GENERIC_FAILURE); - } - } -} From f488a0885ddef73612861606009aac7f5a82cb1c Mon Sep 17 00:00:00 2001 From: NanoNish Date: Thu, 24 Aug 2023 22:52:28 +0530 Subject: [PATCH 19/21] patch: remove old api intialization --- lib/locator.dart | 17 ----------------- 1 file changed, 17 deletions(-) diff --git a/lib/locator.dart b/lib/locator.dart index 29a79b98..4c40c38b 100644 --- a/lib/locator.dart +++ b/lib/locator.dart @@ -1,12 +1,4 @@ import 'package:appetizer/domain/amenity/analytics_service.dart'; -import 'package:appetizer/data/services/api/coupon_api.dart'; -import 'package:appetizer/data/services/api/feedback_api.dart'; -import 'package:appetizer/data/services/api/leave_api.dart'; -import 'package:appetizer/data/services/api/menu_api.dart'; -import 'package:appetizer/data/services/api/multimessing_api.dart'; -import 'package:appetizer/data/services/api/transaction_api.dart'; -import 'package:appetizer/data/services/api/user_api.dart'; -import 'package:appetizer/data/services/api/version_check_api.dart'; import 'package:appetizer/data/services/local/dialog_service.dart'; import 'package:appetizer/data/services/local/local_storage_service.dart'; import 'package:appetizer/data/services/local/package_info_service.dart'; @@ -17,15 +9,6 @@ import 'package:get_it/get_it.dart'; GetIt locator = GetIt.instance; Future setupLocator() async { - locator.registerLazySingleton(() => CouponApi()); - locator.registerLazySingleton(() => FeedbackApi()); - locator.registerLazySingleton(() => LeaveApi()); - locator.registerLazySingleton(() => MenuApi()); - locator.registerLazySingleton(() => MultimessingApi()); - locator.registerLazySingleton(() => TransactionApi()); - locator.registerLazySingleton(() => UserApi()); - locator.registerLazySingleton(() => VersionCheckApi()); - locator.registerLazySingleton(() => PushNotificationService()); locator.registerLazySingleton(() => AnalyticsService()); locator.registerLazySingleton(() => DialogService()); From ba4933e773c2f72922a6fa7de3b34174d9456409 Mon Sep 17 00:00:00 2001 From: Aman Date: Fri, 25 Aug 2023 06:16:02 +0530 Subject: [PATCH 20/21] ptch: fix static analysis Signed-off-by: Aman --- lib/data/services/remote/api_service.dart | 5 ++- lib/domain/models/coupon/coupon.dart | 2 +- lib/domain/models/leaves/leave.dart | 2 +- .../models/leaves/paginated_leaves.dart | 5 +-- lib/domain/models/menu/week_menu.dart | 9 +++-- .../models/multimessing/switchable_meal.dart | 2 +- .../transaction/paginated_yearly_rebate.dart | 2 -- lib/domain/models/user/oauth_user.dart | 6 ++-- lib/domain/models/user/user.dart | 5 ++- lib/domain/repositories/user_repository.dart | 2 +- .../yourMealDailyCardsCombined/menu_card.dart | 7 ++++ pubspec.lock | 34 ++++++++++++------- 12 files changed, 47 insertions(+), 34 deletions(-) diff --git a/lib/data/services/remote/api_service.dart b/lib/data/services/remote/api_service.dart index c31c69e1..fd0b0ca4 100644 --- a/lib/data/services/remote/api_service.dart +++ b/lib/data/services/remote/api_service.dart @@ -25,7 +25,6 @@ abstract class ApiService { @Path("versionNumber") String versionNumber, ); - // TODO: add token to all headers // TODO: find a way to remove maps // Coupon API @@ -149,7 +148,7 @@ abstract class ApiService { Future updateFcmTokenForUser( @Body() Map map, ); - + @PUT(ApiEndpoints.password) Future changePassword( @Body() Map map, @@ -165,7 +164,7 @@ abstract class ApiService { @Query("code") String code, ); - @POST(ApiEndpoints.oAuthComplete) + @POST(ApiEndpoints.oAuthComplete) Future oAuthComplete( @Body() Map map, ); diff --git a/lib/domain/models/coupon/coupon.dart b/lib/domain/models/coupon/coupon.dart index e91ad70c..d655d12c 100644 --- a/lib/domain/models/coupon/coupon.dart +++ b/lib/domain/models/coupon/coupon.dart @@ -13,4 +13,4 @@ class Coupon with _$Coupon { }) = _Coupon; factory Coupon.fromJson(Map json) => _$CouponFromJson(json); -} \ No newline at end of file +} diff --git a/lib/domain/models/leaves/leave.dart b/lib/domain/models/leaves/leave.dart index 2a4fb9f5..465d6962 100644 --- a/lib/domain/models/leaves/leave.dart +++ b/lib/domain/models/leaves/leave.dart @@ -17,4 +17,4 @@ class Leave with _$Leave { }) = _Leave; factory Leave.fromJson(Map json) => _$LeaveFromJson(json); -} \ No newline at end of file +} diff --git a/lib/domain/models/leaves/paginated_leaves.dart b/lib/domain/models/leaves/paginated_leaves.dart index c1b42d8d..b3706285 100644 --- a/lib/domain/models/leaves/paginated_leaves.dart +++ b/lib/domain/models/leaves/paginated_leaves.dart @@ -16,5 +16,6 @@ class PaginatedLeaves with _$PaginatedLeaves { // TODO: check if leaves parse correctly into the map - factory PaginatedLeaves.fromJson(Map json) => _$PaginatedLeavesFromJson(json); -} \ No newline at end of file + factory PaginatedLeaves.fromJson(Map json) => + _$PaginatedLeavesFromJson(json); +} diff --git a/lib/domain/models/menu/week_menu.dart b/lib/domain/models/menu/week_menu.dart index 4cac3cd2..c668baa6 100644 --- a/lib/domain/models/menu/week_menu.dart +++ b/lib/domain/models/menu/week_menu.dart @@ -1,6 +1,7 @@ import 'package:appetizer/enums/enum_values.dart'; import 'package:flutter/foundation.dart'; import 'package:freezed_annotation/freezed_annotation.dart'; +import 'package:intl/intl.dart'; part 'week_menu.freezed.dart'; part 'week_menu.g.dart'; @@ -100,9 +101,8 @@ class Meal with _$Meal { required MealType type, CostType? costType, required List items, - // TODO: write getters - // required DateTime startTime, - // required DateTime endTime, + @JsonKey(fromJson: _fromJson, toJson: _toJson) required DateTime startTime, + @JsonKey(fromJson: _fromJson, toJson: _toJson) required DateTime endTime, required LeaveStatus leaveStatus, required CouponStatus couponStatus, required dynamic wastage, @@ -134,6 +134,9 @@ class Meal with _$Meal { } factory Meal.fromJson(Map json) => _$MealFromJson(json); + + static DateTime _fromJson(String date) => DateFormat('HH:mm:ss').parse(date); + static String _toJson(DateTime date) => DateFormat('HH:mm:ss').format(date); } @freezed diff --git a/lib/domain/models/multimessing/switchable_meal.dart b/lib/domain/models/multimessing/switchable_meal.dart index c86adf59..25e6b932 100644 --- a/lib/domain/models/multimessing/switchable_meal.dart +++ b/lib/domain/models/multimessing/switchable_meal.dart @@ -26,7 +26,7 @@ class SwitchableMeal { factory SwitchableMeal.fromJson(Map json) => _$SwitchableMealFromJson(json); - + Map toJson() => _$SwitchableMealToJson(this); } diff --git a/lib/domain/models/transaction/paginated_yearly_rebate.dart b/lib/domain/models/transaction/paginated_yearly_rebate.dart index 9ed0df66..d49a8baf 100644 --- a/lib/domain/models/transaction/paginated_yearly_rebate.dart +++ b/lib/domain/models/transaction/paginated_yearly_rebate.dart @@ -6,7 +6,6 @@ part 'paginated_yearly_rebate.g.dart'; @freezed class PaginatedYearlyRebate with _$PaginatedYearlyRebate { @JsonSerializable(fieldRename: FieldRename.snake, explicitToJson: true) - const factory PaginatedYearlyRebate({ required int count, required bool hasNext, @@ -21,7 +20,6 @@ class PaginatedYearlyRebate with _$PaginatedYearlyRebate { @freezed class YearlyRebate with _$YearlyRebate { @JsonSerializable(fieldRename: FieldRename.snake) - const factory YearlyRebate({ required int monthId, required int year, diff --git a/lib/domain/models/user/oauth_user.dart b/lib/domain/models/user/oauth_user.dart index 0de69143..5b4d0218 100644 --- a/lib/domain/models/user/oauth_user.dart +++ b/lib/domain/models/user/oauth_user.dart @@ -1,13 +1,10 @@ import 'package:appetizer/domain/models/user/user.dart'; import 'package:json_annotation/json_annotation.dart'; -import 'package:json_annotation/json_annotation.dart'; - part 'oauth_user.g.dart'; @JsonSerializable(fieldRename: FieldRename.snake, explicitToJson: true) class OAuthUser { - String? token; User studentData; bool isNew; @@ -18,7 +15,8 @@ class OAuthUser { required this.isNew, }); - factory OAuthUser.fromJson(Map json) => _$OAuthUserFromJson(json); + factory OAuthUser.fromJson(Map json) => + _$OAuthUserFromJson(json); Map toJson() => _$OAuthUserToJson(this); } diff --git a/lib/domain/models/user/user.dart b/lib/domain/models/user/user.dart index f94e935b..f5c548bc 100644 --- a/lib/domain/models/user/user.dart +++ b/lib/domain/models/user/user.dart @@ -4,9 +4,8 @@ part 'user.freezed.dart'; part 'user.g.dart'; @freezed -class User with _$User{ +class User with _$User { @JsonSerializable(fieldRename: FieldRename.snake) - const factory User({ required String email, required String hostelName, @@ -29,5 +28,5 @@ class User with _$User{ @Default(true) bool isNew, }) = _User; - factory User.fromJson(Map json) => _$UserFromJson(json); + factory User.fromJson(Map json) => _$UserFromJson(json); } diff --git a/lib/domain/repositories/user_repository.dart b/lib/domain/repositories/user_repository.dart index 8d78d82f..e0ca427b 100644 --- a/lib/domain/repositories/user_repository.dart +++ b/lib/domain/repositories/user_repository.dart @@ -122,4 +122,4 @@ class UserRepository { throw Failure(AppConstants.GENERIC_FAILURE); } } -} \ No newline at end of file +} diff --git a/lib/presentation/week_menu/components/yourMealDailyCardsCombined/menu_card.dart b/lib/presentation/week_menu/components/yourMealDailyCardsCombined/menu_card.dart index 9a545a87..7323ce6e 100644 --- a/lib/presentation/week_menu/components/yourMealDailyCardsCombined/menu_card.dart +++ b/lib/presentation/week_menu/components/yourMealDailyCardsCombined/menu_card.dart @@ -273,3 +273,10 @@ class MealCard extends StatelessWidget { ); } } + +// TODO(nano): temp fix for the getters +extension on Meal { + bool get isOutdated => false; + bool get isLeaveToggleOutdated => false; + bool get isCouponOutdated => false; +} diff --git a/pubspec.lock b/pubspec.lock index 617d8e99..913de425 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -173,10 +173,10 @@ packages: dependency: transitive description: name: collection - sha256: "4a07be6cb69c84d677a6c3096fcf960cc3285a8330b4603e0d463d15d9bd934c" + sha256: f092b211a4319e98e5ff58223576de6c2803db36221657b46c82574721240687 url: "https://pub.dev" source: hosted - version: "1.17.1" + version: "1.17.2" convert: dependency: transitive description: @@ -537,10 +537,10 @@ packages: dependency: "direct main" description: name: intl - sha256: a3715e3bc90294e971cb7dc063fbf3cd9ee0ebf8604ffeafabd9e6f16abbdbe6 + sha256: "3bc132a9dbce73a7e4a21a17d06e1878839ffbf975568bc875c60537824b0c4d" url: "https://pub.dev" source: hosted - version: "0.18.0" + version: "0.18.1" io: dependency: transitive description: @@ -593,18 +593,18 @@ packages: dependency: transitive description: name: matcher - sha256: "6501fbd55da300384b768785b83e5ce66991266cec21af89ab9ae7f5ce1c4cbb" + sha256: "1803e76e6653768d64ed8ff2e1e67bea3ad4b923eb5c56a295c3e634bad5960e" url: "https://pub.dev" source: hosted - version: "0.12.15" + version: "0.12.16" material_color_utilities: dependency: transitive description: name: material_color_utilities - sha256: d92141dc6fe1dad30722f9aa826c7fbc896d021d792f80678280601aff8cf724 + sha256: "9528f2f296073ff54cb9fee677df673ace1218163c3bc7628093e7eed5203d41" url: "https://pub.dev" source: hosted - version: "0.2.0" + version: "0.5.0" meta: dependency: transitive description: @@ -926,10 +926,10 @@ packages: dependency: transitive description: name: source_span - sha256: dd904f795d4b4f3b870833847c461801f6750a9fa8e61ea5ac53f9422b31f250 + sha256: "53e943d4206a5e30df338fd4c6e7a077e02254531b138a15aec3bd143c1a8b3c" url: "https://pub.dev" source: hosted - version: "1.9.1" + version: "1.10.0" stack_trace: dependency: transitive description: @@ -982,10 +982,10 @@ packages: dependency: transitive description: name: test_api - sha256: eb6ac1540b26de412b3403a163d919ba86f6a973fe6cc50ae3541b80092fdcfb + sha256: "75760ffd7786fffdfb9597c35c5b27eaeec82be8edfb6d71d32651128ed7aab8" url: "https://pub.dev" source: hosted - version: "0.5.1" + version: "0.6.0" timing: dependency: transitive description: @@ -1058,6 +1058,14 @@ packages: url: "https://pub.dev" source: hosted version: "1.1.0" + web: + dependency: transitive + description: + name: web + sha256: dc8ccd225a2005c1be616fe02951e2e342092edf968cf0844220383757ef8f10 + url: "https://pub.dev" + source: hosted + version: "0.1.4-beta" web_socket_channel: dependency: transitive description: @@ -1099,5 +1107,5 @@ packages: source: hosted version: "3.1.2" sdks: - dart: ">=3.0.0 <4.0.0" + dart: ">=3.1.0-185.0.dev <4.0.0" flutter: ">=3.10.0" From 44f919335b9386d899ed000ff1904e57696598f0 Mon Sep 17 00:00:00 2001 From: Aman Date: Fri, 25 Aug 2023 06:29:36 +0530 Subject: [PATCH 21/21] fix: linter issues Signed-off-by: Aman --- .../repositories/coupon_repository.dart | 9 +- .../repositories/feedback_repository.dart | 7 +- lib/domain/repositories/leave_repository.dart | 11 +- lib/domain/repositories/menu_repository.dart | 13 +- .../repositories/transaction_repositroy.dart | 9 +- lib/domain/repositories/user_repository.dart | 23 +- lib/presentation/app/app.dart | 2 +- lib/presentation/components/black_button.dart | 2 +- .../components/no_data_found_container.dart | 1 - .../coupons/components/coupon_card.dart | 2 +- .../FeedbackTile/bloc/feedback_tile_bloc.dart | 1 - .../bloc/feedback_tile_event.dart | 1 - .../FeedbackTile/feedback_tile.dart | 2 +- lib/presentation/feedback/feedback_view.dart | 8 +- .../components/leave_history.dart | 4 +- .../bloc/notification_page_bloc.dart | 12 +- .../components/no_notification_widget.dart | 2 +- .../components/notification_card.dart | 6 +- .../profile/components/profile_button.dart | 6 +- .../profile/components/profile_card.dart | 4 +- .../profile/components/profile_photo.dart | 2 +- lib/presentation/profile/profile_view.dart | 6 +- .../yourMealDailyCardsCombined/menu_card.dart | 285 +++++++++--------- lib/utils/api_utils.dart | 157 ---------- lib/utils/app_exceptions.dart | 52 ---- 25 files changed, 208 insertions(+), 419 deletions(-) delete mode 100644 lib/utils/api_utils.dart delete mode 100644 lib/utils/app_exceptions.dart diff --git a/lib/domain/repositories/coupon_repository.dart b/lib/domain/repositories/coupon_repository.dart index 0b819026..86b91e53 100644 --- a/lib/domain/repositories/coupon_repository.dart +++ b/lib/domain/repositories/coupon_repository.dart @@ -3,11 +3,12 @@ import 'package:appetizer/data/services/remote/api_service.dart'; import 'package:appetizer/domain/models/coupon/coupon.dart'; import 'package:appetizer/domain/models/failure_model.dart'; import 'package:appetizer/domain/models/menu/week_menu.dart'; +import 'package:flutter/foundation.dart'; -class CouponRepositroy { +class CouponRepository { final ApiService _apiService; - CouponRepositroy(this._apiService); + CouponRepository(this._apiService); Future applyForCoupon(Coupon coupon) async { Map map = { @@ -17,7 +18,7 @@ class CouponRepositroy { try { return await _apiService.applyForCoupon(map); } catch (e) { - print(e); + debugPrint(e.toString()); throw Failure(AppConstants.GENERIC_FAILURE); } } @@ -29,7 +30,7 @@ class CouponRepositroy { try { return await _apiService.cancelCoupon(coupon.meal, map); } catch (e) { - print(e); + debugPrint(e.toString()); throw Failure(AppConstants.GENERIC_FAILURE); } } diff --git a/lib/domain/repositories/feedback_repository.dart b/lib/domain/repositories/feedback_repository.dart index 03b3eb44..64dad343 100644 --- a/lib/domain/repositories/feedback_repository.dart +++ b/lib/domain/repositories/feedback_repository.dart @@ -3,6 +3,7 @@ import 'package:appetizer/data/services/remote/api_service.dart'; import 'package:appetizer/domain/models/failure_model.dart'; import 'package:appetizer/domain/models/feedback/appetizer_feedback.dart'; import 'package:appetizer/domain/models/feedback/feedback_response.dart'; +import 'package:flutter/foundation.dart'; class FeedbackRepository { final ApiService _apiService; @@ -13,7 +14,7 @@ class FeedbackRepository { try { return await _apiService.submittedFeedbacks(); } catch (e) { - print(e); + debugPrint(e.toString()); throw Failure(AppConstants.GENERIC_FAILURE); } } @@ -22,7 +23,7 @@ class FeedbackRepository { try { return await _apiService.responseOfFeedbacks(); } catch (e) { - print(e); + debugPrint(e.toString()); throw Failure(AppConstants.GENERIC_FAILURE); } } @@ -37,7 +38,7 @@ class FeedbackRepository { try { return await _apiService.newFeedback(map); } catch (e) { - print(e); + debugPrint(e.toString()); throw Failure(AppConstants.GENERIC_FAILURE); } } diff --git a/lib/domain/repositories/leave_repository.dart b/lib/domain/repositories/leave_repository.dart index bc6eb919..0b7a7dda 100644 --- a/lib/domain/repositories/leave_repository.dart +++ b/lib/domain/repositories/leave_repository.dart @@ -3,9 +3,10 @@ import 'package:appetizer/data/services/remote/api_service.dart'; import 'package:appetizer/domain/models/failure_model.dart'; import 'package:appetizer/domain/models/leaves/paginated_leaves.dart'; import 'package:appetizer/domain/models/menu/week_menu.dart'; +import 'package:flutter/foundation.dart'; class LeaveRepository { - ApiService _apiService; + final ApiService _apiService; LeaveRepository(this._apiService); @@ -40,7 +41,7 @@ class LeaveRepository { try { return await _apiService.check(map); } catch (e) { - print(e); + debugPrint(e.toString()); throw Failure(AppConstants.GENERIC_FAILURE); } } @@ -52,7 +53,7 @@ class LeaveRepository { try { return await _apiService.check(map); } catch (e) { - print(e); + debugPrint(e.toString()); throw Failure(AppConstants.GENERIC_FAILURE); } } @@ -66,7 +67,7 @@ class LeaveRepository { try { return await _apiService.leave(map); } catch (e) { - print(e); + debugPrint(e.toString()); throw Failure(AppConstants.GENERIC_FAILURE); } } @@ -77,7 +78,7 @@ class LeaveRepository { try { return await _apiService.cancelLeave(meal.id); } catch (e) { - print(e); + debugPrint(e.toString()); throw Failure(AppConstants.GENERIC_FAILURE); } } diff --git a/lib/domain/repositories/menu_repository.dart b/lib/domain/repositories/menu_repository.dart index 6be211f4..f33173ea 100644 --- a/lib/domain/repositories/menu_repository.dart +++ b/lib/domain/repositories/menu_repository.dart @@ -2,9 +2,10 @@ import 'package:appetizer/data/constants/constants.dart'; import 'package:appetizer/data/services/remote/api_service.dart'; import 'package:appetizer/domain/models/failure_model.dart'; import 'package:appetizer/domain/models/menu/week_menu.dart'; +import 'package:flutter/foundation.dart'; class MenuRepository { - ApiService _apiService; + final ApiService _apiService; MenuRepository(this._apiService); @@ -14,7 +15,7 @@ class MenuRepository { try { return await _apiService.weekMenuMultimessing(hostelCode, id); } catch (e) { - print(e); + debugPrint(e.toString()); throw Failure(AppConstants.GENERIC_FAILURE); } } @@ -23,7 +24,7 @@ class MenuRepository { try { return await _apiService.weekMenuForYourMeals(weekId); } catch (e) { - print(e); + debugPrint(e.toString()); throw Failure(AppConstants.GENERIC_FAILURE); } } @@ -34,7 +35,7 @@ class MenuRepository { try { return await _apiService.weekMenuByWeekId(weekId); } catch (e) { - print(e); + debugPrint(e.toString()); throw Failure(AppConstants.GENERIC_FAILURE); } } @@ -43,7 +44,7 @@ class MenuRepository { try { return await _apiService.currentWeekMenu(); } catch (e) { - print(e); + debugPrint(e.toString()); throw Failure(AppConstants.GENERIC_FAILURE); } } @@ -52,7 +53,7 @@ class MenuRepository { try { return await _apiService.dayMenu(week, dayOfWeek); } catch (e) { - print(e); + debugPrint(e.toString()); throw Failure(AppConstants.GENERIC_FAILURE); } } diff --git a/lib/domain/repositories/transaction_repositroy.dart b/lib/domain/repositories/transaction_repositroy.dart index cb74919a..76432cd1 100644 --- a/lib/domain/repositories/transaction_repositroy.dart +++ b/lib/domain/repositories/transaction_repositroy.dart @@ -3,9 +3,10 @@ import 'package:appetizer/data/services/remote/api_service.dart'; import 'package:appetizer/domain/models/failure_model.dart'; import 'package:appetizer/domain/models/transaction/faq.dart'; import 'package:appetizer/domain/models/transaction/paginated_yearly_rebate.dart'; +import 'package:flutter/foundation.dart'; class TransactionRepository { - ApiService _apiService; + final ApiService _apiService; TransactionRepository(this._apiService); @@ -15,7 +16,7 @@ class TransactionRepository { try { return await _apiService.getMonthlyRebate(); } catch (e) { - print(e); + debugPrint(e.toString()); throw Failure(AppConstants.GENERIC_FAILURE); } } @@ -24,7 +25,7 @@ class TransactionRepository { try { return await _apiService.getYearlyRebate(year); } catch (e) { - print(e); + debugPrint(e.toString()); throw Failure(AppConstants.GENERIC_FAILURE); } } @@ -33,7 +34,7 @@ class TransactionRepository { try { return await _apiService.getFAQs(); } catch (e) { - print(e); + debugPrint(e.toString()); throw Failure(AppConstants.GENERIC_FAILURE); } } diff --git a/lib/domain/repositories/user_repository.dart b/lib/domain/repositories/user_repository.dart index e0ca427b..5caf14bd 100644 --- a/lib/domain/repositories/user_repository.dart +++ b/lib/domain/repositories/user_repository.dart @@ -4,9 +4,10 @@ import 'package:appetizer/domain/models/failure_model.dart'; import 'package:appetizer/domain/models/user/notification.dart'; import 'package:appetizer/domain/models/user/oauth_user.dart'; import 'package:appetizer/domain/models/user/user.dart'; +import 'package:flutter/foundation.dart'; class UserRepository { - ApiService _apiService; + final ApiService _apiService; UserRepository(this._apiService); @@ -20,7 +21,7 @@ class UserRepository { try { return await _apiService.login(map); } catch (e) { - print(e); + debugPrint(e.toString()); throw Failure(AppConstants.GENERIC_FAILURE); } } @@ -29,7 +30,7 @@ class UserRepository { try { return await _apiService.logout(); } catch (e) { - print(e); + debugPrint(e.toString()); throw Failure(AppConstants.GENERIC_FAILURE); } } @@ -38,7 +39,7 @@ class UserRepository { try { return await _apiService.getCurrentUser(); } catch (e) { - print(e); + debugPrint(e.toString()); throw Failure(AppConstants.GENERIC_FAILURE); } } @@ -47,7 +48,7 @@ class UserRepository { try { return await _apiService.updateUser(user); } catch (e) { - print(e); + debugPrint(e.toString()); throw Failure(AppConstants.GENERIC_FAILURE); } } @@ -60,7 +61,7 @@ class UserRepository { try { return await _apiService.updateFcmTokenForUser(map); } catch (e) { - print(e); + debugPrint(e.toString()); throw Failure(AppConstants.GENERIC_FAILURE); } } @@ -73,7 +74,7 @@ class UserRepository { try { return await _apiService.changePassword(map); } catch (e) { - print(e); + debugPrint(e.toString()); throw Failure(AppConstants.GENERIC_FAILURE); } } @@ -85,7 +86,7 @@ class UserRepository { try { return await _apiService.resetPassword(map); } catch (e) { - print(e); + debugPrint(e.toString()); throw Failure(AppConstants.GENERIC_FAILURE); } } @@ -94,7 +95,7 @@ class UserRepository { try { return await _apiService.oAuthRedirect(code); } catch (e) { - print(e); + debugPrint(e.toString()); throw Failure(AppConstants.GENERIC_FAILURE); } } @@ -109,7 +110,7 @@ class UserRepository { try { return await _apiService.oAuthComplete(map); } catch (e) { - print(e); + debugPrint(e.toString()); throw Failure(AppConstants.GENERIC_FAILURE); } } @@ -118,7 +119,7 @@ class UserRepository { try { return await _apiService.getNotifications(); } catch (e) { - print(e); + debugPrint(e.toString()); throw Failure(AppConstants.GENERIC_FAILURE); } } diff --git a/lib/presentation/app/app.dart b/lib/presentation/app/app.dart index 13ebc8d9..09489701 100644 --- a/lib/presentation/app/app.dart +++ b/lib/presentation/app/app.dart @@ -29,7 +29,7 @@ class _AppetizerAppState extends State { @override Widget build(BuildContext context) { return MultiRepositoryProvider( - providers: [], + providers: const [], child: BlocBuilder( builder: (context, state) { return MaterialApp.router( diff --git a/lib/presentation/components/black_button.dart b/lib/presentation/components/black_button.dart index fe8051e0..3dab8cbc 100644 --- a/lib/presentation/components/black_button.dart +++ b/lib/presentation/components/black_button.dart @@ -31,7 +31,7 @@ class BlackButton extends StatelessWidget { title, textAlign: TextAlign.center, style: TextStyle( - color: Color(0xFFF6F6F6), + color: const Color(0xFFF6F6F6), fontSize: 12.toAutoScaledFont, fontFamily: 'Lato', fontWeight: FontWeight.w700, diff --git a/lib/presentation/components/no_data_found_container.dart b/lib/presentation/components/no_data_found_container.dart index 00b2d92c..fb847785 100644 --- a/lib/presentation/components/no_data_found_container.dart +++ b/lib/presentation/components/no_data_found_container.dart @@ -1,7 +1,6 @@ import 'package:appetizer/data/core/theme/dimensional/dimensional.dart'; import 'package:flutter/material.dart'; import 'package:flutter_svg/flutter_svg.dart'; -import 'package:flutter_svg_provider/flutter_svg_provider.dart'; class NoDataFoundContainer extends StatelessWidget { const NoDataFoundContainer({ diff --git a/lib/presentation/coupons/components/coupon_card.dart b/lib/presentation/coupons/components/coupon_card.dart index c929b6c1..cf35ff78 100644 --- a/lib/presentation/coupons/components/coupon_card.dart +++ b/lib/presentation/coupons/components/coupon_card.dart @@ -63,7 +63,7 @@ class CouponCard extends StatelessWidget { Text( coupon.meal, style: TextStyle( - color: Color(0xFF2E2E2E), + color: const Color(0xFF2E2E2E), fontSize: 10.toAutoScaledFont, fontFamily: 'Noto Sans', fontWeight: FontWeight.w400, diff --git a/lib/presentation/feedback/components/FeedbackTile/bloc/feedback_tile_bloc.dart b/lib/presentation/feedback/components/FeedbackTile/bloc/feedback_tile_bloc.dart index 18de2eb0..9aedaab9 100644 --- a/lib/presentation/feedback/components/FeedbackTile/bloc/feedback_tile_bloc.dart +++ b/lib/presentation/feedback/components/FeedbackTile/bloc/feedback_tile_bloc.dart @@ -1,6 +1,5 @@ import 'package:bloc/bloc.dart'; import 'package:equatable/equatable.dart'; -import 'package:meta/meta.dart'; part 'feedback_tile_event.dart'; part 'feedback_tile_state.dart'; diff --git a/lib/presentation/feedback/components/FeedbackTile/bloc/feedback_tile_event.dart b/lib/presentation/feedback/components/FeedbackTile/bloc/feedback_tile_event.dart index 8779e1f4..91a76417 100644 --- a/lib/presentation/feedback/components/FeedbackTile/bloc/feedback_tile_event.dart +++ b/lib/presentation/feedback/components/FeedbackTile/bloc/feedback_tile_event.dart @@ -1,6 +1,5 @@ part of 'feedback_tile_bloc.dart'; -@immutable abstract class FeedbackTileEvent extends Equatable { const FeedbackTileEvent(); diff --git a/lib/presentation/feedback/components/FeedbackTile/feedback_tile.dart b/lib/presentation/feedback/components/FeedbackTile/feedback_tile.dart index 9b4e01c4..0dde8a19 100644 --- a/lib/presentation/feedback/components/FeedbackTile/feedback_tile.dart +++ b/lib/presentation/feedback/components/FeedbackTile/feedback_tile.dart @@ -26,7 +26,7 @@ class FeedbackTile extends StatelessWidget { title, textAlign: TextAlign.left, style: TextStyle( - color: Color(0xFF111111), + color: const Color(0xFF111111), fontSize: 20.toAutoScaledFont, fontFamily: 'Lato', fontWeight: FontWeight.w400, diff --git a/lib/presentation/feedback/feedback_view.dart b/lib/presentation/feedback/feedback_view.dart index cfcc5c67..4dd5b041 100644 --- a/lib/presentation/feedback/feedback_view.dart +++ b/lib/presentation/feedback/feedback_view.dart @@ -54,7 +54,7 @@ class FeedbackPage extends StatelessWidget { Text( 'Kindly provide us with your feedback to improve your mess experienWeekly Menuce.', style: TextStyle( - color: Color(0xFF5A5A5A), + color: const Color(0xFF5A5A5A), fontSize: 14.toAutoScaledFont, fontFamily: 'Lato', fontWeight: FontWeight.w400, @@ -72,13 +72,13 @@ class FeedbackPage extends StatelessWidget { ), ); }), - SizedBox( + const SizedBox( height: 2, ), Text( 'If any other feeback, please describe below', style: TextStyle( - color: Color(0xFF111111), + color: const Color(0xFF111111), fontSize: 16.toAutoScaledFont, fontFamily: 'Lato', fontWeight: FontWeight.w400, @@ -103,7 +103,7 @@ class FeedbackPage extends StatelessWidget { border: OutlineInputBorder( borderSide: BorderSide( width: 0.5.toAutoScaledWidth, - color: Color.fromARGB(37, 0, 0, 0), + color: const Color.fromARGB(37, 0, 0, 0), ), ), ), diff --git a/lib/presentation/leaves_and_rebate/components/leave_history.dart b/lib/presentation/leaves_and_rebate/components/leave_history.dart index 800c5bc6..862fbb5d 100644 --- a/lib/presentation/leaves_and_rebate/components/leave_history.dart +++ b/lib/presentation/leaves_and_rebate/components/leave_history.dart @@ -20,9 +20,9 @@ class LeaveHistory extends StatelessWidget { ), shadows: [ BoxShadow( - color: Color(0x19000000), + color: const Color(0x19000000), blurRadius: 7.toAutoScaledWidth, - offset: Offset(2, 2), + offset: const Offset(2, 2), spreadRadius: 1, ) ]), diff --git a/lib/presentation/notifications/bloc/notification_page_bloc.dart b/lib/presentation/notifications/bloc/notification_page_bloc.dart index 5df62298..5c5db942 100644 --- a/lib/presentation/notifications/bloc/notification_page_bloc.dart +++ b/lib/presentation/notifications/bloc/notification_page_bloc.dart @@ -13,17 +13,17 @@ class NotificationPageBloc // TODO: implement repository call bool submissionSuccessful = true; List notifications = [ - Notification( + const Notification( id: 123, dateCreated: 532523, title: "Yesssir", message: "fasfafafassfadasdadsafafasfsdfafasfasfasfasfasfas"), - Notification( + const Notification( id: 123, dateCreated: 532523, title: "Yesssir", message: "fasfafafassfadasdadsafafasfsdfafasfasfasfasfasfas"), - Notification( + const Notification( id: 123, dateCreated: 532523, title: "Yesssir", @@ -50,17 +50,17 @@ class NotificationPageBloc (NotificationPageSwitchChangedEvent event, Emitter emit) { List notifications = [ - Notification( + const Notification( id: 123, dateCreated: 532523, title: "Yesssir", message: "fasfafafassfadasdadsafafasfsdfafasfasfasfasfasfas"), - Notification( + const Notification( id: 123, dateCreated: 532523, title: "Yesssir", message: "fasfafafassfadasdadsafafasfsdfafasfasfasfasfasfas"), - Notification( + const Notification( id: 123, dateCreated: 532523, title: "Yesssir", diff --git a/lib/presentation/notifications/components/no_notification_widget.dart b/lib/presentation/notifications/components/no_notification_widget.dart index 0d2da142..fa6a1c33 100644 --- a/lib/presentation/notifications/components/no_notification_widget.dart +++ b/lib/presentation/notifications/components/no_notification_widget.dart @@ -12,7 +12,7 @@ class NoNotificationsWidget extends StatelessWidget { child: Text( 'No new notifications !', style: TextStyle( - color: Color(0xFF111111), + color: const Color(0xFF111111), fontSize: 18.toAutoScaledFont, fontFamily: 'Noto Sans', fontWeight: FontWeight.w400, diff --git a/lib/presentation/notifications/components/notification_card.dart b/lib/presentation/notifications/components/notification_card.dart index f856bd55..bbfd4f63 100644 --- a/lib/presentation/notifications/components/notification_card.dart +++ b/lib/presentation/notifications/components/notification_card.dart @@ -46,7 +46,7 @@ class NotificationCard extends StatelessWidget { child: Text( data.title, style: TextStyle( - color: Color(0xFF111111), + color: const Color(0xFF111111), fontSize: 18.toAutoScaledFont, fontFamily: 'Noto Sans', fontWeight: FontWeight.w500, @@ -58,7 +58,7 @@ class NotificationCard extends StatelessWidget { child: Text( '${data.dateCreated}', style: TextStyle( - color: Color(0xFF2E2E2E), + color: const Color(0xFF2E2E2E), fontSize: 10.toAutoScaledFont, fontFamily: 'Lato', fontWeight: FontWeight.w400, @@ -74,7 +74,7 @@ class NotificationCard extends StatelessWidget { Text( data.message, style: TextStyle( - color: Color(0xFF2E2E2E), + color: const Color(0xFF2E2E2E), fontSize: 14.toAutoScaledFont, fontFamily: 'Lato', fontWeight: FontWeight.w400, diff --git a/lib/presentation/profile/components/profile_button.dart b/lib/presentation/profile/components/profile_button.dart index 16232484..41160269 100644 --- a/lib/presentation/profile/components/profile_button.dart +++ b/lib/presentation/profile/components/profile_button.dart @@ -29,7 +29,7 @@ class ProfileTextButton extends StatelessWidget { title, textAlign: TextAlign.center, style: TextStyle( - color: Color(0xFF111111), + color: const Color(0xFF111111), fontSize: 13.toAutoScaledFont, fontFamily: 'Lato', fontWeight: FontWeight.w400, @@ -82,7 +82,7 @@ class ProfileIconButton extends StatelessWidget { SizedBox( width: 20.toAutoScaledWidth, height: 20.toAutoScaledHeight, - child: Icon( + child: const Icon( Icons.bookmark_border_outlined, color: Color.fromARGB(255, 255, 203, 116), ), @@ -92,7 +92,7 @@ class ProfileIconButton extends StatelessWidget { title, textAlign: TextAlign.center, style: TextStyle( - color: Color(0xFF111111), + color: const Color(0xFF111111), fontSize: 14.toAutoScaledFont, fontFamily: 'Lato', fontWeight: FontWeight.w500, diff --git a/lib/presentation/profile/components/profile_card.dart b/lib/presentation/profile/components/profile_card.dart index 1cb25794..92bf1e47 100644 --- a/lib/presentation/profile/components/profile_card.dart +++ b/lib/presentation/profile/components/profile_card.dart @@ -19,7 +19,7 @@ class Fields extends StatelessWidget { Text( '$title ', style: TextStyle( - color: Color(0xFF111111), + color: const Color(0xFF111111), fontSize: 16.toAutoScaledFont, fontFamily: 'Lato', fontWeight: FontWeight.w500, @@ -28,7 +28,7 @@ class Fields extends StatelessWidget { Text( data, style: TextStyle( - color: Color(0xFF2E2E2E), + color: const Color(0xFF2E2E2E), fontSize: 16.toAutoScaledFont, fontFamily: 'Inter', fontWeight: FontWeight.w400, diff --git a/lib/presentation/profile/components/profile_photo.dart b/lib/presentation/profile/components/profile_photo.dart index 52ebe3e3..b5ddde21 100644 --- a/lib/presentation/profile/components/profile_photo.dart +++ b/lib/presentation/profile/components/profile_photo.dart @@ -18,7 +18,7 @@ class ProfilePhoto extends StatelessWidget { shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(62.toAutoScaledWidth), side: BorderSide( - color: Color.fromARGB(255, 255, 255, 255), + color: const Color.fromARGB(255, 255, 255, 255), width: 12.4.toAutoScaledWidth, )), ), diff --git a/lib/presentation/profile/profile_view.dart b/lib/presentation/profile/profile_view.dart index 05d85416..ab01afe9 100644 --- a/lib/presentation/profile/profile_view.dart +++ b/lib/presentation/profile/profile_view.dart @@ -49,7 +49,7 @@ class ProfileScreen extends StatelessWidget { Text( data.name, style: TextStyle( - color: Color(0xFF111111), + color: const Color(0xFF111111), fontSize: 25.toAutoScaledFont, fontFamily: 'Noto Sans', fontWeight: FontWeight.w600, @@ -84,7 +84,7 @@ class ProfileScreen extends StatelessWidget { ], ), ), - Divider( + const Divider( height: 2, thickness: 2, color: Color.fromARGB(255, 189, 189, 189), @@ -131,7 +131,7 @@ class ProfileScreen extends StatelessWidget { child: Text( 'Raise a Query', style: TextStyle( - color: Color(0xFF008BFF), + color: const Color(0xFF008BFF), fontSize: 12.toAutoScaledFont, fontFamily: 'Inter', fontWeight: FontWeight.w400, diff --git a/lib/presentation/week_menu/components/yourMealDailyCardsCombined/menu_card.dart b/lib/presentation/week_menu/components/yourMealDailyCardsCombined/menu_card.dart index 1b8b056a..f0a3153b 100644 --- a/lib/presentation/week_menu/components/yourMealDailyCardsCombined/menu_card.dart +++ b/lib/presentation/week_menu/components/yourMealDailyCardsCombined/menu_card.dart @@ -119,164 +119,159 @@ class MealCard extends StatelessWidget { offset: 2, width: 312.toAutoScaledWidth, height: 168.toAutoScaledHeight, - child: Container( - child: Row( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Container( - width: 125.toAutoScaledWidth, - height: 168.toAutoScaledHeight, - decoration: BoxDecoration( - image: DecorationImage( - image: svg.Svg( - 'assets/images/meal_card/${meal.title}.svg', - ), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Container( + width: 125.toAutoScaledWidth, + height: 168.toAutoScaledHeight, + decoration: BoxDecoration( + image: DecorationImage( + image: svg.Svg( + 'assets/images/meal_card/${meal.title}.svg', ), ), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - mainAxisAlignment: MainAxisAlignment.start, - children: [ - SizedBox(height: 15.toAutoScaledHeight), - Container( - height: 28.toAutoScaledHeight, - padding: EdgeInsets.only(left: 12), - child: Text( - meal.title, - style: AppTheme.headline1.copyWith( - fontSize: 20.toAutoScaledFont, - color: AppTheme.black11), - ), - ), - Container( - height: 17.toAutoScaledHeight, - padding: EdgeInsets.only(left: 12.toAutoScaledWidth), - child: Text( - '${DateFormat.jm().format(meal.startTime)} - ${DateFormat.jm().format(meal.endTime)}', - style: AppTheme.headline3.copyWith( - fontWeight: FontWeight.w600, - fontSize: 12.toAutoScaledFont, - color: AppTheme.grey2f), - ), - ), - SizedBox(height: 9.toAutoScaledHeight), - Row( - mainAxisAlignment: MainAxisAlignment.start, - children: [ - Container( - padding: EdgeInsets.only(left: 12.toAutoScaledWidth), - child: FittedBox( - fit: BoxFit.contain, - child: FSwitch( - enable: !meal.isLeaveToggleOutdated, - open: meal.leaveStatus.status != LeaveStatusEnum.A, - sliderColor: AppTheme.customWhite, - openColor: AppTheme.black2e, - height: 20.toAutoScaledHeight, - width: 44.toAutoScaledWidth, - onChanged: (value) async { - context - .read() - .add(ToggleMealLeaveEvent( - mealId: meal.id, - leaveAppliedAlready: - meal.leaveStatus.status == - LeaveStatusEnum.A)); - }, - ), - ), - ), - ], - ), - SizedBox(height: 45.toAutoScaledHeight), - ...[ - meal.isOutdated - ? GestureDetector( - onTap: () { - //TODO: lead to feedback page - }, - child: const FeedbackAndCouponWidget( - taken: false, coupon: false), - ) - : (_isMealValidForCoupon(meal) - ? GestureDetector( - onTap: () { - if (!meal.isCouponOutdated) { - context - .read() - .add(ToggleMealCouponEvent( - couponId: - meal.couponStatus.status == - CouponStatusEnum.A - ? meal.couponStatus.id! - : -1, - couponAppliedAlready: - meal.couponStatus.status == - CouponStatusEnum.A, - mealId: meal.id)); - } else if (meal.couponStatus.status == - CouponStatusEnum.A) { - showCouponDialog( - "Coupon no: ${meal.couponStatus.id!}", - context); - } else { - showCouponDialog( - "You can not apply for coupon now", - context); - } - }, - child: FeedbackAndCouponWidget( - taken: meal.couponStatus.status == - CouponStatusEnum.A, - coupon: true), - ) - : const SizedBox.shrink()), - ], - SizedBox(height: 10.toAutoScaledHeight) - ], - ), ), - Column( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - mainAxisSize: MainAxisSize.max, + child: Column( crossAxisAlignment: CrossAxisAlignment.start, + mainAxisAlignment: MainAxisAlignment.start, children: [ - SizedBox(height: 18.toAutoScaledHeight), - for (var item in meal.items) Text(" \u2022 ${item.name}"), - const Spacer(), + SizedBox(height: 15.toAutoScaledHeight), Container( - margin: EdgeInsets.symmetric( - horizontal: 22.toAutoScaledWidth, + height: 28.toAutoScaledHeight, + padding: const EdgeInsets.only(left: 12), + child: Text( + meal.title, + style: AppTheme.headline1.copyWith( + fontSize: 20.toAutoScaledFont, color: AppTheme.black11), ), - height: 0.5, - width: 145, - color: AppTheme.rulerColor, ), - SizedBox(height: 8.toAutoScaledHeight), Container( - width: 187.toAutoScaledWidth, - padding: EdgeInsets.only( - left: 12.toAutoScaledWidth, - right: 19.toAutoScaledWidth, + height: 17.toAutoScaledHeight, + padding: EdgeInsets.only(left: 12.toAutoScaledWidth), + child: Text( + '${DateFormat.jm().format(meal.startTime)} - ${DateFormat.jm().format(meal.endTime)}', + style: AppTheme.headline3.copyWith( + fontWeight: FontWeight.w600, + fontSize: 12.toAutoScaledFont, + color: AppTheme.grey2f), ), - child: RichText( - text: TextSpan( - text: 'Daily Items: ', - style: AppTheme.bodyText2.copyWith( - fontWeight: FontWeight.w600, - color: const Color(0xFFB51111)), - children: [ - TextSpan( - text: dailyItemsParsed, style: AppTheme.bodyText2) - ], + ), + SizedBox(height: 9.toAutoScaledHeight), + Row( + mainAxisAlignment: MainAxisAlignment.start, + children: [ + Container( + padding: EdgeInsets.only(left: 12.toAutoScaledWidth), + child: FittedBox( + fit: BoxFit.contain, + child: FSwitch( + enable: !meal.isLeaveToggleOutdated, + open: meal.leaveStatus.status != LeaveStatusEnum.A, + sliderColor: AppTheme.customWhite, + openColor: AppTheme.black2e, + height: 20.toAutoScaledHeight, + width: 44.toAutoScaledWidth, + onChanged: (value) async { + context.read().add( + ToggleMealLeaveEvent( + mealId: meal.id, + leaveAppliedAlready: + meal.leaveStatus.status == + LeaveStatusEnum.A)); + }, + ), + ), ), - ), + ], ), - SizedBox(height: 17.toAutoScaledHeight) + SizedBox(height: 45.toAutoScaledHeight), + ...[ + meal.isOutdated + ? GestureDetector( + onTap: () { + //TODO: lead to feedback page + }, + child: const FeedbackAndCouponWidget( + taken: false, coupon: false), + ) + : (_isMealValidForCoupon(meal) + ? GestureDetector( + onTap: () { + if (!meal.isCouponOutdated) { + context + .read() + .add(ToggleMealCouponEvent( + couponId: meal.couponStatus.status == + CouponStatusEnum.A + ? meal.couponStatus.id! + : -1, + couponAppliedAlready: + meal.couponStatus.status == + CouponStatusEnum.A, + mealId: meal.id)); + } else if (meal.couponStatus.status == + CouponStatusEnum.A) { + showCouponDialog( + "Coupon no: ${meal.couponStatus.id!}", + context); + } else { + showCouponDialog( + "You can not apply for coupon now", + context); + } + }, + child: FeedbackAndCouponWidget( + taken: meal.couponStatus.status == + CouponStatusEnum.A, + coupon: true), + ) + : const SizedBox.shrink()), + ], + SizedBox(height: 10.toAutoScaledHeight) ], - ) - ], - ), + ), + ), + Column( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + mainAxisSize: MainAxisSize.max, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + SizedBox(height: 18.toAutoScaledHeight), + for (var item in meal.items) Text(" \u2022 ${item.name}"), + const Spacer(), + Container( + margin: EdgeInsets.symmetric( + horizontal: 22.toAutoScaledWidth, + ), + height: 0.5, + width: 145, + color: AppTheme.rulerColor, + ), + SizedBox(height: 8.toAutoScaledHeight), + Container( + width: 187.toAutoScaledWidth, + padding: EdgeInsets.only( + left: 12.toAutoScaledWidth, + right: 19.toAutoScaledWidth, + ), + child: RichText( + text: TextSpan( + text: 'Daily Items: ', + style: AppTheme.bodyText2.copyWith( + fontWeight: FontWeight.w600, + color: const Color(0xFFB51111)), + children: [ + TextSpan( + text: dailyItemsParsed, style: AppTheme.bodyText2) + ], + ), + ), + ), + SizedBox(height: 17.toAutoScaledHeight) + ], + ) + ], ), ); } diff --git a/lib/utils/api_utils.dart b/lib/utils/api_utils.dart deleted file mode 100644 index 593dc750..00000000 --- a/lib/utils/api_utils.dart +++ /dev/null @@ -1,157 +0,0 @@ -import 'dart:convert'; -import 'dart:io'; -import 'package:appetizer/data/constants/constants.dart'; -import 'package:appetizer/domain/models/failure_model.dart'; -import 'package:appetizer/utils/app_exceptions.dart'; -import 'package:flutter/foundation.dart'; -import 'package:http/http.dart' as http; -import 'package:shared_preferences/shared_preferences.dart'; - -class ApiUtils { - static http.Client client = http.Client(); - - /// Returns JSON GET response - static Future get(String uri, {Map? headers}) async { - try { - final response = await client.get(Uri.parse(uri), headers: headers); - final jsonResponse = ApiUtils.jsonResponse(response); - return jsonResponse; - } on UnauthorizedException catch (e) { - debugPrint(e.message); - throw Failure(AppConstants.UNAUTHORIZED_EXCEPTION); - } on SocketException catch (e) { - debugPrint(e.message); - throw Failure(AppConstants.NO_INTERNET_CONNECTION); - } on HttpException catch (e) { - debugPrint(e.message); - throw Failure(AppConstants.HTTP_EXCEPTION); - } - } - - /// Returns JSON POST response - static Future post(String uri, - {required Map headers, dynamic body}) async { - try { - final response = await client.post(Uri.parse(uri), - headers: headers, body: jsonEncode(body)); - final jsonResponse = ApiUtils.jsonResponse(response); - return jsonResponse; - } on UnauthorizedException catch (e) { - debugPrint(e.message); - throw Failure(AppConstants.UNAUTHORIZED_EXCEPTION); - } on SocketException catch (e) { - debugPrint(e.message); - throw Failure(AppConstants.NO_INTERNET_CONNECTION); - } on HttpException catch (e) { - debugPrint(e.message); - throw Failure(AppConstants.HTTP_EXCEPTION); - } - } - - /// Returns JSON PUT response - static Future put(String uri, - {required Map headers, dynamic body}) async { - try { - final response = await client.put( - Uri.parse(uri), - headers: headers, - body: jsonEncode(body), - ); - final jsonResponse = ApiUtils.jsonResponse(response); - return jsonResponse; - } on UnauthorizedException catch (e) { - debugPrint(e.message); - throw Failure(AppConstants.UNAUTHORIZED_EXCEPTION); - } on SocketException catch (e) { - debugPrint(e.message); - throw Failure(AppConstants.NO_INTERNET_CONNECTION); - } on HttpException catch (e) { - debugPrint(e.message); - throw Failure(AppConstants.HTTP_EXCEPTION); - } - } - - /// Returns JSON PATCH response - static Future patch(String uri, - {required Map headers, dynamic body}) async { - try { - final response = await client.patch(Uri.parse(uri), - headers: headers, body: jsonEncode(body)); - final jsonResponse = ApiUtils.jsonResponse(response); - return jsonResponse; - } on UnauthorizedException catch (e) { - debugPrint(e.message); - throw Failure(AppConstants.UNAUTHORIZED_EXCEPTION); - } on SocketException catch (e) { - debugPrint(e.message); - throw Failure(AppConstants.NO_INTERNET_CONNECTION); - } on HttpException catch (e) { - debugPrint(e.message); - throw Failure(AppConstants.HTTP_EXCEPTION); - } - } - - /// Returns JSON DELETE response - static Future delete(String uri, - {required Map headers}) async { - try { - final response = await http.delete(Uri.parse(uri), headers: headers); - final jsonResponse = ApiUtils.jsonResponse(response); - return jsonResponse; - } on UnauthorizedException catch (e) { - debugPrint(e.message); - throw Failure(AppConstants.UNAUTHORIZED_EXCEPTION); - } on SocketException catch (e) { - debugPrint(e.message); - throw Failure(AppConstants.NO_INTERNET_CONNECTION); - } on HttpException catch (e) { - debugPrint(e.message); - throw Failure(AppConstants.HTTP_EXCEPTION); - } - } - - static dynamic jsonResponse(http.Response response) { - switch (response.statusCode) { - case 200: - case 201: - case 202: - case 204: - if (response.body == '') return; - var responseJson = json.decode(response.body); - debugPrint(responseJson); - return responseJson; - case 400: - debugPrint(response.body); - throw BadRequestException(response.body); - case 401: - debugPrint(response.body); - throw UnauthorizedException(response.body); - case 403: - debugPrint(response.body); - throw ForbiddenException(response.body); - case 404: - debugPrint(response.body); - throw NotFoundException(response.body); - case 409: - debugPrint(response.body); - throw ConflictException(response.body); - case 500: - debugPrint(response.body); - throw InternalServerErrorException(response.body); - case 503: - debugPrint(response.body); - throw ServiceUnavailableException(response.body); - default: - debugPrint(response.body); - throw FetchDataException( - 'Error occured while Communication with Server with StatusCode : ${response.statusCode}', - ); - } - } - - static Future addTokenToHeaders(Map headers) async { - var prefs = await SharedPreferences.getInstance(); - var token = prefs.getString('token'); - headers.addAll({'Authorization': 'Token $token'}); - } -} diff --git a/lib/utils/app_exceptions.dart b/lib/utils/app_exceptions.dart deleted file mode 100644 index 658796f5..00000000 --- a/lib/utils/app_exceptions.dart +++ /dev/null @@ -1,52 +0,0 @@ -class AppException implements Exception { - final _message; - final _prefix; - - AppException([this._message, this._prefix]); - - String get message => _message; - - String get pefix => _prefix; - - @override - String toString() => '$_prefix : $_message'; -} - -class BadRequestException extends AppException { - BadRequestException([message]) : super(message, 'Invalid Request'); -} - -class UnauthorizedException extends AppException { - UnauthorizedException([message]) : super(message, 'Unauthorized'); -} - -class ForbiddenException extends AppException { - ForbiddenException([String? message]) : super(message, 'Forbidden'); -} - -class NotFoundException extends AppException { - NotFoundException([String? message]) : super(message, 'Not Found'); -} - -class ConflictException extends AppException { - ConflictException([String? message]) : super(message, 'Conflict'); -} - -class InternalServerErrorException extends AppException { - InternalServerErrorException([String? message]) - : super(message, 'Internal Server Error'); -} - -class ServiceUnavailableException extends AppException { - ServiceUnavailableException([String? message]) - : super(message, 'Service Unavailable'); -} - -class InvalidInputException extends AppException { - InvalidInputException([String? message]) : super(message, 'Invalid Input'); -} - -class FetchDataException extends AppException { - FetchDataException([String? message]) - : super(message, 'Error During Communication'); -}