From 1e7ff09f140942ff4ff7137f969c28f84ad1a856 Mon Sep 17 00:00:00 2001 From: haroon amjad Date: Sun, 11 Dec 2022 17:23:25 +0300 Subject: [PATCH 01/42] loader uncommented --- lib/ui/leave_balance/add_leave_balance_screen.dart | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/lib/ui/leave_balance/add_leave_balance_screen.dart b/lib/ui/leave_balance/add_leave_balance_screen.dart index ed8396f..5ef03f4 100644 --- a/lib/ui/leave_balance/add_leave_balance_screen.dart +++ b/lib/ui/leave_balance/add_leave_balance_screen.dart @@ -96,7 +96,7 @@ class _AddLeaveBalanceScreenState extends State { } void validateAbsenceTransaction(selectedID) async { - //try { + try { Utils.showLoading(context); Map dffDataMap = {}; for (int i = 1; i <= 20; i++) { @@ -145,10 +145,10 @@ class _AddLeaveBalanceScreenState extends State { } await LeaveBalanceApiClient().cancelHrTransaction(submit.pTRANSACTIONID!); Utils.hideLoading(context); - // } catch (ex) { - // Utils.hideLoading(context); - // Utils.handleException(ex, context, null); - // } + } catch (ex) { + Utils.hideLoading(context); + Utils.handleException(ex, context, null); + } } @override From 7d1086522d094c6886cadd720acfb5bf9d9f3b02 Mon Sep 17 00:00:00 2001 From: "Aamir.Muhammad" Date: Mon, 12 Dec 2022 11:04:28 +0300 Subject: [PATCH 02/42] Chat Fixes & Counter Updated on Signal R --- lib/api/chat/chat_api_client.dart | 98 ++++++---- lib/api/dashboard_api_client.dart | 7 +- .../chat/chat_count_conversation_model.dart | 28 +-- .../chat/get_search_user_chat_model.dart | 36 ++-- lib/provider/chat_provider_model.dart | 169 ++++++++++++++---- lib/provider/dashboard_provider_model.dart | 23 +-- lib/ui/chat/chat_bubble.dart | 50 +++--- lib/ui/chat/chat_detailed_screen.dart | 61 ++++--- lib/ui/chat/chat_home.dart | 18 +- lib/ui/chat/chat_home_screen.dart | 38 ++-- lib/ui/chat/favorite_users_screen.dart | 25 +-- lib/ui/landing/dashboard_screen.dart | 9 +- lib/widgets/app_bar_widget.dart | 13 ++ .../search_employee_bottom_sheet.dart | 3 +- lib/widgets/image_picker.dart | 2 +- 15 files changed, 367 insertions(+), 213 deletions(-) diff --git a/lib/api/chat/chat_api_client.dart b/lib/api/chat/chat_api_client.dart index bea5b7c..3ef8fba 100644 --- a/lib/api/chat/chat_api_client.dart +++ b/lib/api/chat/chat_api_client.dart @@ -2,11 +2,11 @@ import 'dart:convert'; import 'dart:io'; import 'dart:typed_data'; +import 'package:flutter/foundation.dart'; import 'package:http/http.dart'; import 'package:mohem_flutter_app/api/api_client.dart'; import 'package:mohem_flutter_app/app_state/app_state.dart'; import 'package:mohem_flutter_app/classes/consts.dart'; -import 'package:mohem_flutter_app/classes/utils.dart'; import 'package:mohem_flutter_app/exceptions/api_exception.dart'; import 'package:mohem_flutter_app/main.dart'; import 'package:mohem_flutter_app/models/chat/chat_user_image_model.dart'; @@ -29,6 +29,9 @@ class ChatApiClient { "password": "FxIu26rWIKoF8n6mpbOmAjDLphzFGmpG", }, ); + if (!kReleaseMode) { + logger.i("res: " + response.body); + } user.UserAutoLoginModel userLoginResponse = user.userAutoLoginModelFromJson(response.body); return userLoginResponse; } @@ -38,33 +41,36 @@ class ChatApiClient { "${ApiConsts.chatLoginTokenUrl}getUserWithStatusAndFavAsync/$sName/$cUserId", token: AppState().chatDetails!.response!.token, ); - return searchUserJsonModel(response.body); + if (!kReleaseMode) { + logger.i("res: " + response.body); + } + return List.from(json.decode(response.body).map((x) => ChatUser.fromJson(x))); } - List searchUserJsonModel(String str) => List.from(json.decode(str).map((x) => ChatUser.fromJson(x))); - Future getRecentChats() async { try { Response response = await ApiClient().getJsonForResponse( "${ApiConsts.chatRecentUrl}getchathistorybyuserid", token: AppState().chatDetails!.response!.token, ); + if (!kReleaseMode) { + logger.i("res: " + response.body); + } return ChatUserModel.fromJson( json.decode(response.body), ); } catch (e) { - e as APIException; - if (e.message == "api_common_unauthorized") { - user.UserAutoLoginModel userLoginResponse = await ChatApiClient().getUserLoginToken(); - if (userLoginResponse.response != null) { - AppState().setchatUserDetails = userLoginResponse; - getRecentChats(); - } else { - Utils.showToast( - userLoginResponse.errorResponses!.first.fieldName.toString() + " Erorr", - ); - } - } + // if (e.message == "api_common_unauthorized") { + // user.UserAutoLoginModel userLoginResponse = await ChatApiClient().getUserLoginToken(); + // if (userLoginResponse.response != null) { + // AppState().setchatUserDetails = userLoginResponse; + // getRecentChats(); + // } else { + // Utils.showToast( + // userLoginResponse.errorResponses!.first.fieldName.toString() + " Erorr", + // ); + // } + // } throw e; } } @@ -74,9 +80,10 @@ class ChatApiClient { "${ApiConsts.chatFavUser}getFavUserById/${AppState().chatDetails!.response!.id}", token: AppState().chatDetails!.response!.token, ); - return ChatUserModel.fromJson( - json.decode(favRes.body), - ); + if (!kReleaseMode) { + logger.i("res: " + favRes.body); + } + return ChatUserModel.fromJson(json.decode(favRes.body)); } Future getSingleUserChatHistory({required int senderUID, required int receiverUID, required bool loadMore, bool isNewChat = false, required int paginationVal}) async { @@ -85,24 +92,30 @@ class ChatApiClient { "${ApiConsts.chatSingleUserHistoryUrl}GetUserChatHistory/$senderUID/$receiverUID/$paginationVal", token: AppState().chatDetails!.response!.token, ); + if (!kReleaseMode) { + logger.i("res: " + response.body); + } return response; } catch (e) { - e as APIException; - if (e.message == "api_common_unauthorized") { - user.UserAutoLoginModel userLoginResponse = await ChatApiClient().getUserLoginToken(); - if (userLoginResponse.response != null) { - AppState().setchatUserDetails = userLoginResponse; - getSingleUserChatHistory(senderUID: senderUID, receiverUID: receiverUID, loadMore: loadMore, paginationVal: paginationVal); - } else { - Utils.showToast(userLoginResponse.errorResponses!.first.fieldName.toString() + " Erorr"); - } - } + // e as APIException; + // if (e.message == "api_common_unauthorized") { + // user.UserAutoLoginModel userLoginResponse = await ChatApiClient().getUserLoginToken(); + // if (userLoginResponse.response != null) { + // AppState().setchatUserDetails = userLoginResponse; + // getSingleUserChatHistory(senderUID: senderUID, receiverUID: receiverUID, loadMore: loadMore, paginationVal: paginationVal); + // } else { + // Utils.showToast(userLoginResponse.errorResponses!.first.fieldName.toString() + " Erorr"); + // } + // } throw e; } } Future favUser({required int userID, required int targetUserID}) async { Response response = await ApiClient().postJsonForResponse("${ApiConsts.chatFavUser}addFavUser", {"targetUserId": targetUserID, "userId": userID}, token: AppState().chatDetails!.response!.token); + if (!kReleaseMode) { + logger.i("res: " + response.body); + } fav.FavoriteChatUser favoriteChatUser = fav.FavoriteChatUser.fromRawJson(response.body); return favoriteChatUser; } @@ -114,20 +127,23 @@ class ChatApiClient { {"targetUserId": targetUserID, "userId": userID}, token: AppState().chatDetails!.response!.token, ); + if (!kReleaseMode) { + logger.i("res: " + response.body); + } + fav.FavoriteChatUser favoriteChatUser = fav.FavoriteChatUser.fromRawJson(response.body); return favoriteChatUser; } catch (e) { e as APIException; - if (e.message == "api_common_unauthorized") { - logger.d("Token Generated On APIIIIII"); - user.UserAutoLoginModel userLoginResponse = await ChatApiClient().getUserLoginToken(); - if (userLoginResponse.response != null) { - AppState().setchatUserDetails = userLoginResponse; - unFavUser(userID: userID, targetUserID: targetUserID); - } else { - Utils.showToast(userLoginResponse.errorResponses!.first.fieldName.toString() + " Erorr"); - } - } + // if (e.message == "api_common_unauthorized") { + // user.UserAutoLoginModel userLoginResponse = await ChatApiClient().getUserLoginToken(); + // if (userLoginResponse.response != null) { + // AppState().setchatUserDetails = userLoginResponse; + // unFavUser(userID: userID, targetUserID: targetUserID); + // } else { + // Utils.showToast(userLoginResponse.errorResponses!.first.fieldName.toString() + " Erorr"); + // } + // } throw e; } } @@ -138,6 +154,7 @@ class ChatApiClient { request.files.add(await MultipartFile.fromPath('files', file.path)); request.headers.addAll({'Authorization': 'Bearer ${AppState().chatDetails!.response!.token}'}); StreamedResponse response = await request.send(); + if (!kReleaseMode) {} return response; } @@ -159,6 +176,9 @@ class ChatApiClient { {"encryptedEmails": encryptedEmails, "fromClient": false}, token: AppState().chatDetails!.response!.token, ); + if (!kReleaseMode) { + logger.i("res: " + response.body); + } return chatUserImageModelFromJson(response.body); } } diff --git a/lib/api/dashboard_api_client.dart b/lib/api/dashboard_api_client.dart index e30af91..48063c3 100644 --- a/lib/api/dashboard_api_client.dart +++ b/lib/api/dashboard_api_client.dart @@ -180,12 +180,7 @@ class DashboardApiClient { }, url, postParams); } - Future getChatCount() async { - Response response = await ApiClient().getJsonForResponse( - "${ApiConsts.chatLoginTokenUrl}unreadconversationcount/${AppState().getUserName}", - ); - return chatUnreadCovnCountModelFromJson(response.body); - } + // Future setAdvertisementViewed(String masterID, int advertisementId) async { // String url = "${ApiConsts.cocRest}Mohemm_ITG_UpdateAdvertisementAsViewed"; diff --git a/lib/models/chat/chat_count_conversation_model.dart b/lib/models/chat/chat_count_conversation_model.dart index e584d32..1906803 100644 --- a/lib/models/chat/chat_count_conversation_model.dart +++ b/lib/models/chat/chat_count_conversation_model.dart @@ -1,8 +1,8 @@ -import 'dart:convert'; - -ChatUnreadCovnCountModel chatUnreadCovnCountModelFromJson(String str) => ChatUnreadCovnCountModel.fromJson(json.decode(str)); +// To parse this JSON data, do +// +// final chatUnreadCovnCountModel = chatUnreadCovnCountModelFromMap(jsonString); -String chatUnreadCovnCountModelToJson(ChatUnreadCovnCountModel data) => json.encode(data.toJson()); +import 'dart:convert'; class ChatUnreadCovnCountModel { ChatUnreadCovnCountModel({ @@ -13,13 +13,17 @@ class ChatUnreadCovnCountModel { int? singleChatCount; int? groupChatCount; - factory ChatUnreadCovnCountModel.fromJson(Map json) => ChatUnreadCovnCountModel( - singleChatCount: json["singleChatCount"] == null ? null : json["singleChatCount"], - groupChatCount: json["groupChatCount"] == null ? null : json["groupChatCount"], - ); + factory ChatUnreadCovnCountModel.fromJson(String str) => ChatUnreadCovnCountModel.fromMap(json.decode(str)); + + String toJson() => json.encode(toMap()); + + factory ChatUnreadCovnCountModel.fromMap(Map json) => ChatUnreadCovnCountModel( + singleChatCount: json["singleChatCount"] == null ? null : json["singleChatCount"], + groupChatCount: json["groupChatCount"] == null ? null : json["groupChatCount"], + ); - Map toJson() => { - "singleChatCount": singleChatCount == null ? null : singleChatCount, - "groupChatCount": groupChatCount == null ? null : groupChatCount, - }; + Map toMap() => { + "singleChatCount": singleChatCount == null ? null : singleChatCount, + "groupChatCount": groupChatCount == null ? null : groupChatCount, + }; } diff --git a/lib/models/chat/get_search_user_chat_model.dart b/lib/models/chat/get_search_user_chat_model.dart index fe87061..3d023fd 100644 --- a/lib/models/chat/get_search_user_chat_model.dart +++ b/lib/models/chat/get_search_user_chat_model.dart @@ -1,3 +1,5 @@ +import 'dart:io'; + class ChatUserModel { ChatUserModel({ this.response, @@ -35,6 +37,7 @@ class ChatUser { this.isTyping, this.isImageLoaded, this.isImageLoading, + this.userLocalDownlaodedImage, }); int? id; @@ -52,24 +55,25 @@ class ChatUser { bool? isTyping; bool? isImageLoaded; bool? isImageLoading; + File? userLocalDownlaodedImage; factory ChatUser.fromJson(Map json) => ChatUser( - id: json["id"] == null ? null : json["id"], - userName: json["userName"] == null ? null : json["userName"], - email: json["email"] == null ? null : json["email"], - phone: json["phone"], - title: json["title"], - userStatus: json["userStatus"] == null ? null : json["userStatus"], - image: json["image"], - unreadMessageCount: json["unreadMessageCount"] == null ? null : json["unreadMessageCount"], - userAction: json["userAction"], - isPin: json["isPin"] == null ? null : json["isPin"], - isFav: json["isFav"] == null ? null : json["isFav"], - isAdmin: json["isAdmin"] == null ? null : json["isAdmin"], - isTyping: false, - isImageLoaded: false, - isImageLoading: true, - ); + id: json["id"] == null ? null : json["id"], + userName: json["userName"] == null ? null : json["userName"], + email: json["email"] == null ? null : json["email"], + phone: json["phone"], + title: json["title"], + userStatus: json["userStatus"] == null ? null : json["userStatus"], + image: json["image"], + unreadMessageCount: json["unreadMessageCount"] == null ? null : json["unreadMessageCount"], + userAction: json["userAction"], + isPin: json["isPin"] == null ? null : json["isPin"], + isFav: json["isFav"] == null ? null : json["isFav"], + isAdmin: json["isAdmin"] == null ? null : json["isAdmin"], + isTyping: false, + isImageLoaded: false, + isImageLoading: true, + userLocalDownlaodedImage: null); Map toJson() => { "id": id == null ? null : id, diff --git a/lib/provider/chat_provider_model.dart b/lib/provider/chat_provider_model.dart index 5fb4cbf..94a296a 100644 --- a/lib/provider/chat_provider_model.dart +++ b/lib/provider/chat_provider_model.dart @@ -12,6 +12,7 @@ import 'package:mohem_flutter_app/classes/consts.dart'; import 'package:mohem_flutter_app/classes/encryption.dart'; import 'package:mohem_flutter_app/classes/utils.dart'; import 'package:mohem_flutter_app/main.dart'; +import 'package:mohem_flutter_app/models/chat/chat_count_conversation_model.dart'; import 'package:mohem_flutter_app/models/chat/chat_user_image_model.dart'; import 'package:mohem_flutter_app/models/chat/get_search_user_chat_model.dart'; import 'package:mohem_flutter_app/models/chat/get_single_user_chat_list_model.dart'; @@ -19,6 +20,8 @@ import 'package:mohem_flutter_app/models/chat/get_user_login_token_model.dart' a import 'package:mohem_flutter_app/models/chat/make_user_favotire_unfavorite_chat_model.dart' as fav; import 'package:mohem_flutter_app/ui/landing/dashboard_screen.dart'; import 'package:mohem_flutter_app/widgets/image_picker.dart'; +import 'package:open_file/open_file.dart'; +import 'package:path_provider/path_provider.dart'; import 'package:signalr_netcore/hub_connection.dart'; import 'package:signalr_netcore/signalr_client.dart'; import 'package:uuid/uuid.dart'; @@ -39,6 +42,10 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { List repliedMsg = []; List favUsersList = []; int paginationVal = 0; + bool currentUserTyping = false; + + //Chat + int chatUConvCounter = 0; Future getUserAutoLoginToken() async { userLoginToken.UserAutoLoginModel userLoginResponse = await ChatApiClient().getUserLoginToken(); @@ -56,30 +63,23 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { await chatHubConnection.start(); print("Startedddddddd"); chatHubConnection.on("OnDeliveredChatUserAsync", onMsgReceived); + chatHubConnection.on("OnGetChatConversationCount", onNewChatConversion); } Future getHubConnection() async { HubConnection hub; - // try { HttpConnectionOptions httpOp = HttpConnectionOptions(skipNegotiation: false, logMessageContent: true); hub = HubConnectionBuilder() .withUrl(ApiConsts.chatHubConnectionUrl + "?UserId=${AppState().chatDetails!.response!.id}&source=Web&access_token=${AppState().chatDetails!.response!.token}", options: httpOp) .withAutomaticReconnect(retryDelays: [2000, 5000, 10000, 20000]).build(); - // isChatHubLoding = false; return hub; - // } catch (e) { - // getUserAutoLoginToken().whenComplete(() { - // getHubConnection(); - // }); - // throw e; - // } } void registerEvents() { chatHubConnection.on("OnUpdateUserStatusAsync", changeStatus); // chatHubConnection.on("OnDeliveredChatUserAsync", onMsgReceived); // hubConnection.on("OnSeenChatUserAsync", onChatSeen); - //hubConnection.on("OnUserTypingAsync", onUserTyping); + chatHubConnection.on("OnUserTypingAsync", onUserTyping); chatHubConnection.on("OnUserCountAsync", userCountAsync); // hubConnection.on("OnUpdateUserChatHistoryWindowsAsync", updateChatHistoryWindow); chatHubConnection.on("OnGetUserChatHistoryNotDeliveredAsync", chatNotDelivered); @@ -164,7 +164,9 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { } isLoading = false; notifyListeners(); + markRead(userChatHistory, receiverUID); + generateConvId(); } @@ -176,26 +178,28 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { void markRead(List data, int receiverID) { if (data != null) { for (SingleUserChatModel element in data!) { - if (element.isSeen != null) { - if (!element.isSeen!) { - element.isSeen = true; - dynamic data = [ - { - "userChatHistoryId": element.userChatHistoryId, - "TargetUserId": element.currentUserId == receiverID ? element.currentUserId : element.targetUserId, - "isDelivered": true, - "isSeen": true, - } - ]; - updateUserChatHistoryStatusAsync(data); - notifyListeners(); + if (AppState().chatDetails!.response!.id! == element.targetUserId) { + if (element.isSeen != null) { + if (!element.isSeen!) { + element.isSeen = true; + dynamic data = [ + { + "userChatHistoryId": element.userChatHistoryId, + "TargetUserId": element.currentUserId == receiverID ? element.currentUserId : element.targetUserId, + "isDelivered": true, + "isSeen": true, + } + ]; + updateUserChatHistoryStatusAsync(data); + notifyListeners(); + } + } + for (ChatUser element in searchedChats!) { + if (element.id == receiverID) { + element.unreadMessageCount = 0; + chatUConvCounter = 0; + } } - } - } - for (ChatUser element in searchedChats!) { - if (element.id == receiverID) { - element.unreadMessageCount = 0; - // notifyListeners(); } } notifyListeners(); @@ -346,9 +350,23 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { } } } - dynamic contain = searchedChats!.where((ChatUser element) => element.id == data.first.currentUserId); - if (contain.isEmpty) { - searchedChats!.add(ChatUser(id: data.first.currentUserId, userName: data.first.currentUserName, unreadMessageCount: 0, isImageLoading: false, image: "", isImageLoaded: true, userStatus: 1)); + + if (searchedChats != null) { + dynamic contain = searchedChats!.where((ChatUser element) => element.id == data.first.currentUserId); + if (contain.isEmpty) { + searchedChats!.add( + ChatUser( + id: data.first.currentUserId, + userName: data.first.currentUserName, + unreadMessageCount: 0, + isImageLoading: false, + image: "", + isImageLoaded: true, + userStatus: 1, + isTyping: false, + userLocalDownlaodedImage: null), + ); + } } setMsgTune(); @@ -368,6 +386,7 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { {"userChatHistoryId": data.first.userChatHistoryId, "TargetUserId": temp.first.targetUserId, "isDelivered": true, "isSeen": isChatScreenActive ? true : false} ]; updateUserChatHistoryOnMsg(list); + invokeChatCounter(userId: AppState().chatDetails!.response!.id!); notifyListeners(); } @@ -384,7 +403,7 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { if (user.id == parameters![1] && parameters[0] == true) { user.isTyping = parameters[0] as bool?; Future.delayed( - const Duration(seconds: 2), + const Duration(seconds: 1), () { user.isTyping = false; notifyListeners(); @@ -392,6 +411,17 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { ); } } + if (isChatScreenActive) { + currentUserTyping = true; + notifyListeners(); + Future.delayed( + const Duration(seconds: 2), + () { + currentUserTyping = false; + notifyListeners(); + }, + ); + } notifyListeners(); } @@ -473,7 +503,6 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { required bool isImageLoaded}) async { Uuid uuid = const Uuid(); String contentNo = uuid.v4(); - String msg = message.text; SingleUserChatModel data = SingleUserChatModel( chatEventId: chatEventId, @@ -492,8 +521,8 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { fileTypeResponse: isAttachment ? FileTypeResponse( fileTypeId: fileTypeId, - fileTypeName: getFileType(getFileExtension(selectedFile.path).toString()), - fileKind: getFileExtension(selectedFile.path), + fileTypeName: getFileExtension(selectedFile.path).toString(), + fileKind: "file", fileName: selectedFile.path.split("/").last, fileTypeDescription: getFileTypeDescription(getFileExtension(selectedFile.path).toString()), ) @@ -517,7 +546,17 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { dynamic contain = searchedChats!.where((ChatUser element) => element.id == targetUserId); if (contain.isEmpty) { searchedChats!.add( - ChatUser(id: targetUserId, userName: targetUserName, unreadMessageCount: 0, isImageLoading: false, image: "", isImageLoaded: true), + ChatUser( + id: targetUserId, + userName: targetUserName, + unreadMessageCount: 0, + isImageLoading: false, + image: "", + isImageLoaded: true, + isTyping: false, + isFav: false, + userLocalDownlaodedImage: null, + ), ); notifyListeners(); } @@ -530,6 +569,7 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { chatEventId: 1, fileTypeId: null, targetUserId: targetUserId, targetUserName: targetUserName, isAttachment: false, chatReplyId: null, isReply: false, isImageLoaded: false, image: null); } // normal Text msg if (isFileSelected && !isMsgReply) { + bool isImage = false; print("Normal Attachment Msg"); Utils.showLoading(context); dynamic value = await uploadAttachments(AppState().chatDetails!.response!.id.toString(), selectedFile); @@ -605,6 +645,7 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { String? getFileExtension(String fileName) { try { + print("Ext: " + "." + fileName.split('.').last); return "." + fileName.split('.').last; } catch (e) { return null; @@ -740,6 +781,7 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { for (ChatUserImageModel uImage in chatImages) { if (user.email == uImage.email) { user.image = uImage.profilePicture ?? ""; + user.userLocalDownlaodedImage = await downloadImageLocal(uImage.profilePicture, user.id.toString()); user.isImageLoading = false; user.isImageLoaded = true; } @@ -749,6 +791,7 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { for (ChatUserImageModel uImage in chatImages) { if (favUser.email == uImage.email) { favUser.image = uImage.profilePicture ?? ""; + favUser.userLocalDownlaodedImage = await downloadImageLocal(uImage.profilePicture, favUser.id.toString()); favUser.isImageLoading = false; favUser.isImageLoaded = true; } @@ -758,6 +801,35 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { notifyListeners(); } + Future downloadImageLocal(String? encodedBytes, String userID) async { + File? myfile; + if (encodedBytes == null) { + return myfile; + } else { + await deleteFile(userID); + Uint8List decodedBytes = base64Decode(encodedBytes); + Directory appDocumentsDirectory = await getApplicationDocumentsDirectory(); // 1 + late File imageFile = File("${appDocumentsDirectory.path}/$userID.jpg"); + imageFile.writeAsBytesSync(decodedBytes); + return imageFile; + } + } + + Future deleteFile(String userID) async { + Directory appDocumentsDirectory = await getApplicationDocumentsDirectory(); + late File imageFile = File('${appDocumentsDirectory.path}/$userID.jpg'); + if (await imageFile.exists()) { + await imageFile.delete(); + } + } + + Future downChatMedia(Uint8List bytes, String ext) async { + String dir = (await getApplicationDocumentsDirectory()).path; + File file = File("$dir/" + DateTime.now().millisecondsSinceEpoch.toString() + "." + ext); + await file.writeAsBytes(bytes); + return file.path; + } + void setMsgTune() async { AudioPlayer player = AudioPlayer(); await player.setVolume(1.0); @@ -775,4 +847,29 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { print("Error: $e"); } } + + Future getChatMedia({required String fileName, required String fileTypeName, required int fileTypeID}) async { + if (fileTypeID == 1 || fileTypeID == 5 || fileTypeID == 7 || fileTypeID == 6 || fileTypeID == 8 || fileTypeID == 2) { + Uint8List encodedString = await ChatApiClient().downloadURL(fileName: fileName, fileTypeDescription: getFileTypeDescription(fileTypeName)); + try { + String path = await downChatMedia(encodedString, fileTypeName ?? ""); + OpenFile.open(path); + } catch (e) { + Utils.showToast("Cannot open file."); + } + } + } + + void onNewChatConversion(List? params) { + dynamic items = params!.toList(); + logger.d(items); + chatUConvCounter = items[0]["singleChatCount"] ?? 0; + notifyListeners(); + } + + Future invokeChatCounter({required int userId}) async { + print("invokedd"); + await chatHubConnection.invoke("GetChatCounversationCount", args: [userId]); + return ""; + } } diff --git a/lib/provider/dashboard_provider_model.dart b/lib/provider/dashboard_provider_model.dart index 48531b7..c1a186a 100644 --- a/lib/provider/dashboard_provider_model.dart +++ b/lib/provider/dashboard_provider_model.dart @@ -7,7 +7,6 @@ import 'package:mohem_flutter_app/classes/utils.dart'; import 'package:mohem_flutter_app/config/routes.dart'; import 'package:mohem_flutter_app/generated/locale_keys.g.dart'; import 'package:mohem_flutter_app/main.dart'; -import 'package:mohem_flutter_app/models/chat/chat_count_conversation_model.dart'; import 'package:mohem_flutter_app/models/dashboard/drawer_menu_item_model.dart'; import 'package:mohem_flutter_app/models/dashboard/get_accrual_balances_list_model.dart'; import 'package:mohem_flutter_app/models/dashboard/get_attendance_tracking_list_model.dart'; @@ -20,6 +19,7 @@ import 'package:mohem_flutter_app/models/dashboard/mohemm_itg_pending_task_respo import 'package:mohem_flutter_app/models/generic_response_model.dart'; import 'package:mohem_flutter_app/models/itg/itg_response_model.dart'; import 'package:mohem_flutter_app/models/offers_and_discounts/get_offers_list.dart'; +import 'package:mohem_flutter_app/ui/landing/dashboard_screen.dart'; import 'package:mohem_flutter_app/widgets/dialogs/confirm_dialog.dart'; /// Mix-in [DiagnosticableTreeMixin] to have access to [debugFillProperties] for the devtool @@ -35,9 +35,7 @@ class DashboardProviderModel with ChangeNotifier, DiagnosticableTreeMixin { bool isWorkListLoading = true; int workListCounter = 0; - //Chat - bool isChatCounterLoding = true; - int chatUConvCounter = 0; + //Misssing Swipe bool isMissingSwipeLoading = true; @@ -96,8 +94,6 @@ class DashboardProviderModel with ChangeNotifier, DiagnosticableTreeMixin { accrualList = null; leaveBalanceAccrual = null; - isChatCounterLoding = true; - chatUConvCounter = 0; ticketBalance = 0; isServicesMenusLoading = true; @@ -273,21 +269,6 @@ class DashboardProviderModel with ChangeNotifier, DiagnosticableTreeMixin { MohemmItgResponseItem? res = await DashboardApiClient().getITGPageNotification(); return res; } - - void fetchChatCounts() async { - try { - ChatUnreadCovnCountModel response = await DashboardApiClient().getChatCount(); - chatUConvCounter = response.singleChatCount!; - isChatCounterLoding = false; - notifyListeners(); - } catch (ex) { - logger.wtf(ex); - notifyListeners(); - Utils.handleException(ex, null, null); - } - } - - void notify() { notifyListeners(); } diff --git a/lib/ui/chat/chat_bubble.dart b/lib/ui/chat/chat_bubble.dart index ea43004..3e99678 100644 --- a/lib/ui/chat/chat_bubble.dart +++ b/lib/ui/chat/chat_bubble.dart @@ -1,17 +1,23 @@ +import 'dart:convert'; import 'dart:typed_data'; import 'package:flutter/material.dart'; +import 'package:flutter_svg/flutter_svg.dart'; import 'package:mohem_flutter_app/api/api_client.dart'; import 'package:mohem_flutter_app/api/chat/chat_api_client.dart'; import 'package:mohem_flutter_app/app_state/app_state.dart'; import 'package:mohem_flutter_app/classes/colors.dart'; +import 'package:mohem_flutter_app/classes/utils.dart'; import 'package:mohem_flutter_app/extensions/int_extensions.dart'; import 'package:mohem_flutter_app/extensions/string_extensions.dart'; import 'package:mohem_flutter_app/extensions/widget_extensions.dart'; import 'package:mohem_flutter_app/main.dart'; import 'package:mohem_flutter_app/models/chat/get_single_user_chat_list_model.dart'; +import 'package:mohem_flutter_app/provider/chat_provider_model.dart'; import 'package:mohem_flutter_app/ui/chat/chat_full_image_preview.dart'; import 'package:mohem_flutter_app/widgets/bottom_sheet.dart'; +import 'package:open_file/open_file.dart'; +import 'package:provider/provider.dart'; // todo: @aamir use extension methods, and use correct widgets. @@ -19,11 +25,12 @@ class ChatBubble extends StatelessWidget { ChatBubble({Key? key, required this.dateTime, required this.cItem}) : super(key: key); final String dateTime; final SingleUserChatModel cItem; - bool isCurrentUser = false; bool isSeen = false; bool isReplied = false; int? fileTypeID; + String? fileTypeName; + late ChatProviderModel data; String? fileTypeDescription; bool isDelivered = false; @@ -35,6 +42,7 @@ class ChatBubble extends StatelessWidget { isSeen = cItem.isSeen == true ? true : false; isReplied = cItem.userChatReplyResponse != null ? true : false; fileTypeID = cItem.fileTypeId; + fileTypeName = cItem.fileTypeResponse != null ? cItem.fileTypeResponse!.fileTypeName : ""; fileTypeDescription = cItem.fileTypeResponse != null ? cItem.fileTypeResponse!.fileTypeDescription : ""; isDelivered = cItem.currentUserId == AppState().chatDetails!.response!.id && cItem.isDelivered == true ? true : false; userName = AppState().chatDetails!.response!.userName == cItem.currentUserName.toString() ? "You" : cItem.currentUserName.toString(); @@ -45,6 +53,8 @@ class ChatBubble extends StatelessWidget { Size windowSize = MediaQuery.of(context).size; screenOffset = Offset(windowSize.width / 2, windowSize.height / 2); makeAssign(); + data = Provider.of(context, listen: false); + return isCurrentUser ? currentUser(context) : receiptUser(context); } @@ -77,22 +87,6 @@ class ChatBubble extends StatelessWidget { if (cItem.userChatReplyResponse != null && cItem.userChatReplyResponse!.fileTypeId == 12 || cItem.userChatReplyResponse!.fileTypeId == 3 || cItem.userChatReplyResponse!.fileTypeId == 4) - // Container( - // padding: EdgeInsets.all(0), // Border width - // decoration: BoxDecoration(color: Colors.red, borderRadius: const BorderRadius.all(Radius.circular(8))), - // child: ClipRRect( - // borderRadius: const BorderRadius.all( - // Radius.circular(8), - // ), - // child: SizedBox.fromSize( - // size: Size.fromRadius(8), // Image radius - // child: showImage( - // isReplyPreview: true, - // fileName: cItem.userChatReplyResponse!.contant!, - // fileTypeDescription: cItem.userChatReplyResponse!.fileTypeResponse!.fileTypeDescription ?? "image/jpg"), - // ), - // ), - // ), ClipRRect( borderRadius: BorderRadius.circular(8.0), child: SizedBox( @@ -116,8 +110,15 @@ class ChatBubble extends StatelessWidget { anchorPoint: screenOffset, builder: (BuildContext context) => ChatImagePreviewScreen(imgTitle: cItem.contant!, img: cItem.image!), ); - }), - cItem.contant!.toText12(), + }) + else + Row( + children: [ + if (fileTypeID == 1 || fileTypeID == 5 || fileTypeID == 7 || fileTypeID == 6 || fileTypeID == 8 || fileTypeID == 2) + SvgPicture.asset(data.getType(fileTypeName ?? ""), height: 30, width: 22, alignment: Alignment.center, fit: BoxFit.cover).paddingOnly(left: 0, right: 10), + (cItem.contant ?? "").toText12(), + ], + ), Align( alignment: Alignment.centerRight, child: Row( @@ -200,7 +201,16 @@ class ChatBubble extends StatelessWidget { ); }) else - (cItem.contant ?? "").toText12(color: Colors.white), + Row( + children: [ + if (fileTypeID == 1 || fileTypeID == 5 || fileTypeID == 7 || fileTypeID == 6 || fileTypeID == 8 || fileTypeID == 2) + SvgPicture.asset(data.getType(fileTypeName ?? ""), height: 30, width: 22, alignment: Alignment.center, fit: BoxFit.cover).paddingOnly( + left: 0, + right: 10, + ), + (cItem.contant ?? "").toText12(color: Colors.white), + ], + ), Align( alignment: Alignment.centerRight, child: dateTime.toText10(color: Colors.white.withOpacity(.71)), diff --git a/lib/ui/chat/chat_detailed_screen.dart b/lib/ui/chat/chat_detailed_screen.dart index 2ab5fd8..335eda7 100644 --- a/lib/ui/chat/chat_detailed_screen.dart +++ b/lib/ui/chat/chat_detailed_screen.dart @@ -12,6 +12,7 @@ import 'package:mohem_flutter_app/extensions/widget_extensions.dart'; import 'package:mohem_flutter_app/generated/locale_keys.g.dart'; import 'package:mohem_flutter_app/main.dart'; import 'package:mohem_flutter_app/models/chat/call.dart'; +import 'package:mohem_flutter_app/models/chat/get_search_user_chat_model.dart'; import 'package:mohem_flutter_app/models/chat/get_single_user_chat_list_model.dart'; import 'package:mohem_flutter_app/provider/chat_provider_model.dart'; import 'package:mohem_flutter_app/ui/chat/call/chat_outgoing_call_screen.dart'; @@ -23,9 +24,15 @@ import 'package:pull_to_refresh/pull_to_refresh.dart'; import 'package:signalr_netcore/signalr_client.dart'; import 'package:swipe_to/swipe_to.dart'; +class ChatDetailedScreenParams { + ChatUser? chatUser; + bool? isNewChat; + + ChatDetailedScreenParams(this.chatUser, this.isNewChat); +} + class ChatDetailScreen extends StatefulWidget { - // ignore: prefer_const_constructors_in_immutables - ChatDetailScreen({Key? key}) : super(key: key); + const ChatDetailScreen({Key? key}) : super(key: key); @override State createState() => _ChatDetailScreenState(); @@ -33,16 +40,16 @@ class ChatDetailScreen extends StatefulWidget { class _ChatDetailScreenState extends State { final RefreshController _rc = RefreshController(initialRefresh: false); - dynamic userDetails; late ChatProviderModel data; + ChatDetailedScreenParams? params; void getMoreChat() async { - if (userDetails != null) { + if (params != null) { data.paginationVal = data.paginationVal + 10; - if (userDetails != null) { + if (params != null) { data.getSingleUserChatHistory( senderUID: AppState().chatDetails!.response!.id!.toInt(), - receiverUID: userDetails["targetUser"].id, + receiverUID: params!.chatUser!.id!, loadMore: true, isNewChat: false, ); @@ -56,14 +63,14 @@ class _ChatDetailScreenState extends State { @override Widget build(BuildContext context) { - userDetails = ModalRoute.of(context)!.settings.arguments; + params = ModalRoute.of(context)!.settings.arguments as ChatDetailedScreenParams; data = Provider.of(context, listen: false); - if (userDetails != null) { + if (params != null) { data.getSingleUserChatHistory( senderUID: AppState().chatDetails!.response!.id!.toInt(), - receiverUID: userDetails["targetUser"].id, + receiverUID: params!.chatUser!.id!, loadMore: false, - isNewChat: userDetails["isNewChat"], + isNewChat: params!.isNewChat!, ); } @@ -71,9 +78,10 @@ class _ChatDetailScreenState extends State { backgroundColor: MyColors.backgroundColor, appBar: AppBarWidget( context, - title: userDetails["targetUser"].userName.toString().replaceAll(".", " ").capitalizeFirstofEach, + title: params!.chatUser!.userName.toString().replaceAll(".", " ").capitalizeFirstofEach, showHomeButton: false, - image: userDetails["targetUser"].image == null || userDetails["targetUser"].image.isEmpty ? null : userDetails["targetUser"].image, + image: params!.chatUser!.image == null || params!.chatUser!.image.isEmpty ? null : params!.chatUser!.image, + showTyping: true, actions: [ SvgPicture.asset("assets/icons/chat/call.svg", width: 21, height: 23).onPress(() { // makeCall(callType: "AUDIO", con: hubConnection); @@ -124,8 +132,13 @@ class _ChatDetailScreenState extends State { m.userChatHistory[i], ); }, - ).onPress(() { - logger.d(jsonEncode(m.userChatHistory[i])); + ).onPress(() async { + if (m.userChatHistory[i].fileTypeResponse != null) { + m.getChatMedia( + fileTypeName: m.userChatHistory[i].fileTypeResponse!.fileTypeName ?? "", + fileTypeID: m.userChatHistory[i].fileTypeResponse!.fileTypeId!, + fileName: m.userChatHistory[i].contant!); + } }); }, ), @@ -152,7 +165,7 @@ class _ChatDetailScreenState extends State { ], ).expanded, 12.width, - if (m.isMsgReply && m.repliedMsg.isNotEmpty) showReplyImage(m.repliedMsg), + if (m.isMsgReply && m.repliedMsg.isNotEmpty) showReplyImage(m.repliedMsg, m), 12.width, const Icon(Icons.cancel, size: 23, color: MyColors.grey7BColor).onPress(m.closeMe), ], @@ -209,7 +222,7 @@ class _ChatDetailScreenState extends State { ), ).paddingOnly(right: 25), SvgPicture.asset("assets/icons/chat/chat_send_icon.svg", height: 26, width: 26).onPress( - () => m.sendChatMessage(userDetails["targetUser"].id, userDetails["targetUser"].userName, context), + () => m.sendChatMessage(params!.chatUser!.id!, params!.chatUser!.userName!, context), ), ], ), @@ -223,7 +236,8 @@ class _ChatDetailScreenState extends State { ); } - Widget showReplyImage(List data) { + Widget showReplyImage(List data, ChatProviderModel m) { + logger.d(jsonEncode(data)); if (data.first.isImageLoaded! && data.first.image != null) { return Container( width: 43, @@ -232,7 +246,14 @@ class _ChatDetailScreenState extends State { border: Border.all(color: MyColors.darkGrey3BColor, width: 1), borderRadius: BorderRadius.circular(10.0), image: DecorationImage(image: MemoryImage(data.first.image!), fit: BoxFit.cover)), ); } else { - return const SizedBox(); + return data.first.fileTypeResponse != null + ? Container( + width: 43, + height: 43, + constraints: BoxConstraints(), + decoration: BoxDecoration(border: Border.all(color: MyColors.darkGrey3BColor, width: 1), borderRadius: BorderRadius.circular(10.0), color: Colors.white), + child: SvgPicture.asset(m.getType(data.first.fileTypeResponse!.fileTypeName), alignment: Alignment.center, fit: BoxFit.cover).paddingOnly(left: 5, right: 5, top: 5, bottom: 5)) + : SizedBox(); } } @@ -240,7 +261,7 @@ class _ChatDetailScreenState extends State { print("================== Make call Triggered ============================"); Map json = { "callerID": AppState().chatDetails!.response!.id!.toString(), - "callReceiverID": userDetails["targetUser"].id.toString(), + "callReceiverID": params!.chatUser!.id.toString(), "notification_foreground": "true", "message": "Aamir is calling", "title": "Video Call", @@ -259,7 +280,7 @@ class _ChatDetailScreenState extends State { { "isSeen": false, "isDelivered": false, - "targetUserId": userDetails["targetUser"].id, + "targetUserId": params!.chatUser!.id!, "targetUserStatus": 4, } ], diff --git a/lib/ui/chat/chat_home.dart b/lib/ui/chat/chat_home.dart index 76aa027..7d0631e 100644 --- a/lib/ui/chat/chat_home.dart +++ b/lib/ui/chat/chat_home.dart @@ -30,6 +30,16 @@ class _ChatHomeState extends State { super.initState(); data = Provider.of(context, listen: false); data.registerEvents(); + } + + @override + void dispose() { + super.dispose(); + data.clearAll(); + } + + void fetchAgain() { + print("Fetch Triggered"); if (chatHubConnection.state != HubConnectionState.Connected) { data.getUserAutoLoginToken().whenComplete(() async { await data.buildHubConnection(); @@ -42,14 +52,9 @@ class _ChatHomeState extends State { } } - @override - void dispose() { - super.dispose(); - data.clearAll(); - } - @override Widget build(BuildContext context) { + fetchAgain(); return Scaffold( backgroundColor: MyColors.white, appBar: AppBarWidget(context, title: LocaleKeys.chat.tr(), showHomeButton: true), @@ -85,7 +90,6 @@ class _ChatHomeState extends State { onPageChanged: (int pageIndex) { setState(() { tabIndex = pageIndex; - }); }, children: [ diff --git a/lib/ui/chat/chat_home_screen.dart b/lib/ui/chat/chat_home_screen.dart index 804332a..669504f 100644 --- a/lib/ui/chat/chat_home_screen.dart +++ b/lib/ui/chat/chat_home_screen.dart @@ -1,22 +1,19 @@ import 'dart:convert'; -import 'dart:typed_data'; import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; -import 'package:flutter_des/flutter_des.dart'; import 'package:flutter_svg/flutter_svg.dart'; import 'package:mohem_flutter_app/app_state/app_state.dart'; import 'package:mohem_flutter_app/classes/colors.dart'; -import 'package:mohem_flutter_app/classes/encryption.dart'; import 'package:mohem_flutter_app/config/routes.dart'; import 'package:mohem_flutter_app/extensions/string_extensions.dart'; import 'package:mohem_flutter_app/extensions/widget_extensions.dart'; import 'package:mohem_flutter_app/generated/locale_keys.g.dart'; import 'package:mohem_flutter_app/provider/chat_provider_model.dart'; +import 'package:mohem_flutter_app/ui/chat/chat_detailed_screen.dart'; import 'package:mohem_flutter_app/widgets/bottom_sheet.dart'; import 'package:mohem_flutter_app/widgets/bottom_sheets/search_employee_bottom_sheet.dart'; -import 'package:mohem_flutter_app/widgets/circular_avatar.dart'; import 'package:mohem_flutter_app/widgets/shimmer/dashboard_shimmer_widget.dart'; import 'package:provider/provider.dart'; import 'package:pull_to_refresh/pull_to_refresh.dart'; @@ -53,7 +50,9 @@ class _ChatHomeScreenState extends State { body: Consumer( builder: (BuildContext context, ChatProviderModel m, Widget? child) { return m.isLoading - ? ChatHomeShimmer(isDetailedScreen: false,) + ? ChatHomeShimmer( + isDetailedScreen: false, + ) : Column( children: [ TextField( @@ -102,20 +101,24 @@ class _ChatHomeScreenState extends State { height: 48, width: 48, ).toShimmer().circle(30), - if (m.searchedChats![index].isImageLoaded! && m.searchedChats![index].image.isNotEmpty) - CircularAvatar( - radius: 20, - height: 48, - width: 48, - url: m.searchedChats![index].image, - isImageBase64: true, - ), - if (!m.searchedChats![index].isImageLoading! && m.searchedChats![index].isImageLoaded! && m.searchedChats![index].image.isEmpty) + if (!m.searchedChats![index].isImageLoading! && m.searchedChats![index].userLocalDownlaodedImage == null) SvgPicture.asset( "assets/images/user.svg", height: 48, width: 48, ), + if (!m.searchedChats![index].isImageLoading! && m.searchedChats![index].userLocalDownlaodedImage != null) + Container( + width: 48.0, + height: 48.0, + decoration: BoxDecoration( + shape: BoxShape.circle, + image: DecorationImage( + fit: BoxFit.cover, + image: FileImage(m.searchedChats![index].userLocalDownlaodedImage!), + ), + ), + ), Positioned( right: 5, bottom: 1, @@ -128,14 +131,13 @@ class _ChatHomeScreenState extends State { ).circle(10), ) ], - ).onPress(() { - print(jsonEncode(m.searchedChats![index])); - }), + ), Column( mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start, children: [ (m.searchedChats![index].userName!.replaceFirst(".", " ").capitalizeFirstofEach ?? "").toText14(color: MyColors.darkTextColor).paddingOnly(left: 11, top: 13), + (m.searchedChats![index].isTyping! ? "Typing ..." : "").toText10(color: MyColors.lightGreyColor).paddingOnly(left: 11, top: 0), ], ).expanded, SizedBox( @@ -194,7 +196,7 @@ class _ChatHomeScreenState extends State { Navigator.pushNamed( context, AppRoutes.chatDetailed, - arguments: {"targetUser": m.searchedChats![index], "isNewChat": false}, + arguments: ChatDetailedScreenParams(m.searchedChats![index], false), ).then((Object? value) { m.clearSelections(); m.notifyListeners(); diff --git a/lib/ui/chat/favorite_users_screen.dart b/lib/ui/chat/favorite_users_screen.dart index 9378625..157a884 100644 --- a/lib/ui/chat/favorite_users_screen.dart +++ b/lib/ui/chat/favorite_users_screen.dart @@ -9,6 +9,7 @@ import 'package:mohem_flutter_app/classes/utils.dart'; import 'package:mohem_flutter_app/config/routes.dart'; import 'package:mohem_flutter_app/extensions/string_extensions.dart'; import 'package:mohem_flutter_app/extensions/widget_extensions.dart'; +import 'package:mohem_flutter_app/ui/chat/chat_detailed_screen.dart'; import 'package:mohem_flutter_app/widgets/circular_avatar.dart'; import 'package:mohem_flutter_app/widgets/shimmer/dashboard_shimmer_widget.dart'; import 'package:provider/provider.dart'; @@ -45,20 +46,24 @@ class ChatFavoriteUsersScreen extends StatelessWidget { height: 48, width: 48, ).toShimmer().circle(30), - if (m.favUsersList![index].isImageLoaded! && m.favUsersList![index].image != null && m.favUsersList![index].image.isNotEmpty) - CircularAvatar( - radius: 20, - height: 48, - width: 48, - url: m.favUsersList![index].image, - isImageBase64: true, - ), - if (!m.favUsersList![index].isImageLoading! && m.favUsersList![index].isImageLoaded! && m.favUsersList![index].image.isEmpty) + if (!m.favUsersList![index].isImageLoading! && m.favUsersList![index].userLocalDownlaodedImage == null) SvgPicture.asset( "assets/images/user.svg", height: 48, width: 48, ), + if (!m.favUsersList![index].isImageLoading! && m.favUsersList![index].userLocalDownlaodedImage != null) + Container( + width: 48.0, + height: 48.0, + decoration: BoxDecoration( + shape: BoxShape.circle, + image: DecorationImage( + fit: BoxFit.cover, + image: FileImage(m.favUsersList![index].userLocalDownlaodedImage!), + ), + ), + ), Positioned( right: 5, bottom: 1, @@ -106,7 +111,7 @@ class ChatFavoriteUsersScreen extends StatelessWidget { Navigator.pushNamed( context, AppRoutes.chatDetailed, - arguments: {"targetUser": m.favUsersList![index], "isNewChat": false}, + arguments: ChatDetailedScreenParams(m.favUsersList![index], false), ).then( (Object? value) { m.clearSelections(); diff --git a/lib/ui/landing/dashboard_screen.dart b/lib/ui/landing/dashboard_screen.dart index 4e6988b..0e9053a 100644 --- a/lib/ui/landing/dashboard_screen.dart +++ b/lib/ui/landing/dashboard_screen.dart @@ -90,7 +90,6 @@ class _DashboardScreenState extends State { data.fetchMenuEntries(); data.getCategoryOffersListAPI(context); marathonProvider.getMarathonDetailsFromApi(); - data.fetchChatCounts(); _refreshController.refreshCompleted(); } @@ -503,8 +502,8 @@ class _DashboardScreenState extends State { "assets/icons/chat/chat.svg", color: currentIndex == 4 ? MyColors.grey3AColor : MyColors.grey98Color, ).paddingAll(4), - Consumer( - builder: (BuildContext cxt, DashboardProviderModel data, Widget? child) { + Consumer( + builder: (BuildContext cxt, ChatProviderModel data, Widget? child) { return Positioned( right: 0, top: 0, @@ -538,9 +537,7 @@ class _DashboardScreenState extends State { } else if (index == 3) { Navigator.pushNamed(context, AppRoutes.itemsForSale); } else if (index == 4) { - Navigator.pushNamed(context, AppRoutes.chat).then((Object? value) { - data.fetchChatCounts(); - }); + Navigator.pushNamed(context, AppRoutes.chat); } }, ), diff --git a/lib/widgets/app_bar_widget.dart b/lib/widgets/app_bar_widget.dart index 199074a..3903327 100644 --- a/lib/widgets/app_bar_widget.dart +++ b/lib/widgets/app_bar_widget.dart @@ -5,7 +5,9 @@ import 'package:mohem_flutter_app/config/routes.dart'; import 'package:mohem_flutter_app/extensions/int_extensions.dart'; import 'package:mohem_flutter_app/extensions/string_extensions.dart'; import 'package:mohem_flutter_app/extensions/widget_extensions.dart'; +import 'package:mohem_flutter_app/provider/chat_provider_model.dart'; import 'package:mohem_flutter_app/widgets/circular_avatar.dart'; +import 'package:provider/provider.dart'; AppBar AppBarWidget(BuildContext context, {required String title, @@ -13,6 +15,7 @@ AppBar AppBarWidget(BuildContext context, bool showNotificationButton = false, bool showMemberButton = false, String? image, + bool showTyping = false, List? actions, void Function()? onHomeTapped, void Function()? onBackTapped}) { @@ -43,6 +46,16 @@ AppBar AppBarWidget(BuildContext context, ), if (image != null) 14.width, title.toText24(color: MyColors.darkTextColor, isBold: true).expanded, + if(showTyping) + Consumer( + builder: (BuildContext cxt, ChatProviderModel data, Widget? child) { + if (data.currentUserTyping) { + return ("Typing ...").toText10(color: MyColors.lightGreyColor).paddingOnly(left: 5, top: 0); + } else { + return const SizedBox(); + } + }, + ), ], ), centerTitle: false, diff --git a/lib/widgets/bottom_sheets/search_employee_bottom_sheet.dart b/lib/widgets/bottom_sheets/search_employee_bottom_sheet.dart index 475c4a5..77501bc 100644 --- a/lib/widgets/bottom_sheets/search_employee_bottom_sheet.dart +++ b/lib/widgets/bottom_sheets/search_employee_bottom_sheet.dart @@ -20,6 +20,7 @@ import 'package:mohem_flutter_app/models/chat/get_search_user_chat_model.dart'; import 'package:mohem_flutter_app/models/get_action_history_list_model.dart'; import 'package:mohem_flutter_app/models/worklist/get_favorite_replacements_model.dart'; import 'package:mohem_flutter_app/models/worklist/replacement_list_model.dart'; +import 'package:mohem_flutter_app/ui/chat/chat_detailed_screen.dart'; import 'package:mohem_flutter_app/widgets/button/default_button.dart'; import 'package:mohem_flutter_app/widgets/circular_avatar.dart'; import 'package:mohem_flutter_app/widgets/dynamic_forms/dynamic_textfield_widget.dart'; @@ -238,7 +239,7 @@ class _SearchEmployeeBottomSheetState extends State { Navigator.pushNamed( context, AppRoutes.chatDetailed, - arguments: {"targetUser": chatUsersList![index], "isNewChat": true}, + arguments: ChatDetailedScreenParams(chatUsersList![index], true), ); }, ), diff --git a/lib/widgets/image_picker.dart b/lib/widgets/image_picker.dart index 69bf7e4..75466fc 100644 --- a/lib/widgets/image_picker.dart +++ b/lib/widgets/image_picker.dart @@ -45,7 +45,7 @@ class ImageOptions { onFilesTap: () async { FilePickerResult? result = await FilePicker.platform.pickFiles( type: FileType.custom, - allowedExtensions: ['jpg', 'jpeg ', 'pdf', 'txt', 'docx', 'doc', 'pptx', 'xlsx', 'png', 'rar', 'zip', 'xls'], + allowedExtensions: ['jpg', 'jpeg ', 'pdf', 'txt', 'docx', 'doc', 'pptx', 'xlsx', 'png', 'rar', 'zip',], ); List files = result!.paths.map((path) => File(path!)).toList(); image(result.files.first.path.toString(), files.first); From ff3592a120223a1e468e8e69bae1896c6fe6f80e Mon Sep 17 00:00:00 2001 From: "Aamir.Muhammad" Date: Mon, 12 Dec 2022 14:48:38 +0300 Subject: [PATCH 03/42] Chat Fixes & Counter Updated on Signal R --- lib/provider/chat_provider_model.dart | 13 +---- lib/ui/chat/chat_bubble.dart | 6 +-- lib/ui/chat/chat_detailed_screen.dart | 4 +- lib/ui/chat/chat_home_screen.dart | 2 +- lib/widgets/app_bar_widget.dart | 26 --------- lib/widgets/chat_app_bar_widge.dart | 78 +++++++++++++++++++++++++++ 6 files changed, 86 insertions(+), 43 deletions(-) create mode 100644 lib/widgets/chat_app_bar_widge.dart diff --git a/lib/provider/chat_provider_model.dart b/lib/provider/chat_provider_model.dart index c0dbb52..4263569 100644 --- a/lib/provider/chat_provider_model.dart +++ b/lib/provider/chat_provider_model.dart @@ -44,6 +44,7 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { List favUsersList = []; int paginationVal = 0; bool currentUserTyping = false; + int? cTypingUserId = 0; //Chat int chatUConvCounter = 0; @@ -412,17 +413,6 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { ); } } - if (isChatScreenActive) { - currentUserTyping = true; - notifyListeners(); - Future.delayed( - const Duration(seconds: 2), - () { - currentUserTyping = false; - notifyListeners(); - }, - ); - } notifyListeners(); } @@ -869,7 +859,6 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { } Future invokeChatCounter({required int userId}) async { - print("invokedd"); await chatHubConnection.invoke("GetChatCounversationCount", args: [userId]); return ""; } diff --git a/lib/ui/chat/chat_bubble.dart b/lib/ui/chat/chat_bubble.dart index 3e99678..288a13f 100644 --- a/lib/ui/chat/chat_bubble.dart +++ b/lib/ui/chat/chat_bubble.dart @@ -116,7 +116,7 @@ class ChatBubble extends StatelessWidget { children: [ if (fileTypeID == 1 || fileTypeID == 5 || fileTypeID == 7 || fileTypeID == 6 || fileTypeID == 8 || fileTypeID == 2) SvgPicture.asset(data.getType(fileTypeName ?? ""), height: 30, width: 22, alignment: Alignment.center, fit: BoxFit.cover).paddingOnly(left: 0, right: 10), - (cItem.contant ?? "").toText12(), + (cItem.contant ?? "").toText12().expanded, ], ), Align( @@ -208,12 +208,12 @@ class ChatBubble extends StatelessWidget { left: 0, right: 10, ), - (cItem.contant ?? "").toText12(color: Colors.white), + (cItem.contant ?? "").toText12(color: Colors.white).expanded, ], ), Align( alignment: Alignment.centerRight, - child: dateTime.toText10(color: Colors.white.withOpacity(.71)), + child: dateTime.toText10(color: Colors.white.withOpacity(.71),), ), ], ), diff --git a/lib/ui/chat/chat_detailed_screen.dart b/lib/ui/chat/chat_detailed_screen.dart index 335eda7..9454e75 100644 --- a/lib/ui/chat/chat_detailed_screen.dart +++ b/lib/ui/chat/chat_detailed_screen.dart @@ -18,6 +18,7 @@ import 'package:mohem_flutter_app/provider/chat_provider_model.dart'; import 'package:mohem_flutter_app/ui/chat/call/chat_outgoing_call_screen.dart'; import 'package:mohem_flutter_app/ui/chat/chat_bubble.dart'; import 'package:mohem_flutter_app/widgets/app_bar_widget.dart'; +import 'package:mohem_flutter_app/widgets/chat_app_bar_widge.dart'; import 'package:mohem_flutter_app/widgets/shimmer/dashboard_shimmer_widget.dart'; import 'package:provider/provider.dart'; import 'package:pull_to_refresh/pull_to_refresh.dart'; @@ -76,12 +77,13 @@ class _ChatDetailScreenState extends State { return Scaffold( backgroundColor: MyColors.backgroundColor, - appBar: AppBarWidget( + appBar: ChatAppBarWidget( context, title: params!.chatUser!.userName.toString().replaceAll(".", " ").capitalizeFirstofEach, showHomeButton: false, image: params!.chatUser!.image == null || params!.chatUser!.image.isEmpty ? null : params!.chatUser!.image, showTyping: true, + chatUser: params!.chatUser, actions: [ SvgPicture.asset("assets/icons/chat/call.svg", width: 21, height: 23).onPress(() { // makeCall(callType: "AUDIO", con: hubConnection); diff --git a/lib/ui/chat/chat_home_screen.dart b/lib/ui/chat/chat_home_screen.dart index 669504f..fe4291f 100644 --- a/lib/ui/chat/chat_home_screen.dart +++ b/lib/ui/chat/chat_home_screen.dart @@ -137,7 +137,7 @@ class _ChatHomeScreenState extends State { crossAxisAlignment: CrossAxisAlignment.start, children: [ (m.searchedChats![index].userName!.replaceFirst(".", " ").capitalizeFirstofEach ?? "").toText14(color: MyColors.darkTextColor).paddingOnly(left: 11, top: 13), - (m.searchedChats![index].isTyping! ? "Typing ..." : "").toText10(color: MyColors.lightGreyColor).paddingOnly(left: 11, top: 0), + (m.searchedChats![index].isTyping! ? "Typing ..." : "").toText10(color: MyColors.darkTextColor).paddingOnly(left: 11, top: 0), ], ).expanded, SizedBox( diff --git a/lib/widgets/app_bar_widget.dart b/lib/widgets/app_bar_widget.dart index 3903327..8bca3f3 100644 --- a/lib/widgets/app_bar_widget.dart +++ b/lib/widgets/app_bar_widget.dart @@ -14,19 +14,11 @@ AppBar AppBarWidget(BuildContext context, bool showHomeButton = true, bool showNotificationButton = false, bool showMemberButton = false, - String? image, - bool showTyping = false, List? actions, void Function()? onHomeTapped, void Function()? onBackTapped}) { return AppBar( leadingWidth: 0, - // leading: GestureDetector( - // behavior: HitTestBehavior.opaque, - // onTap: Feedback.wrapForTap(() => Navigator.maybePop(context), context), - // child: const Icon(Icons.arrow_back_ios, color: MyColors.darkIconColor), - // ), - //titleSpacing: -1.44, title: Row( children: [ GestureDetector( @@ -37,25 +29,7 @@ AppBar AppBarWidget(BuildContext context, child: const Icon(Icons.arrow_back_ios, color: MyColors.darkIconColor), ), 4.width, - if (image != null) - CircularAvatar( - url: image, - height: 40, - width: 40, - isImageBase64: true, - ), - if (image != null) 14.width, title.toText24(color: MyColors.darkTextColor, isBold: true).expanded, - if(showTyping) - Consumer( - builder: (BuildContext cxt, ChatProviderModel data, Widget? child) { - if (data.currentUserTyping) { - return ("Typing ...").toText10(color: MyColors.lightGreyColor).paddingOnly(left: 5, top: 0); - } else { - return const SizedBox(); - } - }, - ), ], ), centerTitle: false, diff --git a/lib/widgets/chat_app_bar_widge.dart b/lib/widgets/chat_app_bar_widge.dart new file mode 100644 index 0000000..3a9dee4 --- /dev/null +++ b/lib/widgets/chat_app_bar_widge.dart @@ -0,0 +1,78 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_svg/flutter_svg.dart'; +import 'package:mohem_flutter_app/classes/colors.dart'; +import 'package:mohem_flutter_app/config/routes.dart'; +import 'package:mohem_flutter_app/extensions/int_extensions.dart'; +import 'package:mohem_flutter_app/extensions/string_extensions.dart'; +import 'package:mohem_flutter_app/extensions/widget_extensions.dart'; +import 'package:mohem_flutter_app/models/chat/get_search_user_chat_model.dart'; +import 'package:mohem_flutter_app/provider/chat_provider_model.dart'; +import 'package:mohem_flutter_app/widgets/circular_avatar.dart'; +import 'package:provider/provider.dart'; + +AppBar ChatAppBarWidget(BuildContext context, + {required String title, + bool showHomeButton = true, + String? image, + ChatUser? chatUser, + bool showTyping = false, + List? actions, + void Function()? onHomeTapped, + void Function()? onBackTapped}) { + return AppBar( + leadingWidth: 0, + title: Row( + children: [ + GestureDetector( + behavior: HitTestBehavior.opaque, + onTap: Feedback.wrapForTap(() { + (onBackTapped == null ? Navigator.maybePop(context) : onBackTapped()); + }, context), + child: const Icon(Icons.arrow_back_ios, color: MyColors.darkIconColor), + ), + 4.width, + if (image != null) + CircularAvatar( + url: image, + height: 40, + width: 40, + isImageBase64: true, + ), + if (image != null) 14.width, + SizedBox( + height: 40, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisAlignment: MainAxisAlignment.start, + children: [ + title.toText20(color: MyColors.darkTextColor, isBold: true).expanded, + if (showTyping) + Consumer( + builder: (BuildContext cxt, ChatProviderModel data, Widget? child) { + if (chatUser!.isTyping!) { + return ("Typing ...").toText10(color: MyColors.darkTextColor); + } else { + return const SizedBox(); + } + }, + ), + ], + ).expanded, + ) + ], + ), + centerTitle: false, + elevation: 0, + backgroundColor: Colors.white, + actions: [ + if (showHomeButton) + IconButton( + onPressed: () { + onHomeTapped == null ? Navigator.popUntil(context, ModalRoute.withName(AppRoutes.dashboard)) : onHomeTapped(); + }, + icon: const Icon(Icons.home, color: MyColors.darkIconColor), + ), + ...actions ?? [] + ], + ); +} From 668efb8412e9c1cc880c8da8c6aab51b3145bf8b Mon Sep 17 00:00:00 2001 From: "Aamir.Muhammad" Date: Mon, 12 Dec 2022 15:00:02 +0300 Subject: [PATCH 04/42] Chat Fixes & Counter Updated on Signal R --- lib/ui/chat/chat_detailed_screen.dart | 270 +++++++++++++------------- 1 file changed, 136 insertions(+), 134 deletions(-) diff --git a/lib/ui/chat/chat_detailed_screen.dart b/lib/ui/chat/chat_detailed_screen.dart index 9454e75..619e850 100644 --- a/lib/ui/chat/chat_detailed_screen.dart +++ b/lib/ui/chat/chat_detailed_screen.dart @@ -95,145 +95,147 @@ class _ChatDetailScreenState extends State { 21.width, ], ), - body: Consumer( - builder: (BuildContext context, ChatProviderModel m, Widget? child) { - return (m.isLoading - ? ChatHomeShimmer( - isDetailedScreen: true, - ) - : Column( - children: [ - SmartRefresher( - enablePullDown: false, - enablePullUp: true, - onLoading: () { - getMoreChat(); - }, - header: const MaterialClassicHeader( - color: MyColors.gradiantEndColor, - ), - controller: _rc, - reverse: true, - child: ListView.separated( - controller: m.scrollController, - shrinkWrap: true, - physics: const BouncingScrollPhysics(), - reverse: true, - itemCount: m.userChatHistory.length, - padding: const EdgeInsets.all(21), - separatorBuilder: (cxt, index) => 8.height, - itemBuilder: (BuildContext context, int i) { - return SwipeTo( - iconColor: MyColors.lightGreenColor, - child: ChatBubble( - dateTime: m.dateFormte(m.userChatHistory[i].createdDate!), - cItem: m.userChatHistory[i], - ), - onRightSwipe: () { - m.chatReply( - m.userChatHistory[i], - ); - }, - ).onPress(() async { - if (m.userChatHistory[i].fileTypeResponse != null) { - m.getChatMedia( - fileTypeName: m.userChatHistory[i].fileTypeResponse!.fileTypeName ?? "", - fileTypeID: m.userChatHistory[i].fileTypeResponse!.fileTypeId!, - fileName: m.userChatHistory[i].contant!); - } - }); + body: SafeArea( + child: Consumer( + builder: (BuildContext context, ChatProviderModel m, Widget? child) { + return (m.isLoading + ? ChatHomeShimmer( + isDetailedScreen: true, + ) + : Column( + children: [ + SmartRefresher( + enablePullDown: false, + enablePullUp: true, + onLoading: () { + getMoreChat(); }, - ), - ).expanded, - if (m.isMsgReply) - SizedBox( - height: 82, - child: Row( - children: [ - Container(height: 82, color: MyColors.textMixColor, width: 6), - Container( - color: MyColors.darkTextColor.withOpacity(0.10), - padding: const EdgeInsets.only(top: 11, left: 14, bottom: 14, right: 21), - child: Row( - children: [ - Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - (AppState().chatDetails!.response!.userName == m.repliedMsg.first.currentUserName.toString() - ? "You" - : m.repliedMsg.first.currentUserName.toString().replaceAll(".", " ")) - .toText14(color: MyColors.lightGreenColor), - (m.repliedMsg.isNotEmpty ? m.repliedMsg.first.contant! : "").toText12(color: MyColors.grey71Color, maxLine: 2) - ], - ).expanded, - 12.width, - if (m.isMsgReply && m.repliedMsg.isNotEmpty) showReplyImage(m.repliedMsg, m), - 12.width, - const Icon(Icons.cancel, size: 23, color: MyColors.grey7BColor).onPress(m.closeMe), - ], - ), - ).expanded, - ], + header: const MaterialClassicHeader( + color: MyColors.gradiantEndColor, ), - ), - if (m.isFileSelected && m.sFileType == ".png" || m.sFileType == ".jpeg" || m.sFileType == ".jpg") - SizedBox(height: 200, width: double.infinity, child: Image.file(m.selectedFile, fit: BoxFit.cover)).paddingOnly(left: 21, right: 21, top: 21), - const Divider( - height: 1, - color: MyColors.lightGreyEFColor, - ), - TextField( - controller: m.message, - decoration: InputDecoration( - hintText: m.isFileSelected ? m.selectedFile.path.split("/").last : LocaleKeys.typeheretoreply.tr(), - hintStyle: TextStyle(color: m.isFileSelected ? MyColors.darkTextColor : MyColors.grey98Color, fontSize: 14), - border: InputBorder.none, - focusedBorder: InputBorder.none, - enabledBorder: InputBorder.none, - errorBorder: InputBorder.none, - disabledBorder: InputBorder.none, - filled: true, - fillColor: MyColors.white, - contentPadding: const EdgeInsets.only( - left: 21, - top: 20, - bottom: 20, + controller: _rc, + reverse: true, + child: ListView.separated( + controller: m.scrollController, + shrinkWrap: true, + physics: const BouncingScrollPhysics(), + reverse: true, + itemCount: m.userChatHistory.length, + padding: const EdgeInsets.all(21), + separatorBuilder: (cxt, index) => 8.height, + itemBuilder: (BuildContext context, int i) { + return SwipeTo( + iconColor: MyColors.lightGreenColor, + child: ChatBubble( + dateTime: m.dateFormte(m.userChatHistory[i].createdDate!), + cItem: m.userChatHistory[i], + ), + onRightSwipe: () { + m.chatReply( + m.userChatHistory[i], + ); + }, + ).onPress(() async { + if (m.userChatHistory[i].fileTypeResponse != null) { + m.getChatMedia( + fileTypeName: m.userChatHistory[i].fileTypeResponse!.fileTypeName ?? "", + fileTypeID: m.userChatHistory[i].fileTypeResponse!.fileTypeId!, + fileName: m.userChatHistory[i].contant!); + } + }); + }, ), - prefixIconConstraints: const BoxConstraints(), - prefixIcon: m.sFileType.isNotEmpty - ? SvgPicture.asset(m.getType(m.sFileType), height: 30, width: 22, alignment: Alignment.center, fit: BoxFit.cover).paddingOnly(left: 21, right: 15) - : null, - suffixIcon: SizedBox( - width: 100, + ).expanded, + if (m.isMsgReply) + SizedBox( + height: 82, child: Row( - mainAxisAlignment: MainAxisAlignment.end, - crossAxisAlignment: CrossAxisAlignment.center, // added line children: [ - if (m.sFileType.isNotEmpty) - Row( - children: [ - const Icon(Icons.cancel, size: 15, color: MyColors.redA3Color).paddingOnly(right: 5), - ("Clear").toText11(color: MyColors.redA3Color, isUnderLine: true).paddingOnly(left: 0), + Container(height: 82, color: MyColors.textMixColor, width: 6), + Container( + color: MyColors.darkTextColor.withOpacity(0.10), + padding: const EdgeInsets.only(top: 11, left: 14, bottom: 14, right: 21), + child: Row( + children: [ + Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + (AppState().chatDetails!.response!.userName == m.repliedMsg.first.currentUserName.toString() + ? "You" + : m.repliedMsg.first.currentUserName.toString().replaceAll(".", " ")) + .toText14(color: MyColors.lightGreenColor), + (m.repliedMsg.isNotEmpty ? m.repliedMsg.first.contant! : "").toText12(color: MyColors.grey71Color, maxLine: 2) + ], + ).expanded, + 12.width, + if (m.isMsgReply && m.repliedMsg.isNotEmpty) showReplyImage(m.repliedMsg, m), + 12.width, + const Icon(Icons.cancel, size: 23, color: MyColors.grey7BColor).onPress(m.closeMe), ], - ).onPress(() => m.removeAttachment()).paddingOnly(right: 25), - if (m.sFileType.isEmpty) - RotationTransition( - turns: const AlwaysStoppedAnimation(45 / 360), - child: const Icon(Icons.attach_file_rounded, size: 26, color: MyColors.grey3AColor).onPress( - () => m.selectImageToUpload(context), - ), - ).paddingOnly(right: 25), - SvgPicture.asset("assets/icons/chat/chat_send_icon.svg", height: 26, width: 26).onPress( - () => m.sendChatMessage(params!.chatUser!.id!, params!.chatUser!.userName!, context), - ), + ), + ).expanded, ], ), - ).paddingOnly(right: 21), + ), + if (m.isFileSelected && m.sFileType == ".png" || m.sFileType == ".jpeg" || m.sFileType == ".jpg") + SizedBox(height: 200, width: double.infinity, child: Image.file(m.selectedFile, fit: BoxFit.cover)).paddingOnly(left: 21, right: 21, top: 21), + const Divider( + height: 1, + color: MyColors.lightGreyEFColor, + ), + TextField( + controller: m.message, + decoration: InputDecoration( + hintText: m.isFileSelected ? m.selectedFile.path.split("/").last : LocaleKeys.typeheretoreply.tr(), + hintStyle: TextStyle(color: m.isFileSelected ? MyColors.darkTextColor : MyColors.grey98Color, fontSize: 14), + border: InputBorder.none, + focusedBorder: InputBorder.none, + enabledBorder: InputBorder.none, + errorBorder: InputBorder.none, + disabledBorder: InputBorder.none, + filled: true, + fillColor: MyColors.white, + contentPadding: const EdgeInsets.only( + left: 21, + top: 20, + bottom: 20, + ), + prefixIconConstraints: const BoxConstraints(), + prefixIcon: m.sFileType.isNotEmpty + ? SvgPicture.asset(m.getType(m.sFileType), height: 30, width: 22, alignment: Alignment.center, fit: BoxFit.cover).paddingOnly(left: 21, right: 15) + : null, + suffixIcon: SizedBox( + width: 100, + child: Row( + mainAxisAlignment: MainAxisAlignment.end, + crossAxisAlignment: CrossAxisAlignment.center, // added line + children: [ + if (m.sFileType.isNotEmpty) + Row( + children: [ + const Icon(Icons.cancel, size: 15, color: MyColors.redA3Color).paddingOnly(right: 5), + ("Clear").toText11(color: MyColors.redA3Color, isUnderLine: true).paddingOnly(left: 0), + ], + ).onPress(() => m.removeAttachment()).paddingOnly(right: 25), + if (m.sFileType.isEmpty) + RotationTransition( + turns: const AlwaysStoppedAnimation(45 / 360), + child: const Icon(Icons.attach_file_rounded, size: 26, color: MyColors.grey3AColor).onPress( + () => m.selectImageToUpload(context), + ), + ).paddingOnly(right: 25), + SvgPicture.asset("assets/icons/chat/chat_send_icon.svg", height: 26, width: 26).onPress( + () => m.sendChatMessage(params!.chatUser!.id!, params!.chatUser!.userName!, context), + ), + ], + ), + ).paddingOnly(right: 21), + ), ), - ), - ], - )); - }, + ], + )); + }, + ), ), ); } @@ -248,14 +250,14 @@ class _ChatDetailScreenState extends State { border: Border.all(color: MyColors.darkGrey3BColor, width: 1), borderRadius: BorderRadius.circular(10.0), image: DecorationImage(image: MemoryImage(data.first.image!), fit: BoxFit.cover)), ); } else { - return data.first.fileTypeResponse != null + return data.first.fileTypeResponse != null && data.first.fileTypeResponse!.fileTypeName != null ? Container( width: 43, height: 43, - constraints: BoxConstraints(), + constraints: const BoxConstraints(), decoration: BoxDecoration(border: Border.all(color: MyColors.darkGrey3BColor, width: 1), borderRadius: BorderRadius.circular(10.0), color: Colors.white), - child: SvgPicture.asset(m.getType(data.first.fileTypeResponse!.fileTypeName), alignment: Alignment.center, fit: BoxFit.cover).paddingOnly(left: 5, right: 5, top: 5, bottom: 5)) - : SizedBox(); + child: SvgPicture.asset(m.getType(data.first.fileTypeResponse!.fileTypeName ?? ""), alignment: Alignment.center, fit: BoxFit.cover).paddingOnly(left: 5, right: 5, top: 5, bottom: 5)) + : const SizedBox(); } } From ae559df29f07b036756db0d2953a715ba76223ed Mon Sep 17 00:00:00 2001 From: "Aamir.Muhammad" Date: Mon, 12 Dec 2022 15:56:52 +0300 Subject: [PATCH 05/42] Chat Fixes & Counter Updated on Signal R --- lib/provider/chat_provider_model.dart | 7 +++++-- lib/ui/chat/chat_detailed_screen.dart | 6 ++---- lib/ui/chat/chat_home_screen.dart | 10 +++++++++- lib/widgets/chat_app_bar_widge.dart | 10 ++++++++-- pubspec.yaml | 1 + 5 files changed, 25 insertions(+), 9 deletions(-) diff --git a/lib/provider/chat_provider_model.dart b/lib/provider/chat_provider_model.dart index 4263569..d3639c9 100644 --- a/lib/provider/chat_provider_model.dart +++ b/lib/provider/chat_provider_model.dart @@ -405,7 +405,7 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { if (user.id == parameters![1] && parameters[0] == true) { user.isTyping = parameters[0] as bool?; Future.delayed( - const Duration(seconds: 1), + const Duration(seconds: 2), () { user.isTyping = false; notifyListeners(); @@ -839,12 +839,15 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { } } - Future getChatMedia({required String fileName, required String fileTypeName, required int fileTypeID}) async { + Future getChatMedia(BuildContext context, {required String fileName, required String fileTypeName, required int fileTypeID}) async { + Utils.showLoading(context); if (fileTypeID == 1 || fileTypeID == 5 || fileTypeID == 7 || fileTypeID == 6 || fileTypeID == 8 || fileTypeID == 2) { Uint8List encodedString = await ChatApiClient().downloadURL(fileName: fileName, fileTypeDescription: getFileTypeDescription(fileTypeName)); try { String path = await downChatMedia(encodedString, fileTypeName ?? ""); + Utils.hideLoading(context); OpenFile.open(path); + } catch (e) { Utils.showToast("Cannot open file."); } diff --git a/lib/ui/chat/chat_detailed_screen.dart b/lib/ui/chat/chat_detailed_screen.dart index 619e850..15b2156 100644 --- a/lib/ui/chat/chat_detailed_screen.dart +++ b/lib/ui/chat/chat_detailed_screen.dart @@ -137,10 +137,8 @@ class _ChatDetailScreenState extends State { }, ).onPress(() async { if (m.userChatHistory[i].fileTypeResponse != null) { - m.getChatMedia( - fileTypeName: m.userChatHistory[i].fileTypeResponse!.fileTypeName ?? "", - fileTypeID: m.userChatHistory[i].fileTypeResponse!.fileTypeId!, - fileName: m.userChatHistory[i].contant!); + m.getChatMedia(context, + fileTypeName: m.userChatHistory[i].fileTypeResponse!.fileTypeName ?? "", fileTypeID: m.userChatHistory[i].fileTypeId!, fileName: m.userChatHistory[i].contant!); } }); }, diff --git a/lib/ui/chat/chat_home_screen.dart b/lib/ui/chat/chat_home_screen.dart index fe4291f..a9814ee 100644 --- a/lib/ui/chat/chat_home_screen.dart +++ b/lib/ui/chat/chat_home_screen.dart @@ -1,4 +1,5 @@ import 'dart:convert'; +import 'package:animated_text_kit/animated_text_kit.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; @@ -137,7 +138,14 @@ class _ChatHomeScreenState extends State { crossAxisAlignment: CrossAxisAlignment.start, children: [ (m.searchedChats![index].userName!.replaceFirst(".", " ").capitalizeFirstofEach ?? "").toText14(color: MyColors.darkTextColor).paddingOnly(left: 11, top: 13), - (m.searchedChats![index].isTyping! ? "Typing ..." : "").toText10(color: MyColors.darkTextColor).paddingOnly(left: 11, top: 0), + m.searchedChats![index].isTyping! + ? AnimatedTextKit( + animatedTexts: [ + ScaleAnimatedText('Typing...', textStyle: const TextStyle(color: MyColors.textMixColor, fontSize: 10, letterSpacing: -0.4, fontStyle: FontStyle.normal)), + ], + ).paddingOnly(left: 11) + : const SizedBox() + //(m.searchedChats![index].isTyping! ? "Typing ..." : "").toText10(color: MyColors.textMixColor).paddingOnly(left: 11, top: 0), ], ).expanded, SizedBox( diff --git a/lib/widgets/chat_app_bar_widge.dart b/lib/widgets/chat_app_bar_widge.dart index 3a9dee4..0feac6c 100644 --- a/lib/widgets/chat_app_bar_widge.dart +++ b/lib/widgets/chat_app_bar_widge.dart @@ -1,3 +1,4 @@ +import 'package:animated_text_kit/animated_text_kit.dart'; import 'package:flutter/material.dart'; import 'package:flutter_svg/flutter_svg.dart'; import 'package:mohem_flutter_app/classes/colors.dart'; @@ -50,14 +51,19 @@ AppBar ChatAppBarWidget(BuildContext context, Consumer( builder: (BuildContext cxt, ChatProviderModel data, Widget? child) { if (chatUser!.isTyping!) { - return ("Typing ...").toText10(color: MyColors.darkTextColor); + // return ("Typing ...").toText10(color: MyColors.textMixColor); + return AnimatedTextKit( + animatedTexts: [ + ScaleAnimatedText('Typing...', textStyle: const TextStyle(color: MyColors.textMixColor, fontSize: 10, letterSpacing: -0.4, fontStyle: FontStyle.normal)), + ], + ); } else { return const SizedBox(); } }, ), ], - ).expanded, + ), ) ], ), diff --git a/pubspec.yaml b/pubspec.yaml index 0d5cda5..2e3c4c2 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -92,6 +92,7 @@ dependencies: swipe_to: ^1.0.2 flutter_webrtc: ^0.9.16 camera: ^0.10.0+4 + animated_text_kit: ^4.2.2 #Encryption flutter_des: ^2.1.0 From 43fb34c218c7455d725193e24abe300efd4979b9 Mon Sep 17 00:00:00 2001 From: haroon amjad Date: Mon, 12 Dec 2022 16:15:50 +0300 Subject: [PATCH 06/42] fixes --- lib/classes/utils.dart | 4 ++-- lib/models/member_information_list_model.dart | 2 +- lib/ui/profile/contact_details.dart | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/lib/classes/utils.dart b/lib/classes/utils.dart index 050ae4d..1336f3f 100644 --- a/lib/classes/utils.dart +++ b/lib/classes/utils.dart @@ -121,8 +121,8 @@ class Utils { ), ); } else { - // showToast(errorMessage); - confirmDialog(cxt, errorMessage); + showToast(errorMessage); + // confirmDialog(cxt, errorMessage); } } } diff --git a/lib/models/member_information_list_model.dart b/lib/models/member_information_list_model.dart index 4225905..4871855 100644 --- a/lib/models/member_information_list_model.dart +++ b/lib/models/member_information_list_model.dart @@ -48,7 +48,7 @@ class MemberInformationListModel { String? nATIONALITYCODE; String? nATIONALITYMEANING; String? nATIONALIDENTIFIER; - String? nORMALHOURS; + dynamic? nORMALHOURS; int? nOOFROWS; int? oRGANIZATIONID; String? oRGANIZATIONNAME; diff --git a/lib/ui/profile/contact_details.dart b/lib/ui/profile/contact_details.dart index 4d28a81..749978e 100644 --- a/lib/ui/profile/contact_details.dart +++ b/lib/ui/profile/contact_details.dart @@ -160,7 +160,7 @@ class _ContactDetailsState extends State { right: 1, child: const Icon(Icons.add_location_alt_outlined, size: 20).onPress(continueDynamicForms), ), - Utils.getNoDataWidget(context).expanded, + Utils.getNoDataWidget(context), ], ).objectContainerView() ], From ef347f1078041c406a54a61d60a4d888eebd8259 Mon Sep 17 00:00:00 2001 From: "Aamir.Muhammad" Date: Mon, 12 Dec 2022 16:53:21 +0300 Subject: [PATCH 07/42] Sort Fix --- lib/provider/chat_provider_model.dart | 1 + 1 file changed, 1 insertion(+) diff --git a/lib/provider/chat_provider_model.dart b/lib/provider/chat_provider_model.dart index d3639c9..d5b81fe 100644 --- a/lib/provider/chat_provider_model.dart +++ b/lib/provider/chat_provider_model.dart @@ -125,6 +125,7 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { AppState().chatDetails!.response!.id.toString(), ), ); + sort(); notifyListeners(); if (searchedChats!.isNotEmpty) { getUserImages(); From feb5c5071caa3e636e258e41841c7d8d50a94f0e Mon Sep 17 00:00:00 2001 From: "Aamir.Muhammad" Date: Tue, 13 Dec 2022 09:54:32 +0300 Subject: [PATCH 08/42] Fav Users Images Fix --- lib/provider/chat_provider_model.dart | 22 +++++++++++----------- lib/ui/landing/dashboard_screen.dart | 3 +++ 2 files changed, 14 insertions(+), 11 deletions(-) diff --git a/lib/provider/chat_provider_model.dart b/lib/provider/chat_provider_model.dart index d5b81fe..ca07b9b 100644 --- a/lib/provider/chat_provider_model.dart +++ b/lib/provider/chat_provider_model.dart @@ -127,7 +127,7 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { ); sort(); notifyListeners(); - if (searchedChats!.isNotEmpty) { + if (searchedChats!.isNotEmpty || favUsersList.isNotEmpty) { getUserImages(); } } @@ -142,19 +142,11 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { if (isNewChat) userChatHistory = []; if (!loadMore) paginationVal = 0; isChatScreenActive = true; - // if (chatHubConnection.state != HubConnectionState.Connected) { - // getUserAutoLoginToken().whenComplete(() async { - // await buildHubConnection(); - // getSingleUserChatHistory(senderUID: senderUID, receiverUID: receiverUID, loadMore: loadMore); - // }); - // return; - // } Response response = await ChatApiClient().getSingleUserChatHistory(senderUID: senderUID, receiverUID: receiverUID, loadMore: loadMore, paginationVal: paginationVal); if (response.statusCode == 204) { if (isNewChat) { userChatHistory = []; } else if (loadMore) { - // userChatHistory = []; Utils.showToast("No More Data To Load"); } } else { @@ -765,9 +757,18 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { void getUserImages() async { List emails = []; - for (ChatUser element in searchedChats!) { + List exists = [], unique = []; + exists.addAll(searchedChats!); + exists.addAll(favUsersList!); + Map profileMap = {}; + for (ChatUser item in exists) { + profileMap[item.email!] = item; + } + unique = profileMap.values.toList(); + for (ChatUser element in unique!) { emails.add(await EmailImageEncryption().encrypt(val: element.email!)); } + List chatImages = await ChatApiClient().getUsersImages(encryptedEmails: emails); for (ChatUser user in searchedChats!) { for (ChatUserImageModel uImage in chatImages) { @@ -848,7 +849,6 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { String path = await downChatMedia(encodedString, fileTypeName ?? ""); Utils.hideLoading(context); OpenFile.open(path); - } catch (e) { Utils.showToast("Cannot open file."); } diff --git a/lib/ui/landing/dashboard_screen.dart b/lib/ui/landing/dashboard_screen.dart index 0e9053a..1800aa3 100644 --- a/lib/ui/landing/dashboard_screen.dart +++ b/lib/ui/landing/dashboard_screen.dart @@ -72,6 +72,9 @@ class _DashboardScreenState extends State { void _bHubCon() { cProvider.getUserAutoLoginToken().whenComplete(() { cProvider.buildHubConnection(); + Future.delayed(const Duration(seconds: 2), () { + cProvider.invokeChatCounter(userId: AppState().chatDetails!.response!.id!); + }); }); } From 2a39ee9ddc8f929bc9d4b1caabb7652b7e26cdb9 Mon Sep 17 00:00:00 2001 From: "Aamir.Muhammad" Date: Tue, 13 Dec 2022 10:00:27 +0300 Subject: [PATCH 09/42] Fav Users Images Fix --- lib/ui/chat/chat_home.dart | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/lib/ui/chat/chat_home.dart b/lib/ui/chat/chat_home.dart index 7d0631e..807af1a 100644 --- a/lib/ui/chat/chat_home.dart +++ b/lib/ui/chat/chat_home.dart @@ -38,23 +38,23 @@ class _ChatHomeState extends State { data.clearAll(); } - void fetchAgain() { - print("Fetch Triggered"); - if (chatHubConnection.state != HubConnectionState.Connected) { - data.getUserAutoLoginToken().whenComplete(() async { - await data.buildHubConnection(); - data.getUserRecentChats(); - }); - return; - } - if (data.searchedChats == null || data.searchedChats!.isEmpty) { - data.getUserRecentChats(); - } - } + // void fetchAgain() { + // print("Fetch Triggered"); + // if (chatHubConnection.state != HubConnectionState.Connected) { + // data.getUserAutoLoginToken().whenComplete(() async { + // await data.buildHubConnection(); + // data.getUserRecentChats(); + // }); + // return; + // } + // if (data.searchedChats == null || data.searchedChats!.isEmpty) { + // data.getUserRecentChats(); + // } + // } @override Widget build(BuildContext context) { - fetchAgain(); + // fetchAgain(); return Scaffold( backgroundColor: MyColors.white, appBar: AppBarWidget(context, title: LocaleKeys.chat.tr(), showHomeButton: true), From 45b4adc2528986a5b59c7fbdd800f2fc381aa14d Mon Sep 17 00:00:00 2001 From: "Aamir.Muhammad" Date: Tue, 13 Dec 2022 10:09:20 +0300 Subject: [PATCH 10/42] Fav Users Images Fix --- lib/provider/chat_provider_model.dart | 3 ++- lib/ui/chat/chat_bubble.dart | 3 +-- lib/ui/chat/chat_detailed_screen.dart | 3 +-- 3 files changed, 4 insertions(+), 5 deletions(-) diff --git a/lib/provider/chat_provider_model.dart b/lib/provider/chat_provider_model.dart index ca07b9b..3a4e70b 100644 --- a/lib/provider/chat_provider_model.dart +++ b/lib/provider/chat_provider_model.dart @@ -526,7 +526,7 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { await chatHubConnection.invoke("AddChatUserAsync", args: [json.decode(chatData)]); } - void sendChatMessage(int targetUserId, String targetUserName, BuildContext context) async { + void sendChatMessage(int targetUserId, int userStatus, String targetUserName, BuildContext context) async { dynamic contain = searchedChats!.where((ChatUser element) => element.id == targetUserId); if (contain.isEmpty) { searchedChats!.add( @@ -539,6 +539,7 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { isImageLoaded: true, isTyping: false, isFav: false, + userStatus: userStatus, userLocalDownlaodedImage: null, ), ); diff --git a/lib/ui/chat/chat_bubble.dart b/lib/ui/chat/chat_bubble.dart index 288a13f..c79c66b 100644 --- a/lib/ui/chat/chat_bubble.dart +++ b/lib/ui/chat/chat_bubble.dart @@ -54,11 +54,10 @@ class ChatBubble extends StatelessWidget { screenOffset = Offset(windowSize.width / 2, windowSize.height / 2); makeAssign(); data = Provider.of(context, listen: false); - return isCurrentUser ? currentUser(context) : receiptUser(context); } - Widget currentUser(context) { + Widget currentUser(BuildContext context) { return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ diff --git a/lib/ui/chat/chat_detailed_screen.dart b/lib/ui/chat/chat_detailed_screen.dart index 15b2156..05e674a 100644 --- a/lib/ui/chat/chat_detailed_screen.dart +++ b/lib/ui/chat/chat_detailed_screen.dart @@ -223,7 +223,7 @@ class _ChatDetailScreenState extends State { ), ).paddingOnly(right: 25), SvgPicture.asset("assets/icons/chat/chat_send_icon.svg", height: 26, width: 26).onPress( - () => m.sendChatMessage(params!.chatUser!.id!, params!.chatUser!.userName!, context), + () => m.sendChatMessage(params!.chatUser!.id!, params!.chatUser!.userStatus ?? 0, params!.chatUser!.userName!, context), ), ], ), @@ -239,7 +239,6 @@ class _ChatDetailScreenState extends State { } Widget showReplyImage(List data, ChatProviderModel m) { - logger.d(jsonEncode(data)); if (data.first.isImageLoaded! && data.first.image != null) { return Container( width: 43, From 4a513c08d905ba8e82613ce4f0f889a9953e088f Mon Sep 17 00:00:00 2001 From: haroon amjad Date: Tue, 13 Dec 2022 10:46:30 +0300 Subject: [PATCH 11/42] fixes --- lib/classes/consts.dart | 1 + lib/classes/utils.dart | 2 +- lib/main.dart | 5 ++++ .../get_time_card_summary_list_model.dart | 24 +++++++++---------- lib/ui/landing/dashboard_screen.dart | 2 +- lib/ui/work_list/worklist_detail_screen.dart | 22 ++++++++++++++++- 6 files changed, 41 insertions(+), 15 deletions(-) diff --git a/lib/classes/consts.dart b/lib/classes/consts.dart index e9b902a..3d58efd 100644 --- a/lib/classes/consts.dart +++ b/lib/classes/consts.dart @@ -3,6 +3,7 @@ import 'package:mohem_flutter_app/ui/marathon/widgets/question_card.dart'; class ApiConsts { //static String baseUrl = "http://10.200.204.20:2801/"; // Local server // static String baseUrl = "https://uat.hmgwebservices.com"; // UAT server + // static String baseUrl = "https://erptstapp.srca.org.sa"; // SRCA server static String baseUrl = "https://hmgwebservices.com"; // Live server static String baseUrlServices = baseUrl + "/Services/"; // server // static String baseUrlServices = "https://api.cssynapses.com/tangheem/"; // Live server diff --git a/lib/classes/utils.dart b/lib/classes/utils.dart index 1336f3f..3be8356 100644 --- a/lib/classes/utils.dart +++ b/lib/classes/utils.dart @@ -37,7 +37,7 @@ class Utils { timeInSecForIosWeb: 1, backgroundColor: Colors.black54, textColor: Colors.white, - fontSize: 16.0); + fontSize: 13.0); } static dynamic getNotNullValue(List list, int index) { diff --git a/lib/main.dart b/lib/main.dart index aa9f933..fdc4ad6 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -2,6 +2,7 @@ import 'dart:io'; import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; import 'package:logger/logger.dart'; import 'package:mohem_flutter_app/app_state/app_state.dart'; import 'package:mohem_flutter_app/classes/consts.dart'; @@ -37,6 +38,10 @@ bool isTablet = false; Future main() async { WidgetsFlutterBinding.ensureInitialized(); + SystemChrome.setPreferredOrientations([ + DeviceOrientation.portraitUp, + DeviceOrientation.portraitDown, + ]); await EasyLocalization.ensureInitialized(); AppState().setPostParamsInitConfig(); HttpOverrides.global = MyHttpOverrides(); diff --git a/lib/models/get_time_card_summary_list_model.dart b/lib/models/get_time_card_summary_list_model.dart index 85a2a8e..becc1d2 100644 --- a/lib/models/get_time_card_summary_list_model.dart +++ b/lib/models/get_time_card_summary_list_model.dart @@ -1,41 +1,41 @@ class GetTimeCardSummaryList { - int? aBSENTDAYS; + num? aBSENTDAYS; dynamic? aCTUALHRS; dynamic? aPPROVEDTIMEBACKHRS; - int? aSSIGNMENTID; - int? aTTENDEDDAYS; - int? bUSINESSTRIP; + num? aSSIGNMENTID; + num? aTTENDEDDAYS; + num? bUSINESSTRIP; dynamic? cOMPOFFHHRS; dynamic? cOMPOFFNHRS; dynamic? cOMPOFFWHRS; dynamic? dESIREDSCHEDULEDHRS; dynamic? eARLYOUTHRS; dynamic? eXCESSHRS; - int? hALFDAYLEAVE; + num? hALFDAYLEAVE; dynamic? lATEINHRS; dynamic? lEAVESHOLIDAYSHRS; dynamic? nONSCHEDULEDAYS; dynamic? nOTANALYZEDDAYS; - int? oFFDAYS; + num? oFFDAYS; dynamic? oNCALLHRS; dynamic? pAIDLEAVE; - int? pERIODDAYS; + num? pERIODDAYS; dynamic? pLANNEDOTHRS; - int? pUBLICHOLIDAY; + num? pUBLICHOLIDAY; dynamic? sCHEDULEDHRS; dynamic? sCHEDULEDONCALLHRS; dynamic? sCHEDULEDPLANNEDOTHRS; - int? sCHEDULEDAYS; + num? sCHEDULEDAYS; dynamic? sHORTAGEHRS; dynamic? sHORTAGESCHEDULEHRS; - int? sICKLEAVE; + num? sICKLEAVE; dynamic? tIMEBACKHRS; dynamic? tIMEBACKBALANCE; - int? uNAUTHORIZEDLEAVE; + num? uNAUTHORIZEDLEAVE; dynamic? uNCOVERDSHORTAGEHRS; - int? uNPAIDLEAVE; + num? uNPAIDLEAVE; GetTimeCardSummaryList( {this.aBSENTDAYS, diff --git a/lib/ui/landing/dashboard_screen.dart b/lib/ui/landing/dashboard_screen.dart index 0e9053a..15fc795 100644 --- a/lib/ui/landing/dashboard_screen.dart +++ b/lib/ui/landing/dashboard_screen.dart @@ -196,7 +196,7 @@ class _DashboardScreenState extends State { Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - LocaleKeys.goodMorning.tr().toText14(color: MyColors.grey77Color), + LocaleKeys.welcomeBack.tr().toText14(color: MyColors.grey77Color), (AppState().memberInformationList!.eMPLOYEENAME ?? "").toText24(isBold: true), 16.height, Row( diff --git a/lib/ui/work_list/worklist_detail_screen.dart b/lib/ui/work_list/worklist_detail_screen.dart index 75ee88f..b5129a5 100644 --- a/lib/ui/work_list/worklist_detail_screen.dart +++ b/lib/ui/work_list/worklist_detail_screen.dart @@ -106,6 +106,19 @@ class _WorkListDetailScreenState extends State { void getData() async { // try { // Utils.showLoading(context); + + getEitCollectionNotificationBodyList!.clear(); + getAbsenceCollectionNotificationBodyList!.clear(); + getPrNotificationBody = null; + getStampMsNotifications.clear(); + getStampNsNotifications.clear(); + getPoNotificationBody?.pOHeader!.clear(); + getItemCreationNtfBody?.itemCreationHeader!.clear(); + getPhonesNotificationBodyList!.clear(); + getBasicDetNtfBodyList!.clear(); + getAbsenceCollectionNotificationBodyList!.clear(); + getContactNotificationBodyList = null; + if (workListData!.iTEMTYPE == "HRSSA" || workListData!.iTEMTYPE == "STAMP") { getUserInformation(); } @@ -688,7 +701,7 @@ class _WorkListDetailScreenState extends State { GenericResponseModel model = await WorkListApiClient().postNotificationActions(payload); Utils.hideLoading(context); Utils.showToast(LocaleKeys.yourChangeHasBeenSavedSuccessfully.tr()); - animationIndex=animationIndex+1; + animationIndex = animationIndex + 1; AppState().workList!.removeAt(AppState().workListIndex!); if (AppState().workList!.isEmpty) { Navigator.pop(context, "delegate_reload"); @@ -725,6 +738,7 @@ class _WorkListDetailScreenState extends State { try { if (apiCallCount == 0) Utils.showLoading(context); apiCallCount++; + getEitCollectionNotificationBodyList!.clear(); getEitCollectionNotificationBodyList = await WorkListApiClient().GetEitNotificationBody(workListData!.nOTIFICATIONID); apiCallCount--; if (apiCallCount == 0) { @@ -742,6 +756,7 @@ class _WorkListDetailScreenState extends State { try { if (apiCallCount == 0) Utils.showLoading(context); apiCallCount++; + memberInformationListModel = null; memberInformationListModel = await WorkListApiClient().getUserInformation(-999, workListData!.sELECTEDEMPLOYEENUMBER!); apiCallCount--; if (apiCallCount == 0) { @@ -759,6 +774,7 @@ class _WorkListDetailScreenState extends State { try { if (apiCallCount == 0) Utils.showLoading(context); apiCallCount++; + getPhonesNotificationBodyList!.clear(); getPhonesNotificationBodyList = await WorkListApiClient().getPhonesNotificationBodyList(workListData!.nOTIFICATIONID); apiCallCount--; if (apiCallCount == 0) { @@ -776,6 +792,7 @@ class _WorkListDetailScreenState extends State { try { if (apiCallCount == 0) Utils.showLoading(context); apiCallCount++; + getBasicDetNtfBodyList!.clear(); getBasicDetNtfBodyList = await WorkListApiClient().getBasicDetNtfBodyList(workListData!.nOTIFICATIONID); apiCallCount--; if (apiCallCount == 0) { @@ -793,6 +810,7 @@ class _WorkListDetailScreenState extends State { try { if (apiCallCount == 0) Utils.showLoading(context); apiCallCount++; + getAbsenceCollectionNotificationBodyList!.clear(); getAbsenceCollectionNotificationBodyList = await WorkListApiClient().getAbsenceNotificationBody(workListData!.nOTIFICATIONID); apiCallCount--; if (apiCallCount == 0) { @@ -916,6 +934,7 @@ class _WorkListDetailScreenState extends State { try { if (apiCallCount == 0) Utils.showLoading(context); apiCallCount++; + getNotificationRespondAttributes.clear(); getNotificationRespondAttributes = await WorkListApiClient().notificationGetRespondAttributes(workListData!.nOTIFICATIONID!); if (getNotificationRespondAttributes.isNotEmpty) { notificationNoteInput = getNotificationRespondAttributes.first; @@ -936,6 +955,7 @@ class _WorkListDetailScreenState extends State { try { if (apiCallCount == 0) Utils.showLoading(context); apiCallCount++; + notificationButtonsList.clear(); notificationButtonsList = await WorkListApiClient().getNotificationButtons(workListData!.nOTIFICATIONID!); if (notificationButtonsList.isNotEmpty) { isCloseAvailable = notificationButtonsList.any((element) => element.bUTTONACTION == "CLOSE"); From 67c4970897bb1d0493392ee32672b07d2482a62b Mon Sep 17 00:00:00 2001 From: haroon amjad Date: Tue, 13 Dec 2022 11:11:40 +0300 Subject: [PATCH 12/42] fixes --- lib/ui/chat/chat_home.dart | 27 +++++++++++++-------------- lib/ui/landing/dashboard_screen.dart | 2 +- 2 files changed, 14 insertions(+), 15 deletions(-) diff --git a/lib/ui/chat/chat_home.dart b/lib/ui/chat/chat_home.dart index 807af1a..330242a 100644 --- a/lib/ui/chat/chat_home.dart +++ b/lib/ui/chat/chat_home.dart @@ -38,23 +38,22 @@ class _ChatHomeState extends State { data.clearAll(); } - // void fetchAgain() { - // print("Fetch Triggered"); - // if (chatHubConnection.state != HubConnectionState.Connected) { - // data.getUserAutoLoginToken().whenComplete(() async { - // await data.buildHubConnection(); - // data.getUserRecentChats(); - // }); - // return; - // } - // if (data.searchedChats == null || data.searchedChats!.isEmpty) { - // data.getUserRecentChats(); - // } - // } + void fetchAgain() { + if (chatHubConnection.state != HubConnectionState.Connected) { + data.getUserAutoLoginToken().whenComplete(() async { + await data.buildHubConnection(); + data.getUserRecentChats(); + }); + return; + } + if (data.searchedChats == null || data.searchedChats!.isEmpty) { + data.getUserRecentChats(); + } + } @override Widget build(BuildContext context) { - // fetchAgain(); + fetchAgain(); return Scaffold( backgroundColor: MyColors.white, appBar: AppBarWidget(context, title: LocaleKeys.chat.tr(), showHomeButton: true), diff --git a/lib/ui/landing/dashboard_screen.dart b/lib/ui/landing/dashboard_screen.dart index 2d7de09..b423ebd 100644 --- a/lib/ui/landing/dashboard_screen.dart +++ b/lib/ui/landing/dashboard_screen.dart @@ -58,7 +58,6 @@ class _DashboardScreenState extends State { data = Provider.of(context, listen: false); marathonProvider = Provider.of(context, listen: false); cProvider = Provider.of(context, listen: false); - _bHubCon(); _onRefresh(); }); } @@ -80,6 +79,7 @@ class _DashboardScreenState extends State { void _onRefresh() async { data.initProvider(); + _bHubCon(); // data.getITGNotification().then((value) { // print("--------------------detail_1-----------------"); // print(value!.result!.data!.notificationMasterId); From 86d25d3ecce835a6d71a377579d931fb3594d79c Mon Sep 17 00:00:00 2001 From: Faiz Hashmi Date: Tue, 13 Dec 2022 11:13:37 +0300 Subject: [PATCH 13/42] Added Privileged logic for Marathon --- assets/langs/ar-SA.json | 3 +- assets/langs/en-US.json | 3 +- lib/app_state/app_state.dart | 1 + lib/classes/colors.dart | 1 + lib/generated/locale_keys.g.dart | 1 + lib/ui/login/verify_login_screen.dart | 1 + lib/ui/marathon/marathon_provider.dart | 59 ++- lib/ui/marathon/marathon_screen.dart | 141 +++-- lib/ui/marathon/widgets/marathon_banner.dart | 514 ++++++++++++------- 9 files changed, 478 insertions(+), 246 deletions(-) diff --git a/assets/langs/ar-SA.json b/assets/langs/ar-SA.json index d51e724..2adb2ba 100644 --- a/assets/langs/ar-SA.json +++ b/assets/langs/ar-SA.json @@ -512,5 +512,6 @@ "youWantToLeaveMarathon": "هل أنت متأكد أنك تريد العودة؟ سوف تخرج من المسابقة.", "ourSponsor": "راعينا:", "startingIn": "يبدأ في", - "youAreOutOfContest": "أنت خارج المسابقة." + "youAreOutOfContest": "أنت خارج المسابقة.", + "winners": "الفائزين!!!" } \ No newline at end of file diff --git a/assets/langs/en-US.json b/assets/langs/en-US.json index 97e8c5c..46ede79 100644 --- a/assets/langs/en-US.json +++ b/assets/langs/en-US.json @@ -512,6 +512,7 @@ "youWantToLeaveMarathon": "Are you sure you want to go back? You will be out of the contest.", "ourSponsor": "Our Sponsor:", "startingIn": "Starting in", - "youAreOutOfContest": "You are out of the contest." + "youAreOutOfContest": "You are out of the contest.", + "winners": "WINNERS!!!" } \ No newline at end of file diff --git a/lib/app_state/app_state.dart b/lib/app_state/app_state.dart index b0620ad..5060195 100644 --- a/lib/app_state/app_state.dart +++ b/lib/app_state/app_state.dart @@ -38,6 +38,7 @@ class AppState { String? get getForgetPasswordTokenID => forgetPasswordTokenID; + //Wifi info String? _mohemmWifiSSID; diff --git a/lib/classes/colors.dart b/lib/classes/colors.dart index 4394279..5c9b30e 100644 --- a/lib/classes/colors.dart +++ b/lib/classes/colors.dart @@ -63,4 +63,5 @@ class MyColors { static const Color darkDigitColor = Color(0xff2D2F39); static const Color grey71Color = Color(0xff717171); static const Color darkGrey3BColor = Color(0xff3B3B3B); + static const Color lightGreyIconColor = Color(0xff919191); } diff --git a/lib/generated/locale_keys.g.dart b/lib/generated/locale_keys.g.dart index c862385..8960278 100644 --- a/lib/generated/locale_keys.g.dart +++ b/lib/generated/locale_keys.g.dart @@ -499,5 +499,6 @@ abstract class LocaleKeys { static const ourSponsor = 'ourSponsor'; static const startingIn = 'startingIn'; static const youAreOutOfContest = 'youAreOutOfContest'; + static const winners = 'winners'; } diff --git a/lib/ui/login/verify_login_screen.dart b/lib/ui/login/verify_login_screen.dart index ce21b63..b5eb7df 100644 --- a/lib/ui/login/verify_login_screen.dart +++ b/lib/ui/login/verify_login_screen.dart @@ -642,6 +642,7 @@ class _VerifyLoginScreenState extends State { PrivilegeListModel.saveToPrefs(genericResponseModel.privilegeList ?? []); AppState().setMohemmWifiSSID = genericResponseModel.mohemmWifiSSID; AppState().setMohemmWifiPassword = genericResponseModel.mohemmWifiPassword; + AppState().setMohemmWifiPassword = genericResponseModel.mohemmWifiPassword; Utils.saveStringFromPrefs(SharedPrefsConsts.username, AppState().getUserName!); Utils.saveStringFromPrefs(SharedPrefsConsts.password, AppState().password!); Utils.saveStringFromPrefs(SharedPrefsConsts.mohemmWifiSSID, genericResponseModel.mohemmWifiSSID!); diff --git a/lib/ui/marathon/marathon_provider.dart b/lib/ui/marathon/marathon_provider.dart index 2d778b9..175b7be 100644 --- a/lib/ui/marathon/marathon_provider.dart +++ b/lib/ui/marathon/marathon_provider.dart @@ -5,11 +5,13 @@ import 'package:flutter/cupertino.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:mohem_flutter_app/api/marathon/marathon_api_client.dart'; +import 'package:mohem_flutter_app/app_state/app_state.dart'; import 'package:mohem_flutter_app/classes/utils.dart'; import 'package:mohem_flutter_app/config/routes.dart'; import 'package:mohem_flutter_app/models/marathon/marathon_model.dart'; import 'package:mohem_flutter_app/models/marathon/question_model.dart'; import 'package:mohem_flutter_app/models/marathon/winner_model.dart'; +import 'package:mohem_flutter_app/models/privilege_list_model.dart'; import 'package:mohem_flutter_app/ui/marathon/widgets/question_card.dart'; import 'package:video_player/video_player.dart'; @@ -28,6 +30,9 @@ class MarathonProvider extends ChangeNotifier { String? selectedOptionId; int? totalQualifiers; + bool iAmWinner = false; + bool isPrivilegedWithMarathon = false; + bool _isLoading = false; bool get isLoading => _isLoading; @@ -164,7 +169,7 @@ class MarathonProvider extends ChangeNotifier { oneSec, (Timer timer) async { // This 2 is just to show the color of answer tile for 2 seconds and then update card status - if (totalCurrentQuestionTime - currentGapTime == currentQuestion.questionTime! - 2) { + if (totalCurrentQuestionTime - currentGapTime == 1) { getCorrectAnswerAndUpdateAnswerColor(); } @@ -182,7 +187,7 @@ class MarathonProvider extends ChangeNotifier { if (totalCurrentQuestionTime == 0) { updateCardData(); - if (currentQuestionNumber == marathonDetailModel.totalQuestions! - 1) { + if (currentQuestionNumber == marathonDetailModel.totalQuestions! ) { callGetQualifiersApi(); updateQuestionCardStatus(QuestionCardStatus.findingWinner); timer.cancel(); @@ -235,6 +240,19 @@ class MarathonProvider extends ChangeNotifier { Future callGetSelectedWinnersApi() async { selectedWinners = await MarathonApiClient().getSelectedWinner(marathonId: marathonDetailModel.id!); + if (selectedWinners != null) { + selectedWinners!.removeWhere((WinnerModel element) { + print("matching : ${AppState().memberInformationList!.eMPLOYEENUMBER} with ${element.employeeId}"); + if (element.employeeId == AppState().memberInformationList!.eMPLOYEENUMBER) { + iAmWinner = true; + return true; + } else { + return false; + } + }); + } + print("selectedWinners Length : ${selectedWinners!.length}"); + notifyListeners(); } @@ -361,20 +379,35 @@ class MarathonProvider extends ChangeNotifier { notifyListeners(); } + bool checkIfPrivilegedForMarathon() { + for (PrivilegeListModel element in AppState().privilegeListModel!) { + if (element.serviceName == "Marathon") { + if (element.previlege != null) { + return element.previlege!; + } + } + } + return false; + } + Future getMarathonDetailsFromApi() async { isLoading = true; notifyListeners(); - await MarathonApiClient().getMarathonToken().whenComplete(() async { - marathonDetailModel = await MarathonApiClient().getMarathonDetails(); - if (marathonDetailModel.id == null) { - isUpComingMarathon = false; - notifyListeners(); - return; - } - populateQuestionStatusesList(); - isLoading = false; - notifyListeners(); - }); + isPrivilegedWithMarathon = checkIfPrivilegedForMarathon(); + if (isPrivilegedWithMarathon) { + await MarathonApiClient().getMarathonToken().whenComplete(() async { + marathonDetailModel = await MarathonApiClient().getMarathonDetails(); + if (marathonDetailModel.id == null) { + isUpComingMarathon = false; + isLoading = false; + notifyListeners(); + return; + } + populateQuestionStatusesList(); + }); + } + isLoading = false; + notifyListeners(); } Future onJoinMarathonPressed(BuildContext context) async { diff --git a/lib/ui/marathon/marathon_screen.dart b/lib/ui/marathon/marathon_screen.dart index 2ae3f64..71ae3d6 100644 --- a/lib/ui/marathon/marathon_screen.dart +++ b/lib/ui/marathon/marathon_screen.dart @@ -43,71 +43,102 @@ class MarathonScreen extends StatelessWidget { return Image.asset(MyLottieConsts.congratsGif, height: 200); } + // SizedBox( + // height: 200, + // child: Stack( + // fit: StackFit.expand, + // children: [ + // Lottie.asset(MyLottieConsts.celebrate1Lottie, height: 200), + // // Lottie.asset(MyLottieConsts.celebrate2Lottie, height: 200), + // ], + // ), + // ), + Widget getWinnerWidget(BuildContext context, {required MarathonProvider provider}) { return Container( width: double.infinity, decoration: MyDecorations.shadowDecoration, padding: const EdgeInsets.symmetric(vertical: 20, horizontal: 20), - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - SizedBox( - height: 200, - child: Stack( - children: [ - Lottie.asset(MyLottieConsts.celebrate1Lottie, height: 200), - Lottie.asset(MyLottieConsts.celebrate2Lottie, height: 200), + child: Stack( + children: [ + Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + SizedBox( + height: 50, + child: Stack( + children: [ + Align( + alignment: Alignment.center, + child: SvgPicture.asset("assets/images/winner_ribbon.svg", height: 50), + ), + Align( + alignment: Alignment.center, + child: LocaleKeys.winners.tr().toText32(color: MyColors.white, isBold: true, isCentered: true).paddingOnly(top: 07), + ) + ], + ), + ), + 16.height, + !provider.iAmWinner + ? Column( + children: [ + (AppState().isArabic(context) ? AppState().memberInformationList!.eMPLOYEEDISPLAYNAMEAr : AppState().memberInformationList!.eMPLOYEEDISPLAYNAMEEn)!.toText22( + color: MyColors.grey3AColor, + isCentered: true, + ), + 8.height, + AppState().memberInformationList!.eMPLOYEENUMBER!.toText22(color: MyColors.grey57Color), + ], + ) + : const SizedBox(), + 36.height, + if (provider.selectedWinners != null) ...[ + ListView.separated( + shrinkWrap: true, + itemCount: provider.selectedWinners!.length, + separatorBuilder: (BuildContext context, int index) { + return const Divider(); + }, + itemBuilder: (BuildContext context, int index) { + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + (AppState().isArabic(context) ? provider.selectedWinners![index].nameEn : provider.selectedWinners![index].nameEn)!.toText16( + color: MyColors.grey3AColor, + ), + provider.selectedWinners!.first.employeeId!.toText16(color: MyColors.grey57Color), + ], + ); + }, + ), ], - ), - ), - 26.height, - SizedBox( - height: 50, - child: Stack( - children: [ - Align( - alignment: Alignment.center, - child: SvgPicture.asset("assets/images/winner_ribbon.svg", height: 50), + 60.height, + if (provider.marathonDetailModel.sponsors != null && provider.marathonDetailModel.sponsors!.isNotEmpty) ...[ + Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + "${LocaleKeys.sponsoredBy.tr()} ".toText14(color: MyColors.grey77Color), + (AppState().isArabic(context) ? provider.marathonDetailModel.sponsors!.first.nameAr ?? "" : provider.marathonDetailModel.sponsors!.first.nameEn ?? "").toText14( + color: MyColors.darkTextColor, + isBold: true, + ), + ], ), - Align( - alignment: Alignment.center, - child: LocaleKeys.winner.tr().toText32(color: MyColors.white, isBold: true, isCentered: true).paddingOnly(top: 07), + 5.height, + Image.network( + provider.marathonDetailModel.sponsors!.first.image!, + height: 40, + width: 150, + fit: BoxFit.fill, + errorBuilder: (BuildContext context, Object exception, StackTrace? stackTrace) { + return const Center(); + }, ) ], - ), + ], ), - 12.height, - if (provider.selectedWinners != null) ...[ - (AppState().isArabic(context) ? provider.selectedWinners!.first.nameEn : provider.selectedWinners!.first.nameEn)!.toText22( - color: MyColors.grey3AColor, - isCentered: true, - ), - 8.height, - provider.selectedWinners!.first.employeeId!.toText22(color: MyColors.grey57Color), - ], - 60.height, - if (provider.marathonDetailModel.sponsors != null && provider.marathonDetailModel.sponsors!.isNotEmpty) ...[ - Row( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - "${LocaleKeys.sponsoredBy.tr()} ".toText14(color: MyColors.grey77Color), - (AppState().isArabic(context) ? provider.marathonDetailModel.sponsors!.first.nameAr ?? "" : provider.marathonDetailModel.sponsors!.first.nameEn ?? "").toText14( - color: MyColors.darkTextColor, - isBold: true, - ), - ], - ), - 5.height, - Image.network( - provider.marathonDetailModel.sponsors!.first.image!, - height: 40, - width: 150, - fit: BoxFit.fill, - errorBuilder: (BuildContext context, Object exception, StackTrace? stackTrace) { - return const Center(); - }, - ) - ], + Lottie.asset(MyLottieConsts.celebrate1Lottie), ], ), ); diff --git a/lib/ui/marathon/widgets/marathon_banner.dart b/lib/ui/marathon/widgets/marathon_banner.dart index 2be08a9..0487c74 100644 --- a/lib/ui/marathon/widgets/marathon_banner.dart +++ b/lib/ui/marathon/widgets/marathon_banner.dart @@ -22,200 +22,362 @@ class MarathonBanner extends StatelessWidget { const MarathonBanner({Key? key, required this.isMarathonUpcoming}) : super(key: key); - @override - Widget build(BuildContext context) { - MarathonProvider provider = context.read(); - return provider.marathonDetailModel.startTime != null - ? Container( - decoration: MyDecorations.shadowDecoration, - height: isTablet ? MediaQuery.of(context).size.height * 0.17 : MediaQuery.of(context).size.height * 0.11, - clipBehavior: Clip.antiAlias, - child: Stack( + Widget getUnPrivilegedMarathon(BuildContext context) { + return Container( + decoration: MyDecorations.shadowDecoration, + height: isTablet ? MediaQuery.of(context).size.height * 0.17 : MediaQuery.of(context).size.height * 0.11, + clipBehavior: Clip.antiAlias, + child: Stack( + children: [ + Transform( + alignment: Alignment.center, + transform: Matrix4.rotationY( + AppState().isArabic(context) ? math.pi : 0, + ), + child: SvgPicture.asset( + "assets/images/marathon_banner_bg.svg", + fit: BoxFit.fill, + width: double.infinity, + ), + ), + AppState().isArabic(context) + ? Positioned( + right: -15, + top: -10, + child: Transform.rotate( + angle: 10, + child: Container( + width: isTablet ? 70 : 65, + height: isTablet ? 40 : 32, + color: MyColors.darkDigitColor, + ), + ), + ) + : Positioned( + left: -20, + top: -10, + child: Transform.rotate( + angle: 15, + child: Container( + width: isTablet ? 70 : 65, + height: isTablet ? 40 : 32, + color: MyColors.darkDigitColor, + ), + ), + ), + SizedBox( + width: double.infinity, + height: double.infinity, + child: Row( children: [ - Transform( - alignment: Alignment.center, - transform: Matrix4.rotationY( - AppState().isArabic(context) ? math.pi : 0, + const Expanded( + flex: 3, + child: SizedBox( + width: double.infinity, + height: double.infinity, ), - child: SvgPicture.asset( - "assets/images/marathon_banner_bg.svg", - fit: BoxFit.fill, + ), + Expanded( + flex: AppState().isArabic(context) ? 4 : 5, + child: SizedBox( width: double.infinity, + height: double.infinity, + child: Row( + mainAxisAlignment: MainAxisAlignment.start, + children: [ + Column( + mainAxisAlignment: MainAxisAlignment.center, + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + AppState().isArabic(context) ? 0.height : 5.height, + Text( + LocaleKeys.getReadyForContest.tr(), + style: TextStyle( + fontSize: isTablet ? 20 : 11, + fontStyle: FontStyle.italic, + fontWeight: FontWeight.w600, + color: MyColors.white.withOpacity(0.83), + letterSpacing: -0.4, + ), + ), + Text( + LocaleKeys.brainMarathon.tr(), + style: TextStyle( + fontStyle: FontStyle.italic, + fontSize: isTablet ? 30 : 19, + fontWeight: FontWeight.bold, + color: MyColors.white.withOpacity(0.83), + height: 32 / 22, + ), + ), + ], + ).paddingOnly( + left: AppState().isArabic(context) ? 12 : 3, + right: AppState().isArabic(context) ? 3 : 12, + ) + ], + ), ), ), - AppState().isArabic(context) - ? Positioned( - right: -15, - top: -10, - child: Transform.rotate( - angle: 10, - child: Container( - width: isTablet ? 70 : 65, - height: isTablet ? 40 : 32, - color: MyColors.darkDigitColor, - ), - ), - ) - : Positioned( - left: -20, - top: -10, - child: Transform.rotate( - angle: 15, - child: Container( - width: isTablet ? 70 : 65, - height: isTablet ? 40 : 32, - color: MyColors.darkDigitColor, - ), + ], + ), + ), + AppState().isArabic(context) + ? Align( + alignment: Alignment.topRight, + child: SizedBox( + height: isTablet ? 30 : 20, + width: isTablet ? 45 : 35, + child: Transform.rotate( + angle: math.pi / 4.5, + child: Text( + LocaleKeys.brainMarathon.tr(), + textAlign: TextAlign.center, + maxLines: 2, + style: TextStyle( + color: MyColors.white, + fontWeight: FontWeight.bold, + fontSize: isTablet ? 8 : 6, + height: 1.2, ), ), - SizedBox( - width: double.infinity, - height: double.infinity, - child: Row( - children: [ - const Expanded( - flex: 3, - child: SizedBox( - width: double.infinity, - height: double.infinity, + ), + ), + ).paddingOnly(top: 5) + : Align( + alignment: Alignment.topLeft, + child: SizedBox( + height: isTablet ? 30 : 20, + width: isTablet ? 45 : 35, + child: Transform.rotate( + angle: -math.pi / 4.5, + child: Text( + LocaleKeys.brainMarathon.tr(), + textAlign: TextAlign.center, + maxLines: 2, + style: TextStyle( + color: MyColors.kWhiteColor, + fontWeight: FontWeight.bold, + fontSize: isTablet ? 8 : 6, + height: 1.2, ), ), - Expanded( - flex: AppState().isArabic(context) ? 4 : 5, - child: SizedBox( - width: double.infinity, - height: double.infinity, - child: Row( - mainAxisAlignment: MainAxisAlignment.start, - children: [ - Column( - mainAxisAlignment: MainAxisAlignment.center, - crossAxisAlignment: CrossAxisAlignment.start, - mainAxisSize: MainAxisSize.min, + ), + ), + ).paddingOnly(top: 5), + Container( + height: double.infinity, + width: double.infinity, + color: Colors.black.withOpacity(0.6), + child: const Icon( + Icons.lock_rounded, + color: MyColors.lightGreyIconColor, + ), + ), + ], + ), + ); + } + + @override + Widget build(BuildContext context) { + MarathonProvider provider = context.read(); + + return !provider.isPrivilegedWithMarathon + ? getUnPrivilegedMarathon(context) + : provider.marathonDetailModel.startTime != null + ? Container( + decoration: MyDecorations.shadowDecoration, + height: isTablet ? MediaQuery.of(context).size.height * 0.17 : MediaQuery.of(context).size.height * 0.11, + clipBehavior: Clip.antiAlias, + child: Stack( + children: [ + Transform( + alignment: Alignment.center, + transform: Matrix4.rotationY( + AppState().isArabic(context) ? math.pi : 0, + ), + child: SvgPicture.asset( + "assets/images/marathon_banner_bg.svg", + fit: BoxFit.fill, + width: double.infinity, + ), + ), + AppState().isArabic(context) + ? Positioned( + right: -15, + top: -10, + child: Transform.rotate( + angle: 10, + child: Container( + width: isTablet ? 70 : 65, + height: isTablet ? 40 : 32, + color: MyColors.darkDigitColor, + ), + ), + ) + : Positioned( + left: -20, + top: -10, + child: Transform.rotate( + angle: 15, + child: Container( + width: isTablet ? 70 : 65, + height: isTablet ? 40 : 32, + color: MyColors.darkDigitColor, + ), + ), + ), + SizedBox( + width: double.infinity, + height: double.infinity, + child: Row( + children: [ + const Expanded( + flex: 3, + child: SizedBox( + width: double.infinity, + height: double.infinity, + ), + ), + Expanded( + flex: AppState().isArabic(context) ? 4 : 5, + child: SizedBox( + width: double.infinity, + height: double.infinity, + child: Row( + mainAxisAlignment: MainAxisAlignment.start, children: [ - AppState().isArabic(context) ? 0.height : 5.height, - Text( - LocaleKeys.getReadyForContest.tr(), - style: TextStyle( - fontSize: isTablet ? 20 : 11, - fontStyle: FontStyle.italic, - fontWeight: FontWeight.w600, - color: MyColors.white.withOpacity(0.83), - letterSpacing: -0.4, - ), - ), - Text( - AppState().isArabic(context) ? provider.marathonDetailModel.titleAr ?? "" : provider.marathonDetailModel.titleEn ?? "", - style: TextStyle( - fontStyle: FontStyle.italic, - fontSize: isTablet ? 30 : 19, - fontWeight: FontWeight.bold, - color: MyColors.white.withOpacity(0.83), - height: 32 / 22, - ), - ), - isTablet ? 10.height : 3.height, - BuildCountdownTimer( - timeToMarathon: DateTime.parse(provider.marathonDetailModel.startTime!).millisecondsSinceEpoch, - provider: provider, - screenFlag: 0, - ), + Column( + mainAxisAlignment: MainAxisAlignment.center, + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + AppState().isArabic(context) ? 0.height : 5.height, + Text( + LocaleKeys.getReadyForContest.tr(), + style: TextStyle( + fontSize: isTablet ? 20 : 11, + fontStyle: FontStyle.italic, + fontWeight: FontWeight.w600, + color: MyColors.white.withOpacity(0.83), + letterSpacing: -0.4, + ), + ), + Text( + AppState().isArabic(context) ? provider.marathonDetailModel.titleAr ?? "" : provider.marathonDetailModel.titleEn ?? "", + style: TextStyle( + fontStyle: FontStyle.italic, + fontSize: isTablet ? 30 : 19, + fontWeight: FontWeight.bold, + color: MyColors.white.withOpacity(0.83), + height: 32 / 22, + ), + ), + isTablet ? 10.height : 3.height, + BuildCountdownTimer( + timeToMarathon: DateTime.parse(provider.marathonDetailModel.startTime!).millisecondsSinceEpoch, + provider: provider, + screenFlag: 0, + ), + ], + ).paddingOnly( + left: AppState().isArabic(context) ? 12 : 3, + right: AppState().isArabic(context) ? 3 : 12, + ) ], - ).paddingOnly( - left: AppState().isArabic(context) ? 12 : 3, - right: AppState().isArabic(context) ? 3 : 12, - ) - ], + ), + ), ), - ), + ], ), - ], - ), - ), - AppState().isArabic(context) - ? Align( - alignment: Alignment.topRight, - child: SizedBox( - height: isTablet ? 30 : 20, - width: isTablet ? 45 : 35, - child: Transform.rotate( - angle: math.pi / 4.5, - child: Text( - LocaleKeys.brainMarathon.tr(), - textAlign: TextAlign.center, - maxLines: 2, - style: TextStyle( - color: MyColors.white, - fontWeight: FontWeight.bold, - fontSize: isTablet ? 8 : 6, - height: 1.2, + ), + AppState().isArabic(context) + ? Align( + alignment: Alignment.topRight, + child: SizedBox( + height: isTablet ? 30 : 20, + width: isTablet ? 45 : 35, + child: Transform.rotate( + angle: math.pi / 4.5, + child: Text( + LocaleKeys.brainMarathon.tr(), + textAlign: TextAlign.center, + maxLines: 2, + style: TextStyle( + color: MyColors.white, + fontWeight: FontWeight.bold, + fontSize: isTablet ? 8 : 6, + height: 1.2, + ), + ), ), ), - ), - ), - ).paddingOnly(top: 5) - : Align( - alignment: Alignment.topLeft, - child: SizedBox( - height: isTablet ? 30 : 20, - width: isTablet ? 45 : 35, - child: Transform.rotate( - angle: -math.pi / 4.5, - child: Text( - LocaleKeys.brainMarathon.tr(), - textAlign: TextAlign.center, - maxLines: 2, - style: TextStyle( - color: MyColors.kWhiteColor, - fontWeight: FontWeight.bold, - fontSize: isTablet ? 8 : 6, - height: 1.2, + ).paddingOnly(top: 5) + : Align( + alignment: Alignment.topLeft, + child: SizedBox( + height: isTablet ? 30 : 20, + width: isTablet ? 45 : 35, + child: Transform.rotate( + angle: -math.pi / 4.5, + child: Text( + LocaleKeys.brainMarathon.tr(), + textAlign: TextAlign.center, + maxLines: 2, + style: TextStyle( + color: MyColors.kWhiteColor, + fontWeight: FontWeight.bold, + fontSize: isTablet ? 8 : 6, + height: 1.2, + ), + ), ), ), + ).paddingOnly(top: 5), + !AppState().isArabic(context) + ? Positioned( + right: 0, + bottom: 0, + child: RotatedBox( + quarterTurns: 4, + child: SvgPicture.asset("assets/images/arrow_next.svg", color: MyColors.whiteColor), + ).paddingAll(isTablet ? 20 : 15), + ) + : Positioned( + bottom: 0, + left: 0, + child: RotatedBox( + quarterTurns: 2, + child: SvgPicture.asset("assets/images/arrow_next.svg", color: MyColors.whiteColor), + ).paddingAll(isTablet ? 20 : 15), ), - ), - ).paddingOnly(top: 5), - !AppState().isArabic(context) - ? Positioned( - right: 0, - bottom: 0, - child: RotatedBox( - quarterTurns: 4, - child: SvgPicture.asset("assets/images/arrow_next.svg", color: MyColors.whiteColor), - ).paddingAll(isTablet ? 20 : 15), - ) - : Positioned( - bottom: 0, - left: 0, - child: RotatedBox( - quarterTurns: 2, - child: SvgPicture.asset("assets/images/arrow_next.svg", color: MyColors.whiteColor), - ).paddingAll(isTablet ? 20 : 15), - ), - ], - ).onPress(() async { - int remainingTimeInMinutes = DateTime.parse(provider.marathonDetailModel.startTime!).difference(DateTime.now()).inMinutes; - if (remainingTimeInMinutes > 2) { - Utils.showLoading(context); - try { - await provider.initializeVideoPlayer().then((_) { - Utils.hideLoading(context); - provider.startTimerForSponsorVideo(); - Navigator.pushNamed(context, AppRoutes.marathonSponsorVideoScreen); - }); - } catch (e, s) { - if (kDebugMode) { - print("Error in VideoPlayer: ${e.toString()}"); - } - Utils.hideLoading(context); - Navigator.pushNamed(context, AppRoutes.marathonIntroScreen); - } - } else { - Navigator.pushNamed(context, AppRoutes.marathonIntroScreen); - } - }), - ) - : const SizedBox(); + ], + ).onPress(() async { + int remainingTimeInMinutes = DateTime.parse(provider.marathonDetailModel.startTime!).difference(DateTime.now()).inMinutes; + + if (remainingTimeInMinutes > 2) { + Utils.showLoading(context); + try { + await provider.initializeVideoPlayer().then((_) { + Utils.hideLoading(context); + provider.startTimerForSponsorVideo(); + Navigator.pushNamed(context, AppRoutes.marathonSponsorVideoScreen); + }); + } catch (e) { + if (kDebugMode) { + print("Error in VideoPlayer: ${e.toString()}"); + } + Utils.hideLoading(context); + Navigator.pushNamed(context, AppRoutes.marathonIntroScreen); + } + } else { + Navigator.pushNamed(context, AppRoutes.marathonIntroScreen); + } + }), + ) + : const SizedBox(); } } From 76239d0077b1ca46d0b1526d82f67cd211eca314 Mon Sep 17 00:00:00 2001 From: "Aamir.Muhammad" Date: Tue, 13 Dec 2022 11:36:38 +0300 Subject: [PATCH 14/42] Fixes --- .../chat/get_single_user_chat_list_model.dart | 2 ++ lib/provider/chat_provider_model.dart | 36 ++++++++++++------- lib/ui/chat/chat_detailed_screen.dart | 6 +++- lib/ui/chat/chat_home.dart | 27 +++++++------- lib/ui/landing/dashboard_screen.dart | 3 +- 5 files changed, 45 insertions(+), 29 deletions(-) diff --git a/lib/models/chat/get_single_user_chat_list_model.dart b/lib/models/chat/get_single_user_chat_list_model.dart index 80ffa5a..ee4f210 100644 --- a/lib/models/chat/get_single_user_chat_list_model.dart +++ b/lib/models/chat/get_single_user_chat_list_model.dart @@ -38,8 +38,10 @@ class SingleUserChatModel { String? contantNo; int? currentUserId; String? currentUserName; + String? currentUserEmail; int? targetUserId; String? targetUserName; + String? targetUserEmail; String? encryptedTargetUserId; String? encryptedTargetUserName; int? chatEventId; diff --git a/lib/provider/chat_provider_model.dart b/lib/provider/chat_provider_model.dart index 3a4e70b..67899c5 100644 --- a/lib/provider/chat_provider_model.dart +++ b/lib/provider/chat_provider_model.dart @@ -330,8 +330,11 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { temp = getSingleUserChatModel(jsonEncode(msg)); data.first.targetUserId = temp.first.currentUserId; data.first.targetUserName = temp.first.currentUserName; + data.first.targetUserEmail = temp.first.currentUserEmail; data.first.currentUserId = temp.first.targetUserId; data.first.currentUserName = temp.first.targetUserName; + data.first.currentUserEmail = temp.first.targetUserEmail; + if (data.first.fileTypeId == 12 || data.first.fileTypeId == 4 || data.first.fileTypeId == 3) { data.first.image = await ChatApiClient().downloadURL(fileName: data.first.contant!, fileTypeDescription: data.first.fileTypeResponse!.fileTypeDescription ?? "image/jpg"); } @@ -349,21 +352,24 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { if (searchedChats != null) { dynamic contain = searchedChats!.where((ChatUser element) => element.id == data.first.currentUserId); if (contain.isEmpty) { + List emails = []; + emails.add(await EmailImageEncryption().encrypt(val: data.first.currentUserEmail!)); + List chatImages = await ChatApiClient().getUsersImages(encryptedEmails: emails); searchedChats!.add( ChatUser( - id: data.first.currentUserId, - userName: data.first.currentUserName, - unreadMessageCount: 0, - isImageLoading: false, - image: "", - isImageLoaded: true, - userStatus: 1, - isTyping: false, - userLocalDownlaodedImage: null), + id: data.first.currentUserId, + userName: data.first.currentUserName, + unreadMessageCount: 0, + isImageLoading: false, + image: chatImages!.first.profilePicture ?? "", + isImageLoaded: true, + userStatus: 1, + isTyping: false, + userLocalDownlaodedImage: await downloadImageLocal(chatImages.first.profilePicture, data.first.currentUserId.toString()), + ), ); } } - setMsgTune(); userChatHistory.insert(0, data.first); @@ -526,21 +532,25 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { await chatHubConnection.invoke("AddChatUserAsync", args: [json.decode(chatData)]); } - void sendChatMessage(int targetUserId, int userStatus, String targetUserName, BuildContext context) async { + void sendChatMessage(BuildContext context, {required int targetUserId, required int userStatus, required String userEmail, required String targetUserName}) async { dynamic contain = searchedChats!.where((ChatUser element) => element.id == targetUserId); if (contain.isEmpty) { + List emails = []; + emails.add(await EmailImageEncryption().encrypt(val: userEmail)); + List chatImages = await ChatApiClient().getUsersImages(encryptedEmails: emails); searchedChats!.add( ChatUser( id: targetUserId, userName: targetUserName, unreadMessageCount: 0, + email: userEmail, isImageLoading: false, - image: "", + image: chatImages.first.profilePicture ?? "", isImageLoaded: true, isTyping: false, isFav: false, userStatus: userStatus, - userLocalDownlaodedImage: null, + userLocalDownlaodedImage: await downloadImageLocal(chatImages.first.profilePicture, targetUserId.toString()), ), ); notifyListeners(); diff --git a/lib/ui/chat/chat_detailed_screen.dart b/lib/ui/chat/chat_detailed_screen.dart index 05e674a..be685df 100644 --- a/lib/ui/chat/chat_detailed_screen.dart +++ b/lib/ui/chat/chat_detailed_screen.dart @@ -223,7 +223,11 @@ class _ChatDetailScreenState extends State { ), ).paddingOnly(right: 25), SvgPicture.asset("assets/icons/chat/chat_send_icon.svg", height: 26, width: 26).onPress( - () => m.sendChatMessage(params!.chatUser!.id!, params!.chatUser!.userStatus ?? 0, params!.chatUser!.userName!, context), + () => m.sendChatMessage(context, + targetUserId: params!.chatUser!.id!, + userStatus: params!.chatUser!.userStatus ?? 0, + userEmail: params!.chatUser!.email!, + targetUserName: params!.chatUser!.userName!), ), ], ), diff --git a/lib/ui/chat/chat_home.dart b/lib/ui/chat/chat_home.dart index 807af1a..330242a 100644 --- a/lib/ui/chat/chat_home.dart +++ b/lib/ui/chat/chat_home.dart @@ -38,23 +38,22 @@ class _ChatHomeState extends State { data.clearAll(); } - // void fetchAgain() { - // print("Fetch Triggered"); - // if (chatHubConnection.state != HubConnectionState.Connected) { - // data.getUserAutoLoginToken().whenComplete(() async { - // await data.buildHubConnection(); - // data.getUserRecentChats(); - // }); - // return; - // } - // if (data.searchedChats == null || data.searchedChats!.isEmpty) { - // data.getUserRecentChats(); - // } - // } + void fetchAgain() { + if (chatHubConnection.state != HubConnectionState.Connected) { + data.getUserAutoLoginToken().whenComplete(() async { + await data.buildHubConnection(); + data.getUserRecentChats(); + }); + return; + } + if (data.searchedChats == null || data.searchedChats!.isEmpty) { + data.getUserRecentChats(); + } + } @override Widget build(BuildContext context) { - // fetchAgain(); + fetchAgain(); return Scaffold( backgroundColor: MyColors.white, appBar: AppBarWidget(context, title: LocaleKeys.chat.tr(), showHomeButton: true), diff --git a/lib/ui/landing/dashboard_screen.dart b/lib/ui/landing/dashboard_screen.dart index 1800aa3..b1dac53 100644 --- a/lib/ui/landing/dashboard_screen.dart +++ b/lib/ui/landing/dashboard_screen.dart @@ -58,7 +58,7 @@ class _DashboardScreenState extends State { data = Provider.of(context, listen: false); marathonProvider = Provider.of(context, listen: false); cProvider = Provider.of(context, listen: false); - _bHubCon(); + _onRefresh(); }); } @@ -80,6 +80,7 @@ class _DashboardScreenState extends State { void _onRefresh() async { data.initProvider(); + _bHubCon(); // data.getITGNotification().then((value) { // print("--------------------detail_1-----------------"); // print(value!.result!.data!.notificationMasterId); From 1144664d6457b56882c2683e5cb2a2cbe647e35c Mon Sep 17 00:00:00 2001 From: "Aamir.Muhammad" Date: Tue, 13 Dec 2022 11:52:38 +0300 Subject: [PATCH 15/42] Images Fixes --- lib/models/chat/get_single_user_chat_list_model.dart | 6 ++++++ lib/ui/chat/favorite_users_screen.dart | 2 +- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/lib/models/chat/get_single_user_chat_list_model.dart b/lib/models/chat/get_single_user_chat_list_model.dart index ee4f210..246a515 100644 --- a/lib/models/chat/get_single_user_chat_list_model.dart +++ b/lib/models/chat/get_single_user_chat_list_model.dart @@ -19,6 +19,8 @@ class SingleUserChatModel { this.targetUserName, this.encryptedTargetUserId, this.encryptedTargetUserName, + this.currentUserEmail, + this.targetUserEmail, this.chatEventId, this.fileTypeId, this.isSeen, @@ -66,6 +68,8 @@ class SingleUserChatModel { currentUserName: json["currentUserName"] == null ? null : json["currentUserName"], targetUserId: json["targetUserId"] == null ? null : json["targetUserId"], targetUserName: json["targetUserName"] == null ? null : json["targetUserName"], + targetUserEmail: json["targetUserEmail"] == null ? null : json["targetUserEmail"], + currentUserEmail: json["currentUserEmail"] == null ? null : json["currentUserEmail"], encryptedTargetUserId: json["encryptedTargetUserId"] == null ? null : json["encryptedTargetUserId"], encryptedTargetUserName: json["encryptedTargetUserName"] == null ? null : json["encryptedTargetUserName"], chatEventId: json["chatEventId"] == null ? null : json["chatEventId"], @@ -92,6 +96,8 @@ class SingleUserChatModel { "targetUserName": targetUserName == null ? null : targetUserName, "encryptedTargetUserId": encryptedTargetUserId == null ? null : encryptedTargetUserId, "encryptedTargetUserName": encryptedTargetUserName == null ? null : encryptedTargetUserName, + "currentUserEmail": currentUserEmail == null ? null : currentUserEmail, + "targetUserEmail": targetUserEmail == null ? null : targetUserEmail, "chatEventId": chatEventId == null ? null : chatEventId, "fileTypeId": fileTypeId, "isSeen": isSeen == null ? null : isSeen, diff --git a/lib/ui/chat/favorite_users_screen.dart b/lib/ui/chat/favorite_users_screen.dart index 157a884..a978ccb 100644 --- a/lib/ui/chat/favorite_users_screen.dart +++ b/lib/ui/chat/favorite_users_screen.dart @@ -111,7 +111,7 @@ class ChatFavoriteUsersScreen extends StatelessWidget { Navigator.pushNamed( context, AppRoutes.chatDetailed, - arguments: ChatDetailedScreenParams(m.favUsersList![index], false), + arguments: ChatDetailedScreenParams(m.favUsersList![index], true), ).then( (Object? value) { m.clearSelections(); From 243da0c775cef79372d68e181c1e2cf33c0e3cfa Mon Sep 17 00:00:00 2001 From: haroon amjad Date: Tue, 13 Dec 2022 11:57:22 +0300 Subject: [PATCH 16/42] fixes --- lib/widgets/item_detail_view_widget.dart | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/widgets/item_detail_view_widget.dart b/lib/widgets/item_detail_view_widget.dart index ccdedea..77d959b 100644 --- a/lib/widgets/item_detail_view_widget.dart +++ b/lib/widgets/item_detail_view_widget.dart @@ -39,7 +39,7 @@ class ItemDetailViewCol extends StatelessWidget { children: [ "$title:".toText12(isBold: true, color: const Color(0xff2BB8A6), maxLine: 2), 4.width, - (value.isEmpty ? "--" : value).toText12(color: MyColors.normalTextColor, maxLine: 2), + (value.isEmpty ? "--" : value).toText12(color: MyColors.normalTextColor, maxLine: 5), ], ); } From a39e6808d71cde79e81f9befcf5fa0e0d9f14be1 Mon Sep 17 00:00:00 2001 From: haroon amjad Date: Tue, 13 Dec 2022 12:20:55 +0300 Subject: [PATCH 17/42] fixes & updates --- lib/api/marathon/marathon_api_client.dart | 1 - lib/api/monthly_attendance_api_client.dart | 2 -- lib/api/monthly_pay_slip_api_client.dart | 1 - lib/api/my_attendance_api_client.dart | 1 - lib/api/my_team/my_team_api_client.dart | 2 -- lib/api/profile_api_client.dart | 8 -------- lib/api/termination_dff_api_client.dart | 3 --- lib/classes/utils.dart | 1 - lib/ui/chat/chat_home_screen.dart | 12 +++++------- lib/ui/landing/today_attendance_screen.dart | 2 -- lib/ui/login/verify_login_screen.dart | 3 --- lib/ui/marathon/marathon_provider.dart | 2 -- lib/ui/profile/basic_details.dart | 5 ++--- lib/ui/profile/delete_family_member.dart | 1 - .../dynamic_input_address_screen.dart | 1 - .../fragments/items_for_sale.dart | 1 - .../fragments/my_posted_ads_fragment.dart | 1 - lib/ui/termination/end_employement.dart | 1 - lib/ui/work_list/itg_detail_screen.dart | 2 -- lib/widgets/chat_app_bar_widge.dart | 8 +------- lib/widgets/mark_attendance_widget.dart | 17 ----------------- lib/widgets/nfc/nfc_reader_sheet.dart | 1 - pubspec.yaml | 2 +- 23 files changed, 9 insertions(+), 69 deletions(-) diff --git a/lib/api/marathon/marathon_api_client.dart b/lib/api/marathon/marathon_api_client.dart index a9266d2..26a0363 100644 --- a/lib/api/marathon/marathon_api_client.dart +++ b/lib/api/marathon/marathon_api_client.dart @@ -30,7 +30,6 @@ class MarathonApiClient { if (marathonModel.statusCode == 200) { if (marathonModel.data != null && marathonModel.isSuccessful == true) { AppState().setMarathonToken = marathonModel.data["token"] ?? ""; - print("bearer: ${AppState().getMarathonToken}"); return marathonModel.data["token"] ?? ""; } else { //TODO : DO ERROR HANDLING HERE diff --git a/lib/api/monthly_attendance_api_client.dart b/lib/api/monthly_attendance_api_client.dart index 00d444f..e462373 100644 --- a/lib/api/monthly_attendance_api_client.dart +++ b/lib/api/monthly_attendance_api_client.dart @@ -29,7 +29,6 @@ class MonthlyAttendanceApiClient { postParams.addAll(AppState().postParamsJson); return await ApiClient().postJsonForObject((json) { GenericResponseModel? responseData = GenericResponseModel.fromJson(json); - print(responseData); return (responseData.getTimeCardSummaryList?.length ?? 0) > 0 ? responseData.getTimeCardSummaryList!.first : null; }, url, postParams); } @@ -49,7 +48,6 @@ class MonthlyAttendanceApiClient { // postParams["DeviceType"] = deviceType; return await ApiClient().postJsonForObject((json) { GenericResponseModel? responseData = GenericResponseModel.fromJson(json); - print(responseData.getDayHoursTypeDetailsList!.length); return responseData.getDayHoursTypeDetailsList ?? []; }, url, postParams); } diff --git a/lib/api/monthly_pay_slip_api_client.dart b/lib/api/monthly_pay_slip_api_client.dart index 95bf847..e3071a4 100644 --- a/lib/api/monthly_pay_slip_api_client.dart +++ b/lib/api/monthly_pay_slip_api_client.dart @@ -19,7 +19,6 @@ class MonthlyPaySlipApiClient { String url = "${ApiConsts.erpRest}GET_PAYSLIP"; Map postParams = {"P_MENU_TYPE": "E", "P_SELECTED_RESP_ID": -999}; postParams.addAll(AppState().postParamsJson); - print(postParams); return await ApiClient().postJsonForObject((json) { GenericResponseModel? responseData = GenericResponseModel.fromJson(json); return responseData.getPayslipList ?? []; diff --git a/lib/api/my_attendance_api_client.dart b/lib/api/my_attendance_api_client.dart index 5833413..0f078a2 100644 --- a/lib/api/my_attendance_api_client.dart +++ b/lib/api/my_attendance_api_client.dart @@ -26,7 +26,6 @@ class MyAttendanceApiClient { if (empID!.isNotEmpty) { postParams['P_SELECTED_EMPLOYEE_NUMBER'] = empID; // AppState().postParamsJson['P_SELECTED_EMPLOYEE_NUMBER'] = empID; - print(empID); } return await ApiClient().postJsonForObject((json) { GenericResponseModel? responseData = GenericResponseModel.fromJson(json); diff --git a/lib/api/my_team/my_team_api_client.dart b/lib/api/my_team/my_team_api_client.dart index 17a0a90..df635b0 100644 --- a/lib/api/my_team/my_team_api_client.dart +++ b/lib/api/my_team/my_team_api_client.dart @@ -64,7 +64,6 @@ class MyTeamApiClient { postParams['P_SELECTED_EMPLOYEE_NUMBER'] = empID; return await ApiClient().postJsonForObject((json) { GenericResponseModel? responseData = GenericResponseModel.fromJson(json); - print(responseData.getDayHoursTypeDetailsList!.length); return responseData.getDayHoursTypeDetailsList ?? []; }, url, postParams); } @@ -76,7 +75,6 @@ class MyTeamApiClient { postParams['P_SELECTED_EMPLOYEE_NUMBER'] = empID; return await ApiClient().postJsonForObject((json) { GenericResponseModel? responseData = GenericResponseModel.fromJson(json); - print(responseData.getAttendanceTrackingList); return responseData.getAttendanceTrackingList; }, url, postParams); } diff --git a/lib/api/profile_api_client.dart b/lib/api/profile_api_client.dart index 210d179..6a8cfb0 100644 --- a/lib/api/profile_api_client.dart +++ b/lib/api/profile_api_client.dart @@ -41,7 +41,6 @@ class ProfileApiClient { postParams.addAll(AppState().postParamsJson); return await ApiClient().postJsonForObject((json) { GenericResponseModel? responseData = GenericResponseModel.fromJson(json); - print(responseData); return responseData.getEmployeeContactsList ?? []; }, url, postParams); } @@ -258,7 +257,6 @@ class ProfileApiClient { // "EITTransactionTBLModel": list, }; postParams.addAll(AppState().postParamsJson); - print("postParams:$postParams"); postParams["EITTransactionTBL"] = list; postParams["EITTransactionTBLModel"] = list; return await ApiClient().postJsonForObject((json) { @@ -300,7 +298,6 @@ class ProfileApiClient { // "EITTransactionTBLModel": list, }; postParams.addAll(AppState().postParamsJson); - print("postParams:$postParams"); postParams["EITTransactionTBL"] = list; // postParams["EITTransactionTBLModel"] = list; return await ApiClient().postJsonForObject((json) { @@ -389,12 +386,7 @@ class ProfileApiClient { }; postParams.addAll(AppState().postParamsJson); - print("postParam:${json.encode(postParams)}"); postParams["EITTransactionTBL"] = list; - list.forEach((element) { - print(json.encode(element)); - - }); return await ApiClient().postJsonForObject((json) { GenericResponseModel? responseData = GenericResponseModel.fromJson(json); return responseData.submitContactTransactionList; diff --git a/lib/api/termination_dff_api_client.dart b/lib/api/termination_dff_api_client.dart index 0933dea..0d5864f 100644 --- a/lib/api/termination_dff_api_client.dart +++ b/lib/api/termination_dff_api_client.dart @@ -46,9 +46,6 @@ class TerminationDffApiClient { }; postParams.addAll(AppState().postParamsJson); - for (var abc in list) { - print(abc); - } return await ApiClient().postJsonForObject((json) { GenericResponseModel genericResponseModel = GenericResponseModel.fromJson(json); return genericResponseModel.submitTermTransactionList!; diff --git a/lib/classes/utils.dart b/lib/classes/utils.dart index 3be8356..fbdc6ce 100644 --- a/lib/classes/utils.dart +++ b/lib/classes/utils.dart @@ -340,7 +340,6 @@ class Utils { static void readNFc({required Function(String) onRead}) { NfcManager.instance.startSession(onDiscovered: (NfcTag tag) async { - print(tag.data); var f; if (Platform.isAndroid) { f = MifareUltralight(tag: tag, identifier: tag.data["nfca"]["identifier"], type: 2, maxTransceiveLength: 252, timeout: 22); diff --git a/lib/ui/chat/chat_home_screen.dart b/lib/ui/chat/chat_home_screen.dart index a9814ee..395556a 100644 --- a/lib/ui/chat/chat_home_screen.dart +++ b/lib/ui/chat/chat_home_screen.dart @@ -1,5 +1,3 @@ -import 'dart:convert'; -import 'package:animated_text_kit/animated_text_kit.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; @@ -139,11 +137,11 @@ class _ChatHomeScreenState extends State { children: [ (m.searchedChats![index].userName!.replaceFirst(".", " ").capitalizeFirstofEach ?? "").toText14(color: MyColors.darkTextColor).paddingOnly(left: 11, top: 13), m.searchedChats![index].isTyping! - ? AnimatedTextKit( - animatedTexts: [ - ScaleAnimatedText('Typing...', textStyle: const TextStyle(color: MyColors.textMixColor, fontSize: 10, letterSpacing: -0.4, fontStyle: FontStyle.normal)), - ], - ).paddingOnly(left: 11) + ? 'Typing...' + .toText10( + color: MyColors.textMixColor, + ) + .paddingOnly(left: 11.0) : const SizedBox() //(m.searchedChats![index].isTyping! ? "Typing ..." : "").toText10(color: MyColors.textMixColor).paddingOnly(left: 11, top: 0), ], diff --git a/lib/ui/landing/today_attendance_screen.dart b/lib/ui/landing/today_attendance_screen.dart index d23fa10..ea3ae24 100644 --- a/lib/ui/landing/today_attendance_screen.dart +++ b/lib/ui/landing/today_attendance_screen.dart @@ -41,8 +41,6 @@ class _TodayAttendanceScreenState extends State { bool isAvailable = await NfcManager.instance.isAvailable(); setState(() { AppState().privilegeListModel!.forEach((element) { - print(element.serviceName.toString() + " " + element.previlege.toString()); // Check availability - if (element.serviceName == "enableNFC") { if (isAvailable) if (element.previlege ?? false) isNfcEnabled = true; } else if (element.serviceName == "enableQR") { diff --git a/lib/ui/login/verify_login_screen.dart b/lib/ui/login/verify_login_screen.dart index b5eb7df..803f3d9 100644 --- a/lib/ui/login/verify_login_screen.dart +++ b/lib/ui/login/verify_login_screen.dart @@ -636,9 +636,6 @@ class _VerifyLoginScreenState extends State { AppState().setPrivilegeListModel = genericResponseModel!.privilegeList ?? []; AppState().setMemberInformationListModel = genericResponseModel.memberInformationList?.first; MemberInformationListModel.saveToPrefs(genericResponseModel.memberInformationList ?? []); - genericResponseModel.privilegeList!.forEach((element) { - print(element.serviceName.toString() + " " + element.previlege.toString()); // Check availability - }); PrivilegeListModel.saveToPrefs(genericResponseModel.privilegeList ?? []); AppState().setMohemmWifiSSID = genericResponseModel.mohemmWifiSSID; AppState().setMohemmWifiPassword = genericResponseModel.mohemmWifiPassword; diff --git a/lib/ui/marathon/marathon_provider.dart b/lib/ui/marathon/marathon_provider.dart index 175b7be..c5b1cd7 100644 --- a/lib/ui/marathon/marathon_provider.dart +++ b/lib/ui/marathon/marathon_provider.dart @@ -242,7 +242,6 @@ class MarathonProvider extends ChangeNotifier { selectedWinners = await MarathonApiClient().getSelectedWinner(marathonId: marathonDetailModel.id!); if (selectedWinners != null) { selectedWinners!.removeWhere((WinnerModel element) { - print("matching : ${AppState().memberInformationList!.eMPLOYEENUMBER} with ${element.employeeId}"); if (element.employeeId == AppState().memberInformationList!.eMPLOYEENUMBER) { iAmWinner = true; return true; @@ -251,7 +250,6 @@ class MarathonProvider extends ChangeNotifier { } }); } - print("selectedWinners Length : ${selectedWinners!.length}"); notifyListeners(); } diff --git a/lib/ui/profile/basic_details.dart b/lib/ui/profile/basic_details.dart index c91adb5..42ecf1d 100644 --- a/lib/ui/profile/basic_details.dart +++ b/lib/ui/profile/basic_details.dart @@ -44,13 +44,12 @@ class _BasicDetailsState extends State { super.initState(); memberInformationList = AppState().memberInformationList!; List menuData = Provider.of(context, listen: false).getMenuEntriesList!; - for( int i=0;i e.requestType == 'BASIC_DETAILS').toList(); - if(filterList.isNotEmpty) { + if (filterList.isNotEmpty) { menuEntries = filterList.first; } diff --git a/lib/ui/profile/delete_family_member.dart b/lib/ui/profile/delete_family_member.dart index 73c44de..16052f8 100644 --- a/lib/ui/profile/delete_family_member.dart +++ b/lib/ui/profile/delete_family_member.dart @@ -37,7 +37,6 @@ class _DeleteFamilyMemberState extends State { //int? relationId; @override void initState() { - print(widget.relationId); super.initState(); } diff --git a/lib/ui/profile/dynamic_screens/dynamic_input_address_screen.dart b/lib/ui/profile/dynamic_screens/dynamic_input_address_screen.dart index a233839..77b2abd 100644 --- a/lib/ui/profile/dynamic_screens/dynamic_input_address_screen.dart +++ b/lib/ui/profile/dynamic_screens/dynamic_input_address_screen.dart @@ -294,7 +294,6 @@ class _DynamicInputScreenState extends State { countryCode, effectiveDate.isEmpty ? DateFormat('dd-MMM-yyy').format(DateTime.now()) : effectiveDate, ); - print(values); Utils.hideLoading(context); Navigator.pushNamed(context, AppRoutes.requestSubmitScreen, diff --git a/lib/ui/screens/items_for_sale/fragments/items_for_sale.dart b/lib/ui/screens/items_for_sale/fragments/items_for_sale.dart index 50a89cc..ae715fe 100644 --- a/lib/ui/screens/items_for_sale/fragments/items_for_sale.dart +++ b/lib/ui/screens/items_for_sale/fragments/items_for_sale.dart @@ -39,7 +39,6 @@ class _ItemsForSaleFragmentState extends State { if (gridScrollController.position.atEdge) { bool isTop = gridScrollController.position.pixels == 0; if (!isTop && getItemsForSaleList.length == currentPageNo * 10) { - print('At the bottom'); currentPageNo++; getItemsForSale(currentPageNo, currentCategoryID); } diff --git a/lib/ui/screens/items_for_sale/fragments/my_posted_ads_fragment.dart b/lib/ui/screens/items_for_sale/fragments/my_posted_ads_fragment.dart index f477672..64b8bf9 100644 --- a/lib/ui/screens/items_for_sale/fragments/my_posted_ads_fragment.dart +++ b/lib/ui/screens/items_for_sale/fragments/my_posted_ads_fragment.dart @@ -193,7 +193,6 @@ class _MyPostedAdsFragmentState extends State { Utils.hideLoading(context); Utils.handleException(e, context, null); }); - print(response.statusCode); Utils.hideLoading(context); getAdsByEmployee(); } diff --git a/lib/ui/termination/end_employement.dart b/lib/ui/termination/end_employement.dart index 6fbfa61..73e8f79 100644 --- a/lib/ui/termination/end_employement.dart +++ b/lib/ui/termination/end_employement.dart @@ -255,7 +255,6 @@ class _EndEmploymentScreenState extends State { ], onSelected: (int popipIndex) async { termColObject.selectedObjectValue = termColObject.objectValuesList![popipIndex]; - print(termColObject.selectedObjectValue?.toJson()); setState(() {}); }); } diff --git a/lib/ui/work_list/itg_detail_screen.dart b/lib/ui/work_list/itg_detail_screen.dart index e123d22..ebe16c8 100644 --- a/lib/ui/work_list/itg_detail_screen.dart +++ b/lib/ui/work_list/itg_detail_screen.dart @@ -352,7 +352,6 @@ class _ItgDetailScreenState extends State { } void handleFabAction(AllowedActions action) { - print(action.toJson()); switch (action.action) { case "Delegate": showMyBottomSheet(context, @@ -461,7 +460,6 @@ class _ItgDetailScreenState extends State { } void performAction(String actionMode) { - print(actionMode); showDialog( context: context, builder: (cxt) => ITGCommentsDialog( diff --git a/lib/widgets/chat_app_bar_widge.dart b/lib/widgets/chat_app_bar_widge.dart index 0feac6c..a67ae7d 100644 --- a/lib/widgets/chat_app_bar_widge.dart +++ b/lib/widgets/chat_app_bar_widge.dart @@ -1,4 +1,3 @@ -import 'package:animated_text_kit/animated_text_kit.dart'; import 'package:flutter/material.dart'; import 'package:flutter_svg/flutter_svg.dart'; import 'package:mohem_flutter_app/classes/colors.dart'; @@ -51,12 +50,7 @@ AppBar ChatAppBarWidget(BuildContext context, Consumer( builder: (BuildContext cxt, ChatProviderModel data, Widget? child) { if (chatUser!.isTyping!) { - // return ("Typing ...").toText10(color: MyColors.textMixColor); - return AnimatedTextKit( - animatedTexts: [ - ScaleAnimatedText('Typing...', textStyle: const TextStyle(color: MyColors.textMixColor, fontSize: 10, letterSpacing: -0.4, fontStyle: FontStyle.normal)), - ], - ); + return ("Typing ...").toText10(color: MyColors.textMixColor); } else { return const SizedBox(); } diff --git a/lib/widgets/mark_attendance_widget.dart b/lib/widgets/mark_attendance_widget.dart index a6b6cfc..9840700 100644 --- a/lib/widgets/mark_attendance_widget.dart +++ b/lib/widgets/mark_attendance_widget.dart @@ -48,8 +48,6 @@ class _MarkAttendanceWidgetState extends State { bool isAvailable = await NfcManager.instance.isAvailable(); setState(() { AppState().privilegeListModel!.forEach((element) { - print(element.serviceName.toString() + " " + element.previlege.toString()); // Check availability - if (element.serviceName == "enableNFC") { if (isAvailable) if (element.previlege ?? false) isNfcEnabled = true; } else if (element.serviceName == "enableQR") { @@ -76,7 +74,6 @@ class _MarkAttendanceWidgetState extends State { @override Widget build(BuildContext context) { - print(MediaQuery.of(context).size.width); return Container( padding: EdgeInsets.only(left: 21, right: 21, bottom: 21, top: widget.topPadding), decoration: const BoxDecoration(borderRadius: BorderRadius.only(topLeft: Radius.circular(25), topRight: Radius.circular(25)), color: Colors.white), @@ -134,12 +131,6 @@ class _MarkAttendanceWidgetState extends State { } Future performNfcAttendance(DashboardProviderModel model, {String lat = "0", String lng = "0"}) async { - if (isNfcLocationEnabled) { - print("nfc location enabled"); - } else { - print("nfc not location enabled"); - } - if (Platform.isIOS) { Utils.readNFc(onRead: (String nfcId) async { Utils.showLoading(context); @@ -177,7 +168,6 @@ class _MarkAttendanceWidgetState extends State { }); } else { showNfcReader(context, onNcfScan: (String? nfcId) async { - print(nfcId); Utils.showLoading(context); try { GenericResponseModel? g = await DashboardApiClient().markAttendance(pointType: 2, nfcValue: nfcId ?? "", isGpsRequired: isNfcLocationEnabled, lat: lat, long: lng); @@ -214,12 +204,6 @@ class _MarkAttendanceWidgetState extends State { } Future performWifiAttendance(DashboardProviderModel model, {String lat = "0", String lng = "0"}) async { - if (isWifiLocationEnabled) { - print("wifi location enabled"); - } else { - print("wifi not location enabled"); - } - Utils.showLoading(context); bool isConnected = await WiFiForIoTPlugin.connect(AppState().getMohemmWifiSSID ?? "", password: AppState().getMohemmWifiPassword ?? "", joinOnce: Platform.isIOS ? false : true, security: NetworkSecurity.WPA, withInternet: false); @@ -271,7 +255,6 @@ class _MarkAttendanceWidgetState extends State { ), ); if (qrCodeValue != null) { - print("qrCode: " + qrCodeValue); Utils.showLoading(context); try { GenericResponseModel? g = await DashboardApiClient().markAttendance(pointType: 1, isGpsRequired: isQrLocationEnabled, lat: lat, long: lng, QRValue: qrCodeValue); diff --git a/lib/widgets/nfc/nfc_reader_sheet.dart b/lib/widgets/nfc/nfc_reader_sheet.dart index 4ac055b..b7b97a7 100644 --- a/lib/widgets/nfc/nfc_reader_sheet.dart +++ b/lib/widgets/nfc/nfc_reader_sheet.dart @@ -41,7 +41,6 @@ class _NfcLayoutState extends State { super.initState(); NfcManager.instance.startSession(onDiscovered: (NfcTag tag) async { - print(tag.data); var f; if (Platform.isAndroid) { f = MifareUltralight(tag: tag, identifier: tag.data["nfca"]["identifier"], type: 2, maxTransceiveLength: 252, timeout: 22); diff --git a/pubspec.yaml b/pubspec.yaml index 2e3c4c2..086ec65 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -92,7 +92,7 @@ dependencies: swipe_to: ^1.0.2 flutter_webrtc: ^0.9.16 camera: ^0.10.0+4 - animated_text_kit: ^4.2.2 +# animated_text_kit: ^4.2.2 #Encryption flutter_des: ^2.1.0 From 2caf5b6caa07d1191204f3d2cff872e143bb5e3e Mon Sep 17 00:00:00 2001 From: Faiz Hashmi Date: Tue, 13 Dec 2022 15:24:47 +0300 Subject: [PATCH 18/42] Pushing for testing --- lib/api/marathon/marathon_api_client.dart | 1 - lib/classes/consts.dart | 5 ++-- lib/ui/marathon/marathon_provider.dart | 6 ++--- lib/ui/marathon/marathon_screen.dart | 24 ++++++------------ .../marathon_sponsor_video_screen.dart | 3 --- .../widgets/marathon_details_card.dart | 25 ++++++++----------- 6 files changed, 24 insertions(+), 40 deletions(-) diff --git a/lib/api/marathon/marathon_api_client.dart b/lib/api/marathon/marathon_api_client.dart index a9266d2..26a0363 100644 --- a/lib/api/marathon/marathon_api_client.dart +++ b/lib/api/marathon/marathon_api_client.dart @@ -30,7 +30,6 @@ class MarathonApiClient { if (marathonModel.statusCode == 200) { if (marathonModel.data != null && marathonModel.isSuccessful == true) { AppState().setMarathonToken = marathonModel.data["token"] ?? ""; - print("bearer: ${AppState().getMarathonToken}"); return marathonModel.data["token"] ?? ""; } else { //TODO : DO ERROR HANDLING HERE diff --git a/lib/classes/consts.dart b/lib/classes/consts.dart index 3d58efd..0559996 100644 --- a/lib/classes/consts.dart +++ b/lib/classes/consts.dart @@ -2,9 +2,9 @@ import 'package:mohem_flutter_app/ui/marathon/widgets/question_card.dart'; class ApiConsts { //static String baseUrl = "http://10.200.204.20:2801/"; // Local server - // static String baseUrl = "https://uat.hmgwebservices.com"; // UAT server // static String baseUrl = "https://erptstapp.srca.org.sa"; // SRCA server - static String baseUrl = "https://hmgwebservices.com"; // Live server + static String baseUrl = "https://uat.hmgwebservices.com"; // UAT server + // static String baseUrl = "https://hmgwebservices.com"; // Live server static String baseUrlServices = baseUrl + "/Services/"; // server // static String baseUrlServices = "https://api.cssynapses.com/tangheem/"; // Live server static String utilitiesRest = baseUrlServices + "Utilities.svc/REST/"; @@ -28,6 +28,7 @@ class ApiConsts { //Brain Marathon Constants static String marathonBaseUrl = "https://marathoon.com/service/api/"; + static String marathonBaseUrlServices = "https://marathoon.com/service/"; static String marathonParticipantLoginUrl = marathonBaseUrl + "auth/participantlogin"; static String marathonProjectGetUrl = marathonBaseUrl + "Project/Project_Get"; static String marathonUpcomingUrl = marathonBaseUrl + "marathon/upcoming/"; diff --git a/lib/ui/marathon/marathon_provider.dart b/lib/ui/marathon/marathon_provider.dart index 175b7be..4144e32 100644 --- a/lib/ui/marathon/marathon_provider.dart +++ b/lib/ui/marathon/marathon_provider.dart @@ -6,6 +6,7 @@ import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:mohem_flutter_app/api/marathon/marathon_api_client.dart'; import 'package:mohem_flutter_app/app_state/app_state.dart'; +import 'package:mohem_flutter_app/classes/consts.dart'; import 'package:mohem_flutter_app/classes/utils.dart'; import 'package:mohem_flutter_app/config/routes.dart'; import 'package:mohem_flutter_app/models/marathon/marathon_model.dart'; @@ -99,8 +100,7 @@ class MarathonProvider extends ChangeNotifier { late VideoPlayerController videoController; Future initializeVideoPlayer() async { - // videoController = VideoPlayerController.network(marathonDetailModel.sponsors!.first.video!)..initialize(); - videoController = VideoPlayerController.network("http://clips.vorwaerts-gmbh.de/VfE_html5.mp4"); + videoController = VideoPlayerController.network(ApiConsts.marathonBaseUrlServices + marathonDetailModel.sponsors!.first.video!); await videoController.initialize(); await videoController.play(); await videoController.setVolume(1.0); @@ -187,7 +187,7 @@ class MarathonProvider extends ChangeNotifier { if (totalCurrentQuestionTime == 0) { updateCardData(); - if (currentQuestionNumber == marathonDetailModel.totalQuestions! ) { + if (currentQuestionNumber == marathonDetailModel.totalQuestions!) { callGetQualifiersApi(); updateQuestionCardStatus(QuestionCardStatus.findingWinner); timer.cancel(); diff --git a/lib/ui/marathon/marathon_screen.dart b/lib/ui/marathon/marathon_screen.dart index 71ae3d6..67d6f4e 100644 --- a/lib/ui/marathon/marathon_screen.dart +++ b/lib/ui/marathon/marathon_screen.dart @@ -6,6 +6,7 @@ import 'package:flutter_svg/svg.dart'; import 'package:lottie/lottie.dart'; import 'package:mohem_flutter_app/app_state/app_state.dart'; import 'package:mohem_flutter_app/classes/colors.dart'; +import 'package:mohem_flutter_app/classes/consts.dart'; import 'package:mohem_flutter_app/classes/decorations_helper.dart'; import 'package:mohem_flutter_app/classes/lottie_consts.dart'; import 'package:mohem_flutter_app/config/routes.dart'; @@ -43,24 +44,13 @@ class MarathonScreen extends StatelessWidget { return Image.asset(MyLottieConsts.congratsGif, height: 200); } - // SizedBox( - // height: 200, - // child: Stack( - // fit: StackFit.expand, - // children: [ - // Lottie.asset(MyLottieConsts.celebrate1Lottie, height: 200), - // // Lottie.asset(MyLottieConsts.celebrate2Lottie, height: 200), - // ], - // ), - // ), - Widget getWinnerWidget(BuildContext context, {required MarathonProvider provider}) { return Container( width: double.infinity, decoration: MyDecorations.shadowDecoration, padding: const EdgeInsets.symmetric(vertical: 20, horizontal: 20), child: Stack( - children: [ + children: [ Column( mainAxisAlignment: MainAxisAlignment.center, children: [ @@ -80,7 +70,7 @@ class MarathonScreen extends StatelessWidget { ), ), 16.height, - !provider.iAmWinner + provider.iAmWinner ? Column( children: [ (AppState().isArabic(context) ? AppState().memberInformationList!.eMPLOYEEDISPLAYNAMEAr : AppState().memberInformationList!.eMPLOYEEDISPLAYNAMEEn)!.toText22( @@ -103,7 +93,7 @@ class MarathonScreen extends StatelessWidget { itemBuilder: (BuildContext context, int index) { return Column( crossAxisAlignment: CrossAxisAlignment.start, - children: [ + children: [ (AppState().isArabic(context) ? provider.selectedWinners![index].nameEn : provider.selectedWinners![index].nameEn)!.toText16( color: MyColors.grey3AColor, ), @@ -127,10 +117,10 @@ class MarathonScreen extends StatelessWidget { ), 5.height, Image.network( - provider.marathonDetailModel.sponsors!.first.image!, - height: 40, + ApiConsts.marathonBaseUrlServices + provider.marathonDetailModel.sponsors!.first.image!, + height: 50, width: 150, - fit: BoxFit.fill, + fit: BoxFit.contain, errorBuilder: (BuildContext context, Object exception, StackTrace? stackTrace) { return const Center(); }, diff --git a/lib/ui/marathon/marathon_sponsor_video_screen.dart b/lib/ui/marathon/marathon_sponsor_video_screen.dart index 12d5949..88c66f9 100644 --- a/lib/ui/marathon/marathon_sponsor_video_screen.dart +++ b/lib/ui/marathon/marathon_sponsor_video_screen.dart @@ -15,9 +15,6 @@ import 'package:video_player/video_player.dart'; class SponsorVideoScreen extends StatelessWidget { const SponsorVideoScreen({Key? key}) : super(key: key); - Future onSponsorVideoClosed(BuildContext context) async { - Navigator.pop(context); - } @override Widget build(BuildContext context) { diff --git a/lib/ui/marathon/widgets/marathon_details_card.dart b/lib/ui/marathon/widgets/marathon_details_card.dart index b74b78b..e8b37a0 100644 --- a/lib/ui/marathon/widgets/marathon_details_card.dart +++ b/lib/ui/marathon/widgets/marathon_details_card.dart @@ -1,16 +1,14 @@ - import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:mohem_flutter_app/app_state/app_state.dart'; import 'package:mohem_flutter_app/classes/colors.dart'; +import 'package:mohem_flutter_app/classes/consts.dart'; import 'package:mohem_flutter_app/classes/decorations_helper.dart'; import 'package:mohem_flutter_app/extensions/int_extensions.dart'; import 'package:mohem_flutter_app/extensions/string_extensions.dart'; import 'package:mohem_flutter_app/generated/locale_keys.g.dart'; import 'package:mohem_flutter_app/ui/marathon/marathon_provider.dart'; - - class MarathonDetailsCard extends StatelessWidget { final MarathonProvider provider; @@ -38,16 +36,16 @@ class MarathonDetailsCard extends StatelessWidget { ) ], ), - if (provider.itsMarathonTime && provider.marathonDetailModel.sponsors != null) ...[ + if (provider.marathonDetailModel.sponsors != null) ...[ 5.height, provider.marathonDetailModel.sponsors?.first.sponsorPrizes != null ? Row( - children: [ - "${LocaleKeys.prize.tr()} ".toText16(color: MyColors.grey77Color, isBold: true), - "${AppState().isArabic(context) ? provider.marathonDetailModel.sponsors?.first.sponsorPrizes?.first.marathonPrizeAr : provider.marathonDetailModel.sponsors?.first.sponsorPrizes?.first.marathonPrizeAr}" - .toText16(color: MyColors.greenColor, isBold: true), - ], - ) + children: [ + "${LocaleKeys.prize.tr()} ".toText16(color: MyColors.grey77Color, isBold: true), + "${AppState().isArabic(context) ? provider.marathonDetailModel.sponsors?.first.sponsorPrizes?.first.marathonPrizeAr : provider.marathonDetailModel.sponsors?.first.sponsorPrizes?.first.marathonPrizeAr}" + .toText16(color: MyColors.greenColor, isBold: true), + ], + ) : const SizedBox(), Row( children: [ @@ -61,10 +59,10 @@ class MarathonDetailsCard extends StatelessWidget { mainAxisAlignment: MainAxisAlignment.center, children: [ Image.network( - provider.marathonDetailModel.sponsors!.first.image!, - height: 40, + ApiConsts.marathonBaseUrlServices + provider.marathonDetailModel.sponsors!.first.image!, + height: 50, width: 150, - fit: BoxFit.fill, + fit: BoxFit.contain, errorBuilder: (BuildContext context, Object exception, StackTrace? stackTrace) { return const Center(); }, @@ -79,4 +77,3 @@ class MarathonDetailsCard extends StatelessWidget { ); } } - From 7b6e2547d7440387c597236bc2acb91cb239445d Mon Sep 17 00:00:00 2001 From: Sultan khan <> Date: Tue, 13 Dec 2022 16:36:27 +0300 Subject: [PATCH 19/42] comp-off issue fixed --- .../dynamic_screens/dynamic_input_screen.dart | 36 +++++++++++-------- 1 file changed, 21 insertions(+), 15 deletions(-) diff --git a/lib/ui/my_attendance/dynamic_screens/dynamic_input_screen.dart b/lib/ui/my_attendance/dynamic_screens/dynamic_input_screen.dart index 62cafbd..e84a9a8 100644 --- a/lib/ui/my_attendance/dynamic_screens/dynamic_input_screen.dart +++ b/lib/ui/my_attendance/dynamic_screens/dynamic_input_screen.dart @@ -110,9 +110,9 @@ class _DynamicInputScreenState extends State { String dESCFLEXCONTEXTCODE = ""; String descFlexConTextTitle = ""; - Future calGetValueSetValues(GetEITDFFStructureList structureList) async { + Future calGetValueSetValues(GetEITDFFStructureList structureList, {bool showLoading = true}) async { try { - Utils.showLoading(context); + if (showLoading) Utils.showLoading(context); for (int i = 0; i < (structureList.cHILDSEGMENTSVSSplited?.length ?? 0); i++) { List> values = []; String segmentId = structureList.cHILDSEGMENTSVSSplited![i]; @@ -140,18 +140,21 @@ class _DynamicInputScreenState extends State { // getEitDffStructureList = genericResponseModel?.getEITDFFStructureList ?? []; //getEitDffStructureList = getEitDffStructureList!.where((element) => element.dISPLAYFLAG != "N").toList(); } - await Future.delayed(const Duration(seconds: 1)); - Utils.hideLoading(context); + if (showLoading) { + await Future.delayed(const Duration(seconds: 1)); + Utils.hideLoading(context); + } + setState(() {}); } catch (ex) { - Utils.hideLoading(context); + if (showLoading) Utils.hideLoading(context); Utils.handleException(ex, context, null); } } - Future getDefaultValues(GetEITDFFStructureList structureList) async { + Future getDefaultValues(GetEITDFFStructureList structureList, {bool showLoading = true}) async { try { - Utils.showLoading(context); + if (showLoading) Utils.showLoading(context); for (int i = 0; i < (structureList.cHILDSEGMENTSDVSplited?.length ?? 0); i++) { String segmentId = structureList.cHILDSEGMENTSDVSplited![i]; GetEITDFFStructureList? parent = getEitDffStructureList!.firstWhere((element) => element.sEGMENTNAME == segmentId); @@ -176,8 +179,7 @@ class _DynamicInputScreenState extends State { GetEITDFFStructureList defaultValueCheck = getEitDffStructureList!.where((GetEITDFFStructureList element) => element.sEGMENTNAME == segmentId).toList().first; if (defaultValueCheck.cHILDSEGMENTSDVSplited!.isNotEmpty && defaultValueCheck.rEADONLY == 'Y') { - getDefaultValues(defaultValueCheck); - Utils.hideLoading(context); + await getDefaultValues(defaultValueCheck, showLoading: false); // GetEITDFFStructureList? parent = getEitDffStructureList!.firstWhere((element) => element.sEGMENTNAME == segmentId); // List> getSetList = getDefaultValuesIonicLogic(parent); @@ -185,19 +187,23 @@ class _DynamicInputScreenState extends State { // int index = getEitDffStructureList!.indexWhere((element) => element.sEGMENTNAME == segmentId); // getEitDffStructureList![index].eSERVICESDV = defaultValue; } else if (defaultValueCheck.cHILDSEGMENTSVSSplited!.isNotEmpty && defaultValueCheck.rEADONLY == 'Y') { - calGetValueSetValues(defaultValueCheck); - Utils.hideLoading(context); + await calGetValueSetValues(defaultValueCheck, showLoading: false); + // Utils.hideLoading(context); } } else if (values.isNotEmpty) { ESERVICESDV defaultValue = await MyAttendanceApiClient().getDefaultValue(segmentId, structureList.dESCFLEXCONTEXTCODE!, structureList.dESCFLEXNAME!, values); int index = getEitDffStructureList!.indexWhere((element) => element.sEGMENTNAME == segmentId); + getEitDffStructureList![index].eSERVICESDV = defaultValue; } } - await Future.delayed(const Duration(seconds: 1)); - Utils.hideLoading(context); + if (showLoading) { + await Future.delayed(const Duration(seconds: 1)); + Utils.hideLoading(context); + } + setState(() {}); } catch (ex) { - Utils.hideLoading(context); + if (showLoading) Utils.hideLoading(context); Utils.handleException(ex, context, null); } } @@ -331,7 +337,7 @@ class _DynamicInputScreenState extends State { idColName = val; if (getEitDffStructureList![j].fORMATTYPE == "X") { - idColName = Utils.formatDateNew(idColName!); + idColName = Utils.formatDateDefault(idColName!); // commenting to test // DateTime date = DateFormat('yyyy-MM-dd').parse(idColName!); // idColName = DateFormat('yyyy-MM-dd HH:mm:ss').format(date); From 9f91f1e83c2294fdec5ad566e9cadc3a8bb0c86c Mon Sep 17 00:00:00 2001 From: "Aamir.Muhammad" Date: Wed, 14 Dec 2022 09:59:41 +0300 Subject: [PATCH 20/42] Chat Fixes --- lib/provider/chat_provider_model.dart | 7 +++- lib/ui/chat/chat_bubble.dart | 60 ++++++++++++++++++--------- 2 files changed, 45 insertions(+), 22 deletions(-) diff --git a/lib/provider/chat_provider_model.dart b/lib/provider/chat_provider_model.dart index 67899c5..3f76a86 100644 --- a/lib/provider/chat_provider_model.dart +++ b/lib/provider/chat_provider_model.dart @@ -371,7 +371,11 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { } } setMsgTune(); - userChatHistory.insert(0, data.first); + if (isChatScreenActive) { + if (data.first.targetUserId == AppState().chatDetails!.response!.id) { + userChatHistory.insert(0, data.first); + } + } if (searchedChats != null && !isChatScreenActive) { for (ChatUser user in searchedChats!) { @@ -868,7 +872,6 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { void onNewChatConversion(List? params) { dynamic items = params!.toList(); - logger.d(items); chatUConvCounter = items[0]["singleChatCount"] ?? 0; notifyListeners(); } diff --git a/lib/ui/chat/chat_bubble.dart b/lib/ui/chat/chat_bubble.dart index c79c66b..03a41e4 100644 --- a/lib/ui/chat/chat_bubble.dart +++ b/lib/ui/chat/chat_bubble.dart @@ -101,15 +101,22 @@ class ChatBubble extends StatelessWidget { ], ), ), - ).paddingOnly(right: 5, bottom: 7), + ).paddingOnly(bottom: 7), if (fileTypeID == 12 || fileTypeID == 4 || fileTypeID == 3) - showImage(isReplyPreview: false, fileName: cItem.contant!, fileTypeDescription: cItem.fileTypeResponse!.fileTypeDescription).paddingOnly(right: 5).onPress(() { - showDialog( - context: context, - anchorPoint: screenOffset, - builder: (BuildContext context) => ChatImagePreviewScreen(imgTitle: cItem.contant!, img: cItem.image!), - ); - }) + ClipRRect( + borderRadius: BorderRadius.circular(5.0), + child: SizedBox( + height: 140, + width: 227, + child: showImage(isReplyPreview: false, fileName: cItem.contant!, fileTypeDescription: cItem.fileTypeResponse!.fileTypeDescription).onPress(() { + showDialog( + context: context, + anchorPoint: screenOffset, + builder: (BuildContext context) => ChatImagePreviewScreen(imgTitle: cItem.contant!, img: cItem.image!), + ); + }), + ), + ).paddingOnly(bottom: 4) else Row( children: [ @@ -132,12 +139,12 @@ class ChatBubble extends StatelessWidget { ), ), ], - ).paddingOnly(top: 11, left: 13, right: 7, bottom: 5).objectContainerView(disablePadding: true).paddingOnly(left: MediaQuery.of(context).size.width * 0.3); + ).paddingOnly(top: 11, left: 13, right: 13, bottom: 5).objectContainerView(disablePadding: true).paddingOnly(left: MediaQuery.of(context).size.width * 0.3); } Widget receiptUser(BuildContext context) { return Container( - padding: const EdgeInsets.only(top: 11, left: 13, right: 7, bottom: 5), + padding: const EdgeInsets.only(top: 11, left: 13, right: 13, bottom: 5), decoration: BoxDecoration( borderRadius: BorderRadius.circular(10), gradient: const LinearGradient( @@ -190,15 +197,22 @@ class ChatBubble extends StatelessWidget { ], ), ), - ).paddingOnly(right: 5, bottom: 7), + ).paddingOnly(bottom: 7), if (fileTypeID == 12 || fileTypeID == 4 || fileTypeID == 3) - showImage(isReplyPreview: false, fileName: cItem.contant ?? "", fileTypeDescription: cItem.fileTypeResponse!.fileTypeDescription ?? "image/jpg").paddingOnly(right: 5).onPress(() { - showDialog( - context: context, - anchorPoint: screenOffset, - builder: (BuildContext context) => ChatImagePreviewScreen(imgTitle: cItem.contant ?? "", img: cItem.image!), - ); - }) + ClipRRect( + borderRadius: BorderRadius.circular(5.0), + child: SizedBox( + height: 140, + width: 227, + child: showImage(isReplyPreview: false, fileName: cItem.contant ?? "", fileTypeDescription: cItem.fileTypeResponse!.fileTypeDescription ?? "image/jpg").onPress(() { + showDialog( + context: context, + anchorPoint: screenOffset, + builder: (BuildContext context) => ChatImagePreviewScreen(imgTitle: cItem.contant ?? "", img: cItem.image!), + ); + }), + ), + ).paddingOnly(bottom: 4) else Row( children: [ @@ -212,7 +226,9 @@ class ChatBubble extends StatelessWidget { ), Align( alignment: Alignment.centerRight, - child: dateTime.toText10(color: Colors.white.withOpacity(.71),), + child: dateTime.toText10( + color: Colors.white.withOpacity(.71), + ), ), ], ), @@ -220,12 +236,15 @@ class ChatBubble extends StatelessWidget { } Widget showImage({required bool isReplyPreview, required String fileName, required String fileTypeDescription}) { + if (isReplyPreview) {} + if (cItem.isImageLoaded! && cItem.image != null) { return Image.memory( cItem.image!, height: isReplyPreview ? 32 : 140, width: isReplyPreview ? 32 : 227, fit: BoxFit.cover, + alignment: Alignment.center, ); } else { return FutureBuilder( @@ -233,7 +252,7 @@ class ChatBubble extends StatelessWidget { builder: (BuildContext context, AsyncSnapshot snapshot) { if (snapshot.connectionState != ConnectionState.waiting) { if (snapshot.data == null) { - return SizedBox(); + return const SizedBox(); } else { cItem.image = snapshot.data; cItem.isImageLoaded = true; @@ -242,6 +261,7 @@ class ChatBubble extends StatelessWidget { height: isReplyPreview ? 32 : 140, width: isReplyPreview ? 32 : 227, fit: BoxFit.cover, + alignment: Alignment.center, ); } } else { From 2266ace39a6f5331b137253557eca257a9e56847 Mon Sep 17 00:00:00 2001 From: "Aamir.Muhammad" Date: Wed, 14 Dec 2022 10:23:21 +0300 Subject: [PATCH 21/42] Chat Fixes & Call Button Disabled --- lib/api/chat/chat_api_client.dart | 30 --------------------------- lib/provider/chat_provider_model.dart | 11 +++++----- lib/ui/chat/chat_detailed_screen.dart | 16 +++++++------- 3 files changed, 14 insertions(+), 43 deletions(-) diff --git a/lib/api/chat/chat_api_client.dart b/lib/api/chat/chat_api_client.dart index 3ef8fba..35e4f79 100644 --- a/lib/api/chat/chat_api_client.dart +++ b/lib/api/chat/chat_api_client.dart @@ -60,17 +60,6 @@ class ChatApiClient { json.decode(response.body), ); } catch (e) { - // if (e.message == "api_common_unauthorized") { - // user.UserAutoLoginModel userLoginResponse = await ChatApiClient().getUserLoginToken(); - // if (userLoginResponse.response != null) { - // AppState().setchatUserDetails = userLoginResponse; - // getRecentChats(); - // } else { - // Utils.showToast( - // userLoginResponse.errorResponses!.first.fieldName.toString() + " Erorr", - // ); - // } - // } throw e; } } @@ -97,16 +86,6 @@ class ChatApiClient { } return response; } catch (e) { - // e as APIException; - // if (e.message == "api_common_unauthorized") { - // user.UserAutoLoginModel userLoginResponse = await ChatApiClient().getUserLoginToken(); - // if (userLoginResponse.response != null) { - // AppState().setchatUserDetails = userLoginResponse; - // getSingleUserChatHistory(senderUID: senderUID, receiverUID: receiverUID, loadMore: loadMore, paginationVal: paginationVal); - // } else { - // Utils.showToast(userLoginResponse.errorResponses!.first.fieldName.toString() + " Erorr"); - // } - // } throw e; } } @@ -135,15 +114,6 @@ class ChatApiClient { return favoriteChatUser; } catch (e) { e as APIException; - // if (e.message == "api_common_unauthorized") { - // user.UserAutoLoginModel userLoginResponse = await ChatApiClient().getUserLoginToken(); - // if (userLoginResponse.response != null) { - // AppState().setchatUserDetails = userLoginResponse; - // unFavUser(userID: userID, targetUserID: targetUserID); - // } else { - // Utils.showToast(userLoginResponse.errorResponses!.first.fieldName.toString() + " Erorr"); - // } - // } throw e; } } diff --git a/lib/provider/chat_provider_model.dart b/lib/provider/chat_provider_model.dart index 3f76a86..fbcb801 100644 --- a/lib/provider/chat_provider_model.dart +++ b/lib/provider/chat_provider_model.dart @@ -36,6 +36,8 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { String chatCID = ''; bool isLoading = true; bool isChatScreenActive = false; + int ReceiverID = 0; + late File selectedFile; bool isFileSelected = false; String sFileType = ""; @@ -142,6 +144,7 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { if (isNewChat) userChatHistory = []; if (!loadMore) paginationVal = 0; isChatScreenActive = true; + ReceiverID = receiverUID; Response response = await ChatApiClient().getSingleUserChatHistory(senderUID: senderUID, receiverUID: receiverUID, loadMore: loadMore, paginationVal: paginationVal); if (response.statusCode == 204) { if (isNewChat) { @@ -371,13 +374,11 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { } } setMsgTune(); - if (isChatScreenActive) { - if (data.first.targetUserId == AppState().chatDetails!.response!.id) { - userChatHistory.insert(0, data.first); - } + if (isChatScreenActive && data.first.currentUserId == ReceiverID) { + userChatHistory.insert(0, data.first); } - if (searchedChats != null && !isChatScreenActive) { + if (searchedChats != null) { for (ChatUser user in searchedChats!) { if (user.id == data.first.currentUserId) { int tempCount = user.unreadMessageCount ?? 0; diff --git a/lib/ui/chat/chat_detailed_screen.dart b/lib/ui/chat/chat_detailed_screen.dart index be685df..5cad3fa 100644 --- a/lib/ui/chat/chat_detailed_screen.dart +++ b/lib/ui/chat/chat_detailed_screen.dart @@ -85,14 +85,14 @@ class _ChatDetailScreenState extends State { showTyping: true, chatUser: params!.chatUser, actions: [ - SvgPicture.asset("assets/icons/chat/call.svg", width: 21, height: 23).onPress(() { - // makeCall(callType: "AUDIO", con: hubConnection); - }), - 24.width, - SvgPicture.asset("assets/icons/chat/video_call.svg", width: 21, height: 18).onPress(() { - // makeCall(callType: "VIDEO", con: hubConnection); - }), - 21.width, + // SvgPicture.asset("assets/icons/chat/call.svg", width: 21, height: 23).onPress(() { + // // makeCall(callType: "AUDIO", con: hubConnection); + // }), + // 24.width, + // SvgPicture.asset("assets/icons/chat/video_call.svg", width: 21, height: 18).onPress(() { + // // makeCall(callType: "VIDEO", con: hubConnection); + // }), + // 21.width, ], ), body: SafeArea( From cb4b95ddb45856083e47df39717902fa9b78ca05 Mon Sep 17 00:00:00 2001 From: "Aamir.Muhammad" Date: Wed, 14 Dec 2022 10:47:33 +0300 Subject: [PATCH 22/42] Read Issue On Sub Page --- lib/provider/chat_provider_model.dart | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/lib/provider/chat_provider_model.dart b/lib/provider/chat_provider_model.dart index fbcb801..876737f 100644 --- a/lib/provider/chat_provider_model.dart +++ b/lib/provider/chat_provider_model.dart @@ -36,7 +36,7 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { String chatCID = ''; bool isLoading = true; bool isChatScreenActive = false; - int ReceiverID = 0; + int receiverID = 0; late File selectedFile; bool isFileSelected = false; @@ -144,7 +144,7 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { if (isNewChat) userChatHistory = []; if (!loadMore) paginationVal = 0; isChatScreenActive = true; - ReceiverID = receiverUID; + receiverID = receiverUID; Response response = await ChatApiClient().getSingleUserChatHistory(senderUID: senderUID, receiverUID: receiverUID, loadMore: loadMore, paginationVal: paginationVal); if (response.statusCode == 204) { if (isNewChat) { @@ -163,7 +163,9 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { isLoading = false; notifyListeners(); - markRead(userChatHistory, receiverUID); + if (isChatScreenActive && receiverUID == receiverID) { + markRead(userChatHistory, receiverUID); + } generateConvId(); } @@ -374,7 +376,7 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { } } setMsgTune(); - if (isChatScreenActive && data.first.currentUserId == ReceiverID) { + if (isChatScreenActive && data.first.currentUserId == receiverID) { userChatHistory.insert(0, data.first); } @@ -389,7 +391,7 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { } List list = [ - {"userChatHistoryId": data.first.userChatHistoryId, "TargetUserId": temp.first.targetUserId, "isDelivered": true, "isSeen": isChatScreenActive ? true : false} + {"userChatHistoryId": data.first.userChatHistoryId, "TargetUserId": temp.first.targetUserId, "isDelivered": true, "isSeen": isChatScreenActive && data.first.currentUserId == receiverID ? true : false} ]; updateUserChatHistoryOnMsg(list); invokeChatCounter(userId: AppState().chatDetails!.response!.id!); @@ -751,6 +753,7 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { searchedChats = pChatHistory; search.clear(); isChatScreenActive = false; + receiverID = 0; paginationVal = 0; message.text = ''; isFileSelected = false; @@ -764,6 +767,7 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { searchedChats = pChatHistory; search.clear(); isChatScreenActive = false; + receiverID = 0; paginationVal = 0; message.text = ''; isFileSelected = false; From 631752cffae12484d13e517506783f2ff5c50f18 Mon Sep 17 00:00:00 2001 From: haroon amjad Date: Wed, 14 Dec 2022 11:33:28 +0300 Subject: [PATCH 23/42] fixes --- lib/classes/utils.dart | 9 ++++++--- lib/ui/landing/dashboard_screen.dart | 2 +- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/lib/classes/utils.dart b/lib/classes/utils.dart index fbdc6ce..57bb888 100644 --- a/lib/classes/utils.dart +++ b/lib/classes/utils.dart @@ -9,7 +9,6 @@ import 'package:flutter_svg/flutter_svg.dart'; import 'package:fluttertoast/fluttertoast.dart'; import 'package:mohem_flutter_app/app_state/app_state.dart'; import 'package:mohem_flutter_app/classes/colors.dart'; -import 'package:mohem_flutter_app/classes/date_uitl.dart'; import 'package:mohem_flutter_app/config/routes.dart'; import 'package:mohem_flutter_app/exceptions/api_exception.dart'; import 'package:mohem_flutter_app/extensions/int_extensions.dart'; @@ -66,6 +65,7 @@ class Utils { showDialog( context: context, barrierColor: Colors.black.withOpacity(0.5), + useRootNavigator: false, builder: (BuildContext context) => LoadingDialog(), ).then((value) { _isLoadingVisible = false; @@ -121,8 +121,11 @@ class Utils { ), ); } else { - showToast(errorMessage); - // confirmDialog(cxt, errorMessage); + if (cxt != null) { + confirmDialog(cxt, errorMessage); + } else { + showToast(errorMessage); + } } } } diff --git a/lib/ui/landing/dashboard_screen.dart b/lib/ui/landing/dashboard_screen.dart index b1dac53..22768e6 100644 --- a/lib/ui/landing/dashboard_screen.dart +++ b/lib/ui/landing/dashboard_screen.dart @@ -200,7 +200,7 @@ class _DashboardScreenState extends State { Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - LocaleKeys.goodMorning.tr().toText14(color: MyColors.grey77Color), + LocaleKeys.welcomeBack.tr().toText14(color: MyColors.grey77Color), (AppState().memberInformationList!.eMPLOYEENAME ?? "").toText24(isBold: true), 16.height, Row( From 3b6f3f5c4ffcd52c1126207ed7879232b48bfa85 Mon Sep 17 00:00:00 2001 From: haroon amjad Date: Wed, 14 Dec 2022 12:52:37 +0300 Subject: [PATCH 24/42] Address info issue fixed --- lib/api/worklist/worklist_api_client.dart | 15 ++++++++ lib/models/generic_response_model.dart | 12 +++++- .../get_address_notification_body_list.dart | 28 ++++++++++++++ lib/ui/login/login_screen.dart | 6 +-- lib/ui/work_list/worklist_detail_screen.dart | 24 ++++++++++++ .../worklist_fragments/info_fragments.dart | 38 ++++++++++++++++++- .../dynamic_textfield_widget.dart | 6 +-- 7 files changed, 117 insertions(+), 12 deletions(-) create mode 100644 lib/models/worklist/hr/get_address_notification_body_list.dart diff --git a/lib/api/worklist/worklist_api_client.dart b/lib/api/worklist/worklist_api_client.dart index 75992e7..dcbb415 100644 --- a/lib/api/worklist/worklist_api_client.dart +++ b/lib/api/worklist/worklist_api_client.dart @@ -26,6 +26,7 @@ import 'package:mohem_flutter_app/models/update_user_item_type_list.dart'; import 'package:mohem_flutter_app/models/worklist/GetRFCEmployeeList.dart'; import 'package:mohem_flutter_app/models/worklist/get_favorite_replacements_model.dart'; import 'package:mohem_flutter_app/models/worklist/hr/eit_otification_body_model.dart'; +import 'package:mohem_flutter_app/models/worklist/hr/get_address_notification_body_list.dart'; import 'package:mohem_flutter_app/models/worklist/hr/get_basic_det_ntf_body_list_model.dart'; import 'package:mohem_flutter_app/models/worklist/hr/get_contact_notification_body_list_model.dart'; import 'package:mohem_flutter_app/models/worklist/hr/get_phones_notification_body_list_model.dart'; @@ -509,6 +510,20 @@ class WorkListApiClient { }, url, postParams); } + Future?> getAddressNotificationBodyList(int? notificationId) async { + String url = "${ApiConsts.erpRest}GET_ADDRESS_NOTIFICATION_BODY"; + Map postParams = { + "P_NOTIFICATION_ID": notificationId, + "P_PAGE_LIMIT": 100, + "P_PAGE_NUM": 1, + }; + postParams.addAll(AppState().postParamsJson); + return await ApiClient().postJsonForObject((json) { + GenericResponseModel responseData = GenericResponseModel.fromJson(json); + return responseData.getAddressNotificationBodyList; + }, url, postParams); + } + Future?> getFavoriteReplacementWithoutImage() async { String url = "${ApiConsts.erpRest}Mohemm_GetFavoriteReplacementsWithoutImage"; Map postParams = {}; diff --git a/lib/models/generic_response_model.dart b/lib/models/generic_response_model.dart index cd7043c..ed00de4 100644 --- a/lib/models/generic_response_model.dart +++ b/lib/models/generic_response_model.dart @@ -102,6 +102,7 @@ import 'package:mohem_flutter_app/models/validate_eit_transaction_list_model.dar import 'package:mohem_flutter_app/models/worklist/GetRFCEmployeeList.dart'; import 'package:mohem_flutter_app/models/worklist/get_favorite_replacements_model.dart'; import 'package:mohem_flutter_app/models/worklist/hr/eit_otification_body_model.dart'; +import 'package:mohem_flutter_app/models/worklist/hr/get_address_notification_body_list.dart'; import 'package:mohem_flutter_app/models/worklist/hr/get_basic_det_ntf_body_list_model.dart'; import 'package:mohem_flutter_app/models/worklist/hr/get_contact_notification_body_list_model.dart'; import 'package:mohem_flutter_app/models/worklist/hr/get_phones_notification_body_list_model.dart'; @@ -163,12 +164,12 @@ class GenericResponseModel { List? getAbsenceAttachmentsList; List? getAbsenceAttendanceTypesList; List? getAbsenceCollectionNotificationBodyList; + List? getAddressNotificationBodyList; List? getAbsenceDffStructureList; List? getAbsenceTransactionList; List? getAccrualBalancesList; List? getActionHistoryList; List? getAddressDffStructureList; - List? getAddressNotificationBodyList; List? getApprovesList; List? getAttachementList; GetAttendanceTracking? getAttendanceTrackingList; @@ -717,6 +718,13 @@ class GenericResponseModel { }); } + if (json['GetAddressNotificationBodyList'] != null) { + getAddressNotificationBodyList = []; + json['GetAddressNotificationBodyList'].forEach((v) { + getAddressNotificationBodyList!.add(GetAddressNotificationBodyList.fromJson(v)); + }); + } + if (json['GetAbsenceDffStructureList'] != null) { getAbsenceDffStructureList = []; json['GetAbsenceDffStructureList'].forEach((v) { @@ -746,7 +754,7 @@ class GenericResponseModel { getAddressDffStructureList!.add(GetAddressDffStructureList.fromJson(v)); }); } - getAddressNotificationBodyList = json['GetAddressNotificationBodyList']; + // getAddressNotificationBodyList = json['GetAddressNotificationBodyList']; if (json['GetApprovesList'] != null) { getApprovesList = []; diff --git a/lib/models/worklist/hr/get_address_notification_body_list.dart b/lib/models/worklist/hr/get_address_notification_body_list.dart new file mode 100644 index 0000000..28ee516 --- /dev/null +++ b/lib/models/worklist/hr/get_address_notification_body_list.dart @@ -0,0 +1,28 @@ +class GetAddressNotificationBodyList { + String? pREVSEGMENTVALUEDSP; + String? sEGMENTPROMPT; + String? sEGMENTVALUEDSP; + String? uPDATEDFLAG; + + GetAddressNotificationBodyList( + {this.pREVSEGMENTVALUEDSP, + this.sEGMENTPROMPT, + this.sEGMENTVALUEDSP, + this.uPDATEDFLAG}); + + GetAddressNotificationBodyList.fromJson(Map json) { + pREVSEGMENTVALUEDSP = json['PREV_SEGMENT_VALUE_DSP']; + sEGMENTPROMPT = json['SEGMENT_PROMPT']; + sEGMENTVALUEDSP = json['SEGMENT_VALUE_DSP']; + uPDATEDFLAG = json['UPDATED_FLAG']; + } + + Map toJson() { + Map data = new Map(); + data['PREV_SEGMENT_VALUE_DSP'] = this.pREVSEGMENTVALUEDSP; + data['SEGMENT_PROMPT'] = this.sEGMENTPROMPT; + data['SEGMENT_VALUE_DSP'] = this.sEGMENTVALUEDSP; + data['UPDATED_FLAG'] = this.uPDATEDFLAG; + return data; + } +} diff --git a/lib/ui/login/login_screen.dart b/lib/ui/login/login_screen.dart index a0ab3c9..04c3077 100644 --- a/lib/ui/login/login_screen.dart +++ b/lib/ui/login/login_screen.dart @@ -58,9 +58,9 @@ class _LoginScreenState extends State { void initState() { super.initState(); // checkFirebaseToken(); - if (kReleaseMode) { - checkDeviceSafety(); - } + // if (kReleaseMode) { + // checkDeviceSafety(); + // } } void checkDeviceSafety() async { diff --git a/lib/ui/work_list/worklist_detail_screen.dart b/lib/ui/work_list/worklist_detail_screen.dart index b5129a5..8ec8d00 100644 --- a/lib/ui/work_list/worklist_detail_screen.dart +++ b/lib/ui/work_list/worklist_detail_screen.dart @@ -25,6 +25,7 @@ import 'package:mohem_flutter_app/models/member_information_list_model.dart'; import 'package:mohem_flutter_app/models/notification_get_respond_attributes_list_model.dart'; import 'package:mohem_flutter_app/models/worklist/GetRFCEmployeeList.dart'; import 'package:mohem_flutter_app/models/worklist/hr/eit_otification_body_model.dart'; +import 'package:mohem_flutter_app/models/worklist/hr/get_address_notification_body_list.dart'; import 'package:mohem_flutter_app/models/worklist/hr/get_basic_det_ntf_body_list_model.dart'; import 'package:mohem_flutter_app/models/worklist/hr/get_contact_notification_body_list_model.dart'; import 'package:mohem_flutter_app/models/worklist/hr/get_phones_notification_body_list_model.dart'; @@ -78,6 +79,8 @@ class _WorkListDetailScreenState extends State { List? getBasicDetNtfBodyList = []; List? getAbsenceCollectionNotificationBodyList = []; GetContactNotificationBodyList? getContactNotificationBodyList; + List? getAddressNotificationBodyList = []; + GenericResponseModel? getBasicNTFBody; GenericResponseModel? getICBody; @@ -118,6 +121,7 @@ class _WorkListDetailScreenState extends State { getBasicDetNtfBodyList!.clear(); getAbsenceCollectionNotificationBodyList!.clear(); getContactNotificationBodyList = null; + getAddressNotificationBodyList!.clear(); if (workListData!.iTEMTYPE == "HRSSA" || workListData!.iTEMTYPE == "STAMP") { getUserInformation(); @@ -139,6 +143,8 @@ class _WorkListDetailScreenState extends State { getAbsenceNotificationBody(); } else if (workListData!.rEQUESTTYPE == "CONTACT") { getContactNotificationBody(); + } else if (workListData!.rEQUESTTYPE == "ADDRESS") { + getAddressNotificationBody(); } // getBasicNTFBody = await WorkListApiClient().getBasicDetNTFBody(workListData!.nOTIFICATIONID!, -999); // getAbsenceCollectionNotifications = await WorkListApiClient().getAbsenceNotificationBody(workListData!.nOTIFICATIONID!, -999); @@ -271,6 +277,7 @@ class _WorkListDetailScreenState extends State { getEitCollectionNotificationBodyList: getEitCollectionNotificationBodyList, getPhonesNotificationBodyList: getPhonesNotificationBodyList, getBasicDetNtfBodyList: getBasicDetNtfBodyList, + getAddressNotificationBodyList: getAddressNotificationBodyList, getAbsenceCollectionNotificationBodyList: getAbsenceCollectionNotificationBodyList, getContactNotificationBodyList: getContactNotificationBodyList, getPrNotificationBodyList: getPrNotificationBody, @@ -841,6 +848,23 @@ class _WorkListDetailScreenState extends State { } } + void getAddressNotificationBody() async { + try { + if (apiCallCount == 0) Utils.showLoading(context); + apiCallCount++; + getAddressNotificationBodyList = await WorkListApiClient().getAddressNotificationBodyList(workListData!.nOTIFICATIONID); + apiCallCount--; + if (apiCallCount == 0) { + Utils.hideLoading(context); + setState(() {}); + } + } catch (ex) { + apiCallCount--; + Utils.hideLoading(context); + Utils.handleException(ex, context, null); + } + } + void getStampNotificationBody() async { try { if (apiCallCount == 0) Utils.showLoading(context); diff --git a/lib/ui/work_list/worklist_fragments/info_fragments.dart b/lib/ui/work_list/worklist_fragments/info_fragments.dart index 7cf8aa9..bcde517 100644 --- a/lib/ui/work_list/worklist_fragments/info_fragments.dart +++ b/lib/ui/work_list/worklist_fragments/info_fragments.dart @@ -13,6 +13,7 @@ import 'package:mohem_flutter_app/models/get_pr_notification_body_list_model.dar import 'package:mohem_flutter_app/models/get_stamp_ms_notification_body_list_model.dart'; import 'package:mohem_flutter_app/models/get_stamp_ns_notification_body_list_model.dart'; import 'package:mohem_flutter_app/models/worklist/hr/eit_otification_body_model.dart'; +import 'package:mohem_flutter_app/models/worklist/hr/get_address_notification_body_list.dart'; import 'package:mohem_flutter_app/models/worklist/hr/get_basic_det_ntf_body_list_model.dart'; import 'package:mohem_flutter_app/models/worklist/hr/get_contact_notification_body_list_model.dart'; import 'package:mohem_flutter_app/models/worklist/hr/get_phones_notification_body_list_model.dart'; @@ -31,6 +32,7 @@ class InfoFragment extends StatelessWidget { List? getAbsenceCollectionNotificationBodyList; GetContactNotificationBodyList? getContactNotificationBodyList; GetPrNotificationBodyList? getPrNotificationBodyList; + List? getAddressNotificationBodyList = []; InfoFragment( {this.workListData, @@ -43,7 +45,8 @@ class InfoFragment extends StatelessWidget { this.getBasicDetNtfBodyList, this.getAbsenceCollectionNotificationBodyList, this.getContactNotificationBodyList, - this.getPrNotificationBodyList}); + this.getPrNotificationBodyList, + this.getAddressNotificationBodyList}); double itemHeight = 0; double itemWidth = 0; @@ -89,6 +92,7 @@ class InfoFragment extends StatelessWidget { if (getBasicDetNtfBodyList?.isNotEmpty ?? false) getBasicDetNtfBodyListWidget(getBasicDetNtfBodyList ?? []).objectContainerView(title: "Basic Information"), if (getAbsenceCollectionNotificationBodyList?.isNotEmpty ?? false) getAbsenceCollectionNotificationBodyListWidget(getAbsenceCollectionNotificationBodyList ?? []), if (getContactNotificationBodyList != null) getContactNotificationBodyListWidget(getContactNotificationBodyList ?? GetContactNotificationBodyList()).objectContainerView(), + if (getAddressNotificationBodyList?.isNotEmpty ?? false) getAddressNotificationBodyListWidget(getAddressNotificationBodyList!), ]; return Container( width: double.infinity, @@ -465,6 +469,36 @@ class InfoFragment extends StatelessWidget { ); } + Widget getAddressNotificationBodyListWidget(List getAddressNotificationBodyList) { + bool isOdd = false; + try { + if (getAddressNotificationBodyList.length % 2 != 0) { + isOdd = true; + getAddressNotificationBodyList.add(GetAddressNotificationBodyList(sEGMENTPROMPT: "--", sEGMENTVALUEDSP: "--")); + } + } catch (e) {} + + return GridView.builder( + itemCount: getAddressNotificationBodyList!.length, + shrinkWrap: true, + physics: const NeverScrollableScrollPhysics(), + itemBuilder: (context, index) => ItemDetailViewGridItem( + index, + getAddressNotificationBodyList[index].sEGMENTPROMPT, + getAddressNotificationBodyList[index].sEGMENTVALUEDSP, + isNeedToShowEmptyDivider: (getAddressNotificationBodyList.length == index + 1) + ? isOdd + ? true + : false + : false, + ), + gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( + crossAxisCount: 2, + childAspectRatio: (itemWidth / itemHeight), + ), + ).objectContainerView(); + } + List getPRHeaderValues() { List pRHeaders = []; getPrNotificationBodyList!.pRHeader!.forEach((element) { @@ -478,7 +512,7 @@ class InfoFragment extends StatelessWidget { try { if (data.contactNotificationBody!.length % 2 != 0) { isOdd = true; - data.contactNotificationBody!.add(new ContactNotificationBody()); + data.contactNotificationBody!.add(ContactNotificationBody(segmentPrompt: "--", segmentValueDsp: "--")); } } catch (e) {} diff --git a/lib/widgets/dynamic_forms/dynamic_textfield_widget.dart b/lib/widgets/dynamic_forms/dynamic_textfield_widget.dart index 299ef7a..ec4146b 100644 --- a/lib/widgets/dynamic_forms/dynamic_textfield_widget.dart +++ b/lib/widgets/dynamic_forms/dynamic_textfield_widget.dart @@ -68,11 +68,7 @@ class DynamicTextFieldWidget extends StatelessWidget { enabled: isEnable, scrollPadding: EdgeInsets.zero, readOnly: isReadOnly, - keyboardType: (isInputTypeNum) - ? isInputTypeNumSigned - ? const TextInputType.numberWithOptions(signed: true) - : TextInputType.number - : TextInputType.text, + keyboardType: (isInputTypeNum) ? (isInputTypeNumSigned ? const TextInputType.numberWithOptions(signed: true, decimal: true) : TextInputType.numberWithOptions(signed: true, decimal: true)) : TextInputType.text, textInputAction: TextInputAction.done, //controller: controller, maxLines: lines, From 3d4d5403a9b2703be968fece1fe8b6330715b792 Mon Sep 17 00:00:00 2001 From: "Aamir.Muhammad" Date: Thu, 15 Dec 2022 09:48:33 +0300 Subject: [PATCH 25/42] Multiple Chat Issue --- lib/provider/chat_provider_model.dart | 94 +++++++++++++++++---------- 1 file changed, 59 insertions(+), 35 deletions(-) diff --git a/lib/provider/chat_provider_model.dart b/lib/provider/chat_provider_model.dart index 876737f..6affc8a 100644 --- a/lib/provider/chat_provider_model.dart +++ b/lib/provider/chat_provider_model.dart @@ -291,14 +291,12 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { void chatNotDelivered(List? args) { dynamic items = args!.toList(); for (dynamic item in items[0]) { - searchedChats!.forEach( - (ChatUser element) { - if (element.id == item["currentUserId"]) { - int? val = element.unreadMessageCount ?? 0; - element.unreadMessageCount = val! + 1; - } - }, - ); + for (ChatUser element in searchedChats!) { + if (element.id == item["currentUserId"]) { + int? val = element.unreadMessageCount ?? 0; + element.unreadMessageCount = val! + 1; + } + } } notifyListeners(); } @@ -390,8 +388,13 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { sort(); } - List list = [ - {"userChatHistoryId": data.first.userChatHistoryId, "TargetUserId": temp.first.targetUserId, "isDelivered": true, "isSeen": isChatScreenActive && data.first.currentUserId == receiverID ? true : false} + List list = [ + { + "userChatHistoryId": data.first.userChatHistoryId, + "TargetUserId": temp.first.targetUserId, + "isDelivered": true, + "isSeen": isChatScreenActive && data.first.currentUserId == receiverID ? true : false + } ]; updateUserChatHistoryOnMsg(list); invokeChatCounter(userId: AppState().chatDetails!.response!.id!); @@ -400,9 +403,7 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { void sort() { searchedChats!.sort( - (ChatUser a, ChatUser b) => b.unreadMessageCount!.compareTo( - a.unreadMessageCount!, - ), + (ChatUser a, ChatUser b) => b.unreadMessageCount!.compareTo(a.unreadMessageCount!), ); } @@ -540,28 +541,6 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { } void sendChatMessage(BuildContext context, {required int targetUserId, required int userStatus, required String userEmail, required String targetUserName}) async { - dynamic contain = searchedChats!.where((ChatUser element) => element.id == targetUserId); - if (contain.isEmpty) { - List emails = []; - emails.add(await EmailImageEncryption().encrypt(val: userEmail)); - List chatImages = await ChatApiClient().getUsersImages(encryptedEmails: emails); - searchedChats!.add( - ChatUser( - id: targetUserId, - userName: targetUserName, - unreadMessageCount: 0, - email: userEmail, - isImageLoading: false, - image: chatImages.first.profilePicture ?? "", - isImageLoaded: true, - isTyping: false, - isFav: false, - userStatus: userStatus, - userLocalDownlaodedImage: await downloadImageLocal(chatImages.first.profilePicture, targetUserId.toString()), - ), - ); - notifyListeners(); - } if (!isFileSelected && !isMsgReply) { print("Normal Text Msg"); if (message.text == null || message.text.isEmpty) { @@ -621,6 +600,51 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { isImageLoaded: true, image: selectedFile.readAsBytesSync()); } + + if (searchedChats != null) { + dynamic contain = searchedChats!.where((ChatUser element) => element.id == targetUserId); + if (contain.isEmpty) { + List emails = []; + emails.add(await EmailImageEncryption().encrypt(val: userEmail)); + List chatImages = await ChatApiClient().getUsersImages(encryptedEmails: emails); + searchedChats!.add( + ChatUser( + id: targetUserId, + userName: targetUserName, + unreadMessageCount: 0, + email: userEmail, + isImageLoading: false, + image: chatImages.first.profilePicture ?? "", + isImageLoaded: true, + isTyping: false, + isFav: false, + userStatus: userStatus, + userLocalDownlaodedImage: await downloadImageLocal(chatImages.first.profilePicture, targetUserId.toString()), + ), + ); + notifyListeners(); + } + } else { + List emails = []; + emails.add(await EmailImageEncryption().encrypt(val: userEmail)); + List chatImages = await ChatApiClient().getUsersImages(encryptedEmails: emails); + searchedChats!.add( + ChatUser( + id: targetUserId, + userName: targetUserName, + unreadMessageCount: 0, + email: userEmail, + isImageLoading: false, + image: chatImages.first.profilePicture ?? "", + isImageLoaded: true, + isTyping: false, + isFav: false, + userStatus: userStatus, + userLocalDownlaodedImage: await downloadImageLocal(chatImages.first.profilePicture, targetUserId.toString()), + ), + ); + notifyListeners(); + } } void selectImageToUpload(BuildContext context) { From 08e0af8f64664b31df929b4e5dbe9f1d5dd26a75 Mon Sep 17 00:00:00 2001 From: "Aamir.Muhammad" Date: Thu, 15 Dec 2022 12:06:42 +0300 Subject: [PATCH 26/42] Chat Bug's Fix --- lib/provider/chat_provider_model.dart | 60 ++++++++++++++++++++++----- lib/ui/chat/chat_bubble.dart | 7 ++-- lib/ui/chat/chat_detailed_screen.dart | 3 ++ lib/ui/chat/chat_home.dart | 1 + lib/ui/landing/widget/app_drawer.dart | 9 ++++ 5 files changed, 66 insertions(+), 14 deletions(-) diff --git a/lib/provider/chat_provider_model.dart b/lib/provider/chat_provider_model.dart index 6affc8a..a62016f 100644 --- a/lib/provider/chat_provider_model.dart +++ b/lib/provider/chat_provider_model.dart @@ -48,7 +48,7 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { bool currentUserTyping = false; int? cTypingUserId = 0; - //Chat + //Chat Home Page Counter int chatUConvCounter = 0; Future getUserAutoLoginToken() async { @@ -376,16 +376,16 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { setMsgTune(); if (isChatScreenActive && data.first.currentUserId == receiverID) { userChatHistory.insert(0, data.first); - } - - if (searchedChats != null) { - for (ChatUser user in searchedChats!) { - if (user.id == data.first.currentUserId) { - int tempCount = user.unreadMessageCount ?? 0; - user.unreadMessageCount = tempCount + 1; + } else { + if (searchedChats != null) { + for (ChatUser user in searchedChats!) { + if (user.id == data.first.currentUserId) { + int tempCount = user.unreadMessageCount ?? 0; + user.unreadMessageCount = tempCount + 1; + } } + sort(); } - sort(); } List list = [ @@ -749,7 +749,10 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { for (ChatUser user in searchedChats!) { if (user.id == favoriteChatUser.response!.targetUserId!) { user.isFav = favoriteChatUser.response!.isFav; - favUsersList.add(user); + dynamic contain = favUsersList!.where((ChatUser element) => element.id == favoriteChatUser.response!.targetUserId!); + if (contain.isEmpty) { + favUsersList.add(user); + } } } } @@ -788,6 +791,7 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { } void clearAll() { + print("----------------- Disposed ---------------------------"); searchedChats = pChatHistory; search.clear(); isChatScreenActive = false; @@ -799,6 +803,37 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { sFileType = ""; } + void disposeData() { + search.clear(); + isChatScreenActive = false; + receiverID = 0; + paginationVal = 0; + message.text = ''; + isFileSelected = false; + repliedMsg = []; + sFileType = ""; + deleteData(); + favUsersList.clear(); + searchedChats!.clear(); + pChatHistory!.clear(); + chatHubConnection.stop(); + AppState().chatDetails = null; + } + + void deleteData() { + List exists = [], unique = []; + exists.addAll(searchedChats!); + exists.addAll(favUsersList!); + Map profileMap = {}; + for (ChatUser item in exists) { + profileMap[item.email!] = item; + } + unique = profileMap.values.toList(); + for (ChatUser element in unique!) { + deleteFile(element.id.toString()); + } + } + void getUserImages() async { List emails = []; List exists = [], unique = []; @@ -909,4 +944,9 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { await chatHubConnection.invoke("GetChatCounversationCount", args: [userId]); return ""; } + + void userTypingInvoke({required int currentUser, required int reciptUser}) async { + logger.d([reciptUser, currentUser]); + await chatHubConnection.invoke("UserTypingAsync", args: [reciptUser, currentUser]); + } } diff --git a/lib/ui/chat/chat_bubble.dart b/lib/ui/chat/chat_bubble.dart index 03a41e4..3b183ed 100644 --- a/lib/ui/chat/chat_bubble.dart +++ b/lib/ui/chat/chat_bubble.dart @@ -123,6 +123,7 @@ class ChatBubble extends StatelessWidget { if (fileTypeID == 1 || fileTypeID == 5 || fileTypeID == 7 || fileTypeID == 6 || fileTypeID == 8 || fileTypeID == 2) SvgPicture.asset(data.getType(fileTypeName ?? ""), height: 30, width: 22, alignment: Alignment.center, fit: BoxFit.cover).paddingOnly(left: 0, right: 10), (cItem.contant ?? "").toText12().expanded, + if (fileTypeID == 1 || fileTypeID == 5 || fileTypeID == 7 || fileTypeID == 6 || fileTypeID == 8 || fileTypeID == 2) const Icon(Icons.remove_red_eye, size: 20) ], ), Align( @@ -217,11 +218,9 @@ class ChatBubble extends StatelessWidget { Row( children: [ if (fileTypeID == 1 || fileTypeID == 5 || fileTypeID == 7 || fileTypeID == 6 || fileTypeID == 8 || fileTypeID == 2) - SvgPicture.asset(data.getType(fileTypeName ?? ""), height: 30, width: 22, alignment: Alignment.center, fit: BoxFit.cover).paddingOnly( - left: 0, - right: 10, - ), + SvgPicture.asset(data.getType(fileTypeName ?? ""), height: 30, width: 22, alignment: Alignment.center, fit: BoxFit.cover).paddingOnly(left: 0, right: 10), (cItem.contant ?? "").toText12(color: Colors.white).expanded, + if (fileTypeID == 1 || fileTypeID == 5 || fileTypeID == 7 || fileTypeID == 6 || fileTypeID == 8 || fileTypeID == 2) const Icon(Icons.remove_red_eye, color: Colors.white, size: 20) ], ), Align( diff --git a/lib/ui/chat/chat_detailed_screen.dart b/lib/ui/chat/chat_detailed_screen.dart index 5cad3fa..379fe2b 100644 --- a/lib/ui/chat/chat_detailed_screen.dart +++ b/lib/ui/chat/chat_detailed_screen.dart @@ -233,6 +233,9 @@ class _ChatDetailScreenState extends State { ), ).paddingOnly(right: 21), ), + onChanged: (val) { + m.userTypingInvoke(currentUser: AppState().chatDetails!.response!.id!, reciptUser: params!.chatUser!.id!); + }, ), ], )); diff --git a/lib/ui/chat/chat_home.dart b/lib/ui/chat/chat_home.dart index 330242a..af243e5 100644 --- a/lib/ui/chat/chat_home.dart +++ b/lib/ui/chat/chat_home.dart @@ -47,6 +47,7 @@ class _ChatHomeState extends State { return; } if (data.searchedChats == null || data.searchedChats!.isEmpty) { + data.isLoading = true; data.getUserRecentChats(); } } diff --git a/lib/ui/landing/widget/app_drawer.dart b/lib/ui/landing/widget/app_drawer.dart index 4160fde..4b4219d 100644 --- a/lib/ui/landing/widget/app_drawer.dart +++ b/lib/ui/landing/widget/app_drawer.dart @@ -11,6 +11,7 @@ import 'package:mohem_flutter_app/extensions/string_extensions.dart'; import 'package:mohem_flutter_app/extensions/widget_extensions.dart'; import 'package:mohem_flutter_app/generated/locale_keys.g.dart'; import 'package:mohem_flutter_app/models/dashboard/drawer_menu_item_model.dart'; +import 'package:mohem_flutter_app/provider/chat_provider_model.dart'; import 'package:mohem_flutter_app/provider/dashboard_provider_model.dart'; import 'package:mohem_flutter_app/ui/dialogs/id/business_card_dialog.dart'; import 'package:mohem_flutter_app/ui/dialogs/id/employee_digital_id_dialog.dart'; @@ -28,6 +29,13 @@ class AppDrawer extends StatefulWidget { class _AppDrawerState extends State { List drawerMenuItemList = []; + late ChatProviderModel chatData; + + @override + void initState() { + super.initState(); + chatData = Provider.of(context, listen: false); + } @override Widget build(BuildContext context) { @@ -171,6 +179,7 @@ class _AppDrawerState extends State { AppState().isAuthenticated = false; AppState().isLogged = false; AppState().setPostParamsInitConfig(); + chatData.disposeData(); // SharedPreferences prefs = await SharedPreferences.getInstance(); // await prefs.clear(); Navigator.pushNamedAndRemoveUntil(context, AppRoutes.login, (Route route) => false, arguments: null); From 86d6b57cbcef19924c6aad4c5b8f4259a4ca0bdd Mon Sep 17 00:00:00 2001 From: Sikander Saleem Date: Thu, 15 Dec 2022 12:08:10 +0300 Subject: [PATCH 27/42] dynamic list screen items grid view improvements --- lib/classes/consts.dart | 4 +- lib/extensions/string_extensions.dart | 3 +- lib/ui/login/verify_last_login_screen.dart | 2 +- lib/ui/login/verify_login_screen.dart | 2 +- .../dynamic_listview_screen.dart | 59 ++++++------------- lib/ui/work_list/itg_detail_screen.dart | 2 +- lib/ui/work_list/work_list_screen.dart | 58 +++++++++--------- lib/widgets/app_bar_widget.dart | 6 +- lib/widgets/item_detail_view_widget.dart | 1 + pubspec.yaml | 3 +- 10 files changed, 58 insertions(+), 82 deletions(-) diff --git a/lib/classes/consts.dart b/lib/classes/consts.dart index 3d58efd..ac520b1 100644 --- a/lib/classes/consts.dart +++ b/lib/classes/consts.dart @@ -2,9 +2,9 @@ import 'package:mohem_flutter_app/ui/marathon/widgets/question_card.dart'; class ApiConsts { //static String baseUrl = "http://10.200.204.20:2801/"; // Local server - // static String baseUrl = "https://uat.hmgwebservices.com"; // UAT server + static String baseUrl = "https://uat.hmgwebservices.com"; // UAT server // static String baseUrl = "https://erptstapp.srca.org.sa"; // SRCA server - static String baseUrl = "https://hmgwebservices.com"; // Live server + // static String baseUrl = "https://hmgwebservices.com"; // Live server static String baseUrlServices = baseUrl + "/Services/"; // server // static String baseUrlServices = "https://api.cssynapses.com/tangheem/"; // Live server static String utilitiesRest = baseUrlServices + "Utilities.svc/REST/"; diff --git a/lib/extensions/string_extensions.dart b/lib/extensions/string_extensions.dart index 8e1637e..e9e7e93 100644 --- a/lib/extensions/string_extensions.dart +++ b/lib/extensions/string_extensions.dart @@ -102,13 +102,14 @@ extension EmailValidator on String { decoration: isUnderLine ? TextDecoration.underline : null), ); - Widget toText16({Color? color, bool isUnderLine = false, bool isBold = false, int? maxlines}) => Text( + Widget toText16({Color? color, bool isUnderLine = false, bool isBold = false, int? maxlines, double? height}) => Text( this, maxLines: maxlines, style: TextStyle( color: color ?? MyColors.darkTextColor, fontSize: 16, letterSpacing: -0.64, + height: height, fontWeight: isBold ? FontWeight.bold : FontWeight.w600, decoration: isUnderLine ? TextDecoration.underline : null, ), diff --git a/lib/ui/login/verify_last_login_screen.dart b/lib/ui/login/verify_last_login_screen.dart index 81d1ba2..cfa808a 100644 --- a/lib/ui/login/verify_last_login_screen.dart +++ b/lib/ui/login/verify_last_login_screen.dart @@ -289,7 +289,7 @@ class _VerifyLastLoginScreenState extends State { width: 38, color: isDisable ? MyColors.darkTextColor.withOpacity(0.7) : null, ), - _title.toText16() + _title.toText16(height: 20/16) ], ), ), diff --git a/lib/ui/login/verify_login_screen.dart b/lib/ui/login/verify_login_screen.dart index 803f3d9..0ba486b 100644 --- a/lib/ui/login/verify_login_screen.dart +++ b/lib/ui/login/verify_login_screen.dart @@ -572,7 +572,7 @@ class _VerifyLoginScreenState extends State { width: 38, color: isDisable ? MyColors.darkTextColor.withOpacity(0.7) : null, ), - _title.toText16() + _title.toText16(height: 20/16) ], ), ), diff --git a/lib/ui/my_attendance/dynamic_screens/dynamic_listview_screen.dart b/lib/ui/my_attendance/dynamic_screens/dynamic_listview_screen.dart index d1c21e1..68727e5 100644 --- a/lib/ui/my_attendance/dynamic_screens/dynamic_listview_screen.dart +++ b/lib/ui/my_attendance/dynamic_screens/dynamic_listview_screen.dart @@ -1,4 +1,5 @@ import 'package:flutter/material.dart'; +import 'package:flutter_layout_grid/flutter_layout_grid.dart'; import 'package:mohem_flutter_app/api/my_attendance_api_client.dart'; import 'package:mohem_flutter_app/classes/colors.dart'; import 'package:mohem_flutter_app/classes/utils.dart'; @@ -22,7 +23,8 @@ class DynamicListViewParams { List? collectionNotificationList; final String selectedEmp; - DynamicListViewParams(this.title, this.dynamicId, {this.selectedEmp ='', this.uRL = 'GET_EIT_DFF_STRUCTURE', this.requestID = '', this.colsURL = '', this.isUpdate = false, this.collectionNotificationList}); + DynamicListViewParams(this.title, this.dynamicId, + {this.selectedEmp = '', this.uRL = 'GET_EIT_DFF_STRUCTURE', this.requestID = '', this.colsURL = '', this.isUpdate = false, this.collectionNotificationList}); } class DynamicListViewScreen extends StatefulWidget { @@ -37,6 +39,7 @@ class DynamicListViewScreen extends StatefulWidget { class _DynamicListViewScreenState extends State { List? getEITTransactionList; DynamicListViewParams? dynamicParams; + // String? empId; @override @@ -99,47 +102,19 @@ class _DynamicListViewScreenState extends State { : ListView.separated( physics: const NeverScrollableScrollPhysics(), shrinkWrap: true, - itemBuilder: (cxt, int parentIndex) => getEITTransactionList![parentIndex].collectionTransaction!.isEmpty - ? const SizedBox() - : GridView( - gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2, childAspectRatio: 1.0 / 0.75), - padding: const EdgeInsets.only(left: 12,right: 21,top: 12), - shrinkWrap: true, - primary: false, - physics: const ScrollPhysics(), - children: getEITWidgetsList(getEITTransactionList![parentIndex].collectionTransaction), - ).objectContainerView(), - // Column( - // crossAxisAlignment: CrossAxisAlignment.start, - // mainAxisSize: MainAxisSize.min, - // children: [ - // for (int t = 0; t < (getEITTransactionList![parentIndex].collectionTransaction ?? []).length; t++) - // if (getEITTransactionList![parentIndex].collectionTransaction![t].dISPLAYFLAG == "Y") - // // ItemDetailView(getEITTransactionList![parentIndex].collectionTransaction![t].sEGMENTPROMPT!, - // // getEITTransactionList![parentIndex].collectionTransaction![t].sEGMENTVALUEDSP ?? ""), - // // GridView( - // // gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2), - // // padding: const EdgeInsets.only(left: 21, right: 21, bottom: 21, top: 12), - // // shrinkWrap: true, - // // primary: false, - // // physics: const ScrollPhysics(), - // // children: getEITWidgetsList(getEITTransactionList![parentIndex].collectionTransaction), - // // ) - // // ItemDetailViewCol(getEITTransactionList![parentIndex].collectionTransaction![t].sEGMENTPROMPT!, - // // getEITTransactionList![parentIndex].collectionTransaction![t].sEGMENTVALUEDSP ?? ""), - // - // // GridView( - // // gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2), - // // padding: const EdgeInsets.only(left: 21, right: 21, bottom: 21, top: 12), - // // shrinkWrap: true, - // // primary: false, - // // physics: const ScrollPhysics(), - // // children: getEITWidgetsList(getEITTransactionList![parentIndex].collectionTransaction), - // // ) - // // ItemDetailView(getEITTransactionList![parentIndex].collectionTransaction![t].sEGMENTPROMPT!, - // // getEITTransactionList![parentIndex].collectionTransaction![t].sEGMENTVALUEDSP ?? ""), - // ], - // ).objectContainerView(), + itemBuilder: (cxt, int parentIndex) { + if (getEITTransactionList![parentIndex].collectionTransaction!.isEmpty) { + return const SizedBox(); + } + int count = getEITTransactionList![parentIndex].collectionTransaction!.length; + return LayoutGrid( + columnSizes: [1.fr, 1.fr], + rowSizes: [for (int i = 0; i < (count / 2).round(); i++) auto], + columnGap: 8, + rowGap: 12, + children: getEITWidgetsList(getEITTransactionList![parentIndex].collectionTransaction), + ).objectContainerView(); + }, separatorBuilder: (cxt, index) => 12.height, itemCount: getEITTransactionList!.length)), ], diff --git a/lib/ui/work_list/itg_detail_screen.dart b/lib/ui/work_list/itg_detail_screen.dart index ebe16c8..05e542e 100644 --- a/lib/ui/work_list/itg_detail_screen.dart +++ b/lib/ui/work_list/itg_detail_screen.dart @@ -533,7 +533,7 @@ class _ItgDetailScreenState extends State { Utils.hideLoading(context); Utils.showToast(LocaleKeys.yourChangeHasBeenSavedSuccessfully.tr()); // Navigator.pop(context, "delegate_reload"); - animationIndex=animationIndex+1; + animationIndex = animationIndex + 1; AppState().requestAllList!.removeAt(AppState().itgWorkListIndex!); if (AppState().requestAllList!.isEmpty) { Navigator.pop(context, "delegate_reload"); diff --git a/lib/ui/work_list/work_list_screen.dart b/lib/ui/work_list/work_list_screen.dart index da1b60f..69fb7f3 100644 --- a/lib/ui/work_list/work_list_screen.dart +++ b/lib/ui/work_list/work_list_screen.dart @@ -215,11 +215,7 @@ class _WorkListScreenState extends State { Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.white, - appBar: AppBarWidget( - context, - title: LocaleKeys.workList.tr(), - showNotificationButton: true, - ), + appBar: AppBarWidget(context, title: LocaleKeys.workList.tr(), showWorkListSettingButton: true), body: SizedBox( width: double.infinity, height: double.infinity, @@ -284,31 +280,33 @@ class _WorkListScreenState extends State { physics: const BouncingScrollPhysics(), child: itgRequestTypeIndex != null ? Column( + crossAxisAlignment: CrossAxisAlignment.start, children: [ - SizedBox( - height: 40, - child: ListView.separated( - itemBuilder: (context, index) { - RequestType type = itgFormsModel!.requestType![index]; - return Container( - padding: const EdgeInsets.only(left: 21, right: 21, top: 8, bottom: 8), - alignment: Alignment.center, - decoration: BoxDecoration(borderRadius: BorderRadius.circular(30), color: itgRequestTypeIndex == index ? MyColors.darkIconColor : MyColors.lightGreyEAColor), - child: ("${type.requestTypeName}").toText12(color: itgRequestTypeIndex == index ? MyColors.white : MyColors.black), - ).onPress(() { - if (itgRequestTypeIndex != index) { - itgRequestTypeIndex = index; - setState(() {}); - } - }); - }, - separatorBuilder: (context, index) => 8.width, - shrinkWrap: true, - itemCount: itgFormsModel?.requestType?.length ?? 0, - scrollDirection: Axis.horizontal, - padding: const EdgeInsets.only(left: 21, right: 21), - ), - ).paddingOnly(top: 16, bottom: 16), + // todo this is commented for temporary purpose, have issue when selecting any itg category and click any item showing wrong details + // SizedBox( + // height: 40, + // child: ListView.separated( + // itemBuilder: (context, index) { + // RequestType type = itgFormsModel!.requestType![index]; + // return Container( + // padding: const EdgeInsets.only(left: 21, right: 21, top: 8, bottom: 8), + // alignment: Alignment.center, + // decoration: BoxDecoration(borderRadius: BorderRadius.circular(30), color: itgRequestTypeIndex == index ? MyColors.darkIconColor : MyColors.lightGreyEAColor), + // child: ("${type.requestTypeName}").toText12(color: itgRequestTypeIndex == index ? MyColors.white : MyColors.black), + // ).onPress(() { + // if (itgRequestTypeIndex != index) { + // itgRequestTypeIndex = index; + // setState(() {}); + // } + // }); + // }, + // separatorBuilder: (context, index) => 8.width, + // shrinkWrap: true, + // itemCount: itgFormsModel?.requestType?.length ?? 0, + // scrollDirection: Axis.horizontal, + // padding: const EdgeInsets.only(left: 21, right: 21), + // ), + // ).paddingOnly(top: 16, bottom: 16), ListView.separated( shrinkWrap: true, physics: const NeverScrollableScrollPhysics(), @@ -429,7 +427,7 @@ class _WorkListScreenState extends State { void openBottomSheet(BuildContext context) { showMyBottomSheet( context, - callBackFunc: (){}, + callBackFunc: () {}, child: WorkListAdvanceSearch((selectedViewID, selectedItemTypeID, searchByInput, searchByDate) async { itgRequestTypeIndex = null; pNotificationType = selectedViewID; diff --git a/lib/widgets/app_bar_widget.dart b/lib/widgets/app_bar_widget.dart index 8bca3f3..1096f24 100644 --- a/lib/widgets/app_bar_widget.dart +++ b/lib/widgets/app_bar_widget.dart @@ -12,7 +12,7 @@ import 'package:provider/provider.dart'; AppBar AppBarWidget(BuildContext context, {required String title, bool showHomeButton = true, - bool showNotificationButton = false, + bool showWorkListSettingButton = false, bool showMemberButton = false, List? actions, void Function()? onHomeTapped, @@ -43,12 +43,12 @@ AppBar AppBarWidget(BuildContext context, }, icon: const Icon(Icons.home, color: MyColors.darkIconColor), ), - if (showNotificationButton) + if (showWorkListSettingButton) IconButton( onPressed: () { Navigator.pushNamed(context, AppRoutes.worklistSettings); }, - icon: const Icon(Icons.notifications, color: MyColors.textMixColor), + icon: const Icon(Icons.settings_rounded, color: MyColors.darkIconColor), ), if (showMemberButton) IconButton( diff --git a/lib/widgets/item_detail_view_widget.dart b/lib/widgets/item_detail_view_widget.dart index 77d959b..68b245a 100644 --- a/lib/widgets/item_detail_view_widget.dart +++ b/lib/widgets/item_detail_view_widget.dart @@ -36,6 +36,7 @@ class ItemDetailViewCol extends StatelessWidget { Widget build(BuildContext context) { return Column( crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, children: [ "$title:".toText12(isBold: true, color: const Color(0xff2BB8A6), maxLine: 2), 4.width, diff --git a/pubspec.yaml b/pubspec.yaml index 086ec65..baa5e9f 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -68,7 +68,7 @@ dependencies: month_picker_dialog_2: 0.5.5 open_file: ^3.2.1 wifi_iot: ^0.3.16 - flutter_html: ^2.2.1 + flutter_html: ^3.0.0-alpha.6 # flutter_barcode_scanner: ^2.0.0 qr_code_scanner: ^1.0.0 qr_flutter: ^4.0.0 @@ -100,6 +100,7 @@ dependencies: video_player: ^2.4.7 just_audio: ^0.9.30 safe_device: ^1.1.2 + flutter_layout_grid: ^2.0.1 dev_dependencies: flutter_test: From 660fdb63dd0b849636f1453f454f3e8e1742d458 Mon Sep 17 00:00:00 2001 From: haroon amjad Date: Thu, 15 Dec 2022 12:18:49 +0300 Subject: [PATCH 28/42] Updates & fixes --- assets/langs/ar-SA.json | 3 +- assets/langs/en-US.json | 4 +- lib/api/dashboard_api_client.dart | 22 ++++++++++ lib/classes/consts.dart | 4 +- lib/generated/codegen_loader.g.dart | 8 +++- lib/generated/locale_keys.g.dart | 1 + lib/ui/work_list/worklist_detail_screen.dart | 6 +++ lib/widgets/location/Location.dart | 6 +-- lib/widgets/mark_attendance_widget.dart | 44 ++++++++++++++++---- 9 files changed, 79 insertions(+), 19 deletions(-) diff --git a/assets/langs/ar-SA.json b/assets/langs/ar-SA.json index 2adb2ba..ac320f7 100644 --- a/assets/langs/ar-SA.json +++ b/assets/langs/ar-SA.json @@ -513,5 +513,6 @@ "ourSponsor": "راعينا:", "startingIn": "يبدأ في", "youAreOutOfContest": "أنت خارج المسابقة.", - "winners": "الفائزين!!!" + "winners": "الفائزين!!!", + "fakeLocation": ".لقد تتبعنا أنك تحاول استخدام موقع مزيف! يعتبر هذا مخالفة وقد تم إخطار الموارد البشرية" } \ No newline at end of file diff --git a/assets/langs/en-US.json b/assets/langs/en-US.json index 46ede79..1e6025c 100644 --- a/assets/langs/en-US.json +++ b/assets/langs/en-US.json @@ -513,6 +513,6 @@ "ourSponsor": "Our Sponsor:", "startingIn": "Starting in", "youAreOutOfContest": "You are out of the contest.", - "winners": "WINNERS!!!" - + "winners": "WINNERS!!!", + "fakeLocation": "We traced out that you try to use a fake location! This is considered a violation, and HR has been notified." } \ No newline at end of file diff --git a/lib/api/dashboard_api_client.dart b/lib/api/dashboard_api_client.dart index ace0881..5f2ad7e 100644 --- a/lib/api/dashboard_api_client.dart +++ b/lib/api/dashboard_api_client.dart @@ -133,6 +133,28 @@ class DashboardApiClient { }, url, postParams); } + //Mark Fake Location + Future markFakeLocation({String lat = "0", String? long = "0", required String sourceName}) async { + String url = "${ApiConsts.swpRest}CreateIssueInfo"; + var uuid = Uuid(); + // Generate a v4 (random) id + + Map postParams = { + "UID": uuid.v4(), //Mobile Id + "Latitude": lat, + "Longitude": long, + "QRValue": '', + "NFCValue": sourceName == 'NFC' ? sourceName : '', + "WifiValue": sourceName == 'WIFI' ? sourceName : '', + "EmployeeID": AppState().memberInformationList!.eMPLOYEENUMBER, + }; + postParams.addAll(AppState().postParamsJson); + return await ApiClient().postJsonForObject((json) { + GenericResponseModel responseData = GenericResponseModel.fromJson(json); + return responseData; + }, url, postParams); + } + //Check ITG Type Future getITGPageNotification() async { String url = "${ApiConsts.cocRest}Mohemm_ITG_GetPageNotification"; diff --git a/lib/classes/consts.dart b/lib/classes/consts.dart index 3d58efd..93eceee 100644 --- a/lib/classes/consts.dart +++ b/lib/classes/consts.dart @@ -2,9 +2,9 @@ import 'package:mohem_flutter_app/ui/marathon/widgets/question_card.dart'; class ApiConsts { //static String baseUrl = "http://10.200.204.20:2801/"; // Local server - // static String baseUrl = "https://uat.hmgwebservices.com"; // UAT server // static String baseUrl = "https://erptstapp.srca.org.sa"; // SRCA server - static String baseUrl = "https://hmgwebservices.com"; // Live server + static String baseUrl = "https://uat.hmgwebservices.com"; // UAT server + // static String baseUrl = "https://hmgwebservices.com"; // Live server static String baseUrlServices = baseUrl + "/Services/"; // server // static String baseUrlServices = "https://api.cssynapses.com/tangheem/"; // Live server static String utilitiesRest = baseUrlServices + "Utilities.svc/REST/"; diff --git a/lib/generated/codegen_loader.g.dart b/lib/generated/codegen_loader.g.dart index b2a92ad..67408b3 100644 --- a/lib/generated/codegen_loader.g.dart +++ b/lib/generated/codegen_loader.g.dart @@ -528,7 +528,9 @@ class CodegenLoader extends AssetLoader{ "youWantToLeaveMarathon": "هل أنت متأكد أنك تريد العودة؟ سوف تخرج من المسابقة.", "ourSponsor": "راعينا:", "startingIn": "يبدأ في", - "youAreOutOfContest": "أنت خارج المسابقة." + "youAreOutOfContest": "أنت خارج المسابقة.", + "winners": "الفائزين!!!", + "fakeLocation": ".لقد تتبعنا أنك تحاول استخدام موقع مزيف! يعتبر هذا مخالفة وقد تم إخطار الموارد البشرية" }; static const Map en_US = { "mohemm": "Mohemm", @@ -1044,7 +1046,9 @@ static const Map en_US = { "youWantToLeaveMarathon": "Are you sure you want to go back? You will be out of the contest.", "ourSponsor": "Our Sponsor:", "startingIn": "Starting in", - "youAreOutOfContest": "You are out of the contest." + "youAreOutOfContest": "You are out of the contest.", + "winners": "WINNERS!!!", + "fakeLocation": "We traced out that you try to use a fake location! This is considered a violation, and HR has been notified." }; static const Map> mapLocales = {"ar_SA": ar_SA, "en_US": en_US}; } diff --git a/lib/generated/locale_keys.g.dart b/lib/generated/locale_keys.g.dart index 8960278..e4c6ffb 100644 --- a/lib/generated/locale_keys.g.dart +++ b/lib/generated/locale_keys.g.dart @@ -500,5 +500,6 @@ abstract class LocaleKeys { static const startingIn = 'startingIn'; static const youAreOutOfContest = 'youAreOutOfContest'; static const winners = 'winners'; + static const fakeLocation = 'fakeLocation'; } diff --git a/lib/ui/work_list/worklist_detail_screen.dart b/lib/ui/work_list/worklist_detail_screen.dart index 8ec8d00..1f62d4e 100644 --- a/lib/ui/work_list/worklist_detail_screen.dart +++ b/lib/ui/work_list/worklist_detail_screen.dart @@ -436,6 +436,12 @@ class _WorkListDetailScreenState extends State { case "DELEGATE": returnActionImage = "assets/images/delegate.svg"; break; + case "APPROVE": + returnActionImage = "assets/images/worklist/approve.svg"; + break; + case "REJECT": + returnActionImage = "assets/images/worklist/reject.svg"; + break; case "REQUEST_INFO": returnActionImage = "assets/images/request_info.svg"; break; diff --git a/lib/widgets/location/Location.dart b/lib/widgets/location/Location.dart index 0ddca1c..d407c1c 100644 --- a/lib/widgets/location/Location.dart +++ b/lib/widgets/location/Location.dart @@ -46,12 +46,12 @@ class Location { }); } - static void getCurrentLocation(Function(LatLng?) callback, BuildContext context) { + static void getCurrentLocation(Function(LatLng?, bool isMocked) callback, BuildContext context) { void done(Position position) { //AppStorage.sp.saveLocation(position); - + bool isMocked = position.isMocked; LatLng? myCurrentLocation = LatLng(position.latitude, position.longitude); - callback(myCurrentLocation); + callback(myCurrentLocation, isMocked); } AppPermissions.location((granted) { diff --git a/lib/widgets/mark_attendance_widget.dart b/lib/widgets/mark_attendance_widget.dart index 9840700..cbf70ad 100644 --- a/lib/widgets/mark_attendance_widget.dart +++ b/lib/widgets/mark_attendance_widget.dart @@ -94,8 +94,12 @@ class _MarkAttendanceWidgetState extends State { // if (isNfcEnabled) attendanceMethod("NFC", "assets/images/nfc.svg", isNfcEnabled, () { if (isNfcLocationEnabled) { - Location.getCurrentLocation((LatLng? latlng) { - performNfcAttendance(widget.model, lat: latlng?.latitude.toString() ?? "", lng: latlng?.longitude.toString() ?? ""); + Location.getCurrentLocation((LatLng? latlng, bool isMocked) { + if (isMocked) { + markFakeAttendance("NFC", latlng?.latitude.toString() ?? "", latlng?.longitude.toString() ?? ""); + } else { + performNfcAttendance(widget.model, lat: latlng?.latitude.toString() ?? "", lng: latlng?.longitude.toString() ?? ""); + } }, context); } else { performNfcAttendance(widget.model); @@ -104,8 +108,12 @@ class _MarkAttendanceWidgetState extends State { if (isWifiEnabled) attendanceMethod("Wifi", "assets/images/wufu.svg", isWifiEnabled, () { if (isWifiLocationEnabled) { - Location.getCurrentLocation((LatLng? latlng) { - performWifiAttendance(widget.model, lat: latlng?.latitude.toString() ?? "", lng: latlng?.longitude.toString() ?? ""); + Location.getCurrentLocation((LatLng? latlng, bool isMocked) { + if (isMocked) { + markFakeAttendance("WIFI", latlng?.latitude.toString() ?? "", latlng?.longitude.toString() ?? ""); + } else { + performWifiAttendance(widget.model, lat: latlng?.latitude.toString() ?? "", lng: latlng?.longitude.toString() ?? ""); + } }, context); } else { performWifiAttendance(widget.model); @@ -115,8 +123,12 @@ class _MarkAttendanceWidgetState extends State { if (isQrEnabled) attendanceMethod("QR", "assets/images/ic_qr.svg", isQrEnabled, () async { if (isQrLocationEnabled) { - Location.getCurrentLocation((LatLng? latlng) { - performQrCodeAttendance(widget.model, lat: latlng?.latitude.toString() ?? "", lng: latlng?.longitude.toString() ?? ""); + Location.getCurrentLocation((LatLng? latlng, bool isMocked) { + if (isMocked) { + markFakeAttendance("QR", latlng?.latitude.toString() ?? "", latlng?.longitude.toString() ?? ""); + } else { + performQrCodeAttendance(widget.model, lat: latlng?.latitude.toString() ?? "", lng: latlng?.longitude.toString() ?? ""); + } }, context); } else { performQrCodeAttendance(widget.model); @@ -136,7 +148,7 @@ class _MarkAttendanceWidgetState extends State { Utils.showLoading(context); try { GenericResponseModel? g = await DashboardApiClient().markAttendance(pointType: 2, nfcValue: nfcId, isGpsRequired: isNfcLocationEnabled, lat: lat, long: lng); - if(g?.messageStatus != 1) { + if (g?.messageStatus != 1) { Utils.hideLoading(context); showDialog( context: context, @@ -157,7 +169,6 @@ class _MarkAttendanceWidgetState extends State { child: SuccessDialog(widget.isFromDashboard), ); } - } catch (ex) { print(ex); Utils.hideLoading(context); @@ -171,7 +182,7 @@ class _MarkAttendanceWidgetState extends State { Utils.showLoading(context); try { GenericResponseModel? g = await DashboardApiClient().markAttendance(pointType: 2, nfcValue: nfcId ?? "", isGpsRequired: isNfcLocationEnabled, lat: lat, long: lng); - if(g?.messageStatus != 1) { + if (g?.messageStatus != 1) { Utils.hideLoading(context); showDialog( context: context, @@ -276,6 +287,21 @@ class _MarkAttendanceWidgetState extends State { } } + void markFakeAttendance(String sourceName, String lat, String long) async { + Utils.showLoading(context); + try { + await DashboardApiClient().markFakeLocation(sourceName: sourceName, lat: lat, long: long); + Utils.hideLoading(context); + Utils.confirmDialog(context, LocaleKeys.fakeLocation.tr()); + } catch (ex) { + print(ex); + Utils.hideLoading(context); + Utils.handleException(ex, context, (msg) { + Utils.confirmDialog(context, msg); + }); + } + } + Widget attendanceMethod(String title, String image, bool isEnabled, VoidCallback onPress) => Container( decoration: BoxDecoration( borderRadius: BorderRadius.circular(15), From 2174512d792777188333b8c52f80d8e0caaafeba Mon Sep 17 00:00:00 2001 From: haroon amjad Date: Thu, 15 Dec 2022 16:31:52 +0300 Subject: [PATCH 29/42] updates & fixes --- lib/classes/consts.dart | 4 ++-- lib/ui/chat/chat_bubble.dart | 4 ++-- lib/ui/login/login_screen.dart | 6 +++--- lib/ui/work_list/worklist_fragments/info_fragments.dart | 2 +- lib/ui/work_list/worklist_fragments/request_fragment.dart | 8 ++++---- 5 files changed, 12 insertions(+), 12 deletions(-) diff --git a/lib/classes/consts.dart b/lib/classes/consts.dart index ac520b1..3d58efd 100644 --- a/lib/classes/consts.dart +++ b/lib/classes/consts.dart @@ -2,9 +2,9 @@ import 'package:mohem_flutter_app/ui/marathon/widgets/question_card.dart'; class ApiConsts { //static String baseUrl = "http://10.200.204.20:2801/"; // Local server - static String baseUrl = "https://uat.hmgwebservices.com"; // UAT server + // static String baseUrl = "https://uat.hmgwebservices.com"; // UAT server // static String baseUrl = "https://erptstapp.srca.org.sa"; // SRCA server - // static String baseUrl = "https://hmgwebservices.com"; // Live server + static String baseUrl = "https://hmgwebservices.com"; // Live server static String baseUrlServices = baseUrl + "/Services/"; // server // static String baseUrlServices = "https://api.cssynapses.com/tangheem/"; // Live server static String utilitiesRest = baseUrlServices + "Utilities.svc/REST/"; diff --git a/lib/ui/chat/chat_bubble.dart b/lib/ui/chat/chat_bubble.dart index 3b183ed..8978ff1 100644 --- a/lib/ui/chat/chat_bubble.dart +++ b/lib/ui/chat/chat_bubble.dart @@ -123,7 +123,7 @@ class ChatBubble extends StatelessWidget { if (fileTypeID == 1 || fileTypeID == 5 || fileTypeID == 7 || fileTypeID == 6 || fileTypeID == 8 || fileTypeID == 2) SvgPicture.asset(data.getType(fileTypeName ?? ""), height: 30, width: 22, alignment: Alignment.center, fit: BoxFit.cover).paddingOnly(left: 0, right: 10), (cItem.contant ?? "").toText12().expanded, - if (fileTypeID == 1 || fileTypeID == 5 || fileTypeID == 7 || fileTypeID == 6 || fileTypeID == 8 || fileTypeID == 2) const Icon(Icons.remove_red_eye, size: 20) + if (fileTypeID == 1 || fileTypeID == 5 || fileTypeID == 7 || fileTypeID == 6 || fileTypeID == 8 || fileTypeID == 2) const Icon(Icons.remove_red_eye, size: 16) ], ), Align( @@ -220,7 +220,7 @@ class ChatBubble extends StatelessWidget { if (fileTypeID == 1 || fileTypeID == 5 || fileTypeID == 7 || fileTypeID == 6 || fileTypeID == 8 || fileTypeID == 2) SvgPicture.asset(data.getType(fileTypeName ?? ""), height: 30, width: 22, alignment: Alignment.center, fit: BoxFit.cover).paddingOnly(left: 0, right: 10), (cItem.contant ?? "").toText12(color: Colors.white).expanded, - if (fileTypeID == 1 || fileTypeID == 5 || fileTypeID == 7 || fileTypeID == 6 || fileTypeID == 8 || fileTypeID == 2) const Icon(Icons.remove_red_eye, color: Colors.white, size: 20) + if (fileTypeID == 1 || fileTypeID == 5 || fileTypeID == 7 || fileTypeID == 6 || fileTypeID == 8 || fileTypeID == 2) const Icon(Icons.remove_red_eye, color: Colors.white, size: 16) ], ), Align( diff --git a/lib/ui/login/login_screen.dart b/lib/ui/login/login_screen.dart index 04c3077..a0ab3c9 100644 --- a/lib/ui/login/login_screen.dart +++ b/lib/ui/login/login_screen.dart @@ -58,9 +58,9 @@ class _LoginScreenState extends State { void initState() { super.initState(); // checkFirebaseToken(); - // if (kReleaseMode) { - // checkDeviceSafety(); - // } + if (kReleaseMode) { + checkDeviceSafety(); + } } void checkDeviceSafety() async { diff --git a/lib/ui/work_list/worklist_fragments/info_fragments.dart b/lib/ui/work_list/worklist_fragments/info_fragments.dart index bcde517..d2c64f3 100644 --- a/lib/ui/work_list/worklist_fragments/info_fragments.dart +++ b/lib/ui/work_list/worklist_fragments/info_fragments.dart @@ -164,7 +164,7 @@ class InfoFragment extends StatelessWidget { ), ItemDetailGrid( ItemDetailViewCol(LocaleKeys.otherCharges.tr(), poHeaderList[index].oTHERCHARGES?.toString() ?? ""), - ItemDetailViewCol(LocaleKeys.totalPOAmountWithVAT.tr(), poHeaderList[index].qUOTATIONDATE ?? ""), + ItemDetailViewCol(LocaleKeys.totalPOAmountWithVAT.tr(), poHeaderList[index].tOTPOAMT.toString() ?? ""), ), ItemDetailGrid( ItemDetailViewCol(LocaleKeys.totalPOAmountInWords.tr(), poHeaderList[index].tOTPOAMTWORD ?? ""), diff --git a/lib/ui/work_list/worklist_fragments/request_fragment.dart b/lib/ui/work_list/worklist_fragments/request_fragment.dart index b86bb1a..a13f91f 100644 --- a/lib/ui/work_list/worklist_fragments/request_fragment.dart +++ b/lib/ui/work_list/worklist_fragments/request_fragment.dart @@ -58,10 +58,10 @@ class RequestFragment extends StatelessWidget { children: [ ItemDetailGrid( ItemDetailViewCol(LocaleKeys.code.tr(), poLinesList[index].iTEMCODE ?? ""), - ItemDetailViewCol(LocaleKeys.mfg.tr(), poLinesList[index].uOM ?? ""), + ItemDetailViewCol(LocaleKeys.mfg.tr(), poLinesList[index].mFG ?? ""), ), ItemDetailGrid( - ItemDetailViewCol(LocaleKeys.lineType.tr(), poLinesList[index].qUANTITY?.toString() ?? ""), + ItemDetailViewCol(LocaleKeys.lineType.tr(), poLinesList[index].lINETYPE?.toString() ?? ""), ItemDetailViewCol(LocaleKeys.unit.tr(), poLinesList[index].uOM ?? ""), ), ItemDetailGrid( @@ -78,10 +78,10 @@ class RequestFragment extends StatelessWidget { ), ItemDetailGrid( ItemDetailViewCol(LocaleKeys.deliverToLocation.tr(), poLinesList[index].dELIVERTOLOCATION ?? ""), - ItemDetailViewCol(LocaleKeys.requisitionNumber.tr(), poLinesList[index].rEQUESTOR ?? ""), + ItemDetailViewCol(LocaleKeys.requisitionNumber.tr(), poLinesList[index].pRNUM ?? ""), ), ItemDetailGrid( - ItemDetailViewCol(LocaleKeys.requester.tr(), poLinesList[index].pRNUM ?? ""), + ItemDetailViewCol(LocaleKeys.requester.tr(), poLinesList[index].rEQUESTOR ?? ""), Container(), ), 12.height, From 58fb7a78942206ba48d01d0e9fd44e86c485318f Mon Sep 17 00:00:00 2001 From: Faiz Hashmi Date: Thu, 15 Dec 2022 16:49:23 +0300 Subject: [PATCH 30/42] Pushing for testing --- lib/api/marathon/marathon_api_client.dart | 5 +- lib/ui/marathon/marathon_provider.dart | 33 ++++-- lib/ui/marathon/marathon_screen.dart | 112 ++++++++++-------- lib/ui/marathon/widgets/marathon_footer.dart | 17 --- .../widgets/marathon_progress_container.dart | 8 +- .../marathon_qualifiers_container.dart | 1 + 6 files changed, 92 insertions(+), 84 deletions(-) diff --git a/lib/api/marathon/marathon_api_client.dart b/lib/api/marathon/marathon_api_client.dart index 26a0363..9fcdc68 100644 --- a/lib/api/marathon/marathon_api_client.dart +++ b/lib/api/marathon/marathon_api_client.dart @@ -97,6 +97,7 @@ class MarathonApiClient { if (marathonModel.statusCode == 208) { // means participant is already in the marathon i.e already joined + //TODO: NEED TO LOOK UPON THIS return marathonModel.data["remainingTime"]; } @@ -116,13 +117,13 @@ class MarathonApiClient { Map jsonObject = { "previousQuestionId": questionId, "marathonId": marathonId, - }; + }; Response response = await ApiClient().postJsonForResponse(ApiConsts.marathonNextQuestionUrl, jsonObject, token: AppState().getMarathonToken ?? await getMarathonToken()); var json = jsonDecode(response.body); - + logger.i("json in NextQuestion: $json"); var data = json["data"]; diff --git a/lib/ui/marathon/marathon_provider.dart b/lib/ui/marathon/marathon_provider.dart index 4144e32..128b634 100644 --- a/lib/ui/marathon/marathon_provider.dart +++ b/lib/ui/marathon/marathon_provider.dart @@ -31,6 +31,11 @@ class MarathonProvider extends ChangeNotifier { String? selectedOptionId; int? totalQualifiers; + //TODO: THIS BUG NEEDS TO BE FIXED. NOT DONE YET + String? gapTimeImage; + String? gapTimeText; + int? gapTimeType; + bool iAmWinner = false; bool isPrivilegedWithMarathon = false; @@ -178,16 +183,21 @@ class MarathonProvider extends ChangeNotifier { updateCardStatusToAnswer(); - await callSubmitOptionApi().then((bool value) async { - if (value) { - await callNextQuestionApi(); - } + scheduleMicrotask(() async { + await callSubmitOptionApi().then((bool value) async { + if (value) { + await callNextQuestionApi(); + } + }); }); } if (totalCurrentQuestionTime == 0) { + gapTimeImage = currentQuestion.gapImage; + gapTimeText = currentQuestion.gapText; + gapTimeType = currentQuestion.gapType; updateCardData(); - if (currentQuestionNumber == marathonDetailModel.totalQuestions!) { + if (currentQuestionNumber - 1 == marathonDetailModel.totalQuestions!) { callGetQualifiersApi(); updateQuestionCardStatus(QuestionCardStatus.findingWinner); timer.cancel(); @@ -242,7 +252,6 @@ class MarathonProvider extends ChangeNotifier { selectedWinners = await MarathonApiClient().getSelectedWinner(marathonId: marathonDetailModel.id!); if (selectedWinners != null) { selectedWinners!.removeWhere((WinnerModel element) { - print("matching : ${AppState().memberInformationList!.eMPLOYEENUMBER} with ${element.employeeId}"); if (element.employeeId == AppState().memberInformationList!.eMPLOYEENUMBER) { iAmWinner = true; return true; @@ -251,18 +260,18 @@ class MarathonProvider extends ChangeNotifier { } }); } - print("selectedWinners Length : ${selectedWinners!.length}"); notifyListeners(); } - // TODO: here I need to add a logic where I should call this function for Api but for the 1st question it should behave differently - // TODO: Verify the callings!!! Future callNextQuestionApi() async { if (currentQuestionNumber < marathonDetailModel.totalQuestions!) { if (currentQuestionNumber == 0) { Utils.showLoading(AppRoutes.navigatorKey.currentContext!); currentQuestion = (await MarathonApiClient().getNextQuestion(questionId: null, marathonId: marathonDetailModel.id!))!; + gapTimeImage = currentQuestion.gapImage; + gapTimeText = currentQuestion.gapText; + gapTimeType = currentQuestion.gapType; if (Utils.isLoading) { Utils.hideLoading(AppRoutes.navigatorKey.currentContext!); } @@ -283,6 +292,7 @@ class MarathonProvider extends ChangeNotifier { } selectedOptionIndex = null; currentQuestionNumber++; + cardContentList.add(const CardContent()); totalCurrentQuestionTime = currentQuestion.questionTime! + currentQuestion.nextQuestGap!; currentGapTime = currentQuestion.nextQuestGap!; @@ -293,7 +303,7 @@ class MarathonProvider extends ChangeNotifier { void populateQuestionStatusesList() { if (marathonDetailModel.totalQuestions != null) { - for (int i = 0; i < marathonDetailModel.totalQuestions! - 1; i++) { + for (int i = 0; i < marathonDetailModel.totalQuestions!; i++) { answerStatusesList.add(QuestionCardStatus.question); } notifyListeners(); @@ -422,9 +432,6 @@ class MarathonProvider extends ChangeNotifier { Navigator.pushReplacementNamed(context, AppRoutes.marathonWaitingScreen); } } catch (e) { - if (kDebugMode) { - print("error in onJoinMarathonPressed: ${e.toString()}"); - } Utils.hideLoading(context); Utils.confirmDialog(context, e.toString()); } diff --git a/lib/ui/marathon/marathon_screen.dart b/lib/ui/marathon/marathon_screen.dart index 67d6f4e..c032823 100644 --- a/lib/ui/marathon/marathon_screen.dart +++ b/lib/ui/marathon/marathon_screen.dart @@ -22,6 +22,7 @@ import 'package:mohem_flutter_app/ui/marathon/widgets/marathon_qualifiers_contai import 'package:mohem_flutter_app/ui/marathon/widgets/question_card.dart'; import 'package:mohem_flutter_app/ui/marathon/widgets/question_card_builder.dart'; import 'package:mohem_flutter_app/widgets/app_bar_widget.dart'; +import 'package:mohem_flutter_app/widgets/button/default_button.dart'; import 'package:mohem_flutter_app/widgets/dialogs/confirm_dialog.dart'; import 'package:provider/provider.dart'; @@ -197,57 +198,74 @@ class MarathonScreen extends StatelessWidget { } }, ), - body: SingleChildScrollView( - child: Column( - children: [ - 20.height, - if (provider.questionCardStatus == QuestionCardStatus.findingWinner) ...[ - QualifiersContainer(provider: provider).paddingOnly(left: 21, right: 21), - ] else if (provider.questionCardStatus == QuestionCardStatus.winnerFound) - ...[] - else ...[ - MarathonProgressContainer(provider: provider).paddingOnly(left: 21, right: 21), - ], - if (provider.questionCardStatus == QuestionCardStatus.findingWinner) ...[ - getNameContainer(context), + body: Column( + children: [ + ListView( + children: [ + 20.height, + if (provider.questionCardStatus == QuestionCardStatus.findingWinner) ...[ + QualifiersContainer(provider: provider).paddingOnly(left: 21, right: 21), + ] else if (provider.questionCardStatus == QuestionCardStatus.winnerFound) + ...[] + else ...[ + MarathonProgressContainer(provider: provider).paddingOnly(left: 21, right: 21), + ], + if (provider.questionCardStatus == QuestionCardStatus.findingWinner) ...[ + getNameContainer(context), + ], + QuestionCardBuilder( + onQuestion: (BuildContext context) => const QuestionCard(), + onCompleted: (BuildContext context) => CustomStatusWidget( + asset: Lottie.asset(MyLottieConsts.allQuestions, height: 200), + title: LocaleKeys.congrats.tr().toText22(color: MyColors.greenColor), + subTitle: LocaleKeys.allQuestionsCorrect.toText18(color: MyColors.darkTextColor, isCentered: true), + ), + onCorrectAnswer: (BuildContext context) => CustomStatusWidget( + asset: getSuccessWidget(gapType: provider.gapTimeType, gapImage: provider.gapTimeImage, gapText: provider.gapTimeText), + title: LocaleKeys.congrats.tr().toText22(color: MyColors.greenColor), + subTitle: LocaleKeys.yourAnswerCorrect.tr().toText18(color: MyColors.darkTextColor, isCentered: true), + ), + onWinner: (BuildContext context) => getWinnerWidget(context, provider: provider), + onWrongAnswer: (BuildContext context) => CustomStatusWidget( + asset: Image.asset(MyLottieConsts.wrongAnswerGif, height: 200), + title: LocaleKeys.oops.tr().toText22(color: MyColors.redColor), + subTitle: LocaleKeys.wrongAnswer.tr().toText18(color: MyColors.darkTextColor, isCentered: true), + ), + onSkippedAnswer: (BuildContext context) => CustomStatusWidget( + asset: Image.asset(MyLottieConsts.wrongAnswerGif, height: 200), + title: LocaleKeys.oops.tr().toText22(color: MyColors.redColor), + subTitle: LocaleKeys.youMissedTheQuestion.tr().toText18(color: MyColors.darkTextColor, isCentered: true), + ), + onFindingWinner: (BuildContext context) => CustomStatusWidget( + asset: Lottie.asset(MyLottieConsts.winnerLottie, height: 168), + title: LocaleKeys.fingersCrossed.tr().toText22(color: MyColors.greenColor), + subTitle: LocaleKeys.winnerSelectedRandomly.tr().toText18(color: MyColors.darkTextColor, isCentered: true), + ), + questionCardStatus: provider.questionCardStatus, + ).paddingOnly(top: 12, left: 21, right: 21), ], - QuestionCardBuilder( - onQuestion: (BuildContext context) => const QuestionCard(), - onCompleted: (BuildContext context) => CustomStatusWidget( - asset: Lottie.asset(MyLottieConsts.allQuestions, height: 200), - title: LocaleKeys.congrats.tr().toText22(color: MyColors.greenColor), - subTitle: LocaleKeys.allQuestionsCorrect.toText18(color: MyColors.darkTextColor, isCentered: true), - ), - onCorrectAnswer: (BuildContext context) => CustomStatusWidget( - asset: getSuccessWidget(gapType: provider.currentQuestion.gapType, gapImage: provider.currentQuestion.gapImage, gapText: provider.currentQuestion.gapText), - title: LocaleKeys.congrats.tr().toText22(color: MyColors.greenColor), - subTitle: LocaleKeys.yourAnswerCorrect.toText18(color: MyColors.darkTextColor, isCentered: true), - ), - onWinner: (BuildContext context) => getWinnerWidget(context, provider: provider), - onWrongAnswer: (BuildContext context) => CustomStatusWidget( - asset: Image.asset(MyLottieConsts.wrongAnswerGif, height: 200), - title: LocaleKeys.oops.tr().toText22(color: MyColors.redColor), - subTitle: LocaleKeys.wrongAnswer.tr().toText18(color: MyColors.darkTextColor, isCentered: true), - ), - onSkippedAnswer: (BuildContext context) => CustomStatusWidget( - asset: Image.asset(MyLottieConsts.wrongAnswerGif, height: 200), - title: LocaleKeys.oops.tr().toText22(color: MyColors.redColor), - subTitle: LocaleKeys.youMissedTheQuestion.tr().toText18(color: MyColors.darkTextColor, isCentered: true), - ), - onFindingWinner: (BuildContext context) => CustomStatusWidget( - asset: Lottie.asset(MyLottieConsts.winnerLottie, height: 168), - title: LocaleKeys.fingersCrossed.tr().toText22(color: MyColors.greenColor), - subTitle: LocaleKeys.winnerSelectedRandomly.tr().toText18(color: MyColors.darkTextColor, isCentered: true), - ), - questionCardStatus: provider.questionCardStatus, - ).paddingOnly(top: 12, left: 21, right: 21), - ], - ), + ).expanded, + provider.questionCardStatus == QuestionCardStatus.winnerFound + ? DefaultButton(LocaleKeys.ok.tr(), () { + provider.resetValues(); + Navigator.of(context).popUntil(ModalRoute.withName(AppRoutes.dashboard)); + }).insideContainer + : const SizedBox() + ], ), ), onWillPop: () { - provider.resetValues(); - return Future.value(true); + showDialog( + context: context, + builder: (BuildContext context) => ConfirmDialog( + message: LocaleKeys.youWantToLeaveMarathon.tr(), + onTap: () { + provider.resetValues(); + Navigator.of(context).popUntil(ModalRoute.withName(AppRoutes.dashboard)); + }, + ), + ); + return Future.value(false); }, ); } diff --git a/lib/ui/marathon/widgets/marathon_footer.dart b/lib/ui/marathon/widgets/marathon_footer.dart index b5083c0..fea076e 100644 --- a/lib/ui/marathon/widgets/marathon_footer.dart +++ b/lib/ui/marathon/widgets/marathon_footer.dart @@ -47,20 +47,3 @@ class MarathonFooter extends StatelessWidget { ).insideContainer; } } - -//Container( -// color: Colors.white, -// child: Column( -// mainAxisSize: MainAxisSize.min, -// children: [ -// buildNoteForDemo(), -// DefaultButton( -// LocaleKeys.joinDemoMarathon.tr(), -// () { -// provider.connectSignalrAndJoinMarathon(context); -// }, -// color: MyColors.yellowColorII, -// ).insideContainer, -// ], -// ), -// ); diff --git a/lib/ui/marathon/widgets/marathon_progress_container.dart b/lib/ui/marathon/widgets/marathon_progress_container.dart index c0dae6c..5015f25 100644 --- a/lib/ui/marathon/widgets/marathon_progress_container.dart +++ b/lib/ui/marathon/widgets/marathon_progress_container.dart @@ -43,7 +43,8 @@ class MarathonProgressContainer extends StatelessWidget { 8.height, Row( children: [ - "${((provider.currentQuestionNumber / provider.marathonDetailModel.totalQuestions!) * 100).toInt()}% ${LocaleKeys.completed.tr()}".toText14(), + "${provider.currentQuestionNumber == 1 ? 0 : (((provider.currentQuestionNumber - 1) / provider.marathonDetailModel.totalQuestions!) * 100).toInt()}% ${LocaleKeys.completed.tr()}" + .toText14(), ], ), ], @@ -52,9 +53,6 @@ class MarathonProgressContainer extends StatelessWidget { } Color getStepColor(QuestionCardStatus status, bool isOutOfGame) { - if (isOutOfGame) { - return MyColors.redColor; - } switch (status) { case QuestionCardStatus.question: return MyColors.yellowColorII; @@ -79,7 +77,7 @@ class MarathonProgressContainer extends StatelessWidget { child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ - for (int i = 0; i < totalQuestions - 1; i++) + for (int i = 0; i < totalQuestions; i++) if (value <= i) roundContainer(MyColors.lightGreyDeColor, i != 0) else diff --git a/lib/ui/marathon/widgets/marathon_qualifiers_container.dart b/lib/ui/marathon/widgets/marathon_qualifiers_container.dart index dc9d7e4..7463f37 100644 --- a/lib/ui/marathon/widgets/marathon_qualifiers_container.dart +++ b/lib/ui/marathon/widgets/marathon_qualifiers_container.dart @@ -43,6 +43,7 @@ class _QualifiersContainerState extends State { ), 10.height, Row( + crossAxisAlignment: CrossAxisAlignment.end, children: [ widget.provider.totalQualifiers != null ? widget.provider.totalQualifiers.toString().toText30(color: MyColors.greenColor, isBold: true) : const SizedBox(), 2.width, From f62253374de2000af2bb847b37092f5dcc81f17a Mon Sep 17 00:00:00 2001 From: "Aamir.Muhammad" Date: Sun, 18 Dec 2022 09:37:20 +0300 Subject: [PATCH 31/42] Chat Error Handling --- lib/api/chat/chat_api_client.dart | 24 ++++++++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-) diff --git a/lib/api/chat/chat_api_client.dart b/lib/api/chat/chat_api_client.dart index 35e4f79..5bceb24 100644 --- a/lib/api/chat/chat_api_client.dart +++ b/lib/api/chat/chat_api_client.dart @@ -3,10 +3,12 @@ import 'dart:io'; import 'dart:typed_data'; import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; import 'package:http/http.dart'; import 'package:mohem_flutter_app/api/api_client.dart'; import 'package:mohem_flutter_app/app_state/app_state.dart'; import 'package:mohem_flutter_app/classes/consts.dart'; +import 'package:mohem_flutter_app/classes/utils.dart'; import 'package:mohem_flutter_app/exceptions/api_exception.dart'; import 'package:mohem_flutter_app/main.dart'; import 'package:mohem_flutter_app/models/chat/chat_user_image_model.dart'; @@ -22,6 +24,7 @@ class ChatApiClient { factory ChatApiClient() => _instance; Future getUserLoginToken() async { + user.UserAutoLoginModel userLoginResponse = user.UserAutoLoginModel(); Response response = await ApiClient().postJsonForResponse( "${ApiConsts.chatLoginTokenUrl}externaluserlogin", { @@ -32,7 +35,14 @@ class ChatApiClient { if (!kReleaseMode) { logger.i("res: " + response.body); } - user.UserAutoLoginModel userLoginResponse = user.userAutoLoginModelFromJson(response.body); + if (response.statusCode == 200) { + userLoginResponse = user.userAutoLoginModelFromJson(response.body); + } else if (response.statusCode == 504) { + getUserLoginToken(); + } else { + userLoginResponse = user.userAutoLoginModelFromJson(response.body); + Utils.showToast(userLoginResponse.errorResponses!.first.message!); + } return userLoginResponse; } @@ -141,6 +151,7 @@ class ChatApiClient { } Future> getUsersImages({required List encryptedEmails}) async { + List imagesData = []; Response response = await ApiClient().postJsonForResponse( "${ApiConsts.chatUserImages}images", {"encryptedEmails": encryptedEmails, "fromClient": false}, @@ -148,7 +159,16 @@ class ChatApiClient { ); if (!kReleaseMode) { logger.i("res: " + response.body); + print("Images Status Coe is ============== " + response.statusCode.toString()); + } + if (response.statusCode == 200) { + imagesData = chatUserImageModelFromJson(response.body); + } else if (response.statusCode == 504 || response.statusCode == 500) { + getUsersImages(encryptedEmails: encryptedEmails); + } else { + Utils.showToast("Something went wrong while loading images"); + imagesData = []; } - return chatUserImageModelFromJson(response.body); + return imagesData; } } From ece6a68a9569ffe3a361ac9cf5d488a0d0f535cb Mon Sep 17 00:00:00 2001 From: haroon amjad Date: Mon, 19 Dec 2022 09:45:22 +0300 Subject: [PATCH 32/42] fixes --- .../get_po_Item_history_list_model.dart | 2 +- .../get_quotation_analysis_list_model.dart | 2 +- .../leave_balance/leave_balance_screen.dart | 4 +- lib/ui/login/login_screen.dart | 6 +- lib/ui/marathon/marathon_provider.dart | 1 + lib/ui/marathon/widgets/marathon_banner.dart | 374 +++++++++--------- lib/ui/work_list/item_history_screen.dart | 3 +- 7 files changed, 198 insertions(+), 194 deletions(-) diff --git a/lib/models/get_po_Item_history_list_model.dart b/lib/models/get_po_Item_history_list_model.dart index 35e81d6..28a4f28 100644 --- a/lib/models/get_po_Item_history_list_model.dart +++ b/lib/models/get_po_Item_history_list_model.dart @@ -4,7 +4,7 @@ class GetPoItemHistoryList { String? bUYER; String? cLOSEDCODE; String? cREATIONDATE; - int? dISCOUNTPERCENTAGE; + num? dISCOUNTPERCENTAGE; int? fROMROWNUM; int? iTEMID; num? nETPRICE; diff --git a/lib/models/get_quotation_analysis_list_model.dart b/lib/models/get_quotation_analysis_list_model.dart index e041f95..e1926f0 100644 --- a/lib/models/get_quotation_analysis_list_model.dart +++ b/lib/models/get_quotation_analysis_list_model.dart @@ -5,7 +5,7 @@ class GetQuotationAnalysisList { int? nOOFROWS; String? qUOTBONUSQTY; String? qUOTDELIVERYDATE; - int? qUOTLINETOTAL; + num? qUOTLINETOTAL; String? qUOTMFGPARTNUM; String? qUOTNUM; num? qUOTQTY; diff --git a/lib/ui/leave_balance/leave_balance_screen.dart b/lib/ui/leave_balance/leave_balance_screen.dart index d1a64c6..8c346bc 100644 --- a/lib/ui/leave_balance/leave_balance_screen.dart +++ b/lib/ui/leave_balance/leave_balance_screen.dart @@ -43,9 +43,9 @@ class _LeaveBalanceState extends State { void getAbsenceTransactions() async { try { - // Utils.showLoading(context); + Utils.showLoading(context); absenceTransList = await LeaveBalanceApiClient().getAbsenceTransactions(-999, empID: selectedEmp); - //Utils.hideLoading(context); + Utils.hideLoading(context); setState(() {}); } catch (ex) { Utils.hideLoading(context); diff --git a/lib/ui/login/login_screen.dart b/lib/ui/login/login_screen.dart index a0ab3c9..04c3077 100644 --- a/lib/ui/login/login_screen.dart +++ b/lib/ui/login/login_screen.dart @@ -58,9 +58,9 @@ class _LoginScreenState extends State { void initState() { super.initState(); // checkFirebaseToken(); - if (kReleaseMode) { - checkDeviceSafety(); - } + // if (kReleaseMode) { + // checkDeviceSafety(); + // } } void checkDeviceSafety() async { diff --git a/lib/ui/marathon/marathon_provider.dart b/lib/ui/marathon/marathon_provider.dart index 128b634..bde62aa 100644 --- a/lib/ui/marathon/marathon_provider.dart +++ b/lib/ui/marathon/marathon_provider.dart @@ -390,6 +390,7 @@ class MarathonProvider extends ChangeNotifier { } bool checkIfPrivilegedForMarathon() { + return true; for (PrivilegeListModel element in AppState().privilegeListModel!) { if (element.serviceName == "Marathon") { if (element.previlege != null) { diff --git a/lib/ui/marathon/widgets/marathon_banner.dart b/lib/ui/marathon/widgets/marathon_banner.dart index 0487c74..1b5533b 100644 --- a/lib/ui/marathon/widgets/marathon_banner.dart +++ b/lib/ui/marathon/widgets/marathon_banner.dart @@ -184,200 +184,202 @@ class MarathonBanner extends StatelessWidget { Widget build(BuildContext context) { MarathonProvider provider = context.read(); - return !provider.isPrivilegedWithMarathon - ? getUnPrivilegedMarathon(context) - : provider.marathonDetailModel.startTime != null - ? Container( - decoration: MyDecorations.shadowDecoration, - height: isTablet ? MediaQuery.of(context).size.height * 0.17 : MediaQuery.of(context).size.height * 0.11, - clipBehavior: Clip.antiAlias, - child: Stack( - children: [ - Transform( - alignment: Alignment.center, - transform: Matrix4.rotationY( - AppState().isArabic(context) ? math.pi : 0, - ), - child: SvgPicture.asset( - "assets/images/marathon_banner_bg.svg", - fit: BoxFit.fill, - width: double.infinity, - ), + return + // !provider.isPrivilegedWithMarathon + // ? getUnPrivilegedMarathon(context) + // : provider.marathonDetailModel.startTime != null + // ? + Container( + decoration: MyDecorations.shadowDecoration, + height: isTablet ? MediaQuery.of(context).size.height * 0.17 : MediaQuery.of(context).size.height * 0.11, + clipBehavior: Clip.antiAlias, + child: Stack( + children: [ + Transform( + alignment: Alignment.center, + transform: Matrix4.rotationY( + AppState().isArabic(context) ? math.pi : 0, + ), + child: SvgPicture.asset( + "assets/images/marathon_banner_bg.svg", + fit: BoxFit.fill, + width: double.infinity, + ), + ), + AppState().isArabic(context) + ? Positioned( + right: -15, + top: -10, + child: Transform.rotate( + angle: 10, + child: Container( + width: isTablet ? 70 : 65, + height: isTablet ? 40 : 32, + color: MyColors.darkDigitColor, ), - AppState().isArabic(context) - ? Positioned( - right: -15, - top: -10, - child: Transform.rotate( - angle: 10, - child: Container( - width: isTablet ? 70 : 65, - height: isTablet ? 40 : 32, - color: MyColors.darkDigitColor, + ), + ) + : Positioned( + left: -20, + top: -10, + child: Transform.rotate( + angle: 15, + child: Container( + width: isTablet ? 70 : 65, + height: isTablet ? 40 : 32, + color: MyColors.darkDigitColor, + ), + ), + ), + SizedBox( + width: double.infinity, + height: double.infinity, + child: Row( + children: [ + const Expanded( + flex: 3, + child: SizedBox( + width: double.infinity, + height: double.infinity, + ), + ), + Expanded( + flex: AppState().isArabic(context) ? 4 : 5, + child: SizedBox( + width: double.infinity, + height: double.infinity, + child: Row( + mainAxisAlignment: MainAxisAlignment.start, + children: [ + Column( + mainAxisAlignment: MainAxisAlignment.center, + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + AppState().isArabic(context) ? 0.height : 5.height, + Text( + LocaleKeys.getReadyForContest.tr(), + style: TextStyle( + fontSize: isTablet ? 20 : 11, + fontStyle: FontStyle.italic, + fontWeight: FontWeight.w600, + color: MyColors.white.withOpacity(0.83), + letterSpacing: -0.4, ), ), - ) - : Positioned( - left: -20, - top: -10, - child: Transform.rotate( - angle: 15, - child: Container( - width: isTablet ? 70 : 65, - height: isTablet ? 40 : 32, - color: MyColors.darkDigitColor, + Text( + AppState().isArabic(context) ? provider.marathonDetailModel.titleAr ?? "" : provider.marathonDetailModel.titleEn ?? "", + style: TextStyle( + fontStyle: FontStyle.italic, + fontSize: isTablet ? 30 : 19, + fontWeight: FontWeight.bold, + color: MyColors.white.withOpacity(0.83), + height: 32 / 22, ), ), - ), - SizedBox( - width: double.infinity, - height: double.infinity, - child: Row( - children: [ - const Expanded( - flex: 3, - child: SizedBox( - width: double.infinity, - height: double.infinity, - ), - ), - Expanded( - flex: AppState().isArabic(context) ? 4 : 5, - child: SizedBox( - width: double.infinity, - height: double.infinity, - child: Row( - mainAxisAlignment: MainAxisAlignment.start, - children: [ - Column( - mainAxisAlignment: MainAxisAlignment.center, - crossAxisAlignment: CrossAxisAlignment.start, - mainAxisSize: MainAxisSize.min, - children: [ - AppState().isArabic(context) ? 0.height : 5.height, - Text( - LocaleKeys.getReadyForContest.tr(), - style: TextStyle( - fontSize: isTablet ? 20 : 11, - fontStyle: FontStyle.italic, - fontWeight: FontWeight.w600, - color: MyColors.white.withOpacity(0.83), - letterSpacing: -0.4, - ), - ), - Text( - AppState().isArabic(context) ? provider.marathonDetailModel.titleAr ?? "" : provider.marathonDetailModel.titleEn ?? "", - style: TextStyle( - fontStyle: FontStyle.italic, - fontSize: isTablet ? 30 : 19, - fontWeight: FontWeight.bold, - color: MyColors.white.withOpacity(0.83), - height: 32 / 22, - ), - ), - isTablet ? 10.height : 3.height, - BuildCountdownTimer( - timeToMarathon: DateTime.parse(provider.marathonDetailModel.startTime!).millisecondsSinceEpoch, - provider: provider, - screenFlag: 0, - ), - ], - ).paddingOnly( - left: AppState().isArabic(context) ? 12 : 3, - right: AppState().isArabic(context) ? 3 : 12, - ) - ], - ), + isTablet ? 10.height : 3.height, + BuildCountdownTimer( + timeToMarathon: DateTime.parse(provider.marathonDetailModel.startTime!).millisecondsSinceEpoch, + provider: provider, + screenFlag: 0, ), - ), - ], + ], + ).paddingOnly( + left: AppState().isArabic(context) ? 12 : 3, + right: AppState().isArabic(context) ? 3 : 12, + ) + ], + ), + ), + ), + ], + ), + ), + AppState().isArabic(context) + ? Align( + alignment: Alignment.topRight, + child: SizedBox( + height: isTablet ? 30 : 20, + width: isTablet ? 45 : 35, + child: Transform.rotate( + angle: math.pi / 4.5, + child: Text( + LocaleKeys.brainMarathon.tr(), + textAlign: TextAlign.center, + maxLines: 2, + style: TextStyle( + color: MyColors.white, + fontWeight: FontWeight.bold, + fontSize: isTablet ? 8 : 6, + height: 1.2, + ), ), ), - AppState().isArabic(context) - ? Align( - alignment: Alignment.topRight, - child: SizedBox( - height: isTablet ? 30 : 20, - width: isTablet ? 45 : 35, - child: Transform.rotate( - angle: math.pi / 4.5, - child: Text( - LocaleKeys.brainMarathon.tr(), - textAlign: TextAlign.center, - maxLines: 2, - style: TextStyle( - color: MyColors.white, - fontWeight: FontWeight.bold, - fontSize: isTablet ? 8 : 6, - height: 1.2, - ), - ), - ), - ), - ).paddingOnly(top: 5) - : Align( - alignment: Alignment.topLeft, - child: SizedBox( - height: isTablet ? 30 : 20, - width: isTablet ? 45 : 35, - child: Transform.rotate( - angle: -math.pi / 4.5, - child: Text( - LocaleKeys.brainMarathon.tr(), - textAlign: TextAlign.center, - maxLines: 2, - style: TextStyle( - color: MyColors.kWhiteColor, - fontWeight: FontWeight.bold, - fontSize: isTablet ? 8 : 6, - height: 1.2, - ), - ), - ), - ), - ).paddingOnly(top: 5), - !AppState().isArabic(context) - ? Positioned( - right: 0, - bottom: 0, - child: RotatedBox( - quarterTurns: 4, - child: SvgPicture.asset("assets/images/arrow_next.svg", color: MyColors.whiteColor), - ).paddingAll(isTablet ? 20 : 15), - ) - : Positioned( - bottom: 0, - left: 0, - child: RotatedBox( - quarterTurns: 2, - child: SvgPicture.asset("assets/images/arrow_next.svg", color: MyColors.whiteColor), - ).paddingAll(isTablet ? 20 : 15), - ), - - ], - ).onPress(() async { - int remainingTimeInMinutes = DateTime.parse(provider.marathonDetailModel.startTime!).difference(DateTime.now()).inMinutes; + ), + ).paddingOnly(top: 5) + : Align( + alignment: Alignment.topLeft, + child: SizedBox( + height: isTablet ? 30 : 20, + width: isTablet ? 45 : 35, + child: Transform.rotate( + angle: -math.pi / 4.5, + child: Text( + LocaleKeys.brainMarathon.tr(), + textAlign: TextAlign.center, + maxLines: 2, + style: TextStyle( + color: MyColors.kWhiteColor, + fontWeight: FontWeight.bold, + fontSize: isTablet ? 8 : 6, + height: 1.2, + ), + ), + ), + ), + ).paddingOnly(top: 5), + !AppState().isArabic(context) + ? Positioned( + right: 0, + bottom: 0, + child: RotatedBox( + quarterTurns: 4, + child: SvgPicture.asset("assets/images/arrow_next.svg", color: MyColors.whiteColor), + ).paddingAll(isTablet ? 20 : 15), + ) + : Positioned( + bottom: 0, + left: 0, + child: RotatedBox( + quarterTurns: 2, + child: SvgPicture.asset("assets/images/arrow_next.svg", color: MyColors.whiteColor), + ).paddingAll(isTablet ? 20 : 15), + ), + ], + ).onPress(() async { + int remainingTimeInMinutes = DateTime.parse(provider.marathonDetailModel.startTime!).difference(DateTime.now()).inMinutes; - if (remainingTimeInMinutes > 2) { - Utils.showLoading(context); - try { - await provider.initializeVideoPlayer().then((_) { - Utils.hideLoading(context); - provider.startTimerForSponsorVideo(); - Navigator.pushNamed(context, AppRoutes.marathonSponsorVideoScreen); - }); - } catch (e) { - if (kDebugMode) { - print("Error in VideoPlayer: ${e.toString()}"); - } - Utils.hideLoading(context); - Navigator.pushNamed(context, AppRoutes.marathonIntroScreen); - } - } else { - Navigator.pushNamed(context, AppRoutes.marathonIntroScreen); - } - }), - ) - : const SizedBox(); + if (remainingTimeInMinutes > 2) { + Utils.showLoading(context); + try { + await provider.initializeVideoPlayer().then((_) { + Utils.hideLoading(context); + provider.startTimerForSponsorVideo(); + Navigator.pushNamed(context, AppRoutes.marathonSponsorVideoScreen); + }); + } catch (e) { + if (kDebugMode) { + print("Error in VideoPlayer: ${e.toString()}"); + } + Utils.hideLoading(context); + Navigator.pushNamed(context, AppRoutes.marathonIntroScreen); + } + } else { + Navigator.pushNamed(context, AppRoutes.marathonIntroScreen); + } + }), + ); + // ) + // : const SizedBox(); } } diff --git a/lib/ui/work_list/item_history_screen.dart b/lib/ui/work_list/item_history_screen.dart index 562b59f..a3c34a9 100644 --- a/lib/ui/work_list/item_history_screen.dart +++ b/lib/ui/work_list/item_history_screen.dart @@ -88,7 +88,8 @@ class _ItemHistoryScreenState extends State { children: [ if (moItemHistoryList.isNotEmpty) loadMoItemHistoryData(), if (poItemHistoryList.isNotEmpty) loadPoItemHistoryData(), - if (quotationAnalysisList.isNotEmpty) loadQuotationAnalysisData() + if (quotationAnalysisList.isNotEmpty) loadQuotationAnalysisData(), + if (moItemHistoryList.isEmpty && poItemHistoryList.isEmpty && quotationAnalysisList.isEmpty) Utils.getNoDataWidget(context), ], ), ); From 9602e95fe7b5161a7bd98c06c81a22589bf31b87 Mon Sep 17 00:00:00 2001 From: Sikander Saleem Date: Mon, 19 Dec 2022 09:48:25 +0300 Subject: [PATCH 33/42] improvements --- lib/classes/consts.dart | 4 ++-- lib/extensions/widget_extensions.dart | 2 +- lib/ui/profile/personal_info.dart | 13 ++++++------- lib/ui/profile/profile_screen.dart | 17 +++++++---------- lib/ui/profile/widgets/profile_panel.dart | 4 ++-- 5 files changed, 18 insertions(+), 22 deletions(-) diff --git a/lib/classes/consts.dart b/lib/classes/consts.dart index ac520b1..3d58efd 100644 --- a/lib/classes/consts.dart +++ b/lib/classes/consts.dart @@ -2,9 +2,9 @@ import 'package:mohem_flutter_app/ui/marathon/widgets/question_card.dart'; class ApiConsts { //static String baseUrl = "http://10.200.204.20:2801/"; // Local server - static String baseUrl = "https://uat.hmgwebservices.com"; // UAT server + // static String baseUrl = "https://uat.hmgwebservices.com"; // UAT server // static String baseUrl = "https://erptstapp.srca.org.sa"; // SRCA server - // static String baseUrl = "https://hmgwebservices.com"; // Live server + static String baseUrl = "https://hmgwebservices.com"; // Live server static String baseUrlServices = baseUrl + "/Services/"; // server // static String baseUrlServices = "https://api.cssynapses.com/tangheem/"; // Live server static String utilitiesRest = baseUrlServices + "Utilities.svc/REST/"; diff --git a/lib/extensions/widget_extensions.dart b/lib/extensions/widget_extensions.dart index b52ef3e..a52f11a 100644 --- a/lib/extensions/widget_extensions.dart +++ b/lib/extensions/widget_extensions.dart @@ -58,7 +58,7 @@ extension WidgetExtensions on Widget { ), ], ), - alignment: center == true ? Alignment.center : null, + alignment: center ? Alignment.center : null, child: Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisSize: MainAxisSize.min, diff --git a/lib/ui/profile/personal_info.dart b/lib/ui/profile/personal_info.dart index 79d0995..a4a9700 100644 --- a/lib/ui/profile/personal_info.dart +++ b/lib/ui/profile/personal_info.dart @@ -21,25 +21,24 @@ class PersonalInfo extends StatelessWidget { title: LocaleKeys.profile_personalInformation.tr(), ), backgroundColor: MyColors.backgroundColor, - body: SizedBox( - width: MediaQuery.of(context).size.width, + body: SingleChildScrollView( child: Column( crossAxisAlignment: CrossAxisAlignment.start, - // mainAxisSize: MainAxisSize.min, + mainAxisSize: MainAxisSize.min, mainAxisAlignment: MainAxisAlignment.start, children: [ LocaleKeys.category.tr().toText13(color: MyColors.lightGrayColor), (memberInformationList.eMPLOYMENTCATEGORYMEANING ?? "").toText16(), - 20.height, + 12.height, LocaleKeys.address.tr().toText13(color: MyColors.lightGrayColor), (memberInformationList.lOCATIONNAME ?? "").toText16(), - 20.height, + 12.height, LocaleKeys.phoneNumber.tr().toText13(color: MyColors.lightGrayColor), (memberInformationList.eMPLOYEEMOBILENUMBER ?? "").toText16(), - 20.height, + 12.height, LocaleKeys.businessGroup.tr().toText13(color: MyColors.lightGrayColor), (memberInformationList.bUSINESSGROUPNAME ?? "").toText16(), - 20.height, + 12.height, LocaleKeys.Payroll.tr().toText13(color: MyColors.lightGrayColor), (memberInformationList.pAYROLLNAME ?? "").toText16(), ], diff --git a/lib/ui/profile/profile_screen.dart b/lib/ui/profile/profile_screen.dart index 0a78873..6060cbf 100644 --- a/lib/ui/profile/profile_screen.dart +++ b/lib/ui/profile/profile_screen.dart @@ -1,4 +1,3 @@ -import 'dart:convert'; import 'dart:io'; import 'dart:ui'; @@ -76,15 +75,13 @@ class _ProfileScreenState extends State { Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ - IconButton( - onPressed: () { - Navigator.pop(context); - }, - icon: const Icon( - Icons.arrow_back_ios, - color: Colors.white, - ), - ), + CircleAvatar( + radius: 18, + backgroundColor: Colors.black.withOpacity(.21), + child: const Icon(Icons.arrow_back_ios_rounded, color: Colors.white, size: 18).paddingOnly(right: 4), + ).onPress(() { + Navigator.pop(context); + }), InkWell( onTap: () { // startImageSheet(); diff --git a/lib/ui/profile/widgets/profile_panel.dart b/lib/ui/profile/widgets/profile_panel.dart index 440fbb3..3440cc9 100644 --- a/lib/ui/profile/widgets/profile_panel.dart +++ b/lib/ui/profile/widgets/profile_panel.dart @@ -51,8 +51,8 @@ class ProfilePanel extends StatelessWidget { : ClipOval( child: Image.memory( Utils.dataFromBase64String(memberInformationList.eMPLOYEEIMAGE!), - width: 75, - height: 75, + width: 68, + height: 68, fit: BoxFit.fill, ), ); From 5be9adca31b54bde811b8a22f7bc62b080401830 Mon Sep 17 00:00:00 2001 From: haroon amjad Date: Mon, 19 Dec 2022 15:00:08 +0300 Subject: [PATCH 34/42] fixes --- lib/classes/date_uitl.dart | 2 +- lib/ui/my_team/team_members.dart | 160 ++++++++++++++++--------------- 2 files changed, 83 insertions(+), 79 deletions(-) diff --git a/lib/classes/date_uitl.dart b/lib/classes/date_uitl.dart index a1e52d9..29edb2f 100644 --- a/lib/classes/date_uitl.dart +++ b/lib/classes/date_uitl.dart @@ -40,7 +40,7 @@ class DateUtil { } static DateTime convertSimpleStringDateToDate(String date) { - return DateFormat("MM/dd/yyyy hh:mm:ss").parse(date); + return DateFormat("MM/dd/yyyy hh:mm:ss a").parse(date.toUpperCase()); } static DateTime convertSimpleStringDateToDateddMMyyyy(String date) { diff --git a/lib/ui/my_team/team_members.dart b/lib/ui/my_team/team_members.dart index f6d33d8..c4defc4 100644 --- a/lib/ui/my_team/team_members.dart +++ b/lib/ui/my_team/team_members.dart @@ -15,6 +15,7 @@ import 'package:url_launcher/url_launcher.dart'; class TeamMembers extends StatefulWidget { final String? selectedEmp; + const TeamMembers({this.selectedEmp, Key? key}) : super(key: key); @override @@ -22,8 +23,8 @@ class TeamMembers extends StatefulWidget { } class _TeamMembersState extends State { - String searchEmpEmail =""; - String searchEmpName =""; + String searchEmpEmail = ""; + String searchEmpName = ""; String searchEmpNo = ""; String? empId; @@ -32,14 +33,14 @@ class _TeamMembersState extends State { void initState() { super.initState(); - employeeSubordinates(); + employeeSubordinates(); } void employeeSubordinates() async { try { Utils.showLoading(context); getEmployeeSubordinatesList = await MyTeamApiClient().getEmployeeSubordinates(searchEmpEmail.toString(), searchEmpName.toString(), searchEmpNo.toString()); - getEmployeeSubordinatesList = await MyTeamApiClient().employeeSubordinates(searchEmpEmail.toString(), searchEmpName.toString(), searchEmpNo.toString(),getEmployeeSubordinates?.eMPLOYEENUMBER); + getEmployeeSubordinatesList = await MyTeamApiClient().employeeSubordinates(searchEmpEmail.toString(), searchEmpName.toString(), searchEmpNo.toString(), getEmployeeSubordinates?.eMPLOYEENUMBER); Utils.hideLoading(context); setState(() {}); } catch (ex) { @@ -52,80 +53,83 @@ class _TeamMembersState extends State { Widget build(BuildContext context) { getEmployeeSubordinates ??= ModalRoute.of(context)?.settings.arguments as GetEmployeeSubordinatesList; return Scaffold( - appBar: AppBarWidget( - context, - title: LocaleKeys.teamMembers.tr(), + appBar: AppBarWidget( + context, + title: LocaleKeys.teamMembers.tr(), + ), + backgroundColor: MyColors.backgroundColor, + body: SingleChildScrollView( + scrollDirection: Axis.vertical, + child: Column( + children: [ + getEmployeeSubordinatesList.isEmpty + ? Container(margin: const EdgeInsets.only(top: 100), child: Utils.getNoDataWidget(context)) + : ListView.separated( + shrinkWrap: true, + physics: const NeverScrollableScrollPhysics(), + padding: const EdgeInsets.only(top: 12), + separatorBuilder: (BuildContext cxt, int index) => 12.height, + itemCount: getEmployeeSubordinatesList.length, + itemBuilder: (BuildContext context, int index) { + var phoneNumber = Uri.parse('tel:${getEmployeeSubordinatesList[index].eMPLOYEEMOBILENUMBER}'); + return InkWell( + onTap: () async { + Navigator.pushNamed(context, AppRoutes.employeeDetails, arguments: getEmployeeSubordinatesList[index]); + }, + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + getEmployeeSubordinatesList[index].eMPLOYEEIMAGE == null + ? SvgPicture.asset( + "assets/images/user.svg", + height: 34, + width: 34, + ).paddingOnly(top: 4) + : Container( + height: 34, + width: 34, + child: CircleAvatar( + radius: 25, + backgroundImage: MemoryImage(Utils.dataFromBase64String(getEmployeeSubordinatesList[index].eMPLOYEEIMAGE!)), + backgroundColor: Colors.black, + ).paddingOnly(top: 4), + ), + 9.width, + Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + // "Present".toText13(color: MyColors.greenColor), + "${getEmployeeSubordinatesList[index].eMPLOYEENAME}".toText16(color: MyColors.grey3AColor), + "${getEmployeeSubordinatesList[index].pOSITIONNAME}".toText10(color: MyColors.grey57Color), + ], + ).expanded, + Column( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + crossAxisAlignment: CrossAxisAlignment.end, + children: [ + getEmployeeSubordinatesList[index].eMPLOYEEMOBILENUMBER == "" + ? SvgPicture.asset("assets/images/call-disable.svg", width: 22, height: 22) + : InkWell( + onTap: () { + launchUrl(phoneNumber); + }, + child: SvgPicture.asset("assets/images/call.svg", width: 22, height: 22), + ), + 8.height, + const Icon( + Icons.arrow_forward_outlined, + color: MyColors.grey3AColor, + size: 18, + ), + ], + ), + ], + ).paddingOnly(top: 13, bottom: 13, right: 12, left: 14).objectContainerView(radius: 10, disablePadding: true), + ).paddingOnly(left: 16.0, right: 16.0); + }), + ], ), - backgroundColor: MyColors.backgroundColor, - body: SingleChildScrollView( - scrollDirection: Axis.vertical, - child: Column( - children: [ - getEmployeeSubordinatesList.isEmpty - ? Container( - margin: const EdgeInsets.only(top: 100), - child: Utils.getNoDataWidget(context)): - ListView.separated( - shrinkWrap: true, - physics: const NeverScrollableScrollPhysics(), - padding: const EdgeInsets.only(top: 12), - separatorBuilder: (BuildContext cxt,int index) => 12.height, - itemCount: getEmployeeSubordinatesList.length, - itemBuilder: (BuildContext context, int index) { - var phoneNumber = Uri.parse('tel:${getEmployeeSubordinatesList[index].eMPLOYEEMOBILENUMBER}'); - return InkWell( - onTap: () async { - Navigator.pushNamed(context, AppRoutes.employeeDetails, arguments: getEmployeeSubordinatesList[index]); - }, - child: Row( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - getEmployeeSubordinatesList[index].eMPLOYEEIMAGE == null - ? SvgPicture.asset("assets/images/user.svg",height: 34, width: 34, ).paddingOnly(top: 4) - : Container( - height: 34, - width: 34, - child: CircleAvatar( - radius: 25, - backgroundImage: MemoryImage(Utils.dataFromBase64String(getEmployeeSubordinatesList[index].eMPLOYEEIMAGE!)), - backgroundColor: Colors.black, - ).paddingOnly(top: 4), - ), - 9.width, - Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - // "Present".toText13(color: MyColors.greenColor), - "${getEmployeeSubordinatesList[index].eMPLOYEENAME}".toText16(color: MyColors.grey3AColor), - "${getEmployeeSubordinatesList[index].pOSITIONNAME}".toText10( color: MyColors.grey57Color), - ], - ).expanded, - Column( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - crossAxisAlignment: CrossAxisAlignment.end, - children: [ - getEmployeeSubordinatesList[index].eMPLOYEEMOBILENUMBER == "" - ? SvgPicture.asset("assets/images/call-disable.svg", width: 22, height: 22) - :InkWell( - onTap: () { - launchUrl(phoneNumber); - }, - child: SvgPicture.asset("assets/images/call.svg", width: 22, height: 22), - ), - 8.height, - const Icon( - Icons.arrow_forward_outlined, - color: MyColors.grey3AColor, - size: 18, - ), - ], - ), - ], - ).paddingOnly(top: 13, bottom: 13, right: 12, left: 14).objectContainerView(radius: 10, disablePadding: true), - ); - }), - ], - ) - )); + ), + ); } } From 0077a876d9f260cc90fcbe75b375fce9839c9751 Mon Sep 17 00:00:00 2001 From: Sikander Saleem Date: Mon, 19 Dec 2022 16:29:27 +0300 Subject: [PATCH 35/42] improvements --- lib/generated_plugin_registrant.dart | 2 -- lib/ui/profile/personal_info.dart | 46 +++++++++++++++------------- 2 files changed, 24 insertions(+), 24 deletions(-) diff --git a/lib/generated_plugin_registrant.dart b/lib/generated_plugin_registrant.dart index 288ba42..37be8d8 100644 --- a/lib/generated_plugin_registrant.dart +++ b/lib/generated_plugin_registrant.dart @@ -16,7 +16,6 @@ import 'package:image_picker_for_web/image_picker_for_web.dart'; import 'package:shared_preferences_web/shared_preferences_web.dart'; import 'package:url_launcher_web/url_launcher_web.dart'; import 'package:video_player_web/video_player_web.dart'; -import 'package:wakelock_web/wakelock_web.dart'; import 'package:flutter_web_plugins/flutter_web_plugins.dart'; @@ -32,6 +31,5 @@ void registerPlugins(Registrar registrar) { SharedPreferencesPlugin.registerWith(registrar); UrlLauncherPlugin.registerWith(registrar); VideoPlayerPlugin.registerWith(registrar); - WakelockWeb.registerWith(registrar); registrar.registerMessageHandler(); } diff --git a/lib/ui/profile/personal_info.dart b/lib/ui/profile/personal_info.dart index a4a9700..84e45ff 100644 --- a/lib/ui/profile/personal_info.dart +++ b/lib/ui/profile/personal_info.dart @@ -21,28 +21,30 @@ class PersonalInfo extends StatelessWidget { title: LocaleKeys.profile_personalInformation.tr(), ), backgroundColor: MyColors.backgroundColor, - body: SingleChildScrollView( - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - mainAxisSize: MainAxisSize.min, - mainAxisAlignment: MainAxisAlignment.start, - children: [ - LocaleKeys.category.tr().toText13(color: MyColors.lightGrayColor), - (memberInformationList.eMPLOYMENTCATEGORYMEANING ?? "").toText16(), - 12.height, - LocaleKeys.address.tr().toText13(color: MyColors.lightGrayColor), - (memberInformationList.lOCATIONNAME ?? "").toText16(), - 12.height, - LocaleKeys.phoneNumber.tr().toText13(color: MyColors.lightGrayColor), - (memberInformationList.eMPLOYEEMOBILENUMBER ?? "").toText16(), - 12.height, - LocaleKeys.businessGroup.tr().toText13(color: MyColors.lightGrayColor), - (memberInformationList.bUSINESSGROUPNAME ?? "").toText16(), - 12.height, - LocaleKeys.Payroll.tr().toText13(color: MyColors.lightGrayColor), - (memberInformationList.pAYROLLNAME ?? "").toText16(), - ], - ).objectContainerView().paddingAll(21), + body: ListView( + children: [ + Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + mainAxisAlignment: MainAxisAlignment.start, + children: [ + LocaleKeys.category.tr().toText13(color: MyColors.lightGrayColor), + (memberInformationList.eMPLOYMENTCATEGORYMEANING ?? "").toText16(), + 12.height, + LocaleKeys.address.tr().toText13(color: MyColors.lightGrayColor), + (memberInformationList.lOCATIONNAME ?? "").toText16(), + 12.height, + LocaleKeys.phoneNumber.tr().toText13(color: MyColors.lightGrayColor), + (memberInformationList.eMPLOYEEMOBILENUMBER ?? "").toText16(), + 12.height, + LocaleKeys.businessGroup.tr().toText13(color: MyColors.lightGrayColor), + (memberInformationList.bUSINESSGROUPNAME ?? "").toText16(), + 12.height, + LocaleKeys.Payroll.tr().toText13(color: MyColors.lightGrayColor), + (memberInformationList.pAYROLLNAME ?? "").toText16(), + ], + ).objectContainerView(center: false).paddingAll(21), + ], ), ); } From e40cd2c5c82616367a664f5c5899d38d2c3c4e6f Mon Sep 17 00:00:00 2001 From: "Aamir.Muhammad" Date: Mon, 19 Dec 2022 16:49:04 +0300 Subject: [PATCH 36/42] Chat Error Handling & Voice --- lib/api/chat/chat_api_client.dart | 11 +- lib/classes/consts.dart | 4 +- lib/provider/chat_provider_model.dart | 143 +++++++++++++++++++- lib/ui/chat/chat_bubble.dart | 78 ++++++++++- lib/ui/chat/chat_detailed_screen.dart | 186 +++++++++++++++++++------- pubspec.yaml | 4 + 6 files changed, 363 insertions(+), 63 deletions(-) diff --git a/lib/api/chat/chat_api_client.dart b/lib/api/chat/chat_api_client.dart index 5bceb24..409295f 100644 --- a/lib/api/chat/chat_api_client.dart +++ b/lib/api/chat/chat_api_client.dart @@ -33,11 +33,12 @@ class ChatApiClient { }, ); if (!kReleaseMode) { + print("Status Code is ================" + response.statusCode.toString()); logger.i("res: " + response.body); } if (response.statusCode == 200) { userLoginResponse = user.userAutoLoginModelFromJson(response.body); - } else if (response.statusCode == 504) { + } else if (response.statusCode == 501 || response.statusCode == 502 || response.statusCode == 503 || response.statusCode == 504) { getUserLoginToken(); } else { userLoginResponse = user.userAutoLoginModelFromJson(response.body); @@ -141,11 +142,16 @@ class ChatApiClient { // Download File For Chat Future downloadURL({required String fileName, required String fileTypeDescription}) async { + print(fileName); + print(fileTypeDescription); + print("${ApiConsts.chatMediaImageUploadUrl}download"); + print(AppState().chatDetails!.response!.token); Response response = await ApiClient().postJsonForResponse( "${ApiConsts.chatMediaImageUploadUrl}download", {"fileType": fileTypeDescription, "fileName": fileName, "fileSource": 1}, token: AppState().chatDetails!.response!.token, ); + Uint8List data = Uint8List.fromList(response.bodyBytes); return data; } @@ -159,11 +165,10 @@ class ChatApiClient { ); if (!kReleaseMode) { logger.i("res: " + response.body); - print("Images Status Coe is ============== " + response.statusCode.toString()); } if (response.statusCode == 200) { imagesData = chatUserImageModelFromJson(response.body); - } else if (response.statusCode == 504 || response.statusCode == 500) { + } else if (response.statusCode == 500 || response.statusCode == 504) { getUsersImages(encryptedEmails: encryptedEmails); } else { Utils.showToast("Something went wrong while loading images"); diff --git a/lib/classes/consts.dart b/lib/classes/consts.dart index 0559996..c147ea3 100644 --- a/lib/classes/consts.dart +++ b/lib/classes/consts.dart @@ -3,8 +3,8 @@ import 'package:mohem_flutter_app/ui/marathon/widgets/question_card.dart'; class ApiConsts { //static String baseUrl = "http://10.200.204.20:2801/"; // Local server // static String baseUrl = "https://erptstapp.srca.org.sa"; // SRCA server - static String baseUrl = "https://uat.hmgwebservices.com"; // UAT server - // static String baseUrl = "https://hmgwebservices.com"; // Live server + //static String baseUrl = "https://uat.hmgwebservices.com"; // UAT server + static String baseUrl = "https://hmgwebservices.com"; // Live server static String baseUrlServices = baseUrl + "/Services/"; // server // static String baseUrlServices = "https://api.cssynapses.com/tangheem/"; // Live server static String utilitiesRest = baseUrlServices + "Utilities.svc/REST/"; diff --git a/lib/provider/chat_provider_model.dart b/lib/provider/chat_provider_model.dart index a62016f..5f28b0b 100644 --- a/lib/provider/chat_provider_model.dart +++ b/lib/provider/chat_provider_model.dart @@ -2,18 +2,20 @@ import 'dart:async'; import 'dart:convert'; import 'dart:io'; import 'dart:typed_data'; +import 'package:audio_waveforms/audio_waveforms.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/foundation.dart'; +import 'package:flutter/services.dart'; import 'package:http/http.dart'; -import 'package:just_audio/just_audio.dart'; +import 'package:just_audio/just_audio.dart' as JustAudio; import 'package:mohem_flutter_app/api/chat/chat_api_client.dart'; import 'package:mohem_flutter_app/app_state/app_state.dart'; +import 'package:mohem_flutter_app/classes/app_permissions.dart'; import 'package:mohem_flutter_app/classes/consts.dart'; import 'package:mohem_flutter_app/classes/encryption.dart'; import 'package:mohem_flutter_app/classes/utils.dart'; import 'package:mohem_flutter_app/main.dart'; -import 'package:mohem_flutter_app/models/chat/chat_count_conversation_model.dart'; import 'package:mohem_flutter_app/models/chat/chat_user_image_model.dart'; import 'package:mohem_flutter_app/models/chat/get_search_user_chat_model.dart'; import 'package:mohem_flutter_app/models/chat/get_single_user_chat_list_model.dart'; @@ -23,6 +25,7 @@ import 'package:mohem_flutter_app/ui/landing/dashboard_screen.dart'; import 'package:mohem_flutter_app/widgets/image_picker.dart'; import 'package:open_file/open_file.dart'; import 'package:path_provider/path_provider.dart'; +import 'package:permission_handler/permission_handler.dart'; import 'package:signalr_netcore/hub_connection.dart'; import 'package:signalr_netcore/signalr_client.dart'; import 'package:uuid/uuid.dart'; @@ -37,7 +40,6 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { bool isLoading = true; bool isChatScreenActive = false; int receiverID = 0; - late File selectedFile; bool isFileSelected = false; String sFileType = ""; @@ -53,9 +55,13 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { Future getUserAutoLoginToken() async { userLoginToken.UserAutoLoginModel userLoginResponse = await ChatApiClient().getUserLoginToken(); + print("======================================= Chat Login Token Check ====================================="); + logger.d(userLoginResponse.toJson()); + print("======================================= Chat Login Token Check ====================================="); if (userLoginResponse.response != null) { AppState().setchatUserDetails = userLoginResponse; } else { + AppState().setchatUserDetails = userLoginResponse; Utils.showToast( userLoginResponse.errorResponses!.first.fieldName.toString() + " Erorr", ); @@ -903,7 +909,7 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { } void setMsgTune() async { - AudioPlayer player = AudioPlayer(); + JustAudio.AudioPlayer player = JustAudio.AudioPlayer(); await player.setVolume(1.0); String audioAsset = ""; if (Platform.isAndroid) { @@ -949,4 +955,133 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { logger.d([reciptUser, currentUser]); await chatHubConnection.invoke("UserTypingAsync", args: [reciptUser, currentUser]); } + + // Audio Recoding Work + Timer? _timer; + int _recodeDuration = 0; + bool isRecoding = false; + bool isPause = false; + bool isPlaying = false; + String? path; + String? musicFile; + late Directory appDirectory; + late RecorderController recorderController; + late PlayerController playerController; + + //////// Audio Recoding Work //////////////////// + + Future initAudio() async { + appDirectory = await getApplicationDocumentsDirectory(); + path = "${appDirectory.path}/${AppState().chatDetails!.response!.id}-${DateTime.now().microsecondsSinceEpoch}.aac"; + recorderController = RecorderController() + ..androidEncoder = AndroidEncoder.aac + ..androidOutputFormat = AndroidOutputFormat.mpeg4 + ..iosEncoder = IosEncoder.kAudioFormatMPEG4AAC + ..sampleRate = 8000 + ..bitRate = 32000; + playerController = PlayerController(); + } + + void disposeAudio() { + isRecoding = false; + isPlaying = false; + isPause = false; + recorderController.dispose(); + playerController.dispose(); + } + + void startRecoding() async { + PermissionStatus status = await Permission.microphone.request(); + print(status); + if (status.isDenied == true) { + startRecoding(); + } else { + recorderController.reset(); + await recorderController.record(path); + _recodeDuration = 0; + _startTimer(); + isRecoding = !isRecoding; + notifyListeners(); + } + } + + void _startTimer() { + _timer?.cancel(); + _timer = Timer.periodic(const Duration(seconds: 1), (Timer t) { + _recodeDuration++; + buildTimer(); + notifyListeners(); + }); + } + + Future pauseRecoding() async { + isPause = true; + isPlaying = true; + recorderController.pause(); + path = await recorderController.stop(false); + print(path); + File file = File(path!); + file.readAsBytesSync(); + await playerController.preparePlayer(file.path, 1.0); + var tempDuration = _recodeDuration; + _recodeDuration = tempDuration; + _timer?.cancel(); + notifyListeners(); + } + + void resumeRecoding() { + isPause = false; + isPlaying = false; + isRecoding = true; + recorderController.record(path); + _startTimer(); + } + + Future deleteRecoding() async { + print(path); + _recodeDuration = 0; + _timer?.cancel(); + // path = await recorderController.stop(false); + recorderController.reset(); + print(path); + if (path != null && path!.isNotEmpty) { + File delFile = File(path!); + double fileSizeInKB = delFile.lengthSync() / 1024; + double fileSizeInMB = fileSizeInKB / 1024; + debugPrint("Deleted file size: ${delFile.lengthSync()}"); + debugPrint("Deleted file size in KB: " + fileSizeInKB.toString()); + debugPrint("Deleted file size in MB: " + fileSizeInMB.toString()); + if (await delFile.exists()) { + delFile.delete(); + } + isPause = false; + isRecoding = false; + isPlaying = false; + notifyListeners(); + } + } + + String buildTimer() { + String minutes = _formatNum(_recodeDuration ~/ 60); + String seconds = _formatNum(_recodeDuration % 60); + return '$minutes : $seconds'; + } + + String _formatNum(int number) { + String numberStr = number.toString(); + if (number < 10) { + numberStr = '0' + numberStr; + } + return numberStr; + } + + void playRecoding() async { + isPlaying = true; + await playerController.startPlayer(finishMode: FinishMode.stop); + } + + void playOrPause() async { + playerController.playerState == PlayerState.playing ? await playerController.pausePlayer() : playRecoding(); + notifyListeners(); + } } diff --git a/lib/ui/chat/chat_bubble.dart b/lib/ui/chat/chat_bubble.dart index 8978ff1..06afecf 100644 --- a/lib/ui/chat/chat_bubble.dart +++ b/lib/ui/chat/chat_bubble.dart @@ -1,6 +1,7 @@ import 'dart:convert'; import 'dart:typed_data'; +import 'package:audio_waveforms/audio_waveforms.dart'; import 'package:flutter/material.dart'; import 'package:flutter_svg/flutter_svg.dart'; import 'package:mohem_flutter_app/api/api_client.dart'; @@ -120,10 +121,14 @@ class ChatBubble extends StatelessWidget { else Row( children: [ - if (fileTypeID == 1 || fileTypeID == 5 || fileTypeID == 7 || fileTypeID == 6 || fileTypeID == 8 || fileTypeID == 2) + if (fileTypeID == 1 || fileTypeID == 5 || fileTypeID == 7 || fileTypeID == 6 || fileTypeID == 8 + // || fileTypeID == 2 + ) SvgPicture.asset(data.getType(fileTypeName ?? ""), height: 30, width: 22, alignment: Alignment.center, fit: BoxFit.cover).paddingOnly(left: 0, right: 10), (cItem.contant ?? "").toText12().expanded, - if (fileTypeID == 1 || fileTypeID == 5 || fileTypeID == 7 || fileTypeID == 6 || fileTypeID == 8 || fileTypeID == 2) const Icon(Icons.remove_red_eye, size: 16) + if (fileTypeID == 1 || fileTypeID == 5 || fileTypeID == 7 || fileTypeID == 6 || fileTypeID == 8 + //|| fileTypeID == 2 + ) const Icon(Icons.remove_red_eye, size: 16) ], ), Align( @@ -217,10 +222,15 @@ class ChatBubble extends StatelessWidget { else Row( children: [ - if (fileTypeID == 1 || fileTypeID == 5 || fileTypeID == 7 || fileTypeID == 6 || fileTypeID == 8 || fileTypeID == 2) + if (fileTypeID == 1 || fileTypeID == 5 || fileTypeID == 7 || fileTypeID == 6 || fileTypeID == 8 + // || fileTypeID == 2 + ) SvgPicture.asset(data.getType(fileTypeName ?? ""), height: 30, width: 22, alignment: Alignment.center, fit: BoxFit.cover).paddingOnly(left: 0, right: 10), (cItem.contant ?? "").toText12(color: Colors.white).expanded, - if (fileTypeID == 1 || fileTypeID == 5 || fileTypeID == 7 || fileTypeID == 6 || fileTypeID == 8 || fileTypeID == 2) const Icon(Icons.remove_red_eye, color: Colors.white, size: 16) + if (fileTypeID == 1 || fileTypeID == 5 || fileTypeID == 7 || fileTypeID == 6 || fileTypeID == 8 + //|| fileTypeID == 2 + ) + const Icon(Icons.remove_red_eye, color: Colors.white, size: 16) ], ), Align( @@ -274,3 +284,63 @@ class ChatBubble extends StatelessWidget { } } } + +class WaveBubble extends StatelessWidget { + final PlayerController playerController; + final VoidCallback onTap; + final bool isPlaying; + + const WaveBubble({ + Key? key, + required this.playerController, + required this.onTap, + required this.isPlaying, + }) : super(key: key); + + @override + Widget build(BuildContext context) { + return Container( + margin: const EdgeInsets.all(10), + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(30), + gradient: const LinearGradient( + transform: GradientRotation(.83), + begin: Alignment.topRight, + end: Alignment.bottomLeft, + colors: [ + MyColors.gradiantEndColor, + MyColors.gradiantStartColor, + ], + ), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + IconButton( + onPressed: onTap, + icon: Icon(isPlaying ? Icons.stop : Icons.play_arrow), + color: Colors.white, + splashColor: Colors.transparent, + highlightColor: Colors.transparent, + ), + AudioFileWaveforms( + size: Size(MediaQuery.of(context).size.width / 2, 10), + playerController: playerController, + padding: EdgeInsets.zero, + margin: EdgeInsets.zero, + playerWaveStyle: const PlayerWaveStyle( + fixedWaveColor: Colors.white, + liveWaveColor:MyColors.lightGreenColor, + showTop: true, + showBottom: true, + waveCap: StrokeCap.round, + seekLineThickness: 3, + visualizerHeight: 6, + backgroundColor: Colors.transparent + ), + ), + ], + ), + ); + } +} diff --git a/lib/ui/chat/chat_detailed_screen.dart b/lib/ui/chat/chat_detailed_screen.dart index 379fe2b..5d3648e 100644 --- a/lib/ui/chat/chat_detailed_screen.dart +++ b/lib/ui/chat/chat_detailed_screen.dart @@ -1,6 +1,7 @@ import 'dart:async'; import 'dart:convert'; +import 'package:audio_waveforms/audio_waveforms.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:flutter_svg/flutter_svg.dart'; @@ -62,6 +63,12 @@ class _ChatDetailScreenState extends State { _rc.loadComplete(); } + @override + void dispose() { + data.disposeAudio(); + super.dispose(); + } + @override Widget build(BuildContext context) { params = ModalRoute.of(context)!.settings.arguments as ChatDetailedScreenParams; @@ -73,6 +80,7 @@ class _ChatDetailScreenState extends State { loadMore: false, isNewChat: params!.isNewChat!, ); + data.initAudio(); } return Scaffold( @@ -181,62 +189,140 @@ class _ChatDetailScreenState extends State { height: 1, color: MyColors.lightGreyEFColor, ), - TextField( - controller: m.message, - decoration: InputDecoration( - hintText: m.isFileSelected ? m.selectedFile.path.split("/").last : LocaleKeys.typeheretoreply.tr(), - hintStyle: TextStyle(color: m.isFileSelected ? MyColors.darkTextColor : MyColors.grey98Color, fontSize: 14), - border: InputBorder.none, - focusedBorder: InputBorder.none, - enabledBorder: InputBorder.none, - errorBorder: InputBorder.none, - disabledBorder: InputBorder.none, - filled: true, - fillColor: MyColors.white, - contentPadding: const EdgeInsets.only( - left: 21, - top: 20, - bottom: 20, - ), - prefixIconConstraints: const BoxConstraints(), - prefixIcon: m.sFileType.isNotEmpty - ? SvgPicture.asset(m.getType(m.sFileType), height: 30, width: 22, alignment: Alignment.center, fit: BoxFit.cover).paddingOnly(left: 21, right: 15) - : null, - suffixIcon: SizedBox( - width: 100, - child: Row( - mainAxisAlignment: MainAxisAlignment.end, - crossAxisAlignment: CrossAxisAlignment.center, // added line - children: [ - if (m.sFileType.isNotEmpty) - Row( - children: [ - const Icon(Icons.cancel, size: 15, color: MyColors.redA3Color).paddingOnly(right: 5), - ("Clear").toText11(color: MyColors.redA3Color, isUnderLine: true).paddingOnly(left: 0), - ], - ).onPress(() => m.removeAttachment()).paddingOnly(right: 25), - if (m.sFileType.isEmpty) - RotationTransition( - turns: const AlwaysStoppedAnimation(45 / 360), - child: const Icon(Icons.attach_file_rounded, size: 26, color: MyColors.grey3AColor).onPress( - () => m.selectImageToUpload(context), + if (m.isRecoding) + Column( + children: [ + Row( + children: [ + Text(m.buildTimer()).paddingAll(10), + if (m.isRecoding && m.isPlaying) + WaveBubble( + playerController: m.playerController, + onTap: () { + m.playOrPause(); + }, + isPlaying: m.playerController.playerState == PlayerState.playing) + .expanded + else + AudioWaveforms( + waveStyle: const WaveStyle( + waveColor: MyColors.lightGreenColor, + middleLineColor: Colors.transparent, + extendWaveform: true, + showBottom: true, + showTop: true, + waveThickness: 2, + showMiddleLine: false, + middleLineThickness: 0, ), - ).paddingOnly(right: 25), - SvgPicture.asset("assets/icons/chat/chat_send_icon.svg", height: 26, width: 26).onPress( + padding: const EdgeInsets.all(5), + shouldCalculateScrolledPosition: false, + margin: EdgeInsets.zero, + size: const Size(double.infinity, 30.0), + recorderController: m.recorderController, + backgroundColor: Colors.white, + ).expanded, + ], + ), + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + const Icon( + Icons.delete_outlined, + size: 26, + color: MyColors.lightGreenColor, + ).paddingAll(10).onPress(() { + m.deleteRecoding(); + }), + if (m.isPause) + const Icon( + Icons.mic, + size: 26, + color: MyColors.lightGreenColor, + ).paddingOnly(right: 15).onPress(() { + m.resumeRecoding(); + }), + if (!m.isPause) + const Icon( + Icons.pause_circle_outline, + size: 26, + color: MyColors.lightGreenColor, + ).paddingOnly(right: 15).onPress(() { + m.pauseRecoding(); + }), + SvgPicture.asset("assets/icons/chat/chat_send_icon.svg", height: 26, width: 26) + .onPress( + () => m.sendChatMessage(context, + targetUserId: params!.chatUser!.id!, + userStatus: params!.chatUser!.userStatus ?? 0, + userEmail: params!.chatUser!.email!, + targetUserName: params!.chatUser!.userName!), + ) + .paddingOnly(right: 21), + ], + ), + ], + ).objectContainerView(disablePadding: true, radius: 0), + if (!m.isRecoding) + Row( + children: [ + TextField( + controller: m.message, + decoration: InputDecoration( + hintText: m.isFileSelected ? m.selectedFile.path.split("/").last : LocaleKeys.typeheretoreply.tr(), + hintStyle: TextStyle(color: m.isFileSelected ? MyColors.darkTextColor : MyColors.grey98Color, fontSize: 14), + border: InputBorder.none, + focusedBorder: InputBorder.none, + enabledBorder: InputBorder.none, + errorBorder: InputBorder.none, + disabledBorder: InputBorder.none, + filled: true, + fillColor: MyColors.white, + contentPadding: const EdgeInsets.only( + left: 21, + top: 20, + bottom: 20, + ), + prefixIconConstraints: const BoxConstraints(), + prefixIcon: m.sFileType.isNotEmpty + ? SvgPicture.asset(m.getType(m.sFileType), height: 30, width: 22, alignment: Alignment.center, fit: BoxFit.cover).paddingOnly(left: 21, right: 15) + : null, + ), + onChanged: (val) { + m.userTypingInvoke(currentUser: AppState().chatDetails!.response!.id!, reciptUser: params!.chatUser!.id!); + }, + ).expanded, + if (m.sFileType.isNotEmpty) + Row( + children: [ + const Icon(Icons.cancel, size: 15, color: MyColors.redA3Color).paddingOnly(right: 5), + ("Clear").toText11(color: MyColors.redA3Color, isUnderLine: true).paddingOnly(left: 0), + ], + ).onPress(() => m.removeAttachment()).paddingOnly(right: 15), + if (m.sFileType.isEmpty) + RotationTransition( + turns: const AlwaysStoppedAnimation(45 / 360), + child: const Icon(Icons.attach_file_rounded, size: 26, color: MyColors.grey3AColor).onPress( + () => m.selectImageToUpload(context), + ), + ).paddingOnly(right: 15), + Icon( + Icons.mic, + color: MyColors.lightGreenColor, + ).paddingOnly(right: 15).onPress(() { + m.startRecoding(); + }), + SvgPicture.asset("assets/icons/chat/chat_send_icon.svg", height: 26, width: 26) + .onPress( () => m.sendChatMessage(context, targetUserId: params!.chatUser!.id!, userStatus: params!.chatUser!.userStatus ?? 0, userEmail: params!.chatUser!.email!, targetUserName: params!.chatUser!.userName!), - ), - ], - ), - ).paddingOnly(right: 21), - ), - onChanged: (val) { - m.userTypingInvoke(currentUser: AppState().chatDetails!.response!.id!, reciptUser: params!.chatUser!.id!); - }, - ), + ) + .paddingOnly(right: 21), + ], + ).objectContainerView(disablePadding: true, radius: 0), ], )); }, diff --git a/pubspec.yaml b/pubspec.yaml index baa5e9f..c0b77bb 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -92,6 +92,10 @@ dependencies: swipe_to: ^1.0.2 flutter_webrtc: ^0.9.16 camera: ^0.10.0+4 + + #Chat Voice Message Recoding & Play + record: ^4.4.3 + audio_waveforms: ^0.1.5+1 # animated_text_kit: ^4.2.2 #Encryption From 696a6881c4ba38a61eff6398089eaf554a87b6cf Mon Sep 17 00:00:00 2001 From: haroon amjad Date: Tue, 20 Dec 2022 15:23:03 +0300 Subject: [PATCH 37/42] date fixes & Items of sale updates --- lib/classes/date_uitl.dart | 26 +++++++++++++++++-- .../fragments/my_posted_ads_fragment.dart | 19 ++++++++++---- pubspec.yaml | 2 +- 3 files changed, 39 insertions(+), 8 deletions(-) diff --git a/lib/classes/date_uitl.dart b/lib/classes/date_uitl.dart index 29edb2f..ec5358d 100644 --- a/lib/classes/date_uitl.dart +++ b/lib/classes/date_uitl.dart @@ -6,7 +6,6 @@ class DateUtil { /// /// - static DateTime convertStringToDateMarathon(String date) { // /Date(1585774800000+0300)/ if (date != null) { @@ -40,7 +39,30 @@ class DateUtil { } static DateTime convertSimpleStringDateToDate(String date) { - return DateFormat("MM/dd/yyyy hh:mm:ss a").parse(date.toUpperCase()); + // print(date.toUpperCase()); + return getDateTimeFromString(date.split(" ")[0], date.toUpperCase().split(" ")[1] + " " + date.toUpperCase().split(" ")[2]); + } + + static DateTime getDateTimeFromString(String date, String time) { + var hours = num.parse(time.split(":")[0]); + var mins = time.split(":")[1]; + var secs = time.split(":")[2].split(" ")[0]; + + String meridium = time.split(" ")[1]; + if (meridium == "PM") { + if (hours != 12) { + hours = hours + 12; + } + } + if (meridium == "AM") { + if (hours == 12) { + hours = 00; + } + } + date = date + " $hours:$mins:$secs"; + DateTime returnDate = DateFormat("MM/dd/yyyy HH:mm:ss").parse(date); + + return returnDate; } static DateTime convertSimpleStringDateToDateddMMyyyy(String date) { diff --git a/lib/ui/screens/items_for_sale/fragments/my_posted_ads_fragment.dart b/lib/ui/screens/items_for_sale/fragments/my_posted_ads_fragment.dart index 64b8bf9..02db148 100644 --- a/lib/ui/screens/items_for_sale/fragments/my_posted_ads_fragment.dart +++ b/lib/ui/screens/items_for_sale/fragments/my_posted_ads_fragment.dart @@ -141,7 +141,7 @@ class _MyPostedAdsFragmentState extends State { Row( children: [ LocaleKeys.remove.tr().toText12(color: MyColors.redColor).center.onPress(() { - updateItemForSale(employeePostedAdsList[index].itemSaleID!); + updateItemForSale(employeePostedAdsList[index]); }).expanded, Container(width: 1, height: 30, color: MyColors.lightGreyEFColor), LocaleKeys.edit.tr().toText12(color: MyColors.gradiantEndColor).center.onPress(() { @@ -172,7 +172,7 @@ class _MyPostedAdsFragmentState extends State { ); } - void updateItemForSale(int itemSaleID) async { + void updateItemForSale(EmployeePostedAds employeePostedAds) async { Utils.showLoading(context); String? empNum = AppState().memberInformationList?.eMPLOYEENUMBER; @@ -180,15 +180,24 @@ class _MyPostedAdsFragmentState extends State { String? loginTokenID = AppState().postParamsObject?.logInTokenID; String? tokenID = AppState().postParamsObject?.tokenID; - var request = http.MultipartRequest('POST', Uri.parse("${ApiConsts.cocRest}Mohemm_ITG_UpdateItemForSale")); - request.fields['itemSaleID'] = itemSaleID.toString(); + var request = http.MultipartRequest('POST', Uri.parse("${ApiConsts.cocRest}Mohemm_ITG_UpdateItemForSaleMobile")); + request.fields['ItgItemSaleID'] = employeePostedAds.itemSaleID.toString(); + request.fields['ItgCategoryID'] = employeePostedAds.categoryID.toString(); + request.fields['ItgTitle'] = employeePostedAds.title!; + request.fields['ItgDescription'] = employeePostedAds.description!; + request.fields['ItgQuotePrice'] = employeePostedAds.quotePrice.toString(); + request.fields['RegionID'] = employeePostedAds.regionID.toString(); + request.fields['Itg_EndDate'] = employeePostedAds.endDate.toString(); request.fields['Channel'] = "31"; - request.fields['isActive'] = "false"; + request.fields['ItgIsActive'] = "false"; request.fields['LogInToken'] = loginTokenID!; request.fields['Token'] = tokenID!; request.fields['MobileNo'] = empMobNum!; request.fields['EmployeeNumber'] = empNum!; request.fields['employeeNumber'] = empNum; + + // debugPrint(json.encode(request.fields.toString())); + var response = await request.send().catchError((e) { Utils.hideLoading(context); Utils.handleException(e, context, null); diff --git a/pubspec.yaml b/pubspec.yaml index c0b77bb..2f3fffa 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -94,7 +94,7 @@ dependencies: camera: ^0.10.0+4 #Chat Voice Message Recoding & Play - record: ^4.4.3 +# record: ^4.4.3 audio_waveforms: ^0.1.5+1 # animated_text_kit: ^4.2.2 From fe02776a69223e0e55e83b69beca2de9d180ae7f Mon Sep 17 00:00:00 2001 From: Sikander Saleem Date: Wed, 21 Dec 2022 12:29:29 +0300 Subject: [PATCH 38/42] leave balance issues fixed. --- lib/api/dashboard_api_client.dart | 10 +- lib/api/leave_balance_api_client.dart | 61 ++++----- lib/api/my_attendance_api_client.dart | 28 +--- lib/classes/consts.dart | 4 +- .../add_leave_balance_screen.dart | 121 +++++++++--------- .../leave_balance/leave_balance_screen.dart | 111 ++++++++-------- .../dynamic_screens/dynamic_input_screen.dart | 19 ++- .../dynamic_listview_screen.dart | 7 +- .../services_menu_list_screen.dart | 9 +- lib/ui/my_team/create_request.dart | 3 +- lib/widgets/balances_dashboard_widget.dart | 19 ++- 11 files changed, 171 insertions(+), 221 deletions(-) diff --git a/lib/api/dashboard_api_client.dart b/lib/api/dashboard_api_client.dart index 5f2ad7e..95631a9 100644 --- a/lib/api/dashboard_api_client.dart +++ b/lib/api/dashboard_api_client.dart @@ -1,12 +1,10 @@ import 'dart:async'; import 'dart:convert'; -import 'package:http/http.dart'; import 'package:mohem_flutter_app/api/api_client.dart'; import 'package:mohem_flutter_app/app_state/app_state.dart'; import 'package:mohem_flutter_app/classes/consts.dart'; import 'package:mohem_flutter_app/classes/date_uitl.dart'; -import 'package:mohem_flutter_app/models/chat/chat_count_conversation_model.dart'; import 'package:mohem_flutter_app/models/dashboard/get_accrual_balances_list_model.dart'; import 'package:mohem_flutter_app/models/dashboard/get_attendance_tracking_list_model.dart'; import 'package:mohem_flutter_app/models/dashboard/itg_forms_model.dart'; @@ -14,7 +12,6 @@ import 'package:mohem_flutter_app/models/dashboard/list_menu.dart'; import 'package:mohem_flutter_app/models/generic_response_model.dart'; import 'package:mohem_flutter_app/models/itg/itg_main_response.dart'; import 'package:mohem_flutter_app/models/itg/itg_response_model.dart'; - import 'package:uuid/uuid.dart'; class DashboardApiClient { @@ -47,7 +44,6 @@ class DashboardApiClient { Future getCOCNotifications() async { String url = "${ApiConsts.cocRest}Mohemm_ITG_ReviewerAdmin_Pending_Tasks"; Map postParams = {"Date": DateUtil.getISODateFormat(DateTime.now()), "EmployeeNumber": AppState().memberInformationList?.eMPLOYEENUMBER}; - postParams.addAll(AppState().postParamsJson); return await ApiClient().postJsonForObject((json) { GenericResponseModel responseData = GenericResponseModel.fromJson(json); @@ -69,9 +65,7 @@ class DashboardApiClient { String url = "${ApiConsts.erpRest}GET_ACCRUAL_BALANCES"; Map postParams = {"P_EFFECTIVE_DATE": effectiveDate}; postParams.addAll(AppState().postParamsJson); - if (empID != null && empID.isNotEmpty) { - postParams['P_SELECTED_EMPLOYEE_NUMBER'] = empID; - } + if (empID != null) postParams["P_SELECTED_EMPLOYEE_NUMBER"] = empID; return await ApiClient().postJsonForObject((json) { GenericResponseModel responseData = GenericResponseModel.fromJson(json); return responseData.getAccrualBalancesList ?? []; @@ -205,8 +199,6 @@ class DashboardApiClient { }, url, postParams); } - - // Future setAdvertisementViewed(String masterID, int advertisementId) async { // String url = "${ApiConsts.cocRest}Mohemm_ITG_UpdateAdvertisementAsViewed"; // diff --git a/lib/api/leave_balance_api_client.dart b/lib/api/leave_balance_api_client.dart index f9c5e21..ae855ee 100644 --- a/lib/api/leave_balance_api_client.dart +++ b/lib/api/leave_balance_api_client.dart @@ -17,13 +17,11 @@ class LeaveBalanceApiClient { factory LeaveBalanceApiClient() => _instance; - Future> getAbsenceTransactions(int pSelectedResopID, {String? empID}) async { + Future> getAbsenceTransactions(int pSelectedResopID, String? empID) async { String url = "${ApiConsts.erpRest}GET_ABSENCE_TRANSACTIONS"; Map postParams = {"P_PAGE_LIMIT": 50, "P_PAGE_NUM": 1, "P_MENU_TYPE": "E", "P_SELECTED_RESP_ID": pSelectedResopID}; postParams.addAll(AppState().postParamsJson); - if (empID!.isNotEmpty) { - postParams['P_SELECTED_EMPLOYEE_NUMBER'] = empID; - } + if (empID != null) postParams["P_SELECTED_EMPLOYEE_NUMBER"] = empID; return await ApiClient().postJsonForObject((json) { GenericResponseModel? responseData = GenericResponseModel.fromJson(json); return responseData.getAbsenceTransactionList ?? []; @@ -34,16 +32,15 @@ class LeaveBalanceApiClient { String url = "${ApiConsts.erpRest}GET_ABSENCE_ATTENDANCE_TYPES"; Map postParams = {}; postParams.addAll(AppState().postParamsJson); - if (empID!.isNotEmpty) { - postParams['P_SELECTED_EMPLOYEE_NUMBER'] = empID; - } + if (empID != null) postParams["P_SELECTED_EMPLOYEE_NUMBER"] = empID; + return await ApiClient().postJsonForObject((json) { GenericResponseModel? responseData = GenericResponseModel.fromJson(json); return responseData.getAbsenceAttendanceTypesList ?? []; }, url, postParams); } - Future calculateAbsenceDuration(int pAbsenceAttendanceTypeID, String pDateStart, String pDateEnd, int pSelectedResopID, {String? empID}) async { + Future calculateAbsenceDuration(int pAbsenceAttendanceTypeID, String pDateStart, String pDateEnd, int pSelectedResopID, {String? empID}) async { String url = "${ApiConsts.erpRest}CALCULATE_ABSENCE_DURATION"; Map postParams = { "P_ABSENCE_ATTENDANCE_TYPE_ID": pAbsenceAttendanceTypeID, @@ -52,25 +49,26 @@ class LeaveBalanceApiClient { "P_SELECTED_RESP_ID": pSelectedResopID, "P_MENU_TYPE": "E", "P_TIME_END": null, - "P_TIME_START": null, + "P_TIME_START": null }; postParams.addAll(AppState().postParamsJson); - if (empID!.isNotEmpty) { - postParams['P_SELECTED_EMPLOYEE_NUMBER'] = empID; - } + if (empID != null) postParams["P_SELECTED_EMPLOYEE_NUMBER"] = empID; return await ApiClient().postJsonForObject((json) { GenericResponseModel? responseData = GenericResponseModel.fromJson(json); return responseData.calculateAbsenceDuration!; }, url, postParams); } - Future> getAbsenceDffStructure(String pDescFlexContextCode, String pFunctionName, int pSelectedResopID, {String? empID}) async { + Future> getAbsenceDffStructure(String pDescFlexContextCode, String pFunctionName, int pSelectedResopID, {String? empID}) async { String url = "${ApiConsts.erpRest}GET_ABSENCE_DFF_STRUCTURE"; - Map postParams = {"P_DESC_FLEX_CONTEXT_CODE": pDescFlexContextCode, "P_FUNCTION_NAME": pFunctionName, "P_MENU_TYPE": "E", "P_SELECTED_RESP_ID": pSelectedResopID}; + Map postParams = { + "P_DESC_FLEX_CONTEXT_CODE": pDescFlexContextCode, + "P_FUNCTION_NAME": pFunctionName, + "P_MENU_TYPE": "E", + "P_SELECTED_RESP_ID": pSelectedResopID, + }; postParams.addAll(AppState().postParamsJson); - if (empID!.isNotEmpty) { - postParams['P_SELECTED_EMPLOYEE_NUMBER'] = empID; - } + if (empID != null) postParams["P_SELECTED_EMPLOYEE_NUMBER"] = empID; return await ApiClient().postJsonForObject((json) { GenericResponseModel? responseData = GenericResponseModel.fromJson(json); return responseData.getAbsenceDffStructureList ?? []; @@ -79,7 +77,7 @@ class LeaveBalanceApiClient { Future validateAbsenceTransaction( String pDescFlexContextCode, String pFunctionName, int pAbsenceAttendanceTypeID, String pReplacementUserName, String pDateStart, String pDateEnd, int pSelectedResopID, Map data, - {String comments = "", String? empID}) async { + {String comments = "", String? empID}) async { String url = "${ApiConsts.erpRest}VALIDATE_ABSENCE_TRANSACTION"; Map postParams = { "P_DESC_FLEX_CONTEXT_CODE": pDescFlexContextCode, @@ -94,13 +92,11 @@ class LeaveBalanceApiClient { "P_SELECTED_RESP_ID": pSelectedResopID, "P_MENU_TYPE": "E", "P_TIME_END": null, - "P_TIME_START": null, + "P_TIME_START": null }; postParams.addAll(data); postParams.addAll(AppState().postParamsJson); - if (empID!.isNotEmpty) { - postParams['P_SELECTED_EMPLOYEE_NUMBER'] = empID; - } + if (empID != null) postParams["P_SELECTED_EMPLOYEE_NUMBER"] = empID; return await ApiClient().postJsonForObject((json) { GenericResponseModel? responseData = GenericResponseModel.fromJson(json); return responseData; @@ -109,7 +105,7 @@ class LeaveBalanceApiClient { Future submitAbsenceTransaction( String pDescFlexContextCode, String pFunctionName, int pAbsenceAttendanceTypeID, String pReplacementUserName, String pDateStart, String pDateEnd, int pSelectedResopID, Map data, - {String comments = "", String? empID}) async { + {String comments = "", String? empID}) async { String url = "${ApiConsts.erpRest}SUBMIT_ABSENCE_TRANSACTION"; Map postParams = { "P_DESC_FLEX_CONTEXT_CODE": pDescFlexContextCode, @@ -124,13 +120,11 @@ class LeaveBalanceApiClient { "P_SELECTED_RESP_ID": pSelectedResopID, "P_MENU_TYPE": "E", "P_TIME_END": null, - "P_TIME_START": null, + "P_TIME_START": null }; postParams.addAll(data); postParams.addAll(AppState().postParamsJson); - if (empID!.isNotEmpty) { - postParams['P_SELECTED_EMPLOYEE_NUMBER'] = empID; - } + if (empID != null) postParams["P_SELECTED_EMPLOYEE_NUMBER"] = empID; return await ApiClient().postJsonForObject((json) { GenericResponseModel? responseData = GenericResponseModel.fromJson(json); return responseData.sumbitAbsenceTransactionList!; @@ -147,18 +141,11 @@ class LeaveBalanceApiClient { }, url, postParams); } - Future startAbsenceApprovalProcess(int pTransactionID, String comments, int pSelectedResopID,{String? empID}) async { + Future startAbsenceApprovalProcess(int pTransactionID, String comments, int pSelectedResopID, {String? empID}) async { String url = "${ApiConsts.erpRest}START_ABSENCE_APPROVAL_PROCESS"; - Map postParams = { - "P_TRANSACTION_ID": pTransactionID, - "P_SELECTED_RESP_ID": pSelectedResopID, - "P_COMMENTS": comments, - "P_MENU_TYPE": "E", - }; + Map postParams = {"P_TRANSACTION_ID": pTransactionID, "P_SELECTED_RESP_ID": pSelectedResopID, "P_COMMENTS": comments, "P_MENU_TYPE": "E", 'P_SELECTED_EMPLOYEE_NUMBER': empID}; postParams.addAll(AppState().postParamsJson); - if (empID!.isNotEmpty) { - postParams['P_SELECTED_EMPLOYEE_NUMBER'] = empID; - } + return await ApiClient().postJsonForObject((json) { GenericResponseModel? responseData = GenericResponseModel.fromJson(json); return responseData.startAbsenceApprovalProccess!; diff --git a/lib/api/my_attendance_api_client.dart b/lib/api/my_attendance_api_client.dart index 0f078a2..78742a3 100644 --- a/lib/api/my_attendance_api_client.dart +++ b/lib/api/my_attendance_api_client.dart @@ -22,11 +22,7 @@ class MyAttendanceApiClient { String url = "${ApiConsts.erpRest}GET_EIT_TRANSACTIONS"; Map postParams = {"P_PAGE_LIMIT": 50, "P_PAGE_NUM": 1, "P_SELECTED_RESP_ID": -999, "P_MENU_TYPE": "E", "P_FUNCTION_NAME": pFunctionName}; postParams.addAll(AppState().postParamsJson); - // postParams['P_SELECTED_EMPLOYEE_NUMBER'] = empID; - if (empID!.isNotEmpty) { - postParams['P_SELECTED_EMPLOYEE_NUMBER'] = empID; - // AppState().postParamsJson['P_SELECTED_EMPLOYEE_NUMBER'] = empID; - } + if (empID != null) postParams["P_SELECTED_EMPLOYEE_NUMBER"] = empID; return await ApiClient().postJsonForObject((json) { GenericResponseModel? responseData = GenericResponseModel.fromJson(json); return responseData.getEITTransactionList ?? []; @@ -37,9 +33,7 @@ class MyAttendanceApiClient { String url = "${ApiConsts.erpRest}GET_EIT_DFF_STRUCTURE"; Map postParams = {"P_SELECTED_RESP_ID": -999, "P_MENU_TYPE": "E", "P_FUNCTION_NAME": pFunctionName}; postParams.addAll(AppState().postParamsJson); - if (empID!.isNotEmpty) { - postParams['P_SELECTED_EMPLOYEE_NUMBER'] = empID; - } + if (empID != null) postParams["P_SELECTED_EMPLOYEE_NUMBER"] = empID; return await ApiClient().postJsonForObject((json) { GenericResponseModel? responseData = GenericResponseModel.fromJson(json); return responseData; @@ -53,16 +47,14 @@ class MyAttendanceApiClient { "P_MENU_TYPE": "E", "P_PAGE_LIMIT": 1000, "P_PAGE_NUM": 1, - "P_PARENT_VALUE": empID!.isNotEmpty ? parentValue : null, + "P_PARENT_VALUE": empID != null ? parentValue : null, "P_SEGMENT_NAME": pSegmentName, "P_DESC_FLEX_CONTEXT_CODE": pDescFlexContextCode, "P_DESC_FLEX_NAME": pDescFlexName, "GetValueSetValuesTBL": list, }; postParams.addAll(AppState().postParamsJson); - if (empID.isNotEmpty) { - postParams['P_SELECTED_EMPLOYEE_NUMBER'] = empID; - } + if (empID != null) postParams["P_SELECTED_EMPLOYEE_NUMBER"] = empID; return await ApiClient().postJsonForObject((json) { GenericResponseModel? responseData = GenericResponseModel.fromJson(json); return responseData.getValueSetValuesList ?? []; @@ -81,9 +73,7 @@ class MyAttendanceApiClient { "GetValueSetValuesTBL": list, }; postParams.addAll(AppState().postParamsJson); - if (empID != null && empID!.isNotEmpty) { - postParams['P_SELECTED_EMPLOYEE_NUMBER'] = empID; - } + if (empID != null) postParams["P_SELECTED_EMPLOYEE_NUMBER"] = empID; return await ApiClient().postJsonForObject((json) { GenericResponseModel? responseData = GenericResponseModel.fromJson(json); return ESERVICESDV.fromJson(responseData.getDefaultValueList!.toJson()); @@ -100,9 +90,7 @@ class MyAttendanceApiClient { "EITTransactionTBL": list, }; postParams.addAll(AppState().postParamsJson); - if (empID!.isNotEmpty) { - postParams['P_SELECTED_EMPLOYEE_NUMBER'] = empID; - } + if (empID != null) postParams["P_SELECTED_EMPLOYEE_NUMBER"] = empID; return await ApiClient().postJsonForObject((json) { GenericResponseModel? responseData = GenericResponseModel.fromJson(json); return responseData; //ESERVICESDV.fromJson(responseData.getDefaultValueList!.toJson()); @@ -120,9 +108,7 @@ class MyAttendanceApiClient { "EITTransactionTBLModel": list, }; postParams.addAll(AppState().postParamsJson); - if (empID!.isNotEmpty) { - postParams['P_SELECTED_EMPLOYEE_NUMBER'] = empID; - } + if (empID != null) postParams["P_SELECTED_EMPLOYEE_NUMBER"] = empID; return await ApiClient().postJsonForObject((json) { GenericResponseModel responseData = GenericResponseModel.fromJson(json); return responseData.submitEITTransactionList!; //ESERVICESDV.fromJson(responseData.getDefaultValueList!.toJson()); diff --git a/lib/classes/consts.dart b/lib/classes/consts.dart index c147ea3..52d0407 100644 --- a/lib/classes/consts.dart +++ b/lib/classes/consts.dart @@ -3,8 +3,8 @@ import 'package:mohem_flutter_app/ui/marathon/widgets/question_card.dart'; class ApiConsts { //static String baseUrl = "http://10.200.204.20:2801/"; // Local server // static String baseUrl = "https://erptstapp.srca.org.sa"; // SRCA server - //static String baseUrl = "https://uat.hmgwebservices.com"; // UAT server - static String baseUrl = "https://hmgwebservices.com"; // Live server + static String baseUrl = "https://uat.hmgwebservices.com"; // UAT server + // static String baseUrl = "https://hmgwebservices.com"; // Live server static String baseUrlServices = baseUrl + "/Services/"; // server // static String baseUrlServices = "https://api.cssynapses.com/tangheem/"; // Live server static String utilitiesRest = baseUrlServices + "Utilities.svc/REST/"; diff --git a/lib/ui/leave_balance/add_leave_balance_screen.dart b/lib/ui/leave_balance/add_leave_balance_screen.dart index 5ef03f4..71404a9 100644 --- a/lib/ui/leave_balance/add_leave_balance_screen.dart +++ b/lib/ui/leave_balance/add_leave_balance_screen.dart @@ -4,7 +4,6 @@ import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:mohem_flutter_app/api/leave_balance_api_client.dart'; -import 'package:mohem_flutter_app/app_state/app_state.dart'; import 'package:mohem_flutter_app/classes/date_uitl.dart'; import 'package:mohem_flutter_app/classes/utils.dart'; import 'package:mohem_flutter_app/config/routes.dart'; @@ -25,8 +24,7 @@ import 'package:mohem_flutter_app/widgets/button/default_button.dart'; import 'package:mohem_flutter_app/widgets/dynamic_forms/dynamic_textfield_widget.dart'; class AddLeaveBalanceScreen extends StatefulWidget { - final String selectedEmp; - AddLeaveBalanceScreen({this.selectedEmp = '', Key? key}) : super(key: key); + AddLeaveBalanceScreen({Key? key}) : super(key: key); @override _AddLeaveBalanceScreenState createState() { @@ -44,15 +42,21 @@ class _AddLeaveBalanceScreenState extends State { int? totalDays; String comment = ""; ReplacementList? selectedReplacementEmployee; - dynamic dynamicParams; - String selectedEmp = ""; + String? selectedEmp; DateTime selectedDate = DateTime(DateTime.now().year, DateTime.now().month, DateTime.now().day); @override void initState() { super.initState(); - //getAbsenceAttendanceTypes(); + + WidgetsBinding.instance.addPostFrameCallback((timeStamp) { + var dynamicParam = ModalRoute.of(context)!.settings.arguments; + if (dynamicParam != null) { + selectedEmp = dynamicParam.toString(); + } + getAbsenceAttendanceTypes(); + }); } void getAbsenceAttendanceTypes() async { @@ -85,7 +89,6 @@ class _AddLeaveBalanceScreenState extends State { Utils.showLoading(context); CalculateAbsenceDuration duration = await LeaveBalanceApiClient() .calculateAbsenceDuration(selectedAbsenceType!.aBSENCEATTENDANCETYPEID!, Utils.getMonthNamedFormat(startDateTime!), Utils.getMonthNamedFormat(endDateTime!), -999, empID: selectedEmp); - totalDays = duration.pABSENCEDAYS?.toInt(); Utils.hideLoading(context); setState(() {}); @@ -95,56 +98,56 @@ class _AddLeaveBalanceScreenState extends State { } } - void validateAbsenceTransaction(selectedID) async { + void validateAbsenceTransaction(String? selectedID) async { try { - Utils.showLoading(context); - Map dffDataMap = {}; - for (int i = 1; i <= 20; i++) { - dffDataMap["P_ATTRIBUTE$i"] = null; - for (int dffIndex = 0; dffIndex < getabsenceDffStructureList.length; dffIndex++) { - if ("ATTRIBUTE$i" == getabsenceDffStructureList[dffIndex].aPPLICATIONCOLUMNNAME) { - if (getabsenceDffStructureList[dffIndex].fORMATTYPE == "X") { - dffDataMap["P_ATTRIBUTE$i"] = - getabsenceDffStructureList[dffIndex].eSERVICESDV!.pIDCOLUMNNAME != null ? Utils.formatDate(getabsenceDffStructureList[dffIndex].eSERVICESDV!.pIDCOLUMNNAME!) : ""; - } else { - dffDataMap["P_ATTRIBUTE$i"] = getabsenceDffStructureList[dffIndex].eSERVICESDV?.pIDCOLUMNNAME; + Utils.showLoading(context); + Map dffDataMap = {}; + for (int i = 1; i <= 20; i++) { + dffDataMap["P_ATTRIBUTE$i"] = null; + for (int dffIndex = 0; dffIndex < getabsenceDffStructureList.length; dffIndex++) { + if ("ATTRIBUTE$i" == getabsenceDffStructureList[dffIndex].aPPLICATIONCOLUMNNAME) { + if (getabsenceDffStructureList[dffIndex].fORMATTYPE == "X") { + dffDataMap["P_ATTRIBUTE$i"] = + getabsenceDffStructureList[dffIndex].eSERVICESDV!.pIDCOLUMNNAME != null ? Utils.formatDate(getabsenceDffStructureList[dffIndex].eSERVICESDV!.pIDCOLUMNNAME!) : ""; + } else { + dffDataMap["P_ATTRIBUTE$i"] = getabsenceDffStructureList[dffIndex].eSERVICESDV?.pIDCOLUMNNAME; + } + break; } - break; } } - } - await LeaveBalanceApiClient().validateAbsenceTransaction( - selectedAbsenceType!.dESCFLEXCONTEXTCODE!, - "HR_LOA_SS", - selectedAbsenceType!.aBSENCEATTENDANCETYPEID!, - selectedReplacementEmployee != null ? selectedReplacementEmployee!.userName! : "", - DateUtil.getFormattedDate(startDateTime!, "MM/dd/yyyy"), - DateUtil.getFormattedDate(endDateTime!, "MM/dd/yyyy"), - -999, - dffDataMap, - comments: comment, - empID: selectedEmp); + await LeaveBalanceApiClient().validateAbsenceTransaction( + selectedAbsenceType!.dESCFLEXCONTEXTCODE!, + "HR_LOA_SS", + selectedAbsenceType!.aBSENCEATTENDANCETYPEID!, + selectedReplacementEmployee != null ? selectedReplacementEmployee!.userName! : "", + DateUtil.getFormattedDate(startDateTime!, "MM/dd/yyyy"), + DateUtil.getFormattedDate(endDateTime!, "MM/dd/yyyy"), + -999, + dffDataMap, + comments: comment, + empID: selectedID); - SumbitAbsenceTransactionList submit = await LeaveBalanceApiClient().submitAbsenceTransaction( - selectedAbsenceType!.dESCFLEXCONTEXTCODE!, - "HR_LOA_SS", - selectedAbsenceType!.aBSENCEATTENDANCETYPEID!, - selectedReplacementEmployee != null ? selectedReplacementEmployee!.userName! : "", - DateUtil.getFormattedDate(startDateTime!, "MM/dd/yyyy"), - DateUtil.getFormattedDate(endDateTime!, "MM/dd/yyyy"), - -999, - dffDataMap, - comments: comment, - empID: selectedEmp); + SumbitAbsenceTransactionList submit = await LeaveBalanceApiClient().submitAbsenceTransaction( + selectedAbsenceType!.dESCFLEXCONTEXTCODE!, + "HR_LOA_SS", + selectedAbsenceType!.aBSENCEATTENDANCETYPEID!, + selectedReplacementEmployee != null ? selectedReplacementEmployee!.userName! : "", + DateUtil.getFormattedDate(startDateTime!, "MM/dd/yyyy"), + DateUtil.getFormattedDate(endDateTime!, "MM/dd/yyyy"), + -999, + dffDataMap, + comments: comment, + empID: selectedID); - Utils.hideLoading(context); + Utils.hideLoading(context); - var res = await Navigator.pushNamed(context, AppRoutes.requestSubmitScreen, arguments: RequestSubmitScreenParams(LocaleKeys.submit.tr(), submit.pTRANSACTIONID!, "", "add_leave_balance")); - if (res != null && res == true) { - Utils.showLoading(context); - } - await LeaveBalanceApiClient().cancelHrTransaction(submit.pTRANSACTIONID!); - Utils.hideLoading(context); + var res = await Navigator.pushNamed(context, AppRoutes.requestSubmitScreen, arguments: RequestSubmitScreenParams(LocaleKeys.submit.tr(), submit.pTRANSACTIONID!, "", "add_leave_balance")); + if (res != null && res == true) { + Utils.showLoading(context); + } + await LeaveBalanceApiClient().cancelHrTransaction(submit.pTRANSACTIONID!); + Utils.hideLoading(context); } catch (ex) { Utils.hideLoading(context); Utils.handleException(ex, context, null); @@ -158,16 +161,6 @@ class _AddLeaveBalanceScreenState extends State { @override Widget build(BuildContext context) { - if (dynamicParams == null) { - dynamicParams = ModalRoute.of(context)!.settings.arguments; - if (dynamicParams!= null && dynamicParams.isNotEmpty) { - AppState().postParamsJson['P_SELECTED_EMPLOYEE_NUMBER'] = dynamicParams; - selectedEmp = dynamicParams; - getAbsenceAttendanceTypes(); - } else { - getAbsenceAttendanceTypes(); - } - } return Scaffold( backgroundColor: Colors.white, appBar: AppBarWidget( @@ -187,13 +180,13 @@ class _AddLeaveBalanceScreenState extends State { isPopup: true, ), itemBuilder: (_) => >[ - for (int i = 0; i < absenceList.length; i++) PopupMenuItem(value: i, child: Text(absenceList[i].aBSENCEATTENDANCETYPENAME!)), + for (int i = 0; i < (absenceList?.length ?? 0); i++) PopupMenuItem(value: i, child: Text(absenceList![i].aBSENCEATTENDANCETYPENAME!)), ], onSelected: (int popupIndex) { - if (selectedAbsenceType == absenceList[popupIndex]) { + if (selectedAbsenceType == absenceList![popupIndex]) { return; } - selectedAbsenceType = absenceList[popupIndex]; + selectedAbsenceType = absenceList![popupIndex]; setState(() {}); getAbsenceDffStructure(); }, @@ -285,7 +278,7 @@ class _AddLeaveBalanceScreenState extends State { validateFieldData() ? null : () { - validateAbsenceTransaction(selectedEmp); + validateAbsenceTransaction(selectedEmp!.isEmpty ? null : selectedEmp); }, ).insideContainer ], diff --git a/lib/ui/leave_balance/leave_balance_screen.dart b/lib/ui/leave_balance/leave_balance_screen.dart index 8c346bc..881828e 100644 --- a/lib/ui/leave_balance/leave_balance_screen.dart +++ b/lib/ui/leave_balance/leave_balance_screen.dart @@ -1,7 +1,6 @@ import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:mohem_flutter_app/api/leave_balance_api_client.dart'; -import 'package:mohem_flutter_app/app_state/app_state.dart'; import 'package:mohem_flutter_app/classes/colors.dart'; import 'package:mohem_flutter_app/classes/utils.dart'; import 'package:mohem_flutter_app/config/routes.dart'; @@ -14,8 +13,7 @@ import 'package:mohem_flutter_app/widgets/balances_dashboard_widget.dart'; import 'package:mohem_flutter_app/widgets/item_detail_view_widget.dart'; class LeaveBalance extends StatefulWidget { - final String selectedEmp; - LeaveBalance({this.selectedEmp = '', Key? key}) : super(key: key); + LeaveBalance({Key? key}) : super(key: key); @override _LeaveBalanceState createState() { @@ -27,13 +25,18 @@ class _LeaveBalanceState extends State { List? absenceTransList; DateTime accrualDateTime = DateTime.now(); - dynamic dynamicParams; - String selectedEmp = ""; + String? employeeId; @override void initState() { super.initState(); - absenceTransList = []; + WidgetsBinding.instance.addPostFrameCallback((timeStamp) { + var dynamicParam = ModalRoute.of(context)!.settings.arguments; + if (dynamicParam != null) { + employeeId = dynamicParam.toString(); + } + getAbsenceTransactions(); + }); } @override @@ -44,7 +47,7 @@ class _LeaveBalanceState extends State { void getAbsenceTransactions() async { try { Utils.showLoading(context); - absenceTransList = await LeaveBalanceApiClient().getAbsenceTransactions(-999, empID: selectedEmp); + absenceTransList = await LeaveBalanceApiClient().getAbsenceTransactions(-999, employeeId); Utils.hideLoading(context); setState(() {}); } catch (ex) { @@ -55,63 +58,53 @@ class _LeaveBalanceState extends State { @override Widget build(BuildContext context) { - if (dynamicParams == null) { - dynamicParams = ModalRoute.of(context)!.settings.arguments; - if (dynamicParams!= null && dynamicParams.isNotEmpty) { - AppState().postParamsJson['P_SELECTED_EMPLOYEE_NUMBER'] = dynamicParams; - selectedEmp = dynamicParams; - getAbsenceTransactions(); - } else { - getAbsenceTransactions(); - } - } return Scaffold( backgroundColor: Colors.white, appBar: AppBarWidget( context, title: LocaleKeys.leaveBalance.tr(), ), - body: ListView( - physics: const BouncingScrollPhysics(), - padding: const EdgeInsets.all(21), - children: [ - BalancesDashboardWidget(LocaleKeys.currentLeaveBalance.tr(), true, selectedEmp), - 12.height, - absenceTransList == null - ? const SizedBox() - : (absenceTransList!.isEmpty - ? Utils.getNoDataWidget(context).paddingOnly(top: 50) - : ListView.separated( - physics: const NeverScrollableScrollPhysics(), - shrinkWrap: true, - padding: EdgeInsets.zero, - itemBuilder: (cxt, int index) => Column( - crossAxisAlignment: CrossAxisAlignment.start, - mainAxisSize: MainAxisSize.min, - children: [ - ItemDetailGrid( - ItemDetailViewCol(LocaleKeys.startDateT.tr(), absenceTransList![index].sTARTDATE ?? ""), - ItemDetailViewCol(LocaleKeys.endDateT.tr(), absenceTransList![index].eNDDATE ?? ""), - ), - ItemDetailGrid( - ItemDetailViewCol(LocaleKeys.absenceType.tr(), absenceTransList![index].aBSENCETYPE ?? ""), - ItemDetailViewCol(LocaleKeys.absenceCategory.tr(), absenceTransList![index].aBSENCECATEGORY ?? ""), - ), - ItemDetailGrid( - ItemDetailViewCol(LocaleKeys.days.tr(), absenceTransList![index].aBSENCEDAYS?.toString() ?? ""), - ItemDetailViewCol(LocaleKeys.hours.tr(), absenceTransList![index].aBSENCEHOURS?.toString() ?? ""), - ), - ItemDetailGrid( - ItemDetailViewCol(LocaleKeys.approvalStatus.tr(), absenceTransList![index].aPPROVALSTATUS ?? ""), - ItemDetailViewCol(LocaleKeys.absenceStatus.tr(), absenceTransList![index].aBSENCESTATUS ?? ""), - isItLast: true, - ), - ], - ).objectContainerView(), - separatorBuilder: (cxt, index) => 12.height, - itemCount: absenceTransList!.length)), - ], - ), + body: absenceTransList == null + ? const SizedBox() + : (absenceTransList!.isEmpty + ? Utils.getNoDataWidget(context).paddingOnly(top: 50) + : ListView( + physics: const BouncingScrollPhysics(), + padding: const EdgeInsets.all(21), + children: [ + BalancesDashboardWidget(LocaleKeys.currentLeaveBalance.tr(), true, selectedEmp: employeeId), + 12.height, + ListView.separated( + physics: const NeverScrollableScrollPhysics(), + shrinkWrap: true, + padding: EdgeInsets.zero, + itemBuilder: (cxt, int index) => Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + ItemDetailGrid( + ItemDetailViewCol(LocaleKeys.startDateT.tr(), absenceTransList![index].sTARTDATE ?? ""), + ItemDetailViewCol(LocaleKeys.endDateT.tr(), absenceTransList![index].eNDDATE ?? ""), + ), + ItemDetailGrid( + ItemDetailViewCol(LocaleKeys.absenceType.tr(), absenceTransList![index].aBSENCETYPE ?? ""), + ItemDetailViewCol(LocaleKeys.absenceCategory.tr(), absenceTransList![index].aBSENCECATEGORY ?? ""), + ), + ItemDetailGrid( + ItemDetailViewCol(LocaleKeys.days.tr(), absenceTransList![index].aBSENCEDAYS?.toString() ?? ""), + ItemDetailViewCol(LocaleKeys.hours.tr(), absenceTransList![index].aBSENCEHOURS?.toString() ?? ""), + ), + ItemDetailGrid( + ItemDetailViewCol(LocaleKeys.approvalStatus.tr(), absenceTransList![index].aPPROVALSTATUS ?? ""), + ItemDetailViewCol(LocaleKeys.absenceStatus.tr(), absenceTransList![index].aBSENCESTATUS ?? ""), + isItLast: true, + ), + ], + ).objectContainerView(), + separatorBuilder: (cxt, index) => 12.height, + itemCount: absenceTransList!.length), + ], + )), floatingActionButton: Container( height: 54, width: 54, @@ -124,7 +117,7 @@ class _LeaveBalanceState extends State { ), child: const Icon(Icons.add, color: Colors.white, size: 30), ).onPress(() { - Navigator.pushNamed(context, AppRoutes.addLeaveBalance, arguments: selectedEmp ?? ''); + Navigator.pushNamed(context, AppRoutes.addLeaveBalance, arguments: employeeId); }), ); } diff --git a/lib/ui/my_attendance/dynamic_screens/dynamic_input_screen.dart b/lib/ui/my_attendance/dynamic_screens/dynamic_input_screen.dart index 228f1d6..9c0c51b 100644 --- a/lib/ui/my_attendance/dynamic_screens/dynamic_input_screen.dart +++ b/lib/ui/my_attendance/dynamic_screens/dynamic_input_screen.dart @@ -5,7 +5,6 @@ import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:mohem_flutter_app/api/leave_balance_api_client.dart'; import 'package:mohem_flutter_app/api/my_attendance_api_client.dart'; -import 'package:mohem_flutter_app/app_state/app_state.dart'; import 'package:mohem_flutter_app/classes/utils.dart'; import 'package:mohem_flutter_app/config/routes.dart'; import 'package:mohem_flutter_app/extensions/int_extensions.dart'; @@ -431,9 +430,6 @@ class _DynamicInputScreenState extends State { Widget build(BuildContext context) { if (dynamicParams == null) { dynamicParams = ModalRoute.of(context)!.settings.arguments as DynamicListViewParams; - if (dynamicParams!.selectedEmp.isNotEmpty) { - AppState().postParamsJson['P_SELECTED_EMPLOYEE_NUMBER'] = dynamicParams!.selectedEmp; - } getTransactionsStructure(); } return Scaffold( @@ -627,12 +623,15 @@ class _DynamicInputScreenState extends State { ).paddingOnly(bottom: 12), itemBuilder: (_) => >[ if (model.rEADONLY != "Y") - for (int i = 0; i < model.eSERVICESVS!.length; i++) PopupMenuItem(value: i, child: Column( - children: [ - Text(model.eSERVICESVS![i].vALUECOLUMNNAME!), - const PopupMenuDivider(), - ], - )), + for (int i = 0; i < model.eSERVICESVS!.length; i++) + PopupMenuItem( + value: i, + child: Column( + children: [ + Text(model.eSERVICESVS![i].vALUECOLUMNNAME!), + const PopupMenuDivider(), + ], + )), ], onSelected: (int popipIndex) async { ESERVICESDV eservicesdv = ESERVICESDV( diff --git a/lib/ui/my_attendance/dynamic_screens/dynamic_listview_screen.dart b/lib/ui/my_attendance/dynamic_screens/dynamic_listview_screen.dart index 68727e5..a9c9694 100644 --- a/lib/ui/my_attendance/dynamic_screens/dynamic_listview_screen.dart +++ b/lib/ui/my_attendance/dynamic_screens/dynamic_listview_screen.dart @@ -21,10 +21,10 @@ class DynamicListViewParams { bool isUpdate; List? collectionNotificationList; - final String selectedEmp; + final String? selectedEmp; DynamicListViewParams(this.title, this.dynamicId, - {this.selectedEmp = '', this.uRL = 'GET_EIT_DFF_STRUCTURE', this.requestID = '', this.colsURL = '', this.isUpdate = false, this.collectionNotificationList}); + {this.selectedEmp, this.uRL = 'GET_EIT_DFF_STRUCTURE', this.requestID = '', this.colsURL = '', this.isUpdate = false, this.collectionNotificationList}); } class DynamicListViewScreen extends StatefulWidget { @@ -54,7 +54,6 @@ class _DynamicListViewScreenState extends State { getEITTransactionList?.forEach((element) { element.collectionTransaction = element.collectionTransaction?.where((elemen) => elemen.dISPLAYFLAG == "Y").toList() ?? []; }); - getEITTransactionList = getEITTransactionList?.where((element) => element.collectionTransaction?.isNotEmpty ?? false).toList() ?? []; Utils.hideLoading(context); setState(() {}); @@ -94,7 +93,7 @@ class _DynamicListViewScreenState extends State { padding: const EdgeInsets.all(21), children: [ // HMG_TKT_NEW_EIT_SS Id used for ticket balance dashboard - if (isTicketRequest) ...[const BalancesDashboardWidget("Current Ticket Balance", false, ""), 12.height], + if (isTicketRequest) ...[const BalancesDashboardWidget("Current Ticket Balance", false, showLoading: false), 12.height], getEITTransactionList == null ? const SizedBox() : (getEITTransactionList!.isEmpty diff --git a/lib/ui/my_attendance/services_menu_list_screen.dart b/lib/ui/my_attendance/services_menu_list_screen.dart index 7a61029..097a63a 100644 --- a/lib/ui/my_attendance/services_menu_list_screen.dart +++ b/lib/ui/my_attendance/services_menu_list_screen.dart @@ -17,9 +17,9 @@ import 'package:provider/provider.dart'; class ServicesMenuListScreenParams { final String title; final List list; - final String selectedEmp; + final String? selectedEmp; GetEmployeeSubordinatesList? getEmployeeSubordinates; - ServicesMenuListScreenParams(this.title, this.list, {this.selectedEmp =''}); + ServicesMenuListScreenParams(this.title, this.list, {this.selectedEmp}); } class ServicesMenuListScreen extends StatelessWidget { @@ -54,11 +54,12 @@ class ServicesMenuListScreen extends StatelessWidget { } return; } else if (servicesMenuData.list[index].requestType == "ABSENCE") { - Navigator.pushNamed(context, AppRoutes.leaveBalance, arguments: servicesMenuData?.selectedEmp ??''); + Navigator.pushNamed(context, AppRoutes.leaveBalance, arguments: servicesMenuData.selectedEmp); return; } if (servicesMenuData.list[index].requestType == "EIT") { - Navigator.pushNamed(context, AppRoutes.dynamicScreen, arguments: DynamicListViewParams(servicesMenuData.list[index].prompt!, servicesMenuData.list[index].functionName!, selectedEmp: servicesMenuData.selectedEmp)); + Navigator.pushNamed(context, AppRoutes.dynamicScreen, + arguments: DynamicListViewParams(servicesMenuData.list[index].prompt!, servicesMenuData.list[index].functionName!, selectedEmp: servicesMenuData.selectedEmp)); } else { if (servicesMenuData.list[index].requestType == "TERMINATION") { Navigator.pushNamed(context, AppRoutes.endEmploymentScreen, diff --git a/lib/ui/my_team/create_request.dart b/lib/ui/my_team/create_request.dart index 2b3e063..94ac415 100644 --- a/lib/ui/my_team/create_request.dart +++ b/lib/ui/my_team/create_request.dart @@ -68,7 +68,8 @@ class _CreateRequestState extends State { void handleOnPress(context, Menus menu) { if (menu.menuEntry.menuEntryType == "FUNCTION") { if (menu.menuEntry.requestType == "EIT") { - Navigator.pushNamed(context, AppRoutes.dynamicScreen, arguments: DynamicListViewParams(menu.menuEntry.prompt!, menu.menuEntry.functionName!, selectedEmp: getEmployeeSubordinates?.eMPLOYEENUMBER ?? '')); + Navigator.pushNamed(context, AppRoutes.dynamicScreen, + arguments: DynamicListViewParams(menu.menuEntry.prompt!, menu.menuEntry.functionName!, selectedEmp: getEmployeeSubordinates?.eMPLOYEENUMBER ?? '')); } else {} } else { Navigator.pushNamed(context, AppRoutes.servicesMenuListScreen, diff --git a/lib/widgets/balances_dashboard_widget.dart b/lib/widgets/balances_dashboard_widget.dart index 9689de4..aaac793 100644 --- a/lib/widgets/balances_dashboard_widget.dart +++ b/lib/widgets/balances_dashboard_widget.dart @@ -31,9 +31,10 @@ class BalancesDashboardWidget extends StatefulWidget { final String title; final List chartModelList; final bool isLeaveBalance; - final String selectedEmp; + final String? selectedEmp; + final bool showLoading; - const BalancesDashboardWidget(this.title, this.isLeaveBalance, this.selectedEmp, {Key? key, this.chartModelList = const []}) : super(key: key); + const BalancesDashboardWidget(this.title, this.isLeaveBalance, {Key? key, this.selectedEmp, this.showLoading = true, this.chartModelList = const []}) : super(key: key); @override _BalancesDashboardWidgetState createState() { @@ -46,14 +47,12 @@ class _BalancesDashboardWidgetState extends State { late DateTime accrualDateTime; GetAccrualBalancesList? leaveBalanceAccrual; List? ticketBalanceAccrualList; - dynamic dynamicParams; - String selectedEmp = ""; @override void initState() { super.initState(); accrualDateTime = DateTime.now(); - changeAccrualDate(); + changeAccrualDate(widget.showLoading); } @override @@ -61,9 +60,9 @@ class _BalancesDashboardWidgetState extends State { super.dispose(); } - void changeAccrualDate() async { + void changeAccrualDate(bool showLoading) async { try { - // Utils.showLoading(context); + if (showLoading) Utils.showLoading(context); List accrualList = await DashboardApiClient().getAccrualBalances(DateFormat("MM/dd/yyyy").format(accrualDateTime), empID: widget.selectedEmp); if (accrualList.isNotEmpty) { if (widget.isLeaveBalance) { @@ -80,10 +79,10 @@ class _BalancesDashboardWidgetState extends State { ]; } } - // Utils.hideLoading(context); + if (showLoading) Utils.hideLoading(context); setState(() {}); } catch (ex) { - Utils.hideLoading(context); + if (showLoading) Utils.hideLoading(context); Utils.handleException(ex, context, null); } } @@ -125,7 +124,7 @@ class _BalancesDashboardWidgetState extends State { DateTime selectedDate = await Utils.selectDate(context, accrualDateTime); if (selectedDate != accrualDateTime) { accrualDateTime = selectedDate; - changeAccrualDate(); + changeAccrualDate(true); } }), ], From 3a6d1c3273bb3c09b5ec25b64ae3db5865b1bec2 Mon Sep 17 00:00:00 2001 From: Sikander Saleem Date: Wed, 21 Dec 2022 15:28:45 +0300 Subject: [PATCH 39/42] leave balance issues fixed-2. --- lib/api/leave_balance_api_client.dart | 4 +- lib/api/worklist/worklist_api_client.dart | 2 +- .../add_leave_balance_screen.dart | 5 +- lib/ui/misc/request_submit_screen.dart | 16 ++-- .../dynamic_screens/dynamic_input_screen.dart | 8 +- lib/ui/my_team/employee_details.dart | 89 +++++++++---------- 6 files changed, 56 insertions(+), 68 deletions(-) diff --git a/lib/api/leave_balance_api_client.dart b/lib/api/leave_balance_api_client.dart index ae855ee..e0330fb 100644 --- a/lib/api/leave_balance_api_client.dart +++ b/lib/api/leave_balance_api_client.dart @@ -143,9 +143,9 @@ class LeaveBalanceApiClient { Future startAbsenceApprovalProcess(int pTransactionID, String comments, int pSelectedResopID, {String? empID}) async { String url = "${ApiConsts.erpRest}START_ABSENCE_APPROVAL_PROCESS"; - Map postParams = {"P_TRANSACTION_ID": pTransactionID, "P_SELECTED_RESP_ID": pSelectedResopID, "P_COMMENTS": comments, "P_MENU_TYPE": "E", 'P_SELECTED_EMPLOYEE_NUMBER': empID}; + Map postParams = {"P_TRANSACTION_ID": pTransactionID, "P_SELECTED_RESP_ID": pSelectedResopID, "P_COMMENTS": comments, "P_MENU_TYPE": "E"}; postParams.addAll(AppState().postParamsJson); - + if (empID != null) postParams["P_SELECTED_EMPLOYEE_NUMBER"] = empID; return await ApiClient().postJsonForObject((json) { GenericResponseModel? responseData = GenericResponseModel.fromJson(json); return responseData.startAbsenceApprovalProccess!; diff --git a/lib/api/worklist/worklist_api_client.dart b/lib/api/worklist/worklist_api_client.dart index dcbb415..82b865c 100644 --- a/lib/api/worklist/worklist_api_client.dart +++ b/lib/api/worklist/worklist_api_client.dart @@ -157,7 +157,7 @@ class WorkListApiClient { "P_PAGE_NUM": 1, }; postParams.addAll(AppState().postParamsJson); - postParams["P_SELECTED_EMPLOYEE_NUMBER"] = selectedEmployeeNumber; + if (selectedEmployeeNumber != null) postParams["P_SELECTED_EMPLOYEE_NUMBER"] = selectedEmployeeNumber; return await ApiClient().postJsonForObject((json) { GenericResponseModel responseData = GenericResponseModel.fromJson(json); return responseData.memberInformationList![0]; diff --git a/lib/ui/leave_balance/add_leave_balance_screen.dart b/lib/ui/leave_balance/add_leave_balance_screen.dart index 71404a9..9eefc62 100644 --- a/lib/ui/leave_balance/add_leave_balance_screen.dart +++ b/lib/ui/leave_balance/add_leave_balance_screen.dart @@ -142,7 +142,8 @@ class _AddLeaveBalanceScreenState extends State { Utils.hideLoading(context); - var res = await Navigator.pushNamed(context, AppRoutes.requestSubmitScreen, arguments: RequestSubmitScreenParams(LocaleKeys.submit.tr(), submit.pTRANSACTIONID!, "", "add_leave_balance")); + var res = await Navigator.pushNamed(context, AppRoutes.requestSubmitScreen, + arguments: RequestSubmitScreenParams(LocaleKeys.submit.tr(), submit.pTRANSACTIONID!, "", "add_leave_balance", selectedEmployeeID: selectedID)); if (res != null && res == true) { Utils.showLoading(context); } @@ -278,7 +279,7 @@ class _AddLeaveBalanceScreenState extends State { validateFieldData() ? null : () { - validateAbsenceTransaction(selectedEmp!.isEmpty ? null : selectedEmp); + validateAbsenceTransaction(selectedEmp); }, ).insideContainer ], diff --git a/lib/ui/misc/request_submit_screen.dart b/lib/ui/misc/request_submit_screen.dart index 170e288..50096c7 100644 --- a/lib/ui/misc/request_submit_screen.dart +++ b/lib/ui/misc/request_submit_screen.dart @@ -31,13 +31,13 @@ class RequestSubmitScreenParams { int transactionId; String pItemId; String approvalFlag; + String? selectedEmployeeID; - RequestSubmitScreenParams(this.title, this.transactionId, this.pItemId, this.approvalFlag); + RequestSubmitScreenParams(this.title, this.transactionId, this.pItemId, this.approvalFlag, {this.selectedEmployeeID}); } class RequestSubmitScreen extends StatefulWidget { - final String selectedEmp; - RequestSubmitScreen({this.selectedEmp ='',Key? key}) : super(key: key); + RequestSubmitScreen({Key? key}) : super(key: key); @override _RequestSubmitScreenState createState() { @@ -53,7 +53,7 @@ class _RequestSubmitScreenState extends State { List attachmentFiles = []; List attachments = []; dynamic dynamicParams; - String selectedEmp =""; + String selectedEmp = ""; @override void initState() { @@ -64,7 +64,6 @@ class _RequestSubmitScreenState extends State { try { Utils.showLoading(context); approverList = await MyAttendanceApiClient().getApproversList("SSHRMS", params!.transactionId); - Utils.hideLoading(context); setState(() {}); } catch (ex) { @@ -123,12 +122,7 @@ class _RequestSubmitScreenState extends State { params!.transactionId, ); } else if (params!.approvalFlag == 'add_leave_balance') { - await LeaveBalanceApiClient().startAbsenceApprovalProcess( - params!.transactionId, - comments.text, - -999, - empID: widget.selectedEmp - ); + await LeaveBalanceApiClient().startAbsenceApprovalProcess(params!.transactionId, comments.text, -999, empID: params!.selectedEmployeeID); } else if (params!.approvalFlag == 'eit') { await MyAttendanceApiClient().startEitApprovalProcess( "SUBMIT", diff --git a/lib/ui/my_attendance/dynamic_screens/dynamic_input_screen.dart b/lib/ui/my_attendance/dynamic_screens/dynamic_input_screen.dart index 9c0c51b..fe7a6f3 100644 --- a/lib/ui/my_attendance/dynamic_screens/dynamic_input_screen.dart +++ b/lib/ui/my_attendance/dynamic_screens/dynamic_input_screen.dart @@ -43,7 +43,6 @@ class _DynamicInputScreenState extends State { void getTransactionsStructure() async { try { Utils.showLoading(context); - genericResponseModel = await MyAttendanceApiClient().getEitDffStructure(dynamicParams!.dynamicId, dynamicParams!.selectedEmp); dESCFLEXCONTEXTCODE = genericResponseModel!.pDESCFLEXCONTEXTCODE ?? ""; descFlexConTextTitle = genericResponseModel!.pDESCFLEXCONTEXTNAME ?? ""; @@ -91,9 +90,8 @@ class _DynamicInputScreenState extends State { values.add(ValidateEitTransactionModel(dATEVALUE: null, nAME: "PEI_EXTRA_INFO_ID", nUMBERVALUE: -1, tRANSACTIONNUMBER: 1, vARCHAR2VALUE: null).toJson()); values.add(ValidateEitTransactionModel(dATEVALUE: null, nAME: "PEI_OBJECT_VERSION_NUMBER", nUMBERVALUE: 0, tRANSACTIONNUMBER: 1, vARCHAR2VALUE: null).toJson()); - genericResponseModel = await MyAttendanceApiClient().validateEitTransaction(dESCFLEXCONTEXTCODE, dynamicParams!.dynamicId, values, empID: dynamicParams!.selectedEmp ?? ''); - SubmitEITTransactionList submitEITTransactionList = - await MyAttendanceApiClient().submitEitTransaction(dESCFLEXCONTEXTCODE, dynamicParams!.dynamicId, values, empID: dynamicParams!.selectedEmp ?? ''); + genericResponseModel = await MyAttendanceApiClient().validateEitTransaction(dESCFLEXCONTEXTCODE, dynamicParams!.dynamicId, values, empID: dynamicParams!.selectedEmp); + SubmitEITTransactionList submitEITTransactionList = await MyAttendanceApiClient().submitEitTransaction(dESCFLEXCONTEXTCODE, dynamicParams!.dynamicId, values, empID: dynamicParams!.selectedEmp); Utils.hideLoading(context); await Navigator.pushNamed(context, AppRoutes.requestSubmitScreen, arguments: RequestSubmitScreenParams(LocaleKeys.submit.tr(), submitEITTransactionList.pTRANSACTIONID!, submitEITTransactionList.pITEMKEY!, 'eit')); @@ -130,7 +128,7 @@ class _DynamicInputScreenState extends State { .toList(); List eServicesResponseModel = await MyAttendanceApiClient().getValueSetValues(segmentId, structureList.dESCFLEXCONTEXTCODE!, structureList.dESCFLEXNAME!, values, - empID: dynamicParams!.selectedEmp ?? '', parentValue: structureList.eSERVICESDV!.pVALUECOLUMNNAME); + empID: dynamicParams!.selectedEmp, parentValue: structureList.eSERVICESDV!.pVALUECOLUMNNAME); List abc = genericResponseModel?.getEITDFFStructureList ?? []; getEitDffStructureList = abc; int index = getEitDffStructureList!.indexWhere((element) => element.sEGMENTNAME == segmentId); diff --git a/lib/ui/my_team/employee_details.dart b/lib/ui/my_team/employee_details.dart index 9fc0070..1412641 100644 --- a/lib/ui/my_team/employee_details.dart +++ b/lib/ui/my_team/employee_details.dart @@ -67,23 +67,25 @@ class _EmployeeDetailsState extends State { } return Scaffold( - extendBody: true, - backgroundColor: MyColors.lightGreyEFColor, - body: Stack(children: [ - getEmployeeSubordinates!.eMPLOYEEIMAGE != null ? - Container( - height: 200, - margin: EdgeInsets.only(top: 30), - decoration: BoxDecoration(image: DecorationImage(image: MemoryImage(Utils.dataFromBase64String(getEmployeeSubordinates!.eMPLOYEEIMAGE!)), fit: BoxFit.cover)), - child: new BackdropFilter( - filter: new ImageFilter.blur(sigmaX: 10.0, sigmaY: 10.0), - child: new Container( - decoration: new BoxDecoration(color: Colors.white.withOpacity(0.0)), - ), - ), - ) : Container( - decoration: BoxDecoration(color: Colors.white.withOpacity(0.0)), - ), + extendBody: true, + backgroundColor: MyColors.lightGreyEFColor, + body: Stack( + children: [ + getEmployeeSubordinates!.eMPLOYEEIMAGE != null + ? Container( + height: 200, + margin: EdgeInsets.only(top: 30), + decoration: BoxDecoration(image: DecorationImage(image: MemoryImage(Utils.dataFromBase64String(getEmployeeSubordinates!.eMPLOYEEIMAGE!)), fit: BoxFit.cover)), + child: new BackdropFilter( + filter: new ImageFilter.blur(sigmaX: 10.0, sigmaY: 10.0), + child: new Container( + decoration: new BoxDecoration(color: Colors.white.withOpacity(0.0)), + ), + ), + ) + : Container( + decoration: BoxDecoration(color: Colors.white.withOpacity(0.0)), + ), SingleChildScrollView( scrollDirection: Axis.vertical, child: Column( @@ -95,15 +97,13 @@ class _EmployeeDetailsState extends State { child: Row( mainAxisAlignment: MainAxisAlignment.start, children: [ - IconButton( - onPressed: () { - Navigator.pop(context); - }, - icon: Icon( - Icons.arrow_back_ios, - color: Colors.white, - ), - ), + CircleAvatar( + radius: 18, + backgroundColor: Colors.black.withOpacity(.21), + child: const Icon(Icons.arrow_back_ios_rounded, color: Colors.white, size: 18).paddingOnly(right: 4), + ).onPress(() { + Navigator.pop(context); + }), ], ), ), @@ -111,7 +111,9 @@ class _EmployeeDetailsState extends State { ], ), ) - ])); + ], + ), + ); } Widget myTeamInfo() { @@ -202,16 +204,8 @@ class _EmployeeDetailsState extends State { } Widget ProfileImage() => getEmployeeSubordinates?.eMPLOYEEIMAGE == null - ? SvgPicture.asset( - "assets/images/user.svg", - height: 68, - width: 68, - ) - : CircleAvatar( - radius: 68, - backgroundImage: MemoryImage(Utils.getPostBytes(getEmployeeSubordinates?.eMPLOYEEIMAGE)), - backgroundColor: Colors.black, - ); + ? SvgPicture.asset("assets/images/user.svg", height: 68, width: 68) + : CircleAvatar(radius: 68, backgroundImage: MemoryImage(Utils.getPostBytes(getEmployeeSubordinates?.eMPLOYEEIMAGE)), backgroundColor: Colors.black); void setMenu() { menu = [ @@ -256,16 +250,17 @@ class _EmployeeDetailsState extends State { child: Column( children: [ Text(LocaleKeys.addFavoriteList).tr(namedArgs: {'name': '${getEmployeeSubordinates!.eMPLOYEENAME}'}), - getEmployeeSubordinates!.eMPLOYEEIMAGE == null - ? SvgPicture.asset( - "assets/images/user.svg", - height: 68, - width: 68,) - : CircleAvatar( - radius: 68, - backgroundImage: MemoryImage(Utils.dataFromBase64String(getEmployeeSubordinates!.eMPLOYEEIMAGE!)), - backgroundColor: Colors.black, - ), + getEmployeeSubordinates!.eMPLOYEEIMAGE == null + ? SvgPicture.asset( + "assets/images/user.svg", + height: 68, + width: 68, + ) + : CircleAvatar( + radius: 68, + backgroundImage: MemoryImage(Utils.dataFromBase64String(getEmployeeSubordinates!.eMPLOYEEIMAGE!)), + backgroundColor: Colors.black, + ), // Image.memory( // Utils.getPostBytes( // getEmployeeSubordinates!.eMPLOYEEIMAGE ?? "", From bcf67895b9928c5e1ca5227cbbfe7b48057dc22d Mon Sep 17 00:00:00 2001 From: haroon amjad Date: Wed, 21 Dec 2022 19:11:17 +0300 Subject: [PATCH 40/42] Dynamic forms & my team fixes --- assets/icons/chat/chat.svg | 26 +- assets/icons/create_req.svg | 10 +- assets/icons/home.svg | 8 +- assets/icons/item_for_sale.svg | 12 +- assets/icons/work_list.svg | 17 +- lib/classes/utils.dart | 13 +- lib/ui/marathon/widgets/marathon_banner.dart | 374 +++++++++--------- .../dynamic_screens/dynamic_input_screen.dart | 2 +- .../services_menu_list_screen.dart | 1 + lib/ui/my_team/create_request.dart | 10 +- lib/ui/my_team/employee_details.dart | 10 +- lib/ui/my_team/team_members.dart | 9 +- 12 files changed, 247 insertions(+), 245 deletions(-) diff --git a/assets/icons/chat/chat.svg b/assets/icons/chat/chat.svg index 29d4471..bf8977d 100644 --- a/assets/icons/chat/chat.svg +++ b/assets/icons/chat/chat.svg @@ -1,23 +1,13 @@ - - - - - + + + + + - - - - - - - - - - - - - + + + diff --git a/assets/icons/create_req.svg b/assets/icons/create_req.svg index a87e809..76f414f 100644 --- a/assets/icons/create_req.svg +++ b/assets/icons/create_req.svg @@ -1,7 +1,5 @@ - - - - - - + + + + diff --git a/assets/icons/home.svg b/assets/icons/home.svg index fb67997..91992ad 100644 --- a/assets/icons/home.svg +++ b/assets/icons/home.svg @@ -1,7 +1,7 @@ - - - - + + + + diff --git a/assets/icons/item_for_sale.svg b/assets/icons/item_for_sale.svg index 0a87567..a908b3f 100644 --- a/assets/icons/item_for_sale.svg +++ b/assets/icons/item_for_sale.svg @@ -1,3 +1,11 @@ - - + + + + + + + + + + diff --git a/assets/icons/work_list.svg b/assets/icons/work_list.svg index a802c53..becb368 100644 --- a/assets/icons/work_list.svg +++ b/assets/icons/work_list.svg @@ -1,15 +1,6 @@ - - - - - - - - - - - - - + + + + diff --git a/lib/classes/utils.dart b/lib/classes/utils.dart index 57bb888..572c09e 100644 --- a/lib/classes/utils.dart +++ b/lib/classes/utils.dart @@ -310,7 +310,18 @@ class Utils { } static String formatDateDefault(String date) { - return DateFormat('yyyy-MM-dd').format(DateFormat('dd-MMM-yyyy').parseLoose(date)); + if (date.toLowerCase().contains("t")) { + date = date.toLowerCase().split("t")[0]; + // return DateFormat('yyyy-MM-dd').format(DateFormat('dd-MM-yyyy').parseLoose(date)); + return DateFormat('dd-MM-yyyy').format(DateFormat('yyyy-MM-dd').parseLoose(date)); + } else { + if(date.toLowerCase().split("-")[1].length == 3) { + return DateFormat('dd-MM-yyyy').format(DateFormat('dd-MMM-yyyy').parseLoose(date)); + } else { + return DateFormat('dd-MM-yyyy').format(DateFormat('yyyy-MM-dd').parseLoose(date)); + } + // return DateFormat('yyyy-MM-dd').format(DateFormat('dd-MM-yyyy').parseLoose(date)); + } } static Future selectDate(BuildContext context, DateTime selectedDate) async { diff --git a/lib/ui/marathon/widgets/marathon_banner.dart b/lib/ui/marathon/widgets/marathon_banner.dart index 1b5533b..29c4fd3 100644 --- a/lib/ui/marathon/widgets/marathon_banner.dart +++ b/lib/ui/marathon/widgets/marathon_banner.dart @@ -184,202 +184,200 @@ class MarathonBanner extends StatelessWidget { Widget build(BuildContext context) { MarathonProvider provider = context.read(); - return - // !provider.isPrivilegedWithMarathon - // ? getUnPrivilegedMarathon(context) - // : provider.marathonDetailModel.startTime != null - // ? - Container( - decoration: MyDecorations.shadowDecoration, - height: isTablet ? MediaQuery.of(context).size.height * 0.17 : MediaQuery.of(context).size.height * 0.11, - clipBehavior: Clip.antiAlias, - child: Stack( - children: [ - Transform( - alignment: Alignment.center, - transform: Matrix4.rotationY( - AppState().isArabic(context) ? math.pi : 0, - ), - child: SvgPicture.asset( - "assets/images/marathon_banner_bg.svg", - fit: BoxFit.fill, - width: double.infinity, - ), - ), - AppState().isArabic(context) - ? Positioned( - right: -15, - top: -10, - child: Transform.rotate( - angle: 10, - child: Container( - width: isTablet ? 70 : 65, - height: isTablet ? 40 : 32, - color: MyColors.darkDigitColor, - ), - ), - ) - : Positioned( - left: -20, - top: -10, - child: Transform.rotate( - angle: 15, - child: Container( - width: isTablet ? 70 : 65, - height: isTablet ? 40 : 32, - color: MyColors.darkDigitColor, + return provider.isPrivilegedWithMarathon + ? getUnPrivilegedMarathon(context) + : provider.marathonDetailModel.startTime != null + ? Container( + decoration: MyDecorations.shadowDecoration, + height: isTablet ? MediaQuery.of(context).size.height * 0.17 : MediaQuery.of(context).size.height * 0.11, + clipBehavior: Clip.antiAlias, + child: Stack( + children: [ + Transform( + alignment: Alignment.center, + transform: Matrix4.rotationY( + AppState().isArabic(context) ? math.pi : 0, + ), + child: SvgPicture.asset( + "assets/images/marathon_banner_bg.svg", + fit: BoxFit.fill, + width: double.infinity, + ), ), - ), - ), - SizedBox( - width: double.infinity, - height: double.infinity, - child: Row( - children: [ - const Expanded( - flex: 3, - child: SizedBox( - width: double.infinity, - height: double.infinity, - ), - ), - Expanded( - flex: AppState().isArabic(context) ? 4 : 5, - child: SizedBox( - width: double.infinity, - height: double.infinity, - child: Row( - mainAxisAlignment: MainAxisAlignment.start, - children: [ - Column( - mainAxisAlignment: MainAxisAlignment.center, - crossAxisAlignment: CrossAxisAlignment.start, - mainAxisSize: MainAxisSize.min, - children: [ - AppState().isArabic(context) ? 0.height : 5.height, - Text( - LocaleKeys.getReadyForContest.tr(), - style: TextStyle( - fontSize: isTablet ? 20 : 11, - fontStyle: FontStyle.italic, - fontWeight: FontWeight.w600, - color: MyColors.white.withOpacity(0.83), - letterSpacing: -0.4, + AppState().isArabic(context) + ? Positioned( + right: -15, + top: -10, + child: Transform.rotate( + angle: 10, + child: Container( + width: isTablet ? 70 : 65, + height: isTablet ? 40 : 32, + color: MyColors.darkDigitColor, ), ), - Text( - AppState().isArabic(context) ? provider.marathonDetailModel.titleAr ?? "" : provider.marathonDetailModel.titleEn ?? "", - style: TextStyle( - fontStyle: FontStyle.italic, - fontSize: isTablet ? 30 : 19, - fontWeight: FontWeight.bold, - color: MyColors.white.withOpacity(0.83), - height: 32 / 22, + ) + : Positioned( + left: -20, + top: -10, + child: Transform.rotate( + angle: 15, + child: Container( + width: isTablet ? 70 : 65, + height: isTablet ? 40 : 32, + color: MyColors.darkDigitColor, ), ), - isTablet ? 10.height : 3.height, - BuildCountdownTimer( - timeToMarathon: DateTime.parse(provider.marathonDetailModel.startTime!).millisecondsSinceEpoch, - provider: provider, - screenFlag: 0, + ), + SizedBox( + width: double.infinity, + height: double.infinity, + child: Row( + children: [ + const Expanded( + flex: 3, + child: SizedBox( + width: double.infinity, + height: double.infinity, ), - ], - ).paddingOnly( - left: AppState().isArabic(context) ? 12 : 3, - right: AppState().isArabic(context) ? 3 : 12, - ) - ], - ), - ), - ), - ], - ), - ), - AppState().isArabic(context) - ? Align( - alignment: Alignment.topRight, - child: SizedBox( - height: isTablet ? 30 : 20, - width: isTablet ? 45 : 35, - child: Transform.rotate( - angle: math.pi / 4.5, - child: Text( - LocaleKeys.brainMarathon.tr(), - textAlign: TextAlign.center, - maxLines: 2, - style: TextStyle( - color: MyColors.white, - fontWeight: FontWeight.bold, - fontSize: isTablet ? 8 : 6, - height: 1.2, - ), - ), - ), - ), - ).paddingOnly(top: 5) - : Align( - alignment: Alignment.topLeft, - child: SizedBox( - height: isTablet ? 30 : 20, - width: isTablet ? 45 : 35, - child: Transform.rotate( - angle: -math.pi / 4.5, - child: Text( - LocaleKeys.brainMarathon.tr(), - textAlign: TextAlign.center, - maxLines: 2, - style: TextStyle( - color: MyColors.kWhiteColor, - fontWeight: FontWeight.bold, - fontSize: isTablet ? 8 : 6, - height: 1.2, - ), + ), + Expanded( + flex: AppState().isArabic(context) ? 4 : 5, + child: SizedBox( + width: double.infinity, + height: double.infinity, + child: Row( + mainAxisAlignment: MainAxisAlignment.start, + children: [ + Column( + mainAxisAlignment: MainAxisAlignment.center, + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + AppState().isArabic(context) ? 0.height : 5.height, + Text( + LocaleKeys.getReadyForContest.tr(), + style: TextStyle( + fontSize: isTablet ? 20 : 11, + fontStyle: FontStyle.italic, + fontWeight: FontWeight.w600, + color: MyColors.white.withOpacity(0.83), + letterSpacing: -0.4, + ), + ), + Text( + AppState().isArabic(context) ? provider.marathonDetailModel.titleAr ?? "" : provider.marathonDetailModel.titleEn ?? "", + style: TextStyle( + fontStyle: FontStyle.italic, + fontSize: isTablet ? 30 : 19, + fontWeight: FontWeight.bold, + color: MyColors.white.withOpacity(0.83), + height: 32 / 22, + ), + ), + isTablet ? 10.height : 3.height, + BuildCountdownTimer( + timeToMarathon: DateTime.parse(provider.marathonDetailModel.startTime!).millisecondsSinceEpoch, + provider: provider, + screenFlag: 0, + ), + ], + ).paddingOnly( + left: AppState().isArabic(context) ? 12 : 3, + right: AppState().isArabic(context) ? 3 : 12, + ) + ], + ), + ), + ), + ], ), ), - ), - ).paddingOnly(top: 5), - !AppState().isArabic(context) - ? Positioned( - right: 0, - bottom: 0, - child: RotatedBox( - quarterTurns: 4, - child: SvgPicture.asset("assets/images/arrow_next.svg", color: MyColors.whiteColor), - ).paddingAll(isTablet ? 20 : 15), - ) - : Positioned( - bottom: 0, - left: 0, - child: RotatedBox( - quarterTurns: 2, - child: SvgPicture.asset("assets/images/arrow_next.svg", color: MyColors.whiteColor), - ).paddingAll(isTablet ? 20 : 15), - ), - ], - ).onPress(() async { - int remainingTimeInMinutes = DateTime.parse(provider.marathonDetailModel.startTime!).difference(DateTime.now()).inMinutes; + AppState().isArabic(context) + ? Align( + alignment: Alignment.topRight, + child: SizedBox( + height: isTablet ? 30 : 20, + width: isTablet ? 45 : 35, + child: Transform.rotate( + angle: math.pi / 4.5, + child: Text( + LocaleKeys.brainMarathon.tr(), + textAlign: TextAlign.center, + maxLines: 2, + style: TextStyle( + color: MyColors.white, + fontWeight: FontWeight.bold, + fontSize: isTablet ? 8 : 6, + height: 1.2, + ), + ), + ), + ), + ).paddingOnly(top: 5) + : Align( + alignment: Alignment.topLeft, + child: SizedBox( + height: isTablet ? 30 : 20, + width: isTablet ? 45 : 35, + child: Transform.rotate( + angle: -math.pi / 4.5, + child: Text( + LocaleKeys.brainMarathon.tr(), + textAlign: TextAlign.center, + maxLines: 2, + style: TextStyle( + color: MyColors.kWhiteColor, + fontWeight: FontWeight.bold, + fontSize: isTablet ? 8 : 6, + height: 1.2, + ), + ), + ), + ), + ).paddingOnly(top: 5), + !AppState().isArabic(context) + ? Positioned( + right: 0, + bottom: 0, + child: RotatedBox( + quarterTurns: 4, + child: SvgPicture.asset("assets/images/arrow_next.svg", color: MyColors.whiteColor), + ).paddingAll(isTablet ? 20 : 15), + ) + : Positioned( + bottom: 0, + left: 0, + child: RotatedBox( + quarterTurns: 2, + child: SvgPicture.asset("assets/images/arrow_next.svg", color: MyColors.whiteColor), + ).paddingAll(isTablet ? 20 : 15), + ), + ], + ).onPress(() async { + int remainingTimeInMinutes = DateTime.parse(provider.marathonDetailModel.startTime!).difference(DateTime.now()).inMinutes; - if (remainingTimeInMinutes > 2) { - Utils.showLoading(context); - try { - await provider.initializeVideoPlayer().then((_) { - Utils.hideLoading(context); - provider.startTimerForSponsorVideo(); - Navigator.pushNamed(context, AppRoutes.marathonSponsorVideoScreen); - }); - } catch (e) { - if (kDebugMode) { - print("Error in VideoPlayer: ${e.toString()}"); - } - Utils.hideLoading(context); - Navigator.pushNamed(context, AppRoutes.marathonIntroScreen); - } - } else { - Navigator.pushNamed(context, AppRoutes.marathonIntroScreen); - } - }), - ); - // ) - // : const SizedBox(); + if (remainingTimeInMinutes > 2) { + Utils.showLoading(context); + try { + await provider.initializeVideoPlayer().then((_) { + Utils.hideLoading(context); + provider.startTimerForSponsorVideo(); + Navigator.pushNamed(context, AppRoutes.marathonSponsorVideoScreen); + }); + } catch (e) { + if (kDebugMode) { + print("Error in VideoPlayer: ${e.toString()}"); + } + Utils.hideLoading(context); + Navigator.pushNamed(context, AppRoutes.marathonIntroScreen); + } + } else { + Navigator.pushNamed(context, AppRoutes.marathonIntroScreen); + } + }), + // ); + ) + : const SizedBox(); } } diff --git a/lib/ui/my_attendance/dynamic_screens/dynamic_input_screen.dart b/lib/ui/my_attendance/dynamic_screens/dynamic_input_screen.dart index fe7a6f3..a94a6e2 100644 --- a/lib/ui/my_attendance/dynamic_screens/dynamic_input_screen.dart +++ b/lib/ui/my_attendance/dynamic_screens/dynamic_input_screen.dart @@ -188,7 +188,7 @@ class _DynamicInputScreenState extends State { // Utils.hideLoading(context); } } else if (values.isNotEmpty) { - ESERVICESDV defaultValue = await MyAttendanceApiClient().getDefaultValue(segmentId, structureList.dESCFLEXCONTEXTCODE!, structureList.dESCFLEXNAME!, values); + ESERVICESDV defaultValue = await MyAttendanceApiClient().getDefaultValue(segmentId, structureList.dESCFLEXCONTEXTCODE!, structureList.dESCFLEXNAME!, values, empID: dynamicParams!.selectedEmp); int index = getEitDffStructureList!.indexWhere((element) => element.sEGMENTNAME == segmentId); getEitDffStructureList![index].eSERVICESDV = defaultValue; } diff --git a/lib/ui/my_attendance/services_menu_list_screen.dart b/lib/ui/my_attendance/services_menu_list_screen.dart index 097a63a..8e44324 100644 --- a/lib/ui/my_attendance/services_menu_list_screen.dart +++ b/lib/ui/my_attendance/services_menu_list_screen.dart @@ -19,6 +19,7 @@ class ServicesMenuListScreenParams { final List list; final String? selectedEmp; GetEmployeeSubordinatesList? getEmployeeSubordinates; + ServicesMenuListScreenParams(this.title, this.list, {this.selectedEmp}); } diff --git a/lib/ui/my_team/create_request.dart b/lib/ui/my_team/create_request.dart index 94ac415..b77ac30 100644 --- a/lib/ui/my_team/create_request.dart +++ b/lib/ui/my_team/create_request.dart @@ -38,13 +38,13 @@ class _CreateRequestState extends State { @override void initState() { super.initState(); - employeeSubRequest(); + // employeeSubRequest(); } void employeeSubRequest() async { try { Utils.showLoading(context); - getEmployeeSubordinatesList = await MyTeamApiClient().getEmployeeSubordinates(searchEmpEmail.toString(), searchEmpName.toString(), searchEmpNo.toString()); + // getEmployeeSubordinatesList = await MyTeamApiClient().getEmployeeSubordinates(searchEmpEmail.toString(), searchEmpName.toString(), searchEmpNo.toString()); getMenuEntriesList = await MyTeamApiClient().employeeSubordinatesRequest(getEmployeeSubordinates?.eMPLOYEENUMBER); homeMenus = parseMenus(getMenuEntriesList); Utils.hideLoading(context); @@ -80,8 +80,10 @@ class _CreateRequestState extends State { @override Widget build(BuildContext context) { - getEmployeeSubordinates ??= ModalRoute.of(context)?.settings.arguments as GetEmployeeSubordinatesList; - + if (getEmployeeSubordinates == null) { + getEmployeeSubordinates ??= ModalRoute.of(context)?.settings.arguments as GetEmployeeSubordinatesList; + employeeSubRequest(); + } return Scaffold( backgroundColor: Colors.white, appBar: AppBarWidget( diff --git a/lib/ui/my_team/employee_details.dart b/lib/ui/my_team/employee_details.dart index 1412641..e78c304 100644 --- a/lib/ui/my_team/employee_details.dart +++ b/lib/ui/my_team/employee_details.dart @@ -74,12 +74,12 @@ class _EmployeeDetailsState extends State { getEmployeeSubordinates!.eMPLOYEEIMAGE != null ? Container( height: 200, - margin: EdgeInsets.only(top: 30), + margin: const EdgeInsets.only(top: 30), decoration: BoxDecoration(image: DecorationImage(image: MemoryImage(Utils.dataFromBase64String(getEmployeeSubordinates!.eMPLOYEEIMAGE!)), fit: BoxFit.cover)), - child: new BackdropFilter( - filter: new ImageFilter.blur(sigmaX: 10.0, sigmaY: 10.0), - child: new Container( - decoration: new BoxDecoration(color: Colors.white.withOpacity(0.0)), + child: BackdropFilter( + filter: ImageFilter.blur(sigmaX: 10.0, sigmaY: 10.0), + child: Container( + decoration: BoxDecoration(color: Colors.white.withOpacity(0.0)), ), ), ) diff --git a/lib/ui/my_team/team_members.dart b/lib/ui/my_team/team_members.dart index c4defc4..8847c36 100644 --- a/lib/ui/my_team/team_members.dart +++ b/lib/ui/my_team/team_members.dart @@ -33,13 +33,13 @@ class _TeamMembersState extends State { void initState() { super.initState(); - employeeSubordinates(); + // employeeSubordinates(); } void employeeSubordinates() async { try { Utils.showLoading(context); - getEmployeeSubordinatesList = await MyTeamApiClient().getEmployeeSubordinates(searchEmpEmail.toString(), searchEmpName.toString(), searchEmpNo.toString()); + // getEmployeeSubordinatesList = await MyTeamApiClient().getEmployeeSubordinates(searchEmpEmail.toString(), searchEmpName.toString(), searchEmpNo.toString()); getEmployeeSubordinatesList = await MyTeamApiClient().employeeSubordinates(searchEmpEmail.toString(), searchEmpName.toString(), searchEmpNo.toString(), getEmployeeSubordinates?.eMPLOYEENUMBER); Utils.hideLoading(context); setState(() {}); @@ -51,7 +51,10 @@ class _TeamMembersState extends State { @override Widget build(BuildContext context) { - getEmployeeSubordinates ??= ModalRoute.of(context)?.settings.arguments as GetEmployeeSubordinatesList; + if (getEmployeeSubordinates == null) { + getEmployeeSubordinates ??= ModalRoute.of(context)?.settings.arguments as GetEmployeeSubordinatesList; + employeeSubordinates(); + } return Scaffold( appBar: AppBarWidget( context, From b3782f634222830f676521a1d2a335bcc2ca9d70 Mon Sep 17 00:00:00 2001 From: haroon amjad Date: Thu, 22 Dec 2022 10:02:50 +0300 Subject: [PATCH 41/42] updates & fixes --- lib/classes/utils.dart | 24 +++++++++++++++--------- lib/provider/chat_provider_model.dart | 2 +- lib/ui/login/new_password_screen.dart | 8 ++++---- 3 files changed, 20 insertions(+), 14 deletions(-) diff --git a/lib/classes/utils.dart b/lib/classes/utils.dart index 572c09e..09fab3f 100644 --- a/lib/classes/utils.dart +++ b/lib/classes/utils.dart @@ -310,17 +310,23 @@ class Utils { } static String formatDateDefault(String date) { - if (date.toLowerCase().contains("t")) { - date = date.toLowerCase().split("t")[0]; - // return DateFormat('yyyy-MM-dd').format(DateFormat('dd-MM-yyyy').parseLoose(date)); - return DateFormat('dd-MM-yyyy').format(DateFormat('yyyy-MM-dd').parseLoose(date)); - } else { - if(date.toLowerCase().split("-")[1].length == 3) { - return DateFormat('dd-MM-yyyy').format(DateFormat('dd-MMM-yyyy').parseLoose(date)); + if (date.isNotEmpty) { + if (date.toLowerCase().contains("t")) { + date = date.toLowerCase().split("t")[0]; + if (!date.contains("00:00:00")) { + date = date + ' 00:00:00'; + } + return date; } else { - return DateFormat('dd-MM-yyyy').format(DateFormat('yyyy-MM-dd').parseLoose(date)); + if (date.toLowerCase().split("-")[1].length == 3) { + return DateFormat('dd-MM-yyyy').format(DateFormat('dd-MMM-yyyy').parseLoose(date)); + } else { + return DateFormat('dd-MM-yyyy').format(DateFormat('yyyy-MM-dd').parseLoose(date)); + } + // return DateFormat('yyyy-MM-dd').format(DateFormat('dd-MM-yyyy').parseLoose(date)); } - // return DateFormat('yyyy-MM-dd').format(DateFormat('dd-MM-yyyy').parseLoose(date)); + } else { + return date; } } diff --git a/lib/provider/chat_provider_model.dart b/lib/provider/chat_provider_model.dart index 5f28b0b..a96080b 100644 --- a/lib/provider/chat_provider_model.dart +++ b/lib/provider/chat_provider_model.dart @@ -828,7 +828,7 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { void deleteData() { List exists = [], unique = []; - exists.addAll(searchedChats!); + if(searchedChats != null) exists.addAll(searchedChats!); exists.addAll(favUsersList!); Map profileMap = {}; for (ChatUser item in exists) { diff --git a/lib/ui/login/new_password_screen.dart b/lib/ui/login/new_password_screen.dart index 8bb1443..217e049 100644 --- a/lib/ui/login/new_password_screen.dart +++ b/lib/ui/login/new_password_screen.dart @@ -102,8 +102,8 @@ class _NewPasswordScreenState extends State { passwordConstraintsUI(LocaleKeys.minimum8Characters.tr(), password.text.length >= 8), 8.height, passwordConstraintsUI(LocaleKeys.doNotAddRepeatingLetters.tr(), checkRepeatedChars(password.text)), - 8.height, - passwordConstraintsUI(LocaleKeys.itShouldContainSpecialCharacter.tr(), checkRegEx(r'[!@#$%^&*(),.?":{}|<>]')), + // 8.height, + // passwordConstraintsUI(LocaleKeys.itShouldContainSpecialCharacter.tr(), checkRegEx(r'[!@#$%^&*(),.?":{}|<>]')), 8.height, passwordConstraintsUI(LocaleKeys.confirmPasswordMustMatch.tr(), password.text.isNotEmpty && password.text == confirmPassword.text), ], @@ -146,11 +146,11 @@ class _NewPasswordScreenState extends State { bool hasUppercase = password.contains(RegExp(r'[A-Z]')); bool hasDigits = password.contains(RegExp(r'[0-9]')); bool hasLowercase = password.contains(RegExp(r'[a-z]')); - bool hasSpecialCharacters = password.contains(RegExp(r'[!@#$%^&*(),.?":{}|<>]')); + // bool hasSpecialCharacters = password.contains(RegExp(r'[!@#$%^&*(),.?":{}|<>]')); bool hasMinLength = password.length >= minLength; bool isMatched = password == confirmPassword.text; - return hasDigits && hasUppercase && hasLowercase && hasSpecialCharacters && hasMinLength && isMatched && checkRepeatedChars(password); + return hasDigits && hasUppercase && hasLowercase && hasMinLength && isMatched && checkRepeatedChars(password); } bool checkRepeatedChars(String password) { From 8a393c1e73fdfab997d3827964ccbc54357fbfc7 Mon Sep 17 00:00:00 2001 From: haroon amjad Date: Thu, 22 Dec 2022 13:17:09 +0300 Subject: [PATCH 42/42] App update screen implemented --- lib/api/api_client.dart | 11 +++---- lib/app_state/app_state.dart | 2 +- lib/classes/utils.dart | 50 +++++++++++++++++-------------- lib/config/routes.dart | 3 ++ lib/ui/app_update_screen.dart | 56 +++++++++++++++++++++++++++++++++++ 5 files changed, 93 insertions(+), 29 deletions(-) create mode 100644 lib/ui/app_update_screen.dart diff --git a/lib/api/api_client.dart b/lib/api/api_client.dart index 1e66d45..ff26054 100644 --- a/lib/api/api_client.dart +++ b/lib/api/api_client.dart @@ -14,11 +14,12 @@ typedef FactoryConstructor = U Function(dynamic); class APIError { int? errorCode; + int? errorType; String? errorMessage; - APIError(this.errorCode, this.errorMessage); + APIError(this.errorCode, this.errorMessage, this.errorType); - Map toJson() => {'errorCode': errorCode, 'errorMessage': errorMessage}; + Map toJson() => {'errorCode': errorCode, 'errorMessage': errorMessage, 'errorType': errorType,}; @override String toString() { @@ -33,14 +34,14 @@ APIException _throwAPIException(Response response) { if (response.body != null && response.body.isNotEmpty) { var jsonError = jsonDecode(response.body); print(jsonError); - apiError = APIError(jsonError['ErrorCode'], jsonError['ErrorMessage']); + apiError = APIError(jsonError['ErrorCode'], jsonError['ErrorMessage'], jsonError['ErrorType']); } return APIException(APIException.BAD_REQUEST, error: apiError); case 400: APIError? apiError; if (response.body != null && response.body.isNotEmpty) { var jsonError = jsonDecode(response.body); - apiError = APIError(jsonError['ErrorCode'], jsonError['ErrorMessage']); + apiError = APIError(jsonError['ErrorCode'], jsonError['ErrorMessage'], jsonError['ErrorType']); } return APIException(APIException.BAD_REQUEST, error: apiError); case 401: @@ -90,7 +91,7 @@ class ApiClient { return factoryConstructor(jsonData); } else { APIError? apiError; - apiError = APIError(jsonData['ErrorCode'], jsonData['ErrorEndUserMessage']); + apiError = APIError(jsonData['ErrorCode'], jsonData['ErrorEndUserMessage'], jsonData['ErrorType']); throw APIException(APIException.BAD_REQUEST, error: apiError); } // } catch (ex) { diff --git a/lib/app_state/app_state.dart b/lib/app_state/app_state.dart index 5060195..7d175b5 100644 --- a/lib/app_state/app_state.dart +++ b/lib/app_state/app_state.dart @@ -64,7 +64,7 @@ class AppState { String? get getMarathonProjectId => _projectID; - final PostParamsModel _postParamsInitConfig = PostParamsModel(channel: 31, versionID: 5.0, mobileType: Platform.isAndroid ? "android" : "ios"); + final PostParamsModel _postParamsInitConfig = PostParamsModel(channel: 31, versionID: 3.8, mobileType: Platform.isAndroid ? "android" : "ios"); void setPostParamsInitConfig() { isAuthenticated = false; diff --git a/lib/classes/utils.dart b/lib/classes/utils.dart index 09fab3f..bac8616 100644 --- a/lib/classes/utils.dart +++ b/lib/classes/utils.dart @@ -98,33 +98,37 @@ class Utils { static void handleException(dynamic exception, cxt, Function(String)? onErrorMessage) { String errorMessage; - if (exception is APIException) { - if (exception.message == APIException.UNAUTHORIZED) { - return; + if (exception.error.errorType != null && exception.error.errorType == 4) { + Navigator.pushNamedAndRemoveUntil(cxt, AppRoutes.appUpdateScreen, (_) => false, arguments: exception.error?.errorMessage); + } else { + if (exception is APIException) { + if (exception.message == APIException.UNAUTHORIZED) { + return; + } else { + errorMessage = exception.error?.errorMessage ?? exception.message; + } } else { - errorMessage = exception.error?.errorMessage ?? exception.message; + errorMessage = APIException.UNKNOWN; } - } else { - errorMessage = APIException.UNKNOWN; - } - if (onErrorMessage != null) { - onErrorMessage(errorMessage); - } else { - if (!AppState().isAuthenticated) { - showDialog( - context: cxt, - builder: (cxt) => ConfirmDialog( - message: errorMessage, - onTap: () { - Navigator.pushNamedAndRemoveUntil(cxt, AppRoutes.login, (Route route) => false); - }, - ), - ); + if (onErrorMessage != null) { + onErrorMessage(errorMessage); } else { - if (cxt != null) { - confirmDialog(cxt, errorMessage); + if (!AppState().isAuthenticated) { + showDialog( + context: cxt, + builder: (cxt) => ConfirmDialog( + message: errorMessage, + onTap: () { + Navigator.pushNamedAndRemoveUntil(cxt, AppRoutes.login, (Route route) => false); + }, + ), + ); } else { - showToast(errorMessage); + if (cxt != null) { + confirmDialog(cxt, errorMessage); + } else { + showToast(errorMessage); + } } } } diff --git a/lib/config/routes.dart b/lib/config/routes.dart index dc6b553..905f4de 100644 --- a/lib/config/routes.dart +++ b/lib/config/routes.dart @@ -1,4 +1,5 @@ import 'package:flutter/material.dart'; +import 'package:mohem_flutter_app/ui/app_update_screen.dart'; import 'package:mohem_flutter_app/ui/attendance/add_vacation_rule_screen.dart'; import 'package:mohem_flutter_app/ui/attendance/monthly_attendance_screen.dart'; import 'package:mohem_flutter_app/ui/attendance/vacation_rule_screen.dart'; @@ -191,6 +192,7 @@ class AppRoutes { static const String marathonWaitingScreen = "/marathonWaitingScreen"; static const String unsafeDeviceScreen = "/unsafeDeviceScreen"; + static const String appUpdateScreen = "/appUpdateScreen"; static final Map routes = { login: (BuildContext context) => LoginScreen(), @@ -302,5 +304,6 @@ class AppRoutes { marathonWaitingScreen: (BuildContext context) => const MarathonWaitingScreen(), unsafeDeviceScreen: (BuildContext context) => const UnsafeDeviceScreen(), + appUpdateScreen: (BuildContext context) => const AppUpdateScreen(), }; } diff --git a/lib/ui/app_update_screen.dart b/lib/ui/app_update_screen.dart new file mode 100644 index 0000000..4a769c3 --- /dev/null +++ b/lib/ui/app_update_screen.dart @@ -0,0 +1,56 @@ +import 'dart:io'; + +import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/material.dart'; +import 'package:mohem_flutter_app/extensions/int_extensions.dart'; +import 'package:mohem_flutter_app/extensions/string_extensions.dart'; +import 'package:mohem_flutter_app/extensions/widget_extensions.dart'; +import 'package:mohem_flutter_app/generated/locale_keys.g.dart'; +import 'package:mohem_flutter_app/widgets/button/default_button.dart'; +import 'package:url_launcher/url_launcher.dart'; + +class AppUpdateScreen extends StatefulWidget { + const AppUpdateScreen({Key? key}) : super(key: key); + + @override + State createState() => _UnsafeDeviceScreenState(); +} + +class _UnsafeDeviceScreenState extends State { + String? dynamicParams; + + @override + Widget build(BuildContext context) { + dynamicParams ??= ModalRoute.of(context)!.settings.arguments as String; + return Scaffold( + body: SafeArea( + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.center, + mainAxisAlignment: MainAxisAlignment.center, + children: [ + 21.height, + Center(child: Image.asset("assets/images/logos/main_mohemm_logo.png", width: 200, height: 50)), + 50.height, + "Please Update Your App".toText24(isBold: true), + 48.height, + dynamicParams.toString().toText14(isCenter: true).paddingOnly(left: 20.0, right: 20.0), + 21.height, + DefaultButton(LocaleKeys.ok.tr(), () async { + if (Platform.isAndroid || Platform.isIOS) { + var appId = Platform.isAndroid ? 'hmg.cloudSolutions.mohem' : '1468856602'; + var url = Uri.parse( + Platform.isAndroid ? "market://details?id=$appId" : "https://apps.apple.com/app/id$appId", + ); + launchUrl( + url, + mode: LaunchMode.externalApplication, + ); + } + }).paddingAll(24) + ], + ), + ), + ); + } +}