first commit

This commit is contained in:
rodrigo committed 2025-04-10 23:07:21 -03:00
commit c9fb67e751
423 files changed
+53287

No files matched your search

+12
View File
@@ -0,0 +1,12 @@
PORT=5000
BACKEND_URL=http://localhost:5000
FRONTEND_URL=http://localhost:3000
CORS_ORIGIN=http://localhost:3000
NODE_ENV=development
DATABASE_URL="postgresql://user:password@localhost:5432/dbname"
DATAJUD_API_KEY=your_api_key_here
# Nextcloud WebDAV Configuration
NEXTCLOUD_WEBDAV_URL=
NEXTCLOUD_USERNAME=
NEXTCLOUD_PASSWORD=
+29
View File
@@ -0,0 +1,29 @@
module.exports = {
parser: '@typescript-eslint/parser',
extends: [
'plugin:react/recommended',
'plugin:@typescript-eslint/recommended',
'plugin:react-hooks/recommended',
'plugin:prettier/recommended'
],
parserOptions: {
ecmaVersion: 2020,
sourceType: 'module',
ecmaFeatures: {
jsx: true
}
},
plugins: ['react', '@typescript-eslint', 'react-hooks'],
rules: {
'react/react-in-jsx-scope': 'off',
'react/prop-types': 'off',
'@typescript-eslint/explicit-function-return-type': 'off',
'@typescript-eslint/no-explicit-any': 'off',
'prettier/prettier': ['error', {}, { usePrettierrc: true }]
},
settings: {
react: {
version: 'detect'
}
}
};
+61
View File
@@ -0,0 +1,61 @@
Instruções para o GitHub Copilot
Este arquivo fornece instruções específicas para o GitHub Copilot ao trabalhar neste projeto. O objetivo é garantir a geração de código de alta qualidade, evitar erros comuns e otimizar o processo de resolução de problemas.
Contexto do Projeto
Objetivo: criar um sistema de gestão de advocacia completo.
Instruções Específicas
Banco de Dados:
* **NÃO RESETAR O BANCO DE DADOS EM HIPÓTESE ALGUMA.**
* Ao criar ou modificar scripts que interagem com o banco de dados, priorize a segurança e a integridade dos dados.
* Sempre use prepared statements ou consultas parametrizadas para evitar injeção de SQL.
* Antes de executar qualquer operação de escrita (INSERT, UPDATE, DELETE), verifique se os dados são válidos e se o usuário tem permissão para realizar a ação.
* Ao criar novas tabelas ou colunas, defina tipos de dados apropriados e restrições de integridade (NOT NULL, UNIQUE, etc.).
* Sempre faça backup do banco de dados antes de realizar alterações estruturais significativas.
Prevenção de Erros:
* Priorize a prevenção de erros durante a geração de código.
* Implemente tratamento de erros robusto em todas as funções e rotas.
* Use validação de dados para garantir que os dados de entrada estejam no formato correto.
* Sempre verifique se as variáveis estão definidas antes de usá-las.
* Evite o uso de "magic numbers" ou strings literais diretamente no código. Em vez disso, use constantes ou variáveis com nomes significativos.
* Use linting e formatação de código para garantir a consistência e legibilidade do código.
Resolução de Problemas:
* Ao resolver problemas, foque unicamente na solução do problema em questão.
* Evite criar novos problemas ou efeitos colaterais indesejados.
* Antes de implementar uma solução, analise cuidadosamente o problema e suas possíveis causas.
* Use debuggers e logs para identificar a causa raiz do problema.
* Teste a solução em um ambiente de desenvolvimento antes de aplicá-la em produção.
* Documente a solução e as lições aprendidas para evitar que o problema ocorra novamente.
Segurança:
* Sempre sanitize os dados de entrada para evitar ataques de injeção (SQL, XSS, etc.).
* Use criptografia para proteger dados confidenciais (senhas, chaves de API, etc.).
* Implemente autenticação e autorização adequadas para proteger as rotas e recursos da API.
* Mantenha as dependências atualizadas para corrigir vulnerabilidades de segurança.
* Siga as práticas recomendadas de segurança para Node.js e PostgreSQL.
Exemplos
Exemplo de Comentário:
javascript
Copiar
// Função para criar um novo usuário no banco de dados.
// Certifique-se de validar os dados antes de inserir no banco.
async function createUser(userData) {
// ...
}
Exemplo de Tratamento de Erro:
javascript
Copiar
try {
const result = await db.query('SELECT * FROM users WHERE id = $1', [userId]);
return result.rows[0];
} catch (error) {
console.error('Erro ao buscar usuário:', error);
throw new Error('Falha ao buscar usuário.');
}
Notas Adicionais
Este arquivo será atualizado conforme necessário para refletir as necessidades e os desafios do projeto.
Por favor, consulte este arquivo regularmente para garantir que você esteja seguindo as diretrizes mais recentes.
Se você tiver alguma dúvida ou sugestão, entre em contato com [seu nome/equipe].
+9
View File
@@ -0,0 +1,9 @@
node_modules
dist
.env
.env.local
.env.*.local
*.log
.DS_Store
coverage
.vscode
+8
View File
@@ -0,0 +1,8 @@
{
"hash": "8cb35725",
"configHash": "f0a530a0",
"lockfileHash": "ff4b1e25",
"browserHash": "24e5231a",
"optimized": {},
"chunks": {}
}
+3
View File
@@ -0,0 +1,3 @@
{
"type": "module"
}
View File
Whitespace-only changes.
+13
View File
@@ -0,0 +1,13 @@
<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>AdvX - Sistema de Advocacia</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/index.tsx"></script>
</body>
</html>
+144
View File
@@ -0,0 +1,144 @@
<?php
// Verificar se o usuário está logado
if (!isset($_SESSION['user_id'])) {
header("Location: login.php");
exit();
}
$processed_dir = './processed/';
date_default_timezone_set('America/Araguaina');
if (is_dir($processed_dir)) {
$files = scandir($processed_dir);
$files = array_diff($files, array('.', '..'));
usort($files, function($a, $b) use ($processed_dir) {
return filemtime($processed_dir . $b) - filemtime($processed_dir . $a);
});
} else {
$files = [];
}
// Paginação
$files_per_page = 10;
$total_files = count($files);
$total_pages = ceil($total_files / $files_per_page);
$current_page = isset($_GET['page_num']) ? (int)$_GET['page_num'] : 1;
$current_page = max(1, min($total_pages, $current_page));
$start_index = ($current_page - 1) * $files_per_page;
$paginated_files = array_slice($files, $start_index, $files_per_page);
?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="UTF-8">
<title>Lista de Arquivos Processados</title>
<link href="https://cdnjs.cloudflare.com/ajax/libs/lightbox2/2.11.3/css/lightbox.min.css" rel="stylesheet" />
<style>
table { width: 100%; border-collapse: collapse; }
th, td { padding: 10px; text-align: left; border-bottom: 1px solid #ddd; }
th { background-color: #f4f4f4; }
a.download-link { color: #007BFF; text-decoration: none; }
a.download-link:hover { text-decoration: underline; }
.pagination { margin-top: 20px; text-align: center; }
.pagination a { margin: 0 5px; text-decoration: none; color: #007BFF; }
.pagination a:hover { text-decoration: underline; }
.lightbox-container {
display: none;
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.8);
justify-content: center;
align-items: center;
z-index: 1000;
}
.lightbox-content {
width: 80%;
height: 80%;
background-color: #fff;
padding: 20px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.5);
position: relative;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
.lightbox-content iframe {
width: 100%;
height: 100%;
}
.lightbox-close {
position: absolute;
top: 10px;
right: 10px;
background-color: #333;
color: #fff;
border: none;
padding: 5px 10px;
cursor: pointer;
}
</style>
</head>
<body>
<div class="container">
<h2>Lista de Arquivos Processados</h2>
<table>
<thead>
<tr>
<th>Nome do Arquivo</th>
<th>Data de Modificação</th>
</tr>
</thead>
<tbody>
<?php foreach ($paginated_files as $file): ?>
<tr>
<td>
<a class="download-link" href="#" data-file="<?php echo 'processed/' . urlencode($file); ?>" data-title="<?php echo htmlspecialchars($file); ?>">
<?php echo htmlspecialchars($file); ?>
</a>
</td>
<td><?php echo date("d/m/Y H:i:s", filemtime($processed_dir . $file)); ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<div class="pagination">
<?php if ($current_page > 1): ?>
<a href="index.php?page=list_files&page_num=<?php echo $current_page - 1; ?>">&laquo; Anterior</a>
<?php endif; ?>
<?php for ($i = 1; $i <= $total_pages; $i++): ?>
<a href="index.php?page=list_files&page_num=<?php echo $i; ?>" <?php if ($i == $current_page) echo 'style="font-weight: bold;"'; ?>><?php echo $i; ?></a>
<?php endfor; ?>
<?php if ($current_page < $total_pages): ?>
<a href="index.php?page=list_files&page_num=<?php echo $current_page + 1; ?>">Próximo &raquo;</a>
<?php endif; ?>
</div>
</div>
<div id="lightbox" class="lightbox-container">
<div class="lightbox-content">
<button class="lightbox-close" onclick="closeLightbox()">Fechar</button>
<iframe id="lightbox-iframe" src="" frameborder="0"></iframe>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('.download-link').on('click', function(e) {
e.preventDefault();
var fileUrl = $(this).data('file');
$('#lightbox-iframe').attr('src', fileUrl);
$('#lightbox').css('display', 'flex'); // Usar flex para centralizar
});
});
function closeLightbox() {
$('#lightbox').hide();
$('#lightbox-iframe').attr('src', '');
}
</script>
</body>
</html>
+508
View File
@@ -0,0 +1,508 @@
<?php
// process_queue.php
ini_set('memory_limit', '512M');
date_default_timezone_set('America/Araguaina');
// Aumentar o tempo máximo de execução do script para 300 segundos (5 minutos)
set_time_limit(300);
// Verifique se a extensão `pcntl` está disponível
if (!function_exists('pcntl_fork')) {
die("A extensão pcntl não está disponível. Por favor, habilite-a para continuar.\n");
}
// Definir o número máximo de processos filhos
define('MAX_CHILDREN', 3);
$childProcesses = [];
// Função para registrar logs
function log_message($message, $level = 'INFO') {
$timestamp = date("Y-m-d H:i:s P"); // Inclui o fuso horário
// Apenas logar mensagens de nível INFO, ERROR e WARN
if (in_array($level, ['INFO', 'ERROR', 'WARN'])) {
file_put_contents('/var/log/process_queue.log', "[$timestamp] [$level] $message\n", FILE_APPEND);
}
}
log_message("Script iniciado.", 'INFO');
function process_file($row) {
// Cada processo filho deve estabelecer sua própria conexão com o banco de dados
$mysqli = new mysqli("10.15.0.42", "root", "34641747", "valida");
if ($mysqli->connect_error) {
log_message("Connection failed: " . $mysqli->connect_error, 'ERROR');
exit(1); // Sair com erro
}
// Assegurar que as mensagens de log incluam o ID do processo
$process_id = getmypid();
log_message("Processo $process_id: Processando arquivo ID " . $row['id'] . ": " . $row['file_path'], 'INFO');
try {
$file_path = $row['file_path'];
$queue_id = $row['id'];
$user_agent = $row['user_agent'];
$ip_address = $row['ip_address'];
$host_name = $row['host_name'];
$access_time = $row['access_time'] . ' ' . date("P"); // Adiciona fuso horário
$language = $row['language'];
$referer = $row['referer'];
$protocol = $row['protocol'];
$connection = $row['connection'];
$viewport_width = $row['viewport_width'];
$viewport_height = $row['viewport_height'];
$original_location = $row['original_location']; // Novo campo para localização original
// Recuperar a porta do cliente
$result_port = $mysqli->query("SELECT port FROM client_ports WHERE queue_id = $queue_id");
$client_port = $result_port->fetch_assoc()['port'] ?? 'N/A';
$result_port->free();
// Atualizar status para 'processing'
$stmt_update = $mysqli->prepare("UPDATE queue SET status = 'processing' WHERE id = ?");
$stmt_update->bind_param("i", $queue_id);
$stmt_update->execute();
$stmt_update->close();
log_message("Processo $process_id: Atualizou status para 'processing' para o arquivo ID $queue_id.", 'INFO');
// Gerar checksums
$checksums = generate_checksums($file_path);
// Capturar data e hora
$file_datetime = get_file_datetime($file_path);
// Registrar timestamp usando OpenTimestamps
$timestamp_result = register_timestamp_opentimestamps($file_path);
$signature_time = date("d/m/Y H:i:s P"); // Inclui fuso horário
if ($timestamp_result['success']) {
$ots_base64 = $timestamp_result['ots_base64'];
// Coletar dados do dispositivo
$device_data = [
'User Agent' => $user_agent,
'IP Address' => $ip_address . ':' . $client_port,
'Host Name' => $host_name,
'Access Time' => $access_time,
'Language' => $language,
'Referer' => $referer,
'Protocol' => $protocol,
'Connection' => $connection,
'Viewport Width' => $viewport_width,
'Viewport Height' => $viewport_height,
'Original Location' => $original_location // Adicionado
];
// Gerar PDF
$pdf_path = generate_pdf($file_path, [
'name' => basename($file_path),
'creation_time' => $file_datetime['creation_time'] . ' ' . date("P", filectime($file_path)),
'modification_time' => $file_datetime['modification_time'] . ' ' . date("P", filemtime($file_path)),
'upload_time' => $access_time,
'signature_time' => $signature_time
], $checksums, $device_data, $ots_base64);
// Atualizar status para 'completed'
$stmt_complete = $mysqli->prepare("UPDATE queue SET status = 'completed' WHERE id = ?");
$stmt_complete->bind_param("i", $queue_id);
$stmt_complete->execute();
$stmt_complete->close();
log_message("Processo $process_id: Processamento concluído para arquivo ID $queue_id: $file_path", 'INFO');
} else {
// Atualizar status para 'error'
$stmt_error = $mysqli->prepare("UPDATE queue SET status = 'error' WHERE id = ?");
$stmt_error->bind_param("i", $queue_id);
$stmt_error->execute();
$stmt_error->close();
log_message("Processo $process_id: Erro ao processar arquivo ID $queue_id: " . $timestamp_result['message'], 'ERROR');
}
} catch (Exception $e) {
// Atualizar status para 'error'
$stmt_exception = $mysqli->prepare("UPDATE queue SET status = 'error' WHERE id = ?");
$stmt_exception->bind_param("i", $queue_id);
$stmt_exception->execute();
$stmt_exception->close();
log_message("Processo $process_id: Exceção ao processar arquivo ID $queue_id: " . $e->getMessage(), 'ERROR');
}
$mysqli->close();
log_message("Processo $process_id: Fechou conexão com o banco de dados para o arquivo ID $queue_id.", 'INFO');
}
// Funções auxiliares (generate_checksums, get_file_datetime, register_timestamp_opentimestamps, generate_pdf)
// Mantenha estas funções como estão no seu código original, sem alterações. Certifique-se de que as funções não dependam de conexões globais de banco de dados.
require_once __DIR__ . '../../vendor/autoload.php';
// Função para gerar checksums
function generate_checksums($file_path) {
log_message("Gerando checksums para $file_path", 'INFO');
$start_time = microtime(true);
// Carregar o conteúdo do arquivo uma única vez
$file_content = file_get_contents($file_path);
$checksums = [
'sha256' => hash('sha256', $file_content),
'sha512' => hash('sha512', $file_content),
'md5' => hash('md5', $file_content)
];
$end_time = microtime(true);
log_message("Checksums gerados em " . round($end_time - $start_time, 4) . " segundos", 'INFO');
return $checksums;
}
// Função para capturar data e hora do arquivo
function get_file_datetime($file_path) {
log_message("Obtendo data e hora do arquivo para $file_path", 'INFO');
$start_time = microtime(true);
$creation_time = date("d/m/Y H:i:s P", filectime($file_path));
$modification_time = date("d/m/Y H:i:s P", filemtime($file_path));
$end_time = microtime(true);
log_message("Data e hora obtidas em " . round($end_time - $start_time, 4) . " segundos", 'INFO');
return [
'creation_time' => $creation_time,
'modification_time' => $modification_time
];
}
// Função para registrar timestamp usando OpenTimestamps
function register_timestamp_opentimestamps($file_path) {
log_message("Registrando timestamp para $file_path", 'INFO');
$start_time = microtime(true);
// Definir diretório de cache para OTS
$ots_cache_dir = '/var/www/html/ots_cache';
if (!is_dir($ots_cache_dir)) {
log_message("Diretório de cache OTS não existe. Criando em $ots_cache_dir", 'INFO');
if (!mkdir($ots_cache_dir, 0755, true)) {
log_message("Erro ao criar diretório de cache OTS: $ots_cache_dir", 'ERROR');
return ['success' => false, 'message' => "Erro ao criar diretório de cache OTS: $ots_cache_dir"];
}
chmod($ots_cache_dir, 0755); // Ajustar permissões
}
// Definir a variável de ambiente antes de executar o comando
$command_stamp = "OTS_CACHE_DIRECTORY=" . escapeshellarg($ots_cache_dir) . " ots stamp " . escapeshellarg($file_path) . " 2>&1";
log_message("Comando para executar: $command_stamp", 'INFO');
// Executar o comando
exec($command_stamp, $output_stamp, $return_var_stamp);
// Verificar o resultado da execução
if ($return_var_stamp !== 0) {
log_message("Erro ao registrar timestamp: " . implode("\n", $output_stamp), 'ERROR');
return ['success' => false, 'message' => 'Erro ao registrar timestamp: ' . implode("\n", $output_stamp)];
}
// Definir o caminho do arquivo .ots gerado
$ots_file = "{$file_path}.ots";
// Verificar se o arquivo .ots foi criado
if (!file_exists($ots_file)) {
log_message("Arquivo de timestamp não encontrado: $ots_file", 'ERROR');
return ['success' => false, 'message' => "Arquivo de timestamp não encontrado: $ots_file"];
}
// Codificar o arquivo .ots em base64
$ots_base64 = base64_encode(file_get_contents($ots_file));
$end_time = microtime(true);
log_message("Timestamp registrado e codificado em " . round($end_time - $start_time, 4) . " segundos", 'INFO');
return ['success' => true, 'ots_base64' => $ots_base64];
}
// Função para gerar PDF
function generate_pdf($uploaded_file_path, $document_info, $checksums, $device_data, $ots_base64) {
log_message("Gerando PDF para $uploaded_file_path", 'INFO');
$start_time = microtime(true);
// Criar uma nova instância do TCPDF
$pdf = new TCPDF();
// Configurações iniciais do PDF
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor('Seu Nome ou Empresa');
$pdf->SetTitle('Prova de Autenticidade de Documento');
$pdf->SetSubject('Timestamping e Checksums');
// Remover as margens padrão
$pdf->SetMargins(10, 10, 10);
$pdf->SetHeaderMargin(0);
$pdf->SetFooterMargin(0);
// Desativar cabeçalhos e rodapés automáticos
$pdf->setPrintHeader(false);
$pdf->setPrintFooter(false);
// Configurar a fonte padrão uma vez
$pdf->SetFont('helvetica', '', 10);
// Verificar o tipo de arquivo para incorporar no PDF
$file_info = pathinfo($uploaded_file_path);
$extension = strtolower($file_info['extension']);
// Configurar o diretório temporário para o ImageMagick
$temp_dir = '/tmp/imagick';
if (!is_dir($temp_dir)) {
mkdir($temp_dir, 0777, true);
}
chmod($temp_dir, 0777); // Garantir permissões totais
// Configurar o diretório temporário para as imagens
$tmp_dir = '/tmp/image';
if (!is_dir($tmp_dir)) {
mkdir($tmp_dir, 0777, true);
}
chmod($tmp_dir, 0777); // Garantir permissões totais
// Criar uma única instância de Imagick
$imagick = new Imagick();
// Configurar o ambiente para otimização
putenv('MAGICK_TMPDIR=' . $temp_dir); // Defina um diretório temporário adequado
$imagick->setResourceLimit(Imagick::RESOURCETYPE_MEMORY, 512); // Ajuste conforme necessário
$imagick->setResourceLimit(Imagick::RESOURCETYPE_MAP, 512);
$imagick->setResourceLimit(Imagick::RESOURCETYPE_THREAD, 2);
try {
if (in_array($extension, ['jpg', 'jpeg', 'png', 'gif'])) {
log_message("Processando imagem $uploaded_file_path", 'INFO');
// Reduzir a resolução para 1200x900, mantendo a proporção
log_message("Reduzindo resolução da imagem para melhor qualidade e menor tamanho", 'INFO');
$imagick->readImage($uploaded_file_path);
$imagick->resizeImage(1200, 900, Imagick::FILTER_LANCZOS, 1, true);
// Configurar a compressão usando PNG para melhor qualidade sem perder transparência
if ($extension === 'png') {
$imagick->setImageFormat('png');
$imagick->stripImage(); // Remove metadados
$image_blob = $imagick->getImageBlob();
} else {
// Para JPEG e outros, usar alta qualidade com compressão balanceada
log_message("Configurando compressão da imagem para JPEG", 'INFO');
$imagick->setImageCompression(Imagick::COMPRESSION_JPEG);
$imagick->setImageCompressionQuality(85); // Maior qualidade
$imagick->stripImage(); // Remove metadados para reduzir o tamanho
$image_blob = $imagick->getImageBlob();
}
// Salvar a imagem temporariamente
$tmp_img = tempnam($tmp_dir, 'img_') . '.' . $extension;
log_message("Salvando imagem temporária em $tmp_img", 'INFO');
file_put_contents($tmp_img, $image_blob);
chmod($tmp_img, 0666); // Ajustar permissões do arquivo temporário
// Adicionar a imagem ao PDF
log_message("Adicionando imagem ao PDF", 'INFO');
$pdf->AddPage();
$pdf->Image('@' . $image_blob, 15, 40, 180, 160, '', '', 'C', false, 100, '', false, false, 1, false, false, false);
log_message("Imagem adicionada ao PDF", 'INFO');
// Remover a imagem temporária
if (file_exists($tmp_img)) {
log_message("Removendo imagem temporária $tmp_img", 'INFO');
unlink($tmp_img);
} else {
log_message("Imagem temporária $tmp_img não encontrada para remoção", 'WARN');
}
} elseif (in_array($extension, ['pdf'])) {
log_message("Processando PDF $uploaded_file_path", 'INFO');
// Verificar se a extensão Imagick está carregada
if (extension_loaded('imagick')) {
log_message("Imagick está carregado", 'INFO');
// Inicializar Imagick
try {
log_message("Inicializando Imagick para $uploaded_file_path", 'INFO');
$imagick->setResolution(150, 150); // Ajuste a resolução conforme necessário
$imagick->readImage($uploaded_file_path); // Ler todas as páginas do PDF
log_message("PDF lido com sucesso", 'INFO');
// Processar cada página do PDF
$page_count = $imagick->getNumberImages(); // Número total de páginas do PDF
for ($i = 0; $i < $page_count; $i++) {
$imagick->setIteratorIndex($i); // Define a página atual
$imagick->setImageFormat("jpeg"); // Configura o formato como JPEG
// Definir o fundo como branco
$imagick->setImageBackgroundColor('white');
$imagick = $imagick->mergeImageLayers(Imagick::LAYERMETHOD_FLATTEN);
// Reduz a resolução para 1600x1200, mantendo a proporção
$imagick->resizeImage(1600, 1200, Imagick::FILTER_LANCZOS, 1, true);
// Configura as opções de compressão
$imagick->setImageCompression(Imagick::COMPRESSION_JPEG);
$imagick->setImageCompressionQuality(85);
$imagick->stripImage(); // Remove metadados desnecessários
// Obter os dados da imagem
$image_data = $imagick->getImageBlob();
$tmp_img = tempnam($tmp_dir, 'pdf_page_') . '.jpg';
file_put_contents($tmp_img, $image_data); // Salvar página como JPEG temporária
chmod($tmp_img, 0666);
// Adicionar a página como imagem ao novo PDF
$pdf->AddPage();
$pdf->Image($tmp_img, 15, 40, 180, 160, '', '', 'C', false, 100, '', false, false, 1, false, false, false);
// Remover a imagem temporária
unlink($tmp_img);
}
// Limpar recursos do Imagick
$imagick->clear();
$imagick->destroy();
} catch (Exception $e) {
log_message("Erro ao inicializar ou processar imagem com Imagick: " . $e->getMessage(), 'ERROR');
}
} else {
log_message("Imagick não está carregado", 'WARN');
// Se Imagick não estiver disponível, apenas adicionar uma mensagem
$pdf->SetFont('helvetica', '', 12);
$pdf->Write(0, 'Visualização de PDF não suportada.');
}
} else {
log_message("Tipo de arquivo não suportado: $extension", 'WARN');
// Outros tipos de arquivo podem ser adicionados conforme necessidade
$pdf->SetFont('helvetica', '', 12);
$pdf->Write(0, 'Visualização deste tipo de arquivo não está disponível.');
}
} catch (Exception $e) {
log_message("Erro ao processar imagem: " . $e->getMessage(), 'ERROR');
}
// Adicionar uma nova página para as informações
$pdf->AddPage();
// Conteúdo das informações
$html = '<h2>Informações do Documento</h2>';
$html .= '<p><strong>Nome do Arquivo:</strong> ' . htmlspecialchars($document_info['name']) . '</p>';
$html .= '<p><strong>Data de Modificação:</strong> ' . htmlspecialchars($document_info['modification_time']) . '</p>';
$html .= '<p><strong>Data de Envio ao Servidor:</strong> ' . htmlspecialchars($document_info['upload_time']) . '</p>';
$html .= '<p><strong>Data e Hora da Assinatura:</strong> ' . htmlspecialchars($document_info['signature_time']) . ' (UTC-3)</p>';
$html .= '<h3>Checksums</h3>';
$html .= '<ul>';
$html .= '<li><strong>SHA-256:</strong> ' . htmlspecialchars($checksums['sha256']) . '</li>';
$html .= '<li><strong>SHA-512:</strong> ' . htmlspecialchars($checksums['sha512']) . '</li>';
$html .= '<li><strong>MD5:</strong> ' . htmlspecialchars($checksums['md5']) . '</li>';
$html .= '</ul>';
$html .= '<h3>Dados do Dispositivo</h3>';
$html .= '<ul>';
foreach ($device_data as $key => $value) {
$html .= '<li><strong>' . htmlspecialchars((string)$key) . ':</strong> ' . htmlspecialchars((string)$value) . '</li>';
}
$html .= '</ul>';
$orig_link= 'https://validar.martinsevieira.adv.br/uploads/';
$html .= '<h3>Arquivos Originais</h3>';
$html .= '<ul>';
$html .= '<li><a href="' . $orig_link . $document_info['name'] . '">Arquivo Original</a></li>';
$html .= '<li><a href="' . $orig_link . $document_info['name'] . '.ots">Arquivo OTS</a></li>';
$html .= '</ul>';
$html .= '<h3>Arquivo de Timestamp (OTS) em Base64</h3>';
$html .= '<pre>' . htmlspecialchars($ots_base64) . '</pre>';
$pdf->writeHTML($html, true, false, true, false, '');
// Salvar o PDF no servidor
$processed_dir = '/var/www/html/processed/';
if (!is_dir($processed_dir)) {
mkdir($processed_dir, 0777, true);
}
log_message("Salvando PDF no servidor", 'INFO');
$pdf_output_path = $processed_dir . uniqid('prova_') . '.pdf';
$pdf->Output($pdf_output_path, 'F');
$end_time = microtime(true);
log_message("PDF gerado em " . round($end_time - $start_time, 4) . " segundos", 'INFO');
// Limpar recursos do Imagick
$imagick->clear();
$imagick->destroy();
return $pdf_output_path;
}
// Recuperar todos os arquivos pendentes
$mysqli = new mysqli("10.15.0.42", "root", "34641747", "valida");
if ($mysqli->connect_error) {
log_message("Connection failed: " . $mysqli->connect_error, 'ERROR');
die("Connection failed: " . $mysqli->connect_error);
}
log_message("Conexão com o banco de dados estabelecida.", 'INFO');
// Recuperar todos os arquivos pendentes
$result = $mysqli->query("SELECT q.*, cp.port, q.original_location FROM queue q LEFT JOIN client_ports cp ON q.id = cp.queue_id WHERE q.status = 'pending'");
if ($result->num_rows > 0) {
log_message("Encontrados " . $result->num_rows . " arquivos pendentes para processar.", 'INFO');
while ($row = $result->fetch_assoc()) {
// Verificar se o número de processos filhos atingiu o máximo permitido
while (count($childProcesses) >= MAX_CHILDREN) {
// Esperar por qualquer processo filho terminar
$endedPid = pcntl_wait($status);
if ($endedPid > 0) {
unset($childProcesses[$endedPid]);
log_message("Processo filho $endedPid finalizado.", 'INFO');
}
}
// Fork do processo
$pid = pcntl_fork();
if ($pid == -1) {
// Erro ao fork
log_message("Erro ao criar processo filho.", 'ERROR');
} elseif ($pid) {
// Processo pai
$childProcesses[$pid] = true;
log_message("Criado processo filho $pid para o arquivo ID " . $row['id'] . ".", 'INFO');
} else {
// Processo filho
// Fecha a conexão do processo pai antes de iniciar no filho
$mysqli->close();
// Processa o arquivo
process_file($row);
// Finaliza o processo filho
exit(0);
}
}
// Após forçar todos os filhos a serem criados, esperar que terminem
while (count($childProcesses) > 0) {
$endedPid = pcntl_wait($status);
if ($endedPid > 0) {
unset($childProcesses[$endedPid]);
log_message("Processo filho $endedPid finalizado.", 'INFO');
}
}
log_message("Todas as tarefas foram submetidas para processamento.", 'INFO');
} else {
log_message("Nenhum arquivo pendente para processar.", 'INFO');
}
$mysqli->close();
log_message("Processamento da fila finalizado.", 'INFO');
?>
+81
View File
@@ -0,0 +1,81 @@
<?php
// Verificar se o usuário está logado
if (!isset($_SESSION['user_id'])) {
header("Location: login.php");
exit();
}
?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="UTF-8">
<title>Status do Processamento</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
.status { margin-top: 20px; }
.status p { margin: 5px 0; }
.completed { color: green; }
.pending { color: orange; }
.processing { color: blue; }
.error { color: red; }
.pagination { margin-top: 20px; text-align: center; }
.pagination a { margin: 0 5px; text-decoration: none; color: #007BFF; }
.pagination a:hover { text-decoration: underline; }
</style>
<script>
function checkStatus(page = 1) {
fetch(`./prova/status_check.php?page_num=${page}`)
.then(response => response.json())
.then(data => {
let statusContainer = document.getElementById('statusContainer');
statusContainer.innerHTML = '';
data.status.forEach(item => {
let p = document.createElement('p');
p.className = item.status;
p.textContent = `Arquivo: ${item.file_path} - Status: ${item.status}`;
statusContainer.appendChild(p);
});
// Paginação
let paginationContainer = document.getElementById('paginationContainer');
paginationContainer.innerHTML = '';
if (data.current_page > 1) {
let prevLink = document.createElement('a');
prevLink.href = `javascript:checkStatus(${data.current_page - 1})`;
prevLink.textContent = '« Anterior';
paginationContainer.appendChild(prevLink);
}
for (let i = 1; i <= data.total_pages; i++) {
let pageLink = document.createElement('a');
pageLink.href = `javascript:checkStatus(${i})`;
if (i === data.current_page) {
pageLink.style.fontWeight = 'bold';
}
pageLink.textContent = i;
paginationContainer.appendChild(pageLink);
}
if (data.current_page < data.total_pages) {
let nextLink = document.createElement('a');
nextLink.href = `javascript:checkStatus(${data.current_page + 1})`;
nextLink.textContent = 'Próximo »';
paginationContainer.appendChild(nextLink);
}
});
}
setInterval(() => checkStatus(), 15000); // Atualizar a cada 15 segundos
window.onload = () => checkStatus();
</script>
</head>
<body>
<div class="container">
<h2>Status do Processamento</h2>
<div id="statusContainer" class="status">
<!-- Status dos arquivos será exibido aqui -->
</div>
<div id="paginationContainer" class="pagination">
<!-- Paginação será exibida aqui -->
</div>
</div>
</body>
</html>
+34
View File
@@ -0,0 +1,34 @@
<?php
// status_check.php
// Conectar ao banco de dados
$mysqli = new mysqli("10.15.0.42", "root", "34641747", "valida");
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
// Paginação
$files_per_page = 10;
$page = isset($_GET['page_num']) ? (int)$_GET['page_num'] : 1;
$page = max(1, $page);
$offset = ($page - 1) * $files_per_page;
// Recuperar status dos arquivos
$result = $mysqli->query("SELECT file_path, status FROM queue ORDER BY created_at DESC LIMIT $files_per_page OFFSET $offset");
$status = [];
while ($row = $result->fetch_assoc()) {
$status[] = $row;
}
// Contar o total de arquivos para a paginação
$total_result = $mysqli->query("SELECT COUNT(*) AS total FROM queue");
$total_files = $total_result->fetch_assoc()['total'];
$total_pages = ceil($total_files / $files_per_page);
$mysqli->close();
header('Content-Type: application/json');
echo json_encode(['status' => $status, 'current_page' => $page, 'total_pages' => $total_pages]);
?>
+133
View File
@@ -0,0 +1,133 @@
<?php
// Configurações iniciais
date_default_timezone_set('America/Araguaina');
// Conectar ao banco de dados
$mysqli = new mysqli("10.15.0.42", "root", "34641747", "valida");
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
// Diretório de upload
$upload_dir = '/var/www/html/uploads/';
if (!is_dir($upload_dir)) {
mkdir($upload_dir, 0777, true);
}
// Tipos de arquivos permitidos
$allowed_types = ['image/jpeg', 'image/png', 'image/gif', 'application/pdf'];
$max_file_size = 10 * 1024 * 1024; // 10MB
// Ignorar autenticação para esta página
// if (basename($_SERVER['PHP_SELF']) == 'upload.php') {
// // Ignorar autenticação para esta página
// } else {
// // ...código de autenticação existente...
// }
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (isset($_FILES['files'])) {
$files = $_FILES['files'];
$modification_times = isset($_POST['modification_times']) ? explode(',', $_POST['modification_times']) : [];
// Capturar informações adicionais
$user_agent = isset($_POST['user_agent']) ? $_POST['user_agent'] : 'Desconhecido';
$language = isset($_POST['language']) ? $_POST['language'] : 'Desconhecido';
$viewport_width = isset($_POST['viewport_width']) ? intval($_POST['viewport_width']) : 0;
$viewport_height = isset($_POST['viewport_height']) ? intval($_POST['viewport_height']) : 0;
$ip_address = $_SERVER['REMOTE_ADDR'];
$host_name = gethostbyaddr($ip_address);
$access_time = date("Y-m-d H:i:s"); // Formato padrão MySQL
$referer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : 'Desconhecido';
$request_method = $_SERVER['REQUEST_METHOD'];
$server_software = isset($_SERVER['SERVER_SOFTWARE']) ? $_SERVER['SERVER_SOFTWARE'] : 'Desconhecido';
$protocol = isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'Desconhecido';
$connection = isset($_SERVER['HTTP_CONNECTION']) ? $_SERVER['HTTP_CONNECTION'] : 'Desconhecido';
$client_port = isset($_SERVER['REMOTE_PORT']) ? intval($_SERVER['REMOTE_PORT']) : 0;
for ($i = 0; $i < count($files['name']); $i++) {
$file_name = basename($files['name'][$i]);
$file_tmp = $files['tmp_name'][$i];
$file_size = $files['size'][$i];
$file_type = $files['type'][$i];
$file_error = $files['error'][$i];
$file_path = $upload_dir . $file_name;
// Validações
if ($file_error !== UPLOAD_ERR_OK) {
continue;
}
if ($file_size > $max_file_size) {
continue;
}
if (!in_array($file_type, $allowed_types)) {
continue;
}
// Movendo o arquivo
if (move_uploaded_file($file_tmp, $file_path)) {
// Ajustar a data de modificação usando touch()
if (isset($modification_times[$i])) {
$mod_time = intval($modification_times[$i] / 1000); // Convertendo de milissegundos para segundos
touch($file_path, $mod_time);
}
// Gerar hash do arquivo para integridade
$file_hash = hash_file('sha256', $file_path);
// Preparar inserção na tabela queue
$stmt = $mysqli->prepare("INSERT INTO queue (file_path, user_agent, ip_address, host_name, access_time, language, referer, request_method, server_software, protocol, connection, viewport_width, viewport_height, file_hash) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
if (!$stmt) {
unlink($file_path);
continue;
}
$stmt->bind_param(
"ssssssssssssss",
$file_path,
$user_agent,
$ip_address,
$host_name,
$access_time,
$language,
$referer,
$request_method,
$server_software,
$protocol,
$connection,
$viewport_width,
$viewport_height,
$file_hash
);
if ($stmt->execute()) {
$queue_id = $stmt->insert_id;
} else {
unlink($file_path);
$stmt->close();
continue;
}
$stmt->close();
// Adicionar entrada na tabela client_ports
$stmt_port = $mysqli->prepare("INSERT INTO client_ports (queue_id, port) VALUES (?, ?)");
if (!$stmt_port) {
continue;
}
$stmt_port->bind_param("ii", $queue_id, $client_port);
if ($stmt_port->execute()) {
} else {
}
$stmt_port->close();
} else {
}
}
}
}
$mysqli->close();
header("Location: /index.php?page=status");
exit();
?>
+211
View File
@@ -0,0 +1,211 @@
<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="UTF-8">
<title>Upload de Arquivos</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<?php
// Verificação de folhas de estilo previamente aplicadas
$hasStylesheet = false;
// Verificar se há elementos <link> ou <style> no documento
ob_start();
?>
<script>
document.addEventListener("DOMContentLoaded", function() {
var hasStylesheet = document.querySelector('link[rel="stylesheet"], style') !== null;
var xhr = new XMLHttpRequest();
xhr.open("POST", "", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send("hasStylesheet=" + hasStylesheet);
});
</script>
<?php
$script = ob_get_clean();
echo $script;
if (isset($_POST['hasStylesheet']) && $_POST['hasStylesheet'] === 'true') {
$hasStylesheet = true;
}
if (!$hasStylesheet) {
echo '<style>
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
margin: 0;
padding: 0;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
.container {
background-color: #fff;
padding: 20px;
border-radius: 8px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
width: 100%;
max-width: 500px;
text-align: center;
}
h2 {
margin-bottom: 20px;
color: #333;
}
label {
display: block;
margin-bottom: 10px;
color: #555;
}
.custom-file-input {
position: relative;
display: inline-block;
width: 100%;
height: 40px;
margin-bottom: 20px;
}
.custom-file-input input[type="file"] {
position: absolute;
width: 100%;
height: 100%;
opacity: 0;
cursor: pointer;
}
.custom-file-input::before {
content: "Escolher arquivos";
display: inline-block;
background: #007bff;
color: white;
border: none;
padding: 10px 20px;
border-radius: 5px;
cursor: pointer;
text-align: center;
width: 100%;
height: 100%;
line-height: 20px;
}
.custom-file-input input[type="file"]:focus + ::before {
outline: 1px dotted #000;
outline: -webkit-focus-ring-color auto 5px;
}
.custom-file-input input[type="file"]::after {
content: "Nenhum arquivo escolhido";
display: block;
margin-top: 10px;
color: #555;
}
button {
background-color: #007bff;
color: #fff;
border: none;
padding: 10px 20px;
border-radius: 5px;
cursor: pointer;
font-size: 16px;
margin-top: 10px;
}
button:hover {
background-color: #0056b3;
}
@media (max-width: 600px) {
body {
height: auto;
padding: 20px;
}
.container {
padding: 15px;
width: 100%;
}
h2 {
font-size: 18px;
}
button {
width: 100%;
padding: 12px;
font-size: 14px;
}
.custom-file-input::before {
padding: 12px;
font-size: 14px;
}
}
</style>';
}
?>
<script>
function addViewportDimensions() {
var form = document.getElementById('uploadForm');
var vw = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
var vh = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
var inputWidth = document.createElement('input');
inputWidth.type = 'hidden';
inputWidth.name = 'viewport_width';
inputWidth.value = vw;
form.appendChild(inputWidth);
var inputHeight = document.createElement('input');
inputHeight.type = 'hidden';
inputHeight.name = 'viewport_height';
inputHeight.value = vh;
form.appendChild(inputHeight);
var userAgent = navigator.userAgent;
var inputUserAgent = document.createElement('input');
inputUserAgent.type = 'hidden';
inputUserAgent.name = 'user_agent';
inputUserAgent.value = userAgent;
form.appendChild(inputUserAgent);
var language = navigator.language || navigator.userLanguage;
var inputLanguage = document.createElement('input');
inputLanguage.type = 'hidden';
inputLanguage.name = 'language';
inputLanguage.value = language;
form.appendChild(inputLanguage);
var files = document.getElementById('files').files;
var modificationTimes = [];
for (let i = 0; i < files.length; i++) {
const file = files[i];
const lastModified = file.lastModified ? file.lastModified : '';
modificationTimes.push(lastModified);
}
var inputModification = document.createElement('input');
inputModification.type = 'hidden';
inputModification.name = 'modification_times';
inputModification.value = modificationTimes.join(',');
form.appendChild(inputModification);
}
window.onload = function() {
var form = document.getElementById('uploadForm');
form.onsubmit = function(event) {
addViewportDimensions();
}
var fileInput = document.getElementById('files');
fileInput.addEventListener('change', function() {
var existingInputs = document.querySelectorAll('input[name="modification_times"]');
existingInputs.forEach(function(input) {
input.remove();
});
});
}
</script>
</head>
<body>
<div class="container">
<h2>Upload de Arquivos</h2>
<form id="uploadForm" action="./upload.php" method="post" enctype="multipart/form-data">
<label for="files">Selecione os arquivos para autenticar:</label><br><br>
<input type="file" name="files[]" id="files" multiple required><br><br>
<button type="submit">Autenticar</button>
</form>
</div>
</body>
</html>
+13023
View File
File diff suppressed because it is too large. Load diff
+121
View File
@@ -0,0 +1,121 @@
{
"name": "advx",
"version": "1.0.0",
"description": "Sistema de Gestão para Advocacia",
"main": "src/index.tsx",
"type": "commonjs",
"scripts": {
"dev": "vite",
"build": "tsc && vite build",
"preview": "vite preview",
"prisma:generate": "prisma generate",
"prisma:migrate": "prisma migrate dev",
"prisma:studio": "prisma studio",
"prisma:seed": "ts-node -T prisma/seed.ts",
"postinstall": "prisma generate && npx puppeteer browsers install chrome",
"server": "ts-node --transpile-only src/server/index.ts",
"dev:full": "concurrently -n \"frontend,backend\" -c \"blue,green\" \"npm run dev\" \"npm run server\"",
"lint": "eslint . --ext .ts,.tsx",
"lint:fix": "eslint . --ext .ts,.tsx --fix",
"create-admin": "ts-node scripts/create_admin_user.ts",
"worker": "ts-node src/workers/startWorker.ts",
"install-deps": "npm install ua-parser-js uuid axios xlsx"
},
"dependencies": {
"@emotion/react": "^11.11.3",
"@emotion/styled": "^11.11.3",
"@headlessui/react": "^1.7.18",
"@heroicons/react": "^2.1.1",
"@mui/icons-material": "^5.15.6",
"@mui/material": "^5.15.6",
"@mui/x-date-pickers": "^6.19.0",
"@prisma/client": "^6.5.0",
"@tinymce/tinymce-react": "^6.1.0",
"@tiptap/extension-link": "^2.11.7",
"@tiptap/react": "^2.11.7",
"@tiptap/starter-kit": "^2.11.7",
"@types/sharp": "^0.32.0",
"@types/ua-parser-js": "^0.7.36",
"axios": "^1.6.5",
"bcryptjs": "^2.4.3",
"buffer": "^6.0.3",
"bullmq": "^4.12.0",
"cors": "^2.8.5",
"date-fns": "^2.30.0",
"detect-file-type": "^0.2.3",
"dotenv": "^16.4.1",
"express": "^4.18.2",
"jsonwebtoken": "^9.0.2",
"multer": "^1.4.5-lts.1",
"opentimestamps-javascript": "^1.0.1",
"pdf-lib": "^1.17.1",
"puppeteer": "^24.5.0",
"qrcode": "^1.5.3",
"react": "^18.2.0",
"react-beautiful-dnd": "^13.1.1",
"react-dom": "^18.2.0",
"react-dropzone": "^14.3.8",
"react-hook-form": "^7.49.3",
"react-icons": "^5.0.1",
"react-query": "^3.39.3",
"react-router-dom": "^7.4.1",
"react-toastify": "^10.0.4",
"redis": "^4.6.10",
"sharp": "^0.33.2",
"ua-parser-js": "^1.0.35",
"uuid": "^9.0.1",
"webdav": "^5.3.1",
"xlsx": "^0.18.5",
"zod": "^3.22.4"
},
"devDependencies": {
"@tailwindcss/postcss": "^4.1.1",
"@types/bcryptjs": "^2.4.6",
"@types/cors": "^2.8.17",
"@types/express": "^5.0.1",
"@types/jsonwebtoken": "^9.0.9",
"@types/multer": "^1.4.12",
"@types/node": "^22.13.14",
"@types/react": "^19.0.12",
"@types/react-beautiful-dnd": "^13.1.8",
"@types/react-dom": "^19.0.4",
"@types/uuid": "^10.0.0",
"@typescript-eslint/eslint-plugin": "^8.28.0",
"@typescript-eslint/parser": "^8.28.0",
"@vitejs/plugin-react": "^4.3.4",
"autoprefixer": "^10.4.17",
"concurrently": "^9.1.2",
"eslint": "^9.23.0",
"eslint-config-prettier": "^10.1.1",
"eslint-plugin-prettier": "^5.2.5",
"eslint-plugin-react": "^7.37.4",
"eslint-plugin-react-hooks": "^5.2.0",
"postcss": "^8.4.33",
"prettier": "^3.5.3",
"prisma": "^6.5.0",
"tailwindcss": "^3.4.1",
"ts-node": "^10.9.2",
"typescript": "^5.8.2",
"vite": "^6.2.4"
},
"prisma": {
"seed": "ts-node prisma/seed.ts"
},
"puppeteer": {
"headless": true,
"args": [
"--no-sandbox",
"--disable-setuid-sandbox",
"--disable-dev-shm-usage",
"--disable-accelerated-2d-canvas",
"--disable-gpu",
"--window-size=1920x1080"
]
},
"puppeteerOptions": {
"browserFetcher": {
"platform": "win32",
"downloadPath": ".cache/puppeteer"
}
}
}
+7
View File
@@ -0,0 +1,7 @@
module.exports = {
plugins: {
'tailwindcss/nesting': {},
tailwindcss: {},
autoprefixer: {},
},
}
@@ -0,0 +1,14 @@
-- CreateTable
CREATE TABLE "usuarios" (
"id" TEXT NOT NULL,
"nome" TEXT NOT NULL,
"email" TEXT NOT NULL,
"senha" TEXT NOT NULL,
"cargo" TEXT NOT NULL,
"dataCriacao" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "usuarios_pkey" PRIMARY KEY ("id")
);
-- CreateIndex
CREATE UNIQUE INDEX "usuarios_email_key" ON "usuarios"("email");
@@ -0,0 +1,33 @@
-- CreateTable
CREATE TABLE "clientes" (
"id" TEXT NOT NULL,
"nome" TEXT NOT NULL,
"email" TEXT NOT NULL,
"cpfCnpj" TEXT NOT NULL,
"telefone" TEXT NOT NULL,
"endereco" TEXT NOT NULL,
"dataCriacao" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "clientes_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "processos" (
"id" TEXT NOT NULL,
"numero" TEXT NOT NULL,
"titulo" TEXT NOT NULL,
"descricao" TEXT NOT NULL,
"clienteId" TEXT NOT NULL,
"advogadoResponsavelId" TEXT NOT NULL,
"status" TEXT NOT NULL,
"dataCriacao" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"dataAtualizacao" TIMESTAMP(3) NOT NULL,
CONSTRAINT "processos_pkey" PRIMARY KEY ("id")
);
-- CreateIndex
CREATE UNIQUE INDEX "clientes_cpfCnpj_key" ON "clientes"("cpfCnpj");
-- AddForeignKey
ALTER TABLE "processos" ADD CONSTRAINT "processos_clienteId_fkey" FOREIGN KEY ("clienteId") REFERENCES "clientes"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
@@ -0,0 +1,47 @@
/*
Warnings:
- Added the required column `bairro` to the `clientes` table without a default value. This is not possible if the table is not empty.
- Added the required column `cep` to the `clientes` table without a default value. This is not possible if the table is not empty.
- Added the required column `cidade` to the `clientes` table without a default value. This is not possible if the table is not empty.
- Added the required column `estado` to the `clientes` table without a default value. This is not possible if the table is not empty.
- Added the required column `numero` to the `clientes` table without a default value. This is not possible if the table is not empty.
*/
-- AlterTable
ALTER TABLE "clientes" ADD COLUMN "bairro" TEXT NOT NULL,
ADD COLUMN "cep" TEXT NOT NULL,
ADD COLUMN "cidade" TEXT NOT NULL,
ADD COLUMN "complemento" TEXT,
ADD COLUMN "conjugeCpf" TEXT,
ADD COLUMN "conjugeNome" TEXT,
ADD COLUMN "contribuiPrevidencia" BOOLEAN NOT NULL DEFAULT false,
ADD COLUMN "dataNascimento" TIMESTAMP(3),
ADD COLUMN "declaraIR" BOOLEAN NOT NULL DEFAULT false,
ADD COLUMN "estado" TEXT NOT NULL,
ADD COLUMN "estadoCivil" TEXT,
ADD COLUMN "instagram" TEXT,
ADD COLUMN "nomeMae" TEXT,
ADD COLUMN "nomePai" TEXT,
ADD COLUMN "numero" TEXT NOT NULL,
ADD COLUMN "orgaoEmissor" TEXT,
ADD COLUMN "possuiFilhos" BOOLEAN NOT NULL DEFAULT false,
ADD COLUMN "profissao" TEXT,
ADD COLUMN "renda" DECIMAL(65,30),
ADD COLUMN "rg" TEXT,
ADD COLUMN "tipoPrevidencia" TEXT,
ADD COLUMN "usaDNI" BOOLEAN NOT NULL DEFAULT false,
ADD COLUMN "vinculoEmpregaticio" TEXT;
-- CreateTable
CREATE TABLE "filhos" (
"id" TEXT NOT NULL,
"nome" TEXT NOT NULL,
"dataNascimento" TIMESTAMP(3) NOT NULL,
"clienteId" TEXT NOT NULL,
CONSTRAINT "filhos_pkey" PRIMARY KEY ("id")
);
-- AddForeignKey
ALTER TABLE "filhos" ADD CONSTRAINT "filhos_clienteId_fkey" FOREIGN KEY ("clienteId") REFERENCES "clientes"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
@@ -0,0 +1,2 @@
-- AlterTable
ALTER TABLE "clientes" ADD COLUMN "estadoRg" TEXT;
@@ -0,0 +1,2 @@
-- AlterTable
ALTER TABLE "clientes" ALTER COLUMN "tipoPrevidencia" SET DEFAULT 'NAO_CONTRIBUI';
@@ -0,0 +1,11 @@
/*
Warnings:
- You are about to alter the column `rg` on the `clientes` table. The data in that column could be lost. The data in that column will be cast from `Text` to `VarChar(10)`.
- You are about to alter the column `estadoRg` on the `clientes` table. The data in that column could be lost. The data in that column will be cast from `Text` to `Char(2)`.
*/
-- AlterTable
ALTER TABLE "clientes" ALTER COLUMN "dataNascimento" SET DATA TYPE DATE,
ALTER COLUMN "rg" SET DATA TYPE VARCHAR(10),
ALTER COLUMN "estadoRg" SET DATA TYPE CHAR(2);
@@ -0,0 +1,51 @@
/*
Warnings:
- You are about to alter the column `nome` on the `clientes` table. The data in that column could be lost. The data in that column will be cast from `Text` to `VarChar(100)`.
- You are about to alter the column `email` on the `clientes` table. The data in that column could be lost. The data in that column will be cast from `Text` to `VarChar(100)`.
- You are about to alter the column `cpfCnpj` on the `clientes` table. The data in that column could be lost. The data in that column will be cast from `Text` to `VarChar(18)`.
- You are about to alter the column `telefone` on the `clientes` table. The data in that column could be lost. The data in that column will be cast from `Text` to `VarChar(20)`.
- You are about to alter the column `endereco` on the `clientes` table. The data in that column could be lost. The data in that column will be cast from `Text` to `VarChar(150)`.
- You are about to alter the column `bairro` on the `clientes` table. The data in that column could be lost. The data in that column will be cast from `Text` to `VarChar(100)`.
- You are about to alter the column `cep` on the `clientes` table. The data in that column could be lost. The data in that column will be cast from `Text` to `VarChar(9)`.
- You are about to alter the column `cidade` on the `clientes` table. The data in that column could be lost. The data in that column will be cast from `Text` to `VarChar(100)`.
- You are about to alter the column `complemento` on the `clientes` table. The data in that column could be lost. The data in that column will be cast from `Text` to `VarChar(50)`.
- You are about to alter the column `conjugeCpf` on the `clientes` table. The data in that column could be lost. The data in that column will be cast from `Text` to `VarChar(14)`.
- You are about to alter the column `conjugeNome` on the `clientes` table. The data in that column could be lost. The data in that column will be cast from `Text` to `VarChar(100)`.
- You are about to alter the column `estado` on the `clientes` table. The data in that column could be lost. The data in that column will be cast from `Text` to `Char(2)`.
- You are about to alter the column `estadoCivil` on the `clientes` table. The data in that column could be lost. The data in that column will be cast from `Text` to `VarChar(20)`.
- You are about to alter the column `instagram` on the `clientes` table. The data in that column could be lost. The data in that column will be cast from `Text` to `VarChar(50)`.
- You are about to alter the column `nomeMae` on the `clientes` table. The data in that column could be lost. The data in that column will be cast from `Text` to `VarChar(100)`.
- You are about to alter the column `nomePai` on the `clientes` table. The data in that column could be lost. The data in that column will be cast from `Text` to `VarChar(100)`.
- You are about to alter the column `numero` on the `clientes` table. The data in that column could be lost. The data in that column will be cast from `Text` to `VarChar(10)`.
- You are about to alter the column `orgaoEmissor` on the `clientes` table. The data in that column could be lost. The data in that column will be cast from `Text` to `VarChar(10)`.
- You are about to alter the column `profissao` on the `clientes` table. The data in that column could be lost. The data in that column will be cast from `Text` to `VarChar(100)`.
- You are about to alter the column `renda` on the `clientes` table. The data in that column could be lost. The data in that column will be cast from `Decimal(65,30)` to `Decimal(10,2)`.
- You are about to alter the column `tipoPrevidencia` on the `clientes` table. The data in that column could be lost. The data in that column will be cast from `Text` to `VarChar(20)`.
- You are about to alter the column `vinculoEmpregaticio` on the `clientes` table. The data in that column could be lost. The data in that column will be cast from `Text` to `VarChar(50)`.
*/
-- AlterTable
ALTER TABLE "clientes" ALTER COLUMN "nome" SET DATA TYPE VARCHAR(100),
ALTER COLUMN "email" SET DATA TYPE VARCHAR(100),
ALTER COLUMN "cpfCnpj" SET DATA TYPE VARCHAR(18),
ALTER COLUMN "telefone" SET DATA TYPE VARCHAR(20),
ALTER COLUMN "endereco" SET DATA TYPE VARCHAR(150),
ALTER COLUMN "bairro" SET DATA TYPE VARCHAR(100),
ALTER COLUMN "cep" SET DATA TYPE VARCHAR(9),
ALTER COLUMN "cidade" SET DATA TYPE VARCHAR(100),
ALTER COLUMN "complemento" SET DATA TYPE VARCHAR(50),
ALTER COLUMN "conjugeCpf" SET DATA TYPE VARCHAR(14),
ALTER COLUMN "conjugeNome" SET DATA TYPE VARCHAR(100),
ALTER COLUMN "estado" SET DATA TYPE CHAR(2),
ALTER COLUMN "estadoCivil" SET DATA TYPE VARCHAR(20),
ALTER COLUMN "instagram" SET DATA TYPE VARCHAR(50),
ALTER COLUMN "nomeMae" SET DATA TYPE VARCHAR(100),
ALTER COLUMN "nomePai" SET DATA TYPE VARCHAR(100),
ALTER COLUMN "numero" SET DATA TYPE VARCHAR(10),
ALTER COLUMN "orgaoEmissor" SET DATA TYPE VARCHAR(10),
ALTER COLUMN "profissao" SET DATA TYPE VARCHAR(100),
ALTER COLUMN "renda" SET DATA TYPE DECIMAL(10,2),
ALTER COLUMN "rg" SET DATA TYPE VARCHAR(20),
ALTER COLUMN "tipoPrevidencia" SET DATA TYPE VARCHAR(20),
ALTER COLUMN "vinculoEmpregaticio" SET DATA TYPE VARCHAR(50);
@@ -0,0 +1,123 @@
/*
Warnings:
- You are about to drop the column `advogadoResponsavelId` on the `processos` table. All the data in the column will be lost.
- You are about to drop the column `descricao` on the `processos` table. All the data in the column will be lost.
- You are about to drop the column `titulo` on the `processos` table. All the data in the column will be lost.
- The `status` column on the `processos` table would be dropped and recreated. This will lead to data loss if there is data in the column.
- A unique constraint covering the columns `[numero]` on the table `processos` will be added. If there are existing duplicate values, this will fail.
*/
-- CreateEnum
CREATE TYPE "NaturezaProcesso" AS ENUM ('CIVEL', 'CRIMINAL', 'PREVIDENCIARIO', 'TRABALHISTA', 'FAMILIA', 'TRIBUTARIO', 'ADMINISTRATIVO');
-- CreateEnum
CREATE TYPE "TipoParte" AS ENUM ('AUTOR', 'REU');
-- CreateEnum
CREATE TYPE "StatusProcesso" AS ENUM ('INICIAL', 'EM_ANDAMENTO', 'SUSPENSO', 'RECURSO', 'CONCLUSO', 'ARQUIVADO');
-- CreateEnum
CREATE TYPE "TipoDiligencia" AS ENUM ('CITACAO', 'INTIMACAO', 'NOTIFICACAO', 'PERICIA', 'OFICIAL_JUSTICA', 'CARTA_PRECATORIA', 'OUTROS');
-- CreateEnum
CREATE TYPE "TipoAudiencia" AS ENUM ('CONCILIACAO', 'INSTRUCAO', 'INICIAL', 'JULGAMENTO', 'MEDIACAO');
-- AlterTable
ALTER TABLE "processos" DROP COLUMN "advogadoResponsavelId",
DROP COLUMN "descricao",
DROP COLUMN "titulo",
ADD COLUMN "natureza" "NaturezaProcesso",
ADD COLUMN "nomeContraparte" VARCHAR(100),
ADD COLUMN "orgaoJulgador" VARCHAR(100),
ADD COLUMN "orgaoOrigem" VARCHAR(100),
ADD COLUMN "tipoParteCliente" "TipoParte",
ADD COLUMN "valorCausa" DECIMAL(15,2),
DROP COLUMN "status",
ADD COLUMN "status" "StatusProcesso" NOT NULL DEFAULT 'INICIAL';
-- CreateTable
CREATE TABLE "documentos" (
"id" TEXT NOT NULL,
"processoId" TEXT NOT NULL,
"nome" VARCHAR(200) NOT NULL,
"tipo" VARCHAR(50) NOT NULL,
"url" TEXT NOT NULL,
"dataCriacao" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "documentos_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "diligencias" (
"id" TEXT NOT NULL,
"processoId" TEXT NOT NULL,
"tipo" "TipoDiligencia" NOT NULL,
"descricao" TEXT NOT NULL,
"dataLimite" TIMESTAMP(3) NOT NULL,
"status" TEXT DEFAULT 'PENDENTE',
"responsavel" VARCHAR(100),
"observacoes" TEXT,
"dataCriacao" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "diligencias_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "audiencias" (
"id" TEXT NOT NULL,
"processoId" TEXT NOT NULL,
"tipo" "TipoAudiencia" NOT NULL,
"data" TIMESTAMP(3) NOT NULL,
"local" VARCHAR(200) NOT NULL,
"modalidade" TEXT DEFAULT 'PRESENCIAL',
"linkVirtual" TEXT,
"observacoes" TEXT,
"status" TEXT DEFAULT 'AGENDADA',
"dataCriacao" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "audiencias_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "movimentacoes" (
"id" TEXT NOT NULL,
"processoId" TEXT NOT NULL,
"data" TIMESTAMP(3) NOT NULL,
"descricao" TEXT NOT NULL,
"tipo" VARCHAR(50) NOT NULL,
"documento" TEXT,
"dataCriacao" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "movimentacoes_pkey" PRIMARY KEY ("id")
);
-- CreateIndex
CREATE INDEX "documentos_processoId_idx" ON "documentos"("processoId");
-- CreateIndex
CREATE INDEX "diligencias_dataLimite_idx" ON "diligencias"("dataLimite");
-- CreateIndex
CREATE INDEX "audiencias_data_idx" ON "audiencias"("data");
-- CreateIndex
CREATE INDEX "movimentacoes_data_idx" ON "movimentacoes"("data");
-- CreateIndex
CREATE UNIQUE INDEX "processos_numero_key" ON "processos"("numero");
-- CreateIndex
CREATE INDEX "processos_numero_idx" ON "processos"("numero");
-- AddForeignKey
ALTER TABLE "documentos" ADD CONSTRAINT "documentos_processoId_fkey" FOREIGN KEY ("processoId") REFERENCES "processos"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "diligencias" ADD CONSTRAINT "diligencias_processoId_fkey" FOREIGN KEY ("processoId") REFERENCES "processos"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "audiencias" ADD CONSTRAINT "audiencias_processoId_fkey" FOREIGN KEY ("processoId") REFERENCES "processos"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "movimentacoes" ADD CONSTRAINT "movimentacoes_processoId_fkey" FOREIGN KEY ("processoId") REFERENCES "processos"("id") ON DELETE CASCADE ON UPDATE CASCADE;
@@ -0,0 +1,103 @@
-- CreateEnum
CREATE TYPE "StatusAtividade" AS ENUM ('ATIVO', 'BAIXADO', 'SUSPENSO');
-- AlterTable
ALTER TABLE "processos" ADD COLUMN "assuntoCNJ" VARCHAR(100),
ADD COLUMN "codigoAssuntoCNJ" VARCHAR(20),
ADD COLUMN "eventoCalendarioId" TEXT,
ADD COLUMN "orgaoJulgadorId" TEXT,
ADD COLUMN "statusAtividade" "StatusAtividade" NOT NULL DEFAULT 'ATIVO',
ADD COLUMN "ultimaConsulta" TIMESTAMP(3);
-- CreateTable
CREATE TABLE "custas_processuais" (
"id" TEXT NOT NULL,
"processoId" TEXT NOT NULL,
"tipo" VARCHAR(50) NOT NULL,
"valor" DECIMAL(10,2) NOT NULL,
"dataPagamento" TIMESTAMP(3),
"comprovante" TEXT,
"status" TEXT NOT NULL DEFAULT 'PENDENTE',
"dataCriacao" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "custas_processuais_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "honorarios" (
"id" TEXT NOT NULL,
"processoId" TEXT NOT NULL,
"valor" DECIMAL(10,2) NOT NULL,
"parcelas" INTEGER NOT NULL DEFAULT 1,
"dataVencimento" TIMESTAMP(3) NOT NULL,
"status" TEXT NOT NULL DEFAULT 'PENDENTE',
"observacoes" TEXT,
"dataCriacao" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "honorarios_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "modelos_documentos" (
"id" TEXT NOT NULL,
"nome" VARCHAR(100) NOT NULL,
"tipo" VARCHAR(50) NOT NULL,
"conteudo" TEXT NOT NULL,
"variaveis" TEXT[],
"dataCriacao" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "modelos_documentos_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "alertas" (
"id" TEXT NOT NULL,
"usuarioId" TEXT NOT NULL,
"tipo" VARCHAR(50) NOT NULL,
"mensagem" TEXT NOT NULL,
"lido" BOOLEAN NOT NULL DEFAULT false,
"dataAlerta" TIMESTAMP(3) NOT NULL,
"dataCriacao" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "alertas_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "movimentacoes_tribunal" (
"id" TEXT NOT NULL,
"processoId" TEXT NOT NULL,
"tribunal" VARCHAR(50) NOT NULL,
"dataMovimentacao" TIMESTAMP(3) NOT NULL,
"tipo" VARCHAR(100) NOT NULL,
"conteudo" TEXT NOT NULL,
"dataCriacao" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "movimentacoes_tribunal_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "orgaos_julgadores" (
"id" TEXT NOT NULL,
"nome" VARCHAR(200) NOT NULL,
"dataCriacao" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "orgaos_julgadores_pkey" PRIMARY KEY ("id")
);
-- CreateIndex
CREATE UNIQUE INDEX "orgaos_julgadores_nome_key" ON "orgaos_julgadores"("nome");
-- CreateIndex
CREATE INDEX "processos_orgaoJulgadorId_idx" ON "processos"("orgaoJulgadorId");
-- AddForeignKey
ALTER TABLE "processos" ADD CONSTRAINT "processos_orgaoJulgadorId_fkey" FOREIGN KEY ("orgaoJulgadorId") REFERENCES "orgaos_julgadores"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "custas_processuais" ADD CONSTRAINT "custas_processuais_processoId_fkey" FOREIGN KEY ("processoId") REFERENCES "processos"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "honorarios" ADD CONSTRAINT "honorarios_processoId_fkey" FOREIGN KEY ("processoId") REFERENCES "processos"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "movimentacoes_tribunal" ADD CONSTRAINT "movimentacoes_tribunal_processoId_fkey" FOREIGN KEY ("processoId") REFERENCES "processos"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
@@ -0,0 +1,10 @@
/*
Warnings:
- You are about to drop the column `assuntoCNJ` on the `processos` table. All the data in the column will be lost.
- You are about to drop the column `codigoAssuntoCNJ` on the `processos` table. All the data in the column will be lost.
*/
-- AlterTable
ALTER TABLE "processos" DROP COLUMN "assuntoCNJ",
DROP COLUMN "codigoAssuntoCNJ";
@@ -0,0 +1,21 @@
/*
Warnings:
- You are about to drop the column `eventoCalendarioId` on the `processos` table. All the data in the column will be lost.
- You are about to drop the column `ultimaConsulta` on the `processos` table. All the data in the column will be lost.
- Made the column `natureza` on table `processos` required. This step will fail if there are existing NULL values in that column.
- Made the column `nomeContraparte` on table `processos` required. This step will fail if there are existing NULL values in that column.
- Made the column `orgaoJulgador` on table `processos` required. This step will fail if there are existing NULL values in that column.
- Made the column `tipoParteCliente` on table `processos` required. This step will fail if there are existing NULL values in that column.
*/
-- DropIndex
DROP INDEX "processos_orgaoJulgadorId_idx";
-- AlterTable
ALTER TABLE "processos" DROP COLUMN "eventoCalendarioId",
DROP COLUMN "ultimaConsulta",
ALTER COLUMN "natureza" SET NOT NULL,
ALTER COLUMN "nomeContraparte" SET NOT NULL,
ALTER COLUMN "orgaoJulgador" SET NOT NULL,
ALTER COLUMN "tipoParteCliente" SET NOT NULL;
@@ -0,0 +1,29 @@
-- CreateEnum
CREATE TYPE "TipoParticipacao" AS ENUM ('AUTOR', 'REU', 'TERCEIRO_INTERESSADO');
-- CreateTable
CREATE TABLE "partes_processo" (
"id" TEXT NOT NULL,
"processoId" TEXT NOT NULL,
"clienteId" TEXT,
"tipo" "TipoParticipacao" NOT NULL,
"nome" VARCHAR(200) NOT NULL,
"cpfCnpj" VARCHAR(18),
"principal" BOOLEAN NOT NULL DEFAULT false,
"observacoes" TEXT,
"dataCriacao" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "partes_processo_pkey" PRIMARY KEY ("id")
);
-- CreateIndex
CREATE INDEX "partes_processo_processoId_idx" ON "partes_processo"("processoId");
-- CreateIndex
CREATE INDEX "partes_processo_clienteId_idx" ON "partes_processo"("clienteId");
-- AddForeignKey
ALTER TABLE "partes_processo" ADD CONSTRAINT "partes_processo_processoId_fkey" FOREIGN KEY ("processoId") REFERENCES "processos"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "partes_processo" ADD CONSTRAINT "partes_processo_clienteId_fkey" FOREIGN KEY ("clienteId") REFERENCES "clientes"("id") ON DELETE SET NULL ON UPDATE CASCADE;
@@ -0,0 +1,379 @@
/*
Warnings:
- The primary key for the `alertas` table will be changed. If it partially fails, the table could be left without primary key constraint.
- The `id` column on the `alertas` table would be dropped and recreated. This will lead to data loss if there is data in the column.
- The primary key for the `clientes` table will be changed. If it partially fails, the table could be left without primary key constraint.
- The `id` column on the `clientes` table would be dropped and recreated. This will lead to data loss if there is data in the column.
- The primary key for the `custas_processuais` table will be changed. If it partially fails, the table could be left without primary key constraint.
- The `id` column on the `custas_processuais` table would be dropped and recreated. This will lead to data loss if there is data in the column.
- The `status` column on the `custas_processuais` table would be dropped and recreated. This will lead to data loss if there is data in the column.
- The primary key for the `filhos` table will be changed. If it partially fails, the table could be left without primary key constraint.
- The `id` column on the `filhos` table would be dropped and recreated. This will lead to data loss if there is data in the column.
- The primary key for the `honorarios` table will be changed. If it partially fails, the table could be left without primary key constraint.
- You are about to drop the column `parcelas` on the `honorarios` table. All the data in the column will be lost.
- You are about to drop the column `valor` on the `honorarios` table. All the data in the column will be lost.
- The `id` column on the `honorarios` table would be dropped and recreated. This will lead to data loss if there is data in the column.
- The `status` column on the `honorarios` table would be dropped and recreated. This will lead to data loss if there is data in the column.
- The primary key for the `modelos_documentos` table will be changed. If it partially fails, the table could be left without primary key constraint.
- The `id` column on the `modelos_documentos` table would be dropped and recreated. This will lead to data loss if there is data in the column.
- The primary key for the `orgaos_julgadores` table will be changed. If it partially fails, the table could be left without primary key constraint.
- The `id` column on the `orgaos_julgadores` table would be dropped and recreated. This will lead to data loss if there is data in the column.
- The primary key for the `usuarios` table will be changed. If it partially fails, the table could be left without primary key constraint.
- The `id` column on the `usuarios` table would be dropped and recreated. This will lead to data loss if there is data in the column.
- You are about to drop the `audiencias` table. If the table is not empty, all the data it contains will be lost.
- You are about to drop the `diligencias` table. If the table is not empty, all the data it contains will be lost.
- You are about to drop the `documentos` table. If the table is not empty, all the data it contains will be lost.
- You are about to drop the `movimentacoes` table. If the table is not empty, all the data it contains will be lost.
- You are about to drop the `movimentacoes_tribunal` table. If the table is not empty, all the data it contains will be lost.
- You are about to drop the `partes_processo` table. If the table is not empty, all the data it contains will be lost.
- You are about to drop the `processos` table. If the table is not empty, all the data it contains will be lost.
- Changed the type of `usuarioId` on the `alertas` table. No cast exists, the column would be dropped and recreated, which cannot be done if there is data, since the column is required.
- Added the required column `descricao` to the `custas_processuais` table without a default value. This is not possible if the table is not empty.
- Changed the type of `processoId` on the `custas_processuais` table. No cast exists, the column would be dropped and recreated, which cannot be done if there is data, since the column is required.
- Changed the type of `tipo` on the `custas_processuais` table. No cast exists, the column would be dropped and recreated, which cannot be done if there is data, since the column is required.
- Changed the type of `clienteId` on the `filhos` table. No cast exists, the column would be dropped and recreated, which cannot be done if there is data, since the column is required.
- Changed the type of `processoId` on the `honorarios` table. No cast exists, the column would be dropped and recreated, which cannot be done if there is data, since the column is required.
*/
-- CreateEnum
CREATE TYPE "TipoCustaProcessual" AS ENUM ('INICIAL', 'RECURSO', 'PERICIA', 'OFICIAL_JUSTICA', 'CARTA_PRECATORIA', 'DEPOSITO_JUDICIAL', 'CERTIDAO', 'DIGITALIZACAO', 'CONDUTOR', 'CORREIOS', 'CARTORIO', 'OUTROS');
-- CreateEnum
CREATE TYPE "StatusPagamento" AS ENUM ('PENDENTE', 'PARCIALMENTE_PAGO', 'PAGO', 'VENCIDO', 'CANCELADO');
-- CreateEnum
CREATE TYPE "FormaPagamento" AS ENUM ('VISTA', 'PARCELADO', 'ENTRADA_MAIS_PARCELAS', 'PERCENTUAL_CAUSA', 'PERCENTUAL_EXITO');
-- DropForeignKey
ALTER TABLE "audiencias" DROP CONSTRAINT "audiencias_processoId_fkey";
-- DropForeignKey
ALTER TABLE "custas_processuais" DROP CONSTRAINT "custas_processuais_processoId_fkey";
-- DropForeignKey
ALTER TABLE "diligencias" DROP CONSTRAINT "diligencias_processoId_fkey";
-- DropForeignKey
ALTER TABLE "documentos" DROP CONSTRAINT "documentos_processoId_fkey";
-- DropForeignKey
ALTER TABLE "filhos" DROP CONSTRAINT "filhos_clienteId_fkey";
-- DropForeignKey
ALTER TABLE "honorarios" DROP CONSTRAINT "honorarios_processoId_fkey";
-- DropForeignKey
ALTER TABLE "movimentacoes" DROP CONSTRAINT "movimentacoes_processoId_fkey";
-- DropForeignKey
ALTER TABLE "movimentacoes_tribunal" DROP CONSTRAINT "movimentacoes_tribunal_processoId_fkey";
-- DropForeignKey
ALTER TABLE "partes_processo" DROP CONSTRAINT "partes_processo_clienteId_fkey";
-- DropForeignKey
ALTER TABLE "partes_processo" DROP CONSTRAINT "partes_processo_processoId_fkey";
-- DropForeignKey
ALTER TABLE "processos" DROP CONSTRAINT "processos_clienteId_fkey";
-- DropForeignKey
ALTER TABLE "processos" DROP CONSTRAINT "processos_orgaoJulgadorId_fkey";
-- AlterTable
ALTER TABLE "alertas" DROP CONSTRAINT "alertas_pkey",
DROP COLUMN "id",
ADD COLUMN "id" UUID NOT NULL DEFAULT gen_random_uuid(),
DROP COLUMN "usuarioId",
ADD COLUMN "usuarioId" UUID NOT NULL,
ADD CONSTRAINT "alertas_pkey" PRIMARY KEY ("id");
-- AlterTable
ALTER TABLE "clientes" DROP CONSTRAINT "clientes_pkey",
DROP COLUMN "id",
ADD COLUMN "id" UUID NOT NULL DEFAULT gen_random_uuid(),
ADD CONSTRAINT "clientes_pkey" PRIMARY KEY ("id");
-- AlterTable
ALTER TABLE "custas_processuais" DROP CONSTRAINT "custas_processuais_pkey",
ADD COLUMN "descricao" VARCHAR(200) NOT NULL,
ADD COLUMN "numeroParcelas" INTEGER NOT NULL DEFAULT 1,
ADD COLUMN "observacoes" TEXT,
ADD COLUMN "parcelaAtual" INTEGER NOT NULL DEFAULT 1,
ADD COLUMN "percentual" DECIMAL(5,2),
ADD COLUMN "vencimento" TIMESTAMP(3),
DROP COLUMN "id",
ADD COLUMN "id" UUID NOT NULL DEFAULT gen_random_uuid(),
DROP COLUMN "processoId",
ADD COLUMN "processoId" UUID NOT NULL,
DROP COLUMN "tipo",
ADD COLUMN "tipo" "TipoCustaProcessual" NOT NULL,
DROP COLUMN "status",
ADD COLUMN "status" "StatusPagamento" NOT NULL DEFAULT 'PENDENTE',
ADD CONSTRAINT "custas_processuais_pkey" PRIMARY KEY ("id");
-- AlterTable
ALTER TABLE "filhos" DROP CONSTRAINT "filhos_pkey",
DROP COLUMN "id",
ADD COLUMN "id" UUID NOT NULL DEFAULT gen_random_uuid(),
DROP COLUMN "clienteId",
ADD COLUMN "clienteId" UUID NOT NULL,
ADD CONSTRAINT "filhos_pkey" PRIMARY KEY ("id");
-- AlterTable
ALTER TABLE "honorarios" DROP CONSTRAINT "honorarios_pkey",
DROP COLUMN "parcelas",
DROP COLUMN "valor",
ADD COLUMN "dataContrato" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
ADD COLUMN "diaVencimento" INTEGER NOT NULL DEFAULT 10,
ADD COLUMN "formaPagamento" "FormaPagamento" NOT NULL DEFAULT 'VISTA',
ADD COLUMN "numeroParcelas" INTEGER NOT NULL DEFAULT 1,
ADD COLUMN "percentualCausa" DECIMAL(5,2),
ADD COLUMN "percentualExito" DECIMAL(5,2),
ADD COLUMN "valorEntrada" DECIMAL(10,2),
ADD COLUMN "valorFixo" DECIMAL(10,2),
ADD COLUMN "valorParcela" DECIMAL(10,2),
DROP COLUMN "id",
ADD COLUMN "id" UUID NOT NULL DEFAULT gen_random_uuid(),
DROP COLUMN "processoId",
ADD COLUMN "processoId" UUID NOT NULL,
DROP COLUMN "status",
ADD COLUMN "status" "StatusPagamento" NOT NULL DEFAULT 'PENDENTE',
ADD CONSTRAINT "honorarios_pkey" PRIMARY KEY ("id");
-- AlterTable
ALTER TABLE "modelos_documentos" DROP CONSTRAINT "modelos_documentos_pkey",
DROP COLUMN "id",
ADD COLUMN "id" UUID NOT NULL DEFAULT gen_random_uuid(),
ADD CONSTRAINT "modelos_documentos_pkey" PRIMARY KEY ("id");
-- AlterTable
ALTER TABLE "orgaos_julgadores" DROP CONSTRAINT "orgaos_julgadores_pkey",
DROP COLUMN "id",
ADD COLUMN "id" UUID NOT NULL DEFAULT gen_random_uuid(),
ADD CONSTRAINT "orgaos_julgadores_pkey" PRIMARY KEY ("id");
-- AlterTable
ALTER TABLE "usuarios" DROP CONSTRAINT "usuarios_pkey",
DROP COLUMN "id",
ADD COLUMN "id" UUID NOT NULL DEFAULT gen_random_uuid(),
ADD CONSTRAINT "usuarios_pkey" PRIMARY KEY ("id");
-- DropTable
DROP TABLE "audiencias";
-- DropTable
DROP TABLE "diligencias";
-- DropTable
DROP TABLE "documentos";
-- DropTable
DROP TABLE "movimentacoes";
-- DropTable
DROP TABLE "movimentacoes_tribunal";
-- DropTable
DROP TABLE "partes_processo";
-- DropTable
DROP TABLE "processos";
-- CreateTable
CREATE TABLE "ParteProcesso" (
"id" UUID NOT NULL DEFAULT gen_random_uuid(),
"processoId" UUID NOT NULL,
"clienteId" UUID,
"tipo" VARCHAR(20) NOT NULL,
"nome" VARCHAR(200) NOT NULL,
"cpfCnpj" VARCHAR(18),
"principal" BOOLEAN NOT NULL DEFAULT false,
"observacoes" TEXT,
"dataCriacao" TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "ParteProcesso_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "Processo" (
"id" UUID NOT NULL DEFAULT gen_random_uuid(),
"numero" TEXT NOT NULL,
"natureza" TEXT NOT NULL,
"valorCausa" DECIMAL(15,2),
"orgaoJulgador" VARCHAR(100) NOT NULL,
"orgaoOrigem" VARCHAR(100),
"nomeContraparte" VARCHAR(100) NOT NULL,
"status" VARCHAR(20) NOT NULL DEFAULT 'INICIAL',
"statusAtividade" VARCHAR(20) NOT NULL DEFAULT 'ATIVO',
"dataCriacao" TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
"dataAtualizacao" TIMESTAMP NOT NULL,
"clienteId" UUID NOT NULL,
"tipoParteCliente" VARCHAR(20) NOT NULL,
"orgaoJulgadorId" UUID,
CONSTRAINT "Processo_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "Audiencia" (
"id" UUID NOT NULL DEFAULT gen_random_uuid(),
"processoId" UUID NOT NULL,
"tipo" VARCHAR(50) NOT NULL,
"data" TIMESTAMP NOT NULL,
"local" VARCHAR(200) NOT NULL,
"modalidade" VARCHAR(20) NOT NULL DEFAULT 'PRESENCIAL',
"status" VARCHAR(20) NOT NULL DEFAULT 'AGENDADA',
"linkVirtual" TEXT,
"observacoes" TEXT,
"dataCriacao" TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "Audiencia_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "Diligencia" (
"id" UUID NOT NULL DEFAULT gen_random_uuid(),
"processoId" UUID NOT NULL,
"tipo" VARCHAR(50) NOT NULL,
"descricao" TEXT NOT NULL,
"dataLimite" TIMESTAMP NOT NULL,
"status" VARCHAR(20) NOT NULL DEFAULT 'PENDENTE',
"responsavel" VARCHAR(100),
"observacoes" TEXT,
"dataCriacao" TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "Diligencia_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "Movimentacao" (
"id" UUID NOT NULL DEFAULT gen_random_uuid(),
"processoId" UUID NOT NULL,
"data" TIMESTAMP NOT NULL,
"descricao" TEXT NOT NULL,
"tipo" VARCHAR(50) NOT NULL,
"documento" TEXT,
"dataCriacao" TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "Movimentacao_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "Documento" (
"id" UUID NOT NULL DEFAULT gen_random_uuid(),
"processoId" UUID NOT NULL,
"nome" VARCHAR(200) NOT NULL,
"tipo" VARCHAR(50) NOT NULL,
"url" TEXT NOT NULL,
"dataCriacao" TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "Documento_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "parcelas_honorario" (
"id" UUID NOT NULL DEFAULT gen_random_uuid(),
"honorarioId" UUID NOT NULL,
"numeroParcela" INTEGER NOT NULL,
"valor" DECIMAL(10,2) NOT NULL,
"valorPago" DECIMAL(10,2),
"vencimento" TIMESTAMP(3) NOT NULL,
"dataPagamento" TIMESTAMP(3),
"status" "StatusPagamento" NOT NULL DEFAULT 'PENDENTE',
"comprovante" TEXT,
"observacoes" TEXT,
CONSTRAINT "parcelas_honorario_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "MovimentacaoTribunal" (
"id" UUID NOT NULL DEFAULT gen_random_uuid(),
"processoId" UUID NOT NULL,
"tribunal" VARCHAR(50) NOT NULL,
"data" TIMESTAMP(3) NOT NULL,
"descricao" TEXT NOT NULL,
"dataCriacao" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "MovimentacaoTribunal_pkey" PRIMARY KEY ("id")
);
-- CreateIndex
CREATE INDEX "ParteProcesso_processoId_idx" ON "ParteProcesso"("processoId");
-- CreateIndex
CREATE INDEX "ParteProcesso_clienteId_idx" ON "ParteProcesso"("clienteId");
-- CreateIndex
CREATE UNIQUE INDEX "Processo_numero_key" ON "Processo"("numero");
-- CreateIndex
CREATE INDEX "Processo_clienteId_idx" ON "Processo"("clienteId");
-- CreateIndex
CREATE INDEX "Processo_orgaoJulgadorId_idx" ON "Processo"("orgaoJulgadorId");
-- CreateIndex
CREATE INDEX "Audiencia_processoId_idx" ON "Audiencia"("processoId");
-- CreateIndex
CREATE INDEX "Diligencia_processoId_idx" ON "Diligencia"("processoId");
-- CreateIndex
CREATE INDEX "Movimentacao_processoId_idx" ON "Movimentacao"("processoId");
-- CreateIndex
CREATE INDEX "Documento_processoId_idx" ON "Documento"("processoId");
-- CreateIndex
CREATE INDEX "parcelas_honorario_honorarioId_idx" ON "parcelas_honorario"("honorarioId");
-- CreateIndex
CREATE INDEX "MovimentacaoTribunal_processoId_idx" ON "MovimentacaoTribunal"("processoId");
-- CreateIndex
CREATE INDEX "custas_processuais_processoId_idx" ON "custas_processuais"("processoId");
-- CreateIndex
CREATE INDEX "honorarios_processoId_idx" ON "honorarios"("processoId");
-- AddForeignKey
ALTER TABLE "filhos" ADD CONSTRAINT "filhos_clienteId_fkey" FOREIGN KEY ("clienteId") REFERENCES "clientes"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "ParteProcesso" ADD CONSTRAINT "ParteProcesso_processoId_fkey" FOREIGN KEY ("processoId") REFERENCES "Processo"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "ParteProcesso" ADD CONSTRAINT "ParteProcesso_clienteId_fkey" FOREIGN KEY ("clienteId") REFERENCES "clientes"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "Processo" ADD CONSTRAINT "Processo_clienteId_fkey" FOREIGN KEY ("clienteId") REFERENCES "clientes"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "Processo" ADD CONSTRAINT "Processo_orgaoJulgadorId_fkey" FOREIGN KEY ("orgaoJulgadorId") REFERENCES "orgaos_julgadores"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "Audiencia" ADD CONSTRAINT "Audiencia_processoId_fkey" FOREIGN KEY ("processoId") REFERENCES "Processo"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "Diligencia" ADD CONSTRAINT "Diligencia_processoId_fkey" FOREIGN KEY ("processoId") REFERENCES "Processo"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "Movimentacao" ADD CONSTRAINT "Movimentacao_processoId_fkey" FOREIGN KEY ("processoId") REFERENCES "Processo"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "Documento" ADD CONSTRAINT "Documento_processoId_fkey" FOREIGN KEY ("processoId") REFERENCES "Processo"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "custas_processuais" ADD CONSTRAINT "custas_processuais_processoId_fkey" FOREIGN KEY ("processoId") REFERENCES "Processo"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "honorarios" ADD CONSTRAINT "honorarios_processoId_fkey" FOREIGN KEY ("processoId") REFERENCES "Processo"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "parcelas_honorario" ADD CONSTRAINT "parcelas_honorario_honorarioId_fkey" FOREIGN KEY ("honorarioId") REFERENCES "honorarios"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "MovimentacaoTribunal" ADD CONSTRAINT "MovimentacaoTribunal_processoId_fkey" FOREIGN KEY ("processoId") REFERENCES "Processo"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
@@ -0,0 +1,5 @@
-- AlterEnum
ALTER TYPE "FormaPagamento" ADD VALUE 'PERCENTUAL_CAUSA_COM_ENTRADA';
-- AlterTable
ALTER TABLE "honorarios" ADD COLUMN "valorTotalCausa" DECIMAL(10,2);
@@ -0,0 +1,17 @@
/*
Warnings:
- Added the required column `tribunal` to the `Processo` table without a default value. This is not possible if the table is not empty.
- Added the required column `tribunalUF` to the `Processo` table without a default value. This is not possible if the table is not empty.
*/
-- AlterTable
ALTER TABLE "Processo" ADD COLUMN "numeroOriginal" VARCHAR(50),
ADD COLUMN "tribunal" VARCHAR(50) NOT NULL,
ADD COLUMN "tribunalUF" VARCHAR(20) NOT NULL;
-- CreateIndex
CREATE INDEX "Processo_tribunal_idx" ON "Processo"("tribunal");
-- CreateIndex
CREATE INDEX "Processo_tribunalUF_idx" ON "Processo"("tribunalUF");
@@ -0,0 +1,3 @@
-- AlterTable
ALTER TABLE "Processo" ALTER COLUMN "tribunal" DROP NOT NULL,
ALTER COLUMN "tribunalUF" DROP NOT NULL;
@@ -0,0 +1,2 @@
-- AlterTable
ALTER TABLE "Processo" ADD COLUMN "dadosDatajud" JSONB;
@@ -0,0 +1,5 @@
-- AlterTable
ALTER TABLE "Processo" ADD COLUMN "assuntos" TEXT[],
ADD COLUMN "classeProcessual" TEXT,
ADD COLUMN "dataAjuizamento" TIMESTAMP(3),
ADD COLUMN "nivelSigilo" INTEGER;
@@ -0,0 +1,31 @@
/*
Warnings:
- You are about to drop the column `cargo` on the `usuarios` table. All the data in the column will be lost.
- You are about to alter the column `nome` on the `usuarios` table. The data in that column could be lost. The data in that column will be cast from `Text` to `VarChar(100)`.
- You are about to alter the column `email` on the `usuarios` table. The data in that column could be lost. The data in that column will be cast from `Text` to `VarChar(100)`.
- You are about to alter the column `senha` on the `usuarios` table. The data in that column could be lost. The data in that column will be cast from `Text` to `VarChar(100)`.
*/
-- CreateEnum
CREATE TYPE "PerfilUsuario" AS ENUM ('ADVOGADO_ADMIN', 'ADVOGADO', 'ASSISTENTE', 'ESTAGIARIO');
-- AlterTable
ALTER TABLE "usuarios" DROP COLUMN "cargo",
ADD COLUMN "ativo" BOOLEAN NOT NULL DEFAULT true,
ADD COLUMN "bairro" VARCHAR(100),
ADD COLUMN "cep" VARCHAR(9),
ADD COLUMN "cidade" VARCHAR(100),
ADD COLUMN "complemento" VARCHAR(100),
ADD COLUMN "cpf" VARCHAR(14),
ADD COLUMN "endereco" VARCHAR(200),
ADD COLUMN "estado" VARCHAR(2),
ADD COLUMN "numero" VARCHAR(10),
ADD COLUMN "oab" VARCHAR(20),
ADD COLUMN "oabUF" VARCHAR(2),
ADD COLUMN "perfil" "PerfilUsuario" NOT NULL DEFAULT 'ADVOGADO',
ADD COLUMN "rg" VARCHAR(20),
ADD COLUMN "telefone" VARCHAR(15),
ALTER COLUMN "nome" SET DATA TYPE VARCHAR(100),
ALTER COLUMN "email" SET DATA TYPE VARCHAR(100),
ALTER COLUMN "senha" SET DATA TYPE VARCHAR(100);
@@ -0,0 +1,58 @@
-- CreateEnum
CREATE TYPE "TipoAtendimento" AS ENUM ('INICIAL', 'RETORNO', 'ENCAMINHAMENTO', 'ORIENTACAO', 'ACORDO', 'OUTROS');
-- CreateTable
CREATE TABLE "atendimentos" (
"id" UUID NOT NULL DEFAULT gen_random_uuid(),
"protocolo" TEXT NOT NULL,
"clienteId" UUID NOT NULL,
"processoId" UUID,
"tipo" "TipoAtendimento" NOT NULL DEFAULT 'INICIAL',
"titulo" VARCHAR(200) NOT NULL,
"conteudo" TEXT NOT NULL,
"dataAtendimento" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"dataCriacao" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"usuarioId" UUID NOT NULL,
CONSTRAINT "atendimentos_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "anexos_atendimento" (
"id" UUID NOT NULL DEFAULT gen_random_uuid(),
"atendimentoId" UUID NOT NULL,
"nome" VARCHAR(200) NOT NULL,
"tipo" VARCHAR(50) NOT NULL,
"url" TEXT NOT NULL,
"armazenamento" VARCHAR(20) NOT NULL DEFAULT 'NEXTCLOUD',
"dataCriacao" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "anexos_atendimento_pkey" PRIMARY KEY ("id")
);
-- CreateIndex
CREATE UNIQUE INDEX "atendimentos_protocolo_key" ON "atendimentos"("protocolo");
-- CreateIndex
CREATE INDEX "atendimentos_clienteId_idx" ON "atendimentos"("clienteId");
-- CreateIndex
CREATE INDEX "atendimentos_processoId_idx" ON "atendimentos"("processoId");
-- CreateIndex
CREATE INDEX "atendimentos_protocolo_idx" ON "atendimentos"("protocolo");
-- CreateIndex
CREATE INDEX "anexos_atendimento_atendimentoId_idx" ON "anexos_atendimento"("atendimentoId");
-- AddForeignKey
ALTER TABLE "atendimentos" ADD CONSTRAINT "atendimentos_clienteId_fkey" FOREIGN KEY ("clienteId") REFERENCES "clientes"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "atendimentos" ADD CONSTRAINT "atendimentos_processoId_fkey" FOREIGN KEY ("processoId") REFERENCES "Processo"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "atendimentos" ADD CONSTRAINT "atendimentos_usuarioId_fkey" FOREIGN KEY ("usuarioId") REFERENCES "usuarios"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "anexos_atendimento" ADD CONSTRAINT "anexos_atendimento_atendimentoId_fkey" FOREIGN KEY ("atendimentoId") REFERENCES "atendimentos"("id") ON DELETE CASCADE ON UPDATE CASCADE;
@@ -0,0 +1,8 @@
-- AlterTable
ALTER TABLE "atendimentos" ADD COLUMN "atendimentoInicialId" UUID;
-- CreateIndex
CREATE INDEX "atendimentos_atendimentoInicialId_idx" ON "atendimentos"("atendimentoInicialId");
-- AddForeignKey
ALTER TABLE "atendimentos" ADD CONSTRAINT "atendimentos_atendimentoInicialId_fkey" FOREIGN KEY ("atendimentoInicialId") REFERENCES "atendimentos"("id") ON DELETE SET NULL ON UPDATE CASCADE;
@@ -0,0 +1,26 @@
-- CreateEnum
CREATE TYPE "StatusAgendamento" AS ENUM ('AGENDADO', 'CONFIRMADO', 'CANCELADO', 'REALIZADO', 'NAO_COMPARECEU');
-- CreateTable
CREATE TABLE "agendamentos_atendimento" (
"id" UUID NOT NULL DEFAULT gen_random_uuid(),
"clienteId" UUID NOT NULL,
"usuarioId" UUID NOT NULL,
"data" TIMESTAMP NOT NULL,
"observacoes" TEXT,
"status" "StatusAgendamento" NOT NULL DEFAULT 'AGENDADO',
"criadoEm" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"atualizadoEm" TIMESTAMP(3) NOT NULL,
"atendimentoId" UUID,
CONSTRAINT "agendamentos_atendimento_pkey" PRIMARY KEY ("id")
);
-- AddForeignKey
ALTER TABLE "agendamentos_atendimento" ADD CONSTRAINT "agendamentos_atendimento_clienteId_fkey" FOREIGN KEY ("clienteId") REFERENCES "clientes"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "agendamentos_atendimento" ADD CONSTRAINT "agendamentos_atendimento_usuarioId_fkey" FOREIGN KEY ("usuarioId") REFERENCES "usuarios"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "agendamentos_atendimento" ADD CONSTRAINT "agendamentos_atendimento_atendimentoId_fkey" FOREIGN KEY ("atendimentoId") REFERENCES "atendimentos"("id") ON DELETE SET NULL ON UPDATE CASCADE;
@@ -0,0 +1,76 @@
-- CreateEnum
CREATE TYPE "StatusTarefa" AS ENUM ('PENDENTE', 'EM_ANDAMENTO', 'CONCLUIDA', 'CANCELADA');
CREATE TYPE "PrioridadeTarefa" AS ENUM ('BAIXA', 'MEDIA', 'ALTA', 'URGENTE');
-- CreateTable
CREATE TABLE "tarefas" (
"id" UUID NOT NULL DEFAULT gen_random_uuid(),
"titulo" TEXT NOT NULL,
"descricao" TEXT,
"status" "StatusTarefa" NOT NULL,
"prioridade" "PrioridadeTarefa" NOT NULL,
"dataInicio" TIMESTAMP(3) NOT NULL,
"dataVencimento" TIMESTAMP(3) NOT NULL,
"progresso" INTEGER NOT NULL DEFAULT 0,
"responsavelId" UUID NOT NULL,
"criadoPorId" UUID NOT NULL,
"processoId" UUID,
"clienteId" UUID,
"etiquetas" TEXT[],
"criadoEm" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"atualizadoEm" TIMESTAMP(3) NOT NULL,
CONSTRAINT "tarefas_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "subtarefas" (
"id" UUID NOT NULL DEFAULT gen_random_uuid(),
"titulo" TEXT NOT NULL,
"concluida" BOOLEAN NOT NULL DEFAULT false,
"tarefaId" UUID NOT NULL,
CONSTRAINT "subtarefas_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "comentarios" (
"id" UUID NOT NULL DEFAULT gen_random_uuid(),
"texto" TEXT NOT NULL,
"criadoPorId" UUID NOT NULL,
"tarefaId" UUID NOT NULL,
"criadoEm" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "comentarios_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "anexos" (
"id" UUID NOT NULL DEFAULT gen_random_uuid(),
"nome" TEXT NOT NULL,
"url" TEXT NOT NULL,
"tipo" TEXT NOT NULL,
"tamanho" INTEGER NOT NULL,
"tarefaId" UUID NOT NULL,
"criadoEm" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "anexos_pkey" PRIMARY KEY ("id")
);
-- AddForeignKey
ALTER TABLE "tarefas" ADD CONSTRAINT "tarefas_responsavelId_fkey" FOREIGN KEY ("responsavelId") REFERENCES "usuarios"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "tarefas" ADD CONSTRAINT "tarefas_criadoPorId_fkey" FOREIGN KEY ("criadoPorId") REFERENCES "usuarios"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "tarefas" ADD CONSTRAINT "tarefas_processoId_fkey" FOREIGN KEY ("processoId") REFERENCES "processos"("id") ON DELETE SET NULL ON UPDATE CASCADE;
ALTER TABLE "tarefas" ADD CONSTRAINT "tarefas_clienteId_fkey" FOREIGN KEY ("clienteId") REFERENCES "clientes"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "subtarefas" ADD CONSTRAINT "subtarefas_tarefaId_fkey" FOREIGN KEY ("tarefaId") REFERENCES "tarefas"("id") ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE "comentarios" ADD CONSTRAINT "comentarios_criadoPorId_fkey" FOREIGN KEY ("criadoPorId") REFERENCES "usuarios"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "comentarios" ADD CONSTRAINT "comentarios_tarefaId_fkey" FOREIGN KEY ("tarefaId") REFERENCES "tarefas"("id") ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE "anexos" ADD CONSTRAINT "anexos_tarefaId_fkey" FOREIGN KEY ("tarefaId") REFERENCES "tarefas"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- CreateIndex
CREATE INDEX "tarefas_responsavelId_idx" ON "tarefas"("responsavelId");
CREATE INDEX "tarefas_criadoPorId_idx" ON "tarefas"("criadoPorId");
CREATE INDEX "tarefas_processoId_idx" ON "tarefas"("processoId");
CREATE INDEX "tarefas_clienteId_idx" ON "tarefas"("clienteId");
@@ -0,0 +1,86 @@
-- CreateEnum
CREATE TYPE IF NOT EXISTS "StatusTarefa" AS ENUM ('PENDENTE', 'EM_ANDAMENTO', 'CONCLUIDA', 'CANCELADA');
CREATE TYPE IF NOT EXISTS "PrioridadeTarefa" AS ENUM ('BAIXA', 'MEDIA', 'ALTA', 'URGENTE');
-- Tarefas first (parent table)
CREATE TABLE IF NOT EXISTS "tarefas" (
"id" UUID NOT NULL DEFAULT gen_random_uuid(),
"titulo" TEXT NOT NULL,
"descricao" TEXT,
"status" "StatusTarefa" NOT NULL,
"prioridade" "PrioridadeTarefa" NOT NULL,
"dataInicio" TIMESTAMP(3) NOT NULL,
"dataVencimento" TIMESTAMP(3) NOT NULL,
"progresso" INTEGER NOT NULL DEFAULT 0,
"responsavelId" UUID NOT NULL,
"criadoPorId" UUID NOT NULL,
"processoId" UUID,
"clienteId" UUID,
"etiquetas" TEXT[],
"criadoEm" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"atualizadoEm" TIMESTAMP(3) NOT NULL,
CONSTRAINT "tarefas_pkey" PRIMARY KEY ("id"),
CONSTRAINT "tarefas_responsavelId_fkey"
FOREIGN KEY ("responsavelId") REFERENCES "usuarios"("id"),
CONSTRAINT "tarefas_criadoPorId_fkey"
FOREIGN KEY ("criadoPorId") REFERENCES "usuarios"("id"),
CONSTRAINT "tarefas_clienteId_fkey"
FOREIGN KEY ("clienteId") REFERENCES "clientes"("id")
);
-- Then child tables
CREATE TABLE IF NOT EXISTS "subtarefas" (
"id" UUID NOT NULL DEFAULT gen_random_uuid(),
"titulo" TEXT NOT NULL,
"concluida" BOOLEAN NOT NULL DEFAULT false,
"tarefaId" UUID NOT NULL,
CONSTRAINT "subtarefas_pkey" PRIMARY KEY ("id"),
CONSTRAINT "subtarefas_tarefaId_fkey"
FOREIGN KEY ("tarefaId") REFERENCES "tarefas"("id") ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS "comentarios" (
"id" UUID NOT NULL DEFAULT gen_random_uuid(),
"texto" TEXT NOT NULL,
"criadoPorId" UUID NOT NULL,
"tarefaId" UUID NOT NULL,
"criadoEm" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "comentarios_pkey" PRIMARY KEY ("id"),
CONSTRAINT "comentarios_criadoPorId_fkey"
FOREIGN KEY ("criadoPorId") REFERENCES "usuarios"("id"),
CONSTRAINT "comentarios_tarefaId_fkey"
FOREIGN KEY ("tarefaId") REFERENCES "tarefas"("id") ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS "anexos" (
"id" UUID NOT NULL DEFAULT gen_random_uuid(),
"nome" TEXT NOT NULL,
"url" TEXT NOT NULL,
"tipo" TEXT NOT NULL,
"tamanho" INTEGER NOT NULL,
"tarefaId" UUID NOT NULL,
"criadoEm" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "anexos_pkey" PRIMARY KEY ("id"),
CONSTRAINT "anexos_tarefaId_fkey"
FOREIGN KEY ("tarefaId") REFERENCES "tarefas"("id") ON DELETE CASCADE
);
-- Add foreign key for processos after it exists
DO $$
BEGIN
IF EXISTS (
SELECT 1 FROM information_schema.tables
WHERE table_name = 'processos'
) THEN
ALTER TABLE "tarefas"
ADD CONSTRAINT "tarefas_processoId_fkey"
FOREIGN KEY ("processoId")
REFERENCES "processos"("id");
END IF;
END $$;
-- Indexes
CREATE INDEX IF NOT EXISTS "tarefas_responsavelId_idx" ON "tarefas"("responsavelId");
CREATE INDEX IF NOT EXISTS "tarefas_criadoPorId_idx" ON "tarefas"("criadoPorId");
CREATE INDEX IF NOT EXISTS "tarefas_processoId_idx" ON "tarefas"("processoId");
CREATE INDEX IF NOT EXISTS "tarefas_clienteId_idx" ON "tarefas"("clienteId");
@@ -0,0 +1,18 @@
-- Remover colunas se existirem (para evitar conflitos)
ALTER TABLE "atendimentos" DROP COLUMN IF EXISTS "status";
ALTER TABLE "atendimentos" DROP COLUMN IF EXISTS "justificativaCancelamento";
ALTER TABLE "atendimentos" DROP COLUMN IF EXISTS "dataAtualizacao";
-- Adicionar as colunas novamente
ALTER TABLE "atendimentos"
ADD COLUMN "status" VARCHAR(20) DEFAULT 'ATIVO',
ADD COLUMN "justificativaCancelamento" TEXT,
ADD COLUMN "dataAtualizacao" TIMESTAMP DEFAULT CURRENT_TIMESTAMP;
-- Atualizar registros existentes
UPDATE "atendimentos"
SET "status" = 'ATIVO',
"dataAtualizacao" = COALESCE("dataCriacao", CURRENT_TIMESTAMP);
-- Criar índice para melhorar performance de buscas por status
CREATE INDEX IF NOT EXISTS "atendimentos_status_idx" ON "atendimentos"("status");
@@ -0,0 +1,4 @@
-- AlterTable
ALTER TABLE "atendimentos" ADD COLUMN "dataAtualizacao" TIMESTAMP(3) DEFAULT CURRENT_TIMESTAMP,
ADD COLUMN "justificativaCancelamento" TEXT,
ADD COLUMN "status" VARCHAR(20) DEFAULT 'ATIVO';
@@ -0,0 +1,84 @@
-- CreateEnum
CREATE TYPE "StatusTarefa" AS ENUM ('PENDENTE', 'EM_ANDAMENTO', 'CONCLUIDA', 'CANCELADA');
-- CreateEnum
CREATE TYPE "PrioridadeTarefa" AS ENUM ('BAIXA', 'MEDIA', 'ALTA', 'URGENTE');
-- CreateTable
CREATE TABLE "tarefas" (
"id" UUID NOT NULL DEFAULT gen_random_uuid(),
"titulo" TEXT NOT NULL,
"descricao" TEXT,
"status" "StatusTarefa" NOT NULL,
"prioridade" "PrioridadeTarefa" NOT NULL,
"dataInicio" TIMESTAMP(3) NOT NULL,
"dataVencimento" TIMESTAMP(3) NOT NULL,
"progresso" INTEGER NOT NULL DEFAULT 0,
"responsavelId" UUID NOT NULL,
"criadoPorId" UUID NOT NULL,
"processoId" UUID,
"clienteId" UUID,
"etiquetas" TEXT[],
"criadoEm" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"atualizadoEm" TIMESTAMP(3) NOT NULL,
CONSTRAINT "tarefas_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "subtarefas" (
"id" UUID NOT NULL DEFAULT gen_random_uuid(),
"titulo" TEXT NOT NULL,
"concluida" BOOLEAN NOT NULL DEFAULT false,
"tarefaId" UUID NOT NULL,
CONSTRAINT "subtarefas_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "comentarios" (
"id" UUID NOT NULL DEFAULT gen_random_uuid(),
"texto" TEXT NOT NULL,
"criadoPorId" UUID NOT NULL,
"tarefaId" UUID NOT NULL,
"criadoEm" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "comentarios_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "anexos" (
"id" UUID NOT NULL DEFAULT gen_random_uuid(),
"nome" TEXT NOT NULL,
"url" TEXT NOT NULL,
"tipo" TEXT NOT NULL,
"tamanho" INTEGER NOT NULL,
"tarefaId" UUID NOT NULL,
"criadoEm" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "anexos_pkey" PRIMARY KEY ("id")
);
-- AddForeignKey
ALTER TABLE "tarefas" ADD CONSTRAINT "tarefas_responsavelId_fkey" FOREIGN KEY ("responsavelId") REFERENCES "usuarios"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "tarefas" ADD CONSTRAINT "tarefas_criadoPorId_fkey" FOREIGN KEY ("criadoPorId") REFERENCES "usuarios"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "tarefas" ADD CONSTRAINT "tarefas_processoId_fkey" FOREIGN KEY ("processoId") REFERENCES "Processo"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "tarefas" ADD CONSTRAINT "tarefas_clienteId_fkey" FOREIGN KEY ("clienteId") REFERENCES "clientes"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "subtarefas" ADD CONSTRAINT "subtarefas_tarefaId_fkey" FOREIGN KEY ("tarefaId") REFERENCES "tarefas"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "comentarios" ADD CONSTRAINT "comentarios_criadoPorId_fkey" FOREIGN KEY ("criadoPorId") REFERENCES "usuarios"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "comentarios" ADD CONSTRAINT "comentarios_tarefaId_fkey" FOREIGN KEY ("tarefaId") REFERENCES "tarefas"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "anexos" ADD CONSTRAINT "anexos_tarefaId_fkey" FOREIGN KEY ("tarefaId") REFERENCES "tarefas"("id") ON DELETE CASCADE ON UPDATE CASCADE;
@@ -0,0 +1,5 @@
-- CreateEnum
CREATE TYPE "ResultadoProcesso" AS ENUM ('NAO_JULGADO', 'PROCEDENTE', 'PARCIALMENTE_PROCEDENTE', 'IMPROCEDENTE', 'SEM_ANALISE_MERITO');
-- AlterTable
ALTER TABLE "Processo" ADD COLUMN "resultado" "ResultadoProcesso" NOT NULL DEFAULT 'NAO_JULGADO';
@@ -0,0 +1,2 @@
-- AlterTable
ALTER TABLE "tarefas" ADD COLUMN "dataConclusao" TIMESTAMP(3);
@@ -0,0 +1,44 @@
/*
Warnings:
- You are about to drop the `anexos` table. If the table is not empty, all the data it contains will be lost.
- You are about to drop the `anexos_atendimento` table. If the table is not empty, all the data it contains will be lost.
*/
-- DropForeignKey
ALTER TABLE "anexos" DROP CONSTRAINT "anexos_tarefaId_fkey";
-- DropForeignKey
ALTER TABLE "anexos_atendimento" DROP CONSTRAINT "anexos_atendimento_atendimentoId_fkey";
-- DropTable
DROP TABLE "anexos";
-- DropTable
DROP TABLE "anexos_atendimento";
-- CreateTable
CREATE TABLE "Anexo" (
"id" UUID NOT NULL DEFAULT gen_random_uuid(),
"nome" TEXT NOT NULL,
"url" TEXT NOT NULL,
"tipo" TEXT NOT NULL,
"tamanho" INTEGER NOT NULL,
"atendimentoId" UUID,
"tarefaId" UUID,
"criadoEm" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "Anexo_pkey" PRIMARY KEY ("id")
);
-- CreateIndex
CREATE INDEX "Anexo_atendimentoId_idx" ON "Anexo"("atendimentoId");
-- CreateIndex
CREATE INDEX "Anexo_tarefaId_idx" ON "Anexo"("tarefaId");
-- AddForeignKey
ALTER TABLE "Anexo" ADD CONSTRAINT "Anexo_atendimentoId_fkey" FOREIGN KEY ("atendimentoId") REFERENCES "atendimentos"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "Anexo" ADD CONSTRAINT "Anexo_tarefaId_fkey" FOREIGN KEY ("tarefaId") REFERENCES "tarefas"("id") ON DELETE SET NULL ON UPDATE CASCADE;
@@ -0,0 +1,66 @@
/*
Warnings:
- You are about to drop the `Documento` table. If the table is not empty, all the data it contains will be lost.
*/
-- CreateEnum
CREATE TYPE "TipoDocumento" AS ENUM ('PETICAO', 'CONTRATO', 'PROCURACAO', 'DECLARACAO', 'OUTROS');
-- DropForeignKey
ALTER TABLE "Documento" DROP CONSTRAINT "Documento_processoId_fkey";
-- DropTable
DROP TABLE "Documento";
-- CreateTable
CREATE TABLE "documentos" (
"id" UUID NOT NULL DEFAULT gen_random_uuid(),
"nome" VARCHAR(200) NOT NULL,
"tipo" "TipoDocumento" NOT NULL,
"conteudo" TEXT NOT NULL,
"url" TEXT,
"processoId" UUID,
"atendimentoId" UUID,
"anexoId" UUID,
"criadoPorId" UUID NOT NULL,
"criadoEm" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"atualizadoEm" TIMESTAMP(3) NOT NULL,
CONSTRAINT "documentos_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "documentos_modelos" (
"id" UUID NOT NULL DEFAULT gen_random_uuid(),
"nome" VARCHAR(200) NOT NULL,
"descricao" TEXT,
"tipo" "TipoDocumento" NOT NULL,
"conteudo" TEXT NOT NULL,
"variaveis" TEXT[],
"criadoEm" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"atualizadoEm" TIMESTAMP(3) NOT NULL,
CONSTRAINT "documentos_modelos_pkey" PRIMARY KEY ("id")
);
-- CreateIndex
CREATE UNIQUE INDEX "documentos_anexoId_key" ON "documentos"("anexoId");
-- CreateIndex
CREATE INDEX "documentos_processoId_idx" ON "documentos"("processoId");
-- CreateIndex
CREATE INDEX "documentos_atendimentoId_idx" ON "documentos"("atendimentoId");
-- AddForeignKey
ALTER TABLE "documentos" ADD CONSTRAINT "documentos_processoId_fkey" FOREIGN KEY ("processoId") REFERENCES "Processo"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "documentos" ADD CONSTRAINT "documentos_atendimentoId_fkey" FOREIGN KEY ("atendimentoId") REFERENCES "atendimentos"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "documentos" ADD CONSTRAINT "documentos_anexoId_fkey" FOREIGN KEY ("anexoId") REFERENCES "Anexo"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "documentos" ADD CONSTRAINT "documentos_criadoPorId_fkey" FOREIGN KEY ("criadoPorId") REFERENCES "usuarios"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
@@ -0,0 +1,31 @@
/*
Warnings:
- The `variaveis` column on the `modelos_documentos` table would be dropped and recreated. This will lead to data loss if there is data in the column.
*/
-- AlterTable
ALTER TABLE "documentos" ADD COLUMN "protocolo" VARCHAR(20);
-- AlterTable
ALTER TABLE "modelos_documentos" ADD COLUMN "assinatura" BOOLEAN NOT NULL DEFAULT true,
ADD COLUMN "cabecalho" BOOLEAN NOT NULL DEFAULT true,
ADD COLUMN "rodape" BOOLEAN NOT NULL DEFAULT true,
DROP COLUMN "variaveis",
ADD COLUMN "variaveis" JSONB;
-- CreateTable
CREATE TABLE "configuracoes_documentos" (
"id" UUID NOT NULL DEFAULT gen_random_uuid(),
"cabecalhoHtml" TEXT NOT NULL,
"rodapeHtml" TEXT NOT NULL,
"assinaturaHtml" TEXT NOT NULL,
"logoUrl" TEXT,
"criadoEm" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"atualizadoEm" TIMESTAMP(3) NOT NULL,
CONSTRAINT "configuracoes_documentos_pkey" PRIMARY KEY ("id")
);
-- CreateIndex
CREATE INDEX "documentos_protocolo_idx" ON "documentos"("protocolo");
@@ -0,0 +1,19 @@
/*
Warnings:
- You are about to drop the `configuracoes_documentos` table. If the table is not empty, all the data it contains will be lost.
*/
-- DropTable
DROP TABLE "configuracoes_documentos";
-- CreateTable
CREATE TABLE "configuracao_documento" (
"id" UUID NOT NULL DEFAULT gen_random_uuid(),
"headerImageUrl" TEXT,
"footerImageUrl" TEXT,
"logoUrl" TEXT,
"criadoEm" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "configuracao_documento_pkey" PRIMARY KEY ("id")
);
@@ -0,0 +1,6 @@
-- AlterTable
ALTER TABLE "configuracao_documento" ADD COLUMN "timbradoMarginBottom" INTEGER DEFAULT 50,
ADD COLUMN "timbradoMarginLeft" INTEGER DEFAULT 50,
ADD COLUMN "timbradoMarginRight" INTEGER DEFAULT 50,
ADD COLUMN "timbradoMarginTop" INTEGER DEFAULT 100,
ADD COLUMN "timbradoUrl" TEXT;
@@ -0,0 +1,19 @@
/*
Warnings:
- You are about to drop the column `footerImageUrl` on the `configuracao_documento` table. All the data in the column will be lost.
- You are about to drop the column `headerImageUrl` on the `configuracao_documento` table. All the data in the column will be lost.
- You are about to drop the column `logoUrl` on the `configuracao_documento` table. All the data in the column will be lost.
- A unique constraint covering the columns `[escritorioId]` on the table `configuracao_documento` will be added. If there are existing duplicate values, this will fail.
*/
-- AlterTable
ALTER TABLE "configuracao_documento" DROP COLUMN "footerImageUrl",
DROP COLUMN "headerImageUrl",
DROP COLUMN "logoUrl",
ADD COLUMN "escritorioId" UUID,
ADD COLUMN "margensTemplate" JSONB DEFAULT '{"top":35,"bottom":29,"left":25,"right":25}',
ADD COLUMN "templatePadrao" TEXT;
-- CreateIndex
CREATE UNIQUE INDEX "configuracao_documento_escritorioId_key" ON "configuracao_documento"("escritorioId");
@@ -0,0 +1,14 @@
/*
Warnings:
- You are about to drop the column `escritorioId` on the `configuracao_documento` table. All the data in the column will be lost.
*/
-- DropIndex
DROP INDEX "configuracao_documento_escritorioId_key";
-- AlterTable
ALTER TABLE "configuracao_documento" DROP COLUMN "escritorioId";
-- CreateIndex
CREATE INDEX "configuracao_documento_criadoEm_idx" ON "configuracao_documento"("criadoEm");
@@ -0,0 +1,59 @@
-- CreateEnum
CREATE TYPE "StatusProcessoAdministrativo" AS ENUM ('INICIAL', 'EM_ANALISE', 'EM_RECURSO', 'FINALIZADO', 'ARQUIVADO');
-- AlterTable
ALTER TABLE "documentos" ADD COLUMN "processoAdministrativoId" UUID;
-- CreateTable
CREATE TABLE "processos_administrativos" (
"id" UUID NOT NULL DEFAULT gen_random_uuid(),
"numero" TEXT NOT NULL,
"descricao" TEXT NOT NULL,
"orgao" VARCHAR(200) NOT NULL,
"clienteId" UUID NOT NULL,
"tipoParteCliente" "TipoParte" NOT NULL,
"valorPretensao" DECIMAL(15,2),
"status" "StatusProcessoAdministrativo" NOT NULL DEFAULT 'INICIAL',
"resultado" VARCHAR(100),
"observacoes" TEXT,
"dataCriacao" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"dataAtualizacao" TIMESTAMP(3) NOT NULL,
CONSTRAINT "processos_administrativos_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "movimentacoes_administrativas" (
"id" UUID NOT NULL DEFAULT gen_random_uuid(),
"processoId" UUID NOT NULL,
"data" TIMESTAMP(3) NOT NULL,
"descricao" TEXT NOT NULL,
"tipoMovimentacao" VARCHAR(100) NOT NULL,
"numero" VARCHAR(100),
"documentos" TEXT[],
"observacoes" TEXT,
"dataCriacao" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "movimentacoes_administrativas_pkey" PRIMARY KEY ("id")
);
-- CreateIndex
CREATE UNIQUE INDEX "processos_administrativos_numero_key" ON "processos_administrativos"("numero");
-- CreateIndex
CREATE INDEX "processos_administrativos_clienteId_idx" ON "processos_administrativos"("clienteId");
-- CreateIndex
CREATE INDEX "movimentacoes_administrativas_processoId_idx" ON "movimentacoes_administrativas"("processoId");
-- CreateIndex
CREATE INDEX "documentos_processoAdministrativoId_idx" ON "documentos"("processoAdministrativoId");
-- AddForeignKey
ALTER TABLE "processos_administrativos" ADD CONSTRAINT "processos_administrativos_clienteId_fkey" FOREIGN KEY ("clienteId") REFERENCES "clientes"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "movimentacoes_administrativas" ADD CONSTRAINT "movimentacoes_administrativas_processoId_fkey" FOREIGN KEY ("processoId") REFERENCES "processos_administrativos"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "documentos" ADD CONSTRAINT "documentos_processoAdministrativoId_fkey" FOREIGN KEY ("processoAdministrativoId") REFERENCES "processos_administrativos"("id") ON DELETE SET NULL ON UPDATE CASCADE;
@@ -0,0 +1,27 @@
-- CreateEnum
CREATE TYPE "TipoCustaAdministrativa" AS ENUM ('TAXA_ADMINISTRATIVA', 'RECURSO', 'DILIGENCIA', 'CERTIDAO', 'COPIA', 'OUTROS');
-- CreateTable
CREATE TABLE "custas_administrativas" (
"id" UUID NOT NULL DEFAULT gen_random_uuid(),
"processoId" UUID NOT NULL,
"tipo" "TipoCustaAdministrativa" NOT NULL,
"descricao" VARCHAR(200) NOT NULL,
"valor" DECIMAL(10,2) NOT NULL,
"status" "StatusPagamento" NOT NULL DEFAULT 'PENDENTE',
"vencimento" TIMESTAMP(3),
"dataPagamento" TIMESTAMP(3),
"comprovante" TEXT,
"observacoes" TEXT,
"dataCriacao" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"numeroParcelas" INTEGER NOT NULL DEFAULT 1,
"parcelaAtual" INTEGER NOT NULL DEFAULT 1,
CONSTRAINT "custas_administrativas_pkey" PRIMARY KEY ("id")
);
-- CreateIndex
CREATE INDEX "custas_administrativas_processoId_idx" ON "custas_administrativas"("processoId");
-- AddForeignKey
ALTER TABLE "custas_administrativas" ADD CONSTRAINT "custas_administrativas_processoId_fkey" FOREIGN KEY ("processoId") REFERENCES "processos_administrativos"("id") ON DELETE CASCADE ON UPDATE CASCADE;
@@ -0,0 +1,21 @@
-- CreateEnum
CREATE TYPE "StatusProva" AS ENUM ('PENDENTE', 'PROCESSANDO', 'CONCLUIDO', 'ERRO');
-- CreateTable
CREATE TABLE "provas" (
"id" UUID NOT NULL DEFAULT gen_random_uuid(),
"fileName" VARCHAR(255) NOT NULL,
"mimeType" VARCHAR(100) NOT NULL,
"checksumSha256" VARCHAR(64) NOT NULL,
"checksumSha512" VARCHAR(128) NOT NULL,
"checksumMd5" VARCHAR(32) NOT NULL,
"timestamp" TEXT NOT NULL,
"metadata" JSONB NOT NULL,
"reportPath" VARCHAR(255) NOT NULL,
"status" "StatusProva" NOT NULL DEFAULT 'PENDENTE',
"error" TEXT,
"dataCriacao" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"dataValida" TIMESTAMP(3) NOT NULL,
CONSTRAINT "provas_pkey" PRIMARY KEY ("id")
);
@@ -0,0 +1,263 @@
-- CreateTable
CREATE TABLE "calculosjudiciais" (
"id" TEXT NOT NULL,
"titulo" TEXT NOT NULL,
"descricao" TEXT,
"dataBase" TIMESTAMP(3) NOT NULL,
"dataCalculo" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"valorBase" DECIMAL(15,2) NOT NULL,
"valorCorrigido" DECIMAL(15,2) NOT NULL,
"valorFinal" DECIMAL(15,2) NOT NULL,
"status" TEXT NOT NULL DEFAULT 'RASCUNHO',
"usuarioId" UUID,
"processoId" UUID,
"clienteId" UUID,
"configuracoes" JSONB,
"criadoEm" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"atualizadoEm" TIMESTAMP(3) NOT NULL,
CONSTRAINT "calculosjudiciais_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "correcoes_monetarias" (
"id" TEXT NOT NULL,
"calculoId" TEXT NOT NULL,
"indice" TEXT NOT NULL,
"dataInicial" TIMESTAMP(3) NOT NULL,
"dataFinal" TIMESTAMP(3),
"valorOriginal" DECIMAL(15,2) NOT NULL,
"valorCorrigido" DECIMAL(15,2) NOT NULL,
"fatorCorrecao" DECIMAL(15,6) NOT NULL,
"criadoEm" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"atualizadoEm" TIMESTAMP(3) NOT NULL,
CONSTRAINT "correcoes_monetarias_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "juros_calculos" (
"id" TEXT NOT NULL,
"calculoId" TEXT NOT NULL,
"tipo" TEXT NOT NULL,
"taxa" DECIMAL(8,6) NOT NULL,
"periodicidade" TEXT NOT NULL,
"natureza" TEXT NOT NULL,
"dataInicial" TIMESTAMP(3) NOT NULL,
"dataFinal" TIMESTAMP(3),
"valorBase" DECIMAL(15,2) NOT NULL,
"valorJuros" DECIMAL(15,2) NOT NULL,
"criadoEm" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"atualizadoEm" TIMESTAMP(3) NOT NULL,
CONSTRAINT "juros_calculos_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "multas_calculos" (
"id" TEXT NOT NULL,
"calculoId" TEXT NOT NULL,
"tipo" TEXT NOT NULL,
"percentual" DECIMAL(8,6) NOT NULL,
"valorBase" DECIMAL(15,2) NOT NULL,
"valorMulta" DECIMAL(15,2) NOT NULL,
"fundamento" TEXT,
"criadoEm" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"atualizadoEm" TIMESTAMP(3) NOT NULL,
CONSTRAINT "multas_calculos_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "honorarios_calculos" (
"id" TEXT NOT NULL,
"calculoId" TEXT NOT NULL,
"tipo" TEXT NOT NULL,
"percentual" DECIMAL(8,6) NOT NULL,
"valorBase" DECIMAL(15,2) NOT NULL,
"valorHonorario" DECIMAL(15,2) NOT NULL,
"fundamento" TEXT,
"criadoEm" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"atualizadoEm" TIMESTAMP(3) NOT NULL,
CONSTRAINT "honorarios_calculos_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "parcelas_calculos" (
"id" TEXT NOT NULL,
"calculoId" TEXT NOT NULL,
"numero" INTEGER NOT NULL,
"dataVencimento" TIMESTAMP(3) NOT NULL,
"valorOriginal" DECIMAL(15,2) NOT NULL,
"valorCorrigido" DECIMAL(15,2) NOT NULL,
"valorJuros" DECIMAL(15,2) NOT NULL,
"valorMulta" DECIMAL(15,2) NOT NULL,
"valorTotal" DECIMAL(15,2) NOT NULL,
"pago" BOOLEAN NOT NULL DEFAULT false,
"dataPagamento" TIMESTAMP(3),
"criadoEm" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"atualizadoEm" TIMESTAMP(3) NOT NULL,
CONSTRAINT "parcelas_calculos_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "descontos_calculos" (
"id" TEXT NOT NULL,
"calculoId" TEXT NOT NULL,
"tipo" TEXT NOT NULL,
"descricao" TEXT,
"percentual" DECIMAL(8,6),
"valorFixo" DECIMAL(15,2),
"valorBase" DECIMAL(15,2) NOT NULL,
"valorDesconto" DECIMAL(15,2) NOT NULL,
"criadoEm" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"atualizadoEm" TIMESTAMP(3) NOT NULL,
CONSTRAINT "descontos_calculos_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "historicos_calculos" (
"id" TEXT NOT NULL,
"calculoId" TEXT NOT NULL,
"usuarioId" UUID,
"acao" TEXT NOT NULL,
"descricao" TEXT NOT NULL,
"valorAnterior" DECIMAL(15,2),
"valorNovo" DECIMAL(15,2),
"metadados" JSONB,
"criadoEm" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "historicos_calculos_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "exportacoes_calculos" (
"id" TEXT NOT NULL,
"calculoId" TEXT NOT NULL,
"usuarioId" UUID,
"tipo" TEXT NOT NULL,
"arquivo" TEXT NOT NULL,
"criadoEm" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "exportacoes_calculos_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "indices_monetarios" (
"id" TEXT NOT NULL,
"nome" TEXT NOT NULL,
"mesReferencia" INTEGER NOT NULL,
"anoReferencia" INTEGER NOT NULL,
"valor" DECIMAL(15,6) NOT NULL,
"dataPublicacao" TIMESTAMP(3),
"fonte" TEXT,
"criadoEm" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"atualizadoEm" TIMESTAMP(3) NOT NULL,
CONSTRAINT "indices_monetarios_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "pensoes_alimenticias" (
"id" TEXT NOT NULL,
"calculoId" TEXT NOT NULL,
"percentualSalarioMinimo" DECIMAL(8,6) NOT NULL,
"multaPactuada" DECIMAL(8,6),
"tipoAtualizacao" TEXT NOT NULL DEFAULT 'INPC',
"dataInicial" TIMESTAMP(3) NOT NULL,
"dataFinal" TIMESTAMP(3),
"observacoes" TEXT,
"criadoEm" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"atualizadoEm" TIMESTAMP(3) NOT NULL,
CONSTRAINT "pensoes_alimenticias_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "historico_salario_minimo" (
"id" TEXT NOT NULL,
"pensaoId" TEXT NOT NULL,
"dataVigencia" TIMESTAMP(3) NOT NULL,
"valor" DECIMAL(15,2) NOT NULL,
"criadoEm" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"atualizadoEm" TIMESTAMP(3) NOT NULL,
CONSTRAINT "historico_salario_minimo_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "parcelas_pensao" (
"id" TEXT NOT NULL,
"pensaoId" TEXT NOT NULL,
"competencia" TIMESTAMP(3) NOT NULL,
"valorSalarioMinimo" DECIMAL(15,2) NOT NULL,
"percentual" DECIMAL(8,6) NOT NULL,
"valorOriginal" DECIMAL(15,2) NOT NULL,
"valorCorrigido" DECIMAL(15,2) NOT NULL,
"valorJuros" DECIMAL(15,2) NOT NULL,
"valorMulta" DECIMAL(15,2) NOT NULL,
"valorTotal" DECIMAL(15,2) NOT NULL,
"pago" BOOLEAN NOT NULL DEFAULT false,
"dataPagamento" TIMESTAMP(3),
"criadoEm" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"atualizadoEm" TIMESTAMP(3) NOT NULL,
CONSTRAINT "parcelas_pensao_pkey" PRIMARY KEY ("id")
);
-- CreateIndex
CREATE UNIQUE INDEX "indices_monetarios_nome_mesReferencia_anoReferencia_key" ON "indices_monetarios"("nome", "mesReferencia", "anoReferencia");
-- CreateIndex
CREATE UNIQUE INDEX "pensoes_alimenticias_calculoId_key" ON "pensoes_alimenticias"("calculoId");
-- AddForeignKey
ALTER TABLE "calculosjudiciais" ADD CONSTRAINT "calculosjudiciais_usuarioId_fkey" FOREIGN KEY ("usuarioId") REFERENCES "usuarios"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "calculosjudiciais" ADD CONSTRAINT "calculosjudiciais_processoId_fkey" FOREIGN KEY ("processoId") REFERENCES "Processo"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "calculosjudiciais" ADD CONSTRAINT "calculosjudiciais_clienteId_fkey" FOREIGN KEY ("clienteId") REFERENCES "clientes"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "correcoes_monetarias" ADD CONSTRAINT "correcoes_monetarias_calculoId_fkey" FOREIGN KEY ("calculoId") REFERENCES "calculosjudiciais"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "juros_calculos" ADD CONSTRAINT "juros_calculos_calculoId_fkey" FOREIGN KEY ("calculoId") REFERENCES "calculosjudiciais"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "multas_calculos" ADD CONSTRAINT "multas_calculos_calculoId_fkey" FOREIGN KEY ("calculoId") REFERENCES "calculosjudiciais"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "honorarios_calculos" ADD CONSTRAINT "honorarios_calculos_calculoId_fkey" FOREIGN KEY ("calculoId") REFERENCES "calculosjudiciais"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "parcelas_calculos" ADD CONSTRAINT "parcelas_calculos_calculoId_fkey" FOREIGN KEY ("calculoId") REFERENCES "calculosjudiciais"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "descontos_calculos" ADD CONSTRAINT "descontos_calculos_calculoId_fkey" FOREIGN KEY ("calculoId") REFERENCES "calculosjudiciais"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "historicos_calculos" ADD CONSTRAINT "historicos_calculos_calculoId_fkey" FOREIGN KEY ("calculoId") REFERENCES "calculosjudiciais"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "historicos_calculos" ADD CONSTRAINT "historicos_calculos_usuarioId_fkey" FOREIGN KEY ("usuarioId") REFERENCES "usuarios"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "exportacoes_calculos" ADD CONSTRAINT "exportacoes_calculos_calculoId_fkey" FOREIGN KEY ("calculoId") REFERENCES "calculosjudiciais"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "exportacoes_calculos" ADD CONSTRAINT "exportacoes_calculos_usuarioId_fkey" FOREIGN KEY ("usuarioId") REFERENCES "usuarios"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "pensoes_alimenticias" ADD CONSTRAINT "pensoes_alimenticias_calculoId_fkey" FOREIGN KEY ("calculoId") REFERENCES "calculosjudiciais"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "historico_salario_minimo" ADD CONSTRAINT "historico_salario_minimo_pensaoId_fkey" FOREIGN KEY ("pensaoId") REFERENCES "pensoes_alimenticias"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "parcelas_pensao" ADD CONSTRAINT "parcelas_pensao_pensaoId_fkey" FOREIGN KEY ("pensaoId") REFERENCES "pensoes_alimenticias"("id") ON DELETE CASCADE ON UPDATE CASCADE;
@@ -0,0 +1,11 @@
-- Adicionar campos para relatório de audiência
ALTER TABLE "audiencias"
ADD COLUMN IF NOT EXISTS "relatorio" TEXT,
ADD COLUMN IF NOT EXISTS "dataFinalizacao" TIMESTAMP,
ALTER COLUMN "status" TYPE VARCHAR(20)
USING CASE
WHEN status = 'AGENDADA' THEN 'AGENDADA'::VARCHAR
WHEN status = 'REALIZADA' THEN 'REALIZADA'::VARCHAR
WHEN status = 'CANCELADA' THEN 'CANCELADA'::VARCHAR
ELSE 'AGENDADA'::VARCHAR
END;
@@ -0,0 +1,5 @@
-- AlterTable
ALTER TABLE "clientes"
ADD COLUMN IF NOT EXISTS "usaDNI" BOOLEAN NOT NULL DEFAULT false,
ADD COLUMN IF NOT EXISTS "possuiFilhos" BOOLEAN NOT NULL DEFAULT false,
ADD COLUMN IF NOT EXISTS "orgaoEmissor" TEXT;
@@ -0,0 +1,13 @@
-- Criar tabela para documentos
CREATE TABLE IF NOT EXISTS "documentos" (
"id" UUID PRIMARY KEY DEFAULT gen_random_uuid(),
"processoId" UUID NOT NULL,
"nome" VARCHAR(200) NOT NULL,
"tipo" VARCHAR(50) NOT NULL,
"url" TEXT NOT NULL,
"dataCriacao" TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY ("processoId") REFERENCES "processos"("id") ON DELETE CASCADE
);
-- Adicionar índice para melhor performance
CREATE INDEX IF NOT EXISTS "idx_documentos_processo" ON "documentos"("processoId");
@@ -0,0 +1,25 @@
-- AlterTable: Adicionar limites aos campos de texto
ALTER TABLE "clientes"
ALTER COLUMN "nome" TYPE VARCHAR(100),
ALTER COLUMN "email" TYPE VARCHAR(100),
ALTER COLUMN "cpfCnpj" TYPE VARCHAR(18),
ALTER COLUMN "rg" TYPE VARCHAR(20),
ALTER COLUMN "orgaoEmissor" TYPE VARCHAR(10),
ALTER COLUMN "estadoRg" TYPE CHAR(2),
ALTER COLUMN "telefone" TYPE VARCHAR(20),
ALTER COLUMN "instagram" TYPE VARCHAR(50),
ALTER COLUMN "cep" TYPE VARCHAR(9),
ALTER COLUMN "endereco" TYPE VARCHAR(150),
ALTER COLUMN "numero" TYPE VARCHAR(10),
ALTER COLUMN "complemento" TYPE VARCHAR(50),
ALTER COLUMN "bairro" TYPE VARCHAR(100),
ALTER COLUMN "cidade" TYPE VARCHAR(100),
ALTER COLUMN "estado" TYPE CHAR(2),
ALTER COLUMN "estadoCivil" TYPE VARCHAR(20),
ALTER COLUMN "profissao" TYPE VARCHAR(100),
ALTER COLUMN "vinculoEmpregaticio" TYPE VARCHAR(50),
ALTER COLUMN "tipoPrevidencia" TYPE VARCHAR(20),
ALTER COLUMN "nomePai" TYPE VARCHAR(100),
ALTER COLUMN "nomeMae" TYPE VARCHAR(100),
ALTER COLUMN "conjugeNome" TYPE VARCHAR(100),
ALTER COLUMN "conjugeCpf" TYPE VARCHAR(14);
@@ -0,0 +1,11 @@
-- AlterTable: Adicionar novos campos sem modificar os existentes
ALTER TABLE "clientes"
ADD COLUMN IF NOT EXISTS "dataNascimento" TIMESTAMP,
ADD COLUMN IF NOT EXISTS "estadoRg" TEXT,
ADD COLUMN IF NOT EXISTS "orgaoEmissor" TEXT,
ADD COLUMN IF NOT EXISTS "usaDNI" BOOLEAN DEFAULT false,
ADD COLUMN IF NOT EXISTS "possuiFilhos" BOOLEAN DEFAULT false;
-- AlterTable: Modificar valor default do tipoPrevidencia sem afetar dados existentes
ALTER TABLE "clientes"
ALTER COLUMN "tipoPrevidencia" SET DEFAULT 'NAO_CONTRIBUI';
@@ -0,0 +1,83 @@
-- Criar enum TipoParticipacao se não existir
DO $$ BEGIN
IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'tipoparticipacao') THEN
CREATE TYPE "TipoParticipacao" AS ENUM (
'AUTOR',
'REU',
'TERCEIRO_INTERESSADO'
);
END IF;
END $$;
-- Criar tabela de partes_processo mantendo dados existentes
CREATE TABLE IF NOT EXISTS "partes_processo" (
"id" UUID PRIMARY KEY DEFAULT gen_random_uuid(),
"processoId" UUID NOT NULL,
"clienteId" UUID,
"tipo" "TipoParticipacao" NOT NULL,
"nome" VARCHAR(200) NOT NULL,
"cpfCnpj" VARCHAR(18),
"principal" BOOLEAN NOT NULL DEFAULT false,
"observacoes" TEXT,
"dataCriacao" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "fk_partes_processo_processo"
FOREIGN KEY ("processoId")
REFERENCES "processos"("id")
ON DELETE CASCADE,
CONSTRAINT "fk_partes_processo_cliente"
FOREIGN KEY ("clienteId")
REFERENCES "clientes"("id")
ON DELETE SET NULL
);
-- Criar índices para melhor performance
CREATE INDEX IF NOT EXISTS "idx_partes_processo_processo" ON "partes_processo"("processoId");
CREATE INDEX IF NOT EXISTS "idx_partes_processo_cliente" ON "partes_processo"("clienteId");
-- Migrar dados existentes para a nova estrutura
INSERT INTO "partes_processo" (
"processoId",
"clienteId",
"tipo",
"nome",
"principal"
)
SELECT
p.id as "processoId",
p."clienteId",
p."tipoParteCliente"::TipoParticipacao as "tipo",
c.nome as "nome",
true as "principal"
FROM "processos" p
JOIN "clientes" c ON p."clienteId" = c.id
WHERE NOT EXISTS (
SELECT 1 FROM "partes_processo" pp
WHERE pp."processoId" = p.id AND pp."clienteId" = p."clienteId"
);
-- Adicionar partes contraparte
INSERT INTO "partes_processo" (
"processoId",
"tipo",
"nome",
"principal"
)
SELECT
p.id as "processoId",
CASE
WHEN p."tipoParteCliente" = 'AUTOR' THEN 'REU'::TipoParticipacao
ELSE 'AUTOR'::TipoParticipacao
END as "tipo",
p."nomeContraparte" as "nome",
false as "principal"
FROM "processos" p
WHERE p."nomeContraparte" IS NOT NULL
AND NOT EXISTS (
SELECT 1 FROM "partes_processo" pp
WHERE pp."processoId" = p.id AND pp.nome = p."nomeContraparte"
);
-- Não remover colunas antigas ainda para manter compatibilidade
-- Em uma futura migração, após garantir que tudo está funcionando,
-- podemos remover as colunas redundantes
@@ -0,0 +1,98 @@
-- Criar enums
CREATE TYPE "NaturezaProcesso" AS ENUM (
'CIVEL',
'CRIMINAL',
'PREVIDENCIARIO',
'TRABALHISTA',
'FAMILIA',
'TRIBUTARIO',
'ADMINISTRATIVO'
);
CREATE TYPE "TipoParte" AS ENUM (
'AUTOR',
'REU'
);
CREATE TYPE "StatusProcesso" AS ENUM (
'INICIAL',
'EM_ANDAMENTO',
'SUSPENSO',
'RECURSO',
'CONCLUSO',
'ARQUIVADO'
);
CREATE TYPE "TipoDiligencia" AS ENUM (
'CITACAO',
'INTIMACAO',
'NOTIFICACAO',
'PERICIA',
'OFICIAL_JUSTICA',
'CARTA_PRECATORIA',
'OUTROS'
);
CREATE TYPE "TipoAudiencia" AS ENUM (
'CONCILIACAO',
'INSTRUCAO',
'INICIAL',
'JULGAMENTO',
'MEDIACAO'
);
-- Alterar a tabela de processos existente
ALTER TABLE "processos"
ADD COLUMN IF NOT EXISTS "natureza" "NaturezaProcesso",
ADD COLUMN IF NOT EXISTS "tipoParteCliente" "TipoParte",
ADD COLUMN IF NOT EXISTS "valorCausa" DECIMAL(15,2),
ADD COLUMN IF NOT EXISTS "orgaoJulgador" VARCHAR(100),
ADD COLUMN IF NOT EXISTS "orgaoOrigem" VARCHAR(100),
ADD COLUMN IF NOT EXISTS "nomeContraparte" VARCHAR(100);
-- Criar nova tabela para diligências
CREATE TABLE IF NOT EXISTS "diligencias" (
"id" UUID PRIMARY KEY DEFAULT gen_random_uuid(),
"processoId" UUID NOT NULL,
"tipo" "TipoDiligencia" NOT NULL,
"descricao" TEXT NOT NULL,
"dataLimite" TIMESTAMP NOT NULL,
"status" VARCHAR(20) DEFAULT 'PENDENTE',
"responsavel" VARCHAR(100),
"observacoes" TEXT,
"dataCriacao" TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY ("processoId") REFERENCES "processos"("id") ON DELETE CASCADE
);
-- Criar nova tabela para audiências
CREATE TABLE IF NOT EXISTS "audiencias" (
"id" UUID PRIMARY KEY DEFAULT gen_random_uuid(),
"processoId" UUID NOT NULL,
"tipo" "TipoAudiencia" NOT NULL,
"data" TIMESTAMP NOT NULL,
"local" VARCHAR(200) NOT NULL,
"modalidade" VARCHAR(20) DEFAULT 'PRESENCIAL',
"linkVirtual" TEXT,
"observacoes" TEXT,
"status" VARCHAR(20) DEFAULT 'AGENDADA',
"dataCriacao" TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY ("processoId") REFERENCES "processos"("id") ON DELETE CASCADE
);
-- Criar nova tabela para movimentações
CREATE TABLE IF NOT EXISTS "movimentacoes" (
"id" UUID PRIMARY KEY DEFAULT gen_random_uuid(),
"processoId" UUID NOT NULL,
"data" TIMESTAMP NOT NULL,
"descricao" TEXT NOT NULL,
"tipo" VARCHAR(50) NOT NULL,
"documento" TEXT,
"dataCriacao" TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY ("processoId") REFERENCES "processos"("id") ON DELETE CASCADE
);
-- Adicionar índices para melhor performance
CREATE INDEX IF NOT EXISTS "idx_processo_numero" ON "processos"("numero");
CREATE INDEX IF NOT EXISTS "idx_diligencias_data" ON "diligencias"("dataLimite");
CREATE INDEX IF NOT EXISTS "idx_audiencias_data" ON "audiencias"("data");
CREATE INDEX IF NOT EXISTS "idx_movimentacoes_data" ON "movimentacoes"("data");
@@ -0,0 +1,3 @@
-- AlterTable
ALTER TABLE "clientes"
ADD COLUMN IF NOT EXISTS "estadoRg" TEXT;
@@ -0,0 +1,5 @@
-- AlterTable
ALTER TABLE "clientes"
ALTER COLUMN "dataNascimento" TYPE DATE,
ALTER COLUMN "orgaoEmissor" TYPE VARCHAR(10),
ALTER COLUMN "estadoRg" TYPE CHAR(2);
@@ -0,0 +1,15 @@
-- AlterTable
-- Primeiro, atualizar valores existentes para garantir que caibam no novo tipo
UPDATE "clientes"
SET "orgaoEmissor" = LEFT("orgaoEmissor", 10)
WHERE "orgaoEmissor" IS NOT NULL;
UPDATE "clientes"
SET "estadoRg" = UPPER(LEFT("estadoRg", 2))
WHERE "estadoRg" IS NOT NULL;
-- Agora alterar os tipos das colunas
ALTER TABLE "clientes"
ALTER COLUMN "dataNascimento" TYPE DATE USING "dataNascimento"::DATE,
ALTER COLUMN "orgaoEmissor" TYPE VARCHAR(10),
ALTER COLUMN "estadoRg" TYPE CHAR(2);
@@ -0,0 +1,5 @@
-- AlterTable
ALTER TABLE "clientes"
ALTER COLUMN "orgaoEmissor" DROP DEFAULT,
ALTER COLUMN "estadoRg" DROP DEFAULT,
ALTER COLUMN "tipoPrevidencia" SET DEFAULT 'NAO_CONTRIBUI';
@@ -0,0 +1,19 @@
-- Remover campos antigos que não são mais necessários
ALTER TABLE "processos" DROP COLUMN IF EXISTS "orgaoJulgadorId";
ALTER TABLE "processos" DROP COLUMN IF EXISTS "orgaoJulgadorRef";
ALTER TABLE "processos" DROP COLUMN IF EXISTS "eventoCalendarioId";
ALTER TABLE "processos" DROP COLUMN IF EXISTS "ultimaConsulta";
-- Ajustar campos obrigatórios e tipos
ALTER TABLE "processos"
ALTER COLUMN "natureza" SET NOT NULL,
ALTER COLUMN "tipoParteCliente" SET NOT NULL,
ALTER COLUMN "orgaoJulgador" SET NOT NULL,
ALTER COLUMN "nomeContraparte" SET NOT NULL,
ALTER COLUMN "orgaoJulgador" TYPE VARCHAR(100),
ALTER COLUMN "orgaoOrigem" TYPE VARCHAR(100),
ALTER COLUMN "nomeContraparte" TYPE VARCHAR(100);
-- Adicionar índices
CREATE INDEX IF NOT EXISTS "idx_processo_numero" ON "processos"("numero");
CREATE INDEX IF NOT EXISTS "idx_processo_cliente" ON "processos"("clienteId");
@@ -0,0 +1,28 @@
-- Fazer backup da tabela audiencias
CREATE TABLE "audiencias_backup" AS SELECT * FROM "audiencias";
-- Remover constraint existente
ALTER TABLE "audiencias" DROP CONSTRAINT IF EXISTS "audiencias_processoId_fkey";
-- Atualizar colunas
ALTER TABLE "audiencias"
ADD COLUMN IF NOT EXISTS "relatorio" TEXT,
ADD COLUMN IF NOT EXISTS "dataFinalizacao" TIMESTAMP WITH TIME ZONE,
ALTER COLUMN "id" SET DATA TYPE UUID USING (gen_random_uuid()),
ALTER COLUMN "processoId" SET DATA TYPE UUID USING ("processoId"::UUID),
ALTER COLUMN "status" SET DATA TYPE VARCHAR(20);
-- Recriar foreign key com UUID
ALTER TABLE "audiencias"
ADD CONSTRAINT "audiencias_processoId_fkey"
FOREIGN KEY ("processoId") REFERENCES "processos"("id") ON DELETE CASCADE;
-- Adicionar check constraint para status
ALTER TABLE "audiencias"
ADD CONSTRAINT "audiencias_status_check"
CHECK (status IN ('AGENDADA', 'REALIZADA', 'CANCELADA', 'REDESIGNADA'));
-- Atualizar status existentes
UPDATE "audiencias"
SET status = 'AGENDADA'
WHERE status IS NULL OR status NOT IN ('AGENDADA', 'REALIZADA', 'CANCELADA', 'REDESIGNADA');
@@ -0,0 +1,24 @@
-- Adicionar colunas novas sem modificar as existentes
ALTER TABLE "audiencias"
ADD COLUMN IF NOT EXISTS "relatorio" TEXT,
ADD COLUMN IF NOT EXISTS "dataFinalizacao" TIMESTAMP WITH TIME ZONE;
-- Atualizar coluna de status mantendo os dados existentes
DO $$
BEGIN
-- Verificar se a constraint já existe antes de tentar remover
IF EXISTS (SELECT 1 FROM information_schema.constraint_column_usage WHERE constraint_name = 'audiencias_status_check') THEN
ALTER TABLE "audiencias" DROP CONSTRAINT "audiencias_status_check";
END IF;
END $$;
-- Adicionar nova constraint de status
ALTER TABLE "audiencias"
ADD CONSTRAINT "audiencias_status_check"
CHECK (status IN ('AGENDADA', 'REALIZADA', 'CANCELADA', 'REDESIGNADA'));
-- Atualizar valores existentes para o novo formato
UPDATE "audiencias"
SET status = 'AGENDADA'
WHERE status NOT IN ('AGENDADA', 'REALIZADA', 'CANCELADA', 'REDESIGNADA')
OR status IS NULL;
@@ -0,0 +1,5 @@
-- Adicionar coluna dadosDatajud
ALTER TABLE "processos" ADD COLUMN "dadosDatajud" JSONB;
-- Criar índice GIN para busca em JSON
CREATE INDEX "idx_processos_datajud" ON "processos" USING gin("dadosDatajud");
@@ -0,0 +1,12 @@
-- Adicionar novas colunas se não existirem
ALTER TABLE "processos"
ADD COLUMN IF NOT EXISTS "dataAjuizamento" TIMESTAMP,
ADD COLUMN IF NOT EXISTS "classeProcessual" VARCHAR(255),
ADD COLUMN IF NOT EXISTS "assuntos" TEXT[],
ADD COLUMN IF NOT EXISTS "nivelSigilo" INTEGER,
ADD COLUMN IF NOT EXISTS "dadosDatajud" JSONB;
-- Criar índices sem forçar
CREATE INDEX IF NOT EXISTS "idx_processos_data_ajuizamento" ON "processos"("dataAjuizamento");
CREATE INDEX IF NOT EXISTS "idx_processos_classe" ON "processos"("classeProcessual");
CREATE INDEX IF NOT EXISTS "idx_processos_datajud" ON "processos" USING gin("dadosDatajud");
@@ -0,0 +1,52 @@
import { PrismaClient } from '@prisma/client'
const prisma = new PrismaClient()
async function main() {
await prisma.$executeRaw`
CREATE TYPE "TipoDocumento" AS ENUM ('PETICAO', 'CONTRATO', 'PROCURACAO', 'DECLARACAO', 'OUTROS');
-- Criar tabela de documentos
CREATE TABLE IF NOT EXISTS "documentos" (
"id" UUID NOT NULL DEFAULT gen_random_uuid(),
"nome" VARCHAR(200) NOT NULL,
"tipo" "TipoDocumento" NOT NULL,
"conteudo" TEXT NOT NULL,
"url" TEXT,
"processoId" UUID REFERENCES "processos"(id),
"atendimentoId" UUID REFERENCES "atendimentos"(id),
"anexoId" UUID UNIQUE REFERENCES "anexos"(id),
"criadoPorId" UUID NOT NULL REFERENCES "usuarios"(id),
"criadoEm" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"atualizadoEm" TIMESTAMP(3) NOT NULL,
CONSTRAINT "documentos_pkey" PRIMARY KEY ("id")
);
-- Criar tabela de modelos de documentos
CREATE TABLE IF NOT EXISTS "documentos_modelos" (
"id" UUID NOT NULL DEFAULT gen_random_uuid(),
"nome" VARCHAR(200) NOT NULL,
"descricao" TEXT,
"tipo" "TipoDocumento" NOT NULL,
"conteudo" TEXT NOT NULL,
"variaveis" TEXT[] DEFAULT ARRAY[]::TEXT[],
"criadoEm" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"atualizadoEm" TIMESTAMP(3) NOT NULL,
CONSTRAINT "documentos_modelos_pkey" PRIMARY KEY ("id")
);
-- Criar índices
CREATE INDEX "documentos_processoId_idx" ON "documentos"("processoId");
CREATE INDEX "documentos_atendimentoId_idx" ON "documentos"("atendimentoId");
`;
}
main()
.catch(e => {
console.error(e);
process.exit(1);
})
.finally(async () => {
await prisma.$disconnect();
});
Whitespace-only changes.
@@ -0,0 +1,9 @@
ALTER TABLE "processos"
ADD COLUMN IF NOT EXISTS "dataAjuizamento" TIMESTAMP,
ADD COLUMN IF NOT EXISTS "classeProcessual" VARCHAR(255),
ADD COLUMN IF NOT EXISTS "assuntos" TEXT[],
ADD COLUMN IF NOT EXISTS "nivelSigilo" INTEGER;
-- Índices para melhorar performance
CREATE INDEX IF NOT EXISTS "idx_processos_data_ajuizamento" ON "processos"("dataAjuizamento");
CREATE INDEX IF NOT EXISTS "idx_processos_classe" ON "processos"("classeProcessual");
@@ -0,0 +1,19 @@
import { PrismaClient } from '@prisma/client'
const prisma = new PrismaClient()
async function main() {
await prisma.$executeRaw`
ALTER TABLE "configuracao_documento"
ADD COLUMN "templatePadrao" TEXT,
ADD COLUMN "margensTemplate" JSONB DEFAULT '{"top": 35, "bottom": 29, "left": 25, "right": 25}'::jsonb;
`;
}
main()
.catch(e => {
console.error(e);
process.exit(1);
})
.finally(async () => {
await prisma.$disconnect();
});
@@ -0,0 +1,22 @@
import { PrismaClient } from '@prisma/client'
const prisma = new PrismaClient()
async function main() {
await prisma.$executeRaw`
ALTER TABLE "configuracao_documento"
ADD COLUMN "timbradoUrl" TEXT,
ADD COLUMN "timbradoMarginTop" INTEGER DEFAULT 100,
ADD COLUMN "timbradoMarginBottom" INTEGER DEFAULT 50,
ADD COLUMN "timbradoMarginLeft" INTEGER DEFAULT 50,
ADD COLUMN "timbradoMarginRight" INTEGER DEFAULT 50;
`;
}
main()
.catch(e => {
console.error(e);
process.exit(1);
})
.finally(async () => {
await prisma.$disconnect();
});
@@ -0,0 +1,41 @@
-- Passo 1: Adicionar colunas como nullable
ALTER TABLE "processos"
ADD COLUMN "tribunalUF" VARCHAR(20) NULL,
ADD COLUMN "tribunal" VARCHAR(50) NULL,
ADD COLUMN "numeroOriginal" VARCHAR(50) NULL;
-- Passo 2: Preencher dados existentes
UPDATE "processos"
SET
"tribunalUF" =
CASE
WHEN "orgaoJulgador" LIKE '%TJTO%' THEN 'TO'
WHEN "orgaoJulgador" LIKE '%TRF1%' THEN 'DF'
ELSE 'TO' -- Default para processos existentes
END,
"tribunal" =
CASE
WHEN "orgaoJulgador" LIKE '%TJTO%' THEN 'TJTO'
WHEN "orgaoJulgador" LIKE '%TRF1%' THEN 'TRF1'
ELSE 'TJTO' -- Default para processos existentes
END;
-- Passo 3: Verificar se não há valores nulos
DO $$
BEGIN
IF EXISTS (
SELECT 1 FROM "processos"
WHERE "tribunalUF" IS NULL OR "tribunal" IS NULL
) THEN
RAISE EXCEPTION 'Ainda existem registros com valores nulos';
END IF;
END $$;
-- Passo 4: Tornar colunas NOT NULL
ALTER TABLE "processos"
ALTER COLUMN "tribunalUF" SET NOT NULL,
ALTER COLUMN "tribunal" SET NOT NULL;
-- Passo 5: Criar índices
CREATE INDEX IF NOT EXISTS "idx_processos_tribunal" ON "processos"("tribunal");
CREATE INDEX IF NOT EXISTS "idx_processos_tribunalUF" ON "processos"("tribunalUF");
@@ -0,0 +1,30 @@
-- Adicionar novas colunas sem remover as antigas
ALTER TABLE "processos"
ADD COLUMN IF NOT EXISTS "tribunalUF" VARCHAR(20),
ADD COLUMN IF NOT EXISTS "tribunal" VARCHAR(50),
ADD COLUMN IF NOT EXISTS "numeroOriginal" VARCHAR(50);
-- Migrar dados existentes mantendo os dados antigos
UPDATE "processos"
SET
"tribunalUF" =
CASE
WHEN "orgaoJulgador" LIKE '%TJTO%' THEN 'TO'
WHEN "orgaoJulgador" LIKE '%TRF1%' THEN 'DF'
ELSE 'TO'
END
WHERE "tribunalUF" IS NULL;
UPDATE "processos"
SET
"tribunal" =
CASE
WHEN "orgaoJulgador" LIKE '%TJTO%' THEN 'TJTO'
WHEN "orgaoJulgador" LIKE '%TRF1%' THEN 'TRF1'
ELSE 'TJTO'
END
WHERE "tribunal" IS NULL;
-- Criar índices sem interferir nos existentes
CREATE INDEX IF NOT EXISTS "idx_processos_tribunal" ON "processos"("tribunal");
CREATE INDEX IF NOT EXISTS "idx_processos_tribunalUF" ON "processos"("tribunalUF");
@@ -0,0 +1,23 @@
-- Criar tipo temporário com todos os valores
CREATE TYPE "StatusPagamento_new" AS ENUM ('PENDENTE', 'PARCIALMENTE_PAGO', 'PAGO', 'VENCIDO', 'CANCELADO');
-- Converter a coluna antiga para a nova
ALTER TABLE "parcelas_honorario"
ALTER COLUMN status TYPE "StatusPagamento_new"
USING status::text::"StatusPagamento_new";
-- Remover o tipo antigo
DROP TYPE "StatusPagamento";
-- Renomear o novo tipo para o nome original
ALTER TYPE "StatusPagamento_new" RENAME TO "StatusPagamento";
-- Adicionar a coluna valorPago se ela não existir
DO $$
BEGIN
IF NOT EXISTS (SELECT 1 FROM information_schema.columns
WHERE table_name = 'parcelas_honorario'
AND column_name = 'valorpago') THEN
ALTER TABLE "parcelas_honorario" ADD COLUMN "valorPago" DECIMAL(10,2);
END IF;
END $$;
@@ -0,0 +1,23 @@
CREATE TABLE IF NOT EXISTS "Anexo" (
"id" UUID NOT NULL DEFAULT gen_random_uuid(),
"nome" TEXT NOT NULL,
"url" TEXT NOT NULL,
"tipo" TEXT NOT NULL,
"tamanho" INTEGER NOT NULL,
"atendimentoId" UUID,
"tarefaId" UUID,
"criadoEm" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "Anexo_pkey" PRIMARY KEY ("id")
);
-- Criar índices
CREATE INDEX IF NOT EXISTS "Anexo_atendimentoId_idx" ON "Anexo"("atendimentoId");
CREATE INDEX IF NOT EXISTS "Anexo_tarefaId_idx" ON "Anexo"("tarefaId");
-- Adicionar foreign keys
ALTER TABLE "Anexo" ADD CONSTRAINT "Anexo_atendimentoId_fkey"
FOREIGN KEY ("atendimentoId") REFERENCES "Atendimento"("id") ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE "Anexo" ADD CONSTRAINT "Anexo_tarefaId_fkey"
FOREIGN KEY ("tarefaId") REFERENCES "Tarefa"("id") ON DELETE CASCADE ON UPDATE CASCADE;
@@ -0,0 +1,34 @@
import { PrismaClient } from '@prisma/client'
const prisma = new PrismaClient()
async function main() {
await prisma.$executeRaw`
CREATE TABLE IF NOT EXISTS "configuracao_documento" (
"id" UUID NOT NULL DEFAULT gen_random_uuid(),
"headerImageUrl" TEXT,
"footerImageUrl" TEXT,
"logoUrl" TEXT,
"criadoEm" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "configuracao_documento_pkey" PRIMARY KEY ("id")
);
`;
// Inserir configuração padrão
await prisma.configuracaoDocumento.create({
data: {
headerImageUrl: '',
footerImageUrl: '',
logoUrl: ''
}
});
}
main()
.catch(e => {
console.error(e);
process.exit(1);
})
.finally(async () => {
await prisma.$disconnect();
});
@@ -0,0 +1,9 @@
-- AlterTable
ALTER TABLE "processos"
ADD COLUMN IF NOT EXISTS "statusAtividade" VARCHAR(20) NOT NULL DEFAULT 'ATIVO';
-- AlterTable
ALTER TABLE "audiencias"
ADD COLUMN IF NOT EXISTS "relatorio" TEXT,
ADD COLUMN IF NOT EXISTS "dataFinalizacao" TIMESTAMP WITH TIME ZONE,
ALTER COLUMN "status" SET DEFAULT 'AGENDADA';
@@ -0,0 +1,2 @@
-- Forçar sincronização do estado atual
SELECT 1;
@@ -0,0 +1,16 @@
-- Primeiro, alterar as foreign keys existentes
ALTER TABLE "audiencias" DROP CONSTRAINT IF EXISTS "audiencias_processoId_fkey";
ALTER TABLE "partes_processo" DROP CONSTRAINT IF EXISTS "fk_partes_processo_processo";
-- Converter a coluna id para UUID
ALTER TABLE "processos"
ALTER COLUMN "id" TYPE UUID USING id::UUID;
-- Recriar as foreign keys
ALTER TABLE "audiencias"
ADD CONSTRAINT "audiencias_processoId_fkey"
FOREIGN KEY ("processoId") REFERENCES "processos"("id") ON DELETE CASCADE;
ALTER TABLE "partes_processo"
ADD CONSTRAINT "fk_partes_processo_processo"
FOREIGN KEY ("processoId") REFERENCES "processos"("id") ON DELETE CASCADE;
+13
View File
@@ -0,0 +1,13 @@
-- Criar as tabelas principais
CREATE TABLE "usuarios" (
"id" UUID NOT NULL DEFAULT gen_random_uuid(),
"nome" VARCHAR(255) NOT NULL,
"email" VARCHAR(255) NOT NULL UNIQUE,
"senha" VARCHAR(255) NOT NULL,
"cargo" VARCHAR(50) NOT NULL,
"dataCriacao" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "usuarios_pkey" PRIMARY KEY ("id")
);
-- ... resto da criação das tabelas conforme schema.prisma ...
@@ -0,0 +1,15 @@
-- Verificar se todos os registros têm os valores
DO $$
BEGIN
IF EXISTS (
SELECT 1 FROM "processos"
WHERE "tribunalUF" IS NULL OR "tribunal" IS NULL
) THEN
RAISE EXCEPTION 'Ainda existem registros com valores nulos';
END IF;
END $$;
-- Se passar da verificação, tornar as colunas NOT NULL
ALTER TABLE "processos"
ALTER COLUMN "tribunalUF" SET NOT NULL,
ALTER COLUMN "tribunal" SET NOT NULL;
@@ -0,0 +1,43 @@
-- Limpar migrações anteriores
DELETE FROM "_prisma_migrations"
WHERE migration_name LIKE '%add_audiencia_report%';
-- Atualizar tabela de audiências de forma segura
DO $$
BEGIN
-- Adicionar novas colunas se não existirem
BEGIN
ALTER TABLE "audiencias"
ADD COLUMN IF NOT EXISTS "relatorio" TEXT,
ADD COLUMN IF NOT EXISTS "dataFinalizacao" TIMESTAMP WITH TIME ZONE;
EXCEPTION
WHEN duplicate_column THEN
NULL;
END;
-- Atualizar tipo da coluna status
ALTER TABLE "audiencias"
ALTER COLUMN "status" TYPE VARCHAR(20);
-- Remover constraint antiga se existir
IF EXISTS (
SELECT 1
FROM information_schema.constraint_column_usage
WHERE constraint_name = 'audiencias_status_check'
) THEN
ALTER TABLE "audiencias"
DROP CONSTRAINT "audiencias_status_check";
END IF;
-- Adicionar nova constraint
ALTER TABLE "audiencias"
ADD CONSTRAINT "audiencias_status_check"
CHECK (status IN ('AGENDADA', 'REALIZADA', 'CANCELADA', 'REDESIGNADA'));
-- Atualizar registros existentes
UPDATE "audiencias"
SET status = 'AGENDADA'
WHERE status NOT IN ('AGENDADA', 'REALIZADA', 'CANCELADA', 'REDESIGNADA')
OR status IS NULL;
END $$;
@@ -0,0 +1,22 @@
import { PrismaClient } from '@prisma/client'
const prisma = new PrismaClient()
async function main() {
await prisma.$executeRaw`
ALTER TABLE "configuracao_documento"
ADD COLUMN IF NOT EXISTS "timbradoUrl" TEXT,
ADD COLUMN IF NOT EXISTS "timbradoMarginTop" INTEGER DEFAULT 100,
ADD COLUMN IF NOT EXISTS "timbradoMarginBottom" INTEGER DEFAULT 50,
ADD COLUMN IF NOT EXISTS "timbradoMarginLeft" INTEGER DEFAULT 50,
ADD COLUMN IF NOT EXISTS "timbradoMarginRight" INTEGER DEFAULT 50;
`;
}
main()
.catch(e => {
console.error(e);
process.exit(1);
})
.finally(async () => {
await prisma.$disconnect();
});
@@ -0,0 +1,18 @@
-- Adicionando novas colunas
ALTER TABLE "processos" ADD COLUMN "tribunalUF" VARCHAR(20);
ALTER TABLE "processos" ADD COLUMN "tribunal" VARCHAR(50);
ALTER TABLE "processos" ADD COLUMN "numeroOriginal" VARCHAR(50);
-- Preenchendo dados existentes (temporário)
UPDATE "processos" SET
"tribunalUF" = 'TO',
"tribunal" = 'TJTO'
WHERE "tribunalUF" IS NULL;
-- Tornando colunas NOT NULL após migração
ALTER TABLE "processos" ALTER COLUMN "tribunalUF" SET NOT NULL;
ALTER TABLE "processos" ALTER COLUMN "tribunal" SET NOT NULL;
-- Removendo colunas antigas
ALTER TABLE "processos" DROP COLUMN "orgaoJulgador";
ALTER TABLE "processos" DROP COLUMN "orgaoOrigem";
+35
View File
@@ -0,0 +1,35 @@
DO $$
BEGIN
-- 1. Remover constraints existentes se existirem
IF EXISTS (SELECT 1 FROM information_schema.table_constraints WHERE constraint_name = 'audiencias_processoId_fkey') THEN
ALTER TABLE "audiencias" DROP CONSTRAINT "audiencias_processoId_fkey";
END IF;
IF EXISTS (SELECT 1 FROM information_schema.table_constraints WHERE constraint_name = 'fk_partes_processo_processo') THEN
ALTER TABLE "partes_processo" DROP CONSTRAINT "fk_partes_processo_processo";
END IF;
IF EXISTS (SELECT 1 FROM information_schema.table_constraints WHERE constraint_name = 'movimentacoes_processoId_fkey') THEN
ALTER TABLE "movimentacoes" DROP CONSTRAINT "movimentacoes_processoId_fkey";
END IF;
-- 2. Garantir que todas as colunas são UUID
ALTER TABLE "processos" ALTER COLUMN "id" TYPE UUID USING COALESCE("id"::UUID, gen_random_uuid());
ALTER TABLE "audiencias" ALTER COLUMN "processoId" TYPE UUID USING "processoId"::UUID;
ALTER TABLE "partes_processo" ALTER COLUMN "processoId" TYPE UUID USING "processoId"::UUID;
ALTER TABLE "movimentacoes" ALTER COLUMN "processoId" TYPE UUID USING "processoId"::UUID;
-- 3. Recriar as foreign keys
ALTER TABLE "audiencias"
ADD CONSTRAINT "audiencias_processoId_fkey"
FOREIGN KEY ("processoId") REFERENCES "processos"("id") ON DELETE CASCADE;
ALTER TABLE "partes_processo"
ADD CONSTRAINT "fk_partes_processo_processo"
FOREIGN KEY ("processoId") REFERENCES "processos"("id") ON DELETE CASCADE;
ALTER TABLE "movimentacoes"
ADD CONSTRAINT "movimentacoes_processoId_fkey"
FOREIGN KEY ("processoId") REFERENCES "processos"("id") ON DELETE CASCADE;
END $$;
+51
View File
@@ -0,0 +1,51 @@
DO $$
BEGIN
-- 1. Remover todas as foreign keys primeiro
ALTER TABLE "documentos" DROP CONSTRAINT IF EXISTS "documentos_processoId_fkey";
ALTER TABLE "audiencias" DROP CONSTRAINT IF EXISTS "audiencias_processoId_fkey";
ALTER TABLE "partes_processo" DROP CONSTRAINT IF EXISTS "fk_partes_processo_processo";
ALTER TABLE "movimentacoes" DROP CONSTRAINT IF EXISTS "movimentacoes_processoId_fkey";
-- 2. Alterar todos os IDs e chaves estrangeiras para UUID
-- Processos
ALTER TABLE "processos"
ALTER COLUMN "id" TYPE UUID USING COALESCE("id"::UUID, gen_random_uuid());
-- Documentos
ALTER TABLE "documentos"
ALTER COLUMN "id" TYPE UUID USING COALESCE("id"::UUID, gen_random_uuid()),
ALTER COLUMN "processoId" TYPE UUID USING "processoId"::UUID;
-- Audiências
ALTER TABLE "audiencias"
ALTER COLUMN "id" TYPE UUID USING COALESCE("id"::UUID, gen_random_uuid()),
ALTER COLUMN "processoId" TYPE UUID USING "processoId"::UUID;
-- Partes do Processo
ALTER TABLE "partes_processo"
ALTER COLUMN "id" TYPE UUID USING COALESCE("id"::UUID, gen_random_uuid()),
ALTER COLUMN "processoId" TYPE UUID USING "processoId"::UUID;
-- Movimentações
ALTER TABLE "movimentacoes"
ALTER COLUMN "id" TYPE UUID USING COALESCE("id"::UUID, gen_random_uuid()),
ALTER COLUMN "processoId" TYPE UUID USING "processoId"::UUID;
-- 3. Recriar todas as foreign keys
ALTER TABLE "documentos"
ADD CONSTRAINT "documentos_processoId_fkey"
FOREIGN KEY ("processoId") REFERENCES "processos"("id") ON DELETE CASCADE;
ALTER TABLE "audiencias"
ADD CONSTRAINT "audiencias_processoId_fkey"
FOREIGN KEY ("processoId") REFERENCES "processos"("id") ON DELETE CASCADE;
ALTER TABLE "partes_processo"
ADD CONSTRAINT "fk_partes_processo_processo"
FOREIGN KEY ("processoId") REFERENCES "processos"("id") ON DELETE CASCADE;
ALTER TABLE "movimentacoes"
ADD CONSTRAINT "movimentacoes_processoId_fkey"
FOREIGN KEY ("processoId") REFERENCES "processos"("id") ON DELETE CASCADE;
END $$;
+24
View File
@@ -0,0 +1,24 @@
-- Remove todas as foreign keys primeiro
ALTER TABLE "audiencias" DROP CONSTRAINT IF EXISTS "audiencias_processoId_fkey";
ALTER TABLE "partes_processo" DROP CONSTRAINT IF EXISTS "fk_partes_processo_processo";
ALTER TABLE "movimentacoes" DROP CONSTRAINT IF EXISTS "movimentacoes_processoId_fkey";
-- Corrige o tipo das colunas de ID
ALTER TABLE "processos" ALTER COLUMN "id" TYPE UUID USING COALESCE("id"::UUID, gen_random_uuid());
ALTER TABLE "audiencias" ALTER COLUMN "id" TYPE UUID USING COALESCE("id"::UUID, gen_random_uuid());
ALTER TABLE "audiencias" ALTER COLUMN "processoId" TYPE UUID USING "processoId"::UUID;
ALTER TABLE "partes_processo" ALTER COLUMN "processoId" TYPE UUID USING "processoId"::UUID;
ALTER TABLE "movimentacoes" ALTER COLUMN "processoId" TYPE UUID USING "processoId"::UUID;
-- Recria as foreign keys
ALTER TABLE "audiencias"
ADD CONSTRAINT "audiencias_processoId_fkey"
FOREIGN KEY ("processoId") REFERENCES "processos"("id") ON DELETE CASCADE;
ALTER TABLE "partes_processo"
ADD CONSTRAINT "fk_partes_processo_processo"
FOREIGN KEY ("processoId") REFERENCES "processos"("id") ON DELETE CASCADE;
ALTER TABLE "movimentacoes"
ADD CONSTRAINT "movimentacoes_processoId_fkey"
FOREIGN KEY ("processoId") REFERENCES "processos"("id") ON DELETE CASCADE;
@@ -0,0 +1,30 @@
-- Drop constraints first
ALTER TABLE "partes_processo"
DROP CONSTRAINT IF EXISTS "partes_processo_pkey",
DROP CONSTRAINT IF EXISTS "partes_processo_processoId_fkey",
DROP CONSTRAINT IF EXISTS "partes_processo_clienteId_fkey";
-- Fix columns and constraints
ALTER TABLE "partes_processo"
ALTER COLUMN "id" TYPE UUID USING id::UUID,
ALTER COLUMN "processoId" TYPE UUID USING "processoId"::UUID,
ALTER COLUMN "clienteId" TYPE UUID USING "clienteId"::UUID,
ALTER COLUMN "tipo" TYPE VARCHAR(20),
ALTER COLUMN "nome" TYPE VARCHAR(200),
ALTER COLUMN "cpfCnpj" TYPE VARCHAR(18),
ADD PRIMARY KEY ("id");
-- Recreate foreign keys
ALTER TABLE "partes_processo"
ADD CONSTRAINT "partes_processo_processoId_fkey"
FOREIGN KEY ("processoId")
REFERENCES "processos"("id")
ON DELETE CASCADE,
ADD CONSTRAINT "partes_processo_clienteId_fkey"
FOREIGN KEY ("clienteId")
REFERENCES "clientes"("id")
ON DELETE SET NULL;
-- Create indexes
CREATE INDEX IF NOT EXISTS "partes_processo_processoId_idx" ON "partes_processo"("processoId");
CREATE INDEX IF NOT EXISTS "partes_processo_clienteId_idx" ON "partes_processo"("clienteId");
@@ -0,0 +1,2 @@
ALTER TABLE "processos"
ALTER COLUMN "id" SET DEFAULT gen_random_uuid();
+44
View File
@@ -0,0 +1,44 @@
-- Garantir que todas as colunas de ID sejam UUID
BEGIN;
-- Remover constraints existentes para evitar conflitos
ALTER TABLE "audiencias" DROP CONSTRAINT IF EXISTS "audiencias_processoId_fkey";
ALTER TABLE "partes_processo" DROP CONSTRAINT IF EXISTS "fk_partes_processo_processo";
ALTER TABLE "diligencias" DROP CONSTRAINT IF EXISTS "diligencias_processoId_fkey";
ALTER TABLE "movimentacoes" DROP CONSTRAINT IF EXISTS "movimentacoes_processoId_fkey";
-- Converter IDs para UUID
ALTER TABLE "processos"
ALTER COLUMN "id" TYPE UUID USING id::UUID;
ALTER TABLE "audiencias"
ALTER COLUMN "id" TYPE UUID USING id::UUID,
ALTER COLUMN "processoId" TYPE UUID USING "processoId"::UUID;
ALTER TABLE "partes_processo"
ALTER COLUMN "processoId" TYPE UUID USING "processoId"::UUID;
ALTER TABLE "diligencias"
ALTER COLUMN "processoId" TYPE UUID USING "processoId"::UUID;
ALTER TABLE "movimentacoes"
ALTER COLUMN "processoId" TYPE UUID USING "processoId"::UUID;
-- Recriar as foreign keys
ALTER TABLE "audiencias"
ADD CONSTRAINT "audiencias_processoId_fkey"
FOREIGN KEY ("processoId") REFERENCES "processos"("id") ON DELETE CASCADE;
ALTER TABLE "partes_processo"
ADD CONSTRAINT "fk_partes_processo_processo"
FOREIGN KEY ("processoId") REFERENCES "processos"("id") ON DELETE CASCADE;
ALTER TABLE "diligencias"
ADD CONSTRAINT "diligencias_processoId_fkey"
FOREIGN KEY ("processoId") REFERENCES "processos"("id") ON DELETE CASCADE;
ALTER TABLE "movimentacoes"
ADD CONSTRAINT "movimentacoes_processoId_fkey"
FOREIGN KEY ("processoId") REFERENCES "processos"("id") ON DELETE CASCADE;
COMMIT;
+3
View File
@@ -0,0 +1,3 @@
# Please do not edit this file manually
# It should be added in your version-control system (e.g., Git)
provider = "postgresql"
+29
View File
@@ -0,0 +1,29 @@
import { PrismaClient } from "@prisma/client";
import * as bcrypt from "bcryptjs";
const prisma = new PrismaClient();
async function main() {
const senhaHash = await bcrypt.hash("34641747", 10);
await prisma.usuario.upsert({
where: { email: "rodrigo@advx.com" },
update: {},
create: {
email: "rodrigo@advx.com",
nome: "Rodrigo",
senha: senhaHash,
cargo: "admin",
dataCriacao: new Date(),
},
});
}
main()
.catch((e) => {
console.error(e);
process.exit(1);
})
.finally(async () => {
await prisma.$disconnect();
});
+1069
View File
File diff suppressed because it is too large. Load diff
Loaded 100 of 423 files, more files were not shown because too many files have changed in this diff. Show more