1use core::fmt;
8use std::collections::BTreeMap;
9
10use happenstance::bytes::Bytes;
11use happenstance::{
12 Codec, CodecError, DecisionModel, DomainEvent, EventType, InvalidTag, Tag, Tags,
13};
14use serde::{Deserialize, Serialize};
15
16#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
20#[serde(rename_all = "lowercase")]
21pub enum Place {
22 Central,
25 Tablet,
27 Phone,
29}
30
31impl Place {
32 pub const ALL: [Self; 3] = [Self::Central, Self::Tablet, Self::Phone];
34
35 #[must_use]
37 pub const fn as_str(self) -> &'static str {
38 match self {
39 Self::Central => "central",
40 Self::Tablet => "tablet",
41 Self::Phone => "phone",
42 }
43 }
44}
45
46impl fmt::Display for Place {
47 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
49 f.pad(self.as_str())
50 }
51}
52
53impl core::str::FromStr for Place {
54 type Err = UnknownPlace;
55
56 fn from_str(name: &str) -> Result<Self, UnknownPlace> {
57 Self::ALL
58 .into_iter()
59 .find(|place| place.as_str() == name)
60 .ok_or(UnknownPlace)
61 }
62}
63
64#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
66#[error("not a place: expected central, tablet or phone")]
67pub struct UnknownPlace;
68
69#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
72pub enum Device {
73 Tablet,
75 Phone,
77}
78
79impl Device {
80 #[must_use]
82 pub const fn other(self) -> Self {
83 match self {
84 Self::Tablet => Self::Phone,
85 Self::Phone => Self::Tablet,
86 }
87 }
88}
89
90impl From<Device> for Place {
91 fn from(device: Device) -> Self {
92 match device {
93 Device::Tablet => Self::Tablet,
94 Device::Phone => Self::Phone,
95 }
96 }
97}
98
99impl fmt::Display for Device {
100 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
101 fmt::Display::fmt(&Place::from(*self), f)
102 }
103}
104
105#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
111#[serde(try_from = "String", into = "String")]
112pub struct ShowId {
113 name: String,
114 tag: Tag,
115}
116
117impl ShowId {
118 pub fn new(name: &str) -> Result<Self, InvalidTag> {
124 Ok(Self {
125 name: name.to_owned(),
126 tag: Tag::key_value("show", name)?,
127 })
128 }
129
130 #[must_use]
132 pub fn as_str(&self) -> &str {
133 &self.name
134 }
135
136 #[must_use]
138 pub fn scope(&self) -> Tags {
139 [self.tag.clone()].into_iter().collect()
140 }
141}
142
143impl TryFrom<String> for ShowId {
144 type Error = InvalidTag;
145
146 fn try_from(name: String) -> Result<Self, InvalidTag> {
147 Self::new(&name)
148 }
149}
150
151impl From<ShowId> for String {
152 fn from(show: ShowId) -> Self {
153 show.name
154 }
155}
156
157impl fmt::Display for ShowId {
158 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
159 f.write_str(&self.name)
160 }
161}
162
163#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
170#[serde(transparent)]
171pub struct SaleId(String);
172
173impl SaleId {
174 fn mint(at: Place, n: usize) -> Self {
176 Self(format!("{at}-{n}"))
177 }
178
179 #[must_use]
181 pub fn as_str(&self) -> &str {
182 &self.0
183 }
184
185 #[must_use]
187 pub fn into_string(self) -> String {
188 self.0
189 }
190}
191
192impl fmt::Display for SaleId {
193 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
194 f.write_str(&self.0)
195 }
196}
197
198#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
221#[serde(tag = "type", rename_all = "snake_case")]
222pub enum BoxOffice {
223 ShowScheduled {
225 show: ShowId,
227 capacity: u32,
229 },
230 SeatSold {
233 show: ShowId,
235 sale: SaleId,
237 buyer: String,
239 sold_by: Place,
241 },
242 SaleRefunded {
245 show: ShowId,
247 sale: SaleId,
249 reason: RefundReason,
251 },
252}
253
254impl BoxOffice {
255 #[must_use]
257 pub const fn sale(&self) -> Option<&SaleId> {
258 match self {
259 Self::ShowScheduled { .. } => None,
260 Self::SeatSold { sale, .. } | Self::SaleRefunded { sale, .. } => Some(sale),
261 }
262 }
263}
264
265const SHOW_SCHEDULED: EventType = EventType::from_static("ShowScheduled");
266const SEAT_SOLD: EventType = EventType::from_static("SeatSold");
267pub(crate) const SALE_REFUNDED: EventType = EventType::from_static("SaleRefunded");
269
270impl DomainEvent for BoxOffice {
271 const EVENT_TYPES: &'static [EventType] = &[SHOW_SCHEDULED, SEAT_SOLD, SALE_REFUNDED];
272
273 fn event_type(&self) -> EventType {
274 match self {
275 Self::ShowScheduled { .. } => SHOW_SCHEDULED,
276 Self::SeatSold { .. } => SEAT_SOLD,
277 Self::SaleRefunded { .. } => SALE_REFUNDED,
278 }
279 }
280
281 fn tags(&self) -> Tags {
282 match self {
283 Self::ShowScheduled { show, .. }
284 | Self::SeatSold { show, .. }
285 | Self::SaleRefunded { show, .. } => show.scope(),
286 }
287 }
288
289 fn encode<C: Codec>(&self, codec: &C) -> Result<Bytes, CodecError> {
290 codec.encode(self)
291 }
292
293 fn decode<C: Codec>(
294 codec: &C,
295 _event_type: &EventType,
296 data: &Bytes,
297 ) -> Result<Self, CodecError> {
298 codec.decode(data)
299 }
300}
301
302#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
304pub struct RefundReason {
305 pub capacity: u32,
307 pub sales_seen: u32,
309 pub rule: Rule,
311}
312
313impl fmt::Display for RefundReason {
314 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
315 write!(
316 f,
317 "{} sales reached central for {} seats; rule: {}",
318 self.sales_seen, self.capacity, self.rule
319 )
320 }
321}
322
323#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
326pub enum Rule {
327 FirstToReachCentralKeepsTheSeat,
330}
331
332impl fmt::Display for Rule {
333 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
334 f.write_str(match self {
335 Self::FirstToReachCentralKeepsTheSeat => {
336 "the first sale to reach central keeps the seat"
337 }
338 })
339 }
340}
341
342#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
344pub enum Refusal {
345 #[error("show {show} is not scheduled here yet")]
347 NotScheduled {
348 show: String,
350 },
351 #[error("sold out: {held} of {capacity} seats are held")]
353 SoldOut {
354 capacity: u32,
356 held: u32,
358 },
359}
360
361#[derive(Debug, Clone, PartialEq, Eq)]
363pub struct Sale {
364 pub sale: SaleId,
366 pub buyer: String,
368 pub sold_by: Place,
370}
371
372#[derive(Debug, Clone)]
380pub struct ShowLedger {
381 show: ShowId,
382 scope: Tags,
383 capacity: Option<u32>,
384 sales: Vec<Sale>,
385 refunds: BTreeMap<SaleId, RefundReason>,
386}
387
388impl ShowLedger {
389 #[must_use]
391 pub fn new(show: &ShowId) -> Self {
392 Self {
393 show: show.clone(),
394 scope: show.scope(),
395 capacity: None,
396 sales: Vec::new(),
397 refunds: BTreeMap::new(),
398 }
399 }
400
401 #[must_use]
403 pub const fn capacity(&self) -> Option<u32> {
404 self.capacity
405 }
406
407 pub fn sales(&self) -> impl Iterator<Item = &Sale> + '_ {
409 self.sales.iter()
410 }
411
412 pub fn holding(&self) -> impl Iterator<Item = &Sale> + '_ {
414 self.sales
415 .iter()
416 .filter(|sale| !self.refunds.contains_key(&sale.sale))
417 }
418
419 pub fn refunded(&self) -> impl Iterator<Item = &SaleId> + '_ {
421 self.refunds.keys()
422 }
423
424 #[must_use]
426 pub fn refund_reason(&self, sale: &SaleId) -> Option<&RefundReason> {
427 self.refunds.get(sale)
428 }
429
430 #[must_use]
433 pub fn held(&self) -> u32 {
434 u32::try_from(self.holding().count()).unwrap_or(u32::MAX)
435 }
436}
437
438impl DecisionModel for ShowLedger {
439 type Event = BoxOffice;
440
441 fn scope(&self) -> &Tags {
442 &self.scope
443 }
444
445 fn apply(&mut self, event: BoxOffice) {
446 match event {
447 BoxOffice::ShowScheduled { capacity, .. } => self.capacity = Some(capacity),
448 BoxOffice::SeatSold {
449 sale,
450 buyer,
451 sold_by,
452 ..
453 } => self.sales.push(Sale {
454 sale,
455 buyer,
456 sold_by,
457 }),
458 BoxOffice::SaleRefunded { sale, reason, .. } => {
459 self.refunds.insert(sale, reason);
460 }
461 }
462 }
463}
464
465mod decide;
466pub use decide::{adjudicate, schedule, sell_seat};
467
468#[cfg(test)]
469mod tests;