feat(push): PushSubscriptionBanner on delivery consent page
This commit is contained in:
parent
98ebc935c2
commit
82eefb2225
|
|
@ -0,0 +1,207 @@
|
||||||
|
import React, { useState, useEffect, useRef } from "react";
|
||||||
|
|
||||||
|
const VAPID_PUBLIC_KEY = "BDLNGyVp7hDzRujZBncNQ0qyz4zVFAhAWX1nsCMRC2tagmer46Sy6exZOymsGVk-TDb1bhkkXXth9Jkzdv4SdJg";
|
||||||
|
|
||||||
|
const PUSH_API_BASE = (() => {
|
||||||
|
try { return import.meta.env.VITE_PUSH_API_BASE || ""; } catch { return ""; }
|
||||||
|
})();
|
||||||
|
|
||||||
|
const getEndpoint = () => {
|
||||||
|
if (PUSH_API_BASE) return `${PUSH_API_BASE}/functions/v1/push-subscribe`;
|
||||||
|
// Supabase Kong gateway — same origin as other edge functions
|
||||||
|
const base = window.location.origin.replace("dev.mkn8n.ru", "dev.mkn8n.ru");
|
||||||
|
// Fallback: use Supabase Kong directly
|
||||||
|
return "https://dev.mkn8n.ru/functions/v1/push-subscribe";
|
||||||
|
};
|
||||||
|
|
||||||
|
const normalizePhone = (phone) => {
|
||||||
|
if (!phone) return "";
|
||||||
|
const clean = String(phone).replace(/\D/g, "");
|
||||||
|
if (clean.startsWith("8")) return "7" + clean.slice(1);
|
||||||
|
if (!clean.startsWith("7")) return "7" + clean;
|
||||||
|
return clean;
|
||||||
|
};
|
||||||
|
|
||||||
|
const urlBase64ToUint8Array = (base64String) => {
|
||||||
|
const padding = "=".repeat((4 - base64String.length % 4) % 4);
|
||||||
|
const base64 = (base64String + padding).replace(/-/g, "+").replace(/_/g, "/");
|
||||||
|
const rawData = window.atob(base64);
|
||||||
|
const outputArray = new Uint8Array(rawData.length);
|
||||||
|
for (let i = 0; i < rawData.length; ++i) {
|
||||||
|
outputArray[i] = rawData.charCodeAt(i);
|
||||||
|
}
|
||||||
|
return outputArray;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const PushSubscriptionBanner = ({ phone, orderGroupId }) => {
|
||||||
|
const [status, setStatus] = useState("idle"); // idle | prompting | subscribed | denied | unsupported
|
||||||
|
const [dismissed, setDismissed] = useState(false);
|
||||||
|
const phoneNorm = normalizePhone(phone);
|
||||||
|
|
||||||
|
// Check if push is supported
|
||||||
|
useEffect(() => {
|
||||||
|
if (!("serviceWorker" in navigator) || !("PushManager" in window)) {
|
||||||
|
setStatus("unsupported");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// Check existing subscription
|
||||||
|
navigator.serviceWorker.ready.then(async (reg) => {
|
||||||
|
const existing = await reg.pushManager.getSubscription();
|
||||||
|
if (existing) {
|
||||||
|
setStatus("subscribed");
|
||||||
|
}
|
||||||
|
}).catch(() => {});
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const subscribe = async () => {
|
||||||
|
try {
|
||||||
|
setStatus("prompting");
|
||||||
|
const reg = await navigator.serviceWorker.ready;
|
||||||
|
const existing = await reg.pushManager.getSubscription();
|
||||||
|
let subscription = existing;
|
||||||
|
if (!subscription) {
|
||||||
|
subscription = await reg.pushManager.subscribe({
|
||||||
|
userVisibleOnly: true,
|
||||||
|
applicationServerKey: urlBase64ToUint8Array(VAPID_PUBLIC_KEY),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
// Send to backend
|
||||||
|
const sub = subscription.toJSON();
|
||||||
|
const resp = await fetch(getEndpoint(), {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({
|
||||||
|
phone_normalized: phoneNorm,
|
||||||
|
endpoint: sub.endpoint,
|
||||||
|
p256dh: sub.keys?.p256dh || "",
|
||||||
|
auth: sub.keys?.auth || "",
|
||||||
|
user_agent: navigator.userAgent || "",
|
||||||
|
order_group_id: orderGroupId || null,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
if (resp.ok) {
|
||||||
|
setStatus("subscribed");
|
||||||
|
} else {
|
||||||
|
console.warn("[Push] subscribe API error:", resp.status);
|
||||||
|
setStatus("idle");
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
if (err?.name === "NotAllowedError" || err?.name === "denied") {
|
||||||
|
setStatus("denied");
|
||||||
|
} else {
|
||||||
|
console.warn("[Push] subscribe error:", err);
|
||||||
|
setStatus("idle");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const unsubscribe = async () => {
|
||||||
|
try {
|
||||||
|
const reg = await navigator.serviceWorker.ready;
|
||||||
|
const sub = await reg.pushManager.getSubscription();
|
||||||
|
if (sub) {
|
||||||
|
await sub.unsubscribe();
|
||||||
|
// Notify backend
|
||||||
|
await fetch(getEndpoint().replace("push-subscribe", "push-unsubscribe"), {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({
|
||||||
|
endpoint: sub.endpoint,
|
||||||
|
phone_normalized: phoneNorm,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
setStatus("idle");
|
||||||
|
} catch (err) {
|
||||||
|
console.warn("[Push] unsubscribe error:", err);
|
||||||
|
setStatus("idle");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Don't render if unsupported, dismissed, or no phone
|
||||||
|
if (status === "unsupported" || !phoneNorm) return null;
|
||||||
|
if (dismissed && status !== "subscribed" && status !== "denied") return null;
|
||||||
|
|
||||||
|
// Subscribed state — show small confirmation + unsubscribe option
|
||||||
|
if (status === "subscribed") {
|
||||||
|
return (
|
||||||
|
<div className="rounded-xl border border-[rgba(18,128,92,0.25)] bg-[var(--color-accent-soft)] px-4 py-3">
|
||||||
|
<div className="flex items-center justify-between gap-3">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<span className="text-sm">🔔</span>
|
||||||
|
<p className="text-sm font-medium text-[var(--color-accent)]">
|
||||||
|
Уведомления включены
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={unsubscribe}
|
||||||
|
className="text-xs text-[var(--color-text-muted)] transition hover:text-[var(--color-text)] underline"
|
||||||
|
>
|
||||||
|
Отключить
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Denied — user blocked notifications
|
||||||
|
if (status === "denied") {
|
||||||
|
return (
|
||||||
|
<div className="rounded-xl border border-[var(--color-border)] bg-[var(--color-surface)] px-4 py-3">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<span className="text-sm">🔕</span>
|
||||||
|
<p className="text-sm text-[var(--color-text-muted)]">
|
||||||
|
Уведомления заблокированы. Разрешите их в настройках браузера.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Prompting — show loading
|
||||||
|
if (status === "prompting") {
|
||||||
|
return (
|
||||||
|
<div className="rounded-xl border border-[var(--color-border)] bg-[var(--color-surface)] px-4 py-3">
|
||||||
|
<p className="text-sm text-[var(--color-text-muted)]">Ожидание разрешения…</p>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Idle — show subscription banner
|
||||||
|
return (
|
||||||
|
<div className="rounded-xl border border-[rgba(18,128,92,0.2)] bg-[var(--color-accent-soft)] px-4 py-3">
|
||||||
|
<div className="flex items-center justify-between gap-3">
|
||||||
|
<div className="flex items-start gap-2.5">
|
||||||
|
<span className="text-base flex-shrink-0 mt-0.5">🔔</span>
|
||||||
|
<div>
|
||||||
|
<p className="text-sm font-semibold text-[var(--color-text)]">
|
||||||
|
Включить уведомления о доставке
|
||||||
|
</p>
|
||||||
|
<p className="text-xs text-[var(--color-text-muted)] mt-0.5">
|
||||||
|
Получайте push-уведомления вместо SMS. Быстрее и удобнее.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-2 flex-shrink-0">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={subscribe}
|
||||||
|
className="rounded-xl bg-[var(--color-accent)] px-4 py-2 text-sm font-semibold text-white transition hover:opacity-90"
|
||||||
|
>
|
||||||
|
Разрешить
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setDismissed(true)}
|
||||||
|
className="text-xs text-[var(--color-text-muted)] transition hover:text-[var(--color-text)]"
|
||||||
|
>
|
||||||
|
Позже
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default PushSubscriptionBanner;
|
||||||
|
|
@ -6,6 +6,7 @@ import { PickupSlotsPicker } from "../components/client/PickupSlotsPicker";
|
||||||
import { OrderCompositionPanel } from "../components/client/OrderCompositionPanel";
|
import { OrderCompositionPanel } from "../components/client/OrderCompositionPanel";
|
||||||
import { getInvitationReferenceLabel } from "../components/client/invitationReference";
|
import { getInvitationReferenceLabel } from "../components/client/invitationReference";
|
||||||
import { DeliveryStateNotice } from "../components/client/DeliveryStateNotice";
|
import { DeliveryStateNotice } from "../components/client/DeliveryStateNotice";
|
||||||
|
import { PushSubscriptionBanner } from "../components/client/PushSubscriptionBanner";
|
||||||
import { Panel } from "../components/UI/Panel";
|
import { Panel } from "../components/UI/Panel";
|
||||||
|
|
||||||
import { Skeleton } from "../components/UI/Loading";
|
import { Skeleton } from "../components/UI/Loading";
|
||||||
|
|
@ -395,6 +396,11 @@ export const ClientDeliveryPage = () => {
|
||||||
|
|
||||||
<OrderCompositionPanel invitation={invitation} />
|
<OrderCompositionPanel invitation={invitation} />
|
||||||
|
|
||||||
|
<PushSubscriptionBanner
|
||||||
|
phone={invitation?.customerPhone || invitation?.customer_phone || ""}
|
||||||
|
orderGroupId={invitation?.orderGroupId || invitation?.order_group_id || null}
|
||||||
|
/>
|
||||||
|
|
||||||
{isChoiceSaved && savedChoiceLabel ? (
|
{isChoiceSaved && savedChoiceLabel ? (
|
||||||
<Panel className="space-y-2 p-5 sm:p-6">
|
<Panel className="space-y-2 p-5 sm:p-6">
|
||||||
<p className="text-sm uppercase tracking-[0.24em] text-[var(--color-text-muted)]">Ваш выбор</p>
|
<p className="text-sm uppercase tracking-[0.24em] text-[var(--color-text-muted)]">Ваш выбор</p>
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue