From ecb59d8b528326f0a855b8552dabd17fc3d77e2f Mon Sep 17 00:00:00 2001 From: Sewmina Dilshan Date: Fri, 27 Jan 2023 18:50:44 +0530 Subject: [PATCH] rollback to material + app usage init --- android/app/src/main/AndroidManifest.xml | 1 + lib/Data.dart | 232 ++-- lib/Settings/BehaviourSettings.dart | 140 +- lib/User.dart | 886 ++++++++---- lib/main.dart | 1582 ++++++++++++++-------- lib/splash.dart | 58 +- pubspec.lock | 7 + pubspec.yaml | 1 + 8 files changed, 1915 insertions(+), 992 deletions(-) diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml index 72702ff..cade80f 100644 --- a/android/app/src/main/AndroidManifest.xml +++ b/android/app/src/main/AndroidManifest.xml @@ -3,6 +3,7 @@ + json): taskType=json['taskType'], startTime=json['sTime'], endTime=json['eTime']; + Activity.fromJson(Map json) + : taskType = json['taskType'], + startTime = json['sTime'], + endTime = json['eTime']; - Map toJson()=>{ - 'taskType': taskType, - 'sTime':startTime, - 'eTime':endTime - }; + Map toJson() => + {'taskType': taskType, 'sTime': startTime, 'eTime': endTime}; static String colType = "type"; static String colStartTime = "s_time"; static String colEndTime = "e_time"; - static String colMetadata= "metadata"; + static String colMetadata = "metadata"; } -class InitialData{ - static List getTaskTypes(String username){ - List tasks =[ - TaskType(username + 'Sleep','Sleep', 'Relax'), - TaskType(username + 'Physics','Physics', 'Study'), - TaskType(username + 'History','History','Study'), - TaskType(username + 'Football','Football', 'Play'), - TaskType(username + 'At work','At work', 'Work'), - TaskType(username + 'Chores','Chores', 'Daily Activities'), - TaskType(username + 'Eat','Eat','Daily Activities'), - TaskType(username + 'Hang out','Hang out', 'Social') - ]; +class InitialData { + static List getTaskTypes(String username) { + List tasks = [ + TaskType(username + 'Sleep', 'Sleep', 'Relax'), + TaskType(username + 'Physics', 'Physics', 'Study'), + TaskType(username + 'History', 'History', 'Study'), + TaskType(username + 'Football', 'Football', 'Play'), + TaskType(username + 'At work', 'At work', 'Work'), + TaskType(username + 'Chores', 'Chores', 'Daily Activities'), + TaskType(username + 'Eat', 'Eat', 'Daily Activities'), + TaskType(username + 'Hang out', 'Hang out', 'Social') + ]; return tasks; } - static List getCategories(String username){ + static List getCategories(String username) { List cats = [ - Category(username+'Relax','Relax', '#555555', false), - Category(username+'Daily Activities','Daily Activities', '#009955',false), - Category(username+'Study','Study', '#00FF00', true), - Category(username+'Play','Play', '#FF0000', false), - Category(username+'Work','Work', '#00AAFF', true), - Category(username+'Social','Social', '#00AAAA', false) + Category(username + 'Relax', 'Relax', '#555555', false), + Category( + username + 'Daily Activities', 'Daily Activities', '#009955', false), + Category(username + 'Study', 'Study', '#00FF00', true), + Category(username + 'Play', 'Play', '#FF0000', false), + Category(username + 'Work', 'Work', '#00AAFF', true), + Category(username + 'Social', 'Social', '#00AAAA', false) ]; return cats; } } - -class Queries{ - Queries(this.link,this.data); +class Queries { + Queries(this.link, this.data); String link; String data; - static String colLink= "file"; + static String colLink = "file"; static String colData = "data"; } -class Project{ - Project(this.name, this.category, this.steps,this.eta, this.deadline,{this.cat}); +class Project { + Project(this.name, this.category, this.steps, this.eta, this.deadline, + {this.cat}); String name; - String getName()=> name.replaceAll(User.username, ""); + String getName() => name.replaceAll(User.username, ""); String category; Category? cat; List steps; @@ -122,23 +125,29 @@ class Project{ DateTime deadline; static String colName = "name"; - static String colCat="category_id"; + static String colCat = "category_id"; static String colSteps = "steps"; static String colDeadline = "deadline"; static String colEta = "eta"; } -class ProjectStep{ - ProjectStep(this.stepName,this.eta,this.progress); +class ProjectStep { + ProjectStep(this.stepName, this.eta, this.progress); - ProjectStep.fromJson(Map json): stepName=json['name'], eta=json['eta'], progress=json['progress'], finishedDate=(json['finishedDate']!=null) ? DateTime.parse(json['finishedDate']) : null; + ProjectStep.fromJson(Map json) + : stepName = json['name'], + eta = json['eta'], + progress = json['progress'], + finishedDate = (json['finishedDate'] != null) + ? DateTime.parse(json['finishedDate']) + : null; - Map toJson()=>{ - 'name': stepName, - 'eta':eta, - 'progress':progress, - if(finishedDate!=null) 'finishedDate':finishedDate.toString() - }; + Map toJson() => { + 'name': stepName, + 'eta': eta, + 'progress': progress, + if (finishedDate != null) 'finishedDate': finishedDate.toString() + }; String stepName; int eta; @@ -146,8 +155,7 @@ class ProjectStep{ DateTime? finishedDate; } -class Journal{ - +class Journal { Journal(this.id, this.day, {this.title, this.description}); String id; @@ -159,8 +167,9 @@ class Journal{ static String colDescription = 'Desc'; } -class Todo{ - Todo(this.id, this.category,this.metadata, this.dueDate, {this.notificationTime, this.task}); +class Todo { + Todo(this.id, this.category, this.metadata, this.dueDate, + {this.notificationTime, this.task}); String id; String category; @@ -175,101 +184,128 @@ class Todo{ static String colNotificationTime = 'notification_time'; } - -class Settings{ - static Future UUID() async{ +class Settings { + static Future UUID() async { final prefs = await SharedPreferences.getInstance(); - if(prefs.containsKey('uuid')){ + if (prefs.containsKey('uuid')) { return await Future.value(prefs.getString('uuid')); - }else{ - var uuid = Uuid(); - String _uuid = uuid.v4(); - // if(Platform.isAndroid){ - // - // } - await prefs.setString('uuid',_uuid); - return Future.value(_uuid); + } else { + var uuid = Uuid(); + String _uuid = uuid.v4(); + // if(Platform.isAndroid){ + // + // } + await prefs.setString('uuid', _uuid); + return Future.value(_uuid); } } - static Future setTheme(int value) async{ + static Future setTheme(int value) async { final prefs = await SharedPreferences.getInstance(); await prefs.setInt("theme", value); } - static String notification_key= "notification_interval"; + static String notification_key = "notification_interval"; static String adaptive_notification_key = "adaptive_notification"; static String untracked_unprod_key = "untracked_unproductive"; + static String auto_log_key = "auto_log"; - static Future getNotificationInterval() async{ + static Future getNotificationInterval() async { final prefs = await SharedPreferences.getInstance(); int _value = 1; - if(prefs.containsKey(notification_key)){ + if (prefs.containsKey(notification_key)) { _value = await prefs.getInt(notification_key) ?? 1; - }else{ - prefs.setInt(notification_key,_value); + } else { + prefs.setInt(notification_key, _value); } return _value; } - static Future setNotificationInterval(int value) async{ + static Future setNotificationInterval(int value) async { final prefs = await SharedPreferences.getInstance(); prefs.setInt(notification_key, value); } - static List notificationOptions = ['Off','1 hour', '2 hour', '3 hour', '4 hour', '5 hour', '6 hour']; + static List notificationOptions = [ + 'Off', + '1 hour', + '2 hour', + '3 hour', + '4 hour', + '5 hour', + '6 hour' + ]; static bool adaptiveNotificationAvailable() { - List dates = []; - if(User.activities.length < 10){ - return false; - }else{ - for (var element in User.activities) { - String thisDate = DateFormat("MM/dd").format(element.startTime); - if(!dates.contains(thisDate)){ - dates.add(thisDate); - } + List dates = []; + if (User.activities.length < 10) { + return false; + } else { + for (var element in User.activities) { + String thisDate = DateFormat("MM/dd").format(element.startTime); + if (!dates.contains(thisDate)) { + dates.add(thisDate); } } + } - return (dates.length > 2); + return (dates.length > 2); } - static Future getAdaptiveNotification() async{ + static Future getAdaptiveNotification() async { final prefs = await SharedPreferences.getInstance(); bool _value = true; - if(prefs.containsKey(notification_key)){ + if (prefs.containsKey(notification_key)) { _value = await prefs.getBool(adaptive_notification_key) ?? true; - }else{ - prefs.setBool(adaptive_notification_key,_value); + } else { + prefs.setBool(adaptive_notification_key, _value); } return _value; } - static Future setAdaptiveNotification(bool value) async{ + static Future setAdaptiveNotification(bool value) async { final prefs = await SharedPreferences.getInstance(); prefs.setBool(adaptive_notification_key, value); } - static Future getUntrackedUnproductive() async{ + static Future getUntrackedUnproductive() async { final prefs = await SharedPreferences.getInstance(); bool _value = true; - if(prefs.containsKey(untracked_unprod_key)){ + if (prefs.containsKey(untracked_unprod_key)) { _value = await prefs.getBool(untracked_unprod_key) ?? true; - }else{ - prefs.setBool(untracked_unprod_key,_value); + } else { + prefs.setBool(untracked_unprod_key, _value); } return _value; } - static Future setUntrackedUnproductive(bool value) async{ + static Future getAutoLog() async { + final prefs = await SharedPreferences.getInstance(); + + bool _value = true; + if (prefs.containsKey(auto_log_key)) { + _value = await prefs.getBool(auto_log_key) ?? true; + } else { + prefs.setBool(auto_log_key, _value); + } + + return _value; + } + + static Future setUntrackedUnproductive(bool value) async { final prefs = await SharedPreferences.getInstance(); prefs.setBool(untracked_unprod_key, value); } + + static Future setAutoLog(bool value) async { + final prefs = await SharedPreferences.getInstance(); + prefs.setBool(auto_log_key, value); + } } -final settings = Settings(); \ No newline at end of file + +final settings = Settings(); diff --git a/lib/Settings/BehaviourSettings.dart b/lib/Settings/BehaviourSettings.dart index ebade11..6e890e5 100644 --- a/lib/Settings/BehaviourSettings.dart +++ b/lib/Settings/BehaviourSettings.dart @@ -11,20 +11,20 @@ class BehaviourSettings extends StatefulWidget { } class _BehaviourSettingsState extends State { - bool untracked_unprod = true; + bool autoUsage = true; - @override void initState() { + @override + void initState() { // TODO: implement initState super.initState(); init(); } - void init() async{ - untracked_unprod=await Settings.getUntrackedUnproductive(); - setState(() { - - }); + void init() async { + untracked_unprod = await Settings.getUntrackedUnproductive(); + autoUsage = await Settings.getAutoLog(); + setState(() {}); } TextEditingController untrackedGapSettings = TextEditingController(); @@ -36,65 +36,77 @@ class _BehaviourSettingsState extends State { appBar: AppBar(title: Text('Behaviour Settings')), body: SafeArea( child: Container( - child:Column( - children: [ - ListTile( - title:Text("Count untracked time as unproductive"), - subtitle: Text("Not tracking = Not productive"), - trailing: Switch.adaptive(value: untracked_unprod, onChanged: (val){ - untracked_unprod=val; - setState(() { - Settings.setUntrackedUnproductive(val); - }); - setState(() { - - }); - }), - ), - //TODO - ListTile( - title:Text("Untracked Delay Threshold"), - subtitle: Text("Makes it easier to fill in the gaps"), - trailing: - Row( - mainAxisAlignment: MainAxisAlignment.end, - mainAxisSize: MainAxisSize.min, - children: [ - if(untrackedGapValue> 0)InkWell(onTap: (){ - untrackedGapSettings.text = (untrackedGapValue-1).toString(); - setState(() { - - }); - }, - child : Container(margin: EdgeInsets.all(10),child: Text('-')),), - SizedBox( - width: 25, - height: 30, - child: TextField( - textAlign: TextAlign.center, - controller: untrackedGapSettings, - keyboardType: TextInputType.number, - inputFormatters: [ - FilteringTextInputFormatter.digitsOnly - ],), + child: Column( + children: [ + ListTile( + title: Text("Count untracked time as unproductive"), + subtitle: Text("Not tracking = Not productive"), + trailing: Switch.adaptive( + value: untracked_unprod, + onChanged: (val) { + untracked_unprod = val; + setState(() { + Settings.setUntrackedUnproductive(val); + }); + setState(() {}); + }), + ), + //TODO + ListTile( + title: Text("Untracked Delay Threshold"), + subtitle: Text("Makes it easier to fill in the gaps"), + trailing: Row( + mainAxisAlignment: MainAxisAlignment.end, + mainAxisSize: MainAxisSize.min, + children: [ + if (untrackedGapValue > 0) + InkWell( + onTap: () { + untrackedGapSettings.text = + (untrackedGapValue - 1).toString(); + setState(() {}); + }, + child: Container( + margin: EdgeInsets.all(10), child: Text('-')), ), - - InkWell(onTap: (){ - untrackedGapSettings.text = (untrackedGapValue+1).toString(); - setState(() { - - }); + SizedBox( + width: 25, + height: 30, + child: TextField( + textAlign: TextAlign.center, + controller: untrackedGapSettings, + keyboardType: TextInputType.number, + inputFormatters: [ + FilteringTextInputFormatter.digitsOnly + ], + ), + ), + InkWell( + onTap: () { + untrackedGapSettings.text = + (untrackedGapValue + 1).toString(); + setState(() {}); }, - child: Container(margin:EdgeInsets.all(10),child: Text('+')), + child: Container( + margin: EdgeInsets.all(10), child: Text('+')), ) - ], - ), - ) + ], + ), + ), + ListTile( + title: Text("Automatically add tasks from Usage Data"), + subtitle: Text("Requires App Usage access"), + trailing: Switch.adaptive( + value: autoUsage, + onChanged: (val) { + autoUsage = val; + Settings.setAutoLog(val); - ], - ) - ), - ) - ); + setState(() {}); + }), + ), + ], + )), + )); } -} \ No newline at end of file +} diff --git a/lib/User.dart b/lib/User.dart index 202340d..ef2580e 100644 --- a/lib/User.dart +++ b/lib/User.dart @@ -1,6 +1,7 @@ import 'dart:async'; import 'dart:io'; +import 'package:app_usage/app_usage.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/foundation.dart' as K; import 'package:intl/intl.dart'; @@ -32,18 +33,22 @@ List activities = []; List projects = []; List journal = []; List todos = []; - +const API_ENDPOINT = 'http://vps.playpoolstudios.com'; bool offline = true; bool registered = false; StreamController refreshStream = StreamController.broadcast(); Future login(String _username, String password) async { final prefs = await SharedPreferences.getInstance(); - username = _username; var device_id = await Settings.UUID(); try { - loginResponse = (await http.post(Uri.parse('http://161.97.127.136/task_tracker/login.php'), - body: {"username": _username, "password": password, "device_id": device_id})); + loginResponse = (await http.post( + Uri.parse('http://vps.playpoolstudios.com/task_tracker/login.php'), + body: { + "username": _username, + "password": password, + "device_id": device_id + })); if (loginResponse.body.toLowerCase().contains("success")) { offline = false; @@ -64,18 +69,22 @@ Future login(String _username, String password) async { Future initUserData() async { if (cacheEnabled) { await initCacheDatabase(); - int catCount = Sqflite.firstIntValue(await cacheDb.rawQuery('SELECT COUNT(*) FROM Categories')) ?? 0; - int taskCount = Sqflite.firstIntValue(await cacheDb.rawQuery('SELECT COUNT(*) FROM TaskTypes')) ?? 0; - if(catCount > 0 && taskCount > 0){ + int catCount = Sqflite.firstIntValue( + await cacheDb.rawQuery('SELECT COUNT(*) FROM Categories')) ?? + 0; + int taskCount = Sqflite.firstIntValue( + await cacheDb.rawQuery('SELECT COUNT(*) FROM TaskTypes')) ?? + 0; + if (catCount > 0 && taskCount > 0) { await refreshUserData(forceOffline: true); refreshUserData(); - }else{ + } else { await refreshUserData(); } } - BuildBridgeToServer(); + InitUsageListener(); Debug.Log('Initializing UserData...'); if (cacheEnabled) { @@ -97,20 +106,25 @@ Future BuildBridgeToServer() async { while (true) { await UserOperations.executeQueries(); try { - http.Response response = - (await http.post(Uri.parse('http://161.97.127.136/task_tracker/bridge.php'), body: {"username": username})); + http.Response response = (await http.post( + Uri.parse(API_ENDPOINT + '/task_tracker/bridge.php'), + body: {"username": username})); - Debug.LogResponse("${response.body}",src: 'bridge'); + Debug.LogResponse("${response.body}", src: 'bridge'); List data = response.body.split(","); - Debug.LogResponse('Update :\nactivities_rev=${data[0]} tasks_rev=${data[1]} cats_rev=${data[2]} projects_rev=${data[3]}'); - bool changedOffline = offline==true; - offline=false; - if(changedOffline){refreshStream.add(false);} + Debug.LogResponse( + 'Update :\nactivities_rev=${data[0]} tasks_rev=${data[1]} cats_rev=${data[2]} projects_rev=${data[3]}'); + bool changedOffline = offline == true; + offline = false; + if (changedOffline) { + refreshStream.add(false); + } if (data[4].contains('')) { List ongoingData = data[4].split(""); if (!prefs.containsKey('current_activity')) { - StartActivityTimer(ongoingData[0], ongoingData[1], DateTime.parse(ongoingData[2])); + StartActivityTimer( + ongoingData[0], ongoingData[1], DateTime.parse(ongoingData[2])); } } else { if (prefs.containsKey('current_activity')) CancelOngoingActivity(); @@ -131,12 +145,33 @@ Future BuildBridgeToServer() async { } catch (e) { Debug.LogError("Error with bridge : $e"); bool changedOffline = offline == false; - offline=true; - if(changedOffline){refreshStream.add(false);} + offline = true; + if (changedOffline) { + refreshStream.add(false); + } } await Future.delayed(Duration(seconds: 5)); } } +const APP_USAGE_KEY_NAME = "app_usage_data"; +Future InitUsageListener() async { + final prefs = await SharedPreferences.getInstance(); + var delay = Duration(seconds: 10); + if(!prefs.containsKey(APP_USAGE_KEY_NAME)){ + prefs.setString(APP_USAGE_KEY_NAME, ""); + } + + List app_usage = []; + while (true) { + List appUsage = await AppUsage().getAppUsage(DateTime.now().subtract(delay), DateTime.now()); + + List prev_appUsage = jsonDecode(prefs.getString(APP_USAGE_KEY_NAME)!); + + + Debug.Log("Listening to usage"); + await Future.delayed(delay); + } +} bool m_refreshing = false; Future refreshUserData({bool forceOffline = false}) async { @@ -158,7 +193,7 @@ Future refreshUserData({bool forceOffline = false}) async { refreshStream.add(false); } else { - if(K.kIsWeb) { + if (K.kIsWeb) { Debug.LogTest('updating cats ${DateTime.now()}'); categories = await GetCategories(false); Debug.LogTest('updating projs ${DateTime.now()}'); @@ -172,23 +207,29 @@ Future refreshUserData({bool forceOffline = false}) async { Debug.LogTest('updating todos ${DateTime.now()}'); todos = await GetTodos(false); Debug.LogTest('done refreshing ${DateTime.now()}'); - }else { + } else { Debug.LogTest('Doing super update ${DateTime.now()}'); refreshStream.add(true); try { Debug.LogTest('Requesting all data @ ${DateTime.now()}'); - http.Response response = (await http.post(Uri.parse('http://161.97.127.136/task_tracker/grab_all_data.php'), - body: {"username": username, "device_id": await Settings.UUID()})); + http.Response response = (await http.post( + Uri.parse(API_ENDPOINT + '/task_tracker/grab_all_data.php'), + body: { + "username": username, + "device_id": await Settings.UUID() + })); List data = response.body.split(''); - Debug.LogTest('Got response for all data [${response.contentLength}bytes] @ ${DateTime.now()}'); - Debug.LogTest('super update items : ${data.length}\nfilling tables\nActivities : ${data[0].length}\nProjects: ${data[1].length}'); + Debug.LogTest( + 'Got response for all data [${response.contentLength}bytes] @ ${DateTime.now()}'); + Debug.LogTest( + 'super update items : ${data.length}\nfilling tables\nActivities : ${data[0].length}\nProjects: ${data[1].length}'); Debug.LogResponse(response.body); - Debug.LogResponse(data[0],src: 'Activity'); - Debug.LogResponse(data[1],src: 'Categories'); - Debug.LogResponse(data[2],src: 'Projects'); - Debug.LogResponse(data[3],src: 'Journals'); - Debug.LogResponse(data[4],src: 'TaskTypes'); - Debug.LogResponse(data[5],src: 'Todo'); + Debug.LogResponse(data[0], src: 'Activity'); + Debug.LogResponse(data[1], src: 'Categories'); + Debug.LogResponse(data[2], src: 'Projects'); + Debug.LogResponse(data[3], src: 'Journals'); + Debug.LogResponse(data[4], src: 'TaskTypes'); + Debug.LogResponse(data[5], src: 'Todo'); await fillActivityTable(data[0]); await fillCatsTable(data[1]); @@ -199,21 +240,42 @@ Future refreshUserData({bool forceOffline = false}) async { Debug.LogTest('Done filling @ ${DateTime.now()}'); - - categories = await GetCategories(true); - projects = await GetProjects(true); - taskTypes = await GetTaskTypes(true); - activities = await GetActivities(true); - journal = await GetJournals(true); - todos = await GetTodos(true); - - + categories = await GetCategories(true); + projects = await GetProjects(true); + taskTypes = await GetTaskTypes(true); + activities = await GetActivities(true); + journal = await GetJournals(true); + todos = await GetTodos(true); } catch (e) { Debug.LogError("Error while Super Update $e"); } refreshStream.add(false); Debug.LogTest('Done super update ${DateTime.now()}'); } + DateTime now = DateTime.now(); + List appUsage = + await AppUsage().getAppUsage(now.subtract(Duration(days: 2)), now); + + Debug.Log("Adding auto logs"); + appUsage.forEach((task) { + bool foundConflict = false; + for (int i = 1; i < activities.length; i++) { + Activity act = activities[activities.length - i]; + + if (isConflicting( + act.startTime, act.endTime, task.startDate, task.endDate)) { + //Got something here + continue; + } + + // UserOperations.addActivity("At work", task.startDate, task.endDate); + Debug.LogTest(task); + + if (act.startTime.isBefore(now.subtract(Duration(days: 2)))) { + break; + } + } + }); } m_refreshing = false; @@ -222,6 +284,30 @@ Future refreshUserData({bool forceOffline = false}) async { } } +bool isConflicting( + DateTime start1, DateTime end1, DateTime start2, DateTime end2) { + if (start1.isBefore(end2) && end1.isAfter(end2)) { + // 1 starts before 2 and continues after 2 is done + return true; + } + + if (end1.isBefore(end2) && end1.isAfter(start2)) { + // 1 ends within 2 + return true; + } + + if (start1.isAfter(start2) && start1.isBefore(end2)) { + //1 starts within 2 + return true; + } + + if (start1 == start2 || end1 == end2) { + return true; + } + + return false; +} + Future cacheDbExist() async { if (!K.kIsWeb && Platform.isAndroid || Platform.isIOS) { Directory directory = await getApplicationDocumentsDirectory(); @@ -252,10 +338,15 @@ Future initCacheDatabase() async { Directory directory = await getApplicationDocumentsDirectory(); Debug.LogResponse('database at ' + directory.path + '/cache.db'); if (!K.kIsWeb && Platform.isAndroid || Platform.isIOS) { - cacheDb = await openDatabase(directory.path + 'cache.db', version: 1, onCreate: onCacheDatabaseCreate, onUpgrade: onCacheDatabaseUpgrade); + cacheDb = await openDatabase(directory.path + 'cache.db', + version: 1, + onCreate: onCacheDatabaseCreate, + onUpgrade: onCacheDatabaseUpgrade); } else { - cacheDb = await SqlFF.databaseFactoryFfi - .openDatabase(directory.path + 'cache.db', options: OpenDatabaseOptions(version: 1, onCreate: onCacheDatabaseCreate)); + cacheDb = await SqlFF.databaseFactoryFfi.openDatabase( + directory.path + 'cache.db', + options: + OpenDatabaseOptions(version: 1, onCreate: onCacheDatabaseCreate)); } await UserOperations.executeQueries(); } @@ -283,13 +374,16 @@ void onCacheDatabaseCreate(Database db, int newVersion) async { 'CREATE TABLE Projects(id TEXT PRIMARY KEY, ${Project.colName} TEXT, ${Project.colCat} TEXT, ${Project.colSteps} TEXT, ${Project.colEta} INT, ${Project.colDeadline} DATETIME)'; await db.execute(ProjectsTableSQL); - String JournalTableSQL = 'CREATE TABLE Journal(id TEXT PRIMARY KEY, ${Journal.colTitle} TEXT, ${Journal.colDescription})'; + String JournalTableSQL = + 'CREATE TABLE Journal(id TEXT PRIMARY KEY, ${Journal.colTitle} TEXT, ${Journal.colDescription})'; await db.execute(JournalTableSQL); - String TodoTableSQL = 'CREATE TABLE Todos(id TEXT PRIMARY KEY, ${Todo.colCat} TEXT, ${Todo.colMetadata} TEXT, ${Todo.colDueDate} DATE, ${Todo.colNotificationTime} DATETIME)'; + String TodoTableSQL = + 'CREATE TABLE Todos(id TEXT PRIMARY KEY, ${Todo.colCat} TEXT, ${Todo.colMetadata} TEXT, ${Todo.colDueDate} DATE, ${Todo.colNotificationTime} DATETIME)'; await db.execute(TodoTableSQL); - String QueriesTableSQL = 'CREATE TABLE Queries(id INTEGER PRIMARY KEY AUTOINCREMENT, ${Queries.colLink} TEXT,${Queries.colData} TEXT)'; + String QueriesTableSQL = + 'CREATE TABLE Queries(id INTEGER PRIMARY KEY AUTOINCREMENT, ${Queries.colLink} TEXT,${Queries.colData} TEXT)'; await db.execute(QueriesTableSQL); final prefs = await SharedPreferences.getInstance(); @@ -308,11 +402,14 @@ Future addInitialDataToCache() async { //Insert Initial Entries for (Category element in InitialData.getCategories(username)) { - await UserOperations.addCategory(element.name, element.color, element.productive, bulk: true); + await UserOperations.addCategory( + element.name, element.color, element.productive, + bulk: true); } Dialogs.syncingMessage = "Just a minute"; for (TaskType element in InitialData.getTaskTypes(username)) { - await UserOperations.addTaskType(element.name, element.category, bulk: true); + await UserOperations.addTaskType(element.name, element.category, + bulk: true); // Map data = { // TaskType.colName: element.name, // TaskType.colCategory: element.category @@ -326,7 +423,8 @@ Future addInitialDataToCache() async { void onCacheDatabaseUpgrade(Database db, int oldVersion, int newVersion) async { //ValidateCacheDB(); - Debug.LogResponse('Upgrading CacheDB from ver.$oldVersion to ver.$newVersion'); + Debug.LogResponse( + 'Upgrading CacheDB from ver.$oldVersion to ver.$newVersion'); } Future> GetCategories(bool forceOffline) async { @@ -343,7 +441,7 @@ Future> GetCategories(bool forceOffline) async { bool catsUpdated = false; // try { - // http.Response update_response = (await http.post(Uri.parse('http://161.97.127.136/task_tracker/check_update.php'), body: {"username": username, "device_id": android_id})); + // http.Response update_response = (await http.post(Uri.parse(API_ENDPOINT+'/task_tracker/check_update.php'), body: {"username": username, "device_id": android_id})); // final data = update_response.body.split(','); // catsUpdated = data[0] == '1'; // } catch (e) { @@ -366,25 +464,32 @@ Future> GetCategories(bool forceOffline) async { String? catProductive = element[Category.colProductive].toString(); if (catName == null || catColor == null || catProductive == null) { Debug.LogError("Something is null!"); - Debug.LogError("name:{$catName}, color:{$catColor}, prod:{$Category.colProductive}"); + Debug.LogError( + "name:{$catName}, color:{$catColor}, prod:{$Category.colProductive}"); continue; } // Debug.Log("name:{$catName}, color:{$catColor}, prod:{$catProductive}"); - _categories.add(Category(username + catName, catName, catColor, ParseBool(catProductive))); + _categories.add(Category( + username + catName, catName, catColor, ParseBool(catProductive))); } categories = _categories; } else { Debug.Log("NC: Updating Categories as $username"); try { - http.Response response = (await http.post(Uri.parse('http://161.97.127.136/task_tracker/get_categories.php'), - body: {"username": username, "device_id": await Settings.UUID()})); + http.Response response = (await http.post( + Uri.parse(API_ENDPOINT + '/task_tracker/get_categories.php'), + body: { + "username": username, + "device_id": await Settings.UUID() + })); - Debug.LogResponse(response.body,src:'get_categories'); + Debug.LogResponse(response.body, src: 'get_categories'); List data = response.body.split(""); List _categories = []; for (var value in data) { Map cat = jsonDecode(value); - _categories.add(Category(cat['category_id'], cat['name'], cat['color'], ParseBool(cat['productive']))); + _categories.add(Category(cat['category_id'], cat['name'], cat['color'], + ParseBool(cat['productive']))); } categories = _categories; } catch (e) { @@ -397,8 +502,12 @@ Future> GetCategories(bool forceOffline) async { Future UpdateCategoriesFromServer() async { Debug.Log("Updating Categories as $username"); try { - http.Response response = (await http.post(Uri.parse('http://161.97.127.136/task_tracker/get_categories.php'), - body: {"username": username, "device_id": await Settings.UUID()})); + http.Response response = (await http.post( + Uri.parse(API_ENDPOINT + '/task_tracker/get_categories.php'), + body: { + "username": username, + "device_id": await Settings.UUID() + })); Debug.LogResponse(response.body); await fillCatsTable(response.body); @@ -413,8 +522,8 @@ Future fillCatsTable(String response) async { for (var value in data) { Map cat = jsonDecode(value); //Debug.Log(catData); - await cacheDb - .rawInsert("INSERT OR REPLACE INTO Categories (${Category.colCatId},${Category.colName},${Category.colProductive},${Category.colColor}) " + await cacheDb.rawInsert( + "INSERT OR REPLACE INTO Categories (${Category.colCatId},${Category.colName},${Category.colProductive},${Category.colColor}) " "VALUES ('${cat['category_id']}','${cat['name']}',${cat['productive']},'${cat['color']}') "); } } @@ -432,7 +541,7 @@ Future> GetTaskTypes(bool forceOffline) async { bool updated = false; // try { // //Validate device_id to check updates - // http.Response update_response = (await http.post(Uri.parse('http://161.97.127.136/task_tracker/check_update.php'), body: {"username": username, "device_id": android_id})); + // http.Response update_response = (await http.post(Uri.parse(API_ENDPOINT+'/task_tracker/check_update.php'), body: {"username": username, "device_id": android_id})); // final data = update_response.body.split(','); // updated = data[1] == '1'; // } catch (e) { @@ -469,15 +578,20 @@ Future> GetTaskTypes(bool forceOffline) async { } // Debug.Log("name:{$name}, cat:{$category}, prod:{$id}"); - _taskTypes.add(TaskType(id, name, category, cat: cat, relatedProject: relatedProject)); + _taskTypes.add(TaskType(id, name, category, + cat: cat, relatedProject: relatedProject)); } taskTypes = _taskTypes; } else { List _taskTypes = []; Debug.Log("NC: Updating TaskTypes as $username"); try { - http.Response response = (await http.post(Uri.parse('http://161.97.127.136/task_tracker/get_taskTypes.php'), - body: {"username": username, "device_id": await Settings.UUID()})); + http.Response response = (await http.post( + Uri.parse(API_ENDPOINT + '/task_tracker/get_taskTypes.php'), + body: { + "username": username, + "device_id": await Settings.UUID() + })); Debug.LogResponse("taskType retreive (try): ${response.body}"); List data = response.body.split(""); @@ -485,7 +599,9 @@ Future> GetTaskTypes(bool forceOffline) async { for (var value in data) { Map data = jsonDecode(value); Category? cat = await getCatFromId(data['category_id']); - _taskTypes.add(TaskType(data['task_id'], data['name'], data['category_id'], cat: cat, relatedProject: data['related_project'])); + _taskTypes.add(TaskType( + data['task_id'], data['name'], data['category_id'], + cat: cat, relatedProject: data['related_project'])); //Debug.Log(cat); } } catch (e) { @@ -501,8 +617,12 @@ Future UpdateTaskTypesFromServer() async { // await GetCategories(true); Debug.Log("Updating TaskTypes as $username"); try { - http.Response response = (await http.post(Uri.parse('http://161.97.127.136/task_tracker/get_taskTypes.php'), - body: {"username": username, "device_id": await Settings.UUID()})); + http.Response response = (await http.post( + Uri.parse(API_ENDPOINT + '/task_tracker/get_taskTypes.php'), + body: { + "username": username, + "device_id": await Settings.UUID() + })); Debug.LogResponse(response.body); await fillTaskTypes(response.body); @@ -517,18 +637,20 @@ Future fillTaskTypes(String response) async { for (var value in data) { Map cat = jsonDecode(value); //Debug.Log(cat); - await cacheDb - .rawInsert("INSERT OR REPLACE INTO TaskTypes (${TaskType.colId},${TaskType.colName},${TaskType.colCategory},${TaskType.colRelatedProject}) " + await cacheDb.rawInsert( + "INSERT OR REPLACE INTO TaskTypes (${TaskType.colId},${TaskType.colName},${TaskType.colCategory},${TaskType.colRelatedProject}) " "VALUES ('${cat['task_id']}','${cat['name']}','${cat['category_id']}', '${cat['related_project']}') "); Debug.LogResponse(await cacheDb.query("TaskTypes")); } } -void StartActivityTimer(String taskType, String metadata, DateTime startTime) async { +void StartActivityTimer( + String taskType, String metadata, DateTime startTime) async { final prefs = await SharedPreferences.getInstance(); - prefs.setString('current_activity', "$taskType$metadata${UserOperations.dFormat.format(startTime)}"); + prefs.setString('current_activity', + "$taskType$metadata${UserOperations.dFormat.format(startTime)}"); NotificationManager.RescheduleNotifications(); UserOperations.startOngoing(prefs.getString('current_activity')!); @@ -549,7 +671,8 @@ void StopActivityTimer() async { final prefs = await SharedPreferences.getInstance(); try { List data = prefs.getString('current_activity')!.split(""); - UserOperations.addActivity(data[0], DateTime.parse(data[2]), DateTime.now(), metadata: data[1]); + UserOperations.addActivity(data[0], DateTime.parse(data[2]), DateTime.now(), + metadata: data[1]); } catch (e) {} prefs.remove('current_activity'); UserOperations.stopOngoing(); @@ -574,7 +697,7 @@ Future> GetActivities(bool forceOffline) async { bool updated = false; // try { // //Validate device_id to check updates - // http.Response update_response = (await http.post(Uri.parse('http://161.97.127.136/task_tracker/check_update.php'), body: {"username": username, "device_id": android_id})); + // http.Response update_response = (await http.post(Uri.parse(API_ENDPOINT+'/task_tracker/check_update.php'), body: {"username": username, "device_id": android_id})); // final data = update_response.body.split(','); // updated = data[2] == '1'; // } catch (e) { @@ -589,7 +712,8 @@ Future> GetActivities(bool forceOffline) async { } } - List cats = await cacheDb.rawQuery('SELECT * FROM Activities ORDER BY ${Activity.colStartTime} DESC'); + List cats = await cacheDb.rawQuery( + 'SELECT * FROM Activities ORDER BY ${Activity.colStartTime} DESC'); Debug.Log(cats.length); for (Map element in cats) { int? id = element['id']; @@ -598,9 +722,14 @@ Future> GetActivities(bool forceOffline) async { String? endTime = element[Activity.colEndTime].toString(); String? metadata = element[Activity.colMetadata].toString(); TaskType? taskType = await getTaskFromId(type); - if (type == null || startTime == null || endTime == null || taskType == null) { - Debug.LogError("Something is null!\ntype:${type == null}, startTime:${startTime == null}, eTime:${endTime == null}, taskType${taskType == null}"); - Debug.LogError("TaskType:{$type}, Start Time:{$startTime}, endTime:{$endTime}, metadata:${metadata}"); + if (type == null || + startTime == null || + endTime == null || + taskType == null) { + Debug.LogError( + "Something is null!\ntype:${type == null}, startTime:${startTime == null}, eTime:${endTime == null}, taskType${taskType == null}"); + Debug.LogError( + "TaskType:{$type}, Start Time:{$startTime}, endTime:{$endTime}, metadata:${metadata}"); continue; } //Debug.Log("TaskType:{$type}, Start Time:{$startTime}, endTime:{$endTime}, metadata:${metadata}"); @@ -608,26 +737,35 @@ Future> GetActivities(bool forceOffline) async { DateTime eTime = DateTime.parse(endTime); if (eTime.day != sTime.day) { - DateTime midnight = DateTime(eTime.year, eTime.month, eTime.day, 0, 0, 0); + DateTime midnight = + DateTime(eTime.year, eTime.month, eTime.day, 0, 0, 0); int firstHalf = eTime.difference(midnight).inMinutes; int secondHalf = midnight.difference(sTime).inMinutes; // Debug.Log("${taskType.name} first half : $firstHalf -> second half: $secondHalf"); if (firstHalf > 1) { - _activities.add(Activity(taskType, midnight, eTime, metadata: metadata, tStartTime: sTime)); + _activities.add(Activity(taskType, midnight, eTime, + metadata: metadata, tStartTime: sTime)); } if (secondHalf > 1) { - _activities.add(Activity(taskType, sTime, midnight, metadata: metadata, tEndTime: eTime)); + _activities.add(Activity(taskType, sTime, midnight, + metadata: metadata, tEndTime: eTime)); } } else { - _activities.add(Activity(taskType, DateTime.parse(startTime), DateTime.parse(endTime), metadata: metadata)); + _activities.add(Activity( + taskType, DateTime.parse(startTime), DateTime.parse(endTime), + metadata: metadata)); } } activities = _activities; } else { Debug.Log("NC :Updating Activities as $username"); try { - http.Response response = (await http.post(Uri.parse('http://161.97.127.136/task_tracker/get_activities.php'), - body: {"username": username, "device_id": await Settings.UUID()})); + http.Response response = (await http.post( + Uri.parse(API_ENDPOINT + '/task_tracker/get_activities.php'), + body: { + "username": username, + "device_id": await Settings.UUID() + })); Debug.LogResponse("Activity response: ${response.body}"); List _activities = []; @@ -651,18 +789,23 @@ Future> GetActivities(bool forceOffline) async { DateTime eTime = DateTime.parse(endTime); if (eTime.day != sTime.day) { - DateTime midnight = DateTime(eTime.year, eTime.month, eTime.day, 0, 0, 0); + DateTime midnight = + DateTime(eTime.year, eTime.month, eTime.day, 0, 0, 0); int firstHalf = eTime.difference(midnight).inMinutes; int secondHalf = midnight.difference(sTime).inMinutes; // Debug.Log("${taskType.name} first half : $firstHalf -> second half: $secondHalf"); if (firstHalf > 1) { - _activities.add(Activity(taskType, midnight, eTime, metadata: metadata, tStartTime: sTime)); + _activities.add(Activity(taskType, midnight, eTime, + metadata: metadata, tStartTime: sTime)); } if (secondHalf > 1) { - _activities.add(Activity(taskType, sTime, midnight, metadata: metadata, tEndTime: eTime)); + _activities.add(Activity(taskType, sTime, midnight, + metadata: metadata, tEndTime: eTime)); } } else { - _activities.add(Activity(taskType, DateTime.parse(startTime), DateTime.parse(endTime), metadata: metadata)); + _activities.add(Activity( + taskType, DateTime.parse(startTime), DateTime.parse(endTime), + metadata: metadata)); } } @@ -681,19 +824,23 @@ Future UpdateActivitiesFromServer() async { Debug.Log("Updating Activities as $username"); try { - http.Response response = (await http.post(Uri.parse('http://161.97.127.136/task_tracker/get_activities.php'), - body: {"username": username, "device_id": await Settings.UUID()})); + http.Response response = (await http.post( + Uri.parse(API_ENDPOINT + '/task_tracker/get_activities.php'), + body: { + "username": username, + "device_id": await Settings.UUID() + })); - await fillActivityTable(response.body); + await fillActivityTable(response.body); - // Debug.Log("Activity response: ${response.body}"); + // Debug.Log("Activity response: ${response.body}"); } catch (e) { Debug.Log("Error while acts $e"); } } -Future fillActivityTable(String response) async{ +Future fillActivityTable(String response) async { if (response.contains("{")) { await cacheDb.rawDelete("DELETE FROM Activities"); Debug.Log('Truncate Activity Table before'); @@ -704,7 +851,7 @@ Future fillActivityTable(String response) async{ //Debug.Log(cat); await cacheDb.rawInsert( "INSERT OR REPLACE INTO Activities (${Activity.colType}, ${Activity.colStartTime}, ${Activity.colEndTime}, ${Activity.colMetadata}) " - "VALUES ('${cat['task_id']}', '${cat['sTime']}','${cat['eTime']}', '${cat['metadata'].toString().replaceAll("'", "''")}') "); + "VALUES ('${cat['task_id']}', '${cat['sTime']}','${cat['eTime']}', '${cat['metadata'].toString().replaceAll("'", "''")}') "); } } else { Debug.Log("No activities for now"); @@ -740,9 +887,15 @@ Future> GetProjects(bool forceOffline) async { String? deadline = element[Project.colDeadline]; int? eta = element[Project.colEta]; - if (name == null || category == null || stepsJson == null || deadline == null || eta == null) { - Debug.LogError("Something is null!\nname:${name == null}, cat:${category == null}, steps:${stepsJson == null}, deadline${deadline == null}"); - Debug.LogError("TaskType:{$name}, Start Time:{$category}, endTime:{$stepsJson}, metadata:${deadline}"); + if (name == null || + category == null || + stepsJson == null || + deadline == null || + eta == null) { + Debug.LogError( + "Something is null!\nname:${name == null}, cat:${category == null}, steps:${stepsJson == null}, deadline${deadline == null}"); + Debug.LogError( + "TaskType:{$name}, Start Time:{$category}, endTime:{$stepsJson}, metadata:${deadline}"); continue; } Category? cat = await getCatFromId(category); @@ -764,16 +917,22 @@ Future> GetProjects(bool forceOffline) async { eta = (m_eta > 0) ? m_eta : eta; // Debug.Log(steps); - _projects.add(Project(name.replaceAll(username, ""), category, steps, eta, DateTime.parse(deadline), cat: cat)); + _projects.add(Project(name.replaceAll(username, ""), category, steps, eta, + DateTime.parse(deadline), + cat: cat)); } projects = _projects; } else { Debug.Log("NC :Updating Projects as $username"); try { - http.Response response = (await http.post(Uri.parse('http://161.97.127.136/task_tracker/get_projects.php'), - body: {"username": username, "device_id": await Settings.UUID()})); + http.Response response = (await http.post( + Uri.parse(API_ENDPOINT + '/task_tracker/get_projects.php'), + body: { + "username": username, + "device_id": await Settings.UUID() + })); - // Debug.Log("Activity response: ${response.body}"); + // Debug.Log("Activity response: ${response.body}"); List _projects = []; if (response.body.contains("{")) { List data = response.body.split(""); @@ -808,8 +967,12 @@ Future UpdateProjectsFromServer() async { Debug.Log("Updating Projects as $username"); try { - http.Response response = (await http.post(Uri.parse('http://161.97.127.136/task_tracker/get_projects.php'), - body: {"username": username, "device_id": await Settings.UUID()})); + http.Response response = (await http.post( + Uri.parse(API_ENDPOINT + '/task_tracker/get_projects.php'), + body: { + "username": username, + "device_id": await Settings.UUID() + })); await fillProjectsTable(response.body); } catch (e) { @@ -830,7 +993,7 @@ Future fillProjectsTable(String response) async { Debug.LogResponse(cat, src: 'project data'); await cacheDb.rawInsert( "INSERT OR REPLACE INTO Projects (${Project.colName}, ${Project.colCat}, ${Project.colSteps}, ${Project.colDeadline}, ${Project.colEta}) " - "VALUES ('${cat['name']}', '${cat['category']}', '${cat['steps']}', '${cat['deadline']}', ${cat['eta']})"); + "VALUES ('${cat['name']}', '${cat['category']}', '${cat['steps']}', '${cat['deadline']}', ${cat['eta']})"); } } else { Debug.Log("No projects for now"); @@ -850,7 +1013,7 @@ Future> GetJournals(bool forceOffline) async { bool catsUpdated = false; // try { - // http.Response update_response = (await http.post(Uri.parse('http://161.97.127.136/task_tracker/check_update.php'), body: {"username": username, "device_id": android_id})); + // http.Response update_response = (await http.post(Uri.parse(API_ENDPOINT+'/task_tracker/check_update.php'), body: {"username": username, "device_id": android_id})); // final data = update_response.body.split(','); // catsUpdated = data[0] == '1'; // } catch (e) { @@ -882,8 +1045,12 @@ Future> GetJournals(bool forceOffline) async { } else { Debug.Log("NC: Updating Categories as $username"); try { - http.Response response = (await http.post(Uri.parse('http://161.97.127.136/task_tracker/get_journals.php'), - body: {"username": username, "device_id": await Settings.UUID()})); + http.Response response = (await http.post( + Uri.parse(API_ENDPOINT + '/task_tracker/get_journals.php'), + body: { + "username": username, + "device_id": await Settings.UUID() + })); Debug.LogResponse(response.body); List data = response.body.split(""); @@ -891,8 +1058,9 @@ Future> GetJournals(bool forceOffline) async { for (var value in data) { Map cat = jsonDecode(value); //Debug.Log(catData); - _categories - .add(Journal(cat['id'], DateTime.parse(cat['id'].toString().replaceAll(username, '')), title: cat['title'], description: cat['text'])); + _categories.add(Journal(cat['id'], + DateTime.parse(cat['id'].toString().replaceAll(username, '')), + title: cat['title'], description: cat['text'])); } journal = _categories; } catch (e) { @@ -906,8 +1074,12 @@ Future> GetJournals(bool forceOffline) async { Future UpdateJournalsFromServer() async { Debug.Log("Updating Journal as $username"); try { - http.Response response = (await http.post(Uri.parse('http://161.97.127.136/task_tracker/get_journals.php'), - body: {"username": username, "device_id": await Settings.UUID()})); + http.Response response = (await http.post( + Uri.parse(API_ENDPOINT + '/task_tracker/get_journals.php'), + body: { + "username": username, + "device_id": await Settings.UUID() + })); await fillJournalsTable(response.body); } catch (e) { @@ -916,18 +1088,20 @@ Future UpdateJournalsFromServer() async { } Future fillJournalsTable(String response) async { - Debug.LogResponse(response,src:'Journal'); - if(response.isEmpty){ + Debug.LogResponse(response, src: 'Journal'); + if (response.isEmpty) { Debug.Log('Empty Journal'); - }else{ - List data = response.split(""); - await cacheDb.delete("Journal"); - for (var value in data) { - Map cat = jsonDecode(value); - //Debug.Log(catData); - await cacheDb.rawInsert("INSERT OR REPLACE INTO Journal (id, ${Journal.colTitle},${Journal.colDescription}) " - "VALUES ('${cat['id']}','${cat['title'].toString().replaceAll("'", "''")}','${cat['description'].toString().replaceAll("'", "''")}') "); - }} + } else { + List data = response.split(""); + await cacheDb.delete("Journal"); + for (var value in data) { + Map cat = jsonDecode(value); + //Debug.Log(catData); + await cacheDb.rawInsert( + "INSERT OR REPLACE INTO Journal (id, ${Journal.colTitle},${Journal.colDescription}) " + "VALUES ('${cat['id']}','${cat['title'].toString().replaceAll("'", "''")}','${cat['description'].toString().replaceAll("'", "''")}') "); + } + } } Future> GetTodos(bool forceOffline) async { @@ -943,7 +1117,7 @@ Future> GetTodos(bool forceOffline) async { bool catsUpdated = false; // try { - // http.Response update_response = (await http.post(Uri.parse('http://161.97.127.136/task_tracker/check_update.php'), body: {"username": username, "device_id": android_id})); + // http.Response update_response = (await http.post(Uri.parse(API_ENDPOINT+'/task_tracker/check_update.php'), body: {"username": username, "device_id": android_id})); // final data = update_response.body.split(','); // catsUpdated = data[0] == '1'; // } catch (e) { @@ -965,24 +1139,41 @@ Future> GetTodos(bool forceOffline) async { String? due_date = element[Todo.colDueDate]; String? notification_time = element[Todo.colNotificationTime]; - if (id == null || task_id == null || metadata == null || due_date == null) { + if (id == null || + task_id == null || + metadata == null || + due_date == null) { Debug.LogError("Something is null!"); - Debug.LogError("id:{$id}, task:{$task_id}, metadata:${metadata}, due_date: ${due_date}"); + Debug.LogError( + "id:{$id}, task:{$task_id}, metadata:${metadata}, due_date: ${due_date}"); continue; } TaskType? taskType = await getTaskFromId(task_id); - if(taskType == null){Debug.LogError('got null taask for this todo!');Debug.LogResponse("id:{$id}, task:{$task_id}, metadata:${metadata}, due_date: ${due_date}");} + if (taskType == null) { + Debug.LogError('got null taask for this todo!'); + Debug.LogResponse( + "id:{$id}, task:{$task_id}, metadata:${metadata}, due_date: ${due_date}"); + } DateTime dueDate = DateTime.parse(due_date); - DateTime? notificationTime = (notification_time == null) ? null : ((notification_time.isEmpty || notification_time =='null') ? null :DateTime.parse(notification_time)); + DateTime? notificationTime = (notification_time == null) + ? null + : ((notification_time.isEmpty || notification_time == 'null') + ? null + : DateTime.parse(notification_time)); // Debug.Log("name:{$catName}, color:{$catColor}, prod:{$catProductive}"); - _todos.add(Todo(id,task_id,metadata,dueDate, notificationTime: notificationTime, task:taskType)); + _todos.add(Todo(id, task_id, metadata, dueDate, + notificationTime: notificationTime, task: taskType)); } todos = _todos; } else { Debug.Log("NC: Updating todos as $username"); try { - http.Response response = (await http.post(Uri.parse('http://161.97.127.136/task_tracker/get_todos.php'), - body: {"username": username, "device_id": await Settings.UUID()})); + http.Response response = (await http.post( + Uri.parse(API_ENDPOINT + '/task_tracker/get_todos.php'), + body: { + "username": username, + "device_id": await Settings.UUID() + })); Debug.LogResponse(response.body); List data = response.body.split(""); @@ -990,23 +1181,28 @@ Future> GetTodos(bool forceOffline) async { for (var value in data) { Map cat = jsonDecode(value); //Debug.Log(catData); - _categories - .add(Journal(cat['id'], DateTime.parse(cat['id'].toString().replaceAll(username, '')), title: cat['title'], description: cat['text'])); + _categories.add(Journal(cat['id'], + DateTime.parse(cat['id'].toString().replaceAll(username, '')), + title: cat['title'], description: cat['text'])); } journal = _categories; } catch (e) { Debug.LogError("Error while cats NC: $e"); } } - // journal.sort((a, b) => b.day.compareTo(a.day)); + // journal.sort((a, b) => b.day.compareTo(a.day)); return todos; } Future UpdateTodosFromServer() async { Debug.Log("Updating Todos as $username"); try { - http.Response response = (await http.post(Uri.parse('http://161.97.127.136/task_tracker/get_todos.php'), - body: {"username": username, "device_id": await Settings.UUID()})); + http.Response response = (await http.post( + Uri.parse(API_ENDPOINT + '/task_tracker/get_todos.php'), + body: { + "username": username, + "device_id": await Settings.UUID() + })); Debug.LogResponse(response.body); @@ -1017,24 +1213,21 @@ Future UpdateTodosFromServer() async { } Future fillTodosTable(String response) async { - if (response.contains("{")) { List data = response.split(""); await cacheDb.delete("Todos"); for (var value in data) { Map cat = jsonDecode(value); //Debug.Log(catData); - await cacheDb.rawInsert("INSERT OR REPLACE INTO Todos (id, ${Todo.colCat},${Todo.colMetadata},${Todo.colDueDate},${Todo.colNotificationTime}) " - "VALUES ('${cat['id'].toString().replaceAll("'", "''")}', '${cat['task_id']}', '${cat['metadata'].toString().replaceAll( - "'", "''")}', '${cat['due_date']}', '${cat['notification_time']}') "); + await cacheDb.rawInsert( + "INSERT OR REPLACE INTO Todos (id, ${Todo.colCat},${Todo.colMetadata},${Todo.colDueDate},${Todo.colNotificationTime}) " + "VALUES ('${cat['id'].toString().replaceAll("'", "''")}', '${cat['task_id']}', '${cat['metadata'].toString().replaceAll("'", "''")}', '${cat['due_date']}', '${cat['notification_time']}') "); } - }else{ + } else { Debug.Log('Empty Todos'); } } - - Future getTaskFromId(String taskId) async { // await GetTaskTypes(false); TaskType? cat = null; @@ -1045,7 +1238,8 @@ Future getTaskFromId(String taskId) async { } } if (cat == null) { - Debug.LogError('Got null tasktype for ${taskId} after searching on ${taskTypes.length}'); + Debug.LogError( + 'Got null tasktype for ${taskId} after searching on ${taskTypes.length}'); } return cat; @@ -1072,17 +1266,19 @@ Future getProjectFromId(String projectId) async { } } if (project == null) { - Debug.LogError('Got null project for ${projectId} after searching on ${projects.length}'); + Debug.LogError( + 'Got null project for ${projectId} after searching on ${projects.length}'); } return project; } -bool journalExists(DateTime date){ +bool journalExists(DateTime date) { int journalId = -1; - for (int i =0; i < journal.length; i++) { - // Debug.Log('${journal[i].day } : $date'); - if(DateFormat('yyyy-MM-dd').format(journal[i].day) == DateFormat('yyyy-MM-dd').format(date)){ + for (int i = 0; i < journal.length; i++) { + // Debug.Log('${journal[i].day } : $date'); + if (DateFormat('yyyy-MM-dd').format(journal[i].day) == + DateFormat('yyyy-MM-dd').format(date)) { journalId = i; break; } @@ -1113,7 +1309,8 @@ bool ParseBool(obj) { class UserOperations { static DateFormat dFormat = DateFormat("yyyy-MM-dd HH:mm:ss"); - static Future addCategory(String name, String color, bool productive, {bool bulk = false}) async { + static Future addCategory(String name, String color, bool productive, + {bool bulk = false}) async { Map queryBody = { 'username': username, 'device_id': await Settings.UUID(), @@ -1123,9 +1320,13 @@ class UserOperations { }; if (cacheEnabled) { //Add Query - Map query = {Queries.colLink: 'add_category', Queries.colData: jsonEncode(queryBody)}; + Map query = { + Queries.colLink: 'add_category', + Queries.colData: jsonEncode(queryBody) + }; - Debug.LogResponse("adding new query ${query[Queries.colLink]} : ${jsonEncode(queryBody)}"); + Debug.LogResponse( + "adding new query ${query[Queries.colLink]} : ${jsonEncode(queryBody)}"); await cacheDb.insert('Queries', query); @@ -1140,7 +1341,9 @@ class UserOperations { await refreshUserData(forceOffline: true); } else { try { - http.Response queryResponse = (await http.post(Uri.parse('http://161.97.127.136/task_tracker/add_category.php'), body: queryBody)); + http.Response queryResponse = (await http.post( + Uri.parse(API_ENDPOINT + '/task_tracker/add_category.php'), + body: queryBody)); Debug.LogResponse("Query executed : Results{${queryResponse.body}"); if (queryResponse.body.toLowerCase().contains("success")) { //Success @@ -1156,21 +1359,27 @@ class UserOperations { } } - static Future addTaskType(String name, String category, {bool bulk = false, String? relatedProject = null}) async { + static Future addTaskType(String name, String category, + {bool bulk = false, String? relatedProject = null}) async { Map queryBody = { 'id': username + name, 'username': username, 'device_id': await Settings.UUID(), 'name': name, 'category': username + category, - 'related_project': (relatedProject == null) ? '' : (username + relatedProject) + 'related_project': + (relatedProject == null) ? '' : (username + relatedProject) }; if (cacheEnabled) { //Add Query - Map query = {Queries.colLink: 'add_taskType', Queries.colData: jsonEncode(queryBody)}; + Map query = { + Queries.colLink: 'add_taskType', + Queries.colData: jsonEncode(queryBody) + }; - Debug.LogResponse("adding new query ${query[Queries.colLink]} : ${jsonEncode(queryBody)}"); + Debug.LogResponse( + "adding new query ${query[Queries.colLink]} : ${jsonEncode(queryBody)}"); await cacheDb.insert('Queries', query); @@ -1181,13 +1390,16 @@ class UserOperations { Category.colCatId: username + category, }; if (relatedProject != null || relatedProject == 'None') { - data.putIfAbsent(TaskType.colRelatedProject, () => relatedProject.toString()); + data.putIfAbsent( + TaskType.colRelatedProject, () => relatedProject.toString()); } await cacheDb.insert('TaskTypes', data); await refreshUserData(forceOffline: true); } else { try { - http.Response queryResponse = (await http.post(Uri.parse('http://161.97.127.136/task_tracker/add_taskType.php'), body: queryBody)); + http.Response queryResponse = (await http.post( + Uri.parse(API_ENDPOINT + '/task_tracker/add_taskType.php'), + body: queryBody)); Debug.LogResponse("Query executed : Results{${queryResponse.body}"); if (queryResponse.body.toLowerCase().contains("success")) { //Success @@ -1202,20 +1414,26 @@ class UserOperations { } } - static Future editTaskType(String oldName, String name, String category, {bool bulk = false, String? relatedProject = null}) async { + static Future editTaskType(String oldName, String name, String category, + {bool bulk = false, String? relatedProject = null}) async { Map queryBody = { 'id': username + oldName, 'username': username, 'name': name, 'category': username + category, - 'related_project': (relatedProject == null) ? '' : (username + relatedProject) + 'related_project': + (relatedProject == null) ? '' : (username + relatedProject) }; if (cacheEnabled) { //Add Query - Map query = {Queries.colLink: 'edit_taskType', Queries.colData: jsonEncode(queryBody)}; + Map query = { + Queries.colLink: 'edit_taskType', + Queries.colData: jsonEncode(queryBody) + }; - Debug.LogResponse("adding new query ${query[Queries.colLink]} : ${jsonEncode(queryBody)}"); + Debug.LogResponse( + "adding new query ${query[Queries.colLink]} : ${jsonEncode(queryBody)}"); await cacheDb.insert('Queries', query); @@ -1225,7 +1443,9 @@ class UserOperations { await refreshUserData(forceOffline: true); } else { try { - http.Response queryResponse = (await http.post(Uri.parse('http://161.97.127.136/task_tracker/add_taskType.php'), body: queryBody)); + http.Response queryResponse = (await http.post( + Uri.parse(API_ENDPOINT + '/task_tracker/add_taskType.php'), + body: queryBody)); Debug.LogResponse("Query executed : Results{${queryResponse.body}"); if (queryResponse.body.toLowerCase().contains("success")) { //Success @@ -1241,7 +1461,9 @@ class UserOperations { } static Future addActivity(String type, DateTime sTime, DateTime eTime, - {String metadata = 'null', bool bulk = false, Function(int)? onOverlap}) async { + {String metadata = 'null', + bool bulk = false, + Function(int)? onOverlap}) async { Map queryBody = { 'username': username, 'device_id': await Settings.UUID(), @@ -1250,7 +1472,10 @@ class UserOperations { 'eTime': dFormat.format(eTime), 'metadata': metadata }; - Map query = {Queries.colLink: 'add_activity', Queries.colData: jsonEncode(queryBody)}; + Map query = { + Queries.colLink: 'add_activity', + Queries.colData: jsonEncode(queryBody) + }; if (cacheEnabled) { //Check for timeoverlapse activities = await GetActivities(true); @@ -1266,7 +1491,8 @@ class UserOperations { if (metadata.length > 0) {} //Add Query - Debug.LogResponse("adding new query ${query[Queries.colLink]} : ${jsonEncode(queryBody)}"); + Debug.LogResponse( + "adding new query ${query[Queries.colLink]} : ${jsonEncode(queryBody)}"); await cacheDb.insert('Queries', query); @@ -1281,7 +1507,9 @@ class UserOperations { await refreshUserData(forceOffline: true); } else { try { - http.Response queryResponse = (await http.post(Uri.parse('http://161.97.127.136/task_tracker/add_activity.php'), body: queryBody)); + http.Response queryResponse = (await http.post( + Uri.parse(API_ENDPOINT + '/task_tracker/add_activity.php'), + body: queryBody)); Debug.LogResponse("Query executed : Results{${queryResponse.body}"); if (queryResponse.body.toLowerCase().contains("success")) { //Success @@ -1296,8 +1524,11 @@ class UserOperations { } } - static Future editActivity(DateTime init_sTime, DateTime init_eTime, String type, DateTime sTime, DateTime eTime, - {String metadata = 'null', bool bulk = false, Function(int)? onOverlap}) async { + static Future editActivity(DateTime init_sTime, DateTime init_eTime, + String type, DateTime sTime, DateTime eTime, + {String metadata = 'null', + bool bulk = false, + Function(int)? onOverlap}) async { Map queryBody = { 'username': username, 'device_id': await Settings.UUID(), @@ -1308,7 +1539,10 @@ class UserOperations { 'eTime': dFormat.format(eTime), 'metadata': metadata }; - Map query = {Queries.colLink: 'edit_activity', Queries.colData: jsonEncode(queryBody)}; + Map query = { + Queries.colLink: 'edit_activity', + Queries.colData: jsonEncode(queryBody) + }; if (cacheEnabled) { //Check for timeoverlapse activities = await GetActivities(true); @@ -1324,7 +1558,8 @@ class UserOperations { if (metadata.length > 0) {} //Add Query - Debug.LogResponse("adding new query ${query[Queries.colLink]} : ${jsonEncode(queryBody)}"); + Debug.LogResponse( + "adding new query ${query[Queries.colLink]} : ${jsonEncode(queryBody)}"); await cacheDb.insert('Queries', query); @@ -1333,12 +1568,15 @@ class UserOperations { // Map data = {Activity.colType: username + type, Activity.colStartTime: dFormat.format(sTime), Activity.colEndTime: dFormat.format(eTime), Activity.colMetadata: metadata}; // String updateActQuery = "UPDATE Activities SET ${Activity.colType}="; // await cacheDb.insert('Activities', data); - await cacheDb.rawUpdate("UPDATE Activities SET ${Activity.colType}='${username + type}', ${Activity.colStartTime}=datetime('${dFormat.format(sTime)}'), ${Activity.colEndTime}=datetime('${dFormat.format(eTime)}'), ${Activity.colMetadata}='$metadata' WHERE ${Activity.colStartTime}=datetime('${dFormat.format(init_sTime)}')"); + await cacheDb.rawUpdate( + "UPDATE Activities SET ${Activity.colType}='${username + type}', ${Activity.colStartTime}=datetime('${dFormat.format(sTime)}'), ${Activity.colEndTime}=datetime('${dFormat.format(eTime)}'), ${Activity.colMetadata}='$metadata' WHERE ${Activity.colStartTime}=datetime('${dFormat.format(init_sTime)}')"); await refreshUserData(forceOffline: true); } else { // queries.add(Queries('edit_activity', jsonEncode(queryBody))); try { - http.Response queryResponse = (await http.post(Uri.parse('http://161.97.127.136/task_tracker/edit_activity.php'), body: queryBody)); + http.Response queryResponse = (await http.post( + Uri.parse(API_ENDPOINT + '/task_tracker/edit_activity.php'), + body: queryBody)); Debug.LogResponse("Query executed : Results{${queryResponse.body}"); if (queryResponse.body.toLowerCase().contains("success")) { //Success @@ -1361,14 +1599,20 @@ class UserOperations { if (cacheEnabled) { //Add Query - Map query = {Queries.colLink: 'start_ongoing', Queries.colData: jsonEncode(queryBody)}; + Map query = { + Queries.colLink: 'start_ongoing', + Queries.colData: jsonEncode(queryBody) + }; - Debug.LogResponse("adding new query ${query[Queries.colLink]} : ${jsonEncode(queryBody)}"); + Debug.LogResponse( + "adding new query ${query[Queries.colLink]} : ${jsonEncode(queryBody)}"); await cacheDb.insert('Queries', query); } else { try { - http.Response queryResponse = (await http.post(Uri.parse('http://161.97.127.136/task_tracker/start_ongoing.php'), body: queryBody)); + http.Response queryResponse = (await http.post( + Uri.parse(API_ENDPOINT + '/task_tracker/start_ongoing.php'), + body: queryBody)); Debug.LogResponse("Query executed : Results{${queryResponse.body}"); if (queryResponse.body.toLowerCase().contains("success")) { //Success @@ -1388,14 +1632,20 @@ class UserOperations { if (cacheEnabled) { //Add Query - Map query = {Queries.colLink: 'stop_ongoing', Queries.colData: jsonEncode(queryBody)}; + Map query = { + Queries.colLink: 'stop_ongoing', + Queries.colData: jsonEncode(queryBody) + }; - Debug.LogResponse("adding new query ${query[Queries.colLink]} : ${jsonEncode(queryBody)}"); + Debug.LogResponse( + "adding new query ${query[Queries.colLink]} : ${jsonEncode(queryBody)}"); await cacheDb.insert('Queries', query); } else { try { - http.Response queryResponse = (await http.post(Uri.parse('http://161.97.127.136/task_tracker/stop_ongoing.php'), body: queryBody)); + http.Response queryResponse = (await http.post( + Uri.parse(API_ENDPOINT + '/task_tracker/stop_ongoing.php'), + body: queryBody)); Debug.LogResponse("Query executed : Results{${queryResponse.body}"); if (queryResponse.body.toLowerCase().contains("success")) { //Success @@ -1408,7 +1658,8 @@ class UserOperations { await executeQueries(); } - static Future addProject(String name, String category, List steps, int eta, DateTime deadline) async { + static Future addProject(String name, String category, + List steps, int eta, DateTime deadline) async { Map queryBody = { 'name': username + name, 'username': username, @@ -1421,9 +1672,13 @@ class UserOperations { if (cacheEnabled) { //Add Query - Map query = {Queries.colLink: 'add_project', Queries.colData: jsonEncode(queryBody)}; + Map query = { + Queries.colLink: 'add_project', + Queries.colData: jsonEncode(queryBody) + }; - Debug.LogResponse("adding new query ${query[Queries.colLink]} : ${jsonEncode(queryBody)}"); + Debug.LogResponse( + "adding new query ${query[Queries.colLink]} : ${jsonEncode(queryBody)}"); await cacheDb.insert('Queries', query); @@ -1439,7 +1694,9 @@ class UserOperations { await refreshUserData(forceOffline: true); } else { try { - http.Response queryResponse = (await http.post(Uri.parse('http://161.97.127.136/task_tracker/add_project.php'), body: queryBody)); + http.Response queryResponse = (await http.post( + Uri.parse(API_ENDPOINT + '/task_tracker/add_project.php'), + body: queryBody)); Debug.LogResponse("Query executed : Results{${queryResponse.body}"); if (queryResponse.body.toLowerCase().contains("success")) { //Success @@ -1452,7 +1709,8 @@ class UserOperations { await executeQueries(); } - static Future editProject(String oldName, String name, String category, List steps, int eta, DateTime deadline) async { + static Future editProject(String oldName, String name, String category, + List steps, int eta, DateTime deadline) async { Map queryBody = { 'oldName': username + oldName, 'name': username + name, @@ -1465,9 +1723,13 @@ class UserOperations { if (cacheEnabled) { //Add Query - Map query = {Queries.colLink: 'edit_project', Queries.colData: jsonEncode(queryBody)}; + Map query = { + Queries.colLink: 'edit_project', + Queries.colData: jsonEncode(queryBody) + }; - Debug.LogResponse("adding new query ${query[Queries.colLink]} : ${jsonEncode(queryBody)}"); + Debug.LogResponse( + "adding new query ${query[Queries.colLink]} : ${jsonEncode(queryBody)}"); await cacheDb.insert('Queries', query); @@ -1480,12 +1742,15 @@ class UserOperations { Project.colDeadline: deadline.toString() }; await cacheDb.rawUpdate( - "UPDATE Projects SET ${Project.colName}='${username + name}', ${Project.colCat}='${username+category}', ${Project.colSteps}='${jsonEncode(steps)}', ${Project.colEta}='${eta}', ${Project.colDeadline}='${deadline.toString()}' WHERE ${Project.colName}='${username+oldName}'"); - await cacheDb.rawUpdate("UPDATE TaskTypes SET ${TaskType.colRelatedProject}='${username+name}' WHERE ${TaskType.colRelatedProject}='${username+oldName}'"); + "UPDATE Projects SET ${Project.colName}='${username + name}', ${Project.colCat}='${username + category}', ${Project.colSteps}='${jsonEncode(steps)}', ${Project.colEta}='${eta}', ${Project.colDeadline}='${deadline.toString()}' WHERE ${Project.colName}='${username + oldName}'"); + await cacheDb.rawUpdate( + "UPDATE TaskTypes SET ${TaskType.colRelatedProject}='${username + name}' WHERE ${TaskType.colRelatedProject}='${username + oldName}'"); await refreshUserData(forceOffline: true); } else { try { - http.Response queryResponse = (await http.post(Uri.parse('http://161.97.127.136/task_tracker/edit_project.php'), body: queryBody)); + http.Response queryResponse = (await http.post( + Uri.parse(API_ENDPOINT + '/task_tracker/edit_project.php'), + body: queryBody)); Debug.LogResponse("Query executed : Results{${queryResponse.body}"); if (queryResponse.body.toLowerCase().contains("success")) { //Success @@ -1497,7 +1762,8 @@ class UserOperations { await executeQueries(); } - static Future CompleteProjectStep(Project project, ProjectStep step, DateTime finishedDate) async { + static Future CompleteProjectStep( + Project project, ProjectStep step, DateTime finishedDate) async { project.steps.forEach((element) { if (element.stepName == step.stepName) { element.finishedDate = finishedDate; @@ -1512,19 +1778,26 @@ class UserOperations { if (cacheEnabled) { //Add Query - Map query = {Queries.colLink: 'update_projectSteps', Queries.colData: jsonEncode(queryBody)}; + Map query = { + Queries.colLink: 'update_projectSteps', + Queries.colData: jsonEncode(queryBody) + }; - Debug.LogResponse("adding new query ${query[Queries.colLink]} : ${jsonEncode(queryBody)}"); + Debug.LogResponse( + "adding new query ${query[Queries.colLink]} : ${jsonEncode(queryBody)}"); await cacheDb.insert('Queries', query); - await cacheDb.rawUpdate("UPDATE Projects SET steps='${jsonEncode(project.steps)}' WHERE ${Project.colName}='${project.name}'"); + await cacheDb.rawUpdate( + "UPDATE Projects SET steps='${jsonEncode(project.steps)}' WHERE ${Project.colName}='${project.name}'"); //update Cache // Map data = {Project.colName: username+name, Project.colCat: category, Project.colSteps: jsonEncode(steps),Project.colEta: eta, Project.colDeadline: deadline.toString()}; // await cacheDb.insert('Projects', data); await refreshUserData(forceOffline: true); } else { try { - http.Response queryResponse = (await http.post(Uri.parse('http://161.97.127.136/task_tracker/update_projectSteps.php'), body: queryBody)); + http.Response queryResponse = (await http.post( + Uri.parse(API_ENDPOINT + '/task_tracker/update_projectSteps.php'), + body: queryBody)); Debug.LogResponse("Query executed : Results{${queryResponse.body}"); if (queryResponse.body.toLowerCase().contains("success")) { //Success @@ -1552,19 +1825,26 @@ class UserOperations { if (cacheEnabled) { //Add Query - Map query = {Queries.colLink: 'update_projectSteps', Queries.colData: jsonEncode(queryBody)}; + Map query = { + Queries.colLink: 'update_projectSteps', + Queries.colData: jsonEncode(queryBody) + }; - Debug.LogResponse("adding new query ${query[Queries.colLink]} : ${jsonEncode(queryBody)}"); + Debug.LogResponse( + "adding new query ${query[Queries.colLink]} : ${jsonEncode(queryBody)}"); await cacheDb.insert('Queries', query); - await cacheDb.rawUpdate("UPDATE Projects SET steps='${jsonEncode(project.steps)}' WHERE ${Project.colName}='${project.name}'"); + await cacheDb.rawUpdate( + "UPDATE Projects SET steps='${jsonEncode(project.steps)}' WHERE ${Project.colName}='${project.name}'"); //update Cache // Map data = {Project.colName: username+name, Project.colCat: category, Project.colSteps: jsonEncode(steps),Project.colEta: eta, Project.colDeadline: deadline.toString()}; // await cacheDb.insert('Projects', data); await refreshUserData(forceOffline: true); } else { try { - http.Response queryResponse = (await http.post(Uri.parse('http://161.97.127.136/task_tracker/update_projectSteps.php'), body: queryBody)); + http.Response queryResponse = (await http.post( + Uri.parse(API_ENDPOINT + '/task_tracker/update_projectSteps.php'), + body: queryBody)); Debug.LogResponse("Query executed : Results{${queryResponse.body}"); if (queryResponse.body.toLowerCase().contains("success")) { //Success @@ -1577,7 +1857,8 @@ class UserOperations { await executeQueries(); } - static Future addJournal(DateTime day, String title, String text) async { + static Future addJournal( + DateTime day, String title, String text) async { bool exist = false; for (var element in journal) { if (element.day == day) { @@ -1590,22 +1871,37 @@ class UserOperations { return; } String id = username + DateFormat('yyyy-MM-dd').format(day); - Map queryBody = {'username': username, 'id': id, 'title': title, 'description': text}; + Map queryBody = { + 'username': username, + 'id': id, + 'title': title, + 'description': text + }; if (cacheEnabled) { //Add Query - Map query = {Queries.colLink: 'add_journal', Queries.colData: jsonEncode(queryBody)}; + Map query = { + Queries.colLink: 'add_journal', + Queries.colData: jsonEncode(queryBody) + }; - Debug.LogResponse("adding new query ${query[Queries.colLink]} : ${jsonEncode(queryBody)}"); + Debug.LogResponse( + "adding new query ${query[Queries.colLink]} : ${jsonEncode(queryBody)}"); await cacheDb.insert('Queries', query); //update Cache - Map data = {'id': id, Journal.colTitle: title, Journal.colDescription: text}; + Map data = { + 'id': id, + Journal.colTitle: title, + Journal.colDescription: text + }; await cacheDb.insert('Journal', data); await refreshUserData(forceOffline: true); } else { try { - http.Response queryResponse = (await http.post(Uri.parse('http://161.97.127.136/task_tracker/add_journal.php'), body: queryBody)); + http.Response queryResponse = (await http.post( + Uri.parse(API_ENDPOINT + '/task_tracker/add_journal.php'), + body: queryBody)); Debug.LogResponse("Query executed : Results{${queryResponse.body}"); if (queryResponse.body.toLowerCase().contains("success")) { //Success @@ -1619,26 +1915,43 @@ class UserOperations { await executeQueries(); } - static Future editJournal(DateTime oldDay, DateTime day, String title, String text) async { + static Future editJournal( + DateTime oldDay, DateTime day, String title, String text) async { String oldId = username + DateFormat('yyyy-MM-dd').format(oldDay); String id = username + DateFormat('yyyy-MM-dd').format(day); - Map queryBody = {'username': username, 'old_id': oldId, 'id': id, 'title': title, 'description': text}; + Map queryBody = { + 'username': username, + 'old_id': oldId, + 'id': id, + 'title': title, + 'description': text + }; if (cacheEnabled) { //Add Query - Map query = {Queries.colLink: 'edit_journal', Queries.colData: jsonEncode(queryBody)}; + Map query = { + Queries.colLink: 'edit_journal', + Queries.colData: jsonEncode(queryBody) + }; - Debug.LogResponse("adding new query ${query[Queries.colLink]} : ${jsonEncode(queryBody)}"); + Debug.LogResponse( + "adding new query ${query[Queries.colLink]} : ${jsonEncode(queryBody)}"); await cacheDb.insert('Queries', query); await cacheDb.rawUpdate( "UPDATE Journal SET id='$id', ${Journal.colTitle}='${title.toString().replaceAll("'", "''")}', ${Journal.colDescription}='${text.toString().replaceAll("'", "''")}' WHERE id='$oldId'"); //update Cache - Map data = {'id': id, Journal.colTitle: title, Journal.colDescription: text}; + Map data = { + 'id': id, + Journal.colTitle: title, + Journal.colDescription: text + }; // await cacheDb.insert('Journal', data); await refreshUserData(forceOffline: true); } else { try { - http.Response queryResponse = (await http.post(Uri.parse('http://161.97.127.136/task_tracker/edit_journal.php'), body: queryBody)); + http.Response queryResponse = (await http.post( + Uri.parse(API_ENDPOINT + '/task_tracker/edit_journal.php'), + body: queryBody)); Debug.LogResponse("Query executed : Results{${queryResponse.body}"); if (queryResponse.body.toLowerCase().contains("success")) { //Success @@ -1652,10 +1965,10 @@ class UserOperations { await executeQueries(); } - static Future addTodo(String taskType, String metadata, DateTime dueDate, DateTime? notificationTime) async { - + static Future addTodo(String taskType, String metadata, + DateTime dueDate, DateTime? notificationTime) async { String taskId = username + taskType; - if(taskId.contains('[') && taskId.contains(']')){ + if (taskId.contains('[') && taskId.contains(']')) { //has a project related taskId = taskId.substring(0, taskId.indexOf('[') - 1); } @@ -1667,23 +1980,39 @@ class UserOperations { 'task': taskId, 'metadata': metadata, 'due_date': DateFormat('yyyy-MM-dd').format(dueDate), - if(notificationTime!=null)'notification_time':DateFormat('yyyy-MM-dd HH:mm').format(notificationTime) + if (notificationTime != null) + 'notification_time': + DateFormat('yyyy-MM-dd HH:mm').format(notificationTime) }; if (cacheEnabled) { //Add Query - Map query = {Queries.colLink: 'add_todo', Queries.colData: jsonEncode(queryBody)}; + Map query = { + Queries.colLink: 'add_todo', + Queries.colData: jsonEncode(queryBody) + }; - Debug.LogResponse("adding new query ${query[Queries.colLink]} : ${jsonEncode(queryBody)}"); + Debug.LogResponse( + "adding new query ${query[Queries.colLink]} : ${jsonEncode(queryBody)}"); await cacheDb.insert('Queries', query); //update Cache - Map data = {'id': id, Todo.colCat: taskId, Todo.colMetadata: metadata, Todo.colDueDate: DateFormat('yyyy-MM-dd').format(dueDate), if(notificationTime!=null)Todo.colNotificationTime:DateFormat('yyyy-MM-dd HH:mm').format(notificationTime)}; + Map data = { + 'id': id, + Todo.colCat: taskId, + Todo.colMetadata: metadata, + Todo.colDueDate: DateFormat('yyyy-MM-dd').format(dueDate), + if (notificationTime != null) + Todo.colNotificationTime: + DateFormat('yyyy-MM-dd HH:mm').format(notificationTime) + }; await cacheDb.insert('Todos', data); await refreshUserData(forceOffline: true); } else { try { - http.Response queryResponse = (await http.post(Uri.parse('http://161.97.127.136/task_tracker/add_todo.php'), body: queryBody)); + http.Response queryResponse = (await http.post( + Uri.parse(API_ENDPOINT + '/task_tracker/add_todo.php'), + body: queryBody)); Debug.LogResponse("Query executed : Results{${queryResponse.body}"); if (queryResponse.body.toLowerCase().contains("success")) { //Success @@ -1697,10 +2026,10 @@ class UserOperations { await executeQueries(); } - static Future editTodo(String oldId, String taskType, String metadata, DateTime dueDate, DateTime? notificationTime) async { - + static Future editTodo(String oldId, String taskType, String metadata, + DateTime dueDate, DateTime? notificationTime) async { String taskId = username + taskType; - if(taskId.contains('[') && taskId.contains(']')){ + if (taskId.contains('[') && taskId.contains(']')) { //has a project related taskId = taskId.substring(0, taskId.indexOf('[') - 1); } @@ -1708,29 +2037,38 @@ class UserOperations { String id = taskId + metadata; Map queryBody = { - 'old_id' : oldId, + 'old_id': oldId, 'username': username, 'task': taskId, 'metadata': metadata, 'due_date': DateFormat('yyyy-MM-dd').format(dueDate), - if(notificationTime!=null)'notification_time':DateFormat('yyyy-MM-dd HH:mm').format(notificationTime) + if (notificationTime != null) + 'notification_time': + DateFormat('yyyy-MM-dd HH:mm').format(notificationTime) }; if (cacheEnabled) { //Add Query - Map query = {Queries.colLink: 'edit_todo', Queries.colData: jsonEncode(queryBody)}; + Map query = { + Queries.colLink: 'edit_todo', + Queries.colData: jsonEncode(queryBody) + }; - Debug.LogResponse("adding new query ${query[Queries.colLink]} : ${jsonEncode(queryBody)}"); + Debug.LogResponse( + "adding new query ${query[Queries.colLink]} : ${jsonEncode(queryBody)}"); await cacheDb.insert('Queries', query); String dueDateString = DateFormat('yyyy-MM-dd').format(dueDate); //update Cache - // Map data = {'id': id, Todo.colCat: taskId, Todo.colMetadata: metadata, Todo.colDueDate: DateFormat('yyyy-MM-dd').format(dueDate), if(notificationTime!=null)Todo.colNotificationTime:DateFormat('yyyy-MM-dd HH:mm').format(notificationTime)}; - // await cacheDb.insert('Todos', data); - await cacheDb.rawUpdate("UPDATE Todos SET id='$id', ${Todo.colCat}='$taskId', ${Todo.colMetadata}='$metadata', ${Todo.colDueDate}='$dueDateString'${(notificationTime!=null) ? ", ${Todo.colNotificationTime}='${DateFormat('yyyy-MM-dd HH:mm').format(notificationTime)}'" : ''} WHERE id='$oldId'"); + // Map data = {'id': id, Todo.colCat: taskId, Todo.colMetadata: metadata, Todo.colDueDate: DateFormat('yyyy-MM-dd').format(dueDate), if(notificationTime!=null)Todo.colNotificationTime:DateFormat('yyyy-MM-dd HH:mm').format(notificationTime)}; + // await cacheDb.insert('Todos', data); + await cacheDb.rawUpdate( + "UPDATE Todos SET id='$id', ${Todo.colCat}='$taskId', ${Todo.colMetadata}='$metadata', ${Todo.colDueDate}='$dueDateString'${(notificationTime != null) ? ", ${Todo.colNotificationTime}='${DateFormat('yyyy-MM-dd HH:mm').format(notificationTime)}'" : ''} WHERE id='$oldId'"); await refreshUserData(forceOffline: true); } else { try { - http.Response queryResponse = (await http.post(Uri.parse('http://161.97.127.136/task_tracker/edit_todo.php'), body: queryBody)); + http.Response queryResponse = (await http.post( + Uri.parse(API_ENDPOINT + '/task_tracker/edit_todo.php'), + body: queryBody)); Debug.LogResponse("Query executed : Results{${queryResponse.body}"); if (queryResponse.body.toLowerCase().contains("success")) { //Success @@ -1744,7 +2082,6 @@ class UserOperations { await executeQueries(); } - static Future deleteTask(String name, {bulk = false}) async { Map queryBody = { 'id': username + name, @@ -1752,9 +2089,13 @@ class UserOperations { 'device_id': await Settings.UUID(), }; //Add Query - Map query = {Queries.colLink: 'delete_taskType', Queries.colData: jsonEncode(queryBody)}; + Map query = { + Queries.colLink: 'delete_taskType', + Queries.colData: jsonEncode(queryBody) + }; - Debug.LogResponse("adding new query ${query[Queries.colLink]} : ${jsonEncode(queryBody)}"); + Debug.LogResponse( + "adding new query ${query[Queries.colLink]} : ${jsonEncode(queryBody)}"); if (cacheEnabled) { await cacheDb.insert('Queries', query); @@ -1763,13 +2104,16 @@ class UserOperations { TaskType.colId: username + name, Category.colName: name, }; - await cacheDb.rawDelete("DELETE FROM TaskTypes WHERE id='${username + name}'"); + await cacheDb + .rawDelete("DELETE FROM TaskTypes WHERE id='${username + name}'"); await refreshUserData(forceOffline: true); //Add to server and refresh Cache } else { try { - http.Response queryResponse = (await http.post(Uri.parse('http://161.97.127.136/task_tracker/delete_taskType.php'), body: queryBody)); + http.Response queryResponse = (await http.post( + Uri.parse(API_ENDPOINT + '/task_tracker/delete_taskType.php'), + body: queryBody)); Debug.LogResponse("Query executed : Results{${queryResponse.body}"); if (queryResponse.body.toLowerCase().contains("success")) { //Success @@ -1790,9 +2134,13 @@ class UserOperations { 'device_id': await Settings.UUID(), }; //Add Query - Map query = {Queries.colLink: 'delete_category', Queries.colData: jsonEncode(queryBody)}; + Map query = { + Queries.colLink: 'delete_category', + Queries.colData: jsonEncode(queryBody) + }; - Debug.LogResponse("adding new query ${query[Queries.colLink]} : ${jsonEncode(queryBody)}"); + Debug.LogResponse( + "adding new query ${query[Queries.colLink]} : ${jsonEncode(queryBody)}"); if (cacheEnabled) { await cacheDb.insert('Queries', query); @@ -1801,12 +2149,15 @@ class UserOperations { TaskType.colId: username + name, Category.colName: name, }; - await cacheDb.rawDelete("DELETE FROM Categories WHERE ${Category.colCatId}='${username + name}'"); + await cacheDb.rawDelete( + "DELETE FROM Categories WHERE ${Category.colCatId}='${username + name}'"); await refreshUserData(forceOffline: true); //Add to server and refresh Cache } else { try { - http.Response queryResponse = (await http.post(Uri.parse('http://161.97.127.136/task_tracker/delete_category.php'), body: queryBody)); + http.Response queryResponse = (await http.post( + Uri.parse(API_ENDPOINT + '/task_tracker/delete_category.php'), + body: queryBody)); Debug.LogResponse("Query executed : Results{${queryResponse.body}"); if (queryResponse.body.toLowerCase().contains("success")) { //Success @@ -1828,9 +2179,13 @@ class UserOperations { 'eTime': activity.trueEndTime.toString(), }; //Add Query - Map query = {Queries.colLink: 'delete_activity', Queries.colData: jsonEncode(queryBody)}; + Map query = { + Queries.colLink: 'delete_activity', + Queries.colData: jsonEncode(queryBody) + }; - Debug.LogResponse("adding new query ${query[Queries.colLink]} : ${jsonEncode(queryBody)}"); + Debug.LogResponse( + "adding new query ${query[Queries.colLink]} : ${jsonEncode(queryBody)}"); if (cacheEnabled) { await cacheDb.insert('Queries', query); @@ -1845,7 +2200,9 @@ class UserOperations { //Add to server and refresh Cache } else { try { - http.Response queryResponse = (await http.post(Uri.parse('http://161.97.127.136/task_tracker/delete_activity.php'), body: queryBody)); + http.Response queryResponse = (await http.post( + Uri.parse(API_ENDPOINT + '/task_tracker/delete_activity.php'), + body: queryBody)); Debug.LogResponse("Query executed : Results{${queryResponse.body}"); if (queryResponse.body.toLowerCase().contains("success")) { //Success @@ -1865,15 +2222,20 @@ class UserOperations { 'name': username + project, }; //Add Query - Map query = {Queries.colLink: 'delete_project', Queries.colData: jsonEncode(queryBody)}; + Map query = { + Queries.colLink: 'delete_project', + Queries.colData: jsonEncode(queryBody) + }; - Debug.LogResponse("adding new query ${query[Queries.colLink]} : ${jsonEncode(queryBody)}"); + Debug.LogResponse( + "adding new query ${query[Queries.colLink]} : ${jsonEncode(queryBody)}"); if (cacheEnabled) { await cacheDb.insert('Queries', query); //update Cache - String deleteQuery = "DELETE FROM Projects WHERE ${Project.colName}='${username + project}'"; + String deleteQuery = + "DELETE FROM Projects WHERE ${Project.colName}='${username + project}'"; Debug.LogResponse("delteQuery : $deleteQuery"); await cacheDb.rawDelete(deleteQuery); @@ -1881,7 +2243,9 @@ class UserOperations { //Add to server and refresh Cache } else { try { - http.Response queryResponse = (await http.post(Uri.parse('http://161.97.127.136/task_tracker/delete_project.php'), body: queryBody)); + http.Response queryResponse = (await http.post( + Uri.parse(API_ENDPOINT + '/task_tracker/delete_project.php'), + body: queryBody)); Debug.LogResponse("Query executed : Results{${queryResponse.body}"); if (queryResponse.body.toLowerCase().contains("success")) { //Success @@ -1901,9 +2265,13 @@ class UserOperations { 'id': id, }; //Add Query - Map query = {Queries.colLink: 'delete_journal', Queries.colData: jsonEncode(queryBody)}; + Map query = { + Queries.colLink: 'delete_journal', + Queries.colData: jsonEncode(queryBody) + }; - Debug.LogResponse("adding new query ${query[Queries.colLink]} : ${jsonEncode(queryBody)}"); + Debug.LogResponse( + "adding new query ${query[Queries.colLink]} : ${jsonEncode(queryBody)}"); if (cacheEnabled) { await cacheDb.insert('Queries', query); @@ -1917,7 +2285,9 @@ class UserOperations { //Add to server and refresh Cache } else { try { - http.Response queryResponse = (await http.post(Uri.parse('http://161.97.127.136/task_tracker/delete_journal.php'), body: queryBody)); + http.Response queryResponse = (await http.post( + Uri.parse(API_ENDPOINT + '/task_tracker/delete_journal.php'), + body: queryBody)); Debug.LogResponse("Query executed : Results{${queryResponse.body}"); if (queryResponse.body.toLowerCase().contains("success")) { //Success @@ -1937,9 +2307,13 @@ class UserOperations { 'id': id, }; //Add Query - Map query = {Queries.colLink: 'delete_todo', Queries.colData: jsonEncode(queryBody)}; + Map query = { + Queries.colLink: 'delete_todo', + Queries.colData: jsonEncode(queryBody) + }; - Debug.LogResponse("adding new query ${query[Queries.colLink]} : ${jsonEncode(queryBody)}"); + Debug.LogResponse( + "adding new query ${query[Queries.colLink]} : ${jsonEncode(queryBody)}"); if (cacheEnabled) { await cacheDb.insert('Queries', query); @@ -1953,7 +2327,9 @@ class UserOperations { //Add to server and refresh Cache } else { try { - http.Response queryResponse = (await http.post(Uri.parse('http://161.97.127.136/task_tracker/delete_todo.php'), body: queryBody)); + http.Response queryResponse = (await http.post( + Uri.parse(API_ENDPOINT + '/task_tracker/delete_todo.php'), + body: queryBody)); Debug.LogResponse("Query executed : Results{${queryResponse.body}"); if (queryResponse.body.toLowerCase().contains("success")) { //Success @@ -1988,9 +2364,12 @@ class UserOperations { //Execute the http here Map body = jsonDecode(data); try { - http.Response queryResponse = (await http.post(Uri.parse('http://161.97.127.136/task_tracker/$file.php'), body: body)); + http.Response queryResponse = (await http.post( + Uri.parse(API_ENDPOINT + '/task_tracker/$file.php'), + body: body)); Debug.LogResponse("Query executed : Results{${queryResponse.body}"); - if (queryResponse.body.toLowerCase().contains("+") || queryResponse.body.toLowerCase().contains("success")) { + if (queryResponse.body.toLowerCase().contains("+") || + queryResponse.body.toLowerCase().contains("success")) { await cacheDb.rawDelete('DELETE FROM Queries WHERE id=$id'); } offline = false; @@ -2001,7 +2380,8 @@ class UserOperations { //await refreshUserData(); } else { await refreshUserData(); - Debug.LogError('Trying to execute queries in no cahce mode, We dont do that here'); + Debug.LogError( + 'Trying to execute queries in no cahce mode, We dont do that here'); } } } diff --git a/lib/main.dart b/lib/main.dart index 0b8f2df..277f4cf 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -79,10 +79,10 @@ extension HexColor on Color { void main() async { //Wakelock.enable(); // or Wakelock.toggle(on: true); - if(!K.kIsWeb &&(Platform.isAndroid || Platform.isIOS)){ - WidgetsFlutterBinding.ensureInitialized(); - await Firebase.initializeApp(); - } + if (!K.kIsWeb && (Platform.isAndroid || Platform.isIOS)) { + WidgetsFlutterBinding.ensureInitialized(); + await Firebase.initializeApp(); + } // // ByteData data = await PlatformAssetBundle().load('assets/ca/certificate.crt'); // SecurityContext.defaultContext.setTrustedCertificatesBytes(data.buffer.asUint8List()); @@ -102,8 +102,17 @@ class MyApp extends StatelessWidget { return MaterialApp( title: 'Task Tracker', themeMode: themeProvider.themeMode, - theme: ThemeData(accentColor: Colors.redAccent, brightness: Brightness.light, primaryColor: Colors.amber, fontFamily: 'Noto-Sans'), - darkTheme: ThemeData(backgroundColor: Colors.black,accentColor: Colors.redAccent, brightness: Brightness.dark, primaryColor: Colors.amber, fontFamily: 'Noto-Sans'), + theme: ThemeData( + accentColor: Colors.redAccent, + brightness: Brightness.light, + primaryColor: Colors.amber, + fontFamily: 'Noto-Sans'), + darkTheme: ThemeData( + backgroundColor: Colors.black, + accentColor: Colors.redAccent, + brightness: Brightness.dark, + primaryColor: Colors.amber, + fontFamily: 'Noto-Sans'), navigatorKey: navigatorKey, //home: const SplashScreen(), initialRoute: '/', @@ -115,10 +124,10 @@ class MyApp extends StatelessWidget { '/Categories': (context) => const Categories(), '/Activities': (context) => const Activities(), '/Settings': (context) => const SettingsPage(), - '/Projects':(context)=> const Projects(), - '/Journal': (context)=> const JournalPage(), - '/Todos':(context)=> const TodosPage(), - '/Analytics':(context)=> const AnalyticsPage() + '/Projects': (context) => const Projects(), + '/Journal': (context) => const JournalPage(), + '/Todos': (context) => const TodosPage(), + '/Analytics': (context) => const AnalyticsPage() }); }); } @@ -132,11 +141,10 @@ DateTimeRange? taskTypeRange = null; DateTimeRange? catsRange = null; DateTimeRange? prodRange = null; - List pastProductivityData = [ ProductivityMapData('02/24', 32), ProductivityMapData('02/25', 5), - ProductivityMapData('02/26',56), + ProductivityMapData('02/26', 56), ProductivityMapData('02/27', 33), ProductivityMapData('02/28', 50) ]; @@ -148,7 +156,10 @@ List productivityData = [ ProductivityMapData('02/28', 40) ]; -List taskTypesData = [TaskTypeMapData('Eat', 3600, Colors.green), TaskTypeMapData('Play', 300, Colors.blue)]; +List taskTypesData = [ + TaskTypeMapData('Eat', 3600, Colors.green), + TaskTypeMapData('Play', 300, Colors.blue) +]; List catsData = [ CatMapData('Jan', 35, Colors.green), CatMapData('Feb', 28, Colors.blueAccent), @@ -192,7 +203,7 @@ class _MyHomePageState extends State { // } // }); refreshSub = User.refreshStream.stream.listen((event) { - if(event==false){ + if (event == false) { //Update done, Lets go update data LoadStats(); } @@ -202,14 +213,15 @@ class _MyHomePageState extends State { startLoadStatRefresher(); // User.progressDialog=progressDialog; } + double hourglassTime = 0; List hourglassColors = [Colors.black]; List hourglassStops = [1]; int hourglassTotalTime = 0; - void startLoadStatRefresher() async{ + void startLoadStatRefresher() async { int lastMinute = 0; - while(true){ - if(DateTime.now().minute != lastMinute){ + while (true) { + if (DateTime.now().minute != lastMinute) { lastMinute = DateTime.now().minute; LoadStats(); @@ -219,62 +231,61 @@ class _MyHomePageState extends State { // if(hourglassTime > 1){ // hourglassTime=0; // } - hourglassTime = ((DateTime.now().hour * 60) + DateTime.now().minute) / 1440; - // hourglassTime = 1; - // print('hourglass time : $hourglassTime'); - hourglassColors =[]; + hourglassTime = + ((DateTime.now().hour * 60) + DateTime.now().minute) / 1440; + // hourglassTime = 1; + // print('hourglass time : $hourglassTime'); + hourglassColors = []; hourglassStops = []; - hourglassTotalTime=0; + hourglassTotalTime = 0; hourglassCatData.forEach((element) { - // if(element.time > hourglassTotalTime){ - hourglassTotalTime+=element.time; - // } + // if(element.time > hourglassTotalTime){ + hourglassTotalTime += element.time; + // } }); - // print('hourglass cat data'); + // print('hourglass cat data'); double stopsTotal = 0; - for(int i =0 ; i < hourglassCatData.length; i++) { + for (int i = 0; i < hourglassCatData.length; i++) { CatMapData element = hourglassCatData[i]; - // print('${element.name} : ${element.time} / $hourglassTotalTime = ${element.time / hourglassTotalTime}'); - double thisStop = ( element.time/hourglassTotalTime); + // print('${element.name} : ${element.time} / $hourglassTotalTime = ${element.time / hourglassTotalTime}'); + double thisStop = (element.time / hourglassTotalTime); hourglassColors.add(element.color); - hourglassStops.add(stopsTotal+thisStop); + hourglassStops.add(stopsTotal + thisStop); stopsTotal += thisStop; - if(i < hourglassCatData.length-1){ - hourglassColors.add(hourglassCatData[i+1].color); - hourglassStops.add(stopsTotal+thisStop + 0.001); + if (i < hourglassCatData.length - 1) { + hourglassColors.add(hourglassCatData[i + 1].color); + hourglassStops.add(stopsTotal + thisStop + 0.001); } } - // print('total Stops ${stopsTotal}'); - // print('maxT: $hourglassTotalTime'); - if(hourglassColors.isEmpty){ + // print('total Stops ${stopsTotal}'); + // print('maxT: $hourglassTotalTime'); + if (hourglassColors.isEmpty) { hourglassColors.add(Colors.black); hourglassStops.add(1); } - // print('hourglass \n$hourglassColors \n$hourglassStops'); - setState(() { - - }); + // print('hourglass \n$hourglassColors \n$hourglassStops'); + setState(() {}); await Future.delayed(Duration(seconds: 1)); } } - void init(BuildContext context) async{ + void init(BuildContext context) async { await Future.delayed(Duration(seconds: 1)); refreshSub = User.refreshStream.stream.listen((value) { print("Streaming refresh : $value"); - if(value){ - // Dialogs.waiting("Syncing..."); + if (value) { + // Dialogs.waiting("Syncing..."); print("Opening progress dialog"); - }else{ - // Dialogs.hide(); - // Dialogs.hide(); + } else { + // Dialogs.hide(); + // Dialogs.hide(); print("Closing progress dialog"); } }); //await User.refreshUserData(); - } + DateTime? lastProductive = null; @override void dispose() { @@ -285,57 +296,55 @@ class _MyHomePageState extends State { } String ongoingActName = ""; - DateTime ongoingActStime=DateTime.now(); + DateTime ongoingActStime = DateTime.now(); - Future Refresh() async{ + Future Refresh() async { final prefs = await SharedPreferences.getInstance(); - if(prefs.containsKey('current_activity')){ + if (prefs.containsKey('current_activity')) { List data = []; - try{ + try { data = prefs.getString('current_activity')!.split(''); - ongoingActName=data[0]; + ongoingActName = data[0]; ongoingActStime = DateTime.parse(data[2]); - }catch(e){ + } catch (e) { ongoingActName = ""; } - }else{ + } else { ongoingActName = ""; } - if(this.mounted) { - setState(() { - - }); + if (this.mounted) { + setState(() {}); } } - bool loadingStats = false; + + bool loadingStats = false; DateFormat dFormat = DateFormat("yyyy-MM-dd"); void LoadStats() async { // return; - // await User.refreshUserData(); + // await User.refreshUserData(); - if(loadingStats){ + if (loadingStats) { print('loading stats already'); return; - }else { - loadingStats=true; + } else { + loadingStats = true; } await Refresh(); - Map catTimeMap = {}; Map catBriefMap = {}; Map productivtyActs = {}; Map unproductivtyActs = {}; Map taskTypesDuration = {}; - hourglassCatData=[]; - hourglassColors=[]; + hourglassCatData = []; + hourglassColors = []; firstDay = null; lastDay = null; String lastDate = ""; - lastProductive=null; + lastProductive = null; days = []; for (var element in User.activities) { if (lastDay == null) { @@ -343,15 +352,18 @@ class _MyHomePageState extends State { } if (taskTypeRange == null) { print("$lastDay - $firstDay"); - taskTypeRange = DateTimeRange(start: lastDay!.subtract(const Duration(days: 0)), end: lastDay!); + taskTypeRange = DateTimeRange( + start: lastDay!.subtract(const Duration(days: 0)), end: lastDay!); } if (catsRange == null) { print("$lastDay - $firstDay"); - catsRange = DateTimeRange(start: lastDay!.subtract(const Duration(days: 0)), end: lastDay!); + catsRange = DateTimeRange( + start: lastDay!.subtract(const Duration(days: 0)), end: lastDay!); } if (prodRange == null) { print("$lastDay - $firstDay"); - prodRange = DateTimeRange(start: lastDay!.subtract(const Duration(days: 7)), end: lastDay!); + prodRange = DateTimeRange( + start: lastDay!.subtract(const Duration(days: 7)), end: lastDay!); } firstDay = element.startTime; String thisDate = dFormat.format(element.startTime); @@ -365,10 +377,15 @@ class _MyHomePageState extends State { curDay = dFormat.format(DateTime.now()); } - if ((element.startTime.isAfter(taskTypeRange!.start) && element.startTime.isBefore(taskTypeRange!.end)) || - (dFormat.format(element.startTime) == dFormat.format(taskTypeRange!.start) || dFormat.format(element.startTime) == dFormat.format(taskTypeRange!.end))) { + if ((element.startTime.isAfter(taskTypeRange!.start) && + element.startTime.isBefore(taskTypeRange!.end)) || + (dFormat.format(element.startTime) == + dFormat.format(taskTypeRange!.start) || + dFormat.format(element.startTime) == + dFormat.format(taskTypeRange!.end))) { if (taskTypesDuration.containsKey(element.taskType)) { - taskTypesDuration[element.taskType] = taskTypesDuration[element.taskType]! + thisMinutes; + taskTypesDuration[element.taskType] = + taskTypesDuration[element.taskType]! + thisMinutes; } else { taskTypesDuration.putIfAbsent(element.taskType, () => thisMinutes); } @@ -376,53 +393,65 @@ class _MyHomePageState extends State { if (element.taskType.cat?.productive ?? false) { if (lastProductive == null) { lastProductive = element.trueEndTime; - }} - if ((element.startTime.isAfter(prodRange!.start) && element.startTime.isBefore(prodRange!.end)) || - (dFormat.format(element.startTime) == dFormat.format(prodRange!.start) || dFormat.format(element.startTime) == dFormat.format(prodRange!.end))) { + } + } + if ((element.startTime.isAfter(prodRange!.start) && + element.startTime.isBefore(prodRange!.end)) || + (dFormat.format(element.startTime) == + dFormat.format(prodRange!.start) || + dFormat.format(element.startTime) == + dFormat.format(prodRange!.end))) { if (element.taskType.cat?.productive ?? false) { // if (lastProductive == null) { // lastProductive = element.trueEndTime; // } if (productivtyActs.containsKey(thisDate)) { - productivtyActs[thisDate] = (productivtyActs[thisDate]! + thisMinutes); + productivtyActs[thisDate] = + (productivtyActs[thisDate]! + thisMinutes); } else { productivtyActs.putIfAbsent(thisDate, () => thisMinutes); } } else { if (unproductivtyActs.containsKey(thisDate)) { - unproductivtyActs[thisDate] = (unproductivtyActs[thisDate]! + thisMinutes); + unproductivtyActs[thisDate] = + (unproductivtyActs[thisDate]! + thisMinutes); } else { unproductivtyActs.putIfAbsent(thisDate, () => thisMinutes); } } } if (thisDate == curDay) { - if (element.taskType.cat == null) { - continue; - } - print("Null : ${thisMinutes}"); - if (catTimeMap.containsKey(element.taskType.cat)) { - catTimeMap[element.taskType.cat!] = - (catTimeMap[element.taskType.cat]! + thisMinutes); - } else { - catTimeMap.putIfAbsent(element.taskType.cat!, () => thisMinutes); - } + if (element.taskType.cat == null) { + continue; + } + print("Null : ${thisMinutes}"); + if (catTimeMap.containsKey(element.taskType.cat)) { + catTimeMap[element.taskType.cat!] = + (catTimeMap[element.taskType.cat]! + thisMinutes); + } else { + catTimeMap.putIfAbsent(element.taskType.cat!, () => thisMinutes); + } } - if ((element.startTime.isAfter(catsRange!.start) && element.startTime.isBefore(catsRange!.end)) || - (dFormat.format(element.startTime) == dFormat.format(catsRange!.start) || dFormat.format(element.startTime) == dFormat.format(catsRange!.end))) { + if ((element.startTime.isAfter(catsRange!.start) && + element.startTime.isBefore(catsRange!.end)) || + (dFormat.format(element.startTime) == + dFormat.format(catsRange!.start) || + dFormat.format(element.startTime) == + dFormat.format(catsRange!.end))) { if (element.taskType.cat == null) { continue; } print("Null : ${thisMinutes}"); if (catBriefMap.containsKey(element.taskType.cat)) { - catBriefMap[element.taskType.cat!] = (catBriefMap[element.taskType.cat]! + thisMinutes); + catBriefMap[element.taskType.cat!] = + (catBriefMap[element.taskType.cat]! + thisMinutes); } else { catBriefMap.putIfAbsent(element.taskType.cat!, () => thisMinutes); } } - if(dFormat.format(element.startTime) == dFormat.format(DateTime.now())){ + if (dFormat.format(element.startTime) == dFormat.format(DateTime.now())) { if (element.taskType.cat == null) { continue; } @@ -430,24 +459,22 @@ class _MyHomePageState extends State { int? existingEntryIndex; - for(int i=0; i < hourglassCatData.length; i++){ - if(hourglassCatData[i].name == element.taskType.category){ - existingEntryIndex=i; + for (int i = 0; i < hourglassCatData.length; i++) { + if (hourglassCatData[i].name == element.taskType.category) { + existingEntryIndex = i; } - - } - if (existingEntryIndex==null) { - hourglassCatData.add(CatMapData(element.taskType.category, thisMinutes, HexColor.fromHex(element.taskType.cat!.color))); + if (existingEntryIndex == null) { + hourglassCatData.add(CatMapData(element.taskType.category, + thisMinutes, HexColor.fromHex(element.taskType.cat!.color))); } else { - hourglassCatData[existingEntryIndex!].time+=thisMinutes; + hourglassCatData[existingEntryIndex!].time += thisMinutes; } - } hourglassCatData.sort((a, b) => a.time.compareTo(b.time)); - // hourglassCatData = hourglassCatData.reversed.toList(); + // hourglassCatData = hourglassCatData.reversed.toList(); } dailyData = []; productivityData = []; @@ -460,9 +487,9 @@ class _MyHomePageState extends State { dailyData.add(CatMapData(key.name, value, barCol)); trackedTime += value; }); - int untrackedTime = 1440-trackedTime; - if(untrackedTime<0){ - User.refreshUserData().then((val)=>LoadStats()); + int untrackedTime = 1440 - trackedTime; + if (untrackedTime < 0) { + User.refreshUserData().then((val) => LoadStats()); print("Shit went wrong!"); } print("Tracked time : $trackedTime"); @@ -470,30 +497,42 @@ class _MyHomePageState extends State { dailyData.sort((a, b) { return a.name.toLowerCase().compareTo(b.name.toLowerCase()); }); - if(untrackedTime> 0){dailyData.add(CatMapData("Untracked",1440-trackedTime, Colors.black));}else{} + if (untrackedTime > 0) { + dailyData.add(CatMapData("Untracked", 1440 - trackedTime, Colors.black)); + } else {} bool untrackedUnprod = await Settings.getUntrackedUnproductive(); for (var element in days) { // if(productivtyActs.containsKey(element) && unproductivtyActs.containsKey(element)){ int prodActs = (productivtyActs[element] ?? 0); int unprodActs = (unproductivtyActs[element] ?? 0); - double prod = (untrackedUnprod) ? ((prodActs / 1440) * 100) : ((prodActs / unprodActs)*100); + double prod = (untrackedUnprod) + ? ((prodActs / 1440) * 100) + : ((prodActs / unprodActs) * 100); var newProdData = ProductivityMapData(element, prod); - if(prod>0 && !productivityData.contains(newProdData)){ + if (prod > 0 && !productivityData.contains(newProdData)) { productivityData.add(newProdData); } // } } //Past Prod - Map pastProdData = AnalyticTools.getProductivities(DateTimeRange(start: prodRange!.start.subtract(Duration(days: prodRange!.duration.inDays+1)), end: prodRange!.start.subtract(Duration(days: 1)))); - pastProductivityData=[]; + Map pastProdData = AnalyticTools.getProductivities( + DateTimeRange( + start: prodRange!.start + .subtract(Duration(days: prodRange!.duration.inDays + 1)), + end: prodRange!.start.subtract(Duration(days: 1)))); + pastProductivityData = []; pastProdData.forEach((key, value) { - pastProductivityData.add(ProductivityMapData(dFormat.format(key.add(Duration(days: prodRange!.duration.inDays+1))), value)); + pastProductivityData.add(ProductivityMapData( + dFormat + .format(key.add(Duration(days: prodRange!.duration.inDays + 1))), + value)); }); taskTypesDuration.forEach((key, value) { print("$key : $value"); - taskTypesData.add(TaskTypeMapData(key.name, value, HexColor.fromHex(key.cat!.color))); + taskTypesData.add( + TaskTypeMapData(key.name, value, HexColor.fromHex(key.cat!.color))); }); taskTypesData.sort((a, b) { @@ -507,16 +546,16 @@ class _MyHomePageState extends State { }); catsData.sort((a, b) => a.time.compareTo(b.time)); - //relative TOdos List relativeTodoDays = []; - relativeTodos=[]; - for(int i =0; i < 2; i++){ - relativeTodoDays.add(dFormat.format(DateTime.now().add(Duration(days: i)))); + relativeTodos = []; + for (int i = 0; i < 2; i++) { + relativeTodoDays + .add(dFormat.format(DateTime.now().add(Duration(days: i)))); } User.todos.forEach((element) { - if(relativeTodoDays.contains(dFormat.format(element.dueDate))){ + if (relativeTodoDays.contains(dFormat.format(element.dueDate))) { //Suitaable relativeTodos.add(element); } @@ -524,17 +563,15 @@ class _MyHomePageState extends State { //curDay = days[0]; if (this.mounted) { - setState(() { - - }); + setState(() {}); } // print('productivity data'); // productivityData.forEach((element) { // print(element.day); // }); - loadingStats=false; - // loadingStats=false; + loadingStats = false; + // loadingStats=false; } void showOfflineSnack() async { @@ -550,7 +587,6 @@ class _MyHomePageState extends State { @override Widget build(BuildContext context) { - double avgProd = 0; double pastAvgProd = 0; int _avgProdCount = 0; @@ -567,28 +603,36 @@ class _MyHomePageState extends State { avgProd = avgProd / _avgProdCount; pastAvgProd = pastAvgProd / _pastAvgProdCount; - bool landscape=((MediaQuery.of(context).size.width / MediaQuery.of(context).size.height) > 1); + bool landscape = ((MediaQuery.of(context).size.width / + MediaQuery.of(context).size.height) > + 1); return Scaffold( floatingActionButton: FloatingActionButton.extended( onPressed: () { - Navigator.of(context).push(MaterialPageRoute(builder: (context) => NewActivity())); + Navigator.of(context) + .push(MaterialPageRoute(builder: (context) => NewActivity())); }, label: Text("New Activity"), icon: Icon(Icons.add)), appBar: AppBar( title: Column( - mainAxisSize: MainAxisSize.max, - mainAxisAlignment: MainAxisAlignment.end, + mainAxisSize: MainAxisSize.max, + mainAxisAlignment: MainAxisAlignment.end, children: [ Row( mainAxisSize: MainAxisSize.max, mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ - Row(children: [FaIcon(FontAwesomeIcons.chartBar), SizedBox(width: 10), Text('Summary')]), + Row(children: [ + FaIcon(FontAwesomeIcons.chartBar), + SizedBox(width: 10), + Text('Summary') + ]), Row( children: [ (User.offline) - ? Icon(Icons.signal_cellular_connected_no_internet_4_bar_outlined) + ? Icon(Icons + .signal_cellular_connected_no_internet_4_bar_outlined) : InkWell( onTap: () { setState(() async { @@ -611,451 +655,864 @@ class _MyHomePageState extends State { mainAxisSize: MainAxisSize.max, mainAxisAlignment: MainAxisAlignment.start, children: [ - landscape?navDrawer(context, 0) : Container(), - (User.activities.isEmpty) ? Container( - width: 1000, - child: Column( - mainAxisSize: MainAxisSize.max, - mainAxisAlignment: MainAxisAlignment.center, - crossAxisAlignment: CrossAxisAlignment.center - ,children:[ - Expanded(flex: 1,child: Container(),), - Expanded(flex: 2,child: Image(image: AssetImage('images/empty.png'))), - Expanded(flex:2,child: Text("Add your first activity to access Summary",style: TextStyle(color: Colors.grey, fontStyle: FontStyle.italic),)) - ]), - ) :Expanded( - child: Column( - mainAxisSize: MainAxisSize.max, - children: [ - if(User.offline)Expanded(flex:1,child: Container(width:1000,color: Colors.red,child: Align(alignment: Alignment.center,child: Text("Offline")))), - Expanded( - child: SingleChildScrollView( - scrollDirection: Axis.vertical, - child: Column( + landscape ? navDrawer(context, 0) : Container(), + (User.activities.isEmpty) + ? Container( + width: 1000, + child: Column( + mainAxisSize: MainAxisSize.max, + mainAxisAlignment: MainAxisAlignment.center, + crossAxisAlignment: CrossAxisAlignment.center, children: [ - (false) - ? Container( - padding: EdgeInsets.all(20), - child: Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - mainAxisSize: MainAxisSize.max, - children: [ - Text("Good\nMorning!", style: TextStyle(fontSize: 23, fontStyle: FontStyle.italic)), - Text( - "12%", - style: TextStyle(fontSize: 30), - ), - Column( - children: [ - Text(DateFormat("yy - MM-dd").format(DateTime.now())), - Text(DateFormat("HH:mm").format(DateTime.now()), style: TextStyle(fontSize: 40)), - ], - ) - ], - ), - ) - : Container(), - //Ongoing activity card - (ongoingActName == "") ? Container(): - Container( - padding: EdgeInsets.all(10), - child: Card( - color: Colors.white12, - elevation: 20, - shadowColor: Colors.green, - child: Padding( - padding: const EdgeInsets.symmetric(horizontal: 25, vertical: 20), - child: Column( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: [ - Row( - children: [ - SpinKitPouringHourGlass(color: Colors.amber), - SizedBox(width: 20,), - Flexible(child: Text("You are engaged in '$ongoingActName' since ${DateFormat("hh:mm").format(ongoingActStime)}.", style: TextStyle(fontSize: 19),textAlign: TextAlign.center,)), - ], - ), - SizedBox(height: 10,), - Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: [ - Container( - child:Text(MinutesToTimeString(DateTime.now().difference(ongoingActStime).inMinutes)) - ), - Row( - mainAxisAlignment: MainAxisAlignment.end, - children: [ - InkWell( - onTap: (){ - Dialogs.ongoing(); - }, - child: Container( - decoration: BoxDecoration( - color: Colors.green, - borderRadius: BorderRadius.circular(10) - ), - child: Padding( - padding: EdgeInsets.symmetric(vertical: 8,horizontal: 15), - child:Text('Take Action') - ) - ) - ), - ], - ), - ], - ) - ], - ), - )), - ), - if(relativeTodos.isNotEmpty)Container( - padding: EdgeInsets.all(10), - child: Card( - color: Colors.white10, - elevation: 20, - shadowColor: Colors.black, - child: Padding( - padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 10), - child: Column( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: [ - Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: [ - Text('Close To-Do',style: TextStyle(fontSize: 16)), - MaterialButton(height: 30, - color: Colors.green, - onPressed: (){ - Navigator.of(context).pushNamed('/Todos'); - }, - child: Row( - children: [ - Text('More'), - Icon(Icons.keyboard_arrow_right) - ], - ), - - ) - ], - ), - LimitedBox( - maxHeight: 250, - child: ListView.builder( - shrinkWrap: true, - itemCount: relativeTodos.length, - itemBuilder: (context, index){ - return Container( - padding: EdgeInsets.all(10), - margin: EdgeInsets.symmetric(vertical: 2), - decoration: BoxDecoration( - color: Colors.black26, - borderRadius: BorderRadius.circular(10) - ), - child: Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: [ - SizedBox(width:MediaQuery.of(context).size.width * 0.7,child: Text('${relativeTodos[index].task!.name} -> ${relativeTodos[index].metadata}')), - Container( - padding: EdgeInsets.symmetric(horizontal: 5), - decoration: BoxDecoration(borderRadius: BorderRadius.circular(20), color: Colors.blue), - child: Text(DateFormat('MM/dd').format(relativeTodos[index].dueDate)) - ) - ], - ), - ); - }, - ), - ) - ], - ), - )), + Expanded( + flex: 1, + child: Container(), ), + Expanded( + flex: 2, + child: + Image(image: AssetImage('images/empty.png'))), + Expanded( + flex: 2, + child: Text( + "Add your first activity to access Summary", + style: TextStyle( + color: Colors.grey, + fontStyle: FontStyle.italic), + )) + ]), + ) + : Expanded( + child: Column( + mainAxisSize: MainAxisSize.max, + children: [ + if (User.offline) Container( - padding: EdgeInsets.all(10), - child: Card( - color: Colors.white10, - elevation: 20, - shadowColor: Colors.black, - child: Padding( - padding: const EdgeInsets.symmetric(horizontal: 25, vertical: 20), - child: Column( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: [ - Row( - mainAxisAlignment: MainAxisAlignment.spaceAround, - children: [ - Container(width:100,height: 150,child: CustomPaint(painter: HourglassPainter(hourglassTime, hourglassColors, hourglassStops),)), - Column( - children: [ - Text(DateFormat("MMMM-dd").format(DateTime.now()),style:TextStyle(fontSize: 18)), - Text(DateFormat("hh:mm a").format(DateTime.now()),style:TextStyle(fontSize: 40, fontWeight: FontWeight.bold)), - Container(height: 20,) - ], - ) - ], - ) - ], - ), - )), - ), - Container( - height: 400, - padding: EdgeInsets.all(10), - child: Card( - color: Colors.white10, - elevation: 20, - shadowColor: Colors.black, - child: Padding( - padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 20), - child: Column( - children: [ - Padding( - padding: const EdgeInsets.symmetric(horizontal: 10,vertical: 0), + child: Container( + width: 1000, + color: Colors.red, + child: Align( + alignment: Alignment.center, + child: Text("Offline")))), + Expanded( + child: SingleChildScrollView( + scrollDirection: Axis.vertical, + child: Column( + children: [ + (false) + ? Container( + padding: EdgeInsets.all(20), child: Row( + mainAxisAlignment: + MainAxisAlignment.spaceBetween, mainAxisSize: MainAxisSize.max, - mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ - Text("Productivity", style: TextStyle(color: Colors.green, fontWeight: FontWeight.bold)), - InkWell( - onTap: () async { - DateTimeRange? value = await showDateRangePicker(context: context, firstDate: firstDay ?? DateTime.now(), lastDate: lastDay ?? DateTime.now()); - if (value != null) { - prodRange = DateTimeRange(start: DateTime(value.start.year, value.start.month, value.start.day), end: DateTime(value.end.year,value.end.month,value.end.day,23,59,59)); - } - - LoadStats(); - }, - child: Text((prodRange != null) ? (DateFormat("MM/dd").format(prodRange!.start) + " - " + DateFormat("MM/dd").format(prodRange!.end)) : 'n/a'), + Text("Good\nMorning!", + style: TextStyle( + fontSize: 23, + fontStyle: + FontStyle.italic)), + Text( + "12%", + style: TextStyle(fontSize: 30), + ), + Column( + children: [ + Text(DateFormat("yy - MM-dd") + .format(DateTime.now())), + Text( + DateFormat("HH:mm") + .format(DateTime.now()), + style: TextStyle( + fontSize: 40)), + ], ) ], ), - ), - Divider(), - Row( - mainAxisSize: MainAxisSize.max, - mainAxisAlignment: MainAxisAlignment.spaceEvenly, - children: [ - Row( - children: [ - Text("Today : "), - Text("${(productivityData.length > 0) ? productivityData[0].productivity.toStringAsFixed(1) : 'n/a'}%", - style: TextStyle( - fontSize: 20, - color: (productivityData.length > 1) - ? ((productivityData[0].productivity > productivityData[1].productivity) ? Colors.lightGreenAccent : Colors.red) - : Colors.white)) - ], - ), - Row( - children: [ - Text("Yesterday : "), - Text("${(productivityData.length > 1) ? productivityData[1].productivity.toStringAsFixed(1) : 'n/a'}%", style: TextStyle(fontSize: 18)) - ], - ), - ], - ), - Expanded( - child: SfCartesianChart( - // Initialize category axis - primaryXAxis: CategoryAxis(), - series: >[ - LineSeries( - // Bind data source - markerSettings: MarkerSettings(isVisible: true, shape: DataMarkerType.circle), - dataSource: productivityData.reversed.toList(), - xValueMapper: (ProductivityMapData sales, _) => DateFormat('MM-dd').format(dFormat.parse(sales.day)), - yValueMapper: (ProductivityMapData sales, _) => sales.productivity, - dataLabelMapper: (ProductivityMapData sales, _) => sales.productivity.toStringAsFixed(1) + "%", - dataLabelSettings: DataLabelSettings(overflowMode: OverflowMode.hide, showZeroValue: false, isVisible: true), - onPointTap: (ChartPointDetails point){ - Dialogs.showJournalLink(dFormat.parse(productivityData[productivityData.length-point.pointIndex!-1].day)); - //showAlertDialog(context, productivityData[point.pointIndex!].day, "I'll show you detailed info about this day in future, When my master creates the feature"); - }, - pointColorMapper: (ProductivityMapData sales, _)=> (User.journalExists(dFormat.parse(sales.day)) ? Colors.lightGreenAccent : Colors.green) + ) + : Container(), + //Ongoing activity card + (ongoingActName == "") + ? Container() + : Container( + padding: EdgeInsets.all(10), + child: Card( + color: Colors.white12, + elevation: 20, + shadowColor: Colors.green, + child: Padding( + padding: + const EdgeInsets.symmetric( + horizontal: 25, + vertical: 20), + child: Column( + mainAxisAlignment: + MainAxisAlignment + .spaceBetween, + children: [ + Row( + children: [ + SpinKitPouringHourGlass( + color: Colors.amber), + SizedBox( + width: 20, + ), + Flexible( + child: Text( + "You are engaged in '$ongoingActName' since ${DateFormat("hh:mm").format(ongoingActStime)}.", + style: TextStyle( + fontSize: 19), + textAlign: + TextAlign.center, + )), + ], + ), + SizedBox( + height: 10, + ), + Row( + mainAxisAlignment: + MainAxisAlignment + .spaceBetween, + children: [ + Container( + child: Text(MinutesToTimeString( + DateTime.now() + .difference( + ongoingActStime) + .inMinutes))), + Row( + mainAxisAlignment: + MainAxisAlignment + .end, + children: [ + InkWell( + onTap: () { + Dialogs + .ongoing(); + }, + child: Container( + decoration: BoxDecoration( + color: Colors + .green, + borderRadius: + BorderRadius.circular( + 10)), + child: Padding( + padding: EdgeInsets.symmetric( + vertical: + 8, + horizontal: + 15), + child: Text( + 'Take Action')))), + ], + ), + ], + ) + ], ), - LineSeries( - // Bind data source - // dashArray: [0,0.5,1], - dashArray: [2,5], - markerSettings: MarkerSettings(isVisible: true, shape: DataMarkerType.circle), - dataSource: pastProductivityData.reversed.toList(), - xValueMapper: (ProductivityMapData sales, _) => DateFormat('MM-dd').format(dFormat.parse(sales.day)), - yValueMapper: (ProductivityMapData sales, _) => sales.productivity, - // dataLabelMapper: (ProductivityMapData sales, _) => sales.productivity.toStringAsFixed(1) + "%", - // dataLabelSettings: DataLabelSettings(overflowMode: OverflowMode.hide, showZeroValue: false, isVisible: true), - - color: Colors.grey - // pointColorMapper: (ProductivityMapData sales, _)=> (User.journalExists(dFormat.parse(sales.day)) ? Colors.lightGreenAccent : Colors.green) + )), + ), + if (relativeTodos.isNotEmpty) + Container( + padding: EdgeInsets.all(10), + child: Card( + color: Colors.white10, + elevation: 20, + shadowColor: Colors.black, + child: Padding( + padding: const EdgeInsets.symmetric( + horizontal: 20, vertical: 10), + child: Column( + mainAxisAlignment: + MainAxisAlignment.spaceBetween, + children: [ + Row( + mainAxisAlignment: + MainAxisAlignment + .spaceBetween, + children: [ + Text('Close To-Do', + style: TextStyle( + fontSize: 16)), + MaterialButton( + height: 30, + color: Colors.green, + onPressed: () { + Navigator.of(context) + .pushNamed('/Todos'); + }, + child: Row( + children: [ + Text('More'), + Icon(Icons + .keyboard_arrow_right) + ], + ), + ) + ], + ), + LimitedBox( + maxHeight: 250, + child: ListView.builder( + shrinkWrap: true, + itemCount: + relativeTodos.length, + itemBuilder: + (context, index) { + return Container( + padding: + EdgeInsets.all(10), + margin: + EdgeInsets.symmetric( + vertical: 2), + decoration: BoxDecoration( + color: Colors.black26, + borderRadius: + BorderRadius + .circular( + 10)), + child: Row( + mainAxisAlignment: + MainAxisAlignment + .spaceBetween, + children: [ + SizedBox( + width: MediaQuery.of( + context) + .size + .width * + 0.7, + child: Text( + '${relativeTodos[index].task!.name} -> ${relativeTodos[index].metadata}')), + Container( + padding: EdgeInsets + .symmetric( + horizontal: + 5), + decoration: BoxDecoration( + borderRadius: + BorderRadius + .circular( + 20), + color: Colors + .blue), + child: Text(DateFormat( + 'MM/dd') + .format(relativeTodos[ + index] + .dueDate))) + ], + ), + ); + }, + ), ) - //color: User.journalExists(dFormat.parse(productivityData[(productivityData.length-point.pointIndex!-1) as int].day)) ?Colors.green : Colors.red, - ]), - ), - Row( - mainAxisSize: MainAxisSize.max, - mainAxisAlignment: MainAxisAlignment.spaceEvenly, - children: [ - Row( - children: [ - Text("Average : "), - Text("${(productivityData.length > 0) ? avgProd.toStringAsFixed(1) : 'n/a'}%", - style: TextStyle( - fontSize: 18, - color: (avgProd > pastAvgProd) ? Colors.lightGreenAccent : Colors.red)) ], ), - Row( - children: [ - Text("Past Average : "), - Text("${(productivityData.length > 1) ? pastAvgProd.toStringAsFixed(1) : 'n/a'}%", style: TextStyle(fontSize: 18)) - ], - ), - ], - ), - SizedBox(height: 20,), - if(lastProductive!=null && DateTime.now().difference(lastProductive!).inMinutes > 60)RichText(text: TextSpan( - children: [ - TextSpan(text: "You haven't been productive in last",style: TextStyle(color:Colors.orange)), - TextSpan(text:" ${MinutesToTimeString(DateTime.now().difference(lastProductive!).inMinutes)}",style: TextStyle(color:Colors.redAccent,fontWeight: FontWeight.bold)) - ] - )) - - - ], + )), ), - )), - ), - Container( - height: 400, - padding: EdgeInsets.all(10), - child: Card( - color: Colors.white10, - elevation: 20, - shadowColor: Colors.black, - child: Padding( - padding: EdgeInsets.all(8), - child: (!days.isEmpty) - ? Column( + Container( + padding: EdgeInsets.all(10), + child: Card( + color: Colors.white10, + elevation: 20, + shadowColor: Colors.black, + child: Padding( + padding: const EdgeInsets.symmetric( + horizontal: 25, vertical: 20), + child: Column( + mainAxisAlignment: + MainAxisAlignment.spaceBetween, + children: [ + Row( + mainAxisAlignment: + MainAxisAlignment.spaceAround, children: [ - Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ - Padding(padding: EdgeInsets.all(20), child: Text('Daily Briefing', style: TextStyle(fontWeight: FontWeight.bold))), - dayPickerWidget(days, value: curDay, onChange: (_value) { - print('new val : $_value'); - curDay = _value; - setState(() { - LoadStats(); - }); - }), - ]), - Expanded( - child: SfCircularChart(legend: Legend(isVisible: true,position: LegendPosition.bottom,overflowMode: LegendItemOverflowMode.wrap), series: [ - // Render pie chart - PieSeries( - dataSource: dailyData, - pointColorMapper: (CatMapData data, _) => data.color, - xValueMapper: (CatMapData data, _) => data.name, - yValueMapper: (CatMapData data, _) => data.time, - dataLabelMapper: (CatMapData sales, _) => MinutesToTimeString(sales.time), - dataLabelSettings: DataLabelSettings(isVisible: true, useSeriesColor: true, overflowMode: OverflowMode.shift, showZeroValue: false)) - ])) + Container( + width: 100, + height: 150, + child: CustomPaint( + painter: HourglassPainter( + hourglassTime, + hourglassColors, + hourglassStops), + )), + Column( + children: [ + Text( + DateFormat("MMMM-dd") + .format( + DateTime.now()), + style: TextStyle( + fontSize: 18)), + Text( + DateFormat("hh:mm a") + .format( + DateTime.now()), + style: TextStyle( + fontSize: 40, + fontWeight: + FontWeight + .bold)), + Container( + height: 20, + ) + ], + ) ], ) - : Row(mainAxisSize: MainAxisSize.max, mainAxisAlignment: MainAxisAlignment.center, children: [CircularProgressIndicator()])))), - Container( - height: (taskTypesData.length * 45).clamp(350, 1000).toDouble(), - padding: EdgeInsets.all(10), - child: Card( - color: Colors.white10, - elevation: 20, - shadowColor: Colors.black, - child: Padding( - padding: const EdgeInsets.symmetric(horizontal: 25, vertical: 25), - child: Column(children: [ - Row(mainAxisSize: MainAxisSize.max, mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ - Text("Task Types", style: TextStyle(fontWeight: FontWeight.bold)), - InkWell( - onTap: () async { - DateTimeRange? value = await showDateRangePicker(context: context, firstDate: firstDay ?? DateTime.now(), lastDate: lastDay ?? DateTime.now()); - if (value != null) { - taskTypeRange = value; - } + ], + ), + )), + ), + Container( + height: 400, + padding: EdgeInsets.all(10), + child: Card( + color: Colors.white10, + elevation: 20, + shadowColor: Colors.black, + child: Padding( + padding: const EdgeInsets.symmetric( + horizontal: 10, vertical: 20), + child: Column( + children: [ + Padding( + padding: + const EdgeInsets.symmetric( + horizontal: 10, + vertical: 0), + child: Row( + mainAxisSize: MainAxisSize.max, + mainAxisAlignment: + MainAxisAlignment + .spaceBetween, + children: [ + Text("Productivity", + style: TextStyle( + color: Colors.green, + fontWeight: + FontWeight.bold)), + InkWell( + onTap: () async { + DateTimeRange? value = + await showDateRangePicker( + context: context, + firstDate: + firstDay ?? + DateTime + .now(), + lastDate: lastDay ?? + DateTime + .now()); + if (value != null) { + prodRange = + DateTimeRange( + start: DateTime( + value.start + .year, + value.start + .month, + value.start + .day), + end: DateTime( + value.end + .year, + value.end + .month, + value.end + .day, + 23, + 59, + 59)); + } - LoadStats(); - }, - child: Text((taskTypeRange != null) ? (DateFormat("MM/dd").format(taskTypeRange!.start) + " - " + DateFormat("MM/dd").format(taskTypeRange!.end)) : 'n/a'), - ) - ]), - Expanded( - // maxHeight: 300, - // maxWidth: 100, - child: SfCartesianChart(primaryXAxis: CategoryAxis(), - //primaryYAxis: NumericAxis(minimum: 0, maximum: 40, interval: 10), - series: >[ - BarSeries( - dataSource: taskTypesData, - xValueMapper: (TaskTypeMapData data, _) => data.task, - yValueMapper: (TaskTypeMapData data, _) => data.time / 60, - pointColorMapper: (TaskTypeMapData data, _) => data.color, - dataLabelMapper: (TaskTypeMapData data, _) => MinutesToTimeString(data.time), - dataLabelSettings: DataLabelSettings(isVisible: true), - color: Color.fromRGBO(8, 142, 255, 1)) - ]), - ) - ])))), - Container( - height: (catsData.length * 45).clamp(350, 1000).toDouble(), - padding: EdgeInsets.all(10), - child: Card( - color: Colors.white10, - elevation: 20, - shadowColor: Colors.black, - child: Padding( - padding: const EdgeInsets.symmetric(horizontal: 25, vertical: 25), - child: Column(children: [ - Row(mainAxisSize: MainAxisSize.max, mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ - Text("Categories", style: TextStyle(fontWeight: FontWeight.bold)), - InkWell( - onTap: () async { - DateTimeRange? value = await showDateRangePicker(context: context, firstDate: firstDay ?? DateTime.now(), lastDate: lastDay ?? DateTime.now()); - if (value != null) { - catsRange = value; - } + LoadStats(); + }, + child: Text((prodRange != + null) + ? (DateFormat("MM/dd") + .format( + prodRange! + .start) + + " - " + + DateFormat("MM/dd") + .format( + prodRange! + .end)) + : 'n/a'), + ) + ], + ), + ), + Divider(), + Row( + mainAxisSize: MainAxisSize.max, + mainAxisAlignment: + MainAxisAlignment.spaceEvenly, + children: [ + Row( + children: [ + Text("Today : "), + Text( + "${(productivityData.length > 0) ? productivityData[0].productivity.toStringAsFixed(1) : 'n/a'}%", + style: TextStyle( + fontSize: 20, + color: (productivityData + .length > + 1) + ? ((productivityData[ + 0] + .productivity > + productivityData[ + 1] + .productivity) + ? Colors + .lightGreenAccent + : Colors + .red) + : Colors.white)) + ], + ), + Row( + children: [ + Text("Yesterday : "), + Text( + "${(productivityData.length > 1) ? productivityData[1].productivity.toStringAsFixed(1) : 'n/a'}%", + style: TextStyle( + fontSize: 18)) + ], + ), + ], + ), + Expanded( + child: SfCartesianChart( + // Initialize category axis + primaryXAxis: CategoryAxis(), + series: < + LineSeries< + ProductivityMapData, + String>>[ + LineSeries< + ProductivityMapData, + String>( + // Bind data source + markerSettings: MarkerSettings( + isVisible: true, + shape: DataMarkerType + .circle), + dataSource: productivityData.reversed + .toList(), + xValueMapper: (ProductivityMapData sales, _) => + DateFormat('MM-dd') + .format(dFormat.parse( + sales.day)), + yValueMapper: (ProductivityMapData sales, _) => + sales.productivity, + dataLabelMapper: + (ProductivityMapData sales, _) => + sales.productivity.toStringAsFixed(1) + + "%", + dataLabelSettings: DataLabelSettings( + overflowMode: OverflowMode.hide, + showZeroValue: false, + isVisible: true), + onPointTap: (ChartPointDetails point) { + Dialogs.showJournalLink( + dFormat.parse(productivityData[ + productivityData + .length - + point + .pointIndex! - + 1] + .day)); + //showAlertDialog(context, productivityData[point.pointIndex!].day, "I'll show you detailed info about this day in future, When my master creates the feature"); + }, + pointColorMapper: (ProductivityMapData sales, _) => (User.journalExists(dFormat.parse(sales.day)) ? Colors.lightGreenAccent : Colors.green)), + LineSeries< + ProductivityMapData, + String>( + // Bind data source + // dashArray: [0,0.5,1], + dashArray: [2, 5], + markerSettings: + MarkerSettings( + isVisible: true, + shape: + DataMarkerType + .circle), + dataSource: + pastProductivityData + .reversed + .toList(), + xValueMapper: (ProductivityMapData sales, + _) => + DateFormat('MM-dd') + .format(dFormat.parse( + sales.day)), + yValueMapper: + (ProductivityMapData sales, + _) => + sales.productivity, + // dataLabelMapper: (ProductivityMapData sales, _) => sales.productivity.toStringAsFixed(1) + "%", + // dataLabelSettings: DataLabelSettings(overflowMode: OverflowMode.hide, showZeroValue: false, isVisible: true), - LoadStats(); - }, - child: Text((catsRange != null) ? (DateFormat("MM/dd").format(catsRange!.start) + " - " + DateFormat("MM/dd").format(catsRange!.end)) : 'n/a'), - ) - ]), - Expanded( - // maxHeight: 300, - // maxWidth: 100, - child: SfCartesianChart(primaryXAxis: CategoryAxis(), - //primaryYAxis: NumericAxis(minimum: 0, maximum: 40, interval: 10), - series: >[ - BarSeries( - dataSource: catsData, - xValueMapper: (CatMapData data, _) => data.name, - yValueMapper: (CatMapData data, _) => data.time / 60, - pointColorMapper: (CatMapData data, _) => data.color, - dataLabelMapper: (CatMapData data, _) => MinutesToTimeString(data.time), - dataLabelSettings: DataLabelSettings(isVisible: true), - color: Color.fromRGBO(8, 142, 255, 1)) - ]), - ) - ])))), - ], - ), + color: Colors.grey + // pointColorMapper: (ProductivityMapData sales, _)=> (User.journalExists(dFormat.parse(sales.day)) ? Colors.lightGreenAccent : Colors.green) + ) + //color: User.journalExists(dFormat.parse(productivityData[(productivityData.length-point.pointIndex!-1) as int].day)) ?Colors.green : Colors.red, + ]), + ), + Row( + mainAxisSize: MainAxisSize.max, + mainAxisAlignment: + MainAxisAlignment.spaceEvenly, + children: [ + Row( + children: [ + Text("Average : "), + Text( + "${(productivityData.length > 0) ? avgProd.toStringAsFixed(1) : 'n/a'}%", + style: TextStyle( + fontSize: 18, + color: (avgProd > + pastAvgProd) + ? Colors + .lightGreenAccent + : Colors.red)) + ], + ), + Row( + children: [ + Text("Past Average : "), + Text( + "${(productivityData.length > 1) ? pastAvgProd.toStringAsFixed(1) : 'n/a'}%", + style: TextStyle( + fontSize: 18)) + ], + ), + ], + ), + SizedBox( + height: 20, + ), + if (lastProductive != null && + DateTime.now() + .difference( + lastProductive!) + .inMinutes > + 60) + RichText( + text: TextSpan(children: < + TextSpan>[ + TextSpan( + text: + "You haven't been productive in last", + style: TextStyle( + color: Colors.orange)), + TextSpan( + text: + " ${MinutesToTimeString(DateTime.now().difference(lastProductive!).inMinutes)}", + style: TextStyle( + color: Colors.redAccent, + fontWeight: + FontWeight.bold)) + ])) + ], + ), + )), + ), + Container( + height: 400, + padding: EdgeInsets.all(10), + child: Card( + color: Colors.white10, + elevation: 20, + shadowColor: Colors.black, + child: Padding( + padding: EdgeInsets.all(8), + child: (!days.isEmpty) + ? Column( + children: [ + Row( + mainAxisAlignment: + MainAxisAlignment + .spaceBetween, + children: [ + Padding( + padding: + EdgeInsets + .all( + 20), + child: Text( + 'Daily Briefing', + style: TextStyle( + fontWeight: + FontWeight.bold))), + dayPickerWidget( + days, + value: curDay, + onChange: + (_value) { + print( + 'new val : $_value'); + curDay = _value; + setState(() { + LoadStats(); + }); + }), + ]), + Expanded( + child: SfCircularChart( + legend: Legend( + isVisible: + true, + position: + LegendPosition + .bottom, + overflowMode: + LegendItemOverflowMode + .wrap), + series: < + CircularSeries>[ + // Render pie chart + PieSeries( + dataSource: + dailyData, + pointColorMapper: (CatMapData data, _) => + data.color, + xValueMapper: (CatMapData data, _) => + data.name, + yValueMapper: (CatMapData data, _) => + data.time, + dataLabelMapper: + (CatMapData sales, + _) => + MinutesToTimeString(sales + .time), + dataLabelSettings: DataLabelSettings( + isVisible: + true, + useSeriesColor: + true, + overflowMode: + OverflowMode + .shift, + showZeroValue: + false)) + ])) + ], + ) + : Row( + mainAxisSize: + MainAxisSize.max, + mainAxisAlignment: + MainAxisAlignment + .center, + children: [ + CircularProgressIndicator() + ])))), + Container( + height: (taskTypesData.length * 45) + .clamp(350, 1000) + .toDouble(), + padding: EdgeInsets.all(10), + child: Card( + color: Colors.white10, + elevation: 20, + shadowColor: Colors.black, + child: Padding( + padding: const EdgeInsets.symmetric( + horizontal: 25, vertical: 25), + child: Column(children: [ + Row( + mainAxisSize: + MainAxisSize.max, + mainAxisAlignment: + MainAxisAlignment + .spaceBetween, + children: [ + Text("Task Types", + style: TextStyle( + fontWeight: + FontWeight + .bold)), + InkWell( + onTap: () async { + DateTimeRange? value = + await showDateRangePicker( + context: + context, + firstDate: + firstDay ?? + DateTime + .now(), + lastDate: lastDay ?? + DateTime + .now()); + if (value != null) { + taskTypeRange = value; + } + + LoadStats(); + }, + child: Text((taskTypeRange != + null) + ? (DateFormat("MM/dd") + .format( + taskTypeRange! + .start) + + " - " + + DateFormat( + "MM/dd") + .format( + taskTypeRange! + .end)) + : 'n/a'), + ) + ]), + Expanded( + // maxHeight: 300, + // maxWidth: 100, + child: SfCartesianChart( + primaryXAxis: + CategoryAxis(), + //primaryYAxis: NumericAxis(minimum: 0, maximum: 40, interval: 10), + series: < + ChartSeries< + TaskTypeMapData, + String>>[ + BarSeries( + dataSource: + taskTypesData, + xValueMapper: + (TaskTypeMapData data, _) => + data.task, + yValueMapper: (TaskTypeMapData data, _) => + data.time / 60, + pointColorMapper: + (TaskTypeMapData data, _) => + data.color, + dataLabelMapper: (TaskTypeMapData data, _) => + MinutesToTimeString( + data.time), + dataLabelSettings: + DataLabelSettings( + isVisible: + true), + color: Color.fromRGBO( + 8, 142, 255, 1)) + ]), + ) + ])))), + Container( + height: (catsData.length * 45) + .clamp(350, 1000) + .toDouble(), + padding: EdgeInsets.all(10), + child: Card( + color: Colors.white10, + elevation: 20, + shadowColor: Colors.black, + child: Padding( + padding: const EdgeInsets.symmetric( + horizontal: 25, vertical: 25), + child: Column(children: [ + Row( + mainAxisSize: + MainAxisSize.max, + mainAxisAlignment: + MainAxisAlignment + .spaceBetween, + children: [ + Text("Categories", + style: TextStyle( + fontWeight: + FontWeight + .bold)), + InkWell( + onTap: () async { + DateTimeRange? value = + await showDateRangePicker( + context: + context, + firstDate: + firstDay ?? + DateTime + .now(), + lastDate: lastDay ?? + DateTime + .now()); + if (value != null) { + catsRange = value; + } + + LoadStats(); + }, + child: Text((catsRange != + null) + ? (DateFormat("MM/dd") + .format( + catsRange! + .start) + + " - " + + DateFormat( + "MM/dd") + .format( + catsRange! + .end)) + : 'n/a'), + ) + ]), + Expanded( + // maxHeight: 300, + // maxWidth: 100, + child: SfCartesianChart( + primaryXAxis: + CategoryAxis(), + //primaryYAxis: NumericAxis(minimum: 0, maximum: 40, interval: 10), + series: < + ChartSeries>[ + BarSeries( + dataSource: catsData, + xValueMapper: + (CatMapData data, _) => + data.name, + yValueMapper: (CatMapData data, _) => + data.time / 60, + pointColorMapper: + (CatMapData data, _) => + data.color, + dataLabelMapper: (CatMapData data, _) => + MinutesToTimeString( + data.time), + dataLabelSettings: + DataLabelSettings( + isVisible: + true), + color: Color.fromRGBO( + 8, 142, 255, 1)) + ]), + ) + ])))), + ], + ), + ), + ), + ], ), ), - ], - ), - ), ], ), ), ); } - Widget dayPickerWidget(List list, {required String value, required Function(String value) onChange}) { + Widget dayPickerWidget(List list, + {required String value, required Function(String value) onChange}) { if (!list.contains(value)) { print("resetting"); onChange(list[0]); @@ -1073,7 +1530,8 @@ class _MyHomePageState extends State { child: Container( height: 40, width: 40, - child: Icon(Icons.arrow_back_ios, size: 18, color: (nextAvailable) ? Colors.white : Colors.grey), + child: Icon(Icons.arrow_back_ios, + size: 18, color: (nextAvailable) ? Colors.white : Colors.grey), ), ), Text( @@ -1088,7 +1546,9 @@ class _MyHomePageState extends State { child: Container( height: 40, width: 40, - child: Icon(Icons.arrow_forward_ios, size: 18, color: (prevAvailable) ? Colors.white : Colors.grey), + child: Icon(Icons.arrow_forward_ios, + size: 18, + color: (prevAvailable) ? Colors.white : Colors.grey), )) ], ); @@ -1110,8 +1570,13 @@ Drawer navDrawer(BuildContext context, int pageIndex) { children: [ Padding( padding: EdgeInsets.all(16), - child: Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ - Text("Time Tracker", style: TextStyle(fontSize: 25, color: Theme.of(context).accentColor, fontWeight: FontWeight.bold)), + child: + Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ + Text("Time Tracker", + style: TextStyle( + fontSize: 25, + color: Theme.of(context).accentColor, + fontWeight: FontWeight.bold)), Icon( Icons.more_time, size: 30, @@ -1121,7 +1586,8 @@ Drawer navDrawer(BuildContext context, int pageIndex) { ListTile( selected: (pageIndex == 0), title: Text('Summary'), - leading: Icon(Icons.article_outlined, color: Theme.of(context).primaryColor), + leading: + Icon(Icons.article_outlined, color: Theme.of(context).primaryColor), onTap: () { if (pageIndex == 0) { return; @@ -1167,7 +1633,8 @@ Drawer navDrawer(BuildContext context, int pageIndex) { ListTile( selected: (pageIndex == 4), title: Text('Categories'), - leading: Icon(Icons.account_tree_outlined, color: Theme.of(context).primaryColor), + leading: Icon(Icons.account_tree_outlined, + color: Theme.of(context).primaryColor), onTap: () { if (pageIndex == 4) { return; @@ -1179,7 +1646,8 @@ Drawer navDrawer(BuildContext context, int pageIndex) { ListTile( selected: (pageIndex == 7), title: Text('Projects'), - leading: FaIcon(FontAwesomeIcons.rocket, color: Theme.of(context).primaryColor), + leading: FaIcon(FontAwesomeIcons.rocket, + color: Theme.of(context).primaryColor), onTap: () { if (pageIndex == 7) { return; @@ -1190,7 +1658,8 @@ Drawer navDrawer(BuildContext context, int pageIndex) { ListTile( selected: (pageIndex == 9), title: Text('To-Do'), - leading: FaIcon(FontAwesomeIcons.calendarCheck, color: Theme.of(context).primaryColor), + leading: FaIcon(FontAwesomeIcons.calendarCheck, + color: Theme.of(context).primaryColor), onTap: () { if (pageIndex == 9) { return; @@ -1201,7 +1670,8 @@ Drawer navDrawer(BuildContext context, int pageIndex) { ListTile( selected: (pageIndex == 8), title: Text('Journal'), - leading: FaIcon(FontAwesomeIcons.bookJournalWhills, color: Theme.of(context).primaryColor), + leading: FaIcon(FontAwesomeIcons.bookJournalWhills, + color: Theme.of(context).primaryColor), onTap: () { if (pageIndex == 8) { return; diff --git a/lib/splash.dart b/lib/splash.dart index 86ff2eb..dc19894 100644 --- a/lib/splash.dart +++ b/lib/splash.dart @@ -1,8 +1,10 @@ +import 'package:app_usage/app_usage.dart'; import 'package:flutter/material.dart'; import 'package:flutter_local_notifications/flutter_local_notifications.dart'; import 'package:flutter_spinkit/flutter_spinkit.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'package:tasktracker/Data.dart'; +import 'DebugHelper.dart'; import 'User.dart' as Users; import 'package:http/http.dart' as http; import 'theme_provider.dart'; @@ -18,18 +20,19 @@ class SplashScreen extends StatefulWidget { } class _SplashScreenState extends State { - Future initSettings() async{ + Future initSettings() async { final prefs = await SharedPreferences.getInstance(); bool value = true; - if(prefs.containsKey("theme")){ - value = ((await prefs.getInt("theme"))==0); - }else{ + if (prefs.containsKey("theme")) { + value = ((await prefs.getInt("theme")) == 0); + } else { await prefs.setInt("theme", 0); } print('Dark theme is : $value'); final provider = Provider.of(context, listen: false); provider.toggleTheme(value); } + @override void initState() { // TODO: implement initState @@ -38,14 +41,16 @@ class _SplashScreenState extends State { NotificationManager.RescheduleNotifications(); } - void notificationSelected(String? payload) { - if(payload!=null){ - if(payload.toLowerCase().contains("activity")){ - Navigator.of(context).push(MaterialPageRoute(builder: (context) => NewActivity())).then((value) => {Users.refreshUserData()}); + if (payload != null) { + if (payload.toLowerCase().contains("activity")) { + Navigator.of(context) + .push(MaterialPageRoute(builder: (context) => NewActivity())) + .then((value) => {Users.refreshUserData()}); } } } + void init() async { await initSettings(); final prefs = await SharedPreferences.getInstance(); @@ -53,25 +58,29 @@ class _SplashScreenState extends State { // print(loginResponse.body); if (!prefs.containsKey("password") || !prefs.containsKey("username")) { - Navigator.of(context).pushNamedAndRemoveUntil('/welcome', (route) => false); + Navigator.of(context) + .pushNamedAndRemoveUntil('/welcome', (route) => false); } else { try { http.Response loginResponse = await Users.login( prefs.getString("username") ?? '', prefs.getString("password") ?? ''); print(loginResponse.body); - if (loginResponse.body.toLowerCase().contains("success")) { //Login Success + if (loginResponse.body.toLowerCase().contains("success")) { + //Login Success Continue(); - } else { //Login Failed + } else { + //Login Failed LoginFailed(); } - } catch (error) { //Login Failed + } catch (error) { + //Login Failed LoginFailed(); } } } - void LoginFailed() async{ + void LoginFailed() async { bool dbExist = await Users.cacheDbExist(); if (dbExist) { print('cache Database exists, Lets go CACHE!'); @@ -81,7 +90,7 @@ class _SplashScreenState extends State { } } - void Continue() async{ + void Continue() async { await Users.initUserData(); Navigator.of(context).pushReplacementNamed('/home'); print('Going home!'); @@ -91,9 +100,12 @@ class _SplashScreenState extends State { Widget build(BuildContext context) { return Container( decoration: BoxDecoration( - gradient: LinearGradient(colors: [Colors.lightBlue, Colors.blue],stops: [0,1],begin: Alignment.topLeft, end: Alignment.bottomRight) - ), - // color: Colors.redAccent, + gradient: LinearGradient( + colors: [Colors.lightBlue, Colors.blue], + stops: [0, 1], + begin: Alignment.topLeft, + end: Alignment.bottomRight)), + // color: Colors.redAccent, padding: EdgeInsets.all(80), child: Column( mainAxisSize: MainAxisSize.max, @@ -106,11 +118,15 @@ class _SplashScreenState extends State { SpinKitPouringHourGlass(color: Colors.white), ], ), - DefaultTextStyle(style: TextStyle(fontSize: 15,color: Colors.white,fontStyle: FontStyle.italic), - child: Text('If you lie to me, That means you lie to yourself\n\n -This app (2022)',)) + DefaultTextStyle( + style: TextStyle( + fontSize: 15, + color: Colors.white, + fontStyle: FontStyle.italic), + child: Text( + 'If you lie to me, That means you lie to yourself\n\n -This app (2022)', + )) // Text('Loading', style:TextStyle(color: Colors.grey, fontSize: 20,fontStyle: FontStyle.italic)) ])); } - - } diff --git a/pubspec.lock b/pubspec.lock index 69e2f7a..fa7f915 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -1,6 +1,13 @@ # Generated by pub # See https://dart.dev/tools/pub/glossary#lockfile packages: + app_usage: + dependency: "direct main" + description: + name: app_usage + url: "https://pub.dartlang.org" + source: hosted + version: "2.1.1" args: dependency: transitive description: diff --git a/pubspec.yaml b/pubspec.yaml index 951b3b3..4863c14 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -55,6 +55,7 @@ dependencies: google_sign_in: ^5.2.3 font_awesome_flutter: ^10.0.0 restart_app: ^1.1.0 + app_usage: ^2.1.1 dev_dependencies: flutter_test: