index.jsx 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  1. import { NON_DIGIT } from '../constants'
  2. import { Modal, notification } from 'antd'
  3. import { DeleteOutlined } from '@ant-design/icons'
  4. import httpService from '../services/httpService'
  5. import React from 'react'
  6. import { estatusExpediente } from './estatusExpediente'
  7. import { inventarioConcentracion } from './inventarioConcentracion'
  8. import { reporteExpediente } from './reporteExpediente'
  9. import { obtenerExtensionImagen } from './obtenerExtencionImagen'
  10. import { ValidarPermisosVista } from './ValidarPermisosVista'
  11. import { RenderEstatusSolicitudPrimaria } from './RenderEstatusSolicitudPrimaria'
  12. import { QuitarObjetosDuplicados } from './QuitarObjetosDuplicados'
  13. import { InformacionArchivos } from './InformacionArchivos'
  14. import { QuitarSignos } from './QuitarSignos'
  15. const baseUrl = import.meta.env.VITE_API_URL
  16. export const abrirArchivo = (url) => {
  17. if (url) {
  18. const a = document.createElement('a')
  19. a.target = '_blank'
  20. a.href = url
  21. a.click()
  22. }
  23. return null
  24. }
  25. const openInNewTab = (ruta) => {
  26. window.open(`${baseUrl}${ruta}`, '_blank', 'noopener,noreferrer')
  27. }
  28. const capitalizeFirst = (string) => {
  29. const split = string.split('-')
  30. let palabraUnida = ''
  31. split.forEach((s) => {
  32. palabraUnida = palabraUnida + s.charAt(0).toUpperCase() + s.slice(1)
  33. })
  34. return palabraUnida
  35. }
  36. const propertyAccesor = (rootObj, accesor = '') => {
  37. if (!rootObj) return ''
  38. const properties = accesor.split('.')
  39. let tmp = rootObj
  40. properties.forEach((prop) => (tmp = tmp[prop]))
  41. return tmp.toString()
  42. }
  43. const serialDateToJSDate = serial => {
  44. const step = new Date().getTimezoneOffset() <= 0 ? 25567 + 2 : 25567 + 1
  45. const utc_days = Math.floor(serial - step)
  46. const utc_value = utc_days * 86400
  47. const date_info = new Date(utc_value * 1000)
  48. const fractional_day = serial - Math.floor(serial) + 0.0000001
  49. let total_seconds = Math.floor(86400 * fractional_day)
  50. const seconds = total_seconds % 60
  51. total_seconds -= seconds
  52. const hours = Math.floor(total_seconds / (60 * 60))
  53. const minutes = Math.floor(total_seconds / 60) % 60
  54. return new Date(date_info.getFullYear(), date_info.getMonth(), date_info.getDate(), hours, minutes, seconds)
  55. }
  56. const validateName = (name) => {
  57. let re = /^[a-zA-Z]+(([',. -][a-zA-Z ])?[a-zA-Z]*)*$/
  58. return re.test(name)
  59. }
  60. const validateNumber = (number) => {
  61. const intValue = number.toString().replace(NON_DIGIT, '')
  62. return !isNaN(intValue)
  63. }
  64. const agregarFaltantes = (data, newData, campo) => {
  65. let ids = data.map(item => item[campo])
  66. let aux = [...data]
  67. for (let i in newData) {
  68. let modelo = newData[i]
  69. if (!modelo) {
  70. continue
  71. }
  72. const indice = ids.indexOf(modelo[campo])
  73. if (modelo && indice === -1) {
  74. aux.push(modelo)
  75. } else {
  76. aux[indice] = modelo
  77. }
  78. }
  79. return aux
  80. }
  81. const eliminarRegistro = (nombre, id, url, alTerminar) => {
  82. if (!id) return
  83. Modal.confirm({
  84. title: 'Eliminar',
  85. content: `¿Está seguro de eliminar "${nombre}"?`,
  86. icon: <DeleteOutlined style={{ color: '#ff0000' }}/>,
  87. okText: 'Eliminar',
  88. okButtonProps: {
  89. type: 'danger',
  90. },
  91. cancelText: 'Cancelar',
  92. onOk: async () => {
  93. try {
  94. const res = await httpService.delete(url, { id: id })
  95. if (res && res.status === 200) {
  96. notification.success({
  97. message: 'Éxito',
  98. description: res?.mensaje
  99. })
  100. alTerminar && alTerminar()
  101. } else if (res?.status === 400) {
  102. notification.error({
  103. message: 'Atención',
  104. description: res?.mensaje,
  105. })
  106. }
  107. } catch (error) {
  108. console.log(error)
  109. notification.error({
  110. message: 'Error',
  111. description: error,
  112. })
  113. return 'error'
  114. }
  115. },
  116. })
  117. }
  118. const respuestas = (res) => {
  119. let estatus = false
  120. if (!res) return 'Error en respuesta'
  121. console.log(res)
  122. if ((res?.status >= 400 && res?.status < 499)) {
  123. if (res?.errores !== null) {
  124. const errores = Object.values(res?.errores)
  125. notification.error({
  126. message: 'Atención',
  127. description: errores.map((e, i) => <React.Fragment key={`${i}-error`}><span>- {e}</span><br/></React.Fragment>),
  128. placement: 'bottomRight'
  129. })
  130. estatus = false
  131. } else {
  132. notification.error({
  133. message: 'Atención',
  134. description: res?.mensaje ? res?.mensaje : 'Hubo un problema del lado del servidor.',
  135. placement: 'bottomRight'
  136. })
  137. estatus = false
  138. }
  139. } else if (res?.status >= 500) {
  140. notification.error({
  141. message: 'Atención',
  142. description: 'Hubo un problema del lado del servidor.',
  143. placement: 'bottomRight'
  144. })
  145. estatus = false
  146. } else if (res?.status >= 200 && res?.status < 299) {
  147. notification.success({
  148. message: '¡Éxito!',
  149. description: `${res?.mensaje}`,
  150. placement: 'bottomRight'
  151. })
  152. estatus = true
  153. }
  154. return estatus
  155. }
  156. const generateDefaultChartOptions = (chartType = 'pie', options = {}, callback) => ({
  157. chart: {
  158. type: chartType,
  159. inverted: options.inverted || false,
  160. options3d: {
  161. enabled: chartType === 'pie',
  162. alpha: 45,
  163. beta: 0,
  164. },
  165. height: options.chartHeight || null,
  166. },
  167. colors: options?.colores || ['#2f7ed8', '#0d233a', '#8bbc21', '#910000', '#1aadce', '#492970', '#f28f43', '#77a1e5', '#c42525', '#a6c96a'],
  168. credits: {
  169. enabled: false,
  170. },
  171. title: {
  172. text: options?.titulo || 'TITULO POR DEFAULT',
  173. },
  174. plotOptions: {
  175. [chartType]: {
  176. innerSize: 100,
  177. depth: 45,
  178. events: {
  179. click: typeof callback === 'function' ? callback : () => {},
  180. },
  181. series: {
  182. stacking: 'normal'
  183. }
  184. },
  185. },
  186. series: [
  187. {
  188. name: options?.nombre || 'NOMBRE DE LA COLECCION DE DATOS',
  189. data: options?.datos || [],
  190. },
  191. ],
  192. subtitle: {
  193. text: options?.subtitulo || 'SUBTITULO POR DEFAULT',
  194. },
  195. ...options?.options
  196. })
  197. const lastPathName = () => {
  198. const url = window.location.pathname
  199. return {
  200. lastPath: url.split('/').pop(), // cambiar por pathname
  201. beforePath: url.split('/')[url.split('/').length - 2]
  202. }
  203. }
  204. const quitarSignos = (values) => {
  205. let _values = values
  206. if (typeof values === 'string')
  207. _values = values.replaceAll('$', '').replaceAll(',', '')
  208. return parseFloat(_values)
  209. }
  210. function makeKey (length) {
  211. let result = ''
  212. const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
  213. const charactersLength = characters.length
  214. for (var i = 0; i < length; i++) {
  215. result += characters.charAt(Math.floor(Math.random() * charactersLength))
  216. }
  217. return result
  218. }
  219. function eliminarObjeto (arr, key) {
  220. const obj = arr.findIndex((obj) => obj.key === key)
  221. if (obj > -1) {
  222. arr.splice(obj, 1)
  223. }
  224. return arr
  225. }
  226. const isEllipsis = (columns, key) => {
  227. const obtenerColumna = columns.find(column => column.key === key)
  228. return Boolean(obtenerColumna && obtenerColumna?.ellipsis)
  229. }
  230. const getRandomUid = () => Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15)
  231. const renderTotal = (array, prop) => {
  232. if (prop?.length > 0 && array?.length > 0) {
  233. const total = array.reduce((acc, curr) => acc + Number(curr[prop]), 0)
  234. return Number(total) > 0
  235. ? Number(total).toFixed(2)
  236. : (0).toFixed(2)
  237. }
  238. return (0).toFixed(2)
  239. }
  240. const FormatoPesos = (number = 0) => {
  241. const exp = /(\d)(?=(\d{3})+(?!\d))/g
  242. const rep = '$1,'
  243. return number?.toString().replace(exp, rep)
  244. }
  245. const ValidarRfc = (item) => {
  246. let re = /^[A-Z&Ñ]{3,4}[0-9]{2}(0[1-9]|1[012])(0[1-9]|[12][0-9]|3[01])[A-Z0-9]{2}[0-9A]$/
  247. let validado = item.match(re)
  248. if (!validado)
  249. return false
  250. else
  251. return true
  252. }
  253. const ValidarTelefono = (item) => {
  254. let re = /^[0-9]{10}$/
  255. let validado = item.match(re)
  256. if (!validado)
  257. return false
  258. else
  259. return true
  260. }
  261. const ValidarCorreo = (item) => {
  262. let re = /^[^@]+@[^@]+\.[a-zA-Z]{2,}$/
  263. let validado = item.match(re)
  264. if (!validado)
  265. return false
  266. else
  267. return true
  268. }
  269. const GetMesTexto = (number, corto = false) => {
  270. let mes = ''
  271. let mesCorto = ''
  272. let numero = parseInt(number)
  273. if (numero === 1) {
  274. mes = 'Enero'
  275. mesCorto = 'Ene'
  276. }
  277. if (numero === 2) {
  278. mes = 'Febrero'
  279. mesCorto = 'Feb'
  280. }
  281. if (numero === 3) {
  282. mes = 'Marzo'
  283. mesCorto = 'Mar'
  284. }
  285. if (numero === 4) {
  286. mes = 'Abril'
  287. mesCorto = 'Abr'
  288. }
  289. if (numero === 5) {
  290. mes = 'Mayo'
  291. mesCorto = 'May'
  292. }
  293. if (numero === 6) {
  294. mes = 'Junio'
  295. mesCorto = 'Jun'
  296. }
  297. if (numero === 7) {
  298. mes = 'Julio'
  299. mesCorto = 'Jul'
  300. }
  301. if (numero === 8) {
  302. mes = 'Agosto'
  303. mesCorto = 'Ago'
  304. }
  305. if (numero === 9) {
  306. mes = 'Septiembre'
  307. mesCorto = 'Sep'
  308. }
  309. if (numero === 10) {
  310. mes = 'Octubre'
  311. mesCorto = 'Oct'
  312. }
  313. if (numero === 11) {
  314. mes = 'Noviembre'
  315. mesCorto = 'Nov'
  316. }
  317. if (numero === 12) {
  318. mes = 'Diciembre'
  319. mesCorto = 'Dic'
  320. }
  321. if (corto)
  322. return mesCorto
  323. else
  324. return mes
  325. }
  326. const formatearMoneda = new Intl.NumberFormat('es-MX', { style: 'currency', currency: 'MXN' }).format
  327. export {
  328. agregarFaltantes,
  329. capitalizeFirst,
  330. propertyAccesor,
  331. serialDateToJSDate,
  332. validateName,
  333. validateNumber,
  334. QuitarObjetosDuplicados,
  335. eliminarRegistro,
  336. generateDefaultChartOptions,
  337. respuestas,
  338. lastPathName,
  339. makeKey,
  340. eliminarObjeto,
  341. openInNewTab,
  342. quitarSignos,
  343. isEllipsis,
  344. getRandomUid,
  345. renderTotal,
  346. FormatoPesos,
  347. ValidarRfc,
  348. InformacionArchivos,
  349. ValidarTelefono,
  350. ValidarCorreo,
  351. estatusExpediente,
  352. inventarioConcentracion,
  353. obtenerExtensionImagen,
  354. RenderEstatusSolicitudPrimaria,
  355. reporteExpediente,
  356. GetMesTexto,
  357. QuitarSignos,
  358. ValidarPermisosVista,
  359. formatearMoneda,
  360. }