defmodule QRNBU.Validators.InvoiceCreation do
@moduledoc """
Validator for invoice creation datetime.
Validates creation timestamp for invoices in V003 format.
"""
@doc """
Validates invoice creation datetime.
## Rules
- Must be a NaiveDateTime
- Must not be in the future (cannot create invoices with future timestamps)
## Examples
iex> past = ~N[2025-01-01 12:00:00]
iex> QRNBU.Validators.InvoiceCreation.validate(past)
{:ok, past}
iex> now = NaiveDateTime.utc_now()
iex> QRNBU.Validators.InvoiceCreation.validate(now)
{:ok, now}
iex> future = NaiveDateTime.add(NaiveDateTime.utc_now(), 86400, :second)
iex> QRNBU.Validators.InvoiceCreation.validate(future)
{:error, "Invoice creation cannot be in the future"}
iex> QRNBU.Validators.InvoiceCreation.validate("2025-01-01")
{:error, "Invoice creation must be a NaiveDateTime"}
"""
@spec validate(NaiveDateTime.t()) :: {:ok, NaiveDateTime.t()} | {:error, String.t()}
def validate(%NaiveDateTime{} = datetime) do
now = NaiveDateTime.utc_now()
case NaiveDateTime.compare(datetime, now) do
:gt -> {:error, "Invoice creation cannot be in the future"}
_ -> {:ok, datetime}
end
end
def validate(_), do: {:error, "Invoice creation must be a NaiveDateTime"}
end