npm-pkg-hook 1.5.4 → 1.5.5

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.5.4"
46
+ "version": "1.5.5"
47
47
  }
@@ -5,6 +5,7 @@ export * from './useCategoryInStore'
5
5
  export * from './useCategoryStore'
6
6
  export * from './useCatWithProduct'
7
7
  export * from './useManageQueryParams'
8
+ export * from './statusOpenStores'
8
9
  export * from './useCategoriesProduct'
9
10
  export * from './useLogout'
10
11
  export * from './useStatusOpenStore'
@@ -0,0 +1,101 @@
1
+ export const getDayFromOpeningKey = (key) => {
2
+ const days = {
3
+ openingSun: 0,
4
+ openingMon: 1,
5
+ openingTue: 2,
6
+ openingWed: 3,
7
+ openingThu: 4,
8
+ openingFri: 5,
9
+ openingSat: 6
10
+ }
11
+ return days[key] !== undefined ? days[key] : -1
12
+ }
13
+
14
+ // Función para convertir el objeto de tiempo en una cadena de tiempo
15
+ export function getTimeString (timeStr) {
16
+ return timeStr || '00:00' // Return '00:00' for empty time strings
17
+ }
18
+
19
+ export function getCurrentDayAndTime () {
20
+ try {
21
+ const date = new Date()
22
+ const currentTime = date.getHours() * 60 + date.getMinutes()
23
+ const currentDayOfWeek = date.getDay()
24
+ return { currentTime, currentDayOfWeek }
25
+ } catch (error) {
26
+ return {
27
+
28
+ }
29
+ }
30
+ }
31
+
32
+ export function getTimeObject (timeStr) {
33
+ try {
34
+ if (!timeStr || !/\d{2}:\d{2}/.test(timeStr)) {
35
+ return { hours: 0, minutes: 0 } // Return default values for invalid input
36
+ }
37
+ const [hours, minutes] = timeStr.split(':').map(str => parseInt(str))
38
+ return { hours, minutes }
39
+ } catch (e) {
40
+ return { hours: 0, minutes: 0 } // Return default values on error
41
+ }
42
+ }
43
+
44
+ export function sortOpeningsByDay (openings) {
45
+ const days = [
46
+ 'openingSun',
47
+ 'openingMon',
48
+ 'openingTue',
49
+ 'openingWed',
50
+ 'openingThu',
51
+ 'openingFri',
52
+ 'openingSat'
53
+ ]
54
+ const sortedOpenings = {}
55
+
56
+ days.forEach((day) => {
57
+ sortedOpenings[day] = openings[day] || '00:00 - 00:00' // Agregar horario vacío para los días faltantes
58
+ })
59
+
60
+ return sortedOpenings
61
+ }
62
+
63
+ // Función para obtener la clave de openings a partir del día de la semana
64
+ export function getOpeningKeyFromDay (day) {
65
+ const days = {
66
+ 0: 'openingSun',
67
+ 1: 'openingMon',
68
+ 2: 'openingTue',
69
+ 3: 'openingWed',
70
+ 4: 'openingThu',
71
+ 5: 'openingFri',
72
+ 6: 'openingSat'
73
+ }
74
+ return days[day]
75
+ }
76
+
77
+ export const weekDays = [
78
+ 'Domingo',
79
+ 'Lunes',
80
+ 'Martes',
81
+ 'Miércoles',
82
+ 'Jueves',
83
+ 'Viernes',
84
+ 'Sábado'
85
+ ]
86
+
87
+ export function timeToInt (text) {
88
+ const hour = parseInt(text.substring(0, 2))
89
+ const minute = parseInt(text.substring(3))
90
+ return hour * 60 + minute
91
+ }
92
+
93
+ export const days = {
94
+ Monday: 'Lunes',
95
+ Tuesday: 'Martes',
96
+ Wednesday: 'Miércoles',
97
+ Thursday: 'Jueves',
98
+ Friday: 'Viernes',
99
+ Saturday: 'Sábado',
100
+ Sunday: 'Domingo'
101
+ }
@@ -0,0 +1,155 @@
1
+ import {
2
+ getCurrentDayAndTime,
3
+ getOpeningKeyFromDay,
4
+ getTimeString,
5
+ sortOpeningsByDay,
6
+ weekDays,
7
+ timeToInt,
8
+ days
9
+ } from './helpers'
10
+
11
+ export const statusOpenStores = ({
12
+ dataSchedules = []
13
+ } = {}) => {
14
+ const handleHourPmAM = (hour) => {
15
+ const hourPmAm = new Date(`1/1/1999 ${hour}`).toLocaleString('en-US', { hour: 'numeric', minute: 'numeric', hour12: true })
16
+ return hour ? hourPmAm : ''
17
+ }
18
+
19
+ const handleState = (message, open) => {
20
+ return {
21
+ message,
22
+ open
23
+ }
24
+ }
25
+ function getNextDaySchedule (dataSchedules, currentDayOfWeek) {
26
+ const today = new Date()
27
+ const tomorrow = new Date(today)
28
+ tomorrow.setDate(today.getDate() + 1)
29
+ const dayOfWeekTomorrow = tomorrow.getDay()
30
+
31
+ const findNextDay = dataSchedules?.length
32
+ ? dataSchedules?.some((schedule) => schedule?.schDay === dayOfWeekTomorrow)
33
+ : false
34
+
35
+ const findDataNextDay = dataSchedules?.length
36
+ ? dataSchedules?.find((schedule) => schedule?.schDay === dayOfWeekTomorrow)
37
+ : {}
38
+
39
+ return { findNextDay, findDataNextDay, dayOfWeekTomorrow }
40
+ }
41
+
42
+ function getOpeningStatus (openings, currentTime, currentDayOfWeek) {
43
+ const weekDayLookup = [
44
+ 'Sunday',
45
+ 'Monday',
46
+ 'Tuesday',
47
+ 'Wednesday',
48
+ 'Thursday',
49
+ 'Friday',
50
+ 'Saturday'
51
+ ]
52
+
53
+ const ceroHours = '00:00 - 00:00'
54
+ let dayOfWeek = currentDayOfWeek
55
+
56
+ for (let i = 0; i < 7; i++) {
57
+ const dayName = weekDayLookup[dayOfWeek % 7]
58
+ const opening = openings && openings['opening' + dayName.substring(0, 3)]
59
+ const timeSpans = opening?.split(';').map((item) => item.trim())
60
+
61
+ for (const span of timeSpans) {
62
+ const hours = span.split('-').map((item) => item.trim())
63
+ const openTime = timeToInt(hours[0])
64
+ const closeTime = timeToInt(hours[1])
65
+
66
+ if (currentTime >= openTime && currentTime <= closeTime) {
67
+ return handleState(
68
+ 'Abierto Ahora - Cierra a las: ' + handleHourPmAM(hours[1]),
69
+ true
70
+ )
71
+ }
72
+
73
+ if (currentTime < openTime && dayOfWeek === currentDayOfWeek) {
74
+ return handleState(
75
+ 'Aun temprano - Abre hoy a las: ' + handleHourPmAM(hours[0]),
76
+ false
77
+ )
78
+ }
79
+
80
+ if (currentTime >= closeTime - 30 * 60000 && currentTime < closeTime && dayOfWeek === currentDayOfWeek) {
81
+ return handleState(
82
+ 'Pronto por cerrar - Cierra hoy a las: ' + handleHourPmAM(hours[1]),
83
+ true
84
+ )
85
+ }
86
+
87
+ const { findNextDay, findDataNextDay, dayOfWeekTomorrow } = getNextDaySchedule(
88
+ dataSchedules,
89
+ currentDayOfWeek
90
+ )
91
+
92
+ if (findNextDay && findDataNextDay?.schHoSta) {
93
+ const nameOfDayTomorrow = weekDays[dayOfWeekTomorrow]
94
+ return handleState(
95
+ `Cerrado - Mañana ${nameOfDayTomorrow} ${!!findDataNextDay?.schHoSta && 'a las'} ${
96
+ findDataNextDay?.schHoSta ? findDataNextDay?.schHoSta : ''
97
+ }`,
98
+ false
99
+ )
100
+ }
101
+
102
+ const nextDayName = weekDayLookup[(dayOfWeek + 1) % 7]
103
+ const nextOpening = openings && openings['opening' + nextDayName.substring(0, 3)]
104
+ const nextHours = nextOpening?.split(';')?.map((item) => item?.trim())
105
+
106
+ if (nextHours[0] !== ceroHours) {
107
+ return handleState(
108
+ 'Cerrado - Abre el ' + days[nextDayName] + ' a las ' + nextHours[0],
109
+ false
110
+ )
111
+ }
112
+ }
113
+
114
+ dayOfWeek++
115
+ }
116
+
117
+ return handleState('Cerrado', false)
118
+ }
119
+
120
+ function getIsOpening (openings) {
121
+ const { currentTime, currentDayOfWeek } = getCurrentDayAndTime()
122
+ return getOpeningStatus(openings, currentTime, currentDayOfWeek)
123
+ }
124
+
125
+ const createOpeningsObject = (dataSchedules) => {
126
+ const openings = {}
127
+ const existStoreSchedule = dataSchedules || []
128
+
129
+ existStoreSchedule?.forEach((schedule) => {
130
+ const day = schedule.schDay
131
+ const openingKey = getOpeningKeyFromDay(day)
132
+ const schHoSta = getTimeString(schedule?.schHoSta)
133
+ const schHoEnd = getTimeString(schedule?.schHoEnd)
134
+ openings[openingKey] = `${schHoSta} - ${schHoEnd}`
135
+ })
136
+
137
+ for (let i = 0; i < 7; i++) {
138
+ const openingKey = getOpeningKeyFromDay(i)
139
+ // eslint-disable-next-line no-prototype-builtins
140
+ if (!(openingKey in openings)) {
141
+ openings[openingKey] = '00:00 - 00:00' // Horario vacío para el día faltante
142
+ }
143
+ }
144
+
145
+ return openings
146
+ }
147
+
148
+ // Luego puedes usar esta función así:
149
+ const openings = createOpeningsObject(dataSchedules)
150
+ // ...haz lo que necesites con el objeto openings
151
+ const sortedOpenings = sortOpeningsByDay(openings)
152
+
153
+ // Crear el array completo con objetos de tiempo
154
+ return getIsOpening(sortedOpenings)
155
+ }
@@ -8,6 +8,7 @@ import { DELETE_ONE_ITEM_SHOPPING_PRODUCT } from './queries'
8
8
  import { useCart, useGetCart } from '../useCart'
9
9
  import { useManageQueryParams } from '../useManageQueryParams'
10
10
  import { calculateTotalPrice } from './helpers'
11
+ import { statusOpenStores } from '../statusOpenStores'
11
12
  export * from './helpers'
12
13
 
13
14
  /**
@@ -21,12 +22,13 @@ export * from './helpers'
21
22
  export const useAsideCart = ({
22
23
  openModalProduct = false,
23
24
  location = {},
24
- setCountItemProduct = () => { },
25
+ setCountItemProduct = (number) => { return number },
25
26
  setAlertBox = () => { },
26
27
  setOpenModalProduct = () => { },
27
28
  handleMenu = () => { }
28
- } = {}) => {
29
+ } = {
29
30
 
31
+ }) => {
30
32
  const { getOneProduct } = useCart({
31
33
  handleMenu,
32
34
  openModalProduct,
@@ -134,11 +136,58 @@ export const useAsideCart = ({
134
136
  * @returns {number} The calculated total price.
135
137
  */
136
138
  const sumProduct = (ProPrice, ProDelivery, cant) => {
139
+ // Convertir a números, con manejo de posibles errores
137
140
  const price = parseInt(ProPrice)
138
- const priceFinal = cant * price
139
141
  const delivery = parseInt(ProDelivery || 0)
142
+ const quantity = parseInt(cant)
143
+
144
+ // Verificar si las conversiones fueron exitosas
145
+ if (isNaN(price) || isNaN(delivery) || isNaN(quantity)) {
146
+ throw new Error('Los valores proporcionados no son números válidos.')
147
+ }
148
+
149
+ // Calcular el precio final
150
+ const priceFinal = quantity * price
151
+
152
+ // Devolver la suma total, incluyendo el costo de entrega si es aplicable
140
153
  return delivery ? priceFinal + delivery : priceFinal
141
154
  }
155
+ console.log(dataShoppingCard)
156
+
157
+ /**
158
+ * Verifica el estado de apertura de la tienda.
159
+ *
160
+ * @returns {Object|null} Objeto con el estado de apertura de la tienda o null en caso de error.
161
+ * @throws {Error} Si ocurre un error durante la verificación del estado de la tienda.
162
+ */
163
+ const handleVerifyStoreOpenStatus = () => {
164
+ /**
165
+ * @type {Array} dataShoppingCard - El array de la tarjeta de compras.
166
+ */
167
+ if (!Array.isArray(dataShoppingCard)) {
168
+ return { open: false } // Retorna un objeto indicando que la tienda no está abierta
169
+ }
170
+
171
+ /**
172
+ * @type {Object} store - La primera tienda en el array de la tarjeta de compras.
173
+ */
174
+ const store = dataShoppingCard[0] || {}
175
+ /**
176
+ * @type {Object} getStore - El objeto que contiene información de la tienda.
177
+ */
178
+ const { getStore } = store
179
+
180
+ /**
181
+ * @type {Array} storeSchedules - El array de horarios de la tienda.
182
+ */
183
+ const storeSchedules = Array.isArray(getStore?.getStoreSchedules) ? getStore?.getStoreSchedules : []
184
+ try {
185
+ const status = getStore?.scheduleOpenAll ? { open: true } : statusOpenStores({ dataSchedules: storeSchedules })
186
+ return status
187
+ } catch (error) {
188
+ return null
189
+ }
190
+ }
142
191
 
143
192
  return {
144
193
  key,
@@ -147,6 +196,7 @@ export const useAsideCart = ({
147
196
  dataShoppingCard,
148
197
  handleDeleteItemShopping,
149
198
  handleEditProduct,
199
+ handleVerifyStoreOpenStatus,
150
200
  sumProduct
151
201
  }
152
202
  }
@@ -1,4 +1,4 @@
1
- import { gql } from '@apollo/client';
1
+ import { gql } from '@apollo/client'
2
2
 
3
3
  export const CREATE_SHOPPING_CARD = gql`
4
4
  mutation registerShoppingCard(
@@ -109,9 +109,19 @@ export const GET_ALL_SHOPPING_CARD = gql`
109
109
  getStore {
110
110
  idStore
111
111
  cId
112
+ scheduleOpenAll
113
+ getStoreSchedules {
114
+ schId
115
+ idStore
116
+ schDay
117
+ schHoSta
118
+ schHoEnd
119
+ schState
120
+ }
112
121
  id
113
122
  dId
114
123
  ctId
124
+ scheduleOpenAll
115
125
  catStore
116
126
  neighborhoodStore
117
127
  Viaprincipal
@@ -2,8 +2,10 @@ import { GET_ALL_SHOPPING_CARD } from '../queries'
2
2
  import { useQuery } from '@apollo/client'
3
3
 
4
4
  export const useGetCart = ({
5
- setAlertBox = () => { },
6
- setCountItemProduct = () => { }
5
+ setAlertBox = ({
6
+ message
7
+ }) => { return { message } },
8
+ setCountItemProduct = (number) => { return number }
7
9
  } = {}) => {
8
10
  const {
9
11
  data,
@@ -1,5 +1,7 @@
1
1
  import { useQuery } from '@apollo/client'
2
2
  import { GET_ALL_FAV_STORE } from './queries'
3
+ import { filterAndSortByDate } from '../useRestaurant/helpers'
4
+ import { getStatusForStores } from '../useRestaurant/helpers/manageStatusOpen'
3
5
 
4
6
  export const useFavoriteStores = () => {
5
7
  const {
@@ -12,8 +14,16 @@ export const useFavoriteStores = () => {
12
14
  console.log('')
13
15
  }
14
16
  })
17
+ const newArray = data?.getFavorite?.map(store => {
18
+ return {
19
+ ...store.getOneStore
20
+ }
21
+ }) || []
22
+ const dataSort = filterAndSortByDate(newArray)
23
+
24
+ const statuses = getStatusForStores(dataSort)
15
25
 
16
- const favoriteStores = data?.getFavorite || []
26
+ const favoriteStores = statuses || []
17
27
 
18
- return [favoriteStores, { loading, error }]
28
+ return [loading ? [] : favoriteStores, { loading, error }]
19
29
  }
@@ -1,47 +1,53 @@
1
1
  import { gql } from '@apollo/client'
2
2
 
3
3
  export const GET_ALL_FAV_STORE = gql`
4
- query getFavorite{
5
- getFavorite{
6
- fIStoreId
7
- fState
8
- createAt
9
- updateAt
10
- idStore
11
-
12
- getOneStore {
4
+ query getFavorite {
5
+ getFavorite {
6
+ fIStoreId
7
+ fState
8
+ createAt
9
+ updateAt
13
10
  idStore
14
- cId
15
- id
16
- Image
17
- open
18
- cateStore{
19
- catStore
20
- cName
21
-
22
- }
23
- ctId
24
- catStore
25
- dId
26
- storeName
27
- Image
28
- city{
11
+
12
+ getOneStore {
13
+ getStoreSchedules {
14
+ schId
15
+ idStore
16
+ schDay
17
+ schHoSta
18
+ schHoEnd
19
+ schState
20
+ }
21
+ scheduleOpenAll
22
+ idStore
23
+ cId
24
+ id
25
+ Image
26
+ open
27
+ cateStore {
28
+ catStore
29
+ cName
30
+ }
29
31
  ctId
32
+ catStore
30
33
  dId
31
- cName
32
- }
33
- department {
34
- dId
35
- cId
36
- dName
37
-
38
- }
39
- pais {
40
- cId
41
- cName
42
-
34
+ storeName
35
+ Image
36
+ city {
37
+ ctId
38
+ dId
39
+ cName
40
+ }
41
+ department {
42
+ dId
43
+ cId
44
+ dName
45
+ }
46
+ pais {
47
+ cId
48
+ cName
49
+ }
43
50
  }
44
51
  }
45
52
  }
46
- }
47
- `
53
+ `
@@ -4,21 +4,16 @@ export function filterAndSortByDate (array = []) {
4
4
  if (isError) return []
5
5
 
6
6
  const currentDate = new Date()
7
- const sevenDaysAgo = currentDate.getTime() - 7 * 24 * 60 * 60 * 1000 // Calculating timestamp for 7 days ago
7
+ const sevenDaysAgo = currentDate.getTime() - 7 * 24 * 60 * 60 * 1000
8
8
 
9
9
  const filteredAndSorted = array.map(item => {
10
10
  const createdAtDate = new Date(item.createdAt)
11
- const isNew = createdAtDate.getTime() >= sevenDaysAgo
11
+ const isNew = (createdAtDate.getTime() <= sevenDaysAgo)
12
12
  return { ...item, isNew }
13
13
  }).sort((a, b) => {
14
- // Ordenar primero por 'open' en 1 y luego por 'createdAt'
15
- if (a.open !== b.open) {
16
- return b.open - a.open // Orden descendente para 'open' en 1 primero
17
- } else {
18
- const dateA = new Date(a.createdAt).getTime()
19
- const dateB = new Date(b.createdAt).getTime()
20
- return dateA - dateB
21
- }
14
+ const dateA = new Date(a.createdAt).getTime()
15
+ const dateB = new Date(b.createdAt).getTime()
16
+ return dateB - dateA
22
17
  })
23
18
 
24
19
  return filteredAndSorted
@@ -0,0 +1,21 @@
1
+ import { statusOpenStores } from '../../statusOpenStores'
2
+
3
+ export const getStatusForStores = (stores = []) => {
4
+ return stores.map((store) => {
5
+ if (store?.scheduleOpenAll) {
6
+ return {
7
+ ...store,
8
+ status: { message: '', open: true },
9
+ open: 1
10
+ }
11
+ }
12
+ const dataSchedules =
13
+ (store?.getStoreSchedules?.length > 0 && store.getStoreSchedules) || []
14
+ const status = statusOpenStores({ dataSchedules })
15
+ return {
16
+ ...store,
17
+ status,
18
+ open: status?.open ? 1 : 0
19
+ }
20
+ }).sort((a, b) => b.open - a.open)
21
+ }
@@ -3,10 +3,14 @@ import { useLazyQuery } from '@apollo/client'
3
3
  import { GET_ALL_RESTAURANT } from './queries'
4
4
  import { filterAndSortByDate } from './helpers'
5
5
  import { useManageQueryParams } from '../useManageQueryParams'
6
+ import { getStatusForStores } from './helpers/manageStatusOpen'
6
7
 
7
8
  export const useRestaurant = ({
8
9
  location = {
9
- pathname: ''
10
+ query: {},
11
+ push: (props, state, { shallow }) => {
12
+ return { ...props, state, shallow }
13
+ }
10
14
  }
11
15
  } = {}) => {
12
16
  const [loadingFilter, setLoadingFilter] = useState(false)
@@ -40,7 +44,7 @@ export const useRestaurant = ({
40
44
  const handleFilterStore = async () => {
41
45
  setLoadingFilter(true)
42
46
  try {
43
- getAllStoreInStore({
47
+ await getAllStoreInStore({
44
48
 
45
49
  }).then(() => {
46
50
  setLoadingFilter(false)
@@ -51,7 +55,9 @@ export const useRestaurant = ({
51
55
  }
52
56
  const dataRestaurant = data?.getAllStoreInStore || []
53
57
  const dataSort = filterAndSortByDate(dataRestaurant)
54
- return [dataSort, {
58
+ const statuses = getStatusForStores(dataSort)
59
+
60
+ return [statuses, {
55
61
  loading,
56
62
  loadingFilter,
57
63
  error,
@@ -3,6 +3,7 @@ export const GET_ALL_RESTAURANT = gql`
3
3
  query getAllStoreInStore($search: String, $min: Int, $max: Int){
4
4
  getAllStoreInStore(search: $search, min: $min, max: $max) {
5
5
  open
6
+ scheduleOpenAll
6
7
  getStoreSchedules {
7
8
  idStore
8
9
  schId
@@ -15,7 +15,9 @@ import { useFormatDate } from '../useFormatDate'
15
15
  export const useStatusOpenStore = ({ dataSchedules = [] } = {}) => {
16
16
  const [open, setOpen] = useState('')
17
17
  const [openNow, setOpenNow] = useState(false)
18
- const { handleHourPmAM } = useFormatDate({})
18
+ const { handleHourPmAM } = useFormatDate({
19
+ date: null
20
+ })
19
21
 
20
22
  const handleMessageHour = (message, open) => {
21
23
  setOpen(message)
@@ -3,6 +3,7 @@ import { useApolloClient, useQuery } from '@apollo/client'
3
3
  import { GET_ONE_STORE, GET_ONE_STORE_BY_ID } from './queries' // Reemplaza con la importación correcta de tu consulta
4
4
  import { errorHandler } from '../../config/client'
5
5
  import { useLogout } from '../useLogout'
6
+
6
7
  export const useStore = ({ isClient = false, idStore = '' } = {}) => {
7
8
  const client = useApolloClient()
8
9
  const [onClickLogout, { loading: load }] = useLogout()