Skip to main content

kasl/libs/config/
mod.rs

1//! Application configuration: the data model, disk IO, and PATH setup.
2//! The interactive setup wizard lives in [`wizard`] (reached via
3//! [`Config::init`]).
4//!
5//! ```rust,no_run
6//! # fn main() -> anyhow::Result<()> {
7//! use kasl::libs::config::Config;
8//!
9//! let config = Config::read()?;
10//! let updated_config = Config::init()?;
11//! updated_config.save()?;
12//! # Ok(())
13//! # }
14//! ```
15
16mod wizard;
17
18use super::data_storage::DataStorage;
19use crate::api::gitlab::GitLabConfig;
20use crate::api::jira::JiraConfig;
21use crate::api::si::SiConfig;
22use crate::libs::messages::Message;
23use crate::libs::task::normalize_task_name;
24use crate::msg_error;
25use anyhow::Result;
26use serde::{Deserialize, Serialize};
27use std::env;
28use std::fs;
29use std::path::PathBuf;
30use std::process::Command;
31use std::str;
32
33/// Configuration filename inside the app data directory.
34pub const CONFIG_FILE_NAME: &str = "config.json";
35
36/// A configurable module as listed by the setup wizard.
37#[derive(Debug, Clone)]
38pub struct ConfigModule {
39    /// Internal key used for routing.
40    pub key: String,
41    /// Name shown in the wizard.
42    pub name: String,
43}
44
45/// Activity monitor thresholds and intervals.
46#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
47pub struct MonitorConfig {
48    /// Minimum pause length in minutes to keep as a pause record; shorter
49    /// interruptions are noise, not breaks.
50    pub min_pause_duration: u64,
51
52    /// Seconds without input before a pause is detected.
53    pub pause_threshold: u64,
54
55    /// Milliseconds between activity checks.
56    pub poll_interval: u64,
57
58    /// Seconds of sustained activity required to start a workday - keeps
59    /// a stray mouse nudge from opening the day.
60    pub activity_threshold: u64,
61
62    /// Minimum work interval in minutes; shorter ones are filtered from
63    /// report display.
64    pub min_work_interval: u64,
65
66    /// Maximum gap in seconds between two consecutive pauses to merge them.
67    ///
68    /// When the activity monitor briefly registers a stray input between two
69    /// otherwise continuous inactivity periods, it splits a single break into
70    /// several adjacent pause records. Pauses separated by a gap no longer than
71    /// this value are treated as one continuous pause so that sub-threshold
72    /// segments are not dropped from calculations. The value should stay small
73    /// (a few tens of seconds) so that genuine short work periods between pauses
74    /// are preserved rather than swallowed into the break.
75    #[serde(default = "default_pause_merge_gap")]
76    pub pause_merge_gap: u64,
77}
78
79/// Default gap (in seconds) below which consecutive pauses are merged.
80///
81/// Used both by [`MonitorConfig::default`] and by serde when an existing
82/// configuration file predates the `pause_merge_gap` field.
83fn default_pause_merge_gap() -> u64 {
84    30
85}
86
87/// Productivity thresholds for warnings and report validation.
88#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
89pub struct ProductivityConfig {
90    /// Productivity percentage below which reports warn.
91    pub min_productivity_threshold: f64,
92
93    /// Expected workday length in hours.
94    pub workday_hours: f64,
95
96    /// Fraction of the workday that must pass before warnings appear -
97    /// early-day ratios swing too wildly to act on.
98    pub min_workday_fraction_before_suggest: f64,
99}
100
101/// Report export defaults: output directory and file naming.
102#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Default)]
103pub struct ReportConfig {
104    /// Default directory for exports without an explicit `--output`
105    /// (created if missing); unset = timestamped file in the current dir.
106    #[serde(skip_serializing_if = "Option::is_none")]
107    pub output_dir: Option<String>,
108
109    /// File name template (without extension) for generated reports.
110    ///
111    /// Supported placeholders:
112    /// - `{date}` — the report date in `YYYY-MM-DD` format
113    /// - `{seq}`  — a per-day sequence suffix: empty for the first report of the
114    ///   day, then `_2`, `_3`, … for subsequent reports on the same date
115    ///
116    /// The file extension is appended automatically based on the export format.
117    /// Defaults to `daily_report_{date}{seq}` when unset.
118    #[serde(skip_serializing_if = "Option::is_none")]
119    pub filename_template: Option<String>,
120
121    /// Report label language: `ru` (default) or `en`; unknown values fall
122    /// back to `ru`.
123    #[serde(skip_serializing_if = "Option::is_none")]
124    pub language: Option<String>,
125
126    /// Design template name (`<data>/report_templates/<name>.json`);
127    /// unset or missing falls back to the built-in `siserver` look.
128    #[serde(skip_serializing_if = "Option::is_none")]
129    pub template: Option<String>,
130}
131
132/// External reporting server connection.
133#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
134pub struct ServerConfig {
135    /// Base URL of the reporting API.
136    pub api_url: String,
137
138    /// Token sent with report submissions.
139    pub auth_token: String,
140}
141
142/// The root configuration. Every module is optional, and unset modules
143/// are omitted from the JSON, so the file only names what is configured.
144#[derive(Serialize, Deserialize, Clone, Debug, Default)]
145pub struct Config {
146    /// SiServer integration.
147    #[serde(skip_serializing_if = "Option::is_none")]
148    pub si: Option<SiConfig>,
149
150    /// GitLab integration (commit discovery).
151    #[serde(skip_serializing_if = "Option::is_none")]
152    pub gitlab: Option<GitLabConfig>,
153
154    /// Jira integration (issue discovery, inbox).
155    #[serde(skip_serializing_if = "Option::is_none")]
156    pub jira: Option<JiraConfig>,
157
158    /// Activity monitor settings.
159    #[serde(skip_serializing_if = "Option::is_none")]
160    pub monitor: Option<MonitorConfig>,
161
162    /// External reporting server.
163    #[serde(skip_serializing_if = "Option::is_none")]
164    pub server: Option<ServerConfig>,
165
166    /// Productivity thresholds.
167    #[serde(skip_serializing_if = "Option::is_none")]
168    pub productivity: Option<ProductivityConfig>,
169
170    /// Report export defaults.
171    #[serde(skip_serializing_if = "Option::is_none")]
172    pub report: Option<ReportConfig>,
173
174    /// Task discovery ignore list; built-in defaults apply when absent.
175    #[serde(default, skip_serializing_if = "Option::is_none")]
176    pub task_discovery: Option<TaskDiscoveryConfig>,
177
178    /// Jira inbox polling; requires `jira`, disabled when absent.
179    #[serde(default, skip_serializing_if = "Option::is_none")]
180    pub jira_inbox: Option<JiraInboxConfig>,
181}
182
183/// Settings for polling assigned open Jira issues into the local inbox.
184#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
185pub struct JiraInboxConfig {
186    /// Whether the watcher should poll Jira for open assigned issues.
187    #[serde(default = "default_true")]
188    pub enabled: bool,
189
190    /// Seconds between Jira inbox polls (default 300 = 5 minutes).
191    #[serde(default = "default_jira_inbox_poll_interval")]
192    pub poll_interval_secs: u64,
193
194    /// Whether to show a desktop toast when a new issue appears.
195    #[serde(default = "default_true")]
196    pub notify: bool,
197
198    /// Whether to show a toast when an existing issue visibly changes
199    /// (status, priority, score).
200    #[serde(default = "default_true")]
201    pub notify_changes: bool,
202
203    /// Whether to show a toast when an issue leaves the inbox
204    /// (closed or reassigned). Off by default.
205    #[serde(default)]
206    pub notify_gone: bool,
207
208    /// Extra Jira fields to fetch (custom fields such as Scoring).
209    #[serde(default)]
210    pub custom_fields: Vec<JiraCustomField>,
211
212    /// Field id used for ranking (DESC), typically Scoring (`customfield_…`).
213    #[serde(default, skip_serializing_if = "Option::is_none")]
214    pub sort_by_field: Option<String>,
215}
216
217/// A user-configured Jira custom field for inbox sync / display.
218#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
219pub struct JiraCustomField {
220    /// Jira field id, e.g. `customfield_12345`.
221    pub id: String,
222    /// Human-readable label, e.g. `Scoring`.
223    pub label: String,
224}
225
226fn default_true() -> bool {
227    true
228}
229
230fn default_jira_inbox_poll_interval() -> u64 {
231    300
232}
233
234impl Default for JiraInboxConfig {
235    fn default() -> Self {
236        Self {
237            enabled: true,
238            poll_interval_secs: default_jira_inbox_poll_interval(),
239            notify: true,
240            notify_changes: true,
241            notify_gone: false,
242            custom_fields: Vec::new(),
243            sort_by_field: None,
244        }
245    }
246}
247
248impl JiraInboxConfig {
249    /// Field ids to request from Jira search (custom fields only).
250    pub fn extra_field_ids(&self) -> Vec<String> {
251        let mut ids: Vec<String> = self.custom_fields.iter().map(|f| f.id.trim().to_string()).filter(|id| !id.is_empty()).collect();
252        if let Some(sort_id) = &self.sort_by_field {
253            let trimmed = sort_id.trim();
254            if !trimmed.is_empty() && !ids.iter().any(|id| id == trimmed) {
255                ids.push(trimmed.to_string());
256            }
257        }
258        ids
259    }
260}
261
262/// Settings for intelligent task discovery (`kasl task find`).
263#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
264pub struct TaskDiscoveryConfig {
265    /// Names/prefixes of tasks and commits to exclude from discovery.
266    ///
267    /// Matching is case-insensitive after normalization; a pattern matches
268    /// when the candidate name equals it or starts with it.
269    #[serde(default = "default_ignore_names")]
270    pub ignore_names: Vec<String>,
271}
272
273/// Built-in ignore patterns moved from the former hardcoded noise filter.
274pub fn default_ignore_names() -> Vec<String> {
275    vec![
276        "Merge remote-tracking branch".to_string(),
277        "Merge branch ".to_string(),
278        "update webui".to_string(),
279    ]
280}
281
282impl Default for TaskDiscoveryConfig {
283    fn default() -> Self {
284        Self {
285            ignore_names: default_ignore_names(),
286        }
287    }
288}
289
290impl Default for MonitorConfig {
291    fn default() -> Self {
292        MonitorConfig {
293            min_pause_duration: 20,
294            pause_threshold: 60,
295            poll_interval: 500,
296            activity_threshold: 30,
297            min_work_interval: 10,
298            pause_merge_gap: default_pause_merge_gap(),
299        }
300    }
301}
302
303impl Default for ProductivityConfig {
304    fn default() -> Self {
305        ProductivityConfig {
306            min_productivity_threshold: 75.0,
307            workday_hours: 8.0,
308            min_workday_fraction_before_suggest: 0.5,
309        }
310    }
311}
312
313impl Config {
314    /// Loads the config file, or defaults when none exists yet.
315    ///
316    /// ```rust,no_run
317    /// # fn main() -> anyhow::Result<()> {
318    /// use kasl::libs::config::Config;
319    ///
320    /// let config = Config::read()?;
321    ///
322    /// if config.jira.is_some() {
323    ///     println!("Jira integration is configured");
324    /// }
325    /// # Ok(())
326    /// # }
327    /// ```
328    pub fn read() -> Result<Config> {
329        let config_file_path = DataStorage::new().get_path(CONFIG_FILE_NAME)?;
330
331        if !config_file_path.exists() {
332            return Ok(Config::default());
333        }
334
335        let config_str = fs::read_to_string(config_file_path)?;
336        let config: Config = serde_json::from_str(&config_str)?;
337        Ok(config)
338    }
339
340    /// Writes the config as pretty-printed JSON, overwriting the file.
341    ///
342    /// ```rust,no_run
343    /// # fn main() -> anyhow::Result<()> {
344    /// use kasl::libs::config::{Config, MonitorConfig};
345    ///
346    /// let mut config = Config::read()?;
347    /// config.monitor = Some(MonitorConfig::default());
348    /// config.save()?;
349    /// # Ok(())
350    /// # }
351    /// ```
352    pub fn save(&self) -> Result<()> {
353        let config_file_path = DataStorage::new().get_path(CONFIG_FILE_NAME)?;
354        let json_content = serde_json::to_string_pretty(&self)?;
355        fs::write(config_file_path, json_content)?;
356        Ok(())
357    }
358
359    /// Returns the ignore list for task discovery.
360    ///
361    /// When `task_discovery` is not configured, returns the built-in defaults.
362    pub fn effective_ignore_names(&self) -> Vec<String> {
363        self.task_discovery
364            .as_ref()
365            .map(|c| c.ignore_names.clone())
366            .unwrap_or_else(default_ignore_names)
367    }
368
369    /// Appends unique names to the discovery ignore list and saves the config.
370    ///
371    /// Uniqueness is determined by [`normalize_task_name`]. Returns how many
372    /// new entries were added.
373    pub fn add_ignore_names(&mut self, names: &[String]) -> Result<usize> {
374        let mut discovery = self.task_discovery.clone().unwrap_or_default();
375        let mut added = 0;
376
377        for name in names {
378            let trimmed = name.trim();
379            if trimmed.is_empty() {
380                continue;
381            }
382            let key = normalize_task_name(trimmed);
383            let exists = discovery.ignore_names.iter().any(|existing| normalize_task_name(existing) == key);
384            if !exists {
385                discovery.ignore_names.push(trimmed.to_string());
386                added += 1;
387            }
388        }
389
390        self.task_discovery = Some(discovery);
391        self.save()?;
392        Ok(added)
393    }
394
395    /// Adds the executable's directory to the global PATH.
396    ///
397    /// Windows-shaped: checks the process PATH first, then edits the
398    /// machine-level registry value via `reg` (which needs admin rights;
399    /// the setup command downgrades a failure here to a warning).
400    ///
401    /// ```rust,no_run
402    /// # fn main() -> anyhow::Result<()> {
403    /// use kasl::libs::config::Config;
404    ///
405    /// Config::set_app_global()?;
406    /// # Ok(())
407    /// # }
408    /// ```
409    pub fn set_app_global() -> Result<()> {
410        let current_exe_path = env::current_exe()?;
411        let exe_dir = current_exe_path.parent().unwrap();
412
413        let mut paths: Vec<PathBuf> = env::split_paths(&env::var_os("PATH").unwrap()).collect();
414        let str_paths: Vec<&str> = paths.iter().filter_map(|p| p.to_str()).collect();
415
416        if str_paths.contains(&exe_dir.to_str().unwrap()) {
417            return Ok(());
418        }
419
420        if paths.iter().any(|p| p.to_str() == Some(exe_dir.to_str().unwrap())) {
421            return Ok(());
422        }
423
424        paths.push(exe_dir.to_path_buf());
425
426        let new_path = env::join_paths(paths).unwrap_or_else(|_| panic!("{}", Message::FailedToJoinPaths.to_string()));
427
428        let path_key = r"HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment";
429
430        let reg_query_output = Command::new("reg")
431            .arg("query")
432            .arg(path_key)
433            .arg("/v")
434            .arg("Path")
435            .output()
436            .unwrap_or_else(|_| panic!("{}", Message::FailedToExecuteRegQuery.to_string()));
437
438        if !reg_query_output.status.success() {
439            let status = reg_query_output.status.to_string();
440            msg_error!(Message::PathRegistryQueryError { status: status.clone() });
441            return Err(anyhow::anyhow!("{}", Message::PathRegistryQueryError { status }));
442        }
443
444        let current_path = str::from_utf8(&reg_query_output.stdout)
445            .unwrap_or_else(|_| panic!("{}", Message::FailedToParseRegOutput.to_string()))
446            .split_whitespace()
447            .last()
448            .unwrap_or_else(|| panic!("{}", Message::FailedToGetPathFromReg.to_string()));
449
450        let reg_set_output = Command::new("reg")
451            .arg("add")
452            .arg(path_key)
453            .arg("/v")
454            .arg("Path")
455            .arg("/t")
456            .arg("REG_EXPAND_SZ") // Expandable string type for environment variables
457            .arg("/d")
458            .arg(format!("{};{}", current_path, new_path.to_string_lossy()))
459            .arg("/f") // Force overwrite without confirmation
460            .output()
461            .unwrap_or_else(|_| panic!("{}", Message::FailedToExecuteRegSet.to_string()));
462
463        if !reg_set_output.status.success() {
464            let status = reg_set_output.status.to_string();
465            let stderr = String::from_utf8_lossy(&reg_set_output.stderr).to_string();
466            msg_error!(Message::PathRegistryUpdateError {
467                status: status.clone(),
468                stderr: stderr.clone()
469            });
470            return Err(anyhow::anyhow!("{}", Message::PathRegistryUpdateError { status, stderr }));
471        }
472
473        Ok(())
474    }
475}