5 Commits

Author SHA1 Message Date
43e9196dca made icon optional and default to empty string & adjust all game instances
All checks were successful
Pull Request Pipeline / test (pull_request) Successful in 36s
Pull Request Pipeline / lint (pull_request) Successful in 46s
2026-03-09 16:24:04 +01:00
16dc9746bc refactor: rename callback for game creation/editing to onGameChanged
All checks were successful
Pull Request Pipeline / test (pull_request) Successful in 38s
Pull Request Pipeline / lint (pull_request) Successful in 44s
2026-03-08 20:02:50 +01:00
487a921def add error message for game deletion and implement search functionality
All checks were successful
Pull Request Pipeline / test (pull_request) Successful in 39s
Pull Request Pipeline / lint (pull_request) Successful in 45s
2026-03-08 17:01:41 +01:00
69f9900f74 fix linter issues
All checks were successful
Pull Request Pipeline / test (pull_request) Successful in 38s
Pull Request Pipeline / lint (pull_request) Successful in 44s
2026-03-08 15:19:20 +01:00
69d9397ab3 add functionality to create/edit/select groups
Some checks failed
Pull Request Pipeline / test (pull_request) Successful in 38s
Pull Request Pipeline / lint (pull_request) Failing after 44s
2026-03-08 14:49:48 +01:00
19 changed files with 742 additions and 372 deletions

View File

@@ -1,5 +1,9 @@
include: package:flutter_lints/flutter.yaml include: package:flutter_lints/flutter.yaml
analyzer:
exclude:
- lib/presentation/views/main_menu/settings_view/licenses/oss_licenses.dart
linter: linter:
rules: rules:
avoid_print: false avoid_print: false

View File

@@ -1,6 +1,6 @@
import 'package:clock/clock.dart'; import 'package:clock/clock.dart';
import 'package:uuid/uuid.dart';
import 'package:tallee/core/enums.dart'; import 'package:tallee/core/enums.dart';
import 'package:uuid/uuid.dart';
class Game { class Game {
final String id; final String id;
@@ -18,10 +18,11 @@ class Game {
required this.ruleset, required this.ruleset,
String? description, String? description,
required this.color, required this.color,
required this.icon, String? icon,
}) : id = id ?? const Uuid().v4(), }) : id = id ?? const Uuid().v4(),
createdAt = createdAt ?? clock.now(), createdAt = createdAt ?? clock.now(),
description = description ?? ''; description = description ?? '',
icon = icon ?? '';
@override @override
String toString() { String toString() {
@@ -49,4 +50,3 @@ class Game {
'icon': icon, 'icon': icon,
}; };
} }

View File

@@ -27,8 +27,8 @@ class Match {
String? notes, String? notes,
this.winner, this.winner,
}) : id = id ?? const Uuid().v4(), }) : id = id ?? const Uuid().v4(),
createdAt = createdAt ?? clock.now(), createdAt = createdAt ?? clock.now(),
notes = notes ?? ''; notes = notes ?? '';
@override @override
String toString() { String toString() {
@@ -38,14 +38,21 @@ class Match {
/// Creates a Match instance from a JSON object (ID references format). /// Creates a Match instance from a JSON object (ID references format).
/// Related objects are reconstructed from IDs by the DataTransferService. /// Related objects are reconstructed from IDs by the DataTransferService.
Match.fromJson(Map<String, dynamic> json) Match.fromJson(Map<String, dynamic> json)
: id = json['id'], : id = json['id'],
createdAt = DateTime.parse(json['createdAt']), createdAt = DateTime.parse(json['createdAt']),
endedAt = json['endedAt'] != null ? DateTime.parse(json['endedAt']) : null, endedAt = json['endedAt'] != null
name = json['name'], ? DateTime.parse(json['endedAt'])
game = Game(name: '', ruleset: Ruleset.singleWinner, description: '', color: GameColor.blue, icon: ''), // Populated during import via DataTransferService : null,
group = null, // Populated during import via DataTransferService name = json['name'],
players = [], // Populated during import via DataTransferService game = Game(
notes = json['notes'] ?? ''; name: '',
ruleset: Ruleset.singleWinner,
description: '',
color: GameColor.blue,
), // Populated during import via DataTransferService
group = null, // Populated during import via DataTransferService
players = [], // Populated during import via DataTransferService
notes = json['notes'] ?? '';
/// Converts the Match instance to a JSON object using normalized format (ID references only). /// Converts the Match instance to a JSON object using normalized format (ID references only).
Map<String, dynamic> toJson() => { Map<String, dynamic> toJson() => {

View File

@@ -34,6 +34,7 @@
"edit_match": "Gruppe bearbeiten", "edit_match": "Gruppe bearbeiten",
"enter_results": "Ergebnisse eintragen", "enter_results": "Ergebnisse eintragen",
"error_creating_group": "Fehler beim Erstellen der Gruppe, bitte erneut versuchen", "error_creating_group": "Fehler beim Erstellen der Gruppe, bitte erneut versuchen",
"error_deleting_game": "Fehler beim Löschen der Spielvorlage, bitte erneut versuchen",
"error_deleting_group": "Fehler beim Löschen der Gruppe, bitte erneut versuchen", "error_deleting_group": "Fehler beim Löschen der Gruppe, bitte erneut versuchen",
"error_editing_group": "Fehler beim Bearbeiten der Gruppe, bitte erneut versuchen", "error_editing_group": "Fehler beim Bearbeiten der Gruppe, bitte erneut versuchen",
"error_reading_file": "Fehler beim Lesen der Datei", "error_reading_file": "Fehler beim Lesen der Datei",

View File

@@ -104,6 +104,9 @@
"@error_creating_group": { "@error_creating_group": {
"description": "Error message when group creation fails" "description": "Error message when group creation fails"
}, },
"@error_deleting_game": {
"description": "Error message when game deletion fails"
},
"@error_deleting_group": { "@error_deleting_group": {
"description": "Error message when group deletion fails" "description": "Error message when group deletion fails"
}, },
@@ -376,6 +379,7 @@
"edit_match": "Edit Match", "edit_match": "Edit Match",
"enter_results": "Enter Results", "enter_results": "Enter Results",
"error_creating_group": "Error while creating group, please try again", "error_creating_group": "Error while creating group, please try again",
"error_deleting_game": "Error while deleting game, please try again",
"error_deleting_group": "Error while deleting group, please try again", "error_deleting_group": "Error while deleting group, please try again",
"error_editing_group": "Error while editing group, please try again", "error_editing_group": "Error while editing group, please try again",
"error_reading_file": "Error reading file", "error_reading_file": "Error reading file",

View File

@@ -296,6 +296,12 @@ abstract class AppLocalizations {
/// **'Error while creating group, please try again'** /// **'Error while creating group, please try again'**
String get error_creating_group; String get error_creating_group;
/// Error message when game deletion fails
///
/// In en, this message translates to:
/// **'Error while deleting game, please try again'**
String get error_deleting_game;
/// Error message when group deletion fails /// Error message when group deletion fails
/// ///
/// In en, this message translates to: /// In en, this message translates to:

View File

@@ -112,6 +112,10 @@ class AppLocalizationsDe extends AppLocalizations {
String get error_creating_group => String get error_creating_group =>
'Fehler beim Erstellen der Gruppe, bitte erneut versuchen'; 'Fehler beim Erstellen der Gruppe, bitte erneut versuchen';
@override
String get error_deleting_game =>
'Fehler beim Löschen der Spielvorlage, bitte erneut versuchen';
@override @override
String get error_deleting_group => String get error_deleting_group =>
'Fehler beim Löschen der Gruppe, bitte erneut versuchen'; 'Fehler beim Löschen der Gruppe, bitte erneut versuchen';

View File

@@ -112,6 +112,10 @@ class AppLocalizationsEn extends AppLocalizations {
String get error_creating_group => String get error_creating_group =>
'Error while creating group, please try again'; 'Error while creating group, please try again';
@override
String get error_deleting_game =>
'Error while deleting game, please try again';
@override @override
String get error_deleting_group => String get error_deleting_group =>
'Error while deleting group, please try again'; 'Error while deleting group, please try again';

View File

@@ -42,7 +42,12 @@ class _HomeViewState extends State<HomeView> {
2, 2,
Match( Match(
name: 'Skeleton Match', name: 'Skeleton Match',
game: Game(name: '', ruleset: Ruleset.singleWinner, description: '', color: GameColor.blue, icon: ''), game: Game(
name: '',
ruleset: Ruleset.singleWinner,
description: '',
color: GameColor.blue,
),
group: Group( group: Group(
name: 'Skeleton Group', name: 'Skeleton Group',
description: '', description: '',
@@ -104,7 +109,9 @@ class _HomeViewState extends State<HomeView> {
if (recentMatches.isNotEmpty) if (recentMatches.isNotEmpty)
for (Match match in recentMatches) for (Match match in recentMatches)
Padding( Padding(
padding: const EdgeInsets.symmetric(vertical: 6.0), padding: const EdgeInsets.symmetric(
vertical: 6.0,
),
child: MatchTile( child: MatchTile(
compact: true, compact: true,
width: constraints.maxWidth * 0.9, width: constraints.maxWidth * 0.9,
@@ -113,7 +120,8 @@ class _HomeViewState extends State<HomeView> {
await Navigator.of(context).push( await Navigator.of(context).push(
adaptivePageRoute( adaptivePageRoute(
fullscreenDialog: true, fullscreenDialog: true,
builder: (context) => MatchResultView(match: match), builder: (context) =>
MatchResultView(match: match),
), ),
); );
await updatedWinnerInRecentMatches(match.id); await updatedWinnerInRecentMatches(match.id);
@@ -121,7 +129,10 @@ class _HomeViewState extends State<HomeView> {
), ),
) )
else else
Center(heightFactor: 5, child: Text(loc.no_recent_matches_available)), Center(
heightFactor: 5,
child: Text(loc.no_recent_matches_available),
),
], ],
), ),
), ),
@@ -137,22 +148,40 @@ class _HomeViewState extends State<HomeView> {
Row( Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly, mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [ children: [
QuickCreateButton(text: 'Category 1', onPressed: () {}), QuickCreateButton(
QuickCreateButton(text: 'Category 2', onPressed: () {}), text: 'Category 1',
onPressed: () {},
),
QuickCreateButton(
text: 'Category 2',
onPressed: () {},
),
], ],
), ),
Row( Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly, mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [ children: [
QuickCreateButton(text: 'Category 3', onPressed: () {}), QuickCreateButton(
QuickCreateButton(text: 'Category 4', onPressed: () {}), text: 'Category 3',
onPressed: () {},
),
QuickCreateButton(
text: 'Category 4',
onPressed: () {},
),
], ],
), ),
Row( Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly, mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [ children: [
QuickCreateButton(text: 'Category 5', onPressed: () {}), QuickCreateButton(
QuickCreateButton(text: 'Category 6', onPressed: () {}), text: 'Category 5',
onPressed: () {},
),
QuickCreateButton(
text: 'Category 6',
onPressed: () {},
),
], ],
), ),
], ],
@@ -181,9 +210,11 @@ class _HomeViewState extends State<HomeView> {
matchCount = results[0] as int; matchCount = results[0] as int;
groupCount = results[1] as int; groupCount = results[1] as int;
loadedRecentMatches = results[2] as List<Match>; loadedRecentMatches = results[2] as List<Match>;
recentMatches = (loadedRecentMatches..sort((a, b) => b.createdAt.compareTo(a.createdAt))) recentMatches =
.take(2) (loadedRecentMatches
.toList(); ..sort((a, b) => b.createdAt.compareTo(a.createdAt)))
.take(2)
.toList();
if (mounted) { if (mounted) {
setState(() { setState(() {
isLoading = false; isLoading = false;

View File

@@ -2,7 +2,6 @@ import 'package:flutter/material.dart';
import 'package:tallee/core/adaptive_page_route.dart'; import 'package:tallee/core/adaptive_page_route.dart';
import 'package:tallee/core/common.dart'; import 'package:tallee/core/common.dart';
import 'package:tallee/core/custom_theme.dart'; import 'package:tallee/core/custom_theme.dart';
import 'package:tallee/core/enums.dart';
import 'package:tallee/data/dto/game.dart'; import 'package:tallee/data/dto/game.dart';
import 'package:tallee/l10n/generated/app_localizations.dart'; import 'package:tallee/l10n/generated/app_localizations.dart';
import 'package:tallee/presentation/views/main_menu/match_view/create_match/game_view/create_game_view.dart'; import 'package:tallee/presentation/views/main_menu/match_view/create_match/game_view/create_game_view.dart';
@@ -11,19 +10,24 @@ import 'package:tallee/presentation/widgets/tiles/title_description_list_tile.da
class ChooseGameView extends StatefulWidget { class ChooseGameView extends StatefulWidget {
/// A view that allows the user to choose a game from a list of available games /// A view that allows the user to choose a game from a list of available games
/// - [games]: A list of tuples containing the game name, description and ruleset /// - [games]: The list of available games
/// - [initialGameIndex]: The index of the initially selected game /// - [initialSelectedGameId]: The id of the initially selected game
/// - [onGamesUpdated]: Optional callback invoked when the games are updated
const ChooseGameView({ const ChooseGameView({
super.key, super.key,
required this.games, required this.games,
required this.initialGameIndex, required this.initialSelectedGameId,
this.onGamesUpdated,
}); });
/// A list of tuples containing the game name, description and ruleset /// A list of tuples containing the game name, description and ruleset
final List<(String, String, Ruleset)> games; final List<Game> games;
/// The index of the initially selected game /// The index of the initially selected game
final int initialGameIndex; final String initialSelectedGameId;
/// Optional callback invoked when the games are updated
final VoidCallback? onGamesUpdated;
@override @override
State<ChooseGameView> createState() => _ChooseGameViewState(); State<ChooseGameView> createState() => _ChooseGameViewState();
@@ -33,12 +37,18 @@ class _ChooseGameViewState extends State<ChooseGameView> {
/// Controller for the search bar /// Controller for the search bar
final TextEditingController searchBarController = TextEditingController(); final TextEditingController searchBarController = TextEditingController();
/// Currently selected game index /// Currently selected game id
late int selectedGameIndex; late String selectedGameId;
/// Games filtered according to the current search query
late List<Game> filteredGames;
@override @override
void initState() { void initState() {
selectedGameIndex = widget.initialGameIndex; selectedGameId = widget.initialSelectedGameId;
// Start with all games visible
filteredGames = List<Game>.from(widget.games);
super.initState(); super.initState();
} }
@@ -52,21 +62,29 @@ class _ChooseGameViewState extends State<ChooseGameView> {
leading: IconButton( leading: IconButton(
icon: const Icon(Icons.arrow_back_ios), icon: const Icon(Icons.arrow_back_ios),
onPressed: () { onPressed: () {
Navigator.of(context).pop(selectedGameIndex); Navigator.of(context).pop(selectedGameId);
}, },
), ),
actions: [ actions: [
IconButton( IconButton(
icon: const Icon(Icons.add), icon: const Icon(Icons.add),
onPressed: () async { onPressed: () async {
await Navigator.push( final result = await Navigator.push(
context, context,
adaptivePageRoute( adaptivePageRoute(
builder: (context) => CreateGameView( builder: (context) => CreateGameView(
callback: () {}, //TODO: implement callback onGameChanged: () {
widget.onGamesUpdated?.call();
},
), ),
), ),
); );
if (result != null && result.game != null) {
setState(() {
widget.games.insert(0, result.game);
});
_refreshFromSource();
}
}, },
), ),
], ],
@@ -80,7 +98,7 @@ class _ChooseGameViewState extends State<ChooseGameView> {
if (didPop) { if (didPop) {
return; return;
} }
Navigator.of(context).pop(selectedGameIndex); Navigator.of(context).pop(selectedGameId);
}, },
child: Column( child: Column(
children: [ children: [
@@ -89,48 +107,62 @@ class _ChooseGameViewState extends State<ChooseGameView> {
child: CustomSearchBar( child: CustomSearchBar(
controller: searchBarController, controller: searchBarController,
hintText: loc.game_name, hintText: loc.game_name,
onChanged: (value) {
_applySearchFilter(value);
},
), ),
), ),
const SizedBox(height: 5), const SizedBox(height: 5),
Expanded( Expanded(
child: ListView.builder( child: ListView.builder(
itemCount: widget.games.length, itemCount: filteredGames.length,
itemBuilder: (BuildContext context, int index) { itemBuilder: (BuildContext context, int index) {
final game = filteredGames[index];
return TitleDescriptionListTile( return TitleDescriptionListTile(
title: widget.games[index].$1, title: game.name,
description: widget.games[index].$2, description: game.description,
badgeText: translateRulesetToString( badgeText: translateRulesetToString(game.ruleset, context),
widget.games[index].$3, isHighlighted: selectedGameId == game.id,
context,
),
isHighlighted: selectedGameIndex == index,
onTap: () async { onTap: () async {
setState(() { setState(() {
if (selectedGameIndex == index) { if (selectedGameId == game.id) {
selectedGameIndex = -1; selectedGameId = '';
} else { } else {
selectedGameIndex = index; selectedGameId = game.id;
} }
}); });
}, },
onLongPress: () async { onLongPress: () async {
await Navigator.push( final result = await Navigator.push(
context, context,
adaptivePageRoute( adaptivePageRoute(
builder: (context) => CreateGameView( builder: (context) => CreateGameView(
//TODO: implement callback & giving real game to create game view gameToEdit: game,
gameToEdit: Game( onGameChanged: () {
name: 'Cabo', widget.onGamesUpdated?.call();
description: },
'Test Beschreibung mit sehr viel Inhalt',
ruleset: Ruleset.highestScore,
color: GameColor.blue,
icon: '',
),
callback: () {},
), ),
), ),
); );
if (result != null && result.game != null) {
// Find the index in the original list to mutate
final originalIndex = widget.games.indexWhere(
(g) => g.id == game.id,
);
if (originalIndex == -1) {
return;
}
if (result.delete) {
setState(() {
widget.games.removeAt(originalIndex);
});
} else {
setState(() {
widget.games[originalIndex] = result.game;
});
}
_refreshFromSource();
}
}, },
); );
}, },
@@ -141,4 +173,28 @@ class _ChooseGameViewState extends State<ChooseGameView> {
), ),
); );
} }
/// Applies the search filter to the games list based on [query].
void _applySearchFilter(String query) {
final q = query.toLowerCase().trim();
if (q.isEmpty) {
setState(() {
filteredGames = List<Game>.from(widget.games);
});
return;
}
setState(() {
filteredGames = widget.games.where((game) {
final name = game.name.toLowerCase();
final description = game.description.toLowerCase();
return name.contains(q) || description.contains(q);
}).toList();
});
}
/// Re-applies the current filter after the underlying games list changed.
void _refreshFromSource() {
_applySearchFilter(searchBarController.text);
}
} }

View File

@@ -18,9 +18,13 @@ import 'package:tallee/presentation/widgets/player_selection.dart';
import 'package:tallee/presentation/widgets/text_input/text_input_field.dart'; import 'package:tallee/presentation/widgets/text_input/text_input_field.dart';
import 'package:tallee/presentation/widgets/tiles/choose_tile.dart'; import 'package:tallee/presentation/widgets/tiles/choose_tile.dart';
/// A stateful widget for creating or editing a match.
class CreateMatchView extends StatefulWidget { class CreateMatchView extends StatefulWidget {
/// A view that allows creating a new match /// Constructor for `CreateMatchView`.
/// [onWinnerChanged]: Optional callback invoked when the winner is changed ///
/// [onWinnerChanged] is an optional callback invoked when the winner is changed.
/// [matchToEdit] is an optional match to prefill the fields.
/// [onMatchUpdated] is an optional callback invoked when the match is updated.
const CreateMatchView({ const CreateMatchView({
super.key, super.key,
this.onWinnerChanged, this.onWinnerChanged,
@@ -28,45 +32,49 @@ class CreateMatchView extends StatefulWidget {
this.onMatchUpdated, this.onMatchUpdated,
}); });
/// Optional callback invoked when the winner is changed /// Optional callback invoked when the winner is changed.
final VoidCallback? onWinnerChanged; final VoidCallback? onWinnerChanged;
/// Optional callback invoked when the match is updated /// Optional callback invoked when the match is updated.
final void Function(Match)? onMatchUpdated; final void Function(Match)? onMatchUpdated;
/// An optional match to prefill the fields /// An optional match to prefill the fields.
final Match? matchToEdit; final Match? matchToEdit;
@override @override
State<CreateMatchView> createState() => _CreateMatchViewState(); State<CreateMatchView> createState() => _CreateMatchViewState();
} }
/// The state class for `CreateMatchView`, managing the UI and logic for creating or editing a match.
class _CreateMatchViewState extends State<CreateMatchView> { class _CreateMatchViewState extends State<CreateMatchView> {
/// The database instance for accessing match data.
late final AppDatabase db; late final AppDatabase db;
/// Controller for the match name input field /// Controller for the match name input field.
final TextEditingController _matchNameController = TextEditingController(); final TextEditingController _matchNameController = TextEditingController();
/// Hint text for the match name input field /// Hint text for the match name input field.
String? hintText; String? hintText;
/// List of all groups from the database /// List of all games from the database.
List<Game> gamesList = [];
/// List of all groups from the database.
List<Group> groupsList = []; List<Group> groupsList = [];
/// List of all players from the database /// List of all players from the database.
List<Player> playerList = []; List<Player> playerList = [];
/// The currently selected group /// The currently selected group.
Group? selectedGroup; Group? selectedGroup;
/// The index of the currently selected game in [games] to mark it in /// The currently selected game.
/// the [ChooseGameView] Game? selectedGame;
int selectedGameIndex = -1;
/// The currently selected players /// The currently selected players.
List<Player> selectedPlayers = []; List<Player> selectedPlayers = [];
/// GlobalKey for ScaffoldMessenger to show snackbars /// GlobalKey for ScaffoldMessenger to show snackbars.
final _scaffoldMessengerKey = GlobalKey<ScaffoldMessengerState>(); final _scaffoldMessengerKey = GlobalKey<ScaffoldMessengerState>();
@override @override
@@ -78,14 +86,18 @@ class _CreateMatchViewState extends State<CreateMatchView> {
db = Provider.of<AppDatabase>(context, listen: false); db = Provider.of<AppDatabase>(context, listen: false);
// Load games, groups, and players from the database.
Future.wait([ Future.wait([
db.gameDao.getAllGames(),
db.groupDao.getAllGroups(), db.groupDao.getAllGroups(),
db.playerDao.getAllPlayers(), db.playerDao.getAllPlayers(),
]).then((result) async { ]).then((result) async {
groupsList = result[0] as List<Group>; gamesList = result[0] as List<Game>;
playerList = result[1] as List<Player>; gamesList.sort((a, b) => b.createdAt.compareTo(a.createdAt));
groupsList = result[1] as List<Group>;
playerList = result[2] as List<Player>;
// If a match is provided, prefill the fields // If a match is provided, prefill the fields.
if (widget.matchToEdit != null) { if (widget.matchToEdit != null) {
prefillMatchDetails(); prefillMatchDetails();
} }
@@ -105,11 +117,6 @@ class _CreateMatchViewState extends State<CreateMatchView> {
hintText ??= loc.match_name; hintText ??= loc.match_name;
} }
List<(String, String, Ruleset)> games = [
('Example Game 1', 'This is a description', Ruleset.lowestScore),
('Example Game 2', '', Ruleset.singleWinner),
];
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final loc = AppLocalizations.of(context); final loc = AppLocalizations.of(context);
@@ -130,6 +137,7 @@ class _CreateMatchViewState extends State<CreateMatchView> {
child: Column( child: Column(
mainAxisAlignment: MainAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.start,
children: [ children: [
// Match name input field.
Container( Container(
margin: CustomTheme.tileMargin, margin: CustomTheme.tileMargin,
child: TextInputField( child: TextInputField(
@@ -138,38 +146,48 @@ class _CreateMatchViewState extends State<CreateMatchView> {
maxLength: Constants.MAX_MATCH_NAME_LENGTH, maxLength: Constants.MAX_MATCH_NAME_LENGTH,
), ),
), ),
// Game selection tile.
ChooseTile( ChooseTile(
title: loc.game, title: loc.game,
trailingText: selectedGameIndex == -1 trailingText: selectedGame == null
? loc.none ? loc.none
: games[selectedGameIndex].$1, : selectedGame!.name,
onPressed: () async { onPressed: () async {
selectedGameIndex = await Navigator.of(context).push( final String? selectedGameId = await Navigator.of(context)
adaptivePageRoute( .push(
builder: (context) => ChooseGameView( adaptivePageRoute(
games: games, builder: (context) => ChooseGameView(
initialGameIndex: selectedGameIndex, games: gamesList,
), initialSelectedGameId: selectedGame?.id ?? '',
), onGamesUpdated: loadGames,
); ),
),
);
try {
selectedGame = gamesList.firstWhere(
(g) => g.id == selectedGameId,
);
} catch (_) {
selectedGame = null;
}
setState(() { setState(() {
if (selectedGameIndex != -1) { if (selectedGame != null) {
hintText = games[selectedGameIndex].$1; hintText = selectedGame!.name;
} else { } else {
hintText = loc.match_name; hintText = loc.match_name;
} }
}); });
}, },
), ),
// Group selection tile.
ChooseTile( ChooseTile(
title: loc.group, title: loc.group,
trailingText: selectedGroup == null trailingText: selectedGroup == null
? loc.none_group ? loc.none_group
: selectedGroup!.name, : selectedGroup!.name,
onPressed: () async { onPressed: () async {
// Remove all players from the previously selected group from
// the selected players list, in case the user deselects the
// group or selects a different group.
selectedPlayers.removeWhere( selectedPlayers.removeWhere(
(player) => (player) =>
selectedGroup?.members.any( selectedGroup?.members.any(
@@ -196,6 +214,7 @@ class _CreateMatchViewState extends State<CreateMatchView> {
}); });
}, },
), ),
// Player selection widget.
Expanded( Expanded(
child: PlayerSelection( child: PlayerSelection(
key: ValueKey(selectedGroup?.id ?? 'no_group'), key: ValueKey(selectedGroup?.id ?? 'no_group'),
@@ -208,6 +227,7 @@ class _CreateMatchViewState extends State<CreateMatchView> {
}, },
), ),
), ),
// Create or save button.
CustomWidthButton( CustomWidthButton(
text: buttonText, text: buttonText,
sizeRelativeToWidth: 0.95, sizeRelativeToWidth: 0.95,
@@ -229,16 +249,16 @@ class _CreateMatchViewState extends State<CreateMatchView> {
/// ///
/// Returns `true` if: /// Returns `true` if:
/// - A ruleset is selected AND /// - A ruleset is selected AND
/// - Either a group is selected OR at least 2 players are selected /// - Either a group is selected OR at least 2 players are selected.
bool _enableCreateGameButton() { bool _enableCreateGameButton() {
return (selectedGroup != null || return (selectedGroup != null ||
(selectedPlayers.length > 1) && selectedGameIndex != -1); (selectedPlayers.length > 1) && selectedGame != null);
} }
// If a match was provided to the view, it updates the match in the database /// Handles navigation when the create or save button is pressed.
// and navigates back to the previous screen. ///
// If no match was provided, it creates a new match in the database and /// If a match is being edited, updates the match in the database.
// navigates to the MatchResultView for the newly created match. /// Otherwise, creates a new match and navigates to the MatchResultView.
void buttonNavigation(BuildContext context) async { void buttonNavigation(BuildContext context) async {
if (widget.matchToEdit != null) { if (widget.matchToEdit != null) {
await updateMatch(); await updateMatch();
@@ -263,12 +283,8 @@ class _CreateMatchViewState extends State<CreateMatchView> {
} }
} }
/// Updates attributes of the existing match in the database based on the /// Updates the existing match in the database.
/// changes made in the edit view.
Future<void> updateMatch() async { Future<void> updateMatch() async {
//TODO: Remove when Games implemented
final tempGame = await getTemporaryGame();
final updatedMatch = Match( final updatedMatch = Match(
id: widget.matchToEdit!.id, id: widget.matchToEdit!.id,
name: _matchNameController.text.isEmpty name: _matchNameController.text.isEmpty
@@ -276,7 +292,7 @@ class _CreateMatchViewState extends State<CreateMatchView> {
: _matchNameController.text.trim(), : _matchNameController.text.trim(),
group: selectedGroup, group: selectedGroup,
players: selectedPlayers, players: selectedPlayers,
game: tempGame, game: selectedGame!,
winner: widget.matchToEdit!.winner, winner: widget.matchToEdit!.winner,
createdAt: widget.matchToEdit!.createdAt, createdAt: widget.matchToEdit!.createdAt,
endedAt: widget.matchToEdit!.endedAt, endedAt: widget.matchToEdit!.endedAt,
@@ -297,7 +313,13 @@ class _CreateMatchViewState extends State<CreateMatchView> {
); );
} }
// Add players who are in updatedMatch but not in the original match if (widget.matchToEdit!.game.id != updatedMatch.game.id) {
await db.matchDao.updateMatchGame(
matchId: widget.matchToEdit!.id,
gameId: updatedMatch.game.id,
);
}
for (var player in updatedMatch.players) { for (var player in updatedMatch.players) {
if (!widget.matchToEdit!.players.any((p) => p.id == player.id)) { if (!widget.matchToEdit!.players.any((p) => p.id == player.id)) {
await db.playerMatchDao.addPlayerToMatch( await db.playerMatchDao.addPlayerToMatch(
@@ -307,7 +329,6 @@ class _CreateMatchViewState extends State<CreateMatchView> {
} }
} }
// Remove players who are in the original match but not in updatedMatch
for (var player in widget.matchToEdit!.players) { for (var player in widget.matchToEdit!.players) {
if (!updatedMatch.players.any((p) => p.id == player.id)) { if (!updatedMatch.players.any((p) => p.id == player.id)) {
await db.playerMatchDao.removePlayerFromMatch( await db.playerMatchDao.removePlayerFromMatch(
@@ -323,11 +344,8 @@ class _CreateMatchViewState extends State<CreateMatchView> {
widget.onMatchUpdated?.call(updatedMatch); widget.onMatchUpdated?.call(updatedMatch);
} }
// Creates a new match and adds it to the database. /// Creates a new match and adds it to the database.
// Returns the created match.
Future<Match> createMatch() async { Future<Match> createMatch() async {
final tempGame = await getTemporaryGame();
Match match = Match( Match match = Match(
name: _matchNameController.text.isEmpty name: _matchNameController.text.isEmpty
? (hintText ?? '') ? (hintText ?? '')
@@ -335,42 +353,25 @@ class _CreateMatchViewState extends State<CreateMatchView> {
createdAt: DateTime.now(), createdAt: DateTime.now(),
group: selectedGroup, group: selectedGroup,
players: selectedPlayers, players: selectedPlayers,
game: tempGame, game: selectedGame!,
); );
await db.matchDao.addMatch(match: match); await db.matchDao.addMatch(match: match);
return match; return match;
} }
// TODO: Remove when games fully implemented /// Prefills the input fields if a match was provided to the view.
Future<Game> getTemporaryGame() async {
Game? game;
final selectedGame = games[selectedGameIndex];
game = Game(
name: selectedGame.$1,
description: selectedGame.$2,
ruleset: selectedGame.$3,
color: GameColor.blue,
icon: '',
);
await db.gameDao.addGame(game: game);
return game;
}
// If a match was provided to the view, this method prefills the input fields
void prefillMatchDetails() { void prefillMatchDetails() {
final match = widget.matchToEdit!; final match = widget.matchToEdit!;
_matchNameController.text = match.name; _matchNameController.text = match.name;
selectedPlayers = match.players; selectedPlayers = match.players;
selectedGame = match.game;
if (match.group != null) { if (match.group != null) {
selectedGroup = match.group; selectedGroup = match.group;
} }
} }
// If none of the selected players are from the currently selected group, /// Removes the group if none of its members are in the selected players list.
// the group is also deselected.
Future<void> removeGroupWhenNoMemberLeft() async { Future<void> removeGroupWhenNoMemberLeft() async {
if (selectedGroup == null) return; if (selectedGroup == null) return;
@@ -383,4 +384,13 @@ class _CreateMatchViewState extends State<CreateMatchView> {
}); });
} }
} }
/// Loads all games from the database and updates the state.
Future<void> loadGames() async {
final result = await db.gameDao.getAllGames();
result.sort((a, b) => b.createdAt.compareTo(a.createdAt));
setState(() {
gamesList = result;
});
}
} }

View File

@@ -1,41 +1,79 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:tallee/core/adaptive_page_route.dart'; import 'package:tallee/core/adaptive_page_route.dart';
import 'package:tallee/core/common.dart'; import 'package:tallee/core/common.dart';
import 'package:tallee/core/constants.dart'; import 'package:tallee/core/constants.dart';
import 'package:tallee/core/custom_theme.dart'; import 'package:tallee/core/custom_theme.dart';
import 'package:tallee/core/enums.dart'; import 'package:tallee/core/enums.dart';
import 'package:tallee/data/db/database.dart';
import 'package:tallee/data/dto/game.dart'; import 'package:tallee/data/dto/game.dart';
import 'package:tallee/data/dto/group.dart';
import 'package:tallee/l10n/generated/app_localizations.dart'; import 'package:tallee/l10n/generated/app_localizations.dart';
import 'package:tallee/presentation/views/main_menu/match_view/create_match/game_view/choose_color_view.dart'; import 'package:tallee/presentation/views/main_menu/match_view/create_match/game_view/choose_color_view.dart';
import 'package:tallee/presentation/views/main_menu/match_view/create_match/game_view/choose_ruleset_view.dart'; import 'package:tallee/presentation/views/main_menu/match_view/create_match/game_view/choose_ruleset_view.dart';
import 'package:tallee/presentation/widgets/buttons/custom_width_button.dart'; import 'package:tallee/presentation/widgets/buttons/custom_width_button.dart';
import 'package:tallee/presentation/widgets/custom_alert_dialog.dart';
import 'package:tallee/presentation/widgets/text_input/text_input_field.dart'; import 'package:tallee/presentation/widgets/text_input/text_input_field.dart';
import 'package:tallee/presentation/widgets/tiles/choose_tile.dart'; import 'package:tallee/presentation/widgets/tiles/choose_tile.dart';
/// A stateful widget for creating or editing a game.
/// - [gameToEdit] An optional game to prefill the fields
/// - [onGameChanged] Callback to invoke when the game is created or edited
class CreateGameView extends StatefulWidget { class CreateGameView extends StatefulWidget {
const CreateGameView({super.key, this.gameToEdit, required this.callback}); const CreateGameView({
super.key,
this.gameToEdit,
required this.onGameChanged,
});
/// An optional game to prefill the fields
final Game? gameToEdit; final Game? gameToEdit;
final VoidCallback callback; /// Callback to invoke when the game is created or edited
final VoidCallback onGameChanged;
@override @override
State<CreateGameView> createState() => _CreateGameViewState(); State<CreateGameView> createState() => _CreateGameViewState();
} }
class _CreateGameViewState extends State<CreateGameView> { class _CreateGameViewState extends State<CreateGameView> {
/// GlobalKey for ScaffoldMessenger to show snackbars
final _scaffoldMessengerKey = GlobalKey<ScaffoldMessengerState>();
/// The database instance for accessing game data.
late final AppDatabase db;
/// The currently selected ruleset for the game.
Ruleset? selectedRuleset; Ruleset? selectedRuleset;
/// The index of the currently selected ruleset.
int selectedRulesetIndex = -1; int selectedRulesetIndex = -1;
/// A list of available rulesets and their localized names.
late List<(Ruleset, String)> _rulesets; late List<(Ruleset, String)> _rulesets;
/// The currently selected color for the game.
GameColor? selectedColor; GameColor? selectedColor;
/// Controller for the game name input field.
final _gameNameController = TextEditingController(); final _gameNameController = TextEditingController();
/// Controller for the game description input field.
final _descriptionController = TextEditingController(); final _descriptionController = TextEditingController();
/// The ID of the currently selected group.
late String selectedGroupId;
/// A controller for the search bar input field.
final TextEditingController controller = TextEditingController();
/// A list of groups filtered based on the search query.
late final List<Group> filteredGroups;
@override @override
void initState() { void initState() {
super.initState(); super.initState();
db = Provider.of<AppDatabase>(context, listen: false);
_gameNameController.addListener(() => setState(() {})); _gameNameController.addListener(() => setState(() {}));
} }
@@ -94,6 +132,52 @@ class _CreateGameViewState extends State<CreateGameView> {
backgroundColor: CustomTheme.backgroundColor, backgroundColor: CustomTheme.backgroundColor,
appBar: AppBar( appBar: AppBar(
title: Text(isEditing ? loc.edit_game : loc.create_game), title: Text(isEditing ? loc.edit_game : loc.create_game),
actions: widget.gameToEdit == null
? []
: [
IconButton(
icon: const Icon(Icons.delete),
onPressed: () async {
if (widget.gameToEdit != null) {
showDialog<bool>(
context: context,
builder: (context) => CustomAlertDialog(
title: loc.delete_game,
content: loc.this_cannot_be_undone,
actions: [
TextButton(
onPressed: () =>
Navigator.of(context).pop(false),
child: Text(loc.cancel),
),
TextButton(
onPressed: () =>
Navigator.of(context).pop(true),
child: Text(loc.delete),
),
],
),
).then((confirmed) async {
if (confirmed == true && context.mounted) {
bool success = await db.gameDao.deleteGame(
gameId: widget.gameToEdit!.id,
);
if (!context.mounted) return;
if (success) {
widget.onGameChanged.call();
Navigator.of(
context,
).pop((game: widget.gameToEdit, delete: true));
} else {
if (!mounted) return;
showSnackbar(message: loc.error_deleting_game);
}
}
});
}
},
),
],
), ),
body: SafeArea( body: SafeArea(
child: Column( child: Column(
@@ -171,9 +255,24 @@ class _CreateGameViewState extends State<CreateGameView> {
_gameNameController.text.trim().isNotEmpty && _gameNameController.text.trim().isNotEmpty &&
selectedRulesetIndex != -1 && selectedRulesetIndex != -1 &&
selectedColor != null selectedColor != null
? () { ? () async {
//TODO: Handle saving to db & updating game selection view Game newGame = Game(
Navigator.of(context).pop(); name: _gameNameController.text.trim(),
description: _descriptionController.text.trim(),
ruleset: selectedRuleset!,
color: selectedColor!,
);
if (isEditing) {
await handleGameUpdate(newGame);
} else {
await handleGameCreation(newGame);
}
widget.onGameChanged.call();
if (context.mounted) {
Navigator.of(
context,
).pop((game: newGame, delete: false));
}
} }
: null, : null,
), ),
@@ -184,4 +283,69 @@ class _CreateGameViewState extends State<CreateGameView> {
), ),
); );
} }
/// Handles updating an existing game in the database.
///
/// [newGame] The updated game object.
Future<void> handleGameUpdate(Game newGame) async {
final oldGame = widget.gameToEdit!;
if (oldGame.name != newGame.name) {
await db.gameDao.updateGameName(
gameId: oldGame.id,
newName: newGame.name,
);
}
if (oldGame.description != newGame.description) {
await db.gameDao.updateGameDescription(
gameId: oldGame.id,
newDescription: newGame.description,
);
}
if (oldGame.ruleset != newGame.ruleset) {
await db.gameDao.updateGameRuleset(
gameId: oldGame.id,
newRuleset: newGame.ruleset,
);
}
if (oldGame.color != newGame.color) {
await db.gameDao.updateGameColor(
gameId: oldGame.id,
newColor: newGame.color,
);
}
if (oldGame.icon != newGame.icon) {
await db.gameDao.updateGameIcon(
gameId: oldGame.id,
newIcon: newGame.icon,
);
}
}
/// Handles creating a new game in the database.
///
/// [newGame] The game object to be created.
Future<void> handleGameCreation(Game newGame) async {
await db.gameDao.addGame(game: newGame);
}
/// Displays a snackbar with the given message and optional action.
///
/// [message] The message to display in the snackbar.
void showSnackbar({required String message}) {
final messenger = _scaffoldMessengerKey.currentState;
if (messenger != null) {
messenger.hideCurrentSnackBar();
messenger.showSnackBar(
SnackBar(
content: Text(message, style: const TextStyle(color: Colors.white)),
backgroundColor: CustomTheme.boxColor,
),
);
}
}
} }

View File

@@ -19,7 +19,7 @@ import 'package:tallee/presentation/widgets/tiles/match_tile.dart';
import 'package:tallee/presentation/widgets/top_centered_message.dart'; import 'package:tallee/presentation/widgets/top_centered_message.dart';
class MatchView extends StatefulWidget { class MatchView extends StatefulWidget {
/// A view that displays a list of matches /// A view that displays a list of matches.
const MatchView({super.key}); const MatchView({super.key});
@override @override
@@ -27,11 +27,14 @@ class MatchView extends StatefulWidget {
} }
class _MatchViewState extends State<MatchView> { class _MatchViewState extends State<MatchView> {
/// Database instance used to access match data.
late final AppDatabase db; late final AppDatabase db;
/// Indicates whether matches are currently being loaded.
bool isLoading = true; bool isLoading = true;
/// Loaded matches from the database, /// Loaded matches from the database,
/// initially filled with skeleton matches /// initially filled with skeleton matches.
List<Match> matches = List.filled( List<Match> matches = List.filled(
4, 4,
Match( Match(
@@ -41,7 +44,6 @@ class _MatchViewState extends State<MatchView> {
ruleset: Ruleset.singleWinner, ruleset: Ruleset.singleWinner,
description: '', description: '',
color: GameColor.blue, color: GameColor.blue,
icon: '',
), ),
group: Group( group: Group(
name: 'Group name', name: 'Group name',

View File

@@ -40,33 +40,39 @@ class DataTransferService {
'players': players.map((p) => p.toJson()).toList(), 'players': players.map((p) => p.toJson()).toList(),
'games': games.map((g) => g.toJson()).toList(), 'games': games.map((g) => g.toJson()).toList(),
'groups': groups 'groups': groups
.map((g) => { .map(
'id': g.id, (g) => {
'name': g.name, 'id': g.id,
'description': g.description, 'name': g.name,
'createdAt': g.createdAt.toIso8601String(), 'description': g.description,
'memberIds': (g.members).map((m) => m.id).toList(), 'createdAt': g.createdAt.toIso8601String(),
}) 'memberIds': (g.members).map((m) => m.id).toList(),
},
)
.toList(), .toList(),
'teams': teams 'teams': teams
.map((t) => { .map(
'id': t.id, (t) => {
'name': t.name, 'id': t.id,
'createdAt': t.createdAt.toIso8601String(), 'name': t.name,
'memberIds': (t.members).map((m) => m.id).toList(), 'createdAt': t.createdAt.toIso8601String(),
}) 'memberIds': (t.members).map((m) => m.id).toList(),
},
)
.toList(), .toList(),
'matches': matches 'matches': matches
.map((m) => { .map(
'id': m.id, (m) => {
'name': m.name, 'id': m.id,
'createdAt': m.createdAt.toIso8601String(), 'name': m.name,
'endedAt': m.endedAt?.toIso8601String(), 'createdAt': m.createdAt.toIso8601String(),
'gameId': m.game.id, 'endedAt': m.endedAt?.toIso8601String(),
'groupId': m.group?.id, 'gameId': m.game.id,
'playerIds': m.players.map((p) => p.id).toList(), 'groupId': m.group?.id,
'notes': m.notes, 'playerIds': m.players.map((p) => p.id).toList(),
}) 'notes': m.notes,
},
)
.toList(), .toList(),
}; };
@@ -79,9 +85,9 @@ class DataTransferService {
/// [jsonString] The JSON string to be exported. /// [jsonString] The JSON string to be exported.
/// [fileName] The desired name for the exported file (without extension). /// [fileName] The desired name for the exported file (without extension).
static Future<ExportResult> exportData( static Future<ExportResult> exportData(
String jsonString, String jsonString,
String fileName String fileName,
) async { ) async {
try { try {
final bytes = Uint8List.fromList(utf8.encode(jsonString)); final bytes = Uint8List.fromList(utf8.encode(jsonString));
final path = await FilePicker.platform.saveFile( final path = await FilePicker.platform.saveFile(
@@ -94,7 +100,6 @@ class DataTransferService {
} else { } else {
return ExportResult.success; return ExportResult.success;
} }
} catch (e, stack) { } catch (e, stack) {
print('[exportData] $e'); print('[exportData] $e');
print(stack); print(stack);
@@ -122,13 +127,19 @@ class DataTransferService {
final isValid = await _validateJsonSchema(jsonString); final isValid = await _validateJsonSchema(jsonString);
if (!isValid) return ImportResult.invalidSchema; if (!isValid) return ImportResult.invalidSchema;
final Map<String, dynamic> decoded = json.decode(jsonString) as Map<String, dynamic>; final Map<String, dynamic> decoded =
json.decode(jsonString) as Map<String, dynamic>;
final List<dynamic> playersJson = (decoded['players'] as List<dynamic>?) ?? []; final List<dynamic> playersJson =
final List<dynamic> gamesJson = (decoded['games'] as List<dynamic>?) ?? []; (decoded['players'] as List<dynamic>?) ?? [];
final List<dynamic> groupsJson = (decoded['groups'] as List<dynamic>?) ?? []; final List<dynamic> gamesJson =
final List<dynamic> teamsJson = (decoded['teams'] as List<dynamic>?) ?? []; (decoded['games'] as List<dynamic>?) ?? [];
final List<dynamic> matchesJson = (decoded['matches'] as List<dynamic>?) ?? []; final List<dynamic> groupsJson =
(decoded['groups'] as List<dynamic>?) ?? [];
final List<dynamic> teamsJson =
(decoded['teams'] as List<dynamic>?) ?? [];
final List<dynamic> matchesJson =
(decoded['matches'] as List<dynamic>?) ?? [];
// Import Players // Import Players
final List<Player> importedPlayers = playersJson final List<Player> importedPlayers = playersJson
@@ -151,7 +162,8 @@ class DataTransferService {
// Import Groups // Import Groups
final List<Group> importedGroups = groupsJson.map((g) { final List<Group> importedGroups = groupsJson.map((g) {
final map = g as Map<String, dynamic>; final map = g as Map<String, dynamic>;
final memberIds = (map['memberIds'] as List<dynamic>? ?? []).cast<String>(); final memberIds = (map['memberIds'] as List<dynamic>? ?? [])
.cast<String>();
final members = memberIds final members = memberIds
.map((id) => playerById[id]) .map((id) => playerById[id])
@@ -174,7 +186,8 @@ class DataTransferService {
// Import Teams // Import Teams
final List<Team> importedTeams = teamsJson.map((t) { final List<Team> importedTeams = teamsJson.map((t) {
final map = t as Map<String, dynamic>; final map = t as Map<String, dynamic>;
final memberIds = (map['memberIds'] as List<dynamic>? ?? []).cast<String>(); final memberIds = (map['memberIds'] as List<dynamic>? ?? [])
.cast<String>();
final members = memberIds final members = memberIds
.map((id) => playerById[id]) .map((id) => playerById[id])
@@ -195,8 +208,11 @@ class DataTransferService {
final String gameId = map['gameId'] as String; final String gameId = map['gameId'] as String;
final String? groupId = map['groupId'] as String?; final String? groupId = map['groupId'] as String?;
final List<String> playerIds = (map['playerIds'] as List<dynamic>? ?? []).cast<String>(); final List<String> playerIds =
final DateTime? endedAt = map['endedAt'] != null ? DateTime.parse(map['endedAt'] as String) : null; (map['playerIds'] as List<dynamic>? ?? []).cast<String>();
final DateTime? endedAt = map['endedAt'] != null
? DateTime.parse(map['endedAt'] as String)
: null;
final game = gameById[gameId]; final game = gameById[gameId];
final group = (groupId == null) ? null : groupById[groupId]; final group = (groupId == null) ? null : groupById[groupId];
@@ -208,7 +224,14 @@ class DataTransferService {
return Match( return Match(
id: map['id'] as String, id: map['id'] as String,
name: map['name'] as String, name: map['name'] as String,
game: game ?? Game(name: 'Unknown', ruleset: Ruleset.singleWinner, description: '', color: GameColor.blue, icon: ''), game:
game ??
Game(
name: 'Unknown',
ruleset: Ruleset.singleWinner,
description: '',
color: GameColor.blue,
),
group: group, group: group,
players: players, players: players,
createdAt: DateTime.parse(map['createdAt'] as String), createdAt: DateTime.parse(map['createdAt'] as String),

View File

@@ -56,7 +56,6 @@ void main() {
ruleset: Ruleset.singleWinner, ruleset: Ruleset.singleWinner,
description: 'A test game', description: 'A test game',
color: GameColor.blue, color: GameColor.blue,
icon: '',
); );
testMatch1 = Match( testMatch1 = Match(
name: 'First Test Match', name: 'First Test Match',

View File

@@ -2,12 +2,12 @@ import 'package:clock/clock.dart';
import 'package:drift/drift.dart'; import 'package:drift/drift.dart';
import 'package:drift/native.dart'; import 'package:drift/native.dart';
import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_test/flutter_test.dart';
import 'package:tallee/core/enums.dart';
import 'package:tallee/data/db/database.dart'; import 'package:tallee/data/db/database.dart';
import 'package:tallee/data/dto/game.dart'; import 'package:tallee/data/dto/game.dart';
import 'package:tallee/data/dto/match.dart'; import 'package:tallee/data/dto/match.dart';
import 'package:tallee/data/dto/player.dart'; import 'package:tallee/data/dto/player.dart';
import 'package:tallee/data/dto/team.dart'; import 'package:tallee/data/dto/team.dart';
import 'package:tallee/core/enums.dart';
void main() { void main() {
late AppDatabase database; late AppDatabase database;
@@ -37,20 +37,21 @@ void main() {
testPlayer2 = Player(name: 'Bob', description: ''); testPlayer2 = Player(name: 'Bob', description: '');
testPlayer3 = Player(name: 'Charlie', description: ''); testPlayer3 = Player(name: 'Charlie', description: '');
testPlayer4 = Player(name: 'Diana', description: ''); testPlayer4 = Player(name: 'Diana', description: '');
testTeam1 = Team( testTeam1 = Team(name: 'Team Alpha', members: [testPlayer1, testPlayer2]);
name: 'Team Alpha', testTeam2 = Team(name: 'Team Beta', members: [testPlayer3, testPlayer4]);
members: [testPlayer1, testPlayer2], testTeam3 = Team(name: 'Team Gamma', members: [testPlayer1, testPlayer3]);
testGame1 = Game(
name: 'Game 1',
ruleset: Ruleset.singleWinner,
description: 'Test game 1',
color: GameColor.blue,
); );
testTeam2 = Team( testGame2 = Game(
name: 'Team Beta', name: 'Game 2',
members: [testPlayer3, testPlayer4], ruleset: Ruleset.highestScore,
description: 'Test game 2',
color: GameColor.red,
); );
testTeam3 = Team(
name: 'Team Gamma',
members: [testPlayer1, testPlayer3],
);
testGame1 = Game(name: 'Game 1', ruleset: Ruleset.singleWinner, description: 'Test game 1', color: GameColor.blue, icon: '');
testGame2 = Game(name: 'Game 2', ruleset: Ruleset.highestScore, description: 'Test game 2', color: GameColor.red, icon: '');
}); });
await database.playerDao.addPlayersAsList( await database.playerDao.addPlayersAsList(
@@ -65,7 +66,6 @@ void main() {
}); });
group('Team Tests', () { group('Team Tests', () {
// Verifies that a single team can be added and retrieved with all fields intact. // Verifies that a single team can be added and retrieved with all fields intact.
test('Adding and fetching a single team works correctly', () async { test('Adding and fetching a single team works correctly', () async {
final added = await database.teamDao.addTeam(team: testTeam1); final added = await database.teamDao.addTeam(team: testTeam1);
@@ -285,10 +285,7 @@ void main() {
test('Updating team name to empty string works', () async { test('Updating team name to empty string works', () async {
await database.teamDao.addTeam(team: testTeam1); await database.teamDao.addTeam(team: testTeam1);
await database.teamDao.updateTeamName( await database.teamDao.updateTeamName(teamId: testTeam1.id, newName: '');
teamId: testTeam1.id,
newName: '',
);
final updatedTeam = await database.teamDao.getTeamById( final updatedTeam = await database.teamDao.getTeamById(
teamId: testTeam1.id, teamId: testTeam1.id,
@@ -350,9 +347,7 @@ void main() {
await database.matchDao.addMatch(match: match2); await database.matchDao.addMatch(match: match2);
// Add teams to database // Add teams to database
await database.teamDao.addTeamsAsList( await database.teamDao.addTeamsAsList(teams: [testTeam1, testTeam3]);
teams: [testTeam1, testTeam3],
);
// Associate players with teams through match1 // Associate players with teams through match1
// testTeam1: player1, player2 // testTeam1: player1, player2
@@ -420,10 +415,11 @@ void main() {
final allTeams = await database.teamDao.getAllTeams(); final allTeams = await database.teamDao.getAllTeams();
expect(allTeams.length, 3); expect(allTeams.length, 3);
expect( expect(allTeams.map((t) => t.id).toSet(), {
allTeams.map((t) => t.id).toSet(), testTeam1.id,
{testTeam1.id, testTeam2.id, testTeam3.id}, testTeam2.id,
); testTeam3.id,
});
}); });
// Verifies that teamExists returns false for deleted teams. // Verifies that teamExists returns false for deleted teams.
@@ -462,9 +458,7 @@ void main() {
// Verifies that addTeam after deleteAllTeams works correctly. // Verifies that addTeam after deleteAllTeams works correctly.
test('Adding team after deleteAllTeams works correctly', () async { test('Adding team after deleteAllTeams works correctly', () async {
await database.teamDao.addTeamsAsList( await database.teamDao.addTeamsAsList(teams: [testTeam1, testTeam2]);
teams: [testTeam1, testTeam2],
);
expect(await database.teamDao.getTeamCount(), 2); expect(await database.teamDao.getTeamCount(), 2);
await database.teamDao.deleteAllTeams(); await database.teamDao.deleteAllTeams();

View File

@@ -44,7 +44,6 @@ void main() {
ruleset: Ruleset.highestScore, ruleset: Ruleset.highestScore,
description: 'A board game about real estate', description: 'A board game about real estate',
color: GameColor.orange, color: GameColor.orange,
icon: '',
); );
}); });
}); });
@@ -54,7 +53,6 @@ void main() {
}); });
group('Game Tests', () { group('Game Tests', () {
// Verifies that getAllGames returns an empty list when the database has no games. // Verifies that getAllGames returns an empty list when the database has no games.
test('getAllGames returns empty list when no games exist', () async { test('getAllGames returns empty list when no games exist', () async {
final allGames = await database.gameDao.getAllGames(); final allGames = await database.gameDao.getAllGames();
@@ -106,7 +104,7 @@ void main() {
// Verifies that getGameById throws a StateError when the game doesn't exist. // Verifies that getGameById throws a StateError when the game doesn't exist.
test('getGameById throws exception for non-existent game', () async { test('getGameById throws exception for non-existent game', () async {
expect( expect(
() => database.gameDao.getGameById(gameId: 'non-existent-id'), () => database.gameDao.getGameById(gameId: 'non-existent-id'),
throwsA(isA<StateError>()), throwsA(isA<StateError>()),
); );
}); });
@@ -134,7 +132,12 @@ void main() {
// Verifies that a game with empty optional fields can be added and retrieved. // Verifies that a game with empty optional fields can be added and retrieved.
test('addGame handles game with null optional fields', () async { test('addGame handles game with null optional fields', () async {
final gameWithNulls = Game(name: 'Simple Game', ruleset: Ruleset.lowestScore, description: 'A simple game', color: GameColor.green, icon: ''); final gameWithNulls = Game(
name: 'Simple Game',
ruleset: Ruleset.lowestScore,
description: 'A simple game',
color: GameColor.green,
);
final result = await database.gameDao.addGame(game: gameWithNulls); final result = await database.gameDao.addGame(game: gameWithNulls);
expect(result, true); expect(result, true);
@@ -419,9 +422,7 @@ void main() {
// Verifies that getGameCount updates correctly after deleting a game. // Verifies that getGameCount updates correctly after deleting a game.
test('getGameCount updates correctly after deletion', () async { test('getGameCount updates correctly after deletion', () async {
await database.gameDao.addGamesAsList( await database.gameDao.addGamesAsList(games: [testGame1, testGame2]);
games: [testGame1, testGame2],
);
final countBefore = await database.gameDao.getGameCount(); final countBefore = await database.gameDao.getGameCount();
expect(countBefore, 2); expect(countBefore, 2);
@@ -461,7 +462,6 @@ void main() {
ruleset: Ruleset.multipleWinners, ruleset: Ruleset.multipleWinners,
description: 'Description with émojis 🎮🎲', description: 'Description with émojis 🎮🎲',
color: GameColor.purple, color: GameColor.purple,
icon: '',
); );
await database.gameDao.addGame(game: specialGame); await database.gameDao.addGame(game: specialGame);
@@ -478,7 +478,6 @@ void main() {
name: '', name: '',
ruleset: Ruleset.singleWinner, ruleset: Ruleset.singleWinner,
description: '', description: '',
icon: '',
color: GameColor.red, color: GameColor.red,
); );
await database.gameDao.addGame(game: emptyGame); await database.gameDao.addGame(game: emptyGame);
@@ -500,7 +499,6 @@ void main() {
description: longString, description: longString,
ruleset: Ruleset.multipleWinners, ruleset: Ruleset.multipleWinners,
color: GameColor.yellow, color: GameColor.yellow,
icon: '',
); );
await database.gameDao.addGame(game: longGame); await database.gameDao.addGame(game: longGame);

View File

@@ -48,7 +48,12 @@ void main() {
description: '', description: '',
members: [testPlayer1, testPlayer2, testPlayer3], members: [testPlayer1, testPlayer2, testPlayer3],
); );
testGame = Game(name: 'Test Game', ruleset: Ruleset.singleWinner, description: 'A test game', color: GameColor.blue, icon: ''); testGame = Game(
name: 'Test Game',
ruleset: Ruleset.singleWinner,
description: 'A test game',
color: GameColor.blue,
);
testMatchOnlyGroup = Match( testMatchOnlyGroup = Match(
name: 'Test Match with Group', name: 'Test Match with Group',
game: testGame, game: testGame,
@@ -61,14 +66,8 @@ void main() {
players: [testPlayer4, testPlayer5, testPlayer6], players: [testPlayer4, testPlayer5, testPlayer6],
notes: '', notes: '',
); );
testTeam1 = Team( testTeam1 = Team(name: 'Team Alpha', members: [testPlayer1, testPlayer2]);
name: 'Team Alpha', testTeam2 = Team(name: 'Team Beta', members: [testPlayer3, testPlayer4]);
members: [testPlayer1, testPlayer2],
);
testTeam2 = Team(
name: 'Team Beta',
members: [testPlayer3, testPlayer4],
);
}); });
await database.playerDao.addPlayersAsList( await database.playerDao.addPlayersAsList(
players: [ players: [
@@ -88,7 +87,6 @@ void main() {
}); });
group('Player-Match Tests', () { group('Player-Match Tests', () {
// Verifies that matchHasPlayers returns false initially and true after adding a player. // Verifies that matchHasPlayers returns false initially and true after adding a player.
test('Match has player works correctly', () async { test('Match has player works correctly', () async {
await database.matchDao.addMatch(match: testMatchOnlyGroup); await database.matchDao.addMatch(match: testMatchOnlyGroup);
@@ -153,26 +151,23 @@ void main() {
); );
expect(result.players.length, testMatchOnlyPlayers.players.length - 1); expect(result.players.length, testMatchOnlyPlayers.players.length - 1);
final playerExists = result.players.any( final playerExists = result.players.any((p) => p.id == playerToRemove.id);
(p) => p.id == playerToRemove.id,
);
expect(playerExists, false); expect(playerExists, false);
}); });
// Verifies that getPlayersOfMatch returns all players of a match with correct data. // Verifies that getPlayersOfMatch returns all players of a match with correct data.
test('Retrieving players of a match works correctly', () async { test('Retrieving players of a match works correctly', () async {
await database.matchDao.addMatch(match: testMatchOnlyPlayers); await database.matchDao.addMatch(match: testMatchOnlyPlayers);
final players = await database.playerMatchDao.getPlayersOfMatch( final players =
matchId: testMatchOnlyPlayers.id, await database.playerMatchDao.getPlayersOfMatch(
) ?? []; matchId: testMatchOnlyPlayers.id,
) ??
[];
for (int i = 0; i < players.length; i++) { for (int i = 0; i < players.length; i++) {
expect(players[i].id, testMatchOnlyPlayers.players[i].id); expect(players[i].id, testMatchOnlyPlayers.players[i].id);
expect(players[i].name, testMatchOnlyPlayers.players[i].name); expect(players[i].name, testMatchOnlyPlayers.players[i].name);
expect( expect(players[i].createdAt, testMatchOnlyPlayers.players[i].createdAt);
players[i].createdAt,
testMatchOnlyPlayers.players[i].createdAt,
);
} }
}); });
@@ -223,10 +218,20 @@ void main() {
// Verifies that the same player can be added to multiple different matches. // Verifies that the same player can be added to multiple different matches.
test( test(
'Adding the same player to separate matches works correctly', 'Adding the same player to separate matches works correctly',
() async { () async {
final playersList = [testPlayer1, testPlayer2, testPlayer3]; final playersList = [testPlayer1, testPlayer2, testPlayer3];
final match1 = Match(name: 'Match 1', game: testGame, players: playersList, notes: ''); final match1 = Match(
final match2 = Match(name: 'Match 2', game: testGame, players: playersList, notes: ''); name: 'Match 1',
game: testGame,
players: playersList,
notes: '',
);
final match2 = Match(
name: 'Match 2',
game: testGame,
players: playersList,
notes: '',
);
await Future.wait([ await Future.wait([
database.matchDao.addMatch(match: match1), database.matchDao.addMatch(match: match1),
@@ -299,16 +304,19 @@ void main() {
}); });
// Verifies that getPlayerScore returns null for non-existent player-match combination. // Verifies that getPlayerScore returns null for non-existent player-match combination.
test('getPlayerScore returns null for non-existent player in match', () async { test(
await database.matchDao.addMatch(match: testMatchOnlyGroup); 'getPlayerScore returns null for non-existent player in match',
() async {
await database.matchDao.addMatch(match: testMatchOnlyGroup);
final score = await database.playerMatchDao.getPlayerScore( final score = await database.playerMatchDao.getPlayerScore(
matchId: testMatchOnlyGroup.id, matchId: testMatchOnlyGroup.id,
playerId: 'non-existent-player-id', playerId: 'non-existent-player-id',
); );
expect(score, isNull); expect(score, isNull);
}); },
);
// Verifies that updatePlayerScore updates the score correctly. // Verifies that updatePlayerScore updates the score correctly.
test('updatePlayerScore updates score correctly', () async { test('updatePlayerScore updates score correctly', () async {
@@ -331,17 +339,20 @@ void main() {
}); });
// Verifies that updatePlayerScore returns false for non-existent player-match. // Verifies that updatePlayerScore returns false for non-existent player-match.
test('updatePlayerScore returns false for non-existent player-match', () async { test(
await database.matchDao.addMatch(match: testMatchOnlyGroup); 'updatePlayerScore returns false for non-existent player-match',
() async {
await database.matchDao.addMatch(match: testMatchOnlyGroup);
final updated = await database.playerMatchDao.updatePlayerScore( final updated = await database.playerMatchDao.updatePlayerScore(
matchId: testMatchOnlyGroup.id, matchId: testMatchOnlyGroup.id,
playerId: 'non-existent-player-id', playerId: 'non-existent-player-id',
newScore: 50, newScore: 50,
); );
expect(updated, false); expect(updated, false);
}); },
);
// Verifies that adding a player with teamId works correctly. // Verifies that adding a player with teamId works correctly.
test('Adding player with teamId works correctly', () async { test('Adding player with teamId works correctly', () async {
@@ -431,17 +442,20 @@ void main() {
}); });
// Verifies that updatePlayerTeam returns false for non-existent player-match. // Verifies that updatePlayerTeam returns false for non-existent player-match.
test('updatePlayerTeam returns false for non-existent player-match', () async { test(
await database.matchDao.addMatch(match: testMatchOnlyGroup); 'updatePlayerTeam returns false for non-existent player-match',
() async {
await database.matchDao.addMatch(match: testMatchOnlyGroup);
final updated = await database.playerMatchDao.updatePlayerTeam( final updated = await database.playerMatchDao.updatePlayerTeam(
matchId: testMatchOnlyGroup.id, matchId: testMatchOnlyGroup.id,
playerId: 'non-existent-player-id', playerId: 'non-existent-player-id',
teamId: testTeam1.id, teamId: testTeam1.id,
); );
expect(updated, false); expect(updated, false);
}); },
);
// Verifies that getPlayersInTeam returns empty list for non-existent team. // Verifies that getPlayersInTeam returns empty list for non-existent team.
test('getPlayersInTeam returns empty list for non-existent team', () async { test('getPlayersInTeam returns empty list for non-existent team', () async {
@@ -483,16 +497,19 @@ void main() {
}); });
// Verifies that removePlayerFromMatch returns false for non-existent player. // Verifies that removePlayerFromMatch returns false for non-existent player.
test('removePlayerFromMatch returns false for non-existent player', () async { test(
await database.matchDao.addMatch(match: testMatchOnlyPlayers); 'removePlayerFromMatch returns false for non-existent player',
() async {
await database.matchDao.addMatch(match: testMatchOnlyPlayers);
final removed = await database.playerMatchDao.removePlayerFromMatch( final removed = await database.playerMatchDao.removePlayerFromMatch(
playerId: 'non-existent-player-id', playerId: 'non-existent-player-id',
matchId: testMatchOnlyPlayers.id, matchId: testMatchOnlyPlayers.id,
); );
expect(removed, false); expect(removed, false);
}); },
);
// Verifies that adding the same player twice to the same match is ignored. // Verifies that adding the same player twice to the same match is ignored.
test('Adding same player twice to same match is ignored', () async { test('Adding same player twice to same match is ignored', () async {
@@ -528,27 +545,30 @@ void main() {
}); });
// Verifies that updatePlayersFromMatch with empty list removes all players. // Verifies that updatePlayersFromMatch with empty list removes all players.
test('updatePlayersFromMatch with empty list removes all players', () async { test(
await database.matchDao.addMatch(match: testMatchOnlyPlayers); 'updatePlayersFromMatch with empty list removes all players',
() async {
await database.matchDao.addMatch(match: testMatchOnlyPlayers);
// Verify players exist initially // Verify players exist initially
var players = await database.playerMatchDao.getPlayersOfMatch( var players = await database.playerMatchDao.getPlayersOfMatch(
matchId: testMatchOnlyPlayers.id, matchId: testMatchOnlyPlayers.id,
); );
expect(players?.length, 3); expect(players?.length, 3);
// Update with empty list // Update with empty list
await database.playerMatchDao.updatePlayersFromMatch( await database.playerMatchDao.updatePlayersFromMatch(
matchId: testMatchOnlyPlayers.id, matchId: testMatchOnlyPlayers.id,
newPlayer: [], newPlayer: [],
); );
// Verify all players are removed // Verify all players are removed
players = await database.playerMatchDao.getPlayersOfMatch( players = await database.playerMatchDao.getPlayersOfMatch(
matchId: testMatchOnlyPlayers.id, matchId: testMatchOnlyPlayers.id,
); );
expect(players, isNull); expect(players, isNull);
}); },
);
// Verifies that updatePlayersFromMatch with same players makes no changes. // Verifies that updatePlayersFromMatch with same players makes no changes.
test('updatePlayersFromMatch with same players makes no changes', () async { test('updatePlayersFromMatch with same players makes no changes', () async {
@@ -702,16 +722,19 @@ void main() {
}); });
// Verifies that getPlayersInTeam returns empty list for non-existent match. // Verifies that getPlayersInTeam returns empty list for non-existent match.
test('getPlayersInTeam returns empty list for non-existent match', () async { test(
await database.teamDao.addTeam(team: testTeam1); 'getPlayersInTeam returns empty list for non-existent match',
() async {
await database.teamDao.addTeam(team: testTeam1);
final players = await database.playerMatchDao.getPlayersInTeam( final players = await database.playerMatchDao.getPlayersInTeam(
matchId: 'non-existent-match-id', matchId: 'non-existent-match-id',
teamId: testTeam1.id, teamId: testTeam1.id,
); );
expect(players.isEmpty, true); expect(players.isEmpty, true);
}); },
);
// Verifies that players in different teams within the same match are returned correctly. // Verifies that players in different teams within the same match are returned correctly.
test('Players in different teams within same match are separate', () async { test('Players in different teams within same match are separate', () async {
@@ -759,8 +782,18 @@ void main() {
// Verifies that removePlayerFromMatch does not affect other matches. // Verifies that removePlayerFromMatch does not affect other matches.
test('removePlayerFromMatch does not affect other matches', () async { test('removePlayerFromMatch does not affect other matches', () async {
final playersList = [testPlayer1, testPlayer2]; final playersList = [testPlayer1, testPlayer2];
final match1 = Match(name: 'Match 1', game: testGame, players: playersList, notes: ''); final match1 = Match(
final match2 = Match(name: 'Match 2', game: testGame, players: playersList, notes: ''); name: 'Match 1',
game: testGame,
players: playersList,
notes: '',
);
final match2 = Match(
name: 'Match 2',
game: testGame,
players: playersList,
notes: '',
);
await Future.wait([ await Future.wait([
database.matchDao.addMatch(match: match1), database.matchDao.addMatch(match: match1),
@@ -792,8 +825,18 @@ void main() {
// Verifies that updating scores for players in different matches are independent. // Verifies that updating scores for players in different matches are independent.
test('Player scores are independent across matches', () async { test('Player scores are independent across matches', () async {
final playersList = [testPlayer1]; final playersList = [testPlayer1];
final match1 = Match(name: 'Match 1', game: testGame, players: playersList, notes: ''); final match1 = Match(
final match2 = Match(name: 'Match 2', game: testGame, players: playersList, notes: ''); name: 'Match 1',
game: testGame,
players: playersList,
notes: '',
);
final match2 = Match(
name: 'Match 2',
game: testGame,
players: playersList,
notes: '',
);
await Future.wait([ await Future.wait([
database.matchDao.addMatch(match: match1), database.matchDao.addMatch(match: match1),
@@ -829,16 +872,19 @@ void main() {
}); });
// Verifies that updatePlayersFromMatch on non-existent match fails with constraint error. // Verifies that updatePlayersFromMatch on non-existent match fails with constraint error.
test('updatePlayersFromMatch on non-existent match fails with foreign key constraint', () async { test(
// Should throw due to foreign key constraint - match doesn't exist 'updatePlayersFromMatch on non-existent match fails with foreign key constraint',
await expectLater( () async {
database.playerMatchDao.updatePlayersFromMatch( // Should throw due to foreign key constraint - match doesn't exist
matchId: 'non-existent-match-id', await expectLater(
newPlayer: [testPlayer1, testPlayer2], database.playerMatchDao.updatePlayersFromMatch(
), matchId: 'non-existent-match-id',
throwsA(anything), newPlayer: [testPlayer1, testPlayer2],
); ),
}); throwsA(anything),
);
},
);
// Verifies that a player can be in a match without being assigned to a team. // Verifies that a player can be in a match without being assigned to a team.
test('Player can exist in match without team assignment', () async { test('Player can exist in match without team assignment', () async {

View File

@@ -2,11 +2,11 @@ import 'package:clock/clock.dart';
import 'package:drift/drift.dart' hide isNull, isNotNull; import 'package:drift/drift.dart' hide isNull, isNotNull;
import 'package:drift/native.dart'; import 'package:drift/native.dart';
import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_test/flutter_test.dart';
import 'package:tallee/core/enums.dart';
import 'package:tallee/data/db/database.dart'; import 'package:tallee/data/db/database.dart';
import 'package:tallee/data/dto/game.dart'; import 'package:tallee/data/dto/game.dart';
import 'package:tallee/data/dto/match.dart'; import 'package:tallee/data/dto/match.dart';
import 'package:tallee/data/dto/player.dart'; import 'package:tallee/data/dto/player.dart';
import 'package:tallee/core/enums.dart';
void main() { void main() {
late AppDatabase database; late AppDatabase database;
@@ -32,7 +32,12 @@ void main() {
testPlayer1 = Player(name: 'Alice', description: ''); testPlayer1 = Player(name: 'Alice', description: '');
testPlayer2 = Player(name: 'Bob', description: ''); testPlayer2 = Player(name: 'Bob', description: '');
testPlayer3 = Player(name: 'Charlie', description: ''); testPlayer3 = Player(name: 'Charlie', description: '');
testGame = Game(name: 'Test Game', ruleset: Ruleset.singleWinner, description: 'A test game', color: GameColor.blue, icon: ''); testGame = Game(
name: 'Test Game',
ruleset: Ruleset.singleWinner,
description: 'A test game',
color: GameColor.blue,
);
testMatch1 = Match( testMatch1 = Match(
name: 'Test Match 1', name: 'Test Match 1',
game: testGame, game: testGame,
@@ -60,7 +65,6 @@ void main() {
}); });
group('Score Tests', () { group('Score Tests', () {
// Verifies that a score can be added and retrieved with all fields intact. // Verifies that a score can be added and retrieved with all fields intact.
test('Adding and fetching a score works correctly', () async { test('Adding and fetching a score works correctly', () async {
await database.scoreDao.addScore( await database.scoreDao.addScore(
@@ -431,13 +435,16 @@ void main() {
}); });
// Verifies that getScoresForMatch returns empty list for match with no scores. // Verifies that getScoresForMatch returns empty list for match with no scores.
test('Getting scores for match with no scores returns empty list', () async { test(
final scores = await database.scoreDao.getScoresForMatch( 'Getting scores for match with no scores returns empty list',
matchId: testMatch1.id, () async {
); final scores = await database.scoreDao.getScoresForMatch(
matchId: testMatch1.id,
);
expect(scores.isEmpty, true); expect(scores.isEmpty, true);
}); },
);
// Verifies that getPlayerScoresInMatch returns empty list when player has no scores. // Verifies that getPlayerScoresInMatch returns empty list when player has no scores.
test('Getting player scores with no scores returns empty list', () async { test('Getting player scores with no scores returns empty list', () async {
@@ -666,46 +673,58 @@ void main() {
}); });
// Verifies that updating one player's score doesn't affect another player's score in same round. // Verifies that updating one player's score doesn't affect another player's score in same round.
test('Updating one player score does not affect other players in same round', () async { test(
await database.scoreDao.addScore( 'Updating one player score does not affect other players in same round',
playerId: testPlayer1.id, () async {
matchId: testMatch1.id, await database.scoreDao.addScore(
roundNumber: 1, playerId: testPlayer1.id,
score: 10, matchId: testMatch1.id,
change: 10, roundNumber: 1,
); score: 10,
await database.scoreDao.addScore( change: 10,
playerId: testPlayer2.id, );
matchId: testMatch1.id, await database.scoreDao.addScore(
roundNumber: 1, playerId: testPlayer2.id,
score: 20, matchId: testMatch1.id,
change: 20, roundNumber: 1,
); score: 20,
await database.scoreDao.addScore( change: 20,
playerId: testPlayer3.id, );
matchId: testMatch1.id, await database.scoreDao.addScore(
roundNumber: 1, playerId: testPlayer3.id,
score: 30, matchId: testMatch1.id,
change: 30, roundNumber: 1,
); score: 30,
change: 30,
);
await database.scoreDao.updateScore( await database.scoreDao.updateScore(
playerId: testPlayer2.id, playerId: testPlayer2.id,
matchId: testMatch1.id, matchId: testMatch1.id,
roundNumber: 1, roundNumber: 1,
newScore: 99, newScore: 99,
newChange: 89, newChange: 89,
); );
final scores = await database.scoreDao.getScoresForMatch( final scores = await database.scoreDao.getScoresForMatch(
matchId: testMatch1.id, matchId: testMatch1.id,
); );
expect(scores.length, 3); expect(scores.length, 3);
expect(scores.where((s) => s.playerId == testPlayer1.id).first.score, 10); expect(
expect(scores.where((s) => s.playerId == testPlayer2.id).first.score, 99); scores.where((s) => s.playerId == testPlayer1.id).first.score,
expect(scores.where((s) => s.playerId == testPlayer3.id).first.score, 30); 10,
}); );
expect(
scores.where((s) => s.playerId == testPlayer2.id).first.score,
99,
);
expect(
scores.where((s) => s.playerId == testPlayer3.id).first.score,
30,
);
},
);
// Verifies that deleting a player's scores only affects that specific player. // Verifies that deleting a player's scores only affects that specific player.
test('Deleting player scores only affects target player', () async { test('Deleting player scores only affects target player', () async {
@@ -724,9 +743,7 @@ void main() {
change: 20, change: 20,
); );
await database.scoreDao.deleteScoresForPlayer( await database.scoreDao.deleteScoresForPlayer(playerId: testPlayer1.id);
playerId: testPlayer1.id,
);
final match1Scores = await database.scoreDao.getScoresForMatch( final match1Scores = await database.scoreDao.getScoresForMatch(
matchId: testMatch1.id, matchId: testMatch1.id,