Compare commits

..

6 Commits

Author SHA1 Message Date
root d77ad55fbd feat: modal consulta com busca (data/operador/turno) + filtro 2 dias + data-item nos tr
Build Fechamento de Caixa / build (macos-14, app) (push) Has been cancelled
Build Fechamento de Caixa / build (ubuntu-22.04, deb) (push) Has been cancelled
Build Fechamento de Caixa / build (windows-2022, msi) (push) Has been cancelled
2026-07-01 19:57:37 +00:00
root 4a5cae8f2f fix: enviar diferenca e total_cartao_pix no PATCH do Supabase
Build Fechamento de Caixa / build (macos-14, app) (push) Has been cancelled
Build Fechamento de Caixa / build (ubuntu-22.04, deb) (push) Has been cancelled
Build Fechamento de Caixa / build (windows-2022, msi) (push) Has been cancelled
2026-07-01 17:58:01 +00:00
root 313c740470 fix: buildReciboData lê do estado quando DOM vazio (registro anterior) + totaisInfo calcula dos dados reais no modal de edição
Build Fechamento de Caixa / build (macos-14, app) (push) Has been cancelled
Build Fechamento de Caixa / build (ubuntu-22.04, deb) (push) Has been cancelled
Build Fechamento de Caixa / build (windows-2022, msi) (push) Has been cancelled
2026-07-01 16:21:29 +00:00
root d21cb0a98d fix: tabela consulta saldo completo (pixcartão incluído) + preencher formulário principal ao abrir registro anterior
Build Fechamento de Caixa / build (macos-14, app) (push) Has been cancelled
Build Fechamento de Caixa / build (ubuntu-22.04, deb) (push) Has been cancelled
Build Fechamento de Caixa / build (windows-2022, msi) (push) Has been cancelled
2026-07-01 15:52:27 +00:00
root 16bee1eacb fix: estado alimentado ao abrir registro anterior (buildReciboData correto) + coluna SALDO CAIXA na tabela de consulta
Build Fechamento de Caixa / build (macos-14, app) (push) Has been cancelled
Build Fechamento de Caixa / build (ubuntu-22.04, deb) (push) Has been cancelled
Build Fechamento de Caixa / build (windows-2022, msi) (push) Has been cancelled
2026-07-01 15:38:57 +00:00
root c8016f076d fix: dados merge completo (fc,fd,fr,fechamento,saldo_troco,total_*,obs) + fechamento_dinheiro/cartoes/areceber no PATCH
Build Fechamento de Caixa / build (macos-14, app) (push) Has been cancelled
Build Fechamento de Caixa / build (ubuntu-22.04, deb) (push) Has been cancelled
Build Fechamento de Caixa / build (windows-2022, msi) (push) Has been cancelled
2026-07-01 15:25:11 +00:00
+377 -53
View File
@@ -1871,12 +1871,31 @@ function buildReciboData() {
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 fechamentoCounted = parseNum(val('f-fech-dinheiro')) + parseNum(val('f-fech-cartoes')) + parseNum(val('f-fech-receber'));
const saldoEsp = parseNum(val('f-saldo-esperado'));
// 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;
// Lê do DOM (campos do formulário principal — preenchidos pelo updateTotals após edição)
// Fallback: se DOM vazio, usa estado (registro anterior carregado mas updateTotals ainda não chamou)
const trocoDom = parseNum(val('sys-troco'));
const saldoTroco = trocoDom || estado.saldo_troco || 0;
// Os campos readonly sys-credito/sys-debito etc. só têm valor se updateTotals foi chamado
// — em edição sem confirmação, ficam vazios e,我们必须 usar cartDeb etc. do estado
const saldoCred = parseNum(val('sys-credito')) || cartCred;
const saldoDeb = parseNum(val('sys-debito')) || cartDeb;
const saldoAli = parseNum(val('sys-alimentacao')) || cartAli;
const saldoPixCartao = parseNum(val('sys-pix')) || cartPix;
const saldoPixCnpj = parseNum(val('sys-pixcnpj')) || pixCnpjTotal;
const saldoVales = parseNum(val('sys-vales')) || valesTotal;
const saldoReceber = parseNum(val('sys-receber')) || receberTotal;
const fechamentoDinheiro = parseNum(val('f-fech-dinheiro')) || estado.fechamento_contado?.dinheiro || 0;
const fechamentoCartoes = parseNum(val('f-fech-cartoes')) || estado.fechamento_contado?.cartoes || 0;
const fechamentoReceber = parseNum(val('f-fech-receber')) || estado.fechamento_contado?.receber || 0;
const fechamentoCounted = fechamentoDinheiro + fechamentoCartoes + fechamentoReceber;
const saldoEsperado = parseNum(val('f-saldo-esperado')) || estado.saldo_esperado || 0;
// Saldo de Caixa (Sistema) = troco + crédito + débito + alimentação + pix cartão + pixcnpj + vales + receber
const sysTotal = saldoTroco + cartCred + cartDeb + cartAli + cartPix + pixCnpjTotal + valesTotal + receberTotal;
// Diferença = saldo de caixa (sistema) - saldo_esperado - cancelamentos
const diferenca = sysTotal - saldoEsp - cancelTotal;
const diferenca = sysTotal - saldoEsperado - cancelTotal;
return {
uuid: estado.uuid,
id_local: estado.id_local,
@@ -1885,14 +1904,14 @@ function buildReciboData() {
data: estado.data,
operador: estado.operador,
turno: estado.turno,
saldo_troco: parseNum(val('sys-troco')),
saldo_esperado: saldoEsp,
saldo_troco: saldoTroco,
saldo_esperado: saldoEsperado,
fechamento: fechamentoCounted,
diferenca: diferenca,
sys_total: sysTotal,
fechamento_dinheiro: parseNum(val('f-fech-dinheiro')),
fechamento_cartoes: parseNum(val('f-fech-cartoes')),
fechamento_receber: parseNum(val('f-fech-receber')),
fechamento_dinheiro: fechamentoDinheiro,
fechamento_cartoes: fechamentoCartoes,
fechamento_receber: fechamentoReceber,
// Flat totals for ReciboData struct (Rust) — must be numbers
credito: cartCred,
debito: cartDeb,
@@ -2164,12 +2183,19 @@ function buildConsultaModal(recentList) {
};
const rows = recentList.map((item, i) => {
const total = (parseFloat(item.fechamento_dinheiro)||0) + (parseFloat(item.fechamento_cartoes)||0) + (parseFloat(item.fechamento_areceber)||0);
const sysTotal = (parseFloat(item.saldo_troco)||0)
+ (parseFloat(item.saldo_credito)||0)
+ (parseFloat(item.saldo_debito)||0)
+ (parseFloat(item.saldo_alimentacao)||0)
+ (parseFloat(item.saldo_vales)||0)
+ (parseFloat(item.saldo_areceber)||0)
+ (parseFloat(item.total_pixcnpj)||0)
+ (parseFloat(item.total_cartao_pix)||0);
return `<tr>
<td style="padding:6px 8px;border-bottom:1px solid #eee;font-size:12px;cursor:pointer" onclick="openConsultaRegistro(${i})">${fmtDate(item.data)}</td>
<td style="padding:6px 8px;border-bottom:1px solid #eee;font-size:12px;cursor:pointer" onclick="openConsultaRegistro(${i})">${item.operador||'?'}</td>
<td style="padding:6px 8px;border-bottom:1px solid #eee;font-size:12px;cursor:pointer" onclick="openConsultaRegistro(${i})">${item.turno||'?'}</td>
<td style="padding:6px 8px;border-bottom:1px solid #eee;font-size:12px;text-align:right;cursor:pointer" onclick="openConsultaRegistro(${i})">${fmtMoney(total)}</td>
<td style="padding:6px 8px;border-bottom:1px solid #eee;font-size:12px;text-align:right;cursor:pointer" onclick="openConsultaRegistro(${i})">${fmtMoney(sysTotal)}</td>
<td style="padding:6px 8px;border-bottom:1px solid #eee;font-size:12px;text-align:right;cursor:pointer" onclick="openConsultaRegistro(${i})">${fmtMoney(item.saldo_esperado)}</td>
<td style="padding:6px 8px;border-bottom:1px solid #eee;font-size:12px;cursor:pointer" onclick="openConsultaRegistro(${i})">${statusBadge(item.status_diferenca)}</td>
<td style="padding:6px 8px;border-bottom:1px solid #eee;font-size:12px;cursor:pointer" onclick="openConsultaRegistro(${i})">${syncBadge(item.sync_status)}</td>
@@ -2180,32 +2206,130 @@ function buildConsultaModal(recentList) {
}).join('');
overlay.innerHTML = `
<div style="background:#fff;border-radius:10px;padding:20px;max-width:780px;width:95%;max-height:85vh;overflow-y:auto">
<div style="background:#fff;border-radius:10px;padding:20px;max-width:900px;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">📅 Consultar Fechamentos Anteriores</h2>
<h2 style="margin:0;font-size:16px">📅 Consultar Fechamentos</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 ver o relatório ou clique em <strong>Editar</strong> para abrir a janela de edição.</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: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>
<th style="padding:6px 8px;text-align:center;font-size:11px;color:#888">AÇÃO</th>
</tr>
</thead>
<tbody>${rows}</tbody>
</table>
</div>
`;
<div style="display:flex;gap:8px;margin-bottom:12px;align-items:center">
<input id="consulta-search" type="text" placeholder="🔍 Buscar por data, operador ou turno..." style="flex:1;padding:8px 12px;border:1px solid #ccc;border-radius:6px;font-size:13px" />
<select id="consulta-turno" style="padding:8px 12px;border:1px solid #ccc;border-radius:6px;font-size:13px;background:#fff">
<option value="">Todos turnos</option>
<option value="manha">Manhã</option>
<option value="tarde">Tarde</option>
<option value="integral">Integral</option>
</select>
</div>
<div id="consulta-count" style="font-size:11px;color:#888;margin-bottom:6px"></div>
<div style="max-height:60vh;overflow-y:auto;border:1px solid #eee;border-radius:6px">
<table style="width:100%;border-collapse:collapse">
<thead style="position:sticky;top:0;background:#f5f5f5;z-index:1">
<tr>
<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:right;font-size:11px;color:#888">SALDO CAIXA</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:4px 6px;text-align:center;font-size:11px;color:#888">AÇÃO</th>
</tr>
</thead>
<tbody id="consulta-tbody"></tbody>
</table>
</div>
</div>`;
// Store original list for filtering
window._consultaList = recentList;
window._consultaAll = recentList;
window._recentList = recentList; // keep for legacy openConsultaRegistro(idx)
const fmtDate = d => {
if (!d) return '';
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 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 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>`;
};
function renderConsultaRows(list) {
const tbody = document.getElementById('consulta-tbody');
if (!list || list.length === 0) {
tbody.innerHTML = `<tr><td colspan="7" style="padding:20px;text-align:center;color:#888;font-size:13px">Nenhum fechamento encontrado.</td></tr>`;
document.getElementById('consulta-count').textContent = '0 registros';
return;
}
const count = document.getElementById('consulta-count');
if (count) count.textContent = `${list.length} registro${list.length !== 1 ? 's' : ''}`;
tbody.innerHTML = list.map((item, i) => {
const sysTotal = (parseFloat(item.saldo_troco)||0)
+ (parseFloat(item.saldo_credito)||0)
+ (parseFloat(item.saldo_debito)||0)
+ (parseFloat(item.saldo_alimentacao)||0)
+ (parseFloat(item.saldo_vales)||0)
+ (parseFloat(item.saldo_areceber)||0)
+ (parseFloat(item.total_pixcnpj)||0)
+ (parseFloat(item.total_cartao_pix)||0);
return `<tr data-item='${JSON.stringify(item).replace(/'/g,"&#39;")}' style="background:${i%2===0?'#fff':'#fafafa'}" onmouseover="this.style.background='#fff3e0'" onmouseout="this.style.background='${i%2===0?'#fff':'#fafafa'}'">
<td style="padding:6px 8px;border-bottom:1px solid #eee;font-size:12px;cursor:pointer" onclick="window.openConsultaRegistroByItem(this.parentElement)">${fmtDate(item.data)}</td>
<td style="padding:6px 8px;border-bottom:1px solid #eee;font-size:12px;cursor:pointer" onclick="window.openConsultaRegistroByItem(this.parentElement)">${item.operador||'?'}</td>
<td style="padding:6px 8px;border-bottom:1px solid #eee;font-size:12px;cursor:pointer" onclick="window.openConsultaRegistroByItem(this.parentElement)">${item.turno||'?'}</td>
<td style="padding:6px 8px;border-bottom:1px solid #eee;font-size:12px;text-align:right;cursor:pointer" onclick="window.openConsultaRegistroByItem(this.parentElement)">${fmtMoney(sysTotal)}</td>
<td style="padding:6px 8px;border-bottom:1px solid #eee;font-size:12px;text-align:right;cursor:pointer" onclick="window.openConsultaRegistroByItem(this.parentElement)">${fmtMoney(item.saldo_esperado)}</td>
<td style="padding:6px 8px;border-bottom:1px solid #eee;font-size:12px;text-align:center;cursor:pointer" onclick="window.openConsultaRegistroByItem(this.parentElement)">${statusBadge(item.status_diferenca)}</td>
<td style="padding:4px 6px;border-bottom:1px solid #eee;text-align:center">
<button onclick="event.stopPropagation();window.abrirEditaFechamentoByItem(this.closest('tr'))" style="background:#e65100;color:#fff;border:none;border-radius:4px;padding:4px 10px;cursor:pointer;font-size:11px;white-space:nowrap">✏️ Editar</button>
</td>
</tr>`;
}).join('');
}
// Initial: filter to last 2 days
const today = new Date();
const cutoff = new Date(today);
cutoff.setDate(today.getDate() - 2);
const cutoffStr = cutoff.toISOString().split('T')[0];
const twoDays = recentList.filter(item => item.data >= cutoffStr);
renderConsultaRows(twoDays);
window._consultaFiltered = twoDays;
// Search handler — filters by data, operador, or turno
document.getElementById('consulta-search').addEventListener('input', e => {
const q = e.target.value.toLowerCase().trim();
const turno = (document.getElementById('consulta-turno')?.value || '').toLowerCase();
const filtered = recentList.filter(item => {
const matchQ = !q || (item.data||'').includes(q) || (item.operador||'').toLowerCase().includes(q) || (item.turno||'').toLowerCase().includes(q);
const matchTurno = !turno || (item.turno||'').toLowerCase() === turno;
return matchQ && matchTurno;
});
renderConsultaRows(filtered);
window._consultaFiltered = filtered;
});
document.getElementById('consulta-turno').addEventListener('change', e => {
const q = (document.getElementById('consulta-search')?.value || '').toLowerCase().trim();
const turno = e.target.value.toLowerCase();
const filtered = recentList.filter(item => {
const matchQ = !q || (item.data||'').includes(q) || (item.operador||'').toLowerCase().includes(q) || (item.turno||'').toLowerCase().includes(q);
const matchTurno = !turno || (item.turno||'').toLowerCase() === turno;
return matchQ && matchTurno;
});
renderConsultaRows(filtered);
window._consultaFiltered = filtered;
});
document.body.appendChild(overlay);
window._recentList = recentList;
overlay.addEventListener('click', e => { if (e.target === overlay) closeConsultaModal(); });
}
// Abre a janela de edição completa de um registro pelo índice na lista
@@ -2249,6 +2373,79 @@ function closeConsultaModal() {
window._currentConsulta = null;
}
// Abre o relatório pelo elemento <tr> (evita dependência de índice)
window.openConsultaRegistroByItem = async function(tr) {
const dataAttr = tr ? tr.dataset.item : null;
let item = null;
if (dataAttr) {
try { item = JSON.parse(dataAttr); } catch(e) {}
}
if (!item) {
// Fallback: busca pelo texto da primeira célula (data)
const dataText = tr.cells[0]?.textContent?.trim();
if (dataText) {
const [d,m,y] = dataText.split('/');
const dataKey = `${y}-${m}-${d}`;
item = window._consultaAll?.find(it => it.data === dataKey);
}
}
if (!item) { alert('Registro não encontrado.'); return; }
closeConsultaModal();
const hasTauri = !!(window.__TAURI__ && window.__TAURI__.core);
if (!hasTauri) { alert('Tauri não disponível.'); return; }
let full = null;
try {
if (item.id) { try { full = await window.__TAURI__.core.invoke('sb_buscar_por_id', { id: item.id }); } catch(e) {} }
if (!full && 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', { idFechamento: item.id_fechamento }); } catch(e) {} }
} catch(e) { console.warn('Erro buscando registro:', e); }
if (!full) { alert('Registro não encontrado.'); return; }
window._currentConsulta = full;
buildRelatorioModal(full);
};
// Abre a edição pelo elemento <tr> (evita dependência de índice)
window.abrirEditaFechamentoByItem = async function(tr) {
const dataAttr = tr ? tr.dataset.item : null;
let item = null;
if (dataAttr) {
try { item = JSON.parse(dataAttr); } catch(e) {}
}
if (!item) {
const dataText = tr.cells[0]?.textContent?.trim();
if (dataText) {
const [d,m,y] = dataText.split('/');
const dataKey = `${y}-${m}-${d}`;
item = window._consultaAll?.find(it => it.data === dataKey);
}
}
if (!item) { alert('Registro não encontrado.'); return; }
const hasTauri = !!(window.__TAURI__ && window.__TAURI__.core);
if (!hasTauri) { alert('Tauri não disponível.'); return; }
let full = null;
try {
if (item.id) { try { full = await window.__TAURI__.core.invoke('sb_buscar_por_id', { id: item.id }); } catch(e) {} }
if (!full && 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', { idFechamento: item.id_fechamento }); } catch(e) {} }
} catch(e) { console.warn('Erro buscando registro:', e); }
if (!full) { alert('Registro não encontrado.'); return; }
window._currentConsulta = full;
closeConsultaModal();
closeRelatorioModal();
const pw = localStorage.getItem('admin_pw') || '1234';
const granted = await askPassword(pw);
if (!granted) return;
openEditModal(full);
};
// Abre o relatório de um registro selecionado
window.openConsultaRegistro = async function(idx) {
const item = window._recentList[idx];
@@ -2755,20 +2952,32 @@ function openEditModal(full) {
const receber_rows = (dados.receber || []).map(r => [r.nome||'', r.valor||0]);
const receberHTML = editTableHTML('receber', ['Nome', 'Valor (R$)'], receber_rows.length ? receber_rows : [['','']], [1]);
// --- Totais (só leitura formatado) ---
const totaisInfo = `
// --- Totais (só leitura formatado) — calcula dos dados reais ---
const totaisInfo = (() => {
const calcCred = (dados.cartoes?.credito || full.cartoes_credito || []).reduce((s,r) => s+(parseFloat(typeof r==='object'?r.valor:r)||0), 0);
const calcDeb = (dados.cartoes?.debito || full.cartoes_debito || []).reduce((s,r) => s+(parseFloat(typeof r==='object'?r.valor:r)||0), 0);
const calcAli = (dados.cartoes?.alimentacao || full.cartoes_alimentacao || []).reduce((s,r) => s+(parseFloat(typeof r==='object'?r.valor:r)||0), 0);
const calcPix = (dados.cartoes?.pix || full.cartoes_pix || []).reduce((s,r) => s+(parseFloat(typeof r==='object'?r.valor:r)||0), 0);
const calcSang = (dados.sangrias || []).reduce((s,r) => s+(parseFloat(r.retirada||r.valor||0)||0), 0);
const calcDesp = (dados.despesas || []).reduce((s,r) => s+(parseFloat(r.valor||0)||0), 0);
const calcVales = (dados.vales || []).reduce((s,r) => s+(parseFloat(r.valor||0)||0), 0);
const calcPixCnpj = (dados.pixcnpj || []).reduce((s,r) => s+(parseFloat(r.valor||0)||0), 0);
const calcRecv = (dados.receber || []).reduce((s,r) => s+(parseFloat(r.valor||0)||0), 0);
const calcCanc = (dados.cancelamentos || []).reduce((s,r) => s+(parseFloat(r.valor||0)||0), 0);
return `
<div style="display:grid;grid-template-columns:1fr 1fr 1fr 1fr;gap:4px;background:#f5f5f5;border-radius:6px;padding:8px;margin-bottom:8px;font-size:11px">
<div><strong>Total Crédito:</strong> <span id="edit-total-credito">${fmtMR(full.total_cartao_credito||0)}</span></div>
<div><strong>Total Débito:</strong> <span id="edit-total-debito">${fmtMR(full.total_cartao_debito||0)}</span></div>
<div><strong>Total Alimentação:</strong> <span id="edit-total-alimentacao">${fmtMR(full.total_cartao_alimentacao||0)}</span></div>
<div><strong>Total PIX:</strong> <span id="edit-total-pix">${fmtMR(full.total_cartao_pix||0)}</span></div>
<div><strong>Total Sangrias:</strong> <span id="edit-total-sangrias">${fmtMR(full.total_sangrias||0)}</span></div>
<div><strong>Total Despesas:</strong> <span id="edit-total-despesas">${fmtMR(full.total_despesas||0)}</span></div>
<div><strong>Total Vales:</strong> <span id="edit-total-vales">${fmtMR(full.total_vales||0)}</span></div>
<div><strong>Total PIX CNPJ:</strong> <span id="edit-total-pixcnpj">${fmtMR(full.total_pixcnpj||0)}</span></div>
<div><strong>Total Receber:</strong> <span id="edit-total-receber">${fmtMR(full.total_areceber||0)}</span></div>
<div><strong>Total Cancel:</strong> <span id="edit-total-cancel">${fmtMR(full.total_cancelamentos||0)}</span></div>
<div><strong>Total Crédito:</strong> <span id="edit-total-credito">${fmtMR(calcCred)}</span></div>
<div><strong>Total Débito:</strong> <span id="edit-total-debito">${fmtMR(calcDeb)}</span></div>
<div><strong>Total Alimentação:</strong> <span id="edit-total-alimentacao">${fmtMR(calcAli)}</span></div>
<div><strong>Total PIX:</strong> <span id="edit-total-pix">${fmtMR(calcPix)}</span></div>
<div><strong>Total Sangrias:</strong> <span id="edit-total-sangrias">${fmtMR(calcSang)}</span></div>
<div><strong>Total Despesas:</strong> <span id="edit-total-despesas">${fmtMR(calcDesp)}</span></div>
<div><strong>Total Vales:</strong> <span id="edit-total-vales">${fmtMR(calcVales)}</span></div>
<div><strong>Total PIX CNPJ:</strong> <span id="edit-total-pixcnpj">${fmtMR(calcPixCnpj)}</span></div>
<div><strong>Total Receber:</strong> <span id="edit-total-receber">${fmtMR(calcRecv)}</span></div>
<div><strong>Total Cancel:</strong> <span id="edit-total-cancel">${fmtMR(calcCanc)}</span></div>
</div>`;
})();
const overlay = document.createElement('div');
overlay.id = 'modal-edit';
@@ -2959,6 +3168,81 @@ window.abrirEditaFechamento = async function(full) {
if (!full.id_fechamento && full.loja && full.data && full.operador) {
full.id_fechamento = (full.loja + '_' + full.data + '_' + full.operador).toLowerCase().replace(/ /g, '_');
}
// Atualiza estado com o registro carregado para que buildReciboData funcione corretamente
const dados = full.dados || {};
estado = {
uuid: full.uuid || crypto.randomUUID ? crypto.randomUUID() : Date.now().toString(),
id_local: full.id_local || null,
id: full.id || null,
loja: full.loja || estado.loja,
data: full.data || estado.data,
operador: full.operador || '',
turno: full.turno || 'manha',
saldo_troco: parseNum(full.saldo_troco || 0),
fechamento: parseNum(full.fechamento_dinheiro || 0) + parseNum(full.fechamento_cartoes || 0) + parseNum(full.fechamento_areceber || 0),
saldo_esperado: parseNum(full.saldo_esperado || 0),
diferenca: parseNum(full.diferenca || 0),
clientes: parseInt(full.clientes || 0),
frango: parseInt(full.frango || 0),
vendas: parseNum(full.vendas || 0),
observacoes: full.observacoes || '',
sync_status: full.sync_status || 'synced',
// Cartões
cartoes: {
credito: (dados.cartoes?.credito || full.cartoes_credito || []).map(v => ({ valor: parseNum(v) || 0 })),
debito: (dados.cartoes?.debito || full.cartoes_debito || []).map(v => ({ valor: parseNum(v) || 0 })),
alimentacao: (dados.cartoes?.alimentacao || full.cartoes_alimentacao || []).map(v => ({ valor: parseNum(v) || 0 })),
pix: (dados.cartoes?.pix || full.cartoes_pix || []).map(v => ({ valor: parseNum(v) || 0 })),
},
// Demais arrays
vales: (dados.vales || full.vales || []).map(r => ({ nome: r.nome||'', valor: parseNum(r.valor)||0, obs: r.obs||'' })),
despesas: (dados.despesas || full.despesas || []).map(r => ({ desc: r.desc||'', obs: r.obs||'', valor: parseNum(r.valor)||0 })),
sangrias: (dados.sangrias || full.sangrias || []).map(r => ({ hora: r.hora||'', retirada: parseNum(r.retirada||r.valor)||0, gerente: r.gerente||'' })),
cancelamentos: (dados.cancelamentos || full.cancelamentos || []).map(r => ({ numero: r.numero||'', valor: parseNum(r.valor)||0, motivo: r.motivo||'' })),
pixcnpj: (dados.pixcnpj || full.pixcnpj || []).map(r => ({ nome: r.nome||'', valor: parseNum(r.valor)||0 })),
receber: (dados.receber || full.receber || []).map(r => ({ nome: r.nome||'', valor: parseNum(r.valor)||0 })),
fechamento_contado: {
dinheiro: parseNum(full.fechamento_dinheiro || 0),
cartoes: parseNum(full.fechamento_cartoes || 0),
receber: parseNum(full.fechamento_areceber || 0),
},
};
// Preenche os campos do formulário principal para que o botão Recibo funcione
setVal('sys-troco', fmtNum(estado.saldo_troco));
setVal('sys-credito', fmtNum(estado.saldo_credito));
setVal('sys-debito', fmtNum(estado.saldo_debito));
setVal('sys-alimentacao', fmtNum(estado.saldo_alimentacao));
setVal('sys-pixcnpj', fmtNum(estado.total_pixcnpj));
setVal('f-saldo-esperado', estado.saldo_esperado || '');
setVal('f-obs', estado.observacoes || '');
setVal('f-operador', estado.operador || '');
setVal('f-turno', estado.turno || '');
setVal('f-clientes', estado.clientes || '');
setVal('f-frango', estado.frango || '');
setVal('f-vendas', estado.vendas || '');
setVal('f-loja', estado.loja || '');
setVal('f-data', estado.data || '');
setVal('f-fech-dinheiro', estado.fechamento_contado?.dinheiro || '');
setVal('f-fech-cartoes', estado.fechamento_contado?.cartoes || '');
setVal('f-fech-receber', estado.fechamento_contado?.receber || '');
// Renderiza todas as grades
renderTable('tbl-sangrias', estado.sangrias);
renderTable('tbl-despesas', estado.despesas);
renderTable('tbl-vales', estado.vales);
renderTable('tbl-pix', estado.pixcnpj);
renderTable('tbl-receber', estado.receber);
renderTable('tbl-cancelamentos', estado.cancelamentos);
renderTable('tbl-cartao-credito', estado.cartoes.credito);
renderTable('tbl-cartao-debito', estado.cartoes.debito);
renderTable('tbl-cartao-alimentacao',estado.cartoes.alimentacao);
renderTable('tbl-cartao-pix', estado.cartoes.pix);
// Atualiza totais
updateTotals();
// Usa o mesmo modal de edição completo que já funciona — só abre com o registro
openEditModal(full);
};
@@ -3043,26 +3327,66 @@ window.salvarEdicaoModal = async function() {
total_pixcnpj: pixcnpj_tot,
total_areceber: recv_tot,
total_cancelamentos: canc_tot,
total_cartao_pix: cartPix_tot,
// Diferença calculada
diferenca: p(inp('edit-troco')) + cartCred_tot + cartDeb_tot + cartAli_tot + cartPix_tot + pixcnpj_tot + vales_tot + recv_tot
- p(inp('edit-esperado')) - canc_tot,
// Fechamento (campos calculados que o formato antigo usava no dados)
fechamento_dinheiro: p(inp('edit-troco')) + vales_tot + sang_tot - desp_tot - canc_tot,
fechamento_cartoes: cartCred_tot + cartDeb_tot + cartAli_tot + cartPix_tot,
fechamento_areceber: recv_tot,
// Lançamentos detalhados (JSONB — gravados no campo `dados`)
// IMPORTANTE: não usar JSON.stringify — dados deve ser objeto, não string,
// para o Rust serializar corretamente como JSONB no Supabase.
// Se full.dados existe (string de stringify anterior), parsear de volta.
// Merge completo com dados existentes para preservar campos antigos (fc, fd, fr,
// uuid, id_local, sync_status, fechamento, etc.) e sobrepor com valores atuais.
dados: (() => {
const existing = full.dados;
const base = { cartoes, vales, despesas, sangrias, cancelamentos, pixcnpj, receber };
const counters = {
const base = {
cartoes,
vales,
despesas,
sangrias,
cancelamentos,
pixcnpj,
receber,
clientes: parseInt(inp('edit-clientes') || '0'),
frango: parseInt(inp('edit-frango') || '0'),
vendas: p(inp('edit-vendas')),
// Campos que o formato antigo gravava no dados
credito: cartCred_tot,
debito: cartDeb_tot,
alimentacao: cartAli_tot,
fc: cartCred_tot + cartDeb_tot + cartAli_tot + cartPix_tot,
fd: sang_tot,
fr: vales_tot,
fechamento: p(inp('edit-troco')) + vales_tot + sang_tot - desp_tot - canc_tot,
saldo_troco: p(inp('edit-troco')),
total_vales: vales_tot,
total_despesas: desp_tot,
total_sangrias: sang_tot,
total_pixcnpj: pixcnpj_tot,
total_areceber: recv_tot,
total_cancelamentos: canc_tot,
total_cartao_credito: cartCred_tot,
total_cartao_debito: cartDeb_tot,
total_cartao_alimentacao: cartAli_tot,
total_cartao_pix: cartPix_tot,
saldo_esperado: p(inp('edit-esperado')),
observacoes: inp('edit-obs') || '',
data: inp('edit-data') || full.data || '',
loja: inp('edit-loja') || full.loja || '',
turno: inp('edit-turno') || full.turno || '',
operador: inp('edit-operador') || full.operador || '',
};
if (typeof existing === 'string') {
try {
const parsed = JSON.parse(existing);
return { ...parsed, ...base, ...counters };
} catch { return { ...base, ...counters }; }
return { ...parsed, ...base };
} catch { return base; }
}
return { ...(existing || {}), ...base, ...counters };
return { ...(existing || {}), ...base };
})(),
// Contadores