chore: finish profile
ci-api / test (push) Failing after 11m37s
ci-web / test (push) Successful in 14m39s

This commit is contained in:
Nuxgrid
2026-07-29 14:50:31 +02:00
parent 5a0c1bfe3f
commit 6beabfb070
16 changed files with 137 additions and 527 deletions
-5
View File
@@ -18,7 +18,6 @@ import (
"github.com/omnex/control-plane/api/internal/leads" "github.com/omnex/control-plane/api/internal/leads"
"github.com/omnex/control-plane/api/internal/profile" "github.com/omnex/control-plane/api/internal/profile"
"github.com/omnex/control-plane/api/internal/router" "github.com/omnex/control-plane/api/internal/router"
"github.com/omnex/control-plane/api/internal/sav"
"github.com/omnex/control-plane/api/internal/session" "github.com/omnex/control-plane/api/internal/session"
"github.com/omnex/control-plane/api/internal/sub" "github.com/omnex/control-plane/api/internal/sub"
) )
@@ -69,7 +68,6 @@ func main() {
var demoStore demos.Store var demoStore demos.Store
var demoPool demos.Pool var demoPool demos.Pool
var codeStore sub.Store var codeStore sub.Store
var contactStore sav.Store
var profileStore profile.Store var profileStore profile.Store
if cfg.DatabaseURL != "" { if cfg.DatabaseURL != "" {
gdb, err := db.Open(cfg.DatabaseURL) gdb, err := db.Open(cfg.DatabaseURL)
@@ -89,7 +87,6 @@ func main() {
leadStore = leads.NewGormStore(gdb) leadStore = leads.NewGormStore(gdb)
demoStore = demos.NewGormStore(gdb) demoStore = demos.NewGormStore(gdb)
demoPool = demos.NewGormPool(gdb) demoPool = demos.NewGormPool(gdb)
contactStore = sav.NewGormStore(gdb)
profileStore = profile.NewGormStore(gdb) profileStore = profile.NewGormStore(gdb)
log.Printf("persistance: PostgreSQL (GORM)") log.Printf("persistance: PostgreSQL (GORM)")
} else { } else {
@@ -98,7 +95,6 @@ func main() {
leadStore = leads.NewMemStore() leadStore = leads.NewMemStore()
demoStore = demos.NewMemStore() demoStore = demos.NewMemStore()
demoPool = demos.NewMemPool() demoPool = demos.NewMemPool()
contactStore = sav.NewMemContactStore()
log.Printf("persistance: mémoire (dev — définir OMNEX_DATABASE_URL pour PostgreSQL)") log.Printf("persistance: mémoire (dev — définir OMNEX_DATABASE_URL pour PostgreSQL)")
} }
@@ -128,7 +124,6 @@ func main() {
LeadsH: leads.NewHandler(leadStore), LeadsH: leads.NewHandler(leadStore),
DemosH: demos.NewHandler(demoSvc, helmProv), DemosH: demos.NewHandler(demoSvc, helmProv),
SubH: sub.NewHandler(codeStore), SubH: sub.NewHandler(codeStore),
ContactH: sav.NewHandler(contactStore),
ProfileH: profile.NewHandler(profileStore), ProfileH: profile.NewHandler(profileStore),
} }
-2
View File
@@ -12,7 +12,6 @@ import (
"github.com/omnex/control-plane/api/internal/auth" "github.com/omnex/control-plane/api/internal/auth"
"github.com/omnex/control-plane/api/internal/demos" "github.com/omnex/control-plane/api/internal/demos"
"github.com/omnex/control-plane/api/internal/leads" "github.com/omnex/control-plane/api/internal/leads"
"github.com/omnex/control-plane/api/internal/sav"
"github.com/omnex/control-plane/api/internal/sub" "github.com/omnex/control-plane/api/internal/sub"
) )
@@ -45,7 +44,6 @@ func AutoMigrate(gdb *gorm.DB) error {
&leads.Lead{}, &leads.Lead{},
&demos.Demo{}, &demos.Demo{},
&demos.ExternalResource{}, &demos.ExternalResource{},
&sav.Contact{},
) )
} }
@@ -17,6 +17,8 @@ func NewGormStore(db *gorm.DB) *GormStore {
type Store interface { type Store interface {
UpdateUsername(id, newUsername string) (auth.User, error) UpdateUsername(id, newUsername string) (auth.User, error)
UpdatePassword(id, passwordHahs string) (auth.User, error) UpdatePassword(id, passwordHahs string) (auth.User, error)
GetTelegram(id string) (auth.User, error)
SetTelegram(id, telegram string) (auth.User, error)
} }
func (s *GormStore) UpdateUsername(id, newUsername string) (auth.User, error) { func (s *GormStore) UpdateUsername(id, newUsername string) (auth.User, error) {
@@ -36,8 +38,16 @@ func (s *GormStore) UpdateUsername(id, newUsername string) (auth.User, error) {
return user, nil return user, nil
} }
func (s *GormStore) UpdatePassword(id, passwordHash string) (auth.User, error) { func (s *GormStore) GetTelegram(id string) (auth.User, error) {
result := s.db.Model(&auth.User{}).Where("id = ?", id).Update("password", passwordHash) var user auth.User
if err := s.db.First(&user, "id = ?", id).Error; err != nil {
return auth.User{}, err
}
return user, nil
}
func (s *GormStore) SetTelegram(id, telegram string) (auth.User, error) {
result := s.db.Model(&auth.User{}).Where("id = ?", id).Update("telegram", telegram)
if result.Error != nil { if result.Error != nil {
return auth.User{}, result.Error return auth.User{}, result.Error
} }
@@ -23,6 +23,10 @@ type newPassword struct {
Password string `json:"password" binding:"required,min=8"` Password string `json:"password" binding:"required,min=8"`
} }
type newTelegram struct {
Telegram string `json:"telegram" binding:"required,min=3,max=64"`
}
func (h *Handler) UpdateUsernameById(c *gin.Context) { func (h *Handler) UpdateUsernameById(c *gin.Context) {
var u newUsername var u newUsername
@@ -73,3 +77,36 @@ func (h *Handler) UpdatePasswordById(c *gin.Context) {
c.JSON(http.StatusOK, user) c.JSON(http.StatusOK, user)
} }
func (h *Handler) GetTelegramById(c *gin.Context) {
id, ok := c.MustGet("id").(string)
if !ok {
c.JSON(http.StatusUnauthorized, gin.H{"error": "id invalide"})
return
}
user, err := h.store.GetTelegram(id)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "requête invalide"})
return
}
c.JSON(http.StatusOK, gin.H{"telegram": user.Telegram})
}
func (h *Handler) SetTelegramById(c *gin.Context) {
var t newTelegram
if err := c.ShouldBindJSON(&t); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "requête invalide"})
return
}
id, ok := c.MustGet("id").(string)
if !ok {
c.JSON(http.StatusUnauthorized, gin.H{"error": "id invalide"})
return
}
user, err := h.store.SetTelegram(id, t.Telegram)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "erreur serveur"})
return
}
c.JSON(http.StatusOK, gin.H{"telegram": user.Telegram})
}
+2 -4
View File
@@ -12,7 +12,6 @@ import (
"github.com/omnex/control-plane/api/internal/httpx" "github.com/omnex/control-plane/api/internal/httpx"
"github.com/omnex/control-plane/api/internal/leads" "github.com/omnex/control-plane/api/internal/leads"
"github.com/omnex/control-plane/api/internal/profile" "github.com/omnex/control-plane/api/internal/profile"
"github.com/omnex/control-plane/api/internal/sav"
"github.com/omnex/control-plane/api/internal/session" "github.com/omnex/control-plane/api/internal/session"
"github.com/omnex/control-plane/api/internal/sub" "github.com/omnex/control-plane/api/internal/sub"
) )
@@ -26,7 +25,6 @@ type Deps struct {
LeadsH *leads.Handler LeadsH *leads.Handler
DemosH *demos.Handler DemosH *demos.Handler
SubH *sub.Handler SubH *sub.Handler
ContactH *sav.Handler
ProfileH *profile.Handler ProfileH *profile.Handler
} }
@@ -48,7 +46,6 @@ func New(d Deps) *gin.Engine {
api.POST("/auth/login", httpx.RateLimit(1, 5), d.AuthH.Login) api.POST("/auth/login", httpx.RateLimit(1, 5), d.AuthH.Login)
api.POST("/auth/register", httpx.RateLimit(0.2, 3), d.AuthH.Register) api.POST("/auth/register", httpx.RateLimit(0.2, 3), d.AuthH.Register)
api.POST("/leads", httpx.RateLimit(1, 3), d.LeadsH.Create) api.POST("/leads", httpx.RateLimit(1, 3), d.LeadsH.Create)
api.POST("/send/message", httpx.RateLimit(1, 3), d.ContactH.CallSupport)
// Toute route authentifiée (session valide, n'importe quel rôle). // Toute route authentifiée (session valide, n'importe quel rôle).
authed := api.Group("") authed := api.Group("")
authed.Use(auth.RequireAuth(d.Issuer, d.Sessions)) authed.Use(auth.RequireAuth(d.Issuer, d.Sessions))
@@ -65,6 +62,8 @@ func New(d Deps) *gin.Engine {
client.POST("/subscription", d.SubH.AddCode) client.POST("/subscription", d.SubH.AddCode)
client.POST("/profile/username", d.ProfileH.UpdateUsernameById) client.POST("/profile/username", d.ProfileH.UpdateUsernameById)
client.POST("/profile/password", d.ProfileH.UpdatePasswordById) client.POST("/profile/password", d.ProfileH.UpdatePasswordById)
client.GET("/profile/telegram", d.ProfileH.GetTelegramById)
client.POST("/profile/telegram", d.ProfileH.SetTelegramById)
} }
// Espace admin : provisioning des démos (admin uniquement). // Espace admin : provisioning des démos (admin uniquement).
@@ -73,7 +72,6 @@ func New(d Deps) *gin.Engine {
{ {
admin.GET("/codes", d.SubH.ListCodes) admin.GET("/codes", d.SubH.ListCodes)
admin.POST("/codes", d.SubH.CreateCodeForBuy) admin.POST("/codes", d.SubH.CreateCodeForBuy)
admin.GET("/messages", d.ContactH.GetMessage)
admin.POST("/profile/username", d.ProfileH.UpdateUsernameById) admin.POST("/profile/username", d.ProfileH.UpdateUsernameById)
admin.POST("/profile/password", d.ProfileH.UpdatePasswordById) admin.POST("/profile/password", d.ProfileH.UpdatePasswordById)
if d.DemosH != nil { if d.DemosH != nil {
-60
View File
@@ -1,60 +0,0 @@
package sav
import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/omnex/control-plane/api/internal/auth"
)
type Handler struct {
store Store
}
// NewHandler crée un nouveau Handler.
func NewHandler(store Store) *Handler {
return &Handler{store: store}
}
type contactSupport struct {
Username string `json:"username"`
Telegram string `json:"telegram"`
Sujet string `json:"sujet"`
Message string `json:"message"`
}
func (h *Handler) CallSupport(c *gin.Context) {
var req contactSupport
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "requête invalide"})
return
}
contact, err := h.store.ContactSupportByUser(req.Username, req.Telegram, req.Sujet, req.Message)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "erreur serveur"})
return
}
c.JSON(http.StatusCreated, gin.H{"success": "message envoyé", "contact": contact})
}
func (h *Handler) GetMessage(c *gin.Context) {
p := auth.PrincipalFrom(c)
if p == nil {
c.JSON(http.StatusUnauthorized, gin.H{"error": "non authentifié"})
return
}
if p.Role != "admin" {
c.JSON(http.StatusUnauthorized, gin.H{"error": "role non correcte"})
return
}
getMessage, err := h.store.GetMessage()
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "erreur serveur"})
return
}
c.JSON(http.StatusCreated, gin.H{"messages": getMessage})
}
-49
View File
@@ -1,49 +0,0 @@
package sav
import (
"sort"
"sync"
"github.com/google/uuid"
"github.com/omnex/control-plane/api/internal/auth"
)
type MemContactStore struct {
mu sync.RWMutex
items map[string]Contact
}
func NewMemContactStore() *MemContactStore {
return &MemContactStore{
items: make(map[string]Contact),
}
}
func (m *MemContactStore) ContactSupportByUser(username, telegram, sujet, message string) (Contact, error) {
m.mu.RLock()
defer m.mu.RUnlock()
contact := Contact{
ID: uuid.NewString(),
Username: auth.NormalizeUsername(username),
Telegram: auth.NormalizeUsername(telegram),
Sujet: sujet,
Message: message,
}
m.items[contact.ID] = contact
return contact, nil
}
func (m *MemContactStore) GetMessage() ([]Contact, error) {
m.mu.RLock()
defer m.mu.RUnlock()
contacts := make([]Contact, 0, len(m.items))
for _, c := range m.items {
contacts = append(contacts, c)
}
sort.Slice(contacts, func(i, j int) bool {
return contacts[i].CreatedAt.After(contacts[j].CreatedAt)
})
return contacts, nil
}
-12
View File
@@ -1,12 +0,0 @@
package sav
import "time"
type Contact struct {
ID string `gorm:"type:uuid;primaryKey" json:"id"`
Username string `gorm:"size:64;not null" json:"username"`
Telegram string `gorm:"size:64;not null" json:"telegram"`
Sujet string `gorm:"size:64;not null" json:"sujet"`
Message string `gorm:"size:64;not null" json:"message"`
CreatedAt time.Time `json:"created_at"`
}
-43
View File
@@ -1,43 +0,0 @@
package sav
import (
"github.com/google/uuid"
"github.com/omnex/control-plane/api/internal/auth"
"gorm.io/gorm"
)
type Store interface {
ContactSupportByUser(username, telegram, sujet, message string) (Contact, error)
GetMessage() ([]Contact, error)
}
type GormStore struct {
db *gorm.DB
}
func NewGormStore(db *gorm.DB) *GormStore {
return &GormStore{db: db}
}
func (s *GormStore) ContactSupportByUser(username, telegram, sujet, message string) (Contact, error) {
contact := Contact{
ID: uuid.NewString(),
Username: auth.NormalizeUsername(username),
Telegram: auth.NormalizeUsername(telegram),
Sujet: sujet,
Message: message,
}
if err := s.db.Create(&contact).Error; err != nil {
return Contact{}, err
}
return contact, nil
}
func (s *GormStore) GetMessage() ([]Contact, error) {
var contacts []Contact
if err := s.db.Find(&contacts).Error; err != nil {
return nil, err
}
return contacts, nil
}
-11
View File
@@ -7,13 +7,11 @@ import { Login } from './pages/Login'
import { Register } from './pages/Register' import { Register } from './pages/Register'
import { Leads } from './pages/backoffice/Leads' import { Leads } from './pages/backoffice/Leads'
import { Demos } from './pages/backoffice/Demos' import { Demos } from './pages/backoffice/Demos'
import { Messages } from './pages/backoffice/Contact'
import { Codes } from './pages/backoffice/Codes' import { Codes } from './pages/backoffice/Codes'
import { Subscription } from './pages/backoffice/Subscription' import { Subscription } from './pages/backoffice/Subscription'
import { Profile } from './pages/backoffice/Profile' import { Profile } from './pages/backoffice/Profile'
import { PublicLayout } from './components/PublicLayout' import { PublicLayout } from './components/PublicLayout'
import { BackofficeLayout } from './components/BackofficeLayout' import { BackofficeLayout } from './components/BackofficeLayout'
import { Contact } from './pages/Contact'
import { useAuth } from './lib/auth' import { useAuth } from './lib/auth'
import type { JSX } from 'react' import type { JSX } from 'react'
@@ -64,7 +62,6 @@ export function App() {
<Route path="/" element={<Landing />} /> <Route path="/" element={<Landing />} />
<Route path="/tarifs" element={<Pricing />} /> <Route path="/tarifs" element={<Pricing />} />
<Route path="/demo" element={<RequestDemo />} /> <Route path="/demo" element={<RequestDemo />} />
<Route path="/contact" element={<Contact />} />
</Route> </Route>
<Route path="/login" element={<Login />} /> <Route path="/login" element={<Login />} />
<Route path="/register" element={<Register />} /> <Route path="/register" element={<Register />} />
@@ -106,14 +103,6 @@ export function App() {
</RequireAdmin> </RequireAdmin>
} }
/> />
<Route
path="messages"
element={
<RequireAdmin>
<Messages />
</RequireAdmin>
}
/>
<Route <Route
path="profile" path="profile"
element={ element={
-6
View File
@@ -51,7 +51,6 @@ export function BackofficeLayout() {
{(isAdmin || (isClient && !isPremium)) && <NavItem to="/app/leads">Leads</NavItem>} {(isAdmin || (isClient && !isPremium)) && <NavItem to="/app/leads">Leads</NavItem>}
{isClient && <NavItem to="/app/subscription">Abonnement</NavItem>} {isClient && <NavItem to="/app/subscription">Abonnement</NavItem>}
{isAdmin || isClient && <NavItem to="/app/profile">Profile</NavItem>} {isAdmin || isClient && <NavItem to="/app/profile">Profile</NavItem>}
{isAdmin && <NavItem to="/app/messages">Messages</NavItem>}
{isAdmin && <NavItem to="/app/demos">Démos</NavItem>} {isAdmin && <NavItem to="/app/demos">Démos</NavItem>}
{isAdmin && <NavItem to="/app/codes">Codes</NavItem>} {isAdmin && <NavItem to="/app/codes">Codes</NavItem>}
</HStack> </HStack>
@@ -96,11 +95,6 @@ export function BackofficeLayout() {
Abonnement Abonnement
</NavItem> </NavItem>
)} )}
{isAdmin && (
<NavItem to="/app/messages" onClick={onClose} mobile>
Messages
</NavItem>
)}
{isAdmin && ( {isAdmin && (
<NavItem to="/app/demos" onClick={onClose} mobile> <NavItem to="/app/demos" onClick={onClose} mobile>
Démos Démos
+10 -2
View File
@@ -107,6 +107,11 @@ export interface UpdateUsername {
export interface UpdatePassword { export interface UpdatePassword {
password: string password: string
} }
export interface TelegramInfo {
telegram: string
}
// --- Endpoints --- // --- Endpoints ---
export const api = { export const api = {
@@ -157,6 +162,9 @@ export const api = {
request<DemoDetails>('POST', '/demos/details', { username }), request<DemoDetails>('POST', '/demos/details', { username }),
updateUsername: (username: string) => updateUsername: (username: string) =>
request<UpdateUsername>('POST', '/profile/username', { username }), request<UpdateUsername>('POST', '/profile/username', { username }),
updatePassword: (password: string) => updatePassword: (password: string) =>
request<UpdatePassword>('POST', '/profile/password', { password }) request<UpdatePassword>('POST', '/profile/password', { password }),
getTelegram: () => request<TelegramInfo>('GET', '/profile/telegram'),
setTelegram: (telegram: string) =>
request<TelegramInfo>('POST', '/profile/telegram', { telegram }),
} }
-211
View File
@@ -1,211 +0,0 @@
import { useState, type FormEvent } from 'react'
import {
Box,
Button,
Container,
Divider,
Flex,
FormControl,
FormLabel,
FormErrorMessage,
Heading,
Input,
Link,
Stack,
Text,
Textarea,
SimpleGrid,
useToast,
} from '@chakra-ui/react'
import { api, ApiError } from '../lib/api'
interface ContactForm {
name: string
telegram: string
subject: string
message: string
}
const initialForm: ContactForm = {
name: '',
telegram: '',
subject: '',
message: '',
}
// Remplace par le vrai handle / lien de contact Telegram d'Omnex.
const TELEGRAM_CONTACT_URL = 'https://t.me/OMNEX_CORP'
const TelegramIcon = () => (
<Box as="svg" w="20px" h="20px" viewBox="0 0 24 24" fill="currentColor">
<Box
as="path"
d="M21.05 3.79a1.5 1.5 0 0 0-1.53-.25L2.6 10.1a1.5 1.5 0 0 0 .07 2.8l4.44 1.48 1.7 5.46a1.5 1.5 0 0 0 2.5.6l2.4-2.32 4.36 3.2a1.5 1.5 0 0 0 2.38-.86l3.1-14.9a1.5 1.5 0 0 0-.5-1.77ZM8.9 13.6l8.9-6.2-7.2 7.4-.3 3.2-1.4-4.4Z"
/>
</Box>
)
export function Contact() {
const toast = useToast()
const [form, setForm] = useState<ContactForm>(initialForm)
const [errors, setErrors] = useState<Partial<Record<keyof ContactForm, string>>>({})
const [submitting, setSubmitting] = useState(false)
const handleChange =
(field: keyof ContactForm) =>
(e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
setForm((prev) => ({ ...prev, [field]: e.target.value }))
}
const validate = (): boolean => {
const nextErrors: Partial<Record<keyof ContactForm, string>> = {}
if (!form.name.trim()) nextErrors.name = 'Le nom est requis.'
if (!form.telegram.trim()) {
nextErrors.telegram = "L'email est requis."
}
if (!form.subject.trim()) nextErrors.subject = 'Le sujet est requis.'
if (!form.message.trim()) nextErrors.message = 'Le message est requis.'
setErrors(nextErrors)
return Object.keys(nextErrors).length === 0
}
const handleSubmit = async (e: FormEvent) => {
e.preventDefault()
if (!validate()) return
setSubmitting(true)
try {
await api.sendMessage(form.name, form.telegram, form.subject, form.message)
toast({
title: 'Message envoyé',
description: 'Nous vous répondrons dans les plus brefs délais.',
status: 'success',
duration: 5000,
isClosable: true,
})
setForm(initialForm)
setErrors({})
} catch (err) {
const description =
err instanceof ApiError ? err.message : 'Merci de réessayer dans quelques instants.'
toast({
title: "Erreur lors de l'envoi",
description,
status: 'error',
duration: 5000,
isClosable: true,
})
} finally {
setSubmitting(false)
}
}
return (
<Box bg="chakra-subtle-bg" py={{ base: 12, md: 20 }}>
<Container maxW="container.md">
<Stack spacing={3} mb={10} textAlign="center">
<Heading size="xl">Contactez-nous</Heading>
<Text color="gray.400" fontSize="lg">
Une question, une démo à planifier, un projet ? Écrivez-nous.
</Text>
</Stack>
<Flex justify="center" mb={10}>
<Button
as={Link}
href={TELEGRAM_CONTACT_URL}
isExternal
leftIcon={<TelegramIcon />}
colorScheme="telegram"
size="lg"
w={{ base: 'full', sm: 'auto' }}
whiteSpace="normal"
_hover={{ textDecoration: 'none' }}
>
Nous contacter sur Telegram
</Button>
</Flex>
<Flex align="center" mb={10} gap={4}>
<Divider />
<Text fontSize="sm" color="gray.500" whiteSpace="nowrap">
ou par formulaire
</Text>
<Divider />
</Flex>
<Box
as="form"
onSubmit={handleSubmit}
bg="bg-surface"
borderWidth="1px"
borderColor="chakra-border-color"
borderRadius="xl"
p={{ base: 6, md: 10 }}
boxShadow="lg"
>
<Stack spacing={6}>
<SimpleGrid columns={{ base: 1, md: 2 }} spacing={5}>
<FormControl isInvalid={!!errors.name}>
<FormLabel>Nom</FormLabel>
<Input
value={form.name}
onChange={handleChange('name')}
placeholder="Votre nom"
size="lg"
/>
<FormErrorMessage>{errors.name}</FormErrorMessage>
</FormControl>
<FormControl isInvalid={!!errors.telegram}>
<FormLabel>Telegram</FormLabel>
<Input
type="email"
value={form.telegram}
onChange={handleChange('telegram')}
placeholder="vous@entreprise.com"
size="lg"
/>
<FormErrorMessage>{errors.telegram}</FormErrorMessage>
</FormControl>
</SimpleGrid>
<FormControl isInvalid={!!errors.subject}>
<FormLabel>Sujet</FormLabel>
<Input
value={form.subject}
onChange={handleChange('subject')}
placeholder="Demande de démo, question tarifaire..."
size="lg"
/>
<FormErrorMessage>{errors.subject}</FormErrorMessage>
</FormControl>
<FormControl isInvalid={!!errors.message}>
<FormLabel>Message</FormLabel>
<Textarea
value={form.message}
onChange={handleChange('message')}
placeholder="Décrivez votre besoin..."
rows={6}
resize="vertical"
/>
<FormErrorMessage>{errors.message}</FormErrorMessage>
</FormControl>
<Button
type="submit"
colorScheme="primary"
size="lg"
alignSelf={{ base: 'stretch', md: 'flex-start' }}
isLoading={submitting}
loadingText="Envoi..."
>
Envoyer le message
</Button>
</Stack>
</Box>
</Container>
</Box>
)
}
-113
View File
@@ -1,113 +0,0 @@
import { useEffect, useState } from 'react'
import {
Badge,
Box,
Heading,
Spinner,
Stack,
Table,
Tbody,
Td,
Text,
Th,
Thead,
Tr,
Alert,
AlertIcon,
} from '@chakra-ui/react'
import { api, ApiError, type Contact } from '../../lib/api'
export function Messages() {
const [messages, setMessages] = useState<Contact[]>([])
const [loading, setLoading] = useState(true)
const [error, setError] = useState<string | null>(null)
useEffect(() => {
let active = true
api
.getMessage()
.then((res) => {
if (active) setMessages(res.messages)
})
.catch((err) => {
if (active) {
setError(err instanceof ApiError ? err.message : 'Erreur lors du chargement des messages.')
}
})
.finally(() => {
if (active) setLoading(false)
})
return () => {
active = false
}
}, [])
if (loading) {
return (
<Stack align="center" py={20}>
<Spinner />
</Stack>
)
}
if (error) {
return (
<Alert status="error" borderRadius="md">
<AlertIcon />
{error}
</Alert>
)
}
return (
<Stack spacing={6}>
<Stack spacing={1}>
<Heading size="lg">Messages de contact</Heading>
<Text color="gray.400">{messages.length} message(s) reçu(s)</Text>
</Stack>
{messages.length === 0 ? (
<Box bg="bg-surface" borderWidth="1px" borderColor="chakra-border-color" borderRadius="lg" p={8}>
<Text color="gray.400">Aucun message pour le moment.</Text>
</Box>
) : (
<Box
bg="bg-surface"
borderWidth="1px"
borderColor="chakra-border-color"
borderRadius="lg"
overflowX="auto"
>
<Table variant="simple" size="sm">
<Thead>
<Tr>
<Th>Nom</Th>
<Th>Telegram</Th>
<Th>Sujet</Th>
<Th>Message</Th>
<Th>Reçu le</Th>
</Tr>
</Thead>
<Tbody>
{messages.map((m) => (
<Tr key={m.id}>
<Td fontWeight="medium">{m.username}</Td>
<Td>
<Badge colorScheme="blue">{m.telegram}</Badge>
</Td>
<Td>{m.sujet}</Td>
<Td maxW="320px" whiteSpace="normal">
{m.message}
</Td>
<Td whiteSpace="nowrap">
{new Date(m.created_at).toLocaleString('fr-FR')}
</Td>
</Tr>
))}
</Tbody>
</Table>
</Box>
)}
</Stack>
)
}
+2
View File
@@ -74,6 +74,7 @@ export function Leads() {
<Tr> <Tr>
<Th>Telegram</Th> <Th>Telegram</Th>
<Th>Statut</Th> <Th>Statut</Th>
<Th>Message</Th>
<Th>Reçu le</Th> <Th>Reçu le</Th>
<Th></Th> <Th></Th>
</Tr> </Tr>
@@ -85,6 +86,7 @@ export function Leads() {
<Td> <Td>
<Badge>{l.status}</Badge> <Badge>{l.status}</Badge>
</Td> </Td>
<Td fontWeight="medium">{l.message}</Td>
<Td>{formatDate(l.created_at)}</Td> <Td>{formatDate(l.created_at)}</Td>
<Td textAlign="right"> <Td textAlign="right">
{isAdmin && ( {isAdmin && (
+74 -7
View File
@@ -101,12 +101,19 @@ export function Profile() {
const [updatingUsername, setUpdatingUsername] = useState(false) const [updatingUsername, setUpdatingUsername] = useState(false)
const [updatingPassword, setUpdatingPassword] = useState(false) const [updatingPassword, setUpdatingPassword] = useState(false)
const [passwordVersion, setPasswordVersion] = useState(0) const [passwordVersion, setPasswordVersion] = useState(0)
const [telegram, setTelegramState] = useState('')
const [updatingTelegram, setUpdatingTelegram] = useState(false)
const [addingTelegram, setAddingTelegram] = useState(false)
useEffect(() => { useEffect(() => {
let cancelled = false let cancelled = false
;(async () => { ;(async () => {
try { try {
const res = await api.me() const [meRes, tgRes] = await Promise.all([api.me(), api.getTelegram()])
if (!cancelled) setMe(res) if (!cancelled) {
setMe(meRes)
setTelegramState(tgRes.telegram ?? '')
}
} catch (err) { } catch (err) {
if (err instanceof ApiError && err.status === 401) { if (err instanceof ApiError && err.status === 401) {
navigate('/login') navigate('/login')
@@ -117,9 +124,7 @@ export function Profile() {
if (!cancelled) setLoading(false) if (!cancelled) setLoading(false)
} }
})() })()
return () => { return () => { cancelled = true }
cancelled = true
}
}, [navigate, toast]) }, [navigate, toast])
const handleUpdateUsername = async (newUsername: string) => { const handleUpdateUsername = async (newUsername: string) => {
@@ -175,7 +180,32 @@ export function Profile() {
setPasswordVersion(v => v + 1) // vide le champ après tentative setPasswordVersion(v => v + 1) // vide le champ après tentative
} }
} }
const handleUpdateTelegram = async (newTelegram: string) => {
const trimmed = newTelegram.trim()
if (!trimmed) {
setAddingTelegram(false)
return
}
setUpdatingTelegram(true)
try {
const res = await api.setTelegram(trimmed)
setTelegramState(res.telegram)
setAddingTelegram(false)
toast({ status: 'success', title: 'Telegram enregistré' })
} catch (err) {
if (err instanceof ApiError && err.status === 401) {
navigate('/login')
return
}
toast({
status: 'error',
title: "Impossible d'enregistrer le Telegram",
description: err instanceof ApiError ? err.message : undefined,
})
} finally {
setUpdatingTelegram(false)
}
}
const handleLogout = async () => { const handleLogout = async () => {
setLoggingOut(true) setLoggingOut(true)
try { try {
@@ -285,7 +315,44 @@ export function Profile() {
</HStack> </HStack>
</Editable> </Editable>
</Stat> </Stat>
<Stat>
<StatLabel>Telegram</StatLabel>
{telegram ? (
<Editable
key={telegram}
defaultValue={telegram}
onSubmit={handleUpdateTelegram}
isDisabled={updatingTelegram}
submitOnBlur={false}
>
<HStack spacing={2}>
<EditablePreview as={StatNumber} fontSize="md" fontFamily="mono" />
<EditableInput fontSize="md" fontFamily="mono" />
<EditableUsernameControls />
</HStack>
</Editable>
) : addingTelegram ? (
<Editable
defaultValue=""
placeholder="@monpseudo"
startWithEditView
onSubmit={handleUpdateTelegram}
onCancel={() => setAddingTelegram(false)}
isDisabled={updatingTelegram}
submitOnBlur={false}
>
<HStack spacing={2}>
<EditablePreview as={StatNumber} fontSize="md" fontFamily="mono" />
<EditableInput fontSize="md" fontFamily="mono" />
<EditableUsernameControls />
</HStack>
</Editable>
) : (
<Button size="sm" variant="outline" onClick={() => setAddingTelegram(true)}>
Ajouter mon Telegram
</Button>
)}
</Stat>
<Stat> <Stat>
<StatLabel>Expire le</StatLabel> <StatLabel>Expire le</StatLabel>
<StatNumber fontSize="md">{formatDate(me.expired_at)}</StatNumber> <StatNumber fontSize="md">{formatDate(me.expired_at)}</StatNumber>