about summary refs log tree commit diff stats
path: root/crates/rocie-server/src/storage/sql/insert/barcode/mod.rs
blob: fec9c0fc90882bb4665db0a4007edaaf84fc409b (plain) (blame)
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
// rocie - An enterprise grocery management system
//
// Copyright (C) 2026 Benedikt Peetz <benedikt.peetz@b-peetz.de>
// SPDX-License-Identifier: GPL-3.0-or-later
//
// This file is part of Rocie.
//
// You should have received a copy of the License along with this program.
// If not, see <https://www.gnu.org/licenses/gpl-3.0.txt>.

use std::str::FromStr;

use serde::{Deserialize, Serialize};
use sqlx::query;
use uuid::Uuid;

use crate::{
    app::App,
    storage::{
        migrate::get_current_date,
        sql::{
            barcode::{Barcode, BarcodeId},
            insert::{Operations, Transactionable},
            unit::{Unit, UnitAmount},
        },
    },
};

#[derive(Debug, Deserialize, Serialize)]
pub(crate) enum Operation {
    Buy {
        buy_id: Uuid,
        id: BarcodeId,
    },
    Consume {
        buy_id: Uuid,
        id: BarcodeId,
        amount: UnitAmount,
    },
}

impl Transactionable for Operation {
    type ApplyError = apply::Error;
    type UndoError = undo::Error;

    async fn apply(self, txn: &mut sqlx::SqliteConnection) -> Result<(), apply::Error> {
        match self {
            Operation::Buy { buy_id, id } => {
                let id = id.to_db();
                let buy_id = buy_id.to_string();
                let timestamp = get_current_date();

                query!(
                    "
                    INSERT INTO buys (buy_id, barcode_id, timestamp)
                    VALUES (?, ?, ?)
",
                    buy_id,
                    id,
                    timestamp,
                )
                .execute(txn)
                .await?;
            }
            Operation::Consume { buy_id, id, amount } => {
                let id = id.to_db();
                let buy_id = buy_id.to_string();

                let old_amount = {
                    let record = query!(
                        "
                        SELECT used_amount
                        FROM buys
                        WHERE buy_id = ?;
",
                        buy_id
                    )
                    .fetch_one(&mut *txn)
                    .await?;

                    u32::try_from(record.used_amount.unwrap_or(0))
                        .expect("Should be strictly positive")
                };

                // TODO: Check, that this does not overflow the maximum amount. <2025-09-21>
                let new_amount = amount.value + old_amount;

                // TODO(@bpeetz): We need to add the amount. <2025-09-09>
                query!(
                    "
                    UPDATE buys
                    SET used_amount = ?
                    WHERE barcode_id = ? AND buy_id = ?
",
                    new_amount,
                    id,
                    buy_id
                )
                .execute(txn)
                .await?;
            }
        }
        Ok(())
    }

    async fn undo(self, txn: &mut sqlx::SqliteConnection) -> Result<(), undo::Error> {
        match self {
            Operation::Buy { buy_id, id } => {
                let id = id.to_db();
                let buy_id = buy_id.to_string();

                query!(
                    "
                    DELETE FROM buys
                    WHERE barcode_id = ? AND buy_id = ?
",
                    id,
                    buy_id
                )
                .execute(txn)
                .await?;
            }
            Operation::Consume { buy_id, id, amount } => {
                todo!("We would need to subtract the amount.");
            }
        }
        Ok(())
    }
}

pub(crate) mod undo {
    #[derive(thiserror::Error, Debug)]
    pub(crate) enum Error {
        #[error("Failed to execute undo sql statments: {0}")]
        SqlError(#[from] sqlx::Error),
    }
}
pub(crate) mod apply {
    #[derive(thiserror::Error, Debug)]
    pub(crate) enum Error {
        #[error("Failed to execute apply sql statments: {0}")]
        SqlError(#[from] sqlx::Error),
    }
}

impl Barcode {
    pub(crate) fn buy(&self, ops: &mut Operations<Operation>) {
        let id = Uuid::new_v4();
        ops.push(Operation::Buy {
            buy_id: id,
            id: self.id,
        });
    }

    pub(crate) async fn consume(
        &self,
        app: &App,
        amount: UnitAmount,
        ops: &mut Operations<Operation>,
    ) -> Result<(), consume::Error> {
        assert_eq!(
            self.amount.unit, amount.unit,
            "We currently do not support unit conversions yet"
        );

        if amount.value > self.amount.value {
            let foreign_amount_unit = Unit::from_id(app, amount.unit).await?;

            if let Some(foreign_amount_unit) = foreign_amount_unit {
                let self_amount_unit = Unit::from_id(app, self.amount.unit)
                    .await?
                    .expect("This unit id should always exist");

                return Err(consume::Error::ConsumedMoreThanAvailable {
                    consumed: Box::new((amount, foreign_amount_unit)),
                    available: Box::new((self.amount, self_amount_unit)),
                });
            }

            return Err(consume::Error::UnitIdDoesNotExist(amount.unit));
        }

        let barcode_id = self.id.to_db();
        let buy_id = {
            let record = query!(
                "
                SELECT buy_id
                FROM buys
                WHERE barcode_id = ? AND (used_amount IS NULL OR used_amount < ?)
                ORDER BY timestamp DESC
                LIMIT 1;
",
                barcode_id,
                self.amount.value
            )
            .fetch_optional(&app.db)
            .await?;

            if let Some(found) = record {
                Uuid::from_str(&found.buy_id).expect("Was a uuid, should still be one")
            } else {
                return Err(consume::Error::NoMoreAvailable);
            }
        };

        ops.push(Operation::Consume {
            id: self.id,
            amount,
            buy_id,
        });

        Ok(())
    }
}

pub(crate) mod consume {
    use actix_web::ResponseError;

    use crate::storage::{
        self,
        sql::unit::{Unit, UnitAmount, UnitId},
    };

    #[derive(thiserror::Error, Debug)]
    pub(crate) enum Error {
        #[error("Failed to execute apply sql statments: {0}")]
        Sql(#[from] sqlx::Error),

        #[error("Failed to fetch an unit from a specified amount id value")]
        UnitGet(#[from] storage::sql::get::unit::from_id::Error),

        #[error("The specified unit-id does not exist: {0}")]
        UnitIdDoesNotExist(UnitId),

        #[error("No more of this product is available, buy more. ")]
        NoMoreAvailable,

        #[error(
            "Consumed more than available: consumed {} {}, but available: {} {}", consumed.0.value, consumed.1.short_name, available.0.value, available.1.short_name,
        )]
        ConsumedMoreThanAvailable {
            consumed: Box<(UnitAmount, Unit)>,
            available: Box<(UnitAmount, Unit)>,
        },
    }

    impl ResponseError for Error {}
}