diff --git a/hie.yaml b/hie.yaml index 4d7c4b9bf..daf97e6f4 100644 --- a/hie.yaml +++ b/hie.yaml @@ -1,16 +1,2 @@ cradle: - stack: - - path: './src' - component: 'monoscope:lib' - - - path: './app/Main.hs' - component: 'monoscope:exe:monoscope-exe' - - - path: './app/Paths_monoscope.hs' - component: 'monoscope:exe:monoscope-exe' - - - path: './test' - component: 'monoscope:test:monoscope-test' - -dependencies: - - package.yaml + cabal: {} diff --git a/monoscope.cabal b/monoscope.cabal index f600630bc..b0bebfdaf 100644 --- a/monoscope.cabal +++ b/monoscope.cabal @@ -42,6 +42,7 @@ extra-source-files: static/migrations/0015_summary_pattern.sql static/migrations/0016_drop_overly_restrictive_issues_constraint.sql static/migrations/0016_reports_start_and_end_time.sql + static/migrations/0017_teams_table.sql source-repository head type: git @@ -435,6 +436,7 @@ test-suite integration-tests Pages.LogExplorer.LogSpec Pages.MonitorsSpec Pages.Projects.ManageMembersSpec + Pages.DashboardsSpec Pages.Projects.ProjectsSpec Pages.ReportsSpec Pages.ShareSpec diff --git a/src/BackgroundJobs.hs b/src/BackgroundJobs.hs index 68efde0a2..d3db81a32 100644 --- a/src/BackgroundJobs.hs +++ b/src/BackgroundJobs.hs @@ -45,6 +45,7 @@ import Models.Apis.Reports qualified as Reports import Models.Apis.RequestDumps (ATError (..)) import Models.Apis.RequestDumps qualified as RequestDumps import Models.Apis.Shapes qualified as Shapes +import Models.Projects.ProjectMembers qualified as ProjectMembers import Models.Projects.Projects qualified as Projects import Models.Telemetry.Telemetry qualified as Telemetry import Models.Users.Users qualified as Users @@ -59,7 +60,7 @@ import Pages.Charts.Charts qualified as Charts import Pages.Reports qualified as RP import Pkg.DeriveUtils (UUIDId (..)) import Pkg.Drain qualified as Drain -import Pkg.Mail (NotificationAlerts (EndpointAlert, ReportAlert, RuntimeErrorAlert), sendDiscordAlert, sendPostmarkEmail, sendSlackAlert, sendSlackMessage, sendWhatsAppAlert) +import Pkg.Mail (NotificationAlerts (..), sendDiscordAlert, sendPostmarkEmail, sendSlackAlert, sendSlackMessage, sendWhatsAppAlert) import Pkg.Parser import ProcessMessage (processSpanToEntities) import PyF (fmtTrim) @@ -153,7 +154,7 @@ processBackgroundJob :: Config.AuthContext -> Job -> BgJobs -> ATBackgroundCtx ( processBackgroundJob authCtx job bgJob = case bgJob of GenerateOtelFacetsBatch pids timestamp -> generateOtelFacetsBatch pids timestamp - QueryMonitorsTriggered queryMonitorIds -> queryMonitorsTriggered queryMonitorIds + QueryMonitorsTriggered queryMonitorIds -> queryMonitorsTriggered queryMonitorIds authCtx NewAnomaly{projectId, createdAt, anomalyType, anomalyAction, targetHashes} -> newAnomalyJob projectId createdAt anomalyType anomalyAction (V.fromList targetHashes) InviteUserToProject userId projectId reciever projectTitle' -> do userM <- Users.userById userId @@ -747,52 +748,62 @@ reportUsageToLemonsqueezy subItemId quantity apiKey = do pass -queryMonitorsTriggered :: V.Vector Monitors.QueryMonitorId -> ATBackgroundCtx () -queryMonitorsTriggered queryMonitorIds = do +queryMonitorsTriggered :: V.Vector Monitors.QueryMonitorId -> Config.AuthContext -> ATBackgroundCtx () +queryMonitorsTriggered queryMonitorIds authCtx = do monitorsEvaled <- dbtToEff $ Monitors.queryMonitorsById queryMonitorIds forM_ monitorsEvaled \monitorE -> if (monitorE.triggerLessThan && monitorE.evalResult >= monitorE.alertThreshold) || (not monitorE.triggerLessThan && monitorE.evalResult <= monitorE.alertThreshold) - then handleQueryMonitorThreshold monitorE True + then handleQueryMonitorThreshold monitorE True authCtx.config.hostUrl else do if Just True == ( monitorE.warningThreshold <&> \warningThreshold -> (monitorE.triggerLessThan && monitorE.evalResult >= warningThreshold) || (not monitorE.triggerLessThan && monitorE.evalResult <= warningThreshold) ) - then handleQueryMonitorThreshold monitorE False + then handleQueryMonitorThreshold monitorE False authCtx.config.hostUrl else pass -handleQueryMonitorThreshold :: Monitors.QueryMonitorEvaled -> Bool -> ATBackgroundCtx () -handleQueryMonitorThreshold monitorE isAlert = do +handleQueryMonitorThreshold :: Monitors.QueryMonitorEvaled -> Bool -> Text -> ATBackgroundCtx () +handleQueryMonitorThreshold monitorE isAlert hostUrl = do Log.logTrace "Query Monitors Triggered " monitorE _ <- dbtToEff $ Monitors.updateQMonitorTriggeredState monitorE.id isAlert + project <- dbtToEff $ Projects.projectById monitorE.projectId + whenJustM (dbtToEff $ Projects.projectById monitorE.projectId) \p -> do + teams <- dbtToEff $ ProjectMembers.getTeamsById monitorE.projectId monitorE.teams + let thresholdType = if monitorE.triggerLessThan then "below" else "above" + threshold = fromIntegral monitorE.alertThreshold - -- Create query alert issue - let thresholdType = if monitorE.triggerLessThan then "below" else "above" - threshold = fromIntegral monitorE.alertThreshold + issue <- + liftIO + $ Issues.createQueryAlertIssue + monitorE.projectId + (show monitorE.id) + monitorE.alertConfig.title + monitorE.logQuery + threshold + (fromIntegral monitorE.evalResult :: Double) + thresholdType - issue <- - liftIO - $ Issues.createQueryAlertIssue - monitorE.projectId - (show monitorE.id) - monitorE.alertConfig.title - monitorE.logQuery - threshold - (fromIntegral monitorE.evalResult :: Double) - thresholdType + dbtToEff $ Issues.insertIssue issue - dbtToEff $ Issues.insertIssue issue + let alert = MonitorsAlert{monitorTitle = monitorE.alertConfig.title, monitorUrl = hostUrl <> "/p/" <> monitorE.projectId.toText <> "/anomalies/" <> issue.id.toText} + if null teams + then do + Relude.when monitorE.alertConfig.emailAll do + users <- dbtToEff $ Projects.usersByProjectId monitorE.projectId + forM_ users \u -> emailQueryMonitorAlert monitorE u.email (Just u) + forM_ monitorE.alertConfig.emails \email -> emailQueryMonitorAlert monitorE email Nothing + unless (null monitorE.alertConfig.slackChannels) $ sendSlackMessage monitorE.projectId [fmtTrim| 🤖 *Log Alert triggered for `{monitorE.alertConfig.title}`*|] + else do + forM_ teams \team -> do + forM_ team.notify_emails \email -> emailQueryMonitorAlert monitorE (CI.mk email) Nothing + forM_ team.slack_channels (sendSlackAlert alert monitorE.projectId p.title . Just) + forM_ team.discord_channels (sendDiscordAlert alert monitorE.projectId p.title . Just) - -- Send notifications - Relude.when monitorE.alertConfig.emailAll do - users <- dbtToEff $ Projects.usersByProjectId monitorE.projectId - forM_ users \u -> emailQueryMonitorAlert monitorE u.email (Just u) - forM_ monitorE.alertConfig.emails \email -> emailQueryMonitorAlert monitorE email Nothing - unless (null monitorE.alertConfig.slackChannels) $ sendSlackMessage monitorE.projectId [fmtTrim| 🤖 *Log Alert triggered for `{monitorE.alertConfig.title}`*|] +-- Send notifications -- way to get emails for company. for email all -- TODO: based on monitor send emails or slack @@ -947,9 +958,9 @@ sendReportForProject pid rType = do Relude.when pr.weeklyNotif $ forM_ pr.notificationsChannel \case Projects.NDiscord -> do - sendDiscordAlert alert pid pr.title + sendDiscordAlert alert pid pr.title Nothing Projects.NSlack -> do - sendSlackAlert alert pid pr.title + sendSlackAlert alert pid pr.title Nothing Projects.NPhone -> do sendWhatsAppAlert alert pid pr.title pr.whatsappNumbers _ -> do @@ -1060,9 +1071,9 @@ newAnomalyJob pid createdAt anomalyTypesT anomalyActionsT targetHashes = do Relude.when project.errorAlerts do forM_ project.notificationsChannel \case Projects.NSlack -> - forM_ errors \err -> do sendSlackAlert (RuntimeErrorAlert err.errorData) pid project.title + forM_ errors \err -> do sendSlackAlert (RuntimeErrorAlert err.errorData) pid project.title Nothing Projects.NDiscord -> - forM_ errors \err -> do sendDiscordAlert (RuntimeErrorAlert err.errorData) pid project.title + forM_ errors \err -> do sendDiscordAlert (RuntimeErrorAlert err.errorData) pid project.title Nothing Projects.NPhone -> forM_ errors \err -> do sendWhatsAppAlert (RuntimeErrorAlert err.errorData) pid project.title project.whatsappNumbers @@ -1163,8 +1174,8 @@ processAPIChangeAnomalies pid targetHashes = do let alert = EndpointAlert project.title (V.fromList endpointInfo) (fromMaybe "" $ viaNonEmpty head $ V.toList targetHashes) forM_ project.notificationsChannel \case - Projects.NSlack -> sendSlackAlert alert pid project.title - Projects.NDiscord -> sendDiscordAlert alert pid project.title + Projects.NSlack -> sendSlackAlert alert pid project.title Nothing + Projects.NDiscord -> sendDiscordAlert alert pid project.title Nothing Projects.NPhone -> sendWhatsAppAlert alert pid project.title project.whatsappNumbers Projects.NEmail -> do forM_ users \u -> do diff --git a/src/Data/Effectful/Notify.hs b/src/Data/Effectful/Notify.hs index 351d49d2c..3ac6c20c2 100644 --- a/src/Data/Effectful/Notify.hs +++ b/src/Data/Effectful/Notify.hs @@ -36,6 +36,7 @@ module Data.Effectful.Notify ( import Control.Lens ((.~)) import Control.Lens.Setter ((?~)) import Data.Aeson qualified as AE +import Data.Aeson.KeyMap qualified as AEK import Data.Aeson.QQ (aesonQQ) import Effectful import Effectful.Dispatch.Dynamic @@ -59,7 +60,7 @@ data EmailData = EmailData data SlackData = SlackData - { webhookUrl :: Text + { channelId :: Text , message :: AE.Value } deriving stock (Eq, Generic, Show) @@ -111,7 +112,7 @@ emailNotification receiver templateOptions subjectMessage = slackNotification :: Text -> AE.Value -> Notification -slackNotification webhookUrl message = +slackNotification channelId message = SlackNotification SlackData{..} @@ -155,8 +156,12 @@ runNotifyProduction = interpret $ \_ -> \case _ <- liftIO $ postWith opts url payload pass SlackNotification SlackData{..} -> do - let opts = defaults & header "Content-Type" .~ ["application/json"] - _ <- liftIO $ postWith opts (toString webhookUrl) message + appCtx <- ask @Config.AuthContext + let opts = defaults & header "Content-Type" .~ ["application/json"] & header "Authorization" .~ [encodeUtf8 $ "Bearer " <> appCtx.config.slackBotToken] + let messageF = case message of + AE.Object obj -> AE.Object $ obj <> (AEK.fromList [("channel", AE.String channelId)]) + _ -> message + _ <- liftIO $ postWith opts "https://slack.com/api/chat.postMessage" messageF pass DiscordNotification DiscordData{..} -> do appCtx <- ask @Config.AuthContext @@ -196,7 +201,7 @@ runNotifyTest eff = do EmailNotification emailData -> ("Email" :: Text, emailData.receiver, fmap fst emailData.templateOptions) SlackNotification slackData -> - ("Slack" :: Text, slackData.webhookUrl, Nothing :: Maybe Text) + ("Slack" :: Text, slackData.channelId, Nothing :: Maybe Text) DiscordNotification discordData -> ("Discord" :: Text, discordData.channelId, Nothing :: Maybe Text) WhatsAppNotification whatsappData -> diff --git a/src/Models/Apis/Monitors.hs b/src/Models/Apis/Monitors.hs index 358a12efc..d96f19f5a 100644 --- a/src/Models/Apis/Monitors.hs +++ b/src/Models/Apis/Monitors.hs @@ -9,6 +9,7 @@ module Models.Apis.Monitors ( MonitorAlertConfig (..), QueryMonitorId (..), updateQMonitorTriggeredState, + getAlertsByTeamHandle, ) where import Data.Aeson qualified as AE @@ -87,6 +88,7 @@ data QueryMonitor = QueryMonitor , deactivatedAt :: Maybe UTCTime , deletedAt :: Maybe UTCTime , visualizationType :: Text + , teams :: V.Vector UUID.UUID } deriving stock (Generic, Show) deriving anyclass (Default, FromRow, NFData, ToRow) @@ -113,6 +115,7 @@ data QueryMonitorEvaled = QueryMonitorEvaled , deactivatedAt :: Maybe UTCTime , deletedAt :: Maybe UTCTime , visualizationType :: Text + , teams :: V.Vector UUID.UUID , evalResult :: Int } deriving stock (Generic, Show) @@ -138,13 +141,14 @@ queryMonitorUpsert qm = , qm.alertConfig , qm.checkIntervalMins , qm.visualizationType + , qm.teams ) where q = [sql| INSERT INTO monitors.query_monitors (id, project_id, alert_threshold, warning_threshold, log_query, log_query_as_sql, last_evaluated, warning_last_triggered, alert_last_triggered, trigger_less_than, - threshold_sustained_for_mins, alert_config, check_interval_mins, visualization_type) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?) + threshold_sustained_for_mins, alert_config, check_interval_mins, visualization_type, teams) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?::uuid[]) ON CONFLICT (id) DO UPDATE SET alert_threshold=EXCLUDED.alert_threshold, warning_threshold=EXCLUDED.warning_threshold, @@ -157,7 +161,8 @@ queryMonitorUpsert qm = threshold_sustained_for_mins=EXCLUDED.threshold_sustained_for_mins, alert_config=EXCLUDED.alert_config, check_interval_mins=EXCLUDED.check_interval_mins, - visualization_type=EXCLUDED.visualization_type; + visualization_type=EXCLUDED.visualization_type, + teams=EXCLUDED.teams |] @@ -174,7 +179,7 @@ queryMonitorsById ids [sql| SELECT id, created_at, updated_at, project_id, check_interval_mins, alert_threshold, warning_threshold, log_query, log_query_as_sql, last_evaluated, warning_last_triggered, alert_last_triggered, trigger_less_than, - threshold_sustained_for_mins, alert_config, deactivated_at, deleted_at, visualization_type, eval(log_query_as_sql) + threshold_sustained_for_mins, alert_config, deactivated_at, deleted_at, visualization_type, teams, eval(log_query_as_sql) FROM monitors.query_monitors where id=ANY(?::UUID[]) |] @@ -202,3 +207,16 @@ monitorToggleActiveById id' = execute q (Only id') queryMonitorsAll :: Projects.ProjectId -> DBT IO (V.Vector QueryMonitor) queryMonitorsAll pid = selectManyByField @QueryMonitor [DAT.field| project_id |] pid + + +getAlertsByTeamHandle :: Projects.ProjectId -> UUID.UUID -> DBT IO (V.Vector QueryMonitor) +getAlertsByTeamHandle pid teamId = query q (pid, teamId) + where + q = + [sql| + SELECT qm.id, qm.created_at, qm.updated_at, qm.project_id, qm.check_interval_mins, qm.alert_threshold, qm.warning_threshold, + qm.log_query, qm.log_query_as_sql, qm.last_evaluated, qm.warning_last_triggered, qm.alert_last_triggered, qm.trigger_less_than, + qm.threshold_sustained_for_mins, qm.alert_config, qm.deactivated_at, qm.deleted_at, qm.visualization_type, qm.teams + FROM monitors.query_monitors qm + WHERE qm.project_id = ? AND ? = ANY(qm.teams) + |] diff --git a/src/Models/Projects/Dashboards.hs b/src/Models/Projects/Dashboards.hs index ec98d07b9..a0cccc842 100644 --- a/src/Models/Projects/Dashboards.hs +++ b/src/Models/Projects/Dashboards.hs @@ -1,10 +1,27 @@ -module Models.Projects.Dashboards (Dashboard (..), DashboardVM (..), DashboardId, readDashboardFile, Variable (..), VariableType (..), Tab (..), getDashboardById, readDashboardsFromDirectory, readDashboardEndpoint, replaceQueryVariables) where +module Models.Projects.Dashboards ( + Dashboard (..), + DashboardVM (..), + DashboardId, + readDashboardFile, + Variable (..), + VariableType (..), + Tab (..), + getDashboardById, + readDashboardsFromDirectory, + readDashboardEndpoint, + replaceQueryVariables, + deleteDashboardsByIds, + addTeamsToDashboards, + insert, + selectDashboardsByTeam, +) where import Control.Exception (try) import Control.Lens import Data.Aeson qualified as AE import Data.ByteString qualified as BS import Data.Default +import Data.Effectful.UUID qualified as UUID import Data.Effectful.Wreq (HTTP) import Data.Effectful.Wreq qualified as W import Data.Generics.Labels () @@ -18,6 +35,7 @@ import Database.PostgreSQL.Simple (FromRow, ToRow) import Database.PostgreSQL.Simple.FromField import Database.PostgreSQL.Simple.Newtypes (Aeson (..)) import Database.PostgreSQL.Simple.ToField +import Database.PostgreSQL.Simple.TypeInfo.Static (uuid) import Database.PostgreSQL.Simple.Types (Only (Only), Query (Query)) import Database.PostgreSQL.Transact qualified as DBT import Deriving.Aeson qualified as DAE @@ -51,6 +69,7 @@ data DashboardVM = DashboardVM , homepageSince :: Maybe UTCTime , tags :: V.Vector Text , title :: Text + , teams :: V.Vector UUID.UUID } deriving stock (Generic, Show) deriving anyclass (FromRow, NFData, ToRow) @@ -117,6 +136,29 @@ data Tab = Tab deriving (AE.FromJSON, AE.ToJSON) via DAES.Snake Tab +insert :: DB :> es => DashboardVM -> Eff es Int64 +insert dashboardVM = do + dbtToEff $ DBT.execute (Query $ encodeUtf8 q) params + where + q = + [text| INSERT INTO projects.dashboards (id, project_id, created_at, updated_at, created_by, base_template, schema, starred_since, homepage_since, tags, title, teams) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?::uuid[]) |] + params = + ( dashboardVM.id + , dashboardVM.projectId + , dashboardVM.createdAt + , dashboardVM.updatedAt + , dashboardVM.createdBy + , dashboardVM.baseTemplate + , dashboardVM.schema + , dashboardVM.starredSince + , dashboardVM.homepageSince + , dashboardVM.tags + , dashboardVM.title + , dashboardVM.teams + ) + + readDashboardsFromDirectory :: FilePath -> Q Exp readDashboardsFromDirectory dir = do files <- runIO $ listDirectory dir @@ -161,4 +203,29 @@ replaceQueryVariables pid mf mt allParams currentTime variable = getDashboardById :: DB :> es => Text -> Eff es (Maybe DashboardVM) getDashboardById did = dbtToEff $ DBT.queryOne (Query $ encodeUtf8 q) (Only did) where - q = [text|SELECT id, project_id, created_at, updated_at, created_by, base_template, schema, starred_since, homepage_since, tags, title FROM projects.dashboards WHERE id = ?|] + q = [text| SELECT id, project_id, created_at, updated_at, created_by, base_template, schema, starred_since, homepage_since, tags, title, teams FROM projects.dashboards WHERE id = ?|] + + +deleteDashboardsByIds :: DB :> es => Projects.ProjectId -> V.Vector DashboardId -> Eff es Int64 +deleteDashboardsByIds pid dids = dbtToEff $ DBT.execute (Query $ encodeUtf8 q) (pid, dids) + where + q = [text|DELETE FROM projects.dashboards WHERE project_id = ? AND id = ANY(?::uuid[])|] + + +addTeamsToDashboards :: DB :> es => Projects.ProjectId -> V.Vector DashboardId -> V.Vector UUID.UUID -> Eff es Int64 +addTeamsToDashboards pid dids teamIds = do + dbtToEff $ DBT.execute (Query $ encodeUtf8 q) (teamIds, pid, dids) + where + q = + [text| + UPDATE projects.dashboards + SET teams = teams || ?::uuid[] + WHERE project_id = ? AND id = ANY(?::uuid[]) + |] + + +selectDashboardsByTeam :: DB :> es => Projects.ProjectId -> UUID.UUID -> Eff es [DashboardVM] +selectDashboardsByTeam pid teamId = do + dbtToEff $ DBT.query (Query $ encodeUtf8 q) (pid, teamId) + where + q = [text| SELECT id, project_id, created_at, updated_at, created_by, base_template, schema, starred_since, homepage_since, tags, title, teams FROM projects.dashboards WHERE project_id = ? AND teams @> ARRAY[?::uuid]|] diff --git a/src/Models/Projects/ProjectMembers.hs b/src/Models/Projects/ProjectMembers.hs index 05a499b0f..b325bdbdc 100644 --- a/src/Models/Projects/ProjectMembers.hs +++ b/src/Models/Projects/ProjectMembers.hs @@ -7,15 +7,27 @@ module Models.Projects.ProjectMembers ( selectActiveProjectMembers, updateProjectMembersPermissons, softDeleteProjectMembers, + createTeam, + updateTeam, + getTeams, + getTeamByHandle, + getTeamsVM, + TeamVM (..), + deleteTeamByHandle, + deleteTeams, + getTeamsById, + Team (..), + TeamMemberVM (..), ) where import Control.Error (note) +import Data.Aeson qualified as AE import Data.CaseInsensitive (CI) import Data.Default.Instances () -import Data.Time (ZonedTime) +import Data.Time (UTCTime, ZonedTime) import Data.UUID qualified as UUID import Data.Vector qualified as V -import Database.PostgreSQL.Entity.DBT (query) +import Database.PostgreSQL.Entity.DBT (query, queryOne) import Database.PostgreSQL.Entity.Types ( CamelToSnake, Entity, @@ -25,12 +37,16 @@ import Database.PostgreSQL.Entity.Types ( Schema, TableName, ) -import Database.PostgreSQL.Simple (FromRow, Only (Only), ResultError (..), ToRow) +import Database.PostgreSQL.Simple (FromRow, In, Only (Only), ResultError (..), ToRow) import Database.PostgreSQL.Simple.FromField (FromField, fromField, returnError) +import Database.PostgreSQL.Simple.Newtypes (Aeson (..)) import Database.PostgreSQL.Simple.SqlQQ (sql) import Database.PostgreSQL.Simple.ToField (Action (Escape), ToField, toField) +import Database.PostgreSQL.Simple.TypeInfo.Static (uuid) import Database.PostgreSQL.Transact (DBT, execute, executeMany) import Database.PostgreSQL.Transact qualified as PgT +import Deriving.Aeson qualified as DAE +import Effectful.PostgreSQL.Transact.Effect (DB) import Models.Projects.Projects qualified as Projects import Models.Users.Users qualified as Users import Relude @@ -114,6 +130,8 @@ data ProjectMemberVM = ProjectMemberVM , userId :: Users.UserId , permission :: Permissions , email :: CI Text + , first_name :: Text + , last_name :: Text } deriving stock (Eq, Generic, Show) deriving anyclass (FromRow, NFData) @@ -123,7 +141,7 @@ selectActiveProjectMembers :: Projects.ProjectId -> DBT IO (V.Vector ProjectMemb selectActiveProjectMembers = query q where q = - [sql| SELECT pm.id, pm.user_id, pm.permission,us.email from projects.project_members pm + [sql| SELECT pm.id, pm.user_id, pm.permission,us.email, us.first_name, us.last_name from projects.project_members pm JOIN users.users us ON (pm.user_id=us.id) WHERE pm.project_id=?::uuid and pm.active=TRUE ORDER BY pm.created_at ASC; @@ -141,10 +159,186 @@ updateProjectMembersPermissons vals = void $ executeMany q vals softDeleteProjectMembers :: [UUID.UUID] -> DBT IO () -softDeleteProjectMembers [] = pass -softDeleteProjectMembers vals = void $ execute q (Only (V.fromList vals)) +softDeleteProjectMembers vals = unless (null vals) $ void $ execute q (Only $ V.fromList vals) where q = [sql| UPDATE projects.project_members SET active = FALSE WHERE id = Any(?::uuid[]); |] + + +createTeam :: Projects.ProjectId -> Users.UserId -> Text -> Text -> Text -> V.Vector Users.UserId -> V.Vector Text -> V.Vector Text -> V.Vector Text -> DBT IO Int64 +createTeam pid uid name description handle memberIds notifEmails slackChannels discordChannels = execute q (pid, uid, name, description, handle, memberIds, notifEmails, slackChannels, discordChannels) + where + q = + [sql| INSERT INTO projects.teams + (project_id,created_by, name, description, handle, members, notify_emails, slack_channels, discord_channels) + VALUES (?,?, ?,?,?,?::uuid[],?,?,?) |] + + +updateTeam :: Projects.ProjectId -> UUID.UUID -> Text -> Text -> Text -> V.Vector Users.UserId -> V.Vector Text -> V.Vector Text -> V.Vector Text -> DBT IO Int64 +updateTeam pid tid name description handle memberIds notifEmails slackChannels discordChannels = do + execute q (name, description, handle, memberIds, notifEmails, slackChannels, discordChannels, pid, tid) + where + q = + [sql| UPDATE projects.teams + SET name = ?, description = ?, handle = ?, members = ?::uuid[], notify_emails = ?, slack_channels = ?, discord_channels = ? + WHERE project_id = ? AND id = ? |] + + +data Team = Team + { id :: UUID.UUID + , name :: Text + , description :: Text + , handle :: Text + , members :: V.Vector Users.UserId + , created_by :: Users.UserId + , created_at :: UTCTime + , updated_at :: UTCTime + , notify_emails :: V.Vector Text + , slack_channels :: V.Vector Text + , discord_channels :: V.Vector Text + } + deriving stock (Eq, Generic, Show) + deriving anyclass (FromRow, NFData) + + +getTeams :: Projects.ProjectId -> DBT IO (V.Vector Team) +getTeams pid = query q (Only pid) + where + q = + [sql| + SELECT t.id, t.name, t.description, t.handle, t.members, t.created_by, t.created_at, t.updated_at, t.notify_emails, t.slack_channels, t.discord_channels + FROM projects.teams t + WHERE t.project_id = ? AND t.deleted_at is null + |] + + +getTeamsVM :: Projects.ProjectId -> DBT IO (V.Vector TeamVM) +getTeamsVM pid = query q (Only pid) + where + q = + [sql| + SELECT + t.id, + t.created_at, + t.updated_at, + t.created_by, + t.name, + t.handle, + t.description, + t.notify_emails, + t.slack_channels, + t.discord_channels, +ARRAY( + SELECT jsonb_build_object( + 'memberId', u.id, + 'memberName', concat_ws(' ', u.first_name, u.last_name), + 'memberEmail', u.email, + 'memberAvatar', u.display_image_url + ) + FROM unnest(t.members) AS mid + JOIN users.users u ON u.id = mid +) AS members + FROM projects.teams t + WHERE t.project_id = ? AND t.deleted_at is null + |] + + +data TeamVM = TeamVM + { id :: UUID.UUID + , created_at :: UTCTime + , updated_at :: UTCTime + , created_by :: Users.UserId + , name :: Text + , handle :: Text + , description :: Text + , notify_emails :: V.Vector Text + , slack_channels :: V.Vector Text + , discord_channels :: V.Vector Text + , members :: V.Vector TeamMemberVM + } + deriving stock (Eq, Generic, Show) + deriving anyclass (FromRow, NFData) + + +data TeamMemberVM = TeamMemberVM + { memberId :: UUID.UUID + , memberEmail :: Text + , memberName :: Text + , memberAvatar :: Text + } + deriving stock (Eq, Generic, Show) + deriving anyclass (AE.FromJSON, NFData) + deriving (FromField) via Aeson TeamMemberVM + + +getTeamByHandle :: Projects.ProjectId -> Text -> DBT IO (Maybe TeamVM) +getTeamByHandle pid handle = queryOne q (pid, handle) + where + q = + [sql| + SELECT + t.id, + t.created_at, + t.updated_at, + t.created_by, + t.name, + t.handle, + t.description, + t.notify_emails, + t.slack_channels, + t.discord_channels, +ARRAY( + SELECT jsonb_build_object( + 'memberId', u.id, + 'memberName', concat_ws(' ', u.first_name, u.last_name), + 'memberEmail', u.email, + 'memberAvatar', u.display_image_url + ) + FROM unnest(t.members) AS mid + JOIN users.users u ON u.id = mid +) AS members + FROM projects.teams t + WHERE t.project_id = ? + AND t.handle = ? + AND t.deleted_at is null + |] + + +deleteTeamByHandle :: Projects.ProjectId -> Text -> DBT IO () +deleteTeamByHandle pid handle = void $ execute q (pid, handle) + where + q = + [sql| UPDATE projects.teams SET deleted_at = now() WHERE project_id = ? AND handle = ? |] + + +deleteTeams :: Projects.ProjectId -> V.Vector UUID.UUID -> DBT IO () +deleteTeams pid tids + | V.null tids = pure () + | otherwise = void $ execute q (pid, tids) + where + q = + [sql| UPDATE projects.teams SET deleted_at = now() WHERE project_id = ? AND id=ANY(?::UUID[]) |] + + +getTeamsById :: Projects.ProjectId -> V.Vector UUID.UUID -> DBT IO (V.Vector Team) +getTeamsById pid tids = if V.null tids then pure V.empty else query q (pid, tids) + where + q = + [sql| + SELECT + t.id, + t.name, + t.description, + t.handle, + t.members, + t.created_by, + t.created_at, + t.updated_at, + t.notify_emails, + t.slack_channels, + t.discord_channels + FROM projects.teams t + WHERE t.project_id = ? AND t.id=ANY(?::UUID[]) AND t.deleted_at is null + |] diff --git a/src/Pages/BodyWrapper.hs b/src/Pages/BodyWrapper.hs index 5ada0f023..f7550a00c 100644 --- a/src/Pages/BodyWrapper.hs +++ b/src/Pages/BodyWrapper.hs @@ -92,11 +92,11 @@ bodyWrapper bcfg child = do meta_ [name_ "msapplication-TileColor", content_ "#da532c"] meta_ [name_ "theme-color", content_ "#ffffff"] link_ [rel_ "stylesheet", type_ "text/css", href_ $(hashAssetFile "/public/assets/css/thirdparty/notyf3.min.css")] - link_ [rel_ "stylesheet", href_ "https://cdn.jsdelivr.net/npm/@yaireo/tagify/dist/tagify.css", type_ "text/css"] + link_ [rel_ "stylesheet", href_ $(hashAssetFile "/public/assets/css/thirdparty/tagify.min.css"), type_ "text/css"] link_ [rel_ "stylesheet", href_ $(hashAssetFile "/public/assets/deps/gridstack/gridstack.min.css")] link_ [rel_ "stylesheet", href_ $(hashAssetFile "/public/assets/css/thirdparty/rrweb.css")] - link_ [rel_ "stylesheet", type_ "text/css", href_ "/public/assets/css/tailwind.min.css"] + link_ [rel_ "stylesheet", type_ "text/css", href_ $(hashAssetFile "/public/assets/css/tailwind.min.css")] link_ [rel_ "stylesheet", type_ "text/css", href_ $(hashAssetFile "/public/assets/web-components/dist/css/index.css")] -- Include optional head content from the page @@ -694,6 +694,7 @@ navBottomList pidTxt = [ ("gear", "bg-fillBrand-weak", "text-textBrand", "Project settings", "/p/" <> pidTxt <> "/settings", Nothing, Nothing, Nothing) , ("key", "bg-fillSuccess-weak", "text-textSuccess", "API keys", "/p/" <> pidTxt <> "/apis", Nothing, Nothing, Nothing) , ("user-plus", "bg-fillWarning-weak", "text-textWarning", "Manage members", "/p/" <> pidTxt <> "/manage_members", Nothing, Nothing, Nothing) + , ("users", "bg-fillInfo-weak", "text-textInfo", "Manage teams", "/p/" <> pidTxt <> "/manage_teams", Nothing, Nothing, Nothing) , ("dollar", "bg-fillWarning-weak", "text-textWarning", "Manage billing", "/p/" <> pidTxt <> "/manage_billing", Nothing, Nothing, Nothing) , ("arrows-turn-right", "bg-fillBrand-weak", "text-textBrand", "Integrations", "/p/" <> pidTxt <> "/integrations", Nothing, Nothing, Nothing) , ("bucket", "", "", "Your S3 bucket", "/p/" <> pidTxt <> "/byob_s3", Nothing, Nothing, Nothing) diff --git a/src/Pages/Bots/Discord.hs b/src/Pages/Bots/Discord.hs index fbf42b96a..a8a253485 100644 --- a/src/Pages/Bots/Discord.hs +++ b/src/Pages/Bots/Discord.hs @@ -1,6 +1,6 @@ {-# LANGUAGE PackageImports #-} -module Pages.Bots.Discord (linkDiscordGetH, discordInteractionsH, DiscordInteraction) where +module Pages.Bots.Discord (linkDiscordGetH, discordInteractionsH, getDiscordChannels, DiscordInteraction) where import Data.Aeson qualified as AE import Data.ByteString qualified as BS @@ -35,7 +35,7 @@ import Models.Projects.Dashboards qualified as Dashboards import Network.HTTP.Types (urlEncode) import Network.Wreq qualified as Wreq import Network.Wreq.Types (FormParam) -import Pages.Bots.Utils (BotResponse (..), BotType (..), authHeader, chartImageUrl, contentTypeHeader, handleTableResponse) +import Pages.Bots.Utils (BotResponse (..), BotType (..), Channel, authHeader, chartImageUrl, contentTypeHeader, handleTableResponse) import Pkg.AI (callOpenAIAPI, systemPrompt) import Pkg.AI qualified as AI import Pkg.Components.Widget qualified as Widget @@ -117,7 +117,7 @@ data DiscordInteraction = Interaction , data_i :: Maybe InteractionData , channel_id :: Maybe Text , guild_id :: Maybe Text - , channel :: Maybe Channel + , channel :: Maybe Channel' } deriving (Generic, Show) @@ -135,7 +135,7 @@ data ThreadMetadata = ThreadMetadata instance AE.FromJSON ThreadMetadata -data Channel = Channel +data Channel' = Channel' { id :: Text , name :: Text , guild_id :: Maybe Text @@ -147,7 +147,7 @@ data Channel = Channel deriving (Generic, Show) -instance AE.FromJSON Channel where +instance AE.FromJSON Channel' where parseJSON = AE.genericParseJSON AE.defaultOptions{AE.fieldLabelModifier = \f -> if f == "type_" then "type" else f} @@ -197,6 +197,15 @@ data InteractionOption = InteractionOption deriving anyclass (AE.FromJSON) +getDiscordChannels :: HTTP :> es => Text -> Text -> Eff es [Channel] +getDiscordChannels token guildId = do + let url = "https://discord.com/api/v10/guilds/" <> toString guildId <> "/channels" + opts = defaults & header "Authorization" .~ ["Bot " <> encodeUtf8 token] + r <- getWith opts url + let body = r ^. responseBody + pure $ fromRight [] $ AE.eitherDecode body + + discordInteractionsH :: BS.ByteString -> Maybe BS.ByteString -> Maybe BS.ByteString -> ATBaseCtx AE.Value discordInteractionsH rawBody signatureM timestampM = do authCtx <- Effectful.Reader.Static.ask @AuthContext @@ -428,7 +437,7 @@ getThreadStarterMessage :: HTTP :> es => DiscordInteraction -> Text -> Eff es (M getThreadStarterMessage interaction botToken = do case interaction.channel_id of Just channelId -> case interaction.channel of - Just Channel{type_ = 11, parent_id = Just pId} -> do + Just Channel'{type_ = 11, parent_id = Just pId} -> do let baseUrl = "https://discord.com/api/v10/channels/" url = toString $ baseUrl <> channelId <> "/messages?limit=50" starterMessageUrl = toString $ baseUrl <> pId <> "/messages/" <> channelId diff --git a/src/Pages/Bots/Slack.hs b/src/Pages/Bots/Slack.hs index 2e12a27e4..7a12780e0 100644 --- a/src/Pages/Bots/Slack.hs +++ b/src/Pages/Bots/Slack.hs @@ -1,9 +1,10 @@ {-# OPTIONS_GHC -Wno-unrecognised-pragmas #-} -module Pages.Bots.Slack (linkProjectGetH, slackActionsH, SlackEventPayload, slackEventsPostH, SlackActionForm, externalOptionsH, slackInteractionsH, SlackInteraction) where +module Pages.Bots.Slack (linkProjectGetH, slackActionsH, SlackEventPayload, slackEventsPostH, getSlackChannels, SlackChannelsResponse (..), SlackActionForm, externalOptionsH, slackInteractionsH, SlackInteraction) where import BackgroundJobs qualified as BgJobs import Control.Lens ((.~), (^.)) +import Data.Aeson (withObject) import Data.Aeson qualified as AE import Data.Aeson.Key qualified as KEM import Data.Aeson.KeyMap qualified as KEMP @@ -38,7 +39,7 @@ import Network.Wreq qualified as Wreq import Network.Wreq.Types (FormParam) import OddJobs.Job (createJob) import Pages.BodyWrapper (BWConfig, PageCtx (..), currProject, pageTitle, sessM) -import Pages.Bots.Utils (BotResponse (..), BotType (..), contentTypeHeader, handleTableResponse) +import Pages.Bots.Utils (BotResponse (..), BotType (..), Channel, contentTypeHeader, handleTableResponse) import Pkg.AI (callOpenAIAPI, systemPrompt) import Pkg.AI qualified as AI import Pkg.Components.Widget (Widget (..)) @@ -635,6 +636,28 @@ data SlackThreadedMessage = SlackThreadedMessage deriving (Generic, Show) +data SlackChannelsResponse = SlackChannelsResponse + { ok :: Bool + , channels :: [Channel] + } + deriving (Generic, Show) + deriving anyclass (AE.FromJSON) + + +-- | Internal helper to call Slack API +getSlackChannels :: HTTP :> es => Text -> Text -> Eff es (Maybe SlackChannelsResponse) +getSlackChannels token team_id = do + let url = "https://slack.com/api/conversations.list" + opts = + defaults & header "Authorization" .~ ["Bearer " <> encodeUtf8 token] & Wreq.param "team_id" .~ [team_id] + + r <- getWith opts url + let resBody = r ^. responseBody + case AE.eitherDecode resBody of + Right val -> return $ Just val + Left err -> return Nothing + + instance AE.FromJSON SlackThreadedMessage where parseJSON = AE.genericParseJSON AE.defaultOptions{AE.fieldLabelModifier = \f -> if f == "type_" then "type" else f} diff --git a/src/Pages/Bots/Utils.hs b/src/Pages/Bots/Utils.hs index 99f0b4a09..ea924bee3 100644 --- a/src/Pages/Bots/Utils.hs +++ b/src/Pages/Bots/Utils.hs @@ -1,4 +1,4 @@ -module Pages.Bots.Utils (handleTableResponse, BotType (..), BotResponse (..), chartImageUrl, authHeader, contentTypeHeader) where +module Pages.Bots.Utils (handleTableResponse, BotType (..), BotResponse (..), Channel (..), chartImageUrl, authHeader, contentTypeHeader) where import Control.Lens ((.~)) import Data.Aeson qualified as AE @@ -8,6 +8,7 @@ import Data.Text qualified as T import Data.Time qualified as Time import Data.Time.Clock.POSIX (utcTimeToPOSIXSeconds) import Data.Vector qualified as V +import Deriving.Aeson qualified as DAE import Lucid import Models.Projects.Projects qualified as Projects import Network.HTTP.Types (urlEncode) @@ -191,3 +192,14 @@ installedSuccess botPlatform = do p_ [class_ "text-textStrong text-sm"] "Set up this channel to receive automated error reports, weekly summaries, and daily performance alerts." + + +data Channel = Channel + { channelName :: Text + , channelId :: Text + , channelType :: Maybe Int + } + deriving (Generic, Show) + deriving + (AE.FromJSON, AE.ToJSON) + via DAE.CustomJSON '[DAE.OmitNothingFields, DAE.FieldLabelModifier '[DAE.StripPrefix "channel", DAE.CamelToSnake]] Channel diff --git a/src/Pages/Components.hs b/src/Pages/Components.hs index 9d41fd31b..ad7c8de2f 100644 --- a/src/Pages/Components.hs +++ b/src/Pages/Components.hs @@ -401,7 +401,7 @@ modal_ modalId btnTrigger contentHtml = do on closeModal from body set my.checked to false end |] ] - div_ [class_ "modal w-screen", role_ "dialog"] do + div_ [class_ "modal w-screen", role_ "dialog", style_ "--color-base-100: var(--color-fillWeaker)"] do label_ [class_ "modal-backdrop", Lucid.for_ modalId] "" div_ [class_ "modal-box w-auto flex flex-col gap-5 max-w-5xl"] do label_ [Lucid.for_ modalId, class_ "btn btn-sm btn-circle btn-ghost absolute right-2 top-2"] "✕" diff --git a/src/Pages/Dashboards.hs b/src/Pages/Dashboards.hs index 5b84a170c..8c4dda2a6 100644 --- a/src/Pages/Dashboards.hs +++ b/src/Pages/Dashboards.hs @@ -1,4 +1,28 @@ -module Pages.Dashboards (dashboardGetH, entrypointRedirectGetH, DashboardGet (..), dashboardsGetH, DashboardsGet (..), dashboardsPostH, DashboardForm (..), dashboardWidgetPutH, dashboardWidgetReorderPatchH, WidgetReorderItem (..), dashboardDeleteH, dashboardRenamePatchH, DashboardRenameForm (..), dashboardDuplicatePostH, WidgetMoveForm (..), dashboardDuplicateWidgetPostH, dashboardWidgetExpandGetH, visTypes, processEagerWidget) where +module Pages.Dashboards ( + dashboardGetH, + entrypointRedirectGetH, + DashboardGet (..), + dashboardsGetH, + DashboardsGet (..), + dashboardsPostH, + DashboardForm (..), + dashboardWidgetPutH, + dashboardWidgetReorderPatchH, + WidgetReorderItem (..), + dashboardDeleteH, + dashboardRenamePatchH, + DashboardRenameForm (..), + dashboardDuplicatePostH, + WidgetMoveForm (..), + DashboardBulkActionForm (..), + DashboardRes (..), + DashboardsGetD (..), + dashboardDuplicateWidgetPostH, + dashboardWidgetExpandGetH, + visTypes, + processEagerWidget, + dashboardBulkActionPostH, +) where import Control.Lens import Data.Aeson qualified as AE @@ -13,6 +37,7 @@ import Data.List qualified as L import Data.Map qualified as Map import Data.Text qualified as T import Data.Time (UTCTime, defaultTimeLocale, formatTime) +import Data.Time qualified as Time import Data.Vector qualified as V import Database.PostgreSQL.Entity qualified as DBT import Database.PostgreSQL.Entity.DBT (query_) @@ -32,10 +57,12 @@ import Lucid.Htmx (hxConfirm_, hxDelete_, hxExt_, hxPatch_, hxPost_, hxPut_, hxS import Lucid.Hyperscript (__) import Models.Apis.Issues qualified as Issues import Models.Projects.Dashboards qualified as Dashboards +import Models.Projects.ProjectMembers qualified as ManageMembers import Models.Projects.Projects qualified as Projects import Models.Telemetry.Telemetry qualified as Telemetry import Models.Users.Sessions qualified as Sessions import Models.Users.Users +import Models.Users.Users qualified as Users import NeatInterpolation import Network.HTTP.Types.URI qualified as URI import Pages.Anomalies qualified as AnomalyList @@ -44,6 +71,7 @@ import Pages.Charts.Charts qualified as Charts import Pages.Components qualified as Components import Pages.LogExplorer.LogItem (getServiceName) import Pkg.Components.LogQueryBox (LogQueryBoxConfig (..), logQueryBox_, visTypes) +import Pkg.Components.Table (Config (..), Features (..), SearchMode (..), Table (..), ZeroState (..), col) import Pkg.Components.Table qualified as Table import Pkg.Components.TimePicker qualified as TimePicker import Pkg.Components.Widget qualified as Widget @@ -146,20 +174,12 @@ dashboardPage_ pid dashId dash dashVM allParams = do [text| const tagifyInstances = new Map(); document.querySelectorAll('.tagify-select-input').forEach(input => { - const tgfy = new Tagify(input, { + const tgfy = createTagify(input, { whitelist: JSON.parse(input.dataset.whitelistjson || "[]"), enforceWhitelist: true, tagTextProp: 'name', mode: input.dataset.mode || "", - dropdown: { - enabled: 0, - mapValueTo: "name", - highlightFirst: true, - searchKeys: ["name", "value"], - placeAbove: false, - maxItems: 50 - }, - }) + }); const inputKey = input.getAttribute('name') || input.id; tagifyInstances.set(inputKey, tgfy); @@ -367,6 +387,18 @@ processEagerWidget pid now (sinceStr, fromDStr, toDStr) allParams widget = case let issuesVM = V.map (AnomalyList.IssueVM False True now "24h") issues pure $ widget + & #html + ?~ renderText + ( div_ [class_ "flex flex-col gap-4 h-full w-full overflow-hidden"] + $ forM_ issuesVM \vm@(AnomalyList.IssueVM hideByDefault _ _ _ issue) -> + div_ [class_ "border border-strokeWeak rounded-2xl overflow-hidden"] do + Table.renderRowWithColumns + [ class_ $ "flex gap-8 items-start itemsListItem " <> if hideByDefault then "card-round" else "px-0.5 py-4" + , style_ (if hideByDefault then "display:none" else "") + ] + (AnomalyList.issueColumns issue.projectId) + vm + ) & #html ?~ renderText ( div_ [class_ "flex flex-col gap-4 h-full w-full overflow-hidden"] @@ -770,23 +802,29 @@ newWidget_ pid currentRange = widgetViewerEditor_ pid Nothing currentRange Nothi -- Dashboard List -- -data DashboardsGet = DashboardsGet +data DashboardsGetD = DashboardsGetD { dashboards :: V.Vector Dashboards.DashboardVM , projectId :: Projects.ProjectId , embedded :: Bool -- Whether to render in embedded mode (for modals) + , teams :: V.Vector ManageMembers.Team } deriving (Generic, Show) +data DashboardsGet + = DashboardsGet (PageCtx DashboardsGetD) + | DashboardsGetSlim DashboardsGetD + deriving (Generic, Show) instance ToHtml DashboardsGet where - toHtml dash = toHtml $ dashboardsGet_ dash + toHtml (DashboardsGet (PageCtx pc dg)) = toHtml $ PageCtx pc $ dashboardsGet_ dg + toHtml (DashboardsGetSlim dash) = toHtml $ dashboardsGet_ dash toHtmlRaw = toHtml renderDashboardListItem :: Bool -> Text -> Text -> Text -> Maybe Text -> Maybe Text -> Maybe Text -> Html () renderDashboardListItem checked tmplClass title value description icon prview = label_ [ class_ - [text| cursor-pointer group/it border border-transparent hover:bg-fillWeaker hover:border-strokeWeak rounded-lg flex p-1.5 gap-2 items-center + [text| cursor-pointer group/it text-sm border border-transparent hover:bg-fillWeaker hover:border-strokeWeak rounded-lg flex p-1.5 gap-2 items-center group-has-[input:checked]/it:bg-fillWeaker group-has-[input:checked]/it:border-strokeWeak dashboardListItem|] , term "data-title" title , term "data-description" $ maybeToMonoid description @@ -806,110 +844,201 @@ renderDashboardListItem checked tmplClass title value description icon prview = ] do input_ $ [class_ $ "hidden " <> tmplClass, type_ "radio", name_ "file", value_ value] <> [checked_ | checked] - span_ [class_ "p-1 px-2 bg-fillWeak rounded-md"] $ faSprite_ (fromMaybe "square-dashed" icon) "regular" "w-4 h-4" + span_ [class_ "p-1 px-2 bg-fillWeak rounded-md"] $ faSprite_ (fromMaybe "square-dashed" icon) "regular" "w-3 h-3" span_ [class_ "grow"] $ toHtml title - span_ [class_ "px-2 p-1 invisible group-has-[input:checked]/it:visible"] $ faSprite_ "chevron-right" "regular" "w-4 h-4" + span_ [class_ "px-2 p-1 invisible group-has-[input:checked]/it:visible"] $ faSprite_ "chevron-right" "regular" "w-3 h-3" -dashboardsGet_ :: DashboardsGet -> Html () +dashboardsGet_ :: DashboardsGetD -> Html () dashboardsGet_ dg = do unless dg.embedded $ Components.modal_ "newDashboardMdl" "" $ form_ - [ class_ "grid grid-cols-7 overflow-hidden h-full gap-4 group/md" + [ class_ "flex h-[90vh] gap-4 group/md" , hxPost_ "" + , hxVals_ "js:{ teams: getSelectedTeams() }" ] do - div_ [class_ "col-span-2 space-y-4"] do - strong_ "Create dashboard" - label_ [class_ "input input-sm flex items-center "] do - faSprite_ "magnifying-glass" "regular" "w-4 h-4 opacity-70" - input_ - [ type_ "text" - , class_ "grow pl-2" - , placeholder_ "Search" - , [__| - on keyup - if the event's key is 'Escape' set my value to '' then trigger keyup - else show <.dashboardListItem/> in #dashListItemParent when its textContent.toLowerCase() contains my value.toLowerCase() |] - ] - kbd_ [class_ "kbd kbd-sm"] "/" - div_ [class_ "space-y-1", id_ "dashListItemParent"] do + div_ [class_ "w-2/7 space-y-4 h-full flex flex-col"] do + div_ [class_ "flex flex-col gap-2 border-b pb-4"] do + strong_ "Create dashboard" + label_ [class_ "input input-sm flex items-center "] do + faSprite_ "magnifying-glass" "regular" "w-4 h-4 opacity-70" + input_ + [ type_ "text" + , class_ "grow pl-2" + , placeholder_ "Search" + , [__| + on keyup + if the event's key is 'Escape' set my value to '' then trigger keyup + else show <.dashboardListItem/> in #dashListItemParent when its textContent.toLowerCase() contains my value.toLowerCase() |] + ] + kbd_ [class_ "kbd kbd-sm"] "/" + div_ [class_ "space-y-1 h-auto overflow-auto", id_ "dashListItemParent"] do renderDashboardListItem True "tmplRadio0" "Blank dashboard" "" (Just "Get started from a blank slate") (Just "cards-blank") Nothing iforM_ dashboardTemplates \idx dashTmpl -> do let tmplItemClass = "tmplRadio" <> show (idx + 1) renderDashboardListItem False tmplItemClass (maybeToMonoid dashTmpl.title) (maybeToMonoid dashTmpl.file) dashTmpl.description dashTmpl.icon dashTmpl.preview - div_ [class_ "col-span-5 px-3 py-5 divide-y h-full overflow-y-scroll "] do - div_ [class_ "flex gap-3 pb-5"] do - div_ $ div_ [class_ "p-2 bg-fillWeaker rounded-lg ", id_ "dItemIcon"] $ faSprite_ "cards-blank" "regular" "w-8 h-8" - div_ [class_ "flex-1"] do - strong_ [class_ "text-xl", id_ "dItemTitle"] "Custom Dashboard" - p_ [class_ "text-sm line-clamp-2 min-h-10", id_ "dItemDescription"] "Get started from a blank slate" - div_ [class_ "flex items-center justify-center shrink"] $ button_ [class_ "leading-none rounded-lg p-3 cursor-pointer bg-fillBrand-strong shadow-sm text-white", type_ "submit"] "Select template" + div_ [class_ "w-5/7 px-3 py-5 h-full overflow-y-scroll "] do + div_ [class_ "flex items-end justify-between gap-2"] do + div_ [class_ "flex items-center w-full justify-between gap-2"] do + label_ [class_ "flex flex-col gap-1 w-full"] do + span_ [class_ "text-sm font-medium"] "Dashboard name" + input_ + [ type_ "text" + , class_ "input input-sm w-full shrink-1" + , placeholder_ "Dashboard Title" + , name_ "title" + , required_ "required" + ] + label_ [class_ "flex flex-col gap-1 w-full"] do + span_ [class_ "text-sm font-medium"] "Teams" + input_ + [ type_ "text" + , class_ "input input-sm w-full shrink-1" + , id_ "teamHandlesInput" + , name_ "teams" + , placeholder_ "Add teams" + ] + + div_ [class_ "flex items-center justify-center shrink"] $ button_ [class_ "btn btn-primary btn-sm", type_ "submit"] "Create" + div_ [class_ "py-2 border-b border-b-strokeWeak"] do + span_ [class_ "text-sm "] "Using " + span_ [class_ "text-sm font-medium", id_ "dItemTitle"] "Custom Dashboard" + span_ [class_ "text-sm "] " template" + p_ [class_ "text-xs text-textWeak w-full overflow-ellipsis truncate", id_ "dItemDescription"] "Get started from a blank slate" div_ [class_ "pt-5"] - $ div_ [class_ "bg-[#1e9cff] px-5 py-8 rounded-xl aspect-square w-full flex items-center"] - $ img_ [src_ "/public/assets/svgs/screens/dashboard_blank.svg", class_ "w-full", id_ "dItemPreview"] + $ div_ [class_ "bg-fillBrand-strong px-2 py-4 rounded-xl w-full flex items-center"] + $ img_ [src_ "/public/assets/svgs/screens/dashboard_blank.svg", class_ "w-full rounded overflow-hidden", id_ "dItemPreview"] + let teamList = decodeUtf8 $ AE.encode $ (\x -> AE.object ["name" AE..= x.handle, "value" AE..= x.id]) <$> dg.teams + script_ + [text| + window.addEventListener('DOMContentLoaded', (event) => { + const tagify = createTagify('#teamHandlesInput', {tagTextProp: 'name',whitelist: $teamList,}); + }); + const getSelectedTeams = () => { + return tagify.value.map(item => item.value); + } + |] - div_ [id_ "itemsListPage", class_ "mx-auto px-6 pt-4 gap-8 w-full flex flex-col h-full overflow-hidden pb-2 group/pg"] do - div_ [class_ "flex"] $ label_ [class_ "input input-md flex-1 flex bg-fillWeaker border-strokeWeak shadow-none overflow-hidden items-center gap-2"] do - faSprite_ "magnifying-glass" "regular" "w-4 h-4 opacity-70" - input_ - [ type_ "text" - , class_ "grow" - , placeholder_ "Search" - , [__|on keyup if the event's key is 'Escape' set my value to '' then trigger keyup - else show <.itemListItem/> in #itemsListPage when its textContent.toLowerCase() contains my value.toLowerCase() |] - ] + div_ [id_ "itemsListPage", class_ $ "mx-auto gap-8 w-full flex flex-col h-full overflow-hidden group/pg" <> if dg.embedded then "" else "pb-2 px-6 pt-8"] do + let getTeams x = mapMaybe (\xx -> find (\t -> t.id == xx) dg.teams) (V.toList x.teams) + let dashboardCardItems = + V.map + ( \d -> + DashboardCard + { id = d.id + , title = d.title + , createdAt = d.createdAt + , createdBy = d.createdBy + , starredSince = d.starredSince + , homepageSince = d.homepageSince + , teams = V.fromList $ getTeams d + , widgetCount = maybe 0 (\x -> length x.widgets) $ loadDashboardFromVM d + } + ) + dg.dashboards - when dg.embedded $ h3_ [class_ "text-lg font-normal"] "Select a dashboard below, and the widget will be copied there" - - div_ [class_ $ "grid gap-5 " <> if dg.embedded then "grid-cols-1" else "grid-cols-2"] do - forM_ dg.dashboards \dashVM -> do - let dash = loadDashboardFromVM dashVM - let attrs = - if dg.embedded - then - [ class_ "cursor-pointer" - , hxPut_ ("/p/" <> dg.projectId.toText <> "/dashboards/" <> dashVM.id.toText) - , hxVals_ "js:{...JSON.parse(document.getElementById(document.getElementById('dashboards-modal-widget-id').value + '_widgetEl').dataset.widget)}" - , hxSwap_ "none" - , hxExt_ "json-enc" - ] - else [href_ ("/p/" <> dg.projectId.toText <> "/dashboards/" <> dashVM.id.toText)] - a_ ([class_ "rounded-xl border border-strokeWeak hover:border-strokeBrand-strong gap-3.5 p-4 bg-fillWeaker flex itemListItem group/i"] <> attrs) do - div_ [class_ "flex-1 space-y-2"] do - div_ [class_ "flex items-center gap-2"] do - span_ [class_ "group-hover/i:underline underline-offset-2"] - $ strong_ [class_ "font-medium"] (toHtml $ bool "Untitled" dashVM.title (dashVM.title /= "")) - span_ [class_ "leading-none", term "data-tippy-content" "This dashboard is currently your homepage."] do - when (isJust dashVM.homepageSince) $ faSprite_ "house" "regular" "w-4 h-4" - div_ [class_ "gap-2 flex items-center"] do - time_ [class_ "mr-2 text-textWeak", term "data-tippy-content" "Date of dashboard creation", datetime_ $ Utils.formatUTC dashVM.createdAt] $ toHtml $ formatTime defaultTimeLocale "%eth %b %Y" dashVM.createdAt - forM_ dashVM.tags (span_ [class_ "badge badge-neutral"] . toHtml @Text) - div_ [class_ "flex items-end justify-center gap-5"] do - button_ [class_ "leading-none", term "data-tippy-content" "click to star this dashboard"] - $ if isJust dashVM.starredSince - then faSprite_ "star" "solid" "w-5 h-5" - else faSprite_ "star" "regular" "w-5 h-5" - let widgetCount = maybe "0" (show . length . (.widgets)) dash - div_ [class_ "flex items-end gap-2", term "data-tippy-content" $ "There are " <> widgetCount <> " charts/widgets in this dashboard"] $ faSprite_ "chart-area" "regular" "w-5 h-5 text-iconNeutral" >> (span_ [class_ "leading-none"] . toHtml $ widgetCount) + let table = + Table + { config = def{elemID = "dashboardsListForm", renderAsTable = True} + , columns = + [ col "Title" renderDashboardTitle + , col "Modified" renderDateModified + , col "Teams" renderTeams + , col "Widgets" renderWidgetCount + ] + , rows = dashboardCardItems + , features = + def + { search = Just ClientSide + , zeroState = + Just + $ ZeroState + { icon = "empty-set" + , title = "No dashboards created yet" + , description = "Create dashboards to visualize and monitor your project's metrics and logs." + , actionText = "Create dashboard" + , destination = + Left $ "/p/" <> dg.projectId.toText <> "/log_explorer#create-alert-toggle" + } + } + } + div_ [class_ "w-full overflow-y-auto", id_ "dashboardsTableContainer"] do + toHtml table -dashboardsGetH :: Projects.ProjectId -> Maybe Text -> ATAuthCtx (RespHeaders (PageCtx DashboardsGet)) -dashboardsGetH pid embeddedM = do +data DashboardCard = DashboardCard + { id :: Dashboards.DashboardId + , title :: Text + , createdAt :: Time.UTCTime + , createdBy :: Users.UserId + , starredSince :: Maybe Time.UTCTime + , homepageSince :: Maybe Time.UTCTime + , teams :: V.Vector ManageMembers.Team + , widgetCount :: Int + } + deriving (Generic, Show) + + +renderDashboardTitle :: DashboardCard -> Html () +renderDashboardTitle dc = div_ [class_ "flex items-center gap-2"] do + span_ [class_ "text-sm font-medium"] $ toHtml dc.title + when (isJust dc.starredSince) $ span_ [class_ "text-yellow-400"] $ faSprite_ "star" "solid" "w-4 h-4" + when (isJust dc.homepageSince) $ span_ [class_ "text-green-500"] $ faSprite_ "home" "solid" "w-4 h-4" + + +renderDateModified :: DashboardCard -> Html () +renderDateModified dc = div_ [class_ "text-sm text-textWeak"] $ toHtml $ formatTime defaultTimeLocale "%b %-d, %Y %-I:%M %p" dc.createdAt + + +renderTeams :: DashboardCard -> Html () +renderTeams dc = div_ [class_ "flex items-center gap-2"] do + if V.null dc.teams + then span_ [class_ "text-sm text-textWeak"] "No teams" + else forM_ dc.teams \team -> do + span_ [class_ "px-2 py-1 bg-fillWeak rounded-full text-sm"] $ toHtml team.handle + + +renderWidgetCount :: DashboardCard -> Html () +renderWidgetCount dc = div_ [class_ "text-sm text-textWeak"] $ toHtml $ show dc.widgetCount + + +addTeamsDrowndown_ :: Projects.ProjectId -> V.Vector ManageMembers.Team -> Html () +addTeamsDrowndown_ pid teams = div_ [class_ "dropdown dropdown-end"] do + label_ [tabindex_ "0", role_ "button", class_ "flex items-center gap-2 btn btn-sm"] do + faSprite_ "plus" "regular" "w-3 h-3" + span_ "Add teams" + ul_ [tabindex_ "0", class_ "dropdown-content rounded w-52 px-0 py-3"] do + h6_ [class_ "font-medium mb-2 px-2"] "Add up to 5 teams" + forM_ teams \team -> do + li_ [class_ "p-0"] do + label_ [class_ "flex flex-row items-center gap-1 px-2 text-sm hover:bg-fillWeak"] do + input_ [type_ "checkbox", class_ "checkbox checkbox-xs", name_ "teamHandles", value_ $ UUID.toText team.id] + span_ [class_ "px-2 py-1"] $ toHtml team.handle + button_ [class_ "btn btn-primary btn-xs float-right", hxPost_ $ "/p/" <> pid.toText <> "/dashboards/bulk_action/add_teams", hxSwap_ "none"] "Add teams" + + +dashboardsGetH :: Projects.ProjectId -> Maybe Text -> Maybe UUID.UUID -> ATAuthCtx (RespHeaders DashboardsGet) +dashboardsGetH pid embeddedM teamIdM = do (sess, project) <- Sessions.sessionAndProject pid appCtx <- ask @AuthContext now <- Time.currentTime - dashboards <- dbtToEff $ DBT.selectManyByField @Dashboards.DashboardVM [DBT.field| project_id |] pid + dashboards <- case teamIdM of + Just teamId -> do + ds <- Dashboards.selectDashboardsByTeam pid teamId + pure $ V.fromList ds + Nothing -> dbtToEff $ DBT.selectManyByField @Dashboards.DashboardVM [DBT.field| project_id |] pid + teams <- dbtToEff $ ManageMembers.getTeams pid -- Check if we're requesting in embedded mode (for modals, etc.) let embedded = embeddedM == Just "true" || embeddedM == Just "1" || embeddedM == Just "yes" - if embedded + if embedded || isJust teamIdM then -- For embedded mode, use a minimal BWConfig that will still work with ToHtml instance - addRespHeaders $ PageCtx def $ DashboardsGet{dashboards, projectId = pid, embedded = True} + addRespHeaders $ DashboardsGetSlim DashboardsGetD{dashboards, projectId = pid, embedded = True, teams} + -- PageCtx def $ DashboardsGetD{dashboards, projectId = pid, embedded = True, teams} else do freeTierExceeded <- dbtToEff $ checkFreeTierExceeded pid project.paymentPlan - let bwconf = (def :: BWConfig) { sessM = Just sess @@ -917,42 +1046,60 @@ dashboardsGetH pid embeddedM = do , pageTitle = "Dashboards" , freeTierExceeded = freeTierExceeded , config = appCtx.config - , pageActions = Just $ label_ [Lucid.for_ "newDashboardMdl", class_ "leading-none rounded-xl shadow-sm p-3 cursor-pointer bg-fillBrand-strong text-white"] "New Dashboard" + , pageActions = Just $ label_ [Lucid.for_ "newDashboardMdl", class_ "btn btn-primary text-white"] (faSprite_ "plus" "regular" "h-4 w-4 mr-2" >> "New Dashboard") } - addRespHeaders $ PageCtx bwconf $ DashboardsGet{dashboards, projectId = pid, embedded = False} + addRespHeaders $ DashboardsGet (PageCtx bwconf $ DashboardsGetD{dashboards, projectId = pid, embedded = False, teams}) -newtype DashboardForm = DashboardForm +data DashboardRes = DashboardNoContent | DashboardPostError Text + deriving (Generic, Show) + + +instance ToHtml DashboardRes where + toHtml DashboardNoContent = "" + toHtml (DashboardPostError msg) = div_ [class_ "text-textError"] $ toHtml msg + toHtmlRaw = toHtml + + +data DashboardForm = DashboardForm { file :: Text + , teams :: [UUID.UUID] + , title :: Text } deriving stock (Generic, Show) deriving anyclass (FromForm) -dashboardsPostH :: Projects.ProjectId -> DashboardForm -> ATAuthCtx (RespHeaders NoContent) +dashboardsPostH :: Projects.ProjectId -> DashboardForm -> ATAuthCtx (RespHeaders DashboardRes) dashboardsPostH pid form = do (sess, project) <- Sessions.sessionAndProject pid now <- Time.currentTime did <- UUIDId <$> UUID.genUUID - let dashM = find (\dashboard -> dashboard.file == Just form.file) dashboardTemplates - let redirectURI = "/p/" <> pid.toText <> "/dashboards/" <> did.toText - dbtToEff - $ DBT.insert @Dashboards.DashboardVM - $ Dashboards.DashboardVM - { id = did - , projectId = pid - , createdAt = now - , updatedAt = now - , createdBy = sess.user.id - , baseTemplate = if form.file == "" then Nothing else Just form.file - , schema = Nothing - , starredSince = Nothing - , homepageSince = Nothing - , tags = V.fromList $ fromMaybe [] $ dashM >>= (.tags) - , title = fromMaybe [] $ dashM >>= (.title) - } - redirectCS redirectURI - addRespHeaders NoContent + if form.title == "" + then do + addErrorToast "Dashboard title is required" Nothing + addRespHeaders $ DashboardPostError "Dashboard title is required" + else do + let dashM = find (\dashboard -> dashboard.file == Just form.file) dashboardTemplates + let redirectURI = "/p/" <> pid.toText <> "/dashboards/" <> did.toText + let dbd = + Dashboards.DashboardVM + { id = did + , projectId = pid + , createdAt = now + , updatedAt = now + , createdBy = sess.user.id + , baseTemplate = if form.file == "" then Nothing else Just form.file + , schema = Nothing + , starredSince = Nothing + , homepageSince = Nothing + , tags = V.fromList $ fromMaybe [] $ dashM >>= (.tags) + , title = form.title + , teams = V.fromList form.teams + } + _ <- Dashboards.insert dbd + redirectCS redirectURI + addRespHeaders DashboardNoContent -- -- Template Haskell splice to generate the list of dashboards by reading the dashboards folder in filesystem @@ -989,6 +1136,7 @@ entrypointRedirectGetH baseTemplate title tags pid qparams = do , homepageSince = Nothing , tags = V.fromList tags , title = title + , teams = V.empty } pure did.toText redirectTo <- @@ -1017,11 +1165,13 @@ newtype DashboardRenameForm = DashboardRenameForm -- | Handler for renaming a dashboard. -- It updates the title of the specified dashboard. -dashboardRenamePatchH :: Projects.ProjectId -> Dashboards.DashboardId -> DashboardRenameForm -> ATAuthCtx (RespHeaders (Html ())) +dashboardRenamePatchH :: Projects.ProjectId -> Dashboards.DashboardId -> DashboardRenameForm -> ATAuthCtx (RespHeaders DashboardRes) dashboardRenamePatchH pid dashId form = do mDashboard <- dbtToEff $ DBT.selectOneByField @Dashboards.DashboardVM [DBT.field| id |] (Only dashId) case mDashboard of - Nothing -> throwError $ err404{errBody = "Dashboard not found or does not belong to this project"} + Nothing -> do + addErrorToast "Dashboard not found or does not belong to this project" Nothing + addRespHeaders $ DashboardPostError "Dashboard not found or does not belong to this project" Just dashVM -> do _ <- dbtToEff $ DBT.updateFieldsBy @Dashboards.DashboardVM [[DBT.field| title |]] ([DBT.field| id |], dashId) (Only form.title) @@ -1037,17 +1187,18 @@ dashboardRenamePatchH pid dashId form = do addSuccessToast "Dashboard renamed successfully" Nothing addTriggerEvent "closeModal" "" - addRespHeaders (toHtml form.title) + addRespHeaders DashboardNoContent -- | Handler for duplicating a dashboard. -- It creates a new dashboard with the same content but with "(Copy)" appended to the title. -dashboardDuplicatePostH :: Projects.ProjectId -> Dashboards.DashboardId -> ATAuthCtx (RespHeaders NoContent) +dashboardDuplicatePostH :: Projects.ProjectId -> Dashboards.DashboardId -> ATAuthCtx (RespHeaders DashboardRes) dashboardDuplicatePostH pid dashId = do mDashboard <- dbtToEff $ DBT.selectOneByField @Dashboards.DashboardVM [DBT.field| id |] (Only dashId) - case mDashboard of - Nothing -> throwError $ err404{errBody = "Dashboard not found or does not belong to this project"} + Nothing -> do + addErrorToast "Dashboard not found or does not belong to this project" Nothing + addRespHeaders $ DashboardPostError "Dashboard not found or does not belong to this project" Just dashVM -> do (sess, _) <- Sessions.sessionAndProject pid now <- Time.currentTime @@ -1080,13 +1231,13 @@ dashboardDuplicatePostH pid dashId = do let redirectURI = "/p/" <> pid.toText <> "/dashboards/" <> newDashId.toText redirectCS redirectURI addSuccessToast "Dashboard was duplicated successfully" Nothing - addRespHeaders NoContent + addRespHeaders DashboardNoContent -- | Handler for deleting a dashboard. -- It verifies the dashboard exists and belongs to the project before deletion. -- After deletion, redirects to the dashboard list page. -dashboardDeleteH :: Projects.ProjectId -> Dashboards.DashboardId -> ATAuthCtx (RespHeaders NoContent) +dashboardDeleteH :: Projects.ProjectId -> Dashboards.DashboardId -> ATAuthCtx (RespHeaders DashboardRes) dashboardDeleteH pid dashId = do mDashboard <- dbtToEff $ DBT.selectOneByField @Dashboards.DashboardVM [DBT.field| id |] (Only dashId) case mDashboard of @@ -1097,6 +1248,30 @@ dashboardDeleteH pid dashId = do let redirectURI = "/p/" <> pid.toText <> "/dashboards" redirectCS redirectURI addSuccessToast "Dashboard was deleted successfully" Nothing + addRespHeaders DashboardNoContent + + +data DashboardBulkActionForm = DashboardBulkActionForm + { dashboardId :: [Dashboards.DashboardId] + , teamHandles :: [UUID.UUID] + } + deriving stock (Generic, Show) + deriving anyclass (FromForm) + + +dashboardBulkActionPostH :: Projects.ProjectId -> Text -> DashboardBulkActionForm -> ATAuthCtx (RespHeaders NoContent) +dashboardBulkActionPostH pid action DashboardBulkActionForm{..} = do + case action of + "delete" -> do + _ <- Dashboards.deleteDashboardsByIds pid $ V.fromList dashboardId + addSuccessToast "Selected dashboards were deleted successfully" Nothing + addRespHeaders NoContent + "add_teams" -> do + _ <- Dashboards.addTeamsToDashboards pid (V.fromList dashboardId) (V.fromList teamHandles) + addSuccessToast "Teams added to selected dashboards successfully" Nothing + addRespHeaders NoContent + _ -> do + addErrorToast "Invalid action" Nothing addRespHeaders NoContent diff --git a/src/Pages/LogExplorer/Log.hs b/src/Pages/LogExplorer/Log.hs index d5862a6b0..032662818 100644 --- a/src/Pages/LogExplorer/Log.hs +++ b/src/Pages/LogExplorer/Log.hs @@ -50,7 +50,10 @@ import Utils (checkFreeTierExceeded, faSprite_, formatUTC, getServiceColors, lev import Data.Time.Format.ISO8601 (iso8601ParseM, iso8601Show) import Data.UUID qualified as UUID +import Models.Apis.Monitors (MonitorAlertConfig (..)) import Models.Apis.Monitors qualified as Monitors +import Models.Projects.ProjectMembers (TeamVM (..)) +import Models.Projects.ProjectMembers qualified as ManageMembers import Pkg.AI (callOpenAIAPI, systemPrompt) import Pkg.AI qualified as AI @@ -461,6 +464,9 @@ apiLogH pid queryM' cols' cursorM' sinceM fromM toM layoutM sourceM targetSpansM freeTierExceeded <- dbtToEff $ checkFreeTierExceeded pid project.paymentPlan + -- Fetch teams + teams <- dbtToEff $ ManageMembers.getTeams pid + patterns <- case effectiveVizType of Just "patterns" -> do patternsResult <- RequestDumps.fetchLogPatterns pid queryAST (fromD, toD) (parseMaybe pSource =<< sourceM) pTargetM (fromMaybe 0 skipM) @@ -567,6 +573,7 @@ apiLogH pid queryM' cols' cursorM' sinceM fromM toM layoutM sourceM targetSpansM , patternsToSkip , targetPattern = pTargetM , project = project + , teams } let jsonResponse = LogsGetJson finalVecs colors nextLogsURL resetLogsURL recentLogsURL curatedColNames colIdxMap resultCount @@ -653,6 +660,7 @@ data ApiLogsPageData = ApiLogsPageData , patternsToSkip :: Int , targetPattern :: Maybe Text , project :: Projects.Project + , teams :: V.Vector ManageMembers.Team } @@ -855,7 +863,7 @@ apiLogsPage page = do div_ [class_ "hidden group-has-[#create-alert-toggle:checked]/pg:block"] $ resizer_ "alert_container" "alert_width" False div_ [class_ "grow-0 shrink-0 overflow-y-auto overflow-x-hidden h-full c-scroll hidden group-has-[#create-alert-toggle:checked]/pg:block", id_ "alert_container", style_ "width: 500px;"] do - alertConfigurationForm_ page.project page.alert + alertConfigurationForm_ page.project page.alert page.teams div_ [class_ $ "transition-opacity duration-200 hidden group-has-[#viz-logs:checked]/pg:block " <> if isJust page.targetEvent then "" else "opacity-0 pointer-events-none hidden", id_ "resizer-details_width-wrapper"] $ resizer_ "log_details_container" "details_width" False @@ -954,8 +962,8 @@ curateCols summaryCols cols = sortBy sortAccordingly filteredCols -- | Render alert configuration form for creating log-based alerts -alertConfigurationForm_ :: Projects.Project -> Maybe Monitors.QueryMonitor -> Html () -alertConfigurationForm_ project alertM = do +alertConfigurationForm_ :: Projects.Project -> Maybe Monitors.QueryMonitor -> V.Vector ManageMembers.Team -> Html () +alertConfigurationForm_ project alertM teams = do let pid = project.id isByos = project.paymentPlan == "Bring your own storage" div_ [class_ "bg-fillWeaker h-full flex flex-col group/alt"] do @@ -980,7 +988,7 @@ alertConfigurationForm_ project alertM = do form_ [ id_ "alert-form" , hxPost_ $ "/p/" <> pid.toText <> "/monitors/alerts" - , hxVals_ "js:{query:getQueryFromEditor(), since: getTimeRange().since, from: getTimeRange().from, to:getTimeRange().to, source: params().source || 'spans', vizType: getVizType()}" + , hxVals_ "js:{query:getQueryFromEditor(), since: getTimeRange().since, from: getTimeRange().from, to:getTimeRange().to, source: params().source || 'spans', vizType: getVizType(), teams: getSelectedTeams()}" , hxSwap_ "none" , class_ "flex flex-col gap-3" , [__|on htmx:afterRequest @@ -1188,6 +1196,37 @@ alertConfigurationForm_ project alertM = do div_ [class_ "flex items-center gap-1.5 ml-2 hidden", id_ "stopAfterInput"] do input_ [type_ "number", class_ "input input-sm w-16", value_ "5", name_ "stopAfter", min_ "1", max_ "100"] span_ [class_ "text-xs text-textWeak"] "occurrences" + -- Teams + div_ [class_ "border-t border-strokeWeak pt-4 mt-4"] do + div_ [class_ "flex flex-col gap-1"] do + span_ [class_ "text text-sm"] "Teams" + span_ [class_ "text-xs text-textWeak"] "Add teams to notify (if no team is added, project level notification channels will be used)" + textarea_ [class_ "input max-h-max w-full mt-2 resize-none", name_ "teams"] "" + let teamList = decodeUtf8 $ AE.encode $ (\x -> AE.object ["name" AE..= x.handle, "value" AE..= x.id]) <$> teams + -- alertConfig.teams is a list of team IDs + -- teams is a list of TeamVM with id and name + -- map all team IDs to names + teamName tId teamVMs = + case V.find (\t -> t.id == tId) teamVMs of + Just t -> t.handle + Nothing -> "Unknown Team" + + existingTeams = decodeUtf8 $ AE.encode $ case alertM of + Nothing -> [] + Just am -> (\tId -> AE.object ["name" AE..= teamName tId teams, "value" AE..= tId]) <$> am.teams + script_ + [text| + window.addEventListener('DOMContentLoaded', () => { + const tagify = createTagify('#alert-form textarea[name="teams"]', { + tagTextProp: 'name', + whitelist: $teamList, + }); + tagify.addTags($existingTeams); + }) + const getSelectedTeams = () => { + return tagify.value.map(item => item.value); + } + |] -- Recipients checkbox with better spacing div_ [class_ "flex items-center gap-2 mt-4 pt-3 border-t border-strokeWeak"] do diff --git a/src/Pages/Monitors.hs b/src/Pages/Monitors.hs index 42ffc4188..fc09bcd97 100644 --- a/src/Pages/Monitors.hs +++ b/src/Pages/Monitors.hs @@ -58,6 +58,7 @@ data AlertUpsertForm = AlertUpsertForm , conditionType :: Maybe Text , source :: Maybe Text , vizType :: Maybe Text + , teams :: [UUID.UUID] } deriving stock (Generic, Show) deriving anyclass (FromForm) @@ -104,6 +105,7 @@ convertToQueryMonitor projectId now queryMonitorId alertForm = , deletedAt = Nothing , deactivatedAt = Nothing , visualizationType = fromMaybe "timeseries" alertForm.vizType + , teams = V.fromList alertForm.teams } diff --git a/src/Pages/Monitors/Testing.hs b/src/Pages/Monitors/Testing.hs index 1cc35c603..b3e16d7de 100644 --- a/src/Pages/Monitors/Testing.hs +++ b/src/Pages/Monitors/Testing.hs @@ -4,6 +4,7 @@ module Pages.Monitors.Testing ( unifiedMonitorsGetH, unifiedMonitorOverviewH, statusBadge_, + teamAlertsGetH, ) where @@ -26,6 +27,7 @@ import Models.Users.Sessions qualified as Sessions import Pages.BodyWrapper (BWConfig (..), PageCtx (..)) import Pages.Components (statBox_) import Pkg.Components.Table (Config (..), Features (..), SearchMode (..), TabFilter (..), TabFilterOpt (..), Table (..), ZeroState (..), col, withAttrs) +import Pkg.Components.Table qualified as Table import Pkg.Components.Widget (Widget (..)) import Pkg.Components.Widget qualified as Widget import Relude hiding (ask) @@ -68,6 +70,17 @@ data UnifiedMonitorDetails } +teamAlertsGetH :: Projects.ProjectId -> UUID.UUID -> ATAuthCtx (RespHeaders (Table.TableRows UnifiedMonitorItem)) +teamAlertsGetH pid teamId = do + (sess, project) <- Sessions.sessionAndProject pid + appCtx <- ask @AuthContext + alerts <- dbtToEff $ Monitors.getAlertsByTeamHandle pid teamId + currTime <- Time.currentTime + let alerts' = V.map (toUnifiedMonitorItem pid currTime) alerts + + addRespHeaders $ Table.TableRows Nothing [] alerts' + + -- | Unified handler for monitors endpoint showing both alerts and multi-step monitors unifiedMonitorsGetH :: Projects.ProjectId diff --git a/src/Pages/Onboarding/Onboarding.hs b/src/Pages/Onboarding/Onboarding.hs index 585d42038..4ebb14f7e 100644 --- a/src/Pages/Onboarding/Onboarding.hs +++ b/src/Pages/Onboarding/Onboarding.hs @@ -356,7 +356,7 @@ onboardingConfPostH pid form = do onboardingCompleteBody :: Projects.ProjectId -> Html () onboardingCompleteBody pid = do - div_ [class_ "w-[550px] h-full flex items-center mx-auto relative"] $ do + div_ [class_ "w-xl h-full flex items-center mx-auto relative"] $ do canvas_ [id_ "drawing_canvas", class_ "absolute top-0 left-0 w-full"] pass div_ [class_ "flex-col gap-4 flex w-full p-14 my-auto border border-weak rounded-2xl"] $ do div_ [class_ "p-3 bg-fillSuccess-weak rounded-full w-max border-strokeSuccess-weak gap-2 inline-flex"] @@ -508,7 +508,7 @@ integrationsPage pid apikey = div_ [class_ "w-full flex h-screen overflow-hidden group/pg"] do div_ [class_ "w-1/2 bg-bgRaised h-full flex flex-col"] do div_ [class_ "pt-[156px] px-12 flex-shrink-0"] - $ div_ [class_ "max-w-[550px]"] + $ div_ [class_ "max-w-xl"] $ stepIndicator 4 "Instrument your apps or servers" $ "/p/" <> pid.toText @@ -796,7 +796,7 @@ formField labelText inputType inputName inputId inputValue = do notifChannelsWithUrls :: Text -> Text -> Projects.ProjectId -> Text -> V.Vector Text -> Bool -> Bool -> Html () notifChannelsWithUrls slackUrl discordUrl pid phone emails hasDiscord hasSlack = do - div_ [class_ "w-[550px] mx-auto mt-[156px] mb-10"] $ do + div_ [class_ "w-xl mx-auto mt-[156px] mb-10"] $ do div_ [id_ "inviteModalContainer"] pass div_ [class_ "flex-col gap-4 flex w-full"] $ do stepIndicator 3 "How should we notify you about issues?" $ "/p/" <> pid.toText <> "/onboarding?step=Survey" @@ -847,7 +847,7 @@ notifChannelsWithUrls slackUrl discordUrl pid phone emails hasDiscord hasSlack = onboardingInfoBody :: Projects.ProjectId -> Text -> Text -> Text -> Text -> Text -> Html () onboardingInfoBody pid firstName lastName cName cSize fUsFrm = do - div_ [class_ "w-[550px] mx-auto mt-[156px]"] $ do + div_ [class_ "w-xl mx-auto mt-[156px]"] $ do div_ [class_ "flex-col gap-4 flex w-full"] $ do stepIndicator 1 "Tell us a little bit about you" "" form_ [class_ "flex-col w-full gap-8 flex", hxPost_ $ "/p/" <> pid.toText <> "/onboarding/info", hxIndicator_ "#loadingIndicator"] $ do @@ -861,7 +861,7 @@ onboardingInfoBody pid firstName lastName cName cSize fUsFrm = do onboardingConfigBody :: Projects.ProjectId -> Text -> [Text] -> Html () onboardingConfigBody pid loca func = do - div_ [class_ "w-[550px] mx-auto mt-[156px]"] $ do + div_ [class_ "w-xl mx-auto mt-[156px]"] $ do div_ [class_ "flex-col gap-4 flex w-full"] $ do stepIndicator 2 "Let's configure your project" $ "/p/" <> pid.toText <> "/onboarding?step=Info" form_ [class_ "flex-col w-full gap-8 flex", hxPost_ $ "/p/" <> pid.toText <> "/onboarding/survey", hxIndicator_ "#loadingIndicator"] $ do diff --git a/src/Pages/Projects.hs b/src/Pages/Projects.hs index 4e1bc718a..9e9fda933 100644 --- a/src/Pages/Projects.hs +++ b/src/Pages/Projects.hs @@ -19,6 +19,8 @@ module Pages.Projects ( ManageMembersForm (..), manageSubGetH, ManageMembers (..), + -- ManageTeams + manageTeamsGetH, -- CreateProject createProjectPostH, createProjectFormV, @@ -33,6 +35,12 @@ module Pages.Projects ( CreateProject (..), pricingUpdateGetH, CreateProjectResp (..), + manageTeamPostH, + manageTeamBulkActionH, + TeamForm (..), + teamGetH, + ManageTeams (..), + TBulkActionForm (..), ) where @@ -42,13 +50,17 @@ import Data.Aeson qualified as AE import Data.Base64.Types qualified as B64 import Data.CaseInsensitive (original) import Data.CaseInsensitive qualified as CI +import Data.Char (isAlphaNum, isDigit, isLower) import Data.Default (Default (..)) +import Data.Effectful.UUID (UUID) import Data.Effectful.UUID qualified as UUID import Data.Effectful.Wreq import Data.Effectful.Wreq qualified as W import Data.List.Unique (uniq) +import Data.Map qualified as Map import Data.Pool (withResource) import Data.Text qualified as T +import Data.Time import Data.UUID qualified as RealUUID import Data.Valor (Valor, check1, failIf, validateM) import Data.Valor qualified as Valor @@ -61,10 +73,15 @@ import Effectful.Reader.Static (ask) import Fmt import GHC.Records (HasField (getField)) import Lucid +import Lucid (Term (term), div_, href_, min_, pattern_, required_) import Lucid.Htmx +import Lucid.Htmx (hxPost_, hxSelect_, hxSwapOob_, hxTrigger_) import Lucid.Hyperscript (__) +import Models.Apis.Monitors qualified as Monitors import Models.Apis.Slack (SlackData, getDiscordDataByProjectId, getProjectSlackData) +import Models.Apis.Slack qualified as Slack import Models.Projects.ProjectApiKeys qualified as ProjectApiKeys +import Models.Projects.ProjectMembers (ProjectMembers (ProjectMembers), TeamMemberVM (..), TeamVM (..)) import Models.Projects.ProjectMembers qualified as ProjectMembers import Models.Projects.Projects qualified as Projects import Models.Users.Sessions qualified as Sessions @@ -73,7 +90,14 @@ import NeatInterpolation (text) import Network.Wreq (getWith) import OddJobs.Job (createJob) import Pages.BodyWrapper (BWConfig (..), PageCtx (..), bodyWrapper) +import Pages.Bots.Discord qualified as Discord +import Pages.Bots.Slack (channels, getSlackChannels) +import Pages.Bots.Slack qualified as Slack +import Pages.Bots.Slack qualified as SlackP +import Pages.Bots.Utils qualified as BotUtils import Pages.Components (paymentPlanPicker) +import Pkg.Components.Table (Config (renderAsTable), Features (bulkActions, rowId, search, zeroState), SearchMode (ClientSide), Table (..), ZeroState (ZeroState), col, elemID) +import Pkg.Components.Table qualified as Table import Pkg.Components.Widget (Widget (..), WidgetType (..), widget_) import Pkg.ConvertKit qualified as ConvertKit import Pkg.DeriveUtils (UUIDId (..)) @@ -84,8 +108,8 @@ import Servant.API (Header) import Servant.API.ResponseHeaders (Headers) import Servant.Server (err302, errHeaders) import System.Config (AuthContext (..), EnvConfig (..)) -import System.Types (ATAuthCtx, RespHeaders, addErrorToast, addRespHeaders, addSuccessToast, addTriggerEvent, redirectCS) -import Utils (faSprite_, insertIfNotExist, isDemoAndNotSudo, lookupValueText) +import System.Types (ATAuthCtx, RespHeaders, addErrorToast, addRespHeaders, addReswap, addSuccessToast, addTriggerEvent, redirectCS) +import Utils (faSprite_, formatUTC, insertIfNotExist, isDemoAndNotSudo, lookupValueText) import Web.FormUrlEncoded (FromForm) import "base64" Data.ByteString.Base64 qualified as B64 @@ -243,7 +267,7 @@ integrationsSettingsGetH pid = do slackInfo <- getProjectSlackData pid let bwconf = (def :: BWConfig){sessM = Just sess, currProject = Just project, pageTitle = "Integrations", isSettingsPage = True, config = appCtx.config} - addRespHeaders $ bodyWrapper bwconf $ integrationsBody sess.persistentSession appCtx.config True createProj (Just project.notificationsChannel) project.whatsappNumbers slackInfo + addRespHeaders $ bodyWrapper bwconf $ integrationsBody pid sess.persistentSession appCtx.config True createProj (Just project.notificationsChannel) project.whatsappNumbers slackInfo data NotifListForm = NotifListForm @@ -310,11 +334,33 @@ validateWhatsapp :: [Text] -> [Text] -> Either Text () validateWhatsapp notificationsChannel numbers = if "phone" `elem` notificationsChannel && null numbers then Left "Provide at least one whatsapp number" else Right () -integrationsBody :: Sessions.PersistentSession -> EnvConfig -> Bool -> CreateProjectForm -> Maybe (V.Vector Projects.NotificationChannel) -> V.Vector Text -> Maybe SlackData -> Html () -integrationsBody sess envCfg isUpdate cp notifChannel phones slackData = do +validateTeamDetails :: Text -> Text -> Either Text () +validateTeamDetails name handle = do + validateName name + validateHandle handle + pure () + where + validNameChar c = isAlphaNum c || c == ' ' || c == '-' || c == '_' + validHandleChar c = isLower c || isDigit c || c == '-' + validateName n + | T.null n = Left "Team name is required" + | T.length n < 3 = Left "Team name must be at least 3 characters" + | not (T.all validNameChar n) = + Left "Invalid characters in team name" + | otherwise = Right () + validateHandle h + | T.null h = Left "Handle is required" + | not (validHandleChar <$> T.unpack h & and) = + Left "Handle must be lowercase, no spaces, and hyphens only" + | not (isLower (T.head h)) = Left "Handle must start with a lowercase letter" + | otherwise = Right () + + +integrationsBody :: Projects.ProjectId -> Sessions.PersistentSession -> EnvConfig -> Bool -> CreateProjectForm -> Maybe (V.Vector Projects.NotificationChannel) -> V.Vector Text -> Maybe SlackData -> Html () +integrationsBody pid' sess envCfg isUpdate cp notifChannel phones slackData = do section_ [id_ "main-content", class_ "p-3 py-5 sm:p-6 overflow-y-scroll h-full"] do div_ [class_ "mx-auto", style_ "max-width:1000px"] do - let pid = cp.title -- Using title as pid placeholder, will be fixed + let pid = pid'.toText div_ [ class_ "mt-10" , hxPost_ [text|/p/$pid/notifications-channels|] @@ -328,9 +374,9 @@ integrationsBody sess envCfg isUpdate cp notifChannel phones slackData = do div_ [class_ "flex flex-col gap-4"] do p_ [] "Select channels to receive updates on this project." renderNotificationOption "Email Notifications" "Receive project updates via email" "email" Projects.NEmail notifChannel (faSprite_ "envelope" "solid" "h-6 w-6") "" - renderNotificationOption "Slack" "Send notifications to Slack channels" "slack" Projects.NSlack notifChannel (faSprite_ "slack" "solid" "h-6 w-6") (renderSlackIntegration envCfg "" slackData) - renderNotificationOption "Discord" "Send notifications to Discord servers" "discord" Projects.NDiscord notifChannel (faSprite_ "discord" "solid" "h-6 w-6") (renderDiscordIntegration envCfg "") - renderNotificationOption "WhatsApp" "Send notificataoin via WhatsApp" "phone" Projects.NPhone notifChannel (faSprite_ "whatsapp" "solid" "h-6 w-6") renderWhatsappIntegration + renderNotificationOption "Slack" "Send notifications to Slack channels" "slack" Projects.NSlack notifChannel (faSprite_ "slack" "solid" "h-6 w-6") (renderSlackIntegration envCfg pid slackData) + renderNotificationOption "Discord" "Send notifications to Discord servers" "discord" Projects.NDiscord notifChannel (faSprite_ "discord" "solid" "h-6 w-6") (renderDiscordIntegration envCfg pid) + renderNotificationOption "WhatsApp" "Send notification via WhatsApp" "phone" Projects.NPhone notifChannel (faSprite_ "whatsapp" "solid" "h-6 w-6") renderWhatsappIntegration button_ [class_ "btn btn-primary w-max", [__| on click htmx.trigger("#notifsForm", "submit")|]] "Save Selections" let tgs = decodeUtf8 $ AE.encode $ V.toList phones script_ @@ -477,6 +523,450 @@ manageMembersPostH pid onboardingM form = do addRespHeaders $ ManageMembersPost projMembers +data TeamForm = TeamForm + { teamName :: Text + , teamDescription :: Text + , teamHandle :: Text + , teamMembers :: V.Vector Users.UserId + , notifEmails :: V.Vector Text + , slackChannels :: V.Vector Text + , discordChannels :: V.Vector Text + , teamId :: Maybe UUID.UUID + } + deriving stock (Eq, Generic, Show) + deriving anyclass (FromForm) +instance AE.FromJSON TeamForm where + parseJSON = AE.withObject "TeamForm" $ \o -> do + TeamForm + <$> o + AE..: "teamName" + <*> o + AE..: "teamDescription" + <*> o + AE..: "teamHandle" + <*> o + AE..:? "teamMembers" + AE..!= V.empty + <*> o + AE..:? "notifEmails" + AE..!= V.empty + <*> o + AE..:? "slackChannels" + AE..!= V.empty + <*> o + AE..:? "discordChannels" + AE..!= V.empty + <*> o + AE..:? "teamId" + + +manageTeamPostH :: Projects.ProjectId -> TeamForm -> Maybe Text -> ATAuthCtx (RespHeaders ManageTeams) +manageTeamPostH pid TeamForm{teamName, teamDescription, teamHandle, teamMembers, notifEmails, slackChannels, discordChannels, teamId} tmView = do + (sess, project) <- Sessions.sessionAndProject pid + appCtx <- ask @AuthContext + let currUserId = sess.persistentSession.userId + let res = validateTeamDetails teamName teamHandle + case (res, teamId) of + (Right _, Just tid) -> do + _ <- dbtToEff $ ProjectMembers.updateTeam pid tid teamName teamDescription teamHandle teamMembers notifEmails slackChannels discordChannels + addSuccessToast "Team updated successfully" Nothing + case tmView of + Just _ -> teamGetH pid teamHandle (Just "main-page") + _ -> manageTeamsGetH pid (Just "from_post") + (Right _, Nothing) -> do + teamVM <- dbtToEff $ ProjectMembers.getTeamByHandle pid teamHandle + case teamVM of + Just _ -> do + addErrorToast "Team handle already exists" Nothing + addRespHeaders $ ManageTeamsPostError "Team handle already exists for this project." + _ -> do + _ <- dbtToEff $ ProjectMembers.createTeam pid currUserId teamName teamDescription teamHandle teamMembers notifEmails slackChannels discordChannels + addSuccessToast "Team saved successfully" Nothing + manageTeamsGetH pid (Just "from_post") + (Left e, _) -> do + addErrorToast e Nothing + addReswap "" + addRespHeaders $ ManageTeamsPostError e + + +newtype TBulkActionForm = TBulkActionForm + { teamId :: [UUID.UUID] + } + deriving stock (Eq, Generic, Show) + deriving anyclass (FromForm) + + +manageTeamBulkActionH :: Projects.ProjectId -> Text -> TBulkActionForm -> Maybe Text -> ATAuthCtx (RespHeaders ManageTeams) +manageTeamBulkActionH pid action TBulkActionForm{teamId} listViewM = do + (sess, project) <- Sessions.sessionAndProject pid + appCtx <- ask @AuthContext + case action of + "delete" -> do + teamVm <- dbtToEff $ ProjectMembers.getTeamsById pid $ V.fromList teamId + let canDelete = all (\team -> sess.user.id == team.created_by) teamVm + if canDelete + then do + _ <- dbtToEff $ ProjectMembers.deleteTeams pid $ V.fromList teamId + when (isNothing listViewM) do + redirectCS ("/p/" <> pid.toText <> "/manage_teams") + addRespHeaders ManageTeamsDelete + else do + addErrorToast "You may only delete teams you own" Nothing + addRespHeaders $ ManageTeamsPostError "You may only delete teams you own" + _ -> do + addErrorToast "Invalid action" Nothing + addRespHeaders $ ManageTeamsPostError "Invalid action" + + +data ManageTeams + = ManageTeamsGet (PageCtx (Projects.ProjectId, V.Vector ProjectMembers.ProjectMemberVM, [BotUtils.Channel], [BotUtils.Channel], (V.Vector ProjectMembers.TeamVM))) + | ManageTeamsGet' (Projects.ProjectId, V.Vector ProjectMembers.ProjectMemberVM, [BotUtils.Channel], [BotUtils.Channel], (V.Vector ProjectMembers.TeamVM)) + | ManageTeamsPostError Text + | ManageTeamsDelete + | ManageTeamGet (PageCtx (Projects.ProjectId, ProjectMembers.TeamVM, V.Vector ProjectMembers.ProjectMemberVM, [BotUtils.Channel], [BotUtils.Channel])) + | ManageTeamGet' (Projects.ProjectId, ProjectMembers.TeamVM, V.Vector ProjectMembers.ProjectMemberVM, [BotUtils.Channel], [BotUtils.Channel]) + | ManageTeamGetError (PageCtx (Projects.ProjectId, Text)) + + +instance ToHtml ManageTeams where + toHtml (ManageTeamsGet (PageCtx bwconf (pid, members, slackChannels, discordChannels, teams))) = toHtml $ PageCtx bwconf $ manageTeamsPage pid members slackChannels discordChannels teams + toHtml (ManageTeamsGet' (pid, members, slackChannels, discordChannels, teams)) = toHtml $ manageTeamsPage pid members slackChannels discordChannels teams + toHtml (ManageTeamsPostError msg) = span_ [] $ "" + toHtml ManageTeamsDelete = toHtml "" + toHtml (ManageTeamGet (PageCtx bwconf (pid, team, members, slackChannels, discordChannels))) = toHtml $ PageCtx bwconf $ teamPage pid team members slackChannels discordChannels + toHtml (ManageTeamGet' (pid, team, members, slackChannels, discordChannels)) = toHtml $ teamPage pid team members slackChannels discordChannels + toHtml (ManageTeamGetError (PageCtx bwconf (pid, message))) = toHtml $ PageCtx bwconf $ teamPageNF pid message + toHtmlRaw = toHtml + + +manageTeamsGetH :: Projects.ProjectId -> Maybe Text -> ATAuthCtx (RespHeaders ManageTeams) +manageTeamsGetH pid layoutM = do + (sess, project) <- Sessions.sessionAndProject pid + appCtx <- ask @AuthContext + projMembers <- dbtToEff $ ProjectMembers.selectActiveProjectMembers pid + slackDataM <- Slack.getProjectSlackData pid + channels <- case slackDataM of + Just slackData -> do + channels' <- SlackP.getSlackChannels appCtx.env.slackBotToken slackData.teamId + case channels' of + Just chs -> return chs.channels + Nothing -> return [] + Nothing -> return [] + + discordDataM <- Slack.getDiscordDataByProjectId pid + discordChannels <- case discordDataM of + Just discordData -> Discord.getDiscordChannels appCtx.env.discordBotToken discordData.guildId + Nothing -> return [] + teams <- dbtToEff $ ProjectMembers.getTeamsVM pid + let bwconf = + (def :: BWConfig) + { sessM = Just sess + , pageTitle = "Manage teams" + , currProject = Just project + , isSettingsPage = True + , config = appCtx.config + } + case layoutM of + Just _ -> do + addRespHeaders $ ManageTeamsGet' (pid, projMembers, channels, discordChannels, teams) + _ -> do + addRespHeaders $ ManageTeamsGet (PageCtx bwconf (pid, projMembers, channels, discordChannels, teams)) + + +manageTeamsPage :: Projects.ProjectId -> V.Vector ProjectMembers.ProjectMemberVM -> [BotUtils.Channel] -> [BotUtils.Channel] -> V.Vector ProjectMembers.TeamVM -> Html () +manageTeamsPage pid projMembers channels discordChannels teams = do + let whiteList = decodeUtf8 $ AE.encode $ (\x -> AE.object ["name" AE..= (x.first_name <> " " <> x.last_name), "email" AE..= x.email, "value" AE..= x.userId]) <$> projMembers + let channelWhiteList = decodeUtf8 $ AE.encode $ (\x -> AE.object ["name" AE..= ("#" <> x.channelName), "value" AE..= x.channelId]) <$> channels + let discordWhiteList = decodeUtf8 $ AE.encode $ (\x -> AE.object ["name" AE..= ("#" <> x.channelName), "value" AE..= x.channelId]) <$> discordChannels + section_ [id_ "main-content", class_ "w-full py-8"] do + div_ [class_ "p-6 w-full"] do + div_ [class_ "mb-8 w-full flex items-center justify-between"] do + div_ [class_ "flex flex-col gap-2"] do + h2_ [class_ "text-textStrong text-3xl font-semibold"] "Teams" + p_ [class_ "text-textWeak text-sm"] "Manage your project teams and their access" + label_ [class_ "btn btn-primary btn-sm text-white", Lucid.for_ "n-new-team-modal"] (faSprite_ "plus" "regular" "h-4 w-4 mr-2" >> "New Team") + input_ [type_ "checkbox", id_ "n-new-team-modal", class_ "modal-toggle"] + teamModal pid Nothing whiteList channelWhiteList discordWhiteList False + -- let mapColumn x = + -- (Table.mkColumn x x) + -- { columnWidth = if x == "Name" then Just "60%" else if x == "Modified" then Just "20%" else Nothing + -- , columnCheckBox = x == "teamId" + -- , columnActionable = x == "Name" + -- } + -- let tableCols = (\x -> mapColumn x) <$> ["teamId", "Name", "Modified", "Members", "Notifications"] + -- let mapRow x = + -- Map.fromList + -- [ ("teamId", CellCheckbox $ UUID.toText x.id) + -- , ("Name", CellCustom $ nameCell pid x.name x.description x.handle) + -- , ("Modified", CellText $ toText $ formatTime defaultTimeLocale "%b %-e, %-l:%M %P" x.updated_at) + -- , ("Members", CellCustom $ memberCell x.members) + -- , ("Notifications", CellCustom $ notifsCell x) + -- ] + -- tableRows = (mapRow <$> V.toList teams) + -- table = + -- (Table.defaultTable tableCols tableRows) + -- { tableId = Just "teams_table" + -- , tableClass = "border rounded border-strokeWeak" + -- , tableHasSearch = True + -- , tableHasCheckboxes = True + -- , tableActions = + -- Just + -- $ [ button_ [class_ "flex items-center gap-2 btn btn-sm text-textError", type_ "button", hxPost_ $, hxSwap_ "none"] do + -- faSprite_ "trash" "regular" "w-3 h-3" + -- "Delete" + -- ] + -- } + let table = + Table + { config = def{elemID = "teamsListForm", renderAsTable = True} + , columns = [col "Name" (nameCell pid), col "Modified" modifiedCell, col "Members" memberCell, col "Notifications" notifsCell] + , rows = teams + , features = + def + { search = Just ClientSide + , rowId = Just (\team -> UUID.toText team.id) + , bulkActions = + [ Table.BulkAction + { title = "Delete" + , icon = Just "trash" + , uri = "/p/" <> pid.toText <> "/manage_teams/bulk_action/delete" + } + ] + , zeroState = + Just + $ ZeroState + { icon = "empty-set" + , title = "You haven't created any teams yet" + , description = "Create teams to manage access and collaboration" + , actionText = "Create team" + , destination = + Left $ "/p/" <> pid.toText <> "/manage_teams#new-team-modal" + } + } + } + + div_ [class_ "w-full"] do + toHtml table + + +modifiedCell :: ProjectMembers.TeamVM -> Html () +modifiedCell team = do + time_ [datetime_ $ fmt $ dateDashF team.updated_at, class_ "text text-sm"] $ toHtml $ formatTime defaultTimeLocale "%b %-d, %Y %-I:%M %p" team.updated_at + + +nameCell :: Projects.ProjectId -> ProjectMembers.TeamVM -> Html () +nameCell pid team = do + a_ [class_ "flex items-center gap-2", href_ ("/p/" <> pid.toText <> "/manage_teams/" <> team.handle)] do + span_ [class_ "text-textStrong text-sm font-medium"] $ toHtml team.name + span_ [class_ "text-textWeak text-sm overflow-ellipsis truncate "] $ toHtml team.description + + +memberCell :: ProjectMembers.TeamVM -> Html () +memberCell team = do + div_ [class_ "inline-block flex -space-x-2"] do + forM_ team.members $ \m -> do + div_ [class_ "inline-block mx-0.5", term "data-tippy-content" m.memberName] + $ img_ [class_ "inline-block h-6 w-6 rounded-full border border-strokeWeak ", src_ m.memberAvatar, alt_ "User avatar"] + + +notifsCell :: ProjectMembers.TeamVM -> Html () +notifsCell team = do + div_ [class_ "flex items-center gap-2"] do + unless (V.null team.slack_channels) do + div_ [term "data-tippy-content" "Slack"] do + faSprite_ "slack" "solid" "h-3.5 w-3.5" + unless (V.null team.discord_channels) do + div_ [term "data-tippy-content" "Discord"] do + faSprite_ "discord" "solid" "h-3.5 w-3.5" + unless (V.null team.notify_emails) do + div_ [term "data-tippy-content" "Email"] do + faSprite_ "envelope" "solid" "h-3.5 w-3.5" + + +teamGetH :: Projects.ProjectId -> Text -> Maybe Text -> ATAuthCtx (RespHeaders ManageTeams) +teamGetH pid handle layoutM = do + (sess, project) <- Sessions.sessionAndProject pid + appCtx <- ask @AuthContext + teamVm <- dbtToEff $ ProjectMembers.getTeamByHandle pid handle + projMembers <- dbtToEff $ ProjectMembers.selectActiveProjectMembers pid + slackDataM <- Slack.getProjectSlackData pid + channels <- case slackDataM of + Just slackData -> do + channels' <- SlackP.getSlackChannels appCtx.env.slackBotToken slackData.teamId + case channels' of + Just chs -> return chs.channels + Nothing -> return [] + Nothing -> return [] + + discordDataM <- Slack.getDiscordDataByProjectId pid + discordChannels <- case discordDataM of + Just discordData -> Discord.getDiscordChannels appCtx.env.discordBotToken discordData.guildId + Nothing -> return [] + let bwconf = + (def :: BWConfig) + { sessM = Just sess + , pageTitle = "Team details" + , currProject = Just project + , config = appCtx.config + } + case teamVm of + Just team -> case layoutM of + Just _ -> addRespHeaders $ ManageTeamGet' (pid, team, projMembers, channels, discordChannels) + _ -> addRespHeaders $ ManageTeamGet (PageCtx bwconf (pid, team, projMembers, channels, discordChannels)) + Nothing -> addRespHeaders $ ManageTeamGetError (PageCtx bwconf (pid, handle)) + + +teamPage :: Projects.ProjectId -> ProjectMembers.TeamVM -> V.Vector ProjectMembers.ProjectMemberVM -> [BotUtils.Channel] -> [BotUtils.Channel] -> Html () +teamPage pid team projMembers slackChannels discordChannels = do + let whiteList = decodeUtf8 $ AE.encode $ (\x -> AE.object ["name" AE..= (x.first_name <> " " <> x.last_name), "email" AE..= x.email, "value" AE..= x.userId]) <$> projMembers + let channelWhiteList = decodeUtf8 $ AE.encode $ (\x -> AE.object ["name" AE..= ("#" <> x.channelName), "value" AE..= x.channelId]) <$> slackChannels + let discordWhiteList = decodeUtf8 $ AE.encode $ (\x -> AE.object ["name" AE..= ("#" <> x.channelName), "value" AE..= x.channelId]) <$> discordChannels + section_ [id_ "main-content", class_ "w-full h-full"] do + div_ [class_ "flex h-full border-t border-strokeWeak"] do + div_ [class_ "p-4 w-4/12 space-y-6 mx-auto h-full overflow-y-auto"] do + div_ [] do + div_ [class_ "flex items-center gap-3"] do + h2_ [class_ "text-xl font-semibold"] $ toHtml team.name + span_ [class_ "text-textWeak flex items-center gap-1 text-sm"] do + faSprite_ "copy" "regular" "w-3 h-3" + toHtml team.handle + p_ [class_ "text-textWeak mt-3 text-sm"] $ toHtml team.description + div_ [class_ "rounded-lg p-4 border border-strokeWeak"] do + div_ [class_ "flex items-center justify-between mb-2"] do + span_ [class_ "flex items-center gap-2 font-semibold py-2"] do + faSprite_ "users" "regular" "h-5 w-5" + toHtml $ "Members" + span_ [class_ "text-textWeak"] $ ("(" <> show (V.length team.members) <> ")") + label_ [class_ "btn btn-outline border border-strokeWeak btn-xs", Lucid.for_ $ team.handle <> "-new-team-modal"] (faSprite_ "plus" "regular" "h-3 w-3 mr-1" >> "Add") + input_ [type_ "checkbox", id_ $ team.handle <> "-new-team-modal", class_ "modal-toggle"] + teamModal pid (Just team) whiteList channelWhiteList discordWhiteList True + div_ [] do + forM_ team.members \m -> do + div_ [class_ "flex flex-col gap-1 py-3 "] do + div_ [class_ "flex gap-2 text-sm"] do + img_ [src_ m.memberAvatar, class_ "w-5 h-5 rounded-full border border-strokeWeak"] + span_ [] $ toHtml m.memberName + span_ [class_ "text-textWeak text-xs"] $ toHtml m.memberEmail + + div_ [class_ "p-4 rounded-lg border border-strokeWeak"] do + div_ [class_ "flex items-center justify-between mb-2"] do + span_ [class_ "flex items-center gap-2 py-2 font-semibold"] do + faSprite_ "bell" "regular" "h-5 w-5" + "Notifications" + label_ [class_ "btn btn-outline border border-strokeWeak btn-xs", Lucid.for_ $ team.handle <> "-new-team-modal"] (faSprite_ "plus" "regular" "h-3 w-3 mr-1" >> "Add") + div_ [] do + div_ [class_ "flex flex-col gap-2 py-3"] do + div_ [class_ "flex items-center text-sm gap-2 font-medium"] do + faSprite_ "envelope" "regular" "h-4 w-4" + "Email addresses" + div_ [class_ "flex items-center gap-2 text-xs text-textWeak"] do + when (V.null team.notify_emails) $ span_ [] "No emails added" + forM_ team.notify_emails \e -> span_ [] $ toHtml e + div_ [class_ "flex flex-col gap-2 py-3"] do + div_ [class_ "flex items-center text-sm gap-2 font-medium"] do + faSprite_ "slack" "solid" "h-4 w-4" + "Slack channels" + div_ [class_ "flex items-center gap-2 text-xs text-textWeak"] do + when (V.null team.slack_channels) $ span_ [] "No slack channel configured" + forM_ team.slack_channels \e -> do + let tar = maybe e (.channelName) $ find (\x -> x.channelId == e) slackChannels + span_ [] $ toHtml tar + div_ [class_ "flex flex-col gap-2 py-3"] do + div_ [class_ "flex items-center text-sm gap-2 font-medium"] do + faSprite_ "discord" "solid" "h-4 w-4" + "Discord channels" + div_ [class_ "flex items-center gap-2 text-xs text-textWeak"] do + when (V.null team.discord_channels) $ span_ [] "No discord channel configured" + forM_ team.discord_channels \e -> do + let tar = maybe e (.channelName) $ find (\x -> x.channelId == e) discordChannels + span_ [] $ toHtml tar + + div_ [class_ "h-full w-8/12 overflow-y-auto p-4 space-y-6"] do + monitorsSection pid team.id + dashboardsSection pid team.id + servicesSection pid team.id + + +monitorsSection :: Projects.ProjectId -> UUID.UUID -> Html () +monitorsSection pid teamId = div_ [class_ "rounded-xl border border-strokeWeak overflow-x-hidden"] do + div_ + [ class_ "flex items-center justify-between w-full p-2 hover:bg-fillWeaker cursor-pointer" + , [__|on click toggle .hidden on the next
+ then toggle .rotate-270 on the first