Merge remote-tracking branch 'origin/development' into bug/195-datenbank-onDelete-ueberpruefen
# Conflicts: # assets/schema.json # lib/data/db/tables/player_match_table.dart # lib/data/models/game.dart
This commit is contained in:
@@ -10,39 +10,7 @@ part 'game_dao.g.dart';
|
||||
class GameDao extends DatabaseAccessor<AppDatabase> with _$GameDaoMixin {
|
||||
GameDao(super.db);
|
||||
|
||||
/// Retrieves all games from the database.
|
||||
Future<List<Game>> getAllGames() async {
|
||||
final query = select(gameTable);
|
||||
final result = await query.get();
|
||||
return result
|
||||
.map(
|
||||
(row) => Game(
|
||||
id: row.id,
|
||||
name: row.name,
|
||||
ruleset: Ruleset.values.firstWhere((e) => e.name == row.ruleset),
|
||||
description: row.description,
|
||||
color: GameColor.values.firstWhere((e) => e.name == row.color),
|
||||
icon: row.icon,
|
||||
createdAt: row.createdAt,
|
||||
),
|
||||
)
|
||||
.toList();
|
||||
}
|
||||
|
||||
/// Retrieves a [Game] by its [gameId].
|
||||
Future<Game> getGameById({required String gameId}) async {
|
||||
final query = select(gameTable)..where((g) => g.id.equals(gameId));
|
||||
final result = await query.getSingle();
|
||||
return Game(
|
||||
id: result.id,
|
||||
name: result.name,
|
||||
ruleset: Ruleset.values.firstWhere((e) => e.name == result.ruleset),
|
||||
description: result.description,
|
||||
color: GameColor.values.firstWhere((e) => e.name == result.color),
|
||||
icon: result.icon,
|
||||
createdAt: result.createdAt,
|
||||
);
|
||||
}
|
||||
/* Create */
|
||||
|
||||
/// Adds a new [game] to the database.
|
||||
/// If a game with the same ID already exists, no action is taken.
|
||||
@@ -94,71 +62,7 @@ class GameDao extends DatabaseAccessor<AppDatabase> with _$GameDaoMixin {
|
||||
return true;
|
||||
}
|
||||
|
||||
/// Deletes the game with the given [gameId] from the database.
|
||||
/// Returns `true` if the game was deleted, `false` if the game did not exist.
|
||||
Future<bool> deleteGame({required String gameId}) async {
|
||||
final query = delete(gameTable)..where((g) => g.id.equals(gameId));
|
||||
final rowsAffected = await query.go();
|
||||
return rowsAffected > 0;
|
||||
}
|
||||
|
||||
/// Checks if a game with the given [gameId] exists in the database.
|
||||
/// Returns `true` if the game exists, `false` otherwise.
|
||||
Future<bool> gameExists({required String gameId}) async {
|
||||
final query = select(gameTable)..where((g) => g.id.equals(gameId));
|
||||
final result = await query.getSingleOrNull();
|
||||
return result != null;
|
||||
}
|
||||
|
||||
/// Updates the name of the game with the given [gameId] to [newName].
|
||||
Future<void> updateGameName({
|
||||
required String gameId,
|
||||
required String newName,
|
||||
}) async {
|
||||
await (update(gameTable)..where((g) => g.id.equals(gameId))).write(
|
||||
GameTableCompanion(name: Value(newName)),
|
||||
);
|
||||
}
|
||||
|
||||
/// Updates the ruleset of the game with the given [gameId].
|
||||
Future<void> updateGameRuleset({
|
||||
required String gameId,
|
||||
required Ruleset newRuleset,
|
||||
}) async {
|
||||
await (update(gameTable)..where((g) => g.id.equals(gameId))).write(
|
||||
GameTableCompanion(ruleset: Value(newRuleset.name)),
|
||||
);
|
||||
}
|
||||
|
||||
/// Updates the description of the game with the given [gameId].
|
||||
Future<void> updateGameDescription({
|
||||
required String gameId,
|
||||
required String newDescription,
|
||||
}) async {
|
||||
await (update(gameTable)..where((g) => g.id.equals(gameId))).write(
|
||||
GameTableCompanion(description: Value(newDescription)),
|
||||
);
|
||||
}
|
||||
|
||||
/// Updates the color of the game with the given [gameId].
|
||||
Future<void> updateGameColor({
|
||||
required String gameId,
|
||||
required GameColor newColor,
|
||||
}) async {
|
||||
await (update(gameTable)..where((g) => g.id.equals(gameId))).write(
|
||||
GameTableCompanion(color: Value(newColor.name)),
|
||||
);
|
||||
}
|
||||
|
||||
/// Updates the icon of the game with the given [gameId].
|
||||
Future<void> updateGameIcon({
|
||||
required String gameId,
|
||||
required String newIcon,
|
||||
}) async {
|
||||
await (update(gameTable)..where((g) => g.id.equals(gameId))).write(
|
||||
GameTableCompanion(icon: Value(newIcon)),
|
||||
);
|
||||
}
|
||||
/* Read */
|
||||
|
||||
/// Retrieves the total count of games in the database.
|
||||
Future<int> getGameCount() async {
|
||||
@@ -169,6 +73,120 @@ class GameDao extends DatabaseAccessor<AppDatabase> with _$GameDaoMixin {
|
||||
return count ?? 0;
|
||||
}
|
||||
|
||||
/// Checks if a game with the given [gameId] exists in the database.
|
||||
/// Returns `true` if the game exists, `false` otherwise.
|
||||
Future<bool> gameExists({required String gameId}) async {
|
||||
final query = select(gameTable)..where((g) => g.id.equals(gameId));
|
||||
final result = await query.getSingleOrNull();
|
||||
return result != null;
|
||||
}
|
||||
|
||||
/// Retrieves all games from the database.
|
||||
Future<List<Game>> getAllGames() async {
|
||||
final query = select(gameTable);
|
||||
final result = await query.get();
|
||||
return result
|
||||
.map(
|
||||
(row) => Game(
|
||||
id: row.id,
|
||||
name: row.name,
|
||||
ruleset: Ruleset.values.firstWhere((e) => e.name == row.ruleset),
|
||||
description: row.description,
|
||||
color: GameColor.values.firstWhere((e) => e.name == row.color),
|
||||
icon: row.icon,
|
||||
createdAt: row.createdAt,
|
||||
),
|
||||
)
|
||||
.toList();
|
||||
}
|
||||
|
||||
/// Retrieves a [Game] by its [gameId].
|
||||
Future<Game> getGameById({required String gameId}) async {
|
||||
final query = select(gameTable)..where((g) => g.id.equals(gameId));
|
||||
final result = await query.getSingle();
|
||||
return Game(
|
||||
id: result.id,
|
||||
name: result.name,
|
||||
ruleset: Ruleset.values.firstWhere((e) => e.name == result.ruleset),
|
||||
description: result.description,
|
||||
color: GameColor.values.firstWhere((e) => e.name == result.color),
|
||||
icon: result.icon,
|
||||
createdAt: result.createdAt,
|
||||
);
|
||||
}
|
||||
|
||||
/* Update */
|
||||
|
||||
/// Updates the name of the game with the given [gameId] to [name].
|
||||
Future<bool> updateGameName({
|
||||
required String gameId,
|
||||
required String name,
|
||||
}) async {
|
||||
final rowsAffected =
|
||||
await (update(gameTable)..where((g) => g.id.equals(gameId))).write(
|
||||
GameTableCompanion(name: Value(name)),
|
||||
);
|
||||
return rowsAffected > 0;
|
||||
}
|
||||
|
||||
/// Updates the ruleset of the game with the given [gameId].
|
||||
Future<bool> updateGameRuleset({
|
||||
required String gameId,
|
||||
required Ruleset ruleset,
|
||||
}) async {
|
||||
final rowsAffected =
|
||||
await (update(gameTable)..where((g) => g.id.equals(gameId))).write(
|
||||
GameTableCompanion(ruleset: Value(ruleset.name)),
|
||||
);
|
||||
return rowsAffected > 0;
|
||||
}
|
||||
|
||||
/// Updates the description of the game with the given [gameId].
|
||||
Future<bool> updateGameDescription({
|
||||
required String gameId,
|
||||
required String description,
|
||||
}) async {
|
||||
final rowsAffected =
|
||||
await (update(gameTable)..where((g) => g.id.equals(gameId))).write(
|
||||
GameTableCompanion(description: Value(description)),
|
||||
);
|
||||
return rowsAffected > 0;
|
||||
}
|
||||
|
||||
/// Updates the color of the game with the given [gameId].
|
||||
Future<bool> updateGameColor({
|
||||
required String gameId,
|
||||
required GameColor color,
|
||||
}) async {
|
||||
final rowsAffected =
|
||||
await (update(gameTable)..where((g) => g.id.equals(gameId))).write(
|
||||
GameTableCompanion(color: Value(color.name)),
|
||||
);
|
||||
return rowsAffected > 0;
|
||||
}
|
||||
|
||||
/// Updates the icon of the game with the given [gameId].
|
||||
Future<bool> updateGameIcon({
|
||||
required String gameId,
|
||||
required String icon,
|
||||
}) async {
|
||||
final rowsAffected =
|
||||
await (update(gameTable)..where((g) => g.id.equals(gameId))).write(
|
||||
GameTableCompanion(icon: Value(icon)),
|
||||
);
|
||||
return rowsAffected > 0;
|
||||
}
|
||||
|
||||
/* Delete */
|
||||
|
||||
/// Deletes the game with the given [gameId] from the database.
|
||||
/// Returns `true` if the game was deleted, `false` if the game did not exist.
|
||||
Future<bool> deleteGame({required String gameId}) async {
|
||||
final query = delete(gameTable)..where((g) => g.id.equals(gameId));
|
||||
final rowsAffected = await query.go();
|
||||
return rowsAffected > 0;
|
||||
}
|
||||
|
||||
/// Deletes all games from the database.
|
||||
/// Returns `true` if more than 0 rows were affected, otherwise `false`.
|
||||
Future<bool> deleteAllGames() async {
|
||||
@@ -176,4 +194,25 @@ class GameDao extends DatabaseAccessor<AppDatabase> with _$GameDaoMixin {
|
||||
final rowsAffected = await query.go();
|
||||
return rowsAffected > 0;
|
||||
}
|
||||
|
||||
/// Retrieves all games with their respective match counts.
|
||||
/// Returns a list of tuples (Game, matchCount).
|
||||
Future<List<(Game, int)>> getGameUsage() async {
|
||||
final games = await getAllGames();
|
||||
|
||||
final results = <(Game, int)>[];
|
||||
|
||||
for (final game in games) {
|
||||
final matchCount =
|
||||
await (selectOnly(db.matchTable)
|
||||
..where(db.matchTable.gameId.equals(game.id))
|
||||
..addColumns([db.matchTable.id.count()]))
|
||||
.map((row) => row.read(db.matchTable.id.count()))
|
||||
.getSingle();
|
||||
|
||||
results.add((game, matchCount ?? 0));
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,43 +12,7 @@ part 'group_dao.g.dart';
|
||||
class GroupDao extends DatabaseAccessor<AppDatabase> with _$GroupDaoMixin {
|
||||
GroupDao(super.db);
|
||||
|
||||
/// Retrieves all groups from the database.
|
||||
Future<List<Group>> getAllGroups() async {
|
||||
final query = select(groupTable);
|
||||
final result = await query.get();
|
||||
return Future.wait(
|
||||
result.map((groupData) async {
|
||||
final members = await db.playerGroupDao.getPlayersOfGroup(
|
||||
groupId: groupData.id,
|
||||
);
|
||||
return Group(
|
||||
id: groupData.id,
|
||||
name: groupData.name,
|
||||
description: groupData.description,
|
||||
members: members,
|
||||
createdAt: groupData.createdAt,
|
||||
);
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
/// Retrieves a [Group] by its [groupId], including its members.
|
||||
Future<Group> getGroupById({required String groupId}) async {
|
||||
final query = select(groupTable)..where((g) => g.id.equals(groupId));
|
||||
final result = await query.getSingle();
|
||||
|
||||
List<Player> members = await db.playerGroupDao.getPlayersOfGroup(
|
||||
groupId: groupId,
|
||||
);
|
||||
|
||||
return Group(
|
||||
id: result.id,
|
||||
name: result.name,
|
||||
description: result.description,
|
||||
members: members,
|
||||
createdAt: result.createdAt,
|
||||
);
|
||||
}
|
||||
/* Create */
|
||||
|
||||
/// Adds a new group with the given [id] and [name] to the database.
|
||||
/// This method also adds the group's members to the [PlayerGroupTable].
|
||||
@@ -172,38 +136,44 @@ class GroupDao extends DatabaseAccessor<AppDatabase> with _$GroupDaoMixin {
|
||||
});
|
||||
}
|
||||
|
||||
/// Deletes the group with the given [id] from the database.
|
||||
/// Returns `true` if more than 0 rows were affected, otherwise `false`.
|
||||
Future<bool> deleteGroup({required String groupId}) async {
|
||||
final query = (delete(groupTable)..where((g) => g.id.equals(groupId)));
|
||||
final rowsAffected = await query.go();
|
||||
return rowsAffected > 0;
|
||||
/* Read */
|
||||
|
||||
/// Retrieves all groups from the database.
|
||||
Future<List<Group>> getAllGroups() async {
|
||||
final query = select(groupTable);
|
||||
final result = await query.get();
|
||||
return Future.wait(
|
||||
result.map((groupData) async {
|
||||
final members = await db.playerGroupDao.getPlayersOfGroup(
|
||||
groupId: groupData.id,
|
||||
);
|
||||
return Group(
|
||||
id: groupData.id,
|
||||
name: groupData.name,
|
||||
description: groupData.description,
|
||||
members: members,
|
||||
createdAt: groupData.createdAt,
|
||||
);
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
/// Updates the name of the group with the given [id] to [newName].
|
||||
/// Returns `true` if more than 0 rows were affected, otherwise `false`.
|
||||
Future<bool> updateGroupName({
|
||||
required String groupId,
|
||||
required String newName,
|
||||
}) async {
|
||||
final rowsAffected =
|
||||
await (update(groupTable)..where((g) => g.id.equals(groupId))).write(
|
||||
GroupTableCompanion(name: Value(newName)),
|
||||
);
|
||||
return rowsAffected > 0;
|
||||
}
|
||||
/// Retrieves a [Group] by its [groupId], including its members.
|
||||
Future<Group> getGroupById({required String groupId}) async {
|
||||
final query = select(groupTable)..where((g) => g.id.equals(groupId));
|
||||
final result = await query.getSingle();
|
||||
|
||||
/// Updates the description of the group with the given [groupId] to [newDescription].
|
||||
/// Returns `true` if more than 0 rows were affected, otherwise `false`.
|
||||
Future<bool> updateGroupDescription({
|
||||
required String groupId,
|
||||
required String newDescription,
|
||||
}) async {
|
||||
final rowsAffected =
|
||||
await (update(groupTable)..where((g) => g.id.equals(groupId))).write(
|
||||
GroupTableCompanion(description: Value(newDescription)),
|
||||
);
|
||||
return rowsAffected > 0;
|
||||
List<Player> members = await db.playerGroupDao.getPlayersOfGroup(
|
||||
groupId: groupId,
|
||||
);
|
||||
|
||||
return Group(
|
||||
id: result.id,
|
||||
name: result.name,
|
||||
description: result.description,
|
||||
members: members,
|
||||
createdAt: result.createdAt,
|
||||
);
|
||||
}
|
||||
|
||||
/// Retrieves the number of groups in the database.
|
||||
@@ -223,6 +193,16 @@ class GroupDao extends DatabaseAccessor<AppDatabase> with _$GroupDaoMixin {
|
||||
return result != null;
|
||||
}
|
||||
|
||||
/* Delete */
|
||||
|
||||
/// Deletes the group with the given [id] from the database.
|
||||
/// Returns `true` if more than 0 rows were affected, otherwise `false`.
|
||||
Future<bool> deleteGroup({required String groupId}) async {
|
||||
final query = (delete(groupTable)..where((g) => g.id.equals(groupId)));
|
||||
final rowsAffected = await query.go();
|
||||
return rowsAffected > 0;
|
||||
}
|
||||
|
||||
/// Deletes all groups from the database.
|
||||
/// Returns `true` if more than 0 rows were affected, otherwise `false`.
|
||||
Future<bool> deleteAllGroups() async {
|
||||
@@ -231,47 +211,31 @@ class GroupDao extends DatabaseAccessor<AppDatabase> with _$GroupDaoMixin {
|
||||
return rowsAffected > 0;
|
||||
}
|
||||
|
||||
/// Replaces all players in a group with the provided list of players.
|
||||
/// Removes all existing players from the group and adds the new players.
|
||||
/// Also adds any new players to the player table if they don't exist.
|
||||
/// Returns `true` if the group exists and players were replaced, `false` otherwise.
|
||||
Future<bool> replaceGroupPlayers({
|
||||
/* Update */
|
||||
|
||||
/// Updates the name of the group with the given [id] to [name].
|
||||
/// Returns `true` if more than 0 rows were affected, otherwise `false`.
|
||||
Future<bool> updateGroupName({
|
||||
required String groupId,
|
||||
required List<Player> newPlayers,
|
||||
required String name,
|
||||
}) async {
|
||||
if (!await groupExists(groupId: groupId)) return false;
|
||||
final rowsAffected =
|
||||
await (update(groupTable)..where((g) => g.id.equals(groupId))).write(
|
||||
GroupTableCompanion(name: Value(name)),
|
||||
);
|
||||
return rowsAffected > 0;
|
||||
}
|
||||
|
||||
await db.transaction(() async {
|
||||
// Remove all existing players from the group
|
||||
final deleteQuery = delete(db.playerGroupTable)
|
||||
..where((p) => p.groupId.equals(groupId));
|
||||
await deleteQuery.go();
|
||||
|
||||
// Add new players to the player table if they don't exist
|
||||
await Future.wait(
|
||||
newPlayers.map((player) async {
|
||||
if (!await db.playerDao.playerExists(playerId: player.id)) {
|
||||
await db.playerDao.addPlayer(player: player);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
// Add the new players to the group
|
||||
await db.batch(
|
||||
(b) => b.insertAll(
|
||||
db.playerGroupTable,
|
||||
newPlayers
|
||||
.map(
|
||||
(player) => PlayerGroupTableCompanion.insert(
|
||||
playerId: player.id,
|
||||
groupId: groupId,
|
||||
),
|
||||
)
|
||||
.toList(),
|
||||
mode: InsertMode.insertOrReplace,
|
||||
),
|
||||
);
|
||||
});
|
||||
return true;
|
||||
/// Updates the description of the group with the given [groupId] to [description].
|
||||
/// Returns `true` if more than 0 rows were affected, otherwise `false`.
|
||||
Future<bool> updateGroupDescription({
|
||||
required String groupId,
|
||||
required String description,
|
||||
}) async {
|
||||
final rowsAffected =
|
||||
await (update(groupTable)..where((g) => g.id.equals(groupId))).write(
|
||||
GroupTableCompanion(description: Value(description)),
|
||||
);
|
||||
return rowsAffected > 0;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ import 'package:tallee/data/models/game.dart';
|
||||
import 'package:tallee/data/models/group.dart';
|
||||
import 'package:tallee/data/models/match.dart';
|
||||
import 'package:tallee/data/models/player.dart';
|
||||
import 'package:tallee/data/models/team.dart';
|
||||
|
||||
part 'match_dao.g.dart';
|
||||
|
||||
@@ -15,74 +16,13 @@ part 'match_dao.g.dart';
|
||||
class MatchDao extends DatabaseAccessor<AppDatabase> with _$MatchDaoMixin {
|
||||
MatchDao(super.db);
|
||||
|
||||
/// Retrieves all matches from the database.
|
||||
Future<List<Match>> getAllMatches() async {
|
||||
final query = select(matchTable);
|
||||
final result = await query.get();
|
||||
/* Create */
|
||||
|
||||
return Future.wait(
|
||||
result.map((row) async {
|
||||
final game = await db.gameDao.getGameById(gameId: row.gameId);
|
||||
Group? group;
|
||||
if (row.groupId != null) {
|
||||
group = await db.groupDao.getGroupById(groupId: row.groupId!);
|
||||
}
|
||||
final players =
|
||||
await db.playerMatchDao.getPlayersOfMatch(matchId: row.id) ?? [];
|
||||
|
||||
final scores = await db.scoreEntryDao.getAllMatchScores(
|
||||
matchId: row.id,
|
||||
);
|
||||
|
||||
return Match(
|
||||
id: row.id,
|
||||
name: row.name,
|
||||
game: game,
|
||||
group: group,
|
||||
players: players,
|
||||
notes: row.notes ?? '',
|
||||
createdAt: row.createdAt,
|
||||
endedAt: row.endedAt,
|
||||
scores: scores,
|
||||
);
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
/// Retrieves a [Match] by its [matchId].
|
||||
Future<Match> getMatchById({required String matchId}) async {
|
||||
final query = select(matchTable)..where((g) => g.id.equals(matchId));
|
||||
final result = await query.getSingle();
|
||||
|
||||
final game = await db.gameDao.getGameById(gameId: result.gameId);
|
||||
|
||||
Group? group;
|
||||
if (result.groupId != null) {
|
||||
group = await db.groupDao.getGroupById(groupId: result.groupId!);
|
||||
}
|
||||
|
||||
final players =
|
||||
await db.playerMatchDao.getPlayersOfMatch(matchId: matchId) ?? [];
|
||||
|
||||
final scores = await db.scoreEntryDao.getAllMatchScores(matchId: matchId);
|
||||
|
||||
return Match(
|
||||
id: result.id,
|
||||
name: result.name,
|
||||
game: game,
|
||||
group: group,
|
||||
players: players,
|
||||
notes: result.notes ?? '',
|
||||
createdAt: result.createdAt,
|
||||
endedAt: result.endedAt,
|
||||
scores: scores,
|
||||
);
|
||||
}
|
||||
|
||||
/// Adds a new [Match] to the database. Also adds players associations.
|
||||
/// Adds a new [Match] to the database. Also adds players associations and teams.
|
||||
/// This method assumes that the game and group (if any) are already present
|
||||
/// in the database.
|
||||
Future<void> addMatch({required Match match}) async {
|
||||
Future<bool> addMatch({required Match match}) async {
|
||||
if (await matchExists(matchId: match.id)) return false;
|
||||
await db.transaction(() async {
|
||||
await into(matchTable).insert(
|
||||
MatchTableCompanion.insert(
|
||||
@@ -90,18 +30,36 @@ class MatchDao extends DatabaseAccessor<AppDatabase> with _$MatchDaoMixin {
|
||||
gameId: match.game.id,
|
||||
groupId: Value(match.group?.id),
|
||||
name: match.name,
|
||||
notes: Value(match.notes),
|
||||
notes: match.notes,
|
||||
createdAt: match.createdAt,
|
||||
endedAt: Value(match.endedAt),
|
||||
),
|
||||
mode: InsertMode.insertOrReplace,
|
||||
);
|
||||
|
||||
// Add teams
|
||||
if (match.teams != null && match.teams!.isNotEmpty) {
|
||||
await db.teamDao.addTeamsAsList(teams: match.teams!, matchId: match.id);
|
||||
}
|
||||
|
||||
// Collect all player IDs that are already in teams
|
||||
final playersInTeams = <String>{};
|
||||
if (match.teams != null) {
|
||||
for (final team in match.teams!) {
|
||||
for (final member in team.members) {
|
||||
playersInTeams.add(member.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Add players that are not in teams
|
||||
for (final p in match.players) {
|
||||
await db.playerMatchDao.addPlayerToMatch(
|
||||
matchId: match.id,
|
||||
playerId: p.id,
|
||||
);
|
||||
if (!playersInTeams.contains(p.id)) {
|
||||
await db.playerMatchDao.addPlayerToMatch(
|
||||
matchId: match.id,
|
||||
playerId: p.id,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
for (final pid in match.scores.keys) {
|
||||
@@ -115,14 +73,15 @@ class MatchDao extends DatabaseAccessor<AppDatabase> with _$MatchDaoMixin {
|
||||
}
|
||||
}
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
/// Adds multiple [Match]es to the database in a batch operation.
|
||||
/// Also adds associated players and groups if they exist.
|
||||
/// If the [matches] list is empty, the method returns immediately.
|
||||
/// This method should only be used to import matches from a different device.
|
||||
Future<void> addMatchAsList({required List<Match> matches}) async {
|
||||
if (matches.isEmpty) return;
|
||||
Future<bool> addMatchesAsList({required List<Match> matches}) async {
|
||||
if (matches.isEmpty) return false;
|
||||
await db.transaction(() async {
|
||||
// Add all games first (deduplicated)
|
||||
final uniqueGames = <String, Game>{};
|
||||
@@ -183,7 +142,7 @@ class MatchDao extends DatabaseAccessor<AppDatabase> with _$MatchDaoMixin {
|
||||
gameId: match.game.id,
|
||||
groupId: Value(match.group?.id),
|
||||
name: match.name,
|
||||
notes: Value(match.notes),
|
||||
notes: match.notes,
|
||||
createdAt: match.createdAt,
|
||||
endedAt: Value(match.endedAt),
|
||||
),
|
||||
@@ -279,15 +238,28 @@ class MatchDao extends DatabaseAccessor<AppDatabase> with _$MatchDaoMixin {
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Add teams for matches
|
||||
for (final match in matches) {
|
||||
if (match.teams != null && match.teams!.isNotEmpty) {
|
||||
await db.teamDao.addTeamsAsList(
|
||||
teams: match.teams!,
|
||||
matchId: match.id,
|
||||
);
|
||||
}
|
||||
}
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
/// Deletes the match with the given [matchId] from the database.
|
||||
/// Returns `true` if more than 0 rows were affected, otherwise `false`.
|
||||
Future<bool> deleteMatch({required String matchId}) async {
|
||||
final query = delete(matchTable)..where((g) => g.id.equals(matchId));
|
||||
final rowsAffected = await query.go();
|
||||
return rowsAffected > 0;
|
||||
/* Read */
|
||||
|
||||
/// Checks if a match with the given [matchId] exists in the database.
|
||||
/// Returns `true` if the match exists, otherwise `false`.
|
||||
Future<bool> matchExists({required String matchId}) async {
|
||||
final query = select(matchTable)..where((g) => g.id.equals(matchId));
|
||||
final result = await query.getSingleOrNull();
|
||||
return result != null;
|
||||
}
|
||||
|
||||
/// Retrieves the number of matches in the database.
|
||||
@@ -299,9 +271,90 @@ class MatchDao extends DatabaseAccessor<AppDatabase> with _$MatchDaoMixin {
|
||||
return count ?? 0;
|
||||
}
|
||||
|
||||
/// Retrieves all matches from the database.
|
||||
Future<List<Match>> getAllMatches() async {
|
||||
final query = select(matchTable);
|
||||
final result = await query.get();
|
||||
|
||||
return Future.wait(
|
||||
result.map((row) async {
|
||||
final game = await db.gameDao.getGameById(gameId: row.gameId);
|
||||
Group? group;
|
||||
if (row.groupId != null) {
|
||||
group = await db.groupDao.getGroupById(groupId: row.groupId!);
|
||||
}
|
||||
final players = await db.playerMatchDao.getPlayersOfMatch(
|
||||
matchId: row.id,
|
||||
);
|
||||
|
||||
final scores = await db.scoreEntryDao.getAllMatchScores(
|
||||
matchId: row.id,
|
||||
);
|
||||
|
||||
final teams = await _getMatchTeams(matchId: row.id);
|
||||
|
||||
return Match(
|
||||
id: row.id,
|
||||
name: row.name,
|
||||
game: game,
|
||||
group: group,
|
||||
players: players,
|
||||
teams: teams.isEmpty ? null : teams,
|
||||
notes: row.notes,
|
||||
createdAt: row.createdAt,
|
||||
endedAt: row.endedAt,
|
||||
scores: scores,
|
||||
);
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
/// Retrieves a [Match] by its [matchId].
|
||||
Future<Match> getMatchById({required String matchId}) async {
|
||||
final query = select(matchTable)..where((g) => g.id.equals(matchId));
|
||||
final result = await query.getSingle();
|
||||
|
||||
final game = await db.gameDao.getGameById(gameId: result.gameId);
|
||||
|
||||
Group? group;
|
||||
if (result.groupId != null) {
|
||||
group = await db.groupDao.getGroupById(groupId: result.groupId!);
|
||||
}
|
||||
|
||||
final players = await db.playerMatchDao.getPlayersOfMatch(matchId: matchId);
|
||||
|
||||
final scores = await db.scoreEntryDao.getAllMatchScores(matchId: matchId);
|
||||
|
||||
final teams = await _getMatchTeams(matchId: matchId);
|
||||
|
||||
return Match(
|
||||
id: result.id,
|
||||
name: result.name,
|
||||
game: game,
|
||||
group: group,
|
||||
players: players,
|
||||
teams: teams.isEmpty ? null : teams,
|
||||
notes: result.notes,
|
||||
createdAt: result.createdAt,
|
||||
endedAt: result.endedAt,
|
||||
scores: scores,
|
||||
);
|
||||
}
|
||||
|
||||
/// Retrieves the number of matches associated with a specific game.
|
||||
Future<int> getMatchCountByGame({required String gameId}) async {
|
||||
final count =
|
||||
await (selectOnly(matchTable)
|
||||
..where(matchTable.gameId.equals(gameId))
|
||||
..addColumns([matchTable.id.count()]))
|
||||
.map((row) => row.read(matchTable.id.count()))
|
||||
.getSingle();
|
||||
return count ?? 0;
|
||||
}
|
||||
|
||||
/// Retrieves all matches associated with the given [groupId].
|
||||
/// Queries the database directly, filtering by [groupId].
|
||||
Future<List<Match>> getGroupMatches({required String groupId}) async {
|
||||
Future<List<Match>> getMatchesByGroup({required String groupId}) async {
|
||||
final query = select(matchTable)..where((m) => m.groupId.equals(groupId));
|
||||
final rows = await query.get();
|
||||
|
||||
@@ -309,15 +362,18 @@ class MatchDao extends DatabaseAccessor<AppDatabase> with _$MatchDaoMixin {
|
||||
rows.map((row) async {
|
||||
final game = await db.gameDao.getGameById(gameId: row.gameId);
|
||||
final group = await db.groupDao.getGroupById(groupId: groupId);
|
||||
final players =
|
||||
await db.playerMatchDao.getPlayersOfMatch(matchId: row.id) ?? [];
|
||||
final players = await db.playerMatchDao.getPlayersOfMatch(
|
||||
matchId: row.id,
|
||||
);
|
||||
final teams = await _getMatchTeams(matchId: row.id);
|
||||
return Match(
|
||||
id: row.id,
|
||||
name: row.name,
|
||||
game: game,
|
||||
group: group,
|
||||
players: players,
|
||||
notes: row.notes ?? '',
|
||||
teams: teams.isEmpty ? null : teams,
|
||||
notes: row.notes,
|
||||
createdAt: row.createdAt,
|
||||
endedAt: row.endedAt,
|
||||
);
|
||||
@@ -325,19 +381,56 @@ class MatchDao extends DatabaseAccessor<AppDatabase> with _$MatchDaoMixin {
|
||||
);
|
||||
}
|
||||
|
||||
/// Checks if a match with the given [matchId] exists in the database.
|
||||
/// Returns `true` if the match exists, otherwise `false`.
|
||||
Future<bool> matchExists({required String matchId}) async {
|
||||
final query = select(matchTable)..where((g) => g.id.equals(matchId));
|
||||
final result = await query.getSingleOrNull();
|
||||
return result != null;
|
||||
/// Helper method to retrieve teams for a specific match
|
||||
Future<List<Team>> _getMatchTeams({required String matchId}) async {
|
||||
// Get all unique team IDs from PlayerMatchTable for this match
|
||||
final playerMatchQuery = select(db.playerMatchTable)
|
||||
..where((pm) => pm.matchId.equals(matchId) & pm.teamId.isNotNull());
|
||||
final playerMatches = await playerMatchQuery.get();
|
||||
|
||||
if (playerMatches.isEmpty) return [];
|
||||
|
||||
final teamIds = playerMatches
|
||||
.map((pm) => pm.teamId)
|
||||
.whereType<String>()
|
||||
.toSet()
|
||||
.toList();
|
||||
|
||||
// Fetch all teams
|
||||
final teams = await Future.wait(
|
||||
teamIds.map((teamId) => db.teamDao.getTeamById(teamId: teamId)),
|
||||
);
|
||||
|
||||
return teams;
|
||||
}
|
||||
|
||||
/// Deletes all matches from the database.
|
||||
/* Update */
|
||||
|
||||
/// Changes the name of the match with the given [matchId] to [name].
|
||||
/// Returns `true` if more than 0 rows were affected, otherwise `false`.
|
||||
Future<bool> deleteAllMatches() async {
|
||||
final query = delete(matchTable);
|
||||
final rowsAffected = await query.go();
|
||||
Future<bool> updateMatchName({
|
||||
required String matchId,
|
||||
required String name,
|
||||
}) async {
|
||||
final query = update(matchTable)..where((g) => g.id.equals(matchId));
|
||||
final rowsAffected = await query.write(
|
||||
MatchTableCompanion(name: Value(name)),
|
||||
);
|
||||
return rowsAffected > 0;
|
||||
}
|
||||
|
||||
/// Updates the group of the match with the given [matchId].
|
||||
/// Replaces the existing group association with the new group specified by [groupId].
|
||||
/// Pass null to remove the group association.
|
||||
/// Returns `true` if more than 0 rows were affected, otherwise `false`.
|
||||
Future<bool> updateMatchGroup({
|
||||
required String matchId,
|
||||
required String? groupId,
|
||||
}) async {
|
||||
final query = update(matchTable)..where((g) => g.id.equals(matchId));
|
||||
final rowsAffected = await query.write(
|
||||
MatchTableCompanion(groupId: Value(groupId)),
|
||||
);
|
||||
return rowsAffected > 0;
|
||||
}
|
||||
|
||||
@@ -345,7 +438,7 @@ class MatchDao extends DatabaseAccessor<AppDatabase> with _$MatchDaoMixin {
|
||||
/// Returns `true` if more than 0 rows were affected, otherwise `false`.
|
||||
Future<bool> updateMatchNotes({
|
||||
required String matchId,
|
||||
required String? notes,
|
||||
required String notes,
|
||||
}) async {
|
||||
final query = update(matchTable)..where((g) => g.id.equals(matchId));
|
||||
final rowsAffected = await query.write(
|
||||
@@ -354,47 +447,6 @@ class MatchDao extends DatabaseAccessor<AppDatabase> with _$MatchDaoMixin {
|
||||
return rowsAffected > 0;
|
||||
}
|
||||
|
||||
/// Changes the name of the match with the given [matchId] to [newName].
|
||||
/// Returns `true` if more than 0 rows were affected, otherwise `false`.
|
||||
Future<bool> updateMatchName({
|
||||
required String matchId,
|
||||
required String newName,
|
||||
}) async {
|
||||
final query = update(matchTable)..where((g) => g.id.equals(matchId));
|
||||
final rowsAffected = await query.write(
|
||||
MatchTableCompanion(name: Value(newName)),
|
||||
);
|
||||
return rowsAffected > 0;
|
||||
}
|
||||
|
||||
/// Updates the game of the match with the given [matchId].
|
||||
/// Returns `true` if more than 0 rows were affected, otherwise `false`.
|
||||
Future<bool> updateMatchGame({
|
||||
required String matchId,
|
||||
required String gameId,
|
||||
}) async {
|
||||
final query = update(matchTable)..where((g) => g.id.equals(matchId));
|
||||
final rowsAffected = await query.write(
|
||||
MatchTableCompanion(gameId: Value(gameId)),
|
||||
);
|
||||
return rowsAffected > 0;
|
||||
}
|
||||
|
||||
/// Updates the group of the match with the given [matchId].
|
||||
/// Replaces the existing group association with the new group specified by [newGroupId].
|
||||
/// Pass null to remove the group association.
|
||||
/// Returns `true` if more than 0 rows were affected, otherwise `false`.
|
||||
Future<bool> updateMatchGroup({
|
||||
required String matchId,
|
||||
required String? newGroupId,
|
||||
}) async {
|
||||
final query = update(matchTable)..where((g) => g.id.equals(matchId));
|
||||
final rowsAffected = await query.write(
|
||||
MatchTableCompanion(groupId: Value(newGroupId)),
|
||||
);
|
||||
return rowsAffected > 0;
|
||||
}
|
||||
|
||||
/// Removes the group association of the match with the given [matchId].
|
||||
/// Sets the groupId to null.
|
||||
/// Returns `true` if more than 0 rows were affected, otherwise `false`.
|
||||
@@ -406,25 +458,12 @@ class MatchDao extends DatabaseAccessor<AppDatabase> with _$MatchDaoMixin {
|
||||
return rowsAffected > 0;
|
||||
}
|
||||
|
||||
/// Updates the createdAt timestamp of the match with the given [matchId].
|
||||
/// Returns `true` if more than 0 rows were affected, otherwise `false`.
|
||||
Future<bool> updateMatchCreatedAt({
|
||||
required String matchId,
|
||||
required DateTime createdAt,
|
||||
}) async {
|
||||
final query = update(matchTable)..where((g) => g.id.equals(matchId));
|
||||
final rowsAffected = await query.write(
|
||||
MatchTableCompanion(createdAt: Value(createdAt)),
|
||||
);
|
||||
return rowsAffected > 0;
|
||||
}
|
||||
|
||||
/// Updates the endedAt timestamp of the match with the given [matchId].
|
||||
/// Pass null to remove the ended time (mark match as ongoing).
|
||||
/// Returns `true` if more than 0 rows were affected, otherwise `false`.
|
||||
Future<bool> updateMatchEndedAt({
|
||||
required String matchId,
|
||||
required DateTime? endedAt,
|
||||
required DateTime endedAt,
|
||||
}) async {
|
||||
final query = update(matchTable)..where((g) => g.id.equals(matchId));
|
||||
final rowsAffected = await query.write(
|
||||
@@ -433,37 +472,29 @@ class MatchDao extends DatabaseAccessor<AppDatabase> with _$MatchDaoMixin {
|
||||
return rowsAffected > 0;
|
||||
}
|
||||
|
||||
/// Replaces all players in a match with the provided list of players.
|
||||
/// Removes all existing players from the match and adds the new players.
|
||||
/// Also adds any new players to the player table if they don't exist.
|
||||
Future<void> replaceMatchPlayers({
|
||||
required String matchId,
|
||||
required List<Player> newPlayers,
|
||||
}) async {
|
||||
await db.transaction(() async {
|
||||
// Remove all existing players from the match
|
||||
final deleteQuery = delete(db.playerMatchTable)
|
||||
..where((p) => p.matchId.equals(matchId));
|
||||
await deleteQuery.go();
|
||||
/* Delete */
|
||||
|
||||
// Add new players to the player table if they don't exist
|
||||
await Future.wait(
|
||||
newPlayers.map((player) async {
|
||||
if (!await db.playerDao.playerExists(playerId: player.id)) {
|
||||
await db.playerDao.addPlayer(player: player);
|
||||
}
|
||||
}),
|
||||
);
|
||||
/// Deletes the match with the given [matchId] from the database.
|
||||
/// Returns `true` if more than 0 rows were affected, otherwise `false`.
|
||||
Future<bool> deleteMatch({required String matchId}) async {
|
||||
final query = delete(matchTable)..where((g) => g.id.equals(matchId));
|
||||
final rowsAffected = await query.go();
|
||||
return rowsAffected > 0;
|
||||
}
|
||||
|
||||
// Add the new players to the match
|
||||
await Future.wait(
|
||||
newPlayers.map(
|
||||
(player) => db.playerMatchDao.addPlayerToMatch(
|
||||
matchId: matchId,
|
||||
playerId: player.id,
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
/// Deletes all matches from the database.
|
||||
/// Returns `true` if more than 0 rows were affected, otherwise `false`.
|
||||
Future<bool> deleteAllMatches() async {
|
||||
final query = delete(matchTable);
|
||||
final rowsAffected = await query.go();
|
||||
return rowsAffected > 0;
|
||||
}
|
||||
|
||||
/// Deletes all matches associated with a specific game.
|
||||
/// Returns the number of matches deleted.
|
||||
Future<int> deleteMatchesByGame({required String gameId}) async {
|
||||
final query = delete(matchTable)..where((m) => m.gameId.equals(gameId));
|
||||
final rowsAffected = await query.go();
|
||||
return rowsAffected;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,35 +10,7 @@ part 'player_dao.g.dart';
|
||||
class PlayerDao extends DatabaseAccessor<AppDatabase> with _$PlayerDaoMixin {
|
||||
PlayerDao(super.db);
|
||||
|
||||
/// Retrieves all players from the database.
|
||||
Future<List<Player>> getAllPlayers() async {
|
||||
final query = select(playerTable);
|
||||
final result = await query.get();
|
||||
return result
|
||||
.map(
|
||||
(row) => Player(
|
||||
id: row.id,
|
||||
name: row.name,
|
||||
description: row.description,
|
||||
createdAt: row.createdAt,
|
||||
nameCount: row.nameCount,
|
||||
),
|
||||
)
|
||||
.toList();
|
||||
}
|
||||
|
||||
/// Retrieves a [Player] by their [id].
|
||||
Future<Player> getPlayerById({required String playerId}) async {
|
||||
final query = select(playerTable)..where((p) => p.id.equals(playerId));
|
||||
final result = await query.getSingle();
|
||||
return Player(
|
||||
id: result.id,
|
||||
name: result.name,
|
||||
description: result.description,
|
||||
createdAt: result.createdAt,
|
||||
nameCount: result.nameCount,
|
||||
);
|
||||
}
|
||||
/* Create */
|
||||
|
||||
/// Adds a new [player] to the database.
|
||||
/// If a player with the same ID already exists, updates their name to
|
||||
@@ -135,12 +107,15 @@ class PlayerDao extends DatabaseAccessor<AppDatabase> with _$PlayerDaoMixin {
|
||||
return true;
|
||||
}
|
||||
|
||||
/// Deletes the player with the given [id] from the database.
|
||||
/// Returns `true` if the player was deleted, `false` if the player did not exist.
|
||||
Future<bool> deletePlayer({required String playerId}) async {
|
||||
final query = delete(playerTable)..where((p) => p.id.equals(playerId));
|
||||
final rowsAffected = await query.go();
|
||||
return rowsAffected > 0;
|
||||
/* Read */
|
||||
|
||||
/// Retrieves the total count of players in the database.
|
||||
Future<int> getPlayerCount() async {
|
||||
final count =
|
||||
await (selectOnly(playerTable)..addColumns([playerTable.id.count()]))
|
||||
.map((row) => row.read(playerTable.id.count()))
|
||||
.getSingle();
|
||||
return count ?? 0;
|
||||
}
|
||||
|
||||
/// Checks if a player with the given [playerId] exists in the database.
|
||||
@@ -151,10 +126,42 @@ class PlayerDao extends DatabaseAccessor<AppDatabase> with _$PlayerDaoMixin {
|
||||
return result != null;
|
||||
}
|
||||
|
||||
/// Updates the name of the player with the given [playerId] to [newName].
|
||||
Future<void> updatePlayerName({
|
||||
/// Retrieves all players from the database.
|
||||
Future<List<Player>> getAllPlayers() async {
|
||||
final query = select(playerTable);
|
||||
final result = await query.get();
|
||||
return result
|
||||
.map(
|
||||
(row) => Player(
|
||||
id: row.id,
|
||||
name: row.name,
|
||||
description: row.description,
|
||||
createdAt: row.createdAt,
|
||||
nameCount: row.nameCount,
|
||||
),
|
||||
)
|
||||
.toList();
|
||||
}
|
||||
|
||||
/// Retrieves a [Player] by their [id].
|
||||
Future<Player> getPlayerById({required String playerId}) async {
|
||||
final query = select(playerTable)..where((p) => p.id.equals(playerId));
|
||||
final result = await query.getSingle();
|
||||
return Player(
|
||||
id: result.id,
|
||||
name: result.name,
|
||||
description: result.description,
|
||||
createdAt: result.createdAt,
|
||||
nameCount: result.nameCount,
|
||||
);
|
||||
}
|
||||
|
||||
/* Update */
|
||||
|
||||
/// Updates the name of the player with the given [playerId] to [name].
|
||||
Future<bool> updatePlayerName({
|
||||
required String playerId,
|
||||
required String newName,
|
||||
required String name,
|
||||
}) async {
|
||||
// Get previous name and name count for the player before updating
|
||||
final previousPlayerName =
|
||||
@@ -164,14 +171,15 @@ class PlayerDao extends DatabaseAccessor<AppDatabase> with _$PlayerDaoMixin {
|
||||
'';
|
||||
final previousNameCount = await getNameCount(name: previousPlayerName);
|
||||
|
||||
await (update(playerTable)..where((p) => p.id.equals(playerId))).write(
|
||||
PlayerTableCompanion(name: Value(newName)),
|
||||
);
|
||||
final rowsAffected =
|
||||
await (update(playerTable)..where((p) => p.id.equals(playerId))).write(
|
||||
PlayerTableCompanion(name: Value(name)),
|
||||
);
|
||||
|
||||
// Update name count for the new name
|
||||
final count = await calculateNameCount(name: newName);
|
||||
final count = await calculateNameCount(name: name);
|
||||
if (count > 0) {
|
||||
await (update(playerTable)..where((p) => p.name.equals(newName))).write(
|
||||
await (update(playerTable)..where((p) => p.name.equals(name))).write(
|
||||
PlayerTableCompanion(nameCount: Value(count)),
|
||||
);
|
||||
}
|
||||
@@ -188,17 +196,35 @@ class PlayerDao extends DatabaseAccessor<AppDatabase> with _$PlayerDaoMixin {
|
||||
);
|
||||
}
|
||||
}
|
||||
return rowsAffected > 0;
|
||||
}
|
||||
|
||||
/// Retrieves the total count of players in the database.
|
||||
Future<int> getPlayerCount() async {
|
||||
final count =
|
||||
await (selectOnly(playerTable)..addColumns([playerTable.id.count()]))
|
||||
.map((row) => row.read(playerTable.id.count()))
|
||||
.getSingle();
|
||||
return count ?? 0;
|
||||
/// Updates the description of the player with the given [playerId] to
|
||||
/// [description].
|
||||
/// Returns `true` if more than 0 rows were affected, otherwise `false`.
|
||||
Future<bool> updatePlayerDescription({
|
||||
required String playerId,
|
||||
required String description,
|
||||
}) async {
|
||||
final rowsAffected =
|
||||
await (update(playerTable)..where((g) => g.id.equals(playerId))).write(
|
||||
PlayerTableCompanion(description: Value(description)),
|
||||
);
|
||||
return rowsAffected > 0;
|
||||
}
|
||||
|
||||
/* Delete */
|
||||
|
||||
/// Deletes the player with the given [id] from the database.
|
||||
/// Returns `true` if the player was deleted, `false` if the player did not exist.
|
||||
Future<bool> deletePlayer({required String playerId}) async {
|
||||
final query = delete(playerTable)..where((p) => p.id.equals(playerId));
|
||||
final rowsAffected = await query.go();
|
||||
return rowsAffected > 0;
|
||||
}
|
||||
|
||||
/* Name count management */
|
||||
|
||||
/// Retrieves the count of players with the given [name].
|
||||
Future<int> getNameCount({required String name}) async {
|
||||
final query = select(playerTable)..where((p) => p.name.equals(name));
|
||||
|
||||
@@ -11,8 +11,7 @@ class PlayerGroupDao extends DatabaseAccessor<AppDatabase>
|
||||
with _$PlayerGroupDaoMixin {
|
||||
PlayerGroupDao(super.db);
|
||||
|
||||
/// No need for a groupHasPlayers method since the members attribute is
|
||||
/// not nullable
|
||||
/* Create */
|
||||
|
||||
/// Adds a [player] to a group with the given [groupId].
|
||||
/// If the player is already in the group, no action is taken.
|
||||
@@ -33,10 +32,11 @@ class PlayerGroupDao extends DatabaseAccessor<AppDatabase>
|
||||
await into(playerGroupTable).insert(
|
||||
PlayerGroupTableCompanion.insert(playerId: player.id, groupId: groupId),
|
||||
);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/* Read */
|
||||
|
||||
/// Retrieves all players belonging to a specific group by [groupId].
|
||||
Future<List<Player>> getPlayersOfGroup({required String groupId}) async {
|
||||
final query = select(playerGroupTable)
|
||||
@@ -53,18 +53,6 @@ class PlayerGroupDao extends DatabaseAccessor<AppDatabase>
|
||||
return groupMembers;
|
||||
}
|
||||
|
||||
/// Removes a player from a group based on [playerId] and [groupId].
|
||||
/// Returns `true` if more than 0 rows were affected, otherwise `false`.
|
||||
Future<bool> removePlayerFromGroup({
|
||||
required String playerId,
|
||||
required String groupId,
|
||||
}) async {
|
||||
final query = delete(playerGroupTable)
|
||||
..where((p) => p.playerId.equals(playerId) & p.groupId.equals(groupId));
|
||||
final rowsAffected = await query.go();
|
||||
return rowsAffected > 0;
|
||||
}
|
||||
|
||||
/// Checks if a player with [playerId] is in the group with [groupId].
|
||||
/// Returns `true` if the player is in the group, otherwise `false`.
|
||||
Future<bool> isPlayerInGroup({
|
||||
@@ -76,4 +64,65 @@ class PlayerGroupDao extends DatabaseAccessor<AppDatabase>
|
||||
final result = await query.getSingleOrNull();
|
||||
return result != null;
|
||||
}
|
||||
|
||||
/* Update */
|
||||
|
||||
/// Replaces all players in a group with the provided list of players.
|
||||
/// Removes all existing players from the group and adds the new players.
|
||||
/// Also adds any new players to the player table if they don't exist.
|
||||
/// Returns `true` if the group exists and players were replaced, `false` otherwise.
|
||||
Future<bool> replaceGroupPlayers({
|
||||
required String groupId,
|
||||
required List<Player> newPlayers,
|
||||
}) async {
|
||||
if (!await db.groupDao.groupExists(groupId: groupId)) return false;
|
||||
if (newPlayers.isEmpty) return false;
|
||||
|
||||
await db.transaction(() async {
|
||||
// Remove all existing players from the group
|
||||
final deleteQuery = delete(db.playerGroupTable)
|
||||
..where((p) => p.groupId.equals(groupId));
|
||||
await deleteQuery.go();
|
||||
|
||||
// Add new players to the player table if they don't exist
|
||||
await Future.wait(
|
||||
newPlayers.map((player) async {
|
||||
if (!await db.playerDao.playerExists(playerId: player.id)) {
|
||||
await db.playerDao.addPlayer(player: player);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
// Add the new players to the group
|
||||
await db.batch(
|
||||
(b) => b.insertAll(
|
||||
db.playerGroupTable,
|
||||
newPlayers
|
||||
.map(
|
||||
(player) => PlayerGroupTableCompanion.insert(
|
||||
playerId: player.id,
|
||||
groupId: groupId,
|
||||
),
|
||||
)
|
||||
.toList(),
|
||||
mode: InsertMode.insertOrReplace,
|
||||
),
|
||||
);
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
/* Delete */
|
||||
|
||||
/// Removes a player from a group based on [playerId] and [groupId].
|
||||
/// Returns `true` if more than 0 rows were affected, otherwise `false`.
|
||||
Future<bool> removePlayerFromGroup({
|
||||
required String playerId,
|
||||
required String groupId,
|
||||
}) async {
|
||||
final query = delete(playerGroupTable)
|
||||
..where((p) => p.playerId.equals(playerId) & p.groupId.equals(groupId));
|
||||
final rowsAffected = await query.go();
|
||||
return rowsAffected > 0;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,14 +11,16 @@ class PlayerMatchDao extends DatabaseAccessor<AppDatabase>
|
||||
with _$PlayerMatchDaoMixin {
|
||||
PlayerMatchDao(super.db);
|
||||
|
||||
/* Create */
|
||||
|
||||
/// Associates a player with a match by inserting a record into the
|
||||
/// [PlayerMatchTable]. Optionally associates with a team and sets initial score.
|
||||
Future<void> addPlayerToMatch({
|
||||
Future<bool> addPlayerToMatch({
|
||||
required String matchId,
|
||||
required String playerId,
|
||||
String? teamId,
|
||||
}) async {
|
||||
await into(playerMatchTable).insert(
|
||||
final rowsAffected = await into(playerMatchTable).insert(
|
||||
PlayerMatchTableCompanion.insert(
|
||||
playerId: playerId,
|
||||
matchId: matchId,
|
||||
@@ -26,42 +28,14 @@ class PlayerMatchDao extends DatabaseAccessor<AppDatabase>
|
||||
),
|
||||
mode: InsertMode.insertOrReplace,
|
||||
);
|
||||
}
|
||||
|
||||
/// Retrieves a list of [Player]s associated with the given [matchId].
|
||||
/// Returns null if no players are found.
|
||||
Future<List<Player>?> getPlayersOfMatch({required String matchId}) async {
|
||||
final result = await (select(
|
||||
playerMatchTable,
|
||||
)..where((p) => p.matchId.equals(matchId))).get();
|
||||
|
||||
if (result.isEmpty) return null;
|
||||
|
||||
final futures = result.map(
|
||||
(row) => db.playerDao.getPlayerById(playerId: row.playerId),
|
||||
);
|
||||
final players = await Future.wait(futures);
|
||||
return players;
|
||||
}
|
||||
|
||||
/// Updates the team for a player in a match.
|
||||
/// Returns `true` if the update was successful, otherwise `false`.
|
||||
Future<bool> updatePlayerTeam({
|
||||
required String matchId,
|
||||
required String playerId,
|
||||
required String? teamId,
|
||||
}) async {
|
||||
final rowsAffected =
|
||||
await (update(playerMatchTable)..where(
|
||||
(p) => p.matchId.equals(matchId) & p.playerId.equals(playerId),
|
||||
))
|
||||
.write(PlayerMatchTableCompanion(teamId: Value(teamId)));
|
||||
return rowsAffected > 0;
|
||||
}
|
||||
|
||||
/* Read */
|
||||
|
||||
/// Checks if there are any players associated with the given [matchId].
|
||||
/// Returns `true` if there are players, otherwise `false`.
|
||||
Future<bool> matchHasPlayers({required String matchId}) async {
|
||||
Future<bool> hasMatchPlayers({required String matchId}) async {
|
||||
final count =
|
||||
await (selectOnly(playerMatchTable)
|
||||
..where(playerMatchTable.matchId.equals(matchId))
|
||||
@@ -87,31 +61,79 @@ class PlayerMatchDao extends DatabaseAccessor<AppDatabase>
|
||||
return (count ?? 0) > 0;
|
||||
}
|
||||
|
||||
/// Removes the association of a player with a match by deleting the record
|
||||
/// from the [PlayerMatchTable].
|
||||
/// Returns `true` if more than 0 rows were affected, otherwise `false`.
|
||||
Future<bool> removePlayerFromMatch({
|
||||
/// Retrieves a list of [Player]s associated with the given [matchId].
|
||||
/// Returns empty list if no players are found.
|
||||
Future<List<Player>> getPlayersOfMatch({required String matchId}) async {
|
||||
final result = await (select(
|
||||
playerMatchTable,
|
||||
)..where((p) => p.matchId.equals(matchId))).get();
|
||||
|
||||
if (result.isEmpty) return [];
|
||||
|
||||
final futures = result.map(
|
||||
(row) => db.playerDao.getPlayerById(playerId: row.playerId),
|
||||
);
|
||||
final players = await Future.wait(futures);
|
||||
return players;
|
||||
}
|
||||
|
||||
/// Retrieves a list of [Player]s associated with a specific team in a match.
|
||||
/// Returns empty list if no players are found for the team in the match.
|
||||
Future<List<Player>> getPlayersOfTeamInMatch({
|
||||
required String matchId,
|
||||
required String teamId,
|
||||
}) async {
|
||||
final result =
|
||||
await (select(playerMatchTable)
|
||||
..where((p) => p.matchId.equals(matchId))
|
||||
..where((p) => p.teamId.equals(teamId)))
|
||||
.get();
|
||||
|
||||
if (result.isEmpty) return [];
|
||||
|
||||
final futures = result.map(
|
||||
(row) => db.playerDao.getPlayerById(playerId: row.playerId),
|
||||
);
|
||||
final players = await Future.wait(futures);
|
||||
return players;
|
||||
}
|
||||
|
||||
/* Updated */
|
||||
|
||||
/// Updates the team for a player in a match.
|
||||
/// Returns `true` if the update was successful, otherwise `false`.
|
||||
Future<bool> updatePlayersTeam({
|
||||
required String matchId,
|
||||
required String playerId,
|
||||
required String? teamId,
|
||||
}) async {
|
||||
final query = delete(playerMatchTable)
|
||||
..where((pg) => pg.matchId.equals(matchId))
|
||||
..where((pg) => pg.playerId.equals(playerId));
|
||||
final rowsAffected = await query.go();
|
||||
final rowsAffected =
|
||||
await (update(playerMatchTable)..where(
|
||||
(p) => p.matchId.equals(matchId) & p.playerId.equals(playerId),
|
||||
))
|
||||
.write(PlayerMatchTableCompanion(teamId: Value(teamId)));
|
||||
return rowsAffected > 0;
|
||||
}
|
||||
|
||||
/// Updates the players associated with a match based on the provided
|
||||
/// [newPlayer] list. It adds new players and removes players that are no
|
||||
/// [player] list. It adds new players and removes players that are no
|
||||
/// longer associated with the match.
|
||||
Future<void> updatePlayersFromMatch({
|
||||
Future<bool> updateMatchPlayers({
|
||||
required String matchId,
|
||||
required List<Player> newPlayer,
|
||||
required List<Player> player,
|
||||
}) async {
|
||||
if (player.isEmpty) return false;
|
||||
|
||||
final currentPlayers = await getPlayersOfMatch(matchId: matchId);
|
||||
// Create sets of player IDs for easy comparison
|
||||
final currentPlayerIds = currentPlayers?.map((p) => p.id).toSet() ?? {};
|
||||
final newPlayerIdsSet = newPlayer.map((p) => p.id).toSet();
|
||||
final currentPlayerIds = currentPlayers.map((p) => p.id).toSet();
|
||||
final newPlayerIdsSet = player.map((p) => p.id).toSet();
|
||||
|
||||
// Are the current and new player identical?
|
||||
if (currentPlayerIds.containsAll(newPlayerIdsSet) &&
|
||||
newPlayerIdsSet.containsAll(currentPlayerIds)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Determine players to add and remove
|
||||
final playersToAdd = newPlayerIdsSet.difference(currentPlayerIds);
|
||||
@@ -147,22 +169,22 @@ class PlayerMatchDao extends DatabaseAccessor<AppDatabase>
|
||||
);
|
||||
}
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
/// Retrieves all players in a specific team for a match.
|
||||
Future<List<Player>> getPlayersInTeam({
|
||||
/* Delete */
|
||||
|
||||
/// Removes the association of a player with a match by deleting the record
|
||||
/// from the [PlayerMatchTable].
|
||||
/// Returns `true` if more than 0 rows were affected, otherwise `false`.
|
||||
Future<bool> removePlayerFromMatch({
|
||||
required String matchId,
|
||||
required String teamId,
|
||||
required String playerId,
|
||||
}) async {
|
||||
final result = await (select(
|
||||
playerMatchTable,
|
||||
)..where((p) => p.matchId.equals(matchId) & p.teamId.equals(teamId))).get();
|
||||
|
||||
if (result.isEmpty) return [];
|
||||
|
||||
final futures = result.map(
|
||||
(row) => db.playerDao.getPlayerById(playerId: row.playerId),
|
||||
);
|
||||
return Future.wait(futures);
|
||||
final query = delete(playerMatchTable)
|
||||
..where((pg) => pg.matchId.equals(matchId))
|
||||
..where((pg) => pg.playerId.equals(playerId));
|
||||
final rowsAffected = await query.go();
|
||||
return rowsAffected > 0;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,6 +13,8 @@ class ScoreEntryDao extends DatabaseAccessor<AppDatabase>
|
||||
with _$ScoreEntryDaoMixin {
|
||||
ScoreEntryDao(super.db);
|
||||
|
||||
/* Create */
|
||||
|
||||
/// Adds a score entry to the database.
|
||||
Future<void> addScore({
|
||||
required String playerId,
|
||||
@@ -58,6 +60,8 @@ class ScoreEntryDao extends DatabaseAccessor<AppDatabase>
|
||||
});
|
||||
}
|
||||
|
||||
/* Read */
|
||||
|
||||
/// Retrieves the score for a specific round.
|
||||
Future<ScoreEntry?> getScore({
|
||||
required String playerId,
|
||||
@@ -126,28 +130,58 @@ class ScoreEntryDao extends DatabaseAccessor<AppDatabase>
|
||||
);
|
||||
}
|
||||
|
||||
/// Gets the highest (latest) round number for a match.
|
||||
/// Returns `null` if there are no scores for the match.
|
||||
Future<int?> getLatestRoundNumber({required String matchId}) async {
|
||||
final query = selectOnly(scoreEntryTable)
|
||||
..where(scoreEntryTable.matchId.equals(matchId))
|
||||
..addColumns([scoreEntryTable.roundNumber.max()]);
|
||||
final result = await query.getSingle();
|
||||
return result.read(scoreEntryTable.roundNumber.max());
|
||||
}
|
||||
|
||||
/// Aggregates the total score for a player in a match by summing all their
|
||||
/// score entry changes. Returns `0` if there are no scores for the player
|
||||
/// in the match.
|
||||
Future<int> getTotalScoreForPlayer({
|
||||
required String playerId,
|
||||
required String matchId,
|
||||
}) async {
|
||||
final scores = await getAllPlayerScoresInMatch(
|
||||
playerId: playerId,
|
||||
matchId: matchId,
|
||||
);
|
||||
if (scores.isEmpty) return 0;
|
||||
// Return the sum of all score changes
|
||||
return scores.fold<int>(0, (sum, element) => sum + element.change);
|
||||
}
|
||||
|
||||
/* Update */
|
||||
|
||||
/// Updates a score entry.
|
||||
Future<bool> updateScore({
|
||||
required String playerId,
|
||||
required String matchId,
|
||||
required ScoreEntry newEntry,
|
||||
required ScoreEntry entry,
|
||||
}) async {
|
||||
final rowsAffected =
|
||||
await (update(scoreEntryTable)..where(
|
||||
(s) =>
|
||||
s.playerId.equals(playerId) &
|
||||
s.matchId.equals(matchId) &
|
||||
s.roundNumber.equals(newEntry.roundNumber),
|
||||
s.roundNumber.equals(entry.roundNumber),
|
||||
))
|
||||
.write(
|
||||
ScoreEntryTableCompanion(
|
||||
score: Value(newEntry.score),
|
||||
change: Value(newEntry.change),
|
||||
score: Value(entry.score),
|
||||
change: Value(entry.change),
|
||||
),
|
||||
);
|
||||
return rowsAffected > 0;
|
||||
}
|
||||
|
||||
/* Delete */
|
||||
|
||||
/// Deletes a score entry.
|
||||
Future<bool> deleteScore({
|
||||
required String playerId,
|
||||
@@ -182,31 +216,7 @@ class ScoreEntryDao extends DatabaseAccessor<AppDatabase>
|
||||
return rowsAffected > 0;
|
||||
}
|
||||
|
||||
/// Gets the highest (latest) round number for a match.
|
||||
/// Returns `null` if there are no scores for the match.
|
||||
Future<int?> getLatestRoundNumber({required String matchId}) async {
|
||||
final query = selectOnly(scoreEntryTable)
|
||||
..where(scoreEntryTable.matchId.equals(matchId))
|
||||
..addColumns([scoreEntryTable.roundNumber.max()]);
|
||||
final result = await query.getSingle();
|
||||
return result.read(scoreEntryTable.roundNumber.max());
|
||||
}
|
||||
|
||||
/// Aggregates the total score for a player in a match by summing all their
|
||||
/// score entry changes. Returns `0` if there are no scores for the player
|
||||
/// in the match.
|
||||
Future<int> getTotalScoreForPlayer({
|
||||
required String playerId,
|
||||
required String matchId,
|
||||
}) async {
|
||||
final scores = await getAllPlayerScoresInMatch(
|
||||
playerId: playerId,
|
||||
matchId: matchId,
|
||||
);
|
||||
if (scores.isEmpty) return 0;
|
||||
// Return the sum of all score changes
|
||||
return scores.fold<int>(0, (sum, element) => sum + element.change);
|
||||
}
|
||||
/* Winner handling */
|
||||
|
||||
Future<bool> hasWinner({required String matchId}) async {
|
||||
return await getWinner(matchId: matchId) != null;
|
||||
@@ -218,7 +228,7 @@ class ScoreEntryDao extends DatabaseAccessor<AppDatabase>
|
||||
required String playerId,
|
||||
}) async {
|
||||
// Clear previous winner if exists
|
||||
deleteAllScoresForMatch(matchId: matchId);
|
||||
await deleteAllScoresForMatch(matchId: matchId);
|
||||
|
||||
// Set the winner's score to 1
|
||||
final rowsAffected = await into(scoreEntryTable).insert(
|
||||
@@ -235,7 +245,7 @@ class ScoreEntryDao extends DatabaseAccessor<AppDatabase>
|
||||
return rowsAffected > 0;
|
||||
}
|
||||
|
||||
// Retrieves the winner of a match by looking for a score entry where score
|
||||
/// Retrieves the winner of a match by looking for a score entry where score
|
||||
/// is 1. Returns `null` if no player found, else the first with the score.
|
||||
Future<Player?> getWinner({required String matchId}) async {
|
||||
final query =
|
||||
@@ -266,21 +276,52 @@ class ScoreEntryDao extends DatabaseAccessor<AppDatabase>
|
||||
/// Returns `true` if the winner was removed, `false` if there are multiple
|
||||
/// scores or if the winner cannot be removed.
|
||||
Future<bool> removeWinner({required String matchId}) async {
|
||||
final scores = await getAllMatchScores(matchId: matchId);
|
||||
|
||||
if (scores.length > 1) {
|
||||
return false;
|
||||
} else {
|
||||
return await deleteAllScoresForMatch(matchId: matchId);
|
||||
}
|
||||
return await deleteAllScoresForMatch(matchId: matchId);
|
||||
}
|
||||
|
||||
Future<bool> hasLooser({required String matchId}) async {
|
||||
return await getLooser(matchId: matchId) != null;
|
||||
/* multiple winners handling */
|
||||
|
||||
/// Sets the winners for a match.
|
||||
///
|
||||
/// Returns `true` if more than 0 rows were affected
|
||||
Future<bool> setWinners({
|
||||
required List<Player> winners,
|
||||
required String matchId,
|
||||
}) async {
|
||||
// Clear previous winners if exists
|
||||
await deleteAllScoresForMatch(matchId: matchId);
|
||||
|
||||
if (winners.isEmpty) return false;
|
||||
|
||||
await batch((batch) {
|
||||
batch.insertAll(
|
||||
scoreEntryTable,
|
||||
winners
|
||||
.map(
|
||||
(player) => ScoreEntryTableCompanion.insert(
|
||||
playerId: player.id,
|
||||
matchId: matchId,
|
||||
roundNumber: 0,
|
||||
score: 1,
|
||||
change: 0,
|
||||
),
|
||||
)
|
||||
.toList(),
|
||||
mode: InsertMode.insertOrReplace,
|
||||
);
|
||||
});
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/* Loser handling */
|
||||
|
||||
Future<bool> hasLoser({required String matchId}) async {
|
||||
return await getLoser(matchId: matchId) != null;
|
||||
}
|
||||
|
||||
// Setting the looser for a game and clearing previous looser if exists.
|
||||
Future<bool> setLooser({
|
||||
Future<bool> setLoser({
|
||||
required String matchId,
|
||||
required String playerId,
|
||||
}) async {
|
||||
@@ -304,7 +345,7 @@ class ScoreEntryDao extends DatabaseAccessor<AppDatabase>
|
||||
|
||||
/// Retrieves the looser of a match by looking for a score entry where score
|
||||
/// is 0. Returns `null` if no player found, else the first with the score.
|
||||
Future<Player?> getLooser({required String matchId}) async {
|
||||
Future<Player?> getLoser({required String matchId}) async {
|
||||
final query =
|
||||
select(scoreEntryTable).join([
|
||||
innerJoin(
|
||||
@@ -332,7 +373,7 @@ class ScoreEntryDao extends DatabaseAccessor<AppDatabase>
|
||||
///
|
||||
/// Returns `true` if the looser was removed, `false` if there are multiple
|
||||
/// scores or if the looser cannot be removed.
|
||||
Future<bool> removeLooser({required String matchId}) async {
|
||||
Future<bool> removeLoser({required String matchId}) async {
|
||||
final scores = await getAllMatchScores(matchId: matchId);
|
||||
|
||||
if (scores.length > 1) {
|
||||
@@ -341,4 +382,21 @@ class ScoreEntryDao extends DatabaseAccessor<AppDatabase>
|
||||
return await deleteAllScoresForMatch(matchId: matchId);
|
||||
}
|
||||
}
|
||||
|
||||
/* placement handling */
|
||||
|
||||
/// Sets the placement for each player in a match.
|
||||
/// The highest score is assigned to the first player, the second highest to the second player, and so on.
|
||||
Future<void> setPlacements({
|
||||
required String matchId,
|
||||
required List<Player> players,
|
||||
}) async {
|
||||
for (int i = 0; i < players.length; i++) {
|
||||
await db.scoreEntryDao.addScore(
|
||||
matchId: matchId,
|
||||
playerId: players[i].id,
|
||||
entry: ScoreEntry(roundNumber: 0, score: players.length - i, change: 0),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,17 +1,105 @@
|
||||
import 'package:drift/drift.dart';
|
||||
import 'package:tallee/data/db/database.dart';
|
||||
import 'package:tallee/data/db/tables/player_match_table.dart';
|
||||
import 'package:tallee/data/db/tables/team_table.dart';
|
||||
import 'package:tallee/data/models/player.dart';
|
||||
import 'package:tallee/data/models/team.dart';
|
||||
|
||||
part 'team_dao.g.dart';
|
||||
|
||||
@DriftAccessor(tables: [TeamTable])
|
||||
@DriftAccessor(tables: [TeamTable, PlayerMatchTable])
|
||||
class TeamDao extends DatabaseAccessor<AppDatabase> with _$TeamDaoMixin {
|
||||
TeamDao(super.db);
|
||||
|
||||
/* Create */
|
||||
|
||||
/// Adds a new [team] to the database.
|
||||
/// Returns `true` if the team was added, `false` otherwise.
|
||||
Future<bool> addTeam({required Team team, required String matchId}) async {
|
||||
if (await teamExists(teamId: team.id)) return false;
|
||||
await into(teamTable).insert(
|
||||
TeamTableCompanion.insert(
|
||||
id: team.id,
|
||||
name: team.name,
|
||||
createdAt: team.createdAt,
|
||||
),
|
||||
mode: InsertMode.insertOrReplace,
|
||||
);
|
||||
await db.batch((batch) async {
|
||||
for (final player in team.members) {
|
||||
await into(playerMatchTable).insert(
|
||||
PlayerMatchTableCompanion.insert(
|
||||
playerId: player.id,
|
||||
matchId: matchId,
|
||||
teamId: Value(team.id),
|
||||
),
|
||||
mode: InsertMode.insertOrReplace,
|
||||
);
|
||||
}
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
/// Adds multiple [teams] to the database in a batch operation.
|
||||
Future<bool> addTeamsAsList({
|
||||
required List<Team> teams,
|
||||
required String matchId,
|
||||
}) async {
|
||||
if (teams.isEmpty) return false;
|
||||
|
||||
await db.batch(
|
||||
(b) => b.insertAll(
|
||||
teamTable,
|
||||
teams
|
||||
.map(
|
||||
(team) => TeamTableCompanion.insert(
|
||||
id: team.id,
|
||||
name: team.name,
|
||||
createdAt: team.createdAt,
|
||||
),
|
||||
)
|
||||
.toList(),
|
||||
mode: InsertMode.insertOrIgnore,
|
||||
),
|
||||
);
|
||||
|
||||
for (final team in teams) {
|
||||
await db.batch((batch) async {
|
||||
for (final player in team.members) {
|
||||
await into(db.playerMatchTable).insert(
|
||||
PlayerMatchTableCompanion.insert(
|
||||
playerId: player.id,
|
||||
matchId: matchId,
|
||||
teamId: Value(team.id),
|
||||
),
|
||||
mode: InsertMode.insertOrReplace,
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/* Read */
|
||||
|
||||
/// Retrieves the total count of teams in the database.
|
||||
Future<int> getTeamCount() async {
|
||||
final count =
|
||||
await (selectOnly(teamTable)..addColumns([teamTable.id.count()]))
|
||||
.map((row) => row.read(teamTable.id.count()))
|
||||
.getSingle();
|
||||
return count ?? 0;
|
||||
}
|
||||
|
||||
/// Checks if a team with the given [teamId] exists in the database.
|
||||
/// Returns `true` if the team exists, `false` otherwise.
|
||||
Future<bool> teamExists({required String teamId}) async {
|
||||
final query = select(teamTable)..where((t) => t.id.equals(teamId));
|
||||
final result = await query.getSingleOrNull();
|
||||
return result != null;
|
||||
}
|
||||
|
||||
/// Retrieves all teams from the database.
|
||||
/// Note: This returns teams without their members. Use getTeamById for full team data.
|
||||
Future<List<Team>> getAllTeams() async {
|
||||
final query = select(teamTable);
|
||||
final result = await query.get();
|
||||
@@ -41,8 +129,7 @@ class TeamDao extends DatabaseAccessor<AppDatabase> with _$TeamDaoMixin {
|
||||
);
|
||||
}
|
||||
|
||||
/// Helper method to get team members from player_match_table.
|
||||
/// This assumes team members are tracked via the player_match_table.
|
||||
/// Helper method to get team members from PlayerMatchTable.
|
||||
Future<List<Player>> _getTeamMembers({required String teamId}) async {
|
||||
// Get all player_match entries with this teamId
|
||||
final playerMatchQuery = select(db.playerMatchTable)
|
||||
@@ -61,44 +148,28 @@ class TeamDao extends DatabaseAccessor<AppDatabase> with _$TeamDaoMixin {
|
||||
return players;
|
||||
}
|
||||
|
||||
/// Adds a new [team] to the database.
|
||||
/// Returns `true` if the team was added, `false` otherwise.
|
||||
Future<bool> addTeam({required Team team}) async {
|
||||
if (!await teamExists(teamId: team.id)) {
|
||||
await into(teamTable).insert(
|
||||
TeamTableCompanion.insert(
|
||||
id: team.id,
|
||||
name: team.name,
|
||||
createdAt: team.createdAt,
|
||||
),
|
||||
mode: InsertMode.insertOrReplace,
|
||||
);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
/* Update */
|
||||
|
||||
/// Updates the name of the team with the given [teamId].
|
||||
Future<bool> updateTeamName({
|
||||
required String teamId,
|
||||
required String name,
|
||||
}) async {
|
||||
final rowsAffected =
|
||||
await (update(teamTable)..where((t) => t.id.equals(teamId))).write(
|
||||
TeamTableCompanion(name: Value(name)),
|
||||
);
|
||||
return rowsAffected > 0;
|
||||
}
|
||||
|
||||
/// Adds multiple [teams] to the database in a batch operation.
|
||||
Future<bool> addTeamsAsList({required List<Team> teams}) async {
|
||||
if (teams.isEmpty) return false;
|
||||
/* Delete */
|
||||
|
||||
await db.batch(
|
||||
(b) => b.insertAll(
|
||||
teamTable,
|
||||
teams
|
||||
.map(
|
||||
(team) => TeamTableCompanion.insert(
|
||||
id: team.id,
|
||||
name: team.name,
|
||||
createdAt: team.createdAt,
|
||||
),
|
||||
)
|
||||
.toList(),
|
||||
mode: InsertMode.insertOrIgnore,
|
||||
),
|
||||
);
|
||||
|
||||
return true;
|
||||
/// Deletes all teams from the database.
|
||||
/// Returns `true` if more than 0 rows were affected, otherwise `false`.
|
||||
Future<bool> deleteAllTeams() async {
|
||||
final query = delete(teamTable);
|
||||
final rowsAffected = await query.go();
|
||||
return rowsAffected > 0;
|
||||
}
|
||||
|
||||
/// Deletes the team with the given [teamId] from the database.
|
||||
@@ -108,39 +179,4 @@ class TeamDao extends DatabaseAccessor<AppDatabase> with _$TeamDaoMixin {
|
||||
final rowsAffected = await query.go();
|
||||
return rowsAffected > 0;
|
||||
}
|
||||
|
||||
/// Checks if a team with the given [teamId] exists in the database.
|
||||
/// Returns `true` if the team exists, `false` otherwise.
|
||||
Future<bool> teamExists({required String teamId}) async {
|
||||
final query = select(teamTable)..where((t) => t.id.equals(teamId));
|
||||
final result = await query.getSingleOrNull();
|
||||
return result != null;
|
||||
}
|
||||
|
||||
/// Updates the name of the team with the given [teamId].
|
||||
Future<void> updateTeamName({
|
||||
required String teamId,
|
||||
required String newName,
|
||||
}) async {
|
||||
await (update(teamTable)..where((t) => t.id.equals(teamId))).write(
|
||||
TeamTableCompanion(name: Value(newName)),
|
||||
);
|
||||
}
|
||||
|
||||
/// Retrieves the total count of teams in the database.
|
||||
Future<int> getTeamCount() async {
|
||||
final count =
|
||||
await (selectOnly(teamTable)..addColumns([teamTable.id.count()]))
|
||||
.map((row) => row.read(teamTable.id.count()))
|
||||
.getSingle();
|
||||
return count ?? 0;
|
||||
}
|
||||
|
||||
/// Deletes all teams from the database.
|
||||
/// Returns `true` if more than 0 rows were affected, otherwise `false`.
|
||||
Future<bool> deleteAllTeams() async {
|
||||
final query = delete(teamTable);
|
||||
final rowsAffected = await query.go();
|
||||
return rowsAffected > 0;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,6 +5,12 @@ part of 'team_dao.dart';
|
||||
// ignore_for_file: type=lint
|
||||
mixin _$TeamDaoMixin on DatabaseAccessor<AppDatabase> {
|
||||
$TeamTableTable get teamTable => attachedDatabase.teamTable;
|
||||
$PlayerTableTable get playerTable => attachedDatabase.playerTable;
|
||||
$GameTableTable get gameTable => attachedDatabase.gameTable;
|
||||
$GroupTableTable get groupTable => attachedDatabase.groupTable;
|
||||
$MatchTableTable get matchTable => attachedDatabase.matchTable;
|
||||
$PlayerMatchTableTable get playerMatchTable =>
|
||||
attachedDatabase.playerMatchTable;
|
||||
TeamDaoManager get managers => TeamDaoManager(this);
|
||||
}
|
||||
|
||||
@@ -13,4 +19,17 @@ class TeamDaoManager {
|
||||
TeamDaoManager(this._db);
|
||||
$$TeamTableTableTableManager get teamTable =>
|
||||
$$TeamTableTableTableManager(_db.attachedDatabase, _db.teamTable);
|
||||
$$PlayerTableTableTableManager get playerTable =>
|
||||
$$PlayerTableTableTableManager(_db.attachedDatabase, _db.playerTable);
|
||||
$$GameTableTableTableManager get gameTable =>
|
||||
$$GameTableTableTableManager(_db.attachedDatabase, _db.gameTable);
|
||||
$$GroupTableTableTableManager get groupTable =>
|
||||
$$GroupTableTableTableManager(_db.attachedDatabase, _db.groupTable);
|
||||
$$MatchTableTableTableManager get matchTable =>
|
||||
$$MatchTableTableTableManager(_db.attachedDatabase, _db.matchTable);
|
||||
$$PlayerMatchTableTableTableManager get playerMatchTable =>
|
||||
$$PlayerMatchTableTableTableManager(
|
||||
_db.attachedDatabase,
|
||||
_db.playerMatchTable,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1190,9 +1190,9 @@ class $MatchTableTable extends MatchTable
|
||||
late final GeneratedColumn<String> notes = GeneratedColumn<String>(
|
||||
'notes',
|
||||
aliasedName,
|
||||
true,
|
||||
false,
|
||||
type: DriftSqlType.string,
|
||||
requiredDuringInsert: false,
|
||||
requiredDuringInsert: true,
|
||||
);
|
||||
static const VerificationMeta _createdAtMeta = const VerificationMeta(
|
||||
'createdAt',
|
||||
@@ -1270,6 +1270,8 @@ class $MatchTableTable extends MatchTable
|
||||
_notesMeta,
|
||||
notes.isAcceptableOrUnknown(data['notes']!, _notesMeta),
|
||||
);
|
||||
} else if (isInserting) {
|
||||
context.missing(_notesMeta);
|
||||
}
|
||||
if (data.containsKey('created_at')) {
|
||||
context.handle(
|
||||
@@ -1313,7 +1315,7 @@ class $MatchTableTable extends MatchTable
|
||||
notes: attachedDatabase.typeMapping.read(
|
||||
DriftSqlType.string,
|
||||
data['${effectivePrefix}notes'],
|
||||
),
|
||||
)!,
|
||||
createdAt: attachedDatabase.typeMapping.read(
|
||||
DriftSqlType.dateTime,
|
||||
data['${effectivePrefix}created_at'],
|
||||
@@ -1336,7 +1338,7 @@ class MatchTableData extends DataClass implements Insertable<MatchTableData> {
|
||||
final String gameId;
|
||||
final String? groupId;
|
||||
final String name;
|
||||
final String? notes;
|
||||
final String notes;
|
||||
final DateTime createdAt;
|
||||
final DateTime? endedAt;
|
||||
const MatchTableData({
|
||||
@@ -1344,7 +1346,7 @@ class MatchTableData extends DataClass implements Insertable<MatchTableData> {
|
||||
required this.gameId,
|
||||
this.groupId,
|
||||
required this.name,
|
||||
this.notes,
|
||||
required this.notes,
|
||||
required this.createdAt,
|
||||
this.endedAt,
|
||||
});
|
||||
@@ -1357,9 +1359,7 @@ class MatchTableData extends DataClass implements Insertable<MatchTableData> {
|
||||
map['group_id'] = Variable<String>(groupId);
|
||||
}
|
||||
map['name'] = Variable<String>(name);
|
||||
if (!nullToAbsent || notes != null) {
|
||||
map['notes'] = Variable<String>(notes);
|
||||
}
|
||||
map['notes'] = Variable<String>(notes);
|
||||
map['created_at'] = Variable<DateTime>(createdAt);
|
||||
if (!nullToAbsent || endedAt != null) {
|
||||
map['ended_at'] = Variable<DateTime>(endedAt);
|
||||
@@ -1375,9 +1375,7 @@ class MatchTableData extends DataClass implements Insertable<MatchTableData> {
|
||||
? const Value.absent()
|
||||
: Value(groupId),
|
||||
name: Value(name),
|
||||
notes: notes == null && nullToAbsent
|
||||
? const Value.absent()
|
||||
: Value(notes),
|
||||
notes: Value(notes),
|
||||
createdAt: Value(createdAt),
|
||||
endedAt: endedAt == null && nullToAbsent
|
||||
? const Value.absent()
|
||||
@@ -1395,7 +1393,7 @@ class MatchTableData extends DataClass implements Insertable<MatchTableData> {
|
||||
gameId: serializer.fromJson<String>(json['gameId']),
|
||||
groupId: serializer.fromJson<String?>(json['groupId']),
|
||||
name: serializer.fromJson<String>(json['name']),
|
||||
notes: serializer.fromJson<String?>(json['notes']),
|
||||
notes: serializer.fromJson<String>(json['notes']),
|
||||
createdAt: serializer.fromJson<DateTime>(json['createdAt']),
|
||||
endedAt: serializer.fromJson<DateTime?>(json['endedAt']),
|
||||
);
|
||||
@@ -1408,7 +1406,7 @@ class MatchTableData extends DataClass implements Insertable<MatchTableData> {
|
||||
'gameId': serializer.toJson<String>(gameId),
|
||||
'groupId': serializer.toJson<String?>(groupId),
|
||||
'name': serializer.toJson<String>(name),
|
||||
'notes': serializer.toJson<String?>(notes),
|
||||
'notes': serializer.toJson<String>(notes),
|
||||
'createdAt': serializer.toJson<DateTime>(createdAt),
|
||||
'endedAt': serializer.toJson<DateTime?>(endedAt),
|
||||
};
|
||||
@@ -1419,7 +1417,7 @@ class MatchTableData extends DataClass implements Insertable<MatchTableData> {
|
||||
String? gameId,
|
||||
Value<String?> groupId = const Value.absent(),
|
||||
String? name,
|
||||
Value<String?> notes = const Value.absent(),
|
||||
String? notes,
|
||||
DateTime? createdAt,
|
||||
Value<DateTime?> endedAt = const Value.absent(),
|
||||
}) => MatchTableData(
|
||||
@@ -1427,7 +1425,7 @@ class MatchTableData extends DataClass implements Insertable<MatchTableData> {
|
||||
gameId: gameId ?? this.gameId,
|
||||
groupId: groupId.present ? groupId.value : this.groupId,
|
||||
name: name ?? this.name,
|
||||
notes: notes.present ? notes.value : this.notes,
|
||||
notes: notes ?? this.notes,
|
||||
createdAt: createdAt ?? this.createdAt,
|
||||
endedAt: endedAt.present ? endedAt.value : this.endedAt,
|
||||
);
|
||||
@@ -1478,7 +1476,7 @@ class MatchTableCompanion extends UpdateCompanion<MatchTableData> {
|
||||
final Value<String> gameId;
|
||||
final Value<String?> groupId;
|
||||
final Value<String> name;
|
||||
final Value<String?> notes;
|
||||
final Value<String> notes;
|
||||
final Value<DateTime> createdAt;
|
||||
final Value<DateTime?> endedAt;
|
||||
final Value<int> rowid;
|
||||
@@ -1497,13 +1495,14 @@ class MatchTableCompanion extends UpdateCompanion<MatchTableData> {
|
||||
required String gameId,
|
||||
this.groupId = const Value.absent(),
|
||||
required String name,
|
||||
this.notes = const Value.absent(),
|
||||
required String notes,
|
||||
required DateTime createdAt,
|
||||
this.endedAt = const Value.absent(),
|
||||
this.rowid = const Value.absent(),
|
||||
}) : id = Value(id),
|
||||
gameId = Value(gameId),
|
||||
name = Value(name),
|
||||
notes = Value(notes),
|
||||
createdAt = Value(createdAt);
|
||||
static Insertable<MatchTableData> custom({
|
||||
Expression<String>? id,
|
||||
@@ -1532,7 +1531,7 @@ class MatchTableCompanion extends UpdateCompanion<MatchTableData> {
|
||||
Value<String>? gameId,
|
||||
Value<String?>? groupId,
|
||||
Value<String>? name,
|
||||
Value<String?>? notes,
|
||||
Value<String>? notes,
|
||||
Value<DateTime>? createdAt,
|
||||
Value<DateTime?>? endedAt,
|
||||
Value<int>? rowid,
|
||||
@@ -2122,7 +2121,7 @@ class $PlayerMatchTableTable extends PlayerMatchTable
|
||||
type: DriftSqlType.string,
|
||||
requiredDuringInsert: false,
|
||||
defaultConstraints: GeneratedColumn.constraintIsAlways(
|
||||
'REFERENCES team_table (id)',
|
||||
'REFERENCES team_table (id) ON DELETE SET NULL',
|
||||
),
|
||||
);
|
||||
@override
|
||||
@@ -2820,6 +2819,13 @@ abstract class _$AppDatabase extends GeneratedDatabase {
|
||||
),
|
||||
result: [TableUpdate('player_match_table', kind: UpdateKind.delete)],
|
||||
),
|
||||
WritePropagation(
|
||||
on: TableUpdateQuery.onTableName(
|
||||
'team_table',
|
||||
limitUpdateKind: UpdateKind.delete,
|
||||
),
|
||||
result: [TableUpdate('player_match_table', kind: UpdateKind.update)],
|
||||
),
|
||||
WritePropagation(
|
||||
on: TableUpdateQuery.onTableName(
|
||||
'player_table',
|
||||
@@ -4086,7 +4092,7 @@ typedef $$MatchTableTableCreateCompanionBuilder =
|
||||
required String gameId,
|
||||
Value<String?> groupId,
|
||||
required String name,
|
||||
Value<String?> notes,
|
||||
required String notes,
|
||||
required DateTime createdAt,
|
||||
Value<DateTime?> endedAt,
|
||||
Value<int> rowid,
|
||||
@@ -4097,7 +4103,7 @@ typedef $$MatchTableTableUpdateCompanionBuilder =
|
||||
Value<String> gameId,
|
||||
Value<String?> groupId,
|
||||
Value<String> name,
|
||||
Value<String?> notes,
|
||||
Value<String> notes,
|
||||
Value<DateTime> createdAt,
|
||||
Value<DateTime?> endedAt,
|
||||
Value<int> rowid,
|
||||
@@ -4560,7 +4566,7 @@ class $$MatchTableTableTableManager
|
||||
Value<String> gameId = const Value.absent(),
|
||||
Value<String?> groupId = const Value.absent(),
|
||||
Value<String> name = const Value.absent(),
|
||||
Value<String?> notes = const Value.absent(),
|
||||
Value<String> notes = const Value.absent(),
|
||||
Value<DateTime> createdAt = const Value.absent(),
|
||||
Value<DateTime?> endedAt = const Value.absent(),
|
||||
Value<int> rowid = const Value.absent(),
|
||||
@@ -4580,7 +4586,7 @@ class $$MatchTableTableTableManager
|
||||
required String gameId,
|
||||
Value<String?> groupId = const Value.absent(),
|
||||
required String name,
|
||||
Value<String?> notes = const Value.absent(),
|
||||
required String notes,
|
||||
required DateTime createdAt,
|
||||
Value<DateTime?> endedAt = const Value.absent(),
|
||||
Value<int> rowid = const Value.absent(),
|
||||
|
||||
@@ -12,7 +12,7 @@ class MatchTable extends Table {
|
||||
.references(GroupTable, #id, onDelete: KeyAction.setNull)
|
||||
.nullable()();
|
||||
TextColumn get name => text()();
|
||||
TextColumn get notes => text().nullable()();
|
||||
TextColumn get notes => text()();
|
||||
DateTimeColumn get createdAt => dateTime()();
|
||||
DateTimeColumn get endedAt => dateTime().nullable()();
|
||||
BoolColumn get deleted => boolean().withDefault(const Constant(false))();
|
||||
|
||||
@@ -8,8 +8,9 @@ class PlayerMatchTable extends Table {
|
||||
text().references(PlayerTable, #id, onDelete: KeyAction.cascade)();
|
||||
TextColumn get matchId =>
|
||||
text().references(MatchTable, #id, onDelete: KeyAction.cascade)();
|
||||
TextColumn get teamId => text().references(TeamTable, #id).nullable()();
|
||||
BoolColumn get deleted => boolean().withDefault(const Constant(false))();
|
||||
TextColumn get teamId => text()
|
||||
.references(TeamTable, #id, onDelete: KeyAction.setNull)
|
||||
.nullable()();
|
||||
|
||||
@override
|
||||
Set<Column<Object>> get primaryKey => {playerId, matchId};
|
||||
|
||||
@@ -10,27 +10,60 @@ class Game {
|
||||
final String description;
|
||||
final GameColor color;
|
||||
final String icon;
|
||||
final bool deleted;
|
||||
|
||||
Game({
|
||||
String? id,
|
||||
DateTime? createdAt,
|
||||
required this.name,
|
||||
required this.ruleset,
|
||||
String? description,
|
||||
required this.color,
|
||||
required this.icon,
|
||||
this.deleted = false,
|
||||
this.color = GameColor.orange,
|
||||
this.description = '',
|
||||
this.icon = '',
|
||||
String? id,
|
||||
DateTime? createdAt,
|
||||
}) : id = id ?? const Uuid().v4(),
|
||||
createdAt = createdAt ?? clock.now(),
|
||||
description = description ?? '';
|
||||
createdAt = createdAt ?? clock.now();
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return 'Game{id: $id, name: $name, ruleset: $ruleset, description: $description, color: $color, icon: $icon}';
|
||||
}
|
||||
|
||||
/// Creates a Game instance from a JSON object.
|
||||
Game copyWith({
|
||||
String? id,
|
||||
DateTime? createdAt,
|
||||
String? name,
|
||||
Ruleset? ruleset,
|
||||
String? description,
|
||||
GameColor? color,
|
||||
String? icon,
|
||||
}) {
|
||||
return Game(
|
||||
id: id ?? this.id,
|
||||
createdAt: createdAt ?? this.createdAt,
|
||||
name: name ?? this.name,
|
||||
ruleset: ruleset ?? this.ruleset,
|
||||
description: description ?? this.description,
|
||||
color: color ?? this.color,
|
||||
icon: icon ?? this.icon,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) =>
|
||||
identical(this, other) ||
|
||||
other is Game &&
|
||||
runtimeType == other.runtimeType &&
|
||||
id == other.id &&
|
||||
createdAt == other.createdAt &&
|
||||
name == other.name &&
|
||||
ruleset == other.ruleset &&
|
||||
description == other.description &&
|
||||
color == other.color &&
|
||||
icon == other.icon;
|
||||
|
||||
@override
|
||||
int get hashCode =>
|
||||
Object.hash(id, createdAt, name, ruleset, description, color, icon);
|
||||
|
||||
Game.fromJson(Map<String, dynamic> json)
|
||||
: id = json['id'],
|
||||
createdAt = DateTime.parse(json['createdAt']),
|
||||
@@ -41,10 +74,8 @@ class Game {
|
||||
),
|
||||
description = json['description'],
|
||||
color = GameColor.values.firstWhere((e) => e.name == json['color']),
|
||||
icon = json['icon'],
|
||||
deleted = json['deleted'] ?? false;
|
||||
icon = json['icon'];
|
||||
|
||||
/// Converts the Game instance to a JSON object.
|
||||
Map<String, dynamic> toJson() => {
|
||||
'id': id,
|
||||
'createdAt': createdAt.toIso8601String(),
|
||||
@@ -53,6 +84,5 @@ class Game {
|
||||
'description': description,
|
||||
'color': color.name,
|
||||
'icon': icon,
|
||||
'deleted': deleted,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import 'package:clock/clock.dart';
|
||||
import 'package:collection/collection.dart';
|
||||
import 'package:tallee/data/models/player.dart';
|
||||
import 'package:uuid/uuid.dart';
|
||||
|
||||
@@ -26,6 +27,42 @@ class Group {
|
||||
return 'Group{id: $id, name: $name, description: $description, members: $members}';
|
||||
}
|
||||
|
||||
Group copyWith({
|
||||
String? id,
|
||||
String? name,
|
||||
String? description,
|
||||
DateTime? createdAt,
|
||||
List<Player>? members,
|
||||
}) {
|
||||
return Group(
|
||||
id: id ?? this.id,
|
||||
name: name ?? this.name,
|
||||
description: description ?? this.description,
|
||||
createdAt: createdAt ?? this.createdAt,
|
||||
members: members ?? this.members,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) =>
|
||||
identical(this, other) ||
|
||||
other is Group &&
|
||||
runtimeType == other.runtimeType &&
|
||||
id == other.id &&
|
||||
name == other.name &&
|
||||
description == other.description &&
|
||||
createdAt == other.createdAt &&
|
||||
const DeepCollectionEquality().equals(members, other.members);
|
||||
|
||||
@override
|
||||
int get hashCode => Object.hash(
|
||||
id,
|
||||
name,
|
||||
description,
|
||||
createdAt,
|
||||
const DeepCollectionEquality().hash(members),
|
||||
);
|
||||
|
||||
/// Creates a Group instance from a JSON object where the related [Player]
|
||||
/// objects are represented by their IDs.
|
||||
Group.fromJson(Map<String, dynamic> json)
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import 'package:clock/clock.dart';
|
||||
import 'package:collection/collection.dart';
|
||||
import 'package:tallee/core/enums.dart';
|
||||
import 'package:tallee/data/models/game.dart';
|
||||
import 'package:tallee/data/models/group.dart';
|
||||
import 'package:tallee/data/models/player.dart';
|
||||
import 'package:tallee/data/models/score_entry.dart';
|
||||
import 'package:tallee/data/models/team.dart';
|
||||
import 'package:uuid/uuid.dart';
|
||||
|
||||
class Match {
|
||||
@@ -14,6 +16,7 @@ class Match {
|
||||
final Game game;
|
||||
final Group? group;
|
||||
final List<Player> players;
|
||||
final List<Team>? teams;
|
||||
final String notes;
|
||||
Map<String, ScoreEntry?> scores;
|
||||
final bool deleted;
|
||||
@@ -24,6 +27,7 @@ class Match {
|
||||
required this.players,
|
||||
this.endedAt,
|
||||
this.group,
|
||||
this.teams,
|
||||
this.notes = '',
|
||||
String? id,
|
||||
DateTime? createdAt,
|
||||
@@ -38,9 +42,62 @@ class Match {
|
||||
return 'Match{id: $id, createdAt: $createdAt, endedAt: $endedAt, name: $name, game: $game, group: $group, players: $players, notes: $notes, scores: $scores, mvp: $mvp}';
|
||||
}
|
||||
|
||||
/// Creates a Match instance from a JSON object where related objects are
|
||||
/// represented by their IDs. Therefore, the game, group, and players are not
|
||||
/// fully constructed here.
|
||||
Match copyWith({
|
||||
String? id,
|
||||
DateTime? createdAt,
|
||||
DateTime? endedAt,
|
||||
String? name,
|
||||
Game? game,
|
||||
Group? group,
|
||||
List<Player>? players,
|
||||
List<Team>? teams,
|
||||
String? notes,
|
||||
Map<String, ScoreEntry?>? scores,
|
||||
}) {
|
||||
return Match(
|
||||
id: id ?? this.id,
|
||||
createdAt: createdAt ?? this.createdAt,
|
||||
endedAt: endedAt ?? this.endedAt,
|
||||
name: name ?? this.name,
|
||||
game: game ?? this.game,
|
||||
group: group ?? this.group,
|
||||
players: players ?? this.players,
|
||||
teams: teams ?? this.teams,
|
||||
notes: notes ?? this.notes,
|
||||
scores: scores ?? this.scores,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) =>
|
||||
identical(this, other) ||
|
||||
other is Match &&
|
||||
runtimeType == other.runtimeType &&
|
||||
id == other.id &&
|
||||
createdAt == other.createdAt &&
|
||||
endedAt == other.endedAt &&
|
||||
name == other.name &&
|
||||
game == other.game &&
|
||||
group == other.group &&
|
||||
const DeepCollectionEquality().equals(players, other.players) &&
|
||||
const DeepCollectionEquality().equals(teams, other.teams) &&
|
||||
notes == other.notes &&
|
||||
const DeepCollectionEquality().equals(scores, other.scores);
|
||||
|
||||
@override
|
||||
int get hashCode => Object.hash(
|
||||
id,
|
||||
createdAt,
|
||||
endedAt,
|
||||
name,
|
||||
game,
|
||||
group,
|
||||
const DeepCollectionEquality().hash(players),
|
||||
const DeepCollectionEquality().hash(teams),
|
||||
notes,
|
||||
const DeepCollectionEquality().hash(scores),
|
||||
);
|
||||
|
||||
Match.fromJson(Map<String, dynamic> json)
|
||||
: id = json['id'],
|
||||
createdAt = DateTime.parse(json['createdAt']),
|
||||
@@ -57,6 +114,7 @@ class Match {
|
||||
),
|
||||
group = null,
|
||||
players = [],
|
||||
teams = [],
|
||||
scores = json['scores'] != null
|
||||
? (json['scores'] as Map<String, dynamic>).map(
|
||||
(key, value) => MapEntry(
|
||||
@@ -70,9 +128,6 @@ class Match {
|
||||
notes = json['notes'] ?? '',
|
||||
deleted = json['deleted'] ?? false;
|
||||
|
||||
/// Converts the Match instance to a JSON object. Related objects are
|
||||
/// represented by their IDs, so the game, group, and players are not fully
|
||||
/// serialized here.
|
||||
Map<String, dynamic> toJson() => {
|
||||
'id': id,
|
||||
'createdAt': createdAt.toIso8601String(),
|
||||
@@ -81,6 +136,7 @@ class Match {
|
||||
'gameId': game.id,
|
||||
'groupId': group?.id,
|
||||
'playerIds': players.map((player) => player.id).toList(),
|
||||
'teams': teams?.map((team) => team.toJson()).toList(),
|
||||
'scores': scores.map((key, value) => MapEntry(key, value?.toJson())),
|
||||
'notes': notes,
|
||||
'deleted': deleted,
|
||||
@@ -103,7 +159,10 @@ class Match {
|
||||
return _getPlayersWithLowestScore().take(1).toList();
|
||||
|
||||
case Ruleset.multipleWinners:
|
||||
return [];
|
||||
return _getPlayersWithHighestScore().toList();
|
||||
|
||||
case Ruleset.placement:
|
||||
return _getPlayersWithHighestScore().take(1).toList();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -25,7 +25,36 @@ class Player {
|
||||
return 'Player{id: $id, createdAt: $createdAt, name: $name, nameCount: $nameCount, description: $description}';
|
||||
}
|
||||
|
||||
/// Creates a Player instance from a JSON object.
|
||||
Player copyWith({
|
||||
String? id,
|
||||
DateTime? createdAt,
|
||||
String? name,
|
||||
int? nameCount,
|
||||
String? description,
|
||||
}) {
|
||||
return Player(
|
||||
id: id ?? this.id,
|
||||
createdAt: createdAt ?? this.createdAt,
|
||||
name: name ?? this.name,
|
||||
nameCount: nameCount ?? this.nameCount,
|
||||
description: description ?? this.description,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) =>
|
||||
identical(this, other) ||
|
||||
other is Player &&
|
||||
runtimeType == other.runtimeType &&
|
||||
id == other.id &&
|
||||
createdAt == other.createdAt &&
|
||||
name == other.name &&
|
||||
nameCount == other.nameCount &&
|
||||
description == other.description;
|
||||
|
||||
@override
|
||||
int get hashCode => Object.hash(id, createdAt, name, nameCount, description);
|
||||
|
||||
Player.fromJson(Map<String, dynamic> json)
|
||||
: id = json['id'],
|
||||
createdAt = DateTime.parse(json['createdAt']),
|
||||
@@ -34,7 +63,6 @@ class Player {
|
||||
description = json['description'],
|
||||
deleted = json['deleted'] ?? false;
|
||||
|
||||
/// Converts the Player instance to a JSON object.
|
||||
Map<String, dynamic> toJson() => {
|
||||
'id': id,
|
||||
'createdAt': createdAt.toIso8601String(),
|
||||
|
||||
@@ -11,6 +11,26 @@ class ScoreEntry {
|
||||
return 'ScoreEntry{roundNumber: $roundNumber, score: $score, change: $change}';
|
||||
}
|
||||
|
||||
ScoreEntry copyWith({int? roundNumber, int? score, int? change}) {
|
||||
return ScoreEntry(
|
||||
roundNumber: roundNumber ?? this.roundNumber,
|
||||
score: score ?? this.score,
|
||||
change: change ?? this.change,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) =>
|
||||
identical(this, other) ||
|
||||
other is ScoreEntry &&
|
||||
runtimeType == other.runtimeType &&
|
||||
roundNumber == other.roundNumber &&
|
||||
score == other.score &&
|
||||
change == other.change;
|
||||
|
||||
@override
|
||||
int get hashCode => Object.hash(roundNumber, score, change);
|
||||
|
||||
ScoreEntry.fromJson(Map<String, dynamic> json)
|
||||
: roundNumber = json['roundNumber'],
|
||||
score = json['score'],
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import 'package:clock/clock.dart';
|
||||
import 'package:collection/collection.dart';
|
||||
import 'package:tallee/data/models/player.dart';
|
||||
import 'package:uuid/uuid.dart';
|
||||
|
||||
@@ -23,8 +24,38 @@ class Team {
|
||||
return 'Team{id: $id, name: $name, members: $members}';
|
||||
}
|
||||
|
||||
/// Creates a Team instance from a JSON object (memberIds format).
|
||||
/// Player objects are reconstructed from memberIds by the DataTransferService.
|
||||
Team copyWith({
|
||||
String? id,
|
||||
String? name,
|
||||
DateTime? createdAt,
|
||||
List<Player>? members,
|
||||
}) {
|
||||
return Team(
|
||||
id: id ?? this.id,
|
||||
name: name ?? this.name,
|
||||
createdAt: createdAt ?? this.createdAt,
|
||||
members: members ?? this.members,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) =>
|
||||
identical(this, other) ||
|
||||
other is Team &&
|
||||
runtimeType == other.runtimeType &&
|
||||
id == other.id &&
|
||||
name == other.name &&
|
||||
createdAt == other.createdAt &&
|
||||
const DeepCollectionEquality().equals(members, other.members);
|
||||
|
||||
@override
|
||||
int get hashCode => Object.hash(
|
||||
id,
|
||||
name,
|
||||
createdAt,
|
||||
const DeepCollectionEquality().hash(members),
|
||||
);
|
||||
|
||||
Team.fromJson(Map<String, dynamic> json)
|
||||
: id = json['id'],
|
||||
name = json['name'],
|
||||
@@ -32,8 +63,6 @@ class Team {
|
||||
members = [],
|
||||
deleted = json['deleted'] ?? false;
|
||||
|
||||
/// Converts the Team instance to a JSON object. Related objects are
|
||||
/// represented by their IDs.
|
||||
Map<String, dynamic> toJson() => {
|
||||
'id': id,
|
||||
'name': name,
|
||||
|
||||
Reference in New Issue
Block a user