chore: build
This commit is contained in:
@@ -80,6 +80,7 @@ func main() {
|
|||||||
var userStore auth.UserStore
|
var userStore auth.UserStore
|
||||||
var demoStore demos.Store
|
var demoStore demos.Store
|
||||||
var projectStore projects.Store
|
var projectStore projects.Store
|
||||||
|
var requestStore projects.RequestStore
|
||||||
var demoPool demos.Pool
|
var demoPool demos.Pool
|
||||||
var codeStore sub.Store
|
var codeStore sub.Store
|
||||||
var profileStore profile.Store
|
var profileStore profile.Store
|
||||||
@@ -102,6 +103,7 @@ func main() {
|
|||||||
codeStore = sub.NewGormStore(gdb)
|
codeStore = sub.NewGormStore(gdb)
|
||||||
demoStore = demos.NewGormStore(gdb)
|
demoStore = demos.NewGormStore(gdb)
|
||||||
projectStore = projects.NewGormStore(gdb)
|
projectStore = projects.NewGormStore(gdb)
|
||||||
|
requestStore = projects.NewGormRequestStore(gdb)
|
||||||
demoPool = demos.NewGormPool(gdb)
|
demoPool = demos.NewGormPool(gdb)
|
||||||
profileStore = profile.NewGormStore(gdb)
|
profileStore = profile.NewGormStore(gdb)
|
||||||
alertRecipients = alerts.GormRecipients(gdb)
|
alertRecipients = alerts.GormRecipients(gdb)
|
||||||
@@ -111,6 +113,7 @@ func main() {
|
|||||||
codeStore = sub.NewMemStore()
|
codeStore = sub.NewMemStore()
|
||||||
demoStore = demos.NewMemStore()
|
demoStore = demos.NewMemStore()
|
||||||
projectStore = projects.NewMemStore()
|
projectStore = projects.NewMemStore()
|
||||||
|
requestStore = projects.NewMemRequestStore()
|
||||||
demoPool = demos.NewMemPool()
|
demoPool = demos.NewMemPool()
|
||||||
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)")
|
||||||
}
|
}
|
||||||
@@ -212,13 +215,15 @@ func main() {
|
|||||||
log.Printf("alerts: monitoring désactivé (nécessite OMNEX_DATABASE_URL — réglages persistés par admin)")
|
log.Printf("alerts: monitoring désactivé (nécessite OMNEX_DATABASE_URL — réglages persistés par admin)")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
projectsH := projects.NewHandler(projectSvc)
|
||||||
deps := router.Deps{
|
deps := router.Deps{
|
||||||
Cfg: cfg,
|
Cfg: cfg,
|
||||||
Issuer: iss,
|
Issuer: iss,
|
||||||
Sessions: sessions,
|
Sessions: sessions,
|
||||||
AuthH: auth.NewHandler(userStore, sessions, iss, cfg.Secure()),
|
AuthH: auth.NewHandler(userStore, sessions, iss, cfg.Secure()),
|
||||||
DemosH: demos.NewHandler(demoSvc, helmProv),
|
DemosH: demos.NewHandler(demoSvc, helmProv),
|
||||||
ProjectsH: projects.NewHandler(projectSvc),
|
ProjectsH: projectsH,
|
||||||
|
RequestsH: projects.NewRequestHandler(projects.NewRequestService(requestStore, projectSvc), projectsH),
|
||||||
SubH: sub.NewHandler(codeStore, demoSvc),
|
SubH: sub.NewHandler(codeStore, demoSvc),
|
||||||
ProfileH: profile.NewHandler(profileStore),
|
ProfileH: profile.NewHandler(profileStore),
|
||||||
DownloadsH: downloads.NewHandler(cfg.AppDownloadsDir, userStore, demoSvc),
|
DownloadsH: downloads.NewHandler(cfg.AppDownloadsDir, userStore, demoSvc),
|
||||||
|
|||||||
@@ -44,6 +44,7 @@ func AutoMigrate(gdb *gorm.DB) error {
|
|||||||
&demos.Demo{},
|
&demos.Demo{},
|
||||||
&demos.ExternalResource{},
|
&demos.ExternalResource{},
|
||||||
&projects.Project{},
|
&projects.Project{},
|
||||||
|
&projects.Request{},
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import (
|
|||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
|
|
||||||
|
"github.com/omnex/control-plane/api/internal/auth"
|
||||||
"github.com/omnex/control-plane/api/internal/demos"
|
"github.com/omnex/control-plane/api/internal/demos"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -37,10 +38,14 @@ func (h *Handler) writeError(c *gin.Context, err error) {
|
|||||||
switch {
|
switch {
|
||||||
case errors.Is(err, ErrNotFound):
|
case errors.Is(err, ErrNotFound):
|
||||||
c.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
|
c.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
|
||||||
case errors.Is(err, ErrNotExtendable), errors.Is(err, ErrNotReady), errors.Is(err, ErrDomainTaken):
|
case errors.Is(err, ErrRequestNotFound):
|
||||||
|
c.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
|
||||||
|
case errors.Is(err, ErrTooManyRequests):
|
||||||
|
c.JSON(http.StatusTooManyRequests, gin.H{"error": err.Error()})
|
||||||
|
case errors.Is(err, ErrNotExtendable), errors.Is(err, ErrNotReady), errors.Is(err, ErrDomainTaken), errors.Is(err, ErrRequestDecided):
|
||||||
c.JSON(http.StatusConflict, gin.H{"error": err.Error()})
|
c.JSON(http.StatusConflict, gin.H{"error": err.Error()})
|
||||||
case errors.Is(err, ErrInvalidMonths), errors.Is(err, ErrInvalidClient), errors.Is(err, ErrInvalidAdmin),
|
case errors.Is(err, ErrInvalidMonths), errors.Is(err, ErrInvalidClient), errors.Is(err, ErrInvalidAdmin),
|
||||||
errors.Is(err, ErrWeakAdminPass), errors.Is(err, ErrInvalidAdminSize), errors.Is(err, ErrDomainReserved),
|
errors.Is(err, ErrWeakAdminPass), errors.Is(err, ErrInvalidAdminSize), errors.Is(err, ErrDomainReserved), errors.Is(err, ErrInvalidMessage),
|
||||||
errors.Is(err, demos.ErrInvalidDomain):
|
errors.Is(err, demos.ErrInvalidDomain):
|
||||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
default:
|
default:
|
||||||
@@ -80,6 +85,21 @@ func (h *Handler) List(c *gin.Context) {
|
|||||||
c.JSON(http.StatusOK, gin.H{"items": items})
|
c.JSON(http.StatusOK, gin.H{"items": items})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ListMine : GET /projects/mine — sites rattachés au client authentifié.
|
||||||
|
func (h *Handler) ListMine(c *gin.Context) {
|
||||||
|
p := auth.PrincipalFrom(c)
|
||||||
|
if p == nil {
|
||||||
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "non authentifié"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
items, err := h.svc.ListForOwner(p.Username)
|
||||||
|
if err != nil {
|
||||||
|
h.writeError(c, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, gin.H{"items": items})
|
||||||
|
}
|
||||||
|
|
||||||
// Details : GET /projects/:id/details — état live des pods du projet, même
|
// Details : GET /projects/:id/details — état live des pods du projet, même
|
||||||
// format que POST /demos/details (le panneau du back-office est commun).
|
// format que POST /demos/details (le panneau du back-office est commun).
|
||||||
// Le namespace vient de la base, jamais de la requête.
|
// Le namespace vient de la base, jamais de la requête.
|
||||||
|
|||||||
@@ -50,6 +50,9 @@ type Project struct {
|
|||||||
// CustomDomain : domaine du client, servi en plus de Host ("" = aucun).
|
// CustomDomain : domaine du client, servi en plus de Host ("" = aucun).
|
||||||
// URL pointe dessus quand il est défini.
|
// URL pointe dessus quand il est défini.
|
||||||
CustomDomain string `gorm:"size:255" json:"custom_domain,omitempty"`
|
CustomDomain string `gorm:"size:255" json:"custom_domain,omitempty"`
|
||||||
|
// OwnerUsername : compte client qui a demandé le site ("" = déployé
|
||||||
|
// directement par l'admin). Donne au client la lecture de son site.
|
||||||
|
OwnerUsername string `gorm:"size:64;index" json:"owner_username,omitempty"`
|
||||||
|
|
||||||
// AdminUsername : compte admin créé dans le backend déployé (le mot de
|
// AdminUsername : compte admin créé dans le backend déployé (le mot de
|
||||||
// passe n'est jamais persisté). AdminNumber : ADMIN_NUMBER du backend.
|
// passe n'est jamais persisté). AdminNumber : ADMIN_NUMBER du backend.
|
||||||
|
|||||||
@@ -0,0 +1,301 @@
|
|||||||
|
package projects
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"sort"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
|
||||||
|
"github.com/omnex/control-plane/api/internal/auth"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Demandes d'achat d'un site vitrine : un client (compte Omnex) demande un
|
||||||
|
// site, l'admin valide — ce qui déploie le projet pour la durée convenue —
|
||||||
|
// ou refuse. Le paiement reste hors périmètre : l'admin valide quand il est
|
||||||
|
// reçu et peut ajuster la durée.
|
||||||
|
|
||||||
|
type RequestStatus string
|
||||||
|
|
||||||
|
const (
|
||||||
|
RequestPending RequestStatus = "pending"
|
||||||
|
RequestApproved RequestStatus = "approved"
|
||||||
|
RequestRejected RequestStatus = "rejected"
|
||||||
|
)
|
||||||
|
|
||||||
|
// MaxPendingRequests : demandes en attente simultanées par client (anti-spam).
|
||||||
|
const MaxPendingRequests = 3
|
||||||
|
|
||||||
|
const maxMessageLen = 500
|
||||||
|
|
||||||
|
var (
|
||||||
|
ErrRequestNotFound = errors.New("demande introuvable")
|
||||||
|
ErrRequestDecided = errors.New("cette demande a déjà été traitée")
|
||||||
|
ErrTooManyRequests = errors.New("trop de demandes en attente : attendez qu'elles soient traitées")
|
||||||
|
ErrInvalidMessage = errors.New("message trop long (500 caractères maximum)")
|
||||||
|
)
|
||||||
|
|
||||||
|
type Request struct {
|
||||||
|
ID string `gorm:"type:uuid;primaryKey" json:"id"`
|
||||||
|
Username string `gorm:"size:64;not null;index" json:"username"` // compte client demandeur
|
||||||
|
SiteName string `gorm:"size:64;not null" json:"site_name"`
|
||||||
|
// Months : durée souhaitée par le client ; l'admin peut en valider une autre.
|
||||||
|
Months int `json:"months"`
|
||||||
|
Message string `gorm:"size:500" json:"message,omitempty"`
|
||||||
|
Status RequestStatus `gorm:"size:20;not null;index" json:"status"`
|
||||||
|
AdminNote string `gorm:"size:500" json:"admin_note,omitempty"` // motif de refus
|
||||||
|
ProjectID string `gorm:"size:36" json:"project_id,omitempty"` // projet déployé à la validation
|
||||||
|
CreatedAt time.Time `json:"created_at"`
|
||||||
|
DecidedAt *time.Time `json:"decided_at,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (Request) TableName() string { return "project_requests" }
|
||||||
|
|
||||||
|
// RequestStore : persistance des demandes.
|
||||||
|
type RequestStore interface {
|
||||||
|
Create(r Request) (Request, error)
|
||||||
|
Get(id string) (Request, bool)
|
||||||
|
List() ([]Request, error)
|
||||||
|
ListByUsername(username string) ([]Request, error)
|
||||||
|
Update(r Request) (Request, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
type GormRequestStore struct{ db *gorm.DB }
|
||||||
|
|
||||||
|
func NewGormRequestStore(db *gorm.DB) *GormRequestStore { return &GormRequestStore{db: db} }
|
||||||
|
|
||||||
|
func (s *GormRequestStore) Create(r Request) (Request, error) {
|
||||||
|
if err := s.db.Create(&r).Error; err != nil {
|
||||||
|
return Request{}, err
|
||||||
|
}
|
||||||
|
return r, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *GormRequestStore) Get(id string) (Request, bool) {
|
||||||
|
var r Request
|
||||||
|
if err := s.db.Where("id = ?", id).First(&r).Error; err != nil {
|
||||||
|
return Request{}, false
|
||||||
|
}
|
||||||
|
return r, true
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *GormRequestStore) List() ([]Request, error) {
|
||||||
|
var out []Request
|
||||||
|
if err := s.db.Order("created_at DESC").Find(&out).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *GormRequestStore) ListByUsername(username string) ([]Request, error) {
|
||||||
|
var out []Request
|
||||||
|
if err := s.db.Where("username = ?", username).Order("created_at DESC").Find(&out).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *GormRequestStore) Update(r Request) (Request, error) {
|
||||||
|
if err := s.db.Save(&r).Error; err != nil {
|
||||||
|
return Request{}, err
|
||||||
|
}
|
||||||
|
return r, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// MemRequestStore : store en mémoire (dev/tests).
|
||||||
|
type MemRequestStore struct {
|
||||||
|
mu sync.RWMutex
|
||||||
|
items map[string]Request
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewMemRequestStore() *MemRequestStore { return &MemRequestStore{items: map[string]Request{}} }
|
||||||
|
|
||||||
|
func (m *MemRequestStore) Create(r Request) (Request, error) {
|
||||||
|
m.mu.Lock()
|
||||||
|
defer m.mu.Unlock()
|
||||||
|
m.items[r.ID] = r
|
||||||
|
return r, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *MemRequestStore) Get(id string) (Request, bool) {
|
||||||
|
m.mu.RLock()
|
||||||
|
defer m.mu.RUnlock()
|
||||||
|
r, ok := m.items[id]
|
||||||
|
return r, ok
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *MemRequestStore) all(keep func(Request) bool) []Request {
|
||||||
|
m.mu.RLock()
|
||||||
|
defer m.mu.RUnlock()
|
||||||
|
out := make([]Request, 0, len(m.items))
|
||||||
|
for _, r := range m.items {
|
||||||
|
if keep(r) {
|
||||||
|
out = append(out, r)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
sort.Slice(out, func(i, j int) bool { return out[i].CreatedAt.After(out[j].CreatedAt) })
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *MemRequestStore) List() ([]Request, error) {
|
||||||
|
return m.all(func(Request) bool { return true }), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *MemRequestStore) ListByUsername(username string) ([]Request, error) {
|
||||||
|
return m.all(func(r Request) bool { return r.Username == username }), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *MemRequestStore) Update(r Request) (Request, error) {
|
||||||
|
m.mu.Lock()
|
||||||
|
defer m.mu.Unlock()
|
||||||
|
m.items[r.ID] = r
|
||||||
|
return r, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// RequestInput : saisie du client.
|
||||||
|
type RequestInput struct {
|
||||||
|
SiteName string
|
||||||
|
Months int
|
||||||
|
Message string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (in *RequestInput) validate() error {
|
||||||
|
in.SiteName = strings.TrimSpace(in.SiteName)
|
||||||
|
in.Message = strings.TrimSpace(in.Message)
|
||||||
|
if in.SiteName == "" || len(in.SiteName) > 64 {
|
||||||
|
return ErrInvalidClient
|
||||||
|
}
|
||||||
|
if err := ValidateMonths(in.Months); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if len(in.Message) > maxMessageLen {
|
||||||
|
return ErrInvalidMessage
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ApproveInput : saisie de l'admin à la validation (compte admin du site).
|
||||||
|
type ApproveInput struct {
|
||||||
|
Months int // 0 => durée demandée par le client
|
||||||
|
AdminUsername string
|
||||||
|
AdminPassword string
|
||||||
|
AdminNumber int
|
||||||
|
}
|
||||||
|
|
||||||
|
// RequestService : logique métier des demandes.
|
||||||
|
type RequestService struct {
|
||||||
|
store RequestStore
|
||||||
|
projects *Service
|
||||||
|
now func() time.Time
|
||||||
|
|
||||||
|
// mu sérialise les décisions : deux validations simultanées de la même
|
||||||
|
// demande ne doivent pas déployer deux sites.
|
||||||
|
mu sync.Mutex
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewRequestService(store RequestStore, projects *Service) *RequestService {
|
||||||
|
return &RequestService{store: store, projects: projects, now: time.Now}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create enregistre la demande d'un client (en attente de validation).
|
||||||
|
func (s *RequestService) Create(username string, in RequestInput) (Request, error) {
|
||||||
|
if err := in.validate(); err != nil {
|
||||||
|
return Request{}, err
|
||||||
|
}
|
||||||
|
username = auth.NormalizeUsername(username)
|
||||||
|
|
||||||
|
s.mu.Lock()
|
||||||
|
defer s.mu.Unlock()
|
||||||
|
mine, err := s.store.ListByUsername(username)
|
||||||
|
if err != nil {
|
||||||
|
return Request{}, err
|
||||||
|
}
|
||||||
|
pending := 0
|
||||||
|
for _, r := range mine {
|
||||||
|
if r.Status == RequestPending {
|
||||||
|
pending++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if pending >= MaxPendingRequests {
|
||||||
|
return Request{}, ErrTooManyRequests
|
||||||
|
}
|
||||||
|
return s.store.Create(Request{
|
||||||
|
ID: uuid.NewString(),
|
||||||
|
Username: username,
|
||||||
|
SiteName: in.SiteName,
|
||||||
|
Months: in.Months,
|
||||||
|
Message: in.Message,
|
||||||
|
Status: RequestPending,
|
||||||
|
CreatedAt: s.now().UTC(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *RequestService) List() ([]Request, error) { return s.store.List() }
|
||||||
|
|
||||||
|
// ListMine : uniquement les demandes de ce client.
|
||||||
|
func (s *RequestService) ListMine(username string) ([]Request, error) {
|
||||||
|
return s.store.ListByUsername(auth.NormalizeUsername(username))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Approve déploie le site demandé, rattaché au compte du client, puis marque
|
||||||
|
// la demande validée. Si le déploiement est refusé (saisie invalide), la
|
||||||
|
// demande reste en attente.
|
||||||
|
func (s *RequestService) Approve(id string, in ApproveInput) (Request, Project, error) {
|
||||||
|
s.mu.Lock()
|
||||||
|
defer s.mu.Unlock()
|
||||||
|
|
||||||
|
r, ok := s.store.Get(id)
|
||||||
|
if !ok {
|
||||||
|
return Request{}, Project{}, ErrRequestNotFound
|
||||||
|
}
|
||||||
|
if r.Status != RequestPending {
|
||||||
|
return Request{}, Project{}, ErrRequestDecided
|
||||||
|
}
|
||||||
|
months := in.Months
|
||||||
|
if months == 0 {
|
||||||
|
months = r.Months
|
||||||
|
}
|
||||||
|
p, err := s.projects.Create(CreateInput{
|
||||||
|
ClientName: r.SiteName,
|
||||||
|
Months: months,
|
||||||
|
AdminUsername: in.AdminUsername,
|
||||||
|
AdminPassword: in.AdminPassword,
|
||||||
|
AdminNumber: in.AdminNumber,
|
||||||
|
OwnerUsername: r.Username,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return Request{}, Project{}, err
|
||||||
|
}
|
||||||
|
now := s.now().UTC()
|
||||||
|
r.Status = RequestApproved
|
||||||
|
r.ProjectID = p.ID
|
||||||
|
r.DecidedAt = &now
|
||||||
|
r, err = s.store.Update(r)
|
||||||
|
return r, p, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Reject refuse la demande, avec un motif facultatif visible du client.
|
||||||
|
func (s *RequestService) Reject(id, note string) (Request, error) {
|
||||||
|
note = strings.TrimSpace(note)
|
||||||
|
if len(note) > maxMessageLen {
|
||||||
|
return Request{}, ErrInvalidMessage
|
||||||
|
}
|
||||||
|
s.mu.Lock()
|
||||||
|
defer s.mu.Unlock()
|
||||||
|
|
||||||
|
r, ok := s.store.Get(id)
|
||||||
|
if !ok {
|
||||||
|
return Request{}, ErrRequestNotFound
|
||||||
|
}
|
||||||
|
if r.Status != RequestPending {
|
||||||
|
return Request{}, ErrRequestDecided
|
||||||
|
}
|
||||||
|
now := s.now().UTC()
|
||||||
|
r.Status = RequestRejected
|
||||||
|
r.AdminNote = note
|
||||||
|
r.DecidedAt = &now
|
||||||
|
return s.store.Update(r)
|
||||||
|
}
|
||||||
@@ -0,0 +1,119 @@
|
|||||||
|
package projects
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
|
||||||
|
"github.com/omnex/control-plane/api/internal/auth"
|
||||||
|
)
|
||||||
|
|
||||||
|
// RequestHandler : routes des demandes d'achat de site vitrine. Les routes
|
||||||
|
// client agissent toujours sur le compte authentifié, jamais sur un
|
||||||
|
// identifiant fourni par la requête.
|
||||||
|
type RequestHandler struct {
|
||||||
|
svc *RequestService
|
||||||
|
h *Handler // traduction des erreurs en codes HTTP
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewRequestHandler(svc *RequestService, h *Handler) *RequestHandler {
|
||||||
|
return &RequestHandler{svc: svc, h: h}
|
||||||
|
}
|
||||||
|
|
||||||
|
type requestBody struct {
|
||||||
|
SiteName string `json:"site_name" binding:"required,min=1,max=64"`
|
||||||
|
Months int `json:"months" binding:"required,min=1,max=12"`
|
||||||
|
Message string `json:"message" binding:"omitempty,max=500"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type approveBody struct {
|
||||||
|
// Months : durée validée ; 0 ou absent = celle demandée par le client.
|
||||||
|
Months int `json:"months" binding:"omitempty,min=1,max=12"`
|
||||||
|
AdminUsername string `json:"admin_username" binding:"required,min=3,max=64,alphanum"`
|
||||||
|
AdminPassword string `json:"admin_password" binding:"required,min=12"`
|
||||||
|
AdminNumber int `json:"admin_number" binding:"omitempty,min=1,max=20"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type rejectBody struct {
|
||||||
|
Note string `json:"note" binding:"omitempty,max=500"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create : POST /project-requests — le client demande un site (201).
|
||||||
|
func (r *RequestHandler) Create(c *gin.Context) {
|
||||||
|
p := auth.PrincipalFrom(c)
|
||||||
|
if p == nil {
|
||||||
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "non authentifié"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var body requestBody
|
||||||
|
if err := c.ShouldBindJSON(&body); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": "requête invalide"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
req, err := r.svc.Create(p.Username, RequestInput{SiteName: body.SiteName, Months: body.Months, Message: body.Message})
|
||||||
|
if err != nil {
|
||||||
|
r.h.writeError(c, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusCreated, req)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListMine : GET /project-requests/mine — demandes du client authentifié.
|
||||||
|
func (r *RequestHandler) ListMine(c *gin.Context) {
|
||||||
|
p := auth.PrincipalFrom(c)
|
||||||
|
if p == nil {
|
||||||
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "non authentifié"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
items, err := r.svc.ListMine(p.Username)
|
||||||
|
if err != nil {
|
||||||
|
r.h.writeError(c, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, gin.H{"items": items})
|
||||||
|
}
|
||||||
|
|
||||||
|
// List : GET /project-requests — toutes les demandes (admin).
|
||||||
|
func (r *RequestHandler) List(c *gin.Context) {
|
||||||
|
items, err := r.svc.List()
|
||||||
|
if err != nil {
|
||||||
|
r.h.writeError(c, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, gin.H{"items": items})
|
||||||
|
}
|
||||||
|
|
||||||
|
// Approve : POST /project-requests/:id/approve — déploie le site (202).
|
||||||
|
func (r *RequestHandler) Approve(c *gin.Context) {
|
||||||
|
var body approveBody
|
||||||
|
if err := c.ShouldBindJSON(&body); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": "requête invalide"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
req, project, err := r.svc.Approve(c.Param("id"), ApproveInput{
|
||||||
|
Months: body.Months,
|
||||||
|
AdminUsername: body.AdminUsername,
|
||||||
|
AdminPassword: body.AdminPassword,
|
||||||
|
AdminNumber: body.AdminNumber,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
r.h.writeError(c, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusAccepted, gin.H{"request": req, "project": project})
|
||||||
|
}
|
||||||
|
|
||||||
|
// Reject : POST /project-requests/:id/reject {"note": "..."}.
|
||||||
|
func (r *RequestHandler) Reject(c *gin.Context) {
|
||||||
|
var body rejectBody
|
||||||
|
if err := c.ShouldBindJSON(&body); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": "requête invalide"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
req, err := r.svc.Reject(c.Param("id"), body.Note)
|
||||||
|
if err != nil {
|
||||||
|
r.h.writeError(c, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, req)
|
||||||
|
}
|
||||||
@@ -0,0 +1,333 @@
|
|||||||
|
package projects
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
|
||||||
|
"github.com/omnex/control-plane/api/internal/auth"
|
||||||
|
"github.com/omnex/control-plane/api/internal/session"
|
||||||
|
)
|
||||||
|
|
||||||
|
func newRequestService(t *testing.T) (*RequestService, *Service, *fakeProv) {
|
||||||
|
t.Helper()
|
||||||
|
psvc, prov, _ := newTestService(t)
|
||||||
|
return NewRequestService(NewMemRequestStore(), psvc), psvc, prov
|
||||||
|
}
|
||||||
|
|
||||||
|
func goodRequest() RequestInput {
|
||||||
|
return RequestInput{SiteName: "Boutique Dupont", Months: 6, Message: "Livraison à Lyon"}
|
||||||
|
}
|
||||||
|
|
||||||
|
func goodApproval() ApproveInput {
|
||||||
|
return ApproveInput{AdminUsername: "dupont", AdminPassword: "un-mot-de-passe-solide", AdminNumber: 2}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRequest_CreateNormalizesUserAndValidatesInput(t *testing.T) {
|
||||||
|
svc, _, _ := newRequestService(t)
|
||||||
|
|
||||||
|
r, err := svc.Create(" Alice ", goodRequest())
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if r.Username != "alice" || r.Status != RequestPending || r.Months != 6 || r.ID == "" {
|
||||||
|
t.Errorf("demande inattendue : %+v", r)
|
||||||
|
}
|
||||||
|
|
||||||
|
bad := []RequestInput{
|
||||||
|
{SiteName: " ", Months: 1},
|
||||||
|
{SiteName: strings.Repeat("x", 65), Months: 1},
|
||||||
|
{SiteName: "ok", Months: 0},
|
||||||
|
{SiteName: "ok", Months: 13},
|
||||||
|
{SiteName: "ok", Months: 1, Message: strings.Repeat("m", 501)},
|
||||||
|
}
|
||||||
|
for i, in := range bad {
|
||||||
|
if _, err := svc.Create("alice", in); err == nil {
|
||||||
|
t.Errorf("saisie invalide n°%d acceptée : %+v", i, in)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRequest_PendingLimitPerClient(t *testing.T) {
|
||||||
|
svc, _, _ := newRequestService(t)
|
||||||
|
for i := 0; i < MaxPendingRequests; i++ {
|
||||||
|
if _, err := svc.Create("alice", goodRequest()); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if _, err := svc.Create("alice", goodRequest()); !errors.Is(err, ErrTooManyRequests) {
|
||||||
|
t.Errorf("erreur %v, attendu ErrTooManyRequests", err)
|
||||||
|
}
|
||||||
|
// La limite est par client.
|
||||||
|
if _, err := svc.Create("bob", goodRequest()); err != nil {
|
||||||
|
t.Errorf("un autre client est bloqué : %v", err)
|
||||||
|
}
|
||||||
|
// Une demande traitée libère une place.
|
||||||
|
mine, _ := svc.ListMine("alice")
|
||||||
|
if _, err := svc.Reject(mine[0].ID, "non"); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := svc.Create("alice", goodRequest()); err != nil {
|
||||||
|
t.Errorf("place non libérée après refus : %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRequest_ListMineIsolatesClients(t *testing.T) {
|
||||||
|
svc, _, _ := newRequestService(t)
|
||||||
|
if _, err := svc.Create("alice", goodRequest()); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := svc.Create("bob", goodRequest()); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
mine, _ := svc.ListMine("ALICE")
|
||||||
|
if len(mine) != 1 || mine[0].Username != "alice" {
|
||||||
|
t.Errorf("fuite entre clients : %+v", mine)
|
||||||
|
}
|
||||||
|
if all, _ := svc.List(); len(all) != 2 {
|
||||||
|
t.Errorf("l'admin doit tout voir : %d", len(all))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRequest_ApproveDeploysSiteOwnedByRequester(t *testing.T) {
|
||||||
|
svc, psvc, prov := newRequestService(t)
|
||||||
|
r, _ := svc.Create("alice", goodRequest())
|
||||||
|
|
||||||
|
got, p, err := svc.Approve(r.ID, goodApproval())
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
<-prov.provisioned
|
||||||
|
if got.Status != RequestApproved || got.ProjectID != p.ID || got.DecidedAt == nil {
|
||||||
|
t.Errorf("demande après validation : %+v", got)
|
||||||
|
}
|
||||||
|
if p.OwnerUsername != "alice" || p.ClientName != "Boutique Dupont" || p.MonthsPurchased != 6 {
|
||||||
|
t.Errorf("projet : owner=%q nom=%q mois=%d (durée demandée attendue)", p.OwnerUsername, p.ClientName, p.MonthsPurchased)
|
||||||
|
}
|
||||||
|
mine, _ := psvc.ListForOwner("alice")
|
||||||
|
if len(mine) != 1 || mine[0].ID != p.ID {
|
||||||
|
t.Errorf("le client ne voit pas son site : %+v", mine)
|
||||||
|
}
|
||||||
|
if other, _ := psvc.ListForOwner("bob"); len(other) != 0 {
|
||||||
|
t.Errorf("un autre client voit le site : %+v", other)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRequest_ApproveCanOverrideMonthsAndOnlyOnce(t *testing.T) {
|
||||||
|
svc, _, prov := newRequestService(t)
|
||||||
|
r, _ := svc.Create("alice", goodRequest())
|
||||||
|
|
||||||
|
in := goodApproval()
|
||||||
|
in.Months = 12
|
||||||
|
_, p, err := svc.Approve(r.ID, in)
|
||||||
|
if err != nil || p.MonthsPurchased != 12 {
|
||||||
|
t.Fatalf("err=%v mois=%d, attendu 12", err, p.MonthsPurchased)
|
||||||
|
}
|
||||||
|
<-prov.provisioned
|
||||||
|
|
||||||
|
if _, _, err := svc.Approve(r.ID, goodApproval()); !errors.Is(err, ErrRequestDecided) {
|
||||||
|
t.Errorf("double validation : %v, attendu ErrRequestDecided", err)
|
||||||
|
}
|
||||||
|
if _, err := svc.Reject(r.ID, "trop tard"); !errors.Is(err, ErrRequestDecided) {
|
||||||
|
t.Errorf("refus après validation : %v", err)
|
||||||
|
}
|
||||||
|
if len(prov.specs) != 1 {
|
||||||
|
t.Errorf("%d sites déployés pour une seule demande", len(prov.specs))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRequest_InvalidApprovalKeepsRequestPending(t *testing.T) {
|
||||||
|
svc, psvc, _ := newRequestService(t)
|
||||||
|
r, _ := svc.Create("alice", goodRequest())
|
||||||
|
|
||||||
|
weak := goodApproval()
|
||||||
|
weak.AdminPassword = "court"
|
||||||
|
if _, _, err := svc.Approve(r.ID, weak); !errors.Is(err, ErrWeakAdminPass) {
|
||||||
|
t.Fatalf("erreur %v, attendu ErrWeakAdminPass", err)
|
||||||
|
}
|
||||||
|
if got, _ := svc.store.Get(r.ID); got.Status != RequestPending || got.ProjectID != "" {
|
||||||
|
t.Errorf("la demande a changé malgré l'échec : %+v", got)
|
||||||
|
}
|
||||||
|
if all, _ := psvc.List(); len(all) != 0 {
|
||||||
|
t.Errorf("projet créé malgré l'échec : %+v", all)
|
||||||
|
}
|
||||||
|
if _, _, err := svc.Approve("inconnue", goodApproval()); !errors.Is(err, ErrRequestNotFound) {
|
||||||
|
t.Errorf("erreur %v, attendu ErrRequestNotFound", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRequest_RejectStoresNote(t *testing.T) {
|
||||||
|
svc, _, _ := newRequestService(t)
|
||||||
|
r, _ := svc.Create("alice", goodRequest())
|
||||||
|
got, err := svc.Reject(r.ID, " Paiement non reçu ")
|
||||||
|
if err != nil || got.Status != RequestRejected || got.AdminNote != "Paiement non reçu" || got.DecidedAt == nil {
|
||||||
|
t.Errorf("err=%v demande=%+v", err, got)
|
||||||
|
}
|
||||||
|
if _, err := svc.Reject(r.ID, strings.Repeat("n", 501)); !errors.Is(err, ErrRequestDecided) && !errors.Is(err, ErrInvalidMessage) {
|
||||||
|
t.Errorf("erreur inattendue : %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- HTTP : autorisations réelles (JWT + session + rôle), comme en production ---
|
||||||
|
|
||||||
|
type httpFixture struct {
|
||||||
|
r *gin.Engine
|
||||||
|
tokens map[string]string
|
||||||
|
prov *fakeProv
|
||||||
|
}
|
||||||
|
|
||||||
|
func newHTTPFixture(t *testing.T) *httpFixture {
|
||||||
|
t.Helper()
|
||||||
|
gin.SetMode(gin.TestMode)
|
||||||
|
psvc, prov, _ := newTestService(t)
|
||||||
|
h := NewHandler(psvc)
|
||||||
|
rh := NewRequestHandler(NewRequestService(NewMemRequestStore(), psvc), h)
|
||||||
|
|
||||||
|
iss := auth.NewIssuer([]byte("0123456789abcdef0123456789abcdef"), time.Hour)
|
||||||
|
mgr := session.NewMemManager(time.Hour)
|
||||||
|
tokens := map[string]string{}
|
||||||
|
for user, role := range map[string]auth.Role{"alice": auth.RoleClient, "bob": auth.RoleClient, "root": auth.RoleAdmin} {
|
||||||
|
sid, err := mgr.Create(context.Background(), session.Session{UserID: user, Role: string(role)})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
tok, err := iss.Issue(user, user, role, sid)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
tokens[user] = tok
|
||||||
|
}
|
||||||
|
|
||||||
|
r := gin.New()
|
||||||
|
authed := r.Group("")
|
||||||
|
authed.Use(auth.RequireAuth(iss, mgr))
|
||||||
|
client := authed.Group("")
|
||||||
|
client.Use(auth.RequireRole(auth.RoleClient))
|
||||||
|
client.POST("/project-requests", rh.Create)
|
||||||
|
client.GET("/project-requests/mine", rh.ListMine)
|
||||||
|
client.GET("/projects/mine", h.ListMine)
|
||||||
|
admin := authed.Group("")
|
||||||
|
admin.Use(auth.RequireRole(auth.RoleAdmin))
|
||||||
|
admin.GET("/project-requests", rh.List)
|
||||||
|
admin.POST("/project-requests/:id/approve", rh.Approve)
|
||||||
|
admin.POST("/project-requests/:id/reject", rh.Reject)
|
||||||
|
return &httpFixture{r: r, tokens: tokens, prov: prov}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *httpFixture) do(user, method, path, body string) *httptest.ResponseRecorder {
|
||||||
|
req := httptest.NewRequest(method, path, strings.NewReader(body))
|
||||||
|
req.Header.Set("Content-Type", "application/json")
|
||||||
|
if tok, ok := f.tokens[user]; ok {
|
||||||
|
req.Header.Set("Authorization", "Bearer "+tok)
|
||||||
|
}
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
f.r.ServeHTTP(w, req)
|
||||||
|
return w
|
||||||
|
}
|
||||||
|
|
||||||
|
const requestJSON = `{"site_name":"Boutique Dupont","months":3,"message":"bonjour"}`
|
||||||
|
const approveJSON = `{"admin_username":"dupont","admin_password":"un-mot-de-passe-solide"}`
|
||||||
|
|
||||||
|
func TestHTTPRequests_AuthorizationMatrix(t *testing.T) {
|
||||||
|
f := newHTTPFixture(t)
|
||||||
|
|
||||||
|
// Sans compte : rien n'est accessible.
|
||||||
|
for _, c := range []struct{ method, path string }{
|
||||||
|
{"POST", "/project-requests"}, {"GET", "/project-requests/mine"}, {"GET", "/projects/mine"},
|
||||||
|
{"GET", "/project-requests"}, {"POST", "/project-requests/x/approve"}, {"POST", "/project-requests/x/reject"},
|
||||||
|
} {
|
||||||
|
if w := f.do("", c.method, c.path, `{}`); w.Code != http.StatusUnauthorized {
|
||||||
|
t.Errorf("anonyme %s %s : %d, attendu 401", c.method, c.path, w.Code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
w := f.do("alice", "POST", "/project-requests", requestJSON)
|
||||||
|
if w.Code != http.StatusCreated {
|
||||||
|
t.Fatalf("création : %d %s", w.Code, w.Body)
|
||||||
|
}
|
||||||
|
var created Request
|
||||||
|
_ = json.Unmarshal(w.Body.Bytes(), &created)
|
||||||
|
|
||||||
|
// Un client ne décide jamais et ne voit pas la liste globale.
|
||||||
|
for _, c := range []struct{ method, path, body string }{
|
||||||
|
{"GET", "/project-requests", ""},
|
||||||
|
{"POST", "/project-requests/" + created.ID + "/approve", approveJSON},
|
||||||
|
{"POST", "/project-requests/" + created.ID + "/reject", `{}`},
|
||||||
|
} {
|
||||||
|
if w := f.do("alice", c.method, c.path, c.body); w.Code != http.StatusForbidden {
|
||||||
|
t.Errorf("client %s %s : %d, attendu 403", c.method, c.path, w.Code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(f.prov.specs) != 0 {
|
||||||
|
t.Fatal("un client a déclenché un déploiement")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Bob ne voit pas la demande d'Alice.
|
||||||
|
w = f.do("bob", "GET", "/project-requests/mine", "")
|
||||||
|
var bob struct{ Items []Request }
|
||||||
|
_ = json.Unmarshal(w.Body.Bytes(), &bob)
|
||||||
|
if w.Code != http.StatusOK || len(bob.Items) != 0 {
|
||||||
|
t.Errorf("bob voit la demande d'alice : %d %s", w.Code, w.Body)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestHTTPRequests_ApproveFlowAndOwnership(t *testing.T) {
|
||||||
|
f := newHTTPFixture(t)
|
||||||
|
w := f.do("alice", "POST", "/project-requests", requestJSON)
|
||||||
|
var created Request
|
||||||
|
_ = json.Unmarshal(w.Body.Bytes(), &created)
|
||||||
|
|
||||||
|
if w := f.do("root", "POST", "/project-requests/"+created.ID+"/approve", `{"admin_username":"x","admin_password":"court"}`); w.Code != http.StatusBadRequest {
|
||||||
|
t.Errorf("saisie invalide : %d, attendu 400", w.Code)
|
||||||
|
}
|
||||||
|
w = f.do("root", "POST", "/project-requests/"+created.ID+"/approve", approveJSON)
|
||||||
|
if w.Code != http.StatusAccepted {
|
||||||
|
t.Fatalf("validation : %d %s", w.Code, w.Body)
|
||||||
|
}
|
||||||
|
<-f.prov.provisioned
|
||||||
|
if strings.Contains(w.Body.String(), "un-mot-de-passe-solide") {
|
||||||
|
t.Error("le mot de passe admin est renvoyé dans la réponse")
|
||||||
|
}
|
||||||
|
if w := f.do("root", "POST", "/project-requests/"+created.ID+"/approve", approveJSON); w.Code != http.StatusConflict {
|
||||||
|
t.Errorf("double validation : %d, attendu 409", w.Code)
|
||||||
|
}
|
||||||
|
|
||||||
|
w = f.do("alice", "GET", "/projects/mine", "")
|
||||||
|
var mine struct{ Items []Project }
|
||||||
|
_ = json.Unmarshal(w.Body.Bytes(), &mine)
|
||||||
|
if len(mine.Items) != 1 || mine.Items[0].OwnerUsername != "alice" {
|
||||||
|
t.Errorf("sites d'alice : %s", w.Body)
|
||||||
|
}
|
||||||
|
w = f.do("bob", "GET", "/projects/mine", "")
|
||||||
|
_ = json.Unmarshal(w.Body.Bytes(), &mine)
|
||||||
|
if len(mine.Items) != 0 {
|
||||||
|
t.Errorf("bob voit le site d'alice : %s", w.Body)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestHTTPRequests_ValidationAndRateLimitCodes(t *testing.T) {
|
||||||
|
f := newHTTPFixture(t)
|
||||||
|
for _, body := range []string{`{`, `{"site_name":"","months":3}`, `{"site_name":"x","months":13}`, `{"site_name":"x","months":0}`} {
|
||||||
|
if w := f.do("alice", "POST", "/project-requests", body); w.Code != http.StatusBadRequest {
|
||||||
|
t.Errorf("%s : %d, attendu 400", body, w.Code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for i := 0; i < MaxPendingRequests; i++ {
|
||||||
|
if w := f.do("alice", "POST", "/project-requests", requestJSON); w.Code != http.StatusCreated {
|
||||||
|
t.Fatalf("demande %d : %d", i, w.Code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if w := f.do("alice", "POST", "/project-requests", requestJSON); w.Code != http.StatusTooManyRequests {
|
||||||
|
t.Errorf("au-delà de la limite : %d, attendu 429", w.Code)
|
||||||
|
}
|
||||||
|
if w := f.do("root", "POST", "/project-requests/inconnue/reject", `{}`); w.Code != http.StatusNotFound {
|
||||||
|
t.Errorf("demande inconnue : %d, attendu 404", w.Code)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -12,6 +12,7 @@ import (
|
|||||||
|
|
||||||
"github.com/google/uuid"
|
"github.com/google/uuid"
|
||||||
|
|
||||||
|
"github.com/omnex/control-plane/api/internal/auth"
|
||||||
"github.com/omnex/control-plane/api/internal/demos"
|
"github.com/omnex/control-plane/api/internal/demos"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -65,6 +66,8 @@ type CreateInput struct {
|
|||||||
AdminUsername string
|
AdminUsername string
|
||||||
AdminPassword string
|
AdminPassword string
|
||||||
AdminNumber int // 0 => DefaultAdminNumber
|
AdminNumber int // 0 => DefaultAdminNumber
|
||||||
|
// OwnerUsername : compte client propriétaire (voir Request), facultatif.
|
||||||
|
OwnerUsername string
|
||||||
}
|
}
|
||||||
|
|
||||||
// Validate normalise et valide la saisie.
|
// Validate normalise et valide la saisie.
|
||||||
@@ -141,6 +144,7 @@ func (s *Service) Create(in CreateInput) (Project, error) {
|
|||||||
URL: "https://" + host,
|
URL: "https://" + host,
|
||||||
AdminUsername: in.AdminUsername,
|
AdminUsername: in.AdminUsername,
|
||||||
AdminNumber: in.AdminNumber,
|
AdminNumber: in.AdminNumber,
|
||||||
|
OwnerUsername: auth.NormalizeUsername(in.OwnerUsername),
|
||||||
MonthsPurchased: in.Months,
|
MonthsPurchased: in.Months,
|
||||||
CreatedAt: now,
|
CreatedAt: now,
|
||||||
ExpiresAt: expires,
|
ExpiresAt: expires,
|
||||||
@@ -190,6 +194,22 @@ func (s *Service) Get(id string) (Project, error) {
|
|||||||
|
|
||||||
func (s *Service) List() ([]Project, error) { return s.store.List() }
|
func (s *Service) List() ([]Project, error) { return s.store.List() }
|
||||||
|
|
||||||
|
// ListForOwner : sites du client (hors supprimés), du plus récent au plus ancien.
|
||||||
|
func (s *Service) ListForOwner(username string) ([]Project, error) {
|
||||||
|
username = auth.NormalizeUsername(username)
|
||||||
|
all, err := s.store.List()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
out := []Project{}
|
||||||
|
for _, p := range all {
|
||||||
|
if p.OwnerUsername == username && p.Status != StatusDeleted {
|
||||||
|
out = append(out, p)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|
||||||
// State : état live des composants du projet (phase + CPU/mémoire). Un projet
|
// State : état live des composants du projet (phase + CPU/mémoire). Un projet
|
||||||
// qui n'a pas (ou plus) de pods (échec, suppression) renvoie un état vide sans
|
// qui n'a pas (ou plus) de pods (échec, suppression) renvoie un état vide sans
|
||||||
// interroger le cluster.
|
// interroger le cluster.
|
||||||
|
|||||||
@@ -25,6 +25,7 @@ type Deps struct {
|
|||||||
AuthH *auth.Handler
|
AuthH *auth.Handler
|
||||||
DemosH *demos.Handler
|
DemosH *demos.Handler
|
||||||
ProjectsH *projects.Handler
|
ProjectsH *projects.Handler
|
||||||
|
RequestsH *projects.RequestHandler
|
||||||
SubH *sub.Handler
|
SubH *sub.Handler
|
||||||
ProfileH *profile.Handler
|
ProfileH *profile.Handler
|
||||||
DownloadsH *downloads.Handler
|
DownloadsH *downloads.Handler
|
||||||
@@ -88,6 +89,14 @@ func New(d Deps) *gin.Engine {
|
|||||||
if d.DemosH != nil {
|
if d.DemosH != nil {
|
||||||
client.GET("/demos/mine", d.DemosH.ListMine)
|
client.GET("/demos/mine", d.DemosH.ListMine)
|
||||||
}
|
}
|
||||||
|
// Un client demande un site vitrine puis suit ses demandes et ses sites.
|
||||||
|
if d.RequestsH != nil {
|
||||||
|
client.POST("/project-requests", httpx.RateLimit(0.2, 5), d.RequestsH.Create)
|
||||||
|
client.GET("/project-requests/mine", d.RequestsH.ListMine)
|
||||||
|
}
|
||||||
|
if d.ProjectsH != nil {
|
||||||
|
client.GET("/projects/mine", d.ProjectsH.ListMine)
|
||||||
|
}
|
||||||
if d.DownloadsH != nil {
|
if d.DownloadsH != nil {
|
||||||
client.GET("/apps", d.DownloadsH.List)
|
client.GET("/apps", d.DownloadsH.List)
|
||||||
client.GET("/apps/:name", d.DownloadsH.Download)
|
client.GET("/apps/:name", d.DownloadsH.Download)
|
||||||
@@ -122,6 +131,11 @@ func New(d Deps) *gin.Engine {
|
|||||||
admin.POST("/projects/:id/extend", d.ProjectsH.Extend)
|
admin.POST("/projects/:id/extend", d.ProjectsH.Extend)
|
||||||
admin.POST("/projects/:id/domain", d.ProjectsH.SetDomain)
|
admin.POST("/projects/:id/domain", d.ProjectsH.SetDomain)
|
||||||
}
|
}
|
||||||
|
if d.RequestsH != nil {
|
||||||
|
admin.GET("/project-requests", d.RequestsH.List)
|
||||||
|
admin.POST("/project-requests/:id/approve", d.RequestsH.Approve)
|
||||||
|
admin.POST("/project-requests/:id/reject", d.RequestsH.Reject)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return r
|
return r
|
||||||
|
|||||||
Vendored
-1510
File diff suppressed because one or more lines are too long
Vendored
+1510
File diff suppressed because one or more lines are too long
Vendored
+1
-1
@@ -5,7 +5,7 @@
|
|||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
<title>Omnex — Plateforme de gestion de commandes & livraison</title>
|
<title>Omnex — Plateforme de gestion de commandes & livraison</title>
|
||||||
<meta name="description" content="Déployez en un clic une démo complète de la plateforme de gestion de commandes et de livraison." />
|
<meta name="description" content="Déployez en un clic une démo complète de la plateforme de gestion de commandes et de livraison." />
|
||||||
<script type="module" crossorigin src="/assets/index-BdLZEtG3.js"></script>
|
<script type="module" crossorigin src="/assets/index-DfAn10bD.js"></script>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<div id="root"></div>
|
<div id="root"></div>
|
||||||
|
|||||||
@@ -20,6 +20,7 @@ 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'
|
||||||
import { MyDemoPlat } from './pages/backoffice/MyDemoPlat'
|
import { MyDemoPlat } from './pages/backoffice/MyDemoPlat'
|
||||||
|
import { MySites } from './pages/backoffice/MySites'
|
||||||
|
|
||||||
// Chemins admin uniquement : un accès non authentifié y renvoie vers la
|
// Chemins admin uniquement : un accès non authentifié y renvoie vers la
|
||||||
// page de connexion admin plutôt que la page client.
|
// page de connexion admin plutôt que la page client.
|
||||||
@@ -122,6 +123,7 @@ export function App() {
|
|||||||
<Route path="downloads" element={<AppDownloads />} />
|
<Route path="downloads" element={<AppDownloads />} />
|
||||||
<Route path="profile" element={<Profile />} />
|
<Route path="profile" element={<Profile />} />
|
||||||
<Route path="myservices" element={<MyDemoPlat />} />
|
<Route path="myservices" element={<MyDemoPlat />} />
|
||||||
|
<Route path="sites" element={<MySites />} />
|
||||||
</Route>
|
</Route>
|
||||||
|
|
||||||
<Route path="*" element={<Navigate to="/" replace />} />
|
<Route path="*" element={<Navigate to="/" replace />} />
|
||||||
|
|||||||
@@ -76,6 +76,7 @@ export function BackofficeLayout() {
|
|||||||
{isClient && <NavItem to="/app/downloads">Applications</NavItem>}
|
{isClient && <NavItem to="/app/downloads">Applications</NavItem>}
|
||||||
{(isAdmin || isClient) && <NavItem to="/app/profile">Profile</NavItem>}
|
{(isAdmin || isClient) && <NavItem to="/app/profile">Profile</NavItem>}
|
||||||
{isClient && <NavItem to="/app/myservices">{isPremium ? 'Ma plateforme' : 'Ma démo'}</NavItem>}
|
{isClient && <NavItem to="/app/myservices">{isPremium ? 'Ma plateforme' : 'Ma démo'}</NavItem>}
|
||||||
|
{isClient && <NavItem to="/app/sites">Mes sites</NavItem>}
|
||||||
{isAdmin && <NavItem to="/app/demos">Démos</NavItem>}
|
{isAdmin && <NavItem to="/app/demos">Démos</NavItem>}
|
||||||
{isAdmin && <NavItem to="/app/premium">Premium</NavItem>}
|
{isAdmin && <NavItem to="/app/premium">Premium</NavItem>}
|
||||||
{isAdmin && <NavItem to="/app/projects">Projets</NavItem>}
|
{isAdmin && <NavItem to="/app/projects">Projets</NavItem>}
|
||||||
@@ -125,6 +126,11 @@ export function BackofficeLayout() {
|
|||||||
Applications
|
Applications
|
||||||
</NavItem>
|
</NavItem>
|
||||||
)}
|
)}
|
||||||
|
{isClient && (
|
||||||
|
<NavItem to="/app/sites" onClick={onClose} mobile>
|
||||||
|
Mes sites
|
||||||
|
</NavItem>
|
||||||
|
)}
|
||||||
{isAdmin && (
|
{isAdmin && (
|
||||||
<NavItem to="/app/demos" onClick={onClose} mobile>
|
<NavItem to="/app/demos" onClick={onClose} mobile>
|
||||||
Démos
|
Démos
|
||||||
|
|||||||
@@ -0,0 +1,190 @@
|
|||||||
|
import { useEffect, useState } from 'react'
|
||||||
|
import {
|
||||||
|
Button,
|
||||||
|
FormControl,
|
||||||
|
FormHelperText,
|
||||||
|
FormLabel,
|
||||||
|
Input,
|
||||||
|
Modal,
|
||||||
|
ModalBody,
|
||||||
|
ModalCloseButton,
|
||||||
|
ModalContent,
|
||||||
|
ModalFooter,
|
||||||
|
ModalHeader,
|
||||||
|
ModalOverlay,
|
||||||
|
NumberDecrementStepper,
|
||||||
|
NumberIncrementStepper,
|
||||||
|
NumberInput,
|
||||||
|
NumberInputField,
|
||||||
|
NumberInputStepper,
|
||||||
|
Select,
|
||||||
|
Stack,
|
||||||
|
Text,
|
||||||
|
useToast,
|
||||||
|
} from '@chakra-ui/react'
|
||||||
|
import { api, ApiError, type ProjectRequest } from '../lib/api'
|
||||||
|
import { PROJECT_MONTHS, monthsLabel } from '../lib/format'
|
||||||
|
import { PasswordInput } from './PasswordInput'
|
||||||
|
|
||||||
|
interface ProcessRequestModalProps {
|
||||||
|
request: ProjectRequest | null
|
||||||
|
onClose: () => void
|
||||||
|
onDone: () => void
|
||||||
|
}
|
||||||
|
|
||||||
|
const MIN_PASSWORD = 12
|
||||||
|
|
||||||
|
// Traitement d'une demande de site par l'admin : validation (déploie le site
|
||||||
|
// pour la durée convenue, avec son compte admin) ou refus avec un motif.
|
||||||
|
export function ProcessRequestModal({ request, onClose, onDone }: ProcessRequestModalProps) {
|
||||||
|
const toast = useToast()
|
||||||
|
const [months, setMonths] = useState(1)
|
||||||
|
const [adminUsername, setAdminUsername] = useState('')
|
||||||
|
const [adminPassword, setAdminPassword] = useState('')
|
||||||
|
const [adminNumber, setAdminNumber] = useState(1)
|
||||||
|
const [note, setNote] = useState('')
|
||||||
|
const [busy, setBusy] = useState<'approve' | 'reject' | null>(null)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
setMonths(request?.months ?? 1)
|
||||||
|
setAdminUsername('')
|
||||||
|
setAdminPassword('')
|
||||||
|
setAdminNumber(1)
|
||||||
|
setNote('')
|
||||||
|
}, [request])
|
||||||
|
|
||||||
|
const usernameOk = /^[A-Za-z0-9]{3,64}$/.test(adminUsername)
|
||||||
|
const valid = usernameOk && adminPassword.length >= MIN_PASSWORD && adminNumber >= 1
|
||||||
|
|
||||||
|
const handleClose = () => {
|
||||||
|
if (busy) return
|
||||||
|
onClose()
|
||||||
|
}
|
||||||
|
|
||||||
|
const approve = async () => {
|
||||||
|
if (!request) return
|
||||||
|
setBusy('approve')
|
||||||
|
try {
|
||||||
|
await api.approveProjectRequest(request.id, { months, adminUsername, adminPassword, adminNumber })
|
||||||
|
toast({ status: 'success', title: 'Déploiement lancé', description: `${request.site_name} · ${monthsLabel(months)}` })
|
||||||
|
onDone()
|
||||||
|
onClose()
|
||||||
|
} catch (err) {
|
||||||
|
const msg = err instanceof ApiError ? err.message : 'Erreur'
|
||||||
|
toast({ status: 'error', title: 'Validation impossible', description: msg })
|
||||||
|
} finally {
|
||||||
|
setBusy(null)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const reject = async () => {
|
||||||
|
if (!request) return
|
||||||
|
setBusy('reject')
|
||||||
|
try {
|
||||||
|
await api.rejectProjectRequest(request.id, note.trim())
|
||||||
|
toast({ status: 'success', title: 'Demande refusée' })
|
||||||
|
onDone()
|
||||||
|
onClose()
|
||||||
|
} catch (err) {
|
||||||
|
const msg = err instanceof ApiError ? err.message : 'Erreur'
|
||||||
|
toast({ status: 'error', title: 'Refus impossible', description: msg })
|
||||||
|
} finally {
|
||||||
|
setBusy(null)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Modal isOpen={!!request} onClose={handleClose} closeOnOverlayClick={!busy}>
|
||||||
|
<ModalOverlay />
|
||||||
|
<ModalContent>
|
||||||
|
<ModalHeader>Demande de {request?.username}</ModalHeader>
|
||||||
|
<ModalCloseButton isDisabled={!!busy} />
|
||||||
|
<ModalBody>
|
||||||
|
<Stack spacing={4}>
|
||||||
|
<Stack spacing={1} fontSize="sm">
|
||||||
|
<Text>
|
||||||
|
<b>Site :</b> {request?.site_name}
|
||||||
|
</Text>
|
||||||
|
<Text>
|
||||||
|
<b>Durée demandée :</b> {request ? monthsLabel(request.months) : ''}
|
||||||
|
</Text>
|
||||||
|
{request?.message && (
|
||||||
|
<Text whiteSpace="pre-wrap">
|
||||||
|
<b>Message :</b> {request.message}
|
||||||
|
</Text>
|
||||||
|
)}
|
||||||
|
</Stack>
|
||||||
|
|
||||||
|
<FormControl isRequired>
|
||||||
|
<FormLabel fontSize="sm">Durée à déployer</FormLabel>
|
||||||
|
<Select value={months} onChange={(e) => setMonths(Number(e.target.value))} isDisabled={!!busy}>
|
||||||
|
{PROJECT_MONTHS.map((m) => (
|
||||||
|
<option key={m} value={m}>
|
||||||
|
{monthsLabel(m)}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</Select>
|
||||||
|
<FormHelperText>À valider une fois le paiement reçu : le site est déployé aussitôt.</FormHelperText>
|
||||||
|
</FormControl>
|
||||||
|
|
||||||
|
<FormControl isRequired isInvalid={adminUsername !== '' && !usernameOk}>
|
||||||
|
<FormLabel fontSize="sm">Identifiant admin du site</FormLabel>
|
||||||
|
<Input
|
||||||
|
value={adminUsername}
|
||||||
|
maxLength={64}
|
||||||
|
onChange={(e) => setAdminUsername(e.target.value)}
|
||||||
|
isDisabled={!!busy}
|
||||||
|
autoComplete="off"
|
||||||
|
/>
|
||||||
|
<FormHelperText>3 à 64 caractères alphanumériques.</FormHelperText>
|
||||||
|
</FormControl>
|
||||||
|
|
||||||
|
<FormControl isRequired isInvalid={adminPassword !== '' && adminPassword.length < MIN_PASSWORD}>
|
||||||
|
<FormLabel fontSize="sm">Mot de passe admin du site</FormLabel>
|
||||||
|
<PasswordInput
|
||||||
|
value={adminPassword}
|
||||||
|
onChange={(e) => setAdminPassword(e.target.value)}
|
||||||
|
isDisabled={!!busy}
|
||||||
|
autoComplete="new-password"
|
||||||
|
/>
|
||||||
|
<FormHelperText>{MIN_PASSWORD} caractères minimum, à transmettre au client. Il n'est pas conservé.</FormHelperText>
|
||||||
|
</FormControl>
|
||||||
|
|
||||||
|
<FormControl isRequired>
|
||||||
|
<FormLabel fontSize="sm">Nombre d'admins autorisés</FormLabel>
|
||||||
|
<NumberInput
|
||||||
|
min={1}
|
||||||
|
max={20}
|
||||||
|
value={adminNumber}
|
||||||
|
onChange={(_, n) => setAdminNumber(Number.isNaN(n) ? 1 : n)}
|
||||||
|
isDisabled={!!busy}
|
||||||
|
>
|
||||||
|
<NumberInputField />
|
||||||
|
<NumberInputStepper>
|
||||||
|
<NumberIncrementStepper />
|
||||||
|
<NumberDecrementStepper />
|
||||||
|
</NumberInputStepper>
|
||||||
|
</NumberInput>
|
||||||
|
</FormControl>
|
||||||
|
|
||||||
|
<FormControl>
|
||||||
|
<FormLabel fontSize="sm">Motif de refus (visible du client)</FormLabel>
|
||||||
|
<Input value={note} maxLength={500} onChange={(e) => setNote(e.target.value)} isDisabled={!!busy} />
|
||||||
|
</FormControl>
|
||||||
|
</Stack>
|
||||||
|
</ModalBody>
|
||||||
|
<ModalFooter gap={2}>
|
||||||
|
<Button variant="ghost" onClick={handleClose} isDisabled={!!busy}>
|
||||||
|
Annuler
|
||||||
|
</Button>
|
||||||
|
<Button colorScheme="red" variant="outline" onClick={reject} isLoading={busy === 'reject'} isDisabled={busy === 'approve'}>
|
||||||
|
Refuser
|
||||||
|
</Button>
|
||||||
|
<Button colorScheme="primary" onClick={approve} isLoading={busy === 'approve'} isDisabled={!valid || busy === 'reject'}>
|
||||||
|
Valider et déployer
|
||||||
|
</Button>
|
||||||
|
</ModalFooter>
|
||||||
|
</ModalContent>
|
||||||
|
</Modal>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,115 @@
|
|||||||
|
import { useState } from 'react'
|
||||||
|
import {
|
||||||
|
Button,
|
||||||
|
FormControl,
|
||||||
|
FormHelperText,
|
||||||
|
FormLabel,
|
||||||
|
Input,
|
||||||
|
Modal,
|
||||||
|
ModalBody,
|
||||||
|
ModalCloseButton,
|
||||||
|
ModalContent,
|
||||||
|
ModalFooter,
|
||||||
|
ModalHeader,
|
||||||
|
ModalOverlay,
|
||||||
|
Select,
|
||||||
|
Stack,
|
||||||
|
Textarea,
|
||||||
|
useToast,
|
||||||
|
} from '@chakra-ui/react'
|
||||||
|
import { api, ApiError } from '../lib/api'
|
||||||
|
import { PROJECT_MONTHS, monthsLabel } from '../lib/format'
|
||||||
|
|
||||||
|
interface RequestSiteModalProps {
|
||||||
|
isOpen: boolean
|
||||||
|
onClose: () => void
|
||||||
|
onCreated: () => void
|
||||||
|
}
|
||||||
|
|
||||||
|
// Demande d'achat d'un site vitrine par un client connecté. Rien n'est déployé
|
||||||
|
// ni facturé ici : l'équipe Omnex valide la demande, puis déploie le site.
|
||||||
|
export function RequestSiteModal({ isOpen, onClose, onCreated }: RequestSiteModalProps) {
|
||||||
|
const toast = useToast()
|
||||||
|
const [siteName, setSiteName] = useState('')
|
||||||
|
const [months, setMonths] = useState(12)
|
||||||
|
const [message, setMessage] = useState('')
|
||||||
|
const [saving, setSaving] = useState(false)
|
||||||
|
|
||||||
|
const reset = () => {
|
||||||
|
setSiteName('')
|
||||||
|
setMonths(12)
|
||||||
|
setMessage('')
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleClose = () => {
|
||||||
|
if (saving) return
|
||||||
|
reset()
|
||||||
|
onClose()
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleSend = async () => {
|
||||||
|
setSaving(true)
|
||||||
|
try {
|
||||||
|
await api.createProjectRequest({ siteName: siteName.trim(), months, message: message.trim() })
|
||||||
|
toast({ status: 'success', title: 'Demande envoyée', description: 'Nous revenons vers vous rapidement.' })
|
||||||
|
reset()
|
||||||
|
onCreated()
|
||||||
|
onClose()
|
||||||
|
} catch (err) {
|
||||||
|
const msg = err instanceof ApiError ? err.message : 'Erreur'
|
||||||
|
toast({ status: 'error', title: 'Envoi impossible', description: msg })
|
||||||
|
} finally {
|
||||||
|
setSaving(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Modal isOpen={isOpen} onClose={handleClose} closeOnOverlayClick={!saving}>
|
||||||
|
<ModalOverlay />
|
||||||
|
<ModalContent>
|
||||||
|
<ModalHeader>Demander un site vitrine</ModalHeader>
|
||||||
|
<ModalCloseButton isDisabled={saving} />
|
||||||
|
<ModalBody>
|
||||||
|
<Stack spacing={4}>
|
||||||
|
<FormControl isRequired>
|
||||||
|
<FormLabel fontSize="sm">Nom du site</FormLabel>
|
||||||
|
<Input value={siteName} maxLength={64} onChange={(e) => setSiteName(e.target.value)} isDisabled={saving} />
|
||||||
|
</FormControl>
|
||||||
|
|
||||||
|
<FormControl isRequired>
|
||||||
|
<FormLabel fontSize="sm">Durée souhaitée</FormLabel>
|
||||||
|
<Select value={months} onChange={(e) => setMonths(Number(e.target.value))} isDisabled={saving}>
|
||||||
|
{PROJECT_MONTHS.map((m) => (
|
||||||
|
<option key={m} value={m}>
|
||||||
|
{monthsLabel(m)}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</Select>
|
||||||
|
<FormHelperText>Le tarif vous est communiqué par l'équipe avant toute validation.</FormHelperText>
|
||||||
|
</FormControl>
|
||||||
|
|
||||||
|
<FormControl>
|
||||||
|
<FormLabel fontSize="sm">Message (facultatif)</FormLabel>
|
||||||
|
<Textarea
|
||||||
|
value={message}
|
||||||
|
maxLength={500}
|
||||||
|
rows={4}
|
||||||
|
onChange={(e) => setMessage(e.target.value)}
|
||||||
|
isDisabled={saving}
|
||||||
|
placeholder="Votre activité, un nom de domaine souhaité, des besoins particuliers…"
|
||||||
|
/>
|
||||||
|
</FormControl>
|
||||||
|
</Stack>
|
||||||
|
</ModalBody>
|
||||||
|
<ModalFooter>
|
||||||
|
<Button variant="ghost" mr={3} onClick={handleClose} isDisabled={saving}>
|
||||||
|
Annuler
|
||||||
|
</Button>
|
||||||
|
<Button colorScheme="primary" onClick={handleSend} isLoading={saving} isDisabled={siteName.trim() === ''}>
|
||||||
|
Envoyer la demande
|
||||||
|
</Button>
|
||||||
|
</ModalFooter>
|
||||||
|
</ModalContent>
|
||||||
|
</Modal>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -84,6 +84,35 @@ export interface Project {
|
|||||||
expires_at: string
|
expires_at: string
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Demande d'achat d'un site vitrine par un client, à valider par l'admin.
|
||||||
|
export type ProjectRequestStatus = 'pending' | 'approved' | 'rejected'
|
||||||
|
|
||||||
|
export interface ProjectRequest {
|
||||||
|
id: string
|
||||||
|
username: string
|
||||||
|
site_name: string
|
||||||
|
months: number
|
||||||
|
message?: string
|
||||||
|
status: ProjectRequestStatus
|
||||||
|
admin_note?: string
|
||||||
|
project_id?: string
|
||||||
|
created_at: string
|
||||||
|
decided_at?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CreateProjectRequestParams {
|
||||||
|
siteName: string
|
||||||
|
months: number
|
||||||
|
message: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ApproveProjectRequestParams {
|
||||||
|
months?: number
|
||||||
|
adminUsername: string
|
||||||
|
adminPassword: string
|
||||||
|
adminNumber: number
|
||||||
|
}
|
||||||
|
|
||||||
export interface CreateProjectParams {
|
export interface CreateProjectParams {
|
||||||
clientName: string
|
clientName: string
|
||||||
months: number
|
months: number
|
||||||
@@ -260,6 +289,26 @@ export const api = {
|
|||||||
admin_password: params.adminPassword,
|
admin_password: params.adminPassword,
|
||||||
admin_number: params.adminNumber,
|
admin_number: params.adminNumber,
|
||||||
}),
|
}),
|
||||||
|
// --- Espace client : demander un site vitrine, suivre ses sites ---
|
||||||
|
createProjectRequest: (p: CreateProjectRequestParams) =>
|
||||||
|
request<ProjectRequest>('POST', '/project-requests', {
|
||||||
|
site_name: p.siteName,
|
||||||
|
months: p.months,
|
||||||
|
message: p.message,
|
||||||
|
}),
|
||||||
|
listMyProjectRequests: () => request<{ items: ProjectRequest[] }>('GET', '/project-requests/mine'),
|
||||||
|
listMyProjects: () => request<{ items: Project[] }>('GET', '/projects/mine'),
|
||||||
|
// --- Admin : traiter les demandes ---
|
||||||
|
listProjectRequests: () => request<{ items: ProjectRequest[] }>('GET', '/project-requests'),
|
||||||
|
approveProjectRequest: (id: string, p: ApproveProjectRequestParams) =>
|
||||||
|
request<{ request: ProjectRequest; project: Project }>('POST', `/project-requests/${id}/approve`, {
|
||||||
|
months: p.months,
|
||||||
|
admin_username: p.adminUsername,
|
||||||
|
admin_password: p.adminPassword,
|
||||||
|
admin_number: p.adminNumber,
|
||||||
|
}),
|
||||||
|
rejectProjectRequest: (id: string, note: string) =>
|
||||||
|
request<ProjectRequest>('POST', `/project-requests/${id}/reject`, { note }),
|
||||||
setProjectDomain: (id: string, domain: string) =>
|
setProjectDomain: (id: string, domain: string) =>
|
||||||
request<Project>('POST', `/projects/${id}/domain`, { domain }),
|
request<Project>('POST', `/projects/${id}/domain`, { domain }),
|
||||||
extendProject: (id: string, months: number) =>
|
extendProject: (id: string, months: number) =>
|
||||||
|
|||||||
+10
-1
@@ -1,4 +1,4 @@
|
|||||||
import type { DemoStatus, ProjectStatus } from './api'
|
import type { DemoStatus, ProjectRequestStatus, ProjectStatus } from './api'
|
||||||
|
|
||||||
// Couleur de badge Chakra par statut de démo.
|
// Couleur de badge Chakra par statut de démo.
|
||||||
export function statusColor(s: DemoStatus): string {
|
export function statusColor(s: DemoStatus): string {
|
||||||
@@ -123,6 +123,15 @@ export function projectStatusLabel(s: ProjectStatus): string {
|
|||||||
return map[s] ?? s
|
return map[s] ?? s
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Libellé et couleur d'une demande de site vitrine.
|
||||||
|
export function requestStatusLabel(s: ProjectRequestStatus): string {
|
||||||
|
return { pending: 'En attente', approved: 'Validée', rejected: 'Refusée' }[s] ?? s
|
||||||
|
}
|
||||||
|
|
||||||
|
export function requestStatusColor(s: ProjectRequestStatus): string {
|
||||||
|
return { pending: 'orange', approved: 'green', rejected: 'red' }[s] ?? 'gray'
|
||||||
|
}
|
||||||
|
|
||||||
// Durées d'abonnement proposées (1 à 12 mois, contrainte de l'API).
|
// Durées d'abonnement proposées (1 à 12 mois, contrainte de l'API).
|
||||||
export const PROJECT_MONTHS = Array.from({ length: 12 }, (_, i) => i + 1)
|
export const PROJECT_MONTHS = Array.from({ length: 12 }, (_, i) => i + 1)
|
||||||
|
|
||||||
|
|||||||
+80
-18
@@ -12,6 +12,7 @@ import {
|
|||||||
Stack,
|
Stack,
|
||||||
Text,
|
Text,
|
||||||
} from '@chakra-ui/react'
|
} from '@chakra-ui/react'
|
||||||
|
import { Link as RouterLink } from 'react-router-dom'
|
||||||
import { SUPPORT_TELEGRAM_URL } from '../lib/links'
|
import { SUPPORT_TELEGRAM_URL } from '../lib/links'
|
||||||
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
|
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
|
||||||
import { faCheck } from '@fortawesome/free-solid-svg-icons'
|
import { faCheck } from '@fortawesome/free-solid-svg-icons'
|
||||||
@@ -30,27 +31,27 @@ const STOREFRONT: Block[] = [
|
|||||||
title: 'Vos produits, classés par catégories',
|
title: 'Vos produits, classés par catégories',
|
||||||
lead: 'Photos et vidéos par produit, catégories ordonnées à votre convenance, et plusieurs tarifs par produit selon la quantité et l\'unité de vente.',
|
lead: 'Photos et vidéos par produit, catégories ordonnées à votre convenance, et plusieurs tarifs par produit selon la quantité et l\'unité de vente.',
|
||||||
points: [
|
points: [
|
||||||
'Paliers de prix par unité (g, kg, pièce…)',
|
'Paliers de prix par unité, avec les unités que vous définissez',
|
||||||
'Catégories avec image, ordre d\'affichage libre',
|
'Catégories avec image, ordre d\'affichage libre',
|
||||||
'Fiche produit avec galerie média',
|
'Fiche produit avec galerie média',
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
kicker: 'Commande',
|
kicker: 'Commande',
|
||||||
title: 'Un panier et une commande en quelques clics',
|
title: 'Un site vitrine, ou une boutique qui prend les commandes',
|
||||||
lead: 'Le visiteur compose son panier et valide sa commande. Vous la recevez dans votre espace admin et suivez son avancement jusqu\'à la fin.',
|
lead: 'Un simple interrupteur choisit le mode : vitrine pure pour présenter vos produits, ou boutique où les clients composent un panier et envoient leur commande. Vous la recevez dans votre espace admin, avec le détail des produits et le total.',
|
||||||
points: [
|
points: [
|
||||||
'Statuts : en attente, confirmée, en préparation, expédiée, terminée, annulée',
|
'Commandes activables ou désactivables à tout moment',
|
||||||
|
'Chaque commande : produits, quantités, total, nom, téléphone et remarque du client',
|
||||||
'Historique des commandes pour les clients connectés',
|
'Historique des commandes pour les clients connectés',
|
||||||
'Ouverture et fermeture des commandes d\'un simple interrupteur',
|
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
kicker: 'Comptes clients',
|
kicker: 'Comptes clients',
|
||||||
title: 'Des comptes clients, activables à la demande',
|
title: 'Une commande liée à un compte client',
|
||||||
lead: 'Laissez commander sans compte, ou exigez-en un. Vous pouvez aussi demander une vérification d\'identité avant d\'autoriser l\'accès.',
|
lead: 'Pour passer commande, le client doit avoir un compte : vous activez la connexion et l\'inscription depuis vos réglages. Vous pouvez en plus exiger une vérification d\'identité avant la première commande.',
|
||||||
points: [
|
points: [
|
||||||
'Création de compte activable ou non',
|
'Connexion et inscription des clients activables séparément',
|
||||||
'Vérification par pièce d\'identité (recto / verso), validée ou refusée par vos soins',
|
'Vérification par pièce d\'identité (recto / verso), validée ou refusée par vos soins',
|
||||||
'Pièces stockées dans un volume dédié, séparé des médias publics',
|
'Pièces stockées dans un volume dédié, séparé des médias publics',
|
||||||
],
|
],
|
||||||
@@ -84,8 +85,8 @@ const BACKOFFICE: Block[] = [
|
|||||||
{
|
{
|
||||||
kicker: 'Notifications',
|
kicker: 'Notifications',
|
||||||
title: 'Chaque nouvelle commande sur Telegram',
|
title: 'Chaque nouvelle commande sur Telegram',
|
||||||
lead: 'Reliez un bot Telegram : vous êtes prévenu dès qu\'une commande arrive, et, si vous le souhaitez, à chaque changement de statut.',
|
lead: 'Reliez un bot Telegram : vous êtes prévenu dès qu\'une commande arrive, sans avoir à surveiller votre espace admin.',
|
||||||
points: ['Alerte de nouvelle commande', 'Alerte de changement de statut, en option'],
|
points: ['Alerte de nouvelle commande', 'Activable ou désactivable depuis les réglages'],
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
kicker: 'Équipe',
|
kicker: 'Équipe',
|
||||||
@@ -95,6 +96,21 @@ const BACKOFFICE: Block[] = [
|
|||||||
},
|
},
|
||||||
]
|
]
|
||||||
|
|
||||||
|
// Sauvegardes : valeurs réelles du planning Velero créé au déploiement de chaque
|
||||||
|
// site (voir deploy/chart-vitrine/README.md) — à garder alignées avec lui.
|
||||||
|
const BACKUP_STATS: { value: string; label: string }[] = [
|
||||||
|
{ value: '15 min', label: 'entre deux sauvegardes' },
|
||||||
|
{ value: '24 h', label: 'd\'historique conservé' },
|
||||||
|
{ value: '100 %', label: 'des données du site couvertes' },
|
||||||
|
]
|
||||||
|
|
||||||
|
const BACKUP_POINTS = [
|
||||||
|
'Base de données, cache, images et vidéos, pièces d\'identité des clients : tous les volumes du site sont sauvegardés',
|
||||||
|
'Sauvegarde en arrière-plan, sans interrompre ni ralentir votre site',
|
||||||
|
'Les volumes sont en plus répliqués sur plusieurs serveurs du cluster',
|
||||||
|
'En cas d\'incident, nous pouvons remettre le site dans l\'état d\'une sauvegarde récente',
|
||||||
|
]
|
||||||
|
|
||||||
const HOSTING: { title: string; text: string }[] = [
|
const HOSTING: { title: string; text: string }[] = [
|
||||||
{
|
{
|
||||||
title: 'Environnement dédié',
|
title: 'Environnement dédié',
|
||||||
@@ -104,10 +120,6 @@ const HOSTING: { title: string; text: string }[] = [
|
|||||||
title: 'HTTPS et pare-feu applicatif',
|
title: 'HTTPS et pare-feu applicatif',
|
||||||
text: 'Le site est servi en HTTPS, derrière un pare-feu applicatif (WAF) qui filtre les requêtes malveillantes.',
|
text: 'Le site est servi en HTTPS, derrière un pare-feu applicatif (WAF) qui filtre les requêtes malveillantes.',
|
||||||
},
|
},
|
||||||
{
|
|
||||||
title: 'Sauvegardes automatiques',
|
|
||||||
text: 'Les données (base et médias) sont sauvegardées automatiquement et stockées sur des volumes répliqués.',
|
|
||||||
},
|
|
||||||
{
|
{
|
||||||
title: 'Votre propre nom de domaine',
|
title: 'Votre propre nom de domaine',
|
||||||
text: 'Le site est livré sur une adresse Omnex. Si vous le souhaitez, il peut aussi répondre sur votre domaine (par exemple boutique.votre-marque.fr) : demandez-le-nous au moment de la commande.',
|
text: 'Le site est livré sur une adresse Omnex. Si vous le souhaitez, il peut aussi répondre sur votre domaine (par exemple boutique.votre-marque.fr) : demandez-le-nous au moment de la commande.',
|
||||||
@@ -160,12 +172,20 @@ export function Vitrine() {
|
|||||||
</HStack>
|
</HStack>
|
||||||
<Heading size="2xl">Votre boutique en ligne, prête à l'emploi</Heading>
|
<Heading size="2xl">Votre boutique en ligne, prête à l'emploi</Heading>
|
||||||
<Text fontSize="lg" color="gray.500" maxW="2xl">
|
<Text fontSize="lg" color="gray.500" maxW="2xl">
|
||||||
Un site complet pour présenter vos produits et recevoir des commandes, avec son espace d'administration.
|
Un site complet pour présenter vos produits, et recevoir des commandes si vous le souhaitez, avec son espace d'administration.
|
||||||
Nous le déployons, l'hébergeons et le sauvegardons pour vous, pour la durée de votre abonnement.
|
Nous le déployons, l'hébergeons et le sauvegardons pour vous, pour la durée de votre abonnement.
|
||||||
</Text>
|
</Text>
|
||||||
<Button as="a" href={SUPPORT_TELEGRAM_URL} target="_blank" rel="noopener noreferrer" colorScheme="primary" size="lg" mt={2}>
|
<HStack spacing={4} pt={2} flexWrap="wrap" justify="center">
|
||||||
Nous contacter
|
<Button as={RouterLink} to="/app/sites" colorScheme="primary" size="lg">
|
||||||
</Button>
|
Demander un site
|
||||||
|
</Button>
|
||||||
|
<Button as="a" href={SUPPORT_TELEGRAM_URL} target="_blank" rel="noopener noreferrer" variant="outline" size="lg">
|
||||||
|
Nous contacter
|
||||||
|
</Button>
|
||||||
|
</HStack>
|
||||||
|
<Text fontSize="sm" color="gray.500">
|
||||||
|
Un compte client est nécessaire pour faire une demande.
|
||||||
|
</Text>
|
||||||
</Stack>
|
</Stack>
|
||||||
</Container>
|
</Container>
|
||||||
</Box>
|
</Box>
|
||||||
@@ -216,6 +236,48 @@ export function Vitrine() {
|
|||||||
</Box>
|
</Box>
|
||||||
))}
|
))}
|
||||||
</SimpleGrid>
|
</SimpleGrid>
|
||||||
|
|
||||||
|
{/* Sauvegardes */}
|
||||||
|
<Box mt={8} p={{ base: 6, md: 8 }} borderWidth="2px" borderColor="primary.500" borderRadius="xl" bg="bg-surface">
|
||||||
|
<Stack direction={{ base: 'column', lg: 'row' }} spacing={{ base: 8, lg: 12 }} align={{ lg: 'center' }}>
|
||||||
|
<Box flex="1.2" minW={0}>
|
||||||
|
<Text fontSize="xs" fontWeight="extrabold" letterSpacing="wide" textTransform="uppercase" color="primary.500" mb={2}>
|
||||||
|
Sauvegardes
|
||||||
|
</Text>
|
||||||
|
<Heading size="md" mb={3}>
|
||||||
|
Vos données sont sauvegardées en continu
|
||||||
|
</Heading>
|
||||||
|
<Text fontSize="sm" color="gray.500" mb={4}>
|
||||||
|
Chaque site dispose de son propre planning de sauvegarde, créé automatiquement au déploiement : vous
|
||||||
|
n'avez rien à configurer, ni rien à penser à lancer.
|
||||||
|
</Text>
|
||||||
|
<List spacing={2}>
|
||||||
|
{BACKUP_POINTS.map((p) => (
|
||||||
|
<ListItem key={p} fontSize="sm" color="gray.600" display="flex">
|
||||||
|
<ListIcon as={() => <FontAwesomeIcon icon={faCheck} />} color="green.400" mt={1} mr={2} />
|
||||||
|
<span>{p}</span>
|
||||||
|
</ListItem>
|
||||||
|
))}
|
||||||
|
</List>
|
||||||
|
<Text fontSize="xs" color="gray.500" mt={4}>
|
||||||
|
L'historique est de 24 heures : ce n'est pas une archive à long terme. Les sauvegardes sont supprimées
|
||||||
|
en même temps que le site, à son échéance ou sur demande.
|
||||||
|
</Text>
|
||||||
|
</Box>
|
||||||
|
<SimpleGrid flex="1" columns={{ base: 1, sm: 3, lg: 1 }} spacing={4}>
|
||||||
|
{BACKUP_STATS.map((st) => (
|
||||||
|
<Box key={st.label} p={4} borderWidth="1px" borderRadius="lg" textAlign="center">
|
||||||
|
<Text fontSize="2xl" fontWeight="bold" color="primary.500">
|
||||||
|
{st.value}
|
||||||
|
</Text>
|
||||||
|
<Text fontSize="sm" color="gray.500">
|
||||||
|
{st.label}
|
||||||
|
</Text>
|
||||||
|
</Box>
|
||||||
|
))}
|
||||||
|
</SimpleGrid>
|
||||||
|
</Stack>
|
||||||
|
</Box>
|
||||||
</Container>
|
</Container>
|
||||||
|
|
||||||
{/* Abonnement */}
|
{/* Abonnement */}
|
||||||
|
|||||||
@@ -0,0 +1,132 @@
|
|||||||
|
import { useCallback, useEffect, useState } from 'react'
|
||||||
|
import { Badge, Box, Button, Flex, Heading, HStack, Link, Spacer, Spinner, Text, VStack, useToast } from '@chakra-ui/react'
|
||||||
|
import { api, type Project, type ProjectRequest } from '../../lib/api'
|
||||||
|
import {
|
||||||
|
formatDate,
|
||||||
|
monthsLabel,
|
||||||
|
projectStatusColor,
|
||||||
|
projectStatusLabel,
|
||||||
|
requestStatusColor,
|
||||||
|
requestStatusLabel,
|
||||||
|
timeRemaining,
|
||||||
|
} from '../../lib/format'
|
||||||
|
import { RequestSiteModal } from '../../components/RequestSiteModal'
|
||||||
|
|
||||||
|
// Un déploiement en cours => on rafraîchit régulièrement.
|
||||||
|
const POLL_MS = 10000
|
||||||
|
|
||||||
|
// Espace client : demander un site vitrine, suivre ses demandes et ses sites.
|
||||||
|
export function MySites() {
|
||||||
|
const toast = useToast()
|
||||||
|
const [sites, setSites] = useState<Project[]>([])
|
||||||
|
const [requests, setRequests] = useState<ProjectRequest[]>([])
|
||||||
|
const [loading, setLoading] = useState(true)
|
||||||
|
const [modalOpen, setModalOpen] = useState(false)
|
||||||
|
|
||||||
|
const load = useCallback(async () => {
|
||||||
|
try {
|
||||||
|
const [s, r] = await Promise.all([api.listMyProjects(), api.listMyProjectRequests()])
|
||||||
|
setSites(s.items ?? [])
|
||||||
|
setRequests(r.items ?? [])
|
||||||
|
} catch {
|
||||||
|
toast({ status: 'error', title: 'Chargement impossible' })
|
||||||
|
} finally {
|
||||||
|
setLoading(false)
|
||||||
|
}
|
||||||
|
}, [toast])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
void load()
|
||||||
|
const id = setInterval(() => void load(), POLL_MS)
|
||||||
|
return () => clearInterval(id)
|
||||||
|
}, [load])
|
||||||
|
|
||||||
|
// Une demande validée apparaît déjà comme site : on ne la répète pas.
|
||||||
|
const openRequests = requests.filter((r) => r.status !== 'approved')
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<Flex mb={6} align="center" gap={3}>
|
||||||
|
<Heading size="md">Mes sites vitrine</Heading>
|
||||||
|
<Spacer />
|
||||||
|
<Button colorScheme="primary" onClick={() => setModalOpen(true)}>
|
||||||
|
Demander un site
|
||||||
|
</Button>
|
||||||
|
</Flex>
|
||||||
|
|
||||||
|
{loading ? (
|
||||||
|
<Spinner />
|
||||||
|
) : (
|
||||||
|
<VStack align="stretch" spacing={8}>
|
||||||
|
<Box>
|
||||||
|
<Heading size="sm" mb={3}>
|
||||||
|
Sites
|
||||||
|
</Heading>
|
||||||
|
<Box p={6} borderWidth="1px" borderRadius="lg" bg="bg-surface">
|
||||||
|
{sites.length === 0 ? (
|
||||||
|
<Text color="gray.500">Aucun site pour le moment.</Text>
|
||||||
|
) : (
|
||||||
|
<VStack align="stretch" spacing={4}>
|
||||||
|
{sites.map((p) => (
|
||||||
|
<HStack key={p.id} justify="space-between" flexWrap="wrap" rowGap={2}>
|
||||||
|
<Box minW={0}>
|
||||||
|
<Text fontWeight="medium">{p.client_name}</Text>
|
||||||
|
{p.status === 'ready' ? (
|
||||||
|
<Link href={p.url} color="primary.500" isExternal fontFamily="mono" fontSize="sm">
|
||||||
|
{p.custom_domain || p.host}
|
||||||
|
</Link>
|
||||||
|
) : (
|
||||||
|
<Text color="gray.400" fontFamily="mono" fontSize="sm">
|
||||||
|
{p.host}
|
||||||
|
</Text>
|
||||||
|
)}
|
||||||
|
</Box>
|
||||||
|
<Box textAlign="right">
|
||||||
|
<Badge colorScheme={projectStatusColor(p.status)}>{projectStatusLabel(p.status)}</Badge>
|
||||||
|
<Text fontSize="xs" color="gray.500" mt={1}>
|
||||||
|
Jusqu'au {formatDate(p.expires_at)} · {timeRemaining(p.expires_at)}
|
||||||
|
</Text>
|
||||||
|
</Box>
|
||||||
|
</HStack>
|
||||||
|
))}
|
||||||
|
</VStack>
|
||||||
|
)}
|
||||||
|
</Box>
|
||||||
|
</Box>
|
||||||
|
|
||||||
|
<Box>
|
||||||
|
<Heading size="sm" mb={3}>
|
||||||
|
Demandes
|
||||||
|
</Heading>
|
||||||
|
<Box p={6} borderWidth="1px" borderRadius="lg" bg="bg-surface">
|
||||||
|
{openRequests.length === 0 ? (
|
||||||
|
<Text color="gray.500">Aucune demande en cours.</Text>
|
||||||
|
) : (
|
||||||
|
<VStack align="stretch" spacing={4}>
|
||||||
|
{openRequests.map((r) => (
|
||||||
|
<HStack key={r.id} justify="space-between" flexWrap="wrap" rowGap={2} align="flex-start">
|
||||||
|
<Box minW={0}>
|
||||||
|
<Text fontWeight="medium">{r.site_name}</Text>
|
||||||
|
<Text fontSize="sm" color="gray.500">
|
||||||
|
{monthsLabel(r.months)} · demandé le {formatDate(r.created_at)}
|
||||||
|
</Text>
|
||||||
|
{r.status === 'rejected' && r.admin_note && (
|
||||||
|
<Text fontSize="sm" color="red.500" mt={1}>
|
||||||
|
Motif : {r.admin_note}
|
||||||
|
</Text>
|
||||||
|
)}
|
||||||
|
</Box>
|
||||||
|
<Badge colorScheme={requestStatusColor(r.status)}>{requestStatusLabel(r.status)}</Badge>
|
||||||
|
</HStack>
|
||||||
|
))}
|
||||||
|
</VStack>
|
||||||
|
)}
|
||||||
|
</Box>
|
||||||
|
</Box>
|
||||||
|
</VStack>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<RequestSiteModal isOpen={modalOpen} onClose={() => setModalOpen(false)} onCreated={() => void load()} />
|
||||||
|
</>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -25,11 +25,12 @@ import {
|
|||||||
} from '@chakra-ui/react'
|
} from '@chakra-ui/react'
|
||||||
import { EditIcon } from '@chakra-ui/icons'
|
import { EditIcon } from '@chakra-ui/icons'
|
||||||
import { useNavigate } from 'react-router-dom'
|
import { useNavigate } from 'react-router-dom'
|
||||||
import { api, ApiError, type DemoDetails, type Project } from '../../lib/api'
|
import { api, ApiError, type DemoDetails, type Project, type ProjectRequest } from '../../lib/api'
|
||||||
import { formatDate, monthsLabel, projectStatusColor, projectStatusLabel, timeRemaining } from '../../lib/format'
|
import { formatDate, monthsLabel, projectStatusColor, projectStatusLabel, timeRemaining } from '../../lib/format'
|
||||||
import { ConfirmDialog } from '../../components/ConfirmDialog'
|
import { ConfirmDialog } from '../../components/ConfirmDialog'
|
||||||
import { CreateProjectModal } from '../../components/CreateProjectModal'
|
import { CreateProjectModal } from '../../components/CreateProjectModal'
|
||||||
import { EditDomainModal } from '../../components/EditDomainModal'
|
import { EditDomainModal } from '../../components/EditDomainModal'
|
||||||
|
import { ProcessRequestModal } from '../../components/ProcessRequestModal'
|
||||||
import { ExtendProjectModal } from '../../components/ExtendProjectModal'
|
import { ExtendProjectModal } from '../../components/ExtendProjectModal'
|
||||||
import { ChevronIcon, PodStatusPanel } from '../../components/PodStatusPanel'
|
import { ChevronIcon, PodStatusPanel } from '../../components/PodStatusPanel'
|
||||||
|
|
||||||
@@ -50,6 +51,8 @@ export function Projects() {
|
|||||||
const [toExtend, setToExtend] = useState<Project | null>(null)
|
const [toExtend, setToExtend] = useState<Project | null>(null)
|
||||||
const [toDelete, setToDelete] = useState<Project | null>(null)
|
const [toDelete, setToDelete] = useState<Project | null>(null)
|
||||||
const [editingDomain, setEditingDomain] = useState<Project | null>(null)
|
const [editingDomain, setEditingDomain] = useState<Project | null>(null)
|
||||||
|
const [requests, setRequests] = useState<ProjectRequest[]>([])
|
||||||
|
const [processing, setProcessing] = useState<ProjectRequest | null>(null)
|
||||||
|
|
||||||
// --- Ligne dépliée (état live des pods) ---
|
// --- Ligne dépliée (état live des pods) ---
|
||||||
const [expandedId, setExpandedId] = useState<string | null>(null)
|
const [expandedId, setExpandedId] = useState<string | null>(null)
|
||||||
@@ -68,11 +71,27 @@ export function Projects() {
|
|||||||
}
|
}
|
||||||
}, [navigate, toast])
|
}, [navigate, toast])
|
||||||
|
|
||||||
useEffect(() => {
|
// Demandes de clients en attente de validation (silencieux en cas d'échec :
|
||||||
|
// la liste des projets reste utilisable).
|
||||||
|
const loadRequests = useCallback(async () => {
|
||||||
|
try {
|
||||||
|
const res = await api.listProjectRequests()
|
||||||
|
setRequests((res.items ?? []).filter((r) => r.status === 'pending'))
|
||||||
|
} catch {
|
||||||
|
/* on garde la dernière liste connue */
|
||||||
|
}
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
const reloadAll = useCallback(() => {
|
||||||
void load()
|
void load()
|
||||||
const id = setInterval(() => void load(), POLL_MS)
|
void loadRequests()
|
||||||
|
}, [load, loadRequests])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
reloadAll()
|
||||||
|
const id = setInterval(reloadAll, POLL_MS)
|
||||||
return () => clearInterval(id)
|
return () => clearInterval(id)
|
||||||
}, [load])
|
}, [reloadAll])
|
||||||
|
|
||||||
const confirmDelete = async () => {
|
const confirmDelete = async () => {
|
||||||
if (!toDelete) return
|
if (!toDelete) return
|
||||||
@@ -157,6 +176,42 @@ export function Projects() {
|
|||||||
</Button>
|
</Button>
|
||||||
</Flex>
|
</Flex>
|
||||||
|
|
||||||
|
{requests.length > 0 && (
|
||||||
|
<Box mb={8} p={4} borderWidth="1px" borderColor="orange.300" borderRadius="lg" bg="bg-surface">
|
||||||
|
<Heading size="sm" mb={3}>
|
||||||
|
Demandes de sites ({requests.length})
|
||||||
|
</Heading>
|
||||||
|
<TableContainer>
|
||||||
|
<Table size="sm">
|
||||||
|
<Thead>
|
||||||
|
<Tr>
|
||||||
|
<Th>Client</Th>
|
||||||
|
<Th>Site</Th>
|
||||||
|
<Th>Durée</Th>
|
||||||
|
<Th>Reçue le</Th>
|
||||||
|
<Th />
|
||||||
|
</Tr>
|
||||||
|
</Thead>
|
||||||
|
<Tbody>
|
||||||
|
{requests.map((r) => (
|
||||||
|
<Tr key={r.id}>
|
||||||
|
<Td>{r.username}</Td>
|
||||||
|
<Td>{r.site_name}</Td>
|
||||||
|
<Td>{monthsLabel(r.months)}</Td>
|
||||||
|
<Td>{formatDate(r.created_at)}</Td>
|
||||||
|
<Td textAlign="right">
|
||||||
|
<Button size="xs" colorScheme="primary" onClick={() => setProcessing(r)}>
|
||||||
|
Traiter
|
||||||
|
</Button>
|
||||||
|
</Td>
|
||||||
|
</Tr>
|
||||||
|
))}
|
||||||
|
</Tbody>
|
||||||
|
</Table>
|
||||||
|
</TableContainer>
|
||||||
|
</Box>
|
||||||
|
)}
|
||||||
|
|
||||||
{loading ? (
|
{loading ? (
|
||||||
<Spinner />
|
<Spinner />
|
||||||
) : projects.length === 0 ? (
|
) : projects.length === 0 ? (
|
||||||
@@ -305,6 +360,7 @@ export function Projects() {
|
|||||||
</>
|
</>
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
|
<ProcessRequestModal request={processing} onClose={() => setProcessing(null)} onDone={reloadAll} />
|
||||||
<ExtendProjectModal project={toExtend} onClose={() => setToExtend(null)} onExtended={() => void load()} />
|
<ExtendProjectModal project={toExtend} onClose={() => setToExtend(null)} onExtended={() => void load()} />
|
||||||
<ConfirmDialog
|
<ConfirmDialog
|
||||||
isOpen={!!toDelete}
|
isOpen={!!toDelete}
|
||||||
|
|||||||
Reference in New Issue
Block a user