-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
182 lines (156 loc) · 5.24 KB
/
script.js
File metadata and controls
182 lines (156 loc) · 5.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
const requiredColumns = [
'Chamado', 'Contratante', 'Nome Cliente', 'Fone', 'Cidade',
'Endereço', 'Número', 'Complemento', 'Bairro', 'Serviço',
'Tipo do Equipamento', 'Data Limite'
];
let currentData = null;
function showError(msg) {
const el = document.getElementById('error');
el.textContent = msg;
el.style.display = 'block';
}
function hideError() {
document.getElementById('error').style.display = 'none';
}
function renderTable(data, headers) {
const table = document.getElementById('dataTable');
table.innerHTML = '';
// Cabeçalho
const thead = document.createElement('thead');
const tr = document.createElement('tr');
headers.forEach(col => {
const th = document.createElement('th');
th.textContent = col;
tr.appendChild(th);
});
thead.appendChild(tr);
table.appendChild(thead);
// Corpo
const tbody = document.createElement('tbody');
data.forEach((row, i) => {
const tr = document.createElement('tr');
headers.forEach(col => {
const td = document.createElement('td');
const input = document.createElement('input');
input.type = 'text';
input.value = row[col] || '';
input.dataset.row = i;
input.dataset.col = col;
td.appendChild(input);
tr.appendChild(td);
});
tbody.appendChild(tr);
});
table.appendChild(tbody);
}
// Função auxiliar para decodificar buffer com fallback
function decodeBuffer(buffer, encoding) {
try {
const decoder = new TextDecoder(encoding, { fatal: true });
return decoder.decode(buffer);
} catch (e) {
return null;
}
}
document.getElementById('processBtn').addEventListener('click', () => {
const fileInput = document.getElementById('csvFile');
const file = fileInput.files[0];
if (!file) {
showError('Selecione um arquivo CSV.');
return;
}
if (!file.name.toLowerCase().endsWith('.csv')) {
showError('Por favor, selecione um arquivo .csv.');
return;
}
const reader = new FileReader();
reader.onload = function(e) {
const buffer = e.target.result;
// Detectar codificação inicial
let detectedEncoding = jschardet.detect(buffer).encoding || 'utf-8';
// Tentar múltiplos encodings
let text = null;
const encodingsToTry = [
detectedEncoding,
'utf-8',
'iso-8859-1',
'windows-1252',
'latin1'
];
for (const enc of encodingsToTry) {
text = decodeBuffer(buffer, enc);
if (text !== null) {
console.log(`✅ Decodificado com sucesso usando: ${enc}`);
break;
}
}
if (!text) {
text = new TextDecoder('utf-8', { fatal: false }).decode(buffer);
console.warn('⚠️ Falha ao decodificar. Usando UTF-8 com falhas.');
}
// Parse robusto
Papa.parse(text, {
delimiter: ';',
header: true,
skipEmptyLines: 'greedy',
quotes: true,
quoteChar: '"',
escapeChar: '"',
error: function(err) {
console.warn('Erro ignorado no parsing:', err);
},
complete: function(results) {
// Filtra linhas válidas
const validData = (results.data || []).filter(row => {
return row && typeof row === 'object' && Object.keys(row).some(k => row[k] !== '');
});
if (validData.length === 0) {
showError('Nenhum dado válido encontrado no arquivo.');
return;
}
// Constrói dados com todas as colunas desejadas
const filteredData = validData.map(row => {
const newRow = {};
requiredColumns.forEach(col => {
newRow[col] = (row[col] != null) ? String(row[col]).trim() : '';
});
return newRow;
});
currentData = filteredData;
document.getElementById('filename').textContent = file.name;
document.getElementById('total').textContent = filteredData.length;
renderTable(filteredData, requiredColumns);
document.getElementById('table-section').style.display = 'block';
hideError();
}
});
};
reader.readAsArrayBuffer(file);
});
document.getElementById('saveBtn').addEventListener('click', () => {
if (!currentData) return;
const inputs = document.querySelectorAll('#dataTable input');
inputs.forEach(input => {
const rowIdx = parseInt(input.dataset.row);
const colName = input.dataset.col;
currentData[rowIdx][colName] = input.value;
});
alert('Alterações salvas!');
});
document.getElementById('exportBtn').addEventListener('click', () => {
if (!currentData || currentData.length === 0) {
alert('Nenhum dado para exportar.');
return;
}
const ws = XLSX.utils.json_to_sheet(currentData, { header: requiredColumns });
const wb = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(wb, ws, 'Dados');
const filename = document.getElementById('filename').textContent.replace(/\.csv$/i, '_editado.xlsx');
XLSX.writeFile(wb, filename);
});
document.getElementById('clearBtn').addEventListener('click', () => {
currentData = null;
document.getElementById('csvFile').value = '';
document.getElementById('table-section').style.display = 'none';
hideError();
});