utils.js 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163
  1. import { useI18n } from "vue-i18n";
  2. /**
  3. * @description Corta um valor em um determinado tamanho, adicionando "..." no final.
  4. * @param {*} value valor a ser cortado (convertido para string).
  5. * @param {number} maxLength tamanho máximo antes de truncar.
  6. * @returns {string} string truncada.
  7. */
  8. const truncate = (value, maxLength = 40) => {
  9. const text = value == null ? "" : String(value);
  10. if (text.length <= maxLength) return text;
  11. return `${text.slice(0, maxLength)}...`;
  12. };
  13. /**
  14. * @description Formata uma data de DD/MM/YYYY para YYYY-MM-DD
  15. * @param {string} date data.
  16. * @param {string} time tempo.
  17. * @throws {Error} Caso a data seja nula ou invalida.
  18. * @returns {string} data formatada.
  19. */
  20. const formatDateDMYtoYMD = (date, time) => {
  21. if (!date) throw new Error(useI18n().t("validation.rules.required"));
  22. const testDate =
  23. /^([0-2][0-9]|(3)[0-1])(\/)(((0)[0-9])|((1)[0-2]))(\/)\d{4}$/;
  24. if (testDate.test(date) === false)
  25. throw new Error(useI18n().t("validation.rules.date"));
  26. const [day, month, year] = date.split("/");
  27. return `${year}-${month}-${day} ${time ? time : ""}`;
  28. };
  29. /**
  30. * @description Converte uma data e hora para o formato brasileiro.
  31. * @param {string} dateTimeString data e hora.
  32. * @returns {string} data e hora no formato brasileiro.
  33. * @throws {Error} Caso a data seja nula ou invalida.
  34. * @returns {string} data formatada.
  35. * @example
  36. * // convertDateTime("2023-05-23T13:07:27.000000Z");
  37. * // Output: 23/05/2023 10:07:27
  38. */
  39. const convertDateTime = (dateTimeString) => {
  40. const dateTime = new Date(dateTimeString);
  41. const options = {
  42. timeZone: "America/Sao_Paulo",
  43. day: "2-digit",
  44. month: "2-digit",
  45. year: "numeric",
  46. hour: "2-digit",
  47. minute: "2-digit",
  48. second: "2-digit",
  49. };
  50. const formattedDateTime = dateTime
  51. .toLocaleString("pt-BR", options)
  52. .replace(",", "");
  53. return formattedDateTime;
  54. };
  55. /**
  56. * @description Formata uma data de YYYY-MM-DD para DD/MM/YYYY
  57. * @param {string} dateTime data e hora.
  58. * @returns {string} data e hora no formato brasileiro.
  59. * @example
  60. * // formatDateYMDtoDMY("2023-05-23T13:07:27.000000Z");
  61. * // Output: 23/05/2023 10:07:27
  62. */
  63. const formatDateYMDtoDMY = (dateTime) => {
  64. if (!dateTime || typeof dateTime !== "string") return "-";
  65. const normalizedDateTime = dateTime.trim().replace("T", " ");
  66. if (!normalizedDateTime) return "-";
  67. const [datePart, timePart] = normalizedDateTime.split(" ");
  68. const [year, month, day] = datePart.split("-");
  69. if (!year || !month || !day) return "-";
  70. const formattedDate = `${day}/${month}/${year}`;
  71. if (timePart) {
  72. const [hours, minutes, seconds = "00"] = timePart
  73. .replace("Z", "")
  74. .split(":");
  75. const formattedTime = `${hours}:${minutes}:${seconds.split(".")[0]}`;
  76. return `${formattedDate} ${formattedTime}`;
  77. }
  78. return formattedDate;
  79. };
  80. /**
  81. * @description Formata a moeda.
  82. * @param {number} value valor.
  83. * @returns {string} valor formatado.
  84. */
  85. const formatToBRLCurrency = (value) => {
  86. if (value != null) {
  87. value = parseFloat(value);
  88. return value.toLocaleString("pt-BR", {
  89. minimumFractionDigits: 2,
  90. style: "currency",
  91. currency: "BRL",
  92. });
  93. }
  94. return value;
  95. };
  96. const normalizeString = (val) =>
  97. val
  98. .toLowerCase()
  99. .normalize("NFKD")
  100. .replace(/[\u0300-\u036f~]/g, "");
  101. const normalizeUnitName = (value) => {
  102. const name = String(value ?? "").trim();
  103. return name && !["null", "undefined"].includes(name.toLowerCase())
  104. ? name
  105. : null;
  106. };
  107. const formatUnitName = (unit, fallback = "Unidade sem nome") =>
  108. normalizeUnitName(unit?.name) ||
  109. normalizeUnitName(unit?.fantasy_name) ||
  110. normalizeUnitName(unit?.social_reason) ||
  111. fallback;
  112. const isUnderage = (birthDate, referenceDate = new Date()) => {
  113. if (!birthDate || typeof birthDate !== "string") return false;
  114. const normalizedDate = birthDate.trim().split(" ")[0];
  115. const parts = normalizedDate.includes("/")
  116. ? normalizedDate.split("/").reverse()
  117. : normalizedDate.split("-");
  118. const [year, month, day] = parts.map(Number);
  119. if (!year || !month || !day) return false;
  120. const parsedBirthDate = new Date(year, month - 1, day);
  121. const isValidDate =
  122. parsedBirthDate.getFullYear() === year &&
  123. parsedBirthDate.getMonth() === month - 1 &&
  124. parsedBirthDate.getDate() === day;
  125. if (!isValidDate) return false;
  126. const eighteenthBirthday = new Date(year + 18, month - 1, day);
  127. return eighteenthBirthday > referenceDate;
  128. };
  129. export {
  130. formatDateDMYtoYMD,
  131. formatDateYMDtoDMY,
  132. truncate,
  133. convertDateTime,
  134. formatToBRLCurrency,
  135. normalizeString,
  136. formatUnitName,
  137. isUnderage,
  138. };