Skip to content

Commit

Permalink
Dashboard with real data
Browse files Browse the repository at this point in the history
. add dashboard provider for real data on home page
. fix a bug in transactions list not showing some transaction
  • Loading branch information
lucaantonelli committed Dec 26, 2023
1 parent c883459 commit b7164d3
Show file tree
Hide file tree
Showing 13 changed files with 291 additions and 276 deletions.
74 changes: 23 additions & 51 deletions lib/custom_widgets/accounts_sum.dart
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,9 @@ class AccountsSum extends ConsumerWidget with Functions {
final BankAccount account;

const AccountsSum({
Key? key,
super.key,
required this.account,
}) : super(key: key);
});

@override
Widget build(BuildContext context, WidgetRef ref) {
Expand All @@ -40,8 +40,7 @@ class AccountsSum extends ConsumerWidget with Functions {
await ref
.read(accountsProvider.notifier)
.selectedAccount(account)
.whenComplete(
() => Navigator.of(context).pushNamed('/account'));
.whenComplete(() => Navigator.of(context).pushNamed('/account'));
},
child: Container(
padding: const EdgeInsets.fromLTRB(12, 8, 12, 8),
Expand All @@ -68,53 +67,26 @@ class AccountsSum extends ConsumerWidget with Functions {
children: [
Text(
account.name,
style: Theme.of(context)
.textTheme
.bodyLarge!
.copyWith(color: darkBlue7),
), // TODO: set dinamically instead of hardcoded
FutureBuilder<num?>(
future: BankAccountMethods().getAccountSum(account.id),
builder: (context, snapshot) {
if (snapshot.connectionState ==
ConnectionState.waiting) {
// Show a loading indicator while waiting for the future to complete
return Transform.scale(
scale: 0.5,
child: const CircularProgressIndicator(),
);
} else if (snapshot.hasError) {
// Show an error message if the future encounters an error
return Text('Error: ${snapshot.error}');
} else {
// Display the result once the future completes successfully
final accountSum = snapshot.data ?? 0;
return RichText(
textScaleFactor:
MediaQuery.of(context).textScaleFactor,
text: TextSpan(
children: [
TextSpan(
text: numToCurrency(accountSum),
style:
Theme.of(context).textTheme.titleSmall!.copyWith(color: darkBlue7),
),
TextSpan(
text: "€",
style: Theme.of(context)
.textTheme
.bodyMedium
?.apply(
fontFeatures: [
const FontFeature.subscripts()
],
).copyWith(color: darkBlue7),
),
],
),
);
}
},
style: Theme.of(context).textTheme.bodyLarge!.copyWith(color: darkBlue7),
),
RichText(
text: TextSpan(
children: [
TextSpan(
text: numToCurrency(account.total),
style: Theme.of(context)
.textTheme
.titleSmall!
.copyWith(color: darkBlue7),
),
TextSpan(
text: "€",
style: Theme.of(context).textTheme.bodyMedium?.apply(
fontFeatures: [const FontFeature.subscripts()],
).copyWith(color: darkBlue7),
),
],
),
),
],
),
Expand Down
10 changes: 1 addition & 9 deletions lib/custom_widgets/line_chart.dart
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,6 @@ class LineChartWidget extends StatefulWidget {
final List<FlSpot> line2Data; //this should be a list of Flspot(x,y), if you only need one just put an empty list
final Color colorLine2Data;

//These will be used to determine the max value of the chart in order to get the right visualization of the data
final double maxY;
final double minY;

//Contains the number of days of the month
final double maxDays;

Expand All @@ -24,9 +20,7 @@ class LineChartWidget extends StatefulWidget {
required this.line2Data,
required this.colorLine2Data,
required this.colorBackground,
required this.maxY,
required this.minY,
required this.maxDays,
this.maxDays = 31,
});

@override
Expand Down Expand Up @@ -155,8 +149,6 @@ class _LineChartSample2State extends State<LineChartWidget> {
),
minX: 0,
maxX: widget.maxDays - 1,
minY: widget.minY,
maxY: widget.maxY,
lineBarsData: [
LineChartBarData(
spots: widget.line1Data,
Expand Down
7 changes: 4 additions & 3 deletions lib/main.dart
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:sossoldi/providers/theme_provider.dart';
import 'package:sossoldi/utils/app_theme.dart';
import 'routes.dart';
import 'package:intl/date_symbol_data_local.dart';

import 'providers/theme_provider.dart';
import 'routes.dart';
import 'utils/app_theme.dart';

void main() {
initializeDateFormatting('it_IT', null)
.then((_) => runApp(const ProviderScope(child: Launcher())));
Expand Down
31 changes: 23 additions & 8 deletions lib/model/bank_account.dart
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import 'package:sossoldi/model/transaction.dart';
import 'package:sqflite/sqflite.dart';

import '../database/sossoldi_database.dart';
import 'base_entity.dart';
import 'transaction.dart';

const String bankAccountTable = 'bankAccount';

Expand All @@ -14,6 +14,7 @@ class BankAccountFields extends BaseEntityFields {
static String startingValue = 'startingValue';
static String active = 'active';
static String mainAccount = 'mainAccount';
static String total = 'total';
static String createdAt = BaseEntityFields.getCreatedAt;
static String updatedAt = BaseEntityFields.getUpdatedAt;

Expand All @@ -37,18 +38,19 @@ class BankAccount extends BaseEntity {
final num startingValue;
final bool active;
final bool mainAccount;
final num? total;

const BankAccount(
{int? id,
{super.id,
required this.name,
required this.symbol,
required this.color,
required this.startingValue,
required this.mainAccount,
required this.active,
DateTime? createdAt,
DateTime? updatedAt})
: super(id: id, createdAt: createdAt, updatedAt: updatedAt);
required this.mainAccount,
this.total,
super.createdAt,
super.updatedAt});

BankAccount copy(
{int? id,
Expand Down Expand Up @@ -79,6 +81,7 @@ class BankAccount extends BaseEntity {
startingValue: json[BankAccountFields.startingValue] as num,
active: json[BankAccountFields.active] == 1 ? true : false,
mainAccount: json[BankAccountFields.mainAccount] == 1 ? true : false,
total: json[BankAccountFields.total] as num?,
createdAt: DateTime.parse(json[BaseEntityFields.createdAt] as String),
updatedAt: DateTime.parse(json[BaseEntityFields.updatedAt] as String));

Expand All @@ -101,7 +104,7 @@ class BankAccountMethods extends SossoldiDatabase {
final db = await database;

await changeMainAccount(db, item);

final id = await db.insert(bankAccountTable, item.toJson());
return item.copy(id: id);
}
Expand Down Expand Up @@ -146,7 +149,19 @@ class BankAccountMethods extends SossoldiDatabase {
final orderByASC = '${BankAccountFields.createdAt} ASC';
final where = '${BankAccountFields.active} = 1';

final result = await db.query(bankAccountTable, where:where, orderBy: orderByASC);
final result = await db.rawQuery('''
SELECT b.*, (b.${BankAccountFields.startingValue} +
SUM(CASE WHEN t.${TransactionFields.type} = 'IN' OR t.${TransactionFields.type} = 'TRSF' AND t.${TransactionFields.idBankAccountTransfer} = b.${BankAccountFields.id} THEN t.${TransactionFields.amount}
ELSE 0 END) -
SUM(CASE WHEN t.${TransactionFields.type} = 'OUT' OR t.${TransactionFields.type} = 'TRSF' AND t.${TransactionFields.idBankAccount} = b.${BankAccountFields.id} THEN t.${TransactionFields.amount}
ELSE 0 END)
) as ${BankAccountFields.total}
FROM $bankAccountTable as b
LEFT JOIN "$transactionTable" as t ON t.${TransactionFields.idBankAccount} = b.${BankAccountFields.id} OR t.${TransactionFields.idBankAccountTransfer} = b.${BankAccountFields.id}
WHERE $where
GROUP BY b.${BankAccountFields.id}
ORDER BY $orderByASC
''');

return result.map((json) => BankAccount.fromJson(json)).toList();
}
Expand Down
34 changes: 32 additions & 2 deletions lib/model/transaction.dart
Original file line number Diff line number Diff line change
Expand Up @@ -214,10 +214,10 @@ class TransactionMethods extends SossoldiDatabase {
String? where = type != null ? '${TransactionFields.type} = $type' : null; // filter type
if (date != null) {
where =
"${where != null ? '$where and ' : ''}${TransactionFields.date} >= '${date.toIso8601String().substring(0, 10)}T00:00:00' and ${TransactionFields.date} <= '${date.toIso8601String().substring(0, 10)}T23:59:59'";
"${where != null ? '$where and ' : ''}strftime('%Y-%m-%d', ${TransactionFields.date}) >= '${date.toString().substring(0, 10)}' and ${TransactionFields.date} <= '${date.toIso8601String().substring(0, 10)}'";
} else if (dateRangeStart != null && dateRangeEnd != null) {
where =
"${where != null ? '$where and ' : ''}${TransactionFields.date} BETWEEN '${dateRangeStart.toIso8601String().substring(0, 10)}T00:00:00' and '${dateRangeEnd.toIso8601String().substring(0, 10)}T23:59:59'";
"${where != null ? '$where and ' : ''}strftime('%Y-%m-%d', ${TransactionFields.date}) BETWEEN '${dateRangeStart.toString().substring(0, 10)}' and '${dateRangeEnd.toIso8601String().substring(0, 10)}'";
}

final orderByDESC = '${TransactionFields.date} DESC';
Expand All @@ -228,6 +228,36 @@ class TransactionMethods extends SossoldiDatabase {
return result.map((json) => Transaction.fromJson(json)).toList();
}

Future<List> currentMonthTransactions() async {
final db = await database;
final result = await db.rawQuery('''
SELECT
strftime('%Y-%m-%d', ${TransactionFields.date}) as day,
SUM(CASE WHEN ${TransactionFields.type} = 'IN' THEN ${TransactionFields.amount} ELSE 0 END) as income,
SUM(CASE WHEN ${TransactionFields.type} = 'OUT' THEN ${TransactionFields.amount} ELSE 0 END) as expense
FROM "$transactionTable"
WHERE strftime('%Y-%m', ${TransactionFields.date}) = strftime('%Y-%m', date('now'))
GROUP BY day
''');

return result;
}

Future<List> lastMonthTransactions() async {
final db = await database;
final result = await db.rawQuery('''
SELECT
strftime('%Y-%m-%d', ${TransactionFields.date}) as day,
SUM(CASE WHEN ${TransactionFields.type} = 'IN' THEN ${TransactionFields.amount} ELSE 0 END) as income,
SUM(CASE WHEN ${TransactionFields.type} = 'OUT' THEN ${TransactionFields.amount} ELSE 0 END) as expense
FROM "$transactionTable"
WHERE strftime('%Y-%m', ${TransactionFields.date}) = strftime('%Y-%m', date('now', '-1 month'))
GROUP BY day
''');

return result;
}

Future<int> updateItem(Transaction item) async {
final db = await database;

Expand Down
8 changes: 3 additions & 5 deletions lib/pages/account_page/account_page.dart
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import 'package:fl_chart/fl_chart.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:fl_chart/fl_chart.dart';

import '../../providers/accounts_provider.dart';
import '../../custom_widgets/line_chart.dart';
import '../../constants/functions.dart';
import '../../constants/style.dart';
import '../../custom_widgets/line_chart.dart';
import '../../providers/accounts_provider.dart';

class AccountPage extends ConsumerStatefulWidget {
const AccountPage({Key? key}) : super(key: key);
Expand Down Expand Up @@ -68,8 +68,6 @@ class _AccountPage extends ConsumerState<AccountPage> with Functions {
line2Data: <FlSpot>[],
colorLine2Data: Color(0xffffffff),
colorBackground: blue5,
maxY: 5.0,
minY: -5.0,
maxDays: 30.0,
),
],
Expand Down
Loading

0 comments on commit b7164d3

Please sign in to comment.