Просмотр исходного кода

Merge pull request #115 from kaelthasmanu/add_groups

Add groups
Manuel Gorrin 2 месяцев назад
Родитель
Сommit
3d84240239

+ 76 - 0
alembic/versions/013_add_ldap_groups.py

@@ -0,0 +1,76 @@
+"""Add admin-managed LDAP groups and members.
+
+Revision ID: 013_add_ldap_groups
+Revises: 012_add_denied_log_created_at_index
+Create Date: 2026-09-19 00:00:00.000000
+"""
+
+from collections.abc import Sequence
+
+import sqlalchemy as sa
+from sqlalchemy import inspect
+
+from alembic import op
+
+revision: str = "013_add_ldap_groups"
+down_revision: str | None = "012_add_denied_log_created_at_index"
+branch_labels: str | Sequence[str] | None = None
+depends_on: str | Sequence[str] | None = None
+
+
+def upgrade() -> None:
+    inspector = inspect(op.get_bind())
+
+    if not inspector.has_table("ldap_groups"):
+        op.create_table(
+            "ldap_groups",
+            sa.Column("id", sa.Integer(), autoincrement=True, nullable=False),
+            sa.Column("name", sa.String(length=255), nullable=False),
+            sa.Column("description", sa.Text(), nullable=True),
+            sa.Column(
+                "source", sa.String(length=50), nullable=False, server_default="custom"
+            ),
+            sa.Column("created_at", sa.DateTime(), nullable=False),
+            sa.Column("updated_at", sa.DateTime(), nullable=True),
+            sa.PrimaryKeyConstraint("id"),
+            sa.UniqueConstraint("name"),
+        )
+        op.create_index("ix_ldap_groups_name", "ldap_groups", ["name"], unique=False)
+
+    if not inspector.has_table("ldap_group_members"):
+        op.create_table(
+            "ldap_group_members",
+            sa.Column("id", sa.Integer(), autoincrement=True, nullable=False),
+            sa.Column("group_id", sa.Integer(), nullable=False),
+            sa.Column("username", sa.String(length=255), nullable=False),
+            sa.Column(
+                "source", sa.String(length=50), nullable=False, server_default="manual"
+            ),
+            sa.Column("created_at", sa.DateTime(), nullable=False),
+            sa.ForeignKeyConstraint(["group_id"], ["ldap_groups.id"]),
+            sa.PrimaryKeyConstraint("id"),
+            sa.UniqueConstraint("group_id", "username", name="uq_ldap_group_member"),
+        )
+        op.create_index(
+            "ix_ldap_group_members_group_id",
+            "ldap_group_members",
+            ["group_id"],
+            unique=False,
+        )
+        op.create_index(
+            "ix_ldap_group_members_username",
+            "ldap_group_members",
+            ["username"],
+            unique=False,
+        )
+
+
+def downgrade() -> None:
+    inspector = inspect(op.get_bind())
+    if inspector.has_table("ldap_group_members"):
+        op.drop_index("ix_ldap_group_members_username", table_name="ldap_group_members")
+        op.drop_index("ix_ldap_group_members_group_id", table_name="ldap_group_members")
+        op.drop_table("ldap_group_members")
+    if inspector.has_table("ldap_groups"):
+        op.drop_index("ix_ldap_groups_name", table_name="ldap_groups")
+        op.drop_table("ldap_groups")

+ 6 - 0
database/models/__init__.py

@@ -3,6 +3,9 @@ from .models import (
     BackupConfig,
     BackupConfig,
     DailyBase,
     DailyBase,
     DeniedLog,
     DeniedLog,
+    LdapConfig,
+    LdapGroup,
+    LdapGroupMember,
     Log,
     Log,
     LogMetadata,
     LogMetadata,
     Notification,
     Notification,
@@ -25,6 +28,9 @@ __all__ = [
     "Notification",
     "Notification",
     "AdminUser",
     "AdminUser",
     "BackupConfig",
     "BackupConfig",
+    "LdapConfig",
+    "LdapGroup",
+    "LdapGroupMember",
     "SquidConfig",
     "SquidConfig",
     "QuotaUser",
     "QuotaUser",
     "QuotaGroup",
     "QuotaGroup",

+ 30 - 0
database/models/models.py

@@ -4,9 +4,11 @@ from sqlalchemy import (
     BigInteger,
     BigInteger,
     Column,
     Column,
     DateTime,
     DateTime,
+    ForeignKey,
     Integer,
     Integer,
     String,
     String,
     Text,
     Text,
+    UniqueConstraint,
 )
 )
 from sqlalchemy.ext.declarative import declared_attr
 from sqlalchemy.ext.declarative import declared_attr
 from sqlalchemy.orm import declarative_base
 from sqlalchemy.orm import declarative_base
@@ -234,6 +236,34 @@ class LdapConfig(Base):
     updated_at = Column(DateTime, default=datetime.now, onupdate=datetime.now)
     updated_at = Column(DateTime, default=datetime.now, onupdate=datetime.now)
 
 
 
 
+class LdapGroup(Base):
+    """Custom LDAP/AD groups managed by the admin."""
+
+    __tablename__ = "ldap_groups"
+
+    id = Column(Integer, primary_key=True, autoincrement=True)
+    name = Column(String(255), nullable=False, unique=True, index=True)
+    description = Column(Text, nullable=True)
+    source = Column(String(50), nullable=False, default="custom")
+    created_at = Column(DateTime, default=datetime.now, nullable=False)
+    updated_at = Column(DateTime, default=datetime.now, onupdate=datetime.now)
+
+
+class LdapGroupMember(Base):
+    """Users assigned to a managed LDAP/AD group."""
+
+    __tablename__ = "ldap_group_members"
+    __table_args__ = (
+        UniqueConstraint("group_id", "username", name="uq_ldap_group_member"),
+    )
+
+    id = Column(Integer, primary_key=True, autoincrement=True)
+    group_id = Column(Integer, ForeignKey("ldap_groups.id"), nullable=False, index=True)
+    username = Column(String(255), nullable=False, index=True)
+    source = Column(String(50), nullable=False, default="manual")
+    created_at = Column(DateTime, default=datetime.now, nullable=False)
+
+
 class SquidConfig(Base):
 class SquidConfig(Base):
     """Single-row table that stores Squid runtime configuration values."""
     """Single-row table that stores Squid runtime configuration values."""
 
 

+ 43 - 0
routes/admin/ldap_config.py

@@ -44,6 +44,49 @@ def register_routes(bp):
                 {"status": "error", "message": _("Error al guardar la configuración.")}
                 {"status": "error", "message": _("Error al guardar la configuración.")}
             ), 500
             ), 500
 
 
+    @bp.route("/api/ldap/groups", methods=["GET", "POST"])
+    @api_auth_required
+    def ldap_groups_api():
+        if request.method == "GET":
+            return jsonify(ldap_config_service.list_groups())
+
+        data = request.get_json(silent=True) or {}
+        action = (data.get("action") or "").strip().lower()
+
+        try:
+            if action in ("", "list"):
+                return jsonify(ldap_config_service.list_groups())
+            if action in ("create", "save"):
+                return jsonify(ldap_config_service.create_group(data))
+            if action in ("add-member", "add-members"):
+                return jsonify(ldap_config_service.add_members(data))
+            if action == "remove-member":
+                return jsonify(ldap_config_service.remove_member(data))
+            if action == "delete":
+                return jsonify(ldap_config_service.delete_group(data))
+            return jsonify(ldap_config_service.list_groups())
+        except ValueError as exc:
+            logger.warning("LDAP group validation error: {}", exc)
+            return (
+                jsonify(
+                    {
+                        "status": "error",
+                        "message": _("Solicitud inválida para grupos LDAP."),
+                        "groups": [],
+                    }
+                ),
+                400,
+            )
+        except Exception as exc:
+            logger.exception(f"Unexpected LDAP group error: {exc}")
+            return jsonify(
+                {
+                    "status": "error",
+                    "message": _("Error interno en grupos LDAP."),
+                    "groups": [],
+                }
+            ), 500
+
     # ------------------------------------------------------------------
     # ------------------------------------------------------------------
     # Test connection
     # Test connection
     # ------------------------------------------------------------------
     # ------------------------------------------------------------------

+ 51 - 1
routes/logs_routes.py

@@ -1,4 +1,4 @@
-from datetime import datetime
+from datetime import date, datetime, timedelta
 
 
 from flask import Blueprint, jsonify, render_template, request
 from flask import Blueprint, jsonify, render_template, request
 from flask_babel import gettext as _
 from flask_babel import gettext as _
@@ -7,6 +7,7 @@ from loguru import logger
 from database.database import get_session
 from database.database import get_session
 from services.analytics.blacklist_users import find_blacklisted_sites
 from services.analytics.blacklist_users import find_blacklisted_sites
 from services.analytics.fetch_data_logs import get_users_logs
 from services.analytics.fetch_data_logs import get_users_logs
+from services.analytics.ldap_groups_report import get_group_traffic_summary
 
 
 logs_bp = Blueprint("logs", __name__)
 logs_bp = Blueprint("logs", __name__)
 
 
@@ -96,9 +97,56 @@ def enrich_users_with_logs(users):
         user["response_summary"] = build_response_summary(logs)
         user["response_summary"] = build_response_summary(logs)
 
 
 
 
+def _parse_group_report_dates():
+    today = date.today()
+    start_value = request.args.get("start_date") or today.isoformat()
+    end_value = request.args.get("end_date") or start_value
+    try:
+        start_date = datetime.strptime(start_value, "%Y-%m-%d").date()
+        end_date = datetime.strptime(end_value, "%Y-%m-%d").date()
+    except ValueError:
+        return today, today
+    if start_date > end_date:
+        start_date, end_date = end_date, start_date
+    if (end_date - start_date).days > 366:
+        start_date = end_date - timedelta(days=366)
+    return start_date, end_date
+
+
 @logs_bp.route("/logs")
 @logs_bp.route("/logs")
 def logs():
 def logs():
     try:
     try:
+        active_tab = request.args.get("tab", "activity")
+        if active_tab == "groups":
+            start_date, end_date = _parse_group_report_dates()
+            selected_group_id = request.args.get("group_id", type=int)
+            db = get_session()
+            try:
+                group_report = get_group_traffic_summary(
+                    db, start_date, end_date, selected_group_id
+                )
+            finally:
+                db.close()
+            return render_template(
+                "logsView.html",
+                users=[],
+                page_icon="favicon.ico",
+                page_title=_("Actividad usuarios"),
+                icon="fas fa-user-friends",
+                subtitle=_("Analisis de la Actividad de los Usuarios"),
+                selected_date=date.today().isoformat(),
+                search_query="",
+                pagination={
+                    "page": 1,
+                    "per_page": 15,
+                    "total_pages": 1,
+                    "total": 0,
+                    "page_range": [],
+                },
+                active_tab=active_tab,
+                group_report=group_report,
+            )
+
         date_str = request.args.get("date")
         date_str = request.args.get("date")
         page = request.args.get("page", 1, type=int)
         page = request.args.get("page", 1, type=int)
         search = request.args.get("search", "", type=str)
         search = request.args.get("search", "", type=str)
@@ -151,6 +199,8 @@ def logs():
                 "total": users_page.get("total", 0),
                 "total": users_page.get("total", 0),
                 "page_range": list(range(page_start, page_end + 1)),
                 "page_range": list(range(page_start, page_end + 1)),
             },
             },
+            active_tab=active_tab,
+            group_report=None,
         )
         )
     except Exception as e:
     except Exception as e:
         logger.error(f"Error en ruta /logs: {e}")
         logger.error(f"Error en ruta /logs: {e}")

+ 159 - 0
services/analytics/ldap_groups_report.py

@@ -0,0 +1,159 @@
+"""Traffic summaries for admin-managed LDAP groups."""
+
+from __future__ import annotations
+
+from datetime import date, timedelta
+
+from loguru import logger
+from sqlalchemy import func
+from sqlalchemy.orm import Session
+
+from database.database import get_dynamic_models
+from database.models.models import LdapGroup, LdapGroupMember
+
+
+def _date_range(start_date: date, end_date: date):
+    current = start_date
+    while current <= end_date:
+        yield current
+        current += timedelta(days=1)
+
+
+def _empty_result(start_date: date, end_date: date) -> dict:
+    return {
+        "start_date": start_date.isoformat(),
+        "end_date": end_date.isoformat(),
+        "total_requests": 0,
+        "total_bytes": 0,
+        "groups": [],
+        "selected_group": None,
+        "selected_group_users": [],
+    }
+
+
+def get_group_traffic_summary(
+    session: Session,
+    start_date: date,
+    end_date: date,
+    selected_group_id: int | None = None,
+) -> dict:
+    """Aggregate traffic from daily tables and map it to managed LDAP groups."""
+    result = _empty_result(start_date, end_date)
+    if start_date > end_date:
+        return result
+
+    groups = session.query(LdapGroup).order_by(LdapGroup.name.asc()).all()
+    members = session.query(LdapGroupMember).all()
+    group_by_id = {group.id: group for group in groups}
+    username_groups: dict[str, set[int]] = {}
+    for member in members:
+        username_groups.setdefault(member.username, set()).add(member.group_id)
+
+    aggregate: dict[str, dict] = {}
+    for group in groups:
+        aggregate[str(group.id)] = {
+            "id": group.id,
+            "name": group.name,
+            "source": group.source,
+            "total_requests": 0,
+            "total_bytes": 0,
+            "user_count": 0,
+            "users": {},
+        }
+    aggregate["ungrouped"] = {
+        "id": None,
+        "name": "__ungrouped__",
+        "source": "system",
+        "total_requests": 0,
+        "total_bytes": 0,
+        "user_count": 0,
+        "users": {},
+    }
+
+    for current_date in _date_range(start_date, end_date):
+        try:
+            user_model, log_model = get_dynamic_models(current_date.strftime("%Y%m%d"))
+            rows = (
+                session.query(
+                    user_model.username,
+                    func.coalesce(func.sum(log_model.request_count), 0),
+                    func.coalesce(func.sum(log_model.data_transmitted), 0),
+                )
+                .join(log_model, user_model.id == log_model.user_id)
+                .filter(user_model.username != "-")
+                .group_by(user_model.username)
+                .all()
+            )
+        except Exception as exc:
+            logger.debug("Skipping unavailable log table for {}: {}", current_date, exc)
+            continue
+
+        for username, requests, total_bytes in rows:
+            requests = int(requests or 0)
+            total_bytes = int(total_bytes or 0)
+            target_ids = username_groups.get(username) or {None}
+            for group_id in target_ids:
+                key = str(group_id) if group_id is not None else "ungrouped"
+                bucket = aggregate[key]
+                bucket["total_requests"] += requests
+                bucket["total_bytes"] += total_bytes
+                user = bucket["users"].setdefault(
+                    username,
+                    {"username": username, "total_requests": 0, "total_bytes": 0},
+                )
+                user["total_requests"] += requests
+                user["total_bytes"] += total_bytes
+
+    result["total_requests"] = sum(
+        item["total_requests"] for item in aggregate.values()
+    )
+    result["total_bytes"] = sum(item["total_bytes"] for item in aggregate.values())
+
+    group_rows = []
+    for item in aggregate.values():
+        if item["id"] is None and not item["users"]:
+            continue
+        item["user_count"] = len(item["users"])
+        item["users"] = sorted(
+            item["users"].values(),
+            key=lambda user: (-user["total_bytes"], user["username"].lower()),
+        )
+        group_rows.append(item)
+
+    group_rows.sort(key=lambda group: (-group["total_bytes"], group["name"]))
+    for item in group_rows:
+        item["percentage"] = (
+            (item["total_bytes"] * 100 / result["total_bytes"])
+            if result["total_bytes"]
+            else 0
+        )
+    result["groups"] = [
+        {key: value for key, value in item.items() if key != "users"}
+        for item in group_rows
+    ]
+
+    if selected_group_id is not None and selected_group_id in group_by_id:
+        selected = aggregate[str(selected_group_id)]
+        selected["user_count"] = len(selected["users"])
+        selected_users_source = selected["users"]
+        if isinstance(selected_users_source, dict):
+            selected_users_source = selected_users_source.values()
+        selected_users = sorted(
+            selected_users_source,
+            key=lambda user: (-user["total_bytes"], user["username"].lower()),
+        )
+        result["selected_group"] = {
+            "id": selected_group_id,
+            "name": group_by_id[selected_group_id].name,
+            "source": group_by_id[selected_group_id].source,
+            "total_requests": selected["total_requests"],
+            "total_bytes": selected["total_bytes"],
+            "percentage": (
+                selected["total_bytes"] * 100 / result["total_bytes"]
+                if result["total_bytes"]
+                else 0
+            ),
+        }
+        result["selected_group_users"] = selected_users
+
+    return result

+ 218 - 1
services/ldap/ldap_config_service.py

@@ -9,13 +9,15 @@ from __future__ import annotations
 import base64
 import base64
 import hashlib
 import hashlib
 import os
 import os
+import re
 from datetime import datetime
 from datetime import datetime
 
 
 from cryptography.fernet import Fernet, InvalidToken
 from cryptography.fernet import Fernet, InvalidToken
+from flask_babel import gettext as _
 from loguru import logger
 from loguru import logger
 
 
 from database.database import get_session
 from database.database import get_session
-from database.models.models import LdapConfig
+from database.models.models import LdapConfig, LdapGroup, LdapGroupMember
 
 
 
 
 def _default_config() -> dict:
 def _default_config() -> dict:
@@ -136,3 +138,218 @@ def save_config(cfg: dict) -> None:
         raise
         raise
     finally:
     finally:
         session.close()
         session.close()
+
+
+def _normalize_usernames(raw_usernames) -> list[str]:
+    if raw_usernames is None:
+        return []
+    if isinstance(raw_usernames, str):
+        values = [raw_usernames]
+    else:
+        values = list(raw_usernames)
+
+    usernames: list[str] = []
+    for value in values:
+        if value is None:
+            continue
+        for item in re.split(r"[\n,;]+", str(value)):
+            username = item.strip()
+            if username:
+                usernames.append(username)
+    return list(dict.fromkeys(usernames))
+
+
+def _serialize_group(group, session) -> dict:
+    members = (
+        session.query(LdapGroupMember)
+        .filter_by(group_id=group.id)
+        .order_by(LdapGroupMember.username.asc())
+        .all()
+    )
+    return {
+        "id": group.id,
+        "name": group.name,
+        "description": group.description or "",
+        "source": group.source or "custom",
+        "member_count": len(members),
+        "members": [
+            {"id": member.id, "username": member.username, "source": member.source}
+            for member in members
+        ],
+    }
+
+
+def _find_group(session, group_id, group_name):
+    if group_id not in (None, ""):
+        try:
+            group = session.query(LdapGroup).filter_by(id=int(group_id)).first()
+        except (TypeError, ValueError):
+            raise ValueError(_("El identificador del grupo no es válido.")) from None
+        if group is not None:
+            return group
+
+    name = (group_name or "").strip()
+    if name:
+        return session.query(LdapGroup).filter(LdapGroup.name == name).first()
+    return None
+
+
+def list_groups() -> dict:
+    session = get_session()
+    try:
+        groups = session.query(LdapGroup).order_by(LdapGroup.name.asc()).all()
+        return {
+            "status": "success",
+            "groups": [_serialize_group(group, session) for group in groups],
+        }
+    except Exception as exc:
+        logger.error(f"Error listing ldap groups: {exc}")
+        return {
+            "status": "error",
+            "message": _("No se pudieron cargar los grupos."),
+            "groups": [],
+        }
+    finally:
+        session.close()
+
+
+def create_group(data: dict) -> dict:
+    name = (data.get("name") or "").strip()
+    if not name:
+        raise ValueError(_("El nombre del grupo es obligatorio."))
+    if len(name) > 255:
+        raise ValueError(_("El nombre del grupo no puede superar los 255 caracteres."))
+
+    description = (data.get("description") or "").strip()
+    if len(description) > 2000:
+        raise ValueError(_("La descripción no puede superar los 2000 caracteres."))
+    source = (data.get("source") or "custom").strip().lower() or "custom"
+    if source not in {"custom", "ldap"}:
+        raise ValueError(_("El origen del grupo no es válido."))
+    session = get_session()
+    try:
+        group = session.query(LdapGroup).filter(LdapGroup.name == name).first()
+        if group is None:
+            group = LdapGroup(name=name, description=description, source=source)
+            session.add(group)
+        else:
+            group.description = description
+            group.source = source
+            group.updated_at = datetime.now()
+        session.commit()
+        return {
+            "status": "success",
+            "message": _("Grupo guardado."),
+            "group": _serialize_group(group, session),
+        }
+    except Exception as exc:
+        session.rollback()
+        logger.error(f"Error creating ldap group: {exc}")
+        raise ValueError("No se pudo guardar el grupo.") from exc
+    finally:
+        session.close()
+
+
+def add_members(data: dict) -> dict:
+    group_id = data.get("group_id")
+    group_name = (data.get("group_name") or "").strip()
+    usernames = _normalize_usernames(
+        data.get("usernames") or data.get("username") or []
+    )
+    if not usernames:
+        raise ValueError(_("Debe indicar al menos un usuario."))
+    if any(len(username) > 255 for username in usernames):
+        raise ValueError(_("El nombre de usuario no puede superar los 255 caracteres."))
+
+    session = get_session()
+    try:
+        group = _find_group(session, group_id, group_name)
+        if group is None:
+            raise ValueError(_("No se encontró el grupo."))
+
+        for username in usernames:
+            member = (
+                session.query(LdapGroupMember)
+                .filter_by(group_id=group.id, username=username)
+                .first()
+            )
+            if member is None:
+                session.add(
+                    LdapGroupMember(
+                        group_id=group.id,
+                        username=username,
+                        source=data.get("source", "manual") or "manual",
+                    )
+                )
+        session.commit()
+        return {
+            "status": "success",
+            "message": _("Usuarios añadidos."),
+            **list_groups(),
+        }
+    except Exception as exc:
+        session.rollback()
+        logger.error(f"Error adding ldap group members: {exc}")
+        raise ValueError(_("No se pudieron añadir los usuarios al grupo.")) from exc
+    finally:
+        session.close()
+
+
+def remove_member(data: dict) -> dict:
+    group_id = data.get("group_id")
+    group_name = (data.get("group_name") or "").strip()
+    username = (data.get("username") or "").strip()
+    if not username:
+        raise ValueError(_("Debe indicar un usuario."))
+    if len(username) > 255:
+        raise ValueError(_("El nombre de usuario no puede superar los 255 caracteres."))
+
+    session = get_session()
+    try:
+        group = _find_group(session, group_id, group_name)
+        if group is None:
+            raise ValueError(_("No se encontró el grupo."))
+
+        member = (
+            session.query(LdapGroupMember)
+            .filter_by(group_id=group.id, username=username)
+            .first()
+        )
+        if member is not None:
+            session.delete(member)
+            session.commit()
+        return {
+            "status": "success",
+            "message": _("Usuario eliminado."),
+            **list_groups(),
+        }
+    except Exception as exc:
+        session.rollback()
+        logger.error(f"Error removing ldap group member: {exc}")
+        raise ValueError(_("No se pudo quitar al usuario del grupo.")) from exc
+    finally:
+        session.close()
+
+
+def delete_group(data: dict) -> dict:
+    group_id = data.get("group_id")
+    group_name = (data.get("group_name") or "").strip()
+    if group_id in (None, "") and not group_name:
+        raise ValueError(_("Debe indicar el grupo a eliminar."))
+
+    session = get_session()
+    try:
+        group = _find_group(session, group_id, group_name)
+        if group is None:
+            raise ValueError(_("No se encontró el grupo."))
+
+        session.query(LdapGroupMember).filter_by(group_id=group.id).delete()
+        session.delete(group)
+        session.commit()
+        return {"status": "success", "message": _("Grupo eliminado."), **list_groups()}
+    except Exception as exc:
+        session.rollback()
+        logger.error(f"Error deleting ldap group: {exc}")
+        raise ValueError(_("No se pudo eliminar el grupo.")) from exc
+    finally:
+        session.close()

+ 1 - 1
templates/admin/base.html

@@ -132,7 +132,7 @@
                         <i class="fas fa-users mr-3"></i>{{ _("Usuarios") }}
                         <i class="fas fa-users mr-3"></i>{{ _("Usuarios") }}
                     </a>
                     </a>
                     <a href="{{ url_for('admin.ldap_config') }}" class="flex items-center px-4 py-3 text-gray-700 hover:bg-blue-50 hover:text-blue-600 rounded-lg transition-colors" title="{{ _("Configuraciones LDAP/Active Directory") }}">
                     <a href="{{ url_for('admin.ldap_config') }}" class="flex items-center px-4 py-3 text-gray-700 hover:bg-blue-50 hover:text-blue-600 rounded-lg transition-colors" title="{{ _("Configuraciones LDAP/Active Directory") }}">
-                        <i class="fas fa-network-wired mr-3"></i>{{ _("LDAP / Active Directory") }}
+                        <i class="fas fa-network-wired mr-3"></i>{{ _('LDAP/AD y Grupos') }}
                     </a>
                     </a>
                     <a href="{{ url_for('admin.kerberos_config') }}" class="flex items-center justify-between px-4 py-3 text-gray-700 hover:bg-blue-50 hover:text-blue-600 rounded-lg transition-colors" title="{{ _("Autenticación Kerberos / SPNEGO para Squid") }}">
                     <a href="{{ url_for('admin.kerberos_config') }}" class="flex items-center justify-between px-4 py-3 text-gray-700 hover:bg-blue-50 hover:text-blue-600 rounded-lg transition-colors" title="{{ _("Autenticación Kerberos / SPNEGO para Squid") }}">
                         <span class="flex items-center">
                         <span class="flex items-center">

+ 250 - 3
templates/admin/ldap_config.html

@@ -1,17 +1,28 @@
 {% extends 'admin/base.html' %}
 {% extends 'admin/base.html' %}
 
 
-{% block title %}{{ _("LDAP / Active Directory | Admin Squid") }}{% endblock %}
+{% block title %}{{ _("LDAP/AD y Grupos | Admin Squid") }}{% endblock %}
 
 
 {% block content %}
 {% block content %}
 <div class="max-w-7xl mx-auto space-y-6" x-data="ldapApp()" x-init="init()">
 <div class="max-w-7xl mx-auto space-y-6" x-data="ldapApp()" x-init="init()">
+    <div class="bg-white shadow rounded-lg border border-gray-200 p-2">
+        <nav class="flex flex-wrap gap-2" aria-label="{{ _('LDAP tabs') }}">
+            <button type="button" @click="activeTab = 'ldap'" :class="activeTab === 'ldap' ? 'bg-blue-600 text-white shadow' : 'bg-gray-100 text-gray-600 hover:bg-gray-200'" class="px-4 py-2 rounded-lg text-sm font-semibold transition-colors">
+                {{ _("LDAP/AD") }}
+            </button>
+            <button type="button" @click="activeTab = 'groups'" :class="activeTab === 'groups' ? 'bg-indigo-600 text-white shadow' : 'bg-gray-100 text-gray-600 hover:bg-gray-200'" class="px-4 py-2 rounded-lg text-sm font-semibold transition-colors">
+                {{ _("Grupos") }}
+            </button>
+        </nav>
+    </div>
 
 
+    <div x-show="activeTab === 'ldap'" class="space-y-6">
     <!-- ── Header ────────────────────────────────────────────────────── -->
     <!-- ── Header ────────────────────────────────────────────────────── -->
     <div class="bg-white shadow rounded-lg border border-gray-200 p-6">
     <div class="bg-white shadow rounded-lg border border-gray-200 p-6">
         <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
         <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
             <div>
             <div>
                 <h2 class="text-2xl font-bold text-gray-800 flex items-center gap-2">
                 <h2 class="text-2xl font-bold text-gray-800 flex items-center gap-2">
                     <i class="fas fa-network-wired text-blue-600"></i>
                     <i class="fas fa-network-wired text-blue-600"></i>
-                    {{ _("LDAP / Active Directory") }}
+                    {{ _("LDAP/AD") }}
                 </h2>
                 </h2>
                 <p class="text-sm text-gray-500 mt-1">{{ _("Configura la conexión y explora el directorio.") }}</p>
                 <p class="text-sm text-gray-500 mt-1">{{ _("Configura la conexión y explora el directorio.") }}</p>
             </div>
             </div>
@@ -193,7 +204,7 @@
             <!-- Search Groups -->
             <!-- Search Groups -->
             <div class="bg-white shadow rounded-lg border border-gray-200 p-6">
             <div class="bg-white shadow rounded-lg border border-gray-200 p-6">
                 <h3 class="text-lg font-semibold text-gray-800 flex items-center gap-2 mb-4">
                 <h3 class="text-lg font-semibold text-gray-800 flex items-center gap-2 mb-4">
-                    <i class="fas fa-layer-group text-indigo-500"></i> {{ _("Buscar Grupos") }}
+                    <i class="fas fa-layer-group text-indigo-500"></i> {{ _("Buscar Grupos en LDAP/AD") }}
                 </h3>
                 </h3>
                 <div class="flex gap-2 mb-4">
                 <div class="flex gap-2 mb-4">
                     <input x-model="groupQuery" @keydown.enter="searchGroups()" type="text"
                     <input x-model="groupQuery" @keydown.enter="searchGroups()" type="text"
@@ -280,6 +291,104 @@
 
 
         </div>
         </div>
     </div>
     </div>
+    </div>
+
+    <div x-show="activeTab === 'groups'" class="space-y-6">
+        <div class="bg-white shadow rounded-lg border border-gray-200 p-6">
+            <div class="flex items-center justify-between gap-3 mb-4">
+                <h3 class="text-lg font-semibold text-gray-800 flex items-center gap-2">
+                    <i class="fas fa-layer-group text-indigo-500"></i> {{ _("Grupos administrativos") }}
+                </h3>
+                <button @click="loadGroups()" :disabled="loadingGroups" class="text-sm text-indigo-600 hover:text-indigo-800 font-semibold disabled:opacity-50">
+                    <i class="fas fa-sync-alt" :class="loadingGroups ? 'animate-spin' : ''"></i> {{ _("Actualizar") }}
+                </button>
+            </div>
+
+            <div class="grid grid-cols-1 md:grid-cols-3 gap-3 mb-6">
+                <div class="md:col-span-1">
+                    <label class="block text-xs font-medium text-gray-600 mb-1">{{ _("Nombre del grupo") }}</label>
+                    <input x-model="groupForm.name" type="text" placeholder="{{ _('Ej. directivos') }}" class="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500" />
+                </div>
+                <div class="md:col-span-1">
+                    <label class="block text-xs font-medium text-gray-600 mb-1">{{ _("Descripción") }}</label>
+                    <input x-model="groupForm.description" type="text" placeholder="{{ _('Opcional') }}" class="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500" />
+                </div>
+                <div class="md:col-span-1">
+                    <label class="block text-xs font-medium text-gray-600 mb-1">{{ _("Origen") }}</label>
+                    <select x-model="groupForm.source" class="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500">
+                        <option value="custom">{{ _("Personalizado") }}</option>
+                        <!--<option value="ldap">{{ _("LDAP") }}</option>-->
+                    </select>
+                </div>
+            </div>
+
+            <div class="flex justify-end">
+                <button @click="createGroup()" :disabled="creatingGroup" class="bg-indigo-600 hover:bg-indigo-700 disabled:opacity-50 text-white px-4 py-2 rounded-lg text-sm font-semibold transition-colors flex items-center gap-2">
+                    <i class="fas fa-plus"></i>
+                    <span x-text="creatingGroup ? '{{ _('Creando…') }}' : '{{ _('Crear grupo') }}'"></span>
+                </button>
+            </div>
+        </div>
+
+        <div class="bg-white shadow rounded-lg border border-gray-200 p-6">
+            <h3 class="text-lg font-semibold text-gray-800 flex items-center gap-2 mb-4">
+                <i class="fas fa-users text-purple-500"></i> {{ _("Grupos creados") }}
+            </h3>
+
+            <div x-show="groupList.length === 0 && !loadingGroups" class="text-sm text-gray-500 text-center py-6">
+                <i class="fas fa-inbox mr-2"></i>{{ _("Todavía no hay grupos definidos.") }}
+            </div>
+
+            <div x-show="loadingGroups" class="flex items-center justify-center py-8 text-gray-400">
+                <i class="fas fa-circle-notch fa-spin text-2xl mr-3"></i> {{ _("Cargando grupos…") }}
+            </div>
+
+            <div class="space-y-4" x-show="groupList.length > 0 && !loadingGroups">
+                <template x-for="group in groupList" :key="group.id">
+                    <div class="border border-gray-200 rounded-xl p-4 bg-gray-50">
+                        <div class="flex flex-col md:flex-row md:items-start md:justify-between gap-3">
+                            <div>
+                                <div class="flex items-center gap-2 flex-wrap">
+                                    <h4 class="text-lg font-semibold text-gray-800" x-text="group.name"></h4>
+                                    <span class="inline-flex items-center px-2 py-0.5 rounded-full text-[10px] font-semibold uppercase tracking-wide" :class="group.source === 'ldap' ? 'bg-blue-100 text-blue-700' : 'bg-indigo-100 text-indigo-700'" x-text="group.source === 'ldap' ? '{{ _('LDAP') }}' : '{{ _('Personalizado') }}'"></span>
+                                </div>
+                                <p class="text-sm text-gray-600 mt-1" x-text="group.description || '{{ _('Sin descripción') }}'"></p>
+                            </div>
+                            <button @click="deleteGroup(group.id, group.name)" class="text-red-600 hover:text-red-800 text-sm font-semibold transition-colors">
+                                <i class="fas fa-trash-alt mr-1"></i>{{ _("Eliminar") }}
+                            </button>
+                        </div>
+
+                        <div class="mt-4">
+                            <div class="flex flex-col sm:flex-row gap-2">
+                                <input x-model="memberInputs[group.id]" type="text" :placeholder="'{{ _('usuario1, usuario2, ...') }}'" class="flex-1 border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500" />
+                                <button @click="addMembers(group.id, group.name)" class="bg-indigo-600 hover:bg-indigo-700 text-white px-3 py-2 rounded-lg text-sm font-semibold transition-colors">
+                                    <i class="fas fa-user-plus mr-1"></i>{{ _("Añadir usuarios") }}
+                                </button>
+                            </div>
+                        </div>
+
+                        <div class="mt-4" x-show="group.members && group.members.length > 0">
+                            <p class="text-xs text-gray-500 mb-2"><span x-text="group.member_count"></span> {{ _("usuario(s) asociado(s)") }}</p>
+                            <div class="flex flex-wrap gap-2">
+                                <template x-for="member in group.members" :key="member.id">
+                                    <span class="inline-flex items-center gap-2 bg-white border border-gray-200 text-gray-700 text-xs font-medium px-3 py-1.5 rounded-full">
+                                        <span x-text="member.username"></span>
+                                        <button @click="removeMember(group.id, group.name, member.username)" class="text-red-500 hover:text-red-700" title="{{ _('Quitar usuario') }}">
+                                            <i class="fas fa-times"></i>
+                                        </button>
+                                    </span>
+                                </template>
+                            </div>
+                        </div>
+                        <p x-show="group.members && group.members.length === 0" class="text-sm text-gray-500 mt-3">
+                            <i class="fas fa-inbox mr-2"></i>{{ _("Este grupo aún no tiene usuarios asociados.") }}
+                        </p>
+                    </div>
+                </template>
+            </div>
+        </div>
+    </div>
 </div>
 </div>
 
 
 <script type="application/json" id="ldap-config-data">
 <script type="application/json" id="ldap-config-data">
@@ -308,6 +417,15 @@ function ldapApp() {
         connectionStatus: "{{ _('Sin probar') }}",
         connectionStatus: "{{ _('Sin probar') }}",
         clientNotice: "",
         clientNotice: "",
 
 
+        activeTab: "ldap",
+
+        // Group management
+        groupForm: { name: "", description: "", source: "custom" },
+        groupList: [],
+        loadingGroups: false,
+        creatingGroup: false,
+        memberInputs: {},
+
         // Stats
         // Stats
         stats:        { users: null, groups: null },
         stats:        { users: null, groups: null },
         loadingStats: false,
         loadingStats: false,
@@ -342,6 +460,7 @@ function ldapApp() {
                 this.clientNotice = '{{ _('Configuración cargada desde la base de datos.') }}';
                 this.clientNotice = '{{ _('Configuración cargada desde la base de datos.') }}';
             }
             }
             this.$watch('cfg', () => { this.saveLocalConfig(); }, { deep: true });
             this.$watch('cfg', () => { this.saveLocalConfig(); }, { deep: true });
+            this.loadGroups();
         },
         },
 
 
         loadLocalConfig() {
         loadLocalConfig() {
@@ -426,6 +545,134 @@ function ldapApp() {
             }
             }
         },
         },
 
 
+        async loadGroups() {
+            this.loadingGroups = true;
+            try {
+                const res = await fetch('/admin/api/ldap/groups', {
+                    method: 'GET',
+                    headers: { 'X-CSRFToken': this.csrfToken() },
+                });
+                const data = await res.json();
+                if (data.status === 'success') {
+                    this.groupList = data.groups || [];
+                } else {
+                    this.showAlert(data.message || '{{ _('No se pudieron cargar los grupos.') }}', 'error');
+                }
+            } catch (error) {
+                console.error('[LDAP DEBUG] loadGroups error', error);
+                this.showAlert('{{ _('Error al cargar los grupos.') }}', 'error');
+            } finally {
+                this.loadingGroups = false;
+            }
+        },
+
+        async createGroup() {
+            if (!this.groupForm.name.trim()) {
+                this.showAlert('{{ _('El nombre del grupo es obligatorio.') }}', 'error');
+                return;
+            }
+            this.creatingGroup = true;
+            try {
+                const res = await fetch('/admin/api/ldap/groups', {
+                    method: 'POST',
+                    headers: { 'Content-Type': 'application/json', 'X-CSRFToken': this.csrfToken() },
+                    body: JSON.stringify({ action: 'create', ...this.groupForm }),
+                });
+                const data = await res.json();
+                if (data.status === 'success') {
+                    this.groupForm = { name: '', description: '', source: 'custom' };
+                    this.groupList = data.group ? [data.group] : this.groupList;
+                    this.loadGroups();
+                    this.showAlert(data.message, 'success');
+                } else {
+                    this.showAlert(data.message, 'error');
+                }
+            } catch (error) {
+                console.error('[LDAP DEBUG] createGroup error', error);
+                this.showAlert('{{ _('Error al crear el grupo.') }}', 'error');
+            } finally {
+                this.creatingGroup = false;
+            }
+        },
+
+        async addMembers(groupId, groupName) {
+            const raw = this.memberInputs[groupId] || '';
+            const usernames = raw.split(/[\n,;]+/).map(item => item.trim()).filter(Boolean);
+            if (!usernames.length) {
+                this.showAlert('{{ _('Indica al menos un usuario para añadir.') }}', 'error');
+                return;
+            }
+            try {
+                const res = await fetch('/admin/api/ldap/groups', {
+                    method: 'POST',
+                    headers: { 'Content-Type': 'application/json', 'X-CSRFToken': this.csrfToken() },
+                    body: JSON.stringify({ action: 'add-members', group_id: groupId, group_name: groupName, usernames }),
+                });
+                const data = await res.json();
+                if (data.status === 'success') {
+                    this.groupList = data.groups || [];
+                    this.memberInputs[groupId] = '';
+                    this.showAlert(data.message, 'success');
+                } else {
+                    this.showAlert(data.message, 'error');
+                }
+            } catch (error) {
+                console.error('[LDAP DEBUG] addMembers error', error);
+                this.showAlert('{{ _('Error al añadir usuarios al grupo.') }}', 'error');
+            }
+        },
+
+        async removeMember(groupId, groupName, username) {
+            try {
+                const res = await fetch('/admin/api/ldap/groups', {
+                    method: 'POST',
+                    headers: { 'Content-Type': 'application/json', 'X-CSRFToken': this.csrfToken() },
+                    body: JSON.stringify({ action: 'remove-member', group_id: groupId, group_name: groupName, username }),
+                });
+                const data = await res.json();
+                if (data.status === 'success') {
+                    this.groupList = data.groups || [];
+                    this.showAlert(data.message, 'success');
+                } else {
+                    this.showAlert(data.message, 'error');
+                }
+            } catch (error) {
+                console.error('[LDAP DEBUG] removeMember error', error);
+                this.showAlert('{{ _('Error al quitar el usuario del grupo.') }}', 'error');
+            }
+        },
+
+        async deleteGroup(groupId, groupName) {
+            const removeGroup = async () => {
+                try {
+                    const res = await fetch('/admin/api/ldap/groups', {
+                        method: 'POST',
+                        headers: { 'Content-Type': 'application/json', 'X-CSRFToken': this.csrfToken() },
+                        body: JSON.stringify({ action: 'delete', group_id: groupId, group_name: groupName }),
+                    });
+                    const data = await res.json();
+                    if (data.status === 'success') {
+                        this.groupList = data.groups || [];
+                        this.showAlert(data.message, 'success');
+                    } else {
+                        this.showAlert(data.message, 'error');
+                    }
+                } catch (error) {
+                    console.error('[LDAP DEBUG] deleteGroup error', error);
+                    this.showAlert('{{ _('Error al eliminar el grupo.') }}', 'error');
+                }
+            };
+
+            if (typeof showCustomConfirm === 'function') {
+                showCustomConfirm(
+                    {{ _('¿Está seguro de que desea eliminar este grupo y todos sus usuarios asociados?')|tojson }},
+                    removeGroup,
+                );
+            } else {
+                await removeGroup();
+            }
+        },
+
         async testConnection() {
         async testConnection() {
             this.testingConn = true;
             this.testingConn = true;
             this.connectionStatus = "{{ _('Probando…') }}";
             this.connectionStatus = "{{ _('Probando…') }}";

+ 18 - 1
templates/logsView.html

@@ -3,6 +3,7 @@
 {% block styles %}<link rel="stylesheet" href="{{ url_for('static', filename='logs.css') }}"/>{% endblock %}
 {% block styles %}<link rel="stylesheet" href="{{ url_for('static', filename='logs.css') }}"/>{% endblock %}
 
 
 {% block header_actions %}
 {% block header_actions %}
+  {% if active_tab != 'groups' %}
   <form method="get" class="dashboard-header flex justify-between items-center mb-8 flex-wrap gap-4">
   <form method="get" class="dashboard-header flex justify-between items-center mb-8 flex-wrap gap-4">
     <div class="filters-container flex gap-4 items-center w-full max-w-4xl mx-auto">
     <div class="filters-container flex gap-4 items-center w-full max-w-4xl mx-auto">
       <div class="date-filter w-full max-w-sm mx-auto rounded-[0.5rem] shadow-md overflow-hidden relative">
       <div class="date-filter w-full max-w-sm mx-auto rounded-[0.5rem] shadow-md overflow-hidden relative">
@@ -35,10 +36,26 @@
       </div>
       </div>
     </div>
     </div>
   </form>
   </form>
+  {% endif %}
 {% endblock header_actions %}
 {% endblock header_actions %}
 
 
 {% block content %}
 {% block content %}
-    {% include 'partials/logs.html' %}
+    <div class="flex flex-wrap gap-2 mb-6 border-b border-gray-200 pb-3">
+      <a href="{{ url_for('logs.logs', tab='activity', date=selected_date, search=search_query) }}"
+         class="px-4 py-2 rounded-lg text-sm font-semibold transition-colors {% if active_tab != 'groups' %}bg-blue-600 text-white{% else %}bg-gray-100 text-gray-600 hover:bg-gray-200{% endif %}">
+        <i class="fas fa-list mr-2"></i>{{ _('Actividad') }}
+      </a>
+      <a href="{{ url_for('logs.logs', tab='groups') }}"
+         class="px-4 py-2 rounded-lg text-sm font-semibold transition-colors {% if active_tab == 'groups' %}bg-indigo-600 text-white{% else %}bg-gray-100 text-gray-600 hover:bg-gray-200{% endif %}">
+        <i class="fas fa-layer-group mr-2"></i>{{ _('Grupos') }}
+      </a>
+    </div>
+
+    {% if active_tab == 'groups' %}
+      {% include 'partials/logs_groups.html' %}
+    {% else %}
+      {% include 'partials/logs.html' %}
+    {% endif %}
 {% endblock %}
 {% endblock %}
 
 
 {% block scripts %}
 {% block scripts %}

+ 104 - 0
templates/partials/logs_groups.html

@@ -0,0 +1,104 @@
+<div class="space-y-6">
+  <form method="get" class="bg-white rounded-xl shadow-md border border-gray-200 p-4 flex flex-col lg:flex-row lg:items-end gap-4">
+    <input type="hidden" name="tab" value="groups">
+    <div>
+      <label for="groups-start-date" class="block text-xs font-semibold text-gray-600 mb-1">{{ _('Desde') }}</label>
+      <input id="groups-start-date" type="date" name="start_date" value="{{ group_report.start_date }}" class="border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500">
+    </div>
+    <div>
+      <label for="groups-end-date" class="block text-xs font-semibold text-gray-600 mb-1">{{ _('Hasta') }}</label>
+      <input id="groups-end-date" type="date" name="end_date" value="{{ group_report.end_date }}" class="border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500">
+    </div>
+    <div class="flex gap-2">
+      <button type="submit" class="bg-indigo-600 hover:bg-indigo-700 text-white px-4 py-2 rounded-lg text-sm font-semibold transition-colors">
+        <i class="fas fa-filter mr-2"></i>{{ _('Actualizar') }}
+      </button>
+      <a href="{{ url_for('logs.logs', tab='groups') }}" class="bg-gray-100 hover:bg-gray-200 text-gray-700 px-4 py-2 rounded-lg text-sm font-semibold transition-colors">
+        <i class="fas fa-calendar-day mr-2"></i>{{ _('Hoy') }}
+      </a>
+    </div>
+  </form>
+
+  <div class="grid grid-cols-1 sm:grid-cols-3 gap-4">
+    <div class="bg-white rounded-xl shadow-md border border-gray-200 p-5">
+      <p class="text-xs uppercase tracking-wide text-gray-500">{{ _('Periodo') }}</p>
+      <p class="text-lg font-semibold text-gray-800 mt-1">{{ group_report.start_date }} - {{ group_report.end_date }}</p>
+    </div>
+    <div class="bg-white rounded-xl shadow-md border border-gray-200 p-5">
+      <p class="text-xs uppercase tracking-wide text-gray-500">{{ _('Solicitudes') }}</p>
+      <p class="text-2xl font-bold text-blue-600 mt-1">{{ group_report.total_requests }}</p>
+    </div>
+    <div class="bg-white rounded-xl shadow-md border border-gray-200 p-5">
+      <p class="text-xs uppercase tracking-wide text-gray-500">{{ _('Datos consumidos') }}</p>
+      <p class="text-2xl font-bold text-indigo-600 mt-1">{{ group_report.total_bytes|format_bytes }}</p>
+    </div>
+  </div>
+
+  <div class="grid grid-cols-1 xl:grid-cols-5 gap-6">
+    <section class="xl:col-span-3 bg-white rounded-xl shadow-md border border-gray-200 overflow-hidden">
+      <div class="bg-blue-600 text-white px-4 py-3 font-semibold flex items-center gap-2">
+        <i class="fas fa-layer-group"></i>{{ _('Grupos') }}
+      </div>
+      <div class="overflow-x-auto">
+        <table class="min-w-full text-sm">
+          <thead class="bg-gray-50 text-gray-600">
+            <tr>
+              <th class="px-4 py-3 text-left">#</th>
+              <th class="px-4 py-3 text-left">{{ _('Grupo') }}</th>
+              <th class="px-4 py-3 text-right">{{ _('Usuarios') }}</th>
+              <th class="px-4 py-3 text-right">{{ _('Datos') }}</th>
+              <th class="px-4 py-3 text-right">%</th>
+            </tr>
+          </thead>
+          <tbody class="divide-y divide-gray-100">
+            {% for group in group_report.groups %}
+              <tr class="hover:bg-indigo-50 {% if group_report.selected_group and group_report.selected_group.id == group.id %}bg-indigo-50{% endif %}">
+                <td class="px-4 py-3 text-gray-500">{{ loop.index }}</td>
+                <td class="px-4 py-3">
+                  {% if group.id is not none %}
+                    <a href="{{ url_for('logs.logs', tab='groups', start_date=group_report.start_date, end_date=group_report.end_date, group_id=group.id) }}" class="font-semibold text-indigo-700 hover:underline">{{ group.name }}</a>
+                  {% else %}
+                    <span class="font-semibold text-gray-700">{{ _('Sin grupo') }}</span>
+                  {% endif %}
+                </td>
+                <td class="px-4 py-3 text-right">{{ group.user_count }}</td>
+                <td class="px-4 py-3 text-right font-medium">{{ group.total_bytes|format_bytes }}</td>
+                <td class="px-4 py-3 text-right">{{ '%.1f'|format(group.percentage) }}%</td>
+              </tr>
+            {% else %}
+              <tr><td colspan="5" class="px-4 py-8 text-center text-gray-500">{{ _('No hay tráfico para este periodo.') }}</td></tr>
+            {% endfor %}
+          </tbody>
+        </table>
+      </div>
+    </section>
+
+    <section class="xl:col-span-2 bg-white rounded-xl shadow-md border border-gray-200 overflow-hidden">
+      <div class="bg-indigo-600 text-white px-4 py-3 font-semibold flex items-center gap-2">
+        <i class="fas fa-users"></i>
+        {% if group_report.selected_group %}{{ group_report.selected_group.name }}{% else %}{{ _('Usuarios del grupo') }}{% endif %}
+      </div>
+      {% if group_report.selected_group %}
+        <div class="px-4 py-3 border-b border-gray-100 text-sm text-gray-600">
+          {{ group_report.selected_group.total_bytes|format_bytes }} · {{ group_report.selected_group.total_requests }} {{ _('solicitudes') }}
+        </div>
+        <div class="overflow-x-auto">
+          <table class="min-w-full text-sm">
+            <thead class="bg-gray-50 text-gray-600">
+              <tr><th class="px-4 py-3 text-left">{{ _('Usuario') }}</th><th class="px-4 py-3 text-right">{{ _('Solicitudes') }}</th><th class="px-4 py-3 text-right">{{ _('Datos') }}</th></tr>
+            </thead>
+            <tbody class="divide-y divide-gray-100">
+              {% for user in group_report.selected_group_users %}
+                <tr><td class="px-4 py-3 font-medium text-gray-700">{{ user.username }}</td><td class="px-4 py-3 text-right">{{ user.total_requests }}</td><td class="px-4 py-3 text-right">{{ user.total_bytes|format_bytes }}</td></tr>
+              {% else %}
+                <tr><td colspan="3" class="px-4 py-8 text-center text-gray-500">{{ _('No hay usuarios con tráfico.') }}</td></tr>
+              {% endfor %}
+            </tbody>
+          </table>
+        </div>
+      {% else %}
+        <p class="px-4 py-10 text-center text-gray-500">{{ _('Selecciona un grupo para ver sus usuarios.') }}</p>
+      {% endif %}
+    </section>
+  </div>
+</div>

+ 72 - 0
translations/en/sources/03_services.po

@@ -78,6 +78,78 @@ msgstr "Successfully connected to LDAP/AD server."
 msgid "Usuario no encontrado."
 msgid "Usuario no encontrado."
 msgstr "User not found."
 msgstr "User not found."
 
 
+#: services/ldap/ldap_config_service.py
+msgid "El identificador del grupo no es válido."
+msgstr "The group identifier is invalid."
+
+#: services/ldap/ldap_config_service.py
+msgid "No se pudieron cargar los grupos."
+msgstr "Groups could not be loaded."
+
+#: services/ldap/ldap_config_service.py
+msgid "El nombre del grupo es obligatorio."
+msgstr "The group name is required."
+
+#: services/ldap/ldap_config_service.py
+msgid "El nombre del grupo no puede superar los 255 caracteres."
+msgstr "The group name cannot exceed 255 characters."
+
+#: services/ldap/ldap_config_service.py
+msgid "La descripción no puede superar los 2000 caracteres."
+msgstr "The description cannot exceed 2000 characters."
+
+#: services/ldap/ldap_config_service.py
+msgid "El origen del grupo no es válido."
+msgstr "The group source is invalid."
+
+#: services/ldap/ldap_config_service.py
+msgid "Grupo guardado."
+msgstr "Group saved."
+
+#: services/ldap/ldap_config_service.py
+msgid "Debe indicar al menos un usuario."
+msgstr "At least one user is required."
+
+#: services/ldap/ldap_config_service.py
+msgid "El nombre de usuario no puede superar los 255 caracteres."
+msgstr "The username cannot exceed 255 characters."
+
+#: services/ldap/ldap_config_service.py
+msgid "No se encontró el grupo."
+msgstr "Group not found."
+
+#: services/ldap/ldap_config_service.py
+msgid "Usuarios añadidos."
+msgstr "Users added."
+
+#: services/ldap/ldap_config_service.py
+msgid "No se pudieron añadir los usuarios al grupo."
+msgstr "Users could not be added to the group."
+
+#: services/ldap/ldap_config_service.py
+msgid "Debe indicar un usuario."
+msgstr "A user is required."
+
+#: services/ldap/ldap_config_service.py
+msgid "Usuario eliminado."
+msgstr "User removed."
+
+#: services/ldap/ldap_config_service.py
+msgid "No se pudo quitar al usuario del grupo."
+msgstr "The user could not be removed from the group."
+
+#: services/ldap/ldap_config_service.py
+msgid "Debe indicar el grupo a eliminar."
+msgstr "The group to delete is required."
+
+#: services/ldap/ldap_config_service.py
+msgid "Grupo eliminado."
+msgstr "Group deleted."
+
+#: services/ldap/ldap_config_service.py
+msgid "No se pudo eliminar el grupo."
+msgstr "The group could not be deleted."
+
 #: services/notifications/notifications.py:302
 #: services/notifications/notifications.py:302
 msgid "fa-times-circle"
 msgid "fa-times-circle"
 msgstr "fa-times-circle"
 msgstr "fa-times-circle"

+ 124 - 0
translations/en/sources/07_admin_integrations.po

@@ -5,6 +5,74 @@
 msgid "Probando…"
 msgid "Probando…"
 msgstr "Testing..."
 msgstr "Testing..."
 
 
+#: templates/admin/ldap_config.html:8
+msgid "LDAP tabs"
+msgstr "LDAP tabs"
+
+#: templates/admin/base.html:135 templates/admin/ldap_config.html:3
+msgid "LDAP/AD y Grupos"
+msgstr "LDAP/AD and Groups"
+
+#: templates/admin/ldap_config.html:13
+msgid "LDAP/AD"
+msgstr "LDAP/AD"
+
+#: templates/admin/ldap_config.html:302
+msgid "Grupos administrativos"
+msgstr "Administrative groups"
+
+#: templates/admin/ldap_config.html:310
+msgid "Ej. directivos"
+msgstr "E.g. managers"
+
+#: templates/admin/ldap_config.html:313
+msgid "Opcional"
+msgstr "Optional"
+
+#: templates/admin/ldap_config.html:320
+msgid "Personalizado"
+msgstr "Custom"
+
+#: templates/admin/ldap_config.html:326
+msgid "Crear grupo"
+msgstr "Create group"
+
+#: templates/admin/ldap_config.html:339
+msgid "Todavía no hay grupos definidos."
+msgstr "No groups have been defined yet."
+
+#: templates/admin/ldap_config.html:355
+msgid "Sin descripción"
+msgstr "No description"
+
+#: templates/admin/ldap_config.html:364
+msgid "usuario1, usuario2, ..."
+msgstr "user1, user2, ..."
+
+#: templates/admin/ldap_config.html:367
+msgid "Añadir usuarios"
+msgstr "Add users"
+
+#: templates/admin/ldap_config.html:371
+msgid "usuario(s) asociado(s)"
+msgstr "associated user(s)"
+
+#: templates/admin/ldap_config.html:375
+msgid "Quitar usuario"
+msgstr "Remove user"
+
+#: templates/admin/ldap_config.html:385
+msgid "Este grupo aún no tiene usuarios asociados."
+msgstr "This group has no associated users yet."
+
+#: templates/admin/ldap_config.html:591
+msgid "El nombre del grupo es obligatorio."
+msgstr "The group name is required."
+
+#: templates/admin/ldap_config.html:660
+msgid "¿Está seguro de que desea eliminar este grupo y todos sus usuarios asociados?"
+msgstr "Are you sure you want to delete this group and all its associated users?"
+
 #: templates/admin/ldap_config.html:388
 #: templates/admin/ldap_config.html:388
 msgid "Sin probar"
 msgid "Sin probar"
 msgstr "Untested"
 msgstr "Untested"
@@ -289,6 +357,62 @@ msgstr "Network error while saving."
 msgid "Error de red al probar la conexión."
 msgid "Error de red al probar la conexión."
 msgstr "Network error while testing the connection."
 msgstr "Network error while testing the connection."
 
 
+#: templates/logsView.html
+msgid "Actividad"
+msgstr "Activity"
+
+#: templates/logsView.html
+msgid "Grupos"
+msgstr "Groups"
+
+#: templates/partials/logs_groups.html
+msgid "Desde"
+msgstr "From"
+
+#: templates/partials/logs_groups.html
+msgid "Hasta"
+msgstr "To"
+
+#: templates/partials/logs_groups.html
+msgid "Hoy"
+msgstr "Today"
+
+#: templates/partials/logs_groups.html
+msgid "Periodo"
+msgstr "Period"
+
+#: templates/partials/logs_groups.html
+msgid "Datos consumidos"
+msgstr "Data consumed"
+
+#: templates/partials/logs_groups.html
+msgid "Grupo"
+msgstr "Group"
+
+#: templates/partials/logs_groups.html
+msgid "Sin grupo"
+msgstr "No group"
+
+#: templates/partials/logs_groups.html
+msgid "No hay tráfico para este periodo."
+msgstr "There is no traffic for this period."
+
+#: templates/partials/logs_groups.html
+msgid "Usuarios del grupo"
+msgstr "Group users"
+
+#: templates/partials/logs_groups.html
+msgid "solicitudes"
+msgstr "requests"
+
+#: templates/partials/logs_groups.html
+msgid "No hay usuarios con tráfico."
+msgstr "There are no users with traffic."
+
+#: templates/partials/logs_groups.html
+msgid "Selecciona un grupo para ver sus usuarios."
+msgstr "Select a group to view its users."
+
 #: templates/admin/ldap_config.html:481
 #: templates/admin/ldap_config.html:481
 msgid "El campo de búsqueda de usuario no puede estar vacío."
 msgid "El campo de búsqueda de usuario no puede estar vacío."
 msgstr "User search field cannot be empty."
 msgstr "User search field cannot be empty."