fix: buildPrintHTML usa data.diferenca (sys_total - saldo_esperado); btn-anterior null-check robusto
This commit is contained in:
+122
-114
@@ -1290,7 +1290,10 @@ function buildConfirmHTML(data) {
|
||||
// ─── Print Preview Window ──────────────────────────────────────────────────
|
||||
function buildPrintHTML(data) {
|
||||
const fmt = v => 'R$ ' + (v || 0).toFixed(2).replace('.', ',');
|
||||
const diferenca = (data.fechamento || 0) - (data.saldo_esperado || 0);
|
||||
// Usa a diferenca ja calculada pelo tauriRecibo (sys_total - saldo_esperado),
|
||||
// igual ao modal de confirmacao — nao recalcula de fechamento.
|
||||
const diferenca = data.diferenca !== undefined ? data.diferenca
|
||||
: ((data.sys_total || 0) - (data.saldo_esperado || 0));
|
||||
const diffStr = diferenca >= 0 ? `+${fmt(diferenca)}` : fmt(diferenca);
|
||||
const diffColor = diferenca === 0 ? '#2e7d32' : (diferenca > 0 ? '#e65100' : '#c0272d');
|
||||
|
||||
@@ -1700,132 +1703,137 @@ document.getElementById('btn-limpar').addEventListener('click', () => {
|
||||
showToast('Rascunho limpo.', 'info');
|
||||
});
|
||||
|
||||
document.getElementById('btn-anterior').addEventListener('click', async () => {
|
||||
console.log('[DEBUG] btn-anterior clicado');
|
||||
const loja = val('f-loja') || 'União';
|
||||
console.log('[DEBUG] btn-anterior loja:', loja);
|
||||
const btnAnterior = document.getElementById('btn-anterior');
|
||||
if (btnAnterior) {
|
||||
btnAnterior.addEventListener('click', async () => {
|
||||
console.log('[DEBUG] btn-anterior clicado');
|
||||
const loja = val('f-loja') || 'União';
|
||||
console.log('[DEBUG] btn-anterior loja:', loja);
|
||||
|
||||
// Carrega lista de fechamentos recentes do Supabase com uuid
|
||||
let recentList = [];
|
||||
try {
|
||||
recentList = await window.__TAURI__.core.invoke('sb_listar_recentes', { loja, limite: 20 });
|
||||
console.log('[DEBUG] sb_listar_recentes retornou:', recentList?.length, 'itens');
|
||||
} catch(e) {
|
||||
console.warn('sb_listar_recentes falhou:', e);
|
||||
}
|
||||
// Carrega lista de fechamentos recentes do Supabase com uuid
|
||||
let recentList = [];
|
||||
try {
|
||||
recentList = await window.__TAURI__.core.invoke('sb_listar_recentes', { loja, limite: 20 });
|
||||
console.log('[DEBUG] sb_listar_recentes retornou:', recentList?.length, 'itens');
|
||||
} catch(e) {
|
||||
console.warn('sb_listar_recentes falhou:', e);
|
||||
}
|
||||
|
||||
// Extrai datas únicas ordenadas + mapeamento data→id
|
||||
const dateIdMap = {};
|
||||
const dateList = [];
|
||||
if (recentList && recentList.length > 0) {
|
||||
recentList.forEach(item => {
|
||||
if (item.data && !dateIdMap[item.data]) {
|
||||
dateIdMap[item.data] = item.id;
|
||||
dateList.push(item.data);
|
||||
}
|
||||
});
|
||||
dateList.sort().reverse();
|
||||
}
|
||||
console.log('[DEBUG] dateList:', dateList);
|
||||
// Extrai datas únicas ordenadas + mapeamento data→id
|
||||
const dateIdMap = {};
|
||||
const dateList = [];
|
||||
if (recentList && recentList.length > 0) {
|
||||
recentList.forEach(item => {
|
||||
if (item.data && !dateIdMap[item.data]) {
|
||||
dateIdMap[item.data] = item.id;
|
||||
dateList.push(item.data);
|
||||
}
|
||||
});
|
||||
dateList.sort().reverse();
|
||||
}
|
||||
console.log('[DEBUG] dateList:', dateList);
|
||||
|
||||
let selectedDate = null;
|
||||
let selectedId = null;
|
||||
if (dateList.length > 0) {
|
||||
const msg = dateList.map((d, i) => `${i + 1}) ${d}`).join('\n');
|
||||
const escolha = prompt(`Selecione o número do dia anterior:\n${msg}\n\n(Deixe em branco e clique Cancelar para ver só o dia anterior automático)`);
|
||||
if (escolha !== null && escolha.trim() !== '') {
|
||||
const idx = parseInt(escolha) - 1;
|
||||
if (idx >= 0 && idx < dateList.length) {
|
||||
selectedDate = dateList[idx];
|
||||
selectedId = dateIdMap[selectedDate];
|
||||
let selectedDate = null;
|
||||
let selectedId = null;
|
||||
if (dateList.length > 0) {
|
||||
const msg = dateList.map((d, i) => `${i + 1}) ${d}`).join('\n');
|
||||
const escolha = prompt(`Selecione o número do dia anterior:\n${msg}\n\n(Deixe em branco e clique Cancelar para ver só o dia anterior automático)`);
|
||||
if (escolha !== null && escolha.trim() !== '') {
|
||||
const idx = parseInt(escolha) - 1;
|
||||
if (idx >= 0 && idx < dateList.length) {
|
||||
selectedDate = dateList[idx];
|
||||
selectedId = dateIdMap[selectedDate];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Se não escolheu data, usa dia anterior automático (sem id — carrega por data)
|
||||
if (!selectedDate) {
|
||||
const d = new Date(estado.data); d.setDate(d.getDate() - 1);
|
||||
selectedDate = d.toISOString().split('T')[0];
|
||||
}
|
||||
console.log('[DEBUG] selectedDate:', selectedDate, 'selectedId:', selectedId);
|
||||
// Se não escolheu data, usa dia anterior automático (sem id — carrega por data)
|
||||
if (!selectedDate) {
|
||||
const d = new Date(estado.data); d.setDate(d.getDate() - 1);
|
||||
selectedDate = d.toISOString().split('T')[0];
|
||||
}
|
||||
console.log('[DEBUG] selectedDate:', selectedDate, 'selectedId:', selectedId);
|
||||
|
||||
await tauriSaveLocal();
|
||||
setVal('f-data', selectedDate);
|
||||
estado.data = selectedDate;
|
||||
estado.uuid = crypto.randomUUID ? crypto.randomUUID() : Date.now().toString();
|
||||
estado.id_local = null;
|
||||
syncHeader();
|
||||
await tauriSaveLocal();
|
||||
setVal('f-data', selectedDate);
|
||||
estado.data = selectedDate;
|
||||
estado.uuid = crypto.randomUUID ? crypto.randomUUID() : Date.now().toString();
|
||||
estado.id_local = null;
|
||||
syncHeader();
|
||||
|
||||
// Tenta Supabase primeiro (com id se disponível), senão local
|
||||
let rascunho = null;
|
||||
if (selectedId) {
|
||||
try {
|
||||
rascunho = await window.__TAURI__.core.invoke('sb_buscar_por_id', { id: selectedId });
|
||||
console.log('[DEBUG] sb_buscar_por_id retornou:', !!rascunho);
|
||||
} catch(e) { console.warn('sb_buscar_por_id falhou:', e); }
|
||||
}
|
||||
if (!rascunho) {
|
||||
try {
|
||||
rascunho = await window.__TAURI__.core.invoke('sb_carregar_rascunho', { loja, data: selectedDate });
|
||||
console.log('[DEBUG] sb_carregar_rascunho retornou:', !!rascunho);
|
||||
} catch(e) { console.warn('sb_carregar_rascunho falhou:', e); }
|
||||
}
|
||||
// Tenta Supabase primeiro (com id se disponível), senão local
|
||||
let rascunho = null;
|
||||
if (selectedId) {
|
||||
try {
|
||||
rascunho = await window.__TAURI__.core.invoke('sb_buscar_por_id', { id: selectedId });
|
||||
console.log('[DEBUG] sb_buscar_por_id retornou:', !!rascunho);
|
||||
} catch(e) { console.warn('sb_buscar_por_id falhou:', e); }
|
||||
}
|
||||
if (!rascunho) {
|
||||
try {
|
||||
rascunho = await window.__TAURI__.core.invoke('sb_carregar_rascunho', { loja, data: selectedDate });
|
||||
console.log('[DEBUG] sb_carregar_rascunho retornou:', !!rascunho);
|
||||
} catch(e) { console.warn('sb_carregar_rascunho falhou:', e); }
|
||||
}
|
||||
|
||||
if (!rascunho) {
|
||||
try {
|
||||
rascunho = await window.__TAURI__.core.invoke('carregar_rascunho', { loja, data: selectedDate });
|
||||
console.log('[DEBUG] carregar_rascunho local retornou:', !!rascunho);
|
||||
} catch(e) { console.warn('carregar_rascunho local falhou:', e); }
|
||||
}
|
||||
if (!rascunho) {
|
||||
try {
|
||||
rascunho = await window.__TAURI__.core.invoke('carregar_rascunho', { loja, data: selectedDate });
|
||||
console.log('[DEBUG] carregar_rascunho local retornou:', !!rascunho);
|
||||
} catch(e) { console.warn('carregar_rascunho local falhou:', e); }
|
||||
}
|
||||
|
||||
if (rascunho) {
|
||||
console.log('[DEBUG] rascunho carregado com sucesso');
|
||||
if (rascunho.operador) { setVal('f-operador', rascunho.operador); estado.operador = rascunho.operador; }
|
||||
if (rascunho.turno) { setVal('f-turno', rascunho.turno); estado.turno = rascunho.turno; }
|
||||
if (rascunho.saldo_troco) setVal('sys-troco', fmtNum(rascunho.saldo_troco));
|
||||
if (rascunho.saldo_esperado) setVal('f-saldo-esperado', fmtNum(rascunho.saldo_esperado));
|
||||
if (rascunho.observacoes) { setVal('f-obs', rascunho.observacoes); estado.observacoes = rascunho.observacoes; }
|
||||
if (rascunho.despesas && Array.isArray(rascunho.despesas)) {
|
||||
estado.despesas = rascunho.despesas.map(d => ({ desc: d.desc || d.descricao || '', obs: d.obs || '', valor: parseNum(d.valor) || 0 }));
|
||||
if (rascunho) {
|
||||
console.log('[DEBUG] rascunho carregado com sucesso');
|
||||
if (rascunho.operador) { setVal('f-operador', rascunho.operador); estado.operador = rascunho.operador; }
|
||||
if (rascunho.turno) { setVal('f-turno', rascunho.turno); estado.turno = rascunho.turno; }
|
||||
if (rascunho.saldo_troco) setVal('sys-troco', fmtNum(rascunho.saldo_troco));
|
||||
if (rascunho.saldo_esperado) setVal('f-saldo-esperado', fmtNum(rascunho.saldo_esperado));
|
||||
if (rascunho.observacoes) { setVal('f-obs', rascunho.observacoes); estado.observacoes = rascunho.observacoes; }
|
||||
if (rascunho.despesas && Array.isArray(rascunho.despesas)) {
|
||||
estado.despesas = rascunho.despesas.map(d => ({ desc: d.desc || d.descricao || '', obs: d.obs || '', valor: parseNum(d.valor) || 0 }));
|
||||
}
|
||||
if (rascunho.sangrias && Array.isArray(rascunho.sangrias)) {
|
||||
estado.sangrias = rascunho.sangrias.map(s => ({ hora: s.hora || '', retirada: parseNum(s.retirada) || 0, gerente: s.gerente || '' }));
|
||||
}
|
||||
if (rascunho.pixcnpj && Array.isArray(rascunho.pixcnpj)) {
|
||||
estado.pixcnpj = rascunho.pixcnpj.map(p => ({ nome: p.nome || '', valor: parseNum(p.valor) || 0 }));
|
||||
}
|
||||
if (rascunho.vales && Array.isArray(rascunho.vales)) {
|
||||
estado.vales = rascunho.vales.map(v => ({ nome: v.nome || '', obs: v.obs || '', valor: parseNum(v.valor) || 0 }));
|
||||
}
|
||||
if (rascunho.receber && Array.isArray(rascunho.receber)) {
|
||||
estado.receber = rascunho.receber.map(r => ({ nome: r.nome || '', valor: parseNum(r.valor) || 0 }));
|
||||
}
|
||||
if (rascunho.cancelamentos && Array.isArray(rascunho.cancelamentos)) {
|
||||
estado.cancelamentos = rascunho.cancelamentos.map(c => ({ numero: c.numero || '', valor: parseNum(c.valor) || 0, motivo: c.motivo || '' }));
|
||||
}
|
||||
if (rascunho.cartoes) {
|
||||
const norm = (arr) => Array.isArray(arr) ? arr.map(v => ({ valor: (typeof v === 'object' && v !== null) ? (parseNum(v.valor) || 0) : (parseNum(v) || 0) })) : [];
|
||||
estado.cartoes.credito = norm(rascunho.cartoes.credito);
|
||||
estado.cartoes.debito = norm(rascunho.cartoes.debito);
|
||||
estado.cartoes.alimentacao = norm(rascunho.cartoes.alimentacao);
|
||||
estado.cartoes.pix = norm(rascunho.cartoes.pix);
|
||||
}
|
||||
} else {
|
||||
console.log('[DEBUG] nenhum rascunho encontrado para esta data');
|
||||
estado.despesas = []; estado.sangrias = []; estado.pixcnpj = [];
|
||||
estado.vales = []; estado.receber = []; estado.cancelamentos = [];
|
||||
estado.cartoes = { credito: [], debito: [], alimentacao: [], pix: [] };
|
||||
setVal('sys-troco', ''); setVal('f-saldo-esperado', ''); setVal('f-obs', '');
|
||||
}
|
||||
if (rascunho.sangrias && Array.isArray(rascunho.sangrias)) {
|
||||
estado.sangrias = rascunho.sangrias.map(s => ({ hora: s.hora || '', retirada: parseNum(s.retirada) || 0, gerente: s.gerente || '' }));
|
||||
}
|
||||
if (rascunho.pixcnpj && Array.isArray(rascunho.pixcnpj)) {
|
||||
estado.pixcnpj = rascunho.pixcnpj.map(p => ({ nome: p.nome || '', valor: parseNum(p.valor) || 0 }));
|
||||
}
|
||||
if (rascunho.vales && Array.isArray(rascunho.vales)) {
|
||||
estado.vales = rascunho.vales.map(v => ({ nome: v.nome || '', obs: v.obs || '', valor: parseNum(v.valor) || 0 }));
|
||||
}
|
||||
if (rascunho.receber && Array.isArray(rascunho.receber)) {
|
||||
estado.receber = rascunho.receber.map(r => ({ nome: r.nome || '', valor: parseNum(r.valor) || 0 }));
|
||||
}
|
||||
if (rascunho.cancelamentos && Array.isArray(rascunho.cancelamentos)) {
|
||||
estado.cancelamentos = rascunho.cancelamentos.map(c => ({ numero: c.numero || '', valor: parseNum(c.valor) || 0, motivo: c.motivo || '' }));
|
||||
}
|
||||
if (rascunho.cartoes) {
|
||||
const norm = (arr) => Array.isArray(arr) ? arr.map(v => ({ valor: (typeof v === 'object' && v !== null) ? (parseNum(v.valor) || 0) : (parseNum(v) || 0) })) : [];
|
||||
estado.cartoes.credito = norm(rascunho.cartoes.credito);
|
||||
estado.cartoes.debito = norm(rascunho.cartoes.debito);
|
||||
estado.cartoes.alimentacao = norm(rascunho.cartoes.alimentacao);
|
||||
estado.cartoes.pix = norm(rascunho.cartoes.pix);
|
||||
}
|
||||
} else {
|
||||
console.log('[DEBUG] nenhum rascunho encontrado para esta data');
|
||||
estado.despesas = []; estado.sangrias = []; estado.pixcnpj = [];
|
||||
estado.vales = []; estado.receber = []; estado.cancelamentos = [];
|
||||
estado.cartoes = { credito: [], debito: [], alimentacao: [], pix: [] };
|
||||
setVal('sys-troco', ''); setVal('f-saldo-esperado', ''); setVal('f-obs', '');
|
||||
}
|
||||
|
||||
estado.sync_status = rascunho ? 'loaded' : 'local';
|
||||
estado.sync_status = rascunho ? 'loaded' : 'local';
|
||||
|
||||
PRE_FILL_TABLES.forEach(ensureOneRow);
|
||||
Object.keys(TABLES).forEach(renderTable);
|
||||
updateTotals();
|
||||
scheduleSave();
|
||||
console.log('[DEBUG] btn-anterior concluído');
|
||||
});
|
||||
PRE_FILL_TABLES.forEach(ensureOneRow);
|
||||
Object.keys(TABLES).forEach(renderTable);
|
||||
updateTotals();
|
||||
scheduleSave();
|
||||
console.log('[DEBUG] btn-anterior concluído');
|
||||
});
|
||||
} else {
|
||||
console.error('[DEBUG] btn-anterior NÃO encontrado no DOM!');
|
||||
}
|
||||
|
||||
document.getElementById('f-obs').addEventListener('input', e => { estado.observacoes = e.target.value; scheduleSave(); });
|
||||
|
||||
|
||||
Reference in New Issue
Block a user