From 20e20969e42d75f44bdcbe9587d2c6a370821c5d Mon Sep 17 00:00:00 2001 From: Sven Heidemann Date: Sat, 4 Nov 2023 12:02:19 +0100 Subject: [PATCH 01/10] Added scheduled event to db #410 --- .../abc/scheduled_event_repository_abc.py | 35 ++++ .../db_history_scripts/scheduled_events.sql | 65 ++++++ .../migration/scheduled_event_migration.py | 45 +++++ bot/src/bot_data/model/scheduled_event.py | 187 ++++++++++++++++++ .../bot_data/model/scheduled_event_history.py | 118 +++++++++++ .../scheduled_event_repository_service.py | 89 +++++++++ 6 files changed, 539 insertions(+) create mode 100644 bot/src/bot_data/abc/scheduled_event_repository_abc.py create mode 100644 bot/src/bot_data/migration/db_history_scripts/scheduled_events.sql create mode 100644 bot/src/bot_data/migration/scheduled_event_migration.py create mode 100644 bot/src/bot_data/model/scheduled_event.py create mode 100644 bot/src/bot_data/model/scheduled_event_history.py create mode 100644 bot/src/bot_data/service/scheduled_event_repository_service.py diff --git a/bot/src/bot_data/abc/scheduled_event_repository_abc.py b/bot/src/bot_data/abc/scheduled_event_repository_abc.py new file mode 100644 index 00000000..ff0d54c2 --- /dev/null +++ b/bot/src/bot_data/abc/scheduled_event_repository_abc.py @@ -0,0 +1,35 @@ +from abc import ABC, abstractmethod + +from cpl_query.extension import List + +from bot_data.model.scheduled_event import ScheduledEvent + + +class ScheduledEventRepositoryABC(ABC): + @abstractmethod + def __init__(self): + pass + + @abstractmethod + def get_scheduled_events(self) -> List[ScheduledEvent]: + pass + + @abstractmethod + def get_scheduled_event_by_id(self, id: int) -> ScheduledEvent: + pass + + @abstractmethod + def get_scheduled_events_by_server_id(self, id: int) -> List[ScheduledEvent]: + pass + + @abstractmethod + def add_scheduled_event(self, scheduled_event: ScheduledEvent): + pass + + @abstractmethod + def update_scheduled_event(self, scheduled_event: ScheduledEvent): + pass + + @abstractmethod + def delete_scheduled_event(self, scheduled_event: ScheduledEvent): + pass diff --git a/bot/src/bot_data/migration/db_history_scripts/scheduled_events.sql b/bot/src/bot_data/migration/db_history_scripts/scheduled_events.sql new file mode 100644 index 00000000..5ba2cf39 --- /dev/null +++ b/bot/src/bot_data/migration/db_history_scripts/scheduled_events.sql @@ -0,0 +1,65 @@ +CREATE TABLE IF NOT EXISTS `ScheduledEventsHistory` +( + `Id` BIGINT(20) NOT NULL, + `Interval` VARCHAR(255) NOT NULL, + `Name` VARCHAR(255) NOT NULL, + `Description` VARCHAR(255) NOT NULL, + `ChannelId` BIGINT NULL, + `StartTime` DATETIME(6) NOT NULL, + `EndTime` DATETIME(6) NULL, + `EntityType` ENUM (1,2,3) NOT NULL, + `Location` VARCHAR(255) NULL, + `ServerId` BIGINT(20) DEFAULT NULL, + `Deleted` BOOL DEFAULT FALSE, + `DateFrom` DATETIME(6) NOT NULL, + `DateTo` DATETIME(6) NOT NULL +); + +DROP TRIGGER IF EXISTS `TR_ScheduledEventsUpdate`; + +CREATE TRIGGER `TR_ScheduledEventsUpdate` + AFTER UPDATE + ON `ScheduledEvents` + FOR EACH ROW +BEGIN + INSERT INTO `ScheduledEventsHistory` (`Id`, + `Interval`, + `Name`, + `Description`, + `ChannelId`, + `StartTime`, + `EndTime`, + `EntityType`, + `Location`, + `ServerId`, + `DateFrom`, + `DateTo`) + VALUES (OLD.Id, OLD.Interval, OLD.Name, OLD.Description, OLD.ChannelId, OLD.StartTime, OLD.EndTime, OLD.EntityType, + OLD.Location, OLD.ServerId, OLD.LastModifiedAt, + CURRENT_TIMESTAMP(6)); +END; + +DROP TRIGGER IF EXISTS `TR_ScheduledEventsDelete`; + +CREATE TRIGGER `TR_ScheduledEventsDelete` + AFTER DELETE + ON `ScheduledEvents` + FOR EACH ROW +BEGIN + INSERT INTO `ScheduledEventsHistory` (`Id`, + `Interval`, + `Name`, + `Description`, + `ChannelId`, + `StartTime`, + `EndTime`, + `EntityType`, + `Location`, + `ServerId`, + `Deleted`, + `DateFrom`, + `DateTo`) + VALUES (OLD.Id, OLD.Interval, OLD.Name, OLD.Description, OLD.ChannelId, OLD.StartTime, OLD.EndTime, OLD.EntityType, + OLD.Location, OLD.ServerId, TRUE, OLD.LastModifiedAt, + CURRENT_TIMESTAMP(6)); +END; \ No newline at end of file diff --git a/bot/src/bot_data/migration/scheduled_event_migration.py b/bot/src/bot_data/migration/scheduled_event_migration.py new file mode 100644 index 00000000..50cdcec1 --- /dev/null +++ b/bot/src/bot_data/migration/scheduled_event_migration.py @@ -0,0 +1,45 @@ +from bot_core.logging.database_logger import DatabaseLogger +from bot_data.abc.migration_abc import MigrationABC +from bot_data.db_context import DBContext + + +class ScheduledEventMigration(MigrationABC): + name = "1.2.0_ScheduledEventMigration" + + def __init__(self, logger: DatabaseLogger, db: DBContext): + MigrationABC.__init__(self) + self._logger = logger + self._db = db + self._cursor = db.cursor + + def upgrade(self): + self._logger.debug(__name__, "Running upgrade") + + self._cursor.execute( + str( + f""" + CREATE TABLE IF NOT EXISTS `ScheduledEvents` ( + `Id` BIGINT NOT NULL AUTO_INCREMENT, + `Interval` VARCHAR(255) NOT NULL, + `Name` VARCHAR(255) NOT NULL, + `Description` VARCHAR(255) NOT NULL, + `ChannelId` BIGINT NULL, + `StartTime` DATETIME(6) NOT NULL, + `EndTime` DATETIME(6) NULL, + `EntityType` ENUM(1,2,3) NOT NULL, + `Location` VARCHAR(255) NULL, + `ServerId` BIGINT, + `CreatedAt` DATETIME(6) NULL DEFAULT CURRENT_TIMESTAMP(6), + `LastModifiedAt` DATETIME(6) NULL DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6), + PRIMARY KEY(`Id`), + FOREIGN KEY (`ServerId`) REFERENCES `Servers`(`ServerId`) + ); + """ + ) + ) + + self._exec(__file__, "scheduled_events.sql") + + def downgrade(self): + self._cursor.execute("DROP TABLE `ShortRoleNames`;") + self._cursor.execute("DROP TABLE `ShortRoleNamesHistory`;") diff --git a/bot/src/bot_data/model/scheduled_event.py b/bot/src/bot_data/model/scheduled_event.py new file mode 100644 index 00000000..fa05c946 --- /dev/null +++ b/bot/src/bot_data/model/scheduled_event.py @@ -0,0 +1,187 @@ +from datetime import datetime +from typing import Optional + +import discord +from cpl_core.database import TableABC + +from bot_data.model.server import Server + + +class ScheduledEvent(TableABC): + def __init__( + self, + interval: str, + name: str, + description: str, + channel_id: int, + start_time: datetime, + end_time: Optional[datetime], + entity_type: discord.EntityType, + location: Optional[str], + server: Optional[Server], + created_at: datetime = None, + modified_at: datetime = None, + id=0, + ): + self._id = id + self._interval = interval + self._name = name + self._description = description + self._channel_id = channel_id + self._start_time = start_time + self._end_time = end_time + self._entity_type = entity_type + self._location = location + self._server = server + + TableABC.__init__(self) + self._created_at = created_at if created_at is not None else self._created_at + self._modified_at = modified_at if modified_at is not None else self._modified_at + + @property + def id(self) -> int: + return self._id + + @property + def interval(self) -> str: + return self._interval + + @interval.setter + def interval(self, value: str): + self._interval = value + + @property + def name(self) -> str: + return self._name + + @name.setter + def name(self, value: str): + self._name = value + + @property + def description(self) -> str: + return self._description + + @description.setter + def description(self, value: str): + self._description = value + + @property + def channel_id(self) -> int: + return self._channel_id + + @channel_id.setter + def channel_id(self, value: int): + self._channel_id = value + + @property + def start_time(self) -> datetime: + return self._start_time + + @start_time.setter + def start_time(self, value: datetime): + self._start_time = value + + @property + def end_time(self) -> datetime: + return self._end_time + + @end_time.setter + def end_time(self, value: datetime): + self._end_time = value + + @property + def entity_type(self) -> discord.EntityType: + return self._entity_type + + @entity_type.setter + def entity_type(self, value: discord.EntityType): + self._entity_type = value + + @property + def location(self) -> str: + return self._location + + @location.setter + def location(self, value: str): + self._location = value + + @property + def server(self) -> Server: + return self._server + + @server.setter + def server(self, value: Server): + self._server = value + + @staticmethod + def get_select_all_string() -> str: + return str( + f""" + SELECT * FROM `ScheduledEvents`; + """ + ) + + @staticmethod + def get_select_by_id_string(id: int) -> str: + return str( + f""" + SELECT * FROM `ScheduledEvents` + WHERE `Id` = {id}; + """ + ) + + @staticmethod + def get_select_by_server_id_string(s_id: int) -> str: + return str( + f""" + SELECT * FROM `ScheduledEvents` + WHERE `ServerId` = {s_id}; + """ + ) + + @property + def insert_string(self) -> str: + return str( + f""" + INSERT INTO `ScheduledEvents` ( + `Interval`, `Name`, `Description`, `ChannelId`, `StartTime`, `EndTime`, `EntityType`, `Location`, `ServerId`, + ) VALUES ( + '{self._interval}', + '{self._name}', + '{self._description}', + {"NULL" if self._channel_id is None else f"'{self._channel_id}'"}, + '{self._start_time}', + {"NULL" if self._end_time is None else f"'{self._end_time}'"}, + '{self._entity_type}', + {"NULL" if self._location is None else f"'{self._location}'"}, + {self._server.id} + ); + """ + ) + + @property + def udpate_string(self) -> str: + return str( + f""" + UPDATE `ScheduledEvents` + SET `Interval` = '{self._interval}', + `Name` = '{self._name}', + `Description` = '{self._start_time}', + `ChannelId` = {"NULL" if self._channel_id is None else f"'{self._channel_id}'"}, + `StartTime` = '{self._start_time}', + `EndTime` = {"NULL" if self._end_time is None else f"'{self._end_time}'"}, + `EntityType` = '{self._entity_type}', + `Location` = {"NULL" if self._location is None else f"'{self._location}'"} + WHERE `Id` = {self._id}; + """ + ) + + @property + def delete_string(self) -> str: + return str( + f""" + DELETE FROM `ScheduledEvents` + WHERE `Id` = {self._id}; + """ + ) diff --git a/bot/src/bot_data/model/scheduled_event_history.py b/bot/src/bot_data/model/scheduled_event_history.py new file mode 100644 index 00000000..b910e796 --- /dev/null +++ b/bot/src/bot_data/model/scheduled_event_history.py @@ -0,0 +1,118 @@ +from datetime import datetime +from typing import Optional + +import discord +from cpl_core.database import TableABC + +from bot_data.abc.history_table_abc import HistoryTableABC +from bot_data.model.server import Server + + +class ScheduledEventHistory(HistoryTableABC): + def __init__( + self, + interval: str, + name: str, + description: str, + channel_id: int, + start_time: datetime, + end_time: Optional[datetime], + entity_type: discord.EntityType, + location: Optional[str], + server: Optional[Server], + deleted: bool, + date_from: str, + date_to: str, + id=0, + ): + HistoryTableABC.__init__(self) + self._id = id + self._interval = interval + self._name = name + self._description = description + self._channel_id = channel_id + self._start_time = start_time + self._end_time = end_time + self._entity_type = entity_type + self._location = location + self._server = server + + self._deleted = deleted + self._date_from = date_from + self._date_to = date_to + + @property + def id(self) -> int: + return self._id + + @property + def interval(self) -> str: + return self._interval + + @interval.setter + def interval(self, value: str): + self._interval = value + + @property + def name(self) -> str: + return self._name + + @name.setter + def name(self, value: str): + self._name = value + + @property + def description(self) -> str: + return self._description + + @description.setter + def description(self, value: str): + self._description = value + + @property + def channel_id(self) -> int: + return self._channel_id + + @channel_id.setter + def channel_id(self, value: int): + self._channel_id = value + + @property + def start_time(self) -> datetime: + return self._start_time + + @start_time.setter + def start_time(self, value: datetime): + self._start_time = value + + @property + def end_time(self) -> datetime: + return self._end_time + + @end_time.setter + def end_time(self, value: datetime): + self._end_time = value + + @property + def entity_type(self) -> discord.EntityType: + return self._entity_type + + @entity_type.setter + def entity_type(self, value: discord.EntityType): + self._entity_type = value + + @property + def location(self) -> str: + return self._location + + @location.setter + def location(self, value: str): + self._location = value + + @property + def server(self) -> Server: + return self._server + + @server.setter + def server(self, value: Server): + self._server = value diff --git a/bot/src/bot_data/service/scheduled_event_repository_service.py b/bot/src/bot_data/service/scheduled_event_repository_service.py new file mode 100644 index 00000000..7d5e67ba --- /dev/null +++ b/bot/src/bot_data/service/scheduled_event_repository_service.py @@ -0,0 +1,89 @@ +from typing import Optional + +from cpl_core.database.context import DatabaseContextABC +from cpl_query.extension import List + +from bot_core.logging.database_logger import DatabaseLogger +from bot_data.abc.server_repository_abc import ServerRepositoryABC +from bot_data.abc.scheduled_event_repository_abc import ScheduledEventRepositoryABC +from bot_data.model.scheduled_event import ScheduledEvent + + +class ScheduledEventRepositoryService(ScheduledEventRepositoryABC): + def __init__( + self, + logger: DatabaseLogger, + db_context: DatabaseContextABC, + servers: ServerRepositoryABC, + ): + self._logger = logger + self._context = db_context + + self._servers = servers + + ScheduledEventRepositoryABC.__init__(self) + + @staticmethod + def _get_value_from_result(value: any) -> Optional[any]: + if isinstance(value, str) and "NULL" in value: + return None + + return value + + def _scheduled_event_from_result(self, sql_result: tuple) -> ScheduledEvent: + return ScheduledEvent( + self._get_value_from_result(sql_result[0]), # interval + self._get_value_from_result(sql_result[1]), # name + self._get_value_from_result(sql_result[2]), # description + int(self._get_value_from_result(sql_result[3])), # channel_id + self._get_value_from_result(sql_result[4]), # start_time + self._get_value_from_result(sql_result[5]), # end_time + self._get_value_from_result(sql_result[6]), # entity_type + self._get_value_from_result(sql_result[7]), # location + self._servers.get_server_by_id((sql_result[8])), # server + self._get_value_from_result(sql_result[9]), # created_at + self._get_value_from_result(sql_result[10]), # modified_at + id=self._get_value_from_result(sql_result[0]), + ) + + def get_scheduled_events(self) -> List[ScheduledEvent]: + scheduled_events = List(ScheduledEvent) + self._logger.trace(__name__, f"Send SQL command: {ScheduledEvent.get_select_all_string()}") + results = self._context.select(ScheduledEvent.get_select_all_string()) + for result in results: + self._logger.trace(__name__, f"Get scheduled_event with id {result[0]}") + scheduled_events.append(self._scheduled_event_from_result(result)) + + return scheduled_events + + def get_scheduled_event_by_id(self, id: int) -> ScheduledEvent: + self._logger.trace(__name__, f"Send SQL command: {ScheduledEvent.get_select_by_id_string(id)}") + result = self._context.select(ScheduledEvent.get_select_by_id_string(id))[0] + + return self._scheduled_event_from_result(result) + + def get_scheduled_events_by_server_id(self, server_id: int) -> List[ScheduledEvent]: + scheduled_events = List(ScheduledEvent) + self._logger.trace( + __name__, + f"Send SQL command: {ScheduledEvent.get_select_by_server_id_string(server_id)}", + ) + results = self._context.select(ScheduledEvent.get_select_by_server_id_string(server_id)) + + for result in results: + self._logger.trace(__name__, f"Get scheduled_event with id {result[0]}") + scheduled_events.append(self._scheduled_event_from_result(result)) + + return scheduled_events + + def add_scheduled_event(self, scheduled_event: ScheduledEvent): + self._logger.trace(__name__, f"Send SQL command: {scheduled_event.insert_string}") + self._context.cursor.execute(scheduled_event.insert_string) + + def update_scheduled_event(self, scheduled_event: ScheduledEvent): + self._logger.trace(__name__, f"Send SQL command: {scheduled_event.udpate_string}") + self._context.cursor.execute(scheduled_event.udpate_string) + + def delete_scheduled_event(self, scheduled_event: ScheduledEvent): + self._logger.trace(__name__, f"Send SQL command: {scheduled_event.delete_string}") + self._context.cursor.execute(scheduled_event.delete_string) From e8cc42e155837167f8a77c573ab7f29ca0c30f9c Mon Sep 17 00:00:00 2001 From: Sven Heidemann Date: Sun, 5 Nov 2023 21:14:05 +0100 Subject: [PATCH 02/10] Added scheduledEvent to gql #410 --- .../db_history_scripts/scheduled_events.sql | 2 +- .../migration/scheduled_event_migration.py | 2 +- bot/src/bot_graphql/abc/filter_abc.py | 15 +++ bot/src/bot_graphql/abc/query_abc.py | 11 +++ .../filter/scheduled_event_filter.py | 71 ++++++++++++++ .../filter/short_role_name_filter.py | 4 +- bot/src/bot_graphql/graphql/mutation.gql | 1 + bot/src/bot_graphql/graphql/query.gql | 3 + .../bot_graphql/graphql/scheduledEvent.gql | 68 ++++++++++++++ bot/src/bot_graphql/graphql/server.gql | 3 + bot/src/bot_graphql/graphql_module.py | 6 ++ .../mutations/scheduled_event_mutation.py | 92 +++++++++++++++++++ .../queries/scheduled_event_history_query.py | 24 +++++ .../queries/scheduled_event_query.py | 23 +++++ bot/src/bot_graphql/queries/server_query.py | 8 ++ bot/src/bot_graphql/query.py | 8 ++ 16 files changed, 338 insertions(+), 3 deletions(-) create mode 100644 bot/src/bot_graphql/filter/scheduled_event_filter.py create mode 100644 bot/src/bot_graphql/graphql/scheduledEvent.gql create mode 100644 bot/src/bot_graphql/mutations/scheduled_event_mutation.py create mode 100644 bot/src/bot_graphql/queries/scheduled_event_history_query.py create mode 100644 bot/src/bot_graphql/queries/scheduled_event_query.py diff --git a/bot/src/bot_data/migration/db_history_scripts/scheduled_events.sql b/bot/src/bot_data/migration/db_history_scripts/scheduled_events.sql index 5ba2cf39..d456b410 100644 --- a/bot/src/bot_data/migration/db_history_scripts/scheduled_events.sql +++ b/bot/src/bot_data/migration/db_history_scripts/scheduled_events.sql @@ -7,7 +7,7 @@ CREATE TABLE IF NOT EXISTS `ScheduledEventsHistory` `ChannelId` BIGINT NULL, `StartTime` DATETIME(6) NOT NULL, `EndTime` DATETIME(6) NULL, - `EntityType` ENUM (1,2,3) NOT NULL, + `EntityType` ENUM ('1','2','3') NOT NULL, `Location` VARCHAR(255) NULL, `ServerId` BIGINT(20) DEFAULT NULL, `Deleted` BOOL DEFAULT FALSE, diff --git a/bot/src/bot_data/migration/scheduled_event_migration.py b/bot/src/bot_data/migration/scheduled_event_migration.py index 50cdcec1..ee0dde63 100644 --- a/bot/src/bot_data/migration/scheduled_event_migration.py +++ b/bot/src/bot_data/migration/scheduled_event_migration.py @@ -26,7 +26,7 @@ class ScheduledEventMigration(MigrationABC): `ChannelId` BIGINT NULL, `StartTime` DATETIME(6) NOT NULL, `EndTime` DATETIME(6) NULL, - `EntityType` ENUM(1,2,3) NOT NULL, + `EntityType` ENUM('1','2','3') NOT NULL, `Location` VARCHAR(255) NULL, `ServerId` BIGINT, `CreatedAt` DATETIME(6) NULL DEFAULT CURRENT_TIMESTAMP(6), diff --git a/bot/src/bot_graphql/abc/filter_abc.py b/bot/src/bot_graphql/abc/filter_abc.py index e0d5ff8d..7c1fa477 100644 --- a/bot/src/bot_graphql/abc/filter_abc.py +++ b/bot/src/bot_graphql/abc/filter_abc.py @@ -1,8 +1,10 @@ import functools from abc import ABC, abstractmethod from inspect import signature, Parameter +from typing import Callable from cpl_core.dependency_injection import ServiceProviderABC +from cpl_core.type import R, T from cpl_query.extension import List @@ -52,3 +54,16 @@ class FilterABC(ABC): return f(*args, **kwargs) return decorator + + def _get_attributes_from_dict(self, attrs: list[tuple[str, type]], values: dict): + for key_pair in attrs: + attr = key_pair[0] + attr_type = key_pair[1] + if attr in values: + self.__setattr__(f"_{attr}", attr_type(values[attr])) + + @staticmethod + def _filter_by_attributes(attrs: list[Callable], values: List[T]) -> List[R]: + for attr in attrs: + values = values.where(attr) + return values diff --git a/bot/src/bot_graphql/abc/query_abc.py b/bot/src/bot_graphql/abc/query_abc.py index 506428fc..882a420d 100644 --- a/bot/src/bot_graphql/abc/query_abc.py +++ b/bot/src/bot_graphql/abc/query_abc.py @@ -20,6 +20,7 @@ from bot_data.model.auto_role_rule import AutoRoleRule from bot_data.model.client import Client from bot_data.model.known_user import KnownUser from bot_data.model.level import Level +from bot_data.model.scheduled_event import ScheduledEvent from bot_data.model.server import Server from bot_data.model.server_config import ServerConfig from bot_data.model.short_role_name import ShortRoleName @@ -213,6 +214,16 @@ class QueryABC(ObjectType): access = True break + elif type(element) == ScheduledEvent: + element: ScheduledEvent = element + for u in user.users: + u: User = u + guild = bot.get_guild(u.server.discord_id) + member = guild.get_member(u.discord_id) + if permissions.is_member_moderator(member) and u.server.id == element.server.id: + access = True + break + elif type(element) == dict and "key" in element and element["key"] in [e.value for e in FeatureFlagsEnum]: for u in user.users: u: User = u diff --git a/bot/src/bot_graphql/filter/scheduled_event_filter.py b/bot/src/bot_graphql/filter/scheduled_event_filter.py new file mode 100644 index 00000000..d1937c25 --- /dev/null +++ b/bot/src/bot_graphql/filter/scheduled_event_filter.py @@ -0,0 +1,71 @@ +from cpl_core.dependency_injection import ServiceProviderABC +from cpl_discord.service import DiscordBotServiceABC +from cpl_query.extension import List + +from bot_data.model.scheduled_event import ScheduledEvent +from bot_graphql.abc.filter_abc import FilterABC + + +class ScheduledEventFilter(FilterABC): + def __init__(self, bot: DiscordBotServiceABC, services: ServiceProviderABC): + FilterABC.__init__(self) + self._bot = bot + self._services = services + + self._id = None + self._interval = None + self._name = None + self._description = None + self._channel_id = None + self._start_time = None + self._end_time = None + self._entity_type = None + self._location = None + self._server = None + + def from_dict(self, values: dict): + self._get_attributes_from_dict( + [ + ("id", int), + ("interval", str), + ("name", str), + ("description", str), + ("channel_id", str), + ("start_time", str), + ("end_time", str), + ("entity_type", str), + ("location", str), + ], + values, + ) + + if "server" in values: + from bot_graphql.filter.server_filter import ServerFilter + + self._server: ServerFilter = self._services.get_service(ServerFilter) + self._server.from_dict(values["server"]) + + def filter(self, query: List[ScheduledEvent]) -> List[ScheduledEvent]: + if self._id is not None: + query = query.where(lambda x: x.id == self._id) + + query = self._filter_by_attributes( + [ + lambda x: x.id == self._id, + lambda x: x.interval == self._interval, + lambda x: x.name == self._name, + lambda x: x.description == self._description, + lambda x: x.channel_id == self._channel_id, + lambda x: x.start_time == self._start_time, + lambda x: x.end_time == self._end_time, + lambda x: x.entity_type == self._entity_type, + lambda x: x.location == self._location, + ], + query, + ) + + if self._server is not None: + servers = self._server.filter(query.select(lambda x: x.server)).select(lambda x: x.id) + query = query.where(lambda x: x.server.id in servers) + + return query diff --git a/bot/src/bot_graphql/filter/short_role_name_filter.py b/bot/src/bot_graphql/filter/short_role_name_filter.py index 426e3630..ea5a8bba 100644 --- a/bot/src/bot_graphql/filter/short_role_name_filter.py +++ b/bot/src/bot_graphql/filter/short_role_name_filter.py @@ -1,3 +1,4 @@ +from cpl_core.dependency_injection import ServiceProviderABC from cpl_discord.service import DiscordBotServiceABC from cpl_query.extension import List @@ -8,9 +9,10 @@ from bot_graphql.abc.filter_abc import FilterABC class ShortRoleNameFilter(FilterABC): - def __init__(self, bot: DiscordBotServiceABC): + def __init__(self, bot: DiscordBotServiceABC, services: ServiceProviderABC): FilterABC.__init__(self) self._bot = bot + self._services = services self._id = None self._short_name = None diff --git a/bot/src/bot_graphql/graphql/mutation.gql b/bot/src/bot_graphql/graphql/mutation.gql index 9578fde0..56d6374f 100644 --- a/bot/src/bot_graphql/graphql/mutation.gql +++ b/bot/src/bot_graphql/graphql/mutation.gql @@ -6,6 +6,7 @@ type Mutation { userJoinedGameServer: UserJoinedGameServerMutation achievement: AchievementMutation shortRoleName: ShortRoleNameMutation + scheduledEvent: ScheduledEventMutation technicianConfig: TechnicianConfigMutation serverConfig: ServerConfigMutation } \ No newline at end of file diff --git a/bot/src/bot_graphql/graphql/query.gql b/bot/src/bot_graphql/graphql/query.gql index ffa3c21f..6892510d 100644 --- a/bot/src/bot_graphql/graphql/query.gql +++ b/bot/src/bot_graphql/graphql/query.gql @@ -41,6 +41,9 @@ type Query { shortRoleNames(filter: ShortRoleNameFilter, page: Page, sort: Sort): [ShortRoleName] shortRoleNamePositions: [String] + scheduledEventCount: Int + scheduledEvents(filter: ScheduledEventFilter, page: Page, sort: Sort): [ScheduledEvent] + userWarningCount: Int userWarnings(filter: UserWarningFilter, page: Page, sort: Sort): [UserWarning] diff --git a/bot/src/bot_graphql/graphql/scheduledEvent.gql b/bot/src/bot_graphql/graphql/scheduledEvent.gql new file mode 100644 index 00000000..586bbc92 --- /dev/null +++ b/bot/src/bot_graphql/graphql/scheduledEvent.gql @@ -0,0 +1,68 @@ +type ScheduledEvent implements TableWithHistoryQuery { + id: ID + interval: String + name: String + description: String + channelId: String + startTime: String + endTime: String + entityType: Int + location: String + + server: Server + + createdAt: String + modifiedAt: String + + history: [ScheduledEventHistory] +} + +type ScheduledEventHistory implements HistoryTableQuery { + id: ID + interval: String + name: String + description: String + channelId: String + startTime: String + endTime: String + entityType: Int + location: String + + server: ID + + deleted: Boolean + dateFrom: String + dateTo: String +} + +input ScheduledEventFilter { + id: ID + interval: String + name: String + description: String + channelId: String + startTime: String + endTime: String + entityType: Int + location: String + server: ServerFilter +} + +type ScheduledEventMutation { + createScheduledEvent(input: ScheduledEventInput!): ScheduledEvent + updateScheduledEvent(input: ScheduledEventInput!): ScheduledEvent + deleteScheduledEvent(id: ID): ScheduledEvent +} + +input ScheduledEventInput { + id: ID + interval: String + name: String + description: String + channelId: String + startTime: String + endTime: String + entityType: Int + location: String + serverId: ID +} \ No newline at end of file diff --git a/bot/src/bot_graphql/graphql/server.gql b/bot/src/bot_graphql/graphql/server.gql index be603f3a..4624ffca 100644 --- a/bot/src/bot_graphql/graphql/server.gql +++ b/bot/src/bot_graphql/graphql/server.gql @@ -35,6 +35,9 @@ type Server implements TableWithHistoryQuery { shortRoleNameCount: Int shortRoleNames(filter: ShortRoleNameFilter, page: Page, sort: Sort): [ShortRoleName] + scheduledEventCount: Int + scheduledEvents(filter: ScheduledEventFilter, page: Page, sort: Sort): [ScheduledEvent] + config: ServerConfig hasFeatureFlag(flag: String): FeatureFlag diff --git a/bot/src/bot_graphql/graphql_module.py b/bot/src/bot_graphql/graphql_module.py index 95d73f7b..21957e56 100644 --- a/bot/src/bot_graphql/graphql_module.py +++ b/bot/src/bot_graphql/graphql_module.py @@ -12,6 +12,7 @@ from bot_graphql.filter.auto_role_filter import AutoRoleFilter from bot_graphql.filter.auto_role_rule_filter import AutoRoleRuleFilter from bot_graphql.filter.client_filter import ClientFilter from bot_graphql.filter.level_filter import LevelFilter +from bot_graphql.filter.scheduled_event_filter import ScheduledEventFilter from bot_graphql.filter.server_filter import ServerFilter from bot_graphql.filter.short_role_name_filter import ShortRoleNameFilter from bot_graphql.filter.user_filter import UserFilter @@ -27,6 +28,7 @@ from bot_graphql.mutations.achievement_mutation import AchievementMutation from bot_graphql.mutations.auto_role_mutation import AutoRoleMutation from bot_graphql.mutations.auto_role_rule_mutation import AutoRoleRuleMutation from bot_graphql.mutations.level_mutation import LevelMutation +from bot_graphql.mutations.scheduled_event_mutation import ScheduledEventMutation from bot_graphql.mutations.server_config_mutation import ServerConfigMutation from bot_graphql.mutations.short_role_name_mutation import ShortRoleNameMutation from bot_graphql.mutations.technician_config_mutation import TechnicianConfigMutation @@ -54,6 +56,7 @@ from bot_graphql.queries.known_user_history_query import KnownUserHistoryQuery from bot_graphql.queries.known_user_query import KnownUserQuery from bot_graphql.queries.level_history_query import LevelHistoryQuery from bot_graphql.queries.level_query import LevelQuery +from bot_graphql.queries.scheduled_event_query import ScheduledEventQuery from bot_graphql.queries.server_config_query import ServerConfigQuery from bot_graphql.queries.server_history_query import ServerHistoryQuery from bot_graphql.queries.server_query import ServerQuery @@ -140,6 +143,7 @@ class GraphQLModule(ModuleABC): services.add_transient(QueryABC, UserWarningHistoryQuery) services.add_transient(QueryABC, UserWarningQuery) services.add_transient(QueryABC, ServerStatisticQuery) + services.add_transient(QueryABC, ScheduledEventQuery) services.add_transient(QueryABC, DiscordQuery) services.add_transient(QueryABC, GuildQuery) @@ -161,6 +165,7 @@ class GraphQLModule(ModuleABC): services.add_transient(FilterABC, UserJoinedGameServerFilter) services.add_transient(FilterABC, ShortRoleNameFilter) services.add_transient(FilterABC, UserWarningFilter) + services.add_transient(FilterABC, ScheduledEventFilter) # mutations services.add_transient(QueryABC, AutoRoleMutation) @@ -172,3 +177,4 @@ class GraphQLModule(ModuleABC): services.add_transient(QueryABC, UserJoinedGameServerMutation) services.add_transient(QueryABC, TechnicianConfigMutation) services.add_transient(QueryABC, ServerConfigMutation) + services.add_transient(QueryABC, ScheduledEventMutation) diff --git a/bot/src/bot_graphql/mutations/scheduled_event_mutation.py b/bot/src/bot_graphql/mutations/scheduled_event_mutation.py new file mode 100644 index 00000000..c138b082 --- /dev/null +++ b/bot/src/bot_graphql/mutations/scheduled_event_mutation.py @@ -0,0 +1,92 @@ +from cpl_core.database.context import DatabaseContextABC +from cpl_discord.service import DiscordBotServiceABC + +from bot_data.abc.server_repository_abc import ServerRepositoryABC +from bot_data.abc.scheduled_event_repository_abc import ScheduledEventRepositoryABC +from bot_data.model.scheduled_event import ScheduledEvent +from bot_data.model.user_role_enum import UserRoleEnum +from bot_graphql.abc.query_abc import QueryABC +from modules.permission.service.permission_service import PermissionService + + +class ScheduledEventMutation(QueryABC): + def __init__( + self, + servers: ServerRepositoryABC, + scheduled_events: ScheduledEventRepositoryABC, + bot: DiscordBotServiceABC, + db: DatabaseContextABC, + permissions: PermissionService, + ): + QueryABC.__init__(self, "ScheduledEventMutation") + + self._servers = servers + self._scheduled_events = scheduled_events + self._bot = bot + self._db = db + self._permissions = permissions + + self.set_field("createScheduledEvent", self.resolve_create_scheduled_event) + self.set_field("updateScheduledEvent", self.resolve_update_scheduled_event) + self.set_field("deleteScheduledEvent", self.resolve_delete_scheduled_event) + + def resolve_create_scheduled_event(self, *_, input: dict): + server = self._servers.get_server_by_id(input["serverId"]) + self._can_user_mutate_data(server, UserRoleEnum.moderator) + + scheduled_event = ScheduledEvent( + input["interval"], + input["name"], + input["description"], + input["channel_id"], + input["start_time"], + input["end_time"], + input["entity_type"], + input["location"], + server, + ) + + self._scheduled_events.add_scheduled_event(scheduled_event) + self._db.save_changes() + + def get_new_scheduled_event(srn: ScheduledEvent): + return ( + srn.interval == scheduled_event.interval + and srn.name == scheduled_event.name + and srn.description == scheduled_event.description + ) + + return ( + self._scheduled_events.get_scheduled_events_by_server_id(scheduled_event.server.id) + .where(get_new_scheduled_event) + .last() + ) + + def resolve_update_scheduled_event(self, *_, input: dict): + scheduled_event = self._scheduled_events.get_scheduled_event_by_id(input["id"]) + self._can_user_mutate_data(scheduled_event.server, UserRoleEnum.moderator) + + scheduled_event.short_name = input["shortName"] if "shortName" in input else scheduled_event.short_name + scheduled_event.interval = input["interval"] if "interval" in input else scheduled_event.interval + scheduled_event.name = input["name"] if "name" in input else scheduled_event.name + scheduled_event.description = input["description"] if "description" in input else scheduled_event.description + scheduled_event.channel_id = input["channel_id"] if "channel_id" in input else scheduled_event.channel_id + scheduled_event.start_time = input["start_time"] if "start_time" in input else scheduled_event.start_time + scheduled_event.end_time = input["end_time"] if "end_time" in input else scheduled_event.end_time + scheduled_event.entity_type = input["entity_type"] if "entity_type" in input else scheduled_event.entity_type + scheduled_event.location = input["location"] if "location" in input else scheduled_event.location + + self._scheduled_events.update_scheduled_event(scheduled_event) + self._db.save_changes() + + scheduled_event = self._scheduled_events.get_scheduled_event_by_id(input["id"]) + return scheduled_event + + def resolve_delete_scheduled_event(self, *_, id: int): + scheduled_event = self._scheduled_events.get_scheduled_event_by_id(id) + self._can_user_mutate_data(scheduled_event.server, UserRoleEnum.admin) + + self._scheduled_events.delete_scheduled_event(scheduled_event) + self._db.save_changes() + + return scheduled_event diff --git a/bot/src/bot_graphql/queries/scheduled_event_history_query.py b/bot/src/bot_graphql/queries/scheduled_event_history_query.py new file mode 100644 index 00000000..279bcda1 --- /dev/null +++ b/bot/src/bot_graphql/queries/scheduled_event_history_query.py @@ -0,0 +1,24 @@ +from cpl_core.database.context import DatabaseContextABC + +from bot_data.model.scheduled_event_history import ScheduledEventHistory +from bot_graphql.abc.data_query_with_history_abc import DataQueryWithHistoryABC + + +class ScheduledEventHistoryQuery(DataQueryWithHistoryABC): + def __init__( + self, + db: DatabaseContextABC, + ): + DataQueryWithHistoryABC.__init__(self, "ScheduledEvent", "ScheduledEventsHistory", ScheduledEventHistory, db) + + self.set_field("id", lambda x, *_: x.id) + self.set_field("id", lambda x, *_: x.id) + self.set_field("interval", lambda x, *_: x.interval) + self.set_field("name", lambda x, *_: x.name) + self.set_field("description", lambda x, *_: x.description) + self.set_field("channel_id", lambda x, *_: x.channel_id) + self.set_field("start_time", lambda x, *_: x.start_time) + self.set_field("end_time", lambda x, *_: x.end_time) + self.set_field("entity_type", lambda x, *_: x.entity_type) + self.set_field("location", lambda x, *_: x.location) + self.set_field("server", lambda x, *_: x.server) diff --git a/bot/src/bot_graphql/queries/scheduled_event_query.py b/bot/src/bot_graphql/queries/scheduled_event_query.py new file mode 100644 index 00000000..47b09a1b --- /dev/null +++ b/bot/src/bot_graphql/queries/scheduled_event_query.py @@ -0,0 +1,23 @@ +from cpl_core.database.context import DatabaseContextABC + +from bot_data.model.scheduled_event_history import ScheduledEventHistory +from bot_graphql.abc.data_query_with_history_abc import DataQueryWithHistoryABC + + +class ScheduledEventQuery(DataQueryWithHistoryABC): + def __init__( + self, + db: DatabaseContextABC, + ): + DataQueryWithHistoryABC.__init__(self, "ScheduledEvent", "ScheduledEventsHistory", ScheduledEventHistory, db) + + self.set_field("id", lambda x, *_: x.id) + self.set_field("interval", lambda x, *_: x.interval) + self.set_field("name", lambda x, *_: x.name) + self.set_field("description", lambda x, *_: x.description) + self.set_field("channelId", lambda x, *_: x.channel_id) + self.set_field("startTime", lambda x, *_: x.start_time) + self.set_field("endTime", lambda x, *_: x.end_time) + self.set_field("entityType", lambda x, *_: x.entity_type) + self.set_field("location", lambda x, *_: x.location) + self.set_field("server", lambda x, *_: x.server) diff --git a/bot/src/bot_graphql/queries/server_query.py b/bot/src/bot_graphql/queries/server_query.py index 14033101..3760db07 100644 --- a/bot/src/bot_graphql/queries/server_query.py +++ b/bot/src/bot_graphql/queries/server_query.py @@ -9,6 +9,7 @@ from bot_data.abc.auto_role_repository_abc import AutoRoleRepositoryABC from bot_data.abc.client_repository_abc import ClientRepositoryABC from bot_data.abc.game_server_repository_abc import GameServerRepositoryABC from bot_data.abc.level_repository_abc import LevelRepositoryABC +from bot_data.abc.scheduled_event_repository_abc import ScheduledEventRepositoryABC from bot_data.abc.server_config_repository_abc import ServerConfigRepositoryABC from bot_data.abc.short_role_name_repository_abc import ShortRoleNameRepositoryABC from bot_data.abc.user_joined_server_repository_abc import UserJoinedServerRepositoryABC @@ -24,6 +25,7 @@ from bot_graphql.filter.achievement_filter import AchievementFilter from bot_graphql.filter.auto_role_filter import AutoRoleFilter from bot_graphql.filter.client_filter import ClientFilter from bot_graphql.filter.level_filter import LevelFilter +from bot_graphql.filter.scheduled_event_filter import ScheduledEventFilter from bot_graphql.filter.short_role_name_filter import ShortRoleNameFilter from bot_graphql.filter.user_filter import UserFilter from bot_graphql.model.server_statistics import ServerStatistics @@ -44,6 +46,7 @@ class ServerQuery(DataQueryWithHistoryABC): ujvs: UserJoinedVoiceChannelRepositoryABC, achievements: AchievementRepositoryABC, short_role_names: ShortRoleNameRepositoryABC, + scheduled_events: ScheduledEventRepositoryABC, server_configs: ServerConfigRepositoryABC, ): DataQueryWithHistoryABC.__init__(self, "Server", "ServersHistory", ServerHistory, db) @@ -100,6 +103,11 @@ class ServerQuery(DataQueryWithHistoryABC): lambda server, *_: short_role_names.get_short_role_names_by_server_id(server.id), ShortRoleNameFilter, ) + self.add_collection( + "scheduledEvent", + lambda server, *_: scheduled_events.get_scheduled_events_by_server_id(server.id), + ScheduledEventFilter, + ) self.set_field( "config", lambda server, *_: server_configs.get_server_config_by_server(server.id), diff --git a/bot/src/bot_graphql/query.py b/bot/src/bot_graphql/query.py index 41dafdf0..154079d9 100644 --- a/bot/src/bot_graphql/query.py +++ b/bot/src/bot_graphql/query.py @@ -8,6 +8,7 @@ from bot_data.abc.client_repository_abc import ClientRepositoryABC from bot_data.abc.game_server_repository_abc import GameServerRepositoryABC from bot_data.abc.known_user_repository_abc import KnownUserRepositoryABC from bot_data.abc.level_repository_abc import LevelRepositoryABC +from bot_data.abc.scheduled_event_repository_abc import ScheduledEventRepositoryABC from bot_data.abc.server_repository_abc import ServerRepositoryABC from bot_data.abc.short_role_name_repository_abc import ShortRoleNameRepositoryABC from bot_data.abc.technician_config_repository_abc import TechnicianConfigRepositoryABC @@ -27,6 +28,7 @@ from bot_graphql.filter.auto_role_filter import AutoRoleFilter from bot_graphql.filter.auto_role_rule_filter import AutoRoleRuleFilter from bot_graphql.filter.client_filter import ClientFilter from bot_graphql.filter.level_filter import LevelFilter +from bot_graphql.filter.scheduled_event_filter import ScheduledEventFilter from bot_graphql.filter.server_filter import ServerFilter from bot_graphql.filter.short_role_name_filter import ShortRoleNameFilter from bot_graphql.filter.user_filter import UserFilter @@ -59,6 +61,7 @@ class Query(QueryABC): user_warnings: UserWarningsRepositoryABC, achievement_service: AchievementService, technician_config: TechnicianConfigRepositoryABC, + scheduled_events: ScheduledEventRepositoryABC, ): QueryABC.__init__(self, "Query") @@ -95,6 +98,11 @@ class Query(QueryABC): lambda *_: short_role_names.get_short_role_names(), ShortRoleNameFilter, ) + self.add_collection( + "scheduledEvent", + lambda server, *_: scheduled_events.get_scheduled_events_by_server_id(server.id), + ScheduledEventFilter, + ) self.add_collection( "userWarning", lambda *_: user_warnings.get_user_warnings(), From 2de5afd6487779f2b070893fcf76d8d42506255c Mon Sep 17 00:00:00 2001 From: Sven Heidemann Date: Tue, 14 Nov 2023 17:46:12 +0100 Subject: [PATCH 03/10] Rebased & fixed backend #410 --- .../migration/scheduled_event_migration.py | 45 ------------------- .../scripts/1.2.2/1_ScheduledEvents_down.sql | 3 ++ .../1.2.2/1_ScheduledEvents_up.sql} | 40 ++++++++++++----- .../modules/achievements/achievements.json | 4 +- bot/src/modules/config/config.json | 4 +- .../short_role_name/short-role-name.json | 4 +- .../special_offers/special-offers.json | 4 +- .../migration_to_sql/migration-to-sql.json | 10 ++--- 8 files changed, 45 insertions(+), 69 deletions(-) delete mode 100644 bot/src/bot_data/migration/scheduled_event_migration.py create mode 100644 bot/src/bot_data/scripts/1.2.2/1_ScheduledEvents_down.sql rename bot/src/bot_data/{migration/db_history_scripts/scheduled_events.sql => scripts/1.2.2/1_ScheduledEvents_up.sql} (63%) diff --git a/bot/src/bot_data/migration/scheduled_event_migration.py b/bot/src/bot_data/migration/scheduled_event_migration.py deleted file mode 100644 index ee0dde63..00000000 --- a/bot/src/bot_data/migration/scheduled_event_migration.py +++ /dev/null @@ -1,45 +0,0 @@ -from bot_core.logging.database_logger import DatabaseLogger -from bot_data.abc.migration_abc import MigrationABC -from bot_data.db_context import DBContext - - -class ScheduledEventMigration(MigrationABC): - name = "1.2.0_ScheduledEventMigration" - - def __init__(self, logger: DatabaseLogger, db: DBContext): - MigrationABC.__init__(self) - self._logger = logger - self._db = db - self._cursor = db.cursor - - def upgrade(self): - self._logger.debug(__name__, "Running upgrade") - - self._cursor.execute( - str( - f""" - CREATE TABLE IF NOT EXISTS `ScheduledEvents` ( - `Id` BIGINT NOT NULL AUTO_INCREMENT, - `Interval` VARCHAR(255) NOT NULL, - `Name` VARCHAR(255) NOT NULL, - `Description` VARCHAR(255) NOT NULL, - `ChannelId` BIGINT NULL, - `StartTime` DATETIME(6) NOT NULL, - `EndTime` DATETIME(6) NULL, - `EntityType` ENUM('1','2','3') NOT NULL, - `Location` VARCHAR(255) NULL, - `ServerId` BIGINT, - `CreatedAt` DATETIME(6) NULL DEFAULT CURRENT_TIMESTAMP(6), - `LastModifiedAt` DATETIME(6) NULL DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6), - PRIMARY KEY(`Id`), - FOREIGN KEY (`ServerId`) REFERENCES `Servers`(`ServerId`) - ); - """ - ) - ) - - self._exec(__file__, "scheduled_events.sql") - - def downgrade(self): - self._cursor.execute("DROP TABLE `ShortRoleNames`;") - self._cursor.execute("DROP TABLE `ShortRoleNamesHistory`;") diff --git a/bot/src/bot_data/scripts/1.2.2/1_ScheduledEvents_down.sql b/bot/src/bot_data/scripts/1.2.2/1_ScheduledEvents_down.sql new file mode 100644 index 00000000..d055ec13 --- /dev/null +++ b/bot/src/bot_data/scripts/1.2.2/1_ScheduledEvents_down.sql @@ -0,0 +1,3 @@ +DROP TABLE `ShortRoleNames`; + +DROP TABLE `ShortRoleNamesHistory`; \ No newline at end of file diff --git a/bot/src/bot_data/migration/db_history_scripts/scheduled_events.sql b/bot/src/bot_data/scripts/1.2.2/1_ScheduledEvents_up.sql similarity index 63% rename from bot/src/bot_data/migration/db_history_scripts/scheduled_events.sql rename to bot/src/bot_data/scripts/1.2.2/1_ScheduledEvents_up.sql index d456b410..2768651e 100644 --- a/bot/src/bot_data/migration/db_history_scripts/scheduled_events.sql +++ b/bot/src/bot_data/scripts/1.2.2/1_ScheduledEvents_up.sql @@ -1,18 +1,36 @@ +CREATE TABLE IF NOT EXISTS `ScheduledEvents` +( + `Id` BIGINT NOT NULL AUTO_INCREMENT, + `Interval` VARCHAR(255) NOT NULL, + `Name` VARCHAR(255) NOT NULL, + `Description` VARCHAR(255) NOT NULL, + `ChannelId` BIGINT NULL, + `StartTime` DATETIME(6) NOT NULL, + `EndTime` DATETIME(6) NULL, + `EntityType` ENUM ('1','2','3') NOT NULL, + `Location` VARCHAR(255) NULL, + `ServerId` BIGINT, + `CreatedAt` DATETIME(6) NULL DEFAULT CURRENT_TIMESTAMP(6), + `LastModifiedAt` DATETIME(6) NULL DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6), + PRIMARY KEY (`Id`), + FOREIGN KEY (`ServerId`) REFERENCES `Servers` (`ServerId`) +); + CREATE TABLE IF NOT EXISTS `ScheduledEventsHistory` ( - `Id` BIGINT(20) NOT NULL, - `Interval` VARCHAR(255) NOT NULL, - `Name` VARCHAR(255) NOT NULL, - `Description` VARCHAR(255) NOT NULL, - `ChannelId` BIGINT NULL, - `StartTime` DATETIME(6) NOT NULL, - `EndTime` DATETIME(6) NULL, - `EntityType` ENUM ('1','2','3') NOT NULL, - `Location` VARCHAR(255) NULL, + `Id` BIGINT(20) NOT NULL, + `Interval` VARCHAR(255) NOT NULL, + `Name` VARCHAR(255) NOT NULL, + `Description` VARCHAR(255) NOT NULL, + `ChannelId` BIGINT NULL, + `StartTime` DATETIME(6) NOT NULL, + `EndTime` DATETIME(6) NULL, + `EntityType` ENUM ('1','2','3') NOT NULL, + `Location` VARCHAR(255) NULL, `ServerId` BIGINT(20) DEFAULT NULL, `Deleted` BOOL DEFAULT FALSE, - `DateFrom` DATETIME(6) NOT NULL, - `DateTo` DATETIME(6) NOT NULL + `DateFrom` DATETIME(6) NOT NULL, + `DateTo` DATETIME(6) NOT NULL ); DROP TRIGGER IF EXISTS `TR_ScheduledEventsUpdate`; diff --git a/bot/src/modules/achievements/achievements.json b/bot/src/modules/achievements/achievements.json index acea20a4..911cf740 100644 --- a/bot/src/modules/achievements/achievements.json +++ b/bot/src/modules/achievements/achievements.json @@ -16,10 +16,10 @@ "LicenseName": "MIT", "LicenseDescription": "MIT, see LICENSE for more details.", "Dependencies": [ - "cpl-core>=1.2.1" + "cpl-core>=1.2.dev410" ], "DevDependencies": [ - "cpl-cli>=1.2.1" + "cpl-cli>=1.2.dev410" ], "PythonVersion": ">=3.10.4", "PythonPath": {}, diff --git a/bot/src/modules/config/config.json b/bot/src/modules/config/config.json index 301f4630..6a80a8c4 100644 --- a/bot/src/modules/config/config.json +++ b/bot/src/modules/config/config.json @@ -16,10 +16,10 @@ "LicenseName": "", "LicenseDescription": "", "Dependencies": [ - "cpl-core>=1.2.1" + "cpl-core>=1.2.dev410" ], "DevDependencies": [ - "cpl-cli>=1.2.1" + "cpl-cli>=1.2.dev410" ], "PythonVersion": ">=3.10.4", "PythonPath": { diff --git a/bot/src/modules/short_role_name/short-role-name.json b/bot/src/modules/short_role_name/short-role-name.json index 57329ee1..23b81e41 100644 --- a/bot/src/modules/short_role_name/short-role-name.json +++ b/bot/src/modules/short_role_name/short-role-name.json @@ -16,10 +16,10 @@ "LicenseName": "", "LicenseDescription": "", "Dependencies": [ - "cpl-core>=1.2.1" + "cpl-core>=1.2.dev410" ], "DevDependencies": [ - "cpl-cli>=1.2.1" + "cpl-cli>=1.2.dev410" ], "PythonVersion": ">=3.10.4", "PythonPath": { diff --git a/bot/src/modules/special_offers/special-offers.json b/bot/src/modules/special_offers/special-offers.json index 8def3776..cd6b44b1 100644 --- a/bot/src/modules/special_offers/special-offers.json +++ b/bot/src/modules/special_offers/special-offers.json @@ -16,10 +16,10 @@ "LicenseName": "", "LicenseDescription": "", "Dependencies": [ - "cpl-core>=1.2.1" + "cpl-core>=1.2.dev410" ], "DevDependencies": [ - "cpl-cli>=1.2.1" + "cpl-cli>=1.2.dev410" ], "PythonVersion": ">=3.10.4", "PythonPath": { diff --git a/bot/tools/migration_to_sql/migration-to-sql.json b/bot/tools/migration_to_sql/migration-to-sql.json index 5e4a62f8..6be85895 100644 --- a/bot/tools/migration_to_sql/migration-to-sql.json +++ b/bot/tools/migration_to_sql/migration-to-sql.json @@ -2,9 +2,9 @@ "ProjectSettings": { "Name": "migration-to-sql", "Version": { - "Major": "0", - "Minor": "0", - "Micro": "0" + "Major": "1", + "Minor": "2", + "Micro": "2" }, "Author": "", "AuthorEmail": "", @@ -16,10 +16,10 @@ "LicenseName": "", "LicenseDescription": "", "Dependencies": [ - "cpl-core>=2023.10.0" + "cpl-core>=1.2.dev410" ], "DevDependencies": [ - "cpl-cli>=2023.4.0.post3" + "cpl-cli>=1.2.dev410" ], "PythonVersion": ">=3.10.4", "PythonPath": { From a3ebd07093c3887e9483bffbbf8223d9baeecd76 Mon Sep 17 00:00:00 2001 From: Sven Heidemann Date: Tue, 14 Nov 2023 23:45:39 +0100 Subject: [PATCH 04/10] Working on add/edit dialog #410 --- .../configuration/feature_flags_enum.py | 1 + .../configuration/feature_flags_settings.py | 1 + bot/src/bot_data/data_module.py | 3 + .../app/models/data/scheduled_events.model.ts | 34 ++ web/src/app/models/graphql/mutations.model.ts | 64 ++++ web/src/app/models/graphql/queries.model.ts | 52 +++ web/src/app/models/graphql/query.model.ts | 6 + web/src/app/models/graphql/result.model.ts | 9 + web/src/app/modules/shared/shared.module.ts | 22 +- ...edit-scheduled-event-dialog.component.html | 44 +++ ...edit-scheduled-event-dialog.component.scss | 0 ...t-scheduled-event-dialog.component.spec.ts | 23 ++ .../edit-scheduled-event-dialog.component.ts | 70 ++++ .../scheduled-events.component.html | 307 ++++++++++++++++++ .../scheduled-events.component.scss | 0 .../scheduled-events.component.spec.ts | 23 ++ .../scheduled-events.component.ts | 287 ++++++++++++++++ .../scheduled-events-routing.module.ts | 14 + .../scheduled-events.module.ts | 21 ++ .../view/server/server-routing.module.ts | 1 + .../short-role-name/short-role-name.module.ts | 18 +- .../app/services/sidebar/sidebar.service.ts | 11 +- web/src/assets/i18n/de.json | 35 ++ web/src/assets/i18n/en.json | 30 ++ web/src/styles.scss | 33 ++ .../styles/themes/sh-edraft-dark-theme.scss | 39 ++- 26 files changed, 1107 insertions(+), 41 deletions(-) create mode 100644 web/src/app/models/data/scheduled_events.model.ts create mode 100644 web/src/app/modules/view/server/scheduled-events/components/edit-scheduled-event-dialog/edit-scheduled-event-dialog.component.html create mode 100644 web/src/app/modules/view/server/scheduled-events/components/edit-scheduled-event-dialog/edit-scheduled-event-dialog.component.scss create mode 100644 web/src/app/modules/view/server/scheduled-events/components/edit-scheduled-event-dialog/edit-scheduled-event-dialog.component.spec.ts create mode 100644 web/src/app/modules/view/server/scheduled-events/components/edit-scheduled-event-dialog/edit-scheduled-event-dialog.component.ts create mode 100644 web/src/app/modules/view/server/scheduled-events/components/scheduled-events/scheduled-events.component.html create mode 100644 web/src/app/modules/view/server/scheduled-events/components/scheduled-events/scheduled-events.component.scss create mode 100644 web/src/app/modules/view/server/scheduled-events/components/scheduled-events/scheduled-events.component.spec.ts create mode 100644 web/src/app/modules/view/server/scheduled-events/components/scheduled-events/scheduled-events.component.ts create mode 100644 web/src/app/modules/view/server/scheduled-events/scheduled-events-routing.module.ts create mode 100644 web/src/app/modules/view/server/scheduled-events/scheduled-events.module.ts diff --git a/bot/src/bot_core/configuration/feature_flags_enum.py b/bot/src/bot_core/configuration/feature_flags_enum.py index 6d051b0c..8506af95 100644 --- a/bot/src/bot_core/configuration/feature_flags_enum.py +++ b/bot/src/bot_core/configuration/feature_flags_enum.py @@ -27,3 +27,4 @@ class FeatureFlagsEnum(Enum): short_role_name = "ShortRoleName" technician_full_access = "TechnicianFullAccess" steam_special_offers = "SteamSpecialOffers" + scheduled_events = "ScheduledEvents" diff --git a/bot/src/bot_core/configuration/feature_flags_settings.py b/bot/src/bot_core/configuration/feature_flags_settings.py index 0ed95e71..3b994b17 100644 --- a/bot/src/bot_core/configuration/feature_flags_settings.py +++ b/bot/src/bot_core/configuration/feature_flags_settings.py @@ -29,6 +29,7 @@ class FeatureFlagsSettings(ConfigurationModelABC): FeatureFlagsEnum.short_role_name.value: False, # 28.09.2023 #378 FeatureFlagsEnum.technician_full_access.value: False, # 03.10.2023 #393 FeatureFlagsEnum.steam_special_offers.value: False, # 11.10.2023 #188 + FeatureFlagsEnum.scheduled_events.value: False, # 14.11.2023 #410 } def __init__(self, **kwargs: dict): diff --git a/bot/src/bot_data/data_module.py b/bot/src/bot_data/data_module.py index cec9cb37..5d20e874 100644 --- a/bot/src/bot_data/data_module.py +++ b/bot/src/bot_data/data_module.py @@ -14,6 +14,7 @@ from bot_data.abc.data_seeder_abc import DataSeederABC from bot_data.abc.game_server_repository_abc import GameServerRepositoryABC from bot_data.abc.known_user_repository_abc import KnownUserRepositoryABC from bot_data.abc.level_repository_abc import LevelRepositoryABC +from bot_data.abc.scheduled_event_repository_abc import ScheduledEventRepositoryABC from bot_data.abc.server_config_repository_abc import ServerConfigRepositoryABC from bot_data.abc.server_repository_abc import ServerRepositoryABC from bot_data.abc.short_role_name_repository_abc import ShortRoleNameRepositoryABC @@ -45,6 +46,7 @@ from bot_data.service.client_repository_service import ClientRepositoryService from bot_data.service.game_server_repository_service import GameServerRepositoryService from bot_data.service.known_user_repository_service import KnownUserRepositoryService from bot_data.service.level_repository_service import LevelRepositoryService +from bot_data.service.scheduled_event_repository_service import ScheduledEventRepositoryService from bot_data.service.seeder_service import SeederService from bot_data.service.server_config_repository_service import ( ServerConfigRepositoryService, @@ -115,6 +117,7 @@ class DataModule(ModuleABC): services.add_transient(ServerConfigRepositoryABC, ServerConfigRepositoryService) services.add_transient(ShortRoleNameRepositoryABC, ShortRoleNameRepositoryService) services.add_transient(SteamSpecialOfferRepositoryABC, SteamSpecialOfferRepositoryService) + services.add_transient(ScheduledEventRepositoryABC, ScheduledEventRepositoryService) services.add_transient(SeederService) services.add_transient(DataSeederABC, TechnicianConfigSeeder) diff --git a/web/src/app/models/data/scheduled_events.model.ts b/web/src/app/models/data/scheduled_events.model.ts new file mode 100644 index 00000000..c3e8beea --- /dev/null +++ b/web/src/app/models/data/scheduled_events.model.ts @@ -0,0 +1,34 @@ +import { DataWithHistory } from "./data.model"; +import { Server, ServerFilter } from "./server.model"; + +export enum EventType { + stageInstance = 1, + voice = 2, + external = 3, +} + +export interface ScheduledEvent extends DataWithHistory { + id?: number; + interval?: string; + name?: string; + description?: string; + channelId?: string; + startTime?: string; + endTime?: string; + entityType?: EventType; + location?: string; + server?: Server; +} + +export interface ScheduledEventFilter { + id?: number; + interval?: string; + name?: string; + description?: string; + channelId?: string; + startTime?: string; + endTime?: string; + entityType?: number; + location?: string; + server?: ServerFilter; +} diff --git a/web/src/app/models/graphql/mutations.model.ts b/web/src/app/models/graphql/mutations.model.ts index 4f52fa01..27fd48c1 100644 --- a/web/src/app/models/graphql/mutations.model.ts +++ b/web/src/app/models/graphql/mutations.model.ts @@ -173,6 +173,70 @@ export class Mutations { } `; + static createScheduledEvent = ` + mutation createScheduledEvent($interval: String,$name: String,$description: String,$channelId: String,$startTime: String, $endTime: String,$entityType: Int,$location: String, $serverId: ID) { + scheduledEvent { + createScheduledEvent(input: { + interval: $interval, + name: $name, + description: $description, + channelId: $channelId, + startTime: $startTime, + endTime: $endTime, + entityType: $entityType, + location: $location, + serverId: $serverId} + ) { + id + name + description + attribute + operator + value + server { + id + } + } + } + } + `; + + static updateScheduledEvent = ` + mutation updateScheduledEvent($interval: String,$name: String,$description: String,$channelId: String,$startTime: String, $endTime: String,$entityType: Int,$location: String, $serverId: ID) { + scheduledEvent { + updateScheduledEvent(input: { + interval: $interval, + name: $name, + description: $description, + channelId: $channelId, + startTime: $startTime, + endTime: $endTime, + entityType: $entityType, + location: $location, + serverId: $serverId} + ) { + id + name + description + attribute + operator + value + } + } + } + `; + + static deleteScheduledEvent = ` + mutation deleteScheduledEvent($id: ID) { + scheduledEvent { + deleteScheduledEvent(id: $id) { + id + name + } + } + } + `; + static createShortRoleName = ` mutation createShortRoleName($shortName: String, $roleId: String, $position: String, $serverId: ID) { shortRoleName { diff --git a/web/src/app/models/graphql/queries.model.ts b/web/src/app/models/graphql/queries.model.ts index e44e3aab..1365d76e 100644 --- a/web/src/app/models/graphql/queries.model.ts +++ b/web/src/app/models/graphql/queries.model.ts @@ -229,6 +229,58 @@ export class Queries { } `; + static scheduledEventQuery = ` + query ScheduledEventList($serverId: ID, $filter: ScheduledEventFilter, $page: Page, $sort: Sort) { + servers(filter: {id: $serverId}) { + scheduledEventCount + scheduledEvents(filter: $filter, page: $page, sort: $sort) { + id + interval + name + description + channelId + startTime + endTime + entityType + location + server { + id + name + } + createdAt + modifiedAt + } + } + } + `; + + static scheduledEventWithHistoryQuery = ` + query ScheduledEventHistory($serverId: ID, $id: ID) { + servers(filter: {id: $serverId}) { + scheduledEventCount + scheduledEvents(filter: {id: $id}) { + id + + history { + id + interval + name + description + channelId + startTime + endTime + entityType + location + server + deleted + dateFrom + dateTo + } + } + } + } + `; + static shortRoleNamePositionsQuery = ` query { diff --git a/web/src/app/models/graphql/query.model.ts b/web/src/app/models/graphql/query.model.ts index f98f9a4a..b7da6553 100644 --- a/web/src/app/models/graphql/query.model.ts +++ b/web/src/app/models/graphql/query.model.ts @@ -9,6 +9,7 @@ import { ServerConfig } from "../config/server-config.model"; import { ShortRoleName } from "../data/short_role_name.model"; import { FeatureFlag } from "../config/feature-flags.model"; import { UserWarning } from "../data/user_warning.model"; +import { ScheduledEvent } from "../data/scheduled_events.model"; export interface Query { serverCount: number; @@ -57,6 +58,11 @@ export interface AchievementListQuery { achievements: Achievement[]; } +export interface ScheduledEventListQuery { + scheduledEventCount: number; + scheduledEvents: ScheduledEvent[]; +} + export interface AutoRoleQuery { autoRoleCount: number; autoRoles: AutoRole[]; diff --git a/web/src/app/models/graphql/result.model.ts b/web/src/app/models/graphql/result.model.ts index 411d6f1d..2b9844a7 100644 --- a/web/src/app/models/graphql/result.model.ts +++ b/web/src/app/models/graphql/result.model.ts @@ -7,6 +7,7 @@ import { TechnicianConfig } from "../config/technician-config.model"; import { ServerConfig } from "../config/server-config.model"; import { ShortRoleName } from "../data/short_role_name.model"; import { UserWarning } from "../data/user_warning.model"; +import { ScheduledEvent } from "../data/scheduled_events.model"; export interface GraphQLResult { data: { @@ -71,6 +72,14 @@ export interface AchievementMutationResult { }; } +export interface ScheduledEventMutationResult { + scheduledEvent: { + createScheduledEvent?: ScheduledEvent + updateScheduledEvent?: ScheduledEvent + deleteScheduledEvent?: ScheduledEvent + }; +} + export interface ShortRoleNameMutationResult { shortRoleName: { createShortRoleName?: ShortRoleName diff --git a/web/src/app/modules/shared/shared.module.ts b/web/src/app/modules/shared/shared.module.ts index b3ca8e60..2a7bfc45 100644 --- a/web/src/app/modules/shared/shared.module.ts +++ b/web/src/app/modules/shared/shared.module.ts @@ -13,7 +13,7 @@ import { InputTextModule } from "primeng/inputtext"; import { MenuModule } from "primeng/menu"; import { PasswordModule } from "primeng/password"; import { ProgressSpinnerModule } from "primeng/progressspinner"; -import { SortableColumn, TableModule } from "primeng/table"; +import { TableModule } from "primeng/table"; import { ToastModule } from "primeng/toast"; import { AuthRolePipe } from "./pipes/auth-role.pipe"; import { IpAddressPipe } from "./pipes/ip-address.pipe"; @@ -24,18 +24,20 @@ import { InputNumberModule } from "primeng/inputnumber"; import { ImageModule } from "primeng/image"; import { SidebarModule } from "primeng/sidebar"; import { HistoryBtnComponent } from "./components/history-btn/history-btn.component"; -import { DataViewModule, DataViewLayoutOptions } from "primeng/dataview"; +import { DataViewLayoutOptions, DataViewModule } from "primeng/dataview"; import { ConfigListComponent } from "./components/config-list/config-list.component"; import { MultiSelectModule } from "primeng/multiselect"; -import { HideableColumnComponent } from './components/hideable-column/hideable-column.component'; -import { HideableHeaderComponent } from './components/hideable-header/hideable-header.component'; -import { MultiSelectColumnsComponent } from './base/multi-select-columns/multi-select-columns.component'; -import { FeatureFlagListComponent } from './components/feature-flag-list/feature-flag-list.component'; +import { HideableColumnComponent } from "./components/hideable-column/hideable-column.component"; +import { HideableHeaderComponent } from "./components/hideable-header/hideable-header.component"; +import { MultiSelectColumnsComponent } from "./base/multi-select-columns/multi-select-columns.component"; +import { FeatureFlagListComponent } from "./components/feature-flag-list/feature-flag-list.component"; import { InputSwitchModule } from "primeng/inputswitch"; import { CalendarModule } from "primeng/calendar"; -import { DataImportAndExportComponent } from './components/data-import-and-export/data-import-and-export.component'; +import { DataImportAndExportComponent } from "./components/data-import-and-export/data-import-and-export.component"; import { FileUploadModule } from "primeng/fileupload"; import { SelectButtonModule } from "primeng/selectbutton"; +import { TabViewModule } from "primeng/tabview"; +import { RadioButtonModule } from "primeng/radiobutton"; const PrimeNGModules = [ @@ -66,7 +68,9 @@ const PrimeNGModules = [ CalendarModule, FileUploadModule, SelectButtonModule, -] + TabViewModule, + RadioButtonModule +]; @NgModule({ declarations: [ @@ -79,7 +83,7 @@ const PrimeNGModules = [ HideableHeaderComponent, MultiSelectColumnsComponent, FeatureFlagListComponent, - DataImportAndExportComponent, + DataImportAndExportComponent ], imports: [ CommonModule, diff --git a/web/src/app/modules/view/server/scheduled-events/components/edit-scheduled-event-dialog/edit-scheduled-event-dialog.component.html b/web/src/app/modules/view/server/scheduled-events/components/edit-scheduled-event-dialog/edit-scheduled-event-dialog.component.html new file mode 100644 index 00000000..938281d5 --- /dev/null +++ b/web/src/app/modules/view/server/scheduled-events/components/edit-scheduled-event-dialog/edit-scheduled-event-dialog.component.html @@ -0,0 +1,44 @@ +
+ +
+ + +
+ + +
+
+ +

+ Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem + aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. + Nemo + enim + ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos + qui + ratione voluptatem sequi nesciunt. Consectetur, adipisci velit, sed quia non numquam eius modi. +

+
+
+ +
+
+ +
+
+ + + +
+
+
+
+
+
diff --git a/web/src/app/modules/view/server/scheduled-events/components/edit-scheduled-event-dialog/edit-scheduled-event-dialog.component.scss b/web/src/app/modules/view/server/scheduled-events/components/edit-scheduled-event-dialog/edit-scheduled-event-dialog.component.scss new file mode 100644 index 00000000..e69de29b diff --git a/web/src/app/modules/view/server/scheduled-events/components/edit-scheduled-event-dialog/edit-scheduled-event-dialog.component.spec.ts b/web/src/app/modules/view/server/scheduled-events/components/edit-scheduled-event-dialog/edit-scheduled-event-dialog.component.spec.ts new file mode 100644 index 00000000..e97349b3 --- /dev/null +++ b/web/src/app/modules/view/server/scheduled-events/components/edit-scheduled-event-dialog/edit-scheduled-event-dialog.component.spec.ts @@ -0,0 +1,23 @@ +import { ComponentFixture, TestBed } from '@angular/core/testing'; + +import { EditScheduledEventDialogComponent } from './edit-scheduled-event-dialog.component'; + +describe('EditScheduledEventDialogComponent', () => { + let component: EditScheduledEventDialogComponent; + let fixture: ComponentFixture; + + beforeEach(async () => { + await TestBed.configureTestingModule({ + declarations: [ EditScheduledEventDialogComponent ] + }) + .compileComponents(); + + fixture = TestBed.createComponent(EditScheduledEventDialogComponent); + component = fixture.componentInstance; + fixture.detectChanges(); + }); + + it('should create', () => { + expect(component).toBeTruthy(); + }); +}); diff --git a/web/src/app/modules/view/server/scheduled-events/components/edit-scheduled-event-dialog/edit-scheduled-event-dialog.component.ts b/web/src/app/modules/view/server/scheduled-events/components/edit-scheduled-event-dialog/edit-scheduled-event-dialog.component.ts new file mode 100644 index 00000000..ca5ff6d6 --- /dev/null +++ b/web/src/app/modules/view/server/scheduled-events/components/edit-scheduled-event-dialog/edit-scheduled-event-dialog.component.ts @@ -0,0 +1,70 @@ +import { Component, EventEmitter, Input, Output } from "@angular/core"; +import { EventType, ScheduledEvent } from "../../../../../../models/data/scheduled_events.model"; +import { TranslateService } from "@ngx-translate/core"; +import { FormBuilder, FormControl, Validators } from "@angular/forms"; + +@Component({ + selector: "app-edit-scheduled-event-dialog", + templateUrl: "./edit-scheduled-event-dialog.component.html", + styleUrls: ["./edit-scheduled-event-dialog.component.scss"] +}) +export class EditScheduledEventDialogComponent { + @Input() event?: ScheduledEvent; + @Output() save = new EventEmitter(); + + get visible() { + return this.event != undefined; + } + + set visible(val: boolean) { + if (!val) { + this.event = undefined; + } + this.visible = val; + } + + get header() { + if (this.event && this.event.createdAt === "" && this.event.modifiedAt === "") { + return this.translate.instant("view.server.scheduled_events.edit_dialog.add_header"); + } else { + return this.translate.instant("view.server.scheduled_events.edit_dialog.edit_header"); + } + } + + public activeIndex: number = 0; + public inputForm = this.fb.group({ + id: new FormControl(this.event?.id), + interval: new FormControl(this.event?.interval, [Validators.required]), + entityType: new FormControl(this.event?.entityType, [Validators.required]), + channelId: new FormControl(this.event?.channelId, this.event?.entityType == EventType.voice || this.event?.entityType == EventType.stageInstance ? [Validators.required] : []), + location: new FormControl(this.event?.location, this.event?.entityType == EventType.external ? [Validators.required] : []), + name: new FormControl(this.event?.name, [Validators.required]), + startTime: new FormControl(this.event?.startTime, [Validators.required]), + endTime: new FormControl(this.event?.endTime), + description: new FormControl(this.event?.description) + }); + + constructor( + private translate: TranslateService, + private fb: FormBuilder + ) { + } + + public saveEvent() { + this.save.emit(this.event); + } + + public next() { + this.activeIndex++; + } + + public back() { + this.activeIndex--; + } + + protected readonly EventType = { + stage: EventType.stageInstance, + voice: EventType.voice, + somewhere_else: EventType.external + }; +} diff --git a/web/src/app/modules/view/server/scheduled-events/components/scheduled-events/scheduled-events.component.html b/web/src/app/modules/view/server/scheduled-events/components/scheduled-events/scheduled-events.component.html new file mode 100644 index 00000000..1296b1bd --- /dev/null +++ b/web/src/app/modules/view/server/scheduled-events/components/scheduled-events/scheduled-events.component.html @@ -0,0 +1,307 @@ + + +

+ {{'view.server.scheduled_events.header' | translate}} +

+
+
+ + + +
+
+
+ {{scheduledEvents.length}} {{'common.of' | translate}} + {{dt.totalRecords}} + + {{'view.server.scheduled_events.scheduled_events' | translate}} +
+ + +
+ +
+ + + +
+
+
+ + + + +
+
{{'common.id' | translate}}
+ +
+ + + +
+
{{'common.interval' | translate}}
+ +
+ + +
+
{{'common.name' | translate}}
+ +
+ + +
+
{{'common.description' | translate}}
+ +
+ + +
+
{{'common.channel_id' | translate}}
+ +
+ + +
+
{{'common.start_time' | translate}}
+ +
+ + +
+
{{'common.end_time' | translate}}
+ +
+ + +
+
{{'common.type' | translate}}
+ +
+ + +
+
{{'common.location' | translate}}
+ +
+ + + +
+
{{'common.created_at' | translate}}
+
+ + + +
+
{{'common.modified_at' | translate}}
+
+ + + +
+
{{'common.actions' | translate}}
+
+ + + + + +
+ +
+ + + + + +
+ +
+ + + + + + + + + + + + +
+ + + + + {{'common.id' | translate}}: + + + {{scheduledEvent.id}} + + + {{scheduledEvent.id}} + + + + + + {{'common.interval' | translate}}: + + + + + + {{scheduledEvent.interval}} + + + + + + {{'common.name' | translate}}: + + + + + + {{scheduledEvent.name}} + + + + + + {{'common.description' | translate}}: + + + + + + {{scheduledEvent.description}} + + + + + + {{'common.channel_id' | translate}}: + + + + + + {{scheduledEvent.channel_id}} + + + + + + {{'common.start_time' | translate}}: + + + + + + {{scheduledEvent.start_time}} + + + + + + {{'common.end_time' | translate}}: + + + + + + {{scheduledEvent.end_time}} + + + + + + {{'common.type' | translate}}: + + + + + + {{scheduledEvent.type}} + + + + + + {{'common.location' | translate}}: + + + + + + {{scheduledEvent.location}} + + + + + + {{'common.created_at' | translate}}: + + + {{scheduledEvent.createdAt | date:'dd.MM.yy HH:mm'}} + + + {{scheduledEvent.createdAt | date:'dd.MM.yy HH:mm'}} + + + + + {{'common.modified_at' | translate}}: + + + {{scheduledEvent.modifiedAt | date:'dd.MM.yy HH:mm'}} + + + {{scheduledEvent.modifiedAt | date:'dd.MM.yy HH:mm'}} + + + + +
+ + + +
+ + +
+ + + + + {{'common.no_entries_found' | translate}} + + + + + + +
+
+
+ diff --git a/web/src/app/modules/view/server/scheduled-events/components/scheduled-events/scheduled-events.component.scss b/web/src/app/modules/view/server/scheduled-events/components/scheduled-events/scheduled-events.component.scss new file mode 100644 index 00000000..e69de29b diff --git a/web/src/app/modules/view/server/scheduled-events/components/scheduled-events/scheduled-events.component.spec.ts b/web/src/app/modules/view/server/scheduled-events/components/scheduled-events/scheduled-events.component.spec.ts new file mode 100644 index 00000000..f7d3244f --- /dev/null +++ b/web/src/app/modules/view/server/scheduled-events/components/scheduled-events/scheduled-events.component.spec.ts @@ -0,0 +1,23 @@ +import { ComponentFixture, TestBed } from '@angular/core/testing'; + +import { ScheduledEventsComponent } from './scheduled-events.component'; + +describe('ScheduledEventsComponent', () => { + let component: ScheduledEventsComponent; + let fixture: ComponentFixture; + + beforeEach(async () => { + await TestBed.configureTestingModule({ + declarations: [ ScheduledEventsComponent ] + }) + .compileComponents(); + + fixture = TestBed.createComponent(ScheduledEventsComponent); + component = fixture.componentInstance; + fixture.detectChanges(); + }); + + it('should create', () => { + expect(component).toBeTruthy(); + }); +}); diff --git a/web/src/app/modules/view/server/scheduled-events/components/scheduled-events/scheduled-events.component.ts b/web/src/app/modules/view/server/scheduled-events/components/scheduled-events/scheduled-events.component.ts new file mode 100644 index 00000000..da0e8972 --- /dev/null +++ b/web/src/app/modules/view/server/scheduled-events/components/scheduled-events/scheduled-events.component.ts @@ -0,0 +1,287 @@ +import { Component, OnDestroy, OnInit } from "@angular/core"; +import { FormBuilder, FormControl, FormGroup } from "@angular/forms"; +import { Page } from "../../../../../../models/graphql/filter/page.model"; +import { Sort, SortDirection } from "../../../../../../models/graphql/filter/sort.model"; +import { Subject, throwError } from "rxjs"; +import { Server } from "../../../../../../models/data/server.model"; +import { UserDTO } from "../../../../../../models/auth/auth-user.dto"; +import { LazyLoadEvent } from "primeng/api"; +import { Queries } from "../../../../../../models/graphql/queries.model"; +import { AuthService } from "../../../../../../services/auth/auth.service"; +import { SpinnerService } from "../../../../../../services/spinner/spinner.service"; +import { ToastService } from "../../../../../../services/toast/toast.service"; +import { ConfirmationDialogService } from "../../../../../../services/confirmation-dialog/confirmation-dialog.service"; +import { TranslateService } from "@ngx-translate/core"; +import { DataService } from "../../../../../../services/data/data.service"; +import { SidebarService } from "../../../../../../services/sidebar/sidebar.service"; +import { ActivatedRoute } from "@angular/router"; +import { Query, ScheduledEventListQuery } from "../../../../../../models/graphql/query.model"; +import { catchError, debounceTime, takeUntil } from "rxjs/operators"; +import { Table } from "primeng/table"; +import { ScheduledEventMutationResult } from "../../../../../../models/graphql/result.model"; +import { Mutations } from "../../../../../../models/graphql/mutations.model"; +import { ComponentWithTable } from "../../../../../../base/component-with-table"; +import { EventType, ScheduledEvent, ScheduledEventFilter } from "../../../../../../models/data/scheduled_events.model"; + +@Component({ + selector: "app-scheduled-events", + templateUrl: "./scheduled-events.component.html", + styleUrls: ["./scheduled-events.component.scss"] +}) +export class ScheduledEventsComponent extends ComponentWithTable implements OnInit, OnDestroy { + public scheduledEvents: ScheduledEvent[] = []; + public loading = true; + + public filterForm!: FormGroup<{ + id: FormControl, + interval: FormControl, + name: FormControl, + description: FormControl, + channelId: FormControl, + startTime: FormControl, + endTime: FormControl, + entityType: FormControl, + location: FormControl, + }>; + + public filter: ScheduledEventFilter = {}; + public page: Page = { + pageSize: undefined, + pageIndex: undefined + }; + public sort: Sort = { + sortColumn: undefined, + sortDirection: undefined + }; + + public totalRecords: number = 0; + + private unsubscriber = new Subject(); + private server: Server = {}; + public user: UserDTO | null = null; + public query: string = Queries.scheduledEventWithHistoryQuery; + public editableScheduledEvent?: ScheduledEvent = undefined; + + public constructor( + private authService: AuthService, + private spinner: SpinnerService, + private toastService: ToastService, + private confirmDialog: ConfirmationDialogService, + private fb: FormBuilder, + private translate: TranslateService, + private data: DataService, + private sidebar: SidebarService, + private route: ActivatedRoute) { + super("ScheduledEvent", ["id", "interval", "name", "description", "channel_id", "start_time", "end_time", "type", "location"], + (oldElement: ScheduledEvent, newElement: ScheduledEvent) => { + return oldElement.name === newElement.name; + }); + } + + public ngOnInit(): void { + this.loading = true; + this.setFilterForm(); + this.data.getServerFromRoute(this.route).then(async server => { + this.server = server; + let authUser = await this.authService.getLoggedInUser(); + this.user = authUser?.users?.find(u => u.server == this.server.id) ?? null; + }); + } + + public ngOnDestroy(): void { + this.unsubscriber.next(); + this.unsubscriber.complete(); + } + + public loadNextPage(): void { + this.data.query(Queries.scheduledEventQuery, { + serverId: this.server.id, filter: this.filter, page: this.page, sort: this.sort + }, + (data: Query) => { + return data.servers[0]; + } + ).subscribe(data => { + this.totalRecords = data.scheduledEventCount; + this.scheduledEvents = data.scheduledEvents; + this.spinner.hideSpinner(); + this.loading = false; + }); + } + + public setFilterForm(): void { + this.filterForm = this.fb.group({ + id: new FormControl(null), + interval: new FormControl(null), + name: new FormControl(null), + description: new FormControl(null), + channelId: new FormControl(null), + startTime: new FormControl(null), + endTime: new FormControl(null), + entityType: new FormControl(null), + location: new FormControl(null), + }); + + this.filterForm.valueChanges.pipe( + takeUntil(this.unsubscriber), + debounceTime(600) + ).subscribe(changes => { + if (changes.id) { + this.filter.id = changes.id; + } else { + this.filter.id = undefined; + } + + if (changes.interval) { + this.filter.interval = changes.interval; + } else { + this.filter.interval = undefined; + } + + if (changes.name) { + this.filter.name = changes.name; + } else { + this.filter.name = undefined; + } + + if (changes.description) { + this.filter.description = changes.description; + } else { + this.filter.description = undefined; + } + + if (changes.channelId) { + this.filter.channelId = changes.channelId; + } else { + this.filter.channelId = undefined; + } + + if (changes.startTime) { + this.filter.startTime = changes.startTime; + } else { + this.filter.startTime = undefined; + } + + if (changes.endTime) { + this.filter.endTime = changes.endTime; + } else { + this.filter.endTime = undefined; + } + + if (changes.entityType) { + this.filter.entityType = changes.entityType; + } else { + this.filter.entityType = undefined; + } + + if (changes.location) { + this.filter.location = changes.location; + } else { + this.filter.location = undefined; + } + + if (this.page.pageSize) + this.page.pageSize = 10; + + if (this.page.pageIndex) + this.page.pageIndex = 0; + + this.loadNextPage(); + }); + } + + public newScheduledEventTemplate: ScheduledEvent = { + createdAt: "", + modifiedAt: "" + }; + + public nextPage(event: LazyLoadEvent): void { + this.page.pageSize = event.rows ?? 0; + if (event.first != null && event.rows != null) + this.page.pageIndex = event.first / event.rows; + this.sort.sortColumn = event.sortField ?? undefined; + this.sort.sortDirection = event.sortOrder === 1 ? SortDirection.ASC : event.sortOrder === -1 ? SortDirection.DESC : SortDirection.ASC; + + this.loadNextPage(); + } + + public resetFilters(): void { + this.filterForm.reset(); + } + + public onRowEditInit(table: Table, event: ScheduledEvent, index: number): void { + this.editableScheduledEvent = event; + } + + public override onRowEditSave(newScheduledEvent: ScheduledEvent): void { + if (this.isEditingNew && JSON.stringify(newScheduledEvent) === JSON.stringify(this.newScheduledEventTemplate)) { + this.isEditingNew = false; + return; + } + + if (this.isEditingNew) { + this.spinner.showSpinner(); + this.data.mutation(Mutations.createScheduledEvent, { + name: newScheduledEvent.name, + serverId: this.server.id + } + ).pipe(catchError(err => { + this.isEditingNew = false; + this.spinner.hideSpinner(); + return throwError(err); + })).subscribe(result => { + this.isEditingNew = false; + this.spinner.hideSpinner(); + this.toastService.success(this.translate.instant("view.server.ScheduledEvents.message.scheduled_event_create"), this.translate.instant("view.server.ScheduledEvents.message.scheduled_event_create_d", { name: result.scheduledEvent.createScheduledEvent?.name })); + this.loadNextPage(); + }); + return; + } + + this.spinner.showSpinner(); + this.data.mutation(Mutations.updateScheduledEvent, { + id: newScheduledEvent.id, + name: newScheduledEvent.name, + } + ).pipe(catchError(err => { + this.spinner.hideSpinner(); + return throwError(err); + })).subscribe(_ => { + this.spinner.hideSpinner(); + this.toastService.success(this.translate.instant("view.server.ScheduledEvents.message.scheduled_event_update"), this.translate.instant("view.server.ScheduledEvents.message.scheduled_event_update_d", { name: newScheduledEvent.name })); + this.loadNextPage(); + }); + } + + public deleteScheduledEvent(ScheduledEvent: ScheduledEvent): void { + this.confirmDialog.confirmDialog( + this.translate.instant("view.server.ScheduledEvents.message.scheduled_event_delete"), this.translate.instant("view.server.ScheduledEvents.message.scheduled_event_delete_q", { name: ScheduledEvent.name }), + () => { + this.spinner.showSpinner(); + this.data.mutation(Mutations.deleteScheduledEvent, { + id: ScheduledEvent.id + } + ).pipe(catchError(err => { + this.spinner.hideSpinner(); + return throwError(err); + })).subscribe(l => { + this.spinner.hideSpinner(); + this.toastService.success(this.translate.instant("view.server.ScheduledEvents.message.scheduled_event_deleted"), this.translate.instant("view.server.ScheduledEvents.message.scheduled_event_deleted_d", { name: ScheduledEvent.name })); + this.loadNextPage(); + }); + }); + } + + public addScheduledEvent(table: Table): void { + this.editableScheduledEvent = JSON.parse(JSON.stringify(this.newScheduledEventTemplate)); + // const newScheduledEvent = JSON.parse(JSON.stringify(this.newScheduledEventTemplate)); + // + // this.scheduledEvents = [newScheduledEvent, ...this.scheduledEvents]; + // + // table.initRowEdit(newScheduledEvent); + // + // const index = this.scheduledEvents.findIndex(l => l.id == newScheduledEvent.id); + // this.onRowEditInit(table, newScheduledEvent, index); + // + // this.isEditingNew = true; + } +} diff --git a/web/src/app/modules/view/server/scheduled-events/scheduled-events-routing.module.ts b/web/src/app/modules/view/server/scheduled-events/scheduled-events-routing.module.ts new file mode 100644 index 00000000..d0712636 --- /dev/null +++ b/web/src/app/modules/view/server/scheduled-events/scheduled-events-routing.module.ts @@ -0,0 +1,14 @@ +import { NgModule } from "@angular/core"; +import { RouterModule, Routes } from "@angular/router"; +import { ScheduledEventsComponent } from "./components/scheduled-events/scheduled-events.component"; + +const routes: Routes = [ + { path: "", component: ScheduledEventsComponent } +]; + +@NgModule({ + imports: [RouterModule.forChild(routes)], + exports: [RouterModule] +}) +export class ScheduledEventsRoutingModule { +} diff --git a/web/src/app/modules/view/server/scheduled-events/scheduled-events.module.ts b/web/src/app/modules/view/server/scheduled-events/scheduled-events.module.ts new file mode 100644 index 00000000..752b6ce7 --- /dev/null +++ b/web/src/app/modules/view/server/scheduled-events/scheduled-events.module.ts @@ -0,0 +1,21 @@ +import { NgModule } from '@angular/core'; +import { CommonModule } from '@angular/common'; + +import { ScheduledEventsRoutingModule } from './scheduled-events-routing.module'; +import { ScheduledEventsComponent } from "./components/scheduled-events/scheduled-events.component"; +import { SharedModule } from "../../../shared/shared.module"; +import { EditScheduledEventDialogComponent } from './components/edit-scheduled-event-dialog/edit-scheduled-event-dialog.component'; + + +@NgModule({ + declarations: [ + ScheduledEventsComponent, + EditScheduledEventDialogComponent + ], + imports: [ + CommonModule, + SharedModule, + ScheduledEventsRoutingModule + ] +}) +export class ScheduledEventsModule { } diff --git a/web/src/app/modules/view/server/server-routing.module.ts b/web/src/app/modules/view/server/server-routing.module.ts index 505aa609..310e44a5 100644 --- a/web/src/app/modules/view/server/server-routing.module.ts +++ b/web/src/app/modules/view/server/server-routing.module.ts @@ -19,6 +19,7 @@ const routes: Routes = [ { path: "levels", loadChildren: () => import("./levels/levels.module").then(m => m.LevelsModule), canActivate: [AuthGuard], data: { memberRole: MemberRoles.Moderator } }, { path: "achievements", loadChildren: () => import("./achievements/achievements.module").then(m => m.AchievementsModule), canActivate: [AuthGuard], data: { memberRole: MemberRoles.Moderator } }, { path: "short-role-names", loadChildren: () => import("./short-role-name/short-role-name.module").then(m => m.ShortRoleNameModule), canActivate: [AuthGuard], data: { memberRole: MemberRoles.Moderator } }, + { path: "scheduled-events", loadChildren: () => import("./scheduled-events/scheduled-events.module").then(m => m.ScheduledEventsModule), canActivate: [AuthGuard], data: { memberRole: MemberRoles.Moderator } }, { path: "config", loadChildren: () => import("./config/config.module").then(m => m.ConfigModule), canActivate: [AuthGuard], data: { memberRole: MemberRoles.Admin } } ]; diff --git a/web/src/app/modules/view/server/short-role-name/short-role-name.module.ts b/web/src/app/modules/view/server/short-role-name/short-role-name.module.ts index b675df35..dd6e101b 100644 --- a/web/src/app/modules/view/server/short-role-name/short-role-name.module.ts +++ b/web/src/app/modules/view/server/short-role-name/short-role-name.module.ts @@ -1,14 +1,8 @@ -import { NgModule } from '@angular/core'; -import { CommonModule } from '@angular/common'; -import { ShortRoleNamesComponent } from './components/short-role-names/short-role-names.component'; +import { NgModule } from "@angular/core"; +import { CommonModule } from "@angular/common"; +import { ShortRoleNamesComponent } from "./components/short-role-names/short-role-names.component"; import { ShortRoleNameRoutingModule } from "./short-role-name-routing.module"; -import { ButtonModule } from "primeng/button"; -import { InputTextModule } from "primeng/inputtext"; -import { ReactiveFormsModule } from "@angular/forms"; import { SharedModule } from "../../../shared/shared.module"; -import { TableModule } from "primeng/table"; -import { TranslateModule } from "@ngx-translate/core"; - @NgModule({ @@ -18,13 +12,7 @@ import { TranslateModule } from "@ngx-translate/core"; imports: [ CommonModule, ShortRoleNameRoutingModule, - ButtonModule, - InputTextModule, - ReactiveFormsModule, SharedModule, - SharedModule, - TableModule, - TranslateModule ] }) export class ShortRoleNameModule { } diff --git a/web/src/app/services/sidebar/sidebar.service.ts b/web/src/app/services/sidebar/sidebar.service.ts index 2a1f3861..285b3a8f 100644 --- a/web/src/app/services/sidebar/sidebar.service.ts +++ b/web/src/app/services/sidebar/sidebar.service.ts @@ -30,6 +30,7 @@ export class SidebarService { serverAutoRoles: MenuItem = {}; serverLevels: MenuItem = {}; serverAchievements: MenuItem = {}; + serverScheduledEvents: MenuItem = {}; serverShortRoleNames: MenuItem = {}; serverConfig: MenuItem = {}; serverMenu: MenuItem = {}; @@ -110,6 +111,13 @@ export class SidebarService { routerLink: `server/${this.server?.id}/achievements` }; + this.serverScheduledEvents = { + label: this.isSidebarOpen ? this.translateService.instant("sidebar.server.scheduled_events") : "", + icon: "pi pi-calender", + visible: true, + routerLink: `server/${this.server?.id}/scheduled-events` + }; + this.serverShortRoleNames = { label: this.isSidebarOpen ? this.translateService.instant("sidebar.server.short_role_names") : "", icon: "pi pi-list", @@ -129,7 +137,7 @@ export class SidebarService { icon: "pi pi-server", visible: false, expanded: true, - items: [this.serverDashboard, this.serverProfile, this.serverMembers, this.serverAutoRoles, this.serverLevels, this.serverAchievements, this.serverShortRoleNames, this.serverConfig] + items: [this.serverDashboard, this.serverProfile, this.serverMembers, this.serverAutoRoles, this.serverLevels, this.serverAchievements, this.serverScheduledEvents, this.serverShortRoleNames, this.serverConfig] }; this.adminConfig = { label: this.isSidebarOpen ? this.translateService.instant("sidebar.config") : "", @@ -205,6 +213,7 @@ export class SidebarService { this.serverAutoRoles.visible = isTechnicianAndFullAccessActive || this.hasFeature("AutoRoleModule") && user?.isModerator; this.serverLevels.visible = isTechnicianAndFullAccessActive || this.hasFeature("LevelModule") && user?.isModerator; this.serverAchievements.visible = isTechnicianAndFullAccessActive || this.hasFeature("AchievementsModule") && user?.isModerator; + this.serverScheduledEvents.visible = isTechnicianAndFullAccessActive || this.hasFeature("ScheduledEvents") && user?.isModerator; this.serverShortRoleNames.visible = isTechnicianAndFullAccessActive || this.hasFeature("ShortRoleName") && user?.isAdmin; this.serverConfig.visible = isTechnicianAndFullAccessActive || user?.isAdmin; diff --git a/web/src/assets/i18n/de.json b/web/src/assets/i18n/de.json index e8a6e082..845e8a17 100644 --- a/web/src/assets/i18n/de.json +++ b/web/src/assets/i18n/de.json @@ -124,12 +124,14 @@ }, "common": { "404": "404 - Der Eintrag konnte nicht gefunden werden", + "abort": "Abbrechen", "actions": "Aktionen", "active": "Aktiv", "add": "Hinzufügen", "attribute": "Attribut", "auth_role": "Rolle", "author": "Autor", + "back": "Zurück", "bool_as_string": { "false": "Nein", "true": "Ja" @@ -137,12 +139,14 @@ "channel_id": "Kanal Id", "channel_name": "Kanal", "color": "Farbe", + "continue": "Weiter", "created_at": "Erstellt am", "description": "Beschreibung", "discord_id": "Discord Id", "edit": "Bearbeiten", "email": "E-Mail", "emoji": "Emoji", + "end_time": "Endzeit", "error": "Fehler", "export": "Exportieren", "feature_flags": "Funktionen", @@ -176,11 +180,13 @@ }, "id": "Id", "import": "Importieren", + "interval": "Interval", "joined_at": "Beigetreten am", "last_name": "Nachname", "leaved_at": "Verlassen am", "left_server": "Aktiv", "level": "Level", + "location": "Ort", "message_id": "Nachricht Id", "min_xp": "Min. XP", "modified_at": "Bearbeitet am", @@ -200,10 +206,12 @@ "role": "Rolle", "rule_count": "Regeln", "save": "Speichern", + "start_time": "Startzeit", "state": { "off": "Aus", "on": "Ein" }, + "type": "Typ", "user_warnings": "Verwarnungen", "users": "Benutzer", "value": "Wert", @@ -538,6 +546,33 @@ "reaction_count": "Anzahl Reaktionen", "xp": "XP" }, + "scheduled_events": { + "edit_dialog": { + "add_header": "Event hinzufügen", + "edit_header": "Event bearbeiten", + "event_info": { + "description_input": "Erzähl den Leuten ein wenig mehr über dein Event. Markdown, neue Zeilen und Links werden unterstützt.", + "event_topic": "Thema", + "event_topic_input": "Worum geht es bei deinem Event?", + "header": "Worum geht es bei deinem Event?", + "start_date": "Startdatum", + "start_time": "Startzeit", + "tab_name": "Eventinformationen" + }, + "location": { + "header": "Wo ist dein Event?", + "somewhere_else": "Irgendwo anders", + "somewhere_else_input": "Ort eingeben", + "stage": "Stage-Kanal", + "stage_input": "Stage-Kanal auswählen", + "tab_name": "Verzeichnis", + "voice": "Sprachkanal", + "voice_input": "Sprachkanal auswählen" + } + }, + "header": "Geplante Events", + "scheduled_events": "Geplante Events" + }, "short_role_names": { "header": "Rollen Kürzel", "message": { diff --git a/web/src/assets/i18n/en.json b/web/src/assets/i18n/en.json index 4f324ec6..86a3cd2a 100644 --- a/web/src/assets/i18n/en.json +++ b/web/src/assets/i18n/en.json @@ -124,12 +124,14 @@ }, "common": { "404": "404 - Entry not found!", + "abort": "Abort", "actions": "Actions", "active": "Active", "add": "Add", "attribute": "Attribute", "auth_role": "Role", "author": "Author", + "back": "Back", "bool_as_string": { "false": "No", "true": "Yes" @@ -137,6 +139,7 @@ "channel_id": "Channel Id", "channel_name": "Channel", "color": "Color", + "continue": "Continue", "created_at": "Created at", "description": "Description", "discord_id": "Discord Id", @@ -538,6 +541,33 @@ "reaction_count": "Reaction count", "xp": "XP" }, + "scheduled_events": { + "edit_dialog": { + "add_header": "Add event", + "edit_header": "Edit event", + "event_info": { + "description_input": "Tell people a little more about your event. Markdown, new lines and links are supported.", + "event_topic": "Event topic", + "event_topic_input": "What's your event?", + "header": "What's your event about?", + "start_date": "Start date", + "start_time": "Start time", + "tab_name": "Event info" + }, + "location": { + "header": "Where is your event?", + "somewhere_else": "Somewhere else", + "somewhere_else_input": "Enter a location", + "stage": "Stage channel", + "stage_input": "Select a stage channel", + "tab_name": "Location", + "voice": "Voice channel", + "voice_input": "Select a voice channel" + } + }, + "header": "Scheduled events", + "scheduled_events": "Scheduled events" + }, "short_role_names": { "header": "Level", "message": { diff --git a/web/src/styles.scss b/web/src/styles.scss index 64751ea5..3878c311 100644 --- a/web/src/styles.scss +++ b/web/src/styles.scss @@ -635,6 +635,18 @@ footer { border: 0; } +.btn, +.icon-btn, +.text-btn, +.danger-btn, +.danger-icon-btn { + span { + transition-duration: unset !important; + } + + transition: none !important; +} + .spinner-component-wrapper { position: absolute; top: 0; @@ -661,6 +673,27 @@ p-inputNumber { border: none !important; } +.edit-dialog { + .p-dialog-content { + padding: 0 !important; + + .p-tabview-nav { + justify-content: space-between; + + li { + width: 100%; + + a { + width: 100%; + justify-content: center; + } + } + } + + + } +} + @media (max-width: 720px) { footer { .left, diff --git a/web/src/styles/themes/sh-edraft-dark-theme.scss b/web/src/styles/themes/sh-edraft-dark-theme.scss index 6f483f02..f7b2f949 100644 --- a/web/src/styles/themes/sh-edraft-dark-theme.scss +++ b/web/src/styles/themes/sh-edraft-dark-theme.scss @@ -552,6 +552,7 @@ } } + .danger-btn, .danger-icon-btn { background-color: transparent !important; color: $primaryTextColor !important; @@ -568,22 +569,6 @@ } } - .danger-btn { - background-color: $primaryErrorColor !important; - color: $primaryErrorColor !important; - border: 0 !important; - - &:hover { - background-color: $primaryErrorColor !important; - color: $primaryTextColor !important; - border: 0; - } - - .pi { - font-size: 1.275rem !important; - } - } - .p-datatable .p-sortable-column.p-highlight, .p-datatable .p-sortable-column.p-highlight .p-sortable-column-icon, .p-datatable .p-sortable-column:not(.p-highlight):hover { @@ -777,4 +762,26 @@ } } } + + .edit-dialog { + .p-dialog-content { + .p-tabview { + .p-tabview-nav li .p-tabview-nav-link:not(.p-disabled):focus { + box-shadow: none !important; + } + + .p-tabview-nav li.p-highlight .p-tabview-nav-link { + color: $primaryHeaderColor !important; + border-color: $primaryHeaderColor !important; + } + + .p-tabview-nav, + .p-tabview-nav li .p-tabview-nav-link, + .p-tabview-panels { + background-color: $secondaryBackgroundColor !important; + color: $primaryTextColor !important; + } + } + } + } } From 74dba4b98123e95c414038d6096e4c566ac5dfd8 Mon Sep 17 00:00:00 2001 From: Sven Heidemann Date: Sat, 18 Nov 2023 22:15:18 +0100 Subject: [PATCH 05/10] Added add dialog #410 --- bot/src/bot_data/model/scheduled_event.py | 15 +- .../model/scheduled_event_interval_enum.py | 8 + .../scripts/1.2.2/1_ScheduledEvents_up.sql | 8 +- .../scheduled_event_repository_service.py | 23 +-- bot/src/bot_graphql/abc/filter_abc.py | 6 +- .../filter/scheduled_event_filter.py | 18 +-- bot/src/bot_graphql/mutation.py | 3 + .../mutations/scheduled_event_mutation.py | 25 ++-- web/package.json | 110 +++++++------- web/src/app/models/data/discord.model.ts | 5 +- .../app/models/data/scheduled_events.model.ts | 13 +- web/src/app/models/graphql/mutations.model.ts | 28 ++-- web/src/app/modules/shared/shared.module.ts | 11 +- ...edit-scheduled-event-dialog.component.html | 110 ++++++++++---- .../edit-scheduled-event-dialog.component.ts | 139 +++++++++++++++--- .../scheduled-events.component.html | 128 ++++------------ .../scheduled-events.component.ts | 20 ++- .../scheduled-events.module.ts | 16 +- .../app/services/sidebar/sidebar.service.ts | 4 +- web/src/assets/i18n/de.json | 14 +- web/src/assets/i18n/en.json | 1 + web/src/assets/version.json | 12 +- web/src/styles.scss | 34 +++++ web/src/styles/primeng-fixes.scss | 1 + .../styles/themes/sh-edraft-dark-theme.scss | 30 ++++ 25 files changed, 504 insertions(+), 278 deletions(-) create mode 100644 bot/src/bot_data/model/scheduled_event_interval_enum.py diff --git a/bot/src/bot_data/model/scheduled_event.py b/bot/src/bot_data/model/scheduled_event.py index fa05c946..3f8fbee3 100644 --- a/bot/src/bot_data/model/scheduled_event.py +++ b/bot/src/bot_data/model/scheduled_event.py @@ -4,13 +4,14 @@ from typing import Optional import discord from cpl_core.database import TableABC +from bot_data.model.scheduled_event_interval_enum import ScheduledEventIntervalEnum from bot_data.model.server import Server class ScheduledEvent(TableABC): def __init__( self, - interval: str, + interval: ScheduledEventIntervalEnum, name: str, description: str, channel_id: int, @@ -43,11 +44,11 @@ class ScheduledEvent(TableABC): return self._id @property - def interval(self) -> str: + def interval(self) -> ScheduledEventIntervalEnum: return self._interval @interval.setter - def interval(self, value: str): + def interval(self, value: ScheduledEventIntervalEnum): self._interval = value @property @@ -145,11 +146,11 @@ class ScheduledEvent(TableABC): return str( f""" INSERT INTO `ScheduledEvents` ( - `Interval`, `Name`, `Description`, `ChannelId`, `StartTime`, `EndTime`, `EntityType`, `Location`, `ServerId`, + `Interval`, `Name`, `Description`, `ChannelId`, `StartTime`, `EndTime`, `EntityType`, `Location`, `ServerId` ) VALUES ( - '{self._interval}', + '{self._interval.value}', '{self._name}', - '{self._description}', + {"NULL" if self._description is None else f"'{self._description}'"}, {"NULL" if self._channel_id is None else f"'{self._channel_id}'"}, '{self._start_time}', {"NULL" if self._end_time is None else f"'{self._end_time}'"}, @@ -165,7 +166,7 @@ class ScheduledEvent(TableABC): return str( f""" UPDATE `ScheduledEvents` - SET `Interval` = '{self._interval}', + SET `Interval` = '{self._interval.value}', `Name` = '{self._name}', `Description` = '{self._start_time}', `ChannelId` = {"NULL" if self._channel_id is None else f"'{self._channel_id}'"}, diff --git a/bot/src/bot_data/model/scheduled_event_interval_enum.py b/bot/src/bot_data/model/scheduled_event_interval_enum.py new file mode 100644 index 00000000..7f13c589 --- /dev/null +++ b/bot/src/bot_data/model/scheduled_event_interval_enum.py @@ -0,0 +1,8 @@ +from enum import Enum + + +class ScheduledEventIntervalEnum(Enum): + daily = "daily" + weekly = "weekly" + monthly = "monthly" + yearly = "yearly" diff --git a/bot/src/bot_data/scripts/1.2.2/1_ScheduledEvents_up.sql b/bot/src/bot_data/scripts/1.2.2/1_ScheduledEvents_up.sql index 2768651e..843c21fc 100644 --- a/bot/src/bot_data/scripts/1.2.2/1_ScheduledEvents_up.sql +++ b/bot/src/bot_data/scripts/1.2.2/1_ScheduledEvents_up.sql @@ -1,9 +1,9 @@ CREATE TABLE IF NOT EXISTS `ScheduledEvents` ( `Id` BIGINT NOT NULL AUTO_INCREMENT, - `Interval` VARCHAR(255) NOT NULL, + `Interval` ENUM ('daily', 'weekly', 'monthly', 'yearly') NOT NULL, `Name` VARCHAR(255) NOT NULL, - `Description` VARCHAR(255) NOT NULL, + `Description` VARCHAR(255) NULL, `ChannelId` BIGINT NULL, `StartTime` DATETIME(6) NOT NULL, `EndTime` DATETIME(6) NULL, @@ -19,9 +19,9 @@ CREATE TABLE IF NOT EXISTS `ScheduledEvents` CREATE TABLE IF NOT EXISTS `ScheduledEventsHistory` ( `Id` BIGINT(20) NOT NULL, - `Interval` VARCHAR(255) NOT NULL, + `Interval` ENUM ('daily', 'weekly', 'monthly', 'yearly') NOT NULL, `Name` VARCHAR(255) NOT NULL, - `Description` VARCHAR(255) NOT NULL, + `Description` VARCHAR(255) NULL, `ChannelId` BIGINT NULL, `StartTime` DATETIME(6) NOT NULL, `EndTime` DATETIME(6) NULL, diff --git a/bot/src/bot_data/service/scheduled_event_repository_service.py b/bot/src/bot_data/service/scheduled_event_repository_service.py index 7d5e67ba..01d4fc6c 100644 --- a/bot/src/bot_data/service/scheduled_event_repository_service.py +++ b/bot/src/bot_data/service/scheduled_event_repository_service.py @@ -7,6 +7,7 @@ from bot_core.logging.database_logger import DatabaseLogger from bot_data.abc.server_repository_abc import ServerRepositoryABC from bot_data.abc.scheduled_event_repository_abc import ScheduledEventRepositoryABC from bot_data.model.scheduled_event import ScheduledEvent +from bot_data.model.scheduled_event_interval_enum import ScheduledEventIntervalEnum class ScheduledEventRepositoryService(ScheduledEventRepositoryABC): @@ -32,17 +33,17 @@ class ScheduledEventRepositoryService(ScheduledEventRepositoryABC): def _scheduled_event_from_result(self, sql_result: tuple) -> ScheduledEvent: return ScheduledEvent( - self._get_value_from_result(sql_result[0]), # interval - self._get_value_from_result(sql_result[1]), # name - self._get_value_from_result(sql_result[2]), # description - int(self._get_value_from_result(sql_result[3])), # channel_id - self._get_value_from_result(sql_result[4]), # start_time - self._get_value_from_result(sql_result[5]), # end_time - self._get_value_from_result(sql_result[6]), # entity_type - self._get_value_from_result(sql_result[7]), # location - self._servers.get_server_by_id((sql_result[8])), # server - self._get_value_from_result(sql_result[9]), # created_at - self._get_value_from_result(sql_result[10]), # modified_at + self._get_value_from_result(ScheduledEventIntervalEnum(sql_result[1])), # interval + self._get_value_from_result(sql_result[2]), # name + self._get_value_from_result(sql_result[3]), # description + int(self._get_value_from_result(sql_result[4])), # channel_id + self._get_value_from_result(sql_result[5]), # start_time + self._get_value_from_result(sql_result[6]), # end_time + self._get_value_from_result(sql_result[7]), # entity_type + self._get_value_from_result(sql_result[8]), # location + self._servers.get_server_by_id((sql_result[9])), # server + self._get_value_from_result(sql_result[10]), # created_at + self._get_value_from_result(sql_result[11]), # modified_at id=self._get_value_from_result(sql_result[0]), ) diff --git a/bot/src/bot_graphql/abc/filter_abc.py b/bot/src/bot_graphql/abc/filter_abc.py index 7c1fa477..3067b075 100644 --- a/bot/src/bot_graphql/abc/filter_abc.py +++ b/bot/src/bot_graphql/abc/filter_abc.py @@ -63,7 +63,9 @@ class FilterABC(ABC): self.__setattr__(f"_{attr}", attr_type(values[attr])) @staticmethod - def _filter_by_attributes(attrs: list[Callable], values: List[T]) -> List[R]: + def _filter_by_attributes(attrs: list[dict], values: List[T]) -> List[R]: for attr in attrs: - values = values.where(attr) + if attr["attr"] is None: + continue + values = values.where(attr["func"]) return values diff --git a/bot/src/bot_graphql/filter/scheduled_event_filter.py b/bot/src/bot_graphql/filter/scheduled_event_filter.py index d1937c25..e98be02b 100644 --- a/bot/src/bot_graphql/filter/scheduled_event_filter.py +++ b/bot/src/bot_graphql/filter/scheduled_event_filter.py @@ -51,15 +51,15 @@ class ScheduledEventFilter(FilterABC): query = self._filter_by_attributes( [ - lambda x: x.id == self._id, - lambda x: x.interval == self._interval, - lambda x: x.name == self._name, - lambda x: x.description == self._description, - lambda x: x.channel_id == self._channel_id, - lambda x: x.start_time == self._start_time, - lambda x: x.end_time == self._end_time, - lambda x: x.entity_type == self._entity_type, - lambda x: x.location == self._location, + {"attr": self._id, "func": lambda x: x.id == self._id}, + {"attr": self._interval, "func": lambda x: x.interval == self._interval}, + {"attr": self._name, "func": lambda x: x.name == self._name}, + {"attr": self._description, "func": lambda x: x.description == self._description}, + {"attr": self._channel_id, "func": lambda x: x.channel_id == self._channel_id}, + {"attr": self._start_time, "func": lambda x: x.start_time == self._start_time}, + {"attr": self._end_time, "func": lambda x: x.end_time == self._end_time}, + {"attr": self._entity_type, "func": lambda x: x.entity_type == self._entity_type}, + {"attr": self._location, "func": lambda x: x.location == self._location}, ], query, ) diff --git a/bot/src/bot_graphql/mutation.py b/bot/src/bot_graphql/mutation.py index 39e38cc5..86b269d0 100644 --- a/bot/src/bot_graphql/mutation.py +++ b/bot/src/bot_graphql/mutation.py @@ -4,6 +4,7 @@ from bot_graphql.mutations.achievement_mutation import AchievementMutation from bot_graphql.mutations.auto_role_mutation import AutoRoleMutation from bot_graphql.mutations.auto_role_rule_mutation import AutoRoleRuleMutation from bot_graphql.mutations.level_mutation import LevelMutation +from bot_graphql.mutations.scheduled_event_mutation import ScheduledEventMutation from bot_graphql.mutations.server_config_mutation import ServerConfigMutation from bot_graphql.mutations.short_role_name_mutation import ShortRoleNameMutation from bot_graphql.mutations.technician_config_mutation import TechnicianConfigMutation @@ -23,6 +24,7 @@ class Mutation(MutationType): achievement_mutation: AchievementMutation, user_joined_game_server: UserJoinedGameServerMutation, technician_config: TechnicianConfigMutation, + scheduled_event: ScheduledEventMutation, server_config: ServerConfigMutation, short_role_name_mutation: ShortRoleNameMutation, ): @@ -36,4 +38,5 @@ class Mutation(MutationType): self.set_field("userJoinedGameServer", lambda *_: user_joined_game_server) self.set_field("shortRoleName", lambda *_: short_role_name_mutation) self.set_field("technicianConfig", lambda *_: technician_config) + self.set_field("scheduledEvent", lambda *_: scheduled_event) self.set_field("serverConfig", lambda *_: server_config) diff --git a/bot/src/bot_graphql/mutations/scheduled_event_mutation.py b/bot/src/bot_graphql/mutations/scheduled_event_mutation.py index c138b082..81353c62 100644 --- a/bot/src/bot_graphql/mutations/scheduled_event_mutation.py +++ b/bot/src/bot_graphql/mutations/scheduled_event_mutation.py @@ -1,9 +1,12 @@ +from datetime import datetime + from cpl_core.database.context import DatabaseContextABC from cpl_discord.service import DiscordBotServiceABC from bot_data.abc.server_repository_abc import ServerRepositoryABC from bot_data.abc.scheduled_event_repository_abc import ScheduledEventRepositoryABC from bot_data.model.scheduled_event import ScheduledEvent +from bot_data.model.scheduled_event_interval_enum import ScheduledEventIntervalEnum from bot_data.model.user_role_enum import UserRoleEnum from bot_graphql.abc.query_abc import QueryABC from modules.permission.service.permission_service import PermissionService @@ -35,14 +38,14 @@ class ScheduledEventMutation(QueryABC): self._can_user_mutate_data(server, UserRoleEnum.moderator) scheduled_event = ScheduledEvent( - input["interval"], + ScheduledEventIntervalEnum(input["interval"]), input["name"], - input["description"], - input["channel_id"], - input["start_time"], - input["end_time"], - input["entity_type"], - input["location"], + input["description"] if "description" in input else None, + input["channelId"] if "channelId" in input else None, + datetime.strptime(input["startTime"], "%Y-%m-%dT%H:%M:%S.%fZ"), + datetime.strptime(input["endTime"], "%Y-%m-%dT%H:%M:%S.%fZ") if "endTime" in input else None, + input["entityType"], + input["location"] if "location" in input else None, server, ) @@ -70,10 +73,10 @@ class ScheduledEventMutation(QueryABC): scheduled_event.interval = input["interval"] if "interval" in input else scheduled_event.interval scheduled_event.name = input["name"] if "name" in input else scheduled_event.name scheduled_event.description = input["description"] if "description" in input else scheduled_event.description - scheduled_event.channel_id = input["channel_id"] if "channel_id" in input else scheduled_event.channel_id - scheduled_event.start_time = input["start_time"] if "start_time" in input else scheduled_event.start_time - scheduled_event.end_time = input["end_time"] if "end_time" in input else scheduled_event.end_time - scheduled_event.entity_type = input["entity_type"] if "entity_type" in input else scheduled_event.entity_type + scheduled_event.channel_id = input["channelId"] if "channelId" in input else scheduled_event.channel_id + scheduled_event.start_time = input["startTime"] if "startTime" in input else scheduled_event.start_time + scheduled_event.end_time = input["endTime"] if "endTime" in input else scheduled_event.end_time + scheduled_event.entity_type = input["entityType"] if "entityType" in input else scheduled_event.entity_type scheduled_event.location = input["location"] if "location" in input else scheduled_event.location self._scheduled_events.update_scheduled_event(scheduled_event) diff --git a/web/package.json b/web/package.json index 3255abc5..281eca54 100644 --- a/web/package.json +++ b/web/package.json @@ -1,56 +1,56 @@ { - "name": "web", - "version": "1.2.2", - "scripts": { - "ng": "ng", - "update-version": "ts-node update-version.ts", - "prestart": "npm run update-version", - "start": "ng serve", - "prebuild": "npm run update-version", - "build": "ng build", - "watch": "ng build --watch --configuration development", - "test": "ng test", - "gv": "echo $npm_package_version", - "predocker-build": "npm run update-version", - "docker-build": "export VERSION=$npm_package_version; ng build; docker build -t sh-edraft.de/sdb-web:$VERSION .", - "docker-build-dev": "export VERSION=$npm_package_version; ng build --configuration development; docker build -t sh-edraft.de/sdb-web:$VERSION .", - "docker-build-stage": "export VERSION=$npm_package_version; ng build --configuration staging; docker build -t sh-edraft.de/sdb-web:$VERSION ." - }, - "private": true, - "dependencies": { - "@angular/animations": "^15.1.4", - "@angular/common": "^15.1.4", - "@angular/compiler": "^15.1.4", - "@angular/core": "^15.1.4", - "@angular/forms": "^15.1.4", - "@angular/platform-browser": "^15.1.4", - "@angular/platform-browser-dynamic": "^15.1.4", - "@angular/router": "^15.1.4", - "@auth0/angular-jwt": "^5.1.0", - "@microsoft/signalr": "^6.0.9", - "@ngx-translate/core": "^14.0.0", - "@ngx-translate/http-loader": "^7.0.0", - "@types/socket.io-client": "^3.0.0", - "moment": "^2.29.4", - "primeicons": "^6.0.1", - "primeng": "^15.2.0", - "rxjs": "~7.5.0", - "socket.io-client": "^4.5.3", - "zone.js": "~0.11.4" - }, - "devDependencies": { - "@angular-devkit/build-angular": "^15.1.5", - "@angular/cli": "~15.1.5", - "@angular/compiler-cli": "^15.1.4", - "@types/jasmine": "~4.0.0", - "@types/node": "^18.11.9", - "jasmine-core": "~4.1.0", - "karma": "~6.3.0", - "karma-chrome-launcher": "~3.1.0", - "karma-coverage": "~2.2.0", - "karma-jasmine": "~5.0.0", - "karma-jasmine-html-reporter": "~1.7.0", - "tslib": "^2.4.1", - "typescript": "~4.9.5" - } -} + "name": "web", + "version": "1.2.dev410", + "scripts": { + "ng": "ng", + "update-version": "ts-node update-version.ts", + "prestart": "npm run update-version", + "start": "ng serve", + "prebuild": "npm run update-version", + "build": "ng build", + "watch": "ng build --watch --configuration development", + "test": "ng test", + "gv": "echo $npm_package_version", + "predocker-build": "npm run update-version", + "docker-build": "export VERSION=$npm_package_version; ng build; docker build -t sh-edraft.de/sdb-web:$VERSION .", + "docker-build-dev": "export VERSION=$npm_package_version; ng build --configuration development; docker build -t sh-edraft.de/sdb-web:$VERSION .", + "docker-build-stage": "export VERSION=$npm_package_version; ng build --configuration staging; docker build -t sh-edraft.de/sdb-web:$VERSION ." + }, + "private": true, + "dependencies": { + "@angular/animations": "^15.1.4", + "@angular/common": "^15.1.4", + "@angular/compiler": "^15.1.4", + "@angular/core": "^15.1.4", + "@angular/forms": "^15.1.4", + "@angular/platform-browser": "^15.1.4", + "@angular/platform-browser-dynamic": "^15.1.4", + "@angular/router": "^15.1.4", + "@auth0/angular-jwt": "^5.1.0", + "@microsoft/signalr": "^6.0.9", + "@ngx-translate/core": "^14.0.0", + "@ngx-translate/http-loader": "^7.0.0", + "@types/socket.io-client": "^3.0.0", + "moment": "^2.29.4", + "primeicons": "^6.0.1", + "primeng": "^15.2.0", + "rxjs": "~7.5.0", + "socket.io-client": "^4.5.3", + "zone.js": "~0.11.4" + }, + "devDependencies": { + "@angular-devkit/build-angular": "^15.1.5", + "@angular/cli": "~15.1.5", + "@angular/compiler-cli": "^15.1.4", + "@types/jasmine": "~4.0.0", + "@types/node": "^18.11.9", + "jasmine-core": "~4.1.0", + "karma": "~6.3.0", + "karma-chrome-launcher": "~3.1.0", + "karma-coverage": "~2.2.0", + "karma-jasmine": "~5.0.0", + "karma-jasmine-html-reporter": "~1.7.0", + "tslib": "^2.4.1", + "typescript": "~4.9.5" + } +} \ No newline at end of file diff --git a/web/src/app/models/data/discord.model.ts b/web/src/app/models/data/discord.model.ts index 6e640052..a77de21e 100644 --- a/web/src/app/models/data/discord.model.ts +++ b/web/src/app/models/data/discord.model.ts @@ -1,4 +1,4 @@ -export interface Discord { +export interface Discord { guilds?: Guild[]; users?: DiscordUser[]; } @@ -21,7 +21,8 @@ export interface Channel { export enum ChannelType { category = "CategoryChannel", text = "TextChannel", - voice = "VoiceChannel" + voice = "VoiceChannel", + stage = "StageChannel" } export interface Role { diff --git a/web/src/app/models/data/scheduled_events.model.ts b/web/src/app/models/data/scheduled_events.model.ts index c3e8beea..972c10bb 100644 --- a/web/src/app/models/data/scheduled_events.model.ts +++ b/web/src/app/models/data/scheduled_events.model.ts @@ -9,12 +9,12 @@ export enum EventType { export interface ScheduledEvent extends DataWithHistory { id?: number; - interval?: string; + interval?: ScheduledEventInterval; name?: string; description?: string; channelId?: string; - startTime?: string; - endTime?: string; + startTime?: Date; + endTime?: Date; entityType?: EventType; location?: string; server?: Server; @@ -32,3 +32,10 @@ export interface ScheduledEventFilter { location?: string; server?: ServerFilter; } + +export enum ScheduledEventInterval { + daily = "daily", + weekly = "weekly", + monthly = "monthly", + yearly = "yearly" +} diff --git a/web/src/app/models/graphql/mutations.model.ts b/web/src/app/models/graphql/mutations.model.ts index 27fd48c1..95843b64 100644 --- a/web/src/app/models/graphql/mutations.model.ts +++ b/web/src/app/models/graphql/mutations.model.ts @@ -185,14 +185,16 @@ export class Mutations { endTime: $endTime, entityType: $entityType, location: $location, - serverId: $serverId} - ) { - id + serverId: $serverId + }) { + interval name description - attribute - operator - value + channelId + startTime + endTime + entityType + location server { id } @@ -215,12 +217,17 @@ export class Mutations { location: $location, serverId: $serverId} ) { - id + interval name description - attribute - operator - value + channelId + startTime + endTime + entityType + location + server { + id + } } } } @@ -397,7 +404,6 @@ export class Mutations { `; - static createUserWarning = ` mutation createUserWarning($name: String, $description: String, $attribute: String, $operator: String, $value: String, $serverId: ID) { userWarning { diff --git a/web/src/app/modules/shared/shared.module.ts b/web/src/app/modules/shared/shared.module.ts index 2a7bfc45..af9e8ea8 100644 --- a/web/src/app/modules/shared/shared.module.ts +++ b/web/src/app/modules/shared/shared.module.ts @@ -1,4 +1,4 @@ -import { CommonModule } from "@angular/common"; +import { CommonModule, DatePipe } from "@angular/common"; import { HttpClientModule } from "@angular/common/http"; import { NgModule } from "@angular/core"; import { FormsModule, ReactiveFormsModule } from "@angular/forms"; @@ -38,6 +38,8 @@ import { FileUploadModule } from "primeng/fileupload"; import { SelectButtonModule } from "primeng/selectbutton"; import { TabViewModule } from "primeng/tabview"; import { RadioButtonModule } from "primeng/radiobutton"; +import { InputTextareaModule } from "primeng/inputtextarea"; +import { InputMaskModule } from "primeng/inputmask"; const PrimeNGModules = [ @@ -69,7 +71,9 @@ const PrimeNGModules = [ FileUploadModule, SelectButtonModule, TabViewModule, - RadioButtonModule + RadioButtonModule, + InputTextareaModule, + InputMaskModule ]; @NgModule({ @@ -102,6 +106,9 @@ const PrimeNGModules = [ MultiSelectColumnsComponent, FeatureFlagListComponent, DataImportAndExportComponent + ], + providers: [ + DatePipe ] }) export class SharedModule { diff --git a/web/src/app/modules/view/server/scheduled-events/components/edit-scheduled-event-dialog/edit-scheduled-event-dialog.component.html b/web/src/app/modules/view/server/scheduled-events/components/edit-scheduled-event-dialog/edit-scheduled-event-dialog.component.html index 938281d5..62289884 100644 --- a/web/src/app/modules/view/server/scheduled-events/components/edit-scheduled-event-dialog/edit-scheduled-event-dialog.component.html +++ b/web/src/app/modules/view/server/scheduled-events/components/edit-scheduled-event-dialog/edit-scheduled-event-dialog.component.html @@ -1,44 +1,92 @@
- + [style]="{ width: '500px', height: '575px' }">
-
- - +
+
+ {{'view.server.scheduled_events.edit_dialog.location.interval' | translate}}: + +
+ +
+
+ + +
+
+ +
+ + + +
-

- Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem - aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. - Nemo - enim - ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos - qui - ratione voluptatem sequi nesciunt. Consectetur, adipisci velit, sed quia non numquam eius modi. -

+
+
+ {{'view.server.scheduled_events.edit_dialog.event_info.event_topic' | translate}}: + +
+ +
+ {{'view.server.scheduled_events.edit_dialog.event_info.start_date_time' | translate}}: + +
+ +
+ {{'view.server.scheduled_events.edit_dialog.event_info.end_date_time' | translate}}: + +
+ +
+ {{'view.server.scheduled_events.edit_dialog.event_info.description' | translate}}: + +
+
- -
-
- -
-
- - - -
-
-
+ +
+
+ +
+
+ + + +
+
+
diff --git a/web/src/app/modules/view/server/scheduled-events/components/edit-scheduled-event-dialog/edit-scheduled-event-dialog.component.ts b/web/src/app/modules/view/server/scheduled-events/components/edit-scheduled-event-dialog/edit-scheduled-event-dialog.component.ts index ca5ff6d6..f74fb1cd 100644 --- a/web/src/app/modules/view/server/scheduled-events/components/edit-scheduled-event-dialog/edit-scheduled-event-dialog.component.ts +++ b/web/src/app/modules/view/server/scheduled-events/components/edit-scheduled-event-dialog/edit-scheduled-event-dialog.component.ts @@ -1,14 +1,26 @@ -import { Component, EventEmitter, Input, Output } from "@angular/core"; -import { EventType, ScheduledEvent } from "../../../../../../models/data/scheduled_events.model"; +import { Component, EventEmitter, Input, OnInit, Output } from "@angular/core"; +import { + EventType, + ScheduledEvent, + ScheduledEventInterval +} from "../../../../../../models/data/scheduled_events.model"; import { TranslateService } from "@ngx-translate/core"; -import { FormBuilder, FormControl, Validators } from "@angular/forms"; +import { FormBuilder, FormControl, FormGroup, Validators } from "@angular/forms"; +import { SingleDiscordQuery } from "../../../../../../models/graphql/query.model"; +import { Queries } from "../../../../../../models/graphql/queries.model"; +import { Channel, ChannelType, Guild } from "../../../../../../models/data/discord.model"; +import { DataService } from "../../../../../../services/data/data.service"; +import { SpinnerService } from "../../../../../../services/spinner/spinner.service"; +import { ActivatedRoute } from "@angular/router"; +import { Server } from "../../../../../../models/data/server.model"; +import { DatePipe } from "@angular/common"; @Component({ selector: "app-edit-scheduled-event-dialog", templateUrl: "./edit-scheduled-event-dialog.component.html", styleUrls: ["./edit-scheduled-event-dialog.component.scss"] }) -export class EditScheduledEventDialogComponent { +export class EditScheduledEventDialogComponent implements OnInit { @Input() event?: ScheduledEvent; @Output() save = new EventEmitter(); @@ -19,8 +31,9 @@ export class EditScheduledEventDialogComponent { set visible(val: boolean) { if (!val) { this.event = undefined; + this.inputForm.reset(); + this.activeIndex = 0; } - this.visible = val; } get header() { @@ -32,26 +45,118 @@ export class EditScheduledEventDialogComponent { } public activeIndex: number = 0; - public inputForm = this.fb.group({ - id: new FormControl(this.event?.id), - interval: new FormControl(this.event?.interval, [Validators.required]), - entityType: new FormControl(this.event?.entityType, [Validators.required]), - channelId: new FormControl(this.event?.channelId, this.event?.entityType == EventType.voice || this.event?.entityType == EventType.stageInstance ? [Validators.required] : []), - location: new FormControl(this.event?.location, this.event?.entityType == EventType.external ? [Validators.required] : []), - name: new FormControl(this.event?.name, [Validators.required]), - startTime: new FormControl(this.event?.startTime, [Validators.required]), - endTime: new FormControl(this.event?.endTime), - description: new FormControl(this.event?.description) - }); + public inputForm!: FormGroup<{ + entityType: FormControl; + name: FormControl; + description: FormControl; + interval: FormControl; + location: FormControl; + startTime: FormControl; + id: FormControl; + endTime: FormControl; + channelId: FormControl + }>; + server: Server = {}; + public voiceChannels: Channel[] = []; + public stageChannels: Channel[] = []; + public guild: Guild = { channels: [], emojis: [], roles: [] }; + public times: string[] = []; + public now = new Date(); + public interval = Object.keys(ScheduledEventInterval).map(k => ( + { + label: this.translate.instant(`view.server.scheduled_events.edit_dialog.location.intervals.${k}`), + value: k + } + )); constructor( private translate: TranslateService, - private fb: FormBuilder + private fb: FormBuilder, + private data: DataService, + private spinner: SpinnerService, + private route: ActivatedRoute, + private datePipe: DatePipe ) { + for (let i = 0; i < 25; i++) { + let time = ""; + if (i < 10) { + time = `0${i}`; + } else { + time = `${i}`; + } + this.times.push(`${time}:00`); + this.times.push(`${time}:15`); + this.times.push(`${time}:30`); + this.times.push(`${time}:45`); + } + this.setInputForm(); + } + + public ngOnInit() { + this.data.getServerFromRoute(this.route).then(server => { + this.server = server; + this.spinner.showSpinner(); + + this.data.query(Queries.guildsQuery, { + id: server?.discordId + } + ).subscribe(data => { + if (data.discord.guilds) { + this.guild = data.discord.guilds[0]; + } + + this.voiceChannels = this.guild.channels.filter(x => x.type === ChannelType.voice); + this.stageChannels = this.guild.channels.filter(x => x.type === ChannelType.stage); + this.setInputForm(); + this.spinner.hideSpinner(); + }); + }); + } + + public setInputForm() { + if (this.now.getMinutes() % 15 != 0) { + if (this.now.getMinutes() < 15) { + this.now.setMinutes(15); + } else if (this.now.getMinutes() < 30) { + this.now.setMinutes(30); + } else if (this.now.getMinutes() < 45) { + this.now.setMinutes(45); + } else if (this.now.getMinutes() > 45) { + this.now.setMinutes(0); + this.now.setHours(this.now.getHours() + 1); + } + } + this.now.setSeconds(0); + + this.inputForm = this.fb.group({ + id: new FormControl(this.event?.id), + interval: new FormControl(this.event?.interval, [Validators.required]), + entityType: new FormControl(this.event?.entityType, [Validators.required]), + channelId: new FormControl(this.event?.channelId, this.event?.entityType == EventType.voice || this.event?.entityType == EventType.stageInstance ? [Validators.required] : []), + location: new FormControl(this.event?.location, this.event?.entityType == EventType.external ? [Validators.required] : []), + name: new FormControl(this.event?.name, [Validators.required]), + startTime: new FormControl(this.event?.startTime ? new Date(this.event.startTime) : this.now, [Validators.required]), + endTime: new FormControl(this.event?.endTime ? new Date(this.event.endTime) : undefined), + description: new FormControl(this.event?.description) + }); } public saveEvent() { + this.event = { + id: this.inputForm.controls.id.value ?? undefined, + interval: this.inputForm.controls.interval.value ?? undefined, + name: this.inputForm.controls.name.value ?? undefined, + description: this.inputForm.controls.description.value ?? undefined, + channelId: this.inputForm.controls.channelId.value ?? undefined, + startTime: this.inputForm.controls.startTime.value ?? undefined, + endTime: this.inputForm.controls.endTime.value ?? undefined, + entityType: this.inputForm.controls.entityType.value ?? undefined, + location: this.inputForm.controls.location.value ?? undefined, + server: this.server + }; + this.save.emit(this.event); + this.event = undefined; } public next() { diff --git a/web/src/app/modules/view/server/scheduled-events/components/scheduled-events/scheduled-events.component.html b/web/src/app/modules/view/server/scheduled-events/components/scheduled-events/scheduled-events.component.html index 1296b1bd..4e2491b4 100644 --- a/web/src/app/modules/view/server/scheduled-events/components/scheduled-events/scheduled-events.component.html +++ b/web/src/app/modules/view/server/scheduled-events/components/scheduled-events/scheduled-events.component.html @@ -1,4 +1,5 @@ - +

{{'view.server.scheduled_events.header' | translate}} @@ -123,7 +124,7 @@ - +
@@ -132,12 +133,24 @@
- - - - - - + +
+ +
+ + + +
+ +
+ + + + + + @@ -148,133 +161,56 @@ {{'common.id' | translate}}: - - - {{scheduledEvent.id}} - - - {{scheduledEvent.id}} - - + {{scheduledEvent.id}} {{'common.interval' | translate}}: - - - - - - {{scheduledEvent.interval}} - - + {{scheduledEvent.interval}} {{'common.name' | translate}}: - - - - - - {{scheduledEvent.name}} - - + {{scheduledEvent.name}} {{'common.description' | translate}}: - - - - - - {{scheduledEvent.description}} - - + {{scheduledEvent.description}} {{'common.channel_id' | translate}}: - - - - - - {{scheduledEvent.channel_id}} - - + {{scheduledEvent.channelId}} {{'common.start_time' | translate}}: - - - - - - {{scheduledEvent.start_time}} - - + {{scheduledEvent.startTime}} {{'common.end_time' | translate}}: - - - - - - {{scheduledEvent.end_time}} - - + {{scheduledEvent.endTime}} {{'common.type' | translate}}: - - - - - - {{scheduledEvent.type}} - - + {{scheduledEvent.entityType}} {{'common.location' | translate}}: - - - - - - {{scheduledEvent.location}} - - + {{scheduledEvent.location}} {{'common.created_at' | translate}}: - - - {{scheduledEvent.createdAt | date:'dd.MM.yy HH:mm'}} - - - {{scheduledEvent.createdAt | date:'dd.MM.yy HH:mm'}} - - + {{scheduledEvent.createdAt | date:'dd.MM.yy HH:mm'}} {{'common.modified_at' | translate}}: - - - {{scheduledEvent.modifiedAt | date:'dd.MM.yy HH:mm'}} - - - {{scheduledEvent.modifiedAt | date:'dd.MM.yy HH:mm'}} - - + {{scheduledEvent.modifiedAt | date:'dd.MM.yy HH:mm'}}
diff --git a/web/src/app/modules/view/server/scheduled-events/components/scheduled-events/scheduled-events.component.ts b/web/src/app/modules/view/server/scheduled-events/components/scheduled-events/scheduled-events.component.ts index da0e8972..a7534dc1 100644 --- a/web/src/app/modules/view/server/scheduled-events/components/scheduled-events/scheduled-events.component.ts +++ b/web/src/app/modules/view/server/scheduled-events/components/scheduled-events/scheduled-events.component.ts @@ -118,7 +118,7 @@ export class ScheduledEventsComponent extends ComponentWithTable implements OnIn startTime: new FormControl(null), endTime: new FormControl(null), entityType: new FormControl(null), - location: new FormControl(null), + location: new FormControl(null) }); this.filterForm.valueChanges.pipe( @@ -221,7 +221,15 @@ export class ScheduledEventsComponent extends ComponentWithTable implements OnIn if (this.isEditingNew) { this.spinner.showSpinner(); this.data.mutation(Mutations.createScheduledEvent, { + id: newScheduledEvent.id, + interval: newScheduledEvent.interval, name: newScheduledEvent.name, + description: newScheduledEvent.description, + channelId: newScheduledEvent.channelId, + startTime: newScheduledEvent.startTime, + endTime: newScheduledEvent.endTime, + entityType: newScheduledEvent.entityType, + location: newScheduledEvent.location, serverId: this.server.id } ).pipe(catchError(err => { @@ -240,7 +248,15 @@ export class ScheduledEventsComponent extends ComponentWithTable implements OnIn this.spinner.showSpinner(); this.data.mutation(Mutations.updateScheduledEvent, { id: newScheduledEvent.id, + interval: newScheduledEvent.interval, name: newScheduledEvent.name, + description: newScheduledEvent.description, + channelId: newScheduledEvent.channelId, + startTime: newScheduledEvent.startTime, + endTime: newScheduledEvent.endTime, + entityType: newScheduledEvent.entityType, + location: newScheduledEvent.location, + serverId: this.server.id } ).pipe(catchError(err => { this.spinner.hideSpinner(); @@ -250,6 +266,7 @@ export class ScheduledEventsComponent extends ComponentWithTable implements OnIn this.toastService.success(this.translate.instant("view.server.ScheduledEvents.message.scheduled_event_update"), this.translate.instant("view.server.ScheduledEvents.message.scheduled_event_update_d", { name: newScheduledEvent.name })); this.loadNextPage(); }); + this.editableScheduledEvent = undefined; } public deleteScheduledEvent(ScheduledEvent: ScheduledEvent): void { @@ -272,6 +289,7 @@ export class ScheduledEventsComponent extends ComponentWithTable implements OnIn } public addScheduledEvent(table: Table): void { + this.isEditingNew = true; this.editableScheduledEvent = JSON.parse(JSON.stringify(this.newScheduledEventTemplate)); // const newScheduledEvent = JSON.parse(JSON.stringify(this.newScheduledEventTemplate)); // diff --git a/web/src/app/modules/view/server/scheduled-events/scheduled-events.module.ts b/web/src/app/modules/view/server/scheduled-events/scheduled-events.module.ts index 752b6ce7..2ba42372 100644 --- a/web/src/app/modules/view/server/scheduled-events/scheduled-events.module.ts +++ b/web/src/app/modules/view/server/scheduled-events/scheduled-events.module.ts @@ -1,10 +1,12 @@ -import { NgModule } from '@angular/core'; -import { CommonModule } from '@angular/common'; +import { NgModule } from "@angular/core"; +import { CommonModule } from "@angular/common"; -import { ScheduledEventsRoutingModule } from './scheduled-events-routing.module'; +import { ScheduledEventsRoutingModule } from "./scheduled-events-routing.module"; import { ScheduledEventsComponent } from "./components/scheduled-events/scheduled-events.component"; import { SharedModule } from "../../../shared/shared.module"; -import { EditScheduledEventDialogComponent } from './components/edit-scheduled-event-dialog/edit-scheduled-event-dialog.component'; +import { + EditScheduledEventDialogComponent +} from "./components/edit-scheduled-event-dialog/edit-scheduled-event-dialog.component"; @NgModule({ @@ -16,6 +18,8 @@ import { EditScheduledEventDialogComponent } from './components/edit-scheduled-e CommonModule, SharedModule, ScheduledEventsRoutingModule - ] + ], + exports: [] }) -export class ScheduledEventsModule { } +export class ScheduledEventsModule { +} diff --git a/web/src/app/services/sidebar/sidebar.service.ts b/web/src/app/services/sidebar/sidebar.service.ts index 285b3a8f..14c55841 100644 --- a/web/src/app/services/sidebar/sidebar.service.ts +++ b/web/src/app/services/sidebar/sidebar.service.ts @@ -4,7 +4,7 @@ import { BehaviorSubject, forkJoin, Observable } from "rxjs"; import { AuthRoles } from "../../models/auth/auth-roles.enum"; import { AuthService } from "../auth/auth.service"; import { TranslateService } from "@ngx-translate/core"; -import { NavigationEnd, Router } from "@angular/router"; +import { Router } from "@angular/router"; import { ThemeService } from "../theme/theme.service"; import { Server } from "../../models/data/server.model"; import { UserDTO } from "../../models/auth/auth-user.dto"; @@ -113,7 +113,7 @@ export class SidebarService { this.serverScheduledEvents = { label: this.isSidebarOpen ? this.translateService.instant("sidebar.server.scheduled_events") : "", - icon: "pi pi-calender", + icon: "pi pi-calendar", visible: true, routerLink: `server/${this.server?.id}/scheduled-events` }; diff --git a/web/src/assets/i18n/de.json b/web/src/assets/i18n/de.json index 845e8a17..7d70ae2d 100644 --- a/web/src/assets/i18n/de.json +++ b/web/src/assets/i18n/de.json @@ -335,6 +335,7 @@ "config": "Konfiguration", "dashboard": "Dashboard", "members": "Mitglieder", + "scheduled_events": "Geplante Events", "server": { "achievements": "Errungenschaften", "auto_roles": "Auto Rollen", @@ -343,6 +344,7 @@ "levels": "Level", "members": "Mitglieder", "profile": "Dein Profil", + "scheduled_events": "Geplante Events", "short_role_names": "Rollen Kürzel" }, "server_empty": "Kein Server ausgewählt", @@ -551,16 +553,24 @@ "add_header": "Event hinzufügen", "edit_header": "Event bearbeiten", "event_info": { + "description": "Beschreibung", "description_input": "Erzähl den Leuten ein wenig mehr über dein Event. Markdown, neue Zeilen und Links werden unterstützt.", "event_topic": "Thema", "event_topic_input": "Worum geht es bei deinem Event?", "header": "Worum geht es bei deinem Event?", - "start_date": "Startdatum", - "start_time": "Startzeit", + "start_date_time": "Startzeitpunkt", + "end_date_time": "Endzeitpunkt", "tab_name": "Eventinformationen" }, "location": { "header": "Wo ist dein Event?", + "interval": "Interval", + "intervals": { + "daily": "Täglich", + "weekly": "Wöchentlich", + "monthly": "Monatlich", + "yearly": "Jährlich" + }, "somewhere_else": "Irgendwo anders", "somewhere_else_input": "Ort eingeben", "stage": "Stage-Kanal", diff --git a/web/src/assets/i18n/en.json b/web/src/assets/i18n/en.json index 86a3cd2a..ebaa4b27 100644 --- a/web/src/assets/i18n/en.json +++ b/web/src/assets/i18n/en.json @@ -338,6 +338,7 @@ "levels": "Level", "members": "Members", "profile": "Your profile", + "scheduled_events": "Scheduled events", "short_role_names": "Short role names" }, "server_empty": "No server selected", diff --git a/web/src/assets/version.json b/web/src/assets/version.json index 0e2d8ac7..9e53173b 100644 --- a/web/src/assets/version.json +++ b/web/src/assets/version.json @@ -1,7 +1,7 @@ { - "WebVersion": { - "Major": "1", - "Minor": "2", - "Micro": "2" - } -} + "WebVersion": { + "Major": "1", + "Minor": "2", + "Micro": "dev410" + } +} \ No newline at end of file diff --git a/web/src/styles.scss b/web/src/styles.scss index 3878c311..8800861f 100644 --- a/web/src/styles.scss +++ b/web/src/styles.scss @@ -689,8 +689,42 @@ p-inputNumber { } } } + } + .form { + display: flex; + flex-direction: column; + gap: 20px; + textarea { + min-height: 101px !important; + + &:focus { + box-shadow: none !important; + } + } + + .type { + display: flex; + flex-direction: column; + gap: 10px; + + .field-checkbox { + display: flex; + gap: 15px; + } + } + + input, + .p-dropdown { + width: 100%; + } + } +} + +p-calendar { + .p-calendar { + width: 100% !important; } } diff --git a/web/src/styles/primeng-fixes.scss b/web/src/styles/primeng-fixes.scss index cf514b43..cbf7dea3 100644 --- a/web/src/styles/primeng-fixes.scss +++ b/web/src/styles/primeng-fixes.scss @@ -113,3 +113,4 @@ p-table { .pi-sort-amount-down:before { content: "\e913" !important; } + diff --git a/web/src/styles/themes/sh-edraft-dark-theme.scss b/web/src/styles/themes/sh-edraft-dark-theme.scss index f7b2f949..9d9bf6f5 100644 --- a/web/src/styles/themes/sh-edraft-dark-theme.scss +++ b/web/src/styles/themes/sh-edraft-dark-theme.scss @@ -705,6 +705,8 @@ } .p-datepicker { + color: $primaryTextColor !important; + .p-datepicker-header { color: $primaryHeaderColor !important; background-color: $primaryBackgroundColor !important; @@ -764,6 +766,19 @@ } .edit-dialog { + textarea { + background-color: $secondaryBackgroundColor; + color: $primaryTextColor; + + &:hover { + border-color: $primaryHeaderColor; + } + + &:focus { + border-color: $primaryHeaderColor; + } + } + .p-dialog-content { .p-tabview { .p-tabview-nav li .p-tabview-nav-link:not(.p-disabled):focus { @@ -784,4 +799,19 @@ } } } + + .p-radiobutton { + .p-radiobutton-box.p-highlight { + border-color: $primaryHeaderColor !important; + background: $primaryHeaderColor !important; + } + + .p-radiobutton-box:not(.p-disabled):not(.p-highlight):hover { + border-color: $primaryHeaderColor !important; + } + + .p-radiobutton-box:not(.p-disabled).p-focus { + box-shadow: none !important; + } + } } From 171aa63df9865e44592b6348ce192654b2c6e5ed Mon Sep 17 00:00:00 2001 From: Sven Heidemann Date: Sat, 18 Nov 2023 23:10:28 +0100 Subject: [PATCH 06/10] Improved update & add logic #410 --- bot/src/bot_data/model/scheduled_event.py | 2 +- .../mutations/scheduled_event_mutation.py | 17 +++-- .../queries/scheduled_event_history_query.py | 2 +- .../queries/scheduled_event_query.py | 2 +- .../app/models/data/scheduled_events.model.ts | 14 +++-- web/src/app/models/graphql/mutations.model.ts | 3 +- ...edit-scheduled-event-dialog.component.html | 4 +- .../edit-scheduled-event-dialog.component.ts | 63 +++++++++++++------ .../scheduled-events.component.html | 7 ++- .../scheduled-events.component.ts | 19 ++++-- 10 files changed, 91 insertions(+), 42 deletions(-) diff --git a/bot/src/bot_data/model/scheduled_event.py b/bot/src/bot_data/model/scheduled_event.py index 3f8fbee3..041cba28 100644 --- a/bot/src/bot_data/model/scheduled_event.py +++ b/bot/src/bot_data/model/scheduled_event.py @@ -168,7 +168,7 @@ class ScheduledEvent(TableABC): UPDATE `ScheduledEvents` SET `Interval` = '{self._interval.value}', `Name` = '{self._name}', - `Description` = '{self._start_time}', + `Description` = {"NULL" if self._description is None else f"'{self._description}'"}, `ChannelId` = {"NULL" if self._channel_id is None else f"'{self._channel_id}'"}, `StartTime` = '{self._start_time}', `EndTime` = {"NULL" if self._end_time is None else f"'{self._end_time}'"}, diff --git a/bot/src/bot_graphql/mutations/scheduled_event_mutation.py b/bot/src/bot_graphql/mutations/scheduled_event_mutation.py index 81353c62..43f1dd97 100644 --- a/bot/src/bot_graphql/mutations/scheduled_event_mutation.py +++ b/bot/src/bot_graphql/mutations/scheduled_event_mutation.py @@ -69,13 +69,22 @@ class ScheduledEventMutation(QueryABC): scheduled_event = self._scheduled_events.get_scheduled_event_by_id(input["id"]) self._can_user_mutate_data(scheduled_event.server, UserRoleEnum.moderator) - scheduled_event.short_name = input["shortName"] if "shortName" in input else scheduled_event.short_name - scheduled_event.interval = input["interval"] if "interval" in input else scheduled_event.interval + scheduled_event.interval = ( + ScheduledEventIntervalEnum(input["interval"]) if "interval" in input else scheduled_event.interval + ) scheduled_event.name = input["name"] if "name" in input else scheduled_event.name scheduled_event.description = input["description"] if "description" in input else scheduled_event.description scheduled_event.channel_id = input["channelId"] if "channelId" in input else scheduled_event.channel_id - scheduled_event.start_time = input["startTime"] if "startTime" in input else scheduled_event.start_time - scheduled_event.end_time = input["endTime"] if "endTime" in input else scheduled_event.end_time + scheduled_event.start_time = ( + datetime.strptime(input["startTime"], "%Y-%m-%dT%H:%M:%S.%fZ") + if "startTime" in input + else scheduled_event.start_time + ) + scheduled_event.end_time = ( + datetime.strptime(input["endTime"], "%Y-%m-%dT%H:%M:%S.%fZ") + if "endTime" in input + else scheduled_event.end_time + ) scheduled_event.entity_type = input["entityType"] if "entityType" in input else scheduled_event.entity_type scheduled_event.location = input["location"] if "location" in input else scheduled_event.location diff --git a/bot/src/bot_graphql/queries/scheduled_event_history_query.py b/bot/src/bot_graphql/queries/scheduled_event_history_query.py index 279bcda1..f8fe921a 100644 --- a/bot/src/bot_graphql/queries/scheduled_event_history_query.py +++ b/bot/src/bot_graphql/queries/scheduled_event_history_query.py @@ -13,7 +13,7 @@ class ScheduledEventHistoryQuery(DataQueryWithHistoryABC): self.set_field("id", lambda x, *_: x.id) self.set_field("id", lambda x, *_: x.id) - self.set_field("interval", lambda x, *_: x.interval) + self.set_field("interval", lambda x, *_: x.interval.value) self.set_field("name", lambda x, *_: x.name) self.set_field("description", lambda x, *_: x.description) self.set_field("channel_id", lambda x, *_: x.channel_id) diff --git a/bot/src/bot_graphql/queries/scheduled_event_query.py b/bot/src/bot_graphql/queries/scheduled_event_query.py index 47b09a1b..0cae786a 100644 --- a/bot/src/bot_graphql/queries/scheduled_event_query.py +++ b/bot/src/bot_graphql/queries/scheduled_event_query.py @@ -12,7 +12,7 @@ class ScheduledEventQuery(DataQueryWithHistoryABC): DataQueryWithHistoryABC.__init__(self, "ScheduledEvent", "ScheduledEventsHistory", ScheduledEventHistory, db) self.set_field("id", lambda x, *_: x.id) - self.set_field("interval", lambda x, *_: x.interval) + self.set_field("interval", lambda x, *_: x.interval.value) self.set_field("name", lambda x, *_: x.name) self.set_field("description", lambda x, *_: x.description) self.set_field("channelId", lambda x, *_: x.channel_id) diff --git a/web/src/app/models/data/scheduled_events.model.ts b/web/src/app/models/data/scheduled_events.model.ts index 972c10bb..e94db4b5 100644 --- a/web/src/app/models/data/scheduled_events.model.ts +++ b/web/src/app/models/data/scheduled_events.model.ts @@ -33,9 +33,11 @@ export interface ScheduledEventFilter { server?: ServerFilter; } -export enum ScheduledEventInterval { - daily = "daily", - weekly = "weekly", - monthly = "monthly", - yearly = "yearly" -} +// export enum ScheduledEventInterval { +// daily = "daily", +// weekly = "weekly", +// monthly = "monthly", +// yearly = "yearly" +// } + +export type ScheduledEventInterval = "daily" | "weekly" | "monthly" | "month" diff --git a/web/src/app/models/graphql/mutations.model.ts b/web/src/app/models/graphql/mutations.model.ts index 95843b64..bdac7b0c 100644 --- a/web/src/app/models/graphql/mutations.model.ts +++ b/web/src/app/models/graphql/mutations.model.ts @@ -204,9 +204,10 @@ export class Mutations { `; static updateScheduledEvent = ` - mutation updateScheduledEvent($interval: String,$name: String,$description: String,$channelId: String,$startTime: String, $endTime: String,$entityType: Int,$location: String, $serverId: ID) { + mutation updateScheduledEvent($id: ID, $interval: String,$name: String,$description: String,$channelId: String,$startTime: String, $endTime: String,$entityType: Int,$location: String, $serverId: ID) { scheduledEvent { updateScheduledEvent(input: { + id: $id, interval: $interval, name: $name, description: $description, diff --git a/web/src/app/modules/view/server/scheduled-events/components/edit-scheduled-event-dialog/edit-scheduled-event-dialog.component.html b/web/src/app/modules/view/server/scheduled-events/components/edit-scheduled-event-dialog/edit-scheduled-event-dialog.component.html index 62289884..fe5985ff 100644 --- a/web/src/app/modules/view/server/scheduled-events/components/edit-scheduled-event-dialog/edit-scheduled-event-dialog.component.html +++ b/web/src/app/modules/view/server/scheduled-events/components/edit-scheduled-event-dialog/edit-scheduled-event-dialog.component.html @@ -1,5 +1,5 @@
-
@@ -80,7 +80,7 @@
+ (click)="event = undefined">