Estiliza pagina de upload externo - responsiva (novo47)
This commit is contained in:
1 parent
05cd7b9c79
commit
631afa1c46
15 files changed
+1818
-24
No files matched your search
@@ -0,0 +1,9 @@
|
|||||||
|
<IfModule mod_headers.c>
|
||||||
|
Header set Access-Control-Allow-Origin "*"
|
||||||
|
</IfModule>
|
||||||
|
|
||||||
|
<Directory "temp">
|
||||||
|
Options Indexes MultiViews
|
||||||
|
AllowOverride All
|
||||||
|
Require all granted
|
||||||
|
</Directory>
|
||||||
+36
@@ -0,0 +1,36 @@
|
|||||||
|
<?php
|
||||||
|
// Configurações do banco de dados
|
||||||
|
define('DB_HOST', '10.15.0.42');
|
||||||
|
define('DB_USER', 'root');
|
||||||
|
define('DB_PASS', '34641747');
|
||||||
|
define('DB_NAME', 'valida');
|
||||||
|
|
||||||
|
// Criar conexão
|
||||||
|
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
|
||||||
|
|
||||||
|
// Verificar conexão
|
||||||
|
if ($conn->connect_error) {
|
||||||
|
die("Falha na conexão: " . $conn->connect_error);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Configurar charset
|
||||||
|
$conn->set_charset("utf8mb4");
|
||||||
|
|
||||||
|
// Configurar timezone
|
||||||
|
date_default_timezone_set('America/Sao_Paulo');
|
||||||
|
|
||||||
|
// Função para limpar input
|
||||||
|
function clean_input($data) {
|
||||||
|
global $conn;
|
||||||
|
$data = trim($data);
|
||||||
|
$data = stripslashes($data);
|
||||||
|
$data = htmlspecialchars($data);
|
||||||
|
return $conn->real_escape_string($data);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Função para verificar se é uma requisição AJAX
|
||||||
|
function is_ajax_request() {
|
||||||
|
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) &&
|
||||||
|
strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
|
||||||
|
}
|
||||||
|
?>
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
<?php
|
||||||
|
require_once 'config.php';
|
||||||
|
|
||||||
|
if (isset($_GET['id'])) {
|
||||||
|
$doc_id = intval($_GET['id']);
|
||||||
|
|
||||||
|
// Buscar informações do documento
|
||||||
|
$sql = "SELECT arquivo, client_id FROM documentos WHERE id = ?";
|
||||||
|
$stmt = $conn->prepare($sql);
|
||||||
|
$stmt->bind_param("i", $doc_id);
|
||||||
|
$stmt->execute();
|
||||||
|
$result = $stmt->get_result();
|
||||||
|
|
||||||
|
if ($doc = $result->fetch_assoc()) {
|
||||||
|
// Deletar arquivo físico
|
||||||
|
if (file_exists($doc['arquivo'])) {
|
||||||
|
unlink($doc['arquivo']);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Deletar registro do banco
|
||||||
|
$sql = "DELETE FROM documentos WHERE id = ?";
|
||||||
|
$stmt = $conn->prepare($sql);
|
||||||
|
$stmt->bind_param("i", $doc_id);
|
||||||
|
|
||||||
|
if ($stmt->execute()) {
|
||||||
|
header("Location: index.php?page=doc_list&client_id=" . $doc['client_id'] . "&status=deleted");
|
||||||
|
} else {
|
||||||
|
die("Erro ao excluir documento: " . $stmt->error);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
die("Documento não encontrado");
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
die("ID do documento não fornecido");
|
||||||
|
}
|
||||||
|
?>
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
CREATE TABLE IF NOT EXISTS clientes (
|
||||||
|
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||||
|
nome VARCHAR(100) NOT NULL,
|
||||||
|
cpf VARCHAR(14) UNIQUE,
|
||||||
|
email VARCHAR(100),
|
||||||
|
telefone VARCHAR(20),
|
||||||
|
data_cadastro DATETIME DEFAULT CURRENT_TIMESTAMP
|
||||||
|
) ENGINE=InnoDB;
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS documentos (
|
||||||
|
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||||
|
client_id INT NOT NULL,
|
||||||
|
tipo VARCHAR(50) NOT NULL,
|
||||||
|
arquivo VARCHAR(255) NOT NULL,
|
||||||
|
data_upload DATETIME NOT NULL,
|
||||||
|
FOREIGN KEY (client_id) REFERENCES clients(id) ON DELETE CASCADE,
|
||||||
|
INDEX idx_client_id (client_id)
|
||||||
|
) ENGINE=InnoDB;
|
||||||
@@ -0,0 +1,100 @@
|
|||||||
|
import cv2
|
||||||
|
import numpy as np
|
||||||
|
import sys
|
||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
import os
|
||||||
|
from PIL import Image
|
||||||
|
|
||||||
|
def order_points(pts):
|
||||||
|
rect = np.zeros((4, 2), dtype="float32")
|
||||||
|
s = pts.sum(axis=1)
|
||||||
|
rect[0] = pts[np.argmin(s)]
|
||||||
|
rect[2] = pts[np.argmax(s)]
|
||||||
|
diff = np.diff(pts, axis=1)
|
||||||
|
rect[1] = pts[np.argmin(diff)]
|
||||||
|
rect[3] = pts[np.argmax(diff)]
|
||||||
|
return rect
|
||||||
|
|
||||||
|
def process_document(image_path, doc_type, output_dir):
|
||||||
|
try:
|
||||||
|
# Carrega e verifica a imagem
|
||||||
|
image = cv2.imread(str(image_path))
|
||||||
|
if image is None:
|
||||||
|
raise Exception("Não foi possível carregar a imagem")
|
||||||
|
|
||||||
|
original = image.copy()
|
||||||
|
|
||||||
|
# Pré-processamento
|
||||||
|
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
|
||||||
|
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
|
||||||
|
edges = cv2.Canny(blurred, 50, 150)
|
||||||
|
|
||||||
|
# Encontra contornos
|
||||||
|
contours, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
|
||||||
|
if not contours:
|
||||||
|
raise Exception("Nenhum contorno encontrado")
|
||||||
|
|
||||||
|
# Ordena contornos por área
|
||||||
|
contours = sorted(contours, key=cv2.contourArea, reverse=True)
|
||||||
|
doc_corners = None
|
||||||
|
|
||||||
|
# Procura o documento
|
||||||
|
for contour in contours:
|
||||||
|
peri = cv2.arcLength(contour, True)
|
||||||
|
approx = cv2.approxPolyDP(contour, 0.02 * peri, True)
|
||||||
|
if len(approx) == 4:
|
||||||
|
doc_corners = approx
|
||||||
|
break
|
||||||
|
|
||||||
|
if doc_corners is None:
|
||||||
|
raise Exception("Documento não encontrado")
|
||||||
|
|
||||||
|
# Processa cantos e aplica transformação
|
||||||
|
doc_corners = doc_corners.reshape(4, 2)
|
||||||
|
ordered_corners = order_points(doc_corners)
|
||||||
|
|
||||||
|
(tl, tr, br, bl) = ordered_corners
|
||||||
|
widthA = np.linalg.norm(br - bl)
|
||||||
|
widthB = np.linalg.norm(tr - tl)
|
||||||
|
maxWidth = max(int(widthA), int(widthB))
|
||||||
|
|
||||||
|
heightA = np.linalg.norm(tr - br)
|
||||||
|
heightB = np.linalg.norm(tl - bl)
|
||||||
|
maxHeight = max(int(heightA), int(heightB))
|
||||||
|
|
||||||
|
dst = np.array([
|
||||||
|
[0, 0],
|
||||||
|
[maxWidth - 1, 0],
|
||||||
|
[maxWidth - 1, maxHeight - 1],
|
||||||
|
[0, maxHeight - 1]
|
||||||
|
], dtype="float32")
|
||||||
|
|
||||||
|
# Aplica transformação perspectiva
|
||||||
|
matrix = cv2.getPerspectiveTransform(ordered_corners, dst)
|
||||||
|
warped = cv2.warpPerspective(original, matrix, (maxWidth, maxHeight))
|
||||||
|
|
||||||
|
# Salva resultado
|
||||||
|
output_path = os.path.join(output_dir, f"{doc_type}_{Path(image_path).name}")
|
||||||
|
cv2.imwrite(str(output_path), warped)
|
||||||
|
|
||||||
|
return {
|
||||||
|
"success": True,
|
||||||
|
"message": "Processamento concluído com sucesso",
|
||||||
|
"width": maxWidth,
|
||||||
|
"height": maxHeight
|
||||||
|
}
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
return {
|
||||||
|
"success": False,
|
||||||
|
"message": str(e)
|
||||||
|
}
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
if len(sys.argv) != 4:
|
||||||
|
print(json.dumps({"success": False, "message": "Uso: python document_detector.py <input_path> <doc_type> <output_dir>"}))
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
result = process_document(Path(sys.argv[1]), sys.argv[2], Path(sys.argv[3]))
|
||||||
|
print(json.dumps(result))
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
<?php
|
||||||
|
if (!isset($_SESSION['user_id'])) {
|
||||||
|
header("Location: login.php");
|
||||||
|
exit();
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Buscar histórico de documentos processados
|
||||||
|
$query = "SELECT pd.*, u.username FROM processed_documents pd
|
||||||
|
LEFT JOIN users u ON pd.user_id = u.id
|
||||||
|
ORDER BY pd.created_at DESC";
|
||||||
|
$result = $mysqli->query($query);
|
||||||
|
?>
|
||||||
|
|
||||||
|
<div class="container">
|
||||||
|
<h2>Histórico de Documentos Processados</h2>
|
||||||
|
|
||||||
|
<table class="data-table">
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>Data/Hora</th>
|
||||||
|
<th>Usuário</th>
|
||||||
|
<th>Documento Original</th>
|
||||||
|
<th>Documento Processado</th>
|
||||||
|
<th>Ações</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
<?php while ($row = $result->fetch_assoc()): ?>
|
||||||
|
<tr>
|
||||||
|
<td><?php echo date('d/m/Y H:i:s', strtotime($row['created_at'])); ?></td>
|
||||||
|
<td><?php echo htmlspecialchars($row['username']); ?></td>
|
||||||
|
<td>
|
||||||
|
<a href="<?php echo htmlspecialchars($row['original_path']); ?>" target="_blank">
|
||||||
|
Ver Original
|
||||||
|
</a>
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
<a href="<?php echo htmlspecialchars($row['processed_path']); ?>" target="_blank">
|
||||||
|
Ver Processado
|
||||||
|
</a>
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
<button onclick="deleteDocument(<?php echo $row['id']; ?>)" class="delete-btn">
|
||||||
|
Excluir
|
||||||
|
</button>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
<?php endwhile; ?>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
function deleteDocument(id) {
|
||||||
|
if (confirm('Tem certeza que deseja excluir este documento?')) {
|
||||||
|
fetch('delete_document.php', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
},
|
||||||
|
body: JSON.stringify({id: id})
|
||||||
|
})
|
||||||
|
.then(response => response.json())
|
||||||
|
.then(data => {
|
||||||
|
if (data.success) {
|
||||||
|
alert('Documento excluído com sucesso!');
|
||||||
|
location.reload();
|
||||||
|
} else {
|
||||||
|
alert('Erro ao excluir documento: ' + data.message);
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.catch(error => {
|
||||||
|
console.error('Error:', error);
|
||||||
|
alert('Erro ao excluir documento');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
+694
@@ -0,0 +1,694 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<title>Editor de Documentos</title>
|
||||||
|
<link href="https://cdn.jsdelivr.net/npm/cropperjs@1.5.12/dist/cropper.min.css" rel="stylesheet">
|
||||||
|
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
|
||||||
|
<script src="https://unpkg.com/downloadjs@1.4.7/download.js"></script>
|
||||||
|
<style>
|
||||||
|
html, body {
|
||||||
|
margin: 0;
|
||||||
|
padding: 0;
|
||||||
|
height: 100%;
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
body {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
font-family: Arial, sans-serif;
|
||||||
|
background: #f5f5f5;
|
||||||
|
}
|
||||||
|
/* Container principal com scroll */
|
||||||
|
.editor-container {
|
||||||
|
max-width: 1600px;
|
||||||
|
margin: 0 auto;
|
||||||
|
padding: 20px;
|
||||||
|
height: calc(100vh - 20px);
|
||||||
|
overflow-y: auto;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 20px;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Container da imagem ajustado */
|
||||||
|
.img-container {
|
||||||
|
position: relative;
|
||||||
|
background: #fff;
|
||||||
|
border: 1px solid #ddd;
|
||||||
|
border-radius: 8px;
|
||||||
|
height: 70vh;
|
||||||
|
min-height: 500px;
|
||||||
|
max-height: 800px;
|
||||||
|
margin: 20px 0;
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Ajustes do Cropper */
|
||||||
|
.cropper-container {
|
||||||
|
position: relative !important;
|
||||||
|
width: 100% !important;
|
||||||
|
height: 100% !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
.cropper-wrap-box {
|
||||||
|
background-color: #f8f8f8;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Pontos de redimensionamento maiores e mais visíveis */
|
||||||
|
.cropper-point {
|
||||||
|
width: 25px !important;
|
||||||
|
height: 25px !important;
|
||||||
|
background-color: #4CAF50 !important;
|
||||||
|
border: 3px solid white !important;
|
||||||
|
opacity: 1 !important;
|
||||||
|
border-radius: 50% !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
.cropper-point.point-se {
|
||||||
|
width: 25px !important;
|
||||||
|
height: 25px !important;
|
||||||
|
opacity: 1 !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
.cropper-view-box {
|
||||||
|
outline: 2px solid #4CAF50 !important;
|
||||||
|
outline-color: rgba(74, 175, 80, 0.75) !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
.cropper-line {
|
||||||
|
width: 3px !important;
|
||||||
|
height: 3px !important;
|
||||||
|
background-color: #4CAF50 !important;
|
||||||
|
opacity: 0.8 !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Z-index ajustados */
|
||||||
|
.cropper-face {
|
||||||
|
z-index: 2 !important;
|
||||||
|
}
|
||||||
|
.cropper-line, .cropper-point {
|
||||||
|
z-index: 3 !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Área de controles sempre visível */
|
||||||
|
.controls-section {
|
||||||
|
position: sticky;
|
||||||
|
bottom: 70px;
|
||||||
|
background: #fff;
|
||||||
|
padding: 20px;
|
||||||
|
border-radius: 8px;
|
||||||
|
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
|
||||||
|
z-index: 4;
|
||||||
|
}
|
||||||
|
|
||||||
|
.toolbar {
|
||||||
|
position: sticky;
|
||||||
|
bottom: 0;
|
||||||
|
background: #fff;
|
||||||
|
padding: 15px;
|
||||||
|
border-radius: 8px 8px 0 0;
|
||||||
|
box-shadow: 0 -2px 10px rgba(0,0,0,0.1);
|
||||||
|
z-index: 5;
|
||||||
|
}
|
||||||
|
.controls {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
|
||||||
|
gap: 10px;
|
||||||
|
}
|
||||||
|
.range-control {
|
||||||
|
margin-bottom: 10px;
|
||||||
|
}
|
||||||
|
.range-control label {
|
||||||
|
display: block;
|
||||||
|
margin-bottom: 5px;
|
||||||
|
font-weight: bold;
|
||||||
|
}
|
||||||
|
.range-control input[type="range"] {
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
|
.toolbar {
|
||||||
|
display: flex;
|
||||||
|
justify-content: center;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 10px;
|
||||||
|
padding: 10px;
|
||||||
|
text-align: center;
|
||||||
|
background: #fff;
|
||||||
|
border-radius: 4px;
|
||||||
|
}
|
||||||
|
.toolbar button {
|
||||||
|
padding: 10px 20px;
|
||||||
|
margin: 0 8px;
|
||||||
|
font-weight: 500;
|
||||||
|
transition: all 0.3s ease;
|
||||||
|
background: #4CAF50;
|
||||||
|
color: white;
|
||||||
|
border: none;
|
||||||
|
border-radius: 4px;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
.toolbar button:hover {
|
||||||
|
transform: translateY(-2px);
|
||||||
|
box-shadow: 0 2px 8px rgba(0,0,0,0.2);
|
||||||
|
background: #45a049;
|
||||||
|
}
|
||||||
|
#preview {
|
||||||
|
display: block;
|
||||||
|
max-width: 100%;
|
||||||
|
max-height: 100%;
|
||||||
|
margin: auto;
|
||||||
|
}
|
||||||
|
.cropper-container {
|
||||||
|
width: 100% !important;
|
||||||
|
height: 100% !important;
|
||||||
|
}
|
||||||
|
.cropper-wrap-box {
|
||||||
|
background-color: #f8f8f8;
|
||||||
|
}
|
||||||
|
.cropper-view-box {
|
||||||
|
outline: 2px solid #4CAF50;
|
||||||
|
outline-color: rgba(74, 175, 80, 0.75);
|
||||||
|
}
|
||||||
|
.cropper-point {
|
||||||
|
width: 15px !important;
|
||||||
|
height: 15px !important;
|
||||||
|
background-color: #4CAF50;
|
||||||
|
opacity: 0.9;
|
||||||
|
border-radius: 50%;
|
||||||
|
}
|
||||||
|
.cropper-point.point-se {
|
||||||
|
width: 20px !important;
|
||||||
|
height: 20px !important;
|
||||||
|
background-color: #4CAF50;
|
||||||
|
}
|
||||||
|
.cropper-line {
|
||||||
|
background-color: #4CAF50;
|
||||||
|
opacity: 0.4;
|
||||||
|
}
|
||||||
|
.thumbnails {
|
||||||
|
height: 130px;
|
||||||
|
padding: 15px;
|
||||||
|
background: #fff;
|
||||||
|
border-radius: 8px;
|
||||||
|
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
|
||||||
|
display: flex;
|
||||||
|
gap: 10px;
|
||||||
|
overflow-x: auto;
|
||||||
|
flex-shrink: 0; /* Impede encolhimento */
|
||||||
|
}
|
||||||
|
.thumbnail {
|
||||||
|
width: 110px;
|
||||||
|
height: 100px;
|
||||||
|
margin-right: 15px;
|
||||||
|
border-radius: 4px;
|
||||||
|
transition: all 0.3s ease;
|
||||||
|
object-fit: cover;
|
||||||
|
cursor: pointer;
|
||||||
|
border: 2px solid transparent;
|
||||||
|
}
|
||||||
|
.thumbnail:hover {
|
||||||
|
transform: translateY(-2px);
|
||||||
|
box-shadow: 0 2px 8px rgba(0,0,0,0.2);
|
||||||
|
}
|
||||||
|
.thumbnail.active {
|
||||||
|
border-color: #4CAF50;
|
||||||
|
}
|
||||||
|
#preview-container {
|
||||||
|
position: relative;
|
||||||
|
width: 100%;
|
||||||
|
height: 100%;
|
||||||
|
}
|
||||||
|
#preview-canvas {
|
||||||
|
position: absolute;
|
||||||
|
top: 0;
|
||||||
|
left: 0;
|
||||||
|
width: 100%;
|
||||||
|
height: 100%;
|
||||||
|
}
|
||||||
|
.cropper-point {
|
||||||
|
width: 12px !important;
|
||||||
|
height: 12px !important;
|
||||||
|
background-color: #4CAF50 !important;
|
||||||
|
opacity: 0.8 !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Cursores específicos para cada ponto */
|
||||||
|
.cropper-point.point-e { cursor: e-resize !important; }
|
||||||
|
.cropper-point.point-n { cursor: n-resize !important; }
|
||||||
|
.cropper-point.point-w { cursor: w-resize !important; }
|
||||||
|
.cropper-point.point-s { cursor: s-resize !important; }
|
||||||
|
.cropper-point.point-ne { cursor: ne-resize !important; }
|
||||||
|
.cropper-point.point-nw { cursor: nw-resize !important; }
|
||||||
|
.cropper-point.point-sw { cursor: sw-resize !important; }
|
||||||
|
.cropper-point.point-se { cursor: se-resize !important; }
|
||||||
|
|
||||||
|
/* Linhas da caixa de recorte */
|
||||||
|
.cropper-line {
|
||||||
|
background-color: #4CAF50 !important;
|
||||||
|
opacity: 0.3 !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Área de recorte */
|
||||||
|
.cropper-view-box {
|
||||||
|
outline: 2px solid #4CAF50 !important;
|
||||||
|
outline-color: rgba(74, 175, 80, 0.75) !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Área fora do recorte */
|
||||||
|
.cropper-modal {
|
||||||
|
background-color: rgba(0, 0, 0, 0.5) !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Container do Cropper */
|
||||||
|
.cropper-container {
|
||||||
|
margin: auto;
|
||||||
|
max-height: calc(100vh - 350px) !important;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div class="editor-container">
|
||||||
|
<div class="thumbnails" id="thumbnails">
|
||||||
|
<!-- Miniaturas serão inseridas aqui -->
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="img-container">
|
||||||
|
<div id="preview-container">
|
||||||
|
<img id="preview" src="">
|
||||||
|
<canvas id="preview-canvas"></canvas>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="controls-section">
|
||||||
|
<div class="controls">
|
||||||
|
<div class="range-control">
|
||||||
|
<label>Brilho</label>
|
||||||
|
<input type="range" min="-100" max="100" value="0" id="brightness" oninput="adjustImage()">
|
||||||
|
<span id="brightnessValue">0</span>
|
||||||
|
</div>
|
||||||
|
<div class="range-control">
|
||||||
|
<label>Contraste</label>
|
||||||
|
<input type="range" min="-100" max="100" value="0" id="contrast" oninput="adjustImage()">
|
||||||
|
<span id="contrastValue">0</span>
|
||||||
|
</div>
|
||||||
|
<div class="range-control">
|
||||||
|
<label>Saturação</label>
|
||||||
|
<input type="range" min="-100" max="100" value="0" id="saturation" oninput="adjustImage()">
|
||||||
|
<span id="saturationValue">0</span>
|
||||||
|
</div>
|
||||||
|
<div class="range-control">
|
||||||
|
<label>Matiz</label>
|
||||||
|
<input type="range" min="-180" max="180" value="0" id="hue" oninput="adjustImage()">
|
||||||
|
<span id="hueValue">0</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="toolbar">
|
||||||
|
<button onclick="resetImage()">Resetar</button>
|
||||||
|
<button onclick="rotateCCW()">Girar Esquerda</button>
|
||||||
|
<button onclick="rotateCW()">Girar Direita</button>
|
||||||
|
<button onclick="cropImage()">Recortar</button>
|
||||||
|
<button onclick="applyCrop()">Aplicar Recorte</button>
|
||||||
|
<button onclick="autoAdjust()">Otimização Automática</button>
|
||||||
|
<button onclick="combineImages()" style="background: #FF9800;">Unir Imagens</button>
|
||||||
|
<button onclick="saveImage()" style="background: #2196F3;">Salvar</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<script src="https://cdn.jsdelivr.net/npm/cropperjs@1.5.12/dist/cropper.min.js"></script>
|
||||||
|
<script>
|
||||||
|
let cropper = null;
|
||||||
|
let currentImage = null;
|
||||||
|
|
||||||
|
function initCropper(url) {
|
||||||
|
return new Promise((resolve) => {
|
||||||
|
const preview = document.getElementById('preview');
|
||||||
|
preview.src = url;
|
||||||
|
|
||||||
|
if (cropper) {
|
||||||
|
cropper.destroy();
|
||||||
|
cropper = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
preview.onload = function() {
|
||||||
|
cropper = new Cropper(preview, {
|
||||||
|
viewMode: 1,
|
||||||
|
dragMode: 'move',
|
||||||
|
aspectRatio: NaN,
|
||||||
|
autoCrop: true,
|
||||||
|
autoCropArea: 0.98,
|
||||||
|
cropBoxResizable: true,
|
||||||
|
cropBoxMovable: true,
|
||||||
|
zoomable: true,
|
||||||
|
rotatable: true,
|
||||||
|
scalable: true,
|
||||||
|
toggleDragModeOnDblclick: true,
|
||||||
|
ready: function() {
|
||||||
|
resolve();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
};
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function cropImage() {
|
||||||
|
if (!cropper) return;
|
||||||
|
|
||||||
|
if (cropper.getData().width === 0) {
|
||||||
|
// Se não houver área de recorte, criar uma
|
||||||
|
const containerData = cropper.getContainerData();
|
||||||
|
const minSize = Math.min(containerData.width, containerData.height);
|
||||||
|
cropper.setCropBoxData({
|
||||||
|
left: (containerData.width - minSize * 0.8) / 2,
|
||||||
|
top: (containerData.height - minSize * 0.8) / 2,
|
||||||
|
width: minSize * 0.8,
|
||||||
|
height: minSize * 0.8
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Alternar entre modos crop e move
|
||||||
|
if (cropper.options.dragMode === 'crop') {
|
||||||
|
cropper.setDragMode('move');
|
||||||
|
|
||||||
|
// Aplicar o recorte atual
|
||||||
|
const canvas = cropper.getCroppedCanvas();
|
||||||
|
if (canvas) {
|
||||||
|
const croppedImageUrl = canvas.toDataURL('image/jpeg');
|
||||||
|
cropper.replace(croppedImageUrl);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
cropper.setDragMode('crop');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Atualizar a UI
|
||||||
|
const cropBox = document.querySelector('.cropper-crop-box');
|
||||||
|
if (cropBox) {
|
||||||
|
cropBox.style.display = 'block';
|
||||||
|
}
|
||||||
|
|
||||||
|
// Forçar atualização do cropper
|
||||||
|
cropper.clear();
|
||||||
|
setTimeout(() => {
|
||||||
|
cropper.crop();
|
||||||
|
}, 50);
|
||||||
|
}
|
||||||
|
|
||||||
|
function applyCrop() {
|
||||||
|
if (!cropper) return;
|
||||||
|
|
||||||
|
const canvas = cropper.getCroppedCanvas({
|
||||||
|
imageSmoothingEnabled: true,
|
||||||
|
imageSmoothingQuality: 'high'
|
||||||
|
});
|
||||||
|
if (canvas) {
|
||||||
|
const croppedImageUrl = canvas.toDataURL('image/jpeg');
|
||||||
|
cropper.destroy();
|
||||||
|
initCropper(croppedImageUrl);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function rotateCW() {
|
||||||
|
if (!cropper) return;
|
||||||
|
try {
|
||||||
|
await cropper.rotate(90);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Erro ao rotacionar:', error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function rotateCCW() {
|
||||||
|
if (!cropper) return;
|
||||||
|
try {
|
||||||
|
await cropper.rotate(-90);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Erro ao rotacionar:', error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function switchImage(index) {
|
||||||
|
currentImageIndex = index;
|
||||||
|
|
||||||
|
// Atualizar miniaturas
|
||||||
|
document.querySelectorAll('.thumbnail').forEach((thumb, i) => {
|
||||||
|
thumb.className = 'thumbnail' + (i === index ? ' active' : '');
|
||||||
|
});
|
||||||
|
|
||||||
|
// Carregar nova imagem
|
||||||
|
initCropper(images[index].url)
|
||||||
|
.then(() => {
|
||||||
|
// Restaurar filtros após inicialização
|
||||||
|
if (cropper) {
|
||||||
|
currentFilters = { ...images[index].filters };
|
||||||
|
updateFilterInputs();
|
||||||
|
applyCurrentFilters();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
let images = [];
|
||||||
|
let currentImageIndex = 0;
|
||||||
|
let currentFilters = {
|
||||||
|
brightness: 100,
|
||||||
|
contrast: 100,
|
||||||
|
saturation: 100,
|
||||||
|
hue: 0
|
||||||
|
};
|
||||||
|
|
||||||
|
window.onload = function() {
|
||||||
|
try {
|
||||||
|
var allImages = JSON.parse(localStorage.getItem('allImages')) || [];
|
||||||
|
console.log('Imagens carregadas:', allImages);
|
||||||
|
|
||||||
|
if (allImages.length > 0) {
|
||||||
|
images = allImages.map(function(img) {
|
||||||
|
return {
|
||||||
|
url: img.url,
|
||||||
|
filters: { ...currentFilters }
|
||||||
|
};
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
var baseUrl = localStorage.getItem('tempImage');
|
||||||
|
if (!baseUrl) {
|
||||||
|
throw new Error('Nenhuma imagem encontrada');
|
||||||
|
}
|
||||||
|
images = [{
|
||||||
|
url: baseUrl,
|
||||||
|
filters: { ...currentFilters }
|
||||||
|
}];
|
||||||
|
}
|
||||||
|
|
||||||
|
// Criar miniaturas com verificação de URL
|
||||||
|
var thumbnailsContainer = document.getElementById('thumbnails');
|
||||||
|
thumbnailsContainer.innerHTML = '';
|
||||||
|
|
||||||
|
images.forEach(function(image, index) {
|
||||||
|
if (!image.url) {
|
||||||
|
console.error('URL da imagem inválida:', image);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var thumb = document.createElement('img');
|
||||||
|
thumb.src = image.url;
|
||||||
|
thumb.className = 'thumbnail' + (index === 0 ? ' active' : '');
|
||||||
|
thumb.onerror = function() {
|
||||||
|
console.error('Erro ao carregar miniatura:', image.url);
|
||||||
|
this.src = 'data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="110" height="100"><rect width="100%" height="100%" fill="%23ddd"/><text x="50%" y="50%" dominant-baseline="middle" text-anchor="middle" fill="%23666">Erro</text></svg>';
|
||||||
|
};
|
||||||
|
thumb.onclick = function() {
|
||||||
|
switchImage(index);
|
||||||
|
};
|
||||||
|
thumbnailsContainer.appendChild(thumb);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Inicializar primeira imagem com verificação
|
||||||
|
if (images.length > 0 && images[0].url) {
|
||||||
|
console.log('Iniciando cropper com:', images[0].url);
|
||||||
|
initCropper(images[0].url).catch(function(error) {
|
||||||
|
console.error('Erro ao inicializar cropper:', error);
|
||||||
|
alert('Erro ao inicializar editor: ' + error.message);
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
throw new Error('Nenhuma imagem válida para inicializar');
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Erro ao inicializar editor:', error);
|
||||||
|
alert('Erro ao carregar imagens: ' + error.message);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
function updateFilterInputs() {
|
||||||
|
document.getElementById('brightness').value = currentFilters.brightness - 100;
|
||||||
|
document.getElementById('contrast').value = currentFilters.contrast - 100;
|
||||||
|
document.getElementById('saturation').value = currentFilters.saturation - 100;
|
||||||
|
document.getElementById('hue').value = currentFilters.hue;
|
||||||
|
document.getElementById('brightnessValue').textContent = currentFilters.brightness - 100;
|
||||||
|
document.getElementById('contrastValue').textContent = currentFilters.contrast - 100;
|
||||||
|
document.getElementById('saturationValue').textContent = currentFilters.saturation - 100;
|
||||||
|
document.getElementById('hueValue').textContent = currentFilters.hue;
|
||||||
|
}
|
||||||
|
|
||||||
|
function adjustImage() {
|
||||||
|
currentFilters = {
|
||||||
|
brightness: parseInt(document.getElementById('brightness').value) + 100,
|
||||||
|
contrast: parseInt(document.getElementById('contrast').value) + 100,
|
||||||
|
saturation: parseInt(document.getElementById('saturation').value) + 100,
|
||||||
|
hue: parseInt(document.getElementById('hue').value)
|
||||||
|
};
|
||||||
|
|
||||||
|
// Salvar filtros para a imagem atual
|
||||||
|
images[currentImageIndex].filters = { ...currentFilters };
|
||||||
|
applyCurrentFilters();
|
||||||
|
}
|
||||||
|
|
||||||
|
function applyCurrentFilters() {
|
||||||
|
if (!cropper) return;
|
||||||
|
const canvas = cropper.getCroppedCanvas();
|
||||||
|
if (!canvas || canvas.width === 0 || canvas.height === 0) return;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const tempCanvas = document.createElement('canvas');
|
||||||
|
tempCanvas.width = canvas.width;
|
||||||
|
tempCanvas.height = canvas.height;
|
||||||
|
const ctx = tempCanvas.getContext('2d');
|
||||||
|
ctx.filter = `brightness(${currentFilters.brightness}%)
|
||||||
|
contrast(${currentFilters.contrast}%)
|
||||||
|
saturate(${currentFilters.saturation}%)
|
||||||
|
hue-rotate(${currentFilters.hue}deg)`;
|
||||||
|
ctx.drawImage(canvas, 0, 0);
|
||||||
|
cropper.replace(tempCanvas.toDataURL('image/jpeg'));
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Erro ao aplicar filtros:', error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function combineImages() {
|
||||||
|
try {
|
||||||
|
const { jsPDF } = window.jspdf;
|
||||||
|
const pdf = new jsPDF();
|
||||||
|
let currentY = 0;
|
||||||
|
|
||||||
|
for (let image of images) {
|
||||||
|
const img = await createImage(image.url);
|
||||||
|
const canvas = document.createElement('canvas');
|
||||||
|
canvas.width = img.width;
|
||||||
|
canvas.height = img.height;
|
||||||
|
const ctx = canvas.getContext('2d');
|
||||||
|
ctx.filter = `brightness(${image.filters.brightness}%)
|
||||||
|
contrast(${image.filters.contrast}%)
|
||||||
|
saturate(${image.filters.saturation}%)
|
||||||
|
hue-rotate(${image.filters.hue}deg)`;
|
||||||
|
ctx.drawImage(img, 0, 0);
|
||||||
|
|
||||||
|
if (currentY > 0) {
|
||||||
|
pdf.addPage();
|
||||||
|
}
|
||||||
|
|
||||||
|
const imgData = canvas.toDataURL('image/jpeg', 1.0);
|
||||||
|
pdf.addImage(imgData, 'JPEG', 0, 0, pdf.internal.pageSize.width, pdf.internal.pageSize.height, '', 'FAST');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Preview do PDF combinado
|
||||||
|
const pdfData = pdf.output('datauristring');
|
||||||
|
initCropper(pdfData);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Erro ao combinar imagens:', error);
|
||||||
|
alert('Erro ao combinar imagens: ' + error.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function createImage(url) {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const img = new Image();
|
||||||
|
img.onload = () => resolve(img);
|
||||||
|
img.onerror = reject;
|
||||||
|
img.src = url;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function resetImage() {
|
||||||
|
if (cropper) {
|
||||||
|
cropper.reset();
|
||||||
|
currentFilters = {
|
||||||
|
brightness: 100,
|
||||||
|
contrast: 100,
|
||||||
|
saturation: 100,
|
||||||
|
hue: 0
|
||||||
|
};
|
||||||
|
images[currentImageIndex].filters = { ...currentFilters };
|
||||||
|
updateFilterInputs();
|
||||||
|
applyCurrentFilters();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function autoAdjust() {
|
||||||
|
// Implementar otimização automática aqui
|
||||||
|
alert('Função em desenvolvimento');
|
||||||
|
}
|
||||||
|
|
||||||
|
async function saveImage() {
|
||||||
|
if (!cropper) {
|
||||||
|
alert('Editor não inicializado corretamente');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Obter canvas com filtros aplicados
|
||||||
|
const canvas = cropper.getCroppedCanvas({
|
||||||
|
maxWidth: 4096,
|
||||||
|
maxHeight: 4096,
|
||||||
|
fillColor: '#fff',
|
||||||
|
imageSmoothingEnabled: true,
|
||||||
|
imageSmoothingQuality: 'high'
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!canvas) {
|
||||||
|
throw new Error('Não foi possível gerar a imagem');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Criar PDF
|
||||||
|
const { jsPDF } = window.jspdf;
|
||||||
|
const pdf = new jsPDF({
|
||||||
|
orientation: canvas.width > canvas.height ? 'l' : 'p',
|
||||||
|
unit: 'px',
|
||||||
|
format: [canvas.width, canvas.height]
|
||||||
|
});
|
||||||
|
|
||||||
|
// Adicionar imagem ao PDF
|
||||||
|
const imgData = canvas.toDataURL('image/jpeg', 1.0);
|
||||||
|
pdf.addImage(imgData, 'JPEG', 0, 0, canvas.width, canvas.height);
|
||||||
|
|
||||||
|
// Converter PDF para Blob
|
||||||
|
const pdfBlob = pdf.output('blob');
|
||||||
|
|
||||||
|
const formData = new FormData();
|
||||||
|
formData.append('image', pdfBlob, 'documento.pdf');
|
||||||
|
formData.append('client_id', localStorage.getItem('tempClientId'));
|
||||||
|
formData.append('doc_type', localStorage.getItem('tempDocType'));
|
||||||
|
|
||||||
|
const response = await fetch('index.php?page=save_edited', {
|
||||||
|
method: 'POST',
|
||||||
|
body: formData
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error(`HTTP error! status: ${response.status}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await response.json();
|
||||||
|
if (result.success) {
|
||||||
|
window.parent.postMessage({
|
||||||
|
type: 'documentSaved',
|
||||||
|
data: result
|
||||||
|
}, '*');
|
||||||
|
} else {
|
||||||
|
throw new Error(result.message || 'Erro ao salvar');
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Erro:', error);
|
||||||
|
alert('Erro ao processar: ' + error.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -2,9 +2,10 @@
|
|||||||
|
|
||||||
ob_start();
|
ob_start();
|
||||||
session_start();
|
session_start();
|
||||||
|
//require_once 'config.php';
|
||||||
|
|
||||||
// Verificar se o usuário está logado
|
// Verificar se o usuário está logado
|
||||||
if (!isset($_SESSION['user_id'])) {
|
if (!isset($_SESSION['user_id']) && !in_array($_GET['page'], ['login', 'logout'])) {
|
||||||
header("Location: login.php");
|
header("Location: login.php");
|
||||||
exit();
|
exit();
|
||||||
}
|
}
|
||||||
@@ -32,28 +33,84 @@ include 'top_menu.php';
|
|||||||
<?php
|
<?php
|
||||||
if (isset($_GET['page'])) {
|
if (isset($_GET['page'])) {
|
||||||
$page = $_GET['page'];
|
$page = $_GET['page'];
|
||||||
if ($page == 'upload') {
|
switch($page) {
|
||||||
include 'prova/upload_prova.php';
|
case 'upload':
|
||||||
} elseif ($page == 'status') {
|
include 'prova/upload_prova.php';
|
||||||
include 'prova/status.php';
|
break;
|
||||||
} elseif ($page == 'list_files') {
|
case 'status':
|
||||||
include 'prova/list_files.php';
|
include 'prova/status.php';
|
||||||
} elseif ($page == 'register_client') {
|
break;
|
||||||
include 'clientes/register_client.php';
|
case 'list_files':
|
||||||
} elseif ($page == 'list_clients') {
|
include 'prova/list_files.php';
|
||||||
include 'clientes/list_clients.php';
|
break;
|
||||||
} elseif ($page == 'client_details' && isset($_GET['id'])) {
|
case 'register_client':
|
||||||
include 'clientes/client_details.php';
|
include 'clientes/register_client.php';
|
||||||
} elseif ($page == 'edit_client' && isset($_GET['id'])) {
|
break;
|
||||||
include 'clientes/edit_client.php';
|
case 'list_clients':
|
||||||
} elseif ($page == 'delete_client' && isset($_GET['id'])) {
|
include 'clientes/list_clients.php';
|
||||||
include 'clientes/delete_client.php';
|
break;
|
||||||
} elseif ($page == 'edit_note' && isset($_POST['id'])) {
|
case 'client_details':
|
||||||
include 'clientes/edit_note.php';
|
if (isset($_GET['id'])) {
|
||||||
} elseif ($page == 'delete_note' && isset($_POST['id'])) {
|
include 'clientes/client_details.php';
|
||||||
include 'clientes/delete_note.php';
|
}
|
||||||
} else {
|
break;
|
||||||
echo "<h2>Bem-vindo ao Sistema de Ferramentas</h2>";
|
case 'edit_client':
|
||||||
|
if (isset($_GET['id'])) {
|
||||||
|
include 'clientes/edit_client.php';
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case 'delete_client':
|
||||||
|
if (isset($_GET['id'])) {
|
||||||
|
include 'clientes/delete_client.php';
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case 'edit_note':
|
||||||
|
if (isset($_POST['id'])) {
|
||||||
|
include 'clientes/edit_note.php';
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case 'delete_note':
|
||||||
|
if (isset($_POST['id'])) {
|
||||||
|
include 'clientes/delete_note.php';
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case 'doc_upload':
|
||||||
|
include 'upload.php';
|
||||||
|
break;
|
||||||
|
case 'doc_list':
|
||||||
|
include 'list.php';
|
||||||
|
break;
|
||||||
|
case 'delete_document':
|
||||||
|
if (isset($_GET['id'])) {
|
||||||
|
include 'delete_document.php';
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case 'temp_upload':
|
||||||
|
header('Content-Type: application/json');
|
||||||
|
require_once 'temp_upload.php';
|
||||||
|
exit();
|
||||||
|
break;
|
||||||
|
|
||||||
|
case 'save_edited':
|
||||||
|
// Garante que nenhuma saída HTML será enviada
|
||||||
|
ob_clean();
|
||||||
|
header('Content-Type: application/json');
|
||||||
|
require_once 'save_edited.php';
|
||||||
|
exit();
|
||||||
|
break;
|
||||||
|
|
||||||
|
case 'editor':
|
||||||
|
require_once 'editor.php';
|
||||||
|
break;
|
||||||
|
|
||||||
|
case 'auto_adjust':
|
||||||
|
header('Content-Type: application/json');
|
||||||
|
require_once 'auto_adjust.php';
|
||||||
|
exit();
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
echo "<h2>Bem-vindo ao Sistema de Ferramentas</h2>";
|
||||||
|
break;
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
echo "<h2>Bem-vindo ao Sistema de Ferramentas</h2>";
|
echo "<h2>Bem-vindo ao Sistema de Ferramentas</h2>";
|
||||||
|
|||||||
@@ -0,0 +1,133 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<title>Documentos Processados</title>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<style>
|
||||||
|
body { font-family: Arial, sans-serif; margin: 20px; }
|
||||||
|
.file-list {
|
||||||
|
max-width: 800px;
|
||||||
|
margin: 0 auto;
|
||||||
|
padding: 20px;
|
||||||
|
background: #fff;
|
||||||
|
}
|
||||||
|
.file-item {
|
||||||
|
padding: 15px;
|
||||||
|
border-bottom: 1px solid #eee;
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
align-items: center;
|
||||||
|
}
|
||||||
|
.file-info { flex: 1; }
|
||||||
|
.file-actions { margin-left: 15px; }
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div class="file-list">
|
||||||
|
<?php
|
||||||
|
require_once 'config.php';
|
||||||
|
|
||||||
|
// Debug mode
|
||||||
|
error_reporting(E_ALL);
|
||||||
|
ini_set('display_errors', 1);
|
||||||
|
|
||||||
|
echo "<!-- Debug: Iniciando listagem -->\n";
|
||||||
|
|
||||||
|
if ($conn->connect_error) {
|
||||||
|
die("<div class='error'>Erro de conexão: " . $conn->connect_error . "</div>");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!isset($_GET['client_id'])) {
|
||||||
|
echo "<p>Selecione um cliente para ver seus documentos:</p>";
|
||||||
|
$sql = "SELECT id, name FROM clients";
|
||||||
|
echo "<!-- Debug: Executando query: $sql -->\n";
|
||||||
|
|
||||||
|
$result = $conn->query($sql);
|
||||||
|
|
||||||
|
if ($result === false) {
|
||||||
|
echo "<div class='error'>Erro na query: " . $conn->error . "</div>";
|
||||||
|
echo "<!-- Debug: Erro SQL: " . $conn->error . " -->\n";
|
||||||
|
} else {
|
||||||
|
echo "<!-- Debug: Encontrados " . $result->num_rows . " clientes -->\n";
|
||||||
|
while ($row = $result->fetch_assoc()) {
|
||||||
|
echo "<div class='file-item'>";
|
||||||
|
echo "<div class='file-info'>";
|
||||||
|
echo "<strong>" . $row['name'] . "</strong>";
|
||||||
|
echo "</div>";
|
||||||
|
echo "<div class='file-actions'>";
|
||||||
|
echo "<a href='index.php?page=doc_list&client_id=" . $row['id'] . "'>Ver documentos</a>";
|
||||||
|
echo "</div>";
|
||||||
|
echo "</div>";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
$client_id = intval($_GET['client_id']);
|
||||||
|
echo "<!-- Debug: Buscando documentos do cliente $client_id -->\n";
|
||||||
|
|
||||||
|
// Buscar documentos do cliente
|
||||||
|
$sql = "SELECT d.*, c.name as client_name
|
||||||
|
FROM documentos d
|
||||||
|
JOIN clients c ON d.client_id = c.id
|
||||||
|
WHERE d.client_id = ?
|
||||||
|
ORDER BY d.data_upload DESC";
|
||||||
|
|
||||||
|
echo "<!-- Debug: Query documentos: $sql -->\n";
|
||||||
|
|
||||||
|
$stmt = $conn->prepare($sql);
|
||||||
|
if ($stmt === false) {
|
||||||
|
echo "<div class='error'>Erro ao preparar query: " . $conn->error . "</div>";
|
||||||
|
} else {
|
||||||
|
$stmt->bind_param("i", $client_id);
|
||||||
|
$stmt->execute();
|
||||||
|
$result = $stmt->get_result();
|
||||||
|
|
||||||
|
echo "<!-- Debug: Encontrados " . $result->num_rows . " documentos -->\n";
|
||||||
|
|
||||||
|
if ($result->num_rows > 0) {
|
||||||
|
while ($doc = $result->fetch_assoc()) {
|
||||||
|
echo "<div class='file-item'>";
|
||||||
|
echo "<div class='file-info'>";
|
||||||
|
echo "<strong>Tipo: " . ucfirst($doc['tipo']) . "</strong><br>";
|
||||||
|
echo "Data: " . date("d/m/Y H:i", strtotime($doc['data_upload']));
|
||||||
|
echo "</div>";
|
||||||
|
echo "<div class='file-actions'>";
|
||||||
|
echo "<a href='" . $doc['arquivo'] . "' target='_blank'>Visualizar</a> | ";
|
||||||
|
echo "<a href='#' onclick='deleteDocument(" . $doc['id'] . ")'>Excluir</a>";
|
||||||
|
echo "</div>";
|
||||||
|
echo "</div>";
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
echo "<p>Nenhum documento encontrado para este cliente.</p>";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
?>
|
||||||
|
|
||||||
|
<!-- Status messages -->
|
||||||
|
<?php if (isset($_GET['status'])): ?>
|
||||||
|
<div id="status" style="margin: 10px 0; padding: 10px; background: #e8f5e9;">
|
||||||
|
<?php
|
||||||
|
switch($_GET['status']) {
|
||||||
|
case 'success':
|
||||||
|
echo "Documento processado com sucesso!";
|
||||||
|
break;
|
||||||
|
case 'deleted':
|
||||||
|
echo "Documento excluído com sucesso!";
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
echo htmlspecialchars($_GET['status']);
|
||||||
|
}
|
||||||
|
?>
|
||||||
|
</div>
|
||||||
|
<?php endif; ?>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
function deleteDocument(id) {
|
||||||
|
if (confirm('Deseja realmente excluir este documento?')) {
|
||||||
|
window.location.href = 'index.php?page=delete_document&id=' + id;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -12,7 +12,7 @@ if (!isset($_SESSION['user_id'])) {
|
|||||||
<li>
|
<li>
|
||||||
<a href="javascript:void(0);" onclick="toggleSubmenu('submenu1')">Autenticador de Provas Digitais</a>
|
<a href="javascript:void(0);" onclick="toggleSubmenu('submenu1')">Autenticador de Provas Digitais</a>
|
||||||
<ul id="submenu1" class="submenu">
|
<ul id="submenu1" class="submenu">
|
||||||
<li><a href="index.php?page=upload">Upload de Arquivos</a></li>
|
<li><a href="/prova/upload_prova.php">Upload de Arquivos</a></li>
|
||||||
<li><a href="index.php?page=status">Ver Status</a></li>
|
<li><a href="index.php?page=status">Ver Status</a></li>
|
||||||
<li><a href="index.php?page=list_files">Lista de Arquivos Processados</a></li>
|
<li><a href="index.php?page=list_files">Lista de Arquivos Processados</a></li>
|
||||||
</ul>
|
</ul>
|
||||||
@@ -24,6 +24,13 @@ if (!isset($_SESSION['user_id'])) {
|
|||||||
<li><a href="index.php?page=list_clients">Listagem de Clientes</a></li>
|
<li><a href="index.php?page=list_clients">Listagem de Clientes</a></li>
|
||||||
</ul>
|
</ul>
|
||||||
</li>
|
</li>
|
||||||
|
<li>
|
||||||
|
<a href="javascript:void(0);" onclick="toggleSubmenu('submenu3')">Processador de Documentos</a>
|
||||||
|
<ul id="submenu3" class="submenu">
|
||||||
|
<li><a href="index.php?page=doc_upload">Upload de Documentos</a></li>
|
||||||
|
<li><a href="index.php?page=doc_list">Documentos Processados</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
<!-- Adicione mais ferramentas aqui -->
|
<!-- Adicione mais ferramentas aqui -->
|
||||||
</ul>
|
</ul>
|
||||||
</div>
|
</div>
|
||||||
+91
@@ -0,0 +1,91 @@
|
|||||||
|
<?php
|
||||||
|
require_once 'config.php';
|
||||||
|
|
||||||
|
$upload_dir = "uploads/";
|
||||||
|
$processed_dir = "processed/";
|
||||||
|
|
||||||
|
// Debug mode
|
||||||
|
error_reporting(E_ALL);
|
||||||
|
ini_set('display_errors', 1);
|
||||||
|
|
||||||
|
// Criar diretórios se não existirem
|
||||||
|
if (!file_exists($upload_dir)) mkdir($upload_dir, 0777, true);
|
||||||
|
if (!file_exists($processed_dir)) mkdir($processed_dir, 0777, true);
|
||||||
|
|
||||||
|
if ($_FILES["document"]["error"] == 0) {
|
||||||
|
try {
|
||||||
|
$temp = $_FILES["document"]["tmp_name"];
|
||||||
|
$name = basename($_FILES["document"]["name"]);
|
||||||
|
$doc_type = $_POST["doc_type"];
|
||||||
|
$client_id = $_POST["client_id"];
|
||||||
|
|
||||||
|
// Criar diretório específico do cliente
|
||||||
|
$client_dir = $processed_dir . $client_id . "/";
|
||||||
|
if (!file_exists($client_dir)) mkdir($client_dir, 0777, true);
|
||||||
|
|
||||||
|
// Salvar arquivo original com timestamp
|
||||||
|
$timestamp = time();
|
||||||
|
$original_name = $timestamp . "_" . $name;
|
||||||
|
$original_path = $upload_dir . $original_name;
|
||||||
|
|
||||||
|
if (!move_uploaded_file($temp, $original_path)) {
|
||||||
|
throw new Exception("Erro ao fazer upload do arquivo");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Caminho absoluto para o script Python
|
||||||
|
$python_script = realpath(__DIR__ . "/document_detector.py");
|
||||||
|
$original_path = realpath($original_path);
|
||||||
|
$client_dir = realpath($client_dir);
|
||||||
|
|
||||||
|
// Comando Python com paths absolutos
|
||||||
|
$command = sprintf(
|
||||||
|
'python3 "%s" "%s" "%s" "%s" 2>&1',
|
||||||
|
$python_script,
|
||||||
|
$original_path,
|
||||||
|
$doc_type,
|
||||||
|
$client_dir
|
||||||
|
);
|
||||||
|
|
||||||
|
// Log do comando
|
||||||
|
file_put_contents('python_debug.log', date('Y-m-d H:i:s') . "\nComando: " . $command . "\n", FILE_APPEND);
|
||||||
|
|
||||||
|
// Executar comando
|
||||||
|
$output = [];
|
||||||
|
$return_var = 0;
|
||||||
|
exec($command, $output, $return_var);
|
||||||
|
|
||||||
|
// Log da saída
|
||||||
|
file_put_contents('python_debug.log', "Saída: " . implode("\n", $output) . "\nCódigo: $return_var\n\n", FILE_APPEND);
|
||||||
|
|
||||||
|
// Verificar resultado
|
||||||
|
$last_output = end($output);
|
||||||
|
$result = json_decode($last_output, true);
|
||||||
|
|
||||||
|
if ($result && $result['success']) {
|
||||||
|
// Nome do arquivo processado
|
||||||
|
$processed_name = $doc_type . "_" . $original_name;
|
||||||
|
$processed_file = $client_dir . "/" . $processed_name;
|
||||||
|
|
||||||
|
// Registrar no banco
|
||||||
|
$sql = "INSERT INTO documentos (client_id, tipo, arquivo, data_upload) VALUES (?, ?, ?, NOW())";
|
||||||
|
$stmt = $conn->prepare($sql);
|
||||||
|
$stmt->bind_param("iss", $client_id, $doc_type, $processed_file);
|
||||||
|
|
||||||
|
if (!$stmt->execute()) {
|
||||||
|
throw new Exception("Erro ao registrar documento: " . $stmt->error);
|
||||||
|
}
|
||||||
|
|
||||||
|
header("Location: index.php?page=doc_list&client_id=" . $client_id . "&status=success");
|
||||||
|
exit();
|
||||||
|
} else {
|
||||||
|
throw new Exception("Erro no processamento: " . ($result['message'] ?? 'Erro desconhecido'));
|
||||||
|
}
|
||||||
|
|
||||||
|
} catch (Exception $e) {
|
||||||
|
file_put_contents('error.log', date('Y-m-d H:i:s') . " - " . $e->getMessage() . "\n", FILE_APPEND);
|
||||||
|
die("Erro: " . $e->getMessage());
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
die("Erro no upload: " . $_FILES["document"]["error"]);
|
||||||
|
}
|
||||||
|
?>
|
||||||
+116
@@ -0,0 +1,116 @@
|
|||||||
|
<?php
|
||||||
|
// Limpar qualquer saída anterior
|
||||||
|
ob_clean();
|
||||||
|
ob_start();
|
||||||
|
|
||||||
|
// Definir cabeçalhos
|
||||||
|
header('Content-Type: application/json');
|
||||||
|
header('X-Content-Type-Options: nosniff');
|
||||||
|
|
||||||
|
require_once 'config.php';
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Reset de quaisquer resultados pendentes
|
||||||
|
while ($conn->next_result()) {
|
||||||
|
if ($res = $conn->store_result()) {
|
||||||
|
$res->free();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verificar dados do POST e FILES
|
||||||
|
if (!isset($_POST['client_id']) || !isset($_FILES['image'])) {
|
||||||
|
throw new Exception("Dados incompletos");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Debug
|
||||||
|
error_log("POST data: " . print_r($_POST, true));
|
||||||
|
error_log("FILES data: " . print_r($_FILES, true));
|
||||||
|
|
||||||
|
$client_id = intval($_POST['client_id']);
|
||||||
|
$doc_type = $_POST['doc_type'];
|
||||||
|
|
||||||
|
// Verificar cliente com nova conexão
|
||||||
|
$check_client = $conn->prepare("SELECT id FROM clients WHERE id = ? LIMIT 1");
|
||||||
|
if (!$check_client) {
|
||||||
|
throw new Exception("Erro ao preparar consulta: " . $conn->error);
|
||||||
|
}
|
||||||
|
|
||||||
|
$check_client->bind_param("i", $client_id);
|
||||||
|
$check_client->execute();
|
||||||
|
$result = $check_client->get_result();
|
||||||
|
|
||||||
|
if ($result->num_rows === 0) {
|
||||||
|
throw new Exception("Cliente não encontrado");
|
||||||
|
}
|
||||||
|
$check_client->close();
|
||||||
|
|
||||||
|
// Criar diretório do cliente
|
||||||
|
$client_dir = "processed/{$client_id}/";
|
||||||
|
if (!file_exists($client_dir)) {
|
||||||
|
if (!mkdir($client_dir, 0777, true)) {
|
||||||
|
throw new Exception("Erro ao criar diretório");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verificar tipo do arquivo
|
||||||
|
$mime_type = $_FILES['image']['type'];
|
||||||
|
if ($mime_type !== 'application/pdf' && !strpos($mime_type, 'image/') === 0) {
|
||||||
|
throw new Exception("Tipo de arquivo não permitido");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Gerar nome do arquivo sempre como PDF
|
||||||
|
$timestamp = time();
|
||||||
|
$filename = sprintf(
|
||||||
|
'%s_%s_%s.pdf',
|
||||||
|
$doc_type,
|
||||||
|
$timestamp,
|
||||||
|
uniqid()
|
||||||
|
);
|
||||||
|
$filepath = $client_dir . $filename;
|
||||||
|
|
||||||
|
// Se for imagem, converter para PDF
|
||||||
|
if (strpos($mime_type, 'image/') === 0) {
|
||||||
|
require_once 'vendor/autoload.php'; // Requer tecnickcom/tcpdf
|
||||||
|
$pdf = new TCPDF();
|
||||||
|
$pdf->AddPage();
|
||||||
|
$pdf->Image($_FILES['image']['tmp_name'], 0, 0, $pdf->getPageWidth(), $pdf->getPageHeight());
|
||||||
|
$pdf->Output($filepath, 'F');
|
||||||
|
} else {
|
||||||
|
// Se já for PDF, apenas mover
|
||||||
|
move_uploaded_file($_FILES['image']['tmp_name'], $filepath);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Registrar no banco com nova preparação
|
||||||
|
$insert = $conn->prepare("INSERT INTO documentos (client_id, tipo, arquivo, data_upload) VALUES (?, ?, ?, NOW())");
|
||||||
|
if (!$insert) {
|
||||||
|
throw new Exception("Erro ao preparar inserção: " . $conn->error);
|
||||||
|
}
|
||||||
|
|
||||||
|
$insert->bind_param("iss", $client_id, $doc_type, $filepath);
|
||||||
|
|
||||||
|
if (!$insert->execute()) {
|
||||||
|
unlink($filepath);
|
||||||
|
throw new Exception("Erro ao registrar documento: " . $insert->error);
|
||||||
|
}
|
||||||
|
|
||||||
|
$doc_id = $insert->insert_id;
|
||||||
|
$insert->close();
|
||||||
|
|
||||||
|
// Retornar sucesso
|
||||||
|
echo json_encode([
|
||||||
|
'success' => true,
|
||||||
|
'message' => 'Documento salvo com sucesso',
|
||||||
|
'file' => $filepath,
|
||||||
|
'id' => $doc_id
|
||||||
|
]);
|
||||||
|
exit();
|
||||||
|
|
||||||
|
} catch (Exception $e) {
|
||||||
|
http_response_code(400);
|
||||||
|
echo json_encode([
|
||||||
|
'success' => false,
|
||||||
|
'message' => $e->getMessage()
|
||||||
|
]);
|
||||||
|
exit();
|
||||||
|
}
|
||||||
|
?>
|
||||||
@@ -209,3 +209,50 @@ textarea {
|
|||||||
#search-button:hover {
|
#search-button:hover {
|
||||||
background-color: #0056b3;
|
background-color: #0056b3;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Estilos para processamento de documentos */
|
||||||
|
.upload-form {
|
||||||
|
max-width: 600px;
|
||||||
|
margin: 20px auto;
|
||||||
|
padding: 20px;
|
||||||
|
background: #f5f5f5;
|
||||||
|
border-radius: 5px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.result-preview {
|
||||||
|
margin-top: 30px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.image-comparison {
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-around;
|
||||||
|
margin-top: 20px;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.image-comparison img {
|
||||||
|
max-width: 45%;
|
||||||
|
height: auto;
|
||||||
|
margin: 10px;
|
||||||
|
border: 1px solid #ddd;
|
||||||
|
box-shadow: 0 0 5px rgba(0,0,0,0.2);
|
||||||
|
}
|
||||||
|
|
||||||
|
.alert {
|
||||||
|
padding: 15px;
|
||||||
|
margin-bottom: 20px;
|
||||||
|
border: 1px solid transparent;
|
||||||
|
border-radius: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.alert-success {
|
||||||
|
color: #155724;
|
||||||
|
background-color: #d4edda;
|
||||||
|
border-color: #c3e6cb;
|
||||||
|
}
|
||||||
|
|
||||||
|
.alert-error {
|
||||||
|
color: #721c24;
|
||||||
|
background-color: #f8d7da;
|
||||||
|
border-color: #f5c6cb;
|
||||||
|
}
|
||||||
+120
@@ -0,0 +1,120 @@
|
|||||||
|
<?php
|
||||||
|
// Certificar que nenhuma saída foi enviada antes
|
||||||
|
ob_clean();
|
||||||
|
header('Content-Type: application/json');
|
||||||
|
|
||||||
|
// Configurações de erro
|
||||||
|
error_reporting(E_ALL);
|
||||||
|
ini_set('display_errors', 0);
|
||||||
|
|
||||||
|
// Função para retornar resposta JSON
|
||||||
|
function jsonResponse($success, $message, $data = []) {
|
||||||
|
echo json_encode(array_merge([
|
||||||
|
'success' => $success,
|
||||||
|
'message' => $message
|
||||||
|
], $data));
|
||||||
|
exit;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Configurar diretório temporário com caminho absoluto
|
||||||
|
$temp_dir = __DIR__ . "/temp/";
|
||||||
|
$web_temp_dir = "temp/"; // Para URLs
|
||||||
|
|
||||||
|
// Criar diretório se não existir
|
||||||
|
if (!file_exists($temp_dir)) {
|
||||||
|
if (!mkdir($temp_dir, 0777, true)) {
|
||||||
|
throw new Exception("Erro ao criar diretório temporário");
|
||||||
|
}
|
||||||
|
chmod($temp_dir, 0777); // Garantir permissões
|
||||||
|
}
|
||||||
|
|
||||||
|
// Debug
|
||||||
|
error_log("POST: " . print_r($_POST, true));
|
||||||
|
error_log("FILES: " . print_r($_FILES, true));
|
||||||
|
|
||||||
|
// Verificar se recebeu arquivos
|
||||||
|
if (empty($_FILES['document'])) {
|
||||||
|
throw new Exception("Nenhum arquivo enviado");
|
||||||
|
}
|
||||||
|
|
||||||
|
$files = [];
|
||||||
|
$uploaded_files = [];
|
||||||
|
|
||||||
|
// Reorganizar array de arquivos
|
||||||
|
foreach ($_FILES['document']['name'] as $key => $name) {
|
||||||
|
$files[] = [
|
||||||
|
'name' => $_FILES['document']['name'][$key],
|
||||||
|
'type' => $_FILES['document']['type'][$key],
|
||||||
|
'tmp_name' => $_FILES['document']['tmp_name'][$key],
|
||||||
|
'error' => $_FILES['document']['error'][$key],
|
||||||
|
'size' => $_FILES['document']['size'][$key]
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
// Processar cada arquivo
|
||||||
|
foreach ($files as $index => $file) {
|
||||||
|
if ($file['error'] !== UPLOAD_ERR_OK) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validar tipo
|
||||||
|
$finfo = finfo_open(FILEINFO_MIME_TYPE);
|
||||||
|
$mime_type = finfo_file($finfo, $file['tmp_name']);
|
||||||
|
finfo_close($finfo);
|
||||||
|
|
||||||
|
if (!in_array($mime_type, ['image/jpeg', 'image/png', 'image/jpg'])) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Gerar nome único para cada arquivo
|
||||||
|
$ext = pathinfo($file['name'], PATHINFO_EXTENSION);
|
||||||
|
$basename = uniqid('doc_') . '_' . time();
|
||||||
|
$filename = sprintf('%s_%d.%s', $basename, $index, $ext);
|
||||||
|
|
||||||
|
$temp_path = $temp_dir . $filename;
|
||||||
|
$web_path = $web_temp_dir . $filename;
|
||||||
|
|
||||||
|
// Mover arquivo
|
||||||
|
if (move_uploaded_file($file['tmp_name'], $temp_path)) {
|
||||||
|
// Ajustar permissões do arquivo
|
||||||
|
chmod($temp_path, 0644);
|
||||||
|
|
||||||
|
$uploaded_files[] = [
|
||||||
|
'url' => $web_path,
|
||||||
|
'path' => $temp_path,
|
||||||
|
'index' => $index
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (empty($uploaded_files)) {
|
||||||
|
throw new Exception("Nenhum arquivo válido foi enviado");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Debug
|
||||||
|
error_log("Arquivos processados: " . print_r($uploaded_files, true));
|
||||||
|
|
||||||
|
// Retornar sucesso com primeiro arquivo como principal
|
||||||
|
echo json_encode([
|
||||||
|
'success' => true,
|
||||||
|
'message' => count($uploaded_files) . ' arquivo(s) processado(s)',
|
||||||
|
'imageUrl' => $uploaded_files[0]['url'],
|
||||||
|
'allImages' => $uploaded_files,
|
||||||
|
'fileCount' => count($uploaded_files),
|
||||||
|
'baseUrl' => $web_temp_dir,
|
||||||
|
'basename' => $basename
|
||||||
|
]);
|
||||||
|
|
||||||
|
} catch (Exception $e) {
|
||||||
|
error_log("Erro no upload: " . $e->getMessage());
|
||||||
|
echo json_encode([
|
||||||
|
'success' => false,
|
||||||
|
'message' => $e->getMessage(),
|
||||||
|
'debug' => [
|
||||||
|
'POST' => $_POST,
|
||||||
|
'FILES' => isset($_FILES['document']) ? $_FILES['document'] : 'No files'
|
||||||
|
]
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
?>
|
||||||
+245
@@ -0,0 +1,245 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="pt-BR">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<title>Upload de Documentos</title>
|
||||||
|
<style>
|
||||||
|
body { font-family: Arial, sans-serif; margin: 20px; }
|
||||||
|
.upload-form { max-width: 500px; margin: 0 auto; padding: 20px; background: #fff; }
|
||||||
|
.button { padding: 10px 20px; background: #4CAF50; color: white; border: none; }
|
||||||
|
.preview { max-width: 100%; margin: 20px 0; }
|
||||||
|
.preview img { max-width: 100%; }
|
||||||
|
#result { display: none; }
|
||||||
|
.error { color: red; }
|
||||||
|
select { width: 100%; padding: 8px; margin-bottom: 10px; }
|
||||||
|
</style>
|
||||||
|
<!-- jQuery primeiro -->
|
||||||
|
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
|
||||||
|
<!-- jQuery UI depois -->
|
||||||
|
<script src="https://code.jquery.com/ui/1.13.2/jquery-ui.min.js"></script>
|
||||||
|
<link rel="stylesheet" href="https://code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css">
|
||||||
|
<!-- Fancybox por último -->
|
||||||
|
<script src="https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.5.7/jquery.fancybox.min.js"></script>
|
||||||
|
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.5.7/jquery.fancybox.min.css">
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div class="upload-form">
|
||||||
|
<h2>Upload de Documentos</h2>
|
||||||
|
<?php
|
||||||
|
// Debug de inicialização
|
||||||
|
echo "<!-- Debug: Iniciando página de upload -->\n";
|
||||||
|
require_once 'config.php';
|
||||||
|
|
||||||
|
if ($conn->connect_error) {
|
||||||
|
echo "<div class='error'>Erro de conexão: " . $conn->connect_error . "</div>";
|
||||||
|
} else {
|
||||||
|
echo "<!-- Debug: Conexão OK -->\n";
|
||||||
|
}
|
||||||
|
?>
|
||||||
|
<form action="process.php" method="post" enctype="multipart/form-data" id="uploadForm">
|
||||||
|
<p>
|
||||||
|
<label>Cliente:</label><br>
|
||||||
|
<select name="client_id" required>
|
||||||
|
<?php
|
||||||
|
require_once 'config.php';
|
||||||
|
|
||||||
|
// Debug de conexão
|
||||||
|
if (!$conn) {
|
||||||
|
die("Erro de conexão: " . mysqli_connect_error());
|
||||||
|
}
|
||||||
|
|
||||||
|
// Debug da tabela
|
||||||
|
$check_table = $conn->query("SHOW TABLES LIKE 'clients'");
|
||||||
|
if ($check_table->num_rows == 0) {
|
||||||
|
die("Tabela 'clients' não encontrada!");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verificar estrutura da tabela
|
||||||
|
$check_columns = $conn->query("DESCRIBE clients");
|
||||||
|
if (!$check_columns) {
|
||||||
|
die("Erro ao verificar estrutura da tabela: " . $conn->error);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Contar registros
|
||||||
|
$count = $conn->query("SELECT COUNT(*) as total FROM clients");
|
||||||
|
$total = $count->fetch_assoc()['total'];
|
||||||
|
echo "<!-- Total de clientes: " . $total . " -->";
|
||||||
|
|
||||||
|
// Query com validação e debug
|
||||||
|
$sql = "SELECT id, name FROM clients WHERE 1=1";
|
||||||
|
$result = $conn->query($sql);
|
||||||
|
|
||||||
|
if (!$result) {
|
||||||
|
die("Erro na query: " . $conn->error);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Exibir clientes com verificação
|
||||||
|
echo "<option value=''>Selecione um cliente</option>";
|
||||||
|
if ($result->num_rows > 0) {
|
||||||
|
while ($row = $result->fetch_assoc()) {
|
||||||
|
echo "<option value='" . $row['id'] . "'>" .
|
||||||
|
htmlspecialchars($row['name']) . "</option>";
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
echo "<option value='' disabled>Nenhum cliente encontrado</option>";
|
||||||
|
echo "<!-- Query executada: " . $sql . " -->";
|
||||||
|
}
|
||||||
|
?>
|
||||||
|
</select>
|
||||||
|
</p>
|
||||||
|
<p>
|
||||||
|
<label>Selecione o documento:</label><br>
|
||||||
|
<input type="file" name="document[]" accept="image/*" required multiple>
|
||||||
|
<small style="color: #666;">Você pode selecionar várias imagens para unir em um único documento</small>
|
||||||
|
</p>
|
||||||
|
<p>
|
||||||
|
<label>Tipo de documento:</label><br>
|
||||||
|
<select name="doc_type" required>
|
||||||
|
<option value="cpf">CPF</option>
|
||||||
|
<option value="rg">RG</option>
|
||||||
|
<option value="cnh">CNH</option>
|
||||||
|
</select>
|
||||||
|
</p>
|
||||||
|
<input type="submit" value="Processar" class="button">
|
||||||
|
</form>
|
||||||
|
|
||||||
|
<div id="uploadStatus" style="margin: 10px 0; padding: 10px;"></div>
|
||||||
|
<div id="debug" style="margin: 10px 0; padding: 10px; background: #f5f5f5; display: none;"></div>
|
||||||
|
|
||||||
|
<div id="error" class="error">
|
||||||
|
<?php
|
||||||
|
if (isset($conn) && !$result) {
|
||||||
|
echo "Erro ao buscar clientes: " . $conn->error;
|
||||||
|
}
|
||||||
|
?>
|
||||||
|
</div>
|
||||||
|
<p><a href="index.php?page=doc_list">Ver documentos processados</a></p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="result">
|
||||||
|
<h3>Resultado do Processamento:</h3>
|
||||||
|
<div class="preview">
|
||||||
|
<h4>Documento Original:</h4>
|
||||||
|
<img id="originalImage" src="" alt="Original">
|
||||||
|
</div>
|
||||||
|
<div class="preview">
|
||||||
|
<h4>Documento Processado:</h4>
|
||||||
|
<img id="processedImage" src="" alt="Processado">
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="error" class="error"></div>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
$(document).ready(function() {
|
||||||
|
const uploadForm = document.getElementById('uploadForm');
|
||||||
|
const fileInput = uploadForm.querySelector('input[type="file"]');
|
||||||
|
const debugDiv = document.getElementById('debug');
|
||||||
|
const statusDiv = document.getElementById('uploadStatus');
|
||||||
|
|
||||||
|
// Inicializar autocomplete do jQuery UI
|
||||||
|
$("#search").autocomplete({
|
||||||
|
source: function(request, response) {
|
||||||
|
$.getJSON("clientes/autocomplete.php", {
|
||||||
|
term: request.term
|
||||||
|
}, response);
|
||||||
|
},
|
||||||
|
minLength: 2,
|
||||||
|
select: function(event, ui) {
|
||||||
|
if (ui.item) {
|
||||||
|
window.location.href = 'index.php?page=client_details&id=' + ui.item.id;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
fileInput.addEventListener('change', function(e) {
|
||||||
|
const files = e.target.files;
|
||||||
|
if (files.length > 0) {
|
||||||
|
debugDiv.innerHTML = `${files.length} arquivo(s) selecionado(s)`;
|
||||||
|
debugDiv.style.display = 'block';
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
uploadForm.onsubmit = async (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
const formData = new FormData();
|
||||||
|
|
||||||
|
// Adicionar cada arquivo individualmente
|
||||||
|
const files = fileInput.files;
|
||||||
|
Array.from(files).forEach((file, index) => {
|
||||||
|
formData.append('document[]', file);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Adicionar outros campos
|
||||||
|
formData.append('client_id', document.querySelector('select[name="client_id"]').value);
|
||||||
|
formData.append('doc_type', document.querySelector('select[name="doc_type"]').value);
|
||||||
|
|
||||||
|
debugDiv.style.display = 'block';
|
||||||
|
debugDiv.innerHTML = 'Iniciando upload...<br>';
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch('index.php?page=temp_upload', {
|
||||||
|
method: 'POST',
|
||||||
|
body: formData
|
||||||
|
});
|
||||||
|
|
||||||
|
debugDiv.innerHTML += `Status: ${response.status}<br>`;
|
||||||
|
const text = await response.text();
|
||||||
|
debugDiv.innerHTML += `Resposta raw: ${text}<br>`;
|
||||||
|
|
||||||
|
const result = JSON.parse(text);
|
||||||
|
|
||||||
|
if (result.success) {
|
||||||
|
debugDiv.innerHTML += 'Upload bem sucedido, abrindo editor...<br>';
|
||||||
|
localStorage.setItem('tempImage', result.imageUrl);
|
||||||
|
localStorage.setItem('tempClientId', formData.get('client_id'));
|
||||||
|
localStorage.setItem('tempDocType', formData.get('doc_type'));
|
||||||
|
localStorage.setItem('fileCount', result.fileCount);
|
||||||
|
localStorage.setItem('allImages', JSON.stringify(result.allImages));
|
||||||
|
|
||||||
|
jQuery.fancybox.open({
|
||||||
|
src: 'editor.php',
|
||||||
|
type: 'iframe',
|
||||||
|
opts: {
|
||||||
|
baseClass: "fancybox-custom-layout",
|
||||||
|
width: '90%',
|
||||||
|
height: '90%',
|
||||||
|
margin: [20, 0],
|
||||||
|
padding: 0,
|
||||||
|
autoSize: false,
|
||||||
|
fitToView: true,
|
||||||
|
touch: false,
|
||||||
|
afterLoad: function(instance, current) {
|
||||||
|
current.$iframe.css({
|
||||||
|
'max-width': '100%',
|
||||||
|
'max-height': '90vh',
|
||||||
|
'overflow': 'auto' // Permite rolagem dentro do iframe
|
||||||
|
});
|
||||||
|
},
|
||||||
|
afterClose: () => {
|
||||||
|
localStorage.removeItem('tempImage');
|
||||||
|
localStorage.removeItem('tempClientId');
|
||||||
|
localStorage.removeItem('tempDocType');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
throw new Error(result.message);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
debugDiv.innerHTML += `Erro: ${error.message}<br>`;
|
||||||
|
statusDiv.innerHTML = `Erro: ${error.message}`;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
// Receber mensagem do iframe
|
||||||
|
window.addEventListener('message', function(event) {
|
||||||
|
if (event.data.type === 'documentSaved') {
|
||||||
|
$.fancybox.close();
|
||||||
|
window.location.href = 'index.php?page=doc_list&status=success';
|
||||||
|
}
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
Reference in new issue
Block a user