Todo editing

This commit is contained in:
Sewmina
2022-04-05 06:52:58 +05:30
parent b7ce14a558
commit 7aa8712c16
7 changed files with 95 additions and 20 deletions

View File

@@ -37,6 +37,10 @@ class TaskType{
static String colName="name"; static String colName="name";
static String colCategory = "category_id"; static String colCategory = "category_id";
static String colRelatedProject = "related_project"; static String colRelatedProject = "related_project";
static String getDisplayName(TaskType taskType){
return (taskType.name + ((taskType.relatedProject != null) ? ' [${taskType.relatedProject!.name}]' : ''));
}
} }
class Activity{ class Activity{

View File

@@ -17,7 +17,7 @@ class Debug{
static void Log(Object? msg){ static void Log(Object? msg){
if(!enableErrorLoggin) {return;} if(!enableErrorLoggin) {return;}
print('\x1B[0m$msg'); print('\x1B[36m$msg\x1B[0m');
} }
} }

View File

@@ -6,6 +6,7 @@ import 'package:intl/intl.dart';
import 'package:tasktracker/NewTask.dart'; import 'package:tasktracker/NewTask.dart';
import 'package:tasktracker/NotificationsManager.dart'; import 'package:tasktracker/NotificationsManager.dart';
import 'Data.dart'; import 'Data.dart';
import 'DebugHelper.dart';
import 'Dialogs.dart'; import 'Dialogs.dart';
import 'User.dart' as User; import 'User.dart' as User;
@@ -14,19 +15,21 @@ DateFormat dateTimeFormat = DateFormat("yyyy-MM-dd HH:mm");
DateFormat durationFormat = DateFormat("HH:mm:ss"); DateFormat durationFormat = DateFormat("HH:mm:ss");
class NewTodo extends StatefulWidget { class NewTodo extends StatefulWidget {
NewTodo({Key? key, this.selectedTask, this.metadata, this.dueDate,this.notificationTime}) : super(key: key); NewTodo({Key? key, this.selectedTask, this.metadata, this.dueDate,this.notificationTime, this.old_id}) : super(key: key);
late String? old_id;
late String? metadata; late String? metadata;
late String? selectedTask; late String? selectedTask;
late DateTime? dueDate; late DateTime? dueDate;
late DateTime? notificationTime; late DateTime? notificationTime;
@override @override
_NewActivity createState() => _NewActivity(selectedCat: selectedTask, metadata: metadata); _NewActivity createState() => _NewActivity(selectedCat: selectedTask, metadata: metadata, DueDate: dueDate, notificationTime: notificationTime,oldId: old_id);
} }
class _NewActivity extends State<NewTodo> { class _NewActivity extends State<NewTodo> {
late String init_selectedTask; late String init_selectedTask;
_NewActivity({String? metadata, String? selectedCat, DateTime? DueDate, this.notificationTime}) { _NewActivity({String? metadata, String? selectedCat, DateTime? DueDate, this.notificationTime, this.oldId}) {
editing =selectedCat != null && DueDate !=null; Debug.Log('selected cat : $selectedCat');
editing =selectedCat != null && DueDate !=null && metadata !=null && oldId!=null;
dueDate = DueDate ?? DateTime.now().add(Duration(days: 1)); dueDate = DueDate ?? DateTime.now().add(Duration(days: 1));
this.metadataController.text = metadata ?? ""; this.metadataController.text = metadata ?? "";
if(this.metadataController.text.contains('[') && this.metadataController.text.contains(']') ){ if(this.metadataController.text.contains('[') && this.metadataController.text.contains(']') ){
@@ -36,7 +39,7 @@ class _NewActivity extends State<NewTodo> {
selectedStep='None'; selectedStep='None';
} }
this.init_selectedTask = this.selectedCat = selectedCat ?? User.taskTypes[0].name; this.init_selectedTask = this.selectedCat = selectedCat ?? User.taskTypes[0].name;
print(" meta:$metadata, task: $selectedCat"); Debug.Log(" meta:$metadata, task: $selectedCat, notification_time : ${notificationTime}");
} }
TextEditingController metadataController = TextEditingController(); TextEditingController metadataController = TextEditingController();
@@ -45,6 +48,7 @@ class _NewActivity extends State<NewTodo> {
DateTime? notificationTime; DateTime? notificationTime;
bool editing = false; bool editing = false;
String? oldId;
Map<String, TaskType?> taskTypes = <String, TaskType?>{}; Map<String, TaskType?> taskTypes = <String, TaskType?>{};
Map<String, TaskType?> getActivities() { Map<String, TaskType?> getActivities() {
Map<String, TaskType?> _cats = <String, TaskType?>{}; Map<String, TaskType?> _cats = <String, TaskType?>{};
@@ -57,7 +61,7 @@ class _NewActivity extends State<NewTodo> {
String name = element.name; String name = element.name;
if (_cats.keys.toString().contains(element.name)) { if (_cats.keys.toString().contains(element.name)) {
} else { } else {
String displayName = (name + ((element.relatedProject != null) ? ' [${element.relatedProject!.name}]' : '')); String displayName = TaskType.getDisplayName(element);
_cats.putIfAbsent(displayName, () => element); _cats.putIfAbsent(displayName, () => element);
} }
}); });
@@ -298,7 +302,13 @@ class _NewActivity extends State<NewTodo> {
} }
void edit_action() async { void edit_action() async {
if(metadataController.text.isEmpty){
Dialogs.showAlertDialog(context, 'Invalid data', 'Please enter description to add new todo');
return;
}
await User.UserOperations.editTodo(oldId!,selectedCat,((selectedStep!=null && selectedStep != 'None') ? '[$selectedStep]' : '')+ metadataController.text, dueDate, notificationTime);
Navigator.of(context).pop();
} }
} }

View File

@@ -5,6 +5,7 @@ import 'package:intl/intl.dart';
import 'package:shared_preferences/shared_preferences.dart'; import 'package:shared_preferences/shared_preferences.dart';
import 'Data.dart'; import 'Data.dart';
import 'DebugHelper.dart';
import 'Dialogs.dart'; import 'Dialogs.dart';
import 'User.dart' as User; import 'User.dart' as User;
@@ -25,6 +26,7 @@ class NotificationManager{
fltrNotification.initialize(initilizationsSettings, onSelectNotification: notificationSelected); fltrNotification.initialize(initilizationsSettings, onSelectNotification: notificationSelected);
await fltrNotification.cancel(0); await fltrNotification.cancel(0);
await fltrNotification.cancel(2);
int notification_interval = await Settings.getNotificationInterval(); int notification_interval = await Settings.getNotificationInterval();
bool adaptive_notification = await Settings.getAdaptiveNotification(); bool adaptive_notification = await Settings.getAdaptiveNotification();
@@ -68,6 +70,16 @@ class NotificationManager{
fltrNotification.cancel(1); fltrNotification.cancel(1);
} }
User.todos.forEach((element) {
if(element.notificationTime!=null){
if(element.notificationTime!.isAfter(DateTime.now())){
fltrNotification.schedule(2, "Time for ${element.task!.name}", "${element.metadata}", element.notificationTime, generalNotificationDetails);
}
}
});
if(adaptive_notification && adaptive_notification_availabel){ if(adaptive_notification && adaptive_notification_availabel){
print("Smart!, Using adaptive huh?"); print("Smart!, Using adaptive huh?");
//Calculate you little thing! CALCULATE!' //Calculate you little thing! CALCULATE!'
@@ -110,20 +122,20 @@ class NotificationManager{
} }
} }
} }
print("Time Map : ${timeMap.length}"); Debug.LogResponse("${timeMap.length}",src:'Time Map');
print(timeMap); Debug.LogResponse(timeMap);
timeMap.forEach((key, value) { timeMap.forEach((key, value) {
DateTime now = DateTime.now(); DateTime now = DateTime.now();
DateTime todayStart = DateTime(now.year,now.month,now.day,0,0,0); DateTime todayStart = DateTime(now.year,now.month,now.day,0,0,0);
DateTime thisTime = todayStart.add(Duration(minutes: key)); DateTime thisTime = todayStart.add(Duration(minutes: key));
if(value.length < (totalDays.clamp(0, 30) / 3).ceil()){ if(value.length < (totalDays.clamp(0, 30) / 3).ceil()){
print("${timeFormat.format(thisTime)} this happened only ${value.length} times, Ignoring..."); Debug.Log("${timeFormat.format(thisTime)} this happened only ${value.length} times, Ignoring...");
}else { }else {
print(timeFormat.format(thisTime)); Debug.Log(timeFormat.format(thisTime));
if(thisTime.isBefore(DateTime.now())) { if(thisTime.isBefore(DateTime.now())) {
thisTime = thisTime.add(Duration(days: 1)); thisTime = thisTime.add(Duration(days: 1));
} }
print("Scheduling at $thisTime"); Debug.LogResponse("Scheduling at $thisTime");
fltrNotification.schedule(0, "Don't forget to add new activity", "Adaptive notifications suggests that you may have done by now to track.", thisTime, generalNotificationDetails); fltrNotification.schedule(0, "Don't forget to add new activity", "Adaptive notifications suggests that you may have done by now to track.", thisTime, generalNotificationDetails);
} }
@@ -131,18 +143,18 @@ class NotificationManager{
}else if(notification_interval>0) { }else if(notification_interval>0) {
var scheduledTime = DateTime.now().add(Duration(hours: notification_interval)); var scheduledTime = DateTime.now().add(Duration(hours: notification_interval));
fltrNotification.schedule(1, "What did you do in last $notification_interval hours?", "Click here to track your last activities...", fltrNotification.schedule(0, "What did you do in last $notification_interval hours?", "Click here to track your last activities...",
scheduledTime, generalNotificationDetails,); scheduledTime, generalNotificationDetails,);
print("Sent notification schedule"); print("Sent notification schedule");
} }
await Future.delayed(Duration(seconds: 2)); await Future.delayed(Duration(seconds: 2));
try{ final List<PendingNotificationRequest> pendingNotificationRequests =await fltrNotification.pendingNotificationRequests(); try{ final List<PendingNotificationRequest> pendingNotificationRequests =await fltrNotification.pendingNotificationRequests();
print("Notifications"); Debug.LogResponse("Notifications");
pendingNotificationRequests.forEach((element) { pendingNotificationRequests.forEach((element) {
print("${element.id} : ${element.title} -> ${element.body} \n payload:${element.payload}"); Debug.LogResponse("${element.id} : ${element.title} -> ${element.body} \n payload:${element.payload}");
});}catch(e){ });}catch(e){
print("Error printing notifications \n $e"); Debug.LogError("Error printing notifications \n $e");
} }
} }

View File

@@ -9,6 +9,7 @@ import 'package:tasktracker/NewJournal.dart';
import 'package:tasktracker/NewTodo.dart'; import 'package:tasktracker/NewTodo.dart';
import 'package:tasktracker/main.dart'; import 'package:tasktracker/main.dart';
import 'Data.dart'; import 'Data.dart';
import 'DebugHelper.dart';
import 'User.dart' as User; import 'User.dart' as User;
import 'Dialogs.dart'; import 'Dialogs.dart';
@@ -366,9 +367,10 @@ class _TodosPageState extends State<TodosPage> {
if (selecting) if (selecting)
InkWell( InkWell(
onTap: () { onTap: () {
// Navigator.of(context).push(MaterialPageRoute(builder: (context) => NewJournal(date: todo.day, title: todo.title, text: todo.description,))).then((val) { Debug.Log('notification : ${todo.notificationTime}');
// setState(() {}); Navigator.of(context).push(MaterialPageRoute(builder: (context) =>NewTodo(selectedTask: TaskType.getDisplayName(todo.task!), metadata: todo.metadata, dueDate: todo.dueDate, notificationTime: todo.notificationTime, old_id: todo.id,))).then((val) {
// }); setState(() {});
});
selecting = false; selecting = false;
setState(() {}); setState(() {});
}, },

View File

@@ -1595,6 +1595,53 @@ class UserOperations {
await executeQueries(); await executeQueries();
} }
static Future<void> editTodo(String oldId, String taskType, String metadata, DateTime dueDate, DateTime? notificationTime) async {
String taskId = username + taskType;
if(taskId.contains('[') && taskId.contains(']')){
//has a project related
taskId = taskId.substring(0, taskId.indexOf('[') - 1);
}
String id = taskId + metadata;
Map<String, String> queryBody = <String, String>{
'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 (cacheEnabled) {
//Add Query
Map<String, Object> query = {Queries.colLink: 'edit_todo', Queries.colData: 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<String, Object> 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));
Debug.LogResponse("Query executed : Results{${queryResponse.body}");
if (queryResponse.body.toLowerCase().contains("success")) {
//Success
}
} catch (e) {
Debug.LogError('NC: Error editing todo entry $e}');
}
//executeQueries();
}
//Add to server and refresh Cache
await executeQueries();
}
static Future<void> deleteTask(String name, {bulk = false}) async { static Future<void> deleteTask(String name, {bulk = false}) async {
Map<String, String> queryBody = <String, String>{ Map<String, String> queryBody = <String, String>{

View File

@@ -740,7 +740,7 @@ class _MyHomePageState extends State<MyHomePage> {
dataLabelMapper: (ProductivityMapData sales, _) => sales.productivity.toStringAsFixed(1) + "%", dataLabelMapper: (ProductivityMapData sales, _) => sales.productivity.toStringAsFixed(1) + "%",
dataLabelSettings: DataLabelSettings(overflowMode: OverflowMode.hide, showZeroValue: false, isVisible: true), dataLabelSettings: DataLabelSettings(overflowMode: OverflowMode.hide, showZeroValue: false, isVisible: true),
onPointTap: (ChartPointDetails point){ onPointTap: (ChartPointDetails point){
Dialogs.showJournalLink(dFormat.parse(productivityData[productivityData.length-point.pointIndex!].day)); 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"); //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) pointColorMapper: (ProductivityMapData sales, _)=> (User.journalExists(dFormat.parse(sales.day)) ? Colors.lightGreenAccent : Colors.green)