Find prompts, extensions, and productivity tools for Microsoft Copilot.
Design and document API rate limiting with tier-based quotas, retry headers, and client-friendly error responses.
Identify causes of WebSocket disconnections including proxy timeouts, heartbeat failures, and handshake issues.
Generate a complete README with badges, installation, usage examples, contributing guide, and license information.
Replace complex constructor parameters with a fluent builder pattern for better readability and validation.
Create Grafana dashboard configurations with relevant panels, queries, and alerting for application monitoring.
Analyze code for common security issues including SQL injection, XSS, CSRF, and authentication bypasses.
Create a formatted changelog from git commits with proper categorization, breaking changes, and version grouping.
Prompt Copilot to create pivot tables with calculated fields, grouping, and custom value summarizations.
Build interactive dashboards with dynamic charts, slicers, and conditional formatting using Copilot assistance.
Identify the source of memory leaks using heap snapshots, allocation timelines, and object retention analysis.
Get your product in front of the builders defining the future.
Scans applications for security misconfigurations, generates hardening recommendations, and automates security policy enforcement.
Generates detailed code coverage reports with trend analysis, uncovered critical paths, and testing priority suggestions.
Manages monorepo workflows with dependency graphs, affected package detection, and optimized build ordering.
Measures cyclomatic complexity, cognitive complexity, and maintainability index with refactoring suggestions for complex code.
Continuously monitors project dependencies for security vulnerabilities, license compliance issues, and available updates with migration assistance.
Manages environment configurations across development, staging, and production with validation, secret rotation, and drift detection.
Write AI instructions once, sync to every tool. One canonical format (.skillr/) compiles to CLAUDE.md, .cursor/rules, Copilot, Windsurf, Cline, and OpenAI configs.
Stars: 2 Language: PHP
A CLI tool for transferring AI agent configurations (skills, tools, rules, instructions) between different platforms like GitHub Copilot, Cursor, Claude, and Windsurf.
Stars: 1 Language: TypeScript
o CLI that keeps a canonical .ai source of rules, skills, agents, prompts, and MCP config, then generates synchronized hard-copy setups for Cursor, GitHub Copilot, and Claude Code (including dynamic instructions/docs and template-driven automation) across repositories.
Stars: 1 Language: Go
Green-POS es un Sistema de Punto de Venta completo desarrollado en Flask que incluye gestión de inventario, facturación, clientes y servicios de mascotas (grooming, veterinaria).
Este proyecto utiliza tres agents ejecutables en Copilot Agent Mode para desarrollo modular:
🎨 @green-pos-frontend (.github/agents/green-pos-frontend.agent.md)
🐍 @green-pos-backend (.github/agents/green-pos-backend.agent.md)
🗄️ @green-pos-database (.github/agents/green-pos-database.agent.md)
Guías de uso:
.github/agents/README.md.github/agents/QUICK_REFERENCE.mdDocumentación técnica (para humanos):
.github/instructions/frontend-html-agent.instructions.md.github/instructions/backend-python-agent.instructions.md.github/instructions/database-sqlite-agent.instructions.mdUso básico:
@green-pos-frontend crea templates/suppliers/list.html con DataTable
@green-pos-backend implementa CRUD completo para Supplier
@green-pos-database crea modelo Supplier con relación a Product
Con subagents:
@green-pos-frontend
#runSubagent <subagent_scaffold_page> pathOut=templates/reports/sales.html pageTitle="Ventas"
@green-pos-backend
#runSubagent <subagent_generate_crud> entityName=Supplier routePrefix=suppliers
@green-pos-database
#runSubagent <subagent_generate_model> entityName=Category fields=[...]
Workflow multi-agent (CRUD completo):
# Paso 1: Crear modelo
@green-pos-database crea modelo Supplier con campos code, name, phone, email
# Paso 2: Crear rutas
@green-pos-backend implementa CRUD para Supplier con validación
# Paso 3: Crear vistas
@green-pos-frontend crea templates/suppliers/list.html, form.html, view.html
bi-*)CRÍTICO - Restricciones de Producción:
Concurrencia Limitada:
Transacciones Explícitas:
# OBLIGATORIO: Siempre usar try-except con rollback
try:
db.session.add(entity)
db.session.commit()
except Exception as e:
db.session.rollback()
app.logger.error(f"Error: {e}")
raise
Tipos de Datos:
DateTime se almacena como TEXT ISO 8601Tamaño de Base de Datos:
Backups:
CRÍTICO - Servidor de Producción Windows:
NO usar emojis en código Python:
Alternativas permitidas:
# ❌ INCORRECTO: Usar emojis
print("✅ Migración exitosa")
print("❌ Error en migración")
print("🔄 Procesando...")
# ✅ CORRECTO: Usar prefijos de texto
print("[OK] Migracion exitosa")
print("[ERROR] Error en migracion")
print("[INFO] Procesando...")
# Prefijos estándar:
# [OK] - Operación exitosa (verde)
# [ERROR] - Error crítico (rojo)
# [WARNING] - Advertencia (amarillo)
# [INFO] - Información (cyan)
# [DELETE] - Operación de borrado
Caracteres acentuados:
Archivos afectados:
migrate_*.py)verify_*.py)CRÍTICO - Patrón de Resolución de Paths:
NUNCA usar rutas relativas simples:
# ❌ INCORRECTO: Depende del CWD (Current Working Directory)
open('archivo.sql')
sqlite3.connect('instance/app.db')
db_path = os.path.join('instance', 'app.db')
# ✅ CORRECTO: Ruta relativa al script (funciona desde cualquier CWD)
from pathlib import Path
SCRIPT_DIR = Path(__file__).parent
PROJECT_ROOT = SCRIPT_DIR.parent
sql_file = SCRIPT_DIR / 'archivo.sql'
db_path = PROJECT_ROOT / 'instance' / 'app.db'
Usar template estándar:
migrations/TEMPLATE_MIGRATION.pyVerificar desde diferentes directorios:
# SIEMPRE probar desde raíz del proyecto (caso común en producción)
python migrations/migration_nombre.py
# También probar desde directorio migrations/
cd migrations && python migration_nombre.py
# Verificar con ruta absoluta
python D:\ruta\completa\migrations\migration_nombre.py
Resultado esperado: Script funciona en todos los casos sin FileNotFoundError
Archivos afectados:
migrate_*.py, migration_*.py)verify_*.py)query_*.py)migrations/Por qué es importante:
open('archivo') relativo al CWD, NO a la ubicación del scriptpython migrations/script.pyPath(__file__).parent, script busca en raíz en lugar de migrations/FileNotFoundError aunque archivo existaEjemplo del problema:
Green-POS/ <-- CWD al ejecutar: python migrations/script.py
├── migrations/
│ ├── script.py <-- Script ejecutado
│ └── archivo.sql <-- Archivo real AQUÍ
└── archivo.sql <-- Python busca AQUÍ (no existe) ❌
Fix aplicado:
2d412fc: Fix en migration_add_inventory_flag.pydocs/research/2025-11-24-causa-raiz-filenotfounderror-migracion-produccion.mddocs/FIX_FILENOTFOUNDERROR_MIGRATION_PATHS.mdSingle-threaded por defecto:
current_app, g, sessionManejo de Archivos:
Sesiones:
Sin jQuery:
Navegadores Soportados:
Responsive Breakpoints:
// Obligatorio respetar estos breakpoints
xs: <576px (mobile)
sm: ≥576px (mobile landscape)
md: ≥768px (tablet)
lg: ≥992px (desktop)
xl: ≥1200px (large desktop)
xxl: ≥1400px (extra large)
Appointments (Citas):
scheduled_at: Timezone-naive (hora local)Invoices (Facturas):
date: Timezone-aware (UTC storage)format_time_coTimestamps de Sistema:
created_at, updated_at: UTCdatetime.now(timezone.utc) para consistencyFuentes:
Tamaño de Página:
Imágenes:
Uso: Acceso a datos centralizado
# Patrón usado en queries complejas
class ProductRepository:
@staticmethod
def get_with_sales_count():
"""Obtiene productos con conteo de ventas."""
return db.session.query(
Product,
func.count(InvoiceItem.id).label('sales_count')
).outerjoin(InvoiceItem).group_by(Product.id).all()
@staticmethod
def search(query_text, sort_by='name', sort_order='asc'):
"""Búsqueda con ordenamiento dinámico."""
q = Product.query.filter(
or_(
Product.name.ilike(f'%{query_text}%'),
Product.code.ilike(f'%{query_text}%')
)
)
return q.order_by(getattr(Product, sort_by).desc()
if sort_order == 'desc'
else getattr(Product, sort_by).asc()).all()
Ventajas:
Uso: Autorización y autenticación
from functools import wraps
from flask_login import current_user
from flask import flash, redirect, url_for
def role_required(role):
"""Decorator para validar rol del usuario."""
def decorator(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if not current_user.is_authenticated:
flash('Debe iniciar sesión', 'warning')
return redirect(url_for('login'))
if current_user.role != role and current_user.role != 'admin':
flash('Acceso denegado', 'danger')
return redirect(url_for('index'))
return f(*args, **kwargs)
return decorated_function
return decorator
# Uso:
@app.route('/products/new')
@login_required
@role_required('admin')
def product_new():
# Solo admin puede crear productos
pass
Ventajas:
Uso: Creación de usuarios por defecto
class User(db.Model):
# ...
@staticmethod
def create_defaults():
"""Factory para crear usuarios iniciales."""
existing = User.query.count()
if existing == 0:
users = [
('admin', 'admin', 'admin'),
('vendedor', 'vendedor', 'vendedor'),
]
for username, password, role in users:
user = User(username=username, role=role)
user.set_password(password)
db.session.add(user)
db.session.commit()
Uso: Hooks de SQLAlchemy para audit logs
class ProductStockLog(db.Model):
"""Log de cambios - patrón Observer implícito."""
# Al cambiar Product.stock, se crea automáticamente un log
# Implementación en product_edit():
@app.route('/products/edit/<int:id>', methods=['GET', 'POST'])
def product_edit(id):
product = Product.query.get_or_404(id)
if request.method == 'POST':
new_stock = int(request.form.get('stock', 0))
old_stock = product.stock
if new_stock != old_stock:
# "Notificar" al observer creando log
log = ProductStockLog(
product_id=product.id,
user_id=current_user.id,
quantity=abs(new_stock - old_stock),
movement_type='addition' if new_stock > old_stock else 'subtraction',
reason=request.form['stock_reason'],
previous_stock=old_stock,
new_stock=new_stock
)
db.session.add(log)
Ventajas:
Uso: Métodos de pago en facturas
class Invoice(db.Model):
payment_method = db.Column(db.String(50), default='cash')
# Valores: 'cash', 'transfer', 'card', 'mixed'
# Estrategia de procesamiento según método
def process_payment(invoice):
strategies = {
'cash': process_cash_payment,
'transfer': process_transfer_payment,
'card': process_card_payment,
'mixed': process_mixed_payment
}
processor = strategies.get(invoice.payment_method)
return processor(invoice) if processor else None
Uso: Rutas CRUD estándar
# Plantilla común para CRUD operations
def crud_list(model_class, template, **filters):
"""Template method para listar entidades."""
query = model_class.query
# Hook: aplicar filtros
for key, value in filters.items():
if value:
query = query.filter(getattr(model_class, key).ilike(f'%{value}%'))
# Hook: ordenar
items = query.order_by(model_class.created_at.desc()).all()
# Hook: renderizar
return render_template(template, items=items)
# Especialización:
@app.route('/products')
def product_list():
return crud_list(
Product,
'products/list.html',
name=request.args.get('query')
)
Uso: Construcción de mensajes WhatsApp
class WhatsAppMessageBuilder:
"""Builder para crear mensajes WhatsApp estructurados."""
def __init__(self):
self.parts = []
def add_greeting(self, name):
self.parts.append(f"Hola {name}!")
return self
def add_business(self, business_name):
self.parts.append(f"Te saludamos desde *{business_name}*")
return self
def add_appointment_info(self, pet_name, date, time):
self.parts.append(
f"Recuerda la cita con nuestra groomer para *{pet_name}*\n\n"
f"Fecha: {date}\n"
f"Hora: {time}"
)
return self
def add_closing(self):
self.parts.append("Gracias por preferirnos!")
return self
def build(self):
return "%0A".join(self.parts)
# Uso en template:
{% set mensaje = WhatsAppMessageBuilder()
.add_greeting(first_name)
.add_business("Pet Verde")
.add_appointment_info(pet_name, fecha, hora)
.add_closing()
.build() %}
Uso: Adaptador de zona horaria
class TimezoneAdapter:
"""Adapta datetime UTC a timezone local."""
@staticmethod
def to_local(utc_datetime, tz=CO_TZ):
"""Convierte UTC a timezone local."""
if utc_datetime.tzinfo is None:
utc_datetime = utc_datetime.replace(tzinfo=timezone.utc)
return utc_datetime.astimezone(tz)
@staticmethod
def to_utc(local_datetime, tz=CO_TZ):
"""Convierte local a UTC."""
if local_datetime.tzinfo is None:
local_datetime = tz.localize(local_datetime)
return local_datetime.astimezone(timezone.utc)
# Filtro Jinja2:
@app.template_filter('format_time_co')
def format_time_co(dt):
"""Adapta y formatea datetime a hora Colombia."""
if not dt:
return ''
local_dt = TimezoneAdapter.to_local(dt)
return local_dt.strftime('%I:%M %p')
Uso: Estructura jerárquica de servicios
class Appointment(db.Model):
"""Composite: Agrupa múltiples servicios."""
services = db.relationship('PetService', backref='appointment',
lazy='dynamic', cascade='all, delete-orphan')
def recompute_total(self):
"""Calcula total recursivamente de todos los servicios."""
self.total_price = sum(s.price or 0 for s in self.services)
self.total_services = self.services.count()
class PetService(db.Model):
"""Leaf: Servicio individual."""
appointment_id = db.Column(db.Integer, db.ForeignKey('appointment.id'))
service_type_id = db.Column(db.Integer, db.ForeignKey('service_type.id'))
price = db.Column(db.Float, nullable=False)
Uso: Estados de citas y facturas
class AppointmentState:
"""Estado de una cita con transiciones válidas."""
PENDING = 'pending'
DONE = 'done'
CANCELLED = 'cancelled'
TRANSITIONS = {
PENDING: [DONE, CANCELLED],
DONE: [], # Estado final
CANCELLED: [] # Estado final
}
@classmethod
def can_transition(cls, from_state, to_state):
"""Valida si la transición es permitida."""
return to_state in cls.TRANSITIONS.get(from_state, [])
# Uso en ruta:
@app.route('/appointments/<int:id>/cancel', methods=['POST'])
def appointment_cancel(id):
appointment = Appointment.query.get_or_404(id)
if not AppointmentState.can_transition(appointment.status, 'cancelled'):
flash('No se puede cancelar esta cita', 'error')
return redirect(url_for('appointment_view', id=id))
appointment.status = AppointmentState.CANCELLED
db.session.commit()
flash('Cita cancelada exitosamente', 'success')
return redirect(url_for('appointment_list'))
Uso: Encapsulación de funcionalidad frontend
// Pattern IIFE - Módulo de formulario de servicios
window.ServiceForm = (function() {
// Variables privadas
let selectedServices = [];
let totalPrice = 0;
// Métodos privados
function calculateTotal() {
totalPrice = selectedServices.reduce((sum, s) => sum + s.price, 0);
updateDisplay();
}
function updateDisplay() {
document.getElementById('total').textContent =
formatCurrency(totalPrice);
}
// API pública
return {
init: function() {
bindEvents();
loadSelectedServices();
},
addService: function(serviceId, price) {
selectedServices.push({ id: serviceId, price: price });
calculateTotal();
},
removeService: function(serviceId) {
selectedServices = selectedServices.filter(s => s.id !== serviceId);
calculateTotal();
},
getTotal: function() {
return totalPrice;
}
};
})();
// Uso:
ServiceForm.init();
ServiceForm.addService(1, 50000);
┌─────────────────────────────────────────┐
│ Presentation Layer │
│ (Templates Jinja2 + Bootstrap + JS) │
│ - layout.html │
│ - list/form/view templates │
│ - Validación cliente │
└────────────┬────────────────────────────┘
│
┌────────────▼────────────────────────────┐
│ Application Layer │
│ (Flask Routes - app.py) │
│ - Autorización (@decorators) │
│ - Validación servidor │
│ - Orquestación lógica de negocio │
│ - Flash messages │
└────────────┬────────────────────────────┘
│
┌────────────▼────────────────────────────┐
│ Business Logic Layer │
│ (Models + Methods) │
│ - Reglas de negocio │
│ - Cálculos (totales, stocks) │
│ - Validaciones complejas │
│ - State transitions │
└────────────┬────────────────────────────┘
│
┌────────────▼────────────────────────────┐
│ Data Access Layer │
│ (SQLAlchemy ORM) │
│ - CRUD operations │
│ - Queries complejas │
│ - Transacciones │
│ - Relationships │
└────────────┬────────────────────────────┘
│
┌────────────▼────────────────────────────┐
│ Database Layer │
│ (SQLite / PostgreSQL) │
│ - Persistencia │
│ - Constraints │
│ - Indexes │
└─────────────────────────────────────────┘
1. Usuario → HTTP Request
↓
2. Flask App → Route Matching (@app.route)
↓
3. Decorators → Autenticación/Autorización
↓
4. Route Handler → Validación de datos
↓
5. Business Logic → Procesamiento
↓
6. ORM (SQLAlchemy) → Queries
↓
7. Database → Persistencia
↓
8. Response → Template Rendering
↓
9. HTTP Response → Usuario
# 1. Request
POST /services/new
{
customer_id: 1,
pet_id: 2,
service_types: [1, 3],
scheduled_at: '2025-10-22 14:30'
}
# 2. Route + Validation
@app.route('/services/new', methods=['POST'])
@login_required
def service_new():
# 3. Create Appointment (Business Logic)
appointment = Appointment(
customer_id=request.form['customer_id'],
pet_id=request.form['pet_id'],
scheduled_at=datetime.strptime(...)
)
# 4. Add Services (Composite Pattern)
for service_type_id in request.form.getlist('service_types'):
service = PetService(
service_type_id=service_type_id,
price=get_service_price(service_type_id)
)
appointment.services.append(service)
# 5. Recompute Total (Business Logic)
appointment.recompute_total()
# 6. Persist (Data Layer)
db.session.add(appointment)
db.session.commit()
# 7. Response
flash('Cita creada exitosamente', 'success')
return redirect(url_for('appointment_view', id=appointment.id))
# ✅ CORRECTO: Cada clase una responsabilidad
class User(db.Model):
"""Solo maneja datos de usuario."""
username = db.Column(db.String(50))
def set_password(self, password):
"""Responsabilidad: hash de contraseña."""
self.password_hash = generate_password_hash(password)
class UserRepository:
"""Solo maneja acceso a datos de usuario."""
@staticmethod
def find_by_username(username):
return User.query.filter_by(username=username).first()
class AuthService:
"""Solo maneja autenticación."""
@staticmethod
def authenticate(username, password):
user = UserRepository.find_by_username(username)
if user and user.check_password(password):
login_user(user)
return True
return False
# ✅ CORRECTO: Abierto para extensión, cerrado para modificación
class PaymentProcessor:
"""Base para procesadores de pago."""
def process(self, invoice):
raise NotImplementedError
class CashPaymentProcessor(PaymentProcessor):
def process(self, invoice):
# Lógica específica para efectivo
pass
class TransferPaymentProcessor(PaymentProcessor):
def process(self, invoice):
# Lógica específica para transferencia
pass
# Agregar nuevos métodos sin modificar código existente
class CardPaymentProcessor(PaymentProcessor):
def process(self, invoice):
# Nueva funcionalidad
pass
# ✅ CORRECTO: Subclases intercambiables
class Document(db.Model):
"""Documento base."""
__abstract__ = True
number = db.Column(db.String(30))
date = db.Column(db.DateTime)
total = db.Column(db.Float)
def calculate_total(self):
"""Debe ser implementado por subclases."""
raise NotImplementedError
class Invoice(Document):
"""Factura - puede sustituir Document."""
def calculate_total(self):
self.total = self.subtotal + self.tax
class Receipt(Document):
"""Recibo - puede sustituir Document."""
def calculate_total(self):
self.total = self.amount
# ✅ CORRECTO: Interfaces específicas
class Searchable:
"""Interface para entidades buscables."""
def search(self, query):
raise NotImplementedError
class Sortable:
"""Interface para entidades ordenables."""
def sort_by(self, field, order='asc'):
raise NotImplementedError
class Product(db.Model, Searchable, Sortable):
"""Implementa solo lo que necesita."""
def search(self, query):
return Product.query.filter(
Product.name.ilike(f'%{query}%')
).all()
def sort_by(self, field, order='asc'):
return Product.query.order_by(
getattr(Product, field).desc() if order == 'desc'
else getattr(Product, field).asc()
).all()
# ✅ CORRECTO: Depender de abstracciones
class Repository:
"""Abstracción de acceso a datos."""
def get(self, id):
raise NotImplementedError
def save(self, entity):
raise NotImplementedError
class SQLAlchemyRepository(Repository):
"""Implementación concreta con SQLAlchemy."""
def __init__(self, model):
self.model = model
def get(self, id):
return self.model.query.get(id)
def save(self, entity):
db.session.add(entity)
db.session.commit()
# Service depende de abstracción, no de implementación
class ProductService:
def __init__(self, repository: Repository):
self.repository = repository
def get_product(self, id):
return self.repository.get(id)
# ✅ CORRECTO: Usar ORM parametrizado
users = User.query.filter(User.username == username).all()
# ✅ CORRECTO: Queries raw con parámetros
db.session.execute(
"SELECT * FROM users WHERE username = :username",
{"username": username}
)
# ❌ INCORRECTO: Concatenación de strings
db.session.execute(f"SELECT * FROM users WHERE username = '{username}'")
<!-- ✅ CORRECTO: Jinja2 escapa automáticamente -->
<p>{{ user.name }}</p>
<!-- ✅ CORRECTO: Usar |safe solo con contenido confiable -->
<div>{{ content|safe }}</div>
<!-- ❌ INCORRECTO: Insertar HTML no escapado -->
<script>var data = {{ data }};</script>
# ✅ CORRECTO: Flask-WTF incluye token CSRF
from flask_wtf.csrf import CSRFProtect
csrf = CSRFProtect(app)
# En templates:
<form method="post">
{{ csrf_token() }}
<!-- campos -->
</form>
# ✅ CORRECTO: Usar werkzeug con salt automático
from werkzeug.security import generate_password_hash, check_password_hash
# Hash con salt automático (bcrypt-like)
hash = generate_password_hash('password', method='pbkdf2:sha256')
# ❌ INCORRECTO: Hash simple sin salt
import hashlib
hash = hashlib.sha256('password'.encode()).hexdigest()
# ✅ CORRECTO: Configuración segura
app.config['SESSION_COOKIE_SECURE'] = True # Solo HTTPS
app.config['SESSION_COOKIE_HTTPONLY'] = True # No JS access
app.config['SESSION_COOKIE_SAMESITE'] = 'Lax' # CSRF protection
app.config['PERMANENT_SESSION_LIFETIME'] = timedelta(hours=2)
Green-POS/
├── app.py # Aplicación Flask principal (~2000 líneas)
├── models/
│ └── models.py # Modelos SQLAlchemy (User, Customer, Pet, Product, Invoice, Appointment, etc.)
├── templates/
│ ├── layout.html # Plantilla base con navbar y sidebar
│ ├── appointments/ # Sistema de citas
│ │ ├── list.html # Lista agrupada por fecha
│ │ ├── form.html # Crear cita (tarjetas interactivas)
│ │ ├── edit.html # Editar cita (mismo diseño que form)
│ │ └── view.html # Detalle con impresión de consentimiento
│ ├── customers/ # Gestión de clientes
│ ├── invoices/ # Facturación
│ │ └── list.html # Agrupación por fecha con totales por método de pago
│ ├── products/ # Inventario
│ │ ├── stock_history.html # Historial de movimientos
│ │ └── form.html # Con campo de razón para cambios de stock
│ ├── services/ # Servicios (ahora citas)
│ │ └── types/ # Tipos de servicio
│ │ ├── config.html # CRUD de tipos
│ │ └── form.html # Modal para crear/editar
│ └── pets/ # Mascotas
├── static/
│ ├── css/
│ ├── js/
│ │ └── main.js # JavaScript principal
│ └── uploads/
│ └── logo.png # Logo del negocio
├── instance/
│ └── app.db # Base de datos SQLite
└── requirements.txt
def appointment_update(id: int) -> Response:
"""Actualiza una cita existente con validación de cambios.
Args:
id: ID de la cita a actualizar
Returns:
Response: Redirect a vista de cita o formulario con errores
Raises:
404: Si la cita no existe
"""
datetime.now(CO_TZ) para timestamps localesdb.session con rollback en excepcionesapp.logger.error() para errores críticos solamenteCRÍTICO - Ciclo de Desarrollo con Limpieza:
Durante Desarrollo:
Durante Testing:
Antes de Producción:
print(), console.log() temporales# TODO, # DEBUG, # TEMP, # FIXME, # TESTRegla de Oro: El código productivo debe estar limpio, sin rastros de debugging temporal
OBLIGATORIO - Marcado de Código Temporal:
# DEBUG: imprimir valores para troubleshooting
print(f"Debug: usuario = {user}")
# TODO: optimizar esta query con joins
debug_var = "temporal" # TEMP: variable de prueba
# FIXME: revisar lógica de validación de stock
import pdb; pdb.set_trace() # DEBUG: breakpoint temporal
# TEST: función solo para pruebas unitarias
def test_function():
pass
// DEBUG: verificar valores del formulario
console.log("Debug info:", data);
// TODO: implementar validación real
// TEMP: función de prueba para testing
function debugFunction() { alert("Test"); } // DEBUG
// FIXME: corregir cálculo de total
let debugTotal = 0; // TEMP
Marcadores Estándar para Limpieza:
# DEBUG: / // DEBUG: → Código de debugging temporal# TODO: / // TODO: → Tareas pendientes# TEMP: / // TEMP: → Código experimental# FIXME: / // FIXME: → Código que necesita corrección# TEST: / // TEST: → Solo para testing📋 IMPORTANTE: Ver guía completa de limpieza en .github/instructions/code-clean.instructions.md
layout.html<nav aria-label="breadcrumb">
<ol class="breadcrumb">
<li class="breadcrumb-item"><a href="{{ url_for('index') }}">Inicio</a></li>
<li class="breadcrumb-item"><a href="{{ url_for('appointment_list') }}">Citas</a></li>
<li class="breadcrumb-item active">Detalle</li>
</ol>
</nav>
<i class="bi bi-*">)window.ServiceForm = (function(){
// ... funciones privadas
return {
publicFunction1,
publicFunction2
};
})();
addEventListener() en lugar de onclick inlineAntes de Producción Eliminar:
console.log(), console.debug(), console.warn() temporalesalert() de testing// TODO, // DEBUG, // FIXME, // TEMP, // TESTdata-* de debuggingPatrón CRUD estándar:
@app.route('/entity') # GET - Listar (con filtros opcionales)
@app.route('/entity/new') # GET - Formulario crear
@app.route('/entity/create', POST) # POST - Procesar creación (deprecated: usar /new POST)
@app.route('/entity/<id>') # GET - Ver detalle
@app.route('/entity/<id>/edit') # GET - Formulario editar
@app.route('/entity/<id>/update', POST) # POST - Procesar actualización
@app.route('/entity/<id>/delete', POST) # POST - Eliminar (con confirmación)
Patrón moderno preferido (reducir rutas):
@app.route('/entity', methods=['GET']) # Listar
@app.route('/entity/new', methods=['GET','POST']) # Crear (form + procesar)
@app.route('/entity/<id>') # Ver
@app.route('/entity/<id>/edit', methods=['GET','POST']) # Editar (form + procesar)
@app.route('/entity/<id>/delete', methods=['POST']) # Eliminar
Ejemplo real del proyecto:
@app.route('/appointments/<int:id>/edit', methods=['GET', 'POST'])
@login_required
def appointment_edit(id: int):
"""Edita una cita existente.
Restricción: No permite editar citas con factura generada.
"""
appointment = Appointment.query.get_or_404(id)
# Validación de permisos/estado
if appointment.invoice_id:
flash('No se puede editar una cita que ya tiene factura generada', 'error')
return redirect(url_for('appointment_view', id=id))
if request.method == 'POST':
try:
# Procesar actualización
# ... lógica de negocio
db.session.commit()
flash('Cita actualizada exitosamente', 'success')
return redirect(url_for('appointment_view', id=id))
except Exception as e:
db.session.rollback()
app.logger.error(f"Error actualizando cita: {e}")
flash('Error al actualizar la cita', 'error')
# GET - Mostrar formulario
return render_template('appointments/edit.html',
appointment=appointment,
service_types=ServiceType.query.filter_by(is_active=True).all())
Patrón de timestamps:
class BaseModel(db.Model):
__abstract__ = True
created_at = db.Column(db.DateTime, default=lambda: datetime.now(CO_TZ))
updated_at = db.Column(db.DateTime, default=lambda: datetime.now(CO_TZ),
onupdate=lambda: datetime.now(CO_TZ))
Relaciones estándar:
class Appointment(db.Model):
id = db.Column(db.Integer, primary_key=True)
customer_id = db.Column(db.Integer, db.ForeignKey('customer.id'))
pet_id = db.Column(db.Integer, db.ForeignKey('pet.id'))
# Relaciones con backref
customer = db.relationship('Customer', backref='appointments')
pet = db.relationship('Pet', backref='appointments')
# Relación uno a muchos
services = db.relationship('PetService', backref='appointment',
lazy='dynamic', cascade='all, delete-orphan')
Métodos útiles:
class Appointment(db.Model):
# ...
def recompute_total(self):
"""Recalcula el total de la cita basado en sus servicios."""
self.total_price = sum(s.price or 0 for s in self.services)
self.total_services = self.services.count()
def to_dict(self):
"""Serializa el modelo a diccionario para JSON."""
return {
'id': self.id,
'customer': self.customer.name if self.customer else None,
'pet': self.pet.name if self.pet else None,
'total': float(self.total_price or 0),
'status': self.status
}
Sistema de logs de inventario (implementado):
class ProductStockLog(db.Model):
"""Registra todos los movimientos de inventario para trazabilidad."""
id = db.Column(db.Integer, primary_key=True)
product_id = db.Column(db.Integer, db.ForeignKey('product.id'), nullable=False)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
quantity = db.Column(db.Integer, nullable=False) # Valor absoluto
movement_type = db.Column(db.String(20), nullable=False) # 'addition' o 'subtraction'
reason = db.Column(db.Text, nullable=False) # Razón obligatoria
previous_stock = db.Column(db.Integer, nullable=False)
new_stock = db.Column(db.Integer, nullable=False)
created_at = db.Column(db.DateTime, default=lambda: datetime.now(CO_TZ))
product = db.relationship('Product', backref='stock_logs')
user = db.relationship('User', backref='stock_changes')
Sistema de códigos alternativos (implementado Nov 2025):
class ProductCode(db.Model):
"""Códigos alternativos de productos para soportar consolidación.
Permite que un producto tenga múltiples códigos (EAN, SKU, códigos legacy)
manteniendo el código principal en Product.code.
Tipos de código (code_type):
- 'alternative': Código alternativo genérico
- 'legacy': Código de producto consolidado
- 'barcode': Código de barras (EAN, UPC)
- 'supplier_sku': SKU del proveedor
"""
id = db.Column(db.Integer, primary_key=True)
product_id = db.Column(db.Integer, db.ForeignKey('product.id', ondelete='CASCADE'), nullable=False)
code = db.Column(db.String(20), unique=True, nullable=False, index=True)
code_type = db.Column(db.String(20), default='alternative', nullable=False)
created_at = db.Column(db.DateTime, default=datetime.utcnow)
created_by = db.Column(db.Integer, db.ForeignKey('user.id'))
notes = db.Column(db.Text)
# Relaciones
product = db.relationship('Product', backref=db.backref('alternative_codes',
lazy='dynamic', cascade='all, delete-orphan'))
user = db.relationship('User')
# Métodos en Product para códigos alternativos
def get_all_codes(self):
"""Retorna lista de todos los códigos del producto."""
codes = [{'code': self.code, 'type': 'principal', 'is_primary': True}]
codes.extend([{'code': ac.code, 'type': ac.code_type, 'is_primary': False}
for ac in self.alternative_codes.all()])
return codes
@staticmethod
def search_by_any_code(code_query):
"""Busca producto por código principal o alternativo."""
product = Product.query.filter_by(code=code_query).first()
if not product:
alt_code = ProductCode.query.filter_by(code=code_query).first()
if alt_code:
return alt_code.product
return product
Decoradores de autorización:
from functools import wraps
def admin_required(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if not current_user.is_authenticated or current_user.role != 'admin':
flash('Acceso denegado. Requiere permisos de administrador.', 'error')
return redirect(url_for('index'))
return f(*args, **kwargs)
return decorated_function
# Uso:
@app.route('/settings')
@login_required
@admin_required
def settings():
# Solo admins
pass
Roles del sistema:
admin: Acceso total, configuración, reportesvendedor: Ventas, inventario (solo lectura de productos), clientesHasheo de contraseñas:
from werkzeug.security import generate_password_hash, check_password_hash
# Al crear usuario
user.password_hash = generate_password_hash(password)
# Al validar login
if check_password_hash(user.password_hash, password):
login_user(user)
Setting con campo next_invoice_numbercash, transfer, card, mixedInvoice.appointment_id (opcional, puede ser venta directa)InvoiceItem con productos/serviciosFlujo de facturación desde citas:
donedoneSistema de logs implementado:
ProductStockLogEjemplo de uso:
# Al editar producto y cambiar stock
if new_stock != old_stock:
reason = request.form.get('stock_reason', '').strip()
if not reason:
flash('Debe proporcionar una razón para el cambio de stock', 'error')
return render_template(...)
# Crear log
log = ProductStockLog(
product_id=product.id,
user_id=current_user.id,
quantity=abs(new_stock - old_stock),
movement_type='addition' if new_stock > old_stock else 'subtraction',
reason=reason,
previous_stock=old_stock,
new_stock=new_stock
)
db.session.add(log)
Características:
pending, done, cancelledpending y sin facturaFlujo completo:
1. Crear cita (/services/new)
- Seleccionar cliente y mascota
- Elegir servicios (tarjetas clickeables)
- Agregar notas y consentimiento
- Programar fecha/hora (opcional)
→ Guarda Appointment + PetService (sin Invoice)
2. Ver cita (/appointments/<id>)
- Información completa
- Notas y consentimiento
- Lista de servicios
- Botones de acción según estado
3. Editar cita (/appointments/<id>/edit)
- Solo si estado = pending
- Solo si NO tiene factura
- Misma UI que creación
- Puede agregar/quitar servicios
4. Finalizar cita (POST /appointments/<id>/finish)
- Genera Invoice automáticamente
- Asocia servicios a la factura
- Marca servicios como done
- Actualiza estado a done
→ Redirige a Invoice para cobro/impresión
5. Cancelar cita (POST /appointments/<id>/cancel)
- Solo si estado = pending
- Marca como cancelled
Modelo ServiceType:
fixed (fijo) o variableCRUD completo:
/services/types/config/services/types/new y /services/types/<id>/editImplementado en lista de citas:
<a href="https://wa.me/+57{{ phone_clean }}?text={{ mensaje }}"
class="btn btn-sm btn-outline-success"
target="_blank"
title="Confirmar cita por WhatsApp">
<i class="bi bi-whatsapp"></i>
</a>
Mensaje personalizado:
Hola [Nombre]!
Te saludamos desde *Pet Verde*
Recuerda la cita con nuestra groomer para *[Mascota]*
Fecha: 17/10/2025
Hora: 2:30 PM
Gracias por preferirnos!
try:
# operaciones
db.session.commit()
except Exception as e:
db.session.rollback()
app.logger.error(f"Error: {e}")
flash('Error al guardar', 'error')
app.dblazy='dynamic' en relaciones grandesjoinedload() cuando sea necesarioCRÍTICO:
scheduled_at en Appointment: Hora LOCAL (sin conversión)created_at, updated_at: Usar datetime.now(CO_TZ)strftime() directamenteEjemplo correcto:
# Crear cita con hora programada
appointment.scheduled_at = datetime.strptime(
f"{date_str} {time_str}",
'%Y-%m-%d %H:%M'
) # Sin timezone, es hora local
# Mostrar en template
{{ appointment.scheduled_at.strftime('%I:%M %p') }} # 2:30 PM
admin / admin123vendedor / vendedor123Cards para contenido agrupado:
<div class="card mb-3">
<div class="card-header bg-light">
<h5 class="mb-0">Título</h5>
</div>
<div class="card-body">
<!-- Contenido -->
</div>
<div class="card-footer text-end">
<button class="btn btn-primary">Guardar</button>
</div>
</div>
Tables responsive:
<div class="table-responsive">
<table class="table table-hover table-sm align-middle mb-0">
<thead>
<tr>
<th>Columna</th>
</tr>
</thead>
<tbody>
<tr>
<td>Dato</td>
</tr>
</tbody>
</table>
</div>
Modals para CRUD rápido:
<!-- Modal de eliminación -->
<div class="modal fade" id="deleteModal" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Confirmar Eliminación</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal"></button>
</div>
<div class="modal-body">
¿Está seguro de eliminar este registro?
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancelar</button>
<form method="post" action="{{ url_for('entity_delete', id=item.id) }}">
<button type="submit" class="btn btn-danger">Eliminar</button>
</form>
</div>
</div>
</div>
</div>
Agrupación por fecha (patrón usado en invoices y appointments):
{% for date, items in items_by_date.items() %}
<div class="card mb-4">
<div class="card-header bg-light">
<h5 class="mb-0">
<button class="btn btn-link collapsed" data-bs-toggle="collapse"
data-bs-target="#collapse-{{ loop.index }}">
<span class="formatted-date" data-date="{{ date }}">{{ date }}</span>
<i class="bi bi-chevron-down collapse-icon"></i>
</button>
<small class="text-muted ms-2">
({{ items|length }} items)
<span class="ms-2">Total: {{ items|sum(attribute='total')|currency_co }}</span>
</small>
</h5>
</div>
<div id="collapse-{{ loop.index }}" class="collapse{{ ' show' if loop.index == 1 }}">
<div class="card-body p-0">
<div class="table-responsive">
<table class="table table-hover table-sm align-middle mb-0">
<!-- Tabla de items -->
</table>
</div>
</div>
</div>
</div>
{% endfor %}
Acciones estándar:
bi-plus-circle (verde)bi-pencil-square (amarillo/naranja)bi-trash (rojo)bi-eye (azul)bi-savebi-arrow-leftbi-gearbi-whatsapp (verde)bi-receipt-cutoffbi-printerEstados con iconos:
{% if appointment.status == 'done' %}
<i class="bi bi-check-circle-fill text-success" title="Finalizada"></i>
{% elif appointment.status == 'cancelled' %}
<i class="bi bi-x-circle-fill text-danger" title="Cancelada"></i>
{% else %}
<i class="bi bi-hourglass-split text-secondary" title="Pendiente"></i>
{% endif %}
Colores semánticos:
Validación HTML5 + JavaScript:
<form method="post" novalidate>
<div class="mb-3">
<label for="name" class="form-label">Nombre <span class="text-danger">*</span></label>
<input type="text" class="form-control" id="name" name="name" required>
<div class="invalid-feedback">
Este campo es requerido
</div>
</div>
<div class="mb-3">
<label for="stock" class="form-label">Existencias</label>
<input type="number" class="form-control" id="stock" name="stock" min="0">
</div>
<button type="submit" class="btn btn-primary">
<i class="bi bi-save"></i> Guardar
</button>
</form>
Campo de razón para cambios de stock (implementado):
<div id="stockReasonGroup" class="mb-3" style="display: none;">
<label for="stock_reason" class="form-label">
Razón del Cambio de Stock <span class="text-danger">*</span>
</label>
<textarea class="form-control" id="stock_reason" name="stock_reason" rows="3"
placeholder="Ej: Nueva compra factura #1234 del proveedor Italcol - 20/10/2025"></textarea>
<small class="text-muted">
Este cambio quedará registrado en el historial de inventario
</small>
</div>
<script>
const originalStock = {{ product.stock if product else 0 }};
document.getElementById('stock').addEventListener('input', function() {
const newStock = parseInt(this.value) || 0;
const reasonGroup = document.getElementById('stockReasonGroup');
if (newStock !== originalStock) {
reasonGroup.style.display = 'block';
document.getElementById('stock_reason').required = true;
} else {
reasonGroup.style.display = 'none';
document.getElementById('stock_reason').required = false;
}
});
</script>
@app.route('/api/customers/search')
def api_customers_search():
"""Búsqueda de clientes para autocompletado."""
q = request.args.get('q', '')
customers = Customer.query.filter(
Customer.name.ilike(f'%{q}%')
).limit(10).all()
return jsonify([c.to_dict() for c in customers])
@app.route('/api/products/search')
def api_products_search():
"""Búsqueda de productos por nombre o código."""
# Similar a customers
pass
@app.route('/api/dashboard/stats')
@login_required
def api_dashboard_stats():
"""Estadísticas del dashboard en JSON."""
return jsonify({
'sales_today': total_sales,
'pending_appointments': pending_count,
'low_stock_products': low_stock_count
})
/ - Dashboard con estadísticas/customers - Gestión de clientes/customers/<id>/pets - Mascotas del cliente/products - Gestión de inventario/products/<id>/stock-history - Historial de movimientos (nuevo)/invoices - Facturación con agrupación por fecha/services - Redirige a appointments/appointments - Sistema de citas agrupadas por fecha/appointments/<id>/edit - Edición de cita/appointments/<id>/finish - Finalizar y generar factura/services/types/config - Configuración de tipos de servicio/reports - Módulo de reportes y análisis de ventas (nuevo)/settings - Configuración del negocio (admin only)/invoices/<id>/print - PDF de factura (ReportLab)window.print() en /appointments/<id>Logs permitidos en desarrollo:
# DEBUG: solo en desarrollo
print(f"Debug: appointment = {appointment.to_dict()}")
app.logger.debug(f"Services count: {len(services)}")
Logs requeridos en producción:
# Errores críticos
app.logger.error(f"Error al crear factura: {str(e)}")
# Acciones de seguridad
app.logger.warning(f"Intento de acceso denegado: {current_user.username}")
# Transacciones importantes
app.logger.info(f"Factura {invoice.number} creada por {current_user.username}")
Flash messages para feedback:
flash('Cita creada exitosamente', 'success')
flash('No se puede editar una cita con factura', 'error')
flash('Campo requerido: razón del cambio de stock', 'warning')
flash('Producto actualizado', 'info')
Console logs en JavaScript:
// DEBUG: solo en desarrollo
console.log("Debug: selected services =", selectedServices);
// NUNCA en producción
// console.log(), alert(), debugger
OBLIGATORIO antes de deploy:
# Buscar todos los prints temporales
grep -rn "print(" --include="*.py" app.py
# Buscar console.log
grep -rn "console\.log\|console\.debug" --include="*.js" static/
# Buscar marcadores de debugging
grep -rn "# DEBUG\|# TODO\|# TEMP\|# FIXME\|# TEST" --include="*.py" .
grep -rn "// DEBUG\|// TODO\|// TEMP\|// FIXME\|// TEST" --include="*.js" .
# ELIMINAR:
# old_function() # TODO: eliminar deprecated
# if debug_mode: # DEBUG: lógica temporal
# ELIMINAR:
import pdb # DEBUG: breakpoint library
from pprint import pprint # TEMP: debugging
# ELIMINAR:
debug_var = "test" # TEMP
test_data = [] # TEST
// ELIMINAR:
console.log("Debug info"); // DEBUG
// alert("Test"); // TEST
debugVar = "test"; // TEMP
<!-- ELIMINAR comentarios de debugging -->
<!-- DEBUG: verificar este valor -->
<!-- TODO: mejorar este diseño -->
# Windows
.\run.ps1
# O con Waitress
python -m waitress --listen=127.0.0.1:5000 app:app
Servidor WSGI: Waitress
# run.py
from waitress import serve
from app import app
if __name__ == '__main__':
serve(app, host='0.0.0.0', port=5000, threads=4)
Variables de entorno (.env):
FLASK_ENV=production
SECRET_KEY=your-secret-key-here
DATABASE_URL=sqlite:///instance/app.db
Servicio Windows con NSSM:
nssm install GreenPOS "C:\Python313\python.exe" "D:\Path\run.py"
nssm set GreenPOS AppDirectory "D:\Path\Green-POS"
nssm start GreenPOS
Backup automático:
# Script PowerShell para backup diario
Copy-Item "D:\Path\instance\app.db" "D:\Backups\app_$(Get-Date -Format 'yyyyMMdd').db"
Python/Backend:
print() temporales (buscar # DEBUG:)app.logger.debug() no esenciales# TODO, # DEBUG, # TEMP, # FIXME, # TESTpdb, pprint con marcadoresdebug_var, test_data marcadas # TEMP:# old_function() con # TODO:def test_*() con # TEST:Frontend/JavaScript:
console.log(), console.debug(), console.warn() con // DEBUG:alert() de testing con // TEST:// TODO, // DEBUG, // FIXME, // TEMP, // TEST// TEMP:// TEST:debugger; statementsTemplates/HTML:
<!-- DEBUG: -->display: none de testingdata-debug-*Configuración:
SECRET_KEY generado aleatoriamenteFLASK_ENV=productionComandos de Verificación:
# Python
grep -rn "# DEBUG\|# TODO\|# TEMP\|# FIXME\|# TEST" --include="*.py" .
grep -rn "print(" --include="*.py" app.py models/
# JavaScript
grep -rn "// DEBUG\|// TODO\|// TEMP\|// FIXME\|// TEST" --include="*.js" .
grep -rn "console\.log\|console\.debug\|debugger" --include="*.js" static/
# Templates
grep -rn "<!-- DEBUG\|<!-- TODO\|<!-- TEMP" --include="*.html" templates/
SOLO mantener logs de:
app.logger.error()Ejemplo de log productivo:
# ✅ MANTENER
app.logger.error(f"Error al generar factura {invoice.id}: {str(e)}")
app.logger.info(f"Factura {invoice.number} creada por {current_user.username}")
app.logger.warning(f"Acceso denegado a /settings por usuario {current_user.username}")
# ❌ ELIMINAR
print(f"Debug: servicios = {services}") # DEBUG
app.logger.debug(f"Valor de variable x: {x}") # DEBUG
Problema: Pegar archivos enormes completos esperando que la IA "entienda" todo automáticamente.
Por qué falla:
❌ Incorrecto:
# Usuario pega TODO el archivo app.py (1500+ líneas)
# "Ayúdame a debuggear este código"
✅ Correcto:
# Usuario comparte solo el método relevante con contexto:
"""
Tengo un error en la ruta product_edit() cuando cambio el stock.
El ProductStockLog no se está creando.
Contexto:
- product_edit() está en app.py líneas 355-402
- ProductStockLog modelo está en models/models.py líneas 276-295
- Relación: Product tiene backref 'stock_logs'
Aquí está el método que falla:
[código específico del método con 20-30 líneas]
"""
Regla de Oro:
Problema: Asumir que la IA "ya sabe" tu arquitectura, convenciones o decisiones previas.
Por qué falla:
❌ Incorrecto:
Usuario: "Actualiza el appointment para que valide el status"
IA: No sabe qué validaciones específicas necesitas
✅ Correcto:
Usuario: "En Green-POS, Appointment tiene campo 'status' con valores:
- 'pending': puede editarse
- 'done': inmutable, tiene factura asociada
- 'cancelled': inmutable
Quiero agregar validación en appointment_edit() para que:
1. Si status='done' Y existe invoice_id → mostrar error
2. Si status='cancelled' → mostrar error
3. Si status='pending' → permitir edición normal
Patrón usado: State Pattern (ver copilot-instructions.md línea 650)"
Regla de Oro:
appointment, invoice, status)Problema: Crear archivo de instrucciones una vez y nunca actualizarlo a medida que el proyecto evoluciona.
Por qué falla:
❌ Incorrecto:
# copilot-instructions.md creado hace 6 meses
# Proyecto ahora usa:
# - Nuevo patrón de validación de stock
# - Sistema de logs de inventario
# - Zona horaria CO_TZ
# Pero instrucciones NO reflejan estos cambios
✅ Correcto:
# Actualizar copilot-instructions.md en cada milestone:
- Nueva feature implementada → documentar patrón usado
- Cambio arquitectónico → actualizar sección de constraints
- Bug fix importante → agregar a "Lessons Learned"
Ejemplo de actualización:
"## Sistema de Trazabilidad de Inventario (Oct 2025)
- Implementado modelo ProductStockLog
- Campo obligatorio stock_reason al cambiar existencias
- Validación backend + frontend
- Ver: app.py líneas 355-402"
Regla de Oro:
Problema: Usar el mismo nivel de contexto para debugging, features nuevas y análisis de código.
Por qué falla:
❌ Incorrecto:
# Mismo prompt genérico para todo:
"Revisa este código y dime si está bien"
✅ Correcto - Debugging:
"DEBUGGING: Error en product_edit() al guardar ProductStockLog
Síntomas:
- No se crea registro en stock_logs
- No hay error en consola
- Stock del producto SÍ se actualiza
Contexto técnico:
- app.py líneas 380-395 (creación de log)
- db.session.add(log) ejecutándose
- Relación: Product.stock_logs (backref)
Stack trace: [pegar error completo si existe]
Logs: [pegar líneas relevantes de app.log]
Pregunta: ¿Por qué no se persiste el log?"
✅ Correcto - Feature Nueva:
"FEATURE: Sistema de descuentos en facturas
Requisitos de negocio:
- Descuento % o valor fijo por factura
- Aplicable a total antes de IVA
- Razón obligatoria si descuento > 10%
- Solo admin puede aplicar
Restricciones:
- Invoice modelo ya existe (models.py línea 200)
- Usar patrón State para validar aplicación
- Frontend: Bootstrap 5, campo con validación
Pregunta: ¿Cómo estructuro el modelo y la lógica?"
✅ Correcto - Análisis Arquitectónico:
"ANÁLISIS: Evaluar migración de SQLite a PostgreSQL
Contexto actual:
- 50 usuarios concurrentes
- 1000 facturas/mes
- SQLite con timeouts ocasionales
- Backups manuales diarios
Necesito:
1. Pros/contras de migración
2. Cambios requeridos en código
3. Plan de migración sin downtime
4. Estimación de esfuerzo
Ver constraints: copilot-instructions.md líneas 20-100"
Regla de Oro:
Problema: Tener múltiples archivos con reglas contradictorias o redundantes en diferentes lugares.
Por qué falla:
❌ Incorrecto:
Proyecto tiene:
- README.md: "Usamos Bootstrap 4"
- copilot-instructions.md: "Bootstrap 5.3+ sin jQuery"
- CONTRIBUTING.md: "Puedes usar jQuery si quieres"
→ Inconsistencia total
✅ Correcto:
# .github/copilot-instructions.md (FUENTE CANÓNICA)
## Stack Tecnológico Principal
- Frontend: Bootstrap 5.3+ (sin jQuery) + Vanilla JavaScript
- Backend: Flask 3.0+ + SQLAlchemy
- Database: SQLite (dev) → PostgreSQL (prod)
# README.md (REFERENCIA A FUENTE)
## Tecnologías
Ver especificaciones técnicas completas en:
`.github/copilot-instructions.md`
Stack resumido:
- Flask 3.0+
- Bootstrap 5.3+
- SQLite/PostgreSQL
# CONTRIBUTING.md (REFERENCIA A FUENTE)
## Estándares de Código
Seguir guidelines en `.github/copilot-instructions.md`:
- Sección "Requisitos de Estilo de Código"
- Patrones de diseño implementados
- Constraints tecnológicos
Regla de Oro:
.github/copilot-instructions.mdProblema: Usar términos ambiguos que significan cosas diferentes según el contexto.
Por qué falla:
❌ Incorrecto:
# Código usa términos ambiguos sin aclarar
class Service(db.Model): # ¿Qué tipo de servicio?
pass
class Account(db.Model): # ¿Cliente o cuenta de usuario?
pass
# Usuario pregunta:
"Cómo creo un nuevo Service?"
# IA no sabe si hablas de PetService o ServiceType
✅ Correcto - Glosario de Dominio:
## 📖 Glosario de Dominio (Green-POS)
### Entidades Principales
**Customer (Cliente)**:
- Persona que trae mascotas para servicios
- Tiene: nombre, documento, teléfono, dirección
- Modelo: `Customer` (models.py línea 100)
- Relación: Un Customer tiene muchos Pets
**Pet (Mascota)**:
- Animal propiedad de un Customer
- Tiene: nombre, especie, raza, edad
- Modelo: `Pet` (models.py línea 130)
- Relación: Pet pertenece a Customer
**Appointment (Cita)**:
- Agendamiento de servicios para una Pet
- Tiene: fecha, hora, Customer, Pet, servicios, status
- Modelo: `Appointment` (models.py línea 200)
- Estados: 'pending', 'done', 'cancelled'
- Relación: Appointment tiene muchos PetService
**PetService (Servicio de Mascota)**:
- Instancia de un ServiceType aplicado en una Appointment
- Tiene: tipo, precio, notas
- Modelo: `PetService` (models.py línea 240)
- Relación: PetService pertenece a Appointment
**ServiceType (Tipo de Servicio)**:
- Catálogo de servicios ofrecidos (grooming, veterinaria)
- Tiene: nombre, código, precio base, duración
- Modelo: `ServiceType` (models.py línea 270)
- Modo precio: 'fixed' (fijo) o 'variable'
**Invoice (Factura)**:
- Documento de cobro por servicios/productos
- Tiene: número, fecha, total, método de pago
- Modelo: `Invoice` (models.py línea 180)
- Puede asociarse a Appointment (opcional)
**Product (Producto)**:
- Artículo de inventario vendible
- Tiene: código, nombre, precio, stock
- Modelo: `Product` (models.py línea 35)
**User (Usuario del Sistema)**:
- Empleado con acceso al sistema
- Roles: 'admin', 'vendedor'
- Modelo: `User` (models.py línea 250)
### Términos Técnicos
**Stock**: Cantidad de Product disponible en inventario
**Status**: Estado de Appointment ('pending', 'done', 'cancelled')
**Payment Method**: Método de pago ('cash', 'transfer', 'card', 'mixed')
**CO_TZ**: Timezone de Colombia (America/Bogota) usado en timestamps
### Anti-Patrón Común:
❌ "Agregar un service" → Ambiguo
✅ "Agregar un PetService a la Appointment" → Específico
✅ "Crear un ServiceType nuevo en catálogo" → Específico
Regla de Oro:
Problema: No especificar qué significa "terminado" para una tarea, causando implementaciones incompletas.
Por qué falla:
❌ Incorrecto:
Usuario: "Agrega un campo de email al Customer"
IA: Agrega solo el campo al modelo
Faltan: validación, unique constraint, migración, actualizar forms
✅ Correcto:
Usuario: "Agrega campo email al Customer con Definition of Done:
Modelo (models.py):
- Campo: email (String 120, nullable, unique)
- Validación: formato email válido
- Index en columna email
Ruta (app.py):
- Actualizar customer_edit() para incluir email
- Validación backend con regex
- Flash message si email duplicado
Template (customers/form.html):
- Input type="email" con validación HTML5
- Placeholder: ejemplo@dominio.com
- Campo opcional
Migración:
- Crear script de migración manual si necesario
- Default NULL para registros existentes
Documentación:
- Actualizar copilot-instructions.md en sección Customer
- Agregar a glosario de dominio
Testing:
- Validar creación con email válido
- Validar rechazo de email inválido
- Validar unique constraint"
Regla de Oro:
ESTADO: ✅ 100% COMPLETADO
app.py - Aplicación principal con Factory Pattern (201 líneas)config.py - Configuración por ambientesextensions.py - db, login_manager compartidosutils/ - filtros, decoradores, constantesroutes/ - 11 blueprints modularesdocs/archive/docs/CLEANUP_SUMMARY.md - Resumen completo de limpiezadocs/REFACTORING.md - Guía de refactorizaciónREADME.md - Actualizado con arquitectura de blueprintsReferencias Legacy (solo consulta histórica):
docs/archive/app.py.backup - Original monolítico (2107 líneas)docs/archive/app_old.py - Pre-limpiezaESTADO: ✅ 100% COMPLETADO
Sistema completo de consolidación de productos duplicados con soporte para múltiples códigos alternativos (EAN, SKU, códigos legacy).
1. Tabla ProductCode (Base de Datos):
product_code para códigos alternativos ilimitadosalternative, legacy, barcode, supplier_skucode, product_id, code_type para búsqueda eficientemigrations/migration_add_product_codes.py ✅2. Modelo ProductCode (models/models.py):
ProductCode con relación a Product (cascade delete)get_all_codes() - Retorna código principal + alternativossearch_by_any_code(code) - Busca por código principal o alternativoProduct.alternative_codes (lazy='dynamic')3. Script de Consolidación (migrations/merge_products.py):
merge_products(source_ids, target_id, user_id)4. Búsqueda Multi-Código (routes/products.py, routes/api.py):
outerjoin(ProductCode) para búsqueda en códigos alternativos/api/products/search?q=<query> con soporte multi-código.distinct() para evitar duplicados por join5. Interfaz de Consolidación (templates/products/merge.html):
/products/merge (solo admin)# Consolidar productos 101, 102, 103 en producto 100
from migrations.merge_products import merge_products
stats = merge_products(
source_product_ids=[101, 102, 103],
target_product_id=100,
user_id=1 # ID del usuario admin
)
# Retorna: {'invoice_items': 15, 'stock_logs': 8, 'stock_consolidated': 50, ...}
docs/research/2025-11-24-unificacion-productos-solucion-completa.mddocs/PRODUCT_SEARCH_ANALYSIS_MULTICODE.mdmigrations/migration_add_product_codes.sqlProductStockLog/products/<id>/stock-history para ver historialstock_reason al cambiar existencias/reports con filtros de fecha (start_date, end_date)(precio_venta - precio_compra) * cantidad por cada InvoiceItemÚltima actualización: 22 de octubre de 2025 Versión del proyecto: 2.0 Contacto: Sistema Green-POS - Pet Services Management
Este archivo se actualiza automáticamente en cada conversación de Copilot para proporcionar contexto consistente del proyecto.
Make Uncle Bob proud.
Prefer modern, idiomatic approaches for the language in use. Update idioms as you see them to align with current best practices (Boyscout Rule).
Type Clarity: Prioritize clear and explicit type declarations. For Go, prefer any over interface{}.
Standard Idioms and Tooling: Prefer standard idioms and approaches for the language in use. Leverage appropriate code generation tools when beneficial (e.g., go:generate for Go). For JavaScript, utilize tools like bun build for bundling and web-test-runner for testing.
Generated files should be committed to the repository. This ensures that developers can build and test the project without needing to have all code generation tools installed locally. Any files created or modified by go generate ./... should be included in commits.
prefer IoC approaches. Make *-er interfaces for all the things!
Avoid Parameter Objects and Config Structs: Don't bundle unrelated parameters into "Options", "Config", "Settings", or "Dependencies" structs. These become implicit global variables - shared spaces where unrelated concerns accumulate. Instead, pass explicit parameters to functions. This makes dependencies clear, prevents coupling between unrelated features, and avoids the "god object" anti-pattern.
Bad:
type Options struct {
Host string
Port int
Debug bool
Timeout time.Duration
// Grows over time with unrelated fields...
}
func SetupServer(opts Options) { ... }
Good:
func SetupServer(host string, port int) { ... }
func SetupServerWithTLS(host string, port int, tlsPort int, tlsConfig *tls.Config) { ... }
When a function needs many parameters, it's often a sign the function is doing too much. Consider breaking it into smaller, focused functions rather than hiding complexity behind a config struct.
Avoid Meaningless Names: Avoid generic, meaningless names like "Manager", "Handler", "Processor", "Service", "Util", or "Helper" unless they genuinely describe the specific purpose. These names are often cop-outs that don't convey meaningful information about what the type or function actually does. Instead, use descriptive names that clearly indicate the specific responsibility or behavior.
Bad Examples:
PageManager (vague - manages what about pages?)DataProcessor (vague - processes how?)RequestHandler (vague - handles how?)UserService (vague - what service?)Good Examples:
PageReaderMutator (specific - reads and mutates pages)
DataValidator (specific - validates data)
RequestRouter (specific - routes requests)
UserAuthenticator (specific - authenticates users)
Defensive Error Handling: Take a defensive coding approach. Check inputs, assert preconditions, and enforce invariants. For recoverable issues, prefer returning an error or throwing an exception rather than causing a program crash (panic). Crashes/panics should be reserved for truly exceptional and unrecoverable situations. This allows the caller to handle the problem more gracefully.
Go Example (Returning Error):
func MyFunction(input int) error {
if input < 0 {
return fmt.Errorf("input cannot be negative")
}
// ...
return nil
}
TypeScript Example (Throwing Exception):
function myFunction(input: number): boolean {
if (input < 0) {
throw new Error("Input cannot be negative");
}
return true;
}
devbox add <package>. This ensures the devbox.json and devbox.lock files are updated correctly.devbox shell (for an interactive shell) or devbox run <command> (for running specific commands) to work within the Devbox environment.devbox.json to run commands. Run devbox run to see a list of available scripts.static/js directory.vitest.config.js), and package management files (e.g., package.json, bun.lock).static/js directory.static/js (e.g., web-components, utils)..test.js suffix. For example, wiki-search.js should have its tests in wiki-search.test.js in the same directory.timeoutMs instead of timeout, delaySeconds instead of delay, heightPx instead of height. This makes the code self-documenting and prevents unit confusion.All web components use Lit (https://lit.dev/) for the component framework.
Use decorators for property declarations: Now that the codebase is fully TypeScript, use @property() and @state() decorators instead of static properties declarations. Decorators provide better IDE support, type inference, and are the standard Lit idiom for TypeScript projects.
Decorator import:
import { property, state } from 'lit/decorators.js';
Property declarations:
export class MyComponent extends LitElement {
// Public reactive properties
@property({ type: String })
declare title: string;
@property({ type: Boolean, reflect: true })
declare open: boolean;
@property({ type: Number })
declare count: number;
// Properties that don't reflect to attributes
@property({ attribute: false })
declare complexData: ComplexType;
// Internal reactive state
@state()
declare loading: boolean;
@state()
declare error: Error | null;
constructor() {
super();
// Initialize properties with defaults
this.title = '';
this.open = false;
this.count = 0;
this.loading = false;
this.error = null;
}
}
Key points:
@property() for public properties that can be set via HTML attributes@state() for internal state that triggers re-renders but isn't exposed as an attributedeclare keyword with decorator properties (required by TypeScript)reflect: true when the property value should be reflected back to the HTML attributeattribute: false for complex objects that shouldn't be serialized to attributesStorybook is used for developing and documenting UI components in isolation. Follow these principles when creating and maintaining Storybook stories:
ALWAYS use actual components: Stories must render the actual component, never create mock HTML structures that simulate the component's appearance.
Bad: Creating mock HTML divs to simulate a dialog component:
render: (args) => html`
<div style="position: fixed; inset: 0; background: rgba(0,0,0,0.5);">
<div style="background: white; border-radius: 8px;">
<h2>Fake Dialog Title</h2>
<p>Mock content that simulates the real component</p>
</div>
</div>
`;
Good: Using the actual component and setting its properties:
render: (args) => html`
<my-dialog-component .open="${args.open}" .loading="${true}">
</my-dialog-component>
`;
Mock data, not components: It's perfectly acceptable (and encouraged) to use mock data to populate components with realistic content. The distinction is:
Leverage component state: Components often have internal state properties that control loading, error, and other UI states. Set these properties directly in stories to demonstrate different visual states without requiring backend connections.
Test all component states: Create stories that demonstrate all major visual states of a component (loading, error, success, empty, etc.) by manipulating the component's properties.
title metadataargTypes for properties that users should be able to manipulate interactivelydevbox services workflow for seamless developmentdevbox run storybook to run Storybook standalonedevbox run storybook:build to build static Storybook filesCreate dedicated interactive testing stories that demonstrate:
InteractiveFormTesting, KeyboardShortcuts, ErrorRecoveryBind action loggers to all relevant events and verify event payloads:
@click=${action('event-name')} patternsProvide comprehensive documentation:
parameters.docs.description.storyExample Pattern:
export const InteractiveExample: Story = {
render: (args) => html`
<my-component @event=${action("event-triggered")}></my-component>
`,
parameters: {
docs: {
description: {
story: "Test component interactions. Open browser dev tools to see action logs."
}
}
}
};
Storybook is used for visual component exploration and manual interaction testing. Functional testing should be handled by the regular unit test suite.
Storybook should focus on visual and interactive aspects, while automated functional testing is handled by the project's comprehensive unit test suite.
Be Test-Driven. Write the test first, then write the code to make the tests pass.
When adding a new capability (function, method, component), follow a strict TDD workflow: This process is language-agnostic, and the Go examples below illustrate the key steps.
This ensures that code is written to meet specific, testable requirements from the start.
Example: Adding a Sum function.
Step 1: Create the skeleton function
// Sum adds two integers.
func Sum(a, b int) int {
return 0 // No-op implementation
}
Step 2: Write a failing test
// in sum_test.go
Describe("Sum", func() {
It("should add two numbers", func() {
Expect(Sum(2, 3)).To(Equal(5))
})
})
Running the test at this point will fail, as expected.
Step 3: Implement the function to pass the test
// Sum adds two integers.
func Sum(a, b int) int {
return a + b
}
This section outlines best practices for testing, applicable across different programming languages used in the project. The core principles emphasize test-driven development (TDD), clear test structure, and meaningful assertions.
Important: Never remove or skip tests without asking the user first. If tests are failing or seem problematic, discuss with the user before removing them. Instead of removing tests, prefer to fix the underlying code or abstract it to make it testable.
The application can be run locally using devbox services, which manages the development environment and builds the frontend code automatically.
Start the Application:
devbox services start
Stop the Application:
devbox services stop
The devbox services command uses the configuration defined in process-compose.yml to:
go generate ./... to build the frontend codego run main.goThis is the recommended way to run and test the application during development.
Alternatively, you can use:
devbox services up
to start the process manager with all services.
The wiki will be running at http://localhost:8050, and you can access the Structurizr Lite documentation at http://localhost:8080.
Tests for both frontend (JavaScript) and Go MUST be run using devbox scripts, ensuring a consistent environment.
Do not run them directly with npx, npm, bun, bunx, go test, etc. Use the provided scripts to ensure the setup is correct and that there are no environment issues causing false failures.
Frontend Tests (JavaScript):
To run all frontend tests:
devbox run fe:test
To run a single frontend test file, pass the path to the file as an argument. The script will automatically handle the static/js/ prefix if present:
devbox run fe:test -- <path_to_test_file>
For example:
devbox run fe:test -- static/js/web-components/error-display.test.ts
Or:
devbox run fe:test -- web-components/error-display.test.ts
Go Tests:
To run all Go tests:
devbox run go:test
Hanging or flaky async tests are common. The key is to ensure every asynchronous operation either resolves or rejects within a reasonable time. While a global test timeout is a good safety net, the following patterns help create more robust and predictable async tests.
This is the most frequent cause of hangs. If a component's setup code (e.g., in its connectedCallback) fetches data, the test will hang if the server is slow or unreachable.
Pattern: Use a library like sinon to intercept network requests and provide a fake, immediate response.
Example:
// In your test file
import { stub } from "sinon";
describe("My Component", () => {
let fetchStub;
beforeEach(async () => {
// Stub the global fetch function before the component is created
fetchStub = stub(window, "fetch");
// Make it resolve instantly with a fake response
fetchStub.resolves(
new Response(JSON.stringify({ id: 1, name: "Test Data" })),
);
// Now, when you create the component, it won't make a real network call
const el = await fixture(html`<my-component></my-component>`);
});
afterEach(() => {
// Clean up the stub after each test
fetchStub.restore();
});
});
If your component uses setTimeout, setInterval, or other time-based functions, waiting for them in real-time makes tests slow and fragile.
Pattern: Use sinon's fake timers to control the clock from your test.
Example:
import { useFakeTimers } from "sinon";
describe("My Timed Component", () => {
let clock;
beforeEach(() => {
// Take control of time
clock = useFakeTimers();
});
afterEach(() => {
// Give control back
clock.restore();
});
describe("when waiting 2 seconds", () => {
let el;
beforeEach(async () => {
// Arrange
el = await fixture(html`<my-timed-component></my-timed-component>`);
// Act - fast-forward the clock by 2 seconds instantly
await clock.tickAsync(2000);
});
it("should change state to loaded", () => {
// Assert
expect(el.state).to.equal("loaded");
});
});
});
Promise.race for Explicit TimeoutsRace your async setup operation against a timeout promise to pinpoint exactly which async operation is failing.
function timeout(ms: number, message: string): Promise<never> {
return new Promise((_, reject) =>
setTimeout(() => reject(new Error(message)), ms),
);
}
beforeEach(async () => {
el = await Promise.race([
fixture(html`<frontmatter-editor-dialog></frontmatter-editor-dialog>`),
timeout(3000, "Component fixture timed out"),
]);
});
Separate test assertions: Each it block should test one specific behavior. If a test description contains "and", it indicates the test is checking multiple behaviors and should be split into separate it blocks.
Bad: Testing multiple behaviors in one block.
it("should handle rejection events and prevent default", () => {
// This tests TWO behaviors: handling events AND preventing default
expect(() => rejectionHandler(mockRejectionEvent)).to.not.throw();
expect(preventDefaultStub).to.have.been.calledOnce;
});
Good: Split into separate, focused tests with actions in beforeEach.
interface MockEvent {
preventDefault: SinonStub;
}
describe("when handling rejection events", () => {
let preventDefaultStub: SinonStub;
let mockRejectionEvent: MockEvent;
let handlerResult: unknown;
beforeEach(() => {
preventDefaultStub = sinon.stub();
mockRejectionEvent = { preventDefault: preventDefaultStub };
handlerResult = rejectionHandler(mockRejectionEvent);
});
it("should not throw", () => {
expect(handlerResult).to.exist;
});
it("should prevent default", () => {
expect(preventDefaultStub).to.have.been.calledOnce;
});
});
No Actions in It Blocks: All setup (Arrange) and execution (Act) should be in beforeEach blocks within describe or when blocks. It blocks should only contain assertions (Assert). This allows reusing context for multiple assertions.
Good Pattern:
describe("when component is connected to DOM", () => {
let addEventListenerSpy: SinonSpy;
let el: WikiSearchElement;
beforeEach(async () => {
addEventListenerSpy = sinon.spy(window, "addEventListener");
el = await fixture(html`<wiki-search></wiki-search>`);
});
it("should add keydown event listener", () => {
expect(addEventListenerSpy).to.have.been.calledWith("keydown", el._handleKeydown);
});
});
Capture Test Data in BeforeEach: When you need to capture data that results from actions (like log output, response data, or computed values), always capture it in the BeforeEach block after the action is performed, not in the It blocks. Declare the variable in the scope above so multiple It blocks can access it for different assertions.
Bad: Capturing data inside the It block
It("should log the error", func() {
logOutput := logBuffer.String() // Action inside It block
Expect(logOutput).To(ContainSubstring("error message"))
})
Good: Capturing data in BeforeEach after action
When("action is performed", func() {
var logOutput string
var logBuffer *bytes.Buffer
BeforeEach(func() {
// ... setup and action ...
performAction()
// Capture result data after action
logOutput = logBuffer.String()
})
It("should log the error", func() {
Expect(logOutput).To(ContainSubstring("error message"))
})
It("should include error level", func() {
Expect(logOutput).To(ContainSubstring("ERROR"))
})
})
When asserting an error, check for the specific error type or message. Do not just check that an error is not nil. This ensures that the test is validating the specific error that is expected to be returned.
Bad: (Go example)
Expect(err).To(HaveOccurred())
Good: (Go example)
Expect(err).To(MatchError("specific error message"))
Use the Describe blocks first to describe the function/component being tested, then use nested When blocks to establish the scenarios. Besides the basic It(text: "Should exist" tests, everything should be in those nested "When" blocks.
Important: Use "when" in describe block descriptions to establish scenarios, not in it block descriptions. The it blocks should describe the expected behavior or outcome.
Bad:
it("should close when clicking outside", () => {
// test code
});
Good:
describe("when clicking outside", () => {
beforeEach(() => {
// setup and action
});
it("should close the popover", () => {
// assertion only
});
});
When to Use "when" in Describe Blocks: Use "when" only to establish scenarios or conditions (when the source Error has a stack), not to describe features (when preserving original error stack). For features, omit "when" (delegating to original error properties).
Event Handler Wiring Tests: For web components that add/remove event listeners, always test that the event handlers are properly wired up. Use spies to verify that addEventListener and removeEventListener are called with the correct parameters and function references.
Example:
describe("when component is connected to DOM", () => {
let addEventListenerSpy: SinonSpy;
let el: MyComponent;
beforeEach(async () => {
addEventListenerSpy = sinon.spy(document, "addEventListener");
el = await fixture(html`<my-component></my-component>`);
await el.updateComplete;
});
it("should add event listener with correct parameters", () => {
expect(addEventListenerSpy).to.have.been.calledWith("click", el._handleClick);
});
});
This ensures the event listeners are properly registered and prevents memory leaks from incorrectly bound functions.
Comprehensive Testing: Tests should validate the entire user-facing functionality, not just internal implementation details. When unit tests are green, we should be confident the whole app works. For example, when testing a search component, verify not only that results are processed correctly but also that the results view component becomes visible to the user.
No CSS-Only Testing: Tests should not assert that specific CSS properties are applied unless it's for functional reasons (e.g., verifying visibility changes). Avoid testing computed styles like getComputedStyle(element).property unless the test verifies functional behavior that depends on that styling. Focus tests on component behavior, state management, event handling, and user interaction rather than visual styling details.
Avoid Double-Entry Testing: Don't test simple declarations or property assignments that just mirror the code being tested. Focus tests on behavior and logic, not on verifying that properties exist or have been set to specific values that are obvious from the declaration.
Bad: Testing a declaration
it("should have errorKind property", () => {
expect(augmented.errorKind).to.equal(ErrorKind.WARNING);
});
Good: Testing behavior that depends on the property
it("should display warning icon for WARNING errorKind", () => {
expect(AugmentErrorService.getIconString(augmented.icon)).to.equal("⚠️");
});
Include a blank line between all the various Ginkgo blocks. This makes it easier to read the tests.
Prefer Ginkgo/Gomega for testing in Go. The "No Actions in It Blocks" rule applies here too:
Describe("a component", func() {
When("in a certain state", func() {
var result string
var err error
BeforeEach(func() {
result, err = component.DoSomething()
})
It("should not error", func() {
Expect(err).NotTo(HaveOccurred())
})
It("should return expected result", func() {
Expect(result).To(Equal("expected result"))
})
})
})
Follow these modern, correct patterns for consistent error handling:
Action: WRAP & RETURN. Add context. Never log.
return fmt.Errorf("context: %w", err)
Action: CHECK, ACT, & LOG ONCE.
How to Check:
Sentinel Error Pattern: Check for a known error value.
if errors.Is(err, ErrNotFound) { /* Act */ }
Custom Error Type Pattern: Check for and extract a specific error type.
if errors.As(err, &myErr) { /* Act on myErr data */ }
How to Log:
log.Printf("error: %v", err) (Use %v for the full chain)Never use panic() in library code, service functions, or handlers. Always return errors instead.
main.go (e.g., essential configuration missing at startup)(result, error) - let the caller decide how to handle failures(*T, error) and validate required dependencies, not panic on nilPanics are acceptable for asserting internal invariants that should never be violated during normal operation. These indicate programming bugs, not runtime errors. Use clear comments to document the invariant:
// INVARIANT ASSERTION: This function must be called while holding mu lock.
// Panic is intentional here to catch programming bugs during development.
if c.mu.TryLock() {
c.mu.Unlock()
panic("function called without holding mu lock - this is a programming bug")
}
Bad:
func NewServer(logger *Logger) *Server {
if logger == nil {
panic("logger is required") // Crashes the program
}
return &Server{logger: logger}
}
Good:
func NewServer(logger *Logger) (*Server, error) {
if logger == nil {
return nil, errors.New("logger is required")
}
return &Server{logger: logger}, nil
}
Do not obfuscate errors. When a function returns an error, inspect it to return an appropriate error to the caller. Do not wrap it in a generic error that hides the original cause or assumes a specific failure mode that may not be true. For example, if a read operation fails, don't automatically assume the file was "not found" if the underlying error could be something else, like a permissions issue.
Bad:
// This is bad because it assumes any error from ReadFrontMatter means "not found".
_, _, err := s.PageReadWriter.ReadFrontMatter(req.Page)
if err != nil {
return nil, status.Errorf(codes.NotFound, "page not found: %s", req.Page)
}
Good:
// This is better. We check for a specific error type and handle it,
// falling back to a more general error for unexpected cases.
_, _, err := s.PageReadWriter.ReadFrontMatter(req.Page)
if err != nil {
if os.IsNotExist(err) {
return nil, status.Errorf(codes.NotFound, "page not found: %s", req.Page)
}
return nil, status.Errorf(codes.Internal, "failed to read frontmatter: %v", err)
}
Be Explicit with Error State: When handling errors, explicitly set all relevant state variables to make the error handling path clear and obvious. Even if variables have default values, explicitly setting them improves code readability and prevents confusion about the intended state.
Bad:
// Implicit error state - success defaults to false but it's not clear
if err := operation(); err != nil {
logger.Error("Operation failed: %v", err)
message = "Operation failed"
// success remains false by default, but this is not obvious
} else {
message = "Success"
success = true
}
Good:
// Explicit error state - clearly shows intention for both paths
if err := operation(); err != nil {
logger.Error("Operation failed: %v", err)
message = "Operation failed"
success = false // Explicitly set to make error handling clear
} else {
message = "Success"
success = true
}
If a problem is due to an invalid parameter, don't just fix the parameter value. also add an input validation to the function/method receiving the parameter such that the error being fixed is perfectly clear to the next developer.
Do not use recover to hide panics. A panic indicates a serious bug that should crash the program during development and be fixed. Catching panics in handlers can obfuscate the problem and make debugging difficult. Instead, write defensive code to prevent panics in the first place, for example by checking for nil.
Never Branch Logic on Error Messages: Error messages are intended for human consumption and should never be used for conditional logic or control flow. Use proper error types, error codes, or structured error objects instead.
Bad (TypeScript):
try {
await client.getFrontmatter(request);
} catch (err: unknown) {
if (err instanceof Error && err.message.includes("UNAVAILABLE")) {
this.error = "Unable to connect to server";
} else if (err instanceof Error && err.message.includes("PERMISSION_DENIED")) {
this.error = "Access denied";
}
}
Good (TypeScript):
import { ConnectError, Code } from "@connectrpc/connect";
try {
await client.getFrontmatter(request);
} catch (err: unknown) {
if (err instanceof ConnectError) {
switch (err.code) {
case Code.Unavailable:
this.error = "Unable to connect to server";
break;
case Code.PermissionDenied:
this.error = "Access denied";
break;
default:
this.error = "An unexpected error occurred";
}
}
}
This approach ensures that:
Never Just Log Errors: Console logging (e.g., console.error, console.warn) is never sufficient error handling. Errors must always become part of control flow and be communicated to the user through the UX. Logging alone hides problems from users and makes the application appear to work when it's actually broken.
Bad:
try {
await saveData();
} catch (err) {
console.error('Save failed:', err);
// User has no idea the save failed
}
Good:
try {
await saveData();
} catch (err) {
this.error = err instanceof Error ? err : new Error(String(err));
// Error is visible to user in the UI via this.error.message in template
}
For cleanup operations where UI feedback isn't possible (e.g., disconnecting resources), let errors propagate or handle them silently - but never add console logging as a compromise.
Never Invent Opaque Error Strings: Setting this.error = "Some generic message" is an antipattern that discards valuable error information. Errors are inherently unknown at catch time - preserve the original error and let it bubble to the UX edge. At the edge, display the actual error or use an error service that preserves context.
Bad:
} catch {
this.error = 'Search failed. Please try again.';
// Original error is lost - was it network? Permission? Server error?
}
Good:
} catch (err) {
// Preserve the actual error - let error display component handle it
this.error = err;
// Or use an error service that augments while preserving
this.augmentedError = ErrorService.augment(err, 'search');
}
The UX component at the edge should handle displaying errors appropriately while preserving the ability to inspect the original error for debugging.
Keep Errors as Objects Until the UI Edge: Error properties in components should be typed as Error | null, not string. The Error object preserves stack traces, cause chains, and type information for debugging. Convert to string only at render time in templates.
Property declaration:
declare error: Error | null; // Not string!
Assignment (preserve the full Error object):
try {
await someAsyncOperation();
} catch (err) {
this.error = err instanceof Error ? err : new Error(String(err));
}
Template (extract message at UI edge):
${this.error ? html`<div class="error-message">${this.error.message}</div>` : ''}
This pattern ensures error context is available throughout the data layer for logging and debugging, while presenting a clean message to users at the point of display.
Let Unrecoverable Errors Bubble Up: Don't catch exceptions you can't meaningfully handle. Let them bubble to the global error handler for consistent user experience.
Bad: Catching without meaningful recovery
class SomeComponent {
async loadData() {
try {
await this.client.getData();
} catch (err: unknown) {
console.error('Load failed:', err);
// No user feedback, no retry - just hiding the error
}
}
}
Good: Only catch when you can provide recovery
interface ProcessedError {
message: string;
details?: string;
}
class SomeComponent {
async loadData(): Promise<void> {
try {
this.loading = true;
this.error = undefined;
await this.client.getData();
} catch (err: unknown) {
// Can provide user feedback and retry mechanism
this.error = ErrorService.processError(err, 'load data');
this.showRetryButton = true;
} finally {
this.loading = false;
}
}
// User can retry - this is meaningful recovery
async retry(): Promise<void> {
await this.loadData();
}
}
Never Hide Broken Functionality: Do not make systems appear to work when they are actually broken. This includes:
Bad (TypeScript):
function formatTimestamp(timestamp?: Timestamp): string {
if (!timestamp) return "Unknown";
try {
return timestamp.toDate().toLocaleDateString();
} catch {
return "Invalid date"; // This hides the real problem
}
}
Good (TypeScript):
function formatTimestamp(timestamp: Timestamp): string {
// Let the function throw if timestamp is invalid - don't hide the error
const date = timestamp.toDate();
return date.toLocaleDateString();
}
// Usage - handle the null case at the call site
const formatted = buildTime ? formatTimestamp(buildTime) : "";
Avoid Nullable Function Parameters: Nullable parameters (param?: Type) should be rare for function parameters. It's preferable to force an exception at the source of the problem rather than handle null cases inside functions. This makes the code more predictable and helps identify issues earlier.
Bad (TypeScript):
function processUser(user?: User): string {
if (!user) return "No user";
return user.name;
}
Good (TypeScript):
function processUser(user: User): string {
return user.name;
}
// Handle the null case at the call site
const result = user ? processUser(user) : "No user";
Don't Hide Improperly Initialized Components: Components should throw errors when they are not properly initialized rather than providing fallback behavior that masks the problem. This helps identify configuration issues early rather than allowing broken components to appear functional.
Bad:
private get displayIcon(): string {
if (!this.augmentedError) return '⚠️'; // Hides initialization problem
return AugmentErrorService.getIconString(this.augmentedError.icon);
}
Good:
private get displayIcon(): string {
if (!this.augmentedError) {
throw new Error('ErrorDisplay component not properly initialized: augmentedError is required');
}
return AugmentErrorService.getIconString(this.augmentedError.icon);
}
Avoid Default Behaviors Sprinkled Throughout System: Don't scatter default fallback values throughout the codebase as this can hide real problems and make debugging difficult. Instead, ensure proper initialization and let errors surface when components are misconfigured.
Bad:
// Multiple components providing their own defaults
private get hasDetails(): boolean {
return Boolean(this.augmentedError?.details || 'No details available');
}
Good:
// Force proper initialization, let errors surface
private get hasDetails(): boolean {
if (!this.augmentedError) {
throw new Error('Component not properly initialized');
}
return Boolean(this.augmentedError.details && this.augmentedError.details.trim());
}
The application follows a selective exception handling strategy: only catch exceptions you can meaningfully handle or recover from. All unhandled exceptions bubble up to the global error handler.
✅ DO catch when: You can provide user feedback/retry, gracefully degrade functionality, or recover automatically ❌ DON'T catch when: Just logging without handling, hiding programming bugs, or can't provide meaningful recovery
Global Error Handler: Catches unhandled errors/rejections, displays kernel panic screen, allows user restart.
The project uses different linters for different parts of the codebase:
devbox run go:lint to run the Go linter (revive)devbox run fe:lint to run the frontend TypeScript/JavaScript linter (ESLint)devbox run lint:everything to run all linters, tests, and buildsEach linter enforces specific rules:
any instead of interface{} and other Go best practices@typescript-eslint/no-explicit-any rule enableddevbox run lint:everything.ADRs should document significant architectural decisions that have long-term implications for the system design. Use ADRs for:
Do NOT create ADRs for:
Example of ADR-worthy decision: "We chose gRPC-Web over REST for frontend-backend communication" Example of non-ADR decision: "We implemented a version display component in the bottom-right corner"
The application uses OpenTelemetry for metrics and distributed tracing, plus wiki-based metrics for lightweight visibility. See ADR-0007 for the architectural design.
Use observability.Meter("your/scope") to create metric instruments with proper units:
meter := observability.Meter("simple_wiki/yourcomponent")
requestCounter, err := meter.Int64Counter(
"yourcomponent_requests_total",
metric.WithDescription("Total number of requests"),
metric.WithUnit("{request}"),
)
Use observability.Tracer("your/scope") for distributed tracing:
tracer := observability.Tracer("simple_wiki/yourcomponent")
ctx, span := tracer.Start(ctx, "operation-name")
defer span.End()
See internal/observability/doc.go for detailed documentation.
This file provides context and instructions for GitHub Copilot when working in the AI-102 Cert Buddy workspace.
AI-102 Cert Buddy is a certification study companion that helps users prepare for the Microsoft AI-102: Designing and Implementing a Microsoft Azure AI Solution exam. The project provides:
CRITICAL: Always use current Microsoft product names. Never use retired names.
| Retired Name (DO NOT USE) | Current Name (USE THIS) |
|---|---|
| Azure AD | Microsoft Entra ID |
| Azure AD Connect | Microsoft Entra Connect |
| Azure AD Connect Health | Microsoft Entra Connect Health |
| Azure AD Domain Services | Microsoft Entra Domain Services |
| Azure AD B2C | Microsoft Entra External ID |
| Azure AD B2B | Microsoft Entra External ID |
| Azure Active Directory | Microsoft Entra ID |
| Azure Cognitive Services | Azure AI services |
| Cognitive Services | Azure AI services |
| Computer Vision | Azure AI Vision |
| Custom Vision | Azure AI Custom Vision |
| Face API | Azure AI Face |
| Form Recognizer | Azure AI Document Intelligence |
| Language Understanding (LUIS) | Azure AI Language (conversational language understanding) |
| QnA Maker | Azure AI Language (question answering) |
| Speech Service | Azure AI Speech |
| Text Analytics | Azure AI Language |
| Translator | Azure AI Translator |
| Azure Search | Azure Cognitive Search |
| Azure Applied AI Services | Azure AI services |
| Content Moderator | Azure AI Content Safety |
| Personalizer | (retired - no direct replacement) |
| Anomaly Detector | Azure AI Anomaly Detector |
| Metrics Advisor | (retired - use Azure Monitor) |
| Immersive Reader | Azure AI Immersive Reader |
| Video Indexer | Azure Video Indexer |
| Azure Bot Service | Azure AI Bot Service |
| Bot Framework | Azure AI Bot Framework |
| Azure OpenAI Service | Azure OpenAI Service (no change) |
--query with JMESPath for filtering output--output to specify JSON, table, or tsv format--resource-group and --location parameters explicitlyWhen generating practice questions:
When generating practice labs:
.github/
skills/ # Copilot skills for different task types
ai102-item-creator/ # Practice question generator
ai102-lab-creator/ # Practice lab generator
ai102-study-planner/ # Personalized study plan generator
copilot-instructions.md # This file
references/
ai102-objectives.md # Official exam skills outline
style-guide.md # Microsoft writing style rules
fictional-companies.md # Company names for scenarios
.vscode/
mcp.json # MCP server configuration
When generating content related to AI solutions, always consider and reference Microsoft's Responsible AI principles:
Last Updated: March 2026
Ready-to-use automation templates from the marketplace


