// SPDX-License-Identifier: GPL-3.0-only // SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® module Nostro.App:App_impl; import std; import Nostro; import Nostro.Ui; import :App; import :Banks; import :Format; import :Forms; import :Errors; // The app's side that is not drawing: what nostrod is asked and what its answers change, where the user goes, and // what each thing they ask for does. The screens are in Nostro.App-Screens.cpp, and what connecting to a bank takes // in a file of that bank's own. Nothing here names a bank: what is a bank's own it asks :Banks for. namespace Nostro::App { App::App(Ui::Context& context, Host host) : context(context), host(std::move(host)) { } void App::Start() { Refresh(); } bool App::Busy() const noexcept { return changing || std::ranges::any_of(lanes, [](const auto& lane) { return lane.second.busy; }); } bool App::Changing() const noexcept { return changing; } const Loadable>& App::Overview() const noexcept { return overview; } std::string_view App::OAuthState() const noexcept { return bunqOAuth.state; } std::chrono::system_clock::time_point App::Today() const { return host.now ? host.now() : std::chrono::system_clock::now(); } // -- nostrod ----------------------------------------------------------------------------------------------------- Client& App::Nostrod() { if(!client) { Reconnect(); } else if(!client->Connected()) { // The connection to the system bus broke. Every call it carried is answered with an error by the library // before it reports the break, each in its own turn of the loop: until the last of them has been, the old // connection is kept, and what is asked meanwhile fails like them. if(Busy()) { throw std::system_error(std::make_error_code(std::errc::not_connected), "the connection to the system bus broke"); } Reconnect(); } return *client; } void App::Reconnect() { client.reset(); try { client.emplace(host.connect()); } catch(const std::exception& e) { throw NoSystemBus(e.what()); } } void App::Note(const std::vector& more) { for(const std::string& note : more) { if(!std::ranges::contains(notes, note)) { notes.push_back(note); } } } void App::Answered(std::string_view member, bool failed) { if(onAnswer) { onAnswer(member, failed); } } template void App::Fetch(std::string name, std::string member, std::function)> start, std::function)> then) { std::function run = [this, name, member = std::move(member), start = std::move(start), then = std::move(then)] { Lane& lane = lanes[name]; try { // The connection first: whether it can be made anew depends on what is still waited for, and this is not. Client& bank = Nostrod(); lane.busy = true; lane.pending = start(bank, [this, name, member, then](Answer answer) { // The lane is free before the answer is used: what the answer leads to may ask again. Lane& answered = lanes[name]; answered.busy = false; const std::function next = std::exchange(answered.next, nullptr); const bool failed = answer.Failed(); Note(answer.notes); then(std::move(answer)); if(next) { next(); } context.Invalidate(); // Told last: whoever listens finds the app as the answer left it. Answered(member, failed); }); } catch(...) { // The call could not be made: there is no connection to the system bus. lane.busy = false; then(Answer{std::variant(std::in_place_index<1>, std::current_exception()), {}}); context.Invalidate(); } }; Lane& lane = lanes[name]; if(lane.busy) { lane.next = std::move(run); } else { run(); } } template void App::Change(Operation operation, std::string member, std::string title, std::string account, std::function)> start, std::function done) { Wait(std::move(title)); try { Client& bank = Nostrod(); changing = true; change = start(bank, [this, operation, member, account, done = std::move(done)](Answer answer) { changing = false; const bool failed = answer.Failed(); Note(answer.notes); if(failed) { Failed(Explain(answer.Error(), operation), operation, account); } else { try { done(answer.Get()); } catch(const std::exception& e) { // It was done, and what came of it is not what was asked for: a card the bank kept as it was. Failed(Guidance{Problem::Failed, "That did not work", e.what(), false, false}, operation, account); } } context.Invalidate(); Answered(member, failed); if(onSettled) { onSettled(); } }); } catch(...) { // Nothing was sent: there is no connection to the system bus, which is told as any reading's failure is. changing = false; Failed(Explain(std::current_exception(), Operation::Load), Operation::Load, account); } } // The wait for a change's answer, which is where the user confirms it: as nostro is shipped, every change asks for // their password. Where an administrator's rule lets one pass, the answer is there before this is read. void App::Wait(std::string title) { Dialog working; working.kind = Dialog::Kind::Working; working.name = "working"; working.title = std::move(title); working.text = {"Confirm it in your system's password dialog."}; Show(std::move(working)); } void App::Failed(const Guidance& guidance, Operation operation, const std::string& account) { Dialog problem; problem.kind = Dialog::Kind::Problem; problem.name = "problem"; problem.title = guidance.title; problem.text = {guidance.detail}; if(guidance.problem == Problem::OwnAccountsOnly && operation == Operation::Send) { problem.choices.push_back({"problem.draft", "Save as a draft instead", Ui::ButtonKind::Filled, true, {}, [this] { // What is still in the form, as a draft: the press is the asking for it. dialog.reset(); payment.when = When::Draft; SubmitPayment(); }}); } if(guidance.mayHaveHappened && !account.empty()) { problem.choices.push_back({"problem.activity", "Show the account's activity", Ui::ButtonKind::Filled, true, {}, [this, account] { dialog.reset(); stack.clear(); place = Place::Accounts; Data(account).tab = Tab::Activity; Push(Page::Account, account); }}); } problem.choices.push_back({"problem.close", "Close", Ui::ButtonKind::Tonal, true, {}, [this] { Close(); }}); Show(std::move(problem)); // nostrod no longer knows what was named: the connections are not what is shown. if(guidance.problem == Problem::Input) { Refresh(); } if(guidance.mayHaveHappened) { // What may have been sent is not left in its form, a press away from being sent again. if(!stack.empty() && stack.back().page == Page::Pay) { payment.Clear(); } if(!stack.empty() && stack.back().page == Page::Request) { request.Clear(); } // And what is shown of the account may be out of date. Changed(account); } } void App::Refresh(bool again) { if(overview.state == LoadState::Loaded) { overview.refreshing = true; } else { overview.state = LoadState::Loading; } // A link that waits for the accounts starts from the one chosen for pay links: where that could not be read // either, it is read again with them. if(waiting && checkout.state == LoadState::Failed) { LoadCheckout(); } Fetch>("overview", "Connectors", [](Client& bank, Client::Then> then) { return bank.Connectors(std::move(then)); }, [this, again](Answer> answer) { if(answer.Failed()) { OverviewFailed(Explain(answer.Error(), Operation::Load)); return; } LoadAccounts(std::move(answer.Get()), again); }); } void App::OverviewFailed(const Guidance& guidance) { if(overview.refreshing) { // What was known still shows; why it is not newer is said above it, in a line: by its name, and by what // the bank or nostrod said where that is all there is to go on. overview.refreshing = false; const bool said = guidance.problem == Problem::Bank || guidance.problem == Problem::Failed; Note({said ? std::format("The accounts could not be read again. {}: {}", guidance.title, guidance.detail) : std::format("The accounts could not be read again. {}.", guidance.title)}); } else { overview.state = LoadState::Failed; overview.problem = guidance; } } void App::LoadAccounts(std::vector summaries, bool again) { Fetch>("overview.accounts", "Accounts", [](Client& bank, Client::Then> then) { return bank.Accounts(std::move(then)); }, [this, summaries = std::move(summaries), again](Answer> answer) { if(answer.Failed()) { OverviewFailed(Explain(answer.Error(), Operation::Load)); return; } // The two lists are of the same connectors in the same order, unless one was added or removed between // the two calls: then both are read again, once. std::vector& groups = answer.Get(); bool same = groups.size() == summaries.size(); for(std::size_t i = 0; same && i < groups.size(); i++) { same = groups[i].name == summaries[i].name && groups[i].bank == summaries[i].bank; } if(!same) { if(again) { OverviewFailed(Guidance{Problem::Failed, "The connections kept changing", "They changed while they were being read, twice. Try again.", false, true}); } else { Refresh(true); } return; } std::vector connections; for(std::size_t i = 0; i < groups.size(); i++) { // What the connection can do is the bank's own to say, and the way's it was made in. const bool ownAccountsOnly = OwnAccountsOnly(summaries[i].bank, summaries[i].auth); connections.push_back(Connection{summaries[i].name, summaries[i].bank, summaries[i].environment, summaries[i].auth, summaries[i].working, std::move(groups[i].accounts), ownAccountsOnly}); } overview.value = std::move(connections); overview.state = LoadState::Loaded; overview.refreshing = false; // A page about an account that is no longer there has nothing to show. std::erase_if(stack, [this](const Route& route) { return !route.account.empty() && !Find(route.account); }); if(!Find(payFrom)) { payFrom.clear(); } if(!Find(requestInto)) { requestInto.clear(); } if(!Find(filtering)) { filtering.clear(); } // A link's payment waited for this. Last, so that it finds the accounts and the pages as they now are. if(waiting) { TakeLink(); } }); } // An account's payments, as its question has them. nostrod asks the bank for what is new before it answers, which // takes the bank's time and counts against what the bank allows. `stored` is for a question about the list that is // shown, a search in it or more of it: nostrod answers that from what it has stored, at once. void App::LoadActivity(const std::string& key, bool stored) { AccountData& data = Data(key); if(data.activity.state == LoadState::Loaded) { data.activity.refreshing = true; } else { data.activity.state = LoadState::Loading; } const TransactionQuery query = data.query; Fetch>(std::format("activity:{}", key), "Transactions", [this, key, query, stored](Client& bank, Client::Then> then) { // Decided as the call is made, which may be after the one before it was answered: where no list is shown, // because none was read yet or the reading failed, the bank is asked all the same. TransactionQuery asked = query; asked.stored = stored && Data(key).activity.state == LoadState::Loaded; return bank.Transactions(key, asked, std::move(then)); }, [this, key, limit = query.limit](Answer> answer) { AccountData& asked = Data(key); asked.activity.refreshing = false; if(answer.Failed()) { asked.activity.state = LoadState::Failed; asked.activity.problem = Explain(answer.Error(), Operation::Load); ListFailed(asked.activity.problem); return; } asked.activity.value = std::move(answer.Get()); asked.activity.state = LoadState::Loaded; asked.more = asked.activity.value.size() >= limit; }); } void App::ListFailed(const Guidance& guidance) { // nostrod no longer knows the account: the connections are not what is shown. if(guidance.problem == Problem::Input) { Refresh(); } } template void App::LoadList(const std::string& key, std::string_view member, Loadable> AccountData::* list, Client::Pending (Client::* call)(std::string_view, Client::Then>)) { Loadable>& loading = Data(key).*list; if(loading.state == LoadState::Loaded) { loading.refreshing = true; } else { loading.state = LoadState::Loading; } Fetch>(std::format("{}:{}", member, key), std::string(member), [key, call](Client& bank, Client::Then> then) { return (bank.*call)(key, std::move(then)); }, [this, key, list](Answer> answer) { Loadable>& asked = Data(key).*list; asked.refreshing = false; if(answer.Failed()) { asked.state = LoadState::Failed; asked.problem = Explain(answer.Error(), Operation::Load); ListFailed(asked.problem); return; } asked.value = std::move(answer.Get()); asked.state = LoadState::Loaded; }); } void App::LoadTab(const std::string& key, Tab tab, bool again) { AccountData& data = Data(key); // What was never asked for, or failed, is asked for by showing it; what is there only when it is to be new. const auto wanted = [again](LoadState state) { return again || state == LoadState::Idle || state == LoadState::Failed; }; switch(tab) { case Tab::Activity: if(wanted(data.activity.state)) { LoadActivity(key); } break; case Tab::Requests: if(wanted(data.requests.state)) { LoadList(key, "Requests", &AccountData::requests, &Client::Requests); } break; case Tab::Incoming: if(wanted(data.incoming.state)) { LoadList(key, "IncomingRequests", &AccountData::incoming, &Client::IncomingRequests); } break; case Tab::Scheduled: if(wanted(data.scheduled.state)) { LoadList(key, "ScheduledPayments", &AccountData::scheduled, &Client::ScheduledPayments); } break; case Tab::Drafts: if(wanted(data.drafts.state)) { LoadList(key, "DraftPayments", &AccountData::drafts, &Client::DraftPayments); } break; } } void App::LoadCards(bool again) { if(!again && (cards.state == LoadState::Loading || cards.state == LoadState::Loaded)) { return; } if(cards.state == LoadState::Loaded) { cards.refreshing = true; } else { cards.state = LoadState::Loading; } Fetch>("cards", "Cards", [](Client& bank, Client::Then> then) { return bank.Cards(std::move(then)); }, [this](Answer> answer) { cards.refreshing = false; if(answer.Failed()) { cards.state = LoadState::Failed; cards.problem = Explain(answer.Error(), Operation::Load); return; } cards.value = std::move(answer.Get()); cards.state = LoadState::Loaded; }); } void App::LoadCheckout() { checkout.state = LoadState::Loading; Fetch>("checkout", "DefaultCheckoutAccount", [](Client& bank, Client::Then> then) { return bank.DefaultCheckoutAccount(std::move(then)); }, [this](Answer> answer) { if(answer.Failed()) { checkout.state = LoadState::Failed; checkout.problem = Explain(answer.Error(), Operation::Load); } else { checkout.value = std::move(answer.Get()); checkout.state = LoadState::Loaded; } // A link's payment starts from this account, and waited to hear which it is, or that it cannot be read. if(waiting) { TakeLink(); } }); } // Something changed that touched an account: its balance, and whichever of its lists have been looked at. void App::Changed(const std::string& key) { Refresh(); if(key.empty()) { return; } const AccountData& data = Data(key); const std::array, 5> lists = {{ {Tab::Activity, data.activity.state}, {Tab::Requests, data.requests.state}, {Tab::Incoming, data.incoming.state}, {Tab::Scheduled, data.scheduled.state}, {Tab::Drafts, data.drafts.state}, }}; for(const auto& [tab, state] : lists) { if(state != LoadState::Idle) { LoadTab(key, tab, true); } } } // -- going places ------------------------------------------------------------------------------------------------ std::vector App::Accounts() const { std::vector all; for(const Connection& connection : overview.value) { for(const Account& account : connection.accounts) { all.push_back({&connection, &account, AccountKey(account)}); } } return all; } std::optional App::Find(std::string_view key) const { if(key.empty()) { return std::nullopt; } for(AccountRef& account : Accounts()) { if(account.key == key) { return std::move(account); } } return std::nullopt; } App::AccountData& App::Data(const std::string& key) { return accounts.try_emplace(key).first->second; } bool App::Own(std::string_view iban) const { return std::ranges::any_of(Accounts(), [iban](const AccountRef& account) { return account.account->iban == iban; }); } void App::Go(Place to) { place = to; stack.clear(); dialog.reset(); filtering.clear(); picking = Picking::None; // Every page is left by this, a form that makes a connection among them: what was typed into one, a secret // among it, goes with it, as it does by the way back. ForgetConnecting(); // What a place shows and was never read, or could not be, is read by going there. if(to == Place::Cards) { LoadCards(); } else if(to == Place::Settings && (checkout.state == LoadState::Idle || checkout.state == LoadState::Failed)) { LoadCheckout(); } context.Invalidate(); } void App::Push(Page page, std::string account, const Bank* bank, const Way* way) { // An account that went since the press was offered has no page. if(!account.empty() && !Find(account)) { context.Invalidate(); return; } if(page == Page::Account) { LoadTab(account, Data(account).tab); } else if(page == Page::Checkout && checkout.state != LoadState::Loaded) { LoadCheckout(); } stack.push_back({page, std::move(account), bank, way}); context.Invalidate(); } void App::Back() { if(!stack.empty()) { // A form is for one thing: what was filled in for a payment that was walked away from is not there to be // sent by the next one, and a secret is not kept for a page that was left. switch(stack.back().page) { case Page::Pay: payment.Clear(); break; case Page::Request: request.Clear(); break; case Page::Connect: ForgetConnecting(); break; default: break; } stack.pop_back(); } context.Invalidate(); } void App::Show(Dialog shown) { dialog = std::move(shown); context.Invalidate(); } void App::Close() { std::function after; if(dialog) { after = std::move(dialog->onClose); } dialog.reset(); context.Invalidate(); if(after) { after(); } } void App::Tell(std::string_view notice) { context.Notice(std::string(notice)); } bool App::Navigate(std::string_view route) { // Not from under a change: its sheet stays until the answer has said whether it was made. if(changing) { return false; } static constexpr std::array, 3> places = {{{"accounts", Place::Accounts}, {"cards", Place::Cards}, {"settings", Place::Settings}}}; static constexpr std::array, 4> pages = {{ {"connections", Page::Connections}, {"add", Page::Banks}, {"checkout", Page::Checkout}, {"about", Page::About}, }}; if(const auto found = std::ranges::find(places, route, &std::pair::first); found != places.end()) { Go(found->second); return true; } if(const auto found = std::ranges::find(pages, route, &std::pair::first); found != pages.end()) { Go(Place::Settings); Push(found->second); return true; } constexpr std::string_view account = "account:"; if(route.starts_with(account) && Find(route.substr(account.size()))) { Go(Place::Accounts); Push(Page::Account, std::string(route.substr(account.size()))); return true; } // A step of adding a connection: a bank's ways, "add:bunq", or the form of one of them, "add:bunq:key". constexpr std::string_view adding = "add:"; if(route.starts_with(adding)) { const std::string_view named = route.substr(adding.size()); const std::size_t colon = named.find(':'); const Bank* const bank = FindBank(named.substr(0, colon)); if(bank == nullptr) { return false; } if(colon == std::string_view::npos) { Go(Place::Settings); Push(Page::Ways, {}, bank); return true; } const auto way = std::ranges::find(bank->ways, named.substr(colon + 1), &Way::key); if(way == bank->ways.end()) { return false; } Go(Place::Settings); Push(Page::Connect, {}, bank, &*way); return true; } return false; } bool App::Open(std::string_view link) { // Not from under a change, as no place is gone to from under one. if(changing) { return false; } Read read = ReadPaymentLink(link); if(!read.value) { // Said over wherever the user is, with nothing of the link in it: what a stranger wrote is not shown as // the app's own words. A link that waits is left waiting. Dialog problem; problem.kind = Dialog::Kind::Problem; problem.name = "link"; problem.title = "This link cannot be opened"; problem.text = {std::move(read.error)}; problem.choices.push_back({"link.close", "Close", Ui::ButtonKind::Tonal, true, {}, [this] { Close(); }}); Show(std::move(problem)); return true; } Go(Place::Accounts); waiting = std::move(*read.value); // The form starts from the account the user chose for pay links to start from, so that is read if it was not. if(checkout.state == LoadState::Idle || checkout.state == LoadState::Failed) { LoadCheckout(); } TakeLink(); return true; } std::string App::Screen() const { static constexpr std::array places = {"accounts", "cards", "settings"}; // The three steps of adding a connection are one name, as far as it has been gone: "add:bunq:key". static constexpr std::array pages = {"account", "pay", "request", "connections", "add", "add", "add", "checkout", "about"}; std::string screen(places[std::to_underlying(place)]); if(!stack.empty()) { const Route& top = stack.back(); screen = pages[std::to_underlying(top.page)]; if(!top.account.empty()) { screen += std::format(":{}", top.account); } if(top.bank != nullptr) { screen += std::format(":{}", top.bank->id); } if(top.way != nullptr) { screen += std::format(":{}", top.way->key); } } if(dialog) { return std::format("{}+{}", screen, dialog->name); } if(!filtering.empty()) { return std::format("{}+filter", screen); } return picking == Picking::None ? screen : std::format("{}+accounts", screen); } // -- what the user asks for -------------------------------------------------------------------------------------- void App::OpenPay(std::string account) { if(!account.empty()) { payFrom = std::move(account); } if(payFrom.empty() && !Accounts().empty()) { payFrom = Accounts().front().key; } Push(Page::Pay); } void App::OpenRequest(std::string account) { if(!account.empty()) { requestInto = std::move(account); } if(requestInto.empty() && !Accounts().empty()) { requestInto = Accounts().front().key; } Push(Page::Request); } // Tried when a link is opened, and again as the accounts and the account pay links start from are read: it goes // ahead once both are known, or the second is known not to be readable. It is safe to try again: a reading that // fails at once, as one without a system bus does, has tried it already by the time whoever asked for the reading // tries it, and then no link waits any more. void App::TakeLink() { if(!waiting || overview.state != LoadState::Loaded || checkout.state == LoadState::Loading) { return; } const PaymentLink link = std::move(*waiting); waiting.reset(); // The user went elsewhere while the accounts were read, or is being told something: what they are doing is not // taken from under them for what a link asks. The link is theirs to open again. if(place != Place::Accounts || !stack.empty() || dialog.has_value()) { Tell("The link's payment was not opened: open the link again"); return; } // No bank connected, or none whose accounts could be read: there is nothing to pay from, and no form to show. if(Accounts().empty()) { Dialog none; none.kind = Dialog::Kind::Problem; none.name = "link"; none.title = "No account to pay from"; none.text = {"This link asks for a payment, and there is no account to pay it from. Once your bank is connected and its accounts show here, open the link again."}; none.choices.push_back({"link.close", "Close", Ui::ButtonKind::Tonal, true, {}, [this] { Close(); }}); Show(std::move(none)); return; } // From the account the user chose in the settings for pay links to start from. Without one, from the first // whose connection pays anybody: one that pays between the user's own accounts only could do no more than // save a draft. std::string from; if(checkout.state == LoadState::Loaded && checkout.value && Find(AccountKey(*checkout.value))) { from = AccountKey(*checkout.value); } else { for(const AccountRef& account : Accounts()) { if(!account.connection->ownAccountsOnly) { from = account.key; break; } } } payment.Fill(link); OpenPay(std::move(from)); // Which account pays is the user's to say, and a link is where that is asked rather than assumed: the form // opens with its choice of accounts over it, the one it starts from marked, and a tap beside the choice keeps // that one. With one account there is nothing to choose, and the form opens as it is. if(Accounts().size() > 1) { picking = Picking::PayFrom; } } // The pay form's button: what is filled in is checked, and sent. The app asks nothing more itself: a payment, a // schedule and a draft are each confirmed in the system's password dialog, which nostrod words from its own data, // and a draft is not paid until it is accepted, which is confirmed there once more. void App::SubmitPayment() { payment.tried = true; context.Invalidate(); const std::optional from = Find(payFrom); PaymentOrder order; if(!from || payment.Check(from->account->currency, Today(), order).Any()) { return; } // A connection that pays between the user's own accounts only cannot pay anyone else: such a payment can only // be a draft, which is approved in the bank's own app. The form says so, and its button that it saves one. if(from->connection->ownAccountsOnly && !(order.to.type == "IBAN" && Own(order.to.value))) { order.when = When::Draft; } SendPayment(from->key, from->account->currency, order); } void App::SendPayment(const std::string& key, Currency currency, const PaymentOrder& order) { const std::string money = Money(order.amount, currency); const std::string who = PartyName(order.to); // What the user is told once it is done, by what was asked. const auto told = [this, key, money, who, order](std::string title, std::string_view what) { return [this, key, title = std::move(title), what = std::string(what), order](Created& made) { payment.Clear(); Dialog done; done.kind = Dialog::Kind::Done; done.name = "done"; done.title = title; done.lines.push_back({what, std::to_string(made.id)}); if(order.when == When::Scheduled) { done.lines.push_back({"When", ScheduleLabel(order.schedule, Today())}); } else if(order.when == When::Draft) { done.text.push_back("It is paid once it is accepted, here or in your bank's app."); } done.choices.push_back({"done.close", "Done", Ui::ButtonKind::Filled, true, {}, [this] { Close(); }}); done.onClose = [this] { Back(); }; Show(std::move(done)); Changed(key); }; }; if(order.when == When::Now) { Change(Operation::Send, "Send", std::format("Paying {} to {}", money, who), key, [key, order](Client& bank, Client::Then then) { return bank.Send(key, order.to.value, order.to.name, order.amount, order.description, std::move(then)); }, told(std::format("Paid {} to {}", money, who), "Payment")); } else if(order.when == When::Scheduled) { Change(Operation::Schedule, "Schedule", std::format("Scheduling {} to {}", money, who), key, [key, order](Client& bank, Client::Then then) { return bank.Schedule(key, order.to.value, order.to.name, order.amount, order.description, order.schedule, std::move(then)); }, told(std::format("Scheduled {} to {}", money, who), "Schedule")); } else { Change(Operation::Draft, "Draft", std::format("Saving a draft of {} to {}", money, who), key, [key, order](Client& bank, Client::Then then) { return bank.Draft(key, order.to.value, order.to.name, order.amount, order.description, std::move(then)); }, told(std::format("Drafted {} to {}", money, who), "Draft")); } } // The request form's button: what is filled in is checked, and sent, as the pay form's is. The app asks nothing // more itself: a request is confirmed in the system's password dialog, which nostrod words from its own data (who // is asked, for how much, and into which account). Until 2026-11-19 a request needed no password, and the app // showed it for review first; with the dialog that would be a second confirmation of what the dialog confirms. void App::SubmitRequest() { request.tried = true; context.Invalidate(); const std::optional into = Find(requestInto); RequestOrder order; if(!into || request.Check(into->account->currency, order).Any()) { return; } SendRequest(into->key, into->account->currency, order); } void App::SendRequest(const std::string& key, Currency currency, const RequestOrder& order) { const std::string money = Money(order.amount, currency); const std::string who = PartyName(order.from); Change(Operation::Request, "Request", std::format("Asking {} for {}", who, money), key, [key, order](Client& bank, Client::Then then) { return bank.Request(key, order.from.value, order.from.name, order.amount, order.description, std::move(then)); }, [this, key, who, money](BunqPaymentRequest& asked) { request.Clear(); Dialog done; done.kind = Dialog::Kind::Done; done.name = "done"; done.title = std::format("Asked {} for {}", who, money); done.lines.push_back({"Request", std::to_string(asked.id)}); if(!asked.shareUrl.empty()) { done.text.push_back("Anyone can pay it through this link:"); done.link = asked.shareUrl; } done.choices.push_back({"done.close", "Done", Ui::ButtonKind::Filled, true, {}, [this] { Close(); }}); done.onClose = [this] { Back(); }; Show(std::move(done)); Changed(key); }); } void App::ShowTransaction(const std::string& key, const Transaction& transaction) { Dialog detail; detail.name = "transaction"; detail.title = SignedMoney(transaction.amount, transaction.currency); if(!transaction.name.empty()) { detail.lines.push_back({transaction.amount > 0 ? "From" : "To", transaction.name}); } if(!transaction.iban.empty()) { detail.lines.push_back({"IBAN", GroupIban(transaction.iban), transaction.iban}); } if(!transaction.bic.empty()) { detail.lines.push_back({"BIC", transaction.bic}); } if(!transaction.description.empty()) { detail.lines.push_back({"Description", transaction.description}); } detail.lines.push_back({"When", FullTime(transaction.timePoint)}); if(!transaction.kind.empty()) { detail.lines.push_back({"Kind", KindLabel(transaction.kind)}); } if(!transaction.id.empty()) { detail.lines.push_back({"Bank's number", transaction.id}); } // To the same party again, or asking them back: the forms start from what this payment says. const std::string amount = FormatAmount(transaction.amount < 0 ? -transaction.amount : transaction.amount, transaction.currency); if(!transaction.iban.empty()) { detail.choices.push_back({"detail.pay", "Pay again", Ui::ButtonKind::Tonal, true, {}, [this, key, transaction, amount] { dialog.reset(); payment.Clear(); payment.to.Set(transaction.iban); payment.name.Set(transaction.name); payment.amount.Set(amount); payment.description.Set(transaction.description); OpenPay(key); }}); detail.choices.push_back({"detail.request", "Request", Ui::ButtonKind::Tonal, true, {}, [this, key, transaction, amount] { dialog.reset(); request.Clear(); request.from.Set(transaction.iban); request.name.Set(transaction.name); request.amount.Set(amount); request.description.Set(transaction.description); OpenRequest(key); }}); } detail.choices.push_back({"detail.close", "Close", Ui::ButtonKind::Plain, true, {}, [this] { Close(); }}); Show(std::move(detail)); } void App::Simple(Operation operation, std::string member, std::string question, std::string detail, std::string confirm, std::string told, std::string account, std::function)> start) { Dialog ask; ask.kind = Dialog::Kind::Ask; ask.name = "confirm"; ask.title = question; if(!detail.empty()) { ask.text.push_back(std::move(detail)); } ask.text.push_back("Your system asks for your password to confirm it."); ask.choices.push_back({"confirm.yes", std::move(confirm), MovesMoney(operation) ? Ui::ButtonKind::Filled : Ui::ButtonKind::Danger, true, {}, [this, operation, member = std::move(member), question, told = std::move(told), account = std::move(account), start = std::move(start)] { Change(operation, member, question, account, start, [this, operation, told, account](std::monostate&) { if(MovesMoney(operation)) { Dialog done; done.kind = Dialog::Kind::Done; done.name = "done"; done.title = told; done.choices.push_back({"done.close", "Done", Ui::ButtonKind::Filled, true, {}, [this] { Close(); }}); Show(std::move(done)); } else { dialog.reset(); Tell(told); } Changed(account); }); }}); ask.choices.push_back({"confirm.no", "Back", Ui::ButtonKind::Plain, true, {}, [this] { Close(); }}); Show(std::move(ask)); } void App::ShowRequest(const std::string& key, const BunqPaymentRequest& asked) { Dialog detail; detail.name = "request"; detail.title = std::format("{} asked of {}", Money(asked.amount, asked.currency), PartyName(asked.counterparty)); detail.lines.push_back({"Status", StatusLabel(asked.status)}); if(asked.amountPaid) { detail.lines.push_back({"Paid", Money(*asked.amountPaid, asked.currency)}); } if(!asked.counterparty.iban.empty()) { detail.lines.push_back({"IBAN", GroupIban(asked.counterparty.iban), asked.counterparty.iban}); } if(!asked.description.empty()) { detail.lines.push_back({"Description", asked.description}); } detail.lines.push_back({"Asked", FullTime(asked.created)}); detail.link = asked.shareUrl; if(asked.status == "PENDING") { detail.choices.push_back({"detail.revoke", "Revoke", Ui::ButtonKind::Danger, true, {}, [this, key, id = asked.id, who = PartyName(asked.counterparty)] { Simple(Operation::RevokeRequest, "RevokeRequest", std::format("Revoke the request to {}?", who), "It can no longer be paid.", "Revoke", "Request revoked", key, [key, id](Client& bank, Client::Then then) { return bank.RevokeRequest(key, id, std::move(then)); }); }}); } detail.choices.push_back({"detail.close", "Close", Ui::ButtonKind::Plain, true, {}, [this] { Close(); }}); Show(std::move(detail)); } void App::ShowIncoming(const std::string& key, const BunqIncomingRequest& asked) { const std::optional account = Find(key); // A request is someone else's to be paid: not what a connection that pays the user's own accounts only can do. const bool ownOnly = account && account->connection->ownAccountsOnly; const std::string money = Money(asked.amount, asked.currency); const std::string who = PartyName(asked.counterparty); Dialog detail; detail.name = "incoming"; detail.title = std::format("{} asks for {}", who, money); detail.lines.push_back({"Status", StatusLabel(asked.status)}); detail.lines.push_back({"Kind", StatusLabel(asked.type)}); if(!asked.counterparty.iban.empty()) { detail.lines.push_back({"IBAN", GroupIban(asked.counterparty.iban), asked.counterparty.iban}); } if(!asked.description.empty()) { detail.lines.push_back({"Description", asked.description}); } detail.lines.push_back({"Asked", FullTime(asked.created)}); if(asked.status == "PENDING") { detail.choices.push_back({"detail.pay", std::format("Pay {}", money), Ui::ButtonKind::Filled, !ownOnly, ownOnly ? "A request cannot be paid from here: this account's connection pays between your own accounts only. Pay it in your bank's app." : "", [this, key, id = asked.id, who, money] { Simple(Operation::PayRequest, "RespondToRequest", std::format("Pay {} to {}?", money, who), "As they asked in their request.", "Pay", std::format("Paid {} to {}", money, who), key, [key, id](Client& bank, Client::Then then) { return bank.RespondToRequest(key, id, true, std::move(then)); }); }}); detail.choices.push_back({"detail.reject", "Reject", Ui::ButtonKind::Danger, true, {}, [this, key, id = asked.id, who] { Simple(Operation::RejectRequest, "RespondToRequest", std::format("Reject the request from {}?", who), "They are told you will not pay it.", "Reject", "Request rejected", key, [key, id](Client& bank, Client::Then then) { return bank.RespondToRequest(key, id, false, std::move(then)); }); }}); } detail.choices.push_back({"detail.close", "Close", Ui::ButtonKind::Plain, true, {}, [this] { Close(); }}); Show(std::move(detail)); } void App::ShowScheduled(const std::string& key, const BunqScheduledPayment& scheduled) { const std::string money = Money(scheduled.amount, scheduled.currency); const std::string who = PartyName(scheduled.counterparty); Dialog detail; detail.name = "scheduled"; detail.title = std::format("{} to {}", money, who); detail.lines.push_back({"When", ScheduleLabel(scheduled.schedule, Today())}); if(!scheduled.schedule.status.empty()) { detail.lines.push_back({"Status", StatusLabel(scheduled.schedule.status)}); } if(scheduled.schedule.next) { detail.lines.push_back({"Next", FullTime(*scheduled.schedule.next)}); } if(!scheduled.counterparty.iban.empty()) { detail.lines.push_back({"IBAN", GroupIban(scheduled.counterparty.iban), scheduled.counterparty.iban}); } if(!scheduled.description.empty()) { detail.lines.push_back({"Description", scheduled.description}); } if(scheduled.schedule.status == "ACTIVE") { detail.choices.push_back({"detail.cancel", "Cancel the schedule", Ui::ButtonKind::Danger, true, {}, [this, key, id = scheduled.id, who, money] { Simple(Operation::CancelSchedule, "CancelScheduledPayment", std::format("Cancel the payments of {} to {}?", money, who), "No more of them are made.", "Cancel the schedule", "Schedule cancelled", key, [key, id](Client& bank, Client::Then then) { return bank.CancelScheduledPayment(key, id, std::move(then)); }); }}); } detail.choices.push_back({"detail.close", "Close", Ui::ButtonKind::Plain, true, {}, [this] { Close(); }}); Show(std::move(detail)); } void App::ShowDraft(const std::string& key, const BunqDraftPayment& draft) { Dialog detail; detail.name = "draft"; std::int64_t total = 0; Currency currency = Currency::Euro; for(const BunqDraftPayment::Entry& entry : draft.entries) { total += entry.amount; currency = entry.currency; detail.lines.push_back({PartyName(entry.counterparty), entry.description.empty() ? Money(entry.amount, entry.currency) : std::format("{} · {}", Money(entry.amount, entry.currency), entry.description)}); } const std::string money = Money(total, currency); detail.title = std::format("A draft of {}", money); detail.lines.push_back({"Status", StatusLabel(draft.status)}); if(!draft.createdBy.empty()) { detail.lines.push_back({"Made by", draft.createdBy}); } if(draft.status == "PENDING") { detail.choices.push_back({"detail.accept", std::format("Accept and pay {}", money), Ui::ButtonKind::Filled, true, {}, [this, key, id = draft.id, money] { Simple(Operation::AcceptDraft, "RespondToDraftPayment", std::format("Accept the draft and pay {}?", money), "Every payment in it is made.", "Pay", std::format("Draft accepted: {} paid", money), key, [key, id](Client& bank, Client::Then then) { return bank.RespondToDraftPayment(key, id, true, std::move(then)); }); }}); detail.choices.push_back({"detail.reject", "Reject", Ui::ButtonKind::Danger, true, {}, [this, key, id = draft.id, money] { Simple(Operation::RejectDraft, "RespondToDraftPayment", std::format("Reject the draft of {}?", money), "None of it is paid.", "Reject", "Draft rejected", key, [key, id](Client& bank, Client::Then then) { return bank.RespondToDraftPayment(key, id, false, std::move(then)); }); }}); } detail.choices.push_back({"detail.close", "Close", Ui::ButtonKind::Plain, true, {}, [this] { Close(); }}); Show(std::move(detail)); } void App::SetCard(std::uint64_t card, std::string lastFour, Operation operation, std::string status) { static constexpr std::array, 3> doing = {{ {Operation::FreezeCard, "Freezing card •••• {}"}, {Operation::UnfreezeCard, "Unfreezing card •••• {}"}, {Operation::BlockCard, "Blocking card •••• {}"}, }}; const std::string_view title = std::ranges::find(doing, operation, &std::pair::first)->second; Change(operation, "SetCardStatus", std::vformat(title, std::make_format_args(lastFour)), {}, [card, status](Client& bank, Client::Then then) { return bank.SetCardStatus(card, status, std::move(then)); }, [this, status, lastFour](BunqCard& now) { LoadCards(true); // The bank answers with the card as it is, which is not always as it was asked to be: one that was never // activated stays as it was. The check is the library's, which words it for its bank; the app says it in // no bank's name, and of the card as the user knows it. try { now.ExpectStatus(status); } catch(const std::runtime_error&) { throw std::runtime_error(std::format("Your bank kept card •••• {} as it was: {}. A card can only be frozen or unfrozen once it has been activated.", lastFour, StatusLabel(now.status))); } dialog.reset(); Tell(std::format("Card •••• {} is now {}", lastFour, StatusLabel(now.status))); }); } void App::ShowCard(const BunqCard& card) { Dialog detail; detail.name = "card"; detail.title = std::format("{} •••• {}", CardProduct(card.productType), card.lastFour); // How the card stands, as the library reads the bank's two words for it: a virtual card is that and no more, // since the bank reports one as deactivated also while it pays. const bool virtualCard = card.State() == "VIRTUAL"; if(virtualCard) { detail.text.push_back("This is a virtual card. The bank does not report whether a virtual card is frozen, and does not freeze or unfreeze one when Nostro asks: do that in your bank's app."); } else if(card.status == "DEACTIVATED") { // The bank has one word for plastic it was told to freeze and for plastic that was never activated, and // the user who froze nothing is not left to think they did. detail.text.push_back("Deactivated is what the bank reports for a card that is frozen, and for one that was never activated."); } detail.lines.push_back({"Status", StatusLabel(card.State())}); // How far the bank is with the card itself, which is what tells frozen plastic from plastic never activated. if(!virtualCard && !card.orderStatus.empty()) { detail.lines.push_back({"Order status", StatusLabel(card.orderStatus)}); } if(!card.nameOnCard.empty()) { detail.lines.push_back({"Name on card", card.secondLine.empty() ? card.nameOnCard : std::format("{} · {}", card.nameOnCard, card.secondLine)}); } if(!card.expiry.empty()) { detail.lines.push_back({"Expires", CardExpiry(card.expiry)}); } if(!card.iban.empty()) { const std::optional paying = Find(card.iban); detail.lines.push_back({"Pays from", paying ? std::format("{} · {}", paying->account->name, GroupIban(card.iban)) : GroupIban(card.iban)}); } const std::uint64_t id = card.id; const std::string lastFour = card.lastFour; // Not offered for a virtual card: the bank leaves one as it is, and nostrod refuses to ask. if(card.State() == "ACTIVE") { detail.choices.push_back({"detail.freeze", "Freeze", Ui::ButtonKind::Tonal, true, {}, [this, id, lastFour] { SetCard(id, lastFour, Operation::FreezeCard, "DEACTIVATED"); }}); } else if(card.State() == "DEACTIVATED") { detail.choices.push_back({"detail.unfreeze", "Unfreeze", Ui::ButtonKind::Filled, true, {}, [this, id, lastFour] { SetCard(id, lastFour, Operation::UnfreezeCard, "ACTIVE"); }}); } if(card.status == "ACTIVE" || card.status == "DEACTIVATED") { // Twice asked: a card reported lost or stolen is blocked for good. const auto report = [this, id, lastFour](std::string_view how, std::string_view status) { return [this, id, lastFour, how = std::string(how), status = std::string(status)] { Dialog first; first.kind = Dialog::Kind::Ask; first.name = "confirm"; first.title = std::format("Report card •••• {} {}?", lastFour, how); first.text = {"This blocks the card for good. It cannot be unfrozen again: you would need a new card."}; first.choices.push_back({"confirm.yes", std::format("Report it {}", how), Ui::ButtonKind::Danger, true, {}, [this, id, lastFour, how, status] { Dialog second; second.kind = Dialog::Kind::Ask; second.name = "confirm.again"; second.title = std::format("Block card •••• {} for good?", lastFour); second.text = {std::format("It is reported {} to your bank and never works again.", how), "Your system asks for your password to confirm it."}; second.choices.push_back({"confirm.yes", "Block the card", Ui::ButtonKind::Danger, true, {}, [this, id, lastFour, status] { SetCard(id, lastFour, Operation::BlockCard, status); }}); second.choices.push_back({"confirm.no", "Back", Ui::ButtonKind::Plain, true, {}, [this] { Close(); }}); Show(std::move(second)); }}); first.choices.push_back({"confirm.no", "Back", Ui::ButtonKind::Plain, true, {}, [this] { Close(); }}); Show(std::move(first)); }; }; detail.choices.push_back({"detail.lost", "Report lost", Ui::ButtonKind::Danger, true, {}, report("lost", "LOST")}); detail.choices.push_back({"detail.stolen", "Report stolen", Ui::ButtonKind::Danger, true, {}, report("stolen", "STOLEN")}); } detail.choices.push_back({"detail.close", "Close", Ui::ButtonKind::Plain, true, {}, [this] { Close(); }}); Show(std::move(detail)); } void App::ShowConnection(const Connection& connection) { Dialog detail; detail.name = "connection"; detail.title = connection.name; detail.lines.push_back({"Bank", BankName(connection.bank)}); detail.lines.push_back({"Environment", StatusLabel(connection.environment)}); detail.lines.push_back({"Connected with", WayName(connection.bank, connection.auth)}); if(connection.ownAccountsOnly) { detail.lines.push_back({"Pays", "Your own accounts only"}); } detail.lines.push_back({"Status", connection.working ? "Working" : "Failing: the bank did not answer, or refused"}); detail.lines.push_back({"Accounts", std::to_string(connection.accounts.size())}); detail.choices.push_back({"detail.remove", "Remove", Ui::ButtonKind::Danger, true, {}, [this, connection] { RemoveConnection(connection); }}); detail.choices.push_back({"detail.close", "Close", Ui::ButtonKind::Plain, true, {}, [this] { Close(); }}); Show(std::move(detail)); } void App::RemoveConnection(const Connection& connection) { // nostrod removes a connector by its name, or by its number in its list where two have one name. const auto remove = [this, name = connection.name](std::string connector) { Change(Operation::RemoveConnection, "RemoveConnector", std::format("Removing {}", name), {}, [connector](Client& bank, Client::Then then) { return bank.RemoveConnector(connector, std::move(then)); }, [this](std::string& removed) { dialog.reset(); Tell(std::format("Removed {}", removed)); // Its cards went with it, and it may have held the account pay links start from: the cards are read // when they are next looked at, that account now, the settings being where connections are removed from. cards = {}; LoadCheckout(); Refresh(); }); }; Dialog ask; ask.kind = Dialog::Kind::Ask; ask.name = "confirm"; ask.title = std::format("Remove {}?", connection.name); ask.text = {"Nostro logs out of the bank and deletes the payments it stored for this connection.", Revoking(connection.bank, connection.auth), "Your system asks for your password to confirm it."}; ask.choices.push_back({"confirm.yes", "Remove", Ui::ButtonKind::Danger, true, {}, [this, connection, remove] { const bool shared = std::ranges::count(overview.value, connection.name, &Connection::name) > 1; if(!shared) { remove(connection.name); return; } // Its number, in the list as nostrod has it now. Two connections of one name are told apart by their // accounts, which no two connections share. Dialog looking; looking.kind = Dialog::Kind::Working; looking.name = "working"; looking.title = std::format("Removing {}", connection.name); looking.text = {"One moment."}; Show(std::move(looking)); Fetch>("remove", "Accounts", [](Client& bank, Client::Then> then) { return bank.Accounts(std::move(then)); }, [this, connection, remove](Answer> answer) { if(answer.Failed()) { Failed(Explain(answer.Error(), Operation::Load), Operation::Load, {}); return; } const auto keys = [](const std::vector& accounts) { std::vector keys; for(const Account& account : accounts) { keys.push_back(AccountKey(account)); } std::ranges::sort(keys); return keys; }; const std::vector wanted = keys(connection.accounts); const auto is = [&connection, &wanted, &keys](const ConnectorAccounts& listed) { return listed.name == connection.name && listed.bank == connection.bank && keys(listed.accounts) == wanted; }; const std::vector& now = answer.Get(); if(std::ranges::count_if(now, is) != 1) { Failed(Guidance{Problem::Failed, "The connections changed", "Which one to remove is no longer clear. Look at the list again.", false, false}, Operation::Load, {}); Refresh(); return; } remove(std::to_string(std::ranges::find_if(now, is) - now.begin() + 1)); }); }}); ask.choices.push_back({"confirm.no", "Back", Ui::ButtonKind::Plain, true, {}, [this] { Close(); }}); Show(std::move(ask)); } // What was typed to make a connection, a secret among it, is not kept once the connection is made or its form // is left: every bank's forms are emptied here. void App::ForgetConnecting() { bunqKey.Clear(); bunqOAuth.Clear(); bunqOAuthError.clear(); } void App::Connect(std::string member, std::function)> start) { const Route& form = stack.back(); Change(Operation::AddConnection, std::move(member), std::format("Connecting to {}", form.bank->name), {}, std::move(start), [this, way = form.way](AddedConnector& added) { Connected(added, *way); }); } void App::Connected(const AddedConnector& added, const Way& way) { ForgetConnecting(); Dialog done; done.kind = Dialog::Kind::Done; done.name = "done"; done.title = std::format("Connected {}", added.name); done.lines.push_back({"Connected with", std::string(way.title)}); done.lines.push_back({"Environment", StatusLabel(added.environment)}); done.lines.push_back({"Accounts", std::to_string(added.accounts)}); done.choices.push_back({"done.close", "Done", Ui::ButtonKind::Filled, true, {}, [this] { Close(); }}); done.onClose = [this] { Go(Place::Accounts); }; Show(std::move(done)); cards = {}; Refresh(); } void App::ChooseCheckout(const std::string& key, const std::string& name) { Change(Operation::SetCheckoutAccount, "SetDefaultCheckoutAccount", std::format("Having pay links start from {}", name), {}, [key](Client& bank, Client::Then then) { return bank.SetDefaultCheckoutAccount(key, std::move(then)); }, [this](Account& chosen) { checkout.value = chosen; checkout.state = LoadState::Loaded; dialog.reset(); Tell(std::format("Pay links now start from {}", chosen.name)); }); } void App::Search(const std::string& key, bool now) { const std::string name = std::format("search:{}", key); const auto run = [this, key] { const std::optional account = Find(key); AccountData& data = Data(key); // A new question starts with the newest hundred again. TransactionQuery query; if(account && !data.filter.Check(account->account->currency, query).Any()) { data.query = query; LoadActivity(key, true); } }; // What is typed is looked for at once, with every letter: in what nostrod has stored of the list that is shown, // which costs no call to the bank. Only where no list is shown does the question go to the bank, which counts // its calls: not one per letter then, but one once the typing stops. if(now || Data(key).activity.state == LoadState::Loaded) { context.Forget(name); run(); } else { context.At(name, context.Now() + 400, run); } } }