sentry, /viewContent /uploadContent modals, /uploadContent buttons

This commit is contained in:
Verticool committed 2025-02-18 18:03:15 +06:00
1 parent b952a76ccb
commit fc8e8cba5e
13 files changed
+525 -64

No files matched your search

+1
View File
@@ -1,3 +1,4 @@
import './shared/services/sentry/index.ts';
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
@@ -0,0 +1,60 @@
import { useHapticFeedback } from "@vkruglikov/react-telegram-web-app";
import { Button } from "~/shared/ui/button";
type DisclaimerModalProps = {
onConfirm(): void;
};
export const DisclaimerModal = ({
onConfirm,
}: DisclaimerModalProps) => {
const [impactOccurred] = useHapticFeedback();
const handleClick = (fn: () => void) => {
impactOccurred("light");
fn();
};
return (
<div
className={
"fixed left-0 top-0 z-30 flex h-full w-full items-center justify-center bg-black/80 px-[15px]"
}
>
<div className={"flex flex-col gap-[30px]"}>
<div
className={
"border border-white bg-[#1D1D1B] px-[10px] py-[16px] text-start flex flex-col gap-12"
}
>
<p className="mt-4">
«Внимание!
</p>
<p className="">
MY снимает с себя ответственность за правомерность загрузки контента пользователем.
</p>
<p className="flex flex-col">
<span className="tracking-[.25em] w-full">
Сервис исходит из личной
</span>
ответственности пользователя перед законом и третьими лицами. MY категорически не приемлет любые виды пиратства, но признает за Пользователем право принятия самостоятельных решений.
</p>
<p className="flex flex-col">
<span className="tracking-[.25em] w-full">
Перед загрузкой контента
</span>
необходимо убедиться, что первые 30 секунд контента, которые будут использоваться для превью, не содержат материалов, нарушающих возрастное ограничение 18+»
</p>
<Button
className={"mt-[20px]"}
label={"Принять и продолжить"}
includeArrows={false}
onClick={() => handleClick(onConfirm)}
/>
</div>
</div>
</div>
);
};
+24 -1
View File
@@ -1,4 +1,4 @@
import { useMemo } from "react";
import { useEffect, useMemo, useState } from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
@@ -15,6 +15,7 @@ import { Checkbox } from "~/shared/ui/checkbox";
import { AudioPlayer } from "~/shared/ui/audio-player";
import { HashtagInput } from "~/shared/ui/hashtag-input";
import { Replace } from "~/shared/ui/icons/replace";
import { DisclaimerModal } from "./components/disclaimer-modal";
type DataStepProps = {
nextStep(): void;
@@ -22,6 +23,8 @@ type DataStepProps = {
export const DataStep = ({ nextStep }: DataStepProps) => {
const rootStore = useRootStore();
const [disclaimerAccepted, setDisclaimerAccepted] = useState(false);
const formSchema = useMemo(() => {
return z.object({
@@ -64,8 +67,28 @@ export const DataStep = ({ nextStep }: DataStepProps) => {
rootStore.setFileType('');
}
useEffect(() => {
const storedValue = localStorage.getItem('disclaimerAccepted');
if (storedValue === 'true') {
setDisclaimerAccepted(true);
}
}, []);
const handleConfirmDisclaimer = () => {
setDisclaimerAccepted(true);
localStorage.setItem('disclaimerAccepted', 'true');
};
return (
<section className={"mt-4 px-4 pb-8"}>
{(rootStore.fileSrc && !disclaimerAccepted) &&
(<DisclaimerModal
onConfirm={() => {
handleConfirmDisclaimer()}}
/>)}
<div className={"mb-[30px] flex flex-col text-sm"}>
<span className={"ml-4"}>/Заполните информацию о контенте</span>
<div>
+92 -34
View File
@@ -11,28 +11,51 @@ type WelcomeStepProps = {
export const WelcomeStep = ({ nextStep }: WelcomeStepProps) => {
const [tonConnectUI] = useTonConnectUI();
const [isLoaded, setLoaded] = useState(false);
const [isConnected, setIsConnected] = useState(tonConnectUI.connected);
console.log("💩💩💩 enter WelcomeStep");
const auth = useAuth();
console.log("💩💩💩 after useAuth");
const handleNextClick = async () => {
if (tonConnectUI.connected) {
await auth.mutateAsync();
nextStep();
} else {
try {
await tonConnectUI.openModal();
useEffect(() => {
localStorage.setItem('disclaimerAccepted', 'false');
}, []);
useEffect(() => {
const unsubscribe = tonConnectUI.onStatusChange((wallet) => {
setIsConnected(!!wallet);
});
return () => {
unsubscribe();
};
}, [tonConnectUI]);
const handleNextClick = async () => {
if (tonConnectUI.connected) {
await auth.mutateAsync();
nextStep();
} catch (error) {
console.error('Failed to connect or authenticate:', error);
} else {
try {
await tonConnectUI.openModal();
await auth.mutateAsync();
} catch (error) {
console.error('Failed to connect or authenticate:', error);
}
}
};
const handleDisconnect = async () => {
if (isConnected){
try {
await tonConnectUI.disconnect();
} catch (error) {
console.error('Failed to disconnect:', error);
}
}
}
};
// useEffect(() => {
// const first = setTimeout(async () => {
// console.log("💩💩💩 call auth");
@@ -74,8 +97,8 @@ const handleNextClick = async () => {
}
return (
<section className={"mt-4 flex flex-col px-4"}>
<div className={"flex items-center justify-center"}>
<section className={"mt-4 flex flex-col justify-between min-h-[calc(100vh-32px)] px-4"}>
<div className="flex items-center justify-center overflow-hidden w-[100%] h-[400px]">
<img
alt={"splash"}
className={" w-full shrink-0"}
@@ -83,30 +106,65 @@ const handleNextClick = async () => {
/>
</div>
<div className={"flex gap-2 text-sm"}>
<span>/ Добро пожаловать в MY</span>
<div className={"flex flex-col mt-4"}>
<div className={"flex gap-2 text-sm"}>
<span>/ Добро пожаловать в MY</span>
<div className={"flex items-center gap-0"}>
<span>[</span>
<div className={"mb-0.5 h-3 w-3 rounded-full bg-primary"} />
<span>]:</span>
<div className={"flex items-center gap-0"}>
<span>[</span>
<div className={"mb-0.5 h-3 w-3 rounded-full bg-primary"} />
<span>]:</span>
</div>
</div>
</div>
<div className={"mt-2"}>
<p className={"text-sm"}>
децентрализованную систему монетизации контента. для продолжения
необходимо подключить криптокошелек TON
</p>
{isConnected ?
<>
<div className={"mt-2"}>
<p className={"text-sm"}>
Вы зарегистрированы под кошельком:
<span className={"font-bold pl-1"}>{tonConnectUI.account?.address.slice(2, 9)}...{tonConnectUI.account?.address.slice(-4)}</span>
</p>
</div>
<div className="flex flex-col">
<Button
className={"mt-[30px]"}
label={"Продолжить"}
includeArrows={false}
isLoading={auth.isLoading}
onClick={handleNextClick}
/>
<Button
className={"mt-[20px] bg-inherit"}
label={"Изменить кошелек"}
includeArrows={false}
isLoading={false}
onClick={handleDisconnect}
/>
</div>
</>
:
<>
<div className={"mt-2"}>
<p className={"text-sm"}>
Здесь вы можете загрузить свой контент. <br/> Для продолжения подключите кошелек.
</p>
</div>
<div className={"mt-2"}>
<p className={"text-sm"}>
Не волнуйтесь. Вы сможете поменять свой выбор в любой момент.
</p>
</div>
<Button
className={"mt-[30px]"}
label={"Подключить криптокошелёк TON"}
includeArrows={true}
isLoading={auth.isLoading}
onClick={handleNextClick}
/>
</>}
</div>
<Button
className={"mt-[30px]"}
label={"Подключить криптокошелёк TON"}
includeArrows={true}
isLoading={auth.isLoading}
onClick={handleNextClick}
/>
</section>
);
};
@@ -0,0 +1,57 @@
import { useHapticFeedback } from "@vkruglikov/react-telegram-web-app";
import { Button } from "~/shared/ui/button";
type CongratsModalProps = {
onConfirm(): void;
};
export const CongratsModal = ({
onConfirm,
}: CongratsModalProps) => {
const [impactOccurred] = useHapticFeedback();
const handleClick = (fn: () => void) => {
impactOccurred("light");
fn();
};
return (
<div
className={
"fixed left-0 top-0 z-30 flex h-full w-full items-center justify-center bg-black/80 px-[15px]"
}
>
<div className={"flex flex-col gap-[30px]"}>
<div
className={
"border border-white bg-[#1D1D1B] px-[10px] py-[16px] text-start flex flex-col gap-12"
}
>
<p className="mt-12">
<span className="text-xl">🎉</span>
<span className="px-1 font-bold">Поздравляем с покупкой!</span>
<span className="text-xl">🎉</span>
</p>
<p className="">
Ваш контент уже в пути! В ближайшее время в чат-боте <strong>MY Player</strong> вам придёт сообщение с доступом к купленному материалу. В этом чат-боте будет храниться весь ваш приобретённый контент.
</p>
<p className="flex flex-col">
<strong className="w-full">Теперь вы можете самостоятельно осуществить продажу купленного контента.</strong>
<span>
Перешлите сообщение из чата My-Player друзьям или опубликуйте в своём Telegram-канале. Каждый, кто купит контент по вашей ссылке, принесёт вам доход, а автору — заслуженное вознаграждение.
</span>
</p>
<p className="flex flex-col">
Спасибо, что выбираете MY!
</p>
<Button
className={"mt-[20px]"}
label={"Ок"}
includeArrows={false}
onClick={() => handleClick(onConfirm)}
/>
</div>
</div>
</div>
);
};
@@ -0,0 +1,54 @@
import { useHapticFeedback } from "@vkruglikov/react-telegram-web-app";
import { Button } from "~/shared/ui/button";
type ErrorModalProps = {
onConfirm(): void;
};
export const ErrorModal = ({
onConfirm,
}: ErrorModalProps) => {
const [impactOccurred] = useHapticFeedback();
const handleClick = (fn: () => void) => {
impactOccurred("light");
fn();
};
return (
<div
className={
"fixed left-0 top-0 z-30 flex h-full w-full items-center justify-center bg-black/80 px-[15px]"
}
>
<div className={"flex flex-col gap-[30px]"}>
<div
className={
"border border-white bg-[#1D1D1B] px-[10px] py-[16px] text-start flex flex-col gap-12"
}
>
<p className="mt-12">
<span className="px-1 font-bold">Ошибка запроса транзакции</span>
</p>
<p className="">
Не удалось отправить запрос на выполнение транзакции.
</p>
<p className="flex flex-col">
<span>
Попробуйте переподключить кошелек и повторить попытку. Если ошибка сохраняется, попробуйте запросить транзакцию еще раз.
</span>
</p>
<p className="flex flex-col">
Если проблема не исчезает, убедитесь, что ваш кошелек работает корректно, или свяжитесь с поддержкой.
</p>
<Button
className={"mt-[20px]"}
label={"Ок"}
includeArrows={false}
onClick={() => handleClick(onConfirm)}
/>
</div>
</div>
</div>
);
};
+28 -14
View File
@@ -5,9 +5,11 @@ import { useWebApp } from "@vkruglikov/react-telegram-web-app";
import { Button } from "~/shared/ui/button";
import { usePurchaseContent, useViewContent } from "~/shared/services/content";
import { fromNanoTON } from "~/shared/utils";
import {useCallback, useEffect, useMemo} from "react";
import {useCallback, useEffect, useMemo, useState} from "react";
import { AudioPlayer } from "~/shared/ui/audio-player";
import {useAuth} from "~/shared/services/auth";
import { CongratsModal } from "./components/congrats-modal";
import { ErrorModal } from "./components/error-modal";
export const ViewContentPage = () => {
const WebApp = useWebApp();
@@ -20,8 +22,8 @@ export const ViewContentPage = () => {
const auth = useAuth();
const [isCongratsModal, setIsCongratsModal] = useState(false);
const [isErrorModal, setIsErrorModal] = useState(false);
const handleBuyContent = useCallback(async () => {
try {
if (!tonConnectUI.connected) {
@@ -50,11 +52,14 @@ export const ViewContentPage = () => {
if (transactionResponse.boc) {
void refetchContent()
setIsCongratsModal(true);
console.log(transactionResponse.boc, "PURCHASED")
} else {
setIsErrorModal(true);
console.error("Transaction failed:", transactionResponse);
}
} catch (error) {
setIsErrorModal(true);
console.error("Error handling Ton Connect subscription:", error);
}
}, [content, tonConnectUI.connected]);
@@ -71,19 +76,28 @@ export const ViewContentPage = () => {
return () => clearInterval(interval)
}, []);
const handleConfirmCongrats = () => {
setIsCongratsModal(!isCongratsModal);
};
const handleErrorModal = () => {
setIsErrorModal(!isErrorModal);
}
return (
<main className={"min-h-screen flex w-full flex-col gap-[50px] px-4 "}>
{content?.data?.content_type.startsWith("audio") && content?.data?.display_options?.metadata?.image && (
<div className={"mt-[30px] h-[314px] w-full"}>
<img
alt={"content_image"}
className={"h-full w-full object-cover object-center"}
src={content?.data?.display_options?.metadata?.image}
/>
</div>
)}
<main className={"min-h-screen flex w-full flex-col gap-[50px] px-4 "}>
{isCongratsModal && <CongratsModal
onConfirm={handleConfirmCongrats}/>}
{isErrorModal && <ErrorModal
onConfirm={handleErrorModal}/>}
{content?.data?.content_type.startsWith("audio") && content?.data?.display_options?.metadata?.image && (
<div className={"mt-[30px] h-[314px] w-full"}>
<img
alt={"content_image"}
className={"h-full w-full object-cover object-center"}
src={content?.data?.display_options?.metadata?.image}
/>
</div>
)}
{content?.data?.content_type.startsWith("audio") ? (
<AudioPlayer src={content?.data?.display_options?.content_url} />
+15 -12
View File
@@ -1,5 +1,5 @@
import { useRef } from "react";
import { useTonConnectUI, useTonWallet } from "@tonconnect/ui-react";
import { useTonConnectUI } from "@tonconnect/ui-react";
import { useMutation } from "react-query";
import { request } from "~/shared/libs";
import { useWebApp } from "@vkruglikov/react-telegram-web-app";
@@ -9,7 +9,7 @@ const payloadTTLMS = 1000 * 60 * 20;
export const useAuth = () => {
const WebApp = useWebApp();
const wallet = useTonWallet();
// const wallet = useTonWallet();
const [tonConnectUI] = useTonConnectUI();
const interval = useRef<ReturnType<typeof setInterval> | undefined>();
@@ -94,17 +94,20 @@ export const useAuth = () => {
});
}
// Commented this part for two reasons:
// 1) When we include ton_proof from the wallet it fails the call for a reason of bad ton_proof
// 2) This call could happen only if the first case happened and it means that the ton_proof is already have been stored once before
// Case 2: Connected with proof - use it
if (wallet?.connectItems?.tonProof && !("error" in wallet.connectItems.tonProof)) {
console.log("DEBUG: Using existing proof");
return makeAuthRequest({
twa_data: WebApp.initData,
ton_proof: {
account: wallet.account,
ton_proof: wallet.connectItems.tonProof.proof,
},
});
}
// if (wallet?.connectItems?.tonProof && !("error" in wallet.connectItems.tonProof)) {
// console.log("DEBUG: Using existing proof", wallet.connectItems.tonProof.proof);
// return makeAuthRequest({
// twa_data: WebApp.initData,
// ton_proof: {
// account: wallet.account,
// ton_proof: wallet.connectItems.tonProof.proof,
// },
// });
// }
// Case 3: Connected without proof - already authenticated
console.log("DEBUG: Connected without proof, proceeding without it");
+42
View File
@@ -0,0 +1,42 @@
import { useEffect } from "react";
import * as Sentry from "@sentry/react";
import {
createRoutesFromChildren,
matchRoutes,
useLocation,
useNavigationType,
} from "react-router-dom";
Sentry.init({
dsn: import.meta.env.SENTRY_DSN,
integrations: [
// See docs for support of different versions of variation of react router
// https://docs.sentry.io/platforms/javascript/guides/react/configuration/integrations/react-router/
Sentry.reactRouterV6BrowserTracingIntegration({
useEffect,
useLocation,
useNavigationType,
createRoutesFromChildren,
matchRoutes,
}),
Sentry.replayIntegration(),
],
// Set tracesSampleRate to 1.0 to capture 100%
// of transactions for tracing.
// Learn more at
// https://docs.sentry.io/platforms/javascript/configuration/options/#traces-sample-rate
tracesSampleRate: 1.0,
// Set `tracePropagationTargets` to control for which URLs trace propagation should be enabled
tracePropagationTargets: [
/^\//,
new RegExp(`^${import.meta.env.VITE_API_BASE_URL}`),
],
// Capture Replay for 10% of all sessions,
// plus for 100% of sessions with an error
// Learn more at
// https://docs.sentry.io/platforms/javascript/session-replay/configuration/#general-integration-configuration
replaysSessionSampleRate: 0.1,
replaysOnErrorSampleRate: 1.0,
});