npm-pkg-hook 1.10.2 → 1.10.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
@@ -47,5 +47,5 @@
47
47
  "rm": "rm -rf node_modules package-lock.json && npm i",
48
48
  "test": "echo \"Error: no test specified\" && exit 1"
49
49
  },
50
- "version": "1.10.2"
50
+ "version": "1.10.4"
51
51
  }
@@ -122,3 +122,4 @@ export * from './useCart'
122
122
  export * from './useGetStoreCookie'
123
123
  export * from './getGlobalSession'
124
124
  export * from './handleLogin'
125
+ export * from './useInventory'
@@ -119,7 +119,7 @@ query ExtProductFoodsAll($search: String, $min: Int, $max: Int, $pId: ID) {
119
119
  export const GET_ALL_CATEGORIES_WITH_PRODUCT = gql`
120
120
  query getCatProductsWithProduct($search: String, $productName: String, $min: Int, $max: Int, $gender: [String], $desc: [String], $categories: [ID], ) {
121
121
  getCatProductsWithProduct(search: $search, min: $min, productName:$productName, max: $max, gender: $gender, desc: $desc, categories: $categories,) {
122
- totalCount,
122
+ totalCount,
123
123
  catProductsWithProduct {
124
124
  carProId
125
125
  pState
@@ -135,8 +135,9 @@ query getCatProductsWithProduct($search: String, $productName: String, $min: Int
135
135
  pDatMod
136
136
  productFoodsAll {
137
137
  pId
138
+ stock
139
+ manageStock
138
140
  sizeId
139
-
140
141
  colorId
141
142
  carProId
142
143
  cId
@@ -17,6 +17,7 @@ query getCatProductsWithProductClient($search: String, $min: Int, $max: Int, $ge
17
17
  productFoodsAll {
18
18
  pId
19
19
  sizeId
20
+ stock
20
21
  colorId
21
22
  carProId
22
23
  cId
@@ -9,7 +9,7 @@ export const useChartDataAllOrders = ({
9
9
 
10
10
  // Objeto para mapear los códigos de estado a sus nombres
11
11
  const statusMap = {
12
- 1: 'ACEPTA',
12
+ 1: 'ACCEPT',
13
13
  2: 'PROCESSING',
14
14
  3: 'READY',
15
15
  4: 'CONCLUDES',
@@ -5,7 +5,6 @@ import { convertBase64, RandomCode } from '../../utils'
5
5
  import { useLocalStorage } from '../useLocalSorage'
6
6
  import {
7
7
  GET_ALL_FOOD_PRODUCTS,
8
- UPDATE_IMAGE_PRODUCT_FOOD,
9
8
  UPDATE_PRODUCT_FOOD
10
9
  } from '../useProductsFood/queriesStore'
11
10
  import { useStore } from '../useStore'
@@ -13,6 +12,8 @@ import { useTagsProducts } from './../useProductsFood/usetagsProducts'
13
12
  import { useEditImageProduct } from './helpers/useEditImageProduct'
14
13
  import { getCatProductsWithProduct } from './helpers/manageCacheDataCatProduct'
15
14
  import { assignWith } from 'lodash'
15
+ import { UPDATE_IMAGE_PRODUCT_FOOD } from '../useSetImageProducts/queries'
16
+ import useSetImageProducts from '../useSetImageProducts'
16
17
  export * from './helpers'
17
18
 
18
19
  export const useCreateProduct = ({
@@ -38,6 +39,7 @@ export const useCreateProduct = ({
38
39
  ValueDelivery: 0,
39
40
  carProId: ''
40
41
  })
42
+ const [updateImageProducts] = useSetImageProducts()
41
43
  const [names, setName] = useLocalStorage('namefood', '')
42
44
  const [showMore, setShowMore] = useState(50)
43
45
  const [search, setSearch] = useState('')
@@ -52,7 +54,25 @@ export const useCreateProduct = ({
52
54
  const [{ alt, src }, setPreviewImg] = useState(initialState)
53
55
  const fileInputRef = useRef(null)
54
56
  const [arrTags, setTags] = useState([])
57
+ const [stock, setStock] = useState(1)
58
+ // Manage stock optional value boolean
59
+ const [checkStock, setCheckStock] = useState(false)
55
60
 
61
+ const handleIncreaseStock = () => {
62
+ setStock(prevStock => prevStock + 1)
63
+ }
64
+
65
+ const handleDecreaseStock = () => {
66
+ setStock(prevStock => (prevStock > 1 ? prevStock - 1 : 1))
67
+ }
68
+
69
+ const handleCheckStock = () => {
70
+ setCheckStock(prev => {
71
+ const newCheckStock = !prev
72
+ setStock(newCheckStock ? 1 : stock)
73
+ return newCheckStock
74
+ })
75
+ }
56
76
  const [dataStore] = useStore()
57
77
  const {
58
78
  data,
@@ -123,9 +143,7 @@ export const useCreateProduct = ({
123
143
 
124
144
  const [updateProductFoods, { loading }] = useMutation(UPDATE_PRODUCT_FOOD, {
125
145
  })
126
- const [setImageProducts] = useMutation(UPDATE_IMAGE_PRODUCT_FOOD, {
127
- context: { clientName: 'admin-server' }
128
- })
146
+ const [setImageProducts] = useMutation(UPDATE_IMAGE_PRODUCT_FOOD)
129
147
 
130
148
  const onFileInputChange = async event => {
131
149
  const { files } = event.target
@@ -172,7 +190,7 @@ export const useCreateProduct = ({
172
190
  }
173
191
  const formatPrice = ProPrice ?? 0
174
192
  if (!carProId && !names) return setErrors({ ...errors, carProId: true })
175
- const ProImage = `https:${process.env.URL_ADMIN_SERVER}/static/platos/${image?.name}`
193
+ const ProImage = '/images/placeholder-image.webp'
176
194
  const pCode = RandomCode(9)
177
195
  try {
178
196
  const res = await updateProductFoods({
@@ -184,8 +202,10 @@ export const useCreateProduct = ({
184
202
  ValueDelivery: check?.desc ? 0 : ValueDelivery,
185
203
  ProDescription,
186
204
  pName: names,
205
+ manageStock: checkStock,
187
206
  pCode,
188
207
  carProId,
208
+ stock,
189
209
  pState: 1,
190
210
  sTateLogistic: 1,
191
211
  ProStar: 0,
@@ -234,14 +254,11 @@ export const useCreateProduct = ({
234
254
  return
235
255
  }
236
256
  if (image !== null) {
257
+ console.log(image)
237
258
  try {
238
- await setImageProducts({
239
- variables: {
240
- input: {
241
- file: image,
242
- pCode
243
- }
244
- }
259
+ await updateImageProducts({
260
+ pId: res?.data?.updateProductFoods?.data?.pId,
261
+ image
245
262
  })
246
263
  } catch {
247
264
  sendNotification({
@@ -254,7 +271,7 @@ export const useCreateProduct = ({
254
271
  setPid(res?.data?.updateProductFoods?.data?.pId ?? null)
255
272
  return res
256
273
  } catch (error) {
257
- console.log("🚀 ~ handleRegister ~ error:", error)
274
+ console.log('🚀 ~ handleRegister ~ error:', error)
258
275
  setAlertBox({ message: 'Ha ocurrido un error', duration: 7000 })
259
276
  }
260
277
  }
@@ -283,9 +300,11 @@ export const useCreateProduct = ({
283
300
  fileInputRef,
284
301
  values,
285
302
  search,
303
+ stock,
286
304
  pId,
287
305
  dataTags: data,
288
306
  tags,
307
+ checkStock,
289
308
  loading,
290
309
  active,
291
310
  idStore: dataStore?.getStore?.idStore || '',
@@ -297,6 +316,8 @@ export const useCreateProduct = ({
297
316
  handleChangeFilter,
298
317
  handleUpdateBanner,
299
318
  onClickSearch,
319
+ handleDecreaseStock,
320
+ handleIncreaseStock,
300
321
  changeHandler,
301
322
  setErrors,
302
323
  setCheck,
@@ -305,6 +326,7 @@ export const useCreateProduct = ({
305
326
  onFileInputChange,
306
327
  handleRegisterTags,
307
328
  setShowMore,
329
+ handleCheckStock,
308
330
  onTargetClick,
309
331
  handleAddTag,
310
332
  handleCheck,
@@ -3,10 +3,11 @@ import gql from 'graphql-tag'
3
3
  export const GET_ALL_DEPARTMENTS = gql`
4
4
  query getAllDepartments($cId: ID!) {
5
5
  departments(cId: $cId) {
6
- dId
7
- cId
8
- dName
9
- dState
6
+ dId
7
+ cId
8
+ dName
9
+ dState
10
+ code_dId
10
11
  }
11
12
  }
12
13
  `
@@ -108,6 +108,7 @@ export const GET_ALL_PRODUCT_STORE = gql`
108
108
  ProPrice
109
109
  ProDescuento
110
110
  free
111
+ manageStock
111
112
  ProUniDisponibles
112
113
  ProDescription
113
114
  ProProtegido
@@ -126,6 +127,7 @@ export const GET_ALL_PRODUCT_STORE = gql`
126
127
  pDatMod
127
128
  ProDelivery
128
129
  ProVoltaje
130
+ stock
129
131
  pState
130
132
  feat {
131
133
  fId
@@ -0,0 +1,2 @@
1
+ export * from './useGetProductsInStock'
2
+ export * from './useUpdateManageStock'
@@ -0,0 +1,58 @@
1
+ import { useQuery, gql } from "@apollo/client";
2
+
3
+ export const GET_PRODUCTS_IN_STOCK = gql`
4
+ query getProductsInStock($limit: Int, $offset: Int) {
5
+ getProductsInStock(limit: $limit, offset: $offset) {
6
+ pId
7
+ sizeId #Talla
8
+ colorId #Color
9
+ carProId #Categoria a la cual pertenece el producto
10
+ caId
11
+ cId #Country
12
+ dId #Department
13
+ ctId #Cuidad
14
+ fId #Características
15
+ pName
16
+ getOneTags {
17
+ tPsId
18
+ idUser
19
+ idStore
20
+ pId
21
+ nameTag
22
+ }
23
+ ProPrice
24
+ ProDescuento
25
+ free
26
+ ProUniDisponibles
27
+ ProDescription
28
+ ProProtegido
29
+ ProAssurance
30
+ ValueDelivery
31
+ ProStar
32
+ sTateLogistic
33
+ ProImage
34
+ ProWidth
35
+ ProHeight
36
+ ProLength
37
+ ProWeight
38
+ ProQuantity
39
+ ProOutstanding
40
+ pDatCre
41
+ pDatMod
42
+ ProDelivery
43
+ ProVoltaje
44
+ pState
45
+ feat {
46
+ fId
47
+ thpId
48
+ hpqrQuestion
49
+ }
50
+ area {
51
+ aId
52
+ aName
53
+ }
54
+
55
+ }
56
+ }
57
+
58
+ `
@@ -0,0 +1,15 @@
1
+ import { useQuery } from '@apollo/client'
2
+ import { GET_PRODUCTS_IN_STOCK } from './queries'
3
+
4
+ export const useGetProductsInStock = (storeId) => {
5
+ const { data, loading, error } = useQuery(GET_PRODUCTS_IN_STOCK, {
6
+ variables: { storeId },
7
+ skip: !storeId
8
+ })
9
+
10
+ return {
11
+ data: data?.getProductsInStock || [],
12
+ loading,
13
+ error
14
+ }
15
+ }
@@ -0,0 +1,41 @@
1
+ import { gql, useMutation } from '@apollo/client'
2
+
3
+ /**
4
+ * GraphQL Mutation for updating stock and manageStock
5
+ */
6
+ const UPDATE_MANAGE_STOCK = gql`
7
+ mutation UpdateManageStock($input: InputManageStock) {
8
+ updateManageStock(input: $input) {
9
+ success
10
+ message
11
+ data {
12
+ pId
13
+ manageStock
14
+ }
15
+ }
16
+ }
17
+ `
18
+
19
+ /**
20
+ * Custom hook to update stock and manageStock
21
+ * @returns {object} { updateManageStock, data, loading, error }
22
+ */
23
+ export const useUpdateManageStock = () => {
24
+ const [updateManageStockMutation, { data, loading, error }] = useMutation(UPDATE_MANAGE_STOCK)
25
+
26
+ /**
27
+ * Function to call the mutation with given input
28
+ * @param {Object} input - { pId, stock, manageStock }
29
+ * @returns {Promise<Object>} Mutation response
30
+ */
31
+ const updateManageStock = async (input) => {
32
+ try {
33
+ const { data } = await updateManageStockMutation({ variables: { input } })
34
+ return data?.updateManageStock
35
+ } catch (err) {
36
+ return { success: false, message: err.message }
37
+ }
38
+ }
39
+
40
+ return [updateManageStock, { data, loading, error }]
41
+ }
@@ -26,7 +26,7 @@ export function useLocationManager (getDepartments, getCities) {
26
26
  }
27
27
 
28
28
  const handleDepartmentSearch = (value) => {
29
- getCities({ variables: { dId: value } })
29
+ getCities({ variables: { dId: 'ddd5a096-efc6-4541-a568-c91895bc219e' } })
30
30
  }
31
31
 
32
32
  const handleChangeLocation = (e, error) => {
@@ -41,7 +41,7 @@ export function useLocationManager (getDepartments, getCities) {
41
41
  case 'countryId':
42
42
  handleCountrySearch(value)
43
43
  break
44
- case 'dId':
44
+ case 'code_dId':
45
45
  handleDepartmentSearch(value)
46
46
  break
47
47
  default:
@@ -7,23 +7,23 @@
7
7
  * @returns {Array} - Filtered list of valid modules.
8
8
  */
9
9
  export const validateModules = (modules = [], permissions = {}) => {
10
- return modules
11
- .map(module => {
12
- // Check if the main module's view has "read" permission
13
- const hasReadPermission = permissions[module.view]?.includes('read')
10
+ if (!Array.isArray(modules) || module.length <= 0) return []
11
+ return modules?.map(module => {
12
+ // Check if the main module's view has "read" permission
13
+ const hasReadPermission = permissions[module.view]?.includes('read')
14
14
 
15
- // Validate and filter subModules if they exist
16
- const validSubModules = module.subModules?.filter(subModule =>
17
- permissions[subModule.view]?.includes('read')
18
- ) || []
15
+ // Validate and filter subModules if they exist
16
+ const validSubModules = module.subModules?.filter(subModule =>
17
+ permissions[subModule.view]?.includes('read')
18
+ ) || []
19
19
 
20
- // If the module or its subModules don't have read permission, exclude it
21
- if (!hasReadPermission && validSubModules.length === 0) {
22
- return null
23
- }
20
+ // If the module or its subModules don't have read permission, exclude it
21
+ if (!hasReadPermission && validSubModules.length === 0) {
22
+ return null
23
+ }
24
24
 
25
- // Return the module with its valid subModules
26
- return { ...module, subModules: validSubModules }
27
- })
25
+ // Return the module with its valid subModules
26
+ return { ...module, subModules: validSubModules }
27
+ })
28
28
  .filter(Boolean) // Remove null values
29
29
  }
@@ -86,7 +86,7 @@ query getAllOrdersFromStore(
86
86
  max: $max
87
87
  statusOrder: $statusOrder
88
88
  ) {
89
- ACEPTA {
89
+ ACCEPT {
90
90
  pdpId
91
91
  idStore
92
92
  pCodeRef
@@ -27,7 +27,13 @@ export const useProductsFood = ({
27
27
  }) => {
28
28
  // const [productsFood, setProductsFood] = useState([])
29
29
  const [showMore, setShowMore] = useState(500)
30
- const { data, loading, fetchMore, error, called } = useQuery(GET_ALL_PRODUCT_STORE, {
30
+ const {
31
+ data,
32
+ loading,
33
+ fetchMore,
34
+ error,
35
+ called
36
+ } = useQuery(GET_ALL_PRODUCT_STORE, {
31
37
  fetchPolicy,
32
38
  notifyOnNetworkStatusChange: true,
33
39
  nextFetchPolicy: 'cache-first',
@@ -202,6 +208,7 @@ export const useGetOneProductsFood = ({ fetchOnlyProduct = false } = {}) => {
202
208
  loading,
203
209
  error
204
210
  }] = useLazyQuery(GET_ONE_PRODUCTS_FOOD)
211
+
205
212
  const [handleGetExtProductFood, { data: dataOptional }] = useExtProductFoodsOptionalAll()
206
213
  const [handleExtProductFoodsAll, { data: dataExtra }] = useExtProductFoodsAll()
207
214
  const handleGetOneProduct = async (food) => {
@@ -101,6 +101,8 @@ export const GET_ALL_PRODUCT_STORE = gql`
101
101
  pId
102
102
  sizeId #Talla
103
103
  colorId #Color
104
+ stock
105
+ manageStock
104
106
  carProId #Categoria a la cual pertenece el producto
105
107
  caId
106
108
  cId #Country
@@ -315,14 +317,7 @@ export const UPDATE = gql`
315
317
  }
316
318
  }
317
319
  `
318
- export const UPDATE_IMAGE_PRODUCT_FOOD = gql`
319
- mutation setImageProducts($input: IFileImageProductFood) {
320
- setImageProducts(input: $input) {
321
- success
322
- message
323
- }
324
- }
325
- `
320
+
326
321
  export const UPDATE_PRODUCT_FOOD = gql`
327
322
  mutation updateProductFoods($input: InputProductFood) {
328
323
  updateProductFoods(input: $input) {
@@ -579,6 +574,8 @@ export const GET_ONE_PRODUCTS_FOOD = gql`
579
574
  idStore
580
575
  cId
581
576
  caId
577
+ stock
578
+ manageStock
582
579
  dId
583
580
  ctId
584
581
  tpId
@@ -850,7 +847,9 @@ export const GET_ALL_CATEGORIES_WITH_PRODUCT = gql`
850
847
  pId
851
848
  sizeId
852
849
  colorId
850
+ stock
853
851
  carProId
852
+ manageStock
854
853
  cId
855
854
  dId
856
855
  ctId
@@ -281,7 +281,7 @@ export const useSales = ({
281
281
  * @returns {Object} - The new state with the updated product quantity and editing status.
282
282
  */
283
283
  const handleCancelUpdateQuantity = (state, payload) => {
284
- // Validación de `state`
284
+ // Validación de `state`
285
285
  if (!state || typeof state !== 'object') {
286
286
  sendNotification({
287
287
  title: 'Error',
@@ -315,7 +315,7 @@ export const useSales = ({
315
315
  return {
316
316
  ...state,
317
317
  PRODUCT: state.PRODUCT.map((item) => {
318
- // Validación de propiedades en cada item
318
+ // Validación de propiedades en cada item
319
319
  if (item.pId === pId) {
320
320
  if (typeof item.oldQuantity !== 'number' || typeof item.unitPrice !== 'number') {
321
321
  sendNotification({
@@ -343,28 +343,48 @@ export const useSales = ({
343
343
  (state, action) => {
344
344
  const event = action.payload
345
345
  const { value, index, id } = event || {}
346
- const productExist = productsFood?.find((items) => {
347
- return items.pId === id
348
- })
349
- const OneProduct = state?.PRODUCT.find((items) => {
350
- return items.pId === id
351
- })
346
+
347
+ const productExist = productsFood?.find((items) => items.pId === id)
348
+ const OneProduct = state?.PRODUCT.find((items) => items.pId === id)
349
+
350
+ if (!productExist) return state // Validar si el producto existe
351
+
352
+ // Validar si el stock es 0
353
+ if (productExist.stock === 0) {
354
+ sendNotification({
355
+ title: 'Sin stock',
356
+ backgroundColor: 'warning',
357
+ description: `El producto ${OneProduct?.pName} está agotado y no puede ser modificado.`
358
+ })
359
+ return state
360
+ }
361
+
362
+ // Si el valor ingresado es menor o igual a 0, eliminar el producto del carrito
352
363
  if (value <= 0) {
353
- // @ts-ignore
354
364
  dispatch({ type: 'REMOVE_PRODUCT_TO_CART', payload: OneProduct })
365
+ return state
366
+ }
367
+
368
+ // Validar si se intenta superar el stock disponible
369
+ const finalQuantity = Math.min(value, productExist.stock)
370
+ if (value > productExist.stock) {
371
+ sendNotification({
372
+ title: 'Stock insuficiente',
373
+ backgroundColor: 'warning',
374
+ description: `No puedes agregar más unidades de ${OneProduct?.pName}, stock disponible: ${productExist.stock}`
375
+ })
355
376
  }
356
- const finalQuantity = (state.PRODUCT.ProQuantity = value || 0)
357
- const ARR_PRODUCT = state?.PRODUCT?.map((items, i) => {
358
- return i === index
377
+
378
+ const ARR_PRODUCT = state?.PRODUCT?.map((items, i) =>
379
+ i === index
359
380
  ? {
360
381
  ...items,
361
382
  ProQuantity: finalQuantity,
362
- ProPrice: value
363
- ? value * productExist?.ProPrice
364
- : productExist?.ProPrice
383
+ ProPrice: finalQuantity * productExist?.ProPrice
365
384
  }
366
385
  : items
367
- })
386
+ )
387
+
368
388
  return {
369
389
  ...state,
370
390
  PRODUCT: ARR_PRODUCT,
@@ -373,6 +393,7 @@ export const useSales = ({
373
393
  },
374
394
  [productsFood]
375
395
  )
396
+
376
397
  const paymentMethod = (state, action) => {
377
398
  return {
378
399
  ...state,
@@ -380,14 +401,6 @@ export const useSales = ({
380
401
  }
381
402
  }
382
403
  const PRODUCT = (state, action) => {
383
- const productExist = state.PRODUCT.find((items) => {
384
- return items.pId === action.id
385
- })
386
- const OurProduct = productsFood?.find((items) => {
387
- return items.pId === action.id
388
- })
389
- const isFree = productExist?.free
390
-
391
404
  switch (action.type) {
392
405
  case 'ADD_TO_CART':
393
406
  return addToCartFunc(state, action) // https://www.npmjs.com/package/@sourcetoad/vision-camera-plugin-barcode-scanner
@@ -436,22 +449,46 @@ export const useSales = ({
436
449
  case 'TOGGLE_EDITING_PRODUCT': {
437
450
  return handleToggleEditingStatus(state, action)
438
451
  }
439
- case 'INCREMENT':
452
+ case 'INCREMENT': {
440
453
  return {
441
454
  ...state,
442
455
  counter: state.counter + 1,
443
456
  PRODUCT: state?.PRODUCT?.map((items) => {
444
- return items.pId === action.id
445
- ? {
446
- ...items,
447
- ProQuantity: items.ProQuantity + 1,
448
- ProPrice: isFree
449
- ? 0
450
- : (productExist.ProQuantity + 1) * OurProduct?.ProPrice
451
- }
452
- : items
457
+ if (items.pId === action.id) {
458
+ const OurProduct = productsFood?.find((item) => item.pId === action.id)
459
+ const isFree = items.free
460
+ const newQuantity = items.ProQuantity + 1
461
+ // Validar si el stock es 0
462
+ if (OurProduct?.stock === 0) {
463
+ sendNotification({
464
+ title: 'Sin stock',
465
+ backgroundColor: 'warning',
466
+ description: `El producto ${items.pName} está agotado y no puede ser añadido al carrito.`
467
+ })
468
+ return items // Retornar sin modificar
469
+ }
470
+
471
+ // Validar si se supera el stock
472
+ if (newQuantity > OurProduct?.stock) {
473
+ sendNotification({
474
+ title: 'Stock insuficiente',
475
+ backgroundColor: 'warning',
476
+ description: `No puedes agregar más unidades de ${items.pName}, stock disponible: ${OurProduct?.stock}`
477
+ })
478
+ return items // Retornar el producto sin modificar
479
+ }
480
+
481
+ return {
482
+ ...items,
483
+ ProQuantity: newQuantity,
484
+ ProPrice: isFree ? 0 : newQuantity * OurProduct?.ProPrice
485
+ }
486
+ }
487
+ return items
453
488
  })
454
489
  }
490
+ }
491
+
455
492
  case 'PUT_COMMENT':
456
493
  return commentProducts(state, action)
457
494
  case 'PUT_EXTRA_PRODUCTS_AND_OPTIONAL_PRODUCT':
@@ -704,19 +741,46 @@ export const useSales = ({
704
741
  }
705
742
  }
706
743
 
744
+ function isStockInsufficient (currentQuantity, stock) {
745
+ return currentQuantity >= stock
746
+ }
747
+
748
+ function sendAlertStock (stock) {
749
+ return sendNotification({
750
+ title: 'Stock insuficiente',
751
+ backgroundColor: 'warning',
752
+ description: `Solo hay ${stock} unidades disponibles en el inventario`
753
+ })
754
+ }
755
+
707
756
  function addToCartFunc (state, action) {
708
757
  const {
709
758
  pId,
710
759
  pName,
711
760
  getOneTags,
761
+ stock,
712
762
  ProDescription,
713
763
  ProImage,
714
764
  ProPrice
715
- } = action.payload
765
+ } = action.payload ?? {}
766
+ if (stock === 0) {
767
+ sendNotification({
768
+ title: 'Sin stock',
769
+ backgroundColor: 'warning',
770
+ description: 'Producto sin stock disponible en tu inventario'
771
+ })
772
+ return state
773
+ }
716
774
 
717
775
  const productExist = state?.PRODUCT.find((item) => item.pId === pId)
718
776
  const OurProduct = productsFood?.find((item) => item.pId === pId)
719
777
  const isFree = productExist?.free
778
+ const currentQuantity = productExist?.ProQuantity || 0
779
+ console.log('currentQuantity', productExist)
780
+ if (productExist?.manageStock && isStockInsufficient(currentQuantity, stock)) {
781
+ sendAlertStock(stock)
782
+ return state
783
+ }
720
784
 
721
785
  const updatedProduct = {
722
786
  pId,
@@ -724,9 +788,11 @@ export const useSales = ({
724
788
  editing: false,
725
789
  getOneTags,
726
790
  unitPrice: OurProduct?.ProPrice,
791
+ manageStock: OurProduct?.manageStock ?? false,
727
792
  ProDescription,
728
793
  ProImage,
729
794
  ProPrice,
795
+ stock,
730
796
  ProQuantity: 1
731
797
  }
732
798
 
@@ -857,7 +923,7 @@ export const useSales = ({
857
923
  const arrayProduct = data?.PRODUCT?.length > 0
858
924
  ? data?.PRODUCT?.map((product) => {
859
925
  const filteredDataExtra =
860
- product?.dataExtra?.map(({ __typename, ...rest }) => rest) ?? []
926
+ product?.dataExtra?.map(({ __typename, ...rest }) => rest) ?? []
861
927
  const dataOptional = product?.dataOptional?.map(
862
928
  ({ __typename, ...product }) => {
863
929
  const { ExtProductFoodsSubOptionalAll, ...rest } = product
@@ -991,6 +1057,16 @@ export const useSales = ({
991
1057
  pickUp: 1,
992
1058
  discount: discount.discount || 0,
993
1059
  totalProductsPrice: convertInteger(totalProductsPrice) || 0
1060
+ },
1061
+ update (cache) {
1062
+ cache.modify({
1063
+ fields: {
1064
+ productFoodsAll (existingProductFoodsAll = []) {
1065
+ console.log('existingProductFoodsAll', existingProductFoodsAll)
1066
+ return existingProductFoodsAll
1067
+ }
1068
+ }
1069
+ })
994
1070
  }
995
1071
  })
996
1072
  .then((responseRegisterR) => {
@@ -1082,9 +1158,9 @@ export const useSales = ({
1082
1158
  ? existOptionalCookies
1083
1159
  ?.map((obj) => {
1084
1160
  const filteredSubOptions =
1085
- obj.ExtProductFoodsSubOptionalAll.filter(
1086
- (subObj) => subObj.check === true
1087
- )
1161
+ obj.ExtProductFoodsSubOptionalAll.filter(
1162
+ (subObj) => subObj.check === true
1163
+ )
1088
1164
  // Excluya todo el objeto padre si filteredSubOptions está vacío
1089
1165
  if (filteredSubOptions.length === 0) {
1090
1166
  return null
@@ -0,0 +1,30 @@
1
+ import { useMutation } from '@apollo/client'
2
+ import { UPDATE_IMAGE_PRODUCT_FOOD } from './queries'
3
+
4
+ const useSetImageProducts = () => {
5
+ const [setImageProducts, { data, loading, error }] = useMutation(UPDATE_IMAGE_PRODUCT_FOOD)
6
+
7
+ const updateImageProducts = async (variables) => {
8
+ try {
9
+ const response = await setImageProducts({
10
+ variables: {
11
+ input: {
12
+ ...variables
13
+ }
14
+ }
15
+ })
16
+ return response
17
+ } catch (err) {
18
+ console.error('Error updating image products:', err)
19
+ throw err
20
+ }
21
+ }
22
+
23
+ return [updateImageProducts, {
24
+ data,
25
+ loading,
26
+ error
27
+ }]
28
+ }
29
+
30
+ export default useSetImageProducts
@@ -0,0 +1,13 @@
1
+ import { gql } from '@apollo/client'
2
+
3
+ export const UPDATE_IMAGE_PRODUCT_FOOD = gql`
4
+ mutation setImageProducts($input: IFileImageProductFood) {
5
+ setImageProducts(input: $input) {
6
+ success
7
+ message
8
+ errors {
9
+ message
10
+ }
11
+ }
12
+ }
13
+ `
@@ -29,7 +29,7 @@ export const updateExistingOrders = (
29
29
  const updatedExistingOrders = { ...existingOrders } // Copiar el objeto existente
30
30
 
31
31
  const statusKeys = {
32
- 1: 'ACEPTA',
32
+ 1: 'ACCEPT',
33
33
  2: 'PROCESSING',
34
34
  3: 'READY',
35
35
  4: 'CONCLUDES',
@@ -11,25 +11,36 @@ export const useUpdateMultipleProducts = ({
11
11
  loading,
12
12
  error
13
13
  }] = useMutation(UPDATE_MULTIPLE_PRODUCTS)
14
+
14
15
  const [dataCategoriesProducts] = useCategoriesProduct()
15
- const findEmptyCategory = dataCategoriesProducts?.find(category => category.pName === CATEGORY_EMPTY)
16
+ const findEmptyCategory = dataCategoriesProducts?.find(({ pName }) => pName === CATEGORY_EMPTY)
16
17
  const updateProducts = async (products) => {
17
18
  const newProducts = products.map(product => {
19
+ const {
20
+ PRECIO_AL_PUBLICO: ProPrice,
21
+ DESCRIPCION: ProDescription,
22
+ NOMBRE: pName,
23
+ pCode,
24
+ CANTIDAD: stock = 0,
25
+ 'IMPUESTO (%)': vat,
26
+ CODIGO_DE_BARRAS: ProBarCode
27
+ } = product
18
28
  return {
19
29
  idStore: '',
20
- ProPrice: product.PRECIO_AL_PUBLICO,
30
+ ProPrice,
21
31
  ProDescuento: 0,
22
32
  ValueDelivery: 0,
23
- ProDescription: product.DESCRIPCION,
24
- pName: product.NOMBRE,
25
- pCode: product.pCode,
33
+ ProDescription,
34
+ pName,
35
+ pCode,
26
36
  carProId: findEmptyCategory?.carProId ?? null,
27
37
  pState: 1,
28
38
  sTateLogistic: 1,
29
39
  ProStar: 0,
40
+ stock,
30
41
  ProImage: null,
31
- vat: product['IMPUESTO (%)'],
32
- ProBarCode: product.CODIGO_DE_BARRAS,
42
+ vat,
43
+ ProBarCode: String(ProBarCode) || '',
33
44
  ProHeight: null,
34
45
  ProWeight: '',
35
46
  ProOutstanding: 0,
@@ -39,6 +50,16 @@ export const useUpdateMultipleProducts = ({
39
50
  )
40
51
  try {
41
52
  const response = await updateMultipleProducts({ variables: { input: newProducts } })
53
+ // sendNotification
54
+ for (const { errors } of response.data.updateMultipleProducts) {
55
+ if (errors) {
56
+ sendNotification({
57
+ backgroundColor: 'error',
58
+ description: errors[0].message,
59
+ title: 'Error'
60
+ })
61
+ }
62
+ }
42
63
  return response.data.updateMultipleProducts
43
64
  } catch (e) {
44
65
  sendNotification({
@@ -48,4 +48,4 @@ export const UPDATE_MULTIPLE_PRODUCTS = gql`
48
48
  }
49
49
  }
50
50
  }
51
- `;
51
+ `
@@ -3,60 +3,68 @@ export const validateProductDataExcel = (product, productIndex) => {
3
3
  {
4
4
  name: 'NOMBRE',
5
5
  required: true,
6
- type: 'string'
6
+ types: ['string']
7
7
  },
8
8
  {
9
9
  name: 'PRECIO_AL_PUBLICO',
10
10
  required: false,
11
- type: 'number'
11
+ types: ['number', 'string']
12
12
  },
13
13
  {
14
14
  name: 'VALOR_DE_COMPRA',
15
15
  required: false,
16
- type: 'number'
16
+ types: ['number', 'string']
17
17
  },
18
18
  {
19
19
  name: 'CANTIDAD',
20
20
  required: true,
21
- type: 'number'
21
+ types: ['number']
22
22
  },
23
23
  {
24
24
  name: 'DESCRIPCION',
25
25
  required: true,
26
- type: 'string'
26
+ types: ['string']
27
27
  },
28
28
  {
29
29
  name: 'DESCUENTO',
30
30
  required: false,
31
- type: 'number'
31
+ types: ['number', 'string']
32
32
  },
33
33
  {
34
34
  name: 'CATEGORIA',
35
35
  required: false,
36
- type: 'string'
36
+ types: ['string']
37
37
  },
38
38
  {
39
39
  name: 'CODIGO_DE_BARRAS',
40
40
  required: false,
41
- type: 'string'
41
+ types: ['string', 'number']
42
42
  },
43
43
  {
44
44
  name: 'IMPUESTO (%)',
45
45
  required: false,
46
- type: 'number'
46
+ types: ['number', 'string']
47
47
  }
48
48
  ]
49
49
 
50
50
  const errors = []
51
51
 
52
- // Validar encabezados requeridos
53
- expectedHeaders.forEach(({ name, required, type }) => {
54
- if (required && !(name in product)) {
55
- errors.push(`Producto ${productIndex + 1}: Faltan la columna requerida: ${name}.`)
56
- } else if (product[name] !== undefined) {
57
- const isValidType = typeof product[name] === type || (type === 'number' && typeof product[name] === 'number' && !isNaN(product[name]))
52
+ // Validar encabezados requeridos y tipos
53
+ expectedHeaders.forEach(({ name, required, types }) => {
54
+ const value = product[name]
55
+
56
+ if (required && (value === undefined || value === null)) {
57
+ errors.push(`Producto ${productIndex + 1}: Falta la columna requerida: ${name}.`)
58
+ } else if (value !== undefined && value !== null) {
59
+ const isValidType = types.some(type => {
60
+ if (type === 'number') {
61
+ return typeof value === 'number' && !isNaN(value)
62
+ }
63
+ return typeof value === type
64
+ })
65
+
58
66
  if (!isValidType) {
59
- errors.push(`Producto ${productIndex + 1}: El campo ${name} debe ser de tipo ${type}.`)
67
+ errors.push(`Producto ${productIndex + 1}: El campo ${name} debe ser de tipo ${types.join(' o ')}.`)
60
68
  }
61
69
  }
62
70
  })
@@ -10,8 +10,11 @@ const STEPS = {
10
10
 
11
11
  export const useUploadProducts = ({
12
12
  sendNotification = () => { return null }
13
- } = {}) => {
13
+ } = {
14
+ sendNotification: () => { return null }
15
+ }) => {
14
16
  const [data, setData] = useState([])
17
+ console.log("🚀 ~ data:", data)
15
18
  const [isLoading, setIsLoading] = useState(false)
16
19
  const [active, setActive] = useState(STEPS.UPLOAD_FILE)
17
20
  const [overActive, setOverActive] = useState(STEPS.UPLOAD_FILE)
@@ -19,7 +22,6 @@ export const useUploadProducts = ({
19
22
  const handleOverActive = (index) => {
20
23
  setOverActive(index)
21
24
  }
22
-
23
25
  const readExcelFile = (file) => {
24
26
  return new Promise((resolve, reject) => {
25
27
  const reader = new FileReader()
@@ -117,8 +119,9 @@ export const useUploadProducts = ({
117
119
  })
118
120
  return
119
121
  }
120
- if (active === STEPS.UPLOAD_FILE && Boolean(!data.length)) return setActive(0)
121
- if (active === STEPS.UPLOAD_FILE && Boolean(data.length)) return setActive(STEPS.UPLOAD_PRODUCTS)
122
+ if (active === STEPS.UPLOAD_FILE) {
123
+ setActive(data.length ? STEPS.UPLOAD_PRODUCTS : 0)
124
+ }
122
125
  }
123
126
 
124
127
  const updateProductQuantity = (index, quantityChange) => {
@@ -56,12 +56,12 @@ username
56
56
  lastName
57
57
  email
58
58
  avatar
59
- idRole
60
59
  uToken
61
60
  uPhoNum
62
61
  ULocation
63
62
  upLat
64
63
  uState
64
+ idRole
65
65
  upLon
66
66
  upIdeDoc
67
67
  siteWeb
@@ -70,7 +70,6 @@ associateStore
70
70
  createAt
71
71
  role {
72
72
  name
73
- idRole,
74
73
  permissions
75
74
  description
76
75
  createdAt
package/src/index.jsx CHANGED
@@ -1,7 +1,9 @@
1
+ import packageJson from '../package.json'
2
+
1
3
  export * from './hooks/index'
2
4
  export * from './utils'
3
5
  export * from './cookies'
4
6
  export * from './security/index'
5
7
 
6
8
  // version
7
- export { version } from '../package.json'
9
+ export const version = packageJson.version
@@ -84,9 +84,6 @@ export const updateCacheMod = async ({ cache, query, nameFun, dataNew, type, id
84
84
  }
85
85
  })
86
86
  }
87
- const initialState = {}
88
- export const initializer = (initialValue = initialState) => { return JSON.parse(localStorage.getItem(process.env.LOCAL_SALES_STORE)) || initialValue }
89
-
90
87
  /**
91
88
  * Formatea un valor como un número siguiendo el formato de Colombia.
92
89
  * Si el valor no es un número válido, lo devuelve tal como está.
@@ -107,9 +104,9 @@ export const numberFormat = value => {
107
104
  const numberValue = parseFloat(stringValue)
108
105
  if (!isNaN(numberValue)) {
109
106
  return new Intl.NumberFormat('es-CO', {
110
- minimumFractionDigits: 0,
107
+ minimumFractionDigits: 2,
111
108
  style: 'decimal',
112
- maximumFractionDigits: 0
109
+ maximumFractionDigits: 2
113
110
  }).format(numberValue)
114
111
  }
115
112