|
- import 'dart:async';
- import 'dart:convert';
- import 'dart:io';
- import 'package:assetstock/util/download_Upload_Handler.dart';
- import 'package:flutter/services.dart';
- import 'package:path/path.dart';
- import 'package:flutter/cupertino.dart';
- import 'package:flutter/material.dart';
- import 'package:path_provider/path_provider.dart';
- import 'main.dart';
- import 'util/prefsKey.dart';
- import 'util/dbHandler.dart';
- import 'package:permission_handler/permission_handler.dart' as pHandler;
- import 'package:device_info_plus/device_info_plus.dart';
-
-
-
- class Home extends StatefulWidget {
- Home({Key key}) : super(key: key);
-
- @override
- _HomeState createState() => _HomeState();
- }
-
- class _HomeState extends State<Home> {
- List<Widget> Menus = [];
- final hostAddress = new TextEditingController();
- StreamSubscription _dlulStream;
- double progress,progressDL;
- loadMenu()async{
- Menus.add(Padding(
- padding: const EdgeInsets.all(8.0),
- child: Container(
- decoration: BoxDecoration(
- color: Colors.white,
- borderRadius: BorderRadius.circular(5)
- ),
- child: Text('Get Data'),
- ),
- ));
-
- setState(() {
- });
- }
- @override
- void initState() {
- // TODO: implement initState
- super.initState();
- WidgetsBinding.instance.addPostFrameCallback((_) async {
- // await loadMenu();
- // final androidVersion = await DeviceInfoPlugin().androidInfo;
- // if ((androidVersion.version.sdkInt ?? 0) >= 30) {
- // await util.permissionCheck(this.context,pHandler.Permission.manageExternalStorage,()async{print("storage permit granted!");},customMessage: " untuk menyimpan data backup");
- // } else {
- await util.permissionCheck(this.context,pHandler.Permission.storage,()async{print("storage permit granted!");},customMessage: " untuk menyimpan data backup");
- // }
- });
- }
-
- clearData(context)async{
- String errMsg;
- Directory documentsDirectory = await getApplicationDocumentsDirectory();
- String path = join(documentsDirectory.path, "assets.db");
- File db = File(path);
- if(db.existsSync()){
- bool result = await showDialog(context: context,builder: (context)=>WillPopScope(
- onWillPop: ()async{
- Navigator.pop(context,false);
- return false;
- },
- child: AlertDialog(
- title: Text('Clear Data ?'),
- content: Text('Proceed to clear any remaining units data on this device?'),
- actions: <Widget>[
- TextButton(
- child: Text('Proceed'),
- onPressed: ()async{
- util.showLoading(context);
- await Future.sync(()async{
- await prefs.remove(keyClass.dbName);
- // await prefs.setString(keyClass.lastDownload, null);
- // await prefs.setString(keyClass.lastUpload, null);
- // await prefs.setString(keyClass.targetProccess, null);
- setState(() {
- // lastUpload = '';
- // lastDownload = '';
- // timeString = '';
- });
- // var result = await DBHelper.database.deleteAll();
- // if(result!=null) {
-
- // if(result!=null){
- try{
- await DBHelper.database.closeDb();
- db.deleteSync();
- }
- catch(e){
- print(e);
- util.showToast('ERROR','Failed to delete database file');
- }
- // }
- // else{
- // errMsg = 'Failed to clear unit data';
- // }
- // }
- // else{
- // errMsg = 'Failed to clear unit data';
- // }
- });
- Navigator.pop(context);
- Navigator.pop(context,true);
- util.showToast(errMsg==null?"SUCCESS":"ERROR",errMsg??'Data Cleared');
- },
- ),
- TextButton(
- child: Text('Cancel'),
- onPressed: (){Navigator.pop(context,false);},
- )
- ],
- ),
- ));
- return result;
- }
- else return true;
- }
-
- @override
- Widget build(BuildContext context) {
- return Scaffold(
- floatingActionButton: Padding(
- padding: const EdgeInsets.only(bottom:45.0),
- child: FloatingActionButton(
- onPressed: ()async{
- Directory documentsDirectory = await getApplicationDocumentsDirectory();
- String path = join(documentsDirectory.path, "assets.db");
- File db = File(path);
- if(db.existsSync()){
- Navigator.pushNamed(context, '/logs');
- }
- else{
- util.showToast("ALERT", 'Get data Master first');
- }
- },
- child: Icon(Icons.description,size: 30,),
- ),
- ),
- body: Container(
- color: Colors.grey.withOpacity(0.3),
- child:
- // (Menus.length==0)?Container(alignment: Alignment.center,
- // child: Text('Empty',
- // style: TextStyle(fontSize: 20,color: Colors.black38,fontWeight: FontWeight.bold),),)
- // :
- Column(
- children: <Widget>[
- Expanded(
- flex: 1,
- child: Container(
- padding: const EdgeInsets.only(left: 10,top:10,right: 5),
- alignment: Alignment.bottomCenter,
- child: Row(
- mainAxisAlignment: MainAxisAlignment.spaceBetween,
- children: <Widget>[
- Row(
- children: <Widget>[
- Icon(Icons.dashboard,color: Colors.blueGrey,size: 20,),
- SizedBox(width: 5,),
- Text('Menu')
- ],
- ),
- PopupMenuButton(
- itemBuilder: (context)=>[
- PopupMenuItem(
- value: "changeAddress",
- child: Row(
- children: <Widget>[
- Icon(Icons.network_wifi,color: Colors.blueGrey,),
- SizedBox(width: 10,),
- Text('Change Host Address',style: TextStyle(color: Colors.blueGrey,fontWeight: FontWeight.w500),)
- ],
- ),
- ),
- PopupMenuItem(
- value:'backup',
- child: Row(
- children: <Widget>[
- Icon(Icons.save,color: Colors.black,),
- SizedBox(width: 10,),
- Text('Backup Data')
- ],
- ),
- ),
- PopupMenuItem(
- value:'restore',
- child: Row(
- children: <Widget>[
- Icon(Icons.sync,color: Colors.black,),
- SizedBox(width: 10,),
- Text('Restore Data')
- ],
- ),
- ),
- ],
- onSelected: (value)async{
- if(value == "changeAddress"){
- hostAddress.text = prefs.getString(keyClass.hostAddress)??'https://asset.thamringroup.web.id';
- await showDialog(context: context,builder: (context)=>AlertDialog(
- title: Text('Set IP Address'),
- content: TextField(
- controller: hostAddress,
- onSubmitted: (value){
- prefs.setString(keyClass.hostAddress,(value=='')?'https://asset.thamringroup.web.id':value);
- Navigator.pop(context);
- },
- ),
- actions: <Widget>[
- TextButton(
- child: Text('OK'),
- onPressed: (){
- prefs.setString(keyClass.hostAddress,(hostAddress.text=='')?'https://asset.thamringroup.web.id':hostAddress.text);
- Navigator.pop(context);
- },
- )
- ],
- ));
- setState(() {
-
- });
- }
- if(value == 'backup'){
- if(prefs.getString(keyClass.dbName) != null){
- bool isBackup = await showDialog(context: context,builder: (context)=>AlertDialog(
- title: Text('Backup Data ?'),
- content: Text('Backup data akan menghapus dan mengganti data backup unit dan cabang sebelumnya.'),
- actions: <Widget>[
- TextButton(
- child: Text('OK'),
- onPressed: ()async{
- Navigator.pop(context,true);
- },
- ),
- TextButton(
- child: Text('Cancel'),
- onPressed: ()=>Navigator.pop(context,false),
- )
- ],
- ));
- if(isBackup??false){
- var result = await DBHelper.database.backupDb(context:context);
- util.showToast(result["STATUS"]==1?'NORMAL':'ERROR', result['MSG']);
- }
- }
- else{
- util.showToast('ERROR', "Data Unit cabang tidak ditemukan. Silakan get data terlbih dahulu.");
- }
- }
- if(value == 'restore'){
- if(prefs.getString(keyClass.dbName) == null){
- util.showToast('ERROR', "Data Unit cabang tidak ditemukan. Silakan get data terlbih dahulu.");
- }
- else{
- if(prefs.getString(keyClass.dbName) == prefs.getString(keyClass.backup_stock_id)){
- String stock_taking_id = prefs.getString(keyClass.dbName);
- if(stock_taking_id!=null){
- bool isRestore = await showDialog(context: context,builder: (context)=>AlertDialog(
- title: Text('Restore Data ?'),
- content: Text('Restore data akan menghapus dan mengganti data unit dan cabang yang ada dengan data backup.'),
- actions: <Widget>[
- TextButton(
- child: Text('OK'),
- onPressed: ()async{
- Navigator.pop(context,true);
- },
- ),
- TextButton(
- child: Text('Cancel'),
- onPressed: ()=>Navigator.pop(context,false),
- )
- ],
- ));
- if(isRestore??false){
- var response;
- bool isclear;
- Directory documentsDirectory = await getApplicationDocumentsDirectory();
- String path = join(documentsDirectory.path, "assets.db");
- File db = File(path);
- if(db.existsSync()){
- isclear = await clearData(context);
- }
- else{
- isclear = true;
- }
- if(isclear??false){
- var result = await DBHelper.database.restoreDb(context);
- if(result["STATUS"]==1){
- // await prefs.remove(keyClass.lastDownload);
- // await prefs.remove(keyClass.lastUpload);
- // await prefs.remove(keyClass.targetProccess);
- // await prefs.remove(keyClass.submitProccess);
- setState(() {
- // lastUpload = '';
- // lastDownload = '';
- // timeString = '';
- });
- // valueTab value = await DBHelper.database.getValue(keyClass.tgl_start);
- // if(value != null)await prefs.setString(keyClass.lastDownload, DateFormat('dd-MM-yyyy HH:mm:ss').parse(value.value).toIso8601String());
- // else {
- // await prefs.setString(keyClass.lastDownload, DateTime.now().toIso8601String());
- // }
- // value = await DBHelper.database.getValue(keyClass.stock_id);
- // if(value != null) await prefs.setString(keyClass.stock_id,value.value);
- // else {
- await prefs.setString(keyClass.dbName,prefs.getString(keyClass.backup_stock_id));
- // }
- // loadState();
- setState(() {
- // lastDownload = prefs.getString(keyClass.lastDownload);
- });
- }
- response = result["MSG"];
- }
- if(response != null)util.showToast('GENERAL', response);
- }
- }
- }
- else {
- util.showToast("ERROR", "File Backup tidak ditemukan atau sudah selesai");
- }
- }
- }
- },
- child: Padding(
- padding: const EdgeInsets.all(8.0),
- child: Icon(Icons.clear_all,color: Colors.blueGrey,size: 20,),
- ),
- ),
- ],
- ),
- ),
- ),
- Flexible(
- flex: 10,
- child: Container(
- alignment: Alignment.topCenter,
- child: GridView.count(
- padding: EdgeInsets.all(0),
- crossAxisCount: 2,
- children: [
- InkWell(
- onTap: ()async{
- String Address = prefs.getString(keyClass.hostAddress);
- // await Future.delayed(Duration(milliseconds: 300));
- util.showLoading(context,dissmissable: false);
- var bUnits = await util.JsonDataPostRaw({}, "${Address??"https://asset.thamringroup.web.id"}/admin/getBisnisList",timeout: true,duration: 5);
- Navigator.pop(context);
- if(bUnits["STATUS"]==1){
- var selectedBisnis= bUnits["DATA"][0]["id"];
- var bisnisPicked = await showDialog(context: context,builder: (context)=>StatefulBuilder(
- builder: (context,setState)=>AlertDialog(
- title: Text('Pick Bisnis Unit'),
- content: DropdownButtonFormField(
- onChanged: (value)async{
- setState(() {
- selectedBisnis = value;
- });
- },
- value: selectedBisnis,
- items: new List<DropdownMenuItem<dynamic>>.from(bUnits['DATA'].map((value){
- String showText = value["name"];
- if(showText.length>30) showText = showText.substring(0,30);
- return DropdownMenuItem(
- child: Text(showText),
- value: value["id"],
- );
- })),
- ),
- actions: <Widget>[
- TextButton(
- onPressed: ()async{
- Navigator.pop(context,true);
- },
- child: Text('Next'),
- ),
- TextButton(
- onPressed: ()async{
- Navigator.pop(context,false);
- },
- child: Text('Cancel'),
- )
- ],
- ),
- ));
- if(bisnisPicked??false){
- util.showLoading(context,dissmissable: false);
- var result = await util.JsonDataPostRaw({"bUnit":selectedBisnis}, "${Address??"https://asset.thamringroup.web.id"}/admin/getrefDbList");
- Navigator.pop(context);
- if(result['STATUS']==1){
- bool isClear = await clearData(context);
- if(isClear??false){
- String selected = result['DATA'][0]["fullName"];
- bool res =await showDialog(context: context,builder: (context)=>StatefulBuilder(
- builder: (context,setState)=>AlertDialog(
- title: Text('Pick Database'),
- content: DropdownButtonFormField(
- onChanged: (value){
- setState(() {
- selected = value;
- });
- },
- value: selected,
- items: new List<DropdownMenuItem<dynamic>>.from(result['DATA'].map((value){
- String showText = value["name"];
- if(showText.length>20) showText = showText.substring(0,20);
- return DropdownMenuItem(
- child: Text(showText),
- value: value["fullName"],
- );
- })),
- ),
- actions: <Widget>[
- TextButton(
- onPressed: ()async{
- Navigator.pop(context,true);
- },
- child: Text('Get'),
- ),
- TextButton(
- onPressed: ()async{
- Navigator.pop(context,false);
- },
- child: Text('Cancel'),
- )
- ],
- ),
- ));
- if(res??false){
- // util.showLoading(context,dissmissable: false);
- await prefs.setString(keyClass.dbName,selected);
- file_Trans_Handler trans = new file_Trans_Handler();
- await trans.downloadFile("assets.db", "${Address??"https://asset.thamringroup.web.id"}/admin/downloadDb/$selectedBisnis/$selected");
- _dlulStream = trans.progress.listen((value)async {
- setState(() {
- progressDL = (value!=-1.0)?value:null;
- });
- if(value!=null&&value >= 1.0) {
- _dlulStream.cancel();
- progressDL = null;
- // setState(() {
- // lastDownload = DateTime.now().toIso8601String();
- // });
- // await prefs.setString(keyClass.lastDownload, lastDownload);
- // await DBHelper.database.insertUpdateValue(new valueTab(name: 'TGL_START',value: DateFormat('dd-MM-yyyy HH:mm:ss').format(DateTime.parse(lastDownload))));
- // await DBHelper.database.insertUpdateValue(new valueTab(name: 'TGL_STOCK_TAKING',value: DateFormat('dd-MM-yyyy').format(DateTime.parse(lastDownload))));
- // await DBHelper.database.closeDb();
- // var allUnits = await DBHelper.database.getAllAsset();
- // print('${allUnits.length} Units');
- if(prefs.getString(keyClass.backup_stock_id) == null) prefs.setString(keyClass.backup_stock_id,selected);
- util.showToast('ALERT','Data Downloaded');
- }
- if(value==-1.0){
- util.showToast('ALERT','Data Error ${trans.error}');
- }
- });
- // Navigator.pop(context);
- setState(() {
-
- });
- }
- }
- }
- else{
- await util.showToast("ERROR",result['ERROR']??"Database tidak ditemukan");
- }
- }
- }
- else{
- await util.showToast("ERROR",bUnits['DATA']??'not responding');
- }
- },
- child: Padding(
- padding: const EdgeInsets.only(left: 10,top:10,right: 5),
- child: Container(
- decoration: BoxDecoration(
- color: Colors.white,
- borderRadius: BorderRadius.circular(10)
- ),
- child: Column(
- mainAxisAlignment: MainAxisAlignment.center,
- children: <Widget>[
- Expanded(
- flex: 4,
- child: Container(alignment: Alignment.center,child: (progressDL==null)?Icon(Icons.add_to_home_screen,size: 100,color: Colors.blueGrey,):Stack(
- children: <Widget>[
- Container(width: 100,height: 100,child: CircularProgressIndicator(backgroundColor: Color(0xFFB4B4B4),valueColor:new AlwaysStoppedAnimation<Color>(Colors.blueGrey),value: progressDL,)),
- Container(width: 100,height: 100,alignment: Alignment.center,child: Text("${(progressDL*100).floor().toString()}%",style: TextStyle(color: Colors.blueGrey,fontWeight: FontWeight.bold,fontSize: 25),),)
- ],
- )),
- ),
- Flexible(
- flex: 2,
- child: Text('Get Data Master',style: TextStyle(color: Colors.blueGrey,fontSize: 18,fontWeight: FontWeight.bold),),
- ),
- ],
- ),
- ),
- ),
- ),
- Padding(
- padding: const EdgeInsets.only(left: 5,top:10,right: 10),
- child: Material(
- color: Colors.white,
- child: InkWell(
- onTap: ()async{
- await Future.delayed(Duration(milliseconds: 300));
- Directory documentsDirectory = await getApplicationDocumentsDirectory();
- String path = join(documentsDirectory.path, "assets.db");
- File db = File(path);
- if(db.existsSync()) Navigator.pushNamed(context, '/stocking');
- else{
- util.showToast('Alert', 'Please download data master first');
- }
- },
- child: Container(
- decoration: BoxDecoration(
- borderRadius: BorderRadius.circular(10)
- ),
- child: Column(
- mainAxisAlignment: MainAxisAlignment.center,
- children: <Widget>[
- Expanded(
- flex: 4,
- child: Container(alignment: Alignment.center,child: Icon(Icons.aspect_ratio,size: 100,color: Colors.blueGrey,)),
- ),
- Flexible(
- flex: 2,
- child: Text('Start Stocking',style: TextStyle(color: Colors.blueGrey,fontSize: 18,fontWeight: FontWeight.bold),),
- ),
- ],
- ),
- ),
- ),
- ),
- ),
- InkWell(
- onTap: ()async{
- final file = File(
- "${(await getApplicationDocumentsDirectory()).path}/assets.db");
- if(file.existsSync()){
- TextEditingController sendingUser = new TextEditingController();
- sendingUser.text = prefs.getString(keyClass.user)??'';
- bool isUserDefined = await showDialog(context: context,
- barrierDismissible: false,
- builder: (context)=>AlertDialog(
- title: Text('Sender'),
- content: TextField(
- inputFormatters: [FilteringTextInputFormatter.allow(RegExp("[a-zA-Z0-9 ]"))],
- controller: sendingUser,
- ),
- actions: [
- TextButton(
- child: Text('Send'),
- onPressed: ()async{
- if(sendingUser.text!='') Navigator.pop(context,true);
- else Navigator.pop(context,false);
- },
- )
- ],
- ));
- if(isUserDefined??false){
- prefs.setString(keyClass.user, sendingUser.text);
- util.showToast("ALERT",'Preparing Data');
- await DBHelper.database.setOpenState();
- await DBHelper.database.closeDb();
- file_Trans_Handler trans = new file_Trans_Handler();
- util.showToast("ALERT",'Sending Data');
- setState(() {
- progress = 0;
- });
- trans.uploadFile("assets.db", "${prefs.getString(keyClass.hostAddress)??"https://asset.thamringroup.web.id"}/admin/uploadSqliteDb",sendingUser.text,context);
- _dlulStream = trans.progress.listen((value) async {
- setState(() {
- progress = (value!=-1.0)?value:null;
- });
- if(value!=null&&value >= 1.0) {
- if(trans.error==''&&trans.isFinish){
- _dlulStream.cancel();
- progress = null;
- util.showToast("SUCCESS",(trans.success!='')?trans.success:'Data uploaded');
- }
- }
- if(value==-1.0&&trans.isFinish){
- _dlulStream.cancel();
- progress = null;
- util.showToast("ERROR",'Data upload error. ${trans.error}');
- }
- });
- }
- else util.showToast("ALERT",'Sending user not filled');
- }
- else{
- util.showToast("ALERT",'No database file found');
- }
- },
- child: Padding(
- padding: const EdgeInsets.only(left: 10,top:10,right: 5),
- child: Container(
- decoration: BoxDecoration(
- color: Colors.white,
- borderRadius: BorderRadius.circular(10)
- ),
- child: Column(
- mainAxisAlignment: MainAxisAlignment.center,
- children: <Widget>[
- Expanded(
- flex: 4,
- child: Container(alignment: Alignment.center,child: (progress==null)?Icon(Icons.send,size: 100,color: Colors.blueGrey,):Stack(
- children: <Widget>[
- Container(width: 100,height: 100,child: CircularProgressIndicator(backgroundColor: Color(0xFFB4B4B4),valueColor:new AlwaysStoppedAnimation<Color>(Colors.blueGrey),value: progress,)),
- Container(width: 100,height: 100,alignment: Alignment.center,child: Text("${(progress*100).floor().toString()}%",style: TextStyle(color: Colors.blueGrey,fontWeight: FontWeight.bold,fontSize: 25),),)
- ],
- )),
- ),
- Flexible(
- flex: 2,
- child: Text('Send Data',style: TextStyle(color: Colors.blueGrey,fontSize: 18,fontWeight: FontWeight.bold),),
- ),
- ],
- ),
- ),
- ),
- ),
- InkWell(
- onTap: ()async{
- Directory documentsDirectory = await getApplicationDocumentsDirectory();
- String path = join(documentsDirectory.path, "assets.db");
- File db = File(path);
- if(db.existsSync()) await clearData(context);
- else util.showToast('Alert', 'No database file found');
- },
- child: Padding(
- padding: const EdgeInsets.only(left: 5,top:10,right: 10),
- child: Container(
- decoration: BoxDecoration(
- color: Colors.white,
- borderRadius: BorderRadius.circular(10)
- ),
- child: Column(
- mainAxisAlignment: MainAxisAlignment.center,
- children: <Widget>[
- Expanded(
- flex: 4,
- child: Container(alignment: Alignment.center,child: Icon(Icons.delete,size: 100,color: Colors.blueGrey,)),
- ),
- Flexible(
- flex: 2,
- child: Text('Clear Data',style: TextStyle(color: Colors.blueGrey,fontSize: 18,fontWeight: FontWeight.bold),),
- ),
- ],
- ),
- ),
- ),
- ),
- ],
- ),
- ),
- ),
- Flexible(
- flex: 2,
- child: Container(
- padding: EdgeInsets.all(8),
- alignment: Alignment.bottomRight,
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.end,
- mainAxisAlignment: MainAxisAlignment.end,
- children: <Widget>[
- Text((prefs.getString(keyClass.dbName)!=null)?"Master Data : ${prefs.getString(keyClass.dbName)}":'',style: TextStyle(color: Colors.blueGrey),),
- Text('Connected to ${prefs.getString(keyClass.hostAddress)??'https://asset.thamringroup.web.id'}',style: TextStyle(color: Colors.blueGrey),),
- ],
- ),
- ),
- ),
- ],
- ),
- ),
- );
- }
- }
|