1
use derive_more::From;
2
use finance::{
3
    account::Account, commodity::Commodity, error::FinanceError, price::Price, split::Split,
4
    tag::Tag, transaction::Transaction,
5
};
6
use num_rational::Rational64;
7
use serde::{Deserialize, Serialize};
8
use sqlx::{
9
    types::Uuid,
10
    types::chrono::{DateTime, Utc},
11
};
12
use std::{
13
    collections::HashMap,
14
    fmt::{self, Debug},
15
};
16
use thiserror::Error;
17

            
18
use crate::{
19
    config::ConfigError,
20
    db::{DBError, is_pool_unavailable},
21
    error::ServerError,
22
};
23

            
24
mod connect;
25
pub(crate) use connect::{admin_connection, connection};
26
pub mod account;
27
pub mod account_commodities;
28
pub mod account_edit;
29
#[cfg(test)]
30
mod account_edit_tests;
31
pub mod account_merge;
32
#[cfg(test)]
33
mod account_merge_tests;
34
pub mod account_name;
35
#[cfg(test)]
36
mod account_name_tests;
37
pub mod account_reparent;
38
#[cfg(test)]
39
mod account_reparent_tests;
40
pub mod account_tag;
41
#[cfg(test)]
42
mod account_tag_tests;
43
mod attempt;
44
pub mod commodity;
45
pub mod commodity_edit;
46
#[cfg(test)]
47
mod commodity_edit_tests;
48
pub mod commodity_tag;
49
#[cfg(test)]
50
mod commodity_tag_tests;
51
pub mod config;
52
#[cfg(test)]
53
mod config_timezone_tests;
54
pub mod data_findings;
55
pub mod report;
56
pub mod script;
57
#[cfg(test)]
58
mod script_tests;
59
pub mod split;
60
pub mod ssh_key;
61
pub mod tag;
62
mod tag_replace;
63
#[cfg(test)]
64
mod tag_tests;
65
pub mod template;
66
pub mod template_list;
67
#[cfg(test)]
68
mod template_tests;
69
pub mod transaction;
70
pub(crate) mod transaction_edit;
71
#[cfg(test)]
72
mod transaction_edit_tests;
73
pub mod user;
74

            
75
#[derive(Debug, Clone)]
76
pub struct CommodityInfo {
77
    pub commodity_id: Uuid,
78
    pub symbol: String,
79
    pub name: String,
80
}
81

            
82
#[derive(Debug, Clone)]
83
pub struct PaginationInfo {
84
    pub total_count: i64,
85
    pub limit: i64,
86
    pub offset: i64,
87
    pub has_more: bool,
88
}
89

            
90
#[derive(Debug, From)]
91
pub enum FinanceEntity {
92
    Commodity(Commodity),
93
    Tag(Tag),
94
    Split(Split),
95
    Transaction(Transaction),
96
    Price(Price),
97
    Account(Account),
98
}
99

            
100
#[derive(Debug, From)]
101
pub enum Argument {
102
    String(String),
103
    Rational(Rational64),
104
    Uuid(Uuid),
105
    Data(Vec<u8>),
106
    FinanceEntity(FinanceEntity),
107
    FinanceEntities(Vec<FinanceEntity>),
108
    DateTime(DateTime<Utc>),
109
}
110

            
111
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
112
pub struct CommodityAmount {
113
    pub commodity_id: Uuid,
114
    pub commodity_symbol: String,
115
    pub amount: Rational64,
116
}
117

            
118
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
119
pub struct ReportNode {
120
    pub account_id: Uuid,
121
    pub account_name: String,
122
    pub account_path: String,
123
    pub depth: usize,
124
    pub account_type: Option<String>,
125
    pub amounts: Vec<CommodityAmount>,
126
    /// The account's own splits, without its descendants'.
127
    pub own_amounts: Vec<CommodityAmount>,
128
    pub children: Vec<ReportNode>,
129
}
130

            
131
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
132
pub struct ReportMeta {
133
    pub date_from: Option<DateTime<Utc>>,
134
    pub date_to: Option<DateTime<Utc>>,
135
    pub target_commodity_id: Option<Uuid>,
136
}
137

            
138
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
139
pub struct PeriodData {
140
    pub label: Option<String>,
141
    pub roots: Vec<ReportNode>,
142
}
143

            
144
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
145
pub struct ReportData {
146
    pub meta: ReportMeta,
147
    pub periods: Vec<PeriodData>,
148
}
149

            
150
/// One pane of an `ActivityReport`. The caller supplies a label, a filter
151
/// that selects which splits belong in the pane, and a display-time
152
/// sign-flip hint. The command returns raw accountant values; `flip_sign`
153
/// just travels with the data so UIs know how to render it.
154
#[derive(Debug, Clone, Serialize, Deserialize)]
155
pub struct ActivityGroup {
156
    pub label: String,
157
    pub filter: ReportFilter,
158
    #[serde(default)]
159
    pub flip_sign: bool,
160
}
161

            
162
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
163
pub struct ActivityGroupResult {
164
    pub label: String,
165
    pub flip_sign: bool,
166
    pub roots: Vec<ReportNode>,
167
    /// Raw sum of the root amounts; `flip_sign` is applied at display time.
168
    pub total: Vec<CommodityAmount>,
169
}
170

            
171
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
172
pub struct ActivityPeriod {
173
    pub label: Option<String>,
174
    pub groups: Vec<ActivityGroupResult>,
175
    /// Raw sum of the group totals; clients show [`ActivityPeriod::displayed_net`].
176
    pub net: Vec<CommodityAmount>,
177
}
178

            
179
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
180
pub struct ActivityData {
181
    pub meta: ReportMeta,
182
    pub periods: Vec<ActivityPeriod>,
183
}
184

            
185
/// Sentinel value used in `BreakdownRow::tag_value` for splits that have no
186
/// value for the pivot tag.
187
pub const UNCATEGORIZED_KEY: &str = "__uncategorized__";
188

            
189
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
190
pub struct BreakdownRow {
191
    pub tag_value: String,
192
    pub is_uncategorized: bool,
193
    pub amounts: Vec<CommodityAmount>,
194
}
195

            
196
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
197
pub struct BreakdownPeriod {
198
    pub label: Option<String>,
199
    pub rows: Vec<BreakdownRow>,
200
}
201

            
202
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
203
pub struct BreakdownData {
204
    pub meta: ReportMeta,
205
    pub tag_name: String,
206
    pub periods: Vec<BreakdownPeriod>,
207
}
208

            
209
#[derive(Debug, Clone, Serialize, Deserialize)]
210
#[serde(rename_all = "lowercase")]
211
pub enum FilterEntity {
212
    Account,
213
    Transaction,
214
    Split,
215
}
216

            
217
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
218
#[serde(rename_all = "lowercase")]
219
pub enum PeriodGrouping {
220
    Month,
221
    Quarter,
222
    Year,
223
}
224

            
225
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
226
#[serde(rename_all = "snake_case")]
227
pub enum BreakdownSort {
228
    #[default]
229
    AmountDesc,
230
    AmountAsc,
231
    NameAsc,
232
    NameDesc,
233
}
234

            
235
#[derive(Debug, Clone, Serialize, Deserialize)]
236
#[serde(tag = "op", content = "args", rename_all = "snake_case")]
237
pub enum ReportFilter {
238
    AccountEq(Uuid),
239
    AccountIn(Vec<Uuid>),
240
    AccountSubtree(Uuid),
241
    CounterpartyEq(Uuid),
242
    CounterpartyIn(Vec<Uuid>),
243
    CommodityEq(Uuid),
244
    CommodityIn(Vec<Uuid>),
245
    AmountGt(Rational64),
246
    AmountLt(Rational64),
247
    AmountEq(Rational64),
248
    Tag {
249
        entity: FilterEntity,
250
        name: String,
251
        value: String,
252
    },
253
    TagIn {
254
        entity: FilterEntity,
255
        name: String,
256
        values: Vec<String>,
257
    },
258
    And(Vec<ReportFilter>),
259
    Or(Vec<ReportFilter>),
260
    Not(Box<ReportFilter>),
261
}
262

            
263
#[derive(Debug, Error)]
264
pub enum CmdError {
265
    #[error("Wrong arguments: {0}")]
266
    Args(String),
267
    #[error("convert-commodity: no Price row between {from} and {to}")]
268
    NoPrice { from: Uuid, to: Uuid },
269
    #[error("{0}")]
270
    NotFound(String),
271
    #[error("{0}")]
272
    Unkeepable(String),
273
    #[error("{0}")]
274
    Refused(String),
275
    #[error("Parent account {0} not found")]
276
    ParentGone(Uuid),
277
    #[error("Config: {0}")]
278
    Config(#[from] ConfigError),
279
    #[error("Database: {0}")]
280
    DB(#[from] sqlx::Error),
281
    #[error("Server: {0}")]
282
    Server(#[from] ServerError),
283
    #[error("Finance: {0}")]
284
    Finance(#[from] FinanceError),
285
    #[error("Script execution failed: {0}")]
286
    Script(String),
287
    #[error("This account is disabled")]
288
    Disabled,
289
}
290

            
291
impl From<DBError> for CmdError {
292
8837
    fn from(err: DBError) -> Self {
293
8837
        CmdError::Server(err.into())
294
8837
    }
295
}
296

            
297
impl CmdError {
298
    /// The busy condition the failure stands for; see [`ServerError::busy`].
299
119711
    pub fn busy(&self) -> Option<DBError> {
300
119711
        match self {
301
38706
            CmdError::Server(err) => err.busy(),
302
            CmdError::DB(err) | CmdError::Finance(FinanceError::DB(err))
303
6663
                if crate::tag::lock::is_lock_timeout(err) =>
304
            {
305
3
                Some(DBError::WriteConflict)
306
            }
307
81002
            _ => None,
308
        }
309
119711
    }
310

            
311
    /// True when the database behind the failure cannot be reached right now.
312
115755
    pub fn is_unavailable(&self) -> bool {
313
115755
        match self {
314
34755
            CmdError::Server(err) => err.is_unavailable(),
315
            CmdError::DB(err) | CmdError::Finance(FinanceError::DB(err)) => {
316
7380
                is_pool_unavailable(err)
317
            }
318
73620
            _ => false,
319
        }
320
115755
    }
321

            
322
    /// True when a lookup matched no row.
323
81364
    pub fn is_missing_row(&self) -> bool {
324
81364
        match self {
325
4140
            CmdError::DB(err) => matches!(err, sqlx::Error::RowNotFound),
326
14764
            CmdError::Server(err) => err.is_missing_row(),
327
62460
            _ => false,
328
        }
329
81364
    }
330

            
331
    /// A deadlock or serialization failure: the attempt may succeed when run again.
332
4532
    pub(crate) fn is_retryable(&self) -> bool {
333
4532
        match self {
334
            CmdError::DB(err) | CmdError::Finance(FinanceError::DB(err)) => {
335
3
                crate::tag::lock::is_retryable(err)
336
            }
337
4529
            _ => false,
338
        }
339
4532
    }
340
}
341

            
342
// Implementing CmdResult as an enum with String and Rational returning options
343
#[derive(Debug)]
344
pub enum CmdResult {
345
    String(String),
346
    Rational(Rational64),
347
    Uuid(Uuid),
348
    Bool(bool),
349
    Count(i64),
350
    /// `into` kept the merged account and received `moved` splits.
351
    Merged {
352
        into: Uuid,
353
        moved: i64,
354
    },
355
    Data(Vec<u8>),
356
    Lines(Vec<String>),
357
    Entity(FinanceEntity),
358
    Entities(Vec<FinanceEntity>),
359
    TaggedEntities {
360
        entities: Vec<(FinanceEntity, HashMap<String, FinanceEntity>)>,
361
        pagination: Option<PaginationInfo>,
362
    },
363
    /// A split carries every (name, value) pair, ordered by name then value.
364
    TaggedSplits {
365
        entities: Vec<(Split, Vec<Tag>)>,
366
    },
367
    /// Transaction listings carry a per-row computed `amount` summary in a
368
    /// dedicated slot so it never collides with a user tag named `amount`.
369
    TaggedTransactions {
370
        entities: Vec<(
371
            FinanceEntity,
372
            HashMap<String, FinanceEntity>,
373
            Option<String>,
374
        )>,
375
        pagination: Option<PaginationInfo>,
376
    },
377
    CommodityInfoList(Vec<CommodityInfo>),
378
    /// Account to its only commodity, for accounts holding exactly one.
379
    SingleCommodities(HashMap<Uuid, Uuid>),
380
    MultiCurrencyBalance(Vec<(Commodity, Rational64)>),
381
    Report(ReportData),
382
    Breakdown(BreakdownData),
383
    Activity(ActivityData),
384
    SshKeys(Vec<ssh_key::SshKeyRecord>),
385
    /// Template id and name, ordered by name with unnamed last.
386
    Templates(Vec<crate::artifact_mgmt::user::TemplateInfo>),
387
    /// The (name, value) string config pairs, ordered by name.
388
    ConfigEntries(Vec<(String, String)>),
389
    DataFindings(Vec<data_findings::DataFinding>),
390
    Timezone(chrono_tz::Tz),
391
    ScriptRun(crate::script_run::ScriptRun),
392
}
393

            
394
impl From<String> for CmdResult {
395
191124
    fn from(s: String) -> Self {
396
191124
        CmdResult::String(s)
397
191124
    }
398
}
399

            
400
impl fmt::Display for CmdResult {
401
362
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
402
362
        match self {
403
362
            CmdResult::String(s) => write!(f, "{s}"),
404
            CmdResult::Rational(r) => write!(f, "{r}"),
405
            CmdResult::Data(d) => write!(f, "CmdResult<Data>: \"{}\" bytes", d.len()),
406
            CmdResult::Lines(l) => {
407
                // Find the maximum width for alignment
408
                let max_width = l.iter().map(std::string::String::len).max().unwrap_or(0);
409

            
410
                // Write header
411
                writeln!(f, "CmdResult<Lines>: {} items", l.len())?;
412

            
413
                // Write each item in a column format
414
                for (i, item) in l.iter().enumerate() {
415
                    writeln!(f, "{:>4}. {:<width$}", i + 1, item, width = max_width)?;
416
                }
417
                Ok(())
418
            }
419
            CmdResult::Entity(e) => write!(f, "CmdResult<FinanceEntity>: \"{e:?}\""),
420
            CmdResult::Entities(e) => write!(f, "CmdResult<FinanceEntities>: \"{}\"", e.len()),
421
            CmdResult::TaggedEntities {
422
                entities,
423
                pagination,
424
            } => match pagination {
425
                Some(p) => write!(
426
                    f,
427
                    "CmdResult<TaggedEntities>: {} of {} (offset: {})",
428
                    entities.len(),
429
                    p.total_count,
430
                    p.offset
431
                ),
432
                None => write!(f, "CmdResult<TaggedEntities>: \"{}\"", entities.len()),
433
            },
434
            CmdResult::TaggedSplits { entities } => {
435
                write!(f, "CmdResult<TaggedSplits>: \"{}\"", entities.len())
436
            }
437
            CmdResult::TaggedTransactions {
438
                entities,
439
                pagination,
440
            } => match pagination {
441
                Some(p) => write!(
442
                    f,
443
                    "CmdResult<TaggedTransactions>: {} of {} (offset: {})",
444
                    entities.len(),
445
                    p.total_count,
446
                    p.offset
447
                ),
448
                None => write!(f, "CmdResult<TaggedTransactions>: \"{}\"", entities.len()),
449
            },
450
            CmdResult::CommodityInfoList(e) => {
451
                write!(f, "CmdResult<CommodityInfoList>: \"{}\"", e.len())
452
            }
453
            CmdResult::SingleCommodities(e) => {
454
                write!(f, "CmdResult<SingleCommodities>: \"{}\"", e.len())
455
            }
456
            CmdResult::MultiCurrencyBalance(e) => {
457
                write!(f, "CmdResult<MultiCurrencyBalance>: \"{}\"", e.len())
458
            }
459
            CmdResult::Report(r) => {
460
                write!(f, "CmdResult<Report>: {} periods", r.periods.len())
461
            }
462
            CmdResult::Breakdown(b) => {
463
                write!(
464
                    f,
465
                    "CmdResult<Breakdown>: tag={} periods={}",
466
                    b.tag_name,
467
                    b.periods.len()
468
                )
469
            }
470
            CmdResult::Activity(a) => {
471
                write!(
472
                    f,
473
                    "CmdResult<Activity>: {} periods, {} groups",
474
                    a.periods.len(),
475
                    a.periods.first().map_or(0, |p| p.groups.len()),
476
                )
477
            }
478
            CmdResult::Uuid(id) => write!(f, "{id}"),
479
            CmdResult::Bool(b) => write!(f, "{b}"),
480
            CmdResult::Count(n) => write!(f, "{n}"),
481
            CmdResult::Merged { into, moved } => write!(f, "{into}: {moved} splits moved"),
482
            CmdResult::SshKeys(keys) => {
483
                write!(f, "CmdResult<SshKeys>: {} keys", keys.len())
484
            }
485
            CmdResult::Templates(e) => write!(f, "CmdResult<Templates>: {} templates", e.len()),
486
            CmdResult::Timezone(zone) => write!(f, "{zone}"),
487
            CmdResult::ScriptRun(run) => write!(f, "{run}"),
488
            CmdResult::ConfigEntries(entries) => {
489
                write!(f, "CmdResult<ConfigEntries>: {} entries", entries.len())
490
            }
491
            CmdResult::DataFindings(items) => {
492
                write!(f, "CmdResult<DataFindings>: {} findings", items.len())
493
            }
494
        }
495
362
    }
496
}