-- Vida180 Database Schema -- Created: 2024 -- Enable UUID extension CREATE EXTENSION IF NOT EXISTS "uuid-ossp"; -- Users table CREATE TABLE users ( id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), email VARCHAR(255) UNIQUE NOT NULL, username VARCHAR(100) UNIQUE NOT NULL, password_hash VARCHAR(255) NOT NULL, full_name VARCHAR(255), avatar_url TEXT, timezone VARCHAR(50) DEFAULT 'America/Sao_Paulo', created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP, last_login_at TIMESTAMP WITH TIME ZONE, is_active BOOLEAN DEFAULT TRUE, is_verified BOOLEAN DEFAULT FALSE ); -- Categories table CREATE TABLE categories ( id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, name VARCHAR(100) NOT NULL, description TEXT, color VARCHAR(7), icon VARCHAR(50), display_order INTEGER DEFAULT 0, created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP, UNIQUE(user_id, name) ); -- Tasks table CREATE TABLE tasks ( id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, category_id UUID REFERENCES categories(id) ON DELETE SET NULL, title VARCHAR(255) NOT NULL, description TEXT, priority VARCHAR(20) DEFAULT 'medium', status VARCHAR(20) DEFAULT 'pending', due_date DATE, due_time TIME, completed_at TIMESTAMP WITH TIME ZONE, created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP, is_archived BOOLEAN DEFAULT FALSE ); -- Habits table CREATE TABLE habits ( id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, category_id UUID REFERENCES categories(id) ON DELETE SET NULL, name VARCHAR(255) NOT NULL, description TEXT, frequency_type VARCHAR(20) NOT NULL, target_count INTEGER DEFAULT 1, reminder_time TIME, is_active BOOLEAN DEFAULT TRUE, start_date DATE NOT NULL, end_date DATE, created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP ); -- Habit completions table CREATE TABLE habit_completions ( id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), habit_id UUID NOT NULL REFERENCES habits(id) ON DELETE CASCADE, user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, completion_date DATE NOT NULL, completion_time TIME, notes TEXT, quality_rating INTEGER, created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP, UNIQUE(habit_id, completion_date) ); -- Streaks table CREATE TABLE streaks ( id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), habit_id UUID NOT NULL REFERENCES habits(id) ON DELETE CASCADE, user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, current_streak INTEGER DEFAULT 0, longest_streak INTEGER DEFAULT 0, last_completion_date DATE, total_completions INTEGER DEFAULT 0, created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP, UNIQUE(habit_id) ); -- Health metrics table CREATE TABLE health_metrics ( id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, measurement_date DATE NOT NULL, measurement_time TIME DEFAULT CURRENT_TIME, weight DECIMAL(5,2), height DECIMAL(5,2), body_fat_percentage DECIMAL(4,2), muscle_mass DECIMAL(5,2), waist DECIMAL(5,2), chest DECIMAL(5,2), hips DECIMAL(5,2), notes TEXT, created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP, UNIQUE(user_id, measurement_date) ); -- Health goals table CREATE TABLE health_goals ( id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, goal_type VARCHAR(50) NOT NULL, metric_type VARCHAR(50) NOT NULL, starting_value DECIMAL(5,2) NOT NULL, target_value DECIMAL(5,2) NOT NULL, current_value DECIMAL(5,2), start_date DATE NOT NULL, target_date DATE, achieved_date DATE, is_active BOOLEAN DEFAULT TRUE, notes TEXT, created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP ); -- Create indexes CREATE INDEX idx_categories_user_id ON categories(user_id); CREATE INDEX idx_tasks_user_id ON tasks(user_id); CREATE INDEX idx_tasks_status ON tasks(status); CREATE INDEX idx_habits_user_id ON habits(user_id); CREATE INDEX idx_health_metrics_user_id ON health_metrics(user_id); CREATE INDEX idx_health_metrics_date ON health_metrics(measurement_date); -- ============================================ -- MENSAGENS MOTIVACIONAIS -- ============================================ CREATE TABLE motivational_messages ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), message_type VARCHAR(50) NOT NULL, trigger_condition VARCHAR(100) NOT NULL, message_text TEXT NOT NULL, icon VARCHAR(10), priority INTEGER DEFAULT 0, is_active BOOLEAN DEFAULT TRUE, created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP, CONSTRAINT valid_message_type CHECK (message_type IN ( 'streak_achievement', 'reminder', 'progress_milestone', 'time_based', 'special_milestone', 'recovery', 'daily_motivation' )) ); -- Índices CREATE INDEX idx_messages_type ON motivational_messages(message_type); CREATE INDEX idx_messages_active ON motivational_messages(is_active); -- ============================================ -- USER MESSAGES LOG (histórico de mensagens vistas) -- ============================================ CREATE TABLE user_messages_log ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, message_id UUID REFERENCES motivational_messages(id) ON DELETE SET NULL, message_text TEXT NOT NULL, message_type VARCHAR(50), shown_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP, was_clicked BOOLEAN DEFAULT FALSE, clicked_at TIMESTAMP WITH TIME ZONE ); CREATE INDEX idx_user_messages_user_id ON user_messages_log(user_id); CREATE INDEX idx_user_messages_shown_at ON user_messages_log(shown_at); -- ============================================ -- INSERIR MENSAGENS PADRÃO -- ============================================ -- Mensagens de Streak INSERT INTO motivational_messages (message_type, trigger_condition, message_text, icon, priority) VALUES ('streak_achievement', 'streak_7', '🔥 7 dias de sequência! Essa disciplina vai te levar longe!', '🔥', 10), ('streak_achievement', 'streak_14', '💪 14 dias! Você está construindo algo sólido aqui!', '💪', 15), ('streak_achievement', 'streak_30', '🏆 30 DIAS! A maioria desiste antes. Você não!', '🏆', 20), ('streak_achievement', 'streak_60', '⚡ 60 dias de transformação real! Continue nessa pegada!', '⚡', 25), ('streak_achievement', 'streak_100', '👑 100 DIAS! Você oficialmente virou o jogo da sua vida!', '👑', 30), ('streak_achievement', 'streak_365', '🎉 1 ANO! Você é lenda! Prova viva de transformação!', '🎉', 50); -- Lembretes INSERT INTO motivational_messages (message_type, trigger_condition, message_text, icon, priority) VALUES ('reminder', 'no_weight_3days', '📊 Faz 3 dias sem registrar peso. Que tal medir hoje?', '📊', 5), ('reminder', 'no_weight_7days', '⚠️ 7 dias sem medição. Continue acompanhando sua evolução!', '⚠️', 8), ('reminder', 'habits_pending', '🎯 Você tem hábitos esperando por você hoje!', '🎯', 7), ('reminder', 'tasks_pending', '✅ Tarefas do dia te aguardam. Vamos começar?', '✅', 6); -- Progresso INSERT INTO motivational_messages (message_type, trigger_condition, message_text, icon, priority) VALUES ('progress_milestone', 'consistency_80', '💎 80% de consistência esse mês! Top 10% dos usuários!', '💎', 12), ('progress_milestone', 'weight_loss_5kg', '🎊 5kg perdidos! A estrada está aparecendo, continue!', '🎊', 15), ('progress_milestone', 'weight_loss_10kg', '🌟 10kg! Transformação visível! Que orgulho!', '🌟', 20), ('progress_milestone', 'first_goal_achieved', '🏅 Primeiro objetivo alcançado! Defina o próximo!', '🏅', 18); -- Mensagens por Hora do Dia INSERT INTO motivational_messages (message_type, trigger_condition, message_text, icon, priority) VALUES ('time_based', 'morning', '🌅 Bom dia! Que tal começar o dia marcando suas metas?', '🌅', 3), ('time_based', 'afternoon', '☀️ Boa tarde! Como está o progresso de hoje?', '☀️', 2), ('time_based', 'evening', '🌙 Boa noite! Antes de dormir, registre o que conquistou hoje.', '🌙', 3), ('time_based', 'monday', '💼 Segunda-feira! Nova semana, novas vitórias! Vamos lá!', '💼', 4); -- Milestones Especiais INSERT INTO motivational_messages (message_type, trigger_condition, message_text, icon, priority) VALUES ('special_milestone', 'first_habit_complete', '⭐ Primeiro hábito completado! Esse é o início!', '⭐', 8), ('special_milestone', 'all_tasks_complete', '✨ TODAS as tarefas do dia completas! Incrível!', '✨', 10), ('special_milestone', 'perfect_week', '🔥 Semana perfeita! 7 dias sem falhas! Imparável!', '🔥', 15); -- Recuperação INSERT INTO motivational_messages (message_type, trigger_condition, message_text, icon, priority) VALUES ('recovery', 'inactive_7days', '👋 Sentimos sua falta! A vida acontece, mas você pode retomar AGORA!', '👋', 9), ('recovery', 'inactive_14days', '💙 14 dias offline. Que tal voltar hoje? Estamos aqui pra você!', '💙', 11), ('recovery', 'streak_broken', '🔄 Quebrou a sequência? Normal! Recomeçar é parte da jornada.', '🔄', 7); -- Motivacionais Diárias (genéricas) INSERT INTO motivational_messages (message_type, trigger_condition, message_text, icon, priority) VALUES ('daily_motivation', 'default_1', '💪 A transformação acontece um dia de cada vez. Esse dia é hoje!', '💪', 1), ('daily_motivation', 'default_2', '🚀 Cada pequena vitória hoje constrói o grande resultado de amanhã.', '🚀', 1), ('daily_motivation', 'default_3', '⚡ Você não precisa ser perfeito. Só precisa ser consistente.', '⚡', 1), ('daily_motivation', 'default_4', '🎯 O segredo do sucesso? Aparecer todos os dias.', '🎯', 1), ('daily_motivation', 'default_5', '🌟 Seu eu do futuro vai agradecer pelo que você faz hoje.', '🌟', 1), ('daily_motivation', 'default_6', '💎 Pequenos passos, grandes mudanças. Continue!', '💎', 1), ('daily_motivation', 'default_7', '🔥 A disciplina de hoje é a liberdade de amanhã.', '🔥', 1); COMMENT ON TABLE motivational_messages IS 'Banco de mensagens motivacionais contextuais'; COMMENT ON TABLE user_messages_log IS 'Histórico de mensagens exibidas para cada usuário';