| | | 1 | | using EHonda.KicktippAi.Core; |
| | | 2 | | using FirebaseAdapter.Models; |
| | | 3 | | using Google.Cloud.Firestore; |
| | | 4 | | using Microsoft.Extensions.Logging; |
| | | 5 | | |
| | | 6 | | namespace FirebaseAdapter; |
| | | 7 | | |
| | | 8 | | /// <summary> |
| | | 9 | | /// Firebase Firestore implementation of the KPI repository. |
| | | 10 | | /// </summary> |
| | | 11 | | public class FirebaseKpiRepository : IKpiRepository |
| | | 12 | | { |
| | | 13 | | private readonly FirestoreDb _firestoreDb; |
| | | 14 | | private readonly ILogger<FirebaseKpiRepository> _logger; |
| | | 15 | | private readonly string _competition; |
| | | 16 | | |
| | | 17 | | private const string KpiCollectionName = "kpi-documents"; |
| | | 18 | | |
| | 1 | 19 | | public FirebaseKpiRepository(FirestoreDb firestoreDb, ILogger<FirebaseKpiRepository> logger, string? competition = n |
| | | 20 | | { |
| | 1 | 21 | | _firestoreDb = firestoreDb; |
| | 1 | 22 | | _logger = logger; |
| | 1 | 23 | | _competition = string.IsNullOrWhiteSpace(competition) |
| | 1 | 24 | | ? CompetitionIds.Bundesliga2025_26 |
| | 1 | 25 | | : competition.Trim(); |
| | 1 | 26 | | } |
| | | 27 | | |
| | | 28 | | /// <summary> |
| | | 29 | | /// Saves a KPI document with versioning support. |
| | | 30 | | /// Creates a new version if content differs from the latest version. |
| | | 31 | | /// </summary> |
| | | 32 | | /// <param name="documentName">The document name.</param> |
| | | 33 | | /// <param name="content">The document content.</param> |
| | | 34 | | /// <param name="description">The document description.</param> |
| | | 35 | | /// <param name="communityContext">The community context for filtering.</param> |
| | | 36 | | /// <param name="cancellationToken">Cancellation token.</param> |
| | | 37 | | /// <returns>The version number of the saved document.</returns> |
| | | 38 | | public async Task<int> SaveKpiDocumentAsync( |
| | | 39 | | string documentName, |
| | | 40 | | string content, |
| | | 41 | | string description, |
| | | 42 | | string communityContext, |
| | | 43 | | CancellationToken cancellationToken = default) |
| | | 44 | | { |
| | | 45 | | try |
| | | 46 | | { |
| | 1 | 47 | | var now = Timestamp.GetCurrentTimestamp(); |
| | | 48 | | |
| | | 49 | | // Get the latest version to check if content has changed |
| | 1 | 50 | | var latestVersion = await GetLatestVersionAsync(documentName, communityContext, cancellationToken); |
| | 1 | 51 | | var version = 0; |
| | | 52 | | |
| | 1 | 53 | | if (latestVersion >= 0) |
| | | 54 | | { |
| | | 55 | | // Check if content has changed |
| | 1 | 56 | | var latestDocument = await GetKpiDocumentAsync(documentName, communityContext, latestVersion, cancellati |
| | 1 | 57 | | if (latestDocument != null && latestDocument.Content == content) |
| | | 58 | | { |
| | 1 | 59 | | _logger.LogInformation("Content unchanged for KPI document: {DocumentName} version {Version}", docum |
| | 1 | 60 | | return latestVersion; // Return existing version if content is the same |
| | | 61 | | } |
| | | 62 | | |
| | 1 | 63 | | version = latestVersion + 1; |
| | 1 | 64 | | _logger.LogDebug("Creating new version {Version} for KPI document: {DocumentName}", version, documentNam |
| | | 65 | | } |
| | | 66 | | else |
| | | 67 | | { |
| | 1 | 68 | | _logger.LogDebug("Creating first version (0) for new KPI document: {DocumentName}", documentName); |
| | | 69 | | } |
| | | 70 | | |
| | 1 | 71 | | var versionedDocumentId = BuildDocumentId(documentName, communityContext, version); |
| | 1 | 72 | | var docRef = _firestoreDb.Collection(KpiCollectionName).Document(versionedDocumentId); |
| | | 73 | | |
| | 1 | 74 | | var firestoreKpiDocument = new FirestoreKpiDocument |
| | 1 | 75 | | { |
| | 1 | 76 | | Id = versionedDocumentId, |
| | 1 | 77 | | DocumentName = documentName, |
| | 1 | 78 | | Content = content, |
| | 1 | 79 | | Description = description, |
| | 1 | 80 | | Version = version, |
| | 1 | 81 | | CreatedAt = now, |
| | 1 | 82 | | Competition = _competition, |
| | 1 | 83 | | CommunityContext = communityContext |
| | 1 | 84 | | }; |
| | | 85 | | |
| | 1 | 86 | | await docRef.SetAsync(firestoreKpiDocument, cancellationToken: cancellationToken); |
| | | 87 | | |
| | 1 | 88 | | _logger.LogInformation("Created KPI document: {DocumentName} version {Version} for community: {CommunityCont |
| | 1 | 89 | | documentName, version, communityContext); |
| | | 90 | | |
| | 1 | 91 | | return version; |
| | | 92 | | } |
| | 0 | 93 | | catch (Exception ex) |
| | | 94 | | { |
| | 0 | 95 | | _logger.LogError(ex, "Failed to save KPI document: {DocumentName}", documentName); |
| | 0 | 96 | | throw; |
| | | 97 | | } |
| | 1 | 98 | | } |
| | | 99 | | |
| | | 100 | | /// <summary> |
| | | 101 | | /// Retrieves the latest version of a KPI document. |
| | | 102 | | /// </summary> |
| | | 103 | | /// <param name="documentName">The document name.</param> |
| | | 104 | | /// <param name="communityContext">The community context to filter by.</param> |
| | | 105 | | /// <param name="cancellationToken">Cancellation token.</param> |
| | | 106 | | /// <returns>The latest KPI document if found, otherwise null.</returns> |
| | | 107 | | public async Task<KpiDocument?> GetKpiDocumentAsync(string documentName, string communityContext, CancellationToken |
| | | 108 | | { |
| | | 109 | | try |
| | | 110 | | { |
| | 1 | 111 | | var latestVersion = await GetLatestVersionAsync(documentName, communityContext, cancellationToken); |
| | 1 | 112 | | if (latestVersion < 0) |
| | | 113 | | { |
| | 1 | 114 | | return null; |
| | | 115 | | } |
| | | 116 | | |
| | 1 | 117 | | return await GetKpiDocumentAsync(documentName, communityContext, latestVersion, cancellationToken); |
| | | 118 | | } |
| | 0 | 119 | | catch (Exception ex) |
| | | 120 | | { |
| | 0 | 121 | | _logger.LogError(ex, "Failed to get latest KPI document: {DocumentName} for community: {CommunityContext}", |
| | 0 | 122 | | documentName, communityContext); |
| | 0 | 123 | | throw; |
| | | 124 | | } |
| | 1 | 125 | | } |
| | | 126 | | |
| | | 127 | | /// <summary> |
| | | 128 | | /// Retrieves a specific version of a KPI document. |
| | | 129 | | /// </summary> |
| | | 130 | | /// <param name="documentName">The document name.</param> |
| | | 131 | | /// <param name="communityContext">The community context to filter by.</param> |
| | | 132 | | /// <param name="version">The specific version to retrieve.</param> |
| | | 133 | | /// <param name="cancellationToken">Cancellation token.</param> |
| | | 134 | | /// <returns>The KPI document version if found, otherwise null.</returns> |
| | | 135 | | public async Task<KpiDocument?> GetKpiDocumentAsync(string documentName, string communityContext, int version, Cance |
| | | 136 | | { |
| | | 137 | | try |
| | | 138 | | { |
| | 1 | 139 | | var versionedDocumentId = BuildDocumentId(documentName, communityContext, version); |
| | 1 | 140 | | var docRef = _firestoreDb.Collection(KpiCollectionName).Document(versionedDocumentId); |
| | 1 | 141 | | var snapshot = await docRef.GetSnapshotAsync(cancellationToken); |
| | | 142 | | |
| | 1 | 143 | | if (!snapshot.Exists) |
| | | 144 | | { |
| | 1 | 145 | | return null; |
| | | 146 | | } |
| | | 147 | | |
| | 1 | 148 | | var firestoreDoc = snapshot.ConvertTo<FirestoreKpiDocument>(); |
| | 1 | 149 | | return new KpiDocument( |
| | 1 | 150 | | firestoreDoc.DocumentName, |
| | 1 | 151 | | firestoreDoc.Content, |
| | 1 | 152 | | firestoreDoc.Description, |
| | 1 | 153 | | firestoreDoc.Version, |
| | 1 | 154 | | firestoreDoc.CreatedAt.ToDateTimeOffset()); |
| | | 155 | | } |
| | 0 | 156 | | catch (Exception ex) |
| | | 157 | | { |
| | 0 | 158 | | _logger.LogError(ex, "Failed to get KPI document: {DocumentName} version {Version} for community: {Community |
| | 0 | 159 | | documentName, version, communityContext); |
| | 0 | 160 | | throw; |
| | | 161 | | } |
| | 1 | 162 | | } |
| | | 163 | | |
| | | 164 | | /// <summary> |
| | | 165 | | /// Retrieves all versions of a KPI document. |
| | | 166 | | /// </summary> |
| | | 167 | | /// <param name="documentName">The document name.</param> |
| | | 168 | | /// <param name="communityContext">The community context to filter by.</param> |
| | | 169 | | /// <param name="cancellationToken">Cancellation token.</param> |
| | | 170 | | /// <returns>A collection of all versions of the KPI document.</returns> |
| | | 171 | | public async Task<IReadOnlyList<KpiDocument>> GetKpiDocumentVersionsAsync(string documentName, string communityConte |
| | | 172 | | { |
| | | 173 | | try |
| | | 174 | | { |
| | 1 | 175 | | var query = _firestoreDb.Collection(KpiCollectionName) |
| | 1 | 176 | | .WhereEqualTo("documentName", documentName) |
| | 1 | 177 | | .WhereEqualTo("communityContext", communityContext) |
| | 1 | 178 | | .WhereEqualTo("competition", _competition) |
| | 1 | 179 | | .OrderBy("version"); |
| | | 180 | | |
| | 1 | 181 | | var snapshot = await query.GetSnapshotAsync(cancellationToken); |
| | | 182 | | |
| | 1 | 183 | | var versions = new List<KpiDocument>(); |
| | 1 | 184 | | foreach (var document in snapshot.Documents) |
| | | 185 | | { |
| | 1 | 186 | | var firestoreDoc = document.ConvertTo<FirestoreKpiDocument>(); |
| | 1 | 187 | | versions.Add(new KpiDocument( |
| | 1 | 188 | | firestoreDoc.DocumentName, |
| | 1 | 189 | | firestoreDoc.Content, |
| | 1 | 190 | | firestoreDoc.Description, |
| | 1 | 191 | | firestoreDoc.Version, |
| | 1 | 192 | | firestoreDoc.CreatedAt.ToDateTimeOffset())); |
| | | 193 | | } |
| | | 194 | | |
| | 1 | 195 | | _logger.LogInformation("Retrieved {Count} versions for KPI document: {DocumentName} in community: {Community |
| | 1 | 196 | | versions.Count, documentName, communityContext); |
| | | 197 | | |
| | 1 | 198 | | return versions.AsReadOnly(); |
| | | 199 | | } |
| | 0 | 200 | | catch (Exception ex) |
| | | 201 | | { |
| | 0 | 202 | | _logger.LogError(ex, "Failed to get versions for KPI document: {DocumentName} in community: {CommunityContex |
| | 0 | 203 | | documentName, communityContext); |
| | 0 | 204 | | throw; |
| | | 205 | | } |
| | 1 | 206 | | } |
| | | 207 | | |
| | | 208 | | /// <summary> |
| | | 209 | | /// Retrieves all KPI documents for a specific community context (latest versions only). |
| | | 210 | | /// </summary> |
| | | 211 | | /// <param name="communityContext">The community context to filter by.</param> |
| | | 212 | | /// <param name="cancellationToken">Cancellation token.</param> |
| | | 213 | | /// <returns>A collection of KPI documents for the specified community.</returns> |
| | | 214 | | public async Task<IReadOnlyList<KpiDocument>> GetAllKpiDocumentsAsync(string communityContext, CancellationToken can |
| | | 215 | | { |
| | | 216 | | try |
| | | 217 | | { |
| | 1 | 218 | | var query = _firestoreDb.Collection(KpiCollectionName) |
| | 1 | 219 | | .WhereEqualTo("competition", _competition) |
| | 1 | 220 | | .WhereEqualTo("communityContext", communityContext); |
| | | 221 | | |
| | 1 | 222 | | var snapshot = await query.GetSnapshotAsync(cancellationToken); |
| | | 223 | | |
| | | 224 | | // Group by documentName and get the latest version for each |
| | 1 | 225 | | var documentGroups = snapshot.Documents |
| | 1 | 226 | | .Select(doc => doc.ConvertTo<FirestoreKpiDocument>()) |
| | 1 | 227 | | .GroupBy(doc => doc.DocumentName) |
| | 1 | 228 | | .ToList(); |
| | | 229 | | |
| | 1 | 230 | | var latestDocuments = new List<KpiDocument>(); |
| | 1 | 231 | | foreach (var group in documentGroups) |
| | | 232 | | { |
| | 1 | 233 | | var latestDoc = group.OrderByDescending(d => d.Version).First(); |
| | 1 | 234 | | latestDocuments.Add(new KpiDocument( |
| | 1 | 235 | | latestDoc.DocumentName, |
| | 1 | 236 | | latestDoc.Content, |
| | 1 | 237 | | latestDoc.Description, |
| | 1 | 238 | | latestDoc.Version, |
| | 1 | 239 | | latestDoc.CreatedAt.ToDateTimeOffset())); |
| | | 240 | | } |
| | | 241 | | |
| | 1 | 242 | | _logger.LogInformation("Retrieved {Count} latest KPI documents for community: {CommunityContext}", |
| | 1 | 243 | | latestDocuments.Count, communityContext); |
| | | 244 | | |
| | 1 | 245 | | return latestDocuments.AsReadOnly(); |
| | | 246 | | } |
| | 0 | 247 | | catch (Exception ex) |
| | | 248 | | { |
| | 0 | 249 | | _logger.LogError(ex, "Failed to get all KPI documents for community: {CommunityContext}", communityContext); |
| | 0 | 250 | | throw; |
| | | 251 | | } |
| | 1 | 252 | | } |
| | | 253 | | |
| | | 254 | | /// <summary> |
| | | 255 | | /// Gets the latest version number for a specific KPI document. |
| | | 256 | | /// </summary> |
| | | 257 | | /// <param name="documentName">The document name.</param> |
| | | 258 | | /// <param name="communityContext">The community context to filter by.</param> |
| | | 259 | | /// <param name="cancellationToken">Cancellation token.</param> |
| | | 260 | | /// <returns>The latest version number, or -1 if the document doesn't exist.</returns> |
| | | 261 | | public async Task<int> GetLatestVersionAsync(string documentName, string communityContext, CancellationToken cancell |
| | | 262 | | { |
| | | 263 | | try |
| | | 264 | | { |
| | 1 | 265 | | var query = _firestoreDb.Collection(KpiCollectionName) |
| | 1 | 266 | | .WhereEqualTo("documentName", documentName) |
| | 1 | 267 | | .WhereEqualTo("communityContext", communityContext) |
| | 1 | 268 | | .WhereEqualTo("competition", _competition) |
| | 1 | 269 | | .OrderByDescending("version") |
| | 1 | 270 | | .Limit(1); |
| | | 271 | | |
| | 1 | 272 | | var snapshot = await query.GetSnapshotAsync(cancellationToken); |
| | | 273 | | |
| | 1 | 274 | | if (snapshot.Documents.Count == 0) |
| | | 275 | | { |
| | 1 | 276 | | return -1; // Document doesn't exist |
| | | 277 | | } |
| | | 278 | | |
| | 1 | 279 | | var latestDoc = snapshot.Documents.First().ConvertTo<FirestoreKpiDocument>(); |
| | 1 | 280 | | return latestDoc.Version; |
| | | 281 | | } |
| | 0 | 282 | | catch (Exception ex) |
| | | 283 | | { |
| | 0 | 284 | | _logger.LogError(ex, "Failed to get latest version for KPI document: {DocumentName} in community: {Community |
| | 0 | 285 | | documentName, communityContext); |
| | 0 | 286 | | throw; |
| | | 287 | | } |
| | 1 | 288 | | } |
| | | 289 | | |
| | | 290 | | private string BuildDocumentId(string documentName, string communityContext, int version) |
| | | 291 | | { |
| | 1 | 292 | | return string.Equals(_competition, CompetitionIds.Bundesliga2025_26, StringComparison.OrdinalIgnoreCase) |
| | 1 | 293 | | ? $"{documentName}_{communityContext}_{version}" |
| | 1 | 294 | | : $"{_competition}_{documentName}_{communityContext}_{version}"; |
| | | 295 | | } |
| | | 296 | | } |