Projects add and view -> online

This commit is contained in:
Sewmina
2022-03-19 02:45:43 +05:30
parent c2b5656eb3
commit f04e82c5ca
4 changed files with 159 additions and 23 deletions

View File

@@ -5,6 +5,7 @@ import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:flutter/cupertino.dart';
import 'package:intl/intl.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:tasktracker/NewProject.dart';
import 'package:tasktracker/NotificationsManager.dart';
import 'main.dart';
import 'package:http/http.dart' as http;
@@ -27,6 +28,8 @@ late String username;
List<Category> categories = [];
List<TaskType> taskTypes = [];
List<Activity> activities = [];
List<Project> projects = [];
bool offline = true;
bool registered = false;
StreamController<bool> refreshStream = StreamController<bool>();
@@ -81,6 +84,7 @@ Future<void> refreshUserData() async {
await updateCatsList();
await updateTasksList();
await updateActList();
await updateProjectsList();
refreshStream.add(false);
if (cacheEnabled) {
NotificationManager.RescheduleNotifications();
@@ -98,26 +102,21 @@ Future<bool> cacheDbExist() async {
}
Future<void> updateCatsList() async {
//print('Updating with localCache');
// categories = await GetCategories(true);
print('Checking if can refresh');
categories = await GetCategories(false);
}
Future<void> updateTasksList() async {
// print('Updating with localCache');
// taskTypes = await GetTaskTypes(true);
print('Checking if can refresh');
taskTypes = await GetTaskTypes(false);
}
Future<void> updateActList() async {
//print('Updating with localCache');
//activities = await GetActivities(true);
print('Checking if can refresh');
activities = await GetActivities(false);
}
Future<void> updateProjectsList() async{
projects = await GetProjects(false);
}
Future<void> initCacheDatabase() async {
Directory directory = await getApplicationDocumentsDirectory();
print('database at ' + directory.path + 'cache.db');
@@ -151,6 +150,7 @@ void onCacheDatabaseCreate(Database db, int newVersion) async {
String ProjectsTableSQL =
'CREATE TABLE Projects(id TEXT PRIMARY KEY, ${Project.colName} TEXT, ${Project.colCat} TEXT, ${Project.colSteps} TEXT, ${Project.colDeadline} DATETIME)';
await db.execute(ProjectsTableSQL);
String QueriesTableSQL = 'CREATE TABLE Queries(id INTEGER PRIMARY KEY AUTOINCREMENT, ${Queries.colLink} TEXT,${Queries.colData} TEXT)';
// print(QueriesTableSQL);
await db.execute(QueriesTableSQL);
@@ -519,6 +519,123 @@ Future<void> UpdateActivitiesFromServer() async {
}
}
Future<List<Project>> GetProjects(bool forceOffline) async {
if (cacheEnabled) {
List<Project> _projects = [];
if (offline || forceOffline) {
//Retreive from cacheDB
print('offline, refreshing projects');
} else {
//Check if server got updated, If not go for cache
var android_id = await Settings.UUID();
bool updated = false;
print("Need to update activities : ${!updated}");
//Update CacheDB
if (!updated) {
await UpdateProjectsFromServer();
}
}
List<Map> cats = await cacheDb.rawQuery('SELECT * FROM Projects');
print(cats.length);
for (Map element in cats) {
String? name = element[Project.colName];
String? category = element[Project.colCat];
String? stepsJson = element[Project.colSteps];
String? deadline = element[Project.colDeadline];
if (name == null || category == null || stepsJson == null || deadline == null) {
print("Something is null!\nname:${name == null}, cat:${category == null}, steps:${stepsJson == null}, deadline${deadline == null}");
print("TaskType:{$name}, Start Time:{$category}, endTime:{$stepsJson}, metadata:${deadline}");
continue;
}
Category? cat = await getCatFromId(category);
if(cat==null){print('couldnt find cat');continue;}
print('steps : $stepsJson');
List<dynamic> _steps = jsonDecode(stepsJson);
List<ProjectStep> steps = [];
_steps.forEach((element) {
ProjectStep step = ProjectStep.fromJson(element);
steps.add(step);
print(element);
});
// print(steps);
_projects.add(Project(name.replaceAll(username, ""),category,steps,DateTime.parse(deadline)));
}
projects = _projects;
} else {
print("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: <String, String>{"username": username, "device_id": await Settings.UUID()}));
print("Activity response: ${response.body}");
List<Project> _projects = [];
if (response.body.contains("{")) {
List<String> data = response.body.split("<td>");
for (var value in data) {
Map<String, dynamic> cat = jsonDecode(value);
int? id = cat['id'];
String? type = cat['task_id'].toString();
String? startTime = cat['sTime'].toString();
String? endTime = cat['eTime'].toString();
String? metadata = cat['metadata'];
TaskType? taskType = await getTaskFromId(type);
if (taskType == null) {
print('null found');
continue;
}
}
projects = _projects;
} else {
print("No activities for now");
}
} catch (e) {
print("Error : $e @ updating activities");
print("Error while acts $e");
}
}
return projects;
}
Future<void> UpdateProjectsFromServer() async {
print("Updating Projects as $username");
try {
http.Response response = (await http.post(Uri.parse('http://161.97.127.136/task_tracker/get_projects.php'),
body: <String, String>{"username": username, "device_id": await Settings.UUID()}));
await cacheDb.rawDelete("DELETE FROM Projects");
print('Truncate Projects Table before');
print("Projects response: ${response.body}");
if (response.body.contains("{")) {
List<String> data = response.body.split("<td>");
for (var value in data) {
Map<String, dynamic> cat = jsonDecode(value);
print('project data');
print(cat);
await cacheDb.rawInsert(
"INSERT OR REPLACE INTO Projects (${Project.colName}, ${Project.colCat}, ${Project.colSteps}, ${Project.colDeadline}) "
"VALUES ('${cat['name']}', '${cat['category']}', '${cat['steps']}', '${cat['deadline']}')");
}
} else {
print("No activities for now");
}
} catch (e) {
print("Error : $e @ updating activities");
print("Error while acts $e");
}
}
Future<TaskType?> getTaskFromId(String taskId) async {
// await GetTaskTypes(false);
TaskType? cat = null;
@@ -766,9 +883,9 @@ class UserOperations {
'name': username + name,
'username': username,
'device_id': await Settings.UUID(),
'category': username + category,
'category_id': username + category,
'steps': jsonEncode(steps),
'deadline': DateFormat("yyyy-mm-dd").format(deadline)
'deadline': DateFormat("yyyy-MM-dd").format(deadline)
};
if (cacheEnabled) {
@@ -780,7 +897,7 @@ class UserOperations {
await cacheDb.insert('Queries', query);
//update Cache
Map<String, Object> data = {};
Map<String, Object> data = {Project.colName: username+name, Project.colCat: category, Project.colSteps: jsonEncode(steps), Project.colDeadline: deadline.toString()};
await cacheDb.insert('Projects', data);
await refreshUserData();
} else {