post_enrollment_app/lib/pages/session/changePin.dart
2026-07-06 09:55:31 +05:30

629 lines
30 KiB
Dart
Executable File

import 'dart:convert';
import 'dart:io';
import 'package:flutter_svg/svg.dart';
import 'package:go_router/go_router.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:http/http.dart' as http;
import 'package:flutter/material.dart';
import 'package:nhance_app_pwa/pages/service/TokenService.dart';
import 'package:pinput/pinput.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../../config/environment.dart';
import '../../customAppBar/responsive.dart';
import '../../customAppBar/toastHelper.dart';
import '../postEnrollment/service/svg_service.dart';
import '../service/SessionManager.dart';
import 'authenticationService.dart';
import 'package:nhance_app_pwa/logger.dart';
class changePin extends StatefulWidget {
const changePin({Key? key}) : super(key: key);
@override
State<changePin> createState() => _changePinState();
}
class _changePinState extends State<changePin> {
bool _enableBiometric = false;
final _oldPinController = TextEditingController();
final _newPinController = TextEditingController();
final AuthService _authService = AuthService();
late final _formKey = GlobalKey<FormState>();
late final FocusNode focusNode;
dynamic empMobileNo;
dynamic empEmailid;
dynamic _token;
dynamic emp_status;
bool _isSaving = false;
bool _isPinChanged = false; // hard success lock
@override
void initState(){
super.initState();
getLoginDetails();
}
Future<void> getLoginDetails() async {
final SharedPreferences prefs = await SharedPreferences.getInstance();
empMobileNo = prefs.getString('empMobileNo');
empEmailid = prefs.getString('empEmailid');
logDebug('empMobileNo: $empMobileNo');
logDebug('empEmailid: $empEmailid');
}
@override
void dispose() {
super.dispose();
}
Future<void> setChangePin() async {
if (_isSaving || _isPinChanged) return;
if (!_formKey.currentState!.validate()) return;
setState(() {
_isSaving = true;
});
try {
if (_formKey.currentState!.validate()) {
final SharedPreferences prefs = await SharedPreferences.getInstance();
_token = await TokenService.getPostToken();
logDebug(_token);
// empMobileNo = prefs.getString('empMobileNo');
// empEmailid = 'surendar.m@venbainfotech.com';
var params = {};
if (empMobileNo != null && empMobileNo.isNotEmpty) {
params = {'mobile_number': empMobileNo,
'old_mpin': _oldPinController.text,
'new_mpin': _newPinController.text};
} else if(empEmailid != null && empEmailid.isNotEmpty){
params = {'email_id': empEmailid,
'old_mpin': _oldPinController.text,
'new_mpin': _newPinController.text};
}
final response = await http.post(
Uri.parse(Environment.apiUrlEnrollment + 'updateMpin'),
body: json.encode(params),
headers: {
HttpHeaders.contentTypeHeader: 'application/json',
'Authorization': 'Bearer $_token',
'APP-SIGNATURE': 'nhance-2025-signature-T8f6gV9k5fK2wf5V5c4vId3b0J8z6cAm2x8Y',
},
);
logDebug('response $response');
if (response.statusCode == 200) {
Map<String, dynamic> data = json.decode(response.body);
bool pinVerification = data['data']['mpin_verification'];
String message = data['data']['message'];
if (pinVerification) {
setState(() {
_isPinChanged = true;
});
ToastHelper.showSuccessToast(context, message);
context.go('/profile');
} else {
ToastHelper.showErrorToast(context, message);
logDebug('Invalid Pin Number');
}
} else if (response.statusCode == 401) {
await SessionManager().clear();
ToastHelper.showErrorToast(context, 'Session Out');
if (!context.mounted) return;
context.go('/login');
} else if (response.statusCode == 403) {
await SessionManager().clear();
ToastHelper.showErrorToast(context, 'Session Out');
if (!context.mounted) return;
context.go('/login');
} else if (response.statusCode == 451) {
final body = jsonDecode(response.body);
final message = body['message'];
ToastHelper.showWarningToast(context, message);
} else if (response.statusCode == 429) {
final body = jsonDecode(response.body);
final message = body['message'];
ToastHelper.showWarningToast(context, message);
} else {
throw Exception('Failed to load data');
}
}
} catch (e) {
ToastHelper.showErrorToast(context, 'Unable to process. Please try again later');
logDebug('Error: $e');
} finally {
if (mounted) {
setState(() {
_isSaving = false;
});
}
}
}
String? _validatePin(String? value) {
if (value == null || value.isEmpty) {
return 'Please enter a PIN';
}
if (value.length != 4) {
return 'PIN must be 4 digits';
}
return null;
}
String? _validateConfirmPin(String? value) {
if (value == null || value.isEmpty) {
return 'Please enter your PIN';
}
if (value.length != 4) {
return 'PIN must be 4 digits';
}
if (value == _oldPinController.text) {
return 'Please enter a different PIN.';
}
return null;
}
@override
Widget build(BuildContext context) {
const focusedBorderColor = Color.fromRGBO(23, 171, 144, 1);
const fillColor = Color.fromRGBO(243, 246, 249, 0);
const borderColor = Color.fromRGBO(23, 171, 144, 0.4);
Size _size = MediaQuery.of(context).size;
EdgeInsets marginInsets = EdgeInsets.zero;
if (Responsive.isDesktop(context)) {
marginInsets = const EdgeInsets.only(
left: 0,
right: 0,
bottom: 0,
top: 0,
);
} else if (Responsive.isMobile(context)) {
marginInsets = const EdgeInsets.only(
left: 25, // Example value for mobile
right: 25, // Example value for mobile
bottom: 0, // Example value for mobile
top: 0, // Example value for mobile
);
} else if (Responsive.isTablet(context)) {
marginInsets = const EdgeInsets.only(
left: 25, // Example value for mobile
right: 25, // Example value for mobile
bottom: 0, // Example value for mobile
top: 0, // Example value for mobile
);
}
final defaultPinTheme = PinTheme(
width: 56,
height: 56,
textStyle: const TextStyle(
fontSize: 20,
color: Color.fromRGBO(30, 60, 87, 1),
),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(19),
border: Border.all(color: borderColor),
),
);
return PopScope(
canPop: false,
onPopInvokedWithResult: (didPop, result) {
if (didPop) return;
context.go('/profile');
},
child: Scaffold(
resizeToAvoidBottomInset: true, // IMPORTANT
bottomNavigationBar: SafeArea(
child: Container(
color: Colors.white, // 👈 set your color here
padding: const EdgeInsets.only(bottom: 8, top: 4),
child: RichText(
textAlign: TextAlign.center,
text: TextSpan(
text: 'By continuing, you agree with our ',
style: GoogleFonts.poppins(
color: Colors.black,
fontSize: 9,
),
children: const [
TextSpan(
text: 'privacy policy ',
style: TextStyle(color: Color(0xFF00989E)),
),
TextSpan(text: 'and '),
TextSpan(
text: 'terms of use',
style: TextStyle(color: Color(0xFF00989E)),
),
],
),
),
),
),
body: Container(
color: Colors.white, // Set the color for the body
child: SizedBox.expand(
child: Stack(children: [
SingleChildScrollView(
child: Container(
padding: EdgeInsets.all(0),
color: Color(0xFFFFFCE5),
child: Column(children: [
Container(
decoration: BoxDecoration(
color: Color(
0xFFFFFCE5), // Set background color for the container
borderRadius: BorderRadius.circular(
10), // Set border radius for the container
),
// padding: EdgeInsets.only(top: 0, bottom: 0, left: 10, right: 10),
child: Column(
// crossAxisAlignment: CrossAxisAlignment.center,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
InkWell(
onTap: () => context.go('/profile'),
borderRadius: BorderRadius.circular(8),
child: const Padding(
padding: EdgeInsets.only(left: 8, right: 4),
child: Icon(
Icons.chevron_left,
color: Color(0xFF000000),
size: 30,
),
),
),
Image.asset(
'assets/nhance_app_logo.png',
width: 150,
height: 100,
),
],
),
SizedBox(height: 10),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Expanded(
flex: 12,
child: Align(
alignment: Alignment.center,
child: Padding(
padding: const EdgeInsets.only(
left: 16.0), // Add left margin
child: SvgPicture.string(
SvgService.getSvg('mpin'),
width: 150,
height: 150,
),
),
),
),
],
),
SizedBox(height: 10),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Expanded(
flex: 12,
child: Text(
'Change Pin',
textAlign: TextAlign.center,
style: GoogleFonts.poppins(
fontSize: 16,
color: Color(0xFF404040),
fontWeight: FontWeight.w500,
),
),
),
],
),
SizedBox(height: 10),
],
),
),
Container(
decoration: BoxDecoration(
color: Colors
.white, // Set background color for the container
borderRadius: BorderRadius.only(
topLeft: Radius.circular(150.0),
topRight: Radius.circular(0),
), // Set border radius for the container
),
padding: EdgeInsets.only(
top: 20, bottom: 10, left: 10, right: 10),
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Container(
margin: marginInsets,
alignment: Alignment.bottomCenter,
child: SingleChildScrollView(
child: Form(
key: _formKey,
child: Column(
children: [
Row(
children: [
Expanded(
flex: 12,
child: Column(
children: [
SizedBox(height: 40),
Container(
margin: EdgeInsets.symmetric(
horizontal: 30),
child: Row(
mainAxisAlignment:
MainAxisAlignment
.start, // Align text to the right
children: [
Align(
// alignment: Alignment.centerLeft,
child: Text(
'Enter old pin',
style: GoogleFonts
.poppins(
fontSize: 16,
color: Color(
0xFF909090),
fontWeight:
FontWeight.w400,
),
),
),
]),
),
SizedBox(height: 5),
Container(
margin: EdgeInsets.symmetric(
horizontal: 0),
child: Pinput(
enabled: !_isSaving && !_isPinChanged,
length: 4,
defaultPinTheme:
defaultPinTheme,
separatorBuilder: (index) =>
const SizedBox(width: 8),
showCursor: true,
controller: _oldPinController,
validator: _validatePin,
errorPinTheme: defaultPinTheme
.copyBorderWith(
border: Border.all(
color:
Colors.redAccent),
),
hapticFeedbackType:
HapticFeedbackType
.lightImpact,
onCompleted: (pin) {
logDebug(
'onCompleted: $pin');
},
onChanged: (value) {
logDebug(
'onChanged: $value');
},
cursor: Column(
mainAxisAlignment:
MainAxisAlignment.end,
children: [
Container(
margin: const EdgeInsets
.only(bottom: 9),
width: 22,
height: 1,
color:
focusedBorderColor,
),
],
),
focusedPinTheme:
defaultPinTheme.copyWith(
decoration: defaultPinTheme
.decoration!
.copyWith(
borderRadius:
BorderRadius.circular(
8),
border: Border.all(
color:
focusedBorderColor),
),
),
submittedPinTheme:
defaultPinTheme.copyWith(
decoration: defaultPinTheme
.decoration!
.copyWith(
color: fillColor,
borderRadius:
BorderRadius.circular(
19),
border: Border.all(
color:
focusedBorderColor),
),
),
),
),
SizedBox(height: 15),
Container(
margin: EdgeInsets.symmetric(
horizontal: 30),
child: Row(
mainAxisAlignment:
MainAxisAlignment
.start, // Align text to the right
children: [
Align(
// alignment: Alignment.centerLeft,
child: Text(
'Enter new pin',
style: GoogleFonts
.poppins(
fontSize: 16,
color: Color(
0xFF909090),
fontWeight:
FontWeight.w400,
),
),
),
]),
),
SizedBox(height: 5),
Container(
margin: Responsive.isDesktop(
context)
? EdgeInsets.symmetric(
horizontal: 150)
: EdgeInsets.symmetric(
horizontal: 0),
child: Pinput(
enabled: !_isSaving && !_isPinChanged,
length: 4,
defaultPinTheme:
defaultPinTheme,
separatorBuilder: (index) =>
const SizedBox(width: 8),
showCursor: true,
controller: _newPinController,
validator:
_validateConfirmPin,
errorPinTheme: defaultPinTheme
.copyBorderWith(
border: Border.all(
color:
Colors.redAccent),
),
hapticFeedbackType:
HapticFeedbackType
.lightImpact,
onCompleted: (pin) {
logDebug(
'onCompleted: $pin');
},
onChanged: (value) {
logDebug(
'onChanged: $value');
},
cursor: Column(
mainAxisAlignment:
MainAxisAlignment.end,
children: [
Container(
margin: const EdgeInsets
.only(bottom: 9),
width: 22,
height: 1,
color:
focusedBorderColor,
),
],
),
focusedPinTheme:
defaultPinTheme.copyWith(
decoration: defaultPinTheme
.decoration!
.copyWith(
borderRadius:
BorderRadius.circular(
8),
border: Border.all(
color:
focusedBorderColor),
),
),
submittedPinTheme:
defaultPinTheme.copyWith(
decoration: defaultPinTheme
.decoration!
.copyWith(
color: fillColor,
borderRadius:
BorderRadius.circular(
19),
border: Border.all(
color:
focusedBorderColor),
),
),
),
),
SizedBox(height: 15),
Container(
margin: EdgeInsets.symmetric(
horizontal: 30),
child: SizedBox(
width: double.infinity,
height: 45,
child: ElevatedButton(
style: ElevatedButton
.styleFrom(
backgroundColor:
Color(0xFF00989E),
shape:
RoundedRectangleBorder(
borderRadius:
BorderRadius
.circular(10),
),
),
onPressed: (_isSaving || _isPinChanged)
? null
: () {
setChangePin();
},
child: _isSaving
? const SizedBox(
width: 20,
height: 20,
child: CircularProgressIndicator(
strokeWidth: 2,
valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
),
)
: Text(
"Save",
style: GoogleFonts.poppins(color: Colors.white),
),
),
),
),
],
),
),
],
),
],
),
),
),
),
SizedBox(height: 40),
],
),
),
]),
)),
]),
))));
}
}