swipe history added

main_design2.1
WaseemAbbasi22 1 year ago
parent f6e2ef676c
commit c5f863b05c

@ -39,6 +39,7 @@ class URLs {
//Swipe module Api..
static get swipeUrl=> '$_baseUrl/Swipe/Swipe';
static get getSwipeLastTransactionUrl=> '$_baseUrl/Swipe/GetLastTransaction';
static get getSwipeTransactionHistoryUrl=> '$_baseUrl/Swipe/GetTransactions';
static get getAllRequestsAndCount => "$_baseUrl/CallRequest/GetAllRequestsAndCount"; // get
// 08051

@ -10,6 +10,7 @@ import 'package:test_sa/new_views/swipe_module/models/swipe_model.dart';
import 'package:test_sa/new_views/forget_password_module/models/update_password.dart';
import 'package:test_sa/new_views/forget_password_module/models/verify_otp_model.dart';
import 'package:test_sa/models/user.dart';
import 'package:test_sa/new_views/swipe_module/models/swipe_transaction_history.dart';
import 'package:test_sa/new_views/swipe_module/models/swipe_transaction_model.dart';
import '../../../new_views/common_widgets/app_lazy_loading.dart';
@ -54,11 +55,18 @@ class UserProvider extends ChangeNotifier {
// when login or register is done or not start = false
bool _loading = false;
VerifyOtpModel _verifyOtpModel;
SwipeTransaction _swipeTransactionModel=SwipeTransaction();
SwipeTransaction _swipeTransactionModel = SwipeTransaction();
List<SwipeHistory> _swipeHistory = [];
SwipeTransaction get swipeTransactionModel => _swipeTransactionModel;
List<SwipeHistory> get swipeHistory => _swipeHistory;
set swipeHistory(List<SwipeHistory> value) {
_swipeHistory = value;
notifyListeners();
}
set swipeTransactionModel(SwipeTransaction value) {
_swipeTransactionModel = value;
notifyListeners();
@ -106,7 +114,7 @@ class UserProvider extends ChangeNotifier {
Navigator.pop(context);
return response.statusCode;
} catch (error) {
// debugPrint(error);
// debugPrint(error);
Navigator.pop(context);
_loading = false;
notifyListeners();
@ -177,6 +185,7 @@ class UserProvider extends ChangeNotifier {
return -1;
}
}
//this need to be in seprate provider but for now place here...
Future<SwipeModel> makeSwipe({@required Swipe model}) async {
isLoading = true;
@ -187,9 +196,9 @@ class UserProvider extends ChangeNotifier {
response = await ApiManager.instance.post(URLs.swipeUrl, body: model.toJson());
swipeResponse = SwipeModel.fromJson(json.decode(response.body));
if (response.statusCode >= 200 && response.statusCode < 300) {
isUserConfirmSwipe = true;
await getSwipeLastTransaction(userId: user.userID);
notifyListeners();
isUserConfirmSwipe = true;
await getSwipeLastTransaction(userId: user.userID);
notifyListeners();
}
notifyListeners();
@ -221,18 +230,45 @@ class UserProvider extends ChangeNotifier {
}
}
Future<int> getSwipeTransactionHistory({@required String userId, DateTime dateFrom, DateTime dateTo}) async {
isLoading = true;
notifyListeners();
Response response;
var body = {
"userId": userId,
"dateFrom": dateFrom.toIso8601String(),
"dateTo": dateTo.toIso8601String(),
};
try {
response = await ApiManager.instance.post(URLs.getSwipeTransactionHistoryUrl, body: body);
if (response.statusCode >= 200 && response.statusCode < 300) {
List dataList = GeneralResponseModel.fromJson(json.decode(response.body)).data;
swipeHistory = List.generate(dataList.length, (index) => SwipeHistory.fromJson(dataList[index]));
}
isLoading =false ;
notifyListeners();
return response.statusCode;
} catch (error) {
isLoading =false ;
notifyListeners();
return -1;
}
}
Future<GeneralResponseModel> sendForgetPasswordOtp({@required BuildContext context, @required String employeeId}) async {
GeneralResponseModel generalResponseModel= GeneralResponseModel(responseCode: -1) ;
GeneralResponseModel generalResponseModel = GeneralResponseModel(responseCode: -1);
if (_loading == true) return generalResponseModel;
_loading = true;
notifyListeners();
Response response;
try {
showDialog(context: context, barrierDismissible: false, builder: (context) => const AppLazyLoading());
showDialog(context: context, barrierDismissible: false, builder: (context) => const AppLazyLoading());
response = await ApiManager.instance.postWithOutBody(
URLs.sendForgetPasswordOtp + '?employeeId=$employeeId',
);
generalResponseModel = GeneralResponseModel.fromJson(json.decode(response.body));
generalResponseModel = GeneralResponseModel.fromJson(json.decode(response.body));
print('data i got is ${generalResponseModel.data}');
_loading = false;
if (response.statusCode >= 200 && response.statusCode < 300) {
@ -252,27 +288,26 @@ class UserProvider extends ChangeNotifier {
}
}
Future<GeneralResponseModel> forgetPasswordValidateOtp({@required BuildContext context, @required String employeeId, @required String otp}) async {
print('payload i got is ${employeeId} code ${otp}');
GeneralResponseModel generalResponseModel= GeneralResponseModel(responseCode: -1) ;
GeneralResponseModel generalResponseModel = GeneralResponseModel(responseCode: -1);
// if (_loading == true) return generalResponseModel;
_loading = true;
notifyListeners();
Response response;
try {
showDialog(context: context, barrierDismissible: false, builder: (context) => const AppLazyLoading());
showDialog(context: context, barrierDismissible: false, builder: (context) => const AppLazyLoading());
response = await ApiManager.instance.postWithOutBody(
URLs.sendForgetPasswordValidateOtp + '?employeeId=$employeeId&otp=$otp',
);
generalResponseModel = GeneralResponseModel.fromJson(json.decode(response.body));
generalResponseModel = GeneralResponseModel.fromJson(json.decode(response.body));
print('response model i got is ${generalResponseModel.data}');
_loading = false;
if (response.statusCode >= 200 && response.statusCode < 300) {
print('i got status ${response.statusCode}');
if(generalResponseModel.data!=null){
if (generalResponseModel.data != null) {
print('inside data not null ${generalResponseModel.data}');
verifyOtpModel = VerifyOtpModel.fromJson(generalResponseModel.data);
verifyOtpModel = VerifyOtpModel.fromJson(generalResponseModel.data);
}
notifyListeners();
Navigator.pop(context);
@ -290,20 +325,16 @@ class UserProvider extends ChangeNotifier {
}
}
Future<GeneralResponseModel> updateNewPassword({@required BuildContext context,UpdatePasswordModel updatePasswordModel}) async {
GeneralResponseModel generalResponseModel= GeneralResponseModel(responseCode: -1) ;
Future<GeneralResponseModel> updateNewPassword({@required BuildContext context, UpdatePasswordModel updatePasswordModel}) async {
GeneralResponseModel generalResponseModel = GeneralResponseModel(responseCode: -1);
if (_loading == true) return generalResponseModel;
_loading = true;
notifyListeners();
Response response;
try {
showDialog(context: context, barrierDismissible: false, builder: (context) => const AppLazyLoading());
response = await ApiManager.instance.post(
URLs.updateNewPassword,
body:updatePasswordModel.toJson()
);
generalResponseModel = GeneralResponseModel.fromJson(json.decode(response.body));
showDialog(context: context, barrierDismissible: false, builder: (context) => const AppLazyLoading());
response = await ApiManager.instance.post(URLs.updateNewPassword, body: updatePasswordModel.toJson());
generalResponseModel = GeneralResponseModel.fromJson(json.decode(response.body));
_loading = false;
if (response.statusCode >= 200 && response.statusCode < 300) {
notifyListeners();

@ -52,6 +52,10 @@
"searchByName": "بحث بالاسم",
"searchByAssetNumber": "بحث برقم الجهاز",
"address": "العنوان",
"swipeTypeName": "اسم نوع السحب",
"userName": "اسم المستخدم",
"siteName": "اسم الموقع",
"pointName": "اسم النقطة",
"addressNotFound": "لا يوجد عنوان",
"addressValidateMessage": "العنوان مطلوب",
"dataNotFound": "لا يوجد تاريخ",

@ -17,6 +17,10 @@
"employeeIdIsRequired": "Employee Id is required",
"successful": "Successful",
"youHaveSuccessfullyMarkedYourAttendance": "You have successfully marked your attendance",
"swipeTypeName": "Swipe Type Name",
"userName": "User Name",
"siteName": "Site Name",
"pointName": "Point Name",
"done": "Done",
"exit": "Exit",
"checkIn": "Check in",

@ -51,6 +51,7 @@ import 'package:test_sa/new_views/pages/report_bug_page.dart';
import 'package:test_sa/new_views/pages/settings_page.dart';
import 'package:test_sa/new_views/pages/splash_page.dart';
import 'package:test_sa/new_views/pages/usSafeDevice_view.dart';
import 'package:test_sa/new_views/swipe_module/swipe_history_view.dart';
import 'package:test_sa/new_views/swipe_module/swipe_success_view.dart';
import 'package:test_sa/providers/asset_transfer/asset_transfer_status_provider.dart';
import 'package:test_sa/providers/department_provider.dart';
@ -259,6 +260,8 @@ class MyApp extends StatelessWidget {
LoginPage.routeName: (_) => const LoginPage(),
UnsafeDeviceScreen.routeName: (_) => const UnsafeDeviceScreen(),
SwipeSuccessView.routeName: (_) => const SwipeSuccessView(),
SwipeHistoryView.routeName: (_) => const SwipeHistoryView(),
SwipeHistoryView.routeName: (_) => const SwipeHistoryView(),
///todo deleted
//old.LandPage.id: (_) => const old.LandPage(),
LandPage.routeName: (_) => const LandPage(),

@ -6,6 +6,7 @@ import 'package:test_sa/extensions/text_extensions.dart';
import 'package:test_sa/extensions/widget_extensions.dart';
import 'package:test_sa/new_views/app_style/app_color.dart';
import 'package:test_sa/new_views/pages/login_page.dart';
import 'package:test_sa/new_views/swipe_module/swipe_history_view.dart';
import 'package:test_sa/views/app_style/sizing.dart';
import 'package:test_sa/views/pages/user/notifications/notifications_page.dart';
@ -75,8 +76,9 @@ class AppDrawer extends StatelessWidget {
// drawerItem("rate_us", context.translation.rateUs, context),
// 18.height,
drawerItem("setting", context.translation.settings, context).onPress(() => Navigator.of(context).pushNamed(SettingsPage.id)),
// 18.height,
// drawerItem("report", context.translation.reportBg, context) /*.onPress(() => Navigator.of(context).pushNamed(ReportBugPage.id))*/,
18.height,
if(userProvider.user!=null&&!userProvider.user.employeeIsHMG)
drawerItem("swipe", "Swipe History", context) .onPress(() => Navigator.of(context).pushNamed(SwipeHistoryView.routeName)),
// 18.height,
// drawerItem("whats_new", context.translation.whatsNew, context),
],

@ -15,7 +15,6 @@ import 'package:test_sa/new_views/app_style/app_color.dart';
import 'package:test_sa/new_views/forget_password_module/reset_password_view.dart';
class ForgetPasswordVerifyOtpView extends StatefulWidget {
static const String routeName = "/verify_otp";
Map<String,dynamic> data={};
ForgetPasswordVerifyOtpView({Key key,@required this.data}) : super(key: key);

@ -99,11 +99,11 @@ class _ResetPasswordViewState extends State<ResetPasswordView> {
},
),
),
138.height,
AppFilledButton(label: context.translation.resetPassword, maxWidth: true, onPressed: () => _resetPassword(context: context)),
],
),
).center.expanded,
AppFilledButton(label: context.translation.resetPassword, maxWidth: true, onPressed: () => _resetPassword(context: context)),
],
).paddingOnly(start: 16, end: 16, bottom: 24, top: 24),
),

@ -1,6 +1,7 @@
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:nfc_manager/nfc_manager.dart';
import 'package:provider/provider.dart';
import 'package:test_sa/controllers/notification/firebase_notification_manger.dart';
import 'package:test_sa/controllers/notification/notification_manger.dart';
@ -12,11 +13,14 @@ import 'package:test_sa/extensions/context_extension.dart';
import 'package:test_sa/extensions/int_extensions.dart';
import 'package:test_sa/extensions/text_extensions.dart';
import 'package:test_sa/extensions/widget_extensions.dart';
import 'package:test_sa/models/enums/user_types.dart';
import 'package:test_sa/models/user.dart';
import 'package:test_sa/new_views/app_style/app_color.dart';
import 'package:test_sa/new_views/pages/land_page/dashboard_fragments/progress_fragment.dart';
import 'package:test_sa/new_views/pages/land_page/dashboard_fragments/recent_activites_fragment.dart';
import 'package:test_sa/new_views/pages/land_page/dashboard_fragments/requests_fragment.dart';
import 'package:test_sa/new_views/swipe_module/circular_animated_widget.dart';
import 'package:test_sa/new_views/swipe_module/utils/swipe_general_utils.dart';
import 'package:test_sa/views/pages/user/notifications/notifications_page.dart';
class DashboardPage extends StatefulWidget {
@ -61,7 +65,8 @@ class _DashboardPageState extends State<DashboardPage> {
isFCM = false;
}
final user = Provider.of<UserProvider>(context, listen: false).user;
UserProvider userProvider = Provider.of<UserProvider>(context, listen: false);
final user = userProvider.user;
final setting = Provider.of<SettingProvider>(context, listen: false);
return Scaffold(
appBar: AppBar(
@ -156,43 +161,85 @@ class _DashboardPageState extends State<DashboardPage> {
],
).paddingOnly(start: 16, end: 16),
),
body: Column(
crossAxisAlignment: CrossAxisAlignment.start,
body: Stack(
children: [
Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Text(
context.translation.welcome,
style: AppTextStyles.heading6.copyWith(color: context.isDark ? AppColor.neutral10 : AppColor.neutral20),
),
Text(
user?.username ?? "",
style: AppTextStyles.heading2.copyWith(color: context.isDark ? AppColor.neutral30 : AppColor.neutral50, fontWeight: FontWeight.w600),
),
24.height,
Row(
Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
indicatorView(0),
3.width,
indicatorView(1),
3.width,
indicatorView(2),
10.width,
"0${_currentPage + 1}/03".tinyFont(context).custom(fontWeight: FontWeight.w500, color: context.isDark ? AppColor.neutral30 : AppColor.neutral60),
Text(
context.translation.welcome,
style: AppTextStyles.heading6.copyWith(color: context.isDark ? AppColor.neutral10 : AppColor.neutral20),
),
Text(
user?.username ?? "",
style: AppTextStyles.heading2.copyWith(color: context.isDark ? AppColor.neutral30 : AppColor.neutral50, fontWeight: FontWeight.w600),
),
24.height,
Row(
children: [
indicatorView(0),
3.width,
indicatorView(1),
3.width,
indicatorView(2),
10.width,
"0${_currentPage + 1}/03".tinyFont(context).custom(fontWeight: FontWeight.w500, color: context.isDark ? AppColor.neutral30 : AppColor.neutral60),
],
),
],
),
],
).paddingOnly(start: 16, end: 16, top: 8, bottom: 8),
PageView(
onPageChanged: (index) => setState(() => _currentPage = index),
children: [
const RequestsFragment(),
ProgressFragment(),
RecentActivitiesFragment(),
).paddingOnly(start: 16, end: 16, top: 8, bottom: 8),
PageView(
onPageChanged: (index) => setState(() => _currentPage = index),
children: [
const RequestsFragment(),
ProgressFragment(),
RecentActivitiesFragment(),
],
).expanded,
],
).expanded,
),
if (user != null && !user.employeeIsHMG)
Positioned(
right: user.type == UsersTypes.engineer ? 20.toScreenWidth : null,
left: user.type != UsersTypes.engineer ? 20.toScreenWidth : null,
bottom: 20.toScreenHeight,
child: GestureDetector(
onTap: () async {
bool isNfcSupported = await NfcManager.instance.isAvailable();
SwipeGeneralUtils.instance.showSwipeTypeBottomSheetSheet(isNfcSupported: isNfcSupported);
},
child: CircularAnimatedContainer(child: Container(
width: 100.toScreenWidth,
height: 100.toScreenHeight,
decoration: BoxDecoration(
shape: BoxShape.circle,
color: AppColor.white,
border: Border.all(color: AppColor.primary80.withOpacity(0.5), width: 2),
),
child: Consumer<UserProvider>(
builder: (context, userProvider,child) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
'swipe'.toSvgAsset(width: 32, height: 32),
8.height,
Text(
("${context.translation.checkIn}\n${userProvider.swipeTransactionModel != null && userProvider.swipeTransactionModel.swipeTime != null ? SwipeGeneralUtils.instance.formatTimeOnly(userProvider.swipeTransactionModel.swipeTime) : '--:--'}"),
style: AppTextStyles.bodyText2.copyWith(color: AppColor.neutral80, fontWeight: FontWeight.w500, fontFamily: "Poppins"),
),
],
);
}
),
),),
),
),
],
),
);

@ -16,6 +16,7 @@ import 'package:test_sa/new_views/common_widgets/app_filled_button.dart';
import 'package:test_sa/new_views/pages/land_page/calendar_page.dart';
import 'package:test_sa/new_views/pages/land_page/my_request/my_requests_page.dart';
import 'package:test_sa/new_views/pages/settings_page.dart';
import 'package:test_sa/new_views/swipe_module/circular_animated_widget.dart';
import 'package:test_sa/new_views/swipe_module/swipe_success_view.dart';
import 'package:test_sa/new_views/swipe_module/utils/swipe_general_utils.dart';
import 'package:test_sa/views/widgets/equipment/single_device_picker.dart';
@ -109,10 +110,11 @@ class _LandPageState extends State<LandPage> {
Widget build(BuildContext context) {
if (_userProvider == null) {
_userProvider = Provider.of<UserProvider>(context, listen: false);
// if (_userProvider.isUserConfirmSwipe) {
// if (!_userProvider.user.employeeIsHMG) {
// checkNfcSupported();
// }
if (_userProvider.user!=null&&!_userProvider.user.employeeIsHMG) {
print('i am called.');
_userProvider.getSwipeLastTransaction(userId: _userProvider.user.userID);
}
_pages = <Widget>[
DashboardPage(onDrawerPress: (() {
_scaffoldKey.currentState.isDrawerOpen ? _scaffoldKey.currentState.closeDrawer() : _scaffoldKey.currentState.openDrawer();
@ -142,76 +144,38 @@ class _LandPageState extends State<LandPage> {
return false;
},
child: Consumer<UserProvider>(builder: (context, userProvider, child) {
return Stack(
children: [
Scaffold(
key: _scaffoldKey,
drawer: const AppDrawer(),
body: _pages[currentPageIndex],
bottomNavigationBar: AppBottomNavigationBar(
selectedIndex: currentPageIndex,
onPressed: (index) {
bool isEngineer = _userProvider.user.type == UsersTypes.engineer;
return Scaffold(
key: _scaffoldKey,
drawer: const AppDrawer(),
body: _pages[currentPageIndex],
bottomNavigationBar: AppBottomNavigationBar(
selectedIndex: currentPageIndex,
onPressed: (index) {
bool isEngineer = _userProvider.user.type == UsersTypes.engineer;
if (index == (isEngineer ? 4 : 3)) {
showModalBottomSheet(
context: context,
useSafeArea: true,
backgroundColor: Colors.transparent,
builder: (context) => const ContactUsBottomSheet(),
);
} else {
setState(() {
currentPageIndex = index;
});
if (index == 1) {
setState(() {
showAppbar = false;
});
} else {
setState(() {
showAppbar = true;
});
}
}
},
),
),
if (userProvider.user != null && !userProvider.user.employeeIsHMG)
Positioned(
right: _userProvider.user.type == UsersTypes.engineer ? 20.toScreenWidth : null,
left: _userProvider.user.type != UsersTypes.engineer ? 20.toScreenWidth : null,
bottom: 130.toScreenHeight,
child: GestureDetector(
onTap: () async {
isNfcSupported = await NfcManager.instance.isAvailable();
SwipeGeneralUtils.showSwipeTypeBottomSheetSheet(context: context, isNfcSupported: isNfcSupported);
},
child: CircularAnimatedContainer(child: Container(
width: 100.toScreenWidth,
height: 100.toScreenHeight,
decoration: BoxDecoration(
shape: BoxShape.circle,
color: AppColor.white,
border: Border.all(color: AppColor.primary80.withOpacity(0.5), width: 2),
),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
'swipe'.toSvgAsset(width: 32, height: 32),
8.height,
Text(
("${context.translation.checkIn}\n${userProvider.swipeTransactionModel != null && userProvider.swipeTransactionModel.swipeTime != null ? SwipeGeneralUtils.formatTimeOnly(userProvider.swipeTransactionModel.swipeTime) : '--:--'}"),
style: AppTextStyles.bodyText2.copyWith(color: AppColor.neutral80, fontWeight: FontWeight.w500, fontFamily: "Poppins"),
),
],
),
),),
),
),
],
if (index == (isEngineer ? 4 : 3)) {
showModalBottomSheet(
context: context,
useSafeArea: true,
backgroundColor: Colors.transparent,
builder: (context) => const ContactUsBottomSheet(),
);
} else {
setState(() {
currentPageIndex = index;
});
if (index == 1) {
setState(() {
showAppbar = false;
});
} else {
setState(() {
showAppbar = true;
});
}
}
},
),
);
}),
);

@ -164,8 +164,7 @@ class _LoginPageState extends State<LoginPage> {
(await SharedPreferences.getInstance()).remove(ASettings.localAuth);
await _settingProvider.setRememberMe(_user.userName, _user.password, rememberMe);
/// The below line for the new design
// Navigator.pushNamed(context, LandPage.routeName);
Navigator.pushNamed(context, LandPage.routeName);
} else {
Fluttertoast.showToast(msg: _userProvider.user?.message ?? context.translation.failedToCompleteRequest);

@ -0,0 +1,164 @@
import 'package:flutter/animation.dart';
import 'package:flutter/material.dart';
import 'package:test_sa/extensions/int_extensions.dart';
import 'package:test_sa/new_views/app_style/app_color.dart';
class CircularAnimationWithProgressIndicator extends StatefulWidget {
Widget child;
CircularAnimationWithProgressIndicator({Key key, this.child}) : super(key: key);
@override
_CircularAnimationWithProgressIndicatorState createState() =>
_CircularAnimationWithProgressIndicatorState();
}
class _CircularAnimationWithProgressIndicatorState
extends State<CircularAnimationWithProgressIndicator>
with SingleTickerProviderStateMixin {
AnimationController _controller;
@override
void initState() {
super.initState();
// Animation controller for progress indicator
_controller = AnimationController(
vsync: this,
duration: const Duration(seconds: 40), // Duration of one full rotation
)..repeat(); // Repeat animation continuously
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Center(
child: Stack(
alignment: Alignment.center,
children: [
// Animated CircularProgressIndicator
AnimatedBuilder(
animation: _controller,
builder: (context, child) {
return Transform.rotate(
angle: _controller.value * 2 * 3.1416, // Full rotation
child: child,
);
},
child: SizedBox(
width: 100.toScreenHeight,
height: 100.toScreenWidth,
child: const CircularProgressIndicator(
strokeWidth: 3.0,
backgroundColor: AppColor.primary30,
value: null, // Infinite animation
),
),
),
// Static container in the center
widget.child?? const SizedBox(),
],
),
);
}
}
class CircularAnimatedContainer extends StatefulWidget {
Widget child;
CircularAnimatedContainer({Key key, @required this.child}) : super(key: key);
@override
_CircularAnimatedContainerState createState() => _CircularAnimatedContainerState();
}
class _CircularAnimatedContainerState extends State<CircularAnimatedContainer>
with SingleTickerProviderStateMixin {
AnimationController _controller;
Animation<double> _animation;
@override
void initState() {
super.initState();
_controller = AnimationController(
duration: const Duration(seconds: 2),
vsync: this,
)..repeat();
_animation = CurvedAnimation(
parent: _controller,
curve: Curves.easeInOut, // Applies the ease-in-out effect
);
// Repeats animation
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Center(
child: Stack(
alignment: Alignment.center,
children: [
widget.child,
AnimatedBuilder(
animation: _animation,
builder: (context, child) {
return CustomPaint(
painter: CircularProgressPainter(
progress: _animation.value),
size: Size(100.toScreenHeight, 100.toScreenWidth),
);
},
),
],
),
);
}
}
class CircularProgressPainter extends CustomPainter {
final double progress;
CircularProgressPainter({@required this.progress});
@override
void paint(Canvas canvas, Size size) {
final Paint paint = Paint()
..color = AppColor.primary80
..style = PaintingStyle.stroke
..strokeWidth = 3
..strokeCap = StrokeCap.round;
final center = Offset(size.width / 2, size.height / 2);
final radius = size.width / 2.05;
final double startAngle = 2.5 * 3.141592653589793 * progress;
final double sweepAngle = 2 * 3.141592653589793 * progress;
// const double startAngle = -90 * (3.141592653589793 / 180);
// final double sweepAngle = 2.05 * 3.141592653589793 * progress;
canvas.drawArc(
Rect.fromCircle(center: center, radius: radius),
startAngle,
sweepAngle,
false,
paint,
);
}
@override
bool shouldRepaint(covariant CustomPainter oldDelegate) {
return true;
}
}

@ -14,7 +14,7 @@ class _QrScannerDialogState extends State<QrScannerDialog> {
Barcode result;
QRViewController controller;
bool isPicked = false;
//need to check if camera permission is not given...
@override
Widget build(BuildContext context) {
return Scaffold(
@ -31,15 +31,6 @@ class _QrScannerDialogState extends State<QrScannerDialog> {
onQRViewCreated: _onQRViewCreated,
),
),
// Expanded(
// flex: 1,
// child: Center(
// child: (result != null)
// ? Text(
// 'Barcode Type: ${result!.format} Data: ${result!.code}')
// : Text('Scan a code'),
// ),
// ),
Padding(
padding: const EdgeInsets.all(12.0),
child: AppFilledButton(

@ -0,0 +1,47 @@
class SwipeHistory {
final int id;
final String swipeTypeName;
final String userName;
final String siteName;
final String pointName;
final String swipeTime;
final bool isSuccess;
final String errorMessage;
SwipeHistory({
this.id,
this.swipeTypeName,
this.userName,
this.siteName,
this.pointName,
this.swipeTime,
this.isSuccess,
this.errorMessage,
});
factory SwipeHistory.fromJson(Map<String, dynamic> json) {
return SwipeHistory(
id: json['id'],
swipeTypeName: json['swipeTypeName'],
userName: json['userName'],
siteName: json['siteName'],
pointName: json['pointName'],
swipeTime: json['swipeTime']!=null? DateTime.parse(json['swipeTime']).toIso8601String():'',
isSuccess: json['isSuccess'],
errorMessage: json['errorMessage'],
);
}
Map<String, dynamic> toJson() {
return {
'id': id,
'swipeTypeName': swipeTypeName,
'userName': userName,
'siteName': siteName,
'pointName': pointName,
'swipeTime': swipeTime,
'isSuccess': isSuccess,
'errorMessage': errorMessage,
};
}
}

@ -0,0 +1,189 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:test_sa/controllers/providers/api/user_provider.dart';
import 'package:test_sa/extensions/context_extension.dart';
import 'package:test_sa/extensions/int_extensions.dart';
import 'package:test_sa/extensions/string_extensions.dart';
import 'package:test_sa/extensions/text_extensions.dart';
import 'package:test_sa/extensions/widget_extensions.dart';
import 'package:test_sa/new_views/app_style/app_color.dart';
import 'package:test_sa/new_views/common_widgets/app_filled_button.dart';
import 'package:test_sa/new_views/common_widgets/default_app_bar.dart';
import 'package:test_sa/views/widgets/date_and_time/date_picker.dart';
import 'package:test_sa/views/widgets/loaders/lazy_loading.dart';
import 'package:test_sa/views/widgets/loaders/no_item_found.dart';
import 'models/swipe_transaction_history.dart';
class SwipeHistoryView extends StatefulWidget {
static const routeName = '/swipe_list_view';
const SwipeHistoryView({Key key}) : super(key: key);
@override
State<SwipeHistoryView> createState() => _SwipeHistoryViewState();
}
class _SwipeHistoryViewState extends State<SwipeHistoryView> {
DateTime dateFrom = DateTime.now();
DateTime dateTo = DateTime.now();
UserProvider _userProvider;
@override
void initState() {
getSwipeHistory();
super.initState();
}
void getSwipeHistory () {
_userProvider = Provider.of<UserProvider>(context,listen:false);
WidgetsBinding.instance.addPostFrameCallback((_) async {
await _userProvider.getSwipeTransactionHistory(userId: _userProvider.user.userID,dateFrom: dateFrom,dateTo: dateTo);
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: const DefaultAppBar(title: 'Swipe History',),
body: Column(
crossAxisAlignment:CrossAxisAlignment.start,
children: [
8.height,
Row(
children: [
ADatePicker(
label: context.translation.from,
date: dateFrom,
from: DateTime(DateTime.now().year - 5, DateTime.now().month, DateTime.now().day),
formatDateWithTime: true,
onDatePicker: (selectedDate) {
if (selectedDate != null) {
showTimePicker(
context: context,
initialTime: TimeOfDay.now(),
).then((selectedTime) {
// Handle the selected date and time here.
if (selectedTime != null) {
DateTime selectedDateTime = DateTime(
selectedDate.year,
selectedDate.month,
selectedDate.day,
selectedTime.hour,
selectedTime.minute,
);
if (selectedDateTime != null) {
setState(() {
dateFrom = selectedDateTime;
});
}
}
});
}
},
).expanded,
8.width,
ADatePicker(
label: context.translation.to,
date: dateTo,
from: DateTime(DateTime.now().year - 5, DateTime.now().month, DateTime.now().day),
formatDateWithTime: true,
onDatePicker: (selectedDate) {
if (selectedDate != null) {
showTimePicker(
context: context,
initialTime: TimeOfDay.now(),
).then((selectedTime) {
// Handle the selected date and time here.
if (selectedTime != null) {
DateTime selectedDateTime = DateTime(
selectedDate.year,
selectedDate.month,
selectedDate.day,
selectedTime.hour,
selectedTime.minute,
);
if (selectedDateTime != null) {
setState(() {
dateTo = selectedDateTime;
});
}
}
});
}
},
).expanded,
],
),
12.height,
AppFilledButton(label: context.translation.search, maxWidth: false, onPressed: getSwipeHistory),
8.height,
Divider(thickness: 2,),
Consumer<UserProvider>(
builder: (context, snapshot,child) {
return SwipeHistoryList(snapshot.swipeHistory ?? [], snapshot.isLoading).expanded;
}
),
],
).paddingAll(20),
);
}
}
class SwipeHistoryList extends StatelessWidget {
List<SwipeHistory> list;
bool isLoading;
SwipeHistoryList(this.list, this.isLoading, {Key key}) : super(key: key);
@override
Widget build(BuildContext context) {
return (list.isEmpty && !isLoading)
? NoItemFound(message: context.translation.noDataFound)
: ListView.separated(
padding: EdgeInsets.only(top: 12.toScreenHeight),
itemBuilder: (cxt, index) {
if (isLoading) return const SizedBox().toRequestShimmer(cxt, isLoading);
return SwipeHistoryCard(list[index]);
},
separatorBuilder: (cxt, index) => 12.height,
itemCount: isLoading ? 6 : list.length);
}
}
class SwipeHistoryCard extends StatelessWidget {
final SwipeHistory swipeHistory;
final bool showShadow;
const SwipeHistoryCard(this.swipeHistory, {Key key, this.showShadow = true}) : super(key: key);
@override
Widget build(BuildContext context) {
return Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(swipeHistory.swipeTime.toServiceRequestDetailsFormat, textAlign: TextAlign.end, style: AppTextStyles.tinyFont.copyWith(color: context.isDark ? AppColor.neutral10 : AppColor.neutral50)),
],
),
8.height,
'${context.translation.swipeTypeName}: ${swipeHistory.swipeTypeName?.cleanupWhitespace?.capitalizeFirstOfEach}'.bodyText(context),
'${context.translation.userName}: ${swipeHistory.userName}'.bodyText(context),
'${context.translation.siteName}: ${swipeHistory.siteName}'.bodyText(context),
'${context.translation.pointName}: ${swipeHistory.pointName}'.bodyText(context),
8.height,
],
).toShadowContainer(context, showShadow: showShadow);
}
}

@ -2,7 +2,9 @@ import 'package:flutter/material.dart';
import 'package:test_sa/extensions/context_extension.dart';
import 'package:test_sa/extensions/int_extensions.dart';
import 'package:test_sa/extensions/text_extensions.dart';
import 'package:test_sa/extensions/widget_extensions.dart';
import 'package:test_sa/new_views/app_style/app_color.dart';
import 'package:test_sa/new_views/common_widgets/app_filled_button.dart';
class SwipeSuccessView extends StatelessWidget {
static const routeName = '/swipe_success_view';
@ -11,182 +13,32 @@ class SwipeSuccessView extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment:CrossAxisAlignment.center,
children: [
'swipe_success'.toSvgAsset(),
17.height,
context.translation.successful.heading4(context).custom(color: AppColor.neutral80),
8.height,
context.translation.youHaveSuccessfullyMarkedYourAttendance.bodyText2(context).custom(color: AppColor.white20),
],
),
),
);
}
}
class CircularAnimationWithProgressIndicator extends StatefulWidget {
Widget child;
CircularAnimationWithProgressIndicator({Key key, this.child}) : super(key: key);
@override
_CircularAnimationWithProgressIndicatorState createState() =>
_CircularAnimationWithProgressIndicatorState();
}
class _CircularAnimationWithProgressIndicatorState
extends State<CircularAnimationWithProgressIndicator>
with SingleTickerProviderStateMixin {
AnimationController _controller;
@override
void initState() {
super.initState();
// Animation controller for progress indicator
_controller = AnimationController(
vsync: this,
duration: const Duration(seconds: 40), // Duration of one full rotation
)..repeat(); // Repeat animation continuously
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Center(
child: Stack(
alignment: Alignment.center,
children: [
// Animated CircularProgressIndicator
AnimatedBuilder(
animation: _controller,
builder: (context, child) {
return Transform.rotate(
angle: _controller.value * 2 * 3.1416, // Full rotation
child: child,
);
},
child: SizedBox(
width: 100.toScreenHeight,
height: 100.toScreenWidth,
child: const CircularProgressIndicator(
strokeWidth: 3.0,
backgroundColor: AppColor.primary30,
value: null, // Infinite animation
),
),
),
// Static container in the center
widget.child?? const SizedBox(),
],
),
);
}
}
class CircularAnimatedContainer extends StatefulWidget {
Widget child;
CircularAnimatedContainer({Key key, @required this.child}) : super(key: key);
@override
_CircularAnimatedContainerState createState() => _CircularAnimatedContainerState();
}
class _CircularAnimatedContainerState extends State<CircularAnimatedContainer>
with SingleTickerProviderStateMixin {
AnimationController _controller;
Animation<double> _animation;
@override
void initState() {
super.initState();
_controller = AnimationController(
duration: const Duration(seconds: 2),
vsync: this,
)..repeat();
_animation = CurvedAnimation(
parent: _controller,
curve: Curves.easeInOut, // Applies the ease-in-out effect
);
// Repeats animation
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Center(
child: Stack(
alignment: Alignment.center,
body: Column(
children: [
widget.child,
AnimatedBuilder(
animation: _animation,
builder: (context, child) {
return CustomPaint(
painter: CircularProgressPainter(
progress: _animation.value),
size: Size(100.toScreenHeight, 100.toScreenWidth),
);
Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment:CrossAxisAlignment.center,
children: [
'swipe_success'.toSvgAsset(),
17.height,
context.translation.successful.heading4(context).custom(color: AppColor.neutral80),
8.height,
context.translation.youHaveSuccessfullyMarkedYourAttendance.bodyText2(context).custom(color: AppColor.white20),
],
).expanded,
AppFilledButton(
label: 'Close',
maxWidth: true,
onPressed:(){
Navigator.pop(context);
},
),
],
),
).paddingOnly(start: 20, end: 20, bottom: 16),
);
}
}
class CircularProgressPainter extends CustomPainter {
final double progress;
CircularProgressPainter({@required this.progress});
@override
void paint(Canvas canvas, Size size) {
final Paint paint = Paint()
..color = AppColor.primary80
..style = PaintingStyle.stroke
..strokeWidth = 3
..strokeCap = StrokeCap.round;
final center = Offset(size.width / 2, size.height / 2);
final radius = size.width / 2.05;
// final double startAngle = 2 * 3.141592653589793 * progress;
final double sweepAngle = 2 * 3.141592653589793 * progress;
const double startAngle = -90 * (3.141592653589793 / 180);
// final double sweepAngle = 2.05 * 3.141592653589793 * progress;
canvas.drawArc(
Rect.fromCircle(center: center, radius: radius),
startAngle,
sweepAngle,
false,
paint,
);
}
@override
bool shouldRepaint(covariant CustomPainter oldDelegate) {
return true;
}
}
// ClipOval(
// child: Container(

@ -1,9 +1,7 @@
import 'dart:async';
import 'dart:developer';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:geolocator/geolocator.dart';
import 'package:google_api_availability/google_api_availability.dart';
import 'package:huawei_location/huawei_location.dart';
@ -30,30 +28,16 @@ import 'package:test_sa/new_views/swipe_module/swipe_success_view.dart';
import 'package:test_sa/new_views/swipe_module/utils/location_utils.dart';
class SwipeGeneralUtils {
SwipeGeneralUtils._();
static SwipeGeneralUtils instance = SwipeGeneralUtils._();
static bool _isLoadingVisible = false;
static bool get isLoading => _isLoadingVisible;
static void showToast(String message, {bool longDuration = true}) {
Fluttertoast.showToast(
msg: message,
toastLength: longDuration ? Toast.LENGTH_LONG : Toast.LENGTH_SHORT,
gravity: ToastGravity.BOTTOM,
timeInSecForIosWeb: 1,
backgroundColor: Colors.black54,
textColor: Colors.white,
fontSize: 13.0);
}
static dynamic getNotNullValue(List<dynamic> list, int index) {
try {
return list[index];
} catch (ex) {
return null;
}
}
static void markFakeAttendance(dynamic sourceName, String lat, String long, @required BuildContext context) async {
void markFakeAttendance(dynamic sourceName, String lat, String long, @required BuildContext context) async {
showLoading(context);
try {
hideLoading(navigatorKey.currentState.overlay.context);
@ -65,24 +49,11 @@ class SwipeGeneralUtils {
}
}
static int stringToHex(String colorCode) {
try {
return int.parse(colorCode.replaceAll("#", "0xff"));
} catch (ex) {
return (0xff000000);
}
}
static Future delay(int millis) async {
return await Future.delayed(Duration(milliseconds: millis));
}
static void showLoading(BuildContext context) {
void showLoading(BuildContext context) {
WidgetsBinding.instance.addPostFrameCallback((_) {
_isLoadingVisible = true;
// showDialog(context: context, barrierDismissible: false, builder: (context) => const AppLazyLoading());
showDialog(
context: context,
barrierColor: Colors.black.withOpacity(0.5),
@ -94,7 +65,7 @@ class SwipeGeneralUtils {
});
}
static void hideLoading(BuildContext context) {
void hideLoading(BuildContext context) {
if (_isLoadingVisible) {
_isLoadingVisible = false;
Navigator.of(context).pop();
@ -107,81 +78,24 @@ class SwipeGeneralUtils {
return prefs.getString(key) ?? "";
}
static Future<bool> removeStringFromPrefs(String key) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
return prefs.remove(key);
}
static Future<bool> saveStringFromPrefs(String key, String value) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
return await prefs.setString(key, value);
}
// static void handleException(dynamic exception, cxt, Function(String)? onErrorMessage) {
// String errorMessage;
// if (exception.error.errorType != null && exception.error.errorType == 4) {
// Navigator.pushNamedAndRemoveUntil(cxt, AppRoutes.appUpdateScreen, (_) => false, arguments: exception.error?.errorMessage);
// } else {
// if (exception is APIException) {
// if (exception.message == APIException.UNAUTHORIZED) {
// return;
// } else {
// errorMessage = exception.error?.errorMessage ?? exception.message;
// }
// } else {
// errorMessage = APIException.UNKNOWN;
// }
// if (onErrorMessage != null) {
// onErrorMessage(errorMessage);
// } else {
// if (!AppState().isAuthenticated) {
// showDialog(
// barrierDismissible: false,
// context: cxt,
// builder: (cxt) => ConfirmDialog(
// message: errorMessage,
// onTap: () {
// Navigator.pushNamedAndRemoveUntil(cxt, AppRoutes.login, (Route<dynamic> route) => false);
// },
// onCloseTap: () {},
// ),
// );
// } else {
// if (cxt != null) {
// confirmDialog(cxt, errorMessage);
// } else {
// showToast(errorMessage);
// }
// }
// }
// }
// }
//
// static Future showErrorDialog({required BuildContext context, required VoidCallback onOkTapped, required String message}) async {
// return showDialog(
// context: context,
// builder: (BuildContext context) => ConfirmDialog(
// message: message,
// onTap: onOkTapped,
// ),
// );
// }
//
static void confirmDialog(cxt, String message, {VoidCallback onTap}) {
void confirmDialog(cxt, String message, {VoidCallback onTap}) {
showDialog(
context: cxt,
builder: (BuildContext cxt) => ConfirmDialog(message: message, onTap: onTap),
);
}
static void showErrorDialog({String message, @required BuildContext context}) {
void showErrorDialog({String message, @required BuildContext context}) {
showDialog(
context: context,
builder: (context) => ConfirmDialog(message: message, title: 'Error', onTap: () => Navigator.pop(context)),
);
}
static void showMDialog(context, {Widget child, Color backgroundColor, bool isDismissable = true, bool isBusniessCard = false}) async {
void showMDialog(context, {Widget child, Color backgroundColor, bool isDismissable = true, bool isBusniessCard = false}) async {
return showDialog(
context: context,
barrierDismissible: isDismissable,
@ -201,7 +115,7 @@ class SwipeGeneralUtils {
);
}
static Widget attendanceTypeCard(String title, String icon, bool isEnabled, VoidCallback onPress, BuildContext context) {
Widget attendanceTypeCard(String title, String icon, bool isEnabled, VoidCallback onPress, BuildContext context) {
return Container(
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
@ -223,47 +137,10 @@ class SwipeGeneralUtils {
onPress();
},
);
// return Container(
// decoration: BoxDecoration(
// borderRadius: BorderRadius.circular(15),
// color: isEnabled ? null : Colors.grey.withOpacity(.5),
// gradient: isEnabled
// ? const LinearGradient(
// transform: GradientRotation(.64),
// begin: Alignment.topRight,
// end: Alignment.bottomLeft,
// colors: [
// //ToDo set Colors according to design provided by designer...
// Colors.blue,
// Colors.green,
// // AppColor.gradiantEndColor,
// // MyColors.gradiantStartColor,
// ],
// )
// : null,
// ),
// clipBehavior: Clip.antiAlias,
// padding: const EdgeInsets.only(left: 10, right: 10, top: 14, bottom: 14),
// child: Column(
// crossAxisAlignment: CrossAxisAlignment.start,
// children: [
// // SvgPicture.asset(image, color: Colors.white, alignment: Alignment.topLeft).expanded,
// Icon(iconData, color: isEnabled ? AppColor.black35 : Colors.grey),
// title.heading6(context),
// // title.toText17(isBold: true, color: Colors.white),
// ],
// ),
// ).onPress(
// () {
// log('isEnabled is ${!isEnabled}');
// if (!isEnabled) return;
// onPress();
// },
// );
}
//huawei permission part....
static void getHuaweiCurrentLocation({SwipeTypeEnum attendanceType, BuildContext context}) async {
void getHuaweiCurrentLocation({SwipeTypeEnum attendanceType, BuildContext context}) async {
try {
showLoading(context);
FusedLocationProviderClient locationService = FusedLocationProviderClient()..initFusedLocationService();
@ -284,41 +161,6 @@ class SwipeGeneralUtils {
requestCode = 0;
},
);
// locationService.checkLocationSettings(locationSettingsRequest).then((settings) async {
// await locationService.getLastLocation().then((value) {
// if (value.latitude == null || value.longitude == null) {
// showDialog(
// context: context,
// builder: (BuildContext cxt) => ConfirmDialog(
// message: "Unable to get your location, Please check your location settings & try again.",
// onTap: () {
// Navigator.pop(context);
// },
// ),
// );
// } else {
// if (attendanceType == "QR") {
// performQrCodeAttendance(widget.model, lat: value.latitude.toString() ?? "", lng: value.longitude.toString() ?? "");
// }
// if (attendanceType == "WIFI") {
// performWifiAttendance(widget.model, lat: value.latitude.toString() ?? "", lng: value.longitude.toString() ?? "");
// }
// if (attendanceType == "NFC") {
// performNfcAttendance(widget.model, lat: value.latitude.toString() ?? "", lng: value.longitude.toString() ?? "");
// }
// }
// }).catchError((error) {
// log("HUAWEI LOCATION getLastLocation ERROR!!!!!");
// log(error);
// });
// }).catchError((error) {
// log("HUAWEI LOCATION checkLocationSettings ERROR!!!!!");
// log(error);
// if (error.code == "LOCATION_SETTINGS_NOT_AVAILABLE") {
// // Location service not enabled.
// }
// });
} catch (error) {
log("HUAWEI LOCATION ERROR!!!!!");
log('$error');
@ -327,14 +169,14 @@ class SwipeGeneralUtils {
}
}
static Future<bool> requestPermissions() async {
Future<bool> requestPermissions() async {
var result = await [
Permission.location,
].request();
return (result[Permission.location] == PermissionStatus.granted || result[Permission.locationAlways] == PermissionStatus.granted);
}
static void checkHuaweiLocationPermission({SwipeTypeEnum attendanceType, BuildContext context}) async {
void checkHuaweiLocationPermission({SwipeTypeEnum attendanceType, BuildContext context}) async {
// Permission_Handler permissionHandler = PermissionHandler();
LocationUtilities.isEnabled((bool isEnabled) async {
if (isEnabled) {
@ -392,7 +234,7 @@ class SwipeGeneralUtils {
// }
}
static void handleSwipeOperation({@required SwipeTypeEnum swipeType, double lat, double lang, BuildContext context}) {
void handleSwipeOperation({@required SwipeTypeEnum swipeType, double lat, double lang, BuildContext context}) {
switch (swipeType) {
case SwipeTypeEnum.NFC:
handleNfcAttendance(latitude: lat, longitude: lang, context: context);
@ -406,12 +248,13 @@ class SwipeGeneralUtils {
}
}
static String formatTimeOnly(DateTime dateTime) {
String formatTimeOnly(DateTime dateTime) {
return DateFormat.Hms().format(dateTime);
}
static Future<void> performQrCodeAttendance({double latitude, double longitude, BuildContext context}) async {
Future<void> performQrCodeAttendance({double latitude, double longitude, BuildContext context}) async {
UserProvider userProvider = Provider.of<UserProvider>(context, listen: false);
var qrCodeValue = await Navigator.of(context).push(
MaterialPageRoute(
builder: (BuildContext context) => QrScannerDialog(),
@ -420,40 +263,34 @@ class SwipeGeneralUtils {
if (qrCodeValue != null) {
showLoading(context);
try {
//test model..
final swipeModel = Swipe(
swipeTypeValue: SwipeTypeEnum.QR.getIntFromSwipeTypeEnum(),
value: '456',
latitude: 24.70865415364271,
longitude: 46.66600861881879,
value: qrCodeValue,
latitude: latitude,
longitude: longitude,
);
// final swipeModel = Swipe(
// swipeTypeValue: SwipeTypeEnum.QR.getIntFromSwipeTypeEnum(),
// value: qrCodeValue,
// latitude: latitude,
// longitude: longitude,
// );
log('model i got to scan qr is ${swipeModel.toJson()}');
final swipeResponse = await userProvider.makeSwipe(model: swipeModel);
log('response of swipe is ${swipeResponse.toJson()}');
if (swipeResponse.isSuccess) {
hideLoading(context);
Navigator.pushNamed(context, SwipeSuccessView.routeName);
} else {
hideLoading(context);
showDialog(
barrierDismissible: true,
context: context,
builder: (cxt) => ConfirmDialog(
message: swipeResponse.message ?? "",
onTap: () {
Navigator.pop(context);
},
onCloseTap: () {},
),
);
}
await userProvider.makeSwipe(model: swipeModel).then((swipeResponse) {
if (swipeResponse.isSuccess) {
hideLoading(context);
Navigator.pushNamed(context, SwipeSuccessView.routeName);
} else {
hideLoading(context);
showDialog(
barrierDismissible: true,
context: context,
builder: (cxt) => ConfirmDialog(
message: swipeResponse.message ?? "",
onTap: () {
Navigator.pop(context);
},
onCloseTap: () {},
),
);
}
});
} catch (ex) {
log('$ex');
hideLoading(context);
@ -463,7 +300,7 @@ class SwipeGeneralUtils {
}
}
static Future<void> handleNfcAttendance({double latitude = 0, double longitude = 0, BuildContext context}) async {
Future<void> handleNfcAttendance({double latitude = 0, double longitude = 0, BuildContext context}) async {
// UserProvider _userProvider = Provider.of<UserProvider>(context,listen:false);
if (Platform.isIOS) {
@ -477,7 +314,7 @@ class SwipeGeneralUtils {
}
}
static Future<void> _processNfcAttendance(
Future<void> _processNfcAttendance(
String nfcId,
double latitude,
double longitude,
@ -485,21 +322,15 @@ class SwipeGeneralUtils {
) async {
showLoading(context);
try {
// final swipeModel = Swipe(
// swipeTypeValue: SwipeTypeEnum.NFC.getIntFromSwipeTypeEnum(),
// value: nfcId,
// latitude: latitude,
// longitude: longitude,
// );
UserProvider userProvider = Provider.of<UserProvider>(context, listen: false);
//Test model...
final swipeModel = Swipe(
swipeTypeValue: SwipeTypeEnum.NFC.getIntFromSwipeTypeEnum(),
value: '123',
latitude: 24.70865415364271,
longitude: 46.66600861881879,
value: nfcId,
latitude: latitude,
longitude: longitude,
);
UserProvider userProvider = Provider.of<UserProvider>(context, listen: false);
final swipeResponse = await userProvider.makeSwipe(model: swipeModel);
if (swipeResponse.isSuccess) {
@ -511,12 +342,10 @@ class SwipeGeneralUtils {
}
} catch (errSwipeGeneralUtilsor) {
hideLoading(context);
// Uncomment below line for error handling if needed
// handleException(error, context, null);
}
}
static void handleSwipe({SwipeTypeEnum swipeType, @required bool isEnable, @required BuildContext context}) async {
void handleSwipe({SwipeTypeEnum swipeType, @required bool isEnable, @required BuildContext context}) async {
if (!(await isGoogleServicesAvailable())) {
checkHuaweiLocationPermission(attendanceType: swipeType, context: context);
} else {
@ -560,7 +389,7 @@ class SwipeGeneralUtils {
}
}
static void showInfoDialog({@required String message, VoidCallback onTap}) {
void showInfoDialog({@required String message, VoidCallback onTap}) {
showDialog(
context: navigatorKey.currentState.overlay.context,
builder: (BuildContext cxt) => ConfirmDialog(
@ -573,27 +402,31 @@ class SwipeGeneralUtils {
);
}
static List<Widget> availableAttendanceMethodList({@required BuildContext context, @required UserProvider userProvider, @required bool isNfcSupported}) {
List<Widget> availableAttendanceMethodList({@required BuildContext context, @required UserProvider userProvider, @required bool isNfcSupported}) {
List<Widget> availableMethods = [];
if (userProvider.user.enableNFC) {
availableMethods.add(attendanceTypeCard(SwipeTypeEnum.NFC.name, 'nfc_icon', isNfcSupported, () {
Navigator.pop(context);
handleSwipe(swipeType: SwipeTypeEnum.NFC, isEnable: userProvider.user.enableNFC, context: navigatorKey.currentState.overlay.context);
}, context));
}
if (userProvider.user.enableQR) {
availableMethods.add(attendanceTypeCard(SwipeTypeEnum.QR.name, 'qr', userProvider.user.enableQR, () {
Navigator.pop(context);
handleSwipe(swipeType: SwipeTypeEnum.QR, isEnable: userProvider.user.enableQR, context: navigatorKey.currentState.overlay.context);
}, context));
}
if (userProvider.user.enableWifi) {
availableMethods.add(attendanceTypeCard(SwipeTypeEnum.Wifi.name, 'wifi_icon', userProvider.user.enableWifi, () {
Navigator.pop(context);
handleSwipe(swipeType: SwipeTypeEnum.Wifi, isEnable: userProvider.user.enableWifi, context: navigatorKey.currentState.overlay.context);
}, context));
}
return availableMethods;
}
static void showSwipeTypeBottomSheetSheet({@required BuildContext context, @required bool isNfcSupported}) {
void showSwipeTypeBottomSheetSheet({@required bool isNfcSupported}) {
BuildContext context = navigatorKey.currentState.overlay.context;
UserProvider _userProvider = Provider.of<UserProvider>(context, listen: false);
showModalBottomSheet(
@ -623,7 +456,7 @@ class SwipeGeneralUtils {
);
}
static void readNFc({Function(String) onRead}) {
void readNFc({Function(String) onRead}) {
NfcManager.instance.startSession(onDiscovered: (NfcTag tag) async {
MifareUltralight f;
if (Platform.isAndroid) {
@ -640,7 +473,7 @@ class SwipeGeneralUtils {
}
//HUAWEI DECISION MAKING
static Future<bool> isGoogleServicesAvailable() async {
Future<bool> isGoogleServicesAvailable() async {
GooglePlayServicesAvailability availability = await GoogleApiAvailability.instance.checkGooglePlayServicesAvailability();
String status = availability.toString().split('.').last;
if (status == "success") {
@ -648,235 +481,6 @@ class SwipeGeneralUtils {
}
return false;
}
//
// static bool isDate(String input, String format) {
// try {
// DateTime d = DateFormat(format).parseStrict(input);
// //print(d);
// return true;
// } catch (e) {
// //print(e);
// return false;
// }
// }
}
//
// static Widget getNoDataWidget(BuildContext context) {
// return Column(
// mainAxisAlignment: MainAxisAlignment.center,
// crossAxisAlignment: CrossAxisAlignment.center,
// children: [
// SvgPicture.asset('assets/images/not_found.svg', width: 110.0, height: 110.0),
// LocaleKeys.noDataAvailable.tr().toText16().paddingOnly(top: 15),
// ],
// ).center;
// }
//
// static Widget getNoChatWidget(BuildContext context) {
// return Column(
// mainAxisAlignment: MainAxisAlignment.center,
// crossAxisAlignment: CrossAxisAlignment.center,
// children: [
// SvgPicture.asset('assets/images/not_found.svg', width: 110.0, height: 110.0),
// LocaleKeys.noDataAvailable.tr().toText16().paddingOnly(top: 15),
// ],
// ).center;
// }
//
// static Uint8List getPostBytes(img) {
// try {
// var b64 = img.replaceFirst('data:image/png;base64,', '');
// if (img != null && GeneralUtils.isBase64(b64)) return GeneralUtils.dataFromBase64String(b64);
// } catch (e) {}
// return Uint8List.fromList([]);
// }
//
// static String getBase64FromJpeg(img) {
// try {
// var b64 = img.replaceFirst('data:image/jpeg;base64,', '');
// return b64;
// } catch (e) {}
// return "";
// }
//
// static bool isBase64(String str) {
// RegExp _base64 = RegExp(r'^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=|[A-Za-z0-9+\/]{4})$');
// return _base64.hasMatch(str);
// }
//
// static Uint8List dataFromBase64String(String base64String) {
// return base64Decode(base64String);
// }
//
// static Widget tableColumnTitle(String? text, {bool showDivider = true, bool alignCenter = false}) {
// text ??= "";
// return Column(
// crossAxisAlignment: CrossAxisAlignment.start,
// mainAxisSize: MainAxisSize.min,
// children: [
// 6.height,
// alignCenter ? text.toText12().center : text.toText12(),
// 5.height,
// if (showDivider)
// const Divider(
// height: 1,
// color: Color(0xff2E303A),
// thickness: 1,
// )
// ],
// );
// }
//
// static Decoration containerRadius(Color background, double radius) {
// return BoxDecoration(
// color: background,
// border: Border.all(
// width: 1, //
// color: background // <--- border width here
// ),
// borderRadius: BorderRadius.circular(radius),
// );
// }
//
// static Widget mHeight(double h) {
// return Container(
// height: h,
// );
// }
//
// static Widget mDivider(Color color) {
// return Divider(
// // width: double.infinity,
// height: 1,
// color: color,
// );
// }
//
// static Widget tableColumnValue(String text, {bool isCapitable = true, bool alignCenter = false}) {
// return Column(
// crossAxisAlignment: CrossAxisAlignment.start,
// mainAxisSize: MainAxisSize.min,
// children: [
// 12.height,
// if (alignCenter)
// (isCapitable ? text.toLowerCase().capitalizeFirstofEach : text).toText12(color: MyColors.normalTextColor).center
// else
// (isCapitable ? text.toLowerCase().capitalizeFirstofEach : text).toText12(color: MyColors.normalTextColor),
// 12.height,
// ],
// );
// }
//
// /// EIT Forms date formats
//
// static String getMonthNamedFormat(DateTime date) {
// /// it will return like "29-Sep-2022"
// return DateFormat('dd-MMM-yyyy', "en_US").format(date);
// }
//
// static String reverseFormatDate(String date) {
// String formattedDate;
// if (date.isNotEmpty) {
// formattedDate = date.replaceAll('/', '-');
// formattedDate = formattedDate.replaceAll(' 00:00:00', '');
// } else {
// formattedDate = date;
// }
// return formattedDate;
// }
//
// static String formatStandardDate(String date) {
// String formattedDate;
// if (date.isNotEmpty) {
// formattedDate = date.replaceAll('-', '/');
// } else {
// formattedDate = date;
// }
// return formattedDate;
// }
//
// static String reverseFormatStandardDate(String date) {
// String formattedDate;
// if (date.isNotEmpty) {
// formattedDate = date.replaceAll('/', '-');
// } else {
// formattedDate = date;
// }
// return formattedDate;
// }
//
// static String formatDate(String date) {
// String formattedDate;
//
// if (date.isNotEmpty) {
// date = date.substring(0, 10);
// formattedDate = date.replaceAll('-', '/');
// formattedDate = formattedDate + ' 00:00:00';
// } else {
// formattedDate = date;
// }
// return formattedDate;
// }
//
// static String formatDateNew(String date) {
// String formattedDate;
// if (date.isNotEmpty) {
// formattedDate = date.split('T')[0];
// if (!formattedDate.contains("00:00:00")) {
// formattedDate = formattedDate + ' 00:00:00';
// }
// } else {
// formattedDate = date;
// }
// return formattedDate;
// }
//
// static String formatDateDefault(String date) {
// if (date.isNotEmpty) {
// if (date.toLowerCase().contains("t")) {
// date = date.toLowerCase().split("t")[0];
// if (!date.contains("00:00:00")) {
// date = date + ' 00:00:00';
// }
// return date;
// } else {
// if (date.toLowerCase().split("-")[1].length == 3) {
// return DateFormat('dd-MM-yyyy', "en_US").format(DateFormat('dd-MMM-yyyy', "en_US").parseLoose(date));
// } else {
// return DateFormat('dd-MM-yyyy', "en_US").format(DateFormat('yyyy-MM-dd', "en_US").parseLoose(date));
// }
// // return DateFormat('yyyy-MM-dd').format(DateFormat('dd-MM-yyyy').parseLoose(date));
// }
// } else {
// return date;
// }
// }
//
// static Future<DateTime> selectDate(BuildContext context, DateTime selectedDate) async {
// if (!Platform.isIOS) {
// await showCupertinoModalPopup(
// context: context,
// builder: (BuildContext cxt) => Container(
// height: 250,
// color: Colors.white,
// child: CupertinoDatePicker(
// backgroundColor: Colors.white,
// mode: CupertinoDatePickerMode.date,
// onDateTimeChanged: (DateTime value) {
// if (value != null && value != selectedDate) {
// selectedDate = value;
// }
// },
// initialDateTime: selectedDate,
// ),
// ),
// );
// } else {
// DateTime? picked = await showDatePicker(context: context, initialDate: selectedDate, initialEntryMode: DatePickerEntryMode.calendarOnly, firstDate: DateTime(2015, 8), lastDate: DateTime(2101));
// if (picked != null && picked != selectedDate) {
// selectedDate = picked;
// }
// }
// return selectedDate;
// }

Loading…
Cancel
Save