npm-pkg-hook 1.8.6 → 1.8.8

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
@@ -3,6 +3,7 @@
3
3
  "dependencies": {
4
4
  "@apollo/client": "3.6.9",
5
5
  "@typescript-eslint/parser": "^5.37.0",
6
+ "file-saver": "2.0.5",
6
7
  "js-cookie": "3.0.1",
7
8
  "lodash": "^4.17.21",
8
9
  "md5": "2.3.0",
@@ -10,7 +11,8 @@
10
11
  "react": "18.1.0",
11
12
  "react-dom": "18.1.0",
12
13
  "react-query": "^3.39.2",
13
- "react-responsive": "^10.0.0"
14
+ "react-responsive": "^10.0.0",
15
+ "xlsx": "0.18.5"
14
16
  },
15
17
  "description": "description-pkg-hook",
16
18
  "devDependencies": {
@@ -45,5 +47,5 @@
45
47
  "rm": "rm -rf node_modules package-lock.json && npm i",
46
48
  "test": "echo \"Error: no test specified\" && exit 1"
47
49
  },
48
- "version": "1.8.6"
50
+ "version": "1.8.8"
49
51
  }
@@ -0,0 +1,62 @@
1
+ import * as Excel from 'xlsx'
2
+ import { saveAs } from 'file-saver'
3
+
4
+ /**
5
+ * Class to generate Excel reports.
6
+ */
7
+ export class GenerateReport {
8
+ /**
9
+ * Generates an Excel report from given data and type.
10
+ * @param {Array<object>} data - The data to be included in the Excel report.
11
+ * @param {number} type - The type of report to generate.
12
+ * @throws Will throw an error if data is not an array or type is not a valid number.
13
+ */
14
+ GenExcelReport (data, type) {
15
+ if (!Array.isArray(data)) {
16
+ throw new Error('Data must be an array of objects.')
17
+ }
18
+
19
+ if (typeof type !== 'number') {
20
+ throw new Error('Type must be a valid number.')
21
+ }
22
+
23
+ const ws = Excel.utils.json_to_sheet(data)
24
+
25
+ // Apply bold font to the header row
26
+ const range = Excel.utils.decode_range(ws['!ref'])
27
+ for (let C = range.s.c; C <= range.e.c; ++C) {
28
+ const cell = ws[Excel.utils.encode_cell({ r: 0, c: C })]
29
+ if (cell) {
30
+ cell.s = {
31
+ font: {
32
+ bold: true
33
+ }
34
+ }
35
+ }
36
+ }
37
+
38
+ const wb = Excel.utils.book_new()
39
+ Excel.utils.book_append_sheet(wb, ws, 'Hoja1')
40
+ const excelBuffer = Excel.write(wb, { bookType: 'xlsx', type: 'array' })
41
+ const blob = new Blob([excelBuffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
42
+ const fileName = this.GenExcelReportFileName(type)
43
+ if (fileName != null) {
44
+ saveAs(blob, String(fileName))
45
+ } else {
46
+ throw new Error('Invalid report type provided.')
47
+ }
48
+ }
49
+
50
+ /**
51
+ * Generates the file name for the Excel report based on the type.
52
+ * @param {number} type - The type of report.
53
+ * @returns {string | null} The file name for the report, or null if type is invalid.
54
+ */
55
+ GenExcelReportFileName (type) {
56
+ const fileNames = {
57
+ 1: 'report.xlsx'
58
+ }
59
+
60
+ return fileNames[type] ? fileNames[type] : null
61
+ }
62
+ }
@@ -8,6 +8,7 @@ export * from './useManageQueryParams'
8
8
  export * from './useDeliveryTime'
9
9
  export * from './useModules'
10
10
  export * from './getTotalHours'
11
+ export * from './useUpdateMultipleProducts'
11
12
  export * from './useTokenCards'
12
13
  export * from './useSubscriptionValidation'
13
14
  export * from './convertToMilitaryTime'
@@ -15,8 +16,11 @@ export * from './statusOpenStores'
15
16
  export * from './completeSchedules'
16
17
  export * from './useLogout/helpers/BroadcastChannel'
17
18
  export * from './getCardType'
19
+ export * from './useUploadProducts'
20
+ export * from './useAmountInput'
18
21
  export * from './newMessageSubscription'
19
22
  export * from './useGetCookies'
23
+ export * from './generateTemplate'
20
24
  export * from './isTokenExpired'
21
25
  export * from './useCreateDeliveryTime'
22
26
  export * from './addTenMinutes'
@@ -0,0 +1,118 @@
1
+ import { useState } from 'react'
2
+
3
+ const formatCurrency = (
4
+ prefix,
5
+ amountValue,
6
+ number,
7
+ groupSeparator,
8
+ decimalSeparator,
9
+ allowDecimals = false,
10
+ decimalsLimit = 0
11
+ ) => {
12
+ if (isNaN(number)) {
13
+ return prefix + '0'
14
+ }
15
+
16
+ const amountWithoutDecimals = parseInt(number.toString())
17
+ const decimalIdx = amountValue.indexOf(decimalSeparator)
18
+ const notAllowedChars = new RegExp('[^' + decimalSeparator + '\\d]', 'g')
19
+ const decimalsWithSeparator =
20
+ decimalIdx >= 0
21
+ ? amountValue
22
+ .slice(decimalIdx, amountValue.length)
23
+ .replace(notAllowedChars, '')
24
+ .slice(0, decimalsLimit + 1)
25
+ : ''
26
+
27
+ return (
28
+ prefix +
29
+ amountWithoutDecimals
30
+ .toString()
31
+ .replace(/\B(?=(\d{3}){1,5}(?!\d))/g, groupSeparator) +
32
+ decimalsWithSeparator
33
+ )
34
+ }
35
+
36
+ const processInputValue = (input, decimalSeparator) => {
37
+ const decimalRegex = new RegExp('[' + decimalSeparator + ']', 'g')
38
+ const notAllowedChars = new RegExp('[^' + decimalSeparator + '\\d¬]', 'g')
39
+
40
+ return parseFloat(
41
+ input
42
+ .replace(decimalRegex, '¬')
43
+ .replace(notAllowedChars, '')
44
+ .replace('¬', '.')
45
+ )
46
+ }
47
+ /**
48
+ * Truncate excess decimals from a number based on a limit.
49
+ *
50
+ * @param {number} number The number to truncate.
51
+ * @param {number} decimalsLimit The maximum number of decimal places allowed.
52
+ * @returns {number} The number with truncated decimals.
53
+ */
54
+ const truncateDecimals = (number, decimalsLimit) => {
55
+ if (isNaN(number)) {
56
+ return 0;
57
+ }
58
+
59
+ const multiplier = Math.pow(10, decimalsLimit);
60
+ return Math.floor(number * multiplier) / multiplier;
61
+ };
62
+ export const useAmountInput = props => {
63
+ const {
64
+ onChange = () => {},
65
+ prefix = '$',
66
+ groupSeparator = '.',
67
+ decimalSeparator = ',',
68
+ allowDecimals,
69
+ decimalsLimit,
70
+ defaultValue
71
+ } = props
72
+
73
+ const inputVal = defaultValue ?? ''
74
+ const [inputValue, setInputValue] = useState(inputVal)
75
+
76
+ const preProcess = amount => {
77
+ const amountValue = amount.trim()
78
+ const oldInputValue = inputValue
79
+
80
+ if (oldInputValue !== amountValue) {
81
+ const amountFloatValue = processInputValue(amount, decimalSeparator)
82
+ let inputValue = ''
83
+ // This allows for people to use `.` but still input decimals
84
+ const isAboutToIntroduceDecimals =
85
+ oldInputValue + decimalSeparator === amountValue ||
86
+ oldInputValue + '.' === amountValue
87
+ if (allowDecimals === true && isAboutToIntroduceDecimals) {
88
+ inputValue = oldInputValue + decimalSeparator
89
+ } else if (
90
+ (allowDecimals === false || allowDecimals === undefined) &&
91
+ isAboutToIntroduceDecimals
92
+ ) {
93
+ inputValue = oldInputValue
94
+ } else {
95
+ inputValue = formatCurrency(
96
+ prefix,
97
+ amountValue,
98
+ amountFloatValue,
99
+ groupSeparator,
100
+ decimalSeparator,
101
+ allowDecimals,
102
+ decimalsLimit
103
+ )
104
+ }
105
+ console.log(inputValue)
106
+ setInputValue(inputValue)
107
+
108
+ const callbackValue = isNaN(amountFloatValue) ? 0 : amountFloatValue
109
+ if (typeof onChange === 'function') {
110
+ onChange(truncateDecimals(callbackValue, decimalsLimit))
111
+ }
112
+ }
113
+ }
114
+ return {
115
+ inputValue,
116
+ preProcess
117
+ }
118
+ }
@@ -13,15 +13,36 @@ import {
13
13
 
14
14
  export const useGetClients = ({
15
15
  max,
16
+ order = 'DESC',
16
17
  search,
17
18
  sendNotification = () => { }
18
19
  } = {}) => {
19
- const { loading, error, called, data } = useQuery(GET_ALL_CLIENTS, {
20
+ const {
21
+ loading,
22
+ error,
23
+ called,
24
+ data,
25
+ refetch
26
+ } = useQuery(GET_ALL_CLIENTS, {
27
+ onError: () => {
28
+ sendNotification({
29
+ title: 'Error',
30
+ description: 'Algo salió mal',
31
+ backgroundColor: 'error'
32
+ })
33
+ },
20
34
  variables: {
21
- search
35
+ search,
36
+ max: max || 100,
37
+ order
22
38
  }
23
39
  })
24
- return [data?.getAllClients || [], { loading: called ? false : loading, error }]
40
+ return [data?.getAllClients || [], {
41
+ loading: called ? false : loading,
42
+ buttonLoading: loading,
43
+ error,
44
+ refetch
45
+ }]
25
46
  }
26
47
 
27
48
  export const useDeleteClients = ({ sendNotification = () => { } } = {}) => {
@@ -48,7 +69,7 @@ export const useEditClient = ({ sendNotification = () => { } } = {}) => {
48
69
  onCompleted: (data) => {
49
70
  if (data?.editOneClient?.success) {
50
71
  return sendNotification({
51
- title: 'Exito',
72
+ title: 'Éxito',
52
73
  description: data?.editOneClient?.message,
53
74
  backgroundColor: 'success'
54
75
  })
@@ -3,6 +3,20 @@ import { gql } from '@apollo/client'
3
3
  export const CREATE_CLIENTS = gql`
4
4
  mutation createClients ($input: IClients) {
5
5
  createClients(input: $input) {
6
+ success
7
+ message
8
+ errors {
9
+ path
10
+ message
11
+ type
12
+ context {
13
+ limit
14
+ value
15
+ label
16
+ key
17
+ }
18
+ }
19
+ data {
6
20
  cliId
7
21
  idStore
8
22
  idUser
@@ -15,6 +29,7 @@ mutation createClients ($input: IClients) {
15
29
  clientName
16
30
  createAt
17
31
  updateAt
32
+ }
18
33
  }
19
34
  }
20
35
  `
@@ -27,23 +42,44 @@ mutation deleteClient($cliId: ID, $clState: Int!) {
27
42
  }
28
43
  `
29
44
  export const GET_ALL_CLIENTS = gql`
30
- query getAllClients($idStore: ID, $cId: ID, $dId: ID, $ctId: ID, $search: String, $min: Int, $max: Int, $fromDate: DateTime, $toDate: DateTime ) {
31
- getAllClients(idStore: $idStore, cId: $cId, dId: $dId, ctId: $ctId, search: $search, min: $min, max: $max, fromDate: $fromDate, toDate: $toDate) {
32
- cliId
33
- idStore
34
- gender
35
- # idUser
36
- clState
37
- clientNumber
38
- ccClient
39
- clientLastName
40
- clientName
41
- ClientAddress
42
- createAt
43
- updateAt
44
-
45
+ query getAllClients($idStore: ID, $search: String, $min: Int, $max: Int, $fromDate: DateTime, $toDate: DateTime, $page: Int) {
46
+ getAllClients(idStore: $idStore, search: $search, min: $min, max: $max, fromDate: $fromDate, toDate: $toDate, page: $page) {
47
+ success
48
+ message
49
+ data {
50
+
51
+ cliId
52
+ idStore
53
+ gender
54
+ clState
55
+ clientNumber
56
+ ccClient
57
+ clientLastName
58
+
59
+ clientName
60
+ createAt
61
+ updateAt
62
+ }
63
+ pagination {
64
+ totalRecords
65
+ totalPages
66
+ currentPage
67
+ }
68
+ errors {
69
+ path
70
+ message
71
+ type
72
+ context {
73
+ limit
74
+ value
75
+ label
76
+ key
77
+ }
78
+ }
45
79
  }
46
80
  }
81
+
82
+
47
83
  `
48
84
  export const GET_ONE_CLIENT = gql`
49
85
  query getOneClients($cliId: ID) {
@@ -202,12 +202,12 @@ export const useDessertWithPrice = ({
202
202
 
203
203
  const prepareAndValidateData = useCallback((pId) => {
204
204
  const dataArr = LineItems?.Lines?.map(({ extraPrice, exState, extraName }) => ({
205
- extraPrice: parseFloat(extraPrice),
205
+ extraPrice,
206
206
  exState: exState === true ? 1 : 0,
207
207
  extraName,
208
208
  pId
209
209
  }))
210
-
210
+ console.log(dataArr)
211
211
  const message = 'Complete los campos vacíos'
212
212
  const findInputEmpty = dataArr?.find(({ extraName }) => extraName === '')
213
213
  const findInputEmptyPrice = dataArr?.find(({ extraPrice }) => isNaN(extraPrice) || extraPrice === '')
@@ -291,7 +291,7 @@ export const useDessertWithPrice = ({
291
291
  // Luego, transformar los elementos filtrados
292
292
  return filteredItems.map(({ exPid, extraPrice, exState, extraName }) => ({
293
293
  exPid,
294
- extraPrice: stringToInt(extraPrice), // Asumiendo que tienes una función stringToInt definida
294
+ extraPrice,
295
295
  exState: exState === true ? 1 : 0,
296
296
  extraName,
297
297
  pId
@@ -0,0 +1,54 @@
1
+ import { useMutation } from '@apollo/client'
2
+ import { UPDATE_MULTIPLE_PRODUCTS } from './queries'
3
+ import { CATEGORY_EMPTY, RandomCode } from '../../utils/index'
4
+ import { useCategoriesProduct } from '../useCategoriesProduct'
5
+
6
+ export const useUpdateMultipleProducts = ({
7
+ sendNotification = () => { }
8
+ }) => {
9
+ const [updateMultipleProducts, { data, loading, error }] = useMutation(UPDATE_MULTIPLE_PRODUCTS)
10
+ const [dataCategoriesProducts] = useCategoriesProduct()
11
+ const findEmptyCategory = dataCategoriesProducts?.find(category => category.pName === CATEGORY_EMPTY)
12
+ const updateProducts = async (products) => {
13
+ const newProducts = products.map(product => {
14
+ const code = RandomCode(9)
15
+ return {
16
+ idStore: '',
17
+ ProPrice: product.PRECIO_AL_PUBLICO,
18
+ ProDescuento: 0,
19
+ ValueDelivery: 0,
20
+ ProDescription: product.DESCRIPCION,
21
+ pName: product.NOMBRE,
22
+ pCode: code,
23
+ carProId: findEmptyCategory?.carProId ?? null,
24
+ pState: 1,
25
+ sTateLogistic: 1,
26
+ ProStar: 0,
27
+ ProImage: 'https:http://localhost:8080',
28
+ ProHeight: null,
29
+ ProWeight: '',
30
+ ProOutstanding: 0,
31
+ ProDelivery: 0
32
+ }
33
+ }
34
+ )
35
+ try {
36
+ const response = await updateMultipleProducts({ variables: { input: newProducts } })
37
+ return response.data.updateMultipleProducts
38
+ } catch (e) {
39
+ sendNotification({
40
+ backgroundColor: 'error',
41
+ description: 'Ocurrió un error al actualizar los productos',
42
+ title: 'Error'
43
+ })
44
+ return []
45
+ }
46
+ }
47
+
48
+ return {
49
+ updateProducts,
50
+ data,
51
+ loading,
52
+ error
53
+ }
54
+ }
@@ -0,0 +1,51 @@
1
+ import { gql } from '@apollo/client'
2
+
3
+ export const UPDATE_MULTIPLE_PRODUCTS = gql`
4
+ mutation updateMultipleProducts($input: [InputProductFood]) {
5
+ updateMultipleProducts(input: $input) {
6
+ success
7
+ message
8
+ errors {
9
+ path
10
+ message
11
+ type
12
+ context {
13
+ limit
14
+ value
15
+ label
16
+ key
17
+ }
18
+ }
19
+ data {
20
+ pId
21
+ sizeId
22
+ colorId
23
+ cId
24
+ dId
25
+ ctId
26
+ fId
27
+ pName
28
+ pCode
29
+ ProPrice
30
+ carProId
31
+ ProDescuento
32
+ ProUniDisponibles
33
+ ValueDelivery
34
+ ProDescription
35
+ ProProtegido
36
+ ProAssurance
37
+ ProStar
38
+ pState
39
+ ProImage
40
+ ProWidth
41
+ ProHeight
42
+ ProLength
43
+ ProWeight
44
+ ProQuantity
45
+ ProOutstanding
46
+ ProDelivery
47
+ ProVoltaje
48
+ }
49
+ }
50
+ }
51
+ `;
@@ -0,0 +1,43 @@
1
+ import { useState } from 'react'
2
+ import * as XLSX from 'xlsx'
3
+
4
+ export const useUploadProducts = () => {
5
+ const [data, setData] = useState([])
6
+
7
+ const [active, setActive] = useState(0)
8
+ const [overActive, setOverActive] = useState(0)
9
+
10
+ const handleOverActive = (index) => {
11
+ setOverActive(index)
12
+ }
13
+ const readExcelFile = (file) => {
14
+ return new Promise((resolve, reject) => {
15
+ const reader = new FileReader()
16
+ reader.onload = (e) => {
17
+ const data = new Uint8Array(e.target.result)
18
+ const workbook = XLSX.read(data, { type: 'array' })
19
+ const sheetName = workbook.SheetNames[0]
20
+ const worksheet = workbook.Sheets[sheetName]
21
+ const json = XLSX.utils.sheet_to_json(worksheet)
22
+ resolve(json)
23
+ }
24
+ reader.onerror = (error) => reject(error)
25
+ reader.readAsArrayBuffer(file)
26
+ })
27
+ }
28
+
29
+ const onChangeFiles = async (files) => {
30
+ const filePromises = Array.from(files).map(file => readExcelFile(file))
31
+ const data = await Promise.all(filePromises)
32
+ setData(data.flat())
33
+ }
34
+
35
+ return {
36
+ active,
37
+ data,
38
+ overActive,
39
+ handleOverActive,
40
+ onChangeFiles,
41
+ setActive
42
+ }
43
+ }
@@ -208,3 +208,5 @@ export const paymentMethodCards = [
208
208
  icon: 'IconMasterCard'
209
209
  }
210
210
  ]
211
+
212
+ export const CATEGORY_EMPTY = 'NINGUNO'