|
| 1 | +package com.dbaagent.service; |
| 2 | + |
| 3 | +import com.dbaagent.model.DigestDeliveryMethod; |
| 4 | +import com.dbaagent.model.PersonaTag; |
| 5 | +import com.dbaagent.model.Role; |
| 6 | +import com.dbaagent.model.SlackDigestConfig; |
| 7 | +import com.dbaagent.model.User; |
| 8 | +import com.dbaagent.model.UserDigestPreference; |
| 9 | +import com.dbaagent.repository.SlackDigestConfigRepository; |
| 10 | +import com.dbaagent.repository.UserDigestPreferenceRepository; |
| 11 | +import com.dbaagent.repository.UserRepository; |
| 12 | +import com.dbaagent.service.security.ConnectionAccessService; |
| 13 | +import lombok.RequiredArgsConstructor; |
| 14 | +import lombok.extern.slf4j.Slf4j; |
| 15 | +import org.springframework.stereotype.Service; |
| 16 | +import org.springframework.transaction.annotation.Transactional; |
| 17 | + |
| 18 | +import java.util.ArrayList; |
| 19 | +import java.util.List; |
| 20 | +import java.util.Optional; |
| 21 | + |
| 22 | +/** |
| 23 | + * Service for seeding digest preferences from singleton config. |
| 24 | + * |
| 25 | + * <p>Provides migration helpers so existing deployments (like Stayflexi) don't stay |
| 26 | + * on legacy broadcast forever after the first per-user preferences appear. |
| 27 | + * |
| 28 | + * <h3>Seed Strategy</h3> |
| 29 | + * <ol> |
| 30 | + * <li>Find all users with linked Slack accounts (candidates for DM delivery)</li> |
| 31 | + * <li>For each user, create a SLACK_DM preference for each connection they can access</li> |
| 32 | + * <li>Persona tag is inferred from the user's role (can be edited later in UI)</li> |
| 33 | + * <li>Cron expression defaults to the global singleton config</li> |
| 34 | + * </ol> |
| 35 | + */ |
| 36 | +@Service |
| 37 | +@RequiredArgsConstructor |
| 38 | +@Slf4j |
| 39 | +public class DigestPreferenceSeedService { |
| 40 | + |
| 41 | + private final UserDigestPreferenceRepository preferenceRepository; |
| 42 | + private final SlackDigestConfigRepository configRepository; |
| 43 | + private final SlackUserLinkService slackUserLinkService; |
| 44 | + private final ConnectionAccessService connectionAccessService; |
| 45 | + private final UserRepository userRepository; |
| 46 | + |
| 47 | + /** |
| 48 | + * Seed digest preferences for all Slack-linked users. |
| 49 | + * |
| 50 | + * <p>This creates one SLACK_DM preference per connection the user can access. |
| 51 | + * Existing preferences are not overwritten. |
| 52 | + * |
| 53 | + * @param dryRun if true, return what would be created without persisting |
| 54 | + * @return summary of seeded preferences |
| 55 | + */ |
| 56 | + @Transactional |
| 57 | + public SeedResult seedPreferencesFromSingleton(boolean dryRun) { |
| 58 | + List<String> linkedUsernames = slackUserLinkService.getAllLinkedUsernames(); |
| 59 | + if (linkedUsernames.isEmpty()) { |
| 60 | + log.info("No Slack-linked users found; nothing to seed"); |
| 61 | + return new SeedResult(0, 0, List.of(), List.of()); |
| 62 | + } |
| 63 | + |
| 64 | + String globalCron = getGlobalCronExpression(); |
| 65 | + List<UserDigestPreference> created = new ArrayList<>(); |
| 66 | + List<String> skipped = new ArrayList<>(); |
| 67 | + |
| 68 | + for (String username : linkedUsernames) { |
| 69 | + Optional<User> userOpt = userRepository.findByUsernameIgnoreCase(username); |
| 70 | + if (userOpt.isEmpty()) { |
| 71 | + skipped.add(username + ": user not found"); |
| 72 | + continue; |
| 73 | + } |
| 74 | + |
| 75 | + User user = userOpt.get(); |
| 76 | + if (!user.isActive()) { |
| 77 | + skipped.add(username + ": user inactive"); |
| 78 | + continue; |
| 79 | + } |
| 80 | + |
| 81 | + List<String> connectionIds = connectionAccessService |
| 82 | + .getVisibleConnections(username, user.isAdmin()) |
| 83 | + .stream() |
| 84 | + .map(conn -> conn.getId()) |
| 85 | + .toList(); |
| 86 | + |
| 87 | + if (connectionIds.isEmpty()) { |
| 88 | + skipped.add(username + ": no accessible connections"); |
| 89 | + continue; |
| 90 | + } |
| 91 | + |
| 92 | + PersonaTag inferredPersona = inferPersonaFromRole(user.getRoleEnum()); |
| 93 | + |
| 94 | + for (String connectionId : connectionIds) { |
| 95 | + // Check if preference already exists |
| 96 | + Optional<UserDigestPreference> existing = preferenceRepository |
| 97 | + .findByUsernameAndConnectionIdAndDeliveryMethod( |
| 98 | + username, connectionId, DigestDeliveryMethod.SLACK_DM); |
| 99 | + |
| 100 | + if (existing.isPresent()) { |
| 101 | + skipped.add(username + "/" + connectionId + ": preference exists"); |
| 102 | + continue; |
| 103 | + } |
| 104 | + |
| 105 | + UserDigestPreference pref = UserDigestPreference.builder() |
| 106 | + .username(username) |
| 107 | + .connectionId(connectionId) |
| 108 | + .enabled(true) |
| 109 | + .deliveryMethod(DigestDeliveryMethod.SLACK_DM) |
| 110 | + .personaTag(inferredPersona) |
| 111 | + .cronExpression(null) // Use global default |
| 112 | + .timezone(null) // Use system default |
| 113 | + .build(); |
| 114 | + |
| 115 | + if (!dryRun) { |
| 116 | + preferenceRepository.save(pref); |
| 117 | + } |
| 118 | + created.add(pref); |
| 119 | + } |
| 120 | + } |
| 121 | + |
| 122 | + log.info("Digest preference seed: {} users, {} created, {} skipped (dryRun={})", |
| 123 | + linkedUsernames.size(), created.size(), skipped.size(), dryRun); |
| 124 | + |
| 125 | + return new SeedResult(linkedUsernames.size(), created.size(), skipped, created); |
| 126 | + } |
| 127 | + |
| 128 | + /** |
| 129 | + * Seed preferences for a single user. |
| 130 | + */ |
| 131 | + @Transactional |
| 132 | + public SeedResult seedPreferencesForUser(String username, boolean dryRun) { |
| 133 | + Optional<User> userOpt = userRepository.findByUsernameIgnoreCase(username); |
| 134 | + if (userOpt.isEmpty()) { |
| 135 | + return new SeedResult(0, 0, List.of(username + ": user not found"), List.of()); |
| 136 | + } |
| 137 | + |
| 138 | + User user = userOpt.get(); |
| 139 | + if (!user.isActive()) { |
| 140 | + return new SeedResult(0, 0, List.of(username + ": user inactive"), List.of()); |
| 141 | + } |
| 142 | + |
| 143 | + // Check if user has Slack linked |
| 144 | + List<com.dbaagent.model.SlackUserLink> links = slackUserLinkService.getLinkedSlackAccounts(username); |
| 145 | + if (links.isEmpty()) { |
| 146 | + return new SeedResult(0, 0, List.of(username + ": not linked to Slack"), List.of()); |
| 147 | + } |
| 148 | + |
| 149 | + List<String> connectionIds = connectionAccessService |
| 150 | + .getVisibleConnections(username, user.isAdmin()) |
| 151 | + .stream() |
| 152 | + .map(conn -> conn.getId()) |
| 153 | + .toList(); |
| 154 | + |
| 155 | + if (connectionIds.isEmpty()) { |
| 156 | + return new SeedResult(0, 0, List.of(username + ": no accessible connections"), List.of()); |
| 157 | + } |
| 158 | + |
| 159 | + PersonaTag inferredPersona = inferPersonaFromRole(user.getRoleEnum()); |
| 160 | + List<UserDigestPreference> created = new ArrayList<>(); |
| 161 | + List<String> skipped = new ArrayList<>(); |
| 162 | + |
| 163 | + for (String connectionId : connectionIds) { |
| 164 | + Optional<UserDigestPreference> existing = preferenceRepository |
| 165 | + .findByUsernameAndConnectionIdAndDeliveryMethod( |
| 166 | + username, connectionId, DigestDeliveryMethod.SLACK_DM); |
| 167 | + |
| 168 | + if (existing.isPresent()) { |
| 169 | + skipped.add(connectionId + ": preference exists"); |
| 170 | + continue; |
| 171 | + } |
| 172 | + |
| 173 | + UserDigestPreference pref = UserDigestPreference.builder() |
| 174 | + .username(username) |
| 175 | + .connectionId(connectionId) |
| 176 | + .enabled(true) |
| 177 | + .deliveryMethod(DigestDeliveryMethod.SLACK_DM) |
| 178 | + .personaTag(inferredPersona) |
| 179 | + .build(); |
| 180 | + |
| 181 | + if (!dryRun) { |
| 182 | + preferenceRepository.save(pref); |
| 183 | + } |
| 184 | + created.add(pref); |
| 185 | + } |
| 186 | + |
| 187 | + log.info("Seeded {} preferences for user {} (dryRun={})", created.size(), username, dryRun); |
| 188 | + |
| 189 | + return new SeedResult(1, created.size(), skipped, created); |
| 190 | + } |
| 191 | + |
| 192 | + /** |
| 193 | + * Infer a persona tag from the user's role. |
| 194 | + */ |
| 195 | + private PersonaTag inferPersonaFromRole(Role role) { |
| 196 | + if (role == null) { |
| 197 | + return null; // No persona; use role-based prioritization only |
| 198 | + } |
| 199 | + return switch (role) { |
| 200 | + case ADMIN -> null; // Admins often wear multiple hats; let them pick |
| 201 | + case DBA -> PersonaTag.DBA; |
| 202 | + case DATA_ENGINEER -> PersonaTag.DATA_ENG; |
| 203 | + case DEVELOPER -> PersonaTag.APP_ENG; |
| 204 | + }; |
| 205 | + } |
| 206 | + |
| 207 | + private String getGlobalCronExpression() { |
| 208 | + return configRepository.findById(1L) |
| 209 | + .map(SlackDigestConfig::getCronExpression) |
| 210 | + .orElse("0 0 9 * * *"); |
| 211 | + } |
| 212 | + |
| 213 | + /** |
| 214 | + * Get seed preview: what would be created without actually seeding. |
| 215 | + */ |
| 216 | + public SeedResult previewSeed() { |
| 217 | + return seedPreferencesFromSingleton(true); |
| 218 | + } |
| 219 | + |
| 220 | + /** |
| 221 | + * Execute seed: create preferences for all eligible users. |
| 222 | + */ |
| 223 | + public SeedResult executeSeed() { |
| 224 | + return seedPreferencesFromSingleton(false); |
| 225 | + } |
| 226 | + |
| 227 | + public record SeedResult( |
| 228 | + int usersProcessed, |
| 229 | + int preferencesCreated, |
| 230 | + List<String> skipped, |
| 231 | + List<UserDigestPreference> preferences |
| 232 | + ) { |
| 233 | + public boolean hasCreations() { |
| 234 | + return preferencesCreated > 0; |
| 235 | + } |
| 236 | + } |
| 237 | +} |
0 commit comments