import CottonKit import Foundation /// A business's object through the core, as `business.*` answers /// (`crates/cotton-ffi/src/phone/business.rs`): a synthetic studio whose /// pages follow the role the last sync or sign-in left, a booking made by /// `book` once someone is signed in, and refusals on demand. Every request is /// kept as it was sent. final class BusinessFake: CottonCalling, @unchecked Sendable { static let server = "https://cotton-business.synthetic.workers.dev" static let address = BusinessAddress(server: server, slug: "studio") /// A business app's manifest, as one shipped (no business app ships now): /// it founds nothing and names its business's object. static func manifest(_ slug: String) -> String { #"{"genesis":"none","flavour":"\#(slug)","name":"Synthetic Kitchen","databases":"single","fan":{"tools":false},"tools":["people","messages","kitchen"],"business":{"server":"\#(server)","slug":"\#(slug)"}}"# } static let photos = server + "/b/studio/v1/photos/" static let credential = "synthetic.business.credential.c2hlbGwy" /// The database the open host names for every number here. static let database = "11111111-1111-4111-8111-111111111111" private let lock = NSLock() private var _asked: [(method: String, body: String)] = [] var asked: [(method: String, body: String)] { lock.withLock { _asked } } /// What the cache was last synced or signed in as. var role = "public" var booked = false /// The code the next call of a method is refused with, once. var refuseOnce: [String: String] = [:] /// The record pick an act asks (`shell.opened {step: pick, business}`): /// its `step` as the core answers it; nil asks the places stepper. var pickStep: String? /// Rows a person made on the phone's own local database: a connect /// answers that their adopt started (`personal.adopt`). var adoptRows: Int? /// What `personal.adoptStatus` answers, one each time it is asked (the /// last again once they run out). var adoptStatuses: [String] = [] /// A synced sync that carries a credential is refused as revoked. var revoked = false /// The number has no account yet: a sign-in that says `nameAfter` and gives no name is answered `nameNeeded`. var newAccount = false /// Held until `release()`: the next sync. var holdsSync = false private var held: CheckedContinuation? private var arrived: CheckedContinuation? private var syncWaiting = false /// A number's stepper as the core says it (`shell_input::number_rows`). private static func places(count: Double) -> String { let down = count > 1 ? [#"{"value":"down-1","words":"−1","does":"count","count":\#(count - 1)}"#] : [] let rows = down + [#"{"value":"\#(Int(count))","words":"\#(Int(count))","does":"answer"}"#, #"{"value":"up-1","words":"+1","does":"count","count":\#(count + 1)}"#] return #"{"kind":"pick","label":"Places","index":0,"rest":\#(down.count),"writes":{"kind":"business_pick","answers":[],"of":1},"rows":[\#(rows.joined(separator: ","))]}"# } func requests(_ method: String) -> [[String: JSONValue]] { asked.filter { $0.method == method }.compactMap { try? JSONDecoder().decode([String: JSONValue].self, from: Data($0.body.utf8)) } } func callRaw(_ method: String, requestJSON: String) async throws -> String { lock.withLock { _asked.append((method, requestJSON)) } let request = (try? JSONDecoder().decode([String: JSONValue].self, from: Data(requestJSON.utf8))) ?? [:] let signed = request["credential"]?.string == Self.credential if let code = lock.withLock({ refuseOnce.removeValue(forKey: method) }) { return Self.refusal(code) } switch method { case CottonMethod.shellOpened: var count = 1.0 if case .number(let asked)? = request["count"] { count = asked } return Self.ok(#"{"step":\#(pickStep ?? Self.places(count: count))}"#) case CottonMethod.shellInput: return Self.ok(#"{"answers":["\#(request["words"]?.string ?? "")"]}"#) case CottonMethod.businessSync: if holdsSync { await withCheckedContinuation { gate in lock.withLock { held = gate syncWaiting = true arrived?.resume() arrived = nil } } } if signed, revoked { return Self.refusal("credential_revoked") } if !signed { role = "public" } let person = signed ? Self.person(role) : "null" return Self.ok(#"{"version":3,"changed":4,"role":"\#(role)","person":\#(person),"business":{"slug":"studio","name":"Synthetic Studio"}}"#) case CottonMethod.businessPages: return Self.ok(Self.pages(role: role, booked: booked)) case CottonMethod.businessCode: return Self.ok(#"{"challengeId":"ch-1","expiresIn":300,"sentTo":"We sent a code by text message to +1 ••••••••23."}"#) case CottonMethod.businessSignIn: if newAccount, request["nameAfter"]?.bool == true, (request["name"]?.string ?? "").isEmpty { return Self.ok(#"{"nameNeeded":true}"#) } role = "member" return Self.ok(#"{"credential":"\#(Self.credential)","person":\#(Self.person("member")),"expiresIn":7776000}"#) case CottonMethod.personalCode: return Self.ok(#"{"challengeId":"ch-1","expiresIn":300,"known":false,"databaseId":"\#(Self.database)","sentTo":"We sent a code by text message to +1 ••••••••23."}"#) case CottonMethod.personalSignIn: guard request["databaseId"]?.string == Self.database else { return Self.refusal("no_such_database") } if newAccount, request["nameAfter"]?.bool == true, (request["name"]?.string ?? "").isEmpty { return Self.ok(#"{"nameNeeded":true}"#) } return Self.ok(#"{"credential":"\#(Self.credential)","person":\#(Self.person("owner")),"expiresIn":7776000,"databaseId":"\#(Self.database)"}"#) case CottonMethod.personalConnect: guard signed else { return Self.refusal("not_signed_in") } guard request["databaseId"]?.string == Self.database else { return Self.refusal("wrong_database") } if let rows = adoptRows { return Self.ok(#"{"adopt":{"status":"started","rows":\#(rows)}}"#) } return Self.ok(#"{"databaseId":"\#(Self.database)","ownerId":"p1"}"#) case CottonMethod.personalAdoptStatus: let said = lock.withLock { adoptStatuses.count > 1 ? adoptStatuses.removeFirst() : (adoptStatuses.first ?? #"{"status":"none","sent":0,"rows":0,"refused":0}"#) } return Self.ok(#"{"adopt":\#(said)}"#) case CottonMethod.personalStandLocal: return Self.ok(#"{}"#) case CottonMethod.personalRemove: return Self.ok(#"{"removed":"\#(Self.database)"}"#) case CottonMethod.businessSignOut: role = "public" return Self.ok(#"{"ok":true}"#) case CottonMethod.businessAct: guard signed else { return Self.refusal("not_signed_in") } if request["act"]?.string == "book" { booked = true } if request["act"]?.string == "cancel" { booked = false } return Self.ok(#"{"version":5,"changed":[{"table":"yoga_booking","id":"b1","deleted":true}]}"#) default: return Self.refusal("unknown_method") } } /// Until the held sync has been asked. func syncAsked() async { await withCheckedContinuation { gate in lock.withLock { if syncWaiting { gate.resume() } else { arrived = gate } } } } func release() { lock.withLock { held?.resume(); held = nil; holdsSync = false } } func subscribe(_ handler: @escaping @Sendable (CottonEvent) -> Void) {} func close() {} static func ok(_ data: String) -> String { #"{"ok":true,"data":\#(data)}"# } static func refusal(_ code: String) -> String { #"{"ok":false,"error":{"code":"\#(code)","message":"the object said \#(code)"}}"# } static func person(_ role: String) -> String { #"{"id":"p1","phone":"+15550100123","name":"Anita","role":"\#(role)"}"# } /// Book on a session, its quantity the one pick. static func book(_ slot: String) -> String { #"{"id":"book","label":"Book","kind":"command","rank":"main","primary":true,"red":false,"act":"book","args":{"slot":"\#(slot)"},"picks":[{"argument":"quantity","kind":"number","label":"Places","min":1,"default":1}]}"# } static let cancel = #"{"id":"cancel","label":"Cancel","kind":"command","rank":"away","primary":false,"red":true,"confirm":"Cancel this booking?","act":"cancel","args":{"id":"b1"},"picks":[]}"# static func session(_ id: String, _ title: String, _ line: String) -> String { #"{"table":"yoga_session","id":"\#(id)","title":"\#(title)","line":"\#(line)","owner":null,"data":{"name":"\#(title)","capacity":10,"@card":{"face":"event","corner":"\#(line)","fields":{"title":"\#(title)"}}},"acts":[\#(book(id))]}"# } /// The pages a role reads: the public views, a member's own beside them, /// staff's members view beside those. static func pages(role: String, booked: Bool) -> String { var yoga = [ #"{"id":"yoga_session","label":"Today","visibility":"public","is_default":true,"face":null,"table":"yoga_session","count":1,"rows":[\#(session("s1", "Morning hatha", "07:00"))]}"#, #"{"id":"next","label":"Tomorrow","visibility":"public","is_default":false,"face":null,"table":"yoga_session","count":1,"rows":[\#(session("s2", "Vinyasa", "18:00"))]}"#, ] if role != "public" { let booking = booked ? #"{"table":"yoga_booking","id":"b1","title":"Morning hatha","line":"07:00","owner":"p1","data":{"name":"Morning hatha","session":"s1"},"acts":[\#(cancel)]}"# : "" yoga.append(#"{"id":"mine","label":"My bookings","visibility":"customer","table":"yoga_booking","count":\#(booked ? 1 : 0),"rows":[\#(booking)]}"#) } if role == "staff" || role == "owner" { yoga.append(#"{"id":"members","label":"Members","visibility":"staff","table":"yoga_member","count":1,"rows":[{"table":"yoga_member","id":"m1","title":"Anita","data":{"name":"Anita"},"acts":[]}]}"#) } let studio = #"{"id":"studio","label":"Studio","visibility":"public","table":"yoga_place","count":1,"rows":[{"table":"yoga_place","id":"p1","title":"Invented Studio","line":null,"data":{"name":"Invented Studio","photo":"studio/hall.jpg","@card":{"face":"sharmila.studio","fields":{"title":"Invented Studio","photo":"studio/hall.jpg"}}},"acts":[]}]}"# return #""" {"business":{"slug":"studio","name":"Synthetic Studio","currency":"INR","timezone":"Asia/Kolkata"},"role":"\#(role)","person":\#(role == "public" ? "null" : person(role)),"version":3,"photos":"\#(photos)","tools":[ {"tool":"yoga","name":"Yoga","picture":"yoga","card_stock":"sage","views":[\#(yoga.joined(separator: ","))]}, {"tool":"yoga_studio","name":"Studio","picture":null,"card_stock":null,"views":[\#(studio)]}]} """# } }