documentacion
This commit is contained in:
@@ -60,6 +60,10 @@ func Migrate() {
|
||||
&models.BoldWebhookLog{},
|
||||
&models.BoldCallbackLog{},
|
||||
&models.DlocalPaymentLog{},
|
||||
// Documentación por SaaS
|
||||
&models.SaasProducto{},
|
||||
&models.DocCategoria{},
|
||||
&models.DocPagina{},
|
||||
); err != nil {
|
||||
log.Fatalf("Error during main migration: %v", err)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"github.com/sujit-baniya/fiber-boilerplate/app"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// DocCategoria es una categoría GLOBAL que puede aplicarse a la documentación de cualquier SaaS.
|
||||
// Ejemplos: "Primeros Pasos", "API Reference", "Configuración", "Facturación".
|
||||
type DocCategoria struct {
|
||||
gorm.Model
|
||||
Nombre string `json:"nombre" gorm:"column:nombre;not null"`
|
||||
Slug string `json:"slug" gorm:"column:slug;uniqueIndex;not null"`
|
||||
Descripcion string `json:"descripcion" gorm:"column:descripcion;type:text"`
|
||||
Orden int `json:"orden" gorm:"column:orden;default:0"`
|
||||
}
|
||||
|
||||
func (DocCategoria) TableName() string { return "doc_categorias" }
|
||||
|
||||
func GetAllDocCategorias(limit, offset int, search string) ([]DocCategoria, int64, error) {
|
||||
var items []DocCategoria
|
||||
var total int64
|
||||
db := app.Http.Database.DB.Model(&DocCategoria{})
|
||||
if search != "" {
|
||||
db = db.Where("nombre ILIKE ? OR descripcion ILIKE ?", "%"+search+"%", "%"+search+"%")
|
||||
}
|
||||
if err := db.Count(&total).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
if err := db.Order("orden ASC, nombre ASC").Limit(limit).Offset(offset).Find(&items).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
return items, total, nil
|
||||
}
|
||||
|
||||
func GetAllDocCategoriasSelect() ([]DocCategoria, error) {
|
||||
var items []DocCategoria
|
||||
if err := app.Http.Database.DB.Order("orden ASC, nombre ASC").Find(&items).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
func GetDocCategoriaByID(id uint) (*DocCategoria, error) {
|
||||
var item DocCategoria
|
||||
if err := app.Http.Database.DB.First(&item, id).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &item, nil
|
||||
}
|
||||
|
||||
func CreateDocCategoria(c *DocCategoria) error {
|
||||
return app.Http.Database.DB.Create(c).Error
|
||||
}
|
||||
|
||||
func UpdateDocCategoria(c *DocCategoria) error {
|
||||
return app.Http.Database.DB.Model(&DocCategoria{}).Where("id = ?", c.ID).Updates(map[string]interface{}{
|
||||
"nombre": c.Nombre,
|
||||
"slug": c.Slug,
|
||||
"descripcion": c.Descripcion,
|
||||
"orden": c.Orden,
|
||||
}).Error
|
||||
}
|
||||
|
||||
func DeleteDocCategoria(id uint) error {
|
||||
return app.Http.Database.DB.Delete(&DocCategoria{}, id).Error
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"github.com/sujit-baniya/fiber-boilerplate/app"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// DocPagina es el contenido real de documentación.
|
||||
// Visibilidad "public" → accesible sin login.
|
||||
// Visibilidad "private" → requiere login Y tener al menos uno de los roles asignados.
|
||||
// TipoContenido "markdown" | "html" determina cómo se renderiza el campo Contenido.
|
||||
type DocPagina struct {
|
||||
gorm.Model
|
||||
SaasID uint `json:"saas_id" gorm:"column:saas_id;not null"`
|
||||
Saas SaasProducto `json:"saas" gorm:"foreignKey:SaasID"`
|
||||
CategoriaID uint `json:"categoria_id" gorm:"column:categoria_id;not null"`
|
||||
Categoria DocCategoria `json:"categoria" gorm:"foreignKey:CategoriaID"`
|
||||
Titulo string `json:"titulo" gorm:"column:titulo;not null"`
|
||||
Slug string `json:"slug" gorm:"column:slug;not null;uniqueIndex:idx_saas_slug"`
|
||||
Contenido string `json:"contenido" gorm:"column:contenido;type:text"`
|
||||
TipoContenido string `json:"tipo_contenido" gorm:"column:tipo_contenido;default:'markdown'"` // markdown | html
|
||||
Visibilidad string `json:"visibilidad" gorm:"column:visibilidad;default:'public'"` // public | private
|
||||
Orden int `json:"orden" gorm:"column:orden;default:0"`
|
||||
Publicado bool `json:"publicado" gorm:"column:publicado;default:false"`
|
||||
CreadoPor uint `json:"creado_por" gorm:"column:creado_por"`
|
||||
// Roles que pueden ver esta página cuando visibilidad = "private"
|
||||
Roles []Roles `json:"roles" gorm:"many2many:doc_pagina_roles"`
|
||||
}
|
||||
|
||||
func (DocPagina) TableName() string { return "doc_paginas" }
|
||||
|
||||
// ─── Queries ──────────────────────────────────────────────────────────────────
|
||||
|
||||
func GetAllDocPaginas(limit, offset int, search string, saasID, categoriaID uint) ([]DocPagina, int64, error) {
|
||||
var items []DocPagina
|
||||
var total int64
|
||||
db := app.Http.Database.DB.Model(&DocPagina{}).
|
||||
Preload("Saas").Preload("Categoria").Preload("Roles")
|
||||
if search != "" {
|
||||
db = db.Where("titulo ILIKE ?", "%"+search+"%")
|
||||
}
|
||||
if saasID > 0 {
|
||||
db = db.Where("saas_id = ?", saasID)
|
||||
}
|
||||
if categoriaID > 0 {
|
||||
db = db.Where("categoria_id = ?", categoriaID)
|
||||
}
|
||||
if err := db.Count(&total).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
if err := db.Order("saas_id ASC, orden ASC, created_at DESC").Limit(limit).Offset(offset).Find(&items).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
return items, total, nil
|
||||
}
|
||||
|
||||
// GetDocPaginasPublicas devuelve páginas publicadas y públicas de un SaaS, agrupables por categoría.
|
||||
func GetDocPaginasPublicas(saasID uint) ([]DocPagina, error) {
|
||||
var items []DocPagina
|
||||
if err := app.Http.Database.DB.
|
||||
Preload("Categoria").
|
||||
Where("saas_id = ? AND visibilidad = 'public' AND publicado = true", saasID).
|
||||
Order("orden ASC, titulo ASC").
|
||||
Find(&items).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
// GetDocPaginasParaRoles devuelve páginas publicadas accesibles por los roles dados (incluye public + private con rol).
|
||||
func GetDocPaginasParaRoles(saasID uint, rolNames []string) ([]DocPagina, error) {
|
||||
var items []DocPagina
|
||||
db := app.Http.Database.DB.Preload("Categoria").Preload("Roles")
|
||||
|
||||
// Páginas públicas del SaaS
|
||||
if err := db.Where("saas_id = ? AND publicado = true AND visibilidad = 'public'", saasID).
|
||||
Order("orden ASC, titulo ASC").Find(&items).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Páginas privadas accesibles por los roles del usuario
|
||||
if len(rolNames) > 0 {
|
||||
var privadas []DocPagina
|
||||
if err := app.Http.Database.DB.Preload("Categoria").Preload("Roles").
|
||||
Joins("JOIN doc_pagina_roles dpr ON dpr.doc_pagina_id = doc_paginas.id").
|
||||
Joins("JOIN roles r ON r.id = dpr.roles_id").
|
||||
Where("doc_paginas.saas_id = ? AND doc_paginas.publicado = true AND doc_paginas.visibilidad = 'private' AND r.name IN ?", saasID, rolNames).
|
||||
Group("doc_paginas.id").
|
||||
Order("doc_paginas.orden ASC, doc_paginas.titulo ASC").
|
||||
Find(&privadas).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, privadas...)
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
func GetDocPaginaByID(id uint) (*DocPagina, error) {
|
||||
var item DocPagina
|
||||
if err := app.Http.Database.DB.Preload("Saas").Preload("Categoria").Preload("Roles").First(&item, id).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &item, nil
|
||||
}
|
||||
|
||||
func GetDocPaginaBySlug(saasID uint, slug string) (*DocPagina, error) {
|
||||
var item DocPagina
|
||||
if err := app.Http.Database.DB.Preload("Saas").Preload("Categoria").Preload("Roles").
|
||||
Where("saas_id = ? AND slug = ?", saasID, slug).
|
||||
First(&item).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &item, nil
|
||||
}
|
||||
|
||||
func CreateDocPagina(p *DocPagina, rolIDs []uint) error {
|
||||
db := app.Http.Database.DB
|
||||
if err := db.Omit("Roles.*").Create(p).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return syncDocPaginaRoles(p.ID, rolIDs)
|
||||
}
|
||||
|
||||
func UpdateDocPagina(p *DocPagina, rolIDs []uint) error {
|
||||
db := app.Http.Database.DB
|
||||
if err := db.Model(&DocPagina{}).Where("id = ?", p.ID).Updates(map[string]interface{}{
|
||||
"saas_id": p.SaasID,
|
||||
"categoria_id": p.CategoriaID,
|
||||
"titulo": p.Titulo,
|
||||
"slug": p.Slug,
|
||||
"contenido": p.Contenido,
|
||||
"tipo_contenido": p.TipoContenido,
|
||||
"visibilidad": p.Visibilidad,
|
||||
"orden": p.Orden,
|
||||
"publicado": p.Publicado,
|
||||
}).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return syncDocPaginaRoles(p.ID, rolIDs)
|
||||
}
|
||||
|
||||
func DeleteDocPagina(id uint) error {
|
||||
db := app.Http.Database.DB
|
||||
// Limpiar la tabla join antes de borrar el registro
|
||||
if err := db.Exec("DELETE FROM doc_pagina_roles WHERE doc_pagina_id = ?", id).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return db.Delete(&DocPagina{}, id).Error
|
||||
}
|
||||
|
||||
// syncDocPaginaRoles sincroniza los roles de una página usando SQL directo.
|
||||
func syncDocPaginaRoles(paginaID uint, rolIDs []uint) error {
|
||||
db := app.Http.Database.DB
|
||||
if err := db.Exec("DELETE FROM doc_pagina_roles WHERE doc_pagina_id = ?", paginaID).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
for _, rid := range rolIDs {
|
||||
if err := db.Exec(
|
||||
"INSERT INTO doc_pagina_roles (doc_pagina_id, roles_id) VALUES (?, ?) ON CONFLICT DO NOTHING",
|
||||
paginaID, rid,
|
||||
).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"github.com/sujit-baniya/fiber-boilerplate/app"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// SaasProducto representa un producto SaaS al que se le puede asociar documentación.
|
||||
// servicio_id es opcional: un SaaS puede estar relacionado con un servicio existente o ser independiente.
|
||||
type SaasProducto struct {
|
||||
gorm.Model
|
||||
Nombre string `json:"nombre" gorm:"column:nombre;not null"`
|
||||
Slug string `json:"slug" gorm:"column:slug;uniqueIndex;not null"`
|
||||
Descripcion string `json:"descripcion" gorm:"column:descripcion;type:text"`
|
||||
LogoURL string `json:"logo_url" gorm:"column:logo_url"`
|
||||
ServicioID *uint `json:"servicio_id" gorm:"column:servicio_id"` // nullable FK
|
||||
Servicio *Servicio `json:"servicio" gorm:"foreignKey:ServicioID"`
|
||||
Activo bool `json:"activo" gorm:"column:activo;default:true"`
|
||||
Orden int `json:"orden" gorm:"column:orden;default:0"`
|
||||
}
|
||||
|
||||
func (SaasProducto) TableName() string { return "saas_productos" }
|
||||
|
||||
func GetAllSaasProductos(limit, offset int, search string) ([]SaasProducto, int64, error) {
|
||||
var items []SaasProducto
|
||||
var total int64
|
||||
db := app.Http.Database.DB.Model(&SaasProducto{}).Preload("Servicio")
|
||||
if search != "" {
|
||||
db = db.Where("nombre ILIKE ? OR descripcion ILIKE ?", "%"+search+"%", "%"+search+"%")
|
||||
}
|
||||
if err := db.Count(&total).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
if err := db.Order("orden ASC, created_at DESC").Limit(limit).Offset(offset).Find(&items).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
return items, total, nil
|
||||
}
|
||||
|
||||
func GetAllSaasProductosSelect() ([]SaasProducto, error) {
|
||||
var items []SaasProducto
|
||||
if err := app.Http.Database.DB.Where("activo = ?", true).Order("orden ASC, nombre ASC").Find(&items).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
func GetSaasProductoByID(id uint) (*SaasProducto, error) {
|
||||
var item SaasProducto
|
||||
if err := app.Http.Database.DB.Preload("Servicio").First(&item, id).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &item, nil
|
||||
}
|
||||
|
||||
func GetSaasProductoBySlug(slug string) (*SaasProducto, error) {
|
||||
var item SaasProducto
|
||||
if err := app.Http.Database.DB.Where("slug = ?", slug).First(&item).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &item, nil
|
||||
}
|
||||
|
||||
func CreateSaasProducto(s *SaasProducto) error {
|
||||
return app.Http.Database.DB.Create(s).Error
|
||||
}
|
||||
|
||||
func UpdateSaasProducto(s *SaasProducto) error {
|
||||
return app.Http.Database.DB.Model(&SaasProducto{}).Where("id = ?", s.ID).Updates(map[string]interface{}{
|
||||
"nombre": s.Nombre,
|
||||
"slug": s.Slug,
|
||||
"descripcion": s.Descripcion,
|
||||
"logo_url": s.LogoURL,
|
||||
"servicio_id": s.ServicioID,
|
||||
"activo": s.Activo,
|
||||
"orden": s.Orden,
|
||||
}).Error
|
||||
}
|
||||
|
||||
func DeleteSaasProducto(id uint) error {
|
||||
return app.Http.Database.DB.Delete(&SaasProducto{}, id).Error
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
<!-- Vista: Categorías Globales de Documentación -->
|
||||
<div x-data="catApp()" x-init="init()" @keydown.escape="closeModal()" class="bg-white rounded-lg shadow">
|
||||
<div class="container mx-auto p-6 w-full">
|
||||
<h1 class="text-2xl font-bold mb-1">Categorías de Documentación</h1>
|
||||
<p class="text-sm text-gray-500 mb-4">Categorías globales que aplican a todos los productos SaaS. Ejemplos: "Primeros Pasos", "API Reference", "Facturación".</p>
|
||||
|
||||
<div class="flex flex-col md:flex-row md:justify-between md:items-center gap-3 mb-4">
|
||||
<div class="relative">
|
||||
<input type="text" x-model="search" @input="load(1)" placeholder="Buscar..."
|
||||
class="border border-gray-300 rounded w-full md:w-60 p-2 text-sm">
|
||||
<div x-show="loading" class="absolute right-2 top-2">
|
||||
<svg class="animate-spin h-5 w-5 text-gray-400" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
|
||||
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
|
||||
<path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8v4a4 4 0 00-4 4H4z"></path>
|
||||
</svg>
|
||||
</div>
|
||||
</div>
|
||||
<button @click="openAdd()" class="bg-[#8eb02f] text-white px-4 py-2 rounded text-sm">+ Nueva Categoría</button>
|
||||
</div>
|
||||
|
||||
<div class="overflow-x-auto">
|
||||
<table class="table-auto w-full text-sm">
|
||||
<thead class="border-b border-gray-200 text-left font-semibold text-gray-600">
|
||||
<tr>
|
||||
<th class="py-2 px-4 border-b">Nombre</th>
|
||||
<th class="py-2 px-4 border-b">Slug</th>
|
||||
<th class="py-2 px-4 border-b">Descripción</th>
|
||||
<th class="py-2 px-4 border-b w-16">Orden</th>
|
||||
<th class="py-2 px-4 border-b w-20"></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody class="text-gray-500">
|
||||
<template x-if="items.length === 0">
|
||||
<tr><td colspan="5" class="py-4 text-center text-gray-400">Sin categorías registradas</td></tr>
|
||||
</template>
|
||||
<template x-for="item in items" :key="item.ID">
|
||||
<tr class="hover:bg-gray-50 border-b border-gray-100">
|
||||
<td class="py-2 px-4 font-medium text-gray-800" x-text="item.nombre"></td>
|
||||
<td class="py-2 px-4 font-mono text-xs text-gray-500" x-text="item.slug"></td>
|
||||
<td class="py-2 px-4 text-xs text-gray-500" x-text="item.descripcion || '—'"></td>
|
||||
<td class="py-2 px-4 text-xs text-center" x-text="item.orden"></td>
|
||||
<td class="py-2 px-4 flex gap-2 justify-end">
|
||||
<button @click="openEdit(item)" title="Editar" class="text-blue-500 hover:text-blue-700">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"/>
|
||||
</svg>
|
||||
</button>
|
||||
<button @click="confirmDelete(item.ID)" title="Eliminar" class="text-red-400 hover:text-red-600">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"/>
|
||||
</svg>
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
</template>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<!-- Paginación -->
|
||||
<div class="flex items-center justify-between mt-4 text-sm">
|
||||
<span class="text-gray-500">Total: <strong x-text="total"></strong></span>
|
||||
<div class="flex gap-1">
|
||||
<template x-for="p in totalPages" :key="p">
|
||||
<button @click="load(p)"
|
||||
:class="p === page ? 'bg-[#8eb02f] text-white' : 'bg-gray-100 text-gray-600 hover:bg-gray-200'"
|
||||
class="px-3 py-1 rounded text-xs" x-text="p"></button>
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Modal Añadir / Editar -->
|
||||
<div x-cloak x-show="showModal" x-transition
|
||||
class="fixed inset-0 bg-gray-800 bg-opacity-75 flex z-40 justify-center items-center text-sm">
|
||||
<div class="bg-white p-6 rounded shadow-lg w-full max-w-md overflow-y-auto max-h-[90vh]">
|
||||
<h2 class="text-lg font-bold mb-4" x-text="editId ? 'Editar Categoría' : 'Nueva Categoría'"></h2>
|
||||
<form @submit.prevent="submitForm()">
|
||||
<div class="space-y-3">
|
||||
<div>
|
||||
<label class="block text-xs font-medium mb-1">Nombre *</label>
|
||||
<input type="text" x-model="form.nombre" @input="autoSlug()" required
|
||||
class="border border-gray-300 rounded w-full p-2 text-sm">
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-xs font-medium mb-1">Slug * <span class="text-gray-400 font-normal">(URL)</span></label>
|
||||
<input type="text" x-model="form.slug" required
|
||||
class="border border-gray-300 rounded w-full p-2 text-sm font-mono">
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-xs font-medium mb-1">Descripción</label>
|
||||
<textarea x-model="form.descripcion" rows="2"
|
||||
class="border border-gray-300 rounded w-full p-2 text-sm"></textarea>
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-xs font-medium mb-1">Orden</label>
|
||||
<input type="number" x-model.number="form.orden" min="0"
|
||||
class="border border-gray-300 rounded w-full p-2 text-sm">
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex justify-between mt-5">
|
||||
<button type="submit" class="bg-[#8eb02f] text-white px-4 py-2 rounded text-sm">Guardar</button>
|
||||
<button type="button" @click="closeModal()" class="bg-gray-500 text-white px-4 py-2 rounded text-sm">Cancelar</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Modal Confirmar Eliminación -->
|
||||
<div x-cloak x-show="showDeleteModal" x-transition
|
||||
class="fixed inset-0 bg-gray-800 bg-opacity-75 flex z-50 justify-center items-center text-sm">
|
||||
<div class="bg-white p-6 rounded shadow-lg max-w-sm w-full">
|
||||
<h2 class="text-lg font-bold mb-3">Confirmar eliminación</h2>
|
||||
<p class="text-gray-600 mb-4">¿Eliminar esta categoría? Las páginas que la usen quedarán sin categoría.</p>
|
||||
<div class="flex justify-end gap-2">
|
||||
<button @click="doDelete()" class="bg-red-500 text-white px-4 py-2 rounded text-sm">Eliminar</button>
|
||||
<button @click="showDeleteModal = false" class="bg-gray-500 text-white px-4 py-2 rounded text-sm">Cancelar</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
function catApp() {
|
||||
return {
|
||||
items: [], total: 0, totalPages: 1, page: 1, search: '', loading: false,
|
||||
showModal: false, showDeleteModal: false,
|
||||
editId: null, deleteId: null,
|
||||
form: { nombre: '', slug: '', descripcion: '', orden: 0 },
|
||||
|
||||
init() { this.load(1); },
|
||||
|
||||
load(p = 1) {
|
||||
this.page = p; this.loading = true;
|
||||
fetch(`/app/doc/loadcategorias?page=${p}&search=${encodeURIComponent(this.search)}`)
|
||||
.then(r => r.json())
|
||||
.then(d => {
|
||||
this.items = d.items || [];
|
||||
this.total = d.total;
|
||||
this.totalPages = Array.from({ length: d.totalPages }, (_, i) => i + 1);
|
||||
this.loading = false;
|
||||
});
|
||||
},
|
||||
|
||||
autoSlug() {
|
||||
if (!this.editId) {
|
||||
this.form.slug = this.form.nombre
|
||||
.toLowerCase().trim()
|
||||
.normalize('NFD').replace(/[\u0300-\u036f]/g, '')
|
||||
.replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
|
||||
}
|
||||
},
|
||||
|
||||
openAdd() {
|
||||
this.editId = null;
|
||||
this.form = { nombre: '', slug: '', descripcion: '', orden: 0 };
|
||||
this.showModal = true;
|
||||
},
|
||||
|
||||
openEdit(item) {
|
||||
this.editId = item.ID;
|
||||
this.form = { nombre: item.nombre, slug: item.slug, descripcion: item.descripcion, orden: item.orden };
|
||||
this.showModal = true;
|
||||
},
|
||||
|
||||
submitForm() {
|
||||
const url = this.editId ? `/app/doc/categorias/${this.editId}` : '/app/doc/categorias';
|
||||
const method = this.editId ? 'PUT' : 'POST';
|
||||
fetch(url, { method, headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(this.form) })
|
||||
.then(r => r.json())
|
||||
.then(d => { if (d.error) { alert(d.error); return; } this.closeModal(); this.load(this.page); });
|
||||
},
|
||||
|
||||
confirmDelete(id) { this.deleteId = id; this.showDeleteModal = true; },
|
||||
|
||||
doDelete() {
|
||||
fetch(`/app/doc/categorias/${this.deleteId}`, { method: 'DELETE' })
|
||||
.then(r => r.json())
|
||||
.then(() => { this.showDeleteModal = false; this.load(this.page); });
|
||||
},
|
||||
|
||||
closeModal() { this.showModal = false; this.showDeleteModal = false; }
|
||||
};
|
||||
}
|
||||
</script>
|
||||
@@ -0,0 +1,364 @@
|
||||
<!-- Vista: Gestión de Páginas de Documentación -->
|
||||
<!-- EasyMDE para editor Markdown -->
|
||||
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/easymde/dist/easymde.min.css">
|
||||
<script src="https://cdn.jsdelivr.net/npm/easymde/dist/easymde.min.js"></script>
|
||||
<!-- Marked.js para preview de Markdown en la vista de lectura -->
|
||||
<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
|
||||
|
||||
<div x-data="paginasApp()" x-init="init()" @keydown.escape="closeModal()" class="bg-white rounded-lg shadow">
|
||||
<div class="container mx-auto p-6 w-full">
|
||||
<h1 class="text-2xl font-bold mb-1">Páginas de Documentación</h1>
|
||||
<p class="text-sm text-gray-500 mb-4">Crea y gestiona el contenido de documentación para cada producto SaaS.</p>
|
||||
|
||||
<!-- Filtros -->
|
||||
<div class="flex flex-col md:flex-row flex-wrap gap-3 mb-4">
|
||||
<input type="text" x-model="search" @input="load(1)" placeholder="Buscar título..."
|
||||
class="border border-gray-300 rounded p-2 text-sm w-full md:w-48">
|
||||
<select x-model.number="filterSaas" @change="load(1)"
|
||||
class="border border-gray-300 rounded p-2 text-sm w-full md:w-48">
|
||||
<option :value="0">— Todos los SaaS —</option>
|
||||
<template x-for="s in saasList" :key="s.ID">
|
||||
<option :value="s.ID" x-text="s.nombre"></option>
|
||||
</template>
|
||||
</select>
|
||||
<select x-model.number="filterCat" @change="load(1)"
|
||||
class="border border-gray-300 rounded p-2 text-sm w-full md:w-48">
|
||||
<option :value="0">— Todas las categorías —</option>
|
||||
<template x-for="c in catList" :key="c.ID">
|
||||
<option :value="c.ID" x-text="c.nombre"></option>
|
||||
</template>
|
||||
</select>
|
||||
<div class="flex-1"></div>
|
||||
<button @click="openAdd()" class="bg-[#8eb02f] text-white px-4 py-2 rounded text-sm whitespace-nowrap">+ Nueva Página</button>
|
||||
</div>
|
||||
|
||||
<!-- Tabla -->
|
||||
<div class="overflow-x-auto">
|
||||
<table class="table-auto w-full text-sm">
|
||||
<thead class="border-b border-gray-200 text-left font-semibold text-gray-600">
|
||||
<tr>
|
||||
<th class="py-2 px-4 border-b">Título</th>
|
||||
<th class="py-2 px-4 border-b">SaaS</th>
|
||||
<th class="py-2 px-4 border-b">Categoría</th>
|
||||
<th class="py-2 px-4 border-b">Tipo</th>
|
||||
<th class="py-2 px-4 border-b">Visibilidad</th>
|
||||
<th class="py-2 px-4 border-b w-20">Estado</th>
|
||||
<th class="py-2 px-4 border-b w-20"></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody class="text-gray-500">
|
||||
<template x-if="items.length === 0">
|
||||
<tr><td colspan="7" class="py-4 text-center text-gray-400">Sin páginas registradas</td></tr>
|
||||
</template>
|
||||
<template x-for="item in items" :key="item.ID">
|
||||
<tr class="hover:bg-gray-50 border-b border-gray-100">
|
||||
<td class="py-2 px-4">
|
||||
<span class="font-medium text-gray-800" x-text="item.titulo"></span>
|
||||
<span class="block font-mono text-xs text-gray-400" x-text="item.slug"></span>
|
||||
</td>
|
||||
<td class="py-2 px-4 text-xs" x-text="item.saas ? item.saas.nombre : '—'"></td>
|
||||
<td class="py-2 px-4 text-xs" x-text="item.categoria ? item.categoria.nombre : '—'"></td>
|
||||
<td class="py-2 px-4">
|
||||
<span :class="item.tipo_contenido === 'markdown' ? 'bg-blue-100 text-blue-700' : 'bg-purple-100 text-purple-700'"
|
||||
class="text-xs px-2 py-0.5 rounded-full" x-text="item.tipo_contenido"></span>
|
||||
</td>
|
||||
<td class="py-2 px-4">
|
||||
<span :class="item.visibilidad === 'public' ? 'bg-green-100 text-green-700' : 'bg-yellow-100 text-yellow-700'"
|
||||
class="text-xs px-2 py-0.5 rounded-full" x-text="item.visibilidad"></span>
|
||||
</td>
|
||||
<td class="py-2 px-4">
|
||||
<span :class="item.publicado ? 'bg-green-100 text-green-700' : 'bg-gray-100 text-gray-500'"
|
||||
class="text-xs px-2 py-0.5 rounded-full" x-text="item.publicado ? 'Publicado' : 'Borrador'"></span>
|
||||
</td>
|
||||
<td class="py-2 px-4 flex gap-2 justify-end">
|
||||
<button @click="openEdit(item.ID)" title="Editar" class="text-blue-500 hover:text-blue-700">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"/>
|
||||
</svg>
|
||||
</button>
|
||||
<button @click="confirmDelete(item.ID)" title="Eliminar" class="text-red-400 hover:text-red-600">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"/>
|
||||
</svg>
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
</template>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<!-- Paginación -->
|
||||
<div class="flex items-center justify-between mt-4 text-sm">
|
||||
<span class="text-gray-500">Total: <strong x-text="total"></strong></span>
|
||||
<div class="flex gap-1">
|
||||
<template x-for="p in totalPages" :key="p">
|
||||
<button @click="load(p)"
|
||||
:class="p === page ? 'bg-[#8eb02f] text-white' : 'bg-gray-100 text-gray-600 hover:bg-gray-200'"
|
||||
class="px-3 py-1 rounded text-xs" x-text="p"></button>
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ─── Modal Editor (ocupa pantalla completa) ─────────────────────────── -->
|
||||
<div x-cloak x-show="showModal" x-transition
|
||||
class="fixed inset-0 bg-gray-900 bg-opacity-80 flex z-40 justify-center items-start pt-6 px-4 text-sm overflow-y-auto">
|
||||
<div class="bg-white rounded shadow-lg w-full max-w-4xl mb-6">
|
||||
<div class="flex items-center justify-between p-4 border-b">
|
||||
<h2 class="text-lg font-bold" x-text="editId ? 'Editar Página' : 'Nueva Página'"></h2>
|
||||
<button @click="closeModal()" class="text-gray-400 hover:text-gray-600 text-xl font-bold">✕</button>
|
||||
</div>
|
||||
|
||||
<form @submit.prevent="submitForm()" class="p-4 space-y-4">
|
||||
<!-- Fila 1: Título + Slug -->
|
||||
<div class="grid grid-cols-2 gap-3">
|
||||
<div>
|
||||
<label class="block text-xs font-medium mb-1">Título *</label>
|
||||
<input type="text" x-model="form.titulo" @input="autoSlug()" required
|
||||
class="border border-gray-300 rounded w-full p-2 text-sm">
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-xs font-medium mb-1">Slug *</label>
|
||||
<input type="text" x-model="form.slug" required
|
||||
class="border border-gray-300 rounded w-full p-2 text-sm font-mono">
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Fila 2: SaaS + Categoría -->
|
||||
<div class="grid grid-cols-2 gap-3">
|
||||
<div>
|
||||
<label class="block text-xs font-medium mb-1">Producto SaaS *</label>
|
||||
<select x-model.number="form.saas_id" required class="border border-gray-300 rounded w-full p-2 text-sm">
|
||||
<option :value="0" disabled>Seleccionar SaaS...</option>
|
||||
<template x-for="s in saasList" :key="s.ID">
|
||||
<option :value="s.ID" x-text="s.nombre"></option>
|
||||
</template>
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-xs font-medium mb-1">Categoría *</label>
|
||||
<select x-model.number="form.categoria_id" required class="border border-gray-300 rounded w-full p-2 text-sm">
|
||||
<option :value="0" disabled>Seleccionar categoría...</option>
|
||||
<template x-for="c in catList" :key="c.ID">
|
||||
<option :value="c.ID" x-text="c.nombre"></option>
|
||||
</template>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Fila 3: Tipo contenido + Visibilidad + Orden + Publicado -->
|
||||
<div class="grid grid-cols-4 gap-3">
|
||||
<div>
|
||||
<label class="block text-xs font-medium mb-1">Tipo de Contenido</label>
|
||||
<select x-model="form.tipo_contenido" @change="toggleEditor()"
|
||||
class="border border-gray-300 rounded w-full p-2 text-sm">
|
||||
<option value="markdown">Markdown</option>
|
||||
<option value="html">HTML (builder)</option>
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-xs font-medium mb-1">Visibilidad</label>
|
||||
<select x-model="form.visibilidad" class="border border-gray-300 rounded w-full p-2 text-sm">
|
||||
<option value="public">Pública</option>
|
||||
<option value="private">Privada</option>
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-xs font-medium mb-1">Orden</label>
|
||||
<input type="number" x-model.number="form.orden" min="0"
|
||||
class="border border-gray-300 rounded w-full p-2 text-sm">
|
||||
</div>
|
||||
<div class="flex items-center gap-2 mt-4">
|
||||
<input type="checkbox" id="publicado" x-model="form.publicado" class="w-4 h-4">
|
||||
<label for="publicado" class="text-xs font-medium">Publicado</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Roles (sólo cuando visibilidad = private) -->
|
||||
<div x-show="form.visibilidad === 'private'" class="space-y-1">
|
||||
<label class="block text-xs font-medium mb-1">Roles con acceso <span class="text-gray-400 font-normal">(dejar vacío = todos los usuarios logueados)</span></label>
|
||||
<div class="flex flex-wrap gap-2">
|
||||
<template x-for="r in rolesList" :key="r.ID">
|
||||
<label class="flex items-center gap-1 bg-gray-100 px-2 py-1 rounded cursor-pointer text-xs">
|
||||
<input type="checkbox" :value="r.ID"
|
||||
:checked="form.rol_ids.includes(r.ID)"
|
||||
@change="toggleRol(r.ID)">
|
||||
<span x-text="r.name"></span>
|
||||
</label>
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Editor Markdown -->
|
||||
<div x-show="form.tipo_contenido === 'markdown'">
|
||||
<label class="block text-xs font-medium mb-1">Contenido (Markdown)</label>
|
||||
<textarea id="mdEditor"></textarea>
|
||||
</div>
|
||||
|
||||
<!-- Editor HTML -->
|
||||
<div x-show="form.tipo_contenido === 'html'">
|
||||
<label class="block text-xs font-medium mb-1">Contenido (HTML)</label>
|
||||
<textarea x-model="form.contenido" rows="16"
|
||||
class="border border-gray-300 rounded w-full p-2 text-sm font-mono"
|
||||
placeholder="Escribe HTML aquí..."></textarea>
|
||||
</div>
|
||||
|
||||
<div class="flex justify-between pt-2 border-t">
|
||||
<button type="submit" class="bg-[#8eb02f] text-white px-5 py-2 rounded text-sm">Guardar</button>
|
||||
<button type="button" @click="closeModal()" class="bg-gray-500 text-white px-4 py-2 rounded text-sm">Cancelar</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Modal Confirmar Eliminación -->
|
||||
<div x-cloak x-show="showDeleteModal" x-transition
|
||||
class="fixed inset-0 bg-gray-800 bg-opacity-75 flex z-50 justify-center items-center text-sm">
|
||||
<div class="bg-white p-6 rounded shadow-lg max-w-sm w-full">
|
||||
<h2 class="text-lg font-bold mb-3">Confirmar eliminación</h2>
|
||||
<p class="text-gray-600 mb-4">¿Eliminar esta página de documentación? Esta acción no se puede deshacer.</p>
|
||||
<div class="flex justify-end gap-2">
|
||||
<button @click="doDelete()" class="bg-red-500 text-white px-4 py-2 rounded text-sm">Eliminar</button>
|
||||
<button @click="showDeleteModal = false" class="bg-gray-500 text-white px-4 py-2 rounded text-sm">Cancelar</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
let mdEditorInstance = null;
|
||||
|
||||
function paginasApp() {
|
||||
return {
|
||||
items: [], saasList: [], catList: [], rolesList: [],
|
||||
total: 0, totalPages: 1, page: 1,
|
||||
search: '', filterSaas: 0, filterCat: 0,
|
||||
loading: false,
|
||||
showModal: false, showDeleteModal: false,
|
||||
editId: null, deleteId: null,
|
||||
form: {
|
||||
titulo: '', slug: '', saas_id: 0, categoria_id: 0,
|
||||
contenido: '', tipo_contenido: 'markdown', visibilidad: 'public',
|
||||
orden: 0, publicado: false, rol_ids: []
|
||||
},
|
||||
|
||||
init() { this.load(1); },
|
||||
|
||||
load(p = 1) {
|
||||
this.page = p; this.loading = true;
|
||||
const qs = new URLSearchParams({
|
||||
page: p, search: this.search,
|
||||
saas_id: this.filterSaas, categoria_id: this.filterCat
|
||||
});
|
||||
fetch(`/app/doc/loadpaginas?${qs}`)
|
||||
.then(r => r.json())
|
||||
.then(d => {
|
||||
this.items = d.items || [];
|
||||
this.saasList = d.saas || [];
|
||||
this.catList = d.categorias || [];
|
||||
this.rolesList = d.roles || [];
|
||||
this.total = d.total;
|
||||
this.totalPages = Array.from({ length: d.totalPages }, (_, i) => i + 1);
|
||||
this.loading = false;
|
||||
});
|
||||
},
|
||||
|
||||
autoSlug() {
|
||||
if (!this.editId) {
|
||||
this.form.slug = this.form.titulo
|
||||
.toLowerCase().trim()
|
||||
.normalize('NFD').replace(/[\u0300-\u036f]/g, '')
|
||||
.replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
|
||||
}
|
||||
},
|
||||
|
||||
toggleRol(id) {
|
||||
const idx = this.form.rol_ids.indexOf(id);
|
||||
if (idx === -1) this.form.rol_ids.push(id);
|
||||
else this.form.rol_ids.splice(idx, 1);
|
||||
},
|
||||
|
||||
openAdd() {
|
||||
this.editId = null;
|
||||
this.form = {
|
||||
titulo: '', slug: '', saas_id: 0, categoria_id: 0,
|
||||
contenido: '', tipo_contenido: 'markdown', visibilidad: 'public',
|
||||
orden: 0, publicado: false, rol_ids: []
|
||||
};
|
||||
this.showModal = true;
|
||||
this.$nextTick(() => this.initMde());
|
||||
},
|
||||
|
||||
openEdit(id) {
|
||||
fetch(`/app/doc/paginas/${id}`)
|
||||
.then(r => r.json())
|
||||
.then(item => {
|
||||
this.editId = item.ID;
|
||||
this.form = {
|
||||
titulo: item.titulo, slug: item.slug,
|
||||
saas_id: item.saas_id, categoria_id: item.categoria_id,
|
||||
contenido: item.contenido, tipo_contenido: item.tipo_contenido,
|
||||
visibilidad: item.visibilidad, orden: item.orden,
|
||||
publicado: item.publicado,
|
||||
rol_ids: (item.roles || []).map(r => r.ID)
|
||||
};
|
||||
this.showModal = true;
|
||||
this.$nextTick(() => this.initMde(item.contenido));
|
||||
});
|
||||
},
|
||||
|
||||
initMde(val = '') {
|
||||
if (mdEditorInstance) { mdEditorInstance.toTextArea(); mdEditorInstance = null; }
|
||||
if (this.form.tipo_contenido !== 'markdown') return;
|
||||
const ta = document.getElementById('mdEditor');
|
||||
if (!ta) return;
|
||||
mdEditorInstance = new EasyMDE({
|
||||
element: ta,
|
||||
initialValue: val || this.form.contenido,
|
||||
spellChecker: false,
|
||||
autosave: { enabled: false },
|
||||
toolbar: ['bold','italic','heading','|','quote','code','|','unordered-list','ordered-list','|','link','image','|','preview','side-by-side','fullscreen','|','guide']
|
||||
});
|
||||
mdEditorInstance.codemirror.on('change', () => {
|
||||
this.form.contenido = mdEditorInstance.value();
|
||||
});
|
||||
},
|
||||
|
||||
toggleEditor() {
|
||||
this.$nextTick(() => {
|
||||
if (this.form.tipo_contenido === 'markdown') {
|
||||
this.initMde(this.form.contenido);
|
||||
} else {
|
||||
if (mdEditorInstance) { mdEditorInstance.toTextArea(); mdEditorInstance = null; }
|
||||
}
|
||||
});
|
||||
},
|
||||
|
||||
submitForm() {
|
||||
// Sincronizar contenido del editor Markdown antes de enviar
|
||||
if (mdEditorInstance) this.form.contenido = mdEditorInstance.value();
|
||||
|
||||
const url = this.editId ? `/app/doc/paginas/${this.editId}` : '/app/doc/paginas';
|
||||
const method = this.editId ? 'PUT' : 'POST';
|
||||
fetch(url, { method, headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(this.form) })
|
||||
.then(r => r.json())
|
||||
.then(d => { if (d.error) { alert(d.error); return; } this.closeModal(); this.load(this.page); });
|
||||
},
|
||||
|
||||
confirmDelete(id) { this.deleteId = id; this.showDeleteModal = true; },
|
||||
|
||||
doDelete() {
|
||||
fetch(`/app/doc/paginas/${this.deleteId}`, { method: 'DELETE' })
|
||||
.then(r => r.json())
|
||||
.then(() => { this.showDeleteModal = false; this.load(this.page); });
|
||||
},
|
||||
|
||||
closeModal() {
|
||||
if (mdEditorInstance) { mdEditorInstance.toTextArea(); mdEditorInstance = null; }
|
||||
this.showModal = false;
|
||||
this.showDeleteModal = false;
|
||||
}
|
||||
};
|
||||
}
|
||||
</script>
|
||||
@@ -0,0 +1,47 @@
|
||||
<!-- Vista Privada: Índice de Documentación de un SaaS (requiere login) -->
|
||||
<div class="bg-white rounded-lg shadow">
|
||||
<!-- Header -->
|
||||
<div class="border-b px-6 py-5 flex items-center gap-4">
|
||||
{{if .saas.LogoURL}}
|
||||
<img src="{{.saas.LogoURL}}" alt="{{.saas.Nombre}}" class="w-10 h-10 rounded-lg object-contain border border-gray-200">
|
||||
{{end}}
|
||||
<div>
|
||||
<h1 class="text-xl font-bold text-gray-800">{{.saas.Nombre}}</h1>
|
||||
<p class="text-sm text-gray-500">{{.saas.Descripcion}}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="p-6">
|
||||
{{if not .grupos}}
|
||||
<div class="text-center py-12 text-gray-400">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" class="w-10 h-10 mx-auto mb-3 opacity-40" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"/>
|
||||
</svg>
|
||||
<p>Sin páginas disponibles para tu perfil en este producto.</p>
|
||||
</div>
|
||||
{{else}}
|
||||
<div class="grid md:grid-cols-2 lg:grid-cols-3 gap-5">
|
||||
{{range .grupos}}
|
||||
<div class="border border-gray-200 rounded-lg overflow-hidden shadow-sm">
|
||||
<div class="bg-[#8eb02f] px-4 py-3">
|
||||
<h2 class="text-white font-semibold text-sm">{{.Categoria.Nombre}}</h2>
|
||||
</div>
|
||||
<ul class="divide-y divide-gray-100">
|
||||
{{range .Paginas}}
|
||||
<li>
|
||||
<a href="/app/docs/{{$.saas.Slug}}/{{.Slug}}"
|
||||
class="flex items-center justify-between px-4 py-2.5 hover:bg-gray-50 transition-colors text-sm">
|
||||
<span class="text-gray-700 hover:text-[#8eb02f]">{{.Titulo}}</span>
|
||||
{{if eq .Visibilidad "private"}}
|
||||
<span class="text-xs text-yellow-600 bg-yellow-50 px-1.5 py-0.5 rounded">🔒 Privado</span>
|
||||
{{end}}
|
||||
</a>
|
||||
</li>
|
||||
{{end}}
|
||||
</ul>
|
||||
</div>
|
||||
{{end}}
|
||||
</div>
|
||||
{{end}}
|
||||
</div>
|
||||
</div>
|
||||
@@ -0,0 +1,94 @@
|
||||
<!-- Vista Privada: Lectura de página de documentación (requiere login + rol) -->
|
||||
<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
|
||||
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/highlight.js@11.9.0/styles/github.min.css">
|
||||
<script src="https://cdn.jsdelivr.net/npm/highlight.js@11.9.0/lib/highlight.min.js"></script>
|
||||
|
||||
<div class="bg-white rounded-lg shadow">
|
||||
<!-- Topbar de navegación -->
|
||||
<div class="border-b px-6 py-3 flex items-center gap-2 text-sm">
|
||||
<a href="/app/docs/{{.saas.Slug}}" class="flex items-center gap-1 text-gray-500 hover:text-[#8eb02f] transition-colors">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" d="M15 19l-7-7 7-7"/>
|
||||
</svg>
|
||||
{{.saas.Nombre}}
|
||||
</a>
|
||||
<span class="text-gray-300">/</span>
|
||||
<span class="text-gray-400">{{.pagina.Categoria.Nombre}}</span>
|
||||
<span class="text-gray-300">/</span>
|
||||
<span class="text-gray-800 font-medium truncate">{{.pagina.Titulo}}</span>
|
||||
{{if eq .pagina.Visibilidad "private"}}
|
||||
<span class="ml-auto text-xs text-yellow-600 bg-yellow-50 border border-yellow-200 px-2 py-0.5 rounded-full">🔒 Acceso privado</span>
|
||||
{{end}}
|
||||
</div>
|
||||
|
||||
<div class="flex gap-0">
|
||||
<!-- Sidebar de navegación -->
|
||||
<aside class="hidden lg:block w-52 border-r flex-shrink-0 py-4 px-3">
|
||||
<div class="sticky top-4 space-y-4">
|
||||
{{range .grupos}}
|
||||
<div>
|
||||
<p class="text-xs font-semibold text-gray-400 uppercase tracking-wide mb-2 px-2">{{.Categoria.Nombre}}</p>
|
||||
<ul class="space-y-0.5">
|
||||
{{range .Paginas}}
|
||||
<li>
|
||||
<a href="/app/docs/{{$.saas.Slug}}/{{.Slug}}"
|
||||
class="flex items-center justify-between text-xs px-2 py-1.5 rounded transition-colors
|
||||
{{if eq .Slug $.pagina.Slug}}bg-[#8eb02f] text-white font-medium{{else}}text-gray-600 hover:bg-gray-100{{end}}">
|
||||
<span>{{.Titulo}}</span>
|
||||
{{if eq .Visibilidad "private"}}<span class="opacity-60 text-xs">🔒</span>{{end}}
|
||||
</a>
|
||||
</li>
|
||||
{{end}}
|
||||
</ul>
|
||||
</div>
|
||||
{{end}}
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
<!-- Contenido -->
|
||||
<main class="flex-1 min-w-0 p-6 lg:p-8">
|
||||
<div class="mb-6 pb-4 border-b border-gray-100">
|
||||
<span class="text-xs text-gray-400 bg-gray-100 px-2 py-0.5 rounded">{{.pagina.Categoria.Nombre}}</span>
|
||||
<h1 class="text-2xl font-bold text-gray-900 mt-2">{{.pagina.Titulo}}</h1>
|
||||
</div>
|
||||
|
||||
{{if eq .pagina.TipoContenido "markdown"}}
|
||||
<div id="docContent" class="prose prose-gray max-w-none"
|
||||
data-raw="{{.pagina.Contenido}}" data-type="markdown"></div>
|
||||
{{else}}
|
||||
<div class="prose prose-gray max-w-none">{{.pagina.Contenido}}</div>
|
||||
{{end}}
|
||||
</main>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<style>
|
||||
.prose h1,.prose h2,.prose h3,.prose h4 { font-weight:700; margin-top:1.5em; margin-bottom:0.5em; color:#1f2937; }
|
||||
.prose h1 { font-size:1.75rem; }
|
||||
.prose h2 { font-size:1.35rem; border-bottom:1px solid #e5e7eb; padding-bottom:.25rem; }
|
||||
.prose h3 { font-size:1.1rem; }
|
||||
.prose p { margin-bottom:1em; line-height:1.7; color:#374151; }
|
||||
.prose ul,.prose ol { margin:0.75em 0 0.75em 1.5em; color:#374151; }
|
||||
.prose li { margin-bottom:.25em; }
|
||||
.prose code { background:#f3f4f6; padding:2px 5px; border-radius:4px; font-size:.85em; font-family:monospace; }
|
||||
.prose pre { background:#1e293b; color:#e2e8f0; padding:1rem; border-radius:.5rem; overflow-x:auto; margin:1em 0; }
|
||||
.prose pre code { background:transparent; padding:0; font-size:.85em; }
|
||||
.prose blockquote { border-left:4px solid #8eb02f; padding-left:1rem; color:#6b7280; font-style:italic; margin:1em 0; }
|
||||
.prose a { color:#8eb02f; text-decoration:underline; }
|
||||
.prose table { width:100%; border-collapse:collapse; margin:1em 0; }
|
||||
.prose th,.prose td { border:1px solid #e5e7eb; padding:.5rem .75rem; text-align:left; }
|
||||
.prose th { background:#f9fafb; font-weight:600; }
|
||||
</style>
|
||||
|
||||
<script>
|
||||
document.addEventListener('DOMContentLoaded', function () {
|
||||
const el = document.getElementById('docContent');
|
||||
if (!el) return;
|
||||
const raw = el.getAttribute('data-raw') || '';
|
||||
el.removeAttribute('data-raw');
|
||||
el.innerHTML = marked.parse(raw);
|
||||
if (window.hljs) {
|
||||
el.querySelectorAll('pre code').forEach(block => hljs.highlightElement(block));
|
||||
}
|
||||
});
|
||||
</script>
|
||||
@@ -0,0 +1,56 @@
|
||||
<!-- Vista Pública: Índice de Documentación de un SaaS -->
|
||||
<!-- Marked.js para renderizar Markdown -->
|
||||
<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
|
||||
|
||||
<div class="min-h-screen bg-gray-50">
|
||||
<!-- Header del SaaS -->
|
||||
<div class="bg-white border-b shadow-sm">
|
||||
<div class="max-w-5xl mx-auto px-6 py-6 flex items-center gap-4">
|
||||
{{if .saas.LogoURL}}
|
||||
<img src="{{.saas.LogoURL}}" alt="{{.saas.Nombre}}" class="w-12 h-12 rounded-lg object-contain border border-gray-200">
|
||||
{{end}}
|
||||
<div>
|
||||
<h1 class="text-2xl font-bold text-gray-800">{{.saas.Nombre}}</h1>
|
||||
<p class="text-sm text-gray-500">{{.saas.Descripcion}}</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="max-w-5xl mx-auto px-6 py-8">
|
||||
{{if not .grupos}}
|
||||
<div class="text-center py-16 text-gray-400">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" class="w-12 h-12 mx-auto mb-3 opacity-40" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"/>
|
||||
</svg>
|
||||
<p class="text-lg font-medium">Sin documentación publicada</p>
|
||||
<p class="text-sm mt-1">Aún no hay páginas disponibles para este producto.</p>
|
||||
</div>
|
||||
{{else}}
|
||||
<div class="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
|
||||
{{range .grupos}}
|
||||
<div class="bg-white rounded-lg border border-gray-200 shadow-sm overflow-hidden">
|
||||
<div class="bg-[#8eb02f] px-4 py-3">
|
||||
<h2 class="text-white font-semibold text-sm">{{.Categoria.Nombre}}</h2>
|
||||
{{if .Categoria.Descripcion}}
|
||||
<p class="text-green-50 text-xs mt-0.5">{{.Categoria.Descripcion}}</p>
|
||||
{{end}}
|
||||
</div>
|
||||
<ul class="divide-y divide-gray-100">
|
||||
{{range .Paginas}}
|
||||
<li>
|
||||
<a href="/docs/{{$.saas.Slug}}/{{.Slug}}"
|
||||
class="flex items-center gap-2 px-4 py-3 hover:bg-gray-50 transition-colors text-sm text-gray-700 hover:text-[#8eb02f]">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4 text-gray-400 flex-shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"/>
|
||||
</svg>
|
||||
{{.Titulo}}
|
||||
</a>
|
||||
</li>
|
||||
{{end}}
|
||||
</ul>
|
||||
</div>
|
||||
{{end}}
|
||||
</div>
|
||||
{{end}}
|
||||
</div>
|
||||
</div>
|
||||
@@ -0,0 +1,108 @@
|
||||
<!-- Vista Pública: Lectura de una página de documentación -->
|
||||
<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
|
||||
<!-- Highlight.js para bloques de código en Markdown -->
|
||||
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/highlight.js@11.9.0/styles/github.min.css">
|
||||
<script src="https://cdn.jsdelivr.net/npm/highlight.js@11.9.0/lib/highlight.min.js"></script>
|
||||
|
||||
<div class="min-h-screen bg-gray-50 flex flex-col">
|
||||
<!-- Topbar del SaaS -->
|
||||
<div class="bg-white border-b shadow-sm sticky top-0 z-10">
|
||||
<div class="max-w-6xl mx-auto px-6 py-3 flex items-center gap-3">
|
||||
<a href="/docs/{{.saas.Slug}}" class="flex items-center gap-2 text-gray-600 hover:text-[#8eb02f] transition-colors text-sm">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" d="M15 19l-7-7 7-7"/>
|
||||
</svg>
|
||||
{{.saas.Nombre}}
|
||||
</a>
|
||||
<span class="text-gray-300">/</span>
|
||||
<span class="text-sm text-gray-500 truncate">{{.pagina.Titulo}}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="max-w-6xl mx-auto px-4 py-6 w-full flex gap-6 flex-1">
|
||||
|
||||
<!-- Sidebar de navegación -->
|
||||
<aside class="hidden lg:block w-56 flex-shrink-0">
|
||||
<div class="sticky top-20 space-y-4">
|
||||
{{range .grupos}}
|
||||
<div>
|
||||
<p class="text-xs font-semibold text-gray-400 uppercase tracking-wide mb-2">{{.Categoria.Nombre}}</p>
|
||||
<ul class="space-y-0.5">
|
||||
{{range .Paginas}}
|
||||
<li>
|
||||
<a href="/docs/{{$.saas.Slug}}/{{.Slug}}"
|
||||
class="block text-sm px-2 py-1.5 rounded transition-colors
|
||||
{{if eq .Slug $.pagina.Slug}}bg-[#8eb02f] text-white font-medium{{else}}text-gray-600 hover:bg-gray-100 hover:text-gray-800{{end}}">
|
||||
{{.Titulo}}
|
||||
</a>
|
||||
</li>
|
||||
{{end}}
|
||||
</ul>
|
||||
</div>
|
||||
{{end}}
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
<!-- Contenido principal -->
|
||||
<main class="flex-1 min-w-0">
|
||||
<div class="bg-white rounded-lg border border-gray-200 shadow-sm p-6 lg:p-8">
|
||||
<div class="mb-6 pb-4 border-b border-gray-100">
|
||||
<div class="flex items-center gap-2 mb-2">
|
||||
<span class="text-xs text-gray-400 bg-gray-100 px-2 py-0.5 rounded">{{.pagina.Categoria.Nombre}}</span>
|
||||
</div>
|
||||
<h1 class="text-2xl font-bold text-gray-900">{{.pagina.Titulo}}</h1>
|
||||
</div>
|
||||
|
||||
<!-- Renderizado del contenido -->
|
||||
{{if eq .pagina.TipoContenido "markdown"}}
|
||||
<div id="docContent" class="prose prose-gray max-w-none"
|
||||
data-raw="{{.pagina.Contenido}}" data-type="markdown"></div>
|
||||
{{else}}
|
||||
<div class="prose prose-gray max-w-none">
|
||||
{{.pagina.Contenido}}
|
||||
</div>
|
||||
{{end}}
|
||||
</div>
|
||||
|
||||
<!-- Navegación anterior / siguiente -->
|
||||
<div class="flex justify-between mt-4 text-sm">
|
||||
<span></span>
|
||||
<a href="/docs/{{.saas.Slug}}" class="text-[#8eb02f] hover:underline">← Volver al índice</a>
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<style>
|
||||
/* Estilos de prosa para contenido Markdown */
|
||||
.prose h1,.prose h2,.prose h3,.prose h4 { font-weight:700; margin-top:1.5em; margin-bottom:0.5em; color:#1f2937; }
|
||||
.prose h1 { font-size:1.75rem; }
|
||||
.prose h2 { font-size:1.35rem; border-bottom:1px solid #e5e7eb; padding-bottom:.25rem; }
|
||||
.prose h3 { font-size:1.1rem; }
|
||||
.prose p { margin-bottom:1em; line-height:1.7; color:#374151; }
|
||||
.prose ul,.prose ol { margin:0.75em 0 0.75em 1.5em; color:#374151; }
|
||||
.prose li { margin-bottom:.25em; }
|
||||
.prose code { background:#f3f4f6; padding:2px 5px; border-radius:4px; font-size:.85em; font-family:monospace; }
|
||||
.prose pre { background:#1e293b; color:#e2e8f0; padding:1rem; border-radius:.5rem; overflow-x:auto; margin:1em 0; }
|
||||
.prose pre code { background:transparent; padding:0; font-size:.85em; }
|
||||
.prose blockquote { border-left:4px solid #8eb02f; padding-left:1rem; color:#6b7280; font-style:italic; margin:1em 0; }
|
||||
.prose a { color:#8eb02f; text-decoration:underline; }
|
||||
.prose table { width:100%; border-collapse:collapse; margin:1em 0; }
|
||||
.prose th,.prose td { border:1px solid #e5e7eb; padding:.5rem .75rem; text-align:left; }
|
||||
.prose th { background:#f9fafb; font-weight:600; }
|
||||
</style>
|
||||
|
||||
<script>
|
||||
document.addEventListener('DOMContentLoaded', function () {
|
||||
const el = document.getElementById('docContent');
|
||||
if (!el) return;
|
||||
// El contenido viene como texto en el atributo data-raw para evitar doble escape
|
||||
const raw = el.getAttribute('data-raw') || '';
|
||||
el.removeAttribute('data-raw');
|
||||
el.innerHTML = marked.parse(raw);
|
||||
// Resaltado de código
|
||||
if (window.hljs) {
|
||||
el.querySelectorAll('pre code').forEach(block => hljs.highlightElement(block));
|
||||
}
|
||||
});
|
||||
</script>
|
||||
@@ -0,0 +1,224 @@
|
||||
<!-- Vista: Gestión de Productos SaaS -->
|
||||
<div x-data="saasApp()" x-init="init()" @keydown.escape="closeModal()" class="bg-white rounded-lg shadow">
|
||||
<div class="container mx-auto p-6 w-full">
|
||||
<h1 class="text-2xl font-bold mb-1">Productos SaaS</h1>
|
||||
<p class="text-sm text-gray-500 mb-4">Gestiona los productos SaaS a los que se asociará documentación.</p>
|
||||
|
||||
<div class="flex flex-col md:flex-row md:justify-between md:items-center gap-3 mb-4">
|
||||
<!-- Búsqueda -->
|
||||
<div class="relative">
|
||||
<input type="text" x-model="search" @input="load(1)" placeholder="Buscar..."
|
||||
class="border border-gray-300 rounded w-full md:w-60 p-2 text-sm">
|
||||
<div x-show="loading" class="absolute right-2 top-2">
|
||||
<svg class="animate-spin h-5 w-5 text-gray-400" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
|
||||
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
|
||||
<path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8v4a4 4 0 00-4 4H4z"></path>
|
||||
</svg>
|
||||
</div>
|
||||
</div>
|
||||
<button @click="openAdd()" class="bg-[#8eb02f] text-white px-4 py-2 rounded text-sm">+ Nuevo SaaS</button>
|
||||
</div>
|
||||
|
||||
<!-- Tabla -->
|
||||
<div class="overflow-x-auto">
|
||||
<table class="table-auto w-full text-sm">
|
||||
<thead class="border-b border-gray-200 text-left font-semibold text-gray-600">
|
||||
<tr>
|
||||
<th class="py-2 px-4 border-b">Nombre</th>
|
||||
<th class="py-2 px-4 border-b">Slug</th>
|
||||
<th class="py-2 px-4 border-b">Servicio vinculado</th>
|
||||
<th class="py-2 px-4 border-b">Orden</th>
|
||||
<th class="py-2 px-4 border-b w-10">Estado</th>
|
||||
<th class="py-2 px-4 border-b w-24"></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody class="text-gray-500">
|
||||
<template x-if="items.length === 0">
|
||||
<tr><td colspan="6" class="py-4 text-center text-gray-400">Sin registros</td></tr>
|
||||
</template>
|
||||
<template x-for="item in items" :key="item.ID">
|
||||
<tr class="hover:bg-gray-50 border-b border-gray-100">
|
||||
<td class="py-2 px-4 font-medium text-gray-800" x-text="item.nombre"></td>
|
||||
<td class="py-2 px-4 font-mono text-xs text-gray-500" x-text="item.slug"></td>
|
||||
<td class="py-2 px-4 text-xs" x-text="item.servicio ? item.servicio.nombre : '-'"></td>
|
||||
<td class="py-2 px-4 text-xs" x-text="item.orden"></td>
|
||||
<td class="py-2 px-4">
|
||||
<span x-text="item.activo ? 'Activo' : 'Inactivo'"
|
||||
:class="item.activo ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700'"
|
||||
class="text-xs px-2 py-0.5 rounded-full"></span>
|
||||
</td>
|
||||
<td class="py-2 px-4 flex gap-2 justify-end">
|
||||
<button @click="openEdit(item)" title="Editar" class="text-blue-500 hover:text-blue-700">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"/>
|
||||
</svg>
|
||||
</button>
|
||||
<button @click="confirmDelete(item.ID)" title="Eliminar" class="text-red-400 hover:text-red-600">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"/>
|
||||
</svg>
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
</template>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<!-- Paginación -->
|
||||
<div class="flex items-center justify-between mt-4 text-sm">
|
||||
<span class="text-gray-500">Total: <strong x-text="total"></strong></span>
|
||||
<div class="flex gap-1">
|
||||
<template x-for="p in totalPages" :key="p">
|
||||
<button @click="load(p)"
|
||||
:class="p === page ? 'bg-[#8eb02f] text-white' : 'bg-gray-100 text-gray-600 hover:bg-gray-200'"
|
||||
class="px-3 py-1 rounded text-xs" x-text="p"></button>
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Modal Añadir / Editar -->
|
||||
<div x-cloak x-show="showModal" x-transition
|
||||
class="fixed inset-0 bg-gray-800 bg-opacity-75 flex z-40 justify-center items-center text-sm">
|
||||
<div class="bg-white p-6 rounded shadow-lg w-full max-w-md overflow-y-auto max-h-[90vh]">
|
||||
<h2 class="text-lg font-bold mb-4" x-text="editId ? 'Editar SaaS' : 'Nuevo SaaS'"></h2>
|
||||
<form @submit.prevent="submitForm()">
|
||||
<div class="grid grid-cols-2 gap-3">
|
||||
<div class="col-span-2">
|
||||
<label class="block text-xs font-medium mb-1">Nombre *</label>
|
||||
<input type="text" x-model="form.nombre" @input="autoSlug()" required
|
||||
class="border border-gray-300 rounded w-full p-2 text-sm">
|
||||
</div>
|
||||
<div class="col-span-2">
|
||||
<label class="block text-xs font-medium mb-1">Slug * <span class="text-gray-400 font-normal">(URL amigable)</span></label>
|
||||
<input type="text" x-model="form.slug" required
|
||||
class="border border-gray-300 rounded w-full p-2 text-sm font-mono">
|
||||
</div>
|
||||
<div class="col-span-2">
|
||||
<label class="block text-xs font-medium mb-1">Descripción</label>
|
||||
<textarea x-model="form.descripcion" rows="2"
|
||||
class="border border-gray-300 rounded w-full p-2 text-sm"></textarea>
|
||||
</div>
|
||||
<div class="col-span-2">
|
||||
<label class="block text-xs font-medium mb-1">URL del Logo</label>
|
||||
<input type="text" x-model="form.logo_url"
|
||||
class="border border-gray-300 rounded w-full p-2 text-sm">
|
||||
</div>
|
||||
<div class="col-span-2">
|
||||
<label class="block text-xs font-medium mb-1">Servicio vinculado <span class="text-gray-400 font-normal">(opcional)</span></label>
|
||||
<select x-model.number="form.servicio_id" class="border border-gray-300 rounded w-full p-2 text-sm">
|
||||
<option :value="null">— Sin vincular —</option>
|
||||
<template x-for="s in servicios" :key="s.ID">
|
||||
<option :value="s.ID" x-text="s.nombre"></option>
|
||||
</template>
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-xs font-medium mb-1">Orden</label>
|
||||
<input type="number" x-model.number="form.orden" min="0"
|
||||
class="border border-gray-300 rounded w-full p-2 text-sm">
|
||||
</div>
|
||||
<div class="flex items-center gap-2 mt-4">
|
||||
<input type="checkbox" id="activo" x-model="form.activo" class="w-4 h-4">
|
||||
<label for="activo" class="text-xs font-medium">Activo</label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex justify-between mt-5">
|
||||
<button type="submit" class="bg-[#8eb02f] text-white px-4 py-2 rounded text-sm">Guardar</button>
|
||||
<button type="button" @click="closeModal()" class="bg-gray-500 text-white px-4 py-2 rounded text-sm">Cancelar</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Modal Confirmar Eliminación -->
|
||||
<div x-cloak x-show="showDeleteModal" x-transition
|
||||
class="fixed inset-0 bg-gray-800 bg-opacity-75 flex z-50 justify-center items-center text-sm">
|
||||
<div class="bg-white p-6 rounded shadow-lg max-w-sm w-full">
|
||||
<h2 class="text-lg font-bold mb-3">Confirmar eliminación</h2>
|
||||
<p class="text-gray-600 mb-4">¿Eliminar este producto SaaS? También se eliminará su documentación asociada.</p>
|
||||
<div class="flex justify-end gap-2">
|
||||
<button @click="doDelete()" class="bg-red-500 text-white px-4 py-2 rounded text-sm">Eliminar</button>
|
||||
<button @click="showDeleteModal = false" class="bg-gray-500 text-white px-4 py-2 rounded text-sm">Cancelar</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
function saasApp() {
|
||||
return {
|
||||
items: [], servicios: [],
|
||||
total: 0, totalPages: 1, page: 1, search: '',
|
||||
loading: false,
|
||||
showModal: false, showDeleteModal: false,
|
||||
editId: null, deleteId: null,
|
||||
form: { nombre: '', slug: '', descripcion: '', logo_url: '', servicio_id: null, activo: true, orden: 0 },
|
||||
|
||||
init() { this.load(1); },
|
||||
|
||||
load(p = 1) {
|
||||
this.page = p;
|
||||
this.loading = true;
|
||||
const qs = new URLSearchParams({ page: p, search: this.search });
|
||||
fetch(`/app/loadsaas?${qs}`)
|
||||
.then(r => r.json())
|
||||
.then(d => {
|
||||
this.items = d.items || [];
|
||||
this.servicios = d.servicios || [];
|
||||
this.total = d.total;
|
||||
this.totalPages = Array.from({ length: d.totalPages }, (_, i) => i + 1);
|
||||
this.loading = false;
|
||||
});
|
||||
},
|
||||
|
||||
autoSlug() {
|
||||
if (!this.editId) {
|
||||
this.form.slug = this.form.nombre
|
||||
.toLowerCase().trim()
|
||||
.normalize('NFD').replace(/[\u0300-\u036f]/g, '')
|
||||
.replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
|
||||
}
|
||||
},
|
||||
|
||||
openAdd() {
|
||||
this.editId = null;
|
||||
this.form = { nombre: '', slug: '', descripcion: '', logo_url: '', servicio_id: null, activo: true, orden: 0 };
|
||||
this.showModal = true;
|
||||
},
|
||||
|
||||
openEdit(item) {
|
||||
this.editId = item.ID;
|
||||
this.form = {
|
||||
nombre: item.nombre, slug: item.slug, descripcion: item.descripcion,
|
||||
logo_url: item.logo_url, servicio_id: item.servicio_id,
|
||||
activo: item.activo, orden: item.orden
|
||||
};
|
||||
this.showModal = true;
|
||||
},
|
||||
|
||||
submitForm() {
|
||||
const url = this.editId ? `/app/saas/${this.editId}` : '/app/saas';
|
||||
const method = this.editId ? 'PUT' : 'POST';
|
||||
fetch(url, { method, headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(this.form) })
|
||||
.then(r => r.json())
|
||||
.then(d => {
|
||||
if (d.error) { alert(d.error); return; }
|
||||
this.closeModal();
|
||||
this.load(this.page);
|
||||
});
|
||||
},
|
||||
|
||||
confirmDelete(id) { this.deleteId = id; this.showDeleteModal = true; },
|
||||
|
||||
doDelete() {
|
||||
fetch(`/app/saas/${this.deleteId}`, { method: 'DELETE' })
|
||||
.then(r => r.json())
|
||||
.then(() => { this.showDeleteModal = false; this.load(this.page); });
|
||||
},
|
||||
|
||||
closeModal() { this.showModal = false; this.showDeleteModal = false; }
|
||||
};
|
||||
}
|
||||
</script>
|
||||
@@ -0,0 +1,112 @@
|
||||
package controllers
|
||||
|
||||
import (
|
||||
"math"
|
||||
"strconv"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"github.com/sujit-baniya/fiber-boilerplate/pkg/models"
|
||||
)
|
||||
|
||||
// DocCategoriasIndex renderiza el panel de gestión de categorías de documentación.
|
||||
func DocCategoriasIndex(c *fiber.Ctx) error {
|
||||
data := fiber.Map{
|
||||
"user": c.Locals("user").(map[string]interface{}),
|
||||
"modules": c.Locals("userModules"),
|
||||
}
|
||||
if err := c.Render("docs/categorias", data, "layouts/main"); err != nil {
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"error": err.Error()})
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetDocCategorias devuelve la lista paginada de categorías en JSON.
|
||||
func GetDocCategorias(c *fiber.Ctx) error {
|
||||
page, _ := strconv.Atoi(c.Query("page", "1"))
|
||||
if page < 1 {
|
||||
page = 1
|
||||
}
|
||||
search := c.Query("search", "")
|
||||
limit := 10
|
||||
offset := (page - 1) * limit
|
||||
|
||||
items, total, err := models.GetAllDocCategorias(limit, offset, search)
|
||||
if err != nil {
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"error": err.Error()})
|
||||
}
|
||||
return c.JSON(fiber.Map{
|
||||
"items": items,
|
||||
"total": total,
|
||||
"totalPages": int(math.Ceil(float64(total) / float64(limit))),
|
||||
"page": page,
|
||||
"limit": limit,
|
||||
})
|
||||
}
|
||||
|
||||
// CreateDocCategoria crea una nueva categoría global.
|
||||
func CreateDocCategoria(c *fiber.Ctx) error {
|
||||
type Req struct {
|
||||
Nombre string `json:"nombre"`
|
||||
Slug string `json:"slug"`
|
||||
Descripcion string `json:"descripcion"`
|
||||
Orden int `json:"orden"`
|
||||
}
|
||||
var req Req
|
||||
if err := c.BodyParser(&req); err != nil {
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "Datos inválidos"})
|
||||
}
|
||||
if req.Nombre == "" || req.Slug == "" {
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "Nombre y slug son obligatorios"})
|
||||
}
|
||||
item := &models.DocCategoria{
|
||||
Nombre: req.Nombre,
|
||||
Slug: req.Slug,
|
||||
Descripcion: req.Descripcion,
|
||||
Orden: req.Orden,
|
||||
}
|
||||
if err := models.CreateDocCategoria(item); err != nil {
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"error": err.Error()})
|
||||
}
|
||||
return c.JSON(fiber.Map{"message": "Categoría creada", "item": item})
|
||||
}
|
||||
|
||||
// UpdateDocCategoria actualiza una categoría existente.
|
||||
func UpdateDocCategoria(c *fiber.Ctx) error {
|
||||
id, err := strconv.ParseUint(c.Params("id"), 10, 32)
|
||||
if err != nil {
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "ID inválido"})
|
||||
}
|
||||
type Req struct {
|
||||
Nombre string `json:"nombre"`
|
||||
Slug string `json:"slug"`
|
||||
Descripcion string `json:"descripcion"`
|
||||
Orden int `json:"orden"`
|
||||
}
|
||||
var req Req
|
||||
if err := c.BodyParser(&req); err != nil {
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "Datos inválidos"})
|
||||
}
|
||||
item := &models.DocCategoria{
|
||||
Nombre: req.Nombre,
|
||||
Slug: req.Slug,
|
||||
Descripcion: req.Descripcion,
|
||||
Orden: req.Orden,
|
||||
}
|
||||
item.ID = uint(id)
|
||||
if err := models.UpdateDocCategoria(item); err != nil {
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"error": err.Error()})
|
||||
}
|
||||
return c.JSON(fiber.Map{"message": "Categoría actualizada"})
|
||||
}
|
||||
|
||||
// DeleteDocCategoria elimina una categoría.
|
||||
func DeleteDocCategoria(c *fiber.Ctx) error {
|
||||
id, err := strconv.ParseUint(c.Params("id"), 10, 32)
|
||||
if err != nil {
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "ID inválido"})
|
||||
}
|
||||
if err := models.DeleteDocCategoria(uint(id)); err != nil {
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"error": err.Error()})
|
||||
}
|
||||
return c.JSON(fiber.Map{"message": "Categoría eliminada"})
|
||||
}
|
||||
@@ -0,0 +1,359 @@
|
||||
package controllers
|
||||
|
||||
import (
|
||||
"math"
|
||||
"strconv"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"github.com/sujit-baniya/fiber-boilerplate/pkg/models"
|
||||
)
|
||||
|
||||
// DocPaginasIndex renderiza el panel de gestión de páginas de documentación.
|
||||
func DocPaginasIndex(c *fiber.Ctx) error {
|
||||
data := fiber.Map{
|
||||
"user": c.Locals("user").(map[string]interface{}),
|
||||
"modules": c.Locals("userModules"),
|
||||
}
|
||||
if err := c.Render("docs/paginas", data, "layouts/main"); err != nil {
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"error": err.Error()})
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetDocPaginas devuelve la lista paginada de páginas en JSON.
|
||||
func GetDocPaginas(c *fiber.Ctx) error {
|
||||
page, _ := strconv.Atoi(c.Query("page", "1"))
|
||||
if page < 1 {
|
||||
page = 1
|
||||
}
|
||||
search := c.Query("search", "")
|
||||
limit := 10
|
||||
offset := (page - 1) * limit
|
||||
|
||||
var saasID, catID uint
|
||||
if v, err := strconv.ParseUint(c.Query("saas_id", "0"), 10, 32); err == nil {
|
||||
saasID = uint(v)
|
||||
}
|
||||
if v, err := strconv.ParseUint(c.Query("categoria_id", "0"), 10, 32); err == nil {
|
||||
catID = uint(v)
|
||||
}
|
||||
|
||||
items, total, err := models.GetAllDocPaginas(limit, offset, search, saasID, catID)
|
||||
if err != nil {
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"error": err.Error()})
|
||||
}
|
||||
|
||||
// Selects para el formulario
|
||||
saasItems, _ := models.GetAllSaasProductosSelect()
|
||||
categorias, _ := models.GetAllDocCategoriasSelect()
|
||||
roles, _ := models.AllRolesSelect()
|
||||
|
||||
return c.JSON(fiber.Map{
|
||||
"items": items,
|
||||
"saas": saasItems,
|
||||
"categorias": categorias,
|
||||
"roles": roles,
|
||||
"total": total,
|
||||
"totalPages": int(math.Ceil(float64(total) / float64(limit))),
|
||||
"page": page,
|
||||
"limit": limit,
|
||||
})
|
||||
}
|
||||
|
||||
// GetDocPaginaDetalle devuelve una página por ID con todos sus datos para edición.
|
||||
func GetDocPaginaDetalle(c *fiber.Ctx) error {
|
||||
id, err := strconv.ParseUint(c.Params("id"), 10, 32)
|
||||
if err != nil {
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "ID inválido"})
|
||||
}
|
||||
item, err := models.GetDocPaginaByID(uint(id))
|
||||
if err != nil {
|
||||
return c.Status(fiber.StatusNotFound).JSON(fiber.Map{"error": "Página no encontrada"})
|
||||
}
|
||||
return c.JSON(item)
|
||||
}
|
||||
|
||||
// CreateDocPagina crea una nueva página de documentación.
|
||||
func CreateDocPagina(c *fiber.Ctx) error {
|
||||
type Req struct {
|
||||
SaasID uint `json:"saas_id"`
|
||||
CategoriaID uint `json:"categoria_id"`
|
||||
Titulo string `json:"titulo"`
|
||||
Slug string `json:"slug"`
|
||||
Contenido string `json:"contenido"`
|
||||
TipoContenido string `json:"tipo_contenido"`
|
||||
Visibilidad string `json:"visibilidad"`
|
||||
Orden int `json:"orden"`
|
||||
Publicado bool `json:"publicado"`
|
||||
RolIDs []uint `json:"rol_ids"`
|
||||
}
|
||||
var req Req
|
||||
if err := c.BodyParser(&req); err != nil {
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "Datos inválidos"})
|
||||
}
|
||||
if req.Titulo == "" || req.Slug == "" || req.SaasID == 0 || req.CategoriaID == 0 {
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "Título, slug, saas y categoría son obligatorios"})
|
||||
}
|
||||
if req.TipoContenido == "" {
|
||||
req.TipoContenido = "markdown"
|
||||
}
|
||||
if req.Visibilidad == "" {
|
||||
req.Visibilidad = "public"
|
||||
}
|
||||
|
||||
userMap, _ := c.Locals("user").(map[string]interface{})
|
||||
var creadoPor uint
|
||||
if userMap != nil {
|
||||
if idVal, ok := userMap["id"]; ok {
|
||||
switch v := idVal.(type) {
|
||||
case float64:
|
||||
creadoPor = uint(v)
|
||||
case uint:
|
||||
creadoPor = v
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
item := &models.DocPagina{
|
||||
SaasID: req.SaasID,
|
||||
CategoriaID: req.CategoriaID,
|
||||
Titulo: req.Titulo,
|
||||
Slug: req.Slug,
|
||||
Contenido: req.Contenido,
|
||||
TipoContenido: req.TipoContenido,
|
||||
Visibilidad: req.Visibilidad,
|
||||
Orden: req.Orden,
|
||||
Publicado: req.Publicado,
|
||||
CreadoPor: creadoPor,
|
||||
}
|
||||
if err := models.CreateDocPagina(item, req.RolIDs); err != nil {
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"error": err.Error()})
|
||||
}
|
||||
return c.JSON(fiber.Map{"message": "Página creada", "item": item})
|
||||
}
|
||||
|
||||
// UpdateDocPagina actualiza una página existente.
|
||||
func UpdateDocPagina(c *fiber.Ctx) error {
|
||||
id, err := strconv.ParseUint(c.Params("id"), 10, 32)
|
||||
if err != nil {
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "ID inválido"})
|
||||
}
|
||||
type Req struct {
|
||||
SaasID uint `json:"saas_id"`
|
||||
CategoriaID uint `json:"categoria_id"`
|
||||
Titulo string `json:"titulo"`
|
||||
Slug string `json:"slug"`
|
||||
Contenido string `json:"contenido"`
|
||||
TipoContenido string `json:"tipo_contenido"`
|
||||
Visibilidad string `json:"visibilidad"`
|
||||
Orden int `json:"orden"`
|
||||
Publicado bool `json:"publicado"`
|
||||
RolIDs []uint `json:"rol_ids"`
|
||||
}
|
||||
var req Req
|
||||
if err := c.BodyParser(&req); err != nil {
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "Datos inválidos"})
|
||||
}
|
||||
item := &models.DocPagina{
|
||||
SaasID: req.SaasID,
|
||||
CategoriaID: req.CategoriaID,
|
||||
Titulo: req.Titulo,
|
||||
Slug: req.Slug,
|
||||
Contenido: req.Contenido,
|
||||
TipoContenido: req.TipoContenido,
|
||||
Visibilidad: req.Visibilidad,
|
||||
Orden: req.Orden,
|
||||
Publicado: req.Publicado,
|
||||
}
|
||||
item.ID = uint(id)
|
||||
if err := models.UpdateDocPagina(item, req.RolIDs); err != nil {
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"error": err.Error()})
|
||||
}
|
||||
return c.JSON(fiber.Map{"message": "Página actualizada"})
|
||||
}
|
||||
|
||||
// DeleteDocPagina elimina una página de documentación.
|
||||
func DeleteDocPagina(c *fiber.Ctx) error {
|
||||
id, err := strconv.ParseUint(c.Params("id"), 10, 32)
|
||||
if err != nil {
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "ID inválido"})
|
||||
}
|
||||
if err := models.DeleteDocPagina(uint(id)); err != nil {
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"error": err.Error()})
|
||||
}
|
||||
return c.JSON(fiber.Map{"message": "Página eliminada"})
|
||||
}
|
||||
|
||||
// ─── Rutas públicas / privadas de lectura ─────────────────────────────────────
|
||||
|
||||
// DocsPublicoIndex renderiza el índice público de un SaaS (sin login).
|
||||
func DocsPublicoIndex(c *fiber.Ctx) error {
|
||||
saasSlug := c.Params("saas")
|
||||
saas, err := models.GetSaasProductoBySlug(saasSlug)
|
||||
if err != nil {
|
||||
return c.Status(fiber.StatusNotFound).Render("errors/404", fiber.Map{}, "layouts/public")
|
||||
}
|
||||
|
||||
paginas, err := models.GetDocPaginasPublicas(saas.ID)
|
||||
if err != nil {
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"error": err.Error()})
|
||||
}
|
||||
|
||||
// Agrupar por categoría
|
||||
grupos := agruparPorCategoria(paginas)
|
||||
|
||||
return c.Render("docs/public-index", fiber.Map{
|
||||
"saas": saas,
|
||||
"grupos": grupos,
|
||||
}, "layouts/public")
|
||||
}
|
||||
|
||||
// DocsPublicaPagina renderiza una página pública individual.
|
||||
func DocsPublicaPagina(c *fiber.Ctx) error {
|
||||
saasSlug := c.Params("saas")
|
||||
slug := c.Params("slug")
|
||||
|
||||
saas, err := models.GetSaasProductoBySlug(saasSlug)
|
||||
if err != nil {
|
||||
return c.Status(fiber.StatusNotFound).Render("errors/404", fiber.Map{}, "layouts/public")
|
||||
}
|
||||
|
||||
pagina, err := models.GetDocPaginaBySlug(saas.ID, slug)
|
||||
if err != nil || !pagina.Publicado {
|
||||
return c.Status(fiber.StatusNotFound).Render("errors/404", fiber.Map{}, "layouts/public")
|
||||
}
|
||||
if pagina.Visibilidad == "private" {
|
||||
return c.Status(fiber.StatusForbidden).Render("errors/403", fiber.Map{}, "layouts/public")
|
||||
}
|
||||
|
||||
// Índice lateral: páginas públicas del mismo SaaS
|
||||
todas, _ := models.GetDocPaginasPublicas(saas.ID)
|
||||
grupos := agruparPorCategoria(todas)
|
||||
|
||||
return c.Render("docs/public-page", fiber.Map{
|
||||
"saas": saas,
|
||||
"pagina": pagina,
|
||||
"grupos": grupos,
|
||||
}, "layouts/public")
|
||||
}
|
||||
|
||||
// DocsPrivadoIndex renderiza el índice de un SaaS para usuarios autenticados (incluye privadas con rol).
|
||||
func DocsPrivadoIndex(c *fiber.Ctx) error {
|
||||
saasSlug := c.Params("saas")
|
||||
saas, err := models.GetSaasProductoBySlug(saasSlug)
|
||||
if err != nil {
|
||||
return c.Status(fiber.StatusNotFound).Render("errors/404", fiber.Map{}, "layouts/main")
|
||||
}
|
||||
|
||||
rolNames := getUserRolNames(c)
|
||||
paginas, err := models.GetDocPaginasParaRoles(saas.ID, rolNames)
|
||||
if err != nil {
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"error": err.Error()})
|
||||
}
|
||||
grupos := agruparPorCategoria(paginas)
|
||||
|
||||
return c.Render("docs/private-index", fiber.Map{
|
||||
"user": c.Locals("user"),
|
||||
"saas": saas,
|
||||
"grupos": grupos,
|
||||
}, "layouts/main")
|
||||
}
|
||||
|
||||
// DocsPrivadaPagina renderiza una página con verificación de rol.
|
||||
func DocsPrivadaPagina(c *fiber.Ctx) error {
|
||||
saasSlug := c.Params("saas")
|
||||
slug := c.Params("slug")
|
||||
|
||||
saas, err := models.GetSaasProductoBySlug(saasSlug)
|
||||
if err != nil {
|
||||
return c.Status(fiber.StatusNotFound).Render("errors/404", fiber.Map{}, "layouts/main")
|
||||
}
|
||||
|
||||
pagina, err := models.GetDocPaginaBySlug(saas.ID, slug)
|
||||
if err != nil || !pagina.Publicado {
|
||||
return c.Status(fiber.StatusNotFound).Render("errors/404", fiber.Map{}, "layouts/main")
|
||||
}
|
||||
|
||||
if pagina.Visibilidad == "private" {
|
||||
// Verificar que el usuario tenga al menos un rol asignado a la página
|
||||
rolNames := getUserRolNames(c)
|
||||
if !paginaAccesible(pagina, rolNames) {
|
||||
return c.Status(fiber.StatusForbidden).Render("errors/403", fiber.Map{
|
||||
"user": c.Locals("user"),
|
||||
}, "layouts/main")
|
||||
}
|
||||
}
|
||||
|
||||
rolNames := getUserRolNames(c)
|
||||
todas, _ := models.GetDocPaginasParaRoles(saas.ID, rolNames)
|
||||
grupos := agruparPorCategoria(todas)
|
||||
|
||||
return c.Render("docs/private-page", fiber.Map{
|
||||
"user": c.Locals("user"),
|
||||
"modules": c.Locals("userModules"),
|
||||
"saas": saas,
|
||||
"pagina": pagina,
|
||||
"grupos": grupos,
|
||||
}, "layouts/main")
|
||||
}
|
||||
|
||||
// ─── helpers ──────────────────────────────────────────────────────────────────
|
||||
|
||||
type GrupoCategoria struct {
|
||||
Categoria models.DocCategoria
|
||||
Paginas []models.DocPagina
|
||||
}
|
||||
|
||||
func agruparPorCategoria(paginas []models.DocPagina) []GrupoCategoria {
|
||||
orden := []uint{}
|
||||
mapa := map[uint]*GrupoCategoria{}
|
||||
for _, p := range paginas {
|
||||
if _, ok := mapa[p.CategoriaID]; !ok {
|
||||
orden = append(orden, p.CategoriaID)
|
||||
mapa[p.CategoriaID] = &GrupoCategoria{Categoria: p.Categoria}
|
||||
}
|
||||
mapa[p.CategoriaID].Paginas = append(mapa[p.CategoriaID].Paginas, p)
|
||||
}
|
||||
var result []GrupoCategoria
|
||||
for _, id := range orden {
|
||||
result = append(result, *mapa[id])
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func getUserRolNames(c *fiber.Ctx) []string {
|
||||
userMap, ok := c.Locals("user").(map[string]interface{})
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
raw, ok := userMap["roles"]
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
var names []string
|
||||
switch v := raw.(type) {
|
||||
case []string:
|
||||
names = v
|
||||
case []interface{}:
|
||||
for _, r := range v {
|
||||
if s, ok := r.(string); ok {
|
||||
names = append(names, s)
|
||||
}
|
||||
}
|
||||
}
|
||||
return names
|
||||
}
|
||||
|
||||
func paginaAccesible(p *models.DocPagina, userRoles []string) bool {
|
||||
if p.Visibilidad == "public" {
|
||||
return true
|
||||
}
|
||||
for _, pr := range p.Roles {
|
||||
for _, ur := range userRoles {
|
||||
if pr.Name == ur {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
package controllers
|
||||
|
||||
import (
|
||||
"math"
|
||||
"strconv"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"github.com/sujit-baniya/fiber-boilerplate/pkg/models"
|
||||
)
|
||||
|
||||
// SaasIndex renderiza la vista del panel de gestión de productos SaaS.
|
||||
func SaasIndex(c *fiber.Ctx) error {
|
||||
data := fiber.Map{
|
||||
"user": c.Locals("user").(map[string]interface{}),
|
||||
"modules": c.Locals("userModules"),
|
||||
}
|
||||
if err := c.Render("saas", data, "layouts/main"); err != nil {
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"error": err.Error()})
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetSaasProductos devuelve la lista paginada en JSON (para Alpine/HTMX).
|
||||
func GetSaasProductos(c *fiber.Ctx) error {
|
||||
page, _ := strconv.Atoi(c.Query("page", "1"))
|
||||
if page < 1 {
|
||||
page = 1
|
||||
}
|
||||
search := c.Query("search", "")
|
||||
limit := 10
|
||||
offset := (page - 1) * limit
|
||||
|
||||
items, total, err := models.GetAllSaasProductos(limit, offset, search)
|
||||
if err != nil {
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"error": err.Error()})
|
||||
}
|
||||
|
||||
servicios, _ := models.GetAllServiciosSelect()
|
||||
|
||||
return c.JSON(fiber.Map{
|
||||
"items": items,
|
||||
"servicios": servicios,
|
||||
"total": total,
|
||||
"totalPages": int(math.Ceil(float64(total) / float64(limit))),
|
||||
"page": page,
|
||||
"limit": limit,
|
||||
})
|
||||
}
|
||||
|
||||
// CreateSaasProducto crea un nuevo producto SaaS.
|
||||
func CreateSaasProducto(c *fiber.Ctx) error {
|
||||
type Req struct {
|
||||
Nombre string `json:"nombre"`
|
||||
Slug string `json:"slug"`
|
||||
Descripcion string `json:"descripcion"`
|
||||
LogoURL string `json:"logo_url"`
|
||||
ServicioID *uint `json:"servicio_id"`
|
||||
Activo bool `json:"activo"`
|
||||
Orden int `json:"orden"`
|
||||
}
|
||||
var req Req
|
||||
if err := c.BodyParser(&req); err != nil {
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "Datos inválidos"})
|
||||
}
|
||||
if req.Nombre == "" || req.Slug == "" {
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "Nombre y slug son obligatorios"})
|
||||
}
|
||||
item := &models.SaasProducto{
|
||||
Nombre: req.Nombre,
|
||||
Slug: req.Slug,
|
||||
Descripcion: req.Descripcion,
|
||||
LogoURL: req.LogoURL,
|
||||
ServicioID: req.ServicioID,
|
||||
Activo: req.Activo,
|
||||
Orden: req.Orden,
|
||||
}
|
||||
if err := models.CreateSaasProducto(item); err != nil {
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"error": err.Error()})
|
||||
}
|
||||
return c.JSON(fiber.Map{"message": "Producto SaaS creado", "item": item})
|
||||
}
|
||||
|
||||
// UpdateSaasProducto actualiza un producto SaaS existente.
|
||||
func UpdateSaasProducto(c *fiber.Ctx) error {
|
||||
id, err := strconv.ParseUint(c.Params("id"), 10, 32)
|
||||
if err != nil {
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "ID inválido"})
|
||||
}
|
||||
type Req struct {
|
||||
Nombre string `json:"nombre"`
|
||||
Slug string `json:"slug"`
|
||||
Descripcion string `json:"descripcion"`
|
||||
LogoURL string `json:"logo_url"`
|
||||
ServicioID *uint `json:"servicio_id"`
|
||||
Activo bool `json:"activo"`
|
||||
Orden int `json:"orden"`
|
||||
}
|
||||
var req Req
|
||||
if err := c.BodyParser(&req); err != nil {
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "Datos inválidos"})
|
||||
}
|
||||
item := &models.SaasProducto{
|
||||
Nombre: req.Nombre,
|
||||
Slug: req.Slug,
|
||||
Descripcion: req.Descripcion,
|
||||
LogoURL: req.LogoURL,
|
||||
ServicioID: req.ServicioID,
|
||||
Activo: req.Activo,
|
||||
Orden: req.Orden,
|
||||
}
|
||||
item.ID = uint(id)
|
||||
if err := models.UpdateSaasProducto(item); err != nil {
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"error": err.Error()})
|
||||
}
|
||||
return c.JSON(fiber.Map{"message": "Producto SaaS actualizado"})
|
||||
}
|
||||
|
||||
// DeleteSaasProducto elimina un producto SaaS.
|
||||
func DeleteSaasProducto(c *fiber.Ctx) error {
|
||||
id, err := strconv.ParseUint(c.Params("id"), 10, 32)
|
||||
if err != nil {
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "ID inválido"})
|
||||
}
|
||||
if err := models.DeleteSaasProducto(uint(id)); err != nil {
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"error": err.Error()})
|
||||
}
|
||||
return c.JSON(fiber.Map{"message": "Producto SaaS eliminado"})
|
||||
}
|
||||
@@ -25,5 +25,7 @@ func RutasPublicas(web fiber.Router) {
|
||||
web.Get("/pago-exitoso", apiControllers.PagoExitosoPage)
|
||||
// Ruta fuera del prefijo /api para evitar que AuthApi() la intercepte
|
||||
web.Get("/pago/estado", apiControllers.PagoEstadoAPI)
|
||||
}
|
||||
// ─── Documentación pública ────────────────────────────────────────────────
|
||||
web.Get("/docs/:saas", controllers.DocsPublicoIndex)
|
||||
web.Get("/docs/:saas/:slug", controllers.DocsPublicaPagina)}
|
||||
|
||||
|
||||
@@ -144,4 +144,30 @@ func UserRoutes(app fiber.Router) {
|
||||
// Bold API (crear link, consultar estado)
|
||||
protected.Post("/pasarelas/bold/crear-link", apiControllers.BoldCreatePaymentLink)
|
||||
protected.Get("/pasarelas/bold/link/:linkID", apiControllers.BoldGetLinkStatus)
|
||||
|
||||
// ─── Productos SaaS ──────────────────────────────────────────────────────
|
||||
protected.Get("/saas", middlewares.MenuMiddleware, controllers.SaasIndex)
|
||||
protected.Get("/loadsaas", controllers.GetSaasProductos)
|
||||
protected.Post("/saas", controllers.CreateSaasProducto)
|
||||
protected.Put("/saas/:id", controllers.UpdateSaasProducto)
|
||||
protected.Delete("/saas/:id", controllers.DeleteSaasProducto)
|
||||
|
||||
// ─── Documentación: categorías globales ──────────────────────────────────
|
||||
protected.Get("/doc/categorias", middlewares.MenuMiddleware, controllers.DocCategoriasIndex)
|
||||
protected.Get("/doc/loadcategorias", controllers.GetDocCategorias)
|
||||
protected.Post("/doc/categorias", controllers.CreateDocCategoria)
|
||||
protected.Put("/doc/categorias/:id", controllers.UpdateDocCategoria)
|
||||
protected.Delete("/doc/categorias/:id", controllers.DeleteDocCategoria)
|
||||
|
||||
// ─── Documentación: páginas ───────────────────────────────────────────────
|
||||
protected.Get("/doc/paginas", middlewares.MenuMiddleware, controllers.DocPaginasIndex)
|
||||
protected.Get("/doc/loadpaginas", controllers.GetDocPaginas)
|
||||
protected.Get("/doc/paginas/:id", controllers.GetDocPaginaDetalle)
|
||||
protected.Post("/doc/paginas", controllers.CreateDocPagina)
|
||||
protected.Put("/doc/paginas/:id", controllers.UpdateDocPagina)
|
||||
protected.Delete("/doc/paginas/:id", controllers.DeleteDocPagina)
|
||||
|
||||
// ─── Documentación: lectura privada (usuario logueado) ───────────────────
|
||||
protected.Get("/docs/:saas", middlewares.MenuMiddleware, controllers.DocsPrivadoIndex)
|
||||
protected.Get("/docs/:saas/:slug", middlewares.MenuMiddleware, controllers.DocsPrivadaPagina)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user