1
0

70 lines
2.1 KiB
C#
Raw Normal View History

2025-01-14 05:59:55 +00:00
using System.Text.RegularExpressions;
namespace RhSolutions.SkuParser.Models;
public record Product
{
2025-01-15 15:06:04 +03:00
private string _sku = string.Empty;
private const string _parsePattern = @"(?<Lead>[1\s]|^|\b)(?<Article>\d{6})(?<Delimiter>[\s13-])(?<Variant>\d{3})(\b|$)";
private const string _validnessPattern = @"^1\d{6}[1|3]\d{3}$";
2025-01-14 05:59:55 +00:00
/// <summary>
/// Артикул РЕХАУ в заданном формате
/// </summary>
public required string Sku
{
get => _sku;
set
{
_sku = IsValudSku(value)
? value
: throw new ArgumentException("$Неверный артикул: {value}");
}
}
2025-01-15 15:06:04 +03:00
public ProductLine? ProductLine { get; set; }
public string? Name { get; set; }
public decimal? Price { get; set; }
2025-01-14 05:59:55 +00:00
private static bool IsValudSku(string value)
{
return Regex.IsMatch(value.Trim(), _validnessPattern);
}
private static string GetSku(Match match)
{
string lead = match.Groups["Lead"].Value;
string article = match.Groups["Article"].Value;
string delimiter = match.Groups["Delimiter"].Value;
string variant = match.Groups["Variant"].Value;
if (lead != "1" && delimiter == "-")
{
return $"1{article}1{variant}";
}
else
{
return $"{lead}{article}{delimiter}{variant}";
}
}
/// <summary>
/// Проверка строки на наличие в ней артикула РЕХАУ
/// </summary>
/// <param name="value">Входная строка для проверки</param>
/// <param name="product">Артикул, если найден. null - если нет</param>
/// <returns>Если артикул в строке есть возвращает true, Если нет - false</returns>
public static bool TryParse(string value, out Product? product)
{
product = null;
MatchCollection matches = Regex.Matches(value, _parsePattern);
if (matches.Count == 0)
{
return false;
}
string sku = GetSku(matches.First());
product = new Product() { Sku = sku };
return true;
}
public override int GetHashCode() => Sku.GetHashCode();
public override string ToString() => Sku;
2025-01-15 15:06:04 +03:00
}