books/backend/Books.Api.Tests/Helpers/CvrGenerator.cs

52 lines
1.4 KiB
C#
Raw Normal View History

namespace Books.Api.Tests.Helpers;
/// <summary>
/// Generates valid Danish CVR numbers for testing.
/// </summary>
public static class CvrGenerator
{
private static readonly int[] Weights = [2, 7, 6, 5, 4, 3, 2, 1];
private static readonly Random Random = new();
/// <summary>
/// Generates a random valid CVR number with correct modulus 11 checksum.
/// </summary>
public static string Generate()
{
// Generate 7 random digits
var digits = new int[8];
for (var i = 0; i < 7; i++)
{
digits[i] = Random.Next(0, 10);
}
// Ensure first digit is not 0 (CVR numbers don't start with 0)
if (digits[0] == 0) digits[0] = Random.Next(1, 10);
// Calculate checksum digit using modulus 11
// Sum of (digit * weight) for first 7 digits
var sum = 0;
for (var i = 0; i < 7; i++)
{
sum += digits[i] * Weights[i];
}
// Find the last digit that makes sum % 11 == 0
// We need: (sum + digit * 1) % 11 == 0
// So: digit = (11 - (sum % 11)) % 11
var remainder = sum % 11;
var checkDigit = (11 - remainder) % 11;
// If checkDigit is 10, we can't use it (single digit only)
// So regenerate
if (checkDigit == 10)
{
return Generate();
}
digits[7] = checkDigit;
return string.Join("", digits);
}
}