Spaces:
Running
Running
deploy from github actions
Browse files- app/main.py +1 -0
- app/models/lyrics.py +2 -0
- app/routers/alabanza.py +49 -22
- app/routers/lyrics.py +11 -3
- app/utils/clones_letras.py +42 -0
- limpiar_copias_huerfanas.py +54 -0
app/main.py
CHANGED
|
@@ -23,6 +23,7 @@ _COLUMNAS_NUEVAS = [
|
|
| 23 |
"ALTER TABLE tasks ADD COLUMN IF NOT EXISTS harmony_updated_at TIMESTAMP",
|
| 24 |
"ALTER TABLE workers ADD COLUMN IF NOT EXISTS version VARCHAR",
|
| 25 |
"ALTER TABLE tasks ADD COLUMN IF NOT EXISTS downbeats TEXT",
|
|
|
|
| 26 |
]
|
| 27 |
try:
|
| 28 |
from sqlalchemy import text as _sql_text
|
|
|
|
| 23 |
"ALTER TABLE tasks ADD COLUMN IF NOT EXISTS harmony_updated_at TIMESTAMP",
|
| 24 |
"ALTER TABLE workers ADD COLUMN IF NOT EXISTS version VARCHAR",
|
| 25 |
"ALTER TABLE tasks ADD COLUMN IF NOT EXISTS downbeats TEXT",
|
| 26 |
+
"ALTER TABLE user_groups ADD COLUMN IF NOT EXISTS perm_editar_pistas BOOLEAN",
|
| 27 |
]
|
| 28 |
try:
|
| 29 |
from sqlalchemy import text as _sql_text
|
app/models/lyrics.py
CHANGED
|
@@ -62,6 +62,8 @@ class UserGroup(Base):
|
|
| 62 |
|
| 63 |
# Permisos granulares
|
| 64 |
perm_compartir_pistas = Column(Boolean, default=True)
|
|
|
|
|
|
|
| 65 |
perm_compartir_letras = Column(Boolean, default=True)
|
| 66 |
perm_crud_repertorios = Column(Boolean, default=False)
|
| 67 |
perm_crud_letras = Column(Boolean, default=True)
|
|
|
|
| 62 |
|
| 63 |
# Permisos granulares
|
| 64 |
perm_compartir_pistas = Column(Boolean, default=True)
|
| 65 |
+
# Editar pistas del grupo. NULL = igual que perm_compartir_pistas (comportamiento anterior)
|
| 66 |
+
perm_editar_pistas = Column(Boolean, nullable=True)
|
| 67 |
perm_compartir_letras = Column(Boolean, default=True)
|
| 68 |
perm_crud_repertorios = Column(Boolean, default=False)
|
| 69 |
perm_crud_letras = Column(Boolean, default=True)
|
app/routers/alabanza.py
CHANGED
|
@@ -38,7 +38,6 @@ def check_group_permission(ug: UserGroup, modulo: str, accion: str, db: Session)
|
|
| 38 |
('pistas', 'view'): 'perm_ver_pistas',
|
| 39 |
('pistas', 'share'): 'perm_compartir_pistas',
|
| 40 |
('pistas', 'create'): 'perm_compartir_pistas',
|
| 41 |
-
('pistas', 'edit'): 'perm_compartir_pistas',
|
| 42 |
('pistas', 'delete'): 'perm_compartir_pistas',
|
| 43 |
('repertorios', 'view'): 'perm_ver_repertorios',
|
| 44 |
('repertorios', 'create'): 'perm_crud_repertorios',
|
|
@@ -48,6 +47,13 @@ def check_group_permission(ug: UserGroup, modulo: str, accion: str, db: Session)
|
|
| 48 |
('miembros', 'edit'): 'perm_gestionar_solicitudes',
|
| 49 |
('miembros', 'delete'): 'perm_gestionar_solicitudes',
|
| 50 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
mapped_key = key_map.get((modulo, accion))
|
| 52 |
if mapped_key and mapped_key in perms:
|
| 53 |
return bool(perms[mapped_key])
|
|
@@ -69,7 +75,11 @@ def check_group_permission(ug: UserGroup, modulo: str, accion: str, db: Session)
|
|
| 69 |
if accion == 'share': return bool(ug.perm_compartir_letras)
|
| 70 |
elif modulo == 'pistas':
|
| 71 |
if accion == 'view': return bool(ug.perm_ver_pistas)
|
| 72 |
-
if accion
|
|
|
|
|
|
|
|
|
|
|
|
|
| 73 |
elif modulo == 'repertorios':
|
| 74 |
if accion == 'view': return bool(ug.perm_ver_repertorios)
|
| 75 |
if accion in ['create', 'edit', 'delete']: return bool(ug.perm_crud_repertorios)
|
|
@@ -544,14 +554,17 @@ def revoke_user_group_intellectual_property(user_id: int, grupo_id: int, db: Ses
|
|
| 544 |
from datetime import datetime, timedelta
|
| 545 |
|
| 546 |
# 1. Remover letras compartidas con este grupo
|
| 547 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 548 |
group_to_remove = db.query(Group).filter(Group.id == grupo_id).first()
|
| 549 |
-
|
| 550 |
-
|
| 551 |
-
|
| 552 |
-
|
| 553 |
-
|
| 554 |
-
l.group_id = l.groups_shared[0].id if l.groups_shared else None
|
| 555 |
|
| 556 |
# 2. Eliminar referencias en los repertorios de este grupo para las letras de este usuario
|
| 557 |
kicked_lyric_ids = [l.id for l in db.query(Lyric.id).filter(Lyric.created_by == user_id).all()]
|
|
@@ -562,20 +575,26 @@ def revoke_user_group_intellectual_property(user_id: int, grupo_id: int, db: Ses
|
|
| 562 |
RepertorioLyric.lyric_id.in_(kicked_lyric_ids)
|
| 563 |
).delete(synchronize_session=False)
|
| 564 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 565 |
# 3. Remover pistas / stems compartidos con este grupo
|
| 566 |
-
kicked_tasks = db.query(Task).filter(
|
| 567 |
-
|
| 568 |
-
|
| 569 |
-
|
| 570 |
-
|
| 571 |
-
|
| 572 |
-
|
| 573 |
-
|
| 574 |
-
|
| 575 |
-
|
| 576 |
-
|
| 577 |
-
|
| 578 |
-
|
|
|
|
|
|
|
| 579 |
|
| 580 |
|
| 581 |
@router.delete("/grupos/{grupo_id}/miembros/{miembro_id}")
|
|
@@ -757,6 +776,7 @@ def cambiar_rol_miembro(grupo_id: int, miembro_id: int, data: CambiarRolRequest,
|
|
| 757 |
perms_dict = json.loads(custom_rol.permisos) if isinstance(custom_rol.permisos, str) else custom_rol.permisos
|
| 758 |
if isinstance(perms_dict, dict):
|
| 759 |
target_ug.perm_compartir_pistas = bool(perms_dict.get("perm_compartir_pistas", False))
|
|
|
|
| 760 |
target_ug.perm_compartir_letras = bool(perms_dict.get("perm_compartir_letras", False))
|
| 761 |
target_ug.perm_crud_repertorios = bool(perms_dict.get("perm_crud_repertorios", False))
|
| 762 |
target_ug.perm_crud_letras = bool(perms_dict.get("perm_crud_letras", False))
|
|
@@ -776,6 +796,7 @@ def cambiar_rol_miembro(grupo_id: int, miembro_id: int, data: CambiarRolRequest,
|
|
| 776 |
|
| 777 |
if data.role == "admin":
|
| 778 |
target_ug.perm_compartir_pistas = True
|
|
|
|
| 779 |
target_ug.perm_compartir_letras = True
|
| 780 |
target_ug.perm_crud_repertorios = True
|
| 781 |
target_ug.perm_crud_letras = True
|
|
@@ -785,6 +806,7 @@ def cambiar_rol_miembro(grupo_id: int, miembro_id: int, data: CambiarRolRequest,
|
|
| 785 |
target_ug.perm_gestionar_solicitudes = True
|
| 786 |
elif data.role == "member":
|
| 787 |
target_ug.perm_compartir_pistas = True
|
|
|
|
| 788 |
target_ug.perm_compartir_letras = True
|
| 789 |
target_ug.perm_crud_repertorios = False
|
| 790 |
target_ug.perm_crud_letras = True
|
|
@@ -935,6 +957,8 @@ def get_grupo_repertorios(grupo_id: int, db: Session = Depends(get_db), current_
|
|
| 935 |
|
| 936 |
class EditarMiembroPermisosRequest(BaseModel):
|
| 937 |
perm_compartir_pistas: bool
|
|
|
|
|
|
|
| 938 |
perm_compartir_letras: bool
|
| 939 |
perm_crud_repertorios: bool
|
| 940 |
perm_crud_letras: bool
|
|
@@ -1038,6 +1062,7 @@ def get_miembro_permisos(grupo_id: int, miembro_id: int, db: Session = Depends(g
|
|
| 1038 |
|
| 1039 |
return {
|
| 1040 |
"perm_compartir_pistas": target_ug.perm_compartir_pistas,
|
|
|
|
| 1041 |
"perm_compartir_letras": target_ug.perm_compartir_letras,
|
| 1042 |
"perm_crud_repertorios": target_ug.perm_crud_repertorios,
|
| 1043 |
"perm_crud_letras": target_ug.perm_crud_letras,
|
|
@@ -1059,6 +1084,8 @@ def update_miembro_permisos(grupo_id: int, miembro_id: int, data: EditarMiembroP
|
|
| 1059 |
raise HTTPException(status_code=404, detail="Miembro no encontrado en el grupo")
|
| 1060 |
|
| 1061 |
target_ug.perm_compartir_pistas = data.perm_compartir_pistas
|
|
|
|
|
|
|
| 1062 |
target_ug.perm_compartir_letras = data.perm_compartir_letras
|
| 1063 |
target_ug.perm_crud_repertorios = data.perm_crud_repertorios
|
| 1064 |
target_ug.perm_crud_letras = data.perm_crud_letras
|
|
|
|
| 38 |
('pistas', 'view'): 'perm_ver_pistas',
|
| 39 |
('pistas', 'share'): 'perm_compartir_pistas',
|
| 40 |
('pistas', 'create'): 'perm_compartir_pistas',
|
|
|
|
| 41 |
('pistas', 'delete'): 'perm_compartir_pistas',
|
| 42 |
('repertorios', 'view'): 'perm_ver_repertorios',
|
| 43 |
('repertorios', 'create'): 'perm_crud_repertorios',
|
|
|
|
| 47 |
('miembros', 'edit'): 'perm_gestionar_solicitudes',
|
| 48 |
('miembros', 'delete'): 'perm_gestionar_solicitudes',
|
| 49 |
}
|
| 50 |
+
# Formato antiguo de rol: editar pistas usa su propio permiso si existe,
|
| 51 |
+
# si no, el de compartir (comportamiento anterior)
|
| 52 |
+
if (modulo, accion) == ('pistas', 'edit'):
|
| 53 |
+
if 'perm_editar_pistas' in perms:
|
| 54 |
+
return bool(perms['perm_editar_pistas'])
|
| 55 |
+
if 'perm_compartir_pistas' in perms:
|
| 56 |
+
return bool(perms['perm_compartir_pistas'])
|
| 57 |
mapped_key = key_map.get((modulo, accion))
|
| 58 |
if mapped_key and mapped_key in perms:
|
| 59 |
return bool(perms[mapped_key])
|
|
|
|
| 75 |
if accion == 'share': return bool(ug.perm_compartir_letras)
|
| 76 |
elif modulo == 'pistas':
|
| 77 |
if accion == 'view': return bool(ug.perm_ver_pistas)
|
| 78 |
+
if accion == 'edit':
|
| 79 |
+
if ug.perm_editar_pistas is not None:
|
| 80 |
+
return bool(ug.perm_editar_pistas)
|
| 81 |
+
return bool(ug.perm_compartir_pistas)
|
| 82 |
+
if accion in ['share', 'create', 'delete']: return bool(ug.perm_compartir_pistas)
|
| 83 |
elif modulo == 'repertorios':
|
| 84 |
if accion == 'view': return bool(ug.perm_ver_repertorios)
|
| 85 |
if accion in ['create', 'edit', 'delete']: return bool(ug.perm_crud_repertorios)
|
|
|
|
| 554 |
from datetime import datetime, timedelta
|
| 555 |
|
| 556 |
# 1. Remover letras compartidas con este grupo
|
| 557 |
+
# (incluye registros antiguos que solo tienen group_id, sin fila en lyric_groups)
|
| 558 |
+
kicked_lyrics = db.query(Lyric).filter(
|
| 559 |
+
Lyric.created_by == user_id,
|
| 560 |
+
Lyric.groups_shared.any(Group.id == grupo_id) | (Lyric.group_id == grupo_id)
|
| 561 |
+
).all()
|
| 562 |
group_to_remove = db.query(Group).filter(Group.id == grupo_id).first()
|
| 563 |
+
for l in kicked_lyrics:
|
| 564 |
+
if group_to_remove and group_to_remove in l.groups_shared:
|
| 565 |
+
l.groups_shared.remove(group_to_remove)
|
| 566 |
+
if l.group_id == grupo_id:
|
| 567 |
+
l.group_id = l.groups_shared[0].id if l.groups_shared else None
|
|
|
|
| 568 |
|
| 569 |
# 2. Eliminar referencias en los repertorios de este grupo para las letras de este usuario
|
| 570 |
kicked_lyric_ids = [l.id for l in db.query(Lyric.id).filter(Lyric.created_by == user_id).all()]
|
|
|
|
| 575 |
RepertorioLyric.lyric_id.in_(kicked_lyric_ids)
|
| 576 |
).delete(synchronize_session=False)
|
| 577 |
|
| 578 |
+
# Las copias de sus letras que eran de este grupo ya no se usan: se eliminan
|
| 579 |
+
from app.utils.clones_letras import borrar_copias_huerfanas
|
| 580 |
+
borrar_copias_huerfanas(db, [l.id for l in kicked_lyrics])
|
| 581 |
+
|
| 582 |
# 3. Remover pistas / stems compartidos con este grupo
|
| 583 |
+
kicked_tasks = db.query(Task).filter(
|
| 584 |
+
Task.user_id == user_id,
|
| 585 |
+
Task.groups_shared.any(Group.id == grupo_id) | (Task.group_id == grupo_id)
|
| 586 |
+
).all()
|
| 587 |
+
for t in kicked_tasks:
|
| 588 |
+
if group_to_remove and group_to_remove in t.groups_shared:
|
| 589 |
+
t.groups_shared.remove(group_to_remove)
|
| 590 |
+
if t.group_id == grupo_id:
|
| 591 |
+
t.group_id = t.groups_shared[0].id if t.groups_shared else None
|
| 592 |
+
# Si no quedan grupos compartidos y es usuario normal, vuelve a expirar
|
| 593 |
+
if not t.groups_shared:
|
| 594 |
+
if is_premium:
|
| 595 |
+
t.cloud_expires_at = None
|
| 596 |
+
else:
|
| 597 |
+
t.cloud_expires_at = datetime.utcnow() + timedelta(days=30)
|
| 598 |
|
| 599 |
|
| 600 |
@router.delete("/grupos/{grupo_id}/miembros/{miembro_id}")
|
|
|
|
| 776 |
perms_dict = json.loads(custom_rol.permisos) if isinstance(custom_rol.permisos, str) else custom_rol.permisos
|
| 777 |
if isinstance(perms_dict, dict):
|
| 778 |
target_ug.perm_compartir_pistas = bool(perms_dict.get("perm_compartir_pistas", False))
|
| 779 |
+
target_ug.perm_editar_pistas = bool(perms_dict["perm_editar_pistas"]) if "perm_editar_pistas" in perms_dict else None
|
| 780 |
target_ug.perm_compartir_letras = bool(perms_dict.get("perm_compartir_letras", False))
|
| 781 |
target_ug.perm_crud_repertorios = bool(perms_dict.get("perm_crud_repertorios", False))
|
| 782 |
target_ug.perm_crud_letras = bool(perms_dict.get("perm_crud_letras", False))
|
|
|
|
| 796 |
|
| 797 |
if data.role == "admin":
|
| 798 |
target_ug.perm_compartir_pistas = True
|
| 799 |
+
target_ug.perm_editar_pistas = True
|
| 800 |
target_ug.perm_compartir_letras = True
|
| 801 |
target_ug.perm_crud_repertorios = True
|
| 802 |
target_ug.perm_crud_letras = True
|
|
|
|
| 806 |
target_ug.perm_gestionar_solicitudes = True
|
| 807 |
elif data.role == "member":
|
| 808 |
target_ug.perm_compartir_pistas = True
|
| 809 |
+
target_ug.perm_editar_pistas = None
|
| 810 |
target_ug.perm_compartir_letras = True
|
| 811 |
target_ug.perm_crud_repertorios = False
|
| 812 |
target_ug.perm_crud_letras = True
|
|
|
|
| 957 |
|
| 958 |
class EditarMiembroPermisosRequest(BaseModel):
|
| 959 |
perm_compartir_pistas: bool
|
| 960 |
+
# Opcional: las apps viejas no lo mandan y entonces no se cambia
|
| 961 |
+
perm_editar_pistas: Optional[bool] = None
|
| 962 |
perm_compartir_letras: bool
|
| 963 |
perm_crud_repertorios: bool
|
| 964 |
perm_crud_letras: bool
|
|
|
|
| 1062 |
|
| 1063 |
return {
|
| 1064 |
"perm_compartir_pistas": target_ug.perm_compartir_pistas,
|
| 1065 |
+
"perm_editar_pistas": target_ug.perm_editar_pistas if target_ug.perm_editar_pistas is not None else target_ug.perm_compartir_pistas,
|
| 1066 |
"perm_compartir_letras": target_ug.perm_compartir_letras,
|
| 1067 |
"perm_crud_repertorios": target_ug.perm_crud_repertorios,
|
| 1068 |
"perm_crud_letras": target_ug.perm_crud_letras,
|
|
|
|
| 1084 |
raise HTTPException(status_code=404, detail="Miembro no encontrado en el grupo")
|
| 1085 |
|
| 1086 |
target_ug.perm_compartir_pistas = data.perm_compartir_pistas
|
| 1087 |
+
if data.perm_editar_pistas is not None:
|
| 1088 |
+
target_ug.perm_editar_pistas = data.perm_editar_pistas
|
| 1089 |
target_ug.perm_compartir_letras = data.perm_compartir_letras
|
| 1090 |
target_ug.perm_crud_repertorios = data.perm_crud_repertorios
|
| 1091 |
target_ug.perm_crud_letras = data.perm_crud_letras
|
app/routers/lyrics.py
CHANGED
|
@@ -7,6 +7,7 @@ from app.models.user import User
|
|
| 7 |
from app.schemas.lyrics import LyricCreate, LyricOut, GroupCreate, GroupOut, InvitationCreate, InvitationOut, RepertorioCreate, RepertorioOut
|
| 8 |
from app.routers.auth import get_current_user
|
| 9 |
from app.utils.credits import deduct_credits
|
|
|
|
| 10 |
import uuid
|
| 11 |
from datetime import datetime
|
| 12 |
|
|
@@ -557,7 +558,7 @@ def update_repertoire(id: int, rep: RepertorioCreate, db: Session = Depends(get_
|
|
| 557 |
|
| 558 |
# Si cambia de grupo, las letras existentes también deben poder ir al grupo nuevo
|
| 559 |
mismo_grupo = rep.group_id == db_rep.group_id
|
| 560 |
-
ya_presentes = [
|
| 561 |
_validar_letras_para_repertorio(db, current_user, rep.lyrics_ids, rep.group_id, ya_presentes)
|
| 562 |
|
| 563 |
db_rep.name = rep.name
|
|
@@ -569,6 +570,7 @@ def update_repertoire(id: int, rep: RepertorioCreate, db: Session = Depends(get_
|
|
| 569 |
|
| 570 |
# Actualizar letras
|
| 571 |
# Eliminar las actuales
|
|
|
|
| 572 |
db.query(RepertorioLyric).filter(RepertorioLyric.repertorio_id == id).delete()
|
| 573 |
|
| 574 |
# Agregar las nuevas
|
|
@@ -576,7 +578,9 @@ def update_repertoire(id: int, rep: RepertorioCreate, db: Session = Depends(get_
|
|
| 576 |
for idx, lyric_id in enumerate(rep.lyrics_ids):
|
| 577 |
db_rep_lyric = RepertorioLyric(repertorio_id=id, lyric_id=lyric_id, order=idx)
|
| 578 |
db.add(db_rep_lyric)
|
| 579 |
-
|
|
|
|
|
|
|
| 580 |
db.commit()
|
| 581 |
db.refresh(db_rep)
|
| 582 |
if db_rep.group_id is not None:
|
|
@@ -609,8 +613,10 @@ def delete_repertoire(id: int, db: Session = Depends(get_db), current_user: User
|
|
| 609 |
raise HTTPException(status_code=403, detail="No tienes permisos para eliminar este repertorio")
|
| 610 |
|
| 611 |
group_id = db_rep.group_id
|
|
|
|
| 612 |
db.query(RepertorioLyric).filter(RepertorioLyric.repertorio_id == id).delete()
|
| 613 |
db.delete(db_rep)
|
|
|
|
| 614 |
db.commit()
|
| 615 |
if group_id is not None:
|
| 616 |
try:
|
|
@@ -642,7 +648,7 @@ def add_lyric_to_repertoire(id: int, lyric_id: int, db: Session = Depends(get_db
|
|
| 642 |
raise HTTPException(status_code=403, detail="No tienes permisos para modificar este repertorio")
|
| 643 |
|
| 644 |
_validar_letras_para_repertorio(db, current_user, [lyric_id], db_rep.group_id,
|
| 645 |
-
[
|
| 646 |
|
| 647 |
exists = db.query(RepertorioLyric).filter_by(repertorio_id=id, lyric_id=lyric_id).first()
|
| 648 |
if exists:
|
|
@@ -864,6 +870,8 @@ def share_lyric(
|
|
| 864 |
RepertorioLyric.repertorio_id.in_(group_rep_ids),
|
| 865 |
RepertorioLyric.lyric_id == lyric_id
|
| 866 |
).delete(synchronize_session=False)
|
|
|
|
|
|
|
| 867 |
|
| 868 |
db.commit()
|
| 869 |
try:
|
|
|
|
| 7 |
from app.schemas.lyrics import LyricCreate, LyricOut, GroupCreate, GroupOut, InvitationCreate, InvitationOut, RepertorioCreate, RepertorioOut
|
| 8 |
from app.routers.auth import get_current_user
|
| 9 |
from app.utils.credits import deduct_credits
|
| 10 |
+
from app.utils.clones_letras import borrar_copias_huerfanas
|
| 11 |
import uuid
|
| 12 |
from datetime import datetime
|
| 13 |
|
|
|
|
| 558 |
|
| 559 |
# Si cambia de grupo, las letras existentes también deben poder ir al grupo nuevo
|
| 560 |
mismo_grupo = rep.group_id == db_rep.group_id
|
| 561 |
+
ya_presentes = [r[0] for r in db.query(RepertorioLyric.lyric_id).filter(RepertorioLyric.repertorio_id == db_rep.id).all()] if mismo_grupo else []
|
| 562 |
_validar_letras_para_repertorio(db, current_user, rep.lyrics_ids, rep.group_id, ya_presentes)
|
| 563 |
|
| 564 |
db_rep.name = rep.name
|
|
|
|
| 570 |
|
| 571 |
# Actualizar letras
|
| 572 |
# Eliminar las actuales
|
| 573 |
+
ids_anteriores = [rl.lyric_id for rl in db.query(RepertorioLyric).filter(RepertorioLyric.repertorio_id == id).all()]
|
| 574 |
db.query(RepertorioLyric).filter(RepertorioLyric.repertorio_id == id).delete()
|
| 575 |
|
| 576 |
# Agregar las nuevas
|
|
|
|
| 578 |
for idx, lyric_id in enumerate(rep.lyrics_ids):
|
| 579 |
db_rep_lyric = RepertorioLyric(repertorio_id=id, lyric_id=lyric_id, order=idx)
|
| 580 |
db.add(db_rep_lyric)
|
| 581 |
+
|
| 582 |
+
# Las copias que salieron del repertorio y ya no se usan en ningún lado se eliminan
|
| 583 |
+
borrar_copias_huerfanas(db, set(ids_anteriores) - set(rep.lyrics_ids or []))
|
| 584 |
db.commit()
|
| 585 |
db.refresh(db_rep)
|
| 586 |
if db_rep.group_id is not None:
|
|
|
|
| 613 |
raise HTTPException(status_code=403, detail="No tienes permisos para eliminar este repertorio")
|
| 614 |
|
| 615 |
group_id = db_rep.group_id
|
| 616 |
+
ids_letras = [r[0] for r in db.query(RepertorioLyric.lyric_id).filter(RepertorioLyric.repertorio_id == id).all()]
|
| 617 |
db.query(RepertorioLyric).filter(RepertorioLyric.repertorio_id == id).delete()
|
| 618 |
db.delete(db_rep)
|
| 619 |
+
borrar_copias_huerfanas(db, ids_letras)
|
| 620 |
db.commit()
|
| 621 |
if group_id is not None:
|
| 622 |
try:
|
|
|
|
| 648 |
raise HTTPException(status_code=403, detail="No tienes permisos para modificar este repertorio")
|
| 649 |
|
| 650 |
_validar_letras_para_repertorio(db, current_user, [lyric_id], db_rep.group_id,
|
| 651 |
+
[r[0] for r in db.query(RepertorioLyric.lyric_id).filter(RepertorioLyric.repertorio_id == db_rep.id).all()])
|
| 652 |
|
| 653 |
exists = db.query(RepertorioLyric).filter_by(repertorio_id=id, lyric_id=lyric_id).first()
|
| 654 |
if exists:
|
|
|
|
| 870 |
RepertorioLyric.repertorio_id.in_(group_rep_ids),
|
| 871 |
RepertorioLyric.lyric_id == lyric_id
|
| 872 |
).delete(synchronize_session=False)
|
| 873 |
+
# Si era una copia hecha para ese grupo y ya no se usa en ningún lado, se elimina
|
| 874 |
+
borrar_copias_huerfanas(db, [lyric_id])
|
| 875 |
|
| 876 |
db.commit()
|
| 877 |
try:
|
app/utils/clones_letras.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Limpieza de copias (clones) de letras que quedaron sin uso.
|
| 3 |
+
|
| 4 |
+
Al editar una letra ajena dentro de un grupo o repertorio se crea una copia editada
|
| 5 |
+
(parent_lyric_id = original o is_repertoire_only = True). Si esa copia deja de estar en
|
| 6 |
+
cualquier grupo y en cualquier repertorio, nadie la ve: se elimina (decisión del usuario,
|
| 7 |
+
2026-11-02). Las letras originales nunca se borran aquí.
|
| 8 |
+
"""
|
| 9 |
+
from sqlalchemy.orm import Session
|
| 10 |
+
|
| 11 |
+
from app.models.lyrics import Lyric, RepertorioLyric
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def es_copia(letra: Lyric) -> bool:
|
| 15 |
+
return letra.parent_lyric_id is not None or bool(letra.is_repertoire_only)
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def borrar_copias_huerfanas(db: Session, lyric_ids) -> int:
|
| 19 |
+
"""
|
| 20 |
+
Elimina las copias de la lista que ya no están compartidas con ningún grupo ni en
|
| 21 |
+
ningún repertorio. Hace flush, no commit (lo hace quien llama). Devuelve cuántas borró.
|
| 22 |
+
"""
|
| 23 |
+
ids = {int(i) for i in (lyric_ids or []) if i is not None}
|
| 24 |
+
if not ids:
|
| 25 |
+
return 0
|
| 26 |
+
db.flush()
|
| 27 |
+
borradas = 0
|
| 28 |
+
for letra in db.query(Lyric).filter(Lyric.id.in_(ids)).all():
|
| 29 |
+
if not es_copia(letra):
|
| 30 |
+
continue
|
| 31 |
+
if letra.groups_shared or letra.group_id is not None:
|
| 32 |
+
continue
|
| 33 |
+
en_repertorio = db.query(RepertorioLyric.repertorio_id).filter(RepertorioLyric.lyric_id == letra.id).first()
|
| 34 |
+
if en_repertorio:
|
| 35 |
+
continue
|
| 36 |
+
# Las copias de esta copia pasan a ser independientes (igual que al borrar una letra)
|
| 37 |
+
db.query(Lyric).filter(Lyric.parent_lyric_id == letra.id).update({"parent_lyric_id": None})
|
| 38 |
+
db.delete(letra)
|
| 39 |
+
borradas += 1
|
| 40 |
+
if borradas:
|
| 41 |
+
db.flush()
|
| 42 |
+
return borradas
|
limpiar_copias_huerfanas.py
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Elimina las copias de letras (clones de grupo o de repertorio) que ya no están en ningún
|
| 3 |
+
grupo ni en ningún repertorio. Usa la misma regla que la API (app/utils/clones_letras.py):
|
| 4 |
+
las letras originales nunca se borran.
|
| 5 |
+
|
| 6 |
+
Uso:
|
| 7 |
+
python limpiar_copias_huerfanas.py # solo muestra lo que borraría
|
| 8 |
+
python limpiar_copias_huerfanas.py --aplicar # las borra
|
| 9 |
+
"""
|
| 10 |
+
import os
|
| 11 |
+
import sys
|
| 12 |
+
|
| 13 |
+
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
|
| 14 |
+
|
| 15 |
+
from sqlalchemy import or_ # noqa: E402
|
| 16 |
+
|
| 17 |
+
from app.database import SessionLocal # noqa: E402
|
| 18 |
+
from app.models.lyrics import Lyric # noqa: E402
|
| 19 |
+
import app.models.user # noqa: E402,F401
|
| 20 |
+
import app.models.process # noqa: E402,F401
|
| 21 |
+
from app.utils.clones_letras import borrar_copias_huerfanas # noqa: E402
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def main():
|
| 25 |
+
aplicar = "--aplicar" in sys.argv
|
| 26 |
+
db = SessionLocal()
|
| 27 |
+
try:
|
| 28 |
+
copias = db.query(Lyric).filter(
|
| 29 |
+
or_(Lyric.parent_lyric_id.isnot(None), Lyric.is_repertoire_only == True) # noqa: E712
|
| 30 |
+
).all()
|
| 31 |
+
ids = [c.id for c in copias]
|
| 32 |
+
print(f"Copias de letras en la BD: {len(ids)}")
|
| 33 |
+
|
| 34 |
+
# Simula dentro de una transacción y la deshace si no se pidió --aplicar
|
| 35 |
+
nombres = {c.id: f"{c.id} '{c.title}' (dueño {c.created_by})" for c in copias}
|
| 36 |
+
antes = set(ids)
|
| 37 |
+
borradas = borrar_copias_huerfanas(db, ids)
|
| 38 |
+
quedan = {r[0] for r in db.query(Lyric.id).filter(Lyric.id.in_(antes)).all()} if antes else set()
|
| 39 |
+
for i in sorted(antes - quedan):
|
| 40 |
+
print(" huérfana:", nombres[i])
|
| 41 |
+
print(f"Huérfanas: {borradas}")
|
| 42 |
+
|
| 43 |
+
if aplicar:
|
| 44 |
+
db.commit()
|
| 45 |
+
print("Borradas.")
|
| 46 |
+
else:
|
| 47 |
+
db.rollback()
|
| 48 |
+
print("Sin cambios (usa --aplicar para borrarlas).")
|
| 49 |
+
finally:
|
| 50 |
+
db.close()
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
if __name__ == "__main__":
|
| 54 |
+
main()
|