// What a column's value MEANS, per column type — the one place that reads and// writes the stored form, so an editor, a face and the change receipt all agree// on the bytes.//// The stored form is the shared definition format's (agreed with the faces'// builder on 1 Oct 2026)://// text, longtext, choice .text(String)// date .text("YYYY-MM-DD"), or a full ISO 8601 instant// ("2026-10-01T09:30:00Z") when the day has a time// time .text("HH:mm"), 24-hour// number .number(Double)// amount .number — whole minor units; the currency is the// column the definition's `currency` names// link .text(target record id)// photo .text("photo:<hash>")// file .object(["ref": .text("file:<hash>"), "name": .text])// bool .bool// empty .null//// Pure over values and a calendar, so every rule here is a unit test// (`ColumnValuesTests`) with no view in it.importCottonKitimportCottonValuesimportFoundation// ── Date and time ───────────────────────────────────────────────────────────/// A date column's value as a day and an optional clock time, and back.publicstructWhenValue: Equatable, Sendable {/// Local midnight of the day.publicvar day: Date/// The clock time, when the value states one.publicvar time: ClockTime?publicinit(day: Date, time: ClockTime?) {self.day = dayself.time = time }/// Reads a date column's stored text. A bare day is a local calendar day;/// an instant keeps its clock time — a date editor handed a time never/// drops it by accident.publicstaticfunc read(_ value: RecordValue, calendar: Calendar = .current) -> WhenValue? {// A month on its own (a card's expiry) opens on its first day.ifcase .text(let raw) = value, let month = FaceText.month(raw, calendar: calendar) {returnWhenValue(day: month, time: nil) }guardcase .text(let raw) = value, let at = CottonDate.parse(raw, calendar: calendar) else {returnnil }let day = calendar.startOfDay(for: at)guard !CottonDate.isDayOnly(raw) else { returnWhenValue(day: day, time: nil) }let parts = calendar.dateComponents([.hour, .minute], from: at)returnWhenValue(day: day, time: ClockTime(hour: parts.hour ?? 0, minute: parts.minute ?? 0)) }/// The stored form: a bare day when there is no time, otherwise the local/// instant written as UTC ISO 8601 — the form the engines' `due_at` and/// `starts_at` already use.publicfunc stored(calendar: Calendar = .current) -> RecordValue {guardlet time else {let parts = calendar.dateComponents([.year, .month, .day], from: day)return .text(String(format: "%04d-%02d-%02d", parts.year ?? 0, parts.month ?? 0, parts.day ?? 0)) }let at = calendar.date(bySettingHour: time.hour, minute: time.minute, second: 0, of: day) ?? dayreturn .text(CottonDate.format(at)) }/// `Thu 1 Oct` or `Thu 1 Oct 9:30 am`, with the year when it is not this one.publicfunc words(now: Date, calendar: Calendar = .current) -> String {let sameYear = calendar.component(.year, from: day) == calendar.component(.year, from: now)let dayWords = CottonDate.formatter(sameYear ? "EEE d MMM" : "EEE d MMM yyyy", calendar) .string(from: day)guardlet time else { return dayWords }return"\(dayWords) \(time.words(calendar: calendar))" }}// ── Amount ──────────────────────────────────────────────────────────────────/// An amount column's value: minor units in one currency. The shared format/// stores an amount as a WHOLE NUMBER of minor units (1599 = 15.99) and reads/// its currency off the column the definition's `currency` names; the core/// refuses any other shape ("a whole number of minor units").publicstructAmountValue: Equatable, Sendable {publicvar minor: Intpublicvar currency: Stringpublicinit(minor: Int, currency: String) {self.minor = minorself.currency = currency }/// `currency` is the record's currency column value (the definition's/// `column.currency`); a whole number with no currency reads in the/// device's own.publicstaticfunc read(_ value: RecordValue, currency: String? = nil) -> AmountValue? {guardcase .number(let minor) = value else { returnnil }returnAmountValue(minor: Int(minor.rounded()), currency: currency ?? defaultCurrency()) }/// What an editor writes: the minor units alone, as the core keeps them.publicvar stored: RecordValue { .number(Double(minor)) }/// The currency's minor-unit digits: 2 for most, 0 for yen, 3 for dinar.publicstaticfunc digits(_ currency: String) -> Int {let formatter = NumberFormatter() formatter.numberStyle = .currency formatter.currencyCode = currencyreturn formatter.maximumFractionDigits }/// The currency a new amount is written in when the column has none yet:/// the device's own. No country is the default — the person's locale is.publicstaticfunc defaultCurrency(locale: Locale = .current) -> String { locale.currency?.identifier ?? "XXX" }/// The currency's symbol as the core says it (`money.symbols.<CODE>`:/// `₹` for INR, never the locale's `Rs`), else as the locale writes it/// (`$`, `CHF`).publicstaticfunc symbol(_ currency: String, locale: Locale = .current) -> String {iflet said = coreSymbol(currency) { return said }let formatter = NumberFormatter() formatter.numberStyle = .currency formatter.locale = locale formatter.currencyCode = currencyreturn formatter.currencySymbol }/// The symbol the core's money lines give `currency` (the database's/// row first, then the kit's map), the same mark every face draws; nil/// for a code the map does not name, or names blank.staticfunc coreSymbol(_ currency: String) -> String? {let path = "symbols.\(currency.uppercased())"let said = ShellLines.line(MoneyLines.set, path)guard said != "\(MoneyLines.set).\(path)", !said.trimmingCharacters(in: .whitespaces).isEmpty else { returnnil }return said }/// What was typed, as minor units: digits, one decimal separator (`.` or/// the locale's), thousands separators and spaces ignored. More decimals/// than the currency has is refused, not rounded — a typed `1.005` is a/// mistake, not a half-paisa.publicstaticfunc parse(_ typed: String, currency: String, locale: Locale = .current) -> Int? {let decimal = locale.decimalSeparator ?? "."let grouping = locale.groupingSeparator ?? ","var text = typed.trimmingCharacters(in: .whitespaces)let negative = text.hasPrefix("-")if negative { text.removeFirst() } text = text.replacingOccurrences(of: " ", with: "")if grouping != decimal { text = text.replacingOccurrences(of: grouping, with: "") }if decimal != "." { text = text.replacingOccurrences(of: decimal, with: ".") }let halves = text.split(separator: ".", omittingEmptySubsequences: false)guard !text.isEmpty, halves.count <= 2, halves.allSatisfy({ $0.allSatisfy(\.isASCII) && $0.allSatisfy(\.isNumber) })else { returnnil }let digits = digits(currency)let whole = halves[0].isEmpty ? "0" : String(halves[0])let fraction = halves.count == 2 ? String(halves[1]) : ""guard fraction.count <= digits, !(halves[0].isEmpty && fraction.isEmpty) else { returnnil }let padded = fraction.padding(toLength: digits, withPad: "0", startingAt: 0)guardlet minor = Int(whole + padded) else { returnnil }return negative ? -minor : minor }/// The amount an editor echoes while it is being chosen, before any read/// carries the core's words for it: `₹1,850.00`. Every face, card and/// figure draws the core's amount (`column_words`); this is the one/// money spelling Swift keeps, for a value not yet written.publicfunc words(locale: Locale = .current) -> String {let formatter = NumberFormatter() formatter.locale = locale formatter.numberStyle = .currency formatter.currencyCode = currencyiflet said = Self.coreSymbol(currency) { formatter.currencySymbol = said } formatter.groupingSize = 3 formatter.secondaryGroupingSize = currency.uppercased() == "INR" ? 2 : 3let scale = pow(Decimal(10), formatter.maximumFractionDigits)let major = Decimal(minor) / scalereturn formatter.string(from: NSDecimalNumber(decimal: major)) ?? "\(currency) \(minor)" }/// The amount as typed back into its field: `1850.00` → `1850`, `18.5`.publicfunc typed(locale: Locale = .current) -> String {let digits = Self.digits(currency)let major = Decimal(minor) / pow(Decimal(10), digits)let formatter = NumberFormatter() formatter.locale = locale formatter.numberStyle = .decimal formatter.usesGroupingSeparator = false formatter.maximumFractionDigits = digitsreturn formatter.string(from: major as NSDecimalNumber) ?? "\(major)" }}// ── Number ──────────────────────────────────────────────────────────────────/// The core's line set an amount is said through (`kits/shell/lines/money.json`).enumMoneyLines {staticlet set = "money"}publicenumNumberValue {/// What was typed, as a number: the locale's decimal separator or `.`,/// thousands separators ignored. Nil for anything that is not one number.publicstaticfunc parse(_ typed: String, locale: Locale = .current) -> Double? {let decimal = locale.decimalSeparator ?? "."let grouping = locale.groupingSeparator ?? ","var text = typed.trimmingCharacters(in: .whitespaces).replacingOccurrences(of: " ", with: "")if grouping != decimal { text = text.replacingOccurrences(of: grouping, with: "") }if decimal != "." { text = text.replacingOccurrences(of: decimal, with: ".") }guard !text.isEmpty, let number = Double(text), number.isFinite else { returnnil }return number }/// `2`, not `2.0`; `2.5`; grouped as the locale groups.publicstaticfunc words(_ number: Double, locale: Locale = .current) -> String {let formatter = NumberFormatter() formatter.locale = locale formatter.numberStyle = .decimal formatter.maximumFractionDigits = 6return formatter.string(from: NSNumber(value: number)) ?? "\(number)" }/// As typed back into its field: no grouping, so editing never fights it.publicstaticfunc typed(_ number: Double, locale: Locale = .current) -> String {let formatter = NumberFormatter() formatter.locale = locale formatter.numberStyle = .decimal formatter.usesGroupingSeparator = false formatter.maximumFractionDigits = 6return formatter.string(from: NSNumber(value: number)) ?? "\(number)" }}// ── Photo and file ──────────────────────────────────────────────────────────// ── Words ───────────────────────────────────────────────────────────────────/// A value as a line of words, per column type — what a field shows before it/// is tapped and what the change receipt prints for before and after. Nil for/// an empty value. A link's words are its target's title, which only the/// records know; here it is the id.publicenumColumnWords {publicstaticfunc words( _ value: RecordValue, column: ColumnDefinition, now: Date = Date(), calendar: Calendar = .current, locale: Locale = .current ) -> String? {ifcase .null = value { returnnil }if column.presentation == "password" { return value.text == nil ? nil : ShellLines.line("editing", "value.password_supplied") }switch column.type {case .text, .accountNumber, .longtext, .choice, .link, .url, .place:guardcase .text(let text) = value, !text.isEmpty else { returnnil }return textcase .date:returnWhenValue.read(value, calendar: calendar)?.words(now: now, calendar: calendar)case .time:returnClockTime.read(value)?.words(calendar: calendar)case .bytes:return value.number.flatMap(BytesReading.read)case .number:guardcase .number(let number) = value else { returnnil }returnNumberValue.words(number, locale: locale)case .amount:returnAmountValue.read(value)?.words(locale: locale)case .photo:returnAttachmentValue.read(value) == nil ? nil : "Photo"case .file:guardlet file = AttachmentValue.read(value) else { returnnil }return file.name ?? "File"case .bool:guardcase .bool(let on) = value else { returnnil }return on ? "Yes" : "No" } }}extensionClockTime {/// `9:30 am` — the house clock.publicfunc words(calendar: Calendar = .current) -> String {let reference = calendar.startOfDay(for: Date(timeIntervalSince1970: 0))let at = calendar.date(bySettingHour: hour, minute: minute, second: 0, of: reference) ?? referencereturnDateFormats.houseTime(at, calendar: calendar) }}extensionAttachmentValue {/// A photo is its bare ref; a file carries its name beside it.publicfunc stored(for type: ColumnType) -> RecordValue {guard type == .file else { return .text(ref) }var fields: [String: RecordValue] = ["ref": .text(ref)]iflet name { fields["name"] = .text(name) }return .object(fields) }}