stateset-db 1.22.0

Database implementations for StateSet iCommerce
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
//! SQLite implementation of product review repository

use super::{
    map_db_error, parse_datetime_row, parse_enum_row, parse_uuid_row, with_immediate_transaction,
};
use chrono::Utc;
use r2d2::Pool;
use r2d2_sqlite::SqliteConnectionManager;
use stateset_core::{
    CommerceError, CreateReview, ProductId, Result, Review, ReviewFilter, ReviewId,
    ReviewRepository, ReviewSummary, UpdateReview,
};

#[derive(Debug)]
pub struct SqliteReviewRepository {
    pool: Pool<SqliteConnectionManager>,
}

impl SqliteReviewRepository {
    #[must_use]
    pub const fn new(pool: Pool<SqliteConnectionManager>) -> Self {
        Self { pool }
    }

    fn conn(&self) -> Result<r2d2::PooledConnection<SqliteConnectionManager>> {
        self.pool.get().map_err(|e| CommerceError::DatabaseError(e.to_string()))
    }

    fn row_to_review(row: &rusqlite::Row<'_>) -> rusqlite::Result<Review> {
        Ok(Review {
            id: parse_uuid_row(&row.get::<_, String>("id")?, "review", "id")?.into(),
            product_id: parse_uuid_row(
                &row.get::<_, String>("product_id")?,
                "review",
                "product_id",
            )?
            .into(),
            customer_id: parse_uuid_row(
                &row.get::<_, String>("customer_id")?,
                "review",
                "customer_id",
            )?
            .into(),
            rating: row.get::<_, i32>("rating")? as u8,
            title: row.get("title")?,
            body: row.get("body")?,
            status: parse_enum_row(&row.get::<_, String>("status")?, "review", "status")?,
            verified_purchase: row.get::<_, i32>("verified_purchase")? != 0,
            helpful_count: row.get::<_, i32>("helpful_count")? as u32,
            reported_count: row.get::<_, i32>("reported")? as u32,
            created_at: parse_datetime_row(
                &row.get::<_, String>("created_at")?,
                "review",
                "created_at",
            )?,
            updated_at: parse_datetime_row(
                &row.get::<_, String>("updated_at")?,
                "review",
                "updated_at",
            )?,
        })
    }
}

impl ReviewRepository for SqliteReviewRepository {
    fn create(&self, input: CreateReview) -> Result<Review> {
        let id = ReviewId::new();
        let now = Utc::now();
        let id_str = id.to_string();
        let now_str = now.to_rfc3339();

        with_immediate_transaction(&self.pool, |tx| {
            tx.execute(
                "INSERT INTO reviews (id, product_id, customer_id, rating, title, body, status, verified_purchase, created_at, updated_at)
                 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
                rusqlite::params![
                    &id_str,
                    input.product_id.to_string(),
                    input.customer_id.to_string(),
                    input.rating as i32,
                    &input.title,
                    &input.body,
                    "pending",
                    input.verified_purchase as i32,
                    &now_str,
                    &now_str,
                ],
            )?;

            tx.query_row("SELECT * FROM reviews WHERE id = ?", [&id_str], Self::row_to_review)
        })
    }

    fn get(&self, id: ReviewId) -> Result<Option<Review>> {
        let conn = self.conn()?;
        match conn.query_row(
            "SELECT * FROM reviews WHERE id = ?",
            [id.to_string()],
            Self::row_to_review,
        ) {
            Ok(review) => Ok(Some(review)),
            Err(rusqlite::Error::QueryReturnedNoRows) => Ok(None),
            Err(e) => Err(map_db_error(e)),
        }
    }

    fn update(&self, id: ReviewId, input: UpdateReview) -> Result<Review> {
        let id_str = id.to_string();
        let now_str = Utc::now().to_rfc3339();

        with_immediate_transaction(&self.pool, |tx| {
            let mut sets = vec!["updated_at = ?".to_string()];
            let mut params: Vec<Box<dyn rusqlite::types::ToSql>> = vec![Box::new(now_str.clone())];

            if let Some(rating) = input.rating {
                sets.push("rating = ?".into());
                params.push(Box::new(rating as i32));
            }
            if let Some(ref title) = input.title {
                sets.push("title = ?".into());
                params.push(Box::new(title.clone()));
            }
            if let Some(ref body) = input.body {
                sets.push("body = ?".into());
                params.push(Box::new(body.clone()));
            }
            if let Some(status) = input.status {
                sets.push("status = ?".into());
                params.push(Box::new(status.to_string()));
            }

            let sql = format!("UPDATE reviews SET {} WHERE id = ?", sets.join(", "));
            params.push(Box::new(id_str.clone()));

            let param_refs: Vec<&dyn rusqlite::types::ToSql> =
                params.iter().map(|p| p.as_ref()).collect();
            tx.execute(&sql, param_refs.as_slice())?;

            tx.query_row("SELECT * FROM reviews WHERE id = ?", [&id_str], Self::row_to_review)
        })
    }

    fn list(&self, filter: ReviewFilter) -> Result<Vec<Review>> {
        let conn = self.conn()?;
        let mut sql = "SELECT * FROM reviews WHERE 1=1".to_string();
        let mut params: Vec<Box<dyn rusqlite::types::ToSql>> = vec![];

        if let Some(product_id) = filter.product_id {
            sql.push_str(" AND product_id = ?");
            params.push(Box::new(product_id.to_string()));
        }
        if let Some(customer_id) = filter.customer_id {
            sql.push_str(" AND customer_id = ?");
            params.push(Box::new(customer_id.to_string()));
        }
        if let Some(status) = filter.status {
            sql.push_str(" AND status = ?");
            params.push(Box::new(status.to_string()));
        }
        if let Some(min_rating) = filter.min_rating {
            sql.push_str(" AND rating >= ?");
            params.push(Box::new(min_rating as i32));
        }
        if let Some(verified_only) = filter.verified_only {
            // `verified_purchase` is stored as INTEGER (0/1); Postgres applies this
            // filter too.
            sql.push_str(" AND verified_purchase = ?");
            params.push(Box::new(verified_only as i32));
        }

        sql.push_str(" ORDER BY created_at DESC");

        crate::sqlite::append_limit_offset(&mut sql, filter.limit, filter.offset);

        let param_refs: Vec<&dyn rusqlite::types::ToSql> =
            params.iter().map(|p| p.as_ref()).collect();
        let mut stmt = conn.prepare(&sql).map_err(map_db_error)?;
        let reviews = stmt
            .query_map(param_refs.as_slice(), Self::row_to_review)
            .map_err(map_db_error)?
            .collect::<std::result::Result<Vec<_>, _>>()
            .map_err(map_db_error)?;
        Ok(reviews)
    }

    fn delete(&self, id: ReviewId) -> Result<()> {
        let conn = self.conn()?;
        conn.execute("DELETE FROM reviews WHERE id = ?", [id.to_string()]).map_err(map_db_error)?;
        Ok(())
    }

    fn get_summary(&self, product_id: ProductId) -> Result<ReviewSummary> {
        let conn = self.conn()?;
        let pid = product_id.to_string();

        let total: i64 = conn
            .query_row(
                "SELECT COUNT(*) FROM reviews WHERE product_id = ? AND status = 'approved'",
                [&pid],
                |row| row.get(0),
            )
            .map_err(map_db_error)?;

        let avg: f64 = conn
            .query_row(
                "SELECT COALESCE(AVG(CAST(rating AS REAL)), 0.0) FROM reviews WHERE product_id = ? AND status = 'approved'",
                [&pid],
                |row| row.get(0),
            )
            .map_err(map_db_error)?;

        // Compute rating distribution
        let mut distribution = [0u32; 5];
        let mut stmt = conn
            .prepare("SELECT rating, COUNT(*) FROM reviews WHERE product_id = ? AND status = 'approved' GROUP BY rating")
            .map_err(map_db_error)?;
        let rows = stmt
            .query_map([&pid], |row| Ok((row.get::<_, i32>(0)?, row.get::<_, i32>(1)?)))
            .map_err(map_db_error)?;
        for (rating, count) in rows.flatten() {
            let idx = (rating - 1).clamp(0, 4) as usize;
            distribution[idx] = count as u32;
        }

        Ok(ReviewSummary {
            product_id,
            total_reviews: total as u64,
            average_rating: avg,
            rating_distribution: distribution,
        })
    }

    fn mark_helpful(&self, id: ReviewId) -> Result<()> {
        let conn = self.conn()?;
        conn.execute(
            "UPDATE reviews SET helpful_count = helpful_count + 1, updated_at = ? WHERE id = ?",
            rusqlite::params![Utc::now().to_rfc3339(), id.to_string()],
        )
        .map_err(map_db_error)?;
        Ok(())
    }

    fn mark_reported(&self, id: ReviewId) -> Result<()> {
        let conn = self.conn()?;
        conn.execute(
            "UPDATE reviews SET reported = reported + 1, updated_at = ? WHERE id = ?",
            rusqlite::params![Utc::now().to_rfc3339(), id.to_string()],
        )
        .map_err(map_db_error)?;
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::DatabaseConfig;
    use crate::sqlite::SqliteDatabase;
    use stateset_core::CustomerId;

    fn test_repo() -> SqliteReviewRepository {
        let db = SqliteDatabase::new(&DatabaseConfig::in_memory()).unwrap();
        // V4 reviews table isn't in the base migration set — create it for tests
        let conn = db.conn().unwrap();
        conn.execute_batch(
            "CREATE TABLE IF NOT EXISTS reviews (
                id TEXT PRIMARY KEY,
                product_id TEXT NOT NULL,
                customer_id TEXT NOT NULL,
                order_id TEXT,
                rating INTEGER NOT NULL CHECK (rating >= 1 AND rating <= 5),
                title TEXT,
                body TEXT,
                status TEXT NOT NULL DEFAULT 'pending',
                helpful_count INTEGER NOT NULL DEFAULT 0,
                reported INTEGER NOT NULL DEFAULT 0,
                verified_purchase INTEGER NOT NULL DEFAULT 0,
                created_at TEXT NOT NULL DEFAULT (datetime('now')),
                updated_at TEXT NOT NULL DEFAULT (datetime('now'))
            )",
        )
        .unwrap();
        SqliteReviewRepository::new(db.pool().clone())
    }

    #[test]
    fn create_and_get_review() {
        let repo = test_repo();
        let review = repo
            .create(CreateReview {
                product_id: ProductId::new(),
                customer_id: CustomerId::new(),
                rating: 5,
                title: Some("Great product".into()),
                body: Some("Really loved it".into()),
                verified_purchase: true,
            })
            .unwrap();

        assert_eq!(review.rating, 5);
        assert_eq!(review.title.as_deref(), Some("Great product"));
        assert!(review.verified_purchase);

        let fetched = repo.get(review.id).unwrap().unwrap();
        assert_eq!(fetched.id, review.id);
    }

    #[test]
    fn list_reviews_by_product() {
        let repo = test_repo();
        let product_id = ProductId::new();

        for i in 1..=3 {
            repo.create(CreateReview {
                product_id,
                customer_id: CustomerId::new(),
                rating: i as u8 + 2,
                title: None,
                body: None,
                verified_purchase: false,
            })
            .unwrap();
        }

        let reviews =
            repo.list(ReviewFilter { product_id: Some(product_id), ..Default::default() }).unwrap();
        assert_eq!(reviews.len(), 3);
    }

    #[test]
    fn list_filters_by_verified_only() {
        let repo = test_repo();
        let product_id = ProductId::new();
        repo.create(CreateReview {
            product_id,
            customer_id: CustomerId::new(),
            rating: 5,
            title: None,
            body: None,
            verified_purchase: true,
        })
        .unwrap();
        repo.create(CreateReview {
            product_id,
            customer_id: CustomerId::new(),
            rating: 4,
            title: None,
            body: None,
            verified_purchase: false,
        })
        .unwrap();

        // Postgres applies `verified_only`; SQLite must too.
        let verified = repo
            .list(ReviewFilter {
                product_id: Some(product_id),
                verified_only: Some(true),
                ..Default::default()
            })
            .unwrap();
        assert_eq!(verified.len(), 1, "verified_only must filter to verified-purchase reviews");
        assert!(verified[0].verified_purchase);
    }

    #[test]
    fn delete_review() {
        let repo = test_repo();
        let review = repo
            .create(CreateReview {
                product_id: ProductId::new(),
                customer_id: CustomerId::new(),
                rating: 3,
                title: None,
                body: None,
                verified_purchase: false,
            })
            .unwrap();

        repo.delete(review.id).unwrap();
        assert!(repo.get(review.id).unwrap().is_none());
    }

    #[test]
    fn mark_helpful_increments() {
        let repo = test_repo();
        let review = repo
            .create(CreateReview {
                product_id: ProductId::new(),
                customer_id: CustomerId::new(),
                rating: 4,
                title: None,
                body: None,
                verified_purchase: false,
            })
            .unwrap();
        assert_eq!(review.helpful_count, 0);

        repo.mark_helpful(review.id).unwrap();
        repo.mark_helpful(review.id).unwrap();

        let updated = repo.get(review.id).unwrap().unwrap();
        assert_eq!(updated.helpful_count, 2);
    }
}