Repository navigation
Expand file tree
/
Copy pathATM.cpp
More file actions
2367 lines (2198 loc) · 90.9 KB
/
Copy pathATM.cpp
File metadata and controls
2367 lines (2198 loc) · 90.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// ============================================================================
// Brainhub24 ATM Simulator v3 (CLI edition)
// ============================================================================
//
// A terminal ATM that behaves like the GUI demo in demo/index.html:
//
// - Wallet with three demo cards (normal, low balance, expired); the PIN of
// each card is on its "sticky note" on the start screen.
// - Card reader, language choice (English / Deutsch), PIN entry with masked
// keypad input and card capture after 3 wrong PINs (kept across runs).
// - Fast cash, other amount, balance, cash deposit from your wallet,
// transfers (own accounts and to another card holder), mini statement,
// PIN change.
// - Real-machine behaviour: card is returned before cash, cash is retracted
// after 30 s, card is captured if not taken, "Do you need more time?"
// after 30 s of inactivity, note mix limited by cassette stock, daily
// withdrawal limit, multiples of EUR 10.
// - Receipts with ATM ID, transaction number and auth code, an electronic
// journal and cassette levels (operator view).
// - Colour themes, autoplay tour, scripted (piped) input for testing.
//
// Build: g++ -std=c++17 -O2 -Wall -Wextra ATM.cpp -o atm
// Run: ./atm (./atm --help for all options)
//
// All names, card numbers and the bank are fictional. Money is handled as
// 64-bit integer cents. State is saved outside the repository (see --help).
//
// Created by Brainhub24/ATM. © 2026 Brainhub24. All rights reserved.
// ============================================================================
#include <algorithm>
#include <cctype>
#include <cerrno>
#include <chrono>
#include <csignal>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <deque>
#include <filesystem>
#include <fstream>
#include <functional>
#include <map>
#include <random>
#include <sstream>
#include <string>
#include <thread>
#include <utility>
#include <vector>
#ifdef _WIN32
#ifndef NOMINMAX
#define NOMINMAX
#endif
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#include <conio.h>
#include <io.h>
#include <windows.h>
#else
#include <poll.h>
#include <termios.h>
#include <unistd.h>
#endif
using Cents = long long;
static const char* const VERSION = "3.0.0";
static const char* const COPYRIGHT = "© 2026 Brainhub24. All rights reserved.";
static const char* const ATM_ID = "BH24-0042";
static const int DENOMS[] = {50, 20, 10};
static const int MAX_NOTES = 40;
// ============================================================================
// Options and globals
// ============================================================================
struct Options {
std::string theme = "brand";
std::string statePath;
bool color = true;
bool fast = false;
bool sound = false;
bool autoplay = false;
bool reset = false;
bool plain = false; // type a line + Enter per screen, no full-screen redraw
int timeout = 30; // inactivity timeout in seconds, 0 = off
};
static Options opt;
static bool g_tty = false; // interactive terminal: raw keys + redraw in place
static bool g_color = false;
static bool g_eof = false; // input ended: unwind and quit
static bool g_persist = true; // false in autoplay (tour runs on a fresh copy)
static bool g_saveFailed = false;
static bool g_de = false; // session language
static int g_spin = 0;
static std::string g_notice; // one-shot message under the machine
static void pause(int ms) {
if (opt.fast || ms <= 0) return;
std::this_thread::sleep_for(std::chrono::milliseconds(ms));
}
static long long nowMs() {
using namespace std::chrono;
return duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
}
static std::tm localTm(long long ms) {
std::time_t t = static_cast<std::time_t>(ms / 1000);
std::tm tm{};
#ifdef _WIN32
localtime_s(&tm, &t);
#else
localtime_r(&t, &tm);
#endif
return tm;
}
static std::string strftimeMs(long long ms, const char* fmt) {
std::tm tm = localTm(ms);
char buf[64];
std::strftime(buf, sizeof buf, fmt, &tm);
return buf;
}
static std::string today() { return strftimeMs(nowMs(), "%Y-%m-%d"); }
static void bell() {
if (opt.sound) {
std::fputs("\a", stdout);
std::fflush(stdout);
}
}
// ============================================================================
// Platform: terminal and input
// ============================================================================
namespace plat {
#ifdef _WIN32
// Windows console: keys come from _getch() (no echo, no Enter needed), colours
// and cursor control use the console's VT mode (Windows 10 and later).
static bool keys = false; // stdin is a console: read single keys
static bool vtOk = false; // console accepted VT escape sequences
static DWORD origOutMode = 0;
static bool outModeSaved = false;
bool stdinTty() { return _isatty(_fileno(stdin)); }
bool stdoutTty() { return _isatty(_fileno(stdout)) && vtOk; }
void rawOn() { keys = stdinTty(); }
void rawOff() {
keys = false;
if (outModeSaved) SetConsoleMode(GetStdHandle(STD_OUTPUT_HANDLE), origOutMode);
}
int waitReadable(int ms) {
if (!keys) return 1; // line input: fgets blocks, no timeouts
auto end = std::chrono::steady_clock::now() + std::chrono::milliseconds(ms);
for (;;) {
if (_kbhit()) return 1;
if (ms >= 0 && std::chrono::steady_clock::now() >= end) return 0;
Sleep(15);
}
}
long readSome(char* b, size_t n) {
if (keys) {
int c = _getch();
if (c == 0 || c == 0xE0) { // arrow / function key: swallow the second byte
_getch();
return readSome(b, n);
}
if (c == 3) std::raise(SIGINT); // Ctrl+C
b[0] = static_cast<char>(c);
return 1;
}
if (!std::fgets(b, static_cast<int>(n), stdin)) return 0;
return static_cast<long>(std::strlen(b));
}
void flushInput() {
if (keys)
while (_kbhit()) _getch();
}
void setupConsole() {
SetConsoleOutputCP(CP_UTF8);
SetConsoleCP(CP_UTF8);
HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE);
DWORD mode = 0;
if (h != INVALID_HANDLE_VALUE && GetConsoleMode(h, &mode)) {
origOutMode = mode;
outModeSaved = true;
#ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING
#define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004
#endif
vtOk = SetConsoleMode(h, mode | ENABLE_VIRTUAL_TERMINAL_PROCESSING | ENABLE_PROCESSED_OUTPUT) != 0;
}
static char outBuf[1 << 16]; // whole frames per write, so UTF-8 is never split
std::setvbuf(stdout, outBuf, _IOFBF, sizeof outBuf);
}
#else
static termios orig;
static bool raw = false;
bool stdinTty() { return isatty(0); }
bool stdoutTty() { return isatty(1); }
void rawOn() {
if (tcgetattr(0, &orig) != 0) return;
termios t = orig;
t.c_lflag &= ~static_cast<tcflag_t>(ICANON | ECHO);
t.c_cc[VMIN] = 1;
t.c_cc[VTIME] = 0;
if (tcsetattr(0, TCSAFLUSH, &t) == 0) raw = true;
}
void rawOff() {
if (raw) tcsetattr(0, TCSAFLUSH, &orig);
raw = false;
}
int waitReadable(int ms) {
pollfd p{0, POLLIN, 0};
int r = poll(&p, 1, ms);
if (r < 0) return errno == EINTR ? 0 : -1;
return r == 0 ? 0 : 1;
}
long readSome(char* b, size_t n) { return static_cast<long>(read(0, b, n)); }
void flushInput() {
if (raw) tcflush(0, TCIFLUSH);
}
void setupConsole() {}
#endif
} // namespace plat
static void termEnter() {
if (!g_tty) return;
plat::rawOn();
std::fputs("\x1b[?1049h\x1b[?25l\x1b[2J", stdout);
std::fflush(stdout);
}
static void termLeave() {
if (!g_tty) return;
std::fputs("\x1b[0m\x1b[?25h\x1b[?1049l", stdout);
std::fflush(stdout);
plat::rawOff();
}
static void onSignal(int) {
static const char seq[] = "\x1b[0m\x1b[?25h\x1b[?1049l\nATM session aborted.\n";
if (g_tty) {
#ifdef _WIN32
std::fwrite(seq, 1, sizeof seq - 1, stdout);
std::fflush(stdout);
#else
ssize_t r = write(1, seq, sizeof seq - 1);
(void)r;
#endif
plat::rawOff();
}
std::_Exit(130);
}
enum class K { Char, Enter, Back, Esc, Timeout, Eof, None };
struct Key {
K k;
char c = 0;
};
// All input goes through here: raw keys on a terminal, whole lines from a pipe,
// or a scripted tour in autoplay mode.
struct Input {
std::string buf;
bool eof = false;
std::deque<std::pair<int, char>> script; // (delay ms, key); '\n' = Enter
bool keyMode() const { return opt.autoplay || g_tty; }
int fill(int timeoutMs) {
if (eof) return -1;
int w = plat::waitReadable(timeoutMs);
if (w == 0) return 0;
if (w < 0) {
eof = true;
return -1;
}
char tmp[512];
long n = plat::readSome(tmp, sizeof tmp);
if (n < 0 && errno == EINTR) return 0;
if (n <= 0) {
eof = true;
return -1;
}
buf.append(tmp, static_cast<size_t>(n));
return 1;
}
static int remaining(std::chrono::steady_clock::time_point deadline, int timeoutMs) {
if (timeoutMs < 0) return -1;
auto left = std::chrono::duration_cast<std::chrono::milliseconds>(deadline - std::chrono::steady_clock::now()).count();
return left > 0 ? static_cast<int>(left) : 0;
}
Key scripted() {
if (script.empty()) {
g_eof = true;
return {K::Eof};
}
auto [delay, ch] = script.front();
script.pop_front();
if (!opt.fast) {
for (int waited = 0; waited < delay; waited += 50) {
if (g_tty && plat::waitReadable(0) > 0) { // any key stops the tour
char tmp[64];
plat::readSome(tmp, sizeof tmp);
script.clear();
g_eof = true;
return {K::Eof};
}
std::this_thread::sleep_for(std::chrono::milliseconds(50));
}
}
if (ch == '\n') return {K::Enter};
if (ch == 27) return {K::Esc};
return {K::Char, ch};
}
Key next(int timeoutMs) {
if (g_eof) return {K::Eof};
if (opt.autoplay) return scripted();
auto deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(std::max(0, timeoutMs));
for (;;) {
if (buf.empty()) {
int r = fill(remaining(deadline, timeoutMs));
if (r == 0) return {K::Timeout};
if (r < 0) {
g_eof = true;
return {K::Eof};
}
}
unsigned char c = static_cast<unsigned char>(buf[0]);
buf.erase(0, 1);
if (c == '\r' || c == '\n') return {K::Enter};
if (c == 127 || c == 8) return {K::Back};
if (c == 27) {
if (buf.empty()) fill(30);
if (!buf.empty() && (buf[0] == '[' || buf[0] == 'O')) { // arrow keys etc.: ignore
buf.erase(0, 1);
while (!buf.empty()) {
unsigned char e = static_cast<unsigned char>(buf[0]);
buf.erase(0, 1);
if (e >= 0x40 && e <= 0x7e) break;
}
continue;
}
return {K::Esc};
}
if (c == 'x' || c == 'X') return {K::Esc};
if (c >= 32 && c < 127) return {K::Char, static_cast<char>(c)};
}
}
// 1 = line read, 0 = timeout, -1 = end of input
int nextLine(int timeoutMs, std::string& out) {
if (g_eof) return -1;
auto deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(std::max(0, timeoutMs));
for (;;) {
size_t nl = buf.find('\n');
if (nl != std::string::npos) {
out = buf.substr(0, nl);
buf.erase(0, nl + 1);
if (!out.empty() && out.back() == '\r') out.pop_back();
return 1;
}
int r = fill(remaining(deadline, timeoutMs));
if (r == 0) return 0;
if (r < 0) {
if (!buf.empty()) {
out = buf;
buf.clear();
return 1;
}
g_eof = true;
return -1;
}
}
}
};
static Input in;
// ============================================================================
// Text helpers
// ============================================================================
// Visible width: UTF-8 code points, ANSI escape sequences excluded.
static int vis(const std::string& s) {
int n = 0;
for (size_t i = 0; i < s.size(); ++i) {
unsigned char c = static_cast<unsigned char>(s[i]);
if (c == 0x1b && i + 1 < s.size() && s[i + 1] == '[') {
i += 2;
while (i < s.size() && !(s[i] >= 0x40 && s[i] <= 0x7e)) ++i;
continue;
}
if ((c & 0xC0) != 0x80) ++n;
}
return n;
}
// Cut plain (unstyled) text to w code points.
static std::string cut(const std::string& s, int w) {
int n = 0;
for (size_t i = 0; i < s.size(); ++i) {
if ((static_cast<unsigned char>(s[i]) & 0xC0) != 0x80) {
if (n == w) return s.substr(0, i);
++n;
}
}
return s;
}
static std::string rep(const std::string& s, int n) {
std::string r;
for (int i = 0; i < n; ++i) r += s;
return r;
}
static std::string padR(const std::string& s, int w) { return s + std::string(std::max(0, w - vis(s)), ' '); }
static std::string padL(const std::string& s, int w) { return std::string(std::max(0, w - vis(s)), ' ') + s; }
static std::string centre(const std::string& s, int w) {
int p = std::max(0, (w - vis(s)) / 2);
return std::string(p, ' ') + s + std::string(std::max(0, w - p - vis(s)), ' ');
}
static std::vector<std::string> wrap(const std::string& text, int w) {
std::vector<std::string> out;
std::istringstream ss(text);
std::string word, line;
while (ss >> word) {
if (!line.empty() && vis(line) + 1 + vis(word) > w) {
out.push_back(line);
line.clear();
}
line += (line.empty() ? "" : " ") + word;
}
if (!line.empty()) out.push_back(line);
return out;
}
static std::string upper(std::string s) {
for (char& c : s)
if (c >= 'a' && c <= 'z') c = static_cast<char>(c - 'a' + 'A');
return s;
}
static std::string trim(const std::string& s) {
size_t a = s.find_first_not_of(" \t\r\n");
if (a == std::string::npos) return "";
size_t b = s.find_last_not_of(" \t\r\n");
return s.substr(a, b - a + 1);
}
static bool allDigits(const std::string& s) {
return !s.empty() && std::all_of(s.begin(), s.end(), [](char c) { return c >= '0' && c <= '9'; });
}
// ============================================================================
// Translations (same texts as the GUI demo)
// ============================================================================
struct Str {
const char* key;
const char* en;
const char* de;
};
static const Str STRINGS[] = {
{"welcome", "Welcome", "Willkommen"},
{"insert", "Please insert your card", "Bitte Karte einführen"},
{"insertSub", "Chip side up, chip first.", "Chip nach oben, Chip zuerst."},
{"noCash", "Withdrawals unavailable · deposits only", "Auszahlung nicht möglich · nur Einzahlungen"},
{"reading", "Reading your card", "Ihre Karte wird gelesen"},
{"dontRemove", "Please do not remove your card.", "Bitte entnehmen Sie Ihre Karte nicht."},
{"expired", "This card has expired", "Diese Karte ist abgelaufen"},
{"expiredSub", "Please contact your bank for a replacement card.", "Bitte wenden Sie sich für eine Ersatzkarte an Ihre Bank."},
{"pinTitle", "Please enter your PIN", "Bitte geben Sie Ihre PIN ein"},
{"pinSub", "Cover the keypad with your hand. Press ENTER to confirm.", "Verdecken Sie die Tastatur mit der Hand. Mit ENTER bestätigen."},
{"pinShort", "Your PIN has at least 4 digits.", "Ihre PIN hat mindestens 4 Ziffern."},
{"wrongPin1", "Incorrect PIN. 1 attempt remaining.", "Falsche PIN. Noch 1 Versuch."},
{"wrongPinN", "Incorrect PIN. {} attempts remaining.", "Falsche PIN. Noch {} Versuche."},
{"checkingPin", "Checking your PIN", "Ihre PIN wird geprüft"},
{"wait", "Please wait", "Bitte warten"},
{"retained", "Your card has been retained", "Ihre Karte wurde einbehalten"},
{"retainedSub", "The PIN was entered incorrectly 3 times. For your security this ATM has kept the card. Please contact your bank.",
"Die PIN wurde 3-mal falsch eingegeben. Zu Ihrer Sicherheit wurde die Karte einbehalten. Bitte wenden Sie sich an Ihre Bank."},
{"notTaken", "Card retained", "Karte einbehalten"},
{"notTakenSub", "The card was not taken in time and has been kept by the ATM for your security.",
"Die Karte wurde nicht rechtzeitig entnommen und zu Ihrer Sicherheit einbehalten."},
{"menu", "Select a service", "Bitte wählen Sie"},
{"other", "Other amount", "Anderer Betrag"},
{"balance", "Balance", "Kontostand"},
{"deposit", "Deposit cash", "Einzahlung"},
{"transfer", "Transfer", "Überweisung"},
{"more", "More services", "Weitere Services"},
{"statement", "Mini statement", "Umsätze"},
{"changePin", "Change PIN", "PIN ändern"},
{"returnCard", "Return card", "Karte zurück"},
{"back", "Back", "Zurück"},
{"mainMenu", "Main menu", "Hauptmenü"},
{"amountTitle", "Enter the amount", "Betrag eingeben"},
{"amountSub", "Multiples of €10. Notes available:", "Vielfache von 10 €. Verfügbare Scheine:"},
{"confirm", "Confirm", "Bestätigen"},
{"cancel", "Cancel", "Abbrechen"},
{"yes", "Yes", "Ja"},
{"no", "No", "Nein"},
{"notMultiple", "Please enter an amount in multiples of €10.", "Bitte einen Betrag in Vielfachen von 10 € eingeben."},
{"zero", "Please enter an amount.", "Bitte einen Betrag eingeben."},
{"overLimit", "This exceeds your daily withdrawal limit. You can still withdraw {} today.",
"Der Betrag übersteigt Ihr Tageslimit. Heute noch verfügbar: {}."},
{"insufficient", "Insufficient funds. Available balance: {}.", "Nicht genügend Guthaben. Verfügbar: {}."},
{"noNotes", "This amount cannot be paid with the notes currently in the ATM. Please choose a different amount.",
"Dieser Betrag kann mit den vorhandenen Scheinen nicht ausgezahlt werden. Bitte wählen Sie einen anderen Betrag."},
{"tryAgain", "Try another amount", "Anderer Betrag"},
{"receiptQ", "Would you like a receipt?", "Möchten Sie einen Beleg?"},
{"processing", "Processing your request", "Ihr Auftrag wird bearbeitet"},
{"takeCard", "Please take your card", "Bitte entnehmen Sie Ihre Karte"},
{"takeCardSub", "Your cash will follow.", "Danach erhalten Sie Ihr Geld."},
{"takeCardEnd", "Thank you. Please remember your card.", "Vielen Dank. Bitte vergessen Sie Ihre Karte nicht."},
{"counting", "Counting your notes", "Ihre Scheine werden gezählt"},
{"takeCash", "Please take your cash", "Bitte entnehmen Sie Ihr Geld"},
{"takeCashSub", "Cash not taken within 30 seconds is retracted.", "Nicht entnommenes Geld wird nach 30 Sekunden eingezogen."},
{"retracted", "Cash retracted", "Geld eingezogen"},
{"retractedSub", "The notes were not taken and have been retracted. The amount has been returned to your account.",
"Die Scheine wurden nicht entnommen und eingezogen. Der Betrag wurde Ihrem Konto gutgeschrieben."},
{"thanks", "Thank you for banking with Brainhub24", "Vielen Dank für Ihren Besuch"},
{"takeReceipt", "Please take your receipt.", "Bitte entnehmen Sie Ihren Beleg."},
{"printing", "Printing your receipt", "Ihr Beleg wird gedruckt"},
{"balTitle", "Your balances", "Ihre Kontostände"},
{"checkingAcc", "Current account", "Girokonto"},
{"savingsAcc", "Savings account", "Sparkonto"},
{"availToday", "Cash available today", "Heute verfügbar (bar)"},
{"print", "Print receipt", "Beleg drucken"},
{"cont", "Continue", "Weiter"},
{"anotherQ", "Would you like another service?", "Möchten Sie einen weiteren Service nutzen?"},
{"depTitle", "Insert your notes", "Bitte Scheine einlegen"},
{"depSub", "Place the notes flat in the open slot. Up to 50 notes, no coins.",
"Legen Sie die Scheine flach in den offenen Schacht. Bis zu 50 Scheine, keine Münzen."},
{"depInsert", "Insert wallet notes", "Scheine einlegen"},
{"depWallet", "In your wallet:", "In Ihrer Geldbörse:"},
{"depCounted", "Notes counted", "Gezählte Scheine"},
{"depConfirm", "Deposit", "Einzahlen"},
{"depReturn", "Return notes", "Scheine zurück"},
{"depDone", "Deposit complete", "Einzahlung abgeschlossen"},
{"depReturned", "Please take your notes", "Bitte entnehmen Sie Ihre Scheine"},
{"newBal", "New balance", "Neuer Kontostand"},
{"trTitle", "Select a transfer", "Überweisung wählen"},
{"trToSav", "Current → Savings", "Giro → Sparkonto"},
{"trFromSav", "Savings → Current", "Sparkonto → Giro"},
{"trOther", "To another account", "An anderes Konto"},
{"trAcct", "Enter the account number", "Kontonummer eingeben"},
{"trAcctSub", "7 digits. Account numbers are on the sticky notes in your wallet.",
"7 Ziffern. Kontonummern stehen auf den Notizzetteln in der Geldbörse."},
{"trBadAcct", "No account with this number was found.", "Kein Konto mit dieser Nummer gefunden."},
{"trOwn", "Use the options for your own accounts instead.", "Bitte nutzen Sie die Optionen für Ihre eigenen Konten."},
{"trAmt", "Enter the transfer amount", "Überweisungsbetrag eingeben"},
{"trAmtSub", "Type the amount in cents: 12500 = €125.00", "Betrag in Cent: 12500 = 125,00 €"},
{"trConfirm", "Please confirm the transfer", "Bitte Überweisung bestätigen"},
{"trTo", "To", "An"},
{"trFrom", "From", "Von"},
{"trAmount", "Amount", "Betrag"},
{"trDone", "Transfer complete", "Überweisung ausgeführt"},
{"stmtTitle", "Recent transactions", "Letzte Umsätze"},
{"noTx", "No transactions yet.", "Noch keine Umsätze."},
{"newPin", "Enter your new PIN", "Neue PIN eingeben"},
{"newPinSub", "4 digits. Avoid easy combinations such as 1234.", "4 Ziffern. Vermeiden Sie einfache Folgen wie 1234."},
{"repeatPin", "Enter your new PIN again", "Neue PIN wiederholen"},
{"pinMismatch", "The two PINs did not match. Please start again.", "Die PINs stimmen nicht überein. Bitte erneut beginnen."},
{"pinSame", "The new PIN must be different from the current one.", "Die neue PIN muss sich von der bisherigen unterscheiden."},
{"pinChanged", "Your PIN has been changed", "Ihre PIN wurde geändert"},
{"cancelled", "Transaction cancelled", "Vorgang abgebrochen"},
{"moreTime", "Do you need more time?", "Benötigen Sie mehr Zeit?"},
{"moreTimeSub", "Your session will end in {} seconds.", "Ihre Sitzung endet in {} Sekunden."},
{"emptyWallet", "Your wallet has no notes to deposit.", "In Ihrer Geldbörse sind keine Scheine."},
{"txWithdraw", "ATM withdrawal BH24-0042", "Geldautomat BH24-0042"},
{"txReversal", "Reversal: cash retracted", "Rückbuchung eingezogenes Geld"},
{"txDeposit", "Cash deposit BH24-0042", "Bareinzahlung BH24-0042"},
{"txToSav", "Transfer to savings", "Übertrag auf Sparkonto"},
{"txFromSav", "Transfer from savings", "Übertrag vom Sparkonto"},
{"txTo", "Transfer to {}", "Überweisung an {}"},
{"txFrom", "Transfer from {}", "Überweisung von {}"},
};
static std::string tr(const std::string& key, const std::string& arg = "") {
for (const Str& s : STRINGS) {
if (key == s.key) {
std::string v = g_de ? s.de : s.en;
size_t p = v.find("{}");
if (p != std::string::npos) v.replace(p, 2, arg);
return v;
}
}
return key;
}
// ============================================================================
// Money formatting
// ============================================================================
static std::string group(unsigned long long v, char sep) {
std::string s = std::to_string(v);
for (int i = static_cast<int>(s.size()) - 3; i > 0; i -= 3) s.insert(static_cast<size_t>(i), 1, sep);
return s;
}
// €1,234.50 (English) or 1.234,50 € (German), like the GUI.
static std::string fmt(Cents c) {
bool neg = c < 0;
unsigned long long a = neg ? static_cast<unsigned long long>(-(c + 1)) + 1 : static_cast<unsigned long long>(c);
std::string ct = std::to_string(a % 100);
if (ct.size() < 2) ct = "0" + ct;
std::string sign = neg ? "-" : "";
if (g_de) return sign + group(a / 100, '.') + "," + ct + " €";
return sign + "€" + group(a / 100, ',') + "." + ct;
}
static std::string fmtWhole(int euros) { return g_de ? std::to_string(euros) + " €" : "€" + std::to_string(euros); }
// 1,234.50 for receipts and the journal.
static std::string fmtPlain(Cents c) {
bool neg = c < 0;
unsigned long long a = neg ? static_cast<unsigned long long>(-(c + 1)) + 1 : static_cast<unsigned long long>(c);
std::string ct = std::to_string(a % 100);
if (ct.size() < 2) ct = "0" + ct;
return (neg ? "-" : "") + group(a / 100, ',') + "." + ct;
}
// ============================================================================
// Bank state
// ============================================================================
struct Tx {
long long t;
Cents amt;
std::string desc;
};
struct Account {
std::string id, pan, holder, exp, pin, acctNo, day, note;
int tries = 0;
bool captured = false;
Cents checking = 0, savings = 0, limit = 0, withdrawn = 0;
std::vector<Tx> tx;
};
struct Receipt {
long long t;
std::vector<std::string> lines;
};
using Notes = std::map<int, int>;
struct State {
std::vector<Account> accounts;
Notes wallet, cassettes, capacity;
int retractBin = 0;
long long trn = 3417;
std::vector<Receipt> receipts;
std::vector<std::string> journal;
};
static State st;
static int cur = -1; // index of the card in the reader
static Account& acct() { return st.accounts[static_cast<size_t>(cur)]; }
static std::string last4(const Account& a) { return a.pan.substr(a.pan.size() - 4); }
static std::vector<Tx> seedTx(std::initializer_list<std::tuple<int, const char*, Cents>> entries) {
std::vector<Tx> v;
long long now = nowMs();
for (auto& [days, desc, amt] : entries) v.push_back({now - days * 86400000LL, amt, desc});
return v;
}
static State defaults() {
State s;
Account a;
a.id = "A"; a.pan = "4921 7300 0042 4821"; a.holder = "ALEX MORGAN"; a.exp = "09/29"; a.pin = "1234";
a.checking = 245075; a.savings = 1250000; a.acctNo = "1004821"; a.limit = 100000; a.day = today();
a.tx = seedTx({{12, "Salary · Northwind GmbH", 320000}, {11, "Rent · Hausverwaltung", -98000}, {8, "Card · Grocery store", -6420},
{6, "Card · Pharmacy", -1895}, {4, "ATM withdrawal", -10000}, {2, "Transfer from S. Rivera", 2500}, {1, "Card · Bakery", -740}});
Account b;
b.id = "B"; b.pan = "5389 1100 7764 7710"; b.holder = "SAM RIVERA"; b.exp = "02/28"; b.pin = "2580";
b.checking = 8640; b.savings = 0; b.acctNo = "1007710"; b.limit = 50000; b.day = today(); b.note = "low balance";
b.tx = seedTx({{9, "Student grant", 45000}, {7, "Mobile phone", -2999}, {5, "Card · Café", -460},
{2, "Transfer to A. Morgan", -2500}, {1, "Card · Bookshop", -1890}});
Account c;
c.id = "C"; c.pan = "4921 7300 0019 3307"; c.holder = "JO PATEL"; c.exp = "03/25"; c.pin = "1111";
c.checking = 51200; c.savings = 0; c.acctNo = "1003307"; c.limit = 100000; c.day = today(); c.note = "expired card";
s.accounts = {a, b, c};
s.wallet = {{10, 0}, {20, 2}, {50, 1}};
s.cassettes = {{10, 120}, {20, 150}, {50, 90}};
s.capacity = {{10, 200}, {20, 200}, {50, 200}};
return s;
}
// ---- persistence: a small tab-separated text file ----
static std::string defaultStatePath() {
if (const char* p = std::getenv("ATM_STATE_FILE"); p && *p) return p;
namespace fs = std::filesystem;
fs::path base;
#ifdef _WIN32
if (const char* u = std::getenv("APPDATA"); u && *u) base = u; // %APPDATA%\brainhub24-atm
else base = ".";
#else
if (const char* x = std::getenv("XDG_DATA_HOME"); x && *x) base = x;
else if (const char* h = std::getenv("HOME"); h && *h) base = fs::path(h) / ".local" / "share";
else base = ".";
#endif
return (base / "brainhub24-atm" / "state.tsv").string();
}
static std::vector<std::string> split(const std::string& s, char sep) {
std::vector<std::string> v;
std::string f;
for (char c : s) {
if (c == sep) {
v.push_back(f);
f.clear();
} else {
f += c;
}
}
v.push_back(f);
return v;
}
static void save() {
if (!g_persist) return;
namespace fs = std::filesystem;
std::error_code ec;
fs::path p(opt.statePath);
if (p.has_parent_path()) fs::create_directories(p.parent_path(), ec);
std::string tmp = opt.statePath + ".tmp";
{
std::ofstream f(tmp, std::ios::trunc);
if (!f) {
g_saveFailed = true;
return;
}
f << "BH24-ATM-STATE\t1\n";
f << "trn\t" << st.trn << "\nretract\t" << st.retractBin << "\n";
for (int d : DENOMS) f << "cassette\t" << d << "\t" << st.cassettes[d] << "\t" << st.capacity[d] << "\n";
for (int d : DENOMS) f << "wallet\t" << d << "\t" << st.wallet[d] << "\n";
for (const Account& a : st.accounts) {
f << "account\t" << a.id << "\t" << a.pan << "\t" << a.holder << "\t" << a.exp << "\t" << a.pin << "\t" << a.tries << "\t"
<< a.captured << "\t" << a.checking << "\t" << a.savings << "\t" << a.acctNo << "\t" << a.limit << "\t" << a.withdrawn
<< "\t" << a.day << "\t" << a.note << "\n";
for (const Tx& t : a.tx) f << "tx\t" << a.id << "\t" << t.t << "\t" << t.amt << "\t" << t.desc << "\n";
}
for (const Receipt& r : st.receipts) {
f << "receipt\t" << r.t;
for (const std::string& l : r.lines) f << "\t" << l;
f << "\n";
}
for (const std::string& j : st.journal) f << "journal\t" << j << "\n";
f.flush();
if (!f) {
g_saveFailed = true;
return;
}
}
fs::rename(tmp, opt.statePath, ec);
g_saveFailed = static_cast<bool>(ec);
}
static bool load() {
std::ifstream f(opt.statePath);
if (!f) return false;
std::string line;
if (!std::getline(f, line) || line != "BH24-ATM-STATE\t1") return false;
State s;
try {
while (std::getline(f, line)) {
auto v = split(line, '\t');
const std::string& k = v[0];
if (k == "trn" && v.size() == 2) s.trn = std::stoll(v[1]);
else if (k == "retract" && v.size() == 2) s.retractBin = std::stoi(v[1]);
else if (k == "cassette" && v.size() == 4) {
s.cassettes[std::stoi(v[1])] = std::stoi(v[2]);
s.capacity[std::stoi(v[1])] = std::stoi(v[3]);
} else if (k == "wallet" && v.size() == 3) s.wallet[std::stoi(v[1])] = std::stoi(v[2]);
else if (k == "account" && v.size() == 15) {
Account a;
a.id = v[1]; a.pan = v[2]; a.holder = v[3]; a.exp = v[4]; a.pin = v[5]; a.tries = std::stoi(v[6]);
a.captured = v[7] == "1"; a.checking = std::stoll(v[8]); a.savings = std::stoll(v[9]); a.acctNo = v[10];
a.limit = std::stoll(v[11]); a.withdrawn = std::stoll(v[12]); a.day = v[13]; a.note = v[14];
if (a.pan.size() < 4) return false;
s.accounts.push_back(a);
} else if (k == "tx" && v.size() == 5) {
for (Account& a : s.accounts)
if (a.id == v[1]) a.tx.push_back({std::stoll(v[2]), std::stoll(v[3]), v[4]});
} else if (k == "receipt" && v.size() >= 2) {
s.receipts.push_back({std::stoll(v[1]), std::vector<std::string>(v.begin() + 2, v.end())});
} else if (k == "journal" && v.size() >= 2) {
s.journal.push_back(line.substr(8));
}
}
} catch (const std::exception&) {
return false;
}
for (int d : DENOMS)
if (!s.cassettes.count(d) || !s.capacity.count(d) || s.capacity[d] <= 0) return false;
if (s.accounts.size() != 3) return false;
st = s;
return true;
}
static void rollDay(Account& a) {
if (a.day != today()) {
a.day = today();
a.withdrawn = 0;
}
}
// Electronic journal, like a real ATM's EJ.
static void jr(const std::string& msg) {
st.journal.push_back(strftimeMs(nowMs(), "%H:%M:%S") + " " + msg);
if (st.journal.size() > 300) st.journal.erase(st.journal.begin(), st.journal.end() - 300);
save();
}
static long long nextTrn() {
++st.trn;
save();
return st.trn;
}
static std::string authCode() {
static std::mt19937 rng{std::random_device{}()};
static const char* abc = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
std::string s;
for (int i = 0; i < 6; ++i) s += abc[rng() % 36];
return s;
}
// ---- cash logic ----
static int notesTotal(const Notes& n) {
int s = 0;
for (int d : DENOMS) s += (n.count(d) ? n.at(d) : 0) * d;
return s;
}
static int notesCount(const Notes& n) {
int s = 0;
for (int d : DENOMS) s += n.count(d) ? n.at(d) : 0;
return s;
}
static std::string notesStr(const Notes& n) {
std::string s;
for (int d : DENOMS)
if (n.count(d) && n.at(d)) s += (s.empty() ? "" : " ") + std::to_string(d) + "x" + std::to_string(n.at(d));
return s;
}
static bool cashAvailable() {
for (int d : DENOMS)
if (st.cassettes[d] > 0) return true;
return false;
}
// Fewest notes (max 40) that the cassettes can actually pay out.
static bool noteMix(int euros, Notes& out) {
bool found = false;
int bestCount = 0;
Notes acc, best;
std::function<void(size_t, int, int)> rec = [&](size_t i, int rem, int count) {
if (found && count >= bestCount) return;
if (rem == 0) {
found = true;
bestCount = count;
best = acc;
return;
}
if (i >= std::size(DENOMS)) return;
int d = DENOMS[i];
int max = std::min(st.cassettes[d], rem / d);
for (int k = max; k >= 0; --k) {
acc[d] = k;
rec(i + 1, rem - k * d, count + k);
}
acc[d] = 0;
};
rec(0, euros, 0);
if (!found || bestCount > MAX_NOTES) return false;
out = best;
return true;
}
// ============================================================================
// Themes
// ============================================================================
struct Theme {
std::string base, title, err, ok, dim, key, primary, field, frame, brand, glass;
};
static Theme th;
static const char* RESET = "\x1b[0m";
static bool setTheme(const std::string& name) {
auto mk = [](int bg, int fg, int title, int err, int ok, int dim, int keyBg, int fieldBg, int fieldFg) {
auto c = [](const std::string& s) { return "\x1b[" + s + "m"; };
Theme t;
t.base = std::string(RESET) + c("48;5;" + std::to_string(bg)) + c("38;5;" + std::to_string(fg));
t.title = c("1;38;5;" + std::to_string(title));
t.err = c("1;38;5;" + std::to_string(err));
t.ok = c("1;38;5;" + std::to_string(ok));
t.dim = c("38;5;" + std::to_string(dim));
t.key = c("1;38;5;16;48;5;" + std::to_string(keyBg));
t.primary = c("1;4;38;5;" + std::to_string(title));
t.field = c("1;38;5;" + std::to_string(fieldFg) + ";48;5;" + std::to_string(fieldBg));
t.frame = c("38;5;247");
t.brand = c("1;38;5;37");
t.glass = c("38;5;240");
return t;
};
if (name == "brand") th = mk(23, 255, 231, 217, 120, 116, 252, 255, 23); // teal, like the GUI
else if (name == "classic") th = mk(16, 40, 46, 203, 46, 28, 34, 46, 16); // green phosphor
else if (name == "blue") th = mk(18, 255, 231, 217, 120, 111, 252, 255, 18); // modern blue
else if (name == "amber") th = mk(16, 214, 220, 203, 220, 130, 214, 214, 16); // amber CRT
else if (name == "mono") {
th = Theme{RESET, "\x1b[1m", "\x1b[1m", "\x1b[1m", "\x1b[2m", "\x1b[7m", "\x1b[1;4m", "\x1b[7m", "", "\x1b[1m", ""};
} else {
return false;
}
return true;
}
// Styled segment inside the screen glass (returns to the glass colours afterwards).
static std::string sty(const std::string& style, const std::string& text) {
if (!g_color || style.empty()) return text;
return style + text + th.base;
}
// Styled segment outside the glass.
static std::string paint(const std::string& style, const std::string& text) {
if (!g_color || style.empty()) return text;
return style + text + RESET;
}
// ============================================================================
// Screen model and renderer
// ============================================================================
enum Style { ST_NORMAL, ST_TITLE, ST_ERR, ST_BIG, ST_DIM, ST_OK };
enum Field { F_NONE, F_PIN, F_EURO, F_CENTS, F_DIGITS };
enum Led { L_OFF, L_ON, L_BLINK };
struct Line {
std::string s;
int style = ST_NORMAL;
};
struct Opt {
char side; // 'L' or 'R', like the function keys beside a real ATM screen
int row; // 1..4
std::string label;
bool primary = false;
bool disabled = false;
char key = 0;
};
struct Screen {
std::string title, text, hint;
bool err = false, center = true, spinner = false, noTimeout = false, locked = false;
std::vector<Line> body;
int field = F_NONE;
int fmax = 0;
std::vector<Opt> opts;
};
static const int SW = 62; // visible width of the screen glass
static const int CW = SW - 2; // usable content width
static const int SH = 14; // rows on the screen glass
static struct {
int card = L_OFF, rcpt = L_OFF, cash = L_OFF;
} led;
static const char* SPIN[] = {"⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"};
static void assignKeys(Screen& s) {
if (s.field != F_NONE) return; // field screens use letter keys set by the caller
int k = 0;
for (char side : {'L', 'R'})
for (int row = 1; row <= 4; ++row)
for (Opt& o : s.opts)
if (o.side == side && o.row == row) o.key = static_cast<char>('1' + k++);
}
static std::string keyLabel(char k) { return k == '\n' ? "↵" : std::string(1, static_cast<char>(k >= 'a' && k <= 'z' ? k - 32 : k)); }
static std::string fieldStr(const Screen& s, const std::string& buf) {
std::string v;
switch (s.field) {