Skip to content

Commit

Permalink
import file code
Browse files Browse the repository at this point in the history
  • Loading branch information
praslnx8 committed Jan 6, 2024
1 parent d170752 commit 27d91cb
Show file tree
Hide file tree
Showing 4 changed files with 108 additions and 11 deletions.
51 changes: 45 additions & 6 deletions lib/api/apis/backup_api.dart
Original file line number Diff line number Diff line change
@@ -1,31 +1,70 @@
import 'dart:convert';
// ignore: avoid_web_libraries_in_flutter
import 'dart:html' as html;

import 'dart:html';

import 'package:flutter/services.dart';
import 'package:logger/logger.dart';
import 'package:wealth_wave/api/db/app_database.dart';

class BackupApi {
final AppDatabase _db;

BackupApi({final AppDatabase? db}) : _db = db ?? AppDatabase.instance;

Future<void> importDatabase() async {
final file = await _pickFile();
if (file == null) {
return Future.error('No file selected');
}

final json = await _readJsonFromFile(file);

if (json == null) {
return Future.error('Not a json file');
}

await _db.loadBackup(json);
}

Future<void> exportDatabase() async {
final result = await _db.getBackup();

final jsonString = json.encode(result);

final blob = html.Blob([Uint8List.fromList(utf8.encode(jsonString))]);
final blob = Blob([Uint8List.fromList(utf8.encode(jsonString))]);

final anchor = html.AnchorElement(href: html.Url.createObjectUrlFromBlob(blob))
final anchor = AnchorElement(href: Url.createObjectUrlFromBlob(blob))
..target = 'blank'
..download = 'wealth_app_data.json';

// Trigger a click event to prompt the user to download the file
html.document.body?.append(anchor);
document.body?.append(anchor);
anchor.click();
// Clean up
html.Url.revokeObjectUrl(anchor.href!);
Url.revokeObjectUrl(anchor.href!);
}

Future<File?> _pickFile() async {
final input = FileUploadInputElement()..accept = 'application/json';
input.click();

await input.onChange.first;
return input.files?.isNotEmpty == true ? input.files![0] : null;
}

Future<Map<String, List<Map<String, dynamic>>>?> _readJsonFromFile(
File file) async {
try {
final reader = FileReader();
reader.readAsText(file);

await reader.onLoad.first;

final jsonString = reader.result as String;
return json.decode(jsonString) as Map<String, List<Map<String, dynamic>>>;
} catch (e) {
Logger().e(e.toString());
return null;
}
}
}
22 changes: 22 additions & 0 deletions lib/api/db/app_database.dart
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,28 @@ class AppDatabase extends _$AppDatabase {
'goal_investment_table': goalInvestmentBackup,
};
}

Future<void> loadBackup(
Map<String, List<Map<String, dynamic>>> backup) async {
await transaction(() async {
for (var entry in backup.entries) {
var tableName = entry.key;
var tableDatas = entry.value;

for (var tableData in tableDatas) {
var columns = tableData.keys.join(', ');
var values = tableData.keys.map((key) => '?').join(', ');

await customInsert(
'INSERT INTO $tableName ($columns) VALUES ($values)',
variables: tableData.values
.map((value) => Variable.withString('$value'))
.toList(),
);
}
}
});
}
}

DatabaseConnection connectOnWeb() {
Expand Down
28 changes: 28 additions & 0 deletions lib/presentation/main_presenter.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import 'package:wealth_wave/api/apis/backup_api.dart';
import 'package:wealth_wave/core/presenter.dart';
import 'package:wealth_wave/core/single_event.dart';

class MainPresenter extends Presenter<MainViewState> {
final BackupApi _backupApi;

MainPresenter({final BackupApi? backupApi})
: _backupApi = backupApi ?? BackupApi(),
super(MainViewState());

void performImportFile() {
_backupApi.importDatabase().then((value) => updateViewState((viewState) {
viewState.onImportCompleted = SingleEvent(null);
}));
}

void performBackup() {
_backupApi.exportDatabase().then((value) => updateViewState((viewState) {
viewState.onBackupCompleted = SingleEvent(null);
}));
}
}

class MainViewState {
SingleEvent<void>? onBackupCompleted;
SingleEvent<void>? onImportCompleted;
}
18 changes: 13 additions & 5 deletions lib/ui/pages/main_page.dart
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import 'package:flutter/material.dart';
import 'package:wealth_wave/api/apis/backup_api.dart';
import 'package:wealth_wave/core/page_state.dart';
import 'package:wealth_wave/presentation/main_presenter.dart';
import 'package:wealth_wave/ui/pages/baskets_page.dart';
import 'package:wealth_wave/ui/pages/goals_page.dart';
import 'package:wealth_wave/ui/pages/investments_page.dart';
Expand All @@ -13,12 +14,12 @@ class MainPage extends StatefulWidget {
State<MainPage> createState() => _MainPageState();
}

class _MainPageState extends State<MainPage> {
class _MainPageState extends PageState<MainViewState, MainPage, MainPresenter> {
var _selectedIndex = 0;
var _isExtended = true;

@override
Widget build(BuildContext context) {
Widget buildWidget(BuildContext context, MainViewState snapshot) {
return Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
Expand All @@ -27,8 +28,10 @@ class _MainPageState extends State<MainPage> {
PopupMenuButton<int>(
onSelected: (value) {
if (value == 1) {
BackupApi().exportDatabase();
} else if (value == 2) {}
presenter.performBackup();
} else if (value == 2) {
presenter.performImportFile();
}
},
itemBuilder: (context) => [
const PopupMenuItem(
Expand Down Expand Up @@ -91,6 +94,11 @@ class _MainPageState extends State<MainPage> {
),
));
}

@override
MainPresenter initializePresenter() {
return MainPresenter();
}
}

class SideNav extends StatelessWidget {
Expand Down

0 comments on commit 27d91cb

Please sign in to comment.