push messages to telegram from contactUs form

This commit is contained in:
2025-05-22 16:40:13 +03:00
parent 29d3af2ea1
commit 2b902ef0c9
6 changed files with 32 additions and 23 deletions

View File

@@ -26,7 +26,8 @@ class TelegramSerializer(serializers.Serializer):
("main", "Main"), ("main", "Main"),
("admin", "Admin"), ("admin", "Admin"),
("userAccount", "Account"), ("userAccount", "Account"),
("contact-us", "Contact Us") ("contactUs", "Contact Us"),
("support", "Support")
] ]
source = serializers.ChoiceField(choices=SOURCE_CHOICES) source = serializers.ChoiceField(choices=SOURCE_CHOICES)

View File

@@ -18,7 +18,7 @@ GetMembershipData)
urlpatterns = [ urlpatterns = [
path("v1/faq/", FAQView.as_view(), name='faqMain'), path("v1/faq/", FAQView.as_view(), name='faqMain'),
path("v1/news/", NewsView.as_view(), name="newsmain"), path("v1/news/", NewsView.as_view(), name="newsmain"),
path("v1/send-message", TelegramMessageView.as_view(), name='send_message'), path("v1/send-message/", TelegramMessageView.as_view(), name='send_message'),
path("v1/latest-routes/", LatestRoutesView.as_view(), name='latest_routes'), path("v1/latest-routes/", LatestRoutesView.as_view(), name='latest_routes'),
path("auth/refresh/", RefreshTokenView.as_view(), name="token-refresh"), path("auth/refresh/", RefreshTokenView.as_view(), name="token-refresh"),

View File

@@ -137,15 +137,15 @@ export interface AccountSidebarProps {
navigation: NavigationItem[] navigation: NavigationItem[]
} }
export type SourceType = 'main' | 'admin' | 'userAccount' | 'contactUs' | 'support'
export interface TelegramMessage { export interface TelegramMessage {
source: string source: SourceType
name: string name: string
phone_number: string phone_number: string
message: string message: string
} }
export type SourceType = 'account' | 'contact-us'
export interface TextAreaProps { export interface TextAreaProps {
value: string value: string
handleChange: (e: React.ChangeEvent<HTMLTextAreaElement>) => void handleChange: (e: React.ChangeEvent<HTMLTextAreaElement>) => void

View File

@@ -32,7 +32,7 @@ const ContactUs = () => {
message: '', message: '',
}, },
validationRules, validationRules,
async (values) => { async values => {
try { try {
await sendMessage(values) await sendMessage(values)
@@ -42,20 +42,21 @@ const ContactUs = () => {
}) })
resetField('message') resetField('message')
} catch { } catch (error) {
console.error('ContactUs - Error details:', error)
showToast({ type: 'error', message: 'Ой, что то пошло не так..' }) showToast({ type: 'error', message: 'Ой, что то пошло не так..' })
} }
} }
) )
return ( return (
<div className="rounded-2xl shadow overflow-hidden"> <div className="overflow-hidden rounded-2xl shadow">
<div className="p-6 bg-white sm:p-8"> <div className="bg-white p-6 sm:p-8">
<div className="space-y-4"> <div className="space-y-4">
<h2 className="text-2xl">Хотели бы связаться с нами?</h2> <h2 className="text-2xl">Хотели бы связаться с нами?</h2>
<form className="space-y-4" onSubmit={handleSubmit}> <form className="space-y-4" onSubmit={handleSubmit}>
<div className="grid grid-cols-1 md:grid-cols-2 gap-6 h-full"> <div className="grid h-full grid-cols-1 gap-6 md:grid-cols-2">
<div className="space-y-4 h-full flex flex-col"> <div className="flex h-full flex-col space-y-4">
<TextInput <TextInput
label="Ваше имя" label="Ваше имя"
value={values.name} value={values.name}
@@ -81,7 +82,7 @@ const ContactUs = () => {
</div> </div>
<Button <Button
text="Отправить" text="Отправить"
className="text-sm font-semibold py-4 px-6 bg-black text-white flex items-center justify-center w-full rounded-2xl whitespace-nowrap" className="flex w-full items-center justify-center rounded-2xl bg-black px-6 py-4 text-sm font-semibold whitespace-nowrap text-white"
type="submit" type="submit"
/> />
</form> </form>

View File

@@ -9,21 +9,24 @@ export const sendMessage = async (data: TelegramMessage) => {
} }
try { try {
const body = JSON.stringify({
source: data.source,
name: data.name,
phone_number: data.phone_number,
message: data.message,
})
const response = await fetch(`${API_URL}/send-message/`, { const response = await fetch(`${API_URL}/send-message/`, {
method: 'POST', method: 'POST',
headers, headers,
body: JSON.stringify({ body,
source: data.source,
name: data.name,
phone_number: data.phone_number,
message: data.message,
}),
}) })
if (!response.ok) { if (!response.ok) {
let errorMessage = `Failed to send form data: ${response.status} ${response.statusText}` let errorMessage = `Failed to send form data: ${response.status} ${response.statusText}`
try { try {
const errorData = await response.text() const errorData = await response.text()
if (errorData) { if (errorData) {
errorMessage += ` - ${errorData}` errorMessage += ` - ${errorData}`
} }

View File

@@ -1,15 +1,19 @@
// export type SourceType = 'main' | 'admin' | 'userAccount' | 'contactUs' | 'support'
import { SourceType } from '@/app/types' import { SourceType } from '@/app/types'
const pathToSourceMap: Record<string, SourceType> = { const pathToSourceMap: Record<string, SourceType> = {
techSupport: 'contact-us', // берем в кавычки значение с дефисом 'account/support': 'support',
account: 'account', '': 'main', // без слеша -- так работает usePathname
'contact-us': 'contactUs', // URL путь с дефисом -> значение в camelCase
} }
export const getSourceFromPath = (pathname: string): SourceType => { export const getSourceFromPath = (pathname: string): SourceType => {
const cleanPath = pathname.replace(/^\//, '') const cleanPath = pathname.replace(/^\//, '')
const source = pathToSourceMap[cleanPath] || 'contact-us' // дефолтное значение // для путей аккаунта (кроме support)
// console.log('Final source:', source) if (cleanPath.startsWith('account/') && cleanPath !== 'account/support') {
return 'userAccount'
}
const source = pathToSourceMap[cleanPath] || 'contactUs' // дефолтное значение
return source return source
} }