CreateTemporaryPassword

This commit is contained in:
mohammad
2024-06-30 14:59:18 +03:00
parent 695d6c109b
commit b00218ba5d
5 changed files with 102 additions and 59 deletions

View File

@ -3,7 +3,6 @@ import 'package:day_picker/model/day_in_week.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:intl/intl.dart'; import 'package:intl/intl.dart';
import 'package:pin_code_fields/pin_code_fields.dart';
import 'package:syncrow_app/features/devices/bloc/smart_door_bloc/smart_door_event.dart'; import 'package:syncrow_app/features/devices/bloc/smart_door_bloc/smart_door_event.dart';
import 'package:syncrow_app/features/devices/bloc/smart_door_bloc/smart_door_state.dart'; import 'package:syncrow_app/features/devices/bloc/smart_door_bloc/smart_door_state.dart';
import 'package:syncrow_app/features/devices/model/device_control_model.dart'; import 'package:syncrow_app/features/devices/model/device_control_model.dart';
@ -23,6 +22,13 @@ class SmartDoorBloc extends Bloc<SmartDoorEvent, SmartDoorState> {
on<InitialEvent>(_fetchSmartDoorStatus); on<InitialEvent>(_fetchSmartDoorStatus);
on<InitialPasswordsPage>(getTemporaryPasswords); on<InitialPasswordsPage>(getTemporaryPasswords);
on<UpdateLockEvent>(_updateLock); on<UpdateLockEvent>(_updateLock);
on<SavePasswordEvent>(savePassword);
on<ToggleRepeatEvent>(toggleRepeat);
on<SetStartEndTimeEvent>(setStartEndTime);
on<ChangeTimeEvent>(changeTime);
on<GeneratePasswordEvent>(generate7DigitNumber);
on<SelectTimeEvent>(selectTime);
on<DeletePasswordEvent>(deletePassword);
} }
void _fetchSmartDoorStatus( void _fetchSmartDoorStatus(
InitialEvent event, Emitter<SmartDoorState> emit) async { InitialEvent event, Emitter<SmartDoorState> emit) async {
@ -78,26 +84,27 @@ class SmartDoorBloc extends Bloc<SmartDoorEvent, SmartDoorState> {
List<TemporaryPassword>? temporaryPasswords = []; List<TemporaryPassword>? temporaryPasswords = [];
List<TemporaryPassword>? oneTimePasswords = []; List<TemporaryPassword>? oneTimePasswords = [];
changeTime(val, isStartEndTime) { changeTime(ChangeTimeEvent event, Emitter<SmartDoorState> emit) {
emit(LoadingInitialState()); emit(LoadingInitialState());
if (isStartEndTime == true) { if (event.isStartEndTime == true) {
startTime = val; startTime = event.val;
} else { } else {
endTime = val; endTime = event.val;
} }
emit(changeTimeState()); emit(changeTimeState());
} }
bool toggleRepeat() { bool toggleRepeat(ToggleRepeatEvent event, Emitter<SmartDoorState> emit) {
emit(LoadingInitialState()); emit(LoadingInitialState());
repeat = !repeat; repeat = !repeat;
emit(IsRepeatState()); emit(IsRepeatState());
return repeat; return repeat;
} }
bool setStartEndTime(bool val) {
bool setStartEndTime(SetStartEndTimeEvent event, Emitter<SmartDoorState> emit) {
emit(LoadingInitialState()); emit(LoadingInitialState());
isStartEndTime = val; isStartEndTime = event.val;
emit(IsStartEndState()); emit(IsStartEndState());
return isStartEndTime; return isStartEndTime;
} }
@ -119,7 +126,7 @@ class SmartDoorBloc extends Bloc<SmartDoorEvent, SmartDoorState> {
emit(UpdateState(smartDoorModel: deviceStatus)); emit(UpdateState(smartDoorModel: deviceStatus));
} }
void generate7DigitNumber() async { void generate7DigitNumber(GeneratePasswordEvent event, Emitter<SmartDoorState> emit) async {
emit(LoadingInitialState()); emit(LoadingInitialState());
passwordController.clear(); passwordController.clear();
Random random = Random(); Random random = Random();
@ -129,17 +136,16 @@ class SmartDoorBloc extends Bloc<SmartDoorEvent, SmartDoorState> {
emit(GeneratePasswordState()); emit(GeneratePasswordState());
} }
Future<void> selectTime(BuildContext context, Future<void> selectTime(SelectTimeEvent event, Emitter<SmartDoorState> emit) async {
{required bool isEffective}) async {
final DateTime? picked = await showDatePicker( final DateTime? picked = await showDatePicker(
context: context, context: event.context,
initialDate: DateTime.now(), initialDate: DateTime.now(),
firstDate: DateTime(2015, 8), firstDate: DateTime(2015, 8),
lastDate: DateTime(2101), lastDate: DateTime(2101),
); );
if (picked != null) { if (picked != null) {
final TimeOfDay? timePicked = await showTimePicker( final TimeOfDay? timePicked = await showTimePicker(
context: context, context: event.context,
initialTime: TimeOfDay.now(), initialTime: TimeOfDay.now(),
); );
if (timePicked != null) { if (timePicked != null) {
@ -150,12 +156,11 @@ class SmartDoorBloc extends Bloc<SmartDoorEvent, SmartDoorState> {
timePicked.hour, timePicked.hour,
timePicked.minute, timePicked.minute,
); );
if (isEffective) { if (event.isEffective) {
if (expirationTimeTimeStamp != null && if (expirationTimeTimeStamp != null &&
selectedDateTime.millisecondsSinceEpoch > selectedDateTime.millisecondsSinceEpoch >
expirationTimeTimeStamp!) { expirationTimeTimeStamp!) {
_showSnackBar(context, CustomSnackBar.displaySnackBar('Effective Time cannot be later than Expiration Time.');
'Effective Time cannot be later than Expiration Time.');
} else { } else {
effectiveTime = selectedDateTime.toString(); effectiveTime = selectedDateTime.toString();
effectiveTimeTimeStamp = selectedDateTime.millisecondsSinceEpoch; effectiveTimeTimeStamp = selectedDateTime.millisecondsSinceEpoch;
@ -164,8 +169,7 @@ class SmartDoorBloc extends Bloc<SmartDoorEvent, SmartDoorState> {
if (effectiveTimeTimeStamp != null && if (effectiveTimeTimeStamp != null &&
selectedDateTime.millisecondsSinceEpoch < selectedDateTime.millisecondsSinceEpoch <
effectiveTimeTimeStamp!) { effectiveTimeTimeStamp!) {
_showSnackBar(context, CustomSnackBar.displaySnackBar('Expiration Time cannot be earlier than Effective Time.');
'Expiration Time cannot be earlier than Effective Time.');
} else { } else {
expirationTime = selectedDateTime.toString(); expirationTime = selectedDateTime.toString();
expirationTimeTimeStamp = selectedDateTime.millisecondsSinceEpoch; expirationTimeTimeStamp = selectedDateTime.millisecondsSinceEpoch;
@ -176,11 +180,11 @@ class SmartDoorBloc extends Bloc<SmartDoorEvent, SmartDoorState> {
} }
} }
Future<void> savePassword(BuildContext context) async { Future<void> savePassword(SavePasswordEvent event, Emitter<SmartDoorState> emit) async {
if (_validateInputs(context)) return; if (_validateInputs()) return;
try { try {
emit(LoadingSaveState()); emit(LoadingSaveState());
var response = await DevicesAPI.createPassword( var res = await DevicesAPI.createPassword(
pageType: pageType, pageType: pageType,
deviceId: deviceId, deviceId: deviceId,
effectiveTime: effectiveTimeTimeStamp.toString(), effectiveTime: effectiveTimeTimeStamp.toString(),
@ -195,21 +199,20 @@ class SmartDoorBloc extends Bloc<SmartDoorEvent, SmartDoorState> {
workingDay: selectedDay!, workingDay: selectedDay!,
), ),
], ],
).then((value)async { );
add(InitialPasswordsPage(type: pageType)); Navigator.of(event.context).pop(true);
},);
CustomSnackBar.displaySnackBar('Save Successfully'); CustomSnackBar.displaySnackBar('Save Successfully');
emit(SaveState()); emit(SaveState());
} catch (e) {
emit(FailedState(errorMessage: 'Failed to save password: $e')); } catch (_) {
} }
} }
void deletePassword(BuildContext context, passwordId) async { Future<void> deletePassword(DeletePasswordEvent event, Emitter<SmartDoorState> emit) async {
try { try {
emit(LoadingInitialState()); emit(LoadingInitialState());
var response = await DevicesAPI.deletePassword( var response = await DevicesAPI.deletePassword(
deviceId: deviceId, passwordId: passwordId) deviceId: deviceId, passwordId: event.passwordId)
.then((value) async { .then((value) async {
add(InitialPasswordsPage(type: pageType)); add(InitialPasswordsPage(type: pageType));
}); });
@ -218,7 +221,7 @@ class SmartDoorBloc extends Bloc<SmartDoorEvent, SmartDoorState> {
} }
} }
bool _validateInputs(BuildContext context) { bool _validateInputs() {
if (passwordController.text.length<7) { if (passwordController.text.length<7) {
CustomSnackBar.displaySnackBar('Password less than 7'); CustomSnackBar.displaySnackBar('Password less than 7');
return true; return true;
@ -241,20 +244,13 @@ class SmartDoorBloc extends Bloc<SmartDoorEvent, SmartDoorState> {
} }
if (repeat == true && if (repeat == true &&
(endTime == null || startTime == null || selectedDay == null)) { (endTime == null || startTime == null || selectedDay == null)) {
_showSnackBar(context, 'Start Time and End time and the days required '); CustomSnackBar.displaySnackBar('Start Time and End time and the days required ');
return true; return true;
} }
return false; return false;
} }
void _showSnackBar(BuildContext context, String message) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(message),
backgroundColor: Colors.red,
),
);
}
List<DayInWeek> days = [ List<DayInWeek> days = [
DayInWeek("S", dayKey: 'Sun'), DayInWeek("S", dayKey: 'Sun'),

View File

@ -1,4 +1,5 @@
import 'package:equatable/equatable.dart'; import 'package:equatable/equatable.dart';
import 'package:flutter/cupertino.dart';
abstract class SmartDoorEvent extends Equatable { abstract class SmartDoorEvent extends Equatable {
const SmartDoorEvent(); const SmartDoorEvent();
@ -21,4 +22,46 @@ class UpdateLockEvent extends SmartDoorEvent {
List<Object> get props => [value]; List<Object> get props => [value];
} }
class SavePasswordEvent extends SmartDoorEvent {
final BuildContext context;
const SavePasswordEvent({required this.context});
@override
List<Object> get props => [context];
}
class GeneratePasswordEvent extends SmartDoorEvent {}
class SelectTimeEvent extends SmartDoorEvent {
final BuildContext context;
final bool isEffective;
const SelectTimeEvent({required this.context,required this.isEffective});
@override
List<Object> get props => [context,isEffective];
}
class ToggleRepeatEvent extends SmartDoorEvent {}
class SetStartEndTimeEvent extends SmartDoorEvent {
final bool val;
const SetStartEndTimeEvent({required this.val});
@override
List<Object> get props => [val];
}
class DeletePasswordEvent extends SmartDoorEvent {
final String passwordId;
const DeletePasswordEvent({required this.passwordId});
@override
List<Object> get props => [passwordId];
}
class ChangeTimeEvent extends SmartDoorEvent {
final dynamic val;
final bool isStartEndTime;
const ChangeTimeEvent({required this.val,required this.isStartEndTime});
@override
List<Object> get props => [val,isStartEndTime];
}

View File

@ -51,8 +51,7 @@ class CreateTemporaryPassword extends StatelessWidget {
actions: [ actions: [
TextButton( TextButton(
onPressed: () { onPressed: () {
BlocProvider.of<SmartDoorBloc>(context).savePassword(context); BlocProvider.of<SmartDoorBloc>(context).add(SavePasswordEvent(context: context));
SmartDoorBloc(deviceId: deviceId!).add(InitialPasswordsPage(type:type ));
}, },
child: const Text('Save')) child: const Text('Save'))
], ],
@ -114,7 +113,7 @@ class CreateTemporaryPassword extends StatelessWidget {
), ),
InkWell( InkWell(
onTap: () { onTap: () {
BlocProvider.of<SmartDoorBloc>(context).generate7DigitNumber(); BlocProvider.of<SmartDoorBloc>(context).add(GeneratePasswordEvent());
}, },
child: const BodyMedium( child: const BodyMedium(
text: 'Generate Randomly', text: 'Generate Randomly',
@ -162,8 +161,8 @@ class CreateTemporaryPassword extends StatelessWidget {
width: MediaQuery.of(context).size.width / 2, width: MediaQuery.of(context).size.width / 2,
child: InkWell( child: InkWell(
onTap: () { onTap: () {
BlocProvider.of<SmartDoorBloc>(context) BlocProvider.of<SmartDoorBloc>(context)..add(SelectTimeEvent(context: context, isEffective: true));
.selectTime(context, isEffective: true); // .selectTime(context, isEffective: true);
}, },
child: Text( child: Text(
BlocProvider.of<SmartDoorBloc>(context).effectiveTime BlocProvider.of<SmartDoorBloc>(context).effectiveTime
@ -183,9 +182,10 @@ class CreateTemporaryPassword extends StatelessWidget {
width: MediaQuery.of(context).size.width / 2, width: MediaQuery.of(context).size.width / 2,
child: InkWell( child: InkWell(
onTap: () { onTap: () {
BlocProvider.of<SmartDoorBloc>(context) BlocProvider.of<SmartDoorBloc>(context)..add(SelectTimeEvent(context: context, isEffective: false));
.selectTime(context, // BlocProvider.of<SmartDoorBloc>(context)
isEffective: false); // .selectTime(context,
// isEffective: false);
}, },
child: Text( child: Text(
BlocProvider.of<SmartDoorBloc>(context) BlocProvider.of<SmartDoorBloc>(context)
@ -214,8 +214,7 @@ class CreateTemporaryPassword extends StatelessWidget {
value: value:
BlocProvider.of<SmartDoorBloc>(context).repeat, BlocProvider.of<SmartDoorBloc>(context).repeat,
onChanged: (value) { onChanged: (value) {
BlocProvider.of<SmartDoorBloc>(context) BlocProvider.of<SmartDoorBloc>(context).add(ToggleRepeatEvent());
.toggleRepeat();
}, },
applyTheme: true, applyTheme: true,
)), )),
@ -238,14 +237,15 @@ class CreateTemporaryPassword extends StatelessWidget {
children: [ children: [
InkWell( InkWell(
onTap: () { onTap: () {
BlocProvider.of<SmartDoorBloc>(context).setStartEndTime(true); BlocProvider.of<SmartDoorBloc>(context).add(const SetStartEndTimeEvent(val: true));
}, },
child: BodyMedium(text: 'Start',fontColor:BlocProvider.of<SmartDoorBloc>(context).isStartEndTime==false? Colors.black:Colors.blue,fontSize: 18,), child: BodyMedium(text: 'Start',fontColor:BlocProvider.of<SmartDoorBloc>(context).isStartEndTime==false? Colors.black:Colors.blue,fontSize: 18,),
), ),
InkWell( InkWell(
onTap: () { onTap: () {
BlocProvider.of<SmartDoorBloc>(context).setStartEndTime(false); BlocProvider.of<SmartDoorBloc>(context).add(const SetStartEndTimeEvent(val: false));
}, },
child: BodyMedium(text: 'End',fontColor:BlocProvider.of<SmartDoorBloc>(context).isStartEndTime? Colors.black:Colors.blue,fontSize: 18,), child: BodyMedium(text: 'End',fontColor:BlocProvider.of<SmartDoorBloc>(context).isStartEndTime? Colors.black:Colors.blue,fontSize: 18,),
) )
@ -269,7 +269,9 @@ class CreateTemporaryPassword extends StatelessWidget {
highlightedTextStyle: const TextStyle( highlightedTextStyle: const TextStyle(
fontSize: 30, color: Colors.blue), fontSize: 30, color: Colors.blue),
onTimeChange: (time) { onTimeChange: (time) {
BlocProvider.of<SmartDoorBloc>(context).changeTime(time, BlocProvider.of<SmartDoorBloc>(context).isStartEndTime);
// BlocProvider.of<SmartDoorBloc>(context).changeTime(time, BlocProvider.of<SmartDoorBloc>(context).isStartEndTime);
BlocProvider.of<SmartDoorBloc>(context).add(ChangeTimeEvent(val: time, isStartEndTime: BlocProvider.of<SmartDoorBloc>(context).isStartEndTime));
}, },
): Container( ): Container(
child: TimePickerSpinner( child: TimePickerSpinner(
@ -282,7 +284,9 @@ class CreateTemporaryPassword extends StatelessWidget {
highlightedTextStyle: const TextStyle( highlightedTextStyle: const TextStyle(
fontSize: 30, color: Colors.blue), fontSize: 30, color: Colors.blue),
onTimeChange: (time) { onTimeChange: (time) {
BlocProvider.of<SmartDoorBloc>(context).changeTime(time, BlocProvider.of<SmartDoorBloc>(context).isStartEndTime); BlocProvider.of<SmartDoorBloc>(context).add(ChangeTimeEvent(val: time, isStartEndTime: BlocProvider.of<SmartDoorBloc>(context).isStartEndTime));
// BlocProvider.of<SmartDoorBloc>(context).changeTime(time, BlocProvider.of<SmartDoorBloc>(context).isStartEndTime);
}, },
), ),
), ),

View File

@ -42,7 +42,7 @@ class ViewTemporaryPassword extends StatelessWidget {
Navigator.of(context).push(MaterialPageRoute( Navigator.of(context).push(MaterialPageRoute(
builder: (context) => CreateTemporaryPassword(deviceId: deviceId, type: type), builder: (context) => CreateTemporaryPassword(deviceId: deviceId, type: type),
)).then((result) { )).then((result) {
if (result != null) { if (result != null && result) {
smartDoorBloc.add(InitialPasswordsPage(type:type )); smartDoorBloc.add(InitialPasswordsPage(type:type ));
} }
}); });
@ -83,7 +83,7 @@ class ViewTemporaryPassword extends StatelessWidget {
}, },
); );
if(result=='delete'){ if(result=='delete'){
smartDoorBloc.deletePassword(context, smartDoorBloc.temporaryPasswords![index].id.toString()); smartDoorBloc.add(DeletePasswordEvent(passwordId: smartDoorBloc.temporaryPasswords![index].id.toString()));
} }
}, },
trailing: const Icon( trailing: const Icon(

View File

@ -158,7 +158,7 @@ class DevicesAPI {
required String pageType, required String pageType,
List<Schedule>? scheduleList, List<Schedule>? scheduleList,
}) async { }) async {
try {
String endpointPath; String endpointPath;
if (pageType == 'Online Password') { if (pageType == 'Online Password') {
endpointPath = ApiEndpoints.addTemporaryPassword endpointPath = ApiEndpoints.addTemporaryPassword
@ -187,7 +187,7 @@ class DevicesAPI {
expectedResponseModel: (json) => json, expectedResponseModel: (json) => json,
); );
return response; return response;
} catch (e) {}
} }