npm-pkg-hook 1.4.1 → 1.4.2

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.1"
46
+ "version": "1.4.2"
47
47
  }
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Generate the store URL based on given parameters
3
+ * @param {Object} city - The city object with name
4
+ * @param {Object} department - The department object with name
5
+ * @param {string} storeName - The name of the store
6
+ * @param {string} idStore - The ID of the store
7
+ * @returns {string} - The generated URL or null if any field is missing
8
+ */
9
+ export const generateStoreURL = ({ city, department, storeName, idStore }) => {
10
+ try {
11
+ // Validate all necessary fields
12
+ if (
13
+ !process.env.MAIN_URL_BASE ||
14
+ !city?.cName ||
15
+ !department?.dName ||
16
+ !storeName ||
17
+ !idStore
18
+ ) {
19
+ return null // Return null or any default case you'd prefer
20
+ }
21
+
22
+ const cityName = city.cName.toLocaleLowerCase()
23
+ const departmentName = department.dName.toLocaleLowerCase()
24
+
25
+ // Replace spaces in storeName with hyphens
26
+ const formattedStoreName = storeName.replace(/\s+/g, '-')
27
+
28
+ return `${process.env.MAIN_URL_BASE}/delivery/${cityName}-${departmentName}/${formattedStoreName}/${idStore}`
29
+ } catch (_) {
30
+ return null
31
+ }
32
+ }
@@ -10,9 +10,11 @@ export * from './useLogout'
10
10
  export * from './useStatusOpenStore'
11
11
  export * from './useScheduleData'
12
12
  export * from './useOrders'
13
+ export * from './usePushNotifications'
13
14
  export * from './useLocationManager'
14
15
  export * from './useFingerprintjs'
15
16
  export * from './useCountries'
17
+ export * from './generateStoreURL'
16
18
  export * from './useCreateStorePendingToRegister'
17
19
  export * from './useDepartments'
18
20
  export * from './useRoads'
@@ -14,7 +14,7 @@ export const verifyPriceInRange = ({ values = [], sendNotification }) => {
14
14
  sendNotification({
15
15
  backgroundColor: 'warning',
16
16
  title: 'Alerta',
17
- description: 'El valor del producto es muy elevado'
17
+ description: 'El valor es muy elevado'
18
18
  })
19
19
  return false
20
20
  }
@@ -0,0 +1,114 @@
1
+ /* eslint-disable consistent-return */
2
+ const pushServerPublicKey = 'BIN2Jc5Vmkmy-S3AUrcMlpKxJpLeVRAfu9WBqUbJ70SJOCWGCGXKY-Xzyh7HDr6KbRDGYHjqZ06OcS3BjD7uAm8'
3
+
4
+ /**
5
+ * checks if Push notification and service workers are supported by your browser
6
+ */
7
+ function isPushNotificationSupported () {
8
+ if (typeof window !== 'undefined' && window.Notification && window.ServiceWorker) {
9
+ return 'serviceWorker' in navigator && 'PushManager' in window
10
+ }
11
+ }
12
+
13
+ /**
14
+ * asks user consent to receive push notifications and returns the response of the user, one of granted, default, denied
15
+ */
16
+ async function askUserPermission () {
17
+ return await Notification.requestPermission()
18
+ }
19
+ /**
20
+ * shows a notification
21
+ */
22
+ function sendNotification () {
23
+ const img = '/images/jason-leung-HM6TMmevbZQ-unsplash.jpg'
24
+ const text = 'Take a look at this brand new t-shirt!'
25
+ const title = 'New Product Available'
26
+ const options = {
27
+ body: text,
28
+ icon: '/images/jason-leung-HM6TMmevbZQ-unsplash.jpg',
29
+ vibrate: [200, 100, 200],
30
+ tag: 'new-product',
31
+ image: img,
32
+ badge: 'https://spyna.it/icons/android-icon-192x192.png',
33
+ actions: [{ action: 'Detail', title: 'View', icon: 'https://via.placeholder.com/128/ff0000' }]
34
+ }
35
+ navigator.serviceWorker.ready.then(function (serviceWorker) {
36
+ serviceWorker.showNotification(title, options)
37
+ })
38
+ }
39
+
40
+ /**
41
+ *
42
+ */
43
+ function registerServiceWorker () {
44
+ return navigator.serviceWorker.register('/sw.js')
45
+ }
46
+
47
+ /**
48
+ *
49
+ * using the registered service worker creates a push notification subscription and returns it
50
+ *
51
+ */
52
+ async function createNotificationSubscription () {
53
+ // wait for service worker installation to be ready
54
+ const serviceWorker = await navigator.serviceWorker.ready
55
+ // subscribe and return the subscription
56
+ return await serviceWorker.pushManager.subscribe({
57
+ userVisibleOnly: true,
58
+ applicationServerKey: pushServerPublicKey
59
+ })
60
+ }
61
+
62
+ /**
63
+ * returns the subscription if present or nothing
64
+ */
65
+ function getUserSubscription () {
66
+ // wait for service worker installation to be ready, and then
67
+ return navigator.serviceWorker.ready
68
+ .then(function (serviceWorker) {
69
+ return serviceWorker.pushManager.getSubscription()
70
+ })
71
+ .then(function (pushSubscription) {
72
+ return pushSubscription
73
+ })
74
+ }
75
+
76
+ const host = process.env.NODE_ENV === 'production' ? 'http://localhost:4000' : 'http://localhost:4000'
77
+
78
+ function post (path, body) {
79
+ return fetch(`${host}${path}`, {
80
+ body: JSON.stringify(body),
81
+ method: 'POST',
82
+ mode: 'cors'
83
+ })
84
+ .then(function (response) {
85
+ return response.json()
86
+ })
87
+ .then(function (data) {
88
+ return data
89
+ })
90
+ }
91
+
92
+ function get (path) {
93
+ return fetch(`${host}${path}`, {
94
+ method: 'GET',
95
+ mode: 'cors'
96
+ })
97
+ .then(function (response) {
98
+ return response.json()
99
+ })
100
+ .then(function (data) {
101
+ return data
102
+ })
103
+ }
104
+
105
+ export {
106
+ isPushNotificationSupported,
107
+ askUserPermission,
108
+ post,
109
+ get,
110
+ registerServiceWorker,
111
+ sendNotification,
112
+ createNotificationSubscription,
113
+ getUserSubscription
114
+ }
@@ -0,0 +1,149 @@
1
+ /* eslint-disable no-console */
2
+ import { useState, useEffect } from 'react'
3
+ import {
4
+ isPushNotificationSupported,
5
+ post,
6
+ get,
7
+ askUserPermission,
8
+ registerServiceWorker,
9
+ createNotificationSubscription,
10
+ getUserSubscription
11
+ } from './helpers'
12
+ // import all the function created to manage the push notifications
13
+
14
+ const pushNotificationSupported = isPushNotificationSupported()
15
+ // first thing to do: check if the push notifications are supported by the browser
16
+
17
+ export const usePushNotifications = () => {
18
+ const [userConsent, setSuserConsent] = useState()
19
+ useEffect(() => {
20
+ if (typeof Notification !== 'undefined') {
21
+ setSuserConsent(Notification.permission)
22
+ }
23
+ }, [])
24
+
25
+ // to manage the user consent: Notification.permission is a JavaScript native function that return the current state of the permission
26
+ // We initialize the userConsent with that value
27
+ const [userSubscription, setUserSubscription] = useState(null)
28
+ // to manage the use push notification subscription
29
+ const [pushServerSubscriptionId, setPushServerSubscriptionId] = useState()
30
+ // to manage the push server subscription
31
+ const [error, setError] = useState(null)
32
+ // to manage errors
33
+ const [loading, setLoading] = useState(true)
34
+ // to manage async actions
35
+
36
+ useEffect(() => {
37
+ if (pushNotificationSupported) {
38
+ setLoading(true)
39
+ setError(false)
40
+ registerServiceWorker().then(() => {
41
+ setLoading(false)
42
+ })
43
+ }
44
+ }, [])
45
+ // if the push notifications are supported, registers the service worker
46
+ // this effect runs only the first render
47
+
48
+ useEffect(() => {
49
+ setLoading(true)
50
+ setError(false)
51
+ const getExixtingSubscription = async () => {
52
+ const existingSubscription = await getUserSubscription()
53
+ setUserSubscription(existingSubscription)
54
+ setLoading(false)
55
+ }
56
+ getExixtingSubscription()
57
+ }, [])
58
+ // Retrieve if there is any push notification subscription for the registered service worker
59
+ // this use effect runs only in the first render
60
+
61
+ /**
62
+ * define a click handler that asks the user permission,
63
+ * it uses the setSuserConsent state, to set the consent of the user
64
+ * If the user denies the consent, an error is created with the setError hook
65
+ */
66
+ const onClickAskUserPermission = () => {
67
+ setLoading(true)
68
+ setError(false)
69
+ askUserPermission().then(consent => {
70
+ setSuserConsent(consent)
71
+ if (consent !== 'granted') {
72
+ setError({
73
+ name: 'consentimiento denegado',
74
+ message: 'Negaste el consentimiento para recibir notificaciones',
75
+ code: 0
76
+ })
77
+ }
78
+ setLoading(false)
79
+ })
80
+ }
81
+ //
82
+
83
+ /**
84
+ * define a click handler that creates a push notification subscription.
85
+ * Once the subscription is created, it uses the setUserSubscription hook
86
+ */
87
+ const onClickSusbribeToPushNotification = () => {
88
+ setLoading(true)
89
+ setError(false)
90
+ createNotificationSubscription()
91
+ .then(function (subscrition) {
92
+ setUserSubscription(subscrition)
93
+ setLoading(false)
94
+ })
95
+ .catch(err => {
96
+ console.error("Couldn't create the notification subscription", err, 'name:', err.name, 'message:', err.message, 'code:', err.code)
97
+ setError(err)
98
+ setLoading(false)
99
+ })
100
+ }
101
+
102
+ /**
103
+ * define a click handler that sends the push susbcribtion to the push server.
104
+ * Once the subscription ics created on the server, it saves the id using the hook setPushServerSubscriptionId
105
+ */
106
+ const onClickSendSubscriptionToPushServer = () => {
107
+ setLoading(true)
108
+ setError(false)
109
+ post('/subscription2', userSubscription)
110
+ .then(function (response) {
111
+ setPushServerSubscriptionId(response.id)
112
+ setLoading(false)
113
+ })
114
+ .catch(err => {
115
+ setLoading(false)
116
+ setError(err)
117
+ })
118
+ }
119
+
120
+ /**
121
+ * define a click handler that request the push server to send a notification, passing the id of the saved subscription
122
+ */
123
+ const onClickSendNotification = async () => {
124
+ setLoading(true)
125
+ setError(false)
126
+ console.log(pushServerSubscriptionId)
127
+ await get(`/subscription/${pushServerSubscriptionId}`).catch(err => {
128
+ setLoading(false)
129
+ setError(err)
130
+ })
131
+ setLoading(false)
132
+ }
133
+
134
+ /**
135
+ * returns all the stuff needed by a Component
136
+ */
137
+ return {
138
+ onClickAskUserPermission,
139
+ onClickSusbribeToPushNotification,
140
+ onClickSendSubscriptionToPushServer,
141
+ pushServerSubscriptionId,
142
+ onClickSendNotification,
143
+ userConsent,
144
+ pushNotificationSupported,
145
+ userSubscription,
146
+ error,
147
+ loading
148
+ }
149
+ }