feat: allow creating new wallets + fix bugs

This commit is contained in:
Matyáš Caras 2023-11-01 18:39:21 +01:00
parent f614c4dfac
commit 574180c5f2
Signed by untrusted user who does not match committer: hernik
GPG key ID: 2A3175F98820C5C6
6 changed files with 199 additions and 129 deletions

View file

@ -1,4 +1,3 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart'; import 'package:integration_test/integration_test.dart';

View file

@ -5,13 +5,17 @@ import 'package:path_provider/path_provider.dart';
import 'package:prasule/api/wallet.dart'; import 'package:prasule/api/wallet.dart';
class WalletManager { class WalletManager {
static Future<List<String>> listWallets() async { static Future<List<Wallet>> listWallets() async {
var path = var path =
Directory("${(await getApplicationDocumentsDirectory()).path}/wallets"); Directory("${(await getApplicationDocumentsDirectory()).path}/wallets");
if (!path.existsSync()) { if (!path.existsSync()) {
path.createSync(); path.createSync();
} }
return path.listSync().map((e) => e.path.split("/").last).toList(); var wallets = <Wallet>[];
for (var w in path.listSync().map((e) => e.path.split("/").last).toList()) {
wallets.add(await loadWallet(w));
}
return wallets;
} }
static Future<Wallet> loadWallet(String name) async { static Future<Wallet> loadWallet(String name) async {
@ -27,14 +31,16 @@ class WalletManager {
return Wallet.fromJson(jsonDecode(wallet.readAsStringSync())); return Wallet.fromJson(jsonDecode(wallet.readAsStringSync()));
} }
static Future<void> saveWallet(Wallet w) async { static Future<bool> saveWallet(Wallet w) async {
var path = var path =
Directory("${(await getApplicationDocumentsDirectory()).path}/wallets"); Directory("${(await getApplicationDocumentsDirectory()).path}/wallets");
var wallet = File("${path.path}/${w.name}"); var wallet = File("${path.path}/${w.name}");
if (!path.existsSync()) { if (!path.existsSync()) {
path.createSync(); path.createSync();
} }
if (wallet.existsSync()) return false;
wallet.writeAsStringSync(jsonEncode(w.toJson())); wallet.writeAsStringSync(jsonEncode(w.toJson()));
return true;
} }
static Future<void> deleteWallet(Wallet w) async { static Future<void> deleteWallet(Wallet w) async {

View file

@ -7,7 +7,7 @@
"back": "Zpět", "back": "Zpět",
"finish": "Dokončit", "finish": "Dokončit",
"errorEmptyName": "Název nemůže být prázdný!", "errorEmptyName": "Název nemůže být prázdný!",
"welcome": "Vítej!", "welcome": "Vítejte!",
"welcomeAboutPrasule": "Prašule je správce výdajů navržený pro lidi, kteří nechtějí vyplňovat každý malý detail.", "welcomeAboutPrasule": "Prašule je správce výdajů navržený pro lidi, kteří nechtějí vyplňovat každý malý detail.",
"welcomeInstruction": "Na této obrazovce si nastavíte svoji 'peněženku', ve které budou zaznamenány vaše výdaje uspořádané do kategorií, které si nastavíte hned potom.", "welcomeInstruction": "Na této obrazovce si nastavíte svoji 'peněženku', ve které budou zaznamenány vaše výdaje uspořádané do kategorií, které si nastavíte hned potom.",
"setupWalletNameCurrency": "Nastavte si název a měnu peněženky", "setupWalletNameCurrency": "Nastavte si název a měnu peněženky",
@ -53,5 +53,8 @@
"langDownloadProgress": "Postup: $progress %", "langDownloadProgress": "Postup: $progress %",
"addingFromOcr": "Přidat skrz OCR", "addingFromOcr": "Přidat skrz OCR",
"license":"©️ 2023 Matyáš Caras\nVydáno pod licencí GNU AGPL license verze 3", "license":"©️ 2023 Matyáš Caras\nVydáno pod licencí GNU AGPL license verze 3",
"description":"Popis" "description":"Popis",
"newWallet":"Přidat novou peněženku",
"walletExists":"Peněženka s tímto názvem již existuje!"
} }

View file

@ -89,5 +89,7 @@
}, },
"addingFromOcr": "Add from OCR", "addingFromOcr": "Add from OCR",
"license":"©️ 2023 Matyáš Caras\nReleased under the GNU AGPL license version 3", "license":"©️ 2023 Matyáš Caras\nReleased under the GNU AGPL license version 3",
"description":"Description" "description":"Description",
"newWallet":"Add new wallet",
"walletExists":"A wallet with this name already exists!"
} }

View file

@ -31,6 +31,7 @@ class HomeView extends StatefulWidget {
class _HomeViewState extends State<HomeView> { class _HomeViewState extends State<HomeView> {
Wallet? selectedWallet; Wallet? selectedWallet;
List<Wallet> wallets = [];
DateTime? prevDate; DateTime? prevDate;
late String locale; late String locale;
@override @override
@ -47,13 +48,13 @@ class _HomeViewState extends State<HomeView> {
} }
void loadWallet() async { void loadWallet() async {
var wallets = await WalletManager.listWallets(); wallets = await WalletManager.listWallets();
if (wallets.isEmpty && mounted) { if (wallets.isEmpty && mounted) {
Navigator.of(context).pushReplacement( Navigator.of(context).pushReplacement(
MaterialPageRoute(builder: (c) => const SetupView())); MaterialPageRoute(builder: (c) => const SetupView()));
return; return;
} }
selectedWallet = await WalletManager.loadWallet(wallets.first); selectedWallet = wallets.first;
setState(() {}); setState(() {});
} }
@ -98,7 +99,42 @@ class _HomeViewState extends State<HomeView> {
], ],
), ),
appBar: AppBar( appBar: AppBar(
title: Text(AppLocalizations.of(context)!.home), title: DropdownButton<int>(
value:
(selectedWallet == null) ? -1 : wallets.indexOf(selectedWallet!),
items: [
...wallets.map(
(e) => DropdownMenuItem(
value: wallets.indexOf(
e,
),
child: Text(e.name),
),
),
DropdownMenuItem(
value: -1,
child: Text(AppLocalizations.of(context)!.newWallet),
)
],
onChanged: (v) async {
if (v == null || v == -1) {
Navigator.of(context).push(
platformRoute(
(c) => const SetupView(
newWallet: true,
),
),
);
wallets = await WalletManager.listWallets();
logger.i(wallets.length);
selectedWallet = wallets.last;
setState(() {});
return;
}
selectedWallet = wallets[v];
setState(() {});
},
),
actions: [ actions: [
PopupMenuButton( PopupMenuButton(
itemBuilder: (context) => [ itemBuilder: (context) => [
@ -293,8 +329,8 @@ class _HomeViewState extends State<HomeView> {
} }
// get selected languages // get selected languages
var selected = availableLanguages var selected = availableLanguages
.where((element) => selectedLanguages[ .where((element) =>
availableLanguages.indexOf(element)]) selectedLanguages[availableLanguages.indexOf(element)])
.join("+") .join("+")
.replaceAll(".traineddata", ""); .replaceAll(".traineddata", "");
logger.i(selected); logger.i(selected);
@ -338,9 +374,7 @@ class _HomeViewState extends State<HomeView> {
w: selectedWallet!, w: selectedWallet!,
editEntry: WalletSingleEntry( editEntry: WalletSingleEntry(
data: EntryData( data: EntryData(
name: "", name: "", amount: price, description: description),
amount: price,
description: description),
type: EntryType.expense, type: EntryType.expense,
date: DateTime.now(), date: DateTime.now(),
category: selectedWallet!.categories.first, category: selectedWallet!.categories.first,
@ -359,12 +393,14 @@ class _HomeViewState extends State<HomeView> {
}, },
); );
}, },
child: const Text("Ok")), child: const Text("Ok"),
),
TextButton( TextButton(
onPressed: () { onPressed: () {
Navigator.of(c).pop(); Navigator.of(c).pop();
}, },
child: const Text("Cancel")), child: const Text("Cancel"),
),
], ],
title: AppLocalizations.of(context)!.ocrSelect, title: AppLocalizations.of(context)!.ocrSelect,
content: Column( content: Column(

View file

@ -12,8 +12,10 @@ import 'package:prasule/views/home.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart'; import 'package:flutter_gen/gen_l10n/app_localizations.dart';
class SetupView extends StatefulWidget { class SetupView extends StatefulWidget {
const SetupView({super.key}); const SetupView({super.key, this.newWallet = false});
/// We are only creating a new wallet, no first-time setup
final bool newWallet;
@override @override
State<SetupView> createState() => _SetupViewState(); State<SetupView> createState() => _SetupViewState();
} }
@ -36,8 +38,9 @@ class _SetupViewState extends State<SetupView> {
var name = ""; var name = "";
@override @override
void initState() { void didChangeDependencies() {
super.initState(); super.didChangeDependencies();
if (categories.isEmpty) {
categories = [ categories = [
WalletCategory( WalletCategory(
name: AppLocalizations.of(context)!.categoryHealth, name: AppLocalizations.of(context)!.categoryHealth,
@ -50,13 +53,15 @@ class _SetupViewState extends State<SetupView> {
name: AppLocalizations.of(context)!.categoryCar, name: AppLocalizations.of(context)!.categoryCar,
type: EntryType.expense, type: EntryType.expense,
id: 2, id: 2,
icon: IconData(Icons.car_repair.codePoint, fontFamily: 'MaterialIcons'), icon:
IconData(Icons.car_repair.codePoint, fontFamily: 'MaterialIcons'),
), ),
WalletCategory( WalletCategory(
name: AppLocalizations.of(context)!.categoryFood, name: AppLocalizations.of(context)!.categoryFood,
type: EntryType.expense, type: EntryType.expense,
id: 3, id: 3,
icon: IconData(Icons.restaurant.codePoint, fontFamily: 'MaterialIcons'), icon:
IconData(Icons.restaurant.codePoint, fontFamily: 'MaterialIcons'),
), ),
WalletCategory( WalletCategory(
name: AppLocalizations.of(context)!.categoryTravel, name: AppLocalizations.of(context)!.categoryTravel,
@ -67,6 +72,7 @@ class _SetupViewState extends State<SetupView> {
]; ];
setState(() {}); setState(() {});
} }
}
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
@ -99,11 +105,27 @@ class _SetupViewState extends State<SetupView> {
currency: _selectedCurrency, currency: _selectedCurrency,
categories: categories); categories: categories);
WalletManager.saveWallet(wallet).then( WalletManager.saveWallet(wallet).then(
(value) => Navigator.of(context).pushReplacement( (value) {
if (!value) {
ScaffoldMessenger.of(context).clearSnackBars();
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content:
Text(AppLocalizations.of(context)!.walletExists),
),
);
return;
}
if (widget.newWallet) {
Navigator.of(context).pop();
return;
}
Navigator.of(context).pushReplacement(
MaterialPageRoute( MaterialPageRoute(
builder: (c) => const HomeView(), builder: (c) => const HomeView(),
), ),
), );
},
); );
}, },
pages: [ pages: [
@ -123,10 +145,12 @@ class _SetupViewState extends State<SetupView> {
mainAxisAlignment: MainAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center,
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,
children: [ children: [
if (!widget.newWallet)
Flexible( Flexible(
child: Text( child: Text(
AppLocalizations.of(context)!.welcomeAboutPrasule), AppLocalizations.of(context)!.welcomeAboutPrasule),
), ),
if (!widget.newWallet)
const SizedBox( const SizedBox(
height: 5, height: 5,
), ),