test web push
Main daploy / deploy (push) Successful in 45s

This commit is contained in:
2024-11-21 16:11:23 +02:00
parent 14e8a349e6
commit 75be87c144
14 changed files with 438 additions and 63 deletions
@@ -2,45 +2,42 @@
<section>
<h2 class="text-xl font-semibold mb-4">Куда отправлять сообщения?</h2>
<p class="text-gray-600 mb-4">Выберите, как вы хотите получать сообщения.</p>
<div class="flex flex-col gap-3 mb-4">
<div class="flex items-center gap-2" v-for="option in deliveryOptions" :key="option.method">
<RadioButton
v-model="model"
:inputId="option.method"
name="delivery"
:value="option.method"
@change="handleSelection(option.method)"
<CreateMessageDeliveryOptions>
<template #telegram="{ label, method }">
<CreateMessageDeliveryOptionTelegram
:label
:method
v-model="localModel"
@change="onChange"
/>
<label :for="option.method">{{ option.label }}</label>
</div>
</div>
<!-- Сообщение о недоступности -->
<p v-if="telegramNotice" class="text-red-500 mb-2">
Отправка в Telegram пока в разработке.<br />
Этот способ отправки сообщений можно будет выбрать позже.
</p>
</template>
<template #webPush="{ label, method }">
<CreateMessageDeliveryOptionWebPush
:label
:method
v-model="localModel"
@change="onChange"
/>
</template>
<template #default="{ label, method }">
<CreateMessageDeliveryOption :label :method v-model="localModel" @change="onChange" />
</template>
</CreateMessageDeliveryOptions>
</section>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import { type QRCodeDocument } from '@/types/DBDocumentTypes'
import { deliveryOptions } from '@/constants/deliveryOptions'
import CreateMessageDeliveryOptionTelegram from '@/components/create/CreateMessageDeliveryOptionTelegram.vue'
import CreateMessageDeliveryOptionWebPush from '@/components/create/CreateMessageDeliveryOptionWebPush.vue'
import { ref } from 'vue'
const emit = defineEmits(['nextStep'])
const model = defineModel<null | QRCodeDocument['messageDeliveryMethod']>()
const localModel = ref<null | QRCodeDocument['messageDeliveryMethod']>()
// Локальное состояние для уведомления
const telegramNotice = ref(false)
// Обработчик выбора
function handleSelection(method: QRCodeDocument['messageDeliveryMethod']) {
if (method === 'telegram') {
telegramNotice.value = true
} else {
telegramNotice.value = false
emit('nextStep')
}
const onChange = () => {
model.value = localModel.value
emit('nextStep')
}
</script>
@@ -0,0 +1,23 @@
<template>
<div class="flex items-center gap-2">
<RadioButton
v-model="model"
:inputId="method"
name="delivery"
:value="method"
@change="$emit('change', $event)"
/>
<label :for="method">{{ label }}</label>
</div>
</template>
<script setup lang="ts">
import type { QRCodeDocument } from '@/types/DBDocumentTypes'
import type { DeliveryOption } from '@/constants/deliveryOptions'
defineProps<{ label: DeliveryOption['label']; method: DeliveryOption['method'] }>()
defineEmits<{
(e: 'change', value: Event): void
}>()
const model = defineModel<null | QRCodeDocument['messageDeliveryMethod']>()
</script>
@@ -0,0 +1,32 @@
<template>
<CreateMessageDeliveryOption :label :method v-model="model" />
<!-- Сообщение о недоступности -->
<p v-if="telegramNotice" class="text-red-500 mb-2">
Отправка в Telegram пока в разработке.<br />
Этот способ отправки сообщений можно будет выбрать позже.
</p>
</template>
<script setup lang="ts">
import { type QRCodeDocument } from '@/types/DBDocumentTypes'
import { type DeliveryOption, DELIVERY_METHOD_TELEGRAM } from '@/constants/deliveryOptions'
import { computed } from 'vue'
type DeliveryOptionTelegram = Extract<DeliveryOption, { method: typeof DELIVERY_METHOD_TELEGRAM }>
defineProps<{
label: DeliveryOptionTelegram['label']
method: DeliveryOptionTelegram['method']
}>()
defineEmits<{
(e: 'change', value: Event): void
}>()
const model = defineModel<null | QRCodeDocument['messageDeliveryMethod']>()
const telegramNotice = computed(() => {
return model.value! === DELIVERY_METHOD_TELEGRAM
})
</script>
@@ -0,0 +1,100 @@
<template>
<CreateMessageDeliveryOption :label :method v-model="model" @change="handleSelection()" />
<!-- Ошибка разрешений -->
<p v-if="permissionError && model === method" class="text-red-500 mb-2">
Не удалось получить разрешение на отправку уведомлений.<br />
<button @click="retryPushSubscription" class="text-blue-500 underline">Повторить</button>
</p>
</template>
<script setup lang="ts">
import { type QRCodeDocument } from '@/types/DBDocumentTypes'
import { type DeliveryOption, DELIVERY_METHOD_WEB_PUSH } from '@/constants/deliveryOptions'
import { ref } from 'vue'
type DeliveryOptionWebPush = Extract<DeliveryOption, { method: typeof DELIVERY_METHOD_WEB_PUSH }>
defineProps<{
label: DeliveryOptionWebPush['label']
method: DeliveryOptionWebPush['method']
}>()
const emit = defineEmits<{
(e: 'change'): void
}>()
const model = defineModel<null | QRCodeDocument['messageDeliveryMethod']>()
// Локальное состояние для уведомлений и ошибок
const permissionError = ref(false)
// Обработчик выбора
async function handleSelection() {
permissionError.value = false
const permission = await requestNotificationPermission()
if (permission) {
emit('change')
} else {
permissionError.value = true
}
}
// Функция запроса разрешений и подписки
async function requestNotificationPermission(): Promise<boolean> {
if (!('Notification' in window)) {
console.error('Уведомления не поддерживаются этим браузером.')
return false
}
try {
const permission = await Notification.requestPermission()
if (permission !== 'granted') {
console.error('Разрешение на уведомления не предоставлено.')
return false
}
const registration = await navigator.serviceWorker.ready
const subscription = await registration.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey:
'BMPwpR1Q24ZOFxy2T9M-I-Y6F6bucsHFVZKP8QYslgD_4hGCDv16qnZnji-ldngcZ_vBWVBwJ6OIfknVBnCxLsY',
})
console.log('Push-подписка создана:', subscription)
console.log(JSON.stringify(subscription))
// subscription = {
// endpoint:
// 'https://jmt17.google.com/fcm/send/eFYnP7qxt8A:APA91bHYGItzGpnzhXkfKzgMhAXgwcQXaLuRLqq9mt9RPS0VgGpEvVASxW8AF_fJmtSBtK-po0V3mM7fGWSN6tMCrImZqgZG14kGv0chQoghOLuWgHTUQYtQEqhd6f89eVonJdtjAlDN',
// expirationTime: null,
// keys: {
// p256dh:
// 'BAIGLAQ5cZg6e8psnK6vy_MJ1kUJbs2Tymjc38-_6zM1VQXWP2Yj-604uPMye4smHosNKmBEPRDJJOH6Wxr1MLQ',
// auth: '1k48wvT0U3pK_xaXW95Ekw',
// },
// }
// subscription = {
// endpoint:
// 'https://jmt17.google.com/fcm/send/eFYnP7qxt8A:APA91bHYGItzGpnzhXkfKzgMhAXgwcQXaLuRLqq9mt9RPS0VgGpEvVASxW8AF_fJmtSBtK-po0V3mM7fGWSN6tMCrImZqgZG14kGv0chQoghOLuWgHTUQYtQEqhd6f89eVonJdtjAlDN',
// expirationTime: null,
// keys: {
// p256dh:
// 'BAIGLAQ5cZg6e8psnK6vy_MJ1kUJbs2Tymjc38-_6zM1VQXWP2Yj-604uPMye4smHosNKmBEPRDJJOH6Wxr1MLQ',
// auth: '1k48wvT0U3pK_xaXW95Ekw',
// },
// }
// Здесь вы можете сохранить подписку на сервере
return true
} catch (err) {
console.error('Ошибка при создании Push-подписки:', err)
return false
}
}
// Повторный запрос разрешений
function retryPushSubscription() {
permissionError.value = false
handleSelection()
}
</script>
@@ -0,0 +1,30 @@
<template>
<div class="flex flex-col gap-3 mb-4">
<div v-for="option in deliveryOptions" :key="option.method">
<!--
@vue-ignore
Vue: Argument of type
{ label: 'В браузере (push-уведомления)'; method: 'webPush'; } | { label: 'Telegram'; method: 'telegram'; }
is not assignable to parameter of type never
The intersection
{ readonly label: 'В браузере (push-уведомления)'; readonly method: 'webPush'; } & { readonly label: 'Telegram'; readonly method: 'telegram'; }
was reduced to never because property label has conflicting types in some constituents.
-->
<slot :name="option.method" v-bind="option" v-if="slots[option.method]" />
<slot v-bind="option" v-else-if="slots.default" />
</div>
</div>
</template>
<script setup lang="ts">
import { deliveryOptions, type DeliveryOption } from '@/constants/deliveryOptions'
const slots = defineSlots<
{
[K in DeliveryOption['method']]?: (option: Extract<DeliveryOption, { method: K }>) => void
} & {
default?: (option: DeliveryOption) => void
}
>()
</script>
@@ -1,8 +1,13 @@
export const DELIVERY_METHOD_TELEGRAM = 'telegram'
export const DELIVERY_METHOD_WEB_PUSH = 'webPush'
// Массив вариантов доставки
export const deliveryOptions = [
{
label: 'В браузере (push-уведомления)',
method: 'webPushSubscription',
method: DELIVERY_METHOD_WEB_PUSH,
},
{ label: 'Telegram', method: 'telegram' },
{ label: 'Telegram', method: DELIVERY_METHOD_TELEGRAM },
] as const
export type DeliveryOption = (typeof deliveryOptions)[number]
@@ -26,7 +26,7 @@ export interface QRCodeDocument extends BaseDocument {
/** Название объекта, для которого создан QR‑код, например "Мой автомобиль" */
name: string
messageDeliveryMethod: 'telegram' | 'webPushSubscription'
messageDeliveryMethod: 'telegram' | 'webPush'
/** Тип объекта, для которого создан QR‑код, например "car" */
placement: 'car' | 'pet' | 'door' | 'store' | 'restaurant_table' | 'other'