|
| 1 | +using System.Globalization; |
| 2 | +using System.Text; |
| 3 | +using Taskdeck.Application.DTOs; |
| 4 | +using Taskdeck.Domain.Common; |
| 5 | + |
| 6 | +namespace Taskdeck.Application.Services; |
| 7 | + |
| 8 | +/// <summary> |
| 9 | +/// Produces CSV exports of board metrics with schema-versioned columns |
| 10 | +/// and CSV-injection-safe cell values. |
| 11 | +/// </summary> |
| 12 | +public class MetricsExportService : IMetricsExportService |
| 13 | +{ |
| 14 | + /// <summary> |
| 15 | + /// Schema version embedded as the first comment line in every export. |
| 16 | + /// Bump when column layout changes. |
| 17 | + /// </summary> |
| 18 | + internal const string SchemaVersion = "1.0"; |
| 19 | + |
| 20 | + private readonly IBoardMetricsService _metricsService; |
| 21 | + |
| 22 | + public MetricsExportService(IBoardMetricsService metricsService) |
| 23 | + { |
| 24 | + _metricsService = metricsService; |
| 25 | + } |
| 26 | + |
| 27 | + public async Task<Result<MetricsExportResult>> ExportCsvAsync( |
| 28 | + BoardMetricsQuery query, |
| 29 | + Guid actingUserId, |
| 30 | + CancellationToken cancellationToken = default) |
| 31 | + { |
| 32 | + var metricsResult = await _metricsService.GetBoardMetricsAsync(query, actingUserId, cancellationToken); |
| 33 | + if (!metricsResult.IsSuccess) |
| 34 | + return Result.Failure<MetricsExportResult>(metricsResult.ErrorCode, metricsResult.ErrorMessage); |
| 35 | + |
| 36 | + var metrics = metricsResult.Value; |
| 37 | + var csv = BuildCsv(metrics); |
| 38 | + |
| 39 | + var timestamp = DateTimeOffset.UtcNow.ToString("yyyyMMdd-HHmmss", CultureInfo.InvariantCulture); |
| 40 | + var fileName = $"board-metrics-{metrics.BoardId:N}-{timestamp}.csv"; |
| 41 | + |
| 42 | + var bom = Encoding.UTF8.GetPreamble(); |
| 43 | + var csvBytes = Encoding.UTF8.GetBytes(csv); |
| 44 | + var content = new byte[bom.Length + csvBytes.Length]; |
| 45 | + bom.CopyTo(content, 0); |
| 46 | + csvBytes.CopyTo(content, bom.Length); |
| 47 | + |
| 48 | + return Result.Success(new MetricsExportResult(content, fileName, "text/csv")); |
| 49 | + } |
| 50 | + |
| 51 | + internal static string BuildCsv(BoardMetricsResponse metrics) |
| 52 | + { |
| 53 | + var sb = new StringBuilder(); |
| 54 | + |
| 55 | + // Schema version header (comment line) |
| 56 | + sb.AppendLine($"# schema_version={SchemaVersion}"); |
| 57 | + sb.AppendLine($"# board_id={metrics.BoardId}"); |
| 58 | + sb.AppendLine($"# from={metrics.From:o}"); |
| 59 | + sb.AppendLine($"# to={metrics.To:o}"); |
| 60 | + sb.AppendLine($"# exported_at={DateTimeOffset.UtcNow:o}"); |
| 61 | + sb.AppendLine(); |
| 62 | + |
| 63 | + // Section: Summary |
| 64 | + sb.AppendLine("[Summary]"); |
| 65 | + sb.AppendLine("Metric,Value"); |
| 66 | + sb.AppendLine($"AverageCycleTimeDays,{metrics.AverageCycleTimeDays.ToString(CultureInfo.InvariantCulture)}"); |
| 67 | + sb.AppendLine($"TotalWip,{metrics.TotalWip}"); |
| 68 | + sb.AppendLine($"BlockedCount,{metrics.BlockedCount}"); |
| 69 | + sb.AppendLine($"TotalThroughput,{metrics.Throughput.Sum(t => t.CompletedCount)}"); |
| 70 | + sb.AppendLine(); |
| 71 | + |
| 72 | + // Section: Throughput |
| 73 | + sb.AppendLine("[Throughput]"); |
| 74 | + sb.AppendLine("Date,CompletedCount"); |
| 75 | + foreach (var dp in metrics.Throughput) |
| 76 | + { |
| 77 | + sb.AppendLine($"{dp.Date:yyyy-MM-dd},{dp.CompletedCount}"); |
| 78 | + } |
| 79 | + sb.AppendLine(); |
| 80 | + |
| 81 | + // Section: CycleTime |
| 82 | + sb.AppendLine("[CycleTime]"); |
| 83 | + sb.AppendLine("CardId,CardTitle,CycleTimeDays"); |
| 84 | + foreach (var entry in metrics.CycleTimeEntries) |
| 85 | + { |
| 86 | + sb.AppendLine($"{entry.CardId},{SanitizeCsvField(entry.CardTitle)},{entry.CycleTimeDays.ToString(CultureInfo.InvariantCulture)}"); |
| 87 | + } |
| 88 | + sb.AppendLine(); |
| 89 | + |
| 90 | + // Section: WIP |
| 91 | + sb.AppendLine("[WIP]"); |
| 92 | + sb.AppendLine("ColumnId,ColumnName,CardCount,WipLimit"); |
| 93 | + foreach (var wip in metrics.WipSnapshots) |
| 94 | + { |
| 95 | + sb.AppendLine($"{wip.ColumnId},{SanitizeCsvField(wip.ColumnName)},{wip.CardCount},{wip.WipLimit?.ToString(CultureInfo.InvariantCulture) ?? ""}"); |
| 96 | + } |
| 97 | + sb.AppendLine(); |
| 98 | + |
| 99 | + // Section: Blocked |
| 100 | + sb.AppendLine("[Blocked]"); |
| 101 | + sb.AppendLine("CardId,CardTitle,BlockReason,BlockedDurationDays"); |
| 102 | + foreach (var blocked in metrics.BlockedCards) |
| 103 | + { |
| 104 | + sb.AppendLine($"{blocked.CardId},{SanitizeCsvField(blocked.CardTitle)},{SanitizeCsvField(blocked.BlockReason ?? "")},{blocked.BlockedDurationDays.ToString(CultureInfo.InvariantCulture)}"); |
| 105 | + } |
| 106 | + |
| 107 | + return sb.ToString(); |
| 108 | + } |
| 109 | + |
| 110 | + /// <summary> |
| 111 | + /// Sanitize a field for safe CSV inclusion. |
| 112 | + /// - Strips CSV injection characters (=, +, -, @, tab, carriage return) from the start |
| 113 | + /// of the value AND from the start of each embedded line (after \n or \r\n). |
| 114 | + /// - Quotes the field if it contains commas, quotes, or newlines. |
| 115 | + /// - Doubles internal quote characters. |
| 116 | + /// </summary> |
| 117 | + internal static string SanitizeCsvField(string value) |
| 118 | + { |
| 119 | + if (string.IsNullOrEmpty(value)) |
| 120 | + return value; |
| 121 | + |
| 122 | + // Strip leading characters that could trigger formula injection in spreadsheet apps. |
| 123 | + // Apply to each line within the value to prevent injection via embedded newlines |
| 124 | + // (e.g. "hello\n=CMD|'/C calc'!A0" must sanitize the second line too). |
| 125 | + var sanitized = StripDangerousLeadingChars(value); |
| 126 | + sanitized = SanitizeEmbeddedLines(sanitized); |
| 127 | + |
| 128 | + // If the field contains special CSV characters, quote it |
| 129 | + var needsQuoting = sanitized.Contains(',') || |
| 130 | + sanitized.Contains('"') || |
| 131 | + sanitized.Contains('\n') || |
| 132 | + sanitized.Contains('\r'); |
| 133 | + |
| 134 | + if (needsQuoting) |
| 135 | + { |
| 136 | + sanitized = "\"" + sanitized.Replace("\"", "\"\"") + "\""; |
| 137 | + } |
| 138 | + |
| 139 | + return sanitized; |
| 140 | + } |
| 141 | + |
| 142 | + private static string StripDangerousLeadingChars(string s) |
| 143 | + { |
| 144 | + var i = 0; |
| 145 | + while (i < s.Length && IsDangerousLeadingChar(s[i])) |
| 146 | + i++; |
| 147 | + return i == 0 ? s : s[i..]; |
| 148 | + } |
| 149 | + |
| 150 | + /// <summary> |
| 151 | + /// For each line after the first within a multi-line value, strip leading |
| 152 | + /// dangerous characters so that embedded newlines cannot smuggle formula prefixes. |
| 153 | + /// </summary> |
| 154 | + private static string SanitizeEmbeddedLines(string value) |
| 155 | + { |
| 156 | + if (!value.Contains('\n') && !value.Contains('\r')) |
| 157 | + return value; |
| 158 | + |
| 159 | + var lines = value.Split('\n'); |
| 160 | + for (var i = 1; i < lines.Length; i++) |
| 161 | + { |
| 162 | + var line = lines[i]; |
| 163 | + // Handle \r\n: the \r will be at the end of the previous line's split, |
| 164 | + // but also strip dangerous chars that appear after a bare \n. |
| 165 | + lines[i] = StripDangerousLeadingChars(line); |
| 166 | + } |
| 167 | + |
| 168 | + return string.Join('\n', lines); |
| 169 | + } |
| 170 | + |
| 171 | + private static bool IsDangerousLeadingChar(char c) |
| 172 | + => c is '=' or '+' or '-' or '@' or '\t' or '\r'; |
| 173 | +} |
0 commit comments