NumberRuleFormatter.cs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. namespace Admin.NET.Plugin.AiDOP.Supply;
  2. public static class NumberRuleFormatter
  3. {
  4. public static int ResolveSerialWidth(int? maxValue)
  5. {
  6. if (!maxValue.HasValue || maxValue.Value <= 0) return 4;
  7. return Math.Max(1, maxValue.Value.ToString().Length);
  8. }
  9. public static string BuildNumber(string? prefix1, string? prefix2, string? prefix3, string? dateType, bool? isDateType, int serial, int? maxValue, DateTime now)
  10. {
  11. var prefix = BuildPrefix(prefix1, prefix2, prefix3, dateType, isDateType, now);
  12. return $"{prefix}{serial.ToString().PadLeft(ResolveSerialWidth(maxValue), '0')}";
  13. }
  14. public static string BuildPrefix(string? prefix1, string? prefix2, string? prefix3, string? dateType, bool? isDateType, DateTime now)
  15. {
  16. var prefix = string.Concat(
  17. prefix1?.Trim(),
  18. prefix2?.Trim(),
  19. prefix3?.Trim());
  20. if (isDateType == true || !string.IsNullOrWhiteSpace(dateType))
  21. prefix += FormatDatePart(dateType, now);
  22. return prefix;
  23. }
  24. public static string FormatDatePart(string? dateType, DateTime now)
  25. {
  26. var normalized = (dateType ?? string.Empty).Trim().ToUpperInvariant();
  27. return normalized switch
  28. {
  29. "YYYYMMDD" => now.ToString("yyyyMMdd"),
  30. "YYMMDD" => now.ToString("yyMMdd"),
  31. "YYYYMM" => now.ToString("yyyyMM"),
  32. "YYMM" => now.ToString("yyMM"),
  33. "YYYY" => now.ToString("yyyy"),
  34. "MMDD" => now.ToString("MMdd"),
  35. _ => normalized
  36. .Replace("YYYY", now.ToString("yyyy"))
  37. .Replace("YY", now.ToString("yy"))
  38. .Replace("MM", now.ToString("MM"))
  39. .Replace("DD", now.ToString("dd"))
  40. };
  41. }
  42. public static DateTime? ResolveSequenceDate(string? dateType, bool? isDateType, DateTime now)
  43. {
  44. var normalized = (dateType ?? string.Empty).Trim().ToUpperInvariant();
  45. if (isDateType != true && string.IsNullOrWhiteSpace(normalized)) return null;
  46. return normalized switch
  47. {
  48. "YY" or "YYYY" => new DateTime(now.Year, 1, 1),
  49. "YYMM" or "YYYYMM" => new DateTime(now.Year, now.Month, 1),
  50. _ => now.Date
  51. };
  52. }
  53. }