using Developpez.Dotnet.Properties;
using System;
namespace Developpez.Dotnet.Algorithms
{
///
/// Outil de vérification des NIR (Numéro d'Inscription au Répertoire des personnes physiques)
/// usuellement dénommé "numéro de sécurité sociale" en France.
/// http://fr.wikipedia.org/wiki/Num%C3%A9ro_de_s%C3%A9curit%C3%A9_sociale_en_France
///
///
/// Contribution de DelphiManiac
/// http://www.developpez.net/forums/u216/delphimaniac/
///
public static class NIR
{
///
/// Taille exacte du NIR.
///
private const int _NIRExactLength = 13;
///
/// Taille exacte d'une clé de NIR.
///
private const int _NIRKeyExactLength = 2;
///
/// Calcule la clé d'un NIR.
///
/// NIR dont on désire calculer la clé.
/// La clé calculée.
/// Le NIR est invalide.
/// Le NIR est null.
public static string CalcKey(string nir)
{
if (string.IsNullOrEmpty(nir))
throw new ArgumentNullException(ExceptionMessages.StringNullOrEmpty);
if (nir.Length != _NIRExactLength)
throw new ArgumentException(string.Format(ExceptionMessages.StringWrongLength, _NIRExactLength));
string dep = nir.Substring(5, 2);
string newDep = "";
if (dep == "2A")
{
newDep = "19";
}
else if (dep == "2B")
{
newDep = "18";
}
if (newDep != "")
{
nir = nir.Left(5) + newDep + nir.Right(6);
}
decimal nirAsDecimal;
if (!decimal.TryParse(nir, out nirAsDecimal))
{
throw new ArgumentException(ExceptionMessages.InvalidNir);
}
return (97 - (nirAsDecimal % 97)).ToString("00");
}
///
/// Vérifie la validité d'un couple NIR / Clé.
///
/// NIR à contrôler (13 chiffres, sauf numéro de département qui peut être 2A ou 2B).
/// Clé à contrôler (2 chiffres).
/// Vrai si la clé est valide pour ce NIR, faux sinon.
/// Le NIR et/ou la clé sont invalides.
/// Le NIR et/ou la clé sont null.
public static bool Check(string nir, string nirKey)
{
int unusedInt;
if (string.IsNullOrEmpty(nir) || string.IsNullOrEmpty(nirKey))
throw new ArgumentNullException(ExceptionMessages.StringNullOrEmpty);
if (nirKey.Length != _NIRKeyExactLength || !int.TryParse(nirKey, out unusedInt))
throw new ArgumentException(string.Format(ExceptionMessages.StringWrongLength, _NIRKeyExactLength));
return CalcKey(nir) == nirKey;
}
}
}