mirror of
https://github.com/marcogll/molding_assesment.git
synced 2026-03-15 18:25:09 +00:00
Refactor assessment system: rename v2 JSON files, update CLI script, add TUI interface, modify Markdown to hide correct answers in collapsible sections, adjust employee number inputs to text type
This commit is contained in:
@@ -489,3 +489,95 @@ Este error ocurre cuando los campos de texto no tienen el formato correcto de ob
|
|||||||
|
|
||||||
### Solución
|
### Solución
|
||||||
Ejecuta el script `formbricks_assitant.py` - maneja automáticamente la conversión de formato.
|
Ejecuta el script `formbricks_assitant.py` - maneja automáticamente la conversión de formato.
|
||||||
|
|
||||||
|
## Carga y Visualización de Encuestas
|
||||||
|
|
||||||
|
Para responder a consultas sobre Formbricks, es importante distinguir entre obtener los datos (API) y mostrar la encuesta (Renderizado).
|
||||||
|
|
||||||
|
### ¿Cuál es la forma correcta de cargar encuestas?
|
||||||
|
|
||||||
|
Aunque mencionas la REST API, la forma estándar y recomendada para cargar encuestas en una aplicación web no es llamando manualmente a los endpoints REST, sino utilizando el SDK de Formbricks (@formbricks/js).
|
||||||
|
|
||||||
|
El SDK se encarga automáticamente de llamar a la API correcta (Client API), verificar si el usuario debe ver una encuesta (basado en triggers) y renderizar la interfaz.
|
||||||
|
|
||||||
|
**Código de inicialización estándar (SDK):**
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
import formbricks from "@formbricks/js";
|
||||||
|
|
||||||
|
if (typeof window !== "undefined") {
|
||||||
|
formbricks.init({
|
||||||
|
environmentId: "TU_ENV_ID",
|
||||||
|
apiHost: "https://app.formbricks.com", // O tu propia URL si usas self-hosting
|
||||||
|
userId: "ID_DEL_USUARIO", // Opcional: para identificar al usuario
|
||||||
|
});
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Si realmente necesitas usar la REST API manual:
|
||||||
|
Si tu caso de uso es muy personalizado (ej. un backend propio que sirve encuestas), tendrías que llamar al endpoint de Displays para saber qué encuesta mostrar:
|
||||||
|
|
||||||
|
- **Endpoint**: POST /api/v1/client/displays
|
||||||
|
- **Respuesta**: Te devuelve el objeto de la encuesta (preguntas, lógica y estilos).
|
||||||
|
|
||||||
|
**Desventaja**: Tendrás que construir tú mismo todo el HTML y la lógica del formulario basándote en ese JSON.
|
||||||
|
|
||||||
|
### ¿Es posible definir el color principal y usar otros backgrounds?
|
||||||
|
|
||||||
|
Sí, es totalmente posible. Tienes dos caminos principales para lograrlo:
|
||||||
|
|
||||||
|
**Opción A: Sobrescribir estilos vía CSS (Recomendado para desarrolladores)**
|
||||||
|
|
||||||
|
Esta es la forma más flexible si usas el SDK. Formbricks utiliza variables CSS que puedes redefinir en tu hoja de estilos global (globals.css o similar) para forzar tus colores y fondos sin importar lo que diga la configuración de la encuesta.
|
||||||
|
|
||||||
|
Añade esto a tu CSS:
|
||||||
|
|
||||||
|
```css
|
||||||
|
:root {
|
||||||
|
/* Color principal (botones, bordes activos, etc.) */
|
||||||
|
--fb-brand-color: #ff5733;
|
||||||
|
|
||||||
|
/* Color del texto sobre el color principal */
|
||||||
|
--fb-brand-text-color: #ffffff;
|
||||||
|
|
||||||
|
/* Fondo de la tarjeta de la encuesta */
|
||||||
|
--fb-card-bg: #ffffff;
|
||||||
|
|
||||||
|
/* Fondo general (detrás de la tarjeta en encuestas de enlace o modales) */
|
||||||
|
--fb-survey-background-color: #f0f0f0;
|
||||||
|
|
||||||
|
/* Bordes */
|
||||||
|
--fb-border-color: #e2e8f0;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Al definir estas variables en tu proyecto, el SDK de Formbricks las usará automáticamente.
|
||||||
|
|
||||||
|
**Opción B: Definirlo en la configuración de la encuesta (UI o API)**
|
||||||
|
|
||||||
|
Si prefieres que el estilo venga definido desde la base de datos de Formbricks:
|
||||||
|
|
||||||
|
- **Desde la Interfaz (UI)**: Ve a la pestaña "Styling" (o "Look & Feel") dentro del editor de tu encuesta. Ahí puedes definir el Brand Color y el Background Styling (puedes subir una imagen, usar un degradado o un color sólido).
|
||||||
|
|
||||||
|
- **Desde la API (Payload)**: Si estás creando la encuesta programáticamente (POST /api/v1/management/surveys), el objeto JSON de la encuesta incluye una propiedad `styling`. Puedes enviarla así:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"name": "Mi Encuesta",
|
||||||
|
"styling": {
|
||||||
|
"brandColor": "#ff5733",
|
||||||
|
"cardBackgroundColor": "#ffffff",
|
||||||
|
"cardBorderColor": "#e2e8f0",
|
||||||
|
"background": {
|
||||||
|
"bg": "#f0f0f0", // Color de fondo sólido
|
||||||
|
"bgType": "color" // o "image" / "animation"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"questions": [...]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Resumen**
|
||||||
|
|
||||||
|
- **Carga**: Usa el SDK (`formbricks.init`) para la integración más fácil. Usa la API REST solo si vas a construir tu propia interfaz de usuario desde cero.
|
||||||
|
- **Estilos**: La forma más robusta de "definir" el color es usando las variables CSS (`--fb-brand-color`) en tu sitio web. Esto asegura que la encuesta siempre coincida con tu marca, independientemente de la configuración individual de la encuesta.
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -39,9 +39,9 @@ if not all([BASEURL, API_KEY, ENV_ID]):
|
|||||||
|
|
||||||
LEVEL_FILE_MAP = {
|
LEVEL_FILE_MAP = {
|
||||||
"0": "funnel_registration_formbricks.json",
|
"0": "funnel_registration_formbricks.json",
|
||||||
"1": "basic_v2_formbricks.json",
|
"1": "basic_formbricks.json",
|
||||||
"2": "medium_v2_formbricks.json",
|
"2": "medium_formbricks.json",
|
||||||
"3": "advanced_v2_formbricks.json",
|
"3": "advanced_formbricks.json",
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -93,6 +93,34 @@ def main():
|
|||||||
start_date = Prompt.ask("📅 Fecha inicio (YYYY-MM-DD o vacío)", default="")
|
start_date = Prompt.ask("📅 Fecha inicio (YYYY-MM-DD o vacío)", default="")
|
||||||
end_date = Prompt.ask("📅 Fecha término (YYYY-MM-DD o vacío)", default="")
|
end_date = Prompt.ask("📅 Fecha término (YYYY-MM-DD o vacío)", default="")
|
||||||
|
|
||||||
|
# ───────── Styling ─────────
|
||||||
|
console.print(
|
||||||
|
Panel(
|
||||||
|
"🎨 Configuración de colores (opcional - presiona Enter para usar defaults)",
|
||||||
|
border_style=COLORS["blue"],
|
||||||
|
)
|
||||||
|
)
|
||||||
|
brand_color = Prompt.ask(
|
||||||
|
"🎨 Color principal (brand color, ej: #ff5733)", default="#ff5733"
|
||||||
|
)
|
||||||
|
card_bg = Prompt.ask(
|
||||||
|
"🎨 Fondo de tarjeta (card background, ej: #ffffff)", default="#ffffff"
|
||||||
|
)
|
||||||
|
survey_bg = Prompt.ask(
|
||||||
|
"🎨 Fondo general (survey background, ej: #f0f0f0)", default="#f0f0f0"
|
||||||
|
)
|
||||||
|
border_color = Prompt.ask(
|
||||||
|
"🎨 Color de bordes (border color, ej: #e2e8f0)", default="#e2e8f0"
|
||||||
|
)
|
||||||
|
|
||||||
|
# Build styling object
|
||||||
|
styling = {
|
||||||
|
"brandColor": {"light": brand_color, "dark": brand_color},
|
||||||
|
"cardBackgroundColor": {"light": card_bg, "dark": card_bg},
|
||||||
|
"cardBorderColor": {"light": border_color, "dark": border_color},
|
||||||
|
"surveyBackground": {"bg": survey_bg, "bgType": "color"},
|
||||||
|
}
|
||||||
|
|
||||||
file_name = LEVEL_FILE_MAP[level]
|
file_name = LEVEL_FILE_MAP[level]
|
||||||
|
|
||||||
with open(file_name, "r", encoding="utf-8") as f:
|
with open(file_name, "r", encoding="utf-8") as f:
|
||||||
@@ -138,6 +166,7 @@ def main():
|
|||||||
payload["welcomeCard"] = welcome_card
|
payload["welcomeCard"] = welcome_card
|
||||||
if endings:
|
if endings:
|
||||||
payload["endings"] = endings
|
payload["endings"] = endings
|
||||||
|
payload["styling"] = styling
|
||||||
|
|
||||||
headers = {
|
headers = {
|
||||||
"Content-Type": "application/json",
|
"Content-Type": "application/json",
|
||||||
@@ -158,6 +187,12 @@ def main():
|
|||||||
console.print(
|
console.print(
|
||||||
Panel("✅ Encuesta creada correctamente", border_style=COLORS["green"])
|
Panel("✅ Encuesta creada correctamente", border_style=COLORS["green"])
|
||||||
)
|
)
|
||||||
|
console.print(
|
||||||
|
Panel(
|
||||||
|
"💡 Para integración con SDK: Revisa styles.css para variables CSS opcionales",
|
||||||
|
border_style=COLORS["yellow"],
|
||||||
|
)
|
||||||
|
)
|
||||||
else:
|
else:
|
||||||
console.print(Panel("❌ Error al crear encuesta", border_style=COLORS["red"]))
|
console.print(Panel("❌ Error al crear encuesta", border_style=COLORS["red"]))
|
||||||
console.print(response.status_code, response.text)
|
console.print(response.status_code, response.text)
|
||||||
|
|||||||
21
questions/formbricks/styles.css
Normal file
21
questions/formbricks/styles.css
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
/* Template de estilos para Formbricks - Variables CSS para sobrescribir colores */
|
||||||
|
|
||||||
|
/* Añade estas variables a tu hoja de estilos global (globals.css o similar) */
|
||||||
|
/* para forzar colores y fondos en las encuestas mostradas con el SDK */
|
||||||
|
|
||||||
|
:root {
|
||||||
|
/* Color principal (botones, bordes activos, etc.) */
|
||||||
|
--fb-brand-color: #ff5733;
|
||||||
|
|
||||||
|
/* Color del texto sobre el color principal */
|
||||||
|
--fb-brand-text-color: #ffffff;
|
||||||
|
|
||||||
|
/* Fondo de la tarjeta de la encuesta */
|
||||||
|
--fb-card-bg: #ffffff;
|
||||||
|
|
||||||
|
/* Fondo general (detrás de la tarjeta en encuestas de enlace o modales) */
|
||||||
|
--fb-survey-background-color: #f0f0f0;
|
||||||
|
|
||||||
|
/* Bordes */
|
||||||
|
--fb-border-color: #e2e8f0;
|
||||||
|
}
|
||||||
File diff suppressed because it is too large
Load Diff
61
questions/modify_md.py
Normal file
61
questions/modify_md.py
Normal file
@@ -0,0 +1,61 @@
|
|||||||
|
import re
|
||||||
|
|
||||||
|
|
||||||
|
def modify_md(file_path):
|
||||||
|
with open(file_path, "r", encoding="utf-8") as f:
|
||||||
|
content = f.read()
|
||||||
|
|
||||||
|
# Split by questions, assuming ### \d+\.
|
||||||
|
questions = re.split(r"(?=### \d+\.)", content)
|
||||||
|
|
||||||
|
modified_questions = []
|
||||||
|
for q in questions:
|
||||||
|
if not q.strip():
|
||||||
|
continue
|
||||||
|
# Find the options
|
||||||
|
lines = q.split("\n")
|
||||||
|
options_start = None
|
||||||
|
rational_start = None
|
||||||
|
for i, line in enumerate(lines):
|
||||||
|
if line.startswith("- "):
|
||||||
|
if options_start is None:
|
||||||
|
options_start = i
|
||||||
|
if line.startswith("**Racional:**"):
|
||||||
|
rational_start = i
|
||||||
|
break
|
||||||
|
if options_start is not None and rational_start is not None:
|
||||||
|
options = lines[options_start:rational_start]
|
||||||
|
rational = lines[rational_start:]
|
||||||
|
# Find the correct option
|
||||||
|
correct_option = None
|
||||||
|
for opt in options:
|
||||||
|
if "✅" in opt:
|
||||||
|
correct_option = opt.replace(" ✅", "").strip()
|
||||||
|
break
|
||||||
|
if correct_option:
|
||||||
|
# Remove ✅ from options
|
||||||
|
options = [opt.replace(" ✅", "") for opt in options]
|
||||||
|
# Create details
|
||||||
|
details = (
|
||||||
|
[
|
||||||
|
"<details>",
|
||||||
|
"<summary>Respuesta Correcta</summary>",
|
||||||
|
"",
|
||||||
|
correct_option + " ✅",
|
||||||
|
"",
|
||||||
|
]
|
||||||
|
+ rational
|
||||||
|
+ ["</details>"]
|
||||||
|
)
|
||||||
|
# Replace the part
|
||||||
|
lines = lines[:options_start] + options + [""] + details
|
||||||
|
q = "\n".join(lines)
|
||||||
|
modified_questions.append(q)
|
||||||
|
|
||||||
|
modified_content = "".join(modified_questions)
|
||||||
|
with open(file_path, "w", encoding="utf-8") as f:
|
||||||
|
f.write(modified_content)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
modify_md("markdown/Basic_assesment.md")
|
||||||
252
tui_assesment.py
Normal file
252
tui_assesment.py
Normal file
@@ -0,0 +1,252 @@
|
|||||||
|
import os
|
||||||
|
import json
|
||||||
|
import requests
|
||||||
|
from dotenv import load_dotenv
|
||||||
|
from textual.app import App
|
||||||
|
from textual.widgets import Button, Input, Label, Select, Checkbox, ListView, ListItem
|
||||||
|
from textual.containers import Container
|
||||||
|
|
||||||
|
load_dotenv(dotenv_path="questions/formbricks/.env")
|
||||||
|
|
||||||
|
BASEURL = os.getenv("FORMBRICKS_BASEURL")
|
||||||
|
API_KEY = os.getenv("FORMBRICKS_API_KEY")
|
||||||
|
ENV_ID = os.getenv("FORMBRICKS_ENVIRONMENT_ID")
|
||||||
|
|
||||||
|
LEVEL_FILE_MAP = {
|
||||||
|
"0": "questions/formbricks/funnel_registration_formbricks.json",
|
||||||
|
"1": "questions/formbricks/basic_formbricks.json",
|
||||||
|
"2": "questions/formbricks/medium_formbricks.json",
|
||||||
|
"3": "questions/formbricks/advanced_formbricks.json",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def convert_to_object_format(data):
|
||||||
|
if isinstance(data, dict):
|
||||||
|
for key, value in data.items():
|
||||||
|
if key in [
|
||||||
|
"headline",
|
||||||
|
"subheader",
|
||||||
|
"buttonLabel",
|
||||||
|
"backButtonLabel",
|
||||||
|
"placeholder",
|
||||||
|
"label",
|
||||||
|
"html",
|
||||||
|
] and isinstance(value, str):
|
||||||
|
data[key] = {"default": value}
|
||||||
|
elif key == "choices" and isinstance(value, list):
|
||||||
|
for choice in value:
|
||||||
|
if (
|
||||||
|
isinstance(choice, dict)
|
||||||
|
and "label" in choice
|
||||||
|
and isinstance(choice["label"], str)
|
||||||
|
):
|
||||||
|
choice["label"] = {"default": choice["label"]}
|
||||||
|
else:
|
||||||
|
convert_to_object_format(value)
|
||||||
|
elif isinstance(data, list):
|
||||||
|
for item in data:
|
||||||
|
convert_to_object_format(item)
|
||||||
|
|
||||||
|
|
||||||
|
def parse_questions(raw_items):
|
||||||
|
questions = []
|
||||||
|
for i, item in enumerate(raw_items):
|
||||||
|
q = item.copy()
|
||||||
|
if "id" not in q:
|
||||||
|
q["id"] = f"q{i}"
|
||||||
|
questions.append(q)
|
||||||
|
return questions
|
||||||
|
|
||||||
|
|
||||||
|
def get_surveys():
|
||||||
|
headers = {"x-api-key": API_KEY}
|
||||||
|
response = requests.get(f"{BASEURL}/api/v1/management/surveys", headers=headers)
|
||||||
|
if response.ok:
|
||||||
|
return response.json().get("data", [])
|
||||||
|
return []
|
||||||
|
|
||||||
|
|
||||||
|
def update_survey_status(survey_id, status):
|
||||||
|
headers = {"Content-Type": "application/json", "x-api-key": API_KEY}
|
||||||
|
payload = {"status": status}
|
||||||
|
response = requests.put(
|
||||||
|
f"{BASEURL}/api/v1/management/surveys/{survey_id}",
|
||||||
|
json=payload,
|
||||||
|
headers=headers,
|
||||||
|
)
|
||||||
|
return response.ok
|
||||||
|
|
||||||
|
|
||||||
|
class SurveyApp(App):
|
||||||
|
CSS = """
|
||||||
|
App {
|
||||||
|
background: #303446;
|
||||||
|
color: #c6d0f5;
|
||||||
|
}
|
||||||
|
Button {
|
||||||
|
background: #8caaee;
|
||||||
|
color: #303446;
|
||||||
|
}
|
||||||
|
Input {
|
||||||
|
background: #414559;
|
||||||
|
color: #c6d0f5;
|
||||||
|
border: solid #8caaee;
|
||||||
|
}
|
||||||
|
Label {
|
||||||
|
color: #c6d0f5;
|
||||||
|
}
|
||||||
|
CheckBox {
|
||||||
|
color: #c6d0f5;
|
||||||
|
}
|
||||||
|
Select {
|
||||||
|
background: #414559;
|
||||||
|
color: #c6d0f5;
|
||||||
|
border: solid #8caaee;
|
||||||
|
}
|
||||||
|
ListView {
|
||||||
|
background: #414559;
|
||||||
|
color: #c6d0f5;
|
||||||
|
border: solid #8caaee;
|
||||||
|
}
|
||||||
|
"""
|
||||||
|
|
||||||
|
def compose(self):
|
||||||
|
yield Container(
|
||||||
|
Label("Company:"),
|
||||||
|
Input(placeholder="e.g. Aptiv", id="company"),
|
||||||
|
Label("Start Date:"),
|
||||||
|
Input(placeholder="YYYY-MM-DD", id="start_date"),
|
||||||
|
Label("End Date:"),
|
||||||
|
Input(placeholder="YYYY-MM-DD", id="end_date"),
|
||||||
|
Label("Brand Color:"),
|
||||||
|
Input(value="#ff5733", id="brand_color"),
|
||||||
|
Label("Levels to Generate:"),
|
||||||
|
Checkbox(
|
||||||
|
"Funnel (0) - Mandatory unless unchecked", id="level0", value=True
|
||||||
|
),
|
||||||
|
Checkbox("Basic (1)", id="level1"),
|
||||||
|
Checkbox("Medium (2)", id="level2"),
|
||||||
|
Checkbox("Advanced (3)", id="level3"),
|
||||||
|
Button("Generate Selected", id="generate"),
|
||||||
|
Button("List Surveys", id="list"),
|
||||||
|
ListView(id="survey_list"),
|
||||||
|
Label("Select Status for Update:"),
|
||||||
|
Select(
|
||||||
|
[
|
||||||
|
("draft", "Draft"),
|
||||||
|
("inProgress", "In Progress"),
|
||||||
|
("paused", "Paused"),
|
||||||
|
("completed", "Completed"),
|
||||||
|
],
|
||||||
|
id="new_status",
|
||||||
|
),
|
||||||
|
Button("Update Selected Survey", id="update"),
|
||||||
|
Label("", id="status"),
|
||||||
|
)
|
||||||
|
|
||||||
|
def on_button_pressed(self, event):
|
||||||
|
if event.button.id == "generate":
|
||||||
|
company = self.query_one("#company").value
|
||||||
|
start_date = self.query_one("#start_date").value
|
||||||
|
end_date = self.query_one("#end_date").value
|
||||||
|
brand_color = self.query_one("#brand_color").value
|
||||||
|
levels = []
|
||||||
|
for i in range(4):
|
||||||
|
if self.query_one(f"#level{i}").value:
|
||||||
|
levels.append(str(i))
|
||||||
|
if not levels:
|
||||||
|
self.query_one("#status").update("No levels selected.")
|
||||||
|
return
|
||||||
|
for level in levels:
|
||||||
|
file_name = LEVEL_FILE_MAP[level]
|
||||||
|
with open(file_name, "r", encoding="utf-8") as f:
|
||||||
|
raw_file = json.load(f)
|
||||||
|
raw_questions = raw_file.get("questions", [])
|
||||||
|
questions = parse_questions(raw_questions)
|
||||||
|
convert_to_object_format(questions)
|
||||||
|
welcome_card = raw_file.get("welcomeCard")
|
||||||
|
if welcome_card:
|
||||||
|
convert_to_object_format(welcome_card)
|
||||||
|
endings = raw_file.get("endings", [])
|
||||||
|
for ending in endings:
|
||||||
|
ending["id"] = "p73t62dgwq0cvmtt6ug0hmfc"
|
||||||
|
if "buttonLabel" not in ending:
|
||||||
|
ending["buttonLabel"] = {"default": "Completar"}
|
||||||
|
if "buttonLink" not in ending:
|
||||||
|
ending["buttonLink"] = "https://example.com"
|
||||||
|
convert_to_object_format(endings)
|
||||||
|
if level == "0":
|
||||||
|
title = f"{company} | Funnel L0"
|
||||||
|
else:
|
||||||
|
title = f"{company} | Evaluacion de moldeo L{level}"
|
||||||
|
styling = {
|
||||||
|
"brandColor": {"light": brand_color, "dark": brand_color},
|
||||||
|
"cardBackgroundColor": {"light": "#ffffff", "dark": "#ffffff"},
|
||||||
|
"cardBorderColor": {"light": "#e2e8f0", "dark": "#e2e8f0"},
|
||||||
|
"surveyBackground": {"bg": "#f0f0f0", "bgType": "color"},
|
||||||
|
}
|
||||||
|
payload = {
|
||||||
|
"environmentId": ENV_ID,
|
||||||
|
"name": title,
|
||||||
|
"status": "draft",
|
||||||
|
"type": "link",
|
||||||
|
"displayOption": "displayOnce",
|
||||||
|
"languages": [],
|
||||||
|
"questions": questions,
|
||||||
|
}
|
||||||
|
if welcome_card:
|
||||||
|
payload["welcomeCard"] = welcome_card
|
||||||
|
if endings:
|
||||||
|
payload["endings"] = endings
|
||||||
|
payload["styling"] = styling
|
||||||
|
headers = {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
"x-api-key": API_KEY,
|
||||||
|
}
|
||||||
|
response = requests.post(
|
||||||
|
f"{BASEURL}/api/v1/management/surveys",
|
||||||
|
json=payload,
|
||||||
|
headers=headers,
|
||||||
|
timeout=30,
|
||||||
|
)
|
||||||
|
if not response.ok:
|
||||||
|
self.query_one("#status").update(
|
||||||
|
f"Error generating level {level}: {response.text}"
|
||||||
|
)
|
||||||
|
return
|
||||||
|
self.query_one("#status").update("Surveys generated successfully!")
|
||||||
|
elif event.button.id == "list":
|
||||||
|
surveys = get_surveys()
|
||||||
|
list_view = self.query_one("#survey_list")
|
||||||
|
list_view.clear()
|
||||||
|
for survey in surveys:
|
||||||
|
list_view.append(
|
||||||
|
ListItem(
|
||||||
|
Label(f"{survey['name']} - {survey['status']}"), id=survey["id"]
|
||||||
|
)
|
||||||
|
)
|
||||||
|
self.query_one("#status").update("Surveys listed.")
|
||||||
|
elif event.button.id == "update":
|
||||||
|
list_view = self.query_one("#survey_list")
|
||||||
|
if (
|
||||||
|
hasattr(list_view, "selected_index")
|
||||||
|
and list_view.selected_index is not None
|
||||||
|
):
|
||||||
|
selected_item = list_view.children[list_view.selected_index]
|
||||||
|
survey_id = selected_item.id
|
||||||
|
new_status = self.query_one("#new_status").value
|
||||||
|
if update_survey_status(survey_id, new_status):
|
||||||
|
self.query_one("#status").update("Survey status updated.")
|
||||||
|
# Refresh list
|
||||||
|
self.on_button_pressed(
|
||||||
|
Button.Pressed(button=Button("List", id="list"))
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
self.query_one("#status").update("Error updating status.")
|
||||||
|
else:
|
||||||
|
self.query_one("#status").update("No survey selected.")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
app = SurveyApp()
|
||||||
|
app.run()
|
||||||
Reference in New Issue
Block a user