toado 0.12.5

A simple interactive task and project manager for the command line
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
use crate::config;

use super::*;

/// Creates a new task in a toado server with provided arguments. Prompts the user to input any task
/// information not provided in the arguments.
///
/// # Errors
/// Will return an error if any of the user input prompts fail, or if the creation of the task
/// fails.
pub fn create_task(
    args: flags::AddArgs,
    app: toado::Server,
) -> Result<(i64, String), toado::Error> {
    let theme = get_input_theme();

    let name = option_or_input(
        args.name,
        dialoguer::Input::with_theme(&theme)
            .with_prompt("Name")
            .validate_with(|input: &String| validate_name(input)),
    )?;

    let priority = option_or_input(
        args.item_priority,
        dialoguer::Input::with_theme(&theme)
            .with_prompt("Priority")
            .default(0),
    )?;

    let start_time = if args.optional {
        None
    } else {
        option_or_input_option(
            args.start_time,
            dialoguer::Input::with_theme(&theme).with_prompt("Start Time (optional)"),
        )?
    };

    let end_time = if args.optional {
        None
    } else {
        option_or_input_option(
            args.end_time,
            dialoguer::Input::with_theme(&theme).with_prompt("End Time (optional)"),
        )?
    };

    let repeat = if args.optional {
        None
    } else {
        option_or_input_option(
            args.repeat,
            dialoguer::Input::with_theme(&theme).with_prompt("Repeats (optional)"),
        )?
    };

    let notes = if args.optional {
        None
    } else {
        option_or_input_option(
            args.notes,
            dialoguer::Input::with_theme(&theme).with_prompt("Notes (optional)"),
        )?
    };

    let task_id = app.add_task(toado::AddTaskArgs {
        name: String::from(&name),
        priority,
        status: toado::ItemStatus::Incomplete,
        start_time,
        end_time,
        repeat,
        notes,
    })?;

    Ok((task_id, name))
}

/// Deletes a task in a toado server database. Searches for task to delete with given search term,
/// or prompts user for search term if one is not provided
///
/// # Errors
///
/// Will return an error if user input fails, if deletion operation fails, or if no tasks are
/// deleted
pub fn delete_task(
    args: flags::DeleteArgs,
    app: toado::Server,
    config: &config::Config,
) -> Result<Option<i64>, toado::Error> {
    let theme = dialoguer::theme::ColorfulTheme::default();

    let search_term = option_or_input(
        args.term,
        dialoguer::Input::with_theme(&theme).with_prompt("Task name"),
    )?;

    let task = prompt_task_selection(
        &app,
        search_term,
        toado::QueryCols::Some(vec!["id", "name", "priority", "status"]),
        &theme,
        config,
    )?;

    // Get selected task id
    let id = match task.id {
        Some(id) => id,
        None => return Err(Into::into("task id should exist")),
    };

    let affected_rows = app.delete_task(Some(
        toado::QueryConditions::Equal {
            col: "id",
            value: id,
        }
        .to_string(),
    ))?;

    if affected_rows >= 1 {
        Ok(Some(id))
    } else {
        Err(Into::into("no tasks deleted"))
    }
}

/// Update a task in a toado server
///
/// # Errors
///
/// Will return an error if user input fails, if task updating fails, or if no task is updated
pub fn update_task(
    args: flags::UpdateArgs,
    app: toado::Server,
    config: &config::Config,
) -> Result<u64, toado::Error> {
    let theme = dialoguer::theme::ColorfulTheme::default();

    let search_term = option_or_input(
        args.term.clone(),
        dialoguer::Input::with_theme(&theme).with_prompt("Task name"),
    )?;

    let task = prompt_task_selection(
        &app,
        search_term,
        toado::QueryCols::Some(vec!["id", "name", "priority", "status"]),
        &theme,
        config,
    )?;

    // Get selected task id
    let task_id = match task.id {
        Some(id) => id,
        None => return Err(Into::into("task id should exist")),
    };

    let (name, priority, start_time, end_time, repeat, notes) = {
        if args.has_task_update_values() {
            // If update values are set by command arguments, use those values
            (
                toado::UpdateAction::from(args.name),
                toado::UpdateAction::from(args.item_priority),
                nullable_into_update_action(args.start_time),
                nullable_into_update_action(args.end_time),
                nullable_into_update_action(args.repeat),
                nullable_into_update_action(args.notes),
            )
        } else {
            // Else, prompt user for update values

            // Get current task values
            let current_name = match task.name {
                Some(value) => value,
                None => return Err(Into::into("task name should exist")),
            };
            let current_priority = match task.priority {
                Some(value) => value,
                None => return Err(Into::into("task priority should exist")),
            };
            let current_start_time = task.start_time.unwrap_or("".to_string());
            let current_end_time = task.end_time.unwrap_or("".to_string());
            let current_repeat = task.repeat.unwrap_or("".to_string());
            let current_notes = task.notes.unwrap_or("".to_string());

            // Get user input for update values
            let name: String = dialoguer::Input::with_theme(&theme)
                .with_prompt("Name")
                .validate_with(|input: &String| validate_name(input))
                .with_initial_text(current_name)
                .interact_text()?;

            let priority: u64 = dialoguer::Input::with_theme(&theme)
                .with_prompt("Priority")
                .default(0)
                .with_initial_text(current_priority.to_string())
                .interact_text()?;

            let start_time: String = dialoguer::Input::with_theme(&theme)
                .with_prompt("Start Time (optional)")
                .with_initial_text(current_start_time)
                .allow_empty(true)
                .interact_text()?;

            let end_time: String = dialoguer::Input::with_theme(&theme)
                .with_prompt("End Time (optional)")
                .with_initial_text(current_end_time)
                .allow_empty(true)
                .interact_text()?;

            let repeat: String = dialoguer::Input::with_theme(&theme)
                .with_prompt("Repeat (optional)")
                .with_initial_text(current_repeat)
                .allow_empty(true)
                .interact_text()?;

            let notes: String = dialoguer::Input::with_theme(&theme)
                .with_prompt("Notes (optional)")
                .with_initial_text(current_notes)
                .allow_empty(true)
                .interact_text()?;

            fn string_to_update_action(s: String) -> toado::UpdateAction<String> {
                if s.is_empty() {
                    toado::UpdateAction::Null
                } else {
                    toado::UpdateAction::Some(format!("'{s}'"))
                }
            }

            (
                toado::UpdateAction::Some(name),
                toado::UpdateAction::Some(priority),
                string_to_update_action(start_time),
                string_to_update_action(end_time),
                string_to_update_action(repeat),
                string_to_update_action(notes),
            )
        }
    };

    app.update_task(
        Some(
            toado::QueryConditions::Equal {
                col: "id",
                value: task_id,
            }
            .to_string(),
        ),
        toado::UpdateTaskArgs {
            name,
            priority,
            status: toado::UpdateAction::None,
            start_time,
            end_time,
            repeat,
            notes,
        },
    )
}

/// Searches for a task in a toado server database with provided search term. If term is a positive
/// integer, searches by task id, otherwise searches by name
///
/// # Errors
///
/// Will return an error if task selection fails
pub fn search_tasks(
    args: flags::SearchArgs,
    app: toado::Server,
    config: &config::Config,
) -> Result<Option<String>, toado::Error> {
    let condition = match args.term.parse::<usize>() {
        // If search term is number, select by id
        Ok(value) => toado::QueryConditions::Equal {
            col: "id",
            value: value.to_string(),
        },
        // If search term is not number, select by name
        Err(_) => toado::QueryConditions::Like {
            col: "name",
            value: format!("'%{}%'", args.term),
        },
    };

    let tasks = app.select_tasks(
        toado::QueryCols::All,
        Some(condition.to_string()),
        Some(toado::OrderBy::Id),
        None,
        Some(toado::RowLimit::All),
        None,
    )?;

    if tasks.is_empty() {
        Ok(None)
    } else if tasks.len() == 1 {
        Ok(Some(formatting::format_task(tasks[0].clone(), config)))
    } else {
        Ok(Some(formatting::format_task_list(
            tasks,
            args.verbose,
            &config.table,
        )))
    }
}

/// Gets a list of tasks from a toado server
///
/// # Errors
///
/// Will return an error if selecting tasks from the server database fails
pub fn list_tasks(
    args: flags::ListArgs,
    app: toado::Server,
    config: &config::Config,
) -> Result<Option<String>, toado::Error> {
    let (cols, order_by, order_dir, limit, offset) = parse_list_args(&args);

    // Get tasks from application database
    let tasks = app.select_tasks(cols, None, order_by, order_dir, limit, offset)?;
    let num_tasks = tasks.len();

    // Format tasks into a table string to display
    let mut table_string = formatting::format_task_list(tasks, args.verbose, &config.table);

    // If not selecting all tasks, display number of tasks selected
    if !args.full {
        table_string.push_str(&list_footer(
            offset,
            num_tasks,
            app.get_table_row_count(toado::Tables::Tasks)?,
        ));
    }

    Ok(Some(table_string))
}

pub fn check_task(
    args: flags::CheckArgs,
    app: toado::Server,
    config: &config::Config,
) -> Result<(String, toado::ItemStatus), toado::Error> {
    let theme = dialoguer::theme::ColorfulTheme::default();

    let search_term = option_or_input(
        args.term,
        dialoguer::Input::with_theme(&theme).with_prompt("Task name"),
    )?;

    let task = prompt_task_selection(
        &app,
        search_term,
        toado::QueryCols::Some(vec!["id", "name", "priority", "status"]),
        &theme,
        config,
    )?;

    // Get selected task id
    let id = match task.id {
        Some(id) => id,
        None => return Err(Into::into("task id should exist")),
    };

    let name = match task.name {
        Some(name) => name,
        None => return Err(Into::into("task name should exist")),
    };

    let new_status = match args.incomplete {
        true => toado::ItemStatus::Incomplete,
        false => toado::ItemStatus::Complete,
    };

    let affected_rows = app.update_task(
        Some(
            toado::QueryConditions::Equal {
                col: "id",
                value: id,
            }
            .to_string(),
        ),
        toado::UpdateTaskArgs::update_status(new_status),
    )?;

    if affected_rows == 0 {
        Err(Into::into("no rows affected by update"))
    } else {
        Ok((name, new_status))
    }
}

//
// Private Methods
//

/// Selects tasks from an application database given a search term. If multiple tasks match the
/// term, prompts the user to select one of the matching tasks and returns it. If one task matches
/// inputed name, returns said task
///
/// # Errors
/// Will return an error if no tasks match the search term
fn prompt_task_selection(
    app: &toado::Server,
    search_term: String,
    cols: toado::QueryCols,
    theme: &dyn dialoguer::theme::Theme,
    config: &config::Config,
) -> Result<toado::Task, toado::Error> {
    let select_condition = match search_term.parse::<usize>() {
        // If search term is number, select by id
        Ok(num) => toado::QueryConditions::Equal {
            col: "id",
            value: num.to_string(),
        },
        // If search term is not number, select by name
        Err(_) => toado::QueryConditions::Like {
            col: "name",
            value: format!("'%{search_term}%'"),
        },
    };

    // Get tasks matching name argument
    let mut tasks = app.select_tasks(
        // toado::QueryCols::Some(vec!["id", "name", "priority", "status"]),
        cols,
        Some(select_condition.to_string()),
        Some(toado::OrderBy::Name),
        None,
        Some(toado::RowLimit::All),
        None,
    )?;

    // If no tasks match search term, return error
    if tasks.is_empty() {
        return Err(Into::into(format!("no task matches {search_term}")));
    }

    if tasks.len() == 1 {
        Ok(tasks.remove(0))
    }
    // If multiple tasks match name argument, prompt user to select one
    else {
        // Format matching tasks into vector of strings
        let task_strings: Vec<String> =
            formatting::format_task_list(tasks.clone(), false, &config.table)
                .split('\n')
                .map(|line| line.to_string())
                .collect();

        // Get task selection from user
        match tasks.get(
            dialoguer::Select::with_theme(theme)
                .with_prompt("Select task")
                .items(&task_strings)
                .interact()?,
        ) {
            Some(task) => Ok(task.clone()),
            None => Err(Into::into("selected task should exist")),
        }
    }
}