From 5430fd2d324a00660c206d4e08d295f32d97cbef Mon Sep 17 00:00:00 2001 From: "Aamir.Muhammad" Date: Tue, 29 Nov 2022 15:07:02 +0300 Subject: [PATCH 01/35] Chat Fixes & Chat Media Preview Api Implementation / On Msg Received Image --- lib/api/chat/chat_api_client.dart | 2 +- .../chat/get_single_user_chat_list_model.dart | 117 ++++--- lib/provider/chat_provider_model.dart | 103 ++++-- lib/ui/chat/chat_bubble.dart | 307 +++++++----------- lib/ui/chat/chat_detailed_screen.dart | 29 +- 5 files changed, 271 insertions(+), 287 deletions(-) diff --git a/lib/api/chat/chat_api_client.dart b/lib/api/chat/chat_api_client.dart index 91b622a..41f941f 100644 --- a/lib/api/chat/chat_api_client.dart +++ b/lib/api/chat/chat_api_client.dart @@ -147,7 +147,7 @@ class ChatApiClient { } Future uploadMedia(String userId, File file) async { - dynamic request = MultipartRequest('POST', Uri.parse('${ApiConsts.chatServerBaseApiUrl}upload')); + dynamic request = MultipartRequest('POST', Uri.parse('${ApiConsts.chatMediaImageUploadUrl}upload')); request.fields.addAll({'userId': userId, 'fileSource': '1'}); request.files.add(await MultipartFile.fromPath('files', file.path)); request.headers.addAll({'Authorization': 'Bearer ${AppState().chatDetails!.response!.token}'}); 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 6a35f0e..07b2f51 100644 --- a/lib/models/chat/get_single_user_chat_list_model.dart +++ b/lib/models/chat/get_single_user_chat_list_model.dart @@ -1,32 +1,35 @@ import 'dart:convert'; +import 'package:flutter/foundation.dart'; + List singleUserChatModelFromJson(String str) => List.from(json.decode(str).map((x) => SingleUserChatModel.fromJson(x))); String singleUserChatModelToJson(List data) => json.encode(List.from(data.map((x) => x.toJson()))); class SingleUserChatModel { - SingleUserChatModel({ - this.userChatHistoryId, - this.userChatHistoryLineId, - this.contant, - this.contantNo, - this.currentUserId, - this.currentUserName, - this.targetUserId, - this.targetUserName, - this.encryptedTargetUserId, - this.encryptedTargetUserName, - this.chatEventId, - this.fileTypeId, - this.isSeen, - this.isDelivered, - this.createdDate, - this.chatSource, - this.conversationId, - this.fileTypeResponse, - this.userChatReplyResponse, - this.isReplied, - }); + SingleUserChatModel( + {this.userChatHistoryId, + this.userChatHistoryLineId, + this.contant, + this.contantNo, + this.currentUserId, + this.currentUserName, + this.targetUserId, + this.targetUserName, + this.encryptedTargetUserId, + this.encryptedTargetUserName, + this.chatEventId, + this.fileTypeId, + this.isSeen, + this.isDelivered, + this.createdDate, + this.chatSource, + this.conversationId, + this.fileTypeResponse, + this.userChatReplyResponse, + this.isReplied, + this.isImageLoaded, + this.image}); int? userChatHistoryId; int? userChatHistoryLineId; @@ -48,29 +51,32 @@ class SingleUserChatModel { FileTypeResponse? fileTypeResponse; UserChatReplyResponse? userChatReplyResponse; bool? isReplied; + bool? isImageLoaded; + Uint8List? image; factory SingleUserChatModel.fromJson(Map json) => SingleUserChatModel( - userChatHistoryId: json["userChatHistoryId"] == null ? null : json["userChatHistoryId"], - userChatHistoryLineId: json["userChatHistoryLineId"] == null ? null : json["userChatHistoryLineId"], - contant: json["contant"] == null ? null : json["contant"], - contantNo: json["contantNo"] == null ? null : json["contantNo"], - currentUserId: json["currentUserId"] == null ? null : json["currentUserId"], - currentUserName: json["currentUserName"] == null ? null : json["currentUserName"], - targetUserId: json["targetUserId"] == null ? null : json["targetUserId"], - targetUserName: json["targetUserName"] == null ? null : json["targetUserName"], - encryptedTargetUserId: json["encryptedTargetUserId"] == null ? null : json["encryptedTargetUserId"], - encryptedTargetUserName: json["encryptedTargetUserName"] == null ? null : json["encryptedTargetUserName"], - chatEventId: json["chatEventId"] == null ? null : json["chatEventId"], - fileTypeId: json["fileTypeId"], - isSeen: json["isSeen"] == null ? null : json["isSeen"], - isDelivered: json["isDelivered"] == null ? null : json["isDelivered"], - createdDate: json["createdDate"] == null ? null : DateTime.parse(json["createdDate"]), - chatSource: json["chatSource"] == null ? null : json["chatSource"], - conversationId: json["conversationId"] == null ? null : json["conversationId"], - fileTypeResponse: json["fileTypeResponse"] == null ? null : FileTypeResponse.fromJson(json["fileTypeResponse"]), - userChatReplyResponse: json["userChatReplyResponse"] == null ? null : UserChatReplyResponse.fromJson(json["userChatReplyResponse"]), - isReplied: false, - ); + userChatHistoryId: json["userChatHistoryId"] == null ? null : json["userChatHistoryId"], + userChatHistoryLineId: json["userChatHistoryLineId"] == null ? null : json["userChatHistoryLineId"], + contant: json["contant"] == null ? null : json["contant"], + contantNo: json["contantNo"] == null ? null : json["contantNo"], + currentUserId: json["currentUserId"] == null ? null : json["currentUserId"], + currentUserName: json["currentUserName"] == null ? null : json["currentUserName"], + targetUserId: json["targetUserId"] == null ? null : json["targetUserId"], + targetUserName: json["targetUserName"] == null ? null : json["targetUserName"], + encryptedTargetUserId: json["encryptedTargetUserId"] == null ? null : json["encryptedTargetUserId"], + encryptedTargetUserName: json["encryptedTargetUserName"] == null ? null : json["encryptedTargetUserName"], + chatEventId: json["chatEventId"] == null ? null : json["chatEventId"], + fileTypeId: json["fileTypeId"], + isSeen: json["isSeen"] == null ? null : json["isSeen"], + isDelivered: json["isDelivered"] == null ? null : json["isDelivered"], + createdDate: json["createdDate"] == null ? null : DateTime.parse(json["createdDate"]), + chatSource: json["chatSource"] == null ? null : json["chatSource"], + conversationId: json["conversationId"] == null ? null : json["conversationId"], + fileTypeResponse: json["fileTypeResponse"] == null ? null : FileTypeResponse.fromJson(json["fileTypeResponse"]), + userChatReplyResponse: json["userChatReplyResponse"] == null ? null : UserChatReplyResponse.fromJson(json["userChatReplyResponse"]), + isReplied: false, + isImageLoaded: false, + image: null); Map toJson() => { "userChatHistoryId": userChatHistoryId == null ? null : userChatHistoryId, @@ -138,6 +144,8 @@ class UserChatReplyResponse { this.targetUserId, this.targetUserName, this.fileTypeResponse, + this.isImageLoaded, + this.image, }); int? userChatHistoryId; @@ -149,18 +157,21 @@ class UserChatReplyResponse { int? targetUserId; String? targetUserName; FileTypeResponse? fileTypeResponse; + bool? isImageLoaded; + Uint8List? image; factory UserChatReplyResponse.fromJson(Map json) => UserChatReplyResponse( - userChatHistoryId: json["userChatHistoryId"] == null ? null : json["userChatHistoryId"], - chatEventId: json["chatEventId"] == null ? null : json["chatEventId"], - contant: json["contant"] == null ? null : json["contant"], - contantNo: json["contantNo"] == null ? null : json["contantNo"], - fileTypeId: json["fileTypeId"], - createdDate: json["createdDate"] == null ? null : DateTime.parse(json["createdDate"]), - targetUserId: json["targetUserId"] == null ? null : json["targetUserId"], - targetUserName: json["targetUserName"] == null ? null : json["targetUserName"], - fileTypeResponse: json["fileTypeResponse"] == null ? null : FileTypeResponse.fromJson(json["fileTypeResponse"]), - ); + userChatHistoryId: json["userChatHistoryId"] == null ? null : json["userChatHistoryId"], + chatEventId: json["chatEventId"] == null ? null : json["chatEventId"], + contant: json["contant"] == null ? null : json["contant"], + contantNo: json["contantNo"] == null ? null : json["contantNo"], + fileTypeId: json["fileTypeId"], + createdDate: json["createdDate"] == null ? null : DateTime.parse(json["createdDate"]), + targetUserId: json["targetUserId"] == null ? null : json["targetUserId"], + targetUserName: json["targetUserName"] == null ? null : json["targetUserName"], + fileTypeResponse: json["fileTypeResponse"] == null ? null : FileTypeResponse.fromJson(json["fileTypeResponse"]), + isImageLoaded: false, + image: null); Map toJson() => { "userChatHistoryId": userChatHistoryId == null ? null : userChatHistoryId, diff --git a/lib/provider/chat_provider_model.dart b/lib/provider/chat_provider_model.dart index 8184d28..2d01e40 100644 --- a/lib/provider/chat_provider_model.dart +++ b/lib/provider/chat_provider_model.dart @@ -125,6 +125,7 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { userChatHistory, receiverUID, ); + generateConvId(); } @@ -177,16 +178,14 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { try { StreamedResponse response = await ChatApiClient().uploadMedia(userId, file); if (response.statusCode == 200) { - result = jsonDecode( - await response.stream.bytesToString(), - ); + result = jsonDecode(await response.stream.bytesToString()); } else { result = []; } } catch (e) { - print(e); + throw e; } - ; + return result; } @@ -292,6 +291,15 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { data.first.targetUserName = temp.first.currentUserName; data.first.currentUserId = temp.first.targetUserId; data.first.currentUserName = temp.first.targetUserName; + 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); + } + if (data.first.userChatReplyResponse != null) { + if (data.first.userChatReplyResponse!.fileTypeId == 12 || data.first.userChatReplyResponse!.fileTypeId == 4 || data.first.userChatReplyResponse!.fileTypeId == 3) { + data.first.userChatReplyResponse!.image = await ChatApiClient().downloadURL(fileName: data.first.contant!, fileTypeDescription: data.first.fileTypeResponse!.fileTypeDescription); + data.first.userChatReplyResponse!.isImageLoaded = true; + } + } } userChatHistory.insert(0, data.first); var list = [ @@ -389,7 +397,15 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { } Future sendChatToServer( - {required int chatEventId, required fileTypeId, required int targetUserId, required String targetUserName, required chatReplyId, required bool isAttachment, required bool isReply}) async { + {required int chatEventId, + required fileTypeId, + required int targetUserId, + required String targetUserName, + required chatReplyId, + required bool isAttachment, + required bool isReply, + Uint8List? image, + required bool isImageLoaded}) async { Uuid uuid = const Uuid(); var msg = message.text; @@ -416,6 +432,8 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { fileTypeDescription: getFileTypeDescription(getFileExtension(selectedFile.path).toString()), ) : null, + image: image, + isImageLoaded: isImageLoaded, ); userChatHistory.insert(0, data); isFileSelected = false; @@ -433,47 +451,68 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { dynamic contain = searchedChats!.where((ChatUser element) => element.id == targetUserId); if (contain.isEmpty) { searchedChats!.add( - ChatUser( - id: targetUserId, - userName: targetUserName, - ), + ChatUser(id: targetUserId, userName: targetUserName, unreadMessageCount: 0), ); notifyListeners(); } if (!isFileSelected && !isMsgReply) { + print("Normal Text Msg"); if (message.text == null || message.text.isEmpty) { return; } - sendChatToServer(chatEventId: 1, fileTypeId: null, targetUserId: targetUserId, targetUserName: targetUserName, isAttachment: false, chatReplyId: null, isReply: false); - } + sendChatToServer( + chatEventId: 1, fileTypeId: null, targetUserId: targetUserId, targetUserName: targetUserName, isAttachment: false, chatReplyId: null, isReply: false, isImageLoaded: false, image: null); + } // normal Text msg if (isFileSelected && !isMsgReply) { + print("Normal Attachment Msg"); Utils.showLoading(context); dynamic value = await uploadAttachments(AppState().chatDetails!.response!.id.toString(), selectedFile); + logger.d(value); String? ext = getFileExtension(selectedFile.path); Utils.hideLoading(context); - sendChatToServer(chatEventId: 2, fileTypeId: getFileType(ext.toString()), targetUserId: targetUserId, targetUserName: targetUserName, isAttachment: true, chatReplyId: null, isReply: false); - } + sendChatToServer( + chatEventId: 2, + fileTypeId: getFileType(ext.toString()), + targetUserId: targetUserId, + targetUserName: targetUserName, + isAttachment: true, + chatReplyId: null, + isReply: false, + isImageLoaded: true, + image: selectedFile.readAsBytesSync()); + } // normal attachemnt msg if (!isFileSelected && isMsgReply) { + print("Normal Text To Text Reply"); if (message.text == null || message.text.isEmpty) { return; } sendChatToServer( - chatEventId: 1, fileTypeId: null, targetUserId: targetUserId, targetUserName: targetUserName, chatReplyId: repliedMsg.first.userChatHistoryId, isAttachment: false, isReply: true); - } + chatEventId: 1, + fileTypeId: null, + targetUserId: targetUserId, + targetUserName: targetUserName, + chatReplyId: repliedMsg.first.userChatHistoryId, + isAttachment: false, + isReply: true, + isImageLoaded: repliedMsg.first.isImageLoaded!, + image: repliedMsg.first.image); + } // reply msg over image && normal if (isFileSelected && isMsgReply) { + print("Reply With File"); Utils.showLoading(context); dynamic value = await uploadAttachments(AppState().chatDetails!.response!.id.toString(), selectedFile); String? ext = getFileExtension(selectedFile.path); Utils.hideLoading(context); sendChatToServer( - chatEventId: 2, - fileTypeId: getFileType(ext.toString()), - targetUserId: targetUserId, - targetUserName: targetUserName, - isAttachment: true, - chatReplyId: repliedMsg.first.userChatHistoryId, - isReply: true, - ); + chatEventId: 2, + fileTypeId: getFileType(ext.toString()), + targetUserId: targetUserId, + targetUserName: targetUserName, + isAttachment: true, + chatReplyId: repliedMsg.first.userChatHistoryId, + isReply: true, + isImageLoaded: true, + image: selectedFile.readAsBytesSync()); } } @@ -652,10 +691,10 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { ); } - // Future getDownLoadFile(String fileName) async { - // var data = await ChatApiClient().downloadURL(fileName: "data"); - // Image.memory(data); - // } +// Future getDownLoadFile(String fileName) async { +// var data = await ChatApiClient().downloadURL(fileName: "data"); +// Image.memory(data); +// } // void getUserChatHistoryNotDeliveredAsync({required int userId}) async { // try { @@ -665,12 +704,4 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { // } // } - - - - - - - - } diff --git a/lib/ui/chat/chat_bubble.dart b/lib/ui/chat/chat_bubble.dart index 8382585..e69e683 100644 --- a/lib/ui/chat/chat_bubble.dart +++ b/lib/ui/chat/chat_bubble.dart @@ -3,161 +3,44 @@ import 'dart:typed_data'; import 'package:flutter/material.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/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'; // todo: @aamir use extension methods, and use correct widgets. class ChatBubble extends StatelessWidget { - const ChatBubble( - {Key? key, - required this.text, - required this.replyText, - required this.isCurrentUser, - required this.isSeen, - required this.isDelivered, - required this.dateTime, - required this.isReplied, - required this.userName, - this.fileTypeID, - this.fileTypeDescription}) - : super(key: key); - final String text; - final String replyText; - final bool isCurrentUser; - final bool isSeen; - final bool isDelivered; + ChatBubble({Key? key, required this.dateTime, required this.cItem}) : super(key: key); final String dateTime; - final bool isReplied; - final String userName; - final int? fileTypeID; - final String? fileTypeDescription; + final SingleUserChatModel cItem; + + bool isCurrentUser = false; + bool isSeen = false; + bool isReplied = false; + int? fileTypeID; + + String? fileTypeDescription; + bool isDelivered = false; + String userName = ''; + + void makeAssign() { + isCurrentUser = cItem.currentUserId == AppState().chatDetails!.response!.id ? true : false; + isSeen = cItem.isSeen == true ? true : false; + isReplied = cItem.userChatReplyResponse != null ? true : false; + fileTypeID = cItem.fileTypeId; + 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(); + } @override Widget build(BuildContext context) { + makeAssign(); return isCurrentUser ? currentUser(context) : receiptUser(context); - - return Padding( - // padding: EdgeInsets.zero, - padding: EdgeInsets.only( - left: isCurrentUser ? 110 : 20, - right: isCurrentUser ? 20 : 110, - bottom: 9, - ), - - child: Align( - alignment: isCurrentUser ? Alignment.centerRight : Alignment.centerLeft, - child: DecoratedBox( - decoration: BoxDecoration( - color: MyColors.white, - gradient: isCurrentUser - ? null - : const LinearGradient( - transform: GradientRotation( - .46, - ), - begin: Alignment.topRight, - end: Alignment.bottomLeft, - colors: [ - MyColors.gradiantEndColor, - MyColors.gradiantStartColor, - ], - ), - borderRadius: BorderRadius.circular( - 10, - ), - ), - child: Padding( - padding: EdgeInsets.only( - top: isReplied ? 8 : 5, - right: 8, - left: 8, - bottom: 5, - ), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - mainAxisAlignment: MainAxisAlignment.start, - children: [ - if (isReplied) - ClipRRect( - borderRadius: BorderRadius.circular( - 5.0, - ), - child: Container( - decoration: BoxDecoration( - border: Border( - left: BorderSide( - width: 6, - color: isCurrentUser ? MyColors.gradiantStartColor : MyColors.white, - ), - ), - color: isCurrentUser ? MyColors.black.withOpacity(0.10) : MyColors.black.withOpacity(0.30), - ), - child: Row( - children: [ - Expanded( - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - (userName) - .toText12( - color: MyColors.gradiantStartColor, - isBold: false, - ) - .paddingOnly( - right: 5, - top: 5, - bottom: 0, - left: 5, - ), - replyText - .toText10( - color: isCurrentUser ? MyColors.grey71Color : MyColors.white.withOpacity(0.5), - isBold: false, - maxlines: 4, - ) - .paddingOnly( - right: 5, - top: 5, - bottom: 8, - left: 5, - ), - ], - ), - ), - ], - ), - ), - ), - if (isReplied) 8.height, - text.toText12( - color: isCurrentUser ? MyColors.grey57Color : MyColors.white, - ), - Row( - crossAxisAlignment: CrossAxisAlignment.end, - mainAxisAlignment: MainAxisAlignment.end, - children: [ - dateTime.toText12( - color: isCurrentUser ? MyColors.grey41Color.withOpacity(.5) : MyColors.white.withOpacity(0.7), - ), - if (isCurrentUser) 5.width, - if (isCurrentUser) - Icon( - isDelivered ? Icons.done_all : Icons.done_all, - color: isSeen ? MyColors.textMixColor : MyColors.grey9DColor, - size: 14, - ), - ], - ), - ], - ), - ), - ), - ), - ); } Widget currentUser(context) { @@ -166,9 +49,7 @@ class ChatBubble extends StatelessWidget { children: [ if (isReplied) ClipRRect( - borderRadius: BorderRadius.circular( - 5.0, - ), + borderRadius: BorderRadius.circular(5.0), child: Container( width: double.infinity, decoration: BoxDecoration( @@ -177,29 +58,47 @@ class ChatBubble extends StatelessWidget { ), color: isCurrentUser ? MyColors.black.withOpacity(0.10) : MyColors.black.withOpacity(0.30), ), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - (userName).toText12(color: MyColors.gradiantStartColor, isBold: false).paddingOnly(right: 5, top: 5, bottom: 0, left: 5), - replyText.toText10(color: isCurrentUser ? MyColors.grey71Color : MyColors.white.withOpacity(0.5), isBold: false, maxlines: 4).paddingOnly(right: 5, top: 5, bottom: 8, left: 5), + child: Row( + children: [ + Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + (userName).toText12(color: MyColors.gradiantStartColor, isBold: false).paddingOnly(right: 5, top: 5, bottom: 0, left: 5), + (cItem.userChatReplyResponse != null ? cItem.userChatReplyResponse!.contant.toString() : "") + .toText10(color: isCurrentUser ? MyColors.grey71Color : MyColors.white.withOpacity(0.5), isBold: false, maxlines: 4) + .paddingOnly(right: 5, top: 5, bottom: 8, left: 5), + ], + ).expanded, + if (cItem.userChatReplyResponse != null && cItem.userChatReplyResponse!.fileTypeId == 12 || + cItem.userChatReplyResponse!.fileTypeId == 3 || + cItem.userChatReplyResponse!.fileTypeId == 4) + ClipRRect( + borderRadius: BorderRadius.circular( + 8, + ), + child: showImage( + isReplyPreview: true, + fileName: cItem.userChatReplyResponse!.contant!, + fileTypeDescription: cItem.userChatReplyResponse!.fileTypeResponse!.fileTypeDescription ?? "image/jpg") + .paddingOnly(left: 10, right: 10, bottom: 16, top: 16), + ) ], - ).expanded, + ), ), ).paddingOnly(right: 5, bottom: 7), - if (fileTypeID == 12 || fileTypeID == 4 || fileTypeID == 3) showImage().paddingOnly(right: 5), - if (fileTypeID != 12 || fileTypeID != 4 || fileTypeID != 3) (text).toText12(), + if (fileTypeID == 12 || fileTypeID == 4 || fileTypeID == 3) + showImage(isReplyPreview: false, fileName: cItem.contant!, fileTypeDescription: cItem.fileTypeResponse!.fileTypeDescription).paddingOnly(right: 5), + cItem.contant!.toText12(), Align( alignment: Alignment.centerRight, child: Row( mainAxisSize: MainAxisSize.min, children: [ - dateTime.toText10(color: MyColors.grey41Color.withOpacity(.5)), - 7.width, - Icon( - isDelivered ? Icons.done_all : Icons.done_all, - color: isSeen ? MyColors.textMixColor : MyColors.grey9DColor, - size: 14, + dateTime.toText10( + color: MyColors.grey41Color.withOpacity(.5), ), + 7.width, + Icon(isDelivered ? Icons.done_all : Icons.done_all, color: isSeen ? MyColors.textMixColor : MyColors.grey9DColor, size: 14), ], ), ), @@ -227,27 +126,43 @@ class ChatBubble extends StatelessWidget { children: [ if (isReplied) ClipRRect( - borderRadius: BorderRadius.circular( - 5.0, - ), + borderRadius: BorderRadius.circular(5.0), child: Container( width: double.infinity, decoration: BoxDecoration( - border: Border( - left: BorderSide(width: 6, color: isCurrentUser ? MyColors.gradiantStartColor : MyColors.white), - ), + border: Border(left: BorderSide(width: 6, color: isCurrentUser ? MyColors.gradiantStartColor : MyColors.white)), color: isCurrentUser ? MyColors.black.withOpacity(0.10) : MyColors.black.withOpacity(0.30), ), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - (userName).toText12(color: MyColors.gradiantStartColor, isBold: false).paddingOnly(right: 5, top: 5, bottom: 0, left: 5), - replyText.toText10(color: isCurrentUser ? MyColors.grey71Color : MyColors.white.withOpacity(0.5), isBold: false, maxlines: 4).paddingOnly(right: 5, top: 5, bottom: 8, left: 5), + child: Row( + children: [ + Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + (userName).toText12(color: MyColors.gradiantStartColor, isBold: false).paddingOnly(right: 5, top: 5, bottom: 0, left: 5), + (cItem.userChatReplyResponse != null ? cItem.userChatReplyResponse!.contant.toString() : "") + .toText10(color: isCurrentUser ? MyColors.grey71Color : MyColors.white.withOpacity(0.5), isBold: false, maxlines: 4) + .paddingOnly(right: 5, top: 5, bottom: 8, left: 5), + ], + ).expanded, + if (cItem.userChatReplyResponse != null && cItem.userChatReplyResponse!.fileTypeId == 12 || + cItem.userChatReplyResponse!.fileTypeId == 3 || + cItem.userChatReplyResponse!.fileTypeId == 4) + ClipRRect( + borderRadius: BorderRadius.circular(8.0), + child: showImage( + isReplyPreview: true, + fileName: cItem.userChatReplyResponse!.contant!, + fileTypeDescription: cItem.userChatReplyResponse!.fileTypeResponse!.fileTypeDescription ?? "image/jpg") + .paddingOnly(left: 10, right: 10, bottom: 16, top: 16), + ) ], - ).expanded, + ), ), ).paddingOnly(right: 5, bottom: 7), - if (fileTypeID == 12 || fileTypeID == 4 || fileTypeID == 3) showImage().paddingOnly(right: 5) else (text).toText12(color: Colors.white), + if (fileTypeID == 12 || fileTypeID == 4 || fileTypeID == 3) + showImage(isReplyPreview: false, fileName: cItem.contant!, fileTypeDescription: cItem.fileTypeResponse!.fileTypeDescription).paddingOnly(right: 5) + else + (cItem.contant! ?? "").toText12(color: Colors.white), Align( alignment: Alignment.centerRight, child: dateTime.toText10( @@ -259,25 +174,41 @@ class ChatBubble extends StatelessWidget { ).paddingOnly(right: MediaQuery.of(context).size.width * 0.3); } - Widget showImage() { - return FutureBuilder( - future: ChatApiClient().downloadURL(fileName: text, fileTypeDescription: fileTypeDescription!), - builder: (BuildContext context, AsyncSnapshot snapshot) { - if (snapshot.connectionState != ConnectionState.waiting) { - if (snapshot.data == null) { - return (text).toText12(color: Colors.white); + Widget showImage({required bool isReplyPreview, required String fileName, required String fileTypeDescription}) { + if (cItem.isImageLoaded! && cItem.image != null) { + return Image.memory( + cItem.image!, + height: isReplyPreview ? 32 : 140, + width: isReplyPreview ? 32 : 227, + fit: BoxFit.cover, + ); + } else { + return FutureBuilder( + future: ChatApiClient().downloadURL(fileName: fileName, fileTypeDescription: fileTypeDescription), + builder: (BuildContext context, AsyncSnapshot snapshot) { + if (snapshot.connectionState != ConnectionState.waiting) { + if (snapshot.data == null) { + return (cItem.contant.toString()).toText12(); + } else { + //data = image; + cItem.image = snapshot.data; + cItem.isImageLoaded = true; + return Image.memory( + snapshot.data, + height: isReplyPreview ? 32 : 140, + width: isReplyPreview ? 32 : 227, + fit: BoxFit.cover, + ); + } } else { - return Image.memory( - snapshot.data, - height: 140, - width: 227, - fit: BoxFit.cover, + return SizedBox( + height: isReplyPreview ? 32 : 140, + width: isReplyPreview ? 32 : 227, + child: const Center(child: CircularProgressIndicator()), ); } - } else { - return const SizedBox(height: 140, width: 227, child: Center(child: CircularProgressIndicator())); - } - }, - ); + }, + ); + } } } diff --git a/lib/ui/chat/chat_detailed_screen.dart b/lib/ui/chat/chat_detailed_screen.dart index 4dc7c35..643cc19 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_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'; import 'package:mohem_flutter_app/ui/chat/chat_bubble.dart'; @@ -115,16 +116,8 @@ class _ChatDetailScreenState extends State { return SwipeTo( iconColor: MyColors.lightGreenColor, child: ChatBubble( - text: m.userChatHistory[i].contant.toString(), - replyText: m.userChatHistory[i].userChatReplyResponse != null ? m.userChatHistory[i].userChatReplyResponse!.contant.toString() : "", - isSeen: m.userChatHistory[i].isSeen == true ? true : false, - isCurrentUser: m.userChatHistory[i].currentUserId == AppState().chatDetails!.response!.id ? true : false, - isDelivered: m.userChatHistory[i].currentUserId == AppState().chatDetails!.response!.id && m.userChatHistory[i].isDelivered == true ? true : false, dateTime: m.dateFormte(m.userChatHistory[i].createdDate!), - isReplied: m.userChatHistory[i].userChatReplyResponse != null ? true : false, - userName: AppState().chatDetails!.response!.userName == m.userChatHistory[i].currentUserName.toString() ? "You" : m.userChatHistory[i].currentUserName.toString(), - fileTypeID: m.userChatHistory[i].fileTypeId, - fileTypeDescription: m.userChatHistory[i].fileTypeResponse!.fileTypeDescription, + cItem: m.userChatHistory[i], ), onRightSwipe: () { m.chatReply( @@ -159,6 +152,8 @@ class _ChatDetailScreenState extends State { ], ).expanded, 12.width, + if (m.isMsgReply && m.repliedMsg.isNotEmpty) showReplyImage(m.repliedMsg), + 12.width, const Icon(Icons.cancel, size: 23, color: MyColors.grey7BColor).onPress(m.closeMe), ], ), @@ -224,6 +219,22 @@ class _ChatDetailScreenState extends State { ); } + Widget showReplyImage(List data) { + if (data.first.isImageLoaded! && data.first.image != null) { + return ClipRRect( + borderRadius: BorderRadius.circular(10.0), + child: Image.memory( + data.first.image!, + height: 43, + width: 43, + fit: BoxFit.cover, + ), + ); + } else { + return const SizedBox(); + } + } + void makeCall({required String callType, required HubConnection con}) async { print("================== Make call Triggered ============================"); Map json = { From 3309541142f9351bd56b6cfad8427fd533f1b776 Mon Sep 17 00:00:00 2001 From: "Aamir.Muhammad" Date: Tue, 29 Nov 2022 16:36:15 +0300 Subject: [PATCH 02/35] Chat Fixes & Chat Media Preview Api Implementation / On Msg Received Image --- lib/provider/chat_provider_model.dart | 47 ++++++++++++++---------- lib/ui/chat/chat_bubble.dart | 12 ++++-- lib/ui/chat/chat_full_image_preview.dart | 40 ++++++++++++++++++++ 3 files changed, 76 insertions(+), 23 deletions(-) create mode 100644 lib/ui/chat/chat_full_image_preview.dart diff --git a/lib/provider/chat_provider_model.dart b/lib/provider/chat_provider_model.dart index 2d01e40..b0a3b31 100644 --- a/lib/provider/chat_provider_model.dart +++ b/lib/provider/chat_provider_model.dart @@ -292,16 +292,21 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { data.first.currentUserId = temp.first.targetUserId; data.first.currentUserName = temp.first.targetUserName; 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); + data.first.image = await ChatApiClient().downloadURL(fileName: data.first.contant!, fileTypeDescription: data.first.fileTypeResponse!.fileTypeDescription ?? "image/jpg"); } if (data.first.userChatReplyResponse != null) { - if (data.first.userChatReplyResponse!.fileTypeId == 12 || data.first.userChatReplyResponse!.fileTypeId == 4 || data.first.userChatReplyResponse!.fileTypeId == 3) { - data.first.userChatReplyResponse!.image = await ChatApiClient().downloadURL(fileName: data.first.contant!, fileTypeDescription: data.first.fileTypeResponse!.fileTypeDescription); - data.first.userChatReplyResponse!.isImageLoaded = true; + if (data.first.fileTypeResponse != null) { + if (data.first.userChatReplyResponse!.fileTypeId == 12 || data.first.userChatReplyResponse!.fileTypeId == 4 || data.first.userChatReplyResponse!.fileTypeId == 3) { + data.first.userChatReplyResponse!.image = + await ChatApiClient().downloadURL(fileName: data.first.userChatReplyResponse!.contant!, fileTypeDescription: data.first.fileTypeResponse!.fileTypeDescription ?? "image/jpg"); + data.first.userChatReplyResponse!.isImageLoaded = true; + } } } } + userChatHistory.insert(0, data.first); + var list = [ { "userChatHistoryId": data.first.userChatHistoryId, @@ -310,7 +315,9 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { "isSeen": isChatScreenActive ? true : false, } ]; + updateUserChatHistoryStatusAsync(list); + notifyListeners(); } @@ -666,22 +673,22 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { sFileType = ""; } - // void scrollListener() { - // _firstAutoscrollExecuted = true; - // if (scrollController.hasClients && scrollController.position.pixels == scrollController.position.maxScrollExtent) { - // _shouldAutoscroll = true; - // } else { - // _shouldAutoscroll = false; - // } - // } - // - // void scrollToBottom() { - // scrollController.animateTo( - // scrollController.position.maxScrollExtent + 100, - // duration: const Duration(milliseconds: 500), - // curve: Curves.easeIn, - // ); - // } +// void scrollListener() { +// _firstAutoscrollExecuted = true; +// if (scrollController.hasClients && scrollController.position.pixels == scrollController.position.maxScrollExtent) { +// _shouldAutoscroll = true; +// } else { +// _shouldAutoscroll = false; +// } +// } +// +// void scrollToBottom() { +// scrollController.animateTo( +// scrollController.position.maxScrollExtent + 100, +// duration: const Duration(milliseconds: 500), +// curve: Curves.easeIn, +// ); +// } void msgScroll() { scrollController.animateTo( diff --git a/lib/ui/chat/chat_bubble.dart b/lib/ui/chat/chat_bubble.dart index e69e683..62156c8 100644 --- a/lib/ui/chat/chat_bubble.dart +++ b/lib/ui/chat/chat_bubble.dart @@ -10,6 +10,8 @@ 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/ui/chat/chat_full_image_preview.dart'; +import 'package:mohem_flutter_app/widgets/bottom_sheet.dart'; // todo: @aamir use extension methods, and use correct widgets. @@ -87,7 +89,9 @@ class ChatBubble extends StatelessWidget { ), ).paddingOnly(right: 5, bottom: 7), if (fileTypeID == 12 || fileTypeID == 4 || fileTypeID == 3) - showImage(isReplyPreview: false, fileName: cItem.contant!, fileTypeDescription: cItem.fileTypeResponse!.fileTypeDescription).paddingOnly(right: 5), + showImage(isReplyPreview: false, fileName: cItem.contant!, fileTypeDescription: cItem.fileTypeResponse!.fileTypeDescription).paddingOnly(right: 5).onPress(() { + showDialog(context: context, builder: (index) => ChatImagePreviewScreen(imgTitle: cItem.contant!, img: cItem.image!)); + }), cItem.contant!.toText12(), Align( alignment: Alignment.centerRight, @@ -160,7 +164,9 @@ class ChatBubble extends StatelessWidget { ), ).paddingOnly(right: 5, bottom: 7), if (fileTypeID == 12 || fileTypeID == 4 || fileTypeID == 3) - showImage(isReplyPreview: false, fileName: cItem.contant!, fileTypeDescription: cItem.fileTypeResponse!.fileTypeDescription).paddingOnly(right: 5) + showImage(isReplyPreview: false, fileName: cItem.contant!, fileTypeDescription: cItem.fileTypeResponse!.fileTypeDescription ?? "image/jpg").paddingOnly(right: 5).onPress(() { + showDialog(context: context, builder: (index) => ChatImagePreviewScreen(imgTitle: cItem.contant!, img: cItem.image!)); + }) else (cItem.contant! ?? "").toText12(color: Colors.white), Align( @@ -188,7 +194,7 @@ class ChatBubble extends StatelessWidget { builder: (BuildContext context, AsyncSnapshot snapshot) { if (snapshot.connectionState != ConnectionState.waiting) { if (snapshot.data == null) { - return (cItem.contant.toString()).toText12(); + return SizedBox(); } else { //data = image; cItem.image = snapshot.data; diff --git a/lib/ui/chat/chat_full_image_preview.dart b/lib/ui/chat/chat_full_image_preview.dart new file mode 100644 index 0000000..2a5d794 --- /dev/null +++ b/lib/ui/chat/chat_full_image_preview.dart @@ -0,0 +1,40 @@ +import 'dart:typed_data'; + +import 'package:flutter/material.dart'; +import 'package:mohem_flutter_app/classes/colors.dart'; +import 'package:mohem_flutter_app/extensions/widget_extensions.dart'; + +class ChatImagePreviewScreen extends StatelessWidget { + const ChatImagePreviewScreen({Key? key, required this.imgTitle, required this.img}) : super(key: key); + + final String imgTitle; + final Uint8List img; + + @override + Widget build(BuildContext context) { + return GestureDetector( + onTap: () { + Navigator.of(context).pop(); + }, + child: Dialog( + backgroundColor: Colors.transparent, + insetPadding: const EdgeInsets.all(10), + child: Stack( + alignment: Alignment.center, + children: [ + Image.memory( + img, + fit: BoxFit.cover, + + ).paddingAll(10), + const Positioned( + right: 0, + top: 0, + child: Icon(Icons.cancel, color: MyColors.redA3Color, size: 35), + ) + ], + ), + ), + ); + } +} From cd0b00021dd6dae91d2905632f49954dad4d5b50 Mon Sep 17 00:00:00 2001 From: "Aamir.Muhammad" Date: Tue, 29 Nov 2022 16:40:23 +0300 Subject: [PATCH 03/35] Chat Fixes & Chat Media Preview Api Implementation / On Msg Received Image --- lib/ui/chat/chat_full_image_preview.dart | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/ui/chat/chat_full_image_preview.dart b/lib/ui/chat/chat_full_image_preview.dart index 2a5d794..2eaa09d 100644 --- a/lib/ui/chat/chat_full_image_preview.dart +++ b/lib/ui/chat/chat_full_image_preview.dart @@ -25,7 +25,7 @@ class ChatImagePreviewScreen extends StatelessWidget { Image.memory( img, fit: BoxFit.cover, - + ).paddingAll(10), const Positioned( right: 0, From 492b6b5e34056aef345ba1c3556616fccceecc2d Mon Sep 17 00:00:00 2001 From: Sultan khan <> Date: Tue, 29 Nov 2022 16:46:48 +0300 Subject: [PATCH 04/35] basic details issue fixed --- .../dynamic_input_basic_details_screen.dart | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/lib/ui/profile/dynamic_screens/dynamic_input_basic_details_screen.dart b/lib/ui/profile/dynamic_screens/dynamic_input_basic_details_screen.dart index 444b83e..749599c 100644 --- a/lib/ui/profile/dynamic_screens/dynamic_input_basic_details_screen.dart +++ b/lib/ui/profile/dynamic_screens/dynamic_input_basic_details_screen.dart @@ -74,9 +74,9 @@ class _DynamicInputScreenState extends State { getBasicDetColsStructureList?.forEach((GetBasicDetColsStructureList element) { element.userBasicDetail = dynamicParams!.getEmployeeBasicDetailsList!.singleWhere((GetEmployeeBasicDetailsList userDetail) => userDetail.aPPLICATIONCOLUMNNAME == element.aPPLICATIONCOLUMNNAME); - if (element.objectValuesList != null) { - ObjectValuesList dropDownListValue = element.objectValuesList!.singleWhere((ObjectValuesList dropdown) => dropdown.cODE == element.userBasicDetail!.vARCHAR2VALUE); - element.userBasicDetail!.sEGMENTVALUEDSP = dropDownListValue.mEANING; + if (element.objectValuesList != null && element.userBasicDetail?.vARCHAR2VALUE != '') { + ObjectValuesList dropDownListValue = element.objectValuesList!.singleWhere((ObjectValuesList dropdown) => dropdown.cODE == element.userBasicDetail?.vARCHAR2VALUE); + element.userBasicDetail?.sEGMENTVALUEDSP = dropDownListValue.mEANING; } }); } else { @@ -93,9 +93,9 @@ class _DynamicInputScreenState extends State { getBasicDetColsStructureList?.forEach((GetBasicDetColsStructureList element) { element.userBasicDetail = dynamicParams!.getEmployeeBasicDetailsList!.singleWhere((GetEmployeeBasicDetailsList userDetail) => userDetail.aPPLICATIONCOLUMNNAME == element.aPPLICATIONCOLUMNNAME); - if (element.objectValuesList != null) { + if (element.objectValuesList != null && element.userBasicDetail!.vARCHAR2VALUE != '') { ObjectValuesList dropDownListValue = element.objectValuesList!.singleWhere((ObjectValuesList dropdown) => dropdown.cODE == element.userBasicDetail!.vARCHAR2VALUE); - element.userBasicDetail!.sEGMENTVALUEDSP = dropDownListValue.mEANING; + element.userBasicDetail?.sEGMENTVALUEDSP = dropDownListValue.mEANING; } }); } @@ -262,7 +262,7 @@ class _DynamicInputScreenState extends State { return PopupMenuButton( child: DynamicTextFieldWidget( (model.sEGMENTPROMPT ?? "") + (model.rEQUIREDFLAG == "Y" ? "*" : ""), - getBasicDetColsStructureList![index].userBasicDetail!.sEGMENTVALUEDSP ?? "", + getBasicDetColsStructureList![index].userBasicDetail?.sEGMENTVALUEDSP ?? "", isEnable: false, isPopup: true, ).paddingOnly(bottom: 12), @@ -363,7 +363,7 @@ class _DynamicInputScreenState extends State { Utils.showLoading(context); int numberValue = 0; List> values = getBasicDetDffStructureList!.map((e) { - String tempVar = e.userBasicDetail!.vARCHAR2VALUE ?? ""; + String tempVar = e.userBasicDetail?.vARCHAR2VALUE ?? ""; if (e.fORMATTYPE == "X") { // for date format type, date format is changed From b718f96c3a37bdef93d6ffbbd9945f61a4168563 Mon Sep 17 00:00:00 2001 From: Sikander Saleem Date: Tue, 29 Nov 2022 17:20:15 +0300 Subject: [PATCH 05/35] counter direction issue fix. --- lib/ui/landing/dashboard_screen.dart | 19 +- lib/ui/landing/today_attendance_screen2.dart | 13 +- lib/ui/marathon/widgets/countdown_timer.dart | 359 ++++++++++--------- 3 files changed, 200 insertions(+), 191 deletions(-) diff --git a/lib/ui/landing/dashboard_screen.dart b/lib/ui/landing/dashboard_screen.dart index b8a8d95..87c6b31 100644 --- a/lib/ui/landing/dashboard_screen.dart +++ b/lib/ui/landing/dashboard_screen.dart @@ -1,25 +1,21 @@ import 'dart:async'; -import 'dart:convert'; import 'dart:io'; +import 'dart:ui' as ui; import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:flutter_countdown_timer/flutter_countdown_timer.dart'; import 'package:flutter_svg/flutter_svg.dart'; -import 'package:mohem_flutter_app/api/dashboard_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/consts.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'; 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/main.dart'; import 'package:mohem_flutter_app/models/offers_and_discounts/get_offers_list.dart'; import 'package:mohem_flutter_app/provider/dashboard_provider_model.dart'; -import 'package:mohem_flutter_app/ui/landing/itg/its_add_screen_video_image.dart'; import 'package:mohem_flutter_app/ui/landing/widget/app_drawer.dart'; import 'package:mohem_flutter_app/ui/landing/widget/menus_widget.dart'; import 'package:mohem_flutter_app/ui/landing/widget/services_widget.dart'; @@ -237,11 +233,14 @@ class _DashboardScreenState extends State { crossAxisAlignment: CrossAxisAlignment.start, children: [ 9.height, - CountdownTimer( - endTime: model.endTime, - onEnd: null, - endWidget: "00:00:00".toText14(color: Colors.white, isBold: true), - textStyle: const TextStyle(color: Colors.white, fontSize: 14, letterSpacing: -0.48, fontWeight: FontWeight.bold), + Directionality( + textDirection: ui.TextDirection.ltr, + child: CountdownTimer( + endTime: model.endTime, + onEnd: null, + endWidget: "00:00:00".toText14(color: Colors.white, isBold: true), + textStyle: const TextStyle(color: Colors.white, fontSize: 14, letterSpacing: -0.48, fontWeight: FontWeight.bold), + ), ), LocaleKeys.timeLeftToday.tr().toText12(color: Colors.white), 9.height, diff --git a/lib/ui/landing/today_attendance_screen2.dart b/lib/ui/landing/today_attendance_screen2.dart index ada652c..f0228eb 100644 --- a/lib/ui/landing/today_attendance_screen2.dart +++ b/lib/ui/landing/today_attendance_screen2.dart @@ -99,10 +99,13 @@ class _TodayAttendanceScreenState extends State { child: CountdownTimer( endTime: model.endTime, widgetBuilder: (context, v) { - return AutoSizeText( - getValue(v?.hours) + " : " + getValue(v?.min) + " : " + getValue(v?.sec), - maxLines: 1, - style: const TextStyle(color: Colors.white, fontSize: 42, letterSpacing: -1.92, fontWeight: FontWeight.bold, height: 1), + return Directionality( + textDirection: TextDirection.ltr, + child: AutoSizeText( + getValue(v?.hours) + " : " + getValue(v?.min) + " : " + getValue(v?.sec), + maxLines: 1, + style: const TextStyle(color: Colors.white, fontSize: 42, letterSpacing: -1.92, fontWeight: FontWeight.bold, height: 1), + ), ); }, onEnd: null, @@ -116,7 +119,7 @@ class _TodayAttendanceScreenState extends State { mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: [ - LocaleKeys.shiftTime.tr().tr().toTextAuto(color: MyColors.greyACColor, fontSize: 18, maxLine: 1).paddingOnly(left: 21,right: 21), + LocaleKeys.shiftTime.tr().tr().toTextAuto(color: MyColors.greyACColor, fontSize: 18, maxLine: 1).paddingOnly(left: 21, right: 21), (model.attendanceTracking!.pShtName ?? "00:00:00").toString().toTextAuto(color: Colors.white, isBold: true, fontSize: 26, maxLine: 1), ], ), diff --git a/lib/ui/marathon/widgets/countdown_timer.dart b/lib/ui/marathon/widgets/countdown_timer.dart index bb8da6d..4296bc5 100644 --- a/lib/ui/marathon/widgets/countdown_timer.dart +++ b/lib/ui/marathon/widgets/countdown_timer.dart @@ -1,4 +1,5 @@ import 'dart:async'; +import 'dart:ui' as ui; import 'package:auto_size_text/auto_size_text.dart'; import 'package:easy_localization/easy_localization.dart'; @@ -53,80 +54,83 @@ class BuildCountdownTimer extends StatelessWidget { ); Widget buildEmptyWidget() { - return Row( - mainAxisSize: MainAxisSize.min, - mainAxisAlignment: MainAxisAlignment.spaceEvenly, - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Column( - children: [ - // todo @faiz: Make a separate method and pass string , so we can minimize code replication - AutoSizeText( - "00", - maxFontSize: 24, - minFontSize: 20, - style: screenFlag == 0 ? styleDigitHome : styleDigitMarathon, - ), - AutoSizeText( - LocaleKeys.days.tr(), - minFontSize: 7, - maxFontSize: 8, - style: screenFlag == 0 ? styleTextHome : styleTextMarathon, - ), - ], - ), - buildSeparator(), - Column( - children: [ - AutoSizeText( - "00", - maxFontSize: 24, - minFontSize: 20, - style: screenFlag == 0 ? styleDigitHome : styleDigitMarathon, - ), - AutoSizeText( - LocaleKeys.hours.tr(), - minFontSize: 7, - maxFontSize: 8, - style: screenFlag == 0 ? styleTextHome : styleTextMarathon, - ), - ], - ), - buildSeparator(), - Column( - children: [ - AutoSizeText( - "00", - maxFontSize: 24, - minFontSize: 20, - style: screenFlag == 0 ? styleDigitHome : styleDigitMarathon, - ), - AutoSizeText( - LocaleKeys.minutes.tr(), - minFontSize: 7, - maxFontSize: 8, - style: screenFlag == 0 ? styleTextHome : styleTextMarathon, - ), - ], - ), - buildSeparator(), - Column( - children: [ - AutoSizeText( - "00", - maxFontSize: 24, - minFontSize: 20, - style: screenFlag == 0 ? styleDigitHome : styleDigitMarathon, - ), - AutoSizeText( - LocaleKeys.seconds.tr(), - minFontSize: 7, - maxFontSize: 8, - style: screenFlag == 0 ? styleTextHome : styleTextMarathon, - ), - ], - ), - ], + return Directionality( + textDirection: ui.TextDirection.ltr, + child: Row( + mainAxisSize: MainAxisSize.min, + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Column( + children: [ + // todo @faiz: Make a separate method and pass string , so we can minimize code replication + AutoSizeText( + "00", + maxFontSize: 24, + minFontSize: 20, + style: screenFlag == 0 ? styleDigitHome : styleDigitMarathon, + ), + AutoSizeText( + LocaleKeys.days.tr(), + minFontSize: 7, + maxFontSize: 8, + style: screenFlag == 0 ? styleTextHome : styleTextMarathon, + ), + ], + ), + buildSeparator(), + Column( + children: [ + AutoSizeText( + "00", + maxFontSize: 24, + minFontSize: 20, + style: screenFlag == 0 ? styleDigitHome : styleDigitMarathon, + ), + AutoSizeText( + LocaleKeys.hours.tr(), + minFontSize: 7, + maxFontSize: 8, + style: screenFlag == 0 ? styleTextHome : styleTextMarathon, + ), + ], + ), + buildSeparator(), + Column( + children: [ + AutoSizeText( + "00", + maxFontSize: 24, + minFontSize: 20, + style: screenFlag == 0 ? styleDigitHome : styleDigitMarathon, + ), + AutoSizeText( + LocaleKeys.minutes.tr(), + minFontSize: 7, + maxFontSize: 8, + style: screenFlag == 0 ? styleTextHome : styleTextMarathon, + ), + ], + ), + buildSeparator(), + Column( + children: [ + AutoSizeText( + "00", + maxFontSize: 24, + minFontSize: 20, + style: screenFlag == 0 ? styleDigitHome : styleDigitMarathon, + ), + AutoSizeText( + LocaleKeys.seconds.tr(), + minFontSize: 7, + maxFontSize: 8, + style: screenFlag == 0 ? styleTextHome : styleTextMarathon, + ), + ], + ), + ], + ), ); } @@ -149,108 +153,111 @@ class BuildCountdownTimer extends StatelessWidget { return buildEmptyWidget(); } - return Row( - mainAxisSize: MainAxisSize.min, - mainAxisAlignment: MainAxisAlignment.spaceEvenly, - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Column( - children: [ - // todo @faiz: Make a separate method and pass value and string , so we can minimize code replication - time.days == null - ? AutoSizeText( - "00", - maxFontSize: 24, - minFontSize: 20, - style: screenFlag == 0 ? styleDigitHome : styleDigitMarathon, - ) - : AutoSizeText( - time.days! < 10 ? "0${time.days.toString()}" : time.days.toString(), - maxFontSize: 24, - minFontSize: 20, - style: screenFlag == 0 ? styleDigitHome : styleDigitMarathon, - ), - AutoSizeText( - LocaleKeys.days.tr(), - minFontSize: 7, - maxFontSize: 8, - style: screenFlag == 0 ? styleTextHome : styleTextMarathon, - ), - ], - ), - buildSeparator(), - Column( - children: [ - time.hours == null - ? AutoSizeText( - "00", - maxFontSize: 24, - minFontSize: 20, - style: screenFlag == 0 ? styleDigitHome : styleDigitMarathon, - ) - : AutoSizeText( - time.hours! < 10 ? "0${time.hours.toString()}" : time.hours.toString(), - maxFontSize: 24, - minFontSize: 20, - style: screenFlag == 0 ? styleDigitHome : styleDigitMarathon, - ), - AutoSizeText( - LocaleKeys.hours.tr(), - minFontSize: 7, - maxFontSize: 8, - style: screenFlag == 0 ? styleTextHome : styleTextMarathon, - ), - ], - ), - buildSeparator(), - Column( - children: [ - time.min == null - ? AutoSizeText( - "00", - maxFontSize: 24, - minFontSize: 20, - style: screenFlag == 0 ? styleDigitHome : styleDigitMarathon, - ) - : AutoSizeText( - time.min! < 10 ? "0${time.min.toString()}" : time.min.toString(), - maxFontSize: 24, - minFontSize: 20, - style: screenFlag == 0 ? styleDigitHome : styleDigitMarathon, - ), - AutoSizeText( - LocaleKeys.minutes.tr(), - minFontSize: 7, - maxFontSize: 8, - style: screenFlag == 0 ? styleTextHome : styleTextMarathon, - ), - ], - ), - buildSeparator(), - Column( - children: [ - time.sec == null - ? AutoSizeText( - "00", - maxFontSize: 24, - minFontSize: 20, - style: screenFlag == 0 ? styleDigitHome : styleDigitMarathon, - ) - : AutoSizeText( - time.sec! < 10 ? "0${time.sec.toString()}" : time.sec.toString(), - maxFontSize: 24, - minFontSize: 20, - style: screenFlag == 0 ? styleDigitHome : styleDigitMarathon, - ), - AutoSizeText( - LocaleKeys.seconds.tr(), - minFontSize: 7, - maxFontSize: 8, - style: screenFlag == 0 ? styleTextHome : styleTextMarathon, - ), - ], - ), - ], + return Directionality( + textDirection: ui.TextDirection.ltr, + child: Row( + mainAxisSize: MainAxisSize.min, + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Column( + children: [ + // todo @faiz: Make a separate method and pass value and string , so we can minimize code replication + time.days == null + ? AutoSizeText( + "00", + maxFontSize: 24, + minFontSize: 20, + style: screenFlag == 0 ? styleDigitHome : styleDigitMarathon, + ) + : AutoSizeText( + time.days! < 10 ? "0${time.days.toString()}" : time.days.toString(), + maxFontSize: 24, + minFontSize: 20, + style: screenFlag == 0 ? styleDigitHome : styleDigitMarathon, + ), + AutoSizeText( + LocaleKeys.days.tr(), + minFontSize: 7, + maxFontSize: 8, + style: screenFlag == 0 ? styleTextHome : styleTextMarathon, + ), + ], + ), + buildSeparator(), + Column( + children: [ + time.hours == null + ? AutoSizeText( + "00", + maxFontSize: 24, + minFontSize: 20, + style: screenFlag == 0 ? styleDigitHome : styleDigitMarathon, + ) + : AutoSizeText( + time.hours! < 10 ? "0${time.hours.toString()}" : time.hours.toString(), + maxFontSize: 24, + minFontSize: 20, + style: screenFlag == 0 ? styleDigitHome : styleDigitMarathon, + ), + AutoSizeText( + LocaleKeys.hours.tr(), + minFontSize: 7, + maxFontSize: 8, + style: screenFlag == 0 ? styleTextHome : styleTextMarathon, + ), + ], + ), + buildSeparator(), + Column( + children: [ + time.min == null + ? AutoSizeText( + "00", + maxFontSize: 24, + minFontSize: 20, + style: screenFlag == 0 ? styleDigitHome : styleDigitMarathon, + ) + : AutoSizeText( + time.min! < 10 ? "0${time.min.toString()}" : time.min.toString(), + maxFontSize: 24, + minFontSize: 20, + style: screenFlag == 0 ? styleDigitHome : styleDigitMarathon, + ), + AutoSizeText( + LocaleKeys.minutes.tr(), + minFontSize: 7, + maxFontSize: 8, + style: screenFlag == 0 ? styleTextHome : styleTextMarathon, + ), + ], + ), + buildSeparator(), + Column( + children: [ + time.sec == null + ? AutoSizeText( + "00", + maxFontSize: 24, + minFontSize: 20, + style: screenFlag == 0 ? styleDigitHome : styleDigitMarathon, + ) + : AutoSizeText( + time.sec! < 10 ? "0${time.sec.toString()}" : time.sec.toString(), + maxFontSize: 24, + minFontSize: 20, + style: screenFlag == 0 ? styleDigitHome : styleDigitMarathon, + ), + AutoSizeText( + LocaleKeys.seconds.tr(), + minFontSize: 7, + maxFontSize: 8, + style: screenFlag == 0 ? styleTextHome : styleTextMarathon, + ), + ], + ), + ], + ), ); } From 741259505d79ed1641007d7383b411eefb048b86 Mon Sep 17 00:00:00 2001 From: Sikander Saleem Date: Tue, 29 Nov 2022 17:25:31 +0300 Subject: [PATCH 06/35] marathon api const added. --- lib/classes/consts.dart | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/lib/classes/consts.dart b/lib/classes/consts.dart index bdeeecd..779cdec 100644 --- a/lib/classes/consts.dart +++ b/lib/classes/consts.dart @@ -26,6 +26,18 @@ class ApiConsts { static String chatMediaImageUploadUrl = chatServerBaseApiUrl + "shared/"; static String chatFavUser = chatServerBaseApiUrl + "FavUser/"; static String chatUserImages = chatServerBaseUrl + "empservice/api/employee/"; + + //Brain Marathon Constants + static String marathonBaseUrl = "https://18.188.181.12/service/"; + static String marathonParticipantLoginUrl = marathonBaseUrl + "api/auth/participantlogin"; + static String marathonProjectGetUrl = marathonBaseUrl + "api/Project/Project_Get"; + static String marathonUpcomingUrl = marathonBaseUrl + "api/marathon/upcoming/"; + static String marathonHubConnectionUrl = marathonBaseUrl + "MarathonBroadCast"; + + //DummyCards for the UI + + static CardContent dummyQuestion = const CardContent(); + } class SharedPrefsConsts { From cecb2d59e9e795d79b4b9963caa9ac8b7d1307a4 Mon Sep 17 00:00:00 2001 From: "Aamir.Muhammad" Date: Thu, 1 Dec 2022 15:21:06 +0300 Subject: [PATCH 07/35] Chat Fixes & Chat Media Preview Api Implementation / On Msg Received Image --- lib/api/chat/chat_api_client.dart | 25 +--- lib/classes/colors.dart | 1 + lib/classes/consts.dart | 4 +- lib/provider/chat_provider_model.dart | 169 +++++++++-------------- lib/ui/chat/chat_bubble.dart | 55 +++++--- lib/ui/chat/chat_detailed_screen.dart | 13 +- lib/ui/chat/chat_full_image_preview.dart | 3 +- lib/ui/chat/chat_home_screen.dart | 127 +++++++++++++++++ pubspec.yaml | 3 + 9 files changed, 250 insertions(+), 150 deletions(-) diff --git a/lib/api/chat/chat_api_client.dart b/lib/api/chat/chat_api_client.dart index 41f941f..1f97b1f 100644 --- a/lib/api/chat/chat_api_client.dart +++ b/lib/api/chat/chat_api_client.dart @@ -28,9 +28,7 @@ class ChatApiClient { "password": "FxIu26rWIKoF8n6mpbOmAjDLphzFGmpG", }, ); - user.UserAutoLoginModel userLoginResponse = user.userAutoLoginModelFromJson( - response.body, - ); + user.UserAutoLoginModel userLoginResponse = user.userAutoLoginModelFromJson(response.body); return userLoginResponse; } @@ -42,9 +40,7 @@ class ChatApiClient { return searchUserJsonModel(response.body); } - List searchUserJsonModel(String str) => List.from( - json.decode(str).map((x) => ChatUser.fromJson(x)), - ); + List searchUserJsonModel(String str) => List.from(json.decode(str).map((x) => ChatUser.fromJson(x))); Future getRecentChats() async { try { @@ -58,7 +54,6 @@ class ChatApiClient { } 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; @@ -98,9 +93,7 @@ class ChatApiClient { AppState().setchatUserDetails = userLoginResponse; getSingleUserChatHistory(senderUID: senderUID, receiverUID: receiverUID, loadMore: loadMore, paginationVal: paginationVal); } else { - Utils.showToast( - userLoginResponse.errorResponses!.first.fieldName.toString() + " Erorr", - ); + Utils.showToast(userLoginResponse.errorResponses!.first.fieldName.toString() + " Erorr"); } } throw e; @@ -108,13 +101,7 @@ class ChatApiClient { } 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); + Response response = await ApiClient().postJsonForResponse("${ApiConsts.chatFavUser}addFavUser", {"targetUserId": targetUserID, "userId": userID}, token: AppState().chatDetails!.response!.token); fav.FavoriteChatUser favoriteChatUser = fav.FavoriteChatUser.fromRawJson(response.body); return favoriteChatUser; } @@ -137,9 +124,7 @@ class ChatApiClient { AppState().setchatUserDetails = userLoginResponse; unFavUser(userID: userID, targetUserID: targetUserID); } else { - Utils.showToast( - userLoginResponse.errorResponses!.first.fieldName.toString() + " Erorr", - ); + Utils.showToast(userLoginResponse.errorResponses!.first.fieldName.toString() + " Erorr"); } } throw e; diff --git a/lib/classes/colors.dart b/lib/classes/colors.dart index 10681be..4394279 100644 --- a/lib/classes/colors.dart +++ b/lib/classes/colors.dart @@ -62,4 +62,5 @@ class MyColors { static const Color grey9DColor = Color(0xff9D9D9D); static const Color darkDigitColor = Color(0xff2D2F39); static const Color grey71Color = Color(0xff717171); + static const Color darkGrey3BColor = Color(0xff3B3B3B); } diff --git a/lib/classes/consts.dart b/lib/classes/consts.dart index 779cdec..13c4258 100644 --- a/lib/classes/consts.dart +++ b/lib/classes/consts.dart @@ -2,8 +2,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://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 95a990f..f3821f3 100644 --- a/lib/provider/chat_provider_model.dart +++ b/lib/provider/chat_provider_model.dart @@ -5,20 +5,15 @@ import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/foundation.dart'; import 'package:http/http.dart'; -import 'package:logging/logging.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/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/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/models/chat/get_user_login_token_model.dart' as login; 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:signalr_netcore/signalr_client.dart'; import 'package:uuid/uuid.dart'; class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { @@ -92,12 +87,7 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { if (isNewChat) userChatHistory = []; if (!loadMore) paginationVal = 0; isChatScreenActive = true; - Response response = await ChatApiClient().getSingleUserChatHistory( - senderUID: senderUID, - receiverUID: receiverUID, - loadMore: loadMore, - paginationVal: paginationVal, - ); + Response response = await ChatApiClient().getSingleUserChatHistory(senderUID: senderUID, receiverUID: receiverUID, loadMore: loadMore, paginationVal: paginationVal); if (response.statusCode == 204) { if (isNewChat) { userChatHistory = []; @@ -107,25 +97,15 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { } } else { if (loadMore) { - List temp = getSingleUserChatModel( - response.body, - ).reversed.toList(); - userChatHistory.addAll( - temp, - ); + List temp = getSingleUserChatModel(response.body).reversed.toList(); + userChatHistory.addAll(temp); } else { - userChatHistory = getSingleUserChatModel( - response.body, - ).reversed.toList(); + userChatHistory = getSingleUserChatModel(response.body).reversed.toList(); } } isLoading = false; notifyListeners(); - markRead( - userChatHistory, - receiverUID, - ); - + markRead(userChatHistory, receiverUID); generateConvId(); } @@ -139,13 +119,10 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { for (SingleUserChatModel element in data!) { if (element.isSeen != null) { if (!element.isSeen!) { + print("Found Un Read"); + logger.d(jsonEncode(element)); dynamic data = [ - { - "userChatHistoryId": element.userChatHistoryId, - "TargetUserId": element.targetUserId, - "isDelivered": true, - "isSeen": true, - } + {"userChatHistoryId": element.userChatHistoryId, "TargetUserId": element.targetUserId, "isDelivered": true, "isSeen": true} ]; updateUserChatHistoryStatusAsync(data); } @@ -161,17 +138,22 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { } void updateUserChatHistoryStatusAsync(List data) { - hubConnection.invoke( - "UpdateUserChatHistoryStatusAsync", - args: [data], - ); + try { + hubConnection.invoke("UpdateUserChatHistoryStatusAsync", args: [data]); + } catch (e) { + throw e; + } } - List getSingleUserChatModel(String str) => List.from( - json.decode(str).map( - (x) => SingleUserChatModel.fromJson(x), - ), - ); + void updateUserChatHistoryOnMsg(List data) { + try { + hubConnection.invoke("UpdateUserChatHistoryStatusAsync", args: [data]); + } catch (e) { + throw e; + } + } + + List getSingleUserChatModel(String str) => List.from(json.decode(str).map((x) => SingleUserChatModel.fromJson(x))); Future uploadAttachments(String userId, File file) async { dynamic result; @@ -191,15 +173,15 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { void updateUserChatStatus(List? args) { dynamic items = args!.toList(); - for (dynamic cItem in items[0]) { + for (var cItem in items[0]) { for (SingleUserChatModel chat in userChatHistory) { - if (chat.userChatHistoryId.toString() == cItem["userChatHistoryId"].toString()) { + if (cItem["contantNo"].toString() == chat.contantNo.toString()) { chat.isSeen = cItem["isSeen"]; chat.isDelivered = cItem["isDelivered"]; - notifyListeners(); } } } + notifyListeners(); } void onChatSeen(List? args) { @@ -308,14 +290,9 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { userChatHistory.insert(0, data.first); var list = [ - { - "userChatHistoryId": data.first.userChatHistoryId, - "TargetUserId": data.first.targetUserId, - "isDelivered": true, - "isSeen": isChatScreenActive ? true : false, - } + {"userChatHistoryId": data.first.userChatHistoryId, "TargetUserId": temp.first.targetUserId, "isDelivered": true, "isSeen": isChatScreenActive ? true : false} ]; - updateUserChatHistoryStatusAsync(list); + updateUserChatHistoryOnMsg(list); notifyListeners(); } @@ -412,34 +389,34 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { Uint8List? image, required bool isImageLoaded}) async { Uuid uuid = const Uuid(); + var contentNo = uuid.v4(); var msg = message.text; SingleUserChatModel data = SingleUserChatModel( - chatEventId: chatEventId, - chatSource: 1, - contant: msg, - contantNo: uuid.v4(), - conversationId: chatCID, - createdDate: DateTime.now(), - currentUserId: AppState().chatDetails!.response!.id, - currentUserName: AppState().chatDetails!.response!.userName, - targetUserId: targetUserId, - targetUserName: targetUserName, - isReplied: false, - fileTypeId: fileTypeId, - userChatReplyResponse: isReply ? UserChatReplyResponse.fromJson(repliedMsg.first.toJson()) : null, - fileTypeResponse: isAttachment - ? FileTypeResponse( - fileTypeId: fileTypeId, - fileTypeName: getFileType(getFileExtension(selectedFile.path).toString()), - fileKind: getFileExtension(selectedFile.path), - fileName: selectedFile.path.split("/").last, - fileTypeDescription: getFileTypeDescription(getFileExtension(selectedFile.path).toString()), - ) - : null, - image: image, - isImageLoaded: isImageLoaded, - ); + chatEventId: chatEventId, + chatSource: 1, + contant: msg, + contantNo: contentNo, + conversationId: chatCID, + createdDate: DateTime.now(), + currentUserId: AppState().chatDetails!.response!.id, + currentUserName: AppState().chatDetails!.response!.userName, + targetUserId: targetUserId, + targetUserName: targetUserName, + isReplied: false, + fileTypeId: fileTypeId, + userChatReplyResponse: isReply ? UserChatReplyResponse.fromJson(repliedMsg.first.toJson()) : null, + fileTypeResponse: isAttachment + ? FileTypeResponse( + fileTypeId: fileTypeId, + fileTypeName: getFileType(getFileExtension(selectedFile.path).toString()), + fileKind: getFileExtension(selectedFile.path), + fileName: selectedFile.path.split("/").last, + fileTypeDescription: getFileTypeDescription(getFileExtension(selectedFile.path).toString()), + ) + : null, + image: image, + isImageLoaded: isImageLoaded); userChatHistory.insert(0, data); isFileSelected = false; isMsgReply = false; @@ -448,7 +425,7 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { notifyListeners(); String chatData = - '{"contant":"$msg","contantNo":"${uuid.v4()}","chatEventId":$chatEventId,"fileTypeId": $fileTypeId,"currentUserId":${AppState().chatDetails!.response!.id},"chatSource":1,"userChatHistoryLineRequestList":[{"isSeen":false,"isDelivered":false,"targetUserId":$targetUserId,"targetUserStatus":1}],"chatReplyId":$chatReplyId,"conversationId":"$chatCID"}'; + '{"contant":"$msg","contantNo":"$contentNo","chatEventId":$chatEventId,"fileTypeId": $fileTypeId,"currentUserId":${AppState().chatDetails!.response!.id},"chatSource":1,"userChatHistoryLineRequestList":[{"isSeen":false,"isDelivered":false,"targetUserId":$targetUserId,"targetUserStatus":1}],"chatReplyId":$chatReplyId,"conversationId":"$chatCID"}'; await hubConnection.invoke("AddChatUserAsync", args: [json.decode(chatData)]); } @@ -456,11 +433,7 @@ 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 - ), + ChatUser(id: targetUserId, userName: targetUserName, unreadMessageCount: 0), ); notifyListeners(); } @@ -693,17 +666,21 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { // } void msgScroll() { - scrollController.animateTo( - scrollController.position.minScrollExtent - 100, - duration: const Duration(milliseconds: 500), - curve: Curves.easeIn, - ); - } - - // Future getDownLoadFile(String fileName) async { - // var data = await ChatApiClient().downloadURL(fileName: "data"); - // Image.memory(data); - // } + // scrollController.animateTo( + // // index: 150, + // duration: Duration(seconds: 2), + // curve: Curves.easeInOutCubic); + // scrollController.animateTo( + // scrollController.position.minScrollExtent - 100, + // duration: const Duration(milliseconds: 500), + // curve: Curves.easeIn, + // ); + } + +// Future getDownLoadFile(String fileName) async { +// var data = await ChatApiClient().downloadURL(fileName: "data"); +// Image.memory(data); +// } // void getUserChatHistoryNotDeliveredAsync({required int userId}) async { // try { @@ -713,12 +690,4 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { // } // } - - - - - - - - } diff --git a/lib/ui/chat/chat_bubble.dart b/lib/ui/chat/chat_bubble.dart index 62156c8..8995da1 100644 --- a/lib/ui/chat/chat_bubble.dart +++ b/lib/ui/chat/chat_bubble.dart @@ -74,23 +74,41 @@ 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, + borderRadius: BorderRadius.circular(8.0), + child: SizedBox( + height: 32, + width: 32, + child: showImage( + isReplyPreview: true, + fileName: cItem.userChatReplyResponse!.contant!, + fileTypeDescription: cItem.userChatReplyResponse!.fileTypeResponse!.fileTypeDescription ?? "image/jpg") + .paddingOnly(left: 10, right: 10, bottom: 16, top: 16), ), - child: showImage( - isReplyPreview: true, - fileName: cItem.userChatReplyResponse!.contant!, - fileTypeDescription: cItem.userChatReplyResponse!.fileTypeResponse!.fileTypeDescription ?? "image/jpg") - .paddingOnly(left: 10, right: 10, bottom: 16, top: 16), - ) + ), ], ), ), ).paddingOnly(right: 5, 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, builder: (index) => ChatImagePreviewScreen(imgTitle: cItem.contant!, img: cItem.image!)); + showDialog(context: context, builder: (BuildContext context) => ChatImagePreviewScreen(imgTitle: cItem.contant!, img: cItem.image!)); }), cItem.contant!.toText12(), Align( @@ -110,7 +128,7 @@ 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); } - Widget receiptUser(context) { + Widget receiptUser(BuildContext context) { return Container( padding: const EdgeInsets.only(top: 11, left: 13, right: 7, bottom: 5), decoration: BoxDecoration( @@ -153,27 +171,27 @@ class ChatBubble extends StatelessWidget { cItem.userChatReplyResponse!.fileTypeId == 4) ClipRRect( borderRadius: BorderRadius.circular(8.0), - child: showImage( + child: SizedBox( + height: 32, + width: 32, + child: showImage( isReplyPreview: true, fileName: cItem.userChatReplyResponse!.contant!, - fileTypeDescription: cItem.userChatReplyResponse!.fileTypeResponse!.fileTypeDescription ?? "image/jpg") - .paddingOnly(left: 10, right: 10, bottom: 16, top: 16), - ) + fileTypeDescription: cItem.userChatReplyResponse!.fileTypeResponse!.fileTypeDescription ?? "image/jpg")), + ).paddingOnly(left: 10, right: 10, bottom: 16, top: 16) ], ), ), ).paddingOnly(right: 5, 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, builder: (index) => ChatImagePreviewScreen(imgTitle: cItem.contant!, img: cItem.image!)); + showDialog(context: context, builder: (BuildContext context) => ChatImagePreviewScreen(imgTitle: cItem.contant!, img: cItem.image!)); }) else (cItem.contant! ?? "").toText12(color: Colors.white), Align( alignment: Alignment.centerRight, - child: dateTime.toText10( - color: Colors.white.withOpacity(.71), - ), + child: dateTime.toText10(color: Colors.white.withOpacity(.71)), ), ], ), @@ -196,7 +214,6 @@ class ChatBubble extends StatelessWidget { if (snapshot.data == null) { return SizedBox(); } else { - //data = image; cItem.image = snapshot.data; cItem.isImageLoaded = true; return Image.memory( diff --git a/lib/ui/chat/chat_detailed_screen.dart b/lib/ui/chat/chat_detailed_screen.dart index 643cc19..1d220bc 100644 --- a/lib/ui/chat/chat_detailed_screen.dart +++ b/lib/ui/chat/chat_detailed_screen.dart @@ -221,14 +221,11 @@ class _ChatDetailScreenState extends State { Widget showReplyImage(List data) { if (data.first.isImageLoaded! && data.first.image != null) { - return ClipRRect( - borderRadius: BorderRadius.circular(10.0), - child: Image.memory( - data.first.image!, - height: 43, - width: 43, - fit: BoxFit.cover, - ), + return Container( + width: 43, + height: 43, + decoration: BoxDecoration( + 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(); diff --git a/lib/ui/chat/chat_full_image_preview.dart b/lib/ui/chat/chat_full_image_preview.dart index 2eaa09d..26364c5 100644 --- a/lib/ui/chat/chat_full_image_preview.dart +++ b/lib/ui/chat/chat_full_image_preview.dart @@ -25,7 +25,8 @@ class ChatImagePreviewScreen extends StatelessWidget { Image.memory( img, fit: BoxFit.cover, - + height: 400, + width: double.infinity, ).paddingAll(10), const Positioned( right: 0, diff --git a/lib/ui/chat/chat_home_screen.dart b/lib/ui/chat/chat_home_screen.dart index 9072b33..cd2245d 100644 --- a/lib/ui/chat/chat_home_screen.dart +++ b/lib/ui/chat/chat_home_screen.dart @@ -1,3 +1,4 @@ +import 'dart:convert'; import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; @@ -210,6 +211,9 @@ class _ChatHomeScreenState extends State { ), ), onPressed: () async { + // String plainText = 'Muhamad.Alam@cloudsolutions.com.sa'; + // String key = "PeShVmYp"; + // passEncrypt(plainText, "PeShVmYp"); showMyBottomSheet( context, callBackFunc: () {}, @@ -237,4 +241,127 @@ class _ChatHomeScreenState extends State { ), ); } + // + // void passEncrypt(String text, String pass) async { + // var salt = randomUint8List(8); + // var keyndIV = deriveKeyAndIV(pass, salt); + // var key = encrypt.Key(keyndIV.item1); + // var iv = encrypt.IV(keyndIV.item2); + // var encrypter = encrypt.Encrypter(encrypt.AES(key, mode: encrypt.AESMode.cbc, padding: "PKCS7")); + // var encrypted = encrypter.encrypt(text, iv: iv); + // Uint8List encryptedBytesWithSalt = Uint8List.fromList(createUint8ListFromString("Salted__") + salt + encrypted.bytes); + // var resulttt = base64.encode(encryptedBytesWithSalt); + // print("Enc : " + resulttt); + // + // decryptAESCryptoJS(resulttt, pass); + // } + // + // Uint8List randomUint8List(int length) { + // assert(length > 0); + // var random = Random(); + // var ret = Uint8List(length); + // for (var i = 0; i < length; i++) { + // ret[i] = random.nextInt(256); + // } + // return ret; + // } + // + // void decryptAESCryptoJS(String encrypted, String passphrase) { + // try { + // Uint8List encryptedBytesWithSalt = base64.decode(encrypted); + // Uint8List encryptedBytes = encryptedBytesWithSalt.sublist(16, encryptedBytesWithSalt.length); + // var salt = encryptedBytesWithSalt.sublist(8, 16); + // var keyndIV = deriveKeyAndIV(passphrase, salt); + // var key = encrypt.Key(keyndIV.item1); + // var iv = encrypt.IV(keyndIV.item2); + // var encrypter = encrypt.Encrypter(encrypt.AES(key, mode: encrypt.AESMode.cbc, padding: "PKCS7")); + // var decrypted = encrypter.decrypt64(base64.encode(encryptedBytes), iv: iv); + // print("Dec : " + decrypted); + // // return decrypted; + // } catch (error) { + // throw error; + // } + // } + + void enc(String input) { + var ekey = "PeShVmYp"; + var eIV = "j70IbWYn"; + List eByt = utf8.encode(ekey); + List eIvByt = utf8.encode(eIV); + List iByt = utf8.encode(input); + + + + } + + // ///Accepts encrypted data and decrypt it. Returns plain text + // String decryptWithAES(String key, Encrypted encryptedData) { + // var cipherKey = encrypt.Key.fromUtf8(key); + // var encryptService = Encrypter(AES(cipherKey, mode: AESMode.cbc,padding: null)); + // var initVector = IV.fromUtf8(key.substring(0, 16)); + // return encryptService.decrypt(encryptedData, iv: initVector); + // } + // + // ///Encrypts the given plainText using the key. Returns encrypted data + // Encrypted encryptWithAES(String key, String plainText) { + // var cipherKey = encrypt.Key.fromUtf8(key); + // var encryptService = Encrypter(AES(cipherKey, mode: AESMode.cbc,padding: null)); + // var initVector = IV.fromUtf8("j70IbWYn"); + // Encrypted encryptedData = encryptService.encrypt(plainText, iv: initVector); + // print(encryptedData.base64); + // return encryptedData; + // } + // + // Tuple2 deriveKeyAndIV(String passphrase, Uint8List salt) { + // var password = createUint8ListFromString(passphrase); + // Uint8List concatenatedHashes = Uint8List(0); + // Uint8List currentHash = Uint8List(0); + // bool enoughBytesForKey = false; + // Uint8List preHash = Uint8List(0); + // + // while (!enoughBytesForKey) { + // int preHashLength = currentHash.length + password.length + salt.length; + // if (currentHash.length > 0) + // preHash = Uint8List.fromList(currentHash + password + salt); + // else + // preHash = Uint8List.fromList(password + salt); + // + // currentHash = preHash; + // concatenatedHashes = Uint8List.fromList(concatenatedHashes + currentHash); + // if (concatenatedHashes.length >= 48) enoughBytesForKey = true; + // } + // + // var keyBtyes = concatenatedHashes.sublist(0, 32); + // var ivBtyes = concatenatedHashes.sublist(32, 48); + // return new Tuple2(keyBtyes, ivBtyes); + // } + // + // Uint8List createUint8ListFromString(String s) { + // var ret = new Uint8List(s.length); + // for (var i = 0; i < s.length; i++) { + // ret[i] = s.codeUnitAt(i); + // } + // return ret; + // } + // + // Uint8List genRandomWithNonZero(int seedLength) { + // var random = Random.secure(); + // const int randomMax = 245; + // Uint8List uint8list = Uint8List(seedLength); + // for (int i = 0; i < seedLength; i++) { + // uint8list[i] = random.nextInt(randomMax) + 1; + // } + // return uint8list; + // } + // + // + // + // void test(String text, String kk) { + // Uint8List key = Uint8List.fromList(utf8.encode(kk)); + // PaddedBlockCipher cipher = exp.PaddedBlockCipherImpl(exp.PKCS7Padding(), exp.ECBBlockCipher(exp.AESEngine())); + // cipher.init(true, PaddedBlockCipherParameters(KeyParameter(key), null)); + // var byte = Uint8List.fromList(utf8.encode(text)); + // var data = cipher.process(byte); + // print(data); + // } } diff --git a/pubspec.yaml b/pubspec.yaml index 0f1a7b1..a2efb36 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -94,6 +94,9 @@ dependencies: camera: ^0.10.0+4 + #Encryption + cryptography: ^2.0.5 + cryptography_flutter: ^2.0.2 video_player: ^2.4.7 From c7dca3c3774f643a6fdcbe4c0cec77d0785d757e Mon Sep 17 00:00:00 2001 From: haroon amjad Date: Thu, 1 Dec 2022 15:35:04 +0300 Subject: [PATCH 08/35] Jira fixes for announcements & attachments --- lib/classes/date_uitl.dart | 2 +- lib/ui/misc/request_submit_screen.dart | 32 ++++++++++++------- .../screens/announcements/announcements.dart | 2 +- lib/ui/work_list/work_list_screen.dart | 2 +- 4 files changed, 23 insertions(+), 15 deletions(-) diff --git a/lib/classes/date_uitl.dart b/lib/classes/date_uitl.dart index f8d1c02..93a7e3f 100644 --- a/lib/classes/date_uitl.dart +++ b/lib/classes/date_uitl.dart @@ -20,7 +20,7 @@ class DateUtil { } static DateTime convertSimpleStringDateToDate(String date) { - return DateFormat("MM/dd/yyyy hh:mm:ss a").parse(date); + return DateFormat("MM/dd/yyyy hh:mm:ss aaa").parse(date); } static DateTime convertSimpleStringDateToDateddMMyyyy(String date) { diff --git a/lib/ui/misc/request_submit_screen.dart b/lib/ui/misc/request_submit_screen.dart index f5a2d1e..86263bd 100644 --- a/lib/ui/misc/request_submit_screen.dart +++ b/lib/ui/misc/request_submit_screen.dart @@ -22,6 +22,7 @@ import 'package:mohem_flutter_app/widgets/button/default_button.dart'; import 'package:mohem_flutter_app/widgets/button/simple_button.dart'; import 'package:mohem_flutter_app/widgets/circular_avatar.dart'; import 'package:mohem_flutter_app/widgets/dialogs/confirm_dialog.dart'; +import 'package:mohem_flutter_app/widgets/image_picker.dart'; import 'package:mohem_flutter_app/widgets/input_widget.dart'; class RequestSubmitScreenParams { @@ -48,6 +49,7 @@ class _RequestSubmitScreenState extends State { List approverList = []; List attachmentFiles = []; + List attachments = []; @override void initState() { @@ -72,16 +74,16 @@ class _RequestSubmitScreenState extends State { Utils.showLoading(context); List> list = []; if (attachmentFiles.isNotEmpty) { - attachmentFiles.asMap().forEach((index, value) async { - String type = value.path.split('.').last; - String name = value.path.split('/').last; - List fileContent = await value.readAsBytes(); - String encodedFile = base64Encode(fileContent); + attachments.asMap().forEach((index, value) async { + String type = attachmentFiles[index].path.split('.').last; + String name = attachmentFiles[index].path.split('/').last; + // List fileContent = await value.readAsBytes(); + // String encodedFile = base64Encode(fileContent); list.add(AttachmentModel( attachmentID: index, pFILECONTENTTYPE: type, pFILENAME: name, - pFILEDATA: encodedFile, + pFILEDATA: value, pTRANSACTIONID: params!.transactionId, ).toJson()); }); @@ -261,12 +263,18 @@ class _RequestSubmitScreenState extends State { title.toText16().expanded, 6.width, SimpleButton(LocaleKeys.add.tr(), () async { - FilePickerResult? result = await FilePicker.platform.pickFiles(allowMultiple: true); - if (result != null) { - attachmentFiles = attachmentFiles + result.paths.map((path) => File(path!)).toList(); - attachmentFiles = attachmentFiles.toSet().toList(); - setState(() {}); - } + ImageOptions.showImageOptionsNew(context, false, (String image, File file) { + setState(() { + attachmentFiles.add(file); + attachments.add(image); + Navigator.of(context).pop(); + }); + }); + // if (result != null) { + // attachmentFiles = attachmentFiles + result.paths.map((path) => File(path!)).toList(); + // attachmentFiles = attachmentFiles.toSet().toList(); + // setState(() {}); + // } }, fontSize: 14), ], ), diff --git a/lib/ui/screens/announcements/announcements.dart b/lib/ui/screens/announcements/announcements.dart index d43c12c..941ff65 100644 --- a/lib/ui/screens/announcements/announcements.dart +++ b/lib/ui/screens/announcements/announcements.dart @@ -95,7 +95,7 @@ class _AnnouncementsState extends State { Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - (AppState().isArabic(context) ? _foundAnnouncements[index].titleAR! : getAnnouncementsObject[index].titleEN!).toText13(), + (AppState().isArabic(context) ? _foundAnnouncements[index].titleAR! : _foundAnnouncements[index].titleEN!).toText13(), 8.height, _foundAnnouncements[index].created!.toText10(color: MyColors.grey98Color) ], diff --git a/lib/ui/work_list/work_list_screen.dart b/lib/ui/work_list/work_list_screen.dart index f9f8d91..da1b60f 100644 --- a/lib/ui/work_list/work_list_screen.dart +++ b/lib/ui/work_list/work_list_screen.dart @@ -528,7 +528,7 @@ class _WorkListScreenState extends State { 10.height, Row( children: [ - DateUtil.formatDateToDate(DateUtil.convertSimpleStringDateToDate(workData.bEGINDATE!), false).toText10(color: MyColors.lightTextColor).expanded, + DateUtil.formatDateToDate(DateUtil.convertSimpleStringDateToDateddMMyyyy(workData.bEGINDATE!), false).toText10(color: MyColors.lightTextColor).expanded, RotatedBox(quarterTurns: AppState().isArabic(context) ? 2 : 4, child: SvgPicture.asset("assets/images/arrow_next.svg", color: MyColors.darkIconColor)), ], ), From c9dd403b238d8d5274d0d4a78eac70602ce95394 Mon Sep 17 00:00:00 2001 From: haroon amjad Date: Thu, 1 Dec 2022 16:36:31 +0300 Subject: [PATCH 09/35] subordinate leave fix --- lib/ui/my_team/subordinate_leave.dart | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/ui/my_team/subordinate_leave.dart b/lib/ui/my_team/subordinate_leave.dart index f08193c..e2fb999 100644 --- a/lib/ui/my_team/subordinate_leave.dart +++ b/lib/ui/my_team/subordinate_leave.dart @@ -99,7 +99,7 @@ class _SubordinateLeaveState extends State { itemBuilder: (BuildContext context, int index) { var diffDays = DateUtil.convertStringToDate(getSubordinatesLeavesTotalList[index].dATEEND!) .difference(DateUtil.convertStringToDate(getSubordinatesLeavesTotalList[index].dATESTART!)) - .inDays; + .inDays + 1; return Row( crossAxisAlignment: CrossAxisAlignment.start, children: [ From f6f801f9cff59303cc5675677fa5a7710adc5e4a Mon Sep 17 00:00:00 2001 From: "Aamir.Muhammad" Date: Sun, 4 Dec 2022 16:15:47 +0300 Subject: [PATCH 10/35] Chat Fixes & User Chat Counter --- lib/classes/consts.dart | 4 +- lib/classes/encryption.dart | 188 ++++++++++++++++++ lib/provider/chat_provider_model.dart | 17 +- lib/provider/dashboard_provider_model.dart | 20 +- lib/ui/chat/chat_bubble.dart | 32 ++- lib/ui/chat/chat_full_image_preview.dart | 57 +++--- lib/ui/chat/chat_home_screen.dart | 142 +------------ lib/ui/landing/dashboard_screen.dart | 11 + .../itg/its_add_screen_video_image.dart | 37 ++-- pubspec.yaml | 5 - 10 files changed, 304 insertions(+), 209 deletions(-) create mode 100644 lib/classes/encryption.dart diff --git a/lib/classes/consts.dart b/lib/classes/consts.dart index 13c4258..841f29c 100644 --- a/lib/classes/consts.dart +++ b/lib/classes/consts.dart @@ -3,7 +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://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/"; @@ -12,8 +12,6 @@ class ApiConsts { static String user = baseUrlServices + "api/User/"; static String cocRest = baseUrlServices + "COCWS.svc/REST/"; - // todo @aamir move api end point last repo to concerned method. - //Chat static String chatServerBaseUrl = "https://apiderichat.hmg.com/"; static String chatServerBaseApiUrl = chatServerBaseUrl + "api/"; diff --git a/lib/classes/encryption.dart b/lib/classes/encryption.dart new file mode 100644 index 0000000..67466fe --- /dev/null +++ b/lib/classes/encryption.dart @@ -0,0 +1,188 @@ +// import 'dart:convert'; +// +// import 'package:encrypt/encrypt.dart'; +// import 'package:crypto/crypto.dart'; +// +// class Encryption { +// static final Encryption instance = Encryption._(); +// +// late IV _iv; +// late Encrypter _encrypter; +// +// Encryption._() { +// const mykey = 'PeShVmYp'; +// const myiv = 'j70IbWYn'; +// var keyUtf8 = utf8.encode(mykey); +// var ivUtf8 = utf8.encode(myiv); +// var key = sha256.convert(keyUtf8).toString().substring(0, 32); +// var iv = sha256.convert(ivUtf8).toString().substring(0, 16); +// _iv = IV.fromUtf8(iv); +// +// _encrypter = Encrypter(AES(Key.fromUtf8(key), mode: AESMode.cbc)); +// } +// +// String encrypt(String value) { +// return _encrypter.encrypt(value, iv: _iv).base64; +// } +// +// String decrypt(String base64value) { +// var encrypted = Encrypted.fromBase64(base64value); +// return _encrypter.decrypt(encrypted, iv: _iv); +// } +// +// // +// // void passEncrypt(String text, String pass) async { +// // var salt = randomUint8List(8); +// // var keyndIV = deriveKeyAndIV(pass, salt); +// // var key = encrypt.Key(keyndIV.item1); +// // var iv = encrypt.IV(keyndIV.item2); +// // var encrypter = encrypt.Encrypter(encrypt.AES(key, mode: encrypt.AESMode.cbc, padding: "PKCS7")); +// // var encrypted = encrypter.encrypt(text, iv: iv); +// // Uint8List encryptedBytesWithSalt = Uint8List.fromList(createUint8ListFromString("Salted__") + salt + encrypted.bytes); +// // var resulttt = base64.encode(encryptedBytesWithSalt); +// // print("Enc : " + resulttt); +// // +// // decryptAESCryptoJS(resulttt, pass); +// // } +// // +// // Uint8List randomUint8List(int length) { +// // assert(length > 0); +// // var random = Random(); +// // var ret = Uint8List(length); +// // for (var i = 0; i < length; i++) { +// // ret[i] = random.nextInt(256); +// // } +// // return ret; +// // } +// // +// // void decryptAESCryptoJS(String encrypted, String passphrase) { +// // try { +// // Uint8List encryptedBytesWithSalt = base64.decode(encrypted); +// // Uint8List encryptedBytes = encryptedBytesWithSalt.sublist(16, encryptedBytesWithSalt.length); +// // var salt = encryptedBytesWithSalt.sublist(8, 16); +// // var keyndIV = deriveKeyAndIV(passphrase, salt); +// // var key = encrypt.Key(keyndIV.item1); +// // var iv = encrypt.IV(keyndIV.item2); +// // var encrypter = encrypt.Encrypter(encrypt.AES(key, mode: encrypt.AESMode.cbc, padding: "PKCS7")); +// // var decrypted = encrypter.decrypt64(base64.encode(encryptedBytes), iv: iv); +// // print("Dec : " + decrypted); +// // // return decrypted; +// // } catch (error) { +// // throw error; +// // } +// // } +// // +// // Future enc(String input) async { +// // var ekey = "PeShVmYpPeShVmYp"; +// // var eIV = "j70IbWYnj70IbWYn"; +// // +// // var abc = Encryption.instance.encrypt(input); +// // // +// // // var inputByt = utf8.encode(input); +// // // final encrypted = encrypter.encrypt(plainText); +// // // final decrypted = encrypter.decrypt(encrypted); +// // // +// // // print(decrypted); // Lorem ipsum dolor sit amet, consectetur adipiscing elit +// // // print(encrypted.base64); // R4PxiU3h8YoIRqVowBXm36ZcCeNeZ4s1OvVBTfFlZRdmohQqOpPQqD1YecJeZMAop/hZ4OxqgC1WtwvX/hP9mw== +// // // /// +// // +// // var key = encrypt.Key.fromUtf8(ekey.substring(0, 8)); +// // var iv = encrypt.IV.fromLength(8); +// // var encrypter = Encrypter(AES(key)); +// // var encrypted = encrypter.encrypt(input, iv: iv); +// // var decrypted = encrypter.decrypt(encrypted, iv: iv); +// // print("====== ORI =========="); +// // print("e4PTDencHsiLJv0XcbT2I4tafb7dqJP9c72PEnhp1Uv6U2GZ/gODtA=="); +// // print("====== ENC =========="); +// // print(encrypted.base64); +// // print("====== DEC =========="); +// // print(decrypted); +// // print("====== B64 =========="); +// // String bs64 = base64.encode(utf8.encode(input)); +// // print(bs64); +// // +// // // try { +// // // var cipher = _cipher; +// // // var secretBox = await cipher.encrypt( +// // // iByt, +// // // secretKey: SecretKeyData(eByt), +// // // nonce: eIvByt, +// // // ); +// // // print(utf8.decode(secretBox.cipherText)); +// // // } catch (error) { +// // // print(error); +// // // return; +// // // } +// // } +// // ///Accepts encrypted data and decrypt it. Returns plain text +// // String decryptWithAES(String key, Encrypted encryptedData) { +// // var cipherKey = encrypt.Key.fromUtf8(key); +// // var encryptService = Encrypter(AES(cipherKey, mode: AESMode.cbc,padding: null)); +// // var initVector = IV.fromUtf8(key.substring(0, 16)); +// // return encryptService.decrypt(encryptedData, iv: initVector); +// // } +// // +// // ///Encrypts the given plainText using the key. Returns encrypted data +// // Encrypted encryptWithAES(String key, String plainText) { +// // var cipherKey = encrypt.Key.fromUtf8(key); +// // var encryptService = Encrypter(AES(cipherKey, mode: AESMode.cbc,padding: null)); +// // var initVector = IV.fromUtf8("j70IbWYn"); +// // Encrypted encryptedData = encryptService.encrypt(plainText, iv: initVector); +// // print(encryptedData.base64); +// // return encryptedData; +// // } +// // +// // Tuple2 deriveKeyAndIV(String passphrase, Uint8List salt) { +// // var password = createUint8ListFromString(passphrase); +// // Uint8List concatenatedHashes = Uint8List(0); +// // Uint8List currentHash = Uint8List(0); +// // bool enoughBytesForKey = false; +// // Uint8List preHash = Uint8List(0); +// // +// // while (!enoughBytesForKey) { +// // int preHashLength = currentHash.length + password.length + salt.length; +// // if (currentHash.length > 0) +// // preHash = Uint8List.fromList(currentHash + password + salt); +// // else +// // preHash = Uint8List.fromList(password + salt); +// // +// // currentHash = preHash; +// // concatenatedHashes = Uint8List.fromList(concatenatedHashes + currentHash); +// // if (concatenatedHashes.length >= 48) enoughBytesForKey = true; +// // } +// // +// // var keyBtyes = concatenatedHashes.sublist(0, 32); +// // var ivBtyes = concatenatedHashes.sublist(32, 48); +// // return new Tuple2(keyBtyes, ivBtyes); +// // } +// // +// // Uint8List createUint8ListFromString(String s) { +// // var ret = new Uint8List(s.length); +// // for (var i = 0; i < s.length; i++) { +// // ret[i] = s.codeUnitAt(i); +// // } +// // return ret; +// // } +// // +// // Uint8List genRandomWithNonZero(int seedLength) { +// // var random = Random.secure(); +// // const int randomMax = 245; +// // Uint8List uint8list = Uint8List(seedLength); +// // for (int i = 0; i < seedLength; i++) { +// // uint8list[i] = random.nextInt(randomMax) + 1; +// // } +// // return uint8list; +// // } +// // +// // +// // +// // void test(String text, String kk) { +// // Uint8List key = Uint8List.fromList(utf8.encode(kk)); +// // PaddedBlockCipher cipher = exp.PaddedBlockCipherImpl(exp.PKCS7Padding(), exp.ECBBlockCipher(exp.AESEngine())); +// // cipher.init(true, PaddedBlockCipherParameters(KeyParameter(key), null)); +// // var byte = Uint8List.fromList(utf8.encode(text)); +// // var data = cipher.process(byte); +// // print(data); +// // } +// +// } diff --git a/lib/provider/chat_provider_model.dart b/lib/provider/chat_provider_model.dart index f3821f3..886951c 100644 --- a/lib/provider/chat_provider_model.dart +++ b/lib/provider/chat_provider_model.dart @@ -120,7 +120,7 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { if (element.isSeen != null) { if (!element.isSeen!) { print("Found Un Read"); - logger.d(jsonEncode(element)); + element.isSeen = true; dynamic data = [ {"userChatHistoryId": element.userChatHistoryId, "TargetUserId": element.targetUserId, "isDelivered": true, "isSeen": true} ]; @@ -131,9 +131,10 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { for (ChatUser element in searchedChats!) { if (element.id == receiverID) { element.unreadMessageCount = 0; - notifyListeners(); + // notifyListeners(); } } + notifyListeners(); } } @@ -223,7 +224,6 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { void chatNotDelivered(List? args) { dynamic items = args!.toList(); - logger.d(items); for (dynamic item in items[0]) { searchedChats!.forEach( (ChatUser element) { @@ -288,8 +288,16 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { } userChatHistory.insert(0, data.first); + if (searchedChats != null) { + for (ChatUser user in searchedChats!) { + if (user.id == data.first.currentUserId) { + var tempCount = user.unreadMessageCount ?? 0; + user.unreadMessageCount = tempCount + 1; + } + } + } - var list = [ + List list = [ {"userChatHistoryId": data.first.userChatHistoryId, "TargetUserId": temp.first.targetUserId, "isDelivered": true, "isSeen": isChatScreenActive ? true : false} ]; updateUserChatHistoryOnMsg(list); @@ -624,7 +632,6 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { } void clearSelections() { - print("Hereee i am "); searchedChats = pChatHistory; search.clear(); isChatScreenActive = false; diff --git a/lib/provider/dashboard_provider_model.dart b/lib/provider/dashboard_provider_model.dart index 59b62b6..461196f 100644 --- a/lib/provider/dashboard_provider_model.dart +++ b/lib/provider/dashboard_provider_model.dart @@ -307,13 +307,21 @@ class DashboardProviderModel with ChangeNotifier, DiagnosticableTreeMixin { Future getHubConnection() async { HubConnection hub; - 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; + 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 notify() { notifyListeners(); } diff --git a/lib/ui/chat/chat_bubble.dart b/lib/ui/chat/chat_bubble.dart index 8995da1..ec772f6 100644 --- a/lib/ui/chat/chat_bubble.dart +++ b/lib/ui/chat/chat_bubble.dart @@ -28,6 +28,7 @@ class ChatBubble extends StatelessWidget { String? fileTypeDescription; bool isDelivered = false; String userName = ''; + late Offset screenOffset; void makeAssign() { isCurrentUser = cItem.currentUserId == AppState().chatDetails!.response!.id ? true : false; @@ -41,6 +42,8 @@ class ChatBubble extends StatelessWidget { @override Widget build(BuildContext context) { + Size windowSize = MediaQuery.of(context).size; + screenOffset = Offset(windowSize.width / 2, windowSize.height / 2); makeAssign(); return isCurrentUser ? currentUser(context) : receiptUser(context); } @@ -108,7 +111,11 @@ class ChatBubble extends StatelessWidget { ).paddingOnly(right: 5, 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, builder: (BuildContext context) => ChatImagePreviewScreen(imgTitle: cItem.contant!, img: cItem.image!)); + showDialog( + context: context, + anchorPoint: screenOffset, + builder: (BuildContext context) => ChatImagePreviewScreen(imgTitle: cItem.contant!, img: cItem.image!), + ); }), cItem.contant!.toText12(), Align( @@ -172,23 +179,28 @@ class ChatBubble extends StatelessWidget { ClipRRect( borderRadius: BorderRadius.circular(8.0), child: SizedBox( - height: 32, - width: 32, - child: showImage( - isReplyPreview: true, - fileName: cItem.userChatReplyResponse!.contant!, - fileTypeDescription: cItem.userChatReplyResponse!.fileTypeResponse!.fileTypeDescription ?? "image/jpg")), + height: 32, + width: 32, + child: showImage( + isReplyPreview: true, + fileName: cItem.userChatReplyResponse!.contant!, + fileTypeDescription: cItem.userChatReplyResponse!.fileTypeResponse!.fileTypeDescription ?? "image/jpg"), + ), ).paddingOnly(left: 10, right: 10, bottom: 16, top: 16) ], ), ), ).paddingOnly(right: 5, 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, builder: (BuildContext context) => ChatImagePreviewScreen(imgTitle: cItem.contant!, img: cItem.image!)); + 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!), + ); }) else - (cItem.contant! ?? "").toText12(color: Colors.white), + (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_full_image_preview.dart b/lib/ui/chat/chat_full_image_preview.dart index 26364c5..c731c25 100644 --- a/lib/ui/chat/chat_full_image_preview.dart +++ b/lib/ui/chat/chat_full_image_preview.dart @@ -12,29 +12,40 @@ class ChatImagePreviewScreen extends StatelessWidget { @override Widget build(BuildContext context) { - return GestureDetector( - onTap: () { - Navigator.of(context).pop(); - }, - child: Dialog( - backgroundColor: Colors.transparent, - insetPadding: const EdgeInsets.all(10), - child: Stack( - alignment: Alignment.center, - children: [ - Image.memory( - img, - fit: BoxFit.cover, - height: 400, - width: double.infinity, - ).paddingAll(10), - const Positioned( - right: 0, - top: 0, - child: Icon(Icons.cancel, color: MyColors.redA3Color, size: 35), - ) - ], - ), + return Dialog( + backgroundColor: Colors.transparent, + insetPadding: const EdgeInsets.all(10), + child: Stack( + alignment: Alignment.center, + fit: StackFit.loose, + children: [ + Image.memory( + img, + fit: BoxFit.cover, + height: 400, + width: double.infinity, + ).paddingAll(15), + Positioned( + right: 0, + top: 0, + child: Container( + width: 30, + height: 30, + alignment: Alignment.center, + padding: EdgeInsets.zero, + margin: EdgeInsets.zero, + constraints: const BoxConstraints(), + color: MyColors.white, + child: const Icon( + Icons.cancel, + color: MyColors.redA3Color, + size: 30, + ), + ).onPress(() { + Navigator.of(context).pop(); + }).circle(35), + ) + ], ), ); } diff --git a/lib/ui/chat/chat_home_screen.dart b/lib/ui/chat/chat_home_screen.dart index cd2245d..e2f2dc2 100644 --- a/lib/ui/chat/chat_home_screen.dart +++ b/lib/ui/chat/chat_home_screen.dart @@ -63,7 +63,7 @@ class _ChatHomeScreenState extends State { hintText: LocaleKeys.searchfromchat.tr(), hintStyle: const TextStyle(color: MyColors.lightTextColor, fontStyle: FontStyle.italic, fontWeight: FontWeight.w500, fontSize: 12), filled: true, - fillColor: const Color(0xFFF7F7F7), + fillColor: MyColors.greyF7Color, suffixIconConstraints: const BoxConstraints(), suffixIcon: m.search.text.isNotEmpty ? IconButton( @@ -83,7 +83,6 @@ class _ChatHomeScreenState extends State { shrinkWrap: true, physics: const ClampingScrollPhysics(), itemBuilder: (BuildContext context, int index) { - // todo @aamir, remove list tile, make a custom ui instead return SizedBox( height: 55, child: Row( @@ -103,11 +102,8 @@ class _ChatHomeScreenState extends State { height: 10, decoration: BoxDecoration( color: m.searchedChats![index].userStatus == 1 ? MyColors.green2DColor : Colors.red, - borderRadius: const BorderRadius.all( - Radius.circular(10), - ), ), - ), + ).circle(10), ) ], ), @@ -211,9 +207,6 @@ class _ChatHomeScreenState extends State { ), ), onPressed: () async { - // String plainText = 'Muhamad.Alam@cloudsolutions.com.sa'; - // String key = "PeShVmYp"; - // passEncrypt(plainText, "PeShVmYp"); showMyBottomSheet( context, callBackFunc: () {}, @@ -231,137 +224,10 @@ class _ChatHomeScreenState extends State { OutlineInputBorder fieldBorder({required double radius, required int color}) { return OutlineInputBorder( - borderRadius: BorderRadius.circular( - radius, - ), + borderRadius: BorderRadius.circular(radius), borderSide: BorderSide( - color: Color( - color, - ), + color: Color(color), ), ); } - // - // void passEncrypt(String text, String pass) async { - // var salt = randomUint8List(8); - // var keyndIV = deriveKeyAndIV(pass, salt); - // var key = encrypt.Key(keyndIV.item1); - // var iv = encrypt.IV(keyndIV.item2); - // var encrypter = encrypt.Encrypter(encrypt.AES(key, mode: encrypt.AESMode.cbc, padding: "PKCS7")); - // var encrypted = encrypter.encrypt(text, iv: iv); - // Uint8List encryptedBytesWithSalt = Uint8List.fromList(createUint8ListFromString("Salted__") + salt + encrypted.bytes); - // var resulttt = base64.encode(encryptedBytesWithSalt); - // print("Enc : " + resulttt); - // - // decryptAESCryptoJS(resulttt, pass); - // } - // - // Uint8List randomUint8List(int length) { - // assert(length > 0); - // var random = Random(); - // var ret = Uint8List(length); - // for (var i = 0; i < length; i++) { - // ret[i] = random.nextInt(256); - // } - // return ret; - // } - // - // void decryptAESCryptoJS(String encrypted, String passphrase) { - // try { - // Uint8List encryptedBytesWithSalt = base64.decode(encrypted); - // Uint8List encryptedBytes = encryptedBytesWithSalt.sublist(16, encryptedBytesWithSalt.length); - // var salt = encryptedBytesWithSalt.sublist(8, 16); - // var keyndIV = deriveKeyAndIV(passphrase, salt); - // var key = encrypt.Key(keyndIV.item1); - // var iv = encrypt.IV(keyndIV.item2); - // var encrypter = encrypt.Encrypter(encrypt.AES(key, mode: encrypt.AESMode.cbc, padding: "PKCS7")); - // var decrypted = encrypter.decrypt64(base64.encode(encryptedBytes), iv: iv); - // print("Dec : " + decrypted); - // // return decrypted; - // } catch (error) { - // throw error; - // } - // } - - void enc(String input) { - var ekey = "PeShVmYp"; - var eIV = "j70IbWYn"; - List eByt = utf8.encode(ekey); - List eIvByt = utf8.encode(eIV); - List iByt = utf8.encode(input); - - - - } - - // ///Accepts encrypted data and decrypt it. Returns plain text - // String decryptWithAES(String key, Encrypted encryptedData) { - // var cipherKey = encrypt.Key.fromUtf8(key); - // var encryptService = Encrypter(AES(cipherKey, mode: AESMode.cbc,padding: null)); - // var initVector = IV.fromUtf8(key.substring(0, 16)); - // return encryptService.decrypt(encryptedData, iv: initVector); - // } - // - // ///Encrypts the given plainText using the key. Returns encrypted data - // Encrypted encryptWithAES(String key, String plainText) { - // var cipherKey = encrypt.Key.fromUtf8(key); - // var encryptService = Encrypter(AES(cipherKey, mode: AESMode.cbc,padding: null)); - // var initVector = IV.fromUtf8("j70IbWYn"); - // Encrypted encryptedData = encryptService.encrypt(plainText, iv: initVector); - // print(encryptedData.base64); - // return encryptedData; - // } - // - // Tuple2 deriveKeyAndIV(String passphrase, Uint8List salt) { - // var password = createUint8ListFromString(passphrase); - // Uint8List concatenatedHashes = Uint8List(0); - // Uint8List currentHash = Uint8List(0); - // bool enoughBytesForKey = false; - // Uint8List preHash = Uint8List(0); - // - // while (!enoughBytesForKey) { - // int preHashLength = currentHash.length + password.length + salt.length; - // if (currentHash.length > 0) - // preHash = Uint8List.fromList(currentHash + password + salt); - // else - // preHash = Uint8List.fromList(password + salt); - // - // currentHash = preHash; - // concatenatedHashes = Uint8List.fromList(concatenatedHashes + currentHash); - // if (concatenatedHashes.length >= 48) enoughBytesForKey = true; - // } - // - // var keyBtyes = concatenatedHashes.sublist(0, 32); - // var ivBtyes = concatenatedHashes.sublist(32, 48); - // return new Tuple2(keyBtyes, ivBtyes); - // } - // - // Uint8List createUint8ListFromString(String s) { - // var ret = new Uint8List(s.length); - // for (var i = 0; i < s.length; i++) { - // ret[i] = s.codeUnitAt(i); - // } - // return ret; - // } - // - // Uint8List genRandomWithNonZero(int seedLength) { - // var random = Random.secure(); - // const int randomMax = 245; - // Uint8List uint8list = Uint8List(seedLength); - // for (int i = 0; i < seedLength; i++) { - // uint8list[i] = random.nextInt(randomMax) + 1; - // } - // return uint8list; - // } - // - // - // - // void test(String text, String kk) { - // Uint8List key = Uint8List.fromList(utf8.encode(kk)); - // PaddedBlockCipher cipher = exp.PaddedBlockCipherImpl(exp.PKCS7Padding(), exp.ECBBlockCipher(exp.AESEngine())); - // cipher.init(true, PaddedBlockCipherParameters(KeyParameter(key), null)); - // var byte = Uint8List.fromList(utf8.encode(text)); - // var data = cipher.process(byte); - // print(data); - // } } diff --git a/lib/ui/landing/dashboard_screen.dart b/lib/ui/landing/dashboard_screen.dart index 7cf28cf..b449bd1 100644 --- a/lib/ui/landing/dashboard_screen.dart +++ b/lib/ui/landing/dashboard_screen.dart @@ -6,6 +6,7 @@ import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:flutter_countdown_timer/flutter_countdown_timer.dart'; import 'package:flutter_svg/flutter_svg.dart'; +import 'package:mohem_flutter_app/api/dashboard_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'; @@ -63,6 +64,14 @@ class _DashboardScreenState extends State { void buildHubConnection() async { hubConnection = await data.getHubConnection(); await hubConnection.start(); + hubConnection.onreconnecting(({Exception? error}) { + print("============== Reconnecting ======================"); + if (hubConnection.state != HubConnectionState.Connected) { + data.getUserAutoLoginToken().whenComplete(() { + buildHubConnection(); + }); + } + }); } @override @@ -106,9 +115,11 @@ class _DashboardScreenState extends State { // onPressed: () { // data.getITGNotification().then((val) { // if (val!.result!.data != null) { + // print("-------------------- Survey ----------------------------"); // if (val.result!.data!.notificationType == "Survey") { // Navigator.pushNamed(context, AppRoutes.survey, arguments: val.result!.data); // } else { + // print("------------------------------------------- Ads --------------------"); // DashboardApiClient().getAdvertisementDetail(val.result!.data!.notificationMasterId ?? "").then( // (value) { // if (value!.mohemmItgResponseItem!.statusCode == 200) { diff --git a/lib/ui/landing/itg/its_add_screen_video_image.dart b/lib/ui/landing/itg/its_add_screen_video_image.dart index a71a71b..bcb9ed4 100644 --- a/lib/ui/landing/itg/its_add_screen_video_image.dart +++ b/lib/ui/landing/itg/its_add_screen_video_image.dart @@ -69,7 +69,7 @@ class _ITGAdsScreenState extends State { await controller.setLooping(false); return controller; } catch (e) { - return new VideoPlayerController.asset("dataSource"); + return VideoPlayerController.asset("dataSource"); } } @@ -94,29 +94,28 @@ class _ITGAdsScreenState extends State { if (advertisementData != null) { checkFileType(); } - double height = MediaQuery.of(context).size.height * .25; + // double height = MediaQuery.of(context).size.height * .25; return Scaffold( - body: Column( + body: Stack( children: [ if (isVideo) - SizedBox( - height: MediaQuery.of(context).size.height * .3, - child: FutureBuilder( - future: _futureController, - builder: (BuildContext context, AsyncSnapshot snapshot) { - if (snapshot.connectionState == ConnectionState.done && snapshot.data != null) { - _controller = snapshot.data as VideoPlayerController; - return AspectRatio( + FutureBuilder( + future: _futureController, + builder: (BuildContext context, AsyncSnapshot snapshot) { + if (snapshot.connectionState == ConnectionState.done && snapshot.data != null) { + _controller = snapshot.data as VideoPlayerController; + return Positioned.fill( + child: AspectRatio( aspectRatio: _controller.value.aspectRatio, child: VideoPlayer(_controller), - ); - } else { - return const Center( - child: CircularProgressIndicator(), - ); - } - }, - ), + ), + ); + } else { + return const Center( + child: CircularProgressIndicator(), + ); + } + }, ), if (isImage) Image.file(imageFile), if (skip) diff --git a/pubspec.yaml b/pubspec.yaml index a2efb36..f17ce5f 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -94,11 +94,6 @@ dependencies: camera: ^0.10.0+4 - #Encryption - cryptography: ^2.0.5 - cryptography_flutter: ^2.0.2 - - video_player: ^2.4.7 just_audio: ^0.9.30 From a08f1c6d77a92be0e0ed198e0c78a807c783b523 Mon Sep 17 00:00:00 2001 From: "Aamir.Muhammad" Date: Sun, 4 Dec 2022 16:53:11 +0300 Subject: [PATCH 11/35] Chat Fixes & User Chat Counter --- lib/provider/chat_provider_model.dart | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/lib/provider/chat_provider_model.dart b/lib/provider/chat_provider_model.dart index 886951c..b48d845 100644 --- a/lib/provider/chat_provider_model.dart +++ b/lib/provider/chat_provider_model.dart @@ -36,7 +36,7 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { void registerEvents() { hubConnection.on("OnUpdateUserStatusAsync", changeStatus); hubConnection.on("OnDeliveredChatUserAsync", onMsgReceived); - // hubConnection.on("OnSeenChatUserAsync", onChatSeen); + hubConnection.on("OnSeenChatUserAsync", onChatSeen); //hubConnection.on("OnUserTypingAsync", onUserTyping); hubConnection.on("OnUserCountAsync", userCountAsync); hubConnection.on("OnUpdateUserChatHistoryWindowsAsync", updateChatHistoryWindow); @@ -119,12 +119,12 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { for (SingleUserChatModel element in data!) { if (element.isSeen != null) { if (!element.isSeen!) { - print("Found Un Read"); element.isSeen = true; dynamic data = [ - {"userChatHistoryId": element.userChatHistoryId, "TargetUserId": element.targetUserId, "isDelivered": true, "isSeen": true} + {"userChatHistoryId": element.userChatHistoryId, "TargetUserId": element.currentUserId, "isDelivered": true, "isSeen": true} ]; updateUserChatHistoryStatusAsync(data); + notifyListeners(); } } } @@ -288,7 +288,8 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { } userChatHistory.insert(0, data.first); - if (searchedChats != null) { + + if (searchedChats != null && !isChatScreenActive) { for (ChatUser user in searchedChats!) { if (user.id == data.first.currentUserId) { var tempCount = user.unreadMessageCount ?? 0; From 3e666eb6be1efb8ccd14c6bc29945d89dcd34ed3 Mon Sep 17 00:00:00 2001 From: "Aamir.Muhammad" Date: Mon, 5 Dec 2022 11:30:10 +0300 Subject: [PATCH 12/35] Chat Fixes & User Chat Counter --- lib/api/chat/chat_api_client.dart | 11 +- lib/classes/encryption.dart | 216 +++--------------- lib/models/chat/chat_user_image_model.dart | 33 +++ .../chat/get_search_user_chat_model.dart | 38 +-- lib/provider/chat_provider_model.dart | 35 ++- lib/ui/chat/chat_detailed_screen.dart | 3 +- lib/ui/chat/chat_home.dart | 2 + lib/ui/chat/chat_home_screen.dart | 33 ++- lib/ui/chat/favorite_users_screen.dart | 31 ++- lib/widgets/app_bar_widget.dart | 13 +- pubspec.yaml | 2 + 11 files changed, 183 insertions(+), 234 deletions(-) create mode 100644 lib/models/chat/chat_user_image_model.dart diff --git a/lib/api/chat/chat_api_client.dart b/lib/api/chat/chat_api_client.dart index 1f97b1f..bea5b7c 100644 --- a/lib/api/chat/chat_api_client.dart +++ b/lib/api/chat/chat_api_client.dart @@ -9,6 +9,7 @@ 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'; import 'package:mohem_flutter_app/models/chat/get_search_user_chat_model.dart'; import 'package:mohem_flutter_app/models/chat/get_user_login_token_model.dart' as user; import 'package:mohem_flutter_app/models/chat/make_user_favotire_unfavorite_chat_model.dart' as fav; @@ -152,16 +153,12 @@ class ChatApiClient { return data; } - Future getUsersImages({required List encryptedEmails}) async { + Future> getUsersImages({required List encryptedEmails}) async { Response response = await ApiClient().postJsonForResponse( "${ApiConsts.chatUserImages}images", - { - "encryptedEmails": ["/g8Rc+s6eEOdci41PwJuV5dX+gXe51G9OTHzb9ahcVlHCmVvNhxReirudF79+hdxVSkCnQ6wC5DBFV8xnJlC74X6157PxF7mNYrAYuHRgp4="], - "fromClient": true - }, + {"encryptedEmails": encryptedEmails, "fromClient": false}, token: AppState().chatDetails!.response!.token, ); - logger.d(response.body); - // Uint8List data = Uint8List.fromList(response.body); + return chatUserImageModelFromJson(response.body); } } diff --git a/lib/classes/encryption.dart b/lib/classes/encryption.dart index 67466fe..f26c92b 100644 --- a/lib/classes/encryption.dart +++ b/lib/classes/encryption.dart @@ -1,188 +1,28 @@ -// import 'dart:convert'; -// -// import 'package:encrypt/encrypt.dart'; -// import 'package:crypto/crypto.dart'; -// -// class Encryption { -// static final Encryption instance = Encryption._(); -// -// late IV _iv; -// late Encrypter _encrypter; -// -// Encryption._() { -// const mykey = 'PeShVmYp'; -// const myiv = 'j70IbWYn'; -// var keyUtf8 = utf8.encode(mykey); -// var ivUtf8 = utf8.encode(myiv); -// var key = sha256.convert(keyUtf8).toString().substring(0, 32); -// var iv = sha256.convert(ivUtf8).toString().substring(0, 16); -// _iv = IV.fromUtf8(iv); -// -// _encrypter = Encrypter(AES(Key.fromUtf8(key), mode: AESMode.cbc)); -// } -// -// String encrypt(String value) { -// return _encrypter.encrypt(value, iv: _iv).base64; -// } -// -// String decrypt(String base64value) { -// var encrypted = Encrypted.fromBase64(base64value); -// return _encrypter.decrypt(encrypted, iv: _iv); -// } -// -// // -// // void passEncrypt(String text, String pass) async { -// // var salt = randomUint8List(8); -// // var keyndIV = deriveKeyAndIV(pass, salt); -// // var key = encrypt.Key(keyndIV.item1); -// // var iv = encrypt.IV(keyndIV.item2); -// // var encrypter = encrypt.Encrypter(encrypt.AES(key, mode: encrypt.AESMode.cbc, padding: "PKCS7")); -// // var encrypted = encrypter.encrypt(text, iv: iv); -// // Uint8List encryptedBytesWithSalt = Uint8List.fromList(createUint8ListFromString("Salted__") + salt + encrypted.bytes); -// // var resulttt = base64.encode(encryptedBytesWithSalt); -// // print("Enc : " + resulttt); -// // -// // decryptAESCryptoJS(resulttt, pass); -// // } -// // -// // Uint8List randomUint8List(int length) { -// // assert(length > 0); -// // var random = Random(); -// // var ret = Uint8List(length); -// // for (var i = 0; i < length; i++) { -// // ret[i] = random.nextInt(256); -// // } -// // return ret; -// // } -// // -// // void decryptAESCryptoJS(String encrypted, String passphrase) { -// // try { -// // Uint8List encryptedBytesWithSalt = base64.decode(encrypted); -// // Uint8List encryptedBytes = encryptedBytesWithSalt.sublist(16, encryptedBytesWithSalt.length); -// // var salt = encryptedBytesWithSalt.sublist(8, 16); -// // var keyndIV = deriveKeyAndIV(passphrase, salt); -// // var key = encrypt.Key(keyndIV.item1); -// // var iv = encrypt.IV(keyndIV.item2); -// // var encrypter = encrypt.Encrypter(encrypt.AES(key, mode: encrypt.AESMode.cbc, padding: "PKCS7")); -// // var decrypted = encrypter.decrypt64(base64.encode(encryptedBytes), iv: iv); -// // print("Dec : " + decrypted); -// // // return decrypted; -// // } catch (error) { -// // throw error; -// // } -// // } -// // -// // Future enc(String input) async { -// // var ekey = "PeShVmYpPeShVmYp"; -// // var eIV = "j70IbWYnj70IbWYn"; -// // -// // var abc = Encryption.instance.encrypt(input); -// // // -// // // var inputByt = utf8.encode(input); -// // // final encrypted = encrypter.encrypt(plainText); -// // // final decrypted = encrypter.decrypt(encrypted); -// // // -// // // print(decrypted); // Lorem ipsum dolor sit amet, consectetur adipiscing elit -// // // print(encrypted.base64); // R4PxiU3h8YoIRqVowBXm36ZcCeNeZ4s1OvVBTfFlZRdmohQqOpPQqD1YecJeZMAop/hZ4OxqgC1WtwvX/hP9mw== -// // // /// -// // -// // var key = encrypt.Key.fromUtf8(ekey.substring(0, 8)); -// // var iv = encrypt.IV.fromLength(8); -// // var encrypter = Encrypter(AES(key)); -// // var encrypted = encrypter.encrypt(input, iv: iv); -// // var decrypted = encrypter.decrypt(encrypted, iv: iv); -// // print("====== ORI =========="); -// // print("e4PTDencHsiLJv0XcbT2I4tafb7dqJP9c72PEnhp1Uv6U2GZ/gODtA=="); -// // print("====== ENC =========="); -// // print(encrypted.base64); -// // print("====== DEC =========="); -// // print(decrypted); -// // print("====== B64 =========="); -// // String bs64 = base64.encode(utf8.encode(input)); -// // print(bs64); -// // -// // // try { -// // // var cipher = _cipher; -// // // var secretBox = await cipher.encrypt( -// // // iByt, -// // // secretKey: SecretKeyData(eByt), -// // // nonce: eIvByt, -// // // ); -// // // print(utf8.decode(secretBox.cipherText)); -// // // } catch (error) { -// // // print(error); -// // // return; -// // // } -// // } -// // ///Accepts encrypted data and decrypt it. Returns plain text -// // String decryptWithAES(String key, Encrypted encryptedData) { -// // var cipherKey = encrypt.Key.fromUtf8(key); -// // var encryptService = Encrypter(AES(cipherKey, mode: AESMode.cbc,padding: null)); -// // var initVector = IV.fromUtf8(key.substring(0, 16)); -// // return encryptService.decrypt(encryptedData, iv: initVector); -// // } -// // -// // ///Encrypts the given plainText using the key. Returns encrypted data -// // Encrypted encryptWithAES(String key, String plainText) { -// // var cipherKey = encrypt.Key.fromUtf8(key); -// // var encryptService = Encrypter(AES(cipherKey, mode: AESMode.cbc,padding: null)); -// // var initVector = IV.fromUtf8("j70IbWYn"); -// // Encrypted encryptedData = encryptService.encrypt(plainText, iv: initVector); -// // print(encryptedData.base64); -// // return encryptedData; -// // } -// // -// // Tuple2 deriveKeyAndIV(String passphrase, Uint8List salt) { -// // var password = createUint8ListFromString(passphrase); -// // Uint8List concatenatedHashes = Uint8List(0); -// // Uint8List currentHash = Uint8List(0); -// // bool enoughBytesForKey = false; -// // Uint8List preHash = Uint8List(0); -// // -// // while (!enoughBytesForKey) { -// // int preHashLength = currentHash.length + password.length + salt.length; -// // if (currentHash.length > 0) -// // preHash = Uint8List.fromList(currentHash + password + salt); -// // else -// // preHash = Uint8List.fromList(password + salt); -// // -// // currentHash = preHash; -// // concatenatedHashes = Uint8List.fromList(concatenatedHashes + currentHash); -// // if (concatenatedHashes.length >= 48) enoughBytesForKey = true; -// // } -// // -// // var keyBtyes = concatenatedHashes.sublist(0, 32); -// // var ivBtyes = concatenatedHashes.sublist(32, 48); -// // return new Tuple2(keyBtyes, ivBtyes); -// // } -// // -// // Uint8List createUint8ListFromString(String s) { -// // var ret = new Uint8List(s.length); -// // for (var i = 0; i < s.length; i++) { -// // ret[i] = s.codeUnitAt(i); -// // } -// // return ret; -// // } -// // -// // Uint8List genRandomWithNonZero(int seedLength) { -// // var random = Random.secure(); -// // const int randomMax = 245; -// // Uint8List uint8list = Uint8List(seedLength); -// // for (int i = 0; i < seedLength; i++) { -// // uint8list[i] = random.nextInt(randomMax) + 1; -// // } -// // return uint8list; -// // } -// // -// // -// // -// // void test(String text, String kk) { -// // Uint8List key = Uint8List.fromList(utf8.encode(kk)); -// // PaddedBlockCipher cipher = exp.PaddedBlockCipherImpl(exp.PKCS7Padding(), exp.ECBBlockCipher(exp.AESEngine())); -// // cipher.init(true, PaddedBlockCipherParameters(KeyParameter(key), null)); -// // var byte = Uint8List.fromList(utf8.encode(text)); -// // var data = cipher.process(byte); -// // print(data); -// // } -// -// } +import 'dart:convert'; + +import 'package:flutter/services.dart'; + +class Encryption { + static final Encryption _instance = Encryption._internal(); + static const MethodChannel _channel = MethodChannel('flutter_des'); + static const key = "PeShVmYp"; + static const iv = "j70IbWYn"; + + Encryption._internal(); + + factory Encryption() => _instance; + + Future encrypt({required String val}) async { + Uint8List? crypt = await _channel.invokeMethod('encrypt', [val, key, iv]); + String data = base64Encode(crypt!.toList()); + print("Base64Enc: " + data); + return data; + } + + Future decrypt({required String encodedVal}) async { + var deco = base64Decode(encodedVal); + String? decCrypt = await _channel.invokeMethod('decrypt', [deco, key, iv]); + print("Base64ToStringDec: " + decCrypt!); + return decCrypt!; + } +} diff --git a/lib/models/chat/chat_user_image_model.dart b/lib/models/chat/chat_user_image_model.dart new file mode 100644 index 0000000..cdee33d --- /dev/null +++ b/lib/models/chat/chat_user_image_model.dart @@ -0,0 +1,33 @@ +// To parse this JSON data, do +// +// final chatUserImageModel = chatUserImageModelFromJson(jsonString); + +import 'dart:convert'; + +List chatUserImageModelFromJson(String str) => List.from(json.decode(str).map((x) => ChatUserImageModel.fromJson(x))); + +String chatUserImageModelToJson(List data) => json.encode(List.from(data.map((x) => x.toJson()))); + +class ChatUserImageModel { + ChatUserImageModel({ + this.email, + this.profilePicture, + this.mobileNumber, + }); + + String? email; + String? profilePicture; + String? mobileNumber; + + factory ChatUserImageModel.fromJson(Map json) => ChatUserImageModel( + email: json["email"] == null ? null : json["email"], + profilePicture: json["profilePicture"] == null ? null : json["profilePicture"], + mobileNumber: json["mobileNumber"] == null ? null : json["mobileNumber"], + ); + + Map toJson() => { + "email": email == null ? null : email, + "profilePicture": profilePicture == null ? null : profilePicture, + "mobileNumber": mobileNumber == null ? null : mobileNumber, + }; +} diff --git a/lib/models/chat/get_search_user_chat_model.dart b/lib/models/chat/get_search_user_chat_model.dart index 31d1085..fe87061 100644 --- a/lib/models/chat/get_search_user_chat_model.dart +++ b/lib/models/chat/get_search_user_chat_model.dart @@ -19,21 +19,23 @@ class ChatUserModel { } class ChatUser { - ChatUser( - {this.id, - this.userName, - this.email, - this.phone, - this.title, - this.userStatus, - this.image, - this.unreadMessageCount, - this.userAction, - this.isPin, - this.isFav, - this.isAdmin, - this.isTyping, - this.isLoadingCounter}); + ChatUser({ + this.id, + this.userName, + this.email, + this.phone, + this.title, + this.userStatus, + this.image, + this.unreadMessageCount, + this.userAction, + this.isPin, + this.isFav, + this.isAdmin, + this.isTyping, + this.isImageLoaded, + this.isImageLoading, + }); int? id; String? userName; @@ -48,7 +50,8 @@ class ChatUser { bool? isFav; bool? isAdmin; bool? isTyping; - bool? isLoadingCounter; + bool? isImageLoaded; + bool? isImageLoading; factory ChatUser.fromJson(Map json) => ChatUser( id: json["id"] == null ? null : json["id"], @@ -64,7 +67,8 @@ class ChatUser { isFav: json["isFav"] == null ? null : json["isFav"], isAdmin: json["isAdmin"] == null ? null : json["isAdmin"], isTyping: false, - isLoadingCounter: true, + isImageLoaded: false, + isImageLoading: true, ); Map toJson() => { diff --git a/lib/provider/chat_provider_model.dart b/lib/provider/chat_provider_model.dart index b48d845..c56241f 100644 --- a/lib/provider/chat_provider_model.dart +++ b/lib/provider/chat_provider_model.dart @@ -7,8 +7,10 @@ import 'package:flutter/foundation.dart'; import 'package:http/http.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/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_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'; import 'package:mohem_flutter_app/models/chat/make_user_favotire_unfavorite_chat_model.dart' as fav; @@ -75,6 +77,7 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { ), ); notifyListeners(); + getUserImages(); } Future invokeUserChatHistoryNotDeliveredAsync({required int userId}) async { @@ -105,7 +108,7 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { } isLoading = false; notifyListeners(); - markRead(userChatHistory, receiverUID); + // markRead(userChatHistory, receiverUID); generateConvId(); } @@ -231,7 +234,6 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { int? val = element.unreadMessageCount ?? 0; element.unreadMessageCount = val! + 1; } - element.isLoadingCounter = false; }, ); } @@ -698,4 +700,33 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { // } // } + void getUserImages() async { + List emails = []; + for (ChatUser element in searchedChats!) { + var encMail = await Encryption().encrypt(val: element.email!); + emails.add(encMail); + } + List chatImages = await ChatApiClient().getUsersImages(encryptedEmails: emails); + for (ChatUser user in searchedChats!) { + for (ChatUserImageModel uImage in chatImages) { + if (user.email == uImage.email) { + user.image = uImage.profilePicture ?? ""; + user.isImageLoading = false; + user.isImageLoaded = true; + notifyListeners(); + } + } + } + + for (ChatUser favUser in favUsersList) { + for (ChatUserImageModel uImage in chatImages) { + if (favUser.email == uImage.email) { + favUser.image = uImage.profilePicture ?? ""; + favUser.isImageLoading = false; + favUser.isImageLoaded = true; + notifyListeners(); + } + } + } + } } diff --git a/lib/ui/chat/chat_detailed_screen.dart b/lib/ui/chat/chat_detailed_screen.dart index 1d220bc..6f9e4cf 100644 --- a/lib/ui/chat/chat_detailed_screen.dart +++ b/lib/ui/chat/chat_detailed_screen.dart @@ -68,6 +68,7 @@ class _ChatDetailScreenState extends State { isNewChat: userDetails["isNewChat"], ); } + print("Img: "+ userDetails["targetUser"].image); return Scaffold( backgroundColor: MyColors.backgroundColor, @@ -75,7 +76,7 @@ class _ChatDetailScreenState extends State { context, title: userDetails["targetUser"].userName.toString().replaceAll(".", " ").capitalizeFirstofEach, showHomeButton: false, - image: userDetails["targetUser"].image, + image: userDetails["targetUser"].image.isEmpty ? null : userDetails["targetUser"].image, 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.dart b/lib/ui/chat/chat_home.dart index 3bf8cda..1ae3252 100644 --- a/lib/ui/chat/chat_home.dart +++ b/lib/ui/chat/chat_home.dart @@ -27,6 +27,8 @@ class _ChatHomeState extends State { void initState() { super.initState(); data = Provider.of(context, listen: false); + data.registerEvents(); + data.getUserRecentChats(); } @override diff --git a/lib/ui/chat/chat_home_screen.dart b/lib/ui/chat/chat_home_screen.dart index e2f2dc2..5ccc6ad 100644 --- a/lib/ui/chat/chat_home_screen.dart +++ b/lib/ui/chat/chat_home_screen.dart @@ -1,10 +1,14 @@ 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'; @@ -12,6 +16,7 @@ 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/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'; @@ -26,11 +31,8 @@ class _ChatHomeScreenState extends State { @override void initState() { - // TODO: implement initState super.initState(); data = Provider.of(context, listen: false); - data.registerEvents(); - data.getUserRecentChats(); } @override @@ -89,11 +91,26 @@ class _ChatHomeScreenState extends State { children: [ Stack( children: [ - SvgPicture.asset( - "assets/images/user.svg", - height: 48, - width: 48, - ), + if (m.searchedChats![index].isImageLoading!) + const SizedBox( + height: 48, + width: 48, + child: Center(child: CircularProgressIndicator()), + ), + if (m.searchedChats![index].isImageLoaded! && m.searchedChats![index].image != null && 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) + SvgPicture.asset( + "assets/images/user.svg", + height: 48, + width: 48, + ), Positioned( right: 5, bottom: 1, diff --git a/lib/ui/chat/favorite_users_screen.dart b/lib/ui/chat/favorite_users_screen.dart index 6bc0040..8bfcc4a 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/widgets/circular_avatar.dart'; import 'package:mohem_flutter_app/widgets/shimmer/dashboard_shimmer_widget.dart'; import 'package:provider/provider.dart'; @@ -36,11 +37,26 @@ class ChatFavoriteUsersScreen extends StatelessWidget { children: [ Stack( children: [ - SvgPicture.asset( - "assets/images/user.svg", - height: 48, - width: 48, - ), + if (m.favUsersList![index].isImageLoading!) + const SizedBox( + height: 48, + width: 48, + child: Center(child: CircularProgressIndicator()), + ), + 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) + SvgPicture.asset( + "assets/images/user.svg", + height: 48, + width: 48, + ), Positioned( right: 5, bottom: 1, @@ -49,11 +65,8 @@ class ChatFavoriteUsersScreen extends StatelessWidget { height: 10, decoration: BoxDecoration( color: m.favUsersList![index].userStatus == 1 ? MyColors.green2DColor : Colors.red, - borderRadius: const BorderRadius.all( - Radius.circular(10), - ), ), - ), + ).circle(10), ) ], ), diff --git a/lib/widgets/app_bar_widget.dart b/lib/widgets/app_bar_widget.dart index c2129c1..9cd7e27 100644 --- a/lib/widgets/app_bar_widget.dart +++ b/lib/widgets/app_bar_widget.dart @@ -5,6 +5,7 @@ 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/widgets/circular_avatar.dart'; AppBar AppBarWidget(BuildContext context, {required String title, bool showHomeButton = true, bool showNotificationButton = false, bool showMemberButton = false, String? image, List? actions}) { @@ -25,12 +26,20 @@ AppBar AppBarWidget(BuildContext context, ), 4.width, if (image != null) + CircularAvatar( + url: image, + height: 40, + width: 40, + isImageBase64: true, + ), + if (image == null) SvgPicture.asset( - image, + "assets/images/user.svg", height: 40, width: 40, ), if (image != null) 14.width, + if (image == null) 14.width, title.toText24(color: MyColors.darkTextColor, isBold: true).expanded, ], ), @@ -59,7 +68,7 @@ AppBar AppBarWidget(BuildContext context, }, icon: const Icon(Icons.people, color: MyColors.textMixColor), ), - ...actions??[] + ...actions ?? [] ], ); } diff --git a/pubspec.yaml b/pubspec.yaml index f17ce5f..4fc00c8 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -93,6 +93,8 @@ dependencies: flutter_webrtc: ^0.9.16 camera: ^0.10.0+4 + #Encryption + flutter_des: ^2.1.0 video_player: ^2.4.7 just_audio: ^0.9.30 From ef5136ebfa465d3b7d3ce64059da7cfda473334a Mon Sep 17 00:00:00 2001 From: "mirza.shafique" Date: Mon, 5 Dec 2022 11:37:50 +0300 Subject: [PATCH 13/35] worklist animation & loader --- lib/classes/consts.dart | 4 +- .../add_leave_balance_screen.dart | 27 +- lib/ui/misc/request_submit_screen.dart | 4 +- .../dynamic_screens/dynamic_input_screen.dart | 6 +- lib/ui/work_list/worklist_detail_screen.dart | 334 +++++++++--------- lib/widgets/app_bar_widget.dart | 4 +- 6 files changed, 200 insertions(+), 179 deletions(-) diff --git a/lib/classes/consts.dart b/lib/classes/consts.dart index 13c4258..57e92ec 100644 --- a/lib/classes/consts.dart +++ b/lib/classes/consts.dart @@ -2,8 +2,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://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 85337aa..d1b7d77 100644 --- a/lib/ui/leave_balance/add_leave_balance_screen.dart +++ b/lib/ui/leave_balance/add_leave_balance_screen.dart @@ -109,17 +109,16 @@ class _AddLeaveBalanceScreenState extends State { } } } - 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); + 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); SumbitAbsenceTransactionList submit = await LeaveBalanceApiClient().submitAbsenceTransaction( selectedAbsenceType!.dESCFLEXCONTEXTCODE!, @@ -134,8 +133,10 @@ class _AddLeaveBalanceScreenState extends State { Utils.hideLoading(context); - await Navigator.pushNamed(context, AppRoutes.requestSubmitScreen, arguments: RequestSubmitScreenParams(LocaleKeys.submit.tr(), submit.pTRANSACTIONID!, "", "add_leave_balance")); - Utils.showLoading(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) { diff --git a/lib/ui/misc/request_submit_screen.dart b/lib/ui/misc/request_submit_screen.dart index f5a2d1e..a4ffdcb 100644 --- a/lib/ui/misc/request_submit_screen.dart +++ b/lib/ui/misc/request_submit_screen.dart @@ -68,7 +68,7 @@ class _RequestSubmitScreenState extends State { } void submitRequest() async { - try { + try { Utils.showLoading(context); List> list = []; if (attachmentFiles.isNotEmpty) { @@ -129,7 +129,7 @@ class _RequestSubmitScreenState extends State { params!.pItemId, params!.transactionId, ); - }else if (params!.approvalFlag == 'endEmployment') { + } else if (params!.approvalFlag == 'endEmployment') { await TerminationDffApiClient().startTermApprovalProcess( "SUBMIT", comments.text, 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 ad7ad50..72aa190 100644 --- a/lib/ui/my_attendance/dynamic_screens/dynamic_input_screen.dart +++ b/lib/ui/my_attendance/dynamic_screens/dynamic_input_screen.dart @@ -96,9 +96,11 @@ class _DynamicInputScreenState extends State { SubmitEITTransactionList submitEITTransactionList = await MyAttendanceApiClient().submitEitTransaction(dESCFLEXCONTEXTCODE, dynamicParams!.dynamicId, values, empID: dynamicParams!.selectedEmp ?? ''); Utils.hideLoading(context); - await Navigator.pushNamed(context, AppRoutes.requestSubmitScreen, + var res = await Navigator.pushNamed(context, AppRoutes.requestSubmitScreen, arguments: RequestSubmitScreenParams(LocaleKeys.submit.tr(), submitEITTransactionList.pTRANSACTIONID!, submitEITTransactionList.pITEMKEY!, 'eit')); - Utils.showLoading(context); + if (res != null && res == true) { + Utils.showLoading(context); + } await LeaveBalanceApiClient().cancelHrTransaction(submitEITTransactionList.pTRANSACTIONID!); Utils.hideLoading(context); } catch (ex) { diff --git a/lib/ui/work_list/worklist_detail_screen.dart b/lib/ui/work_list/worklist_detail_screen.dart index 824edc3..5d6727c 100644 --- a/lib/ui/work_list/worklist_detail_screen.dart +++ b/lib/ui/work_list/worklist_detail_screen.dart @@ -191,169 +191,187 @@ class _WorkListDetailScreenState extends State { return Scaffold( appBar: AppBarWidget(context, title: LocaleKeys.details.tr()), backgroundColor: Colors.white, - body: Stack( - children: [ - Column( - children: [ - Container( - padding: const EdgeInsets.only(left: 21, right: 21, top: 16, bottom: 16), - decoration: const BoxDecoration( - borderRadius: BorderRadius.only( - bottomLeft: Radius.circular(25), - bottomRight: Radius.circular(25), - ), - gradient: LinearGradient( - transform: GradientRotation(.83), - begin: Alignment.topRight, - end: Alignment.bottomLeft, - colors: [ - MyColors.gradiantEndColor, - MyColors.gradiantStartColor, - ], - ), - ), - child: Row( - children: [ - myTab(LocaleKeys.info.tr(), 0), - (workListData!.iTEMTYPE == "HRSSA" || workListData!.iTEMTYPE == "STAMP") ? myTab(LocaleKeys.details.tr(), 1) : myTab(LocaleKeys.request.tr(), 1), - myTab(LocaleKeys.actions.tr(), 2), - myTab(LocaleKeys.attachments.tr(), 3), - ], - ), - ), - if ((workListData?.sUBJECT ?? "").isNotEmpty) workListData!.sUBJECT!.toText14().paddingOnly(top: 20, right: 21, left: 21), - PageView( - controller: controller, - onPageChanged: (pageIndex) { - setState(() { - tabIndex = pageIndex; - }); - }, - children: [ - InfoFragment( - poHeaderList: getPoNotificationBody?.pOHeader ?? [], - workListData: workListData, - itemCreationHeader: getItemCreationNtfBody?.itemCreationHeader ?? [], - getStampMsNotifications: getStampMsNotifications, - getStampNsNotifications: getStampNsNotifications, - getEitCollectionNotificationBodyList: getEitCollectionNotificationBodyList, - getPhonesNotificationBodyList: getPhonesNotificationBodyList, - getBasicDetNtfBodyList: getBasicDetNtfBodyList, - getAbsenceCollectionNotificationBodyList: getAbsenceCollectionNotificationBodyList, - getContactNotificationBodyList: getContactNotificationBodyList, - getPrNotificationBodyList: getPrNotificationBody, - ), - (workListData!.iTEMTYPE == "HRSSA" || workListData!.iTEMTYPE == "STAMP") - ? DetailFragment(workListData, memberInformationListModel) - : RequestFragment( - moNotificationBodyList: getMoNotificationBodyList, - poLinesList: getPoNotificationBody?.pOLines ?? [], - itemCreationLines: getItemCreationNtfBody?.itemCreationLines ?? [], - prLinesList: getPrNotificationBody?.pRLines ?? [], - ), - isActionHistoryLoaded - ? actionHistoryList.isEmpty - ? Utils.getNoDataWidget(context) - : ActionsFragment( - workListData!.nOTIFICATIONID, - actionHistoryList, - voidCallback: reloadWorkList, - ) - : showLoadingAnimation(), - isAttachmentLoaded - ? getAttachmentList.isEmpty - ? Utils.getNoDataWidget(context) - : AttachmentsFragment(getAttachmentList) - : showLoadingAnimation(), - ], - ).expanded, - if (isApproveAvailable || isRejectAvailable || isCloseAvailable) + body: AnimatedSwitcher( + duration: const Duration(milliseconds: 500), + switchInCurve: Curves.easeInToLinear, + transitionBuilder: (Widget child, Animation animation) { + Animation custom = Tween( + begin: const Offset(1.0, 0.0), + end: Offset.zero, + ).animate(animation); + return ClipRect( + child: SlideTransition( + position: custom, + child: child, + // textDirection: TextDirection.ltr, + ), + ); + }, + child: Stack( + key: ValueKey(AppState().workListIndex ?? 0), + children: [ + Column( + children: [ Container( - padding: const EdgeInsets.only(top: 14, bottom: 14, left: 21, right: 21), + padding: const EdgeInsets.only(left: 21, right: 21, top: 16, bottom: 16), decoration: const BoxDecoration( - color: Colors.white, - border: Border( - top: BorderSide(color: MyColors.lightGreyEFColor, width: 1.0), + borderRadius: BorderRadius.only( + bottomLeft: Radius.circular(25), + bottomRight: Radius.circular(25), + ), + gradient: LinearGradient( + transform: GradientRotation(.83), + begin: Alignment.topRight, + end: Alignment.bottomLeft, + colors: [ + MyColors.gradiantEndColor, + MyColors.gradiantStartColor, + ], ), ), child: Row( children: [ - if (isRejectAvailable) - DefaultButton( - LocaleKeys.reject.tr(), - () => performAction("REJECTED"), - colors: const [Color(0xffE47A7E), Color(0xffDE6D71)], - ).expanded, - if (isApproveAvailable && isRejectAvailable) 8.width, - if (isApproveAvailable) - DefaultButton( - LocaleKeys.approve.tr(), - () => performAction("APPROVED"), - colors: const [Color(0xff28C884), Color(0xff1BB271)], - ).expanded, - if (isCloseAvailable) - DefaultButton( - LocaleKeys.ok.tr(), - () => performAction("CLOSE"), - colors: const [Color(0xff32D892), Color(0xff1AB170)], - ).expanded, - 8.width, - Container( - height: 43, - width: 43, - decoration: const BoxDecoration( - shape: BoxShape.circle, - color: MyColors.lightGreyE6Color, - ), - child: Icon(showFabOptions ? Icons.more_vert_rounded : Icons.more_horiz_rounded, color: MyColors.darkIconColor), - ).onPress(() { - setState(() { - showFabOptions = true; - }); - }) + myTab(LocaleKeys.info.tr(), 0), + (workListData!.iTEMTYPE == "HRSSA" || workListData!.iTEMTYPE == "STAMP") ? myTab(LocaleKeys.details.tr(), 1) : myTab(LocaleKeys.request.tr(), 1), + myTab(LocaleKeys.actions.tr(), 2), + myTab(LocaleKeys.attachments.tr(), 3), ], ), - ) - ], - ), - IgnorePointer( - ignoring: !showFabOptions, - child: AnimatedOpacity( - opacity: showFabOptions ? 1 : 0, - duration: const Duration(milliseconds: 250), - child: Container( - padding: const EdgeInsets.only(left: 21, right: 21, bottom: 75 - 12), - width: double.infinity, - height: double.infinity, - color: Colors.white.withOpacity(.67), - alignment: Alignment.bottomRight, - child: Column( - mainAxisSize: MainAxisSize.min, - crossAxisAlignment: CrossAxisAlignment.end, + ), + if ((workListData?.sUBJECT ?? "").isNotEmpty) workListData!.sUBJECT!.toText14().paddingOnly(top: 20, right: 21, left: 21), + PageView( + controller: controller, + onPageChanged: (int pageIndex) { + setState(() { + tabIndex = pageIndex; + }); + }, children: [ - myFab(LocaleKeys.skip.tr(), "assets/images/skip.svg").onPress(() { - if (AppState().workList!.length - 1 > AppState().workListIndex!) { - AppState().setWorkListIndex = AppState().workListIndex! + 1; - workListData = null; - showFabOptions = false; - tabIndex = 0; - getDataFromState(); - } else if (AppState().workList!.length - 1 == AppState().workListIndex!) { - Navigator.pop(context); - } - }), - 12.height, - ...viewApiButtonsList(notificationButtonsList), + InfoFragment( + poHeaderList: getPoNotificationBody?.pOHeader ?? [], + workListData: workListData, + itemCreationHeader: getItemCreationNtfBody?.itemCreationHeader ?? [], + getStampMsNotifications: getStampMsNotifications, + getStampNsNotifications: getStampNsNotifications, + getEitCollectionNotificationBodyList: getEitCollectionNotificationBodyList, + getPhonesNotificationBodyList: getPhonesNotificationBodyList, + getBasicDetNtfBodyList: getBasicDetNtfBodyList, + getAbsenceCollectionNotificationBodyList: getAbsenceCollectionNotificationBodyList, + getContactNotificationBodyList: getContactNotificationBodyList, + getPrNotificationBodyList: getPrNotificationBody, + ), + (workListData!.iTEMTYPE == "HRSSA" || workListData!.iTEMTYPE == "STAMP") + ? DetailFragment(workListData, memberInformationListModel) + : RequestFragment( + moNotificationBodyList: getMoNotificationBodyList, + poLinesList: getPoNotificationBody?.pOLines ?? [], + itemCreationLines: getItemCreationNtfBody?.itemCreationLines ?? [], + prLinesList: getPrNotificationBody?.pRLines ?? [], + ), + isActionHistoryLoaded + ? actionHistoryList.isEmpty + ? Utils.getNoDataWidget(context) + : ActionsFragment( + workListData!.nOTIFICATIONID, + actionHistoryList, + voidCallback: reloadWorkList, + ) + : showLoadingAnimation(), + isAttachmentLoaded + ? getAttachmentList.isEmpty + ? Utils.getNoDataWidget(context) + : AttachmentsFragment(getAttachmentList) + : showLoadingAnimation(), ], + ).expanded, + if (isApproveAvailable || isRejectAvailable || isCloseAvailable) + Container( + padding: const EdgeInsets.only(top: 14, bottom: 14, left: 21, right: 21), + decoration: const BoxDecoration( + color: Colors.white, + border: Border( + top: BorderSide(color: MyColors.lightGreyEFColor, width: 1.0), + ), + ), + child: Row( + children: [ + if (isRejectAvailable) + DefaultButton( + LocaleKeys.reject.tr(), + () => performAction("REJECTED"), + colors: const [Color(0xffE47A7E), Color(0xffDE6D71)], + ).expanded, + if (isApproveAvailable && isRejectAvailable) 8.width, + if (isApproveAvailable) + DefaultButton( + LocaleKeys.approve.tr(), + () => performAction("APPROVED"), + colors: const [Color(0xff28C884), Color(0xff1BB271)], + ).expanded, + if (isCloseAvailable) + DefaultButton( + LocaleKeys.ok.tr(), + () => performAction("CLOSE"), + colors: const [Color(0xff32D892), Color(0xff1AB170)], + ).expanded, + 8.width, + Container( + height: 43, + width: 43, + decoration: const BoxDecoration( + shape: BoxShape.circle, + color: MyColors.lightGreyE6Color, + ), + child: Icon(showFabOptions ? Icons.more_vert_rounded : Icons.more_horiz_rounded, color: MyColors.darkIconColor), + ).onPress(() { + setState(() { + showFabOptions = true; + }); + }) + ], + ), + ) + ], + ), + IgnorePointer( + ignoring: !showFabOptions, + child: AnimatedOpacity( + opacity: showFabOptions ? 1 : 0, + duration: const Duration(milliseconds: 250), + child: Container( + padding: const EdgeInsets.only(left: 21, right: 21, bottom: 75 - 12), + width: double.infinity, + height: double.infinity, + color: Colors.white.withOpacity(.67), + alignment: Alignment.bottomRight, + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.end, + children: [ + myFab(LocaleKeys.skip.tr(), "assets/images/skip.svg").onPress(() { + if (AppState().workList!.length - 1 > AppState().workListIndex!) { + AppState().setWorkListIndex = AppState().workListIndex! + 1; + workListData = null; + showFabOptions = false; + tabIndex = 0; + getDataFromState(); + } else if (AppState().workList!.length - 1 == AppState().workListIndex!) { + Navigator.pop(context); + } + }), + 12.height, + ...viewApiButtonsList(notificationButtonsList), + ], + ), ), - ), - ).onPress(() { - setState(() { - showFabOptions = false; - }); - }), - ), - ], + ).onPress(() { + setState(() { + showFabOptions = false; + }); + }), + ), + ], + ), ), floatingActionButton: (!isApproveAvailable && !isRejectAvailable && !isCloseAvailable) ? Container( @@ -546,7 +564,7 @@ class _WorkListDetailScreenState extends State { Future performNetworkCall(BuildContext context, {String? email, String? userId}) async { showDialog( context: context, - builder: (cxt) => ConfirmDialog( + builder: (BuildContext cxt) => ConfirmDialog( message: LocaleKeys.wantToReject.tr(), okTitle: LocaleKeys.reject.tr(), onTap: () async { @@ -629,12 +647,12 @@ class _WorkListDetailScreenState extends State { print(actionMode); showDialog( context: context, - builder: (cxt) => AcceptRejectInputDialog( + builder: (BuildContext cxt) => AcceptRejectInputDialog( message: title != null ? null : LocaleKeys.requestedItems.tr(), title: title, notificationGetRespond: notificationNoteInput, actionMode: actionMode, - onTap: (note) { + onTap: (String note) { Map payload = { "P_ACTION_MODE": actionMode, "P_APPROVER_INDEX": null, @@ -915,9 +933,9 @@ class _WorkListDetailScreenState extends State { apiCallCount++; notificationButtonsList = await WorkListApiClient().getNotificationButtons(workListData!.nOTIFICATIONID!); if (notificationButtonsList.isNotEmpty) { - isCloseAvailable = notificationButtonsList.any((element) => element.bUTTONACTION == "CLOSE"); - isApproveAvailable = notificationButtonsList.any((element) => element.bUTTONACTION == "APPROVED"); - isRejectAvailable = notificationButtonsList.any((element) => element.bUTTONACTION == "REJECTED"); + isCloseAvailable = notificationButtonsList.any((GetNotificationButtonsList element) => element.bUTTONACTION == "CLOSE"); + isApproveAvailable = notificationButtonsList.any((GetNotificationButtonsList element) => element.bUTTONACTION == "APPROVED"); + isRejectAvailable = notificationButtonsList.any((GetNotificationButtonsList element) => element.bUTTONACTION == "REJECTED"); } apiCallCount--; if (apiCallCount == 0) { diff --git a/lib/widgets/app_bar_widget.dart b/lib/widgets/app_bar_widget.dart index c2129c1..fa59d3a 100644 --- a/lib/widgets/app_bar_widget.dart +++ b/lib/widgets/app_bar_widget.dart @@ -20,7 +20,7 @@ AppBar AppBarWidget(BuildContext context, children: [ GestureDetector( behavior: HitTestBehavior.opaque, - onTap: Feedback.wrapForTap(() => Navigator.maybePop(context), context), + onTap: Feedback.wrapForTap(() => Navigator.maybePop(context, true), context), child: const Icon(Icons.arrow_back_ios, color: MyColors.darkIconColor), ), 4.width, @@ -59,7 +59,7 @@ AppBar AppBarWidget(BuildContext context, }, icon: const Icon(Icons.people, color: MyColors.textMixColor), ), - ...actions??[] + ...actions ?? [] ], ); } From 13a7f60d675c94527ca9d24488389ad74823fe9d Mon Sep 17 00:00:00 2001 From: "Aamir.Muhammad" Date: Mon, 5 Dec 2022 11:59:23 +0300 Subject: [PATCH 14/35] Chat Fixes & User Chat Counter --- lib/classes/encryption.dart | 16 +++++++--------- lib/provider/chat_provider_model.dart | 4 +--- lib/ui/chat/chat_detailed_screen.dart | 1 - lib/ui/chat/chat_home.dart | 4 +++- 4 files changed, 11 insertions(+), 14 deletions(-) diff --git a/lib/classes/encryption.dart b/lib/classes/encryption.dart index f26c92b..a4ab6be 100644 --- a/lib/classes/encryption.dart +++ b/lib/classes/encryption.dart @@ -2,27 +2,25 @@ import 'dart:convert'; import 'package:flutter/services.dart'; -class Encryption { - static final Encryption _instance = Encryption._internal(); +class EmailImageEncryption { + static final EmailImageEncryption _instance = EmailImageEncryption._internal(); static const MethodChannel _channel = MethodChannel('flutter_des'); static const key = "PeShVmYp"; static const iv = "j70IbWYn"; - Encryption._internal(); + EmailImageEncryption._internal(); - factory Encryption() => _instance; + factory EmailImageEncryption() => _instance; Future encrypt({required String val}) async { Uint8List? crypt = await _channel.invokeMethod('encrypt', [val, key, iv]); - String data = base64Encode(crypt!.toList()); - print("Base64Enc: " + data); - return data; + String enc = base64Encode(crypt!.toList()); + return enc; } Future decrypt({required String encodedVal}) async { - var deco = base64Decode(encodedVal); + Uint8List deco = base64Decode(encodedVal); String? decCrypt = await _channel.invokeMethod('decrypt', [deco, key, iv]); - print("Base64ToStringDec: " + decCrypt!); return decCrypt!; } } diff --git a/lib/provider/chat_provider_model.dart b/lib/provider/chat_provider_model.dart index c56241f..535dc2e 100644 --- a/lib/provider/chat_provider_model.dart +++ b/lib/provider/chat_provider_model.dart @@ -460,7 +460,6 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { print("Normal Attachment Msg"); Utils.showLoading(context); dynamic value = await uploadAttachments(AppState().chatDetails!.response!.id.toString(), selectedFile); - logger.d(value); String? ext = getFileExtension(selectedFile.path); Utils.hideLoading(context); sendChatToServer( @@ -703,8 +702,7 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { void getUserImages() async { List emails = []; for (ChatUser element in searchedChats!) { - var encMail = await Encryption().encrypt(val: element.email!); - emails.add(encMail); + emails.add(await EmailImageEncryption().encrypt(val: element.email!)); } List chatImages = await ChatApiClient().getUsersImages(encryptedEmails: emails); for (ChatUser user in searchedChats!) { diff --git a/lib/ui/chat/chat_detailed_screen.dart b/lib/ui/chat/chat_detailed_screen.dart index 6f9e4cf..345884f 100644 --- a/lib/ui/chat/chat_detailed_screen.dart +++ b/lib/ui/chat/chat_detailed_screen.dart @@ -68,7 +68,6 @@ class _ChatDetailScreenState extends State { isNewChat: userDetails["isNewChat"], ); } - print("Img: "+ userDetails["targetUser"].image); return Scaffold( backgroundColor: MyColors.backgroundColor, diff --git a/lib/ui/chat/chat_home.dart b/lib/ui/chat/chat_home.dart index 1ae3252..0438dc6 100644 --- a/lib/ui/chat/chat_home.dart +++ b/lib/ui/chat/chat_home.dart @@ -28,7 +28,9 @@ class _ChatHomeState extends State { super.initState(); data = Provider.of(context, listen: false); data.registerEvents(); - data.getUserRecentChats(); + if (data.searchedChats == null || data.searchedChats!.isEmpty) { + data.getUserRecentChats(); + } } @override From 6a3c6a25d0c9fd7d833e220846ab308b2575137f Mon Sep 17 00:00:00 2001 From: "Aamir.Muhammad" Date: Mon, 5 Dec 2022 12:40:56 +0300 Subject: [PATCH 15/35] Chat Fixes & User Chat Counter --- lib/provider/chat_provider_model.dart | 15 +++++++++------ lib/ui/chat/chat_home_screen.dart | 4 ++-- 2 files changed, 11 insertions(+), 8 deletions(-) diff --git a/lib/provider/chat_provider_model.dart b/lib/provider/chat_provider_model.dart index 535dc2e..fd908a1 100644 --- a/lib/provider/chat_provider_model.dart +++ b/lib/provider/chat_provider_model.dart @@ -38,10 +38,10 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { void registerEvents() { hubConnection.on("OnUpdateUserStatusAsync", changeStatus); hubConnection.on("OnDeliveredChatUserAsync", onMsgReceived); - hubConnection.on("OnSeenChatUserAsync", onChatSeen); + // hubConnection.on("OnSeenChatUserAsync", onChatSeen); //hubConnection.on("OnUserTypingAsync", onUserTyping); hubConnection.on("OnUserCountAsync", userCountAsync); - hubConnection.on("OnUpdateUserChatHistoryWindowsAsync", updateChatHistoryWindow); + // hubConnection.on("OnUpdateUserChatHistoryWindowsAsync", updateChatHistoryWindow); hubConnection.on("OnGetUserChatHistoryNotDeliveredAsync", chatNotDelivered); hubConnection.on("OnUpdateUserChatHistoryStatusAsync", updateUserChatStatus); } @@ -108,7 +108,7 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { } isLoading = false; notifyListeners(); - // markRead(userChatHistory, receiverUID); + markRead(userChatHistory, receiverUID); generateConvId(); } @@ -124,7 +124,12 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { if (!element.isSeen!) { element.isSeen = true; dynamic data = [ - {"userChatHistoryId": element.userChatHistoryId, "TargetUserId": element.currentUserId, "isDelivered": true, "isSeen": true} + { + "userChatHistoryId": element.userChatHistoryId, + "TargetUserId": element.currentUserId == receiverID ? element.currentUserId : element.targetUserId, + "isDelivered": true, + "isSeen": true, + } ]; updateUserChatHistoryStatusAsync(data); notifyListeners(); @@ -190,8 +195,6 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { void onChatSeen(List? args) { dynamic items = args!.toList(); - logger.d("---------------------------------Chat Seen -------------------------------------"); - logger.d(items); // for (var user in searchedChats!) { // if (user.id == items.first["id"]) { // user.userStatus = items.first["userStatus"]; diff --git a/lib/ui/chat/chat_home_screen.dart b/lib/ui/chat/chat_home_screen.dart index 5ccc6ad..73c084a 100644 --- a/lib/ui/chat/chat_home_screen.dart +++ b/lib/ui/chat/chat_home_screen.dart @@ -84,6 +84,7 @@ class _ChatHomeScreenState extends State { itemCount: m.searchedChats!.length, shrinkWrap: true, physics: const ClampingScrollPhysics(), + padding: EdgeInsets.only(bottom: 80.0), itemBuilder: (BuildContext context, int index) { return SizedBox( height: 55, @@ -189,14 +190,13 @@ class _ChatHomeScreenState extends State { AppRoutes.chatDetailed, arguments: {"targetUser": m.searchedChats![index], "isNewChat": false}, ).then((Object? value) { - // m.GetUserChatHistoryNotDeliveredAsync(userId: int.parse(AppState().chatDetails!.response!.id.toString())); m.clearSelections(); m.notifyListeners(); }); }); }, separatorBuilder: (BuildContext context, int index) => const Divider(color: MyColors.lightGreyE5Color).paddingOnly(left: 59), - ).paddingOnly(bottom: 70).expanded, + ).expanded, ], ).paddingOnly(left: 21, right: 21); }, From fb97319164d030fee3b52146e9fc315a1f4f1d30 Mon Sep 17 00:00:00 2001 From: "Aamir.Muhammad" Date: Mon, 5 Dec 2022 14:36:57 +0300 Subject: [PATCH 16/35] Chat Fixes & User Chat Counter --- lib/provider/chat_provider_model.dart | 46 +-------------------------- lib/ui/landing/dashboard_screen.dart | 4 +-- 2 files changed, 3 insertions(+), 47 deletions(-) diff --git a/lib/provider/chat_provider_model.dart b/lib/provider/chat_provider_model.dart index fd908a1..385c64a 100644 --- a/lib/provider/chat_provider_model.dart +++ b/lib/provider/chat_provider_model.dart @@ -660,48 +660,6 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { sFileType = ""; } - // void scrollListener() { - // _firstAutoscrollExecuted = true; - // if (scrollController.hasClients && scrollController.position.pixels == scrollController.position.maxScrollExtent) { - // _shouldAutoscroll = true; - // } else { - // _shouldAutoscroll = false; - // } - // } - // - // void scrollToBottom() { - // scrollController.animateTo( - // scrollController.position.maxScrollExtent + 100, - // duration: const Duration(milliseconds: 500), - // curve: Curves.easeIn, - // ); - // } - - void msgScroll() { - // scrollController.animateTo( - // // index: 150, - // duration: Duration(seconds: 2), - // curve: Curves.easeInOutCubic); - // scrollController.animateTo( - // scrollController.position.minScrollExtent - 100, - // duration: const Duration(milliseconds: 500), - // curve: Curves.easeIn, - // ); - } - -// Future getDownLoadFile(String fileName) async { -// var data = await ChatApiClient().downloadURL(fileName: "data"); -// Image.memory(data); -// } - -// void getUserChatHistoryNotDeliveredAsync({required int userId}) async { -// try { -// await hubConnection.invoke("GetUserChatHistoryNotDeliveredAsync", args: [userId]); -// } finally { -// hubConnection.off("GetUserChatHistoryNotDeliveredAsync", method: chatNotDelivered); -// } -// } - void getUserImages() async { List emails = []; for (ChatUser element in searchedChats!) { @@ -714,20 +672,18 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { user.image = uImage.profilePicture ?? ""; user.isImageLoading = false; user.isImageLoaded = true; - notifyListeners(); } } } - for (ChatUser favUser in favUsersList) { for (ChatUserImageModel uImage in chatImages) { if (favUser.email == uImage.email) { favUser.image = uImage.profilePicture ?? ""; favUser.isImageLoading = false; favUser.isImageLoaded = true; - notifyListeners(); } } } + notifyListeners(); } } diff --git a/lib/ui/landing/dashboard_screen.dart b/lib/ui/landing/dashboard_screen.dart index b449bd1..954b647 100644 --- a/lib/ui/landing/dashboard_screen.dart +++ b/lib/ui/landing/dashboard_screen.dart @@ -66,11 +66,11 @@ class _DashboardScreenState extends State { await hubConnection.start(); hubConnection.onreconnecting(({Exception? error}) { print("============== Reconnecting ======================"); - if (hubConnection.state != HubConnectionState.Connected) { + //if (hubConnection.state != HubConnectionState.Connected) { data.getUserAutoLoginToken().whenComplete(() { buildHubConnection(); }); - } + //} }); } From 0db4a5a7cd3b88863e58c8d6c000b19bcc430d54 Mon Sep 17 00:00:00 2001 From: "Aamir.Muhammad" Date: Mon, 5 Dec 2022 14:38:57 +0300 Subject: [PATCH 17/35] Chat Fixes & User Chat Counter --- lib/ui/landing/dashboard_screen.dart | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/lib/ui/landing/dashboard_screen.dart b/lib/ui/landing/dashboard_screen.dart index 954b647..e1250b4 100644 --- a/lib/ui/landing/dashboard_screen.dart +++ b/lib/ui/landing/dashboard_screen.dart @@ -66,11 +66,10 @@ class _DashboardScreenState extends State { await hubConnection.start(); hubConnection.onreconnecting(({Exception? error}) { print("============== Reconnecting ======================"); - //if (hubConnection.state != HubConnectionState.Connected) { - data.getUserAutoLoginToken().whenComplete(() { - buildHubConnection(); - }); - //} + data.getUserAutoLoginToken().whenComplete(() { + buildHubConnection(); + data.notifyListeners(); + }); }); } From 9d0bf4fe7e24e4e19d355c6f0092aa0846496b09 Mon Sep 17 00:00:00 2001 From: Fatimah Alshammari Date: Mon, 5 Dec 2022 15:30:57 +0300 Subject: [PATCH 18/35] fix issues --- lib/api/dashboard_api_client.dart | 5 ++- lib/api/leave_balance_api_client.dart | 35 +++++++++++++++---- lib/classes/consts.dart | 4 +-- .../add_leave_balance_screen.dart | 29 +++++++++++---- .../leave_balance/leave_balance_screen.dart | 31 ++++++++++++---- lib/ui/misc/request_submit_screen.dart | 15 ++++++++ .../dynamic_screens/dynamic_input_screen.dart | 4 ++- .../services_menu_list_screen.dart | 2 +- lib/ui/my_team/create_request.dart | 2 +- lib/widgets/balances_dashboard_widget.dart | 15 +++++++- 10 files changed, 115 insertions(+), 27 deletions(-) diff --git a/lib/api/dashboard_api_client.dart b/lib/api/dashboard_api_client.dart index 9747e5c..c8fb015 100644 --- a/lib/api/dashboard_api_client.dart +++ b/lib/api/dashboard_api_client.dart @@ -65,10 +65,13 @@ class DashboardApiClient { }, url, postParams); } - Future> getAccrualBalances(String effectiveDate) async { + Future> getAccrualBalances(String effectiveDate, {String? empID}) async { String url = "${ApiConsts.erpRest}GET_ACCRUAL_BALANCES"; Map postParams = {"P_EFFECTIVE_DATE": effectiveDate}; 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.getAccrualBalancesList ?? []; diff --git a/lib/api/leave_balance_api_client.dart b/lib/api/leave_balance_api_client.dart index cd577ba..bb3f129 100644 --- a/lib/api/leave_balance_api_client.dart +++ b/lib/api/leave_balance_api_client.dart @@ -17,27 +17,33 @@ class LeaveBalanceApiClient { factory LeaveBalanceApiClient() => _instance; - Future> getAbsenceTransactions(int pSelectedResopID) 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; + } return await ApiClient().postJsonForObject((json) { GenericResponseModel? responseData = GenericResponseModel.fromJson(json); return responseData.getAbsenceTransactionList ?? []; }, url, postParams); } - Future> getAbsenceAttendanceTypes() async { + Future> getAbsenceAttendanceTypes({String? empID}) async { String url = "${ApiConsts.erpRest}GET_ABSENCE_ATTENDANCE_TYPES"; Map postParams = {}; 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.getAbsenceAttendanceTypesList ?? []; }, url, postParams); } - Future calculateAbsenceDuration(int pAbsenceAttendanceTypeID, String pDateStart, String pDateEnd, int pSelectedResopID) 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, @@ -49,16 +55,22 @@ class LeaveBalanceApiClient { "P_TIME_START": null, }; 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.calculateAbsenceDuration!; }, url, postParams); } - Future> getAbsenceDffStructure(String pDescFlexContextCode, String pFunctionName, int pSelectedResopID) 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}; 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.getAbsenceDffStructureList ?? []; @@ -67,7 +79,7 @@ class LeaveBalanceApiClient { Future validateAbsenceTransaction( String pDescFlexContextCode, String pFunctionName, int pAbsenceAttendanceTypeID, String pReplacementUserName, String pDateStart, String pDateEnd, int pSelectedResopID, Map data, - {String comments = ""}) async { + {String comments = "", String? empID}) async { String url = "${ApiConsts.erpRest}VALIDATE_ABSENCE_TRANSACTION"; Map postParams = { "P_DESC_FLEX_CONTEXT_CODE": pDescFlexContextCode, @@ -86,6 +98,9 @@ class LeaveBalanceApiClient { }; postParams.addAll(data); 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; @@ -94,7 +109,7 @@ class LeaveBalanceApiClient { Future submitAbsenceTransaction( String pDescFlexContextCode, String pFunctionName, int pAbsenceAttendanceTypeID, String pReplacementUserName, String pDateStart, String pDateEnd, int pSelectedResopID, Map data, - {String comments = ""}) async { + {String comments = "", String? empID}) async { String url = "${ApiConsts.erpRest}SUBMIT_ABSENCE_TRANSACTION"; Map postParams = { "P_DESC_FLEX_CONTEXT_CODE": pDescFlexContextCode, @@ -113,6 +128,9 @@ class LeaveBalanceApiClient { }; postParams.addAll(data); 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.sumbitAbsenceTransactionList!; @@ -129,7 +147,7 @@ class LeaveBalanceApiClient { }, url, postParams); } - Future startAbsenceApprovalProcess(int pTransactionID, String comments, int pSelectedResopID) 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, @@ -138,6 +156,9 @@ class LeaveBalanceApiClient { "P_MENU_TYPE": "E", }; 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/classes/consts.dart b/lib/classes/consts.dart index c5788f9..ede22e3 100644 --- a/lib/classes/consts.dart +++ b/lib/classes/consts.dart @@ -1,7 +1,7 @@ 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://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 85337aa..b2b2843 100644 --- a/lib/ui/leave_balance/add_leave_balance_screen.dart +++ b/lib/ui/leave_balance/add_leave_balance_screen.dart @@ -4,6 +4,7 @@ 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'; @@ -24,7 +25,8 @@ 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 { - AddLeaveBalanceScreen({Key? key}) : super(key: key); + final String selectedEmp; + AddLeaveBalanceScreen({this.selectedEmp ='',Key? key}) : super(key: key); @override _AddLeaveBalanceScreenState createState() { @@ -43,6 +45,8 @@ class _AddLeaveBalanceScreenState extends State { String comment = ""; ReplacementList? selectedReplacementEmployee; + dynamic dynamicParams; + String selectedEmp =""; DateTime selectedDate = DateTime(DateTime.now().year, DateTime.now().month, DateTime.now().day); @override @@ -54,7 +58,7 @@ class _AddLeaveBalanceScreenState extends State { void getAbsenceAttendanceTypes() async { try { Utils.showLoading(context); - absenceList = await LeaveBalanceApiClient().getAbsenceAttendanceTypes(); + absenceList = await LeaveBalanceApiClient().getAbsenceAttendanceTypes(empID: selectedEmp); Utils.hideLoading(context); setState(() {}); } catch (ex) { @@ -67,7 +71,7 @@ class _AddLeaveBalanceScreenState extends State { try { Utils.showLoading(context); getabsenceDffStructureList.clear(); - getabsenceDffStructureList = await LeaveBalanceApiClient().getAbsenceDffStructure(selectedAbsenceType!.dESCFLEXCONTEXTCODE!, "HR_LOA_SS", -999); + getabsenceDffStructureList = await LeaveBalanceApiClient().getAbsenceDffStructure(selectedAbsenceType!.dESCFLEXCONTEXTCODE!, "HR_LOA_SS", -999, empID: selectedEmp); Utils.hideLoading(context); setState(() {}); } catch (ex) { @@ -80,7 +84,7 @@ class _AddLeaveBalanceScreenState extends State { try { Utils.showLoading(context); CalculateAbsenceDuration duration = await LeaveBalanceApiClient() - .calculateAbsenceDuration(selectedAbsenceType!.aBSENCEATTENDANCETYPEID!, Utils.getMonthNamedFormat(startDateTime!), Utils.getMonthNamedFormat(endDateTime!), -999); + .calculateAbsenceDuration(selectedAbsenceType!.aBSENCEATTENDANCETYPEID!, Utils.getMonthNamedFormat(startDateTime!), Utils.getMonthNamedFormat(endDateTime!), -999, empID: selectedEmp); totalDays = duration.pABSENCEDAYS?.toInt(); Utils.hideLoading(context); @@ -119,7 +123,7 @@ class _AddLeaveBalanceScreenState extends State { DateUtil.getFormattedDate(endDateTime!, "MM/dd/yyyy"), -999, dffDataMap, - comments: comment); + comments: comment,empID: selectedEmp ); SumbitAbsenceTransactionList submit = await LeaveBalanceApiClient().submitAbsenceTransaction( selectedAbsenceType!.dESCFLEXCONTEXTCODE!, @@ -130,7 +134,8 @@ class _AddLeaveBalanceScreenState extends State { DateUtil.getFormattedDate(endDateTime!, "MM/dd/yyyy"), -999, dffDataMap, - comments: comment); + comments: comment, + empID: selectedEmp); Utils.hideLoading(context); @@ -151,6 +156,18 @@ class _AddLeaveBalanceScreenState extends State { @override Widget build(BuildContext context) { + if (dynamicParams == null) { + dynamicParams = ModalRoute + .of(context)! + .settings + .arguments; + if (dynamicParams.isNotEmpty) { + AppState().postParamsJson['P_SELECTED_EMPLOYEE_NUMBER'] = dynamicParams; + selectedEmp =dynamicParams; + getAbsenceAttendanceTypes(); + + } + } return Scaffold( backgroundColor: Colors.white, appBar: AppBarWidget( diff --git a/lib/ui/leave_balance/leave_balance_screen.dart b/lib/ui/leave_balance/leave_balance_screen.dart index 548ca99..1218914 100644 --- a/lib/ui/leave_balance/leave_balance_screen.dart +++ b/lib/ui/leave_balance/leave_balance_screen.dart @@ -1,6 +1,7 @@ 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'; @@ -8,12 +9,14 @@ import 'package:mohem_flutter_app/extensions/int_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/leave_balance/get_absence_transaction_list_model.dart'; +import 'package:mohem_flutter_app/ui/my_attendance/services_menu_list_screen.dart'; import 'package:mohem_flutter_app/widgets/app_bar_widget.dart'; 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 { - LeaveBalance({Key? key}) : super(key: key); + final String selectedEmp; + LeaveBalance({this.selectedEmp ='', Key? key}) : super(key: key); @override _LeaveBalanceState createState() { @@ -25,12 +28,13 @@ class _LeaveBalanceState extends State { List? absenceTransList; DateTime accrualDateTime = DateTime.now(); - + dynamic dynamicParams; + String selectedEmp =""; @override void initState() { super.initState(); - getAbsenceTransactions(); + } @override @@ -39,9 +43,9 @@ class _LeaveBalanceState extends State { } void getAbsenceTransactions() async { - try { + try { Utils.showLoading(context); - absenceTransList = await LeaveBalanceApiClient().getAbsenceTransactions(-999); + absenceTransList = await LeaveBalanceApiClient().getAbsenceTransactions(-999, empID: selectedEmp); Utils.hideLoading(context); setState(() {}); } catch (ex) { @@ -52,6 +56,19 @@ class _LeaveBalanceState extends State { @override Widget build(BuildContext context) { + if (dynamicParams == null) { + dynamicParams = ModalRoute + .of(context)! + .settings + .arguments; + if (dynamicParams.isNotEmpty) { + AppState().postParamsJson['P_SELECTED_EMPLOYEE_NUMBER'] = dynamicParams; + selectedEmp =dynamicParams; + getAbsenceTransactions(); + // setState(() {}); + + } + } return Scaffold( backgroundColor: Colors.white, appBar: AppBarWidget( @@ -62,7 +79,7 @@ class _LeaveBalanceState extends State { physics: const BouncingScrollPhysics(), padding: const EdgeInsets.all(21), children: [ - BalancesDashboardWidget(LocaleKeys.currentLeaveBalance.tr(), true), + BalancesDashboardWidget(LocaleKeys.currentLeaveBalance.tr(), true,), 12.height, absenceTransList == null ? const SizedBox() @@ -111,7 +128,7 @@ class _LeaveBalanceState extends State { ), child: const Icon(Icons.add, color: Colors.white, size: 30), ).onPress(() { - Navigator.pushNamed(context, AppRoutes.addLeaveBalance); + Navigator.pushNamed(context, AppRoutes.addLeaveBalance, arguments: selectedEmp ??''); }), ); } diff --git a/lib/ui/misc/request_submit_screen.dart b/lib/ui/misc/request_submit_screen.dart index f5a2d1e..a12bedb 100644 --- a/lib/ui/misc/request_submit_screen.dart +++ b/lib/ui/misc/request_submit_screen.dart @@ -8,6 +8,7 @@ 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/api/profile_api_client.dart'; import 'package:mohem_flutter_app/api/termination_dff_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'; @@ -48,6 +49,8 @@ class _RequestSubmitScreenState extends State { List approverList = []; List attachmentFiles = []; + dynamic dynamicParams; + String selectedEmp =""; @override void initState() { @@ -121,6 +124,7 @@ class _RequestSubmitScreenState extends State { params!.transactionId, comments.text, -999, + empID: selectedEmp ); } else if (params!.approvalFlag == 'eit') { await MyAttendanceApiClient().startEitApprovalProcess( @@ -155,6 +159,17 @@ class _RequestSubmitScreenState extends State { @override Widget build(BuildContext context) { + if (dynamicParams == null) { + dynamicParams = ModalRoute + .of(context)! + .settings + .arguments; + if (dynamicParams.isNotEmpty) { + AppState().postParamsJson['P_SELECTED_EMPLOYEE_NUMBER'] = dynamicParams; + selectedEmp =dynamicParams; + submitRequest(); + } + } if (params == null) { params = ModalRoute.of(context)!.settings.arguments as RequestSubmitScreenParams; getApproverList(); 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 ad7ad50..6f02be4 100644 --- a/lib/ui/my_attendance/dynamic_screens/dynamic_input_screen.dart +++ b/lib/ui/my_attendance/dynamic_screens/dynamic_input_screen.dart @@ -595,7 +595,9 @@ class _DynamicInputScreenState extends State { ).paddingOnly(bottom: 12), itemBuilder: (_) => >[ if (model.rEADONLY != "Y") - for (int i = 0; i < model.eSERVICESVS!.length; i++) PopupMenuItem(child: Text(model.eSERVICESVS![i].vALUECOLUMNNAME!), value: i), + for (int i = 0; i < model.eSERVICESVS!.length; i++) PopupMenuItem( + padding: EdgeInsets.all(10), + child: Text(model.eSERVICESVS![i].vALUECOLUMNNAME!), value: i), ], onSelected: (int popipIndex) async { ESERVICESDV eservicesdv = ESERVICESDV( diff --git a/lib/ui/my_attendance/services_menu_list_screen.dart b/lib/ui/my_attendance/services_menu_list_screen.dart index cd76132..7a61029 100644 --- a/lib/ui/my_attendance/services_menu_list_screen.dart +++ b/lib/ui/my_attendance/services_menu_list_screen.dart @@ -54,7 +54,7 @@ class ServicesMenuListScreen extends StatelessWidget { } return; } else if (servicesMenuData.list[index].requestType == "ABSENCE") { - Navigator.pushNamed(context, AppRoutes.leaveBalance); + Navigator.pushNamed(context, AppRoutes.leaveBalance, arguments: servicesMenuData?.selectedEmp ??''); return; } if (servicesMenuData.list[index].requestType == "EIT") { diff --git a/lib/ui/my_team/create_request.dart b/lib/ui/my_team/create_request.dart index 53205c9..1637586 100644 --- a/lib/ui/my_team/create_request.dart +++ b/lib/ui/my_team/create_request.dart @@ -69,7 +69,7 @@ class _CreateRequestState extends State { if (menu.menuEntry.menuEntryType == "FUNCTION") { if (menu.menuEntry.requestType == "EIT") { - Navigator.pushNamed(context, AppRoutes.dynamicScreen, arguments: DynamicListViewParams(menu.menuEntry.prompt!, menu.menuEntry.functionName!)); + Navigator.pushNamed(context, AppRoutes.dynamicScreen, arguments: DynamicListViewParams(menu.menuEntry.prompt!, menu.menuEntry.functionName!, selectedEmp: getEmployeeSubordinates?.eMPLOYEENUMBER??'')); } else {} } else { Navigator.pushNamed(context, AppRoutes.servicesMenuListScreen, arguments: ServicesMenuListScreenParams(menu.menuEntry.prompt!, menu.menuEntiesList, selectedEmp: getEmployeeSubordinates?.eMPLOYEENUMBER??'')); diff --git a/lib/widgets/balances_dashboard_widget.dart b/lib/widgets/balances_dashboard_widget.dart index e546acf..e640ff4 100644 --- a/lib/widgets/balances_dashboard_widget.dart +++ b/lib/widgets/balances_dashboard_widget.dart @@ -45,6 +45,8 @@ class _BalancesDashboardWidgetState extends State { late DateTime accrualDateTime; GetAccrualBalancesList? leaveBalanceAccrual; List? ticketBalanceAccrualList; + dynamic dynamicParams; + String selectedEmp =""; @override void initState() { @@ -60,7 +62,7 @@ class _BalancesDashboardWidgetState extends State { void changeAccrualDate() async { try { Utils.showLoading(context); - List accrualList = await DashboardApiClient().getAccrualBalances(DateFormat("MM/dd/yyyy").format(accrualDateTime)); + List accrualList = await DashboardApiClient().getAccrualBalances(DateFormat("MM/dd/yyyy").format(accrualDateTime),empID: selectedEmp); if (accrualList.isNotEmpty) { if (widget.isLeaveBalance) { leaveBalanceAccrual = accrualList[0]; @@ -86,6 +88,17 @@ class _BalancesDashboardWidgetState extends State { @override Widget build(BuildContext context) { + if (dynamicParams == null) { + dynamicParams = ModalRoute + .of(context)! + .settings + .arguments; + if (dynamicParams.isNotEmpty) { + AppState().postParamsJson['P_SELECTED_EMPLOYEE_NUMBER'] = dynamicParams; + selectedEmp =dynamicParams; + changeAccrualDate(); + } + } if (leaveBalanceAccrual == null && widget.isLeaveBalance) { leaveBalanceAccrual = Provider.of(context, listen: false).leaveBalanceAccrual; chartModelList = [ From 0f13ab65d67473fe808482bde87c105c1b65175d Mon Sep 17 00:00:00 2001 From: "Aamir.Muhammad" Date: Mon, 5 Dec 2022 16:02:21 +0300 Subject: [PATCH 19/35] Chat Fixes & User Chat Counter --- lib/provider/dashboard_provider_model.dart | 26 +++---- lib/ui/chat/chat_detailed_screen.dart | 2 +- lib/ui/chat/chat_full_image_preview.dart | 6 +- lib/ui/chat/chat_home_screen.dart | 9 ++- lib/ui/chat/favorite_users_screen.dart | 5 +- lib/widgets/app_bar_widget.dart | 7 -- .../shimmer/dashboard_shimmer_widget.dart | 76 ++++++++++--------- 7 files changed, 64 insertions(+), 67 deletions(-) diff --git a/lib/provider/dashboard_provider_model.dart b/lib/provider/dashboard_provider_model.dart index 461196f..5d6a53e 100644 --- a/lib/provider/dashboard_provider_model.dart +++ b/lib/provider/dashboard_provider_model.dart @@ -307,19 +307,19 @@ class DashboardProviderModel with ChangeNotifier, DiagnosticableTreeMixin { 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; - } + // 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 notify() { diff --git a/lib/ui/chat/chat_detailed_screen.dart b/lib/ui/chat/chat_detailed_screen.dart index 345884f..905bffa 100644 --- a/lib/ui/chat/chat_detailed_screen.dart +++ b/lib/ui/chat/chat_detailed_screen.dart @@ -90,7 +90,7 @@ class _ChatDetailScreenState extends State { body: Consumer( builder: (BuildContext context, ChatProviderModel m, Widget? child) { return (m.isLoading - ? ChatHomeShimmer() + ? ChatHomeShimmer(isDetailedScreen: true,) : Column( children: [ SmartRefresher( diff --git a/lib/ui/chat/chat_full_image_preview.dart b/lib/ui/chat/chat_full_image_preview.dart index c731c25..6c8073f 100644 --- a/lib/ui/chat/chat_full_image_preview.dart +++ b/lib/ui/chat/chat_full_image_preview.dart @@ -21,9 +21,9 @@ class ChatImagePreviewScreen extends StatelessWidget { children: [ Image.memory( img, - fit: BoxFit.cover, - height: 400, - width: double.infinity, + fit: BoxFit.fill, + height:500, + width: 500, ).paddingAll(15), Positioned( right: 0, diff --git a/lib/ui/chat/chat_home_screen.dart b/lib/ui/chat/chat_home_screen.dart index 73c084a..641c13d 100644 --- a/lib/ui/chat/chat_home_screen.dart +++ b/lib/ui/chat/chat_home_screen.dart @@ -21,6 +21,8 @@ import 'package:mohem_flutter_app/widgets/shimmer/dashboard_shimmer_widget.dart' import 'package:provider/provider.dart'; class ChatHomeScreen extends StatefulWidget { + const ChatHomeScreen({Key? key}) : super(key: key); + @override State createState() => _ChatHomeScreenState(); } @@ -48,7 +50,7 @@ class _ChatHomeScreenState extends State { body: Consumer( builder: (BuildContext context, ChatProviderModel m, Widget? child) { return m.isLoading - ? ChatHomeShimmer() + ? ChatHomeShimmer(isDetailedScreen: false,) : Column( children: [ TextField( @@ -84,7 +86,7 @@ class _ChatHomeScreenState extends State { itemCount: m.searchedChats!.length, shrinkWrap: true, physics: const ClampingScrollPhysics(), - padding: EdgeInsets.only(bottom: 80.0), + padding: const EdgeInsets.only(bottom: 80.0), itemBuilder: (BuildContext context, int index) { return SizedBox( height: 55, @@ -96,8 +98,7 @@ class _ChatHomeScreenState extends State { const SizedBox( height: 48, width: 48, - child: Center(child: CircularProgressIndicator()), - ), + ).toShimmer().circle(30), if (m.searchedChats![index].isImageLoaded! && m.searchedChats![index].image != null && m.searchedChats![index].image.isNotEmpty) CircularAvatar( radius: 20, diff --git a/lib/ui/chat/favorite_users_screen.dart b/lib/ui/chat/favorite_users_screen.dart index 8bfcc4a..6034151 100644 --- a/lib/ui/chat/favorite_users_screen.dart +++ b/lib/ui/chat/favorite_users_screen.dart @@ -23,7 +23,7 @@ class ChatFavoriteUsersScreen extends StatelessWidget { body: Consumer( builder: (BuildContext context, ChatProviderModel m, Widget? child) { if (m.isLoading) { - return ChatHomeShimmer(); + return ChatHomeShimmer(isDetailedScreen: false,); } else { return m.favUsersList != null && m.favUsersList.isNotEmpty ? ListView.separated( @@ -41,8 +41,7 @@ class ChatFavoriteUsersScreen extends StatelessWidget { const SizedBox( height: 48, width: 48, - child: Center(child: CircularProgressIndicator()), - ), + ).toShimmer().circle(30), if (m.favUsersList![index].isImageLoaded! && m.favUsersList![index].image != null && m.favUsersList![index].image.isNotEmpty) CircularAvatar( radius: 20, diff --git a/lib/widgets/app_bar_widget.dart b/lib/widgets/app_bar_widget.dart index d18d7e6..29c94d2 100644 --- a/lib/widgets/app_bar_widget.dart +++ b/lib/widgets/app_bar_widget.dart @@ -32,14 +32,7 @@ AppBar AppBarWidget(BuildContext context, width: 40, isImageBase64: true, ), - if (image == null) - SvgPicture.asset( - "assets/images/user.svg", - height: 40, - width: 40, - ), if (image != null) 14.width, - if (image == null) 14.width, title.toText24(color: MyColors.darkTextColor, isBold: true).expanded, ], ), diff --git a/lib/widgets/shimmer/dashboard_shimmer_widget.dart b/lib/widgets/shimmer/dashboard_shimmer_widget.dart index 6fe5a03..fc243f0 100644 --- a/lib/widgets/shimmer/dashboard_shimmer_widget.dart +++ b/lib/widgets/shimmer/dashboard_shimmer_widget.dart @@ -188,7 +188,6 @@ class ServicesMenuShimmer extends StatelessWidget { } } - class MarathonBannerShimmer extends StatelessWidget { const MarathonBannerShimmer({Key? key}) : super(key: key); @@ -236,6 +235,11 @@ class MarathonBannerShimmer extends StatelessWidget { } class ChatHomeShimmer extends StatelessWidget { + bool isDetailedScreen; + + ChatHomeShimmer({Key? key, required this.isDetailedScreen}) : super(key: key); + + @override @override Widget build(BuildContext context) { return Container( @@ -254,42 +258,42 @@ class ChatHomeShimmer extends StatelessWidget { child: Row( crossAxisAlignment: CrossAxisAlignment.start, children: [ - Container( - width: 48.0, - height: 48.0, - decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.all(Radius.circular(40))), - ), - const Padding( - padding: EdgeInsets.symmetric(horizontal: 8.0), - ), - Expanded( - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Container( - width: double.infinity, - height: 8.0, - color: Colors.white, - ), - const Padding( - padding: EdgeInsets.symmetric(vertical: 2.0), - ), - Container( - width: double.infinity, - height: 8.0, - color: Colors.white, - ), - const Padding( - padding: EdgeInsets.symmetric(vertical: 2.0), - ), - Container( - width: 40.0, - height: 8.0, - color: Colors.white, - ), - ], + if (!isDetailedScreen) + Container( + width: 48.0, + height: 48.0, + decoration: const BoxDecoration(color: Colors.white, borderRadius: BorderRadius.all(Radius.circular(40))), + ), + if (!isDetailedScreen) + const Padding( + padding: EdgeInsets.symmetric(horizontal: 8.0), ), - ) + Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Container( + width: double.infinity, + height: 8.0, + color: Colors.white, + ), + const Padding( + padding: EdgeInsets.symmetric(vertical: 2.0), + ), + Container( + width: double.infinity, + height: 8.0, + color: Colors.white, + ), + const Padding( + padding: EdgeInsets.symmetric(vertical: 2.0), + ), + Container( + width: 40.0, + height: 8.0, + color: Colors.white, + ), + ], + ).expanded ], ), ), From 4e961082075831cabb218eebad7aa75569e83372 Mon Sep 17 00:00:00 2001 From: "Aamir.Muhammad" Date: Mon, 5 Dec 2022 16:03:46 +0300 Subject: [PATCH 20/35] Chat Fixes & User Chat Counter --- lib/ui/landing/dashboard_screen.dart | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/lib/ui/landing/dashboard_screen.dart b/lib/ui/landing/dashboard_screen.dart index e1250b4..8c1bdfe 100644 --- a/lib/ui/landing/dashboard_screen.dart +++ b/lib/ui/landing/dashboard_screen.dart @@ -65,10 +65,9 @@ class _DashboardScreenState extends State { hubConnection = await data.getHubConnection(); await hubConnection.start(); hubConnection.onreconnecting(({Exception? error}) { - print("============== Reconnecting ======================"); + print("============== Reconnecting Hub ======================"); data.getUserAutoLoginToken().whenComplete(() { buildHubConnection(); - data.notifyListeners(); }); }); } From e505a9fa8c8ea6da51800ca0d545e91facc6480f Mon Sep 17 00:00:00 2001 From: haroon amjad Date: Mon, 5 Dec 2022 16:25:55 +0300 Subject: [PATCH 21/35] fixes --- lib/classes/date_uitl.dart | 2 +- lib/ui/work_list/worklist_detail_screen.dart | 44 ++++++++++---------- 2 files changed, 24 insertions(+), 22 deletions(-) diff --git a/lib/classes/date_uitl.dart b/lib/classes/date_uitl.dart index ae80080..a1e52d9 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 aaa").parse(date); + return DateFormat("MM/dd/yyyy hh:mm:ss").parse(date); } static DateTime convertSimpleStringDateToDateddMMyyyy(String date) { diff --git a/lib/ui/work_list/worklist_detail_screen.dart b/lib/ui/work_list/worklist_detail_screen.dart index 824edc3..f87db2a 100644 --- a/lib/ui/work_list/worklist_detail_screen.dart +++ b/lib/ui/work_list/worklist_detail_screen.dart @@ -146,7 +146,9 @@ class _WorkListDetailScreenState extends State { getPRNotification(); } - controller.jumpToPage(0); + if(controller.hasClients) { + controller.jumpToPage(0); + } // List dataToFetch = await Future.wait([ // @@ -214,9 +216,9 @@ class _WorkListDetailScreenState extends State { ), child: Row( children: [ - myTab(LocaleKeys.info.tr(), 0), - (workListData!.iTEMTYPE == "HRSSA" || workListData!.iTEMTYPE == "STAMP") ? myTab(LocaleKeys.details.tr(), 1) : myTab(LocaleKeys.request.tr(), 1), - myTab(LocaleKeys.actions.tr(), 2), + (workListData!.iTEMTYPE == "HRSSA" || workListData!.iTEMTYPE == "STAMP") ? myTab(LocaleKeys.details.tr(), 0) : myTab(LocaleKeys.request.tr(), 0), + myTab(LocaleKeys.actions.tr(), 1), + myTab(LocaleKeys.info.tr(), 2), myTab(LocaleKeys.attachments.tr(), 3), ], ), @@ -230,6 +232,23 @@ class _WorkListDetailScreenState extends State { }); }, children: [ + (workListData!.iTEMTYPE == "HRSSA" || workListData!.iTEMTYPE == "STAMP") + ? DetailFragment(workListData, memberInformationListModel) + : RequestFragment( + moNotificationBodyList: getMoNotificationBodyList, + poLinesList: getPoNotificationBody?.pOLines ?? [], + itemCreationLines: getItemCreationNtfBody?.itemCreationLines ?? [], + prLinesList: getPrNotificationBody?.pRLines ?? [], + ), + isActionHistoryLoaded + ? actionHistoryList.isEmpty + ? Utils.getNoDataWidget(context) + : ActionsFragment( + workListData!.nOTIFICATIONID, + actionHistoryList, + voidCallback: reloadWorkList, + ) + : showLoadingAnimation(), InfoFragment( poHeaderList: getPoNotificationBody?.pOHeader ?? [], workListData: workListData, @@ -243,23 +262,6 @@ class _WorkListDetailScreenState extends State { getContactNotificationBodyList: getContactNotificationBodyList, getPrNotificationBodyList: getPrNotificationBody, ), - (workListData!.iTEMTYPE == "HRSSA" || workListData!.iTEMTYPE == "STAMP") - ? DetailFragment(workListData, memberInformationListModel) - : RequestFragment( - moNotificationBodyList: getMoNotificationBodyList, - poLinesList: getPoNotificationBody?.pOLines ?? [], - itemCreationLines: getItemCreationNtfBody?.itemCreationLines ?? [], - prLinesList: getPrNotificationBody?.pRLines ?? [], - ), - isActionHistoryLoaded - ? actionHistoryList.isEmpty - ? Utils.getNoDataWidget(context) - : ActionsFragment( - workListData!.nOTIFICATIONID, - actionHistoryList, - voidCallback: reloadWorkList, - ) - : showLoadingAnimation(), isAttachmentLoaded ? getAttachmentList.isEmpty ? Utils.getNoDataWidget(context) From 62acd531b044cbf8b007fe61714242268156db39 Mon Sep 17 00:00:00 2001 From: haroon amjad Date: Tue, 6 Dec 2022 09:37:29 +0300 Subject: [PATCH 22/35] fixes --- .../items_for_sale_api_client.dart | 35 ++++++++++++++++++ lib/ui/work_list/worklist_detail_screen.dart | 37 ++++++++++--------- lib/widgets/app_bar_widget.dart | 2 +- 3 files changed, 55 insertions(+), 19 deletions(-) diff --git a/lib/api/items_for_sale/items_for_sale_api_client.dart b/lib/api/items_for_sale/items_for_sale_api_client.dart index 436ae6e..eae6ffb 100644 --- a/lib/api/items_for_sale/items_for_sale_api_client.dart +++ b/lib/api/items_for_sale/items_for_sale_api_client.dart @@ -66,6 +66,41 @@ class ItemsForSaleApiClient { }, url, postParams); } + Future updateItemsForSale(int itemSaleID) async { + List getItemsForSaleList = []; + + String url = "${ApiConsts.cocRest}Mohemm_ITG_UpdateItemForSale"; + + // request.fields['itemSaleID'] = itemSaleID.toString(); + // request.fields['Channel'] = "31"; + // request.fields['isActive'] = "false"; + // request.fields['LogInToken'] = loginTokenID!; + // request.fields['Token'] = tokenID!; + // request.fields['MobileNo'] = empMobNum!; + // request.fields['EmployeeNumber'] = empNum!; + // request.fields['employeeNumber'] = empNum; + + Map postParams = { + "EmployeeNumber": AppState().memberInformationList?.eMPLOYEENUMBER, + "employeeNumber": AppState().memberInformationList?.eMPLOYEENUMBER, + "MobileNo": AppState().memberInformationList?.eMPLOYEEMOBILENUMBER, + "itemSaleID": itemSaleID.toString(), + "Channel": "31", + "isActive": "false", + "Token": AppState().postParamsObject?.tokenID + }; + + postParams.addAll(AppState().postParamsJson); + return await ApiClient().postJsonForObject((response) { + var body = json.decode(response['Mohemm_ITG_ResponseItem']); + + // body['result']['data'].forEach((v) { + // getItemsForSaleList.add(new GetItemsForSaleList.fromJson(v)); + // }); + return getItemsForSaleList; + }, url, postParams); + } + Future> getEmployeePostedAds() async { List employeePostedAdsList = []; diff --git a/lib/ui/work_list/worklist_detail_screen.dart b/lib/ui/work_list/worklist_detail_screen.dart index 96bd09f..3f5655e 100644 --- a/lib/ui/work_list/worklist_detail_screen.dart +++ b/lib/ui/work_list/worklist_detail_screen.dart @@ -146,7 +146,7 @@ class _WorkListDetailScreenState extends State { getPRNotification(); } - if(controller.hasClients) { + if (controller.hasClients) { controller.jumpToPage(0); } @@ -210,6 +210,7 @@ class _WorkListDetailScreenState extends State { ); }, child: Stack( + key: ValueKey(AppState().workListIndex ?? 0), children: [ Column( children: [ @@ -251,19 +252,19 @@ class _WorkListDetailScreenState extends State { (workListData!.iTEMTYPE == "HRSSA" || workListData!.iTEMTYPE == "STAMP") ? DetailFragment(workListData, memberInformationListModel) : RequestFragment( - moNotificationBodyList: getMoNotificationBodyList, - poLinesList: getPoNotificationBody?.pOLines ?? [], - itemCreationLines: getItemCreationNtfBody?.itemCreationLines ?? [], - prLinesList: getPrNotificationBody?.pRLines ?? [], - ), + moNotificationBodyList: getMoNotificationBodyList, + poLinesList: getPoNotificationBody?.pOLines ?? [], + itemCreationLines: getItemCreationNtfBody?.itemCreationLines ?? [], + prLinesList: getPrNotificationBody?.pRLines ?? [], + ), isActionHistoryLoaded ? actionHistoryList.isEmpty - ? Utils.getNoDataWidget(context) - : ActionsFragment( - workListData!.nOTIFICATIONID, - actionHistoryList, - voidCallback: reloadWorkList, - ) + ? Utils.getNoDataWidget(context) + : ActionsFragment( + workListData!.nOTIFICATIONID, + actionHistoryList, + voidCallback: reloadWorkList, + ) : showLoadingAnimation(), InfoFragment( poHeaderList: getPoNotificationBody?.pOHeader ?? [], @@ -565,7 +566,7 @@ class _WorkListDetailScreenState extends State { Future performNetworkCall(BuildContext context, {String? email, String? userId}) async { showDialog( context: context, - builder: (BuildContext cxt) => ConfirmDialog( + builder: (cxt) => ConfirmDialog( message: LocaleKeys.wantToReject.tr(), okTitle: LocaleKeys.reject.tr(), onTap: () async { @@ -648,12 +649,12 @@ class _WorkListDetailScreenState extends State { print(actionMode); showDialog( context: context, - builder: (BuildContext cxt) => AcceptRejectInputDialog( + builder: (cxt) => AcceptRejectInputDialog( message: title != null ? null : LocaleKeys.requestedItems.tr(), title: title, notificationGetRespond: notificationNoteInput, actionMode: actionMode, - onTap: (String note) { + onTap: (note) { Map payload = { "P_ACTION_MODE": actionMode, "P_APPROVER_INDEX": null, @@ -934,9 +935,9 @@ class _WorkListDetailScreenState extends State { apiCallCount++; notificationButtonsList = await WorkListApiClient().getNotificationButtons(workListData!.nOTIFICATIONID!); if (notificationButtonsList.isNotEmpty) { - isCloseAvailable = notificationButtonsList.any((GetNotificationButtonsList element) => element.bUTTONACTION == "CLOSE"); - isApproveAvailable = notificationButtonsList.any((GetNotificationButtonsList element) => element.bUTTONACTION == "APPROVED"); - isRejectAvailable = notificationButtonsList.any((GetNotificationButtonsList element) => element.bUTTONACTION == "REJECTED"); + isCloseAvailable = notificationButtonsList.any((element) => element.bUTTONACTION == "CLOSE"); + isApproveAvailable = notificationButtonsList.any((element) => element.bUTTONACTION == "APPROVED"); + isRejectAvailable = notificationButtonsList.any((element) => element.bUTTONACTION == "REJECTED"); } apiCallCount--; if (apiCallCount == 0) { diff --git a/lib/widgets/app_bar_widget.dart b/lib/widgets/app_bar_widget.dart index fa59d3a..38cf570 100644 --- a/lib/widgets/app_bar_widget.dart +++ b/lib/widgets/app_bar_widget.dart @@ -20,7 +20,7 @@ AppBar AppBarWidget(BuildContext context, children: [ GestureDetector( behavior: HitTestBehavior.opaque, - onTap: Feedback.wrapForTap(() => Navigator.maybePop(context, true), context), + onTap: Feedback.wrapForTap(() => Navigator.maybePop(context), context), child: const Icon(Icons.arrow_back_ios, color: MyColors.darkIconColor), ), 4.width, From 8d5cc7ed23e5e0e01f32a397ddbbc8fdd22adc9d Mon Sep 17 00:00:00 2001 From: "Aamir.Muhammad" Date: Tue, 6 Dec 2022 09:40:50 +0300 Subject: [PATCH 23/35] Chat Fixes & User Chat Counter --- lib/provider/chat_provider_model.dart | 51 ++++++++++++++++++++++ lib/provider/dashboard_provider_model.dart | 34 --------------- lib/ui/chat/chat_detailed_screen.dart | 6 ++- lib/ui/chat/chat_full_image_preview.dart | 4 +- lib/ui/landing/dashboard_screen.dart | 24 +++++----- 5 files changed, 66 insertions(+), 53 deletions(-) diff --git a/lib/provider/chat_provider_model.dart b/lib/provider/chat_provider_model.dart index 385c64a..b045bbb 100644 --- a/lib/provider/chat_provider_model.dart +++ b/lib/provider/chat_provider_model.dart @@ -7,15 +7,19 @@ import 'package:flutter/foundation.dart'; import 'package:http/http.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/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_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'; +import 'package:mohem_flutter_app/models/chat/get_user_login_token_model.dart' as userLoginToken; 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:signalr_netcore/hub_connection.dart'; +import 'package:signalr_netcore/signalr_client.dart'; import 'package:uuid/uuid.dart'; class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { @@ -35,6 +39,41 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { List favUsersList = []; int paginationVal = 0; + Future getUserAutoLoginToken() async { + userLoginToken.UserAutoLoginModel userLoginResponse = await ChatApiClient().getUserLoginToken(); + if (userLoginResponse.response != null) { + AppState().setchatUserDetails = userLoginResponse; + } else { + Utils.showToast( + userLoginResponse.errorResponses!.first.fieldName.toString() + " Erorr", + ); + } + } + + Future buildHubConnection() async { + hubConnection = await getHubConnection(); + await hubConnection.start()!.then((value) { + print('-----------------------Hub Started For Chat------------------'); + }); + } + + 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() { hubConnection.on("OnUpdateUserStatusAsync", changeStatus); hubConnection.on("OnDeliveredChatUserAsync", onMsgReceived); @@ -47,6 +86,13 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { } void getUserRecentChats() async { + if (hubConnection.state != HubConnectionState.Connected) { + getUserAutoLoginToken().whenComplete(() async { + await buildHubConnection(); + getUserRecentChats(); + }); + return; + } ChatUserModel recentChat = await ChatApiClient().getRecentChats(); ChatUserModel favUList = await ChatApiClient().getFavUsers(); @@ -686,4 +732,9 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { } notifyListeners(); } + + ///getUserAutoLoginToken().whenComplete(() { +// buildHubConnection(); +// print("After Reconnect State: " + hubConnection.state.toString()); +// }); } diff --git a/lib/provider/dashboard_provider_model.dart b/lib/provider/dashboard_provider_model.dart index 5d6a53e..48531b7 100644 --- a/lib/provider/dashboard_provider_model.dart +++ b/lib/provider/dashboard_provider_model.dart @@ -1,17 +1,13 @@ import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; -import 'package:mohem_flutter_app/api/chat/chat_api_client.dart'; import 'package:mohem_flutter_app/api/dashboard_api_client.dart'; import 'package:mohem_flutter_app/api/offers_and_discounts_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/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/chat/get_user_login_token_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'; @@ -25,7 +21,6 @@ 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/widgets/dialogs/confirm_dialog.dart'; -import 'package:signalr_netcore/signalr_client.dart'; /// Mix-in [DiagnosticableTreeMixin] to have access to [debugFillProperties] for the devtool // ignore: prefer_mixin @@ -42,7 +37,6 @@ class DashboardProviderModel with ChangeNotifier, DiagnosticableTreeMixin { //Chat bool isChatCounterLoding = true; - bool isChatHubLoding = true; int chatUConvCounter = 0; //Misssing Swipe @@ -103,7 +97,6 @@ class DashboardProviderModel with ChangeNotifier, DiagnosticableTreeMixin { leaveBalanceAccrual = null; isChatCounterLoding = true; - isChatHubLoding = true; chatUConvCounter = 0; ticketBalance = 0; @@ -294,33 +287,6 @@ class DashboardProviderModel with ChangeNotifier, DiagnosticableTreeMixin { } } - Future getUserAutoLoginToken() async { - UserAutoLoginModel userLoginResponse = await ChatApiClient().getUserLoginToken(); - if (userLoginResponse.response != null) { - AppState().setchatUserDetails = userLoginResponse; - } else { - Utils.showToast( - userLoginResponse.errorResponses!.first.fieldName.toString() + " Erorr", - ); - } - } - - 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 notify() { notifyListeners(); diff --git a/lib/ui/chat/chat_detailed_screen.dart b/lib/ui/chat/chat_detailed_screen.dart index 905bffa..f027915 100644 --- a/lib/ui/chat/chat_detailed_screen.dart +++ b/lib/ui/chat/chat_detailed_screen.dart @@ -75,7 +75,7 @@ class _ChatDetailScreenState extends State { context, title: userDetails["targetUser"].userName.toString().replaceAll(".", " ").capitalizeFirstofEach, showHomeButton: false, - image: userDetails["targetUser"].image.isEmpty ? null : userDetails["targetUser"].image, + image: userDetails["targetUser"].image == null || userDetails["targetUser"].image.isEmpty ? null : userDetails["targetUser"].image, actions: [ SvgPicture.asset("assets/icons/chat/call.svg", width: 21, height: 23).onPress(() { // makeCall(callType: "AUDIO", con: hubConnection); @@ -90,7 +90,9 @@ class _ChatDetailScreenState extends State { body: Consumer( builder: (BuildContext context, ChatProviderModel m, Widget? child) { return (m.isLoading - ? ChatHomeShimmer(isDetailedScreen: true,) + ? ChatHomeShimmer( + isDetailedScreen: true, + ) : Column( children: [ SmartRefresher( diff --git a/lib/ui/chat/chat_full_image_preview.dart b/lib/ui/chat/chat_full_image_preview.dart index 6c8073f..32e2760 100644 --- a/lib/ui/chat/chat_full_image_preview.dart +++ b/lib/ui/chat/chat_full_image_preview.dart @@ -18,12 +18,10 @@ class ChatImagePreviewScreen extends StatelessWidget { child: Stack( alignment: Alignment.center, fit: StackFit.loose, - children: [ + children: [ Image.memory( img, fit: BoxFit.fill, - height:500, - width: 500, ).paddingAll(15), Positioned( right: 0, diff --git a/lib/ui/landing/dashboard_screen.dart b/lib/ui/landing/dashboard_screen.dart index 8c1bdfe..f15b36e 100644 --- a/lib/ui/landing/dashboard_screen.dart +++ b/lib/ui/landing/dashboard_screen.dart @@ -16,6 +16,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/offers_and_discounts/get_offers_list.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/landing/widget/app_drawer.dart'; import 'package:mohem_flutter_app/ui/landing/widget/menus_widget.dart'; @@ -44,6 +45,7 @@ class DashboardScreen extends StatefulWidget { class _DashboardScreenState extends State { late DashboardProviderModel data; late MarathonProvider marathonProvider; + late ChatProviderModel cProvider; final GlobalKey _scaffoldState = GlobalKey(); final RefreshController _refreshController = RefreshController(initialRefresh: false); @@ -56,22 +58,12 @@ class _DashboardScreenState extends State { scheduleMicrotask(() { data = Provider.of(context, listen: false); marathonProvider = Provider.of(context, listen: false); + cProvider = Provider.of(context, listen: false); _bHubCon(); _onRefresh(); }); } - void buildHubConnection() async { - hubConnection = await data.getHubConnection(); - await hubConnection.start(); - hubConnection.onreconnecting(({Exception? error}) { - print("============== Reconnecting Hub ======================"); - data.getUserAutoLoginToken().whenComplete(() { - buildHubConnection(); - }); - }); - } - @override void dispose() { super.dispose(); @@ -79,8 +71,8 @@ class _DashboardScreenState extends State { } void _bHubCon() { - data.getUserAutoLoginToken().whenComplete(() { - buildHubConnection(); + cProvider.getUserAutoLoginToken().whenComplete(() { + cProvider.buildHubConnection(); }); } @@ -187,7 +179,11 @@ class _DashboardScreenState extends State { "assets/images/announcements.svg", matchTextDirection: true, ).onPress(() async { - await Navigator.pushNamed(context, AppRoutes.announcements); + /// await Navigator.pushNamed(context, AppRoutes.announcements); + hubConnection.stop().then((value) { + print("----------- Stoppped ----------"); + print(hubConnection.state); + }); }) ], ).paddingOnly(left: 21, right: 21, top: 48, bottom: 7), From abc586b81e7cb9a1917e55dbea5cce8599761346 Mon Sep 17 00:00:00 2001 From: "Aamir.Muhammad" Date: Tue, 6 Dec 2022 09:41:10 +0300 Subject: [PATCH 24/35] Chat Fixes & User Chat Counter --- lib/ui/landing/dashboard_screen.dart | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/lib/ui/landing/dashboard_screen.dart b/lib/ui/landing/dashboard_screen.dart index f15b36e..8c1291a 100644 --- a/lib/ui/landing/dashboard_screen.dart +++ b/lib/ui/landing/dashboard_screen.dart @@ -179,11 +179,7 @@ class _DashboardScreenState extends State { "assets/images/announcements.svg", matchTextDirection: true, ).onPress(() async { - /// await Navigator.pushNamed(context, AppRoutes.announcements); - hubConnection.stop().then((value) { - print("----------- Stoppped ----------"); - print(hubConnection.state); - }); + await Navigator.pushNamed(context, AppRoutes.announcements); }) ], ).paddingOnly(left: 21, right: 21, top: 48, bottom: 7), From 31fba1f8e64550d0066df341cfecabc74c15468c Mon Sep 17 00:00:00 2001 From: "mirza.shafique" Date: Tue, 6 Dec 2022 09:58:55 +0300 Subject: [PATCH 25/35] worklist animation fix --- lib/ui/work_list/itg_detail_screen.dart | 291 ++++++++++--------- lib/ui/work_list/worklist_detail_screen.dart | 7 +- lib/widgets/app_bar_widget.dart | 2 +- 3 files changed, 164 insertions(+), 136 deletions(-) diff --git a/lib/ui/work_list/itg_detail_screen.dart b/lib/ui/work_list/itg_detail_screen.dart index cf33648..e123d22 100644 --- a/lib/ui/work_list/itg_detail_screen.dart +++ b/lib/ui/work_list/itg_detail_screen.dart @@ -35,6 +35,7 @@ class ItgDetailScreen extends StatefulWidget { class _ItgDetailScreenState extends State { int tabIndex = 0; + int animationIndex = 0; PageController controller = PageController(); bool showFabOptions = false; @@ -82,6 +83,7 @@ class _ItgDetailScreenState extends State { void getDataFromState() { if (requestDetails == null) { + animationIndex = animationIndex + 1; requestDetails = AppState().requestAllList![AppState().itgWorkListIndex!]; // ModalRoute.of(context)!.settings.arguments as WorkListResponseModel; providerData.itgFormsModel!.totalCount = providerData.itgFormsModel!.totalCount! - 1; getItgData(); @@ -95,151 +97,170 @@ class _ItgDetailScreenState extends State { return Scaffold( appBar: AppBarWidget(context, title: LocaleKeys.details.tr()), backgroundColor: Colors.white, - body: Stack( - children: [ - Column( - children: [ - Container( - padding: const EdgeInsets.only(left: 21, right: 21, top: 16, bottom: 16), - decoration: const BoxDecoration( - borderRadius: BorderRadius.only( - bottomLeft: Radius.circular(25), - bottomRight: Radius.circular(25), + body: AnimatedSwitcher( + duration: const Duration(milliseconds: 500), + switchInCurve: Curves.easeInToLinear, + transitionBuilder: (Widget child, Animation animation) { + Animation custom = Tween( + begin: const Offset(1.0, 0.0), + end: Offset.zero, + ).animate(animation); + return ClipRect( + child: SlideTransition( + position: custom, + child: child, + // textDirection: TextDirection.ltr, + ), + ); + }, + child: Stack( + key: ValueKey(animationIndex), + children: [ + Column( + children: [ + Container( + padding: const EdgeInsets.only(left: 21, right: 21, top: 16, bottom: 16), + decoration: const BoxDecoration( + borderRadius: BorderRadius.only( + bottomLeft: Radius.circular(25), + bottomRight: Radius.circular(25), + ), + gradient: LinearGradient( + transform: GradientRotation(.83), + begin: Alignment.topRight, + end: Alignment.bottomLeft, + colors: [ + MyColors.gradiantEndColor, + MyColors.gradiantStartColor, + ], + ), ), - gradient: LinearGradient( - transform: GradientRotation(.83), - begin: Alignment.topRight, - end: Alignment.bottomLeft, - colors: [ - MyColors.gradiantEndColor, - MyColors.gradiantStartColor, + child: Row( + children: [ + myTab(LocaleKeys.requestDetails.tr(), 0), + myTab(LocaleKeys.approvalLevel.tr(), 1), + myTab(LocaleKeys.requesterDetails.tr(), 2), ], ), ), - child: Row( + PageView( + controller: controller, + onPageChanged: (pageIndex) { + setState(() { + tabIndex = pageIndex; + }); + }, children: [ - myTab(LocaleKeys.requestDetails.tr(), 0), - myTab(LocaleKeys.approvalLevel.tr(), 1), - myTab(LocaleKeys.requesterDetails.tr(), 2), + RequestDetailFragment(fields: itgRequest?.fieldGoups?[1].fields ?? []), + ApprovalLevelfragment( + wFHistory: itgRequest?.wFHistory ?? [], + voidCallback: reloadITG, + ), + RequestDetailFragment(fields: itgRequest?.fieldGoups?[0].fields ?? []), ], - ), - ), - PageView( - controller: controller, - onPageChanged: (pageIndex) { - setState(() { - tabIndex = pageIndex; - }); - }, - children: [ - RequestDetailFragment(fields: itgRequest?.fieldGoups?[1].fields ?? []), - ApprovalLevelfragment( - wFHistory: itgRequest?.wFHistory ?? [], - voidCallback: reloadITG, - ), - RequestDetailFragment(fields: itgRequest?.fieldGoups?[0].fields ?? []), - ], - ).expanded, - if (isApproveAvailable || isRejectAvailable || isCloseAvailable) - Container( - padding: const EdgeInsets.only(top: 14, bottom: 14, left: 21, right: 21), - decoration: const BoxDecoration( - color: Colors.white, - border: Border( - top: BorderSide( - color: MyColors.lightGreyEFColor, - width: 1.0, + ).expanded, + if (isApproveAvailable || isRejectAvailable || isCloseAvailable) + Container( + padding: const EdgeInsets.only(top: 14, bottom: 14, left: 21, right: 21), + decoration: const BoxDecoration( + color: Colors.white, + border: Border( + top: BorderSide( + color: MyColors.lightGreyEFColor, + width: 1.0, + ), ), ), - ), - child: Row( + child: Row( + children: [ + if (isRejectAvailable) + DefaultButton( + LocaleKeys.reject.tr(), + () => performAction("REJECTED"), + colors: const [ + Color(0xffE47A7E), + Color(0xffDE6D71), + ], + ).expanded, + if (isApproveAvailable && isRejectAvailable) 8.width, + if (isApproveAvailable) + DefaultButton( + LocaleKeys.approve.tr(), + () => performAction("APPROVED"), + colors: const [ + Color(0xff28C884), + Color(0xff1BB271), + ], + ).expanded, + if (isCloseAvailable) + DefaultButton( + LocaleKeys.ok.tr(), + () => performAction("CLOSE"), + colors: const [ + Color(0xff32D892), + Color(0xff1AB170), + ], + ).expanded, + 8.width, + Container( + height: 43, + width: 43, + decoration: const BoxDecoration( + shape: BoxShape.circle, + color: MyColors.lightGreyE6Color, + ), + child: Icon(showFabOptions ? Icons.more_vert_rounded : Icons.more_horiz_rounded, color: MyColors.darkIconColor), + ).onPress(() { + setState(() { + showFabOptions = true; + }); + }) + ], + ), + ) + ], + ), + IgnorePointer( + ignoring: !showFabOptions, + child: AnimatedOpacity( + opacity: showFabOptions ? 1 : 0, + duration: const Duration(milliseconds: 250), + child: Container( + padding: const EdgeInsets.only(left: 21, right: 21, bottom: 75 - 12), + width: double.infinity, + height: double.infinity, + color: Colors.white.withOpacity(.67), + alignment: Alignment.bottomRight, + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.end, children: [ - if (isRejectAvailable) - DefaultButton( - LocaleKeys.reject.tr(), - () => performAction("REJECTED"), - colors: const [ - Color(0xffE47A7E), - Color(0xffDE6D71), - ], - ).expanded, - if (isApproveAvailable && isRejectAvailable) 8.width, - if (isApproveAvailable) - DefaultButton( - LocaleKeys.approve.tr(), - () => performAction("APPROVED"), - colors: const [ - Color(0xff28C884), - Color(0xff1BB271), - ], - ).expanded, - if (isCloseAvailable) - DefaultButton( - LocaleKeys.ok.tr(), - () => performAction("CLOSE"), - colors: const [ - Color(0xff32D892), - Color(0xff1AB170), - ], - ).expanded, - 8.width, - Container( - height: 43, - width: 43, - decoration: const BoxDecoration( - shape: BoxShape.circle, - color: MyColors.lightGreyE6Color, - ), - child: Icon(showFabOptions ? Icons.more_vert_rounded : Icons.more_horiz_rounded, color: MyColors.darkIconColor), - ).onPress(() { - setState(() { - showFabOptions = true; - }); - }) + myFab(LocaleKeys.skip.tr(), "assets/images/skip.svg").onPress(() { + if (AppState().requestAllList!.length - 1 > AppState().itgWorkListIndex!) { + animationIndex = animationIndex + 1; + AppState().itgWorkListIndex = AppState().itgWorkListIndex! + 1; + requestDetails = null; + itgRequest = null; + tabIndex = 0; + showFabOptions = false; + getDataFromState(); + } else if (AppState().requestAllList!.length - 1 == AppState().itgWorkListIndex!) { + Navigator.pop(context); + } + }), + 12.height, + ...viewApiButtonsList(allowedActionList), ], ), - ) - ], - ), - IgnorePointer( - ignoring: !showFabOptions, - child: AnimatedOpacity( - opacity: showFabOptions ? 1 : 0, - duration: const Duration(milliseconds: 250), - child: Container( - padding: const EdgeInsets.only(left: 21, right: 21, bottom: 75 - 12), - width: double.infinity, - height: double.infinity, - color: Colors.white.withOpacity(.67), - alignment: Alignment.bottomRight, - child: Column( - mainAxisSize: MainAxisSize.min, - crossAxisAlignment: CrossAxisAlignment.end, - children: [ - myFab(LocaleKeys.skip.tr(), "assets/images/skip.svg").onPress(() { - if (AppState().requestAllList!.length - 1 > AppState().itgWorkListIndex!) { - AppState().itgWorkListIndex = AppState().itgWorkListIndex! + 1; - requestDetails = null; - itgRequest = null; - tabIndex = 0; - showFabOptions = false; - getDataFromState(); - } else if (AppState().requestAllList!.length - 1 == AppState().itgWorkListIndex!) { - Navigator.pop(context); - } - }), - 12.height, - ...viewApiButtonsList(allowedActionList), - ], ), - ), - ).onPress(() { - setState(() { - showFabOptions = false; - }); - }), - ), - ], + ).onPress(() { + setState(() { + showFabOptions = false; + }); + }), + ), + ], + ), ), floatingActionButton: (!isApproveAvailable && !isRejectAvailable && !isCloseAvailable) ? Container( @@ -514,6 +535,7 @@ class _ItgDetailScreenState extends State { Utils.hideLoading(context); Utils.showToast(LocaleKeys.yourChangeHasBeenSavedSuccessfully.tr()); // Navigator.pop(context, "delegate_reload"); + animationIndex=animationIndex+1; AppState().requestAllList!.removeAt(AppState().itgWorkListIndex!); if (AppState().requestAllList!.isEmpty) { Navigator.pop(context, "delegate_reload"); @@ -534,9 +556,11 @@ class _ItgDetailScreenState extends State { void performDataCorrectionORReportGeneratedAction(String requestType, int taskId, int itemId, String employeeNumber) async { try { Utils.showLoading(context); + animationIndex = animationIndex + 1; ITGRequest? itgRequest = await WorkListApiClient().grantITGRequest(requestType, taskId, itemId, employeeNumber, "", ""); Utils.hideLoading(context); Utils.showToast(LocaleKeys.yourChangeHasBeenSavedSuccessfully.tr()); + AppState().requestAllList!.removeAt(AppState().itgWorkListIndex!); if (AppState().requestAllList!.isEmpty) { Navigator.pop(context, "delegate_reload"); @@ -555,6 +579,7 @@ class _ItgDetailScreenState extends State { } void reloadITG() { + animationIndex = animationIndex + 1; AppState().requestAllList!.removeAt(AppState().itgWorkListIndex!); if (AppState().requestAllList!.isEmpty) { Navigator.pop(context, "delegate_reload"); diff --git a/lib/ui/work_list/worklist_detail_screen.dart b/lib/ui/work_list/worklist_detail_screen.dart index 5d6727c..9ae62fd 100644 --- a/lib/ui/work_list/worklist_detail_screen.dart +++ b/lib/ui/work_list/worklist_detail_screen.dart @@ -55,6 +55,7 @@ class WorkListDetailScreen extends StatefulWidget { class _WorkListDetailScreenState extends State { int tabIndex = 0; + int animationIndex = 0; PageController controller = PageController(); bool showFabOptions = false; @@ -187,7 +188,6 @@ class _WorkListDetailScreenState extends State { @override Widget build(BuildContext context) { getDataFromState(); - return Scaffold( appBar: AppBarWidget(context, title: LocaleKeys.details.tr()), backgroundColor: Colors.white, @@ -208,7 +208,7 @@ class _WorkListDetailScreenState extends State { ); }, child: Stack( - key: ValueKey(AppState().workListIndex ?? 0), + key: ValueKey(animationIndex), children: [ Column( children: [ @@ -350,6 +350,7 @@ class _WorkListDetailScreenState extends State { children: [ myFab(LocaleKeys.skip.tr(), "assets/images/skip.svg").onPress(() { if (AppState().workList!.length - 1 > AppState().workListIndex!) { + animationIndex = animationIndex + 1; AppState().setWorkListIndex = AppState().workListIndex! + 1; workListData = null; showFabOptions = false; @@ -685,6 +686,7 @@ class _WorkListDetailScreenState extends State { GenericResponseModel model = await WorkListApiClient().postNotificationActions(payload); Utils.hideLoading(context); Utils.showToast(LocaleKeys.yourChangeHasBeenSavedSuccessfully.tr()); + animationIndex=animationIndex+1; AppState().workList!.removeAt(AppState().workListIndex!); if (AppState().workList!.isEmpty) { Navigator.pop(context, "delegate_reload"); @@ -703,6 +705,7 @@ class _WorkListDetailScreenState extends State { } void reloadWorkList() { + animationIndex = animationIndex + 1; AppState().workList!.removeAt(AppState().workListIndex!); if (AppState().workList!.isEmpty) { Navigator.pop(context, "delegate_reload"); diff --git a/lib/widgets/app_bar_widget.dart b/lib/widgets/app_bar_widget.dart index fa59d3a..38cf570 100644 --- a/lib/widgets/app_bar_widget.dart +++ b/lib/widgets/app_bar_widget.dart @@ -20,7 +20,7 @@ AppBar AppBarWidget(BuildContext context, children: [ GestureDetector( behavior: HitTestBehavior.opaque, - onTap: Feedback.wrapForTap(() => Navigator.maybePop(context, true), context), + onTap: Feedback.wrapForTap(() => Navigator.maybePop(context), context), child: const Icon(Icons.arrow_back_ios, color: MyColors.darkIconColor), ), 4.width, From 581e6de8976d902f8aed4e2ec2d2ceedb2151164 Mon Sep 17 00:00:00 2001 From: Fatimah Alshammari Date: Tue, 6 Dec 2022 09:59:30 +0300 Subject: [PATCH 26/35] fix issues --- .../dynamic_screens/dynamic_listview_screen.dart | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) 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 5c4053c..a670cbb 100644 --- a/lib/ui/my_attendance/dynamic_screens/dynamic_listview_screen.dart +++ b/lib/ui/my_attendance/dynamic_screens/dynamic_listview_screen.dart @@ -102,8 +102,8 @@ class _DynamicListViewScreenState extends State { itemBuilder: (cxt, int parentIndex) => getEITTransactionList![parentIndex].collectionTransaction!.isEmpty ? const SizedBox() : GridView( - gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2, childAspectRatio: 1.9 / 0.75), - padding: const EdgeInsets.all(12.0), + 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(), From f3ffdc0088ef5b0483ec802dcce59c7ec6f6a8a9 Mon Sep 17 00:00:00 2001 From: haroon amjad Date: Tue, 6 Dec 2022 10:48:27 +0300 Subject: [PATCH 27/35] marathon URL update --- lib/classes/consts.dart | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/classes/consts.dart b/lib/classes/consts.dart index fb506a9..944a29b 100644 --- a/lib/classes/consts.dart +++ b/lib/classes/consts.dart @@ -26,7 +26,7 @@ class ApiConsts { static String chatUserImages = chatServerBaseUrl + "empservice/api/employee/"; //Brain Marathon Constants - static String marathonBaseUrl = "https://18.188.181.12/service/"; + static String marathonBaseUrl = "https://marathoon.com/service/"; static String marathonParticipantLoginUrl = marathonBaseUrl + "api/auth/participantlogin"; static String marathonProjectGetUrl = marathonBaseUrl + "api/Project/Project_Get"; static String marathonUpcomingUrl = marathonBaseUrl + "api/marathon/upcoming/"; From ff7eb2ad6db95da7dda5e0b7063d91bcfea751c0 Mon Sep 17 00:00:00 2001 From: "Aamir.Muhammad" Date: Tue, 6 Dec 2022 10:51:55 +0300 Subject: [PATCH 28/35] Chat Fixes & User Chat Counter --- lib/ui/chat/chat_home.dart | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/lib/ui/chat/chat_home.dart b/lib/ui/chat/chat_home.dart index 0438dc6..df03ba7 100644 --- a/lib/ui/chat/chat_home.dart +++ b/lib/ui/chat/chat_home.dart @@ -8,8 +8,10 @@ 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_home_screen.dart'; import 'package:mohem_flutter_app/ui/chat/favorite_users_screen.dart'; +import 'package:mohem_flutter_app/ui/landing/dashboard_screen.dart'; import 'package:mohem_flutter_app/widgets/app_bar_widget.dart'; import 'package:provider/provider.dart'; +import 'package:signalr_netcore/signalr_client.dart'; class ChatHome extends StatefulWidget { const ChatHome({Key? key}) : super(key: key); @@ -28,6 +30,13 @@ class _ChatHomeState extends State { super.initState(); data = Provider.of(context, listen: false); data.registerEvents(); + if (hubConnection.state != HubConnectionState.Connected) { + data.getUserAutoLoginToken().whenComplete(() async { + await data.buildHubConnection(); + data.getUserRecentChats(); + }); + return; + } if (data.searchedChats == null || data.searchedChats!.isEmpty) { data.getUserRecentChats(); } From e94a8d9a5e86e291132df140d09c40be9d5c702b Mon Sep 17 00:00:00 2001 From: "Aamir.Muhammad" Date: Tue, 6 Dec 2022 10:57:56 +0300 Subject: [PATCH 29/35] Hub Connection Fix --- lib/provider/chat_provider_model.dart | 26 ++++++++++++-------------- lib/ui/chat/chat_home.dart | 2 +- lib/ui/landing/dashboard_screen.dart | 4 ++-- 3 files changed, 15 insertions(+), 17 deletions(-) diff --git a/lib/provider/chat_provider_model.dart b/lib/provider/chat_provider_model.dart index b045bbb..0b522db 100644 --- a/lib/provider/chat_provider_model.dart +++ b/lib/provider/chat_provider_model.dart @@ -51,10 +51,8 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { } Future buildHubConnection() async { - hubConnection = await getHubConnection(); - await hubConnection.start()!.then((value) { - print('-----------------------Hub Started For Chat------------------'); - }); + chatHubConnection = await getHubConnection(); + await chatHubConnection.start(); } Future getHubConnection() async { @@ -75,18 +73,18 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { } void registerEvents() { - hubConnection.on("OnUpdateUserStatusAsync", changeStatus); - hubConnection.on("OnDeliveredChatUserAsync", onMsgReceived); + chatHubConnection.on("OnUpdateUserStatusAsync", changeStatus); + chatHubConnection.on("OnDeliveredChatUserAsync", onMsgReceived); // hubConnection.on("OnSeenChatUserAsync", onChatSeen); //hubConnection.on("OnUserTypingAsync", onUserTyping); - hubConnection.on("OnUserCountAsync", userCountAsync); + chatHubConnection.on("OnUserCountAsync", userCountAsync); // hubConnection.on("OnUpdateUserChatHistoryWindowsAsync", updateChatHistoryWindow); - hubConnection.on("OnGetUserChatHistoryNotDeliveredAsync", chatNotDelivered); - hubConnection.on("OnUpdateUserChatHistoryStatusAsync", updateUserChatStatus); + chatHubConnection.on("OnGetUserChatHistoryNotDeliveredAsync", chatNotDelivered); + chatHubConnection.on("OnUpdateUserChatHistoryStatusAsync", updateUserChatStatus); } void getUserRecentChats() async { - if (hubConnection.state != HubConnectionState.Connected) { + if (chatHubConnection.state != HubConnectionState.Connected) { getUserAutoLoginToken().whenComplete(() async { await buildHubConnection(); getUserRecentChats(); @@ -127,7 +125,7 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { } Future invokeUserChatHistoryNotDeliveredAsync({required int userId}) async { - await hubConnection.invoke("GetUserChatHistoryNotDeliveredAsync", args: [userId]); + await chatHubConnection.invoke("GetUserChatHistoryNotDeliveredAsync", args: [userId]); return ""; } @@ -194,7 +192,7 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { void updateUserChatHistoryStatusAsync(List data) { try { - hubConnection.invoke("UpdateUserChatHistoryStatusAsync", args: [data]); + chatHubConnection.invoke("UpdateUserChatHistoryStatusAsync", args: [data]); } catch (e) { throw e; } @@ -202,7 +200,7 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { void updateUserChatHistoryOnMsg(List data) { try { - hubConnection.invoke("UpdateUserChatHistoryStatusAsync", args: [data]); + chatHubConnection.invoke("UpdateUserChatHistoryStatusAsync", args: [data]); } catch (e) { throw e; } @@ -486,7 +484,7 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { String chatData = '{"contant":"$msg","contantNo":"$contentNo","chatEventId":$chatEventId,"fileTypeId": $fileTypeId,"currentUserId":${AppState().chatDetails!.response!.id},"chatSource":1,"userChatHistoryLineRequestList":[{"isSeen":false,"isDelivered":false,"targetUserId":$targetUserId,"targetUserStatus":1}],"chatReplyId":$chatReplyId,"conversationId":"$chatCID"}'; - await hubConnection.invoke("AddChatUserAsync", args: [json.decode(chatData)]); + await chatHubConnection.invoke("AddChatUserAsync", args: [json.decode(chatData)]); } void sendChatMessage(int targetUserId, String targetUserName, BuildContext context) async { diff --git a/lib/ui/chat/chat_home.dart b/lib/ui/chat/chat_home.dart index df03ba7..4e218e3 100644 --- a/lib/ui/chat/chat_home.dart +++ b/lib/ui/chat/chat_home.dart @@ -30,7 +30,7 @@ class _ChatHomeState extends State { super.initState(); data = Provider.of(context, listen: false); data.registerEvents(); - if (hubConnection.state != HubConnectionState.Connected) { + if (chatHubConnection.state != HubConnectionState.Connected) { data.getUserAutoLoginToken().whenComplete(() async { await data.buildHubConnection(); data.getUserRecentChats(); diff --git a/lib/ui/landing/dashboard_screen.dart b/lib/ui/landing/dashboard_screen.dart index 8c1291a..f06a405 100644 --- a/lib/ui/landing/dashboard_screen.dart +++ b/lib/ui/landing/dashboard_screen.dart @@ -31,7 +31,7 @@ import 'package:provider/provider.dart'; import 'package:pull_to_refresh/pull_to_refresh.dart'; import 'package:signalr_netcore/signalr_client.dart'; -late HubConnection hubConnection; +late HubConnection chatHubConnection; class DashboardScreen extends StatefulWidget { DashboardScreen({Key? key}) : super(key: key); @@ -67,7 +67,7 @@ class _DashboardScreenState extends State { @override void dispose() { super.dispose(); - hubConnection.stop(); + chatHubConnection.stop(); } void _bHubCon() { From a949f15023cf047b16dc4e666411ee293f4dbb58 Mon Sep 17 00:00:00 2001 From: haroon amjad Date: Tue, 6 Dec 2022 11:04:13 +0300 Subject: [PATCH 30/35] fixes --- lib/ui/work_list/worklist_fragments/detail_fragment.dart | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lib/ui/work_list/worklist_fragments/detail_fragment.dart b/lib/ui/work_list/worklist_fragments/detail_fragment.dart index 43b5d7d..03e2272 100644 --- a/lib/ui/work_list/worklist_fragments/detail_fragment.dart +++ b/lib/ui/work_list/worklist_fragments/detail_fragment.dart @@ -46,6 +46,7 @@ class _DetailFragmentState extends State { ], ).objectContainerView(), 12.height, + widget.memberInformationListModel != null ? Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisSize: MainAxisSize.min, @@ -69,7 +70,7 @@ class _DetailFragmentState extends State { isItLast: true, ), ], - ).objectContainerView(), + ).objectContainerView() : Container(), ], ).paddingAll(21), ); From 915a7d208f1342c56672afc6e00fb859589ea2c4 Mon Sep 17 00:00:00 2001 From: haroon amjad Date: Tue, 6 Dec 2022 13:17:16 +0300 Subject: [PATCH 31/35] Jira translation fix --- lib/ui/landing/widget/app_drawer.dart | 44 +++++++++++++-------------- 1 file changed, 22 insertions(+), 22 deletions(-) diff --git a/lib/ui/landing/widget/app_drawer.dart b/lib/ui/landing/widget/app_drawer.dart index ac70035..4160fde 100644 --- a/lib/ui/landing/widget/app_drawer.dart +++ b/lib/ui/landing/widget/app_drawer.dart @@ -69,28 +69,28 @@ class _AppDrawerState extends State { ).expanded ], ).paddingOnly(left: 14, right: 14, top: 21, bottom: 21), - Row( - children: [ - Row( - children: [ - LocaleKeys.english.tr().toText14(color: AppState().isArabic(context) ? null : MyColors.textMixColor).onPress(() { - context.setLocale(const Locale("en", "US")); - postLanguageChange(context); - }), - Container( - width: 1, - color: MyColors.darkWhiteColor, - height: 16, - margin: const EdgeInsets.only(left: 10, right: 10), - ), - LocaleKeys.arabic.tr().toText14(color: !AppState().isArabic(context) ? null : MyColors.textMixColor).onPress(() { - context.setLocale(const Locale("ar", "SA")); - postLanguageChange(context); - }), - ], - ), - ], - ).paddingOnly(left: 14, right: 14, bottom: 14), + // Row( + // children: [ + // Row( + // children: [ + // LocaleKeys.english.tr().toText14(color: AppState().isArabic(context) ? null : MyColors.textMixColor).onPress(() { + // context.setLocale(const Locale("en", "US")); + // postLanguageChange(context); + // }), + // Container( + // width: 1, + // color: MyColors.darkWhiteColor, + // height: 16, + // margin: const EdgeInsets.only(left: 10, right: 10), + // ), + // LocaleKeys.arabic.tr().toText14(color: !AppState().isArabic(context) ? null : MyColors.textMixColor).onPress(() { + // context.setLocale(const Locale("ar", "SA")); + // postLanguageChange(context); + // }), + // ], + // ), + // ], + // ).paddingOnly(left: 14, right: 14, bottom: 14), const Divider( height: 1, thickness: 1, From c500da9a188c3a1a436b4cd1381a8e2c50b68adf Mon Sep 17 00:00:00 2001 From: Sultan khan <> Date: Tue, 6 Dec 2022 14:12:01 +0300 Subject: [PATCH 32/35] bug fix --- lib/api/my_attendance_api_client.dart | 4 +- lib/classes/utils.dart | 11 +++-- .../dynamic_screens/dynamic_input_screen.dart | 46 +++++++++++++++++-- lib/ui/profile/personal_info.dart | 2 +- 4 files changed, 53 insertions(+), 10 deletions(-) diff --git a/lib/api/my_attendance_api_client.dart b/lib/api/my_attendance_api_client.dart index 9bb16a8..5833413 100644 --- a/lib/api/my_attendance_api_client.dart +++ b/lib/api/my_attendance_api_client.dart @@ -70,7 +70,7 @@ class MyAttendanceApiClient { }, url, postParams); } - Future getDefaultValue(String pSegmentName, String pDescFlexContextCode, String pDescFlexName, List> list, String? empID) async { + Future getDefaultValue(String pSegmentName, String pDescFlexContextCode, String pDescFlexName, List> list, {String? empID}) async { String url = "${ApiConsts.erpRest}GET_DEFAULT_VALUE"; Map postParams = { "P_SELECTED_RESP_ID": -999, @@ -82,7 +82,7 @@ class MyAttendanceApiClient { "GetValueSetValuesTBL": list, }; postParams.addAll(AppState().postParamsJson); - if (empID!.isNotEmpty) { + if (empID != null && empID!.isNotEmpty) { postParams['P_SELECTED_EMPLOYEE_NUMBER'] = empID; } return await ApiClient().postJsonForObject((json) { diff --git a/lib/classes/utils.dart b/lib/classes/utils.dart index 7e7e83c..33d9830 100644 --- a/lib/classes/utils.dart +++ b/lib/classes/utils.dart @@ -9,6 +9,7 @@ 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'; @@ -20,6 +21,7 @@ import 'package:mohem_flutter_app/widgets/loading_dialog.dart'; import 'package:nfc_manager/nfc_manager.dart'; import 'package:nfc_manager/platform_tags.dart'; import 'package:shared_preferences/shared_preferences.dart'; + // ignore_for_file: avoid_annotating_with_dynamic class Utils { @@ -289,7 +291,7 @@ class Utils { String formattedDate; if (date.isNotEmpty) { formattedDate = date.split('T')[0]; - if(!formattedDate.contains("00:00:00")) { + if (!formattedDate.contains("00:00:00")) { formattedDate = formattedDate + ' 00:00:00'; } } else { @@ -298,6 +300,10 @@ class Utils { return formattedDate; } + static String formatDateDefault(String date) { + return DateFormat('yyyy-MM-dd').format(DateFormat('dd-MMM-yyyy').parseLoose(date)); + } + static Future selectDate(BuildContext context, DateTime selectedDate) async { if (!Platform.isIOS) { await showCupertinoModalPopup( @@ -326,8 +332,7 @@ class Utils { return selectedDate; } - static void readNFc({required Function(String) onRead}) { - + static void readNFc({required Function(String) onRead}) { NfcManager.instance.startSession(onDiscovered: (NfcTag tag) async { print(tag.data); var f; 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 ad7ad50..1c86eb8 100644 --- a/lib/ui/my_attendance/dynamic_screens/dynamic_input_screen.dart +++ b/lib/ui/my_attendance/dynamic_screens/dynamic_input_screen.dart @@ -50,6 +50,18 @@ class _DynamicInputScreenState extends State { descFlexConTextTitle = genericResponseModel!.pDESCFLEXCONTEXTNAME ?? ""; getEitDffStructureList = genericResponseModel?.getEITDFFStructureList ?? []; //getEitDffStructureList = getEitDffStructureList!.where((element) => element.dISPLAYFLAG != "N").toList(); + if (dynamicParams!.collectionNotificationList != null && dynamicParams!.collectionNotificationList!.isNotEmpty) { + getEitDffStructureList!.forEach((element) { + dynamicParams!.collectionNotificationList!.forEach((element2) { + if (element.sEGMENTNAME == element2.segmentName) { + element.fieldAnswer = element2.varchar2Value; + element.eSERVICESDV ??= ESERVICESDV(); + element.eSERVICESDV!.pIDCOLUMNNAME = element2.varchar2Value; + } + }); + }); + } + Utils.hideLoading(context); setState(() {}); } catch (ex) { @@ -114,15 +126,22 @@ class _DynamicInputScreenState extends State { try { Utils.showLoading(context); for (int i = 0; i < (structureList.cHILDSEGMENTSVSSplited?.length ?? 0); i++) { + List> values = []; String segmentId = structureList.cHILDSEGMENTSVSSplited![i]; if (dESCFLEXCONTEXTCODE.isEmpty) dESCFLEXCONTEXTCODE = structureList.dESCFLEXCONTEXTCODE!; List filteredList = getEitDffStructureList?.where((element) => element.cHILDSEGMENTSVSSplited!.contains(segmentId)).toList() ?? []; - List> values = filteredList + + if (filteredList.isEmpty && structureList.cHILDSEGMENTSVSSplited!.isNotEmpty) { + segmentId = structureList.cHILDSEGMENTSVSSplited![0]; + filteredList = getEitDffStructureList?.where((element) => element.cHILDSEGMENTSVSSplited!.contains(segmentId)).toList() ?? []; + } + values = filteredList .map((e) => GetSetValuesRequestModel( sEGMENTNAME: e.sEGMENTNAME, vALUECOLUMNNAME: e.eSERVICESDV!.pVALUECOLUMNNAME, dESCRIPTION: "", iDCOLUMNNAME: e.eSERVICESDV!.pIDCOLUMNNAME, fLEXVALUESETNAME: e.fLEXVALUESETNAME) .toJson()) .toList(); + List eServicesResponseModel = await MyAttendanceApiClient().getValueSetValues(segmentId, structureList.dESCFLEXCONTEXTCODE!, structureList.dESCFLEXNAME!, values, empID: dynamicParams!.selectedEmp ?? '', parentValue: structureList.eSERVICESDV!.pVALUECOLUMNNAME); List abc = genericResponseModel?.getEITDFFStructureList ?? []; @@ -162,9 +181,28 @@ class _DynamicInputScreenState extends State { List> getSetList = getDefaultValuesIonicLogic(parent); if (getSetList.isNotEmpty) { - ESERVICESDV defaultValue = await MyAttendanceApiClient().getDefaultValue(segmentId, structureList.dESCFLEXCONTEXTCODE!, structureList.dESCFLEXNAME!, getSetList, dynamicParams!.selectedEmp); + ESERVICESDV defaultValue = + await MyAttendanceApiClient().getDefaultValue(segmentId, structureList.dESCFLEXCONTEXTCODE!, structureList.dESCFLEXNAME!, getSetList, empID: dynamicParams!.selectedEmp); int index = getEitDffStructureList!.indexWhere((element) => element.sEGMENTNAME == segmentId); getEitDffStructureList![index].eSERVICESDV = defaultValue; + GetEITDFFStructureList defaultValueCheck = getEitDffStructureList!.where((GetEITDFFStructureList element) => element.sEGMENTNAME == segmentId).toList().first; + + if (defaultValueCheck.cHILDSEGMENTSDVSplited!.isNotEmpty && defaultValueCheck.rEADONLY == 'Y') { + getDefaultValues(defaultValueCheck); + Utils.hideLoading(context); + + // GetEITDFFStructureList? parent = getEitDffStructureList!.firstWhere((element) => element.sEGMENTNAME == segmentId); + // List> getSetList = getDefaultValuesIonicLogic(parent); + // ESERVICESDV defaultValue = await MyAttendanceApiClient().getDefaultValue(segmentId, defaultValueCheck.dESCFLEXCONTEXTCODE!, defaultValueCheck.dESCFLEXNAME!, getSetList); + // 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); + } + } else if (values.isNotEmpty) { + ESERVICESDV defaultValue = await MyAttendanceApiClient().getDefaultValue(segmentId, structureList.dESCFLEXCONTEXTCODE!, structureList.dESCFLEXNAME!, values); + int index = getEitDffStructureList!.indexWhere((element) => element.sEGMENTNAME == segmentId); } } await Future.delayed(const Duration(seconds: 1)); @@ -305,7 +343,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); @@ -324,7 +362,7 @@ class _DynamicInputScreenState extends State { if (getEitDffStructureList![j].rEADONLY != "Y") { var data = getEitDffStructureList![j].eSERVICESDV; - // let x = document.getElementById(getEitDffStructureList![j].aPPLICATIONCOLUMNNAME) as HTMLSelectElement; + //let x = document.getElementById(getEitDffStructureList![j].aPPLICATIONCOLUMNNAME) as HTMLSelectElement; String? text = data?.pIDCOLUMNNAME; //x.options[x.selectedIndex] ? x.options[x.selectedIndex].text : ""; String? val = data?.pVALUECOLUMNNAME; //x.options[x.selectedIndex] ? x.options[x.selectedIndex].value : null; if ((val ?? "").isEmpty && parentsList[i].isRequired == "REQUIRED") { diff --git a/lib/ui/profile/personal_info.dart b/lib/ui/profile/personal_info.dart index b715cdc..79d0995 100644 --- a/lib/ui/profile/personal_info.dart +++ b/lib/ui/profile/personal_info.dart @@ -43,7 +43,7 @@ class PersonalInfo extends StatelessWidget { LocaleKeys.Payroll.tr().toText13(color: MyColors.lightGrayColor), (memberInformationList.pAYROLLNAME ?? "").toText16(), ], - ).objectContainerView(center: false).paddingAll(21), + ).objectContainerView().paddingAll(21), ), ); } From 323741ad069a2eeda7156d78c6ff58f66088ad2f Mon Sep 17 00:00:00 2001 From: haroon amjad Date: Tue, 6 Dec 2022 16:08:35 +0300 Subject: [PATCH 33/35] no message --- lib/api/dashboard_api_client.dart | 5 +- lib/api/leave_balance_api_client.dart | 35 +++----------- .../add_leave_balance_screen.dart | 48 ++++++------------- .../leave_balance/leave_balance_screen.dart | 31 +++--------- lib/ui/misc/request_submit_screen.dart | 18 ------- .../dynamic_screens/dynamic_input_screen.dart | 4 +- .../dynamic_listview_screen.dart | 4 +- .../services_menu_list_screen.dart | 2 +- lib/ui/my_team/create_request.dart | 2 +- lib/widgets/balances_dashboard_widget.dart | 15 +----- 10 files changed, 36 insertions(+), 128 deletions(-) diff --git a/lib/api/dashboard_api_client.dart b/lib/api/dashboard_api_client.dart index 3eab65b..e30af91 100644 --- a/lib/api/dashboard_api_client.dart +++ b/lib/api/dashboard_api_client.dart @@ -65,13 +65,10 @@ class DashboardApiClient { }, url, postParams); } - Future> getAccrualBalances(String effectiveDate, {String? empID}) async { + Future> getAccrualBalances(String effectiveDate) async { String url = "${ApiConsts.erpRest}GET_ACCRUAL_BALANCES"; Map postParams = {"P_EFFECTIVE_DATE": effectiveDate}; 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.getAccrualBalancesList ?? []; diff --git a/lib/api/leave_balance_api_client.dart b/lib/api/leave_balance_api_client.dart index bb3f129..cd577ba 100644 --- a/lib/api/leave_balance_api_client.dart +++ b/lib/api/leave_balance_api_client.dart @@ -17,33 +17,27 @@ class LeaveBalanceApiClient { factory LeaveBalanceApiClient() => _instance; - Future> getAbsenceTransactions(int pSelectedResopID, {String? empID}) async { + Future> getAbsenceTransactions(int pSelectedResopID) 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; - } return await ApiClient().postJsonForObject((json) { GenericResponseModel? responseData = GenericResponseModel.fromJson(json); return responseData.getAbsenceTransactionList ?? []; }, url, postParams); } - Future> getAbsenceAttendanceTypes({String? empID}) async { + Future> getAbsenceAttendanceTypes() async { String url = "${ApiConsts.erpRest}GET_ABSENCE_ATTENDANCE_TYPES"; Map postParams = {}; 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.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) async { String url = "${ApiConsts.erpRest}CALCULATE_ABSENCE_DURATION"; Map postParams = { "P_ABSENCE_ATTENDANCE_TYPE_ID": pAbsenceAttendanceTypeID, @@ -55,22 +49,16 @@ class LeaveBalanceApiClient { "P_TIME_START": null, }; 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.calculateAbsenceDuration!; }, url, postParams); } - Future> getAbsenceDffStructure(String pDescFlexContextCode, String pFunctionName, int pSelectedResopID, {String? empID}) async { + Future> getAbsenceDffStructure(String pDescFlexContextCode, String pFunctionName, int pSelectedResopID) 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}; 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.getAbsenceDffStructureList ?? []; @@ -79,7 +67,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 = ""}) async { String url = "${ApiConsts.erpRest}VALIDATE_ABSENCE_TRANSACTION"; Map postParams = { "P_DESC_FLEX_CONTEXT_CODE": pDescFlexContextCode, @@ -98,9 +86,6 @@ class LeaveBalanceApiClient { }; postParams.addAll(data); 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; @@ -109,7 +94,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 = ""}) async { String url = "${ApiConsts.erpRest}SUBMIT_ABSENCE_TRANSACTION"; Map postParams = { "P_DESC_FLEX_CONTEXT_CODE": pDescFlexContextCode, @@ -128,9 +113,6 @@ class LeaveBalanceApiClient { }; postParams.addAll(data); 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.sumbitAbsenceTransactionList!; @@ -147,7 +129,7 @@ class LeaveBalanceApiClient { }, url, postParams); } - Future startAbsenceApprovalProcess(int pTransactionID, String comments, int pSelectedResopID, {String? empID}) async { + Future startAbsenceApprovalProcess(int pTransactionID, String comments, int pSelectedResopID) async { String url = "${ApiConsts.erpRest}START_ABSENCE_APPROVAL_PROCESS"; Map postParams = { "P_TRANSACTION_ID": pTransactionID, @@ -156,9 +138,6 @@ class LeaveBalanceApiClient { "P_MENU_TYPE": "E", }; 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/ui/leave_balance/add_leave_balance_screen.dart b/lib/ui/leave_balance/add_leave_balance_screen.dart index c879f9c..d1b7d77 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() { @@ -45,8 +43,6 @@ class _AddLeaveBalanceScreenState extends State { String comment = ""; ReplacementList? selectedReplacementEmployee; - dynamic dynamicParams; - String selectedEmp =""; DateTime selectedDate = DateTime(DateTime.now().year, DateTime.now().month, DateTime.now().day); @override @@ -58,7 +54,7 @@ class _AddLeaveBalanceScreenState extends State { void getAbsenceAttendanceTypes() async { try { Utils.showLoading(context); - absenceList = await LeaveBalanceApiClient().getAbsenceAttendanceTypes(empID: selectedEmp); + absenceList = await LeaveBalanceApiClient().getAbsenceAttendanceTypes(); Utils.hideLoading(context); setState(() {}); } catch (ex) { @@ -71,7 +67,7 @@ class _AddLeaveBalanceScreenState extends State { try { Utils.showLoading(context); getabsenceDffStructureList.clear(); - getabsenceDffStructureList = await LeaveBalanceApiClient().getAbsenceDffStructure(selectedAbsenceType!.dESCFLEXCONTEXTCODE!, "HR_LOA_SS", -999, empID: selectedEmp); + getabsenceDffStructureList = await LeaveBalanceApiClient().getAbsenceDffStructure(selectedAbsenceType!.dESCFLEXCONTEXTCODE!, "HR_LOA_SS", -999); Utils.hideLoading(context); setState(() {}); } catch (ex) { @@ -84,7 +80,7 @@ class _AddLeaveBalanceScreenState extends State { try { Utils.showLoading(context); CalculateAbsenceDuration duration = await LeaveBalanceApiClient() - .calculateAbsenceDuration(selectedAbsenceType!.aBSENCEATTENDANCETYPEID!, Utils.getMonthNamedFormat(startDateTime!), Utils.getMonthNamedFormat(endDateTime!), -999, empID: selectedEmp); + .calculateAbsenceDuration(selectedAbsenceType!.aBSENCEATTENDANCETYPEID!, Utils.getMonthNamedFormat(startDateTime!), Utils.getMonthNamedFormat(endDateTime!), -999); totalDays = duration.pABSENCEDAYS?.toInt(); Utils.hideLoading(context); @@ -113,17 +109,16 @@ class _AddLeaveBalanceScreenState extends State { } } } - 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); SumbitAbsenceTransactionList submit = await LeaveBalanceApiClient().submitAbsenceTransaction( selectedAbsenceType!.dESCFLEXCONTEXTCODE!, @@ -134,8 +129,7 @@ class _AddLeaveBalanceScreenState extends State { DateUtil.getFormattedDate(endDateTime!, "MM/dd/yyyy"), -999, dffDataMap, - comments: comment, - empID: selectedEmp); + comments: comment); Utils.hideLoading(context); @@ -158,18 +152,6 @@ class _AddLeaveBalanceScreenState extends State { @override Widget build(BuildContext context) { - if (dynamicParams == null) { - dynamicParams = ModalRoute - .of(context)! - .settings - .arguments; - if (dynamicParams.isNotEmpty) { - AppState().postParamsJson['P_SELECTED_EMPLOYEE_NUMBER'] = dynamicParams; - selectedEmp =dynamicParams; - getAbsenceAttendanceTypes(); - - } - } return Scaffold( backgroundColor: Colors.white, appBar: AppBarWidget( diff --git a/lib/ui/leave_balance/leave_balance_screen.dart b/lib/ui/leave_balance/leave_balance_screen.dart index 1218914..548ca99 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'; @@ -9,14 +8,12 @@ import 'package:mohem_flutter_app/extensions/int_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/leave_balance/get_absence_transaction_list_model.dart'; -import 'package:mohem_flutter_app/ui/my_attendance/services_menu_list_screen.dart'; import 'package:mohem_flutter_app/widgets/app_bar_widget.dart'; 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() { @@ -28,13 +25,12 @@ class _LeaveBalanceState extends State { List? absenceTransList; DateTime accrualDateTime = DateTime.now(); - dynamic dynamicParams; - String selectedEmp =""; + @override void initState() { super.initState(); - + getAbsenceTransactions(); } @override @@ -43,9 +39,9 @@ class _LeaveBalanceState extends State { } void getAbsenceTransactions() async { - try { + try { Utils.showLoading(context); - absenceTransList = await LeaveBalanceApiClient().getAbsenceTransactions(-999, empID: selectedEmp); + absenceTransList = await LeaveBalanceApiClient().getAbsenceTransactions(-999); Utils.hideLoading(context); setState(() {}); } catch (ex) { @@ -56,19 +52,6 @@ class _LeaveBalanceState extends State { @override Widget build(BuildContext context) { - if (dynamicParams == null) { - dynamicParams = ModalRoute - .of(context)! - .settings - .arguments; - if (dynamicParams.isNotEmpty) { - AppState().postParamsJson['P_SELECTED_EMPLOYEE_NUMBER'] = dynamicParams; - selectedEmp =dynamicParams; - getAbsenceTransactions(); - // setState(() {}); - - } - } return Scaffold( backgroundColor: Colors.white, appBar: AppBarWidget( @@ -79,7 +62,7 @@ class _LeaveBalanceState extends State { physics: const BouncingScrollPhysics(), padding: const EdgeInsets.all(21), children: [ - BalancesDashboardWidget(LocaleKeys.currentLeaveBalance.tr(), true,), + BalancesDashboardWidget(LocaleKeys.currentLeaveBalance.tr(), true), 12.height, absenceTransList == null ? const SizedBox() @@ -128,7 +111,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); }), ); } diff --git a/lib/ui/misc/request_submit_screen.dart b/lib/ui/misc/request_submit_screen.dart index 84adf9f..f05bacb 100644 --- a/lib/ui/misc/request_submit_screen.dart +++ b/lib/ui/misc/request_submit_screen.dart @@ -8,7 +8,6 @@ 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/api/profile_api_client.dart'; import 'package:mohem_flutter_app/api/termination_dff_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'; @@ -50,13 +49,8 @@ class _RequestSubmitScreenState extends State { List approverList = []; List attachmentFiles = []; - - dynamic dynamicParams; - String selectedEmp =""; - List attachments = []; - @override void initState() { super.initState(); @@ -129,7 +123,6 @@ class _RequestSubmitScreenState extends State { params!.transactionId, comments.text, -999, - empID: selectedEmp ); } else if (params!.approvalFlag == 'eit') { await MyAttendanceApiClient().startEitApprovalProcess( @@ -164,17 +157,6 @@ class _RequestSubmitScreenState extends State { @override Widget build(BuildContext context) { - if (dynamicParams == null) { - dynamicParams = ModalRoute - .of(context)! - .settings - .arguments; - if (dynamicParams.isNotEmpty) { - AppState().postParamsJson['P_SELECTED_EMPLOYEE_NUMBER'] = dynamicParams; - selectedEmp =dynamicParams; - submitRequest(); - } - } if (params == null) { params = ModalRoute.of(context)!.settings.arguments as RequestSubmitScreenParams; getApproverList(); 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 e914c70..08d2be7 100644 --- a/lib/ui/my_attendance/dynamic_screens/dynamic_input_screen.dart +++ b/lib/ui/my_attendance/dynamic_screens/dynamic_input_screen.dart @@ -635,9 +635,7 @@ class _DynamicInputScreenState extends State { ).paddingOnly(bottom: 12), itemBuilder: (_) => >[ if (model.rEADONLY != "Y") - for (int i = 0; i < model.eSERVICESVS!.length; i++) PopupMenuItem( - padding: EdgeInsets.all(10), - child: Text(model.eSERVICESVS![i].vALUECOLUMNNAME!), value: i), + for (int i = 0; i < model.eSERVICESVS!.length; i++) PopupMenuItem(child: Text(model.eSERVICESVS![i].vALUECOLUMNNAME!), value: i), ], 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 a670cbb..5c4053c 100644 --- a/lib/ui/my_attendance/dynamic_screens/dynamic_listview_screen.dart +++ b/lib/ui/my_attendance/dynamic_screens/dynamic_listview_screen.dart @@ -102,8 +102,8 @@ class _DynamicListViewScreenState extends State { 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), + gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2, childAspectRatio: 1.9 / 0.75), + padding: const EdgeInsets.all(12.0), shrinkWrap: true, primary: false, physics: const ScrollPhysics(), diff --git a/lib/ui/my_attendance/services_menu_list_screen.dart b/lib/ui/my_attendance/services_menu_list_screen.dart index 7a61029..cd76132 100644 --- a/lib/ui/my_attendance/services_menu_list_screen.dart +++ b/lib/ui/my_attendance/services_menu_list_screen.dart @@ -54,7 +54,7 @@ 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); return; } if (servicesMenuData.list[index].requestType == "EIT") { diff --git a/lib/ui/my_team/create_request.dart b/lib/ui/my_team/create_request.dart index 1637586..53205c9 100644 --- a/lib/ui/my_team/create_request.dart +++ b/lib/ui/my_team/create_request.dart @@ -69,7 +69,7 @@ class _CreateRequestState extends State { 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!)); } else {} } else { Navigator.pushNamed(context, AppRoutes.servicesMenuListScreen, arguments: ServicesMenuListScreenParams(menu.menuEntry.prompt!, menu.menuEntiesList, selectedEmp: getEmployeeSubordinates?.eMPLOYEENUMBER??'')); diff --git a/lib/widgets/balances_dashboard_widget.dart b/lib/widgets/balances_dashboard_widget.dart index e640ff4..e546acf 100644 --- a/lib/widgets/balances_dashboard_widget.dart +++ b/lib/widgets/balances_dashboard_widget.dart @@ -45,8 +45,6 @@ class _BalancesDashboardWidgetState extends State { late DateTime accrualDateTime; GetAccrualBalancesList? leaveBalanceAccrual; List? ticketBalanceAccrualList; - dynamic dynamicParams; - String selectedEmp =""; @override void initState() { @@ -62,7 +60,7 @@ class _BalancesDashboardWidgetState extends State { void changeAccrualDate() async { try { Utils.showLoading(context); - List accrualList = await DashboardApiClient().getAccrualBalances(DateFormat("MM/dd/yyyy").format(accrualDateTime),empID: selectedEmp); + List accrualList = await DashboardApiClient().getAccrualBalances(DateFormat("MM/dd/yyyy").format(accrualDateTime)); if (accrualList.isNotEmpty) { if (widget.isLeaveBalance) { leaveBalanceAccrual = accrualList[0]; @@ -88,17 +86,6 @@ class _BalancesDashboardWidgetState extends State { @override Widget build(BuildContext context) { - if (dynamicParams == null) { - dynamicParams = ModalRoute - .of(context)! - .settings - .arguments; - if (dynamicParams.isNotEmpty) { - AppState().postParamsJson['P_SELECTED_EMPLOYEE_NUMBER'] = dynamicParams; - selectedEmp =dynamicParams; - changeAccrualDate(); - } - } if (leaveBalanceAccrual == null && widget.isLeaveBalance) { leaveBalanceAccrual = Provider.of(context, listen: false).leaveBalanceAccrual; chartModelList = [ From d80f93a6dcf1f8c4e8ba68f68dc3c95e3cc34525 Mon Sep 17 00:00:00 2001 From: haroon amjad Date: Tue, 6 Dec 2022 16:08:43 +0300 Subject: [PATCH 34/35] Revert "no message" This reverts commit 323741ad069a2eeda7156d78c6ff58f66088ad2f. --- lib/api/dashboard_api_client.dart | 5 +- lib/api/leave_balance_api_client.dart | 35 +++++++++++--- .../add_leave_balance_screen.dart | 48 +++++++++++++------ .../leave_balance/leave_balance_screen.dart | 31 +++++++++--- lib/ui/misc/request_submit_screen.dart | 18 +++++++ .../dynamic_screens/dynamic_input_screen.dart | 4 +- .../dynamic_listview_screen.dart | 4 +- .../services_menu_list_screen.dart | 2 +- lib/ui/my_team/create_request.dart | 2 +- lib/widgets/balances_dashboard_widget.dart | 15 +++++- 10 files changed, 128 insertions(+), 36 deletions(-) diff --git a/lib/api/dashboard_api_client.dart b/lib/api/dashboard_api_client.dart index e30af91..3eab65b 100644 --- a/lib/api/dashboard_api_client.dart +++ b/lib/api/dashboard_api_client.dart @@ -65,10 +65,13 @@ class DashboardApiClient { }, url, postParams); } - Future> getAccrualBalances(String effectiveDate) async { + Future> getAccrualBalances(String effectiveDate, {String? empID}) async { String url = "${ApiConsts.erpRest}GET_ACCRUAL_BALANCES"; Map postParams = {"P_EFFECTIVE_DATE": effectiveDate}; 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.getAccrualBalancesList ?? []; diff --git a/lib/api/leave_balance_api_client.dart b/lib/api/leave_balance_api_client.dart index cd577ba..bb3f129 100644 --- a/lib/api/leave_balance_api_client.dart +++ b/lib/api/leave_balance_api_client.dart @@ -17,27 +17,33 @@ class LeaveBalanceApiClient { factory LeaveBalanceApiClient() => _instance; - Future> getAbsenceTransactions(int pSelectedResopID) 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; + } return await ApiClient().postJsonForObject((json) { GenericResponseModel? responseData = GenericResponseModel.fromJson(json); return responseData.getAbsenceTransactionList ?? []; }, url, postParams); } - Future> getAbsenceAttendanceTypes() async { + Future> getAbsenceAttendanceTypes({String? empID}) async { String url = "${ApiConsts.erpRest}GET_ABSENCE_ATTENDANCE_TYPES"; Map postParams = {}; 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.getAbsenceAttendanceTypesList ?? []; }, url, postParams); } - Future calculateAbsenceDuration(int pAbsenceAttendanceTypeID, String pDateStart, String pDateEnd, int pSelectedResopID) 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, @@ -49,16 +55,22 @@ class LeaveBalanceApiClient { "P_TIME_START": null, }; 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.calculateAbsenceDuration!; }, url, postParams); } - Future> getAbsenceDffStructure(String pDescFlexContextCode, String pFunctionName, int pSelectedResopID) 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}; 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.getAbsenceDffStructureList ?? []; @@ -67,7 +79,7 @@ class LeaveBalanceApiClient { Future validateAbsenceTransaction( String pDescFlexContextCode, String pFunctionName, int pAbsenceAttendanceTypeID, String pReplacementUserName, String pDateStart, String pDateEnd, int pSelectedResopID, Map data, - {String comments = ""}) async { + {String comments = "", String? empID}) async { String url = "${ApiConsts.erpRest}VALIDATE_ABSENCE_TRANSACTION"; Map postParams = { "P_DESC_FLEX_CONTEXT_CODE": pDescFlexContextCode, @@ -86,6 +98,9 @@ class LeaveBalanceApiClient { }; postParams.addAll(data); 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; @@ -94,7 +109,7 @@ class LeaveBalanceApiClient { Future submitAbsenceTransaction( String pDescFlexContextCode, String pFunctionName, int pAbsenceAttendanceTypeID, String pReplacementUserName, String pDateStart, String pDateEnd, int pSelectedResopID, Map data, - {String comments = ""}) async { + {String comments = "", String? empID}) async { String url = "${ApiConsts.erpRest}SUBMIT_ABSENCE_TRANSACTION"; Map postParams = { "P_DESC_FLEX_CONTEXT_CODE": pDescFlexContextCode, @@ -113,6 +128,9 @@ class LeaveBalanceApiClient { }; postParams.addAll(data); 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.sumbitAbsenceTransactionList!; @@ -129,7 +147,7 @@ class LeaveBalanceApiClient { }, url, postParams); } - Future startAbsenceApprovalProcess(int pTransactionID, String comments, int pSelectedResopID) 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, @@ -138,6 +156,9 @@ class LeaveBalanceApiClient { "P_MENU_TYPE": "E", }; 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/ui/leave_balance/add_leave_balance_screen.dart b/lib/ui/leave_balance/add_leave_balance_screen.dart index d1b7d77..c879f9c 100644 --- a/lib/ui/leave_balance/add_leave_balance_screen.dart +++ b/lib/ui/leave_balance/add_leave_balance_screen.dart @@ -4,6 +4,7 @@ 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'; @@ -24,7 +25,8 @@ 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 { - AddLeaveBalanceScreen({Key? key}) : super(key: key); + final String selectedEmp; + AddLeaveBalanceScreen({this.selectedEmp ='',Key? key}) : super(key: key); @override _AddLeaveBalanceScreenState createState() { @@ -43,6 +45,8 @@ class _AddLeaveBalanceScreenState extends State { String comment = ""; ReplacementList? selectedReplacementEmployee; + dynamic dynamicParams; + String selectedEmp =""; DateTime selectedDate = DateTime(DateTime.now().year, DateTime.now().month, DateTime.now().day); @override @@ -54,7 +58,7 @@ class _AddLeaveBalanceScreenState extends State { void getAbsenceAttendanceTypes() async { try { Utils.showLoading(context); - absenceList = await LeaveBalanceApiClient().getAbsenceAttendanceTypes(); + absenceList = await LeaveBalanceApiClient().getAbsenceAttendanceTypes(empID: selectedEmp); Utils.hideLoading(context); setState(() {}); } catch (ex) { @@ -67,7 +71,7 @@ class _AddLeaveBalanceScreenState extends State { try { Utils.showLoading(context); getabsenceDffStructureList.clear(); - getabsenceDffStructureList = await LeaveBalanceApiClient().getAbsenceDffStructure(selectedAbsenceType!.dESCFLEXCONTEXTCODE!, "HR_LOA_SS", -999); + getabsenceDffStructureList = await LeaveBalanceApiClient().getAbsenceDffStructure(selectedAbsenceType!.dESCFLEXCONTEXTCODE!, "HR_LOA_SS", -999, empID: selectedEmp); Utils.hideLoading(context); setState(() {}); } catch (ex) { @@ -80,7 +84,7 @@ class _AddLeaveBalanceScreenState extends State { try { Utils.showLoading(context); CalculateAbsenceDuration duration = await LeaveBalanceApiClient() - .calculateAbsenceDuration(selectedAbsenceType!.aBSENCEATTENDANCETYPEID!, Utils.getMonthNamedFormat(startDateTime!), Utils.getMonthNamedFormat(endDateTime!), -999); + .calculateAbsenceDuration(selectedAbsenceType!.aBSENCEATTENDANCETYPEID!, Utils.getMonthNamedFormat(startDateTime!), Utils.getMonthNamedFormat(endDateTime!), -999, empID: selectedEmp); totalDays = duration.pABSENCEDAYS?.toInt(); Utils.hideLoading(context); @@ -109,16 +113,17 @@ class _AddLeaveBalanceScreenState extends State { } } } - 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); + 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 ); SumbitAbsenceTransactionList submit = await LeaveBalanceApiClient().submitAbsenceTransaction( selectedAbsenceType!.dESCFLEXCONTEXTCODE!, @@ -129,7 +134,8 @@ class _AddLeaveBalanceScreenState extends State { DateUtil.getFormattedDate(endDateTime!, "MM/dd/yyyy"), -999, dffDataMap, - comments: comment); + comments: comment, + empID: selectedEmp); Utils.hideLoading(context); @@ -152,6 +158,18 @@ class _AddLeaveBalanceScreenState extends State { @override Widget build(BuildContext context) { + if (dynamicParams == null) { + dynamicParams = ModalRoute + .of(context)! + .settings + .arguments; + if (dynamicParams.isNotEmpty) { + AppState().postParamsJson['P_SELECTED_EMPLOYEE_NUMBER'] = dynamicParams; + selectedEmp =dynamicParams; + getAbsenceAttendanceTypes(); + + } + } return Scaffold( backgroundColor: Colors.white, appBar: AppBarWidget( diff --git a/lib/ui/leave_balance/leave_balance_screen.dart b/lib/ui/leave_balance/leave_balance_screen.dart index 548ca99..1218914 100644 --- a/lib/ui/leave_balance/leave_balance_screen.dart +++ b/lib/ui/leave_balance/leave_balance_screen.dart @@ -1,6 +1,7 @@ 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'; @@ -8,12 +9,14 @@ import 'package:mohem_flutter_app/extensions/int_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/leave_balance/get_absence_transaction_list_model.dart'; +import 'package:mohem_flutter_app/ui/my_attendance/services_menu_list_screen.dart'; import 'package:mohem_flutter_app/widgets/app_bar_widget.dart'; 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 { - LeaveBalance({Key? key}) : super(key: key); + final String selectedEmp; + LeaveBalance({this.selectedEmp ='', Key? key}) : super(key: key); @override _LeaveBalanceState createState() { @@ -25,12 +28,13 @@ class _LeaveBalanceState extends State { List? absenceTransList; DateTime accrualDateTime = DateTime.now(); - + dynamic dynamicParams; + String selectedEmp =""; @override void initState() { super.initState(); - getAbsenceTransactions(); + } @override @@ -39,9 +43,9 @@ class _LeaveBalanceState extends State { } void getAbsenceTransactions() async { - try { + try { Utils.showLoading(context); - absenceTransList = await LeaveBalanceApiClient().getAbsenceTransactions(-999); + absenceTransList = await LeaveBalanceApiClient().getAbsenceTransactions(-999, empID: selectedEmp); Utils.hideLoading(context); setState(() {}); } catch (ex) { @@ -52,6 +56,19 @@ class _LeaveBalanceState extends State { @override Widget build(BuildContext context) { + if (dynamicParams == null) { + dynamicParams = ModalRoute + .of(context)! + .settings + .arguments; + if (dynamicParams.isNotEmpty) { + AppState().postParamsJson['P_SELECTED_EMPLOYEE_NUMBER'] = dynamicParams; + selectedEmp =dynamicParams; + getAbsenceTransactions(); + // setState(() {}); + + } + } return Scaffold( backgroundColor: Colors.white, appBar: AppBarWidget( @@ -62,7 +79,7 @@ class _LeaveBalanceState extends State { physics: const BouncingScrollPhysics(), padding: const EdgeInsets.all(21), children: [ - BalancesDashboardWidget(LocaleKeys.currentLeaveBalance.tr(), true), + BalancesDashboardWidget(LocaleKeys.currentLeaveBalance.tr(), true,), 12.height, absenceTransList == null ? const SizedBox() @@ -111,7 +128,7 @@ class _LeaveBalanceState extends State { ), child: const Icon(Icons.add, color: Colors.white, size: 30), ).onPress(() { - Navigator.pushNamed(context, AppRoutes.addLeaveBalance); + Navigator.pushNamed(context, AppRoutes.addLeaveBalance, arguments: selectedEmp ??''); }), ); } diff --git a/lib/ui/misc/request_submit_screen.dart b/lib/ui/misc/request_submit_screen.dart index f05bacb..84adf9f 100644 --- a/lib/ui/misc/request_submit_screen.dart +++ b/lib/ui/misc/request_submit_screen.dart @@ -8,6 +8,7 @@ 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/api/profile_api_client.dart'; import 'package:mohem_flutter_app/api/termination_dff_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'; @@ -49,8 +50,13 @@ class _RequestSubmitScreenState extends State { List approverList = []; List attachmentFiles = []; + + dynamic dynamicParams; + String selectedEmp =""; + List attachments = []; + @override void initState() { super.initState(); @@ -123,6 +129,7 @@ class _RequestSubmitScreenState extends State { params!.transactionId, comments.text, -999, + empID: selectedEmp ); } else if (params!.approvalFlag == 'eit') { await MyAttendanceApiClient().startEitApprovalProcess( @@ -157,6 +164,17 @@ class _RequestSubmitScreenState extends State { @override Widget build(BuildContext context) { + if (dynamicParams == null) { + dynamicParams = ModalRoute + .of(context)! + .settings + .arguments; + if (dynamicParams.isNotEmpty) { + AppState().postParamsJson['P_SELECTED_EMPLOYEE_NUMBER'] = dynamicParams; + selectedEmp =dynamicParams; + submitRequest(); + } + } if (params == null) { params = ModalRoute.of(context)!.settings.arguments as RequestSubmitScreenParams; getApproverList(); 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 08d2be7..e914c70 100644 --- a/lib/ui/my_attendance/dynamic_screens/dynamic_input_screen.dart +++ b/lib/ui/my_attendance/dynamic_screens/dynamic_input_screen.dart @@ -635,7 +635,9 @@ class _DynamicInputScreenState extends State { ).paddingOnly(bottom: 12), itemBuilder: (_) => >[ if (model.rEADONLY != "Y") - for (int i = 0; i < model.eSERVICESVS!.length; i++) PopupMenuItem(child: Text(model.eSERVICESVS![i].vALUECOLUMNNAME!), value: i), + for (int i = 0; i < model.eSERVICESVS!.length; i++) PopupMenuItem( + padding: EdgeInsets.all(10), + child: Text(model.eSERVICESVS![i].vALUECOLUMNNAME!), value: i), ], 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 5c4053c..a670cbb 100644 --- a/lib/ui/my_attendance/dynamic_screens/dynamic_listview_screen.dart +++ b/lib/ui/my_attendance/dynamic_screens/dynamic_listview_screen.dart @@ -102,8 +102,8 @@ class _DynamicListViewScreenState extends State { itemBuilder: (cxt, int parentIndex) => getEITTransactionList![parentIndex].collectionTransaction!.isEmpty ? const SizedBox() : GridView( - gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2, childAspectRatio: 1.9 / 0.75), - padding: const EdgeInsets.all(12.0), + 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(), diff --git a/lib/ui/my_attendance/services_menu_list_screen.dart b/lib/ui/my_attendance/services_menu_list_screen.dart index cd76132..7a61029 100644 --- a/lib/ui/my_attendance/services_menu_list_screen.dart +++ b/lib/ui/my_attendance/services_menu_list_screen.dart @@ -54,7 +54,7 @@ class ServicesMenuListScreen extends StatelessWidget { } return; } else if (servicesMenuData.list[index].requestType == "ABSENCE") { - Navigator.pushNamed(context, AppRoutes.leaveBalance); + Navigator.pushNamed(context, AppRoutes.leaveBalance, arguments: servicesMenuData?.selectedEmp ??''); return; } if (servicesMenuData.list[index].requestType == "EIT") { diff --git a/lib/ui/my_team/create_request.dart b/lib/ui/my_team/create_request.dart index 53205c9..1637586 100644 --- a/lib/ui/my_team/create_request.dart +++ b/lib/ui/my_team/create_request.dart @@ -69,7 +69,7 @@ class _CreateRequestState extends State { if (menu.menuEntry.menuEntryType == "FUNCTION") { if (menu.menuEntry.requestType == "EIT") { - Navigator.pushNamed(context, AppRoutes.dynamicScreen, arguments: DynamicListViewParams(menu.menuEntry.prompt!, menu.menuEntry.functionName!)); + Navigator.pushNamed(context, AppRoutes.dynamicScreen, arguments: DynamicListViewParams(menu.menuEntry.prompt!, menu.menuEntry.functionName!, selectedEmp: getEmployeeSubordinates?.eMPLOYEENUMBER??'')); } else {} } else { Navigator.pushNamed(context, AppRoutes.servicesMenuListScreen, arguments: ServicesMenuListScreenParams(menu.menuEntry.prompt!, menu.menuEntiesList, selectedEmp: getEmployeeSubordinates?.eMPLOYEENUMBER??'')); diff --git a/lib/widgets/balances_dashboard_widget.dart b/lib/widgets/balances_dashboard_widget.dart index e546acf..e640ff4 100644 --- a/lib/widgets/balances_dashboard_widget.dart +++ b/lib/widgets/balances_dashboard_widget.dart @@ -45,6 +45,8 @@ class _BalancesDashboardWidgetState extends State { late DateTime accrualDateTime; GetAccrualBalancesList? leaveBalanceAccrual; List? ticketBalanceAccrualList; + dynamic dynamicParams; + String selectedEmp =""; @override void initState() { @@ -60,7 +62,7 @@ class _BalancesDashboardWidgetState extends State { void changeAccrualDate() async { try { Utils.showLoading(context); - List accrualList = await DashboardApiClient().getAccrualBalances(DateFormat("MM/dd/yyyy").format(accrualDateTime)); + List accrualList = await DashboardApiClient().getAccrualBalances(DateFormat("MM/dd/yyyy").format(accrualDateTime),empID: selectedEmp); if (accrualList.isNotEmpty) { if (widget.isLeaveBalance) { leaveBalanceAccrual = accrualList[0]; @@ -86,6 +88,17 @@ class _BalancesDashboardWidgetState extends State { @override Widget build(BuildContext context) { + if (dynamicParams == null) { + dynamicParams = ModalRoute + .of(context)! + .settings + .arguments; + if (dynamicParams.isNotEmpty) { + AppState().postParamsJson['P_SELECTED_EMPLOYEE_NUMBER'] = dynamicParams; + selectedEmp =dynamicParams; + changeAccrualDate(); + } + } if (leaveBalanceAccrual == null && widget.isLeaveBalance) { leaveBalanceAccrual = Provider.of(context, listen: false).leaveBalanceAccrual; chartModelList = [ From 6463dfc4245cd305fd11e5aa51a4b339fa9ac6c8 Mon Sep 17 00:00:00 2001 From: haroon amjad Date: Tue, 6 Dec 2022 16:09:49 +0300 Subject: [PATCH 35/35] Reverting fatima changes --- lib/api/dashboard_api_client.dart | 5 +- lib/api/leave_balance_api_client.dart | 35 +++----------- .../add_leave_balance_screen.dart | 48 ++++++------------- .../leave_balance/leave_balance_screen.dart | 31 +++--------- lib/ui/misc/request_submit_screen.dart | 18 ------- .../dynamic_screens/dynamic_input_screen.dart | 4 +- .../dynamic_listview_screen.dart | 4 +- .../services_menu_list_screen.dart | 2 +- lib/ui/my_team/create_request.dart | 2 +- lib/widgets/balances_dashboard_widget.dart | 15 +----- 10 files changed, 36 insertions(+), 128 deletions(-) diff --git a/lib/api/dashboard_api_client.dart b/lib/api/dashboard_api_client.dart index 3eab65b..e30af91 100644 --- a/lib/api/dashboard_api_client.dart +++ b/lib/api/dashboard_api_client.dart @@ -65,13 +65,10 @@ class DashboardApiClient { }, url, postParams); } - Future> getAccrualBalances(String effectiveDate, {String? empID}) async { + Future> getAccrualBalances(String effectiveDate) async { String url = "${ApiConsts.erpRest}GET_ACCRUAL_BALANCES"; Map postParams = {"P_EFFECTIVE_DATE": effectiveDate}; 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.getAccrualBalancesList ?? []; diff --git a/lib/api/leave_balance_api_client.dart b/lib/api/leave_balance_api_client.dart index bb3f129..cd577ba 100644 --- a/lib/api/leave_balance_api_client.dart +++ b/lib/api/leave_balance_api_client.dart @@ -17,33 +17,27 @@ class LeaveBalanceApiClient { factory LeaveBalanceApiClient() => _instance; - Future> getAbsenceTransactions(int pSelectedResopID, {String? empID}) async { + Future> getAbsenceTransactions(int pSelectedResopID) 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; - } return await ApiClient().postJsonForObject((json) { GenericResponseModel? responseData = GenericResponseModel.fromJson(json); return responseData.getAbsenceTransactionList ?? []; }, url, postParams); } - Future> getAbsenceAttendanceTypes({String? empID}) async { + Future> getAbsenceAttendanceTypes() async { String url = "${ApiConsts.erpRest}GET_ABSENCE_ATTENDANCE_TYPES"; Map postParams = {}; 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.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) async { String url = "${ApiConsts.erpRest}CALCULATE_ABSENCE_DURATION"; Map postParams = { "P_ABSENCE_ATTENDANCE_TYPE_ID": pAbsenceAttendanceTypeID, @@ -55,22 +49,16 @@ class LeaveBalanceApiClient { "P_TIME_START": null, }; 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.calculateAbsenceDuration!; }, url, postParams); } - Future> getAbsenceDffStructure(String pDescFlexContextCode, String pFunctionName, int pSelectedResopID, {String? empID}) async { + Future> getAbsenceDffStructure(String pDescFlexContextCode, String pFunctionName, int pSelectedResopID) 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}; 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.getAbsenceDffStructureList ?? []; @@ -79,7 +67,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 = ""}) async { String url = "${ApiConsts.erpRest}VALIDATE_ABSENCE_TRANSACTION"; Map postParams = { "P_DESC_FLEX_CONTEXT_CODE": pDescFlexContextCode, @@ -98,9 +86,6 @@ class LeaveBalanceApiClient { }; postParams.addAll(data); 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; @@ -109,7 +94,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 = ""}) async { String url = "${ApiConsts.erpRest}SUBMIT_ABSENCE_TRANSACTION"; Map postParams = { "P_DESC_FLEX_CONTEXT_CODE": pDescFlexContextCode, @@ -128,9 +113,6 @@ class LeaveBalanceApiClient { }; postParams.addAll(data); 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.sumbitAbsenceTransactionList!; @@ -147,7 +129,7 @@ class LeaveBalanceApiClient { }, url, postParams); } - Future startAbsenceApprovalProcess(int pTransactionID, String comments, int pSelectedResopID, {String? empID}) async { + Future startAbsenceApprovalProcess(int pTransactionID, String comments, int pSelectedResopID) async { String url = "${ApiConsts.erpRest}START_ABSENCE_APPROVAL_PROCESS"; Map postParams = { "P_TRANSACTION_ID": pTransactionID, @@ -156,9 +138,6 @@ class LeaveBalanceApiClient { "P_MENU_TYPE": "E", }; 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/ui/leave_balance/add_leave_balance_screen.dart b/lib/ui/leave_balance/add_leave_balance_screen.dart index c879f9c..d1b7d77 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() { @@ -45,8 +43,6 @@ class _AddLeaveBalanceScreenState extends State { String comment = ""; ReplacementList? selectedReplacementEmployee; - dynamic dynamicParams; - String selectedEmp =""; DateTime selectedDate = DateTime(DateTime.now().year, DateTime.now().month, DateTime.now().day); @override @@ -58,7 +54,7 @@ class _AddLeaveBalanceScreenState extends State { void getAbsenceAttendanceTypes() async { try { Utils.showLoading(context); - absenceList = await LeaveBalanceApiClient().getAbsenceAttendanceTypes(empID: selectedEmp); + absenceList = await LeaveBalanceApiClient().getAbsenceAttendanceTypes(); Utils.hideLoading(context); setState(() {}); } catch (ex) { @@ -71,7 +67,7 @@ class _AddLeaveBalanceScreenState extends State { try { Utils.showLoading(context); getabsenceDffStructureList.clear(); - getabsenceDffStructureList = await LeaveBalanceApiClient().getAbsenceDffStructure(selectedAbsenceType!.dESCFLEXCONTEXTCODE!, "HR_LOA_SS", -999, empID: selectedEmp); + getabsenceDffStructureList = await LeaveBalanceApiClient().getAbsenceDffStructure(selectedAbsenceType!.dESCFLEXCONTEXTCODE!, "HR_LOA_SS", -999); Utils.hideLoading(context); setState(() {}); } catch (ex) { @@ -84,7 +80,7 @@ class _AddLeaveBalanceScreenState extends State { try { Utils.showLoading(context); CalculateAbsenceDuration duration = await LeaveBalanceApiClient() - .calculateAbsenceDuration(selectedAbsenceType!.aBSENCEATTENDANCETYPEID!, Utils.getMonthNamedFormat(startDateTime!), Utils.getMonthNamedFormat(endDateTime!), -999, empID: selectedEmp); + .calculateAbsenceDuration(selectedAbsenceType!.aBSENCEATTENDANCETYPEID!, Utils.getMonthNamedFormat(startDateTime!), Utils.getMonthNamedFormat(endDateTime!), -999); totalDays = duration.pABSENCEDAYS?.toInt(); Utils.hideLoading(context); @@ -113,17 +109,16 @@ class _AddLeaveBalanceScreenState extends State { } } } - 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); SumbitAbsenceTransactionList submit = await LeaveBalanceApiClient().submitAbsenceTransaction( selectedAbsenceType!.dESCFLEXCONTEXTCODE!, @@ -134,8 +129,7 @@ class _AddLeaveBalanceScreenState extends State { DateUtil.getFormattedDate(endDateTime!, "MM/dd/yyyy"), -999, dffDataMap, - comments: comment, - empID: selectedEmp); + comments: comment); Utils.hideLoading(context); @@ -158,18 +152,6 @@ class _AddLeaveBalanceScreenState extends State { @override Widget build(BuildContext context) { - if (dynamicParams == null) { - dynamicParams = ModalRoute - .of(context)! - .settings - .arguments; - if (dynamicParams.isNotEmpty) { - AppState().postParamsJson['P_SELECTED_EMPLOYEE_NUMBER'] = dynamicParams; - selectedEmp =dynamicParams; - getAbsenceAttendanceTypes(); - - } - } return Scaffold( backgroundColor: Colors.white, appBar: AppBarWidget( diff --git a/lib/ui/leave_balance/leave_balance_screen.dart b/lib/ui/leave_balance/leave_balance_screen.dart index 1218914..548ca99 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'; @@ -9,14 +8,12 @@ import 'package:mohem_flutter_app/extensions/int_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/leave_balance/get_absence_transaction_list_model.dart'; -import 'package:mohem_flutter_app/ui/my_attendance/services_menu_list_screen.dart'; import 'package:mohem_flutter_app/widgets/app_bar_widget.dart'; 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() { @@ -28,13 +25,12 @@ class _LeaveBalanceState extends State { List? absenceTransList; DateTime accrualDateTime = DateTime.now(); - dynamic dynamicParams; - String selectedEmp =""; + @override void initState() { super.initState(); - + getAbsenceTransactions(); } @override @@ -43,9 +39,9 @@ class _LeaveBalanceState extends State { } void getAbsenceTransactions() async { - try { + try { Utils.showLoading(context); - absenceTransList = await LeaveBalanceApiClient().getAbsenceTransactions(-999, empID: selectedEmp); + absenceTransList = await LeaveBalanceApiClient().getAbsenceTransactions(-999); Utils.hideLoading(context); setState(() {}); } catch (ex) { @@ -56,19 +52,6 @@ class _LeaveBalanceState extends State { @override Widget build(BuildContext context) { - if (dynamicParams == null) { - dynamicParams = ModalRoute - .of(context)! - .settings - .arguments; - if (dynamicParams.isNotEmpty) { - AppState().postParamsJson['P_SELECTED_EMPLOYEE_NUMBER'] = dynamicParams; - selectedEmp =dynamicParams; - getAbsenceTransactions(); - // setState(() {}); - - } - } return Scaffold( backgroundColor: Colors.white, appBar: AppBarWidget( @@ -79,7 +62,7 @@ class _LeaveBalanceState extends State { physics: const BouncingScrollPhysics(), padding: const EdgeInsets.all(21), children: [ - BalancesDashboardWidget(LocaleKeys.currentLeaveBalance.tr(), true,), + BalancesDashboardWidget(LocaleKeys.currentLeaveBalance.tr(), true), 12.height, absenceTransList == null ? const SizedBox() @@ -128,7 +111,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); }), ); } diff --git a/lib/ui/misc/request_submit_screen.dart b/lib/ui/misc/request_submit_screen.dart index 84adf9f..f05bacb 100644 --- a/lib/ui/misc/request_submit_screen.dart +++ b/lib/ui/misc/request_submit_screen.dart @@ -8,7 +8,6 @@ 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/api/profile_api_client.dart'; import 'package:mohem_flutter_app/api/termination_dff_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'; @@ -50,13 +49,8 @@ class _RequestSubmitScreenState extends State { List approverList = []; List attachmentFiles = []; - - dynamic dynamicParams; - String selectedEmp =""; - List attachments = []; - @override void initState() { super.initState(); @@ -129,7 +123,6 @@ class _RequestSubmitScreenState extends State { params!.transactionId, comments.text, -999, - empID: selectedEmp ); } else if (params!.approvalFlag == 'eit') { await MyAttendanceApiClient().startEitApprovalProcess( @@ -164,17 +157,6 @@ class _RequestSubmitScreenState extends State { @override Widget build(BuildContext context) { - if (dynamicParams == null) { - dynamicParams = ModalRoute - .of(context)! - .settings - .arguments; - if (dynamicParams.isNotEmpty) { - AppState().postParamsJson['P_SELECTED_EMPLOYEE_NUMBER'] = dynamicParams; - selectedEmp =dynamicParams; - submitRequest(); - } - } if (params == null) { params = ModalRoute.of(context)!.settings.arguments as RequestSubmitScreenParams; getApproverList(); 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 e914c70..08d2be7 100644 --- a/lib/ui/my_attendance/dynamic_screens/dynamic_input_screen.dart +++ b/lib/ui/my_attendance/dynamic_screens/dynamic_input_screen.dart @@ -635,9 +635,7 @@ class _DynamicInputScreenState extends State { ).paddingOnly(bottom: 12), itemBuilder: (_) => >[ if (model.rEADONLY != "Y") - for (int i = 0; i < model.eSERVICESVS!.length; i++) PopupMenuItem( - padding: EdgeInsets.all(10), - child: Text(model.eSERVICESVS![i].vALUECOLUMNNAME!), value: i), + for (int i = 0; i < model.eSERVICESVS!.length; i++) PopupMenuItem(child: Text(model.eSERVICESVS![i].vALUECOLUMNNAME!), value: i), ], 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 a670cbb..5c4053c 100644 --- a/lib/ui/my_attendance/dynamic_screens/dynamic_listview_screen.dart +++ b/lib/ui/my_attendance/dynamic_screens/dynamic_listview_screen.dart @@ -102,8 +102,8 @@ class _DynamicListViewScreenState extends State { 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), + gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2, childAspectRatio: 1.9 / 0.75), + padding: const EdgeInsets.all(12.0), shrinkWrap: true, primary: false, physics: const ScrollPhysics(), diff --git a/lib/ui/my_attendance/services_menu_list_screen.dart b/lib/ui/my_attendance/services_menu_list_screen.dart index 7a61029..cd76132 100644 --- a/lib/ui/my_attendance/services_menu_list_screen.dart +++ b/lib/ui/my_attendance/services_menu_list_screen.dart @@ -54,7 +54,7 @@ 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); return; } if (servicesMenuData.list[index].requestType == "EIT") { diff --git a/lib/ui/my_team/create_request.dart b/lib/ui/my_team/create_request.dart index 1637586..53205c9 100644 --- a/lib/ui/my_team/create_request.dart +++ b/lib/ui/my_team/create_request.dart @@ -69,7 +69,7 @@ class _CreateRequestState extends State { 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!)); } else {} } else { Navigator.pushNamed(context, AppRoutes.servicesMenuListScreen, arguments: ServicesMenuListScreenParams(menu.menuEntry.prompt!, menu.menuEntiesList, selectedEmp: getEmployeeSubordinates?.eMPLOYEENUMBER??'')); diff --git a/lib/widgets/balances_dashboard_widget.dart b/lib/widgets/balances_dashboard_widget.dart index e640ff4..e546acf 100644 --- a/lib/widgets/balances_dashboard_widget.dart +++ b/lib/widgets/balances_dashboard_widget.dart @@ -45,8 +45,6 @@ class _BalancesDashboardWidgetState extends State { late DateTime accrualDateTime; GetAccrualBalancesList? leaveBalanceAccrual; List? ticketBalanceAccrualList; - dynamic dynamicParams; - String selectedEmp =""; @override void initState() { @@ -62,7 +60,7 @@ class _BalancesDashboardWidgetState extends State { void changeAccrualDate() async { try { Utils.showLoading(context); - List accrualList = await DashboardApiClient().getAccrualBalances(DateFormat("MM/dd/yyyy").format(accrualDateTime),empID: selectedEmp); + List accrualList = await DashboardApiClient().getAccrualBalances(DateFormat("MM/dd/yyyy").format(accrualDateTime)); if (accrualList.isNotEmpty) { if (widget.isLeaveBalance) { leaveBalanceAccrual = accrualList[0]; @@ -88,17 +86,6 @@ class _BalancesDashboardWidgetState extends State { @override Widget build(BuildContext context) { - if (dynamicParams == null) { - dynamicParams = ModalRoute - .of(context)! - .settings - .arguments; - if (dynamicParams.isNotEmpty) { - AppState().postParamsJson['P_SELECTED_EMPLOYEE_NUMBER'] = dynamicParams; - selectedEmp =dynamicParams; - changeAccrualDate(); - } - } if (leaveBalanceAccrual == null && widget.isLeaveBalance) { leaveBalanceAccrual = Provider.of(context, listen: false).leaveBalanceAccrual; chartModelList = [