aboutsummaryrefslogtreecommitdiff
path: root/src/db/payments.rs
blob: 35e7f68aac17138093191efff6903c1bcd605553 (plain)
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
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
use sqlx::error::Error;
use sqlx::sqlite::{Sqlite, SqliteArguments};
use sqlx::sqlite::{SqlitePool, SqliteRow};
use sqlx::FromRow;
use sqlx_core::row::Row;
use std::collections::HashMap;
use std::iter::FromIterator;

use crate::db::utils;
use crate::model::frequency::Frequency;
use crate::model::payment;
use crate::model::report::Report;
use crate::queries;
use crate::utils::text;

#[derive(FromRow)]
pub struct Count {
    pub count: i64,
    pub total_cost: i64,
}

pub async fn count(
    pool: &SqlitePool,
    payment_query: &queries::Payments,
) -> Count {
    let search = payment_query.search.clone().unwrap_or("".to_string());

    let query = format!(
        r#"
SELECT
    COUNT(*) AS count,
    SUM(payments.cost) AS total_cost
FROM
    payments
INNER JOIN
    users ON users.id = payments.user_id
INNER JOIN
    categories ON categories.id = payments.category_id
WHERE
    payments.deleted_at IS NULL
    AND payments.frequency = ?
    {}
        "#,
        search_query(search.clone())
    );

    let res = bind_search(
        sqlx::query_as::<_, Count>(&query)
            .bind(payment_query.frequency.unwrap_or(Frequency::Punctual)),
        search,
    )
    .fetch_one(pool)
    .await;

    match res {
        Ok(count) => count,
        Err(err) => {
            error!("Error counting payments: {:?}", err);
            Count {
                count: 0,
                total_cost: 0,
            }
        }
    }
}

pub async fn list_for_table(
    pool: &SqlitePool,
    payment_query: &queries::Payments,
    per_page: i64,
) -> Vec<payment::Table> {
    let offset = (payment_query.page.unwrap_or(1) - 1) * per_page;
    let search = payment_query.search.clone().unwrap_or("".to_string());

    let query = format!(
        r#"
SELECT
    payments.id,
    payments.name,
    payments.cost,
    users.name AS user,
    categories.name AS category_name,
    categories.color AS category_color,
    strftime('%d/%m/%Y', date) AS date,
    payments.frequency AS frequency
FROM
    payments
INNER JOIN
    users ON users.id = payments.user_id
INNER JOIN
    categories ON categories.id = payments.category_id
WHERE
    payments.deleted_at IS NULL
    AND payments.frequency = ?
    {}
ORDER BY
    payments.date DESC
LIMIT ?
OFFSET ?
        "#,
        search_query(search.clone())
    );

    let res = bind_search(
        sqlx::query_as::<_, payment::Table>(&query)
            .bind(payment_query.frequency.unwrap_or(Frequency::Punctual)),
        search,
    )
    .bind(per_page)
    .bind(offset)
    .fetch_all(pool)
    .await;

    match res {
        Ok(payments) => payments,
        Err(err) => {
            error!("Error listing payments: {:?}", err);
            vec![]
        }
    }
}

fn search_query(search: String) -> String {
    let payments_name = utils::format_key_for_search("payments.name");
    let users_name = utils::format_key_for_search("users.name");
    let categories_name = utils::format_key_for_search("categories.name");

    search
        .split_ascii_whitespace()
        .map(|_| {
            format!(
                r#"
AND (
    {} LIKE ?
    OR payments.cost LIKE ?
    OR {} LIKE ?
    OR {} LIKE ?
    OR strftime('%d/%m/%Y', date) LIKE ?
)
        "#,
                payments_name, users_name, categories_name
            )
        })
        .collect::<Vec<String>>()
        .join(" ")
}

fn bind_search<'a, Row: FromRow<'a, SqliteRow>>(
    query: sqlx::query::QueryAs<'a, Sqlite, Row, SqliteArguments<'a>>,
    search: String,
) -> sqlx::query::QueryAs<'a, Sqlite, Row, SqliteArguments<'a>> {
    search.split_ascii_whitespace().fold(query, |q, word| {
        let s = format!("%{}%", text::format_search(&word.to_string()));
        q.bind(s.clone())
            .bind(s.clone())
            .bind(s.clone())
            .bind(s.clone())
            .bind(s.clone())
    })
}

pub async fn list_for_stats(pool: &SqlitePool) -> Vec<payment::Stat> {
    let query = r#"
SELECT
    strftime('%Y-%m-01', payments.date) AS start_date,
    SUM(payments.cost) AS cost,
    payments.category_id AS category_id
FROM
    payments
WHERE
    payments.deleted_at IS NULL
    AND payments.frequency = 'Punctual'
GROUP BY
    start_date,
    payments.category_id;
    "#;

    let result = sqlx::query_as::<_, payment::Stat>(query)
        .fetch_all(pool)
        .await;

    match result {
        Ok(payments) => payments,
        Err(err) => {
            error!("Error listing payments for statistics: {:?}", err);
            vec![]
        }
    }
}

pub async fn get_row(pool: &SqlitePool, id: i64, frequency: Frequency) -> i64 {
    let query = r#"
SELECT
    row
FROM (
    SELECT
        ROW_NUMBER () OVER (ORDER BY date DESC) AS row,
        id
    FROM
        payments
    WHERE
        deleted_at IS NULL
        AND frequency = ?
)
WHERE
    id = ?
    "#;

    let res = sqlx::query(query)
        .bind(frequency)
        .bind(id)
        .map(|row: SqliteRow| row.get("row"))
        .fetch_one(pool)
        .await;

    match res {
        Ok(count) => count,
        Err(err) => {
            error!("Error getting payment row: {:?}", err);
            1
        }
    }
}

pub async fn get_for_form(pool: &SqlitePool, id: i64) -> Option<payment::Form> {
    let query = r#"
SELECT
    id,
    name,
    cost,
    user_id,
    category_id,
    strftime('%Y-%m-%d', date) AS date,
    frequency AS frequency
FROM
    payments
WHERE
    id = ?
    AND deleted_at IS NULL
    "#;

    let res = sqlx::query_as::<_, payment::Form>(query)
        .bind(id)
        .fetch_one(pool)
        .await;

    match res {
        Ok(p) => Some(p),
        Err(err) => {
            error!("Error looking for payment {}: {:?}", id, err);
            None
        }
    }
}

pub async fn create(pool: &SqlitePool, p: &payment::Create) -> Option<i64> {
    let res = sqlx::query(
        r#"
INSERT INTO
    payments(name, cost, user_id, category_id, date, frequency)
VALUES
    (?, ?, ?, ?, ?, ?)
    "#,
    )
    .bind(p.name.clone())
    .bind(p.cost)
    .bind(p.user_id)
    .bind(p.category_id)
    .bind(p.date)
    .bind(p.frequency)
    .execute(pool)
    .await;

    match res {
        Ok(x) => Some(x.last_insert_rowid()),
        Err(err) => {
            error!("Error creating payment: {:?}", err);
            None
        }
    }
}

pub async fn update(pool: &SqlitePool, id: i64, p: &payment::Update) -> bool {
    let res = sqlx::query(
        r#"
UPDATE
    payments
SET
    name = ?,
    cost = ?,
    user_id = ?,
    category_id = ?,
    date = ?,
    updated_at = datetime()
WHERE
    id = ?
    "#,
    )
    .bind(p.name.clone())
    .bind(p.cost)
    .bind(p.user_id)
    .bind(p.category_id)
    .bind(p.date)
    .bind(id)
    .execute(pool)
    .await;

    match res {
        Ok(_) => true,
        Err(err) => {
            error!("Error updating payment {}: {:?}", id, err);
            false
        }
    }
}

pub async fn delete(pool: &SqlitePool, id: i64) -> bool {
    let res = sqlx::query(
        r#"
UPDATE
    payments
SET
    deleted_at = datetime()
WHERE
    id = ?
    "#,
    )
    .bind(id)
    .execute(pool)
    .await;

    match res {
        Ok(_) => true,
        Err(err) => {
            error!("Error deleting payment {}: {:?}", id, err);
            false
        }
    }
}

pub async fn search_category(
    pool: &SqlitePool,
    payment_name: String,
) -> Option<i64> {
    let query = format!(
        r#"
SELECT
    category_id
FROM
    payments
WHERE
    deleted_at IS NULL
    AND {} LIKE ?
ORDER BY
    updated_at, created_at
        "#,
        utils::format_key_for_search("name")
    );

    let res = sqlx::query(&query)
        .bind(text::format_search(&format!("%{}%", payment_name)))
        .map(|row: SqliteRow| row.get("category_id"))
        .fetch_one(pool)
        .await;

    match res {
        Ok(category) => Some(category),
        Err(Error::RowNotFound) => None,
        Err(err) => {
            error!(
                "Error looking for the category of {}: {:?}",
                payment_name, err
            );
            None
        }
    }
}

pub async fn is_category_used(pool: &SqlitePool, category_id: i64) -> bool {
    let query = r#"
SELECT
    1
FROM
    payments
WHERE
    category_id = ?
    AND deleted_at IS NULL
LIMIT
    1
    "#;

    let res = sqlx::query(&query).bind(category_id).fetch_one(pool).await;

    match res {
        Ok(_) => true,
        Err(Error::RowNotFound) => false,
        Err(err) => {
            error!(
                "Error looking if category {} is used: {:?}",
                category_id, err
            );
            false
        }
    }
}

pub async fn repartition(pool: &SqlitePool) -> HashMap<i64, i64> {
    let query = r#"
SELECT
    users.id AS user_id,
    COALESCE(payments.sum, 0) AS sum
FROM
    users
LEFT OUTER JOIN (
    SELECT
        user_id,
        SUM(cost) AS sum
    FROM
        payments
    WHERE
        deleted_at IS NULL
        AND frequency = 'Punctual'
    GROUP BY
        user_id
) payments
ON
    users.id = payments.user_id"#;

    let res = sqlx::query(&query)
        .map(|row: SqliteRow| (row.get("user_id"), row.get("sum")))
        .fetch_all(pool)
        .await;

    match res {
        Ok(costs) => HashMap::from_iter(costs),
        Err(err) => {
            error!("Error getting payments repartition: {:?}", err);
            HashMap::new()
        }
    }
}

pub async fn create_monthly_payments(pool: &SqlitePool) -> () {
    let query = r#"
INSERT INTO
    payments(name, cost, user_id, category_id, date, frequency)
SELECT
    name,
    cost,
    user_id,
    category_id,
    date() AS date,
    'Punctual' AS frequency
FROM
    payments
WHERE
    frequency = 'Monthly'
    AND deleted_at IS NULL
    "#;

    let res = sqlx::query(query).execute(pool).await;

    match res {
        Ok(_) => (),
        Err(err) => {
            error!("Error creating monthly payments: {:?}", err);
            ()
        }
    }
}

pub async fn last_week(pool: &SqlitePool) -> Vec<Report> {
    let query = r#"
SELECT
    strftime('%d/%m/%Y', payments.date) AS date,
    (payments.name || ' (' || users.name || ')') AS name,
    payments.cost AS amount,
    (CASE
        WHEN
            payments.deleted_at IS NOT NULL
        THEN
            'Deleted'
        WHEN
            payments.updated_at IS NOT NULL
            AND payments.created_at < date('now', 'weekday 0', '-13 days')
        THEN
            'Updated'
        ELSE
            'Created'
    END) AS action
FROM
    payments
INNER JOIN
    users
ON
    payments.user_id = users.id
WHERE
    payments.frequency = 'Punctual'
    AND (
        (
            payments.created_at >= date('now', 'weekday 0', '-13 days')
            AND payments.created_at < date('now', 'weekday 0', '-6 days')
        ) OR (
            payments.updated_at >= date('now', 'weekday 0', '-13 days')
            AND payments.updated_at < date('now', 'weekday 0', '-6 days')
        ) OR (
            payments.deleted_at >= date('now', 'weekday 0', '-13 days')
            AND payments.deleted_at < date('now', 'weekday 0', '-6 days')
        )
    )
ORDER BY
    payments.date
    "#;

    let res = sqlx::query_as::<_, Report>(query).fetch_all(pool).await;

    match res {
        Ok(payments) => payments,
        Err(err) => {
            error!("Error listing payments for report: {:?}", err);
            vec![]
        }
    }
}