npm-pkg-hook 1.4.3 → 1.4.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -43,5 +43,5 @@
43
43
  "rm": "rm -rf node_modules package-lock.json && npm i",
44
44
  "test": "echo \"Error: no test specified\" && exit 1"
45
45
  },
46
- "version": "1.4.3"
46
+ "version": "1.4.4"
47
47
  }
@@ -14,6 +14,7 @@ export * from './usePushNotifications'
14
14
  export * from './useLocationManager'
15
15
  export * from './useFingerprintjs'
16
16
  export * from './useCountries'
17
+ export * from './useDessertWithPrice'
17
18
  export * from './generateStoreURL'
18
19
  export * from './useCreateStorePendingToRegister'
19
20
  export * from './useDepartments'
@@ -5,9 +5,8 @@ import { GET_ALL_SALES } from '../useReport/queries'
5
5
  export * from './useChartDataAllOrders'
6
6
 
7
7
  export const useChartData = ({ year }) => {
8
- // Construcción del nuevo array:
9
8
  const { data, loading } = useQuery(GET_ALL_SALES)
10
- const [chartType, setChartType] = useState('bar')
9
+ const [chartType, setChartType] = useState('line')
11
10
  const [chartTypeYear, setChartTypeYear] = useState(new Date().getFullYear())
12
11
  const [asFilter, setFilter] = useState(false)
13
12
  const [newResult, setNewResult] = useState([])
@@ -17,6 +17,10 @@ export const useDessert = ({
17
17
  initialData = null,
18
18
  sendNotification = () => { }
19
19
  }) => {
20
+ const [selectedExtra, setSelectedExtra] = useState({})
21
+ const [openModalEditExtra, setOpenModalEditExtra] = useState(false)
22
+ const [selectedItem, setSelectedItem] = useState({})
23
+
20
24
  // Initialize state variables using the useState hook
21
25
  const [setCheck, setChecker] = useState({
22
26
  exState: false
@@ -202,8 +206,24 @@ export const useDessert = ({
202
206
  console.error(error)
203
207
  }
204
208
  }
205
- const [selectedItem, setSelectedItem] = useState({})
206
209
 
210
+ /**
211
+ * Edits a single item within a list.
212
+ *
213
+ * The `editOneItem` function is responsible for editing the title of a specific item in a list.
214
+ * It first updates the state of the selected item, then searches for the item in the current list
215
+ * using its ID, and compares the existing title with the new title provided. If the title is
216
+ * different and not null, it makes an API call (`editExtFoodSubsOptional`) to update the
217
+ * title in the database. If the update is successful, a success notification is sent, and
218
+ * the local state is updated to reflect the changes in the item. The function handles errors
219
+ * internally and logs them to the console.
220
+ *
221
+ * @param {Object} params - Parameters for editing an item.
222
+ * @param {string} params.listID - The ID of the list containing the item to be edited.
223
+ * @param {string} params.id - The ID of the specific item to be edited.
224
+ * @param {string|null} [params.title=null] - The new title for the item. If null, no
225
+ * update is performed.
226
+ */
207
227
  const editOneItem = ({
208
228
  listID = '',
209
229
  id = '',
@@ -214,7 +234,7 @@ export const useDessert = ({
214
234
  return { listID, id }
215
235
  })
216
236
  const currentList = data.lists[listID]
217
- const findItem = currentList?.cards?.find(item => item.id === id)
237
+ const findItem = currentList?.cards?.find(item => { return item.id === id })
218
238
  const checkDifferentText = findItem?.title !== title
219
239
  if (title && checkDifferentText) {
220
240
  editExtFoodSubsOptional({
@@ -228,7 +248,7 @@ export const useDessert = ({
228
248
  const { success } = editExtFoodSubsOptional || { success: false }
229
249
  if (success) {
230
250
  sendNotification({
231
- description: 'El sub item actualizado con exito',
251
+ description: 'El sub item actualizado con éxito',
232
252
  title: 'Actualizado',
233
253
  backgroundColor: 'success'
234
254
  })
@@ -259,8 +279,6 @@ export const useDessert = ({
259
279
  console.error(error)
260
280
  }
261
281
  }
262
- const [selectedExtra, setSelectedExtra] = useState({})
263
- const [openModalEditExtra, setOpenModalEditExtra] = useState(false)
264
282
 
265
283
  const updateListById = (listId, updatedFields) => {
266
284
  setData((prevData) => {
@@ -0,0 +1,327 @@
1
+ import { useCallback, useEffect, useMemo, useRef, useState, createRef } from 'react'
2
+ import { useUpdateMultipleExtProductFoods } from '../useUpdateMultipleExtProductFoods'
3
+ import { useMutation } from '@apollo/client'
4
+ import { DELETE_EXTRA_PRODUCTS, EDIT_EXTRA_PRODUCT_FOODS } from './queries'
5
+
6
+ export const useDessertWithPrice = ({
7
+ dataExtra = [],
8
+ sendNotification = () => { },
9
+ setAlertBox = () => { }
10
+ } = {}) => {
11
+ const [selected, setSelected] = useState({
12
+ loading: false,
13
+ exPid: null
14
+ })
15
+ const [editExtraProductFoods] = useMutation(EDIT_EXTRA_PRODUCT_FOODS)
16
+
17
+ const initialLine = useMemo(() => {
18
+ return {
19
+ extraName: '',
20
+ extraPrice: '',
21
+ exState: false
22
+ }
23
+ }, [])
24
+
25
+ const initialLineItems = useMemo(() => {
26
+ return {
27
+ Lines: [
28
+ {
29
+ extraName: '',
30
+ extraPrice: '',
31
+ exState: false
32
+ },
33
+ (initialLine)
34
+ ]
35
+ }
36
+ }, [initialLine])
37
+ const transformedData = dataExtra?.map(item => ({
38
+ extraName: item.extraName || '',
39
+ extraPrice: item?.extraPrice?.toString() || '', // Convierte a string si es necesario
40
+ exState: !!item.exState,
41
+ forEdit: true,
42
+ ...item
43
+ }))
44
+ const [LineItems, setLine] = useState(
45
+ Array.isArray(dataExtra) && dataExtra.length > 0 ? { Lines: transformedData } : initialLineItems
46
+ )
47
+ useEffect(() => {
48
+ setLine(Array.isArray(dataExtra) && dataExtra.length > 0 ? { Lines: transformedData } : initialLineItems)
49
+ }, [dataExtra.length])
50
+
51
+ const inputRefs = useRef(LineItems.Lines.map(() => createRef()))
52
+
53
+ const handleSelect = (item, index) => {
54
+ try {
55
+ const { exPid } = item || {}
56
+ setSelected({ exPid, loading: false })
57
+ if (inputRefs?.current[index]) {
58
+ inputRefs.current[index].current.focus()
59
+ }
60
+ } catch (error) {
61
+ console.log(error)
62
+ }
63
+ }
64
+
65
+ useEffect(() => {
66
+ // Asegurándote de que las referencias se actualicen si LineItems cambia
67
+ inputRefs.current = LineItems.Lines.map((_, i) => inputRefs.current[i] || createRef())
68
+ }, [LineItems])
69
+ const handleCleanLines = useCallback(() => {
70
+ setLine(initialLineItems)
71
+ }, [initialLineItems])
72
+
73
+ const [updateMultipleExtProductFoods, { loading }] = useUpdateMultipleExtProductFoods({ handleCleanLines: () => { } })
74
+ /**
75
+ * Handles the addition of two new lines to the Lines array in LineItems state.
76
+ */
77
+ const handleAdd = useCallback(() => {
78
+ try {
79
+ // Ensure that LineItems and initialLine are not null or undefined
80
+ if (!LineItems || !initialLine) {
81
+ throw new Error('Han ocurrido un error.')
82
+ }
83
+
84
+ // Ensure that LineItems.Lines is an array
85
+ if (!Array.isArray(LineItems.Lines)) {
86
+ throw new Error('Han ocurrido un error.')
87
+ }
88
+
89
+ // Clone the existing Lines array and add two new objects (clones of initialLine) to it
90
+ const Lines = [...LineItems.Lines, { ...initialLine }]
91
+
92
+ // Update the LineItems state with the new Lines array
93
+ setLine((prevLineItems) => { return { ...prevLineItems, Lines } })
94
+ } catch (error) {
95
+ sendNotification({
96
+ title: error.message,
97
+ description: 'Error',
98
+ backgroundColor: 'error'
99
+ })
100
+ }
101
+ }, [LineItems, initialLine, setLine])
102
+
103
+ const handleFocusChange = (index) => {
104
+ const lastItem = LineItems.Lines.length - 1
105
+ if (lastItem === index) {
106
+ handleAdd()
107
+ }
108
+ }
109
+
110
+ /**
111
+ * Handles changes in line items, updating the state accordingly.
112
+ * @param {number} index - The index of the line item being updated.
113
+ * @param {string} name - The name of the attribute being changed.
114
+ * @param {any} value - The new value of the attribute.
115
+ */
116
+ const handleLineChange = (index, name, value) => {
117
+ const newLines = LineItems.Lines.map((line, i) => {
118
+ if (i !== index) return { ...line }
119
+
120
+ const newLine = { ...line }
121
+
122
+ if (name === 'extraName' || name === 'extraPrice') {
123
+ newLine[name] = value
124
+ } else if (name === 'exState') {
125
+ newLine[name] = value.target.checked
126
+ } else {
127
+ newLine[name] = value
128
+ }
129
+
130
+ return newLine
131
+ })
132
+
133
+ setLine({ ...LineItems, Lines: newLines })
134
+ }
135
+ const [deleteExtraProductFoods] = useMutation(DELETE_EXTRA_PRODUCTS)
136
+
137
+ const filterOneLine = (index) => {
138
+ console.log(index)
139
+ const Lines = LineItems?.Lines?.filter((_, i) => { return i !== index })
140
+ return setLine({ ...LineItems, Lines })
141
+ }
142
+ const handleRemove = async (i, exPid) => {
143
+ try {
144
+ if (exPid) {
145
+ const findDataExtra = dataExtra?.find(x => { return x?.exPid === exPid })
146
+ if (findDataExtra) {
147
+ const data = await deleteExtraProductFoods({
148
+ variables: {
149
+ state: 1,
150
+ id: exPid
151
+ }
152
+ })
153
+ const { success } = data?.data?.deleteextraproductfoods || {}
154
+ if (success) {
155
+ console.log(i, exPid)
156
+ return filterOneLine(i)
157
+ }
158
+ }
159
+ }
160
+ if (!exPid) {
161
+ return filterOneLine(i)
162
+ }
163
+ } catch (error) {
164
+ sendNotification({
165
+ title: 'error',
166
+ description: 'Ocurrió un error',
167
+ backgroundColor: 'error'
168
+ })
169
+ }
170
+ }
171
+
172
+ // Prepares and validates data for submission.
173
+ const prepareAndValidateData = useCallback((pId) => {
174
+ const dataArr = LineItems?.Lines?.map(({ extraPrice, exState, extraName }) => ({
175
+ extraPrice: parseFloat(extraPrice),
176
+ exState: exState === true ? 1 : 0,
177
+ extraName,
178
+ pId
179
+ }))
180
+
181
+ const message = 'Complete los campos vacíos'
182
+ const findInputEmpty = dataArr.find(({ extraName }) => extraName === '')
183
+ const findInputEmptyPrice = dataArr.find(({ extraPrice }) => isNaN(extraPrice) || extraPrice === '')
184
+
185
+ if (findInputEmpty || findInputEmptyPrice) {
186
+ setAlertBox({ message })
187
+ return null
188
+ }
189
+ return dataArr
190
+ }, [LineItems])
191
+
192
+ /**
193
+ * Convierte un string con números y puntos en un número entero.
194
+ * @param {string} str - El string a convertir.
195
+ * @returns {number} El número entero resultante.
196
+ */
197
+ function stringToInt (str) {
198
+ try {
199
+ // Verifica si el string es válido
200
+ if (!str || typeof str !== 'string') {
201
+ throw new Error('Input must be a valid string.')
202
+ }
203
+
204
+ // Elimina los puntos y convierte a número
205
+ const num = parseInt(str.replace(/\./g, ''), 10)
206
+
207
+ // Verifica si el resultado es un número válido
208
+ if (isNaN(num)) {
209
+ throw new Error('The string must contain only numbers and dots.')
210
+ }
211
+
212
+ return num
213
+ } catch (_error) {
214
+ return 0
215
+ }
216
+ }
217
+ const handleEdit = async (i, exPid) => {
218
+ setSelected({ exPid: null, loading: true })
219
+ const findOneExtra = LineItems?.Lines?.find((x, i) => { return x?.exPid === exPid })
220
+ const { extraName, extraPrice: price } = findOneExtra || {}
221
+ const extraPrice = stringToInt(price)
222
+ const { data } = await editExtraProductFoods({
223
+ variables: {
224
+ exPid,
225
+ extraName,
226
+ extraPrice
227
+ },
228
+ update: (cache) => {
229
+ cache.modify({
230
+ fields: {
231
+ ExtProductFoodsAll: () => {
232
+ return LineItems?.Lines || []
233
+ }
234
+ }
235
+ })
236
+ }
237
+ })
238
+ if (!data?.editExtraProductFoods?.success) {
239
+ return sendNotification({
240
+ title: 'Error',
241
+ description: data?.editExtraProductFoods?.message || '',
242
+ backgroundColor: 'error'
243
+ })
244
+ }
245
+
246
+ if (data?.editExtraProductFoods?.success) {
247
+ return sendNotification({
248
+ title: 'Producto actualizado',
249
+ description: data?.editExtraProductFoods?.message || '',
250
+ backgroundColor: 'success'
251
+ })
252
+ }
253
+ }
254
+ function filterItemsWithValidExPid (items, pId) {
255
+ // Primero, filtrar los elementos basados en exPid
256
+ const filteredItems = items.filter(({ exPid }) => {
257
+ const isExPidValid = !exPid
258
+ return isExPidValid
259
+ })
260
+
261
+ // Luego, transformar los elementos filtrados
262
+ return filteredItems.map(({ exPid, extraPrice, exState, extraName }) => ({
263
+ exPid,
264
+ extraPrice: stringToInt(extraPrice), // Asumiendo que tienes una función stringToInt definida
265
+ exState: exState === true ? 1 : 0,
266
+ extraName,
267
+ pId
268
+ }))
269
+ }
270
+
271
+ const handleSubmit = ({ pId }) => {
272
+ try {
273
+ if (!prepareAndValidateData(pId)) return
274
+ const dataArr = LineItems?.Lines?.map(x => {
275
+ const extraPrice = stringToInt(x.extraPrice)
276
+ const extraName = x.extraName
277
+ return {
278
+ extraPrice,
279
+ exState: x.exState === true ? 1 : 0,
280
+ extraName,
281
+ pId
282
+ }
283
+ })
284
+ const filteredItems = filterItemsWithValidExPid(LineItems?.Lines, pId)
285
+
286
+ return updateMultipleExtProductFoods({
287
+ variables: {
288
+ inputLineItems: {
289
+ setData: filteredItems
290
+ }
291
+ },
292
+ update: (cache) => {
293
+ cache.modify({
294
+ fields: {
295
+ ExtProductFoodsAll: () => {
296
+ return dataArr
297
+ }
298
+ }
299
+ })
300
+ }
301
+ }).then((res) => {
302
+ setAlertBox({ message: 'Se ha creado correctamente', duration: 7000, success: true })
303
+ })
304
+ } catch (error) {
305
+ setAlertBox({ message: `${error}`, duration: 7000 })
306
+ }
307
+ }
308
+ const isLoading = loading
309
+
310
+ return {
311
+ initialLine,
312
+ inputRefs,
313
+ selected,
314
+ loading: isLoading,
315
+ initialLineItems,
316
+ LineItems,
317
+ handleCleanLines,
318
+ handleLineChange,
319
+ handleSelect,
320
+ handleFocusChange,
321
+ setLine,
322
+ handleEdit,
323
+ handleRemove,
324
+ handleAdd,
325
+ handleSubmit
326
+ }
327
+ }
@@ -0,0 +1,18 @@
1
+ import { gql } from '@apollo/client'
2
+
3
+ export const DELETE_EXTRA_PRODUCTS = gql`
4
+ mutation deleteextraproductfoods($id: ID, $state: Int){
5
+ deleteextraproductfoods(id: $id, state: $state){
6
+ success,
7
+ message
8
+ }
9
+ }
10
+ `
11
+ export const EDIT_EXTRA_PRODUCT_FOODS = gql`
12
+ mutation EditExtraProductFoods($exPid: ID, $state: Int, $extraName: String, $extraPrice: Float) {
13
+ editExtraProductFoods(exPid: $exPid, state: $state, extraName: $extraName, extraPrice: $extraPrice) {
14
+ success
15
+ message
16
+ }
17
+ }
18
+ `
@@ -75,9 +75,9 @@ export const useProductsFood = ({
75
75
  export const useDeleteProductsFood = ({ sendNotification = () => { } } = {}) => {
76
76
  const [updateProductFoods, { data, loading, error }] = useMutation(UPDATE_PRODUCT_FOOD)
77
77
 
78
- const handleDelete = product => {
78
+ const handleDelete = async product => {
79
79
  const { pId, pState } = product || {}
80
- updateProductFoods({
80
+ return await updateProductFoods({
81
81
  variables: {
82
82
  input: {
83
83
  pId,
@@ -435,24 +435,6 @@ export const GET_EXTRAS_PRODUCT_FOOD_SUB_OPTIONAL = gql`
435
435
  }
436
436
  `
437
437
 
438
- // CREATE EXTRAS PRODUCT
439
- export const UPDATE_MULTI_EXTRAS_PRODUCT_FOOD = gql`
440
- mutation updateMultipleExtProductFoods(
441
- $inputLineItems: ILineItemsExtraFinal
442
- ) {
443
- updateMultipleExtProductFoods(inputLineItems: $inputLineItems) {
444
- pId
445
- exPid
446
- exState
447
- extraName
448
- extraPrice
449
- state
450
- pDatCre
451
- pDatMod
452
- }
453
- }
454
- `
455
-
456
438
  export const DELETE_ONE_PRODUCT = gql`
457
439
  mutation deleteProducts($input: IDeleteProduct) {
458
440
  deleteProducts(input: $input) {
@@ -1,7 +1,7 @@
1
1
  import { gql } from '@apollo/client'
2
2
 
3
3
  export const GET_ALL_ROAD = gql`
4
- query getTypeRoad{
4
+ query getTypeRoad {
5
5
  road{
6
6
  rId
7
7
  rName
@@ -26,7 +26,6 @@ import {
26
26
  } from './queries'
27
27
  import { updateExistingOrders } from '../useUpdateExistingOrders'
28
28
  import { useGetSale } from './useGetSale'
29
- import { convertToIntegerOrFloat } from './helpers'
30
29
  import { useCatWithProduct } from './../useCatWithProduct/index'
31
30
  import { useCheckboxState } from '../useCheckbox'
32
31
  import { useLogout } from '../useLogout'
@@ -488,7 +487,7 @@ export const useSales = ({
488
487
 
489
488
  function handleIncrementExtra ({ Adicionales, index }) {
490
489
  const { pId } = product?.PRODUCT || {}
491
- const exPid = Adicionales.exPid || null
490
+ const exPid = Adicionales?.exPid || null
492
491
 
493
492
  if (exPid && pId) {
494
493
  const newExtra = dataExtra.map((producto) => {
@@ -512,7 +511,7 @@ export const useSales = ({
512
511
 
513
512
  function handleDecrementExtra ({ Adicionales, index }) {
514
513
  const { pId } = product?.PRODUCT || {}
515
- const exPid = Adicionales.exPid || null
514
+ const exPid = Adicionales?.exPid || null
516
515
 
517
516
  // Comprobar que el objeto Adicionales existe en dataExtra
518
517
  const extraIndex = dataExtra.findIndex((extra) => extra.exPid === exPid)
@@ -0,0 +1,17 @@
1
+ import { useMutation } from '@apollo/client'
2
+ import { UPDATE_MULTI_EXTRAS_PRODUCT_FOOD } from './queries'
3
+
4
+ /**
5
+ * Custom hook para manejar la actualización de múltiples extras de productos alimenticios.
6
+ * @param {Function} cleanLines - Función para limpiar líneas después de completar la mutación.
7
+ * @returns {Array} Retorna un array con la función de mutación y el estado de carga.
8
+ */
9
+ export const useUpdateMultipleExtProductFoods = ({ cleanLines = () => { } } = {}) => {
10
+ const [updateMultipleExtProductFoods, { loading }] = useMutation(UPDATE_MULTI_EXTRAS_PRODUCT_FOOD, {
11
+ onCompleted: () => {
12
+ cleanLines()
13
+ }
14
+ })
15
+
16
+ return [updateMultipleExtProductFoods, { loading }]
17
+ }
@@ -0,0 +1,19 @@
1
+ import { gql } from '@apollo/client'
2
+
3
+ // CREATE EXTRAS PRODUCT
4
+ export const UPDATE_MULTI_EXTRAS_PRODUCT_FOOD = gql`
5
+ mutation updateMultipleExtProductFoods(
6
+ $inputLineItems: ILineItemsExtraFinal
7
+ ) {
8
+ updateMultipleExtProductFoods(inputLineItems: $inputLineItems) {
9
+ pId
10
+ exPid
11
+ exState
12
+ extraName
13
+ extraPrice
14
+ state
15
+ pDatCre
16
+ pDatMod
17
+ }
18
+ }
19
+ `
File without changes
@@ -37,7 +37,7 @@ export const validationSubmitHooks = elements => {
37
37
  }
38
38
 
39
39
  export const getCurrentDomain = () => {
40
- return typeof window !== 'undefined' && window.location.hostname;
40
+ return typeof window !== 'undefined' && window.location.hostname
41
41
  }
42
42
 
43
43
  export function RandomCode (length) {
@@ -70,8 +70,35 @@ export const updateCacheMod = async ({ cache, query, nameFun, dataNew, type, id
70
70
  const initialState = {}
71
71
  export const initializer = (initialValue = initialState) => { return JSON.parse(localStorage.getItem(process.env.LOCAL_SALES_STORE)) || initialValue }
72
72
 
73
- export const numberFormat = value => { return value ? (parseInt(value) ? new Intl.NumberFormat('de-DE').format(parseFloat(`${value}`.replace(/\./g, ''))) : value) : (value) }
73
+ /**
74
+ * Formatea un valor como un número siguiendo el formato de Colombia.
75
+ * Si el valor no es un número válido, lo devuelve tal como está.
76
+ *
77
+ * @param {string|number} value - El valor a formatear.
78
+ * @returns {string} El valor formateado como número o el valor original si no es numérico.
79
+ */
80
+ export const numberFormat = value => {
81
+ // Verifica si el valor es nulo o indefinido, devolviendo el mismo valor.
82
+ if (value === null || value === undefined) {
83
+ return value
84
+ }
74
85
 
86
+ // Convierte el valor a string y elimina puntos.
87
+ const stringValue = `${value}`.replace(/\./g, '')
88
+
89
+ // Intenta convertir a número y formatear si es posible.
90
+ const numberValue = parseFloat(stringValue)
91
+ if (!isNaN(numberValue)) {
92
+ return new Intl.NumberFormat('es-CO', {
93
+ minimumFractionDigits: 0,
94
+ style: 'decimal',
95
+ maximumFractionDigits: 0
96
+ }).format(numberValue)
97
+ }
98
+
99
+ // Devuelve el valor original si no es un número.
100
+ return value
101
+ }
75
102
  /**
76
103
  *
77
104
  * @param {Object} data objeto a filtrar