use chrono::{Datelike, NaiveDate};
use super::{Db, DbError, Executor, Migration, Row, Transaction, sql};
use crate::Result;
pub(crate) const MIGRATION: Migration =
crate::db::framework_migration!("sequence", "00010101000420_create_sequences_table");
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Period {
None,
Year(i32),
Month(i32, u32),
}
impl Period {
pub fn of_year(date: NaiveDate) -> Self {
Period::Year(date.year())
}
pub fn of_month(date: NaiveDate) -> Self {
Period::Month(date.year(), date.month())
}
pub fn key(&self) -> String {
match self {
Period::None => String::new(),
Period::Year(y) => format!("{y:04}"),
Period::Month(y, m) => format!("{y:04}-{m:02}"),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[must_use = "a sequence does nothing until you ask it for a number"]
pub struct Sequence {
series: String,
scope: String,
period: Period,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct SequenceRow {
pub series: String,
pub scope: String,
pub period: String,
pub last: i64,
}
impl Sequence {
pub fn new(series: impl Into<String>) -> Self {
Sequence {
series: series.into(),
scope: String::new(),
period: Period::None,
}
}
pub fn scope(mut self, scope: impl ToString) -> Self {
self.scope = scope.to_string();
self
}
pub fn period(mut self, period: Period) -> Self {
self.period = period;
self
}
pub async fn next(&self, tx: &mut Transaction) -> Result<i64> {
let last: i64 = sql(
"INSERT INTO sequences (series, scope, period, last) VALUES (?, ?, ?, 1) \
ON CONFLICT (series, scope, period) DO UPDATE SET last = sequences.last + 1 \
RETURNING last",
)
.bind(self.series.as_str())
.bind(self.scope.as_str())
.bind(self.period.key())
.scalar(tx)
.await?;
Ok(last)
}
pub async fn next_allowing_gaps(&self, db: &Db) -> Result<i64> {
let mut tx = db.begin().await?;
let n = self.next(&mut tx).await?;
tx.commit().await?;
Ok(n)
}
pub async fn peek<'c>(&self, db: impl Executor<'c>) -> Result<i64> {
Ok(self.last(db).await? + 1)
}
pub async fn last<'c>(&self, db: impl Executor<'c>) -> Result<i64> {
let last: Option<i64> =
sql("SELECT last FROM sequences WHERE series = ? AND scope = ? AND period = ?")
.bind(self.series.as_str())
.bind(self.scope.as_str())
.bind(self.period.key())
.scalar_optional(db)
.await?;
Ok(last.unwrap_or(0))
}
pub async fn set_start<'c>(&self, db: impl Executor<'c>, last: i64) -> Result<()> {
sql(
"INSERT INTO sequences (series, scope, period, last) VALUES (?, ?, ?, ?) \
ON CONFLICT (series, scope, period) DO UPDATE SET last = excluded.last",
)
.bind(self.series.as_str())
.bind(self.scope.as_str())
.bind(self.period.key())
.bind(last)
.execute(db)
.await?;
Ok(())
}
pub async fn list<'c>(db: impl Executor<'c>) -> Result<Vec<SequenceRow>> {
let rows = sql("SELECT series, scope, period, last FROM sequences \
ORDER BY series, scope, period")
.fetch_all(db)
.await?;
rows.iter()
.map(|row: &Row| -> Result<SequenceRow, DbError> {
Ok(SequenceRow {
series: row.try_get("series")?,
scope: row.try_get("scope")?,
period: row.try_get("period")?,
last: row.try_get("last")?,
})
})
.collect::<Result<_, _>>()
.map_err(Into::into)
}
pub fn format(pattern: &str, n: i64, date: NaiveDate) -> String {
NumberFormat::new(pattern).render(n, date)
}
}
#[derive(Debug, Clone)]
pub struct NumberFormat {
pattern: String,
tokens: Vec<(String, String)>,
}
impl NumberFormat {
pub fn new(pattern: impl Into<String>) -> Self {
NumberFormat {
pattern: pattern.into(),
tokens: Vec::new(),
}
}
pub fn token(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
self.tokens.push((name.into(), value.into()));
self
}
pub fn render(&self, n: i64, date: NaiveDate) -> String {
let mut out = String::with_capacity(self.pattern.len() + 8);
let mut rest = self.pattern.as_str();
while let Some(open) = rest.find('{') {
out.push_str(&rest[..open]);
let after = &rest[open + 1..];
let Some(close) = after.find('}') else {
out.push_str(&rest[open..]);
return out;
};
let name = &after[..close];
match self.expand(name, n, date) {
Some(text) => {
out.push_str(&text);
rest = &after[close + 1..];
}
None => {
out.push('{');
rest = after;
}
}
}
out.push_str(rest);
out
}
fn expand(&self, name: &str, n: i64, date: NaiveDate) -> Option<String> {
match name {
"yyyy" => Some(format!("{:04}", date.year())),
"yy" => Some(format!("{:02}", date.year().rem_euclid(100))),
"mm" => Some(format!("{:02}", date.month())),
zeros if !zeros.is_empty() && zeros.bytes().all(|b| b == b'0') => {
Some(format!("{n:0width$}", width = zeros.len()))
}
other => self
.tokens
.iter()
.rev()
.find(|(name, _)| name == other)
.map(|(_, value)| value.clone()),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn date() -> NaiveDate {
NaiveDate::from_ymd_opt(2026, 3, 9).unwrap()
}
#[test]
fn formats_tokens() {
assert_eq!(
Sequence::format("INV-{yyyy}-{0000}", 42, date()),
"INV-2026-0042"
);
assert_eq!(Sequence::format("{yy}{mm}-{00}", 5, date()), "2603-05");
assert_eq!(Sequence::format("{0}", 12345, date()), "12345", "no cut");
assert_eq!(Sequence::format("no tokens", 1, date()), "no tokens");
assert_eq!(Sequence::format("{unknown}-{0", 1, date()), "{unknown}-{0");
assert_eq!(Sequence::format("{{0000}", 1, date()), "{0001");
}
#[test]
fn named_tokens_are_not_rescanned() {
let text = NumberFormat::new("{p}-{0000}")
.token("p", "{yyyy}")
.render(3, date());
assert_eq!(text, "{yyyy}-0003");
let later = NumberFormat::new("{p}")
.token("p", "a")
.token("p", "b")
.render(1, date());
assert_eq!(later, "b", "the last value wins");
}
#[test]
fn period_keys() {
assert_eq!(Period::None.key(), "");
assert_eq!(Period::Year(2026).key(), "2026");
assert_eq!(Period::Month(2026, 3).key(), "2026-03");
assert_eq!(Period::of_month(date()), Period::Month(2026, 3));
}
}