|
|
|
@@ -855,8 +855,8 @@ function updateTotals() {
|
|
|
|
|
const receberTotal = estado.receber.reduce((s, r) => s + (parseNum(r['valor'] || 0) || 0), 0);
|
|
|
|
|
document.getElementById('sys-receber').value = receberTotal > 0 ? fmtNum(receberTotal) : '';
|
|
|
|
|
|
|
|
|
|
// SYS total = crédito + débito + alimentação + vales + receber + pixCartão + pixCnpj (NÃO inclui troco)
|
|
|
|
|
const sysTotal = cartCred + cartDeb + cartAli + valesTotal + receberTotal + cartPix + pixCnpjTotal;
|
|
|
|
|
// Saldo de Caixa (Sistema) = troco + crédito + débito + alimentação + vales + receber + pixCartão + pixCnpj
|
|
|
|
|
const sysTotal = parseNum(val('sys-troco')) + cartCred + cartDeb + cartAli + valesTotal + receberTotal + cartPix + pixCnpjTotal;
|
|
|
|
|
setText('sys-total', fmt(sysTotal));
|
|
|
|
|
|
|
|
|
|
// ── Fechamento Contado — auto-populate (readonly, filled from tables) ──
|
|
|
|
@@ -873,10 +873,9 @@ function updateTotals() {
|
|
|
|
|
const fr = receberTotal;
|
|
|
|
|
setText('fech-total', fmt(fd + fc + fr));
|
|
|
|
|
|
|
|
|
|
// Diferença = fechamento - saldo_esperado - cancelamentos
|
|
|
|
|
const fechamentoTotal = fd + fc + fr;
|
|
|
|
|
// Diferença = total_fechamento (sysTotal: troco+credito+debito+alimentacao+vales+receber+pixCartao+pixCnpj) - saldo_esperado - cancelamentos
|
|
|
|
|
const cancelTotal = estado.cancelamentos.reduce((s,r) => s+(parseNum(r.valor||0)||0), 0);
|
|
|
|
|
const diff = fechamentoTotal - parseNum(val('f-saldo-esperado')) - cancelTotal;
|
|
|
|
|
const diff = sysTotal - parseNum(val('f-saldo-esperado')) - cancelTotal;
|
|
|
|
|
const difEl = document.getElementById('diferenca');
|
|
|
|
|
const badgeEl = document.getElementById('dif-badge');
|
|
|
|
|
if (difEl) {
|
|
|
|
@@ -1060,6 +1059,18 @@ const LS_KEY = 'fc_v7';
|
|
|
|
|
const CFG_KEY = 'fc_cfg';
|
|
|
|
|
|
|
|
|
|
function buildEstadoForBackend() {
|
|
|
|
|
// Calcula totais das tabelas (mesma lógica do updateTotals)
|
|
|
|
|
const sangriasTotal = estado.sangrias.reduce((s, r) => s + (parseNum(r['retirada'] || 0) || 0), 0);
|
|
|
|
|
const despesasTotal = estado.despesas.reduce((s, r) => s + (parseNum(r['valor'] || 0) || 0), 0);
|
|
|
|
|
const pixcnpjTotal = estado.pixcnpj.reduce((s, r) => s + (parseNum(r['valor'] || 0) || 0), 0);
|
|
|
|
|
const valesTotal = estado.vales.reduce((s, r) => s + (parseNum(r['valor'] || 0) || 0), 0);
|
|
|
|
|
const receberTotal = estado.receber.reduce((s, r) => s + (parseNum(r['valor'] || 0) || 0), 0);
|
|
|
|
|
const cancelTotal = estado.cancelamentos.reduce((s, r) => s + (parseNum(r['valor'] || 0) || 0), 0);
|
|
|
|
|
const cartCred = estado.cartoes.credito.reduce((s, r) => s + (r.valor || 0), 0);
|
|
|
|
|
const cartDeb = estado.cartoes.debito.reduce((s, r) => s + (r.valor || 0), 0);
|
|
|
|
|
const cartAli = estado.cartoes.alimentacao.reduce((s, r) => s + (r.valor || 0), 0);
|
|
|
|
|
const cartPix = estado.cartoes.pix.reduce((s, r) => s + (r.valor || 0), 0);
|
|
|
|
|
|
|
|
|
|
// Monta o objeto exactly as o backend espera (storage.rs → salvar_fechamento)
|
|
|
|
|
return {
|
|
|
|
|
uuid: estado.uuid,
|
|
|
|
@@ -1068,9 +1079,31 @@ function buildEstadoForBackend() {
|
|
|
|
|
data: estado.data,
|
|
|
|
|
operador: estado.operador,
|
|
|
|
|
turno: estado.turno,
|
|
|
|
|
saldo_troco: parseNum(val('sys-troco')), // troco do sistema
|
|
|
|
|
saldo_troco: parseNum(val('sys-troco')),
|
|
|
|
|
saldo_esperado: parseNum(val('f-saldo-esperado')),
|
|
|
|
|
fechamento: parseNum(val('f-fech-dinheiro')) + parseNum(val('f-fech-cartoes')) + parseNum(val('f-fech-receber')),
|
|
|
|
|
// Saldos de cartões (do Sys / Saldo de Caixa)
|
|
|
|
|
credito: parseNum(val('sys-credito')) || cartCred,
|
|
|
|
|
debito: parseNum(val('sys-debito')) || cartDeb,
|
|
|
|
|
alimentacao: parseNum(val('sys-alimentacao')) || cartAli,
|
|
|
|
|
pixcnpj: parseNum(val('sys-pixcnpj')) || pixcnpjTotal,
|
|
|
|
|
vales: parseNum(val('sys-vales')) || valesTotal,
|
|
|
|
|
receber: parseNum(val('sys-receber')) || receberTotal,
|
|
|
|
|
// Totais para colunas SQL
|
|
|
|
|
total_sangrias: sangriasTotal,
|
|
|
|
|
total_despesas: despesasTotal,
|
|
|
|
|
total_pixcnpj: pixcnpjTotal,
|
|
|
|
|
total_vales: valesTotal,
|
|
|
|
|
total_areceber: receberTotal,
|
|
|
|
|
total_cancelamentos: cancelTotal,
|
|
|
|
|
total_cartao_credito: cartCred,
|
|
|
|
|
total_cartao_debito: cartDeb,
|
|
|
|
|
total_cartao_alimentacao: cartAli,
|
|
|
|
|
total_cartao_pix: cartPix,
|
|
|
|
|
// Fechamento contado
|
|
|
|
|
fd: parseNum(val('f-fech-dinheiro')),
|
|
|
|
|
fc: parseNum(val('f-fech-cartoes')),
|
|
|
|
|
fr: parseNum(val('f-fech-receber')),
|
|
|
|
|
despesas: estado.despesas.map(r => ({ desc: r.desc || '', obs: r.obs || '', valor: r.valor || 0 })),
|
|
|
|
|
sangrias: estado.sangrias.map(r => ({ hora: r.hora || '', retirada: r.retirada || 0, gerente: r.gerente || '' })),
|
|
|
|
|
pixcnpj: estado.pixcnpj.map(r => ({ nome: r.nome || '', valor: r.valor || 0 })),
|
|
|
|
@@ -1636,6 +1669,10 @@ ${cancLines.map(l => `<div class="row"><span>${l.label}</span><span>${fmt(l.valo
|
|
|
|
|
<div class="row"><span>À Receber:</span><span>${fmt(frec)}</span></div>
|
|
|
|
|
<div class="row total-row"><span>TOTAL:</span><span>${fmt(ftotal)}</span></div>
|
|
|
|
|
|
|
|
|
|
<div class="section-title">CONTADORES</div>
|
|
|
|
|
<div class="row"><span>Clientes:</span><span>${data.clientes || 0}</span></div>
|
|
|
|
|
<div class="row"><span>Frango Assado:</span><span>${data.frango || 0}</span></div>
|
|
|
|
|
|
|
|
|
|
${data.observacoes ? `<div class="obs">${data.observacoes}</div>` : ''}
|
|
|
|
|
|
|
|
|
|
<div class="footer">Gerado em ${new Date().toLocaleString('pt-BR')}</div>
|
|
|
|
@@ -1695,8 +1732,6 @@ function buildReportHTML(data) {
|
|
|
|
|
<div class="row"><span>💳 Débito:</span><span class="val">${fmt(cartDeb)}</span></div>
|
|
|
|
|
<div class="row"><span>💳 Alimentação:</span><span class="val">${fmt(cartAli)}</span></div>
|
|
|
|
|
<div class="row"><span>❌ Cancelamentos:</span><span class="val">${fmt(cancelamentos)}</span></div>
|
|
|
|
|
<div class="row"><span>👥 Clientes:</span><span class="val">${data.clientes || 0}</span></div>
|
|
|
|
|
<div class="row"><span>🍗 Frango Assado:</span><span class="val">${data.frango || 0}</span></div>
|
|
|
|
|
<hr>
|
|
|
|
|
<div class="row"><span>📋 Fechamento (contado):</span><span class="val">${fmt(fechamento)}</span></div>
|
|
|
|
|
<div class="row"><span>🖥️ Total Sistema:</span><span class="val">${fmt(sysTotal)}</span></div>
|
|
|
|
@@ -1704,6 +1739,9 @@ function buildReportHTML(data) {
|
|
|
|
|
<div class="row"><span>🎯 Saldo Esperado (contado):</span><span class="val">${fmt(saldoEsp)}</span></div>
|
|
|
|
|
<div class="row"><span>📐 Diferença:</span><span class="val" style="color:${diffColor}">${diffStr}</span></div>
|
|
|
|
|
<hr>
|
|
|
|
|
<div class="row"><span>👥 Clientes:</span><span class="val">${data.clientes || 0}</span></div>
|
|
|
|
|
<div class="row"><span>🍗 Frango Assado:</span><span class="val">${data.frango || 0}</span></div>
|
|
|
|
|
<hr>
|
|
|
|
|
<div style="text-align:center;font-size:10px;color:#888">ID: ${data.loja}_${data.data}_${data.operador}</div>
|
|
|
|
|
<div class="footer">Gerado em ${new Date().toLocaleString('pt-BR')}</div>
|
|
|
|
|
</body></html>`;
|
|
|
|
@@ -1807,10 +1845,10 @@ function buildReciboData() {
|
|
|
|
|
const cancelTotal = estado.cancelamentos.reduce((s,r) => s+(parseNum(r.valor||0)||0), 0);
|
|
|
|
|
const fechamentoCounted = parseNum(val('f-fech-dinheiro')) + parseNum(val('f-fech-cartoes')) + parseNum(val('f-fech-receber'));
|
|
|
|
|
const saldoEsp = parseNum(val('f-saldo-esperado'));
|
|
|
|
|
// SYS total = crédito + débito + alimentação + voucher pix + pixcnpj + vales + receber (NÃO inclui troco)
|
|
|
|
|
const sysTotal = cartCred + cartDeb + cartAli + cartPix + pixCnpjTotal + valesTotal + receberTotal;
|
|
|
|
|
// Diferença = fechamento - saldo_esperado - cancelamentos
|
|
|
|
|
const diferenca = fechamentoCounted - saldoEsp - cancelTotal;
|
|
|
|
|
// Saldo de Caixa (Sistema) = troco + crédito + débito + alimentação + voucher pix + pixcnpj + vales + receber
|
|
|
|
|
const sysTotal = parseNum(val('sys-troco')) + cartCred + cartDeb + cartAli + cartPix + pixCnpjTotal + valesTotal + receberTotal;
|
|
|
|
|
// Diferença = saldo de caixa (sistema) - saldo_esperado - cancelamentos
|
|
|
|
|
const diferenca = sysTotal - saldoEsp - cancelTotal;
|
|
|
|
|
return {
|
|
|
|
|
uuid: estado.uuid,
|
|
|
|
|
id_local: estado.id_local,
|
|
|
|
@@ -1902,8 +1940,8 @@ function openConfirmModal() {
|
|
|
|
|
const pixcnpj = estado.pixcnpj.reduce((s,r) => s+(parseNum(r.valor||0)||0), 0);
|
|
|
|
|
const fechamento = parseNum(val('f-fech-dinheiro')) + parseNum(val('f-fech-cartoes')) + parseNum(val('f-fech-receber'));
|
|
|
|
|
const saldoEsp = parseNum(val('f-saldo-esperado'));
|
|
|
|
|
const sysTotal = cartCred + cartDeb + cartAli + cartPix + vales + receber + pixcnpj;
|
|
|
|
|
const diferenca = fechamento - saldoEsp - cancelamentos;
|
|
|
|
|
const sysTotal = parseNum(val('sys-troco')) + cartCred + cartDeb + cartAli + cartPix + vales + receber + pixcnpj;
|
|
|
|
|
const diferenca = sysTotal - saldoEsp - cancelamentos;
|
|
|
|
|
const diffClass = diferenca === 0 ? '#2e7d32' : (diferenca > 0 ? '#e65100' : '#c0272d');
|
|
|
|
|
document.getElementById('confirm-summary').innerHTML =
|
|
|
|
|
`<div style="margin-bottom:6px"><strong>📅 Data:</strong> ${estado.data} <strong>👤 Operador:</strong> ${operador} <strong>⏰ Turno:</strong> ${turno} <strong>🏪 Loja:</strong> ${loja}</div>
|
|
|
|
@@ -2026,20 +2064,17 @@ document.getElementById('btn-limpar').addEventListener('click', () => {
|
|
|
|
|
showToast('Rascunho limpo.', 'info');
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
// ─── Dia Anterior — seleção de registro do Supabase ────────────────────────
|
|
|
|
|
// ─── Dia Anterior — seleção + consulta + edição de registros do Supabase ───
|
|
|
|
|
const btnAnterior = document.getElementById('btn-anterior');
|
|
|
|
|
if (btnAnterior) {
|
|
|
|
|
btnAnterior.addEventListener('click', async () => {
|
|
|
|
|
console.log('[DEBUG] btn-anterior clicado');
|
|
|
|
|
const hasTauri = !!(window.__TAURI__ && window.__TAURI__.core);
|
|
|
|
|
|
|
|
|
|
// Pega lista do Supabase
|
|
|
|
|
let recentList = [];
|
|
|
|
|
if (hasTauri) {
|
|
|
|
|
try {
|
|
|
|
|
const loja = val('f-loja') || 'União';
|
|
|
|
|
recentList = await window.__TAURI__.core.invoke('sb_listar_recentes', { loja, limite: 50 });
|
|
|
|
|
console.log('[DEBUG] sb_listar_recentes retornou:', recentList?.length, 'itens');
|
|
|
|
|
} catch(e) {
|
|
|
|
|
console.warn('sb_listar_recentes falhou:', e);
|
|
|
|
|
}
|
|
|
|
@@ -2050,19 +2085,17 @@ if (btnAnterior) {
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Mostra modal de seleção com datas
|
|
|
|
|
buildAnteriorModal(recentList);
|
|
|
|
|
buildConsultaModal(recentList);
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Monta e abre o modal de seleção de dia anterior
|
|
|
|
|
function buildAnteriorModal(recentList) {
|
|
|
|
|
// Remove modal anterior
|
|
|
|
|
const old = document.getElementById('modal-anterior');
|
|
|
|
|
// Monta o modal de consulta — lista de fechamentos do Supabase
|
|
|
|
|
function buildConsultaModal(recentList) {
|
|
|
|
|
const old = document.getElementById('modal-consulta');
|
|
|
|
|
if (old) document.body.removeChild(old);
|
|
|
|
|
|
|
|
|
|
const overlay = document.createElement('div');
|
|
|
|
|
overlay.id = 'modal-anterior';
|
|
|
|
|
overlay.id = 'modal-consulta';
|
|
|
|
|
overlay.style.cssText = `
|
|
|
|
|
position:fixed;top:0;left:0;right:0;bottom:0;
|
|
|
|
|
background:rgba(0,0,0,0.6);z-index:99998;
|
|
|
|
@@ -2074,35 +2107,49 @@ function buildAnteriorModal(recentList) {
|
|
|
|
|
const [y,m,day] = d.split('-');
|
|
|
|
|
return `${day}/${m}/${y}`;
|
|
|
|
|
};
|
|
|
|
|
const fmtMoney = v => v != null ? `R$ ${parseFloat(v).toFixed(2).replace('.', ',')}` : 'R$ 0,00';
|
|
|
|
|
const syncBadge = s => {
|
|
|
|
|
const colors = { synced: '#2e7d32', local: '#e65100', syncing: '#f57f17', error: '#c0272d' };
|
|
|
|
|
const labels = { synced: '✓ Sync', local: '⚠ Local', syncing: '⏳ Sync', error: '✗ Erro' };
|
|
|
|
|
return `<span style="background:${colors[s]||'#888'};color:#fff;padding:1px 5px;border-radius:3px;font-size:10px">${labels[s]||s||'?'}</span>`;
|
|
|
|
|
};
|
|
|
|
|
const statusBadge = s => {
|
|
|
|
|
if (s === 'ok') return '<span style="color:#2e7d32;font-weight:bold">✓ OK</span>';
|
|
|
|
|
if (s === 'sobrando') return '<span style="color:#e65100;font-weight:bold">⚠ SOBRANDO</span>';
|
|
|
|
|
if (s === 'faltando') return '<span style="color:#c0272d;font-weight:bold">⚠ FALTANDO</span>';
|
|
|
|
|
return s || '?';
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
const rows = recentList.map((item, i) => `
|
|
|
|
|
<tr style="cursor:pointer" onclick="selectDiaAnterior(${i})">
|
|
|
|
|
const rows = recentList.map((item, i) => {
|
|
|
|
|
const total = (parseFloat(item.fechamento_dinheiro)||0) + (parseFloat(item.fechamento_cartoes)||0) + (parseFloat(item.fechamento_areceber)||0);
|
|
|
|
|
return `<tr style="cursor:pointer" onclick="openConsultaRegistro(${i})">
|
|
|
|
|
<td style="padding:6px 8px;border-bottom:1px solid #eee;font-size:12px">${fmtDate(item.data)}</td>
|
|
|
|
|
<td style="padding:6px 8px;border-bottom:1px solid #eee;font-size:12px">${item.operador||'?'}</td>
|
|
|
|
|
<td style="padding:6px 8px;border-bottom:1px solid #eee;font-size:12px">${item.turno||'?'}</td>
|
|
|
|
|
<td style="padding:6px 8px;border-bottom:1px solid #eee;font-size:12px;text-align:right">${fmtMoney(total)}</td>
|
|
|
|
|
<td style="padding:6px 8px;border-bottom:1px solid #eee;font-size:12px;text-align:right">${fmtMoney(item.saldo_esperado)}</td>
|
|
|
|
|
<td style="padding:6px 8px;border-bottom:1px solid #eee;font-size:12px">${statusBadge(item.status_diferenca)}</td>
|
|
|
|
|
<td style="padding:6px 8px;border-bottom:1px solid #eee;font-size:12px">${syncBadge(item.sync_status)}</td>
|
|
|
|
|
</tr>
|
|
|
|
|
`).join('');
|
|
|
|
|
</tr>`;
|
|
|
|
|
}).join('');
|
|
|
|
|
|
|
|
|
|
overlay.innerHTML = `
|
|
|
|
|
<div style="background:#fff;border-radius:10px;padding:20px;max-width:480px;width:90%;max-height:80vh;overflow-y:auto">
|
|
|
|
|
<div style="background:#fff;border-radius:10px;padding:20px;max-width:700px;width:95%;max-height:85vh;overflow-y:auto">
|
|
|
|
|
<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:12px">
|
|
|
|
|
<h2 style="margin:0;font-size:16px">📅 Selecionar Dia Anterior</h2>
|
|
|
|
|
<button onclick="closeAnteriorModal()" style="background:none;border:none;font-size:18px;cursor:pointer">✕</button>
|
|
|
|
|
<h2 style="margin:0;font-size:16px">📅 Consultar Fechamentos Anteriores</h2>
|
|
|
|
|
<button onclick="closeConsultaModal()" style="background:none;border:none;font-size:18px;cursor:pointer">✕</button>
|
|
|
|
|
</div>
|
|
|
|
|
<p style="font-size:12px;color:#666;margin:0 0 10px">Clique em um registro para carregar. Dados do Supabase.</p>
|
|
|
|
|
<p style="font-size:12px;color:#666;margin:0 0 10px">Clique em um registro para ver o relatório e, se necessário, editar campos com senha admin.</p>
|
|
|
|
|
<table style="width:100%;border-collapse:collapse">
|
|
|
|
|
<thead>
|
|
|
|
|
<tr style="background:#f5f5f5">
|
|
|
|
|
<th style="padding:6px 8px;text-align:left;font-size:11px;color:#888">DATA</th>
|
|
|
|
|
<th style="padding:6px 8px;text-align:left;font-size:11px;color:#888">OPERADOR</th>
|
|
|
|
|
<th style="padding:6px 8px;text-align:left;font-size:11px;color:#888">TURNO</th>
|
|
|
|
|
<th style="padding:6px 8px;text-align:left;font-size:11px;color:#888">STATUS</th>
|
|
|
|
|
<th style="padding:6px 8px;text-align:right;font-size:11px;color:#888">FECHAMENTO</th>
|
|
|
|
|
<th style="padding:6px 8px;text-align:right;font-size:11px;color:#888">ESPERADO</th>
|
|
|
|
|
<th style="padding:6px 8px;text-align:center;font-size:11px;color:#888">STATUS</th>
|
|
|
|
|
<th style="padding:6px 8px;text-align:center;font-size:11px;color:#888">SYNC</th>
|
|
|
|
|
</tr>
|
|
|
|
|
</thead>
|
|
|
|
|
<tbody>${rows}</tbody>
|
|
|
|
@@ -2114,102 +2161,275 @@ function buildAnteriorModal(recentList) {
|
|
|
|
|
window._recentList = recentList;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function closeAnteriorModal() {
|
|
|
|
|
const m = document.getElementById('modal-anterior');
|
|
|
|
|
function closeConsultaModal() {
|
|
|
|
|
const m = document.getElementById('modal-consulta');
|
|
|
|
|
if (m) document.body.removeChild(m);
|
|
|
|
|
window._recentList = null;
|
|
|
|
|
window._currentConsulta = null;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Usuário clicou numa linha — pede senha se configurada
|
|
|
|
|
window.selectDiaAnterior = async function(idx) {
|
|
|
|
|
// Abre o relatório de um registro selecionado
|
|
|
|
|
window.openConsultaRegistro = async function(idx) {
|
|
|
|
|
const item = window._recentList[idx];
|
|
|
|
|
if (!item) return;
|
|
|
|
|
closeAnteriorModal();
|
|
|
|
|
closeConsultaModal();
|
|
|
|
|
|
|
|
|
|
const hasTauri = !!(window.__TAURI__ && window.__TAURI__.core);
|
|
|
|
|
if (!hasTauri) { alert('Tauri não disponível.'); return; }
|
|
|
|
|
|
|
|
|
|
let full = null;
|
|
|
|
|
try {
|
|
|
|
|
if (item.uuid) {
|
|
|
|
|
try { full = await window.__TAURI__.core.invoke('sb_buscar_por_uuid', { uuid: item.uuid }); } catch(e) {}
|
|
|
|
|
}
|
|
|
|
|
if (!full && item.id_fechamento) {
|
|
|
|
|
try { full = await window.__TAURI__.core.invoke('sb_buscar_por_id_fechamento', { id_fechamento: item.id_fechamento }); } catch(e) {}
|
|
|
|
|
}
|
|
|
|
|
if (!full && item.id) {
|
|
|
|
|
try { full = await window.__TAURI__.core.invoke('sb_buscar_por_id', { id: String(item.id) }); } catch(e) {}
|
|
|
|
|
}
|
|
|
|
|
} catch(e) {
|
|
|
|
|
console.warn('Erro buscando registro:', e);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (!full) { alert('Registro não encontrado.'); return; }
|
|
|
|
|
|
|
|
|
|
window._currentConsulta = full;
|
|
|
|
|
buildRelatorioModal(full);
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
// Monta o modal de relatório (readonly) com opção de editar
|
|
|
|
|
function buildRelatorioModal(full) {
|
|
|
|
|
const old = document.getElementById('modal-relatorio');
|
|
|
|
|
if (old) document.body.removeChild(old);
|
|
|
|
|
|
|
|
|
|
const overlay = document.createElement('div');
|
|
|
|
|
overlay.id = 'modal-relatorio';
|
|
|
|
|
overlay.style.cssText = `
|
|
|
|
|
position:fixed;top:0;left:0;right:0;bottom:0;
|
|
|
|
|
background:rgba(0,0,0,0.6);z-index:99998;
|
|
|
|
|
display:flex;align-items:center;justify-content:center;
|
|
|
|
|
`;
|
|
|
|
|
|
|
|
|
|
const fmt = v => v != null ? parseFloat(v).toFixed(2).replace('.', ',') : '0,00';
|
|
|
|
|
const fmtMoney = v => `R$ ${fmt(v)}`;
|
|
|
|
|
|
|
|
|
|
const dados = full.dados || {};
|
|
|
|
|
|
|
|
|
|
// Campos do sistema
|
|
|
|
|
const troco = parseFloat(full.saldo_troco || 0);
|
|
|
|
|
const credito = parseFloat(full.saldo_credito || 0);
|
|
|
|
|
const debito = parseFloat(full.saldo_debito || 0);
|
|
|
|
|
const alimentacao = parseFloat(full.saldo_alimentacao || 0);
|
|
|
|
|
const vales = parseFloat(full.saldo_vales || 0);
|
|
|
|
|
const pixCartao = parseFloat(full.total_cartao_pix || 0);
|
|
|
|
|
const pixCnpj = parseFloat(full.total_pixcnpj || 0);
|
|
|
|
|
const sysTotal = troco + credito + debito + alimentacao + vales + (parseFloat(full.saldo_areceber)||0) + pixCartao + pixCnpj;
|
|
|
|
|
|
|
|
|
|
// Campos contados
|
|
|
|
|
const fd = parseFloat(full.fechamento_dinheiro || 0);
|
|
|
|
|
const fc = parseFloat(full.fechamento_cartoes || 0);
|
|
|
|
|
const fr = parseFloat(full.fechamento_areceber || 0);
|
|
|
|
|
const fechamentoContado = fd + fc + fr;
|
|
|
|
|
|
|
|
|
|
// Despesas e sangrias
|
|
|
|
|
const totalDespesas = parseFloat(full.total_despesas || 0);
|
|
|
|
|
const totalSangrias = parseFloat(full.total_sangrias || 0);
|
|
|
|
|
const totalCancelamentos = parseFloat(full.total_cancelamentos || 0);
|
|
|
|
|
|
|
|
|
|
// Esperado e diferença
|
|
|
|
|
const saldoEsperado = parseFloat(full.saldo_esperado || 0);
|
|
|
|
|
const diferenca = parseFloat(full.diferenca || 0);
|
|
|
|
|
const statusDif = full.status_diferenca || '?';
|
|
|
|
|
|
|
|
|
|
const diffClass = statusDif === 'ok' ? '#2e7d32' : (statusDif === 'sobrando' ? '#e65100' : '#c0272d');
|
|
|
|
|
const diffLabel = statusDif === 'ok' ? '✓ OK' : (statusDif === 'sobrando' ? '⚠ SOBRANDO' : (statusDif === 'faltando' ? '⚠ FALTANDO' : statusDif));
|
|
|
|
|
|
|
|
|
|
const operador = full.operador || '?';
|
|
|
|
|
const turno = full.turno || '?';
|
|
|
|
|
const data = full.data || '?';
|
|
|
|
|
const loja = full.loja || '?';
|
|
|
|
|
const obs = full.observacoes || '';
|
|
|
|
|
const clientes = full.clientes || 0;
|
|
|
|
|
const frango = full.frango || 0;
|
|
|
|
|
const atualizado = full.atualizado_em ? new Date(full.atualizado_em).toLocaleString('pt-BR') : '?';
|
|
|
|
|
|
|
|
|
|
const totalGeral = fd + fc + fr;
|
|
|
|
|
|
|
|
|
|
overlay.innerHTML = `
|
|
|
|
|
<div id="relatorio-inner" style="background:#fff;border-radius:10px;padding:20px;max-width:520px;width:95%;max-height:90vh;overflow-y:auto;font-family:monospace;font-size:13px">
|
|
|
|
|
<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:10px">
|
|
|
|
|
<h2 style="margin:0;font-size:15px">🧾 Relatório — ${loja.toUpperCase()}</h2>
|
|
|
|
|
<button onclick="closeRelatorioModal()" style="background:none;border:none;font-size:18px;cursor:pointer">✕</button>
|
|
|
|
|
</div>
|
|
|
|
|
|
|
|
|
|
<div style="background:#f8f8f8;border-radius:6px;padding:10px;margin-bottom:10px;font-size:12px">
|
|
|
|
|
<div><strong>📅 Data:</strong> ${data} <strong>Turno:</strong> ${turno} <strong>Operador:</strong> ${operador}</div>
|
|
|
|
|
<div><strong>Atualizado:</strong> ${atualizado}</div>
|
|
|
|
|
</div>
|
|
|
|
|
|
|
|
|
|
<div style="border:1px solid #ddd;border-radius:6px;overflow:hidden;margin-bottom:10px">
|
|
|
|
|
<div style="background:#e65100;color:#fff;padding:4px 8px;font-weight:bold;font-size:12px">FECHAMENTO DE CAIXA</div>
|
|
|
|
|
<div style="padding:8px">
|
|
|
|
|
<div style="display:flex;justify-content:space-between"><span>Troco (+)</span><span>${fmtMoney(troco)}</span></div>
|
|
|
|
|
<div style="display:flex;justify-content:space-between"><span>Credito (+)</span><span>${fmtMoney(credito)}</span></div>
|
|
|
|
|
<div style="display:flex;justify-content:space-between"><span>Debito (+)</span><span>${fmtMoney(debito)}</span></div>
|
|
|
|
|
<div style="display:flex;justify-content:space-between"><span>Alimentacao (+)</span><span>${fmtMoney(alimentacao)}</span></div>
|
|
|
|
|
<div style="display:flex;justify-content:space-between"><span>Vales (+)</span><span>${fmtMoney(vales)}</span></div>
|
|
|
|
|
<div style="display:flex;justify-content:space-between"><span>A Receber (+)</span><span>${fmtMoney(parseFloat(full.saldo_areceber||0))}</span></div>
|
|
|
|
|
<div style="display:flex;justify-content:space-between"><span>PIX Cartao (+)</span><span>${fmtMoney(pixCartao)}</span></div>
|
|
|
|
|
<div style="display:flex;justify-content:space-between"><span>PIX CNPJ (+)</span><span>${fmtMoney(pixCnpj)}</span></div>
|
|
|
|
|
<div style="border-top:1px solid #ddd;margin-top:4px;padding-top:4px;display:flex;justify-content:space-between;font-weight:bold"><span>TOTAL SISTEMA</span><span style="color:#e65100">${fmtMoney(sysTotal)}</span></div>
|
|
|
|
|
</div>
|
|
|
|
|
</div>
|
|
|
|
|
|
|
|
|
|
<div style="border:1px solid #ddd;border-radius:6px;overflow:hidden;margin-bottom:10px">
|
|
|
|
|
<div style="background:#1565c0;color:#fff;padding:4px 8px;font-weight:bold;font-size:12px">SALDO DE CAIXA (CONTADO)</div>
|
|
|
|
|
<div style="padding:8px">
|
|
|
|
|
<div style="display:flex;justify-content:space-between"><span>Dinheiro</span><span>${fmtMoney(fd)}</span></div>
|
|
|
|
|
<div style="display:flex;justify-content:space-between"><span>Cartoes</span><span>${fmtMoney(fc)}</span></div>
|
|
|
|
|
<div style="display:flex;justify-content:space-between"><span>A Receber</span><span>${fmtMoney(fr)}</span></div>
|
|
|
|
|
<div style="border-top:1px solid #ddd;margin-top:4px;padding-top:4px;display:flex;justify-content:space-between;font-weight:bold"><span>TOTAL CONTADO</span><span>${fmtMoney(totalGeral)}</span></div>
|
|
|
|
|
</div>
|
|
|
|
|
</div>
|
|
|
|
|
|
|
|
|
|
<div style="border:1px solid #ddd;border-radius:6px;overflow:hidden;margin-bottom:10px">
|
|
|
|
|
<div style="background:#333;color:#fff;padding:4px 8px;font-weight:bold;font-size:12px">RESULTADO</div>
|
|
|
|
|
<div style="padding:8px">
|
|
|
|
|
<div style="display:flex;justify-content:space-between"><span>Saldo Esperado</span><span>${fmtMoney(saldoEsperado)}</span></div>
|
|
|
|
|
<div style="display:flex;justify-content:space-between"><span>Cancelamentos</span><span>- ${fmtMoney(totalCancelamentos)}</span></div>
|
|
|
|
|
<div style="display:flex;justify-content:space-between;border-top:1px solid #ddd;margin-top:4px;padding-top:4px">
|
|
|
|
|
<span>Diferenca</span>
|
|
|
|
|
<span style="color:${diffClass};font-weight:bold">${fmtMoney(Math.abs(diferenca))} ${diferenca >= 0 ? '(+)' : '(-)'}</span>
|
|
|
|
|
</div>
|
|
|
|
|
<div style="text-align:center;margin-top:4px;font-weight:bold;color:${diffClass}">${diffLabel}</div>
|
|
|
|
|
</div>
|
|
|
|
|
</div>
|
|
|
|
|
|
|
|
|
|
<div style="border:1px solid #ddd;border-radius:6px;overflow:hidden;margin-bottom:10px">
|
|
|
|
|
<div style="background:#555;color:#fff;padding:4px 8px;font-weight:bold;font-size:12px">DEMAIS TOTAIS</div>
|
|
|
|
|
<div style="padding:8px">
|
|
|
|
|
<div style="display:flex;justify-content:space-between"><span>Total Sangrias</span><span>${fmtMoney(totalSangrias)}</span></div>
|
|
|
|
|
<div style="display:flex;justify-content:space-between"><span>Total Despesas</span><span>${fmtMoney(totalDespesas)}</span></div>
|
|
|
|
|
<div style="display:flex;justify-content:space-between"><span>Clientes</span><span>${clientes}</span></div>
|
|
|
|
|
<div style="display:flex;justify-content:space-between"><span>Frango Assado</span><span>${frango}</span></div>
|
|
|
|
|
</div>
|
|
|
|
|
</div>
|
|
|
|
|
|
|
|
|
|
${obs ? `<div style="background:#fff8e1;border-radius:6px;padding:8px;margin-bottom:10px;font-size:12px"><strong>Obs:</strong> ${obs}</div>` : ''}
|
|
|
|
|
|
|
|
|
|
<div id="edit-section" style="display:none;margin-bottom:10px">
|
|
|
|
|
<div style="font-size:12px;color:#666;margin-bottom:6px">Editar campos (requer senha admin):</div>
|
|
|
|
|
<div style="margin-bottom:6px">
|
|
|
|
|
<label style="font-size:11px;color:#555">Saldo Esperado:</label><br>
|
|
|
|
|
<input type="text" id="edit-esperado" value="${fmtMoney(saldoEsperado)}" style="width:100%;padding:4px;border:1px solid #ccc;border-radius:4px" />
|
|
|
|
|
</div>
|
|
|
|
|
<div style="margin-bottom:6px">
|
|
|
|
|
<label style="font-size:11px;color:#555">Observacoes:</label><br>
|
|
|
|
|
<textarea id="edit-obs" style="width:100%;padding:4px;border:1px solid #ccc;border-radius:4px;height:60px">${obs}</textarea>
|
|
|
|
|
</div>
|
|
|
|
|
</div>
|
|
|
|
|
|
|
|
|
|
<div style="display:flex;gap:8px;flex-wrap:wrap">
|
|
|
|
|
<button onclick="window.printRelatorio()" style="flex:1;padding:8px;background:#1565c0;color:#fff;border:none;border-radius:6px;cursor:pointer;font-size:13px">🖨️ Imprimir</button>
|
|
|
|
|
<button onclick="window.toggleEditConsulta()" style="flex:1;padding:8px;background:#e65100;color:#fff;border:none;border-radius:6px;cursor:pointer;font-size:13px" id="btn-edit-consulta">✏️ Editar (senha)</button>
|
|
|
|
|
<button onclick="window.salvarEdicaoConsulta()" style="flex:1;padding:8px;background:#2e7d32;color:#fff;border:none;border-radius:6px;cursor:pointer;font-size:13px;display:none" id="btn-salvar-consulta">💾 Salvar</button>
|
|
|
|
|
</div>
|
|
|
|
|
</div>
|
|
|
|
|
`;
|
|
|
|
|
|
|
|
|
|
document.body.appendChild(overlay);
|
|
|
|
|
window._editMode = false;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Fecha o modal de relatório
|
|
|
|
|
function closeRelatorioModal() {
|
|
|
|
|
const m = document.getElementById('modal-relatorio');
|
|
|
|
|
if (m) document.body.removeChild(m);
|
|
|
|
|
window._currentConsulta = null;
|
|
|
|
|
window._editMode = false;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Toggle modo de edição — pede senha admin
|
|
|
|
|
window.toggleEditConsulta = async function() {
|
|
|
|
|
if (window._editMode) {
|
|
|
|
|
// Cancela edição
|
|
|
|
|
window._editMode = false;
|
|
|
|
|
document.getElementById('edit-section').style.display = 'none';
|
|
|
|
|
document.getElementById('btn-salvar-consulta').style.display = 'none';
|
|
|
|
|
document.getElementById('btn-edit-consulta').textContent = '✏️ Editar (senha)';
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const pw = config.admin_password;
|
|
|
|
|
let ok = true;
|
|
|
|
|
if (pw) {
|
|
|
|
|
const input = prompt('🔐 Digite a senha admin para editar este registro:');
|
|
|
|
|
if (input !== pw) {
|
|
|
|
|
alert('Senha incorreta. Acesso negado.');
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
ok = (input === pw);
|
|
|
|
|
if (!ok) { alert('Senha incorreta.'); return; }
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
window._editMode = true;
|
|
|
|
|
document.getElementById('edit-section').style.display = 'block';
|
|
|
|
|
document.getElementById('btn-salvar-consulta').style.display = 'block';
|
|
|
|
|
document.getElementById('btn-edit-consulta').textContent = '✕ Cancelar';
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
// Salva edições de volta ao Supabase
|
|
|
|
|
window.salvarEdicaoConsulta = async function() {
|
|
|
|
|
const full = window._currentConsulta;
|
|
|
|
|
if (!full) return;
|
|
|
|
|
|
|
|
|
|
const newEsperado = parseNum(document.getElementById('edit-esperado').value);
|
|
|
|
|
const newObs = document.getElementById('edit-obs').value;
|
|
|
|
|
|
|
|
|
|
const updates = {
|
|
|
|
|
saldo_esperado: newEsperado,
|
|
|
|
|
observacoes: newObs
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
const hasTauri = !!(window.__TAURI__ && window.__TAURI__.core);
|
|
|
|
|
if (!hasTauri) { alert('Tauri não disponível.'); return; }
|
|
|
|
|
|
|
|
|
|
try {
|
|
|
|
|
// Primeiro tenta buscar por id (retorna registro completo)
|
|
|
|
|
let full = null;
|
|
|
|
|
if (item.id) {
|
|
|
|
|
try { full = await window.__TAURI__.core.invoke('sb_buscar_por_id', { id: item.id }); } catch(e) {}
|
|
|
|
|
}
|
|
|
|
|
// Fallback: buscar por uuid
|
|
|
|
|
if (!full && item.uuid) {
|
|
|
|
|
try { full = await window.__TAURI__.core.invoke('sb_buscar_por_uuid', { uuid: item.uuid }); } catch(e) {}
|
|
|
|
|
}
|
|
|
|
|
// Último fallback: carregar por loja+data
|
|
|
|
|
if (!full) {
|
|
|
|
|
const loja = val('f-loja') || 'União';
|
|
|
|
|
full = await window.__TAURI__.core.invoke('sb_carregar_rascunho', { loja, data: item.data });
|
|
|
|
|
let uuid = full.uuid;
|
|
|
|
|
if (!uuid && full.id_fechamento) {
|
|
|
|
|
// Buscar uuid pelo id_fechamento primeiro
|
|
|
|
|
const found = await window.__TAURI__.core.invoke('sb_buscar_por_id_fechamento', { id_fechamento: full.id_fechamento });
|
|
|
|
|
if (found && found.uuid) uuid = found.uuid;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (!full) { alert('Registro não encontrado.'); return; }
|
|
|
|
|
if (!uuid) { alert('UUID do registro não encontrado. Não é possível atualizar.'); return; }
|
|
|
|
|
|
|
|
|
|
// Aplica dados ao estado
|
|
|
|
|
if (full.data) { setVal('f-data', full.data); estado.data = full.data; }
|
|
|
|
|
if (full.operador) { setVal('f-operador', full.operador); estado.operador = full.operador; }
|
|
|
|
|
if (full.turno) { setVal('f-turno', full.turno); estado.turno = full.turno; }
|
|
|
|
|
if (full.saldo_troco != null) setVal('sys-troco', fmtNum(full.saldo_troco));
|
|
|
|
|
if (full.saldo_esperado != null) setVal('f-saldo-esperado', fmtNum(full.saldo_esperado));
|
|
|
|
|
if (full.observacoes) { setVal('f-obs', full.observacoes); estado.observacoes = full.observacoes; }
|
|
|
|
|
|
|
|
|
|
// Tenta carregar campos aninhados do campo "dados" (jsonb)
|
|
|
|
|
const dados = full.dados || full;
|
|
|
|
|
if (dados.despesas && Array.isArray(dados.despesas)) {
|
|
|
|
|
estado.despesas = dados.despesas.map(d => ({ desc: d.desc||d.descricao||'', obs: d.obs||'', valor: parseNum(d.valor)||0 }));
|
|
|
|
|
}
|
|
|
|
|
if (dados.sangrias && Array.isArray(dados.sangrias)) {
|
|
|
|
|
estado.sangrias = dados.sangrias.map(s => ({ hora: s.hora||'', retirada: parseNum(s.retirada)||0, gerente: s.gerente||'' }));
|
|
|
|
|
}
|
|
|
|
|
if (dados.pixcnpj && Array.isArray(dados.pixcnpj)) {
|
|
|
|
|
estado.pixcnpj = dados.pixcnpj.map(p => ({ nome: p.nome||'', valor: parseNum(p.valor)||0 }));
|
|
|
|
|
}
|
|
|
|
|
if (dados.vales && Array.isArray(dados.vales)) {
|
|
|
|
|
estado.vales = dados.vales.map(v => ({ nome: v.nome||'', obs: v.obs||'', valor: parseNum(v.valor)||0 }));
|
|
|
|
|
}
|
|
|
|
|
if (dados.receber && Array.isArray(dados.receber)) {
|
|
|
|
|
estado.receber = dados.receber.map(r => ({ nome: r.nome||'', valor: parseNum(r.valor)||0 }));
|
|
|
|
|
}
|
|
|
|
|
if (dados.cancelamentos && Array.isArray(dados.cancelamentos)) {
|
|
|
|
|
estado.cancelamentos = dados.cancelamentos.map(c => ({ numero: c.numero||'', valor: parseNum(c.valor)||0, motivo: c.motivo||'' }));
|
|
|
|
|
}
|
|
|
|
|
if (dados.cartoes) {
|
|
|
|
|
const norm = arr => Array.isArray(arr) ? arr.map(v => ({ valor: (typeof v === 'object') ? (parseNum(v.valor)||0) : (parseNum(v)||0) })) : [];
|
|
|
|
|
estado.cartoes.credito = norm(dados.cartoes.credito);
|
|
|
|
|
estado.cartoes.debito = norm(dados.cartoes.debito);
|
|
|
|
|
estado.cartoes.alimentacao = norm(dados.cartoes.alimentacao);
|
|
|
|
|
estado.cartoes.pix = norm(dados.cartoes.pix);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Marca como modo de edição — ao clicar Enviar vai fazer PATCH, não POST
|
|
|
|
|
estado.uuid = full.uuid || item.uuid || estado.uuid;
|
|
|
|
|
estado.id_local = full.id || item.id || null;
|
|
|
|
|
estado.sync_status = 'editing'; // flag: editar registro existente
|
|
|
|
|
|
|
|
|
|
PRE_FILL_TABLES.forEach(ensureOneRow);
|
|
|
|
|
Object.keys(TABLES).forEach(renderTable);
|
|
|
|
|
updateTotals();
|
|
|
|
|
syncUI();
|
|
|
|
|
scheduleSave();
|
|
|
|
|
|
|
|
|
|
alert(`✅ Registro carregado!\n\n📅 ${item.data}\n👤 ${item.operador||'?'} — ${item.turno||'?'}\n\nAo clicar "Enviar Fechamento", o registro será ATUALIZADO no Supabase (não criado novamente).`);
|
|
|
|
|
await window.__TAURI__.core.invoke('sb_atualizar_fechamento', { uuid, updates });
|
|
|
|
|
alert('✅ Atualizado com sucesso!');
|
|
|
|
|
closeRelatorioModal();
|
|
|
|
|
} catch(e) {
|
|
|
|
|
console.error('Erro ao carregar registro:', e);
|
|
|
|
|
alert('Erro ao carregar registro: ' + (e?.message || e));
|
|
|
|
|
console.error('Erro ao salvar:', e);
|
|
|
|
|
alert('Erro ao salvar: ' + (e?.message || e));
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
// Imprime o relatório (abre janela de impressão do navegador)
|
|
|
|
|
window.printRelatorio = function() {
|
|
|
|
|
const inner = document.getElementById('relatorio-inner');
|
|
|
|
|
if (!inner) return;
|
|
|
|
|
const Win = window.open('', '', 'width=600,height=700');
|
|
|
|
|
Win.document.write(`<html><head><title>Relatorio Fechamento</title><style>
|
|
|
|
|
body{font-family:monospace;font-size:13px;padding:10px;margin:0;width:280px}
|
|
|
|
|
.header{text-align:center;border-bottom:1px dashed #000;padding-bottom:5px;margin-bottom:5px}
|
|
|
|
|
.section{border:1px solid #000;margin-bottom:8px}
|
|
|
|
|
.section-title{background:#000;color:#fff;padding:2px 5px;font-size:11px}
|
|
|
|
|
.row{display:flex;justify-content:space-between;padding:2px 5px}
|
|
|
|
|
.total{border-top:1px solid #000;margin-top:2px;padding:2px 5px;font-weight:bold}
|
|
|
|
|
.result{text-align:center;padding:4px;font-weight:bold}
|
|
|
|
|
button{display:none}
|
|
|
|
|
</style></head><body>${inner.innerHTML}</body></html>`);
|
|
|
|
|
Win.document.close();
|
|
|
|
|
Win.focus();
|
|
|
|
|
setTimeout(() => { Win.print(); Win.close(); }, 500);
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
// Intercepta o envio — se sync_status=editing, faz PATCH
|
|
|
|
|
const _originalBtnEnviarHandler = () => {
|
|
|
|
|
const operador = val('f-operador').trim();
|
|
|
|
|