Cotton code
368 lines · 17.5 KB · SwiftRaw
// A SPEND as a TILL RECEIPT (owner, 30 Oct 2026: "each time we spend// something, a receipt is good"; the money picture `objects-2/money/1-till-// receipt`): a strip of thermal paper with a till's serrated foot, lying bare// on the money's pink terrazzo (`FaceGround.terrazzo`), no paper and no rule of// the deck's. The paper and its shadow are PAINTED (`Media.xcassets`, cut and// imported by `scripts/import-money-materials.py`), nothing printed on them;// the face prints live, in the till's purple-black ribbon, only what the card// decides:////   the payee as the printed head (`title`, who the money went to: a shop,//   or a person, for money sent to someone), in capitals, two lines at most;//   the day and time (`date`) and what it was for (`subtitle`, else `body`);//   the amount large, typed with "Rs" and two places ("Rs 2,340.00");//   the account it was paid from, by its name (`account`);//   and at the foot the account's balance before and after it, as two//   printed lines, as a shop's receipt prints a card's balance (the owner: "after//   every spend, it'll be nice if there's a before and after amount").//// The card's corner ("in 9 days") and state ("Expected") are pencilled at the// receipt's top. A tap on the screen's sides cuts to the next card// (`FaceStep.cut`). Every word but the till's own print ("TOTAL", "PAID",// "BALANCE BEFORE", "BALANCE AFTER") is the core's (`DeckCard`); the till labels// resolve from the kit's cards lines.import CottonPaperimport CottonValuesimport SwiftUIenum ReceiptFaceKnobs {    // THE PAPER, as painted (`receipt-paper`): its width over its height, and    // how far its shadow reaches past it, as a share of its width — measured    // off the painting by the cut (`cut.py` beside the layers).    static let aspect: CGFloat = 850.0 / 1466.0    static let shadowReach: CGFloat = 0.0824    /// The paper in the card's room: the most of its height and width it takes.    static let fillHeight: CGFloat = 0.97    static let fillWidth: CGFloat = 0.9    /// The print's margins, as shares of the paper's width (sides) and    /// height (top; the foot keeps clear of the serrated teeth).    static let side: CGFloat = 0.085    static let top: CGFloat = 0.075    static let foot: CGFloat = 0.07    /// The type, as shares of the paper's width: print on an object scales    /// with the object, never with Dynamic Type.    static let headSize: CGFloat = 0.108    static let lineSize: CGFloat = 0.062    static let amountSize: CGFloat = 0.13    static let totalSize: CGFloat = 0.05    static let footSize: CGFloat = 0.056    static let pencilSize: CGFloat = 0.075    /// The least gap between the receipt's parts, as a share of its height:    /// the parts spread down the paper to its foot, so the print fills it.    static let gap: CGFloat = 0.022}public struct TransactionReceiptFace: View {    let card: DeckCard    @Environment(\.faceOpened) private var opened    public init(card: DeckCard) {        self.card = card    }    public var body: some View {        let knobs = ReceiptFaceKnobs.self        if opened {            OpenedReceipt(card: card)        } else {        GeometryReader { box in            let height = min(box.size.height * knobs.fillHeight, box.size.width * knobs.fillWidth / knobs.aspect)            let size = CGSize(width: height * knobs.aspect, height: height)            ZStack(alignment: .topLeading) {                MoneyPaper(name: "receipt-paper", size: size, reach: knobs.shadowReach, standIn: MoneyMaterial.receipt.colour, corner: 0)                ReceiptPrint(card: card, size: size)                    .frame(width: size.width, height: size.height)            }            .frame(width: size.width, height: size.height)            .accessibilityElement(children: .contain)            .accessibilityIdentifier("receipt")            .frame(width: box.size.width, height: box.size.height)        }        }    }}/// What the till printed, and the pencil over it.private struct ReceiptPrint: View {    let card: DeckCard    let size: CGSize    var body: some View {        let knobs = ReceiptFaceKnobs.self        let w = size.width        let h = size.height        let ink = MoneyMaterial.posting.colour        let amount = card.text("amount").flatMap(SaidAmount.init)        let balances = MoneyReading.balances(card)        ZStack(alignment: .topLeading) {            VStack(alignment: .center, spacing: 0) {                if let title = card.text("title") {                    Text(title.uppercased())                        .font(CottonFonts.type(knobs.headSize * w))                        .tracking(0.04 * knobs.headSize * w)                        .foregroundStyle(ink)                        .multilineTextAlignment(.center)                        .lineLimit(2)                        .minimumScaleFactor(0.6)                        .frame(maxWidth: .infinity)                        .accessibilityIdentifier("deck-title")                        .facePart(.title)                }                Spacer(minLength: knobs.gap * h)                PrintedDashes(ink: ink, weight: 0.006 * w)                Spacer(minLength: knobs.gap * h)                VStack(spacing: 0.5 * knobs.gap * h) {                    if let date = card.text("date") {                        FittedLine(words: date.uppercased(), font: CottonFonts.type(knobs.lineSize * w), ink: ink, alignment: .center)                            .facePart(.when)                    }                    if let purpose = MoneyReading.purpose(card) {                        Text(purpose.words.uppercased())                            .font(CottonFonts.type(knobs.lineSize * w))                            .foregroundStyle(ink)                            .multilineTextAlignment(.center)                            .lineLimit(2)                            .minimumScaleFactor(0.7)                            .frame(maxWidth: .infinity)                            .facePart(purpose.part)                    }                }                Spacer(minLength: knobs.gap * h)                PrintedDashes(ink: ink, weight: 0.006 * w)                Spacer(minLength: knobs.gap * h)                if let amount {                    HStack(alignment: .firstTextBaseline, spacing: 0.03 * w) {                        Text(ReceiptPrintWords.total)                            .font(CottonFonts.type(knobs.totalSize * w))                            .foregroundStyle(ink)                        FittedLine(words: MoneyReading.typed(amount), font: CottonFonts.type(knobs.amountSize * w), ink: ink, alignment: .trailing)                    }                    .facePart(.amount)                } else if let said = card.text("amount") {                    FittedLine(words: said, font: CottonFonts.type(knobs.amountSize * w), ink: ink, alignment: .center)                        .facePart(.amount)                }                Spacer(minLength: knobs.gap * h)                if let account = card.text("account") {                    FittedLine(words: "\(ReceiptPrintWords.paid) \(account.uppercased())", font: CottonFonts.type(knobs.lineSize * w), ink: ink, alignment: .center, shrink: 0.6)                }                Spacer(minLength: knobs.gap * h)                if balances.before != nil || balances.after != nil {                    PrintedDashes(ink: ink, weight: 0.006 * w)                    Spacer(minLength: knobs.gap * h)                    balanceLines(balances, ink: ink)                }                Spacer(minLength: knobs.gap * h)                PrintedDashes(ink: ink, weight: 0.006 * w)            }            .padding(.horizontal, knobs.side * w)            .padding(.top, knobs.top * h)            .padding(.bottom, knobs.foot * h)            .frame(width: w, height: h, alignment: .top)            // Ribbon ink sits in the paper.            .blendMode(.multiply)            pencil        }    }    /// The two balance lines, label left and figures right, set at one size    /// that fits the longer in the print's width (the type is monospaced:    /// every character is 0.6 of its size wide).    private func balanceLines(_ balances: (before: SaidAmount?, after: SaidAmount?), ink: Color) -> some View {        let knobs = ReceiptFaceKnobs.self        let w = size.width        let lines = [(ReceiptPrintWords.before, balances.before), (ReceiptPrintWords.after, balances.after)]            .compactMap { label, amount in amount.map { (label, MoneyReading.typed($0)) } }        let longest = lines.map { $0.0.count + 2 + $0.1.count }.max() ?? 1        let room = w * (1 - 2 * knobs.side)        let points = min(knobs.footSize * w, room / (CGFloat(longest) * 0.6))        return VStack(spacing: 0.5 * knobs.gap * size.height) {            ForEach(lines, id: \.0) { label, figures in                HStack(alignment: .firstTextBaseline, spacing: 0) {                    Text(label)                    Spacer(minLength: points * 0.6)                    Text(figures)                }                .font(CottonFonts.type(points))                .foregroundStyle(ink)                .lineLimit(1)            }        }    }    /// The corner and the state, pencilled at the receipt's top right.    @ViewBuilder private var pencil: some View {        let knobs = ReceiptFaceKnobs.self        let w = size.width        if card.corner != nil || card.text("state") != nil {            VStack(alignment: .trailing, spacing: 0) {                if let corner = card.corner {                    Text(corner).facePart(.corner)                }                if let state = card.text("state") {                    Text(state).facePart(.state)                }            }            .font(CottonFonts.hand(knobs.pencilSize * w))            .foregroundStyle(card.pressing ? MoneyMaterial.tab.colour : MoneyMaterial.pencil.colour)            .rotationEffect(.degrees(-6))            .frame(width: 0.96 * w, alignment: .topTrailing)            .padding(.top, 0.008 * size.height)        }    }}/// The till's own print: the words a receipt is printed with whatever was/// bought, as its paper's heads are (the ledger card's are painted).enum ReceiptPrintWords {    static let total = "TOTAL"    static let paid = "PAID"    static var before: String { ShellLines.line("cards", "faces.balance_before") }    static var after: String { ShellLines.line("cards", "faces.balance_after") }}/// A spend as a till receipt, by its id beside the transaction's own face,/// and the spends it is reviewed in: invented names only. The specimen/// world's today is Thursday 29 October 2026; a date is said as the core/// says it.public enum TransactionReceiptFaceCatalogue {    public static let stock: FaceStock = .own    public static let ground: FaceGround = .terrazzo    public static let face = Face(id: "transaction.receipt", specimens: [        Specimen("opened", opened, opened: true),        Specimen("grocer", grocer), Specimen("to-a-person", toAPerson), Specimen("large", large),    ], steps: .cut) { card, _, _ in        TransactionReceiptFace(card: card)    }    public static var opened: DeckCard {        var card = grocer        card.fields["tag"] = .text("Household")        card.fields["period"] = .text("October 2026")        card.fields["people"] = .list([.object(["name": .text("Alex Sample")])])        card.fields["body"] = .text("Weekly provisions for the shared kitchen. Keep the receipt with this month's accounts.")        card.fields["state"] = .text("Expected")        return card    }    static func spend(_ record: String, _ fields: [String: RecordValue], corner: String? = nil) -> DeckCard {        DeckCard(face: "transaction.receipt", corner: corner, pressing: false, pace: nil, plate: nil, fields: fields)            .reading { $0.record = record }    }    static func balances(_ before: String, _ after: String) -> RecordValue {        .list([            .object(["label": .text("Balance before"), "said": .text(before)]),            .object(["label": .text("Balance after"), "said": .text(after)]),        ])    }    static func when(_ day: String, _ clock: String) -> RecordValue {        .text(day + EventWhen.join + clock)    }    /// The reference's spend: groceries from the savings account.    public static let grocer = spend("0f6c2a4e-91d3-4b7a-8c55-3e2b17a04217", [        "title": .text("Greenleaf Grocers"),        "subtitle": .text("Groceries"),        "amount": .text("\u{20B9}2,340"),        "account": .text("Northern Bank Savings"),        "facts": balances("\u{20B9}1,26,840", "\u{20B9}1,24,500"),        "date": when("Thu 29 Oct", "6:12 pm"),    ])    /// Money sent to a person: the same receipt, their name its head.    public static let toAPerson = spend("7a1d0c3b-5e2f-4c8a-9b61-d2e4f90c1388", [        "title": .text("Ravi K."),        "subtitle": .text("Dinner, my half"),        "amount": .text("\u{20B9}1,850.50"),        "account": .text("Northern Bank Savings"),        "facts": balances("\u{20B9}1,24,500", "\u{20B9}1,22,649.50"),        "date": when("Tue 27 Oct", "10:41 pm"),    ])    /// A lakh figure: the amount and both balances run long.    public static let large = spend("c3e9b5d1-2a7f-4e60-8d14-6b0f3a9e2c75", [        "title": .text("Lakeside Furniture Works"),        "subtitle": .text("Sofa and two armchairs"),        "amount": .text("\u{20B9}1,24,500"),        "account": .text("Northern Bank Savings"),        "facts": balances("\u{20B9}4,92,400", "\u{20B9}3,67,900"),        "date": when("Sat 17 Oct", "4:05 pm"),    ])}private struct OpenedReceipt: View {    let card: DeckCard    var body: some View {        GeometryReader { room in            let width = room.size.width * ReceiptFaceKnobs.fillWidth            ScrollView {                VStack(spacing: width * 0.045) {                    VStack(spacing: width * 0.035) {                        if let title = card.text("title") { Text(title.uppercased()).font(CottonFonts.type(width * 0.09)) }                        if let date = card.text("date") { Text(date) }                        PrintedDashes(ink: MoneyMaterial.posting.colour, weight: width * 0.006)                        if let amount = card.text("amount") {                            HStack { Text(ReceiptPrintWords.total); Spacer(); Text(SaidAmount(amount).map { MoneyReading.typed($0) } ?? amount).font(CottonFonts.type(width * 0.11)).lineLimit(1).minimumScaleFactor(0.65) }                        }                        if let account = card.text("account") { Text(ReceiptPrintWords.paid + " " + account.uppercased()) }                        PrintedDashes(ink: MoneyMaterial.posting.colour, weight: width * 0.006)                    }                    .font(CottonFonts.type(width * ReceiptFaceKnobs.lineSize))                    .foregroundStyle(MoneyMaterial.posting.colour)                    .padding(.horizontal, width * ReceiptFaceKnobs.side)                    .padding(.top, width * 0.12)                    VStack(alignment: .leading, spacing: width * 0.045) {                        ForEach(["tag", "period"], id: \.self) { slot in                            if let words = card.text(slot) { Text(words).fixedSize(horizontal: false, vertical: true) }                        }                        ForEach(Array(card.entries("people").enumerated()), id: \.offset) { _, person in                            if let name = person["name"]?.text { Text(name) }                        }                        if let notes = card.text("body") { Text(notes).fixedSize(horizontal: false, vertical: true).facePart(.body) }                        if let state = ReceiptOpenedReading.stamp(card) {                            Text(state.uppercased()).foregroundStyle(MoneyMaterial.stamp.colour)                                .rotationEffect(.degrees(-6)).facePart(.state)                        }                    }                    .font(CottonFonts.type(width * ReceiptFaceKnobs.lineSize))                    .foregroundStyle(MoneyMaterial.posting.colour)                    .frame(maxWidth: .infinity, alignment: .leading)                    .padding(.horizontal, width * ReceiptFaceKnobs.side)                    .padding(.bottom, width * 0.05)                    let balances = MoneyReading.balances(card)                    VStack(spacing: 8) {                        if let before = balances.before { Text(ReceiptPrintWords.before + " " + MoneyReading.typed(before)) }                        if let after = balances.after { Text(ReceiptPrintWords.after + " " + MoneyReading.typed(after)) }                    }                    .font(CottonFonts.type(width * 0.047))                    .foregroundStyle(MoneyMaterial.posting.colour)                    .padding(.bottom, width * 0.12)                }                .background {                    GeometryReader { paper in                        MoneyPaper(name: "receipt-paper", size: paper.size, reach: ReceiptFaceKnobs.shadowReach,                                   standIn: MoneyMaterial.receipt.colour, corner: 0)                    }                }                .frame(width: width)                .padding(.vertical, 16)                .frame(maxWidth: .infinity)            }            .accessibilityIdentifier("receipt-opened")        }    }}enum ReceiptOpenedReading {    static func stamp(_ card: DeckCard) -> String? {        for slot in ["state", "note"] {            if let value = card.stored[slot], ["proposed", "expected", "posted", "estimate"].contains(value) {                return ShellLines.line("cards", "opened.stamps." + value)            }        }        return card.text("state")    }}