Compare commits

...

11 Commits

Author SHA1 Message Date
root cb48afeb9c fix: abrirEditaFechamento usa modal openEditModal (Tauri context) em vez de popup sem Tauri; _recalcEditTotals atualiza ambos prefixes de IDs
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 12:45:30 +00:00
root 2b8ff711ed feat: window.abrirEditaFechamento(full) — abre janela separada para edição completa de fechamento
- Nova função window.abrirEditaFechamento(full) via window.open com HTML inline
  pré-preenchido com todos os campos do registro
- Botão Salvar chama sb_atualizar_fechamento com updates completos
- Botão Cancelar fecha a janela (window.close)
- Coluna 'Editar' adicionada à tabela de dias anteriores com botão ✏️
- Nova helper window.abrirEditaFechamentoIndex(idx) busca registro e abre popup
- Fluxo existente (relatório + modal de edição) mantido intacto
2026-07-01 12:26:34 +00:00
root 9a4ccabd1b fix: ler resposta real do PATCH e logar body enviado/recebido para debug
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 12:11:35 +00:00
root 32728eec37 fix: rename_all snake_case no comando sb_atualizar_fechamento (Tauri converte id_fechamento pra idFechamento na interface JS)
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 11:53:46 +00:00
root 905ca253d7 fix: PATCH usa id_fechamento (não id/uuid); inclui id_fechamento no updates; Rust sb_atualizar_fechamento usa id_fechamento como chave
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 01:46:01 +00:00
root d89b79a3f8 fix: _editingRecord preserves full object; dados.vales etc (not full.vales_arr)
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 01:32:11 +00:00
root c4dda7e2e5 debug: add console.log to salvarEdicaoModal to trace where it hangs
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 01:25:01 +00:00
root 662f3681a5 Revert "fix: fórmula diferença = sys_total - saldo_esperado - cancelamentos (todas as 3 functions de print); aumenta fonte print para 17px + ajustes de padding/margens"
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
This reverts commit a56d7188f2.
2026-06-30 22:26:52 +00:00
root a56d7188f2 fix: fórmula diferença = sys_total - saldo_esperado - cancelamentos (todas as 3 functions de print); aumenta fonte print para 17px + ajustes de padding/margens
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-06-30 22:03:12 +00:00
root 7e1ee6bc04 fix: diff=sysTotal-esperado; toggleEdit fecha relatorio; saldo=soma carts; print diff=sysTotal
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-06-30 20:54:02 +00:00
root 6a8881d41d fix: cartoes do dados JSONB no print; listar_recentes com dados; table-layout fixed; modal conf font 14px
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-06-30 20:00:07 +00:00
2 changed files with 151 additions and 66 deletions
+25 -18
View File
@@ -248,27 +248,37 @@ impl SupabaseClient {
} }
} }
/// Atualiza campos específicos de um fechamento pelo id numérico (pk) ou UUID. /// Atualiza campos específicos de um fechamento pelo id_fechamento.
pub fn atualizar_fechamento(&self, id: Option<i64>, uuid: &str, updates: &serde_json::Value) -> Result<Value, SupabaseError> { pub fn atualizar_fechamento(&self, id_fechamento: &str, updates: &serde_json::Value) -> Result<Value, SupabaseError> {
// Se temos id numerico, usa id=eq.; senao usa id=eq.UUID let url = format!(
let url = if let Some(num) = id { "{}/rest/v1/fechamentos_web?id_fechamento=eq.{}",
format!("{}/rest/v1/fechamentos_web?id=eq.{}", self.base_url, num) self.base_url,
} else { urlencoding::encode(id_fechamento)
format!("{}/rest/v1/fechamentos_web?id=eq.{}", self.base_url, uuid) );
};
// Log do que está sendo enviado (debug)
log::info!("[PATCH] url={} body={}", url, updates);
let resp = self let resp = self
.http .http
.patch(&url) .patch(&url)
.headers(self.headers(true)) .headers(self.headers(true))
.header("Prefer", "return=representation")
.json(updates) .json(updates)
.send()?; .send()?;
if resp.status().is_success() { let status = resp.status();
Ok(serde_json::json!({ "ok": true, "id": id.unwrap_or(0) })) if status.is_success() {
// Ler a resposta real do Supabase (retorna o registro atualizado)
if let Ok(ret) = resp.json::<serde_json::Value>() {
log::info!("[PATCH] sucesso — resposta: {}", ret);
} else {
log::warn!("[PATCH] sucesso mas não conseguiu ler resposta");
}
Ok(serde_json::json!({ "ok": true, "id_fechamento": id_fechamento }))
} else { } else {
let status = resp.status();
let body = resp.text().unwrap_or_default(); let body = resp.text().unwrap_or_default();
log::error!("[PATCH] HTTP {} body: {}", status.as_u16(), body);
Err(SupabaseError::Api(format!( Err(SupabaseError::Api(format!(
"HTTP {}: {}", "HTTP {}: {}",
status.as_u16(), status.as_u16(),
@@ -279,7 +289,7 @@ impl SupabaseClient {
pub fn listar_recentes(&self, loja: &str, limite: i64) -> Result<Vec<Value>, SupabaseError> { pub fn listar_recentes(&self, loja: &str, limite: i64) -> Result<Vec<Value>, SupabaseError> {
let loja_normalized = sem_acento(&loja.to_lowercase()); let loja_normalized = sem_acento(&loja.to_lowercase());
let url = format!( let url = format!(
"{}/rest/v1/fechamentos_web?loja=eq.{}&order=data.desc,atualizado_em.desc&limit={}&select=id,id_fechamento,data,operador,turno,saldo_troco,saldo_esperado,fechamento_dinheiro,fechamento_cartoes,fechamento_areceber,diferenca,status_diferenca,observacoes,atualizado_em", "{}/rest/v1/fechamentos_web?loja=eq.{}&order=data.desc,atualizado_em.desc&limit={}&select=id,id_fechamento,data,operador,turno,saldo_troco,saldo_esperado,fechamento_dinheiro,fechamento_cartoes,fechamento_areceber,diferenca,status_diferenca,observacoes,atualizado_em,dados",
self.base_url, self.base_url,
urlencoding::encode(&loja_normalized), urlencoding::encode(&loja_normalized),
limite, limite,
@@ -504,16 +514,13 @@ pub fn sb_buscar_por_id_fechamento(
sb.buscar_por_id_fechamento(&id_fechamento) sb.buscar_por_id_fechamento(&id_fechamento)
} }
#[tauri::command] #[tauri::command(rename_all = "snake_case")]
pub fn sb_atualizar_fechamento( pub fn sb_atualizar_fechamento(
sb: State<'_, SupabaseClient>, sb: State<'_, SupabaseClient>,
id: String, id_fechamento: String,
updates: serde_json::Value, updates: serde_json::Value,
) -> Result<serde_json::Value, SupabaseError> { ) -> Result<serde_json::Value, SupabaseError> {
// Tenta primeiro como i64 (id numerico), depois como String (UUID) sb.atualizar_fechamento(&id_fechamento, &updates)
let id_i64 = id.parse::<i64>().ok();
let id_str = &id;
sb.atualizar_fechamento(id_i64, id_str, &updates)
} }
#[tauri::command] #[tauri::command]
+126 -48
View File
@@ -564,7 +564,7 @@
<p style="font-size:13px;color:#444;margin-bottom:14px"> <p style="font-size:13px;color:#444;margin-bottom:14px">
Tem certeza que deseja <strong>enviar este fechamento e encerrar o caixa?</strong> Tem certeza que deseja <strong>enviar este fechamento e encerrar o caixa?</strong>
</p> </p>
<div id="confirm-summary" style="border:1px solid #b3d9f7;border-radius:8px;padding:12px;background:#f0f7ff;font-size:12px;font-family:monospace"> <div id="confirm-summary" style="border:1px solid #b3d9f7;border-radius:8px;padding:14px;background:#f0f7ff;font-size:14px;font-family:Arial,sans-serif;line-height:1.6">
</div> </div>
<p style="font-size:11px;color:#888;margin-top:10px"> <p style="font-size:11px;color:#888;margin-top:10px">
Após enviar, <strong>não dá pra editar este fechamento</strong> sem a senha do Filipe. Após enviar, <strong>não dá pra editar este fechamento</strong> sem a senha do Filipe.
@@ -1394,8 +1394,8 @@ function buildConfirmHTML(data) {
.section-title { font-weight: bold !important; font-size: 14px; border-top: 2px solid #000; padding-top: 4px; margin-top: 8px; } .section-title { font-weight: bold !important; font-size: 14px; border-top: 2px solid #000; padding-top: 4px; margin-top: 8px; }
.row { display: flex; justify-content: space-between; padding: 2px 0; font-size: 14px; font-weight: bold !important; } .row { display: flex; justify-content: space-between; padding: 2px 0; font-size: 14px; font-weight: bold !important; }
.row.total-row { font-weight: bold !important; } .row.total-row { font-weight: bold !important; }
.cart-table { width: 100%; border-collapse: collapse; font-size: 13px; margin-top: 4px; font-weight: bold !important; } .cart-table { table-layout: fixed; width: 100%; border-collapse: collapse; font-size: 13px; margin-top: 4px; font-weight: bold !important; }
.cart-table th { font-weight: bold !important; border-bottom: 2px solid #000; padding: 3px; font-size: 13px; } .cart-table th { font-weight: bold !important; border-bottom: 2px solid #000; padding: 3px; font-size: 13px; width: 25%; }
.cart-table td { padding: 3px 5px; text-align: right; font-weight: bold !important; font-size: 13px; } .cart-table td { padding: 3px 5px; text-align: right; font-weight: bold !important; font-size: 13px; }
.cart-table td:first-child { text-align: left; } .cart-table td:first-child { text-align: left; }
.cart-table tr.total-row { font-weight: bold !important; border-top: 2px solid #000; } .cart-table tr.total-row { font-weight: bold !important; border-top: 2px solid #000; }
@@ -1486,9 +1486,11 @@ ${data.observacoes ? `<div class="obs">${data.observacoes}</div>` : ''}
function buildPrintHTML(data) { function buildPrintHTML(data) {
const fmt = v => 'R$ ' + (v || 0).toFixed(2).replace('.', ','); const fmt = v => 'R$ ' + (v || 0).toFixed(2).replace('.', ',');
const fmtNeg = v => (v < 0 ? '-' : '') + 'R$ ' + Math.abs(v || 0).toFixed(2).replace('.', ','); const fmtNeg = v => (v < 0 ? '-' : '') + 'R$ ' + Math.abs(v || 0).toFixed(2).replace('.', ',');
// Diferença = fechamento - saldo_esperado - cancelamentos // Diferença = Total Sistema - Saldo Esperado - Cancelamentos
const diferenca = data.diferenca !== undefined ? data.diferenca const sysTotalCalc = (data.sysTotal || 0);
: ((data.fechamento || 0) - (data.saldo_esperado || 0) - (data.cancelamentos || 0)); const saldoEsperadoCalc = (data.saldo_esperado || 0);
const cancelamentosCalc = (data.cancelamentos || 0);
const diferenca = sysTotalCalc - saldoEsperadoCalc - cancelamentosCalc;
const diffStr = diferenca >= 0 ? `+${fmt(diferenca)}` : fmtNeg(diferenca); const diffStr = diferenca >= 0 ? `+${fmt(diferenca)}` : fmtNeg(diferenca);
const diffColor = diferenca === 0 ? '#2e7d32' : (diferenca > 0 ? '#e65100' : '#c0272d'); const diffColor = diferenca === 0 ? '#2e7d32' : (diferenca > 0 ? '#e65100' : '#c0272d');
@@ -1612,8 +1614,8 @@ function buildPrintHTML(data) {
.section-title { font-weight: bold !important; font-size: 14px; border-top: 2px solid #000; padding-top: 4px; margin-top: 8px; } .section-title { font-weight: bold !important; font-size: 14px; border-top: 2px solid #000; padding-top: 4px; margin-top: 8px; }
.row { display: flex; justify-content: space-between; padding: 2px 0; font-size: 14px; font-weight: bold !important; } .row { display: flex; justify-content: space-between; padding: 2px 0; font-size: 14px; font-weight: bold !important; }
.row.total-row { font-weight: bold !important; } .row.total-row { font-weight: bold !important; }
.cart-table { width: 100%; border-collapse: collapse; font-size: 13px; margin-top: 4px; font-weight: bold !important; } .cart-table { table-layout: fixed; width: 100%; border-collapse: collapse; font-size: 13px; margin-top: 4px; font-weight: bold !important; }
.cart-table th { font-weight: bold !important; border-bottom: 2px solid #000; padding: 3px; font-size: 13px; } .cart-table th { font-weight: bold !important; border-bottom: 2px solid #000; padding: 3px; font-size: 13px; width: 25%; }
.cart-table td { padding: 3px 5px; text-align: right; font-weight: bold !important; font-size: 13px; } .cart-table td { padding: 3px 5px; text-align: right; font-weight: bold !important; font-size: 13px; }
.cart-table td:first-child { text-align: left; } .cart-table td:first-child { text-align: left; }
.cart-table tr.total-row { font-weight: bold !important; border-top: 2px solid #000; } .cart-table tr.total-row { font-weight: bold !important; border-top: 2px solid #000; }
@@ -2163,24 +2165,27 @@ function buildConsultaModal(recentList) {
const rows = recentList.map((item, i) => { const rows = recentList.map((item, i) => {
const total = (parseFloat(item.fechamento_dinheiro)||0) + (parseFloat(item.fechamento_cartoes)||0) + (parseFloat(item.fechamento_areceber)||0); 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})"> return `<tr>
<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;cursor:pointer" onclick="openConsultaRegistro(${i})">${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;cursor:pointer" onclick="openConsultaRegistro(${i})">${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;cursor:pointer" onclick="openConsultaRegistro(${i})">${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;cursor:pointer" onclick="openConsultaRegistro(${i})">${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;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">${statusBadge(item.status_diferenca)}</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">${syncBadge(item.sync_status)}</td> <td style="padding:6px 8px;border-bottom:1px solid #eee;font-size:12px;cursor:pointer" onclick="openConsultaRegistro(${i})">${syncBadge(item.sync_status)}</td>
<td style="padding:4px 6px;border-bottom:1px solid #eee;text-align:center">
<button onclick="event.stopPropagation();window.abrirEditaFechamentoIndex(${i})" 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>`; </tr>`;
}).join(''); }).join('');
overlay.innerHTML = ` overlay.innerHTML = `
<div style="background:#fff;border-radius:10px;padding:20px;max-width:700px;width:95%;max-height:85vh;overflow-y:auto"> <div style="background:#fff;border-radius:10px;padding:20px;max-width:780px;width:95%;max-height:85vh;overflow-y:auto">
<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:12px"> <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 Anteriores</h2>
<button onclick="closeConsultaModal()" style="background:none;border:none;font-size:18px;cursor:pointer">✕</button> <button onclick="closeConsultaModal()" style="background:none;border:none;font-size:18px;cursor:pointer">✕</button>
</div> </div>
<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> <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"> <table style="width:100%;border-collapse:collapse">
<thead> <thead>
<tr style="background:#f5f5f5"> <tr style="background:#f5f5f5">
@@ -2191,6 +2196,7 @@ function buildConsultaModal(recentList) {
<th style="padding:6px 8px;text-align:right;font-size:11px;color:#888">ESPERADO</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">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">SYNC</th>
<th style="padding:6px 8px;text-align:center;font-size:11px;color:#888">AÇÃO</th>
</tr> </tr>
</thead> </thead>
<tbody>${rows}</tbody> <tbody>${rows}</tbody>
@@ -2202,6 +2208,40 @@ function buildConsultaModal(recentList) {
window._recentList = recentList; window._recentList = recentList;
} }
// Abre a janela de edição completa de um registro pelo índice na lista
window.abrirEditaFechamentoIndex = async function(idx) {
const item = window._recentList ? window._recentList[idx] : null;
if (!item) 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; }
// Adiciona id_fechamento se não vier do banco
if (!full.id_fechamento && full.loja && full.data && full.operador) {
full.id_fechamento = (full.loja + '_' + full.data + '_' + full.operador).toLowerCase().replace(/ /g, '_');
}
closeConsultaModal();
window.abrirEditaFechamento(full);
};
function closeConsultaModal() { function closeConsultaModal() {
const m = document.getElementById('modal-consulta'); const m = document.getElementById('modal-consulta');
if (m) document.body.removeChild(m); if (m) document.body.removeChild(m);
@@ -2283,10 +2323,10 @@ function buildRelatorioModal(full) {
const totalSangrias = parseFloat(full.total_sangrias || 0); const totalSangrias = parseFloat(full.total_sangrias || 0);
const totalCancelamentos = parseFloat(full.total_cancelamentos || 0); const totalCancelamentos = parseFloat(full.total_cancelamentos || 0);
// Esperado e diferença // Esperado e diferença — calculada: Total Sistema - Saldo Esperado - Cancelamentos
const saldoEsperado = parseFloat(full.saldo_esperado || 0); const saldoEsperado = parseFloat(full.saldo_esperado || 0);
const diferenca = parseFloat(full.diferenca || 0); const diferenca = sysTotal - saldoEsperado - totalCancelamentos;
const statusDif = full.status_diferenca || '?'; const statusDif = diferenca === 0 ? 'ok' : (diferenca > 0 ? 'sobrando' : 'faltando');
const diffClass = statusDif === 'ok' ? '#2e7d32' : (statusDif === 'sobrando' ? '#e65100' : '#c0272d'); const diffClass = statusDif === 'ok' ? '#2e7d32' : (statusDif === 'sobrando' ? '#e65100' : '#c0272d');
const diffLabel = statusDif === 'ok' ? '✓ OK' : (statusDif === 'sobrando' ? '⚠ SOBRANDO' : (statusDif === 'faltando' ? '⚠ FALTANDO' : statusDif)); const diffLabel = statusDif === 'ok' ? '✓ OK' : (statusDif === 'sobrando' ? '⚠ SOBRANDO' : (statusDif === 'faltando' ? '⚠ FALTANDO' : statusDif));
@@ -2495,6 +2535,7 @@ window.toggleEditConsulta = async function() {
} }
openEditModal(full); openEditModal(full);
closeRelatorioModal();
}; };
// Pede senha admin — retorna Promise<boolean> // Pede senha admin — retorna Promise<boolean>
@@ -2631,6 +2672,7 @@ window._recalcEditTotals = function() {
const el = id => document.getElementById(id); const el = id => document.getElementById(id);
const fmtTot = v => v > 0 ? 'R$ ' + v.toLocaleString('pt-BR', { minimumFractionDigits: 2 }) : '—'; const fmtTot = v => v > 0 ? 'R$ ' + v.toLocaleString('pt-BR', { minimumFractionDigits: 2 }) : '—';
// Atualiza spans do total-box (prefixo "edit-total-") E do resumo rápido (prefixo "tot-")
if (el('edit-total-credito')) el('edit-total-credito').textContent = fmtTot(cartCred_tot); if (el('edit-total-credito')) el('edit-total-credito').textContent = fmtTot(cartCred_tot);
if (el('edit-total-debito')) el('edit-total-debito').textContent = fmtTot(cartDeb_tot); if (el('edit-total-debito')) el('edit-total-debito').textContent = fmtTot(cartDeb_tot);
if (el('edit-total-alimentacao')) el('edit-total-alimentacao').textContent = fmtTot(cartAli_tot); if (el('edit-total-alimentacao')) el('edit-total-alimentacao').textContent = fmtTot(cartAli_tot);
@@ -2638,14 +2680,27 @@ window._recalcEditTotals = function() {
if (el('edit-total-vales')) el('edit-total-vales').textContent = fmtTot(vales_tot); if (el('edit-total-vales')) el('edit-total-vales').textContent = fmtTot(vales_tot);
if (el('edit-total-despesas')) el('edit-total-despesas').textContent = fmtTot(desp_tot); if (el('edit-total-despesas')) el('edit-total-despesas').textContent = fmtTot(desp_tot);
if (el('edit-total-sangrias')) el('edit-total-sangrias').textContent = fmtTot(sang_tot); if (el('edit-total-sangrias')) el('edit-total-sangrias').textContent = fmtTot(sang_tot);
if (el('edit-total-pixcnpj')) el('edit-total-pixcnpj').textContent = fmtTot(pixcnpj_tot); if (el('edit-total-pixcnpj')) el('edit-total-pixcnpj').textContent = fmtTot(pixcnpj_tot);
if (el('edit-total-receber')) el('edit-total-receber').textContent = fmtTot(recv_tot); if (el('edit-total-receber')) el('edit-total-receber').textContent = fmtTot(recv_tot);
if (el('edit-total-cancel')) el('edit-total-cancel').textContent = fmtTot(canc_tot); if (el('edit-total-cancel')) el('edit-total-cancel').textContent = fmtTot(canc_tot);
// Atualiza também os spans do total-box da popup (prefixo "tot-")
if (el('tot-credito')) el('tot-credito').textContent = fmtTot(cartCred_tot);
if (el('tot-debito')) el('tot-debito').textContent = fmtTot(cartDeb_tot);
if (el('tot-ali')) el('tot-ali').textContent = fmtTot(cartAli_tot);
if (el('tot-pix')) el('tot-pix').textContent = fmtTot(cartPix_tot);
if (el('tot-pixcnpj')) el('tot-pixcnpj').textContent = fmtTot(pixcnpj_tot);
if (el('tot-vales')) el('tot-vales').textContent = fmtTot(vales_tot);
if (el('tot-areceber')) el('tot-areceber').textContent = fmtTot(recv_tot);
if (el('tot-sangrias')) el('tot-sangrias').textContent = fmtTot(sang_tot);
if (el('tot-despesas')) el('tot-despesas').textContent = fmtTot(desp_tot);
if (el('tot-cancel')) el('tot-cancel').textContent = fmtTot(canc_tot);
}; };
// Modal de edição completo com todas as grades // Modal de edição completo com todas as grades
function openEditModal(full) { function openEditModal(full) {
window._editModalOpen = true; window._editModalOpen = true;
// Salva o registro ANTES de fechar o modal de relatório — usa variável separada para não conflitar
window._editingRecord = full;
const dados = full.dados || {}; const dados = full.dados || {};
@@ -2676,27 +2731,27 @@ function openEditModal(full) {
const cartPixHTML = editTableHTML('pix', ['Valor (R$)'], cartPix_rows.length ? cartPix_rows : [['']], [0]); const cartPixHTML = editTableHTML('pix', ['Valor (R$)'], cartPix_rows.length ? cartPix_rows : [['']], [0]);
// --- Vales --- // --- Vales ---
const vales_rows = (full.vales_arr || []).map(r => [r.nome||r.Nome||'', r.valor||0, r.obs||r.Obs||'']); const vales_rows = (dados.vales || []).map(r => [r.nome||'', r.valor||0, r.obs||'']);
const valesHTML = editTableHTML('vales', ['Nome', 'Valor (R$)', 'Obs'], vales_rows.length ? vales_rows : [['','','']], [1]); const valesHTML = editTableHTML('vales', ['Nome', 'Valor (R$)', 'Obs'], vales_rows.length ? vales_rows : [['','','']], [1]);
// --- Despesas --- // --- Despesas ---
const despesas_rows = (full.despesas_arr || []).map(r => [r.desc||r.Desc||'', r.obs||r.Obs||'', r.valor||0]); const despesas_rows = (dados.despesas || []).map(r => [r.desc||'', r.obs||'', r.valor||0]);
const despesasHTML = editTableHTML('despesas', ['Descrição', 'Obs', 'Valor (R$)'], despesas_rows.length ? despesas_rows : [['','','']], [2]); const despesasHTML = editTableHTML('despesas', ['Descrição', 'Obs', 'Valor (R$)'], despesas_rows.length ? despesas_rows : [['','','']], [2]);
// --- Sangrias --- // --- Sangrias ---
const sangrias_rows = (full.sangrias_arr || []).map(r => [r.hora||r.Hora||'', r.retirada||r.valor||0, r.gerente||r.Gerente||'']); const sangrias_rows = (dados.sangrias || []).map(r => [r.hora||'', r.retirada||r.valor||0, r.gerente||'']);
const sangriasHTML = editTableHTML('sangrias', ['Hora', 'Valor (R$)', 'Gerente'], sangrias_rows.length ? sangrias_rows : [['','','']], [1]); const sangriasHTML = editTableHTML('sangrias', ['Hora', 'Valor (R$)', 'Gerente'], sangrias_rows.length ? sangrias_rows : [['','','']], [1]);
// --- Cancelamentos --- // --- Cancelamentos ---
const cancel_rows = (full.cancelamentos_arr || []).map(r => [r.numero||r.Numero||'', r.valor||0, r.motivo||r.Motivo||'']); const cancel_rows = (dados.cancelamentos || []).map(r => [r.numero||'', r.valor||0, r.motivo||'']);
const cancelHTML = editTableHTML('cancelamentos', ['Número', 'Valor (R$)', 'Motivo'], cancel_rows.length ? cancel_rows : [['','','']], [1]); const cancelHTML = editTableHTML('cancelamentos', ['Número', 'Valor (R$)', 'Motivo'], cancel_rows.length ? cancel_rows : [['','','']], [1]);
// --- PIX CNPJ --- // --- PIX CNPJ ---
const pixcnpj_rows = (full.pixcnpj_arr || []).map(r => [r.nome||r.desc||r.Desc||'', r.valor||0]); const pixcnpj_rows = (dados.pixcnpj || []).map(r => [r.nome||r.desc||'', r.valor||0]);
const pixcnpjHTML = editTableHTML('pixcnpj', ['Nome', 'Valor (R$)'], pixcnpj_rows.length ? pixcnpj_rows : [['','']], [1]); const pixcnpjHTML = editTableHTML('pixcnpj', ['Nome', 'Valor (R$)'], pixcnpj_rows.length ? pixcnpj_rows : [['','']], [1]);
// --- A Receber --- // --- A Receber ---
const receber_rows = (full.receber_arr || []).map(r => [r.nome||r.Nome||'', r.valor||0]); 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]); const receberHTML = editTableHTML('receber', ['Nome', 'Valor (R$)'], receber_rows.length ? receber_rows : [['','']], [1]);
// --- Totais (só leitura formatado) --- // --- Totais (só leitura formatado) ---
@@ -2892,10 +2947,26 @@ function closeEditModal() {
window._editModalOpen = false; window._editModalOpen = false;
} }
// ─── Janela de edição completa (usa modal interno, não popup) ─────────────────
// Reaproveita openEditModal que já tem todas as tabelas editáveis,
// grades de cartões/vales/despesas/sangrias/pixcnjp/receber/cancelamentos,
// e conexão Tauri funcionando. Apenas pré-preenche o registro e abre.
window.abrirEditaFechamento = async function(full) {
if (!full) { alert('Registro não fornecido.'); return; }
// Garante id_fechamento
if (!full.id_fechamento && full.loja && full.data && full.operador) {
full.id_fechamento = (full.loja + '_' + full.data + '_' + full.operador).toLowerCase().replace(/ /g, '_');
}
// Usa o mesmo modal de edição completo que já funciona — só abre com o registro
openEditModal(full);
};
// Salva edições do modal de edição completo // Salva edições do modal de edição completo
window.salvarEdicaoModal = async function() { window.salvarEdicaoModal = async function() {
const full = window._currentConsulta; console.log('[DEBUG] salvarEdicaoModal called');
if (!full) return; const full = window._editingRecord;
if (!full) { console.log('[DEBUG] _editingRecord is null'); alert('Nenhum registro selecionado.'); return; }
console.log('[DEBUG] full.uuid:', full.uuid, 'full.id:', full.id);
const p = v => parseNum(v); const p = v => parseNum(v);
const inp = id => { const el = document.getElementById(id); return el ? el.value : ''; }; const inp = id => { const el = document.getElementById(id); return el ? el.value : ''; };
@@ -2934,6 +3005,9 @@ window.salvarEdicaoModal = async function() {
const operador = estado.operador || full.operador || ''; const operador = estado.operador || full.operador || '';
const updates = { const updates = {
// Chave natural — essencial para o Supabase encontrar o registro
id_fechamento: inp('edit-loja') + '_' + inp('edit-data') + '_' + inp('edit-operador'),
// Identificação // Identificação
loja: inp('edit-loja'), loja: inp('edit-loja'),
data: inp('edit-data'), data: inp('edit-data'),
@@ -2952,14 +3026,14 @@ window.salvarEdicaoModal = async function() {
total_cartao_alimentacao: cartAli_tot, total_cartao_alimentacao: cartAli_tot,
total_cartao_pix: cartPix_tot, total_cartao_pix: cartPix_tot,
// Saldo de caixa (editável via tabela saldo) // Saldo de caixa — soma automática dos itens editados (não dos campos readonly)
saldo_troco: p(inp('edit-troco')), saldo_troco: p(inp('edit-troco')),
saldo_credito: p(inp('edit-sld-credito')), saldo_credito: cartCred_tot,
saldo_debito: p(inp('edit-sld-debito')), saldo_debito: cartDeb_tot,
saldo_alimentacao: p(inp('edit-sld-alimentacao')), saldo_alimentacao: cartAli_tot,
saldo_vales: p(inp('edit-sld-vales')), saldo_vales: vales_tot,
total_pixcnpj: p(inp('edit-sld-pixcnpj')), total_pixcnpj: pixcnpj_tot,
saldo_areceber: p(inp('edit-sld-areceber')), saldo_areceber: recv_tot,
// Totais // Totais
total_vales: vales_tot, total_vales: vales_tot,
@@ -2994,12 +3068,16 @@ window.salvarEdicaoModal = async function() {
if (!hasTauri) { alert('Tauri não disponível.'); return; } if (!hasTauri) { alert('Tauri não disponível.'); return; }
try { try {
// Usa uuid (string) — que é o id externo do registro no Supabase // Usa id_fechamento que é a chave natural do registro
const uuid = full.uuid || full.id; const id_fechamento = full.id_fechamento || (full.loja && full.data && full.operador
if (!uuid) { alert('UUID do registro não encontrado.'); return; } ? `${full.loja}_${full.data}_${full.operador}`.toLowerCase().replace(/ /g, '_')
console.log('[DEBUG] salvarEdicaoModal uuid:', uuid, 'updates:', JSON.stringify(updates)); : null);
if (!id_fechamento) { alert('id_fechamento não encontrado.'); return; }
console.log('[DEBUG] salvarEdicaoModal id_fechamento:', id_fechamento, 'updates:', JSON.stringify(updates));
await window.__TAURI__.core.invoke('sb_atualizar_fechamento', { id: uuid, updates: JSON.stringify(updates) }); console.log('[DEBUG] invoking sb_atualizar_fechamento...');
const result = await window.__TAURI__.core.invoke('sb_atualizar_fechamento', { id_fechamento, updates: JSON.stringify(updates) });
console.log('[DEBUG] invoke result:', result);
closeEditModal(); closeEditModal();
closeRelatorioModal(); closeRelatorioModal();
alert('✅ Atualizado com sucesso!'); alert('✅ Atualizado com sucesso!');
@@ -3085,10 +3163,10 @@ function consultaToPrintData(full) {
const vales_arr = (dados.vales || []).map(v => ({ nome: v.nome || '', obs: v.obs || '', valor: parseFloat(v.valor || 0) })); const vales_arr = (dados.vales || []).map(v => ({ nome: v.nome || '', obs: v.obs || '', valor: parseFloat(v.valor || 0) }));
const receber_arr = (dados.receber || []).map(r => ({ nome: r.nome || '', valor: parseFloat(r.valor || 0) })); const receber_arr = (dados.receber || []).map(r => ({ nome: r.nome || '', valor: parseFloat(r.valor || 0) }));
const cancelamentos_arr = (dados.cancelamentos || []).map(c => ({ numero: c.numero || '', valor: parseFloat(c.valor || 0), motivo: c.motivo || '' })); const cancelamentos_arr = (dados.cancelamentos || []).map(c => ({ numero: c.numero || '', valor: parseFloat(c.valor || 0), motivo: c.motivo || '' }));
const cartoes_credito = (full.cartoes_credito || []).map(v => parseFloat(v || 0)); const cartoes_credito = (dados.cartoes?.credito || full.cartoes_credito || []).map(v => parseFloat(typeof v === 'object' ? (v.valor ?? 0) : (v || 0)));
const cartoes_debito = (full.cartoes_debito || []).map(v => parseFloat(v || 0)); const cartoes_debito = (dados.cartoes?.debito || full.cartoes_debito || []).map(v => parseFloat(typeof v === 'object' ? (v.valor ?? 0) : (v || 0)));
const cartoes_alimentacao = (full.cartoes_alimentacao || []).map(v => parseFloat(v || 0)); const cartoes_alimentacao = (dados.cartoes?.alimentacao || full.cartoes_alimentacao || []).map(v => parseFloat(typeof v === 'object' ? (v.valor ?? 0) : (v || 0)));
const cartoes_pix = (full.cartoes_pix || []).map(v => parseFloat(v || 0)); const cartoes_pix = (dados.cartoes?.pix || full.cartoes_pix || []).map(v => parseFloat(typeof v === 'object' ? (v.valor ?? 0) : (v || 0)));
const totalSangrias = sangrias_arr.reduce((s, r) => s + r.retirada + r.valor, 0); const totalSangrias = sangrias_arr.reduce((s, r) => s + r.retirada + r.valor, 0);
const totalDespesas = despesas_arr.reduce((s, r) => s + r.valor, 0); const totalDespesas = despesas_arr.reduce((s, r) => s + r.valor, 0);
const totalPixCnpj = pixcnpj_arr.reduce((s, r) => s + r.valor, 0); const totalPixCnpj = pixcnpj_arr.reduce((s, r) => s + r.valor, 0);
@@ -3170,8 +3248,8 @@ window.printRelatorio = function() {
.section-title { font-weight: bold; font-size: 14px; border-top: 2px solid #000; padding-top: 4px; margin-top: 8px; } .section-title { font-weight: bold; font-size: 14px; border-top: 2px solid #000; padding-top: 4px; margin-top: 8px; }
.row { display: flex; justify-content: space-between; padding: 2px 0; font-size: 13px; font-weight: bold; } .row { display: flex; justify-content: space-between; padding: 2px 0; font-size: 13px; font-weight: bold; }
.row.total-row { font-weight: bold; } .row.total-row { font-weight: bold; }
.cart-table { width: 100%; border-collapse: collapse; font-size: 12px; margin-top: 4px; font-weight: bold; } .cart-table { table-layout: fixed; width: 100%; border-collapse: collapse; font-size: 13px; margin-top: 4px; font-weight: bold; }
.cart-table th { font-weight: bold; border-bottom: 2px solid #000; padding: 2px; } .cart-table th { font-weight: bold; border-bottom: 2px solid #000; padding: 2px; width: 25%; }
.cart-table td { padding: 2px 4px; text-align: right; font-weight: bold; } .cart-table td { padding: 2px 4px; text-align: right; font-weight: bold; }
.cart-table td:first-child { text-align: left; } .cart-table td:first-child { text-align: left; }
.cart-table tr.total-row { font-weight: bold; border-top: 2px solid #000; } .cart-table tr.total-row { font-weight: bold; border-top: 2px solid #000; }