/* catcrafts.net Copyright (C) 2026 Catcrafts The source code of this website is made available for viewing purposes only. No permission is granted to copy, modify, distribute, or create derivative works. */ // Order storage: an append-only JSON-lines event log. // // Four event types share the file: // // {"type":"order", ...full record...} written once, at checkout // {"type":"status", "id":..,"status":..} one per transition // {"type":"invoice", "id":..,"number":..} the number assignment, at paid // {"type":"notified","id":..,"what":..} the confirmation email left // // New keys on the order event are additive: the fold defaults anything absent, // so a ledger written by an older build still reads correctly under a newer // one. That property is the reason nothing here is ever rewritten in place. // // Current state is a left fold over the file; later events win. Nothing is // ever rewritten, so the log doubles as the audit trail the tax records need, // and a crash mid-write costs at most its own line (a truncated last line is // skipped by the reader, not fatal, and the next event starts a line of its // own rather than being written onto the end of the broken one). // // The fold is held in memory and redone only when the file changes, so a // request costs a stat and a lookup, not a parse of the whole history. The // file stays the one source of truth: an append from the CLI or an edit by // hand is noticed on the next call (see Ledger, below). // // Why not SQLite yet: single-digit orders per week, one writer, no relations. // The day volume proves that wrong, this imports into a database in one // sitting. What this file holds is personal data (name, address, email), so // the same rules as ever: 0600 via the service's umask, off the web root, // encrypted before any backup leaves the machine. module; module Catcrafts.Server; import std; import Catcrafts.Shared; namespace Catcrafts::Server { namespace { std::mutex gOrdersMutex; std::filesystem::path gOrdersPath; // Minimal JSON string escaping. Values were validated upstream, but they are // still user input, and a raw newline or quote would corrupt the // line-per-record format — silently truncating the data on the next read. std::string JsonEscape(std::string_view s) { std::string out; out.reserve(s.size() + 8); for (const char c : s) { switch (c) { case '"': out += "\\\""; break; case '\\': out += "\\\\"; break; case '\n': out += "\\n"; break; case '\r': out += "\\r"; break; case '\t': out += "\\t"; break; default: if (static_cast(c) < 0x20) { out += std::format("\\u{:04x}", static_cast(c)); } else { out += c; } } } return out; } // A reference as a transfer is matched: upper-case letters and digits, nothing // else. Two references that reduce to the same thing are one reference to the // bank-transfer rail, so that is the form uniqueness is decided in. std::string ReferenceKey(std::string_view reference) { std::string out; out.reserve(reference.size()); for (const char c : reference) { if (c >= '0' && c <= '9') out += c; else if (c >= 'A' && c <= 'Z') out += c; else if (c >= 'a' && c <= 'z') out += static_cast(c - 'a' + 'A'); } return out; } // ── the fold, kept ──────────────────────────────────────────────────── // // The ledger folded into its current state, held in memory between calls and // folded again only when the FILE changes underneath it. // // It used to be folded from disk on every call: every order page, every // /financials request, every reconciler sweep, and every two seconds for the // mailer. And each event found its order by walking the orders so far, so the // fold was quadratic. Neither mattered at a dozen orders. But anyone can add // orders, and a ledger of 40 000 took twelve seconds to fold (measured // 2026-11-26), on a path a visitor can hit as often as they like while the // ledger lock is held. So: orders are found through an index, which makes a // fold one pass, and the result is kept. // // Kept, and still never trusted over the file. The file is the ledger; this // is a reading of it. Two things other than this process change the file, and // both have to show up without a restart: `--orders --mark-paid` and its // siblings append from a second process, and an operator edits fields by hand // (the erasure request). So every call asks the file what it looks like now, // one stat, and a different size or modification time means fold it all // again. What this process appends itself is applied to the held fold by the // same code that folds a line from disk, so the two cannot come to mean // different things. struct Ledger { std::vector orders; // in the order placed std::unordered_map byToken; // token -> index in orders std::set references; // ReferenceKey of every order // The file does not end in a line break: its last line was cut short by a // crash mid-write, or it was edited by hand without one. Remembered // because the next append has to start a line of its own (see AppendLine). bool tornTail = false; }; // What the file looked like when it was folded. Size catches every append and // nearly every edit; the modification time catches the edit that keeps the // size, which is what blanking a name in place is. struct FileStamp { bool exists = false; std::uintmax_t size = 0; std::filesystem::file_time_type modified{}; bool operator==(const FileStamp&) const = default; }; Ledger gLedger; FileStamp gLedgerStamp; // gLedger is the fold of the file as gLedgerStamp describes it. False until // the first fold, after SetOrdersPath, and whenever something happened that // leaves that in doubt; the next reader then folds from disk. bool gLedgerCurrent = false; FileStamp StampOf(const std::filesystem::path& path) { FileStamp stamp; if (path.empty()) return stamp; std::error_code ec; // One stat: a directory_entry reads size and time together. const std::filesystem::directory_entry entry(path, ec); if (ec || !entry.is_regular_file(ec) || ec) return stamp; stamp.size = entry.file_size(ec); if (ec) return stamp; stamp.modified = entry.last_write_time(ec); if (ec) return stamp; stamp.exists = true; return stamp; } // Fold ONE line into the ledger. The whole meaning of the file is here, and // it is the only place it is: a fold from disk calls this for every line, and // an append calls it for the line it has just written. A line that is not an // event (corrupt, cut short, blank) changes nothing — one bad line must not // take the rest of the ledger with it. void Apply(Ledger& ledger, std::string_view line) { const auto doc = Json::Parse(line); if (!doc || !doc->IsObject()) return; auto find = [&](std::string_view token) -> OrderRecord* { const auto at = ledger.byToken.find(std::string(token)); return at == ledger.byToken.end() ? nullptr : &ledger.orders[at->second]; }; const std::string_view type = doc->Str("type"); if (type == "order") { OrderRecord r; r.token = std::string(doc->Str("id")); r.reference = std::string(doc->Str("ref")); r.product = std::string(doc->Str("product")); r.color = std::string(doc->Str("color")); r.quantity = doc->Int("quantity", 1); r.unitMinor = doc->Int("unit_minor"); r.createdAt = std::string(doc->Str("at")); r.updatedAt = r.createdAt; r.buyer.email = std::string(doc->Str("email")); r.buyer.name = std::string(doc->Str("name")); r.buyer.street = std::string(doc->Str("street")); r.buyer.postal = std::string(doc->Str("postal")); r.buyer.city = std::string(doc->Str("city")); r.buyer.country = std::string(doc->Str("country")); r.goodsMinor = doc->Int("goods_minor"); r.shippingMinor = doc->Int("shipping_minor"); r.totalMinor = doc->Int("total_minor"); r.vatIncluded = doc->Bool("vat_included"); // Additive key: absent (every pre-donations line) reads false, // so an old ledger's orders all stay sales. r.donation = doc->Bool("donation"); r.status = std::string(doc->Str("status", "awaiting_payment")); // Read as written, with no default applied here: the ledger // should keep saying exactly what it recorded, and resolving an // unexpected value to a rail is PaymentRails::For's single job. r.payChoice = std::string(doc->Str("pay_choice")); r.payUrl = std::string(doc->Str("pay_url")); r.payId = std::string(doc->Str("pay_id")); if (r.token.empty()) return; // A duplicate "order" event for an id would be a writer bug; first // one wins so a replayed line cannot rewrite history. if (find(r.token)) return; ledger.byToken.emplace(r.token, ledger.orders.size()); if (std::string key = ReferenceKey(r.reference); !key.empty()) { ledger.references.insert(std::move(key)); } ledger.orders.push_back(std::move(r)); } else if (type == "invoice") { OrderRecord* r = find(doc->Str("id")); if (!r) return; r->invoiceNumber = std::string(doc->Str("number")); r->invoicedAt = std::string(doc->Str("at")); } else if (type == "notified") { OrderRecord* r = find(doc->Str("id")); if (!r) return; // "what" names the message so a future shipped-notice can share // the event type without re-marking the confirmation as sent. if (doc->Str("what") == "confirmation") { r->confirmationSentAt = std::string(doc->Str("at")); } } else if (type == "status") { OrderRecord* r = find(doc->Str("id")); if (!r) return; // status for an unknown order: nothing to change const std::string_view status = doc->Str("status"); if (status.empty()) return; r->status = std::string(status); r->updatedAt = std::string(doc->Str("at")); if (const std::string_view via = doc->Str("via"); !via.empty()) { r->paidVia = std::string(via); } // The FIRST paid event is the sale, whatever happens later — a // refund folds the status onward but never unhappens the payment // (see SummarizeSales). First, not last, so a replayed line // cannot move the recorded moment. if (status == "paid" && r->paidAt.empty()) { r->paidAt = std::string(doc->Str("at")); } } } // The ledger as the file has it now: the held fold when the file is as it was // folded, a fresh fold from disk otherwise. Called with gOrdersMutex held, // and the reference it returns is good only until the next call that may fold // or append (AppendLine does both), so nothing keeps it across one. const Ledger& CurrentLocked() { const FileStamp before = StampOf(gOrdersPath); if (gLedgerCurrent && before == gLedgerStamp) return gLedger; std::string text; bool read = true; if (before.exists) { std::ifstream in(gOrdersPath, std::ios::binary); if (in) { text.assign(std::istreambuf_iterator(in), std::istreambuf_iterator()); } else { read = false; // there and unreadable: an empty fold, and not kept } } Ledger fresh; for (std::size_t start = 0; start < text.size();) { const std::size_t nl = text.find('\n', start); const std::size_t end = nl == std::string::npos ? text.size() : nl; Apply(fresh, std::string_view(text).substr(start, end - start)); if (nl == std::string::npos) break; start = nl + 1; } fresh.tornTail = !text.empty() && text.back() != '\n'; gLedger = std::move(fresh); // Kept only when the file held still while it was read: the same before // and after, and exactly as many bytes as were folded. A file that // another process was writing at that moment gives this caller what was // read, and the next caller a fresh fold. const FileStamp after = StampOf(gOrdersPath); gLedgerStamp = after; gLedgerCurrent = read && after == before && (after.exists ? after.size == text.size() : text.empty()); return gLedger; } bool AppendLine(const std::string& line) { if (gOrdersPath.empty()) return false; // Fold first if the file moved, so that what is written below can be // applied on top of a fold that matches the file it is appended to. const bool torn = CurrentLocked().tornTail; const bool current = gLedgerCurrent; const std::uintmax_t sizeBefore = gLedgerStamp.exists ? gLedgerStamp.size : 0; // Open per append: orders arrive rarely, and a file reopened each time can // be rotated or edited underneath the running process without a restart. std::ofstream out(gOrdersPath, std::ios::app | std::ios::binary); if (!out) return false; // A file that ends mid-line gets its line break first. Without it this // event would be written onto the end of the broken line and be read as // part of it: a crash that cut one line short would cost the NEXT event // too, and that event is as likely as not somebody's "paid". if (torn) out << '\n'; out << line << '\n'; out.flush(); // Report the stream state: a full disk must surface as a visible error, // not a payment link over an order that was never recorded. if (!out) { gLedgerCurrent = false; // part of the line may be on disk: fold again return false; } out.close(); // Apply the line to the held fold, provided the file grew by exactly what // was written. If it grew by more, another process appended in the same // moment and its line is in there unread: fold from disk next time. const FileStamp after = StampOf(gOrdersPath); const std::uintmax_t wrote = line.size() + 1 + (torn ? 1 : 0); if (current && after.exists && after.size == sizeBefore + wrote) { Apply(gLedger, line); gLedger.tornTail = false; gLedgerStamp = after; } else { gLedgerCurrent = false; } return true; } // References handed out by NewUniqueOrderToken whose order is not in the // ledger yet: the gap between minting a token and CreateOrder writing it, // which is where the payment rail is asked for its link. Guarded by // gOrdersMutex. A checkout that fails in that gap leaves its entry behind // until the process restarts, which costs one reference out of sixteen // million and is not worth a second code path to hand back. std::set gHeldReferences; } // namespace void SetOrdersPath(const std::filesystem::path& p) { std::lock_guard lock(gOrdersMutex); gOrdersPath = p; // Another file, or the same name for a file that has just been replaced: // either way what is held is not a fold of it. gLedger = Ledger{}; gLedgerStamp = FileStamp{}; gLedgerCurrent = false; } bool CreateOrder(const OrderRecord& o) { std::lock_guard lock(gOrdersMutex); // "donation" is written only when true, matching the status writer's // omit-rather-than-empty rule: absent-means-false is what lets a ledger // from before donations existed keep reading correctly. const bool written = AppendLine(std::format( R"({{"type":"order","at":"{}","id":"{}","ref":"{}","product":"{}",)" R"("color":"{}","quantity":{},"unit_minor":{},)" R"("email":"{}","name":"{}","street":"{}","postal":"{}","city":"{}","country":"{}",)" R"("goods_minor":{},"shipping_minor":{},"total_minor":{},"vat_included":{},{})" R"("status":"{}","pay_choice":"{}","pay_url":"{}","pay_id":"{}"}})", JsonEscape(o.createdAt), JsonEscape(o.token), JsonEscape(o.reference), JsonEscape(o.product), JsonEscape(o.color), o.quantity, o.unitMinor, JsonEscape(o.buyer.email), JsonEscape(o.buyer.name), JsonEscape(o.buyer.street), JsonEscape(o.buyer.postal), JsonEscape(o.buyer.city), JsonEscape(o.buyer.country), o.goodsMinor, o.shippingMinor, o.totalMinor, o.vatIncluded, o.donation ? R"("donation":true,)" : "", JsonEscape(o.status), JsonEscape(o.payChoice), JsonEscape(o.payUrl), JsonEscape(o.payId))); // The order is in the ledger now, which is where the next mint looks for // its reference, so the hold NewUniqueOrderToken placed has done its job. // Kept when the write failed: nothing was stored, and handing the same // reference straight to the next checkout would only be confusing in the // log of what went wrong. if (written) gHeldReferences.erase(ReferenceKey(o.reference)); return written; } bool AppendOrderStatus(std::string_view token, std::string_view status, std::string_view isoTimestamp, std::string_view via) { std::lock_guard lock(gOrdersMutex); if (via.empty()) { return AppendLine(std::format( R"({{"type":"status","at":"{}","id":"{}","status":"{}"}})", JsonEscape(isoTimestamp), JsonEscape(token), JsonEscape(status))); } return AppendLine(std::format( R"({{"type":"status","at":"{}","id":"{}","status":"{}","via":"{}"}})", JsonEscape(isoTimestamp), JsonEscape(token), JsonEscape(status), JsonEscape(via))); } namespace { // Case-normalised email: the customer key. Good enough on purpose — a person // with two addresses is two customers, exactly as they would be in the manual // administration this scheme continues. std::string CustomerKey(std::string_view email) { std::string out(email); for (char& c : out) { if (c >= 'A' && c <= 'Z') c = static_cast(c - 'A' + 'a'); } return out; } // A random v4 UUID — the customer number, matching the pre-shop invoice // administration (folders named by customer UUID, invoices -). std::string NewCustomerUuid() { std::random_device rd; std::array w{ rd(), rd(), rd(), rd() }; auto* b = reinterpret_cast(w.data()); b[6] = static_cast((b[6] & 0x0f) | 0x40); // version 4 b[8] = static_cast((b[8] & 0x3f) | 0x80); // variant 10 std::string out; out.reserve(36); static constexpr char hex[] = "0123456789abcdef"; for (int i = 0; i < 16; ++i) { if (i == 4 || i == 6 || i == 8 || i == 10) out += '-'; out += hex[b[i] >> 4]; out += hex[b[i] & 0xf]; } return out; } } // namespace std::optional AssignInvoiceNumber(std::string_view token, std::string_view isoTimestamp) { // Numbering continues the shop owner's existing administration: one // SERIES PER CUSTOMER (a random UUID as customer number), sequential // within it — "f57c6512-…-3" is that customer's third invoice. Multiple // series are what art. 226(2)'s "one or more series" permits, and the // append-only ledger plus the payment provider's records carry the // completeness proof an auditor actually wants. std::lock_guard lock(gOrdersMutex); // `ledger` and `target` are read up to the append at the end and not // after it: the append updates the held fold and may replace it. const Ledger& ledger = CurrentLocked(); const auto at = ledger.byToken.find(std::string(token)); if (at == ledger.byToken.end()) return std::nullopt; const OrderRecord* target = &ledger.orders[at->second]; // Idempotent: a paid order re-processed (manual CLI after the reconciler, // say) keeps its number — a sequence never burns a member on a retry. if (!target->invoiceNumber.empty()) return target->invoiceNumber; // The customer's existing series, if any: same email (case-normalised), // highest sequence. Invoice numbers are "-". const std::string key = CustomerKey(target->buyer.email); std::string customer; std::int64_t maxSeq = 0; for (const OrderRecord& r : ledger.orders) { if (r.invoiceNumber.size() < 38 || CustomerKey(r.buyer.email) != key) continue; customer = r.invoiceNumber.substr(0, 36); std::int64_t seq = 0; const char* b = r.invoiceNumber.data() + 37; std::from_chars(b, r.invoiceNumber.data() + r.invoiceNumber.size(), seq); maxSeq = std::max(maxSeq, seq); } if (customer.empty()) customer = NewCustomerUuid(); const std::string number = std::format("{}-{}", customer, maxSeq + 1); if (!AppendLine(std::format( R"({{"type":"invoice","at":"{}","id":"{}","number":"{}","customer":"{}"}})", JsonEscape(isoTimestamp), JsonEscape(token), JsonEscape(number), JsonEscape(customer)))) { return std::nullopt; } return number; } bool AppendOrderNotified(std::string_view token, std::string_view isoTimestamp) { std::lock_guard lock(gOrdersMutex); return AppendLine(std::format( R"({{"type":"notified","at":"{}","id":"{}","what":"confirmation"}})", JsonEscape(isoTimestamp), JsonEscape(token))); } std::optional FindOrder(std::string_view token) { std::lock_guard lock(gOrdersMutex); const Ledger& ledger = CurrentLocked(); const auto at = ledger.byToken.find(std::string(token)); if (at == ledger.byToken.end()) return std::nullopt; return ledger.orders[at->second]; } std::vector ListOrders() { std::lock_guard lock(gOrdersMutex); return CurrentLocked().orders; } SalesSummary LedgerSales() { std::lock_guard lock(gOrdersMutex); return SummarizeSales(CurrentLocked().orders); } SalesSummary SummarizeSales(std::span orders) { SalesSummary out; for (const OrderRecord& r : orders) { // paidAt is the signal. The status check keeps faith with a ledger // whose order was marked shipped by hand without a paid event ever // being written — the same paid-or-shipped idiom the invoice // download uses. if (r.paidAt.empty() && r.status != "paid" && r.status != "shipped") continue; // A paid donation is income but not a sale: /financials shows it in // the donations row, and counting it here too would double-book it. if (r.donation) { ++out.donationCount; out.donationsMinor += r.totalMinor; continue; } ++out.count; out.totalMinor += r.totalMinor; } return out; } std::string NewOrderToken() { // std::random_device on this platform reads the kernel CSPRNG. The token // gates access to a name and address, so 128 bits — the same order of // unguessability as a session cookie. std::random_device rd; std::string out; out.reserve(32); for (int i = 0; i < 4; ++i) { const std::uint32_t w = rd(); out += std::format("{:08x}", w); } return out; } std::optional NewUniqueOrderToken() { return NewUniqueOrderToken([] { return NewOrderToken(); }); } std::optional NewUniqueOrderToken(const std::function& draw) { std::lock_guard lock(gOrdersMutex); // Every reference the ledger holds, from the held fold: no pass over the // file for a checkout. Nothing below folds or appends, so the reference // stays good for the loop. const std::set& taken = CurrentLocked().references; // A draw collides with probability (orders ever placed) / 2^24, so even a // ledger of a million orders gets through in a couple of draws. The bound // is there so that a ledger too full to mint for ends in an honest // refusal at checkout instead of a loop. for (int i = 0; i < kUniqueTokenDraws; ++i) { std::string token = draw(); std::string key = ReferenceKey(ReferenceFromToken(token)); if (taken.contains(key) || gHeldReferences.contains(key)) continue; gHeldReferences.insert(std::move(key)); return token; } return std::nullopt; } bool ReferenceInUse(std::string_view reference) { std::lock_guard lock(gOrdersMutex); const std::string key = ReferenceKey(reference); if (key.empty()) return false; return gHeldReferences.contains(key) || CurrentLocked().references.contains(key); } std::string ReferenceFromToken(std::string_view token) { // Derived, not random: an order can never carry a mismatched pair. Six hex // chars is what a human will actually type into a transfer description; at // this volume a collision is a curiosity, and the amount+time still // disambiguate at reconciliation. std::string out = "CC-"; for (std::size_t i = 0; i < 6 && i < token.size(); ++i) { char c = token[i]; if (c >= 'a' && c <= 'z') c = static_cast(c - 'a' + 'A'); out += c; } return out; } namespace { // ISO 7064 mod-97-10 over an alphanumeric string, the same arithmetic that // checks an IBAN: letters become two digits (A=10 … Z=35), everything is read // as one long decimal number, and the remainder mod 97 is taken. Folded // incrementally so no big-integer type is needed — the running value never // exceeds 97*100+35, which fits an int comfortably. // // Returns nullopt on any character that is not [0-9A-Z], because silently // skipping one would make two different references check out identically. std::optional Mod97(std::string_view s) { int rem = 0; for (const char c : s) { if (c >= '0' && c <= '9') { rem = (rem * 10 + (c - '0')) % 97; } else if (c >= 'A' && c <= 'Z') { const int v = c - 'A' + 10; rem = (rem * 100 + v) % 97; } else { return std::nullopt; } } return rem; } // The body an RF reference carries: the CC- reference with its hyphen dropped, // because ISO 11649 permits only alphanumerics. "CC-2B6457" -> "CC2B6457". std::string ReferenceBody(std::string_view token) { const std::string human = ReferenceFromToken(token); std::string body; body.reserve(human.size()); for (const char c : human) { if (c != '-') body += c; } return body; } } // namespace std::string CreditorReferenceFromToken(std::string_view token) { const std::string body = ReferenceBody(token); // The check digits are computed over the body followed by "RF00" — the // standard's rearrangement, prefix and placeholder moved to the end. const std::optional rem = Mod97(body + "RF00"); if (!rem) return {}; // unreachable for our own token alphabet const int check = 98 - *rem; return std::format("RF{:02}{}", check, body); } bool IsValidCreditorReference(std::string_view s) { // "RF" + 2 check digits + 1..21 body characters. if (s.size() < 5 || s.size() > 25) return false; if (s[0] != 'R' || s[1] != 'F') return false; if (s[2] < '0' || s[2] > '9' || s[3] < '0' || s[3] > '9') return false; // Rearranged the same way the generator does it, then the whole thing must // leave a remainder of exactly 1 — that is what mod-97-10 verification is. std::string rearranged(s.substr(4)); rearranged += s.substr(0, 4); const std::optional rem = Mod97(rearranged); return rem && *rem == 1; } } // namespace Catcrafts::Server