kasl-cli 0.10.1

kasl is a comprehensive command-line utility 🛠️ designed to streamline the tracking of work activities 📊, including start times ⏰, pauses ⏸, and task completion
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
//! Manual break management command for productivity optimization.
//!
//! Provides functionality to add manual break periods to improve productivity calculations and help users reach minimum productivity thresholds for report submission.
//!
//! ## Features
//!
//! - **Automatic Placement**: Intelligent break placement in longest work intervals
//! - **Interactive Mode**: Manual selection of break timing and duration
//! - **Productivity Integration**: Immediate impact on productivity calculations
//! - **Smart Recommendations**: Suggests optimal break durations and placement
//! - **Validation**: Ensures breaks don't overlap with existing pauses
//!
//! ## Usage
//!
//! ```bash
//! # Add break with automatic placement
//! kasl breaks --minutes 30
//!
//! # Interactive break creation
//! kasl breaks
//!
//! # Force break creation ignoring validation
//! kasl breaks --minutes 60 --force
//! ```

use crate::{
    db::{breaks::Breaks, pauses::Pauses, workdays::Workdays},
    libs::{config::Config, formatter::format_duration, messages::Message, pause::Pause, productivity::Productivity, report},
    msg_error, msg_info, msg_print, msg_success,
};
use anyhow::Result;
use chrono::{Duration, Local, NaiveDate, NaiveDateTime};
use clap::Args;
use dialoguer::{Input, Select, theme::ColorfulTheme};

/// Command-line arguments for the breaks command.
///
/// Supports both automatic break placement and interactive selection
/// of break timing and placement options.
#[derive(Debug, Args)]
pub struct BreaksArgs {
    /// Minutes duration for the break (automatic placement)
    ///
    /// When specified, the system will automatically find the optimal
    /// placement for a break of this duration. If not specified, enters
    /// interactive mode for manual break configuration.
    #[arg(long, short)]
    minutes: Option<u64>,

    /// Force creation even if productivity validation fails
    ///
    /// Bypasses normal productivity threshold checks and creates the break
    /// regardless of current productivity levels. Use with caution.
    #[arg(long)]
    force: bool,
}

/// Represents a break placement option with timing details.
///
/// Each option shows the user when and where a break would be placed,
/// providing context for informed decision making.
#[derive(Debug, Clone)]
pub struct BreakOption {
    /// Start time of the proposed break
    pub start: NaiveDateTime,
    /// End time of the proposed break
    pub end: NaiveDateTime,
    /// Duration of the break
    pub duration: Duration,
    /// Human-readable description of the placement
    pub description: String,
}

/// Main entry point for the breaks command.
///
/// Routes between automatic placement mode and interactive configuration
/// based on command line arguments provided by the user.
///
/// # Arguments
///
/// * `args` - Parsed command line arguments specifying break options
///
/// # Returns
///
/// Returns `Ok(())` on successful break creation, or an error if
/// validation fails or database operations encounter issues.
pub async fn cmd(args: BreaksArgs) -> Result<()> {
    let today = Local::now().date_naive();

    // Validate that we can only create breaks for today
    let config = Config::read()?;
    let productivity_config = config.productivity.unwrap_or_default();

    if let Some(minutes) = args.minutes {
        handle_automatic_break_placement(today, minutes, &productivity_config, args.force).await
    } else {
        handle_interactive_break_creation(today, &productivity_config, args.force).await
    }
}

/// Handles automatic break placement with specified duration.
///
/// Finds the optimal placement for a break of the given duration and
/// creates it without user interaction. Includes productivity validation
/// unless forced.
async fn handle_automatic_break_placement(
    date: NaiveDate,
    minutes: u64,
    productivity_config: &crate::libs::config::ProductivityConfig,
    _force: bool,
) -> Result<()> {
    // Validate break duration
    if minutes < productivity_config.min_break_duration {
        msg_error!(Message::BreakDurationPrompt {
            min_duration: productivity_config.min_break_duration,
            max_duration: productivity_config.max_break_duration,
        });
        return Ok(());
    }

    if minutes > productivity_config.max_break_duration {
        msg_error!(Message::BreakDurationPrompt {
            min_duration: productivity_config.min_break_duration,
            max_duration: productivity_config.max_break_duration,
        });
        return Ok(());
    }

    // Get workday and pauses data
    let workday = match Workdays::new()?.fetch(date)? {
        Some(wd) => wd,
        None => {
            msg_error!("No workday found for today");
            return Ok(());
        }
    };

    let config = Config::read()?;
    let monitor_config = config.monitor.unwrap_or_default();
    let pauses = Pauses::new()?
        .set_min_duration(monitor_config.min_pause_duration)
        .get_workday_pauses(&workday)?;

    // Find optimal break placement
    let break_options = find_break_placement_options(&workday, &pauses, minutes, monitor_config.min_work_interval)?;

    if break_options.is_empty() {
        msg_error!(Message::NoValidBreakPlacement);
        return Ok(());
    }

    // Use the first (optimal) option
    let break_option = &break_options[0];

    // Create the break record
    let break_record = crate::db::breaks::Break {
        id: None,
        date,
        start: break_option.start,
        end: break_option.end,
        duration: break_option.duration,
        reason: None,
        created_at: None,
    };

    let breaks_db = Breaks::new()?;
    breaks_db.insert(&break_record)?;

    msg_success!(Message::BreakCreated {
        start_time: break_option.start.format("%H:%M").to_string(),
        end_time: break_option.end.format("%H:%M").to_string(),
        duration_minutes: minutes,
    });

    // Recalculate and show productivity
    show_updated_productivity(date).await?;

    Ok(())
}

/// Handles interactive break creation with user selection.
///
/// Prompts user for break duration and presents placement options
/// for selection. Provides full control over break timing and placement.
async fn handle_interactive_break_creation(date: NaiveDate, productivity_config: &crate::libs::config::ProductivityConfig, _force: bool) -> Result<()> {
    msg_print!(Message::BreakInteractivePrompt);

    // Prompt for break duration
    let theme = ColorfulTheme::default();
    let duration_input: String = Input::with_theme(&theme)
        .with_prompt(format!(
            "Enter break duration ({}-{} minutes)",
            productivity_config.min_break_duration, productivity_config.max_break_duration
        ))
        .interact_text()?;

    let minutes: u64 = match duration_input.parse() {
        Ok(m) if m >= productivity_config.min_break_duration && m <= productivity_config.max_break_duration => m,
        _ => {
            msg_error!(Message::BreakDurationPrompt {
                min_duration: productivity_config.min_break_duration,
                max_duration: productivity_config.max_break_duration,
            });
            return Ok(());
        }
    };

    // Get workday and pauses data
    let workday = match Workdays::new()?.fetch(date)? {
        Some(wd) => wd,
        None => {
            msg_error!("No workday found for today");
            return Ok(());
        }
    };

    let config = Config::read()?;
    let monitor_config = config.monitor.unwrap_or_default();
    let pauses = Pauses::new()?
        .set_min_duration(monitor_config.min_pause_duration)
        .get_workday_pauses(&workday)?;

    // Find break placement options
    let break_options = find_break_placement_options(&workday, &pauses, minutes, monitor_config.min_work_interval)?;

    if break_options.is_empty() {
        msg_error!(Message::NoValidBreakPlacement);
        return Ok(());
    }

    // Present options to user
    msg_print!(Message::BreakPlacementOptions);
    let option_labels: Vec<String> = break_options
        .iter()
        .enumerate()
        .map(|(i, opt)| {
            format!(
                "{}. {} - {} ({} min) - {}",
                i + 1,
                opt.start.format("%H:%M"),
                opt.end.format("%H:%M"),
                opt.duration.num_minutes(),
                opt.description
            )
        })
        .collect();

    let selection = Select::with_theme(&theme)
        .with_prompt("Select break placement")
        .items(&option_labels)
        .default(0)
        .interact()?;

    let chosen_option = &break_options[selection];

    // Create the break record
    let break_record = crate::db::breaks::Break {
        id: None,
        date,
        start: chosen_option.start,
        end: chosen_option.end,
        duration: chosen_option.duration,
        reason: None,
        created_at: None,
    };

    let breaks_db = Breaks::new()?;
    breaks_db.insert(&break_record)?;

    msg_success!(Message::BreakCreated {
        start_time: chosen_option.start.format("%H:%M").to_string(),
        end_time: chosen_option.end.format("%H:%M").to_string(),
        duration_minutes: minutes,
    });

    // Recalculate and show productivity
    show_updated_productivity(date).await?;

    Ok(())
}

/// Finds optimal placement options for a break of the given duration.
///
/// Analyzes the workday and existing pauses to suggest the best times
/// to place a break, avoiding conflicts and maintaining minimum work intervals.
fn find_break_placement_options(
    workday: &crate::db::workdays::Workday,
    pauses: &[Pause],
    duration_minutes: u64,
    min_work_interval: u64,
) -> Result<Vec<BreakOption>> {
    let mut options = Vec::new();
    let current_time = Local::now().naive_local();
    let workday_end = workday.end.unwrap_or(current_time);

    // Calculate work intervals
    let intervals = report::calculate_work_intervals(workday, pauses);

    // Find gaps between pauses that can accommodate the break
    let break_duration = Duration::minutes(duration_minutes as i64);

    if intervals.is_empty() {
        return Ok(options);
    }

    // Strategy 1: Place break in the middle of the longest interval
    let longest_interval = intervals.iter().max_by_key(|interval| interval.duration.num_minutes());

    if let Some(interval) = longest_interval {
        // Check if the interval is long enough to accommodate the break plus minimum work time
        let required_time = break_duration + Duration::minutes(min_work_interval as i64 * 2);
        if interval.duration >= required_time && interval.end <= current_time {
            let interval_mid = interval.start + (interval.duration / 2);
            let break_start = interval_mid - (break_duration / 2);
            let break_end = break_start + break_duration;

            options.push(BreakOption {
                start: break_start,
                end: break_end,
                duration: break_duration,
                description: "Middle of longest work period".to_string(),
            });
        }
    }

    // Strategy 2: Place break after existing pauses (if there's room)
    for (i, pause) in pauses.iter().enumerate() {
        if let Some(pause_end) = pause.end {
            // Find the next pause or end of workday
            let next_pause_start = pauses.get(i + 1).map(|p| p.start).unwrap_or(workday_end.min(current_time));

            let available_time = next_pause_start - pause_end;
            let required_time = break_duration + Duration::minutes(min_work_interval as i64);

            if available_time >= required_time && pause_end + break_duration <= current_time {
                options.push(BreakOption {
                    start: pause_end,
                    end: pause_end + break_duration,
                    duration: break_duration,
                    description: format!("After {} pause", format_duration(&pause.duration.unwrap_or_default())),
                });
            }
        }
    }

    // Strategy 3: Place break before existing pauses (if there's room)
    for pause in pauses.iter() {
        let work_start = workday.start;
        let available_time = pause.start - work_start;
        let required_time = break_duration + Duration::minutes(min_work_interval as i64);

        if available_time >= required_time {
            let break_end = pause.start - Duration::minutes(min_work_interval as i64);
            let break_start = break_end - break_duration;

            if break_start >= work_start && break_end <= current_time {
                options.push(BreakOption {
                    start: break_start,
                    end: break_end,
                    duration: break_duration,
                    description: format!("Before {} pause", format_duration(&pause.duration.unwrap_or_default())),
                });
            }
        }
    }

    // Remove duplicates and sort by start time
    options.sort_by_key(|opt| opt.start);
    options.dedup_by(|a, b| {
        (a.start - b.start).num_minutes().abs() < 5 // Consider times within 5 minutes as duplicates
    });

    // Limit to top 3 options
    options.truncate(3);

    Ok(options)
}

/// Shows updated productivity after break creation.
///
/// Recalculates productivity using the centralized `Productivity` module and displays
/// the updated productivity percentage to the user. This provides immediate feedback
/// on how the newly added break affects overall productivity metrics.
///
/// ## Calculation Process
///
/// 1. **Data Loading**: Fetches the current workday record
/// 2. **Comprehensive Analysis**: Uses `Productivity::new()` to automatically load:
///    - All manual breaks (including the just-created break)
///    - Short pauses (< min_pause_duration)  
///    - Long pauses (>= min_pause_duration)
/// 3. **Unified Calculation**: Applies the same productivity logic used throughout the app
/// 4. **User Feedback**: Displays the recalculated productivity percentage
///
/// This ensures the user sees exactly how their break addition impacts the productivity
/// metric that will be used in reports and other application features.
async fn show_updated_productivity(date: NaiveDate) -> Result<()> {
    // Get workday data for the specified date
    let workday = Workdays::new()?.fetch(date)?.expect("Workday should exist");

    // Use centralized productivity module for consistent calculation
    let productivity = Productivity::new(&workday)?.calculate_productivity();

    msg_info!(Message::ProductivityRecalculated(productivity));
    Ok(())
}