1use happenstance::{ConvergentProjection, Delivered, Projection, ProjectionId, Tags};
26use happenstance_sqlite::projection_store::{
27 SqliteBatch, SqliteProjectionStore, SqliteProjectionStoreError,
28};
29use rusqlite::Connection;
30use rusqlite::types::{FromSql, FromSqlError, FromSqlResult, Value, ValueRef};
31
32use crate::domain::{BoxOffice, Place, ShowId};
33
34pub(crate) const DDL: &str = "
43CREATE TABLE IF NOT EXISTS show_seats (
44 show TEXT PRIMARY KEY,
45 capacity INTEGER NOT NULL
46) STRICT;
47CREATE TABLE IF NOT EXISTS seat_ledger (
48 show TEXT NOT NULL,
49 sale TEXT NOT NULL,
50 buyer TEXT,
51 sold_by TEXT,
52 status TEXT NOT NULL CHECK (status IN ('held', 'refunded')),
53 reason TEXT,
54 PRIMARY KEY (show, sale)
55) STRICT;
56";
57
58const SEAT_TIMELINE: ProjectionId = ProjectionId::from_static("seat_timeline");
60
61#[derive(Debug)]
63pub struct Timeline {
64 id: ProjectionId,
65 scope: Tags,
66}
67
68impl Timeline {
69 #[must_use]
71 pub fn new(show: &ShowId) -> Self {
72 Self {
73 id: SEAT_TIMELINE,
74 scope: show.scope(),
75 }
76 }
77}
78
79impl Projection for Timeline {
80 type Event = BoxOffice;
81 type Store = SqliteProjectionStore;
82 type Error = SqliteProjectionStoreError;
83
84 fn id(&self) -> &ProjectionId {
85 &self.id
86 }
87
88 fn scope(&self) -> &Tags {
89 &self.scope
90 }
91
92 async fn apply(
93 &mut self,
94 event: Delivered<BoxOffice>,
95 batch: &mut SqliteBatch,
96 ) -> Result<(), SqliteProjectionStoreError> {
97 match event.into_event() {
98 BoxOffice::ShowScheduled { show, capacity } => batch.push(
99 "INSERT INTO show_seats (show, capacity) VALUES (?1, ?2) \
100 ON CONFLICT (show) DO NOTHING",
101 [Value::Text(show.into()), Value::Integer(capacity.into())],
102 ),
103 BoxOffice::SeatSold {
104 show,
105 sale,
106 buyer,
107 sold_by,
108 } => batch.push(
109 "INSERT INTO seat_ledger (show, sale, buyer, sold_by, status) \
110 VALUES (?1, ?2, ?3, ?4, 'held') \
111 ON CONFLICT (show, sale) DO UPDATE \
112 SET buyer = excluded.buyer, sold_by = excluded.sold_by",
113 [
114 Value::Text(show.into()),
115 Value::Text(sale.into_string()),
116 Value::Text(buyer),
117 Value::Text(sold_by.as_str().to_owned()),
118 ],
119 ),
120 BoxOffice::SaleRefunded { show, sale, reason } => batch.push(
121 "INSERT INTO seat_ledger (show, sale, status, reason) \
122 VALUES (?1, ?2, 'refunded', ?3) \
123 ON CONFLICT (show, sale) DO UPDATE \
124 SET status = 'refunded', reason = excluded.reason",
125 [
126 Value::Text(show.into()),
127 Value::Text(sale.into_string()),
128 Value::Text(reason.to_string()),
129 ],
130 ),
131 }
132 Ok(())
133 }
134}
135
136impl ConvergentProjection for Timeline {}
138
139#[derive(Debug, Clone, Copy, PartialEq, Eq)]
141pub enum Status {
142 Held,
144 Refunded,
146}
147
148impl FromSql for Status {
149 fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
150 match value.as_str()? {
151 "held" => Ok(Self::Held),
152 "refunded" => Ok(Self::Refunded),
153 _ => Err(FromSqlError::InvalidType),
154 }
155 }
156}
157
158impl FromSql for Place {
159 fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
160 value
161 .as_str()?
162 .parse()
163 .map_err(|error| FromSqlError::Other(Box::new(error)))
164 }
165}
166
167#[derive(Debug, Clone, PartialEq, Eq)]
169pub struct Row {
170 pub sale: String,
172 pub buyer: Option<String>,
174 pub sold_by: Option<Place>,
176 pub status: Status,
178 pub reason: Option<String>,
180}
181
182#[derive(Debug, Clone, PartialEq, Eq)]
184pub struct TimelineView {
185 pub capacity: Option<u32>,
187 pub rows: Vec<Row>,
189}
190
191impl TimelineView {
192 pub fn read(app: &Connection, show: &ShowId) -> rusqlite::Result<Self> {
201 let capacity = app
202 .prepare("SELECT capacity FROM show_seats WHERE show = ?1")?
203 .query_map([show.as_str()], |row| row.get::<_, u32>(0))?
204 .next()
205 .transpose()?;
206 let rows = app
207 .prepare(
208 "SELECT sale, buyer, sold_by, status, reason FROM seat_ledger \
209 WHERE show = ?1 ORDER BY status = 'refunded', sale",
210 )?
211 .query_map([show.as_str()], |row| {
212 Ok(Row {
213 sale: row.get(0)?,
214 buyer: row.get(1)?,
215 sold_by: row.get(2)?,
216 status: row.get(3)?,
217 reason: row.get(4)?,
218 })
219 })?
220 .collect::<rusqlite::Result<_>>()?;
221 Ok(Self { capacity, rows })
222 }
223
224 #[must_use]
227 pub fn held(&self) -> u32 {
228 self.count(Status::Held)
229 }
230
231 #[must_use]
233 pub fn refunds(&self) -> u32 {
234 self.count(Status::Refunded)
235 }
236
237 #[must_use]
239 pub fn sales(&self) -> u32 {
240 u32::try_from(self.rows.len()).unwrap_or(u32::MAX)
241 }
242
243 fn count(&self, status: Status) -> u32 {
244 let n = self.rows.iter().filter(|row| row.status == status).count();
245 u32::try_from(n).unwrap_or(u32::MAX)
246 }
247}
248
249#[cfg(test)]
250mod tests;