Commit b76cf1af authored by Sai Srinivas's avatar Sai Srinivas
Browse files

06-05-2025 By Sai Srinivas

First Commit
LoginScreen.dart
HomeScreen.dart
WebERPScreen.dart
WebWhizzdomScreen.dart
parent aaf72461
class TechnicianLoadNumbersResponse {
List<PaymentModeList>? paymentModeList;
List<Contacts>? contacts;
int? error;
int? sessionExists;
TechnicianLoadNumbersResponse(
{this.paymentModeList, this.contacts, this.error, this.sessionExists});
TechnicianLoadNumbersResponse.fromJson(Map<String, dynamic> json) {
if (json['payment_mode_list'] != null) {
paymentModeList = <PaymentModeList>[];
json['payment_mode_list'].forEach((v) {
paymentModeList!.add(new PaymentModeList.fromJson(v));
});
}
if (json['contacts'] != null) {
contacts = <Contacts>[];
json['contacts'].forEach((v) {
contacts!.add(new Contacts.fromJson(v));
});
}
error = json['error'];
sessionExists = json['session_exists'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.paymentModeList != null) {
data['payment_mode_list'] =
this.paymentModeList!.map((v) => v.toJson()).toList();
}
if (this.contacts != null) {
data['contacts'] = this.contacts!.map((v) => v.toJson()).toList();
}
data['error'] = this.error;
data['session_exists'] = this.sessionExists;
return data;
}
}
class PaymentModeList {
String? id;
String? name;
PaymentModeList({this.id, this.name});
PaymentModeList.fromJson(Map<String, dynamic> json) {
id = json['id'];
name = json['name'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['name'] = this.name;
return data;
}
}
class Contacts {
String? mob1;
String? name;
Contacts({this.mob1, this.name});
Contacts.fromJson(Map<String, dynamic> json) {
mob1 = json['mob1'];
name = json['name'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['mob1'] = this.mob1;
data['name'] = this.name;
return data;
}
}
class TechnicianPendingComplaintsResponse {
List<TP_List>? list;
int? error;
int? sessionExists;
TechnicianPendingComplaintsResponse(
{this.list, this.error, this.sessionExists});
TechnicianPendingComplaintsResponse.fromJson(Map<String, dynamic> json) {
if (json['list'] != null) {
list = <TP_List>[];
json['list'].forEach((v) {
list!.add(new TP_List.fromJson(v));
});
}
error = json['error'];
sessionExists = json['session_exists'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.list != null) {
data['list'] = this.list!.map((v) => v.toJson()).toList();
}
data['error'] = this.error;
data['session_exists'] = this.sessionExists;
return data;
}
}
class TP_List {
String? genId;
String? address;
String? loc;
String? complaintId;
String? companyName;
String? productName;
String? complaintCategory;
String? compRegDatetime;
String? mobileNo;
TP_List(
{this.genId,
this.address,
this.loc,
this.complaintId,
this.companyName,
this.productName,
this.complaintCategory,
this.compRegDatetime,
this.mobileNo});
TP_List.fromJson(Map<String, dynamic> json) {
genId = json['gen_id'];
address = json['address'];
loc = json['loc'];
complaintId = json['complaint_id'];
companyName = json['company_name'];
productName = json['product_name'];
complaintCategory = json['complaint_category'];
compRegDatetime = json['comp_reg_datetime'];
mobileNo = json['mobile_no'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['gen_id'] = this.genId;
data['address'] = this.address;
data['loc'] = this.loc;
data['complaint_id'] = this.complaintId;
data['company_name'] = this.companyName;
data['product_name'] = this.productName;
data['complaint_category'] = this.complaintCategory;
data['comp_reg_datetime'] = this.compRegDatetime;
data['mobile_no'] = this.mobileNo;
return data;
}
}
class TodayVisitResponse {
List<Visitlist>? list;
int? error;
int? sessionExists;
TodayVisitResponse({this.list, this.error, this.sessionExists});
TodayVisitResponse.fromJson(Map<String, dynamic> json) {
if (json['list'] != null) {
list = <Visitlist>[];
json['list'].forEach((v) {
list!.add(new Visitlist.fromJson(v));
});
}
error = json['error'];
sessionExists = json['session_exists'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.list != null) {
data['list'] = this.list!.map((v) => v.toJson()).toList();
}
data['error'] = this.error;
data['session_exists'] = this.sessionExists;
return data;
}
}
class Visitlist {
String? genId;
String? complaintId;
String? address;
String? loc;
String? mobileNo;
String? followupId;
String? companyName;
String? productName;
String? complaintCategory;
String? visitDatetime;
Visitlist(
{this.genId,
this.complaintId,
this.address,
this.loc,
this.mobileNo,
this.followupId,
this.companyName,
this.productName,
this.complaintCategory,
this.visitDatetime});
Visitlist.fromJson(Map<String, dynamic> json) {
genId = json['gen_id'];
complaintId = json['complaint_id'];
address = json['address'];
loc = json['loc'];
mobileNo = json['mobile_no'];
followupId = json['followup_id'];
companyName = json['company_name'];
productName = json['product_name'];
complaintCategory = json['complaint_category'];
visitDatetime = json['visit_datetime'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['gen_id'] = this.genId;
data['complaint_id'] = this.complaintId;
data['address'] = this.address;
data['loc'] = this.loc;
data['mobile_no'] = this.mobileNo;
data['followup_id'] = this.followupId;
data['company_name'] = this.companyName;
data['product_name'] = this.productName;
data['complaint_category'] = this.complaintCategory;
data['visit_datetime'] = this.visitDatetime;
return data;
}
}
\ No newline at end of file
class UpdateComplaintResponse {
int? error;
String? fsrFileName;
int? sessionExists;
UpdateComplaintResponse({this.error, this.fsrFileName, this.sessionExists});
UpdateComplaintResponse.fromJson(Map<String, dynamic> json) {
error = json['error'];
fsrFileName = json['fsr_file_name'];
sessionExists = json['session_exists'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['error'] = this.error;
data['fsr_file_name'] = this.fsrFileName;
data['session_exists'] = this.sessionExists;
return data;
}
}
class UpdatePasswordResponse {
int? error;
String? message;
int? sessionExists;
UpdatePasswordResponse({this.error, this.message, this.sessionExists});
UpdatePasswordResponse.fromJson(Map<String, dynamic> json) {
error = json['error'];
message = json['message'];
sessionExists = json['session_exists'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['error'] = this.error;
data['message'] = this.message;
data['session_exists'] = this.sessionExists;
return data;
}
}
class VersionsResponse {
String? latestVersion;
int? latestVersionCode;
String? url;
String? releaseNotes;
String? iosLatestVersion;
int? iosLatestVersionCode;
String? iosUrl;
String? iosReleaseNotes;
VersionsResponse(
{this.latestVersion,
this.latestVersionCode,
this.url,
this.releaseNotes,
this.iosLatestVersion,
this.iosLatestVersionCode,
this.iosUrl,
this.iosReleaseNotes});
VersionsResponse.fromJson(Map<String, dynamic> json) {
latestVersion = json['latestVersion'];
latestVersionCode = json['latestVersionCode'];
url = json['url'];
releaseNotes = json['releaseNotes'];
iosLatestVersion = json['ios_latestVersion'];
iosLatestVersionCode = json['ios_latestVersionCode'];
iosUrl = json['ios_url'];
iosReleaseNotes = json['ios_releaseNotes'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['latestVersion'] = this.latestVersion;
data['latestVersionCode'] = this.latestVersionCode;
data['url'] = this.url;
data['releaseNotes'] = this.releaseNotes;
data['ios_latestVersion'] = this.iosLatestVersion;
data['ios_latestVersionCode'] = this.iosLatestVersionCode;
data['ios_url'] = this.iosUrl;
data['ios_releaseNotes'] = this.iosReleaseNotes;
return data;
}
}
class ViewVisitDetailsResponse {
Complaintdetails? complaintDetails;
int? error;
int? sessionExists;
ViewVisitDetailsResponse(
{this.complaintDetails, this.error, this.sessionExists});
ViewVisitDetailsResponse.fromJson(Map<String, dynamic> json) {
complaintDetails = json['complaint_details'] != null
? new Complaintdetails.fromJson(json['complaint_details'])
: null;
error = json['error'];
sessionExists = json['session_exists'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.complaintDetails != null) {
data['complaint_details'] = this.complaintDetails!.toJson();
}
data['error'] = this.error;
data['session_exists'] = this.sessionExists;
return data;
}
}
class Complaintdetails {
String? id;
String? oemPemName;
String? accId;
String? productId;
String? genHashId;
String? engineModel;
String? alt;
String? engineNo;
String? altNo;
String? invNo;
String? dgSetNo;
String? btryNo;
String? state;
String? district;
String? address;
String? branchId;
String? salesEmpId;
String? dispDate;
String? cmsngDate;
String? dateOfEngineSale;
String? pdiDate;
String? wrntyExpiryDate;
String? nextService;
String? date;
String? extra;
String? status;
String? dataSource;
String? refType;
String? refId;
String? orderId;
String? empId;
String? isSuspense;
String? loc;
String? tempLoc;
String? locStatus;
String? isExist;
String? delRemarks;
String? delEmpId;
String? delDatetime;
String? cname;
String? mob1;
String? mob2;
String? mail;
String? aname;
String? emodel;
String? spname;
String? complaintId;
String? openedDate;
String? dateOfSupply;
String? complaintType;
String? complaintCategory;
String? complaintDesc;
Complaintdetails(
{this.id,
this.oemPemName,
this.accId,
this.productId,
this.genHashId,
this.engineModel,
this.alt,
this.engineNo,
this.altNo,
this.invNo,
this.dgSetNo,
this.btryNo,
this.state,
this.district,
this.address,
this.branchId,
this.salesEmpId,
this.dispDate,
this.cmsngDate,
this.dateOfEngineSale,
this.pdiDate,
this.wrntyExpiryDate,
this.nextService,
this.date,
this.extra,
this.status,
this.dataSource,
this.refType,
this.refId,
this.orderId,
this.empId,
this.isSuspense,
this.loc,
this.tempLoc,
this.locStatus,
this.isExist,
this.delRemarks,
this.delEmpId,
this.delDatetime,
this.cname,
this.mob1,
this.mob2,
this.mail,
this.aname,
this.emodel,
this.spname,
this.complaintId,
this.openedDate,
this.dateOfSupply,
this.complaintType,
this.complaintCategory,
this.complaintDesc});
Complaintdetails.fromJson(Map<String, dynamic> json) {
id = json['id'];
oemPemName = json['oem_pem_name'];
accId = json['acc_id'];
productId = json['product_id'];
genHashId = json['gen_hash_id'];
engineModel = json['engine_model'];
alt = json['alt'];
engineNo = json['engine_no'];
altNo = json['alt_no'];
invNo = json['inv_no'];
dgSetNo = json['dg_set_no'];
btryNo = json['btry_no'];
state = json['state'];
district = json['district'];
address = json['address'];
branchId = json['branch_id'];
salesEmpId = json['sales_emp_id'];
dispDate = json['disp_date'];
cmsngDate = json['cmsng_date'];
dateOfEngineSale = json['date_of_engine_sale'];
pdiDate = json['pdi_date'];
wrntyExpiryDate = json['wrnty_expiry_date'];
nextService = json['next_service'];
date = json['date'];
extra = json['extra'];
status = json['status'];
dataSource = json['data_source'];
refType = json['ref_type'];
refId = json['ref_id'];
orderId = json['order_id'];
empId = json['emp_id'];
isSuspense = json['is_suspense'];
loc = json['loc'];
tempLoc = json['temp_loc'];
locStatus = json['loc_status'];
isExist = json['is_exist'];
delRemarks = json['del_remarks'];
delEmpId = json['del_emp_id'];
delDatetime = json['del_datetime'];
cname = json['cname'];
mob1 = json['mob1'];
mob2 = json['mob2'];
mail = json['mail'];
aname = json['aname'];
emodel = json['emodel'];
spname = json['spname'];
complaintId = json['complaint_id'];
openedDate = json['opened_date'];
dateOfSupply = json['date_of_supply'];
complaintType = json['complaint_type'];
complaintCategory = json['complaint_category'];
complaintDesc = json['complaint_desc'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['oem_pem_name'] = this.oemPemName;
data['acc_id'] = this.accId;
data['product_id'] = this.productId;
data['gen_hash_id'] = this.genHashId;
data['engine_model'] = this.engineModel;
data['alt'] = this.alt;
data['engine_no'] = this.engineNo;
data['alt_no'] = this.altNo;
data['inv_no'] = this.invNo;
data['dg_set_no'] = this.dgSetNo;
data['btry_no'] = this.btryNo;
data['state'] = this.state;
data['district'] = this.district;
data['address'] = this.address;
data['branch_id'] = this.branchId;
data['sales_emp_id'] = this.salesEmpId;
data['disp_date'] = this.dispDate;
data['cmsng_date'] = this.cmsngDate;
data['date_of_engine_sale'] = this.dateOfEngineSale;
data['pdi_date'] = this.pdiDate;
data['wrnty_expiry_date'] = this.wrntyExpiryDate;
data['next_service'] = this.nextService;
data['date'] = this.date;
data['extra'] = this.extra;
data['status'] = this.status;
data['data_source'] = this.dataSource;
data['ref_type'] = this.refType;
data['ref_id'] = this.refId;
data['order_id'] = this.orderId;
data['emp_id'] = this.empId;
data['is_suspense'] = this.isSuspense;
data['loc'] = this.loc;
data['temp_loc'] = this.tempLoc;
data['loc_status'] = this.locStatus;
data['is_exist'] = this.isExist;
data['del_remarks'] = this.delRemarks;
data['del_emp_id'] = this.delEmpId;
data['del_datetime'] = this.delDatetime;
data['cname'] = this.cname;
data['mob1'] = this.mob1;
data['mob2'] = this.mob2;
data['mail'] = this.mail;
data['aname'] = this.aname;
data['emodel'] = this.emodel;
data['spname'] = this.spname;
data['complaint_id'] = this.complaintId;
data['opened_date'] = this.openedDate;
data['date_of_supply'] = this.dateOfSupply;
data['complaint_type'] = this.complaintType;
data['complaint_category'] = this.complaintCategory;
data['complaint_desc'] = this.complaintDesc;
return data;
}
}
class generatorComplaintResponse {
int? error;
List<C_List>? list;
int? sessionExists;
generatorComplaintResponse({this.error, this.list, this.sessionExists});
generatorComplaintResponse.fromJson(Map<String, dynamic> json) {
error = json['error'];
if (json['list'] != null) {
list = <C_List>[];
json['list'].forEach((v) {
list!.add(new C_List.fromJson(v));
});
}
sessionExists = json['session_exists'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['error'] = this.error;
if (this.list != null) {
data['list'] = this.list!.map((v) => v.toJson()).toList();
}
data['session_exists'] = this.sessionExists;
return data;
}
}
class C_List {
String? compId;
String? compType;
String? compStatus;
String? compRegdate;
String? complaintNote;
String? techName;
C_List(
{this.compId,
this.compType,
this.compStatus,
this.compRegdate,
this.complaintNote,
this.techName});
C_List.fromJson(Map<String, dynamic> json) {
compId = json['comp_id'];
compType = json['comp_type'];
compStatus = json['comp_status'];
compRegdate = json['comp_regdate'];
complaintNote = json['complaint_note'];
techName = json['tech_name'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['comp_id'] = this.compId;
data['comp_type'] = this.compType;
data['comp_status'] = this.compStatus;
data['comp_regdate'] = this.compRegdate;
data['complaint_note'] = this.complaintNote;
data['tech_name'] = this.techName;
return data;
}
}
class loadGeneratorDetailsResponse {
int? error;
String? genId;
String? aname;
String? emodel;
String? spname;
String? mob1;
String? mob2;
String? mail;
String? cname;
String? engineNo;
String? dateOfEngineSale;
String? altNo;
String? btryNo;
String? dgSetNo;
String? state;
String? district;
String? address;
String? dispDate;
String? cmsngDate;
String? status;
List<ComplaintCategoryList>? complaintCategoryList;
List<ComplaintTypeList>? complaintTypeList;
List<ComplaintDescriptionList>? complaintDescriptionList;
String? nextService;
int? sessionExists;
loadGeneratorDetailsResponse(
{this.error,
this.genId,
this.aname,
this.emodel,
this.spname,
this.mob1,
this.mob2,
this.mail,
this.cname,
this.engineNo,
this.dateOfEngineSale,
this.altNo,
this.btryNo,
this.dgSetNo,
this.state,
this.district,
this.address,
this.dispDate,
this.cmsngDate,
this.status,
this.complaintCategoryList,
this.complaintTypeList,
this.complaintDescriptionList,
this.nextService,
this.sessionExists});
loadGeneratorDetailsResponse.fromJson(Map<String, dynamic> json) {
error = json['error'];
genId = json['gen_id'];
aname = json['aname'];
emodel = json['emodel'];
spname = json['spname'];
mob1 = json['mob1'];
mob2 = json['mob2'];
mail = json['mail'];
cname = json['cname'];
engineNo = json['engine_no'];
dateOfEngineSale = json['date_of_engine_sale'];
altNo = json['alt_no'];
btryNo = json['btry_no'];
dgSetNo = json['dg_set_no'];
state = json['state'];
district = json['district'];
address = json['address'];
dispDate = json['disp_date'];
cmsngDate = json['cmsng_date'];
status = json['status'];
if (json['complaint_category_list'] != null) {
complaintCategoryList = <ComplaintCategoryList>[];
json['complaint_category_list'].forEach((v) {
complaintCategoryList!.add(new ComplaintCategoryList.fromJson(v));
});
}
if (json['complaint_type_list'] != null) {
complaintTypeList = <ComplaintTypeList>[];
json['complaint_type_list'].forEach((v) {
complaintTypeList!.add(new ComplaintTypeList.fromJson(v));
});
}
if (json['complaint_description_list'] != null) {
complaintDescriptionList = <ComplaintDescriptionList>[];
json['complaint_description_list'].forEach((v) {
complaintDescriptionList!.add(new ComplaintDescriptionList.fromJson(v));
});
}
nextService = json['next_service'];
sessionExists = json['session_exists'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['error'] = this.error;
data['gen_id'] = this.genId;
data['aname'] = this.aname;
data['emodel'] = this.emodel;
data['spname'] = this.spname;
data['mob1'] = this.mob1;
data['mob2'] = this.mob2;
data['mail'] = this.mail;
data['cname'] = this.cname;
data['engine_no'] = this.engineNo;
data['date_of_engine_sale'] = this.dateOfEngineSale;
data['alt_no'] = this.altNo;
data['btry_no'] = this.btryNo;
data['dg_set_no'] = this.dgSetNo;
data['state'] = this.state;
data['district'] = this.district;
data['address'] = this.address;
data['disp_date'] = this.dispDate;
data['cmsng_date'] = this.cmsngDate;
data['status'] = this.status;
if (this.complaintCategoryList != null) {
data['complaint_category_list'] =
this.complaintCategoryList!.map((v) => v.toJson()).toList();
}
if (this.complaintTypeList != null) {
data['complaint_type_list'] =
this.complaintTypeList!.map((v) => v.toJson()).toList();
}
if (this.complaintDescriptionList != null) {
data['complaint_description_list'] =
this.complaintDescriptionList!.map((v) => v.toJson()).toList();
}
data['next_service'] = this.nextService;
data['session_exists'] = this.sessionExists;
return data;
}
}
class ComplaintCategoryList {
String? id;
String? name;
ComplaintCategoryList({this.id, this.name});
ComplaintCategoryList.fromJson(Map<String, dynamic> json) {
id = json['id'];
name = json['name'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['name'] = this.name;
return data;
}
}
class ComplaintTypeList {
String? id;
String? name;
ComplaintTypeList({this.id, this.name});
ComplaintTypeList.fromJson(Map<String, dynamic> json) {
id = json['id'];
name = json['name'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['name'] = this.name;
return data;
}
}
class ComplaintDescriptionList {
String? id;
String? name;
ComplaintDescriptionList({this.id, this.name});
ComplaintDescriptionList.fromJson(Map<String, dynamic> json) {
id = json['id'];
name = json['name'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['name'] = this.name;
return data;
}
}
\ No newline at end of file
import 'package:flutter/foundation.dart';
class AttendanceNotifier extends ChangeNotifier{
}
\ No newline at end of file
import 'package:flutter/foundation.dart';
class Counter extends ChangeNotifier{
int _count = 0;
get count => _count;
void incrementCount(){
_count++;
notifyListeners();
}
}
\ No newline at end of file
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:generp/Utils/SharedpreferencesService.dart';
import 'package:generp/screens/LoginScreen.dart';
import 'package:generp/services/api_calling.dart';
import 'package:intl/intl.dart';
import '../Utils/WebSocketManager.dart';
import '../Utils/background_service.dart';
class HomescreenNotifier extends ChangeNotifier {
String isBatterIgnoredText = 'Unknown';
String _username = "";
String _email = "";
String _curdate = "";
String _empId = "";
String _session = "";
String _webPageUrl = "";
String _whizzdomPageUrl = "";
String _roleStatus = "";
int _att_status = 0;
int _loginStatus = 0;
bool _isLoading = true;
var _Sessionid;
var _onlineStatus;
String get username => _username;
String get email => _email;
String get curdate => _curdate;
String get empId => _empId;
String get session => _session;
String get webPageUrl => _webPageUrl;
String get whizzdomPageUrl => _whizzdomPageUrl;
String get roleStatus => _roleStatus;
int get att_status => _att_status;
int get loginStatus => _loginStatus;
get Sessionid => _Sessionid;
get onlineStatus => _onlineStatus;
WebSocketManager webSocketManager = WebSocketManager(
onConnectSuccess: () {
// Handle on connect success callback
},
onMessage: (message) {
// Handle on message callback
},
onClose: () {
// Handle on close callback
},
onConnectFailed: () {
// Handle on connect failed callback
},
);
Future<void> DashboardApiFunction(context) async {
try {
_loginStatus = await SharedpreferencesService().getInt("loginStatus") ?? 0;
_empId = await SharedpreferencesService().getString("UserId") ?? "";
_username = await SharedpreferencesService().getString("UserName") ?? "";
_email = await SharedpreferencesService().getString("UserEmail") ?? "";
_session = await SharedpreferencesService().getString("Session_id") ?? "";
_roleStatus = await SharedpreferencesService().getString("roles") ?? "";
var lastLocationTime = await SharedpreferencesService().getString(
"lastLocationTime",
);
notifyListeners();
print("lastLocationTime:${lastLocationTime}");
if (await SharedpreferencesService().getString("redirectUrl") == null) {
_webPageUrl =
"https://erp.gengroup.in/ci/app/home/web_erp?emp_id=$empId&session_id=$session";
_whizzdomPageUrl =
"https://erp.gengroup.in/ci/app/home/web_erp?emp_id=$empId&session_id=$session&login_type=whizzdom&redirect_url=https://whizzdom.gengroup.in";
} else {
_webPageUrl =
"https://erp.gengroup.in/ci/app/home/web_erp?emp_id=$empId&session_id=$session&redirect_url=${await SharedpreferencesService().getString("redirectUrl").toString()}";
_whizzdomPageUrl =
"https://erp.gengroup.in/ci/app/home/web_erp?emp_id=$empId&session_id=$session&login_type=whizzdom&redirect_url=${await SharedpreferencesService().getString("redirectUrl").toString()}";
}
notifyListeners();
if (kDebugMode) {
print("s:" + session);
print("r:" + roleStatus);
print(roleStatus.length);
}
final data = await ApiCalling.DashboardFunctionApi(
empId ?? "",
session ?? "",
);
if (data != null) {
if (data.sessionExists == 1) {
_isLoading = false;
_att_status = data.attStatus ?? 0;
// BatteryOptimisation();
// checkOptimisation(),
if (att_status == 0) {
webSocketManager.close();
BackgroundLocation.stopLocationService();
_onlineStatus = "Offline";
// print("setstatus:$setstatus");
} else if (att_status == 1) {
// print("att_status:$att_status");
DateTime Date1;
DateTime Date2;
String getCurrentTime() {
DateTime now = DateTime.now(); // Get current time
DateFormat formatter = DateFormat('HH:mm:ss'); // Define the format
return formatter.format(now); // Format and return the time string
}
String currentTime = getCurrentTime();
// var currentTime = DateTime.now();
// var df = DateFormat('HH:mm:ss').format(currentTime);
if (lastLocationTime != null) {
Date1 = DateFormat('HH:mm:ss').parse(currentTime);
Date2 = DateFormat('HH:mm:ss').parse(lastLocationTime);
Duration difference = Date1.difference(Date2);
var diff = difference.inSeconds / 1000;
// print(diff);
if (diff >= 20) {
// print("diff");
_onlineStatus = "Offline";
} else {
// print("nodiff");
_onlineStatus = "Online";
}
} else {
// print("Status knlknn offine");
}
BackgroundLocation.startLocationService();
// print("setstatus:$setstatus");
} else if (att_status == 2) {
// print("att_status:$att_status");
webSocketManager.close();
BackgroundLocation.stopLocationService();
_onlineStatus = "Offline";
// print("setstatus:$setstatus");
}
notifyListeners();
} else if (data.sessionExists == 0) {
SharedpreferencesService().clearPreferences();
Navigator.push(
context,
MaterialPageRoute(builder: (context) => LoginScreen()),
);
notifyListeners();
// print(data.toString());
}
} else {
// print("Something went wrong, Please try again.")
}
} on Exception catch (e) {
print("$e");
}
}
}
\ No newline at end of file
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:generp/Notifiers/HomeScreenNotifier.dart';
import 'package:generp/Utils/SharedpreferencesService.dart';
import 'package:generp/screens/LoginScreen.dart';
import 'package:generp/services/api_calling.dart';
class LogoutNotifier extends ChangeNotifier{
bool _isLoading = false;
bool get isLoading => _isLoading;
Future<void> LogoutApiFunction(HomescreenNotifier prov,BuildContext context) async {
// print("lohi");
try {
final data = await ApiCalling.LogoutFunctionApi(prov.empId ?? "", prov.session ?? "");
if (data != null)
{
if (data.error == 0) {
_isLoading = false;
SharedpreferencesService().clearPreferences();
Navigator.push(context,
MaterialPageRoute(builder: (context) => LoginScreen()));
notifyListeners();
} else {
// print(data.toString());
}
}
else{}
// {print("Something went wrong, Please try again.")}
} on Exception catch (e) {
print("$e");
}
}
}
\ No newline at end of file
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:generp/Notifiers/HomeScreenNotifier.dart';
import 'package:generp/Utils/SharedpreferencesService.dart';
import 'package:generp/screens/LoginScreen.dart';
import 'package:generp/services/api_calling.dart';
import 'package:provider/provider.dart';
class ProfileNotifer extends ChangeNotifier{
var _profileImage = "";
var _company = "";
var _branch = "";
var _designation;
var _mobile_num = "";
var _isLoading =false;
var _secretKey ="";
var _latestversion ="";
var _releaseNotes ="";
var _employeeName ="";
var _employerID ="";
var _employeeDesignation ="";
var _employeeEmail ="";
get profileImage => _profileImage;
get company => _company;
get branch => _branch;
get designation => _designation;
get mobileNUmber => _mobile_num;
get isLoading => _isLoading;
get secretKey => _secretKey;
get latestVersion => _latestversion;
get releaseNotes => _releaseNotes;
get employeeName => _employeeName;
get employeeeID => _employerID;
get employeeDesignation => _employeeDesignation;
get employeeEmail => _employeeEmail;
Future<void> ProfileApiFunction(HomescreenNotifier prov, BuildContext context) async {
try {
final data = await ApiCalling.ProfileFunctionApi(prov.empId ?? "", prov.session ?? "");
if (data != null)
{
if (data.sessionExists == 1) {
_profileImage = data.profilePic ?? "";
_company = data.company ?? "";
_branch = data.branchName ?? "";
_designation = data.designation ?? "";
_mobile_num = data.mobileNo ?? "";
_isLoading = false;
_secretKey = data.totpSecret!;
_employeeName = data.empName??"";
_employerID = data.empId??"";
_employeeDesignation = data.designation??"";
_employeeEmail = data.emailId??"";
notifyListeners();
} else if (data.sessionExists == 0) {
SharedpreferencesService().clearPreferences();
Navigator.push(context,
MaterialPageRoute(builder: (context) => LoginScreen()));
notifyListeners();
// print(data.toString());
}
}
else
{print("Something went wrong, Please try again.");}
} on Exception catch (e) {
print("$e");
}
}
Future<void> VersionApiFunction() async {
try {
final data = await ApiCalling.checkAppVersionApi();
if (data != null)
{
_latestversion = data.latestVersion ?? "";
if (Platform.isAndroid) {
_releaseNotes = data.releaseNotes ?? "";
} else if (Platform.isIOS) {
_releaseNotes = data.iosReleaseNotes ?? "";
}
notifyListeners();
}
else
{print("Something went wrong, Please try again.");}
} on Exception catch (e) {
print("$e");
}
}
}
\ No newline at end of file
import 'dart:io';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:generp/Utils/SharedpreferencesService.dart';
import 'package:generp/screens/HomeScreen.dart';
import 'package:generp/services/api_calling.dart';
import 'package:android_id/android_id.dart';
import 'package:device_info_plus/device_info_plus.dart';
import '../Utils/commonServices.dart';
class Loginnotifier extends ChangeNotifier {
// Private variables
String _emailError = '';
String _passwordError = '';
bool _isLoading = false;
int? _loginErrorCode;
bool _pwdVisible = false;
String _email = '';
String _password = '';
String _deviceDetails = "";
String _deviceId = "";
String _androidId = 'Unknown';
static const _androidIdPlugin = AndroidId();
bool get isButtonEnabled =>
_email.isNotEmpty &&
_password.isNotEmpty &&
RegExp(r'\S+@\S+\.\S+').hasMatch(_email);
// Public getters
String get emailError => _emailError;
String get passwordError => _passwordError;
bool get isLoading => _isLoading;
int? get loginErrorCode => _loginErrorCode;
bool get pwdVisible => _pwdVisible;
String get deviceId => _deviceId;
String get deviceDetails => _deviceDetails;
String get AndroidDevId => _androidId;
Future<void> initAndroidId() async {
String androidId;
var deviceInfo = DeviceInfoPlugin(); // import 'dart:io'
var androidDeviceInfo = await deviceInfo.androidInfo;
_deviceDetails = await "Version Name: " +
androidDeviceInfo.version.baseOS.toString().trim() +
", " +
"Version Code: " +
androidDeviceInfo.version.codename.toString().trim() +
", " +
"OS Version: " +
androidDeviceInfo.version.codename.toString().trim() +
", SDK Version: " +
androidDeviceInfo.version.sdkInt.toString().trim() +
", Device: " +
androidDeviceInfo.device.toString().trim() +
", Model: " +
androidDeviceInfo.model.toString().trim() +
", Product: " +
androidDeviceInfo.product.toString().trim() +
", Manufacturer: " +
androidDeviceInfo.manufacturer.toString().trim() +
", Brand: " +
androidDeviceInfo.brand.toString().trim() +
", User: " +
androidDeviceInfo.data['user'].toString().trim() +
", Display: " +
androidDeviceInfo.display.toString().trim() +
", Hardware: " +
androidDeviceInfo.hardware.toString().trim() +
", Board: " +
androidDeviceInfo.board.toString().trim() +
", Host: " +
androidDeviceInfo.host.toString().trim() +
", Serial: " +
androidDeviceInfo.serialNumber.toString().trim() +
", ID: " +
androidDeviceInfo.id.toString().trim() +
", Bootloader: " +
androidDeviceInfo.bootloader.toString().trim() +
", CPU ABI1: " +
androidDeviceInfo.supported64BitAbis.toString().trim() +
", CPU ABI2: " +
androidDeviceInfo.supported64BitAbis.toString().trim() +
", FingerPrint: " +
androidDeviceInfo.fingerprint.toString().trim();
try {
androidId = await _androidIdPlugin.getId() ?? 'Unknown ID';
_deviceId = androidId;
debugPrint("testing" + deviceId);
debugPrint(_deviceDetails.toString());
} on PlatformException {
androidId = 'Failed to get Android ID.';
}
_androidId = androidId;
print(_deviceDetails);
print(_deviceId);
print(_androidId);
}
Future<String?> getDevId() async {
var deviceInfo = DeviceInfoPlugin(); // import 'dart:io'
var iosDeviceInfo = await deviceInfo.iosInfo;
_deviceId = iosDeviceInfo.identifierForVendor!;
_deviceDetails = iosDeviceInfo.toString();
}
bool visibility_ov(){
_pwdVisible = !_pwdVisible;
print(_pwdVisible);
notifyListeners();
return _pwdVisible;
}
// Update methods for fields
void updateEmail(String email) {
_email = email;
_emailError = '';
notifyListeners();
}
void updatePassword(String password) {
_password = password;
_passwordError = '';
notifyListeners();
}
// Validation
bool _validate(String email, String password) {
_emailError = '';
_passwordError = '';
if (!RegExp(r'\S+@\S+\.\S+').hasMatch(email)) {
_emailError = "Please enter a valid email address";
}
if (password.isEmpty) {
_passwordError = "Please enter your password";
}
notifyListeners();
return _emailError.isEmpty && _passwordError.isEmpty;
}
Future<void> LoginApiFunction(
context,
email,
password,
) async {
try {
if (!_validate(email, password)) return;
_isLoading = true;
notifyListeners();
String? fcmToken = await FirebaseMessaging.instance.getToken();
final data = await ApiCalling.LoginFunctionApi(
email,
password,
fcmToken.toString() ?? "",
deviceId.toString() ?? "",
deviceDetails.toString(),
);
if (data != null) {
_isLoading = false;
_loginErrorCode = data?.error;
notifyListeners();
debugPrint("${data.error} login error here");
if (data.error == 0) {
SharedpreferencesService().saveInt("loginStatus", 1);
SharedpreferencesService().saveString("UserId", data.userId!);
SharedpreferencesService().saveString("UserName", data.name!);
SharedpreferencesService().saveString("UserEmail", data.emailId!);
SharedpreferencesService().saveString("Session_id", data.sessionId!);
var roles = data.permissions!.toString();
SharedpreferencesService().saveString("roles", roles);
Navigator.push(
context,
MaterialPageRoute(builder: (context) => MyHomePage()),
);
} else if (data.error == 1) {
toast(context,
"You are not authorized to login in this device !");
} else if (data.error == 2) {
toast(context, "Invalid login credentials !");
} else {
toast(context, "Invalid login credentials !");
}
} else {}
} on Exception catch (e) {
debugPrint("$e");
}
}
}
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:generp/Models/VersionsResponse.dart';
import 'package:generp/Utils/SharedpreferencesService.dart';
import 'package:generp/screens/HomeScreen.dart';
import 'package:generp/screens/LoginScreen.dart';
import 'package:generp/screens/UpdatePasswordScreen.dart';
import 'package:package_info_plus/package_info_plus.dart';
import '../services/api_calling.dart';
class SplashVersionNotifier extends ChangeNotifier {
VersionsResponse? versionsResponse;
Map<String, String> _packagedetails = {};
VersionsResponse? get versionDetails => versionsResponse;
Map<String, String> get packageDetails => _packagedetails;
Future<void> initPackageInfo() async {
PackageInfo packageInfo = await PackageInfo.fromPlatform();
_packagedetails = {
"Version": packageInfo.version,
"App Name": packageInfo.appName,
"Package Name": packageInfo.packageName,
"Build Number": packageInfo.buildNumber,
};
notifyListeners();
}
Future<void> handleVersionCheck(context) async {
var loginStatus = await SharedpreferencesService().getInt("loginstatus");
try {
final data = await ApiCalling.checkAppVersionApi();
if (data != null) {
final int currentBuild =
int.tryParse(_packagedetails["Build Number"] ?? "0") ?? 0;
if (Platform.isAndroid &&
currentBuild < (data.latestVersionCode ?? 0)) {
print("Update");
// AppUpdateDialouge(data.url!, data.releaseNotes!);
} else if (Platform.isIOS &&
currentBuild < (data.iosLatestVersionCode ?? 0)) {
print("Update");
// AppUpdateDialouge(data.iosUrl!, data.iosReleaseNotes!);
} else {
// Version is up to date
if (loginStatus == 0) {
Navigator.of(
context,
).push(MaterialPageRoute(builder: (context) => LoginScreen()));
} else {
getSessiondetailsApiFunction(
context,
); // make sure this is accessible
}
}
notifyListeners();
} else {
debugPrint("Version check returned null data.");
}
} catch (e) {
debugPrint("Version check failed: $e");
}
}
Future<void> getSessiondetailsApiFunction(context) async {
var session = await SharedpreferencesService().getString("Session_id");
var empId = await SharedpreferencesService().getString("UserId");
try {
final data = await ApiCalling.CheckSessionExistsApi(empId, session);
if (data != null) {
if (data.sessionExists == 1) {
print("geos session");
if (data.updatePasswordRequired == 0) {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => MyHomePage()),
);
} else if (data.updatePasswordRequired == 1) {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => UpdatepasswordScreen()),
);
}
} else {
print("goes here");
Navigator.push(
context,
MaterialPageRoute(builder: (context) => LoginScreen()),
);
// toast(context,
// "Your Session has been expired, Please Login Again");
}
notifyListeners();
} else {
//toast(context,"Something went wrong, Please try again later!")
}
} on Error catch (e) {
print(e.toString());
}
}
}
import 'package:shared_preferences/shared_preferences.dart';
class SharedpreferencesService {
void saveString(String key, String value) async {
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
sharedPreferences.setString(key, value);
}
void saveInt(String key, int value) async {
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
sharedPreferences.setInt(key, value);
}
void saveBool(String key, bool value) async {
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
sharedPreferences.setBool(key, value);
}
void saveDouble(String key, double value) async {
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
sharedPreferences.setDouble(key, value);
}
Future<String?> getString(String key) async {
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
return sharedPreferences.getString(key);
}
Future<int?> getInt(String key) async {
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
return sharedPreferences.getInt(key);
}
Future<double?> getDouble(String key) async {
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
return sharedPreferences.getDouble(key);
}
Future<bool?> getBoolean(String key) async {
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
return sharedPreferences.getBool(key);
}
void clearPreferences()async{
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
sharedPreferences.clear();
}
}
import 'dart:async';
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:generp/Utils/SharedpreferencesService.dart';
import 'package:http/http.dart' as http;
import 'package:web_socket_channel/io.dart';
class WebSocketManager {
static const int MAX_NUM = 50; // Maximum number of reconnections
static const int MILLIS = 50000;
late String TAG;
late http.Client client;
late http.Request request;
// String url;
bool isConnect = false;
int connectNum = 0;
IOWebSocketChannel? channel;
StreamSubscription? subscription;
Function()? onConnectSuccess;
Function(String)? onMessage;
Function()? onClose;
Function()? onConnectFailed;
WebSocketManager(
{this.onConnectSuccess,
this.onMessage,
this.onClose,
this.onConnectFailed});
// void init() async{
// TAG = 'WebSocketManager';
// client = http.Client();
// request = http.Request('GET', Uri.parse('wss://ws.erp.gengroup.in/?type=user&route=employe_live_location_update&session_id=${await PreferenceService().getString("Session_id")}'));
// print('WebSocket Initiated');
// }
Future<bool> init() async {
try {
TAG = 'WebSocketManager';
client = http.Client();
request = http.Request('GET', Uri.parse('wss://ws.erp.gengroup.in/?type=user&route=employe_live_location_update&session_id=${await SharedpreferencesService().getString("Session_id")}'));
print('WebSocket Initiated');
return true; // WebSocket initialization successful
} catch (e) {
print('Failed to initialize WebSocket: $e');
return false; // WebSocket initialization failed
}
}
void connect() async {
if (isConnected()) {
print('WebSocket connected');
return;
}
print('WebSocket Not connected');
try {
final sessionId = await SharedpreferencesService().getString("Session_id");
final url = 'wss://ws.erp.gengroup.in/?type=user&route=employe_live_location_update&session_id=$sessionId';
print(url);
channel = IOWebSocketChannel.connect(url);
channel!.stream.handleError((error) {
print('WebSocket error: $error');
// Handle error appropriately
});
if (channel == null) {
print('Failed to connect to WebSocket');
return; // Exit the function if connection failed
}
subscription = channel!.stream.listen((message) {
print('Received: $message');
onMessage?.call(message);
}, onError: (error) {
print('WebSocket error: $error');
onClose?.call();
reconnect();
}, onDone: () {
print('WebSocket closed');
onClose?.call();
reconnect();
}, cancelOnError: true);
isConnect = true;
onConnectSuccess?.call();
} catch (e) {
print('Error connecting to WebSocket: $e');
// Handle error appropriately (e.g., retry connection, show error message)
}
}
void reconnect() {
if (connectNum <= MAX_NUM) {
Future.delayed(Duration(milliseconds: MILLIS), () {
connect();
connectNum++;
});
} else {
print('Reconnect over $MAX_NUM, please check URL or network');
}
}
// void sendMessage(String text) {
// if (!isConnected())
// return;
// channel?.sink.add(text);
// print('Send Message Completed');
// }
void sendMessage(String text) {
if (isConnected()) {
print('WebSocket is not connected. Message not sent.');
// connect();
return;
}
// Add listener to the sink's done event
channel?.sink.done.then((_) {
print('WebSocket sink is closed. Message not sent.');
}).catchError((error) {
print('Error occurred while sending message: $error');
});
// Send the message
channel?.sink.add(text);
print('Message sent: $text');
}
bool isConnected() {
return isConnect;
}
Future<void> close() async {
if (isConnected()) {
print('WebSocket Closed');
channel?.sink.close();
channel = null;
isConnect = false;
}
}
Future<bool> isNetworkAvailable() async {
var connectivityResult = await (Connectivity().checkConnectivity());
if (connectivityResult == ConnectivityResult.none) {
return false;
} else {
return true;
}
}
}
import 'dart:ui';
class AppColors {
static Color white = Color(0xFFFFFFFF);
static Color semi_black = Color(0xFF2D2D2D);
static Color app_blue = Color(0xFF1487C9);
static Color greenish = Color(0xFF00BC57);
static Color grey_semi = Color(0xFF999999);
static Color grey_thick = Color(0xFF818181);
static Color red = Color (0xFFFF0000);
static Color thick_navy_blue = Color(0xff023047);
static Color cyan_blue = Color(0xFF219EBC);
static Color profile_card_gradient1 = Color(0xFFCFEEFF);
static Color profile_card_gradient2 = Color(0xFF97D9FF);
static Color scaffold_bg_color = Color(0xFFF0F4F5);
static Color button_disabled = Color(0xFFBEE5FB);
static Color text_field_color = Color(0xFFF0F4F5);
static Color overlay_box_color = Color(0xFFE6F6FF);
static Color ERP_text_color = Color(0xFF2D357F);
}
\ No newline at end of file
import 'dart:async';
import 'dart:convert';
import 'dart:io' show Platform;
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:generp/Utils/SharedpreferencesService.dart';
import 'package:geolocator/geolocator.dart';
import 'package:intl/intl.dart';
import 'package:location/location.dart' as loc;
import 'package:location/location.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'WebSocketManager.dart';
/// BackgroundLocation plugin to get background
/// lcoation updates in iOS and Android
class BackgroundLocation {
// The channel to be used for communication.
// This channel is also refrenced inside both iOS and Abdroid classes
static const MethodChannel _channel =
MethodChannel('com.almoullim.background_location/methods');
static Timer? _locationTimer;
static get context => null;
static const String customChannelId = 'GEN ERP flutter';
static const String customChannelName = 'GEN ERP flutter';
static const String customChannelDescription = 'GEN ERP flutter';
String input = "";
static const int notificationId = 0;
WebSocketManager webSocketManager = WebSocketManager(
onConnectSuccess: () {
// Handle WebSocket connection success
},
onMessage: (message) {
// Handle incoming WebSocket message
},
onClose: () {
// Handle WebSocket connection closure
},
onConnectFailed: () {
// Handle WebSocket connection failure
},
);
static final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
FlutterLocalNotificationsPlugin();
static void init() async {
try {
final InitializationSettings initializationSettings =
InitializationSettings(
android: AndroidInitializationSettings('@mipmap/ic_launcher'),
iOS: DarwinInitializationSettings(
requestAlertPermission: false,
requestBadgePermission: false,
requestSoundPermission: false,
));
await flutterLocalNotificationsPlugin.initialize(initializationSettings);
// Disable sound for the default notification channel
const AndroidNotificationChannel androidChannel =
AndroidNotificationChannel(
customChannelId,
customChannelName,
description: customChannelDescription,
importance: Importance.max,
playSound: false, // Set this to false to disable playing sound
);
await flutterLocalNotificationsPlugin
.resolvePlatformSpecificImplementation<
AndroidFlutterLocalNotificationsPlugin>()
?.createNotificationChannel(androidChannel);
// print("Flutter Local Notifications initialized successfully.");
} catch (e) {
// print("Error initializing Flutter Local Notifications: $e");
// Handle initialization error as needed
}
}
static Future<void> checkAndRequestLocationPermissions() async {
bool isLocationEnabled = false;
bool hasLocationPermission = false;
// Check if location services are enabled
isLocationEnabled = await Geolocator.isLocationServiceEnabled();
// Check if the app has been granted location permission
LocationPermission permission = await Geolocator.checkPermission();
hasLocationPermission = permission == LocationPermission.always ||
permission == LocationPermission.whileInUse;
final loc.Location location = loc.Location();
bool serviceEnabled;
PermissionStatus permissionGranted;
serviceEnabled = await location.serviceEnabled();
if (!serviceEnabled) {
serviceEnabled = await location.requestService();
if (!serviceEnabled) {
return;
}
}
permissionGranted = (await location.hasPermission());
if (permissionGranted == PermissionStatus) {
permissionGranted = (await location.requestPermission());
if (permissionGranted != PermissionStatus) {
return;
}
}
}
static void showNotification(String title, String message) async {
const AndroidNotificationDetails androidPlatformChannelSpecifics =
AndroidNotificationDetails(
customChannelId,
customChannelName,
importance: Importance.defaultImportance,
ticker: 'ticker',
ongoing: true,
playSound: false,
);
const DarwinNotificationDetails darwinNotificationDetails =
DarwinNotificationDetails(
presentSound: false,
sound: "",
// Set this to false to disable playing sound
);
const NotificationDetails platformChannelSpecifics = NotificationDetails(
android: androidPlatformChannelSpecifics,
iOS: darwinNotificationDetails);
// Check if the notification with the same ID is already being shown
final List<PendingNotificationRequest> pendingNotifications =
await flutterLocalNotificationsPlugin.pendingNotificationRequests();
final notificationAlreadyExists = pendingNotifications
.any((notification) => notification.id == notificationId);
// If notification already exists, update it; otherwise, show a new one
if (notificationAlreadyExists) {
await flutterLocalNotificationsPlugin.show(
notificationId,
title,
message,
platformChannelSpecifics,
);
} else {
await flutterLocalNotificationsPlugin.show(
notificationId,
title,
message,
platformChannelSpecifics,
);
}
}
static void hideNotification(int notificationId) async {
await flutterLocalNotificationsPlugin.cancel(0);
}
void initWebSocket() {
Future.delayed(Duration.zero, () {
webSocketManager.connect();
});
}
/// Stop receiving location updates
static stopLocationService() async {
// print("Background location Service stopped");
hideNotification(0);
if (_locationTimer != null) {
_locationTimer!.cancel();
}
return await _channel.invokeMethod('stop_location_service');
}
/// Check if the location update service is running
static Future<bool> isServiceRunning() async {
var result = await _channel.invokeMethod('is_service_running');
return result == true;
}
static Future<bool> checkGpsStatus() async {
// print("Hello");
bool isGpsEnabled = await Geolocator.isLocationServiceEnabled();
return isGpsEnabled;
}
static Future<bool> checkNetworkStatus() async {
// print("Hello");
var connectivityResult = await Connectivity().checkConnectivity();
return connectivityResult != ConnectivityResult.none;
}
/// Start receiving location updates at 5-second interval
static startLocationService() async {
init();
bool isGpsEnabled = await checkGpsStatus();
bool isNetworkAvailable = await checkNetworkStatus();
if (isGpsEnabled && isNetworkAvailable) {
// Both GPS and network are available, start background location service
// Your code to start background location service goes here
// print("GEN ERP You're Online !");
showNotification("GEN ERP", "You're Online !");
} else {
// Notify the user to enable GPS or connect to a network
if (!isGpsEnabled) {
// Notify user to enable GPS
checkAndRequestLocationPermissions();
showNotification(
"GEN ERP", "You're Offline !, Check your GPS connection.");
// print(
// 'GPS is not enabled. Please enable GPS to start the location service.');
}
if (!isNetworkAvailable) {
// Notify user to connect to a network
showNotification(
"GEN ERP", "You're Offline !, Check your network connection.");
// print(
// 'Network is not available. Please connect to a network to start the location service.');
}
}
// print("Background location Service started");
// Stop previous timer if running
BackgroundLocation backgroundLocation = BackgroundLocation();
// Initialize WebSocket
backgroundLocation.initWebSocket();
stopLocationService();
// Start a new timer for location updates
_locationTimer = Timer.periodic(Duration(seconds: 10), (timer) async {
await _channel.invokeMethod('start_location_service');
var location = await BackgroundLocation().getCurrentLocation();
});
}
// static setAndroidNotification(
// {String? title, String? message, String? icon}) async {
// if (Platform.isAndroid) {
// return await _channel.invokeMethod('set_android_notification',
// <String, dynamic>{'title': title, 'message': message, 'icon': icon});
// } else {
// //return Promise.resolve();
// }
// }
// static setAndroidConfiguration(int interval) async {
// if (Platform.isAndroid) {
// return await _channel.invokeMethod('set_configuration', <String, dynamic>{
// 'interval': interval.toString(),
// });
// } else {
// //return Promise.resolve();
// }
// }
String? empId;
String? sessionId;
/// Get the current location once.
Future<Location> getCurrentLocation() async {
empId = await SharedpreferencesService().getString("UserId");
sessionId = await SharedpreferencesService().getString("Session_id");
// print('Received Location Update: of GEN ERP');
saveLastLocationTime();
var completer = Completer<Location>();
var _location = Location();
await getLocationUpdates((location) {
_location.latitude = location.latitude;
_location.longitude = location.longitude;
_location.accuracy = location.accuracy;
_location.altitude = location.altitude;
_location.bearing = location.bearing;
_location.speed = location.speed;
_location.time = location.time;
completer.complete(_location);
});
return completer.future;
}
/// Register a function to recive location updates as long as the location
/// service has started
getLocationUpdates(Function(Location) location) {
// add a handler on the channel to recive updates from the native classes
_channel.setMethodCallHandler((MethodCall methodCall) async {
if (methodCall.method == 'location') {
var locationData = Map.from(methodCall.arguments);
// print('Received Location Update: $locationData');
// toast(context,'Received Location Update: $locationData');
// Call the user passed function
location(
Location(
latitude: locationData['latitude'],
longitude: locationData['longitude'],
altitude: locationData['altitude'],
accuracy: locationData['accuracy'],
bearing: locationData['bearing'],
speed: locationData['speed'],
time: locationData['time'],
isMock: locationData['is_mock']),
);
//Send location updates using WebSocketManager
if (await webSocketManager.isNetworkAvailable()) {
webSocketManager.sendMessage(jsonEncode({
"command": "server_request",
"route": "attendenece_live_location_update",
"session_id": sessionId,
"ref_data": {
"session_id": sessionId,
"location":
"${locationData['latitude']},${locationData['longitude']}",
"speed": locationData['speed'],
"altitude": locationData['altitude'],
"direction": locationData['bearing'],
"direction_accuracy": locationData['bearingAccuracyDegrees'],
"altitude_accuracy": locationData['verticalAccuracyMeters'],
"speed_accuracy": locationData['speedAccuracyMetersPerSecond'],
"location_accuracy": locationData['accuracy'],
"location_provider": "",
}
}));
// print("Hello GENERP! You're Online!");
showNotification("GEN ERP", "You're Online!");
} else {
// print("Hello GENERP! You're Offline!");
showNotification("GEN ERP", "You're Offline!");
}
saveLastLocationTime();
}
});
}
// Future<Location> getCurrentLocation() async {
// empId = await PreferenceService().getString("UserId");
// sessionId = await PreferenceService().getString("Session_id");
// print('Requesting Current Location...');
//
// // Create a completer to handle the asynchronous nature of obtaining location
// var completer = Completer<Location>();
//
// // Define a boolean flag to track if the completer is completed
// var isCompleterCompleted = false;
//
// // Define a function to handle the location once obtained
// void handleLocation(Location location) {
// // Complete the completer only if it hasn't been completed before
// if (!isCompleterCompleted) {
// completer.complete(location);
// isCompleterCompleted = true; // Set the flag to true to indicate completion
// }
// }
//
// // Start listening for location updates
// getLocationUpdates((location) {
// handleLocation(location);
// });
//
// // Return the future from the completer
// return completer.future;
// }
//
//
// void getLocationUpdates(Function(Location) location) {
// // Define a function to handle location updates
// void handleLocation(Position position) async {
// // Create a Location object from the Position data
// Location locationData = Location(
// latitude: position.latitude,
// longitude: position.longitude,
// altitude: position.altitude,
// accuracy: position.accuracy,
// bearing: position.heading,
// speed: position.speed,
// time: position.timestamp.millisecondsSinceEpoch,
// isMock: false, // Assuming the position is not mocked
// );
// print('Received Location Update:${locationData}');
// // Call the user passed function with the location data
// location(locationData);
//
// // Send location updates using WebSocketManager
// // Assuming webSocketManager and sessionId are defined elsewhere
// if (await webSocketManager.isNetworkAvailable()) {
// webSocketManager.sendMessage(jsonEncode({
// "command": "server_request",
// "route": "attendenece_live_location_update",
// "session_id": sessionId,
// "ref_data": {
// "session_id": sessionId,
// "location": "${position.latitude},${position.longitude}",
// "speed": position.speed,
// "altitude": position.altitude,
// "direction": position.heading,
// "direction_accuracy": position.headingAccuracy,
// "altitude_accuracy":position.altitudeAccuracy,
// "speed_accuracy":position.speedAccuracy,
// "location_accuracy": position.accuracy,
// "location_provider": "",
// // Include additional location attributes as needed
// }
// }));
// print("Hello GENERP! You're Online!");
// showNotification("GEN ERP", "You're Online!");
// } else {
// print("Hello GENERP! You're Offline!");
// showNotification("GEN ERP", "You're Offline!");
// }
// saveLastLocationTime();
// }
//
// // Start listening for location updates
// Geolocator.getPositionStream().listen((Position position) {
// // Handle the received location
// handleLocation(position);
// }, onError: (error) => print("Error receiving location: $error"));
// }
}
saveLastLocationTime() {
var currentTime = DateTime.now();
var formatter = DateFormat('HH:mm:ss').format(currentTime);
SharedpreferencesService().saveString("lastLocationTime", formatter);
// print("formatter:${formatter}");
}
/// about the user current location
class Location {
double? latitude;
double? longitude;
double? altitude;
double? bearing;
double? accuracy;
double? speed;
double? time;
bool? isMock;
Location(
{@required this.longitude,
@required this.latitude,
@required this.altitude,
@required this.accuracy,
@required this.bearing,
@required this.speed,
@required this.time,
@required this.isMock});
toMap() {
var obj = {
'latitude': latitude,
'longitude': longitude,
'altitude': altitude,
'bearing': bearing,
'accuracy': accuracy,
'speed': speed,
'time': time,
'is_mock': isMock
};
return obj;
}
}
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment