SPB Git

Repository Public

main.swift 15.2 KB 286 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Sheet9// File             : Packages/FeatureAutomation/Sources/automation-preview/main.swift10// Module           : automation-preview11// Repository       : https://git.spboucher.ai/orix-sheet12// Created          : 2026-11-2113// Last Modified    : 2026-11-2114//15// =============================================================================16// AUTHOR & PROFESSIONAL AFFILIATION17// =============================================================================18//19// Author           : Simon-Pierre Boucher20// Position         : Professor of Finance21// Institution      : Université du Québec en Outaouais (UQO)22// Department       : Département des sciences administratives23// Organization     : SP Boucher24//25// Website          : https://spboucher.ai26// Git              : https://git.spboucher.ai27//28// =============================================================================29// OFFICIAL CONTACT DIRECTORY30// =============================================================================31//32// General          : info@spboucher.ai33// Professional     : contact@spboucher.ai34// Direct           : simon@spboucher.ai35// Research         : research@spboucher.ai36// Development      : dev@spboucher.ai37// Support          : support@spboucher.ai38// Security/Admin   : admin@spboucher.ai39// Notifications    : notifications@spboucher.ai40//41// Preferred Contact: support@spboucher.ai42//43// =============================================================================44// COPYRIGHT & INTELLECTUAL PROPERTY45// =============================================================================46//47// Copyright (c) 202648// Simon-Pierre Boucher49//50// All rights reserved where applicable.51//52// This file is governed by the applicable project license,53// copyright notices, institutional agreements and relevant law.54//55// Unless expressly authorized by the applicable license or56// rights holder, copying, redistribution, sublicensing,57// publication and commercial exploitation are not permitted.58//59// Existing third-party rights and notices remain unaffected.60//61// =============================================================================62// CONFIDENTIALITY & SECURITY63// =============================================================================64//65// Classification   : Public66// Distribution     : Public repository; use is governed by the project license67// Security Contact : admin@spboucher.ai68//69// Access to this source does not independently grant permission70// to redistribute or disclose confidential materials.71//72// Do not embed credentials, private keys, access tokens,73// certificates or confidential personal information.74//75// =============================================================================76// LICENSE & MAINTENANCE77// =============================================================================78//79// License          : None specified (no license file in this repository)80// Maintainer       : Simon-Pierre Boucher81// Technical Contact: dev@spboucher.ai82//83// =============================================================================84// END OF SP BOUCHER SOURCE HEADER85// =============================================================================8687import AppKit88import SwiftUI89import SheetCore90import SheetEngine91import SheetIO92import SheetUI93import SheetAutomation94import FeatureAutomation9596// Development harness of the Automation studio.97//   automation-preview [--state editor|running|finished|history|schedule] [--shot out.png] [--dark] [--size WxH] [--compact] [--fr]98// Everything is synthetic: sample files are generated in a temporary folder, and Application Support is redirected99// there, so the user's workflow library, history and approvals are never touched.100// With --shot the window content is rendered to a PNG by the app itself and the process exits.101102let demoCategories = ["Housing", "Groceries", "Transport", "Leisure", "Utilities"]103let demoRegions = ["North", "South", "East", "West"]104105func demoRows(_ count: Int, seed: UInt64) -> [[String]] {106    var state = seed107    func next(_ n: Int) -> Int { state = state &* 6364136223846793005 &+ 1442695040888963407; return Int((state >> 33) % UInt64(n)) }108    return (0..<count).map { i in109        ["2026-\(String(format: "%02d", 9 + i % 3))-\(String(format: "%02d", 1 + next(27)))", demoRegions[next(4)], demoCategories[next(5)], "\(40 + next(900)).\(String(format: "%02d", next(100)))"]110    }111}112113@MainActor func demoSession() -> WorkbookSession {114    ORIXEngine.bootstrap()115    let wb = Workbook(sheetNames: ["Sales", "Summary"])116    let session = WorkbookSession(workbook: wb, locale: Locale(identifier: "en_US"))117    session.perform("Demo") { e in118        let parser = InputParser(locale: Locale(identifier: "en_US_POSIX"))119        for (c, h) in ["date", "region", "category", "amount"].enumerated() { e.set(sheet: 0, row: 0, col: c, .value(.text(h))) }120        for (r, row) in demoRows(48, seed: 7).enumerated() { for (c, text) in row.enumerated() { try? e.setInput(sheet: 0, row: r + 1, col: c, text, parser: parser) } }121        e.setStyle(sheet: 0, range: RangeRef(a1: "A1:D1")!) { $0.bold = true }122        e.setStyle(sheet: 0, range: RangeRef(a1: "D2:D49")!) { $0.numberFormat = "#,##0.00" }123    }124    session.select(RangeRef(a1: "A1:D49")!, active: CellRef(a1: "A1")!)125    return session126}127128func writeCSV(_ url: URL, rows: Int, seed: UInt64) {129    let lines = ["date,region,category,amount"] + demoRows(rows, seed: seed).map { $0.joined(separator: ",") }130    try? Data((lines.joined(separator: "\n") + "\n").utf8).write(to: url)131}132133@MainActor final class Demo {134    let root: URL135    let session: WorkbookSession136    let model: AutomationModel137    var reportID = UUID()138139    init() {140        root = FileManager.default.temporaryDirectory.appendingPathComponent("orix-automation-preview-\(UUID().uuidString)", isDirectory: true)141        let data = root.appendingPathComponent("Reports", isDirectory: true), inbox = data.appendingPathComponent("Inbox", isDirectory: true)142        try? FileManager.default.createDirectory(at: inbox, withIntermediateDirectories: true)143        WorkflowPaths.supportDirectory = root.appendingPathComponent("Support", isDirectory: true)144        writeCSV(data.appendingPathComponent("sales-2026.csv"), rows: 160, seed: 11)145        for (i, name) in ["north.csv", "south.csv", "east.csv", "west.csv"].enumerated() { writeCSV(inbox.appendingPathComponent(name), rows: 30 + i * 6, seed: UInt64(20 + i)) }146147        // library: a report on the open workbook with a nested batch, and a copy of a template148        let report = Workflow(name: "Weekly sales report", summary: "Clean the Sales sheet, summarise it by category, chart it, check the totals, convert the regional exports and publish a PDF.",149            parameters: [WorkflowParameter(name: "inbox", label: "Regional exports", kind: .folder, defaultValue: inbox.path),150                         WorkflowParameter(name: "output", label: "Report", kind: .file, defaultValue: data.appendingPathComponent("weekly-{{date}}.pdf").path)],151            steps: [152                WorkflowItem(.cleanRange(CleanRangeSettings(range: "Sales!*", parseNumbers: true, removeDuplicates: true))),153                WorkflowItem(.createPivot(CreatePivotSettings(range: "Sales!*", rows: ["category"], columns: ["region"], values: ["sum(amount)"], sheet: "By category", name: "By category"))),154                WorkflowItem(.formatRange(FormatRangeSettings(range: "By category!B:F", numberFormat: "#,##0", columnWidth: 86))),155                WorkflowItem(.createChart(CreateChartSettings(range: "By category!A1:E6", kind: "column", title: "Sales by category and region", name: "Sales chart", sheet: "By category", anchor: "A10", width: 520, height: 280))),156                WorkflowItem(.validate(ValidateSettings(noErrorValues: true, requiredCells: ["By category!A2:B2"], mustBeTrue: ["=SUM(Sales!D:D)>0"]))),157                WorkflowItem(.forEachFile(ForEachFileSettings(folder: "{{inbox}}", pattern: "*.csv", steps: [158                    WorkflowItem(.openWorkbook(OpenWorkbookSettings(path: "{{input}}"))),159                    WorkflowItem(.exportFile(ExportFileSettings(path: "{{inbox}}/xlsx/{{input.basename}}.xlsx"))),160                ])), onError: .continue),161                WorkflowItem(.exportPDF(ExportPDFSettings(path: "{{output}}", sheets: ["By category"]))),162            ])163        reportID = report.id164        try? WorkflowStore.saveToLibrary(report)165        WorkflowTrust.approve(report)166        let convert = WorkflowTemplates.batchConvert.duplicated(name: "Convert the inbox")167        try? WorkflowStore.saveToLibrary(convert)168        WorkflowTrust.approve(convert)169170        session = demoSession()171        // a workflow that came with the workbook: listed, never run, not approved172        let embedded = Workflow(name: "Month-end checks", summary: "Checks that the model has no error value before the books are closed.",173                                [.recalculate(RecalculateSettings()), .validate(ValidateSettings(noErrorValues: true, auditFailOn: .error)),174                                 .exportFile(ExportFileSettings(path: data.appendingPathComponent("month-end.xlsx").path))])175        try? WorkflowStore.save(embedded, to: session.workbook)176        session.studioPane = AutomationFeature.paneID177        session.showSidebar = false178        session.inspectorPane = nil179        model = AutomationFeature.model(for: session)180        model.baseDirectory = data181    }182183    var csv: String { root.appendingPathComponent("Reports/sales-2026.csv").path }184185    /// Real runs, so that the history shows real results (one of them fails on purpose).186    func seedHistory() async {187        if let t = WorkflowTemplates.all.first(where: { $0.name == "Monthly report" }) {188            model.select(t.id, .template)189            await model.runSelected(values: ["data": csv, "period": "2026-10"])190            await model.runSelected(values: ["data": csv, "period": "2031-01"])191        }192        if let convert = model.libraryFlows.first(where: { $0.name == "Convert the inbox" }) {193            model.select(convert.id, .library)194            await model.runSelected(values: ["folder": root.appendingPathComponent("Reports/Inbox").path])195        }196    }197198    func prepare(_ state: String) async {199        switch state {200        case "running":201            // a long query keeps the run in flight while the screenshot is taken202            let slow = Workflow(name: "Quarterly consolidation", [203                .rangeToDataset(RangeToDatasetSettings(range: "Sales!*", name: "sales")),204                .runSQL(RunSQLSettings(sql: "SELECT region, category, sum(amount) AS total FROM sales GROUP BY ALL ORDER BY 1, 2", output: .sheet("Consolidated"))),205                .runSQL(RunSQLSettings(sql: "SELECT count(*) AS n FROM range(60000000000) t(i) WHERE hash(i) % 7 = 3", output: .dataset("stress"))),206                .createChart(CreateChartSettings(range: "Consolidated!*", name: "Totals")),207                .exportPDF(ExportPDFSettings(path: "consolidated.pdf")),208            ])209            try? WorkflowStore.saveToLibrary(slow)210            WorkflowTrust.approve(slow)211            model.reload()212            model.select(slow.id, .library)213            model.runsOnOpenWorkbook = true214            Task { await model.runSelected() }215        case "finished":216            if let t = WorkflowTemplates.all.first(where: { $0.name == "CSV report" }) {217                model.select(t.id, .template)218                await model.runSelected(values: ["source": csv, "category": "category", "value": "amount"])219            }220        case "history":221            await seedHistory()222            model.select(reportID, .library)223            model.tab = .history224            model.selectedRunID = model.history.first { $0.status == .failed }?.id ?? model.history.first?.id225        case "schedule":226            if let convert = model.libraryFlows.first(where: { $0.name == "Convert the inbox" }) {227                model.select(convert.id, .library)228                model.parameterValues[convert.id] = ["folder": root.appendingPathComponent("Reports/Inbox").path]229            }230            model.schedule.kind = .weekdays231            model.schedule.hour = 6; model.schedule.minute = 30232            model.tab = .schedule233        default:234            model.select(reportID, .library)235            model.selectedPath = [1]236            model.tab = .editor237        }238    }239}240241final class AppDelegate: NSObject, NSApplicationDelegate {242    var window: NSWindow!243    var demo: Demo!244245    func applicationDidFinishLaunching(_ notification: Notification) {246        let args = CommandLine.arguments247        func value(_ flag: String) -> String? { args.firstIndex(of: flag).flatMap { $0 + 1 < args.count ? args[$0 + 1] : nil } }248        var size = NSSize(width: 1360, height: 860)249        if let s = value("--size")?.split(separator: "x").compactMap({ Double($0) }), s.count == 2 { size = NSSize(width: s[0], height: s[1]) }250        if args.contains("--dark") { NSApp.appearance = NSAppearance(named: .darkAqua) }251        if args.contains("--fr") { AutomationStrings.forceLanguage("fr-CA") }252        AutomationFeature.register()253        demo = Demo()254        if args.contains("--compact") { demo.session.showSidebar = true; demo.session.inspectorPane = "format" }255        let state = value("--state") ?? "editor"256        window = NSWindow(contentRect: NSRect(origin: .zero, size: size), styleMask: [.titled, .closable, .resizable, .miniaturizable], backing: .buffered, defer: false)257        window.title = "ORIX Sheet — Automation preview"258        window.contentView = NSHostingView(rootView: WorkbookView(session: demo.session))259        window.center()260        window.makeKeyAndOrderFront(nil)261        NSApp.activate(ignoringOtherApps: false)262        let shot = value("--shot")263        Task { @MainActor in264            await self.demo.prepare(state)265            guard let out = shot else { return }266            try? await Task.sleep(nanoseconds: state == "running" ? 1_300_000_000 : 900_000_000)267            guard let view = self.window.contentView, let rep = view.bitmapImageRepForCachingDisplay(in: view.bounds) else { exit(2) }268            view.cacheDisplay(in: view.bounds, to: rep)269            try? FileManager.default.createDirectory(at: URL(fileURLWithPath: out).deletingLastPathComponent(), withIntermediateDirectories: true)270            try? rep.representation(using: .png, properties: [:])?.write(to: URL(fileURLWithPath: out))271            if let run = self.demo.model.lastRun { print("last run: \(run.workflowName) \(run.status.rawValue) — \(run.message)") }272            self.demo.model.stop()273            try? FileManager.default.removeItem(at: self.demo.root)274            exit(0)275        }276    }277    func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { true }278    func applicationWillTerminate(_ notification: Notification) { MainActor.assumeIsolated { try? FileManager.default.removeItem(at: demo.root) } }279}280281let app = NSApplication.shared282let delegate = AppDelegate()283app.delegate = delegate284app.setActivationPolicy(CommandLine.arguments.contains("--shot") ? .accessory : .regular)285app.run()286
Files main
Menu

Theme