namespace New.Domain.ValueObjects; /// /// A Dutch "burgerservicenummer" - always exactly 9 digits, validated with the /// eleven-proof (elfproef) checksum. /// /// This value object deliberately does NOT trim or otherwise massage its /// input. The legacy source stores BSNs as a space-padded CHAR(9), and it is /// the legacy mapper's job (New.Infrastructure.Legacy.LegacyAanvraagMapper) /// to trim before handing the raw value to this constructor - if it forgets, /// this constructor throws, which is the point: silently accepting padded /// input here would hide that mapping bug instead of surfacing it. /// public sealed record Bsn { public string Value { get; } public Bsn(string value) { if (string.IsNullOrEmpty(value) || value.Length != 9 || !value.All(char.IsDigit)) { throw new DomainInvariantViolationException( "Bsn.Format", $"A BSN must be exactly 9 digits. Got '{value}'."); } if (!PassesElevenProof(value)) { throw new DomainInvariantViolationException( "Bsn.ElevenProof", $"'{value}' does not pass the eleven-proof (elfproef) checksum."); } // All-zero digits trivially satisfy the eleven-proof formula (every // weighted term is zero) but "000000000" has never been an issued // BSN - real BSN validation excludes it explicitly, not just via the // checksum. if (value == "000000000") { throw new DomainInvariantViolationException( "Bsn.ElevenProof", "'000000000' is not a valid BSN."); } Value = value; } /// /// (9*d1 + 8*d2 + 7*d3 + 6*d4 + 5*d5 + 4*d6 + 3*d7 + 2*d8 - 1*d9) % 11 == 0 /// private static bool PassesElevenProof(string digits) { var sum = 0; for (var i = 0; i < 8; i++) { var weight = 9 - i; sum += weight * (digits[i] - '0'); } sum -= digits[8] - '0'; return sum % 11 == 0; } public override string ToString() => Value; }